nex-code 0.3.39 → 0.3.40

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 (2) hide show
  1. package/dist/nex-code.js +276 -276
  2. package/package.json +1 -1
package/dist/nex-code.js CHANGED
@@ -1,20 +1,20 @@
1
1
  #!/usr/bin/env node
2
- var L=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Rn=L((e$,Bl)=>{Bl.exports={name:"nex-code",version:"0.3.39",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 Lr=L((t$,Pr)=>{var N={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"},Or=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Nr=["\u273D","\u2726","\u2727","\u2726"],Ps=class{constructor(e="Thinking..."){this.text=e,this.frame=0,this.interval=null,this.startTime=null}_render(){if(this._stopped)return;let e=Or[this.frame%Or.length],s="";if(this.startTime){let n=Math.floor((Date.now()-this.startTime)/1e3);if(n>=60){let o=Math.floor(n/60),i=n%60;s=` ${N.dim}${o}m ${String(i).padStart(2,"0")}s${N.reset}`}else n>=1&&(s=` ${N.dim}${n}s${N.reset}`)}process.stderr.write(`\x1B[2K\r${N.cyan}${e}${N.reset} ${N.dim}${this.text}${N.reset}${s}`),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(),80))}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}},Mr=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Ls=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=Mr[this.frame%Mr.length],s=this._formatElapsed(),n=s?` ${N.dim}${s}${N.reset}`:"",o="";for(let i=0;i<this.labels.length;i++){let r,c;switch(this.statuses[i]){case"done":r=`${N.green}\u2713${N.reset}`,c=N.dim;break;case"error":r=`${N.red}\u2717${N.reset}`,c=N.dim;break;default:r=`${N.cyan}${e}${N.reset}`,c=""}let l=i===this.labels.length-1?n:"";o+=`\x1B[2K ${r} ${c}${this.labels[i]}${N.reset}${l}
3
- `}this.lineCount>0&&(o+=`\x1B[${this.lineCount}A`),process.stderr.write(o),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(),80)}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?` ${N.dim}${e}${N.reset}`:"",n="";for(let o=0;o<this.labels.length;o++){let i;switch(this.statuses[o]){case"done":i=`${N.green}\u2713${N.reset}`;break;case"error":i=`${N.red}\u2717${N.reset}`;break;default:i=`${N.yellow}\u25CB${N.reset}`}let r=o===this.labels.length-1?s:"";n+=`\x1B[2K ${i} ${N.dim}${this.labels[o]}${N.reset}${r}
5
- `}process.stderr.write(n)}},An={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},On={done:N.green,in_progress:N.cyan,pending:N.dim,failed:N.red},rt=null,Is=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=Nr[this.frame%Nr.length],s=this._formatElapsed(),n=this._formatTokens(),o=[s,n?`\u2193 ${n} tokens`:""].filter(Boolean).join(" \xB7 "),i=o?` ${N.dim}(${o})${N.reset}`:"",r=`\x1B[2K${N.cyan}${e}${N.reset} ${this.name}\u2026${i}
2
+ var L=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Rn=L((t$,Bl)=>{Bl.exports={name:"nex-code",version:"0.3.40",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 Ir=L((n$,Lr)=>{var N={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"},Nr=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Mr=["\u273D","\u2726","\u2727","\u2726"],Ls=class{constructor(e="Thinking..."){this.text=e,this.frame=0,this.interval=null,this.startTime=null}_render(){if(this._stopped)return;let e=Nr[this.frame%Nr.length],o="";if(this.startTime){let n=Math.floor((Date.now()-this.startTime)/1e3);if(n>=60){let s=Math.floor(n/60),i=n%60;o=` ${N.dim}${s}m ${String(i).padStart(2,"0")}s${N.reset}`}else n>=1&&(o=` ${N.dim}${n}s${N.reset}`)}process.stderr.write(`\x1B[2K\r${N.cyan}${e}${N.reset} ${N.dim}${this.text}${N.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(),80))}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}},Pr=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Is=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 o=Math.floor(e/60),n=e%60;return o>0?`${o}m ${String(n).padStart(2,"0")}s`:`${n}s`}_render(){if(this._stopped)return;let e=Pr[this.frame%Pr.length],o=this._formatElapsed(),n=o?` ${N.dim}${o}${N.reset}`:"",s="";for(let i=0;i<this.labels.length;i++){let r,c;switch(this.statuses[i]){case"done":r=`${N.green}\u2713${N.reset}`,c=N.dim;break;case"error":r=`${N.red}\u2717${N.reset}`,c=N.dim;break;default:r=`${N.cyan}${e}${N.reset}`,c=""}let l=i===this.labels.length-1?n:"";s+=`\x1B[2K ${r} ${c}${this.labels[i]}${N.reset}${l}
3
+ `}this.lineCount>0&&(s+=`\x1B[${this.lineCount}A`),process.stderr.write(s),this.frame++}start(){this._stopped=!1,this.startTime=Date.now();let e="\x1B[?25l";for(let o=0;o<this.lineCount;o++)e+=`
4
+ `;this.lineCount>0&&(e+=`\x1B[${this.lineCount}A`),process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),80)}update(e,o){e>=0&&e<this.statuses.length&&(this.statuses[e]=o)}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),this._renderFinal(),process.stderr.write("\x1B[?25h")}_renderFinal(){let e=this._formatElapsed(),o=e?` ${N.dim}${e}${N.reset}`:"",n="";for(let s=0;s<this.labels.length;s++){let i;switch(this.statuses[s]){case"done":i=`${N.green}\u2713${N.reset}`;break;case"error":i=`${N.red}\u2717${N.reset}`;break;default:i=`${N.yellow}\u25CB${N.reset}`}let r=s===this.labels.length-1?o:"";n+=`\x1B[2K ${i} ${N.dim}${this.labels[s]}${N.reset}${r}
5
+ `}process.stderr.write(n)}},An={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},On={done:N.green,in_progress:N.cyan,pending:N.dim,failed:N.red},rt=null,qs=class{constructor(e,o){this.name=e,this.tasks=o.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 o=Math.floor(e/60),n=e%60;return o>0?`${o}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=Mr[this.frame%Mr.length],o=this._formatElapsed(),n=this._formatTokens(),s=[o,n?`\u2193 ${n} tokens`:""].filter(Boolean).join(" \xB7 "),i=s?` ${N.dim}(${s})${N.reset}`:"",r=`\x1B[2K${N.cyan}${e}${N.reset} ${this.name}\u2026${i}
6
6
  `;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=An[l.status]||An.pending,f=On[l.status]||On.pending,m=l.description.length>55?l.description.substring(0,52)+"...":l.description;r+=`\x1B[2K ${N.dim}${u}${N.reset} ${f}${d}${N.reset} ${m}
7
- `}r+=`\x1B[${this.lineCount}A`,process.stderr.write(r),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),rt=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,rt===this&&(rt=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._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,i=n>0?`${s}/${o} done, ${n} failed`:`${s}/${o} done`,r=`\x1B[2K${N.green}\u2714${N.reset} ${this.name} ${N.dim}(${e} \xB7 ${i})${N.reset}
7
+ `}r+=`\x1B[${this.lineCount}A`,process.stderr.write(r),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),this._paused=!1;let e="\x1B[?25l";for(let o=0;o<this.lineCount;o++)e+=`
8
+ `;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120),rt=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,rt===this&&(rt=null)}pause(){if(this._paused)return;this.interval&&(clearInterval(this.interval),this.interval=null);let e="";for(let o=0;o<this.lineCount;o++)e+=`\x1B[2K
9
+ `;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 o=0;o<this.lineCount;o++)e+=`
10
+ `;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120)}updateTask(e,o){let n=this.tasks.find(s=>s.id===e);n&&(n.status=o)}setStats({tokens:e}){e!==void 0&&(this.tokens=e)}isActive(){return this.interval!==null||this._paused}_renderFinal(){let e=this._formatElapsed(),o=this.tasks.filter(c=>c.status==="done").length,n=this.tasks.filter(c=>c.status==="failed").length,s=this.tasks.length,i=n>0?`${o}/${s} done, ${n} failed`:`${o}/${s} done`,r=`\x1B[2K${N.green}\u2714${N.reset} ${this.name} ${N.dim}(${e} \xB7 ${i})${N.reset}
11
11
  `;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=An[l.status]||An.pending,f=On[l.status]||On.pending,m=l.description.length>55?l.description.substring(0,52)+"...":l.description;r+=`\x1B[2K ${N.dim}${u}${N.reset} ${f}${d}${N.reset} ${N.dim}${m}${N.reset}
12
- `}process.stderr.write(r)}};function Hl(t){rt=t}function Gl(){return rt}function zl(){rt&&(rt.stop(),rt=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}Pr.exports={C:N,Spinner:Ps,MultiProgress:Ls,TaskProgress:Is,setActiveTaskProgress:Hl,getActiveTaskProgress:Gl,cleanupTerminal:zl}});var jr=L((n$,qr)=>{var R={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 Ir(t){if(!t)return"";let e=t.replace(/^\.\//,"").split("/");return e.length>1?e.slice(-2).join("/"):e[0]}var Kl={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"},qs={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 Nn(t,e=!1,s=null){return e?`${R.red}\u25CF${R.reset}`:`${Kl[t]||R.green}${s!==null?s:"\u25CF"}${R.reset}`}function Yl(t,e,s=!1,n=null){let o=(t||[]).filter(l=>l&&l.canExecute!==!1);if(o.length===0)return`${Nn("",s,n)} Step ${e}`;if(o.length===1){let l=o[0],u=l.args||{},d=qs[l.fnName]||l.fnName.replace(/_/g," "),f="";u.path?f=Ir(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?`${R.dim}(${f})${R.reset}`:"";return`${Nn(l.fnName,s,n)} ${R.bold}${d}${R.reset} ${m}`}let i=o[0].fnName,r=[...new Set(o.map(l=>qs[l.fnName]||l.fnName.replace(/_/g," ")))],c=r.length<=3?r.join(" \xB7 "):`${o.length} actions`;return`${Nn(i,s,n)} ${c}`}function Jl(t,e){let s;switch(t){case"write_file":case"edit_file":case"patch_file":case"read_file":case"list_directory":s=Ir(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=qs[t]||t.replace(/_/g," "),o=s?` ${R.dim}(${s})${R.reset}`:"";return`${Nn(t)} ${R.bold}${n}${R.reset}${o}`}function Xl(t,e=8){let s=t.split(`
13
- `),n=s.slice(0,e),o=s.length-e,i=`${R.dim} \u2514 ${R.reset}`,r=" ",c=n.map((l,u)=>`${u===0?i:r}${R.green}${l}${R.reset}`).join(`
14
- `);return o>0&&(c+=`
15
- ${R.gray} \u2026 +${o} lines${R.reset}`),c}function Vl(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 Ql(t,e,s,n){let o=String(s||"");if(n){let r=o.split(`
16
- `)[0].replace(/^ERROR:\s*/i,"").substring(0,80),c=o.match(/\nHINT: (.+)/),l=c?`
17
- ${R.dim}${c[1].substring(0,100)}${R.reset}`:"";return` ${R.red}\u2514 ${r}${R.reset}${l}`}let i;switch(t){case"read_file":{let r=o.split(`
12
+ `}process.stderr.write(r)}};function Hl(t){rt=t}function Gl(){return rt}function zl(){rt&&(rt.stop(),rt=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}Lr.exports={C:N,Spinner:Ls,MultiProgress:Is,TaskProgress:qs,setActiveTaskProgress:Hl,getActiveTaskProgress:Gl,cleanupTerminal:zl}});var Dr=L((s$,jr)=>{var R={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 Kl={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"},js={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 Nn(t,e=!1,o=null){return e?`${R.red}\u25CF${R.reset}`:`${Kl[t]||R.green}${o!==null?o:"\u25CF"}${R.reset}`}function Yl(t,e,o=!1,n=null){let s=(t||[]).filter(l=>l&&l.canExecute!==!1);if(s.length===0)return`${Nn("",o,n)} Step ${e}`;if(s.length===1){let l=s[0],u=l.args||{},d=js[l.fnName]||l.fnName.replace(/_/g," "),f="";u.path?f=qr(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?`${R.dim}(${f})${R.reset}`:"";return`${Nn(l.fnName,o,n)} ${R.bold}${d}${R.reset} ${m}`}let i=s[0].fnName,r=[...new Set(s.map(l=>js[l.fnName]||l.fnName.replace(/_/g," ")))],c=r.length<=3?r.join(" \xB7 "):`${s.length} actions`;return`${Nn(i,o,n)} ${c}`}function Jl(t,e){let o;switch(t){case"write_file":case"edit_file":case"patch_file":case"read_file":case"list_directory":o=qr(e.path);break;case"bash":o=(e.command||"").substring(0,80);break;case"grep":case"search_files":o=e.pattern?`"${e.pattern}"${e.path?` in ${e.path}`:""}`:"";break;case"glob":o=e.pattern||"";break;case"web_fetch":o=(e.url||"").substring(0,60);break;case"web_search":o=(e.query||"").substring(0,50);break;default:o=JSON.stringify(e).substring(0,80)}let n=js[t]||t.replace(/_/g," "),s=o?` ${R.dim}(${o})${R.reset}`:"";return`${Nn(t)} ${R.bold}${n}${R.reset}${s}`}function Xl(t,e=8){let o=t.split(`
13
+ `),n=o.slice(0,e),s=o.length-e,i=`${R.dim} \u2514 ${R.reset}`,r=" ",c=n.map((l,u)=>`${u===0?i:r}${R.green}${l}${R.reset}`).join(`
14
+ `);return s>0&&(c+=`
15
+ ${R.gray} \u2026 +${s} lines${R.reset}`),c}function Vl(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 Ql(t,e,o,n){let s=String(o||"");if(n){let r=s.split(`
16
+ `)[0].replace(/^ERROR:\s*/i,"").substring(0,80),c=s.match(/\nHINT: (.+)/),l=c?`
17
+ ${R.dim}${c[1].substring(0,100)}${R.reset}`:"";return` ${R.red}\u2514 ${r}${R.reset}${l}`}let i;switch(t){case"read_file":{let r=s.split(`
18
18
  `).filter(Boolean),c=r.length,l=r[r.length-1],u=l?parseInt(l.match(/^(\d+):/)?.[1]||"0"):0,d=e.line_start||e.line_end,f=(r[0]||"").replace(/^\d+:\s*/,"").trim(),m=f?` ${R.dim}\u2014 ${f.substring(0,60)}${f.length>60?"\u2026":""}${R.reset}`:"";d&&u>c?i=`Read lines ${e.line_start||1}\u2013${u}${m}`:i=`Read ${c} line${c!==1?"s":""}${m}`;break}case"write_file":{let r=(e.content||"").split(`
19
19
  `).length;i=`Wrote ${r} line${r!==1?"s":""}`;break}case"edit_file":{let r=(e.old_text||"").split(`
20
20
  `),c=(e.new_text||"").split(`
@@ -22,123 +22,123 @@ ${R.gray} \u2026 +${o} lines${R.reset}`),c}function Vl(t,e){switch(t){case"b
22
22
  `+h.join(`
23
23
  `):"");break}case"patch_file":{let r=e.patches||[],c=r.reduce((u,d)=>u+(d.old_text||"").split(`
24
24
  `).length,0),l=r.reduce((u,d)=>u+(d.new_text||"").split(`
25
- `).length,0);i=`${R.reset}${r.length} patch${r.length!==1?"es":""} ${R.red}\u2212${c}${R.reset} ${R.green}+${l}${R.reset}`;break}case"bash":{let r=o.match(/^EXIT (\d+)/);if(r){let c=r[1],l=o.match(/\nHINT: (.+)/);if(l)i=`${c==="0"?`${R.green}\u2713${R.reset}`:`${R.red}\u2717 Exit ${c}${R.reset}`} ${R.dim}\u2014 ${l[1].substring(0,60)}${R.reset}`;else{let u=o.split(`
26
- `).filter(h=>h&&!h.startsWith("EXIT ")&&h.trim()),d=u[0]?` ${R.dim}\xB7 ${u[0].substring(0,70)}${R.reset}`:"",f=u.length>1?` ${R.dim}+${u.length-1}${R.reset}`:"";i=`${c==="0"?`${R.green}\u2713${R.reset}`:`${R.red}\u2717 Exit ${c}${R.reset}`}${d}${f}`}}else{let c=o.split(`
27
- `).filter(Boolean);i=c.length>1?`${c[0].substring(0,60)} ${R.dim}+${c.length-1} more${R.reset}`:(c[0]||"").substring(0,70)||"Done"}break}case"grep":case"search_files":{if(o.includes("(no matches)")||o==="no matches")i="No matches";else{let r=o.split(`
28
- `).filter(Boolean),c=r.length,u=new Set(r.map(d=>d.split(":")[0]).filter(Boolean)).size;i=u>1?`${c} match${c!==1?"es":""} in ${u} files`:`${c} match${c!==1?"es":""}`}break}case"glob":{if(o==="(no matches)")i="No files found";else{let r=o.split(`
29
- `).filter(Boolean).length;i=`${r} file${r!==1?"s":""} found`}break}case"list_directory":{let r=o==="(empty)"?0:o.split(`
30
- `).filter(Boolean).length;i=`${r} entr${r!==1?"ies":"y"}`;break}case"git_status":{let r=o.match(/Branch:\s*(\S+)/),c=o.split(`
31
- `).filter(l=>/^\s*[MADRCU?!]/.test(l)).length;i=r?`${r[1]} \xB7 ${c} change${c!==1?"s":""}`:"Done";break}case"git_diff":{let r=(o.match(/^\+[^+]/gm)||[]).length,c=(o.match(/^-[^-]/gm)||[]).length;i=r||c?`+${r} \u2212${c} lines`:"No diff";break}case"git_log":{let r=o.split(`
32
- `).filter(c=>/^commit\s+[0-9a-f]{7}/.test(c)).length;i=r>0?`${r} commit${r!==1?"s":""}`:"Log retrieved";break}case"git_commit":{let r=o.match(/\[[\w./\-]+ ([0-9a-f]{7,})\]/),c=o.match(/\[[\w./\-]+ [0-9a-f]+\]\s+(.+)/);i=r?`${r[1]}${c?` \u2014 ${c[1].substring(0,55)}`:""}`:"Committed";break}case"git_push":{let r=o.match(/(?:->|→)\s*(\S+)/);i=r?`\u2192 ${r[1]}`:"Pushed";break}case"git_pull":{if(/Already up.to.date/i.test(o))i="Already up to date";else{let r=(o.match(/^\+/gm)||[]).length;i=r>0?`Pulled \xB7 +${r} lines`:"Pulled"}break}case"web_fetch":i="Fetched";break;case"web_search":{let r=o.split(`
33
-
34
- `).filter(Boolean).length;i=`${r} result${r!==1?"s":""}`;break}case"task_list":i="Done";break;case"spawn_agents":{let r=(o.match(/✓ Agent/g)||[]).length,c=(o.match(/✗ Agent/g)||[]).length;i=c>0?`${r} done, ${c} failed`:`${r} agent${r!==1?"s":""} done`;break}case"switch_model":{let r=o.match(/Switched to (.+)/);i=r?`\u2192 ${r[1]}`:"Done";break}default:i="Done"}return` ${R.dim}\u2514 ${i}${R.reset}`}qr.exports={C:R,formatToolCall:Jl,formatResult:Xl,getToolSpinnerText:Vl,formatToolSummary:Ql,formatSectionHeader:Yl}});var ce=L((s$,Dr)=>{var Rt={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 Zl(t,e){return[...t].map(s=>s===" "?s:`\x1B[38;2;${e[0]};${e[1]};${e[2]}m${s}`).join("")+Rt.reset}function eu(t,e){let s=(t.length-1)*e,n=Math.min(Math.floor(s),t.length-2),o=s-n;return[Math.round(t[n][0]+(t[n+1][0]-t[n][0])*o),Math.round(t[n][1]+(t[n+1][1]-t[n][1])*o),Math.round(t[n][2]+(t[n+1][2]-t[n][2])*o)]}function tu(t,e,s={}){let n=Rt.bold,o=Rt.dim,i=Rt.reset,r=["\u2588\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557 \u2501 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557","\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u255A\u2588\u2588\u2557\u2588\u2588\u2554\u255D \u2501 \u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D","\u2588\u2588\u2554\u2588\u2588\u2557 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2557 \u255A\u2588\u2588\u2588\u2554\u255D \u2501 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2557","\u2588\u2588\u2551\u255A\u2588\u2588\u2557\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D \u2588\u2588\u2554\u2588\u2588\u2557 \u2501 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D","\u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2554\u255D \u2588\u2588\u2557 \u2501 \u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557","\u255A\u2550\u255D \u255A\u2550\u2550\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D \u2501 \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D"],c=[[220,240,255],[80,200,255],[40,100,220]],l=r.map((d,f)=>{let m=f/(r.length-1||1);return Zl(d,eu(c,m))}).join(`
35
- `),u=s.yolo?` ${n}${Rt.yellow}\u26A1 YOLO${i}`:"";console.log(`
25
+ `).length,0);i=`${R.reset}${r.length} patch${r.length!==1?"es":""} ${R.red}\u2212${c}${R.reset} ${R.green}+${l}${R.reset}`;break}case"bash":{let r=s.match(/^EXIT (\d+)/);if(r){let c=r[1],l=s.match(/\nHINT: (.+)/);if(l)i=`${c==="0"?`${R.green}\u2713${R.reset}`:`${R.red}\u2717 Exit ${c}${R.reset}`} ${R.dim}\u2014 ${l[1].substring(0,60)}${R.reset}`;else{let u=s.split(`
26
+ `).filter(h=>h&&!h.startsWith("EXIT ")&&h.trim()),d=u[0]?` ${R.dim}\xB7 ${u[0].substring(0,70)}${R.reset}`:"",f=u.length>1?` ${R.dim}+${u.length-1}${R.reset}`:"";i=`${c==="0"?`${R.green}\u2713${R.reset}`:`${R.red}\u2717 Exit ${c}${R.reset}`}${d}${f}`}}else{let c=s.split(`
27
+ `).filter(Boolean);i=c.length>1?`${c[0].substring(0,60)} ${R.dim}+${c.length-1} more${R.reset}`:(c[0]||"").substring(0,70)||"Done"}break}case"grep":case"search_files":{if(s.includes("(no matches)")||s==="no matches")i="No matches";else{let r=s.split(`
28
+ `).filter(Boolean),c=r.length,u=new Set(r.map(d=>d.split(":")[0]).filter(Boolean)).size;i=u>1?`${c} match${c!==1?"es":""} in ${u} files`:`${c} match${c!==1?"es":""}`}break}case"glob":{if(s==="(no matches)")i="No files found";else{let r=s.split(`
29
+ `).filter(Boolean).length;i=`${r} file${r!==1?"s":""} found`}break}case"list_directory":{let r=s==="(empty)"?0:s.split(`
30
+ `).filter(Boolean).length;i=`${r} entr${r!==1?"ies":"y"}`;break}case"git_status":{let r=s.match(/Branch:\s*(\S+)/),c=s.split(`
31
+ `).filter(l=>/^\s*[MADRCU?!]/.test(l)).length;i=r?`${r[1]} \xB7 ${c} change${c!==1?"s":""}`:"Done";break}case"git_diff":{let r=(s.match(/^\+[^+]/gm)||[]).length,c=(s.match(/^-[^-]/gm)||[]).length;i=r||c?`+${r} \u2212${c} lines`:"No diff";break}case"git_log":{let r=s.split(`
32
+ `).filter(c=>/^commit\s+[0-9a-f]{7}/.test(c)).length;i=r>0?`${r} commit${r!==1?"s":""}`:"Log retrieved";break}case"git_commit":{let r=s.match(/\[[\w./\-]+ ([0-9a-f]{7,})\]/),c=s.match(/\[[\w./\-]+ [0-9a-f]+\]\s+(.+)/);i=r?`${r[1]}${c?` \u2014 ${c[1].substring(0,55)}`:""}`:"Committed";break}case"git_push":{let r=s.match(/(?:->|→)\s*(\S+)/);i=r?`\u2192 ${r[1]}`:"Pushed";break}case"git_pull":{if(/Already up.to.date/i.test(s))i="Already up to date";else{let r=(s.match(/^\+/gm)||[]).length;i=r>0?`Pulled \xB7 +${r} lines`:"Pulled"}break}case"web_fetch":i="Fetched";break;case"web_search":{let r=s.split(`
33
+
34
+ `).filter(Boolean).length;i=`${r} result${r!==1?"s":""}`;break}case"task_list":i="Done";break;case"spawn_agents":{let r=(s.match(/✓ Agent/g)||[]).length,c=(s.match(/✗ Agent/g)||[]).length;i=c>0?`${r} done, ${c} failed`:`${r} agent${r!==1?"s":""} done`;break}case"switch_model":{let r=s.match(/Switched to (.+)/);i=r?`\u2192 ${r[1]}`:"Done";break}default:i="Done"}return` ${R.dim}\u2514 ${i}${R.reset}`}jr.exports={C:R,formatToolCall:Jl,formatResult:Xl,getToolSpinnerText:Vl,formatToolSummary:Ql,formatSectionHeader:Yl}});var ce=L((o$,Fr)=>{var Rt={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 Zl(t,e){return[...t].map(o=>o===" "?o:`\x1B[38;2;${e[0]};${e[1]};${e[2]}m${o}`).join("")+Rt.reset}function eu(t,e){let o=(t.length-1)*e,n=Math.min(Math.floor(o),t.length-2),s=o-n;return[Math.round(t[n][0]+(t[n+1][0]-t[n][0])*s),Math.round(t[n][1]+(t[n+1][1]-t[n][1])*s),Math.round(t[n][2]+(t[n+1][2]-t[n][2])*s)]}function tu(t,e,o={}){let n=Rt.bold,s=Rt.dim,i=Rt.reset,r=["\u2588\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557 \u2501 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557","\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u255A\u2588\u2588\u2557\u2588\u2588\u2554\u255D \u2501 \u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D","\u2588\u2588\u2554\u2588\u2588\u2557 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2557 \u255A\u2588\u2588\u2588\u2554\u255D \u2501 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2557","\u2588\u2588\u2551\u255A\u2588\u2588\u2557\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D \u2588\u2588\u2554\u2588\u2588\u2557 \u2501 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D","\u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2554\u255D \u2588\u2588\u2557 \u2501 \u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557","\u255A\u2550\u255D \u255A\u2550\u2550\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D \u2501 \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D"],c=[[220,240,255],[80,200,255],[40,100,220]],l=r.map((d,f)=>{let m=f/(r.length-1||1);return Zl(d,eu(c,m))}).join(`
35
+ `),u=o.yolo?` ${n}${Rt.yellow}\u26A1 YOLO${i}`:"";console.log(`
36
36
  ${l}
37
- ${o}Agentic Coding CLI v${Rn().version}${i}
38
- ${o}Model: ${t}${i} ${o}\xB7 /help${i}${u}
39
- `)}var{Spinner:nu,MultiProgress:su,TaskProgress:ou,setActiveTaskProgress:ru,getActiveTaskProgress:iu,cleanupTerminal:au}=Lr(),{formatToolCall:cu,formatResult:lu,getToolSpinnerText:uu,formatToolSummary:du,formatSectionHeader:fu}=jr();Dr.exports={C:Rt,banner:tu,Spinner:nu,MultiProgress:su,TaskProgress:ou,setActiveTaskProgress:ru,getActiveTaskProgress:iu,cleanupTerminal:au,formatToolCall:cu,formatResult:lu,getToolSpinnerText:uu,formatToolSummary:du,formatSectionHeader:fu}});var Fe=L((o$,Hr)=>{var mu=require("readline"),{C:De}=ce(),Fr=[/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/],js=[/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 Ur(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,i=>i.replace(/;/g,"\0")).replace(/\bwhile\s[\s\S]*?\bdone\b/g,i=>i.replace(/;/g,"\0")).split(/\s*(?:&&|;)\s*/).map(i=>i.replace(/\x00/g,";").trim()).filter(Boolean);if(n.length===0)return!1;let o=i=>{let r=i.replace(/^sudo\s+(?:-[ugCD]\s+\S+\s+|-[A-Za-z]+\s+)*/,"");if(/^\s*(?:echo|printf)\s/.test(r))return!0;if(/^\s*for\s/.test(i)||/^\s*while\s/.test(i)){let c=i.match(/\bdo\s+([\s\S]*?)\s*(?:done|$)/)?.[1];return c?c.split(/\s*;\s*/).map(u=>u.trim()).filter(Boolean).every(u=>o(u)):js.some(l=>l.test(i))}return/^\w+=\$?\(/.test(r)||/^\w+=["']/.test(r)||/^\w+=\S/.test(r)?!0:js.some(c=>c.test(r))};return n.every(o)}var Ds=[/rm\s+-rf\s/,/docker\s+system\s+prune/,/kubectl\s+delete/,/sudo\s/],Wr=[/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/],Br=[...Ds,...Wr],Fs=!1,pt=null;function pu(t){Fs=t}function hu(){return Fs}function gu(t){pt=t}function $u(t){for(let e of Fr)if(e.test(t))return e;return null}function yu(t){if(/ssh\s/.test(t)&&Ur(t))return!1;for(let e of Br)if(e.test(t))return!0;return!1}function wu(t){for(let e of Ds)if(e.test(t))return!0;return!1}function bu(t,e={}){if(Fs)return Promise.resolve(!0);if(!process.stdout.isTTY||!process.stdin.isTTY)return xu(t,e);let s=e.toolName?["Yes","No","Always allow"]:["Yes","No"];return new Promise(n=>{let o=0,i=!1;pt&&pt.pause();let r=()=>{i&&process.stdout.write(`\x1B[${s.length+1}A`),i=!0,process.stdout.write(`\r\x1B[K${De.yellow}${t}${De.reset}
40
- `);for(let d=0;d<s.length;d++){let f=d===o,m=f?`${De.yellow}\u276F${De.reset}`:" ",h=f?`${De.yellow}${s[d]}${De.reset}`:s[d];process.stdout.write(`\r\x1B[K ${m} ${h}
41
- `)}},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
42
- `);process.stdout.write(`\x1B[${s.length+1}A`),pt&&pt.resume(),n(d)},l=d=>{if(d===1){c(!1);return}d===2&&e.toolName&&Mn(e.toolName),c(!0)},u=d=>{if(d[0]===3){c(!1);return}let f=d.toString();if(f==="\r"||f===`
43
- `){l(o);return}if(f==="\x1B[A"){o=(o-1+s.length)%s.length,r();return}if(f==="\x1B[B"){o=(o+1)%s.length,r();return}let m=f.toLowerCase().trim();if(m==="y"){c(!0);return}if(m==="n"){c(!1);return}if(m==="a"&&e.toolName){Mn(e.toolName),c(!0);return}};r(),process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",u)})}function xu(t,e){let s=e.toolName?"[Y/n/a] ":"[Y/n] ";return new Promise(n=>{let o=i=>{let r=i.trim().toLowerCase();r==="a"&&e.toolName?(Mn(e.toolName),n(!0)):n(r!=="n")};if(pt)pt.question(`${De.yellow}${t} ${s}${De.reset}`,o);else{let i=mu.createInterface({input:process.stdin,output:process.stdout});i.question(`${De.yellow}${t} ${s}${De.reset}`,r=>{i.close(),o(r)})}})}var Mn=()=>{};function _u(t){Mn=t}Hr.exports={FORBIDDEN_PATTERNS:Fr,SSH_SAFE_PATTERNS:js,isSSHReadOnly:Ur,DANGEROUS_BASH:Br,CRITICAL_BASH:Ds,NOTABLE_BASH:Wr,isForbidden:$u,isDangerous:yu,isCritical:wu,confirm:bu,setAutoConfirm:pu,getAutoConfirm:hu,setReadlineInterface:gu,setAllowAlwaysHandler:_u}});var At=L((r$,Gr)=>{var Us=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`)}};Gr.exports={BaseProvider:Us}});var Yr=L((i$,Kr)=>{var Pn=require("axios"),ku=require("http"),vu=require("https"),{BaseProvider:Su}=At(),Ln=new ku.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),In=new vu.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),zr={"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}},Ws=class extends Su{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||zr,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){Pn.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Ln,httpsAgent:In}).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 Pn.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Ln,httpsAgent:In})).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 r of s.content)r.type==="text"?n.push(r.text??""):r.type==="image"&&r.data&&o.push(r.data);let i={role:"user",content:n.join(`
44
- `)};return o.length>0&&(i.images=o),i}return s})}async chat(e,s,n={}){await this.discoverModels();let o=n.model||this.defaultModel,i=this.getModel(o),r=n.maxTokens||i?.maxTokens||16384,c=await Pn.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:r}},{timeout:n.timeout||this.timeout,headers:this._getHeaders(),httpAgent:Ln,httpsAgent:In});return this.normalizeResponse(c.data)}async stream(e,s,n={}){await this.discoverModels();let o=n.model||this.defaultModel,i=this.getModel(o),r=n.maxTokens||i?.maxTokens||16384,c=n.onToken||(()=>{}),l=n.onThinkingToken||(()=>{}),u;try{u=await Pn.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:r}},{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal,httpAgent:Ln,httpsAgent:In})}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="";n.signal&&n.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(`
45
- `);p=$.pop()||"";for(let y of $){if(!y.trim())continue;let x;try{x=JSON.parse(y)}catch{continue}if(x.message?.thinking&&l(x.message.thinking),x.message?.content&&(c(x.message.content),m+=x.message.content),x.message?.tool_calls&&(h=h.concat(x.message.tool_calls)),x.done){d({content:m,tool_calls:this._normalizeToolCalls(h)});return}}}),u.data.on("error",g=>{n.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,n)=>({id:s.id||`ollama-${Date.now()}-${n}`,function:{name:s.function?.name||s.name||"unknown",arguments:s.function?.arguments||s.arguments||{}}}))}};Kr.exports={OllamaProvider:Ws,OLLAMA_MODELS:zr}});var ei=L((a$,Zr)=>{var{callChat:Eu}=ge(),{estimateTokens:Bs}=Pe(),Jr=process.env.NEX_COMPACTION!=="false",Xr=6,Vr=500,Tu=`Summarize this conversation history concisely. Focus on:
37
+ ${s}Agentic Coding CLI v${Rn().version}${i}
38
+ ${s}Model: ${t}${i} ${s}\xB7 /help${i}${u}
39
+ `)}var{Spinner:nu,MultiProgress:su,TaskProgress:ou,setActiveTaskProgress:ru,getActiveTaskProgress:iu,cleanupTerminal:au}=Ir(),{formatToolCall:cu,formatResult:lu,getToolSpinnerText:uu,formatToolSummary:du,formatSectionHeader:fu}=Dr();Fr.exports={C:Rt,banner:tu,Spinner:nu,MultiProgress:su,TaskProgress:ou,setActiveTaskProgress:ru,getActiveTaskProgress:iu,cleanupTerminal:au,formatToolCall:cu,formatResult:lu,getToolSpinnerText:uu,formatToolSummary:du,formatSectionHeader:fu}});var Fe=L((r$,Gr)=>{var mu=require("readline"),{C:De}=ce(),Ur=[/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/],Ds=[/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 Wr(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,i=>i.replace(/;/g,"\0")).replace(/\bwhile\s[\s\S]*?\bdone\b/g,i=>i.replace(/;/g,"\0")).split(/\s*(?:&&|;)\s*/).map(i=>i.replace(/\x00/g,";").trim()).filter(Boolean);if(n.length===0)return!1;let s=i=>{let r=i.replace(/^sudo\s+(?:-[ugCD]\s+\S+\s+|-[A-Za-z]+\s+)*/,"");if(/^\s*(?:echo|printf)\s/.test(r))return!0;if(/^\s*for\s/.test(i)||/^\s*while\s/.test(i)){let c=i.match(/\bdo\s+([\s\S]*?)\s*(?:done|$)/)?.[1];return c?c.split(/\s*;\s*/).map(u=>u.trim()).filter(Boolean).every(u=>s(u)):Ds.some(l=>l.test(i))}return/^\w+=\$?\(/.test(r)||/^\w+=["']/.test(r)||/^\w+=\S/.test(r)?!0:Ds.some(c=>c.test(r))};return n.every(s)}var Fs=[/rm\s+-rf\s/,/docker\s+system\s+prune/,/kubectl\s+delete/,/sudo\s/],Br=[/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/],Hr=[...Fs,...Br],Us=!1,pt=null;function pu(t){Us=t}function hu(){return Us}function gu(t){pt=t}function $u(t){for(let e of Ur)if(e.test(t))return e;return null}function yu(t){if(/ssh\s/.test(t)&&Wr(t))return!1;for(let e of Hr)if(e.test(t))return!0;return!1}function wu(t){for(let e of Fs)if(e.test(t))return!0;return!1}function bu(t,e={}){if(Us)return Promise.resolve(!0);if(!process.stdout.isTTY||!process.stdin.isTTY)return xu(t,e);let o=e.toolName?["Yes","No","Always allow"]:["Yes","No"];return new Promise(n=>{let s=0,i=!1;pt&&pt.pause();let r=()=>{i&&process.stdout.write(`\x1B[${o.length+1}A`),i=!0,process.stdout.write(`\r\x1B[K${De.yellow}${t}${De.reset}
40
+ `);for(let d=0;d<o.length;d++){let f=d===s,m=f?`${De.yellow}\u276F${De.reset}`:" ",h=f?`${De.yellow}${o[d]}${De.reset}`:o[d];process.stdout.write(`\r\x1B[K ${m} ${h}
41
+ `)}},c=d=>{process.stdin.setRawMode(!1),process.stdin.pause(),process.stdin.removeListener("data",u),process.stdout.write(`\x1B[${o.length+1}A`);for(let f=0;f<o.length+1;f++)process.stdout.write(`\r\x1B[K
42
+ `);process.stdout.write(`\x1B[${o.length+1}A`),pt&&pt.resume(),n(d)},l=d=>{if(d===1){c(!1);return}d===2&&e.toolName&&Mn(e.toolName),c(!0)},u=d=>{if(d[0]===3){c(!1);return}let f=d.toString();if(f==="\r"||f===`
43
+ `){l(s);return}if(f==="\x1B[A"){s=(s-1+o.length)%o.length,r();return}if(f==="\x1B[B"){s=(s+1)%o.length,r();return}let m=f.toLowerCase().trim();if(m==="y"){c(!0);return}if(m==="n"){c(!1);return}if(m==="a"&&e.toolName){Mn(e.toolName),c(!0);return}};r(),process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",u)})}function xu(t,e){let o=e.toolName?"[Y/n/a] ":"[Y/n] ";return new Promise(n=>{let s=i=>{let r=i.trim().toLowerCase();r==="a"&&e.toolName?(Mn(e.toolName),n(!0)):n(r!=="n")};if(pt)pt.question(`${De.yellow}${t} ${o}${De.reset}`,s);else{let i=mu.createInterface({input:process.stdin,output:process.stdout});i.question(`${De.yellow}${t} ${o}${De.reset}`,r=>{i.close(),s(r)})}})}var Mn=()=>{};function _u(t){Mn=t}Gr.exports={FORBIDDEN_PATTERNS:Ur,SSH_SAFE_PATTERNS:Ds,isSSHReadOnly:Wr,DANGEROUS_BASH:Hr,CRITICAL_BASH:Fs,NOTABLE_BASH:Br,isForbidden:$u,isDangerous:yu,isCritical:wu,confirm:bu,setAutoConfirm:pu,getAutoConfirm:hu,setReadlineInterface:gu,setAllowAlwaysHandler:_u}});var At=L((i$,zr)=>{var Ws=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,o,n={}){throw new Error(`${this.name}: chat() not implemented`)}async stream(e,o,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`)}};zr.exports={BaseProvider:Ws}});var Jr=L((a$,Yr)=>{var Pn=require("axios"),ku=require("http"),vu=require("https"),{BaseProvider:Su}=At(),Ln=new ku.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),In=new vu.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Kr={"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}},Bs=class extends Su{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||Kr,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){Pn.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Ln,httpsAgent:In}).then(e=>{let o=e.data?.models||[];for(let n of o){let s=(n.name||n.model||"").replace(/:latest$/,"");!s||this.models[s]||(this.models[s]={id:s,name:n.name||s,maxTokens:16384,contextWindow:131072})}}).catch(()=>{});return}try{let o=(await Pn.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Ln,httpsAgent:In})).data?.models||[];for(let n of o){let s=(n.name||n.model||"").replace(/:latest$/,"");!s||this.models[s]||(this.models[s]={id:s,name:n.name||s,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(o=>{if(o.role==="user"&&Array.isArray(o.content)){let n=[],s=[];for(let r of o.content)r.type==="text"?n.push(r.text??""):r.type==="image"&&r.data&&s.push(r.data);let i={role:"user",content:n.join(`
44
+ `)};return s.length>0&&(i.images=s),i}return o})}async chat(e,o,n={}){await this.discoverModels();let s=n.model||this.defaultModel,i=this.getModel(s),r=n.maxTokens||i?.maxTokens||16384,c=await Pn.post(`${this.baseUrl}/api/chat`,{model:s,messages:this._formatMessages(e),tools:o&&o.length>0?o:void 0,stream:!1,options:{temperature:n.temperature??this.temperature,num_predict:r}},{timeout:n.timeout||this.timeout,headers:this._getHeaders(),httpAgent:Ln,httpsAgent:In});return this.normalizeResponse(c.data)}async stream(e,o,n={}){await this.discoverModels();let s=n.model||this.defaultModel,i=this.getModel(s),r=n.maxTokens||i?.maxTokens||16384,c=n.onToken||(()=>{}),l=n.onThinkingToken||(()=>{}),u;try{u=await Pn.post(`${this.baseUrl}/api/chat`,{model:s,messages:this._formatMessages(e),tools:o&&o.length>0?o:void 0,stream:!0,options:{temperature:n.temperature??this.temperature,num_predict:r}},{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal,httpAgent:Ln,httpsAgent:In})}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="";n.signal&&n.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(`
45
+ `);p=$.pop()||"";for(let y of $){if(!y.trim())continue;let x;try{x=JSON.parse(y)}catch{continue}if(x.message?.thinking&&l(x.message.thinking),x.message?.content&&(c(x.message.content),m+=x.message.content),x.message?.tool_calls&&(h=h.concat(x.message.tool_calls)),x.done){d({content:m,tool_calls:this._normalizeToolCalls(h)});return}}}),u.data.on("error",g=>{n.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 o=e.message||{};return{content:o.content||"",tool_calls:this._normalizeToolCalls(o.tool_calls||[])}}_normalizeToolCalls(e){return e.map((o,n)=>({id:o.id||`ollama-${Date.now()}-${n}`,function:{name:o.function?.name||o.name||"unknown",arguments:o.function?.arguments||o.arguments||{}}}))}};Yr.exports={OllamaProvider:Bs,OLLAMA_MODELS:Kr}});var ti=L((c$,ei)=>{var{callChat:Eu}=ge(),{estimateTokens:Hs}=Pe(),Xr=process.env.NEX_COMPACTION!=="false",Vr=6,Qr=500,Tu=`Summarize this conversation history concisely. Focus on:
46
46
  - What files were read, created, or modified
47
47
  - Key decisions made and their rationale
48
48
  - Current state of the task (what's done, what's pending)
49
49
  - Any errors encountered and how they were resolved
50
- Be factual and brief. Use bullet points. Max 300 words.`;async function Cu(t){if(!Jr||t.length<Xr)return null;let e=[{role:"system",content:Tu},{role:"user",content:Qr(t)}];try{let n=((await Eu(e,[],{temperature:0,maxTokens:Vr})).content||"").trim();if(!n)return null;let o=t.reduce((r,c)=>r+Bs(c.content||"")+(c.tool_calls?Bs(JSON.stringify(c.tool_calls)):0),0),i=Bs(n);return i>=o*.8?null:{message:{role:"system",content:`[Conversation Summary \u2014 ${t.length} messages compacted]
51
- ${n}`,_compacted:!0,_originalCount:t.length},tokensRemoved:o-i}}catch{return null}}function Qr(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(i=>i.function?.name).join(", ");return`[${s}] ${n}
52
- tools: ${o}`}return`[${s}] ${n}`}).join(`
50
+ Be factual and brief. Use bullet points. Max 300 words.`;async function Cu(t){if(!Xr||t.length<Vr)return null;let e=[{role:"system",content:Tu},{role:"user",content:Zr(t)}];try{let n=((await Eu(e,[],{temperature:0,maxTokens:Qr})).content||"").trim();if(!n)return null;let s=t.reduce((r,c)=>r+Hs(c.content||"")+(c.tool_calls?Hs(JSON.stringify(c.tool_calls)):0),0),i=Hs(n);return i>=s*.8?null:{message:{role:"system",content:`[Conversation Summary \u2014 ${t.length} messages compacted]
51
+ ${n}`,_compacted:!0,_originalCount:t.length},tokensRemoved:s-i}}catch{return null}}function Zr(t){return t.map(e=>{let o=e.role==="tool"?"tool_result":e.role,n=(e.content||"").substring(0,500);if(e.tool_calls){let s=e.tool_calls.map(i=>i.function?.name).join(", ");return`[${o}] ${n}
52
+ tools: ${s}`}return`[${o}] ${n}`}).join(`
53
53
 
54
- `)}Zr.exports={compactMessages:Cu,formatMessagesForSummary:Qr,COMPACTION_ENABLED:Jr,COMPACTION_MIN_MESSAGES:Xr,COMPACTION_SUMMARY_BUDGET:Vr}});var Pe=L((c$,ai)=>{function ni(){return ge().getActiveModel()}var Ru={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},Jt=new Map,ti=1e3,Hs=new WeakMap,Xt=null;function Au(){if(Xt!==null)return Xt;try{let e=ni()?.provider||"ollama";return Xt=Ru[e]||4,Xt}catch{return 4}}function Ou(){Xt=null}function gt(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=Jt.get(e);if(s!==void 0)return s;let n=Math.ceil(t.length/Au());if(Jt.size>=ti){let o=ti>>1,i=Jt.keys();for(let r=0;r<o;r++)Jt.delete(i.next().value)}return Jt.set(e,n),n}function Nu(t){if(Hs.has(t))return Hs.get(t);let e=JSON.stringify(t);return Hs.set(t,e),e}function Ot(t){let s=4;if(t.content&&(s+=gt(t.content)),t.tool_calls)for(let n of t.tool_calls){s+=4,s+=gt(n.function?.name||"");let o=n.function?.arguments;typeof o=="string"?s+=gt(o):o&&(s+=gt(JSON.stringify(o)))}return s}function Le(t){let e=0;for(let s of t)e+=Ot(s);return e}function Mu(t,e){if(t&&t.length===e.length){let i=!1;for(let r=0;r<e.length;r++)if(t[r]!==e[r]){i=!0;break}if(!i)return 0}let s=t?t.length:0,n=e.length,o=0;for(let i=s;i<n;i++)o+=Ot(e[i]);return o}function qn(t){return!t||t.length===0?0:gt(JSON.stringify(t))}function jn(){return ni()?.contextWindow||32768}function Pu(t,e){let s=Le(t),n=qn(e),o=s+n,i=jn(),r=i>0?o/i*100:0,c=0,l=0,u=0;for(let d of t){let f=Ot(d);d.role==="system"?c+=f:d.role==="tool"?u+=f:l+=f}return{used:o,limit:i,percentage:Math.round(r*10)/10,breakdown:{system:c,conversation:l,toolResults:u,toolDefinitions:n},messageCount:t.length}}var si=.75,oi=.1,ri=10,Lu=200,Iu=500;function ii(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(`
55
- `);if(o.length<=10){let p=Math.floor(n*.6),g=Math.floor(n*.4),$=t.substring(0,p),y=t.substring(t.length-g);return $+`
54
+ `)}ei.exports={compactMessages:Cu,formatMessagesForSummary:Zr,COMPACTION_ENABLED:Xr,COMPACTION_MIN_MESSAGES:Vr,COMPACTION_SUMMARY_BUDGET:Qr}});var Pe=L((l$,ci)=>{function si(){return ge().getActiveModel()}var Ru={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},Jt=new Map,ni=1e3,Gs=new WeakMap,Xt=null;function Au(){if(Xt!==null)return Xt;try{let e=si()?.provider||"ollama";return Xt=Ru[e]||4,Xt}catch{return 4}}function Ou(){Xt=null}function gt(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)}`,o=Jt.get(e);if(o!==void 0)return o;let n=Math.ceil(t.length/Au());if(Jt.size>=ni){let s=ni>>1,i=Jt.keys();for(let r=0;r<s;r++)Jt.delete(i.next().value)}return Jt.set(e,n),n}function Nu(t){if(Gs.has(t))return Gs.get(t);let e=JSON.stringify(t);return Gs.set(t,e),e}function Ot(t){let o=4;if(t.content&&(o+=gt(t.content)),t.tool_calls)for(let n of t.tool_calls){o+=4,o+=gt(n.function?.name||"");let s=n.function?.arguments;typeof s=="string"?o+=gt(s):s&&(o+=gt(JSON.stringify(s)))}return o}function Le(t){let e=0;for(let o of t)e+=Ot(o);return e}function Mu(t,e){if(t&&t.length===e.length){let i=!1;for(let r=0;r<e.length;r++)if(t[r]!==e[r]){i=!0;break}if(!i)return 0}let o=t?t.length:0,n=e.length,s=0;for(let i=o;i<n;i++)s+=Ot(e[i]);return s}function qn(t){return!t||t.length===0?0:gt(JSON.stringify(t))}function jn(){return si()?.contextWindow||32768}function Pu(t,e){let o=Le(t),n=qn(e),s=o+n,i=jn(),r=i>0?s/i*100:0,c=0,l=0,u=0;for(let d of t){let f=Ot(d);d.role==="system"?c+=f:d.role==="tool"?u+=f:l+=f}return{used:s,limit:i,percentage:Math.round(r*10)/10,breakdown:{system:c,conversation:l,toolResults:u,toolDefinitions:n},messageCount:t.length}}var oi=.75,ri=.1,ii=10,Lu=200,Iu=500;function ai(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 s=t.split(`
55
+ `);if(s.length<=10){let p=Math.floor(n*.6),g=Math.floor(n*.4),$=t.substring(0,p),y=t.substring(t.length-g);return $+`
56
56
  ...(${t.length} chars total)...
57
- `+y}let i=Math.floor(o.length*.4),r=Math.floor(o.length*.4),c=[],l=0,u=Math.floor(n*.4);for(let p=0;p<i&&l<u;p++)if(l+o[p].length+1>u&&o[p].trim().startsWith("```")){c.push(o[p]),l+=o[p].length+1;let g=p+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),p=g}else c.push(o[p]),l+=o[p].length+1;let d=[],f=0,m=Math.floor(n*.4);for(let p=o.length-1;p>=o.length-r&&f<m;p--)if(f+o[p].length+1>m&&o[p].trim().startsWith("```")){d.push(o[p]),f+=o[p].length+1;let g=p-1;for(;g>=0&&f<m*1.5&&!o[g].trim().startsWith("```");)d.push(o[g]),f+=o[g].length+1,g--;g>=0&&o[g].trim().startsWith("```")&&(d.push(o[g]),f+=o[g].length+1),p=g}else d.push(o[p]),f+=o[p].length+1;d.reverse();let h=o.length-c.length-d.length;return c.join(`
57
+ `+y}let i=Math.floor(s.length*.4),r=Math.floor(s.length*.4),c=[],l=0,u=Math.floor(n*.4);for(let p=0;p<i&&l<u;p++)if(l+s[p].length+1>u&&s[p].trim().startsWith("```")){c.push(s[p]),l+=s[p].length+1;let g=p+1;for(;g<s.length&&l<u*1.5&&!s[g].trim().startsWith("```");)c.push(s[g]),l+=s[g].length+1,g++;g<s.length&&s[g].trim().startsWith("```")&&(c.push(s[g]),l+=s[g].length+1),p=g}else c.push(s[p]),l+=s[p].length+1;let d=[],f=0,m=Math.floor(n*.4);for(let p=s.length-1;p>=s.length-r&&f<m;p--)if(f+s[p].length+1>m&&s[p].trim().startsWith("```")){d.push(s[p]),f+=s[p].length+1;let g=p-1;for(;g>=0&&f<m*1.5&&!s[g].trim().startsWith("```");)d.push(s[g]),f+=s[g].length+1,g--;g>=0&&s[g].trim().startsWith("```")&&(d.push(s[g]),f+=s[g].length+1),p=g}else d.push(s[p]),f+=s[p].length+1;d.reverse();let h=s.length-c.length-d.length;return c.join(`
58
58
  `)+`
59
- ...(${h} lines omitted, ${o.length} total)...
59
+ ...(${h} lines omitted, ${s.length} total)...
60
60
  `+d.join(`
61
- `)}function Vt(t,e="light"){let s=e==="aggressive"?100:e==="medium"?200:Iu,n=e==="aggressive"?50:e==="medium"?100:Lu;if(t.role==="tool"){let o=typeof t.content=="string"?t.content:JSON.stringify(t.content);return o.length>n?{...t,content:ii(o,n)}:t}if(t.role==="assistant"){let o={...t};return o.content&&o.content.length>s&&(o.content=o.content.substring(0,s)+`
62
- ...(truncated)`),o.tool_calls&&e==="aggressive"&&(o.tool_calls=o.tool_calls.map(i=>({...i,function:{name:i.function.name,arguments:typeof i.function.arguments=="string"?i.function.arguments.substring(0,50):i.function.arguments}}))),o}return t}async function qu(t,e,s={}){let n=s.threshold??si,o=s.safetyMargin??oi,i=s.keepRecent??ri,r=jn(),c=qn(e),l=Math.floor(r*(n-o)),u=l-c,d=Le(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-i),$=t.slice(p,g),y=t.slice(g),x=$.filter(O=>!O._compacted);if(x.length>=6)try{let{compactMessages:O}=ei(),v=await O(x);if(v){let j=[...$.filter(Q=>Q._compacted),v.message],J=ht(h,j,y),U=Le(J);if(U+c<=l)return{messages:J,compressed:!0,compacted:!0,tokensRemoved:m-U};$=j}}catch(O){process.env.NEX_DEBUG&&console.error("[context-engine] LLM compacting failed:",O.message)}let T=(f-l)/l,k=$.map(O=>Vt(O,"light")),E=ht(h,k,y),C=Le(E);if(C+c<=l)return{messages:E,compressed:!0,compacted:!1,tokensRemoved:m-C};if(k=$.map(O=>Vt(O,"medium")),E=ht(h,k,y),C=Le(E),C+c<=l)return{messages:E,compressed:!0,compacted:!1,tokensRemoved:m-C};if(k=$.map(O=>Vt(O,"aggressive")),E=ht(h,k,y),C=Le(E),C+c<=l)return{messages:E,compressed:!0,compacted:!1,tokensRemoved:m-C};for(;k.length>0&&C>u;){let O=k.shift();C-=Ot(O)}return E=ht(h,k,y),C=Le(E),{messages:E,compressed:!0,compacted:!1,tokensRemoved:m-C}}function ht(t,e,s){let n=[];return t&&n.push(t),n.push(...e,...s),n}function ju(t,e){if(!t)return"";if(gt(t)<=e)return t;let n=e*4,o=t.split(`
63
- `),i=Math.floor(n*.6),r=Math.floor(n*.4),c="",l=0;for(let h of o){if(c.length+h.length+1>i)break;c+=(c?`
64
- `:"")+h,l++}let u="",d=0;for(let h=o.length-1;h>=l;h--){let p=o[h]+(u?`
61
+ `)}function Vt(t,e="light"){let o=e==="aggressive"?100:e==="medium"?200:Iu,n=e==="aggressive"?50:e==="medium"?100:Lu;if(t.role==="tool"){let s=typeof t.content=="string"?t.content:JSON.stringify(t.content);return s.length>n?{...t,content:ai(s,n)}:t}if(t.role==="assistant"){let s={...t};return s.content&&s.content.length>o&&(s.content=s.content.substring(0,o)+`
62
+ ...(truncated)`),s.tool_calls&&e==="aggressive"&&(s.tool_calls=s.tool_calls.map(i=>({...i,function:{name:i.function.name,arguments:typeof i.function.arguments=="string"?i.function.arguments.substring(0,50):i.function.arguments}}))),s}return t}async function qu(t,e,o={}){let n=o.threshold??oi,s=o.safetyMargin??ri,i=o.keepRecent??ii,r=jn(),c=qn(e),l=Math.floor(r*(n-s)),u=l-c,d=Le(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-i),$=t.slice(p,g),y=t.slice(g),x=$.filter(O=>!O._compacted);if(x.length>=6)try{let{compactMessages:O}=ti(),v=await O(x);if(v){let j=[...$.filter(Q=>Q._compacted),v.message],J=ht(h,j,y),U=Le(J);if(U+c<=l)return{messages:J,compressed:!0,compacted:!0,tokensRemoved:m-U};$=j}}catch(O){process.env.NEX_DEBUG&&console.error("[context-engine] LLM compacting failed:",O.message)}let T=(f-l)/l,k=$.map(O=>Vt(O,"light")),E=ht(h,k,y),C=Le(E);if(C+c<=l)return{messages:E,compressed:!0,compacted:!1,tokensRemoved:m-C};if(k=$.map(O=>Vt(O,"medium")),E=ht(h,k,y),C=Le(E),C+c<=l)return{messages:E,compressed:!0,compacted:!1,tokensRemoved:m-C};if(k=$.map(O=>Vt(O,"aggressive")),E=ht(h,k,y),C=Le(E),C+c<=l)return{messages:E,compressed:!0,compacted:!1,tokensRemoved:m-C};for(;k.length>0&&C>u;){let O=k.shift();C-=Ot(O)}return E=ht(h,k,y),C=Le(E),{messages:E,compressed:!0,compacted:!1,tokensRemoved:m-C}}function ht(t,e,o){let n=[];return t&&n.push(t),n.push(...e,...o),n}function ju(t,e){if(!t)return"";if(gt(t)<=e)return t;let n=e*4,s=t.split(`
63
+ `),i=Math.floor(n*.6),r=Math.floor(n*.4),c="",l=0;for(let h of s){if(c.length+h.length+1>i)break;c+=(c?`
64
+ `:"")+h,l++}let u="",d=0;for(let h=s.length-1;h>=l;h--){let p=s[h]+(u?`
65
65
  `:"")+u;if(p.length>r)break;u=p,d++}let m=`
66
66
 
67
- ... (${o.length-l-d} lines omitted, ${o.length} total) ...
67
+ ... (${s.length-l-d} lines omitted, ${s.length} total) ...
68
68
 
69
- `;return c+m+u}var Du=6;function Fu(t,e){let s=jn(),n=qn(e),o=Math.floor(s*.5)-n,i=Le(t),r=null,c=0;t.length>0&&t[0].role==="system"&&(r=t[0],c=1);let l=Math.max(c,t.length-Du),u=t.slice(c,l),d=t.slice(l),f=u.map(p=>Vt(p,"aggressive")),m=ht(r,f,d),h=Le(m);for(;f.length>0&&h>o;){let p=f.shift();h-=Ot(p)}return m=ht(r,f,d),h=Le(m),{messages:m,tokensRemoved:i-h}}ai.exports={estimateTokens:gt,estimateMessageTokens:Ot,estimateMessagesTokens:Le,estimateDeltaTokens:Mu,estimateToolsTokens:qn,serializeMessage:Nu,getContextWindow:jn,getUsage:Pu,compressMessage:Vt,compressToolResult:ii,fitToContext:qu,forceCompress:Fu,truncateFileContent:ju,invalidateTokenRatioCache:Ou,COMPRESSION_THRESHOLD:si,SAFETY_MARGIN:oi,KEEP_RECENT:ri}});var di=L((u$,ui)=>{var ci=require("axios"),{BaseProvider:Uu}=At(),{serializeMessage:l$}=Pe(),li={"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}},Gs=class extends Uu{constructor(e={}){super({name:"openai",baseUrl:e.baseUrl||"https://api.openai.com/v1",models:e.models||li,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 r=this._messageStringCache.get(o);this._messageFormatCache.set(n,r),s.push(r);continue}let i=this._formatSingleMessage(n);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(o,i),this._messageFormatCache.set(n,i),s.push(i)}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,i=this.getModel(o),r=n.maxTokens||i?.maxTokens||16384,{messages:c}=this.formatMessages(e),l={model:o,messages:c,max_tokens:r,temperature:n.temperature??this.temperature};s&&s.length>0&&(l.tools=s);let u=await ci.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,i=this.getModel(o),r=n.maxTokens||i?.maxTokens||16384,c=n.onToken||(()=>{}),{messages:l}=this.formatMessages(e),u={model:o,messages:l,max_tokens:r,temperature:n.temperature??this.temperature,stream:!0};s&&s.length>0&&(u.tools=s);let d;try{d=await ci.post(`${this.baseUrl}/chat/completions`,u,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.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="";n.signal&&n.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(`
70
- `);g=y.pop()||"";for(let x of y){let T=x.trim();if(!T||!T.startsWith("data: "))continue;let k=T.slice(6);if(k==="[DONE]"){f({content:h,tool_calls:this._buildToolCalls(p)});return}let E;try{E=JSON.parse(k)}catch{continue}let C=E.choices?.[0]?.delta;if(C&&(C.content&&(c(C.content),h+=C.content),C.tool_calls))for(let O of C.tool_calls){let v=O.index??0;p[v]||(p[v]={id:O.id||"",name:"",arguments:""}),O.id&&(p[v].id=O.id),O.function?.name&&(p[v].name+=O.function.name),O.function?.arguments&&(p[v].arguments+=O.function.arguments)}}}),d.data.on("error",$=>{n.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||{},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}}))}};ui.exports={OpenAIProvider:Gs,OPENAI_MODELS:li}});var hi=L((f$,pi)=>{var fi=require("axios"),{BaseProvider:Wu}=At(),{serializeMessage:d$}=Pe(),mi={"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}},Bu="2023-06-01",zs=class extends Wu{constructor(e={}){super({name:"anthropic",baseUrl:e.baseUrl||"https://api.anthropic.com/v1",models:e.models||mi,defaultModel:e.defaultModel||"claude-sonnet",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this.apiVersion=e.apiVersion||Bu}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
+ `;return c+m+u}var Du=6;function Fu(t,e){let o=jn(),n=qn(e),s=Math.floor(o*.5)-n,i=Le(t),r=null,c=0;t.length>0&&t[0].role==="system"&&(r=t[0],c=1);let l=Math.max(c,t.length-Du),u=t.slice(c,l),d=t.slice(l),f=u.map(p=>Vt(p,"aggressive")),m=ht(r,f,d),h=Le(m);for(;f.length>0&&h>s;){let p=f.shift();h-=Ot(p)}return m=ht(r,f,d),h=Le(m),{messages:m,tokensRemoved:i-h}}ci.exports={estimateTokens:gt,estimateMessageTokens:Ot,estimateMessagesTokens:Le,estimateDeltaTokens:Mu,estimateToolsTokens:qn,serializeMessage:Nu,getContextWindow:jn,getUsage:Pu,compressMessage:Vt,compressToolResult:ai,fitToContext:qu,forceCompress:Fu,truncateFileContent:ju,invalidateTokenRatioCache:Ou,COMPRESSION_THRESHOLD:oi,SAFETY_MARGIN:ri,KEEP_RECENT:ii}});var fi=L((d$,di)=>{var li=require("axios"),{BaseProvider:Uu}=At(),{serializeMessage:u$}=Pe(),ui={"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}},zs=class extends Uu{constructor(e={}){super({name:"openai",baseUrl:e.baseUrl||"https://api.openai.com/v1",models:e.models||ui,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 o=[];for(let n of e){if(this._messageFormatCache.has(n)){o.push(this._messageFormatCache.get(n));continue}let s=this._getMessageCacheKey(n);if(this._messageStringCache.has(s)){let r=this._messageStringCache.get(s);this._messageFormatCache.set(n,r),o.push(r);continue}let i=this._formatSingleMessage(n);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(s,i),this._messageFormatCache.set(n,i),o.push(i)}return{messages:o}}_getMessageCacheKey(e){let o=e.role||"",n=typeof e.content=="string"?e.content.substring(0,100):"",s=e.tool_calls?e.tool_calls.length:0;return`${o}:${n.length}:${s}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||null,tool_calls:e.tool_calls.map(o=>({id:o.id||`call-${Date.now()}`,type:"function",function:{name:o.function.name,arguments:typeof o.function.arguments=="string"?o.function.arguments:JSON.stringify(o.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 o=[];for(let n of e.content)if(n.type==="text")o.push({type:"text",text:n.text??""});else if(n.type==="image"&&n.data){let s=n.data.startsWith("data:")?n.data:`data:${n.media_type||"image/png"};base64,${n.data}`;o.push({type:"image_url",image_url:{url:s,detail:"auto"}})}return{role:"user",content:o}}return{role:e.role,content:e.content}}async chat(e,o,n={}){let s=n.model||this.defaultModel,i=this.getModel(s),r=n.maxTokens||i?.maxTokens||16384,{messages:c}=this.formatMessages(e),l={model:s,messages:c,max_tokens:r,temperature:n.temperature??this.temperature};o&&o.length>0&&(l.tools=o);let u=await li.post(`${this.baseUrl}/chat/completions`,l,{timeout:n.timeout||this.timeout,headers:this._getHeaders()});return this.normalizeResponse(u.data)}async stream(e,o,n={}){let s=n.model||this.defaultModel,i=this.getModel(s),r=n.maxTokens||i?.maxTokens||16384,c=n.onToken||(()=>{}),{messages:l}=this.formatMessages(e),u={model:s,messages:l,max_tokens:r,temperature:n.temperature??this.temperature,stream:!0};o&&o.length>0&&(u.tools=o);let d;try{d=await li.post(`${this.baseUrl}/chat/completions`,u,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.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="";n.signal&&n.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(`
70
+ `);g=y.pop()||"";for(let x of y){let T=x.trim();if(!T||!T.startsWith("data: "))continue;let k=T.slice(6);if(k==="[DONE]"){f({content:h,tool_calls:this._buildToolCalls(p)});return}let E;try{E=JSON.parse(k)}catch{continue}let C=E.choices?.[0]?.delta;if(C&&(C.content&&(c(C.content),h+=C.content),C.tool_calls))for(let O of C.tool_calls){let v=O.index??0;p[v]||(p[v]={id:O.id||"",name:"",arguments:""}),O.id&&(p[v].id=O.id),O.function?.name&&(p[v].name+=O.function.name),O.function?.arguments&&(p[v].arguments+=O.function.arguments)}}}),d.data.on("error",$=>{n.signal?.aborted||m(new Error(`Stream error: ${$.message}`))}),d.data.on("end",()=>{f({content:h,tool_calls:this._buildToolCalls(p)})})})}normalizeResponse(e){let o=e.choices?.[0]?.message||{},n=(o.tool_calls||[]).map(s=>({id:s.id,function:{name:s.function.name,arguments:s.function.arguments}}));return{content:o.content||"",tool_calls:n}}_buildToolCalls(e){return Object.values(e).filter(o=>o.name).map(o=>({id:o.id||`openai-${Date.now()}`,function:{name:o.name,arguments:o.arguments}}))}};di.exports={OpenAIProvider:zs,OPENAI_MODELS:ui}});var gi=L((m$,hi)=>{var mi=require("axios"),{BaseProvider:Wu}=At(),{serializeMessage:f$}=Pe(),pi={"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}},Bu="2023-06-01",Ks=class extends Wu{constructor(e={}){super({name:"anthropic",baseUrl:e.baseUrl||"https://api.anthropic.com/v1",models:e.models||pi,defaultModel:e.defaultModel||"claude-sonnet",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this.apiVersion=e.apiVersion||Bu}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 o="",n=[];for(let s of e){if(s.role==="system"){o+=(o?`
71
71
 
72
- `:"")+o.content;continue}if(o.role!=="system"&&o.role!=="tool"&&this._messageFormatCache.has(o)){n.push(this._messageFormatCache.get(o));continue}let i=this._formatSingleMessage(o,n);if(i){if(o.role!=="system"&&o.role!=="tool"&&this._messageStringCache.size<this._maxCacheSize){let r=this._getMessageCacheKey(o);this._messageStringCache.set(r,i),this._messageFormatCache.set(o,i)}n.push(i)}}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,i=this._resolveModelId(o),r=this.getModel(o),c=n.maxTokens||r?.maxTokens||8192,{messages:l,system:u}=this.formatMessages(e),d={model:i,messages:l,max_tokens:c,temperature:n.temperature??this.temperature};u&&(d.system=u);let f=this.formatTools(s);f.length>0&&(d.tools=f);let m=await fi.post(`${this.baseUrl}/messages`,d,{timeout:n.timeout||this.timeout,headers:this._getHeaders()});return this.normalizeResponse(m.data)}async stream(e,s,n={}){let o=n.model||this.defaultModel,i=this._resolveModelId(o),r=this.getModel(o),c=n.maxTokens||r?.maxTokens||8192,l=n.onToken||(()=>{}),{messages:u,system:d}=this.formatMessages(e),f={model:i,messages:u,max_tokens:c,temperature:n.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 fi.post(`${this.baseUrl}/messages`,f,{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 g=p.response?.data?.error?.message||p.message;throw new Error(`API Error: ${g}`)}return new Promise((p,g)=>{let $="",y=[],x=-1,T="";n.signal&&n.signal.addEventListener("abort",()=>{h.data.destroy(),g(new DOMException("The operation was aborted","AbortError"))},{once:!0}),h.data.on("data",k=>{T+=k.toString();let E=T.split(`
73
- `);T=E.pop()||"";for(let C of E){let O=C.trim();if(O.startsWith("data: ")){let v=O.slice(6),F;try{F=JSON.parse(v)}catch{continue}switch(F.type){case"content_block_start":{let j=F.content_block;j?.type==="tool_use"&&(x=y.length,y.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),$+=j.text),j?.type==="input_json_delta"&&j.partial_json!==void 0&&x>=0&&(y[x].inputJson+=j.partial_json);break}case"content_block_stop":x=-1;break;case"message_stop":p({content:$,tool_calls:this._buildToolCalls(y)});return}}}}),h.data.on("error",k=>{n.signal?.aborted||g(new Error(`Stream error: ${k.message}`))}),h.data.on("end",()=>{p({content:$,tool_calls:this._buildToolCalls(y)})})})}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}}})}};pi.exports={AnthropicProvider:zs,ANTHROPIC_MODELS:mi}});var wi=L((p$,yi)=>{var gi=require("axios"),{BaseProvider:Hu}=At(),{serializeMessage:m$}=Pe(),$i={"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}},Ks=class extends Hu{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||$i,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 r=this._messageStringCache.get(o);this._messageFormatCache.set(n,r),s.push(r);continue}let i=this._formatSingleMessage(n);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(o,i),this._messageFormatCache.set(n,i),s.push(i)}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,i=this.getModel(o),r=n.maxTokens||i?.maxTokens||8192,{messages:c}=this.formatMessages(e),l={model:o,messages:c,max_tokens:r,temperature:n.temperature??this.temperature};s&&s.length>0&&(l.tools=s);let u=await gi.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,i=this.getModel(o),r=n.maxTokens||i?.maxTokens||8192,c=n.onToken||(()=>{}),{messages:l}=this.formatMessages(e),u={model:o,messages:l,max_tokens:r,temperature:n.temperature??this.temperature,stream:!0};s&&s.length>0&&(u.tools=s);let d;try{d=await gi.post(`${this.baseUrl}/chat/completions`,u,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.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="";n.signal&&n.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 x of y){let T=x.trim();if(!T||!T.startsWith("data: "))continue;let k=T.slice(6);if(k==="[DONE]"){f({content:h,tool_calls:this._buildToolCalls(p)});return}let E;try{E=JSON.parse(k)}catch{continue}let C=E.choices?.[0]?.delta;if(C&&(C.content&&(c(C.content),h+=C.content),C.tool_calls))for(let O of C.tool_calls){let v=O.index??0;p[v]||(p[v]={id:O.id||"",name:"",arguments:""}),O.id&&(p[v].id=O.id),O.function?.name&&(p[v].name+=O.function.name),O.function?.arguments&&(p[v].arguments+=O.function.arguments)}}}),d.data.on("error",$=>{n.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||{},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}}))}};yi.exports={GeminiProvider:Ks,GEMINI_MODELS:$i}});var _i=L((h$,xi)=>{var Dn=require("axios"),{BaseProvider:Gu}=At(),bi="http://localhost:11434",Ys=class extends Gu{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||bi,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 Dn.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 i=o.replace(/:latest$/,""),r=32768;try{let c=await Dn.post(`${this.baseUrl}/api/show`,{name:o},{timeout:5e3}),l=c.data?.model_info||c.data?.details||{};r=l["general.context_length"]||l["llama.context_length"]||this._parseContextFromModelfile(c.data?.modelfile)||32768}catch{}this.models[i]={id:i,name:n.name,maxTokens:Math.min(8192,Math.floor(r*.1)),contextWindow:r}}!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 r of s.content)r.type==="text"?n.push(r.text??""):r.type==="image"&&r.data&&o.push(r.data);let i={role:"user",content:n.join(`
75
- `)};return o.length>0&&(i.images=o),i}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 i=await Dn.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(i.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 i=n.onToken||(()=>{}),r;try{r=await Dn.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=[],f="";n.signal&&n.signal.addEventListener("abort",()=>{r.data.destroy(),l(new DOMException("The operation was aborted","AbortError"))},{once:!0}),r.data.on("data",m=>{f+=m.toString();let h=f.split(`
76
- `);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&&(i(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}}}),r.data.on("error",m=>{n.signal?.aborted||l(new Error(`Stream error: ${m.message}`))}),r.data.on("end",()=>{if(f.trim())try{let m=JSON.parse(f);m.message?.content&&(i(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,n)=>({id:s.id||`local-${Date.now()}-${n}`,function:{name:s.function?.name||s.name||"unknown",arguments:s.function?.arguments||s.arguments||{}}}))}};xi.exports={LocalProvider:Ys,DEFAULT_LOCAL_URL:bi}});var Nt=L((g$,Ri)=>{var $t=require("fs"),Js=require("path"),ki={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:{}},Fn=[],it={};function zu(t,e,s,n){if(Fn.push({provider:t,model:e,input:s,output:n}),it[t]!==void 0){let o=Ti(t);o.allowed||process.stderr.write(`\x1B[33m\u26A0 Budget limit reached for ${t}: $${o.spent.toFixed(2)} / $${o.limit.toFixed(2)}\x1B[0m
77
- `)}}function Xs(t,e){let s=ki[t];return s?s[e]||{input:0,output:0}:{input:0,output:0}}function vi(t){let e=Xs(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function Si(){let t={};for(let i of Fn){let r=`${i.provider}:${i.model}`;t[r]||(t[r]={provider:i.provider,model:i.model,input:0,output:0}),t[r].input+=i.input,t[r].output+=i.output}let e=Object.values(t).map(i=>({...i,cost:vi(i)})),s=e.reduce((i,r)=>i+r.cost,0),n=e.reduce((i,r)=>i+r.input,0),o=e.reduce((i,r)=>i+r.output,0);return{totalCost:s,totalInput:n,totalOutput:o,breakdown:e}}function Ku(){let{totalCost:t,totalInput:e,totalOutput:s,breakdown:n}=Si();if(n.length===0)return"No token usage recorded this session.";let o=[];o.push("Session Token Usage:"),o.push("");for(let i of n){let r=i.cost>0?`$${i.cost.toFixed(4)}`:"free";o.push(` ${i.provider}:${i.model}`),o.push(` Input: ${i.input.toLocaleString()} tokens`),o.push(` Output: ${i.output.toLocaleString()} tokens`),o.push(` Cost: ${r}`)}return o.push(""),o.push(` Total: ${e.toLocaleString()} in + ${s.toLocaleString()} out = $${t.toFixed(4)}`),o.join(`
78
- `)}function Yu(t,e,s,n){let o=Xs(t,e),i=(s*o.input+n*o.output)/1e6;return i<=0?"":`[~$${i.toFixed(4)}]`}function Ju(){Fn=[]}function Xu(t,e){it[t]=e}function Vu(t){delete it[t]}function Qu(){return{...it}}function Ei(t){let e=0;for(let s of Fn)s.provider===t&&(e+=vi(s));return e}function Ti(t){let e=Ei(t),s=it[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 Ci(){let t=Js.join(process.cwd(),".nex","config.json");if($t.existsSync(t))try{let e=JSON.parse($t.readFileSync(t,"utf-8"));e.costLimits&&typeof e.costLimits=="object"&&(it={...e.costLimits})}catch{}}function Zu(){let t=Js.join(process.cwd(),".nex"),e=Js.join(t,"config.json"),s={};if($t.existsSync(e))try{s=JSON.parse($t.readFileSync(e,"utf-8"))}catch{s={}}s.costLimits=it,$t.existsSync(t)||$t.mkdirSync(t,{recursive:!0}),$t.writeFileSync(e,JSON.stringify(s,null,2),"utf-8")}function ed(){it={}}Ci();Ri.exports={PRICING:ki,trackUsage:zu,getSessionCosts:Si,formatCosts:Ku,formatCostHint:Yu,resetCosts:Ju,getPricing:Xs,setCostLimit:Xu,removeCostLimit:Vu,getCostLimits:Qu,getProviderSpend:Ei,checkBudget:Ti,loadCostLimits:Ci,saveCostLimits:Zu,resetCostLimits:ed}});var Un=L(($$,Ai)=>{var Qt=ge(),td={"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 nd(){return Qt.getActiveModel()}function sd(t){return Qt.setActiveModel(t)}function od(){return Qt.getModelNames()}function rd(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 id(t,e){let{C:s}=ce(),{Spinner:n}=ce(),o=new n("Thinking...");o.start();let i=!0,r="";try{let c=await Qt.callStream(t,e,{onToken:l=>{i&&(o.stop(),process.stdout.write(`${s.blue}`),i=!1),process.stdout.write(l),r+=l}});return i?o.stop():process.stdout.write(`${s.reset}
79
- `),c}catch(c){throw o.stop(),c}}async function ad(t,e){return Qt.callChat(t,e)}Ai.exports={MODELS:td,getActiveModel:nd,setActiveModel:sd,getModelNames:od,callOllamaStream:id,callOllama:ad,parseToolArgs:rd}});var Mi=L((y$,Ni)=>{var Wn=require("path"),{C:_}=ce(),{confirm:cd,getAutoConfirm:ld}=Fe(),Oi=2e3;function Zt(t,e){let s=t.split(`
72
+ `:"")+s.content;continue}if(s.role!=="system"&&s.role!=="tool"&&this._messageFormatCache.has(s)){n.push(this._messageFormatCache.get(s));continue}let i=this._formatSingleMessage(s,n);if(i){if(s.role!=="system"&&s.role!=="tool"&&this._messageStringCache.size<this._maxCacheSize){let r=this._getMessageCacheKey(s);this._messageStringCache.set(r,i),this._messageFormatCache.set(s,i)}n.push(i)}}return{messages:n,system:o}}_getMessageCacheKey(e){let o=e.role||"",n=typeof e.content=="string"?e.content.substring(0,100):"",s=e.tool_calls?e.tool_calls.length:0;return`${o}:${n.length}:${s}`}_formatSingleMessage(e,o=[]){if(e.role==="assistant"){let n=[];if(e.content&&n.push({type:"text",text:e.content}),e.tool_calls)for(let s of e.tool_calls)n.push({type:"tool_use",id:s.id||`toolu-${Date.now()}`,name:s.function.name,input:typeof s.function.arguments=="string"?JSON.parse(s.function.arguments||"{}"):s.function.arguments||{}});return{role:"assistant",content:n.length>0?n:[{type:"text",text:""}]}}if(e.role==="tool"){let n=o[o.length-1],s={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(s),null):{role:"user",content:[s]}}if(Array.isArray(e.content)){let n=[];for(let s of e.content)s.type==="text"?n.push({type:"text",text:s.text??""}):s.type==="image"&&s.data&&n.push({type:"image",source:{type:"base64",media_type:s.media_type||"image/png",data:s.data}});return{role:"user",content:n}}return{role:"user",content:e.content}}formatTools(e){return!e||e.length===0?[]:e.map(o=>({name:o.function.name,description:o.function.description||"",input_schema:o.function.parameters||{type:"object",properties:{}}}))}_resolveModelId(e){return this.getModel(e)?.id||e}async chat(e,o,n={}){let s=n.model||this.defaultModel,i=this._resolveModelId(s),r=this.getModel(s),c=n.maxTokens||r?.maxTokens||8192,{messages:l,system:u}=this.formatMessages(e),d={model:i,messages:l,max_tokens:c,temperature:n.temperature??this.temperature};u&&(d.system=u);let f=this.formatTools(o);f.length>0&&(d.tools=f);let m=await mi.post(`${this.baseUrl}/messages`,d,{timeout:n.timeout||this.timeout,headers:this._getHeaders()});return this.normalizeResponse(m.data)}async stream(e,o,n={}){let s=n.model||this.defaultModel,i=this._resolveModelId(s),r=this.getModel(s),c=n.maxTokens||r?.maxTokens||8192,l=n.onToken||(()=>{}),{messages:u,system:d}=this.formatMessages(e),f={model:i,messages:u,max_tokens:c,temperature:n.temperature??this.temperature,stream:!0};d&&(f.system=d);let m=this.formatTools(o);m.length>0&&(f.tools=m);let h;try{h=await mi.post(`${this.baseUrl}/messages`,f,{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 g=p.response?.data?.error?.message||p.message;throw new Error(`API Error: ${g}`)}return new Promise((p,g)=>{let $="",y=[],x=-1,T="";n.signal&&n.signal.addEventListener("abort",()=>{h.data.destroy(),g(new DOMException("The operation was aborted","AbortError"))},{once:!0}),h.data.on("data",k=>{T+=k.toString();let E=T.split(`
73
+ `);T=E.pop()||"";for(let C of E){let O=C.trim();if(O.startsWith("data: ")){let v=O.slice(6),F;try{F=JSON.parse(v)}catch{continue}switch(F.type){case"content_block_start":{let j=F.content_block;j?.type==="tool_use"&&(x=y.length,y.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),$+=j.text),j?.type==="input_json_delta"&&j.partial_json!==void 0&&x>=0&&(y[x].inputJson+=j.partial_json);break}case"content_block_stop":x=-1;break;case"message_stop":p({content:$,tool_calls:this._buildToolCalls(y)});return}}}}),h.data.on("error",k=>{n.signal?.aborted||g(new Error(`Stream error: ${k.message}`))}),h.data.on("end",()=>{p({content:$,tool_calls:this._buildToolCalls(y)})})})}normalizeResponse(e){let o="",n=[];for(let s of e.content||[])s.type==="text"?o+=s.text:s.type==="tool_use"&&n.push({id:s.id,function:{name:s.name,arguments:s.input}});return{content:o,tool_calls:n}}_buildToolCalls(e){return e.filter(o=>o.name).map(o=>{let n={};if(o.inputJson)try{n=JSON.parse(o.inputJson)}catch{n=o.inputJson}return{id:o.id||`anthropic-${Date.now()}`,function:{name:o.name,arguments:n}}})}};hi.exports={AnthropicProvider:Ks,ANTHROPIC_MODELS:pi}});var bi=L((h$,wi)=>{var $i=require("axios"),{BaseProvider:Hu}=At(),{serializeMessage:p$}=Pe(),yi={"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}},Ys=class extends Hu{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||yi,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 o=[];for(let n of e){if(this._messageFormatCache.has(n)){o.push(this._messageFormatCache.get(n));continue}let s=this._getMessageCacheKey(n);if(this._messageStringCache.has(s)){let r=this._messageStringCache.get(s);this._messageFormatCache.set(n,r),o.push(r);continue}let i=this._formatSingleMessage(n);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(s,i),this._messageFormatCache.set(n,i),o.push(i)}return{messages:o}}_getMessageCacheKey(e){let o=e.role||"",n=typeof e.content=="string"?e.content.substring(0,100):"",s=e.tool_calls?e.tool_calls.length:0;return`${o}:${n.length}:${s}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||"",tool_calls:e.tool_calls.map(o=>({id:o.id||`call-${Date.now()}`,type:"function",function:{name:o.function.name,arguments:typeof o.function.arguments=="string"?o.function.arguments:JSON.stringify(o.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 o=[];for(let n of e.content)if(n.type==="text")o.push({type:"text",text:n.text??""});else if(n.type==="image"&&n.data){let s=n.data.startsWith("data:")?n.data:`data:${n.media_type||"image/png"};base64,${n.data}`;o.push({type:"image_url",image_url:{url:s,detail:"auto"}})}return{role:"user",content:o}}return{role:e.role,content:e.content}}async chat(e,o,n={}){let s=n.model||this.defaultModel,i=this.getModel(s),r=n.maxTokens||i?.maxTokens||8192,{messages:c}=this.formatMessages(e),l={model:s,messages:c,max_tokens:r,temperature:n.temperature??this.temperature};o&&o.length>0&&(l.tools=o);let u=await $i.post(`${this.baseUrl}/chat/completions`,l,{timeout:n.timeout||this.timeout,headers:this._getHeaders()});return this.normalizeResponse(u.data)}async stream(e,o,n={}){let s=n.model||this.defaultModel,i=this.getModel(s),r=n.maxTokens||i?.maxTokens||8192,c=n.onToken||(()=>{}),{messages:l}=this.formatMessages(e),u={model:s,messages:l,max_tokens:r,temperature:n.temperature??this.temperature,stream:!0};o&&o.length>0&&(u.tools=o);let d;try{d=await $i.post(`${this.baseUrl}/chat/completions`,u,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.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="";n.signal&&n.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 x of y){let T=x.trim();if(!T||!T.startsWith("data: "))continue;let k=T.slice(6);if(k==="[DONE]"){f({content:h,tool_calls:this._buildToolCalls(p)});return}let E;try{E=JSON.parse(k)}catch{continue}let C=E.choices?.[0]?.delta;if(C&&(C.content&&(c(C.content),h+=C.content),C.tool_calls))for(let O of C.tool_calls){let v=O.index??0;p[v]||(p[v]={id:O.id||"",name:"",arguments:""}),O.id&&(p[v].id=O.id),O.function?.name&&(p[v].name+=O.function.name),O.function?.arguments&&(p[v].arguments+=O.function.arguments)}}}),d.data.on("error",$=>{n.signal?.aborted||m(new Error(`Stream error: ${$.message}`))}),d.data.on("end",()=>{f({content:h,tool_calls:this._buildToolCalls(p)})})})}normalizeResponse(e){let o=e.choices?.[0]?.message||{},n=(o.tool_calls||[]).map(s=>({id:s.id,function:{name:s.function.name,arguments:s.function.arguments}}));return{content:o.content||"",tool_calls:n}}_buildToolCalls(e){return Object.values(e).filter(o=>o.name).map(o=>({id:o.id||`call-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,function:{name:o.name,arguments:o.arguments}}))}};wi.exports={GeminiProvider:Ys,GEMINI_MODELS:yi}});var ki=L((g$,_i)=>{var Dn=require("axios"),{BaseProvider:Gu}=At(),xi="http://localhost:11434",Js=class extends Gu{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||xi,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 o=(await Dn.get(`${this.baseUrl}/api/tags`,{timeout:5e3})).data?.models||[];this.models={};for(let n of o){let s=n.name||n.model;if(!s)continue;let i=s.replace(/:latest$/,""),r=32768;try{let c=await Dn.post(`${this.baseUrl}/api/show`,{name:s},{timeout:5e3}),l=c.data?.model_info||c.data?.details||{};r=l["general.context_length"]||l["llama.context_length"]||this._parseContextFromModelfile(c.data?.modelfile)||32768}catch{}this.models[i]={id:i,name:n.name,maxTokens:Math.min(8192,Math.floor(r*.1)),contextWindow:r}}!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(o=>{if(o.role==="user"&&Array.isArray(o.content)){let n=[],s=[];for(let r of o.content)r.type==="text"?n.push(r.text??""):r.type==="image"&&r.data&&s.push(r.data);let i={role:"user",content:n.join(`
75
+ `)};return s.length>0&&(i.images=s),i}return o})}async chat(e,o,n={}){this._modelsLoaded||await this.loadModels();let s=n.model||this.defaultModel;if(!s)throw new Error("No local model available. Is Ollama running?");let i=await Dn.post(`${this.baseUrl}/api/chat`,{model:s,messages:this._formatMessages(e),tools:o&&o.length>0?o:void 0,stream:!1,options:{temperature:n.temperature??this.temperature,num_predict:n.maxTokens||8192}},{timeout:n.timeout||this.timeout});return this.normalizeResponse(i.data)}async stream(e,o,n={}){this._modelsLoaded||await this.loadModels();let s=n.model||this.defaultModel;if(!s)throw new Error("No local model available. Is Ollama running?");let i=n.onToken||(()=>{}),r;try{r=await Dn.post(`${this.baseUrl}/api/chat`,{model:s,messages:this._formatMessages(e),tools:o&&o.length>0?o: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=[],f="";n.signal&&n.signal.addEventListener("abort",()=>{r.data.destroy(),l(new DOMException("The operation was aborted","AbortError"))},{once:!0}),r.data.on("data",m=>{f+=m.toString();let h=f.split(`
76
+ `);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&&(i(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}}}),r.data.on("error",m=>{n.signal?.aborted||l(new Error(`Stream error: ${m.message}`))}),r.data.on("end",()=>{if(f.trim())try{let m=JSON.parse(f);m.message?.content&&(i(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 o=e.message||{};return{content:o.content||"",tool_calls:this._normalizeToolCalls(o.tool_calls||[])}}_parseContextFromModelfile(e){if(!e)return null;let o=e.match(/PARAMETER\s+num_ctx\s+(\d+)/i);return o?parseInt(o[1],10):null}_normalizeToolCalls(e){return e.map((o,n)=>({id:o.id||`local-${Date.now()}-${n}`,function:{name:o.function?.name||o.name||"unknown",arguments:o.function?.arguments||o.arguments||{}}}))}};_i.exports={LocalProvider:Js,DEFAULT_LOCAL_URL:xi}});var Nt=L(($$,Ai)=>{var $t=require("fs"),Xs=require("path"),vi={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:{}},Fn=[],it={};function zu(t,e,o,n){if(Fn.push({provider:t,model:e,input:o,output:n}),it[t]!==void 0){let s=Ci(t);s.allowed||process.stderr.write(`\x1B[33m\u26A0 Budget limit reached for ${t}: $${s.spent.toFixed(2)} / $${s.limit.toFixed(2)}\x1B[0m
77
+ `)}}function Vs(t,e){let o=vi[t];return o?o[e]||{input:0,output:0}:{input:0,output:0}}function Si(t){let e=Vs(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function Ei(){let t={};for(let i of Fn){let r=`${i.provider}:${i.model}`;t[r]||(t[r]={provider:i.provider,model:i.model,input:0,output:0}),t[r].input+=i.input,t[r].output+=i.output}let e=Object.values(t).map(i=>({...i,cost:Si(i)})),o=e.reduce((i,r)=>i+r.cost,0),n=e.reduce((i,r)=>i+r.input,0),s=e.reduce((i,r)=>i+r.output,0);return{totalCost:o,totalInput:n,totalOutput:s,breakdown:e}}function Ku(){let{totalCost:t,totalInput:e,totalOutput:o,breakdown:n}=Ei();if(n.length===0)return"No token usage recorded this session.";let s=[];s.push("Session Token Usage:"),s.push("");for(let i of n){let r=i.cost>0?`$${i.cost.toFixed(4)}`:"free";s.push(` ${i.provider}:${i.model}`),s.push(` Input: ${i.input.toLocaleString()} tokens`),s.push(` Output: ${i.output.toLocaleString()} tokens`),s.push(` Cost: ${r}`)}return s.push(""),s.push(` Total: ${e.toLocaleString()} in + ${o.toLocaleString()} out = $${t.toFixed(4)}`),s.join(`
78
+ `)}function Yu(t,e,o,n){let s=Vs(t,e),i=(o*s.input+n*s.output)/1e6;return i<=0?"":`[~$${i.toFixed(4)}]`}function Ju(){Fn=[]}function Xu(t,e){it[t]=e}function Vu(t){delete it[t]}function Qu(){return{...it}}function Ti(t){let e=0;for(let o of Fn)o.provider===t&&(e+=Si(o));return e}function Ci(t){let e=Ti(t),o=it[t];if(o===void 0)return{allowed:!0,spent:e,limit:null,remaining:null};let n=Math.max(0,o-e);return{allowed:e<o,spent:e,limit:o,remaining:n}}function Ri(){let t=Xs.join(process.cwd(),".nex","config.json");if($t.existsSync(t))try{let e=JSON.parse($t.readFileSync(t,"utf-8"));e.costLimits&&typeof e.costLimits=="object"&&(it={...e.costLimits})}catch{}}function Zu(){let t=Xs.join(process.cwd(),".nex"),e=Xs.join(t,"config.json"),o={};if($t.existsSync(e))try{o=JSON.parse($t.readFileSync(e,"utf-8"))}catch{o={}}o.costLimits=it,$t.existsSync(t)||$t.mkdirSync(t,{recursive:!0}),$t.writeFileSync(e,JSON.stringify(o,null,2),"utf-8")}function ed(){it={}}Ri();Ai.exports={PRICING:vi,trackUsage:zu,getSessionCosts:Ei,formatCosts:Ku,formatCostHint:Yu,resetCosts:Ju,getPricing:Vs,setCostLimit:Xu,removeCostLimit:Vu,getCostLimits:Qu,getProviderSpend:Ti,checkBudget:Ci,loadCostLimits:Ri,saveCostLimits:Zu,resetCostLimits:ed}});var Un=L((y$,Oi)=>{var Qt=ge(),td={"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 nd(){return Qt.getActiveModel()}function sd(t){return Qt.setActiveModel(t)}function od(){return Qt.getModelNames()}function rd(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 o=t.match(/```(?:json)?\s*([\s\S]*?)```/);if(o)try{return JSON.parse(o[1].trim())}catch{}return null}async function id(t,e){let{C:o}=ce(),{Spinner:n}=ce(),s=new n("Thinking...");s.start();let i=!0,r="";try{let c=await Qt.callStream(t,e,{onToken:l=>{i&&(s.stop(),process.stdout.write(`${o.blue}`),i=!1),process.stdout.write(l),r+=l}});return i?s.stop():process.stdout.write(`${o.reset}
79
+ `),c}catch(c){throw s.stop(),c}}async function ad(t,e){return Qt.callChat(t,e)}Oi.exports={MODELS:td,getActiveModel:nd,setActiveModel:sd,getModelNames:od,callOllamaStream:id,callOllama:ad,parseToolArgs:rd}});var Pi=L((w$,Mi)=>{var Wn=require("path"),{C:_}=ce(),{confirm:cd,getAutoConfirm:ld}=Fe(),Ni=2e3;function Zt(t,e){let o=t.split(`
80
80
  `),n=e.split(`
81
- `),o=[],i=s.length,r=n.length;if(i>Oi||r>Oi){for(let f of s)o.push({type:"remove",line:f});for(let f of n)o.push({type:"add",line:f});return o}let c=Array.from({length:i+1},()=>new Array(r+1).fill(0));for(let f=1;f<=i;f++)for(let m=1;m<=r;m++)s[f-1]===n[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=i,u=r,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 ud(t,e,s,n=3){console.log(`
82
- ${_.bold}${_.cyan} Diff: ${t}${_.reset}`);let o=Zt(e,s),i=[];if(o.forEach((l,u)=>{l.type!=="same"&&i.push(u)}),i.length===0){console.log(`${_.gray} (no changes)${_.reset}`);return}let r=Math.max(0,i[0]-n),c=Math.min(o.length,i[i.length-1]+n+1);r>0&&console.log(`${_.gray} ...${_.reset}`);for(let l=r;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 dd(t,e,s){console.log(`
83
- ${_.bold}${_.cyan} File exists \u2014 showing changes: ${t}${_.reset}`);let n=Zt(e,s),o=0;for(let r of n)r.type!=="same"&&o++;if(o===0){console.log(`${_.gray} (identical content)${_.reset}`);return}let i=0;for(let r of n){if(i>=30){console.log(`${_.gray} ...(${o-i} more changes)${_.reset}`);break}switch(r.type){case"remove":console.log(`${_.red} - ${r.line}${_.reset}`),i++;break;case"add":console.log(`${_.green} + ${r.line}${_.reset}`),i++;break;default:i>0&&console.log(`${_.gray} ${r.line}${_.reset}`)}}console.log()}function fd(t,e){console.log(`
84
- ${_.bold}${_.cyan} New file: ${t}${_.reset}`);let s=e.split(`
85
- `),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 ld()?!0:cd(` ${t}?`)}function pd(t,e,s,n){let o=n||process.stdout.columns||80,i=Math.floor((o-3)/2);console.log(`
86
- ${_.bold}${_.cyan} Side-by-side: ${t}${_.reset}`),console.log(` ${_.dim}${"\u2500".repeat(i)}\u252C${"\u2500".repeat(i)}${_.reset}`);let r=Zt(e,s),c=[],l=0;for(;l<r.length;)if(r[l].type==="same")c.push({left:r[l].line,right:r[l].line,type:"same"}),l++;else if(r[l].type==="remove"){let h=[];for(;l<r.length&&r[l].type==="remove";)h.push(r[l].line),l++;let p=[];for(;l<r.length&&r[l].type==="add";)p.push(r[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 r[l].type==="add"&&(c.push({left:"",right:r[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(` ${_.gray}(no changes)${_.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(` ${_.dim}${"\xB7".repeat(i)}\u250A${"\xB7".repeat(i)}${_.reset}`);for(let h=d;h<f;h++){let p=c[h];if(p.type==="same")console.log(` ${_.gray}${m(p.left,i)}${_.reset}\u2502${_.gray}${m(p.right,i)}${_.reset}`);else{let g=p.left?`${_.red}${m(p.left,i)}${_.reset}`:`${m("",i)}`,$=p.right?`${_.green}${m(p.right,i)}${_.reset}`:`${m("",i)}`;console.log(` ${g}\u2502${$}`)}}f<c.length&&console.log(` ${_.dim}${"\xB7".repeat(i)}\u250A${"\xB7".repeat(i)}${_.reset}`),console.log(` ${_.dim}${"\u2500".repeat(i)}\u2534${"\u2500".repeat(i)}${_.reset}
87
- `)}function hd(t,e,s,n={}){let o=n.label||"Update",i=n.context||3,r=n.annotations||[],c=Wn.isAbsolute(t)?Wn.relative(process.cwd(),t):t,l=Zt(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 f=0,m=0;for(let k of l)k.type==="add"?f++:k.type==="remove"&&m++;if(console.log(`
88
- ${_.cyan}\u23FA${_.reset} ${_.bold}${o}(${c})${_.reset}`),f===0&&m===0){console.log(` ${_.dim}\u23BF (no changes)${_.reset}
89
- `);return}let h=[];if(f>0&&h.push(`Added ${f} line${f!==1?"s":""}`),m>0&&h.push(`removed ${m} line${m!==1?"s":""}`),r.length>0){let k=r.filter(v=>v.severity==="error").length,E=r.filter(v=>v.severity==="warn").length,C=r.filter(v=>v.severity==="info").length,O=[];k>0&&O.push(`${_.red}${k} error${k!==1?"s":""}${_.dim}`),E>0&&O.push(`${_.yellow}${E} warning${E!==1?"s":""}${_.dim}`),C>0&&O.push(`${_.cyan}${C} info${C!==1?"s":""}${_.dim}`),h.push(`found ${O.join(", ")}`)}console.log(` ${_.dim}\u23BF ${h.join(", ")}${_.reset}`);let g=[];l.forEach((k,E)=>{k.type!=="same"&&g.push(E)});let $=[],y=null,x=null;for(let k of g){let E=Math.max(0,k-i),C=Math.min(l.length-1,k+i);y===null?(y=E,x=C):(E<=x+1||($.push([y,x]),y=E),x=C)}y!==null&&$.push([y,x]);let T=" ";for(let k=0;k<$.length;k++){k>0&&console.log(`${T}${_.dim}\xB7\xB7\xB7${_.reset}`);let[E,C]=$[k];for(let O=E;O<=C;O++){let v=l[O],F=v.newLine!=null?v.newLine:v.oldLine,j=String(F).padStart(4),J=v.type!=="remove"?r.filter(U=>U.line===v.newLine):[];v.type==="remove"?console.log(`${T}${_.red}${j} -${v.line}${_.reset}`):v.type==="add"?console.log(`${T}${_.green}${j} +${v.line}${_.reset}`):console.log(`${T}${_.dim}${j}${_.reset} ${v.line}`);for(let U of J){let Q=_.cyan,me="\u2139";U.severity==="error"?(Q=_.red,me="\u2716"):U.severity==="warn"&&(Q=_.yellow,me="\u26A0"),console.log(`${T} ${Q}${me} ${U.message}${_.reset}`)}}}console.log()}function gd(t,e,s={}){let n=Wn.isAbsolute(t)?Wn.relative(process.cwd(),t):t,o=e.split(`
90
- `),i=s.annotations||[];console.log(`
91
- ${_.cyan}\u23FA${_.reset} ${_.bold}Create(${n})${_.reset}`);let r=[`${o.length} line${o.length!==1?"s":""}`];if(i.length>0){let d=i.filter(p=>p.severity==="error").length,f=i.filter(p=>p.severity==="warn").length,m=i.filter(p=>p.severity==="info").length,h=[];d>0&&h.push(`${_.red}${d} error${d!==1?"s":""}${_.dim}`),f>0&&h.push(`${_.yellow}${f} warning${f!==1?"s":""}${_.dim}`),m>0&&h.push(`${_.cyan}${m} info${m!==1?"s":""}${_.dim}`),r.push(`found ${h.join(", ")}`)}console.log(` ${_.dim}\u23BF ${r.join(", ")}${_.reset}`);let l=" ",u=Math.min(o.length,20);for(let d=0;d<u;d++){let f=String(d+1).padStart(4),m=d+1,h=i.filter(p=>p.line===m);console.log(`${l}${_.green}${f} +${o[d]}${_.reset}`);for(let p of h){let g=_.cyan,$="\u2139";p.severity==="error"?(g=_.red,$="\u2716"):p.severity==="warn"&&(g=_.yellow,$="\u26A0"),console.log(`${l} ${g}${$} ${p.message}${_.reset}`)}}o.length>20&&console.log(`${l}${_.dim} ...+${o.length-20} more lines${_.reset}`),console.log()}Ni.exports={diffLines:Zt,showEditDiff:ud,showWriteDiff:dd,showNewFilePreview:fd,confirmFileChange:md,showSideBySideDiff:pd,showClaudeDiff:hd,showClaudeNewFile:gd}});var yt=L((w$,Ii)=>{var Pi=require("util").promisify(require("child_process").exec),$d=require("util").promisify(require("child_process").execFile),{C:re}=ce();async function Vs(t){try{let{stdout:e}=await Pi(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function Bn(...t){try{let{stdout:e}=await $d("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function yd(){return await Vs("git rev-parse --is-inside-work-tree")==="true"}async function wd(){return await Vs("git branch --show-current")}async function Qs(){try{let{stdout:t}=await Pi("git status --porcelain",{cwd:process.cwd(),timeout:3e4});return!t||!t.trim()?[]:t.split(`
92
- `).filter(Boolean).map(e=>{let s=e.substring(0,2).trim(),n=e.substring(3);return{status:s,file:n}})}catch{return[]}}async function Hn(t=!1){return await Vs(`git diff ${t?"--cached":""}`)||""}async function Zs(){return(await Qs()).map(e=>e.file)}async function Li(){let t=await Zs();if(t.length===0)return null;let e=await Hn(),n=await Hn(!0)||e,o=0,i=0;if(n){let d=n.split(`
93
- `);for(let f of d)f.startsWith("+")&&!f.startsWith("+++")&&o++,f.startsWith("-")&&!f.startsWith("---")&&i++}else o=t.length;let r="chore",c=t.join(" ").toLowerCase();c.includes("test")?r="test":c.includes("readme")||c.includes("doc")?r="docs":o>i*2?r="feat":i>o?r="refactor":r="fix";let l=t.slice(0,3).map(d=>d.split("/").pop());return{summary:`${r}: update ${l.join(", ")}${t.length>3?` (+${t.length-3} more)`:""}`,type:r,files:t,stats:{additions:o,deletions:i}}}async function bd(t){let s=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await Bn("checkout","-b",s)!==null?s:null}async function xd(t){return await Bn("add","-A"),await Bn("commit","-m",t)?await Bn("rev-parse","--short","HEAD"):null}async function _d(){let t=await Li();if(!t)return`${re.dim}No changes${re.reset}`;let e=[];e.push(`
81
+ `),s=[],i=o.length,r=n.length;if(i>Ni||r>Ni){for(let f of o)s.push({type:"remove",line:f});for(let f of n)s.push({type:"add",line:f});return s}let c=Array.from({length:i+1},()=>new Array(r+1).fill(0));for(let f=1;f<=i;f++)for(let m=1;m<=r;m++)o[f-1]===n[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=i,u=r,d=[];for(;l>0||u>0;)l>0&&u>0&&o[l-1]===n[u-1]?(d.unshift({type:"same",line:o[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:o[l-1]}),l--);return d}function ud(t,e,o,n=3){console.log(`
82
+ ${_.bold}${_.cyan} Diff: ${t}${_.reset}`);let s=Zt(e,o),i=[];if(s.forEach((l,u)=>{l.type!=="same"&&i.push(u)}),i.length===0){console.log(`${_.gray} (no changes)${_.reset}`);return}let r=Math.max(0,i[0]-n),c=Math.min(s.length,i[i.length-1]+n+1);r>0&&console.log(`${_.gray} ...${_.reset}`);for(let l=r;l<c;l++){let u=s[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<s.length&&console.log(`${_.gray} ...${_.reset}`),console.log()}function dd(t,e,o){console.log(`
83
+ ${_.bold}${_.cyan} File exists \u2014 showing changes: ${t}${_.reset}`);let n=Zt(e,o),s=0;for(let r of n)r.type!=="same"&&s++;if(s===0){console.log(`${_.gray} (identical content)${_.reset}`);return}let i=0;for(let r of n){if(i>=30){console.log(`${_.gray} ...(${s-i} more changes)${_.reset}`);break}switch(r.type){case"remove":console.log(`${_.red} - ${r.line}${_.reset}`),i++;break;case"add":console.log(`${_.green} + ${r.line}${_.reset}`),i++;break;default:i>0&&console.log(`${_.gray} ${r.line}${_.reset}`)}}console.log()}function fd(t,e){console.log(`
84
+ ${_.bold}${_.cyan} New file: ${t}${_.reset}`);let o=e.split(`
85
+ `),n=o.slice(0,20);for(let s of n)console.log(`${_.green} + ${s}${_.reset}`);o.length>20&&console.log(`${_.gray} ...+${o.length-20} more lines${_.reset}`),console.log()}async function md(t){return ld()?!0:cd(` ${t}?`)}function pd(t,e,o,n){let s=n||process.stdout.columns||80,i=Math.floor((s-3)/2);console.log(`
86
+ ${_.bold}${_.cyan} Side-by-side: ${t}${_.reset}`),console.log(` ${_.dim}${"\u2500".repeat(i)}\u252C${"\u2500".repeat(i)}${_.reset}`);let r=Zt(e,o),c=[],l=0;for(;l<r.length;)if(r[l].type==="same")c.push({left:r[l].line,right:r[l].line,type:"same"}),l++;else if(r[l].type==="remove"){let h=[];for(;l<r.length&&r[l].type==="remove";)h.push(r[l].line),l++;let p=[];for(;l<r.length&&r[l].type==="add";)p.push(r[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 r[l].type==="add"&&(c.push({left:"",right:r[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(` ${_.gray}(no changes)${_.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(` ${_.dim}${"\xB7".repeat(i)}\u250A${"\xB7".repeat(i)}${_.reset}`);for(let h=d;h<f;h++){let p=c[h];if(p.type==="same")console.log(` ${_.gray}${m(p.left,i)}${_.reset}\u2502${_.gray}${m(p.right,i)}${_.reset}`);else{let g=p.left?`${_.red}${m(p.left,i)}${_.reset}`:`${m("",i)}`,$=p.right?`${_.green}${m(p.right,i)}${_.reset}`:`${m("",i)}`;console.log(` ${g}\u2502${$}`)}}f<c.length&&console.log(` ${_.dim}${"\xB7".repeat(i)}\u250A${"\xB7".repeat(i)}${_.reset}`),console.log(` ${_.dim}${"\u2500".repeat(i)}\u2534${"\u2500".repeat(i)}${_.reset}
87
+ `)}function hd(t,e,o,n={}){let s=n.label||"Update",i=n.context||3,r=n.annotations||[],c=Wn.isAbsolute(t)?Wn.relative(process.cwd(),t):t,l=Zt(e,o),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 f=0,m=0;for(let k of l)k.type==="add"?f++:k.type==="remove"&&m++;if(console.log(`
88
+ ${_.cyan}\u23FA${_.reset} ${_.bold}${s}(${c})${_.reset}`),f===0&&m===0){console.log(` ${_.dim}\u23BF (no changes)${_.reset}
89
+ `);return}let h=[];if(f>0&&h.push(`Added ${f} line${f!==1?"s":""}`),m>0&&h.push(`removed ${m} line${m!==1?"s":""}`),r.length>0){let k=r.filter(v=>v.severity==="error").length,E=r.filter(v=>v.severity==="warn").length,C=r.filter(v=>v.severity==="info").length,O=[];k>0&&O.push(`${_.red}${k} error${k!==1?"s":""}${_.dim}`),E>0&&O.push(`${_.yellow}${E} warning${E!==1?"s":""}${_.dim}`),C>0&&O.push(`${_.cyan}${C} info${C!==1?"s":""}${_.dim}`),h.push(`found ${O.join(", ")}`)}console.log(` ${_.dim}\u23BF ${h.join(", ")}${_.reset}`);let g=[];l.forEach((k,E)=>{k.type!=="same"&&g.push(E)});let $=[],y=null,x=null;for(let k of g){let E=Math.max(0,k-i),C=Math.min(l.length-1,k+i);y===null?(y=E,x=C):(E<=x+1||($.push([y,x]),y=E),x=C)}y!==null&&$.push([y,x]);let T=" ";for(let k=0;k<$.length;k++){k>0&&console.log(`${T}${_.dim}\xB7\xB7\xB7${_.reset}`);let[E,C]=$[k];for(let O=E;O<=C;O++){let v=l[O],F=v.newLine!=null?v.newLine:v.oldLine,j=String(F).padStart(4),J=v.type!=="remove"?r.filter(U=>U.line===v.newLine):[];v.type==="remove"?console.log(`${T}${_.red}${j} -${v.line}${_.reset}`):v.type==="add"?console.log(`${T}${_.green}${j} +${v.line}${_.reset}`):console.log(`${T}${_.dim}${j}${_.reset} ${v.line}`);for(let U of J){let Q=_.cyan,me="\u2139";U.severity==="error"?(Q=_.red,me="\u2716"):U.severity==="warn"&&(Q=_.yellow,me="\u26A0"),console.log(`${T} ${Q}${me} ${U.message}${_.reset}`)}}}console.log()}function gd(t,e,o={}){let n=Wn.isAbsolute(t)?Wn.relative(process.cwd(),t):t,s=e.split(`
90
+ `),i=o.annotations||[];console.log(`
91
+ ${_.cyan}\u23FA${_.reset} ${_.bold}Create(${n})${_.reset}`);let r=[`${s.length} line${s.length!==1?"s":""}`];if(i.length>0){let d=i.filter(p=>p.severity==="error").length,f=i.filter(p=>p.severity==="warn").length,m=i.filter(p=>p.severity==="info").length,h=[];d>0&&h.push(`${_.red}${d} error${d!==1?"s":""}${_.dim}`),f>0&&h.push(`${_.yellow}${f} warning${f!==1?"s":""}${_.dim}`),m>0&&h.push(`${_.cyan}${m} info${m!==1?"s":""}${_.dim}`),r.push(`found ${h.join(", ")}`)}console.log(` ${_.dim}\u23BF ${r.join(", ")}${_.reset}`);let l=" ",u=Math.min(s.length,20);for(let d=0;d<u;d++){let f=String(d+1).padStart(4),m=d+1,h=i.filter(p=>p.line===m);console.log(`${l}${_.green}${f} +${s[d]}${_.reset}`);for(let p of h){let g=_.cyan,$="\u2139";p.severity==="error"?(g=_.red,$="\u2716"):p.severity==="warn"&&(g=_.yellow,$="\u26A0"),console.log(`${l} ${g}${$} ${p.message}${_.reset}`)}}s.length>20&&console.log(`${l}${_.dim} ...+${s.length-20} more lines${_.reset}`),console.log()}Mi.exports={diffLines:Zt,showEditDiff:ud,showWriteDiff:dd,showNewFilePreview:fd,confirmFileChange:md,showSideBySideDiff:pd,showClaudeDiff:hd,showClaudeNewFile:gd}});var yt=L((b$,qi)=>{var Li=require("util").promisify(require("child_process").exec),$d=require("util").promisify(require("child_process").execFile),{C:re}=ce();async function Qs(t){try{let{stdout:e}=await Li(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function Bn(...t){try{let{stdout:e}=await $d("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function yd(){return await Qs("git rev-parse --is-inside-work-tree")==="true"}async function wd(){return await Qs("git branch --show-current")}async function Zs(){try{let{stdout:t}=await Li("git status --porcelain",{cwd:process.cwd(),timeout:3e4});return!t||!t.trim()?[]:t.split(`
92
+ `).filter(Boolean).map(e=>{let o=e.substring(0,2).trim(),n=e.substring(3);return{status:o,file:n}})}catch{return[]}}async function Hn(t=!1){return await Qs(`git diff ${t?"--cached":""}`)||""}async function eo(){return(await Zs()).map(e=>e.file)}async function Ii(){let t=await eo();if(t.length===0)return null;let e=await Hn(),n=await Hn(!0)||e,s=0,i=0;if(n){let d=n.split(`
93
+ `);for(let f of d)f.startsWith("+")&&!f.startsWith("+++")&&s++,f.startsWith("-")&&!f.startsWith("---")&&i++}else s=t.length;let r="chore",c=t.join(" ").toLowerCase();c.includes("test")?r="test":c.includes("readme")||c.includes("doc")?r="docs":s>i*2?r="feat":i>s?r="refactor":r="fix";let l=t.slice(0,3).map(d=>d.split("/").pop());return{summary:`${r}: update ${l.join(", ")}${t.length>3?` (+${t.length-3} more)`:""}`,type:r,files:t,stats:{additions:s,deletions:i}}}async function bd(t){let o=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await Bn("checkout","-b",o)!==null?o:null}async function xd(t){return await Bn("add","-A"),await Bn("commit","-m",t)?await Bn("rev-parse","--short","HEAD"):null}async function _d(){let t=await Ii();if(!t)return`${re.dim}No changes${re.reset}`;let e=[];e.push(`
94
94
  ${re.bold}${re.cyan}Git Diff Summary:${re.reset}`),e.push(` ${re.green}+${t.stats.additions}${re.reset} ${re.red}-${t.stats.deletions}${re.reset} in ${t.files.length} file(s)`),e.push(`
95
- ${re.bold}${re.cyan}Files:${re.reset}`);for(let s of t.files.slice(0,20))e.push(` ${re.dim}${s}${re.reset}`);return t.files.length>20&&e.push(` ${re.dim}...+${t.files.length-20} more${re.reset}`),e.push(`
95
+ ${re.bold}${re.cyan}Files:${re.reset}`);for(let o of t.files.slice(0,20))e.push(` ${re.dim}${o}${re.reset}`);return t.files.length>20&&e.push(` ${re.dim}...+${t.files.length-20} more${re.reset}`),e.push(`
96
96
  ${re.bold}${re.cyan}Suggested message:${re.reset}`),e.push(` ${re.cyan}${t.summary}${re.reset}
97
97
  `),e.join(`
98
- `)}async function kd(){return(await Qs()).filter(e=>e.status==="UU"||e.status==="AA"||e.status==="DD")}async function vd(){let t=await Zs();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 Hn();if(s){let n=s.length>5e3?s.substring(0,5e3)+`
99
- ...(truncated)`:s;e.push(`
98
+ `)}async function kd(){return(await Zs()).filter(e=>e.status==="UU"||e.status==="AA"||e.status==="DD")}async function vd(){let t=await eo();if(t.length===0)return"";let e=[`CHANGED FILES (${t.length}):`];for(let n of t.slice(0,10))e.push(` ${n}`);let o=await Hn();if(o){let n=o.length>5e3?o.substring(0,5e3)+`
99
+ ...(truncated)`:o;e.push(`
100
100
  DIFF:
101
101
  ${n}`)}return e.join(`
102
- `)}Ii.exports={isGitRepo:yd,getCurrentBranch:wd,getStatus:Qs,getDiff:Hn,getChangedFiles:Zs,analyzeDiff:Li,createBranch:bd,commit:xd,formatDiffSummary:_d,getDiffContext:vd,getMergeConflicts:kd}});var Pt=L((b$,qi)=>{var eo=require("fs").promises,Sd=50,Xe=[],Mt=[];function Ed(t,e,s,n){for(Xe.push({tool:t,filePath:e,oldContent:s,newContent:n,timestamp:Date.now()});Xe.length>Sd;)Xe.shift();Mt.length=0}async function Td(){if(Xe.length===0)return null;let t=Xe.pop();if(t.oldContent===null)try{await eo.unlink(t.filePath)}catch{}else await eo.writeFile(t.filePath,t.oldContent,"utf-8");return Mt.push(t),{tool:t.tool,filePath:t.filePath,wasCreated:t.oldContent===null}}async function Cd(){if(Mt.length===0)return null;let t=Mt.pop();return await eo.writeFile(t.filePath,t.newContent,"utf-8"),Xe.push(t),{tool:t.tool,filePath:t.filePath}}function Rd(t=10){return Xe.slice(-t).reverse().map(e=>({tool:e.tool,filePath:e.filePath,timestamp:e.timestamp}))}function Ad(){return Xe.length}function Od(){return Mt.length}function Nd(){Xe.length=0,Mt.length=0}qi.exports={recordChange:Ed,undo:Td,redo:Cd,getHistory:Rd,getUndoCount:Ad,getRedoCount:Od,clearHistory:Nd}});var en=L((x$,Bi)=>{var Te=require("fs"),Lt=require("path"),_e=[];function to(){return Lt.join(process.cwd(),".nex","skills")}function ji(){return Lt.join(process.cwd(),".nex","config.json")}function Md(){let t=to();return Te.existsSync(t)||Te.mkdirSync(t,{recursive:!0}),t}function no(){let t=ji();if(!Te.existsSync(t))return[];try{let e=JSON.parse(Te.readFileSync(t,"utf-8"));return e.skills&&Array.isArray(e.skills.disabled)?e.skills.disabled:[]}catch{return[]}}function Di(t){let e=ji(),s={};if(Te.existsSync(e))try{s=JSON.parse(Te.readFileSync(e,"utf-8"))}catch{s={}}s.skills||(s.skills={}),s.skills.disabled=t;let n=Lt.dirname(e);Te.existsSync(n)||Te.mkdirSync(n,{recursive:!0}),Te.writeFileSync(e,JSON.stringify(s,null,2),"utf-8")}function Fi(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 Ui(t){try{let e=Te.readFileSync(t,"utf-8").trim();return e?{name:Lt.basename(t,".md"),type:"prompt",filePath:t,instructions:e,commands:[],tools:[]}:null}catch{return null}}function Wi(t){try{let e=require(t),{valid:s,errors:n}=Fi(e,t);return s?{name:e.name||Lt.basename(t,".js"),type:"script",filePath:t,description:e.description||"",instructions:e.instructions||"",commands:(e.commands||[]).map(i=>({cmd:i.cmd.startsWith("/")?i.cmd:`/${i.cmd}`,desc:i.desc||i.description||"",handler:i.handler||null})),tools:(e.tools||[]).map(i=>({type:i.type||"function",function:{name:i.function.name,description:i.function.description||"",parameters:i.function.parameters||{type:"object",properties:{}}},execute:i.execute||null}))}:(console.error(`Skill validation failed: ${t}
102
+ `)}qi.exports={isGitRepo:yd,getCurrentBranch:wd,getStatus:Zs,getDiff:Hn,getChangedFiles:eo,analyzeDiff:Ii,createBranch:bd,commit:xd,formatDiffSummary:_d,getDiffContext:vd,getMergeConflicts:kd}});var Pt=L((x$,ji)=>{var to=require("fs").promises,Sd=50,Xe=[],Mt=[];function Ed(t,e,o,n){for(Xe.push({tool:t,filePath:e,oldContent:o,newContent:n,timestamp:Date.now()});Xe.length>Sd;)Xe.shift();Mt.length=0}async function Td(){if(Xe.length===0)return null;let t=Xe.pop();if(t.oldContent===null)try{await to.unlink(t.filePath)}catch{}else await to.writeFile(t.filePath,t.oldContent,"utf-8");return Mt.push(t),{tool:t.tool,filePath:t.filePath,wasCreated:t.oldContent===null}}async function Cd(){if(Mt.length===0)return null;let t=Mt.pop();return await to.writeFile(t.filePath,t.newContent,"utf-8"),Xe.push(t),{tool:t.tool,filePath:t.filePath}}function Rd(t=10){return Xe.slice(-t).reverse().map(e=>({tool:e.tool,filePath:e.filePath,timestamp:e.timestamp}))}function Ad(){return Xe.length}function Od(){return Mt.length}function Nd(){Xe.length=0,Mt.length=0}ji.exports={recordChange:Ed,undo:Td,redo:Cd,getHistory:Rd,getUndoCount:Ad,getRedoCount:Od,clearHistory:Nd}});var en=L((_$,Hi)=>{var Te=require("fs"),Lt=require("path"),_e=[];function no(){return Lt.join(process.cwd(),".nex","skills")}function Di(){return Lt.join(process.cwd(),".nex","config.json")}function Md(){let t=no();return Te.existsSync(t)||Te.mkdirSync(t,{recursive:!0}),t}function so(){let t=Di();if(!Te.existsSync(t))return[];try{let e=JSON.parse(Te.readFileSync(t,"utf-8"));return e.skills&&Array.isArray(e.skills.disabled)?e.skills.disabled:[]}catch{return[]}}function Fi(t){let e=Di(),o={};if(Te.existsSync(e))try{o=JSON.parse(Te.readFileSync(e,"utf-8"))}catch{o={}}o.skills||(o.skills={}),o.skills.disabled=t;let n=Lt.dirname(e);Te.existsSync(n)||Te.mkdirSync(n,{recursive:!0}),Te.writeFileSync(e,JSON.stringify(o,null,2),"utf-8")}function Ui(t,e){let o=[];if(typeof t!="object"||t===null)return{valid:!1,errors:["Module must export an object"]};if(t.name!==void 0&&typeof t.name!="string"&&o.push("name must be a string"),t.description!==void 0&&typeof t.description!="string"&&o.push("description must be a string"),t.instructions!==void 0&&typeof t.instructions!="string"&&o.push("instructions must be a string"),t.commands!==void 0)if(!Array.isArray(t.commands))o.push("commands must be an array");else for(let n=0;n<t.commands.length;n++){let s=t.commands[n];(!s.cmd||typeof s.cmd!="string")&&o.push(`commands[${n}].cmd must be a non-empty string`),s.handler!==void 0&&typeof s.handler!="function"&&o.push(`commands[${n}].handler must be a function`)}if(t.tools!==void 0)if(!Array.isArray(t.tools))o.push("tools must be an array");else for(let n=0;n<t.tools.length;n++){let s=t.tools[n];(!s.function||!s.function.name||typeof s.function.name!="string")&&o.push(`tools[${n}].function.name must be a non-empty string`),s.execute!==void 0&&typeof s.execute!="function"&&o.push(`tools[${n}].execute must be a function`)}return{valid:o.length===0,errors:o}}function Wi(t){try{let e=Te.readFileSync(t,"utf-8").trim();return e?{name:Lt.basename(t,".md"),type:"prompt",filePath:t,instructions:e,commands:[],tools:[]}:null}catch{return null}}function Bi(t){try{let e=require(t),{valid:o,errors:n}=Ui(e,t);return o?{name:e.name||Lt.basename(t,".js"),type:"script",filePath:t,description:e.description||"",instructions:e.instructions||"",commands:(e.commands||[]).map(i=>({cmd:i.cmd.startsWith("/")?i.cmd:`/${i.cmd}`,desc:i.desc||i.description||"",handler:i.handler||null})),tools:(e.tools||[]).map(i=>({type:i.type||"function",function:{name:i.function.name,description:i.function.description||"",parameters:i.function.parameters||{type:"object",properties:{}}},execute:i.execute||null}))}:(console.error(`Skill validation failed: ${t}
103
103
  ${n.join(`
104
- `)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function Pd(){_e=[];let t=to();if(!Te.existsSync(t))return _e;let e=no(),s;try{s=Te.readdirSync(t)}catch{return _e}for(let n of s){let o=Lt.join(t,n),i;try{i=Te.statSync(o)}catch{continue}if(!i.isFile())continue;let r=null;n.endsWith(".md")?r=Ui(o):n.endsWith(".js")&&(r=Wi(o)),r&&(r.enabled=!e.includes(r.name),_e.push(r))}return _e}function Ld(){let t=[];for(let e of _e)!e.enabled||!e.instructions||t.push(`[Skill: ${e.name}]
104
+ `)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function Pd(){_e=[];let t=no();if(!Te.existsSync(t))return _e;let e=so(),o;try{o=Te.readdirSync(t)}catch{return _e}for(let n of o){let s=Lt.join(t,n),i;try{i=Te.statSync(s)}catch{continue}if(!i.isFile())continue;let r=null;n.endsWith(".md")?r=Wi(s):n.endsWith(".js")&&(r=Bi(s)),r&&(r.enabled=!e.includes(r.name),_e.push(r))}return _e}function Ld(){let t=[];for(let e of _e)!e.enabled||!e.instructions||t.push(`[Skill: ${e.name}]
105
105
  ${e.instructions}`);return t.length===0?"":`SKILL INSTRUCTIONS:
106
106
  ${t.join(`
107
107
 
108
- `)}`}function Id(){let t=[];for(let e of _e)if(e.enabled)for(let s of e.commands)t.push({cmd:s.cmd,desc:s.desc||`[skill: ${e.name}]`});return t}function qd(){let t=[];for(let e of _e)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 jd(t,e){if(!t.startsWith("skill_"))return null;let s=t.substring(6);for(let n of _e)if(n.enabled){for(let o of n.tools)if(o.function.name===s&&o.execute)try{let i=await o.execute(e);return typeof i=="string"?i:JSON.stringify(i)}catch(i){return`ERROR: Skill tool '${s}' failed: ${i.message}`}}return`ERROR: Skill tool '${s}' not found`}function Dd(t){let[e,...s]=t.split(/\s+/),n=s.join(" ").trim();for(let o of _e)if(o.enabled){for(let i of o.commands)if(i.cmd===e&&i.handler){try{i.handler(n)}catch(r){console.error(`Skill command error (${e}): ${r.message}`)}return!0}}return!1}function Fd(){return _e.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 Ud(t){let e=_e.find(n=>n.name===t);if(!e)return!1;e.enabled=!0;let s=no().filter(n=>n!==t);return Di(s),!0}function Wd(t){let e=_e.find(n=>n.name===t);if(!e)return!1;e.enabled=!1;let s=no();return s.includes(t)||(s.push(t),Di(s)),!0}function Bd(){return _e}Bi.exports={initSkillsDir:Md,loadAllSkills:Pd,getSkillInstructions:Ld,getSkillCommands:Id,getSkillToolDefinitions:qd,routeSkillCall:jd,handleSkillCommand:Dd,listSkills:Fd,enableSkill:Ud,disableSkill:Wd,getLoadedSkills:Bd,_getSkillsDir:to,_validateScriptSkill:Fi,_loadMarkdownSkill:Ui,_loadScriptSkill:Wi}});var zn=L((_$,Ji)=>{var{spawn:Hd}=require("child_process"),Gd=require("path"),Hi=require("fs"),Ve=new Map;function zd(){return Gd.join(process.cwd(),".nex","config.json")}function so(){let t=zd();if(!Hi.existsSync(t))return{};try{return JSON.parse(Hi.readFileSync(t,"utf-8")).mcpServers||{}}catch{return{}}}function Gn(t,e,s={},n=1e4){return new Promise((o,i)=>{let r=`${Date.now()}-${Math.random().toString(36).slice(2,6)}`,c=JSON.stringify({jsonrpc:"2.0",id:r,method:e,params:s})+`
108
+ `)}`}function Id(){let t=[];for(let e of _e)if(e.enabled)for(let o of e.commands)t.push({cmd:o.cmd,desc:o.desc||`[skill: ${e.name}]`});return t}function qd(){let t=[];for(let e of _e)if(e.enabled)for(let o of e.tools)t.push({type:"function",function:{name:`skill_${o.function.name}`,description:`[Skill:${e.name}] ${o.function.description}`,parameters:o.function.parameters}});return t}async function jd(t,e){if(!t.startsWith("skill_"))return null;let o=t.substring(6);for(let n of _e)if(n.enabled){for(let s of n.tools)if(s.function.name===o&&s.execute)try{let i=await s.execute(e);return typeof i=="string"?i:JSON.stringify(i)}catch(i){return`ERROR: Skill tool '${o}' failed: ${i.message}`}}return`ERROR: Skill tool '${o}' not found`}function Dd(t){let[e,...o]=t.split(/\s+/),n=o.join(" ").trim();for(let s of _e)if(s.enabled){for(let i of s.commands)if(i.cmd===e&&i.handler){try{i.handler(n)}catch(r){console.error(`Skill command error (${e}): ${r.message}`)}return!0}}return!1}function Fd(){return _e.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 Ud(t){let e=_e.find(n=>n.name===t);if(!e)return!1;e.enabled=!0;let o=so().filter(n=>n!==t);return Fi(o),!0}function Wd(t){let e=_e.find(n=>n.name===t);if(!e)return!1;e.enabled=!1;let o=so();return o.includes(t)||(o.push(t),Fi(o)),!0}function Bd(){return _e}Hi.exports={initSkillsDir:Md,loadAllSkills:Pd,getSkillInstructions:Ld,getSkillCommands:Id,getSkillToolDefinitions:qd,routeSkillCall:jd,handleSkillCommand:Dd,listSkills:Fd,enableSkill:Ud,disableSkill:Wd,getLoadedSkills:Bd,_getSkillsDir:no,_validateScriptSkill:Ui,_loadMarkdownSkill:Wi,_loadScriptSkill:Bi}});var zn=L((k$,Xi)=>{var{spawn:Hd}=require("child_process"),Gd=require("path"),Gi=require("fs"),Ve=new Map;function zd(){return Gd.join(process.cwd(),".nex","config.json")}function oo(){let t=zd();if(!Gi.existsSync(t))return{};try{return JSON.parse(Gi.readFileSync(t,"utf-8")).mcpServers||{}}catch{return{}}}function Gn(t,e,o={},n=1e4){return new Promise((s,i)=>{let r=`${Date.now()}-${Math.random().toString(36).slice(2,6)}`,c=JSON.stringify({jsonrpc:"2.0",id:r,method:e,params:o})+`
109
109
  `,l="",u=setTimeout(()=>{f(),i(new Error(`MCP request timeout: ${e}`))},n);function d(m){l+=m.toString();let h=l.split(`
110
- `);for(let p of h)if(p.trim())try{let g=JSON.parse(p);if(g.id===r){f(),g.error?i(new Error(`MCP error: ${g.error.message||JSON.stringify(g.error)}`)):o(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(),i(new Error(`MCP write failed: ${m.message}`))}})}async function Gi(t,e){if(Ve.has(t))return Ve.get(t);let s=["PATH","HOME","USER","SHELL","LANG","TERM","NODE_ENV"],n={};for(let r of s)process.env[r]&&(n[r]=process.env[r]);let o=Hd(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:{...n,...e.env||{}}}),i={name:t,proc:o,tools:[],config:e};try{await Gn(o,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.2.0"}});let r=await Gn(o,"tools/list",{});return i.tools=r&&r.tools||[],Ve.set(t,i),i}catch(r){throw o.kill(),new Error(`Failed to connect MCP server '${t}': ${r.message}`)}}function zi(t){let e=Ve.get(t);if(!e)return!1;try{e.proc.kill()}catch{}return Ve.delete(t),!0}function Kd(){for(let[t]of Ve)zi(t)}async function Ki(t,e,s={}){let n=Ve.get(t);if(!n)throw new Error(`MCP server not connected: ${t}`);let o=await Gn(n.proc,"tools/call",{name:e,arguments:s});return o&&Array.isArray(o.content)?o.content.filter(i=>i.type==="text").map(i=>i.text).join(`
111
- `):JSON.stringify(o)}function Yi(){let t=[];for(let[e,s]of Ve)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 Yd(){return Yi().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function Jd(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 Ki(n,o,e)}function Xd(){let t=so();return Object.entries(t).map(([e,s])=>{let n=Ve.get(e);return{name:e,command:s.command,connected:!!n,toolCount:n?n.tools.length:0}})}async function Vd(){let t=so(),e=[];for(let[s,n]of Object.entries(t))try{let o=await Gi(s,n);e.push({name:s,tools:o.tools.length})}catch(o){e.push({name:s,tools:0,error:o.message})}return e}Ji.exports={loadMCPConfig:so,sendRequest:Gn,connectServer:Gi,disconnectServer:zi,disconnectAll:Kd,callTool:Ki,getAllTools:Yi,getMCPToolDefinitions:Yd,routeMCPCall:Jd,listServers:Xd,connectAll:Vd}});var oo=L((k$,Zi)=>{var{getSkillToolDefinitions:Qd}=en(),{getMCPToolDefinitions:Zd}=zn(),Kn=new Map;function Xi(){let{TOOL_DEFINITIONS:t}=Ue();return[...t,...Qd(),...Zd()]}function Vi(t){if(Kn.has(t))return Kn.get(t);let s=Xi().find(o=>o.function.name===t);if(!s)return null;let n=s.function.parameters;return Kn.set(t,n),n}function ef(){Kn.clear()}function Yn(t,e){if(!t||e.length===0)return null;let s=null,n=1/0;for(let o of e){let i=Qi(t.toLowerCase(),o.toLowerCase());i<n&&(n=i,s=o)}return n<=Math.ceil(t.length/2)?s:null}function Qi(t,e){let s=t.length,n=e.length,o=Array.from({length:s+1},()=>Array(n+1).fill(0));for(let i=0;i<=s;i++)o[i][0]=i;for(let i=0;i<=n;i++)o[0][i]=i;for(let i=1;i<=s;i++)for(let r=1;r<=n;r++)o[i][r]=t[i-1]===e[r-1]?o[i-1][r-1]:1+Math.min(o[i-1][r],o[i][r-1],o[i-1][r-1]);return o[s][n]}function tf(t,e){let s=Vi(t);if(s===null){let d=Xi().map(m=>m.function.name),f=Yn(t,d);return{valid:!1,error:`Unknown tool "${t}".${f?` Did you mean "${f}"?`:""}
112
- Available tools: ${d.join(", ")}`}}if(!s||!s.properties)return{valid:!0};let n=s.required||[],o=Object.keys(s.properties),i=Object.keys(e),r=[],c={...e},l=!1;for(let u of n)if(!(u in e)||e[u]===void 0||e[u]===null){let d=Yn(u,i);d&&!o.includes(d)?(c[u]=e[d],delete c[d],l=!0):r.push(`Missing required parameter "${u}" (${s.properties[u]?.description||s.properties[u]?.type||"unknown"})`)}for(let u of i)if(!o.includes(u)){let d=Yn(u,o);d&&!(d in c)?(c[d]=e[u],delete c[u],l=!0):l||r.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 r.length>0&&!l?{valid:!1,error:`Tool "${t}" argument errors:
110
+ `);for(let p of h)if(p.trim())try{let g=JSON.parse(p);if(g.id===r){f(),g.error?i(new Error(`MCP error: ${g.error.message||JSON.stringify(g.error)}`)):s(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(),i(new Error(`MCP write failed: ${m.message}`))}})}async function zi(t,e){if(Ve.has(t))return Ve.get(t);let o=["PATH","HOME","USER","SHELL","LANG","TERM","NODE_ENV"],n={};for(let r of o)process.env[r]&&(n[r]=process.env[r]);let s=Hd(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:{...n,...e.env||{}}}),i={name:t,proc:s,tools:[],config:e};try{await Gn(s,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.2.0"}});let r=await Gn(s,"tools/list",{});return i.tools=r&&r.tools||[],Ve.set(t,i),i}catch(r){throw s.kill(),new Error(`Failed to connect MCP server '${t}': ${r.message}`)}}function Ki(t){let e=Ve.get(t);if(!e)return!1;try{e.proc.kill()}catch{}return Ve.delete(t),!0}function Kd(){for(let[t]of Ve)Ki(t)}async function Yi(t,e,o={}){let n=Ve.get(t);if(!n)throw new Error(`MCP server not connected: ${t}`);let s=await Gn(n.proc,"tools/call",{name:e,arguments:o});return s&&Array.isArray(s.content)?s.content.filter(i=>i.type==="text").map(i=>i.text).join(`
111
+ `):JSON.stringify(s)}function Ji(){let t=[];for(let[e,o]of Ve)for(let n of o.tools)t.push({server:e,name:n.name,description:n.description||"",inputSchema:n.inputSchema||{type:"object",properties:{}}});return t}function Yd(){return Ji().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function Jd(t,e){if(!t.startsWith("mcp_"))return null;let o=t.substring(4).split("_");if(o.length<2)return null;let n=o[0],s=o.slice(1).join("_");return Yi(n,s,e)}function Xd(){let t=oo();return Object.entries(t).map(([e,o])=>{let n=Ve.get(e);return{name:e,command:o.command,connected:!!n,toolCount:n?n.tools.length:0}})}async function Vd(){let t=oo(),e=[];for(let[o,n]of Object.entries(t))try{let s=await zi(o,n);e.push({name:o,tools:s.tools.length})}catch(s){e.push({name:o,tools:0,error:s.message})}return e}Xi.exports={loadMCPConfig:oo,sendRequest:Gn,connectServer:zi,disconnectServer:Ki,disconnectAll:Kd,callTool:Yi,getAllTools:Ji,getMCPToolDefinitions:Yd,routeMCPCall:Jd,listServers:Xd,connectAll:Vd}});var ro=L((v$,ea)=>{var{getSkillToolDefinitions:Qd}=en(),{getMCPToolDefinitions:Zd}=zn(),Kn=new Map;function Vi(){let{TOOL_DEFINITIONS:t}=Ue();return[...t,...Qd(),...Zd()]}function Qi(t){if(Kn.has(t))return Kn.get(t);let o=Vi().find(s=>s.function.name===t);if(!o)return null;let n=o.function.parameters;return Kn.set(t,n),n}function ef(){Kn.clear()}function Yn(t,e){if(!t||e.length===0)return null;let o=null,n=1/0;for(let s of e){let i=Zi(t.toLowerCase(),s.toLowerCase());i<n&&(n=i,o=s)}return n<=Math.ceil(t.length/2)?o:null}function Zi(t,e){let o=t.length,n=e.length,s=Array.from({length:o+1},()=>Array(n+1).fill(0));for(let i=0;i<=o;i++)s[i][0]=i;for(let i=0;i<=n;i++)s[0][i]=i;for(let i=1;i<=o;i++)for(let r=1;r<=n;r++)s[i][r]=t[i-1]===e[r-1]?s[i-1][r-1]:1+Math.min(s[i-1][r],s[i][r-1],s[i-1][r-1]);return s[o][n]}function tf(t,e){let o=Qi(t);if(o===null){let d=Vi().map(m=>m.function.name),f=Yn(t,d);return{valid:!1,error:`Unknown tool "${t}".${f?` Did you mean "${f}"?`:""}
112
+ Available tools: ${d.join(", ")}`}}if(!o||!o.properties)return{valid:!0};let n=o.required||[],s=Object.keys(o.properties),i=Object.keys(e),r=[],c={...e},l=!1;for(let u of n)if(!(u in e)||e[u]===void 0||e[u]===null){let d=Yn(u,i);d&&!s.includes(d)?(c[u]=e[d],delete c[d],l=!0):r.push(`Missing required parameter "${u}" (${o.properties[u]?.description||o.properties[u]?.type||"unknown"})`)}for(let u of i)if(!s.includes(u)){let d=Yn(u,s);d&&!(d in c)?(c[d]=e[u],delete c[u],l=!0):l||r.push(`Unknown parameter "${u}".${d?` Did you mean "${d}"?`:""}`)}for(let u of Object.keys(c)){if(!o.properties[u])continue;let d=o.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 r.length>0&&!l?{valid:!1,error:`Tool "${t}" argument errors:
113
113
  `+r.map(u=>` - ${u}`).join(`
114
114
  `)+`
115
115
 
116
- Expected parameters: ${JSON.stringify(s.properties,null,2)}`}:{valid:!0,corrected:l?c:null}}Zi.exports={validateToolArgs:tf,closestMatch:Yn,levenshtein:Qi,getCachedSchema:Vi,clearSchemaCache:ef}});var sa=L((v$,na)=>{var{levenshtein:Jn}=oo(),nf=200,sf=.3,of=2;function ro(t){return t.replace(/\r\n/g,`
116
+ Expected parameters: ${JSON.stringify(o.properties,null,2)}`}:{valid:!0,corrected:l?c:null}}ea.exports={validateToolArgs:tf,closestMatch:Yn,levenshtein:Zi,getCachedSchema:Qi,clearSchemaCache:ef}});var oa=L((S$,sa)=>{var{levenshtein:Jn}=ro(),nf=200,sf=.3,of=2;function io(t){return t.replace(/\r\n/g,`
117
117
  `).replace(/\r/g,`
118
118
  `).replace(/\t/g," ".repeat(of)).split(`
119
- `).map(e=>{let s=e.replace(/\s+$/,""),n=s.match(/^(\s*)(.*)/);if(!n)return s;let[,o,i]=n;return o+i.replace(/ {2,}/g," ")}).join(`
120
- `)}function rf(t,e){if(t.includes(e))return e;let s=ro(t),n=ro(e);if(!s.includes(n))return null;let o=t.split(`
121
- `),i=s.split(`
119
+ `).map(e=>{let o=e.replace(/\s+$/,""),n=o.match(/^(\s*)(.*)/);if(!n)return o;let[,s,i]=n;return s+i.replace(/ {2,}/g," ")}).join(`
120
+ `)}function rf(t,e){if(t.includes(e))return e;let o=io(t),n=io(e);if(!o.includes(n))return null;let s=t.split(`
121
+ `),i=o.split(`
122
122
  `),r=n.split(`
123
- `),c=r[0],l=r[r.length-1];for(let u=0;u<=i.length-r.length;u++){let d=!0;for(let f=0;f<r.length;f++)if(i[u+f]!==r[f]){d=!1;break}if(d)return o.slice(u,u+r.length).join(`
124
- `)}if(r.length===1){for(let u=0;u<i.length;u++)if(i[u].indexOf(n)!==-1)return o[u]}return null}function af(t,e){if(!t||!e)return null;let s=t.split(`
125
- `),o=e.split(`
126
- `).length;return s.length===0||o===0?null:o===1?cf(s,e):uf(s,e,o)}function ea(t){return Math.max(1,Math.floor(t/nf))}function ta(t,e){return t<=Math.ceil(e*sf)}function cf(t,e){let s=e.trim(),n=ea(t.length),o=null,i=1/0;for(let r=0;r<t.length;r+=n){let c=t[r];if(!c.trim())continue;let l=Jn(c.trim(),s);l<i&&(i=l,o={text:c,distance:l,line:r+1})}return o&&n>1&&(o=lf(t,s,o,n)||o,i=o.distance),ta(i,e.length)?o:null}function lf(t,e,s,n){let o=s.line-1,i=Math.max(0,o-n),r=Math.min(t.length-1,o+n),c=s.distance,l=null;for(let u=i;u<=r;u++){let d=t[u];if(!d.trim())continue;let f=Jn(d.trim(),e);f<c&&(c=f,l={text:d,distance:f,line:u+1})}return l}function uf(t,e,s){let n=t.length-s+1;if(n<=0)return null;let o=ea(n),i=null,r=1/0;for(let c=0;c<n;c+=o){let l=t.slice(c,c+s).join(`
127
- `),u=Jn(l,e);u<r&&(r=u,i={text:l,distance:u,line:c+1})}return i&&o>1&&(i=df(t,e,i,o,s,n)||i,r=i.distance),ta(r,e.length)?i:null}function df(t,e,s,n,o,i){let r=s.line-1,c=Math.max(0,r-n),l=Math.min(i-1,r+n),u=s.distance,d=null;for(let f=c;f<=l;f++){let m=t.slice(f,f+o).join(`
128
- `),h=Jn(m,e);h<u&&(u=h,d={text:m,distance:h,line:f+1})}return d}na.exports={normalizeWhitespace:ro,fuzzyFindText:rf,findMostSimilar:af}});var ra=L((E$,oa)=>{var{C:S$}=ce(),ff=[{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}],mf=[{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 pf(t,e){let s=e.split(`
129
- `),n=[],o=t?`.${t.split(".").pop()}`:"";for(let i=0;i<s.length;i++){let r=s[i],c=i+1;for(let l of ff)l.regex.test(r)&&n.push({line:c,message:`Potential secret detected: ${l.name}`,severity:"error"});for(let l of mf)l.ext&&!l.ext.includes(o)||l.regex.test(r)&&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}oa.exports={runDiagnostics:pf}});var co=L((T$,ca)=>{var hf=require("fs").promises,ia=require("path"),{exec:gf}=require("util").promisify(require("child_process").exec),It=[],ao=null,Xn=!1,io=0,$f=6e4;function aa(t){return!(It.length===0||ao!==t||Date.now()-io>$f)}async function yf(t){if(!Xn&&!aa(t)){Xn=!0,ao=t;try{try{let{stdout:n}=await gf("rg --files",{cwd:t,timeout:5e3});It=n.split(`
130
- `).filter(Boolean),io=Date.now(),Xn=!1;return}catch{}let e=[],s=async(n,o)=>{let i;try{i=await hf.readdir(n,{withFileTypes:!0})}catch{return}for(let r of i){if(r.name==="node_modules"||r.name===".git"||r.name.startsWith("."))continue;let c=o?`${o}/${r.name}`:r.name;r.isDirectory()?await s(ia.join(n,r.name),c):e.push(c)}};await s(t,""),It=e,io=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{Xn=!1}}}function wf(){return It}function bf(){return ao}function xf(t){return It.filter(e=>ia.basename(e)===t)}function _f(t){let e=t.toLowerCase();return It.filter(s=>s.toLowerCase().includes(e)).slice(0,20)}ca.exports={refreshIndex:yf,getFileIndex:wf,getIndexedCwd:bf,findFileInIndex:xf,searchIndex:_f,isIndexValid:aa}});var qt=L((C$,fa)=>{var Vn=require("fs"),Zn=require("path"),lo=require("os"),{execFile:kf}=require("child_process"),{promisify:vf}=require("util"),uo=vf(kf),Sf=Zn.join(".nex","servers.json"),Qn=Zn.join(lo.tmpdir(),"nex-ssh-sockets");function Ef(){return Zn.join(process.cwd(),Sf)}function la(){let t=Ef();if(!Vn.existsSync(t))return{};try{return JSON.parse(Vn.readFileSync(t,"utf-8"))}catch{return{}}}function Tf(t){let e=la();if(e[t])return{...e[t],_name:t};if(/^[\w.-]+@[\w.-]+$/.test(t)||/[\w-]+\.[\w.-]+/.test(t)||t==="localhost"){let[o,i]=t.includes("@")?t.split("@"):[void 0,t];return{host:i,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 Cf(){Vn.existsSync(Qn)||Vn.mkdirSync(Qn,{recursive:!0})}function ua(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-o","ServerAliveInterval=30"];t.key&&e.push("-i",t.key.replace(/^~/,lo.homedir())),t.port&&Number(t.port)!==22&&e.push("-p",String(t.port)),Cf();let s=t.user?`${t.user}@${t.host}`:t.host,n=Zn.join(Qn,s.replace(/[@.:]/g,"_"));return e.push("-o","ControlMaster=auto","-o",`ControlPath=${n}`,"-o","ControlPersist=120"),e.push(s),{args:e,target:s}}function da(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-r"];return t.key&&e.push("-i",t.key.replace(/^~/,lo.homedir())),t.port&&Number(t.port)!==22&&e.push("-P",String(t.port)),e}async function Rf(t,e,{timeout:s=3e4,sudo:n=!1}={}){let{args:o}=ua(t),i=n&&t.sudo?`sudo sh -c ${JSON.stringify(e)}`:e;try{let{stdout:r,stderr:c}=await uo("ssh",[...o,i],{timeout:s,maxBuffer:4194304});return{stdout:r||"",stderr:c||"",exitCode:0}}catch(r){let c=typeof r.code=="number"?r.code:1,l=(r.stderr||r.message||"").toString();return{stdout:(r.stdout||"").toString(),stderr:l,exitCode:c,error:es(l,t)}}}async function Af(t,e,s,{timeout:n=12e4}={}){let o=da(t),i=t.user?`${t.user}@${t.host}`:t.host;o.push(e,`${i}:${s}`);try{let{stdout:r,stderr:c}=await uo("scp",o,{timeout:n,maxBuffer:1048576});return r||c||`Uploaded ${e} \u2192 ${i}:${s}`}catch(r){let c=(r.stderr||r.message||"").toString();throw new Error(es(c,t)||c)}}async function Of(t,e,s,{timeout:n=12e4}={}){let o=da(t),i=t.user?`${t.user}@${t.host}`:t.host;o.push(`${i}:${e}`,s);try{let{stdout:r,stderr:c}=await uo("scp",o,{timeout:n,maxBuffer:1048576});return r||c||`Downloaded ${i}:${e} \u2192 ${s}`}catch(r){let c=(r.stderr||r.message||"").toString();throw new Error(es(c,t)||c)}}function es(t,e){if(!t)return"";if(/connection refused/i.test(t)){let s=e.port||22;return`${t}
131
- 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}
132
- 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}
123
+ `),c=r[0],l=r[r.length-1];for(let u=0;u<=i.length-r.length;u++){let d=!0;for(let f=0;f<r.length;f++)if(i[u+f]!==r[f]){d=!1;break}if(d)return s.slice(u,u+r.length).join(`
124
+ `)}if(r.length===1){for(let u=0;u<i.length;u++)if(i[u].indexOf(n)!==-1)return s[u]}return null}function af(t,e){if(!t||!e)return null;let o=t.split(`
125
+ `),s=e.split(`
126
+ `).length;return o.length===0||s===0?null:s===1?cf(o,e):uf(o,e,s)}function ta(t){return Math.max(1,Math.floor(t/nf))}function na(t,e){return t<=Math.ceil(e*sf)}function cf(t,e){let o=e.trim(),n=ta(t.length),s=null,i=1/0;for(let r=0;r<t.length;r+=n){let c=t[r];if(!c.trim())continue;let l=Jn(c.trim(),o);l<i&&(i=l,s={text:c,distance:l,line:r+1})}return s&&n>1&&(s=lf(t,o,s,n)||s,i=s.distance),na(i,e.length)?s:null}function lf(t,e,o,n){let s=o.line-1,i=Math.max(0,s-n),r=Math.min(t.length-1,s+n),c=o.distance,l=null;for(let u=i;u<=r;u++){let d=t[u];if(!d.trim())continue;let f=Jn(d.trim(),e);f<c&&(c=f,l={text:d,distance:f,line:u+1})}return l}function uf(t,e,o){let n=t.length-o+1;if(n<=0)return null;let s=ta(n),i=null,r=1/0;for(let c=0;c<n;c+=s){let l=t.slice(c,c+o).join(`
127
+ `),u=Jn(l,e);u<r&&(r=u,i={text:l,distance:u,line:c+1})}return i&&s>1&&(i=df(t,e,i,s,o,n)||i,r=i.distance),na(r,e.length)?i:null}function df(t,e,o,n,s,i){let r=o.line-1,c=Math.max(0,r-n),l=Math.min(i-1,r+n),u=o.distance,d=null;for(let f=c;f<=l;f++){let m=t.slice(f,f+s).join(`
128
+ `),h=Jn(m,e);h<u&&(u=h,d={text:m,distance:h,line:f+1})}return d}sa.exports={normalizeWhitespace:io,fuzzyFindText:rf,findMostSimilar:af}});var ia=L((T$,ra)=>{var{C:E$}=ce(),ff=[{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}],mf=[{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 pf(t,e){let o=e.split(`
129
+ `),n=[],s=t?`.${t.split(".").pop()}`:"";for(let i=0;i<o.length;i++){let r=o[i],c=i+1;for(let l of ff)l.regex.test(r)&&n.push({line:c,message:`Potential secret detected: ${l.name}`,severity:"error"});for(let l of mf)l.ext&&!l.ext.includes(s)||l.regex.test(r)&&n.push({line:c,message:l.message||`Found ${l.name}`,severity:l.severity||"warn"})}return o.length>500&&n.push({line:0,message:`Large file detected (${o.length} lines). Consider refactoring.`,severity:"info"}),n}ra.exports={runDiagnostics:pf}});var lo=L((C$,la)=>{var hf=require("fs").promises,aa=require("path"),{exec:gf}=require("util").promisify(require("child_process").exec),It=[],co=null,Xn=!1,ao=0,$f=6e4;function ca(t){return!(It.length===0||co!==t||Date.now()-ao>$f)}async function yf(t){if(!Xn&&!ca(t)){Xn=!0,co=t;try{try{let{stdout:n}=await gf("rg --files",{cwd:t,timeout:5e3});It=n.split(`
130
+ `).filter(Boolean),ao=Date.now(),Xn=!1;return}catch{}let e=[],o=async(n,s)=>{let i;try{i=await hf.readdir(n,{withFileTypes:!0})}catch{return}for(let r of i){if(r.name==="node_modules"||r.name===".git"||r.name.startsWith("."))continue;let c=s?`${s}/${r.name}`:r.name;r.isDirectory()?await o(aa.join(n,r.name),c):e.push(c)}};await o(t,""),It=e,ao=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{Xn=!1}}}function wf(){return It}function bf(){return co}function xf(t){return It.filter(e=>aa.basename(e)===t)}function _f(t){let e=t.toLowerCase();return It.filter(o=>o.toLowerCase().includes(e)).slice(0,20)}la.exports={refreshIndex:yf,getFileIndex:wf,getIndexedCwd:bf,findFileInIndex:xf,searchIndex:_f,isIndexValid:ca}});var qt=L((R$,ma)=>{var Vn=require("fs"),Zn=require("path"),uo=require("os"),{execFile:kf}=require("child_process"),{promisify:vf}=require("util"),fo=vf(kf),Sf=Zn.join(".nex","servers.json"),Qn=Zn.join(uo.tmpdir(),"nex-ssh-sockets");function Ef(){return Zn.join(process.cwd(),Sf)}function ua(){let t=Ef();if(!Vn.existsSync(t))return{};try{return JSON.parse(Vn.readFileSync(t,"utf-8"))}catch{return{}}}function Tf(t){let e=ua();if(e[t])return{...e[t],_name:t};if(/^[\w.-]+@[\w.-]+$/.test(t)||/[\w-]+\.[\w.-]+/.test(t)||t==="localhost"){let[s,i]=t.includes("@")?t.split("@"):[void 0,t];return{host:i,user:s}}let o=Object.keys(e),n=o.length?`Available profiles: ${o.join(", ")}`:"No profiles configured. Create .nex/servers.json";throw new Error(`Unknown server: "${t}". ${n}`)}function Cf(){Vn.existsSync(Qn)||Vn.mkdirSync(Qn,{recursive:!0})}function da(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-o","ServerAliveInterval=30"];t.key&&e.push("-i",t.key.replace(/^~/,uo.homedir())),t.port&&Number(t.port)!==22&&e.push("-p",String(t.port)),Cf();let o=t.user?`${t.user}@${t.host}`:t.host,n=Zn.join(Qn,o.replace(/[@.:]/g,"_"));return e.push("-o","ControlMaster=auto","-o",`ControlPath=${n}`,"-o","ControlPersist=120"),e.push(o),{args:e,target:o}}function fa(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-r"];return t.key&&e.push("-i",t.key.replace(/^~/,uo.homedir())),t.port&&Number(t.port)!==22&&e.push("-P",String(t.port)),e}async function Rf(t,e,{timeout:o=3e4,sudo:n=!1}={}){let{args:s}=da(t),i=n&&t.sudo?`sudo sh -c ${JSON.stringify(e)}`:e;try{let{stdout:r,stderr:c}=await fo("ssh",[...s,i],{timeout:o,maxBuffer:4194304});return{stdout:r||"",stderr:c||"",exitCode:0}}catch(r){let c=typeof r.code=="number"?r.code:1,l=(r.stderr||r.message||"").toString();return{stdout:(r.stdout||"").toString(),stderr:l,exitCode:c,error:es(l,t)}}}async function Af(t,e,o,{timeout:n=12e4}={}){let s=fa(t),i=t.user?`${t.user}@${t.host}`:t.host;s.push(e,`${i}:${o}`);try{let{stdout:r,stderr:c}=await fo("scp",s,{timeout:n,maxBuffer:1048576});return r||c||`Uploaded ${e} \u2192 ${i}:${o}`}catch(r){let c=(r.stderr||r.message||"").toString();throw new Error(es(c,t)||c)}}async function Of(t,e,o,{timeout:n=12e4}={}){let s=fa(t),i=t.user?`${t.user}@${t.host}`:t.host;s.push(`${i}:${e}`,o);try{let{stdout:r,stderr:c}=await fo("scp",s,{timeout:n,maxBuffer:1048576});return r||c||`Downloaded ${i}:${e} \u2192 ${o}`}catch(r){let c=(r.stderr||r.message||"").toString();throw new Error(es(c,t)||c)}}function es(t,e){if(!t)return"";if(/connection refused/i.test(t)){let o=e.port||22;return`${t}
131
+ HINT: Connection refused on ${e.host}:${o}. Check: server is running, SSH service is active (systemctl status sshd), firewall allows port ${o} (firewall-cmd --list-ports).`}if(/permission denied/i.test(t)){let o=e.key?`key: ${e.key}`:"SSH agent";return`${t}
132
+ HINT: Auth failed using ${o} 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}
133
133
  HINT: Cannot reach ${e.host}. Check: network connection, correct hostname/IP, DNS resolution.`:/host key verification failed/i.test(t)?`${t}
134
134
  HINT: Host key changed for ${e.host}. To reset: ssh-keygen -R ${e.host}`:/timed out/i.test(t)?`${t}
135
135
  HINT: Connection timed out to ${e.host}. Check firewall rules and network connectivity.`:/too many authentication failures/i.test(t)?`${t}
136
- HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function Nf(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}]`:"",i=e.key?` key:${e.key}`:"",r=e.sudo?" sudo:yes":"";return`${t}: ${s}${n}${o}${i}${r}`}fa.exports={loadServerProfiles:la,resolveProfile:Tf,buildSSHArgs:ua,sshExec:Rf,scpUpload:Af,scpDownload:Of,enrichSSHError:es,formatProfile:Nf,SSH_SOCKET_DIR:Qn}});var po=L((R$,pa)=>{var tn=require("fs"),fo=require("path"),Mf=fo.join(".nex","deploy.json");function mo(){return fo.join(process.cwd(),Mf)}function ma(){let t=mo();if(!tn.existsSync(t))return{};try{return JSON.parse(tn.readFileSync(t,"utf-8"))}catch{return{}}}function Pf(t){let e=ma();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 Lf(t){let e=fo.join(process.cwd(),".nex");tn.existsSync(e)||tn.mkdirSync(e,{recursive:!0}),tn.writeFileSync(mo(),JSON.stringify(t,null,2)+`
137
- `,"utf-8")}pa.exports={loadDeployConfigs:ma,resolveDeployConfig:Pf,saveDeployConfigs:Lf,getDeployConfigPath:mo}});var sn=L((A$,$a)=>{var ho=null,Qe=null,nn=null,ha=`Playwright is not installed. Install with:
136
+ HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function Nf(t,e){let o=e.user?`${e.user}@${e.host}`:e.host,n=e.port&&Number(e.port)!==22?`:${e.port}`:"",s=e.os?` [${e.os}]`:"",i=e.key?` key:${e.key}`:"",r=e.sudo?" sudo:yes":"";return`${t}: ${o}${n}${s}${i}${r}`}ma.exports={loadServerProfiles:ua,resolveProfile:Tf,buildSSHArgs:da,sshExec:Rf,scpUpload:Af,scpDownload:Of,enrichSSHError:es,formatProfile:Nf,SSH_SOCKET_DIR:Qn}});var ho=L((A$,ha)=>{var tn=require("fs"),mo=require("path"),Mf=mo.join(".nex","deploy.json");function po(){return mo.join(process.cwd(),Mf)}function pa(){let t=po();if(!tn.existsSync(t))return{};try{return JSON.parse(tn.readFileSync(t,"utf-8"))}catch{return{}}}function Pf(t){let e=pa();if(e[t])return{...e[t],_name:t};let o=Object.keys(e),n=o.length?`Available: ${o.join(", ")}`:"No deploy configs found. Create .nex/deploy.json or use explicit params.";throw new Error(`Unknown deploy config: "${t}". ${n}`)}function Lf(t){let e=mo.join(process.cwd(),".nex");tn.existsSync(e)||tn.mkdirSync(e,{recursive:!0}),tn.writeFileSync(po(),JSON.stringify(t,null,2)+`
137
+ `,"utf-8")}ha.exports={loadDeployConfigs:pa,resolveDeployConfig:Pf,saveDeployConfigs:Lf,getDeployConfigPath:po}});var sn=L((O$,ya)=>{var go=null,Qe=null,nn=null,ga=`Playwright is not installed. Install with:
138
138
  npm install playwright && npx playwright install chromium
139
- Then restart nex-code.`;function ga(){if(nn!==null)return nn;try{require("playwright"),nn=!0}catch{nn=!1}return nn}async function ts(){if(!ga())throw new Error(ha);return ho||(ho=require("playwright")),(!Qe||!Qe.isConnected())&&(Qe=await ho.chromium.launch({headless:!0})),Qe}async function If(){if(Qe){try{await Qe.close()}catch{}Qe=null}}process.on("exit",()=>{if(Qe)try{Qe.close()}catch{}});async function qf(t,{timeout:e=3e4,waitFor:s="domcontentloaded"}={}){let o=await(await ts()).newPage();try{await o.goto(t,{waitUntil:s,timeout:e});let i=await o.title(),r=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:i,url:o.url(),text:r.substring(0,8e3)+(r.length>8e3?`
140
- ...(truncated)`:""),links:c.slice(0,20)}}finally{await o.close()}}async function jf(t,{width:e=1280,height:s=800,fullPage:n=!1,timeout:o=3e4}={}){let r=await(await ts()).newPage();try{await r.setViewportSize({width:e,height:s}),await r.goto(t,{waitUntil:"networkidle",timeout:o});let c=await r.screenshot({type:"png",fullPage:n}),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 r.title(),url:r.url()}}finally{await r.close()}}async function Df(t,{selector:e,text:s,timeout:n=3e4}={}){if(!e&&!s)throw new Error("selector or text is required");let i=await(await ts()).newPage();try{await i.goto(t,{waitUntil:"domcontentloaded",timeout:n}),s?await i.getByText(s,{exact:!1}).first().click({timeout:1e4}):await i.locator(e).first().click({timeout:1e4}),await i.waitForLoadState("domcontentloaded");let r=await i.title();return`Clicked \u2014 now at: ${i.url()} (${r})`}finally{await i.close()}}async function Ff(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 r=await(await ts()).newPage();try{return await r.goto(t,{waitUntil:"domcontentloaded",timeout:o}),await r.fill(e,String(s)),n&&(await r.keyboard.press("Enter"),await r.waitForLoadState("domcontentloaded")),`Filled "${e}" with value. ${n?`Submitted \u2192 ${r.url()}`:"Not submitted."}`}finally{await r.close()}}$a.exports={isPlaywrightAvailable:ga,browserNavigate:qf,browserScreenshot:jf,browserClick:Df,browserFill:Ff,closeBrowser:If,INSTALL_MSG:ha}});var ns=L((O$,ya)=>{var{C:ee}=ce(),rn="",we=[],on=0,wt=null;function Uf(t){wt=t}function Wf(t,e){rn=t,we=[],on=0;for(let n of e){on++;let o=`t${on}`;we.push({id:o,description:n.description||n.title||n.name||n.task||`Task ${on}`,status:"pending",dependsOn:n.depends_on||[],result:null})}let s=we.map(n=>({...n}));return wt&&wt("create",{name:t,tasks:s}),s}function Bf(t,e,s){let n=we.find(o=>o.id===t);return n?(n.status=e,s!==void 0&&(n.result=s),wt&&wt("update",{id:t,status:e,result:s}),{...n}):null}function Hf(){return{name:rn,tasks:we.map(t=>({...t}))}}function Gf(){rn="",we=[],on=0,wt&&wt("clear",{})}function zf(){return we.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let s=we.find(n=>n.id===e);return s&&s.status==="done"}))}function Kf(){if(we.length===0)return`${ee.dim}No active tasks${ee.reset}`;let t=[];rn&&(t.push(` ${ee.bold}${ee.cyan}Tasks: ${rn}${ee.reset}`),t.push(` ${ee.dim}${"\u2500".repeat(40)}${ee.reset}`));for(let o of we){let i,r;switch(o.status){case"done":i="\u2713",r=ee.green;break;case"in_progress":i="\u2192",r=ee.cyan;break;case"failed":i="\u2717",r=ee.red;break;default:i="\xB7",r=ee.dim}let c=o.dependsOn.length>0?` ${ee.dim}(after: ${o.dependsOn.join(", ")})${ee.reset}`:"",l=`[${o.status}]`,u=o.description.length>50?o.description.substring(0,47)+"...":o.description;if(t.push(` ${r}${i}${ee.reset} ${ee.bold}${o.id}${ee.reset} ${u.padEnd(40)} ${r}${l}${ee.reset}${c}`),o.result&&o.status==="done"){let d=o.result.length>60?o.result.substring(0,57)+"...":o.result;t.push(` ${ee.dim}\u2192 ${d}${ee.reset}`)}}let e=we.filter(o=>o.status==="done").length,s=we.filter(o=>o.status==="failed").length,n=we.length;return t.push(` ${ee.dim}${"\u2500".repeat(40)}${ee.reset}`),t.push(` ${ee.dim}${e}/${n} done${s>0?`, ${s} failed`:""}${ee.reset}`),t.join(`
141
- `)}function Yf(){return we.length>0&&we.some(t=>t.status==="pending"||t.status==="in_progress")}ya.exports={createTasks:Wf,updateTask:Bf,getTaskList:Hf,clearTasks:Gf,getReadyTasks:zf,renderTaskList:Kf,setOnChange:Uf,hasActiveTasks:Yf}});var $o=L((N$,ba)=>{var{getActiveModel:Jf,getActiveProviderName:Xf}=ge(),an={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},cn={"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"},ln={ollama:"full",openai:"full",anthropic:"full",gemini:"full",local:"essential"},We={};function wa(){try{let t=require("fs"),s=require("path").join(process.cwd(),".nex","config.json");t.existsSync(s)&&(We=JSON.parse(t.readFileSync(s,"utf-8")).toolTiers||{})}catch{We={}}}wa();function go(){let e=Jf()?.id,s=Xf();return e&&We[e]?We[e]:s&&We[`${s}:*`]?We[`${s}:*`]:e&&cn[e]?cn[e]:s&&ln[s]?ln[s]:"full"}function Vf(t,e){return t&&We[t]?We[t]:e&&We[`${e}:*`]?We[`${e}:*`]:t&&cn[t]?cn[t]:e&&ln[e]?ln[e]:"full"}function Qf(t,e){let s=e||go();if(s==="full"||!an[s])return t;let n=new Set(an[s]);return t.filter(o=>n.has(o.function.name))}function Zf(){let t=go(),e=an[t]?an[t].length:"all";return{tier:t,toolCount:e}}ba.exports={filterToolsForModel:Qf,getActiveTier:go,getModelTier:Vf,getTierInfo:Zf,TIERS:an,MODEL_TIERS:cn,PROVIDER_DEFAULT_TIER:ln,loadConfigOverrides:wa}});var Na=L((P$,Oa)=>{var{callStream:em,getActiveProviderName:os,getActiveModelId:tm,getConfiguredProviders:nm,getProvider:xa,getActiveProvider:_a,parseModelSpec:ka}=ge(),{parseToolArgs:sm}=Un(),{filterToolsForModel:om,getModelTier:ss}=$o(),{trackUsage:rm}=Nt(),{MultiProgress:im,C:M$}=ce(),am=15,va=5,Sa=3,rs=new Map;function cm(t,e){let s=rs.get(t);return s&&s!==e?!1:(rs.set(t,e),!0)}function un(t){rs.delete(t)}function yo(){rs.clear()}function Ea(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 Ta(t,e,s){let n;for(let o=0;o<=Sa;o++)try{return await em(t,e,s)}catch(i){if(n=i,o<Sa&&Ea(i)){let c=(i.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 i}throw n}var lm=new Set(["ask_user","task_list","spawn_agents"]),um=new Set(["write_file","edit_file","patch_file"]),dm=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,fm=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function Ca(t){return fm.test(t)?"full":dm.test(t)?"essential":"standard"}function Ra(t){let e=nm(),s=os(),n=[...e].sort((o,i)=>(o.name===s?-1:1)-(i.name===s?-1:1));for(let o of n)for(let i of o.models)if(ss(i.id,o.name)===t)return{provider:o.name,model:i.id};return null}var mm={essential:process.env.NEX_FAST_MODEL||null,standard:process.env.NEX_STANDARD_MODEL||null,full:process.env.NEX_HEAVY_MODEL||null};function wo(t){if(t.model){let{provider:o,model:i}=ka(t.model),r=o?xa(o):_a(),c=o||os();if(r&&r.isConfigured()&&(r.getModel(i)||c==="local")){let l=ss(i,c);return{provider:c,model:i,tier:l}}}let e=Ca(t.task),s=mm[e];if(s){let{provider:o,model:i}=ka(s),r=o?xa(o):_a(),c=o||os();if(r&&r.isConfigured()&&(r.getModel(i)||c==="local")){let l=ss(i,c);return{provider:c,model:i,tier:l}}}let n=Ra(e);if(n){let o=ss(n.model,n.provider);return{provider:n.provider,model:n.model,tier:o}}return{provider:null,model:null,tier:null}}async function Aa(t,e={}){let s=Math.min(t.max_iterations||10,am),n=`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,o=[],i={input:0,output:0},r=new Set,l=[{role:"system",content:`You are a focused sub-agent. Complete this specific task efficiently.
139
+ Then restart nex-code.`;function $a(){if(nn!==null)return nn;try{require("playwright"),nn=!0}catch{nn=!1}return nn}async function ts(){if(!$a())throw new Error(ga);return go||(go=require("playwright")),(!Qe||!Qe.isConnected())&&(Qe=await go.chromium.launch({headless:!0})),Qe}async function If(){if(Qe){try{await Qe.close()}catch{}Qe=null}}process.on("exit",()=>{if(Qe)try{Qe.close()}catch{}});async function qf(t,{timeout:e=3e4,waitFor:o="domcontentloaded"}={}){let s=await(await ts()).newPage();try{await s.goto(t,{waitUntil:o,timeout:e});let i=await s.title(),r=await s.evaluate(()=>(document.querySelectorAll("script,style,nav,footer,header,aside,[role=navigation]").forEach(u=>u.remove()),document.body?.innerText||"")),c=await s.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:i,url:s.url(),text:r.substring(0,8e3)+(r.length>8e3?`
140
+ ...(truncated)`:""),links:c.slice(0,20)}}finally{await s.close()}}async function jf(t,{width:e=1280,height:o=800,fullPage:n=!1,timeout:s=3e4}={}){let r=await(await ts()).newPage();try{await r.setViewportSize({width:e,height:o}),await r.goto(t,{waitUntil:"networkidle",timeout:s});let c=await r.screenshot({type:"png",fullPage:n}),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 r.title(),url:r.url()}}finally{await r.close()}}async function Df(t,{selector:e,text:o,timeout:n=3e4}={}){if(!e&&!o)throw new Error("selector or text is required");let i=await(await ts()).newPage();try{await i.goto(t,{waitUntil:"domcontentloaded",timeout:n}),o?await i.getByText(o,{exact:!1}).first().click({timeout:1e4}):await i.locator(e).first().click({timeout:1e4}),await i.waitForLoadState("domcontentloaded");let r=await i.title();return`Clicked \u2014 now at: ${i.url()} (${r})`}finally{await i.close()}}async function Ff(t,{selector:e,value:o,submit:n=!1,timeout:s=3e4}={}){if(!e||o===void 0)throw new Error("selector and value are required");let r=await(await ts()).newPage();try{return await r.goto(t,{waitUntil:"domcontentloaded",timeout:s}),await r.fill(e,String(o)),n&&(await r.keyboard.press("Enter"),await r.waitForLoadState("domcontentloaded")),`Filled "${e}" with value. ${n?`Submitted \u2192 ${r.url()}`:"Not submitted."}`}finally{await r.close()}}ya.exports={isPlaywrightAvailable:$a,browserNavigate:qf,browserScreenshot:jf,browserClick:Df,browserFill:Ff,closeBrowser:If,INSTALL_MSG:ga}});var ns=L((N$,wa)=>{var{C:ee}=ce(),rn="",we=[],on=0,wt=null;function Uf(t){wt=t}function Wf(t,e){rn=t,we=[],on=0;for(let n of e){on++;let s=`t${on}`;we.push({id:s,description:n.description||n.title||n.name||n.task||`Task ${on}`,status:"pending",dependsOn:n.depends_on||[],result:null})}let o=we.map(n=>({...n}));return wt&&wt("create",{name:t,tasks:o}),o}function Bf(t,e,o){let n=we.find(s=>s.id===t);return n?(n.status=e,o!==void 0&&(n.result=o),wt&&wt("update",{id:t,status:e,result:o}),{...n}):null}function Hf(){return{name:rn,tasks:we.map(t=>({...t}))}}function Gf(){rn="",we=[],on=0,wt&&wt("clear",{})}function zf(){return we.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let o=we.find(n=>n.id===e);return o&&o.status==="done"}))}function Kf(){if(we.length===0)return`${ee.dim}No active tasks${ee.reset}`;let t=[];rn&&(t.push(` ${ee.bold}${ee.cyan}Tasks: ${rn}${ee.reset}`),t.push(` ${ee.dim}${"\u2500".repeat(40)}${ee.reset}`));for(let s of we){let i,r;switch(s.status){case"done":i="\u2713",r=ee.green;break;case"in_progress":i="\u2192",r=ee.cyan;break;case"failed":i="\u2717",r=ee.red;break;default:i="\xB7",r=ee.dim}let c=s.dependsOn.length>0?` ${ee.dim}(after: ${s.dependsOn.join(", ")})${ee.reset}`:"",l=`[${s.status}]`,u=s.description.length>50?s.description.substring(0,47)+"...":s.description;if(t.push(` ${r}${i}${ee.reset} ${ee.bold}${s.id}${ee.reset} ${u.padEnd(40)} ${r}${l}${ee.reset}${c}`),s.result&&s.status==="done"){let d=s.result.length>60?s.result.substring(0,57)+"...":s.result;t.push(` ${ee.dim}\u2192 ${d}${ee.reset}`)}}let e=we.filter(s=>s.status==="done").length,o=we.filter(s=>s.status==="failed").length,n=we.length;return t.push(` ${ee.dim}${"\u2500".repeat(40)}${ee.reset}`),t.push(` ${ee.dim}${e}/${n} done${o>0?`, ${o} failed`:""}${ee.reset}`),t.join(`
141
+ `)}function Yf(){return we.length>0&&we.some(t=>t.status==="pending"||t.status==="in_progress")}wa.exports={createTasks:Wf,updateTask:Bf,getTaskList:Hf,clearTasks:Gf,getReadyTasks:zf,renderTaskList:Kf,setOnChange:Uf,hasActiveTasks:Yf}});var yo=L((M$,xa)=>{var{getActiveModel:Jf,getActiveProviderName:Xf}=ge(),an={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},cn={"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"},ln={ollama:"full",openai:"full",anthropic:"full",gemini:"full",local:"essential"},We={};function ba(){try{let t=require("fs"),o=require("path").join(process.cwd(),".nex","config.json");t.existsSync(o)&&(We=JSON.parse(t.readFileSync(o,"utf-8")).toolTiers||{})}catch{We={}}}ba();function $o(){let e=Jf()?.id,o=Xf();return e&&We[e]?We[e]:o&&We[`${o}:*`]?We[`${o}:*`]:e&&cn[e]?cn[e]:o&&ln[o]?ln[o]:"full"}function Vf(t,e){return t&&We[t]?We[t]:e&&We[`${e}:*`]?We[`${e}:*`]:t&&cn[t]?cn[t]:e&&ln[e]?ln[e]:"full"}function Qf(t,e){let o=e||$o();if(o==="full"||!an[o])return t;let n=new Set(an[o]);return t.filter(s=>n.has(s.function.name))}function Zf(){let t=$o(),e=an[t]?an[t].length:"all";return{tier:t,toolCount:e}}xa.exports={filterToolsForModel:Qf,getActiveTier:$o,getModelTier:Vf,getTierInfo:Zf,TIERS:an,MODEL_TIERS:cn,PROVIDER_DEFAULT_TIER:ln,loadConfigOverrides:ba}});var Ma=L((L$,Na)=>{var{callStream:em,getActiveProviderName:os,getActiveModelId:tm,getConfiguredProviders:nm,getProvider:_a,getActiveProvider:ka,parseModelSpec:va}=ge(),{parseToolArgs:sm}=Un(),{filterToolsForModel:om,getModelTier:ss}=yo(),{trackUsage:rm}=Nt(),{MultiProgress:im,C:P$}=ce(),am=15,Sa=5,Ea=3,rs=new Map;function cm(t,e){let o=rs.get(t);return o&&o!==e?!1:(rs.set(t,e),!0)}function un(t){rs.delete(t)}function wo(){rs.clear()}function Ta(t){let e=t.message||"",o=t.code||"";return!!(e.includes("429")||e.includes("500")||e.includes("502")||e.includes("503")||e.includes("504")||o==="ECONNRESET"||o==="ECONNABORTED"||o==="ETIMEDOUT"||o==="ECONNREFUSED"||e.includes("socket disconnected")||e.includes("TLS")||e.includes("ECONNRESET")||e.includes("fetch failed")||e.includes("ETIMEDOUT")||e.includes("ENOTFOUND"))}async function Ca(t,e,o){let n;for(let s=0;s<=Ea;s++)try{return await em(t,e,o)}catch(i){if(n=i,s<Ea&&Ta(i)){let c=(i.message||"").includes("429")?Math.min(2e3*Math.pow(2,s),15e3):Math.min(500*Math.pow(2,s),4e3);await new Promise(l=>setTimeout(l,c).unref());continue}throw i}throw n}var lm=new Set(["ask_user","task_list","spawn_agents"]),um=new Set(["write_file","edit_file","patch_file"]),dm=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,fm=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function Ra(t){return fm.test(t)?"full":dm.test(t)?"essential":"standard"}function Aa(t){let e=nm(),o=os(),n=[...e].sort((s,i)=>(s.name===o?-1:1)-(i.name===o?-1:1));for(let s of n)for(let i of s.models)if(ss(i.id,s.name)===t)return{provider:s.name,model:i.id};return null}var mm={essential:process.env.NEX_FAST_MODEL||null,standard:process.env.NEX_STANDARD_MODEL||null,full:process.env.NEX_HEAVY_MODEL||null};function bo(t){if(t.model){let{provider:s,model:i}=va(t.model),r=s?_a(s):ka(),c=s||os();if(r&&r.isConfigured()&&(r.getModel(i)||c==="local")){let l=ss(i,c);return{provider:c,model:i,tier:l}}}let e=Ra(t.task),o=mm[e];if(o){let{provider:s,model:i}=va(o),r=s?_a(s):ka(),c=s||os();if(r&&r.isConfigured()&&(r.getModel(i)||c==="local")){let l=ss(i,c);return{provider:c,model:i,tier:l}}}let n=Aa(e);if(n){let s=ss(n.model,n.provider);return{provider:n.provider,model:n.model,tier:s}}return{provider:null,model:null,tier:null}}async function Oa(t,e={}){let o=Math.min(t.max_iterations||10,am),n=`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,s=[],i={input:0,output:0},r=new Set,l=[{role:"system",content:`You are a focused sub-agent. Complete this specific task efficiently.
142
142
 
143
143
  TASK: ${t.task}
144
144
  ${t.context?`
@@ -160,118 +160,118 @@ TOOL STRATEGY:
160
160
  ERROR RECOVERY:
161
161
  - If edit_file fails with "old_text not found": read the file again, compare, and retry with exact text.
162
162
  - If bash fails: read the error, fix the root cause, then retry.
163
- - After 2 failed attempts at the same operation, summarize the issue and stop.`}];l.push({role:"user",content:t.task});let u=wo(t),d=u.provider,f=u.model,m=u.tier,{TOOL_DEFINITIONS:h,executeTool:p}=Ue(),g=om(h.filter(y=>!lm.has(y.function.name)),m);if(f&&!t._skipLog){let y=m?` (${m})`:"";process.stderr.write(` [sub-agent: ${d}:${f}${y}]
164
- `)}let $={};d&&($.provider=d),f&&($.model=f);try{for(let y=0;y<s;y++){let x=await Ta(l,g,$);if(!x||typeof x!="object")throw new Error("Empty or invalid response from provider");if(x.usage){let v=x.usage.prompt_tokens||0,F=x.usage.completion_tokens||0;i.input+=v,i.output+=F;let j=d||os(),J=f||tm();rm(j,J,v,F)}let T=x.content||"",k=x.tool_calls,E={role:"assistant",content:T||""};if(k&&k.length>0&&(E.tool_calls=k),l.push(E),!k||k.length===0){for(let v of r)un(v);return{task:t.task,status:"done",result:T||"(no response)",toolsUsed:o,tokensUsed:i,modelSpec:d&&f?`${d}:${f}`:null}}let C=k.map(v=>{let F=v.function.name,j=sm(v.function.arguments),J=v.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:J});let U=null;if(um.has(F)&&j.path){let Q=require("path"),me=Q.isAbsolute(j.path)?j.path:Q.resolve(process.cwd(),j.path);if(r.has(me)||!cm(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:J});r.add(me),U=me}return o.push(F),p(F,j,{autoConfirm:!0,silent:!0}).then(Q=>{U&&(un(U),r.delete(U));let me=String(Q??"");return{role:"tool",content:me.length>2e4?me.substring(0,2e4)+`
165
- ...(truncated)`:me,tool_call_id:J}}).catch(Q=>(U&&(un(U),r.delete(U)),{role:"tool",content:`ERROR: ${Q.message}`,tool_call_id:J}))}),O=await Promise.all(C);l.push(...O),e.onUpdate&&e.onUpdate(`step ${y+1}/${s}`)}for(let y of r)un(y);return{task:t.task,status:"truncated",abortReason:"iteration_limit",result:l[l.length-1]?.content||"(max iterations reached)",toolsUsed:o,tokensUsed:i,modelSpec:d&&f?`${d}:${f}`:null}}catch(y){for(let x of r)un(x);return{task:t.task,status:"failed",result:`Error: ${y.message}`,toolsUsed:o,tokensUsed:i,modelSpec:d&&f?`${d}:${f}`:null}}}async function pm(t){let e=t.agents||[];if(e.length===0)return"ERROR: No agents specified";if(e.length>va)return`ERROR: Max ${va} parallel agents allowed, got ${e.length}`;let s=e.map(i=>wo(i)),n=e.map((i,r)=>{let c=s[r],l=c.model?` [${c.model}]`:"",u=i.task.substring(0,44-l.length);return`Agent ${r+1}${l}: ${u}${i.task.length>u.length?"...":""}`}),o=new im(n);o.start();try{let i=e.map((d,f)=>{let m=s[f],h=m.model?{...d,model:`${m.provider}:${m.model}`,_skipLog:!0}:{...d,_skipLog:!0};return Aa(h,{onUpdate:()=>{}}).then(p=>(o.update(f,p.status==="failed"?"error":"done"),p)).catch(p=>(o.update(f,"error"),{task:d.task,status:"failed",result:`Error: ${p.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}))}),r=await Promise.all(i);o.stop(),yo();let c=["Sub-agent results:",""],l=0,u=0;for(let d=0;d<r.length;d++){let f=r[d],m=f.status==="done"?"\u2713":f.status==="truncated"?"\u26A0":"\u2717",h=f.modelSpec?` [${f.modelSpec}]`:"";c.push(`${m} Agent ${d+1}${h}: ${f.task}`),c.push(` Status: ${f.status}`),c.push(` Tools used: ${f.toolsUsed.length>0?f.toolsUsed.join(", "):"none"}`),c.push(` Result: ${f.result}`),c.push(""),l+=f.tokensUsed.input,u+=f.tokensUsed.output}return c.push(`Total sub-agent tokens: ${l} input + ${u} output`),c.join(`
166
- `)}catch(i){return o.stop(),yo(),`ERROR: Sub-agent execution failed: ${i.message}`}}Oa.exports={runSubAgent:Aa,executeSpawnAgents:pm,clearAllLocks:yo,classifyTask:Ca,pickModelForTier:Ra,resolveSubAgentModel:wo,isRetryableError:Ea,callWithRetry:Ta}});var mn=L((L$,Ga)=>{var se=require("fs"),Ze=require("path"),hm=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 jt(){let t=Ze.join(process.cwd(),".nex","brain");return se.existsSync(t)||se.mkdirSync(t,{recursive:!0}),t}function Ma(){return Ze.join(jt(),".brain-index.json")}function _o(){return Ze.join(jt(),".embeddings.json")}function dn(){let t=Ze.join(process.cwd(),".nex","brain");if(!se.existsSync(t))return[];try{return se.readdirSync(t).filter(e=>e.endsWith(".md")&&!e.startsWith(".")).map(e=>{let s=Ze.join(t,e),n=se.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 fn(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(`
167
- `);for(let i of o){let r=i.match(/^(\w+):\s*(.+)$/);if(!r)continue;let c=r[1].trim(),l=r[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 Pa(t){let e=Ze.join(jt(),`${t}.md`);if(!se.existsSync(e))return{name:t,content:"",body:"",frontmatter:{}};let s=se.readFileSync(e,"utf-8"),{frontmatter:n,body:o}=fn(s);return{name:t,content:s,body:o,frontmatter:n}}function gm(t,e){let s=Ze.join(jt(),`${t}.md`);se.writeFileSync(s,e,"utf-8"),wm(t,e),$m()}function $m(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return;let t=_o();se.existsSync(t)&&setImmediate(async()=>{try{await Ua()}catch{}})}function ym(t){let e=Ze.join(jt(),`${t}.md`);return se.existsSync(e)?(se.unlinkSync(e),bm(t),!0):!1}function is(t){return t.toLowerCase().replace(/[^a-z0-9äöüß\s-]/g," ").split(/[\s-]+/).filter(e=>e.length>2&&!hm.has(e))}function ko(t){let e={},{frontmatter:s,body:n}=fn(t),o=Array.isArray(s.tags)?s.tags:[];for(let r of o){let c=r.toLowerCase().replace(/[^a-z0-9-]/g,"");c.length>1&&(e[c]=(e[c]||0)+5)}let i=(n||t).split(`
168
- `);for(let r of i)if(r.startsWith("#")){let c=r.replace(/^#+\s*/,"");for(let l of is(c))e[l]=(e[l]||0)+3}for(let r of is(n||t))e[r]=(e[r]||0)+1;return e}function vo(){let t=Ma();if(!se.existsSync(t))return{documents:{}};try{return JSON.parse(se.readFileSync(t,"utf-8"))}catch{return{documents:{}}}}function So(t){se.writeFileSync(Ma(),JSON.stringify(t,null,2),"utf-8")}function wm(t,e){let s=vo(),{frontmatter:n}=fn(e),o=Array.isArray(n.tags)?n.tags:[];s.documents[t]={keywords:ko(e),tags:o,modified:new Date().toISOString()},So(s)}function bm(t){let e=vo();delete e.documents[t],So(e)}function xo(){let t=dn(),e={documents:{}};for(let s of t){let n=se.readFileSync(s.path,"utf-8"),{frontmatter:o}=fn(n),i=Array.isArray(o.tags)?o.tags:[];e.documents[s.name]={keywords:ko(n),tags:i,modified:s.modified.toISOString()}}return So(e),e}function La(){let t=vo(),e=dn();for(let s of e){let n=t.documents[s.name];if(!n||new Date(n.modified)<s.modified)return xo()}for(let s of Object.keys(t.documents))if(!e.some(n=>n.name===s))return xo();return t}function Ia(t,e={}){let{topK:s=3,minScore:n=.1}=e,o=is(t);if(o.length===0)return[];let i=La(),r=[];for(let[c,l]of Object.entries(i.documents)){let u=0;for(let d of o){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>=n&&r.push({name:c,score:u})}return r.sort((c,l)=>l.score-c.score),r.slice(0,s)}var qa=process.env.NEX_EMBED_MODEL||"nomic-embed-text",bo=400,xm=50;async function ja(){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 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(qa.split(":")[0]))}catch{return!1}}async function Eo(t){let e=process.env.OLLAMA_HOST||"http://localhost:11434",s=require("http"),n=require("https"),o=new URL(`${e}/api/embeddings`),i=o.protocol==="https:"?n:s,r=JSON.stringify({model:qa,prompt:t});return new Promise((c,l)=>{let u=i.request(o,{method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(r)},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(r),u.end()})}function Da(t,e){if(!t||!e||t.length!==e.length)return 0;let s=0,n=0,o=0;for(let r=0;r<t.length;r++)s+=t[r]*e[r],n+=t[r]*t[r],o+=e[r]*e[r];let i=Math.sqrt(n)*Math.sqrt(o);return i===0?0:s/i}function Fa(t){let e=t.split(/\s+/),s=[],n=0;for(;n<e.length;){let o=e.slice(n,n+bo).join(" ");if(s.push({text:o,offset:n}),n+bo>=e.length)break;n+=bo-xm}return s}async function Ua(){let t=dn(),e={documents:{}},s=_o();if(se.existsSync(s))try{e=JSON.parse(se.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 i=se.readFileSync(n.path,"utf-8"),r=Fa(i),c=[];for(let l of r){let u=await Eo(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 se.writeFileSync(s,JSON.stringify(e),"utf-8"),e}async function Wa(t,e={}){let{topK:s=3,minSimilarity:n=.3}=e,o=_o();if(!se.existsSync(o))return[];let i;try{i=JSON.parse(se.readFileSync(o,"utf-8"))}catch{return[]}let r=await Eo(t),c=[];for(let[l,u]of Object.entries(i.documents||{})){let d=0,f="";for(let m of u.chunks||[]){let h=Da(r,m.embedding);h>d&&(d=h,f=m.text)}d>=n&&c.push({name:l,score:d,bestChunk:f})}return c.sort((l,u)=>u.score-l.score),c.slice(0,s)}function Ba(t,e,s={}){let{k:n=60,topK:o=3}=s,i={};return t.forEach((r,c)=>{i[r.name]=(i[r.name]||0)+1/(n+c+1)}),e.forEach((r,c)=>{i[r.name]=(i[r.name]||0)+1/(n+c+1)}),Object.entries(i).map(([r,c])=>({name:r,score:c})).sort((r,c)=>c.score-r.score).slice(0,o)}async function Ha(t,e={}){let{topK:s=3,minScore:n=.1}=e,o=Ia(t,{topK:s,minScore:n}),i=o;if(process.env.NEX_BRAIN_EMBEDDINGS!=="false")try{if(await ja()){let c=await Wa(t,{topK:s});i=Ba(o,c,{topK:s})}}catch{}return i.map(r=>{let c=Pa(r.name),l=(c.body||c.content||"").slice(0,300).replace(/\n+/g," ")+"...";return{name:r.name,score:r.score,content:c.content,excerpt:l}})}async function _m(t){if(!t||!t.trim())return"";let e=Ze.join(process.cwd(),".nex","brain");if(!se.existsSync(e)||dn().length===0)return"";let n;try{n=await Ha(t,{topK:3})}catch{return""}if(!n||n.length===0)return"";let o;try{o=Pe().estimateTokens}catch{o=l=>Math.ceil(l.length/4)}let i=25e3,r=[],c=0;for(let l of n){let u=l.content||"",d=o(u);if(c+d>i){let m=i-c;if(m<100)break;let h=m/d;u=u.slice(0,Math.floor(u.length*h))+`
163
+ - After 2 failed attempts at the same operation, summarize the issue and stop.`}];l.push({role:"user",content:t.task});let u=bo(t),d=u.provider,f=u.model,m=u.tier,{TOOL_DEFINITIONS:h,executeTool:p}=Ue(),g=om(h.filter(y=>!lm.has(y.function.name)),m);if(f&&!t._skipLog){let y=m?` (${m})`:"";process.stderr.write(` [sub-agent: ${d}:${f}${y}]
164
+ `)}let $={};d&&($.provider=d),f&&($.model=f);try{for(let y=0;y<o;y++){let x=await Ca(l,g,$);if(!x||typeof x!="object")throw new Error("Empty or invalid response from provider");if(x.usage){let v=x.usage.prompt_tokens||0,F=x.usage.completion_tokens||0;i.input+=v,i.output+=F;let j=d||os(),J=f||tm();rm(j,J,v,F)}let T=x.content||"",k=x.tool_calls,E={role:"assistant",content:T||""};if(k&&k.length>0&&(E.tool_calls=k),l.push(E),!k||k.length===0){for(let v of r)un(v);return{task:t.task,status:"done",result:T||"(no response)",toolsUsed:s,tokensUsed:i,modelSpec:d&&f?`${d}:${f}`:null}}let C=k.map(v=>{let F=v.function.name,j=sm(v.function.arguments),J=v.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:J});let U=null;if(um.has(F)&&j.path){let Q=require("path"),me=Q.isAbsolute(j.path)?j.path:Q.resolve(process.cwd(),j.path);if(r.has(me)||!cm(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:J});r.add(me),U=me}return s.push(F),p(F,j,{autoConfirm:!0,silent:!0}).then(Q=>{U&&(un(U),r.delete(U));let me=String(Q??"");return{role:"tool",content:me.length>2e4?me.substring(0,2e4)+`
165
+ ...(truncated)`:me,tool_call_id:J}}).catch(Q=>(U&&(un(U),r.delete(U)),{role:"tool",content:`ERROR: ${Q.message}`,tool_call_id:J}))}),O=await Promise.all(C);l.push(...O),e.onUpdate&&e.onUpdate(`step ${y+1}/${o}`)}for(let y of r)un(y);return{task:t.task,status:"truncated",abortReason:"iteration_limit",result:l[l.length-1]?.content||"(max iterations reached)",toolsUsed:s,tokensUsed:i,modelSpec:d&&f?`${d}:${f}`:null}}catch(y){for(let x of r)un(x);return{task:t.task,status:"failed",result:`Error: ${y.message}`,toolsUsed:s,tokensUsed:i,modelSpec:d&&f?`${d}:${f}`:null}}}async function pm(t){let e=t.agents||[];if(e.length===0)return"ERROR: No agents specified";if(e.length>Sa)return`ERROR: Max ${Sa} parallel agents allowed, got ${e.length}`;let o=e.map(i=>bo(i)),n=e.map((i,r)=>{let c=o[r],l=c.model?` [${c.model}]`:"",u=i.task.substring(0,44-l.length);return`Agent ${r+1}${l}: ${u}${i.task.length>u.length?"...":""}`}),s=new im(n);s.start();try{let i=e.map((d,f)=>{let m=o[f],h=m.model?{...d,model:`${m.provider}:${m.model}`,_skipLog:!0}:{...d,_skipLog:!0};return Oa(h,{onUpdate:()=>{}}).then(p=>(s.update(f,p.status==="failed"?"error":"done"),p)).catch(p=>(s.update(f,"error"),{task:d.task,status:"failed",result:`Error: ${p.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}))}),r=await Promise.all(i);s.stop(),wo();let c=["Sub-agent results:",""],l=0,u=0;for(let d=0;d<r.length;d++){let f=r[d],m=f.status==="done"?"\u2713":f.status==="truncated"?"\u26A0":"\u2717",h=f.modelSpec?` [${f.modelSpec}]`:"";c.push(`${m} Agent ${d+1}${h}: ${f.task}`),c.push(` Status: ${f.status}`),c.push(` Tools used: ${f.toolsUsed.length>0?f.toolsUsed.join(", "):"none"}`),c.push(` Result: ${f.result}`),c.push(""),l+=f.tokensUsed.input,u+=f.tokensUsed.output}return c.push(`Total sub-agent tokens: ${l} input + ${u} output`),c.join(`
166
+ `)}catch(i){return s.stop(),wo(),`ERROR: Sub-agent execution failed: ${i.message}`}}Na.exports={runSubAgent:Oa,executeSpawnAgents:pm,clearAllLocks:wo,classifyTask:Ra,pickModelForTier:Aa,resolveSubAgentModel:bo,isRetryableError:Ta,callWithRetry:Ca}});var mn=L((I$,za)=>{var se=require("fs"),Ze=require("path"),hm=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 jt(){let t=Ze.join(process.cwd(),".nex","brain");return se.existsSync(t)||se.mkdirSync(t,{recursive:!0}),t}function Pa(){return Ze.join(jt(),".brain-index.json")}function ko(){return Ze.join(jt(),".embeddings.json")}function dn(){let t=Ze.join(process.cwd(),".nex","brain");if(!se.existsSync(t))return[];try{return se.readdirSync(t).filter(e=>e.endsWith(".md")&&!e.startsWith(".")).map(e=>{let o=Ze.join(t,e),n=se.statSync(o);return{name:e.replace(/\.md$/,""),path:o,size:n.size,modified:new Date(n.mtimeMs)}}).sort((e,o)=>o.modified-e.modified)}catch{return[]}}function fn(t){let e={},o=t,n=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(n){let s=n[1].split(`
167
+ `);for(let i of s){let r=i.match(/^(\w+):\s*(.+)$/);if(!r)continue;let c=r[1].trim(),l=r[2].trim();l.startsWith("[")&&l.endsWith("]")?e[c]=l.slice(1,-1).split(",").map(u=>u.trim()).filter(Boolean):e[c]=l}o=n[2]}return{frontmatter:e,body:o}}function La(t){let e=Ze.join(jt(),`${t}.md`);if(!se.existsSync(e))return{name:t,content:"",body:"",frontmatter:{}};let o=se.readFileSync(e,"utf-8"),{frontmatter:n,body:s}=fn(o);return{name:t,content:o,body:s,frontmatter:n}}function gm(t,e){let o=Ze.join(jt(),`${t}.md`);se.writeFileSync(o,e,"utf-8"),wm(t,e),$m()}function $m(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return;let t=ko();se.existsSync(t)&&setImmediate(async()=>{try{await Wa()}catch{}})}function ym(t){let e=Ze.join(jt(),`${t}.md`);return se.existsSync(e)?(se.unlinkSync(e),bm(t),!0):!1}function is(t){return t.toLowerCase().replace(/[^a-z0-9äöüß\s-]/g," ").split(/[\s-]+/).filter(e=>e.length>2&&!hm.has(e))}function vo(t){let e={},{frontmatter:o,body:n}=fn(t),s=Array.isArray(o.tags)?o.tags:[];for(let r of s){let c=r.toLowerCase().replace(/[^a-z0-9-]/g,"");c.length>1&&(e[c]=(e[c]||0)+5)}let i=(n||t).split(`
168
+ `);for(let r of i)if(r.startsWith("#")){let c=r.replace(/^#+\s*/,"");for(let l of is(c))e[l]=(e[l]||0)+3}for(let r of is(n||t))e[r]=(e[r]||0)+1;return e}function So(){let t=Pa();if(!se.existsSync(t))return{documents:{}};try{return JSON.parse(se.readFileSync(t,"utf-8"))}catch{return{documents:{}}}}function Eo(t){se.writeFileSync(Pa(),JSON.stringify(t,null,2),"utf-8")}function wm(t,e){let o=So(),{frontmatter:n}=fn(e),s=Array.isArray(n.tags)?n.tags:[];o.documents[t]={keywords:vo(e),tags:s,modified:new Date().toISOString()},Eo(o)}function bm(t){let e=So();delete e.documents[t],Eo(e)}function _o(){let t=dn(),e={documents:{}};for(let o of t){let n=se.readFileSync(o.path,"utf-8"),{frontmatter:s}=fn(n),i=Array.isArray(s.tags)?s.tags:[];e.documents[o.name]={keywords:vo(n),tags:i,modified:o.modified.toISOString()}}return Eo(e),e}function Ia(){let t=So(),e=dn();for(let o of e){let n=t.documents[o.name];if(!n||new Date(n.modified)<o.modified)return _o()}for(let o of Object.keys(t.documents))if(!e.some(n=>n.name===o))return _o();return t}function qa(t,e={}){let{topK:o=3,minScore:n=.1}=e,s=is(t);if(s.length===0)return[];let i=Ia(),r=[];for(let[c,l]of Object.entries(i.documents)){let u=0;for(let d of s){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>=n&&r.push({name:c,score:u})}return r.sort((c,l)=>l.score-c.score),r.slice(0,o)}var ja=process.env.NEX_EMBED_MODEL||"nomic-embed-text",xo=400,xm=50;async function Da(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return!1;try{let t=process.env.OLLAMA_HOST||"http://localhost:11434",e=require("http"),o=require("https"),n=new URL(`${t}/api/tags`),s=n.protocol==="https:"?o:e;return((await new Promise((c,l)=>{let u=s.get(n.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(ja.split(":")[0]))}catch{return!1}}async function To(t){let e=process.env.OLLAMA_HOST||"http://localhost:11434",o=require("http"),n=require("https"),s=new URL(`${e}/api/embeddings`),i=s.protocol==="https:"?n:o,r=JSON.stringify({model:ja,prompt:t});return new Promise((c,l)=>{let u=i.request(s,{method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(r)},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(r),u.end()})}function Fa(t,e){if(!t||!e||t.length!==e.length)return 0;let o=0,n=0,s=0;for(let r=0;r<t.length;r++)o+=t[r]*e[r],n+=t[r]*t[r],s+=e[r]*e[r];let i=Math.sqrt(n)*Math.sqrt(s);return i===0?0:o/i}function Ua(t){let e=t.split(/\s+/),o=[],n=0;for(;n<e.length;){let s=e.slice(n,n+xo).join(" ");if(o.push({text:s,offset:n}),n+xo>=e.length)break;n+=xo-xm}return o}async function Wa(){let t=dn(),e={documents:{}},o=ko();if(se.existsSync(o))try{e=JSON.parse(se.readFileSync(o,"utf-8"))}catch{}for(let n of t){let s=e.documents[n.name];if(s&&new Date(s.modified)>=n.modified)continue;let i=se.readFileSync(n.path,"utf-8"),r=Ua(i),c=[];for(let l of r){let u=await To(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(s=>s.name===n)||delete e.documents[n];return se.writeFileSync(o,JSON.stringify(e),"utf-8"),e}async function Ba(t,e={}){let{topK:o=3,minSimilarity:n=.3}=e,s=ko();if(!se.existsSync(s))return[];let i;try{i=JSON.parse(se.readFileSync(s,"utf-8"))}catch{return[]}let r=await To(t),c=[];for(let[l,u]of Object.entries(i.documents||{})){let d=0,f="";for(let m of u.chunks||[]){let h=Fa(r,m.embedding);h>d&&(d=h,f=m.text)}d>=n&&c.push({name:l,score:d,bestChunk:f})}return c.sort((l,u)=>u.score-l.score),c.slice(0,o)}function Ha(t,e,o={}){let{k:n=60,topK:s=3}=o,i={};return t.forEach((r,c)=>{i[r.name]=(i[r.name]||0)+1/(n+c+1)}),e.forEach((r,c)=>{i[r.name]=(i[r.name]||0)+1/(n+c+1)}),Object.entries(i).map(([r,c])=>({name:r,score:c})).sort((r,c)=>c.score-r.score).slice(0,s)}async function Ga(t,e={}){let{topK:o=3,minScore:n=.1}=e,s=qa(t,{topK:o,minScore:n}),i=s;if(process.env.NEX_BRAIN_EMBEDDINGS!=="false")try{if(await Da()){let c=await Ba(t,{topK:o});i=Ha(s,c,{topK:o})}}catch{}return i.map(r=>{let c=La(r.name),l=(c.body||c.content||"").slice(0,300).replace(/\n+/g," ")+"...";return{name:r.name,score:r.score,content:c.content,excerpt:l}})}async function _m(t){if(!t||!t.trim())return"";let e=Ze.join(process.cwd(),".nex","brain");if(!se.existsSync(e)||dn().length===0)return"";let n;try{n=await Ga(t,{topK:3})}catch{return""}if(!n||n.length===0)return"";let s;try{s=Pe().estimateTokens}catch{s=l=>Math.ceil(l.length/4)}let i=25e3,r=[],c=0;for(let l of n){let u=l.content||"",d=s(u);if(c+d>i){let m=i-c;if(m<100)break;let h=m/d;u=u.slice(0,Math.floor(u.length*h))+`
169
169
  ...(truncated)`}let f=typeof l.score=="number"?l.score.toFixed(2):String(l.score);if(r.push(`--- ${l.name} (relevance: ${f}) ---
170
- ${u}`),c+=o(u),c>=i)break}return r.length===0?"":`KNOWLEDGE BASE (auto-selected):
170
+ ${u}`),c+=s(u),c>=i)break}return r.length===0?"":`KNOWLEDGE BASE (auto-selected):
171
171
 
172
172
  ${r.join(`
173
173
 
174
- `)}`}Ga.exports={getBrainDir:jt,listDocuments:dn,readDocument:Pa,writeDocument:gm,removeDocument:ym,buildIndex:xo,getIndex:La,query:Ha,getBrainContext:_m,isEmbeddingAvailable:ja,generateEmbedding:Eo,buildEmbeddingIndex:Ua,semanticQuery:Wa,cosineSimilarity:Da,_keywordQuery:Ia,_extractKeywords:ko,_chunkText:Fa,parseFrontmatter:fn,tokenize:is,_fuseResults:Ba}});var Ue=L((D$,nc)=>{var oe=require("fs").promises,za=require("fs"),ve=require("path"),ie=require("util").promisify(require("child_process").exec),Ka=require("util").promisify(require("child_process").execFile),{spawnSync:km}=require("child_process"),To=require("axios"),{isForbidden:vm,isDangerous:Sm,isCritical:Ya,confirm:Be}=Fe(),{showClaudeDiff:as,showClaudeNewFile:Em,showEditDiff:I$,confirmFileChange:pn}=Mi(),{C:I,Spinner:Za,getToolSpinnerText:Tm}=ce(),{isGitRepo:Co,getCurrentBranch:Ja,getStatus:Cm,getDiff:Rm}=yt(),{recordChange:cs}=Pt(),{fuzzyFindText:Xa,findMostSimilar:Ao}=sa(),{runDiagnostics:hn}=ra(),{findFileInIndex:Am,getFileIndex:q$}=co(),{resolveProfile:He,sshExec:at,scpUpload:Om,scpDownload:Nm}=qt(),{resolveDeployConfig:Mm,loadDeployConfigs:j$}=po(),Pm=/^(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/,Lm=/^ssh\s/,Im=/^ssh(?:\s+-\S+)*\s+\S+@?\S+\s+["']?[^-]/;async function ls(t){if(!t)return{fixedPath:null,message:""};let e=t.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),s=ke(e);if(s&&await oe.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=ve.extname(t);if(!o)for(let r of n){let c=ke(t+r);if(c&&await oe.access(c).then(()=>!0).catch(()=>!1))return{fixedPath:c,message:`(auto-fixed: added ${r} extension)`}}if(o){let r=t.replace(/\.[^.]+$/,"");for(let c of n){if(c===o)continue;let l=ke(r+c);if(l&&await oe.access(l).then(()=>!0).catch(()=>!1))return{fixedPath:l,message:`(auto-fixed: ${o} \u2192 ${c})`}}}let i=ve.basename(t);if(i&&i.length>2)try{let r=Am(i).map(c=>ke(c));if(r.length===1)return{fixedPath:r[0],message:`(auto-fixed: found ${i} at ${ve.relative(process.cwd(),r[0])})`};if(r.length>1&&r.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
174
+ `)}`}za.exports={getBrainDir:jt,listDocuments:dn,readDocument:La,writeDocument:gm,removeDocument:ym,buildIndex:_o,getIndex:Ia,query:Ga,getBrainContext:_m,isEmbeddingAvailable:Da,generateEmbedding:To,buildEmbeddingIndex:Wa,semanticQuery:Ba,cosineSimilarity:Fa,_keywordQuery:qa,_extractKeywords:vo,_chunkText:Ua,parseFrontmatter:fn,tokenize:is,_fuseResults:Ha}});var Ue=L((F$,sc)=>{var oe=require("fs").promises,Ka=require("fs"),ve=require("path"),ie=require("util").promisify(require("child_process").exec),Ya=require("util").promisify(require("child_process").execFile),{spawnSync:km}=require("child_process"),Co=require("axios"),{isForbidden:vm,isDangerous:Sm,isCritical:Ja,confirm:Be}=Fe(),{showClaudeDiff:as,showClaudeNewFile:Em,showEditDiff:q$,confirmFileChange:pn}=Pi(),{C:I,Spinner:ec,getToolSpinnerText:Tm}=ce(),{isGitRepo:Ro,getCurrentBranch:Xa,getStatus:Cm,getDiff:Rm}=yt(),{recordChange:cs}=Pt(),{fuzzyFindText:Va,findMostSimilar:Oo}=oa(),{runDiagnostics:hn}=ia(),{findFileInIndex:Am,getFileIndex:j$}=lo(),{resolveProfile:He,sshExec:at,scpUpload:Om,scpDownload:Nm}=qt(),{resolveDeployConfig:Mm,loadDeployConfigs:D$}=ho(),Pm=/^(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/,Lm=/^ssh\s/,Im=/^ssh(?:\s+-\S+)*\s+\S+@?\S+\s+["']?[^-]/;async function ls(t){if(!t)return{fixedPath:null,message:""};let e=t.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),o=ke(e);if(o&&await oe.access(o).then(()=>!0).catch(()=>!1))return{fixedPath:o,message:`(auto-fixed path: ${t} \u2192 ${e})`};let n=[".js",".ts",".jsx",".tsx",".mjs",".cjs",".json"],s=ve.extname(t);if(!s)for(let r of n){let c=ke(t+r);if(c&&await oe.access(c).then(()=>!0).catch(()=>!1))return{fixedPath:c,message:`(auto-fixed: added ${r} extension)`}}if(s){let r=t.replace(/\.[^.]+$/,"");for(let c of n){if(c===s)continue;let l=ke(r+c);if(l&&await oe.access(l).then(()=>!0).catch(()=>!1))return{fixedPath:l,message:`(auto-fixed: ${s} \u2192 ${c})`}}}let i=ve.basename(t);if(i&&i.length>2)try{let r=Am(i).map(c=>ke(c));if(r.length===1)return{fixedPath:r[0],message:`(auto-fixed: found ${i} at ${ve.relative(process.cwd(),r[0])})`};if(r.length>1&&r.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
175
175
  ${r.map(l=>ve.relative(process.cwd(),l)).map(l=>` - ${l}`).join(`
176
- `)}`}}catch{}return{fixedPath:null,message:""}}function qm(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 ec(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"),s.length===0?t:t+`
176
+ `)}`}}catch{}return{fixedPath:null,message:""}}function qm(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 tc(t,e){let o=[];if(/command not found|not recognized/i.test(t)){let n=e.match(/^(\S+)/),s=n?n[1]:"";/^(npx|npm|node|yarn|pnpm|bun)$/.test(s)?o.push("HINT: Node.js/npm may not be in PATH. Check your Node.js installation."):/^(python|python3|pip|pip3)$/.test(s)?o.push("HINT: Python may not be installed. Try: brew install python3 (macOS) or apt install python3 (Linux)"):o.push(`HINT: "${s}" 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 '([^']+)'/),s=n?n[1]:"";s&&!s.startsWith(".")&&!s.startsWith("/")?o.push(`HINT: Missing npm package "${s}". Run: npm install ${s}`):o.push("HINT: Module not found. Check the import path or run npm install.")}if(/permission denied|EACCES/i.test(t)&&o.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+)/),s=n?n[1]||n[2]:"";o.push(`HINT: Port ${s||""} is already in use. Kill the process or use a different port.`)}if(/SyntaxError|Unexpected token/i.test(t)&&o.push("HINT: Syntax error in the code. Check the file at the line number shown above."),/TS\d{4}:/i.test(t)&&o.push("HINT: TypeScript compilation error. Fix the type issue at the indicated line."),/Test Suites:.*failed|Tests:.*failed/i.test(t)&&o.push("HINT: Test failures detected. Read the error output above to identify failing tests."),/fatal: not a git repository/i.test(t)&&o.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+)\)/),s=n?parseInt(n[1],10):null;s===6||/Could not resolve host/i.test(t)?o.push("HINT: Hostname could not be resolved. Check DNS or use an IP address directly."):s===7||/Failed to connect|Connection refused/i.test(t)?o.push("HINT: Service not running or port wrong. Check if the service is up and the port is correct."):s===22||/HTTP error/i.test(t)?o.push("HINT: HTTP 4xx/5xx response. The endpoint exists but returned an error status."):s===28||/timed out/i.test(t)?o.push("HINT: Request timed out. The host may be unreachable or the service is slow."):(s===35||/SSL.*error/i.test(t))&&o.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+)/),s=n?n[1]:"";o.push(`HINT: SSH remote port forwarding failed for port ${s}. The port may already be bound on the server. Check with: ssh server "ss -tuln | grep ${s}" and kill any lingering process with that port.`)}return/bind.*Cannot assign requested address|Address already in use/i.test(t)&&o.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)&&o.push("HINT: SSH connection timed out. Check if the host is reachable: ping <host> and verify the port with: nc -zv <host> 22"),o.length===0?t:t+`
177
177
 
178
- `+s.join(`
179
- `)}function tc(t,e,s){let n=Ao(t,e);if(!n)return null;let o=Math.max(3,Math.ceil(e.length*.05));return n.distance>o?null:{autoFixed:!0,matchText:n.text,content:t.split(n.text).join(s),distance:n.distance,line:n.line}}var Va=!1,bt=null;function jm(){bt&&(bt(),bt=null)}var Oo=null;function Dm(t){Oo=t}async function Ro(){if(!Va){Va=!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 Fm=[/\.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 ke(t){let e=ve.isAbsolute(t)?ve.resolve(t):ve.resolve(process.cwd(),t);for(let s of Fm)if(s.test(e))return null;return e}var Um=[{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 gn(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,i="kubectl";if(o&&(i+=` --context ${o}`),i+=` ${t}`,n){let r=i.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`ssh -o ConnectTimeout=10 -o BatchMode=yes ${n} "${r}"`}return i}async function Qa(t,e,s={}){switch(t){case"bash":{let n=e.command,o=vm(n);if(o){let u=qm(n);return`BLOCKED: Command matches forbidden pattern: ${o}${u?`
180
- HINT: ${u}`:""}`}if(s.autoConfirm?Ya(n):Sm(n)){let u=Ya(n)?" \u26D4 Critical command":" \u26A0 Dangerous command";if(console.log(`
181
- ${I.yellow}${u}: ${n}${I.reset}`),!await Be(" Execute?"))return"CANCELLED: User declined to execute this command."}let r=process.cwd();try{za.accessSync(r)}catch{r=require("os").homedir(),s.silent||console.log(`${I.yellow} \u26A0 Working directory no longer exists \u2014 running in ${r}${I.reset}`)}let c=Lm.test(n.trim())&&!Im.test(n.trim());if(Pm.test(n.trim())||c){s.silent||console.log(`${I.dim} \u25B6 interactive: ${n}${I.reset}`);let u=km("sh",["-c",n],{stdio:"inherit",cwd:r});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 Za(`Running: ${n.substring(0,60)}${n.length>60?"...":""}`);l&&l.start();try{let{stdout:u,stderr:d}=await ie(n,{cwd:r,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),f=ec(d,n);return`EXIT ${u.code||1}
178
+ `+o.join(`
179
+ `)}function nc(t,e,o){let n=Oo(t,e);if(!n)return null;let s=Math.max(3,Math.ceil(e.length*.05));return n.distance>s?null:{autoFixed:!0,matchText:n.text,content:t.split(n.text).join(o),distance:n.distance,line:n.line}}var Qa=!1,bt=null;function jm(){bt&&(bt(),bt=null)}var No=null;function Dm(t){No=t}async function Ao(){if(!Qa){Qa=!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 Fm=[/\.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 ke(t){let e=ve.isAbsolute(t)?ve.resolve(t):ve.resolve(process.cwd(),t);for(let o of Fm)if(o.test(e))return null;return e}var Um=[{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 gn(t,{server:e,context:o}={}){let n=e?e.replace(/[^a-zA-Z0-9@._-]/g,""):null,s=o?o.replace(/[^a-zA-Z0-9._/-]/g,""):null,i="kubectl";if(s&&(i+=` --context ${s}`),i+=` ${t}`,n){let r=i.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`ssh -o ConnectTimeout=10 -o BatchMode=yes ${n} "${r}"`}return i}async function Za(t,e,o={}){switch(t){case"bash":{let n=e.command,s=vm(n);if(s){let u=qm(n);return`BLOCKED: Command matches forbidden pattern: ${s}${u?`
180
+ HINT: ${u}`:""}`}if(o.autoConfirm?Ja(n):Sm(n)){let u=Ja(n)?" \u26D4 Critical command":" \u26A0 Dangerous command";if(console.log(`
181
+ ${I.yellow}${u}: ${n}${I.reset}`),!await Be(" Execute?"))return"CANCELLED: User declined to execute this command."}let r=process.cwd();try{Ka.accessSync(r)}catch{r=require("os").homedir(),o.silent||console.log(`${I.yellow} \u26A0 Working directory no longer exists \u2014 running in ${r}${I.reset}`)}let c=Lm.test(n.trim())&&!Im.test(n.trim());if(Pm.test(n.trim())||c){o.silent||console.log(`${I.dim} \u25B6 interactive: ${n}${I.reset}`);let u=km("sh",["-c",n],{stdio:"inherit",cwd:r});return u.error?`ERROR: ${u.error.message}`:u.status===0?"(interactive command completed successfully)":`(interactive command exited with code ${u.status})`}let l=o.silent?null:new ec(`Running: ${n.substring(0,60)}${n.length>60?"...":""}`);l&&l.start();try{let{stdout:u,stderr:d}=await ie(n,{cwd:r,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),f=tc(d,n);return`EXIT ${u.code||1}
182
182
  ${f}`}}case"read_file":{let n=ke(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await oe.access(n).then(()=>!0).catch(()=>!1)){let m=await ls(e.path);if(m.fixedPath)n=m.fixedPath,console.log(`${I.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ve.relative(process.cwd(),n)}${I.reset}`);else return`ERROR: File not found: ${e.path}${m.message?`
183
- `+m.message:""}`}let i=Buffer.alloc(8192),r=await za.promises.open(n,"r"),{bytesRead:c}=await r.read(i,0,8192,0);await r.close();for(let m=0;m<c;m++)if(i[m]===0)return`ERROR: ${n} is a binary file (not readable as text)`;let l=await oe.readFile(n,"utf-8");if(!l&&(await oe.stat(n)).size>0)return`WARNING: ${n} is empty or unreadable`;let u=l.split(`
183
+ `+m.message:""}`}let i=Buffer.alloc(8192),r=await Ka.promises.open(n,"r"),{bytesRead:c}=await r.read(i,0,8192,0);await r.close();for(let m=0;m<c;m++)if(i[m]===0)return`ERROR: ${n} is a binary file (not readable as text)`;let l=await oe.readFile(n,"utf-8");if(!l&&(await oe.stat(n)).size>0)return`WARNING: ${n} is empty or unreadable`;let u=l.split(`
184
184
  `),d=(e.line_start||1)-1,f=e.line_end||u.length;return u.slice(d,f).map((m,h)=>`${d+h+1}: ${m}`).join(`
185
- `)}case"write_file":{await Ro();let n=ke(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let o=await oe.access(n).then(()=>!0).catch(()=>!1),i=null;if(s.autoConfirm)o&&(i=await oe.readFile(n,"utf-8"));else if(o){i=await oe.readFile(n,"utf-8");let l=await hn(n,e.content);if(as(n,i,e.content,{annotations:l}),!await pn("Overwrite"))return"CANCELLED: User declined to overwrite file."}else{let l=await hn(n,e.content);if(Em(n,e.content,{annotations:l}),!await pn("Create"))return"CANCELLED: User declined to create file."}let r=ve.dirname(n);return await oe.access(r).then(()=>!0).catch(()=>!1)||await oe.mkdir(r,{recursive:!0}),await oe.writeFile(n,e.content,"utf-8"),cs("write_file",n,i,e.content),`Written: ${n} (${e.content.length} chars)`}case"edit_file":{await Ro();let n=ke(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await oe.access(n).then(()=>!0).catch(()=>!1)){let d=await ls(e.path);if(d.fixedPath)n=d.fixedPath,console.log(`${I.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ve.relative(process.cwd(),n)}${I.reset}`);else return`ERROR: File not found: ${e.path}${d.message?`
186
- `+d.message:""}`}let i=await oe.readFile(n,"utf-8"),r=e.old_text,c=!1,l=!1;if(!i.includes(e.old_text)){let d=Xa(i,e.old_text);if(d)r=d,c=!0,console.log(`${I.dim} \u2713 fuzzy whitespace match applied${I.reset}`);else{let f=tc(i,e.old_text,e.new_text);if(f){if(!s.autoConfirm){let p=await hn(n,f.content);if(as(n,i,f.content,{annotations:p}),!await pn(`Apply (auto-fix, line ${f.line}, distance ${f.distance})`))return"CANCELLED: User declined to apply edit."}await oe.writeFile(n,f.content,"utf-8"),cs("edit_file",n,i,f.content);let h=f.matchText.length>80?f.matchText.substring(0,77)+"...":f.matchText;return console.log(`${I.dim} \u2713 auto-fixed edit: line ${f.line}, distance ${f.distance}${I.reset}`),`Edited: ${n} (auto-fixed, line ${f.line}, distance ${f.distance}, matched: "${h}")`}let m=Ao(i,e.old_text);return m?`ERROR: old_text not found in ${n}
185
+ `)}case"write_file":{await Ao();let n=ke(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let s=await oe.access(n).then(()=>!0).catch(()=>!1),i=null;if(o.autoConfirm)s&&(i=await oe.readFile(n,"utf-8"));else if(s){i=await oe.readFile(n,"utf-8");let l=await hn(n,e.content);if(as(n,i,e.content,{annotations:l}),!await pn("Overwrite"))return"CANCELLED: User declined to overwrite file."}else{let l=await hn(n,e.content);if(Em(n,e.content,{annotations:l}),!await pn("Create"))return"CANCELLED: User declined to create file."}let r=ve.dirname(n);return await oe.access(r).then(()=>!0).catch(()=>!1)||await oe.mkdir(r,{recursive:!0}),await oe.writeFile(n,e.content,"utf-8"),cs("write_file",n,i,e.content),`Written: ${n} (${e.content.length} chars)`}case"edit_file":{await Ao();let n=ke(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await oe.access(n).then(()=>!0).catch(()=>!1)){let d=await ls(e.path);if(d.fixedPath)n=d.fixedPath,console.log(`${I.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ve.relative(process.cwd(),n)}${I.reset}`);else return`ERROR: File not found: ${e.path}${d.message?`
186
+ `+d.message:""}`}let i=await oe.readFile(n,"utf-8"),r=e.old_text,c=!1,l=!1;if(!i.includes(e.old_text)){let d=Va(i,e.old_text);if(d)r=d,c=!0,console.log(`${I.dim} \u2713 fuzzy whitespace match applied${I.reset}`);else{let f=nc(i,e.old_text,e.new_text);if(f){if(!o.autoConfirm){let p=await hn(n,f.content);if(as(n,i,f.content,{annotations:p}),!await pn(`Apply (auto-fix, line ${f.line}, distance ${f.distance})`))return"CANCELLED: User declined to apply edit."}await oe.writeFile(n,f.content,"utf-8"),cs("edit_file",n,i,f.content);let h=f.matchText.length>80?f.matchText.substring(0,77)+"...":f.matchText;return console.log(`${I.dim} \u2713 auto-fixed edit: line ${f.line}, distance ${f.distance}${I.reset}`),`Edited: ${n} (auto-fixed, line ${f.line}, distance ${f.distance}, matched: "${h}")`}let m=Oo(i,e.old_text);return m?`ERROR: old_text not found in ${n}
187
187
  Most similar text (line ${m.line}, distance ${m.distance}):
188
- ${m.text}`:`ERROR: old_text not found in ${n}`}}if(!s.autoConfirm){let d=i.split(r).join(e.new_text),f=await hn(n,d);if(as(n,i,d,{annotations:f}),!await pn(c?"Apply (fuzzy match)":"Apply"))return"CANCELLED: User declined to apply edit."}let u=i.split(r).join(e.new_text);return await oe.writeFile(n,u,"utf-8"),cs("edit_file",n,i,u),c?`Edited: ${n} (fuzzy match)`:`Edited: ${n}`}case"list_directory":{let n=ke(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await oe.access(n).then(()=>!0).catch(()=>!1)){let u=e.path.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),d=ke(u),f=await oe.access(d).then(()=>!0).catch(()=>!1);if(d&&f)n=d;else return`ERROR: Directory not found: ${e.path}`}let i=e.max_depth||2,r=null;if(e.pattern)try{let u=e.pattern.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");r=new RegExp(`^${u}$`)}catch{return`ERROR: Invalid pattern: ${e.pattern}`}let c=[],l=async(u,d,f)=>{if(d>i)return;let m;try{m=await oe.readdir(u,{withFileTypes:!0})}catch{return}m=m.filter(h=>!h.name.startsWith(".")&&h.name!=="node_modules");for(let h of m){if(r&&!h.isDirectory()&&!r.test(h.name))continue;let p=h.isDirectory()?"/":"";c.push(`${f}${h.name}${p}`),h.isDirectory()&&await l(ve.join(u,h.name),d+1,f+" ")}};return await l(n,1,""),c.join(`
189
- `)||"(empty)"}case"search_files":{let n=ke(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:i}=await Ka("grep",o,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),r=i.split("\0"),c=[];for(let l=0;l<r.length;l+=2){let u=r[l],d=r[l+1];if(u&&d){let f=d.split(`
188
+ ${m.text}`:`ERROR: old_text not found in ${n}`}}if(!o.autoConfirm){let d=i.split(r).join(e.new_text),f=await hn(n,d);if(as(n,i,d,{annotations:f}),!await pn(c?"Apply (fuzzy match)":"Apply"))return"CANCELLED: User declined to apply edit."}let u=i.split(r).join(e.new_text);return await oe.writeFile(n,u,"utf-8"),cs("edit_file",n,i,u),c?`Edited: ${n} (fuzzy match)`:`Edited: ${n}`}case"list_directory":{let n=ke(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await oe.access(n).then(()=>!0).catch(()=>!1)){let u=e.path.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),d=ke(u),f=await oe.access(d).then(()=>!0).catch(()=>!1);if(d&&f)n=d;else return`ERROR: Directory not found: ${e.path}`}let i=e.max_depth||2,r=null;if(e.pattern)try{let u=e.pattern.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");r=new RegExp(`^${u}$`)}catch{return`ERROR: Invalid pattern: ${e.pattern}`}let c=[],l=async(u,d,f)=>{if(d>i)return;let m;try{m=await oe.readdir(u,{withFileTypes:!0})}catch{return}m=m.filter(h=>!h.name.startsWith(".")&&h.name!=="node_modules");for(let h of m){if(r&&!h.isDirectory()&&!r.test(h.name))continue;let p=h.isDirectory()?"/":"";c.push(`${f}${h.name}${p}`),h.isDirectory()&&await l(ve.join(u,h.name),d+1,f+" ")}};return await l(n,1,""),c.join(`
189
+ `)||"(empty)"}case"search_files":{let n=ke(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let s=["-rn","--null","-H"];e.file_pattern&&s.push(`--include=${e.file_pattern}`),s.push(e.pattern,n);try{let{stdout:i}=await Ya("grep",s,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),r=i.split("\0"),c=[];for(let l=0;l<r.length;l+=2){let u=r[l],d=r[l+1];if(u&&d){let f=d.split(`
190
190
  `).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(`
191
- `)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let o=process.cwd(),i=e.path?ke(e.path):o,r=e.pattern,c=k=>{let E=k.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"(.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");return new RegExp(`^${E}$`)},l=c(r),u=r.split("/").pop(),d=c(u),{getFileIndex:f,getIndexedCwd:m,refreshIndex:h,isIndexValid:p}=co(),g=f(),$=m();p(i)||(await h(i),g=f());let y=g.filter(k=>l.test(k)||d.test(ve.basename(k))).map(k=>ve.join(i,k));if(y.length===0)return"(no matches)";let x=y.length>200,T=y.slice(0,200).join(`
191
+ `)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let s=process.cwd(),i=e.path?ke(e.path):s,r=e.pattern,c=k=>{let E=k.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"(.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");return new RegExp(`^${E}$`)},l=c(r),u=r.split("/").pop(),d=c(u),{getFileIndex:f,getIndexedCwd:m,refreshIndex:h,isIndexValid:p}=lo(),g=f(),$=m();p(i)||(await h(i),g=f());let y=g.filter(k=>l.test(k)||d.test(ve.basename(k))).map(k=>ve.join(i,k));if(y.length===0)return"(no matches)";let x=y.length>200,T=y.slice(0,200).join(`
192
192
  `);return x?`${T}
193
193
 
194
- \u26A0 Results truncated at 200. Use a more specific pattern.`:T}case"grep":{let n=e.path?ke(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:i}=await Ka("grep",o,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),r=i.split("\0"),c=[];for(let l=0;l<r.length;l+=2){let u=r[l],d=r[l+1];if(u&&d){let f=d.split(`
194
+ \u26A0 Results truncated at 200. Use a more specific pattern.`:T}case"grep":{let n=e.path?ke(e.path):process.cwd(),s=["-rn","-E","--null","-H"];e.ignore_case&&s.push("-i"),e.include&&s.push(`--include=${e.include}`),s.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage"),s.push(e.pattern,n);try{let{stdout:i}=await Ya("grep",s,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),r=i.split("\0"),c=[];for(let l=0;l<r.length;l+=2){let u=r[l],d=r[l+1];if(u&&d){let f=d.split(`
195
195
  `).filter(m=>m.trim());for(let m of f)if(c.push(`${u}:${m}`),c.length>=100)break}if(c.length>=100)break}return c.join(`
196
- `).trim()||"(no matches)"}catch(i){return i.code===2?`ERROR: Invalid regex pattern: ${e.pattern}`:"(no matches)"}}case"patch_file":{await Ro();let n=ke(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await oe.access(n).then(()=>!0).catch(()=>!1)){let m=await ls(e.path);if(m.fixedPath)n=m.fixedPath,console.log(`${I.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ve.relative(process.cwd(),n)}${I.reset}`);else return`ERROR: File not found: ${e.path}${m.message?`
197
- `+m.message:""}`}let i=e.patches;if(!Array.isArray(i)||i.length===0)return"ERROR: No patches provided";let r=await oe.readFile(n,"utf-8"),c=[],l=!1,u=!1;for(let m=0;m<i.length;m++){let{old_text:h,new_text:p}=i[m];if(r.includes(h))c.push({old_text:h,new_text:p});else{let g=Xa(r,h);if(g)c.push({old_text:g,new_text:p}),l=!0;else{let $=Ao(r,h);if($){let y=Math.max(3,Math.ceil(h.length*.05));if($.distance<=y)c.push({old_text:$.text,new_text:p}),u=!0;else return`ERROR: Patch ${m+1} old_text not found in ${n}
196
+ `).trim()||"(no matches)"}catch(i){return i.code===2?`ERROR: Invalid regex pattern: ${e.pattern}`:"(no matches)"}}case"patch_file":{await Ao();let n=ke(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await oe.access(n).then(()=>!0).catch(()=>!1)){let m=await ls(e.path);if(m.fixedPath)n=m.fixedPath,console.log(`${I.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ve.relative(process.cwd(),n)}${I.reset}`);else return`ERROR: File not found: ${e.path}${m.message?`
197
+ `+m.message:""}`}let i=e.patches;if(!Array.isArray(i)||i.length===0)return"ERROR: No patches provided";let r=await oe.readFile(n,"utf-8"),c=[],l=!1,u=!1;for(let m=0;m<i.length;m++){let{old_text:h,new_text:p}=i[m];if(r.includes(h))c.push({old_text:h,new_text:p});else{let g=Va(r,h);if(g)c.push({old_text:g,new_text:p}),l=!0;else{let $=Oo(r,h);if($){let y=Math.max(3,Math.ceil(h.length*.05));if($.distance<=y)c.push({old_text:$.text,new_text:p}),u=!0;else return`ERROR: Patch ${m+1} old_text not found in ${n}
198
198
  Most similar text (line ${$.line}, distance ${$.distance}):
199
- ${$.text}`}else return`ERROR: Patch ${m+1} old_text not found in ${n}`}}}let d=r;for(let{old_text:m,new_text:h}of c)d=d.split(m).join(h);if(!s.autoConfirm){let m=await hn(n,d);if(as(n,r,d,{annotations:m}),!await pn(l?"Apply patches (fuzzy match)":"Apply patches"))return"CANCELLED: User declined to apply patches."}await oe.writeFile(n,d,"utf-8"),cs("patch_file",n,r,d);let f=u?" (auto-fixed)":l?" (fuzzy match)":"";return`Patched: ${n} (${i.length} replacements)${f}`}case"web_fetch":{let n=e.url,o=e.max_length||1e4;try{let i=await To.get(n,{timeout:15e3,maxContentLength:1048576,responseType:"text",headers:{"User-Agent":"nex-code/0.2.0"}});return(typeof i.data=="string"?i.data:JSON.stringify(i.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(i){return`ERROR: Failed to fetch ${n}: ${i.message}`}}case"web_search":{let n=e.max_results||5;if(process.env.PERPLEXITY_API_KEY)try{let o=await To.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"}}),i=o.data?.choices?.[0]?.message?.content||"",r=o.data?.citations||[],c=`[Perplexity grounded search]
199
+ ${$.text}`}else return`ERROR: Patch ${m+1} old_text not found in ${n}`}}}let d=r;for(let{old_text:m,new_text:h}of c)d=d.split(m).join(h);if(!o.autoConfirm){let m=await hn(n,d);if(as(n,r,d,{annotations:m}),!await pn(l?"Apply patches (fuzzy match)":"Apply patches"))return"CANCELLED: User declined to apply patches."}await oe.writeFile(n,d,"utf-8"),cs("patch_file",n,r,d);let f=u?" (auto-fixed)":l?" (fuzzy match)":"";return`Patched: ${n} (${i.length} replacements)${f}`}case"web_fetch":{let n=e.url,s=e.max_length||1e4;try{let i=await Co.get(n,{timeout:15e3,maxContentLength:1048576,responseType:"text",headers:{"User-Agent":"nex-code/0.2.0"}});return(typeof i.data=="string"?i.data:JSON.stringify(i.data)).replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim().substring(0,s)||"(empty response)"}catch(i){return`ERROR: Failed to fetch ${n}: ${i.message}`}}case"web_search":{let n=e.max_results||5;if(process.env.PERPLEXITY_API_KEY)try{let s=await Co.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"}}),i=s.data?.choices?.[0]?.message?.content||"",r=s.data?.citations||[],c=`[Perplexity grounded search]
200
200
 
201
201
  ${i}`;return r.length>0&&(c+=`
202
202
 
203
203
  Sources:
204
204
  `+r.slice(0,n).map((l,u)=>`${u+1}. ${l}`).join(`
205
- `)),c}catch(o){console.error(`${I.dim} Perplexity search failed (${o.message}), falling back to DuckDuckGo${I.reset}`)}try{let i=(await To.get("https://html.duckduckgo.com/html/",{params:{q:e.query},timeout:1e4,responseType:"text",headers:{"User-Agent":"nex-code/0.2.0"}})).data,r=[],c=/<a[^>]*class="result__a"[^>]*href="([^"]*)"[^>]*>([\s\S]*?)<\/a>/gi,l;for(;(l=c.exec(i))!==null&&r.length<n;){let u=l[1].replace(/.*uddg=/,"").split("&")[0],d=l[2].replace(/<[^>]+>/g,"").trim();try{r.push({title:d,url:decodeURIComponent(u)})}catch{r.push({title:d,url:u})}}return r.length===0?"(no results)":r.map((u,d)=>`${d+1}. ${u.title}
205
+ `)),c}catch(s){console.error(`${I.dim} Perplexity search failed (${s.message}), falling back to DuckDuckGo${I.reset}`)}try{let i=(await Co.get("https://html.duckduckgo.com/html/",{params:{q:e.query},timeout:1e4,responseType:"text",headers:{"User-Agent":"nex-code/0.2.0"}})).data,r=[],c=/<a[^>]*class="result__a"[^>]*href="([^"]*)"[^>]*>([\s\S]*?)<\/a>/gi,l;for(;(l=c.exec(i))!==null&&r.length<n;){let u=l[1].replace(/.*uddg=/,"").split("&")[0],d=l[2].replace(/<[^>]+>/g,"").trim();try{r.push({title:d,url:decodeURIComponent(u)})}catch{r.push({title:d,url:u})}}return r.length===0?"(no results)":r.map((u,d)=>`${d+1}. ${u.title}
206
206
  ${u.url}`).join(`
207
207
 
208
- `)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:n}=sn();try{let o=await n(e.url,{waitFor:e.wait_for}),i=o.links.length>0?`
208
+ `)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:n}=sn();try{let s=await n(e.url,{waitFor:e.wait_for}),i=s.links.length>0?`
209
209
 
210
210
  Links:
211
- `+o.links.map(r=>` ${r.text} \u2192 ${r.href}`).join(`
212
- `):"";return`Title: ${o.title}
213
- URL: ${o.url}
211
+ `+s.links.map(r=>` ${r.text} \u2192 ${r.href}`).join(`
212
+ `):"";return`Title: ${s.title}
213
+ URL: ${s.url}
214
214
 
215
- ${o.text}${i}`}catch(o){return`ERROR: ${o.message}`}}case"browser_screenshot":{let{browserScreenshot:n}=sn();try{let o=await n(e.url,{width:e.width,height:e.height,fullPage:e.full_page});return`Screenshot saved: ${o.path}
216
- Title: ${o.title}
217
- URL: ${o.url}
215
+ ${s.text}${i}`}catch(s){return`ERROR: ${s.message}`}}case"browser_screenshot":{let{browserScreenshot:n}=sn();try{let s=await n(e.url,{width:e.width,height:e.height,fullPage:e.full_page});return`Screenshot saved: ${s.path}
216
+ Title: ${s.title}
217
+ URL: ${s.url}
218
218
 
219
- To analyze visually, paste the path into your next message: ${o.path}`}catch(o){return`ERROR: ${o.message}`}}case"browser_click":{let{browserClick:n}=sn();try{return await n(e.url,{selector:e.selector,text:e.text})}catch(o){return`ERROR: ${o.message}`}}case"browser_fill":{let{browserFill:n}=sn();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 Oo?new Promise(i=>{bt=()=>i("CANCELLED"),Oo(n,o).then(r=>{bt=null,i(r||"User did not answer")})}):new Promise(i=>{let r=require("readline").createInterface({input:process.stdin,output:process.stdout});bt=()=>{r.close(),i("CANCELLED")};let c=o.length>0?`
220
- ${o.map((l,u)=>` ${u+1}. ${l}`).join(`
219
+ To analyze visually, paste the path into your next message: ${s.path}`}catch(s){return`ERROR: ${s.message}`}}case"browser_click":{let{browserClick:n}=sn();try{return await n(e.url,{selector:e.selector,text:e.text})}catch(s){return`ERROR: ${s.message}`}}case"browser_fill":{let{browserFill:n}=sn();try{return await n(e.url,{selector:e.selector,value:e.value,submit:e.submit})}catch(s){return`ERROR: ${s.message}`}}case"ask_user":{let{question:n,options:s=[]}=e;return No?new Promise(i=>{bt=()=>i("CANCELLED"),No(n,s).then(r=>{bt=null,i(r||"User did not answer")})}):new Promise(i=>{let r=require("readline").createInterface({input:process.stdin,output:process.stdout});bt=()=>{r.close(),i("CANCELLED")};let c=s.length>0?`
220
+ ${s.map((l,u)=>` ${u+1}. ${l}`).join(`
221
221
  `)}
222
222
  `:"";console.log(`
223
- ${I.cyan}${I.bold} ? ${n}${I.reset}${c}`),r.question(`${I.cyan} > ${I.reset}`,l=>{bt=null,r.close(),i(l.trim()||"(no response)")})})}case"git_status":{if(!await Co())return"ERROR: Not a git repository";let n=await Ja()||"(detached)",o=await Cm();if(o.length===0)return`Branch: ${n}
224
- Clean working tree (no changes)`;let i=[`Branch: ${n}`,`Changed files (${o.length}):`];for(let r of o){let c=r.status==="M"?"modified":r.status==="A"?"added":r.status==="D"?"deleted":r.status==="??"?"untracked":r.status;i.push(` ${c}: ${r.file}`)}return i.join(`
225
- `)}case"git_diff":{if(!await Co())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 Rm(!!e.staged);return n||"(no diff)"}case"git_log":{if(!await Co())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:i,renderTaskList:r,hasActiveTasks:c}=ns(),{getActiveTaskProgress:l}=ce(),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(`
223
+ ${I.cyan}${I.bold} ? ${n}${I.reset}${c}`),r.question(`${I.cyan} > ${I.reset}`,l=>{bt=null,r.close(),i(l.trim()||"(no response)")})})}case"git_status":{if(!await Ro())return"ERROR: Not a git repository";let n=await Xa()||"(detached)",s=await Cm();if(s.length===0)return`Branch: ${n}
224
+ Clean working tree (no changes)`;let i=[`Branch: ${n}`,`Changed files (${s.length}):`];for(let r of s){let c=r.status==="M"?"modified":r.status==="A"?"added":r.status==="D"?"deleted":r.status==="??"?"untracked":r.status;i.push(` ${c}: ${r.file}`)}return i.join(`
225
+ `)}case"git_diff":{if(!await Ro())return"ERROR: Not a git repository";let n;if(e.file){let s=["diff"];e.staged&&s.push("--cached"),s.push("--",e.file);try{n=execFileSync("git",s,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()}catch{n=""}}else n=await Rm(!!e.staged);return n||"(no diff)"}case"git_log":{if(!await Ro())return"ERROR: Not a git repository";let s=["log","--oneline",`-${Math.min(e.count||10,50)}`];e.file&&s.push("--",e.file);try{return execFileSync("git",s,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()||"(no commits)"}catch{return"(no commits)"}}case"task_list":{let{createTasks:n,updateTask:s,getTaskList:i,renderTaskList:r,hasActiveTasks:c}=ns(),{getActiveTaskProgress:l}=ce(),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(`
226
226
  `+r()),`Created task list "${e.name}" with ${d.length} tasks:
227
227
  `+d.map(f=>` ${f.id}: ${f.description}`).join(`
228
- `)}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(`
228
+ `)}case"update":return!e.task_id||!e.status?"ERROR: task_list update requires task_id and status":s(e.task_id,e.status,e.result)?(u||console.log(`
229
229
  `+r()),`Updated ${e.task_id}: ${e.status}${e.result?" \u2014 "+e.result:""}`):`ERROR: Task not found: ${e.task_id}`;case"get":{let d=i();return d.tasks.length===0?"No active tasks":(u||console.log(`
230
- `+r()),JSON.stringify(d,null,2))}default:return`ERROR: Unknown task_list action: ${e.action}. Use: create, update, get`}}case"spawn_agents":{let{executeSpawnAgents:n}=Na();return n(e)}case"switch_model":{let{setActiveModel:n,getActiveProviderName:o,getActiveModelId:i}=ge();return n(e.model)?`Switched to ${o()}:${i()}`:`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:i}=await ie(`gh ${o.join(" ")}`,{cwd:process.cwd(),timeout:3e4}),r=JSON.parse(i||"[]");return r.length===0?"No workflow runs found.":r.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
+ `+r()),JSON.stringify(d,null,2))}default:return`ERROR: Unknown task_list action: ${e.action}. Use: create, update, get`}}case"spawn_agents":{let{executeSpawnAgents:n}=Ma();return n(e)}case"switch_model":{let{setActiveModel:n,getActiveProviderName:s,getActiveModelId:i}=ge();return n(e.model)?`Switched to ${s()}:${i()}`:`ERROR: Unknown model: ${e.model}. Use /providers to see available models.`}case"gh_run_list":{let n=Math.min(e.limit||10,30),s=["run","list","--limit",String(n),"--json","databaseId,status,conclusion,name,headBranch,createdAt,updatedAt,event"];e.workflow&&s.push("--workflow",e.workflow),e.branch&&s.push("--branch",e.branch),e.status&&s.push("--status",e.status);try{let{stdout:i}=await ie(`gh ${s.join(" ")}`,{cwd:process.cwd(),timeout:3e4}),r=JSON.parse(i||"[]");return r.length===0?"No workflow runs found.":r.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(`
231
231
  `)}catch(i){let r=(i.stderr||i.message||"").toString();return r.includes("not found")||r.includes("not logged")?"ERROR: gh CLI not found or not authenticated. Run: gh auth login":`ERROR: ${r.split(`
232
232
  `)[0]}`}}case"gh_run_view":{if(!e.run_id)return"ERROR: run_id is required";try{if(e.log){let{stdout:r}=await ie(`gh run view ${e.run_id} --log`,{cwd:process.cwd(),timeout:6e4,maxBuffer:5242880});return r.substring(0,8e3)+(r.length>8e3?`
233
- ...(truncated)`:"")}let{stdout:n}=await ie(`gh run view ${e.run_id} --json status,conclusion,name,headBranch,createdAt,updatedAt,jobs`,{cwd:process.cwd(),timeout:3e4}),o=JSON.parse(n),i=[`Run: ${o.name} [${e.run_id}]`,`Branch: ${o.headBranch} Status: ${o.conclusion||o.status}`,`Started: ${o.createdAt} Finished: ${o.updatedAt||"\u2014"}`,"","Jobs:"];for(let r of o.jobs||[]){let c=r.conclusion==="success"?"\u2713":r.conclusion==="failure"?"\u2717":"\u25CB";i.push(` ${c} ${r.name} (${r.conclusion||r.status})`);for(let l of r.steps||[]){if(l.conclusion==="failure"||l.conclusion==="skipped")continue;let u=l.conclusion==="success"?" \u2713":l.conclusion==="failure"?" \u2717":" \u25CB";i.push(` ${u} ${l.name}`)}}return i.join(`
233
+ ...(truncated)`:"")}let{stdout:n}=await ie(`gh run view ${e.run_id} --json status,conclusion,name,headBranch,createdAt,updatedAt,jobs`,{cwd:process.cwd(),timeout:3e4}),s=JSON.parse(n),i=[`Run: ${s.name} [${e.run_id}]`,`Branch: ${s.headBranch} Status: ${s.conclusion||s.status}`,`Started: ${s.createdAt} Finished: ${s.updatedAt||"\u2014"}`,"","Jobs:"];for(let r of s.jobs||[]){let c=r.conclusion==="success"?"\u2713":r.conclusion==="failure"?"\u2717":"\u25CB";i.push(` ${c} ${r.name} (${r.conclusion||r.status})`);for(let l of r.steps||[]){if(l.conclusion==="failure"||l.conclusion==="skipped")continue;let u=l.conclusion==="success"?" \u2713":l.conclusion==="failure"?" \u2717":" \u25CB";i.push(` ${u} ${l.name}`)}}return i.join(`
234
234
  `)}catch(n){return`ERROR: ${(n.stderr||n.message||"").toString().split(`
235
- `)[0]}`}}case"gh_workflow_trigger":{if(!e.workflow)return"ERROR: workflow is required";let{confirm:n}=Fe(),o=e.branch||await Ja()||"main",i=e.inputs?Object.entries(e.inputs).map(([l,u])=>`-f ${l}=${u}`).join(" "):"",r=`gh workflow run ${e.workflow} --ref ${o} ${i}`.trim();if(console.log(`
236
- ${I.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${o}${I.reset}`),!await n(" Trigger?"))return"CANCELLED: User declined to trigger workflow.";try{return await ie(r,{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(`
237
- `)[0]}`}}case"k8s_pods":{let n=e.namespace?`-n ${e.namespace}`:"-A",o=e.label?`-l ${e.label}`:"",i=gn(`get pods ${n} ${o} -o wide`.trim(),e);try{let{stdout:r,stderr:c}=await ie(i,{timeout:3e4,maxBuffer:2097152});return(r||c||"(no pods)").trim()}catch(r){let c=(r.stderr||r.message||"").toString().split(`
238
- `)[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,i=`logs ${e.pod} -n ${n} --tail=${o}`;e.since&&(i+=` --since=${e.since}`),e.container&&(i+=` -c ${e.container}`);let r=gn(i,e);try{let{stdout:c,stderr:l}=await ie(r,{timeout:6e4,maxBuffer:5242880}),u=(c||l||"(no logs)").trim();return u.substring(0,2e4)+(u.length>2e4?`
235
+ `)[0]}`}}case"gh_workflow_trigger":{if(!e.workflow)return"ERROR: workflow is required";let{confirm:n}=Fe(),s=e.branch||await Xa()||"main",i=e.inputs?Object.entries(e.inputs).map(([l,u])=>`-f ${l}=${u}`).join(" "):"",r=`gh workflow run ${e.workflow} --ref ${s} ${i}`.trim();if(console.log(`
236
+ ${I.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${s}${I.reset}`),!await n(" Trigger?"))return"CANCELLED: User declined to trigger workflow.";try{return await ie(r,{cwd:process.cwd(),timeout:3e4}),`Workflow "${e.workflow}" triggered on branch "${s}". Check status with gh_run_list.`}catch(l){return`ERROR: ${(l.stderr||l.message||"").toString().split(`
237
+ `)[0]}`}}case"k8s_pods":{let n=e.namespace?`-n ${e.namespace}`:"-A",s=e.label?`-l ${e.label}`:"",i=gn(`get pods ${n} ${s} -o wide`.trim(),e);try{let{stdout:r,stderr:c}=await ie(i,{timeout:3e4,maxBuffer:2097152});return(r||c||"(no pods)").trim()}catch(r){let c=(r.stderr||r.message||"").toString().split(`
238
+ `)[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",s=e.tail||100,i=`logs ${e.pod} -n ${n} --tail=${s}`;e.since&&(i+=` --since=${e.since}`),e.container&&(i+=` -c ${e.container}`);let r=gn(i,e);try{let{stdout:c,stderr:l}=await ie(r,{timeout:6e4,maxBuffer:5242880}),u=(c||l||"(no logs)").trim();return u.substring(0,2e4)+(u.length>2e4?`
239
239
  ...(truncated)`:"")}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
240
240
  `)[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(`
241
241
  ${I.yellow} \u26A0 kubectl exec into pod: ${e.pod} (ns: ${n})${I.reset}`),console.log(`${I.dim} Command: ${e.command}${I.reset}`),!await Be(" Execute in pod?"))return"CANCELLED: User declined.";let i=`exec ${e.pod} -n ${n}`;e.container&&(i+=` -c ${e.container}`),i+=` -- sh -c ${JSON.stringify(e.command)}`;let r=gn(i,e);try{let{stdout:c,stderr:l}=await ie(r,{timeout:6e4,maxBuffer:2097152});return(c||l||"(no output)").trim()}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
242
242
  `)[0]}`}}case"k8s_apply":{if(!e.file)return"ERROR: file is required";let n=!!e.dry_run;if(!n){let r=e.file;if(console.log(`
243
- ${I.yellow} \u26A0 kubectl apply: ${r}${e.namespace?` (ns: ${e.namespace})`:""}${I.reset}`),!await Be(" 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 i=gn(o,e);try{let{stdout:r,stderr:c}=await ie(i,{timeout:12e4,maxBuffer:2097152});return(r||c||"(no output)").trim()}catch(r){return`ERROR: ${(r.stderr||r.message||"").toString().split(`
243
+ ${I.yellow} \u26A0 kubectl apply: ${r}${e.namespace?` (ns: ${e.namespace})`:""}${I.reset}`),!await Be(" Apply to cluster?"))return"CANCELLED: User declined."}let s=`apply -f ${e.file}`;e.namespace&&(s+=` -n ${e.namespace}`),n&&(s+=" --dry-run=client");let i=gn(s,e);try{let{stdout:r,stderr:c}=await ie(i,{timeout:12e4,maxBuffer:2097152});return(r||c||"(no output)").trim()}catch(r){return`ERROR: ${(r.stderr||r.message||"").toString().split(`
244
244
  `)[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(`
245
245
  ${I.yellow} \u26A0 ${c}: deployment/${e.deployment} (ns: ${n})${I.reset}`),!await Be(` ${c}?`))return"CANCELLED: User declined."}let i=`rollout ${e.action} deployment/${e.deployment} -n ${n}`,r=gn(i,e);try{let{stdout:c,stderr:l}=await ie(r,{timeout:12e4,maxBuffer:2097152});return(c||l||"(no output)").trim()}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
246
- `)[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}=mn(),{name:i,content:r,mode:c}=e;if(c==="create"&&o(i).content)return`ERROR: Document "${i}" already exists. Use mode "update" to overwrite.`;if(c==="append"){let l=o(i),u=l.content?l.content+`
246
+ `)[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:s}=mn(),{name:i,content:r,mode:c}=e;if(c==="create"&&s(i).content)return`ERROR: Document "${i}" already exists. Use mode "update" to overwrite.`;if(c==="append"){let l=s(i),u=l.content?l.content+`
247
247
 
248
- `+r:r;return n(i,u),`Appended to brain document: ${i}.md`}return n(i,r),`${c==="create"?"Created":"Updated"} brain document: ${i}.md`}case"ssh_exec":{if(!e.server)return"ERROR: server is required";if(!e.command)return"ERROR: command is required";let n;try{n=He(e.server)}catch(h){return`ERROR: ${h.message}`}let o=e.command,i=!!e.sudo,r=(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(`
249
- ${I.yellow} \u26A0 Remote command on ${h}: ${o}${I.reset}`),!await Be(" Execute on remote server?"))return"CANCELLED: User declined to execute remote command."}let{stdout:l,stderr:u,exitCode:d,error:f}=await at(n,o,{timeout:r,sudo:i}),m=[l,u].filter(Boolean).join(`
248
+ `+r:r;return n(i,u),`Appended to brain document: ${i}.md`}return n(i,r),`${c==="create"?"Created":"Updated"} brain document: ${i}.md`}case"ssh_exec":{if(!e.server)return"ERROR: server is required";if(!e.command)return"ERROR: command is required";let n;try{n=He(e.server)}catch(h){return`ERROR: ${h.message}`}let s=e.command,i=!!e.sudo,r=(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(s)){let h=n.user?`${n.user}@${n.host}`:n.host;if(console.log(`
249
+ ${I.yellow} \u26A0 Remote command on ${h}: ${s}${I.reset}`),!await Be(" Execute on remote server?"))return"CANCELLED: User declined to execute remote command."}let{stdout:l,stderr:u,exitCode:d,error:f}=await at(n,s,{timeout:r,sudo:i}),m=[l,u].filter(Boolean).join(`
250
250
  `).trim();return d!==0?`EXIT ${d}
251
- ${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 n;try{n=He(e.server)}catch(r){return`ERROR: ${r.message}`}let o=n.user?`${n.user}@${n.host}`:n.host;if(console.log(`
252
- ${I.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${o}:${e.remote_path}${I.reset}`),!await Be(" Upload to remote server?"))return"CANCELLED: User declined upload.";try{return await Om(n,e.local_path,e.remote_path)}catch(r){return`ERROR: ${r.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=He(e.server)}catch(o){return`ERROR: ${o.message}`}try{return await Nm(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",i=e.action==="status",r=null;if(!o)try{r=He(e.server)}catch(l){return`ERROR: ${l.message}`}if(!i){let l=o?"local machine":r.user?`${r.user}@${r.host}`:r.host;if(console.log(`
253
- ${I.yellow} \u26A0 Service: systemctl ${e.action} ${e.service} on ${l}${I.reset}`),!await Be(" 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: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}
251
+ ${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 n;try{n=He(e.server)}catch(r){return`ERROR: ${r.message}`}let s=n.user?`${n.user}@${n.host}`:n.host;if(console.log(`
252
+ ${I.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${s}:${e.remote_path}${I.reset}`),!await Be(" Upload to remote server?"))return"CANCELLED: User declined upload.";try{return await Om(n,e.local_path,e.remote_path)}catch(r){return`ERROR: ${r.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=He(e.server)}catch(s){return`ERROR: ${s.message}`}try{return await Nm(n,e.remote_path,e.local_path)}catch(s){return`ERROR: ${s.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 s=!e.server||e.server==="local"||e.server==="localhost",i=e.action==="status",r=null;if(!s)try{r=He(e.server)}catch(l){return`ERROR: ${l.message}`}if(!i){let l=s?"local machine":r.user?`${r.user}@${r.host}`:r.host;if(console.log(`
253
+ ${I.yellow} \u26A0 Service: systemctl ${e.action} ${e.service} on ${l}${I.reset}`),!await Be(" Execute?"))return"CANCELLED: User declined service action."}let c=`systemctl ${e.action} ${e.service}`;if(s){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}
254
254
  ${f}`}}else{let{stdout:l,stderr:u,exitCode:d,error:f}=await at(r,c,{timeout:15e3,sudo:!0}),m=[l,u].filter(Boolean).join(`
255
255
  `).trim();return d!==0?/not found|loaded.*not-found/i.test(m)?`ERROR: Service "${e.service}" not found on ${r.host}. Check: ssh_exec to run "systemctl list-units --type=service"`:`EXIT ${d}
256
- ${f||m||"(no output)"}`:m||`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,i=e.since?`--since "${e.since}"`:"",r=e.follow?"-f":"",c=`journalctl -u ${e.service} -n ${o} ${i} ${r} --no-pager`.trim().replace(/\s+/g," ");if(n)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}
256
+ ${f||m||"(no output)"}`:m||`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",s=e.lines||50,i=e.since?`--since "${e.since}"`:"",r=e.follow?"-f":"",c=`journalctl -u ${e.service} -n ${s} ${i} ${r} --no-pager`.trim().replace(/\s+/g," ");if(n)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}
257
257
  ${(p.stderr||p.message||"").toString().trim()}`}let l;try{l=He(e.server)}catch(p){return`ERROR: ${p.message}`}let{stdout:u,stderr:d,exitCode:f,error:m}=await at(l,c,{timeout:2e4}),h=[u,d].filter(Boolean).join(`
258
258
  `).trim();return f!==0?`EXIT ${f}
259
259
  ${m||h||"(no output)"}`:h||"(no log output)"}case"container_list":{let n=!e.server||e.server==="local"||e.server==="localhost",i=`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:m,stderr:h}=await ie(i,{timeout:1e4});return(m||h||"(no containers)").trim()}catch(m){return`EXIT ${m.code||1}
260
260
  ${(m.stderr||m.message||"").toString().trim()}`}let r;try{r=He(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:c,stderr:l,exitCode:u,error:d}=await at(r,i,{timeout:15e3}),f=[c,l].filter(Boolean).join(`
261
261
  `).trim();return u!==0?`EXIT ${u}
262
- ${d||f}`:f||"(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,i=e.since?`--since "${e.since}"`:"",r=`docker logs --tail ${o} ${i} ${e.container} 2>&1`.trim().replace(/\s+/g," ");if(n)try{let{stdout:h,stderr:p}=await ie(r,{timeout:15e3});return(h||p||"(no log output)").trim()}catch(h){return`EXIT ${h.code||1}
262
+ ${d||f}`:f||"(no containers)"}case"container_logs":{if(!e.container)return"ERROR: container is required";let n=!e.server||e.server==="local"||e.server==="localhost",s=e.lines||50,i=e.since?`--since "${e.since}"`:"",r=`docker logs --tail ${s} ${i} ${e.container} 2>&1`.trim().replace(/\s+/g," ");if(n)try{let{stdout:h,stderr:p}=await ie(r,{timeout:15e3});return(h||p||"(no log output)").trim()}catch(h){return`EXIT ${h.code||1}
263
263
  ${(h.stderr||h.message||"").toString().trim()}`}let c;try{c=He(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:l,stderr:u,exitCode:d,error:f}=await at(c,r,{timeout:2e4}),m=[l,u].filter(Boolean).join(`
264
264
  `).trim();return d!==0?`EXIT ${d}
265
- ${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 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
+ ${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 n=!e.server||e.server==="local"||e.server==="localhost",s=/^(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(!o.autoConfirm&&!s.test(e.command.trim())){let h=n?"local":e.server;if(console.log(`
266
266
  ${I.yellow} \u26A0 docker exec in ${e.container} on ${h}: ${e.command}${I.reset}`),!await Be(" Execute?"))return"CANCELLED: User declined."}let r=`docker exec ${e.container} sh -c ${JSON.stringify(e.command)}`;if(n)try{let{stdout:h,stderr:p}=await ie(r,{timeout:3e4});return(h||p||"(no output)").trim()}catch(h){return`EXIT ${h.code||1}
267
267
  ${(h.stderr||h.message||"").toString().trim()}`}let c;try{c=He(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:l,stderr:u,exitCode:d,error:f}=await at(c,r,{timeout:35e3}),m=[l,u].filter(Boolean).join(`
268
268
  `).trim();return d!==0?`EXIT ${d}
269
- ${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 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 p=o?"local":e.server;if(console.log(`
270
- ${I.yellow} \u26A0 docker ${e.action} ${e.container} on ${p}${I.reset}`),!await Be(" Execute?"))return"CANCELLED: User declined."}let r=e.action==="remove"?"rm":e.action,c=e.action==="inspect"?`docker inspect ${e.container}`:`docker ${r} ${e.container}`;if(o)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}
269
+ ${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 n=["start","stop","restart","remove","inspect"];if(!n.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${n.join(", ")}`;let s=!e.server||e.server==="local"||e.server==="localhost";if(!(e.action==="inspect")&&!o.autoConfirm){let p=s?"local":e.server;if(console.log(`
270
+ ${I.yellow} \u26A0 docker ${e.action} ${e.container} on ${p}${I.reset}`),!await Be(" Execute?"))return"CANCELLED: User declined."}let r=e.action==="remove"?"rm":e.action,c=e.action==="inspect"?`docker inspect ${e.container}`:`docker ${r} ${e.container}`;if(s)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}
271
271
  ${(p.stderr||p.message||"").toString().trim()}`}let l;try{l=He(e.server)}catch(p){return`ERROR: ${p.message}`}let{stdout:u,stderr:d,exitCode:f,error:m}=await at(l,c,{timeout:35e3}),h=[u,d].filter(Boolean).join(`
272
272
  `).trim();return f!==0?`EXIT ${f}
273
- ${m||h}`:h||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...Mm(e.config),...e},delete e.config,delete e._name}catch(p){return`ERROR: ${p.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=He(e.server)}catch(p){return`ERROR: ${p.message}`}let o=n.user?`${n.user}@${n.host}`:n.host,i=n.port&&Number(n.port)!==22?`-e "ssh -p ${n.port}"`:"",r=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}`:""}"`:i,l=(e.exclude||[]).map(p=>`--exclude="${p}"`).join(" "),u=e.dry_run?"--dry-run":"",d=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`,f=`rsync -avz --delete ${u} ${l} ${c} ${d} ${o}:${e.remote_path}`.trim().replace(/\s+/g," ");if(!e.dry_run&&!s.autoConfirm&&(console.log(`
274
- ${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 Be(" Proceed with deployment?")))return"CANCELLED: User declined.";let m="";try{let{stdout:p,stderr:g}=await ie(f,{timeout:12e4});m=(p||g||"").trim()}catch(p){return`ERROR (rsync): ${(p.stderr||p.message||"").toString().trim()}`}if(e.dry_run)return`DRY RUN:
273
+ ${m||h}`:h||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...Mm(e.config),...e},delete e.config,delete e._name}catch(p){return`ERROR: ${p.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=He(e.server)}catch(p){return`ERROR: ${p.message}`}let s=n.user?`${n.user}@${n.host}`:n.host,i=n.port&&Number(n.port)!==22?`-e "ssh -p ${n.port}"`:"",r=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}`:""}"`:i,l=(e.exclude||[]).map(p=>`--exclude="${p}"`).join(" "),u=e.dry_run?"--dry-run":"",d=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`,f=`rsync -avz --delete ${u} ${l} ${c} ${d} ${s}:${e.remote_path}`.trim().replace(/\s+/g," ");if(!e.dry_run&&!o.autoConfirm&&(console.log(`
274
+ ${I.yellow} \u26A0 Deploy: ${d} \u2192 ${s}:${e.remote_path}${I.reset}`),e.deploy_script&&console.log(`${I.yellow} Then run: ${e.deploy_script}${I.reset}`),!await Be(" Proceed with deployment?")))return"CANCELLED: User declined.";let m="";try{let{stdout:p,stderr:g}=await ie(f,{timeout:12e4});m=(p||g||"").trim()}catch(p){return`ERROR (rsync): ${(p.stderr||p.message||"").toString().trim()}`}if(e.dry_run)return`DRY RUN:
275
275
  ${m||"(nothing to sync)"}`;let h="";if(e.deploy_script){let{stdout:p,stderr:g,exitCode:$,error:y}=await at(n,e.deploy_script,{timeout:6e4}),x=[p,g].filter(Boolean).join(`
276
276
  `).trim();if($!==0)return`rsync OK
277
277
 
@@ -279,34 +279,34 @@ ERROR (deploy_script, exit ${$}):
279
279
  ${y||x}`;h=`
280
280
 
281
281
  Remote script output:
282
- ${x||"(no output)"}`}return`Deployed ${d} \u2192 ${o}:${e.remote_path}
283
- ${m}${h}`.trim()}default:return`ERROR: Unknown tool: ${t}`}}async function Wm(t,e,s={}){let n=s.silent?null:Tm(t,e);if(!n)return Qa(t,e,s);let o=new Za(n);o.start();try{let i=await Qa(t,e,s);return o.stop(),i}catch(i){throw o.stop(),i}}nc.exports={TOOL_DEFINITIONS:Um,executeTool:Wm,resolvePath:ke,autoFixPath:ls,autoFixEdit:tc,enrichBashError:ec,cancelPendingAskUser:jm,setAskUserHandler:Dm}});var oc=L((F$,sc)=>{var{loadServerProfiles:Mo}=qt(),No={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 Bm(){let t=Mo();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,i]of Object.entries(t)){let r=i.user?`${i.user}@${i.host}`:i.host,c=i.port&&Number(i.port)!==22?`:${i.port}`:"",l=i.os?` \u2014 OS: ${i.os}`:"",u=i.sudo?", sudo available":"";s.push(`- **${o}**: ${r}${c}${l}${u}`)}let n=new Set;for(let o of Object.values(t))o.os&&No[o.os]&&n.add(o.os);if(n.size>0){s.push("");for(let o of n){let i={almalinux9:"AlmaLinux 9",almalinux8:"AlmaLinux 8",ubuntu:"Ubuntu",debian:"Debian",macos:"macOS"}[o]||o;s.push(`### ${i} Notes`);for(let r of No[o])s.push(`- ${r}`)}}return s.join(`
284
- `)}function Hm(t){let e=Mo();return Object.values(e).some(s=>s.os&&s.os.startsWith(t))}function Gm(){return Object.keys(Mo())}sc.exports={getServerContext:Bm,hasServerOS:Hm,getProfileNames:Gm,OS_HINTS:No}});var Lo=L((U$,ic)=>{var Ie=require("fs").promises,Ne=require("path"),us=require("util").promisify(require("child_process").exec),{C:Ge}=ce(),{getMergeConflicts:rc}=yt(),{getServerContext:zm}=oc(),Po=new Map,Dt=new Map,ds=null,Km=3e4;async function ct(t){try{return await t()}catch{return null}}async function Ym(){if(!ds||Date.now()>ds)return!1;let t=[Ne.join(process.cwd(),"package.json"),Ne.join(process.cwd(),"README.md"),Ne.join(process.cwd(),".gitignore")];for(let e of t)try{let s=await Ie.stat(e),n=Dt.get(e);if(!n||s.mtimeMs!==n)return!1}catch{if(Dt.has(e))return!1}try{let e=Ne.join(process.cwd(),".git","HEAD"),s=await Ie.stat(e),n=Dt.get(e);if(!n||s.mtimeMs!==n)return!1}catch{}return!0}async function Jm(){let t=[Ne.join(process.cwd(),"package.json"),Ne.join(process.cwd(),"README.md"),Ne.join(process.cwd(),".gitignore"),Ne.join(process.cwd(),".git","HEAD")];for(let e of t)try{let s=await Ie.stat(e);Dt.set(e,s.mtimeMs)}catch{Dt.delete(e)}}async function Xm(t){let e="fileContext",s=Po.get(e),n=!1;if(s&&await Ym()&&(n=!0),!n){let u=[],d=Ne.join(t,"package.json");if(await ct(()=>Ie.access(d).then(()=>!0).catch(()=>!1)))try{let $=await Ie.readFile(d,"utf-8"),y=JSON.parse($),x={name:y.name,version:y.version};y.scripts&&(x.scripts=Object.keys(y.scripts).slice(0,15)),y.dependencies&&(x.deps=Object.keys(y.dependencies).length),y.devDependencies&&(x.devDeps=Object.keys(y.devDependencies).length),u.push(`PACKAGE: ${JSON.stringify(x)}`)}catch{}let m=Ne.join(t,"README.md");if(await ct(()=>Ie.access(m).then(()=>!0).catch(()=>!1))){let y=(await Ie.readFile(m,"utf-8")).split(`
282
+ ${x||"(no output)"}`}return`Deployed ${d} \u2192 ${s}:${e.remote_path}
283
+ ${m}${h}`.trim()}default:return`ERROR: Unknown tool: ${t}`}}async function Wm(t,e,o={}){let n=o.silent?null:Tm(t,e);if(!n)return Za(t,e,o);let s=new ec(n);s.start();try{let i=await Za(t,e,o);return s.stop(),i}catch(i){throw s.stop(),i}}sc.exports={TOOL_DEFINITIONS:Um,executeTool:Wm,resolvePath:ke,autoFixPath:ls,autoFixEdit:nc,enrichBashError:tc,cancelPendingAskUser:jm,setAskUserHandler:Dm}});var rc=L((U$,oc)=>{var{loadServerProfiles:Po}=qt(),Mo={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 Bm(){let t=Po();if(Object.keys(t).length===0)return null;let o=["## Remote Servers (.nex/servers.json)"];o.push(""),o.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[s,i]of Object.entries(t)){let r=i.user?`${i.user}@${i.host}`:i.host,c=i.port&&Number(i.port)!==22?`:${i.port}`:"",l=i.os?` \u2014 OS: ${i.os}`:"",u=i.sudo?", sudo available":"";o.push(`- **${s}**: ${r}${c}${l}${u}`)}let n=new Set;for(let s of Object.values(t))s.os&&Mo[s.os]&&n.add(s.os);if(n.size>0){o.push("");for(let s of n){let i={almalinux9:"AlmaLinux 9",almalinux8:"AlmaLinux 8",ubuntu:"Ubuntu",debian:"Debian",macos:"macOS"}[s]||s;o.push(`### ${i} Notes`);for(let r of Mo[s])o.push(`- ${r}`)}}return o.join(`
284
+ `)}function Hm(t){let e=Po();return Object.values(e).some(o=>o.os&&o.os.startsWith(t))}function Gm(){return Object.keys(Po())}oc.exports={getServerContext:Bm,hasServerOS:Hm,getProfileNames:Gm,OS_HINTS:Mo}});var Io=L((W$,ac)=>{var Ie=require("fs").promises,Ne=require("path"),us=require("util").promisify(require("child_process").exec),{C:Ge}=ce(),{getMergeConflicts:ic}=yt(),{getServerContext:zm}=rc(),Lo=new Map,Dt=new Map,ds=null,Km=3e4;async function ct(t){try{return await t()}catch{return null}}async function Ym(){if(!ds||Date.now()>ds)return!1;let t=[Ne.join(process.cwd(),"package.json"),Ne.join(process.cwd(),"README.md"),Ne.join(process.cwd(),".gitignore")];for(let e of t)try{let o=await Ie.stat(e),n=Dt.get(e);if(!n||o.mtimeMs!==n)return!1}catch{if(Dt.has(e))return!1}try{let e=Ne.join(process.cwd(),".git","HEAD"),o=await Ie.stat(e),n=Dt.get(e);if(!n||o.mtimeMs!==n)return!1}catch{}return!0}async function Jm(){let t=[Ne.join(process.cwd(),"package.json"),Ne.join(process.cwd(),"README.md"),Ne.join(process.cwd(),".gitignore"),Ne.join(process.cwd(),".git","HEAD")];for(let e of t)try{let o=await Ie.stat(e);Dt.set(e,o.mtimeMs)}catch{Dt.delete(e)}}async function Xm(t){let e="fileContext",o=Lo.get(e),n=!1;if(o&&await Ym()&&(n=!0),!n){let u=[],d=Ne.join(t,"package.json");if(await ct(()=>Ie.access(d).then(()=>!0).catch(()=>!1)))try{let $=await Ie.readFile(d,"utf-8"),y=JSON.parse($),x={name:y.name,version:y.version};y.scripts&&(x.scripts=Object.keys(y.scripts).slice(0,15)),y.dependencies&&(x.deps=Object.keys(y.dependencies).length),y.devDependencies&&(x.devDeps=Object.keys(y.devDependencies).length),u.push(`PACKAGE: ${JSON.stringify(x)}`)}catch{}let m=Ne.join(t,"README.md");if(await ct(()=>Ie.access(m).then(()=>!0).catch(()=>!1))){let y=(await Ie.readFile(m,"utf-8")).split(`
285
285
  `).slice(0,50);u.push(`README (first 50 lines):
286
286
  ${y.join(`
287
287
  `)}`)}let p=Ne.join(t,".gitignore");if(await ct(()=>Ie.access(p).then(()=>!0).catch(()=>!1))){let $=await Ie.readFile(p,"utf-8");u.push(`GITIGNORE:
288
- ${$.trim()}`)}s=u.join(`
288
+ ${$.trim()}`)}o=u.join(`
289
289
 
290
- `),Po.set(e,s),ds=Date.now()+Km,await Jm()}let o=[s],[i,r,c,l]=await Promise.all([ct(async()=>{let{stdout:u}=await us("git branch --show-current",{cwd:t,timeout:5e3});return u.trim()}),ct(async()=>{let{stdout:u}=await us("git status --short",{cwd:t,timeout:5e3});return u.trim()}),ct(async()=>{let{stdout:u}=await us("git log --oneline -5",{cwd:t,timeout:5e3});return u.trim()}),rc()]);if(i&&o.push(`GIT BRANCH: ${i}`),r&&o.push(`GIT STATUS:
291
- ${r}`),c&&o.push(`RECENT COMMITS:
290
+ `),Lo.set(e,o),ds=Date.now()+Km,await Jm()}let s=[o],[i,r,c,l]=await Promise.all([ct(async()=>{let{stdout:u}=await us("git branch --show-current",{cwd:t,timeout:5e3});return u.trim()}),ct(async()=>{let{stdout:u}=await us("git status --short",{cwd:t,timeout:5e3});return u.trim()}),ct(async()=>{let{stdout:u}=await us("git log --oneline -5",{cwd:t,timeout:5e3});return u.trim()}),ic()]);if(i&&s.push(`GIT BRANCH: ${i}`),r&&s.push(`GIT STATUS:
291
+ ${r}`),c&&s.push(`RECENT COMMITS:
292
292
  ${c}`),l&&l.length>0){let u=l.map(d=>` ${d.file}`).join(`
293
- `);o.push(`MERGE CONFLICTS (resolve before editing these files):
294
- ${u}`)}try{let u=zm();u&&o.push(u)}catch{}return o.join(`
293
+ `);s.push(`MERGE CONFLICTS (resolve before editing these files):
294
+ ${u}`)}try{let u=zm();u&&s.push(u)}catch{}return s.join(`
295
295
 
296
- `)}async function Vm(t){let e=Ne.join(t,"package.json"),s="";if(await ct(()=>Ie.access(e).then(()=>!0).catch(()=>!1)))try{let r=await Ie.readFile(e,"utf-8"),c=JSON.parse(r);s=`${c.name||"?"} v${c.version||"?"}`}catch{}let[o,i]=await Promise.all([ct(async()=>{let{stdout:r}=await us("git branch --show-current",{cwd:t,timeout:5e3});return r.trim()}),rc()]);if(s&&console.log(`${Ge.dim} project: ${s}${Ge.reset}`),o&&console.log(`${Ge.dim} branch: ${o}${Ge.reset}`),i&&i.length>0){console.log(`${Ge.red} \u26A0 ${i.length} unresolved merge conflict(s):${Ge.reset}`);for(let r of i)console.log(`${Ge.red} ${r.file}${Ge.reset}`);console.log(`${Ge.yellow} \u2192 Resolve conflicts before starting tasks${Ge.reset}`)}console.log()}ic.exports={gatherProjectContext:Xm,printContext:Vm,_clearContextCache:()=>{Po.clear(),Dt.clear(),ds=null}}});var _t=L((W$,uc)=>{var tt=require("fs"),Io=require("path");function fs(){return Io.join(process.cwd(),".nex","sessions")}function ac(){let t=fs();tt.existsSync(t)||tt.mkdirSync(t,{recursive:!0})}function qo(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return Io.join(fs(),`${e}.json`)}function jo(t,e,s={}){ac();let n=qo(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 tt.writeFileSync(n,JSON.stringify(o,null,2),"utf-8"),{path:n,name:t}}function cc(t){let e=qo(t);if(!tt.existsSync(e))return null;try{return JSON.parse(tt.readFileSync(e,"utf-8"))}catch{return null}}function lc(){ac();let t=fs(),e=tt.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(tt.readFileSync(Io.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 Qm(t){let e=qo(t);return tt.existsSync(e)?(tt.unlinkSync(e),!0):!1}function Zm(){let t=lc();return t.length===0?null:cc(t[0].name)}var xt=null,et=null,$n=null;function ep(t,e={}){t.length!==0&&(xt&&clearTimeout(xt),et=t,$n=e||{},xt=setTimeout(()=>{et&&et.length>0&&jo("_autosave",et,$n),xt=null,et=null,$n=null},5e3))}function tp(){xt&&(clearTimeout(xt),xt=null),et&&et.length>0&&(jo("_autosave",et,$n),et=null,$n=null)}uc.exports={saveSession:jo,loadSession:cc,listSessions:lc,deleteSession:Qm,getLastSession:Zm,autoSave:ep,flushAutoSave:tp,_getSessionsDir:fs}});var lt=L((B$,gc)=>{var nt=require("fs"),ms=require("path"),np=require("os");function Do(){return ms.join(process.cwd(),".nex","memory")}function Fo(){return ms.join(Do(),"memory.json")}function sp(){return ms.join(process.cwd(),"NEX.md")}function dc(){return ms.join(np.homedir(),".nex","NEX.md")}function op(){let t=Do();nt.existsSync(t)||nt.mkdirSync(t,{recursive:!0})}function ps(){let t=Fo();if(!nt.existsSync(t))return{};try{return JSON.parse(nt.readFileSync(t,"utf-8"))}catch{return{}}}function fc(t){op(),nt.writeFileSync(Fo(),JSON.stringify(t,null,2),"utf-8")}function rp(t,e){let s=ps();s[t]={value:e,updatedAt:new Date().toISOString()},fc(s)}function ip(t){let e=ps();return e[t]?e[t].value:null}function ap(t){let e=ps();return t in e?(delete e[t],fc(e),!0):!1}function mc(){let t=ps();return Object.entries(t).map(([e,s])=>({key:e,value:s.value,updatedAt:s.updatedAt}))}function pc(){let t=dc();if(!nt.existsSync(t))return"";try{return nt.readFileSync(t,"utf-8").trim()}catch{return""}}function hc(){let t=sp();if(!nt.existsSync(t))return"";try{return nt.readFileSync(t,"utf-8").trim()}catch{return""}}function cp(){let t=[],e=pc();e&&t.push(`GLOBAL INSTRUCTIONS (~/.nex/NEX.md):
297
- ${e}`);let s=hc();s&&t.push(`PROJECT INSTRUCTIONS (NEX.md):
298
- ${s}`);let n=mc();if(n.length>0){let o=n.map(i=>` ${i.key}: ${i.value}`).join(`
296
+ `)}async function Vm(t){let e=Ne.join(t,"package.json"),o="";if(await ct(()=>Ie.access(e).then(()=>!0).catch(()=>!1)))try{let r=await Ie.readFile(e,"utf-8"),c=JSON.parse(r);o=`${c.name||"?"} v${c.version||"?"}`}catch{}let[s,i]=await Promise.all([ct(async()=>{let{stdout:r}=await us("git branch --show-current",{cwd:t,timeout:5e3});return r.trim()}),ic()]);if(o&&console.log(`${Ge.dim} project: ${o}${Ge.reset}`),s&&console.log(`${Ge.dim} branch: ${s}${Ge.reset}`),i&&i.length>0){console.log(`${Ge.red} \u26A0 ${i.length} unresolved merge conflict(s):${Ge.reset}`);for(let r of i)console.log(`${Ge.red} ${r.file}${Ge.reset}`);console.log(`${Ge.yellow} \u2192 Resolve conflicts before starting tasks${Ge.reset}`)}console.log()}ac.exports={gatherProjectContext:Xm,printContext:Vm,_clearContextCache:()=>{Lo.clear(),Dt.clear(),ds=null}}});var _t=L((B$,dc)=>{var tt=require("fs"),qo=require("path");function fs(){return qo.join(process.cwd(),".nex","sessions")}function cc(){let t=fs();tt.existsSync(t)||tt.mkdirSync(t,{recursive:!0})}function jo(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return qo.join(fs(),`${e}.json`)}function Do(t,e,o={}){cc();let n=jo(t),s={name:t,createdAt:o.createdAt||new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:e.length,model:o.model||null,provider:o.provider||null,messages:e};return tt.writeFileSync(n,JSON.stringify(s,null,2),"utf-8"),{path:n,name:t}}function lc(t){let e=jo(t);if(!tt.existsSync(e))return null;try{return JSON.parse(tt.readFileSync(e,"utf-8"))}catch{return null}}function uc(){cc();let t=fs(),e=tt.readdirSync(t).filter(n=>n.endsWith(".json")),o=[];for(let n of e)try{let s=JSON.parse(tt.readFileSync(qo.join(t,n),"utf-8"));o.push({name:s.name||n.replace(".json",""),createdAt:s.createdAt,updatedAt:s.updatedAt,messageCount:s.messageCount||0,model:s.model,provider:s.provider})}catch{}return o.sort((n,s)=>(s.updatedAt||"").localeCompare(n.updatedAt||""))}function Qm(t){let e=jo(t);return tt.existsSync(e)?(tt.unlinkSync(e),!0):!1}function Zm(){let t=uc();return t.length===0?null:lc(t[0].name)}var xt=null,et=null,$n=null;function ep(t,e={}){t.length!==0&&(xt&&clearTimeout(xt),et=t,$n=e||{},xt=setTimeout(()=>{et&&et.length>0&&Do("_autosave",et,$n),xt=null,et=null,$n=null},5e3))}function tp(){xt&&(clearTimeout(xt),xt=null),et&&et.length>0&&(Do("_autosave",et,$n),et=null,$n=null)}dc.exports={saveSession:Do,loadSession:lc,listSessions:uc,deleteSession:Qm,getLastSession:Zm,autoSave:ep,flushAutoSave:tp,_getSessionsDir:fs}});var lt=L((H$,$c)=>{var nt=require("fs"),ms=require("path"),np=require("os");function Fo(){return ms.join(process.cwd(),".nex","memory")}function Uo(){return ms.join(Fo(),"memory.json")}function sp(){return ms.join(process.cwd(),"NEX.md")}function fc(){return ms.join(np.homedir(),".nex","NEX.md")}function op(){let t=Fo();nt.existsSync(t)||nt.mkdirSync(t,{recursive:!0})}function ps(){let t=Uo();if(!nt.existsSync(t))return{};try{return JSON.parse(nt.readFileSync(t,"utf-8"))}catch{return{}}}function mc(t){op(),nt.writeFileSync(Uo(),JSON.stringify(t,null,2),"utf-8")}function rp(t,e){let o=ps();o[t]={value:e,updatedAt:new Date().toISOString()},mc(o)}function ip(t){let e=ps();return e[t]?e[t].value:null}function ap(t){let e=ps();return t in e?(delete e[t],mc(e),!0):!1}function pc(){let t=ps();return Object.entries(t).map(([e,o])=>({key:e,value:o.value,updatedAt:o.updatedAt}))}function hc(){let t=fc();if(!nt.existsSync(t))return"";try{return nt.readFileSync(t,"utf-8").trim()}catch{return""}}function gc(){let t=sp();if(!nt.existsSync(t))return"";try{return nt.readFileSync(t,"utf-8").trim()}catch{return""}}function cp(){let t=[],e=hc();e&&t.push(`GLOBAL INSTRUCTIONS (~/.nex/NEX.md):
297
+ ${e}`);let o=gc();o&&t.push(`PROJECT INSTRUCTIONS (NEX.md):
298
+ ${o}`);let n=pc();if(n.length>0){let s=n.map(i=>` ${i.key}: ${i.value}`).join(`
299
299
  `);t.push(`PROJECT MEMORY:
300
- ${o}`)}return t.join(`
300
+ ${s}`)}return t.join(`
301
301
 
302
- `)}gc.exports={remember:rp,recall:ip,forget:ap,listMemories:mc,loadGlobalInstructions:pc,loadProjectInstructions:hc,getMemoryContext:cp,_getMemoryDir:Do,_getMemoryFile:Fo,_getGlobalNexMdPath:dc}});var yn=L((G$,wc)=>{var kt=require("fs"),Uo=require("path"),{C:H$}=ce(),hs={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"},Ft={...hs};function $c(){let t=Uo.join(process.cwd(),".nex","config.json");if(kt.existsSync(t))try{let e=JSON.parse(kt.readFileSync(t,"utf-8"));e.permissions&&(Ft={...hs,...e.permissions})}catch{}}function lp(){let t=Uo.join(process.cwd(),".nex"),e=Uo.join(t,"config.json"),s={};if(kt.existsSync(e))try{s=JSON.parse(kt.readFileSync(e,"utf-8"))}catch{s={}}s.permissions=Ft,kt.existsSync(t)||kt.mkdirSync(t,{recursive:!0}),kt.writeFileSync(e,JSON.stringify(s,null,2),"utf-8")}function yc(t){return Ft[t]||"ask"}function up(t,e){return["allow","ask","deny"].includes(e)?(Ft[t]=e,!0):!1}function dp(t){return yc(t)}function fp(){return Object.entries(Ft).map(([t,e])=>({tool:t,mode:e}))}function mp(){Ft={...hs}}$c();wc.exports={getPermission:yc,setPermission:up,checkPermission:dp,listPermissions:fp,loadPermissions:$c,savePermissions:lp,resetPermissions:mp,DEFAULT_PERMISSIONS:hs}});var Ut=L((K$,vc)=>{var vt=require("fs"),gs=require("path"),z$=require("readline"),{C:K}=ce(),le=null,Wo=!1,Bo=null,bc=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 $s(){return gs.join(process.cwd(),".nex","plans")}function xc(){let t=$s();vt.existsSync(t)||vt.mkdirSync(t,{recursive:!0})}function pp(t,e=[]){return le={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()},le}function hp(){return le}function gp(t){Wo=t}function $p(){return Wo}function yp(){return!le||le.status!=="draft"?!1:(le.status="approved",le.updatedAt=new Date().toISOString(),!0)}function wp(){return!le||le.status!=="approved"?!1:(le.status="executing",!0)}function bp(t,e){return!le||t<0||t>=le.steps.length?!1:(le.steps[t].status=e,le.updatedAt=new Date().toISOString(),le.steps.every(s=>s.status==="done"||s.status==="skipped")&&(le.status="completed"),!0)}function xp(t){if(!t)return`${K.dim}No active plan${K.reset}`;let e={draft:`${K.yellow}DRAFT${K.reset}`,approved:`${K.green}APPROVED${K.reset}`,executing:`${K.blue}EXECUTING${K.reset}`,completed:`${K.green}COMPLETED${K.reset}`},s=[];s.push(`
303
- ${K.bold}${K.cyan}Plan: ${t.task}${K.reset}`),s.push(`${K.dim}Status: ${e[t.status]||t.status}${K.reset}
304
- `);for(let n=0;n<t.steps.length;n++){let o=t.steps[n],i;switch(o.status){case"done":i=`${K.green}\u2713${K.reset}`;break;case"in_progress":i=`${K.blue}\u2192${K.reset}`;break;case"skipped":i=`${K.dim}\u25CB${K.reset}`;break;default:i=`${K.dim} ${K.reset}`}s.push(` ${i} ${K.bold}Step ${n+1}:${K.reset} ${o.description}`),o.files.length>0&&s.push(` ${K.dim}Files: ${o.files.join(", ")}${K.reset}`)}return s.push(""),s.join(`
305
- `)}function _p(t){if(t||(t=le),!t)return null;xc();let e=gs.join($s(),`${t.name}.json`);return vt.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function kp(t){let e=gs.join($s(),`${t}.json`);if(!vt.existsSync(e))return null;try{let s=JSON.parse(vt.readFileSync(e,"utf-8"));return le=s,s}catch{return null}}function vp(){xc();let t=$s(),e=vt.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(vt.readFileSync(gs.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 Sp(t){Bo=t}function Ep(){return Bo}function Tp(){le=null,Wo=!1,Bo=null}function Cp(){return`
302
+ `)}$c.exports={remember:rp,recall:ip,forget:ap,listMemories:pc,loadGlobalInstructions:hc,loadProjectInstructions:gc,getMemoryContext:cp,_getMemoryDir:Fo,_getMemoryFile:Uo,_getGlobalNexMdPath:fc}});var yn=L((z$,bc)=>{var kt=require("fs"),Wo=require("path"),{C:G$}=ce(),hs={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"},Ft={...hs};function yc(){let t=Wo.join(process.cwd(),".nex","config.json");if(kt.existsSync(t))try{let e=JSON.parse(kt.readFileSync(t,"utf-8"));e.permissions&&(Ft={...hs,...e.permissions})}catch{}}function lp(){let t=Wo.join(process.cwd(),".nex"),e=Wo.join(t,"config.json"),o={};if(kt.existsSync(e))try{o=JSON.parse(kt.readFileSync(e,"utf-8"))}catch{o={}}o.permissions=Ft,kt.existsSync(t)||kt.mkdirSync(t,{recursive:!0}),kt.writeFileSync(e,JSON.stringify(o,null,2),"utf-8")}function wc(t){return Ft[t]||"ask"}function up(t,e){return["allow","ask","deny"].includes(e)?(Ft[t]=e,!0):!1}function dp(t){return wc(t)}function fp(){return Object.entries(Ft).map(([t,e])=>({tool:t,mode:e}))}function mp(){Ft={...hs}}yc();bc.exports={getPermission:wc,setPermission:up,checkPermission:dp,listPermissions:fp,loadPermissions:yc,savePermissions:lp,resetPermissions:mp,DEFAULT_PERMISSIONS:hs}});var Ut=L((Y$,Sc)=>{var vt=require("fs"),gs=require("path"),K$=require("readline"),{C:K}=ce(),le=null,Bo=!1,Ho=null,xc=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 $s(){return gs.join(process.cwd(),".nex","plans")}function _c(){let t=$s();vt.existsSync(t)||vt.mkdirSync(t,{recursive:!0})}function pp(t,e=[]){return le={name:`plan-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,task:t,steps:e.map(o=>({description:o.description||o,files:o.files||[],status:"pending"})),status:"draft",createdAt:new Date().toISOString()},le}function hp(){return le}function gp(t){Bo=t}function $p(){return Bo}function yp(){return!le||le.status!=="draft"?!1:(le.status="approved",le.updatedAt=new Date().toISOString(),!0)}function wp(){return!le||le.status!=="approved"?!1:(le.status="executing",!0)}function bp(t,e){return!le||t<0||t>=le.steps.length?!1:(le.steps[t].status=e,le.updatedAt=new Date().toISOString(),le.steps.every(o=>o.status==="done"||o.status==="skipped")&&(le.status="completed"),!0)}function xp(t){if(!t)return`${K.dim}No active plan${K.reset}`;let e={draft:`${K.yellow}DRAFT${K.reset}`,approved:`${K.green}APPROVED${K.reset}`,executing:`${K.blue}EXECUTING${K.reset}`,completed:`${K.green}COMPLETED${K.reset}`},o=[];o.push(`
303
+ ${K.bold}${K.cyan}Plan: ${t.task}${K.reset}`),o.push(`${K.dim}Status: ${e[t.status]||t.status}${K.reset}
304
+ `);for(let n=0;n<t.steps.length;n++){let s=t.steps[n],i;switch(s.status){case"done":i=`${K.green}\u2713${K.reset}`;break;case"in_progress":i=`${K.blue}\u2192${K.reset}`;break;case"skipped":i=`${K.dim}\u25CB${K.reset}`;break;default:i=`${K.dim} ${K.reset}`}o.push(` ${i} ${K.bold}Step ${n+1}:${K.reset} ${s.description}`),s.files.length>0&&o.push(` ${K.dim}Files: ${s.files.join(", ")}${K.reset}`)}return o.push(""),o.join(`
305
+ `)}function _p(t){if(t||(t=le),!t)return null;_c();let e=gs.join($s(),`${t.name}.json`);return vt.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function kp(t){let e=gs.join($s(),`${t}.json`);if(!vt.existsSync(e))return null;try{let o=JSON.parse(vt.readFileSync(e,"utf-8"));return le=o,o}catch{return null}}function vp(){_c();let t=$s(),e=vt.readdirSync(t).filter(n=>n.endsWith(".json")),o=[];for(let n of e)try{let s=JSON.parse(vt.readFileSync(gs.join(t,n),"utf-8"));o.push({name:s.name,task:s.task,status:s.status,steps:s.steps?s.steps.length:0,createdAt:s.createdAt})}catch{}return o.sort((n,s)=>(s.createdAt||"").localeCompare(n.createdAt||""))}function Sp(t){Ho=t}function Ep(){return Ho}function Tp(){le=null,Bo=!1,Ho=null}function Cp(){return`
306
306
  PLAN MODE ACTIVE: You are in analysis-only mode. You MUST NOT execute any changes.
307
307
 
308
308
  # Allowed Tools (read-only)
309
- You may ONLY use these tools: ${[...bc].join(", ")}
309
+ You may ONLY use these tools: ${[...xc].join(", ")}
310
310
  Any other tool call will be blocked and returned with an error.
311
311
 
312
312
  # Analysis Phase
@@ -337,53 +337,53 @@ Bullet list of potential issues and mitigations.
337
337
  # Important
338
338
  - Order steps by dependency (later steps may depend on earlier ones).
339
339
  - After presenting the plan, tell the user to type \`/plan approve\` to proceed.
340
- - Do NOT make any file changes \u2014 your role is analysis and planning only.`}var _c=["interactive","semi-auto","autonomous"],kc="interactive";function Rp(t){return _c.includes(t)?(kc=t,!0):!1}function Ap(){return kc}vc.exports={createPlan:pp,getActivePlan:hp,setPlanMode:gp,isPlanMode:$p,approvePlan:yp,startExecution:wp,updateStep:bp,formatPlan:xp,savePlan:_p,loadPlan:kp,listPlans:vp,clearPlan:Tp,getPlanModePrompt:Cp,setPlanContent:Sp,getPlanContent:Ep,PLAN_MODE_ALLOWED_TOOLS:bc,setAutonomyLevel:Rp,getAutonomyLevel:Ap,AUTONOMY_LEVELS:_c}});var Pc=L((Y$,Mc)=>{var{C:w}=ce();function Op(t){if(!t)return"";let e=t.split(`
341
- `),s=[],n=!1,o="";for(let i of e){if(i.trim().startsWith("```")){if(n)s.push(`${w.dim}${"\u2500".repeat(40)}${w.reset}`),n=!1,o="";else{n=!0,o=i.trim().substring(3).trim();let r=o?` ${o} `:"";s.push(`${w.dim}${"\u2500".repeat(3)}${r}${"\u2500".repeat(Math.max(0,37-r.length))}${w.reset}`)}continue}if(n){s.push(` ${Go(i,o)}`);continue}if(i.startsWith("### ")){s.push(`${w.bold}${w.cyan} ${St(i.substring(4))}${w.reset}`);continue}if(i.startsWith("## ")){s.push(`${w.bold}${w.cyan} ${St(i.substring(3))}${w.reset}`);continue}if(i.startsWith("# ")){s.push(`${w.bold}${w.cyan}${St(i.substring(2))}${w.reset}`);continue}if(/^\s*[-*]\s/.test(i)){let r=i.match(/^(\s*)/)[1],c=i.replace(/^\s*[-*]\s/,"");s.push(`${r}${w.cyan}\u2022${w.reset} ${Et(c)}`);continue}if(/^\s*\d+\.\s/.test(i)){let r=i.match(/^(\s*)(\d+)\.\s(.*)/);if(r){s.push(`${r[1]}${w.cyan}${r[2]}.${w.reset} ${Et(r[3])}`);continue}}s.push(Et(i))}return s.join(`
342
- `)}function St(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function Et(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 Go(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?Sc(t):e==="bash"||e==="sh"||e==="shell"||e==="zsh"?Ec(t):e==="json"||e==="jsonc"?Tc(t):e==="python"||e==="py"?Cc(t):e==="go"||e==="golang"?Rc(t):e==="rust"||e==="rs"?Ac(t):e==="css"||e==="scss"||e==="less"?Oc(t):e==="html"||e==="xml"||e==="svg"||e==="htm"?Nc(t):t:""}function Sc(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,i=t;return i=i.replace(o,`${w.yellow}$1${w.reset}`),i=i.replace(e,`${w.magenta}$1${w.reset}`),i=i.replace(s,`${w.green}$&${w.reset}`),i=i.replace(n,`${w.dim}$1${w.reset}`),i}function Ec(t){let e=/^(\s*)([\w-]+)/,s=/(--?\w[\w-]*)/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(#.*$)/,i=t;return i=i.replace(s,`${w.cyan}$1${w.reset}`),i=i.replace(e,`$1${w.green}$2${w.reset}`),i=i.replace(n,`${w.yellow}$&${w.reset}`),i=i.replace(o,`${w.dim}$1${w.reset}`),i}function Tc(t){let e=/("[\w-]+")\s*:/g,s=/:\s*("(?:[^"\\]|\\.)*")/g,n=/:\s*(\d+\.?\d*)/g,o=/:\s*(true|false|null)/g,i=t;return i=i.replace(e,`${w.cyan}$1${w.reset}:`),i=i.replace(s,`: ${w.green}$1${w.reset}`),i=i.replace(n,`: ${w.yellow}$1${w.reset}`),i=i.replace(o,`: ${w.magenta}$1${w.reset}`),i}function Cc(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,i=/^(\s*@\w+)/,r=t;return r=r.replace(o,`${w.yellow}$1${w.reset}`),r=r.replace(e,`${w.magenta}$1${w.reset}`),r=r.replace(i,`${w.cyan}$1${w.reset}`),r=r.replace(s,`${w.green}$&${w.reset}`),r=r.replace(n,`${w.dim}$1${w.reset}`),r}function Rc(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=/(\/\/.*$)/,i=/\b(\d+\.?\d*)\b/g,r=t;return r=r.replace(i,`${w.yellow}$1${w.reset}`),r=r.replace(s,`${w.cyan}$1${w.reset}`),r=r.replace(e,`${w.magenta}$1${w.reset}`),r=r.replace(n,`${w.green}$&${w.reset}`),r=r.replace(o,`${w.dim}$1${w.reset}`),r}function Ac(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=/(\/\/.*$)/,i=/\b(\d+\.?\d*)\b/g,r=/\b(\w+!)/g,c=t;return c=c.replace(i,`${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(r,`${w.yellow}$1${w.reset}`),c=c.replace(n,`${w.green}$&${w.reset}`),c=c.replace(o,`${w.dim}$1${w.reset}`),c}function Oc(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,i=/(\/\*.*?\*\/|\/\/.*$)/,r=/(#[0-9a-fA-F]{3,8})\b/g,c=t;return c=c.replace(r,`${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(i,`${w.dim}$1${w.reset}`),c}function Nc(t){let e=/<\/?(\w[\w-]*)/g,s=/\s([\w-]+)=/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(<!--.*?-->)/g,i=/(&\w+;)/g,r=t;return r=r.replace(o,`${w.dim}$1${w.reset}`),r=r.replace(n,`${w.green}$&${w.reset}`),r=r.replace(e,`<${w.magenta}$1${w.reset}`),r=r.replace(s,` ${w.cyan}$1${w.reset}=`),r=r.replace(i,`${w.yellow}$1${w.reset}`),r}function Np(t,e){if(!t||t.length===0)return"";let s=t.map((r,c)=>{let l=e.reduce((u,d)=>Math.max(u,(d[c]||"").length),0);return Math.max(r.length,l)}),n=s.map(r=>"\u2500".repeat(r+2)).join("\u253C"),o=t.map((r,c)=>` ${w.bold}${r.padEnd(s[c])}${w.reset} `).join("\u2502"),i=[];i.push(`${w.dim}\u250C${n.replace(/┼/g,"\u252C")}\u2510${w.reset}`),i.push(`${w.dim}\u2502${w.reset}${o}${w.dim}\u2502${w.reset}`),i.push(`${w.dim}\u251C${n}\u2524${w.reset}`);for(let r of e){let c=t.map((l,u)=>` ${(r[u]||"").padEnd(s[u])} `).join(`${w.dim}\u2502${w.reset}`);i.push(`${w.dim}\u2502${w.reset}${c}${w.dim}\u2502${w.reset}`)}return i.push(`${w.dim}\u2514${n.replace(/┼/g,"\u2534")}\u2518${w.reset}`),i.join(`
343
- `)}function Mp(t,e,s,n=30){let o=s>0?Math.round(e/s*100):0,i=Math.round(o/100*n),r=n-i,c=o>=100?w.green:o>50?w.yellow:w.cyan;return` ${t} ${c}${"\u2588".repeat(i)}${w.dim}${"\u2591".repeat(r)}${w.reset} ${o}% (${e}/${s})`}var Ho=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(),80))}_renderCursor(){let e=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],s=e[this._cursorFrame%e.length];this._cursorWrite(`\x1B[2K\r\x1B[36m${s}\x1B[0m`),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(`
344
- `))!==-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(),120))}flush(){this.stopCursor(),this.buffer&&(this._renderLine(this.buffer),this.buffer=""),this.inCodeBlock&&(this._safeWrite(`${w.dim}${"\u2500".repeat(40)}${w.reset}
340
+ - Do NOT make any file changes \u2014 your role is analysis and planning only.`}var kc=["interactive","semi-auto","autonomous"],vc="interactive";function Rp(t){return kc.includes(t)?(vc=t,!0):!1}function Ap(){return vc}Sc.exports={createPlan:pp,getActivePlan:hp,setPlanMode:gp,isPlanMode:$p,approvePlan:yp,startExecution:wp,updateStep:bp,formatPlan:xp,savePlan:_p,loadPlan:kp,listPlans:vp,clearPlan:Tp,getPlanModePrompt:Cp,setPlanContent:Sp,getPlanContent:Ep,PLAN_MODE_ALLOWED_TOOLS:xc,setAutonomyLevel:Rp,getAutonomyLevel:Ap,AUTONOMY_LEVELS:kc}});var Lc=L((J$,Pc)=>{var{C:w}=ce();function Op(t){if(!t)return"";let e=t.split(`
341
+ `),o=[],n=!1,s="";for(let i of e){if(i.trim().startsWith("```")){if(n)o.push(`${w.dim}${"\u2500".repeat(40)}${w.reset}`),n=!1,s="";else{n=!0,s=i.trim().substring(3).trim();let r=s?` ${s} `:"";o.push(`${w.dim}${"\u2500".repeat(3)}${r}${"\u2500".repeat(Math.max(0,37-r.length))}${w.reset}`)}continue}if(n){o.push(` ${zo(i,s)}`);continue}if(i.startsWith("### ")){o.push(`${w.bold}${w.cyan} ${St(i.substring(4))}${w.reset}`);continue}if(i.startsWith("## ")){o.push(`${w.bold}${w.cyan} ${St(i.substring(3))}${w.reset}`);continue}if(i.startsWith("# ")){o.push(`${w.bold}${w.cyan}${St(i.substring(2))}${w.reset}`);continue}if(/^\s*[-*]\s/.test(i)){let r=i.match(/^(\s*)/)[1],c=i.replace(/^\s*[-*]\s/,"");o.push(`${r}${w.cyan}\u2022${w.reset} ${Et(c)}`);continue}if(/^\s*\d+\.\s/.test(i)){let r=i.match(/^(\s*)(\d+)\.\s(.*)/);if(r){o.push(`${r[1]}${w.cyan}${r[2]}.${w.reset} ${Et(r[3])}`);continue}}o.push(Et(i))}return o.join(`
342
+ `)}function St(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function Et(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 zo(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?Ec(t):e==="bash"||e==="sh"||e==="shell"||e==="zsh"?Tc(t):e==="json"||e==="jsonc"?Cc(t):e==="python"||e==="py"?Rc(t):e==="go"||e==="golang"?Ac(t):e==="rust"||e==="rs"?Oc(t):e==="css"||e==="scss"||e==="less"?Nc(t):e==="html"||e==="xml"||e==="svg"||e==="htm"?Mc(t):t:""}function Ec(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,o=/(["'`])(?:(?=(\\?))\2.)*?\1/g,n=/(\/\/.*$)/,s=/\b(\d+\.?\d*)\b/g,i=t;return i=i.replace(s,`${w.yellow}$1${w.reset}`),i=i.replace(e,`${w.magenta}$1${w.reset}`),i=i.replace(o,`${w.green}$&${w.reset}`),i=i.replace(n,`${w.dim}$1${w.reset}`),i}function Tc(t){let e=/^(\s*)([\w-]+)/,o=/(--?\w[\w-]*)/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,s=/(#.*$)/,i=t;return i=i.replace(o,`${w.cyan}$1${w.reset}`),i=i.replace(e,`$1${w.green}$2${w.reset}`),i=i.replace(n,`${w.yellow}$&${w.reset}`),i=i.replace(s,`${w.dim}$1${w.reset}`),i}function Cc(t){let e=/("[\w-]+")\s*:/g,o=/:\s*("(?:[^"\\]|\\.)*")/g,n=/:\s*(\d+\.?\d*)/g,s=/:\s*(true|false|null)/g,i=t;return i=i.replace(e,`${w.cyan}$1${w.reset}:`),i=i.replace(o,`: ${w.green}$1${w.reset}`),i=i.replace(n,`: ${w.yellow}$1${w.reset}`),i=i.replace(s,`: ${w.magenta}$1${w.reset}`),i}function Rc(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,o=/("""[\s\S]*?"""|'''[\s\S]*?'''|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')/g,n=/(#.*$)/,s=/\b(\d+\.?\d*)\b/g,i=/^(\s*@\w+)/,r=t;return r=r.replace(s,`${w.yellow}$1${w.reset}`),r=r.replace(e,`${w.magenta}$1${w.reset}`),r=r.replace(i,`${w.cyan}$1${w.reset}`),r=r.replace(o,`${w.green}$&${w.reset}`),r=r.replace(n,`${w.dim}$1${w.reset}`),r}function Ac(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,o=/\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,s=/(\/\/.*$)/,i=/\b(\d+\.?\d*)\b/g,r=t;return r=r.replace(i,`${w.yellow}$1${w.reset}`),r=r.replace(o,`${w.cyan}$1${w.reset}`),r=r.replace(e,`${w.magenta}$1${w.reset}`),r=r.replace(n,`${w.green}$&${w.reset}`),r=r.replace(s,`${w.dim}$1${w.reset}`),r}function Oc(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,o=/\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,s=/(\/\/.*$)/,i=/\b(\d+\.?\d*)\b/g,r=/\b(\w+!)/g,c=t;return c=c.replace(i,`${w.yellow}$1${w.reset}`),c=c.replace(o,`${w.cyan}$1${w.reset}`),c=c.replace(e,`${w.magenta}$1${w.reset}`),c=c.replace(r,`${w.yellow}$1${w.reset}`),c=c.replace(n,`${w.green}$&${w.reset}`),c=c.replace(s,`${w.dim}$1${w.reset}`),c}function Nc(t){let e=/^(\s*)([\w-]+)\s*:/,o=/:\s*([^;]+)/,n=/^(\s*[.#@][\w-]+)/,s=/\b(\d+\.?\d*(px|em|rem|%|vh|vw|s|ms|deg|fr)?)\b/g,i=/(\/\*.*?\*\/|\/\/.*$)/,r=/(#[0-9a-fA-F]{3,8})\b/g,c=t;return c=c.replace(r,`${w.yellow}$1${w.reset}`),c=c.replace(s,`${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(i,`${w.dim}$1${w.reset}`),c}function Mc(t){let e=/<\/?(\w[\w-]*)/g,o=/\s([\w-]+)=/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,s=/(<!--.*?-->)/g,i=/(&\w+;)/g,r=t;return r=r.replace(s,`${w.dim}$1${w.reset}`),r=r.replace(n,`${w.green}$&${w.reset}`),r=r.replace(e,`<${w.magenta}$1${w.reset}`),r=r.replace(o,` ${w.cyan}$1${w.reset}=`),r=r.replace(i,`${w.yellow}$1${w.reset}`),r}function Np(t,e){if(!t||t.length===0)return"";let o=t.map((r,c)=>{let l=e.reduce((u,d)=>Math.max(u,(d[c]||"").length),0);return Math.max(r.length,l)}),n=o.map(r=>"\u2500".repeat(r+2)).join("\u253C"),s=t.map((r,c)=>` ${w.bold}${r.padEnd(o[c])}${w.reset} `).join("\u2502"),i=[];i.push(`${w.dim}\u250C${n.replace(/┼/g,"\u252C")}\u2510${w.reset}`),i.push(`${w.dim}\u2502${w.reset}${s}${w.dim}\u2502${w.reset}`),i.push(`${w.dim}\u251C${n}\u2524${w.reset}`);for(let r of e){let c=t.map((l,u)=>` ${(r[u]||"").padEnd(o[u])} `).join(`${w.dim}\u2502${w.reset}`);i.push(`${w.dim}\u2502${w.reset}${c}${w.dim}\u2502${w.reset}`)}return i.push(`${w.dim}\u2514${n.replace(/┼/g,"\u2534")}\u2518${w.reset}`),i.join(`
343
+ `)}function Mp(t,e,o,n=30){let s=o>0?Math.round(e/o*100):0,i=Math.round(s/100*n),r=n-i,c=s>=100?w.green:s>50?w.yellow:w.cyan;return` ${t} ${c}${"\u2588".repeat(i)}${w.dim}${"\u2591".repeat(r)}${w.reset} ${s}% (${e}/${o})`}var Go=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(o){if(o.code!=="EPIPE")throw o}}_cursorWrite(e){try{process.stderr.write(e)}catch(o){if(o.code!=="EPIPE")throw o}}startCursor(){process.stderr.isTTY&&(this._cursorActive=!0,this._cursorFrame=0,this._cursorWrite("\x1B[?25l"),this._renderCursor(),this._cursorTimer=setInterval(()=>this._renderCursor(),80))}_renderCursor(){let e=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],o=e[this._cursorFrame%e.length];this._cursorWrite(`\x1B[2K\r\x1B[36m${o}\x1B[0m`),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 o;for(;(o=this.buffer.indexOf(`
344
+ `))!==-1;){let n=this.buffer.substring(0,o);this.buffer=this.buffer.substring(o+1),this._renderLine(n)}this._cursorActive&&(this._renderCursor(),this._cursorTimer&&clearInterval(this._cursorTimer),this._cursorTimer=setInterval(()=>this._renderCursor(),120))}flush(){this.stopCursor(),this.buffer&&(this._renderLine(this.buffer),this.buffer=""),this.inCodeBlock&&(this._safeWrite(`${w.dim}${"\u2500".repeat(40)}${w.reset}
345
345
  `),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){if(e.trim().startsWith("```")){if(this.inCodeBlock)this._safeWrite(`${w.dim}${"\u2500".repeat(40)}${w.reset}
346
- `),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}
347
- `)}return}if(this.inCodeBlock){this._safeWrite(` ${Go(e,this.codeBlockLang)}
346
+ `),this.inCodeBlock=!1,this.codeBlockLang="";else{this.inCodeBlock=!0,this.codeBlockLang=e.trim().substring(3).trim();let o=this.codeBlockLang?` ${this.codeBlockLang} `:"";this._safeWrite(`${w.dim}${"\u2500".repeat(3)}${o}${"\u2500".repeat(Math.max(0,37-o.length))}${w.reset}
347
+ `)}return}if(this.inCodeBlock){this._safeWrite(` ${zo(e,this.codeBlockLang)}
348
348
  `);return}if(e.startsWith("### ")){this._safeWrite(`${w.bold}${w.cyan} ${St(e.substring(4))}${w.reset}
349
349
  `);return}if(e.startsWith("## ")){this._safeWrite(`${w.bold}${w.cyan} ${St(e.substring(3))}${w.reset}
350
350
  `);return}if(e.startsWith("# ")){this._safeWrite(`${w.bold}${w.cyan}${St(e.substring(2))}${w.reset}
351
- `);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} ${Et(n)}
352
- `);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} ${Et(s[3])}
351
+ `);return}if(/^\s*[-*]\s/.test(e)){let o=e.match(/^(\s*)/)[1],n=e.replace(/^\s*[-*]\s/,"");this._safeWrite(`${o}${w.cyan}\u2022${w.reset} ${Et(n)}
352
+ `);return}if(/^\s*\d+\.\s/.test(e)){let o=e.match(/^(\s*)(\d+)\.\s(.*)/);if(o){this._safeWrite(`${o[1]}${w.cyan}${o[2]}.${w.reset} ${Et(o[3])}
353
353
  `);return}}this._safeWrite(`${Et(e)}
354
- `)}};Mc.exports={renderMarkdown:Op,renderInline:Et,stripHeadingMarkers:St,highlightCode:Go,highlightJS:Sc,highlightBash:Ec,highlightJSON:Tc,highlightPython:Cc,highlightGo:Rc,highlightRust:Ac,highlightCSS:Oc,highlightHTML:Nc,renderTable:Np,renderProgress:Mp,StreamRenderer:Ho}});var Yo=L((J$,jc)=>{var{execSync:Pp}=require("child_process"),zo=require("path"),wn=require("fs"),Ko=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function Lc(){return zo.join(process.cwd(),".nex","hooks")}function Lp(){return zo.join(process.cwd(),".nex","config.json")}function Ic(){let t=Lp();if(!wn.existsSync(t))return{};try{return JSON.parse(wn.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function ys(t){if(!Ko.includes(t))return[];let e=[],s=Lc(),n=zo.join(s,t);wn.existsSync(n)&&e.push(n);let o=Ic();if(o[t]){let i=Array.isArray(o[t])?o[t]:[o[t]];e.push(...i)}return e}function qc(t,e={},s=3e4){try{return{success:!0,output:Pp(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 Ip(t,e={}){let s=ys(t);if(s.length===0)return[];let n={};for(let[i,r]of Object.entries(e))n[`NEX_${i.toUpperCase()}`]=String(r);let o=[];for(let i of s){let r=qc(i,n);if(o.push({command:i,...r}),!r.success&&t.startsWith("pre-"))break}return o}function qp(t){return ys(t).length>0}function jp(){let t=[];for(let e of Ko){let s=ys(e);s.length>0&&t.push({event:e,commands:s})}return t}function Dp(){let t=Lc();return wn.existsSync(t)||wn.mkdirSync(t,{recursive:!0}),t}jc.exports={HOOK_EVENTS:Ko,loadHookConfig:Ic,getHooksForEvent:ys,executeHook:qc,runHooks:Ip,hasHooks:qp,listHooks:jp,initHooksDir:Dp}});var de=L((Q$,Vc)=>{var{C:b,Spinner:Wt,TaskProgress:Fp,formatToolCall:Up,formatResult:Wp,formatToolSummary:Hc,formatSectionHeader:ws,setActiveTaskProgress:X$}=ce(),{callStream:Bp}=ge(),{parseToolArgs:Hp}=Un(),{executeTool:Gp}=Ue(),{gatherProjectContext:zp}=Lo(),{fitToContext:Kp,forceCompress:Jo,getUsage:Yp,estimateTokens:Jp}=Pe(),{autoSave:Xp,flushAutoSave:Vp}=_t();function ze(t){Xp(t),Vp()}var{getMemoryContext:Qp}=lt(),{checkPermission:Zp,setPermission:eh,savePermissions:th}=yn(),{confirm:Gc,setAllowAlwaysHandler:nh}=Fe(),{isPlanMode:vs,getPlanModePrompt:sh,PLAN_MODE_ALLOWED_TOOLS:zc,setPlanContent:oh}=Ut(),{StreamRenderer:rh}=Pc(),{runHooks:Dc}=Yo(),{routeMCPCall:ih,getMCPToolDefinitions:ah}=zn(),{getSkillInstructions:ch,getSkillToolDefinitions:lh,routeSkillCall:uh}=en(),{trackUsage:dh}=Nt(),{validateToolArgs:fh}=oo(),{filterToolsForModel:Fc,getModelTier:mh,PROVIDER_DEFAULT_TIER:V$}=$o(),{getConfiguredProviders:ph,getActiveProviderName:bn,getActiveModelId:bs,setActiveModel:Uc,MODEL_EQUIVALENTS:Ss}=ge(),rr=require("fs"),ir=require("path"),Wc=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi;function hh(t){let e=[],s;for(Wc.lastIndex=0;(s=Wc.exec(t))!==null;){let n=s[1].trim(),o=n.startsWith("~")?n.replace("~",process.env.HOME||""):ir.resolve(n);rr.existsSync(o)&&e.push({raw:n,abs:o})}return e}function gh(t){let e=rr.readFileSync(t),s=ir.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 Kc(t){let e=hh(t);if(e.length===0)return t;let s=[{type:"text",text:t}];for(let n of e)try{let{data:o,media_type:i}=gh(n.abs);s.push({type:"image",media_type:i,data:o})}catch{}return s.length>1?s:t}var Xo=null,Vo=null,Qo=null;function Bt(){if(Xo===null){let{TOOL_DEFINITIONS:t}=Ue();Xo=t}return Vo===null&&(Vo=lh()),Qo===null&&(Qo=ah()),[...Xo,...Vo,...Qo]}var sr=50;function $h(t){Number.isFinite(t)&&t>0&&(sr=t)}var xs=()=>null;function yh(t){xs=t}var xn=null,or=null,Ht=null,_s=new Map,wh=1e4,bh=6e3,xh=/\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 _h(t){return!t||typeof t!="string"?t:t.replace(xh,(e,s)=>`${s}=***REDACTED***`)}function kh(t){let e=_h(t);if(Jp(e)>wh)try{let{compressToolResult:n}=Pe();return n(e,bh)}catch{return e}return e}function Yc(t){try{let{getActiveModel:e}=ge(),s=e(),n=s?`${s.provider}:${s.id}`:"default";if(_s.has(n))return _s.get(n);let o=Fc(t);return _s.set(n,o),o}catch{return Fc(t)}}function vh(){_s.clear()}async function Jc(){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(i=>t.stat(i).then(r=>`${i}:${r.mtimeMs}`)))).filter(i=>i.status==="fulfilled").map(i=>i.value);try{let{getMemoryContextHash:i}=lt(),r=i();r&&o.push(`memory:${r}`)}catch{}try{let i=e.join(process.cwd(),".nex","brain");if(rr.existsSync(i)){let r=await t.stat(i);o.push(`brain:${r.mtimeMs}`)}}catch{}return o.join("|")}catch{return`fallback:${Date.now()}`}}function Sh(){xn=null,or=null,Ht=null}var Eh=new Set(["spawn_agents"]),Zo=5,er=3,tr=2,Th=parseInt(process.env.NEX_STALE_WARN_MS||"60000",10),Ch=parseInt(process.env.NEX_STALE_ABORT_MS||"120000",10),Rh=process.env.NEX_STALE_AUTO_SWITCH!=="0";function Ah(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{}}nh(t=>{eh(t,"allow"),th(),console.log(`${b.green} \u2713 ${t}: always allow${b.reset}`)});async function Oh(t){let e=t.function.name,s=Hp(t.function.arguments),n=t.id||`cli-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!s){let l=Bt().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.
354
+ `)}};Pc.exports={renderMarkdown:Op,renderInline:Et,stripHeadingMarkers:St,highlightCode:zo,highlightJS:Ec,highlightBash:Tc,highlightJSON:Cc,highlightPython:Rc,highlightGo:Ac,highlightRust:Oc,highlightCSS:Nc,highlightHTML:Mc,renderTable:Np,renderProgress:Mp,StreamRenderer:Go}});var Jo=L((X$,Dc)=>{var{execSync:Pp}=require("child_process"),Ko=require("path"),wn=require("fs"),Yo=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function Ic(){return Ko.join(process.cwd(),".nex","hooks")}function Lp(){return Ko.join(process.cwd(),".nex","config.json")}function qc(){let t=Lp();if(!wn.existsSync(t))return{};try{return JSON.parse(wn.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function ys(t){if(!Yo.includes(t))return[];let e=[],o=Ic(),n=Ko.join(o,t);wn.existsSync(n)&&e.push(n);let s=qc();if(s[t]){let i=Array.isArray(s[t])?s[t]:[s[t]];e.push(...i)}return e}function jc(t,e={},o=3e4){try{return{success:!0,output:Pp(t,{cwd:process.cwd(),encoding:"utf-8",timeout:o,env:{...process.env,...e},stdio:["pipe","pipe","pipe"]}).trim()}}catch(n){return{success:!1,error:n.stderr?n.stderr.trim():n.message}}}function Ip(t,e={}){let o=ys(t);if(o.length===0)return[];let n={};for(let[i,r]of Object.entries(e))n[`NEX_${i.toUpperCase()}`]=String(r);let s=[];for(let i of o){let r=jc(i,n);if(s.push({command:i,...r}),!r.success&&t.startsWith("pre-"))break}return s}function qp(t){return ys(t).length>0}function jp(){let t=[];for(let e of Yo){let o=ys(e);o.length>0&&t.push({event:e,commands:o})}return t}function Dp(){let t=Ic();return wn.existsSync(t)||wn.mkdirSync(t,{recursive:!0}),t}Dc.exports={HOOK_EVENTS:Yo,loadHookConfig:qc,getHooksForEvent:ys,executeHook:jc,runHooks:Ip,hasHooks:qp,listHooks:jp,initHooksDir:Dp}});var de=L((Z$,Qc)=>{var{C:b,Spinner:Wt,TaskProgress:Fp,formatToolCall:Up,formatResult:Wp,formatToolSummary:Gc,formatSectionHeader:ws,setActiveTaskProgress:V$}=ce(),{callStream:Bp}=ge(),{parseToolArgs:Hp}=Un(),{executeTool:Gp}=Ue(),{gatherProjectContext:zp}=Io(),{fitToContext:Kp,forceCompress:Xo,getUsage:Yp,estimateTokens:Jp}=Pe(),{autoSave:Xp,flushAutoSave:Vp}=_t();function ze(t){Xp(t),Vp()}var{getMemoryContext:Qp}=lt(),{checkPermission:Zp,setPermission:eh,savePermissions:th}=yn(),{confirm:zc,setAllowAlwaysHandler:nh}=Fe(),{isPlanMode:vs,getPlanModePrompt:sh,PLAN_MODE_ALLOWED_TOOLS:Kc,setPlanContent:oh}=Ut(),{StreamRenderer:rh}=Lc(),{runHooks:Fc}=Jo(),{routeMCPCall:ih,getMCPToolDefinitions:ah}=zn(),{getSkillInstructions:ch,getSkillToolDefinitions:lh,routeSkillCall:uh}=en(),{trackUsage:dh}=Nt(),{validateToolArgs:fh}=ro(),{filterToolsForModel:Uc,getModelTier:mh,PROVIDER_DEFAULT_TIER:Q$}=yo(),{getConfiguredProviders:ph,getActiveProviderName:bn,getActiveModelId:bs,setActiveModel:Wc,MODEL_EQUIVALENTS:Ss}=ge(),ir=require("fs"),ar=require("path"),Bc=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi;function hh(t){let e=[],o;for(Bc.lastIndex=0;(o=Bc.exec(t))!==null;){let n=o[1].trim(),s=n.startsWith("~")?n.replace("~",process.env.HOME||""):ar.resolve(n);ir.existsSync(s)&&e.push({raw:n,abs:s})}return e}function gh(t){let e=ir.readFileSync(t),o=ar.extname(t).toLowerCase().replace(".",""),n=o==="jpg"||o==="jpeg"?"image/jpeg":o==="png"?"image/png":o==="gif"?"image/gif":o==="webp"?"image/webp":"image/png";return{data:e.toString("base64"),media_type:n}}function Yc(t){let e=hh(t);if(e.length===0)return t;let o=[{type:"text",text:t}];for(let n of e)try{let{data:s,media_type:i}=gh(n.abs);o.push({type:"image",media_type:i,data:s})}catch{}return o.length>1?o:t}var Vo=null,Qo=null,Zo=null;function Bt(){if(Vo===null){let{TOOL_DEFINITIONS:t}=Ue();Vo=t}return Qo===null&&(Qo=lh()),Zo===null&&(Zo=ah()),[...Vo,...Qo,...Zo]}var or=50;function $h(t){Number.isFinite(t)&&t>0&&(or=t)}var xs=()=>null;function yh(t){xs=t}var xn=null,rr=null,Ht=null,_s=new Map,wh=1e4,bh=6e3,xh=/\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 _h(t){return!t||typeof t!="string"?t:t.replace(xh,(e,o)=>`${o}=***REDACTED***`)}function kh(t){let e=_h(t);if(Jp(e)>wh)try{let{compressToolResult:n}=Pe();return n(e,bh)}catch{return e}return e}function Jc(t){try{let{getActiveModel:e}=ge(),o=e(),n=o?`${o.provider}:${o.id}`:"default";if(_s.has(n))return _s.get(n);let s=Uc(t);return _s.set(n,s),s}catch{return Uc(t)}}function vh(){_s.clear()}async function Xc(){try{let t=require("fs").promises,e=require("path"),o=[e.join(process.cwd(),"package.json"),e.join(process.cwd(),".git","HEAD"),e.join(process.cwd(),"README.md"),e.join(process.cwd(),"NEX.md")],s=(await Promise.allSettled(o.map(i=>t.stat(i).then(r=>`${i}:${r.mtimeMs}`)))).filter(i=>i.status==="fulfilled").map(i=>i.value);try{let{getMemoryContextHash:i}=lt(),r=i();r&&s.push(`memory:${r}`)}catch{}try{let i=e.join(process.cwd(),".nex","brain");if(ir.existsSync(i)){let r=await t.stat(i);s.push(`brain:${r.mtimeMs}`)}}catch{}return s.join("|")}catch{return`fallback:${Date.now()}`}}function Sh(){xn=null,rr=null,Ht=null}var Eh=new Set(["spawn_agents"]),er=5,tr=3,nr=2,Th=parseInt(process.env.NEX_STALE_WARN_MS||"60000",10),Ch=parseInt(process.env.NEX_STALE_ABORT_MS||"120000",10),Rh=process.env.NEX_STALE_AUTO_SWITCH!=="0";function Ah(t){try{let e=require("fs"),o=require("path"),n=o.join(process.cwd(),".nex","plans");e.existsSync(n)||e.mkdirSync(n,{recursive:!0});let s=o.join(n,"current-plan.md");e.writeFileSync(s,t,"utf-8")}catch{}}nh(t=>{eh(t,"allow"),th(),console.log(`${b.green} \u2713 ${t}: always allow${b.reset}`)});async function Oh(t){let e=t.function.name,o=Hp(t.function.arguments),n=t.id||`cli-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!o){let l=Bt().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.
355
355
  Raw input: ${typeof t.function.arguments=="string"?t.function.arguments.substring(0,200):"N/A"}
356
356
 
357
357
  Expected JSON schema for "${e}":
358
358
  ${u}
359
359
 
360
- Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:n}}}let o=fh(e,s);if(!o.valid)return console.log(`${b.yellow} \u26A0 ${e}: ${o.error.split(`
361
- `)[0]}${b.reset}`),{callId:n,fnName:e,args:s,canExecute:!1,errorResult:{role:"tool",content:o.error,tool_call_id:n}};let i=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(vs()&&!zc.has(e))return console.log(`${b.yellow} \u2717 ${e}: blocked in plan mode${b.reset}`),{callId:n,fnName:e,args:i,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 r=Zp(e);if(r==="deny")return console.log(`${b.red} \u2717 ${e}: denied by permissions${b.reset}`),{callId:n,fnName:e,args:i,canExecute:!1,errorResult:{role:"tool",content:`DENIED: Tool '${e}' is blocked by permissions`,tool_call_id:n}};if(r==="ask"){let c=` Allow ${e}?`;return e==="bash"&&i.command&&(c=` bash: \`${i.command.substring(0,80)}${i.command.length>80?"\u2026":""}\`?`),await Gc(c,{toolName:e})?{callId:n,fnName:e,args:i,canExecute:!0,confirmedByUser:!0,errorResult:null}:{callId:n,fnName:e,args:i,canExecute:!1,confirmedByUser:!1,errorResult:{role:"tool",content:`CANCELLED: User declined ${e}`,tool_call_id:n}}}return{callId:n,fnName:e,args:i,canExecute:!0,confirmedByUser:!0,errorResult:null}}async function Nh(t,e,s={}){let n=await uh(t,e);if(n!==null)return n;let o=await ih(t,e);return o!==null?o:Gp(t,e,s)}function Mh(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 nr(t,e=!1){e||console.log(Up(t.fnName,t.args)),Dc("pre-tool",{tool_name:t.fnName});let s=await Nh(t.fnName,t.args,{silent:!0,autoConfirm:t.confirmedByUser===!0}),n=String(s??""),o=n.length>5e4?n.substring(0,5e4)+`
362
- ...(truncated ${n.length-5e4} chars)`:n,i=o.split(`
363
- `)[0],r=i.startsWith("ERROR")||i.includes("CANCELLED")||i.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(o)&&/✗ Agent/.test(o),c=Hc(t.fnName,t.args,o,r);return e||(console.log(Wp(o)),console.log(c)),Dc("post-tool",{tool_name:t.fnName}),{msg:{role:"tool",content:kh(o),tool_call_id:t.callId},summary:c}}async function Ph(t,e=!1,s={}){let n=new Array(t.length),o=[],i=[],r=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=Mh(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}`}r=new Wt(u),r.start()}}async function c(){if(i.length!==0){if(i.length===1){let l=i[0],{msg:u,summary:d}=await nr(t[l],e);n[l]=u,o.push(d)}else{let l=i.map(d=>nr(t[d],e)),u=await Promise.all(l);for(let d=0;d<i.length;d++)n[i[d]]=u[d].msg,o.push(u[d].summary)}i=[]}}for(let l=0;l<t.length;l++){let u=t[l];if(!u.canExecute){await c(),n[l]=u.errorResult,o.push(Hc(u.fnName,u.args||{},u.errorResult.content,!0));continue}if(Eh.has(u.fnName)){await c(),u.fnName==="spawn_agents"&&r&&(r.stop(),r=null);let{msg:d,summary:f}=await nr(u,e);n[l]=d,o.push(f)}else i.push(l)}if(await c(),r&&r.stop(),e&&o.length>0&&!s.skipSummaries)for(let l of o)console.log(l);return{results:n,summaries:o}}var Y=[],Bc=300,ks=[];function Lh(t){ks.push(t.trim())}function Ih(){return ks.length===0?null:ks.splice(0,ks.length).join(`
364
- `)}function qh(){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)
365
- `];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, always display the actual .PHONY declarations and dependency chains"),o.push(" \u2022 For dataclasses, always show the complete class definition with field types and defaults");let i=e||(n?"English":null);i&&o.push(`CODE LANGUAGE: Write all code comments, docstrings, variable descriptions, and inline documentation in ${i}.`);let r=s||(n?"English":null);return r&&o.push(`COMMIT MESSAGES: Write all git commit messages in ${r}.`),n&&o.push(`
366
- 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(`
360
+ Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:n}}}let s=fh(e,o);if(!s.valid)return console.log(`${b.yellow} \u26A0 ${e}: ${s.error.split(`
361
+ `)[0]}${b.reset}`),{callId:n,fnName:e,args:o,canExecute:!1,errorResult:{role:"tool",content:s.error,tool_call_id:n}};let i=s.corrected||o;if(s.corrected){let c=Object.keys(o),l=Object.keys(s.corrected),u=c.filter(d=>!l.includes(d));u.length&&console.log(`${b.dim} \u2713 ${e}: corrected args (${u.join(", ")})${b.reset}`)}if(vs()&&!Kc.has(e))return console.log(`${b.yellow} \u2717 ${e}: blocked in plan mode${b.reset}`),{callId:n,fnName:e,args:i,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 r=Zp(e);if(r==="deny")return console.log(`${b.red} \u2717 ${e}: denied by permissions${b.reset}`),{callId:n,fnName:e,args:i,canExecute:!1,errorResult:{role:"tool",content:`DENIED: Tool '${e}' is blocked by permissions`,tool_call_id:n}};if(r==="ask"){let c=` Allow ${e}?`;return e==="bash"&&i.command&&(c=` bash: \`${i.command.substring(0,80)}${i.command.length>80?"\u2026":""}\`?`),await zc(c,{toolName:e})?{callId:n,fnName:e,args:i,canExecute:!0,confirmedByUser:!0,errorResult:null}:{callId:n,fnName:e,args:i,canExecute:!1,confirmedByUser:!1,errorResult:{role:"tool",content:`CANCELLED: User declined ${e}`,tool_call_id:n}}}return{callId:n,fnName:e,args:i,canExecute:!0,confirmedByUser:!0,errorResult:null}}async function Nh(t,e,o={}){let n=await uh(t,e);if(n!==null)return n;let s=await ih(t,e);return s!==null?s:Gp(t,e,o)}function Mh(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 sr(t,e=!1){e||console.log(Up(t.fnName,t.args)),Fc("pre-tool",{tool_name:t.fnName});let o=await Nh(t.fnName,t.args,{silent:!0,autoConfirm:t.confirmedByUser===!0}),n=String(o??""),s=n.length>5e4?n.substring(0,5e4)+`
362
+ ...(truncated ${n.length-5e4} chars)`:n,i=s.split(`
363
+ `)[0],r=i.startsWith("ERROR")||i.includes("CANCELLED")||i.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(s)&&/✗ Agent/.test(s),c=Gc(t.fnName,t.args,s,r);return e||(console.log(Wp(s)),console.log(c)),Fc("post-tool",{tool_name:t.fnName}),{msg:{role:"tool",content:kh(s),tool_call_id:t.callId},summary:c}}async function Ph(t,e=!1,o={}){let n=new Array(t.length),s=[],i=[],r=null;if(e&&!o.skipSpinner){let l=t.filter(u=>u.canExecute);if(l.length>0){let u;if(l.length===1){let d=l[0],f=Mh(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}`}r=new Wt(u),r.start()}}async function c(){if(i.length!==0){if(i.length===1){let l=i[0],{msg:u,summary:d}=await sr(t[l],e);n[l]=u,s.push(d)}else{let l=i.map(d=>sr(t[d],e)),u=await Promise.all(l);for(let d=0;d<i.length;d++)n[i[d]]=u[d].msg,s.push(u[d].summary)}i=[]}}for(let l=0;l<t.length;l++){let u=t[l];if(!u.canExecute){await c(),n[l]=u.errorResult,s.push(Gc(u.fnName,u.args||{},u.errorResult.content,!0));continue}if(Eh.has(u.fnName)){await c(),u.fnName==="spawn_agents"&&r&&(r.stop(),r=null);let{msg:d,summary:f}=await sr(u,e);n[l]=d,s.push(f)}else i.push(l)}if(await c(),r&&r.stop(),e&&s.length>0&&!o.skipSummaries)for(let l of s)console.log(l);return{results:n,summaries:s}}var Y=[],Hc=300,ks=[];function Lh(t){ks.push(t.trim())}function Ih(){return ks.length===0?null:ks.splice(0,ks.length).join(`
364
+ `)}function qh(){let t=process.env.NEX_LANGUAGE,e=process.env.NEX_CODE_LANGUAGE,o=process.env.NEX_COMMIT_LANGUAGE,n=!t||t==="auto"?null:t,s=[`# Language Rules (CRITICAL \u2014 enforce strictly)
365
+ `];n?s.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.`):s.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."),s.push("CODE EXAMPLES: Always show actual, working code examples \u2014 never pseudocode or placeholder snippets."),s.push("COMPLETENESS RULES:"),s.push(" \u2022 ALWAYS show actual code when explaining implementations \u2014 never describe without showing"),s.push(" \u2022 Include complete examples with full context (imports, function signatures, error handling)"),s.push(' \u2022 Show alternative approaches when relevant (e.g., "Alternative: use util.promisify instead")'),s.push(" \u2022 Include edge cases in explanations (empty input, null values, boundary conditions)"),s.push(" \u2022 Provide platform-specific guidance when commands differ by OS (Linux/macOS/Windows)"),s.push(" \u2022 For Makefiles, always display the actual .PHONY declarations and dependency chains"),s.push(" \u2022 For dataclasses, always show the complete class definition with field types and defaults");let i=e||(n?"English":null);i&&s.push(`CODE LANGUAGE: Write all code comments, docstrings, variable descriptions, and inline documentation in ${i}.`);let r=o||(n?"English":null);return r&&s.push(`COMMIT MESSAGES: Write all git commit messages in ${r}.`),n&&s.push(`
366
+ 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.`),s.join(`
367
367
  `)+`
368
368
 
369
- `}function jh(){if(Ht!==null)return Ht;try{let e=ph().flatMap(o=>o.models.map(i=>({spec:`${o.name}:${i.id}`,tier:mh(i.id,o.name),name:i.name})));if(e.length<2)return Ht="","";let s={full:"complex tasks (refactor, implement, generate)",standard:"regular tasks (edit, fix, analyze)",essential:"simple tasks (read, search, list)"},n=`
369
+ `}function jh(){if(Ht!==null)return Ht;try{let e=ph().flatMap(s=>s.models.map(i=>({spec:`${s.name}:${i.id}`,tier:mh(i.id,s.name),name:i.name})));if(e.length<2)return Ht="","";let o={full:"complex tasks (refactor, implement, generate)",standard:"regular tasks (edit, fix, analyze)",essential:"simple tasks (read, search, list)"},n=`
370
370
  # Sub-Agent Model Routing
371
371
 
372
372
  `;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 |
373
373
  |---|---|---|
374
- `;for(let o of e)n+=`| ${o.spec} | ${o.tier} | ${s[o.tier]||o.tier} |
375
- `;return Ht=n,n}catch(t){return process.env.NEX_DEBUG&&console.error("[agent] model routing guide failed:",t.message),Ht="",""}}async function Xc(){let t=await Jc();if(xn!==null&&t===or)return xn;let e=await zp(process.cwd()),s=Qp(),n=ch(),o=vs()?sh():"",i=qh();return xn=`You are Nex Code, an expert coding assistant. You help with programming tasks by reading, writing, and editing files, running commands, and answering questions.
374
+ `;for(let s of e)n+=`| ${s.spec} | ${s.tier} | ${o[s.tier]||s.tier} |
375
+ `;return Ht=n,n}catch(t){return process.env.NEX_DEBUG&&console.error("[agent] model routing guide failed:",t.message),Ht="",""}}async function Vc(){let t=await Xc();if(xn!==null&&t===rr)return xn;let e=await zp(process.cwd()),o=Qp(),n=ch(),s=vs()?sh():"",i=qh();return xn=`You are Nex Code, an expert coding assistant. You help with programming tasks by reading, writing, and editing files, running commands, and answering questions.
376
376
 
377
377
  WORKING DIRECTORY: ${process.cwd()}
378
378
  All relative paths resolve from this directory.
379
379
  PROJECT CONTEXT:
380
380
  ${e}
381
- ${s?`
382
- ${s}
381
+ ${o?`
382
+ ${o}
383
383
  `:""}${n?`
384
384
  ${n}
385
- `:""}${o?`
386
- ${o}
385
+ `:""}${s?`
386
+ ${s}
387
387
  `:""}
388
388
  ${i?`${i}
389
389
  `:""}# Core Behavior
@@ -544,23 +544,23 @@ You have access to a persistent knowledge base in .nex/brain/.
544
544
  - Include tags in frontmatter for better retrieval
545
545
  - The user reviews all brain writes via /brain review or git diff
546
546
 
547
- `,or=t,xn}function Dh(){Y=[]}function Fh(){Y.length>Bc&&Y.splice(0,Y.length-Bc)}function Uh(){return Y.length}function Wh(){return Y}function Bh(t){Y=t}async function Hh(){let{execFile:t}=require("child_process"),e=require("fs"),s=process.cwd(),n=(f,m)=>new Promise(h=>{t(f,m,{cwd:s,timeout:3e3},(p,g)=>{h(p?"":(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/*"])]),i=new Set(["js","ts","jsx","tsx","py","go","rs","rb","java","cpp","c","cs"]),r=(o?o.split(`
548
- `):[]).filter(f=>{let m=f.split(".").pop();return i.has(m)});if(r.length<3)return null;let c={};for(let f of r){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=ir.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+=`
549
- \u{1F4E6} ${h}${p}`}}catch{}return u}function Ke(t,e,s,n,o){if(t<1)return;let i=[...e.values()].reduce((c,l)=>c+l,0),r=`\u2500\u2500 ${t} ${t===1?"step":"steps"} \xB7 ${i} ${i===1?"tool":"tools"}`;if(s.size>0&&(r+=` \xB7 ${s.size} ${s.size===1?"file":"files"} modified`),o){let c=Date.now()-o,l=Math.round(c/1e3);r+=l>=60?` \xB7 ${Math.floor(l/60)}m ${l%60}s`:` \xB7 ${l}s`}r+=" \u2500\u2500",console.log(`
550
- ${b.dim} ${r}${b.reset}`),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 Gh(){if(!process.stdout.isTTY)return{action:"quit"};let t=bn(),e=bs(),s=Ss.fast?.[t],n=Ss.strong?.[t],o=s&&s!==e,i=n&&n!==e&&n!==s,r=[];r.push({key:"r",label:`Retry with current model ${b.dim}(${e})${b.reset}`}),o&&r.push({key:"f",label:`Switch to ${b.bold}${s}${b.reset} ${b.dim}\u2014 fast, low latency${b.reset}`,model:s}),i&&r.push({key:"s",label:`Switch to ${b.bold}${n}${b.reset} ${b.dim}\u2014 reliable tool-calling, medium speed${b.reset}`,model:n}),r.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 r)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,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}
551
- `),m==="")return c({action:"quit"});let p=r.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)})}async function zh(t){let e=Kc(t);Y.push({role:"user",content:e}),Fh();let{setOnChange:s}=ns(),n=null,o=0;s((V,ne)=>{V==="create"?(n&&n.stop(),n=new Fp(ne.name,ne.tasks),n.setStats({tokens:o}),n.start()):V==="update"&&n?n.updateTask(ne.id,ne.status):V==="clear"&&n&&(n.stop(),n=null)});let i=await Xc(),r=i;try{let{getBrainContext:V}=mn(),ne=await V(t);ne&&(r=i+`
547
+ `,rr=t,xn}function Dh(){Y=[]}function Fh(){Y.length>Hc&&Y.splice(0,Y.length-Hc)}function Uh(){return Y.length}function Wh(){return Y}function Bh(t){Y=t}async function Hh(){let{execFile:t}=require("child_process"),e=require("fs"),o=process.cwd(),n=(f,m)=>new Promise(h=>{t(f,m,{cwd:o,timeout:3e3},(p,g)=>{h(p?"":(g||"").trim())})}),[s]=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/*"])]),i=new Set(["js","ts","jsx","tsx","py","go","rs","rb","java","cpp","c","cs"]),r=(s?s.split(`
548
+ `):[]).filter(f=>{let m=f.split(".").pop();return i.has(m)});if(r.length<3)return null;let c={};for(let f of r){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=ar.join(o,"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+=`
549
+ \u{1F4E6} ${h}${p}`}}catch{}return u}function Ke(t,e,o,n,s){if(t<1)return;let i=[...e.values()].reduce((c,l)=>c+l,0),r=`\u2500\u2500 ${t} ${t===1?"step":"steps"} \xB7 ${i} ${i===1?"tool":"tools"}`;if(o.size>0&&(r+=` \xB7 ${o.size} ${o.size===1?"file":"files"} modified`),s){let c=Date.now()-s,l=Math.round(c/1e3);r+=l>=60?` \xB7 ${Math.floor(l/60)}m ${l%60}s`:` \xB7 ${l}s`}r+=" \u2500\u2500",console.log(`
550
+ ${b.dim} ${r}${b.reset}`),o.size>0?console.log(`${b.dim} \u{1F4A1} /diff \xB7 /commit \xB7 /undo${b.reset}`):n.size>=5&&o.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 Gh(){if(!process.stdout.isTTY)return{action:"quit"};let t=bn(),e=bs(),o=Ss.fast?.[t],n=Ss.strong?.[t],s=o&&o!==e,i=n&&n!==e&&n!==o,r=[];r.push({key:"r",label:`Retry with current model ${b.dim}(${e})${b.reset}`}),s&&r.push({key:"f",label:`Switch to ${b.bold}${o}${b.reset} ${b.dim}\u2014 fast, low latency${b.reset}`,model:o}),i&&r.push({key:"s",label:`Switch to ${b.bold}${n}${b.reset} ${b.dim}\u2014 reliable tool-calling, medium speed${b.reset}`,model:n}),r.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 r)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,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}
551
+ `),m==="")return c({action:"quit"});let p=r.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)})}async function zh(t){let e=Yc(t);Y.push({role:"user",content:e}),Fh();let{setOnChange:o}=ns(),n=null,s=0;o((V,ne)=>{V==="create"?(n&&n.stop(),n=new Fp(ne.name,ne.tasks),n.setStats({tokens:s}),n.start()):V==="update"&&n?n.updateTask(ne.id,ne.status):V==="clear"&&n&&(n.stop(),n=null)});let i=await Vc(),r=i;try{let{getBrainContext:V}=mn(),ne=await V(t);ne&&(r=i+`
552
552
  `+ne+`
553
- `)}catch(V){process.env.NEX_DEBUG&&console.error("[agent] brain context failed:",V.message)}let c=[{role:"system",content:r},...Y],l=new Wt("Thinking...");l.start();let d=Y.length===1?Hh().catch(()=>null):Promise.resolve(null),f=Bt(),[{messages:m,compressed:h,compacted:p,tokensRemoved:g},$]=await Promise.all([Kp(c,f),d]),y=Yp(c,f);if(l.stop(),$&&console.log(`${b.dim}${$}${b.reset}`),p)console.log(`${b.dim} [context compacted \u2014 summary (~${g} tokens freed)]${b.reset}`);else if(h){let V=y.limit>0?Math.round(g/y.limit*100):0;console.log(`${b.dim} [context compressed \u2014 ~${g} tokens freed (${V}%)]${b.reset}`)}y.percentage>85&&console.log(`${b.yellow} \u26A0 Context ${Math.round(y.percentage)}% full \u2014 consider /clear or /save + start fresh${b.reset}`);let x=m,T=0,k=0,E=0,C=0,O=0,v=0,F=new Map,j=new Set,J=new Set,U=Date.now(),Q=new Map,me=5,Sn=10,he=new Map,Tt=5,P=8,M=0,H=6,X=10,D,W=sr,G=0,Z=10;e:for(;;){for(D=0;D<W&&!xs()?.aborted;D++){let ne=!0,$e=null;if(n&&n.isActive())n._paused&&n.resume();else if(!n){let S=v>0?`Thinking... (step ${v+1})`:"Thinking...";$e=new Wt(S),$e.start()}let Ae=!0,qe="",xe=new rh,ot,As=Date.now(),En=!1,Os=new AbortController,Er=setInterval(()=>{let S=Date.now()-As;if(S>=Ch)xe._clearCursorLine(),console.log(`${b.yellow} \u26A0 Stream stale for ${Math.round(S/1e3)}s \u2014 aborting and retrying${b.reset}`),Os.abort();else if(S>=Th&&!En){En=!0,xe._clearCursorLine();let q=Ss.fast?.[bn()];console.log(`${b.yellow} \u26A0 No tokens received for ${Math.round(S/1e3)}s \u2014 waiting...${b.reset}`),q&&q!==bs()?console.log(`${b.dim} \u{1F4A1} Will auto-switch to ${q} if no tokens arrive before abort${b.reset}`):q&&console.log(`${b.dim} \u{1F4A1} Ctrl+C to abort and retry${b.reset}`)}},5e3),Oe="",Je=null;try{let S=Yc(Bt()),q=vs()?S.filter(ue=>zc.has(ue.function.name)):S,Cn=xs(),z=new AbortController;Cn&&Cn.addEventListener("abort",()=>z.abort(),{once:!0}),Os.signal.addEventListener("abort",()=>z.abort(),{once:!0}),ot=await Bp(x,q,{signal:z.signal,onThinkingToken:()=>{As=Date.now(),En=!1},onToken:ue=>{As=Date.now(),En=!1,Oe+=ue,process.stdout.isTTY?Je||(Je=setTimeout(()=>{Oe&&xe&&xe.push(Oe),Oe="",Je=null},50)):(xe.push(Oe),Oe=""),Ae&&(n&&!n._paused?n.pause():$e&&$e.stop(),ne||(ne=!0),xe.startCursor(),Ae=!1),qe+=ue}})}catch(S){if(clearInterval(Er),Je&&(clearTimeout(Je),Je=null),Oe&&xe&&(xe.push(Oe),Oe=""),n&&!n._paused&&n.pause(),$e&&$e.stop(),xe.stopCursor(),Os.signal.aborted&&!xs()?.aborted){if(E++,E>tr){if(C<1){C++,console.log(`${b.yellow} \u26A0 Stale retries exhausted \u2014 last-resort force-compress...${b.reset}`);let ye=Bt(),{messages:Ee,tokensRemoved:Ct}=Jo(x,ye);x=Ee,console.log(`${b.dim} [force-compressed \u2014 ~${Ct} tokens freed]${b.reset}`),E=0,D--;continue}n&&(n.stop(),n=null);let B=await Gh();if(B.action==="quit"){s(null),Ke(v,F,j,J,U),ze(Y);break}B.action==="switch"&&(Uc(`${B.provider}:${B.model}`),console.log(`${b.green} \u2713 Switched to ${B.provider}:${B.model}${b.reset}`)),E=0,C=0,D--;continue}let z=E===1?3e3:5e3;if(E>=1&&O<1){O++,console.log(`${b.yellow} \u26A0 Stale retry ${E}/${tr} \u2014 force-compressing before retry...${b.reset}`);let B=Bt(),{messages:ye,tokensRemoved:Ee}=Jo(x,B);if(x=ye,Ee>0&&console.log(`${b.dim} [force-compressed \u2014 ~${Ee} tokens freed]${b.reset}`),Rh){let Ct=Ss.fast?.[bn()];Ct&&Ct!==bs()&&(Uc(`${bn()}:${Ct}`),console.log(`${b.cyan} \u26A1 Auto-switched to ${Ct} 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 ${E}/${tr} \u2014 retrying in ${z/1e3}s...${b.reset}`);let ue=new Wt(`Waiting ${z/1e3}s before retry...`);ue.start(),await new Promise(B=>setTimeout(B,z)),ue.stop(),D--;continue}if(S.name==="AbortError"||S.name==="CanceledError"||S.message?.includes("canceled")||S.message?.includes("aborted")){n&&(n.stop(),n=null),s(null),Ke(v,F,j,J,U),ze(Y);break}let q=S.message;if(S.code==="ECONNREFUSED"||S.message.includes("ECONNREFUSED"))q="Connection refused \u2014 please check your internet connection or API endpoint";else if(S.code==="ENOTFOUND"||S.message.includes("ENOTFOUND"))q="Network error \u2014 could not reach the API server. Please check your connection";else if(S.code==="ETIMEDOUT"||S.message.includes("timeout"))q="Request timed out \u2014 the API server took too long to respond. Please try again";else if(S.message.includes("401")||S.message.includes("Unauthorized"))q="Authentication failed \u2014 please check your API key in the .env file";else if(S.message.includes("403")||S.message.includes("Forbidden"))q="Access denied \u2014 your API key may not have permission for this model";else if(S.message.includes("400")){if(C<2){C++,console.log(`${b.yellow} \u26A0 Bad request (400) \u2014 force-compressing and retrying... (attempt ${C}/2)${b.reset}`);let B=Bt(),{messages:ye,tokensRemoved:Ee}=Jo(x,B);x=ye,Ee>0&&console.log(`${b.dim} [force-compressed \u2014 ~${Ee} tokens freed]${b.reset}`),D--;continue}let z=(S.message||"").toLowerCase();z.includes("context")||z.includes("token")||z.includes("length")||z.includes("too long")||z.includes("too many")||z.includes("prompt")||z.includes("size")||z.includes("exceeds")||z.includes("num_ctx")||z.includes("input")?q="Context too long \u2014 force compression exhausted. Use /clear to start fresh":q="Bad request \u2014 compression did not help. Use /clear and retry"}else S.message.includes("500")||S.message.includes("502")||S.message.includes("503")||S.message.includes("504")?q="API server error \u2014 the provider is experiencing issues. Please try again in a moment":(S.message.includes("fetch failed")||S.message.includes("fetch"))&&(q="Network request failed \u2014 please check your internet connection");if(console.log(`${b.red} \u2717 ${q}${b.reset}`),S.message.includes("429")){if(T++,T>Zo){console.log(`${b.red} Rate limit: max retries (${Zo}) exceeded. Try again later or use /budget to check your limits.${b.reset}`),n&&(n.stop(),n=null),s(null),Ke(v,F,j,J,U),ze(Y);break}let z=Math.min(1e4*Math.pow(2,T-1),12e4),ue=new Wt(`Rate limit \u2014 waiting ${Math.round(z/1e3)}s (retry ${T}/${Zo})`);ue.start(),await new Promise(B=>setTimeout(B,z)),ue.stop();continue}if(S.message.includes("socket disconnected")||S.message.includes("TLS")||S.message.includes("ECONNRESET")||S.message.includes("ECONNABORTED")||S.message.includes("ETIMEDOUT")||S.code==="ECONNRESET"||S.code==="ECONNABORTED"){if(k++,k>er){console.log(`${b.red} Network error: max retries (${er}) exceeded. Check your connection and try again.${b.reset}`),n&&(n.stop(),n=null),s(null),Ke(v,F,j,J,U),ze(Y);break}let z=Math.min(2e3*Math.pow(2,k-1),3e4),ue=new Wt(`Network error \u2014 retrying in ${Math.round(z/1e3)}s (${k}/${er})`);ue.start(),await new Promise(B=>setTimeout(B,z)),ue.stop(),D--;continue}n&&(n.stop(),n=null),s(null),Ke(v,F,j,J,U),ze(Y);break}clearInterval(Er),T=0,k=0,Ae&&(n&&!n._paused&&n.pause(),$e&&$e.stop()),Je&&(clearTimeout(Je),Je=null),Oe&&xe&&(xe.push(Oe),Oe=""),qe&&xe.flush(),k=0,E=0,ot&&ot.usage&&(dh(bn(),bs(),ot.usage.prompt_tokens||0,ot.usage.completion_tokens||0),o+=(ot.usage.prompt_tokens||0)+(ot.usage.completion_tokens||0),n&&n.setStats({tokens:o}));let{content:Ns,tool_calls:mt}=ot,Ms={role:"assistant",content:Ns||""};if(mt&&mt.length>0&&(Ms.tool_calls=mt),Y.push(Ms),x.push(Ms),!mt||mt.length===0){let S=(Ns||"").trim().length>0||qe.trim().length>0;if(!S&&v>0&&D<sr-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."};x.push(q),Y.push(q);continue}if(vs()&&S){let q=(Ns||qe||"").trim();oh(q),Ah(q),console.log(`
554
- ${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),Ke(v,F,j,J,U),ze(Y);return}v++,v>1&&(ne=!1);for(let S of mt){let q=S.function.name;F.set(q,(F.get(q)||0)+1)}let je=await Promise.all(mt.map(S=>Oh(S))),Yt=n?{skipSpinner:!0,skipSummaries:!0}:{},Wl=je.some(S=>S.fnName==="ask_user"),Tr=!Yt.skipSummaries&&!ne,Tn=null;if(Tr&&!Wl)if(ne=!0,Yt.skipSpinner=!0,process.stdout.isTTY){let S=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],q=0;process.stdout.write(ws(je,v,!1,S[0])),Tn=setInterval(()=>{process.stdout.write(`\r\x1B[2K${ws(je,v,!1,S[q++%S.length])}`)},80)}else process.stdout.write(ws(je,v,!1)+`
555
- `);else Tr&&(ne=!0,Yt.skipSpinner=!0);n&&n._paused&&n.resume();let{results:Cr,summaries:Rr}=await Ph(je,!0,{...Yt,skipSummaries:!0});if(Tn&&(clearInterval(Tn),Tn=null,process.stdout.write(`\r\x1B[2K${ws(je,v,!1)}
556
- `)),!Yt.skipSummaries)for(let S=0;S<Rr.length;S++)je[S]&&je[S].fnName==="ask_user"||console.log(Rr[S]);for(let S=0;S<je.length;S++){let q=je[S];if(!q.canExecute)continue;let z=Cr[S].content.split(`
557
- `)[0],ue=!z.startsWith("ERROR")&&!z.startsWith("CANCELLED");if(ue&&["write_file","edit_file","patch_file"].includes(q.fnName)&&q.args&&q.args.path){j.add(q.args.path);let B=(Q.get(q.args.path)||0)+1;Q.set(q.args.path,B);let ye=q.args.path.split("/").slice(-2).join("/");if(B===me){console.log(`${b.yellow} \u26A0 Loop warning: "${ye}" edited ${B}\xD7 \u2014 possible edit loop${b.reset}`);let Ee={role:"user",content:`[SYSTEM WARNING] You have edited "${q.args.path}" ${B} 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(Ee),x.push(Ee)}else if(B>=Sn){console.log(`${b.red} \u2716 Loop abort: "${ye}" edited ${B}\xD7 \u2014 aborting to prevent runaway loop${b.reset}`),n&&(n.stop(),n=null),s(null),Ke(v,F,j,J,U),ze(Y);return}}if(q.fnName==="bash_exec"&&q.args&&q.args.command){let B=q.args.command.replace(/\s+/g," ").trim().slice(0,100),ye=(he.get(B)||0)+1;if(he.set(B,ye),ye===Tt){console.log(`${b.yellow} \u26A0 Loop warning: same bash command run ${ye}\xD7 \u2014 possible debug loop${b.reset}`);let Ee={role:"user",content:`[SYSTEM WARNING] You have run the same or similar bash command ${ye} 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(Ee),x.push(Ee)}else if(ye>=P){console.log(`${b.red} \u2716 Loop abort: same bash command run ${ye}\xD7 \u2014 aborting runaway debug loop${b.reset}`),n&&(n.stop(),n=null),s(null),Ke(v,F,j,J,U),ze(Y);return}}if(ue)M=0;else if(M++,M===H){console.log(`${b.yellow} \u26A0 Loop warning: ${M} consecutive tool errors \u2014 possible stuck loop${b.reset}`);let B={role:"user",content:`[SYSTEM WARNING] ${M} 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(B),x.push(B)}else if(M>=X){console.log(`${b.red} \u2716 Loop abort: ${M} consecutive errors \u2014 aborting stuck loop${b.reset}`),n&&(n.stop(),n=null),s(null),Ke(v,F,j,J,U),ze(Y);return}ue&&q.fnName==="read_file"&&q.args&&q.args.path&&J.add(q.args.path)}for(let S of Cr)Y.push(S),x.push(S);let Ar=Ih();if(Ar){let S={role:"user",content:`[User note mid-run]: ${Ar}`};Y.push(S),x.push(S),console.log(`${b.cyan} \u270E Kontext hinzugef\xFCgt${b.reset}`)}}if(D>=W){n&&(n.stop(),n=null),s(null),Ke(v,F,j,J,U),ze(Y);let{getActiveProviderName:V}=ge();if(V()==="ollama"&&G<Z){G++,W=20,console.log(`${b.dim} \u2500\u2500 auto-extending (+20 turns, ext ${G}/${Z}) \u2500\u2500${b.reset}`);continue e}if(console.log(`
558
- ${b.yellow}\u26A0 Max iterations reached.${b.reset}`),await Gc(" Continue for 20 more turns?")){W=20;continue e}console.log(`${b.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${b.reset}`)}break e}}Vc.exports={processInput:zh,clearConversation:Dh,getConversationLength:Uh,getConversationMessages:Wh,setConversationMessages:Bh,setAbortSignalGetter:yh,setMaxIterations:$h,invalidateSystemPromptCache:Sh,clearToolFilterCache:vh,getCachedFilteredTools:Yc,buildSystemPrompt:Xc,getProjectContextHash:Jc,buildUserContent:Kc,injectMidRunNote:Lh}});var ge=L((Z$,nl)=>{var{OllamaProvider:Kh}=Yr(),{OpenAIProvider:Yh}=di(),{AnthropicProvider:Jh}=hi(),{GeminiProvider:Xh}=wi(),{LocalProvider:Vh}=_i(),{checkBudget:Qh}=Nt(),ar={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"}},Qc={};for(let[t,e]of Object.entries(ar))for(let s of Object.values(e))Qc[s]=t;function Zc(t,e){let s=Qc[t];return s&&ar[s][e]||t}var pe={},Se=null,fe=null,_n=[];function Me(){if(Object.keys(pe).length>0)return;Gt("ollama",new Kh),Gt("openai",new Yh),Gt("anthropic",new Jh),Gt("gemini",new Xh),Gt("local",new Vh);let t=process.env.DEFAULT_PROVIDER||"ollama",e=process.env.DEFAULT_MODEL||null;pe[t]?(Se=t,fe=e||pe[t].defaultModel):(Se="ollama",fe="kimi-k2.5");let s=process.env.FALLBACK_CHAIN;s&&(_n=s.split(",").map(n=>n.trim()).filter(Boolean))}function Gt(t,e){pe[t]=e}function Zh(t){return Me(),pe[t]||null}function cr(){return Me(),pe[Se]||null}function eg(){return Me(),Se}function tg(){return Me(),fe}function ng(){Me();let t=cr();if(!t)return{id:fe,name:fe,provider:Se};let e=t.getModel(fe);return e?{...e,provider:Se}:{id:fe,name:fe,provider:Se}}function el(t){if(!t)return{provider:null,model:null};let e=t.indexOf(":");if(e>0){let s=t.slice(0,e);if(pe[s]||["ollama","openai","anthropic","gemini","local"].includes(s))return{provider:s,model:t.slice(e+1)}}return{provider:null,model:t}}function sg(t){Me();let{provider:e,model:s}=el(t);if(e){let o=pe[e];return o&&(o.getModel(s)||e==="local"||e==="ollama")?(Se=e,fe=s,Es(),!0):!1}let n=cr();if(n&&n.getModel(s))return fe=s,Es(),!0;for(let[o,i]of Object.entries(pe))if(i.getModel(s))return Se=o,fe=s,Es(),!0;return!1}function Es(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=de();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=Pe();t()}catch{}}function og(){Me();let t=new Set;for(let e of Object.values(pe))for(let s of e.getModelNames())t.add(s);return Array.from(t)}function rg(){return Me(),Object.entries(pe).map(([t,e])=>({provider:t,configured:e.isConfigured(),models:Object.values(e.getModels()).map(s=>({...s,active:t===Se&&s.id===fe}))}))}function ig(){Me();let t=[];for(let[e,s]of Object.entries(pe)){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 ag(t){_n=Array.isArray(t)?t:[]}function cg(){return[..._n]}function lg(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 tl(t){let e=[Se,..._n.filter(i=>i!==Se)],s,n=0,o=0;for(let i=0;i<e.length;i++){let r=e[i],c=pe[r];if(!c||!c.isConfigured())continue;o++;let l=Qh(r);if(!l.allowed){n++,s=new Error(`Budget limit reached for ${r}: $${l.spent.toFixed(2)} / $${l.limit.toFixed(2)}`);continue}try{let u=i>0,d=u?Zc(fe,r):fe;return u&&d!==fe&&process.stderr.write(` [fallback: ${r}:${d}]
559
- `),await t(c,r,d)}catch(u){if(s=u,lg(u)&&i<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 ug(t,e,s={}){return Me(),tl((n,o,i)=>n.stream(t,e,{model:i,signal:s.signal,...s}))}async function dg(t,e,s={}){if(Me(),s.provider){let n=pe[s.provider];if(!n||!n.isConfigured())throw new Error(`Provider '${s.provider}' is not available`);let o={model:s.model||fe,...s};try{return await n.chat(t,e,o)}catch(i){if(typeof n.stream=="function")try{return await n.stream(t,e,{...o,onToken:()=>{}})}catch{}throw i}}return tl(async(n,o,i)=>{try{return await n.chat(t,e,{model:i,...s})}catch(r){if(typeof n.stream=="function")try{return await n.stream(t,e,{model:i,...s,onToken:()=>{}})}catch{}throw r}})}function fg(){Me();let t=[];for(let[e,s]of Object.entries(pe))s.isConfigured()&&t.push({name:e,models:Object.values(s.getModels())});return t}function mg(){for(let t of Object.keys(pe))delete pe[t];Se=null,fe=null,_n=[]}nl.exports={registerProvider:Gt,getProvider:Zh,getActiveProvider:cr,getActiveProviderName:eg,getActiveModelId:tg,getActiveModel:ng,setActiveModel:sg,getModelNames:og,parseModelSpec:el,listProviders:rg,listAllModels:ig,callStream:ug,callChat:dg,getConfiguredProviders:fg,setFallbackChain:ag,getFallbackChain:cg,resolveModelForProvider:Zc,MODEL_EQUIVALENTS:ar,_reset:mg}});var rl=L((ey,ol)=>{"use strict";var pg="\x1B[2m",hg="\x1B[0m";function sl(t){return t.replace(/\x1b\[[^a-zA-Z]*[a-zA-Z]/g,"").length}var lr=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._lastOutputRow=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 pg+"\u2500".repeat(this._cols)+hg}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")}activate(e){if(!process.stdout.isTTY)return;this._rl=e,this._origWrite=process.stdout.write.bind(process.stdout),this._active=!0,this._setScrollRegion(),this._lastOutputRow=1,this.drawFooter();let s=this,n=process.stdout.write.bind(process.stdout);this._origWrite=n,process.stdout.write=function(u,...d){if(s._active&&typeof u=="string"){if(s._cursorOnInputRow){let $=u.replace(/\n/g,"");return $?n($,...d):!0}let f=s._cols||80,m=0,h=u.split(`
560
- `);for(let $=0;$<h.length;$++){let y=sl(h[$]);y>0&&(m+=Math.floor(y/f))}let g=h.length-1+m;g>0&&(s._lastOutputRow=Math.min(s._lastOutputRow+g,s._scrollEnd))}return n(u,...d)},this._cursorOnInputRow=!1,this._origStderrWrite=process.stderr.write.bind(process.stderr),process.stderr.write=function(u,...d){if(!s._active)return s._origStderrWrite(u,...d);if(typeof u=="string"&&u.includes("\r")){let f=Math.min(s._lastOutputRow+1,s._scrollEnd);s._origWrite(s._goto(f))}return s._origStderrWrite(u,...d)},this._origLog=console.log,this._origError=console.error;function o(...u){if(!s._active){s._origLog(...u);return}s._origWrite(s._goto(Math.min(s._lastOutputRow+1,s._scrollEnd))),s._cursorOnInputRow=!1,s._origLog(...u),s.drawFooter()}function i(...u){if(!s._active){s._origError(...u);return}s._origWrite(s._goto(Math.min(s._lastOutputRow+1,s._scrollEnd))),s._cursorOnInputRow=!1,s._origError(...u),s.drawFooter()}console.log=o,console.error=i,this._origSetPr=e.setPrompt.bind(e),e.setPrompt=function(u){s._origSetPr(u),s._active&&s.drawFooter(u)},this._origPrompt=e.prompt.bind(e),e.prompt=function(u){if(!s._active)return s._origPrompt(u);e._prevPos=null,s._origWrite(s._goto(s._rowInput)),s._origPrompt(u),s._cursorOnInputRow=!0};let r=e.question.bind(e);e.question=function(u,d){if(!s._active)return r(u,d);s._origWrite(s._goto(s._rowInput)+"\x1B[2K"),e._prevPos=null,s._cursorOnInputRow=!0,r(u,f=>{s._origWrite(s._goto(s._rowInput)+"\x1B[2K"),s._cursorOnInputRow=!1,s.drawFooter(),d(f)})};let c=e._refreshLine?e._refreshLine.bind(e):null;this._origRefreshLine=c,c&&(e._refreshLine=function(){if(!s._active)return c();let u=s._cols,d=sl(e._prompt||""),f=u-d-1;if(e.line.length<=f)return c();let m=e.line,h=e.cursor,p=Math.max(1,f-1),$=Math.max(0,h-p),y=($>0?"\xAB":"")+m.slice($,$+p+($>0?0:1));e.line=y,e.cursor=y.length,c(),e.line=m,e.cursor=h}),e.on("line",u=>{s._active&&(s._cursorOnInputRow=!1,s._origWrite(s._goto(s._rowInput)+"\x1B[2K"),s._origWrite(s._goto(Math.min(s._lastOutputRow+1,s._scrollEnd))),s.drawFooter())});let l=()=>{this._setScrollRegion(),this.drawFooter()};process.stdout.on("resize",l),this._offResize=()=>process.stdout.off("resize",l)}deactivate(){this._active&&(this._active=!1,this._offResize&&(this._offResize(),this._offResize=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&&(this._rl._refreshLine=this._origRefreshLine,this._origRefreshLine=null)),this._eraseStatus(),this._clearScrollRegion(),this._origWrite=null)}};ol.exports={StickyFooter:lr}});var cl=L((ty,al)=>{var{C:te}=ce(),{listProviders:gg,getActiveProviderName:$g,getActiveModelId:yg,setActiveModel:wg}=ge();function il(t,e,s={}){let{title:n="Select",hint:o="\u2191\u2193 navigate \xB7 Enter select \xB7 Esc cancel"}=s;return new Promise(i=>{let r=e.map((y,x)=>y.isHeader?-1:x).filter(y=>y>=0);if(r.length===0){i(null);return}let c=e.findIndex(y=>y.isCurrent),l=c>=0?r.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=r[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 E=0;E<m;E++)process.stdout.write(`\x1B[2K
561
- `);process.stdout.write(`\x1B[${m}A`)}let y=[];y.push(` ${te.bold}${te.cyan}${n}${te.reset}`),y.push(` ${te.dim}${o}${te.reset}`),y.push("");let{start:x,end:T}=f();x>0&&y.push(` ${te.dim}\u2191 more${te.reset}`);for(let E=x;E<T;E++){let C=e[E];if(C.isHeader){y.push(` ${te.bold}${te.dim}${C.label}${te.reset}`);continue}let O=r[l]===E,v=O?`${te.cyan}> `:" ",F=C.isCurrent?` ${te.yellow}<current>${te.reset}`:"";O?y.push(`${v}${te.bold}${C.label}${te.reset}${F}`):y.push(`${v}${te.dim}${C.label}${te.reset}${F}`)}T<e.length&&y.push(` ${te.dim}\u2193 more${te.reset}`);let k=y.join(`
553
+ `)}catch(V){process.env.NEX_DEBUG&&console.error("[agent] brain context failed:",V.message)}let c=[{role:"system",content:r},...Y],l=new Wt("Thinking...");l.start();let d=Y.length===1?Hh().catch(()=>null):Promise.resolve(null),f=Bt(),[{messages:m,compressed:h,compacted:p,tokensRemoved:g},$]=await Promise.all([Kp(c,f),d]),y=Yp(c,f);if(l.stop(),$&&console.log(`${b.dim}${$}${b.reset}`),p)console.log(`${b.dim} [context compacted \u2014 summary (~${g} tokens freed)]${b.reset}`);else if(h){let V=y.limit>0?Math.round(g/y.limit*100):0;console.log(`${b.dim} [context compressed \u2014 ~${g} tokens freed (${V}%)]${b.reset}`)}y.percentage>85&&console.log(`${b.yellow} \u26A0 Context ${Math.round(y.percentage)}% full \u2014 consider /clear or /save + start fresh${b.reset}`);let x=m,T=0,k=0,E=0,C=0,O=0,v=0,F=new Map,j=new Set,J=new Set,U=Date.now(),Q=new Map,me=5,Sn=10,he=new Map,Tt=5,P=8,M=0,H=6,X=10,D,W=or,G=0,Z=10;e:for(;;){for(D=0;D<W&&!xs()?.aborted;D++){let ne=!0,$e=null;if(n&&n.isActive())n._paused&&n.resume();else if(!n){let S=v>0?`Thinking... (step ${v+1})`:"Thinking...";$e=new Wt(S),$e.start()}let Ae=!0,qe="",xe=new rh,ot,Os=Date.now(),En=!1,Ns=new AbortController,Tr=setInterval(()=>{let S=Date.now()-Os;if(S>=Ch)xe._clearCursorLine(),console.log(`${b.yellow} \u26A0 Stream stale for ${Math.round(S/1e3)}s \u2014 aborting and retrying${b.reset}`),Ns.abort();else if(S>=Th&&!En){En=!0,xe._clearCursorLine();let q=Ss.fast?.[bn()];console.log(`${b.yellow} \u26A0 No tokens received for ${Math.round(S/1e3)}s \u2014 waiting...${b.reset}`),q&&q!==bs()?console.log(`${b.dim} \u{1F4A1} Will auto-switch to ${q} if no tokens arrive before abort${b.reset}`):q&&console.log(`${b.dim} \u{1F4A1} Ctrl+C to abort and retry${b.reset}`)}},5e3),Oe="",Je=null;try{let S=Jc(Bt()),q=vs()?S.filter(ue=>Kc.has(ue.function.name)):S,Cn=xs(),z=new AbortController;Cn&&Cn.addEventListener("abort",()=>z.abort(),{once:!0}),Ns.signal.addEventListener("abort",()=>z.abort(),{once:!0}),ot=await Bp(x,q,{signal:z.signal,onThinkingToken:()=>{Os=Date.now(),En=!1},onToken:ue=>{Os=Date.now(),En=!1,Oe+=ue,process.stdout.isTTY?Je||(Je=setTimeout(()=>{Oe&&xe&&xe.push(Oe),Oe="",Je=null},50)):(xe.push(Oe),Oe=""),Ae&&(n&&!n._paused?n.pause():$e&&$e.stop(),ne||(ne=!0),xe.startCursor(),Ae=!1),qe+=ue}})}catch(S){if(clearInterval(Tr),Je&&(clearTimeout(Je),Je=null),Oe&&xe&&(xe.push(Oe),Oe=""),n&&!n._paused&&n.pause(),$e&&$e.stop(),xe.stopCursor(),Ns.signal.aborted&&!xs()?.aborted){if(E++,E>nr){if(C<1){C++,console.log(`${b.yellow} \u26A0 Stale retries exhausted \u2014 last-resort force-compress...${b.reset}`);let ye=Bt(),{messages:Ee,tokensRemoved:Ct}=Xo(x,ye);x=Ee,console.log(`${b.dim} [force-compressed \u2014 ~${Ct} tokens freed]${b.reset}`),E=0,D--;continue}n&&(n.stop(),n=null);let B=await Gh();if(B.action==="quit"){o(null),Ke(v,F,j,J,U),ze(Y);break}B.action==="switch"&&(Wc(`${B.provider}:${B.model}`),console.log(`${b.green} \u2713 Switched to ${B.provider}:${B.model}${b.reset}`)),E=0,C=0,D--;continue}let z=E===1?3e3:5e3;if(E>=1&&O<1){O++,console.log(`${b.yellow} \u26A0 Stale retry ${E}/${nr} \u2014 force-compressing before retry...${b.reset}`);let B=Bt(),{messages:ye,tokensRemoved:Ee}=Xo(x,B);if(x=ye,Ee>0&&console.log(`${b.dim} [force-compressed \u2014 ~${Ee} tokens freed]${b.reset}`),Rh){let Ct=Ss.fast?.[bn()];Ct&&Ct!==bs()&&(Wc(`${bn()}:${Ct}`),console.log(`${b.cyan} \u26A1 Auto-switched to ${Ct} 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 ${E}/${nr} \u2014 retrying in ${z/1e3}s...${b.reset}`);let ue=new Wt(`Waiting ${z/1e3}s before retry...`);ue.start(),await new Promise(B=>setTimeout(B,z)),ue.stop(),D--;continue}if(S.name==="AbortError"||S.name==="CanceledError"||S.message?.includes("canceled")||S.message?.includes("aborted")){n&&(n.stop(),n=null),o(null),Ke(v,F,j,J,U),ze(Y);break}let q=S.message;if(S.code==="ECONNREFUSED"||S.message.includes("ECONNREFUSED"))q="Connection refused \u2014 please check your internet connection or API endpoint";else if(S.code==="ENOTFOUND"||S.message.includes("ENOTFOUND"))q="Network error \u2014 could not reach the API server. Please check your connection";else if(S.code==="ETIMEDOUT"||S.message.includes("timeout"))q="Request timed out \u2014 the API server took too long to respond. Please try again";else if(S.message.includes("401")||S.message.includes("Unauthorized"))q="Authentication failed \u2014 please check your API key in the .env file";else if(S.message.includes("403")||S.message.includes("Forbidden"))q="Access denied \u2014 your API key may not have permission for this model";else if(S.message.includes("400")){if(C<2){C++,console.log(`${b.yellow} \u26A0 Bad request (400) \u2014 force-compressing and retrying... (attempt ${C}/2)${b.reset}`);let B=Bt(),{messages:ye,tokensRemoved:Ee}=Xo(x,B);x=ye,Ee>0&&console.log(`${b.dim} [force-compressed \u2014 ~${Ee} tokens freed]${b.reset}`),D--;continue}let z=(S.message||"").toLowerCase();z.includes("context")||z.includes("token")||z.includes("length")||z.includes("too long")||z.includes("too many")||z.includes("prompt")||z.includes("size")||z.includes("exceeds")||z.includes("num_ctx")||z.includes("input")?q="Context too long \u2014 force compression exhausted. Use /clear to start fresh":q="Bad request \u2014 compression did not help. Use /clear and retry"}else S.message.includes("500")||S.message.includes("502")||S.message.includes("503")||S.message.includes("504")?q="API server error \u2014 the provider is experiencing issues. Please try again in a moment":(S.message.includes("fetch failed")||S.message.includes("fetch"))&&(q="Network request failed \u2014 please check your internet connection");if(console.log(`${b.red} \u2717 ${q}${b.reset}`),S.message.includes("429")){if(T++,T>er){console.log(`${b.red} Rate limit: max retries (${er}) exceeded. Try again later or use /budget to check your limits.${b.reset}`),n&&(n.stop(),n=null),o(null),Ke(v,F,j,J,U),ze(Y);break}let z=Math.min(1e4*Math.pow(2,T-1),12e4),ue=new Wt(`Rate limit \u2014 waiting ${Math.round(z/1e3)}s (retry ${T}/${er})`);ue.start(),await new Promise(B=>setTimeout(B,z)),ue.stop();continue}if(S.message.includes("socket disconnected")||S.message.includes("TLS")||S.message.includes("ECONNRESET")||S.message.includes("ECONNABORTED")||S.message.includes("ETIMEDOUT")||S.code==="ECONNRESET"||S.code==="ECONNABORTED"){if(k++,k>tr){console.log(`${b.red} Network error: max retries (${tr}) exceeded. Check your connection and try again.${b.reset}`),n&&(n.stop(),n=null),o(null),Ke(v,F,j,J,U),ze(Y);break}let z=Math.min(2e3*Math.pow(2,k-1),3e4),ue=new Wt(`Network error \u2014 retrying in ${Math.round(z/1e3)}s (${k}/${tr})`);ue.start(),await new Promise(B=>setTimeout(B,z)),ue.stop(),D--;continue}n&&(n.stop(),n=null),o(null),Ke(v,F,j,J,U),ze(Y);break}clearInterval(Tr),T=0,k=0,Ae&&(n&&!n._paused&&n.pause(),$e&&$e.stop()),Je&&(clearTimeout(Je),Je=null),Oe&&xe&&(xe.push(Oe),Oe=""),qe&&xe.flush(),k=0,E=0,ot&&ot.usage&&(dh(bn(),bs(),ot.usage.prompt_tokens||0,ot.usage.completion_tokens||0),s+=(ot.usage.prompt_tokens||0)+(ot.usage.completion_tokens||0),n&&n.setStats({tokens:s}));let{content:Ms,tool_calls:mt}=ot,Ps={role:"assistant",content:Ms||""};if(mt&&mt.length>0&&(Ps.tool_calls=mt),Y.push(Ps),x.push(Ps),!mt||mt.length===0){let S=(Ms||"").trim().length>0||qe.trim().length>0;if(!S&&v>0&&D<or-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."};x.push(q),Y.push(q);continue}if(vs()&&S){let q=(Ms||qe||"").trim();oh(q),Ah(q),console.log(`
554
+ ${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),o(null),Ke(v,F,j,J,U),ze(Y);return}v++,v>1&&(ne=!1);for(let S of mt){let q=S.function.name;F.set(q,(F.get(q)||0)+1)}let je=await Promise.all(mt.map(S=>Oh(S))),Yt=n?{skipSpinner:!0,skipSummaries:!0}:{},Wl=je.some(S=>S.fnName==="ask_user"),Cr=!Yt.skipSummaries&&!ne,Tn=null;if(Cr&&!Wl)if(ne=!0,Yt.skipSpinner=!0,process.stdout.isTTY){let S=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],q=0;process.stdout.write(ws(je,v,!1,S[0])),Tn=setInterval(()=>{process.stdout.write(`\r\x1B[2K${ws(je,v,!1,S[q++%S.length])}`)},80)}else process.stdout.write(ws(je,v,!1)+`
555
+ `);else Cr&&(ne=!0,Yt.skipSpinner=!0);n&&n._paused&&n.resume();let{results:Rr,summaries:Ar}=await Ph(je,!0,{...Yt,skipSummaries:!0});if(Tn&&(clearInterval(Tn),Tn=null,process.stdout.write(`\r\x1B[2K${ws(je,v,!1)}
556
+ `)),!Yt.skipSummaries)for(let S=0;S<Ar.length;S++)je[S]&&je[S].fnName==="ask_user"||console.log(Ar[S]);for(let S=0;S<je.length;S++){let q=je[S];if(!q.canExecute)continue;let z=Rr[S].content.split(`
557
+ `)[0],ue=!z.startsWith("ERROR")&&!z.startsWith("CANCELLED");if(ue&&["write_file","edit_file","patch_file"].includes(q.fnName)&&q.args&&q.args.path){j.add(q.args.path);let B=(Q.get(q.args.path)||0)+1;Q.set(q.args.path,B);let ye=q.args.path.split("/").slice(-2).join("/");if(B===me){console.log(`${b.yellow} \u26A0 Loop warning: "${ye}" edited ${B}\xD7 \u2014 possible edit loop${b.reset}`);let Ee={role:"user",content:`[SYSTEM WARNING] You have edited "${q.args.path}" ${B} 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(Ee),x.push(Ee)}else if(B>=Sn){console.log(`${b.red} \u2716 Loop abort: "${ye}" edited ${B}\xD7 \u2014 aborting to prevent runaway loop${b.reset}`),n&&(n.stop(),n=null),o(null),Ke(v,F,j,J,U),ze(Y);return}}if(q.fnName==="bash_exec"&&q.args&&q.args.command){let B=q.args.command.replace(/\s+/g," ").trim().slice(0,100),ye=(he.get(B)||0)+1;if(he.set(B,ye),ye===Tt){console.log(`${b.yellow} \u26A0 Loop warning: same bash command run ${ye}\xD7 \u2014 possible debug loop${b.reset}`);let Ee={role:"user",content:`[SYSTEM WARNING] You have run the same or similar bash command ${ye} 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(Ee),x.push(Ee)}else if(ye>=P){console.log(`${b.red} \u2716 Loop abort: same bash command run ${ye}\xD7 \u2014 aborting runaway debug loop${b.reset}`),n&&(n.stop(),n=null),o(null),Ke(v,F,j,J,U),ze(Y);return}}if(ue)M=0;else if(M++,M===H){console.log(`${b.yellow} \u26A0 Loop warning: ${M} consecutive tool errors \u2014 possible stuck loop${b.reset}`);let B={role:"user",content:`[SYSTEM WARNING] ${M} 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(B),x.push(B)}else if(M>=X){console.log(`${b.red} \u2716 Loop abort: ${M} consecutive errors \u2014 aborting stuck loop${b.reset}`),n&&(n.stop(),n=null),o(null),Ke(v,F,j,J,U),ze(Y);return}ue&&q.fnName==="read_file"&&q.args&&q.args.path&&J.add(q.args.path)}for(let S of Rr)Y.push(S),x.push(S);let Or=Ih();if(Or){let S={role:"user",content:`[User note mid-run]: ${Or}`};Y.push(S),x.push(S),console.log(`${b.cyan} \u270E Kontext hinzugef\xFCgt${b.reset}`)}}if(D>=W){n&&(n.stop(),n=null),o(null),Ke(v,F,j,J,U),ze(Y);let{getActiveProviderName:V}=ge();if(V()==="ollama"&&G<Z){G++,W=20,console.log(`${b.dim} \u2500\u2500 auto-extending (+20 turns, ext ${G}/${Z}) \u2500\u2500${b.reset}`);continue e}if(console.log(`
558
+ ${b.yellow}\u26A0 Max iterations reached.${b.reset}`),await zc(" Continue for 20 more turns?")){W=20;continue e}console.log(`${b.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${b.reset}`)}break e}}Qc.exports={processInput:zh,clearConversation:Dh,getConversationLength:Uh,getConversationMessages:Wh,setConversationMessages:Bh,setAbortSignalGetter:yh,setMaxIterations:$h,invalidateSystemPromptCache:Sh,clearToolFilterCache:vh,getCachedFilteredTools:Jc,buildSystemPrompt:Vc,getProjectContextHash:Xc,buildUserContent:Yc,injectMidRunNote:Lh}});var ge=L((ey,sl)=>{var{OllamaProvider:Kh}=Jr(),{OpenAIProvider:Yh}=fi(),{AnthropicProvider:Jh}=gi(),{GeminiProvider:Xh}=bi(),{LocalProvider:Vh}=ki(),{checkBudget:Qh}=Nt(),cr={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"}},Zc={};for(let[t,e]of Object.entries(cr))for(let o of Object.values(e))Zc[o]=t;function el(t,e){let o=Zc[t];return o&&cr[o][e]||t}var pe={},Se=null,fe=null,_n=[];function Me(){if(Object.keys(pe).length>0)return;Gt("ollama",new Kh),Gt("openai",new Yh),Gt("anthropic",new Jh),Gt("gemini",new Xh),Gt("local",new Vh);let t=process.env.DEFAULT_PROVIDER||"ollama",e=process.env.DEFAULT_MODEL||null;pe[t]?(Se=t,fe=e||pe[t].defaultModel):(Se="ollama",fe="kimi-k2.5");let o=process.env.FALLBACK_CHAIN;o&&(_n=o.split(",").map(n=>n.trim()).filter(Boolean))}function Gt(t,e){pe[t]=e}function Zh(t){return Me(),pe[t]||null}function lr(){return Me(),pe[Se]||null}function eg(){return Me(),Se}function tg(){return Me(),fe}function ng(){Me();let t=lr();if(!t)return{id:fe,name:fe,provider:Se};let e=t.getModel(fe);return e?{...e,provider:Se}:{id:fe,name:fe,provider:Se}}function tl(t){if(!t)return{provider:null,model:null};let e=t.indexOf(":");if(e>0){let o=t.slice(0,e);if(pe[o]||["ollama","openai","anthropic","gemini","local"].includes(o))return{provider:o,model:t.slice(e+1)}}return{provider:null,model:t}}function sg(t){Me();let{provider:e,model:o}=tl(t);if(e){let s=pe[e];return s&&(s.getModel(o)||e==="local"||e==="ollama")?(Se=e,fe=o,Es(),!0):!1}let n=lr();if(n&&n.getModel(o))return fe=o,Es(),!0;for(let[s,i]of Object.entries(pe))if(i.getModel(o))return Se=s,fe=o,Es(),!0;return!1}function Es(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=de();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=Pe();t()}catch{}}function og(){Me();let t=new Set;for(let e of Object.values(pe))for(let o of e.getModelNames())t.add(o);return Array.from(t)}function rg(){return Me(),Object.entries(pe).map(([t,e])=>({provider:t,configured:e.isConfigured(),models:Object.values(e.getModels()).map(o=>({...o,active:t===Se&&o.id===fe}))}))}function ig(){Me();let t=[];for(let[e,o]of Object.entries(pe)){let n=o.isConfigured();for(let s of Object.values(o.getModels()))t.push({spec:`${e}:${s.id}`,name:s.name,provider:e,configured:n})}return t}function ag(t){_n=Array.isArray(t)?t:[]}function cg(){return[..._n]}function lg(t){let e=t.message||"",o=t.code||"";return!!(e.includes("429")||e.includes("500")||e.includes("502")||e.includes("503")||e.includes("504")||o==="ECONNABORTED"||o==="ETIMEDOUT"||o==="ECONNREFUSED"||o==="ECONNRESET"||o==="EHOSTUNREACH"||o==="ENETUNREACH"||o==="EPIPE"||o==="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 nl(t){let e=[Se,..._n.filter(i=>i!==Se)],o,n=0,s=0;for(let i=0;i<e.length;i++){let r=e[i],c=pe[r];if(!c||!c.isConfigured())continue;s++;let l=Qh(r);if(!l.allowed){n++,o=new Error(`Budget limit reached for ${r}: $${l.spent.toFixed(2)} / $${l.limit.toFixed(2)}`);continue}try{let u=i>0,d=u?el(fe,r):fe;return u&&d!==fe&&process.stderr.write(` [fallback: ${r}:${d}]
559
+ `),await t(c,r,d)}catch(u){if(o=u,lg(u)&&i<e.length-1)continue;throw u}}throw n>0&&n===s?new Error("All providers are over budget. Use /budget to check limits or /budget <provider> off to remove a limit."):s===0?new Error("No configured provider available"):o||new Error("No configured provider available")}async function ug(t,e,o={}){return Me(),nl((n,s,i)=>n.stream(t,e,{model:i,signal:o.signal,...o}))}async function dg(t,e,o={}){if(Me(),o.provider){let n=pe[o.provider];if(!n||!n.isConfigured())throw new Error(`Provider '${o.provider}' is not available`);let s={model:o.model||fe,...o};try{return await n.chat(t,e,s)}catch(i){if(typeof n.stream=="function")try{return await n.stream(t,e,{...s,onToken:()=>{}})}catch{}throw i}}return nl(async(n,s,i)=>{try{return await n.chat(t,e,{model:i,...o})}catch(r){if(typeof n.stream=="function")try{return await n.stream(t,e,{model:i,...o,onToken:()=>{}})}catch{}throw r}})}function fg(){Me();let t=[];for(let[e,o]of Object.entries(pe))o.isConfigured()&&t.push({name:e,models:Object.values(o.getModels())});return t}function mg(){for(let t of Object.keys(pe))delete pe[t];Se=null,fe=null,_n=[]}sl.exports={registerProvider:Gt,getProvider:Zh,getActiveProvider:lr,getActiveProviderName:eg,getActiveModelId:tg,getActiveModel:ng,setActiveModel:sg,getModelNames:og,parseModelSpec:tl,listProviders:rg,listAllModels:ig,callStream:ug,callChat:dg,getConfiguredProviders:fg,setFallbackChain:ag,getFallbackChain:cg,resolveModelForProvider:el,MODEL_EQUIVALENTS:cr,_reset:mg}});var il=L((ty,rl)=>{"use strict";var pg="\x1B[2m",hg="\x1B[0m";function ol(t){return t.replace(/\x1b\[[^a-zA-Z]*[a-zA-Z]/g,"").length}var ur=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._lastOutputRow=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,o=1){return`\x1B[${e};${o}H`}_statusLine(){return pg+"\u2500".repeat(this._cols)+hg}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")}activate(e){if(!process.stdout.isTTY)return;this._rl=e,this._origWrite=process.stdout.write.bind(process.stdout),this._active=!0,this._setScrollRegion(),this._lastOutputRow=1,this.drawFooter();let o=this,n=process.stdout.write.bind(process.stdout);this._origWrite=n,process.stdout.write=function(u,...d){if(o._active&&typeof u=="string"){if(o._cursorOnInputRow){let $=u.replace(/\n/g,"");return $?n($,...d):!0}let f=o._cols||80,m=0,h=u.split(`
560
+ `);for(let $=0;$<h.length;$++){let y=ol(h[$]);y>0&&(m+=Math.floor(y/f))}let g=h.length-1+m;g>0&&(o._lastOutputRow=Math.min(o._lastOutputRow+g,o._scrollEnd))}return n(u,...d)},this._cursorOnInputRow=!1,this._origStderrWrite=process.stderr.write.bind(process.stderr),process.stderr.write=function(u,...d){if(!o._active)return o._origStderrWrite(u,...d);if(typeof u=="string"&&u.includes("\r")){let f=Math.min(o._lastOutputRow+1,o._scrollEnd);o._origWrite(o._goto(f))}return o._origStderrWrite(u,...d)},this._origLog=console.log,this._origError=console.error;function s(...u){if(!o._active){o._origLog(...u);return}o._origWrite(o._goto(Math.min(o._lastOutputRow+1,o._scrollEnd))),o._cursorOnInputRow=!1,o._origLog(...u),o.drawFooter()}function i(...u){if(!o._active){o._origError(...u);return}o._origWrite(o._goto(Math.min(o._lastOutputRow+1,o._scrollEnd))),o._cursorOnInputRow=!1,o._origError(...u),o.drawFooter()}console.log=s,console.error=i,this._origSetPr=e.setPrompt.bind(e),e.setPrompt=function(u){o._origSetPr(u),o._active&&o.drawFooter(u)},this._origPrompt=e.prompt.bind(e),e.prompt=function(u){if(!o._active)return o._origPrompt(u);e._prevPos=null,o._origWrite(o._goto(o._rowInput)),o._origPrompt(u),o._cursorOnInputRow=!0};let r=e.question.bind(e);e.question=function(u,d){if(!o._active)return r(u,d);o._origWrite(o._goto(o._rowInput)+"\x1B[2K"),e._prevPos=null,o._cursorOnInputRow=!0,r(u,f=>{o._origWrite(o._goto(o._rowInput)+"\x1B[2K"),o._cursorOnInputRow=!1,o.drawFooter(),d(f)})};let c=e._refreshLine?e._refreshLine.bind(e):null;this._origRefreshLine=c,c&&(e._refreshLine=function(){if(!o._active)return c();let u=o._cols,d=ol(e._prompt||""),f=u-d-1;if(e.line.length<=f)return c();let m=e.line,h=e.cursor,p=Math.max(1,f-1),$=Math.max(0,h-p),y=($>0?"\xAB":"")+m.slice($,$+p+($>0?0:1));e.line=y,e.cursor=y.length,c(),e.line=m,e.cursor=h}),e.on("line",u=>{o._active&&(o._cursorOnInputRow=!1,o._origWrite(o._goto(o._rowInput)+"\x1B[2K"),o._origWrite(o._goto(Math.min(o._lastOutputRow+1,o._scrollEnd))),o.drawFooter())});let l=()=>{this._setScrollRegion(),this.drawFooter()};process.stdout.on("resize",l),this._offResize=()=>process.stdout.off("resize",l)}deactivate(){this._active&&(this._active=!1,this._offResize&&(this._offResize(),this._offResize=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&&(this._rl._refreshLine=this._origRefreshLine,this._origRefreshLine=null)),this._eraseStatus(),this._clearScrollRegion(),this._origWrite=null)}};rl.exports={StickyFooter:ur}});var ll=L((ny,cl)=>{var{C:te}=ce(),{listProviders:gg,getActiveProviderName:$g,getActiveModelId:yg,setActiveModel:wg}=ge();function al(t,e,o={}){let{title:n="Select",hint:s="\u2191\u2193 navigate \xB7 Enter select \xB7 Esc cancel"}=o;return new Promise(i=>{let r=e.map((y,x)=>y.isHeader?-1:x).filter(y=>y>=0);if(r.length===0){i(null);return}let c=e.findIndex(y=>y.isCurrent),l=c>=0?r.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=r[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 E=0;E<m;E++)process.stdout.write(`\x1B[2K
561
+ `);process.stdout.write(`\x1B[${m}A`)}let y=[];y.push(` ${te.bold}${te.cyan}${n}${te.reset}`),y.push(` ${te.dim}${s}${te.reset}`),y.push("");let{start:x,end:T}=f();x>0&&y.push(` ${te.dim}\u2191 more${te.reset}`);for(let E=x;E<T;E++){let C=e[E];if(C.isHeader){y.push(` ${te.bold}${te.dim}${C.label}${te.reset}`);continue}let O=r[l]===E,v=O?`${te.cyan}> `:" ",F=C.isCurrent?` ${te.yellow}<current>${te.reset}`:"";O?y.push(`${v}${te.bold}${C.label}${te.reset}${F}`):y.push(`${v}${te.dim}${C.label}${te.reset}${F}`)}T<e.length&&y.push(` ${te.dim}\u2193 more${te.reset}`);let k=y.join(`
562
562
  `);process.stdout.write(k+`
563
- `),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,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<r.length-1&&(l++,h());return}if(x.name==="return"){let T=e[r[l]];g(),i(T?T.value:null);return}if(x.name==="escape"||x.ctrl&&x.name==="c"){g(),i(null);return}}}process.stdin.on("keypress",$),h()})}async function bg(t){let e=gg(),s=$g(),n=yg(),o=[];for(let r of e)if(r.models.length!==0){o.push({label:r.provider,value:null,isHeader:!0});for(let c of r.models){let l=r.provider===s&&c.id===n;o.push({label:` ${c.name} (${r.provider}:${c.id})`,value:`${r.provider}:${c.id}`,isCurrent:l})}}let i=await il(t,o,{title:"Select Model"});return i?(wg(i),console.log(`${te.green}Switched to ${i}${te.reset}`),!0):(console.log(`${te.dim}Cancelled${te.reset}`),!1)}al.exports={pickFromList:il,showModelPicker:bg}});var fr=L((sy,hl)=>{var ur=require("fs"),xg=require("path"),{callChat:ll}=ge(),{remember:_g,listMemories:ny,recall:kg}=lt(),dr=4,vg=`You are a memory optimization agent for an AI coding assistant called nex-code.
563
+ `),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,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<r.length-1&&(l++,h());return}if(x.name==="return"){let T=e[r[l]];g(),i(T?T.value:null);return}if(x.name==="escape"||x.ctrl&&x.name==="c"){g(),i(null);return}}}process.stdin.on("keypress",$),h()})}async function bg(t){let e=gg(),o=$g(),n=yg(),s=[];for(let r of e)if(r.models.length!==0){s.push({label:r.provider,value:null,isHeader:!0});for(let c of r.models){let l=r.provider===o&&c.id===n;s.push({label:` ${c.name} (${r.provider}:${c.id})`,value:`${r.provider}:${c.id}`,isCurrent:l})}}let i=await al(t,s,{title:"Select Model"});return i?(wg(i),console.log(`${te.green}Switched to ${i}${te.reset}`),!0):(console.log(`${te.dim}Cancelled${te.reset}`),!1)}cl.exports={pickFromList:al,showModelPicker:bg}});var mr=L((oy,gl)=>{var dr=require("fs"),xg=require("path"),{callChat:ul}=ge(),{remember:_g,listMemories:sy,recall:kg}=lt(),fr=4,vg=`You are a memory optimization agent for an AI coding assistant called nex-code.
564
564
  Analyze this conversation history and extract actionable learnings the assistant should remember.
565
565
 
566
566
  Return ONLY valid JSON in this exact format:
@@ -586,15 +586,15 @@ Rules:
586
586
  - value: concise actionable instruction, max 120 chars
587
587
  - nex_additions: project-level instructions/conventions only (not personal preferences)
588
588
  - If nothing significant to learn, return {"memories": [], "nex_additions": [], "summary": "..."}
589
- - Return ONLY the JSON, no markdown, no explanation`;function ul(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(`
589
+ - Return ONLY the JSON, no markdown, no explanation`;function dl(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(`
590
590
 
591
- `)}async function dl(t){if(t.filter(o=>o.role==="user").length<dr)return{memories:[],nex_additions:[],summary:null,skipped:!0};let s=ul(t);if(!s.trim())return{memories:[],nex_additions:[],summary:null,skipped:!0};let n=[{role:"system",content:vg},{role:"user",content:`Conversation to analyze:
591
+ `)}async function fl(t){if(t.filter(s=>s.role==="user").length<fr)return{memories:[],nex_additions:[],summary:null,skipped:!0};let o=dl(t);if(!o.trim())return{memories:[],nex_additions:[],summary:null,skipped:!0};let n=[{role:"system",content:vg},{role:"user",content:`Conversation to analyze:
592
592
 
593
- ${s}`}];try{let r=((await ll(n,[],{temperature:0,maxTokens:800})).content||"").trim().match(/\{[\s\S]*\}/);if(!r)return{memories:[],nex_additions:[],summary:null,error:"No JSON in response"};let c=JSON.parse(r[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 fl(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),i=n.trim().substring(0,200);if(!o||!i)continue;let r=kg(o);r!==i&&(_g(o,i),e.push({key:o,value:i,action:r?"updated":"added"}))}return e}function ml(t){if(!t||t.length===0)return[];let e=xg.join(process.cwd(),"NEX.md"),s="";try{ur.existsSync(e)&&(s=ur.readFileSync(e,"utf-8"))}catch{}let n=[],o=s;for(let i of t){if(!i||typeof i!="string")continue;let r=i.trim();if(!r)continue;let c=r.substring(0,35).toLowerCase();s.toLowerCase().includes(c)||(n.push(r),o=o?o.endsWith(`
594
- `)?o+r:o+`
595
- `+r:r)}return n.length>0&&(o.endsWith(`
596
- `)||(o+=`
597
- `),ur.writeFileSync(e,o,"utf-8")),n}async function Sg(t){let e=await dl(t);if(e.skipped)return{applied:[],nexAdded:[],summary:null,skipped:!0};if(e.error)return{applied:[],nexAdded:[],summary:null,error:e.error};let s=fl(e.memories),n=ml(e.nex_additions);return{applied:s,nexAdded:n,summary:e.summary}}var Eg=`You are a knowledge base agent for an AI coding assistant called nex-code.
593
+ ${o}`}];try{let r=((await ul(n,[],{temperature:0,maxTokens:800})).content||"").trim().match(/\{[\s\S]*\}/);if(!r)return{memories:[],nex_additions:[],summary:null,error:"No JSON in response"};let c=JSON.parse(r[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(s){return{memories:[],nex_additions:[],summary:null,error:s.message}}}function ml(t){let e=[];for(let{key:o,value:n}of t||[]){if(!o||!n||typeof o!="string"||typeof n!="string")continue;let s=o.trim().replace(/\s+/g,"-").substring(0,60),i=n.trim().substring(0,200);if(!s||!i)continue;let r=kg(s);r!==i&&(_g(s,i),e.push({key:s,value:i,action:r?"updated":"added"}))}return e}function pl(t){if(!t||t.length===0)return[];let e=xg.join(process.cwd(),"NEX.md"),o="";try{dr.existsSync(e)&&(o=dr.readFileSync(e,"utf-8"))}catch{}let n=[],s=o;for(let i of t){if(!i||typeof i!="string")continue;let r=i.trim();if(!r)continue;let c=r.substring(0,35).toLowerCase();o.toLowerCase().includes(c)||(n.push(r),s=s?s.endsWith(`
594
+ `)?s+r:s+`
595
+ `+r:r)}return n.length>0&&(s.endsWith(`
596
+ `)||(s+=`
597
+ `),dr.writeFileSync(e,s,"utf-8")),n}async function Sg(t){let e=await fl(t);if(e.skipped)return{applied:[],nexAdded:[],summary:null,skipped:!0};if(e.error)return{applied:[],nexAdded:[],summary:null,error:e.error};let o=ml(e.memories),n=pl(e.nex_additions);return{applied:o,nexAdded:n,summary:e.summary}}var Eg=`You are a knowledge base agent for an AI coding assistant called nex-code.
598
598
  Analyze this conversation and extract knowledge worth persisting in the project knowledge base (.nex/brain/).
599
599
 
600
600
  Return ONLY valid JSON in this exact format:
@@ -628,37 +628,37 @@ Rules:
628
628
  ---
629
629
  - Maximum 3 documents per session. Quality over quantity.
630
630
  - If nothing worth persisting: return {"documents": [], "skip_reason": "..."}
631
- - Return ONLY the JSON, no markdown fences, no explanation`;async function pl(t){if(t.filter(o=>o.role==="user").length<dr)return{documents:[],skip_reason:"Session too short"};let s=ul(t);if(!s.trim())return{documents:[],skip_reason:"No usable content"};let n=[{role:"system",content:Eg},{role:"user",content:`Conversation to analyze:
631
+ - Return ONLY the JSON, no markdown fences, no explanation`;async function hl(t){if(t.filter(s=>s.role==="user").length<fr)return{documents:[],skip_reason:"Session too short"};let o=dl(t);if(!o.trim())return{documents:[],skip_reason:"No usable content"};let n=[{role:"system",content:Eg},{role:"user",content:`Conversation to analyze:
632
632
 
633
- ${s}`}];try{let r=((await ll(n,[],{temperature:0,maxTokens:2e3})).content||"").trim().match(/\{[\s\S]*\}/);if(!r)return{documents:[],error:"No JSON in response"};let c=JSON.parse(r[0]);return{documents:Array.isArray(c.documents)?c.documents:[],skip_reason:c.skip_reason}}catch(o){return{documents:[],error:o.message}}}async function Tg(t){let e=await pl(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}=mn(),o=[],i=[];for(let r of e.documents){if(!r.name||!r.content)continue;let c=r.name.trim().replace(/\.md$/,"").replace(/[^a-z0-9-]/g,"-").substring(0,60);if(!c)continue;let l=n(c);if(l.content){let d=`
633
+ ${o}`}];try{let r=((await ul(n,[],{temperature:0,maxTokens:2e3})).content||"").trim().match(/\{[\s\S]*\}/);if(!r)return{documents:[],error:"No JSON in response"};let c=JSON.parse(r[0]);return{documents:Array.isArray(c.documents)?c.documents:[],skip_reason:c.skip_reason}}catch(s){return{documents:[],error:s.message}}}async function Tg(t){let e=await hl(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:o,readDocument:n}=mn(),s=[],i=[];for(let r of e.documents){if(!r.name||!r.content)continue;let c=r.name.trim().replace(/\.md$/,"").replace(/[^a-z0-9-]/g,"-").substring(0,60);if(!c)continue;let l=n(c);if(l.content){let d=`
634
634
 
635
635
  ## Update ${new Date().toISOString().split("T")[0]}
636
636
 
637
- ${r.content}`;s(c,l.content+d),o.push({name:c,reason:r.reason||"",action:"updated"})}else s(c,r.content),o.push({name:c,reason:r.reason||"",action:"created"})}return{written:o,skipped:i}}hl.exports={learnFromSession:Sg,learnBrainFromSession:Tg,reflectOnSession:dl,reflectBrain:pl,applyMemories:fl,applyNexAdditions:ml,LEARN_MIN_MESSAGES:dr}});var bl=L((ry,wl)=>{var be=require("fs"),Kt=require("path"),oy=require("os"),Cg=require("readline"),{C:A}=ce(),gl=".nex",mr=null;function Rg(t){mr=t}function Ce(t,e=""){let s=e?` ${A.dim}[${e}]${A.reset}`:"",n=` ${A.cyan}${t}${s}${A.reset}: `;return new Promise(o=>{let i=r=>{let c=r.trim()||e;o(c)};if(mr)mr.question(n,i);else{let r=Cg.createInterface({input:process.stdin,output:process.stdout});r.question(n,c=>{r.close(),i(c)})}})}function zt(t,e=!0){return Ce(`${t} (${e?"Y/n":"y/N"})`,e?"y":"n").then(n=>n.toLowerCase()!=="n"&&n.toLowerCase()!=="no")}async function $l(t,e,s){let n=e.map((c,l)=>`${A.dim}${l+1})${A.reset} ${c}`).join(" ");console.log(` ${A.cyan}${t}${A.reset}`),console.log(` ${n}`);let o=s?e.indexOf(s)+1:1,i=await Ce("Enter number",String(o)),r=parseInt(i,10)-1;return e[Math.max(0,Math.min(r,e.length-1))]}async function Ag(){let t=Kt.join(process.cwd(),gl),e=Kt.join(t,"servers.json"),s={};if(be.existsSync(e))try{s=JSON.parse(be.readFileSync(e,"utf-8"))}catch{}console.log(`
637
+ ${r.content}`;o(c,l.content+d),s.push({name:c,reason:r.reason||"",action:"updated"})}else o(c,r.content),s.push({name:c,reason:r.reason||"",action:"created"})}return{written:s,skipped:i}}gl.exports={learnFromSession:Sg,learnBrainFromSession:Tg,reflectOnSession:fl,reflectBrain:hl,applyMemories:ml,applyNexAdditions:pl,LEARN_MIN_MESSAGES:fr}});var xl=L((iy,bl)=>{var be=require("fs"),Kt=require("path"),ry=require("os"),Cg=require("readline"),{C:A}=ce(),$l=".nex",pr=null;function Rg(t){pr=t}function Ce(t,e=""){let o=e?` ${A.dim}[${e}]${A.reset}`:"",n=` ${A.cyan}${t}${o}${A.reset}: `;return new Promise(s=>{let i=r=>{let c=r.trim()||e;s(c)};if(pr)pr.question(n,i);else{let r=Cg.createInterface({input:process.stdin,output:process.stdout});r.question(n,c=>{r.close(),i(c)})}})}function zt(t,e=!0){return Ce(`${t} (${e?"Y/n":"y/N"})`,e?"y":"n").then(n=>n.toLowerCase()!=="n"&&n.toLowerCase()!=="no")}async function yl(t,e,o){let n=e.map((c,l)=>`${A.dim}${l+1})${A.reset} ${c}`).join(" ");console.log(` ${A.cyan}${t}${A.reset}`),console.log(` ${n}`);let s=o?e.indexOf(o)+1:1,i=await Ce("Enter number",String(s)),r=parseInt(i,10)-1;return e[Math.max(0,Math.min(r,e.length-1))]}async function Ag(){let t=Kt.join(process.cwd(),$l),e=Kt.join(t,"servers.json"),o={};if(be.existsSync(e))try{o=JSON.parse(be.readFileSync(e,"utf-8"))}catch{}console.log(`
638
638
  ${A.bold}${A.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${A.reset}`),console.log(`${A.bold}${A.cyan}\u2551 nex-code Server Setup Wizard \u2551${A.reset}`),console.log(`${A.bold}${A.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${A.reset}
639
- `);let n=Object.keys(s);if(n.length>0&&(console.log(`${A.dim}Existing profiles: ${n.join(", ")}${A.reset}`),!await zt("Add or update a server profile?",!0))){console.log(`${A.dim}No changes made.${A.reset}
640
- `);return}let o={...s},i=!0;for(;i;){console.log(`
641
- ${A.bold}\u2500\u2500\u2500 New Server Profile \u2500\u2500\u2500${A.reset}`);let l=await Ce("Profile name (e.g. prod, staging, macbook)");if(!l){console.log(`${A.red} Name is required.${A.reset}`);continue}let u=await Ce("Host / IP address");if(!u){console.log(`${A.red} Host is required.${A.reset}`);continue}let d=await Ce("SSH user","root"),f=await Ce("SSH port","22"),m=parseInt(f,10)||22,h=await Ce("SSH key path (leave empty for SSH agent)",""),p=await $l("Operating system",["almalinux9","macos","ubuntu","debian","other"],"almalinux9"),g=await zt("Allow sudo commands?",!0),$={host:u,user:d};m!==22&&($.port=m),h&&($.key=h),p!=="other"&&($.os=p),g&&($.sudo=!0),o[l]=$,console.log(`
639
+ `);let n=Object.keys(o);if(n.length>0&&(console.log(`${A.dim}Existing profiles: ${n.join(", ")}${A.reset}`),!await zt("Add or update a server profile?",!0))){console.log(`${A.dim}No changes made.${A.reset}
640
+ `);return}let s={...o},i=!0;for(;i;){console.log(`
641
+ ${A.bold}\u2500\u2500\u2500 New Server Profile \u2500\u2500\u2500${A.reset}`);let l=await Ce("Profile name (e.g. prod, staging, macbook)");if(!l){console.log(`${A.red} Name is required.${A.reset}`);continue}let u=await Ce("Host / IP address");if(!u){console.log(`${A.red} Host is required.${A.reset}`);continue}let d=await Ce("SSH user","root"),f=await Ce("SSH port","22"),m=parseInt(f,10)||22,h=await Ce("SSH key path (leave empty for SSH agent)",""),p=await yl("Operating system",["almalinux9","macos","ubuntu","debian","other"],"almalinux9"),g=await zt("Allow sudo commands?",!0),$={host:u,user:d};m!==22&&($.port=m),h&&($.key=h),p!=="other"&&($.os=p),g&&($.sudo=!0),s[l]=$,console.log(`
642
642
  ${A.green}\u2713${A.reset} Profile "${l}" added: ${d}@${u}${m!==22?`:${m}`:""}${p!=="other"?` [${p}]`:""}`),i=await zt(`
643
- Add another server?`,!1)}be.existsSync(t)||be.mkdirSync(t,{recursive:!0}),be.writeFileSync(e,JSON.stringify(o,null,2)+`
643
+ Add another server?`,!1)}be.existsSync(t)||be.mkdirSync(t,{recursive:!0}),be.writeFileSync(e,JSON.stringify(s,null,2)+`
644
644
  `,"utf-8"),console.log(`
645
- ${A.green}\u2713 Saved .nex/servers.json (${Object.keys(o).length} profile${Object.keys(o).length!==1?"s":""})${A.reset}`);let r=Kt.join(process.cwd(),".gitignore");be.existsSync(r)&&(be.readFileSync(r,"utf-8").includes(".nex/")||await zt("Add .nex/ to .gitignore?",!0)&&(be.appendFileSync(r,`
645
+ ${A.green}\u2713 Saved .nex/servers.json (${Object.keys(s).length} profile${Object.keys(s).length!==1?"s":""})${A.reset}`);let r=Kt.join(process.cwd(),".gitignore");be.existsSync(r)&&(be.readFileSync(r,"utf-8").includes(".nex/")||await zt("Add .nex/ to .gitignore?",!0)&&(be.appendFileSync(r,`
646
646
  # nex-code server profiles
647
647
  .nex/
648
648
  `),console.log(`${A.green}\u2713 Added .nex/ to .gitignore${A.reset}`))),await zt(`
649
- Set up deploy configs (.nex/deploy.json)?`,!1)&&await yl(o,t),console.log(`
649
+ Set up deploy configs (.nex/deploy.json)?`,!1)&&await wl(s,t),console.log(`
650
650
  ${A.dim}Use /servers to list profiles, /servers ping to check connectivity.${A.reset}
651
- `)}async function yl(t,e){let s=e||Kt.join(process.cwd(),gl),n=Kt.join(s,"deploy.json"),o={};if(be.existsSync(n))try{o=JSON.parse(be.readFileSync(n,"utf-8"))}catch{}if(!t){let u=Kt.join(s,"servers.json");if(be.existsSync(u))try{t=JSON.parse(be.readFileSync(u,"utf-8"))}catch{t={}}else t={}}let i=Object.keys(t);console.log(`
651
+ `)}async function wl(t,e){let o=e||Kt.join(process.cwd(),$l),n=Kt.join(o,"deploy.json"),s={};if(be.existsSync(n))try{s=JSON.parse(be.readFileSync(n,"utf-8"))}catch{}if(!t){let u=Kt.join(o,"servers.json");if(be.existsSync(u))try{t=JSON.parse(be.readFileSync(u,"utf-8"))}catch{t={}}else t={}}let i=Object.keys(t);console.log(`
652
652
  ${A.bold}${A.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${A.reset}`),console.log(`${A.bold}${A.cyan}\u2551 Deploy Config Wizard \u2551${A.reset}`),console.log(`${A.bold}${A.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${A.reset}
653
- `);let r=Object.keys(o);r.length>0&&console.log(`${A.dim}Existing deploy configs: ${r.join(", ")}${A.reset}`);let c={...o},l=!0;for(;l;){console.log(`
654
- ${A.bold}\u2500\u2500\u2500 New Deploy Config \u2500\u2500\u2500${A.reset}`);let u=await Ce("Config name (e.g. prod, staging)");if(!u){console.log(`${A.red} Name is required.${A.reset}`);continue}let d;i.length>0?d=await $l("Target server",i,i[0]):d=await Ce("Target server (profile name or user@host)");let f=await Ce("Local path to sync (e.g. dist/ or ./build)","dist/"),m=await Ce("Remote destination path (e.g. /var/www/app)");if(!m){console.log(`${A.red} Remote path is required.${A.reset}`);continue}let h=await Ce("Deploy script to run after sync (leave empty to skip)",""),p=await Ce("Exclude paths (comma-separated, e.g. node_modules,.env)","node_modules,.env"),g=p?p.split(",").map(x=>x.trim()).filter(Boolean):[],$={server:d,local_path:f,remote_path:m};h&&($.deploy_script=h),g.length>0&&($.exclude=g),c[u]=$;let y=f.endsWith("/")?f:`${f}/`;console.log(`
653
+ `);let r=Object.keys(s);r.length>0&&console.log(`${A.dim}Existing deploy configs: ${r.join(", ")}${A.reset}`);let c={...s},l=!0;for(;l;){console.log(`
654
+ ${A.bold}\u2500\u2500\u2500 New Deploy Config \u2500\u2500\u2500${A.reset}`);let u=await Ce("Config name (e.g. prod, staging)");if(!u){console.log(`${A.red} Name is required.${A.reset}`);continue}let d;i.length>0?d=await yl("Target server",i,i[0]):d=await Ce("Target server (profile name or user@host)");let f=await Ce("Local path to sync (e.g. dist/ or ./build)","dist/"),m=await Ce("Remote destination path (e.g. /var/www/app)");if(!m){console.log(`${A.red} Remote path is required.${A.reset}`);continue}let h=await Ce("Deploy script to run after sync (leave empty to skip)",""),p=await Ce("Exclude paths (comma-separated, e.g. node_modules,.env)","node_modules,.env"),g=p?p.split(",").map(x=>x.trim()).filter(Boolean):[],$={server:d,local_path:f,remote_path:m};h&&($.deploy_script=h),g.length>0&&($.exclude=g),c[u]=$;let y=f.endsWith("/")?f:`${f}/`;console.log(`
655
655
  ${A.green}\u2713${A.reset} Deploy config "${u}": ${y} \u2192 ${d}:${m}`),h&&console.log(` ${A.dim} Then: ${h}${A.reset}`),l=await zt(`
656
- Add another deploy config?`,!1)}be.existsSync(s)||be.mkdirSync(s,{recursive:!0}),be.writeFileSync(n,JSON.stringify(c,null,2)+`
656
+ Add another deploy config?`,!1)}be.existsSync(o)||be.mkdirSync(o,{recursive:!0}),be.writeFileSync(n,JSON.stringify(c,null,2)+`
657
657
  `,"utf-8"),console.log(`
658
658
  ${A.green}\u2713 Saved .nex/deploy.json (${Object.keys(c).length} config${Object.keys(c).length!==1?"s":""})${A.reset}`),console.log(`${A.dim}Use: deploy prod (or with explicit params)${A.reset}
659
- `)}wl.exports={runServerWizard:Ag,runDeployWizard:yl,setWizardRL:Rg}});var kl=L((iy,_l)=>{var Og=require("axios"),kn=require("fs"),xl=require("path"),Ng="nex-code",pr=xl.join(process.cwd(),".nex"),hr=xl.join(pr,"last-version-check");kn.existsSync(pr)||kn.mkdirSync(pr,{recursive:!0});async function Mg(){try{let t=Lg(),e=Date.now();if(t&&e-t<1440*60*1e3)return{hasNewVersion:!1};Ig(e);let s=Pg(),o=(await Og.get(`https://registry.npmjs.org/${Ng}/latest`,{timeout:5e3})).data.version,i=qg(o,s);return{hasNewVersion:i,latestVersion:i?o:void 0,currentVersion:i?s:void 0}}catch{return{hasNewVersion:!1}}}function Pg(){return Rn().version}function Lg(){try{if(kn.existsSync(hr)){let t=kn.readFileSync(hr,"utf8");return parseInt(t,10)}}catch{}return null}function Ig(t){try{kn.writeFileSync(hr,t.toString())}catch{}}function qg(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}}_l.exports={checkForNewVersion:Mg}});var jl=L((cy,ql)=>{var jg=require("readline"),ft=require("fs"),Ye=require("path"),{C:a,banner:Dg,cleanupTerminal:vl}=ce(),{listProviders:$r,getActiveProviderName:ut,listAllModels:ay,setFallbackChain:Fg,getFallbackChain:Ug,getProvider:Wg}=ge(),{flushAutoSave:Sl}=_t(),{getActiveModel:dt,setActiveModel:El}=Un(),{printContext:Tl}=Lo(),{loadAllSkills:Bg,getSkillCommands:yr,handleSkillCommand:Hg}=en(),{setReadlineInterface:Gg,setAutoConfirm:zg,getAutoConfirm:Cl}=Fe(),{StickyFooter:Kg}=rl(),Cs=process.cwd(),st=null;function Rl(){return st?.signal??null}var Rs=[{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:"/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:"/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:"/undo",desc:"Undo last file change"},{cmd:"/redo",desc:"Redo last undone change"},{cmd:"/history",desc:"Show file change history"},{cmd:"/k8s",desc:"Kubernetes overview: namespaces and pods"},{cmd:"/exit",desc:"Quit"}];function Al(){let t=yr(),e=[...Rs,...t],s=Math.max(...e.map(n=>n.cmd.length));console.log("");for(let{cmd:n,desc:o}of Rs)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(`
659
+ `)}bl.exports={runServerWizard:Ag,runDeployWizard:wl,setWizardRL:Rg}});var vl=L((ay,kl)=>{var Og=require("axios"),kn=require("fs"),_l=require("path"),Ng="nex-code",hr=_l.join(process.cwd(),".nex"),gr=_l.join(hr,"last-version-check");kn.existsSync(hr)||kn.mkdirSync(hr,{recursive:!0});async function Mg(){try{let t=Lg(),e=Date.now();if(t&&e-t<1440*60*1e3)return{hasNewVersion:!1};Ig(e);let o=Pg(),s=(await Og.get(`https://registry.npmjs.org/${Ng}/latest`,{timeout:5e3})).data.version,i=qg(s,o);return{hasNewVersion:i,latestVersion:i?s:void 0,currentVersion:i?o:void 0}}catch{return{hasNewVersion:!1}}}function Pg(){return Rn().version}function Lg(){try{if(kn.existsSync(gr)){let t=kn.readFileSync(gr,"utf8");return parseInt(t,10)}}catch{}return null}function Ig(t){try{kn.writeFileSync(gr,t.toString())}catch{}}function qg(t,e){try{let o=t.split(".").map(Number),n=e.split(".").map(Number);return o[0]>n[0]?!0:o[0]<n[0]?!1:o[1]>n[1]?!0:o[1]<n[1]?!1:o[2]>n[2]}catch{return!1}}kl.exports={checkForNewVersion:Mg}});var Dl=L((ly,jl)=>{var jg=require("readline"),ft=require("fs"),Ye=require("path"),{C:a,banner:Dg,cleanupTerminal:Sl}=ce(),{listProviders:yr,getActiveProviderName:ut,listAllModels:cy,setFallbackChain:Fg,getFallbackChain:Ug,getProvider:Wg}=ge(),{flushAutoSave:El}=_t(),{getActiveModel:dt,setActiveModel:Tl}=Un(),{printContext:Cl}=Io(),{loadAllSkills:Bg,getSkillCommands:wr,handleSkillCommand:Hg}=en(),{setReadlineInterface:Gg,setAutoConfirm:zg,getAutoConfirm:Rl}=Fe(),{StickyFooter:Kg}=il(),Cs=process.cwd(),st=null;function Al(){return st?.signal??null}var Rs=[{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:"/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:"/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:"/undo",desc:"Undo last file change"},{cmd:"/redo",desc:"Redo last undone change"},{cmd:"/history",desc:"Show file change history"},{cmd:"/k8s",desc:"Kubernetes overview: namespaces and pods"},{cmd:"/exit",desc:"Quit"}];function Ol(){let t=wr(),e=[...Rs,...t],o=Math.max(...e.map(n=>n.cmd.length));console.log("");for(let{cmd:n,desc:s}of Rs)console.log(` ${a.cyan}${n.padEnd(o+2)}${a.reset}${a.dim}${s}${a.reset}`);for(let{cmd:n,desc:s}of t)console.log(` ${a.cyan}${n.padEnd(o+2)}${a.reset}${a.dim}${s} ${a.yellow}[skill]${a.reset}`);console.log(`
660
660
  ${a.dim}Type /help for detailed usage${a.reset}
661
- `)}function Ol(t){try{let e,s;t.endsWith("/")||t.endsWith(Ye.sep)?(e=t,s=""):(e=Ye.dirname(t),s=Ye.basename(t)),e.startsWith("~")&&(e=Ye.join(require("os").homedir(),e.slice(1)));let n=Ye.isAbsolute(e)?e:Ye.resolve(Cs,e);if(!ft.existsSync(n)||!ft.statSync(n).isDirectory())return[];let o=ft.readdirSync(n,{withFileTypes:!0}),i=[];for(let r of o){if(r.name.startsWith(".")||r.name==="node_modules"||s&&!r.name.startsWith(s))continue;let c=t.endsWith("/")||t.endsWith(Ye.sep)?t:Ye.dirname(t)+"/",l=c==="./"&&!t.startsWith("./")?r.name:c+r.name;i.push(r.isDirectory()?l+"/":l)}return i}catch{return[]}}function Nl(t){if(t.startsWith("/")){let n=[...Rs,...yr()],o=n.map(i=>i.cmd).filter(i=>i.startsWith(t));return[o.length?o:n.map(i=>i.cmd),t]}let e=t.split(/\s+/),s=e[e.length-1]||"";return s&&(s.includes("/")||s.startsWith("./")||s.startsWith("../")||s.startsWith("~"))?[Ol(s),s]:[[],t]}function Ml(){console.log(`
661
+ `)}function Nl(t){try{let e,o;t.endsWith("/")||t.endsWith(Ye.sep)?(e=t,o=""):(e=Ye.dirname(t),o=Ye.basename(t)),e.startsWith("~")&&(e=Ye.join(require("os").homedir(),e.slice(1)));let n=Ye.isAbsolute(e)?e:Ye.resolve(Cs,e);if(!ft.existsSync(n)||!ft.statSync(n).isDirectory())return[];let s=ft.readdirSync(n,{withFileTypes:!0}),i=[];for(let r of s){if(r.name.startsWith(".")||r.name==="node_modules"||o&&!r.name.startsWith(o))continue;let c=t.endsWith("/")||t.endsWith(Ye.sep)?t:Ye.dirname(t)+"/",l=c==="./"&&!t.startsWith("./")?r.name:c+r.name;i.push(r.isDirectory()?l+"/":l)}return i}catch{return[]}}function Ml(t){if(t.startsWith("/")){let n=[...Rs,...wr()],s=n.map(i=>i.cmd).filter(i=>i.startsWith(t));return[s.length?s:n.map(i=>i.cmd),t]}let e=t.split(/\s+/),o=e[e.length-1]||"";return o&&(o.includes("/")||o.startsWith("./")||o.startsWith("../")||o.startsWith("~"))?[Nl(o),o]:[[],t]}function Pl(){console.log(`
662
662
  ${a.bold}${a.cyan}Commands:${a.reset}
663
663
  ${a.cyan}/help${a.reset} ${a.dim}Show this help${a.reset}
664
664
  ${a.cyan}/model [spec]${a.reset} ${a.dim}Show/switch model (e.g. openai:gpt-4o, claude-sonnet)${a.reset}
@@ -719,48 +719,48 @@ ${a.bold}${a.cyan}Undo / Redo:${a.reset}
719
719
  ${a.cyan}/history${a.reset} ${a.dim}Show file change history${a.reset}
720
720
 
721
721
  ${a.cyan}/exit${a.reset} ${a.dim}Quit${a.reset}
722
- `)}function Pl(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 gr(){let t=$r(),e=ut(),s=dt();console.log(`
723
- ${a.bold}${a.cyan}Providers:${a.reset}`);for(let n of t){let o=n.provider===e,i=n.configured?`${a.green}\u2713${a.reset}`:`${a.red}\u2717${a.reset}`,r=o?` ${a.cyan}(active)${a.reset}`:"";console.log(` ${i} ${a.bold}${n.provider}${a.reset}${r}`);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 Ll(t,e){let[s,...n]=t.split(/\s+/);switch(s){case"/help":return Ml(),!0;case"/model":{let o=n.join(" ").trim();if(!o){if(e){let{showModelPicker:i}=cl();await i(e)}else{let i=dt(),r=ut();console.log(`${a.bold}${a.cyan}Active model:${a.reset} ${a.dim}${r}:${i.id} (${i.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 gr(),!0;if(El(o)){let i=dt(),r=ut();console.log(`${a.green}Switched to ${r}:${i.id} (${i.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 gr(),!0;case"/fallback":{let o=n.join(" ").trim();if(!o){let r=Ug();return r.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} ${r.join(" \u2192 ")}`),!0}let i=o.split(",").map(r=>r.trim()).filter(Boolean);return Fg(i),console.log(`${a.green}Fallback chain: ${i.join(" \u2192 ")}${a.reset}`),!0}case"/tokens":{let{getConversationMessages:o}=de(),{getUsage:i}=Pe(),{TOOL_DEFINITIONS:r}=Ue(),c=o(),l=i(c,r),u=dt(),d=ut();console.log(`
724
- ${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=Pl(l.percentage);return console.log(` ${f}`),console.log(`
725
- ${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:i}=Nt();return n.join(" ").trim()==="reset"?(i(),console.log(`${a.green}Cost tracking reset${a.reset}`),!0):(console.log(`
726
- ${o()}
727
- `),!0)}case"/budget":{let{getCostLimits:o,getProviderSpend:i,checkBudget:r,removeCostLimit:c,saveCostLimits:l,setCostLimit:u}=Nt(),d=n[0];if(!d){let h=o(),p=$r();console.log(`
728
- ${a.bold}${a.cyan}Cost Limits:${a.reset}`);let g=!1;for(let $ of p){let y=i($.provider),x=h[$.provider];if(x!==void 0){g=!0;let T=Math.min(100,Math.round(y/x*100)),k=10,E=Math.round(T/100*k),C=k-E,v=`${T>=100?a.red:T>=80?a.yellow:a.green}${"\u2588".repeat(E)}${a.dim}${"\u2591".repeat(C)}${a.reset}`;console.log(` ${a.bold}${$.provider}:${a.reset} $${y.toFixed(2)} / $${x.toFixed(2)} (${T}%) ${v}`)}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=n[1];if(!f){let h=r(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:o,getConversationMessages:i}=de(),{clearHistory:r}=Pt(),c=i();if(c.filter(u=>u.role==="user").length>=4){process.stdout.write(`${a.dim}Reflecting on session...${a.reset} `);let{learnFromSession:u}=fr();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}
722
+ `)}function Ll(t){let o=Math.round(t/100*30),n=30-o;return` ${t>80?a.red:t>50?a.yellow:a.green}${"\u2588".repeat(o)}${a.dim}${"\u2591".repeat(n)}${a.reset} ${t}%`}function $r(){let t=yr(),e=ut(),o=dt();console.log(`
723
+ ${a.bold}${a.cyan}Providers:${a.reset}`);for(let n of t){let s=n.provider===e,i=n.configured?`${a.green}\u2713${a.reset}`:`${a.red}\u2717${a.reset}`,r=s?` ${a.cyan}(active)${a.reset}`:"";console.log(` ${i} ${a.bold}${n.provider}${a.reset}${r}`);for(let c of n.models){let l=c.id===o.id&&s?` ${a.yellow}\u25C4${a.reset}`:"";console.log(` ${a.dim}${c.id}${a.reset} \u2014 ${c.name}${l}`)}}console.log()}async function Il(t,e){let[o,...n]=t.split(/\s+/);switch(o){case"/help":return Pl(),!0;case"/model":{let s=n.join(" ").trim();if(!s){if(e){let{showModelPicker:i}=ll();await i(e)}else{let i=dt(),r=ut();console.log(`${a.bold}${a.cyan}Active model:${a.reset} ${a.dim}${r}:${i.id} (${i.name})${a.reset}`),console.log(`${a.gray}Use /model <provider:model> to switch. /providers to see all.${a.reset}`)}return!0}if(s==="list")return $r(),!0;if(Tl(s)){let i=dt(),r=ut();console.log(`${a.green}Switched to ${r}:${i.id} (${i.name})${a.reset}`)}else console.log(`${a.red}Unknown model: ${s}${a.reset}`),console.log(`${a.gray}Use /providers to see available models${a.reset}`);return!0}case"/providers":return $r(),!0;case"/fallback":{let s=n.join(" ").trim();if(!s){let r=Ug();return r.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} ${r.join(" \u2192 ")}`),!0}let i=s.split(",").map(r=>r.trim()).filter(Boolean);return Fg(i),console.log(`${a.green}Fallback chain: ${i.join(" \u2192 ")}${a.reset}`),!0}case"/tokens":{let{getConversationMessages:s}=de(),{getUsage:i}=Pe(),{TOOL_DEFINITIONS:r}=Ue(),c=s(),l=i(c,r),u=dt(),d=ut();console.log(`
724
+ ${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=Ll(l.percentage);return console.log(` ${f}`),console.log(`
725
+ ${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:s,resetCosts:i}=Nt();return n.join(" ").trim()==="reset"?(i(),console.log(`${a.green}Cost tracking reset${a.reset}`),!0):(console.log(`
726
+ ${s()}
727
+ `),!0)}case"/budget":{let{getCostLimits:s,getProviderSpend:i,checkBudget:r,removeCostLimit:c,saveCostLimits:l,setCostLimit:u}=Nt(),d=n[0];if(!d){let h=s(),p=yr();console.log(`
728
+ ${a.bold}${a.cyan}Cost Limits:${a.reset}`);let g=!1;for(let $ of p){let y=i($.provider),x=h[$.provider];if(x!==void 0){g=!0;let T=Math.min(100,Math.round(y/x*100)),k=10,E=Math.round(T/100*k),C=k-E,v=`${T>=100?a.red:T>=80?a.yellow:a.green}${"\u2588".repeat(E)}${a.dim}${"\u2591".repeat(C)}${a.reset}`;console.log(` ${a.bold}${$.provider}:${a.reset} $${y.toFixed(2)} / $${x.toFixed(2)} (${T}%) ${v}`)}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=n[1];if(!f){let h=r(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:s,getConversationMessages:i}=de(),{clearHistory:r}=Pt(),c=i();if(c.filter(u=>u.role==="user").length>=4){process.stdout.write(`${a.dim}Reflecting on session...${a.reset} `);let{learnFromSession:u}=mr();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}
729
729
  `)}else process.stdout.write(`${a.dim}nothing new${a.reset}
730
730
  `)}).catch(()=>process.stdout.write(`
731
- `))}return o(),r(),console.log(`${a.green}Conversation cleared${a.reset}`),!0}case"/context":return await Tl(Cs),!0;case"/autoconfirm":{let o=!Cl();return zg(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}=_t(),{getConversationMessages:i}=de(),r=n.join(" ").trim()||`session-${Date.now()}`,c=i();if(c.length===0)return console.log(`${a.yellow}No conversation to save${a.reset}`),!0;let l=dt(),u=ut();return o(r,c,{model:l.id,provider:u}),console.log(`${a.green}Session saved: ${r} (${c.length} messages)${a.reset}`),!0}case"/load":{let{loadSession:o}=_t(),{setConversationMessages:i}=de(),r=n.join(" ").trim();if(!r)return console.log(`${a.red}Usage: /load <name>${a.reset}`),!0;let c=o(r);return c?(i(c.messages),console.log(`${a.green}Loaded session: ${c.name} (${c.messageCount} messages)${a.reset}`),!0):(console.log(`${a.red}Session not found: ${r}${a.reset}`),!0)}case"/sessions":{let{listSessions:o}=_t(),i=o();if(i.length===0)return console.log(`${a.dim}No saved sessions${a.reset}`),!0;console.log(`
732
- ${a.bold}${a.cyan}Sessions:${a.reset}`);for(let r of i){let c=r.updatedAt?new Date(r.updatedAt).toLocaleString():"?",l=r.name==="_autosave"?` ${a.dim}(auto)${a.reset}`:"";console.log(` ${a.cyan}${r.name}${a.reset}${l} \u2014 ${r.messageCount} msgs, ${c}`)}return console.log(),!0}case"/resume":{let{getLastSession:o}=_t(),{setConversationMessages:i}=de(),r=o();return r?(i(r.messages),console.log(`${a.green}Resumed: ${r.name} (${r.messageCount} messages)${a.reset}`),!0):(console.log(`${a.yellow}No session to resume${a.reset}`),!0)}case"/remember":{let{remember:o}=lt(),i=n.join(" ").trim();if(!i)return console.log(`${a.red}Usage: /remember <key>=<value> or /remember <text>${a.reset}`),!0;let r=i.indexOf("="),c,l;return r>0?(c=i.substring(0,r).trim(),l=i.substring(r+1).trim()):(c=i.substring(0,40).replace(/\s+/g,"-"),l=i),o(c,l),console.log(`${a.green}Remembered: ${c}${a.reset}`),!0}case"/forget":{let{forget:o}=lt(),i=n.join(" ").trim();return i?(o(i)?console.log(`${a.green}Forgotten: ${i}${a.reset}`):console.log(`${a.red}Memory not found: ${i}${a.reset}`),!0):(console.log(`${a.red}Usage: /forget <key>${a.reset}`),!0)}case"/memory":{let{listMemories:o}=lt(),i=o();if(i.length===0)return console.log(`${a.dim}No memories saved${a.reset}`),!0;console.log(`
733
- ${a.bold}${a.cyan}Memory:${a.reset}`);for(let r of i)console.log(` ${a.cyan}${r.key}${a.reset} = ${r.value}`);return console.log(),!0}case"/brain":{let{listDocuments:o,readDocument:i,writeDocument:r,removeDocument:c,buildIndex:l,buildEmbeddingIndex:u,isEmbeddingAvailable:d,query:f}=mn(),m=n[0],h=n.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){r(h,`# ${h}
731
+ `))}return s(),r(),console.log(`${a.green}Conversation cleared${a.reset}`),!0}case"/context":return await Cl(Cs),!0;case"/autoconfirm":{let s=!Rl();return zg(s),console.log(`${a.green}Auto-confirm: ${s?"ON":"OFF"}${a.reset}`),s&&console.log(`${a.yellow} \u26A0 File changes will be applied without confirmation${a.reset}`),!0}case"/save":{let{saveSession:s}=_t(),{getConversationMessages:i}=de(),r=n.join(" ").trim()||`session-${Date.now()}`,c=i();if(c.length===0)return console.log(`${a.yellow}No conversation to save${a.reset}`),!0;let l=dt(),u=ut();return s(r,c,{model:l.id,provider:u}),console.log(`${a.green}Session saved: ${r} (${c.length} messages)${a.reset}`),!0}case"/load":{let{loadSession:s}=_t(),{setConversationMessages:i}=de(),r=n.join(" ").trim();if(!r)return console.log(`${a.red}Usage: /load <name>${a.reset}`),!0;let c=s(r);return c?(i(c.messages),console.log(`${a.green}Loaded session: ${c.name} (${c.messageCount} messages)${a.reset}`),!0):(console.log(`${a.red}Session not found: ${r}${a.reset}`),!0)}case"/sessions":{let{listSessions:s}=_t(),i=s();if(i.length===0)return console.log(`${a.dim}No saved sessions${a.reset}`),!0;console.log(`
732
+ ${a.bold}${a.cyan}Sessions:${a.reset}`);for(let r of i){let c=r.updatedAt?new Date(r.updatedAt).toLocaleString():"?",l=r.name==="_autosave"?` ${a.dim}(auto)${a.reset}`:"";console.log(` ${a.cyan}${r.name}${a.reset}${l} \u2014 ${r.messageCount} msgs, ${c}`)}return console.log(),!0}case"/resume":{let{getLastSession:s}=_t(),{setConversationMessages:i}=de(),r=s();return r?(i(r.messages),console.log(`${a.green}Resumed: ${r.name} (${r.messageCount} messages)${a.reset}`),!0):(console.log(`${a.yellow}No session to resume${a.reset}`),!0)}case"/remember":{let{remember:s}=lt(),i=n.join(" ").trim();if(!i)return console.log(`${a.red}Usage: /remember <key>=<value> or /remember <text>${a.reset}`),!0;let r=i.indexOf("="),c,l;return r>0?(c=i.substring(0,r).trim(),l=i.substring(r+1).trim()):(c=i.substring(0,40).replace(/\s+/g,"-"),l=i),s(c,l),console.log(`${a.green}Remembered: ${c}${a.reset}`),!0}case"/forget":{let{forget:s}=lt(),i=n.join(" ").trim();return i?(s(i)?console.log(`${a.green}Forgotten: ${i}${a.reset}`):console.log(`${a.red}Memory not found: ${i}${a.reset}`),!0):(console.log(`${a.red}Usage: /forget <key>${a.reset}`),!0)}case"/memory":{let{listMemories:s}=lt(),i=s();if(i.length===0)return console.log(`${a.dim}No memories saved${a.reset}`),!0;console.log(`
733
+ ${a.bold}${a.cyan}Memory:${a.reset}`);for(let r of i)console.log(` ${a.cyan}${r.key}${a.reset} = ${r.value}`);return console.log(),!0}case"/brain":{let{listDocuments:s,readDocument:i,writeDocument:r,removeDocument:c,buildIndex:l,buildEmbeddingIndex:u,isEmbeddingAvailable:d,query:f}=mn(),m=n[0],h=n.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){r(h,`# ${h}
734
734
 
735
- `);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);r(g,$),console.log(`${a.green}Added to brain: ${g}${a.reset}`)}return!0}case"list":{let p=o();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(`
735
+ `);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);r(g,$),console.log(`${a.green}Added to brain: ${g}${a.reset}`)}return!0}case"list":{let p=s();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(`
736
736
  ${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:x}=i(y.name),T=Array.isArray(x.tags)?x.tags.join(", "):"",k=y.size<1024?`${y.size}B`:`${(y.size/1024).toFixed(1)}K`,E=y.modified.toLocaleDateString();console.log(` ${a.cyan}${y.name.padEnd(g+2)}${a.reset}${a.dim}${T.substring(0,$-1).padEnd($)}${k.padStart(7)} ${E}${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(`
737
737
  ${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(`
738
738
  ${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=i(h);return p.content?(console.log(`
739
739
  ${a.bold}${a.cyan}${h}.md${a.reset}
740
- `),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}=Fe();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=o(),g=require("fs"),$=require("path"),y=$.join(process.cwd(),".nex","brain",".brain-index.json"),x=$.join(process.cwd(),".nex","brain",".embeddings.json");if(console.log(`
740
+ `),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}=Fe();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=s(),g=require("fs"),$=require("path"),y=$.join(process.cwd(),".nex","brain",".brain-index.json"),x=$.join(process.cwd(),".nex","brain",".embeddings.json");if(console.log(`
741
741
  ${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(x)?a.green+"present"+a.reset:a.dim+"not built (run /brain embed)"+a.reset}`),p.length>0){let T=p.reduce((k,E)=>k+E.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(`
742
742
  ${a.bold}${a.cyan}Brain Changes (git diff):${a.reset}
743
- `),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=o();if(y.length===0)return console.log(`${a.dim}No brain documents to undo${a.reset}`),!0;let x=y[0],{exec:T}=require("child_process"),{promisify:k}=require("util"),E=k(T);try{await E(`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 p=o();if(p.length===0)console.log(`
743
+ `),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=s();if(y.length===0)return console.log(`${a.dim}No brain documents to undo${a.reset}`),!0;let x=y[0],{exec:T}=require("child_process"),{promisify:k}=require("util"),E=k(T);try{await E(`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 p=s();if(p.length===0)console.log(`
744
744
  ${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(`
745
745
  ${a.dim}Commands: add \xB7 list \xB7 search \xB7 show \xB7 remove \xB7 rebuild \xB7 embed \xB7 status \xB7 review \xB7 undo${a.reset}
746
746
  `);else{console.log(`
747
747
  ${a.bold}${a.cyan}Brain: ${p.length} document(s)${a.reset}`);for(let g of p){let{frontmatter:$}=i(g.name),y=Array.isArray($.tags)?` [${$.tags.join(", ")}]`:"";console.log(` ${a.cyan}${g.name}${a.reset}${a.dim}${y}${a.reset}`)}console.log(`
748
748
  ${a.dim}Use /brain search <query> \xB7 /brain show <name> \xB7 /brain add <name>${a.reset}
749
- `)}return!0}}}case"/learn":{let{learnFromSession:o,learnBrainFromSession:i}=fr(),{getConversationMessages:r}=de(),c=r(),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),i(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:o}=de(),{getUsage:i}=Pe(),{TOOL_DEFINITIONS:r}=Ue(),{listMemories:c}=lt(),l=o(),u=i(l,r),d=dt(),f=ut(),m=c();console.log(`
749
+ `)}return!0}}}case"/learn":{let{learnFromSession:s,learnBrainFromSession:i}=mr(),{getConversationMessages:r}=de(),c=r(),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([s(c),i(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:s}=de(),{getUsage:i}=Pe(),{TOOL_DEFINITIONS:r}=Ue(),{listMemories:c}=lt(),l=s(),u=i(l,r),d=dt(),f=ut(),m=c();console.log(`
750
750
  ${a.bold}${a.cyan}Optimization Report${a.reset}
751
751
  `);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(`
752
752
  ${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((C,O)=>new Date(O.updatedAt)-new Date(C.updatedAt))[0],k=T?Math.round((Date.now()-new Date(T.updatedAt))/6e4):null,E=k!==null?k<60?`${k}m ago`:`${Math.round(k/60)}h ago`:"?";console.log(` ${a.dim}Latest update: ${E}${a.reset}`),m.length>30&&console.log(` ${a.yellow}\u2192 Many memories (${m.length}) \u2014 consider pruning with /forget${a.reset}`)}console.log(`
753
753
  ${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(x=>x.role==="user").length;console.log(`
754
754
  ${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(`
755
- ${a.bold}Quick Wins:${a.reset}`);for(let x of $)console.log(` ${a.cyan}\u2192${a.reset} ${x}`)}return console.log(""),!0}case"/plan":{let{getActivePlan:o,approvePlan:i,startExecution:r,setPlanMode:c,getPlanContent:l,formatPlan:u}=Ut(),{invalidateSystemPromptCache:d}=de(),f=n.join(" ").trim();if(f==="status"){let m=o();return console.log(u(m)),!0}if(f==="approve"){if(i()){r(),c(!1),d();let m=!!l();console.log(`${a.green}${a.bold}Plan approved!${a.reset} ${m?"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),d(),console.log(`
755
+ ${a.bold}Quick Wins:${a.reset}`);for(let x of $)console.log(` ${a.cyan}\u2192${a.reset} ${x}`)}return console.log(""),!0}case"/plan":{let{getActivePlan:s,approvePlan:i,startExecution:r,setPlanMode:c,getPlanContent:l,formatPlan:u}=Ut(),{invalidateSystemPromptCache:d}=de(),f=n.join(" ").trim();if(f==="status"){let m=s();return console.log(u(m)),!0}if(f==="approve"){if(i()){r(),c(!1),d();let m=!!l();console.log(`${a.green}${a.bold}Plan approved!${a.reset} ${m?"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),d(),console.log(`
756
756
  ${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\u2510${a.reset}
757
757
  ${a.cyan}${a.bold}\u2502${a.reset} Analysis only \u2014 no file changes until approved ${a.cyan}${a.bold}\u2502${a.reset}
758
758
  ${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}
759
- ${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\u2518${a.reset}`),f&&console.log(`${a.dim}Task: ${f}${a.reset}`),!0}case"/plans":{let{listPlans:o}=Ut(),i=o();if(i.length===0)return console.log(`${a.dim}No saved plans${a.reset}`),!0;console.log(`
760
- ${a.bold}${a.cyan}Plans:${a.reset}`);for(let r of i){let c=r.status==="completed"?`${a.green}\u2713`:r.status==="executing"?`${a.blue}\u2192`:`${a.dim}\u25CB`;console.log(` ${c} ${a.reset}${a.bold}${r.name}${a.reset} \u2014 ${r.task||"?"} (${r.steps} steps, ${r.status})`)}return console.log(),!0}case"/auto":{let{getAutonomyLevel:o,setAutonomyLevel:i,AUTONOMY_LEVELS:r}=Ut(),c=n.join(" ").trim();return c?(i(c)?console.log(`${a.green}Autonomy: ${c}${a.reset}`):console.log(`${a.red}Unknown level: ${c}. Use: ${r.join(", ")}${a.reset}`),!0):(console.log(`${a.bold}${a.cyan}Autonomy:${a.reset} ${o()}`),console.log(`${a.dim}Levels: ${r.join(", ")}${a.reset}`),!0)}case"/permissions":{let{listPermissions:o}=yn(),i=o();console.log(`
759
+ ${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\u2518${a.reset}`),f&&console.log(`${a.dim}Task: ${f}${a.reset}`),!0}case"/plans":{let{listPlans:s}=Ut(),i=s();if(i.length===0)return console.log(`${a.dim}No saved plans${a.reset}`),!0;console.log(`
760
+ ${a.bold}${a.cyan}Plans:${a.reset}`);for(let r of i){let c=r.status==="completed"?`${a.green}\u2713`:r.status==="executing"?`${a.blue}\u2192`:`${a.dim}\u25CB`;console.log(` ${c} ${a.reset}${a.bold}${r.name}${a.reset} \u2014 ${r.task||"?"} (${r.steps} steps, ${r.status})`)}return console.log(),!0}case"/auto":{let{getAutonomyLevel:s,setAutonomyLevel:i,AUTONOMY_LEVELS:r}=Ut(),c=n.join(" ").trim();return c?(i(c)?console.log(`${a.green}Autonomy: ${c}${a.reset}`):console.log(`${a.red}Unknown level: ${c}. Use: ${r.join(", ")}${a.reset}`),!0):(console.log(`${a.bold}${a.cyan}Autonomy:${a.reset} ${s()}`),console.log(`${a.dim}Levels: ${r.join(", ")}${a.reset}`),!0)}case"/permissions":{let{listPermissions:s}=yn(),i=s();console.log(`
761
761
  ${a.bold}${a.cyan}Tool Permissions:${a.reset}`);for(let r of i){let c=r.mode==="allow"?`${a.green}\u2713`:r.mode==="deny"?`${a.red}\u2717`:`${a.yellow}?`;console.log(` ${c} ${a.reset}${a.bold}${r.tool}${a.reset} ${a.dim}(${r.mode})${a.reset}`)}return console.log(`
762
762
  ${a.dim}Use /allow <tool> or /deny <tool> to change${a.reset}
763
- `),!0}case"/allow":{let{setPermission:o,savePermissions:i}=yn(),r=n.join(" ").trim();return r?(o(r,"allow"),i(),console.log(`${a.green}${r}: allow${a.reset}`),!0):(console.log(`${a.red}Usage: /allow <tool>${a.reset}`),!0)}case"/deny":{let{setPermission:o,savePermissions:i}=yn(),r=n.join(" ").trim();return r?(o(r,"deny"),i(),console.log(`${a.red}${r}: deny${a.reset}`),!0):(console.log(`${a.red}Usage: /deny <tool>${a.reset}`),!0)}case"/commit":{let{isGitRepo:o,commit:i,analyzeDiff:r,formatDiffSummary:c}=yt(),{confirm:l}=Fe();if(!o())return console.log(`${a.red}Not a git repository${a.reset}`),!0;let u=n.join(" ").trim();if(u){let p=await i(u);return console.log(p?`${a.green}Committed: ${p} \u2014 ${u}${a.reset}`:`${a.red}Commit failed${a.reset}`),!0}if(!r())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 i("nex-code update");return h&&console.log(`${a.green} \u2713 Committed: ${h}${a.reset}`),!0}case"/diff":{let{isGitRepo:o,formatDiffSummary:i}=yt();return o()?(console.log(i()),!0):(console.log(`${a.red}Not a git repository${a.reset}`),!0)}case"/review":{let{isGitRepo:o,getDiff:i}=yt(),{processInput:r}=de(),c=n.join(" ").trim(),l=c.includes("--strict"),u=c.replace("--strict","").trim(),f=`## Review Protocol
763
+ `),!0}case"/allow":{let{setPermission:s,savePermissions:i}=yn(),r=n.join(" ").trim();return r?(s(r,"allow"),i(),console.log(`${a.green}${r}: allow${a.reset}`),!0):(console.log(`${a.red}Usage: /allow <tool>${a.reset}`),!0)}case"/deny":{let{setPermission:s,savePermissions:i}=yn(),r=n.join(" ").trim();return r?(s(r,"deny"),i(),console.log(`${a.red}${r}: deny${a.reset}`),!0):(console.log(`${a.red}Usage: /deny <tool>${a.reset}`),!0)}case"/commit":{let{isGitRepo:s,commit:i,analyzeDiff:r,formatDiffSummary:c}=yt(),{confirm:l}=Fe();if(!s())return console.log(`${a.red}Not a git repository${a.reset}`),!0;let u=n.join(" ").trim();if(u){let p=await i(u);return console.log(p?`${a.green}Committed: ${p} \u2014 ${u}${a.reset}`:`${a.red}Commit failed${a.reset}`),!0}if(!r())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 i("nex-code update");return h&&console.log(`${a.green} \u2713 Committed: ${h}${a.reset}`),!0}case"/diff":{let{isGitRepo:s,formatDiffSummary:i}=yt();return s()?(console.log(i()),!0):(console.log(`${a.red}Not a git repository${a.reset}`),!0)}case"/review":{let{isGitRepo:s,getDiff:i}=yt(),{processInput:r}=de(),c=n.join(" ").trim(),l=c.includes("--strict"),u=c.replace("--strict","").trim(),f=`## Review Protocol
764
764
 
765
765
  **Phase 1 \u2014 Broad Scan:** Read the target code and identify all issues at a high level.
766
766
 
@@ -797,26 +797,26 @@ For each issue, include:
797
797
 
798
798
  \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}\`.
799
799
 
800
- ${f}`;else{if(!o())return console.log(`${a.red}Not a git repository \u2014 try /review <file>${a.reset}`),!0;let[h,p]=await Promise.all([i(!1),i(!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.
800
+ ${f}`;else{if(!s())return console.log(`${a.red}Not a git repository \u2014 try /review <file>${a.reset}`),!0;let[h,p]=await Promise.all([i(!1),i(!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.
801
801
 
802
802
  ${f}
803
803
 
804
804
  \`\`\`diff
805
805
  ${g.substring(0,2e4)}
806
- \`\`\``}return await r(m),!0}case"/branch":{let{isGitRepo:o,getCurrentBranch:i,createBranch:r}=yt();if(!o())return console.log(`${a.red}Not a git repository${a.reset}`),!0;let c=n.join(" ").trim();if(!c){let u=i();return console.log(`${a.bold}${a.cyan}Branch:${a.reset} ${u||"(detached)"}`),!0}let l=r(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:i,disconnectAll:r}=zn(),c=n.join(" ").trim();if(c==="connect")return console.log(`${a.dim}Connecting MCP servers...${a.reset}`),i().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 r(),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(`
806
+ \`\`\``}return await r(m),!0}case"/branch":{let{isGitRepo:s,getCurrentBranch:i,createBranch:r}=yt();if(!s())return console.log(`${a.red}Not a git repository${a.reset}`),!0;let c=n.join(" ").trim();if(!c){let u=i();return console.log(`${a.bold}${a.cyan}Branch:${a.reset} ${u||"(detached)"}`),!0}let l=r(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:s,connectAll:i,disconnectAll:r}=zn(),c=n.join(" ").trim();if(c==="connect")return console.log(`${a.dim}Connecting MCP servers...${a.reset}`),i().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 r(),console.log(`${a.green}All MCP servers disconnected${a.reset}`),!0;let l=s();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(`
807
807
  ${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(`
808
808
  ${a.dim}Use /mcp connect to connect all servers${a.reset}
809
- `),!0}case"/hooks":{let{listHooks:o}=Yo(),i=o();if(i.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(`
810
- ${a.bold}${a.cyan}Hooks:${a.reset}`);for(let r of i){console.log(` ${a.cyan}${r.event}${a.reset}`);for(let c of r.commands)console.log(` ${a.dim}\u2192 ${c}${a.reset}`)}return console.log(),!0}case"/skills":{let{listSkills:o,enableSkill:i,disableSkill:r}=en(),c=n.join(" ").trim();if(c.startsWith("enable ")){let u=c.substring(7).trim();return i(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 r(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(`
809
+ `),!0}case"/hooks":{let{listHooks:s}=Jo(),i=s();if(i.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(`
810
+ ${a.bold}${a.cyan}Hooks:${a.reset}`);for(let r of i){console.log(` ${a.cyan}${r.event}${a.reset}`);for(let c of r.commands)console.log(` ${a.dim}\u2192 ${c}${a.reset}`)}return console.log(),!0}case"/skills":{let{listSkills:s,enableSkill:i,disableSkill:r}=en(),c=n.join(" ").trim();if(c.startsWith("enable ")){let u=c.substring(7).trim();return i(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 r(u)?console.log(`${a.yellow}Skill disabled: ${u}${a.reset}`):console.log(`${a.red}Skill not found: ${u}${a.reset}`),!0}let l=s();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(`
811
811
  ${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(`
812
812
  ${a.dim}Use /skills enable <name> or /skills disable <name>${a.reset}
813
- `),!0}case"/tasks":{let{renderTaskList:o,clearTasks:i}=ns();return n.join(" ").trim()==="clear"?(i(),console.log(`${a.green}Tasks cleared${a.reset}`),!0):(console.log(`
814
- `+o()+`
815
- `),!0)}case"/undo":{let{undo:o,getUndoCount:i}=Pt(),r=o();if(!r)return console.log(`${a.yellow}Nothing to undo${a.reset}`),!0;r.wasCreated?console.log(`${a.green}Undone: deleted ${r.filePath} (was created by ${r.tool})${a.reset}`):console.log(`${a.green}Undone: restored ${r.filePath} (${r.tool})${a.reset}`);let c=i();return c>0&&console.log(`${a.dim}${c} more change(s) to undo${a.reset}`),!0}case"/redo":{let{redo:o,getRedoCount:i}=Pt(),r=o();if(!r)return console.log(`${a.yellow}Nothing to redo${a.reset}`),!0;console.log(`${a.green}Redone: ${r.filePath} (${r.tool})${a.reset}`);let c=i();return c>0&&console.log(`${a.dim}${c} more change(s) to redo${a.reset}`),!0}case"/history":{let{getHistory:o,getUndoCount:i,getRedoCount:r}=Pt(),c=o(20);if(c.length===0)return console.log(`${a.dim}No file changes in this session${a.reset}`),!0;console.log(`
813
+ `),!0}case"/tasks":{let{renderTaskList:s,clearTasks:i}=ns();return n.join(" ").trim()==="clear"?(i(),console.log(`${a.green}Tasks cleared${a.reset}`),!0):(console.log(`
814
+ `+s()+`
815
+ `),!0)}case"/undo":{let{undo:s,getUndoCount:i}=Pt(),r=s();if(!r)return console.log(`${a.yellow}Nothing to undo${a.reset}`),!0;r.wasCreated?console.log(`${a.green}Undone: deleted ${r.filePath} (was created by ${r.tool})${a.reset}`):console.log(`${a.green}Undone: restored ${r.filePath} (${r.tool})${a.reset}`);let c=i();return c>0&&console.log(`${a.dim}${c} more change(s) to undo${a.reset}`),!0}case"/redo":{let{redo:s,getRedoCount:i}=Pt(),r=s();if(!r)return console.log(`${a.yellow}Nothing to redo${a.reset}`),!0;console.log(`${a.green}Redone: ${r.filePath} (${r.tool})${a.reset}`);let c=i();return c>0&&console.log(`${a.dim}${c} more change(s) to redo${a.reset}`),!0}case"/history":{let{getHistory:s,getUndoCount:i,getRedoCount:r}=Pt(),c=s(20);if(c.length===0)return console.log(`${a.dim}No file changes in this session${a.reset}`),!0;console.log(`
816
816
  ${a.bold}File Change History${a.reset}
817
817
  `);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(`
818
818
  ${a.dim}${i()} undo / ${r()} redo available${a.reset}
819
- `),!0}case"/k8s":{let o=n.join(" ").trim(),{exec:i}=require("child_process"),{promisify:r}=require("util"),c=r(i),l=o||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(`
819
+ `),!0}case"/k8s":{let s=n.join(" ").trim(),{exec:i}=require("child_process"),{promisify:r}=require("util"),c=r(i),l=s||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(`
820
820
  ${a.bold}${a.cyan}Kubernetes Overview${a.reset}${l?a.dim+" (remote: "+l+")"+a.reset:""}
821
821
  `);try{let{stdout:f}=await c(d("kubectl get namespaces --no-headers -o custom-columns=NAME:.metadata.name"),{timeout:15e3}),m=f.trim().split(`
822
822
  `).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}
@@ -824,26 +824,26 @@ ${a.bold}${a.cyan}Kubernetes Overview${a.reset}${l?a.dim+" (remote: "+l+")"+a.re
824
824
  `).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}
825
825
  `);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}
826
826
  `)}catch(f){console.log(`${a.dim}Could not list pods: ${f.message}${a.reset}
827
- `)}return!0}case"/servers":{let{loadServerProfiles:o,resolveProfile:i,sshExec:r}=qt(),c=o(),l=Object.keys(c);if(l.length===0)return console.log(`
827
+ `)}return!0}case"/servers":{let{loadServerProfiles:s,resolveProfile:i,sshExec:r}=qt(),c=s(),l=Object.keys(c);if(l.length===0)return console.log(`
828
828
  ${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}
829
829
  `),!0;if(n[0]==="ping"){let f=n[1]?[n[1]]:l;return console.log(`
830
830
  ${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 r(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}=qt();console.log(`
831
831
  ${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(`
832
832
  ${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}
833
- `),!0}case"/docker":{let{loadServerProfiles:o,sshExec:i}=qt(),{exec:r}=require("child_process"),{promisify:c}=require("util"),l=c(r),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(),f=[["local",null],...Object.entries(d)];console.log(`
833
+ `),!0}case"/docker":{let{loadServerProfiles:s,sshExec:i}=qt(),{exec:r}=require("child_process"),{promisify:c}=require("util"),l=c(r),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=s(),f=[["local",null],...Object.entries(d)];console.log(`
834
834
  ${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 i(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(`
835
- `).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:o}=po(),i=o(),r=Object.keys(i),c=n[0];if(c&&r.includes(c)){let l=n.includes("--dry-run")||n.includes("-n"),u=i[c],{executeTool:d}=Ue();console.log(`
835
+ `).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:s}=ho(),i=s(),r=Object.keys(i),c=n[0];if(c&&r.includes(c)){let l=n.includes("--dry-run")||n.includes("-n"),u=i[c],{executeTool:d}=Ue();console.log(`
836
836
  ${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(r.length===0)return console.log(`
837
837
  ${a.dim}No deploy configs. Run /init to create .nex/deploy.json${a.reset}
838
838
  `),!0;console.log(`
839
839
  ${a.bold}${a.cyan}Deploy configs (${r.length}):${a.reset}`);for(let[l,u]of Object.entries(i)){let d=u.local_path||"",f=`${u.server}:${u.remote_path}`,m=u.deploy_script?` ${a.dim}\u2192 ${u.deploy_script}${a.reset}`:"";console.log(` ${a.green}${l}${a.reset} ${a.dim}${d} \u2192 ${f}${a.reset}${m}`)}return console.log(`
840
840
  ${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}
841
- `),!0}case"/init":{let{runServerWizard:o,runDeployWizard:i,setWizardRL:r}=bl();return r(e),n[0]==="deploy"?await i():await o(),!0}case"/exit":case"/quit":process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J"),process.exit(0);default:return Hg(t)||console.log(`${a.red}Unknown command: ${s}. Type /help${a.reset}`),!0}}var wr=1e3;function br(){return Ye.join(process.cwd(),".nex","repl_history")}function Il(){try{let t=br();if(ft.existsSync(t))return ft.readFileSync(t,"utf-8").split(`
842
- `).filter(Boolean).slice(-wr)}catch{}return[]}function Ts(t){try{let e=br(),s=Ye.dirname(e);ft.existsSync(s)||ft.mkdirSync(s,{recursive:!0}),ft.appendFileSync(e,t+`
843
- `)}catch{}}function Re(){let{isPlanMode:t,getAutonomyLevel:e}=Ut(),s=[];t()&&s.push("plan");let n=e();n!=="interactive"&&s.push(n);let o=ut(),i=dt(),r=o==="ollama"?i.id:`${o}:${i.id}`;return s.push(r),`${s.length>0?`${a.dim}[${s.join(" \xB7 ")}]${a.reset} `:""}${a.bold}${a.cyan}>${a.reset} `}var xr="\x1B[200~",_r="\x1B[201~";function Yg(t){return typeof t=="string"&&t.includes(xr)}function Jg(t){return typeof t=="string"&&t.includes(_r)}function vn(t){return typeof t!="string"?t:t.split(xr).join("").split(_r).join("")}async function Xg(){if(!Wg("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"),El("local:llama3"),!0}catch{return!1}}async function Vg(){let{setAbortSignalGetter:t,getConversationLength:e,processInput:s}=de();t(Rl);let o=$r().some(P=>P.configured),i=(async()=>{Bg();let P=dt(),M=ut();return{model:P,providerName:M}})(),r=(async()=>o?!0:await Xg()?(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}
844
- `),!0):!1)(),c=(async()=>{if(process.env.NEX_DISABLE_UPDATE_CHECK==="1")return{hasNewVersion:!1};try{let{checkForNewVersion:P}=kl();return await P()}catch{return{hasNewVersion:!1}}})(),[l,u,d]=await Promise.all([i,r,c]);!u&&!o&&(console.error(`
841
+ `),!0}case"/init":{let{runServerWizard:s,runDeployWizard:i,setWizardRL:r}=xl();return r(e),n[0]==="deploy"?await i():await s(),!0}case"/exit":case"/quit":process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J"),process.exit(0);default:return Hg(t)||console.log(`${a.red}Unknown command: ${o}. Type /help${a.reset}`),!0}}var br=1e3;function xr(){return Ye.join(process.cwd(),".nex","repl_history")}function ql(){try{let t=xr();if(ft.existsSync(t))return ft.readFileSync(t,"utf-8").split(`
842
+ `).filter(Boolean).slice(-br)}catch{}return[]}function Ts(t){try{let e=xr(),o=Ye.dirname(e);ft.existsSync(o)||ft.mkdirSync(o,{recursive:!0}),ft.appendFileSync(e,t+`
843
+ `)}catch{}}function Re(){let{isPlanMode:t,getAutonomyLevel:e}=Ut(),o=[];t()&&o.push("plan");let n=e();n!=="interactive"&&o.push(n);let s=ut(),i=dt(),r=s==="ollama"?i.id:`${s}:${i.id}`;return o.push(r),`${o.length>0?`${a.dim}[${o.join(" \xB7 ")}]${a.reset} `:""}${a.bold}${a.cyan}>${a.reset} `}var _r="\x1B[200~",kr="\x1B[201~";function Yg(t){return typeof t=="string"&&t.includes(_r)}function Jg(t){return typeof t=="string"&&t.includes(kr)}function vn(t){return typeof t!="string"?t:t.split(_r).join("").split(kr).join("")}async function Xg(){if(!Wg("local"))return!1;try{let{exec:e}=require("child_process"),{promisify:o}=require("util");return await o(e)("curl -s --max-time 1 http://localhost:11434/api/tags"),Tl("local:llama3"),!0}catch{return!1}}async function Vg(){let{setAbortSignalGetter:t,getConversationLength:e,processInput:o}=de();t(Al);let s=yr().some(P=>P.configured),i=(async()=>{Bg();let P=dt(),M=ut();return{model:P,providerName:M}})(),r=(async()=>s?!0:await Xg()?(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}
844
+ `),!0):!1)(),c=(async()=>{if(process.env.NEX_DISABLE_UPDATE_CHECK==="1")return{hasNewVersion:!1};try{let{checkForNewVersion:P}=vl();return await P()}catch{return{hasNewVersion:!1}}})(),[l,u,d]=await Promise.all([i,r,c]);!u&&!s&&(console.error(`
845
845
  ${a.red}\u2717 No provider configured and no local Ollama detected.${a.reset}
846
- `),process.exit(1));let f=Il(),m=jg.createInterface({input:process.stdin,output:process.stdout,prompt:Re(),completer:Nl,history:f,historySize:wr});Gg(m);let{setAskUserHandler:h}=Ue();h(async(P,M)=>{let H="\x1B[0m",X="\x1B[1m",D="\x1B[2m",W="\x1B[36m";return process.stdout.write(`
846
+ `),process.exit(1));let f=ql(),m=jg.createInterface({input:process.stdin,output:process.stdout,prompt:Re(),completer:Ml,history:f,historySize:br});Gg(m);let{setAskUserHandler:h}=Ue();h(async(P,M)=>{let H="\x1B[0m",X="\x1B[1m",D="\x1B[2m",W="\x1B[36m";return process.stdout.write(`
847
847
  ${X}\x1B[33m\u2753${H} ${X}${P}${H}
848
848
 
849
849
  `),M.forEach((Z,V)=>{process.stdout.write(` ${W}${V+1}${H} ${Z}
@@ -855,26 +855,26 @@ ${a.red}\u2717 No provider configured and no local Ollama detected.${a.reset}
855
855
  `),ne(),Z(M[qe-1])):(qe===M.length+1||Ae==="\r"||Ae===`
856
856
  `)&&(process.stdout.write(`
857
857
  `),process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.removeListener("data",V),process.stdout.write(` ${W}\u203A${H} `),m.resume(),m.once("line",xe=>{process.stdout.write(`
858
- `),Z(xe.trim()||"")}))};function ne(){process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.removeListener("data",V),m.resume()}process.stdin.on("data",V)})});let p=new Kg;p.activate(m);let g=l.providerName==="ollama"?l.model.id:`${l.providerName}:${l.model.id}`;Dg(g,Cs,{yolo:Cl()}),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}
859
- `),await Tl(Cs);let $=!1,y=0,x=!1,T=null;function k(){Sl(),p.deactivate(),vl(),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",()=>{Sl()}),m.on("SIGINT",()=>{if(vl(),y++,y>=2){k();return}if($){st&&st.abort();let{cancelPendingAskUser:P}=Ue();P(),console.log(`
858
+ `),Z(xe.trim()||"")}))};function ne(){process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.removeListener("data",V),m.resume()}process.stdin.on("data",V)})});let p=new Kg;p.activate(m);let g=l.providerName==="ollama"?l.model.id:`${l.providerName}:${l.model.id}`;Dg(g,Cs,{yolo:Rl()}),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}
859
+ `),await Cl(Cs);let $=!1,y=0,x=!1,T=null;function k(){El(),p.deactivate(),Sl(),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",()=>{El()}),m.on("SIGINT",()=>{if(Sl(),y++,y>=2){k();return}if($){st&&st.abort();let{cancelPendingAskUser:P}=Ue();P(),console.log(`
860
860
  ${a.yellow} Task cancelled. Press Ctrl+C again to exit.${a.reset}`),$=!1,m.setPrompt(Re()),m.prompt()}else process.stdout.write(`
861
861
  ${a.dim} (Press Ctrl+C again to exit)${a.reset}
862
862
  `),m.setPrompt(Re()),m.prompt(),T&&clearTimeout(T),T=setTimeout(()=>{y=0,T=null},2e3)}),process.on("SIGINT",()=>{process.stdin.isTTY?(y++,y>=2&&k()):k()});let E=!1,C=[],O=0,v={},F=!1;function j(){let P=C.join(`
863
863
  `).replace(/\r/g,"").trim();if(C=[],E=!1,!P)return!0;O++,F=!0;let M=O;v[M]=P;let H=P.split(`
864
- `).length,X=H>1?`[Pasted content #${M} \u2014 ${H} lines]`:`[Pasted content #${M}]`,D=m.line||"",W=D&&!D.endsWith(" ")?" ":"",G=D+W+X;return m.setPrompt(Re()),m.prompt(),m.line=G,m.cursor=G.length,m._refreshLine(),!0}function J(P){return P.replace(/\[Pasted content #(\d+)(?:[^\]]*)\]/g,(M,H)=>v[Number(H)]||"")}function U(){O=0,v={},F=!1}if(process.stdin.isTTY){process.stdout.write("\x1B[?2004h");let P=process.stdin.emit.bind(process.stdin);process.stdin.emit=function(M,...H){if(M!=="data")return P.call(process.stdin,M,...H);let X=H[0];if(Buffer.isBuffer(X)&&(X=X.toString("utf8")),typeof X!="string")return P.call(process.stdin,M,...H);let D=X.includes(xr),W=X.includes(_r);if(D&&W){let G=vn(X);return G&&C.push(...G.split(`
864
+ `).length,X=H>1?`[Pasted content #${M} \u2014 ${H} lines]`:`[Pasted content #${M}]`,D=m.line||"",W=D&&!D.endsWith(" ")?" ":"",G=D+W+X;return m.setPrompt(Re()),m.prompt(),m.line=G,m.cursor=G.length,m._refreshLine(),!0}function J(P){return P.replace(/\[Pasted content #(\d+)(?:[^\]]*)\]/g,(M,H)=>v[Number(H)]||"")}function U(){O=0,v={},F=!1}if(process.stdin.isTTY){process.stdout.write("\x1B[?2004h");let P=process.stdin.emit.bind(process.stdin);process.stdin.emit=function(M,...H){if(M!=="data")return P.call(process.stdin,M,...H);let X=H[0];if(Buffer.isBuffer(X)&&(X=X.toString("utf8")),typeof X!="string")return P.call(process.stdin,M,...H);let D=X.includes(_r),W=X.includes(kr);if(D&&W){let G=vn(X);return G&&C.push(...G.split(`
865
865
  `)),j()}if(D){E=!0,C=[];let G=vn(X);return G&&C.push(...G.split(`
866
866
  `)),!0}if(W){let G=vn(X);return G&&C.push(...G.split(`
867
867
  `)),j()}if(E){let G=vn(X);return G&&C.push(...G.split(`
868
- `)),!0}return P.call(process.stdin,M,...H)}}let Q=0;function me(){if(Q>0){let P="";for(let M=0;M<Q;M++)P+="\x1B[1B\x1B[2K";P+=`\x1B[${Q}A`,process.stdout.write(P),Q=0}}function Sn(P){let M=[...Rs,...yr()].filter(Z=>Z.cmd.startsWith(P));if(!M.length||M.length===1&&M[0].cmd===P)return;let H=10,X=M.slice(0,H),D=Math.max(...X.map(Z=>Z.cmd.length)),W="";for(let{cmd:Z,desc:V}of X){let ne=Z.substring(0,P.length),$e=Z.substring(P.length),Ae=" ".repeat(Math.max(0,D-Z.length+2));W+=`
868
+ `)),!0}return P.call(process.stdin,M,...H)}}let Q=0;function me(){if(Q>0){let P="";for(let M=0;M<Q;M++)P+="\x1B[1B\x1B[2K";P+=`\x1B[${Q}A`,process.stdout.write(P),Q=0}}function Sn(P){let M=[...Rs,...wr()].filter(Z=>Z.cmd.startsWith(P));if(!M.length||M.length===1&&M[0].cmd===P)return;let H=10,X=M.slice(0,H),D=Math.max(...X.map(Z=>Z.cmd.length)),W="";for(let{cmd:Z,desc:V}of X){let ne=Z.substring(0,P.length),$e=Z.substring(P.length),Ae=" ".repeat(Math.max(0,D-Z.length+2));W+=`
869
869
  \x1B[2K ${a.cyan}${ne}${a.reset}${a.dim}${$e}${Ae}${V}${a.reset}`}Q=X.length,M.length>H&&(W+=`
870
870
  \x1B[2K ${a.dim}\u2026 +${M.length-H} more${a.reset}`,Q++);let G=m._prompt.replace(/\x1b\[[0-9;]*m/g,"").length;W+=`\x1B[${Q}A\x1B[${G+m.cursor+1}G`,process.stdout.write(W)}process.stdin.isTTY&&process.stdin.on("keypress",(P,M)=>{me(),!(M&&(M.name==="tab"||M.name==="return"))&&setImmediate(()=>{m.line&&m.line.startsWith("/")&&Sn(m.line)})});let he=null,Tt=`${a.dim}...${a.reset} `;m.setPrompt(Re()),m.prompt(),m.on("line",async P=>{if(me(),Object.keys(v).length>0&&(P=J(P),U(),m.setPrompt(Re())),$){let D=P.trim();if(D){let{injectMidRunNote:W}=de();W(D),process.stdout.write(`${a.cyan} \u270E Wird im n\xE4chsten Schritt ber\xFCcksichtigt${a.reset}
871
871
  `)}return}if(he!==null){if(he._mode==="triple"){if(P.trim()==='"""'){let D=he.join(`
872
- `).trim();if(he=null,D){Ts(D.replace(/\n/g,"\\n")),$=!0,y=0,x=!1,T&&(clearTimeout(T),T=null),st=new AbortController;try{await s(D)}catch(G){if(!st?.signal?.aborted){let Z=G.message?.split(`
872
+ `).trim();if(he=null,D){Ts(D.replace(/\n/g,"\\n")),$=!0,y=0,x=!1,T&&(clearTimeout(T),T=null),st=new AbortController;try{await o(D)}catch(G){if(!st?.signal?.aborted){let Z=G.message?.split(`
873
873
  `)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${Z}${a.reset}`)}}$=!1;let W=H();W>0&&process.stdout.write(`${a.gray}[${W} messages] ${a.reset}`)}m.setPrompt(Re()),m.prompt();return}he.push(P),m.setPrompt(Tt),m.prompt();return}if(P.endsWith("\\"))he.push(P.slice(0,-1));else{he.push(P);let D=he.join(`
874
- `).trim();if(he=null,D){Ts(D.replace(/\n/g,"\\n")),$=!0,y=0,x=!1,T&&(clearTimeout(T),T=null),st=new AbortController;try{await s(D)}catch(Z){if(!st?.signal?.aborted){let V=Z.message?.split(`
875
- `)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${V}${a.reset}`)}}let{getConversationLength:W}=de();$=!1;let G=W();G>0&&process.stdout.write(`${a.gray}[${G} messages] ${a.reset}`)}m.setPrompt(Re()),m.prompt();return}m.setPrompt(Tt),m.prompt();return}if(P.trim()==='"""'||P.trim().startsWith('"""')){let D=P.trim().substring(3);he=D?[D]:[],he._mode="triple",m.setPrompt(Tt),m.prompt();return}if(P.endsWith("\\")){he=[P.slice(0,-1)],he._mode="backslash",m.setPrompt(Tt),m.prompt();return}let M=P.trim();if(!M){m.setPrompt(Re()),m.prompt();return}if(Ts(M),M==="/"){Al(),m.setPrompt(Re()),m.prompt();return}if(M.startsWith("/")){await Ll(M,m),m.setPrompt(Re()),m.prompt();return}{let D="\x1B[48;5;237m",W=process.stdout.columns||80;M.split(`
876
- `).forEach((Z,V)=>{let ne=V===0?"\x1B[1;36m\u203A\x1B[22;39m":" ",$e=2+Z.length,Ae=" ".repeat(Math.max(0,W-$e));console.log(`${D}${ne} ${Z}${Ae}\x1B[0m`)})}$=!0,y=0,x=!1,T&&(clearTimeout(T),T=null),st=new AbortController;try{await s(M)}catch(D){if(!st?.signal?.aborted){let W=D.message?.split(`
877
- `)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${W}${a.reset}`)}}$=!1;let{getConversationLength:H}=de(),X=H();X>0&&process.stdout.write(`${a.gray}[${X} messages] ${a.reset}`),m.setPrompt(Re()),m.prompt()}),m.on("close",()=>{process.stdin.isTTY&&process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J"),process.exit(0)})}ql.exports={startREPL:Vg,getPrompt:Re,loadHistory:Il,appendHistory:Ts,getHistoryPath:br,HISTORY_MAX:wr,showCommandList:Al,completer:Nl,completeFilePath:Ol,handleSlashCommand:Ll,showProviders:gr,showHelp:Ml,renderBar:Pl,hasPasteStart:Yg,hasPasteEnd:Jg,stripPasteSequences:vn,getAbortSignal:Rl}});var Ul=require("path");require("dotenv").config({path:Ul.join(__dirname,"..",".env")});require("dotenv").config();var ae=process.argv.slice(2);(ae.includes("--help")||ae.includes("-h"))&&(console.log(`Usage: nex-code [options]
874
+ `).trim();if(he=null,D){Ts(D.replace(/\n/g,"\\n")),$=!0,y=0,x=!1,T&&(clearTimeout(T),T=null),st=new AbortController;try{await o(D)}catch(Z){if(!st?.signal?.aborted){let V=Z.message?.split(`
875
+ `)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${V}${a.reset}`)}}let{getConversationLength:W}=de();$=!1;let G=W();G>0&&process.stdout.write(`${a.gray}[${G} messages] ${a.reset}`)}m.setPrompt(Re()),m.prompt();return}m.setPrompt(Tt),m.prompt();return}if(P.trim()==='"""'||P.trim().startsWith('"""')){let D=P.trim().substring(3);he=D?[D]:[],he._mode="triple",m.setPrompt(Tt),m.prompt();return}if(P.endsWith("\\")){he=[P.slice(0,-1)],he._mode="backslash",m.setPrompt(Tt),m.prompt();return}let M=P.trim();if(!M){m.setPrompt(Re()),m.prompt();return}if(Ts(M),M==="/"){Ol(),m.setPrompt(Re()),m.prompt();return}if(M.startsWith("/")){await Il(M,m),m.setPrompt(Re()),m.prompt();return}{let D="\x1B[48;5;237m",W=process.stdout.columns||80;M.split(`
876
+ `).forEach((Z,V)=>{let ne=V===0?"\x1B[1;36m\u203A\x1B[22;39m":" ",$e=2+Z.length,Ae=" ".repeat(Math.max(0,W-$e));console.log(`${D}${ne} ${Z}${Ae}\x1B[0m`)})}$=!0,y=0,x=!1,T&&(clearTimeout(T),T=null),st=new AbortController;try{await o(M)}catch(D){if(!st?.signal?.aborted){let W=D.message?.split(`
877
+ `)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${W}${a.reset}`)}}$=!1;let{getConversationLength:H}=de(),X=H();X>0&&process.stdout.write(`${a.gray}[${X} messages] ${a.reset}`),m.setPrompt(Re()),m.prompt()}),m.on("close",()=>{process.stdin.isTTY&&process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J"),process.exit(0)})}jl.exports={startREPL:Vg,getPrompt:Re,loadHistory:ql,appendHistory:Ts,getHistoryPath:xr,HISTORY_MAX:br,showCommandList:Ol,completer:Ml,completeFilePath:Nl,handleSlashCommand:Il,showProviders:$r,showHelp:Pl,renderBar:Ll,hasPasteStart:Yg,hasPasteEnd:Jg,stripPasteSequences:vn,getAbortSignal:Al}});var As=require("path");require("dotenv").config({path:As.join(__dirname,"..",".env")});require("dotenv").config();var ae=process.argv.slice(2);(ae.includes("--help")||ae.includes("-h"))&&(console.log(`Usage: nex-code [options]
878
878
 
879
879
  Options:
880
880
  --task <prompt> Run a single task and exit (headless mode)
@@ -887,4 +887,4 @@ Options:
887
887
  --json Output result as JSON (for CI parsing)
888
888
  -h, --help Show this help
889
889
  -v, --version Show version
890
- `),process.exit(0));if(ae.includes("-v")||ae.includes("--version")){let t=Rn();console.log(t.version),process.exit(0)}var Qg=ae.includes("--yolo")||ae.includes("-yolo");if(Qg){let{setAutoConfirm:t}=Fe();t(!0)}var kr=ae.indexOf("--model");if(kr!==-1&&ae[kr+1]){let{setActiveModel:t}=ge();t(ae[kr+1])}var vr=ae.indexOf("--max-turns");if(vr!==-1&&ae[vr+1]){let t=parseInt(ae[vr+1],10);if(t>0){let{setMaxIterations:e}=de();e(t)}}else try{let t=require("fs"),e=Ul.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}=de();o(n)}}}catch{}function Sr(){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{}}function Dl(t){if(ae.includes("--auto")){let{setAutoConfirm:o}=Fe();o(!0)}if(!ae.includes("--model")){let{setActiveModel:o}=ge(),i=process.env.HEADLESS_MODEL||"devstral-small-2:24b";o(i)}let{processInput:s,getConversationMessages:n}=de();s(t).then(()=>{if(ae.includes("--json")){let i=n().filter(r=>r.role==="assistant").pop();console.log(JSON.stringify({success:!0,response:i?.content||""}))}process.exit(0)}).catch(o=>{ae.includes("--json")?console.log(JSON.stringify({success:!1,error:o.message})):console.error(o.message),process.exit(1)})}var Fl=ae.indexOf("--prompt-file");if(Fl!==-1){let t=ae[Fl+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)),ae.includes("--delete-prompt-file"))try{e.unlinkSync(t)}catch{}Sr(),Dl(s)}else{let t=ae.indexOf("--task");if(t!==-1){let e=ae[t+1];(!e||e.startsWith("--"))&&(console.error("--task requires a prompt"),process.exit(1)),Sr(),Dl(e)}else{Sr();let{startREPL:e}=jl();e()}}
890
+ `),process.exit(0));if(ae.includes("-v")||ae.includes("--version")){let t=Rn();console.log(t.version),process.exit(0)}var Qg=ae.includes("--yolo")||ae.includes("-yolo");if(Qg){let{setAutoConfirm:t}=Fe();t(!0)}var vr=ae.indexOf("--model");if(vr!==-1&&ae[vr+1]){let{setActiveModel:t}=ge();t(ae[vr+1])}var Sr=ae.indexOf("--max-turns");if(Sr!==-1&&ae[Sr+1]){let t=parseInt(ae[Sr+1],10);if(t>0){let{setMaxIterations:e}=de();e(t)}}else try{let t=require("fs"),e=As.join(process.cwd(),".nex","config.json");if(t.existsSync(e)){let o=JSON.parse(t.readFileSync(e,"utf-8")),n=parseInt(o.maxIterations,10);if(n>0){let{setMaxIterations:s}=de();s(n)}}}catch{}function Er(){if(process.platform==="darwin")try{let{spawn:t}=require("child_process"),e=t("caffeinate",["-i","-m"],{stdio:"ignore",detached:!1});e.unref();let o=()=>{try{e.kill()}catch{}};process.on("exit",o),process.on("SIGINT",o),process.on("SIGTERM",o)}catch{}}function Zg(){let t=require("fs"),e=t.existsSync(As.join(__dirname,"..",".env"))||t.existsSync(As.join(process.cwd(),".env")),o=process.env.ANTHROPIC_API_KEY||process.env.OPENAI_API_KEY||process.env.GEMINI_API_KEY||process.env.OPENROUTER_API_KEY,n=process.env.DEFAULT_PROVIDER||process.env.DEFAULT_MODEL;if(e||o||n)return;let s="\x1B[0m",i="\x1B[1m",r="\x1B[2m",c="\x1B[33m",l="\x1B[36m",u="\x1B[32m";console.log(),console.log(`${c}${i} \u2726 No configuration found \u2014 quick setup guide${s}`),console.log(`${r} \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${s}`),console.log(),console.log(` Create a ${i}.env${s} file in your project directory with one of:`),console.log(),console.log(`${u} \u250C\u2500 Ollama (local or cloud, no API key required) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510${s}`),console.log(`${u} \u2502${s} Works out of the box if Ollama is running locally. ${u}\u2502${s}`),console.log(`${u} \u2502${s} ${u}\u2502${s}`),console.log(`${u} \u2502${s} ${r}# .env${s} ${u}\u2502${s}`),console.log(`${u} \u2502${s} ${l}DEFAULT_PROVIDER${s}=ollama ${u}\u2502${s}`),console.log(`${u} \u2502${s} ${l}DEFAULT_MODEL${s}=qwen3-coder ${u}\u2502${s}`),console.log(`${u} \u2502${s} ${l}OLLAMA_HOST${s}=http://localhost:11434 ${u}\u2502${s}`),console.log(`${u} \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\u2500\u2500\u2500\u2500\u2500\u2500\u2518${s}`),console.log(),console.log(`${l} \u250C\u2500 Anthropic (Claude) \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${s}`),console.log(`${l} \u2502${s} ${l}DEFAULT_PROVIDER${s}=anthropic ${l}\u2502${s}`),console.log(`${l} \u2502${s} ${l}ANTHROPIC_API_KEY${s}=sk-ant-... ${l}\u2502${s}`),console.log(`${l} \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\u2500\u2500\u2500\u2500\u2500\u2500\u2518${s}`),console.log(),console.log(`${r} \u250C\u2500 OpenAI \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\u2510${s}`),console.log(`${r} \u2502${s} ${l}DEFAULT_PROVIDER${s}=openai ${r}\u2502${s}`),console.log(`${r} \u2502${s} ${l}OPENAI_API_KEY${s}=sk-... ${r}\u2502${s}`),console.log(`${r} \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\u2500\u2500\u2500\u2500\u2500\u2500\u2518${s}`),console.log(),console.log(` Run ${i}/init${s} inside nex-code for an interactive setup wizard.`),console.log(` Docs: ${r}https://github.com/hybridpicker/nex-code${s}`),console.log(),console.log(`${r} Continuing with Ollama defaults (localhost:11434)...${s}`),console.log()}function Fl(t){if(ae.includes("--auto")){let{setAutoConfirm:s}=Fe();s(!0)}if(!ae.includes("--model")){let{setActiveModel:s}=ge(),i=process.env.HEADLESS_MODEL||"devstral-small-2:24b";s(i)}let{processInput:o,getConversationMessages:n}=de();o(t).then(()=>{if(ae.includes("--json")){let i=n().filter(r=>r.role==="assistant").pop();console.log(JSON.stringify({success:!0,response:i?.content||""}))}process.exit(0)}).catch(s=>{ae.includes("--json")?console.log(JSON.stringify({success:!1,error:s.message})):console.error(s.message),process.exit(1)})}var Ul=ae.indexOf("--prompt-file");if(Ul!==-1){let t=ae[Ul+1];(!t||t.startsWith("--"))&&(console.error("--prompt-file requires a file path"),process.exit(1));let e=require("fs"),o;try{o=e.readFileSync(t,"utf-8").trim()}catch(n){console.error(`--prompt-file: cannot read file: ${n.message}`),process.exit(1)}if(o||(console.error("--prompt-file: file is empty"),process.exit(1)),ae.includes("--delete-prompt-file"))try{e.unlinkSync(t)}catch{}Er(),Fl(o)}else{let t=ae.indexOf("--task");if(t!==-1){let e=ae[t+1];(!e||e.startsWith("--"))&&(console.error("--task requires a prompt"),process.exit(1)),Er(),Fl(e)}else{Zg(),Er();let{startREPL:e}=Dl();e()}}