nex-code 0.3.63 → 0.3.65
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +29 -1
- package/dist/nex-code.js +421 -421
- package/package.json +1 -1
package/dist/nex-code.js
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var q=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Es=q((
|
|
3
|
-
`),n=t("python3",["-c",e],{encoding:"buffer",timeout:400,stdio:["ignore","pipe","ignore"]}).toString("utf8").match(/rgb:([0-9a-fA-F]+)\/([0-9a-fA-F]+)\/([0-9a-fA-F]+)/);if(n){let r=parseInt(n[1].slice(0,2),16),
|
|
4
|
-
`}this.lineCount>0&&(
|
|
5
|
-
`;this.lineCount>0&&(e+=`\x1B[${this.lineCount}A`),process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),100)}update(e,s){e>=0&&e<this.statuses.length&&(this.statuses[e]=s)}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),this._renderFinal(),process.stderr.write("\x1B[?25h")}_renderFinal(){let e=this._formatElapsed(),s=e?` ${P.dim}${e}${P.reset}`:"",o="";for(let n=0;n<this.labels.length;n++){let r;switch(this.statuses[n]){case"done":r=`${P.green}\u2713${P.reset}`;break;case"error":r=`${P.red}\u2717${P.reset}`;break;default:r=`${P.yellow}\u25CB${P.reset}`}let
|
|
6
|
-
`}process.stderr.write(o)}},Ts={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},Rs={done:P.green,in_progress:P.cyan,pending:P.dim,failed:P.red},Nt=null,tr=class{constructor(e,s){this.name=e,this.tasks=s.map(o=>({id:o.id,description:o.description,status:o.status||"pending"})),this.frame=0,this.interval=null,this.startTime=null,this.tokens=0,this.lineCount=1+this.tasks.length,this._paused=!1}_formatElapsed(){if(!this.startTime)return"";let e=Math.floor((Date.now()-this.startTime)/1e3);if(e<1)return"";let s=Math.floor(e/60),o=e%60;return s>0?`${s}m ${String(o).padStart(2,"0")}s`:`${o}s`}_formatTokens(){return this.tokens<=0?"":this.tokens>=1e3?`${(this.tokens/1e3).toFixed(1)}k`:String(this.tokens)}_render(){if(this._stopped)return;let e=
|
|
7
|
-
`;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=Ts[l.status]||Ts.pending,f=Rs[l.status]||Rs.pending,m=l.description.length>55?l.description.substring(0,52)+"...":l.description;
|
|
8
|
-
`}
|
|
2
|
+
var q=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Es=q((Pb,Nf)=>{Nf.exports={name:"nex-code",version:"0.3.65",description:"The open-source agentic coding CLI. Free with Ollama Cloud \u2014 switch to OpenAI, Anthropic or Gemini anytime. Alternative to Claude Code & Gemini CLI.",bin:{"nex-code":"./dist/nex-code.js"},files:["dist/","README.md","LICENSE"],engines:{node:">=18.0.0"},scripts:{start:"node dist/nex-code.js",build:"esbuild bin/nex-code.js --bundle --platform=node --target=node18 --outfile=dist/nex-code.js --minify --external:axios --external:dotenv --external:playwright",test:"jest --forceExit",coverage:"jest --coverage --forceExit","test:watch":"jest --watch",format:"prettier --write .","install-hooks":"ln -sf ../../hooks/pre-push .git/hooks/pre-push && chmod +x .git/hooks/pre-push && ln -sf ../../hooks/post-merge .git/hooks/post-merge && chmod +x .git/hooks/post-merge && echo 'Hooks installed (pre-push, post-merge).'",prepublishOnly:"npm run build && npm test",release:"npm version patch && git push --follow-tags && npm publish"},keywords:["ai","cli","coding","agent","ollama","ollama-cloud","openai","anthropic","claude","gemini","llm","gpt","agentic","terminal","coding-assistant","claude-code-alternative","gemini-cli-alternative","open-source","free","qwen3","devstral","kimi-k2","deepseek","local-llm","mcp","model-context-protocol","multi-provider"],repository:{type:"git",url:"https://github.com/hybridpicker/nex-code.git"},bugs:{url:"https://github.com/hybridpicker/nex-code/issues"},homepage:"https://github.com/hybridpicker/nex-code#readme",license:"MIT",dependencies:{axios:"^1.7.0",dotenv:"^16.4.0"},devDependencies:{esbuild:"^0.27.3",jest:"^29.7.0"},jest:{coverageThreshold:{global:{lines:45,functions:30,branches:35},"./cli/sub-agent.js":{lines:70,functions:65,branches:55}}}}});var Ht=q((Lb,ya)=>{"use strict";var fa="\x1B[0m",pa="\x1B[1m",dn="\x1B[2m";function O(t,e,s){return`\x1B[38;2;${t};${e};${s}m`}function Mf(){if(!process.stdout.isTTY)return null;try{let{execFileSync:t}=require("child_process"),e=["import sys,os,tty,termios,select","f=open('/dev/tty','r+b',buffering=0)","fd=f.fileno()","s=termios.tcgetattr(fd)","try:"," tty.setraw(fd)"," f.write(bytes([0x1b,0x5d,0x31,0x31,0x3b,0x3f,0x1b,0x5c]))"," r=select.select([fd],[],[],0.1)[0]"," d=b''"," if r:"," while True:"," r2=select.select([fd],[],[],0.05)[0]"," if not r2:break"," c=os.read(fd,1)"," d+=c"," if d[-1:]==bytes([0x07]) or d[-2:]==bytes([0x1b,0x5c]):break"," sys.stdout.buffer.write(d)","finally:"," termios.tcsetattr(fd,termios.TCSADRAIN,s)"," f.close()"].join(`
|
|
3
|
+
`),n=t("python3",["-c",e],{encoding:"buffer",timeout:400,stdio:["ignore","pipe","ignore"]}).toString("utf8").match(/rgb:([0-9a-fA-F]+)\/([0-9a-fA-F]+)\/([0-9a-fA-F]+)/);if(n){let r=parseInt(n[1].slice(0,2),16),a=parseInt(n[2].slice(0,2),16),c=parseInt(n[3].slice(0,2),16);return .299*r+.587*a+.114*c<128}}catch{}return null}function ma(){let t=require("os");return require("path").join(t.homedir(),".nex-code",".theme_cache.json")}function If(t){try{let s=require("fs").readFileSync(ma(),"utf8"),o=JSON.parse(s);if(o&&typeof o[t]=="boolean")return o[t]}catch{}return null}function Pf(t,e){try{let s=require("fs"),o=require("path"),n=ma(),r=o.dirname(n),a={};try{a=JSON.parse(s.readFileSync(n,"utf8"))}catch{}a[t]=e;let c=Object.keys(a);c.length>50&&c.slice(0,c.length-50).forEach(l=>delete a[l]),s.existsSync(r)||s.mkdirSync(r,{recursive:!0}),s.writeFileSync(n,JSON.stringify(a),"utf8")}catch{}}function Lf(){let t=(process.env.NEX_THEME||"").toLowerCase();if(t==="light")return!1;if(t==="dark")return!0;let e=process.env.COLORFGBG;if(e){let a=e.split(";"),c=parseInt(a[a.length-1],10);if(!isNaN(c))return c<8}let s=process.env.TERM_SESSION_ID||"default",o=If(s);if(o!==null)return o;let n=Mf(),r=n!==null?n:!0;return Pf(s,r),r}var ha=Lf(),ga={reset:fa,bold:pa,dim:dn,primary:O(80,190,255),secondary:O(60,170,190),success:O(80,210,120),warning:O(245,175,50),error:O(230,80,80),muted:dn,subtle:O(130,130,145),tool_read:O(80,190,255),tool_write:O(245,165,55),tool_exec:O(185,100,235),tool_search:O(70,185,190),tool_git:O(90,210,100),tool_web:O(100,215,250),tool_sysadmin:O(225,150,75),tool_default:O(100,205,115),syn_keyword:O(185,100,235),syn_string:O(90,210,120),syn_number:O(245,175,50),syn_comment:dn,syn_key:O(80,190,255),diff_add:O(80,210,120),diff_rem:O(230,80,80),banner_logo:O(80,200,255),banner_name:O(80,200,255),banner_version:dn,banner_model:dn,banner_yolo:O(245,175,50),footer_sep:dn,footer_model:O(80,175,235),footer_branch:O(80,210,100),footer_project:O(130,130,145),footer_divider:O(80,80,95),white:"\x1B[37m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",gray:"\x1B[90m",bgRed:"\x1B[41m",bgGreen:"\x1B[42m",diff_add_bg:"\x1B[48;2;10;46;20m",diff_rem_bg:"\x1B[48;2;58;16;16m",brightCyan:"\x1B[96m",brightMagenta:"\x1B[95m",brightBlue:"\x1B[94m"},$a={reset:fa,bold:pa,dim:O(110,110,120),primary:O(0,110,190),secondary:O(0,125,148),success:O(0,148,62),warning:O(168,92,0),error:O(188,32,32),muted:O(110,110,120),subtle:O(155,155,165),tool_read:O(0,110,190),tool_write:O(168,92,0),tool_exec:O(128,42,188),tool_search:O(0,122,148),tool_git:O(0,138,62),tool_web:O(0,112,178),tool_sysadmin:O(168,82,0),tool_default:O(0,138,62),syn_keyword:O(128,42,188),syn_string:O(0,138,62),syn_number:O(168,92,0),syn_comment:O(135,135,148),syn_key:O(0,110,190),diff_add:O(0,148,62),diff_rem:O(188,32,32),banner_logo:O(0,122,205),banner_name:O(0,122,205),banner_version:O(100,100,118),banner_model:O(100,100,118),banner_yolo:O(168,62,0),footer_sep:O(168,168,178),footer_model:O(0,102,175),footer_branch:O(0,138,62),footer_project:O(135,135,148),footer_divider:O(168,168,178),white:O(40,40,52),red:O(188,32,32),green:O(0,148,62),yellow:O(168,92,0),blue:O(0,110,190),magenta:O(128,42,188),cyan:O(0,125,148),gray:O(132,132,142),bgRed:"\x1B[41m",bgGreen:"\x1B[42m",diff_add_bg:"\x1B[48;2;215;245;220m",diff_rem_bg:"\x1B[48;2;255;215;215m",brightCyan:O(0,158,182),brightMagenta:O(158,52,208),brightBlue:O(0,112,208)},jf=ha?ga:$a;ya.exports={T:jf,isDark:ha,DARK:ga,LIGHT:$a}});var Dn=q((jb,ba)=>{var{T:P}=Ht(),Cs=5,fn=(()=>{let t=[];for(let e=0;e<Cs;e++)t.push(e);for(let e=Cs-2;e>=1;e--)t.push(e);return t})(),wa=["\u273D","\u2726","\u2727","\u2726"],Zo=class{constructor(e="Thinking..."){this.text=e,this.frame=0,this.interval=null,this.startTime=null}_render(){if(this._stopped)return;let e=fn[this.frame%fn.length],s="";for(let n=0;n<Cs;n++)s+=n===e?`${P.cyan}\u25CF${P.reset}`:" ";let o="";if(this.startTime){let n=Math.floor((Date.now()-this.startTime)/1e3);if(n>=60){let r=Math.floor(n/60),a=n%60;o=` ${P.dim}${r}m ${String(a).padStart(2,"0")}s${P.reset}`}else n>=1&&(o=` ${P.dim}${n}s${P.reset}`)}process.stderr.write(`\x1B[2K\r${s} ${P.dim}${this.text}${P.reset}${o}`),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),process.stderr.isTTY&&(process.stderr.write("\x1B[?25l"),this._render(),this.interval=setInterval(()=>this._render(),100))}update(e){this.text=e}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),process.stderr.isTTY&&process.stderr.write("\x1B[2K\r\x1B[?25h"),this.startTime=null}},er=class{constructor(e){this.labels=e,this.statuses=e.map(()=>"running"),this.frame=0,this.interval=null,this.startTime=null,this.lineCount=e.length}_formatElapsed(){if(!this.startTime)return"";let e=Math.floor((Date.now()-this.startTime)/1e3);if(e<1)return"";let s=Math.floor(e/60),o=e%60;return s>0?`${s}m ${String(o).padStart(2,"0")}s`:`${o}s`}_render(){if(this._stopped)return;let e=fn[this.frame%fn.length],s=`${P.cyan}\u25CF${P.reset}`,o=`${P.dim}\u25CB${P.reset}`,n=this._formatElapsed(),r=n?` ${P.dim}${n}${P.reset}`:"",a="";for(let c=0;c<this.labels.length;c++){let l,u;switch(this.statuses[c]){case"done":l=`${P.green}\u2713${P.reset}`,u=P.dim;break;case"error":l=`${P.red}\u2717${P.reset}`,u=P.dim;break;default:l=c===e?s:" ",u=""}let d=c===this.labels.length-1?r:"";a+=`\x1B[2K ${l} ${u}${this.labels[c]}${P.reset}${d}
|
|
4
|
+
`}this.lineCount>0&&(a+=`\x1B[${this.lineCount}A`),process.stderr.write(a),this.frame++}start(){this._stopped=!1,this.startTime=Date.now();let e="\x1B[?25l";for(let s=0;s<this.lineCount;s++)e+=`
|
|
5
|
+
`;this.lineCount>0&&(e+=`\x1B[${this.lineCount}A`),process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),100)}update(e,s){e>=0&&e<this.statuses.length&&(this.statuses[e]=s)}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),this._renderFinal(),process.stderr.write("\x1B[?25h")}_renderFinal(){let e=this._formatElapsed(),s=e?` ${P.dim}${e}${P.reset}`:"",o="";for(let n=0;n<this.labels.length;n++){let r;switch(this.statuses[n]){case"done":r=`${P.green}\u2713${P.reset}`;break;case"error":r=`${P.red}\u2717${P.reset}`;break;default:r=`${P.yellow}\u25CB${P.reset}`}let a=n===this.labels.length-1?s:"";o+=`\x1B[2K ${r} ${P.dim}${this.labels[n]}${P.reset}${a}
|
|
6
|
+
`}process.stderr.write(o)}},Ts={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},Rs={done:P.green,in_progress:P.cyan,pending:P.dim,failed:P.red},Nt=null,tr=class{constructor(e,s){this.name=e,this.tasks=s.map(o=>({id:o.id,description:o.description,status:o.status||"pending"})),this.frame=0,this.interval=null,this.startTime=null,this.tokens=0,this.lineCount=1+this.tasks.length,this._paused=!1}_formatElapsed(){if(!this.startTime)return"";let e=Math.floor((Date.now()-this.startTime)/1e3);if(e<1)return"";let s=Math.floor(e/60),o=e%60;return s>0?`${s}m ${String(o).padStart(2,"0")}s`:`${o}s`}_formatTokens(){return this.tokens<=0?"":this.tokens>=1e3?`${(this.tokens/1e3).toFixed(1)}k`:String(this.tokens)}_render(){if(this._stopped)return;let e=wa[this.frame%wa.length],s=this._formatElapsed(),o=this._formatTokens(),n=[s,o?`\u2193 ${o} tokens`:""].filter(Boolean).join(" \xB7 "),r=n?` ${P.dim}(${n})${P.reset}`:"",a=`\x1B[2K${P.cyan}${e}${P.reset} ${this.name}\u2026${r}
|
|
7
|
+
`;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=Ts[l.status]||Ts.pending,f=Rs[l.status]||Rs.pending,m=l.description.length>55?l.description.substring(0,52)+"...":l.description;a+=`\x1B[2K ${P.dim}${u}${P.reset} ${f}${d}${P.reset} ${m}
|
|
8
|
+
`}a+=`\x1B[${this.lineCount}A`,process.stderr.write(a),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+=`
|
|
9
9
|
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120),Nt=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,Nt===this&&(Nt=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
|
|
10
10
|
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._paused=!0}resume(){if(!this._paused)return;this._paused=!1;let e="\x1B[?25l";for(let s=0;s<this.lineCount;s++)e+=`
|
|
11
|
-
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120)}updateTask(e,s){let o=this.tasks.find(n=>n.id===e);o&&(o.status=s)}setStats({tokens:e}){e!==void 0&&(this.tokens=e)}isActive(){return this.interval!==null||this._paused}_renderFinal(){let e=this._formatElapsed(),s=this.tasks.filter(c=>c.status==="done").length,o=this.tasks.filter(c=>c.status==="failed").length,n=this.tasks.length,r=o>0?`${s}/${n} done, ${o} failed`:`${s}/${n} done`,
|
|
12
|
-
`;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=Ts[l.status]||Ts.pending,f=Rs[l.status]||Rs.pending,m=l.description.length>55?l.description.substring(0,52)+"...":l.description;
|
|
13
|
-
`}process.stderr.write(
|
|
14
|
-
`),o=s.slice(0,e),n=s.length-e,r=`${S.muted} \u2514 ${S.reset}`,
|
|
11
|
+
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120)}updateTask(e,s){let o=this.tasks.find(n=>n.id===e);o&&(o.status=s)}setStats({tokens:e}){e!==void 0&&(this.tokens=e)}isActive(){return this.interval!==null||this._paused}_renderFinal(){let e=this._formatElapsed(),s=this.tasks.filter(c=>c.status==="done").length,o=this.tasks.filter(c=>c.status==="failed").length,n=this.tasks.length,r=o>0?`${s}/${n} done, ${o} failed`:`${s}/${n} done`,a=`\x1B[2K${P.green}\u2714${P.reset} ${this.name} ${P.dim}(${e} \xB7 ${r})${P.reset}
|
|
12
|
+
`;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=Ts[l.status]||Ts.pending,f=Rs[l.status]||Rs.pending,m=l.description.length>55?l.description.substring(0,52)+"...":l.description;a+=`\x1B[2K ${P.dim}${u}${P.reset} ${f}${d}${P.reset} ${P.dim}${m}${P.reset}
|
|
13
|
+
`}process.stderr.write(a)}},nr=class{constructor(e,s){this.toolName=e,this.message=s||`Running ${e}...`,this.count=0,this.total=null,this.detail="",this.frame=0,this.interval=null,this.startTime=null,this._stopped=!1}_render(){if(this._stopped||!process.stderr.isTTY)return;let e=fn[this.frame%fn.length],s="";for(let r=0;r<Cs;r++)s+=r===e?`${P.cyan}\u25CF${P.reset}`:" ";let o=this.message;this.count>0&&(o+=` ${P.cyan}${this.count}${P.reset}`,this.total&&(o+=`/${this.total}`),this.detail&&(o+=` ${P.dim}${this.detail}${P.reset}`));let n="";if(this.startTime){let r=Math.floor((Date.now()-this.startTime)/1e3);r>=1&&(n=` ${P.dim}${r}s${P.reset}`)}process.stderr.write(`\x1B[2K\r${s} ${P.dim}${o}${P.reset}${n}`),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),process.stderr.isTTY&&(process.stderr.write("\x1B[?25l"),this._render(),this.interval=setInterval(()=>this._render(),100))}update(e){e.count!==void 0&&(this.count=e.count),e.total!==void 0&&(this.total=e.total),e.detail!==void 0&&(this.detail=e.detail),e.message!==void 0&&(this.message=e.message)}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),process.stderr.isTTY&&process.stderr.write("\x1B[2K\r\x1B[?25h")}};function Df(t){Nt=t}function qf(){return Nt}function Ff(){Nt&&(Nt.stop(),Nt=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}ba.exports={C:P,Spinner:Zo,MultiProgress:er,TaskProgress:tr,ToolProgress:nr,setActiveTaskProgress:Df,getActiveTaskProgress:qf,cleanupTerminal:Ff}});var xa=q((Db,ka)=>{var{T:S}=Ht(),Ne=S;function _a(t){if(!t)return"";let e=t.replace(/^\.\//,"").split("/");return e.length>1?e.slice(-2).join("/"):e[0]}var Uf={read_file:S.tool_read,list_directory:S.tool_read,write_file:S.tool_write,edit_file:S.tool_write,patch_file:S.tool_write,bash:S.tool_exec,grep:S.tool_search,search_files:S.tool_search,glob:S.tool_search,git_commit:S.tool_git,git_push:S.tool_git,git_pull:S.tool_git,git_status:S.tool_git,git_diff:S.tool_git,git_log:S.tool_git,git_branch:S.tool_git,git_stash:S.tool_git,web_fetch:S.tool_web,web_search:S.tool_web,sysadmin:S.tool_sysadmin,ssh_exec:S.tool_sysadmin,ssh_upload:S.tool_sysadmin,ssh_download:S.tool_sysadmin,deploy:S.tool_sysadmin},sr={read_file:"Read file",write_file:"Write",edit_file:"Update",patch_file:"Update",list_directory:"List directory",bash:"Run command",grep:"Search code",search_files:"Search files",glob:"Find files",web_fetch:"Fetch URL",web_search:"Web search",git_status:"Git status",git_diff:"Git diff",git_log:"Git log",git_commit:"Git commit",git_push:"Git push",git_pull:"Git pull",git_branch:"Git branch",git_stash:"Git stash",task_list:"Task list",spawn_agents:"Spawn agents",ask_user:"Ask user",switch_model:"Switch model",gh_run_list:"GH Actions",gh_run_view:"GH Actions",gh_workflow_trigger:"GH trigger",browser_open:"Browser open",browser_screenshot:"Screenshot",browser_click:"Browser click",browser_fill:"Browser fill",ssh_exec:"SSH exec",ssh_upload:"SSH upload",ssh_download:"SSH download",service_manage:"Service",service_logs:"Service logs",container_list:"Containers",container_logs:"Container logs",container_exec:"Container exec",brain_write:"Brain write",deploy:"Deploy",frontend_recon:"Frontend recon"};function As(t,e=!1,s=null){if(e)return`${S.error}\u25CF${S.reset}`;let o=Uf[t]||S.tool_default;return s==="blink"?`${o}\x1B[5m\u25CF\x1B[25m${S.reset}`:`${o}${s!==null?s:"\u25CF"}${S.reset}`}function Wf(t,e,s=!1,o=null){let n=(t||[]).filter(l=>l&&l.canExecute!==!1);if(n.length===0)return`${As("",s,o)} Step ${e}`;if(n.length===1){let l=n[0],u=l.args||{},d=sr[l.fnName]||l.fnName.replace(/_/g," "),f="";u.path?f=_a(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?`${Ne.dim}(${f})${Ne.reset}`:"";return`${As(l.fnName,s,o)} ${Ne.bold}${d}${Ne.reset} ${m}`}let r=n[0].fnName,a=[...new Set(n.map(l=>sr[l.fnName]||l.fnName.replace(/_/g," ")))],c=a.length<=3?a.join(" \xB7 "):`${n.length} actions`;return`${As(r,s,o)} ${c}`}function Bf(t,e){let s;switch(t){case"write_file":case"edit_file":case"patch_file":case"read_file":case"list_directory":s=_a(e.path);break;case"bash":s=(e.command||"").substring(0,80);break;case"grep":case"search_files":s=e.pattern?`"${e.pattern}"${e.path?` in ${e.path}`:""}`:"";break;case"glob":s=e.pattern||"";break;case"web_fetch":s=(e.url||"").substring(0,60);break;case"web_search":s=(e.query||"").substring(0,50);break;default:s=JSON.stringify(e).substring(0,80)}let o=sr[t]||t.replace(/_/g," "),n=s?` ${Ne.dim}(${s})${Ne.reset}`:"";return`${As(t)} ${Ne.bold}${o}${Ne.reset}${n}`}function Hf(t,e=8){let s=t.split(`
|
|
14
|
+
`),o=s.slice(0,e),n=s.length-e,r=`${S.muted} \u2514 ${S.reset}`,a=" ",c=o.map((l,u)=>`${u===0?r:a}${S.success}${l}${S.reset}`).join(`
|
|
15
15
|
`);return n>0&&(c+=`
|
|
16
|
-
${S.subtle} \u2026 +${n} lines${S.reset}`),c}function
|
|
16
|
+
${S.subtle} \u2026 +${n} lines${S.reset}`),c}function Gf(t,e){switch(t){case"bash":case"ask_user":case"write_file":case"edit_file":case"patch_file":case"task_list":case"spawn_agents":return null;case"read_file":return`Reading: ${e.path||"file"}`;case"list_directory":return`Listing: ${e.path||"."}`;case"search_files":return`Searching: ${e.pattern||"..."}`;case"glob":return`Glob: ${e.pattern||"..."}`;case"grep":return`Grep: ${e.pattern||"..."}`;case"web_fetch":return`Fetching: ${(e.url||"").substring(0,60)}`;case"web_search":return`Searching web: ${(e.query||"").substring(0,50)}`;case"git_status":return"Git status...";case"git_diff":return`Git diff${e.file?`: ${e.file}`:""}...`;case"git_log":return`Git log${e.file?`: ${e.file}`:""}...`;case"gh_run_list":return`GitHub Actions: listing runs${e.workflow?` (${e.workflow})`:""}...`;case"gh_run_view":return`GitHub Actions: run ${e.run_id}...`;case"gh_workflow_trigger":return`GitHub Actions: trigger ${e.workflow}...`;case"browser_open":return`Browser: opening ${(e.url||"").substring(0,60)}...`;case"browser_screenshot":return`Browser: screenshot ${(e.url||"").substring(0,60)}...`;case"browser_click":return`Browser: clicking ${e.text||e.selector||"element"}...`;case"browser_fill":return`Browser: filling ${e.selector||"field"}...`;case"sysadmin":{let s=e.server&&e.server!=="local"?` [${e.server}]`:"";switch(e.action){case"audit":return`Sysadmin${s}: full audit...`;case"disk_usage":return`Sysadmin${s}: disk usage ${e.path||"/"}...`;case"process_list":return`Sysadmin${s}: top processes (${e.sort_by||"cpu"})...`;case"network_status":return`Sysadmin${s}: network status...`;case"ssl_check":return`Sysadmin${s}: SSL check ${e.domain||e.cert_path||""}...`;case"log_tail":return`Sysadmin${s}: tail ${e.path||"log"}...`;case"find_large":return`Sysadmin${s}: find large files in ${e.path||"/"}...`;case"service":return`Sysadmin${s}: service ${e.service_action||""} ${e.service_name||""}...`;case"kill_process":return`Sysadmin${s}: kill PID ${e.pid||e.process_name||"?"}...`;case"journalctl":return`Sysadmin${s}: journal ${e.unit?`[${e.unit}]`:""}${e.since?` since ${e.since}`:""}...`;case"package":return`Sysadmin${s}: package ${e.package_action||""} ${(e.packages||[]).join(" ")}...`;case"firewall":return`Sysadmin${s}: firewall ${e.firewall_action||""}...`;case"user_manage":return`Sysadmin${s}: user ${e.user_action||""} ${e.user||""}...`;case"cron":return`Sysadmin${s}: cron ${e.cron_action||""}...`;default:return`Sysadmin${s}: ${e.action}...`}}default:return`Running: ${t}`}}function Kf(t,e,s,o){let n=String(s||"");if(o){let c=n.split(`
|
|
17
17
|
`)[0].replace(/^ERROR:\s*/i,"").substring(0,80),l=n.match(/\nHINT: (.+)/),u=l?`
|
|
18
18
|
${S.muted}${l[1].substring(0,100)}${S.reset}`:"";return` ${S.error}\u2514 ${c}${S.reset}${u}`}let r;switch(t){case"read_file":{let l=n.split(`
|
|
19
19
|
`).filter(Boolean).filter($=>!/^File:\s/.test($)&&!/^\[LARGE FILE:/.test($)),u=l.length,d=l[l.length-1],f=d?parseInt(d.match(/^(\d+):/)?.[1]||"0"):0,m=e.line_start||e.line_end,h=e.path?require("path").basename(e.path):null,p=h?` ${S.muted}from ${h}${S.reset}`:"",g=(l[0]||"").replace(/^\d+:\s*/,"").trim(),y=g?` ${Ne.dim}\u2014 ${g.substring(0,70)}${g.length>70?"\u2026":""}${Ne.reset}`:"";m&&f>u?r=`Read lines ${e.line_start||1}\u2013${f}${p}${y}`:r=`Read ${u} line${u!==1?"s":""}${p}${y}`;break}case"write_file":{let c=(e.content||"").split(`
|
|
@@ -30,7 +30,7 @@ ${h}
|
|
|
30
30
|
`).length,0),u=c.reduce((d,f)=>d+(f.new_text||"").split(`
|
|
31
31
|
`).length,0);r=`${S.reset}${c.length} patch${c.length!==1?"es":""} ${S.diff_rem}\u2212${l}${S.reset} ${S.diff_add}+${u}${S.reset}`;break}case"bash":{let l=n.match(/^EXIT (\d+)/),u=n.split(`
|
|
32
32
|
`).filter(m=>m&&!m.startsWith("EXIT ")&&!m.startsWith("HINT:")&&m.trim()),d=l?l[1]==="0"?`${S.success}\u2713${S.reset}`:`${S.error}\u2717 Exit ${l[1]}${S.reset}`:`${S.success}\u2713${S.reset}`,f=n.match(/\nHINT: (.+)/);if(f)r=`${d} ${S.muted}\u2014 ${f[1].substring(0,100)}${S.reset}`;else if(u.length===0)r=d;else{let m=l&&l[1]!=="0",h=m?u.slice(-6):u.slice(0,6),p=u.length-6,g=h.map((y,$)=>$===0?`${d} ${S.muted}${y.substring(0,120)}${S.reset}`:` ${S.muted}${y.substring(0,120)}${S.reset}`);if(p>0){let y=m?` ${S.subtle}${p} lines above\u2026${S.reset}`:` ${S.subtle}\u2026 +${p} lines${S.reset}`;m?g.unshift(y):g.push(y)}r=g.join(`
|
|
33
|
-
`)}break}case"grep":case"search_files":{if(n.includes("(no matches)")||n==="no matches")r=`No matches${e.pattern?` ${S.muted}"${String(e.pattern).substring(0,40)}"${S.reset}`:""}`;else{let p=function($){let w=$.indexOf(":");if(w===-1)return`${S.muted}${$.substring(0,90)}${S.reset}`;let E=$.substring(0,w),b=$.substring(w+1),k=b.match(/^(\d+)[:-](.*)/s),v=k?`:${k[1]}`:"",R=(k?k[2]:b).trim(),C=`${S.subtle}${c.basename(E)}${v}${S.reset}`,A=`${S.muted}${R.substring(0,80)}${R.length>80?"\u2026":""}${S.reset}`;return`${C} ${A}`};var
|
|
33
|
+
`)}break}case"grep":case"search_files":{if(n.includes("(no matches)")||n==="no matches")r=`No matches${e.pattern?` ${S.muted}"${String(e.pattern).substring(0,40)}"${S.reset}`:""}`;else{let p=function($){let w=$.indexOf(":");if(w===-1)return`${S.muted}${$.substring(0,90)}${S.reset}`;let E=$.substring(0,w),b=$.substring(w+1),k=b.match(/^(\d+)[:-](.*)/s),v=k?`:${k[1]}`:"",R=(k?k[2]:b).trim(),C=`${S.subtle}${c.basename(E)}${v}${S.reset}`,A=`${S.muted}${R.substring(0,80)}${R.length>80?"\u2026":""}${S.reset}`;return`${C} ${A}`};var a=p;let c=require("path"),l=n.split(`
|
|
34
34
|
`).filter(Boolean),u=l.length,f=new Set(l.map($=>$.split(":")[0]).filter(Boolean)).size,m=e.pattern?` ${S.muted}"${String(e.pattern).substring(0,40)}"${S.reset}`:"",h=f>1?`${u} match${u!==1?"es":""} in ${f} files${m}`:`${u} match${u!==1?"es":""}${m}`,g=l.slice(0,4).map(($,w)=>w===0?`${h}
|
|
35
35
|
${p($)}`:` ${p($)}`),y=l.length-4;y>0&&g.push(` ${S.subtle}\u2026 +${y} lines${S.reset}`),r=g.join(`
|
|
36
36
|
`)}break}case"glob":{let c=e.pattern?` ${S.muted}${String(e.pattern).substring(0,50)}${S.reset}`:"";if(n==="(no matches)")r=`No files found${c}`;else{let l=require("path"),u=n.split(`
|
|
@@ -42,114 +42,114 @@ ${h}
|
|
|
42
42
|
|
|
43
43
|
`).filter(Boolean),l=c.length,u=c[0]?c[0].split(`
|
|
44
44
|
`)[0].replace(/^\d+\.\s*/,"").trim():null,d=u?` ${S.muted}\u2014 ${u.substring(0,70)}${S.reset}`:"";r=`${l} result${l!==1?"s":""}${d}`;break}case"task_list":r="Done";break;case"spawn_agents":{let c=(n.match(/✓ Agent/g)||[]).length,l=(n.match(/✗ Agent/g)||[]).length;r=l>0?`${c} done, ${l} failed`:`${c} agent${c!==1?"s":""} done`;break}case"switch_model":{let c=n.match(/Switched to (.+)/);r=c?`\u2192 ${c[1]}`:"Done";break}default:{let c=n.split(`
|
|
45
|
-
`).filter(l=>l.trim()&&!l.startsWith("EXIT ")&&!l.startsWith("HINT:"));if(c.length>0){let l=c[0].trim().substring(0,90),u=c.length>1?` ${S.subtle}+${c.length-1}${S.reset}`:"";r=`${S.muted}${l}${S.reset}${u}`}else r="Done"}}return` ${S.muted}\u2514 ${r}${S.reset}`}function
|
|
45
|
+
`).filter(l=>l.trim()&&!l.startsWith("EXIT ")&&!l.startsWith("HINT:"));if(c.length>0){let l=c[0].trim().substring(0,90),u=c.length>1?` ${S.subtle}+${c.length-1}${S.reset}`:"";r=`${S.muted}${l}${S.reset}${u}`}else r="Done"}}return` ${S.muted}\u2514 ${r}${S.reset}`}function zf(t,e,s,o,n,r){let a=[...s.values()].reduce((d,f)=>d+f,0),c=Math.round(o/1e3),l=c>=60?`${Math.floor(c/60)}m ${c%60}s`:`${c}s`,u=`${S.success}\u25C6${Ne.reset} ${Ne.bold}${t}${Ne.reset}`;return u+=`${Ne.dim} \xB7 ${e} step${e!==1?"s":""}`,u+=` \xB7 ${a} tool${a!==1?"s":""}`,u+=` \xB7 ${l}`,r.size>0&&(u+=` \xB7 ${r.size} file${r.size!==1?"s":""} modified`),u+=Ne.reset,u}ka.exports={C:Ne,formatToolCall:Bf,formatResult:Hf,getToolSpinnerText:Gf,formatToolSummary:Kf,formatSectionHeader:Wf,formatMilestone:zf}});var we=q((qb,Sa)=>{var{T:Gt}=Ht(),or=Gt,va=["01100110","01111110","01111110","01011010","01111110","00111100"];function Yf(t,e){let s=[];for(let o=0;o<t.length;o+=2){let n="";for(let r=0;r<t[0].length;r++){let a=t[o][r]==="1",c=o+1<t.length&&t[o+1][r]==="1";a&&c?n+=`${e}\u2588\x1B[0m`:a&&!c?n+=`${e}\u2580\x1B[0m`:!a&&c?n+=`${e}\u2584\x1B[0m`:n+=" "}s.push(n)}return s}function Xf(t,e,s={}){let o=or.bold,n=or.reset,r=Yf(va,Gt.banner_logo),a=s.yolo?` ${o}${Gt.banner_yolo}\u26A1 YOLO${n}`:"",c=Es().version,l=[` ${Gt.banner_name}${o}nex-code${n} ${Gt.banner_version}v${c}${n}`,` ${Gt.banner_model}${t}${n} ${Gt.muted}\xB7 /help${n}${a}`,""],u=Math.max(r.length,l.length),d=Math.floor((u-r.length)/2),f=Math.floor((u-l.length)/2),m=va[0].length,h=[];for(let p=0;p<u;p++){let g=r[p-d]??" ".repeat(m),y=l[p-f]??"";h.push(g+y)}console.log(`
|
|
46
46
|
`+h.join(`
|
|
47
47
|
`)+`
|
|
48
|
-
`)}var{Spinner:
|
|
49
|
-
`);for(let
|
|
50
|
-
`)}},
|
|
51
|
-
`);
|
|
52
|
-
`){
|
|
53
|
-
`)};return n.length>0&&(r.images=n),r}return s})}async chat(e,s,o={}){await this.discoverModels();let n=o.model||this.defaultModel,r=this.getModel(n),
|
|
54
|
-
`);p=y.pop()||"";for(let $ of y){if(!$.trim())continue;let w;try{w=JSON.parse($)}catch{continue}if(w.message?.thinking&&l(w.message.thinking),w.message?.content&&(c(w.message.content),m+=w.message.content),w.message?.tool_calls&&(h=h.concat(w.message.tool_calls)),w.done){d({content:m,tool_calls:this._normalizeToolCalls(h)});return}}}),u.data.on("error",g=>{o.signal?.aborted||f(new Error(`Stream error: ${g.message}`))}),u.data.on("end",()=>{if(p.trim())try{let g=JSON.parse(p);g.message?.thinking&&l(g.message.thinking),g.message?.content&&(c(g.message.content),m+=g.message.content),g.message?.tool_calls&&(h=h.concat(g.message.tool_calls))}catch{}d({content:m,tool_calls:this._normalizeToolCalls(h)})})})}normalizeResponse(e){let s=e.message||{};return{content:s.content||"",tool_calls:this._normalizeToolCalls(s.tool_calls||[])}}_normalizeToolCalls(e){return e.map((s,o)=>({id:s.id||`ollama-${Date.now()}-${o}`,function:{name:s.function?.name||s.name||"unknown",arguments:s.function?.arguments||s.arguments||{}}}))}};
|
|
48
|
+
`)}var{Spinner:Jf,MultiProgress:Vf,TaskProgress:Qf,ToolProgress:Zf,setActiveTaskProgress:ep,getActiveTaskProgress:tp,cleanupTerminal:np}=Dn(),{formatToolCall:sp,formatResult:op,getToolSpinnerText:rp,formatToolSummary:ip,formatSectionHeader:ap,formatMilestone:cp}=xa();Sa.exports={C:or,banner:Xf,Spinner:Jf,MultiProgress:Vf,TaskProgress:Qf,ToolProgress:Zf,setActiveTaskProgress:ep,getActiveTaskProgress:tp,cleanupTerminal:np,formatToolCall:sp,formatResult:op,getToolSpinnerText:rp,formatToolSummary:ip,formatSectionHeader:ap,formatMilestone:cp}});var Ie=q((Fb,Oa)=>{var lp=require("readline"),{C:gt}=we(),Ea=[/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/],Ta=[/\.env\b/,/credentials\b/i,/\.ssh\b/,/\.gnupg\b/,/\.aws\b/,/\.npmrc\b/,/\.docker\/config/,/\.kube\/config/,/venv\b/,/\.venv\b/,/\.sqlite3\b/,/\.git\/(?!hooks)/],up=/\b(?:rm|rmdir|unlink|truncate|shred|mv|cp)\b/,rr=[/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 Ra(t){let e=t.match(/ssh\s+[^"]*"([^"]+)"/)?.[1]||t.match(/ssh\s+[^']*'([^']+)'/)?.[1];if(!e)return!1;let o=e.replace(/\bfor\s[\s\S]*?\bdone\b/g,r=>r.replace(/;/g,"\0")).replace(/\bwhile\s[\s\S]*?\bdone\b/g,r=>r.replace(/;/g,"\0")).split(/\s*(?:&&|;)\s*/).map(r=>r.replace(/\x00/g,";").trim()).filter(Boolean);if(o.length===0)return!1;let n=r=>{let a=r.replace(/^sudo\s+(?:-[ugCD]\s+\S+\s+|-[A-Za-z]+\s+)*/,"");if(/^\s*(?:echo|printf)\s/.test(a))return!0;if(/^\s*for\s/.test(r)||/^\s*while\s/.test(r)){let c=r.match(/\bdo\s+([\s\S]*?)\s*(?:done|$)/)?.[1];return c?c.split(/\s*;\s*/).map(u=>u.trim()).filter(Boolean).every(u=>n(u)):rr.some(l=>l.test(r))}return/^\w+=\$?\(/.test(a)||/^\w+=["']/.test(a)||/^\w+=\S/.test(a)?!0:rr.some(c=>c.test(a))};return o.every(n)}var ar=[/rm\s+-rf\s/,/docker\s+system\s+prune/,/kubectl\s+delete/,/sudo\s/,/--no-verify\b/,/git\s+reset\s+--hard\b/,/git\s+clean\s+-[a-z]*f/,/git\s+checkout\s+--\s/,/git\s+push\s+(?:--force\b|-f\b)/],Ca=[/git\s+push/,/npm\s+publish/,/\bHUSKY=0\b/,/\bSKIP_HUSKY=1\b/,/\bSKIP_PREFLIGHT_CHECK=true\b/,/npx\s+.*publish/,/docker\s+rm/,/ssh\s/,/wget\s/,/curl\s.*-o\s/,/pip\s+install/,/npm\s+install\s+-g/],Aa=[...ar,...Ca],cr=!1,Kt=null,ir=null;function dp(t){cr=t}function fp(t){ir=t}function pp(){return cr}function mp(t){Kt=t}function hp(t){for(let e of Ea)if(e.test(t))return e;return null}function gp(t){if(/ssh\s/.test(t)&&Ra(t))return!1;for(let e of Aa)if(e.test(t))return!0;return!1}function $p(t){for(let e of ar)if(e.test(t))return!0;return!1}function yp(t){if(process.env.NEX_UNPROTECT==="1"||!up.test(t))return null;for(let e of Ta)if(e.test(t))return e;return null}function wp(t,e={}){if(cr)return Promise.resolve(!0);if(ir)return ir(t,e);if(!process.stdout.isTTY||!process.stdin.isTTY)return bp(t,e);let s=e.toolName?["Yes","No","Always allow"]:["Yes","No"];return new Promise(o=>{let n=0,r=!1;Kt&&Kt.pause();let a=global._nexRawWrite||(f=>process.stdout.write(f)),c=()=>{r&&a(`\x1B[${s.length+1}A`),r=!0,a(`\r\x1B[K${gt.yellow}${t}${gt.reset}
|
|
49
|
+
`);for(let f=0;f<s.length;f++){let m=f===n,h=m?`${gt.yellow}\u276F${gt.reset}`:" ",p=m?`${gt.yellow}${s[f]}${gt.reset}`:s[f];a(`\r\x1B[K ${h} ${p}
|
|
50
|
+
`)}},l=f=>{process.stdin.setRawMode(!1),process.stdin.pause(),process.stdin.removeListener("data",d);let m=global._nexRawWrite||(h=>process.stdout.write(h));m(`\x1B[${s.length+1}A`);for(let h=0;h<s.length+1;h++)m(`\r\x1B[K
|
|
51
|
+
`);m(`\x1B[${s.length+1}A`),Kt&&Kt.resume(),o(f)},u=f=>{if(f===1){l(!1);return}f===2&&e.toolName&&Os(e.toolName),l(!0)},d=f=>{if(f[0]===3){l(!1);return}let m=f.toString();if(m==="\r"||m===`
|
|
52
|
+
`){u(n);return}if(m==="\x1B[A"){n=(n-1+s.length)%s.length,c();return}if(m==="\x1B[B"){n=(n+1)%s.length,c();return}let h=m.toLowerCase().trim();if(h==="y"){l(!0);return}if(h==="n"){l(!1);return}if(h==="a"&&e.toolName){Os(e.toolName),l(!0);return}};c(),process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",d)})}function bp(t,e){let s=e.toolName?"[Y/n/a] ":"[Y/n] ";return new Promise(o=>{let n=r=>{let a=r.trim().toLowerCase();a==="a"&&e.toolName?(Os(e.toolName),o(!0)):o(a!=="n")};if(Kt)Kt.question(`${gt.yellow}${t} ${s}${gt.reset}`,n);else{let r=lp.createInterface({input:process.stdin,output:process.stdout});r.question(`${gt.yellow}${t} ${s}${gt.reset}`,a=>{r.close(),n(a)})}})}var Os=()=>{};function _p(t){Os=t}Oa.exports={FORBIDDEN_PATTERNS:Ea,BASH_PROTECTED_PATHS:Ta,SSH_SAFE_PATTERNS:rr,isSSHReadOnly:Ra,DANGEROUS_BASH:Aa,CRITICAL_BASH:ar,NOTABLE_BASH:Ca,isForbidden:hp,isDangerous:gp,isCritical:$p,isBashPathForbidden:yp,confirm:wp,setAutoConfirm:dp,getAutoConfirm:pp,setConfirmHook:fp,setReadlineInterface:mp,setAllowAlwaysHandler:_p}});var pn=q((Ub,Na)=>{var lr=class t{constructor(e={}){if(new.target===t)throw new Error("BaseProvider is abstract \u2014 use a concrete provider");this.name=e.name||"unknown",this.baseUrl=e.baseUrl||"",this.models=e.models||{},this.defaultModel=e.defaultModel||null}isConfigured(){throw new Error(`${this.name}: isConfigured() not implemented`)}getApiKey(){return null}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}getModel(e){return this.models[e]||null}async chat(e,s,o={}){throw new Error(`${this.name}: chat() not implemented`)}async stream(e,s,o={}){throw new Error(`${this.name}: stream() not implemented`)}formatMessages(e){return{messages:e}}formatTools(e){return e}normalizeResponse(e){throw new Error(`${this.name}: normalizeResponse() not implemented`)}};Na.exports={BaseProvider:lr}});var Pa=q((Wb,Ia)=>{var Ns=require("axios"),kp=require("http"),xp=require("https"),{BaseProvider:vp}=pn(),Ms=new kp.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Is=new xp.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Ma={"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}},ur=class extends vp{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||Ma,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){Ns.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Ms,httpsAgent:Is}).then(e=>{let s=e.data?.models||[];for(let o of s){let n=(o.name||o.model||"").replace(/:latest$/,"");!n||this.models[n]||(this.models[n]={id:n,name:o.name||n,maxTokens:16384,contextWindow:131072})}}).catch(()=>{});return}try{let s=(await Ns.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Ms,httpsAgent:Is})).data?.models||[];for(let o of s){let n=(o.name||o.model||"").replace(/:latest$/,"");!n||this.models[n]||(this.models[n]={id:n,name:o.name||n,maxTokens:16384,contextWindow:131072})}}catch{}}}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OLLAMA_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OLLAMA_API_KEY not set");return{Authorization:`Bearer ${e}`}}_formatMessages(e){return e.map(s=>{if(s.role==="user"&&Array.isArray(s.content)){let o=[],n=[];for(let a of s.content)a.type==="text"?o.push(a.text??""):a.type==="image"&&a.data&&n.push(a.data);let r={role:"user",content:o.join(`
|
|
53
|
+
`)};return n.length>0&&(r.images=n),r}return s})}async chat(e,s,o={}){await this.discoverModels();let n=o.model||this.defaultModel,r=this.getModel(n),a=o.maxTokens||r?.maxTokens||16384,c=await Ns.post(`${this.baseUrl}/api/chat`,{model:n,messages:this._formatMessages(e),tools:s&&s.length>0?s:void 0,stream:!1,options:{temperature:o.temperature??this.temperature,num_predict:a}},{timeout:o.timeout||this.timeout,headers:this._getHeaders(),httpAgent:Ms,httpsAgent:Is});return this.normalizeResponse(c.data)}async stream(e,s,o={}){await this.discoverModels();let n=o.model||this.defaultModel,r=this.getModel(n),a=o.maxTokens||r?.maxTokens||16384,c=o.onToken||(()=>{}),l=o.onThinkingToken||(()=>{}),u;try{u=await Ns.post(`${this.baseUrl}/api/chat`,{model:n,messages:this._formatMessages(e),tools:s&&s.length>0?s:void 0,stream:!0,options:{temperature:o.temperature??this.temperature,num_predict:a}},{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal,httpAgent:Ms,httpsAgent:Is})}catch(d){if(d.name==="CanceledError"||d.name==="AbortError"||d.code==="ERR_CANCELED")throw d;let f=d.response?.data?.error||d.message;throw new Error(`API Error: ${f}`)}return new Promise((d,f)=>{let m="",h=[],p="";o.signal&&o.signal.addEventListener("abort",()=>{u.data.destroy(),f(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",g=>{p+=g.toString();let y=p.split(`
|
|
54
|
+
`);p=y.pop()||"";for(let $ of y){if(!$.trim())continue;let w;try{w=JSON.parse($)}catch{continue}if(w.message?.thinking&&l(w.message.thinking),w.message?.content&&(c(w.message.content),m+=w.message.content),w.message?.tool_calls&&(h=h.concat(w.message.tool_calls)),w.done){d({content:m,tool_calls:this._normalizeToolCalls(h)});return}}}),u.data.on("error",g=>{o.signal?.aborted||f(new Error(`Stream error: ${g.message}`))}),u.data.on("end",()=>{if(p.trim())try{let g=JSON.parse(p);g.message?.thinking&&l(g.message.thinking),g.message?.content&&(c(g.message.content),m+=g.message.content),g.message?.tool_calls&&(h=h.concat(g.message.tool_calls))}catch{}d({content:m,tool_calls:this._normalizeToolCalls(h)})})})}normalizeResponse(e){let s=e.message||{};return{content:s.content||"",tool_calls:this._normalizeToolCalls(s.tool_calls||[])}}_normalizeToolCalls(e){return e.map((s,o)=>({id:s.id||`ollama-${Date.now()}-${o}`,function:{name:s.function?.name||s.name||"unknown",arguments:s.function?.arguments||s.arguments||{}}}))}};Ia.exports={OllamaProvider:ur,OLLAMA_MODELS:Ma}});var Ua=q((Bb,Fa)=>{var{callChat:Sp}=be(),{estimateTokens:dr}=lt(),La=process.env.NEX_COMPACTION!=="false",ja=6,Da=500,Ep=`Summarize this conversation history concisely. Focus on:
|
|
55
55
|
- What files were read, created, or modified
|
|
56
56
|
- Key decisions made and their rationale
|
|
57
57
|
- Current state of the task (what's done, what's pending)
|
|
58
58
|
- Any errors encountered and how they were resolved
|
|
59
|
-
Be factual and brief. Use bullet points. Max 300 words.`;async function
|
|
60
|
-
${o}`,_compacted:!0,_originalCount:t.length},tokensRemoved:n-r}}catch{return null}}function
|
|
59
|
+
Be factual and brief. Use bullet points. Max 300 words.`;async function Tp(t){if(!La||t.length<ja)return null;let e=[{role:"system",content:Ep},{role:"user",content:qa(t)}];try{let o=((await Sp(e,[],{temperature:0,maxTokens:Da})).content||"").trim();if(!o)return null;let n=t.reduce((a,c)=>a+dr(c.content||"")+(c.tool_calls?dr(JSON.stringify(c.tool_calls)):0),0),r=dr(o);return r>=n*.8?null:{message:{role:"system",content:`[Conversation Summary \u2014 ${t.length} messages compacted]
|
|
60
|
+
${o}`,_compacted:!0,_originalCount:t.length},tokensRemoved:n-r}}catch{return null}}function qa(t){return t.map(e=>{let s=e.role==="tool"?"tool_result":e.role,o=(e.content||"").substring(0,500);if(e.tool_calls){let n=e.tool_calls.map(r=>r.function?.name).join(", ");return`[${s}] ${o}
|
|
61
61
|
tools: ${n}`}return`[${s}] ${o}`}).join(`
|
|
62
62
|
|
|
63
|
-
`)}
|
|
63
|
+
`)}Fa.exports={compactMessages:Tp,formatMessagesForSummary:qa,COMPACTION_ENABLED:La,COMPACTION_MIN_MESSAGES:ja,COMPACTION_SUMMARY_BUDGET:Da}});var lt=q((Hb,Ja)=>{var Rp=require("path");function Ba(){return be().getActiveModel()}var Cp={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},zt=new Map,Wa=1e3,fr=new WeakMap,qn=null;function Ap(){if(qn!==null)return qn;try{let e=Ba()?.provider||"ollama";return qn=Cp[e]||4,qn}catch{return 4}}function Op(){qn=null}function Yt(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=zt.get(e);if(s!==void 0)return zt.delete(e),zt.set(e,s),s;let o=Math.ceil(t.length/Ap());if(zt.size>=Wa){let n=Wa>>1,r=zt.keys();for(let a=0;a<n;a++)zt.delete(r.next().value)}return zt.set(e,o),o}function Np(t){if(fr.has(t))return fr.get(t);let e=JSON.stringify(t);return fr.set(t,e),e}function hn(t){let s=4;if(t.content&&(s+=Yt(t.content)),t.tool_calls)for(let o of t.tool_calls){s+=4,s+=Yt(o.function?.name||"");let n=o.function?.arguments;typeof n=="string"?s+=Yt(n):n&&(s+=Yt(JSON.stringify(n)))}return s}function st(t){let e=0;for(let s of t)e+=hn(s);return e}function Mp(t,e){if(t&&t.length===e.length){let r=!1;for(let a=0;a<e.length;a++)if(t[a]!==e[a]){r=!0;break}if(!r)return 0}let s=t?t.length:0,o=e.length,n=0;for(let r=s;r<o;r++)n+=hn(e[r]);return n}function Ps(t){return!t||t.length===0?0:Yt(JSON.stringify(t))}function Ls(){return Ba()?.contextWindow||32768}function Ip(t,e){let s=st(t),o=Ps(e),n=s+o,r=Ls(),a=r>0?n/r*100:0,c=0,l=0,u=0;for(let d of t){let f=hn(d);d.role==="system"?c+=f:d.role==="tool"?u+=f:l+=f}return{used:n,limit:r,percentage:Math.round(a*10)/10,breakdown:{system:c,conversation:l,toolResults:u,toolDefinitions:o},messageCount:t.length}}var Ha=parseFloat(process.env.NEX_COMPRESSION_THRESHOLD)||.75,Ga=parseFloat(process.env.NEX_SAFETY_MARGIN)||.1,Ka=parseInt(process.env.NEX_KEEP_RECENT,10)||10,Pp=200,Lp=500;function za(t,e){if(!t||t.length<=e)return t;let o=/^(ERROR|EXIT|BLOCKED|CANCELLED)/i.test(t)?e*3:e;if(t.length<=o)return t;let n=t.split(`
|
|
64
64
|
`);if(n.length<=10){let p=Math.floor(o*.6),g=Math.floor(o*.4),y=t.substring(0,p),$=t.substring(t.length-g);return y+`
|
|
65
65
|
...(${t.length} chars total)...
|
|
66
|
-
`+$}let r=Math.floor(n.length*.4),
|
|
66
|
+
`+$}let r=Math.floor(n.length*.4),a=Math.floor(n.length*.4),c=[],l=0,u=Math.floor(o*.4);for(let p=0;p<r&&l<u;p++)if(l+n[p].length+1>u&&n[p].trim().startsWith("```")){c.push(n[p]),l+=n[p].length+1;let g=p+1;for(;g<n.length&&l<u*1.5&&!n[g].trim().startsWith("```");)c.push(n[g]),l+=n[g].length+1,g++;g<n.length&&n[g].trim().startsWith("```")&&(c.push(n[g]),l+=n[g].length+1),p=g}else c.push(n[p]),l+=n[p].length+1;let d=[],f=0,m=Math.floor(o*.4);for(let p=n.length-1;p>=n.length-a&&f<m;p--)if(f+n[p].length+1>m&&n[p].trim().startsWith("```")){d.push(n[p]),f+=n[p].length+1;let g=p-1;for(;g>=0&&f<m*1.5&&!n[g].trim().startsWith("```");)d.push(n[g]),f+=n[g].length+1,g--;g>=0&&n[g].trim().startsWith("```")&&(d.push(n[g]),f+=n[g].length+1),p=g}else d.push(n[p]),f+=n[p].length+1;d.reverse();let h=n.length-c.length-d.length;return c.join(`
|
|
67
67
|
`)+`
|
|
68
68
|
...(${h} lines omitted, ${n.length} total)...
|
|
69
69
|
`+d.join(`
|
|
70
|
-
`)}function mn(t,e="light"){let s=e==="aggressive"?100:e==="medium"?200:
|
|
71
|
-
...(truncated)`),n.tool_calls&&e==="aggressive"&&(n.tool_calls=n.tool_calls.map(r=>({...r,function:{name:r.function.name,arguments:typeof r.function.arguments=="string"?r.function.arguments.substring(0,50):r.function.arguments}}))),n}return t}function
|
|
72
|
-
`),r=Math.floor(o*.6),
|
|
70
|
+
`)}function mn(t,e="light"){let s=e==="aggressive"?100:e==="medium"?200:Lp,o=e==="aggressive"?50:e==="medium"?100:Pp;if(t.role==="tool"){let n=typeof t.content=="string"?t.content:JSON.stringify(t.content);return n.length>o?{...t,content:za(n,o)}:t}if(t.role==="assistant"){let n={...t};return n.content&&n.content.length>s&&(n.content=n.content.substring(0,s)+`
|
|
71
|
+
...(truncated)`),n.tool_calls&&e==="aggressive"&&(n.tool_calls=n.tool_calls.map(r=>({...r,function:{name:r.function.name,arguments:typeof r.function.arguments=="string"?r.function.arguments.substring(0,50):r.function.arguments}}))),n}return t}function Ya(t,e,s,o){let n=0;if(t.role==="system")return 100;if(t.role==="user")n+=35;else if(t.role==="tool"){let a=typeof t.content=="string"?t.content:JSON.stringify(t.content||"");/^(ERROR|BLOCKED|CANCELLED)/i.test(a)?n+=30:n+=15}else t.role==="assistant"&&(n+=t.tool_calls?20:10);let r=s>1?e/(s-1):1;if(n+=Math.round(r*30),o&&o.size>0){let a=typeof t.content=="string"?t.content:JSON.stringify(t.content||""),c=0;for(let l of o)(a.includes(l)||a.includes(Rp.basename(l)))&&c++;n+=Math.min(30,c*10)}return Math.min(100,n)}function Xa(t,e=10){let s=new Set,o=t.slice(-e),n=/(?:\/[\w.-]+)+\.\w+/g;for(let r of o){let c=(typeof r.content=="string"?r.content:JSON.stringify(r.content||"")).match(n);c&&c.forEach(l=>s.add(l))}return s}async function jp(t,e,s={}){let o=s.threshold??Ha,n=s.safetyMargin??Ga,r=s.keepRecent??Ka,a=Ls(),c=Ps(e),l=Math.floor(a*(o-n)),u=l-c,d=st(t),f=d+c;if(f<=l)return{messages:t,compressed:!1,compacted:!1,tokensRemoved:0};let m=d,h=null,p=0;t.length>0&&t[0].role==="system"&&(h=t[0],p=1);let g=Math.max(p,t.length-r),y=t.slice(p,g),$=t.slice(g),w=y.filter(A=>!A._compacted);if(w.length>=6)try{let{compactMessages:A}=Ua(),j=await A(w);if(j){let X=[...y.filter(U=>U._compacted),j.message],H=Mt(h,X,$),G=st(H);if(G+c<=l)return{messages:H,compressed:!0,compacted:!0,tokensRemoved:m-G};y=X}}catch(A){process.env.NEX_DEBUG&&console.error("[context-engine] LLM compacting failed:",A.message)}let E=(f-l)/l,b=y.map(A=>mn(A,"light")),k=Mt(h,b,$),v=st(k);if(v+c<=l)return{messages:k,compressed:!0,compacted:!1,tokensRemoved:m-v};if(b=y.map(A=>mn(A,"medium")),k=Mt(h,b,$),v=st(k),v+c<=l)return{messages:k,compressed:!0,compacted:!1,tokensRemoved:m-v};if(b=y.map(A=>mn(A,"aggressive")),k=Mt(h,b,$),v=st(k),v+c<=l)return{messages:k,compressed:!0,compacted:!1,tokensRemoved:m-v};let R=Xa([...b,...$]),C=b.map((A,j)=>({msg:A,score:Ya(A,j,b.length,R),tokens:hn(A)}));for(;C.length>0&&v>u;){let A=0;for(let j=1;j<C.length;j++)C[j].score<C[A].score&&(A=j);v-=C[A].tokens,C.splice(A,1)}return b=C.map(A=>A.msg),k=Mt(h,b,$),v=st(k),{messages:k,compressed:!0,compacted:!1,tokensRemoved:m-v}}function Mt(t,e,s){let o=[];return t&&o.push(t),o.push(...e,...s),o}function Dp(t,e){if(!t)return"";if(Yt(t)<=e)return t;let o=e*4,n=t.split(`
|
|
72
|
+
`),r=Math.floor(o*.6),a=Math.floor(o*.4),c="",l=0;for(let h of n){if(c.length+h.length+1>r)break;c+=(c?`
|
|
73
73
|
`:"")+h,l++}let u="",d=0;for(let h=n.length-1;h>=l;h--){let p=n[h]+(u?`
|
|
74
|
-
`:"")+u;if(p.length>
|
|
74
|
+
`:"")+u;if(p.length>a)break;u=p,d++}let m=`
|
|
75
75
|
|
|
76
76
|
... (${n.length-l-d} lines omitted, ${n.length} total) ...
|
|
77
77
|
|
|
78
|
-
`;return c+m+u}var
|
|
79
|
-
`);g=$.pop()||"";for(let w of $){let E=w.trim();if(!E||!E.startsWith("data: "))continue;let b=E.slice(6);if(b==="[DONE]"){f({content:h,tool_calls:this._buildToolCalls(p)});return}let k;try{k=JSON.parse(b)}catch{continue}let v=k.choices?.[0]?.delta;if(v&&(v.content&&(c(v.content),h+=v.content),v.tool_calls))for(let R of v.tool_calls){let C=R.index??0;p[C]||(p[C]={id:R.id||"",name:"",arguments:""}),R.id&&(p[C].id=R.id),R.function?.name&&(p[C].name+=R.function.name),R.function?.arguments&&(p[C].arguments+=R.function.arguments)}}}),d.data.on("error",y=>{o.signal?.aborted||m(new Error(`Stream error: ${y.message}`))}),d.data.on("end",()=>{f({content:h,tool_calls:this._buildToolCalls(p)})})})}normalizeResponse(e){let s=e.choices?.[0]?.message||{},o=(s.tool_calls||[]).map(n=>({id:n.id,function:{name:n.function.name,arguments:n.function.arguments}}));return{content:s.content||"",tool_calls:o}}_buildToolCalls(e){return Object.values(e).filter(s=>s.name).map(s=>({id:s.id||`openai-${Date.now()}`,function:{name:s.name,arguments:s.arguments}}))}};
|
|
80
|
-
|
|
81
|
-
`:"")+n.content;continue}if(n.role!=="system"&&n.role!=="tool"&&this._messageFormatCache.has(n)){o.push(this._messageFormatCache.get(n));continue}let r=this._formatSingleMessage(n,o);if(r){if(n.role!=="system"&&n.role!=="tool"&&this._messageStringCache.size<this._maxCacheSize){let
|
|
82
|
-
`);E=k.pop()||"";for(let v of k){let R=v.trim();if(R.startsWith("data: ")){let C=R.slice(6),A;try{A=JSON.parse(C)}catch{continue}switch(A.type){case"content_block_start":{let j=A.content_block;j?.type==="tool_use"&&(w=$.length,$.push({id:j.id,name:j.name,inputJson:""}));break}case"content_block_delta":{let j=A.delta;j?.type==="text_delta"&&j.text&&(l(j.text),y+=j.text),j?.type==="input_json_delta"&&j.partial_json!==void 0&&w>=0&&($[w].inputJson+=j.partial_json);break}case"content_block_stop":w=-1;break;case"message_stop":p({content:y,tool_calls:this._buildToolCalls($)});return}}}}),h.data.on("error",b=>{o.signal?.aborted||g(new Error(`Stream error: ${b.message}`))}),h.data.on("end",()=>{p({content:y,tool_calls:this._buildToolCalls($)})})})}normalizeResponse(e){let s="",o=[];for(let n of e.content||[])n.type==="text"?s+=n.text:n.type==="tool_use"&&o.push({id:n.id,function:{name:n.name,arguments:n.input}});return{content:s,tool_calls:o}}_buildToolCalls(e){return e.filter(s=>s.name).map(s=>{let o={};if(s.inputJson)try{o=JSON.parse(s.inputJson)}catch{o=s.inputJson}return{id:s.id||`anthropic-${Date.now()}`,function:{name:s.name,arguments:o}}})}};
|
|
83
|
-
`);g=$.pop()||"";for(let w of $){let E=w.trim();if(!E||!E.startsWith("data: "))continue;let b=E.slice(6);if(b==="[DONE]"){f({content:h,tool_calls:this._buildToolCalls(p)});return}let k;try{k=JSON.parse(b)}catch{continue}let v=k.choices?.[0]?.delta;if(v&&(v.content&&(c(v.content),h+=v.content),v.tool_calls))for(let R of v.tool_calls){let C=R.index??0;p[C]||(p[C]={id:R.id||"",name:"",arguments:""}),R.id&&(p[C].id=R.id),R.function?.name&&(p[C].name+=R.function.name),R.function?.arguments&&(p[C].arguments+=R.function.arguments)}}}),d.data.on("error",y=>{o.signal?.aborted||m(new Error(`Stream error: ${y.message}`))}),d.data.on("end",()=>{f({content:h,tool_calls:this._buildToolCalls(p)})})})}normalizeResponse(e){let s=e.choices?.[0]?.message||{},o=(s.tool_calls||[]).map(n=>({id:n.id,function:{name:n.function.name,arguments:n.function.arguments}}));return{content:s.content||"",tool_calls:o}}_buildToolCalls(e){return Object.values(e).filter(s=>s.name).map(s=>({id:s.id||`call-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,function:{name:s.name,arguments:s.arguments}}))}};
|
|
84
|
-
`)};return n.length>0&&(r.images=n),r}return s})}async chat(e,s,o={}){this._modelsLoaded||await this.loadModels();let n=o.model||this.defaultModel;if(!n)throw new Error("No local model available. Is Ollama running?");let r=await js.post(`${this.baseUrl}/api/chat`,{model:n,messages:this._formatMessages(e),tools:s&&s.length>0?s:void 0,stream:!1,options:{temperature:o.temperature??this.temperature,num_predict:o.maxTokens||8192}},{timeout:o.timeout||this.timeout});return this.normalizeResponse(r.data)}async stream(e,s,o={}){this._modelsLoaded||await this.loadModels();let n=o.model||this.defaultModel;if(!n)throw new Error("No local model available. Is Ollama running?");let r=o.onToken||(()=>{}),
|
|
85
|
-
`);f=h.pop()||"";for(let p of h){if(!p.trim())continue;let g;try{g=JSON.parse(p)}catch{continue}if(g.message?.content&&(r(g.message.content),u+=g.message.content),g.message?.tool_calls&&(d=d.concat(g.message.tool_calls)),g.done){c({content:u,tool_calls:this._normalizeToolCalls(d)});return}}}),
|
|
86
|
-
`)}}function yr(t,e){let s=
|
|
87
|
-
`)}function
|
|
88
|
-
`),c}catch(c){throw n.stop(),c}}async function
|
|
78
|
+
`;return c+m+u}var qp=6;function Fp(t,e,s=!1){let o=Ls(),n=Ps(e),r=Math.floor(o*(s?.35:.5))-n,a=st(t),c=Math.floor(a*(s?.5:.8));r>c&&(r=c);let l=null,u=0;t.length>0&&t[0].role==="system"&&(l=t[0],u=1);let d=s?2:qp,f=Math.max(u,t.length-d),m=t.slice(u,f),h=t.slice(f),p=m.map($=>mn($,"aggressive"));s&&(h=h.map($=>mn($,"aggressive")));let g=Mt(l,p,h),y=st(g);for(;p.length>0&&y>r;){let $=p.shift();y-=hn($)}return s&&y>r&&(h=h.filter(w=>w.role==="user").slice(-1),g=Mt(l,[],h),y=st(g)),g=Mt(l,p,h),{messages:g,tokensRemoved:a-st(g)}}Ja.exports={estimateTokens:Yt,estimateMessageTokens:hn,estimateMessagesTokens:st,estimateDeltaTokens:Mp,estimateToolsTokens:Ps,serializeMessage:Np,getContextWindow:Ls,getUsage:Ip,compressMessage:mn,compressToolResult:za,scoreMessageRelevance:Ya,extractActiveFiles:Xa,fitToContext:jp,forceCompress:Fp,truncateFileContent:Dp,invalidateTokenRatioCache:Op,COMPRESSION_THRESHOLD:Ha,SAFETY_MARGIN:Ga,KEEP_RECENT:Ka}});var ec=q((Kb,Za)=>{var Va=require("axios"),{BaseProvider:Up}=pn(),{serializeMessage:Gb}=lt(),Qa={"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}},pr=class extends Up{constructor(e={}){super({name:"openai",baseUrl:e.baseUrl||"https://api.openai.com/v1",models:e.models||Qa,defaultModel:e.defaultModel||"gpt-4o",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OPENAI_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OPENAI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let s=[];for(let o of e){if(this._messageFormatCache.has(o)){s.push(this._messageFormatCache.get(o));continue}let n=this._getMessageCacheKey(o);if(this._messageStringCache.has(n)){let a=this._messageStringCache.get(n);this._messageFormatCache.set(o,a),s.push(a);continue}let r=this._formatSingleMessage(o);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(n,r),this._messageFormatCache.set(o,r),s.push(r)}return{messages:s}}_getMessageCacheKey(e){let s=e.role||"",o=typeof e.content=="string"?e.content.substring(0,100):"",n=e.tool_calls?e.tool_calls.length:0;return`${s}:${o.length}:${n}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||null,tool_calls:e.tool_calls.map(s=>({id:s.id||`call-${Date.now()}`,type:"function",function:{name:s.function.name,arguments:typeof s.function.arguments=="string"?s.function.arguments:JSON.stringify(s.function.arguments)}}))};if(e.role==="tool")return{role:"tool",content:typeof e.content=="string"?e.content:JSON.stringify(e.content),tool_call_id:e.tool_call_id};if(e.role==="user"&&Array.isArray(e.content)){let s=[];for(let o of e.content)if(o.type==="text")s.push({type:"text",text:o.text??""});else if(o.type==="image"&&o.data){let n=o.data.startsWith("data:")?o.data:`data:${o.media_type||"image/png"};base64,${o.data}`;s.push({type:"image_url",image_url:{url:n,detail:"auto"}})}return{role:"user",content:s}}return{role:e.role,content:e.content}}async chat(e,s,o={}){let n=o.model||this.defaultModel,r=this.getModel(n),a=o.maxTokens||r?.maxTokens||16384,{messages:c}=this.formatMessages(e),l={model:n,messages:c,max_tokens:a,temperature:o.temperature??this.temperature};s&&s.length>0&&(l.tools=s);let u=await Va.post(`${this.baseUrl}/chat/completions`,l,{timeout:o.timeout||this.timeout,headers:this._getHeaders()});return this.normalizeResponse(u.data)}async stream(e,s,o={}){let n=o.model||this.defaultModel,r=this.getModel(n),a=o.maxTokens||r?.maxTokens||16384,c=o.onToken||(()=>{}),{messages:l}=this.formatMessages(e),u={model:n,messages:l,max_tokens:a,temperature:o.temperature??this.temperature,stream:!0};s&&s.length>0&&(u.tools=s);let d;try{d=await Va.post(`${this.baseUrl}/chat/completions`,u,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let m=f.response?.data?.error?.message||f.message;throw new Error(`API Error: ${m}`)}return new Promise((f,m)=>{let h="",p={},g="";o.signal&&o.signal.addEventListener("abort",()=>{d.data.destroy(),m(new DOMException("The operation was aborted","AbortError"))},{once:!0}),d.data.on("data",y=>{g+=y.toString();let $=g.split(`
|
|
79
|
+
`);g=$.pop()||"";for(let w of $){let E=w.trim();if(!E||!E.startsWith("data: "))continue;let b=E.slice(6);if(b==="[DONE]"){f({content:h,tool_calls:this._buildToolCalls(p)});return}let k;try{k=JSON.parse(b)}catch{continue}let v=k.choices?.[0]?.delta;if(v&&(v.content&&(c(v.content),h+=v.content),v.tool_calls))for(let R of v.tool_calls){let C=R.index??0;p[C]||(p[C]={id:R.id||"",name:"",arguments:""}),R.id&&(p[C].id=R.id),R.function?.name&&(p[C].name+=R.function.name),R.function?.arguments&&(p[C].arguments+=R.function.arguments)}}}),d.data.on("error",y=>{o.signal?.aborted||m(new Error(`Stream error: ${y.message}`))}),d.data.on("end",()=>{f({content:h,tool_calls:this._buildToolCalls(p)})})})}normalizeResponse(e){let s=e.choices?.[0]?.message||{},o=(s.tool_calls||[]).map(n=>({id:n.id,function:{name:n.function.name,arguments:n.function.arguments}}));return{content:s.content||"",tool_calls:o}}_buildToolCalls(e){return Object.values(e).filter(s=>s.name).map(s=>({id:s.id||`openai-${Date.now()}`,function:{name:s.name,arguments:s.arguments}}))}};Za.exports={OpenAIProvider:pr,OPENAI_MODELS:Qa}});var oc=q((Yb,sc)=>{var tc=require("axios"),{BaseProvider:Wp}=pn(),{serializeMessage:zb}=lt(),nc={"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}},Bp="2023-06-01",mr=class extends Wp{constructor(e={}){super({name:"anthropic",baseUrl:e.baseUrl||"https://api.anthropic.com/v1",models:e.models||nc,defaultModel:e.defaultModel||"claude-sonnet",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this.apiVersion=e.apiVersion||Bp}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.ANTHROPIC_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("ANTHROPIC_API_KEY not set");return{"x-api-key":e,"anthropic-version":this.apiVersion,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let s="",o=[];for(let n of e){if(n.role==="system"){s+=(s?`
|
|
80
|
+
|
|
81
|
+
`:"")+n.content;continue}if(n.role!=="system"&&n.role!=="tool"&&this._messageFormatCache.has(n)){o.push(this._messageFormatCache.get(n));continue}let r=this._formatSingleMessage(n,o);if(r){if(n.role!=="system"&&n.role!=="tool"&&this._messageStringCache.size<this._maxCacheSize){let a=this._getMessageCacheKey(n);this._messageStringCache.set(a,r),this._messageFormatCache.set(n,r)}o.push(r)}}return{messages:o,system:s}}_getMessageCacheKey(e){let s=e.role||"",o=typeof e.content=="string"?e.content.substring(0,100):"",n=e.tool_calls?e.tool_calls.length:0;return`${s}:${o.length}:${n}`}_formatSingleMessage(e,s=[]){if(e.role==="assistant"){let o=[];if(e.content&&o.push({type:"text",text:e.content}),e.tool_calls)for(let n of e.tool_calls)o.push({type:"tool_use",id:n.id||`toolu-${Date.now()}`,name:n.function.name,input:typeof n.function.arguments=="string"?JSON.parse(n.function.arguments||"{}"):n.function.arguments||{}});return{role:"assistant",content:o.length>0?o:[{type:"text",text:""}]}}if(e.role==="tool"){let o=s[s.length-1],n={type:"tool_result",tool_use_id:e.tool_call_id,content:typeof e.content=="string"?e.content:JSON.stringify(e.content)};return o&&o.role==="user"&&Array.isArray(o.content)&&o.content[0]?.type==="tool_result"?(o.content.push(n),null):{role:"user",content:[n]}}if(Array.isArray(e.content)){let o=[];for(let n of e.content)n.type==="text"?o.push({type:"text",text:n.text??""}):n.type==="image"&&n.data&&o.push({type:"image",source:{type:"base64",media_type:n.media_type||"image/png",data:n.data}});return{role:"user",content:o}}return{role:"user",content:e.content}}formatTools(e){return!e||e.length===0?[]:e.map(s=>({name:s.function.name,description:s.function.description||"",input_schema:s.function.parameters||{type:"object",properties:{}}}))}_resolveModelId(e){return this.getModel(e)?.id||e}async chat(e,s,o={}){let n=o.model||this.defaultModel,r=this._resolveModelId(n),a=this.getModel(n),c=o.maxTokens||a?.maxTokens||8192,{messages:l,system:u}=this.formatMessages(e),d={model:r,messages:l,max_tokens:c,temperature:o.temperature??this.temperature};u&&(d.system=u);let f=this.formatTools(s);f.length>0&&(d.tools=f);let m=await tc.post(`${this.baseUrl}/messages`,d,{timeout:o.timeout||this.timeout,headers:this._getHeaders()});return this.normalizeResponse(m.data)}async stream(e,s,o={}){let n=o.model||this.defaultModel,r=this._resolveModelId(n),a=this.getModel(n),c=o.maxTokens||a?.maxTokens||8192,l=o.onToken||(()=>{}),{messages:u,system:d}=this.formatMessages(e),f={model:r,messages:u,max_tokens:c,temperature:o.temperature??this.temperature,stream:!0};d&&(f.system=d);let m=this.formatTools(s);m.length>0&&(f.tools=m);let h;try{h=await tc.post(`${this.baseUrl}/messages`,f,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal})}catch(p){if(p.name==="CanceledError"||p.name==="AbortError"||p.code==="ERR_CANCELED")throw p;let g=p.response?.data?.error?.message||p.message;throw new Error(`API Error: ${g}`)}return new Promise((p,g)=>{let y="",$=[],w=-1,E="";o.signal&&o.signal.addEventListener("abort",()=>{h.data.destroy(),g(new DOMException("The operation was aborted","AbortError"))},{once:!0}),h.data.on("data",b=>{E+=b.toString();let k=E.split(`
|
|
82
|
+
`);E=k.pop()||"";for(let v of k){let R=v.trim();if(R.startsWith("data: ")){let C=R.slice(6),A;try{A=JSON.parse(C)}catch{continue}switch(A.type){case"content_block_start":{let j=A.content_block;j?.type==="tool_use"&&(w=$.length,$.push({id:j.id,name:j.name,inputJson:""}));break}case"content_block_delta":{let j=A.delta;j?.type==="text_delta"&&j.text&&(l(j.text),y+=j.text),j?.type==="input_json_delta"&&j.partial_json!==void 0&&w>=0&&($[w].inputJson+=j.partial_json);break}case"content_block_stop":w=-1;break;case"message_stop":p({content:y,tool_calls:this._buildToolCalls($)});return}}}}),h.data.on("error",b=>{o.signal?.aborted||g(new Error(`Stream error: ${b.message}`))}),h.data.on("end",()=>{p({content:y,tool_calls:this._buildToolCalls($)})})})}normalizeResponse(e){let s="",o=[];for(let n of e.content||[])n.type==="text"?s+=n.text:n.type==="tool_use"&&o.push({id:n.id,function:{name:n.name,arguments:n.input}});return{content:s,tool_calls:o}}_buildToolCalls(e){return e.filter(s=>s.name).map(s=>{let o={};if(s.inputJson)try{o=JSON.parse(s.inputJson)}catch{o=s.inputJson}return{id:s.id||`anthropic-${Date.now()}`,function:{name:s.name,arguments:o}}})}};sc.exports={AnthropicProvider:mr,ANTHROPIC_MODELS:nc}});var cc=q((Jb,ac)=>{var rc=require("axios"),{BaseProvider:Hp}=pn(),{serializeMessage:Xb}=lt(),ic={"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}},hr=class extends Hp{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||ic,defaultModel:e.defaultModel||"gemini-2.5-flash",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("GEMINI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let s=[];for(let o of e){if(this._messageFormatCache.has(o)){s.push(this._messageFormatCache.get(o));continue}let n=this._getMessageCacheKey(o);if(this._messageStringCache.has(n)){let a=this._messageStringCache.get(n);this._messageFormatCache.set(o,a),s.push(a);continue}let r=this._formatSingleMessage(o);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(n,r),this._messageFormatCache.set(o,r),s.push(r)}return{messages:s}}_getMessageCacheKey(e){let s=e.role||"",o=typeof e.content=="string"?e.content.substring(0,100):"",n=e.tool_calls?e.tool_calls.length:0;return`${s}:${o.length}:${n}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||"",tool_calls:e.tool_calls.map(s=>({id:s.id||`call-${Date.now()}`,type:"function",function:{name:s.function.name,arguments:typeof s.function.arguments=="string"?s.function.arguments:JSON.stringify(s.function.arguments)}}))};if(e.role==="tool")return{role:"tool",content:typeof e.content=="string"?e.content:JSON.stringify(e.content),tool_call_id:e.tool_call_id};if(e.role==="user"&&Array.isArray(e.content)){let s=[];for(let o of e.content)if(o.type==="text")s.push({type:"text",text:o.text??""});else if(o.type==="image"&&o.data){let n=o.data.startsWith("data:")?o.data:`data:${o.media_type||"image/png"};base64,${o.data}`;s.push({type:"image_url",image_url:{url:n,detail:"auto"}})}return{role:"user",content:s}}return{role:e.role,content:e.content}}async chat(e,s,o={}){let n=o.model||this.defaultModel,r=this.getModel(n),a=o.maxTokens||r?.maxTokens||8192,{messages:c}=this.formatMessages(e),l={model:n,messages:c,max_tokens:a,temperature:o.temperature??this.temperature};s&&s.length>0&&(l.tools=s);let u=await rc.post(`${this.baseUrl}/chat/completions`,l,{timeout:o.timeout||this.timeout,headers:this._getHeaders()});return this.normalizeResponse(u.data)}async stream(e,s,o={}){let n=o.model||this.defaultModel,r=this.getModel(n),a=o.maxTokens||r?.maxTokens||8192,c=o.onToken||(()=>{}),{messages:l}=this.formatMessages(e),u={model:n,messages:l,max_tokens:a,temperature:o.temperature??this.temperature,stream:!0};s&&s.length>0&&(u.tools=s);let d;try{d=await rc.post(`${this.baseUrl}/chat/completions`,u,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let m=f.response?.data?.error?.message||f.message;throw new Error(`API Error: ${m}`)}return new Promise((f,m)=>{let h="",p={},g="";o.signal&&o.signal.addEventListener("abort",()=>{d.data.destroy(),m(new DOMException("The operation was aborted","AbortError"))},{once:!0}),d.data.on("data",y=>{g+=y.toString();let $=g.split(`
|
|
83
|
+
`);g=$.pop()||"";for(let w of $){let E=w.trim();if(!E||!E.startsWith("data: "))continue;let b=E.slice(6);if(b==="[DONE]"){f({content:h,tool_calls:this._buildToolCalls(p)});return}let k;try{k=JSON.parse(b)}catch{continue}let v=k.choices?.[0]?.delta;if(v&&(v.content&&(c(v.content),h+=v.content),v.tool_calls))for(let R of v.tool_calls){let C=R.index??0;p[C]||(p[C]={id:R.id||"",name:"",arguments:""}),R.id&&(p[C].id=R.id),R.function?.name&&(p[C].name+=R.function.name),R.function?.arguments&&(p[C].arguments+=R.function.arguments)}}}),d.data.on("error",y=>{o.signal?.aborted||m(new Error(`Stream error: ${y.message}`))}),d.data.on("end",()=>{f({content:h,tool_calls:this._buildToolCalls(p)})})})}normalizeResponse(e){let s=e.choices?.[0]?.message||{},o=(s.tool_calls||[]).map(n=>({id:n.id,function:{name:n.function.name,arguments:n.function.arguments}}));return{content:s.content||"",tool_calls:o}}_buildToolCalls(e){return Object.values(e).filter(s=>s.name).map(s=>({id:s.id||`call-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,function:{name:s.name,arguments:s.arguments}}))}};ac.exports={GeminiProvider:hr,GEMINI_MODELS:ic}});var dc=q((Vb,uc)=>{var js=require("axios"),{BaseProvider:Gp}=pn(),lc="http://localhost:11434",gr=class extends Gp{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||lc,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 js.get(`${this.baseUrl}/api/tags`,{timeout:5e3})).data?.models||[];this.models={};for(let o of s){let n=o.name||o.model;if(!n)continue;let r=n.replace(/:latest$/,""),a=32768;try{let c=await js.post(`${this.baseUrl}/api/show`,{name:n},{timeout:5e3}),l=c.data?.model_info||c.data?.details||{};a=l["general.context_length"]||l["llama.context_length"]||this._parseContextFromModelfile(c.data?.modelfile)||32768}catch{}this.models[r]={id:r,name:o.name,maxTokens:Math.min(8192,Math.floor(a*.1)),contextWindow:a}}!this.defaultModel&&Object.keys(this.models).length>0&&(this.defaultModel=Object.keys(this.models)[0]),this._modelsLoaded=!0}catch{this.models={},this._modelsLoaded=!1}return this.models}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}_formatMessages(e){return e.map(s=>{if(s.role==="user"&&Array.isArray(s.content)){let o=[],n=[];for(let a of s.content)a.type==="text"?o.push(a.text??""):a.type==="image"&&a.data&&n.push(a.data);let r={role:"user",content:o.join(`
|
|
84
|
+
`)};return n.length>0&&(r.images=n),r}return s})}async chat(e,s,o={}){this._modelsLoaded||await this.loadModels();let n=o.model||this.defaultModel;if(!n)throw new Error("No local model available. Is Ollama running?");let r=await js.post(`${this.baseUrl}/api/chat`,{model:n,messages:this._formatMessages(e),tools:s&&s.length>0?s:void 0,stream:!1,options:{temperature:o.temperature??this.temperature,num_predict:o.maxTokens||8192}},{timeout:o.timeout||this.timeout});return this.normalizeResponse(r.data)}async stream(e,s,o={}){this._modelsLoaded||await this.loadModels();let n=o.model||this.defaultModel;if(!n)throw new Error("No local model available. Is Ollama running?");let r=o.onToken||(()=>{}),a;try{a=await js.post(`${this.baseUrl}/api/chat`,{model:n,messages:this._formatMessages(e),tools:s&&s.length>0?s:void 0,stream:!0,options:{temperature:o.temperature??this.temperature,num_predict:o.maxTokens||8192}},{timeout:o.timeout||this.timeout,responseType:"stream",signal:o.signal})}catch(c){if(c.name==="CanceledError"||c.name==="AbortError"||c.code==="ERR_CANCELED")throw c;let l=c.response?.data?.error||c.message;throw new Error(`API Error: ${l}`)}return new Promise((c,l)=>{let u="",d=[],f="";o.signal&&o.signal.addEventListener("abort",()=>{a.data.destroy(),l(new DOMException("The operation was aborted","AbortError"))},{once:!0}),a.data.on("data",m=>{f+=m.toString();let h=f.split(`
|
|
85
|
+
`);f=h.pop()||"";for(let p of h){if(!p.trim())continue;let g;try{g=JSON.parse(p)}catch{continue}if(g.message?.content&&(r(g.message.content),u+=g.message.content),g.message?.tool_calls&&(d=d.concat(g.message.tool_calls)),g.done){c({content:u,tool_calls:this._normalizeToolCalls(d)});return}}}),a.data.on("error",m=>{o.signal?.aborted||l(new Error(`Stream error: ${m.message}`))}),a.data.on("end",()=>{if(f.trim())try{let m=JSON.parse(f);m.message?.content&&(r(m.message.content),u+=m.message.content),m.message?.tool_calls&&(d=d.concat(m.message.tool_calls))}catch{}c({content:u,tool_calls:this._normalizeToolCalls(d)})})})}normalizeResponse(e){let s=e.message||{};return{content:s.content||"",tool_calls:this._normalizeToolCalls(s.tool_calls||[])}}_parseContextFromModelfile(e){if(!e)return null;let s=e.match(/PARAMETER\s+num_ctx\s+(\d+)/i);return s?parseInt(s[1],10):null}_normalizeToolCalls(e){return e.map((s,o)=>({id:s.id||`local-${Date.now()}-${o}`,function:{name:s.function?.name||s.name||"unknown",arguments:s.function?.arguments||s.arguments||{}}}))}};uc.exports={LocalProvider:gr,DEFAULT_LOCAL_URL:lc}});var It=q((Qb,pc)=>{"use strict";var Je=require("fs"),fc=require("path");function Kp(t){if(!t||isNaN(t))return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function zp(t){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}catch{let e=Date.now()+t;for(;Date.now()<e;);}}function Yp(t,e){let s=fc.dirname(t),o=fc.join(s,`.nex-tmp.${process.pid}.${Date.now()}`);try{Je.existsSync(s)||Je.mkdirSync(s,{recursive:!0}),Je.writeFileSync(o,e,"utf-8"),Je.renameSync(o,t)}catch(n){try{Je.unlinkSync(o)}catch{}throw n}}function Xp(t,e,{timeout:s=5e3,retryMs:o=50}={}){let n=t+".lock",r=Date.now()+s;for(;;){let a=-1;try{a=Je.openSync(n,"wx"),Je.writeSync(a,Buffer.from(String(process.pid))),Je.closeSync(a),a=-1;try{return e()}finally{try{Je.unlinkSync(n)}catch{}}}catch(c){if(a!==-1)try{Je.closeSync(a)}catch{}if(c.code!=="EEXIST")throw c;try{let l=Je.readFileSync(n,"utf-8").trim(),u=parseInt(l,10);if(!Kp(u)){try{Je.unlinkSync(n)}catch{}continue}}catch(l){if(l.code&&l.code!=="ENOENT")throw l;continue}if(Date.now()>=r){try{Je.unlinkSync(n)}catch{}return e()}zp(o)}}}pc.exports={atomicWrite:Yp,withFileLockSync:Xp}});var $n=q((Zb,bc)=>{var gn=require("fs"),$r=require("path"),{atomicWrite:Jp,withFileLockSync:Vp}=It(),mc={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:{}},Ds=[],Pt={};function Qp(t,e,s,o){if(Ds.push({provider:t,model:e,input:s,output:o}),Pt[t]!==void 0){let n=yc(t);n.allowed||process.stderr.write(`\x1B[33m\u26A0 Budget limit reached for ${t}: $${n.spent.toFixed(2)} / $${n.limit.toFixed(2)}\x1B[0m
|
|
86
|
+
`)}}function yr(t,e){let s=mc[t];return s?s[e]||{input:0,output:0}:{input:0,output:0}}function hc(t){let e=yr(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function gc(){let t={};for(let r of Ds){let a=`${r.provider}:${r.model}`;t[a]||(t[a]={provider:r.provider,model:r.model,input:0,output:0}),t[a].input+=r.input,t[a].output+=r.output}let e=Object.values(t).map(r=>({...r,cost:hc(r)})),s=e.reduce((r,a)=>r+a.cost,0),o=e.reduce((r,a)=>r+a.input,0),n=e.reduce((r,a)=>r+a.output,0);return{totalCost:s,totalInput:o,totalOutput:n,breakdown:e}}function Zp(){let{totalCost:t,totalInput:e,totalOutput:s,breakdown:o}=gc();if(o.length===0)return"No token usage recorded this session.";let n=[];n.push("Session Token Usage:"),n.push("");for(let r of o){let a=r.cost>0?`$${r.cost.toFixed(4)}`:"free";n.push(` ${r.provider}:${r.model}`),n.push(` Input: ${r.input.toLocaleString()} tokens`),n.push(` Output: ${r.output.toLocaleString()} tokens`),n.push(` Cost: ${a}`)}return n.push(""),n.push(` Total: ${e.toLocaleString()} in + ${s.toLocaleString()} out = $${t.toFixed(4)}`),n.join(`
|
|
87
|
+
`)}function em(t,e,s,o){let n=yr(t,e),r=(s*n.input+o*n.output)/1e6;return r<=0?"":`[~$${r.toFixed(4)}]`}function tm(){Ds=[]}function nm(t,e){Pt[t]=e}function sm(t){delete Pt[t]}function om(){return{...Pt}}function $c(t){let e=0;for(let s of Ds)s.provider===t&&(e+=hc(s));return e}function yc(t){let e=$c(t),s=Pt[t];if(s===void 0)return{allowed:!0,spent:e,limit:null,remaining:null};let o=Math.max(0,s-e);return{allowed:e<s,spent:e,limit:s,remaining:o}}function wc(){let t=$r.join(process.cwd(),".nex","config.json");if(gn.existsSync(t))try{let e=JSON.parse(gn.readFileSync(t,"utf-8"));e.costLimits&&typeof e.costLimits=="object"&&(Pt={...e.costLimits})}catch{}}function rm(){let t=$r.join(process.cwd(),".nex"),e=$r.join(t,"config.json");gn.existsSync(t)||gn.mkdirSync(t,{recursive:!0}),Vp(e,()=>{let s={};if(gn.existsSync(e))try{s=JSON.parse(gn.readFileSync(e,"utf-8"))}catch{s={}}s.costLimits=Pt,Jp(e,JSON.stringify(s,null,2))})}function im(){Pt={}}wc();bc.exports={PRICING:mc,trackUsage:Qp,getSessionCosts:gc,formatCosts:Zp,formatCostHint:em,resetCosts:tm,getPricing:yr,setCostLimit:nm,removeCostLimit:sm,getCostLimits:om,getProviderSpend:$c,checkBudget:yc,loadCostLimits:wc,saveCostLimits:rm,resetCostLimits:im}});var xc=q((e_,kc)=>{"use strict";var am=new Set(["read_file","grep","glob","search_files","list_directory"]),cm=new Set(["write_file","edit_file","patch_file"]),lm=new Set(["bash"]),um=new Set(["web_search","web_fetch","perplexity_search"]);function _c(t,e){let s=0,o=0,n=0,r=0,a=0;for(let[c,l]of t)a+=l,am.has(c)&&(s+=l),cm.has(c)&&(o+=l),lm.has(c)&&(n+=l),um.has(c)&&(r+=l);return a===0?`Phase ${e}`:r/a>.5?"Research":s/a>.5?"Exploration":o/a>.3?"Implementation":n/a>.3&&o/a<.15?"Verification":`Phase ${e}`}var wr=class{constructor(e){this._N=e,this._disabled=e<=0,this._phaseNum=0,this._stepsThisPhase=0,this._phaseCounts=new Map,this._phaseStart=Date.now()}record(e,s,o,n){if(this._disabled)return null;this._stepsThisPhase++;for(let a of s)this._phaseCounts.set(a,(this._phaseCounts.get(a)||0)+1);if(this._stepsThisPhase<this._N)return null;this._phaseNum++;let r={phaseNum:this._phaseNum,phaseName:_c(this._phaseCounts,this._phaseNum),stepCount:this._stepsThisPhase,toolCounts:new Map(this._phaseCounts),elapsed:Date.now()-this._phaseStart,filesRead:new Set(o),filesModified:new Set(n)};return this._stepsThisPhase=0,this._phaseCounts=new Map,this._phaseStart=Date.now(),r}};kc.exports={MilestoneTracker:wr,_phaseName:_c}});var qs=q((t_,vc)=>{var Fn=be(),dm={"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 fm(){return Fn.getActiveModel()}function pm(t){return Fn.setActiveModel(t)}function mm(){return Fn.getModelNames()}function hm(t){if(!t)return null;if(typeof t=="object")return t;try{return JSON.parse(t)}catch{}try{let o=t.replace(/,\s*([}\]])/g,"$1").replace(/'/g,'"');return JSON.parse(o)}catch{}let e=t.match(/\{[\s\S]*\}/);if(e)try{return JSON.parse(e[0])}catch{}try{let o=t.replace(/(\{|,)\s*([a-zA-Z_]\w*)\s*:/g,'$1"$2":');return JSON.parse(o)}catch{}let s=t.match(/```(?:json)?\s*([\s\S]*?)```/);if(s)try{return JSON.parse(s[1].trim())}catch{}return null}async function gm(t,e){let{C:s}=we(),{Spinner:o}=we(),n=new o("Thinking...");n.start();let r=!0,a="";try{let c=await Fn.callStream(t,e,{onToken:l=>{r&&(n.stop(),process.stdout.write(`${s.blue}`),r=!1),process.stdout.write(l),a+=l}});return r?n.stop():process.stdout.write(`${s.reset}
|
|
88
|
+
`),c}catch(c){throw n.stop(),c}}async function $m(t,e){return Fn.callChat(t,e)}vc.exports={MODELS:dm,getActiveModel:fm,setActiveModel:pm,getModelNames:mm,callOllamaStream:gm,callOllama:$m,parseToolArgs:hm}});var Tc=q((s_,Ec)=>{var Fs=require("path"),{C:T}=we(),{T:br,isDark:n_}=Ht(),{confirm:ym,getAutoConfirm:wm}=Ie(),Sc=2e3;function Un(t,e){let s=t.split(`
|
|
89
89
|
`),o=e.split(`
|
|
90
|
-
`),n=[],r=s.length,
|
|
91
|
-
${T.bold}${T.cyan} Diff: ${t}${T.reset}`);let n=Un(e,s),r=[];if(n.forEach((l,u)=>{l.type!=="same"&&r.push(u)}),r.length===0){console.log(`${T.gray} (no changes)${T.reset}`);return}let
|
|
92
|
-
${T.bold}${T.cyan} File exists \u2014 showing changes: ${t}${T.reset}`);let o=Un(e,s),n=0;for(let
|
|
90
|
+
`),n=[],r=s.length,a=o.length;if(r>Sc||a>Sc){for(let f of s)n.push({type:"remove",line:f});for(let f of o)n.push({type:"add",line:f});return n}let c=Array.from({length:r+1},()=>new Array(a+1).fill(0));for(let f=1;f<=r;f++)for(let m=1;m<=a;m++)s[f-1]===o[m-1]?c[f][m]=c[f-1][m-1]+1:c[f][m]=Math.max(c[f-1][m],c[f][m-1]);let l=r,u=a,d=[];for(;l>0||u>0;)l>0&&u>0&&s[l-1]===o[u-1]?(d.unshift({type:"same",line:s[l-1]}),l--,u--):u>0&&(l===0||c[l][u-1]>=c[l-1][u])?(d.unshift({type:"add",line:o[u-1]}),u--):(d.unshift({type:"remove",line:s[l-1]}),l--);return d}function bm(t,e,s,o=3){console.log(`
|
|
91
|
+
${T.bold}${T.cyan} Diff: ${t}${T.reset}`);let n=Un(e,s),r=[];if(n.forEach((l,u)=>{l.type!=="same"&&r.push(u)}),r.length===0){console.log(`${T.gray} (no changes)${T.reset}`);return}let a=Math.max(0,r[0]-o),c=Math.min(n.length,r[r.length-1]+o+1);a>0&&console.log(`${T.gray} ...${T.reset}`);for(let l=a;l<c;l++){let u=n[l];switch(u.type){case"remove":console.log(`${T.red} - ${u.line}${T.reset}`);break;case"add":console.log(`${T.green} + ${u.line}${T.reset}`);break;default:console.log(`${T.gray} ${u.line}${T.reset}`)}}c<n.length&&console.log(`${T.gray} ...${T.reset}`),console.log()}function _m(t,e,s){console.log(`
|
|
92
|
+
${T.bold}${T.cyan} File exists \u2014 showing changes: ${t}${T.reset}`);let o=Un(e,s),n=0;for(let a of o)a.type!=="same"&&n++;if(n===0){console.log(`${T.gray} (identical content)${T.reset}`);return}let r=0;for(let a of o){if(r>=30){console.log(`${T.gray} ...(${n-r} more changes)${T.reset}`);break}switch(a.type){case"remove":console.log(`${T.red} - ${a.line}${T.reset}`),r++;break;case"add":console.log(`${T.green} + ${a.line}${T.reset}`),r++;break;default:r>0&&console.log(`${T.gray} ${a.line}${T.reset}`)}}console.log()}function km(t,e){console.log(`
|
|
93
93
|
${T.bold}${T.cyan} New file: ${t}${T.reset}`);let s=e.split(`
|
|
94
|
-
`),o=s.slice(0,20);for(let n of o)console.log(`${T.green} + ${n}${T.reset}`);s.length>20&&console.log(`${T.gray} ...+${s.length-20} more lines${T.reset}`),console.log()}async function
|
|
95
|
-
${T.bold}${T.cyan} Side-by-side: ${t}${T.reset}`),console.log(` ${T.dim}${"\u2500".repeat(r)}\u252C${"\u2500".repeat(r)}${T.reset}`);let
|
|
96
|
-
`)}function
|
|
94
|
+
`),o=s.slice(0,20);for(let n of o)console.log(`${T.green} + ${n}${T.reset}`);s.length>20&&console.log(`${T.gray} ...+${s.length-20} more lines${T.reset}`),console.log()}async function xm(t){return wm()?!0:ym(` ${t}?`)}function vm(t,e,s,o){let n=o||process.stdout.columns||80,r=Math.floor((n-3)/2);console.log(`
|
|
95
|
+
${T.bold}${T.cyan} Side-by-side: ${t}${T.reset}`),console.log(` ${T.dim}${"\u2500".repeat(r)}\u252C${"\u2500".repeat(r)}${T.reset}`);let a=Un(e,s),c=[],l=0;for(;l<a.length;)if(a[l].type==="same")c.push({left:a[l].line,right:a[l].line,type:"same"}),l++;else if(a[l].type==="remove"){let h=[];for(;l<a.length&&a[l].type==="remove";)h.push(a[l].line),l++;let p=[];for(;l<a.length&&a[l].type==="add";)p.push(a[l].line),l++;let g=Math.max(h.length,p.length);for(let y=0;y<g;y++)c.push({left:y<h.length?h[y]:"",right:y<p.length?p[y]:"",type:"changed"})}else a[l].type==="add"&&(c.push({left:"",right:a[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(` ${T.gray}(no changes)${T.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(` ${T.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${T.reset}`);for(let h=d;h<f;h++){let p=c[h];if(p.type==="same")console.log(` ${T.gray}${m(p.left,r)}${T.reset}\u2502${T.gray}${m(p.right,r)}${T.reset}`);else{let g=p.left?`${T.red}${m(p.left,r)}${T.reset}`:`${m("",r)}`,y=p.right?`${T.green}${m(p.right,r)}${T.reset}`:`${m("",r)}`;console.log(` ${g}\u2502${y}`)}}f<c.length&&console.log(` ${T.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${T.reset}`),console.log(` ${T.dim}${"\u2500".repeat(r)}\u2534${"\u2500".repeat(r)}${T.reset}
|
|
96
|
+
`)}function Sm(t,e,s,o={}){let n=o.label||"Update",r=o.context||3,a=o.annotations||[],c=Fs.isAbsolute(t)?Fs.relative(process.cwd(),t):t,l=Un(e,s),u=1,d=1;for(let v of l)v.type==="same"?(v.oldLine=u++,v.newLine=d++):v.type==="remove"?(v.oldLine=u++,v.newLine=null):(v.oldLine=null,v.newLine=d++);let f=0,m=0;for(let v of l)v.type==="add"?f++:v.type==="remove"&&m++;if(console.log(`
|
|
97
97
|
${T.green}\u25CF${T.reset} ${T.bold}${n}(${c})${T.reset}`),f===0&&m===0){console.log(` ${T.dim}\u2514 (no changes)${T.reset}
|
|
98
|
-
`);return}let h=[];if(f>0&&h.push(`Added ${f} line${f!==1?"s":""}`),m>0&&h.push(`removed ${m} line${m!==1?"s":""}`),
|
|
98
|
+
`);return}let h=[];if(f>0&&h.push(`Added ${f} line${f!==1?"s":""}`),m>0&&h.push(`removed ${m} line${m!==1?"s":""}`),a.length>0){let v=a.filter(j=>j.severity==="error").length,R=a.filter(j=>j.severity==="warn").length,C=a.filter(j=>j.severity==="info").length,A=[];v>0&&A.push(`${T.red}${v} error${v!==1?"s":""}${T.dim}`),R>0&&A.push(`${T.yellow}${R} warning${R!==1?"s":""}${T.dim}`),C>0&&A.push(`${T.cyan}${C} info${C!==1?"s":""}${T.dim}`),h.push(`found ${A.join(", ")}`)}console.log(` ${T.dim}\u2514 ${h.join(", ")}${T.reset}`);let g=[];l.forEach((v,R)=>{v.type!=="same"&&g.push(R)});let y=[],$=null,w=null;for(let v of g){let R=Math.max(0,v-r),C=Math.min(l.length-1,v+r);$===null?($=R,w=C):(R<=w+1||(y.push([$,w]),$=R),w=C)}$!==null&&y.push([$,w]);let E=" ",b=process.stdout.columns||120;function k(v,R,C){let A=C.replace(/\x1b\[[0-9;]*m/g,""),j=C+" ".repeat(Math.max(0,b-A.length));return`${v}${R}${j}${T.reset}`}for(let v=0;v<y.length;v++){v>0&&console.log(`${E}${T.dim}\xB7\xB7\xB7${T.reset}`);let[R,C]=y[v];for(let A=R;A<=C;A++){let j=l[A],Q=j.newLine!=null?j.newLine:j.oldLine,X=String(Q).padStart(4),H=j.type!=="remove"?a.filter(G=>G.line===j.newLine):[];j.type==="remove"?console.log(k(br.diff_rem_bg,T.red,`${E}${X} - ${j.line}`)):j.type==="add"?console.log(k(br.diff_add_bg,T.green,`${E}${X} + ${j.line}`)):console.log(`${E}${T.dim}${X} ${T.reset}${j.line}`);for(let G of H){let U=T.cyan,pe="\u2139";G.severity==="error"?(U=T.red,pe="\u2716"):G.severity==="warn"&&(U=T.yellow,pe="\u26A0"),console.log(`${E} ${U}${pe} ${G.message}${T.reset}`)}}}console.log()}function Em(t,e,s={}){let o=Fs.isAbsolute(t)?Fs.relative(process.cwd(),t):t,n=e.split(`
|
|
99
99
|
`),r=s.annotations||[];console.log(`
|
|
100
|
-
${T.green}\u25CF${T.reset} ${T.bold}Create(${o})${T.reset}`);let
|
|
101
|
-
`).filter(Boolean).map(e=>{let s=e.substring(0,2).trim(),o=e.substring(3);return{status:s,file:o}})}catch{return[]}}async function Ws(t=!1){return await _r(`git diff ${t?"--cached":""}`)||""}async function xr(){return(await kr()).map(e=>e.file)}async function
|
|
102
|
-
`);for(let f of d)f.startsWith("+")&&!f.startsWith("+++")&&n++,f.startsWith("-")&&!f.startsWith("---")&&r++}else n=t.length;let
|
|
100
|
+
${T.green}\u25CF${T.reset} ${T.bold}Create(${o})${T.reset}`);let a=[`${n.length} line${n.length!==1?"s":""}`];if(r.length>0){let f=r.filter(g=>g.severity==="error").length,m=r.filter(g=>g.severity==="warn").length,h=r.filter(g=>g.severity==="info").length,p=[];f>0&&p.push(`${T.red}${f} error${f!==1?"s":""}${T.dim}`),m>0&&p.push(`${T.yellow}${m} warning${m!==1?"s":""}${T.dim}`),h>0&&p.push(`${T.cyan}${h} info${h!==1?"s":""}${T.dim}`),a.push(`found ${p.join(", ")}`)}console.log(` ${T.dim}\u2514 ${a.join(", ")}${T.reset}`);let l=" ",u=process.stdout.columns||120,d=Math.min(n.length,20);for(let f=0;f<d;f++){let m=String(f+1).padStart(4),h=f+1,p=r.filter(w=>w.line===h),g=`${l}${m} + ${n[f]}`,y=g.replace(/\x1b\[[0-9;]*m/g,""),$=g+" ".repeat(Math.max(0,u-y.length));console.log(`${br.diff_add_bg}${T.green}${$}${T.reset}`);for(let w of p){let E=T.cyan,b="\u2139";w.severity==="error"?(E=T.red,b="\u2716"):w.severity==="warn"&&(E=T.yellow,b="\u26A0"),console.log(`${l} ${E}${b} ${w.message}${T.reset}`)}}n.length>20&&console.log(`${l}${T.dim} ...+${n.length-20} more lines${T.reset}`),console.log()}Ec.exports={diffLines:Un,showEditDiff:bm,showWriteDiff:_m,showNewFilePreview:km,confirmFileChange:xm,showSideBySideDiff:vm,showClaudeDiff:Sm,showClaudeNewFile:Em}});var Xt=q((o_,Ac)=>{var Rc=require("util").promisify(require("child_process").exec),Tm=require("util").promisify(require("child_process").execFile),{C:$e}=we();async function _r(t){try{let{stdout:e}=await Rc(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function Us(...t){try{let{stdout:e}=await Tm("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function Rm(){return await _r("git rev-parse --is-inside-work-tree")==="true"}async function Cm(){return await _r("git branch --show-current")}async function kr(){try{let{stdout:t}=await Rc("git status --porcelain",{cwd:process.cwd(),timeout:3e4});return!t||!t.trim()?[]:t.split(`
|
|
101
|
+
`).filter(Boolean).map(e=>{let s=e.substring(0,2).trim(),o=e.substring(3);return{status:s,file:o}})}catch{return[]}}async function Ws(t=!1){return await _r(`git diff ${t?"--cached":""}`)||""}async function xr(){return(await kr()).map(e=>e.file)}async function Cc(){let t=await xr();if(t.length===0)return null;let e=await Ws(),o=await Ws(!0)||e,n=0,r=0;if(o){let d=o.split(`
|
|
102
|
+
`);for(let f of d)f.startsWith("+")&&!f.startsWith("+++")&&n++,f.startsWith("-")&&!f.startsWith("---")&&r++}else n=t.length;let a="chore",c=t.join(" ").toLowerCase();c.includes("test")?a="test":c.includes("readme")||c.includes("doc")?a="docs":n>r*2?a="feat":r>n?a="refactor":a="fix";let l=t.slice(0,3).map(d=>d.split("/").pop());return{summary:`${a}: update ${l.join(", ")}${t.length>3?` (+${t.length-3} more)`:""}`,type:a,files:t,stats:{additions:n,deletions:r}}}async function Am(t){let s=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await Us("checkout","-b",s)!==null?s:null}async function Om(t){return await Us("add","-A"),await Us("commit","-m",t)?await Us("rev-parse","--short","HEAD"):null}async function Nm(){let t=await Cc();if(!t)return`${$e.dim}No changes${$e.reset}`;let e=[];e.push(`
|
|
103
103
|
${$e.bold}${$e.cyan}Git Diff Summary:${$e.reset}`),e.push(` ${$e.green}+${t.stats.additions}${$e.reset} ${$e.red}-${t.stats.deletions}${$e.reset} in ${t.files.length} file(s)`),e.push(`
|
|
104
104
|
${$e.bold}${$e.cyan}Files:${$e.reset}`);for(let s of t.files.slice(0,20))e.push(` ${$e.dim}${s}${$e.reset}`);return t.files.length>20&&e.push(` ${$e.dim}...+${t.files.length-20} more${$e.reset}`),e.push(`
|
|
105
105
|
${$e.bold}${$e.cyan}Suggested message:${$e.reset}`),e.push(` ${$e.cyan}${t.summary}${$e.reset}
|
|
106
106
|
`),e.join(`
|
|
107
|
-
`)}async function
|
|
107
|
+
`)}async function Mm(){return(await kr()).filter(e=>e.status==="UU"||e.status==="AA"||e.status==="DD")}async function Im(){let t=await xr();if(t.length===0)return"";let e=[`CHANGED FILES (${t.length}):`];for(let o of t.slice(0,10))e.push(` ${o}`);let s=await Ws();if(s){let o=s.length>5e3?s.substring(0,5e3)+`
|
|
108
108
|
...(truncated)`:s;e.push(`
|
|
109
109
|
DIFF:
|
|
110
110
|
${o}`)}return e.join(`
|
|
111
|
-
`)}
|
|
112
|
-
`).map(s=>{let o=s.match(/^stash@\{(\d+)\}:\s+(?:WIP on [^:]+:\s+\S+\s+|On \S+:\s+)(.*)/);if(!o)return null;let n=o[2].trim();return n.startsWith(Bs)?{index:parseInt(o[1],10),label:n,shortName:n.replace(`${Bs}-`,""),date:s}:null}).filter(Boolean):[]}catch{return[]}}function
|
|
111
|
+
`)}Ac.exports={isGitRepo:Rm,getCurrentBranch:Cm,getStatus:kr,getDiff:Ws,getChangedFiles:xr,analyzeDiff:Cc,createBranch:Am,commit:Om,formatDiffSummary:Nm,getDiffContext:Im,getMergeConflicts:Mm}});var _t=q((i_,Lc)=>{var Re=require("fs").promises,r_=require("fs"),ot=require("path"),Pm=require("crypto"),{execSync:Wn}=require("child_process"),Lm=100*1024,Mc=50,Fe=[],yn=[];function jm(t,e,s,o){for(Fe.push({tool:t,filePath:e,oldContent:s,newContent:o,timestamp:Date.now()});Fe.length>Mc;)Fe.shift();yn.length=0,Ic(Fe[Fe.length-1]).catch(()=>{})}async function Dm(){if(Fe.length===0)return null;let t=Fe.pop();if(t.oldContent===null)try{await Re.unlink(t.filePath)}catch{}else await Re.writeFile(t.filePath,t.oldContent,"utf-8");return yn.push(t),{tool:t.tool,filePath:t.filePath,wasCreated:t.oldContent===null}}async function qm(){if(yn.length===0)return null;let t=yn.pop();return await Re.writeFile(t.filePath,t.newContent,"utf-8"),Fe.push(t),{tool:t.tool,filePath:t.filePath}}function Fm(t=10){return Fe.slice(-t).reverse().map(e=>({tool:e.tool,filePath:e.filePath,timestamp:e.timestamp}))}function Um(){return Fe.length}function Wm(){return yn.length}function Bm({diskToo:t=!0}={}){if(Fe.length=0,yn.length=0,t){let e=Hs();Re.readdir(e).then(s=>{for(let o of s)o.endsWith(".json")&&Re.unlink(ot.join(e,o)).catch(()=>{})}).catch(()=>{})}}function Hs(){return ot.join(process.cwd(),".nex","history")}async function Oc(t,e){if(t==null)return{inline:!0,content:t};if(Buffer.byteLength(t,"utf-8")<=Lm)return{inline:!0,content:t};let s=Pm.createHash("sha256").update(t,"utf-8").digest("hex"),o=ot.join(e,"blobs");return await Re.mkdir(o,{recursive:!0}),await Re.writeFile(ot.join(o,s),t,"utf-8"),{inline:!1,hash:s}}async function Ic(t){let e=Hs();await Re.mkdir(e,{recursive:!0});let s=ot.basename(t.filePath).replace(/[^a-zA-Z0-9]/g,"-"),o=`${t.timestamp}-${s}.json`,n=await Oc(t.oldContent,e),r=await Oc(t.newContent,e),a={tool:t.tool,filePath:t.filePath,timestamp:t.timestamp,oldContent:n.inline?{inline:!0,content:n.content}:{inline:!1,hash:n.hash},newContent:r.inline?{inline:!0,content:r.content}:{inline:!1,hash:r.hash}};await Re.writeFile(ot.join(e,o),JSON.stringify(a),"utf-8")}async function Nc(t,e){if(!t)return null;if(t.inline)return t.content;let s=ot.join(e,"blobs",t.hash);return Re.readFile(s,"utf-8")}async function Hm(){let t=Hs(),e;try{e=await Re.readdir(t)}catch{return 0}let s=e.filter(n=>n.endsWith(".json")).sort(),o=0;for(let n of s)try{let r=await Re.readFile(ot.join(t,n),"utf-8"),a=JSON.parse(r),c=await Nc(a.oldContent,t),l=await Nc(a.newContent,t);Fe.push({tool:a.tool,filePath:a.filePath,timestamp:a.timestamp,oldContent:c,newContent:l}),o++}catch{}for(;Fe.length>Mc;)Fe.shift();return o}async function Gm(t=7){let e=Hs(),s;try{s=await Re.readdir(e)}catch{return 0}let o=Date.now()-t*24*60*60*1e3,n=s.filter(u=>u.endsWith(".json")),r=0,a=new Set,c=[];for(let u of n)try{let d=await Re.readFile(ot.join(e,u),"utf-8"),f=JSON.parse(d);f.timestamp<o?(c.push(u),r++):(f.oldContent&&!f.oldContent.inline&&f.oldContent.hash&&a.add(f.oldContent.hash),f.newContent&&!f.newContent.inline&&f.newContent.hash&&a.add(f.newContent.hash))}catch{}for(let u of c)try{await Re.unlink(ot.join(e,u))}catch{}let l=ot.join(e,"blobs");try{let u=await Re.readdir(l);for(let d of u)if(!a.has(d))try{await Re.unlink(ot.join(l,d))}catch{}}catch{}return r}var Bs="nex-snapshot";function Km(t,e=process.cwd()){let s=t?`${Bs}-${t.replace(/[^a-zA-Z0-9_-]/g,"-")}`:`${Bs}-${Date.now()}`;try{return Wn("git status --porcelain",{cwd:e,timeout:1e4}).toString().trim()?(Wn(`git stash push -u -m "${s}"`,{cwd:e,timeout:15e3}),Wn("git stash pop",{cwd:e,timeout:1e4}),{name:s,label:s,ok:!0}):{name:s,label:s,ok:!1,error:"No changes to snapshot (working tree clean)"}}catch(o){return{name:s,label:s,ok:!1,error:o.message}}}function Pc(t=process.cwd()){try{let e=Wn("git stash list",{cwd:t,timeout:1e4}).toString().trim();return e?e.split(`
|
|
112
|
+
`).map(s=>{let o=s.match(/^stash@\{(\d+)\}:\s+(?:WIP on [^:]+:\s+\S+\s+|On \S+:\s+)(.*)/);if(!o)return null;let n=o[2].trim();return n.startsWith(Bs)?{index:parseInt(o[1],10),label:n,shortName:n.replace(`${Bs}-`,""),date:s}:null}).filter(Boolean):[]}catch{return[]}}function zm(t,e=process.cwd()){try{let s=Pc(e);if(s.length===0)return{ok:!1,error:"No snapshots found"};let o;return t===void 0||t==="last"?o=s[0]:typeof t=="number"?o=s.find(n=>n.index===t):o=s.find(n=>n.label===t||n.shortName===t||n.shortName.includes(String(t))),o?(Wn(`git stash apply stash@{${o.index}}`,{cwd:e,timeout:15e3}),{ok:!0,label:o.label}):{ok:!1,error:`Snapshot not found: ${t}`}}catch(s){return{ok:!1,error:s.message}}}Lc.exports={recordChange:jm,undo:Dm,redo:qm,getHistory:Fm,getUndoCount:Um,getRedoCount:Wm,clearHistory:Bm,persistEntry:Ic,loadPersistedHistory:Hm,pruneHistory:Gm,createSnapshot:Km,listSnapshots:Pc,restoreSnapshot:zm}});var Lt=q((a_,Uc)=>{var le=require("fs"),Ue=require("path"),{atomicWrite:Ym,withFileLockSync:Xm}=It(),We=[];function Bn(){return Ue.join(process.cwd(),".nex","skills")}function jc(){return Ue.join(process.cwd(),".nex","config.json")}function Dc(){let t=Bn();return le.existsSync(t)||le.mkdirSync(t,{recursive:!0}),t}function Er(){let t=jc();if(!le.existsSync(t))return[];try{let e=JSON.parse(le.readFileSync(t,"utf-8"));return e.skills&&Array.isArray(e.skills.disabled)?e.skills.disabled:[]}catch{return[]}}function qc(t){let e=jc(),s=Ue.dirname(e);le.existsSync(s)||le.mkdirSync(s,{recursive:!0}),Xm(e,()=>{let o={};if(le.existsSync(e))try{o=JSON.parse(le.readFileSync(e,"utf-8"))}catch{o={}}o.skills||(o.skills={}),o.skills.disabled=t,Ym(e,JSON.stringify(o,null,2))})}function Fc(t,e){let s=[];if(typeof t!="object"||t===null)return{valid:!1,errors:["Module must export an object"]};if(t.name!==void 0&&typeof t.name!="string"&&s.push("name must be a string"),t.description!==void 0&&typeof t.description!="string"&&s.push("description must be a string"),t.instructions!==void 0&&typeof t.instructions!="string"&&s.push("instructions must be a string"),t.commands!==void 0)if(!Array.isArray(t.commands))s.push("commands must be an array");else for(let o=0;o<t.commands.length;o++){let n=t.commands[o];(!n.cmd||typeof n.cmd!="string")&&s.push(`commands[${o}].cmd must be a non-empty string`),n.handler!==void 0&&typeof n.handler!="function"&&s.push(`commands[${o}].handler must be a function`)}if(t.tools!==void 0)if(!Array.isArray(t.tools))s.push("tools must be an array");else for(let o=0;o<t.tools.length;o++){let n=t.tools[o];(!n.function||!n.function.name||typeof n.function.name!="string")&&s.push(`tools[${o}].function.name must be a non-empty string`),n.execute!==void 0&&typeof n.execute!="function"&&s.push(`tools[${o}].execute must be a function`)}return{valid:s.length===0,errors:s}}function vr(t){try{let e=le.readFileSync(t,"utf-8").trim();return e?{name:Ue.basename(t,".md"),type:"prompt",filePath:t,instructions:e,commands:[],tools:[]}:null}catch{return null}}function Sr(t){try{let e=require(t),{valid:s,errors:o}=Fc(e,t);return s?{name:e.name||Ue.basename(t,".js"),type:"script",filePath:t,description:e.description||"",instructions:e.instructions||"",commands:(e.commands||[]).map(r=>({cmd:r.cmd.startsWith("/")?r.cmd:`/${r.cmd}`,desc:r.desc||r.description||"",handler:r.handler||null})),tools:(e.tools||[]).map(r=>({type:r.type||"function",function:{name:r.function.name,description:r.function.description||"",parameters:r.function.parameters||{type:"object",properties:{}}},execute:r.execute||null}))}:(console.error(`Skill validation failed: ${t}
|
|
113
113
|
${o.join(`
|
|
114
|
-
`)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function Tr(){We=[];let t=Er(),e=Bn(),s=[];if(le.existsSync(e))try{s=le.readdirSync(e)}catch{s=[]}for(let n of s){let r=Ue.join(e,n),
|
|
114
|
+
`)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function Tr(){We=[];let t=Er(),e=Bn(),s=[];if(le.existsSync(e))try{s=le.readdirSync(e)}catch{s=[]}for(let n of s){let r=Ue.join(e,n),a;try{a=le.statSync(r)}catch{continue}if(!a.isFile())continue;let c=null;n.endsWith(".md")?c=vr(r):n.endsWith(".js")&&(c=Sr(r)),c&&(c.enabled=!t.includes(c.name),We.push(c))}let o=Ue.join(__dirname,"skills");if(!process.env.NEX_SKIP_BUILTIN_SKILLS&&le.existsSync(o)){let n;try{n=le.readdirSync(o).filter(r=>r.endsWith(".md")||r.endsWith(".js"))}catch{n=[]}for(let r of n){let a=Ue.join(o,r),c=Ue.basename(r,Ue.extname(r));if(We.some(d=>d.name===c))continue;let l;try{l=le.statSync(a)}catch{continue}if(!l.isFile())continue;let u=r.endsWith(".md")?vr(a):Sr(a);u&&(u._builtin=!0,u.enabled=!t.includes(u.name),We.push(u))}}return We}function Jm(){let t=[];for(let e of We)!e.enabled||!e.instructions||t.push(`[Skill: ${e.name}]
|
|
115
115
|
${e.instructions}`);return t.length===0?"":`SKILL INSTRUCTIONS:
|
|
116
116
|
${t.join(`
|
|
117
117
|
|
|
118
|
-
`)}`}function
|
|
118
|
+
`)}`}function Vm(){let t=[];for(let e of We)if(e.enabled)for(let s of e.commands)t.push({cmd:s.cmd,desc:s.desc||`[skill: ${e.name}]`});return t}function Qm(){let t=[];for(let e of We)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 Zm(t,e){if(!t.startsWith("skill_"))return null;let s=t.substring(6);for(let o of We)if(o.enabled){for(let n of o.tools)if(n.function.name===s&&n.execute)try{let r=await n.execute(e);return typeof r=="string"?r:JSON.stringify(r)}catch(r){return`ERROR: Skill tool '${s}' failed: ${r.message}`}}return`ERROR: Skill tool '${s}' not found`}function eh(t){let[e,...s]=t.split(/\s+/),o=s.join(" ").trim();for(let n of We)if(n.enabled){for(let r of n.commands)if(r.cmd===e&&r.handler){try{r.handler(o)}catch(a){console.error(`Skill command error (${e}): ${a.message}`)}return!0}}return!1}function th(){return We.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 nh(t){let e=We.find(o=>o.name===t);if(!e)return!1;e.enabled=!0;let s=Er().filter(o=>o!==t);return qc(s),!0}function sh(t){let e=We.find(o=>o.name===t);if(!e)return!1;e.enabled=!1;let s=Er();return s.includes(t)||(s.push(t),qc(s)),!0}function oh(){return We}async function rh(t,e={}){let{execSync:s}=require("child_process"),o=Dc(),n=t;/^[\w-]+\/[\w.-]+$/.test(t)&&(n=`https://github.com/${t}.git`);let r=e.name||Ue.basename(n,".git").replace(/^nex-skill-/,""),a=Ue.join(o,r);if(le.existsSync(a))return{ok:!1,name:r,error:`Skill "${r}" is already installed at ${a}. Remove it first to reinstall.`};try{s(`git clone --depth 1 ${n} ${a}`,{timeout:3e4,stdio:"pipe"})}catch(d){return{ok:!1,name:r,error:`Git clone failed: ${d.stderr?.toString().trim()||d.message}`}}let c=Ue.join(a,"skill.json"),l=le.existsSync(c),u=le.readdirSync(a).some(d=>(d.endsWith(".md")||d.endsWith(".js"))&&!d.startsWith("."));if(!l&&!u){try{le.rmSync(a,{recursive:!0,force:!0})}catch{}return{ok:!1,name:r,error:"No skill.json manifest or .md/.js skill file found in repository"}}if(l)try{let d=JSON.parse(le.readFileSync(c,"utf-8"));d.name||(d.name=r)}catch{try{le.rmSync(a,{recursive:!0,force:!0})}catch{}return{ok:!1,name:r,error:"Invalid skill.json \u2014 not valid JSON"}}return Tr(),{ok:!0,name:r}}async function ih(t){let e=require("axios");try{let s=encodeURIComponent(`nex-skill ${t} OR nex-code-skill ${t}`);return((await e.get(`https://api.github.com/search/repositories?q=${s}&sort=stars&per_page=10`,{timeout:1e4,headers:{Accept:"application/vnd.github.v3+json"}})).data.items||[]).map(n=>({name:n.name.replace(/^nex-skill-/,""),description:n.description||"(no description)",url:n.clone_url,stars:n.stargazers_count,owner:n.owner.login}))}catch(s){return[{name:"error",description:`Search failed: ${s.message}`,url:"",stars:0,owner:""}]}}function ah(t){let e=Ue.join(Bn(),t);if(!le.existsSync(e))return{ok:!1,error:`Skill "${t}" not found in ${Bn()}`};try{return le.rmSync(e,{recursive:!0,force:!0}),Tr(),{ok:!0}}catch(s){return{ok:!1,error:s.message}}}Uc.exports={initSkillsDir:Dc,loadAllSkills:Tr,getSkillInstructions:Jm,getSkillCommands:Vm,getSkillToolDefinitions:Qm,routeSkillCall:Zm,handleSkillCommand:eh,listSkills:th,enableSkill:nh,disableSkill:sh,getLoadedSkills:oh,installSkill:rh,searchSkills:ih,removeSkill:ah,_getSkillsDir:Bn,_validateScriptSkill:Fc,_loadMarkdownSkill:vr,_loadScriptSkill:Sr}});var Ks=q((c_,zc)=>{var{spawn:ch}=require("child_process"),lh=require("path"),Wc=require("fs"),kt=new Map;function uh(){return lh.join(process.cwd(),".nex","config.json")}function Rr(){let t=uh();if(!Wc.existsSync(t))return{};try{return JSON.parse(Wc.readFileSync(t,"utf-8")).mcpServers||{}}catch{return{}}}function Gs(t,e,s={},o=1e4){return new Promise((n,r)=>{let a=`${Date.now()}-${Math.random().toString(36).slice(2,6)}`,c=JSON.stringify({jsonrpc:"2.0",id:a,method:e,params:s})+`
|
|
119
119
|
`,l="",u=setTimeout(()=>{f(),r(new Error(`MCP request timeout: ${e}`))},o);function d(m){l+=m.toString();let h=l.split(`
|
|
120
|
-
`);for(let p of h)if(p.trim())try{let g=JSON.parse(p);if(g.id===
|
|
121
|
-
`):JSON.stringify(n)}function
|
|
122
|
-
Available tools: ${d.join(", ")}`}}if(!s||!s.properties)return{valid:!0};let o=s.required||[],n=Object.keys(s.properties),r=Object.keys(e),
|
|
123
|
-
`+
|
|
120
|
+
`);for(let p of h)if(p.trim())try{let g=JSON.parse(p);if(g.id===a){f(),g.error?r(new Error(`MCP error: ${g.error.message||JSON.stringify(g.error)}`)):n(g.result);return}}catch{}l=h[h.length-1]||""}function f(){clearTimeout(u),t.stdout.removeListener("data",d)}t.stdout.on("data",d);try{t.stdin.write(c)}catch(m){f(),r(new Error(`MCP write failed: ${m.message}`))}})}async function Bc(t,e){if(kt.has(t))return kt.get(t);let s=["PATH","HOME","USER","SHELL","LANG","TERM","NODE_ENV"],o={};for(let a of s)process.env[a]&&(o[a]=process.env[a]);let n=ch(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:{...o,...e.env||{}}}),r={name:t,proc:n,tools:[],config:e};try{await Gs(n,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.2.0"}});let a=await Gs(n,"tools/list",{});return r.tools=a&&a.tools||[],kt.set(t,r),r}catch(a){throw n.kill(),new Error(`Failed to connect MCP server '${t}': ${a.message}`)}}function Hc(t){let e=kt.get(t);if(!e)return!1;try{e.proc.kill()}catch{}return kt.delete(t),!0}function dh(){for(let[t]of kt)Hc(t)}async function Gc(t,e,s={}){let o=kt.get(t);if(!o)throw new Error(`MCP server not connected: ${t}`);let n=await Gs(o.proc,"tools/call",{name:e,arguments:s});return n&&Array.isArray(n.content)?n.content.filter(r=>r.type==="text").map(r=>r.text).join(`
|
|
121
|
+
`):JSON.stringify(n)}function Kc(){let t=[];for(let[e,s]of kt)for(let o of s.tools)t.push({server:e,name:o.name,description:o.description||"",inputSchema:o.inputSchema||{type:"object",properties:{}}});return t}function fh(){return Kc().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function ph(t,e){if(!t.startsWith("mcp_"))return null;let s=t.substring(4).split("_");if(s.length<2)return null;let o=s[0],n=s.slice(1).join("_");return Gc(o,n,e)}function mh(){let t=Rr();return Object.entries(t).map(([e,s])=>{let o=kt.get(e);return{name:e,command:s.command,connected:!!o,toolCount:o?o.tools.length:0}})}async function hh(){let t=Rr(),e=[];for(let[s,o]of Object.entries(t))try{let n=await Bc(s,o);e.push({name:s,tools:n.tools.length})}catch(n){e.push({name:s,tools:0,error:n.message})}return e}zc.exports={loadMCPConfig:Rr,sendRequest:Gs,connectServer:Bc,disconnectServer:Hc,disconnectAll:dh,callTool:Gc,getAllTools:Kc,getMCPToolDefinitions:fh,routeMCPCall:ph,listServers:mh,connectAll:hh}});var Ys=q((l_,Vc)=>{var Yc=require("fs"),Cr=require("path"),zs=[],Hn=[],Jt={},Gn=["onToolResult","onModelResponse","onSessionStart","onSessionEnd","onFileChange","beforeToolExec","afterToolExec"];function Xc(t,e){if(!t||!t.function||!t.function.name)return{ok:!1,error:"Tool definition must have function.name"};if(typeof e!="function")return{ok:!1,error:"Handler must be a function"};let s=t.function.name;return Hn.some(o=>o.definition.function.name===s)?{ok:!1,error:`Tool "${s}" is already registered`}:(Hn.push({definition:{type:"function",...t},handler:e}),{ok:!0})}function Jc(t,e){return Gn.includes(t)?typeof e!="function"?{ok:!1,error:"Handler must be a function"}:(Jt[t]||(Jt[t]=[]),Jt[t].push(e),{ok:!0}):{ok:!1,error:`Unknown event "${t}". Available: ${Gn.join(", ")}`}}async function Ar(t,e){let s=Jt[t]||[],o=e;for(let n of s)try{let r=await n(o);r!==void 0&&(o=r)}catch(r){process.env.NEX_DEBUG&&console.error(`[plugin] Hook error on ${t}: ${r.message}`)}return o}function gh(){let t=Cr.join(process.cwd(),".nex","plugins"),e=[];if(!Yc.existsSync(t))return{loaded:0,errors:[]};let s=Yc.readdirSync(t).filter(n=>n.endsWith(".js")),o={registerTool:Xc,registerHook:Jc,EVENTS:Gn};for(let n of s){let r=Cr.join(t,n);try{let a=require(r);if(typeof a=="function")a(o);else if(typeof a.setup=="function")a.setup(o);else{e.push(`${n}: Plugin must export a function or { setup: function }`);continue}zs.push({name:a.name||Cr.basename(n,".js"),filePath:r})}catch(a){e.push(`${n}: ${a.message}`)}}return{loaded:zs.length,errors:e}}function $h(){return Hn.map(t=>t.definition)}async function yh(t,e,s={}){let o=Hn.find(c=>c.definition.function.name===t);if(!o)return null;let n=await Ar("beforeToolExec",{name:t,args:e,options:s}),r=await o.handler(n.args||e,s);return(await Ar("afterToolExec",{name:t,args:e,result:r})).result||r}function wh(){return[...zs]}function bh(){let t={};for(let e of Gn)t[e]=(Jt[e]||[]).length;return t}function _h(){zs.length=0,Hn.length=0;for(let t of Object.keys(Jt))delete Jt[t]}Vc.exports={registerTool:Xc,registerHook:Jc,emit:Ar,loadPlugins:gh,getPluginToolDefinitions:$h,executePluginTool:yh,getLoadedPlugins:wh,getHookCounts:bh,clearPlugins:_h,EVENTS:Gn}});var Or=q((u_,tl)=>{var{getSkillToolDefinitions:kh}=Lt(),{getMCPToolDefinitions:xh}=Ks(),{getPluginToolDefinitions:vh}=Ys(),Xs=new Map;function Qc(){let{TOOL_DEFINITIONS:t}=ut();return[...t,...kh(),...xh(),...vh()]}function Zc(t){if(Xs.has(t))return Xs.get(t);let s=Qc().find(n=>n.function.name===t);if(!s)return null;let o=s.function.parameters;return Xs.set(t,o),o}function Sh(){Xs.clear()}function Js(t,e){if(!t||e.length===0)return null;let s=null,o=1/0;for(let n of e){let r=el(t.toLowerCase(),n.toLowerCase());r<o&&(o=r,s=n)}return o<=Math.ceil(t.length/2)?s:null}function el(t,e){let s=t.length,o=e.length,n=Array.from({length:s+1},()=>Array(o+1).fill(0));for(let r=0;r<=s;r++)n[r][0]=r;for(let r=0;r<=o;r++)n[0][r]=r;for(let r=1;r<=s;r++)for(let a=1;a<=o;a++)n[r][a]=t[r-1]===e[a-1]?n[r-1][a-1]:1+Math.min(n[r-1][a],n[r][a-1],n[r-1][a-1]);return n[s][o]}function Eh(t,e){let s=Zc(t);if(s===null){let d=Qc().map(m=>m.function.name),f=Js(t,d);return{valid:!1,error:`Unknown tool "${t}".${f?` Did you mean "${f}"?`:""}
|
|
122
|
+
Available tools: ${d.join(", ")}`}}if(!s||!s.properties)return{valid:!0};let o=s.required||[],n=Object.keys(s.properties),r=Object.keys(e),a=[],c={...e},l=!1;for(let u of o)if(!(u in e)||e[u]===void 0||e[u]===null){let d=Js(u,r);d&&!n.includes(d)?(c[u]=e[d],delete c[d],l=!0):a.push(`Missing required parameter "${u}" (${s.properties[u]?.description||s.properties[u]?.type||"unknown"})`)}for(let u of r)if(!n.includes(u)){let d=Js(u,n);d&&!(d in c)?(c[d]=e[u],delete c[u],l=!0):l||a.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 a.length>0&&!l?{valid:!1,error:`Tool "${t}" argument errors:
|
|
123
|
+
`+a.map(u=>` - ${u}`).join(`
|
|
124
124
|
`)+`
|
|
125
125
|
|
|
126
|
-
Expected parameters: ${JSON.stringify(s.properties,null,2)}`}:{valid:!0,corrected:l?c:null}}function
|
|
126
|
+
Expected parameters: ${JSON.stringify(s.properties,null,2)}`}:{valid:!0,corrected:l?c:null}}function Th(t,e){let s=[],o={...t};if(!o.function&&!o.name)return s.push('Tool call missing both "function" and "name" fields'),{valid:!1,normalized:o,errors:s};if(!o.function&&o.name&&(o.function={name:o.name,arguments:o.arguments||o.args||{}},delete o.name,delete o.args),o.function&&o.function.args!==void 0&&o.function.arguments===void 0&&(o.function.arguments=o.function.args,delete o.function.args),o.function&&(o.function.arguments===void 0||o.function.arguments===null)&&(o.function.arguments={}),o.function&&typeof o.function.arguments=="string"){let n=o.function.arguments;if(n.trim()==="")o.function.arguments={};else try{o.function.arguments=JSON.parse(n)}catch(r){return s.push(`Invalid JSON in arguments${e?` (${e})`:""}: ${r.message}`),{valid:!1,normalized:o,errors:s}}}return o.function&&typeof o.function.arguments!="object"?(s.push(`Arguments must be an object, got ${typeof o.function.arguments}`),{valid:!1,normalized:o,errors:s}):!o.function.name||typeof o.function.name!="string"?(s.push("Tool call function name must be a non-empty string"),{valid:!1,normalized:o,errors:s}):{valid:s.length===0,normalized:o,errors:s}}tl.exports={validateToolArgs:Eh,validateToolCallFormat:Th,closestMatch:Js,levenshtein:el,getCachedSchema:Zc,clearSchemaCache:Sh}});var rl=q((d_,ol)=>{var{levenshtein:Vs}=Or(),Rh=200,Ch=.3,Ah=2;function Nr(t){return t.replace(/\r\n/g,`
|
|
127
127
|
`).replace(/\r/g,`
|
|
128
|
-
`).replace(/\t/g," ".repeat(
|
|
128
|
+
`).replace(/\t/g," ".repeat(Ah)).split(`
|
|
129
129
|
`).map(e=>{let s=e.replace(/\s+$/,""),o=s.match(/^(\s*)(.*)/);if(!o)return s;let[,n,r]=o;return n+r.replace(/ {2,}/g," ")}).join(`
|
|
130
|
-
`)}function
|
|
130
|
+
`)}function Oh(t,e){if(t.includes(e))return e;if(e.length<10)return null;let s=Nr(t),o=Nr(e);if(!s.includes(o))return null;let n=t.split(`
|
|
131
131
|
`),r=s.split(`
|
|
132
|
-
`),
|
|
133
|
-
`),c=
|
|
134
|
-
`)}if(
|
|
132
|
+
`),a=o.split(`
|
|
133
|
+
`),c=a[0],l=a[a.length-1];for(let u=0;u<=r.length-a.length;u++){let d=!0;for(let f=0;f<a.length;f++)if(r[u+f]!==a[f]){d=!1;break}if(d)return n.slice(u,u+a.length).join(`
|
|
134
|
+
`)}if(a.length===1){for(let u=0;u<r.length;u++)if(r[u].indexOf(o)!==-1)return n[u]}return null}function Nh(t,e){if(!t||!e)return null;let s=t.split(`
|
|
135
135
|
`),n=e.split(`
|
|
136
|
-
`).length;return s.length===0||n===0?null:n===1?
|
|
137
|
-
`),u=Vs(l,e);u<
|
|
138
|
-
`),h=Vs(m,e);h<u&&(u=h,d={text:m,distance:h,line:f+1})}return d}
|
|
139
|
-
`),o=[],n=t?`.${t.split(".").pop()}`:"";for(let r=0;r<s.length;r++){let
|
|
140
|
-
`).filter(Boolean),Ir=Date.now(),Qs=!1;return}catch{}let e=[],s=async(o,n)=>{let r;try{r=await wn.readdir(o,{withFileTypes:!0})}catch{return}for(let
|
|
141
|
-
`);for(let n=0;n<o.length;n++){let r=o[n],
|
|
136
|
+
`).length;return s.length===0||n===0?null:n===1?Mh(s,e):Ph(s,e,n)}function nl(t){return Math.max(1,Math.floor(t/Rh))}function sl(t,e){return t<=Math.ceil(e*Ch)}function Mh(t,e){let s=e.trim(),o=nl(t.length),n=null,r=1/0;for(let a=0;a<t.length;a+=o){let c=t[a];if(!c.trim())continue;let l=Vs(c.trim(),s);l<r&&(r=l,n={text:c,distance:l,line:a+1})}return n&&o>1&&(n=Ih(t,s,n,o)||n,r=n.distance),sl(r,e.length)?n:null}function Ih(t,e,s,o){let n=s.line-1,r=Math.max(0,n-o),a=Math.min(t.length-1,n+o),c=s.distance,l=null;for(let u=r;u<=a;u++){let d=t[u];if(!d.trim())continue;let f=Vs(d.trim(),e);f<c&&(c=f,l={text:d,distance:f,line:u+1})}return l}function Ph(t,e,s){let o=t.length-s+1;if(o<=0)return null;let n=nl(o),r=null,a=1/0;for(let c=0;c<o;c+=n){let l=t.slice(c,c+s).join(`
|
|
137
|
+
`),u=Vs(l,e);u<a&&(a=u,r={text:l,distance:u,line:c+1})}return r&&n>1&&(r=Lh(t,e,r,n,s,o)||r,a=r.distance),sl(a,e.length)?r:null}function Lh(t,e,s,o,n,r){let a=s.line-1,c=Math.max(0,a-o),l=Math.min(r-1,a+o),u=s.distance,d=null;for(let f=c;f<=l;f++){let m=t.slice(f,f+n).join(`
|
|
138
|
+
`),h=Vs(m,e);h<u&&(u=h,d={text:m,distance:h,line:f+1})}return d}ol.exports={normalizeWhitespace:Nr,fuzzyFindText:Oh,findMostSimilar:Nh}});var al=q((p_,il)=>{var{C:f_}=we(),jh=[{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}],Dh=[{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 qh(t,e){let s=e.split(`
|
|
139
|
+
`),o=[],n=t?`.${t.split(".").pop()}`:"";for(let r=0;r<s.length;r++){let a=s[r],c=r+1;for(let l of jh)l.regex.test(a)&&o.push({line:c,message:`Potential secret detected: ${l.name}`,severity:"error"});for(let l of Dh)l.ext&&!l.ext.includes(n)||l.regex.test(a)&&o.push({line:c,message:l.message||`Found ${l.name}`,severity:l.severity||"warn"})}return s.length>500&&o.push({line:0,message:`Large file detected (${s.length} lines). Consider refactoring.`,severity:"info"}),o}il.exports={runDiagnostics:qh}});var jr=q((m_,pl)=>{var wn=require("fs").promises,bn=require("path"),{exec:Fh}=require("util").promisify(require("child_process").exec),_n=[],Lr=null,Qs=!1,Ir=0,Uh=6e4;function ll(t){return!(_n.length===0||Lr!==t||Date.now()-Ir>Uh)}async function ul(t){if(!Qs&&!ll(t)){Qs=!0,Lr=t;try{try{let{stdout:o}=await Fh("rg --files",{cwd:t,timeout:5e3});_n=o.split(`
|
|
140
|
+
`).filter(Boolean),Ir=Date.now(),Qs=!1;return}catch{}let e=[],s=async(o,n)=>{let r;try{r=await wn.readdir(o,{withFileTypes:!0})}catch{return}for(let a of r){if(a.name==="node_modules"||a.name===".git"||a.name.startsWith("."))continue;let c=n?`${n}/${a.name}`:a.name;a.isDirectory()?await s(bn.join(o,a.name),c):e.push(c)}};await s(t,""),_n=e,Ir=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{Qs=!1}}}function Pr(){return _n}function Wh(){return Lr}function Bh(t){return _n.filter(e=>bn.basename(e)===t)}function Hh(t){let e=t.toLowerCase();return _n.filter(s=>s.toLowerCase().includes(e)).slice(0,20)}var Mr=null,cl=0,Gh=12e4,Kh=new Set([".js",".ts",".jsx",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".rb"]);function dl(t,e){let s=[],o=t.split(`
|
|
141
|
+
`);for(let n=0;n<o.length;n++){let r=o[n],a=n+1;if([".js",".ts",".jsx",".tsx",".mjs",".cjs"].includes(e)){let c=r.match(/(?:export\s+)?(?:async\s+)?function\s+(\w+)/);c&&s.push({type:"function",name:c[1],line:a});let l=r.match(/(?:export\s+)?class\s+(\w+)/);l&&s.push({type:"class",name:l[1],line:a});let u=r.match(/(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?(?:\([^)]*\)|[\w$]+)\s*=>/);u&&s.push({type:"function",name:u[1],line:a});let d=r.match(/module\.exports\s*=\s*\{([^}]+)\}/);if(d){let m=d[1].split(",").map(h=>h.trim().split(":")[0].trim()).filter(Boolean);for(let h of m)/^\w+$/.test(h)&&s.push({type:"export",name:h,line:a})}let f=r.match(/(?:require\(['"]([^'"]+)['"]\)|from\s+['"]([^'"]+)['"])/);if(f){let m=f[1]||f[2];s.push({type:"import",name:m,line:a})}}if(e===".py"){let c=r.match(/^(?:async\s+)?def\s+(\w+)/);c&&s.push({type:"function",name:c[1],line:a});let l=r.match(/^class\s+(\w+)/);l&&s.push({type:"class",name:l[1],line:a});let u=r.match(/^(?:from\s+(\S+)\s+)?import\s+(\S+)/);u&&s.push({type:"import",name:u[1]||u[2],line:a})}if(e===".go"){let c=r.match(/^func\s+(?:\([^)]+\)\s+)?(\w+)/);c&&s.push({type:"function",name:c[1],line:a});let l=r.match(/^type\s+(\w+)\s+struct/);l&&s.push({type:"class",name:l[1],line:a})}}return s}async function fl(t){t=t||process.cwd();let e=bn.join(t,".nex","index","content-index.json"),s={};if(Mr&&Date.now()-cl<Gh)return Mr;try{let a=await wn.readFile(e,"utf-8");s=JSON.parse(a)}catch{s={files:{}}}Pr().length===0&&await ul(t);let n={files:{}},r=!1;for(let a of Pr()){let c=bn.extname(a);if(!Kh.has(c))continue;let l=bn.join(t,a);try{let d=(await wn.stat(l)).mtimeMs;if(s.files[a]&&s.files[a].mtime===d){n.files[a]=s.files[a];continue}let f=await wn.readFile(l,"utf-8"),m=dl(f,c);n.files[a]={defs:m,mtime:d},r=!0}catch{}}if(r){let a=bn.join(t,".nex","index");await wn.mkdir(a,{recursive:!0}),await wn.writeFile(e,JSON.stringify(n),"utf-8")}return Mr=n,cl=Date.now(),n}async function zh(t,e){let s=await fl(),o=[],n=t.toLowerCase();for(let[r,a]of Object.entries(s.files))for(let c of a.defs)e&&c.type!==e||c.name.toLowerCase().includes(n)&&o.push({file:r,type:c.type,name:c.name,line:c.line});return o.sort((r,a)=>{let c=r.name.toLowerCase()===n?0:1,l=a.name.toLowerCase()===n?0:1;if(c!==l)return c-l;let u=r.name.toLowerCase().startsWith(n)?0:1,d=a.name.toLowerCase().startsWith(n)?0:1;return u-d}),o.slice(0,50)}pl.exports={refreshIndex:ul,getFileIndex:Pr,getIndexedCwd:Wh,findFileInIndex:Bh,searchIndex:Hh,isIndexValid:ll,buildContentIndex:fl,searchContentIndex:zh,extractDefinitions:dl}});var kn=q((h_,$l)=>{var Zs=require("fs"),to=require("path"),no=require("os"),{execFile:Yh}=require("child_process"),{promisify:Xh}=require("util"),Dr=Xh(Yh),Jh=to.join(no.homedir(),".nex","servers.json"),eo=to.join(no.tmpdir(),"nex-ssh-sockets");function Vh(){return to.join(process.cwd(),".nex","servers.json")}function ml(){let t=o=>{if(!Zs.existsSync(o))return{};try{return JSON.parse(Zs.readFileSync(o,"utf-8"))}catch{return{}}},e=t(Jh),s=t(Vh());return{...e,...s}}function Qh(t){let e=ml();if(e[t])return{...e[t],_name:t};if(/^[\w.-]+@[\w.-]+$/.test(t)||/[\w-]+\.[\w.-]+/.test(t)||t==="localhost"){let[n,r]=t.includes("@")?t.split("@"):[void 0,t];return{host:r,user:n}}let s=Object.keys(e),o=s.length?`Available profiles: ${s.join(", ")}`:"No profiles configured. Create .nex/servers.json (project) or ~/.nex/servers.json (global)";throw new Error(`Unknown server: "${t}". ${o}`)}function Zh(){Zs.existsSync(eo)||Zs.mkdirSync(eo,{recursive:!0})}function hl(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-o","ServerAliveInterval=30"];t.key&&e.push("-i",t.key.replace(/^~/,no.homedir())),t.port&&Number(t.port)!==22&&e.push("-p",String(t.port)),Zh();let s=t.user?`${t.user}@${t.host}`:t.host,o=to.join(eo,s.replace(/[@.:]/g,"_"));return e.push("-o","ControlMaster=auto","-o",`ControlPath=${o}`,"-o","ControlPersist=120"),e.push(s),{args:e,target:s}}function gl(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-r"];return t.key&&e.push("-i",t.key.replace(/^~/,no.homedir())),t.port&&Number(t.port)!==22&&e.push("-P",String(t.port)),e}async function eg(t,e,{timeout:s=3e4,sudo:o=!1}={}){let{args:n}=hl(t),r=o&&t.sudo?`sudo sh -c ${JSON.stringify(e)}`:e;try{let{stdout:a,stderr:c}=await Dr("ssh",[...n,r],{timeout:s,maxBuffer:4194304});return{stdout:a||"",stderr:c||"",exitCode:0}}catch(a){let c=typeof a.code=="number"?a.code:1,l=(a.stderr||a.message||"").toString();return{stdout:(a.stdout||"").toString(),stderr:l,exitCode:c,error:so(l,t)}}}async function tg(t,e,s,{timeout:o=12e4}={}){let n=gl(t),r=t.user?`${t.user}@${t.host}`:t.host;n.push(e,`${r}:${s}`);try{let{stdout:a,stderr:c}=await Dr("scp",n,{timeout:o,maxBuffer:1048576});return a||c||`Uploaded ${e} \u2192 ${r}:${s}`}catch(a){let c=(a.stderr||a.message||"").toString();throw new Error(so(c,t)||c)}}async function ng(t,e,s,{timeout:o=12e4}={}){let n=gl(t),r=t.user?`${t.user}@${t.host}`:t.host;n.push(`${r}:${e}`,s);try{let{stdout:a,stderr:c}=await Dr("scp",n,{timeout:o,maxBuffer:1048576});return a||c||`Downloaded ${r}:${e} \u2192 ${s}`}catch(a){let c=(a.stderr||a.message||"").toString();throw new Error(so(c,t)||c)}}function so(t,e){if(!t)return"";if(/connection refused/i.test(t)){let s=e.port||22;return`${t}
|
|
142
142
|
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}
|
|
143
143
|
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}
|
|
144
144
|
HINT: Cannot reach ${e.host}. Check: network connection, correct hostname/IP, DNS resolution.`:/host key verification failed/i.test(t)?`${t}
|
|
145
145
|
HINT: Host key changed for ${e.host}. To reset: ssh-keygen -R ${e.host}`:/timed out/i.test(t)?`${t}
|
|
146
146
|
HINT: Connection timed out to ${e.host}. Check firewall rules and network connectivity.`:/too many authentication failures/i.test(t)?`${t}
|
|
147
|
-
HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function
|
|
148
|
-
`,"utf-8")}
|
|
147
|
+
HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function sg(t,e){let s=e.user?`${e.user}@${e.host}`:e.host,o=e.port&&Number(e.port)!==22?`:${e.port}`:"",n=e.os?` [${e.os}]`:"",r=e.key?` key:${e.key}`:"",a=e.sudo?" sudo:yes":"";return`${t}: ${s}${o}${n}${r}${a}`}$l.exports={loadServerProfiles:ml,resolveProfile:Qh,buildSSHArgs:hl,sshExec:eg,scpUpload:tg,scpDownload:ng,enrichSSHError:so,formatProfile:sg,SSH_SOCKET_DIR:eo}});var Ur=q((g_,wl)=>{var Kn=require("fs"),qr=require("path"),og=qr.join(".nex","deploy.json");function Fr(){return qr.join(process.cwd(),og)}function yl(){let t=Fr();if(!Kn.existsSync(t))return{};try{return JSON.parse(Kn.readFileSync(t,"utf-8"))}catch{return{}}}function rg(t){let e=yl();if(e[t])return{...e[t],_name:t};let s=Object.keys(e),o=s.length?`Available: ${s.join(", ")}`:"No deploy configs found. Create .nex/deploy.json or use explicit params.";throw new Error(`Unknown deploy config: "${t}". ${o}`)}function ig(t){let e=qr.join(process.cwd(),".nex");Kn.existsSync(e)||Kn.mkdirSync(e,{recursive:!0}),Kn.writeFileSync(Fr(),JSON.stringify(t,null,2)+`
|
|
148
|
+
`,"utf-8")}wl.exports={loadDeployConfigs:yl,resolveDeployConfig:rg,saveDeployConfigs:ig,getDeployConfigPath:Fr}});var oo=q(($_,kl)=>{var{getActiveModel:ag,getActiveProviderName:cg}=be(),zn={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},Yn={"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"},Xn={ollama:"full",openai:"full",anthropic:"full",gemini:"full",local:"essential"},$t={};function _l(){try{let t=require("fs"),s=require("path").join(process.cwd(),".nex","config.json");t.existsSync(s)&&($t=JSON.parse(t.readFileSync(s,"utf-8")).toolTiers||{})}catch{$t={}}}_l();function Wr(){let e=ag()?.id,s=cg();return e&&$t[e]?$t[e]:s&&$t[`${s}:*`]?$t[`${s}:*`]:e&&Yn[e]?Yn[e]:s&&Xn[s]?Xn[s]:"full"}var lg=new Set(["claude-sonnet","claude-sonnet-4-5","claude-sonnet-4","claude-opus","claude-haiku","gpt-4o","gpt-4.1","o1","o3","o4-mini","kimi-k2:1t","kimi-k2.5","kimi-k2-thinking","qwen3-coder:480b","qwen3-coder-next","deepseek-v3.2","deepseek-v3.1:671b"]),bl={anthropic:"strict",openai:"strict",gemini:"strict",ollama:"fuzzy",local:"fuzzy"};function ug(t,e){return t&&(lg.has(t)||t.startsWith("claude-"))?"strict":e&&bl[e]?bl[e]:"fuzzy"}function dg(t,e){return t&&$t[t]?$t[t]:e&&$t[`${e}:*`]?$t[`${e}:*`]:t&&Yn[t]?Yn[t]:e&&Xn[e]?Xn[e]:"full"}function fg(t,e){let s=e||Wr();if(s==="full"||!zn[s])return t;let o=new Set(zn[s]);return t.filter(n=>o.has(n.function.name))}function pg(){let t=Wr(),e=zn[t]?zn[t].length:"all";return{tier:t,toolCount:e}}kl.exports={filterToolsForModel:fg,getActiveTier:Wr,getModelTier:dg,getEditMode:ug,getTierInfo:pg,TIERS:zn,MODEL_TIERS:Yn,PROVIDER_DEFAULT_TIER:Xn,loadConfigOverrides:_l}});var Vn=q((y_,Sl)=>{var Br=null,xt=null,Jn=null,xl=`Playwright is not installed. Install with:
|
|
149
149
|
npm install playwright && npx playwright install chromium
|
|
150
|
-
Then restart nex-code.`;function
|
|
151
|
-
...(truncated)`:""),links:c.slice(0,20)}}finally{await n.close()}}async function
|
|
152
|
-
`)}function
|
|
150
|
+
Then restart nex-code.`;function vl(){if(Jn!==null)return Jn;try{require("playwright"),Jn=!0}catch{Jn=!1}return Jn}async function ro(){if(!vl())throw new Error(xl);return Br||(Br=require("playwright")),(!xt||!xt.isConnected())&&(xt=await Br.chromium.launch({headless:!0})),xt}async function mg(){if(xt){try{await xt.close()}catch{}xt=null}}process.on("exit",()=>{if(xt)try{xt.close()}catch{}});async function hg(t,{timeout:e=3e4,waitFor:s="domcontentloaded"}={}){let n=await(await ro()).newPage();try{await n.goto(t,{waitUntil:s,timeout:e});let r=await n.title(),a=await n.evaluate(()=>(document.querySelectorAll("script,style,nav,footer,header,aside,[role=navigation]").forEach(u=>u.remove()),document.body?.innerText||"")),c=await n.evaluate(()=>Array.from(document.querySelectorAll("a[href]")).slice(0,30).map(l=>({text:(l.innerText||l.textContent||"").trim().substring(0,80),href:l.href})).filter(l=>l.text&&l.href&&!l.href.startsWith("javascript:")));return{title:r,url:n.url(),text:a.substring(0,8e3)+(a.length>8e3?`
|
|
151
|
+
...(truncated)`:""),links:c.slice(0,20)}}finally{await n.close()}}async function gg(t,{width:e=1280,height:s=800,fullPage:o=!1,timeout:n=3e4}={}){let a=await(await ro()).newPage();try{await a.setViewportSize({width:e,height:s}),await a.goto(t,{waitUntil:"networkidle",timeout:n});let c=await a.screenshot({type:"png",fullPage:o}),l=require("os"),u=require("path"),d=require("fs"),f=u.join(l.tmpdir(),`nex-screenshot-${Date.now()}.png`);return d.writeFileSync(f,c),{path:f,base64:c.toString("base64"),media_type:"image/png",title:await a.title(),url:a.url()}}finally{await a.close()}}async function $g(t,{selector:e,text:s,timeout:o=3e4}={}){if(!e&&!s)throw new Error("selector or text is required");let r=await(await ro()).newPage();try{await r.goto(t,{waitUntil:"domcontentloaded",timeout:o}),s?await r.getByText(s,{exact:!1}).first().click({timeout:1e4}):await r.locator(e).first().click({timeout:1e4}),await r.waitForLoadState("domcontentloaded");let a=await r.title();return`Clicked \u2014 now at: ${r.url()} (${a})`}finally{await r.close()}}async function yg(t,{selector:e,value:s,submit:o=!1,timeout:n=3e4}={}){if(!e||s===void 0)throw new Error("selector and value are required");let a=await(await ro()).newPage();try{return await a.goto(t,{waitUntil:"domcontentloaded",timeout:n}),await a.fill(e,String(s)),o&&(await a.keyboard.press("Enter"),await a.waitForLoadState("domcontentloaded")),`Filled "${e}" with value. ${o?`Submitted \u2192 ${a.url()}`:"Not submitted."}`}finally{await a.close()}}Sl.exports={isPlaywrightAvailable:vl,browserNavigate:hg,browserScreenshot:gg,browserClick:$g,browserFill:yg,closeBrowser:mg,INSTALL_MSG:xl}});var io=q((w_,El)=>{var{C:ue}=we(),Zn="",Pe=[],Qn=0,Vt=null;function wg(t){Vt=t}function bg(t,e){Zn=t,Pe=[],Qn=0;for(let o of e){Qn++;let n=`t${Qn}`;Pe.push({id:n,description:o.description||o.title||o.name||o.task||`Task ${Qn}`,status:"pending",dependsOn:o.depends_on||[],result:null})}let s=Pe.map(o=>({...o}));return Vt&&Vt("create",{name:t,tasks:s}),s}function _g(t,e,s){let o=Pe.find(n=>n.id===t);return o?(o.status=e,s!==void 0&&(o.result=s),Vt&&Vt("update",{id:t,status:e,result:s}),{...o}):null}function kg(){return{name:Zn,tasks:Pe.map(t=>({...t}))}}function xg(){Zn="",Pe=[],Qn=0,Vt&&Vt("clear",{})}function vg(){return Pe.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let s=Pe.find(o=>o.id===e);return s&&s.status==="done"}))}function Sg(){if(Pe.length===0)return`${ue.dim}No active tasks${ue.reset}`;let t=[];Zn&&(t.push(` ${ue.bold}${ue.cyan}Tasks: ${Zn}${ue.reset}`),t.push(` ${ue.dim}${"\u2500".repeat(40)}${ue.reset}`));for(let n of Pe){let r,a;switch(n.status){case"done":r="\u2713",a=ue.green;break;case"in_progress":r="\u2192",a=ue.cyan;break;case"failed":r="\u2717",a=ue.red;break;default:r="\xB7",a=ue.dim}let c=n.dependsOn.length>0?` ${ue.dim}(after: ${n.dependsOn.join(", ")})${ue.reset}`:"",l=`[${n.status}]`,u=n.description.length>50?n.description.substring(0,47)+"...":n.description;if(t.push(` ${a}${r}${ue.reset} ${ue.bold}${n.id}${ue.reset} ${u.padEnd(40)} ${a}${l}${ue.reset}${c}`),n.result&&n.status==="done"){let d=n.result.length>60?n.result.substring(0,57)+"...":n.result;t.push(` ${ue.dim}\u2192 ${d}${ue.reset}`)}}let e=Pe.filter(n=>n.status==="done").length,s=Pe.filter(n=>n.status==="failed").length,o=Pe.length;return t.push(` ${ue.dim}${"\u2500".repeat(40)}${ue.reset}`),t.push(` ${ue.dim}${e}/${o} done${s>0?`, ${s} failed`:""}${ue.reset}`),t.join(`
|
|
152
|
+
`)}function Eg(){return Pe.length>0&&Pe.some(t=>t.status==="pending"||t.status==="in_progress")}El.exports={createTasks:bg,updateTask:_g,getTaskList:kg,clearTasks:xg,getReadyTasks:vg,renderTaskList:Sg,setOnChange:wg,hasActiveTasks:Eg}});var Hl=q((__,Bl)=>{var{callStream:Tg,getActiveProviderName:co,getActiveModelId:Rg,getConfiguredProviders:Cg,getProvider:Tl,getActiveProvider:Rl,parseModelSpec:Cl}=be(),{parseToolArgs:Al}=qs(),{filterToolsForModel:Ag,getModelTier:ao}=oo(),{trackUsage:Og}=$n(),{MultiProgress:Ng,C:b_}=we(),Ml=15,Mg=5,Ol=3,Il=8,Ig=2,lo=new Map,Pl=600*1e3;function Pg(t,e){let s=lo.get(t);return s&&s.agentId!==e&&Date.now()-s.timestamp<Pl?!1:(lo.set(t,{agentId:e,timestamp:Date.now()}),!0)}function es(t){lo.delete(t)}function Hr(){lo.clear()}function Ll(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 jl(t,e,s){let o;for(let n=0;n<=Ol;n++)try{return await Tg(t,e,s)}catch(r){if(o=r,n<Ol&&Ll(r)){let c=(r.message||"").includes("429")?Math.min(2e3*Math.pow(2,n),15e3):Math.min(500*Math.pow(2,n),4e3);await new Promise(l=>setTimeout(l,c).unref());continue}throw r}throw o}var Nl=new Set(["ask_user","task_list"]);function Dl(t){return t>=2?new Set([...Nl,"spawn_agents"]):Nl}var Lg=new Set(["write_file","edit_file","patch_file"]),jg=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,Dg=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function ql(t){return Dg.test(t)?"full":jg.test(t)?"essential":"standard"}function Fl(t){let e=Cg(),s=co(),o=[...e].sort((n,r)=>(n.name===s?-1:1)-(r.name===s?-1:1));for(let n of o)for(let r of n.models)if(ao(r.id,n.name)===t)return{provider:n.name,model:r.id};return null}var qg={essential:process.env.NEX_FAST_MODEL||null,standard:process.env.NEX_STANDARD_MODEL||null,full:process.env.NEX_HEAVY_MODEL||null};function Gr(t){if(t.model){let{provider:n,model:r}=Cl(t.model),a=n?Tl(n):Rl(),c=n||co();if(a&&a.isConfigured()&&(a.getModel(r)||c==="local")){let l=ao(r,c);return{provider:c,model:r,tier:l}}}let e=ql(t.task),s=qg[e];if(s){let{provider:n,model:r}=Cl(s),a=n?Tl(n):Rl(),c=n||co();if(a&&a.isConfigured()&&(a.getModel(r)||c==="local")){let l=ao(r,c);return{provider:c,model:r,tier:l}}}let o=Fl(e);if(o){let n=ao(o.model,o.provider);return{provider:o.provider,model:o.model,tier:n}}return{provider:null,model:null,tier:null}}async function Ul(t,e={},s=0){let o=s===0?Ml:Il,n=Math.min(t.max_iterations||10,o),r=`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,a=[],c={input:0,output:0},l=new Set,u=new Map,f=[{role:"system",content:`You are a focused sub-agent. Complete this specific task efficiently.
|
|
153
153
|
|
|
154
154
|
TASK: ${t.task}
|
|
155
155
|
${t.context?`
|
|
@@ -171,64 +171,64 @@ TOOL STRATEGY:
|
|
|
171
171
|
ERROR RECOVERY:
|
|
172
172
|
- If edit_file fails with "old_text not found": read the file again, compare, and retry with exact text.
|
|
173
173
|
- If bash fails: read the error, fix the root cause, then retry.
|
|
174
|
-
- After 2 failed attempts at the same operation, summarize the issue and stop.`}];f.push({role:"user",content:t.task});let m=Gr(t),h=m.provider,p=m.model,g=m.tier,{TOOL_DEFINITIONS:y,executeTool:$}=ut(),w=
|
|
175
|
-
`)}let b={};h&&(b.provider=h),p&&(b.model=p);try{for(let v=0;v<n;v++){let R=await
|
|
176
|
-
...(truncated)`:Ae,tool_call_id:pe}}).catch(Me=>(Te&&(es(Te),l.delete(Te)),{role:"tool",content:`ERROR: ${Me.message}`,tool_call_id:pe}))}),X=await Promise.all(Q);f.push(...X);for(let H=0;H<A.length;H++){let G=A[H];if(G.function.name==="bash_exec"){let U=
|
|
177
|
-
`)}catch(d){return u.stop(),Hr(),`ERROR: Sub-agent execution failed: ${d.message}`}}
|
|
178
|
-
`);for(let r of n){let
|
|
179
|
-
`);for(let
|
|
180
|
-
...(truncated)`}let f=typeof l.score=="number"?l.score.toFixed(2):String(l.score);if(
|
|
181
|
-
${u}`),c+=n(u),c>=r)break}return
|
|
182
|
-
|
|
183
|
-
${
|
|
184
|
-
|
|
185
|
-
`)}`}
|
|
186
|
-
`;os.appendFileSync(
|
|
187
|
-
`).filter(l=>l.trim());for(let l of c)try{let u=JSON.parse(l);if(t.tool&&u.tool!==t.tool)continue;o.push(u)}catch{}if(t.date)break}return o}function
|
|
188
|
-
${
|
|
189
|
-
`)}`}}catch{}return{fixedPath:null,message:""}}function
|
|
174
|
+
- After 2 failed attempts at the same operation, summarize the issue and stop.`}];f.push({role:"user",content:t.task});let m=Gr(t),h=m.provider,p=m.model,g=m.tier,{TOOL_DEFINITIONS:y,executeTool:$}=ut(),w=Dl(s),E=Ag(y.filter(k=>!w.has(k.function.name)),g);if(p&&!t._skipLog){let k=g?` (${g})`:"";process.stderr.write(` [sub-agent: ${h}:${p}${k}]
|
|
175
|
+
`)}let b={};h&&(b.provider=h),p&&(b.model=p);try{for(let v=0;v<n;v++){let R=await jl(f,E,b);if(!R||typeof R!="object")throw new Error("Empty or invalid response from provider");if(R.usage){let H=R.usage.prompt_tokens||0,G=R.usage.completion_tokens||0;c.input+=H,c.output+=G;let U=h||co(),pe=p||Rg();Og(U,pe,H,G)}let C=R.content||"",A=R.tool_calls,j={role:"assistant",content:C||""};if(A&&A.length>0&&(j.tool_calls=A),f.push(j),!A||A.length===0){for(let H of l)es(H);return{task:t.task,status:"done",result:C||"(no response)",toolsUsed:a,tokensUsed:c,modelSpec:h&&p?`${h}:${p}`:null}}let Q=A.map(H=>{let G=H.function.name,U=Al(H.function.arguments),pe=H.id||`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!U)return Promise.resolve({role:"tool",content:`ERROR: Malformed tool arguments for ${G}`,tool_call_id:pe});let Te=null;if(Lg.has(G)&&U.path){let Me=require("path"),Ae=Me.isAbsolute(U.path)?U.path:Me.resolve(process.cwd(),U.path);if(l.has(Ae)||!Pg(Ae,r))return Promise.resolve({role:"tool",content:`ERROR: File '${U.path}' is locked by another operation. Try a different approach or skip this file.`,tool_call_id:pe});l.add(Ae),Te=Ae}return a.push(G),(G==="spawn_agents"?Wl(U,s+1):$(G,U,{autoConfirm:!0,silent:!0})).then(Me=>{Te&&(es(Te),l.delete(Te));let Ae=String(Me??"");return{role:"tool",content:Ae.length>2e4?Ae.substring(0,2e4)+`
|
|
176
|
+
...(truncated)`:Ae,tool_call_id:pe}}).catch(Me=>(Te&&(es(Te),l.delete(Te)),{role:"tool",content:`ERROR: ${Me.message}`,tool_call_id:pe}))}),X=await Promise.all(Q);f.push(...X);for(let H=0;H<A.length;H++){let G=A[H];if(G.function.name==="bash_exec"){let U=Al(G.function.arguments);if((X[H]?.content||"").startsWith("ERROR")&&U&&U.command){let Te=U.command.replace(/\s+/g," ").trim().slice(0,100);u.set(Te,(u.get(Te)||0)+1)}}}e.onUpdate&&e.onUpdate(`step ${v+1}/${n}`)}for(let v of l)es(v);let k=[...u.entries()].filter(([,v])=>v>=3).sort((v,R)=>R[1]-v[1]).slice(0,3).map(([v,R])=>`"${v}" (failed ${R}\xD7)`);return{task:t.task,status:"truncated",abortReason:"iteration_limit",repeatedFailures:k,result:f[f.length-1]?.content||"(max iterations reached)",toolsUsed:a,tokensUsed:c,modelSpec:h&&p?`${h}:${p}`:null}}catch(k){for(let v of l)es(v);return{task:t.task,status:"failed",result:`Error: ${k.message}`,toolsUsed:a,tokensUsed:c,modelSpec:h&&p?`${h}:${p}`:null}}}async function Wl(t,e=0){if(e>=2)return"ERROR: max agent nesting depth (2) reached \u2014 reviewer agents cannot spawn further agents.";let s=e===0?Mg:Ig,o=e===0?Ml:Il,n=(t.agents||[]).slice(0,s);if(n.length===0)return"ERROR: No agents specified";let r=e>0?" \u21B3 ":"",a=e>0?38:44,c=n.map(d=>Gr(d)),l=n.map((d,f)=>{let m=c[f],h=m.model?` [${m.model}]`:"",p=d.task.substring(0,a-h.length);return`${r}Agent ${f+1}${h}: ${p}${d.task.length>p.length?"...":""}`}),u=new Ng(l);u.start();try{let d=n.map((g,y)=>{let $=c[y],w=Math.min(g.max_iterations||o,o),E=$.model?{...g,model:`${$.provider}:${$.model}`,_skipLog:!0,max_iterations:w}:{...g,_skipLog:!0,max_iterations:w};return Ul(E,{onUpdate:()=>{}},e).then(b=>(u.update(y,b.status==="failed"?"error":"done"),b)).catch(b=>(u.update(y,"error"),{task:g.task,status:"failed",result:`Error: ${b.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}))}),f=await Promise.all(d);u.stop(),Hr();let m=["Sub-agent results:",""],h=0,p=0;for(let g=0;g<f.length;g++){let y=f[g],$=y.status==="done"?"\u2713":y.status==="truncated"?"\u26A0":"\u2717",w=y.modelSpec?` [${y.modelSpec}]`:"";m.push(`${$} Agent ${g+1}${w}: ${y.task}`),m.push(` Status: ${y.status}`),m.push(` Tools used: ${y.toolsUsed.length>0?y.toolsUsed.join(", "):"none"}`),m.push(` Result: ${y.result}`),y.repeatedFailures&&y.repeatedFailures.length>0&&m.push(` Repeated failures: ${y.repeatedFailures.join("; ")}`),m.push(""),h+=y.tokensUsed.input,p+=y.tokensUsed.output}return m.push(`Total sub-agent tokens: ${h} input + ${p} output`),m.join(`
|
|
177
|
+
`)}catch(d){return u.stop(),Hr(),`ERROR: Sub-agent execution failed: ${d.message}`}}Bl.exports={runSubAgent:Ul,executeSpawnAgents:Wl,clearAllLocks:Hr,classifyTask:ql,pickModelForTier:Fl,resolveSubAgentModel:Gr,isRetryableError:Ll,callWithRetry:jl,getExcludedTools:Dl,LOCK_TIMEOUT_MS:Pl}});var ss=q((k_,ou)=>{var _e=require("fs"),vt=require("path"),{atomicWrite:Gl,withFileLockSync:Kl}=It(),Fg=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 xn(){let t=vt.join(process.cwd(),".nex","brain");return _e.existsSync(t)||_e.mkdirSync(t,{recursive:!0}),t}function fo(){return vt.join(xn(),".brain-index.json")}function Yr(){return vt.join(xn(),".embeddings.json")}function ts(){let t=vt.join(process.cwd(),".nex","brain");if(!_e.existsSync(t))return[];try{return _e.readdirSync(t).filter(e=>e.endsWith(".md")&&!e.startsWith(".")).map(e=>{let s=vt.join(t,e),o=_e.statSync(s);return{name:e.replace(/\.md$/,""),path:s,size:o.size,modified:new Date(o.mtimeMs)}}).sort((e,s)=>s.modified-e.modified)}catch{return[]}}function ns(t){let e={},s=t,o=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(o){let n=o[1].split(`
|
|
178
|
+
`);for(let r of n){let a=r.match(/^(\w+):\s*(.+)$/);if(!a)continue;let c=a[1].trim(),l=a[2].trim();l.startsWith("[")&&l.endsWith("]")?e[c]=l.slice(1,-1).split(",").map(u=>u.trim()).filter(Boolean):e[c]=l}s=o[2]}return{frontmatter:e,body:s}}function zl(t){let e=vt.join(xn(),`${t}.md`);if(!_e.existsSync(e))return{name:t,content:"",body:"",frontmatter:{}};let s=_e.readFileSync(e,"utf-8"),{frontmatter:o,body:n}=ns(s);return{name:t,content:s,body:n,frontmatter:o}}function Ug(t,e){let s=vt.join(xn(),`${t}.md`);Gl(s,e),Hg(t,e),Wg()}function Wg(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return;let t=Yr();_e.existsSync(t)&&setImmediate(async()=>{try{await eu()}catch{}})}function Bg(t){let e=vt.join(xn(),`${t}.md`);return _e.existsSync(e)?(_e.unlinkSync(e),Gg(t),!0):!1}function uo(t){return t.toLowerCase().replace(/[^a-z0-9äöüß\s-]/g," ").split(/[\s-]+/).filter(e=>e.length>2&&!Fg.has(e))}function Xr(t){let e={},{frontmatter:s,body:o}=ns(t),n=Array.isArray(s.tags)?s.tags:[];for(let a of n){let c=a.toLowerCase().replace(/[^a-z0-9-]/g,"");c.length>1&&(e[c]=(e[c]||0)+5)}let r=(o||t).split(`
|
|
179
|
+
`);for(let a of r)if(a.startsWith("#")){let c=a.replace(/^#+\s*/,"");for(let l of uo(c))e[l]=(e[l]||0)+3}for(let a of uo(o||t))e[a]=(e[a]||0)+1;return e}function Jr(){let t=fo();if(!_e.existsSync(t))return{documents:{}};try{return JSON.parse(_e.readFileSync(t,"utf-8"))}catch{return{documents:{}}}}function Vr(t){Gl(fo(),JSON.stringify(t,null,2))}function Hg(t,e){Kl(fo(),()=>{let s=Jr(),{frontmatter:o}=ns(e),n=Array.isArray(o.tags)?o.tags:[];s.documents[t]={keywords:Xr(e),tags:n,modified:new Date().toISOString()},Vr(s)})}function Gg(t){Kl(fo(),()=>{let e=Jr();delete e.documents[t],Vr(e)})}function zr(){let t=ts(),e={documents:{}};for(let s of t){let o=_e.readFileSync(s.path,"utf-8"),{frontmatter:n}=ns(o),r=Array.isArray(n.tags)?n.tags:[];e.documents[s.name]={keywords:Xr(o),tags:r,modified:s.modified.toISOString()}}return Vr(e),e}function Yl(){let t=Jr(),e=ts();for(let s of e){let o=t.documents[s.name];if(!o||new Date(o.modified)<s.modified)return zr()}for(let s of Object.keys(t.documents))if(!e.some(o=>o.name===s))return zr();return t}function Xl(t,e={}){let{topK:s=3,minScore:o=.1}=e,n=uo(t);if(n.length===0)return[];let r=Yl(),a=[];for(let[c,l]of Object.entries(r.documents)){let u=0;for(let d of n){l.keywords[d]&&(u+=l.keywords[d]);for(let[f,m]of Object.entries(l.keywords))f!==d&&f.length>3&&d.length>3&&(f.includes(d)||d.includes(f))&&(u+=m*.3)}u>=o&&a.push({name:c,score:u})}return a.sort((c,l)=>l.score-c.score),a.slice(0,s)}var Jl=process.env.NEX_EMBED_MODEL||"nomic-embed-text",Kr=400,Kg=50;async function Vl(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return!1;try{let t=process.env.OLLAMA_HOST||"http://localhost:11434",e=require("http"),s=require("https"),o=new URL(`${t}/api/tags`),n=o.protocol==="https:"?s:e;return((await new Promise((c,l)=>{let u=n.get(o.toString(),{timeout:2e3},d=>{let f="";d.on("data",m=>f+=m),d.on("end",()=>{try{c(JSON.parse(f))}catch{l(new Error("bad json"))}})});u.on("error",l),u.on("timeout",()=>{u.destroy(),l(new Error("timeout"))})})).models||[]).map(c=>c.name).some(c=>c.startsWith(Jl.split(":")[0]))}catch{return!1}}async function Qr(t){let e=process.env.OLLAMA_HOST||"http://localhost:11434",s=require("http"),o=require("https"),n=new URL(`${e}/api/embeddings`),r=n.protocol==="https:"?o:s,a=JSON.stringify({model:Jl,prompt:t});return new Promise((c,l)=>{let u=r.request(n,{method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(a)},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(a),u.end()})}function Ql(t,e){if(!t||!e||t.length!==e.length)return 0;let s=0,o=0,n=0;for(let a=0;a<t.length;a++)s+=t[a]*e[a],o+=t[a]*t[a],n+=e[a]*e[a];let r=Math.sqrt(o)*Math.sqrt(n);return r===0?0:s/r}function Zl(t){let e=t.split(/\s+/),s=[],o=0;for(;o<e.length;){let n=e.slice(o,o+Kr).join(" ");if(s.push({text:n,offset:o}),o+Kr>=e.length)break;o+=Kr-Kg}return s}async function eu(){let t=ts(),e={documents:{}},s=Yr();if(_e.existsSync(s))try{e=JSON.parse(_e.readFileSync(s,"utf-8"))}catch{}for(let o of t){let n=e.documents[o.name];if(n&&new Date(n.modified)>=o.modified)continue;let r=_e.readFileSync(o.path,"utf-8"),a=Zl(r),c=[];for(let l of a){let u=await Qr(l.text);c.push({text:l.text,embedding:u,offset:l.offset})}e.documents[o.name]={chunks:c,modified:o.modified.toISOString()}}for(let o of Object.keys(e.documents))t.some(n=>n.name===o)||delete e.documents[o];return _e.writeFileSync(s,JSON.stringify(e),"utf-8"),e}async function tu(t,e={}){let{topK:s=3,minSimilarity:o=.3}=e,n=Yr();if(!_e.existsSync(n))return[];let r;try{r=JSON.parse(_e.readFileSync(n,"utf-8"))}catch{return[]}let a=await Qr(t),c=[];for(let[l,u]of Object.entries(r.documents||{})){let d=0,f="";for(let m of u.chunks||[]){let h=Ql(a,m.embedding);h>d&&(d=h,f=m.text)}d>=o&&c.push({name:l,score:d,bestChunk:f})}return c.sort((l,u)=>u.score-l.score),c.slice(0,s)}function nu(t,e,s={}){let{k:o=60,topK:n=3}=s,r={};return t.forEach((a,c)=>{r[a.name]=(r[a.name]||0)+1/(o+c+1)}),e.forEach((a,c)=>{r[a.name]=(r[a.name]||0)+1/(o+c+1)}),Object.entries(r).map(([a,c])=>({name:a,score:c})).sort((a,c)=>c.score-a.score).slice(0,n)}async function su(t,e={}){let{topK:s=3,minScore:o=.1}=e,n=Xl(t,{topK:s,minScore:o}),r=n;if(process.env.NEX_BRAIN_EMBEDDINGS!=="false")try{if(await Vl()){let c=await tu(t,{topK:s});r=nu(n,c,{topK:s})}}catch{}return r.map(a=>{let c=zl(a.name),l=(c.body||c.content||"").slice(0,300).replace(/\n+/g," ")+"...";return{name:a.name,score:a.score,content:c.content,excerpt:l}})}async function zg(t){if(!t||!t.trim())return"";let e=vt.join(process.cwd(),".nex","brain");if(!_e.existsSync(e)||ts().length===0)return"";let o;try{o=await su(t,{topK:3})}catch{return""}if(!o||o.length===0)return"";let n;try{n=lt().estimateTokens}catch{n=l=>Math.ceil(l.length/4)}let r=25e3,a=[],c=0;for(let l of o){let u=l.content||"",d=n(u);if(c+d>r){let m=r-c;if(m<100)break;let h=m/d;u=u.slice(0,Math.floor(u.length*h))+`
|
|
180
|
+
...(truncated)`}let f=typeof l.score=="number"?l.score.toFixed(2):String(l.score);if(a.push(`--- ${l.name} (relevance: ${f}) ---
|
|
181
|
+
${u}`),c+=n(u),c>=r)break}return a.length===0?"":`KNOWLEDGE BASE (auto-selected):
|
|
182
|
+
|
|
183
|
+
${a.join(`
|
|
184
|
+
|
|
185
|
+
`)}`}ou.exports={getBrainDir:xn,listDocuments:ts,readDocument:zl,writeDocument:Ug,removeDocument:Bg,buildIndex:zr,getIndex:Yl,query:su,getBrainContext:zg,isEmbeddingAvailable:Vl,generateEmbedding:Qr,buildEmbeddingIndex:eu,semanticQuery:tu,cosineSimilarity:Ql,_keywordQuery:Xl,_extractKeywords:Xr,_chunkText:Zl,parseFrontmatter:ns,tokenize:uo,_fuseResults:nu}});var ti=q((x_,lu)=>{var os=require("fs"),Zr=require("path"),ei=process.env.NEX_AUDIT!=="false",Qt=null;function ru(){return Qt||(Qt=Zr.join(process.cwd(),".nex","audit"),os.existsSync(Qt)||os.mkdirSync(Qt,{recursive:!0}),Qt)}function iu(){let t=new Date().toISOString().split("T")[0];return Zr.join(ru(),`${t}.jsonl`)}function Yg(t){if(ei)try{let e={timestamp:new Date().toISOString(),tool:t.tool,args:au(t.args),resultLength:typeof t.result=="string"?t.result.length:0,resultPreview:typeof t.result=="string"?t.result.substring(0,200):"",duration:t.duration||0,success:t.success!==!1,model:t.model||null,provider:t.provider||null},s=JSON.stringify(e)+`
|
|
186
|
+
`;os.appendFileSync(iu(),s,"utf-8")}catch{}}function au(t){if(!t||typeof t!="object")return{};let e={};for(let[s,o]of Object.entries(t))/key|token|password|secret|credential/i.test(s)?e[s]="***":typeof o=="string"&&o.length>500?e[s]=o.substring(0,500)+`... (${o.length} chars)`:e[s]=o;return e}function cu(t={}){let e=ru(),s=t.days||1,o=[];for(let n=0;n<s;n++){let r=t.date||new Date(Date.now()-n*864e5).toISOString().split("T")[0],a=Zr.join(e,`${r}.jsonl`);if(!os.existsSync(a))continue;let c=os.readFileSync(a,"utf-8").split(`
|
|
187
|
+
`).filter(l=>l.trim());for(let l of c)try{let u=JSON.parse(l);if(t.tool&&u.tool!==t.tool)continue;o.push(u)}catch{}if(t.date)break}return o}function Xg(t=1){let e=cu({days:t});if(e.length===0)return{totalCalls:0,byTool:{},avgDuration:0,successRate:1};let s={},o=0,n=0;for(let r of e)s[r.tool]=(s[r.tool]||0)+1,o+=r.duration||0,r.success&&n++;return{totalCalls:e.length,byTool:s,avgDuration:Math.round(o/e.length),successRate:n/e.length}}function Jg(t){ei=t}function Vg(){return ei}function Qg(){Qt=null}lu.exports={logToolExecution:Yg,sanitizeArgs:au,readAuditLog:cu,getAuditSummary:Xg,setAuditEnabled:Jg,isAuditEnabled:Vg,getAuditLogPath:iu,_reset:Qg}});var ut=q((E_,bu)=>{var ke=require("fs").promises,uu=require("fs"),ce=require("path"),ae=require("util").promisify(require("child_process").exec),du=require("util").promisify(require("child_process").execFile),{spawnSync:Zg}=require("child_process"),ni=require("axios"),{isForbidden:e$,isDangerous:t$,isCritical:fu,isBashPathForbidden:n$,confirm:dt}=Ie(),{showClaudeDiff:po,showClaudeNewFile:s$,showEditDiff:v_,confirmFileChange:rs}=Tc(),{C:F,Spinner:o$,getToolSpinnerText:r$}=we(),{isGitRepo:si,getCurrentBranch:pu,getStatus:i$,getDiff:a$}=Xt(),{recordChange:mo}=_t(),{fuzzyFindText:mu,findMostSimilar:cs}=rl(),{runDiagnostics:is}=al(),{findFileInIndex:c$,getFileIndex:S_}=jr(),{resolveProfile:rt,sshExec:Be,scpUpload:l$,scpDownload:u$}=kn(),{resolveDeployConfig:d$,loadDeployConfigs:f$}=Ur(),{getEditMode:hu}=oo(),p$=/^(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/,m$=/^ssh\s/,h$=/^ssh(?:\s+-\S+)*\s+\S+@?\S+\s+["']?[^-]/;async function it(t){return ke.access(t).then(()=>!0).catch(()=>!1)}async function ho(t){if(!t)return{fixedPath:null,message:""};let e=t.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),s=He(e);if(s&&await it(s))return{fixedPath:s,message:`(auto-fixed path: ${t} \u2192 ${e})`};let o=[".js",".ts",".jsx",".tsx",".mjs",".cjs",".json"],n=ce.extname(t);if(!n)for(let a of o){let c=He(t+a);if(c&&await it(c))return{fixedPath:c,message:`(auto-fixed: added ${a} extension)`}}if(n){let a=t.replace(/\.[^.]+$/,"");for(let c of o){if(c===n)continue;let l=He(a+c);if(l&&await it(l))return{fixedPath:l,message:`(auto-fixed: ${n} \u2192 ${c})`}}}let r=ce.basename(t);if(r&&r.length>2)try{let a=c$(r).map(c=>He(c));if(a.length===1)return{fixedPath:a[0],message:`(auto-fixed: found ${r} at ${ce.relative(process.cwd(),a[0])})`};if(a.length>1&&a.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
|
|
188
|
+
${a.map(l=>ce.relative(process.cwd(),l)).map(l=>` - ${l}`).join(`
|
|
189
|
+
`)}`}}catch{}return{fixedPath:null,message:""}}function g$(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 yu(t,e){let s=[];if(/command not found|: not found|not recognized/i.test(t)){let o=e.match(/^(\S+)/),n=o?o[1]:"";/^(npx|npm|node|yarn|pnpm|bun)$/.test(n)?s.push("HINT: Node.js/npm may not be in PATH. Check your Node.js installation."):/^(python|python3|pip|pip3)$/.test(n)?s.push("HINT: Python may not be installed. Try: brew install python3 (macOS) or apt install python3 (Linux)"):s.push(`HINT: "${n}" is not installed. Try installing it with your package manager.`)}if(/Cannot find module|MODULE_NOT_FOUND/i.test(t)){let o=t.match(/Cannot find module '([^']+)'/),n=o?o[1]:"";n&&!n.startsWith(".")&&!n.startsWith("/")?s.push(`HINT: Missing npm package "${n}". Run: npm install ${n}`):s.push("HINT: Module not found. Check the import path or run npm install.")}if(/permission denied|EACCES/i.test(t)&&s.push("HINT: Permission denied. Check file permissions or try a different approach."),/EADDRINUSE|address already in use/i.test(t)){let o=t.match(/port (\d+)|:(\d+)/),n=o?o[1]||o[2]:"";s.push(`HINT: Port ${n||""} is already in use. Kill the process or use a different port.`)}if(/SyntaxError|Unexpected token/i.test(t)&&s.push("HINT: Syntax error in the code. Check the file at the line number shown above."),/TS\d{4}:/i.test(t)&&s.push("HINT: TypeScript compilation error. Fix the type issue at the indicated line."),/Test Suites:.*failed|Tests:.*failed/i.test(t)&&s.push("HINT: Test failures detected. Read the error output above to identify failing tests."),/fatal: not a git repository/i.test(t)&&s.push("HINT: Not inside a git repository. Run git init or cd to a git project."),/^curl\b/.test(e)){let o=t.match(/curl:\s*\((\d+)\)/),n=o?parseInt(o[1],10):null;n===6||/Could not resolve host/i.test(t)?s.push("HINT: Hostname could not be resolved. Check DNS or use an IP address directly."):n===7||/Failed to connect|Connection refused/i.test(t)?s.push("HINT: Service not running or port wrong. Check if the service is up and the port is correct."):n===22||/HTTP error/i.test(t)?s.push("HINT: HTTP 4xx/5xx response. The endpoint exists but returned an error status."):n===28||/timed out/i.test(t)?s.push("HINT: Request timed out. The host may be unreachable or the service is slow."):(n===35||/SSL.*error/i.test(t))&&s.push("HINT: SSL/TLS handshake failed. Try with --insecure to bypass, or check the certificate.")}if(/remote port forwarding failed/i.test(t)){let o=t.match(/port (\d+)/),n=o?o[1]:"";s.push(`HINT: SSH remote port forwarding failed for port ${n}. The port may already be bound on the server. Check with: ssh server "ss -tuln | grep ${n}" and kill any lingering process with that port.`)}return/bind.*Cannot assign requested address|Address already in use/i.test(t)&&s.push("HINT: Port is already in use. Find the process with: ss -tuln | grep <port> and kill it, then retry."),/Connection.*timed out|ssh.*timeout/i.test(t)&&/^ssh\b/.test(e)&&s.push("HINT: SSH connection timed out. Check if the host is reachable: ping <host> and verify the port with: nc -zv <host> 22"),/cp.*\$f.*\$f\.bak.*sed.*-i\.bak|sed.*-i\.bak.*cp.*\$f.*\$f\.bak/i.test(e)&&s.push('HINT: Using both cp with .bak and sed -i.bak creates double backups (.bak.bak). Choose one method: either cp "$f" "$f.bak" OR sed -i.bak, not both.'),s.length===0?t:t+`
|
|
190
190
|
|
|
191
191
|
`+s.join(`
|
|
192
|
-
`)}function $u(t,e,s){let o=cs(t,e);if(!o)return null;let n=Math.max(2,Math.ceil(e.length*.03));return o.distance>n?null:{autoFixed:!0,matchText:o.text,content:t.split(o.text).join(s),distance:o.distance,line:o.line}}var mu=!1,Zt=null;function f$(){Zt&&(Zt(),Zt=null)}var ri=null;function p$(t){ri=t}async function oi(){if(!mu){mu=!0;try{let{stdout:t}=await ae("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await ae('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await ae("git stash pop",{cwd:process.cwd(),timeout:1e4}),await ae("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var m$=[/\.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 He(t){let e=ce.isAbsolute(t)?ce.resolve(t):ce.resolve(process.cwd(),t);for(let s of m$)if(s.test(e))return null;return e}var h$=[{type:"function",function:{name:"bash",description:"Execute a bash command in the project directory. Timeout: 90s. Use for: running tests, installing packages, git commands, build tools, starting servers. Do NOT use bash for file operations when a dedicated tool exists \u2014 use read_file instead of cat, edit_file instead of sed, glob instead of find, grep instead of grep/rg. Always quote paths with spaces. Prefer specific commands over rm -rf. Destructive or dangerous commands require user confirmation.",parameters:{type:"object",properties:{command:{type:"string",description:"The bash command to execute"}},required:["command"]}}},{type:"function",function:{name:"read_file",description:"Read a file's contents with line numbers. Always read a file BEFORE editing it to see exact content. Use line_start/line_end for large files to read specific sections. Prefer this over bash cat/head/tail. Files are read with UTF-8 encoding. For binary files, use bash with appropriate flags. Alternative: use util.promisify(fs.readFile) for programmatic access.",parameters:{type:"object",properties:{path:{type:"string",description:"File path (relative or absolute)"},line_start:{type:"number",description:"Start line (1-based, optional)"},line_end:{type:"number",description:"End line (1-based, optional)"}},required:["path"]}}},{type:"function",function:{name:"write_file",description:"Create a new file or completely overwrite an existing file. For targeted changes to existing files, prefer edit_file or patch_file instead \u2014 they only send the diff and are safer. Only use write_file when creating new files or when the entire content needs to be replaced.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},content:{type:"string",description:"Full file content"}},required:["path","content"]}}},{type:"function",function:{name:"edit_file",description:"Replace specific text in a file. IMPORTANT: old_text must match the file content EXACTLY \u2014 including all whitespace, indentation (tabs vs spaces), and newlines. Always read_file first to see the exact content before editing. If old_text is not found, the edit fails. For multiple changes to the same file, prefer patch_file instead.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},old_text:{type:"string",description:"Exact text to find (must match file content precisely)"},new_text:{type:"string",description:"Replacement text"}},required:["path","old_text","new_text"]}}},{type:"function",function:{name:"list_directory",description:"List files and directories in a tree view. Use this to understand project structure. For finding specific files by pattern, prefer glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory path"},max_depth:{type:"number",description:"Max depth (default: 2)"},pattern:{type:"string",description:"File filter glob (e.g. '*.js')"}},required:["path"]}}},{type:"function",function:{name:"search_files",description:"Search for a text pattern across files (regex). Returns matching lines with file paths. For simple content search, grep is equivalent. For finding files by name, use glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory to search"},pattern:{type:"string",description:"Search pattern (regex)"},file_pattern:{type:"string",description:"File filter (e.g. '*.js')"}},required:["path","pattern"]}}},{type:"function",function:{name:"glob",description:"Find files matching a glob pattern. Fast file search by name/extension. Use this to find files before reading them. Examples: '**/*.test.js' (all test files), 'src/**/*.ts' (all TypeScript in src). Prefer this over bash find/ls.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Glob pattern (e.g. '**/*.ts', 'src/**/*.test.js')"},path:{type:"string",description:"Base directory (default: project root)"}},required:["pattern"]}}},{type:"function",function:{name:"grep",description:"Search file contents with regex. Returns matching lines with file paths and line numbers. Supports output modes (content/files_with_matches/count), context lines, head_limit, offset, type filter, and multiline. Prefer this over bash grep/rg.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Regex pattern to search for"},path:{type:"string",description:"Directory or file to search (default: project root)"},include:{type:"string",description:"File filter glob (e.g. '*.js', '*.ts')"},ignore_case:{type:"boolean",description:"Case-insensitive search"},output_mode:{type:"string",enum:["content","files_with_matches","count"],description:"Output mode: content (matching lines), files_with_matches (file paths only), count (match counts). Default: content"},context:{type:"number",description:"Lines of context around each match (like grep -C)"},before_context:{type:"number",description:"Lines before each match (like grep -B)"},after_context:{type:"number",description:"Lines after each match (like grep -A)"},head_limit:{type:"number",description:"Limit output to first N results"},offset:{type:"number",description:"Skip first N results"},type:{type:"string",description:"File type filter (e.g. 'js', 'py', 'ts') \u2014 maps to --include='*.ext'"},multiline:{type:"boolean",description:"Enable multiline matching (grep -Pz)"}},required:["pattern"]}}},{type:"function",function:{name:"patch_file",description:"Apply multiple text replacements to a file atomically. All patches are validated before any are applied \u2014 if one fails, none are written. Prefer this over multiple edit_file calls when making several changes to the same file. Like edit_file, all old_text values must match exactly.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},patches:{type:"array",description:"Array of { old_text, new_text } replacements to apply in order",items:{type:"object",properties:{old_text:{type:"string",description:"Text to find"},new_text:{type:"string",description:"Replacement text"}},required:["old_text","new_text"]}}},required:["path","patches"]}}},{type:"function",function:{name:"web_fetch",description:"Fetch content from a URL and return text. HTML tags are stripped. Use for reading documentation, API responses, or web pages. Will not work with authenticated/private URLs.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to fetch"},max_length:{type:"number",description:"Max response length in chars (default: 10000)"}},required:["url"]}}},{type:"function",function:{name:"web_search",description:"Search the web. Uses Perplexity (grounded, AI-summarized) if PERPLEXITY_API_KEY is set, otherwise DuckDuckGo. Returns titles, URLs, and summaries. Use to find documentation, solutions, or current information beyond your knowledge cutoff.",parameters:{type:"object",properties:{query:{type:"string",description:"Search query"},max_results:{type:"number",description:"Max results (default: 5)"}},required:["query"]}}},{type:"function",function:{name:"browser_open",description:"Open a URL in a headless browser and return the page title, text content, and links. More reliable than web_fetch for JavaScript-heavy pages. Requires playwright (npm install playwright && npx playwright install chromium).",parameters:{type:"object",properties:{url:{type:"string",description:"URL to open"},wait_for:{type:"string",enum:["domcontentloaded","networkidle","load"],description:"When to consider page loaded (default: domcontentloaded)"}},required:["url"]}}},{type:"function",function:{name:"browser_screenshot",description:"Take a screenshot of a URL in a headless browser. Returns the screenshot file path. The path can be pasted into the next message for visual analysis. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot"},full_page:{type:"boolean",description:"Capture full page (default: false \u2014 viewport only)"},width:{type:"number",description:"Viewport width in px (default: 1280)"},height:{type:"number",description:"Viewport height in px (default: 800)"}},required:["url"]}}},{type:"function",function:{name:"browser_click",description:"Click an element on a web page (by CSS selector or visible text). Returns the new URL after navigation. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of element to click (mutually exclusive with text)"},text:{type:"string",description:"Visible text of element to click (mutually exclusive with selector)"}},required:["url"]}}},{type:"function",function:{name:"browser_fill",description:"Fill a form field on a web page and optionally submit. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of the input field"},value:{type:"string",description:"Value to fill in"},submit:{type:"boolean",description:"Press Enter to submit after filling (default: false)"}},required:["url","selector","value"]}}},{type:"function",function:{name:"ask_user",description:"Ask the user a clarifying question with 2-3 specific options. Use when the user's intent is ambiguous. Always provide concrete, actionable options. The user can select an option or type a custom answer.",parameters:{type:"object",properties:{question:{type:"string",description:"The clarifying question to ask"},options:{type:"array",items:{type:"string"},description:"2-3 specific, actionable answer options for the user to choose from",minItems:1,maxItems:3}},required:["question","options"]}}},{type:"function",function:{name:"git_status",description:"Get git status: current branch, changed files, staged/unstaged state. Use before git operations to understand the current state.",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"git_diff",description:"Get git diff for changed files. Shows additions and deletions.",parameters:{type:"object",properties:{staged:{type:"boolean",description:"Show only staged changes (default: false)"},file:{type:"string",description:"Diff specific file only (optional)"}},required:[]}}},{type:"function",function:{name:"git_log",description:"Show recent git commits (short format).",parameters:{type:"object",properties:{count:{type:"number",description:"Number of commits to show (default: 10)"},file:{type:"string",description:"Show commits for specific file (optional)"}},required:[]}}},{type:"function",function:{name:"task_list",description:"Create and manage a task list for complex multi-step tasks. Use for tasks with 3+ steps to track progress. Actions: create (new list with tasks), update (mark task in_progress/done/failed), get (view current list). Always update task status as you work.",parameters:{type:"object",properties:{action:{type:"string",enum:["create","update","get"],description:"Action to perform"},name:{type:"string",description:"Task list name (for create)"},tasks:{type:"array",description:"Array of tasks to create (for create)",items:{type:"object",properties:{description:{type:"string",description:"Task description"},depends_on:{type:"array",items:{type:"string"},description:"IDs of prerequisite tasks"}},required:["description"]}},task_id:{type:"string",description:"Task ID to update (for update)"},status:{type:"string",enum:["in_progress","done","failed"],description:"New status (for update)"},result:{type:"string",description:"Result summary (for update, optional)"}},required:["action"]}}},{type:"function",function:{name:"gh_run_list",description:"List recent GitHub Actions workflow runs for this repository. Shows run status, conclusion, branch, and timing. Use to check CI/CD status or find a run ID.",parameters:{type:"object",properties:{limit:{type:"number",description:"Number of runs to show (default: 10, max: 30)"},workflow:{type:"string",description:"Filter by workflow name or filename (optional)"},branch:{type:"string",description:"Filter by branch name (optional)"},status:{type:"string",enum:["completed","in_progress","queued","failure","success"],description:"Filter by status (optional)"}},required:[]}}},{type:"function",function:{name:"gh_run_view",description:"View details of a specific GitHub Actions workflow run: steps, logs, errors. Use gh_run_list first to get the run ID.",parameters:{type:"object",properties:{run_id:{type:"string",description:"The run ID (from gh_run_list)"},log:{type:"boolean",description:"Include full log output (default: false \u2014 shows step summary only)"}},required:["run_id"]}}},{type:"function",function:{name:"gh_workflow_trigger",description:"Trigger a GitHub Actions workflow dispatch event. Only works for workflows with workflow_dispatch trigger. Requires user confirmation.",parameters:{type:"object",properties:{workflow:{type:"string",description:"Workflow filename (e.g. ci.yml) or name"},branch:{type:"string",description:"Branch to run on (default: current branch)"},inputs:{type:"object",description:"Workflow input parameters as key-value pairs (optional)"}},required:["workflow"]}}},{type:"function",function:{name:"spawn_agents",description:"Run multiple independent sub-agents in parallel (max 5 at top level, max 2 when called from within a sub-agent). Each agent has its own conversation context. Use when 2+ tasks can run simultaneously \u2014 e.g. reading multiple files, analyzing separate modules, independent research. Do NOT use for tasks that depend on each other or modify the same file. Keep task descriptions specific and self-contained. SWARM PATTERN: Sub-agents can call spawn_agents once (max nesting depth 2) to enable Architect\u2192Coder\u2192Reviewer pipelines: a coder agent spawns 1-2 reviewer agents that validate and fix its own output before returning results to the parent.",parameters:{type:"object",properties:{agents:{type:"array",description:"Array of agent definitions to run in parallel (max 5)",items:{type:"object",properties:{task:{type:"string",description:"Task description for the agent"},context:{type:"string",description:"Additional context (optional)"},max_iterations:{type:"number",description:"Max iterations (default: 10, max: 15)"},model:{type:"string",description:'Override model for this agent (provider:model, e.g. "anthropic:claude-haiku"). Auto-selected if omitted.'}},required:["task"]}}},required:["agents"]}}},{type:"function",function:{name:"switch_model",description:"Switch the active AI model mid-conversation. Use when a different model is better for the next steps \u2014 e.g. switch to a fast model for simple lookups, or a more capable model for complex refactoring. The switch persists for all subsequent turns.",parameters:{type:"object",properties:{model:{type:"string",description:'Model spec: "provider:model" (e.g. "ollama:devstral-small-2:24b") or just model name'}},required:["model"]}}},{type:"function",function:{name:"k8s_pods",description:"List Kubernetes pods. Shows pod name, status, restarts, and age. Runs kubectl locally or via SSH on a remote server. Use namespace to filter, or omit for all namespaces.",parameters:{type:"object",properties:{namespace:{type:"string",description:"Namespace to list pods in (default: all namespaces)"},label:{type:"string",description:'Label selector filter (e.g. "app=nginx")'},context:{type:"string",description:"kubectl context to use (optional)"},server:{type:"string",description:"Remote server as user@host to run kubectl via SSH (optional, local kubectl if omitted)"}},required:[]}}},{type:"function",function:{name:"k8s_logs",description:'Fetch logs from a Kubernetes pod. Use tail to limit output, since for time-based filtering (e.g. "1h", "30m").',parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (required if pod has multiple containers)"},tail:{type:"number",description:"Number of recent lines to show (default: 100)"},since:{type:"string",description:'Show logs since duration (e.g. "1h", "30m", "5s")'},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod"]}}},{type:"function",function:{name:"k8s_exec",description:"Execute a command inside a running Kubernetes pod (kubectl exec). Requires user confirmation. Use for inspecting container state, reading configs, or debugging.",parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},command:{type:"string",description:'Command to run in the pod (e.g. "env", "ls /app", "cat /etc/config.yaml")'},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (optional)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod","command"]}}},{type:"function",function:{name:"k8s_apply",description:"Apply a Kubernetes manifest file (kubectl apply -f). Requires confirmation before applying to the cluster. Use dry_run=true to validate without applying.",parameters:{type:"object",properties:{file:{type:"string",description:"Path to manifest YAML file (relative or absolute)"},namespace:{type:"string",description:"Override namespace (optional)"},dry_run:{type:"boolean",description:"Validate only without applying (default: false)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["file"]}}},{type:"function",function:{name:"k8s_rollout",description:"Manage Kubernetes deployment rollouts: check status, restart (rolling update), view history, or undo (rollback). Restart and undo require confirmation.",parameters:{type:"object",properties:{action:{type:"string",enum:["status","restart","history","undo"],description:"Action: status (check rollout progress), restart (rolling restart), history (show revision history), undo (rollback to previous revision)"},deployment:{type:"string",description:"Deployment name"},namespace:{type:"string",description:"Namespace (default: default)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["action","deployment"]}}},{type:"function",function:{name:"brain_write",description:"Write or update a knowledge document in the project brain (.nex/brain/). Use this to persist important findings, architecture decisions, debugging insights, or conventions discovered during the session. The user can review changes via /brain review or git diff.",parameters:{type:"object",properties:{name:{type:"string",description:'Document name (without .md extension). Use kebab-case. Examples: "api-auth-flow", "db-schema-notes", "deployment-checklist"'},content:{type:"string",description:"Full Markdown content. Use headings (#), lists (-), and code blocks. Include optional YAML frontmatter with tags."},mode:{type:"string",enum:["create","update","append"],description:"create: new document (fails if exists). update: overwrite existing. append: add to end of existing document."}},required:["name","content","mode"]}}},{type:"function",function:{name:"ssh_exec",description:'Execute a command on a remote server via SSH. Server is a profile name from .nex/servers.json (e.g. "prod") or "user@host". Use for: checking status, reading logs, running deployments. Destructive commands (restart, delete, modify config) require confirmation. For service management prefer service_manage; for logs prefer service_logs.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name (from .nex/servers.json) or "user@host"'},command:{type:"string",description:"Shell command to run on the remote server"},sudo:{type:"boolean",description:"Run command with sudo (only if profile has sudo:true). Default: false"},timeout:{type:"number",description:"Timeout in seconds. Default: 30"}},required:["server","command"]}}},{type:"function",function:{name:"ssh_upload",description:"Upload a local file or directory to a remote server via SCP. Recursive for directories. Requires confirmation before upload.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},local_path:{type:"string",description:"Local path to upload (file or directory)"},remote_path:{type:"string",description:"Destination path on the remote server (absolute preferred)"}},required:["server","local_path","remote_path"]}}},{type:"function",function:{name:"ssh_download",description:"Download a file or directory from a remote server via SCP. Recursive for directories.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},remote_path:{type:"string",description:"Path on the remote server to download"},local_path:{type:"string",description:"Local destination path"}},required:["server","remote_path","local_path"]}}},{type:"function",function:{name:"remote_agent",description:'Delegate a coding task to nex-code running on a remote server. Use this when the task involves server-side projects (musikschule, stadtkapelle, cahill, schoensgibl, jarvis) that live on almalinux9/jarvis. Runs nex-code --auto on the server and streams output. Server is a profile name from .nex/servers.json or "user@host".',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name from .nex/servers.json (e.g. "almalinux9") or "user@host"'},task:{type:"string",description:"The full task description to run on the remote nex-code"},project_path:{type:"string",description:"Working directory on the remote server (e.g. /home/jarvis/jarvis-agent). Defaults to home directory."},model:{type:"string",description:"Model to use on remote nex-code (e.g. qwen3-coder:480b). Defaults to server default."}},required:["server","task"]}}},{type:"function",function:{name:"service_manage",description:"Manage a systemd service on a remote (or local) server. Uses systemctl. Status is read-only; start/stop/restart/reload/enable/disable require confirmation. For AlmaLinux 9: runs via SSH with sudo if configured.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn", "postgresql")'},action:{type:"string",enum:["status","start","stop","restart","reload","enable","disable"],description:"systemctl action to perform"}},required:["service","action"]}}},{type:"function",function:{name:"service_logs",description:"Fetch systemd service logs via journalctl. Works on AlmaLinux 9 and any systemd Linux. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn")'},lines:{type:"number",description:"Number of recent log lines to fetch. Default: 50"},since:{type:"string",description:'Time filter, e.g. "1 hour ago", "today", "2024-01-01 12:00". Optional.'},follow:{type:"boolean",description:"Tail logs in real-time (follow mode). Default: false"}},required:["service"]}}},{type:"function",function:{name:"container_list",description:"List Docker containers on a server (or locally). Shows container ID, name, image, status, and ports. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},all:{type:"boolean",description:"Show all containers including stopped ones. Default: false (running only)."}},required:[]}}},{type:"function",function:{name:"container_logs",description:"Fetch logs from a Docker container on a server (or locally). Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},lines:{type:"number",description:"Number of recent log lines. Default: 50."},since:{type:"string",description:'Time filter, e.g. "1h", "30m", "2024-01-01T12:00:00". Optional.'}},required:["container"]}}},{type:"function",function:{name:"container_exec",description:"Execute a command inside a running Docker container. Destructive or state-changing commands require confirmation.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},command:{type:"string",description:'Command to run inside the container (e.g. "cat /etc/nginx/nginx.conf").'}},required:["container","command"]}}},{type:"function",function:{name:"container_manage",description:'Start, stop, restart, or remove a Docker container. All actions except "inspect" require confirmation.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},action:{type:"string",enum:["start","stop","restart","remove","inspect"],description:"Action to perform on the container."}},required:["container","action"]}}},{type:"function",function:{name:"frontend_recon",description:"MANDATORY first step before creating or significantly modifying any frontend file (HTML template, Vue/React component, CSS). Scans the project and returns: (1) design tokens \u2014 CSS variables, Tailwind theme colors/fonts, (2) main layout/index page structure, (3) a reference component of the same type, (4) detected JS/CSS framework stack. Call this BEFORE writing any markup or styles. Never skip it for frontend tasks.",parameters:{type:"object",properties:{type:{type:"string",description:'Type of frontend file you are about to create. Used to find a relevant reference component. Examples: "list", "form", "detail", "dashboard", "modal", "component". Optional but improves reference quality.'}},required:[]}}},{type:"function",function:{name:"deploy",description:'Deploy to a remote server. Supports two methods: "rsync" (sync local files) and "git" (git pull on remote). Can use a named config from .nex/deploy.json. Requires confirmation before executing.',parameters:{type:"object",properties:{config:{type:"string",description:'Named deploy config from .nex/deploy.json (e.g. "prod"). Overrides all other params if provided.'},method:{type:"string",enum:["rsync","git"],description:'Deploy method: "rsync" syncs local files (default), "git" runs git pull on the remote.'},server:{type:"string",description:'Profile name or "user@host". Required if no config.'},remote_path:{type:"string",description:"Remote project directory. Required for git method; destination path for rsync."},local_path:{type:"string",description:"Local directory or file to sync. Required for rsync method."},branch:{type:"string",description:"Branch to pull (git method only). Defaults to current remote branch."},deploy_script:{type:"string",description:'Shell command(s) to run on the remote after sync/pull (e.g. "npm ci && systemctl restart myapp"). Optional.'},health_check:{type:"string",description:"URL (HTTP GET) or shell command to verify the service is healthy after deploy. If it fails, the deploy is marked as failed. Optional."},exclude:{type:"array",items:{type:"string"},description:"Paths to exclude from rsync. Optional."},dry_run:{type:"boolean",description:"Show what would happen without executing. Default: false."}},required:[]}}},{type:"function",function:{name:"deployment_status",description:"Check deployment status across all configured servers. Reads .nex/deploy.json configs and checks service health on each server. Returns a status summary table.",parameters:{type:"object",properties:{config:{type:"string",description:"Specific deploy config name to check (optional \u2014 checks all if omitted)"}},required:[]}}},{type:"function",function:{name:"sysadmin",description:"Senior sysadmin operations on a remote (or local) Linux server. Covers: system audit, disk_usage, process_list, network_status, package management (dnf/apt), user management, firewall (firewalld/ufw/iptables), cron, SSL cert checks, log tailing, large file discovery, systemd service management, process kill, journalctl log querying. Read-only actions run without confirmation; state-changing actions require user approval.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},action:{type:"string",enum:["audit","disk_usage","process_list","network_status","package","user_manage","firewall","cron","ssl_check","log_tail","find_large","service","kill_process","journalctl"],description:"Sysadmin operation. audit=full health overview; disk_usage=df+du; process_list=top procs; network_status=open ports; package=dnf/apt; user_manage=users/keys; firewall=rules; cron=crontab; ssl_check=cert expiry+days; log_tail=tail any log; find_large=big files; service=systemd unit management; kill_process=kill by PID or name; journalctl=query system journal."},path:{type:"string",description:"File or directory path. For disk_usage (default /), log_tail (required), find_large (default /)."},lines:{type:"number",description:"Lines to tail for log_tail or journalctl. Default: 100."},limit:{type:"number",description:"Result count for process_list (default 20) or find_large (default 20)."},sort_by:{type:"string",enum:["cpu","mem"],description:"Sort order for process_list. Default: cpu."},min_size:{type:"string",description:'Minimum file size for find_large. Default: "100M". Examples: "50M", "1G".'},package_action:{type:"string",enum:["install","remove","update","list","upgrade"],description:"Package sub-action for action=package."},packages:{type:"array",items:{type:"string"},description:"Package name(s) for install/remove/update."},user_action:{type:"string",enum:["list","create","delete","add_ssh_key","info"],description:"User sub-action for action=user_manage."},user:{type:"string",description:"Linux username for user_manage or cron."},groups:{type:"array",items:{type:"string"},description:'Groups to assign on user create (e.g. ["sudo", "docker"]).'},ssh_key:{type:"string",description:"SSH public key string to add for user_action=add_ssh_key."},firewall_action:{type:"string",enum:["status","allow","deny","remove","reload"],description:"Firewall sub-action for action=firewall."},port:{type:"string",description:'Port/protocol for firewall rules, e.g. "80/tcp", "443", "8080/udp".'},cron_action:{type:"string",enum:["list","add","remove"],description:"Cron sub-action for action=cron."},schedule:{type:"string",description:'Cron schedule expression for cron add, e.g. "0 2 * * *".'},command:{type:"string",description:"Command for cron add, or substring to match for cron remove."},domain:{type:"string",description:`Domain for ssl_check (e.g. "example.com"). Auto-detects Let's Encrypt cert on server; falls back to live TLS probe.`},cert_path:{type:"string",description:'Explicit path to cert file on server for ssl_check (e.g. "/etc/letsencrypt/live/x/cert.pem").'},service_name:{type:"string",description:'Systemd unit name for action=service (e.g. "nginx", "jarvis-api", "gunicorn"). .service suffix optional.'},service_action:{type:"string",enum:["status","start","stop","restart","reload","enable","disable","list_failed"],description:"Sub-action for action=service. list_failed shows all failed units."},pid:{type:"number",description:"Process ID to kill for action=kill_process."},process_name:{type:"string",description:"Process name to kill (uses pkill) for action=kill_process. Use with pid for safety."},signal:{type:"string",enum:["SIGTERM","SIGKILL","SIGHUP","SIGINT"],description:"Signal for kill_process. Default: SIGTERM."},unit:{type:"string",description:'Systemd unit to filter for journalctl (e.g. "nginx", "jarvis-api"). Omit for system-wide.'},since:{type:"string",description:'Time filter for journalctl, e.g. "1 hour ago", "today", "2026-03-17 10:00". Default: last 200 lines.'},priority:{type:"string",enum:["emerg","alert","crit","err","warning","notice","info","debug"],description:"Minimum log priority for journalctl. Default: no filter."}},required:["action"]}}}];function as(t,{server:e,context:s}={}){let o=e?e.replace(/[^a-zA-Z0-9@._-]/g,""):null,n=s?s.replace(/[^a-zA-Z0-9._/-]/g,""):null,r="kubectl";if(n&&(r+=` --context ${n}`),r+=` ${t}`,o){let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`ssh -o ConnectTimeout=10 -o BatchMode=yes ${o} "${i}"`}return r}async function hu(t,e,s={}){switch(t){case"bash":{let o=e.command,n=Jg(o);if(n){let d=d$(o);return`BLOCKED: Command matches forbidden pattern: ${n}${d?`
|
|
193
|
-
HINT: ${
|
|
194
|
-
${
|
|
195
|
-
${
|
|
196
|
-
`+w.message:""}`}let r=Buffer.alloc(8192),
|
|
192
|
+
`)}function wu(t,e,s){let o=cs(t,e);if(!o)return null;let n=Math.max(2,Math.ceil(e.length*.03));return o.distance>n?null:{autoFixed:!0,matchText:o.text,content:t.split(o.text).join(s),distance:o.distance,line:o.line}}var gu=!1,Zt=null;function $$(){Zt&&(Zt(),Zt=null)}var ri=null;function y$(t){ri=t}async function oi(){if(!gu){gu=!0;try{let{stdout:t}=await ae("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await ae('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await ae("git stash pop",{cwd:process.cwd(),timeout:1e4}),await ae("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var w$=[/\.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 He(t){let e=ce.isAbsolute(t)?ce.resolve(t):ce.resolve(process.cwd(),t);for(let s of w$)if(s.test(e))return null;return e}var b$=[{type:"function",function:{name:"bash",description:"Execute a bash command in the project directory. Timeout: 90s. Use for: running tests, installing packages, git commands, build tools, starting servers. Do NOT use bash for file operations when a dedicated tool exists \u2014 use read_file instead of cat, edit_file instead of sed, glob instead of find, grep instead of grep/rg. Always quote paths with spaces. Prefer specific commands over rm -rf. Destructive or dangerous commands require user confirmation.",parameters:{type:"object",properties:{command:{type:"string",description:"The bash command to execute"}},required:["command"]}}},{type:"function",function:{name:"read_file",description:"Read a file's contents with line numbers. Always read a file BEFORE editing it to see exact content. Use line_start/line_end for large files to read specific sections. Prefer this over bash cat/head/tail. Files are read with UTF-8 encoding. For binary files, use bash with appropriate flags. Alternative: use util.promisify(fs.readFile) for programmatic access.",parameters:{type:"object",properties:{path:{type:"string",description:"File path (relative or absolute)"},line_start:{type:"number",description:"Start line (1-based, optional)"},line_end:{type:"number",description:"End line (1-based, optional)"}},required:["path"]}}},{type:"function",function:{name:"write_file",description:"Create a new file or completely overwrite an existing file. For targeted changes to existing files, prefer edit_file or patch_file instead \u2014 they only send the diff and are safer. Only use write_file when creating new files or when the entire content needs to be replaced.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},content:{type:"string",description:"Full file content"}},required:["path","content"]}}},{type:"function",function:{name:"edit_file",description:"Replace specific text in a file. IMPORTANT: old_text must match the file content EXACTLY \u2014 including all whitespace, indentation (tabs vs spaces), and newlines. Always read_file first to see the exact content before editing. If old_text is not found, the edit fails. For multiple changes to the same file, prefer patch_file instead.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},old_text:{type:"string",description:"Exact text to find (must match file content precisely)"},new_text:{type:"string",description:"Replacement text"}},required:["path","old_text","new_text"]}}},{type:"function",function:{name:"list_directory",description:"List files and directories in a tree view. Use this to understand project structure. For finding specific files by pattern, prefer glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory path"},max_depth:{type:"number",description:"Max depth (default: 2)"},pattern:{type:"string",description:"File filter glob (e.g. '*.js')"}},required:["path"]}}},{type:"function",function:{name:"search_files",description:"Search for a text pattern across files (regex). Returns matching lines with file paths. For simple content search, grep is equivalent. For finding files by name, use glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory to search"},pattern:{type:"string",description:"Search pattern (regex)"},file_pattern:{type:"string",description:"File filter (e.g. '*.js')"}},required:["path","pattern"]}}},{type:"function",function:{name:"glob",description:"Find files matching a glob pattern. Fast file search by name/extension. Use this to find files before reading them. Examples: '**/*.test.js' (all test files), 'src/**/*.ts' (all TypeScript in src). Prefer this over bash find/ls.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Glob pattern (e.g. '**/*.ts', 'src/**/*.test.js')"},path:{type:"string",description:"Base directory (default: project root)"}},required:["pattern"]}}},{type:"function",function:{name:"grep",description:"Search file contents with regex. Returns matching lines with file paths and line numbers. Supports output modes (content/files_with_matches/count), context lines, head_limit, offset, type filter, and multiline. Prefer this over bash grep/rg.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Regex pattern to search for"},path:{type:"string",description:"Directory or file to search (default: project root)"},include:{type:"string",description:"File filter glob (e.g. '*.js', '*.ts')"},ignore_case:{type:"boolean",description:"Case-insensitive search"},output_mode:{type:"string",enum:["content","files_with_matches","count"],description:"Output mode: content (matching lines), files_with_matches (file paths only), count (match counts). Default: content"},context:{type:"number",description:"Lines of context around each match (like grep -C)"},before_context:{type:"number",description:"Lines before each match (like grep -B)"},after_context:{type:"number",description:"Lines after each match (like grep -A)"},head_limit:{type:"number",description:"Limit output to first N results"},offset:{type:"number",description:"Skip first N results"},type:{type:"string",description:"File type filter (e.g. 'js', 'py', 'ts') \u2014 maps to --include='*.ext'"},multiline:{type:"boolean",description:"Enable multiline matching (grep -Pz)"}},required:["pattern"]}}},{type:"function",function:{name:"patch_file",description:"Apply multiple text replacements to a file atomically. All patches are validated before any are applied \u2014 if one fails, none are written. Prefer this over multiple edit_file calls when making several changes to the same file. Like edit_file, all old_text values must match exactly.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},patches:{type:"array",description:"Array of { old_text, new_text } replacements to apply in order",items:{type:"object",properties:{old_text:{type:"string",description:"Text to find"},new_text:{type:"string",description:"Replacement text"}},required:["old_text","new_text"]}}},required:["path","patches"]}}},{type:"function",function:{name:"web_fetch",description:"Fetch content from a URL and return text. HTML tags are stripped. Use for reading documentation, API responses, or web pages. Will not work with authenticated/private URLs.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to fetch"},max_length:{type:"number",description:"Max response length in chars (default: 10000)"}},required:["url"]}}},{type:"function",function:{name:"web_search",description:"Search the web. Uses Perplexity (grounded, AI-summarized) if PERPLEXITY_API_KEY is set, otherwise DuckDuckGo. Returns titles, URLs, and summaries. Use to find documentation, solutions, or current information beyond your knowledge cutoff.",parameters:{type:"object",properties:{query:{type:"string",description:"Search query"},max_results:{type:"number",description:"Max results (default: 5)"}},required:["query"]}}},{type:"function",function:{name:"browser_open",description:"Open a URL in a headless browser and return the page title, text content, and links. More reliable than web_fetch for JavaScript-heavy pages. Requires playwright (npm install playwright && npx playwright install chromium).",parameters:{type:"object",properties:{url:{type:"string",description:"URL to open"},wait_for:{type:"string",enum:["domcontentloaded","networkidle","load"],description:"When to consider page loaded (default: domcontentloaded)"}},required:["url"]}}},{type:"function",function:{name:"browser_screenshot",description:"Take a screenshot of a URL in a headless browser. Returns the screenshot file path. The path can be pasted into the next message for visual analysis. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot"},full_page:{type:"boolean",description:"Capture full page (default: false \u2014 viewport only)"},width:{type:"number",description:"Viewport width in px (default: 1280)"},height:{type:"number",description:"Viewport height in px (default: 800)"}},required:["url"]}}},{type:"function",function:{name:"browser_click",description:"Click an element on a web page (by CSS selector or visible text). Returns the new URL after navigation. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of element to click (mutually exclusive with text)"},text:{type:"string",description:"Visible text of element to click (mutually exclusive with selector)"}},required:["url"]}}},{type:"function",function:{name:"browser_fill",description:"Fill a form field on a web page and optionally submit. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of the input field"},value:{type:"string",description:"Value to fill in"},submit:{type:"boolean",description:"Press Enter to submit after filling (default: false)"}},required:["url","selector","value"]}}},{type:"function",function:{name:"ask_user",description:"Ask the user a clarifying question with 2-3 specific options. Use when the user's intent is ambiguous. Always provide concrete, actionable options. The user can select an option or type a custom answer.",parameters:{type:"object",properties:{question:{type:"string",description:"The clarifying question to ask"},options:{type:"array",items:{type:"string"},description:"2-3 specific, actionable answer options for the user to choose from",minItems:1,maxItems:3}},required:["question","options"]}}},{type:"function",function:{name:"git_status",description:"Get git status: current branch, changed files, staged/unstaged state. Use before git operations to understand the current state.",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"git_diff",description:"Get git diff for changed files. Shows additions and deletions.",parameters:{type:"object",properties:{staged:{type:"boolean",description:"Show only staged changes (default: false)"},file:{type:"string",description:"Diff specific file only (optional)"}},required:[]}}},{type:"function",function:{name:"git_log",description:"Show recent git commits (short format).",parameters:{type:"object",properties:{count:{type:"number",description:"Number of commits to show (default: 10)"},file:{type:"string",description:"Show commits for specific file (optional)"}},required:[]}}},{type:"function",function:{name:"task_list",description:"Create and manage a task list for complex multi-step tasks. Use for tasks with 3+ steps to track progress. Actions: create (new list with tasks), update (mark task in_progress/done/failed), get (view current list). Always update task status as you work.",parameters:{type:"object",properties:{action:{type:"string",enum:["create","update","get"],description:"Action to perform"},name:{type:"string",description:"Task list name (for create)"},tasks:{type:"array",description:"Array of tasks to create (for create)",items:{type:"object",properties:{description:{type:"string",description:"Task description"},depends_on:{type:"array",items:{type:"string"},description:"IDs of prerequisite tasks"}},required:["description"]}},task_id:{type:"string",description:"Task ID to update (for update)"},status:{type:"string",enum:["in_progress","done","failed"],description:"New status (for update)"},result:{type:"string",description:"Result summary (for update, optional)"}},required:["action"]}}},{type:"function",function:{name:"gh_run_list",description:"List recent GitHub Actions workflow runs for this repository. Shows run status, conclusion, branch, and timing. Use to check CI/CD status or find a run ID.",parameters:{type:"object",properties:{limit:{type:"number",description:"Number of runs to show (default: 10, max: 30)"},workflow:{type:"string",description:"Filter by workflow name or filename (optional)"},branch:{type:"string",description:"Filter by branch name (optional)"},status:{type:"string",enum:["completed","in_progress","queued","failure","success"],description:"Filter by status (optional)"}},required:[]}}},{type:"function",function:{name:"gh_run_view",description:"View details of a specific GitHub Actions workflow run: steps, logs, errors. Use gh_run_list first to get the run ID.",parameters:{type:"object",properties:{run_id:{type:"string",description:"The run ID (from gh_run_list)"},log:{type:"boolean",description:"Include full log output (default: false \u2014 shows step summary only)"}},required:["run_id"]}}},{type:"function",function:{name:"gh_workflow_trigger",description:"Trigger a GitHub Actions workflow dispatch event. Only works for workflows with workflow_dispatch trigger. Requires user confirmation.",parameters:{type:"object",properties:{workflow:{type:"string",description:"Workflow filename (e.g. ci.yml) or name"},branch:{type:"string",description:"Branch to run on (default: current branch)"},inputs:{type:"object",description:"Workflow input parameters as key-value pairs (optional)"}},required:["workflow"]}}},{type:"function",function:{name:"spawn_agents",description:"Run multiple independent sub-agents in parallel (max 5 at top level, max 2 when called from within a sub-agent). Each agent has its own conversation context. Use when 2+ tasks can run simultaneously \u2014 e.g. reading multiple files, analyzing separate modules, independent research. Do NOT use for tasks that depend on each other or modify the same file. Keep task descriptions specific and self-contained. SWARM PATTERN: Sub-agents can call spawn_agents once (max nesting depth 2) to enable Architect\u2192Coder\u2192Reviewer pipelines: a coder agent spawns 1-2 reviewer agents that validate and fix its own output before returning results to the parent.",parameters:{type:"object",properties:{agents:{type:"array",description:"Array of agent definitions to run in parallel (max 5)",items:{type:"object",properties:{task:{type:"string",description:"Task description for the agent"},context:{type:"string",description:"Additional context (optional)"},max_iterations:{type:"number",description:"Max iterations (default: 10, max: 15)"},model:{type:"string",description:'Override model for this agent (provider:model, e.g. "anthropic:claude-haiku"). Auto-selected if omitted.'}},required:["task"]}}},required:["agents"]}}},{type:"function",function:{name:"switch_model",description:"Switch the active AI model mid-conversation. Use when a different model is better for the next steps \u2014 e.g. switch to a fast model for simple lookups, or a more capable model for complex refactoring. The switch persists for all subsequent turns.",parameters:{type:"object",properties:{model:{type:"string",description:'Model spec: "provider:model" (e.g. "ollama:devstral-small-2:24b") or just model name'}},required:["model"]}}},{type:"function",function:{name:"k8s_pods",description:"List Kubernetes pods. Shows pod name, status, restarts, and age. Runs kubectl locally or via SSH on a remote server. Use namespace to filter, or omit for all namespaces.",parameters:{type:"object",properties:{namespace:{type:"string",description:"Namespace to list pods in (default: all namespaces)"},label:{type:"string",description:'Label selector filter (e.g. "app=nginx")'},context:{type:"string",description:"kubectl context to use (optional)"},server:{type:"string",description:"Remote server as user@host to run kubectl via SSH (optional, local kubectl if omitted)"}},required:[]}}},{type:"function",function:{name:"k8s_logs",description:'Fetch logs from a Kubernetes pod. Use tail to limit output, since for time-based filtering (e.g. "1h", "30m").',parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (required if pod has multiple containers)"},tail:{type:"number",description:"Number of recent lines to show (default: 100)"},since:{type:"string",description:'Show logs since duration (e.g. "1h", "30m", "5s")'},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod"]}}},{type:"function",function:{name:"k8s_exec",description:"Execute a command inside a running Kubernetes pod (kubectl exec). Requires user confirmation. Use for inspecting container state, reading configs, or debugging.",parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},command:{type:"string",description:'Command to run in the pod (e.g. "env", "ls /app", "cat /etc/config.yaml")'},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (optional)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod","command"]}}},{type:"function",function:{name:"k8s_apply",description:"Apply a Kubernetes manifest file (kubectl apply -f). Requires confirmation before applying to the cluster. Use dry_run=true to validate without applying.",parameters:{type:"object",properties:{file:{type:"string",description:"Path to manifest YAML file (relative or absolute)"},namespace:{type:"string",description:"Override namespace (optional)"},dry_run:{type:"boolean",description:"Validate only without applying (default: false)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["file"]}}},{type:"function",function:{name:"k8s_rollout",description:"Manage Kubernetes deployment rollouts: check status, restart (rolling update), view history, or undo (rollback). Restart and undo require confirmation.",parameters:{type:"object",properties:{action:{type:"string",enum:["status","restart","history","undo"],description:"Action: status (check rollout progress), restart (rolling restart), history (show revision history), undo (rollback to previous revision)"},deployment:{type:"string",description:"Deployment name"},namespace:{type:"string",description:"Namespace (default: default)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["action","deployment"]}}},{type:"function",function:{name:"brain_write",description:"Write or update a knowledge document in the project brain (.nex/brain/). Use this to persist important findings, architecture decisions, debugging insights, or conventions discovered during the session. The user can review changes via /brain review or git diff.",parameters:{type:"object",properties:{name:{type:"string",description:'Document name (without .md extension). Use kebab-case. Examples: "api-auth-flow", "db-schema-notes", "deployment-checklist"'},content:{type:"string",description:"Full Markdown content. Use headings (#), lists (-), and code blocks. Include optional YAML frontmatter with tags."},mode:{type:"string",enum:["create","update","append"],description:"create: new document (fails if exists). update: overwrite existing. append: add to end of existing document."}},required:["name","content","mode"]}}},{type:"function",function:{name:"ssh_exec",description:'Execute a command on a remote server via SSH. Server is a profile name from .nex/servers.json (e.g. "prod") or "user@host". Use for: checking status, reading logs, running deployments. Destructive commands (restart, delete, modify config) require confirmation. For service management prefer service_manage; for logs prefer service_logs.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name (from .nex/servers.json) or "user@host"'},command:{type:"string",description:"Shell command to run on the remote server"},sudo:{type:"boolean",description:"Run command with sudo (only if profile has sudo:true). Default: false"},timeout:{type:"number",description:"Timeout in seconds. Default: 30"}},required:["server","command"]}}},{type:"function",function:{name:"ssh_upload",description:"Upload a local file or directory to a remote server via SCP. Recursive for directories. Requires confirmation before upload.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},local_path:{type:"string",description:"Local path to upload (file or directory)"},remote_path:{type:"string",description:"Destination path on the remote server (absolute preferred)"}},required:["server","local_path","remote_path"]}}},{type:"function",function:{name:"ssh_download",description:"Download a file or directory from a remote server via SCP. Recursive for directories.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},remote_path:{type:"string",description:"Path on the remote server to download"},local_path:{type:"string",description:"Local destination path"}},required:["server","remote_path","local_path"]}}},{type:"function",function:{name:"remote_agent",description:'Delegate a coding task to nex-code running on a remote server. Use this when the task involves server-side projects (musikschule, stadtkapelle, cahill, schoensgibl, jarvis) that live on almalinux9/jarvis. Runs nex-code --auto on the server and streams output. Server is a profile name from .nex/servers.json or "user@host".',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name from .nex/servers.json (e.g. "almalinux9") or "user@host"'},task:{type:"string",description:"The full task description to run on the remote nex-code"},project_path:{type:"string",description:"Working directory on the remote server (e.g. /home/jarvis/jarvis-agent). Defaults to home directory."},model:{type:"string",description:"Model to use on remote nex-code (e.g. qwen3-coder:480b). Defaults to server default."}},required:["server","task"]}}},{type:"function",function:{name:"service_manage",description:"Manage a systemd service on a remote (or local) server. Uses systemctl. Status is read-only; start/stop/restart/reload/enable/disable require confirmation. For AlmaLinux 9: runs via SSH with sudo if configured.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn", "postgresql")'},action:{type:"string",enum:["status","start","stop","restart","reload","enable","disable"],description:"systemctl action to perform"}},required:["service","action"]}}},{type:"function",function:{name:"service_logs",description:"Fetch systemd service logs via journalctl. Works on AlmaLinux 9 and any systemd Linux. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn")'},lines:{type:"number",description:"Number of recent log lines to fetch. Default: 50"},since:{type:"string",description:'Time filter, e.g. "1 hour ago", "today", "2024-01-01 12:00". Optional.'},follow:{type:"boolean",description:"Tail logs in real-time (follow mode). Default: false"}},required:["service"]}}},{type:"function",function:{name:"container_list",description:"List Docker containers on a server (or locally). Shows container ID, name, image, status, and ports. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},all:{type:"boolean",description:"Show all containers including stopped ones. Default: false (running only)."}},required:[]}}},{type:"function",function:{name:"container_logs",description:"Fetch logs from a Docker container on a server (or locally). Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},lines:{type:"number",description:"Number of recent log lines. Default: 50."},since:{type:"string",description:'Time filter, e.g. "1h", "30m", "2024-01-01T12:00:00". Optional.'}},required:["container"]}}},{type:"function",function:{name:"container_exec",description:"Execute a command inside a running Docker container. Destructive or state-changing commands require confirmation.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},command:{type:"string",description:'Command to run inside the container (e.g. "cat /etc/nginx/nginx.conf").'}},required:["container","command"]}}},{type:"function",function:{name:"container_manage",description:'Start, stop, restart, or remove a Docker container. All actions except "inspect" require confirmation.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},action:{type:"string",enum:["start","stop","restart","remove","inspect"],description:"Action to perform on the container."}},required:["container","action"]}}},{type:"function",function:{name:"frontend_recon",description:"MANDATORY first step before creating or significantly modifying any frontend file (HTML template, Vue/React component, CSS). Scans the project and returns: (1) design tokens \u2014 CSS variables, Tailwind theme colors/fonts, (2) main layout/index page structure, (3) a reference component of the same type, (4) detected JS/CSS framework stack. Call this BEFORE writing any markup or styles. Never skip it for frontend tasks.",parameters:{type:"object",properties:{type:{type:"string",description:'Type of frontend file you are about to create. Used to find a relevant reference component. Examples: "list", "form", "detail", "dashboard", "modal", "component". Optional but improves reference quality.'}},required:[]}}},{type:"function",function:{name:"deploy",description:'Deploy to a remote server. Supports two methods: "rsync" (sync local files) and "git" (git pull on remote). Can use a named config from .nex/deploy.json. Requires confirmation before executing.',parameters:{type:"object",properties:{config:{type:"string",description:'Named deploy config from .nex/deploy.json (e.g. "prod"). Overrides all other params if provided.'},method:{type:"string",enum:["rsync","git"],description:'Deploy method: "rsync" syncs local files (default), "git" runs git pull on the remote.'},server:{type:"string",description:'Profile name or "user@host". Required if no config.'},remote_path:{type:"string",description:"Remote project directory. Required for git method; destination path for rsync."},local_path:{type:"string",description:"Local directory or file to sync. Required for rsync method."},branch:{type:"string",description:"Branch to pull (git method only). Defaults to current remote branch."},deploy_script:{type:"string",description:'Shell command(s) to run on the remote after sync/pull (e.g. "npm ci && systemctl restart myapp"). Optional.'},health_check:{type:"string",description:"URL (HTTP GET) or shell command to verify the service is healthy after deploy. If it fails, the deploy is marked as failed. Optional."},exclude:{type:"array",items:{type:"string"},description:"Paths to exclude from rsync. Optional."},dry_run:{type:"boolean",description:"Show what would happen without executing. Default: false."}},required:[]}}},{type:"function",function:{name:"deployment_status",description:"Check deployment status across all configured servers. Reads .nex/deploy.json configs and checks service health on each server. Returns a status summary table.",parameters:{type:"object",properties:{config:{type:"string",description:"Specific deploy config name to check (optional \u2014 checks all if omitted)"}},required:[]}}},{type:"function",function:{name:"sysadmin",description:"Senior sysadmin operations on a remote (or local) Linux server. Covers: system audit, disk_usage, process_list, network_status, package management (dnf/apt), user management, firewall (firewalld/ufw/iptables), cron, SSL cert checks, log tailing, large file discovery, systemd service management, process kill, journalctl log querying. Read-only actions run without confirmation; state-changing actions require user approval.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},action:{type:"string",enum:["audit","disk_usage","process_list","network_status","package","user_manage","firewall","cron","ssl_check","log_tail","find_large","service","kill_process","journalctl"],description:"Sysadmin operation. audit=full health overview; disk_usage=df+du; process_list=top procs; network_status=open ports; package=dnf/apt; user_manage=users/keys; firewall=rules; cron=crontab; ssl_check=cert expiry+days; log_tail=tail any log; find_large=big files; service=systemd unit management; kill_process=kill by PID or name; journalctl=query system journal."},path:{type:"string",description:"File or directory path. For disk_usage (default /), log_tail (required), find_large (default /)."},lines:{type:"number",description:"Lines to tail for log_tail or journalctl. Default: 100."},limit:{type:"number",description:"Result count for process_list (default 20) or find_large (default 20)."},sort_by:{type:"string",enum:["cpu","mem"],description:"Sort order for process_list. Default: cpu."},min_size:{type:"string",description:'Minimum file size for find_large. Default: "100M". Examples: "50M", "1G".'},package_action:{type:"string",enum:["install","remove","update","list","upgrade"],description:"Package sub-action for action=package."},packages:{type:"array",items:{type:"string"},description:"Package name(s) for install/remove/update."},user_action:{type:"string",enum:["list","create","delete","add_ssh_key","info"],description:"User sub-action for action=user_manage."},user:{type:"string",description:"Linux username for user_manage or cron."},groups:{type:"array",items:{type:"string"},description:'Groups to assign on user create (e.g. ["sudo", "docker"]).'},ssh_key:{type:"string",description:"SSH public key string to add for user_action=add_ssh_key."},firewall_action:{type:"string",enum:["status","allow","deny","remove","reload"],description:"Firewall sub-action for action=firewall."},port:{type:"string",description:'Port/protocol for firewall rules, e.g. "80/tcp", "443", "8080/udp".'},cron_action:{type:"string",enum:["list","add","remove"],description:"Cron sub-action for action=cron."},schedule:{type:"string",description:'Cron schedule expression for cron add, e.g. "0 2 * * *".'},command:{type:"string",description:"Command for cron add, or substring to match for cron remove."},domain:{type:"string",description:`Domain for ssl_check (e.g. "example.com"). Auto-detects Let's Encrypt cert on server; falls back to live TLS probe.`},cert_path:{type:"string",description:'Explicit path to cert file on server for ssl_check (e.g. "/etc/letsencrypt/live/x/cert.pem").'},service_name:{type:"string",description:'Systemd unit name for action=service (e.g. "nginx", "jarvis-api", "gunicorn"). .service suffix optional.'},service_action:{type:"string",enum:["status","start","stop","restart","reload","enable","disable","list_failed"],description:"Sub-action for action=service. list_failed shows all failed units."},pid:{type:"number",description:"Process ID to kill for action=kill_process."},process_name:{type:"string",description:"Process name to kill (uses pkill) for action=kill_process. Use with pid for safety."},signal:{type:"string",enum:["SIGTERM","SIGKILL","SIGHUP","SIGINT"],description:"Signal for kill_process. Default: SIGTERM."},unit:{type:"string",description:'Systemd unit to filter for journalctl (e.g. "nginx", "jarvis-api"). Omit for system-wide.'},since:{type:"string",description:'Time filter for journalctl, e.g. "1 hour ago", "today", "2026-03-17 10:00". Default: last 200 lines.'},priority:{type:"string",enum:["emerg","alert","crit","err","warning","notice","info","debug"],description:"Minimum log priority for journalctl. Default: no filter."}},required:["action"]}}}];function as(t,{server:e,context:s}={}){let o=e?e.replace(/[^a-zA-Z0-9@._-]/g,""):null,n=s?s.replace(/[^a-zA-Z0-9._/-]/g,""):null,r="kubectl";if(n&&(r+=` --context ${n}`),r+=` ${t}`,o){let a=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`ssh -o ConnectTimeout=10 -o BatchMode=yes ${o} "${a}"`}return r}async function $u(t,e,s={}){switch(t){case"bash":{let o=e.command,n=e$(o);if(n){let f=g$(o);return`BLOCKED: Command matches forbidden pattern: ${n}${f?`
|
|
193
|
+
HINT: ${f}`:""}`}let r=n$(o);if(r)return`BLOCKED: Destructive operation on protected path: ${r}
|
|
194
|
+
HINT: Protected files (.env, credentials, venv, .ssh, etc.) cannot be deleted or moved via bash. Override with NEX_UNPROTECT=1 if intentional.`;if(s.autoConfirm?fu(o):t$(o)){let f=fu(o)?"\u26D4":"\u26A0";if(!await dt(` ${f} bash: \`${o}\``,{toolName:"bash"}))return"CANCELLED: User declined to execute this command."}let c;try{c=process.cwd(),uu.accessSync(c)}catch{c=require("os").homedir(),s.silent||console.log(`${F.yellow} \u26A0 Working directory no longer exists \u2014 running in ${c}${F.reset}`)}let l=m$.test(o.trim())&&!h$.test(o.trim());if(p$.test(o.trim())||l){s.silent||console.log(`${F.dim} \u25B6 interactive: ${o}${F.reset}`);let f=Zg("sh",["-c",o],{stdio:"inherit",cwd:c});return f.error?`ERROR: ${f.error.message}`:f.status===0?"(interactive command completed successfully)":`(interactive command exited with code ${f.status})`}let{ToolProgress:u}=Dn(),d=s.silent?null:new u("bash",o.substring(0,40));d&&d.start();try{let{stdout:f,stderr:m}=await ae(o,{cwd:c,timeout:9e4,maxBuffer:5242880});return d&&d.stop(),f||m||"(no output)"}catch(f){d&&d.stop();let m=(f.stderr||f.stdout||f.message||"").toString().substring(0,5e3),h=yu(m,o);return`EXIT ${f.code||1}
|
|
195
|
+
${h}`}}case"read_file":{let o=He(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await it(o)){let w=await ho(e.path);if(w.fixedPath)o=w.fixedPath,console.log(`${F.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ce.relative(process.cwd(),o)}${F.reset}`);else return`ERROR: File not found: ${e.path}${w.message?`
|
|
196
|
+
`+w.message:""}`}let r=Buffer.alloc(8192),a=await uu.promises.open(o,"r"),{bytesRead:c}=await a.read(r,0,8192,0);await a.close();for(let w=0;w<c;w++)if(r[w]===0)return`ERROR: ${o} is a binary file (not readable as text)`;let l=await ke.readFile(o,"utf-8");if(!l&&(await ke.stat(o)).size>0)return`WARNING: ${o} is empty or unreadable`;let u=l.split(`
|
|
197
197
|
`),d=(e.line_start||1)-1,f=e.line_end||u.length,m=await ke.stat(o),h=u.length,p=`File: ${ce.relative(process.cwd(),o)} (${h} lines, ${m.size} bytes)`,g=u.slice(d,f).map((w,E)=>`${d+E+1}: ${w}`).join(`
|
|
198
198
|
`),$=!e.line_start&&!e.line_end&&h>150?`
|
|
199
199
|
[LARGE FILE: ${h} lines returned in full. For subsequent reads use line_start/line_end to avoid context overflow.]`:"";return`${p}
|
|
200
|
-
${g}${$}`}case"write_file":{await oi();let o=He(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let n=await it(o),r=null;if(s.autoConfirm)n&&(r=await ke.readFile(o,"utf-8"));else if(n){r=await ke.readFile(o,"utf-8");let d=await is(o,e.content);if(po(o,r,e.content,{annotations:d}),!await rs("Overwrite"))return"CANCELLED: User declined to overwrite file."}else{let d=await is(o,e.content);if(
|
|
201
|
-
`+d.message:""}`}let r=await ke.readFile(o,"utf-8"),
|
|
200
|
+
${g}${$}`}case"write_file":{await oi();let o=He(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let n=await it(o),r=null;if(s.autoConfirm)n&&(r=await ke.readFile(o,"utf-8"));else if(n){r=await ke.readFile(o,"utf-8");let d=await is(o,e.content);if(po(o,r,e.content,{annotations:d}),!await rs("Overwrite"))return"CANCELLED: User declined to overwrite file."}else{let d=await is(o,e.content);if(s$(o,e.content,{annotations:d}),!await rs("Create"))return"CANCELLED: User declined to create file."}let a=ce.dirname(o);await it(a)||await ke.mkdir(a,{recursive:!0}),await ke.writeFile(o,e.content,"utf-8");let l=/[/\\]\.git[/\\]hooks[/\\]/.test(o)||o.endsWith(".sh")||e.content.startsWith("#!");l&&await ke.chmod(o,493),mo("write_file",o,r,e.content);let u=l?" [chmod +x applied]":"";return`Written: ${o} (${e.content.length} chars)${u}`}case"edit_file":{await oi();let o=He(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await it(o)){let d=await ho(e.path);if(d.fixedPath)o=d.fixedPath,console.log(`${F.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ce.relative(process.cwd(),o)}${F.reset}`);else return`ERROR: File not found: ${e.path}${d.message?`
|
|
201
|
+
`+d.message:""}`}let r=await ke.readFile(o,"utf-8"),a=e.old_text,c=!1,l=!1;if(!r.includes(e.old_text)){let{getActiveModelId:d,getActiveProviderName:f}=be();if(hu(d(),f())==="strict"){let p=cs(r,e.old_text);return p?`ERROR: old_text not found in ${o} (strict mode \u2014 exact match required)
|
|
202
202
|
Most similar text (line ${p.line}, distance ${p.distance}):
|
|
203
|
-
${p.text}`:`ERROR: old_text not found in ${o} (strict mode \u2014 exact match required)`}let h=
|
|
203
|
+
${p.text}`:`ERROR: old_text not found in ${o} (strict mode \u2014 exact match required)`}let h=mu(r,e.old_text);if(h)a=h,c=!0,console.log(`${F.dim} \u2713 fuzzy whitespace match applied${F.reset}`);else{let p=wu(r,e.old_text,e.new_text);if(p){if(!s.autoConfirm){let $=await is(o,p.content);if(po(o,r,p.content,{annotations:$}),!await rs(`Apply (auto-fix, line ${p.line}, distance ${p.distance})`))return"CANCELLED: User declined to apply edit."}await ke.writeFile(o,p.content,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(o)||o.endsWith(".sh")||p.content.startsWith("#!"))&&await ke.chmod(o,493),mo("edit_file",o,r,p.content);let y=p.matchText.length>80?p.matchText.substring(0,77)+"...":p.matchText;return console.log(`${F.dim} \u2713 auto-fixed edit: line ${p.line}, distance ${p.distance}${F.reset}`),`Edited: ${o} (auto-fixed, line ${p.line}, distance ${p.distance}, matched: "${y}")`}let g=cs(r,e.old_text);return g?`ERROR: old_text not found in ${o}
|
|
204
204
|
Most similar text (line ${g.line}, distance ${g.distance}):
|
|
205
|
-
${g.text}`:`ERROR: old_text not found in ${o}`}}if(!s.autoConfirm){let d=r.split(
|
|
206
|
-
`)||"(empty)"}case"search_files":{let o=He(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let n=["-rn","--null","-H"];e.file_pattern&&n.push(`--include=${e.file_pattern}`),n.push(e.pattern,o);try{let{stdout:r}=await
|
|
205
|
+
${g.text}`:`ERROR: old_text not found in ${o}`}}if(!s.autoConfirm){let d=r.split(a).join(e.new_text),f=await is(o,d);if(po(o,r,d,{annotations:f}),!await rs(c?"Apply (fuzzy match)":"Apply"))return"CANCELLED: User declined to apply edit."}let u=r.split(a).join(e.new_text);return await ke.writeFile(o,u,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(o)||o.endsWith(".sh")||u.startsWith("#!"))&&await ke.chmod(o,493),mo("edit_file",o,r,u),c?`Edited: ${o} (fuzzy match)`:`Edited: ${o}`}case"list_directory":{let o=He(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await it(o)){let u=e.path.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),d=He(u),f=await it(d);if(d&&f)o=d;else return`ERROR: Directory not found: ${e.path}`}let r=e.max_depth||2,a=null;if(e.pattern)try{let u=e.pattern.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");a=new RegExp(`^${u}$`)}catch{return`ERROR: Invalid pattern: ${e.pattern}`}let c=[],l=async(u,d,f)=>{if(d>r)return;let m;try{m=await ke.readdir(u,{withFileTypes:!0})}catch{return}m=m.filter(h=>!h.name.startsWith(".")&&h.name!=="node_modules");for(let h of m){if(a&&!h.isDirectory()&&!a.test(h.name))continue;let p=h.isDirectory()?"/":"";c.push(`${f}${h.name}${p}`),h.isDirectory()&&await l(ce.join(u,h.name),d+1,f+" ")}};return await l(o,1,""),c.join(`
|
|
206
|
+
`)||"(empty)"}case"search_files":{let o=He(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let n=["-rn","--null","-H"];e.file_pattern&&n.push(`--include=${e.file_pattern}`),n.push(e.pattern,o);try{let{stdout:r}=await du("grep",n,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),a=r.split("\0"),c=[];for(let l=0;l<a.length;l+=2){let u=a[l],d=a[l+1];if(u&&d){let f=d.split(`
|
|
207
207
|
`).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(`
|
|
208
|
-
`)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let n=process.cwd(),r=e.path?He(e.path):n,
|
|
208
|
+
`)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let n=process.cwd(),r=e.path?He(e.path):n,a=e.pattern,c=C=>{let A=C.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"(.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");return new RegExp(`^${A}$`)},l=c(a),u=a.split("/").pop(),d=c(u),{ToolProgress:f}=Dn(),m=new f("glob","Finding files...");m.start();let{getFileIndex:h,getIndexedCwd:p,refreshIndex:g,isIndexValid:y}=jr(),$=h(),w=p();y(r)||(await g(r),$=h());let E=$.filter(C=>l.test(C)||d.test(ce.basename(C))).map(C=>ce.join(r,C));if(E.length===0)return m.stop(),"(no matches)";let b=await Promise.all(E.slice(0,210).map(async C=>{try{let A=await ke.stat(C);return{path:C,mtime:A.mtimeMs}}catch{return{path:C,mtime:0}}}));b.sort((C,A)=>A.mtime-C.mtime);let k=b.map(C=>C.path),v=E.length>200,R=k.slice(0,200).join(`
|
|
209
209
|
`);return m.update({count:E.length,detail:e.pattern}),m.stop(),v?`${R}
|
|
210
210
|
|
|
211
|
-
\u26A0 Results truncated at 200. Use a more specific pattern.`:R}case"grep":{let o=e.path?He(e.path):process.cwd(),n=["-rn","-E","--null","-H"];e.ignore_case&&n.push("-i"),e.include&&n.push(`--include=${e.include}`),e.type&&n.push(`--include=*.${e.type}`),e.context?n.push("-C",String(e.context)):(e.before_context&&n.push("-B",String(e.before_context)),e.after_context&&n.push("-A",String(e.after_context))),e.output_mode==="files_with_matches"?n.push("-l"):e.output_mode==="count"&&n.push("-c"),n.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage"),n.push(e.pattern,o);let{ToolProgress:r}=Dn(),
|
|
211
|
+
\u26A0 Results truncated at 200. Use a more specific pattern.`:R}case"grep":{let o=e.path?He(e.path):process.cwd(),n=["-rn","-E","--null","-H"];e.ignore_case&&n.push("-i"),e.include&&n.push(`--include=${e.include}`),e.type&&n.push(`--include=*.${e.type}`),e.context?n.push("-C",String(e.context)):(e.before_context&&n.push("-B",String(e.before_context)),e.after_context&&n.push("-A",String(e.after_context))),e.output_mode==="files_with_matches"?n.push("-l"):e.output_mode==="count"&&n.push("-c"),n.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage"),n.push(e.pattern,o);let{ToolProgress:r}=Dn(),a=new r("grep","Searching...");a.start();try{let{stdout:c}=await du("grep",n,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),l;if(e.output_mode==="files_with_matches"||e.output_mode==="count")l=c.trim().split(`
|
|
212
212
|
`).filter(f=>f.trim());else{let f=c.split("\0");l=[];for(let m=0;m<f.length;m+=2){let h=f[m],p=f[m+1];if(h&&p){let g=p.split(`
|
|
213
|
-
`).filter(y=>y.trim());for(let y of g)l.push(`${h}:${y}`)}}}let u=e.offset||0,d=e.head_limit||(e.output_mode==="files_with_matches"?200:100);return l=l.slice(u,u+d),
|
|
214
|
-
`).trim()||"(no matches)"}catch(c){return
|
|
215
|
-
`+$.message:""}`}let r=e.patches;if(!Array.isArray(r)||r.length===0)return"ERROR: No patches provided";let
|
|
213
|
+
`).filter(y=>y.trim());for(let y of g)l.push(`${h}:${y}`)}}}let u=e.offset||0,d=e.head_limit||(e.output_mode==="files_with_matches"?200:100);return l=l.slice(u,u+d),a.update({count:l.length,detail:`in ${o}`}),a.stop(),l.join(`
|
|
214
|
+
`).trim()||"(no matches)"}catch(c){return a.stop(),c.code===2?`ERROR: Invalid regex pattern: ${e.pattern}`:"(no matches)"}}case"patch_file":{await oi();let o=He(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await it(o)){let $=await ho(e.path);if($.fixedPath)o=$.fixedPath,console.log(`${F.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ce.relative(process.cwd(),o)}${F.reset}`);else return`ERROR: File not found: ${e.path}${$.message?`
|
|
215
|
+
`+$.message:""}`}let r=e.patches;if(!Array.isArray(r)||r.length===0)return"ERROR: No patches provided";let a=await ke.readFile(o,"utf-8"),{getActiveModelId:c,getActiveProviderName:l}=be(),u=hu(c(),l()),d=[],f=!1,m=!1;for(let $=0;$<r.length;$++){let{old_text:w,new_text:E}=r[$];if(a.includes(w))d.push({old_text:w,new_text:E});else if(u==="strict"){let b=cs(a,w);return b?`ERROR: Patch ${$+1} old_text not found in ${o} (strict mode \u2014 exact match required)
|
|
216
216
|
Most similar text (line ${b.line}, distance ${b.distance}):
|
|
217
|
-
${b.text}`:`ERROR: Patch ${$+1} old_text not found in ${o} (strict mode \u2014 exact match required)`}else{let b=
|
|
217
|
+
${b.text}`:`ERROR: Patch ${$+1} old_text not found in ${o} (strict mode \u2014 exact match required)`}else{let b=mu(a,w);if(b)d.push({old_text:b,new_text:E}),f=!0;else{let k=cs(a,w);if(k){let v=Math.max(3,Math.ceil(w.length*.05));if(k.distance<=v)d.push({old_text:k.text,new_text:E}),m=!0;else return`ERROR: Patch ${$+1} old_text not found in ${o}
|
|
218
218
|
Most similar text (line ${k.line}, distance ${k.distance}):
|
|
219
|
-
${k.text}`}else return`ERROR: Patch ${$+1} old_text not found in ${o}`}}}let h=
|
|
219
|
+
${k.text}`}else return`ERROR: Patch ${$+1} old_text not found in ${o}`}}}let h=a;for(let{old_text:$,new_text:w}of d)h=h.split($).join(w);if(!s.autoConfirm){let $=await is(o,h);if(po(o,a,h,{annotations:$}),!await rs(f?"Apply patches (fuzzy match)":"Apply patches"))return"CANCELLED: User declined to apply patches."}await ke.writeFile(o,h,"utf-8");let p=/[/\\]\.git[/\\]hooks[/\\]/.test(o)||o.endsWith(".sh")||h.startsWith("#!");p&&await ke.chmod(o,493),mo("patch_file",o,a,h);let g=m?" (auto-fixed)":f?" (fuzzy match)":"",y=p?" [chmod +x applied]":"";return`Patched: ${o} (${r.length} replacements)${g}${y}`}case"web_fetch":{let o=e.url,n=e.max_length||1e4;try{let r=await ni.get(o,{timeout:15e3,maxContentLength:1048576,responseType:"text",headers:{"User-Agent":"nex-code/0.2.0"}});return(typeof r.data=="string"?r.data:JSON.stringify(r.data)).replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim().substring(0,n)||"(empty response)"}catch(r){return`ERROR: Failed to fetch ${o}: ${r.message}`}}case"web_search":{let o=e.max_results||5;if(process.env.PERPLEXITY_API_KEY)try{let n=await ni.post("https://api.perplexity.ai/chat/completions",{model:"sonar",messages:[{role:"user",content:e.query}],max_tokens:1024,search_recency_filter:"month",return_citations:!0},{timeout:2e4,headers:{Authorization:`Bearer ${process.env.PERPLEXITY_API_KEY}`,"Content-Type":"application/json"}}),r=n.data?.choices?.[0]?.message?.content||"",a=n.data?.citations||[],c=`[Perplexity grounded search]
|
|
220
220
|
|
|
221
|
-
${r}`;return
|
|
221
|
+
${r}`;return a.length>0&&(c+=`
|
|
222
222
|
|
|
223
223
|
Sources:
|
|
224
|
-
`+
|
|
225
|
-
`)),c}catch(n){console.error(`${F.dim} Perplexity search failed (${n.message}), falling back to DuckDuckGo${F.reset}`)}try{let r=(await ni.get("https://html.duckduckgo.com/html/",{params:{q:e.query},timeout:1e4,responseType:"text",headers:{"User-Agent":"nex-code/0.2.0"}})).data,
|
|
224
|
+
`+a.slice(0,o).map((l,u)=>`${u+1}. ${l}`).join(`
|
|
225
|
+
`)),c}catch(n){console.error(`${F.dim} Perplexity search failed (${n.message}), falling back to DuckDuckGo${F.reset}`)}try{let r=(await ni.get("https://html.duckduckgo.com/html/",{params:{q:e.query},timeout:1e4,responseType:"text",headers:{"User-Agent":"nex-code/0.2.0"}})).data,a=[],c=/<a[^>]*class="result__a"[^>]*href="([^"]*)"[^>]*>([\s\S]*?)<\/a>/gi,l;for(;(l=c.exec(r))!==null&&a.length<o;){let u=l[1].replace(/.*uddg=/,"").split("&")[0],d=l[2].replace(/<[^>]+>/g,"").trim();try{a.push({title:d,url:decodeURIComponent(u)})}catch{a.push({title:d,url:u})}}return a.length===0?"(no results)":a.map((u,d)=>`${d+1}. ${u.title}
|
|
226
226
|
${u.url}`).join(`
|
|
227
227
|
|
|
228
228
|
`)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:o}=Vn();try{let n=await o(e.url,{waitFor:e.wait_for}),r=n.links.length>0?`
|
|
229
229
|
|
|
230
230
|
Links:
|
|
231
|
-
`+n.links.map(
|
|
231
|
+
`+n.links.map(a=>` ${a.text} \u2192 ${a.href}`).join(`
|
|
232
232
|
`):"";return`Title: ${n.title}
|
|
233
233
|
URL: ${n.url}
|
|
234
234
|
|
|
@@ -236,69 +236,69 @@ ${n.text}${r}`}catch(n){return`ERROR: ${n.message}`}}case"browser_screenshot":{l
|
|
|
236
236
|
Title: ${n.title}
|
|
237
237
|
URL: ${n.url}
|
|
238
238
|
|
|
239
|
-
To analyze visually, paste the path into your next message: ${n.path}`}catch(n){return`ERROR: ${n.message}`}}case"browser_click":{let{browserClick:o}=Vn();try{return await o(e.url,{selector:e.selector,text:e.text})}catch(n){return`ERROR: ${n.message}`}}case"browser_fill":{let{browserFill:o}=Vn();try{return await o(e.url,{selector:e.selector,value:e.value,submit:e.submit})}catch(n){return`ERROR: ${n.message}`}}case"ask_user":{let{question:o,options:n=[]}=e;return ri?new Promise(r=>{Zt=()=>r("CANCELLED"),ri(o,n).then(
|
|
239
|
+
To analyze visually, paste the path into your next message: ${n.path}`}catch(n){return`ERROR: ${n.message}`}}case"browser_click":{let{browserClick:o}=Vn();try{return await o(e.url,{selector:e.selector,text:e.text})}catch(n){return`ERROR: ${n.message}`}}case"browser_fill":{let{browserFill:o}=Vn();try{return await o(e.url,{selector:e.selector,value:e.value,submit:e.submit})}catch(n){return`ERROR: ${n.message}`}}case"ask_user":{let{question:o,options:n=[]}=e;return ri?new Promise(r=>{Zt=()=>r("CANCELLED"),ri(o,n).then(a=>{Zt=null,r(a||"User did not answer")})}):new Promise(r=>{let a=require("readline").createInterface({input:process.stdin,output:process.stdout});Zt=()=>{a.close(),r("CANCELLED")};let c=n.length>0?`
|
|
240
240
|
${n.map((l,u)=>` ${u+1}. ${l}`).join(`
|
|
241
241
|
`)}
|
|
242
242
|
`:"";console.log(`
|
|
243
|
-
${F.cyan}${F.bold} ? ${o}${F.reset}${c}`),
|
|
244
|
-
Clean working tree (no changes)`;let r=[`Branch: ${o}`,`Changed files (${n.length}):`];for(let
|
|
245
|
-
`)}case"git_diff":{if(!await si())return"ERROR: Not a git repository";let o;if(e.file){let n=["diff"];e.staged&&n.push("--cached"),n.push("--",e.file);try{o=execFileSync("git",n,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()}catch{o=""}}else o=await
|
|
246
|
-
`+
|
|
243
|
+
${F.cyan}${F.bold} ? ${o}${F.reset}${c}`),a.question(`${F.cyan} > ${F.reset}`,l=>{Zt=null,a.close(),r(l.trim()||"(no response)")})})}case"git_status":{if(!await si())return"ERROR: Not a git repository";let o=await pu()||"(detached)",n=await i$();if(n.length===0)return`Branch: ${o}
|
|
244
|
+
Clean working tree (no changes)`;let r=[`Branch: ${o}`,`Changed files (${n.length}):`];for(let a of n){let c=a.status==="M"?"modified":a.status==="A"?"added":a.status==="D"?"deleted":a.status==="??"?"untracked":a.status;r.push(` ${c}: ${a.file}`)}return r.join(`
|
|
245
|
+
`)}case"git_diff":{if(!await si())return"ERROR: Not a git repository";let o;if(e.file){let n=["diff"];e.staged&&n.push("--cached"),n.push("--",e.file);try{o=execFileSync("git",n,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()}catch{o=""}}else o=await a$(!!e.staged);return o||"(no diff)"}case"git_log":{if(!await si())return"ERROR: Not a git repository";let n=["log","--oneline",`-${Math.min(e.count||10,50)}`];e.file&&n.push("--",e.file);try{return execFileSync("git",n,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()||"(no commits)"}catch{return"(no commits)"}}case"task_list":{let{createTasks:o,updateTask:n,getTaskList:r,renderTaskList:a,hasActiveTasks:c}=io(),{getActiveTaskProgress:l}=we(),u=l();switch(e.action){case"create":{if(!e.name||!e.tasks)return"ERROR: task_list create requires name and tasks";let d=o(e.name,e.tasks);return u||console.log(`
|
|
246
|
+
`+a()),`Created task list "${e.name}" with ${d.length} tasks:
|
|
247
247
|
`+d.map(f=>` ${f.id}: ${f.description}`).join(`
|
|
248
248
|
`)}case"update":return!e.task_id||!e.status?"ERROR: task_list update requires task_id and status":n(e.task_id,e.status,e.result)?(u||console.log(`
|
|
249
|
-
`+
|
|
250
|
-
`+
|
|
251
|
-
`)}catch(r){let
|
|
252
|
-
`)[0]}`}}case"gh_run_view":{if(!e.run_id)return"ERROR: run_id is required";try{if(e.log){let{stdout:
|
|
253
|
-
...(truncated)`:"")}let{stdout:o}=await ae(`gh run view ${e.run_id} --json status,conclusion,name,headBranch,createdAt,updatedAt,jobs`,{cwd:process.cwd(),timeout:3e4}),n=JSON.parse(o),r=[`Run: ${n.name} [${e.run_id}]`,`Branch: ${n.headBranch} Status: ${n.conclusion||n.status}`,`Started: ${n.createdAt} Finished: ${n.updatedAt||"\u2014"}`,"","Jobs:"];for(let
|
|
249
|
+
`+a()),`Updated ${e.task_id}: ${e.status}${e.result?" \u2014 "+e.result:""}`):`ERROR: Task not found: ${e.task_id}`;case"get":{let d=r();return d.tasks.length===0?"No active tasks":(u||console.log(`
|
|
250
|
+
`+a()),JSON.stringify(d,null,2))}default:return`ERROR: Unknown task_list action: ${e.action}. Use: create, update, get`}}case"spawn_agents":{let{executeSpawnAgents:o}=Hl();return o(e)}case"switch_model":{let{setActiveModel:o,getActiveProviderName:n,getActiveModelId:r}=be();return o(e.model)?`Switched to ${n()}:${r()}`:`ERROR: Unknown model: ${e.model}. Use /providers to see available models.`}case"gh_run_list":{let o=Math.min(e.limit||10,30),n=["run","list","--limit",String(o),"--json","databaseId,status,conclusion,name,headBranch,createdAt,updatedAt,event"];e.workflow&&n.push("--workflow",e.workflow),e.branch&&n.push("--branch",e.branch),e.status&&n.push("--status",e.status);try{let{stdout:r}=await ae(`gh ${n.join(" ")}`,{cwd:process.cwd(),timeout:3e4}),a=JSON.parse(r||"[]");return a.length===0?"No workflow runs found.":a.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(`
|
|
251
|
+
`)}catch(r){let a=(r.stderr||r.message||"").toString();return a.includes("not found")||a.includes("not logged")?"ERROR: gh CLI not found or not authenticated. Run: gh auth login":`ERROR: ${a.split(`
|
|
252
|
+
`)[0]}`}}case"gh_run_view":{if(!e.run_id)return"ERROR: run_id is required";try{if(e.log){let{stdout:a}=await ae(`gh run view ${e.run_id} --log`,{cwd:process.cwd(),timeout:6e4,maxBuffer:5242880});return a.substring(0,8e3)+(a.length>8e3?`
|
|
253
|
+
...(truncated)`:"")}let{stdout:o}=await ae(`gh run view ${e.run_id} --json status,conclusion,name,headBranch,createdAt,updatedAt,jobs`,{cwd:process.cwd(),timeout:3e4}),n=JSON.parse(o),r=[`Run: ${n.name} [${e.run_id}]`,`Branch: ${n.headBranch} Status: ${n.conclusion||n.status}`,`Started: ${n.createdAt} Finished: ${n.updatedAt||"\u2014"}`,"","Jobs:"];for(let a of n.jobs||[]){let c=a.conclusion==="success"?"\u2713":a.conclusion==="failure"?"\u2717":"\u25CB";r.push(` ${c} ${a.name} (${a.conclusion||a.status})`);for(let l of a.steps||[]){if(l.conclusion==="failure"||l.conclusion==="skipped")continue;let u=l.conclusion==="success"?" \u2713":l.conclusion==="failure"?" \u2717":" \u25CB";r.push(` ${u} ${l.name}`)}}return r.join(`
|
|
254
254
|
`)}catch(o){return`ERROR: ${(o.stderr||o.message||"").toString().split(`
|
|
255
|
-
`)[0]}`}}case"gh_workflow_trigger":{if(!e.workflow)return"ERROR: workflow is required";let{confirm:o}=
|
|
256
|
-
${F.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${n}${F.reset}`),!await o(" Trigger?"))return"CANCELLED: User declined to trigger workflow.";try{return await ae(
|
|
257
|
-
`)[0]}`}}case"k8s_pods":{let o=e.namespace?`-n ${e.namespace}`:"-A",n=e.label?`-l ${e.label}`:"",r=as(`get pods ${o} ${n} -o wide`.trim(),e);try{let{stdout:
|
|
258
|
-
`)[0];return c.includes("command not found")?"ERROR: kubectl not found. Install kubectl or provide a server with kubectl.":`ERROR: ${c}`}}case"k8s_logs":{if(!e.pod)return"ERROR: pod is required";let o=e.namespace||"default",n=e.tail||100,r=`logs ${e.pod} -n ${o} --tail=${n}`;e.since&&(r+=` --since=${e.since}`),e.container&&(r+=` -c ${e.container}`);let
|
|
255
|
+
`)[0]}`}}case"gh_workflow_trigger":{if(!e.workflow)return"ERROR: workflow is required";let{confirm:o}=Ie(),n=e.branch||await pu()||"main",r=e.inputs?Object.entries(e.inputs).map(([l,u])=>`-f ${l}=${u}`).join(" "):"",a=`gh workflow run ${e.workflow} --ref ${n} ${r}`.trim();if(console.log(`
|
|
256
|
+
${F.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${n}${F.reset}`),!await o(" Trigger?"))return"CANCELLED: User declined to trigger workflow.";try{return await ae(a,{cwd:process.cwd(),timeout:3e4}),`Workflow "${e.workflow}" triggered on branch "${n}". Check status with gh_run_list.`}catch(l){return`ERROR: ${(l.stderr||l.message||"").toString().split(`
|
|
257
|
+
`)[0]}`}}case"k8s_pods":{let o=e.namespace?`-n ${e.namespace}`:"-A",n=e.label?`-l ${e.label}`:"",r=as(`get pods ${o} ${n} -o wide`.trim(),e);try{let{stdout:a,stderr:c}=await ae(r,{timeout:3e4,maxBuffer:2097152});return(a||c||"(no pods)").trim()}catch(a){let c=(a.stderr||a.message||"").toString().split(`
|
|
258
|
+
`)[0];return c.includes("command not found")?"ERROR: kubectl not found. Install kubectl or provide a server with kubectl.":`ERROR: ${c}`}}case"k8s_logs":{if(!e.pod)return"ERROR: pod is required";let o=e.namespace||"default",n=e.tail||100,r=`logs ${e.pod} -n ${o} --tail=${n}`;e.since&&(r+=` --since=${e.since}`),e.container&&(r+=` -c ${e.container}`);let a=as(r,e);try{let{stdout:c,stderr:l}=await ae(a,{timeout:6e4,maxBuffer:5242880}),u=(c||l||"(no logs)").trim();return u.substring(0,2e4)+(u.length>2e4?`
|
|
259
259
|
...(truncated)`:"")}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
|
|
260
260
|
`)[0]}`}}case"k8s_exec":{if(!e.pod)return"ERROR: pod is required";if(!e.command)return"ERROR: command is required";let o=e.namespace||"default";if(console.log(`
|
|
261
|
-
${F.yellow} \u26A0 kubectl exec into pod: ${e.pod} (ns: ${o})${F.reset}`),console.log(`${F.dim} Command: ${e.command}${F.reset}`),!await dt(" Execute in pod?"))return"CANCELLED: User declined.";let r=`exec ${e.pod} -n ${o}`;e.container&&(r+=` -c ${e.container}`),r+=` -- sh -c ${JSON.stringify(e.command)}`;let
|
|
262
|
-
`)[0]}`}}case"k8s_apply":{if(!e.file)return"ERROR: file is required";let o=!!e.dry_run;if(!o){let
|
|
263
|
-
${F.yellow} \u26A0 kubectl apply: ${
|
|
261
|
+
${F.yellow} \u26A0 kubectl exec into pod: ${e.pod} (ns: ${o})${F.reset}`),console.log(`${F.dim} Command: ${e.command}${F.reset}`),!await dt(" Execute in pod?"))return"CANCELLED: User declined.";let r=`exec ${e.pod} -n ${o}`;e.container&&(r+=` -c ${e.container}`),r+=` -- sh -c ${JSON.stringify(e.command)}`;let a=as(r,e);try{let{stdout:c,stderr:l}=await ae(a,{timeout:6e4,maxBuffer:2097152});return(c||l||"(no output)").trim()}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
|
|
262
|
+
`)[0]}`}}case"k8s_apply":{if(!e.file)return"ERROR: file is required";let o=!!e.dry_run;if(!o){let a=e.file;if(console.log(`
|
|
263
|
+
${F.yellow} \u26A0 kubectl apply: ${a}${e.namespace?` (ns: ${e.namespace})`:""}${F.reset}`),!await dt(" Apply to cluster?"))return"CANCELLED: User declined."}let n=`apply -f ${e.file}`;e.namespace&&(n+=` -n ${e.namespace}`),o&&(n+=" --dry-run=client");let r=as(n,e);try{let{stdout:a,stderr:c}=await ae(r,{timeout:12e4,maxBuffer:2097152});return(a||c||"(no output)").trim()}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
|
|
264
264
|
`)[0]}`}}case"k8s_rollout":{if(!e.action)return"ERROR: action is required";if(!e.deployment)return"ERROR: deployment is required";let o=e.namespace||"default";if(e.action==="restart"||e.action==="undo"){let c=e.action==="restart"?"Rolling restart":"Rollback (undo)";if(console.log(`
|
|
265
|
-
${F.yellow} \u26A0 ${c}: deployment/${e.deployment} (ns: ${o})${F.reset}`),!await dt(` ${c}?`))return"CANCELLED: User declined."}let r=`rollout ${e.action} deployment/${e.deployment} -n ${o}`,
|
|
266
|
-
`)[0]}`}}case"brain_write":{if(!e.name)return"ERROR: name is required";if(!e.content)return"ERROR: content is required";if(!e.mode)return"ERROR: mode is required (create, update, append)";let{writeDocument:o,readDocument:n}=ss(),{name:r,content:
|
|
265
|
+
${F.yellow} \u26A0 ${c}: deployment/${e.deployment} (ns: ${o})${F.reset}`),!await dt(` ${c}?`))return"CANCELLED: User declined."}let r=`rollout ${e.action} deployment/${e.deployment} -n ${o}`,a=as(r,e);try{let{stdout:c,stderr:l}=await ae(a,{timeout:12e4,maxBuffer:2097152});return(c||l||"(no output)").trim()}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
|
|
266
|
+
`)[0]}`}}case"brain_write":{if(!e.name)return"ERROR: name is required";if(!e.content)return"ERROR: content is required";if(!e.mode)return"ERROR: mode is required (create, update, append)";let{writeDocument:o,readDocument:n}=ss(),{name:r,content:a,mode:c}=e;if(c==="create"&&n(r).content)return`ERROR: Document "${r}" already exists. Use mode "update" to overwrite.`;if(c==="append"){let l=n(r),u=l.content?l.content+`
|
|
267
267
|
|
|
268
|
-
`+
|
|
269
|
-
${F.yellow} \u26A0 Remote command on ${h}: ${n}${F.reset}`),!await dt(" Execute on remote server?"))return"CANCELLED: User declined to execute remote command."}let{stdout:l,stderr:u,exitCode:d,error:f}=await Be(o,n,{timeout:
|
|
268
|
+
`+a:a;return o(r,u),`Appended to brain document: ${r}.md`}return o(r,a),`${c==="create"?"Created":"Updated"} brain document: ${r}.md`}case"ssh_exec":{if(!e.server)return"ERROR: server is required";if(!e.command)return"ERROR: command is required";let o;try{o=rt(e.server)}catch(h){return`ERROR: ${h.message}`}let n=e.command,r=!!e.sudo,a=(e.timeout||30)*1e3;if(/\b(rm|rmdir|mv|cp|chmod|chown|dd|mkfs|systemctl\s+(start|stop|restart|reload|enable|disable)|dnf\s+(install|remove|update|upgrade)|yum\s+(install|remove)|apt(-get)?\s+(install|remove|purge)|pip\s+install|pip3\s+install|firewall-cmd\s+--permanent|semanage|setsebool|passwd|userdel|useradd|nginx\s+-s\s+(reload|stop)|service\s+\w+\s+(start|stop|restart))\b/.test(n)){let h=o.user?`${o.user}@${o.host}`:o.host;if(console.log(`
|
|
269
|
+
${F.yellow} \u26A0 Remote command on ${h}: ${n}${F.reset}`),!await dt(" Execute on remote server?"))return"CANCELLED: User declined to execute remote command."}let{stdout:l,stderr:u,exitCode:d,error:f}=await Be(o,n,{timeout:a,sudo:r}),m=[l,u].filter(Boolean).join(`
|
|
270
270
|
`).trim();return d!==0?`EXIT ${d}
|
|
271
|
-
${f||m||"(no output)"}`:m||"(command completed, no output)"}case"ssh_upload":{if(!e.server||!e.local_path||!e.remote_path)return"ERROR: server, local_path, and remote_path are required";let o;try{o=rt(e.server)}catch(
|
|
272
|
-
${F.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${n}:${e.remote_path}${F.reset}`),!await dt(" Upload to remote server?"))return"CANCELLED: User declined upload.";try{return await
|
|
273
|
-
${h.slice(-2e3)}`:h.slice(-5e3)||"Remote nex-code completed (no output)"}case"service_manage":{if(!e.service)return"ERROR: service is required";if(!e.action)return"ERROR: action is required";let o=["status","start","stop","restart","reload","enable","disable"];if(!o.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${o.join(", ")}`;let n=!e.server||e.server==="local"||e.server==="localhost",r=e.action==="status",
|
|
271
|
+
${f||m||"(no output)"}`:m||"(command completed, no output)"}case"ssh_upload":{if(!e.server||!e.local_path||!e.remote_path)return"ERROR: server, local_path, and remote_path are required";let o;try{o=rt(e.server)}catch(a){return`ERROR: ${a.message}`}let n=o.user?`${o.user}@${o.host}`:o.host;if(console.log(`
|
|
272
|
+
${F.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${n}:${e.remote_path}${F.reset}`),!await dt(" Upload to remote server?"))return"CANCELLED: User declined upload.";try{return await l$(o,e.local_path,e.remote_path)}catch(a){return`ERROR: ${a.message}`}}case"ssh_download":{if(!e.server||!e.remote_path||!e.local_path)return"ERROR: server, remote_path, and local_path are required";let o;try{o=rt(e.server)}catch(n){return`ERROR: ${n.message}`}try{return await u$(o,e.remote_path,e.local_path)}catch(n){return`ERROR: ${n.message}`}}case"remote_agent":{let o=require("path").join(process.cwd(),".nex","servers.json"),n=null;try{n=JSON.parse(require("fs").readFileSync(o,"utf-8"))[e.server]||null}catch{}let r=n?`${n.user||"root"}@${n.host}`:e.server,a=n?.key?["-i",n.key]:[],c=e.project_path||n?.home||"~",l=e.model||"",d=["TMPFILE=$(mktemp /tmp/nexcode-XXXXXX.txt)",`echo "${Buffer.from(e.task).toString("base64")}" | base64 -d > "$TMPFILE"`,`cd "${c}" 2>/dev/null || true`,l?`nex-code --prompt-file "$TMPFILE" --auto --model "${l}" 2>&1`:'nex-code --prompt-file "$TMPFILE" --auto 2>&1',"EXIT_CODE=$?",'rm -f "$TMPFILE"',"exit $EXIT_CODE"].join(" && "),{spawnSync:f}=require("child_process"),m=f("ssh",[...a,"-o","StrictHostKeyChecking=no","-o","ConnectTimeout=10",r,`bash -c '${d}'`],{encoding:"utf-8",maxBuffer:10*1024*1024,timeout:3e5});if(m.error)return`ERROR: SSH connection failed: ${m.error.message}`;let h=(m.stdout||"")+(m.stderr||"");return m.status!==0?`Remote nex-code exited with code ${m.status}.
|
|
273
|
+
${h.slice(-2e3)}`:h.slice(-5e3)||"Remote nex-code completed (no output)"}case"service_manage":{if(!e.service)return"ERROR: service is required";if(!e.action)return"ERROR: action is required";let o=["status","start","stop","restart","reload","enable","disable"];if(!o.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${o.join(", ")}`;let n=!e.server||e.server==="local"||e.server==="localhost",r=e.action==="status",a=null;if(!n)try{a=rt(e.server)}catch(l){return`ERROR: ${l.message}`}if(!r){let l=n?"local machine":a.user?`${a.user}@${a.host}`:a.host;if(console.log(`
|
|
274
274
|
${F.yellow} \u26A0 Service: systemctl ${e.action} ${e.service} on ${l}${F.reset}`),!await dt(" Execute?"))return"CANCELLED: User declined service action."}let c=`systemctl ${e.action} ${e.service}`;if(n){let u=e.action!=="status"?`sudo ${c}`:c;try{let{stdout:d,stderr:f}=await ae(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}
|
|
275
|
-
${f}`}}else{let{stdout:l,stderr:u,exitCode:d,error:f}=await Be(
|
|
276
|
-
`).trim();return d!==0?/not found|loaded.*not-found/i.test(m)?`ERROR: Service "${e.service}" not found on ${
|
|
277
|
-
${f||m||"(no output)"}`:m||`systemctl ${e.action} ${e.service}: OK`}}case"service_logs":{if(!e.service)return"ERROR: service is required";let o=!e.server||e.server==="local"||e.server==="localhost",n=e.lines||50,r=e.since?`--since "${e.since}"`:"",
|
|
275
|
+
${f}`}}else{let{stdout:l,stderr:u,exitCode:d,error:f}=await Be(a,c,{timeout:15e3,sudo:!0}),m=[l,u].filter(Boolean).join(`
|
|
276
|
+
`).trim();return d!==0?/not found|loaded.*not-found/i.test(m)?`ERROR: Service "${e.service}" not found on ${a.host}. Check: ssh_exec to run "systemctl list-units --type=service"`:`EXIT ${d}
|
|
277
|
+
${f||m||"(no output)"}`:m||`systemctl ${e.action} ${e.service}: OK`}}case"service_logs":{if(!e.service)return"ERROR: service is required";let o=!e.server||e.server==="local"||e.server==="localhost",n=e.lines||50,r=e.since?`--since "${e.since}"`:"",a=e.follow?"-f":"",c=`journalctl -u ${e.service} -n ${n} ${r} ${a} --no-pager`.trim().replace(/\s+/g," ");if(o)try{let{stdout:p,stderr:g}=await ae(c,{timeout:15e3});return(p||g||"(no log output)").trim()}catch(p){return`EXIT ${p.code||1}
|
|
278
278
|
${(p.stderr||p.message||"").toString().trim()}`}let l;try{l=rt(e.server)}catch(p){return`ERROR: ${p.message}`}let{stdout:u,stderr:d,exitCode:f,error:m}=await Be(l,c,{timeout:2e4}),h=[u,d].filter(Boolean).join(`
|
|
279
279
|
`).trim();return f!==0?`EXIT ${f}
|
|
280
280
|
${m||h||"(no output)"}`:h||"(no log output)"}case"container_list":{let o=!e.server||e.server==="local"||e.server==="localhost",r=`docker ps ${e.all?"-a":""} --format "table {{.ID}}\\t{{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}"`.trim().replace(/\s+/g," ");if(o)try{let{stdout:m,stderr:h}=await ae(r,{timeout:1e4});return(m||h||"(no containers)").trim()}catch(m){return`EXIT ${m.code||1}
|
|
281
|
-
${(m.stderr||m.message||"").toString().trim()}`}let
|
|
281
|
+
${(m.stderr||m.message||"").toString().trim()}`}let a;try{a=rt(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:c,stderr:l,exitCode:u,error:d}=await Be(a,r,{timeout:15e3}),f=[c,l].filter(Boolean).join(`
|
|
282
282
|
`).trim();return u!==0?`EXIT ${u}
|
|
283
|
-
${d||f}`:f||"(no containers)"}case"container_logs":{if(!e.container)return"ERROR: container is required";let o=!e.server||e.server==="local"||e.server==="localhost",n=e.lines||50,r=e.since?`--since "${e.since}"`:"",
|
|
284
|
-
${(h.stderr||h.message||"").toString().trim()}`}let c;try{c=rt(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:l,stderr:u,exitCode:d,error:f}=await Be(c,
|
|
283
|
+
${d||f}`:f||"(no containers)"}case"container_logs":{if(!e.container)return"ERROR: container is required";let o=!e.server||e.server==="local"||e.server==="localhost",n=e.lines||50,r=e.since?`--since "${e.since}"`:"",a=`docker logs --tail ${n} ${r} ${e.container} 2>&1`.trim().replace(/\s+/g," ");if(o)try{let{stdout:h,stderr:p}=await ae(a,{timeout:15e3});return(h||p||"(no log output)").trim()}catch(h){return`EXIT ${h.code||1}
|
|
284
|
+
${(h.stderr||h.message||"").toString().trim()}`}let c;try{c=rt(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:l,stderr:u,exitCode:d,error:f}=await Be(c,a,{timeout:2e4}),m=[l,u].filter(Boolean).join(`
|
|
285
285
|
`).trim();return d!==0?`EXIT ${d}
|
|
286
286
|
${f||m}`:m||"(no log output)"}case"container_exec":{if(!e.container)return"ERROR: container is required";if(!e.command)return"ERROR: command is required";let o=!e.server||e.server==="local"||e.server==="localhost",n=/^(cat|ls|echo|env|printenv|df|du|ps|id|whoami|uname|hostname|date|pwd|which|find\s|head\s|tail\s|grep\s|curl\s+-[A-Za-z]*G|curl\s+https?:\/\/[^\s]+$)/;if(!s.autoConfirm&&!n.test(e.command.trim())){let h=o?"local":e.server;if(console.log(`
|
|
287
|
-
${F.yellow} \u26A0 docker exec in ${e.container} on ${h}: ${e.command}${F.reset}`),!await dt(" Execute?"))return"CANCELLED: User declined."}let
|
|
288
|
-
${(h.stderr||h.message||"").toString().trim()}`}let c;try{c=rt(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:l,stderr:u,exitCode:d,error:f}=await Be(c,
|
|
287
|
+
${F.yellow} \u26A0 docker exec in ${e.container} on ${h}: ${e.command}${F.reset}`),!await dt(" Execute?"))return"CANCELLED: User declined."}let a=`docker exec ${e.container} sh -c ${JSON.stringify(e.command)}`;if(o)try{let{stdout:h,stderr:p}=await ae(a,{timeout:3e4});return(h||p||"(no output)").trim()}catch(h){return`EXIT ${h.code||1}
|
|
288
|
+
${(h.stderr||h.message||"").toString().trim()}`}let c;try{c=rt(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:l,stderr:u,exitCode:d,error:f}=await Be(c,a,{timeout:35e3}),m=[l,u].filter(Boolean).join(`
|
|
289
289
|
`).trim();return d!==0?`EXIT ${d}
|
|
290
290
|
${f||m}`:m||"(no output)"}case"container_manage":{if(!e.container)return"ERROR: container is required";if(!e.action)return"ERROR: action is required";let o=["start","stop","restart","remove","inspect"];if(!o.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${o.join(", ")}`;let n=!e.server||e.server==="local"||e.server==="localhost";if(!(e.action==="inspect")&&!s.autoConfirm){let p=n?"local":e.server;if(console.log(`
|
|
291
|
-
${F.yellow} \u26A0 docker ${e.action} ${e.container} on ${p}${F.reset}`),!await dt(" Execute?"))return"CANCELLED: User declined."}let
|
|
291
|
+
${F.yellow} \u26A0 docker ${e.action} ${e.container} on ${p}${F.reset}`),!await dt(" Execute?"))return"CANCELLED: User declined."}let a=e.action==="remove"?"rm":e.action,c=e.action==="inspect"?`docker inspect ${e.container}`:`docker ${a} ${e.container}`;if(n)try{let{stdout:p,stderr:g}=await ae(c,{timeout:3e4});return(p||g||`docker ${e.action} ${e.container}: OK`).trim()}catch(p){return`EXIT ${p.code||1}
|
|
292
292
|
${(p.stderr||p.message||"").toString().trim()}`}let l;try{l=rt(e.server)}catch(p){return`ERROR: ${p.message}`}let{stdout:u,stderr:d,exitCode:f,error:m}=await Be(l,c,{timeout:35e3}),h=[u,d].filter(Boolean).join(`
|
|
293
293
|
`).trim();return f!==0?`EXIT ${f}
|
|
294
|
-
${m||h}`:h||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...
|
|
294
|
+
${m||h}`:h||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...d$(e.config),...e},delete e.config,delete e._name}catch(d){return`ERROR: ${d.message}`}if(!e.server)return'ERROR: server is required (or use config: "<name>")';if(!e.remote_path)return"ERROR: remote_path is required";let o=e.method||"rsync";if(o==="rsync"&&!e.local_path)return"ERROR: local_path is required for rsync method";let n;try{n=rt(e.server)}catch(d){return`ERROR: ${d.message}`}let r=n.user?`${n.user}@${n.host}`:n.host;if(!e.dry_run&&!s.autoConfirm){if(o==="git"){let f=e.branch?` (branch: ${e.branch})`:"";console.log(`
|
|
295
295
|
${F.yellow} \u26A0 Deploy [git pull]: ${r}:${e.remote_path}${f}${F.reset}`)}else{let f=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`;console.log(`
|
|
296
|
-
${F.yellow} \u26A0 Deploy [rsync]: ${f} \u2192 ${r}:${e.remote_path}${F.reset}`)}if(e.deploy_script&&console.log(`${F.yellow} Then run: ${e.deploy_script}${F.reset}`),e.health_check&&console.log(`${F.yellow} Health check: ${e.health_check}${F.reset}`),!await dt(" Proceed with deployment?"))return"CANCELLED: User declined."}let
|
|
296
|
+
${F.yellow} \u26A0 Deploy [rsync]: ${f} \u2192 ${r}:${e.remote_path}${F.reset}`)}if(e.deploy_script&&console.log(`${F.yellow} Then run: ${e.deploy_script}${F.reset}`),e.health_check&&console.log(`${F.yellow} Health check: ${e.health_check}${F.reset}`),!await dt(" Proceed with deployment?"))return"CANCELLED: User declined."}let a="";if(o==="git"){let d=e.branch?`cd ${e.remote_path} && git fetch origin && git checkout ${e.branch} && git pull origin ${e.branch}`:`cd ${e.remote_path} && git pull`;if(e.dry_run)return`DRY RUN [git]: would run on ${r}:
|
|
297
297
|
${d}${e.deploy_script?`
|
|
298
|
-
${e.deploy_script}`:""}`;let{stdout:f,stderr:m,exitCode:h,error:p}=await Be(n,d,{timeout:12e4});if(
|
|
298
|
+
${e.deploy_script}`:""}`;let{stdout:f,stderr:m,exitCode:h,error:p}=await Be(n,d,{timeout:12e4});if(a=[f,m].filter(Boolean).join(`
|
|
299
299
|
`).trim(),h!==0)return`ERROR (git pull, exit ${h}):
|
|
300
|
-
${p||
|
|
301
|
-
${
|
|
300
|
+
${p||a}`}else{let d=n.key?`-e "ssh -i ${n.key.replace(/^~/,require("os").homedir())}${n.port&&Number(n.port)!==22?` -p ${n.port}`:""}"`:n.port&&Number(n.port)!==22?`-e "ssh -p ${n.port}"`:"",f=(e.exclude||[]).map(g=>`--exclude="${g}"`).join(" "),m=e.dry_run?"--dry-run":"",h=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`,p=`rsync -avz --delete ${m} ${f} ${d} ${h} ${r}:${e.remote_path}`.trim().replace(/\s+/g," ");try{let{stdout:g,stderr:y}=await ae(p,{timeout:12e4});a=(g||y||"").trim()}catch(g){return`ERROR (rsync): ${(g.stderr||g.message||"").toString().trim()}`}if(e.dry_run)return`DRY RUN [rsync]:
|
|
301
|
+
${a||"(nothing to sync)"}`}let c="";if(e.deploy_script){let{stdout:d,stderr:f,exitCode:m,error:h}=await Be(n,e.deploy_script,{timeout:12e4}),p=[d,f].filter(Boolean).join(`
|
|
302
302
|
`).trim();if(m!==0)return`${o==="git"?"git pull":"rsync"} OK
|
|
303
303
|
|
|
304
304
|
ERROR (deploy_script, exit ${m}):
|
|
@@ -309,45 +309,45 @@ ${p||"(no output)"}`}let l="";if(e.health_check){let d=e.health_check.trim();if(
|
|
|
309
309
|
|
|
310
310
|
Health check: \u2713 ${d} \u2192 ${h.status}`;else return l=`
|
|
311
311
|
|
|
312
|
-
Health check FAILED: ${d} \u2192 HTTP ${h.status}`,(o==="git"?"git pull OK":"rsync OK")+
|
|
312
|
+
Health check FAILED: ${d} \u2192 HTTP ${h.status}`,(o==="git"?"git pull OK":"rsync OK")+a+c+l}catch(m){return l=`
|
|
313
313
|
|
|
314
|
-
Health check FAILED: ${d} \u2192 ${m.message}`,(o==="git"?"git pull OK":"rsync OK")+
|
|
314
|
+
Health check FAILED: ${d} \u2192 ${m.message}`,(o==="git"?"git pull OK":"rsync OK")+a+c+l}else{let{stdout:m,stderr:h,exitCode:p}=await Be(n,d,{timeout:15e3}),g=[m,h].filter(Boolean).join(`
|
|
315
315
|
`).trim();if(p!==0)return l=`
|
|
316
316
|
|
|
317
|
-
Health check FAILED (exit ${p}): ${g}`,(o==="git"?"git pull OK":"rsync OK")+
|
|
317
|
+
Health check FAILED (exit ${p}): ${g}`,(o==="git"?"git pull OK":"rsync OK")+a+c+l;l=`
|
|
318
318
|
|
|
319
319
|
Health check: \u2713 ${g||"(exit 0)"}`}}let u=o==="git"?`${r}:${e.remote_path}`:`${e.local_path} \u2192 ${r}:${e.remote_path}`;return`Deployed [${o}] ${u}
|
|
320
|
-
${
|
|
320
|
+
${a}${c}${l}`.trim()}case"deployment_status":{let o=f$(),n=e.config?[e.config]:Object.keys(o);if(n.length===0)return"No deploy configs found. Create .nex/deploy.json to configure deployments.";let r=[];for(let a of n){let c=o[a];if(!c){r.push(`${a}: NOT FOUND`);continue}try{let l=rt(c.server||a),d=(await Be(l,"echo OK",{timeout:1e4})).stdout.trim()==="OK",f="unknown";if(d&&c.deploy_script){let h=c.deploy_script.match(/systemctl\s+\w+\s+(\S+)/);if(h)try{f=(await Be(l,`systemctl is-active ${h[1]}`,{timeout:1e4})).stdout.trim()}catch{f="inactive"}}let m="N/A";if(c.health_check){let h=c.health_check.trim();if(/^https?:\/\//.test(h))try{let p=require("node-fetch"),g=await Promise.race([p(h),new Promise((y,$)=>setTimeout(()=>$(new Error("timeout")),1e4))]);m=g.ok?"healthy":`HTTP ${g.status}`}catch(p){m=`unhealthy: ${p.message.substring(0,50)}`}else try{m=(await Be(l,h,{timeout:1e4})).exitCode===0?"healthy":"unhealthy"}catch{m="unhealthy"}}r.push(`${a}: server=${d?"reachable":"unreachable"} service=${f} health=${m}`)}catch(l){r.push(`${a}: ERROR \u2014 ${l.message}`)}}return`Deployment Status:
|
|
321
321
|
${r.join(`
|
|
322
|
-
`)}`}case"frontend_recon":{let o=process.cwd(),n=(e.type||"").toLowerCase(),r=[],
|
|
322
|
+
`)}`}case"frontend_recon":{let o=process.cwd(),n=(e.type||"").toLowerCase(),r=[],a=async(b,k=120)=>{try{let v=ce.isAbsolute(b)?b:ce.join(o,b),C=(await ke.readFile(v,"utf8")).split(`
|
|
323
323
|
`),A=C.slice(0,k).join(`
|
|
324
324
|
`);return C.length>k?A+`
|
|
325
325
|
... (${C.length-k} more lines \u2014 use read_file for full content)`:A}catch{return null}},l=["node_modules",".git","dist","build","vendor",".next","__pycache__","venv",".venv"].map(b=>`-not -path "*/${b}/*"`).join(" "),u=async b=>{try{let{stdout:k}=await ae(`find "${o}" -type f -name "${b}" ${l} 2>/dev/null | head -10`,{timeout:8e3});return k.trim().split(`
|
|
326
326
|
`).filter(Boolean)}catch{return[]}},d=async(b,k)=>{try{let{stdout:v}=await ae(`grep -rl "${b}" "${o}" --include="${k}" --exclude-dir=node_modules --exclude-dir=.git --exclude-dir=dist --exclude-dir=build 2>/dev/null | head -5`,{timeout:8e3});return v.trim().split(`
|
|
327
327
|
`).filter(Boolean)}catch{return[]}};r.push(`## STEP 1: Design Tokens
|
|
328
|
-
`);let f=[...await u("tailwind.config.js"),...await u("tailwind.config.ts"),...await u("tailwind.config.mjs")];if(f.length>0){let b=await
|
|
328
|
+
`);let f=[...await u("tailwind.config.js"),...await u("tailwind.config.ts"),...await u("tailwind.config.mjs")];if(f.length>0){let b=await a(f[0],80);b&&r.push(`### Tailwind config (${ce.relative(o,f[0])})
|
|
329
329
|
\`\`\`js
|
|
330
330
|
${b}
|
|
331
|
-
\`\`\``)}else r.push("(no tailwind.config found)");let m=["variables.css","_variables.scss","tokens.css","base.css","global.css","main.css","index.css","app.css","style.css","styles.css"],h=!1;for(let b of m){let k=await u(b);for(let v of k){let R=await
|
|
331
|
+
\`\`\``)}else r.push("(no tailwind.config found)");let m=["variables.css","_variables.scss","tokens.css","base.css","global.css","main.css","index.css","app.css","style.css","styles.css"],h=!1;for(let b of m){let k=await u(b);for(let v of k){let R=await a(v,100);if(R&&R.includes(":root")){r.push(`### CSS Variables (${ce.relative(o,v)})
|
|
332
332
|
\`\`\`css
|
|
333
333
|
${R}
|
|
334
|
-
\`\`\``),h=!0;break}}if(h)break}if(!h){let b=await d(":root","*.css");if(b.length>0){let k=await
|
|
334
|
+
\`\`\``),h=!0;break}}if(h)break}if(!h){let b=await d(":root","*.css");if(b.length>0){let k=await a(b[0],100);k&&r.push(`### CSS Variables (${ce.relative(o,b[0])})
|
|
335
335
|
\`\`\`css
|
|
336
336
|
${k}
|
|
337
337
|
\`\`\``),h=!0}}h||r.push("(no CSS custom properties / :root found)"),r.push(`
|
|
338
338
|
## STEP 2: Main Layout / Index Page
|
|
339
|
-
`);let p=["base.html","_base.html","layout.html","base.jinja","App.vue","App.jsx","App.tsx","_app.jsx","_app.tsx","_app.js","layout.vue","index.html"],g=!1;for(let b of p){let k=await u(b);if(k.length>0){let v=await
|
|
339
|
+
`);let p=["base.html","_base.html","layout.html","base.jinja","App.vue","App.jsx","App.tsx","_app.jsx","_app.tsx","_app.js","layout.vue","index.html"],g=!1;for(let b of p){let k=await u(b);if(k.length>0){let v=await a(k[0],150);if(v){r.push(`### Main layout: ${ce.relative(o,k[0])}
|
|
340
340
|
\`\`\`html
|
|
341
341
|
${v}
|
|
342
342
|
\`\`\``),g=!0;break}}}g||r.push("(no main layout/index file found \u2014 try read_file on your root template manually)"),r.push(`
|
|
343
343
|
## STEP 3: Reference Component (same type)
|
|
344
344
|
`);let y=[];if(n){for(let b of["*.html","*.vue","*.jsx","*.tsx"])if(y=await d(n,b),y.length>0)break}if(y.length===0)try{let{stdout:b}=await ae(`find "${o}" -type f \\( -name "*.html" -o -name "*.vue" -o -name "*.jsx" -o -name "*.tsx" \\) -not -path "*/node_modules/*" -not -path "*/.git/*" -not -path "*/dist/*" -not -path "*/build/*" -not -name "base.html" -not -name "_base.html" -not -name "layout.html" -not -name "App.vue" -not -name "App.jsx" 2>/dev/null | head -20`,{timeout:8e3});y=b.trim().split(`
|
|
345
|
-
`).filter(Boolean)}catch{y=[]}if(y.length>0){let b=y[0],k=await
|
|
345
|
+
`).filter(Boolean)}catch{y=[]}if(y.length>0){let b=y[0],k=await a(b,150);k?r.push(`### Reference: ${ce.relative(o,b)}
|
|
346
346
|
\`\`\`html
|
|
347
347
|
${k}
|
|
348
348
|
\`\`\``):r.push("(reference file found but could not be read)")}else r.push("(no reference component found \u2014 check manually with glob or list_directory)");r.push(`
|
|
349
349
|
## STEP 4: Framework Stack
|
|
350
|
-
`);let $=[],w=await
|
|
350
|
+
`);let $=[],w=await a(ce.join(o,"package.json"),999);if(w){if((w.includes('"react"')||w.includes("'react'"))&&$.push("React"),w.includes('"vue"')||w.includes("'vue'")){let k=w.match(/"vue":\s*"[\^~]?(\d+)/);$.push(k?`Vue.js v${k[1]}`:"Vue.js")}let b=w.match(/"alpinejs":\s*"[\^~]?(\d+)/);b&&$.push(`Alpine.js v${b[1]} (\u26A0 v2 vs v3 API differs!)`),(w.includes('"htmx')||w.includes("'htmx"))&&$.push("HTMX"),w.includes('"tailwindcss"')&&$.push("Tailwind CSS"),w.includes('"bootstrap"')&&$.push("Bootstrap")}if((await it(ce.join(o,"manage.py"))||(await a(ce.join(o,"requirements.txt"),50)||"").includes("Django"))&&$.push("Django (server-rendered templates)"),!$.some(b=>b.includes("Alpine"))){let b=await d("alpinejs","*.html");if(b.length>0){let v=(await a(b[0],30)||"").match(/alpinejs[@/]v?(\d)/);$.push(v?`Alpine.js v${v[1]} (via CDN \u2014 \u26A0 v2 vs v3 API differs!)`:"Alpine.js (via CDN \u2014 check version!)")}}return $.some(b=>b.includes("HTMX"))||(await d("htmx","*.html")).length>0&&$.push("HTMX (via CDN)"),$.length>0?(r.push($.map(b=>`- ${b}`).join(`
|
|
351
351
|
`)),r.push(`
|
|
352
352
|
\u26A0 Use ONLY the frameworks listed above. Do NOT mix (e.g. no fetch() when HTMX is used for the same action).`)):r.push("(framework not detected \u2014 check package.json or script tags manually)"),r.push(`
|
|
353
353
|
---
|
|
@@ -396,35 +396,35 @@ ${d}`:d||"(empty log)"}case"find_large":{let l=e.path||"/",u=e.limit||20,d=e.min
|
|
|
396
396
|
${m}`:m||`(no files larger than ${d} in ${l})`}case"service":{if(!e.service_action)return"ERROR: service_action is required for action=service";if(e.service_action!=="list_failed"&&!e.service_name)return"ERROR: service_name is required (except for list_failed)";let l=e.service_name?e.service_name.includes(".")?e.service_name:`${e.service_name}.service`:"",u;switch(e.service_action){case"status":u=`systemctl status ${l} --no-pager -l 2>&1 | head -40`;break;case"list_failed":u="systemctl list-units --state=failed --no-legend 2>/dev/null";break;case"start":u=`systemctl start ${l} && systemctl status ${l} --no-pager -l 2>&1 | head -20`;break;case"stop":u=`systemctl stop ${l} && echo "${l} stopped"`;break;case"restart":u=`systemctl restart ${l} && systemctl status ${l} --no-pager -l 2>&1 | head -20`;break;case"reload":u=`systemctl reload ${l} 2>&1 || systemctl reload-or-restart ${l} 2>&1`;break;case"enable":u=`systemctl enable ${l} && echo "${l} enabled"`;break;case"disable":u=`systemctl disable ${l} && echo "${l} disabled"`;break;default:return`ERROR: Unknown service_action: ${e.service_action}`}let{out:d,exitCode:f}=await r(u,3e4);return f!==0?`EXIT ${f}
|
|
397
397
|
${d}`:d||`service ${e.service_action} OK`}case"kill_process":{if(!e.pid&&!e.process_name)return"ERROR: pid or process_name is required for kill_process";let l=e.signal||"SIGTERM",u;e.pid?u=`ps -p ${e.pid} -o pid,user,%cpu,%mem,etime,cmd 2>/dev/null && kill -${l} ${e.pid} && echo "Sent ${l} to PID ${e.pid}"`:u=`pgrep -a "${e.process_name}" 2>/dev/null | head -5 && pkill -${l} "${e.process_name}" && echo "Sent ${l} to all '${e.process_name}' processes"`;let{out:d,exitCode:f}=await r(u,15e3);return f!==0?`EXIT ${f}
|
|
398
398
|
${d}`:d}case"journalctl":{let l=e.lines||100,u=["journalctl","--no-pager","-n",String(l)];e.unit&&u.push("-u",e.unit.includes(".")?e.unit:`${e.unit}.service`),e.priority&&u.push("-p",e.priority),e.since&&u.push(`--since="${e.since}"`),u.push('2>/dev/null || echo "(journalctl not available)"');let{out:d,exitCode:f}=await r(u.join(" "),2e4);return f!==0?`EXIT ${f}
|
|
399
|
-
${d}`:d||"(no log entries)"}default:return`ERROR: Unknown sysadmin action: ${e.action}`}}default:{let{executePluginTool:o}=Ys(),n=await o(t,e,s);return n!==null?n:`ERROR: Unknown tool: ${t}`}}}async function
|
|
400
|
-
`)}function
|
|
401
|
-
`).map(s=>s.trim()).filter(s=>s&&!s.startsWith("#")&&!s.startsWith("!")).map(s=>s.replace(/\/$/,""))}catch{return[]}}function
|
|
402
|
-
`)}var ci=new Map,Sn=new Map,$o=null,
|
|
399
|
+
${d}`:d||"(no log entries)"}default:return`ERROR: Unknown sysadmin action: ${e.action}`}}default:{let{executePluginTool:o}=Ys(),n=await o(t,e,s);return n!==null?n:`ERROR: Unknown tool: ${t}`}}}async function _$(t,e,s={}){let{emit:o}=Ys(),{logToolExecution:n}=ti(),r=Date.now(),a=s.silent?null:r$(t,e);if(!a){let l=await $u(t,e,s);return n({tool:t,args:e,result:l,duration:Date.now()-r,success:!l.startsWith?.("ERROR")}),await o("onToolResult",{tool:t,args:e,result:l}),l}let c=new o$(a);c.start();try{let l=await $u(t,e,s);return c.stop(),n({tool:t,args:e,result:l,duration:Date.now()-r,success:!l.startsWith?.("ERROR")}),await o("onToolResult",{tool:t,args:e,result:l}),l}catch(l){throw c.stop(),n({tool:t,args:e,result:l.message,duration:Date.now()-r,success:!1}),l}}bu.exports={TOOL_DEFINITIONS:b$,executeTool:_$,resolvePath:He,autoFixPath:ho,autoFixEdit:wu,enrichBashError:yu,cancelPendingAskUser:$$,setAskUserHandler:y$,fileExists:it}});var ku=q((T_,_u)=>{var{loadServerProfiles:ai}=kn(),ii={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 k$(){let t=ai();if(Object.keys(t).length===0)return null;let s=["## Remote Servers (.nex/servers.json)"];s.push(""),s.push("Available server profiles (use with ssh_exec, ssh_upload, ssh_download, service_manage, service_logs, container_list, container_logs, container_exec, container_manage, deploy):");for(let[n,r]of Object.entries(t)){let a=r.user?`${r.user}@${r.host}`:r.host,c=r.port&&Number(r.port)!==22?`:${r.port}`:"",l=r.os?` \u2014 OS: ${r.os}`:"",u=r.sudo?", sudo available":"";s.push(`- **${n}**: ${a}${c}${l}${u}`)}let o=new Set;for(let n of Object.values(t))n.os&&ii[n.os]&&o.add(n.os);if(o.size>0){s.push("");for(let n of o){let r={almalinux9:"AlmaLinux 9",almalinux8:"AlmaLinux 8",ubuntu:"Ubuntu",debian:"Debian",macos:"macOS"}[n]||n;s.push(`### ${r} Notes`);for(let a of ii[n])s.push(`- ${a}`)}}return s.join(`
|
|
400
|
+
`)}function x$(t){let e=ai();return Object.values(e).some(s=>s.os&&s.os.startsWith(t))}function v$(){return Object.keys(ai())}_u.exports={getServerContext:k$,hasServerOS:x$,getProfileNames:v$,OS_HINTS:ii}});var yo=q((R_,Su)=>{var ft=require("fs").promises,xu=require("fs"),Le=require("path"),go=require("util").promisify(require("child_process").exec),{C:vn}=we(),{getMergeConflicts:vu}=Xt(),{getServerContext:S$}=ku(),E$=new Set(["node_modules",".git",".svn","dist","build","coverage",".nyc_output","__pycache__",".DS_Store",".next",".nuxt",".turbo",".cache","vendor","tmp","temp"]);function T$(t){try{return xu.readFileSync(t,"utf-8").split(`
|
|
401
|
+
`).map(s=>s.trim()).filter(s=>s&&!s.startsWith("#")&&!s.startsWith("!")).map(s=>s.replace(/\/$/,""))}catch{return[]}}function R$(t,e){for(let s of e)if(s===t||s.includes("*")&&new RegExp("^"+s.replace(/\./g,"\\.").replace(/\*/g,".*")+"$").test(t))return!0;return!1}function C$(t,{maxDepth:e=3,maxFiles:s=200,giPatterns:o=[]}={}){let n=Le.join(t,".gitignore"),r=[...o,...T$(n)],a=0,c=[Le.basename(t)+"/"];function l(u,d,f){if(f>e||a>=s)return;let m;try{m=xu.readdirSync(u,{withFileTypes:!0})}catch{return}m.sort((p,g)=>p.isDirectory()!==g.isDirectory()?p.isDirectory()?-1:1:p.name.localeCompare(g.name));let h=m.filter(p=>!(E$.has(p.name)||p.name.startsWith(".")&&p.name!==".env.example"||R$(p.name,r)));for(let p=0;p<h.length;p++){if(a>=s){c.push(`${d}\u2514\u2500\u2500 \u2026 (truncated)`);break}let g=h[p],y=p===h.length-1,$=y?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",w=d+(y?" ":"\u2502 "),E=g.isDirectory()?g.name+"/":g.name;c.push(`${d}${$}${E}`),a++,g.isDirectory()&&l(Le.join(u,g.name),w,f+1)}}return l(t,"",1),c.join(`
|
|
402
|
+
`)}var ci=new Map,Sn=new Map,$o=null,A$=3e4;async function jt(t){try{return await t()}catch{return null}}async function O$(){if(!$o||Date.now()>$o)return!1;let t=[Le.join(process.cwd(),"package.json"),Le.join(process.cwd(),"README.md"),Le.join(process.cwd(),".gitignore")];for(let e of t)try{let s=await ft.stat(e),o=Sn.get(e);if(!o||s.mtimeMs!==o)return!1}catch{if(Sn.has(e))return!1}try{let e=Le.join(process.cwd(),".git","HEAD"),s=await ft.stat(e),o=Sn.get(e);if(!o||s.mtimeMs!==o)return!1}catch{}return!0}async function N$(){let t=[Le.join(process.cwd(),"package.json"),Le.join(process.cwd(),"README.md"),Le.join(process.cwd(),".gitignore"),Le.join(process.cwd(),".git","HEAD")];for(let e of t)try{let s=await ft.stat(e);Sn.set(e,s.mtimeMs)}catch{Sn.delete(e)}}async function M$(t){let e="fileContext",s=ci.get(e),o=!1;if(s&&await O$()&&(o=!0),!o){let u=[],d=Le.join(t,"package.json");if(await jt(()=>ft.access(d).then(()=>!0).catch(()=>!1)))try{let y=await ft.readFile(d,"utf-8"),$=JSON.parse(y),w={name:$.name,version:$.version};$.scripts&&(w.scripts=Object.keys($.scripts).slice(0,15)),$.dependencies&&(w.deps=Object.keys($.dependencies).length),$.devDependencies&&(w.devDeps=Object.keys($.devDependencies).length),u.push(`PACKAGE: ${JSON.stringify(w)}`)}catch{}let m=Le.join(t,"README.md");if(await jt(()=>ft.access(m).then(()=>!0).catch(()=>!1))){let $=(await ft.readFile(m,"utf-8")).split(`
|
|
403
403
|
`).slice(0,50);u.push(`README (first 50 lines):
|
|
404
404
|
${$.join(`
|
|
405
|
-
`)}`)}let p=
|
|
405
|
+
`)}`)}let p=Le.join(t,".gitignore");if(await jt(()=>ft.access(p).then(()=>!0).catch(()=>!1))){let y=await ft.readFile(p,"utf-8");u.push(`GITIGNORE:
|
|
406
406
|
${y.trim()}`)}s=u.join(`
|
|
407
407
|
|
|
408
|
-
`),ci.set(e,s),$o=Date.now()+
|
|
409
|
-
${
|
|
408
|
+
`),ci.set(e,s),$o=Date.now()+A$,await N$()}let n=[s],[r,a,c,l]=await Promise.all([jt(async()=>{let{stdout:u}=await go("git branch --show-current",{cwd:t,timeout:5e3});return u.trim()}),jt(async()=>{let{stdout:u}=await go("git status --short",{cwd:t,timeout:5e3});return u.trim()}),jt(async()=>{let{stdout:u}=await go("git log --oneline -5",{cwd:t,timeout:5e3});return u.trim()}),vu()]);if(r&&n.push(`GIT BRANCH: ${r}`),a&&n.push(`GIT STATUS:
|
|
409
|
+
${a}`),c&&n.push(`RECENT COMMITS:
|
|
410
410
|
${c}`),l&&l.length>0){let u=l.map(d=>` ${d.file}`).join(`
|
|
411
411
|
`);n.push(`MERGE CONFLICTS (resolve before editing these files):
|
|
412
|
-
${u}`)}try{let u=
|
|
412
|
+
${u}`)}try{let u=S$();u&&n.push(u)}catch{}return n.join(`
|
|
413
413
|
|
|
414
|
-
`)}async function
|
|
415
|
-
${e}`);let s=
|
|
416
|
-
${s}`);let o=
|
|
414
|
+
`)}async function I$(t){let e=Le.join(t,"package.json"),s="";if(await jt(()=>ft.access(e).then(()=>!0).catch(()=>!1)))try{let a=await ft.readFile(e,"utf-8"),c=JSON.parse(a);s=`${c.name||"?"} v${c.version||"?"}`}catch{}let[n,r]=await Promise.all([jt(async()=>{let{stdout:a}=await go("git branch --show-current",{cwd:t,timeout:5e3});return a.trim()}),vu()]);if(r&&r.length>0){console.log(`${vn.red} \u26A0 ${r.length} unresolved merge conflict(s):${vn.reset}`);for(let a of r)console.log(`${vn.red} ${a.file}${vn.reset}`);console.log(`${vn.yellow} \u2192 Resolve conflicts before starting tasks${vn.reset}`)}console.log()}Su.exports={gatherProjectContext:M$,printContext:I$,generateFileTree:C$,_clearContextCache:()=>{ci.clear(),Sn.clear(),$o=null}}});var Et=q((C_,Cu)=>{var Dt=require("fs"),li=require("path"),{atomicWrite:P$}=It();function wo(){return li.join(process.cwd(),".nex","sessions")}function Eu(){let t=wo();Dt.existsSync(t)||Dt.mkdirSync(t,{recursive:!0})}function ui(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return li.join(wo(),`${e}.json`)}function di(t,e,s={}){Eu();let o=ui(t),n={name:t,createdAt:s.createdAt||new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:e.length,model:s.model||null,provider:s.provider||null,messages:e};return P$(o,JSON.stringify(n,null,2)),{path:o,name:t}}function Tu(t){let e=ui(t);if(!Dt.existsSync(e))return null;try{return JSON.parse(Dt.readFileSync(e,"utf-8"))}catch{return null}}function Ru(){Eu();let t=wo(),e=Dt.readdirSync(t).filter(o=>o.endsWith(".json")),s=[];for(let o of e)try{let n=JSON.parse(Dt.readFileSync(li.join(t,o),"utf-8"));s.push({name:n.name||o.replace(".json",""),createdAt:n.createdAt,updatedAt:n.updatedAt,messageCount:n.messageCount||0,model:n.model,provider:n.provider})}catch{}return s.sort((o,n)=>(n.updatedAt||"").localeCompare(o.updatedAt||""))}function L$(t){let e=ui(t);return Dt.existsSync(e)?(Dt.unlinkSync(e),!0):!1}function j$(){let t=Ru();return t.length===0?null:Tu(t[0].name)}var en=null,St=null,ls=null;function D$(t,e={}){t.length!==0&&(en&&clearTimeout(en),St=t,ls=e||{},en=setTimeout(()=>{St&&St.length>0&&di("_autosave",St,ls),en=null,St=null,ls=null},5e3))}function q$(){en&&(clearTimeout(en),en=null),St&&St.length>0&&(di("_autosave",St,ls),St=null,ls=null)}Cu.exports={saveSession:di,loadSession:Tu,listSessions:Ru,deleteSession:L$,getLastSession:j$,autoSave:D$,flushAutoSave:q$,_getSessionsDir:wo}});var Ft=q((A_,Lu)=>{var qt=require("fs"),bo=require("path"),F$=require("os"),{atomicWrite:U$,withFileLockSync:Au}=It();function fi(){return bo.join(process.cwd(),".nex","memory")}function us(){return bo.join(fi(),"memory.json")}function W$(){return bo.join(process.cwd(),"NEX.md")}function Ou(){return bo.join(F$.homedir(),".nex","NEX.md")}function pi(){let t=fi();qt.existsSync(t)||qt.mkdirSync(t,{recursive:!0})}function _o(){let t=us();if(!qt.existsSync(t))return{};try{return JSON.parse(qt.readFileSync(t,"utf-8"))}catch{return{}}}function Nu(t){pi(),U$(us(),JSON.stringify(t,null,2))}function B$(t,e){pi(),Au(us(),()=>{let s=_o();s[t]={value:e,updatedAt:new Date().toISOString()},Nu(s)})}function H$(t){let e=_o();return e[t]?e[t].value:null}function G$(t){return pi(),Au(us(),()=>{let e=_o();return t in e?(delete e[t],Nu(e),!0):!1})}function Mu(){let t=_o();return Object.entries(t).map(([e,s])=>({key:e,value:s.value,updatedAt:s.updatedAt}))}function Iu(){let t=Ou();if(!qt.existsSync(t))return"";try{return qt.readFileSync(t,"utf-8").trim()}catch{return""}}function Pu(){let t=W$();if(!qt.existsSync(t))return"";try{return qt.readFileSync(t,"utf-8").trim()}catch{return""}}function K$(){let t=[],e=Iu();e&&t.push(`GLOBAL INSTRUCTIONS (~/.nex/NEX.md):
|
|
415
|
+
${e}`);let s=Pu();s&&t.push(`PROJECT INSTRUCTIONS (NEX.md):
|
|
416
|
+
${s}`);let o=Mu();if(o.length>0){let n=o.map(r=>` ${r.key}: ${r.value}`).join(`
|
|
417
417
|
`);t.push(`PROJECT MEMORY:
|
|
418
418
|
${n}`)}return t.join(`
|
|
419
419
|
|
|
420
|
-
`)}
|
|
420
|
+
`)}Lu.exports={remember:B$,recall:H$,forget:G$,listMemories:Mu,loadGlobalInstructions:Iu,loadProjectInstructions:Pu,getMemoryContext:K$,_getMemoryDir:fi,_getMemoryFile:us,_getGlobalNexMdPath:Ou}});var fs=q((N_,Uu)=>{var Ve=require("fs"),En=require("path"),{C:O_}=we(),{atomicWrite:z$,withFileLockSync:Y$}=It(),ko={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"},Tn={...ko};function ju(){let t=En.join(process.cwd(),".nex","config.json");if(Ve.existsSync(t))try{let e=JSON.parse(Ve.readFileSync(t,"utf-8"));e.permissions&&(Tn={...ko,...e.permissions})}catch{}}function X$(){let t=En.join(process.cwd(),".nex"),e=En.join(t,"config.json");Ve.existsSync(t)||Ve.mkdirSync(t,{recursive:!0}),Y$(e,()=>{let s={};if(Ve.existsSync(e))try{s=JSON.parse(Ve.readFileSync(e,"utf-8"))}catch{s={}}s.permissions=Tn,z$(e,JSON.stringify(s,null,2))})}function Du(t){return Tn[t]||"ask"}function J$(t,e){return["allow","ask","deny"].includes(e)?(Tn[t]=e,!0):!1}function V$(t){return Du(t)}function Q$(){return Object.entries(Tn).map(([t,e])=>({tool:t,mode:e}))}function Z$(){Tn={...ko}}var ds={readonly:{description:"Read-only access \u2014 can search and read but not modify",allowedTools:["read_file","list_directory","search_files","glob","grep","git_status","git_diff","git_log","ask_user","web_fetch","web_search","browser_open","browser_screenshot","task_list"],blockedTools:["bash","write_file","edit_file","patch_file","deploy","ssh_exec","service_manage","container_manage","container_exec","remote_agent"],autoConfirm:!1,allowDangerous:!1},developer:{description:"Standard developer access \u2014 can read, write, and run commands",allowedTools:null,blockedTools:["deploy","service_manage","container_manage","remote_agent"],autoConfirm:!1,allowDangerous:!1},admin:{description:"Full access \u2014 all tools, including deployment and infrastructure",allowedTools:null,blockedTools:[],autoConfirm:!1,allowDangerous:!0}};function qu(){let t=En.join(process.cwd(),".nex","config.json");try{return Ve.existsSync(t)&&JSON.parse(Ve.readFileSync(t,"utf-8")).teamPermissions||null}catch{return null}}function ey(t){let e=En.join(process.cwd(),".nex"),s=En.join(e,"config.json");Ve.existsSync(e)||Ve.mkdirSync(e,{recursive:!0});let o={};try{Ve.existsSync(s)&&(o=JSON.parse(Ve.readFileSync(s,"utf-8")))}catch{o={}}o.teamPermissions=t,Ve.writeFileSync(s,JSON.stringify(o,null,2),"utf-8")}function Fu(){let t=qu();if(!t)return ds.admin;let e=t.role||"admin",s=ds[e]||ds.admin;return{...s,...t.overrides,blockedTools:[...s.blockedTools||[],...t.overrides?.blockedTools||[]]}}function ty(t){let e=Fu();return e.blockedTools&&e.blockedTools.includes(t)?{allowed:!1,reason:`Tool "${t}" is blocked by permission preset "${e.description||"custom"}"`}:e.allowedTools&&!e.allowedTools.includes(t)?{allowed:!1,reason:`Tool "${t}" is not in the allowed list for this permission level`}:{allowed:!0}}function ny(){return Object.entries(ds).map(([t,e])=>({name:t,description:e.description,toolCount:e.allowedTools?`${e.allowedTools.length} allowed`:"all allowed",blockedCount:e.blockedTools.length}))}ju();Uu.exports={getPermission:Du,setPermission:J$,checkPermission:V$,listPermissions:Q$,loadPermissions:ju,savePermissions:X$,resetPermissions:Z$,DEFAULT_PERMISSIONS:ko,PERMISSION_PRESETS:ds,loadPresetConfig:qu,savePresetConfig:ey,getEffectivePreset:Fu,isToolAllowed:ty,listPresets:ny}});var Ut=q((I_,Ku)=>{var nn=require("fs"),xo=require("path"),M_=require("readline"),{C:ie}=we(),se=null,hi=!1,gi=null,Wu=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 vo(){return xo.join(process.cwd(),".nex","plans")}function Bu(){let t=vo();nn.existsSync(t)||nn.mkdirSync(t,{recursive:!0})}function sy(t,e=[]){return se={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()},se}function oy(){return se}function ry(t){hi=t}function iy(){return hi}function ay(){return!se||se.status!=="draft"?!1:(se.status="approved",se.updatedAt=new Date().toISOString(),!0)}function cy(){return!se||se.status!=="approved"?!1:(se.status="executing",!0)}function mi(t,e){return!se||t<0||t>=se.steps.length?!1:(se.steps[t].status=e,se.updatedAt=new Date().toISOString(),se.steps.every(s=>s.status==="done"||s.status==="skipped")&&(se.status="completed"),!0)}function ly(t){if(!t)return`${ie.dim}No active plan${ie.reset}`;let e={draft:`${ie.yellow}DRAFT${ie.reset}`,approved:`${ie.green}APPROVED${ie.reset}`,executing:`${ie.blue}EXECUTING${ie.reset}`,completed:`${ie.green}COMPLETED${ie.reset}`},s=[];s.push(`
|
|
421
421
|
${ie.bold}${ie.cyan}Plan: ${t.task}${ie.reset}`),s.push(`${ie.dim}Status: ${e[t.status]||t.status}${ie.reset}
|
|
422
422
|
`);for(let o=0;o<t.steps.length;o++){let n=t.steps[o],r;switch(n.status){case"done":r=`${ie.green}\u2713${ie.reset}`;break;case"in_progress":r=`${ie.blue}\u2192${ie.reset}`;break;case"skipped":r=`${ie.dim}\u25CB${ie.reset}`;break;default:r=`${ie.dim} ${ie.reset}`}s.push(` ${r} ${ie.bold}Step ${o+1}:${ie.reset} ${n.description}`),n.files.length>0&&s.push(` ${ie.dim}Files: ${n.files.join(", ")}${ie.reset}`)}return s.push(""),s.join(`
|
|
423
|
-
`)}function
|
|
423
|
+
`)}function uy(t){if(t||(t=se),!t)return null;Bu();let e=xo.join(vo(),`${t.name}.json`);return nn.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function dy(t){let e=xo.join(vo(),`${t}.json`);if(!nn.existsSync(e))return null;try{let s=JSON.parse(nn.readFileSync(e,"utf-8"));return se=s,s}catch{return null}}function fy(){Bu();let t=vo(),e=nn.readdirSync(t).filter(o=>o.endsWith(".json")),s=[];for(let o of e)try{let n=JSON.parse(nn.readFileSync(xo.join(t,o),"utf-8"));s.push({name:n.name,task:n.task,status:n.status,steps:n.steps?n.steps.length:0,createdAt:n.createdAt})}catch{}return s.sort((o,n)=>(n.createdAt||"").localeCompare(o.createdAt||""))}function py(t){if(!t)return[];let e=[],s=t.match(/##\s+Steps?\s*\n([\s\S]*?)(?:\n##|\s*$)/i),o=s?s[1]:t,n=/^\s*(\d+)[.)]\s+(.+)/gm,r;for(;(r=n.exec(o))!==null;){let c=r[2].trim().replace(/^\*\*What\*\*:\s*/i,"").replace(/^\*\*\d+\.\*\*\s*/,"").replace(/\*\*/g,"").trim();c.length>3&&e.push({description:c,files:[],status:"pending"})}if(e.length===0){let a=/\*\*Step\s+\d+[:.]\*\*\s*(.+)/gi;for(;(r=a.exec(t))!==null;){let c=r[1].replace(/\*\*/g,"").trim();c.length>3&&e.push({description:c,files:[],status:"pending"})}}if(e.length>0){let a=/\*\*(?:Where|Files?)\*\*:\s*(.+)/gi,c=[...t.matchAll(a)];for(let l=0;l<Math.min(e.length,c.length);l++){let u=c[l][1];e[l].files=u.split(/[,\s]+/).filter(d=>/[./]/.test(d)).slice(0,5)}}return e}function my(t){gi=t}function hy(){return gi}function gy(){se=null,hi=!1,gi=null,by()}function $y(){return`
|
|
424
424
|
PLAN MODE ACTIVE: You are in analysis-only mode. You MUST NOT execute any changes.
|
|
425
425
|
|
|
426
426
|
# Allowed Tools (read-only)
|
|
427
|
-
You may ONLY use these tools: ${[...
|
|
427
|
+
You may ONLY use these tools: ${[...Wu].join(", ")}
|
|
428
428
|
Any other tool call will be blocked and returned with an error.
|
|
429
429
|
|
|
430
430
|
# Analysis Phase
|
|
@@ -455,45 +455,45 @@ Bullet list of potential issues and mitigations.
|
|
|
455
455
|
# Important
|
|
456
456
|
- Order steps by dependency (later steps may depend on earlier ones).
|
|
457
457
|
- After presenting the plan, tell the user to type \`/plan approve\` to proceed.
|
|
458
|
-
- Do NOT make any file changes \u2014 your role is analysis and planning only.`}var tn=0;function
|
|
459
|
-
`),s=[],o=!1,n="";for(let r of e){let
|
|
460
|
-
`)}function sn(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function on(t){return t?t.replace(/`([^`]+)`/g,`${_.cyan}$1${_.reset}`).replace(/\*\*([^*]+)\*\*/g,`${_.bold}$1${_.reset}`).replace(/\*([^*]+)\*/g,`${_.dim}$1${_.reset}`).replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${_.cyan}$1${_.reset} ${_.dim}($2)${_.reset}`):""}function yi(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?
|
|
461
|
-
`+s,c=r+1,
|
|
462
|
-
`+s,c=
|
|
463
|
-
`)}function
|
|
458
|
+
- Do NOT make any file changes \u2014 your role is analysis and planning only.`}var tn=0;function yy(){!se||se.status!=="executing"||(tn>0&&mi(tn-1,"done"),tn<se.steps.length&&(mi(tn,"in_progress"),tn++))}function wy(){if(!se||se.status!=="executing"||se.steps.length===0)return null;let t=Math.min(tn,se.steps.length),e=se.steps.length,s=Math.max(0,t-1),o=se.steps[s]?.description||"";return{current:t,total:e,description:o}}function by(){tn=0}var Hu=["interactive","semi-auto","autonomous"],Gu="interactive";function _y(t){return Hu.includes(t)?(Gu=t,!0):!1}function ky(){return Gu}Ku.exports={createPlan:sy,getActivePlan:oy,setPlanMode:ry,isPlanMode:iy,approvePlan:ay,startExecution:cy,updateStep:mi,formatPlan:ly,savePlan:uy,loadPlan:dy,listPlans:fy,clearPlan:gy,getPlanModePrompt:$y,setPlanContent:my,getPlanContent:hy,extractStepsFromText:py,advancePlanStep:yy,getPlanStepInfo:wy,PLAN_MODE_ALLOWED_TOOLS:Wu,setAutonomyLevel:_y,getAutonomyLevel:ky,AUTONOMY_LEVELS:Hu}});var sd=q((P_,nd)=>{var{C:_}=we();function zu(){return Math.max(10,(process.stdout.columns||80)-2)}function xy(t){if(!t)return"";let e=t.split(`
|
|
459
|
+
`),s=[],o=!1,n="";for(let r of e){let a=zu();if(r.trim().startsWith("```")){if(o)s.push(`${_.dim}${"\u2500".repeat(40)}${_.reset}`),o=!1,n="";else{o=!0,n=r.trim().substring(3).trim();let c=n?` ${n} `:"";s.push(`${_.dim}${"\u2500".repeat(3)}${c}${"\u2500".repeat(Math.max(0,37-c.length))}${_.reset}`)}continue}if(o){s.push(` ${yi(r,n)}`);continue}if(r.startsWith("### ")){s.push(`${_.bold}${_.cyan} ${sn(r.substring(4))}${_.reset}`);continue}if(r.startsWith("## ")){s.push(`${_.bold}${_.cyan} ${sn(r.substring(3))}${_.reset}`);continue}if(r.startsWith("# ")){s.push(`${_.bold}${_.cyan}${sn(r.substring(2))}${_.reset}`);continue}if(/^\s*[-*]\s/.test(r)){let c=r.match(/^(\s*)/)[1],l=r.replace(/^\s*[-*]\s/,""),u=`${c}${_.cyan}\u2022${_.reset} ${on(l)}`;s.push(rn(u,a,c+" "));continue}if(/^\s*\d+\.\s/.test(r)){let c=r.match(/^(\s*)(\d+)\.\s(.*)/);if(c){let l=c[1],u=c[2],d=c[3],f=`${l}${_.cyan}${u}.${_.reset} ${on(d)}`,m=l+" ".repeat(u.length+2);s.push(rn(f,a,m));continue}}s.push(rn(on(r),a))}return s.join(`
|
|
460
|
+
`)}function sn(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function on(t){return t?t.replace(/`([^`]+)`/g,`${_.cyan}$1${_.reset}`).replace(/\*\*([^*]+)\*\*/g,`${_.bold}$1${_.reset}`).replace(/\*([^*]+)\*/g,`${_.dim}$1${_.reset}`).replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${_.cyan}$1${_.reset} ${_.dim}($2)${_.reset}`):""}function yi(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?Yu(t):e==="bash"||e==="sh"||e==="shell"||e==="zsh"?Xu(t):e==="json"||e==="jsonc"?Ju(t):e==="python"||e==="py"?Vu(t):e==="go"||e==="golang"?Qu(t):e==="rust"||e==="rs"?Zu(t):e==="css"||e==="scss"||e==="less"?ed(t):e==="html"||e==="xml"||e==="svg"||e==="htm"?td(t):t:""}function Yu(t){let e=/\b(const|let|var|function|return|if|else|for|while|class|import|export|from|require|async|await|new|this|throw|try|catch|switch|case|break|default|typeof|instanceof)\b/g,s=/(["'`])(?:(?=(\\?))\2.)*?\1/g,o=/(\/\/.*$)/,n=/\b(\d+\.?\d*)\b/g,r=t;return r=r.replace(n,`${_.yellow}$1${_.reset}`),r=r.replace(e,`${_.magenta}$1${_.reset}`),r=r.replace(s,`${_.green}$&${_.reset}`),r=r.replace(o,`${_.dim}$1${_.reset}`),r}function Xu(t){let e=/^(\s*)([\w-]+)/,s=/(--?\w[\w-]*)/g,o=/(["'])(?:(?=(\\?))\2.)*?\1/g,n=/(#.*$)/,r=t;return r=r.replace(s,`${_.cyan}$1${_.reset}`),r=r.replace(e,`$1${_.green}$2${_.reset}`),r=r.replace(o,`${_.yellow}$&${_.reset}`),r=r.replace(n,`${_.dim}$1${_.reset}`),r}function Ju(t){let e=/("[\w-]+")\s*:/g,s=/:\s*("(?:[^"\\]|\\.)*")/g,o=/:\s*(\d+\.?\d*)/g,n=/:\s*(true|false|null)/g,r=t;return r=r.replace(e,`${_.cyan}$1${_.reset}:`),r=r.replace(s,`: ${_.green}$1${_.reset}`),r=r.replace(o,`: ${_.yellow}$1${_.reset}`),r=r.replace(n,`: ${_.magenta}$1${_.reset}`),r}function Vu(t){let e=/\b(def|class|if|elif|else|for|while|return|import|from|as|try|except|finally|raise|with|yield|lambda|pass|break|continue|and|or|not|in|is|None|True|False|self|async|await|nonlocal|global)\b/g,s=/("""[\s\S]*?"""|'''[\s\S]*?'''|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')/g,o=/(#.*$)/,n=/\b(\d+\.?\d*)\b/g,r=/^(\s*@\w+)/,a=t;return a=a.replace(n,`${_.yellow}$1${_.reset}`),a=a.replace(e,`${_.magenta}$1${_.reset}`),a=a.replace(r,`${_.cyan}$1${_.reset}`),a=a.replace(s,`${_.green}$&${_.reset}`),a=a.replace(o,`${_.dim}$1${_.reset}`),a}function Qu(t){let e=/\b(func|package|import|var|const|type|struct|interface|map|chan|go|defer|return|if|else|for|range|switch|case|default|break|continue|select|fallthrough|nil|true|false|make|new|len|cap|append|copy|delete|panic|recover)\b/g,s=/\b(string|int|int8|int16|int32|int64|uint|uint8|uint16|uint32|uint64|float32|float64|bool|byte|rune|error|any)\b/g,o=/(["'`])(?:(?=(\\?))\2.)*?\1/g,n=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,a=t;return a=a.replace(r,`${_.yellow}$1${_.reset}`),a=a.replace(s,`${_.cyan}$1${_.reset}`),a=a.replace(e,`${_.magenta}$1${_.reset}`),a=a.replace(o,`${_.green}$&${_.reset}`),a=a.replace(n,`${_.dim}$1${_.reset}`),a}function Zu(t){let e=/\b(fn|let|mut|const|struct|enum|impl|trait|pub|use|mod|crate|self|super|match|if|else|for|while|loop|return|break|continue|where|as|in|ref|move|async|await|unsafe|extern|type|static|dyn|macro_rules)\b/g,s=/\b(i8|i16|i32|i64|i128|u8|u16|u32|u64|u128|f32|f64|bool|char|str|String|Vec|Option|Result|Box|Rc|Arc|Self|Some|None|Ok|Err|true|false)\b/g,o=/(["'])(?:(?=(\\?))\2.)*?\1/g,n=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,a=/\b(\w+!)/g,c=t;return c=c.replace(r,`${_.yellow}$1${_.reset}`),c=c.replace(s,`${_.cyan}$1${_.reset}`),c=c.replace(e,`${_.magenta}$1${_.reset}`),c=c.replace(a,`${_.yellow}$1${_.reset}`),c=c.replace(o,`${_.green}$&${_.reset}`),c=c.replace(n,`${_.dim}$1${_.reset}`),c}function ed(t){let e=/^(\s*)([\w-]+)\s*:/,s=/:\s*([^;]+)/,o=/^(\s*[.#@][\w-]+)/,n=/\b(\d+\.?\d*(px|em|rem|%|vh|vw|s|ms|deg|fr)?)\b/g,r=/(\/\*.*?\*\/|\/\/.*$)/,a=/(#[0-9a-fA-F]{3,8})\b/g,c=t;return c=c.replace(a,`${_.yellow}$1${_.reset}`),c=c.replace(n,`${_.yellow}$1${_.reset}`),c=c.replace(e,`$1${_.cyan}$2${_.reset}:`),c=c.replace(o,`$1${_.magenta}$&${_.reset}`),c=c.replace(r,`${_.dim}$1${_.reset}`),c}function td(t){let e=/<\/?(\w[\w-]*)/g,s=/\s([\w-]+)=/g,o=/(["'])(?:(?=(\\?))\2.)*?\1/g,n=/(<!--.*?-->)/g,r=/(&\w+;)/g,a=t;return a=a.replace(n,`${_.dim}$1${_.reset}`),a=a.replace(o,`${_.green}$&${_.reset}`),a=a.replace(e,`<${_.magenta}$1${_.reset}`),a=a.replace(s,` ${_.cyan}$1${_.reset}=`),a=a.replace(r,`${_.yellow}$1${_.reset}`),a}function rn(t,e,s=""){if(!e||e<10)return t;let o="",n=0,r=-1,a=0,c=0,l=t.length;for(;a<l;){if(t[a]==="\x1B"){let u=a+1;if(u<l&&t[u]==="["){for(u++;u<l&&!/[a-zA-Z]/.test(t[u]);)u++;u<l&&u++}a=u;continue}if(t[a]===" "&&(r=a),n++,n>e&&r!==-1){o+=t.slice(c,r)+`
|
|
461
|
+
`+s,c=r+1,a=c,n=s.length,r=-1;continue}n>e&&r===-1&&(o+=t.slice(c,a)+`
|
|
462
|
+
`+s,c=a,n=s.length+1),a++}return o+=t.slice(c),o}function vy(t,e){if(!t||t.length===0)return"";let s=t.map((a,c)=>{let l=e.reduce((u,d)=>Math.max(u,(d[c]||"").length),0);return Math.max(a.length,l)}),o=s.map(a=>"\u2500".repeat(a+2)).join("\u253C"),n=t.map((a,c)=>` ${_.bold}${a.padEnd(s[c])}${_.reset} `).join("\u2502"),r=[];r.push(`${_.dim}\u250C${o.replace(/┼/g,"\u252C")}\u2510${_.reset}`),r.push(`${_.dim}\u2502${_.reset}${n}${_.dim}\u2502${_.reset}`),r.push(`${_.dim}\u251C${o}\u2524${_.reset}`);for(let a of e){let c=t.map((l,u)=>` ${(a[u]||"").padEnd(s[u])} `).join(`${_.dim}\u2502${_.reset}`);r.push(`${_.dim}\u2502${_.reset}${c}${_.dim}\u2502${_.reset}`)}return r.push(`${_.dim}\u2514${o.replace(/┼/g,"\u2534")}\u2518${_.reset}`),r.join(`
|
|
463
|
+
`)}function Sy(t,e,s,o=30){let n=s>0?Math.round(e/s*100):0,r=Math.round(n/100*o),a=o-r,c=n>=100?_.green:n>50?_.yellow:_.cyan;return` ${t} ${c}${"\u2588".repeat(r)}${_.dim}${"\u2591".repeat(a)}${_.reset} ${n}% (${e}/${s})`}var $i=class{constructor(){this.buffer="",this.inCodeBlock=!1,this.codeBlockLang="",this.lineCount=0,this._cursorTimer=null,this._cursorFrame=0,this._cursorActive=!1}_safeWrite(e){try{this.lineCount+=(e.match(/\n/g)||[]).length,process.stdout.write(e)}catch(s){if(s.code!=="EPIPE")throw s}}_cursorWrite(e){try{process.stderr.write(e)}catch(s){if(s.code!=="EPIPE")throw s}}startCursor(){process.stderr.isTTY&&(this._cursorActive=!0,this._cursorFrame=0,this._cursorWrite("\x1B[?25l"),this._renderCursor(),this._cursorTimer=setInterval(()=>this._renderCursor(),100))}_renderCursor(){let s=[0,1,2,3,4,3,2,1],o=s[this._cursorFrame%s.length],n="";for(let r=0;r<5;r++)n+=r===o?"\x1B[36m\u25CF\x1B[0m":" ";this._cursorWrite(`\x1B[2K\r${n}`),this._cursorFrame++}_clearCursorLine(){this._cursorActive&&this._cursorWrite("\x1B[2K\r")}stopCursor(){this._cursorTimer&&(clearInterval(this._cursorTimer),this._cursorTimer=null),this._cursorActive&&(this._cursorWrite("\x1B[2K\r\x1B[?25h"),this._cursorActive=!1)}push(e){if(!e)return;this._clearCursorLine(),this.buffer+=e;let s;for(;(s=this.buffer.indexOf(`
|
|
464
464
|
`))!==-1;){let o=this.buffer.substring(0,s);this.buffer=this.buffer.substring(s+1),this._renderLine(o)}this._cursorActive&&(this._renderCursor(),this._cursorTimer&&clearInterval(this._cursorTimer),this._cursorTimer=setInterval(()=>this._renderCursor(),100))}flush(){this.stopCursor(),this.buffer&&(this._renderLine(this.buffer),this.buffer=""),this.inCodeBlock&&(this._safeWrite(`${_.dim}${"\u2500".repeat(40)}${_.reset}
|
|
465
|
-
`),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){let s=
|
|
465
|
+
`),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){let s=zu();if(e.trim().startsWith("```")){if(this.inCodeBlock)this._safeWrite(`${_.dim}${"\u2500".repeat(40)}${_.reset}
|
|
466
466
|
`),this.inCodeBlock=!1,this.codeBlockLang="";else{this.inCodeBlock=!0,this.codeBlockLang=e.trim().substring(3).trim();let n=this.codeBlockLang?` ${this.codeBlockLang} `:"";this._safeWrite(`${_.dim}${"\u2500".repeat(3)}${n}${"\u2500".repeat(Math.max(0,37-n.length))}${_.reset}
|
|
467
467
|
`)}return}if(this.inCodeBlock){this._safeWrite(` ${yi(e,this.codeBlockLang)}
|
|
468
468
|
`);return}if(e.startsWith("### ")){this._safeWrite(`${_.bold}${_.cyan} ${sn(e.substring(4))}${_.reset}
|
|
469
469
|
`);return}if(e.startsWith("## ")){this._safeWrite(`${_.bold}${_.cyan} ${sn(e.substring(3))}${_.reset}
|
|
470
470
|
`);return}if(e.startsWith("# ")){this._safeWrite(`${_.bold}${_.cyan}${sn(e.substring(2))}${_.reset}
|
|
471
|
-
`);return}if(/^\s*[-*]\s/.test(e)){let n=e.match(/^(\s*)/)[1],r=e.replace(/^\s*[-*]\s/,""),
|
|
472
|
-
`);return}if(/^\s*\d+\.\s/.test(e)){let n=e.match(/^(\s*)(\d+)\.\s(.*)/);if(n){let r=n[1],
|
|
471
|
+
`);return}if(/^\s*[-*]\s/.test(e)){let n=e.match(/^(\s*)/)[1],r=e.replace(/^\s*[-*]\s/,""),a=`${n}${_.cyan}\u2022${_.reset} ${on(r)}`,c=rn(a,s,n+" ");this._safeWrite(`${c}
|
|
472
|
+
`);return}if(/^\s*\d+\.\s/.test(e)){let n=e.match(/^(\s*)(\d+)\.\s(.*)/);if(n){let r=n[1],a=n[2],c=n[3],l=`${r}${_.cyan}${a}.${_.reset} ${on(c)}`,u=r+" ".repeat(a.length+2),d=rn(l,s,u);this._safeWrite(`${d}
|
|
473
473
|
`);return}}let o=rn(on(e),s);this._safeWrite(`${o}
|
|
474
|
-
`)}};
|
|
475
|
-
`)}var
|
|
474
|
+
`)}};nd.exports={renderMarkdown:xy,renderInline:on,stripHeadingMarkers:sn,highlightCode:yi,highlightJS:Yu,highlightBash:Xu,highlightJSON:Ju,highlightPython:Vu,highlightGo:Qu,highlightRust:Zu,highlightCSS:ed,highlightHTML:td,renderTable:vy,renderProgress:Sy,wrapAnsi:rn,StreamRenderer:$i}});var _i=q((L_,ad)=>{var{execSync:Ey}=require("child_process"),wi=require("path"),ps=require("fs"),bi=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function od(){return wi.join(process.cwd(),".nex","hooks")}function Ty(){return wi.join(process.cwd(),".nex","config.json")}function rd(){let t=Ty();if(!ps.existsSync(t))return{};try{return JSON.parse(ps.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function So(t){if(!bi.includes(t))return[];let e=[],s=od(),o=wi.join(s,t);ps.existsSync(o)&&e.push(o);let n=rd();if(n[t]){let r=Array.isArray(n[t])?n[t]:[n[t]];e.push(...r)}return e}function id(t,e={},s=3e4){try{return{success:!0,output:Ey(t,{cwd:process.cwd(),encoding:"utf-8",timeout:s,env:{...process.env,...e},stdio:["pipe","pipe","pipe"]}).trim()}}catch(o){return{success:!1,error:o.stderr?o.stderr.trim():o.message}}}function Ry(t,e={}){let s=So(t);if(s.length===0)return[];let o={};for(let[r,a]of Object.entries(e))o[`NEX_${r.toUpperCase()}`]=String(a);let n=[];for(let r of s){let a=id(r,o);if(n.push({command:r,...a}),!a.success&&t.startsWith("pre-"))break}return n}function Cy(t){return So(t).length>0}function Ay(){let t=[];for(let e of bi){let s=So(e);s.length>0&&t.push({event:e,commands:s})}return t}function Oy(){let t=od();return ps.existsSync(t)||ps.mkdirSync(t,{recursive:!0}),t}ad.exports={HOOK_EVENTS:bi,loadHookConfig:rd,getHooksForEvent:So,executeHook:id,runHooks:Ry,hasHooks:Cy,listHooks:Ay,initHooksDir:Oy}});var de=q((U_,kd)=>{var{C:x,Spinner:Rn,TaskProgress:Ny,formatToolCall:My,formatResult:Iy,formatToolSummary:hd,formatSectionHeader:ki,formatMilestone:Py,setActiveTaskProgress:j_}=we(),{MilestoneTracker:Ly}=xc(),{callStream:jy}=be(),{parseToolArgs:Dy}=qs(),{executeTool:qy}=ut(),{gatherProjectContext:Fy}=yo(),{fitToContext:Uy,forceCompress:xi,getUsage:cd,estimateTokens:Wy}=lt(),{autoSave:By,flushAutoSave:Hy}=Et();function pt(t){By(t),Hy()}var{getMemoryContext:Gy}=Ft(),{checkPermission:Ky,setPermission:zy,savePermissions:Yy}=fs(),{confirm:gd,setAllowAlwaysHandler:Xy}=Ie(),{isPlanMode:Oo,getPlanModePrompt:Jy,PLAN_MODE_ALLOWED_TOOLS:$d,setPlanContent:Vy,extractStepsFromText:Qy,createPlan:Zy,getActivePlan:D_,startExecution:q_,advancePlanStep:ew,getPlanStepInfo:tw}=Ut(),{StreamRenderer:nw}=sd(),{runHooks:ld}=_i(),{routeMCPCall:sw,getMCPToolDefinitions:ow}=Ks(),{getSkillInstructions:rw,getSkillToolDefinitions:iw,routeSkillCall:aw}=Lt(),{trackUsage:cw}=$n(),{validateToolArgs:lw}=Or(),{filterToolsForModel:ud,getModelTier:uw,PROVIDER_DEFAULT_TIER:F_}=oo(),{getConfiguredProviders:dw,getActiveProviderName:ms,getActiveModelId:To,setActiveModel:dd,MODEL_EQUIVALENTS:No}=be(),Ni=require("fs"),Mi=require("path"),fw=(()=>{let t=parseInt(process.env.NEX_MILESTONE_STEPS??"5",10);return Number.isFinite(t)&&t>=0?t:5})();function pw(t){let e=Py(t.phaseName,t.stepCount,t.toolCounts,t.elapsed,t.filesRead,t.filesModified);process.stdout.write(`${e}
|
|
475
|
+
`)}var fd=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi;function mw(t){let e=[],s;for(fd.lastIndex=0;(s=fd.exec(t))!==null;){let o=s[1].trim(),n=o.startsWith("~")?o.replace("~",process.env.HOME||""):Mi.resolve(o);Ni.existsSync(n)&&e.push({raw:o,abs:n})}return e}function hw(t){let e=Ni.readFileSync(t),s=Mi.extname(t).toLowerCase().replace(".",""),o=s==="jpg"||s==="jpeg"?"image/jpeg":s==="png"?"image/png":s==="gif"?"image/gif":s==="webp"?"image/webp":"image/png";return{data:e.toString("base64"),media_type:o}}function yd(t){let e=mw(t);if(e.length===0)return t;let s=[{type:"text",text:t}];for(let o of e)try{let{data:n,media_type:r}=hw(o.abs);s.push({type:"image",media_type:r,data:n})}catch{}return s.length>1?s:t}var vi=null,Si=null,Ei=null;function Cn(){if(vi===null){let{TOOL_DEFINITIONS:t}=ut();vi=t}return Si===null&&(Si=iw()),Ei===null&&(Ei=ow()),[...vi,...Si,...Ei]}var Ai=50;function gw(t){Number.isFinite(t)&&t>0&&(Ai=t)}var Ro=()=>null;function $w(t){Ro=t}var hs=null,Oi=null,An=null,Co=new Map,yw=1e4,ww=6e3,bw=/\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 _w(t){return!t||typeof t!="string"?t:t.replace(bw,(e,s)=>`${s}=***REDACTED***`)}var kw=7e3,xw=4e3;function vw(t,e=null){let s=_w(t),o=Wy(s),n=e==="read_file"?kw:yw,r=e==="read_file"?xw:ww;if(o>n)try{let{compressToolResult:a}=lt();return a(s,r)}catch{return s}return s}function wd(t){try{let{getActiveModel:e}=be(),s=e(),o=s?`${s.provider}:${s.id}`:"default";if(Co.has(o))return Co.get(o);let n=ud(t);return Co.set(o,n),n}catch{return ud(t)}}function Sw(){Co.clear()}async function bd(){try{let t=require("fs").promises,e=require("path"),s=[e.join(process.cwd(),"package.json"),e.join(process.cwd(),".git","HEAD"),e.join(process.cwd(),"README.md"),e.join(process.cwd(),"NEX.md")],n=(await Promise.allSettled(s.map(r=>t.stat(r).then(a=>`${r}:${a.mtimeMs}`)))).filter(r=>r.status==="fulfilled").map(r=>r.value);try{let{getMemoryContextHash:r}=Ft(),a=r();a&&n.push(`memory:${a}`)}catch{}try{let r=e.join(process.cwd(),".nex","brain");if(Ni.existsSync(r)){let a=await t.stat(r);n.push(`brain:${a.mtimeMs}`)}}catch{}return n.join("|")}catch{return`fallback:${Date.now()}`}}function Ew(){hs=null,Oi=null,An=null}var Tw=new Set(["spawn_agents"]),Ti=5,Ri=3,Eo=2,Rw=parseInt(process.env.NEX_STALE_WARN_MS||"60000",10),pd=parseInt(process.env.NEX_STALE_ABORT_MS||"120000",10),Cw=process.env.NEX_STALE_AUTO_SWITCH!=="0";function Aw(t){try{let e=require("fs"),s=require("path"),o=s.join(process.cwd(),".nex","plans");e.existsSync(o)||e.mkdirSync(o,{recursive:!0});let n=s.join(o,"current-plan.md");e.writeFileSync(n,t,"utf-8")}catch{}}Xy(t=>{zy(t,"allow"),Yy(),console.log(`${x.green} \u2713 ${t}: always allow${x.reset}`)});async function Ow(t){let e=t.function.name,s=Dy(t.function.arguments),o=t.id||`cli-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!s){let l=Cn().find(d=>d.function.name===e),u=l?JSON.stringify(l.function.parameters,null,2):"unknown";return console.log(`${x.yellow} \u26A0 ${e}: malformed arguments, sending schema hint${x.reset}`),{callId:o,fnName:e,args:null,canExecute:!1,errorResult:{role:"tool",content:`ERROR: Malformed tool arguments. Could not parse your arguments as JSON.
|
|
476
476
|
Raw input: ${typeof t.function.arguments=="string"?t.function.arguments.substring(0,200):"N/A"}
|
|
477
477
|
|
|
478
478
|
Expected JSON schema for "${e}":
|
|
479
479
|
${u}
|
|
480
480
|
|
|
481
|
-
Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:o}}}let n=
|
|
482
|
-
`)[0]}${x.reset}`),{callId:o,fnName:e,args:s,canExecute:!1,errorResult:{role:"tool",content:n.error,tool_call_id:o}};let r=n.corrected||s;if(n.corrected){let c=Object.keys(s),l=Object.keys(n.corrected),u=c.filter(d=>!l.includes(d));u.length&&console.log(`${x.dim} \u2713 ${e}: corrected args (${u.join(", ")})${x.reset}`)}if(Oo()
|
|
483
|
-
...(truncated ${n.length-5e4} chars)`:n,
|
|
484
|
-
`)[0],c=
|
|
485
|
-
`)}function
|
|
486
|
-
`];o?n.push(`RESPONSE LANGUAGE: You MUST always respond in ${o}. This overrides any language defaults from your training. Never output Chinese, Japanese, or any other language in your responses \u2014 even when summarizing or thinking. ${o} only.`):n.push("RESPONSE LANGUAGE: Always respond in the same language as the user's message. If the user writes in German, respond in German; if in English, respond in English; etc."),n.push("CODE EXAMPLES: Always show actual, working code examples \u2014 never pseudocode or placeholder snippets."),n.push("COMPLETENESS RULES:"),n.push(" \u2022 ALWAYS show actual code when explaining implementations \u2014 never describe without showing"),n.push(" \u2022 FILE CREATION TASKS (Makefile, Dockerfile, config files): paste the COMPLETE file content in a fenced code block in your TEXT RESPONSE \u2014 writing a file with a tool does NOT make it visible. The fenced code block MUST appear in your response, not just via write_file."),n.push(" \u2022 Include complete examples with full context (imports, function signatures, error handling)"),n.push(' \u2022 Show alternative approaches when relevant (e.g., "Alternative: use util.promisify instead")'),n.push(" \u2022 Include edge cases in explanations (empty input, null values, boundary conditions)"),n.push(" \u2022 Provide platform-specific guidance when commands differ by OS (Linux/macOS/Windows)"),n.push(' \u2022 For Makefiles, paste the COMPLETE Makefile code DIRECTLY in your text response \u2014 every target, recipe, dependency, and .PHONY line. Writing the Makefile with a tool does NOT count as showing it. The Makefile MUST appear verbatim in your chat text as a code block, even if you also wrote it to a file. Never describe structure without showing the actual code. CRITICAL: use EXACTLY the command specified \u2014 if the task says "runs jest", write "jest" in the recipe, NEVER "npm test". npm test is NOT jest. Recipes need real TAB indentation. ONE .PHONY line listing ALL phony targets.'),n.push(" \u2022 For dataclasses, paste the COMPLETE dataclass code DIRECTLY in your text response \u2014 @dataclass decorator, all fields with types and defaults, full __post_init__ validation. Writing the file with a tool does NOT count as showing the code. The code MUST appear verbatim in your chat text, even if you also wrote it to a file."),n.push(" \u2022 For cron expressions, re-read the exact time boundaries in the task before writing. If asked for 8-18h, the range is 8,9,...,18 \u2014 write exactly what was asked, not an approximation."),n.push(' \u2022 When a task explicitly specifies a tool (e.g., "use tsc"), NEVER mention alternatives (e.g., "swc build") \u2014 use exactly what was requested.'),n.push(' \u2022 In Makefile prerequisites, NEVER use shell glob patterns like src/**/*.ts \u2014 make does not expand these natively. Keep prerequisite lists explicit or omit them. When a Makefile target says "runs jest", call jest directly in the recipe (not npm test).'),n.push(" \u2022 For bash in-place text replacements with backups: use ONLY ONE backup method \u2014 either sed -i.bak (let sed create the backup) OR cp file file.bak followed by sed -i (no extension). Never use both cp and sed -i.bak together \u2014 that produces redundant double backups (file.bak and file.bak.bak)."),n.push(" \u2022 For iterative array-flattening (flattenDeep): use push() and reverse() at the end \u2014 NEVER unshift(). unshift is O(n) per call making the whole function O(n^2). The iterative version MUST use a loop (while/for) and an explicit stack array \u2014 zero recursive calls. If a function calls itself, it is recursive regardless of its name. Never label a recursive function as iterative."),n.push(" \u2022 FORBIDDEN: when refactoring callbacks to async/await, NEVER write try { ... } catch(e) { throw e } \u2014 this is an explicit anti-pattern. WRONG: async function f() { try { const d = await readFile(..); await writeFile(.., d); } catch(e) { throw e; } } \u2014 RIGHT: async function f() { const d = await readFile(..); await writeFile(.., d); } \u2014 omit the try-catch entirely, let rejections propagate."),n.push(' \u2022 Docker HEALTHCHECK: always include --start-period=30s (or appropriate startup time) so the container has time to initialise before failures are counted. Also note that curl may not be available in minimal Node.js images \u2014 offer wget or "node -e" as alternatives.'),n.push(' \u2022 When fixing a bash word-splitting bug like "for f in $(ls *.txt)": replace the entire $(ls *.txt) with a bare glob directly \u2014 "for f in *.txt". The fix is eliminating the ls command and $() subshell entirely. Emphasise this in the explanation: the glob in the for loop prevents word splitting because the shell expands the glob into separate words before the loop \u2014 there is no subshell output to split. CRITICAL: NEVER suggest "ls -N" or any ls variant as a fix \u2014 ls -N outputs filenames one per line, but word splitting still occurs on each line when used in a subshell expansion. The only correct fix is the bare glob pattern.');let r=e||(o?"English":null);r&&n.push(`CODE LANGUAGE: Write all code comments, docstrings, variable descriptions, and inline documentation in ${r}.`);let
|
|
481
|
+
Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:o}}}let n=lw(e,s);if(!n.valid)return console.log(`${x.yellow} \u26A0 ${e}: ${n.error.split(`
|
|
482
|
+
`)[0]}${x.reset}`),{callId:o,fnName:e,args:s,canExecute:!1,errorResult:{role:"tool",content:n.error,tool_call_id:o}};let r=n.corrected||s;if(n.corrected){let c=Object.keys(s),l=Object.keys(n.corrected),u=c.filter(d=>!l.includes(d));u.length&&console.log(`${x.dim} \u2713 ${e}: corrected args (${u.join(", ")})${x.reset}`)}if(Oo()&&!$d.has(e))return console.log(`${x.yellow} \u2717 ${e}: blocked in plan mode${x.reset}`),{callId:o,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`PLAN MODE: '${e}' is blocked. Only read-only tools are allowed. Present your plan as text output instead of making changes.`,tool_call_id:o}};let a=Ky(e);if(a==="deny")return console.log(`${x.red} \u2717 ${e}: denied by permissions${x.reset}`),{callId:o,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`DENIED: Tool '${e}' is blocked by permissions`,tool_call_id:o}};if(a==="ask"){let c=` Allow ${e}?`;return e==="bash"&&r.command&&(c=` bash: \`${r.command.substring(0,80)}${r.command.length>80?"\u2026":""}\`?`),await gd(c,{toolName:e})?{callId:o,fnName:e,args:r,canExecute:!0,confirmedByUser:!0,errorResult:null}:{callId:o,fnName:e,args:r,canExecute:!1,confirmedByUser:!1,errorResult:{role:"tool",content:`CANCELLED: User declined ${e}`,tool_call_id:o}}}return{callId:o,fnName:e,args:r,canExecute:!0,confirmedByUser:!0,errorResult:null}}async function Nw(t,e,s={}){let o=await aw(t,e);if(o!==null)return o;let n=await sw(t,e);return n!==null?n:qy(t,e,s)}function Mw(t,e){switch(t){case"read_file":case"write_file":case"edit_file":case"patch_file":case"list_directory":return e.path||"";case"bash":return(e.command||"").substring(0,60);case"grep":case"search_files":case"glob":return e.pattern||"";case"web_fetch":return(e.url||"").substring(0,50);case"web_search":return(e.query||"").substring(0,40);default:return""}}async function Ci(t,e=!1){e||console.log(My(t.fnName,t.args));let s=ld("pre-tool",{tool_name:t.fnName});if(!e&&s.length>0)for(let m of s)m.success?console.log(`${x.dim} [hook pre-tool] ${m.command} \u2192 ${m.output||"ok"}${x.reset}`):console.log(`${x.yellow} [hook pre-tool] ${m.command} \u2192 ERROR: ${m.error}${x.reset}`);yt?.onToolStart&&yt.onToolStart(t.fnName,t.args);let o=await Nw(t.fnName,t.args,{silent:!0,autoConfirm:t.confirmedByUser===!0}),n=String(o??""),r=n.length>5e4?n.substring(0,5e4)+`
|
|
483
|
+
...(truncated ${n.length-5e4} chars)`:n,a=r.split(`
|
|
484
|
+
`)[0],c=a.startsWith("ERROR")||a.includes("CANCELLED")||a.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(r)&&/✗ Agent/.test(r),l=hd(t.fnName,t.args,r,c);e||(console.log(Iy(r)),console.log(l)),yt?.onToolEnd&&yt.onToolEnd(t.fnName,l,!c);let u=ld("post-tool",{tool_name:t.fnName});if(!e&&u.length>0)for(let m of u)m.success?console.log(`${x.dim} [hook post-tool] ${m.command} \u2192 ${m.output||"ok"}${x.reset}`):console.log(`${x.yellow} [hook post-tool] ${m.command} \u2192 ERROR: ${m.error}${x.reset}`);return{msg:{role:"tool",content:vw(r,t.fnName),tool_call_id:t.callId},summary:l}}async function Iw(t,e=!1,s={}){let o=new Array(t.length),n=[],r=[],a=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=Mw(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}`}a=new Rn(u),a.start()}}async function c(){if(r.length!==0){if(r.length===1){let l=r[0],{msg:u,summary:d}=await Ci(t[l],e);o[l]=u,n.push(d)}else{let l=r.map(d=>Ci(t[d],e)),u=await Promise.all(l);for(let d=0;d<r.length;d++)o[r[d]]=u[d].msg,n.push(u[d].summary)}r=[]}}for(let l=0;l<t.length;l++){let u=t[l];if(!u.canExecute){await c(),o[l]=u.errorResult,n.push(hd(u.fnName,u.args||{},u.errorResult.content,!0));continue}if(Tw.has(u.fnName)){await c(),u.fnName==="spawn_agents"&&a&&(a.stop(),a=null);let{msg:d,summary:f}=await Ci(u,e);o[l]=d,n.push(f)}else r.push(l)}if(await c(),a&&a.stop(),e&&n.length>0&&!s.skipSummaries)for(let l of n)console.log(l);return{results:o,summaries:n}}var ne=[],md=300,Ao=[];function Pw(t){Ao.push(t.trim())}function Lw(){return Ao.length===0?null:Ao.splice(0,Ao.length).join(`
|
|
485
|
+
`)}function jw(){let t=process.env.NEX_LANGUAGE,e=process.env.NEX_CODE_LANGUAGE,s=process.env.NEX_COMMIT_LANGUAGE,o=!t||t==="auto"?"English":t,n=[`# Language Rules (CRITICAL \u2014 enforce strictly)
|
|
486
|
+
`];o?n.push(`RESPONSE LANGUAGE: You MUST always respond in ${o}. This overrides any language defaults from your training. Never output Chinese, Japanese, or any other language in your responses \u2014 even when summarizing or thinking. ${o} only.`):n.push("RESPONSE LANGUAGE: Always respond in the same language as the user's message. If the user writes in German, respond in German; if in English, respond in English; etc."),n.push("CODE EXAMPLES: Always show actual, working code examples \u2014 never pseudocode or placeholder snippets."),n.push("COMPLETENESS RULES:"),n.push(" \u2022 ALWAYS show actual code when explaining implementations \u2014 never describe without showing"),n.push(" \u2022 FILE CREATION TASKS (Makefile, Dockerfile, config files): paste the COMPLETE file content in a fenced code block in your TEXT RESPONSE \u2014 writing a file with a tool does NOT make it visible. The fenced code block MUST appear in your response, not just via write_file."),n.push(" \u2022 Include complete examples with full context (imports, function signatures, error handling)"),n.push(' \u2022 Show alternative approaches when relevant (e.g., "Alternative: use util.promisify instead")'),n.push(" \u2022 Include edge cases in explanations (empty input, null values, boundary conditions)"),n.push(" \u2022 Provide platform-specific guidance when commands differ by OS (Linux/macOS/Windows)"),n.push(' \u2022 For Makefiles, paste the COMPLETE Makefile code DIRECTLY in your text response \u2014 every target, recipe, dependency, and .PHONY line. Writing the Makefile with a tool does NOT count as showing it. The Makefile MUST appear verbatim in your chat text as a code block, even if you also wrote it to a file. Never describe structure without showing the actual code. CRITICAL: use EXACTLY the command specified \u2014 if the task says "runs jest", write "jest" in the recipe, NEVER "npm test". npm test is NOT jest. Recipes need real TAB indentation. ONE .PHONY line listing ALL phony targets.'),n.push(" \u2022 For dataclasses, paste the COMPLETE dataclass code DIRECTLY in your text response \u2014 @dataclass decorator, all fields with types and defaults, full __post_init__ validation. Writing the file with a tool does NOT count as showing the code. The code MUST appear verbatim in your chat text, even if you also wrote it to a file."),n.push(" \u2022 For cron expressions, re-read the exact time boundaries in the task before writing. If asked for 8-18h, the range is 8,9,...,18 \u2014 write exactly what was asked, not an approximation."),n.push(' \u2022 When a task explicitly specifies a tool (e.g., "use tsc"), NEVER mention alternatives (e.g., "swc build") \u2014 use exactly what was requested.'),n.push(' \u2022 In Makefile prerequisites, NEVER use shell glob patterns like src/**/*.ts \u2014 make does not expand these natively. Keep prerequisite lists explicit or omit them. When a Makefile target says "runs jest", call jest directly in the recipe (not npm test).'),n.push(" \u2022 For bash in-place text replacements with backups: use ONLY ONE backup method \u2014 either sed -i.bak (let sed create the backup) OR cp file file.bak followed by sed -i (no extension). Never use both cp and sed -i.bak together \u2014 that produces redundant double backups (file.bak and file.bak.bak)."),n.push(" \u2022 For iterative array-flattening (flattenDeep): use push() and reverse() at the end \u2014 NEVER unshift(). unshift is O(n) per call making the whole function O(n^2). The iterative version MUST use a loop (while/for) and an explicit stack array \u2014 zero recursive calls. If a function calls itself, it is recursive regardless of its name. Never label a recursive function as iterative."),n.push(" \u2022 FORBIDDEN: when refactoring callbacks to async/await, NEVER write try { ... } catch(e) { throw e } \u2014 this is an explicit anti-pattern. WRONG: async function f() { try { const d = await readFile(..); await writeFile(.., d); } catch(e) { throw e; } } \u2014 RIGHT: async function f() { const d = await readFile(..); await writeFile(.., d); } \u2014 omit the try-catch entirely, let rejections propagate."),n.push(' \u2022 Docker HEALTHCHECK: always include --start-period=30s (or appropriate startup time) so the container has time to initialise before failures are counted. Also note that curl may not be available in minimal Node.js images \u2014 offer wget or "node -e" as alternatives.'),n.push(' \u2022 When fixing a bash word-splitting bug like "for f in $(ls *.txt)": replace the entire $(ls *.txt) with a bare glob directly \u2014 "for f in *.txt". The fix is eliminating the ls command and $() subshell entirely. Emphasise this in the explanation: the glob in the for loop prevents word splitting because the shell expands the glob into separate words before the loop \u2014 there is no subshell output to split. CRITICAL: NEVER suggest "ls -N" or any ls variant as a fix \u2014 ls -N outputs filenames one per line, but word splitting still occurs on each line when used in a subshell expansion. The only correct fix is the bare glob pattern.');let r=e||(o?"English":null);r&&n.push(`CODE LANGUAGE: Write all code comments, docstrings, variable descriptions, and inline documentation in ${r}.`);let a=s||(o?"English":null);return a&&n.push(`COMMIT MESSAGES: Write all git commit messages in ${a}.`),o&&n.push(`
|
|
487
487
|
This is a hard requirement. Always respond in ${o}. Do NOT switch to any other language \u2014 even if the user writes to you in German, French, or any other language, your reply MUST be in ${o}.`),n.join(`
|
|
488
488
|
`)+`
|
|
489
489
|
|
|
490
|
-
`}function
|
|
490
|
+
`}function Dw(){if(An!==null)return An;try{let e=dw().flatMap(n=>n.models.map(r=>({spec:`${n.name}:${r.id}`,tier:uw(r.id,n.name),name:r.name})));if(e.length<2)return An="","";let s={full:"complex tasks (refactor, implement, generate)",standard:"regular tasks (edit, fix, analyze)",essential:"simple tasks (read, search, list)"},o=`
|
|
491
491
|
# Sub-Agent Model Routing
|
|
492
492
|
|
|
493
493
|
`;o+='Sub-agents auto-select models by task complexity. Override with `model: "provider:model"` in agent definition.\n\n',o+=`| Model | Tier | Auto-assigned for |
|
|
494
494
|
|---|---|---|
|
|
495
495
|
`;for(let n of e)o+=`| ${n.spec} | ${n.tier} | ${s[n.tier]||n.tier} |
|
|
496
|
-
`;return An=o,o}catch(t){return process.env.NEX_DEBUG&&console.error("[agent] model routing guide failed:",t.message),An="",""}}async function
|
|
496
|
+
`;return An=o,o}catch(t){return process.env.NEX_DEBUG&&console.error("[agent] model routing guide failed:",t.message),An="",""}}async function _d(){let t=await bd();if(hs!==null&&t===Oi)return hs;let e=await Fy(process.cwd()),s=Gy(),o=rw(),n=Oo()?Jy():"",r=jw();return hs=`You are Nex Code, an expert coding assistant. You help with programming tasks by reading, writing, and editing files, running commands, and answering questions.
|
|
497
497
|
|
|
498
498
|
WORKING DIRECTORY: ${process.cwd()}
|
|
499
499
|
All relative paths resolve from this directory.
|
|
@@ -675,7 +675,7 @@ This applies to bash output, SSH output, grep results, and all other tool output
|
|
|
675
675
|
- Good for: reading multiple files, analyzing separate modules.
|
|
676
676
|
- Bad for: tasks that depend on each other or modify the same file.
|
|
677
677
|
- Max 5 parallel agents.
|
|
678
|
-
${
|
|
678
|
+
${Dw()}
|
|
679
679
|
|
|
680
680
|
# Edit Reliability (Critical)
|
|
681
681
|
|
|
@@ -726,31 +726,31 @@ You have access to a persistent knowledge base in .nex/brain/.
|
|
|
726
726
|
- Include tags in frontmatter for better retrieval
|
|
727
727
|
- The user reviews all brain writes via /brain review or git diff
|
|
728
728
|
|
|
729
|
-
`,Oi=t,hs}function
|
|
730
|
-
`):[]).filter(f=>{let m=f.split(".").pop();return r.has(m)});if(
|
|
731
|
-
\u{1F4E6} ${h}${p}`}}catch{}return u}function
|
|
732
|
-
${x.dim} ${c}${x.reset}`),l>=30&&process.stdout.isTTY){let u=s.size>0?`Done \u2014 ${s.size} ${s.size===1?"file":"files"} modified in ${l}s`:`Done \u2014 ${t} ${t===1?"step":"steps"} in ${l}s`;
|
|
733
|
-
`),m==="")return c({action:"quit"});let p=
|
|
729
|
+
`,Oi=t,hs}function qw(){ne=[]}function Fw(){ne.length>md&&ne.splice(0,ne.length-md)}function Uw(){return ne.length}function Ww(){return ne}function Bw(t){ne=t}async function Hw(){let{execFile:t}=require("child_process"),e=require("fs"),s=process.cwd(),o=(f,m)=>new Promise(h=>{t(f,m,{cwd:s,timeout:3e3},(p,g)=>{h(p?"":(g||"").trim())})}),[n]=await Promise.all([o("find",[".","-type","f","-not","-path","*/node_modules/*","-not","-path","*/.git/*","-not","-path","*/dist/*","-not","-path","*/.next/*","-not","-path","*/build/*","-not","-path","*/__pycache__/*","-not","-path","*/vendor/*"])]),r=new Set(["js","ts","jsx","tsx","py","go","rs","rb","java","cpp","c","cs"]),a=(n?n.split(`
|
|
730
|
+
`):[]).filter(f=>{let m=f.split(".").pop();return r.has(m)});if(a.length<3)return null;let c={};for(let f of a){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=Mi.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+=`
|
|
731
|
+
\u{1F4E6} ${h}${p}`}}catch{}return u}function Gw(t){if(process.platform==="darwin")try{let{execFileSync:e}=require("child_process");e("osascript",["-e",`display notification "${t.replace(/"/g,'\\"')}" with title "nex-code"`],{timeout:3e3,stdio:"ignore"})}catch{}}function mt(t,e,s,o,n,{suppressHint:r=!1}={}){if(t<1)return;let a=[...e.values()].reduce((u,d)=>u+d,0),c=`\u2500\u2500 ${t} ${t===1?"step":"steps"} \xB7 ${a} ${a===1?"tool":"tools"}`,l=0;if(n){let u=Date.now()-n;l=Math.round(u/1e3),c+=l>=60?` \xB7 ${Math.floor(l/60)}m ${l%60}s`:` \xB7 ${l}s`}if(s.size>0&&(c+=` \xB7 ${s.size} ${s.size===1?"file":"files"} modified`),c+=" \u2500\u2500",console.log(`
|
|
732
|
+
${x.dim} ${c}${x.reset}`),l>=30&&process.stdout.isTTY){let u=s.size>0?`Done \u2014 ${s.size} ${s.size===1?"file":"files"} modified in ${l}s`:`Done \u2014 ${t} ${t===1?"step":"steps"} in ${l}s`;Gw(u)}s.size>0?console.log(`${x.dim} \u{1F4A1} /diff \xB7 /commit \xB7 /undo${x.reset}`):!r&&o.size>=5&&s.size===0&&t>=3?console.log(`${x.dim} \u{1F4A1} Found issues? Say "fix 1" or "apply all fixes"${x.reset}`):o.size>0&&t>=2&&console.log(`${x.dim} \u{1F4A1} /save \xB7 /clear${x.reset}`)}async function Kw(){if(!process.stdout.isTTY)return{action:"quit"};let t=ms(),e=To(),s=No.fast?.[t],o=No.strong?.[t],n=s&&s!==e,r=o&&o!==e&&o!==s,a=[];a.push({key:"r",label:`Retry with current model ${x.dim}(${e})${x.reset}`}),n&&a.push({key:"f",label:`Switch to ${x.bold}${s}${x.reset} ${x.dim}\u2014 fast, low latency${x.reset}`,model:s}),r&&a.push({key:"s",label:`Switch to ${x.bold}${o}${x.reset} ${x.dim}\u2014 reliable tool-calling, medium speed${x.reset}`,model:o}),a.push({key:"q",label:`${x.dim}Quit${x.reset}`}),console.log(),console.log(`${x.yellow} Stream stale \u2014 all retries exhausted.${x.reset} What would you like to do?`);for(let c of a)console.log(` ${x.cyan}[${c.key}]${x.reset} ${c.label}`);return process.stdout.write(` ${x.yellow}> ${x.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}
|
|
733
|
+
`),m==="")return c({action:"quit"});let p=a.find(g=>g.key===h);!p||p.key==="q"||!p.model&&p.key!=="r"?c({action:"quit"}):p.key==="r"?c({action:"retry"}):c({action:"switch",model:p.model,provider:t})};l.on("data",f)})}var yt=null;async function zw(t,e=null){yt=e;let s=yd(t);ne.push({role:"user",content:s}),Fw();let{setOnChange:o}=io(),n=null,r=0;o((ye,xe)=>{ye==="create"?(n&&n.stop(),n=new Ny(xe.name,xe.tasks),n.setStats({tokens:r}),n.start()):ye==="update"&&n?n.updateTask(xe.id,xe.status):ye==="clear"&&n&&(n.stop(),n=null)});let a=await _d(),c=a;try{let{getBrainContext:ye}=ss(),xe=await ye(t);xe&&(c=a+`
|
|
734
734
|
`+xe+`
|
|
735
|
-
`)}catch(ye){process.env.NEX_DEBUG&&console.error("[agent] brain context failed:",ye.message)}let l=[{role:"system",content:c},...ne],u=new Rn("Thinking...");u.start();let f=ne.length===1?
|
|
735
|
+
`)}catch(ye){process.env.NEX_DEBUG&&console.error("[agent] brain context failed:",ye.message)}let l=[{role:"system",content:c},...ne],u=new Rn("Thinking...");u.start();let f=ne.length===1?Hw().catch(()=>null):Promise.resolve(null),m=Cn(),[{messages:h,compressed:p,compacted:g,tokensRemoved:y},$]=await Promise.all([Uy(l,m),f]),w=cd(l,m);if(u.stop(),$&&console.log(`${x.dim}${$}${x.reset}`),g)console.log(`${x.dim} [context compacted \u2014 summary (~${y} tokens freed)]${x.reset}`);else if(p){let ye=w.limit>0?Math.round(y/w.limit*100):0;console.log(`${x.dim} [context compressed \u2014 ~${y} tokens freed (${ye}%)]${x.reset}`)}w.percentage>85&&console.log(`${x.yellow} \u26A0 Context ${Math.round(w.percentage)}% full \u2014 consider /clear or /save + start fresh${x.reset}`);let E=h,b=0,k=0,v=0,R=0,C=0,A=9,j=0,Q=0,X=new Map,H=new Set,G=new Set,U=Date.now(),pe=new Ly(fw),Te=new Map,ve=2,Me=4,Ae=new Map,et=5,vs=8,N=0,D=6,K=10,W=0,B=2,re=3,Z=0,z,te=Ai,Oe=0,ze=3,Ye=!1;e:for(;;){for(Ye=!1,z=0;z<te&&!Ro()?.aborted;z++){let xe=!0;Q>0&&ew();let wt=null;if(n&&n.isActive())n._paused&&n.resume();else if(!n){let M,I=tw();if(I&&I.total>1){let me=I.description.length>40?I.description.slice(0,37)+"\u2026":I.description;M=`Plan step ${I.current}/${I.total}: ${me}`}else M=Q>0?`Thinking... (step ${Q+1})`:"Thinking...";wt=new Rn(M),wt.start()}let zo=!0,Ln="",tt=new nw,Ot,Yo=Date.now(),Ss=!1,Xo=new AbortController,ca=setInterval(()=>{let M=Date.now()-Yo;if(M>=pd)tt._clearCursorLine(),console.log(`${x.yellow} \u26A0 Stream stale for ${Math.round(M/1e3)}s \u2014 aborting and retrying${x.reset}`),Xo.abort();else if(M>=Rw&&!Ss){Ss=!0,tt._clearCursorLine();let I=No.fast?.[ms()],me=v>0?` (retry ${v+1}/${Eo})`:"",V=Math.round((pd-M)/1e3);console.log(`${x.yellow} \u26A0 No tokens received for ${Math.round(M/1e3)}s \u2014 waiting...${me}${x.reset}`),I&&I!==To()?console.log(`${x.dim} \u{1F4A1} Will auto-switch to ${I} in ~${V}s if no tokens arrive${x.reset}`):console.log(`${x.dim} \u{1F4A1} Ctrl+C to abort \xB7 auto-abort in ~${V}s${x.reset}`)}},5e3),nt="",bt=null;try{let M=wd(Cn()),I=Oo()?M.filter(ee=>$d.has(ee.function.name)):M,me=Ro(),V=new AbortController;me&&me.addEventListener("abort",()=>V.abort(),{once:!0}),Xo.signal.addEventListener("abort",()=>V.abort(),{once:!0}),Ot=await jy(E,I,{signal:V.signal,onThinkingToken:()=>{Yo=Date.now(),Ss=!1,yt?.onThinkingToken&&yt.onThinkingToken()},onToken:ee=>{if(Yo=Date.now(),Ss=!1,yt?.onToken){yt.onToken(ee),Ln+=ee;return}nt+=ee,process.stdout.isTTY?bt||(bt=setTimeout(()=>{nt&&tt&&tt.push(nt),nt="",bt=null},50)):(tt.push(nt),nt=""),zo&&(n&&!n._paused?n.pause():wt&&wt.stop(),xe||(xe=!0),tt.startCursor(),zo=!1),Ln+=ee}})}catch(M){if(clearInterval(ca),bt&&(clearTimeout(bt),bt=null),nt&&tt&&(tt.push(nt),nt=""),n&&!n._paused&&n.pause(),wt&&wt.stop(),tt.stopCursor(),Xo.signal.aborted&&!Ro()?.aborted){if(v++,v>Eo){if(R<1){R++,console.log(`${x.yellow} \u26A0 Stale retries exhausted \u2014 last-resort force-compress...${x.reset}`);let he=Cn(),{messages:Xe,tokensRemoved:un}=xi(E,he);E=Xe,console.log(`${x.dim} [force-compressed \u2014 ~${un} tokens freed]${x.reset}`),v=0,z--;continue}n&&(n.stop(),n=null);let Y=await Kw();if(Y.action==="quit"){o(null),mt(Q,X,H,G,U),pt(ne);break}Y.action==="switch"&&(dd(`${Y.provider}:${Y.model}`),console.log(`${x.green} \u2713 Switched to ${Y.provider}:${Y.model}${x.reset}`)),v=0,z--;continue}let V=v===1?3e3:5e3;if(v>=1&&j<1){j++,console.log(`${x.yellow} \u26A0 Stale retry ${v}/${Eo} \u2014 force-compressing before retry...${x.reset}`);let Y=Cn(),{messages:he,tokensRemoved:Xe}=xi(E,Y,!0);if(E=he,Xe>0&&console.log(`${x.dim} [force-compressed \u2014 ~${Xe} tokens freed]${x.reset}`),Cw){let un=No.fast?.[ms()];un&&un!==To()&&(dd(`${ms()}:${un}`),console.log(`${x.cyan} \u26A1 Auto-switched to ${un} to avoid further stale timeouts${x.reset}`),console.log(`${x.dim} (disable with NEX_STALE_AUTO_SWITCH=0)${x.reset}`))}}else console.log(`${x.yellow} \u26A0 Stale retry ${v}/${Eo} \u2014 retrying in ${V/1e3}s...${x.reset}`);let ee=new Rn(`Waiting ${V/1e3}s before retry...`);ee.start(),await new Promise(Y=>setTimeout(Y,V)),ee.stop(),z--;continue}if(M.name==="AbortError"||M.name==="CanceledError"||M.message?.includes("canceled")||M.message?.includes("aborted")){n&&(n.stop(),n=null),o(null),mt(Q,X,H,G,U),pt(ne);break}let I=M.message;if(M.code==="ECONNREFUSED"||M.message.includes("ECONNREFUSED"))I="Connection refused \u2014 please check your internet connection or API endpoint";else if(M.code==="ENOTFOUND"||M.message.includes("ENOTFOUND"))I="Network error \u2014 could not reach the API server. Please check your connection";else if(M.code==="ETIMEDOUT"||M.message.includes("timeout"))I="Request timed out \u2014 the API server took too long to respond. Please try again";else if(M.message.includes("401")||M.message.includes("Unauthorized"))I="Authentication failed \u2014 please check your API key in the .env file";else if(M.message.includes("403")||M.message.includes("Forbidden"))I="Access denied \u2014 your API key may not have permission for this model";else if(M.message.includes("400")){if(R<3&&C<A){R++,C++;let V=R===3||j>0;console.log(V?`${x.yellow} \u26A0 Bad request (400) \u2014 nuclear compression (attempt ${R}/3, dropping history)...${x.reset}`:`${x.yellow} \u26A0 Bad request (400) \u2014 force-compressing and retrying... (attempt ${R}/3)${x.reset}`);let ee=Cn(),{messages:Y,tokensRemoved:he}=xi(E,ee,V);E=Y,he>0&&console.log(`${x.dim} [force-compressed \u2014 ~${he} tokens freed]${x.reset}`),z--;continue}I="Context too large to compress \u2014 use /clear to start fresh"}else M.message.includes("500")||M.message.includes("502")||M.message.includes("503")||M.message.includes("504")?I="API server error \u2014 the provider is experiencing issues. Please try again in a moment":(M.message.includes("fetch failed")||M.message.includes("fetch"))&&(I="Network request failed \u2014 please check your internet connection");if(console.log(`${x.red} \u2717 ${I}${x.reset}`),M.message.includes("429")){if(b++,b>Ti){console.log(`${x.red} Rate limit: max retries (${Ti}) exceeded. Try again later or use /budget to check your limits.${x.reset}`),n&&(n.stop(),n=null),o(null),mt(Q,X,H,G,U),pt(ne);break}let V=Math.min(1e4*Math.pow(2,b-1),12e4),ee=new Rn(`Rate limit \u2014 waiting ${Math.round(V/1e3)}s (retry ${b}/${Ti})`);ee.start(),await new Promise(Y=>setTimeout(Y,V)),ee.stop();continue}if(M.message.includes("socket disconnected")||M.message.includes("TLS")||M.message.includes("ECONNRESET")||M.message.includes("ECONNABORTED")||M.message.includes("ETIMEDOUT")||M.code==="ECONNRESET"||M.code==="ECONNABORTED"){if(k++,k>Ri){console.log(`${x.red} Network error: max retries (${Ri}) exceeded. Check your connection and try again.${x.reset}`),n&&(n.stop(),n=null),o(null),mt(Q,X,H,G,U),pt(ne);break}let V=Math.min(2e3*Math.pow(2,k-1),3e4),ee=new Rn(`Network error \u2014 retrying in ${Math.round(V/1e3)}s (${k}/${Ri})`);ee.start(),await new Promise(Y=>setTimeout(Y,V)),ee.stop(),z--;continue}n&&(n.stop(),n=null),o(null),mt(Q,X,H,G,U),pt(ne);break}clearInterval(ca),b=0,k=0,zo&&(n&&!n._paused&&n.pause(),wt&&wt.stop()),bt&&(clearTimeout(bt),bt=null),nt&&tt&&(tt.push(nt),nt=""),Ln&&tt.flush(),k=0,v=0,Ot&&Ot.usage&&(cw(ms(),To(),Ot.usage.prompt_tokens||0,Ot.usage.completion_tokens||0),r+=(Ot.usage.prompt_tokens||0)+(Ot.usage.completion_tokens||0),n&&n.setStats({tokens:r}));let{content:Jo,tool_calls:Bt}=Ot,Vo={role:"assistant",content:Jo||""};if(Bt&&Bt.length>0&&(Vo.tool_calls=Bt),ne.push(Vo),E.push(Vo),!Bt||Bt.length===0){let M=(Jo||"").trim().length>0||Ln.trim().length>0;if(!M&&Q>0&&z<Ai-1){let I={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."};E.push(I),ne.push(I);continue}if(Oo()&&M){let I=(Jo||Ln||"").trim();Vy(I),Aw(I);let me=Qy(I);if(me.length>0){let V=ne.find(he=>he.role==="user"),ee=typeof V?.content=="string"?V.content.slice(0,120):"Task";Zy(ee,me);let Y=me.length===1?"step":"steps";console.log(`
|
|
736
736
|
${x.cyan}${x.bold}Plan ready${x.reset} ${x.dim}(${me.length} ${Y} extracted).${x.reset} Type ${x.cyan}/plan approve${x.reset}${x.dim} to execute, or ${x.reset}${x.cyan}/plan edit${x.reset}${x.dim} to review.${x.reset}`)}else console.log(`
|
|
737
|
-
${x.cyan}${x.bold}Plan ready.${x.reset} ${x.dim}Type ${x.reset}${x.cyan}/plan approve${x.reset}${x.dim} to execute, or ask follow-up questions to refine.${x.reset}`)}n&&(n.stop(),n=null),o(null),mt(Q,X,H,G,U),pt(ne);return}Q++,Q>=1&&(xe=!1);for(let M of Bt){let I=M.function.name;X.set(I,(X.get(I)||0)+1)}let ct=await Promise.all(Bt.map(M=>
|
|
738
|
-
`)):
|
|
739
|
-
`)),!jn.skipSummaries){let M=
|
|
740
|
-
`)[0],ee=!V.startsWith("ERROR")&&!V.startsWith("CANCELLED");if(ee&&["write_file","edit_file","patch_file"].includes(I.fnName)&&I.args&&I.args.path){H.add(I.args.path);let Y=(Te.get(I.args.path)||0)+1;Te.set(I.args.path,Y);let he=I.args.path.split("/").slice(-2).join("/");if(Y===ve){console.log(`${x.yellow} \u26A0 Loop warning: "${he}" edited ${Y}\xD7 \u2014 possible edit loop${x.reset}`);let Xe={role:"user",content:`[SYSTEM WARNING] You have edited "${I.args.path}" ${Y} times already. STOP. Do NOT edit this file again unless absolutely necessary. Read it once to verify the current state, make at most ONE more targeted change, then move on or declare the task complete. Further edits to this file will abort the session.`};ne.push(Xe),E.push(Xe)}else if(Y>=Me){console.log(`${x.red} \u2716 Loop abort: "${he}" edited ${Y}\xD7 \u2014 aborting to prevent runaway loop${x.reset}`),n&&(n.stop(),n=null),o(null),mt(Q,X,H,G,U,{suppressHint:!0}),pt(ne);return}}if(I.fnName==="bash_exec"&&I.args&&I.args.command){let Y=I.args.command.replace(/\s+/g," ").trim().slice(0,100),he=(Ae.get(Y)||0)+1;if(Ae.set(Y,he),he===et){console.log(`${x.yellow} \u26A0 Loop warning: same bash command run ${he}\xD7 \u2014 possible debug loop${x.reset}`);let Xe={role:"user",content:`[SYSTEM WARNING] You have run the same or similar bash command ${he} times. This looks like a debug loop. STOP repeating the same command. Try a completely different approach or declare that the current approach is not working and explain why.`};ne.push(Xe),E.push(Xe)}else if(he>=vs){console.log(`${x.red} \u2716 Loop abort: same bash command run ${he}\xD7 \u2014 aborting runaway debug loop${x.reset}`),n&&(n.stop(),n=null),o(null),mt(Q,X,H,G,U,{suppressHint:!0}),pt(ne);return}}if(ee)N=0,Ye=!0;else if(N++,N===D){console.log(`${x.yellow} \u26A0 Loop warning: ${N} consecutive tool errors \u2014 possible stuck loop${x.reset}`);let Y={role:"user",content:`[SYSTEM WARNING] ${N} 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.`};ne.push(Y),E.push(Y)}else if(N>=K){console.log(`${x.red} \u2716 Loop abort: ${N} consecutive errors \u2014 aborting stuck loop${x.reset}`),n&&(n.stop(),n=null),o(null),mt(Q,X,H,G,U,{suppressHint:!0}),pt(ne);return}if(ee&&I.fnName==="read_file"&&I.args&&I.args.path&&G.add(I.args.path),I.fnName==="spawn_agents"){let Y=(me.match(/\bStatus: done\b/g)||[]).length;if((me.match(/\bStatus: truncated\b/g)||[]).length>0&&Y===0){if(W++,W===B){console.log(`${x.yellow} \u26A0 Swarm warning: all sub-agents hit iteration limit ${W}\xD7 in a row${x.reset}`);let Xe={role:"user",content:`[SYSTEM WARNING] All sub-agents hit their iteration limit without completing the task for the ${W}nd time in a row. Change strategy: do not spawn further agents for the same search \u2014 try a different approach or report what you know.`};ne.push(Xe),E.push(Xe)}else if(W>=re){console.log(`${x.red} \u2716 Swarm abort: all sub-agents hit iteration limit ${W}\xD7 \u2014 aborting stuck swarm${x.reset}`),n&&(n.stop(),n=null),o(null),mt(Q,X,H,G,U,{suppressHint:!0}),pt(ne);return}}else Y>0&&(W=0)}}for(let M of
|
|
741
|
-
${x.yellow}\u26A0 Max iterations reached.${x.reset}`),await
|
|
742
|
-
`),await t(c,
|
|
743
|
-
`?(o.setRawMode(n||!1),o.removeListener("data",
|
|
737
|
+
${x.cyan}${x.bold}Plan ready.${x.reset} ${x.dim}Type ${x.reset}${x.cyan}/plan approve${x.reset}${x.dim} to execute, or ask follow-up questions to refine.${x.reset}`)}n&&(n.stop(),n=null),o(null),mt(Q,X,H,G,U),pt(ne);return}Q++,Q>=1&&(xe=!1);for(let M of Bt){let I=M.function.name;X.set(I,(X.get(I)||0)+1)}let ct=await Promise.all(Bt.map(M=>Ow(M)));{let M=cd(E,[]),I=M.percentage,me=ct.some(ee=>ee.canExecute&&ee.fnName==="read_file"&&!ee.args?.line_end);if(I>=70&&me&&Z<70||I>=85&&Z<85){Z=I;let ee=I>=85?"URGENT":"WARNING",Y=me?`You are about to read a file without line_start/line_end. At ${Math.round(I)}% context this risks a 400 context-overflow error. Read only the specific lines you need (use line_start/line_end). Do NOT re-read files already in context.`:`Context is ${Math.round(I)}% full. Avoid large file reads. Wrap up exploration and complete the task with what you know.`,he={role:"user",content:`[SYSTEM ${ee}] Context ${Math.round(I)}% full (${M.used}/${M.limit} tokens). ${Y}`};ne.push(he),E.push(he),I>=85&&console.log(`${x.yellow} \u26A0 Context ${Math.round(I)}% full \u2014 agent warned to use targeted reads${x.reset}`)}}let jn=n?{skipSpinner:!0,skipSummaries:!0}:{},Af=ct.some(M=>M.fnName==="ask_user"),la=!jn.skipSummaries&&!xe,Qo=null;la&&!Af?(xe=!0,jn.skipSpinner=!0,process.stdout.isTTY?(process.stdout.write(ki(ct,Q,!1,"blink")),Qo=!0):yt||process.stdout.write(ki(ct,Q,!1)+`
|
|
738
|
+
`)):la&&(xe=!0,jn.skipSpinner=!0),n&&n._paused&&n.resume();let{results:ua,summaries:Of}=await Iw(ct,!0,{...jn,skipSummaries:!0});if(Qo&&(Qo=null,process.stdout.write(`\r\x1B[2K${ki(ct,Q,!1)}
|
|
739
|
+
`)),!jn.skipSummaries){let M=Of.filter((V,ee)=>!(ct[ee]&&ct[ee].fnName==="ask_user"));for(let V of M)console.log(V);console.log("");let I=ct.filter(V=>V&&V.fnName!=="ask_user").map(V=>V.fnName),me=pe.record(0,I,G,H);me&&pw(me)}for(let M=0;M<ct.length;M++){let I=ct[M];if(!I.canExecute)continue;let me=ua[M].content,V=me.split(`
|
|
740
|
+
`)[0],ee=!V.startsWith("ERROR")&&!V.startsWith("CANCELLED");if(ee&&["write_file","edit_file","patch_file"].includes(I.fnName)&&I.args&&I.args.path){H.add(I.args.path);let Y=(Te.get(I.args.path)||0)+1;Te.set(I.args.path,Y);let he=I.args.path.split("/").slice(-2).join("/");if(Y===ve){console.log(`${x.yellow} \u26A0 Loop warning: "${he}" edited ${Y}\xD7 \u2014 possible edit loop${x.reset}`);let Xe={role:"user",content:`[SYSTEM WARNING] You have edited "${I.args.path}" ${Y} times already. STOP. Do NOT edit this file again unless absolutely necessary. Read it once to verify the current state, make at most ONE more targeted change, then move on or declare the task complete. Further edits to this file will abort the session.`};ne.push(Xe),E.push(Xe)}else if(Y>=Me){console.log(`${x.red} \u2716 Loop abort: "${he}" edited ${Y}\xD7 \u2014 aborting to prevent runaway loop${x.reset}`),n&&(n.stop(),n=null),o(null),mt(Q,X,H,G,U,{suppressHint:!0}),pt(ne);return}}if(I.fnName==="bash_exec"&&I.args&&I.args.command){let Y=I.args.command.replace(/\s+/g," ").trim().slice(0,100),he=(Ae.get(Y)||0)+1;if(Ae.set(Y,he),he===et){console.log(`${x.yellow} \u26A0 Loop warning: same bash command run ${he}\xD7 \u2014 possible debug loop${x.reset}`);let Xe={role:"user",content:`[SYSTEM WARNING] You have run the same or similar bash command ${he} times. This looks like a debug loop. STOP repeating the same command. Try a completely different approach or declare that the current approach is not working and explain why.`};ne.push(Xe),E.push(Xe)}else if(he>=vs){console.log(`${x.red} \u2716 Loop abort: same bash command run ${he}\xD7 \u2014 aborting runaway debug loop${x.reset}`),n&&(n.stop(),n=null),o(null),mt(Q,X,H,G,U,{suppressHint:!0}),pt(ne);return}}if(ee)N=0,Ye=!0;else if(N++,N===D){console.log(`${x.yellow} \u26A0 Loop warning: ${N} consecutive tool errors \u2014 possible stuck loop${x.reset}`);let Y={role:"user",content:`[SYSTEM WARNING] ${N} 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.`};ne.push(Y),E.push(Y)}else if(N>=K){console.log(`${x.red} \u2716 Loop abort: ${N} consecutive errors \u2014 aborting stuck loop${x.reset}`),n&&(n.stop(),n=null),o(null),mt(Q,X,H,G,U,{suppressHint:!0}),pt(ne);return}if(ee&&I.fnName==="read_file"&&I.args&&I.args.path&&G.add(I.args.path),I.fnName==="spawn_agents"){let Y=(me.match(/\bStatus: done\b/g)||[]).length;if((me.match(/\bStatus: truncated\b/g)||[]).length>0&&Y===0){if(W++,W===B){console.log(`${x.yellow} \u26A0 Swarm warning: all sub-agents hit iteration limit ${W}\xD7 in a row${x.reset}`);let Xe={role:"user",content:`[SYSTEM WARNING] All sub-agents hit their iteration limit without completing the task for the ${W}nd time in a row. Change strategy: do not spawn further agents for the same search \u2014 try a different approach or report what you know.`};ne.push(Xe),E.push(Xe)}else if(W>=re){console.log(`${x.red} \u2716 Swarm abort: all sub-agents hit iteration limit ${W}\xD7 \u2014 aborting stuck swarm${x.reset}`),n&&(n.stop(),n=null),o(null),mt(Q,X,H,G,U,{suppressHint:!0}),pt(ne);return}}else Y>0&&(W=0)}}for(let M of ua)ne.push(M),E.push(M);let da=Lw();if(da){let M={role:"user",content:`[User note mid-run]: ${da}`};ne.push(M),E.push(M),console.log(`${x.cyan} \u270E Context added${x.reset}`)}}if(z>=te){n&&(n.stop(),n=null),o(null),mt(Q,X,H,G,U),pt(ne);let{getActiveProviderName:ye}=be();if(ye()==="ollama"&&Oe<ze){if(H.size===0&&!Ye){console.log(`${x.yellow} \u26A0 Max iterations reached with no progress. Stopping.${x.reset}`);break e}Oe++,te=20,console.log(`${x.dim} \u2500\u2500 auto-extending (+20 turns, ext ${Oe}/${ze}) \u2500\u2500${x.reset}`);continue e}if(console.log(`
|
|
741
|
+
${x.yellow}\u26A0 Max iterations reached.${x.reset}`),await gd(" Continue for 20 more turns?")){te=20;continue e}console.log(`${x.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${x.reset}`)}break e}}kd.exports={processInput:zw,clearConversation:qw,getConversationLength:Uw,getConversationMessages:Ww,setConversationMessages:Bw,setAbortSignalGetter:$w,setMaxIterations:gw,invalidateSystemPromptCache:Ew,clearToolFilterCache:Sw,getCachedFilteredTools:wd,buildSystemPrompt:_d,getProjectContextHash:bd,buildUserContent:yd,injectMidRunNote:Pw}});var be=q((W_,Td)=>{var{OllamaProvider:Yw}=Pa(),{OpenAIProvider:Xw}=ec(),{AnthropicProvider:Jw}=oc(),{GeminiProvider:Vw}=cc(),{LocalProvider:Qw}=dc(),{checkBudget:Zw}=$n(),Ii={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"}},xd={};for(let[t,e]of Object.entries(Ii))for(let s of Object.values(e))xd[s]=t;function vd(t,e){let s=xd[t];return s&&Ii[s][e]||t}var Ce={},Ge=null,Se=null,gs=[];function at(){if(Object.keys(Ce).length>0)return;On("ollama",new Yw),On("openai",new Xw),On("anthropic",new Jw),On("gemini",new Vw),On("local",new Qw);let t=process.env.DEFAULT_PROVIDER||"ollama",e=process.env.DEFAULT_MODEL||null;Ce[t]?(Ge=t,Se=e||Ce[t].defaultModel):(Ge="ollama",Se="kimi-k2.5");let s=process.env.FALLBACK_CHAIN;s&&(gs=s.split(",").map(o=>o.trim()).filter(Boolean))}function On(t,e){Ce[t]=e}function e0(t){return at(),Ce[t]||null}function Pi(){return at(),Ce[Ge]||null}function t0(){return at(),Ge}function n0(){return at(),Se}function s0(){at();let t=Pi();if(!t)return{id:Se,name:Se,provider:Ge};let e=t.getModel(Se);return e?{...e,provider:Ge}:{id:Se,name:Se,provider:Ge}}function Sd(t){if(!t)return{provider:null,model:null};let e=t.indexOf(":");if(e>0){let s=t.slice(0,e);if(Ce[s]||["ollama","openai","anthropic","gemini","local"].includes(s))return{provider:s,model:t.slice(e+1)}}return{provider:null,model:t}}function o0(t){at();let{provider:e,model:s}=Sd(t);if(e){let n=Ce[e];return n&&(n.getModel(s)||e==="local"||e==="ollama")?(Ge=e,Se=s,Mo(),!0):!1}let o=Pi();if(o&&o.getModel(s))return Se=s,Mo(),!0;for(let[n,r]of Object.entries(Ce))if(r.getModel(s))return Ge=n,Se=s,Mo(),!0;return!1}function Mo(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=de();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=lt();t()}catch{}}function r0(){at();let t=new Set;for(let e of Object.values(Ce))for(let s of e.getModelNames())t.add(s);return Array.from(t)}function i0(){return at(),Object.entries(Ce).map(([t,e])=>({provider:t,configured:e.isConfigured(),models:Object.values(e.getModels()).map(s=>({...s,active:t===Ge&&s.id===Se}))}))}function a0(){at();let t=[];for(let[e,s]of Object.entries(Ce)){let o=s.isConfigured();for(let n of Object.values(s.getModels()))t.push({spec:`${e}:${n.id}`,name:n.name,provider:e,configured:o})}return t}function c0(t){gs=Array.isArray(t)?t:[]}function l0(){return[...gs]}function u0(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 Ed(t){let e=[Ge,...gs.filter(r=>r!==Ge)],s,o=0,n=0;for(let r=0;r<e.length;r++){let a=e[r],c=Ce[a];if(!c||!c.isConfigured())continue;n++;let l=Zw(a);if(!l.allowed){o++,s=new Error(`Budget limit reached for ${a}: $${l.spent.toFixed(2)} / $${l.limit.toFixed(2)}`);continue}try{let u=r>0,d=u?vd(Se,a):Se;return u&&d!==Se&&process.stderr.write(` [fallback: ${a}:${d}]
|
|
742
|
+
`),await t(c,a,d)}catch(u){if(s=u,u0(u)&&r<e.length-1)continue;throw u}}throw o>0&&o===n?new Error("All providers are over budget. Use /budget to check limits or /budget <provider> off to remove a limit."):n===0?new Error("No configured provider available"):s||new Error("No configured provider available")}async function d0(t,e,s={}){return at(),Ed((o,n,r)=>o.stream(t,e,{model:r,signal:s.signal,...s}))}async function f0(t,e,s={}){if(at(),s.provider){let o=Ce[s.provider];if(!o||!o.isConfigured())throw new Error(`Provider '${s.provider}' is not available`);let n={model:s.model||Se,...s};try{return await o.chat(t,e,n)}catch(r){if(typeof o.stream=="function")try{return await o.stream(t,e,{...n,onToken:()=>{}})}catch{}throw r}}return Ed(async(o,n,r)=>{try{return await o.chat(t,e,{model:r,...s})}catch(a){if(typeof o.stream=="function")try{return await o.stream(t,e,{model:r,...s,onToken:()=>{}})}catch{}throw a}})}function p0(){at();let t=[];for(let[e,s]of Object.entries(Ce))s.isConfigured()&&t.push({name:e,models:Object.values(s.getModels())});return t}function m0(){for(let t of Object.keys(Ce))delete Ce[t];Ge=null,Se=null,gs=[]}Td.exports={registerProvider:On,getProvider:e0,getActiveProvider:Pi,getActiveProviderName:t0,getActiveModelId:n0,getActiveModel:s0,setActiveModel:o0,getModelNames:r0,parseModelSpec:Sd,listProviders:i0,listAllModels:a0,callStream:d0,callChat:f0,getConfiguredProviders:p0,setFallbackChain:c0,getFallbackChain:l0,resolveModelForProvider:vd,MODEL_EQUIVALENTS:Ii,_reset:m0}});var ji=q((B_,Rd)=>{"use strict";var Tt=require("fs"),Io=require("path"),h0=require("readline"),oe="\x1B[0m",Li="\x1B[1m",Qe="\x1B[2m",Po="\x1B[33m",Nn="\x1B[36m",Lo="\x1B[32m";function g0(t){return(e,s="")=>new Promise(o=>{let n=s?` ${Qe}[${s}]${oe}`:"";t.question(` ${Nn}${e}${n}${oe}: `,r=>o(r.trim()||s))})}function jo(t,e){return new Promise(s=>{e&&e.pause(),process.stdout.write(` ${Nn}${t}${oe}: `);let o=process.stdin,n=o.isRaw,r="";o.setRawMode(!0),o.resume(),o.setEncoding("utf8");let a=c=>{c==="\r"||c===`
|
|
743
|
+
`?(o.setRawMode(n||!1),o.removeListener("data",a),process.stdout.write(`
|
|
744
744
|
`),e&&e.resume(),s(r)):c===""?(process.stdout.write(`
|
|
745
|
-
`),process.exit(0)):c==="\x7F"?r.length>0&&(r=r.slice(0,-1),process.stdout.write("\b \b")):(r+=c,process.stdout.write("*"))};o.on("data",
|
|
745
|
+
`),process.exit(0)):c==="\x7F"?r.length>0&&(r=r.slice(0,-1),process.stdout.write("\b \b")):(r+=c,process.stdout.write("*"))};o.on("data",a)})}async function $0({rl:t=null,force:e=!1}={}){if(!e){let m=Tt.existsSync(Io.join(process.cwd(),".env"))||Tt.existsSync(Io.join(__dirname,"..",".env")),h=process.env.ANTHROPIC_API_KEY||process.env.OPENAI_API_KEY||process.env.GEMINI_API_KEY||process.env.OPENROUTER_API_KEY,p=process.env.DEFAULT_PROVIDER||process.env.DEFAULT_MODEL;if(m||h||p)return}let s=!t,o=t||h0.createInterface({input:process.stdin,output:process.stdout,terminal:!0}),n=g0(o),r=!e;console.log(),console.log(r?`${Po}${Li} \u2726 Welcome to nex-code! No configuration found.${oe}`:`${Nn}${Li} \u2726 nex-code \u2014 Provider & API Key Setup${oe}`),console.log(`${Qe} \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500${oe}`),r&&console.log(` Let's set you up in 60 seconds.
|
|
746
746
|
`),console.log(` ${Li}Which AI provider do you want to use?${oe}
|
|
747
|
-
`),console.log(` ${Lo}1)${oe} Ollama ${Qe}local/cloud \u2014 no API key needed${oe}`),console.log(` ${Nn}2)${oe} Anthropic ${Qe}Claude (claude-sonnet-4-6 etc.)${oe}`),console.log(` ${Nn}3)${oe} OpenAI ${Qe}GPT-4o, GPT-4.1 etc.${oe}`),console.log(` ${Nn}4)${oe} Gemini ${Qe}Google Gemini 2.x${oe}`),console.log(` ${Qe}5) Skip / Cancel${oe}`),console.log();let
|
|
747
|
+
`),console.log(` ${Lo}1)${oe} Ollama ${Qe}local/cloud \u2014 no API key needed${oe}`),console.log(` ${Nn}2)${oe} Anthropic ${Qe}Claude (claude-sonnet-4-6 etc.)${oe}`),console.log(` ${Nn}3)${oe} OpenAI ${Qe}GPT-4o, GPT-4.1 etc.${oe}`),console.log(` ${Nn}4)${oe} Gemini ${Qe}Google Gemini 2.x${oe}`),console.log(` ${Qe}5) Skip / Cancel${oe}`),console.log();let a=await n("Enter number","1"),c=[];if(a==="5"){s&&o.close(),console.log(`
|
|
748
748
|
${Qe} Cancelled \u2014 no changes made.${oe}
|
|
749
|
-
`);return}if(
|
|
749
|
+
`);return}if(a==="1"){console.log();let m=await n("Ollama host","http://localhost:11434"),h=await n("Default model","qwen3-coder");c.push("DEFAULT_PROVIDER=ollama",`DEFAULT_MODEL=${h}`,`OLLAMA_HOST=${m}`),process.env.DEFAULT_PROVIDER="ollama",process.env.DEFAULT_MODEL=h,process.env.OLLAMA_HOST=m}else if(a==="2"){console.log(),console.log(` ${Qe}Get your key: https://console.anthropic.com/settings/keys${oe}`);let m=await jo("ANTHROPIC_API_KEY",t);if(!m){s&&o.close(),console.log(`
|
|
750
750
|
${Po} No key entered \u2014 cancelled.${oe}
|
|
751
|
-
`);return}let h=await n("Default model","claude-sonnet-4-6");c.push("DEFAULT_PROVIDER=anthropic",`DEFAULT_MODEL=${h}`,`ANTHROPIC_API_KEY=${m}`),process.env.DEFAULT_PROVIDER="anthropic",process.env.DEFAULT_MODEL=h,process.env.ANTHROPIC_API_KEY=m}else if(
|
|
751
|
+
`);return}let h=await n("Default model","claude-sonnet-4-6");c.push("DEFAULT_PROVIDER=anthropic",`DEFAULT_MODEL=${h}`,`ANTHROPIC_API_KEY=${m}`),process.env.DEFAULT_PROVIDER="anthropic",process.env.DEFAULT_MODEL=h,process.env.ANTHROPIC_API_KEY=m}else if(a==="3"){console.log(),console.log(` ${Qe}Get your key: https://platform.openai.com/api-keys${oe}`);let m=await jo("OPENAI_API_KEY",t);if(!m){s&&o.close(),console.log(`
|
|
752
752
|
${Po} No key entered \u2014 cancelled.${oe}
|
|
753
|
-
`);return}let h=await n("Default model","gpt-4o");c.push("DEFAULT_PROVIDER=openai",`DEFAULT_MODEL=${h}`,`OPENAI_API_KEY=${m}`),process.env.DEFAULT_PROVIDER="openai",process.env.DEFAULT_MODEL=h,process.env.OPENAI_API_KEY=m}else if(
|
|
753
|
+
`);return}let h=await n("Default model","gpt-4o");c.push("DEFAULT_PROVIDER=openai",`DEFAULT_MODEL=${h}`,`OPENAI_API_KEY=${m}`),process.env.DEFAULT_PROVIDER="openai",process.env.DEFAULT_MODEL=h,process.env.OPENAI_API_KEY=m}else if(a==="4"){console.log(),console.log(` ${Qe}Get your key: https://aistudio.google.com/app/apikey${oe}`);let m=await jo("GEMINI_API_KEY",t);if(!m){s&&o.close(),console.log(`
|
|
754
754
|
${Po} No key entered \u2014 cancelled.${oe}
|
|
755
755
|
`);return}let h=await n("Default model","gemini-2.0-flash");c.push("DEFAULT_PROVIDER=gemini",`DEFAULT_MODEL=${h}`,`GEMINI_API_KEY=${m}`),process.env.DEFAULT_PROVIDER="gemini",process.env.DEFAULT_MODEL=h,process.env.GEMINI_API_KEY=m}if(console.log(),(await n("Add Perplexity key for grounded web search? (y/N)","n")).toLowerCase()==="y"){console.log(` ${Qe}Get your key: https://www.perplexity.ai/settings/api${oe}`);let m=await jo("PERPLEXITY_API_KEY",t);m&&(c.push(`PERPLEXITY_API_KEY=${m}`),process.env.PERPLEXITY_API_KEY=m)}console.log();let u=Io.join(process.cwd(),".env"),d=(Tt.existsSync(u),"y"),f=await n(`Save to ${u}? (Y/n)`,d);if(s&&o.close(),f.toLowerCase()!=="n"){let m=Tt.existsSync(u)?Tt.readFileSync(u,"utf-8").trimEnd()+`
|
|
756
756
|
|
|
@@ -762,18 +762,18 @@ ${Po} No key entered \u2014 cancelled.${oe}
|
|
|
762
762
|
`)),console.log(`
|
|
763
763
|
${Lo} \u2713 Saved to ${u}${oe}`),c.some(p=>p.includes("API_KEY"))&&console.log(`${Qe} (key stored locally \u2014 never committed)${oe}`)}if(process.env.DEFAULT_PROVIDER)try{let{setActiveModel:m}=be(),h=process.env.DEFAULT_MODEL?`${process.env.DEFAULT_PROVIDER}:${process.env.DEFAULT_MODEL}`:process.env.DEFAULT_PROVIDER;m(h),console.log(`${Lo} \u2713 Switched to ${h} for this session${oe}`)}catch{}console.log(`
|
|
764
764
|
${Lo} \u2713 Setup complete!${oe}
|
|
765
|
-
`)}
|
|
766
|
-
`)}function
|
|
767
|
-
`);console.log=t,console.warn=t,console.info=t;let{setConfirmHook:e}=
|
|
768
|
-
`))}function
|
|
765
|
+
`)}Rd.exports={runSetupWizard:$0}});var Ad=q((H_,Cd)=>{"use strict";var y0=require("readline");function an(t){process.stdout.write(JSON.stringify(t)+`
|
|
766
|
+
`)}function w0(){process.env.NEX_SERVER="1";let t=(...c)=>process.stderr.write(c.map(String).join(" ")+`
|
|
767
|
+
`);console.log=t,console.warn=t,console.info=t;let{setConfirmHook:e}=Ie(),s=new Map,o=0;e((c,l)=>{let u="cfm-"+ ++o,d=l?.toolName||"",f=!1;try{let{isCritical:m}=Ie();f=m(c)}catch{}return an({type:"confirm_request",id:u,question:c,tool:d,critical:f}),new Promise(m=>{s.set(u,m)})});let n=null,r={onToken(c){n&&an({type:"token",id:n,text:c})},onThinkingToken(){},onToolStart(c,l){n&&an({type:"tool_start",id:n,tool:c,args:l||{}})},onToolEnd(c,l,u){n&&an({type:"tool_end",id:n,tool:c,summary:l||"",ok:!!u})}},a=y0.createInterface({input:process.stdin,output:null,terminal:!1});an({type:"ready"}),a.on("line",async c=>{let l=c.trim();if(!l)return;let u;try{u=JSON.parse(l)}catch{return}switch(u.type){case"chat":{let d=u.id||"msg-"+Date.now();n=d;let{processInput:f}=de();try{await f(u.text,r),an({type:"done",id:d})}catch(m){an({type:"error",id:d,message:m?.message||String(m)})}finally{n=null}break}case"confirm":{let d=s.get(u.id);d&&(s.delete(u.id),d(!!u.answer));break}case"cancel":{for(let[d,f]of s)s.delete(d),f(!1);break}case"clear":{let{clearConversation:d}=de();d();for(let[f,m]of s)s.delete(f),m(!1);break}default:break}}),a.on("close",()=>{process.exit(0)})}Cd.exports={startServerMode:w0}});var Id=q((G_,Md)=>{"use strict";var Do=require("fs"),{T:cn,isDark:b0}=Ht(),Rt="\x1B[0m",_0=!b0,k0=process.env.FOOTER_DEBUG==="1"||process.env.FOOTER_DEBUG==="2",x0=process.env.FOOTER_DEBUG==="2",Mn=null;function Wt(...t){k0&&(Mn||(Mn=Do.openSync("/tmp/footer-debug.log","w")),Do.writeSync(Mn,t.join(" ")+`
|
|
768
|
+
`))}function Od(t,e){if(!x0||typeof e!="string")return;Mn||(Mn=Do.openSync("/tmp/footer-debug.log","w"));let s=e.replace(/\x1b\[([^a-zA-Z]*)([a-zA-Z])/g,(o,n,r)=>`<ESC[${n}${r}>`).replace(/\x1b([^[])/g,(o,n)=>`<ESC${n}>`).replace(/\r/g,"<CR>").replace(/\n/g,`<LF>
|
|
769
769
|
`).replace(/[\x00-\x08\x0b-\x1f\x7f]/g,o=>`<${o.charCodeAt(0).toString(16).padStart(2,"0")}>`);Do.writeSync(Mn,`${t}: ${s}
|
|
770
|
-
`)}function
|
|
770
|
+
`)}function Nd(t){return t.replace(/\x1b\[[^a-zA-Z]*[a-zA-Z]/g,"").length}var Di=class{constructor(){this._active=!1,this._rl=null,this._origWrite=null,this._origPrompt=null,this._origSetPr=null,this._origRefreshLine=null,this._origLog=null,this._origError=null,this._origStderrWrite=null,this._drawing=!1,this._offResize=null,this._cursorOnInputRow=!1,this._inRefreshLine=!1,this._lastOutputRow=1,this._prevTermRows=0,this._prevTermCols=0,this._consistencyTimer=null,this._dirty=!1,this._statusModel="",this._statusBranch="",this._statusProject=""}setStatusInfo({model:e="",branch:s="",project:o=""}={}){this._statusModel=e,this._statusBranch=s,this._statusProject=o,this._active&&this.drawFooter()}get _rows(){return process.stdout.rows||24}get _cols(){return process.stdout.columns||80}get _scrollEnd(){return this._rows-2}get _rowStatus(){return this._rows-1}get _rowInput(){return this._rows}_goto(e,s=1){return`\x1B[${e};${s}H`}_statusLine(){let e=this._cols,s=this._statusModel,o=this._statusBranch,n=this._statusProject;if(!s)return cn.footer_sep+"\u2500".repeat(e)+Rt;let r=` ${cn.footer_divider}\xB7${Rt} `,a=[];s&&a.push(`${cn.footer_model}${s}${Rt}`),o&&a.push(`${cn.footer_branch}${o}${Rt}`),n&&a.push(`${cn.footer_project}${n}${Rt}`);let c=a.join(r),l=[s,o,n].filter(Boolean).join(" \xB7 ").length,u="\u2500 ",d=Math.max(0,e-u.length-l-2),f="\u2500".repeat(d);return`${cn.footer_sep}${u}${Rt}${c}${cn.footer_sep} ${f}${Rt}`}drawFooter(e){!this._origWrite||this._drawing||(this._drawing=!0,this._origWrite("\x1B7"+this._goto(this._rowStatus)+"\x1B[2K"+this._statusLine(e)+"\x1B8"),this._drawing=!1)}_setScrollRegion(){if(_0)return;let e=Math.max(1,this._scrollEnd);this._origWrite(`\x1B[1;${e}r`)}_clearScrollRegion(){this._origWrite&&this._origWrite("\x1B[r")}_eraseStatus(){this._origWrite&&this._origWrite("\x1B7"+this._goto(this._rowStatus)+"\x1B[2K\x1B8")}rawWrite(e){return Od("RAW",e),this._origWrite?this._origWrite(e):process.stdout.write(e)}_relayout(e){if(!this._origWrite)return;let s=this._origWrite,o=this._rows,n=this._cols,r=Math.max(1,o-2);Wt("RELAYOUT:",e,"rows="+o,"cols="+n,"scrollEnd="+r,"cursorOnInput="+this._cursorOnInputRow),this._prevTermRows=o,this._prevTermCols=n;let a=Math.min(this._lastOutputRow+1,r+1),c="";for(let l=a;l<=o;l++)c+=this._goto(l)+"\x1B[2K";s(c),this._setScrollRegion(),this._lastOutputRow=Math.min(this._lastOutputRow,r),this.drawFooter(),this._cursorOnInputRow&&this._rl&&this._rl.prompt(!0),this._dirty=!1}activate(e){if(!process.stdout.isTTY)return;this._rl=e,this._origWrite=process.stdout.write.bind(process.stdout),this._active=!0,this._prevTermRows=this._rows,this._prevTermCols=this._cols,this._origWrite("\x1B[r"),this._setScrollRegion(),this._lastOutputRow=1,this.drawFooter();let s=this,o=process.stdout.write.bind(process.stdout);this._origWrite=o,process.stdout.write=function(p,...g){if(Od("PATCH",p),!s._active||typeof p!="string")return o(p,...g);if(s._inRefreshLine){let b=p.replace(/\n/g,"");return b?o(b,...g):!0}if(s._cursorOnInputRow)if(p.includes(`
|
|
771
771
|
`)&&p.length>4&&!p.includes("\r"))Wt("STDOUT: agent output, leaving input row, data="+JSON.stringify(p).slice(0,100)),s._cursorOnInputRow=!1,o(s._goto(Math.min(s._lastOutputRow+1,s._scrollEnd)));else{if(p.length<=4&&!p.includes(`
|
|
772
772
|
`)&&!p.includes("\r")&&!/[\x00-\x1f\x7f]/.test(p))return Wt("STDOUT: char intercept:",JSON.stringify(p)),s._origRefreshLine&&s._doRefreshLine(),!0;{let b=p.replace(/\n/g,"");return b?o(b,...g):!0}}let y=s._cols||80,$=0,w=p.split(`
|
|
773
|
-
`);for(let b=0;b<w.length;b++){let k=
|
|
774
|
-
`);process.stdout.write(`\x1B[${m}A`)}let $=[];$.push(` ${fe.bold}${fe.cyan}${o}${fe.reset}`),$.push(` ${fe.dim}${n}${fe.reset}`),$.push("");let{start:w,end:E}=f();w>0&&$.push(` ${fe.dim}\u2191 more${fe.reset}`);for(let k=w;k<E;k++){let v=e[k];if(v.isHeader){$.push(` ${fe.bold}${fe.dim}${v.label}${fe.reset}`);continue}let R=
|
|
773
|
+
`);for(let b=0;b<w.length;b++){let k=Nd(w[b]);k>0&&($+=Math.floor((k-1)/y))}let E=w.length-1;return E+$>0&&(s._lastOutputRow=Math.min(s._lastOutputRow+E+$,s._scrollEnd)),o(p,...g)},this._cursorOnInputRow=!1,this._origStderrWrite=process.stderr.write.bind(process.stderr),process.stderr.write=function(p,...g){if(!s._active)return s._origStderrWrite(p,...g);if(typeof p=="string"&&p.includes("\r")){let y=Math.min(s._lastOutputRow+1,s._scrollEnd);if(s._cursorOnInputRow){s._origWrite("\x1B7"),s._origWrite(s._goto(y));let $=s._origStderrWrite(p,...g);return s._origWrite("\x1B8"),$}s._origWrite(s._goto(y))}return s._origStderrWrite(p,...g)},this._origLog=console.log,this._origError=console.error;function n(...p){if(!s._active){s._origLog(...p);return}s._origWrite(s._goto(Math.min(s._lastOutputRow+1,s._scrollEnd))),s._cursorOnInputRow=!1,s._origLog(...p),s.drawFooter(),s._rl&&s._rl.prompt()}function r(...p){if(!s._active){s._origError(...p);return}s._origWrite(s._goto(Math.min(s._lastOutputRow+1,s._scrollEnd))),s._cursorOnInputRow=!1,s._origError(...p),s.drawFooter(),s._rl&&s._rl.prompt()}console.log=n,console.error=r,this._origSetPr=e.setPrompt.bind(e),e.setPrompt=function(p){s._origSetPr(p),s._active&&s.drawFooter(p)},this._origPrompt=e.prompt.bind(e),e.prompt=function(p){if(!s._active)return s._origPrompt(p);Wt("PROMPT: goto rowInput="+s._rowInput),e.prevRows=0,o(s._goto(s._rowInput)+Rt+"\x1B[2K"),s._cursorOnInputRow=!0,s._origPrompt(p)};let a=e.question.bind(e);e.question=function(p,g){if(!s._active)return a(p,g);o(s._goto(s._rowInput)+"\x1B[2K"),e.prevRows=0,s._cursorOnInputRow=!0,a(p,y=>{o(s._goto(s._rowInput)+"\x1B[2K"),s._cursorOnInputRow=!1,s.drawFooter(),g(y)})};let c=Object.getPrototypeOf(e),l=Object.getOwnPropertySymbols(c).find(p=>p.toString()==="Symbol(_refreshLine)"),u=l?c[l].bind(e):e._refreshLine?e._refreshLine.bind(e):null;if(this._origRefreshLine=u,this._doRefreshLine=function(){if(!s._active||!u)return;if(s._rows!==s._prevTermRows||s._cols!==s._prevTermCols){s._dirty=!0;return}e.prevRows=0,o(s._goto(s._rowInput)+Rt+"\x1B[2K");let p=s._cols,g=e._prompt||"",y=Nd(g),$=p-y-1;s._inRefreshLine=!0;try{if(e.line.length<=$){Wt("REFRESH: short line, len="+e.line.length),u();return}Wt("REFRESH: long line, len="+e.line.length+", max="+$);let w=e.line,E=e.cursor,b=Math.max(1,$-1),k=Math.max(0,E-b),v=(k>0?"\xAB":"")+w.slice(k,k+b+(k>0?0:1));e.line=v,e.cursor=v.length,u(),e.line=w,e.cursor=E}finally{s._inRefreshLine=!1}},u){let p=this._doRefreshLine;l&&Object.defineProperty(e,l,{value:p,writable:!0,configurable:!0}),e._refreshLine=p}e.on("line",()=>{s._active&&(Wt("LINE: leaving input row"),s._cursorOnInputRow=!1,o(s._goto(s._rowInput)+"\x1B[2K"),o(s._goto(Math.min(s._lastOutputRow+1,s._scrollEnd))),s.drawFooter())});let d=null,f=null,m=()=>{d=null,s._relayout("resize"),f&&clearTimeout(f),f=setTimeout(()=>{f=null,s._relayout("resize-cleanup")},300)},h=()=>{s._dirty=!0,d&&clearTimeout(d),d=setTimeout(m,80)};process.stdout.on("resize",h),this._offResize=()=>{process.stdout.off("resize",h),d&&(clearTimeout(d),d=null),f&&(clearTimeout(f),f=null)},this._consistencyTimer=setInterval(()=>{if(!s._active)return;let p=s._rows,g=s._cols;(s._dirty||p!==s._prevTermRows||g!==s._prevTermCols)&&(Wt("CONSISTENCY: dirty="+s._dirty+" rows="+p+"/"+s._prevTermRows+" cols="+g+"/"+s._prevTermCols),s._relayout("consistency"))},800)}deactivate(){if(this._active){if(this._active=!1,this._offResize&&(this._offResize(),this._offResize=null),this._consistencyTimer&&(clearInterval(this._consistencyTimer),this._consistencyTimer=null),this._origStderrWrite&&(process.stderr.write=this._origStderrWrite,this._origStderrWrite=null),this._origLog&&(console.log=this._origLog,this._origLog=null),this._origError&&(console.error=this._origError,this._origError=null),this._origWrite&&(process.stdout.write=this._origWrite),this._rl&&(this._origPrompt&&(this._rl.prompt=this._origPrompt,this._origPrompt=null),this._origSetPr&&(this._rl.setPrompt=this._origSetPr,this._origSetPr=null),this._origRefreshLine)){let e=Object.getOwnPropertySymbols(Object.getPrototypeOf(this._rl)).find(s=>s.toString()==="Symbol(_refreshLine)");e&&delete this._rl[e],delete this._rl._refreshLine,this._origRefreshLine=null}this._eraseStatus(),this._clearScrollRegion(),this._origWrite=null}}};Md.exports={StickyFooter:Di}});var jd=q((K_,Ld)=>{var{C:fe}=we(),{listProviders:v0,getActiveProviderName:S0,getActiveModelId:E0,setActiveModel:T0}=be();function Pd(t,e,s={}){let{title:o="Select",hint:n="\u2191\u2193 navigate \xB7 Enter select \xB7 Esc cancel"}=s;return new Promise(r=>{let a=e.map(($,w)=>$.isHeader?-1:w).filter($=>$>=0);if(a.length===0){r(null);return}let c=e.findIndex($=>$.isCurrent),l=c>=0?a.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 $=a[l];return $<d?d=$:$>=d+u&&(d=$-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 k=0;k<m;k++)process.stdout.write(`\x1B[2K
|
|
774
|
+
`);process.stdout.write(`\x1B[${m}A`)}let $=[];$.push(` ${fe.bold}${fe.cyan}${o}${fe.reset}`),$.push(` ${fe.dim}${n}${fe.reset}`),$.push("");let{start:w,end:E}=f();w>0&&$.push(` ${fe.dim}\u2191 more${fe.reset}`);for(let k=w;k<E;k++){let v=e[k];if(v.isHeader){$.push(` ${fe.bold}${fe.dim}${v.label}${fe.reset}`);continue}let R=a[l]===k,C=R?`${fe.cyan}> `:" ",A=v.isCurrent?` ${fe.yellow}<current>${fe.reset}`:"";R?$.push(`${C}${fe.bold}${v.label}${fe.reset}${A}`):$.push(`${C}${fe.dim}${v.label}${fe.reset}${A}`)}E<e.length&&$.push(` ${fe.dim}\u2193 more${fe.reset}`);let b=$.join(`
|
|
775
775
|
`);process.stdout.write(b+`
|
|
776
|
-
`),m=$.length}t.pause();let p=process.stdin.isRaw;process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume();function g(){process.stdin.removeListener("keypress",y),process.stdin.isTTY&&p!==void 0&&process.stdin.setRawMode(p),t.resume()}function y($,w){if(w){if(w.name==="up"||w.ctrl&&w.name==="p"){l>0&&(l--,h());return}if(w.name==="down"||w.ctrl&&w.name==="n"){l<
|
|
776
|
+
`),m=$.length}t.pause();let p=process.stdin.isRaw;process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume();function g(){process.stdin.removeListener("keypress",y),process.stdin.isTTY&&p!==void 0&&process.stdin.setRawMode(p),t.resume()}function y($,w){if(w){if(w.name==="up"||w.ctrl&&w.name==="p"){l>0&&(l--,h());return}if(w.name==="down"||w.ctrl&&w.name==="n"){l<a.length-1&&(l++,h());return}if(w.name==="return"){let E=e[a[l]];g(),r(E?E.value:null);return}if(w.name==="escape"||w.ctrl&&w.name==="c"){g(),r(null);return}}}process.stdin.on("keypress",y),h()})}async function R0(t){let e=v0(),s=S0(),o=E0(),n=[];for(let a of e)if(a.models.length!==0){n.push({label:a.provider,value:null,isHeader:!0});for(let c of a.models){let l=a.provider===s&&c.id===o;n.push({label:` ${c.name} (${a.provider}:${c.id})`,value:`${a.provider}:${c.id}`,isCurrent:l})}}let r=await Pd(t,n,{title:"Select Model"});return r?(T0(r),console.log(`${fe.green}Switched to ${r}${fe.reset}`),!0):(console.log(`${fe.dim}Cancelled${fe.reset}`),!1)}Ld.exports={pickFromList:Pd,showModelPicker:R0}});var Fi=q((Y_,Gd)=>{var Dd=require("fs"),C0=require("path"),{atomicWrite:A0,withFileLockSync:O0}=It(),{callChat:qd}=be(),{remember:N0,listMemories:z_,recall:M0}=Ft(),qi=4,I0=`You are a memory optimization agent for an AI coding assistant called nex-code.
|
|
777
777
|
Analyze this conversation history and extract actionable learnings the assistant should remember.
|
|
778
778
|
|
|
779
779
|
Return ONLY valid JSON in this exact format:
|
|
@@ -799,15 +799,15 @@ Rules:
|
|
|
799
799
|
- value: concise actionable instruction, max 120 chars
|
|
800
800
|
- nex_additions: project-level instructions/conventions only (not personal preferences)
|
|
801
801
|
- If nothing significant to learn, return {"memories": [], "nex_additions": [], "summary": "..."}
|
|
802
|
-
- Return ONLY the JSON, no markdown, no explanation`;function
|
|
802
|
+
- Return ONLY the JSON, no markdown, no explanation`;function Fd(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(`
|
|
803
803
|
|
|
804
|
-
`)}async function
|
|
804
|
+
`)}async function Ud(t){if(t.filter(n=>n.role==="user").length<qi)return{memories:[],nex_additions:[],summary:null,skipped:!0};let s=Fd(t);if(!s.trim())return{memories:[],nex_additions:[],summary:null,skipped:!0};let o=[{role:"system",content:I0},{role:"user",content:`Conversation to analyze:
|
|
805
805
|
|
|
806
|
-
${s}`}];try{let
|
|
807
|
-
`)?n+
|
|
808
|
-
`+
|
|
806
|
+
${s}`}];try{let a=((await qd(o,[],{temperature:0,maxTokens:800})).content||"").trim().match(/\{[\s\S]*\}/);if(!a)return{memories:[],nex_additions:[],summary:null,error:"No JSON in response"};let c=JSON.parse(a[0]);return{memories:Array.isArray(c.memories)?c.memories:[],nex_additions:Array.isArray(c.nex_additions)?c.nex_additions:[],summary:typeof c.summary=="string"?c.summary:null}}catch(n){return{memories:[],nex_additions:[],summary:null,error:n.message}}}function Wd(t){let e=[];for(let{key:s,value:o}of t||[]){if(!s||!o||typeof s!="string"||typeof o!="string")continue;let n=s.trim().replace(/\s+/g,"-").substring(0,60),r=o.trim().substring(0,200);if(!n||!r)continue;let a=M0(n);a!==r&&(N0(n,r),e.push({key:n,value:r,action:a?"updated":"added"}))}return e}function Bd(t){if(!t||t.length===0)return[];let e=C0.join(process.cwd(),"NEX.md");return O0(e,()=>{let s="";try{Dd.existsSync(e)&&(s=Dd.readFileSync(e,"utf-8"))}catch{}let o=[],n=s;for(let r of t){if(!r||typeof r!="string")continue;let a=r.trim();if(!a)continue;let c=a.substring(0,35).toLowerCase();s.toLowerCase().includes(c)||(o.push(a),n=n?n.endsWith(`
|
|
807
|
+
`)?n+a:n+`
|
|
808
|
+
`+a:a)}return o.length>0&&(n.endsWith(`
|
|
809
809
|
`)||(n+=`
|
|
810
|
-
`),
|
|
810
|
+
`),A0(e,n)),o})}async function P0(t){let e=await Ud(t);if(e.skipped)return{applied:[],nexAdded:[],summary:null,skipped:!0};if(e.error)return{applied:[],nexAdded:[],summary:null,error:e.error};let s=Wd(e.memories),o=Bd(e.nex_additions);return{applied:s,nexAdded:o,summary:e.summary}}var L0=`You are a knowledge base agent for an AI coding assistant called nex-code.
|
|
811
811
|
Analyze this conversation and extract knowledge worth persisting in the project knowledge base (.nex/brain/).
|
|
812
812
|
|
|
813
813
|
Return ONLY valid JSON in this exact format:
|
|
@@ -841,35 +841,35 @@ Rules:
|
|
|
841
841
|
---
|
|
842
842
|
- Maximum 3 documents per session. Quality over quantity.
|
|
843
843
|
- If nothing worth persisting: return {"documents": [], "skip_reason": "..."}
|
|
844
|
-
- Return ONLY the JSON, no markdown fences, no explanation`;async function
|
|
844
|
+
- Return ONLY the JSON, no markdown fences, no explanation`;async function Hd(t){if(t.filter(n=>n.role==="user").length<qi)return{documents:[],skip_reason:"Session too short"};let s=Fd(t);if(!s.trim())return{documents:[],skip_reason:"No usable content"};let o=[{role:"system",content:L0},{role:"user",content:`Conversation to analyze:
|
|
845
845
|
|
|
846
|
-
${s}`}];try{let
|
|
846
|
+
${s}`}];try{let a=((await qd(o,[],{temperature:0,maxTokens:2e3})).content||"").trim().match(/\{[\s\S]*\}/);if(!a)return{documents:[],error:"No JSON in response"};let c=JSON.parse(a[0]);return{documents:Array.isArray(c.documents)?c.documents:[],skip_reason:c.skip_reason}}catch(n){return{documents:[],error:n.message}}}async function j0(t){let e=await Hd(t);if(e.error)return{written:[],skipped:[],error:e.error};if(!e.documents||e.documents.length===0)return{written:[],skipped:[],skip_reason:e.skip_reason};let{writeDocument:s,readDocument:o}=ss(),n=[],r=[];for(let a of e.documents){if(!a.name||!a.content)continue;let c=a.name.trim().replace(/\.md$/,"").replace(/[^a-z0-9-]/g,"-").substring(0,60);if(!c)continue;let l=o(c);if(l.content){let d=`
|
|
847
847
|
|
|
848
848
|
## Update ${new Date().toISOString().split("T")[0]}
|
|
849
849
|
|
|
850
|
-
${
|
|
850
|
+
${a.content}`;s(c,l.content+d),n.push({name:c,reason:a.reason||"",action:"updated"})}else s(c,a.content),n.push({name:c,reason:a.reason||"",action:"created"})}return{written:n,skipped:r}}Gd.exports={learnFromSession:P0,learnBrainFromSession:j0,reflectOnSession:Ud,reflectBrain:Hd,applyMemories:Wd,applyNexAdditions:Bd,LEARN_MIN_MESSAGES:qi}});var Xd=q((J_,Yd)=>{var je=require("fs"),Pn=require("path"),X_=require("os"),D0=require("readline"),{C:L}=we(),Kd=".nex",Ui=null;function q0(t){Ui=t}function De(t,e=""){let s=e?` ${L.dim}[${e}]${L.reset}`:"",o=` ${L.cyan}${t}${s}${L.reset}: `;return new Promise(n=>{let r=a=>{let c=a.trim()||e;n(c)};if(Ui)Ui.question(o,r);else{let a=D0.createInterface({input:process.stdin,output:process.stdout});a.question(o,c=>{a.close(),r(c)})}})}function In(t,e=!0){return De(`${t} (${e?"Y/n":"y/N"})`,e?"y":"n").then(o=>o.toLowerCase()!=="n"&&o.toLowerCase()!=="no")}async function Wi(t,e,s){let o=e.map((c,l)=>`${L.dim}${l+1})${L.reset} ${c}`).join(" ");console.log(` ${L.cyan}${t}${L.reset}`),console.log(` ${o}`);let n=s?e.indexOf(s)+1:1,r=await De("Enter number",String(n)),a=parseInt(r,10)-1;return e[Math.max(0,Math.min(a,e.length-1))]}async function F0(){let t=Pn.join(process.cwd(),Kd),e=Pn.join(t,"servers.json"),s={};if(je.existsSync(e))try{s=JSON.parse(je.readFileSync(e,"utf-8"))}catch{}console.log(`
|
|
851
851
|
${L.bold}${L.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${L.reset}`),console.log(`${L.bold}${L.cyan}\u2551 nex-code Server Setup Wizard \u2551${L.reset}`),console.log(`${L.bold}${L.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${L.reset}
|
|
852
852
|
`);let o=Object.keys(s);if(o.length>0&&(console.log(`${L.dim}Existing profiles: ${o.join(", ")}${L.reset}`),!await In("Add or update a server profile?",!0))){console.log(`${L.dim}No changes made.${L.reset}
|
|
853
853
|
`);return}let n={...s},r=!0;for(;r;){console.log(`
|
|
854
|
-
${L.bold}\u2500\u2500\u2500 New Server Profile \u2500\u2500\u2500${L.reset}`);let l=await
|
|
854
|
+
${L.bold}\u2500\u2500\u2500 New Server Profile \u2500\u2500\u2500${L.reset}`);let l=await De("Profile name (e.g. prod, staging, macbook)");if(!l){console.log(`${L.red} Name is required.${L.reset}`);continue}let u=await De("Host / IP address");if(!u){console.log(`${L.red} Host is required.${L.reset}`);continue}let d=await De("SSH user","root"),f=await De("SSH port","22"),m=parseInt(f,10)||22,h=await De("SSH key path (leave empty for SSH agent)",""),p=await Wi("Operating system",["almalinux9","macos","ubuntu","debian","other"],"almalinux9"),g=await In("Allow sudo commands?",!0),y={host:u,user:d};m!==22&&(y.port=m),h&&(y.key=h),p!=="other"&&(y.os=p),g&&(y.sudo=!0),n[l]=y,console.log(`
|
|
855
855
|
${L.green}\u2713${L.reset} Profile "${l}" added: ${d}@${u}${m!==22?`:${m}`:""}${p!=="other"?` [${p}]`:""}`),r=await In(`
|
|
856
|
-
Add another server?`,!1)}
|
|
856
|
+
Add another server?`,!1)}je.existsSync(t)||je.mkdirSync(t,{recursive:!0}),je.writeFileSync(e,JSON.stringify(n,null,2)+`
|
|
857
857
|
`,"utf-8"),console.log(`
|
|
858
|
-
${L.green}\u2713 Saved .nex/servers.json (${Object.keys(n).length} profile${Object.keys(n).length!==1?"s":""})${L.reset}`);let
|
|
858
|
+
${L.green}\u2713 Saved .nex/servers.json (${Object.keys(n).length} profile${Object.keys(n).length!==1?"s":""})${L.reset}`);let a=Pn.join(process.cwd(),".gitignore");je.existsSync(a)&&(je.readFileSync(a,"utf-8").includes(".nex/")||await In("Add .nex/ to .gitignore?",!0)&&(je.appendFileSync(a,`
|
|
859
859
|
# nex-code server profiles
|
|
860
860
|
.nex/
|
|
861
861
|
`),console.log(`${L.green}\u2713 Added .nex/ to .gitignore${L.reset}`))),await In(`
|
|
862
|
-
Set up deploy configs (.nex/deploy.json)?`,!1)&&await
|
|
862
|
+
Set up deploy configs (.nex/deploy.json)?`,!1)&&await zd(n,t),console.log(`
|
|
863
863
|
${L.dim}Use /servers to list profiles, /servers ping to check connectivity.${L.reset}
|
|
864
|
-
`)}async function
|
|
864
|
+
`)}async function zd(t,e){let s=e||Pn.join(process.cwd(),Kd),o=Pn.join(s,"deploy.json"),n={};if(je.existsSync(o))try{n=JSON.parse(je.readFileSync(o,"utf-8"))}catch{}if(!t){let u=Pn.join(s,"servers.json");if(je.existsSync(u))try{t=JSON.parse(je.readFileSync(u,"utf-8"))}catch{t={}}else t={}}let r=Object.keys(t);console.log(`
|
|
865
865
|
${L.bold}${L.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${L.reset}`),console.log(`${L.bold}${L.cyan}\u2551 Deploy Config Wizard \u2551${L.reset}`),console.log(`${L.bold}${L.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${L.reset}
|
|
866
|
-
`);let
|
|
867
|
-
${L.bold}\u2500\u2500\u2500 New Deploy Config \u2500\u2500\u2500${L.reset}`);let u=await
|
|
866
|
+
`);let a=Object.keys(n);a.length>0&&console.log(`${L.dim}Existing deploy configs: ${a.join(", ")}${L.reset}`);let c={...n},l=!0;for(;l;){console.log(`
|
|
867
|
+
${L.bold}\u2500\u2500\u2500 New Deploy Config \u2500\u2500\u2500${L.reset}`);let u=await De("Config name (e.g. prod, staging)");if(!u){console.log(`${L.red} Name is required.${L.reset}`);continue}let d;r.length>0?d=await Wi("Target server",r,r[0]):d=await De("Target server (profile name or user@host)");let f=await Wi("Deploy method",["rsync","git"],"rsync"),m="",h=[],p="";if(f==="rsync"){m=await De("Local path to sync (e.g. dist/ or ./build)","dist/");let b=await De("Exclude paths (comma-separated, e.g. node_modules,.env)","node_modules,.env");h=b?b.split(",").map(k=>k.trim()).filter(Boolean):[]}else p=await De("Branch to pull (leave empty for current remote branch)","main");let g=await De(f==="git"?"Remote repo path (e.g. /home/jarvis/my-app)":"Remote destination path (e.g. /var/www/app)");if(!g){console.log(`${L.red} Remote path is required.${L.reset}`);continue}let y=await De("Command to run on remote after deploy (leave empty to skip)",""),$=await De("Health check URL or remote command (leave empty to skip)",""),w={server:d,method:f,remote_path:g};f==="rsync"?(w.local_path=m,h.length>0&&(w.exclude=h)):p&&(w.branch=p),y&&(w.deploy_script=y),$&&(w.health_check=$),c[u]=w;let E=f==="git"?`${d}:${g}${p?` (${p})`:""}`:`${m.endsWith("/")?m:m+"/"} \u2192 ${d}:${g}`;console.log(`
|
|
868
868
|
${L.green}\u2713${L.reset} Deploy config "${u}": [${f}] ${E}`),y&&console.log(` ${L.dim} Then: ${y}${L.reset}`),$&&console.log(` ${L.dim} Health: ${$}${L.reset}`),l=await In(`
|
|
869
|
-
Add another deploy config?`,!1)}
|
|
869
|
+
Add another deploy config?`,!1)}je.existsSync(s)||je.mkdirSync(s,{recursive:!0}),je.writeFileSync(o,JSON.stringify(c,null,2)+`
|
|
870
870
|
`,"utf-8"),console.log(`
|
|
871
871
|
${L.green}\u2713 Saved .nex/deploy.json (${Object.keys(c).length} config${Object.keys(c).length!==1?"s":""})${L.reset}`),console.log(`${L.dim}Use: deploy prod (or with explicit params)${L.reset}
|
|
872
|
-
`)}
|
|
872
|
+
`)}Yd.exports={runServerWizard:F0,runDeployWizard:zd,setWizardRL:q0}});var Bi=q((V_,Zd)=>{"use strict";var U0=require("os"),Jd=require("path"),$s=require("fs"),ys=Jd.join(U0.homedir(),".nex-code","model-routing.json"),qo={frontend:{id:"frontend",label:"Frontend",icon:"\u2B21",envVar:"NEX_ROUTE_FRONTEND",pattern:/\b(react|vue|angular|svelte|jsx|tsx|html|css|scss|sass|tailwind|bootstrap|component|dom\b|ui\s|button|modal|navbar|sidebar|stylesheet|responsive|flexbox|grid|animation|frontend|front.end|onclick|hover|transition|web\s+design|landing\s+page|browser\s+event)\b/i},sysadmin:{id:"sysadmin",label:"Sysadmin",icon:"\u2699",envVar:"NEX_ROUTE_SYSADMIN",pattern:/\b(nginx|apache|docker|kubernetes|k8s|systemd|systemctl|deploy(ment)?|server\s+config|firewall|iptables\b|ssh\s+key|cron(job)?|ansible|terraform|ci\/cd|pipeline|container\b|pod\b|apt\s+install|yum\s+install|daemon|pm2|supervisor|logrotate|ssl\s+cert|lets.encrypt|reverse\s+proxy|load\s+balanc|haproxy|vhost|virtual\s+host)\b/i},data:{id:"data",label:"Data",icon:"\u2B21",envVar:"NEX_ROUTE_DATA",pattern:/\b(sql\b|mysql|postgres(ql)?|sqlite|mongodb|redis\b|query\b|database|db\s+migration|schema\s+change|table\s+join|aggregate\b|pandas\b|dataframe|\.csv\b|etl\b|data\s+transform|data\s+pipeline|analytics|data\s+warehouse|dbt\b|orm\b|knex|sequelize|prisma\s+schema)\b/i},agentic:{id:"agentic",label:"Agentic",icon:"\u2B21",envVar:"NEX_ROUTE_AGENTIC",pattern:/\b(spawn\s+agent|agent\s+swarm|multi.?agent|parallel\s+agent|orchestrat|coordinate\s+multiple\s+agent|delegate.+agent|sub.?agent|architect.*coder)\b/i},coding:{id:"coding",label:"Coding",icon:"\u2B21",envVar:"NEX_ROUTE_CODING",pattern:null}},Vd=["agentic","frontend","sysadmin","data","coding"];function W0(t){if(!t||t.length<8)return null;for(let e of Vd){let s=qo[e];if(!s.pattern||s.pattern.test(t))return s}return qo.coding}function Qd(){try{if($s.existsSync(ys))return JSON.parse($s.readFileSync(ys,"utf-8"))}catch{}return{}}function B0(t){let e=qo[t];return e?.envVar&&process.env[e.envVar]?process.env[e.envVar]:Qd()[t]||null}function H0(t){let e=Jd.dirname(ys);$s.existsSync(e)||$s.mkdirSync(e,{recursive:!0}),$s.writeFileSync(ys,JSON.stringify(t,null,2))}Zd.exports={CATEGORIES:qo,DETECTION_ORDER:Vd,detectCategory:W0,getModelForCategory:B0,saveRoutingConfig:H0,loadRoutingConfig:Qd,ROUTING_CONFIG_PATH:ys}});var Bo=q((Q_,nf)=>{"use strict";var Hi=require("os"),Wo=require("path"),Ke=require("fs"),G0=require("axios"),K0=require("https"),Fo=Wo.join(Hi.homedir(),".nex-code","known-models.json"),z0="https://ollama.com/api/tags",Y0=60,X0={"qwen3-coder:480b":131072,"devstral-2:123b":131072,"devstral-small-2:24b":131072,"kimi-k2:1t":262144,"kimi-k2.5":262144,"kimi-k2-thinking":262144,"minimax-m2.7:cloud":2e5,"minimax-m2.5":131072,"qwen3.5:397b":262144,"qwen3.5:35b-a3b":262144,"deepseek-v3.2":131072,"cogito-2.1:671b":131072,"glm-5":128e3,"glm-4.7":128e3};function Gi(){try{if(Ke.existsSync(Fo))return JSON.parse(Ke.readFileSync(Fo,"utf-8"))}catch{}return{benchmarked:[],lastChecked:null}}function J0(t){let e=Wo.dirname(Fo);Ke.existsSync(e)||Ke.mkdirSync(e,{recursive:!0}),Ke.writeFileSync(Fo,JSON.stringify(t,null,2))}function V0(t){let e=Gi(),s=new Set(e.benchmarked);for(let o of t)s.add(o);e.benchmarked=[...s],e.lastChecked=new Date().toISOString(),J0(e)}async function ef(){let t=process.env.OLLAMA_API_KEY;if(!t)throw new Error("OLLAMA_API_KEY not set");let e=new K0.Agent({keepAlive:!0});return((await G0.get(z0,{headers:{Authorization:`Bearer ${t}`},timeout:15e3,httpsAgent:e})).data?.models||[]).map(o=>(o.name||o.model||"").replace(/:latest$/,"")).filter(Boolean)}async function Q0(){let t=await ef(),e=Gi(),s=new Set(e.benchmarked),o=t.filter(n=>!s.has(n));return{allCloud:t,newModels:o,store:e}}var Ki="<!-- nex-benchmark-start -->",Uo="<!-- nex-benchmark-end -->",Z0={"devstral-2:123b":"Default \u2014 fastest + most reliable tool selection","devstral-small-2:24b":"Fast sub-agents, simple lookups","qwen3-coder:480b":"Coding-heavy sessions, heavy sub-agents","kimi-k2:1t":"Large repos (>100K tokens)","kimi-k2.5":"Large repos \u2014 faster than k2:1t","minimax-m2.7:cloud":"Complex swarm / multi-agent sessions (Toolathon SOTA)","minimax-m2.5":"Multi-agent, large context","qwen3.5:35b-a3b":"Fast MoE with 256K context"};function eb(t){return t?t>=25e4?"256K":t>=19e4?"200K":t>=128e3?"131K":t>=64e3?"64K":`${Math.round(t/1024)}K`:"?"}function tf(t,e){let s=["\u{1F947}","\u{1F948}","\u{1F949}"],o=(e||new Date().toISOString()).split("T")[0],n=t.filter(r=>r.score>=Y0).map((r,a)=>{let c=s[a]||"\u2014",l=eb(X0[r.model]),u=Z0[r.model]||"\u2014",d=`${(r.avgLatency/1e3).toFixed(1)}s`,f=a===0?`**${r.score}**`:String(r.score);return`| ${c} | \`${r.model}\` | ${f} | ${d} | ${l} | ${u} |`}).join(`
|
|
873
873
|
`);return`${Ki}
|
|
874
874
|
<!-- Updated: ${o} \u2014 run \`/benchmark --discover\` after new Ollama Cloud releases -->
|
|
875
875
|
|
|
@@ -879,131 +879,131 @@ ${n}
|
|
|
879
879
|
|
|
880
880
|
> Rankings are nex-code-specific: tool name accuracy, argument validity, schema compliance.
|
|
881
881
|
> Toolathon (Minimax SOTA) measures different task types \u2014 run \`/benchmark --discover\` after model releases.
|
|
882
|
-
${Uo}`}function
|
|
882
|
+
${Uo}`}function tb(t,e){if(!Ke.existsSync(e))return!1;let s=Ke.readFileSync(e,"utf-8"),o=s.indexOf(Ki),n=s.indexOf(Uo);if(o===-1||n===-1)return!1;let r=s.slice(0,o),a=s.slice(n+Uo.length),c=tf(t);return Ke.writeFileSync(e,r+c+a),!0}function nb(t){let e=Wo.join(Hi.homedir(),".nex-code","models.env");if(!Ke.existsSync(e)||t.length===0)return{updated:!1,reason:"models.env not found or empty summary"};let s=t[0],o=Ke.readFileSync(e,"utf-8"),r=o.match(/^DEFAULT_MODEL=(\S+)/m)?.[1];if(r===s.model)return{updated:!1,reason:"winner unchanged"};let a=t.find(l=>l.model===r);if(a&&s.score-a.score<5)return{updated:!1,reason:`margin ${(s.score-a.score).toFixed(1)}pts < 5pts threshold`};let c=new Date().toISOString().split("T")[0];return o=o.replace(/^DEFAULT_MODEL=\S+/m,`DEFAULT_MODEL=${s.model}`).replace(/^# Last reviewed:.*$/m,`# Last reviewed: ${c} (after /benchmark, ${s.model} wins nex-code tasks)`),Ke.writeFileSync(e,o),{updated:!0,previousModel:r,newModel:s.model}}function sb(t){let{saveRoutingConfig:e}=Bi(),s=Wo.join(Hi.homedir(),".nex-code","models.env"),o=[],n=Object.entries(t).filter(([,c])=>c.score>0);if(n.length===0)return{saved:!1,envUpdated:!1,changes:[]};let r={};for(let[c,l]of n)r[c]=l.model,o.push(`${c}: ${l.model} (${l.score}/100)`);e(r);let a=!1;if(Ke.existsSync(s)){let c=Ke.readFileSync(s,"utf-8"),u=Object.entries({coding:"NEX_ROUTE_CODING",frontend:"NEX_ROUTE_FRONTEND",sysadmin:"NEX_ROUTE_SYSADMIN",data:"NEX_ROUTE_DATA",agentic:"NEX_ROUTE_AGENTIC"}).filter(([m])=>t[m]&&t[m].score>0).map(([m,h])=>`${h}=${t[m].model} # ${m} score: ${t[m].score}/100`).join(`
|
|
883
883
|
`),d="# \u2500\u2500 Task-type routing (auto-updated by /benchmark) \u2500\u2500",f="# \u2500\u2500 end routing \u2500\u2500";if(c.includes(d)){let m=c.indexOf(d),h=c.indexOf(f);h!==-1&&(c=c.slice(0,m)+`${d}
|
|
884
884
|
${u}
|
|
885
885
|
${f}`+c.slice(h+f.length))}else c+=`
|
|
886
886
|
${d}
|
|
887
887
|
${u}
|
|
888
888
|
${f}
|
|
889
|
-
`;Ke.writeFileSync(s,c),i=!0}return{saved:!0,envUpdated:i,changes:o}}ef.exports={findNewModels:z0,fetchCloudModels:Qd,loadKnownModels:Gi,markBenchmarked:K0,updateReadme:J0,updateModelsEnv:V0,updateRoutingConfig:Q0,generateBenchmarkBlock:Zd,SENTINEL_START:Ki,SENTINEL_END:Uo}});var _s=q((X_,af)=>{"use strict";var{C:J}=we(),Z0=be(),{TOOL_DEFINITIONS:tf}=ut(),ws=[{id:"read-package",category:"file-ops",prompt:"Read the file package.json and show me its contents.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("package.json")},{id:"write-file",category:"file-ops",prompt:'Create a file at /tmp/nex-bench-test.txt with the content "benchmark run".',expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&typeof t.content=="string"},{id:"edit-file",category:"file-ops",prompt:'In the file src/config.js, replace the string "debug: false" with "debug: true".',expectedTool:["edit_file","patch_file"],validateArgs:t=>!!(t.path&&t.old_string!==void 0&&t.new_string!==void 0||t.path&&Array.isArray(t.patches)&&t.patches.length>0)},{id:"list-directory",category:"file-ops",prompt:"Show me all files and folders in the cli/ directory.",expectedTool:["list_directory","glob"],validateArgs:t=>!!(typeof t.path=="string"&&t.path.includes("cli")||typeof t.pattern=="string"&&t.pattern.includes("cli"))},{id:"glob-js-files",category:"file-ops",prompt:"Find all JavaScript files (*.js) recursively in the cli/ directory.",expectedTool:"glob",validateArgs:t=>typeof t.pattern=="string"&&t.pattern.includes(".js")},{id:"search-constant",category:"search",prompt:'Search for the string "DEFAULT_MODEL" across all files in the project.',expectedTool:["search_files","grep"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("DEFAULT_MODEL")},{id:"grep-function-def",category:"search",prompt:'Find where the function "callStream" is defined in the codebase.',expectedTool:["grep","search_files"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("callStream")},{id:"search-todos",category:"search",prompt:"Find all TODO comments in the source code.",expectedTool:["grep","search_files","bash"],validateArgs:t=>JSON.stringify(t).toUpperCase().includes("TODO")},{id:"git-branch",category:"shell",prompt:"What git branch am I currently on?",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("git")},{id:"git-status",category:"shell",prompt:"Show me the current git status of the repository.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("git status")},{id:"npm-install",category:"shell",prompt:"Run npm install to install project dependencies.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("npm")},{id:"schema-strict",category:"schema",prompt:"Read the file README.md",expectedTool:"read_file",validateArgs:(t,e)=>{let s=e?.function?.parameters||{},o=s.required||[],n=Object.keys(s.properties||{});return o.every(r=>t[r]!==void 0)&&Object.keys(t).every(r=>n.includes(r))}},{id:"multi-step-version",category:"multi-step",prompt:"What is the current version of this project? Check the source files.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("package.json")},{id:"multi-step-count",category:"multi-step",prompt:"How many JavaScript files are in the cli/ directory? Count them.",expectedTool:["bash","glob","list_directory"],validateArgs:t=>!!(typeof t.command=="string"&&t.command.includes("cli")||typeof t.pattern=="string"&&t.pattern.includes("cli")||typeof t.path=="string"&&t.path.includes("cli"))},{id:"no-tool-reasoning",category:"reasoning",prompt:'What does the acronym "API" stand for?',expectedTool:null,validateArgs:()=>!0},{id:"frontend-find-hook",category:"frontend",prompt:"Find all files that import useState from React.",expectedTool:["grep","search_files"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("useState")},{id:"frontend-create-component",category:"frontend",prompt:"Create a React functional component called Button that accepts a label prop and renders a styled button element. Save it to src/components/Button.jsx.",expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&(t.path.includes(".jsx")||t.path.includes(".tsx")||t.path.includes(".js"))&&typeof t.content=="string"},{id:"frontend-edit-css",category:"frontend",prompt:'In the file src/styles.css, change the background-color value from "blue" to "red".',expectedTool:["edit_file","patch_file"],validateArgs:t=>t.path&&t.old_string!==void 0?t.path.includes(".css")||t.old_string.includes("blue")||t.old_string.includes("background"):!!(t.path&&Array.isArray(t.patches))},{id:"frontend-glob-components",category:"frontend",prompt:"Find all JSX and TSX component files in the components/ directory.",expectedTool:"glob",validateArgs:t=>typeof t.pattern=="string"&&(t.pattern.includes(".jsx")||t.pattern.includes(".tsx")||t.pattern.includes("{jsx,tsx}"))},{id:"frontend-list-assets",category:"frontend",prompt:"List all files in the src/assets/ directory.",expectedTool:["list_directory","glob"],validateArgs:t=>!!(typeof t.path=="string"&&t.path.includes("assets")||typeof t.pattern=="string"&&t.pattern.includes("assets"))},{id:"sysadmin-port-check",category:"sysadmin",prompt:"Which process is currently listening on port 3000?",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("lsof")||t.command.includes("ss")||t.command.includes("netstat")||t.command.includes("3000"))},{id:"sysadmin-nginx-config",category:"sysadmin",prompt:"Create an nginx server block that proxies requests to localhost:3000. Save it to /etc/nginx/sites-available/myapp.",expectedTool:["write_file","bash"],validateArgs:t=>!!(t.path&&(t.path.includes("nginx")||t.path.includes("sites-available"))||t.command&&t.command.includes("nginx"))},{id:"sysadmin-service-status",category:"sysadmin",prompt:"Check the status of the nginx service and show if it is running.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("systemctl")||t.command.includes("service")||t.command.includes("nginx"))},{id:"sysadmin-error-log",category:"sysadmin",prompt:"Show the last 100 lines of the nginx error log.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("tail")||t.command.includes("journalctl")||t.command.includes("nginx"))},{id:"sysadmin-docker-compose",category:"sysadmin",prompt:"Create a docker-compose.yml file for a Node.js application with a PostgreSQL database.",expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("docker-compose")&&typeof t.content=="string"},{id:"data-sql-query",category:"data",prompt:"Write a SQL query to find all users who have not logged in for more than 30 days. Save it to queries/inactive-users.sql.",expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&(t.path.includes(".sql")||t.path.includes("quer"))&&typeof t.content=="string"},{id:"data-find-json-key",category:"data",prompt:'Find all JSON files in the project that contain the key "userId".',expectedTool:["grep","search_files"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("userId")},{id:"data-python-csv",category:"data",prompt:'Write a Python script that reads data.csv and calculates the average of the "price" column. Save it to scripts/average_price.py.',expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes(".py")&&typeof t.content=="string"},{id:"data-find-migrations",category:"data",prompt:"Find all database migration files in this project.",expectedTool:["glob","search_files","grep"],validateArgs:t=>JSON.stringify(t).toLowerCase().includes("migrat")},{id:"agentic-test-first",category:"agentic",prompt:"Run the full test suite. If any tests fail, identify the failing test file and read it to understand the issue.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("test")||t.command.includes("jest")||t.command.includes("npm"))},{id:"agentic-read-then-act",category:"agentic",prompt:"Read the project README.md, find the TODO section, and list which items are completed.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("README")},{id:"agentic-build-deploy",category:"agentic",prompt:"Build the project with npm run build, then verify the output exists in the dist/ directory.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("build")||t.command.includes("npm"))}],nf=["minimax-m2.7:cloud","qwen3-coder:480b","kimi-k2:1t","devstral-2:123b","devstral-small-2:24b"],sf=["minimax-m2.7:cloud","qwen3-coder:480b","devstral-2:123b"],eb=7,Ho={producedToolCall:.2,correctTool:.35,validArgs:.3,schemaCompliant:.15},tb="You are a coding assistant. Use the provided tools to help with file operations, search, and development tasks. Only call a tool when one is clearly needed to answer the request. Do not call a tool for questions you can answer from general knowledge.";async function of(t,e){let s={taskId:t.id,category:t.category,model:e,producedToolCall:!1,correctTool:!1,validArgs:!1,schemaCompliant:!1,toolCalled:null,error:null,latencyMs:0},o=[{role:"system",content:tb},{role:"user",content:t.prompt}],n=Date.now();try{let r=await Z0.callChat(o,tf,{provider:"ollama",model:e,temperature:0,timeout:9e4});s.latencyMs=Date.now()-n;let i=r.tool_calls||[];if(t.expectedTool===null){let c=i.length===0;s.producedToolCall=c,s.correctTool=c,s.validArgs=!0,s.schemaCompliant=!0}else if(i.length>0){let c=i[0],l=c.function?.name||"unknown",u=c.function?.arguments||{};s.producedToolCall=!0,s.toolCalled=l;let d=Array.isArray(t.expectedTool)?t.expectedTool:[t.expectedTool];if(s.correctTool=d.includes(l),s.correctTool){let f=tf.find(m=>m.function?.name===l);if(s.validArgs=!!t.validateArgs(u,f),f){let m=f.function?.parameters||{},h=m.required||[],p=Object.keys(m.properties||{});s.schemaCompliant=h.every(g=>u[g]!==void 0)&&Object.keys(u).every(g=>p.includes(g))}}}}catch(r){s.latencyMs=Date.now()-n,s.error=r.message.slice(0,120)}return s}function bs(t){return t.error?0:((t.producedToolCall?Ho.producedToolCall:0)+(t.correctTool?Ho.correctTool:0)+(t.validArgs?Ho.validArgs:0)+(t.schemaCompliant?Ho.schemaCompliant:0))*100}var nb={coding:"coding",search:"coding",shell:"coding",schema:"coding","multi-step":"coding",reasoning:"coding",frontend:"frontend",sysadmin:"sysadmin",data:"data",agentic:"agentic"};function zi(t){return Object.entries(t).map(([e,s])=>{let o=s.map(bs),n=o.reduce((c,l)=>c+l,0)/o.length,r=c=>Math.round(s.filter(c).length/s.length*100),i={};for(let c of["coding","frontend","sysadmin","data","agentic"]){let l=s.filter(d=>nb[d.category]===c);if(l.length===0)continue;let u=l.map(bs).reduce((d,f)=>d+f,0)/l.length;i[c]=Math.round(u*10)/10}return{model:e,score:Math.round(n*10)/10,toolCallRate:r(c=>!c.error&&(c.producedToolCall||c.category==="reasoning")),correctRate:r(c=>c.correctTool),validArgsRate:r(c=>c.validArgs),schemaRate:r(c=>c.schemaCompliant),avgLatency:Math.round(s.reduce((c,l)=>c+l.latencyMs,0)/s.length),errorCount:s.filter(c=>c.error).length,categoryScores:i,results:s}}).sort((e,s)=>s.score-e.score)}function sb(t){let e={};for(let s of["coding","frontend","sysadmin","data","agentic"]){let o=t.filter(n=>n.categoryScores[s]!==void 0).sort((n,r)=>r.categoryScores[s]-n.categoryScores[s]);o.length>0&&(e[s]={model:o[0].model,score:o[0].categoryScores[s]})}return e}function rf(t,e){let s=`nex-code Model Benchmark (${e} tasks \xB7 ollama cloud)`,o=[{label:"#",width:3},{label:"Model",width:26},{label:"Score",width:7},{label:"Tool\u2713",width:7},{label:"Name\u2713",width:7},{label:"Args\u2713",width:7},{label:"Schema\u2713",width:8},{label:"Latency",width:8},{label:"Err",width:4}],n=o.reduce((u,d)=>u+d.width+1,0)+1,r="\u2500".repeat(n);console.log(`
|
|
890
|
-
${J.bold}${s}${J.reset}`),console.log(r);let
|
|
889
|
+
`;Ke.writeFileSync(s,c),a=!0}return{saved:!0,envUpdated:a,changes:o}}nf.exports={findNewModels:Q0,fetchCloudModels:ef,loadKnownModels:Gi,markBenchmarked:V0,updateReadme:tb,updateModelsEnv:nb,updateRoutingConfig:sb,generateBenchmarkBlock:tf,SENTINEL_START:Ki,SENTINEL_END:Uo}});var _s=q((Z_,lf)=>{"use strict";var{C:J}=we(),ob=be(),{TOOL_DEFINITIONS:sf}=ut(),ws=[{id:"read-package",category:"file-ops",prompt:"Read the file package.json and show me its contents.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("package.json")},{id:"write-file",category:"file-ops",prompt:'Create a file at /tmp/nex-bench-test.txt with the content "benchmark run".',expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&typeof t.content=="string"},{id:"edit-file",category:"file-ops",prompt:'In the file src/config.js, replace the string "debug: false" with "debug: true".',expectedTool:["edit_file","patch_file"],validateArgs:t=>!!(t.path&&t.old_string!==void 0&&t.new_string!==void 0||t.path&&Array.isArray(t.patches)&&t.patches.length>0)},{id:"list-directory",category:"file-ops",prompt:"Show me all files and folders in the cli/ directory.",expectedTool:["list_directory","glob"],validateArgs:t=>!!(typeof t.path=="string"&&t.path.includes("cli")||typeof t.pattern=="string"&&t.pattern.includes("cli"))},{id:"glob-js-files",category:"file-ops",prompt:"Find all JavaScript files (*.js) recursively in the cli/ directory.",expectedTool:"glob",validateArgs:t=>typeof t.pattern=="string"&&t.pattern.includes(".js")},{id:"search-constant",category:"search",prompt:'Search for the string "DEFAULT_MODEL" across all files in the project.',expectedTool:["search_files","grep"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("DEFAULT_MODEL")},{id:"grep-function-def",category:"search",prompt:'Find where the function "callStream" is defined in the codebase.',expectedTool:["grep","search_files"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("callStream")},{id:"search-todos",category:"search",prompt:"Find all TODO comments in the source code.",expectedTool:["grep","search_files","bash"],validateArgs:t=>JSON.stringify(t).toUpperCase().includes("TODO")},{id:"git-branch",category:"shell",prompt:"What git branch am I currently on?",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("git")},{id:"git-status",category:"shell",prompt:"Show me the current git status of the repository.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("git status")},{id:"npm-install",category:"shell",prompt:"Run npm install to install project dependencies.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("npm")},{id:"schema-strict",category:"schema",prompt:"Read the file README.md",expectedTool:"read_file",validateArgs:(t,e)=>{let s=e?.function?.parameters||{},o=s.required||[],n=Object.keys(s.properties||{});return o.every(r=>t[r]!==void 0)&&Object.keys(t).every(r=>n.includes(r))}},{id:"multi-step-version",category:"multi-step",prompt:"What is the current version of this project? Check the source files.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("package.json")},{id:"multi-step-count",category:"multi-step",prompt:"How many JavaScript files are in the cli/ directory? Count them.",expectedTool:["bash","glob","list_directory"],validateArgs:t=>!!(typeof t.command=="string"&&t.command.includes("cli")||typeof t.pattern=="string"&&t.pattern.includes("cli")||typeof t.path=="string"&&t.path.includes("cli"))},{id:"no-tool-reasoning",category:"reasoning",prompt:'What does the acronym "API" stand for?',expectedTool:null,validateArgs:()=>!0},{id:"frontend-find-hook",category:"frontend",prompt:"Find all files that import useState from React.",expectedTool:["grep","search_files"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("useState")},{id:"frontend-create-component",category:"frontend",prompt:"Create a React functional component called Button that accepts a label prop and renders a styled button element. Save it to src/components/Button.jsx.",expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&(t.path.includes(".jsx")||t.path.includes(".tsx")||t.path.includes(".js"))&&typeof t.content=="string"},{id:"frontend-edit-css",category:"frontend",prompt:'In the file src/styles.css, change the background-color value from "blue" to "red".',expectedTool:["edit_file","patch_file"],validateArgs:t=>t.path&&t.old_string!==void 0?t.path.includes(".css")||t.old_string.includes("blue")||t.old_string.includes("background"):!!(t.path&&Array.isArray(t.patches))},{id:"frontend-glob-components",category:"frontend",prompt:"Find all JSX and TSX component files in the components/ directory.",expectedTool:"glob",validateArgs:t=>typeof t.pattern=="string"&&(t.pattern.includes(".jsx")||t.pattern.includes(".tsx")||t.pattern.includes("{jsx,tsx}"))},{id:"frontend-list-assets",category:"frontend",prompt:"List all files in the src/assets/ directory.",expectedTool:["list_directory","glob"],validateArgs:t=>!!(typeof t.path=="string"&&t.path.includes("assets")||typeof t.pattern=="string"&&t.pattern.includes("assets"))},{id:"sysadmin-port-check",category:"sysadmin",prompt:"Which process is currently listening on port 3000?",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("lsof")||t.command.includes("ss")||t.command.includes("netstat")||t.command.includes("3000"))},{id:"sysadmin-nginx-config",category:"sysadmin",prompt:"Create an nginx server block that proxies requests to localhost:3000. Save it to /etc/nginx/sites-available/myapp.",expectedTool:["write_file","bash"],validateArgs:t=>!!(t.path&&(t.path.includes("nginx")||t.path.includes("sites-available"))||t.command&&t.command.includes("nginx"))},{id:"sysadmin-service-status",category:"sysadmin",prompt:"Check the status of the nginx service and show if it is running.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("systemctl")||t.command.includes("service")||t.command.includes("nginx"))},{id:"sysadmin-error-log",category:"sysadmin",prompt:"Show the last 100 lines of the nginx error log.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("tail")||t.command.includes("journalctl")||t.command.includes("nginx"))},{id:"sysadmin-docker-compose",category:"sysadmin",prompt:"Create a docker-compose.yml file for a Node.js application with a PostgreSQL database.",expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("docker-compose")&&typeof t.content=="string"},{id:"data-sql-query",category:"data",prompt:"Write a SQL query to find all users who have not logged in for more than 30 days. Save it to queries/inactive-users.sql.",expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&(t.path.includes(".sql")||t.path.includes("quer"))&&typeof t.content=="string"},{id:"data-find-json-key",category:"data",prompt:'Find all JSON files in the project that contain the key "userId".',expectedTool:["grep","search_files"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("userId")},{id:"data-python-csv",category:"data",prompt:'Write a Python script that reads data.csv and calculates the average of the "price" column. Save it to scripts/average_price.py.',expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes(".py")&&typeof t.content=="string"},{id:"data-find-migrations",category:"data",prompt:"Find all database migration files in this project.",expectedTool:["glob","search_files","grep"],validateArgs:t=>JSON.stringify(t).toLowerCase().includes("migrat")},{id:"agentic-test-first",category:"agentic",prompt:"Run the full test suite. If any tests fail, identify the failing test file and read it to understand the issue.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("test")||t.command.includes("jest")||t.command.includes("npm"))},{id:"agentic-read-then-act",category:"agentic",prompt:"Read the project README.md, find the TODO section, and list which items are completed.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("README")},{id:"agentic-build-deploy",category:"agentic",prompt:"Build the project with npm run build, then verify the output exists in the dist/ directory.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("build")||t.command.includes("npm"))}],of=["minimax-m2.7:cloud","qwen3-coder:480b","kimi-k2:1t","devstral-2:123b","devstral-small-2:24b"],rf=["minimax-m2.7:cloud","qwen3-coder:480b","devstral-2:123b"],rb=7,Ho={producedToolCall:.2,correctTool:.35,validArgs:.3,schemaCompliant:.15},ib="You are a coding assistant. Use the provided tools to help with file operations, search, and development tasks. Only call a tool when one is clearly needed to answer the request. Do not call a tool for questions you can answer from general knowledge.";async function af(t,e){let s={taskId:t.id,category:t.category,model:e,producedToolCall:!1,correctTool:!1,validArgs:!1,schemaCompliant:!1,toolCalled:null,error:null,latencyMs:0},o=[{role:"system",content:ib},{role:"user",content:t.prompt}],n=Date.now();try{let r=await ob.callChat(o,sf,{provider:"ollama",model:e,temperature:0,timeout:9e4});s.latencyMs=Date.now()-n;let a=r.tool_calls||[];if(t.expectedTool===null){let c=a.length===0;s.producedToolCall=c,s.correctTool=c,s.validArgs=!0,s.schemaCompliant=!0}else if(a.length>0){let c=a[0],l=c.function?.name||"unknown",u=c.function?.arguments||{};s.producedToolCall=!0,s.toolCalled=l;let d=Array.isArray(t.expectedTool)?t.expectedTool:[t.expectedTool];if(s.correctTool=d.includes(l),s.correctTool){let f=sf.find(m=>m.function?.name===l);if(s.validArgs=!!t.validateArgs(u,f),f){let m=f.function?.parameters||{},h=m.required||[],p=Object.keys(m.properties||{});s.schemaCompliant=h.every(g=>u[g]!==void 0)&&Object.keys(u).every(g=>p.includes(g))}}}}catch(r){s.latencyMs=Date.now()-n,s.error=r.message.slice(0,120)}return s}function bs(t){return t.error?0:((t.producedToolCall?Ho.producedToolCall:0)+(t.correctTool?Ho.correctTool:0)+(t.validArgs?Ho.validArgs:0)+(t.schemaCompliant?Ho.schemaCompliant:0))*100}var ab={coding:"coding",search:"coding",shell:"coding",schema:"coding","multi-step":"coding",reasoning:"coding",frontend:"frontend",sysadmin:"sysadmin",data:"data",agentic:"agentic"};function zi(t){return Object.entries(t).map(([e,s])=>{let o=s.map(bs),n=o.reduce((c,l)=>c+l,0)/o.length,r=c=>Math.round(s.filter(c).length/s.length*100),a={};for(let c of["coding","frontend","sysadmin","data","agentic"]){let l=s.filter(d=>ab[d.category]===c);if(l.length===0)continue;let u=l.map(bs).reduce((d,f)=>d+f,0)/l.length;a[c]=Math.round(u*10)/10}return{model:e,score:Math.round(n*10)/10,toolCallRate:r(c=>!c.error&&(c.producedToolCall||c.category==="reasoning")),correctRate:r(c=>c.correctTool),validArgsRate:r(c=>c.validArgs),schemaRate:r(c=>c.schemaCompliant),avgLatency:Math.round(s.reduce((c,l)=>c+l.latencyMs,0)/s.length),errorCount:s.filter(c=>c.error).length,categoryScores:a,results:s}}).sort((e,s)=>s.score-e.score)}function cb(t){let e={};for(let s of["coding","frontend","sysadmin","data","agentic"]){let o=t.filter(n=>n.categoryScores[s]!==void 0).sort((n,r)=>r.categoryScores[s]-n.categoryScores[s]);o.length>0&&(e[s]={model:o[0].model,score:o[0].categoryScores[s]})}return e}function cf(t,e){let s=`nex-code Model Benchmark (${e} tasks \xB7 ollama cloud)`,o=[{label:"#",width:3},{label:"Model",width:26},{label:"Score",width:7},{label:"Tool\u2713",width:7},{label:"Name\u2713",width:7},{label:"Args\u2713",width:7},{label:"Schema\u2713",width:8},{label:"Latency",width:8},{label:"Err",width:4}],n=o.reduce((u,d)=>u+d.width+1,0)+1,r="\u2500".repeat(n);console.log(`
|
|
890
|
+
${J.bold}${s}${J.reset}`),console.log(r);let a=o.map(u=>u.label.padEnd(u.width)).join(" ");if(console.log(`${J.dim}${a}${J.reset}`),console.log(r),t.forEach((u,d)=>{let f=String(d+1).padEnd(o[0].width),m=u.model.slice(0,o[1].width).padEnd(o[1].width),h=String(u.score).padEnd(o[2].width),p=`${u.toolCallRate}%`.padEnd(o[3].width),g=`${u.correctRate}%`.padEnd(o[4].width),y=`${u.validArgsRate}%`.padEnd(o[5].width),$=`${u.schemaRate}%`.padEnd(o[6].width),w=`${(u.avgLatency/1e3).toFixed(1)}s`.padEnd(o[7].width),E=u.errorCount>0?`${J.red}${u.errorCount}${J.reset}`:`${J.dim}0${J.reset}`,b=u.score>=80?J.green:u.score>=60?J.yellow:J.red,k=d===0?`${J.yellow}${f}${J.reset}`:`${J.dim}${f}${J.reset}`;console.log(`${k} ${b}${m}${J.reset} ${J.bold}${b}${h}${J.reset} ${p} ${g} ${y} ${$} ${J.dim}${w}${J.reset} ${E}`)}),console.log(r),t.length>0){let u=t[0];if(console.log(`
|
|
891
891
|
${J.bold}${J.green}Winner: ${u.model}${J.reset} score ${u.score}/100`),t.length>1){let d=(u.score-t[1].score).toFixed(1);console.log(`${J.dim}+${d} pts over ${t[1].model}${J.reset}`)}}let c=["coding","frontend","sysadmin","data","agentic"];if(t.some(u=>Object.keys(u.categoryScores).length>1)){console.log(`
|
|
892
|
-
${J.bold}Best model per task type:${J.reset}`);for(let u of c){let d=t.filter(p=>p.categoryScores[u]!==void 0).sort((p,g)=>g.categoryScores[u]-p.categoryScores[u]);if(d.length===0)continue;let f=d[0],m=f.categoryScores[u],h=m>=80?J.green:m>=60?J.yellow:J.red;console.log(` ${J.dim}${u.padEnd(10)}${J.reset} ${h}${f.model}${J.reset} ${J.dim}${m}/100${J.reset}`)}}console.log()}async function
|
|
893
|
-
${
|
|
894
|
-
`)}function
|
|
895
|
-
${
|
|
896
|
-
${
|
|
897
|
-
${
|
|
898
|
-
${
|
|
899
|
-
${
|
|
900
|
-
${
|
|
901
|
-
${
|
|
902
|
-
${
|
|
903
|
-
${
|
|
904
|
-
${
|
|
905
|
-
${
|
|
906
|
-
|
|
907
|
-
${
|
|
908
|
-
${
|
|
909
|
-
${
|
|
910
|
-
${
|
|
911
|
-
${
|
|
912
|
-
|
|
913
|
-
${
|
|
914
|
-
${
|
|
915
|
-
${
|
|
916
|
-
${
|
|
917
|
-
${
|
|
918
|
-
${
|
|
919
|
-
|
|
920
|
-
${
|
|
921
|
-
${
|
|
922
|
-
${
|
|
923
|
-
${
|
|
924
|
-
|
|
925
|
-
${
|
|
926
|
-
${
|
|
927
|
-
${
|
|
928
|
-
${
|
|
929
|
-
${
|
|
930
|
-
${
|
|
931
|
-
|
|
932
|
-
${
|
|
933
|
-
${
|
|
934
|
-
${
|
|
935
|
-
${
|
|
936
|
-
|
|
937
|
-
${
|
|
938
|
-
${
|
|
939
|
-
${
|
|
940
|
-
${
|
|
941
|
-
${
|
|
942
|
-
${
|
|
943
|
-
${
|
|
944
|
-
|
|
945
|
-
${
|
|
946
|
-
${
|
|
947
|
-
${
|
|
948
|
-
|
|
949
|
-
${
|
|
950
|
-
${
|
|
951
|
-
${
|
|
952
|
-
${
|
|
953
|
-
|
|
954
|
-
${
|
|
955
|
-
${
|
|
956
|
-
${
|
|
957
|
-
|
|
958
|
-
${
|
|
959
|
-
`)}function
|
|
960
|
-
${
|
|
961
|
-
${
|
|
962
|
-
${
|
|
892
|
+
${J.bold}Best model per task type:${J.reset}`);for(let u of c){let d=t.filter(p=>p.categoryScores[u]!==void 0).sort((p,g)=>g.categoryScores[u]-p.categoryScores[u]);if(d.length===0)continue;let f=d[0],m=f.categoryScores[u],h=m>=80?J.green:m>=60?J.yellow:J.red;console.log(` ${J.dim}${u.padEnd(10)}${J.reset} ${h}${f.model}${J.reset} ${J.dim}${m}/100${J.reset}`)}}console.log()}async function lb({models:t,quick:e=!1,onProgress:s}={}){let o=e?ws.slice(0,rb):ws,n=t?.length>0?t:e?rf:of,r={};for(let c of n){r[c]=[];for(let l of o){s?.({model:c,task:l.id,done:!1});let u=await af(l,c);r[c].push(u),s?.({model:c,task:l.id,done:!0,score:bs(u),error:u.error})}}let a=zi(r);return cf(a,o.length),a}async function ub({newModels:t,existingRanking:e=[],onProgress:s}={}){if(!t||t.length===0)return e;let o={};for(let a of t){o[a]=[];for(let c of ws){s?.({model:a,task:c.id,done:!1});let l=await af(c,a);o[a].push(l),s?.({model:a,task:c.id,done:!0,score:bs(l),error:l.error})}}let r=[...zi(o)];for(let a of e)r.find(c=>c.model===a.model)||r.push(a);return r.sort((a,c)=>c.score-a.score),cf(r,ws.length),r}lf.exports={runBenchmark:lb,runDiscoverBenchmark:ub,buildSummary:zi,buildCategoryWinners:cb,TASKS:ws,scoreResult:bs,DEFAULT_MODELS:of,QUICK_MODELS:rf}});var ff=q((ek,df)=>{var db=require("axios"),ks=require("fs"),uf=require("path"),fb="nex-code",Yi=uf.join(process.cwd(),".nex"),Xi=uf.join(Yi,"last-version-check");ks.existsSync(Yi)||ks.mkdirSync(Yi,{recursive:!0});async function pb(){try{let t=hb(),e=Date.now();if(t&&e-t<1440*60*1e3)return{hasNewVersion:!1};gb(e);let s=mb(),n=(await db.get(`https://registry.npmjs.org/${fb}/latest`,{timeout:5e3})).data.version,r=$b(n,s);return{hasNewVersion:r,latestVersion:r?n:void 0,currentVersion:r?s:void 0}}catch{return{hasNewVersion:!1}}}function mb(){return Es().version}function hb(){try{if(ks.existsSync(Xi)){let t=ks.readFileSync(Xi,"utf8");return parseInt(t,10)}}catch{}return null}function gb(t){try{ks.writeFileSync(Xi,t.toString())}catch{}}function $b(t,e){try{let s=t.split(".").map(Number),o=e.split(".").map(Number);return s[0]>o[0]?!0:s[0]<o[0]?!1:s[1]>o[1]?!0:s[1]<o[1]?!1:s[2]>o[2]}catch{return!1}}df.exports={checkForNewVersion:pb}});var Ef=q((nk,Sf)=>{var yb=require("readline"),qe=require("fs"),Ee=require("path"),{C:i,banner:wb,cleanupTerminal:pf}=we(),{isDark:bb}=Ht(),{listProviders:Vi,getActiveProviderName:ln,listAllModels:tk,setFallbackChain:_b,getFallbackChain:kb,getProvider:xb}=be(),{flushAutoSave:mf}=Et(),{getActiveModel:At,setActiveModel:Qi}=qs(),{printContext:hf}=yo(),{loadAllSkills:vb,getSkillCommands:Zi,handleSkillCommand:Sb}=Lt(),{setReadlineInterface:Eb,setAutoConfirm:Tb,getAutoConfirm:gf}=Ie(),{StickyFooter:Rb}=Id(),ht=process.cwd(),Ct=null;function $f(){return Ct?.signal??null}var Ko=[{cmd:"/help",desc:"Show full help"},{cmd:"/model",desc:"Show/switch model"},{cmd:"/providers",desc:"List providers and models"},{cmd:"/fallback",desc:"Show/set fallback chain"},{cmd:"/tokens",desc:"Token usage and context budget"},{cmd:"/costs",desc:"Session token costs"},{cmd:"/budget",desc:"Show/set cost limits per provider"},{cmd:"/clear",desc:"Clear conversation"},{cmd:"/context",desc:"Show project context"},{cmd:"/tree [depth]",desc:"Show project file tree (default depth 3)"},{cmd:"/autoconfirm",desc:"Toggle auto-confirm"},{cmd:"/save",desc:"Save session"},{cmd:"/load",desc:"Load a saved session"},{cmd:"/sessions",desc:"List saved sessions"},{cmd:"/resume",desc:"Resume last session"},{cmd:"/remember",desc:"Save a memory"},{cmd:"/forget",desc:"Delete a memory"},{cmd:"/memory",desc:"Show all memories"},{cmd:"/brain",desc:"Manage knowledge base"},{cmd:"/brain add",desc:"Add document: /brain add <name> [content]"},{cmd:"/brain list",desc:"List all brain documents"},{cmd:"/brain search",desc:"Search brain: /brain search <query>"},{cmd:"/brain show",desc:"Show document: /brain show <name>"},{cmd:"/brain remove",desc:"Remove document: /brain remove <name>"},{cmd:"/brain rebuild",desc:"Rebuild keyword index"},{cmd:"/brain embed",desc:"Build/rebuild embedding index"},{cmd:"/brain status",desc:"Show brain status (docs, index, embeddings)"},{cmd:"/brain review",desc:"Review pending brain changes (git diff)"},{cmd:"/brain undo",desc:"Undo last brain write"},{cmd:"/learn",desc:"Reflect on session and update memory"},{cmd:"/optimize",desc:"Show optimization opportunities"},{cmd:"/permissions",desc:"Show tool permissions"},{cmd:"/allow",desc:"Auto-allow a tool"},{cmd:"/deny",desc:"Block a tool"},{cmd:"/plan",desc:"Plan mode (analyze before executing)"},{cmd:"/plan edit",desc:"Open current plan in $EDITOR"},{cmd:"/plans",desc:"List saved plans"},{cmd:"/auto",desc:"Set autonomy level"},{cmd:"/commit",desc:"Smart commit (diff + message)"},{cmd:"/diff",desc:"Show current diff"},{cmd:"/review [--strict] [file]",desc:"Deep code review with score table and diff suggestions (--strict: force \u22653 critical findings)"},{cmd:"/branch",desc:"Create feature branch"},{cmd:"/mcp",desc:"MCP servers and tools"},{cmd:"/hooks",desc:"Show configured hooks"},{cmd:"/skills",desc:"List, enable, disable skills"},{cmd:"/install-skill <url>",desc:"Install a skill from git URL or user/repo"},{cmd:"/search-skill <query>",desc:"Search for skills on GitHub"},{cmd:"/remove-skill <name>",desc:"Remove an installed skill"},{cmd:"/tasks",desc:"Show task list"},{cmd:"/servers",desc:"List server profiles / ping"},{cmd:"/docker",desc:"List containers across all servers"},{cmd:"/deploy",desc:"List deploy configs / run named deploy"},{cmd:"/benchmark [--quick] [--models=a,b]",desc:"Rank Ollama Cloud models on nex-code tool-calling tasks (--history for nightly log)"},{cmd:"/init",desc:"Interactive setup wizard (.nex/)"},{cmd:"/setup",desc:"Configure provider and API keys"},{cmd:"/undo",desc:"Undo last file change"},{cmd:"/redo",desc:"Redo last undone change"},{cmd:"/history",desc:"Show file change history"},{cmd:"/snapshot [name]",desc:"Create a named git snapshot of current changes"},{cmd:"/restore [name|last]",desc:"Restore a previously created snapshot"},{cmd:"/audit",desc:"Show tool execution audit log"},{cmd:"/k8s",desc:"Kubernetes overview: namespaces and pods"},{cmd:"/exit",desc:"Quit"}];function yf(){let t=Zi(),e=[...Ko,...t],s=Math.max(...e.map(o=>o.cmd.length));console.log("");for(let{cmd:o,desc:n}of Ko)console.log(` ${i.cyan}${o.padEnd(s+2)}${i.reset}${i.dim}${n}${i.reset}`);for(let{cmd:o,desc:n}of t)console.log(` ${i.cyan}${o.padEnd(s+2)}${i.reset}${i.dim}${n} ${i.yellow}[skill]${i.reset}`);console.log(`
|
|
893
|
+
${i.dim}Type /help for detailed usage${i.reset}
|
|
894
|
+
`)}function wf(t){try{let e,s;t.endsWith("/")||t.endsWith(Ee.sep)?(e=t,s=""):(e=Ee.dirname(t),s=Ee.basename(t)),e.startsWith("~")&&(e=Ee.join(require("os").homedir(),e.slice(1)));let o=Ee.isAbsolute(e)?e:Ee.resolve(ht,e);if(!qe.existsSync(o)||!qe.statSync(o).isDirectory())return[];let n=qe.readdirSync(o,{withFileTypes:!0}),r=[];for(let a of n){if(a.name.startsWith(".")||a.name==="node_modules"||s&&!a.name.startsWith(s))continue;let c=t.endsWith("/")||t.endsWith(Ee.sep)?t:Ee.dirname(t)+"/",l=c==="./"&&!t.startsWith("./")?a.name:c+a.name;r.push(a.isDirectory()?l+"/":l)}return r}catch{return[]}}function bf(t){if(t.startsWith("/")){let o=[...Ko,...Zi()],n=o.map(r=>r.cmd).filter(r=>r.startsWith(t));return[n.length?n:o.map(r=>r.cmd),t]}let e=t.split(/\s+/),s=e[e.length-1]||"";return s&&(s.includes("/")||s.startsWith("./")||s.startsWith("../")||s.startsWith("~"))?[wf(s),s]:[[],t]}function _f(){console.log(`
|
|
895
|
+
${i.bold}${i.cyan}Commands:${i.reset}
|
|
896
|
+
${i.cyan}/help${i.reset} ${i.dim}Show this help${i.reset}
|
|
897
|
+
${i.cyan}/model [spec]${i.reset} ${i.dim}Show/switch model (e.g. openai:gpt-4o, claude-sonnet)${i.reset}
|
|
898
|
+
${i.cyan}/providers${i.reset} ${i.dim}Show available providers and models${i.reset}
|
|
899
|
+
${i.cyan}/fallback [chain]${i.reset} ${i.dim}Show/set fallback chain (e.g. anthropic,openai,local)${i.reset}
|
|
900
|
+
${i.cyan}/tokens${i.reset} ${i.dim}Show token usage and context budget${i.reset}
|
|
901
|
+
${i.cyan}/costs${i.reset} ${i.dim}Show session token costs${i.reset}
|
|
902
|
+
${i.cyan}/budget [prov] [n]${i.reset}${i.dim}Show/set cost limits per provider${i.reset}
|
|
903
|
+
${i.cyan}/clear${i.reset} ${i.dim}Clear conversation context${i.reset}
|
|
904
|
+
${i.cyan}/context${i.reset} ${i.dim}Show project context${i.reset}
|
|
905
|
+
${i.cyan}/autoconfirm${i.reset} ${i.dim}Toggle auto-confirm for file changes${i.reset}
|
|
906
|
+
|
|
907
|
+
${i.bold}${i.cyan}Sessions:${i.reset}
|
|
908
|
+
${i.cyan}/save [name]${i.reset} ${i.dim}Save current session${i.reset}
|
|
909
|
+
${i.cyan}/load <name>${i.reset} ${i.dim}Load a saved session${i.reset}
|
|
910
|
+
${i.cyan}/sessions${i.reset} ${i.dim}List all saved sessions${i.reset}
|
|
911
|
+
${i.cyan}/resume${i.reset} ${i.dim}Resume last session${i.reset}
|
|
912
|
+
|
|
913
|
+
${i.bold}${i.cyan}Memory:${i.reset}
|
|
914
|
+
${i.cyan}/remember <text>${i.reset} ${i.dim}Save a memory (key=value or freeform)${i.reset}
|
|
915
|
+
${i.cyan}/forget <key>${i.reset} ${i.dim}Delete a memory${i.reset}
|
|
916
|
+
${i.cyan}/memory${i.reset} ${i.dim}Show all memories${i.reset}
|
|
917
|
+
${i.cyan}/learn${i.reset} ${i.dim}Reflect on this session and auto-update memory + NEX.md${i.reset}
|
|
918
|
+
${i.cyan}/optimize${i.reset} ${i.dim}Show context, memory health, and optimization tips${i.reset}
|
|
919
|
+
|
|
920
|
+
${i.bold}${i.cyan}Permissions:${i.reset}
|
|
921
|
+
${i.cyan}/permissions${i.reset} ${i.dim}Show tool permissions${i.reset}
|
|
922
|
+
${i.cyan}/allow <tool>${i.reset} ${i.dim}Auto-allow a tool${i.reset}
|
|
923
|
+
${i.cyan}/deny <tool>${i.reset} ${i.dim}Block a tool${i.reset}
|
|
924
|
+
|
|
925
|
+
${i.bold}${i.cyan}Planning:${i.reset}
|
|
926
|
+
${i.cyan}/plan [task]${i.reset} ${i.dim}Enter plan mode (analyze, don't execute)${i.reset}
|
|
927
|
+
${i.cyan}/plan status${i.reset} ${i.dim}Show current plan progress${i.reset}
|
|
928
|
+
${i.cyan}/plan approve${i.reset} ${i.dim}Approve current plan${i.reset}
|
|
929
|
+
${i.cyan}/plans${i.reset} ${i.dim}List saved plans${i.reset}
|
|
930
|
+
${i.cyan}/auto [level]${i.reset} ${i.dim}Set autonomy: interactive/semi-auto/autonomous${i.reset}
|
|
931
|
+
|
|
932
|
+
${i.bold}${i.cyan}Git:${i.reset}
|
|
933
|
+
${i.cyan}/commit [msg]${i.reset} ${i.dim}Smart commit (analyze diff, suggest message)${i.reset}
|
|
934
|
+
${i.cyan}/diff${i.reset} ${i.dim}Show current diff summary${i.reset}
|
|
935
|
+
${i.cyan}/branch [name]${i.reset} ${i.dim}Create feature branch${i.reset}
|
|
936
|
+
|
|
937
|
+
${i.bold}${i.cyan}Extensibility:${i.reset}
|
|
938
|
+
${i.cyan}/mcp${i.reset} ${i.dim}Show MCP servers and tools${i.reset}
|
|
939
|
+
${i.cyan}/mcp connect${i.reset} ${i.dim}Connect all configured MCP servers${i.reset}
|
|
940
|
+
${i.cyan}/hooks${i.reset} ${i.dim}Show configured hooks${i.reset}
|
|
941
|
+
${i.cyan}/skills${i.reset} ${i.dim}List loaded skills${i.reset}
|
|
942
|
+
${i.cyan}/skills enable${i.reset} ${i.dim}Enable a skill by name${i.reset}
|
|
943
|
+
${i.cyan}/skills disable${i.reset} ${i.dim}Disable a skill by name${i.reset}
|
|
944
|
+
|
|
945
|
+
${i.bold}${i.cyan}Tasks:${i.reset}
|
|
946
|
+
${i.cyan}/tasks${i.reset} ${i.dim}Show current task list${i.reset}
|
|
947
|
+
${i.cyan}/tasks clear${i.reset} ${i.dim}Clear all tasks${i.reset}
|
|
948
|
+
|
|
949
|
+
${i.bold}${i.cyan}Undo / Redo:${i.reset}
|
|
950
|
+
${i.cyan}/undo${i.reset} ${i.dim}Undo last file change${i.reset}
|
|
951
|
+
${i.cyan}/redo${i.reset} ${i.dim}Redo last undone change${i.reset}
|
|
952
|
+
${i.cyan}/history${i.reset} ${i.dim}Show file change history${i.reset}
|
|
953
|
+
|
|
954
|
+
${i.cyan}/benchmark${i.reset} ${i.dim}Rank Ollama Cloud models on nex-code tool-calling tasks${i.reset}
|
|
955
|
+
${i.cyan}/benchmark --quick${i.reset}${i.dim} Fast run: 7 tasks, 3 models${i.reset}
|
|
956
|
+
${i.cyan}/benchmark --models=a,b${i.reset}${i.dim} Custom model list${i.reset}
|
|
957
|
+
|
|
958
|
+
${i.cyan}/exit${i.reset} ${i.dim}Quit${i.reset}
|
|
959
|
+
`)}function kf(t){let s=Math.round(t/100*30),o=30-s;return` ${t>80?i.red:t>50?i.yellow:i.green}${"\u2588".repeat(s)}${i.dim}${"\u2591".repeat(o)}${i.reset} ${t}%`}function Ji(){let t=Vi(),e=ln(),s=At();console.log(`
|
|
960
|
+
${i.bold}${i.cyan}Providers:${i.reset}`);for(let o of t){let n=o.provider===e,r=o.configured?`${i.green}\u2713${i.reset}`:`${i.red}\u2717${i.reset}`,a=n?` ${i.cyan}(active)${i.reset}`:"";console.log(` ${r} ${i.bold}${o.provider}${i.reset}${a}`);for(let c of o.models){let l=c.id===s.id&&n?` ${i.yellow}\u25C4${i.reset}`:"";console.log(` ${i.dim}${c.id}${i.reset} \u2014 ${c.name}${l}`)}}console.log()}async function xf(t,e){let[s,...o]=t.split(/\s+/);switch(s){case"/help":return _f(),!0;case"/model":{let n=o.join(" ").trim();if(!n){if(e){let{showModelPicker:r}=jd();await r(e)}else{let r=At(),a=ln();console.log(`${i.bold}${i.cyan}Active model:${i.reset} ${i.dim}${a}:${r.id} (${r.name})${i.reset}`),console.log(`${i.gray}Use /model <provider:model> to switch. /providers to see all.${i.reset}`)}return!0}if(n==="list")return Ji(),!0;if(Qi(n)){let r=At(),a=ln();console.log(`${i.green}Switched to ${a}:${r.id} (${r.name})${i.reset}`)}else console.log(`${i.red}Unknown model: ${n}${i.reset}`),console.log(`${i.gray}Use /providers to see available models${i.reset}`);return!0}case"/providers":return Ji(),!0;case"/fallback":{let n=o.join(" ").trim();if(!n){let a=kb();return a.length===0?(console.log(`${i.dim}No fallback chain configured${i.reset}`),console.log(`${i.dim}Use /fallback anthropic,openai,local to set${i.reset}`)):console.log(`${i.bold}${i.cyan}Fallback chain:${i.reset} ${a.join(" \u2192 ")}`),!0}let r=n.split(",").map(a=>a.trim()).filter(Boolean);return _b(r),console.log(`${i.green}Fallback chain: ${r.join(" \u2192 ")}${i.reset}`),!0}case"/tokens":{let{getConversationMessages:n}=de(),{getUsage:r}=lt(),{TOOL_DEFINITIONS:a}=ut(),c=n(),l=r(c,a),u=At(),d=ln();console.log(`
|
|
961
|
+
${i.bold}${i.cyan}Token Usage:${i.reset}`),console.log(` ${i.dim}Model:${i.reset} ${d}:${u.id} (${(l.limit/1e3).toFixed(0)}k context)`),console.log(` ${i.dim}Used:${i.reset} ${l.used.toLocaleString()} / ${l.limit.toLocaleString()} (${l.percentage}%)`);let f=kf(l.percentage);return console.log(` ${f}`),console.log(`
|
|
962
|
+
${i.dim}Breakdown:${i.reset}`),console.log(` System prompt: ${l.breakdown.system.toLocaleString()} tokens`),console.log(` Conversation: ${l.breakdown.conversation.toLocaleString()} tokens`),console.log(` Tool results: ${l.breakdown.toolResults.toLocaleString()} tokens`),console.log(` Tool definitions: ${l.breakdown.toolDefinitions.toLocaleString()} tokens`),console.log(` Messages: ${l.messageCount}`),console.log(),!0}case"/costs":{let{formatCosts:n,resetCosts:r}=$n();return o.join(" ").trim()==="reset"?(r(),console.log(`${i.green}Cost tracking reset${i.reset}`),!0):(console.log(`
|
|
963
963
|
${n()}
|
|
964
|
-
`),!0)}case"/budget":{let{getCostLimits:n,getProviderSpend:r,checkBudget:
|
|
965
|
-
${
|
|
966
|
-
`)}else process.stdout.write(`${
|
|
964
|
+
`),!0)}case"/budget":{let{getCostLimits:n,getProviderSpend:r,checkBudget:a,removeCostLimit:c,saveCostLimits:l,setCostLimit:u}=$n(),d=o[0];if(!d){let h=n(),p=Vi();console.log(`
|
|
965
|
+
${i.bold}${i.cyan}Cost Limits:${i.reset}`);let g=!1;for(let y of p){let $=r(y.provider),w=h[y.provider];if(w!==void 0){g=!0;let E=Math.min(100,Math.round($/w*100)),b=10,k=Math.round(E/100*b),v=b-k,C=`${E>=100?i.red:E>=80?i.yellow:i.green}${"\u2588".repeat(k)}${i.dim}${"\u2591".repeat(v)}${i.reset}`;console.log(` ${i.bold}${y.provider}:${i.reset} $${$.toFixed(2)} / $${w.toFixed(2)} (${E}%) ${C}`)}else y.provider==="ollama"||y.provider==="local"?console.log(` ${i.bold}${y.provider}:${i.reset} ${i.dim}free (no limit)${i.reset}`):$>0&&console.log(` ${i.bold}${y.provider}:${i.reset} $${$.toFixed(2)} ${i.dim}(no limit)${i.reset}`)}return g||console.log(` ${i.dim}No limits set. Use /budget <provider> <amount> to set one.${i.reset}`),console.log(),!0}let f=o[1];if(!f){let h=a(d);return h.limit!==null?console.log(`${i.bold}${d}:${i.reset} $${h.spent.toFixed(2)} / $${h.limit.toFixed(2)} ($${h.remaining.toFixed(2)} remaining)`):console.log(`${i.bold}${d}:${i.reset} $${h.spent.toFixed(2)} ${i.dim}(no limit)${i.reset}`),!0}if(f==="off"||f==="remove"||f==="clear")return c(d),l(),console.log(`${i.green}Removed cost limit for ${d}${i.reset}`),!0;let m=parseFloat(f);return isNaN(m)||m<=0?(console.log(`${i.red}Invalid amount: ${f}. Use a positive number or 'off'.${i.reset}`),!0):(u(d,m),l(),console.log(`${i.green}Set ${d} budget limit: $${m.toFixed(2)}${i.reset}`),!0)}case"/clear":{let{clearConversation:n,getConversationMessages:r}=de(),{clearHistory:a}=_t(),c=r();if(c.filter(d=>d.role==="user").length>=4){process.stdout.write(`${i.dim}Reflecting on session...${i.reset} `);let{learnFromSession:d}=Fi();d(c).then(f=>{if(!f.skipped&&!f.error&&(f.applied.length>0||f.nexAdded.length>0)){let m=f.applied.length+f.nexAdded.length;process.stdout.write(`${i.green}${m} learning(s) saved${i.reset}
|
|
966
|
+
`)}else process.stdout.write(`${i.dim}nothing new${i.reset}
|
|
967
967
|
`)}).catch(()=>process.stdout.write(`
|
|
968
|
-
`))}n(),
|
|
969
|
-
${
|
|
970
|
-
`),console.log(`${
|
|
971
|
-
`),!0}case"/autoconfirm":{let n=!
|
|
972
|
-
${
|
|
973
|
-
${
|
|
974
|
-
|
|
975
|
-
`);let g=require("path").join(process.cwd(),".nex","brain",`${h}.md`);console.log(`${
|
|
976
|
-
${
|
|
977
|
-
${
|
|
978
|
-
${
|
|
979
|
-
${
|
|
980
|
-
`),console.log(p.content),!0):(console.log(`${
|
|
981
|
-
${
|
|
982
|
-
${
|
|
983
|
-
`),console.log($)):console.log(`${
|
|
984
|
-
${
|
|
985
|
-
${
|
|
968
|
+
`))}n(),a();let{deleteSession:u}=Et();return u("_autosave"),console.log(`${i.green}Conversation cleared${i.reset}`),!0}case"/context":return await hf(ht),!0;case"/tree":{let{generateFileTree:n}=yo(),r=parseInt(o.join(" ").trim(),10),a=!isNaN(r)&&r>0?Math.min(r,8):3,c=n(ht,{maxDepth:a,maxFiles:300});return console.log(`
|
|
969
|
+
${i.bold}${i.cyan}Project tree${i.reset}${i.dim} (depth ${a})${i.reset}
|
|
970
|
+
`),console.log(`${i.dim}${c}${i.reset}
|
|
971
|
+
`),!0}case"/autoconfirm":{let n=!gf();return Tb(n),console.log(`${i.green}Auto-confirm: ${n?"ON":"OFF"}${i.reset}`),n&&console.log(`${i.yellow} \u26A0 File changes will be applied without confirmation${i.reset}`),!0}case"/save":{let{saveSession:n}=Et(),{getConversationMessages:r}=de(),a=o.join(" ").trim()||`session-${Date.now()}`,c=r();if(c.length===0)return console.log(`${i.yellow}No conversation to save${i.reset}`),!0;let l=At(),u=ln();return n(a,c,{model:l.id,provider:u}),console.log(`${i.green}Session saved: ${a} (${c.length} messages)${i.reset}`),!0}case"/load":{let{loadSession:n}=Et(),{setConversationMessages:r}=de(),a=o.join(" ").trim();if(!a)return console.log(`${i.red}Usage: /load <name>${i.reset}`),!0;let c=n(a);return c?(r(c.messages),console.log(`${i.green}Loaded session: ${c.name} (${c.messageCount} messages)${i.reset}`),!0):(console.log(`${i.red}Session not found: ${a}${i.reset}`),!0)}case"/sessions":{let{listSessions:n}=Et(),r=n();if(r.length===0)return console.log(`${i.dim}No saved sessions${i.reset}`),!0;console.log(`
|
|
972
|
+
${i.bold}${i.cyan}Sessions:${i.reset}`);for(let a of r){let c=a.updatedAt?new Date(a.updatedAt).toLocaleString():"?",l=a.name==="_autosave"?` ${i.dim}(auto)${i.reset}`:"";console.log(` ${i.cyan}${a.name}${i.reset}${l} \u2014 ${a.messageCount} msgs, ${c}`)}return console.log(),!0}case"/resume":{let{getLastSession:n}=Et(),{setConversationMessages:r}=de(),a=n();return a?(r(a.messages),console.log(`${i.green}Resumed: ${a.name} (${a.messageCount} messages)${i.reset}`),!0):(console.log(`${i.yellow}No session to resume${i.reset}`),!0)}case"/remember":{let{remember:n}=Ft(),r=o.join(" ").trim();if(!r)return console.log(`${i.red}Usage: /remember <key>=<value> or /remember <text>${i.reset}`),!0;let a=r.indexOf("="),c,l;return a>0?(c=r.substring(0,a).trim(),l=r.substring(a+1).trim()):(c=r.substring(0,40).replace(/\s+/g,"-"),l=r),n(c,l),console.log(`${i.green}Remembered: ${c}${i.reset}`),!0}case"/forget":{let{forget:n}=Ft(),r=o.join(" ").trim();return r?(n(r)?console.log(`${i.green}Forgotten: ${r}${i.reset}`):console.log(`${i.red}Memory not found: ${r}${i.reset}`),!0):(console.log(`${i.red}Usage: /forget <key>${i.reset}`),!0)}case"/memory":{let{listMemories:n}=Ft(),r=n();if(r.length===0)return console.log(`${i.dim}No memories saved${i.reset}`),!0;console.log(`
|
|
973
|
+
${i.bold}${i.cyan}Memory:${i.reset}`);for(let a of r)console.log(` ${i.cyan}${a.key}${i.reset} = ${a.value}`);return console.log(),!0}case"/brain":{let{listDocuments:n,readDocument:r,writeDocument:a,removeDocument:c,buildIndex:l,buildEmbeddingIndex:u,isEmbeddingAvailable:d,query:f}=ss(),m=o[0],h=o.slice(1).join(" ").trim();switch(m){case"add":{if(!h)return console.log(`${i.red}Usage: /brain add <name> [content]${i.reset}`),console.log(`${i.dim} /brain add api-notes \u2014 creates empty file${i.reset}`),console.log(`${i.dim} /brain add api-notes This is content \u2014 writes directly${i.reset}`),!0;let p=h.indexOf(" ");if(p<0){a(h,`# ${h}
|
|
974
|
+
|
|
975
|
+
`);let g=require("path").join(process.cwd(),".nex","brain",`${h}.md`);console.log(`${i.green}Created .nex/brain/${h}.md${i.reset}`),console.log(`${i.dim}Edit it directly at: ${g}${i.reset}`)}else{let g=h.substring(0,p),y=h.substring(p+1);a(g,y),console.log(`${i.green}Added to brain: ${g}${i.reset}`)}return!0}case"list":{let p=n();if(p.length===0)return console.log(`${i.dim}No brain documents yet. Use /brain add <name> to create one.${i.reset}`),!0;console.log(`
|
|
976
|
+
${i.bold}${i.cyan}Brain Documents:${i.reset}`);let g=Math.max(8,...p.map($=>$.name.length)),y=20;console.log(` ${"Name".padEnd(g+2)}${"Tags".padEnd(y)}${"Size".padStart(7)} Modified`),console.log(` ${"-".repeat(g+2)}${"-".repeat(y)}${"-".repeat(7)} --------`);for(let $ of p){let{frontmatter:w}=r($.name),E=Array.isArray(w.tags)?w.tags.join(", "):"",b=$.size<1024?`${$.size}B`:`${($.size/1024).toFixed(1)}K`,k=$.modified.toLocaleDateString();console.log(` ${i.cyan}${$.name.padEnd(g+2)}${i.reset}${i.dim}${E.substring(0,y-1).padEnd(y)}${b.padStart(7)} ${k}${i.reset}`)}return console.log(),!0}case"search":{if(!h)return console.log(`${i.red}Usage: /brain search <query>${i.reset}`),!0;let p=await f(h,{topK:5});if(p.length===0)return console.log(`${i.dim}No matching brain documents for: ${h}${i.reset}`),!0;console.log(`
|
|
977
|
+
${i.bold}${i.cyan}Brain Search: "${h}"${i.reset}`);for(let g of p){let y=typeof g.score=="number"?g.score.toFixed(2):g.score;console.log(`
|
|
978
|
+
${i.cyan}${g.name}${i.reset} ${i.dim}(score: ${y})${i.reset}`),console.log(` ${i.dim}${g.excerpt||""}${i.reset}`)}return console.log(),!0}case"show":{if(!h)return console.log(`${i.red}Usage: /brain show <name>${i.reset}`),!0;let p=r(h);return p.content?(console.log(`
|
|
979
|
+
${i.bold}${i.cyan}${h}.md${i.reset}
|
|
980
|
+
`),console.log(p.content),!0):(console.log(`${i.red}Document not found: ${h}${i.reset}`),!0)}case"remove":{if(!h)return console.log(`${i.red}Usage: /brain remove <name>${i.reset}`),!0;let{confirm:p}=Ie();if(!await p(`Remove brain document "${h}"?`))return console.log(`${i.dim}Cancelled${i.reset}`),!0;let y=c(h);return console.log(y?`${i.green}Removed: ${h}.md${i.reset}`:`${i.red}Document not found: ${h}${i.reset}`),!0}case"rebuild":{let p=l(),g=Object.keys(p.documents).length;return console.log(`${i.green}Index rebuilt: ${g} document(s)${i.reset}`),!0}case"embed":{if(!await d())return console.log(`${i.yellow}Ollama embedding model not available.${i.reset}`),console.log(`${i.dim}Set NEX_EMBED_MODEL env var (default: nomic-embed-text) and ensure Ollama is running.${i.reset}`),!0;console.log(`${i.dim}Building embedding index...${i.reset}`);try{let g=await u(),y=Object.keys(g.documents||{}).length;console.log(`${i.green}Embedding index built: ${y} document(s)${i.reset}`)}catch(g){console.log(`${i.red}Embedding failed: ${g.message}${i.reset}`)}return!0}case"status":{let p=n(),g=require("fs"),y=require("path"),$=y.join(process.cwd(),".nex","brain",".brain-index.json"),w=y.join(process.cwd(),".nex","brain",".embeddings.json");if(console.log(`
|
|
981
|
+
${i.bold}${i.cyan}Brain Status${i.reset}`),console.log(` Documents: ${p.length}`),console.log(` Index: ${g.existsSync($)?i.green+"present"+i.reset:i.dim+"not built"+i.reset}`),console.log(` Embeddings: ${g.existsSync(w)?i.green+"present"+i.reset:i.dim+"not built (run /brain embed)"+i.reset}`),p.length>0){let E=p.reduce((b,k)=>b+k.size,0);console.log(` Total size: ${E<1024?E+"B":(E/1024).toFixed(1)+"K"}`)}return console.log(),!0}case"review":{let{exec:p}=require("child_process"),{promisify:g}=require("util"),y=g(p);try{let{stdout:$}=await y("git diff .nex/brain/",{cwd:process.cwd()});$.trim()?(console.log(`
|
|
982
|
+
${i.bold}${i.cyan}Brain Changes (git diff):${i.reset}
|
|
983
|
+
`),console.log($)):console.log(`${i.dim}No pending brain changes (clean git state)${i.reset}`)}catch{console.log(`${i.dim}Not a git repo or no brain dir${i.reset}`)}return!0}case"undo":{let p=require("fs"),y=require("path").join(process.cwd(),".nex","brain");if(!p.existsSync(y))return console.log(`${i.dim}No brain directory found${i.reset}`),!0;let $=n();if($.length===0)return console.log(`${i.dim}No brain documents to undo${i.reset}`),!0;let w=$[0],{exec:E}=require("child_process"),{promisify:b}=require("util"),k=b(E);try{await k(`git checkout -- ".nex/brain/${w.name}.md"`,{cwd:process.cwd()}),l(),console.log(`${i.green}Undone: restored ${w.name}.md from git${i.reset}`)}catch{console.log(`${i.red}Could not undo \u2014 not tracked in git or no prior version${i.reset}`)}return!0}default:{let p=n();if(p.length===0)console.log(`
|
|
984
|
+
${i.bold}${i.cyan}Brain Knowledge Base${i.reset}`),console.log(`${i.dim}No documents yet. Create with /brain add <name>${i.reset}`),console.log(`
|
|
985
|
+
${i.dim}Commands: add \xB7 list \xB7 search \xB7 show \xB7 remove \xB7 rebuild \xB7 embed \xB7 status \xB7 review \xB7 undo${i.reset}
|
|
986
986
|
`);else{console.log(`
|
|
987
|
-
${
|
|
988
|
-
${
|
|
989
|
-
`)}return!0}}}case"/learn":{let{learnFromSession:n,learnBrainFromSession:r}=Fi(),{getConversationMessages:
|
|
990
|
-
${
|
|
991
|
-
`);let h=u.percentage>80?
|
|
992
|
-
${
|
|
993
|
-
${
|
|
994
|
-
${
|
|
995
|
-
${
|
|
996
|
-
${
|
|
997
|
-
${
|
|
998
|
-
${
|
|
999
|
-
${
|
|
1000
|
-
${
|
|
1001
|
-
${
|
|
1002
|
-
${
|
|
1003
|
-
`),!0}case"/allow":{let{setPermission:n,savePermissions:r}=fs(),
|
|
1004
|
-
${
|
|
1005
|
-
`),console.log(` Total tool calls: ${
|
|
1006
|
-
${
|
|
987
|
+
${i.bold}${i.cyan}Brain: ${p.length} document(s)${i.reset}`);for(let g of p){let{frontmatter:y}=r(g.name),$=Array.isArray(y.tags)?` [${y.tags.join(", ")}]`:"";console.log(` ${i.cyan}${g.name}${i.reset}${i.dim}${$}${i.reset}`)}console.log(`
|
|
988
|
+
${i.dim}Use /brain search <query> \xB7 /brain show <name> \xB7 /brain add <name>${i.reset}
|
|
989
|
+
`)}return!0}}}case"/learn":{let{learnFromSession:n,learnBrainFromSession:r}=Fi(),{getConversationMessages:a}=de(),c=a(),l=c.filter(u=>u.role==="user").length;if(l<4)return console.log(`${i.yellow}Session too short to learn from (need 4+ user messages, have ${l})${i.reset}`),!0;console.log(`${i.dim}Analyzing session for learnings...${i.reset}`);try{let[u,d]=await Promise.all([n(c),r(c)]);if(u.skipped&&(!d.written||d.written.length===0))return console.log(`${i.dim}Session too short${i.reset}`),!0;u.error&&console.log(`${i.red}Reflection error: ${u.error}${i.reset}`),console.log(""),u.summary&&(console.log(`${i.bold}Session:${i.reset} ${i.dim}${u.summary}${i.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(`${i.dim}No new learnings extracted from this session${i.reset}`);else{if(f){console.log(`${i.bold}${i.cyan}Memory updates:${i.reset}`);for(let{key:p,value:g,action:y}of u.applied){let $=y==="updated"?`${i.yellow}~${i.reset}`:`${i.green}+${i.reset}`;console.log(` ${$} ${i.bold}${p}${i.reset} = ${g}`)}}if(m){console.log(`${i.bold}${i.cyan}Added to NEX.md:${i.reset}`);for(let p of u.nexAdded)console.log(` ${i.green}+${i.reset} ${p}`)}if(h){console.log(`${i.bold}${i.cyan}Brain documents:${i.reset}`);for(let{name:p,reason:g,action:y}of d.written){let $=y==="updated"?`${i.yellow}~${i.reset}`:`${i.green}+${i.reset}`;console.log(` ${$} ${i.bold}${p}.md${i.reset}${g?i.dim+" \u2014 "+g+i.reset:""}`)}}}console.log("")}catch(u){console.log(`${i.red}Learn failed: ${u.message}${i.reset}`)}return!0}case"/optimize":{let{getConversationMessages:n}=de(),{getUsage:r}=lt(),{TOOL_DEFINITIONS:a}=ut(),{listMemories:c}=Ft(),l=n(),u=r(l,a),d=At(),f=ln(),m=c();console.log(`
|
|
990
|
+
${i.bold}${i.cyan}Optimization Report${i.reset}
|
|
991
|
+
`);let h=u.percentage>80?i.red:u.percentage>50?i.yellow:i.green;if(console.log(`${i.bold}Context Window:${i.reset} ${h}${u.percentage}%${i.reset} used (${u.used.toLocaleString()} / ${u.limit.toLocaleString()} tokens)`),u.percentage>75?console.log(` ${i.yellow}\u2192 Tip: Use /clear to free context (auto-learns first)${i.reset}`):u.percentage>50?console.log(` ${i.dim}\u2192 Context is filling up, consider /clear soon${i.reset}`):console.log(` ${i.green}\u2192 Context healthy${i.reset}`),console.log(`
|
|
992
|
+
${i.bold}Memory:${i.reset} ${m.length} entries`),m.length===0)console.log(` ${i.yellow}\u2192 No memories yet. Use /learn after sessions or /remember key=value${i.reset}`);else{let E=[...m].sort((v,R)=>new Date(R.updatedAt)-new Date(v.updatedAt))[0],b=E?Math.round((Date.now()-new Date(E.updatedAt))/6e4):null,k=b!==null?b<60?`${b}m ago`:`${Math.round(b/60)}h ago`:"?";console.log(` ${i.dim}Latest update: ${k}${i.reset}`),m.length>30&&console.log(` ${i.yellow}\u2192 Many memories (${m.length}) \u2014 consider pruning with /forget${i.reset}`)}console.log(`
|
|
993
|
+
${i.bold}Active Model:${i.reset} ${f}:${d.id}`);let p=d.contextWindow||d.maxTokens||0;p>0&&p<32e3&&l.length>10?console.log(` ${i.yellow}\u2192 Small context window (${(p/1e3).toFixed(0)}k). Consider /model for larger context${i.reset}`):p>=128e3&&console.log(` ${i.green}\u2192 Large context window (${(p/1e3).toFixed(0)}k) \u2014 good for long sessions${i.reset}`);let g=l.filter(w=>w.role==="user").length;console.log(`
|
|
994
|
+
${i.bold}Session:${i.reset} ${g} turns, ${l.length} messages total`),g>=4&&g%10===0&&console.log(` ${i.cyan}\u2192 Good time to /learn and capture session insights${i.reset}`);let y=[],$=require("path").join(process.cwd(),"NEX.md");if(require("fs").existsSync($)||y.push("Create NEX.md in project root to give nex-code project-specific instructions"),y.length>0){console.log(`
|
|
995
|
+
${i.bold}Quick Wins:${i.reset}`);for(let w of y)console.log(` ${i.cyan}\u2192${i.reset} ${w}`)}return console.log(""),!0}case"/plan":{let{getActivePlan:n,approvePlan:r,startExecution:a,setPlanMode:c,getPlanContent:l,getPlanContent:u,formatPlan:d,extractStepsFromText:f,createPlan:m}=Ut(),{invalidateSystemPromptCache:h}=de(),p=o.join(" ").trim();if(p==="status"){let g=n();return console.log(d(g)),!0}if(p==="edit"){let g=l();if(!g)return console.log(`${i.yellow}No plan to edit. Generate a plan first with /plan${i.reset}`),!0;let y=require("os"),$=require("path").join(y.tmpdir(),`nex-plan-${Date.now()}.md`);require("fs").writeFileSync($,g,"utf-8");let w=process.env.EDITOR||process.env.VISUAL||"nano",{spawnSync:E}=require("child_process");if(console.log(`${i.dim}Opening plan in ${w}... (save and close to update)${i.reset}`),E(w,[$],{stdio:"inherit"}).status===0){let{setPlanContent:k}=Ut(),v=require("fs").readFileSync($,"utf-8");k(v);let R=f(v);if(R.length>0){let A=n()?.task||"Task";m(A,R),console.log(`${i.green}Plan updated \u2014 ${R.length} steps extracted.${i.reset}`)}else console.log(`${i.green}Plan updated.${i.reset}`)}else console.log(`${i.yellow}Editor exited with error \u2014 plan unchanged.${i.reset}`);try{require("fs").unlinkSync($)}catch{}return!0}if(p==="approve"){if(r()){a(),c(!1),h();let y=n()?.steps?.length||0,$=!!l(),w=y>0?` (${y} steps)`:"";console.log(`${i.green}${i.bold}Plan approved!${i.reset}${w} ${$?"Executing the planned steps...":"Starting execution..."}`),console.log(`${i.dim}Plan mode disabled \u2014 all tools now available.${i.reset}`)}else console.log(`${i.red}No plan to approve. Enter plan mode first with /plan${i.reset}`);return!0}return c(!0),h(),console.log(`
|
|
996
|
+
${i.cyan}${i.bold}\u250C\u2500 PLAN MODE \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510${i.reset}
|
|
997
|
+
${i.cyan}${i.bold}\u2502${i.reset} Analysis only \u2014 no file changes until approved ${i.cyan}${i.bold}\u2502${i.reset}
|
|
998
|
+
${i.cyan}${i.bold}\u2502${i.reset} ${i.dim}Read-only tools only \xB7 /plan approve to execute${i.reset} ${i.cyan}${i.bold}\u2502${i.reset}
|
|
999
|
+
${i.cyan}${i.bold}\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518${i.reset}`),p&&console.log(`${i.dim}Task: ${p}${i.reset}`),!0}case"/plans":{let{listPlans:n}=Ut(),r=n();if(r.length===0)return console.log(`${i.dim}No saved plans${i.reset}`),!0;console.log(`
|
|
1000
|
+
${i.bold}${i.cyan}Plans:${i.reset}`);for(let a of r){let c=a.status==="completed"?`${i.green}\u2713`:a.status==="executing"?`${i.blue}\u2192`:`${i.dim}\u25CB`;console.log(` ${c} ${i.reset}${i.bold}${a.name}${i.reset} \u2014 ${a.task||"?"} (${a.steps} steps, ${a.status})`)}return console.log(),!0}case"/auto":{let{getAutonomyLevel:n,setAutonomyLevel:r,AUTONOMY_LEVELS:a}=Ut(),c=o.join(" ").trim();return c?(r(c)?console.log(`${i.green}Autonomy: ${c}${i.reset}`):console.log(`${i.red}Unknown level: ${c}. Use: ${a.join(", ")}${i.reset}`),!0):(console.log(`${i.bold}${i.cyan}Autonomy:${i.reset} ${n()}`),console.log(`${i.dim}Levels: ${a.join(", ")}${i.reset}`),!0)}case"/permissions":{let{listPermissions:n}=fs(),r=n();console.log(`
|
|
1001
|
+
${i.bold}${i.cyan}Tool Permissions:${i.reset}`);for(let a of r){let c=a.mode==="allow"?`${i.green}\u2713`:a.mode==="deny"?`${i.red}\u2717`:`${i.yellow}?`;console.log(` ${c} ${i.reset}${i.bold}${a.tool}${i.reset} ${i.dim}(${a.mode})${i.reset}`)}return console.log(`
|
|
1002
|
+
${i.dim}Use /allow <tool> or /deny <tool> to change${i.reset}
|
|
1003
|
+
`),!0}case"/allow":{let{setPermission:n,savePermissions:r}=fs(),a=o.join(" ").trim();return a?(n(a,"allow"),r(),console.log(`${i.green}${a}: allow${i.reset}`),!0):(console.log(`${i.red}Usage: /allow <tool>${i.reset}`),!0)}case"/deny":{let{setPermission:n,savePermissions:r}=fs(),a=o.join(" ").trim();return a?(n(a,"deny"),r(),console.log(`${i.red}${a}: deny${i.reset}`),!0):(console.log(`${i.red}Usage: /deny <tool>${i.reset}`),!0)}case"/audit":{let{getAuditSummary:n,isAuditEnabled:r}=ti();if(!r())return console.log(`${i.yellow}Audit logging is disabled (set NEX_AUDIT=true to enable)${i.reset}`),!0;let a=parseInt(o.join(" ").trim())||1,c=n(a);if(console.log(`
|
|
1004
|
+
${i.bold}${i.cyan}Audit Summary (${a} day${a>1?"s":""})${i.reset}
|
|
1005
|
+
`),console.log(` Total tool calls: ${i.bold}${c.totalCalls}${i.reset}`),console.log(` Avg duration: ${i.dim}${c.avgDuration}ms${i.reset}`),console.log(` Success rate: ${c.successRate>=.95?i.green:i.yellow}${Math.round(c.successRate*100)}%${i.reset}`),Object.keys(c.byTool).length>0){console.log(`
|
|
1006
|
+
${i.dim}Tool${" ".repeat(25)}Count${i.reset}`),console.log(` ${i.dim}${"\u2500".repeat(35)}${i.reset}`);let l=Object.entries(c.byTool).sort((u,d)=>d[1]-u[1]);for(let[u,d]of l.slice(0,15))console.log(` ${u.padEnd(30)}${d}`)}return console.log(),!0}case"/commit":{let{isGitRepo:n,commit:r,analyzeDiff:a,formatDiffSummary:c}=Xt(),{confirm:l}=Ie();if(!n())return console.log(`${i.red}Not a git repository${i.reset}`),!0;let u=o.join(" ").trim();if(u){let p=await r(u);return console.log(p?`${i.green}Committed: ${p} \u2014 ${u}${i.reset}`:`${i.red}Commit failed${i.reset}`),!0}if(!a())return console.log(`${i.yellow}No changes to commit${i.reset}`),!0;let f=await c();if(console.log(f),!await l(" Commit changes?"))return!0;let h=await r("nex-code update");return h&&console.log(`${i.green} \u2713 Committed: ${h}${i.reset}`),!0}case"/diff":{let{isGitRepo:n,formatDiffSummary:r}=Xt();return n()?(console.log(r()),!0):(console.log(`${i.red}Not a git repository${i.reset}`),!0)}case"/review":{let{isGitRepo:n,getDiff:r}=Xt(),{processInput:a}=de(),c=o.join(" ").trim(),l=c.includes("--strict"),u=c.replace("--strict","").trim(),f=`## Review Protocol
|
|
1007
1007
|
|
|
1008
1008
|
**Phase 1 \u2014 Broad Scan:** Read the target code and identify all issues at a high level.
|
|
1009
1009
|
|
|
@@ -1040,73 +1040,73 @@ For each issue, include:
|
|
|
1040
1040
|
|
|
1041
1041
|
\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}\`.
|
|
1042
1042
|
|
|
1043
|
-
${f}`;else{if(!n())return console.log(`${
|
|
1043
|
+
${f}`;else{if(!n())return console.log(`${i.red}Not a git repository \u2014 try /review <file>${i.reset}`),!0;let[h,p]=await Promise.all([r(!1),r(!0)]),g=p||h;if(!g||!g.trim())return console.log(`${i.yellow}No changes to review \u2014 commit something or specify a file: /review <file>${i.reset}`),!0;m=`Review the following code diff.
|
|
1044
1044
|
|
|
1045
1045
|
${f}
|
|
1046
1046
|
|
|
1047
1047
|
\`\`\`diff
|
|
1048
1048
|
${g.substring(0,2e4)}
|
|
1049
|
-
\`\`\``}return await
|
|
1050
|
-
${
|
|
1051
|
-
${
|
|
1052
|
-
`),!0}case"/hooks":{let{listHooks:n}=_i(),r=n();if(r.length===0)return console.log(`${
|
|
1053
|
-
${
|
|
1054
|
-
${
|
|
1055
|
-
${
|
|
1056
|
-
`),!0}case"/install-skill":{let n=o.join(" ").trim();if(!n)return console.log(`${
|
|
1057
|
-
${
|
|
1058
|
-
`);for(let c of
|
|
1059
|
-
`))}return!0}case"/remove-skill":{let n=o.join(" ").trim();if(!n)return console.log(`${
|
|
1049
|
+
\`\`\``}return await a(m),!0}case"/branch":{let{isGitRepo:n,getCurrentBranch:r,createBranch:a}=Xt();if(!n())return console.log(`${i.red}Not a git repository${i.reset}`),!0;let c=o.join(" ").trim();if(!c){let u=r();return console.log(`${i.bold}${i.cyan}Branch:${i.reset} ${u||"(detached)"}`),!0}let l=a(c);return console.log(l?`${i.green}Created and switched to: ${l}${i.reset}`:`${i.red}Failed to create branch${i.reset}`),!0}case"/mcp":{let{listServers:n,connectAll:r,disconnectAll:a}=Ks(),c=o.join(" ").trim();if(c==="connect")return console.log(`${i.dim}Connecting MCP servers...${i.reset}`),r().then(u=>{for(let d of u)d.error?console.log(` ${i.red}\u2717${i.reset} ${d.name}: ${d.error}`):console.log(` ${i.green}\u2713${i.reset} ${d.name}: ${d.tools} tools`);u.length===0&&console.log(`${i.dim}No MCP servers configured in .nex/config.json${i.reset}`)}).catch(u=>{console.log(`${i.red}MCP connection error: ${u.message}${i.reset}`)}),!0;if(c==="disconnect")return a(),console.log(`${i.green}All MCP servers disconnected${i.reset}`),!0;let l=n();if(l.length===0)return console.log(`${i.dim}No MCP servers configured${i.reset}`),console.log(`${i.dim}Add servers to .nex/config.json under "mcpServers"${i.reset}`),!0;console.log(`
|
|
1050
|
+
${i.bold}${i.cyan}MCP Servers:${i.reset}`);for(let u of l){let d=u.connected?`${i.green}\u2713 connected${i.reset}`:`${i.dim}\u25CB disconnected${i.reset}`;console.log(` ${d} ${i.bold}${u.name}${i.reset} (${u.command}) \u2014 ${u.toolCount} tools`)}return console.log(`
|
|
1051
|
+
${i.dim}Use /mcp connect to connect all servers${i.reset}
|
|
1052
|
+
`),!0}case"/hooks":{let{listHooks:n}=_i(),r=n();if(r.length===0)return console.log(`${i.dim}No hooks configured${i.reset}`),console.log(`${i.dim}Add hooks to .nex/config.json or .nex/hooks/${i.reset}`),!0;console.log(`
|
|
1053
|
+
${i.bold}${i.cyan}Hooks:${i.reset}`);for(let a of r){console.log(` ${i.cyan}${a.event}${i.reset}`);for(let c of a.commands)console.log(` ${i.dim}\u2192 ${c}${i.reset}`)}return console.log(),!0}case"/skills":{let{listSkills:n,enableSkill:r,disableSkill:a}=Lt(),c=o.join(" ").trim();if(c.startsWith("enable ")){let u=c.substring(7).trim();return r(u)?console.log(`${i.green}Skill enabled: ${u}${i.reset}`):console.log(`${i.red}Skill not found: ${u}${i.reset}`),!0}if(c.startsWith("disable ")){let u=c.substring(8).trim();return a(u)?console.log(`${i.yellow}Skill disabled: ${u}${i.reset}`):console.log(`${i.red}Skill not found: ${u}${i.reset}`),!0}let l=n();if(l.length===0)return console.log(`${i.dim}No skills loaded${i.reset}`),console.log(`${i.dim}Add .md or .js files to .nex/skills/${i.reset}`),!0;console.log(`
|
|
1054
|
+
${i.bold}${i.cyan}Skills:${i.reset}`);for(let u of l){let d=u.enabled?`${i.green}\u2713${i.reset}`:`${i.red}\u2717${i.reset}`,f=u.type==="prompt"?`${i.dim}(prompt)${i.reset}`:`${i.dim}(script)${i.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} ${i.bold}${u.name}${i.reset} ${f}${h}`)}return console.log(`
|
|
1055
|
+
${i.dim}Use /skills enable <name> or /skills disable <name>${i.reset}
|
|
1056
|
+
`),!0}case"/install-skill":{let n=o.join(" ").trim();if(!n)return console.log(`${i.yellow}Usage: /install-skill <git-url-or-user/repo>${i.reset}`),!0;let{installSkill:r}=Lt();console.log(`${i.dim}Installing skill from ${n}...${i.reset}`);let a=await r(n);return a.ok?(console.log(`${i.green}Skill "${a.name}" installed successfully${i.reset}`),console.log(`${i.dim}Reload with /skills to see it${i.reset}`)):console.log(`${i.red}Failed: ${a.error}${i.reset}`),!0}case"/search-skill":{let n=o.join(" ").trim();if(!n)return console.log(`${i.yellow}Usage: /search-skill <query>${i.reset}`),!0;let{searchSkills:r}=Lt();console.log(`${i.dim}Searching for "${n}"...${i.reset}`);let a=await r(n);if(a.length===0)console.log(`${i.yellow}No skills found matching "${n}"${i.reset}`);else{console.log(`
|
|
1057
|
+
${i.bold}Skills matching "${n}":${i.reset}
|
|
1058
|
+
`);for(let c of a)c.name==="error"?console.log(` ${i.red}${c.description}${i.reset}`):(console.log(` ${i.cyan}${c.owner}/${c.name}${i.reset} ${i.dim}\u2605${c.stars}${i.reset}`),console.log(` ${c.description}`),console.log(` ${i.dim}/install-skill ${c.url}${i.reset}
|
|
1059
|
+
`))}return!0}case"/remove-skill":{let n=o.join(" ").trim();if(!n)return console.log(`${i.yellow}Usage: /remove-skill <name>${i.reset}`),!0;let{removeSkill:r}=Lt(),a=r(n);return a.ok?console.log(`${i.green}Skill "${n}" removed${i.reset}`):console.log(`${i.red}${a.error}${i.reset}`),!0}case"/tasks":{let{renderTaskList:n,clearTasks:r}=io();return o.join(" ").trim()==="clear"?(r(),console.log(`${i.green}Tasks cleared${i.reset}`),!0):(console.log(`
|
|
1060
1060
|
`+n()+`
|
|
1061
|
-
`),!0)}case"/undo":{let{undo:n,getUndoCount:r}=_t(),
|
|
1062
|
-
${
|
|
1063
|
-
`);for(let l of c){let u=new Date(l.timestamp).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});console.log(` ${
|
|
1064
|
-
${
|
|
1065
|
-
`),!0}case"/snapshot":{let{createSnapshot:n,listSnapshots:r}=_t(),
|
|
1066
|
-
${
|
|
1067
|
-
${
|
|
1068
|
-
${
|
|
1069
|
-
`)}return!0}let c=n(
|
|
1070
|
-
${
|
|
1061
|
+
`),!0)}case"/undo":{let{undo:n,getUndoCount:r}=_t(),a=n();if(!a)return console.log(`${i.yellow}Nothing to undo${i.reset}`),!0;a.wasCreated?console.log(`${i.green}Undone: deleted ${a.filePath} (was created by ${a.tool})${i.reset}`):console.log(`${i.green}Undone: restored ${a.filePath} (${a.tool})${i.reset}`);let c=r();return c>0&&console.log(`${i.dim}${c} more change(s) to undo${i.reset}`),!0}case"/redo":{let{redo:n,getRedoCount:r}=_t(),a=n();if(!a)return console.log(`${i.yellow}Nothing to redo${i.reset}`),!0;console.log(`${i.green}Redone: ${a.filePath} (${a.tool})${i.reset}`);let c=r();return c>0&&console.log(`${i.dim}${c} more change(s) to redo${i.reset}`),!0}case"/history":{let{getHistory:n,getUndoCount:r,getRedoCount:a}=_t(),c=n(20);if(c.length===0)return console.log(`${i.dim}No file changes in this session${i.reset}`),!0;console.log(`
|
|
1062
|
+
${i.bold}File Change History${i.reset}
|
|
1063
|
+
`);for(let l of c){let u=new Date(l.timestamp).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});console.log(` ${i.dim}${u}${i.reset} ${i.yellow}${l.tool}${i.reset} ${l.filePath}`)}return console.log(`
|
|
1064
|
+
${i.dim}${r()} undo / ${a()} redo available${i.reset}
|
|
1065
|
+
`),!0}case"/snapshot":{let{createSnapshot:n,listSnapshots:r}=_t(),a=o.join(" ").trim()||void 0;if(a==="list"){let l=r(ht);if(l.length===0)console.log(`${i.dim}No snapshots found${i.reset}`);else{console.log(`
|
|
1066
|
+
${i.bold}${i.cyan}Snapshots:${i.reset}`);for(let u of l)console.log(` ${i.cyan}#${u.index}${i.reset} ${i.bold}${u.shortName}${i.reset}`);console.log()}return!0}let c=n(a,ht);return c.ok?(console.log(`${i.green}Snapshot created:${i.reset} ${c.label}`),console.log(`${i.dim}Use /restore to apply it later${i.reset}`)):console.log(`${i.yellow}${c.error}${i.reset}`),!0}case"/restore":{let{restoreSnapshot:n,listSnapshots:r}=_t(),a=o.join(" ").trim()||"last";if(a==="list"){let l=r(ht);if(l.length===0)console.log(`${i.dim}No snapshots available${i.reset}`);else{console.log(`
|
|
1067
|
+
${i.bold}${i.cyan}Available snapshots:${i.reset}`);for(let u of l)console.log(` ${i.cyan}#${u.index}${i.reset} ${i.bold}${u.shortName}${i.reset}`);console.log(`
|
|
1068
|
+
${i.dim}Usage: /restore <name|last>${i.reset}
|
|
1069
|
+
`)}return!0}let c=n(a,ht);return c.ok?(console.log(`${i.green}Restored snapshot:${i.reset} ${c.label}`),console.log(`${i.dim}Working tree updated. Use /undo for in-session file undos.${i.reset}`)):(console.log(`${i.red}Restore failed:${i.reset} ${c.error}`),console.log(`${i.dim}Use /snapshot list to see available snapshots${i.reset}`)),!0}case"/k8s":{let n=o.join(" ").trim(),{exec:r}=require("child_process"),{promisify:a}=require("util"),c=a(r),l=n||null,u=l?`ssh -o ConnectTimeout=10 -o BatchMode=yes ${l.replace(/[^a-zA-Z0-9@._-]/g,"")} `:"",d=f=>l?`${u}"${f.replace(/"/g,'\\"')}"`:f;console.log(`
|
|
1070
|
+
${i.bold}${i.cyan}Kubernetes Overview${i.reset}${l?i.dim+" (remote: "+l+")"+i.reset:""}
|
|
1071
1071
|
`);try{let{stdout:f}=await c(d("kubectl get namespaces --no-headers -o custom-columns=NAME:.metadata.name"),{timeout:15e3}),m=f.trim().split(`
|
|
1072
|
-
`).filter(Boolean);console.log(`${
|
|
1072
|
+
`).filter(Boolean);console.log(`${i.bold}Namespaces (${m.length}):${i.reset}`);for(let h of m)console.log(` ${i.cyan}${h}${i.reset}`);console.log()}catch{return console.log(`${i.dim}Could not reach cluster \u2014 is kubectl configured?${i.reset}
|
|
1073
1073
|
`),!0}try{let{stdout:f}=await c(d("kubectl get pods -A --no-headers -o custom-columns=NS:.metadata.namespace,NAME:.metadata.name,READY:.status.containerStatuses[0].ready,STATUS:.status.phase,RESTARTS:.status.containerStatuses[0].restartCount"),{timeout:2e4}),m=f.trim().split(`
|
|
1074
|
-
`).filter(Boolean),h=m.filter($=>$.includes("Running")).length,p=m.filter($=>$.includes("Pending")).length,g=m.filter($=>$.includes("Failed")||$.includes("Error")||$.includes("CrashLoop")).length;console.log(`${
|
|
1075
|
-
`);let y=m.filter($=>!$.includes("Running")&&!$.includes("<none>"));if(y.length>0){console.log(`${
|
|
1076
|
-
`)}catch(f){console.log(`${
|
|
1077
|
-
`)}return!0}case"/servers":{let{loadServerProfiles:n,resolveProfile:r,sshExec:
|
|
1078
|
-
${
|
|
1074
|
+
`).filter(Boolean),h=m.filter($=>$.includes("Running")).length,p=m.filter($=>$.includes("Pending")).length,g=m.filter($=>$.includes("Failed")||$.includes("Error")||$.includes("CrashLoop")).length;console.log(`${i.bold}Pods: ${m.length} total ${i.green}${h} running${i.reset} ${i.yellow}${p} pending${i.reset} ${i.red}${g} unhealthy${i.reset}
|
|
1075
|
+
`);let y=m.filter($=>!$.includes("Running")&&!$.includes("<none>"));if(y.length>0){console.log(`${i.bold}${i.red}Unhealthy Pods:${i.reset}`);for(let $ of y)console.log(` ${i.red}${$}${i.reset}`);console.log()}console.log(`${i.dim}Use k8s_pods / k8s_logs / k8s_exec tools for details${i.reset}`),console.log(`${i.dim}Or: /k8s user@host to query a remote cluster${i.reset}
|
|
1076
|
+
`)}catch(f){console.log(`${i.dim}Could not list pods: ${f.message}${i.reset}
|
|
1077
|
+
`)}return!0}case"/servers":{let{loadServerProfiles:n,resolveProfile:r,sshExec:a}=kn(),c=n(),l=Object.keys(c);if(l.length===0)return console.log(`
|
|
1078
|
+
${i.dim}No servers configured. Create .nex/servers.json:${i.reset}`),console.log(`${i.dim} { "prod": { "host": "1.2.3.4", "user": "jarvis", "os": "almalinux9" } }${i.reset}
|
|
1079
1079
|
`),!0;if(o[0]==="ping"){let f=o[1]?[o[1]]:l;return console.log(`
|
|
1080
|
-
${
|
|
1081
|
-
${
|
|
1082
|
-
${
|
|
1083
|
-
`),!0}case"/docker":{let{loadServerProfiles:n,sshExec:r}=kn(),{exec:
|
|
1084
|
-
${
|
|
1085
|
-
`).forEach(y=>console.log(` ${
|
|
1086
|
-
${
|
|
1087
|
-
${
|
|
1080
|
+
${i.bold}${i.cyan}Server connectivity:${i.reset}`),await Promise.all(f.map(async m=>{if(!c[m]){console.log(` ${i.red}\u2717${i.reset} ${m} \u2014 unknown profile`);return}try{let h={...c[m],_name:m},{exitCode:p}=await a(h,"echo ok",{timeout:8e3});console.log(p===0?` ${i.green}\u2713${i.reset} ${m} (${h.user?h.user+"@":""}${h.host})`:` ${i.red}\u2717${i.reset} ${m} (${h.host}) \u2014 SSH failed (exit ${p})`)}catch(h){console.log(` ${i.red}\u2717${i.reset} ${m} \u2014 ${h.message}`)}})),console.log(""),!0}let{formatProfile:d}=kn();console.log(`
|
|
1081
|
+
${i.bold}${i.cyan}Configured servers (${l.length}):${i.reset}`);for(let f of l)console.log(` ${i.green}${f}${i.reset} ${i.dim}${d(f,c[f])}${i.reset}`);return console.log(`
|
|
1082
|
+
${i.dim}/servers ping \u2014 check SSH connectivity for all servers${i.reset}`),console.log(`${i.dim}/servers ping <name> \u2014 check a specific server${i.reset}
|
|
1083
|
+
`),!0}case"/docker":{let{loadServerProfiles:n,sshExec:r}=kn(),{exec:a}=require("child_process"),{promisify:c}=require("util"),l=c(a),u=o[0]==="-a"||o[0]==="--all"?'docker ps -a --format "table {{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}"':'docker ps --format "table {{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}"',d=n(),f=[["local",null],...Object.entries(d)];console.log(`
|
|
1084
|
+
${i.bold}${i.cyan}Docker Containers:${i.reset}`);for(let[m,h]of f){let p=m==="local"?`${i.dim}local${i.reset}`:`${i.cyan}${m}${i.reset}`;try{let g;if(m==="local"){let{stdout:y}=await l(u,{timeout:8e3});g=(y||"").trim()}else{let y=await r(h,u,{timeout:1e4});if(g=[y.stdout,y.stderr].filter(Boolean).join("").trim(),y.exitCode!==0){console.log(` ${p}: ${i.red}SSH error (${y.exitCode})${i.reset}`);continue}}!g||g==="NAMES IMAGE STATUS PORTS"?console.log(` ${p}: ${i.dim}(no containers)${i.reset}`):(console.log(` ${p}:`),g.split(`
|
|
1085
|
+
`).forEach(y=>console.log(` ${i.dim}${y}${i.reset}`)))}catch(g){console.log(` ${p}: ${i.red}${g.message}${i.reset}`)}}return console.log(""),!0}case"/deploy":{let{loadDeployConfigs:n}=Ur(),r=n(),a=Object.keys(r),c=o[0];if(c&&a.includes(c)){let l=o.includes("--dry-run")||o.includes("-n"),u=r[c],{executeTool:d}=ut();console.log(`
|
|
1086
|
+
${i.bold}Running deploy: ${c}${l?" (dry run)":""}${i.reset}`);let f=await d("deploy",{...u,dry_run:l});return console.log(f),!0}if(a.length===0)return console.log(`
|
|
1087
|
+
${i.dim}No deploy configs. Run /init to create .nex/deploy.json${i.reset}
|
|
1088
1088
|
`),!0;console.log(`
|
|
1089
|
-
${
|
|
1090
|
-
${
|
|
1091
|
-
`),!0}case"/init":{let{runServerWizard:n,runDeployWizard:r,setWizardRL:
|
|
1092
|
-
${
|
|
1093
|
-
`),console.log(` ${
|
|
1094
|
-
${
|
|
1095
|
-
${
|
|
1096
|
-
`);break}console.log(`${
|
|
1097
|
-
`);let A=require("os"),j=Ee.join(A.homedir(),".nex-code","benchmark-results.json"),Q=[];try{
|
|
1098
|
-
`),X=et,process.stdout.write(`${
|
|
1099
|
-
`);try{
|
|
1100
|
-
${
|
|
1089
|
+
${i.bold}${i.cyan}Deploy configs (${a.length}):${i.reset}`);for(let[l,u]of Object.entries(r)){let d=u.method||"rsync",f=`[${d}]`,m=d==="git"?`${u.server}:${u.remote_path}${u.branch?` (${u.branch})`:""}`:`${u.local_path||""} \u2192 ${u.server}:${u.remote_path}`,h=[u.deploy_script?`script: ${u.deploy_script}`:null,u.health_check?`health: ${u.health_check}`:null].filter(Boolean).map(p=>` ${i.dim}\u2192 ${p}${i.reset}`).join("");console.log(` ${i.green}${l}${i.reset} ${i.dim}${f} ${m}${i.reset}${h}`)}return console.log(`
|
|
1090
|
+
${i.dim}/deploy <name> \u2014 run a named deploy${i.reset}`),console.log(`${i.dim}/deploy <name> --dry-run \u2014 preview without syncing${i.reset}
|
|
1091
|
+
`),!0}case"/init":{let{runServerWizard:n,runDeployWizard:r,setWizardRL:a}=Xd();return a(e),o[0]==="deploy"?await r():await n(),!0}case"/setup":{let{runSetupWizard:n}=ji();return await n({rl:e,force:!0}),!0}case"/benchmark":{if(o.includes("--history")){let y=require("os"),$=Ee.join(y.homedir(),"Coding","nex-code-benchmarks","results");if(!qe.existsSync($)){console.log(`${i.yellow}No nightly results at ${$}${i.reset}`),console.log(`${i.dim}Use /benchmark (no flags) to run a live model comparison.${i.reset}`);break}let w=qe.readdirSync($).filter(b=>b.endsWith(".json")).sort().slice(-7);if(w.length===0){console.log(`${i.yellow}No result files found${i.reset}`);break}console.log(`
|
|
1092
|
+
${i.bold}${i.cyan}OpenClaw Nightly Results (${w.length}-day trend)${i.reset}
|
|
1093
|
+
`),console.log(` ${i.dim}${"Date".padEnd(12)} ${"Model".padEnd(25)} ${"Score".padEnd(8)} ${"Pass".padEnd(8)}${i.reset}`),console.log(` ${i.dim}${"\u2500".repeat(58)}${i.reset}`);let E=[];for(let b of w)try{let k=JSON.parse(qe.readFileSync(Ee.join($,b),"utf-8")),v=b.replace(".json",""),R=k.tasks?.length||k.total||0,C=k.tasks?.filter(X=>X.passed||X.score>=.7)?.length||k.passed||0,A=k.score??k.overall_score??(R>0?Math.round(C/R*100):"N/A"),j=k.model||k.config?.model||"unknown";E.push({date:v,model:j,total:R,passed:C,score:A});let Q=typeof A=="number"?A>=80?i.green:A>=60?i.yellow:i.red:i.dim;console.log(` ${v.padEnd(12)} ${j.substring(0,24).padEnd(25)} ${Q}${String(A).padEnd(8)}${i.reset} ${C}/${R}`)}catch{}if(E.length>=2){let b=E[0].score,k=E[E.length-1].score;if(typeof b=="number"&&typeof k=="number"){let v=k-b,R=v>0?`${i.green}\u25B2 +${v}`:v<0?`${i.red}\u25BC ${v}`:`${i.dim}\u2192 stable`;console.log(`
|
|
1094
|
+
${i.bold}Trend:${i.reset} ${R}${i.reset} over ${E.length} days`)}}console.log();break}if(o.includes("--discover")){let{findNewModels:y,markBenchmarked:$,updateReadme:w,updateModelsEnv:E}=Bo(),{runDiscoverBenchmark:b,buildSummary:k}=_s();console.log(`
|
|
1095
|
+
${i.bold}Checking Ollama Cloud for new models...${i.reset}`);let v;try{v=await y()}catch(et){console.log(`${i.red}Discovery failed: ${et.message}${i.reset}`);break}let{newModels:R,allCloud:C}=v;if(console.log(`${i.dim}${C.length} models available on cloud${i.reset}`),R.length===0){console.log(`${i.green}No new models since last benchmark run.${i.reset}
|
|
1096
|
+
`);break}console.log(`${i.cyan}New models to benchmark (${R.length}):${i.reset} ${R.join(", ")}
|
|
1097
|
+
`);let A=require("os"),j=Ee.join(A.homedir(),".nex-code","benchmark-results.json"),Q=[];try{qe.existsSync(j)&&(Q=JSON.parse(qe.readFileSync(j,"utf-8")))}catch{}let X="",H=await b({newModels:R,existingRanking:Q,onProgress:({model:et,task:vs,done:N,score:D,error:K})=>{if(!N){et!==X&&(X&&process.stdout.write(`
|
|
1098
|
+
`),X=et,process.stdout.write(`${i.cyan}${et}${i.reset} `));return}let W=K?`${i.red}\u2717${i.reset}`:D>=80?`${i.green}\xB7${i.reset}`:D>=40?`${i.yellow}\xB7${i.reset}`:`${i.red}\xB7${i.reset}`;process.stdout.write(W)}});X&&process.stdout.write(`
|
|
1099
|
+
`);try{qe.writeFileSync(j,JSON.stringify(H,null,2))}catch{}$(C);let G=Ee.join(process.cwd(),"README.md"),U=w(H,G),pe=E(H),{buildCategoryWinners:Te}=_s(),{updateRoutingConfig:ve}=Bo(),Me=Te(H),Ae=ve(Me);if(U&&console.log(`${i.green}README.md benchmark table updated${i.reset}`),pe.updated?console.log(`${i.green}DEFAULT_MODEL: ${pe.previousModel} \u2192 ${pe.newModel}${i.reset}`):pe.reason&&console.log(`${i.dim}models.env unchanged: ${pe.reason}${i.reset}`),Ae.changes.length>0){console.log(`${i.green}Routing updated:${i.reset}`);for(let et of Ae.changes)console.log(` ${i.dim}${et}${i.reset}`)}return console.log(),!0}let{runBenchmark:n,DEFAULT_MODELS:r,QUICK_MODELS:a}=_s(),c=o.includes("--quick"),l=o.find(y=>y.startsWith("--models=")),u=l?l.replace("--models=","").split(",").map(y=>y.trim()).filter(Boolean):[],d=c?7:15,f=u.length>0?u:c?a:r;console.log(`
|
|
1100
|
+
${i.bold}Starting benchmark${i.reset} ${i.dim}${d} tasks \xB7 ${f.length} models \xB7 ollama cloud${i.reset}`),console.log(`${i.dim}Models: ${f.join(", ")}${i.reset}
|
|
1101
1101
|
`);let m="",h=0,p=d*f.length,g=await n({models:f,quick:c,onProgress:({model:y,task:$,done:w,score:E,error:b})=>{if(!w){y!==m&&(m&&process.stdout.write(`
|
|
1102
|
-
`),m=y,process.stdout.write(`${
|
|
1102
|
+
`),m=y,process.stdout.write(`${i.cyan}${y}${i.reset} `));return}h++;let k=b?`${i.red}\u2717${i.reset}`:E>=80?`${i.green}\xB7${i.reset}`:E>=40?`${i.yellow}\xB7${i.reset}`:`${i.red}\xB7${i.reset}`;process.stdout.write(k)}});if(m&&process.stdout.write(`
|
|
1103
1103
|
`),!c&&g&&g.length>0){let{buildCategoryWinners:y}=_s(),{updateRoutingConfig:$,updateReadme:w,updateModelsEnv:E}=Bo(),b=y(g),k=$(b);if(k.changes.length>0){console.log(`
|
|
1104
|
-
${
|
|
1105
|
-
`).filter(Boolean).slice(-ea)}catch{}return[]}function Go(t){try{let e=ta(),s=Ee.dirname(e);
|
|
1106
|
-
`)}catch{}}function Ze(){let{isPlanMode:t,getAutonomyLevel:e}=Ut(),s=[];t()&&s.push("plan");let o=e();return o!=="interactive"&&s.push(o),`${s.length>0?`${
|
|
1107
|
-
`),!0):!1)(),c=(async()=>{if(process.env.NEX_DISABLE_UPDATE_CHECK==="1")return{hasNewVersion:!1};try{let{checkForNewVersion:N}=
|
|
1108
|
-
${
|
|
1109
|
-
`),process.exit(1));let{loadPersistedHistory:f,pruneHistory:m}=_t();f().then(N=>{N>0&&console.log(`${
|
|
1104
|
+
${i.bold}Per-category routing saved:${i.reset}`);for(let A of k.changes)console.log(` ${i.dim}${A}${i.reset}`)}let v=Ee.join(process.cwd(),"README.md");w(g,v)&&console.log(`${i.green}README.md updated${i.reset}`),E(g);let R=require("os"),C=Ee.join(R.homedir(),".nex-code","benchmark-results.json");try{qe.writeFileSync(C,JSON.stringify(g,null,2))}catch{}}return!0}case"/exit":case"/quit":process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J"),process.exit(0);default:return Sb(t)||console.log(`${i.red}Unknown command: ${s}. Type /help${i.reset}`),!0}}var ea=1e3;function ta(){return Ee.join(process.cwd(),".nex","repl_history")}function vf(){try{let t=ta();if(qe.existsSync(t))return qe.readFileSync(t,"utf-8").split(`
|
|
1105
|
+
`).filter(Boolean).slice(-ea)}catch{}return[]}function Go(t){try{let e=ta(),s=Ee.dirname(e);qe.existsSync(s)||qe.mkdirSync(s,{recursive:!0}),qe.appendFileSync(e,t+`
|
|
1106
|
+
`)}catch{}}function Ze(){let{isPlanMode:t,getAutonomyLevel:e}=Ut(),s=[];t()&&s.push("plan");let o=e();return o!=="interactive"&&s.push(o),`${s.length>0?`${i.dim}[${s.join(" \xB7 ")}]${i.reset} `:""}${i.bold}${i.cyan}>${i.reset} `}var na="\x1B[200~",sa="\x1B[201~";function Cb(t){return typeof t=="string"&&t.includes(na)}function Ab(t){return typeof t=="string"&&t.includes(sa)}function xs(t){return typeof t!="string"?t:t.split(na).join("").split(sa).join("")}async function Ob(){if(!xb("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"),Qi("local:llama3"),!0}catch{return!1}}async function Nb(){let{setAbortSignalGetter:t,getConversationLength:e,processInput:s}=de();t($f);let n=Vi().some(N=>N.configured),r=(async()=>{vb();let N=At(),D=ln();return{model:N,providerName:D}})(),a=(async()=>n?!0:await Ob()?(console.log(`${i.green}\u2713 Local Ollama detected \u2014 using local models${i.reset}`),console.log(`${i.dim}Tip: Set API keys for cloud providers for more model options (OPENAI_API_KEY, ANTHROPIC_API_KEY, etc.)${i.reset}
|
|
1107
|
+
`),!0):!1)(),c=(async()=>{if(process.env.NEX_DISABLE_UPDATE_CHECK==="1")return{hasNewVersion:!1};try{let{checkForNewVersion:N}=ff();return await N()}catch{return{hasNewVersion:!1}}})(),[l,u,d]=await Promise.all([r,a,c]);!u&&!n&&(console.error(`
|
|
1108
|
+
${i.red}\u2717 No provider configured and no local Ollama detected.${i.reset}
|
|
1109
|
+
`),process.exit(1));let{loadPersistedHistory:f,pruneHistory:m}=_t();f().then(N=>{N>0&&console.log(`${i.dim}Loaded ${N} undo entries from previous session${i.reset}`)}),m().catch(()=>{});let h=vf(),p=yb.createInterface({input:process.stdin,output:process.stdout,prompt:Ze(),completer:bf,history:h,historySize:ea});Eb(p);let{setAskUserHandler:g}=ut();g(async(N,D)=>{let K="\x1B[0m",W="\x1B[1m",B="\x1B[2m",re="\x1B[36m";return process.stdout.write(`
|
|
1110
1110
|
${W}\x1B[33m\u2753${K} ${W}${N}${K}
|
|
1111
1111
|
|
|
1112
1112
|
`),D.forEach((z,te)=>{process.stdout.write(` ${re}${te+1}${K} ${z}
|
|
@@ -1118,9 +1118,9 @@ ${a.red}\u2717 No provider configured and no local Ollama detected.${a.reset}
|
|
|
1118
1118
|
`),Oe(),z(D[ye-1])):(ye===D.length+1||Ye==="\r"||Ye===`
|
|
1119
1119
|
`)&&(process.stdout.write(`
|
|
1120
1120
|
`),process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.removeListener("data",te),process.stdout.write(` ${re}\u203A${K} `),p.resume(),p.once("line",xe=>{process.stdout.write(`
|
|
1121
|
-
`),z(xe.trim()||"")}))};function Oe(){process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.removeListener("data",te),p.resume()}process.stdin.on("data",te)})});let y=new
|
|
1122
|
-
`),await
|
|
1123
|
-
${
|
|
1121
|
+
`),z(xe.trim()||"")}))};function Oe(){process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.removeListener("data",te),p.resume()}process.stdin.on("data",te)})});let y=new Rb;y.activate(p),global._nexFooter=y,process.stdout.isTTY&&process.stdout.write("\x1B[H\x1B[2J\x1B[3J");let $=l.providerName==="ollama"?l.model.id:`${l.providerName}:${l.model.id}`;wb($,ht,{yolo:gf()});{y.setStatusInfo({model:$,branch:"",project:Ee.basename(ht)});let{execFile:N}=require("child_process");N("git",["rev-parse","--abbrev-ref","HEAD"],{encoding:"utf8"},(D,K)=>{!D&&K&&y.setStatusInfo({model:$,branch:K.trim(),project:Ee.basename(ht)})})}d.hasNewVersion&&console.log(`${i.yellow}\u{1F4A1} New version available!${i.reset} Run ${i.cyan}npm update -g nex-code${i.reset} to upgrade from ${i.dim}${d.currentVersion}${i.reset} to ${i.green}${d.latestVersion}${i.reset}
|
|
1122
|
+
`),await hf(ht);let w=!1,E=0,b=!1,k=null;function v(){mf(),y.deactivate(),pf(),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",v),process.on("exit",()=>{mf()}),p.on("SIGINT",()=>{if(pf(),E++,E>=2){v();return}if(w){Ct&&Ct.abort();let{cancelPendingAskUser:N}=ut();N(),console.log(`
|
|
1123
|
+
${i.yellow} Task cancelled. Press Ctrl+C again to exit.${i.reset}`),w=!1,p.setPrompt(Ze()),p.prompt()}else console.log(`${i.dim} (Press Ctrl+C again to exit)${i.reset}`),p.setPrompt(Ze()),p.prompt(),k&&clearTimeout(k),k=setTimeout(()=>{E=0,k=null},2e3)}),process.on("SIGINT",()=>{process.stdin.isTTY?(E++,E>=2&&v()):v()});let R=!1,C=[],A=0,j={},Q=!1;function X(){let N=C.join(`
|
|
1124
1124
|
`).replace(/\r/g,"").trim();if(C=[],R=!1,!N)return!0;A++,Q=!0;let D=A;j[D]=N;let K=N.split(`
|
|
1125
1125
|
`).length,W=K>1?`[Pasted content #${D} \u2014 ${K} lines]`:`[Pasted content #${D}]`,B=p.line||"",re=B&&!B.endsWith(" ")?" ":"",Z=B+re+W;return p.setPrompt(Ze()),p.prompt(),p.line=Z,p.cursor=Z.length,p._refreshLine(),!0}function H(N){return N.replace(/\[Pasted content #(\d+)(?:[^\]]*)\]/g,(D,K)=>j[Number(K)]||"")}function G(){A=0,j={},Q=!1}if(process.stdin.isTTY){process.stdout.write("\x1B[?2004h");let N=process.stdin.emit.bind(process.stdin);process.stdin.emit=function(D,...K){if(D!=="data")return N.call(process.stdin,D,...K);let W=K[0];if(Buffer.isBuffer(W)&&(W=W.toString("utf8")),typeof W!="string")return N.call(process.stdin,D,...K);let B=W.includes(na),re=W.includes(sa);if(B&&re){let Z=xs(W);return Z&&C.push(...Z.split(`
|
|
1126
1126
|
`)),X()}if(B){R=!0,C=[];let Z=xs(W);return Z&&C.push(...Z.split(`
|
|
@@ -1128,16 +1128,16 @@ ${a.yellow} Task cancelled. Press Ctrl+C again to exit.${a.reset}`),w=!1,p.setP
|
|
|
1128
1128
|
`)),X()}if(R){let Z=xs(W);return Z&&C.push(...Z.split(`
|
|
1129
1129
|
`)),!0}return W.includes(`
|
|
1130
1130
|
`)&&W.length>40&&!R?(C.push(...W.replace(/\r/g,"").split(`
|
|
1131
|
-
`)),X()):N.call(process.stdin,D,...K)}}let U=0;function pe(){if(U>0){let N=y._scrollEnd,D="\x1B7";for(let K=0;K<U;K++)D+=`\x1B[${N-U+1+K};1H\x1B[2K`;D+="\x1B8",y.rawWrite(D),U=0}}function Te(N){let D=[...Ko,...Zi()].filter(te=>te.cmd.startsWith(N));if(!D.length||D.length===1&&D[0].cmd===N)return;let K=y._scrollEnd,W=Math.min(10,K-2);if(W<1)return;let B=D.slice(0,W),re=Math.max(...B.map(te=>te.cmd.length));U=B.length,D.length>W&&U++;let Z=K-U+1,z="\x1B7";for(let te=0;te<B.length;te++){let{cmd:Oe,desc:ze}=B[te],Ye=Oe.substring(0,N.length),ye=Oe.substring(N.length),xe=" ".repeat(Math.max(0,re-Oe.length+2));z+=`\x1B[${Z+te};1H\x1B[2K ${
|
|
1132
|
-
${B}. `).trim()}let{loadSession:et}=Et(),{setConversationMessages:vs}=de();if(e()===0){let N=et("_autosave");if(N&&N.messages&&N.messages.length>0&&Date.now()-new Date(N.updatedAt).getTime()<1440*60*1e3){let{confirm:K}=
|
|
1133
|
-
`))}}p.setPrompt(Ze()),p.prompt(),p.on("line",async N=>{if(pe(),Object.keys(j).length>0&&(N=H(N),G(),p.setPrompt(Ze())),w){let B=N.trim();if(B){let{injectMidRunNote:re}=de();re(B),process.stdout.write(`${
|
|
1131
|
+
`)),X()):N.call(process.stdin,D,...K)}}let U=0;function pe(){if(U>0){let N=y._scrollEnd,D="\x1B7";for(let K=0;K<U;K++)D+=`\x1B[${N-U+1+K};1H\x1B[2K`;D+="\x1B8",y.rawWrite(D),U=0}}function Te(N){let D=[...Ko,...Zi()].filter(te=>te.cmd.startsWith(N));if(!D.length||D.length===1&&D[0].cmd===N)return;let K=y._scrollEnd,W=Math.min(10,K-2);if(W<1)return;let B=D.slice(0,W),re=Math.max(...B.map(te=>te.cmd.length));U=B.length,D.length>W&&U++;let Z=K-U+1,z="\x1B7";for(let te=0;te<B.length;te++){let{cmd:Oe,desc:ze}=B[te],Ye=Oe.substring(0,N.length),ye=Oe.substring(N.length),xe=" ".repeat(Math.max(0,re-Oe.length+2));z+=`\x1B[${Z+te};1H\x1B[2K ${i.cyan}${Ye}${i.reset}${i.dim}${ye}${xe}${ze}${i.reset}`}D.length>W&&(z+=`\x1B[${Z+B.length};1H\x1B[2K ${i.dim}\u2026 +${D.length-W} more${i.reset}`),z+="\x1B8",y.rawWrite(z)}process.stdin.isTTY&&process.stdin.on("keypress",(N,D)=>{pe(),!(D&&(D.name==="tab"||D.name==="return"))&&setImmediate(()=>{p.line&&p.line.startsWith("/")&&Te(p.line)})});let ve=null,Me=`${i.dim}...${i.reset} `;function Ae(N){return(N.match(/[^\s\d](\d{1,2})\.\s+\S/g)||[]).length<2?N:N.replace(/([^\s\d])(\d{1,2})\.\s+/g,(K,W,B)=>`${W}
|
|
1132
|
+
${B}. `).trim()}let{loadSession:et}=Et(),{setConversationMessages:vs}=de();if(e()===0){let N=et("_autosave");if(N&&N.messages&&N.messages.length>0&&Date.now()-new Date(N.updatedAt).getTime()<1440*60*1e3){let{confirm:K}=Ie();await K("Previous session found. Resume?")&&(vs(N.messages),console.log(`${i.green}Session restored (${N.messages.length} messages)${i.reset}
|
|
1133
|
+
`))}}p.setPrompt(Ze()),p.prompt(),p.on("line",async N=>{if(pe(),Object.keys(j).length>0&&(N=H(N),G(),p.setPrompt(Ze())),w){let B=N.trim();if(B){let{injectMidRunNote:re}=de();re(B),process.stdout.write(`${i.cyan} \u270E Queued \u2014 will be applied in the next step${i.reset}
|
|
1134
1134
|
`),p.prompt()}return}if(ve!==null){if(ve._mode==="triple"){if(N.trim()==='"""'){let B=ve.join(`
|
|
1135
1135
|
`).trim();if(ve=null,B){Go(B.replace(/\n/g,"\\n")),w=!0,p.prompt(),E=0,b=!1,k&&(clearTimeout(k),k=null),Ct=new AbortController;try{await s(B)}catch(Z){if(!Ct?.signal?.aborted){let z=Z.message?.split(`
|
|
1136
|
-
`)[0]||"An unexpected error occurred";console.log(`${
|
|
1136
|
+
`)[0]||"An unexpected error occurred";console.log(`${i.red}Error: ${z}${i.reset}`)}}w=!1;let re=K();re>0&&process.stdout.write(`${i.gray}[${re} messages] ${i.reset}`)}p.setPrompt(Ze()),p.prompt();return}ve.push(N),p.setPrompt(Me),p.prompt();return}if(N.endsWith("\\"))ve.push(N.slice(0,-1));else{ve.push(N);let B=ve.join(`
|
|
1137
1137
|
`).trim();if(ve=null,B){Go(B.replace(/\n/g,"\\n")),w=!0,p.prompt(),E=0,b=!1,k&&(clearTimeout(k),k=null),Ct=new AbortController;try{await s(B)}catch(z){if(!Ct?.signal?.aborted){let te=z.message?.split(`
|
|
1138
|
-
`)[0]||"An unexpected error occurred";console.log(`${
|
|
1139
|
-
`).forEach((z,te)=>{let Oe=te===0?"\x1B[1;36m\u203A\x1B[22;39m":" ",ze=2+z.length,Ye=" ".repeat(Math.max(0,re-ze));console.log(`${B}${Oe} ${z}${Ye}\x1B[0m`)})}if(process.env.NEX_AUTO_PLAN!=="0"){let{isPlanMode:B,setPlanMode:re}=Ut(),{invalidateSystemPromptCache:Z}=de(),z=/\b(implement|refactor|migrate|redesign)\b/i,te=/\b(create|build|add|write|introduce|develop|set\s+up)\b/i,Oe=/^(how|what|why|when|where|which|explain|show|list|tell|describe|can\s+you|could\s+you|do\s+you)\b/i,ze=/\b(spawn[_\s]?agents?|swarm)\b/i;!Oe.test(D)&&!ze.test(D)&&(z.test(D)||te.test(D)&&D.split(/\s+/).length>=5)&&!B()&&(re(!0),Z(),console.log(`${
|
|
1140
|
-
`)[0]||"An unexpected error occurred";console.log(`${
|
|
1138
|
+
`)[0]||"An unexpected error occurred";console.log(`${i.red}Error: ${te}${i.reset}`)}}let{getConversationLength:re}=de();w=!1;let Z=re();Z>0&&process.stdout.write(`${i.gray}[${Z} messages] ${i.reset}`)}p.setPrompt(Ze()),p.prompt();return}p.setPrompt(Me),p.prompt();return}if(N.trim()==='"""'||N.trim().startsWith('"""')){let B=N.trim().substring(3);ve=B?[B]:[],ve._mode="triple",p.setPrompt(Me),p.prompt();return}if(N.endsWith("\\")){ve=[N.slice(0,-1)],ve._mode="backslash",p.setPrompt(Me),p.prompt();return}let D=Ae(N.trim());if(!D){p.setPrompt(Ze()),p.prompt();return}if(Go(D),D==="/"){yf(),p.setPrompt(Ze()),p.prompt();return}if(D.startsWith("/")){await xf(D,p),p.setPrompt(Ze()),p.prompt();return}{let B=bb?"\x1B[48;5;237m":"\x1B[48;2;220;225;235m",re=process.stdout.columns||80;D.split(`
|
|
1139
|
+
`).forEach((z,te)=>{let Oe=te===0?"\x1B[1;36m\u203A\x1B[22;39m":" ",ze=2+z.length,Ye=" ".repeat(Math.max(0,re-ze));console.log(`${B}${Oe} ${z}${Ye}\x1B[0m`)})}if(process.env.NEX_AUTO_PLAN!=="0"){let{isPlanMode:B,setPlanMode:re}=Ut(),{invalidateSystemPromptCache:Z}=de(),z=/\b(implement|refactor|migrate|redesign)\b/i,te=/\b(create|build|add|write|introduce|develop|set\s+up)\b/i,Oe=/^(how|what|why|when|where|which|explain|show|list|tell|describe|can\s+you|could\s+you|do\s+you)\b/i,ze=/\b(spawn[_\s]?agents?|swarm)\b/i;!Oe.test(D)&&!ze.test(D)&&(z.test(D)||te.test(D)&&D.split(/\s+/).length>=5)&&!B()&&(re(!0),Z(),console.log(`${i.cyan}${i.bold}\u2387 Auto Plan Mode${i.reset}${i.dim} \u2014 implementation task detected \xB7 read-only until /plan approve${i.reset}`))}{let{getConversationLength:B}=de();if(B()===0)try{let{detectCategory:re,getModelForCategory:Z}=Bi(),z=re(D);if(z&&z.id!=="coding"){let te=Z(z.id),Oe=At();if(te&&te!==Oe?.id&&Qi(te)){let ze=At();console.log(`${i.dim}\u21B3 ${z.icon} ${z.label} task \u2014 routing to ${ze?.name||te}${i.reset}`),global._nexFooter&&global._nexFooter.setStatusInfo({model:ze?.name||te})}}}catch{}}w=!0,p.prompt(),E=0,b=!1,k&&(clearTimeout(k),k=null),Ct=new AbortController;try{await s(D)}catch(B){if(!Ct?.signal?.aborted){let re=B.message?.split(`
|
|
1140
|
+
`)[0]||"An unexpected error occurred";console.log(`${i.red}Error: ${re}${i.reset}`)}}w=!1;let{getConversationLength:K}=de(),W=K();W>0&&process.stdout.write(`${i.gray}[${W} messages] ${i.reset}`),p.setPrompt(Ze()),p.prompt()}),p.on("close",()=>{process.stdin.isTTY&&process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J"),process.exit(0)})}Sf.exports={startREPL:Nb,getPrompt:Ze,loadHistory:vf,appendHistory:Go,getHistoryPath:ta,HISTORY_MAX:ea,showCommandList:yf,completer:bf,completeFilePath:wf,handleSlashCommand:xf,showProviders:Ji,showHelp:_f,renderBar:kf,hasPasteStart:Cb,hasPasteEnd:Ab,stripPasteSequences:xs,getAbortSignal:$f}});var aa=require("path");require("dotenv").config({path:aa.join(__dirname,"..",".env")});require("dotenv").config();var ge=process.argv.slice(2);(ge.includes("--help")||ge.includes("-h"))&&(console.log(`Usage: nex-code [options]
|
|
1141
1141
|
|
|
1142
1142
|
Options:
|
|
1143
1143
|
--task <prompt> Run a single task and exit (headless mode)
|
|
@@ -1151,4 +1151,4 @@ Options:
|
|
|
1151
1151
|
--json Output result as JSON (for CI parsing)
|
|
1152
1152
|
-h, --help Show this help
|
|
1153
1153
|
-v, --version Show version
|
|
1154
|
-
`),process.exit(0));if(ge.includes("-v")||ge.includes("--version")){let t=Es();console.log(t.version),process.exit(0)}var
|
|
1154
|
+
`),process.exit(0));if(ge.includes("-v")||ge.includes("--version")){let t=Es();console.log(t.version),process.exit(0)}var Cf=ge.includes("--yolo")||ge.includes("-yolo");if(Cf){let{setAutoConfirm:t}=Ie();t(!0)}if(!Cf)try{let t=require("fs"),e=aa.join(process.cwd(),".nex","config.json");if(t.existsSync(e)&&JSON.parse(t.readFileSync(e,"utf-8")).yolo===!0){let{setAutoConfirm:o}=Ie();o(!0)}}catch{}var oa=ge.indexOf("--model");if(oa!==-1&&ge[oa+1]){let{setActiveModel:t}=be();t(ge[oa+1])}var ra=ge.indexOf("--max-turns");if(ra!==-1&&ge[ra+1]){let t=parseInt(ge[ra+1],10);if(t>0){let{setMaxIterations:e}=de();e(t)}}else try{let t=require("fs"),e=aa.join(process.cwd(),".nex","config.json");if(t.existsSync(e)){let s=JSON.parse(t.readFileSync(e,"utf-8")),o=parseInt(s.maxIterations,10);if(o>0){let{setMaxIterations:n}=de();n(o)}}}catch{}function ia(){if(process.platform==="darwin")try{let{spawn:t}=require("child_process"),e=t("caffeinate",["-i","-m"],{stdio:"ignore",detached:!1});e.unref();let s=()=>{try{e.kill()}catch{}};process.on("exit",s),process.on("SIGINT",s),process.on("SIGTERM",s)}catch{}}async function Mb(){let{runSetupWizard:t}=ji();await t()}function Tf(t){if(ge.includes("--auto")){let{setAutoConfirm:n}=Ie();n(!0)}if(!ge.includes("--model")){let{setActiveModel:n}=be(),r=process.env.HEADLESS_MODEL||"devstral-small-2:24b";n(r)}let{processInput:s,getConversationMessages:o}=de();s(t).then(()=>{if(ge.includes("--json")){let r=o().filter(a=>a.role==="assistant").pop();console.log(JSON.stringify({success:!0,response:r?.content||""}))}process.exit(0)}).catch(n=>{ge.includes("--json")?console.log(JSON.stringify({success:!1,error:n.message})):console.error(n.message),process.exit(1)})}if(ge.includes("--server")){let{setAutoConfirm:t}=Ie();t(!0),Ad().startServerMode();return}var Rf=ge.indexOf("--prompt-file");if(Rf!==-1){let t=ge[Rf+1];(!t||t.startsWith("--"))&&(console.error("--prompt-file requires a file path"),process.exit(1));let e=require("fs"),s;try{s=e.readFileSync(t,"utf-8").trim()}catch(o){console.error(`--prompt-file: cannot read file: ${o.message}`),process.exit(1)}if(s||(console.error("--prompt-file: file is empty"),process.exit(1)),ge.includes("--delete-prompt-file"))try{e.unlinkSync(t)}catch{}ia(),Tf(s)}else{let t=ge.indexOf("--task");if(t!==-1){let e=ge[t+1];(!e||e.startsWith("--"))&&(console.error("--task requires a prompt"),process.exit(1)),ia(),Tf(e)}else Mb().then(()=>{ia();let{startREPL:e}=Ef();e()})}
|