nex-code 0.3.71 → 0.3.73
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/nex-code.js +539 -451
- package/package.json +1 -1
package/dist/nex-code.js
CHANGED
|
@@ -1,154 +1,155 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
`),n=t("python3",["-c",e],{encoding:"buffer",timeout:400,stdio:["ignore","pipe","ignore"]}).toString("utf8").match(/rgb:([0-9a-fA-F]+)\/([0-9a-fA-F]+)\/([0-9a-fA-F]+)/);if(n){let r=parseInt(n[1].slice(0,2),16),i=parseInt(n[2].slice(0,2),16),c=parseInt(n[3].slice(0,2),16);return .299*r+.587*i+.114*c<128}}catch{}return null}function
|
|
2
|
+
var G=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Sn=G((lx,Dp)=>{Dp.exports={name:"nex-code",version:"0.3.73",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","merge-to-main":"bash scripts/merge-to-main.sh",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 an=G((ux,ic)=>{"use strict";var ec="\x1B[0m",tc="\x1B[1m",En="\x1B[2m";function I(t,e,s){return`\x1B[38;2;${t};${e};${s}m`}function qp(){if(!process.stdout.isTTY)return null;try{let{execFileSync:t}=require("child_process"),e=["import sys,os,tty,termios,select","f=open('/dev/tty','r+b',buffering=0)","fd=f.fileno()","s=termios.tcgetattr(fd)","try:"," tty.setraw(fd)"," f.write(bytes([0x1b,0x5d,0x31,0x31,0x3b,0x3f,0x1b,0x5c]))"," r=select.select([fd],[],[],0.1)[0]"," d=b''"," if r:"," while True:"," r2=select.select([fd],[],[],0.05)[0]"," if not r2:break"," c=os.read(fd,1)"," d+=c"," if d[-1:]==bytes([0x07]) or d[-2:]==bytes([0x1b,0x5c]):break"," sys.stdout.buffer.write(d)","finally:"," termios.tcsetattr(fd,termios.TCSADRAIN,s)"," f.close()"].join(`
|
|
3
|
+
`),n=t("python3",["-c",e],{encoding:"buffer",timeout:400,stdio:["ignore","pipe","ignore"]}).toString("utf8").match(/rgb:([0-9a-fA-F]+)\/([0-9a-fA-F]+)\/([0-9a-fA-F]+)/);if(n){let r=parseInt(n[1].slice(0,2),16),i=parseInt(n[2].slice(0,2),16),c=parseInt(n[3].slice(0,2),16);return .299*r+.587*i+.114*c<128}}catch{}return null}function nc(){let t=require("os");return require("path").join(t.homedir(),".nex-code",".theme_cache.json")}function Fp(t){try{let s=require("fs").readFileSync(nc(),"utf8"),o=JSON.parse(s);if(o&&typeof o[t]=="boolean")return o[t]}catch{}return null}function Up(t,e){try{let s=require("fs"),o=require("path"),n=nc(),r=o.dirname(n),i={};try{i=JSON.parse(s.readFileSync(n,"utf8"))}catch{}i[t]=e;let c=Object.keys(i);c.length>50&&c.slice(0,c.length-50).forEach(l=>delete i[l]),s.existsSync(r)||s.mkdirSync(r,{recursive:!0}),s.writeFileSync(n,JSON.stringify(i),"utf8")}catch{}}function Wp(){let t=(process.env.NEX_THEME||"").toLowerCase();if(t==="light")return!1;if(t==="dark")return!0;let e=process.env.COLORFGBG;if(e){let i=e.split(";"),c=parseInt(i[i.length-1],10);if(!isNaN(c))return c<8}let s=process.env.TERM_SESSION_ID||"default",o=Fp(s);if(o!==null)return o;let n=qp(),r=n!==null?n:!0;return Up(s,r),r}var sc=Wp(),oc={reset:ec,bold:tc,dim:En,primary:I(80,190,255),secondary:I(60,170,190),success:I(80,210,120),warning:I(245,175,50),error:I(230,80,80),muted:En,subtle:I(130,130,145),tool_read:I(80,190,255),tool_write:I(245,165,55),tool_exec:I(185,100,235),tool_search:I(70,185,190),tool_git:I(90,210,100),tool_web:I(100,215,250),tool_sysadmin:I(225,150,75),tool_default:I(100,205,115),syn_keyword:I(185,100,235),syn_string:I(90,210,120),syn_number:I(245,175,50),syn_comment:En,syn_key:I(80,190,255),diff_add:I(80,210,120),diff_rem:I(230,80,80),banner_logo:I(80,200,255),banner_name:I(80,200,255),banner_version:En,banner_model:En,banner_yolo:I(245,175,50),footer_sep:En,footer_model:I(80,175,235),footer_branch:I(80,210,100),footer_project:I(130,130,145),footer_divider:I(80,80,95),footer_mode:I(210,150,50),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"},rc={reset:ec,bold:tc,dim:I(110,110,120),primary:I(0,110,190),secondary:I(0,125,148),success:I(0,148,62),warning:I(168,92,0),error:I(188,32,32),muted:I(110,110,120),subtle:I(155,155,165),tool_read:I(0,110,190),tool_write:I(168,92,0),tool_exec:I(128,42,188),tool_search:I(0,122,148),tool_git:I(0,138,62),tool_web:I(0,112,178),tool_sysadmin:I(168,82,0),tool_default:I(0,138,62),syn_keyword:I(128,42,188),syn_string:I(0,138,62),syn_number:I(168,92,0),syn_comment:I(135,135,148),syn_key:I(0,110,190),diff_add:I(0,148,62),diff_rem:I(188,32,32),banner_logo:I(0,122,205),banner_name:I(0,122,205),banner_version:I(100,100,118),banner_model:I(100,100,118),banner_yolo:I(168,62,0),footer_sep:I(168,168,178),footer_model:I(0,102,175),footer_branch:I(0,138,62),footer_project:I(135,135,148),footer_divider:I(168,168,178),footer_mode:I(148,88,0),white:I(40,40,52),red:I(188,32,32),green:I(0,148,62),yellow:I(168,92,0),blue:I(0,110,190),magenta:I(128,42,188),cyan:I(0,125,148),gray:I(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:I(0,158,182),brightMagenta:I(158,52,208),brightBlue:I(0,112,208)},Bp=sc?oc:rc;ic.exports={T:Bp,isDark:sc,DARK:oc,LIGHT:rc}});var Rn=G((dx,cc)=>{var{T:B}=an(),so=5,Tn=(()=>{let t=[];for(let e=0;e<so;e++)t.push(e);for(let e=so-2;e>=1;e--)t.push(e);return t})(),ac=["\u273D","\u2726","\u2727","\u2726"],Mr=class{constructor(e="Thinking..."){this.text=e,this.frame=0,this.interval=null,this.startTime=null}_render(){if(this._stopped)return;let e=Tn[this.frame%Tn.length],s="";for(let n=0;n<so;n++)s+=n===e?`${B.cyan}\u25CF${B.reset}`:" ";let o="";if(this.startTime){let n=Math.floor((Date.now()-this.startTime)/1e3);if(n>=60){let r=Math.floor(n/60),i=n%60;o=` ${B.dim}${r}m ${String(i).padStart(2,"0")}s${B.reset}`}else n>=1&&(o=` ${B.dim}${n}s${B.reset}`)}process.stderr.write(`\x1B[2K\r${s} ${B.dim}${this.text}${B.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}},Pr=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=Tn[this.frame%Tn.length],s=`${B.cyan}\u25CF${B.reset}`,o=`${B.dim}\u25CB${B.reset}`,n=this._formatElapsed(),r=n?` ${B.dim}${n}${B.reset}`:"",i="";for(let c=0;c<this.labels.length;c++){let l,u;switch(this.statuses[c]){case"done":l=`${B.green}\u2713${B.reset}`,u=B.dim;break;case"error":l=`${B.red}\u2717${B.reset}`,u=B.dim;break;default:l=c===e?s:" ",u=""}let d=c===this.labels.length-1?r:"";i+=`\x1B[2K ${l} ${u}${this.labels[c]}${B.reset}${d}
|
|
4
4
|
`}this.lineCount>0&&(i+=`\x1B[${this.lineCount}A`),process.stderr.write(i),this.frame++}start(){this._stopped=!1,this.startTime=Date.now();let e="\x1B[?25l";for(let s=0;s<this.lineCount;s++)e+=`
|
|
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?` ${
|
|
6
|
-
`}process.stderr.write(o)}},
|
|
7
|
-
`;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=
|
|
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?` ${B.dim}${e}${B.reset}`:"",o="";for(let n=0;n<this.labels.length;n++){let r;switch(this.statuses[n]){case"done":r=`${B.green}\u2713${B.reset}`;break;case"error":r=`${B.red}\u2717${B.reset}`;break;default:r=`${B.yellow}\u25CB${B.reset}`}let i=n===this.labels.length-1?s:"";o+=`\x1B[2K ${r} ${B.dim}${this.labels[n]}${B.reset}${i}
|
|
6
|
+
`}process.stderr.write(o)}},to={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},no={done:B.green,in_progress:B.cyan,pending:B.dim,failed:B.red},Yt=null,Ir=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=ac[this.frame%ac.length],s=this._formatElapsed(),o=this._formatTokens(),n=[s,o?`\u2193 ${o} tokens`:""].filter(Boolean).join(" \xB7 "),r=n?` ${B.dim}(${n})${B.reset}`:"",i=`\x1B[2K${B.cyan}${e}${B.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=to[l.status]||to.pending,f=no[l.status]||no.pending,p=l.description.length>55?l.description.substring(0,52)+"...":l.description;i+=`\x1B[2K ${B.dim}${u}${B.reset} ${f}${d}${B.reset} ${p}
|
|
8
8
|
`}i+=`\x1B[${this.lineCount}A`,process.stderr.write(i),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),this._paused=!1;let e="\x1B[?25l";for(let s=0;s<this.lineCount;s++)e+=`
|
|
9
|
-
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120),
|
|
9
|
+
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120),Yt=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,Yt===this&&(Yt=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`,i=`\x1B[2K${
|
|
12
|
-
`;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=
|
|
13
|
-
`}process.stderr.write(i)}},
|
|
14
|
-
`),o=s.slice(0,e),n=s.length-e,r=`${
|
|
11
|
+
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120)}updateTask(e,s){let o=this.tasks.find(n=>n.id===e);o&&(o.status=s)}setStats({tokens:e}){e!==void 0&&(this.tokens=e)}isActive(){return this.interval!==null||this._paused}_renderFinal(){let e=this._formatElapsed(),s=this.tasks.filter(c=>c.status==="done").length,o=this.tasks.filter(c=>c.status==="failed").length,n=this.tasks.length,r=o>0?`${s}/${n} done, ${o} failed`:`${s}/${n} done`,i=`\x1B[2K${B.green}\u2714${B.reset} ${this.name} ${B.dim}(${e} \xB7 ${r})${B.reset}
|
|
12
|
+
`;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=to[l.status]||to.pending,f=no[l.status]||no.pending,p=l.description.length>55?l.description.substring(0,52)+"...":l.description;i+=`\x1B[2K ${B.dim}${u}${B.reset} ${f}${d}${B.reset} ${B.dim}${p}${B.reset}
|
|
13
|
+
`}process.stderr.write(i)}},Lr=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=Tn[this.frame%Tn.length],s="";for(let r=0;r<so;r++)s+=r===e?`${B.cyan}\u25CF${B.reset}`:" ";let o=this.message;this.count>0&&(o+=` ${B.cyan}${this.count}${B.reset}`,this.total&&(o+=`/${this.total}`),this.detail&&(o+=` ${B.dim}${this.detail}${B.reset}`));let n="";if(this.startTime){let r=Math.floor((Date.now()-this.startTime)/1e3);r>=1&&(n=` ${B.dim}${r}s${B.reset}`)}process.stderr.write(`\x1B[2K\r${s} ${B.dim}${o}${B.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 Hp(t){Yt=t}function Gp(){return Yt}function Kp(){Yt&&(Yt.stop(),Yt=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}cc.exports={C:B,Spinner:Mr,MultiProgress:Pr,TaskProgress:Ir,ToolProgress:Lr,setActiveTaskProgress:Hp,getActiveTaskProgress:Gp,cleanupTerminal:Kp}});var dc=G((fx,uc)=>{var{T:E}=an(),Ve=E;function lc(t){if(!t)return"";let e=t.replace(/^\.\//,"").split("/");return e.length>1?e.slice(-2).join("/"):e[0]}var Yp={read_file:E.tool_read,list_directory:E.tool_read,write_file:E.tool_write,edit_file:E.tool_write,patch_file:E.tool_write,bash:E.tool_exec,grep:E.tool_search,search_files:E.tool_search,glob:E.tool_search,git_commit:E.tool_git,git_push:E.tool_git,git_pull:E.tool_git,git_status:E.tool_git,git_diff:E.tool_git,git_log:E.tool_git,git_branch:E.tool_git,git_stash:E.tool_git,web_fetch:E.tool_web,web_search:E.tool_web,sysadmin:E.tool_sysadmin,ssh_exec:E.tool_sysadmin,ssh_upload:E.tool_sysadmin,ssh_download:E.tool_sysadmin,deploy:E.tool_sysadmin},jr={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 oo(t,e=!1,s=null){if(e)return`${E.error}\u25CF${E.reset}`;let o=Yp[t]||E.tool_default;return s==="blink"?`${o}\x1B[5m\u25CF\x1B[25m${E.reset}`:`${o}${s!==null?s:"\u25CF"}${E.reset}`}function zp(t,e,s=!1,o=null){let n=(t||[]).filter(l=>l&&l.canExecute!==!1);if(n.length===0)return`${oo("",s,o)} Step ${e}`;if(n.length===1){let l=n[0],u=l.args||{},d=jr[l.fnName]||l.fnName.replace(/_/g," "),f="";u.path?f=lc(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 p=f?`${Ve.dim}(${f})${Ve.reset}`:"";return`${oo(l.fnName,s,o)} ${Ve.bold}${d}${Ve.reset} ${p}`}let r=n[0].fnName,i=[...new Set(n.map(l=>jr[l.fnName]||l.fnName.replace(/_/g," ")))],c=i.length<=3?i.join(" \xB7 "):`${n.length} actions`;return`${oo(r,s,o)} ${c}`}function Xp(t,e){let s;switch(t){case"write_file":case"edit_file":case"patch_file":case"read_file":case"list_directory":s=lc(e.path);break;case"bash":case"ssh_exec":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=jr[t]||t.replace(/_/g," "),n=s?` ${Ve.dim}(${s})${Ve.reset}`:"";return`${oo(t)} ${Ve.bold}${o}${Ve.reset}${n}`}function Jp(t,e=8){let s=t.split(`
|
|
14
|
+
`),o=s.slice(0,e),n=s.length-e,r=`${E.muted} \u2514 ${E.reset}`,i=" ",c=o.map((l,u)=>`${u===0?r:i}${E.success}${l}${E.reset}`).join(`
|
|
15
15
|
`);return n>0&&(c+=`
|
|
16
|
-
${
|
|
16
|
+
${E.subtle} \u2026 +${n} lines${E.reset}`),c}function Vp(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 Qp(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
|
-
${
|
|
19
|
-
`).filter(Boolean).filter(
|
|
20
|
-
`),l=c.length,u=e.path?require("path").basename(e.path):null,d=u?`Wrote ${u} \xB7 ${l} line${l!==1?"s":""}`:`Wrote ${l} line${l!==1?"s":""}`,f=40,
|
|
18
|
+
${E.muted}${l[1].substring(0,100)}${E.reset}`:"";return` ${E.error}\u2514 ${c}${E.reset}${u}`}let r;switch(t){case"read_file":{let l=n.split(`
|
|
19
|
+
`).filter(Boolean).filter(g=>!/^File:\s/.test(g)&&!/^\[LARGE FILE:/.test(g)),u=l.length,d=l[l.length-1],f=d?parseInt(d.match(/^(\d+):/)?.[1]||"0"):0,p=e.line_start||e.line_end,h=e.path?require("path").basename(e.path):null,m=h?` ${E.muted}from ${h}${E.reset}`:"";p&&f>u?r=`Read lines ${e.line_start||1}\u2013${f}${m}`:r=`Read ${u} line${u!==1?"s":""}${m}`;break}case"write_file":{let c=(e.content||"").split(`
|
|
20
|
+
`),l=c.length,u=e.path?require("path").basename(e.path):null,d=u?`Wrote ${u} \xB7 ${l} line${l!==1?"s":""}`:`Wrote ${l} line${l!==1?"s":""}`,f=40,p=8;if(l<=f){let h=c.map(m=>` ${E.muted}${m}${E.reset}`).join(`
|
|
21
21
|
`);r=`${d}
|
|
22
|
-
${h}`}else{let h=c.slice(0,
|
|
22
|
+
${h}`}else{let h=c.slice(0,p).map(m=>` ${E.muted}${m}${E.reset}`).join(`
|
|
23
23
|
`);r=`${d}
|
|
24
24
|
${h}
|
|
25
|
-
${
|
|
25
|
+
${E.subtle}\u2026 +${l-p} lines${E.reset}`}break}case"edit_file":{let c=(e.old_text||"").split(`
|
|
26
26
|
`),l=(e.new_text||"").split(`
|
|
27
|
-
`),u=c.length,d=l.length,f=
|
|
28
|
-
`+
|
|
27
|
+
`),u=c.length,d=l.length,f=e.path?require("path").basename(e.path):null,p=f?` ${E.muted}${f}${E.reset}`:"",h=c.find($=>$.trim()),m=l.find($=>$.trim()),g=[];h&&g.push(` ${E.diff_rem}- ${E.reset}${E.muted}${h.trimEnd().substring(0,72)}${E.reset}`),m&&g.push(` ${E.diff_add}+ ${E.reset}${E.muted}${m.trimEnd().substring(0,72)}${E.reset}`),r=`${E.diff_rem}\u2212${u}${E.reset} ${E.diff_add}+${d}${E.reset}${p}`+(g.length>0?`
|
|
28
|
+
`+g.join(`
|
|
29
29
|
`):"");break}case"patch_file":{let c=e.patches||[],l=c.reduce((d,f)=>d+(f.old_text||"").split(`
|
|
30
30
|
`).length,0),u=c.reduce((d,f)=>d+(f.new_text||"").split(`
|
|
31
|
-
`).length,0);r=`${
|
|
32
|
-
`).filter(
|
|
33
|
-
`)}break}case"grep":case"search_files":{if(n.includes("(no matches)")||n==="no matches")r=`No matches${e.pattern?` ${
|
|
34
|
-
`).filter(Boolean),u=l.length,f=new Set(l.map(
|
|
35
|
-
|
|
36
|
-
`)}break}case"glob":{let c=e.pattern?` ${
|
|
37
|
-
`).filter(Boolean),d=u.length,f=u.slice(0,5).map(
|
|
38
|
-
`).filter(Boolean),l=c.length,u=c.slice(0,6).join(", "),d=l-6;r=d>0?`${l} entries \u2014 ${
|
|
31
|
+
`).length,0);r=`${E.reset}${c.length} patch${c.length!==1?"es":""} ${E.diff_rem}\u2212${l}${E.reset} ${E.diff_add}+${u}${E.reset}`;break}case"bash":{let l=n.match(/^EXIT (\d+)/),u=n.split(`
|
|
32
|
+
`).filter(p=>p&&!p.startsWith("EXIT ")&&!p.startsWith("HINT:")&&p.trim()),d=l?l[1]==="0"?`${E.success}\u2713${E.reset}`:`${E.error}\u2717 Exit ${l[1]}${E.reset}`:`${E.success}\u2713${E.reset}`,f=n.match(/\nHINT: (.+)/);if(f)r=`${d} ${E.muted}\u2014 ${f[1].substring(0,100)}${E.reset}`;else if(u.length===0)r=d;else{let p=l&&l[1]!=="0",h=p?u.slice(-3):u.slice(0,3),m=u.length-3,g=h.map(($,y)=>y===0?`${d} ${E.muted}${$.substring(0,120)}${E.reset}`:` ${E.muted}${$.substring(0,120)}${E.reset}`);if(m>0){let $=p?` ${E.subtle}${m} lines above\u2026${E.reset}`:` ${E.subtle}\u2026 +${m} lines${E.reset}`;p?g.unshift($):g.push($)}r=g.join(`
|
|
33
|
+
`)}break}case"grep":case"search_files":{if(n.includes("(no matches)")||n==="no matches")r=`No matches${e.pattern?` ${E.muted}"${String(e.pattern).substring(0,40)}"${E.reset}`:""}`;else{let m=function(y){let x=y.indexOf(":");if(x===-1)return`${E.muted}${y.substring(0,90)}${E.reset}`;let _=y.substring(0,x),v=y.substring(x+1),b=v.match(/^(\d+)[:-](.*)/s),k=b?`:${b[1]}`:"",R=(b?b[2]:v).trim(),O=`${E.subtle}${c.basename(_)}${k}${E.reset}`,P=`${E.muted}${R.substring(0,80)}${R.length>80?"\u2026":""}${E.reset}`;return`${O} ${P}`};var i=m;let c=require("path"),l=n.split(`
|
|
34
|
+
`).filter(Boolean),u=l.length,f=new Set(l.map(y=>y.split(":")[0]).filter(Boolean)).size,p=e.pattern?` ${E.muted}"${String(e.pattern).substring(0,40)}"${E.reset}`:"",h=f>1?`${u} match${u!==1?"es":""} in ${f} files${p}`:`${u} match${u!==1?"es":""}${p}`,g=l.slice(0,3).map((y,x)=>x===0?`${h}
|
|
35
|
+
${m(y)}`:` ${m(y)}`),$=l.length-3;$>0&&g.push(` ${E.subtle}\u2026 +${$} lines${E.reset}`),r=g.join(`
|
|
36
|
+
`)}break}case"glob":{let c=e.pattern?` ${E.muted}${String(e.pattern).substring(0,50)}${E.reset}`:"";if(n==="(no matches)")r=`No files found${c}`;else{let l=require("path"),u=n.split(`
|
|
37
|
+
`).filter(Boolean),d=u.length,f=u.slice(0,5).map(m=>l.basename(m)),p=d-f.length,h=f.join(", ")+(p>0?`, +${p} more`:"");r=`${d} file${d!==1?"s":""}${c} \u2014 ${E.muted}${h}${E.reset}`}break}case"list_directory":{if(n==="(empty)")r="0 entries";else{let c=n.split(`
|
|
38
|
+
`).filter(Boolean),l=c.length,u=c.slice(0,6).join(", "),d=l-6;r=d>0?`${l} entries \u2014 ${E.muted}${u}, +${d} more${E.reset}`:`${l} entr${l!==1?"ies":"y"} \u2014 ${E.muted}${u}${E.reset}`}break}case"git_status":{let c=n.match(/Branch:\s*(\S+)/),l=n.split(`
|
|
39
39
|
`).filter(u=>/^\s*[MADRCU?!]/.test(u)).length;r=c?`${c[1]} \xB7 ${l} change${l!==1?"s":""}`:"Done";break}case"git_diff":{let c=(n.match(/^\+[^+]/gm)||[]).length,l=(n.match(/^-[^-]/gm)||[]).length;r=c||l?`+${c} \u2212${l} lines`:"No diff";break}case"git_log":{let c=n.split(`
|
|
40
40
|
`).filter(f=>/^commit\s+[0-9a-f]{7}/.test(f)),l=c.length,u=c[0]?c[0].replace(/^commit\s+/,"").substring(0,7):null,d=(()=>{let f=n.indexOf(c[0]||"\0");return f===-1?null:n.substring(f).split(`
|
|
41
|
-
`).find((h,
|
|
41
|
+
`).find((h,m)=>m>0&&h.trim()&&!h.startsWith("Author:")&&!h.startsWith("Date:")&&!h.startsWith("Merge:"))})();if(l===0)r="Log retrieved";else if(u&&d){let f=l>1?` ${E.muted}+${l-1} more${E.reset}`:"";r=`${u} ${E.muted}${d.trim().substring(0,60)}${E.reset}${f}`}else r=`${l} commit${l!==1?"s":""}`;break}case"git_commit":{let c=n.match(/\[[\w./\-]+ ([0-9a-f]{7,})\]/),l=n.match(/\[[\w./\-]+ [0-9a-f]+\]\s+(.+)/);r=c?`${c[1]}${l?` \u2014 ${l[1].substring(0,55)}`:""}`:"Committed";break}case"git_push":{let c=n.match(/(?:->|→)\s*(\S+)/);r=c?`\u2192 ${c[1]}`:"Pushed";break}case"git_pull":{if(/Already up.to.date/i.test(n))r="Already up to date";else{let c=(n.match(/^\+/gm)||[]).length;r=c>0?`Pulled \xB7 +${c} lines`:"Pulled"}break}case"web_fetch":{let c=n.match(/<title[^>]*>([^<]{1,80})<\/title>/i),l=n.match(/^#\s+(.{1,80})/m),u=e.url||"",d="";try{d=new URL(u).hostname}catch{d=u.substring(0,60)}let f=c?c[1].trim():l?l[1].trim():null;r=f?`${d} \u2014 ${E.muted}${f.substring(0,70)}${E.reset}`:`Fetched ${d}`;break}case"web_search":{let c=n.split(`
|
|
42
42
|
|
|
43
43
|
`).filter(Boolean),l=c.length,u=c[0]?c[0].split(`
|
|
44
|
-
`)[0].replace(/^\d+\.\s*/,"").trim():null,d=u?` ${
|
|
45
|
-
`).filter(f=>f.trim()&&!f.startsWith("EXIT ")),d=l?`${
|
|
44
|
+
`)[0].replace(/^\d+\.\s*/,"").trim():null,d=u?` ${E.muted}\u2014 ${u.substring(0,70)}${E.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}case"ssh_exec":{let l=n.startsWith("EXIT ")||n.startsWith("Command failed"),u=n.split(`
|
|
45
|
+
`).filter(f=>f.trim()&&!f.startsWith("EXIT ")),d=l?`${E.error}\u2717${E.reset}`:`${E.success}\u2713${E.reset}`;if(u.length===0)r=d;else{if(u.length>2&&u.every(g=>/^\[/.test(g.trim()))){r=`${d} ${u.length} log lines`;break}let p=l?u.slice(-3):u.slice(0,3),h=u.length-3,m=p.map((g,$)=>$===0?`${d} ${E.muted}${g.substring(0,120)}${E.reset}`:` ${E.muted}${g.substring(0,120)}${E.reset}`);if(h>0){let g=l?` ${E.subtle}${h} lines above\u2026${E.reset}`:` ${E.subtle}\u2026 +${h} lines${E.reset}`;l?m.unshift(g):m.push(g)}r=m.join(`
|
|
46
46
|
`)}break}default:{let c=n.split(`
|
|
47
|
-
`).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?` ${
|
|
47
|
+
`).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?` ${E.subtle}\u2026 +${c.length-1} lines${E.reset}`:"";r=`${E.muted}${l}${E.reset}${u}`}else r="Done"}}return` ${E.muted}\u2514 ${r}${E.reset}`}function Zp(t,e,s,o,n,r){let i=[...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=`
|
|
48
|
+
${E.success}\u25C6${Ve.reset} ${Ve.bold}${t}${Ve.reset}`;return u+=`${Ve.dim} \xB7 ${e} step${e!==1?"s":""}`,u+=` \xB7 ${i} tool${i!==1?"s":""}`,u+=` \xB7 ${l}`,r.size>0&&(u+=` \xB7 ${r.size} file${r.size!==1?"s":""} modified`),u+=Ve.reset,u}uc.exports={C:Ve,formatToolCall:Xp,formatResult:Jp,getToolSpinnerText:Vp,formatToolSummary:Qp,formatSectionHeader:zp,formatMilestone:Zp}});var ve=G((px,pc)=>{var{T:cn}=an(),Dr=cn,fc=["01100110","01111110","01111110","01011010","01111110","00111100"];function em(t,e){let s=[];for(let o=0;o<t.length;o+=2){let n="";for(let r=0;r<t[0].length;r++){let i=t[o][r]==="1",c=o+1<t.length&&t[o+1][r]==="1";i&&c?n+=`${e}\u2588\x1B[0m`:i&&!c?n+=`${e}\u2580\x1B[0m`:!i&&c?n+=`${e}\u2584\x1B[0m`:n+=" "}s.push(n)}return s}function tm(t,e,s={}){let o=Dr.bold,n=Dr.reset,r=em(fc,cn.banner_logo),i=s.yolo?` ${o}${cn.banner_yolo}\u26A1 YOLO${n}`:"",c=Sn().version,l=[` ${cn.banner_name}${o}nex-code${n} ${cn.banner_version}v${c}${n}`,` ${cn.banner_model}${t}${n} ${cn.muted}\xB7 /help${n}${i}`,""],u=Math.max(r.length,l.length),d=Math.floor((u-r.length)/2),f=Math.floor((u-l.length)/2),p=fc[0].length,h=[];for(let m=0;m<u;m++){let g=r[m-d]??" ".repeat(p),$=l[m-f]??"";h.push(g+$)}console.log(`
|
|
48
49
|
`+h.join(`
|
|
49
50
|
`)+`
|
|
50
|
-
`)}var{Spinner:
|
|
51
|
-
`){u(n);return}if(
|
|
52
|
-
`)};return n.length>0&&(r.images=n),r}return s})}async chat(e,s,o={}){await this.discoverModels();let n=o.model||this.defaultModel,r=this.getModel(n),i=o.maxTokens||r?.maxTokens||16384,c=await
|
|
53
|
-
`);
|
|
51
|
+
`)}var{Spinner:nm,MultiProgress:sm,TaskProgress:om,ToolProgress:rm,setActiveTaskProgress:im,getActiveTaskProgress:am,cleanupTerminal:cm}=Rn(),{formatToolCall:lm,formatResult:um,getToolSpinnerText:dm,formatToolSummary:fm,formatSectionHeader:pm,formatMilestone:mm}=dc();pc.exports={C:Dr,banner:tm,Spinner:nm,MultiProgress:sm,TaskProgress:om,ToolProgress:rm,setActiveTaskProgress:im,getActiveTaskProgress:am,cleanupTerminal:cm,formatToolCall:lm,formatResult:um,getToolSpinnerText:dm,formatToolSummary:fm,formatSectionHeader:pm,formatMilestone:mm}});var Ue=G((mx,wc)=>{var hm=require("readline"),{C:At}=ve(),Ur=[/rm\s+-rf\s+\/(?:\s|$)/,/rm\s+-rf\s+~(?:\/|\s|$)/,/rm\s+-rf\s+\.(?:\/|\s|$)/,/rm\s+-rf\s+\*(?:\s|$)/,/mkfs/,/dd\s+if=/,/:\(\)\s*\{/,/>\/dev\/sd/,/curl.*\|\s*(?:ba)?sh/,/wget.*\|\s*(?:ba)?sh/,/cat\s+.*\.env\b/,/cat\s+.*credentials/i,/chmod\s+777/,/chown\s+root/,/passwd/,/userdel/,/useradd/,/\beval\s*\(/,/base64.*\|.*bash/,/\bprintenv\b/,/cat\s+.*\.ssh\/id_/,/cat\s+.*\.ssh\/config/,/\bnc\s+-[el]/,/\bncat\b/,/\bsocat\b/,/python3?\s+-c\s/,/node\s+-e\s/,/perl\s+-e\s/,/ruby\s+-e\s/,/(?:^|[;&|]\s*)history(?:\s|$)/,/curl.*-X\s*POST/,/curl.*--data/,/\bsed\s+-n\s+['"]?\d+,\d+p/],mc=[...Ur,/\bgrep\b.*\.env\b/,/\bawk\b.*\.env\b/,/\bsed\b.*\.env\b/,/\bhead\b.*\.env\b/,/\btail\b.*\.env\b/,/\bless\b.*\.env\b/,/\bmore\b.*\.env\b/,/\bstrings\b.*\.env\b/,/\bgrep\b.*credentials/i,/\bawk\b.*credentials/i,/\bsed\b.*credentials/i,/\bhead\b.*credentials/i,/\btail\b.*credentials/i,/\bcat\b.*private.*key/i,/\bgrep\b.*private_key/i,/\bcat\b.*google.*\.json/i,/\bcat\b.*service.?account/i];function gm(t){for(let e of mc)if(e.test(t))return e;return null}var hc=[/\.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)/],$m=/\b(?:rm|rmdir|unlink|truncate|shred|mv|cp)\b/,qr=[/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 gc(t){let e=t.match(/ssh\s+[^"]*"([^"]+)"/)?.[1]||t.match(/ssh\s+[^']*'([^']+)'/)?.[1];if(!e)return!1;let o=e.replace(/\bfor\s[\s\S]*?\bdone\b/g,r=>r.replace(/;/g,"\0")).replace(/\bwhile\s[\s\S]*?\bdone\b/g,r=>r.replace(/;/g,"\0")).split(/\s*(?:&&|;)\s*/).map(r=>r.replace(/\x00/g,";").trim()).filter(Boolean);if(o.length===0)return!1;let n=r=>{let i=r.replace(/^sudo\s+(?:-[ugCD]\s+\S+\s+|-[A-Za-z]+\s+)*/,"");if(/^\s*(?:echo|printf)\s/.test(i))return!0;if(/^\s*for\s/.test(r)||/^\s*while\s/.test(r)){let c=r.match(/\bdo\s+([\s\S]*?)\s*(?:done|$)/)?.[1];return c?c.split(/\s*;\s*/).map(u=>u.trim()).filter(Boolean).every(u=>n(u)):qr.some(l=>l.test(r))}return/^\w+=\$?\(/.test(i)||/^\w+=["']/.test(i)||/^\w+=\S/.test(i)?!0:qr.some(c=>c.test(i))};return o.every(n)}var Wr=[/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)/],$c=[/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/],yc=[...Wr,...$c],Br=!1,ln=null,Fr=null;function ym(t){Br=t}function wm(t){Fr=t}function bm(){return Br}function _m(t){ln=t}function xm(t){for(let e of Ur)if(e.test(t))return e;return null}function km(t){if(/ssh\s/.test(t)&&gc(t))return!1;for(let e of yc)if(e.test(t))return!0;return!1}function vm(t){for(let e of Wr)if(e.test(t))return!0;return!1}function Sm(t){if(process.env.NEX_UNPROTECT==="1"||!$m.test(t))return null;for(let e of hc)if(e.test(t))return e;return null}function Em(t,e={}){if(Br)return Promise.resolve(!0);if(Fr)return Fr(t,e);if(!process.stdout.isTTY||!process.stdin.isTTY)return Tm(t,e);let s=e.toolName?["Yes","No","Always allow"]:["Yes","No"];return new Promise(o=>{let n=0;ln&&ln.pause();let r=global._nexRawWrite||(f=>process.stdout.write(f)),i=()=>{let f=process.stdout.rows||24;return Math.max(1,f-s.length-2)},c=()=>{let f=i(),p=`\x1B[${f};1H\x1B[2K${At.yellow}${t}${At.reset}`;for(let h=0;h<s.length;h++){let m=h===n,g=m?`${At.yellow}\u276F${At.reset}`:" ",$=m?`${At.yellow}${s[h]}${At.reset}`:s[h];p+=`\x1B[${f+1+h};1H\x1B[2K ${g} ${$}`}r(p)},l=f=>{process.stdin.setRawMode(!1),process.stdin.pause(),process.stdin.removeListener("data",d);let p=global._nexRawWrite||(g=>process.stdout.write(g)),h=i(),m="";for(let g=0;g<s.length+1;g++)m+=`\x1B[${h+g};1H\x1B[2K`;p(m),global._nexFooter&&global._nexFooter.drawFooter(),ln&&ln.resume(),o(f)},u=f=>{if(f===1){l(!1);return}f===2&&e.toolName&&ro(e.toolName),l(!0)},d=f=>{if(f[0]===3){l(!1);return}let p=f.toString();if(p==="\r"||p===`
|
|
52
|
+
`){u(n);return}if(p==="\x1B[A"){n=(n-1+s.length)%s.length,c();return}if(p==="\x1B[B"){n=(n+1)%s.length,c();return}let h=p.toLowerCase().trim();if(h==="y"){l(!0);return}if(h==="n"){l(!1);return}if(h==="a"&&e.toolName){ro(e.toolName),l(!0);return}};c(),process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",d)})}function Tm(t,e){let s=e.toolName?"[Y/n/a] ":"[Y/n] ";return new Promise(o=>{let n=r=>{let i=r.trim().toLowerCase();i==="a"&&e.toolName?(ro(e.toolName),o(!0)):o(i!=="n")};if(ln)ln.question(`${At.yellow}${t} ${s}${At.reset}`,n);else{let r=hm.createInterface({input:process.stdin,output:process.stdout});r.question(`${At.yellow}${t} ${s}${At.reset}`,i=>{r.close(),n(i)})}})}var ro=()=>{};function Rm(t){ro=t}wc.exports={FORBIDDEN_PATTERNS:Ur,SSH_FORBIDDEN_PATTERNS:mc,BASH_PROTECTED_PATHS:hc,SSH_SAFE_PATTERNS:qr,isSSHReadOnly:gc,DANGEROUS_BASH:yc,CRITICAL_BASH:Wr,NOTABLE_BASH:$c,isForbidden:xm,isSSHForbidden:gm,isDangerous:km,isCritical:vm,isBashPathForbidden:Sm,confirm:Em,setAutoConfirm:ym,getAutoConfirm:bm,setConfirmHook:wm,setReadlineInterface:_m,setAllowAlwaysHandler:Rm}});var Cn=G((hx,bc)=>{async function Cm(t,e){if(!t.response?.data)return t.message;let s=t.response.data;if(typeof s=="object"&&s!==null&&typeof s.pipe!="function")return e(s)||t.message;try{let o=await new Promise((r,i)=>{let c=[];s.on("data",l=>c.push(l)),s.on("end",()=>r(Buffer.concat(c).toString("utf8"))),s.on("error",i)}),n=JSON.parse(o);return e(n)||o||t.message}catch{return t.message}}var Hr=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`)}};bc.exports={BaseProvider:Hr,readStreamErrorBody:Cm}});var kc=G((gx,xc)=>{var io=require("axios"),Am=require("http"),Om=require("https"),{BaseProvider:Nm,readStreamErrorBody:Mm}=Cn(),ao=new Am.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),co=new Om.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),_c={"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}},Gr=class extends Nm{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||_c,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){io.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:ao,httpsAgent:co}).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 io.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:ao,httpsAgent:co})).data?.models||[];for(let o of s){let n=(o.name||o.model||"").replace(/:latest$/,"");!n||this.models[n]||(this.models[n]={id:n,name:o.name||n,maxTokens:16384,contextWindow:131072})}}catch{}}}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OLLAMA_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OLLAMA_API_KEY not set");return{Authorization:`Bearer ${e}`}}_formatMessages(e){return e.map(s=>{if(s.role==="user"&&Array.isArray(s.content)){let o=[],n=[];for(let i of s.content)i.type==="text"?o.push(i.text??""):i.type==="image"&&i.data&&n.push(i.data);let r={role:"user",content:o.join(`
|
|
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),i=o.maxTokens||r?.maxTokens||16384,c;try{c=await io.post(`${this.baseUrl}/api/chat`,{model:n,messages:this._formatMessages(e),tools:s&&s.length>0?s:void 0,stream:!1,options:{temperature:o.temperature??this.temperature,num_predict:i}},{timeout:o.timeout||this.timeout,headers:this._getHeaders(),httpAgent:ao,httpsAgent:co})}catch(l){if(l.name==="CanceledError"||l.name==="AbortError"||l.code==="ERR_CANCELED")throw l;let u=l.response?.status?` [HTTP ${l.response.status}]`:"",d=l.response?.data?.error||l.message;throw new Error(`API Error${u}: ${d}`)}return this.normalizeResponse(c.data)}async stream(e,s,o={}){await this.discoverModels();let n=o.model||this.defaultModel,r=this.getModel(n),i=o.maxTokens||r?.maxTokens||16384,c=o.onToken||(()=>{}),l=o.onThinkingToken||(()=>{}),u;try{u=await io.post(`${this.baseUrl}/api/chat`,{model:n,messages:this._formatMessages(e),tools:s&&s.length>0?s:void 0,stream:!0,options:{temperature:o.temperature??this.temperature,num_predict:i}},{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal,httpAgent:ao,httpsAgent:co})}catch(d){if(d.name==="CanceledError"||d.name==="AbortError"||d.code==="ERR_CANCELED")throw d;let f=d.response?.status?` [HTTP ${d.response.status}]`:"",p=await Mm(d,h=>h?.error);throw new Error(`API Error${f}: ${p}`)}return new Promise((d,f)=>{let p="",h=[],m="";o.signal&&o.signal.addEventListener("abort",()=>{u.data.destroy(),f(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",g=>{m+=g.toString();let $=m.split(`
|
|
54
|
+
`);m=$.pop()||"";for(let y of $){if(!y.trim())continue;let x;try{x=JSON.parse(y)}catch{continue}if(x.message?.thinking&&l(x.message.thinking),x.message?.content&&(c(x.message.content),p+=x.message.content),x.message?.tool_calls&&(h=h.concat(x.message.tool_calls)),x.done){d({content:p,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(m.trim())try{let g=JSON.parse(m);g.message?.thinking&&l(g.message.thinking),g.message?.content&&(c(g.message.content),p+=g.message.content),g.message?.tool_calls&&(h=h.concat(g.message.tool_calls))}catch{}d({content:p,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||{}}}))}};xc.exports={OllamaProvider:Gr,OLLAMA_MODELS:_c}});var Cc=G(($x,Rc)=>{var{callChat:Pm}=Se(),{estimateTokens:Kr}=He(),vc=process.env.NEX_COMPACTION!=="false",Sc=6,Ec=500,Im=`Summarize this conversation history concisely. Focus on:
|
|
54
55
|
- What files were read, created, or modified
|
|
55
56
|
- Key decisions made and their rationale
|
|
56
57
|
- Current state of the task (what's done, what's pending)
|
|
57
58
|
- Any errors encountered and how they were resolved
|
|
58
|
-
Be factual and brief. Use bullet points. Max 300 words.`;async function
|
|
59
|
-
${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 Lm(t){if(!vc||t.length<Sc)return null;let e=[{role:"system",content:Im},{role:"user",content:Tc(t)}];try{let o=((await Pm(e,[],{temperature:0,maxTokens:Ec})).content||"").trim();if(!o)return null;let n=t.reduce((i,c)=>i+Kr(c.content||"")+(c.tool_calls?Kr(JSON.stringify(c.tool_calls)):0),0),r=Kr(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 Tc(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}
|
|
60
61
|
tools: ${n}`}return`[${s}] ${o}`}).join(`
|
|
61
62
|
|
|
62
|
-
`)}
|
|
63
|
-
`);if(n.length<=10){let
|
|
63
|
+
`)}Rc.exports={compactMessages:Lm,formatMessagesForSummary:Tc,COMPACTION_ENABLED:vc,COMPACTION_MIN_MESSAGES:Sc,COMPACTION_SUMMARY_BUDGET:Ec}});var He=G((yx,Dc)=>{var jm=require("path");function Oc(){return Se().getActiveModel()}var Dm={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},un=new Map,Ac=1e3,Yr=new WeakMap,is=null;function qm(){if(is!==null)return is;try{let e=Oc()?.provider||"ollama";return is=Dm[e]||4,is}catch{return 4}}function Fm(){is=null}function dn(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=un.get(e);if(s!==void 0)return un.delete(e),un.set(e,s),s;let o=Math.ceil(t.length/qm());if(un.size>=Ac){let n=Ac>>1,r=un.keys();for(let i=0;i<n;i++)un.delete(r.next().value)}return un.set(e,o),o}function Um(t){if(Yr.has(t))return Yr.get(t);let e=JSON.stringify(t);return Yr.set(t,e),e}function On(t){let s=4;if(t.content&&(s+=dn(t.content)),t.tool_calls)for(let o of t.tool_calls){s+=4,s+=dn(o.function?.name||"");let n=o.function?.arguments;typeof n=="string"?s+=dn(n):n&&(s+=dn(JSON.stringify(n)))}return s}function $t(t){let e=0;for(let s of t)e+=On(s);return e}function Wm(t,e){if(t&&t.length===e.length){let r=!1;for(let i=0;i<e.length;i++)if(t[i]!==e[i]){r=!0;break}if(!r)return 0}let s=t?t.length:0,o=e.length,n=0;for(let r=s;r<o;r++)n+=On(e[r]);return n}function lo(t){return!t||t.length===0?0:dn(JSON.stringify(t))}function uo(){return Oc()?.contextWindow||32768}function Bm(t,e){let s=$t(t),o=lo(e),n=s+o,r=uo(),i=r>0?n/r*100:0,c=0,l=0,u=0;for(let d of t){let f=On(d);d.role==="system"?c+=f:d.role==="tool"?u+=f:l+=f}return{used:n,limit:r,percentage:Math.round(i*10)/10,breakdown:{system:c,conversation:l,toolResults:u,toolDefinitions:o},messageCount:t.length}}var Nc=parseFloat(process.env.NEX_COMPRESSION_THRESHOLD)||.75,Mc=parseFloat(process.env.NEX_SAFETY_MARGIN)||.1,Pc=parseInt(process.env.NEX_KEEP_RECENT,10)||10,Hm=200,Gm=500;function Ic(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
|
+
`);if(n.length<=10){let m=Math.floor(o*.6),g=Math.floor(o*.4),$=t.substring(0,m),y=t.substring(t.length-g);return $+`
|
|
64
65
|
...(${t.length} chars total)...
|
|
65
|
-
|
|
66
|
+
`+y}let r=Math.floor(n.length*.4),i=Math.floor(n.length*.4),c=[],l=0,u=Math.floor(o*.4);for(let m=0;m<r&&l<u;m++)if(l+n[m].length+1>u&&n[m].trim().startsWith("```")){c.push(n[m]),l+=n[m].length+1;let g=m+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),m=g}else c.push(n[m]),l+=n[m].length+1;let d=[],f=0,p=Math.floor(o*.4);for(let m=n.length-1;m>=n.length-i&&f<p;m--)if(f+n[m].length+1>p&&n[m].trim().startsWith("```")){d.push(n[m]),f+=n[m].length+1;let g=m-1;for(;g>=0&&f<p*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),m=g}else d.push(n[m]),f+=n[m].length+1;d.reverse();let h=n.length-c.length-d.length;return c.join(`
|
|
66
67
|
`)+`
|
|
67
68
|
...(${h} lines omitted, ${n.length} total)...
|
|
68
69
|
`+d.join(`
|
|
69
|
-
`)}function
|
|
70
|
-
...(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
|
|
70
|
+
`)}function An(t,e="light"){let s=e==="aggressive"?100:e==="medium"?200:Gm,o=e==="aggressive"?50:e==="medium"?100:Hm;if(t.role==="tool"){let n=typeof t.content=="string"?t.content:JSON.stringify(t.content);return n.length>o?{...t,content:Ic(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 Lc(t,e,s,o){let n=0;if(t.role==="system")return 100;if(t.role==="user")n+=35;else if(t.role==="tool"){let i=typeof t.content=="string"?t.content:JSON.stringify(t.content||"");/^(ERROR|BLOCKED|CANCELLED)/i.test(i)?n+=30:n+=15}else t.role==="assistant"&&(n+=t.tool_calls?20:10);let r=s>1?e/(s-1):1;if(n+=Math.round(r*30),o&&o.size>0){let i=typeof t.content=="string"?t.content:JSON.stringify(t.content||""),c=0;for(let l of o)(i.includes(l)||i.includes(jm.basename(l)))&&c++;n+=Math.min(30,c*10)}return Math.min(100,n)}function jc(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 Km(t,e,s={}){let o=s.threshold??Nc,n=s.safetyMargin??Mc,r=s.keepRecent??Pc,i=uo(),c=lo(e),l=Math.floor(i*(o-n)),u=l-c,d=$t(t),f=d+c;if(f<=l)return{messages:t,compressed:!1,compacted:!1,tokensRemoved:0};let p=d,h=null,m=0;t.length>0&&t[0].role==="system"&&(h=t[0],m=1);let g=Math.max(m,t.length-r),$=t.slice(m,g),y=t.slice(g),x=$.filter(P=>!P._compacted);if(x.length>=6)try{let{compactMessages:P}=Cc(),F=await P(x);if(F){let me=[...$.filter(D=>D._compacted),F.message],A=zt(h,me,y),M=$t(A);if(M+c<=l)return{messages:A,compressed:!0,compacted:!0,tokensRemoved:p-M};$=me}}catch(P){process.env.NEX_DEBUG&&console.error("[context-engine] LLM compacting failed:",P.message)}let _=(f-l)/l,v=$.map(P=>An(P,"light")),b=zt(h,v,y),k=$t(b);if(k+c<=l)return{messages:b,compressed:!0,compacted:!1,tokensRemoved:p-k};if(v=$.map(P=>An(P,"medium")),b=zt(h,v,y),k=$t(b),k+c<=l)return{messages:b,compressed:!0,compacted:!1,tokensRemoved:p-k};if(v=$.map(P=>An(P,"aggressive")),b=zt(h,v,y),k=$t(b),k+c<=l)return{messages:b,compressed:!0,compacted:!1,tokensRemoved:p-k};let R=jc([...v,...y]),O=v.map((P,F)=>({msg:P,score:Lc(P,F,v.length,R),tokens:On(P)}));for(;O.length>0&&k>u;){let P=0;for(let F=1;F<O.length;F++)O[F].score<O[P].score&&(P=F);k-=O[P].tokens,O.splice(P,1)}return v=O.map(P=>P.msg),b=zt(h,v,y),k=$t(b),{messages:b,compressed:!0,compacted:!1,tokensRemoved:p-k}}function zt(t,e,s){let o=[];return t&&o.push(t),o.push(...e,...s),o}function Ym(t,e){if(!t)return"";if(dn(t)<=e)return t;let o=e*4,n=t.split(`
|
|
71
72
|
`),r=Math.floor(o*.6),i=Math.floor(o*.4),c="",l=0;for(let h of n){if(c.length+h.length+1>r)break;c+=(c?`
|
|
72
|
-
`:"")+h,l++}let u="",d=0;for(let h=n.length-1;h>=l;h--){let
|
|
73
|
-
`:"")+u;if(
|
|
73
|
+
`:"")+h,l++}let u="",d=0;for(let h=n.length-1;h>=l;h--){let m=n[h]+(u?`
|
|
74
|
+
`:"")+u;if(m.length>i)break;u=m,d++}let p=`
|
|
74
75
|
|
|
75
76
|
... (${n.length-l-d} lines omitted, ${n.length} total) ...
|
|
76
77
|
|
|
77
|
-
`;return c+
|
|
78
|
-
`);g
|
|
79
|
-
|
|
80
|
-
`:"")+n.content;continue}if(n.role!=="system"&&n.role!=="tool"&&this._messageFormatCache.has(n)){o.push(this._messageFormatCache.get(n));continue}let r=this._formatSingleMessage(n,o);if(r){if(n.role!=="system"&&n.role!=="tool"&&this._messageStringCache.size<this._maxCacheSize){let i=this._getMessageCacheKey(n);this._messageStringCache.set(i,r),this._messageFormatCache.set(n,r)}o.push(r)}}return{messages:o,system:s}}_getMessageCacheKey(e){let s=e.role||"",o=typeof e.content=="string"?e.content.substring(0,100):"",n=e.tool_calls?e.tool_calls.length:0;return`${s}:${o.length}:${n}`}_formatSingleMessage(e,s=[]){if(e.role==="assistant"){let o=[];if(e.content&&o.push({type:"text",text:e.content}),e.tool_calls)for(let n of e.tool_calls)o.push({type:"tool_use",id:n.id||`toolu-${Date.now()}`,name:n.function.name,input:typeof n.function.arguments=="string"?JSON.parse(n.function.arguments||"{}"):n.function.arguments||{}});return{role:"assistant",content:o.length>0?o:[{type:"text",text:""}]}}if(e.role==="tool"){let o=s[s.length-1],n={type:"tool_result",tool_use_id:e.tool_call_id,content:typeof e.content=="string"?e.content:JSON.stringify(e.content)};return o&&o.role==="user"&&Array.isArray(o.content)&&o.content[0]?.type==="tool_result"?(o.content.push(n),null):{role:"user",content:[n]}}if(Array.isArray(e.content)){let o=[];for(let n of e.content)n.type==="text"?o.push({type:"text",text:n.text??""}):n.type==="image"&&n.data&&o.push({type:"image",source:{type:"base64",media_type:n.media_type||"image/png",data:n.data}});return{role:"user",content:o}}return{role:"user",content:e.content}}formatTools(e){return!e||e.length===0?[]:e.map(s=>({name:s.function.name,description:s.function.description||"",input_schema:s.function.parameters||{type:"object",properties:{}}}))}_resolveModelId(e){return this.getModel(e)?.id||e}async chat(e,s,o={}){let n=o.model||this.defaultModel,r=this._resolveModelId(n),i=this.getModel(n),c=o.maxTokens||i?.maxTokens||8192,{messages:l,system:u}=this.formatMessages(e),d={model:r,messages:l,max_tokens:c,temperature:o.temperature??this.temperature};u&&(d.system=u);let f=this.formatTools(s);f.length>0&&(d.tools=f);let
|
|
81
|
-
`);
|
|
82
|
-
`);g
|
|
83
|
-
`)};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
|
|
84
|
-
`);f=h.pop()||"";for(let
|
|
85
|
-
`)}}function
|
|
86
|
-
`)}function
|
|
87
|
-
`),c}catch(c){throw n.stop(),c}}async function
|
|
78
|
+
`;return c+p+u}var zm=6;function Xm(t,e,s=!1){let o=uo(),n=lo(e),r=Math.floor(o*(s?.35:.5))-n,i=$t(t),c=Math.floor(i*(s?.5:.8));r>c&&(r=c);let l=null,u=0;t.length>0&&t[0].role==="system"&&(l=t[0],u=1);let d=s?2:zm,f=Math.max(u,t.length-d),p=t.slice(u,f),h=t.slice(f),m=p.map(b=>An(b,"aggressive"));s&&(h=h.map(b=>An(b,"aggressive")));let g=zt(l,m,h),$=$t(g);for(;m.length>0&&$>r;){let b=m.shift();$-=On(b)}s&&$>r&&(h=h.filter(k=>k.role==="user").slice(-1),g=zt(l,[],h),$=$t(g)),g=zt(l,m,h);let y=t.filter(b=>b.role==="user"),x=b=>{let k=typeof b.content=="string"?b.content:"";return k.startsWith("[SYSTEM WARNING]")||k.startsWith("[SYSTEM:")||k.startsWith("BLOCKED:")},_=y.find(b=>!x(b)),v=[...y].reverse().find(b=>!x(b));if(_&&!g.find(b=>b===_)){let b=g.findIndex(R=>R.role==="system"),k=b>=0?b+1:0;g.splice(k,0,_)}return v&&v!==_&&!g.find(b=>b===v)&&g.push(v),{messages:g,tokensRemoved:i-$t(g)}}Dc.exports={estimateTokens:dn,estimateMessageTokens:On,estimateMessagesTokens:$t,estimateDeltaTokens:Wm,estimateToolsTokens:lo,serializeMessage:Um,getContextWindow:uo,getUsage:Bm,compressMessage:An,compressToolResult:Ic,scoreMessageRelevance:Lc,extractActiveFiles:jc,fitToContext:Km,forceCompress:Xm,truncateFileContent:Ym,invalidateTokenRatioCache:Fm,COMPRESSION_THRESHOLD:Nc,SAFETY_MARGIN:Mc,KEEP_RECENT:Pc}});var Wc=G((bx,Uc)=>{var qc=require("axios"),{BaseProvider:Jm,readStreamErrorBody:Vm}=Cn(),{serializeMessage:wx}=He(),Fc={"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}},zr=class extends Jm{constructor(e={}){super({name:"openai",baseUrl:e.baseUrl||"https://api.openai.com/v1",models:e.models||Fc,defaultModel:e.defaultModel||"gpt-4o",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OPENAI_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OPENAI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let s=[];for(let o of e){if(this._messageFormatCache.has(o)){s.push(this._messageFormatCache.get(o));continue}let n=this._getMessageCacheKey(o);if(this._messageStringCache.has(n)){let i=this._messageStringCache.get(n);this._messageFormatCache.set(o,i),s.push(i);continue}let r=this._formatSingleMessage(o);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(n,r),this._messageFormatCache.set(o,r),s.push(r)}return{messages:s}}_getMessageCacheKey(e){let s=e.role||"",o=typeof e.content=="string"?e.content.substring(0,100):"",n=e.tool_calls?e.tool_calls.length:0;return`${s}:${o.length}:${n}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||null,tool_calls:e.tool_calls.map(s=>({id:s.id||`call-${Date.now()}`,type:"function",function:{name:s.function.name,arguments:typeof s.function.arguments=="string"?s.function.arguments:JSON.stringify(s.function.arguments)}}))};if(e.role==="tool")return{role:"tool",content:typeof e.content=="string"?e.content:JSON.stringify(e.content),tool_call_id:e.tool_call_id};if(e.role==="user"&&Array.isArray(e.content)){let s=[];for(let o of e.content)if(o.type==="text")s.push({type:"text",text:o.text??""});else if(o.type==="image"&&o.data){let n=o.data.startsWith("data:")?o.data:`data:${o.media_type||"image/png"};base64,${o.data}`;s.push({type:"image_url",image_url:{url:n,detail:"auto"}})}return{role:"user",content:s}}return{role:e.role,content:e.content}}async chat(e,s,o={}){let n=o.model||this.defaultModel,r=this.getModel(n),i=o.maxTokens||r?.maxTokens||16384,{messages:c}=this.formatMessages(e),l={model:n,messages:c,max_tokens:i,temperature:o.temperature??this.temperature};s&&s.length>0&&(l.tools=s);let u;try{u=await qc.post(`${this.baseUrl}/chat/completions`,l,{timeout:o.timeout||this.timeout,headers:this._getHeaders()})}catch(d){if(d.name==="CanceledError"||d.name==="AbortError"||d.code==="ERR_CANCELED")throw d;let f=d.response?.status?` [HTTP ${d.response.status}]`:"",p=d.response?.data?.error?.message||d.response?.data?.error||d.message;throw new Error(`API Error${f}: ${p}`)}return this.normalizeResponse(u.data)}async stream(e,s,o={}){let n=o.model||this.defaultModel,r=this.getModel(n),i=o.maxTokens||r?.maxTokens||16384,c=o.onToken||(()=>{}),{messages:l}=this.formatMessages(e),u={model:n,messages:l,max_tokens:i,temperature:o.temperature??this.temperature,stream:!0};s&&s.length>0&&(u.tools=s);let d;try{d=await qc.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 p=f.response?.status?` [HTTP ${f.response.status}]`:"",h=await Vm(f,m=>m?.error?.message||m?.error);throw new Error(`API Error${p}: ${h}`)}return new Promise((f,p)=>{let h="",m={},g="";o.signal&&o.signal.addEventListener("abort",()=>{d.data.destroy(),p(new DOMException("The operation was aborted","AbortError"))},{once:!0}),d.data.on("data",$=>{g+=$.toString();let y=g.split(`
|
|
79
|
+
`);g=y.pop()||"";for(let x of y){let _=x.trim();if(!_||!_.startsWith("data: "))continue;let v=_.slice(6);if(v==="[DONE]"){f({content:h,tool_calls:this._buildToolCalls(m)});return}let b;try{b=JSON.parse(v)}catch{continue}let k=b.choices?.[0]?.delta;if(k&&(k.content&&(c(k.content),h+=k.content),k.tool_calls))for(let R of k.tool_calls){let O=R.index??0;m[O]||(m[O]={id:R.id||"",name:"",arguments:""}),R.id&&(m[O].id=R.id),R.function?.name&&(m[O].name+=R.function.name),R.function?.arguments&&(m[O].arguments+=R.function.arguments)}}}),d.data.on("error",$=>{o.signal?.aborted||p(new Error(`Stream error: ${$.message}`))}),d.data.on("end",()=>{f({content:h,tool_calls:this._buildToolCalls(m)})})})}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}}))}};Uc.exports={OpenAIProvider:zr,OPENAI_MODELS:Fc}});var Kc=G((xx,Gc)=>{var Bc=require("axios"),{BaseProvider:Qm,readStreamErrorBody:Zm}=Cn(),{serializeMessage:_x}=He(),Hc={"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}},eh="2023-06-01",Xr=class extends Qm{constructor(e={}){super({name:"anthropic",baseUrl:e.baseUrl||"https://api.anthropic.com/v1",models:e.models||Hc,defaultModel:e.defaultModel||"claude-sonnet",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this.apiVersion=e.apiVersion||eh}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 i=this._getMessageCacheKey(n);this._messageStringCache.set(i,r),this._messageFormatCache.set(n,r)}o.push(r)}}return{messages:o,system:s}}_getMessageCacheKey(e){let s=e.role||"",o=typeof e.content=="string"?e.content.substring(0,100):"",n=e.tool_calls?e.tool_calls.length:0;return`${s}:${o.length}:${n}`}_formatSingleMessage(e,s=[]){if(e.role==="assistant"){let o=[];if(e.content&&o.push({type:"text",text:e.content}),e.tool_calls)for(let n of e.tool_calls)o.push({type:"tool_use",id:n.id||`toolu-${Date.now()}`,name:n.function.name,input:typeof n.function.arguments=="string"?JSON.parse(n.function.arguments||"{}"):n.function.arguments||{}});return{role:"assistant",content:o.length>0?o:[{type:"text",text:""}]}}if(e.role==="tool"){let o=s[s.length-1],n={type:"tool_result",tool_use_id:e.tool_call_id,content:typeof e.content=="string"?e.content:JSON.stringify(e.content)};return o&&o.role==="user"&&Array.isArray(o.content)&&o.content[0]?.type==="tool_result"?(o.content.push(n),null):{role:"user",content:[n]}}if(Array.isArray(e.content)){let o=[];for(let n of e.content)n.type==="text"?o.push({type:"text",text:n.text??""}):n.type==="image"&&n.data&&o.push({type:"image",source:{type:"base64",media_type:n.media_type||"image/png",data:n.data}});return{role:"user",content:o}}return{role:"user",content:e.content}}formatTools(e){return!e||e.length===0?[]:e.map(s=>({name:s.function.name,description:s.function.description||"",input_schema:s.function.parameters||{type:"object",properties:{}}}))}_resolveModelId(e){return this.getModel(e)?.id||e}async chat(e,s,o={}){let n=o.model||this.defaultModel,r=this._resolveModelId(n),i=this.getModel(n),c=o.maxTokens||i?.maxTokens||8192,{messages:l,system:u}=this.formatMessages(e),d={model:r,messages:l,max_tokens:c,temperature:o.temperature??this.temperature};u&&(d.system=u);let f=this.formatTools(s);f.length>0&&(d.tools=f);let p;try{p=await Bc.post(`${this.baseUrl}/messages`,d,{timeout:o.timeout||this.timeout,headers:this._getHeaders()})}catch(h){if(h.name==="CanceledError"||h.name==="AbortError"||h.code==="ERR_CANCELED")throw h;let m=h.response?.status?` [HTTP ${h.response.status}]`:"",g=h.response?.data?.error?.message||h.response?.data?.error||h.message;throw new Error(`API Error${m}: ${g}`)}return this.normalizeResponse(p.data)}async stream(e,s,o={}){let n=o.model||this.defaultModel,r=this._resolveModelId(n),i=this.getModel(n),c=o.maxTokens||i?.maxTokens||8192,l=o.onToken||(()=>{}),{messages:u,system:d}=this.formatMessages(e),f={model:r,messages:u,max_tokens:c,temperature:o.temperature??this.temperature,stream:!0};d&&(f.system=d);let p=this.formatTools(s);p.length>0&&(f.tools=p);let h;try{h=await Bc.post(`${this.baseUrl}/messages`,f,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal})}catch(m){if(m.name==="CanceledError"||m.name==="AbortError"||m.code==="ERR_CANCELED")throw m;let g=m.response?.status?` [HTTP ${m.response.status}]`:"",$=await Zm(m,y=>y?.error?.message||y?.error);throw new Error(`API Error${g}: ${$}`)}return new Promise((m,g)=>{let $="",y=[],x=-1,_="";o.signal&&o.signal.addEventListener("abort",()=>{h.data.destroy(),g(new DOMException("The operation was aborted","AbortError"))},{once:!0}),h.data.on("data",v=>{_+=v.toString();let b=_.split(`
|
|
82
|
+
`);_=b.pop()||"";for(let k of b){let R=k.trim();if(R.startsWith("data: ")){let O=R.slice(6),P;try{P=JSON.parse(O)}catch{continue}switch(P.type){case"content_block_start":{let F=P.content_block;F?.type==="tool_use"&&(x=y.length,y.push({id:F.id,name:F.name,inputJson:""}));break}case"content_block_delta":{let F=P.delta;F?.type==="text_delta"&&F.text&&(l(F.text),$+=F.text),F?.type==="input_json_delta"&&F.partial_json!==void 0&&x>=0&&(y[x].inputJson+=F.partial_json);break}case"content_block_stop":x=-1;break;case"message_stop":m({content:$,tool_calls:this._buildToolCalls(y)});return}}}}),h.data.on("error",v=>{o.signal?.aborted||g(new Error(`Stream error: ${v.message}`))}),h.data.on("end",()=>{m({content:$,tool_calls:this._buildToolCalls(y)})})})}normalizeResponse(e){let s="",o=[];for(let n of e.content||[])n.type==="text"?s+=n.text:n.type==="tool_use"&&o.push({id:n.id,function:{name:n.name,arguments:n.input}});return{content:s,tool_calls:o}}_buildToolCalls(e){return e.filter(s=>s.name).map(s=>{let o={};if(s.inputJson)try{o=JSON.parse(s.inputJson)}catch{o=s.inputJson}return{id:s.id||`anthropic-${Date.now()}`,function:{name:s.name,arguments:o}}})}};Gc.exports={AnthropicProvider:Xr,ANTHROPIC_MODELS:Hc}});var Jc=G((vx,Xc)=>{var Yc=require("axios"),{BaseProvider:th,readStreamErrorBody:nh}=Cn(),{serializeMessage:kx}=He(),zc={"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}},Jr=class extends th{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||zc,defaultModel:e.defaultModel||"gemini-2.5-flash",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("GEMINI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let s=[];for(let o of e){if(this._messageFormatCache.has(o)){s.push(this._messageFormatCache.get(o));continue}let n=this._getMessageCacheKey(o);if(this._messageStringCache.has(n)){let i=this._messageStringCache.get(n);this._messageFormatCache.set(o,i),s.push(i);continue}let r=this._formatSingleMessage(o);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(n,r),this._messageFormatCache.set(o,r),s.push(r)}return{messages:s}}_getMessageCacheKey(e){let s=e.role||"",o=typeof e.content=="string"?e.content.substring(0,100):"",n=e.tool_calls?e.tool_calls.length:0;return`${s}:${o.length}:${n}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||"",tool_calls:e.tool_calls.map(s=>({id:s.id||`call-${Date.now()}`,type:"function",function:{name:s.function.name,arguments:typeof s.function.arguments=="string"?s.function.arguments:JSON.stringify(s.function.arguments)}}))};if(e.role==="tool")return{role:"tool",content:typeof e.content=="string"?e.content:JSON.stringify(e.content),tool_call_id:e.tool_call_id};if(e.role==="user"&&Array.isArray(e.content)){let s=[];for(let o of e.content)if(o.type==="text")s.push({type:"text",text:o.text??""});else if(o.type==="image"&&o.data){let n=o.data.startsWith("data:")?o.data:`data:${o.media_type||"image/png"};base64,${o.data}`;s.push({type:"image_url",image_url:{url:n,detail:"auto"}})}return{role:"user",content:s}}return{role:e.role,content:e.content}}async chat(e,s,o={}){let n=o.model||this.defaultModel,r=this.getModel(n),i=o.maxTokens||r?.maxTokens||8192,{messages:c}=this.formatMessages(e),l={model:n,messages:c,max_tokens:i,temperature:o.temperature??this.temperature};s&&s.length>0&&(l.tools=s);let u;try{u=await Yc.post(`${this.baseUrl}/chat/completions`,l,{timeout:o.timeout||this.timeout,headers:this._getHeaders()})}catch(d){if(d.name==="CanceledError"||d.name==="AbortError"||d.code==="ERR_CANCELED")throw d;let f=d.response?.status?` [HTTP ${d.response.status}]`:"",p=d.response?.data?.error?.message||d.response?.data?.error||d.message;throw new Error(`API Error${f}: ${p}`)}return this.normalizeResponse(u.data)}async stream(e,s,o={}){let n=o.model||this.defaultModel,r=this.getModel(n),i=o.maxTokens||r?.maxTokens||8192,c=o.onToken||(()=>{}),{messages:l}=this.formatMessages(e),u={model:n,messages:l,max_tokens:i,temperature:o.temperature??this.temperature,stream:!0};s&&s.length>0&&(u.tools=s);let d;try{d=await Yc.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 p=f.response?.status?` [HTTP ${f.response.status}]`:"",h=await nh(f,m=>m?.error?.message||m?.error);throw new Error(`API Error${p}: ${h}`)}return new Promise((f,p)=>{let h="",m={},g="";o.signal&&o.signal.addEventListener("abort",()=>{d.data.destroy(),p(new DOMException("The operation was aborted","AbortError"))},{once:!0}),d.data.on("data",$=>{g+=$.toString();let y=g.split(`
|
|
83
|
+
`);g=y.pop()||"";for(let x of y){let _=x.trim();if(!_||!_.startsWith("data: "))continue;let v=_.slice(6);if(v==="[DONE]"){f({content:h,tool_calls:this._buildToolCalls(m)});return}let b;try{b=JSON.parse(v)}catch{continue}let k=b.choices?.[0]?.delta;if(k&&(k.content&&(c(k.content),h+=k.content),k.tool_calls))for(let R of k.tool_calls){let O=R.index??0;m[O]||(m[O]={id:R.id||"",name:"",arguments:""}),R.id&&(m[O].id=R.id),R.function?.name&&(m[O].name+=R.function.name),R.function?.arguments&&(m[O].arguments+=R.function.arguments)}}}),d.data.on("error",$=>{o.signal?.aborted||p(new Error(`Stream error: ${$.message}`))}),d.data.on("end",()=>{f({content:h,tool_calls:this._buildToolCalls(m)})})})}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}}))}};Xc.exports={GeminiProvider:Jr,GEMINI_MODELS:zc}});var Zc=G((Sx,Qc)=>{var fo=require("axios"),{BaseProvider:sh,readStreamErrorBody:oh}=Cn(),Vc="http://localhost:11434",Vr=class extends sh{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||Vc,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 fo.get(`${this.baseUrl}/api/tags`,{timeout:5e3})).data?.models||[];this.models={};for(let o of s){let n=o.name||o.model;if(!n)continue;let r=n.replace(/:latest$/,""),i=32768;try{let c=await fo.post(`${this.baseUrl}/api/show`,{name:n},{timeout:5e3}),l=c.data?.model_info||c.data?.details||{};i=l["general.context_length"]||l["llama.context_length"]||this._parseContextFromModelfile(c.data?.modelfile)||32768}catch{}this.models[r]={id:r,name:o.name,maxTokens:Math.min(8192,Math.floor(i*.1)),contextWindow:i}}!this.defaultModel&&Object.keys(this.models).length>0&&(this.defaultModel=Object.keys(this.models)[0]),this._modelsLoaded=!0}catch{this.models={},this._modelsLoaded=!1}return this.models}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}_formatMessages(e){return e.map(s=>{if(s.role==="user"&&Array.isArray(s.content)){let o=[],n=[];for(let i of s.content)i.type==="text"?o.push(i.text??""):i.type==="image"&&i.data&&n.push(i.data);let r={role:"user",content:o.join(`
|
|
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;try{r=await fo.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})}catch(i){if(i.name==="CanceledError"||i.name==="AbortError"||i.code==="ERR_CANCELED")throw i;let c=i.response?.status?` [HTTP ${i.response.status}]`:"",l=i.response?.data?.error||i.message;throw new Error(`API Error${c}: ${l}`)}return this.normalizeResponse(r.data)}async stream(e,s,o={}){this._modelsLoaded||await this.loadModels();let n=o.model||this.defaultModel;if(!n)throw new Error("No local model available. Is Ollama running?");let r=o.onToken||(()=>{}),i;try{i=await fo.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?.status?` [HTTP ${c.response.status}]`:"",u=await oh(c,d=>d?.error);throw new Error(`API Error${l}: ${u}`)}return new Promise((c,l)=>{let u="",d=[],f="";o.signal&&o.signal.addEventListener("abort",()=>{i.data.destroy(),l(new DOMException("The operation was aborted","AbortError"))},{once:!0}),i.data.on("data",p=>{f+=p.toString();let h=f.split(`
|
|
85
|
+
`);f=h.pop()||"";for(let m of h){if(!m.trim())continue;let g;try{g=JSON.parse(m)}catch{continue}if(g.message?.content&&(r(g.message.content),u+=g.message.content),g.message?.tool_calls&&(d=d.concat(g.message.tool_calls)),g.done){c({content:u,tool_calls:this._normalizeToolCalls(d)});return}}}),i.data.on("error",p=>{o.signal?.aborted||l(new Error(`Stream error: ${p.message}`))}),i.data.on("end",()=>{if(f.trim())try{let p=JSON.parse(f);p.message?.content&&(r(p.message.content),u+=p.message.content),p.message?.tool_calls&&(d=d.concat(p.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||{}}}))}};Qc.exports={LocalProvider:Vr,DEFAULT_LOCAL_URL:Vc}});var Xt=G((Ex,tl)=>{"use strict";var at=require("fs"),el=require("path");function rh(t){if(!t||isNaN(t))return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function ih(t){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}catch{let e=Date.now()+t;for(;Date.now()<e;);}}function ah(t,e){let s=el.dirname(t),o=el.join(s,`.nex-tmp.${process.pid}.${Date.now()}`);try{at.existsSync(s)||at.mkdirSync(s,{recursive:!0}),at.writeFileSync(o,e,"utf-8"),at.renameSync(o,t)}catch(n){try{at.unlinkSync(o)}catch{}throw n}}function ch(t,e,{timeout:s=5e3,retryMs:o=50}={}){let n=t+".lock",r=Date.now()+s;for(;;){let i=-1;try{i=at.openSync(n,"wx"),at.writeSync(i,Buffer.from(String(process.pid))),at.closeSync(i),i=-1;try{return e()}finally{try{at.unlinkSync(n)}catch{}}}catch(c){if(i!==-1)try{at.closeSync(i)}catch{}if(c.code!=="EEXIST")throw c;try{let l=at.readFileSync(n,"utf-8").trim(),u=parseInt(l,10);if(!rh(u)){try{at.unlinkSync(n)}catch{}continue}}catch(l){if(l.code&&l.code!=="ENOENT")throw l;continue}if(Date.now()>=r){try{at.unlinkSync(n)}catch{}return e()}ih(o)}}}tl.exports={atomicWrite:ah,withFileLockSync:ch}});var Mn=G((Tx,cl)=>{var Nn=require("fs"),Qr=require("path"),{atomicWrite:lh,withFileLockSync:uh}=Xt(),nl={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:{}},po=[],Jt={};function dh(t,e,s,o){if(po.push({provider:t,model:e,input:s,output:o}),Jt[t]!==void 0){let n=il(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 Zr(t,e){let s=nl[t];return s?s[e]||{input:0,output:0}:{input:0,output:0}}function sl(t){let e=Zr(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function ol(){let t={};for(let r of po){let i=`${r.provider}:${r.model}`;t[i]||(t[i]={provider:r.provider,model:r.model,input:0,output:0}),t[i].input+=r.input,t[i].output+=r.output}let e=Object.values(t).map(r=>({...r,cost:sl(r)})),s=e.reduce((r,i)=>r+i.cost,0),o=e.reduce((r,i)=>r+i.input,0),n=e.reduce((r,i)=>r+i.output,0);return{totalCost:s,totalInput:o,totalOutput:n,breakdown:e}}function fh(){let{totalCost:t,totalInput:e,totalOutput:s,breakdown:o}=ol();if(o.length===0)return"No token usage recorded this session.";let n=[];n.push("Session Token Usage:"),n.push("");for(let r of o){let i=r.cost>0?`$${r.cost.toFixed(4)}`:"free";n.push(` ${r.provider}:${r.model}`),n.push(` Input: ${r.input.toLocaleString()} tokens`),n.push(` Output: ${r.output.toLocaleString()} tokens`),n.push(` Cost: ${i}`)}return n.push(""),n.push(` Total: ${e.toLocaleString()} in + ${s.toLocaleString()} out = $${t.toFixed(4)}`),n.join(`
|
|
87
|
+
`)}function ph(t,e,s,o){let n=Zr(t,e),r=(s*n.input+o*n.output)/1e6;return r<=0?"":`[~$${r.toFixed(4)}]`}function mh(){po=[]}function hh(t,e){Jt[t]=e}function gh(t){delete Jt[t]}function $h(){return{...Jt}}function rl(t){let e=0;for(let s of po)s.provider===t&&(e+=sl(s));return e}function il(t){let e=rl(t),s=Jt[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 al(){let t=Qr.join(process.cwd(),".nex","config.json");if(Nn.existsSync(t))try{let e=JSON.parse(Nn.readFileSync(t,"utf-8"));e.costLimits&&typeof e.costLimits=="object"&&(Jt={...e.costLimits})}catch{}}function yh(){let t=Qr.join(process.cwd(),".nex"),e=Qr.join(t,"config.json");Nn.existsSync(t)||Nn.mkdirSync(t,{recursive:!0}),uh(e,()=>{let s={};if(Nn.existsSync(e))try{s=JSON.parse(Nn.readFileSync(e,"utf-8"))}catch{s={}}s.costLimits=Jt,lh(e,JSON.stringify(s,null,2))})}function wh(){Jt={}}al();cl.exports={PRICING:nl,trackUsage:dh,getSessionCosts:ol,formatCosts:fh,formatCostHint:ph,resetCosts:mh,getPricing:Zr,setCostLimit:hh,removeCostLimit:gh,getCostLimits:$h,getProviderSpend:rl,checkBudget:il,loadCostLimits:al,saveCostLimits:yh,resetCostLimits:wh}});var dl=G((Rx,ul)=>{"use strict";var bh=new Set(["read_file","grep","glob","search_files","list_directory"]),_h=new Set(["write_file","edit_file","patch_file"]),xh=new Set(["bash"]),kh=new Set(["web_search","web_fetch","perplexity_search"]);function ll(t,e){let s=0,o=0,n=0,r=0,i=0;for(let[c,l]of t)i+=l,bh.has(c)&&(s+=l),_h.has(c)&&(o+=l),xh.has(c)&&(n+=l),kh.has(c)&&(r+=l);return i===0?`Phase ${e}`:r/i>.5?"Research":s/i>.5?"Exploration":o/i>.3?"Implementation":n/i>.3&&o/i<.15?"Verification":`Phase ${e}`}var ei=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 i of s)this._phaseCounts.set(i,(this._phaseCounts.get(i)||0)+1);if(this._stepsThisPhase<this._N)return null;this._phaseNum++;let r={phaseNum:this._phaseNum,phaseName:ll(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}};ul.exports={MilestoneTracker:ei,_phaseName:ll}});var Pn=G((Cx,fl)=>{var as=Se(),vh={"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 Sh(){return as.getActiveModel()}function Eh(t){return as.setActiveModel(t)}function Th(){return as.getModelNames()}function Rh(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 Ch(t,e){let{C:s}=ve(),{Spinner:o}=ve(),n=new o("Thinking...");n.start();let r=!0,i="";try{let c=await as.callStream(t,e,{onToken:l=>{r&&(n.stop(),process.stdout.write(`${s.blue}`),r=!1),process.stdout.write(l),i+=l}});return r?n.stop():process.stdout.write(`${s.reset}
|
|
88
|
+
`),c}catch(c){throw n.stop(),c}}async function Ah(t,e){return as.callChat(t,e)}fl.exports={MODELS:vh,getActiveModel:Sh,setActiveModel:Eh,getModelNames:Th,callOllamaStream:Ch,callOllama:Ah,parseToolArgs:Rh}});var hl=G((Ox,ml)=>{var mo=require("path"),{C:N}=ve(),{T:ti,isDark:Ax}=an(),{confirm:Oh,getAutoConfirm:Nh}=Ue(),pl=2e3;function cs(t,e){let s=t.split(`
|
|
88
89
|
`),o=e.split(`
|
|
89
|
-
`),n=[],r=s.length,i=o.length;if(r>
|
|
90
|
-
${
|
|
91
|
-
${
|
|
92
|
-
${
|
|
93
|
-
`),o=s.slice(0,20);for(let n of o)console.log(`${
|
|
94
|
-
${
|
|
95
|
-
`)}function
|
|
96
|
-
${
|
|
97
|
-
`);return}let h=[];if(f>0&&h.push(`Added ${f} line${f!==1?"s":""}`),
|
|
90
|
+
`),n=[],r=s.length,i=o.length;if(r>pl||i>pl){for(let f of s)n.push({type:"remove",line:f});for(let f of o)n.push({type:"add",line:f});return n}let c=Array.from({length:r+1},()=>new Array(i+1).fill(0));for(let f=1;f<=r;f++)for(let p=1;p<=i;p++)s[f-1]===o[p-1]?c[f][p]=c[f-1][p-1]+1:c[f][p]=Math.max(c[f-1][p],c[f][p-1]);let l=r,u=i,d=[];for(;l>0||u>0;)l>0&&u>0&&s[l-1]===o[u-1]?(d.unshift({type:"same",line:s[l-1]}),l--,u--):u>0&&(l===0||c[l][u-1]>=c[l-1][u])?(d.unshift({type:"add",line:o[u-1]}),u--):(d.unshift({type:"remove",line:s[l-1]}),l--);return d}function Mh(t,e,s,o=3){console.log(`
|
|
91
|
+
${N.bold}${N.cyan} Diff: ${t}${N.reset}`);let n=cs(e,s),r=[];if(n.forEach((l,u)=>{l.type!=="same"&&r.push(u)}),r.length===0){console.log(`${N.gray} (no changes)${N.reset}`);return}let i=Math.max(0,r[0]-o),c=Math.min(n.length,r[r.length-1]+o+1);i>0&&console.log(`${N.gray} ...${N.reset}`);for(let l=i;l<c;l++){let u=n[l];switch(u.type){case"remove":console.log(`${N.red} - ${u.line}${N.reset}`);break;case"add":console.log(`${N.green} + ${u.line}${N.reset}`);break;default:console.log(`${N.gray} ${u.line}${N.reset}`)}}c<n.length&&console.log(`${N.gray} ...${N.reset}`),console.log()}function Ph(t,e,s){console.log(`
|
|
92
|
+
${N.bold}${N.cyan} File exists \u2014 showing changes: ${t}${N.reset}`);let o=cs(e,s),n=0;for(let i of o)i.type!=="same"&&n++;if(n===0){console.log(`${N.gray} (identical content)${N.reset}`);return}let r=0;for(let i of o){if(r>=30){console.log(`${N.gray} ...(${n-r} more changes)${N.reset}`);break}switch(i.type){case"remove":console.log(`${N.red} - ${i.line}${N.reset}`),r++;break;case"add":console.log(`${N.green} + ${i.line}${N.reset}`),r++;break;default:r>0&&console.log(`${N.gray} ${i.line}${N.reset}`)}}console.log()}function Ih(t,e){console.log(`
|
|
93
|
+
${N.bold}${N.cyan} New file: ${t}${N.reset}`);let s=e.split(`
|
|
94
|
+
`),o=s.slice(0,20);for(let n of o)console.log(`${N.green} + ${n}${N.reset}`);s.length>20&&console.log(`${N.gray} ...+${s.length-20} more lines${N.reset}`),console.log()}async function Lh(t){return Nh()?!0:Oh(` ${t}?`)}function jh(t,e,s,o){let n=o||process.stdout.columns||80,r=Math.floor((n-3)/2);console.log(`
|
|
95
|
+
${N.bold}${N.cyan} Side-by-side: ${t}${N.reset}`),console.log(` ${N.dim}${"\u2500".repeat(r)}\u252C${"\u2500".repeat(r)}${N.reset}`);let i=cs(e,s),c=[],l=0;for(;l<i.length;)if(i[l].type==="same")c.push({left:i[l].line,right:i[l].line,type:"same"}),l++;else if(i[l].type==="remove"){let h=[];for(;l<i.length&&i[l].type==="remove";)h.push(i[l].line),l++;let m=[];for(;l<i.length&&i[l].type==="add";)m.push(i[l].line),l++;let g=Math.max(h.length,m.length);for(let $=0;$<g;$++)c.push({left:$<h.length?h[$]:"",right:$<m.length?m[$]:"",type:"changed"})}else i[l].type==="add"&&(c.push({left:"",right:i[l].line,type:"changed"}),l++);let u=c.map((h,m)=>h.type!=="same"?m:-1).filter(h=>h>=0);if(u.length===0){console.log(` ${N.gray}(no changes)${N.reset}`);return}let d=Math.max(0,u[0]-2),f=Math.min(c.length,u[u.length-1]+3),p=(h,m)=>{let g=h.replace(/\x1b\[[0-9;]*m/g,"");return g.length>=m?h.substring(0,m):h+" ".repeat(m-g.length)};d>0&&console.log(` ${N.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${N.reset}`);for(let h=d;h<f;h++){let m=c[h];if(m.type==="same")console.log(` ${N.gray}${p(m.left,r)}${N.reset}\u2502${N.gray}${p(m.right,r)}${N.reset}`);else{let g=m.left?`${N.red}${p(m.left,r)}${N.reset}`:`${p("",r)}`,$=m.right?`${N.green}${p(m.right,r)}${N.reset}`:`${p("",r)}`;console.log(` ${g}\u2502${$}`)}}f<c.length&&console.log(` ${N.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${N.reset}`),console.log(` ${N.dim}${"\u2500".repeat(r)}\u2534${"\u2500".repeat(r)}${N.reset}
|
|
96
|
+
`)}function Dh(t,e,s,o={}){let n=o.label||"Update",r=o.context||3,i=o.annotations||[],c=mo.isAbsolute(t)?mo.relative(process.cwd(),t):t,l=cs(e,s),u=1,d=1;for(let k of l)k.type==="same"?(k.oldLine=u++,k.newLine=d++):k.type==="remove"?(k.oldLine=u++,k.newLine=null):(k.oldLine=null,k.newLine=d++);let f=0,p=0;for(let k of l)k.type==="add"?f++:k.type==="remove"&&p++;if(console.log(`
|
|
97
|
+
${N.green}\u25CF${N.reset} ${N.bold}${n}(${c})${N.reset}`),f===0&&p===0){console.log(` ${N.dim}\u2514 (no changes)${N.reset}
|
|
98
|
+
`);return}let h=[];if(f>0&&h.push(`Added ${f} line${f!==1?"s":""}`),p>0&&h.push(`removed ${p} line${p!==1?"s":""}`),i.length>0){let k=i.filter(F=>F.severity==="error").length,R=i.filter(F=>F.severity==="warn").length,O=i.filter(F=>F.severity==="info").length,P=[];k>0&&P.push(`${N.red}${k} error${k!==1?"s":""}${N.dim}`),R>0&&P.push(`${N.yellow}${R} warning${R!==1?"s":""}${N.dim}`),O>0&&P.push(`${N.cyan}${O} info${O!==1?"s":""}${N.dim}`),h.push(`found ${P.join(", ")}`)}console.log(` ${N.dim}\u2514 ${h.join(", ")}${N.reset}`);let g=[];l.forEach((k,R)=>{k.type!=="same"&&g.push(R)});let $=[],y=null,x=null;for(let k of g){let R=Math.max(0,k-r),O=Math.min(l.length-1,k+r);y===null?(y=R,x=O):(R<=x+1||($.push([y,x]),y=R),x=O)}y!==null&&$.push([y,x]);let _=" ",v=process.stdout.columns||120;function b(k,R,O){let P=O.replace(/\x1b\[[0-9;]*m/g,""),F=O+" ".repeat(Math.max(0,v-P.length));return`${k}${R}${F}${N.reset}`}for(let k=0;k<$.length;k++){k>0&&console.log(`${_}${N.dim}\xB7\xB7\xB7${N.reset}`);let[R,O]=$[k];for(let P=R;P<=O;P++){let F=l[P],De=F.newLine!=null?F.newLine:F.oldLine,me=String(De).padStart(4),A=F.type!=="remove"?i.filter(M=>M.line===F.newLine):[];F.type==="remove"?console.log(b(ti.diff_rem_bg,N.red,`${_}${me} - ${F.line}`)):F.type==="add"?console.log(b(ti.diff_add_bg,N.green,`${_}${me} + ${F.line}`)):console.log(`${_}${N.dim}${me} ${N.reset}${F.line}`);for(let M of A){let D=N.cyan,W="\u2139";M.severity==="error"?(D=N.red,W="\u2716"):M.severity==="warn"&&(D=N.yellow,W="\u26A0"),console.log(`${_} ${D}${W} ${M.message}${N.reset}`)}}}console.log()}function qh(t,e,s={}){let o=mo.isAbsolute(t)?mo.relative(process.cwd(),t):t,n=e.split(`
|
|
98
99
|
`),r=s.annotations||[];console.log(`
|
|
99
|
-
${
|
|
100
|
-
`).filter(Boolean).map(e=>{let s=e.substring(0,2).trim(),o=e.substring(3);return{status:s,file:o}})}catch{return[]}}async function
|
|
101
|
-
`);for(let f of d)f.startsWith("+")&&!f.startsWith("+++")&&n++,f.startsWith("-")&&!f.startsWith("---")&&r++}else n=t.length;let i="chore",c=t.join(" ").toLowerCase();c.includes("test")?i="test":c.includes("readme")||c.includes("doc")?i="docs":n>r*2?i="feat":r>n?i="refactor":i="fix";let l=t.slice(0,3).map(d=>d.split("/").pop());return{summary:`${i}: update ${l.join(", ")}${t.length>3?` (+${t.length-3} more)`:""}`,type:i,files:t,stats:{additions:n,deletions:r}}}async function
|
|
102
|
-
${
|
|
103
|
-
${
|
|
104
|
-
${
|
|
100
|
+
${N.green}\u25CF${N.reset} ${N.bold}Create(${o})${N.reset}`);let i=[`${n.length} line${n.length!==1?"s":""}`];if(r.length>0){let f=r.filter(g=>g.severity==="error").length,p=r.filter(g=>g.severity==="warn").length,h=r.filter(g=>g.severity==="info").length,m=[];f>0&&m.push(`${N.red}${f} error${f!==1?"s":""}${N.dim}`),p>0&&m.push(`${N.yellow}${p} warning${p!==1?"s":""}${N.dim}`),h>0&&m.push(`${N.cyan}${h} info${h!==1?"s":""}${N.dim}`),i.push(`found ${m.join(", ")}`)}console.log(` ${N.dim}\u2514 ${i.join(", ")}${N.reset}`);let l=" ",u=process.stdout.columns||120,d=Math.min(n.length,20);for(let f=0;f<d;f++){let p=String(f+1).padStart(4),h=f+1,m=r.filter(x=>x.line===h),g=`${l}${p} + ${n[f]}`,$=g.replace(/\x1b\[[0-9;]*m/g,""),y=g+" ".repeat(Math.max(0,u-$.length));console.log(`${ti.diff_add_bg}${N.green}${y}${N.reset}`);for(let x of m){let _=N.cyan,v="\u2139";x.severity==="error"?(_=N.red,v="\u2716"):x.severity==="warn"&&(_=N.yellow,v="\u26A0"),console.log(`${l} ${_}${v} ${x.message}${N.reset}`)}}n.length>20&&console.log(`${l}${N.dim} ...+${n.length-20} more lines${N.reset}`),console.log()}ml.exports={diffLines:cs,showEditDiff:Mh,showWriteDiff:Ph,showNewFilePreview:Ih,confirmFileChange:Lh,showSideBySideDiff:jh,showClaudeDiff:Dh,showClaudeNewFile:qh}});var Vt=G((Nx,yl)=>{var gl=require("util").promisify(require("child_process").exec),Fh=require("util").promisify(require("child_process").execFile),{C:ke}=ve();async function ni(t){try{let{stdout:e}=await gl(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function ho(...t){try{let{stdout:e}=await Fh("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function Uh(){return await ni("git rev-parse --is-inside-work-tree")==="true"}async function Wh(){return await ni("git branch --show-current")}async function si(){try{let{stdout:t}=await gl("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 go(t=!1){return await ni(`git diff ${t?"--cached":""}`)||""}async function oi(){return(await si()).map(e=>e.file)}async function $l(){let t=await oi();if(t.length===0)return null;let e=await go(),o=await go(!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 i="chore",c=t.join(" ").toLowerCase();c.includes("test")?i="test":c.includes("readme")||c.includes("doc")?i="docs":n>r*2?i="feat":r>n?i="refactor":i="fix";let l=t.slice(0,3).map(d=>d.split("/").pop());return{summary:`${i}: update ${l.join(", ")}${t.length>3?` (+${t.length-3} more)`:""}`,type:i,files:t,stats:{additions:n,deletions:r}}}async function Bh(t){let s=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await ho("checkout","-b",s)!==null?s:null}async function Hh(t){return await ho("add","-A"),await ho("commit","-m",t)?await ho("rev-parse","--short","HEAD"):null}async function Gh(){let t=await $l();if(!t)return`${ke.dim}No changes${ke.reset}`;let e=[];e.push(`
|
|
103
|
+
${ke.bold}${ke.cyan}Git Diff Summary:${ke.reset}`),e.push(` ${ke.green}+${t.stats.additions}${ke.reset} ${ke.red}-${t.stats.deletions}${ke.reset} in ${t.files.length} file(s)`),e.push(`
|
|
104
|
+
${ke.bold}${ke.cyan}Files:${ke.reset}`);for(let s of t.files.slice(0,20))e.push(` ${ke.dim}${s}${ke.reset}`);return t.files.length>20&&e.push(` ${ke.dim}...+${t.files.length-20} more${ke.reset}`),e.push(`
|
|
105
|
+
${ke.bold}${ke.cyan}Suggested message:${ke.reset}`),e.push(` ${ke.cyan}${t.summary}${ke.reset}
|
|
105
106
|
`),e.join(`
|
|
106
|
-
`)}async function
|
|
107
|
+
`)}async function Kh(){return(await si()).filter(e=>e.status==="UU"||e.status==="AA"||e.status==="DD")}async function Yh(){let t=await oi();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 go();if(s){let o=s.length>5e3?s.substring(0,5e3)+`
|
|
107
108
|
...(truncated)`:s;e.push(`
|
|
108
109
|
DIFF:
|
|
109
110
|
${o}`)}return e.join(`
|
|
110
|
-
`)}
|
|
111
|
-
`).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(
|
|
111
|
+
`)}yl.exports={isGitRepo:Uh,getCurrentBranch:Wh,getStatus:si,getDiff:go,getChangedFiles:oi,analyzeDiff:$l,createBranch:Bh,commit:Hh,formatDiffSummary:Gh,getDiffContext:Yh,getMergeConflicts:Kh}});var It=G((Px,vl)=>{var Pe=require("fs").promises,Mx=require("fs"),yt=require("path"),zh=require("crypto"),{execSync:ls}=require("child_process"),Xh=100*1024,_l=50,Qe=[],In=[];function Jh(t,e,s,o){for(Qe.push({tool:t,filePath:e,oldContent:s,newContent:o,timestamp:Date.now()});Qe.length>_l;)Qe.shift();In.length=0,xl(Qe[Qe.length-1]).catch(()=>{})}async function Vh(){if(Qe.length===0)return null;let t=Qe.pop();if(t.oldContent===null)try{await Pe.unlink(t.filePath)}catch{}else await Pe.writeFile(t.filePath,t.oldContent,"utf-8");return In.push(t),{tool:t.tool,filePath:t.filePath,wasCreated:t.oldContent===null}}async function Qh(){if(In.length===0)return null;let t=In.pop();return await Pe.writeFile(t.filePath,t.newContent,"utf-8"),Qe.push(t),{tool:t.tool,filePath:t.filePath}}function Zh(t=10){return Qe.slice(-t).reverse().map(e=>({tool:e.tool,filePath:e.filePath,timestamp:e.timestamp}))}function eg(){return Qe.length}function tg(){return In.length}function ng({diskToo:t=!0}={}){if(Qe.length=0,In.length=0,t){let e=yo();Pe.readdir(e).then(s=>{for(let o of s)o.endsWith(".json")&&Pe.unlink(yt.join(e,o)).catch(()=>{})}).catch(()=>{})}}function yo(){return yt.join(process.cwd(),".nex","history")}async function wl(t,e){if(t==null)return{inline:!0,content:t};if(Buffer.byteLength(t,"utf-8")<=Xh)return{inline:!0,content:t};let s=zh.createHash("sha256").update(t,"utf-8").digest("hex"),o=yt.join(e,"blobs");return await Pe.mkdir(o,{recursive:!0}),await Pe.writeFile(yt.join(o,s),t,"utf-8"),{inline:!1,hash:s}}async function xl(t){let e=yo();await Pe.mkdir(e,{recursive:!0});let s=yt.basename(t.filePath).replace(/[^a-zA-Z0-9]/g,"-"),o=`${t.timestamp}-${s}.json`,n=await wl(t.oldContent,e),r=await wl(t.newContent,e),i={tool:t.tool,filePath:t.filePath,timestamp:t.timestamp,oldContent:n.inline?{inline:!0,content:n.content}:{inline:!1,hash:n.hash},newContent:r.inline?{inline:!0,content:r.content}:{inline:!1,hash:r.hash}};await Pe.writeFile(yt.join(e,o),JSON.stringify(i),"utf-8")}async function bl(t,e){if(!t)return null;if(t.inline)return t.content;let s=yt.join(e,"blobs",t.hash);return Pe.readFile(s,"utf-8")}async function sg(){let t=yo(),e;try{e=await Pe.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 Pe.readFile(yt.join(t,n),"utf-8"),i=JSON.parse(r),c=await bl(i.oldContent,t),l=await bl(i.newContent,t);Qe.push({tool:i.tool,filePath:i.filePath,timestamp:i.timestamp,oldContent:c,newContent:l}),o++}catch{}for(;Qe.length>_l;)Qe.shift();return o}async function og(t=7){let e=yo(),s;try{s=await Pe.readdir(e)}catch{return 0}let o=Date.now()-t*24*60*60*1e3,n=s.filter(u=>u.endsWith(".json")),r=0,i=new Set,c=[];for(let u of n)try{let d=await Pe.readFile(yt.join(e,u),"utf-8"),f=JSON.parse(d);f.timestamp<o?(c.push(u),r++):(f.oldContent&&!f.oldContent.inline&&f.oldContent.hash&&i.add(f.oldContent.hash),f.newContent&&!f.newContent.inline&&f.newContent.hash&&i.add(f.newContent.hash))}catch{}for(let u of c)try{await Pe.unlink(yt.join(e,u))}catch{}let l=yt.join(e,"blobs");try{let u=await Pe.readdir(l);for(let d of u)if(!i.has(d))try{await Pe.unlink(yt.join(l,d))}catch{}}catch{}return r}var $o="nex-snapshot";function rg(t,e=process.cwd()){let s=t?`${$o}-${t.replace(/[^a-zA-Z0-9_-]/g,"-")}`:`${$o}-${Date.now()}`;try{return ls("git status --porcelain",{cwd:e,timeout:1e4}).toString().trim()?(ls(`git stash push -u -m "${s}"`,{cwd:e,timeout:15e3}),ls("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 kl(t=process.cwd()){try{let e=ls("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($o)?{index:parseInt(o[1],10),label:n,shortName:n.replace(`${$o}-`,""),date:s}:null}).filter(Boolean):[]}catch{return[]}}function ig(t,e=process.cwd()){try{let s=kl(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?(ls(`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}}}vl.exports={recordChange:Jh,undo:Vh,redo:Qh,getHistory:Zh,getUndoCount:eg,getRedoCount:tg,clearHistory:ng,persistEntry:xl,loadPersistedHistory:sg,pruneHistory:og,createSnapshot:rg,listSnapshots:kl,restoreSnapshot:ig}});var Qt=G((Ix,Cl)=>{var ye=require("fs"),Ze=require("path"),{atomicWrite:ag,withFileLockSync:cg}=Xt(),et=[];function us(){return Ze.join(process.cwd(),".nex","skills")}function Sl(){return Ze.join(process.cwd(),".nex","config.json")}function El(){let t=us();return ye.existsSync(t)||ye.mkdirSync(t,{recursive:!0}),t}function ai(){let t=Sl();if(!ye.existsSync(t))return[];try{let e=JSON.parse(ye.readFileSync(t,"utf-8"));return e.skills&&Array.isArray(e.skills.disabled)?e.skills.disabled:[]}catch{return[]}}function Tl(t){let e=Sl(),s=Ze.dirname(e);ye.existsSync(s)||ye.mkdirSync(s,{recursive:!0}),cg(e,()=>{let o={};if(ye.existsSync(e))try{o=JSON.parse(ye.readFileSync(e,"utf-8"))}catch{o={}}o.skills||(o.skills={}),o.skills.disabled=t,ag(e,JSON.stringify(o,null,2))})}function Rl(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 ri(t){try{let e=ye.readFileSync(t,"utf-8").trim();return e?{name:Ze.basename(t,".md"),type:"prompt",filePath:t,instructions:e,commands:[],tools:[]}:null}catch{return null}}function ii(t){try{let e=require(t),{valid:s,errors:o}=Rl(e,t);return s?{name:e.name||Ze.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}
|
|
112
113
|
${o.join(`
|
|
113
|
-
`)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function
|
|
114
|
+
`)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function ci(){et=[];let t=ai(),e=us(),s=[];if(ye.existsSync(e))try{s=ye.readdirSync(e)}catch{s=[]}for(let n of s){let r=Ze.join(e,n),i;try{i=ye.statSync(r)}catch{continue}if(!i.isFile())continue;let c=null;n.endsWith(".md")?c=ri(r):n.endsWith(".js")&&(c=ii(r)),c&&(c.enabled=!t.includes(c.name),et.push(c))}let o=Ze.join(__dirname,"skills");if(!process.env.NEX_SKIP_BUILTIN_SKILLS&&ye.existsSync(o)){let n;try{n=ye.readdirSync(o).filter(r=>r.endsWith(".md")||r.endsWith(".js"))}catch{n=[]}for(let r of n){let i=Ze.join(o,r),c=Ze.basename(r,Ze.extname(r));if(et.some(d=>d.name===c))continue;let l;try{l=ye.statSync(i)}catch{continue}if(!l.isFile())continue;let u=r.endsWith(".md")?ri(i):ii(i);u&&(u._builtin=!0,u.enabled=!t.includes(u.name),et.push(u))}}return et}function lg(){let t=[];for(let e of et)!e.enabled||!e.instructions||t.push(`[Skill: ${e.name}]
|
|
114
115
|
${e.instructions}`);return t.length===0?"":`SKILL INSTRUCTIONS:
|
|
115
116
|
${t.join(`
|
|
116
117
|
|
|
117
|
-
`)}`}function
|
|
118
|
-
`,l="",u=setTimeout(()=>{f(),r(new Error(`MCP request timeout: ${e}`))},o);function d(
|
|
119
|
-
`);for(let
|
|
120
|
-
`):JSON.stringify(n)}function
|
|
121
|
-
Available tools: ${d.join(", ")}`}}if(!s||!s.properties)return{valid:!0};let o=s.required||[],n=Object.keys(s.properties),r=Object.keys(e),i=[],c={...e},l=!1;for(let u of o)if(!(u in e)||e[u]===void 0||e[u]===null){let d=
|
|
118
|
+
`)}`}function ug(){let t=[];for(let e of et)if(e.enabled)for(let s of e.commands)t.push({cmd:s.cmd,desc:s.desc||`[skill: ${e.name}]`});return t}function dg(){let t=[];for(let e of et)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 fg(t,e){if(!t.startsWith("skill_"))return null;let s=t.substring(6);for(let o of et)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 pg(t){let[e,...s]=t.split(/\s+/),o=s.join(" ").trim();for(let n of et)if(n.enabled){for(let r of n.commands)if(r.cmd===e&&r.handler){try{r.handler(o)}catch(i){console.error(`Skill command error (${e}): ${i.message}`)}return!0}}return!1}function mg(){return et.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 hg(t){let e=et.find(o=>o.name===t);if(!e)return!1;e.enabled=!0;let s=ai().filter(o=>o!==t);return Tl(s),!0}function gg(t){let e=et.find(o=>o.name===t);if(!e)return!1;e.enabled=!1;let s=ai();return s.includes(t)||(s.push(t),Tl(s)),!0}function $g(){return et}async function yg(t,e={}){let{execSync:s}=require("child_process"),o=El(),n=t;/^[\w-]+\/[\w.-]+$/.test(t)&&(n=`https://github.com/${t}.git`);let r=e.name||Ze.basename(n,".git").replace(/^nex-skill-/,""),i=Ze.join(o,r);if(ye.existsSync(i))return{ok:!1,name:r,error:`Skill "${r}" is already installed at ${i}. Remove it first to reinstall.`};try{s(`git clone --depth 1 ${n} ${i}`,{timeout:3e4,stdio:"pipe"})}catch(d){return{ok:!1,name:r,error:`Git clone failed: ${d.stderr?.toString().trim()||d.message}`}}let c=Ze.join(i,"skill.json"),l=ye.existsSync(c),u=ye.readdirSync(i).some(d=>(d.endsWith(".md")||d.endsWith(".js"))&&!d.startsWith("."));if(!l&&!u){try{ye.rmSync(i,{recursive:!0,force:!0})}catch{}return{ok:!1,name:r,error:"No skill.json manifest or .md/.js skill file found in repository"}}if(l)try{let d=JSON.parse(ye.readFileSync(c,"utf-8"));d.name||(d.name=r)}catch{try{ye.rmSync(i,{recursive:!0,force:!0})}catch{}return{ok:!1,name:r,error:"Invalid skill.json \u2014 not valid JSON"}}return ci(),{ok:!0,name:r}}async function wg(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 bg(t){let e=Ze.join(us(),t);if(!ye.existsSync(e))return{ok:!1,error:`Skill "${t}" not found in ${us()}`};try{return ye.rmSync(e,{recursive:!0,force:!0}),ci(),{ok:!0}}catch(s){return{ok:!1,error:s.message}}}Cl.exports={initSkillsDir:El,loadAllSkills:ci,getSkillInstructions:lg,getSkillCommands:ug,getSkillToolDefinitions:dg,routeSkillCall:fg,handleSkillCommand:pg,listSkills:mg,enableSkill:hg,disableSkill:gg,getLoadedSkills:$g,installSkill:yg,searchSkills:wg,removeSkill:bg,_getSkillsDir:us,_validateScriptSkill:Rl,_loadMarkdownSkill:ri,_loadScriptSkill:ii}});var bo=G((Lx,Il)=>{var{spawn:_g}=require("child_process"),xg=require("path"),Al=require("fs"),Lt=new Map;function kg(){return xg.join(process.cwd(),".nex","config.json")}function li(){let t=kg();if(!Al.existsSync(t))return{};try{return JSON.parse(Al.readFileSync(t,"utf-8")).mcpServers||{}}catch{return{}}}function wo(t,e,s={},o=1e4){return new Promise((n,r)=>{let i=`${Date.now()}-${Math.random().toString(36).slice(2,6)}`,c=JSON.stringify({jsonrpc:"2.0",id:i,method:e,params:s})+`
|
|
119
|
+
`,l="",u=setTimeout(()=>{f(),r(new Error(`MCP request timeout: ${e}`))},o);function d(p){l+=p.toString();let h=l.split(`
|
|
120
|
+
`);for(let m of h)if(m.trim())try{let g=JSON.parse(m);if(g.id===i){f(),g.error?r(new Error(`MCP error: ${g.error.message||JSON.stringify(g.error)}`)):n(g.result);return}}catch{}l=h[h.length-1]||""}function f(){clearTimeout(u),t.stdout.removeListener("data",d)}t.stdout.on("data",d);try{t.stdin.write(c)}catch(p){f(),r(new Error(`MCP write failed: ${p.message}`))}})}async function Ol(t,e){if(Lt.has(t))return Lt.get(t);let s=["PATH","HOME","USER","SHELL","LANG","TERM","NODE_ENV"],o={};for(let i of s)process.env[i]&&(o[i]=process.env[i]);let n=_g(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:{...o,...e.env||{}}}),r={name:t,proc:n,tools:[],config:e};try{await wo(n,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.2.0"}});let i=await wo(n,"tools/list",{});return r.tools=i&&i.tools||[],Lt.set(t,r),r}catch(i){throw n.kill(),new Error(`Failed to connect MCP server '${t}': ${i.message}`)}}function Nl(t){let e=Lt.get(t);if(!e)return!1;try{e.proc.kill()}catch{}return Lt.delete(t),!0}function vg(){for(let[t]of Lt)Nl(t)}async function Ml(t,e,s={}){let o=Lt.get(t);if(!o)throw new Error(`MCP server not connected: ${t}`);let n=await wo(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 Pl(){let t=[];for(let[e,s]of Lt)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 Sg(){return Pl().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function Eg(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 Ml(o,n,e)}function Tg(){let t=li();return Object.entries(t).map(([e,s])=>{let o=Lt.get(e);return{name:e,command:s.command,connected:!!o,toolCount:o?o.tools.length:0}})}async function Rg(){let t=li(),e=[];for(let[s,o]of Object.entries(t))try{let n=await Ol(s,o);e.push({name:s,tools:n.tools.length})}catch(n){e.push({name:s,tools:0,error:n.message})}return e}Il.exports={loadMCPConfig:li,sendRequest:wo,connectServer:Ol,disconnectServer:Nl,disconnectAll:vg,callTool:Ml,getAllTools:Pl,getMCPToolDefinitions:Sg,routeMCPCall:Eg,listServers:Tg,connectAll:Rg}});var xo=G((jx,ql)=>{var Ll=require("fs"),ui=require("path"),_o=[],ds=[],fn={},fs=["onToolResult","onModelResponse","onSessionStart","onSessionEnd","onFileChange","beforeToolExec","afterToolExec"];function jl(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 ds.some(o=>o.definition.function.name===s)?{ok:!1,error:`Tool "${s}" is already registered`}:(ds.push({definition:{type:"function",...t},handler:e}),{ok:!0})}function Dl(t,e){return fs.includes(t)?typeof e!="function"?{ok:!1,error:"Handler must be a function"}:(fn[t]||(fn[t]=[]),fn[t].push(e),{ok:!0}):{ok:!1,error:`Unknown event "${t}". Available: ${fs.join(", ")}`}}async function di(t,e){let s=fn[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 Cg(){let t=ui.join(process.cwd(),".nex","plugins"),e=[];if(!Ll.existsSync(t))return{loaded:0,errors:[]};let s=Ll.readdirSync(t).filter(n=>n.endsWith(".js")),o={registerTool:jl,registerHook:Dl,EVENTS:fs};for(let n of s){let r=ui.join(t,n);try{let i=require(r);if(typeof i=="function")i(o);else if(typeof i.setup=="function")i.setup(o);else{e.push(`${n}: Plugin must export a function or { setup: function }`);continue}_o.push({name:i.name||ui.basename(n,".js"),filePath:r})}catch(i){e.push(`${n}: ${i.message}`)}}return{loaded:_o.length,errors:e}}function Ag(){return ds.map(t=>t.definition)}async function Og(t,e,s={}){let o=ds.find(c=>c.definition.function.name===t);if(!o)return null;let n=await di("beforeToolExec",{name:t,args:e,options:s}),r=await o.handler(n.args||e,s);return(await di("afterToolExec",{name:t,args:e,result:r})).result||r}function Ng(){return[..._o]}function Mg(){let t={};for(let e of fs)t[e]=(fn[e]||[]).length;return t}function Pg(){_o.length=0,ds.length=0;for(let t of Object.keys(fn))delete fn[t]}ql.exports={registerTool:jl,registerHook:Dl,emit:di,loadPlugins:Cg,getPluginToolDefinitions:Ag,executePluginTool:Og,getLoadedPlugins:Ng,getHookCounts:Mg,clearPlugins:Pg,EVENTS:fs}});var fi=G((Dx,Bl)=>{var{getSkillToolDefinitions:Ig}=Qt(),{getMCPToolDefinitions:Lg}=bo(),{getPluginToolDefinitions:jg}=xo(),ko=new Map;function Fl(){let{TOOL_DEFINITIONS:t}=kt();return[...t,...Ig(),...Lg(),...jg()]}function Ul(t){if(ko.has(t))return ko.get(t);let s=Fl().find(n=>n.function.name===t);if(!s)return null;let o=s.function.parameters;return ko.set(t,o),o}function Dg(){ko.clear()}function vo(t,e){if(!t||e.length===0)return null;let s=null,o=1/0;for(let n of e){let r=Wl(t.toLowerCase(),n.toLowerCase());r<o&&(o=r,s=n)}return o<=Math.ceil(t.length/2)?s:null}function Wl(t,e){let s=t.length,o=e.length,n=Array.from({length:s+1},()=>Array(o+1).fill(0));for(let r=0;r<=s;r++)n[r][0]=r;for(let r=0;r<=o;r++)n[0][r]=r;for(let r=1;r<=s;r++)for(let i=1;i<=o;i++)n[r][i]=t[r-1]===e[i-1]?n[r-1][i-1]:1+Math.min(n[r-1][i],n[r][i-1],n[r-1][i-1]);return n[s][o]}function qg(t,e){let s=Ul(t);if(s===null){let d=Fl().map(p=>p.function.name),f=vo(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),i=[],c={...e},l=!1;for(let u of o)if(!(u in e)||e[u]===void 0||e[u]===null){let d=vo(u,r);d&&!n.includes(d)?(c[u]=e[d],delete c[d],l=!0):i.push(`Missing required parameter "${u}" (${s.properties[u]?.description||s.properties[u]?.type||"unknown"})`)}for(let u of r)if(!n.includes(u)){let d=vo(u,n);d&&!(d in c)?(c[d]=e[u],delete c[u],l=!0):l||i.push(`Unknown parameter "${u}".${d?` Did you mean "${d}"?`:""}`)}for(let u of Object.keys(c)){if(!s.properties[u])continue;let d=s.properties[u].type,f=typeof c[u];d==="string"&&f==="number"?(c[u]=String(c[u]),l=!0):d==="number"&&f==="string"&&!isNaN(c[u])?(c[u]=Number(c[u]),l=!0):d==="boolean"&&f==="string"&&(c[u]=c[u]==="true",l=!0)}return i.length>0&&!l?{valid:!1,error:`Tool "${t}" argument errors:
|
|
122
123
|
`+i.map(u=>` - ${u}`).join(`
|
|
123
124
|
`)+`
|
|
124
125
|
|
|
125
|
-
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 Fg(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}}Bl.exports={validateToolArgs:qg,validateToolCallFormat:Fg,closestMatch:vo,levenshtein:Wl,getCachedSchema:Ul,clearSchemaCache:Dg}});var Yl=G((qx,Kl)=>{var{levenshtein:So}=fi(),Ug=200,Wg=.3,Bg=2;function pi(t){return t.replace(/\r\n/g,`
|
|
126
127
|
`).replace(/\r/g,`
|
|
127
|
-
`).replace(/\t/g," ".repeat(
|
|
128
|
+
`).replace(/\t/g," ".repeat(Bg)).split(`
|
|
128
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(`
|
|
129
|
-
`)}function
|
|
130
|
+
`)}function Hg(t,e){if(t.includes(e))return e;if(e.length<10)return null;let s=pi(t),o=pi(e);if(!s.includes(o))return null;let n=t.split(`
|
|
130
131
|
`),r=s.split(`
|
|
131
132
|
`),i=o.split(`
|
|
132
133
|
`),c=i[0],l=i[i.length-1];for(let u=0;u<=r.length-i.length;u++){let d=!0;for(let f=0;f<i.length;f++)if(r[u+f]!==i[f]){d=!1;break}if(d)return n.slice(u,u+i.length).join(`
|
|
133
|
-
`)}if(i.length===1){for(let u=0;u<r.length;u++)if(r[u].indexOf(o)!==-1)return n[u]}return null}function
|
|
134
|
+
`)}if(i.length===1){for(let u=0;u<r.length;u++)if(r[u].indexOf(o)!==-1)return n[u]}return null}function Gg(t,e){if(!t||!e)return null;let s=t.split(`
|
|
134
135
|
`),n=e.split(`
|
|
135
|
-
`).length;return s.length===0||n===0?null:n===1?
|
|
136
|
-
`),u=
|
|
137
|
-
`),h=
|
|
138
|
-
`),o=[],n=t?`.${t.split(".").pop()}`:"";for(let r=0;r<s.length;r++){let i=s[r],c=r+1;for(let l of
|
|
139
|
-
`).filter(Boolean),
|
|
140
|
-
`);for(let n=0;n<o.length;n++){let r=o[n],i=n+1;if([".js",".ts",".jsx",".tsx",".mjs",".cjs"].includes(e)){let c=r.match(/(?:export\s+)?(?:async\s+)?function\s+(\w+)/);c&&s.push({type:"function",name:c[1],line:i});let l=r.match(/(?:export\s+)?class\s+(\w+)/);l&&s.push({type:"class",name:l[1],line:i});let u=r.match(/(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?(?:\([^)]*\)|[\w$]+)\s*=>/);u&&s.push({type:"function",name:u[1],line:i});let d=r.match(/module\.exports\s*=\s*\{([^}]+)\}/);if(d){let
|
|
136
|
+
`).length;return s.length===0||n===0?null:n===1?Kg(s,e):zg(s,e,n)}function Hl(t){return Math.max(1,Math.floor(t/Ug))}function Gl(t,e){return t<=Math.ceil(e*Wg)}function Kg(t,e){let s=e.trim(),o=Hl(t.length),n=null,r=1/0;for(let i=0;i<t.length;i+=o){let c=t[i];if(!c.trim())continue;let l=So(c.trim(),s);l<r&&(r=l,n={text:c,distance:l,line:i+1})}return n&&o>1&&(n=Yg(t,s,n,o)||n,r=n.distance),Gl(r,e.length)?n:null}function Yg(t,e,s,o){let n=s.line-1,r=Math.max(0,n-o),i=Math.min(t.length-1,n+o),c=s.distance,l=null;for(let u=r;u<=i;u++){let d=t[u];if(!d.trim())continue;let f=So(d.trim(),e);f<c&&(c=f,l={text:d,distance:f,line:u+1})}return l}function zg(t,e,s){let o=t.length-s+1;if(o<=0)return null;let n=Hl(o),r=null,i=1/0;for(let c=0;c<o;c+=n){let l=t.slice(c,c+s).join(`
|
|
137
|
+
`),u=So(l,e);u<i&&(i=u,r={text:l,distance:u,line:c+1})}return r&&n>1&&(r=Xg(t,e,r,n,s,o)||r,i=r.distance),Gl(i,e.length)?r:null}function Xg(t,e,s,o,n,r){let i=s.line-1,c=Math.max(0,i-o),l=Math.min(r-1,i+o),u=s.distance,d=null;for(let f=c;f<=l;f++){let p=t.slice(f,f+n).join(`
|
|
138
|
+
`),h=So(p,e);h<u&&(u=h,d={text:p,distance:h,line:f+1})}return d}Kl.exports={normalizeWhitespace:pi,fuzzyFindText:Hg,findMostSimilar:Gg}});var Xl=G((Ux,zl)=>{var{C:Fx}=ve(),Jg=[{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}],Vg=[{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 Qg(t,e){let s=e.split(`
|
|
139
|
+
`),o=[],n=t?`.${t.split(".").pop()}`:"";for(let r=0;r<s.length;r++){let i=s[r],c=r+1;for(let l of Jg)l.regex.test(i)&&o.push({line:c,message:`Potential secret detected: ${l.name}`,severity:"error"});for(let l of Vg)l.ext&&!l.ext.includes(n)||l.regex.test(i)&&o.push({line:c,message:l.message||`Found ${l.name}`,severity:l.severity||"warn"})}return s.length>500&&o.push({line:0,message:`Large file detected (${s.length} lines). Consider refactoring.`,severity:"info"}),o}zl.exports={runDiagnostics:Qg}});var yi=G((Wx,tu)=>{var Ln=require("fs").promises,jn=require("path"),{exec:Zg}=require("util").promisify(require("child_process").exec),Dn=[],$i=null,Eo=!1,hi=0,e$=6e4;function Vl(t){return!(Dn.length===0||$i!==t||Date.now()-hi>e$)}async function Ql(t){if(!Eo&&!Vl(t)){Eo=!0,$i=t;try{try{let{stdout:o}=await Zg("rg --files",{cwd:t,timeout:5e3});Dn=o.split(`
|
|
140
|
+
`).filter(Boolean),hi=Date.now(),Eo=!1;return}catch{}let e=[],s=async(o,n)=>{let r;try{r=await Ln.readdir(o,{withFileTypes:!0})}catch{return}for(let i of r){if(i.name==="node_modules"||i.name===".git"||i.name.startsWith("."))continue;let c=n?`${n}/${i.name}`:i.name;i.isDirectory()?await s(jn.join(o,i.name),c):e.push(c)}};await s(t,""),Dn=e,hi=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{Eo=!1}}}function gi(){return Dn}function t$(){return $i}function n$(t){return Dn.filter(e=>jn.basename(e)===t)}function s$(t){let e=t.toLowerCase();return Dn.filter(s=>s.toLowerCase().includes(e)).slice(0,20)}var mi=null,Jl=0,o$=12e4,r$=new Set([".js",".ts",".jsx",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".rb"]);function Zl(t,e){let s=[],o=t.split(`
|
|
141
|
+
`);for(let n=0;n<o.length;n++){let r=o[n],i=n+1;if([".js",".ts",".jsx",".tsx",".mjs",".cjs"].includes(e)){let c=r.match(/(?:export\s+)?(?:async\s+)?function\s+(\w+)/);c&&s.push({type:"function",name:c[1],line:i});let l=r.match(/(?:export\s+)?class\s+(\w+)/);l&&s.push({type:"class",name:l[1],line:i});let u=r.match(/(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?(?:\([^)]*\)|[\w$]+)\s*=>/);u&&s.push({type:"function",name:u[1],line:i});let d=r.match(/module\.exports\s*=\s*\{([^}]+)\}/);if(d){let p=d[1].split(",").map(h=>h.trim().split(":")[0].trim()).filter(Boolean);for(let h of p)/^\w+$/.test(h)&&s.push({type:"export",name:h,line:i})}let f=r.match(/(?:require\(['"]([^'"]+)['"]\)|from\s+['"]([^'"]+)['"])/);if(f){let p=f[1]||f[2];s.push({type:"import",name:p,line:i})}}if(e===".py"){let c=r.match(/^(?:async\s+)?def\s+(\w+)/);c&&s.push({type:"function",name:c[1],line:i});let l=r.match(/^class\s+(\w+)/);l&&s.push({type:"class",name:l[1],line:i});let u=r.match(/^(?:from\s+(\S+)\s+)?import\s+(\S+)/);u&&s.push({type:"import",name:u[1]||u[2],line:i})}if(e===".go"){let c=r.match(/^func\s+(?:\([^)]+\)\s+)?(\w+)/);c&&s.push({type:"function",name:c[1],line:i});let l=r.match(/^type\s+(\w+)\s+struct/);l&&s.push({type:"class",name:l[1],line:i})}}return s}async function eu(t){t=t||process.cwd();let e=jn.join(t,".nex","index","content-index.json"),s={};if(mi&&Date.now()-Jl<o$)return mi;try{let i=await Ln.readFile(e,"utf-8");s=JSON.parse(i)}catch{s={files:{}}}gi().length===0&&await Ql(t);let n={files:{}},r=!1;for(let i of gi()){let c=jn.extname(i);if(!r$.has(c))continue;let l=jn.join(t,i);try{let d=(await Ln.stat(l)).mtimeMs;if(s.files[i]&&s.files[i].mtime===d){n.files[i]=s.files[i];continue}let f=await Ln.readFile(l,"utf-8"),p=Zl(f,c);n.files[i]={defs:p,mtime:d},r=!0}catch{}}if(r){let i=jn.join(t,".nex","index");await Ln.mkdir(i,{recursive:!0}),await Ln.writeFile(e,JSON.stringify(n),"utf-8")}return mi=n,Jl=Date.now(),n}async function i$(t,e){let s=await eu(),o=[],n=t.toLowerCase();for(let[r,i]of Object.entries(s.files))for(let c of i.defs)e&&c.type!==e||c.name.toLowerCase().includes(n)&&o.push({file:r,type:c.type,name:c.name,line:c.line});return o.sort((r,i)=>{let c=r.name.toLowerCase()===n?0:1,l=i.name.toLowerCase()===n?0:1;if(c!==l)return c-l;let u=r.name.toLowerCase().startsWith(n)?0:1,d=i.name.toLowerCase().startsWith(n)?0:1;return u-d}),o.slice(0,50)}tu.exports={refreshIndex:Ql,getFileIndex:gi,getIndexedCwd:t$,findFileInIndex:n$,searchIndex:s$,isIndexValid:Vl,buildContentIndex:eu,searchContentIndex:i$,extractDefinitions:Zl}});var qn=G((Bx,ru)=>{var To=require("fs"),Co=require("path"),Ao=require("os"),{execFile:a$}=require("child_process"),{promisify:c$}=require("util"),wi=c$(a$),l$=Co.join(Ao.homedir(),".nex","servers.json"),Ro=Co.join(Ao.tmpdir(),"nex-ssh-sockets");function u$(){return Co.join(process.cwd(),".nex","servers.json")}function nu(){let t=o=>{if(!To.existsSync(o))return{};try{return JSON.parse(To.readFileSync(o,"utf-8"))}catch{return{}}},e=t(l$),s=t(u$());return{...e,...s}}function d$(t){let e=nu();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 f$(){To.existsSync(Ro)||To.mkdirSync(Ro,{recursive:!0})}function su(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-o","ServerAliveInterval=30"];t.key&&e.push("-i",t.key.replace(/^~/,Ao.homedir())),t.port&&Number(t.port)!==22&&e.push("-p",String(t.port)),f$();let s=t.user?`${t.user}@${t.host}`:t.host,o=Co.join(Ro,s.replace(/[@.:]/g,"_"));return e.push("-o","ControlMaster=auto","-o",`ControlPath=${o}`,"-o","ControlPersist=120"),e.push(s),{args:e,target:s}}function ou(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-r"];return t.key&&e.push("-i",t.key.replace(/^~/,Ao.homedir())),t.port&&Number(t.port)!==22&&e.push("-P",String(t.port)),e}async function p$(t,e,{timeout:s=3e4,sudo:o=!1}={}){let{args:n}=su(t),r=o&&t.sudo?`sudo sh -c ${JSON.stringify(e)}`:e;try{let{stdout:i,stderr:c}=await wi("ssh",[...n,r],{timeout:s,maxBuffer:4194304});return{stdout:i||"",stderr:c||"",exitCode:0}}catch(i){let c=typeof i.code=="number"?i.code:1,l=(i.stderr||i.message||"").toString();return{stdout:(i.stdout||"").toString(),stderr:l,exitCode:c,error:Oo(l,t)}}}async function m$(t,e,s,{timeout:o=12e4}={}){let n=ou(t),r=t.user?`${t.user}@${t.host}`:t.host;n.push(e,`${r}:${s}`);try{let{stdout:i,stderr:c}=await wi("scp",n,{timeout:o,maxBuffer:1048576});return i||c||`Uploaded ${e} \u2192 ${r}:${s}`}catch(i){let c=(i.stderr||i.message||"").toString();throw new Error(Oo(c,t)||c)}}async function h$(t,e,s,{timeout:o=12e4}={}){let n=ou(t),r=t.user?`${t.user}@${t.host}`:t.host;n.push(`${r}:${e}`,s);try{let{stdout:i,stderr:c}=await wi("scp",n,{timeout:o,maxBuffer:1048576});return i||c||`Downloaded ${r}:${e} \u2192 ${s}`}catch(i){let c=(i.stderr||i.message||"").toString();throw new Error(Oo(c,t)||c)}}function Oo(t,e){if(!t)return"";if(/connection refused/i.test(t)){let s=e.port||22;return`${t}
|
|
141
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}
|
|
142
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}
|
|
143
144
|
HINT: Cannot reach ${e.host}. Check: network connection, correct hostname/IP, DNS resolution.`:/host key verification failed/i.test(t)?`${t}
|
|
144
145
|
HINT: Host key changed for ${e.host}. To reset: ssh-keygen -R ${e.host}`:/timed out/i.test(t)?`${t}
|
|
145
146
|
HINT: Connection timed out to ${e.host}. Check firewall rules and network connectivity.`:/too many authentication failures/i.test(t)?`${t}
|
|
146
|
-
HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function
|
|
147
|
-
`,"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 g$(t,e){let s=e.user?`${e.user}@${e.host}`:e.host,o=e.port&&Number(e.port)!==22?`:${e.port}`:"",n=e.os?` [${e.os}]`:"",r=e.key?` key:${e.key}`:"",i=e.sudo?" sudo:yes":"";return`${t}: ${s}${o}${n}${r}${i}`}ru.exports={loadServerProfiles:nu,resolveProfile:d$,buildSSHArgs:su,sshExec:p$,scpUpload:m$,scpDownload:h$,enrichSSHError:Oo,formatProfile:g$,SSH_SOCKET_DIR:Ro}});var xi=G((Hx,au)=>{var ps=require("fs"),bi=require("path"),$$=bi.join(".nex","deploy.json");function _i(){return bi.join(process.cwd(),$$)}function iu(){let t=_i();if(!ps.existsSync(t))return{};try{return JSON.parse(ps.readFileSync(t,"utf-8"))}catch{return{}}}function y$(t){let e=iu();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 w$(t){let e=bi.join(process.cwd(),".nex");ps.existsSync(e)||ps.mkdirSync(e,{recursive:!0}),ps.writeFileSync(_i(),JSON.stringify(t,null,2)+`
|
|
148
|
+
`,"utf-8")}au.exports={loadDeployConfigs:iu,resolveDeployConfig:y$,saveDeployConfigs:w$,getDeployConfigPath:_i}});var No=G((Gx,uu)=>{var{getActiveModel:b$,getActiveProviderName:_$}=Se(),ms={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},hs={"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"},gs={ollama:"full",openai:"full",anthropic:"full",gemini:"full",local:"essential"},Ot={};function lu(){try{let t=require("fs"),s=require("path").join(process.cwd(),".nex","config.json");t.existsSync(s)&&(Ot=JSON.parse(t.readFileSync(s,"utf-8")).toolTiers||{})}catch{Ot={}}}lu();function ki(){let e=b$()?.id,s=_$();return e&&Ot[e]?Ot[e]:s&&Ot[`${s}:*`]?Ot[`${s}:*`]:e&&hs[e]?hs[e]:s&&gs[s]?gs[s]:"full"}var x$=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"]),cu={anthropic:"strict",openai:"strict",gemini:"strict",ollama:"fuzzy",local:"fuzzy"};function k$(t,e){return t&&(x$.has(t)||t.startsWith("claude-"))?"strict":e&&cu[e]?cu[e]:"fuzzy"}function v$(t,e){return t&&Ot[t]?Ot[t]:e&&Ot[`${e}:*`]?Ot[`${e}:*`]:t&&hs[t]?hs[t]:e&&gs[e]?gs[e]:"full"}function S$(t,e){let s=e||ki();if(s==="full"||!ms[s])return t;let o=new Set(ms[s]);return t.filter(n=>o.has(n.function.name))}function E$(){let t=ki(),e=ms[t]?ms[t].length:"all";return{tier:t,toolCount:e}}uu.exports={filterToolsForModel:S$,getActiveTier:ki,getModelTier:v$,getEditMode:k$,getTierInfo:E$,TIERS:ms,MODEL_TIERS:hs,PROVIDER_DEFAULT_TIER:gs,loadConfigOverrides:lu}});var ys=G((Kx,pu)=>{var vi=null,jt=null,$s=null,du=`Playwright is not installed. Install with:
|
|
148
149
|
npm install playwright && npx playwright install chromium
|
|
149
|
-
Then restart nex-code.`;function
|
|
150
|
-
...(truncated)`:""),links:c.slice(0,20)}}finally{await n.close()}}async function
|
|
151
|
-
`)}function
|
|
150
|
+
Then restart nex-code.`;function fu(){if($s!==null)return $s;try{require("playwright"),$s=!0}catch{$s=!1}return $s}async function Mo(){if(!fu())throw new Error(du);return vi||(vi=require("playwright")),(!jt||!jt.isConnected())&&(jt=await vi.chromium.launch({headless:!0})),jt}async function T$(){if(jt){try{await jt.close()}catch{}jt=null}}process.on("exit",()=>{if(jt)try{jt.close()}catch{}});async function R$(t,{timeout:e=3e4,waitFor:s="domcontentloaded"}={}){let n=await(await Mo()).newPage();try{await n.goto(t,{waitUntil:s,timeout:e});let r=await n.title(),i=await n.evaluate(()=>(document.querySelectorAll("script,style,nav,footer,header,aside,[role=navigation]").forEach(u=>u.remove()),document.body?.innerText||"")),c=await n.evaluate(()=>Array.from(document.querySelectorAll("a[href]")).slice(0,30).map(l=>({text:(l.innerText||l.textContent||"").trim().substring(0,80),href:l.href})).filter(l=>l.text&&l.href&&!l.href.startsWith("javascript:")));return{title:r,url:n.url(),text:i.substring(0,8e3)+(i.length>8e3?`
|
|
151
|
+
...(truncated)`:""),links:c.slice(0,20)}}finally{await n.close()}}async function C$(t,{width:e=1280,height:s=800,fullPage:o=!1,timeout:n=3e4}={}){let i=await(await Mo()).newPage();try{await i.setViewportSize({width:e,height:s}),await i.goto(t,{waitUntil:"networkidle",timeout:n});let c=await i.screenshot({type:"png",fullPage:o}),l=require("os"),u=require("path"),d=require("fs"),f=u.join(l.tmpdir(),`nex-screenshot-${Date.now()}.png`);return d.writeFileSync(f,c),{path:f,base64:c.toString("base64"),media_type:"image/png",title:await i.title(),url:i.url()}}finally{await i.close()}}async function A$(t,{selector:e,text:s,timeout:o=3e4}={}){if(!e&&!s)throw new Error("selector or text is required");let r=await(await Mo()).newPage();try{await r.goto(t,{waitUntil:"domcontentloaded",timeout:o}),s?await r.getByText(s,{exact:!1}).first().click({timeout:1e4}):await r.locator(e).first().click({timeout:1e4}),await r.waitForLoadState("domcontentloaded");let i=await r.title();return`Clicked \u2014 now at: ${r.url()} (${i})`}finally{await r.close()}}async function O$(t,{selector:e,value:s,submit:o=!1,timeout:n=3e4}={}){if(!e||s===void 0)throw new Error("selector and value are required");let i=await(await Mo()).newPage();try{return await i.goto(t,{waitUntil:"domcontentloaded",timeout:n}),await i.fill(e,String(s)),o&&(await i.keyboard.press("Enter"),await i.waitForLoadState("domcontentloaded")),`Filled "${e}" with value. ${o?`Submitted \u2192 ${i.url()}`:"Not submitted."}`}finally{await i.close()}}pu.exports={isPlaywrightAvailable:fu,browserNavigate:R$,browserScreenshot:C$,browserClick:A$,browserFill:O$,closeBrowser:T$,INSTALL_MSG:du}});var Po=G((Yx,mu)=>{var{C:we}=ve(),bs="",Ge=[],ws=0,pn=null;function N$(t){pn=t}function M$(t,e){bs=t,Ge=[],ws=0;for(let o of e){ws++;let n=`t${ws}`;Ge.push({id:n,description:o.description||o.title||o.name||o.task||`Task ${ws}`,status:"pending",dependsOn:o.depends_on||[],result:null})}let s=Ge.map(o=>({...o}));return pn&&pn("create",{name:t,tasks:s}),s}function P$(t,e,s){let o=Ge.find(n=>n.id===t);return o?(o.status=e,s!==void 0&&(o.result=s),pn&&pn("update",{id:t,status:e,result:s}),{...o}):null}function I$(){return{name:bs,tasks:Ge.map(t=>({...t}))}}function L$(){bs="",Ge=[],ws=0,pn&&pn("clear",{})}function j$(){return Ge.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let s=Ge.find(o=>o.id===e);return s&&s.status==="done"}))}function D$(){if(Ge.length===0)return`${we.dim}No active tasks${we.reset}`;let t=[];bs&&(t.push(` ${we.bold}${we.cyan}Tasks: ${bs}${we.reset}`),t.push(` ${we.dim}${"\u2500".repeat(40)}${we.reset}`));for(let n of Ge){let r,i;switch(n.status){case"done":r="\u2713",i=we.green;break;case"in_progress":r="\u2192",i=we.cyan;break;case"failed":r="\u2717",i=we.red;break;default:r="\xB7",i=we.dim}let c=n.dependsOn.length>0?` ${we.dim}(after: ${n.dependsOn.join(", ")})${we.reset}`:"",l=`[${n.status}]`,u=n.description.length>50?n.description.substring(0,47)+"...":n.description;if(t.push(` ${i}${r}${we.reset} ${we.bold}${n.id}${we.reset} ${u.padEnd(40)} ${i}${l}${we.reset}${c}`),n.result&&n.status==="done"){let d=n.result.length>60?n.result.substring(0,57)+"...":n.result;t.push(` ${we.dim}\u2192 ${d}${we.reset}`)}}let e=Ge.filter(n=>n.status==="done").length,s=Ge.filter(n=>n.status==="failed").length,o=Ge.length;return t.push(` ${we.dim}${"\u2500".repeat(40)}${we.reset}`),t.push(` ${we.dim}${e}/${o} done${s>0?`, ${s} failed`:""}${we.reset}`),t.join(`
|
|
152
|
+
`)}function q$(){return Ge.length>0&&Ge.some(t=>t.status==="pending"||t.status==="in_progress")}mu.exports={createTasks:M$,updateTask:P$,getTaskList:I$,clearTasks:L$,getReadyTasks:j$,renderTaskList:D$,setOnChange:N$,hasActiveTasks:q$}});var Nu=G((Xx,Ou)=>{var{callStream:F$,getActiveProviderName:Lo,getActiveModelId:U$,getConfiguredProviders:W$,getProvider:hu,getActiveProvider:gu,parseModelSpec:$u}=Se(),{parseToolArgs:yu}=Pn(),{filterToolsForModel:B$,getModelTier:Io}=No(),{trackUsage:H$}=Mn(),{MultiProgress:G$,C:zx}=ve(),_u=15,K$=5,wu=3,xu=8,Y$=2,jo=new Map,ku=600*1e3;function z$(t,e){let s=jo.get(t);return s&&s.agentId!==e&&Date.now()-s.timestamp<ku?!1:(jo.set(t,{agentId:e,timestamp:Date.now()}),!0)}function _s(t){jo.delete(t)}function Si(){jo.clear()}function vu(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 Su(t,e,s){let o;for(let n=0;n<=wu;n++)try{return await F$(t,e,s)}catch(r){if(o=r,n<wu&&vu(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 bu=new Set(["ask_user","task_list"]);function Eu(t){return t>=2?new Set([...bu,"spawn_agents"]):bu}var X$=new Set(["write_file","edit_file","patch_file"]),J$=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,V$=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function Tu(t){return V$.test(t)?"full":J$.test(t)?"essential":"standard"}function Ru(t){let e=W$(),s=Lo(),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(Io(r.id,n.name)===t)return{provider:n.name,model:r.id};return null}var Q$={essential:process.env.NEX_FAST_MODEL||null,standard:process.env.NEX_STANDARD_MODEL||null,full:process.env.NEX_HEAVY_MODEL||null};function Ei(t){if(t.model){let{provider:n,model:r}=$u(t.model),i=n?hu(n):gu(),c=n||Lo();if(i&&i.isConfigured()&&(i.getModel(r)||c==="local")){let l=Io(r,c);return{provider:c,model:r,tier:l}}}let e=Tu(t.task),s=Q$[e];if(s){let{provider:n,model:r}=$u(s),i=n?hu(n):gu(),c=n||Lo();if(i&&i.isConfigured()&&(i.getModel(r)||c==="local")){let l=Io(r,c);return{provider:c,model:r,tier:l}}}let o=Ru(e);if(o){let n=Io(o.model,o.provider);return{provider:o.provider,model:o.model,tier:n}}return{provider:null,model:null,tier:null}}async function Cu(t,e={},s=0){let o=s===0?_u:xu,n=Math.min(t.max_iterations||10,o),r=`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,i=[],c={input:0,output:0},l=new Set,u=new Map,f=[{role:"system",content:`You are a focused sub-agent. Complete this specific task efficiently.
|
|
152
153
|
|
|
153
154
|
TASK: ${t.task}
|
|
154
155
|
${t.context?`
|
|
@@ -170,208 +171,228 @@ TOOL STRATEGY:
|
|
|
170
171
|
ERROR RECOVERY:
|
|
171
172
|
- If edit_file fails with "old_text not found": read the file again, compare, and retry with exact text.
|
|
172
173
|
- If bash fails: read the error, fix the root cause, then retry.
|
|
173
|
-
- After 2 failed attempts at the same operation, summarize the issue and stop.`}];f.push({role:"user",content:t.task});let
|
|
174
|
-
`)}let
|
|
175
|
-
...(truncated)`:
|
|
176
|
-
`)}catch(d){return u.stop(),
|
|
177
|
-
`);for(let r of n){let i=r.match(/^(\w+):\s*(.+)$/);if(!i)continue;let c=i[1].trim(),l=i[2].trim();l.startsWith("[")&&l.endsWith("]")?e[c]=l.slice(1,-1).split(",").map(u=>u.trim()).filter(Boolean):e[c]=l}s=o[2]}return{frontmatter:e,body:s}}function
|
|
178
|
-
`);for(let i of r)if(i.startsWith("#")){let c=i.replace(/^#+\s*/,"");for(let l of
|
|
174
|
+
- After 2 failed attempts at the same operation, summarize the issue and stop.`}];f.push({role:"user",content:t.task});let p=Ei(t),h=p.provider,m=p.model,g=p.tier,{TOOL_DEFINITIONS:$,executeTool:y}=kt(),x=Eu(s),_=B$($.filter(b=>!x.has(b.function.name)),g);if(m&&!t._skipLog){let b=g?` (${g})`:"";process.stderr.write(` [sub-agent: ${h}:${m}${b}]
|
|
175
|
+
`)}let v={};h&&(v.provider=h),m&&(v.model=m);try{for(let k=0;k<n;k++){let R=await Su(f,_,v);if(!R||typeof R!="object")throw new Error("Empty or invalid response from provider");if(R.usage){let A=R.usage.prompt_tokens||0,M=R.usage.completion_tokens||0;c.input+=A,c.output+=M;let D=h||Lo(),W=m||U$();H$(D,W,A,M)}let O=R.content||"",P=R.tool_calls,F={role:"assistant",content:O||""};if(P&&P.length>0&&(F.tool_calls=P),f.push(F),!P||P.length===0){for(let A of l)_s(A);return{task:t.task,status:"done",result:O||"(no response)",toolsUsed:i,tokensUsed:c,modelSpec:h&&m?`${h}:${m}`:null}}let De=P.map(A=>{let M=A.function.name,D=yu(A.function.arguments),W=A.id||`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!D)return Promise.resolve({role:"tool",content:`ERROR: Malformed tool arguments for ${M}`,tool_call_id:W});let Q=null;if(X$.has(M)&&D.path){let qe=require("path"),Re=qe.isAbsolute(D.path)?D.path:qe.resolve(process.cwd(),D.path);if(l.has(Re)||!z$(Re,r))return Promise.resolve({role:"tool",content:`ERROR: File '${D.path}' is locked by another operation. Try a different approach or skip this file.`,tool_call_id:W});l.add(Re),Q=Re}return i.push(M),(M==="spawn_agents"?Au(D,s+1):y(M,D,{autoConfirm:!0,silent:!0})).then(qe=>{Q&&(_s(Q),l.delete(Q));let Re=String(qe??"");return{role:"tool",content:Re.length>2e4?Re.substring(0,2e4)+`
|
|
176
|
+
...(truncated)`:Re,tool_call_id:W}}).catch(qe=>(Q&&(_s(Q),l.delete(Q)),{role:"tool",content:`ERROR: ${qe.message}`,tool_call_id:W}))}),me=await Promise.all(De);f.push(...me);for(let A=0;A<P.length;A++){let M=P[A];if(M.function.name==="bash_exec"){let D=yu(M.function.arguments);if((me[A]?.content||"").startsWith("ERROR")&&D&&D.command){let Q=D.command.replace(/\s+/g," ").trim().slice(0,100);u.set(Q,(u.get(Q)||0)+1)}}}e.onUpdate&&e.onUpdate(`step ${k+1}/${n}`)}for(let k of l)_s(k);let b=[...u.entries()].filter(([,k])=>k>=3).sort((k,R)=>R[1]-k[1]).slice(0,3).map(([k,R])=>`"${k}" (failed ${R}\xD7)`);return{task:t.task,status:"truncated",abortReason:"iteration_limit",repeatedFailures:b,result:f[f.length-1]?.content||"(max iterations reached)",toolsUsed:i,tokensUsed:c,modelSpec:h&&m?`${h}:${m}`:null}}catch(b){for(let k of l)_s(k);return{task:t.task,status:"failed",result:`Error: ${b.message}`,toolsUsed:i,tokensUsed:c,modelSpec:h&&m?`${h}:${m}`:null}}}async function Au(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?K$:Y$,o=e===0?_u:xu,n=(t.agents||[]).slice(0,s);if(n.length===0)return"ERROR: No agents specified";let r=e>0?" \u21B3 ":"",i=e>0?38:44,c=n.map(d=>Ei(d)),l=n.map((d,f)=>{let p=c[f],h=p.model?` [${p.model}]`:"",m=d.task.substring(0,i-h.length);return`${r}Agent ${f+1}${h}: ${m}${d.task.length>m.length?"...":""}`}),u=new G$(l);u.start();try{let d=n.map((g,$)=>{let y=c[$],x=Math.min(g.max_iterations||o,o),_=y.model?{...g,model:`${y.provider}:${y.model}`,_skipLog:!0,max_iterations:x}:{...g,_skipLog:!0,max_iterations:x};return Cu(_,{onUpdate:()=>{}},e).then(v=>(u.update($,v.status==="failed"?"error":"done"),v)).catch(v=>(u.update($,"error"),{task:g.task,status:"failed",result:`Error: ${v.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}))}),f=await Promise.all(d);u.stop(),Si();let p=["Sub-agent results:",""],h=0,m=0;for(let g=0;g<f.length;g++){let $=f[g],y=$.status==="done"?"\u2713":$.status==="truncated"?"\u26A0":"\u2717",x=$.modelSpec?` [${$.modelSpec}]`:"";p.push(`${y} Agent ${g+1}${x}: ${$.task}`),p.push(` Status: ${$.status}`),p.push(` Tools used: ${$.toolsUsed.length>0?$.toolsUsed.join(", "):"none"}`),p.push(` Result: ${$.result}`),$.repeatedFailures&&$.repeatedFailures.length>0&&p.push(` Repeated failures: ${$.repeatedFailures.join("; ")}`),p.push(""),h+=$.tokensUsed.input,m+=$.tokensUsed.output}return p.push(`Total sub-agent tokens: ${h} input + ${m} output`),p.join(`
|
|
177
|
+
`)}catch(d){return u.stop(),Si(),`ERROR: Sub-agent execution failed: ${d.message}`}}Ou.exports={runSubAgent:Cu,executeSpawnAgents:Au,clearAllLocks:Si,classifyTask:Tu,pickModelForTier:Ru,resolveSubAgentModel:Ei,isRetryableError:vu,callWithRetry:Su,getExcludedTools:Eu,LOCK_TIMEOUT_MS:ku}});var vs=G((Jx,Ku)=>{var Ee=require("fs"),Dt=require("path"),{atomicWrite:Mu,withFileLockSync:Pu}=Xt(),Z$=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 Fn(){let t=Dt.join(process.cwd(),".nex","brain");return Ee.existsSync(t)||Ee.mkdirSync(t,{recursive:!0}),t}function qo(){return Dt.join(Fn(),".brain-index.json")}function Ci(){return Dt.join(Fn(),".embeddings.json")}function xs(){let t=Dt.join(process.cwd(),".nex","brain");if(!Ee.existsSync(t))return[];try{return Ee.readdirSync(t).filter(e=>e.endsWith(".md")&&!e.startsWith(".")).map(e=>{let s=Dt.join(t,e),o=Ee.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 ks(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 i=r.match(/^(\w+):\s*(.+)$/);if(!i)continue;let c=i[1].trim(),l=i[2].trim();l.startsWith("[")&&l.endsWith("]")?e[c]=l.slice(1,-1).split(",").map(u=>u.trim()).filter(Boolean):e[c]=l}s=o[2]}return{frontmatter:e,body:s}}function Iu(t){let e=Dt.join(Fn(),`${t}.md`);if(!Ee.existsSync(e))return{name:t,content:"",body:"",frontmatter:{}};let s=Ee.readFileSync(e,"utf-8"),{frontmatter:o,body:n}=ks(s);return{name:t,content:s,body:n,frontmatter:o}}function ey(t,e){let s=Dt.join(Fn(),`${t}.md`);Mu(s,e),sy(t,e),ty()}function ty(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return;let t=Ci();Ee.existsSync(t)&&setImmediate(async()=>{try{await Wu()}catch{}})}function ny(t){let e=Dt.join(Fn(),`${t}.md`);return Ee.existsSync(e)?(Ee.unlinkSync(e),oy(t),!0):!1}function Do(t){return t.toLowerCase().replace(/[^a-z0-9äöüß\s-]/g," ").split(/[\s-]+/).filter(e=>e.length>2&&!Z$.has(e))}function Ai(t){let e={},{frontmatter:s,body:o}=ks(t),n=Array.isArray(s.tags)?s.tags:[];for(let i of n){let c=i.toLowerCase().replace(/[^a-z0-9-]/g,"");c.length>1&&(e[c]=(e[c]||0)+5)}let r=(o||t).split(`
|
|
179
|
+
`);for(let i of r)if(i.startsWith("#")){let c=i.replace(/^#+\s*/,"");for(let l of Do(c))e[l]=(e[l]||0)+3}for(let i of Do(o||t))e[i]=(e[i]||0)+1;return e}function Oi(){let t=qo();if(!Ee.existsSync(t))return{documents:{}};try{return JSON.parse(Ee.readFileSync(t,"utf-8"))}catch{return{documents:{}}}}function Ni(t){Mu(qo(),JSON.stringify(t,null,2))}function sy(t,e){Pu(qo(),()=>{let s=Oi(),{frontmatter:o}=ks(e),n=Array.isArray(o.tags)?o.tags:[];s.documents[t]={keywords:Ai(e),tags:n,modified:new Date().toISOString()},Ni(s)})}function oy(t){Pu(qo(),()=>{let e=Oi();delete e.documents[t],Ni(e)})}function Ri(){let t=xs(),e={documents:{}};for(let s of t){let o=Ee.readFileSync(s.path,"utf-8"),{frontmatter:n}=ks(o),r=Array.isArray(n.tags)?n.tags:[];e.documents[s.name]={keywords:Ai(o),tags:r,modified:s.modified.toISOString()}}return Ni(e),e}function Lu(){let t=Oi(),e=xs();for(let s of e){let o=t.documents[s.name];if(!o||new Date(o.modified)<s.modified)return Ri()}for(let s of Object.keys(t.documents))if(!e.some(o=>o.name===s))return Ri();return t}function ju(t,e={}){let{topK:s=3,minScore:o=.1}=e,n=Do(t);if(n.length===0)return[];let r=Lu(),i=[];for(let[c,l]of Object.entries(r.documents)){let u=0;for(let d of n){l.keywords[d]&&(u+=l.keywords[d]);for(let[f,p]of Object.entries(l.keywords))f!==d&&f.length>3&&d.length>3&&(f.includes(d)||d.includes(f))&&(u+=p*.3)}u>=o&&i.push({name:c,score:u})}return i.sort((c,l)=>l.score-c.score),i.slice(0,s)}var Du=process.env.NEX_EMBED_MODEL||"nomic-embed-text",Ti=400,ry=50;async function qu(){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",p=>f+=p),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(Du.split(":")[0]))}catch{return!1}}async function Mi(t){let e=process.env.OLLAMA_HOST||"http://localhost:11434",s=require("http"),o=require("https"),n=new URL(`${e}/api/embeddings`),r=n.protocol==="https:"?o:s,i=JSON.stringify({model:Du,prompt:t});return new Promise((c,l)=>{let u=r.request(n,{method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(i)},timeout:3e4},d=>{let f="";d.on("data",p=>f+=p),d.on("end",()=>{try{c(JSON.parse(f).embedding||[])}catch(p){l(p)}})});u.on("error",l),u.on("timeout",()=>{u.destroy(),l(new Error("embedding timeout"))}),u.write(i),u.end()})}function Fu(t,e){if(!t||!e||t.length!==e.length)return 0;let s=0,o=0,n=0;for(let i=0;i<t.length;i++)s+=t[i]*e[i],o+=t[i]*t[i],n+=e[i]*e[i];let r=Math.sqrt(o)*Math.sqrt(n);return r===0?0:s/r}function Uu(t){let e=t.split(/\s+/),s=[],o=0;for(;o<e.length;){let n=e.slice(o,o+Ti).join(" ");if(s.push({text:n,offset:o}),o+Ti>=e.length)break;o+=Ti-ry}return s}async function Wu(){let t=xs(),e={documents:{}},s=Ci();if(Ee.existsSync(s))try{e=JSON.parse(Ee.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=Ee.readFileSync(o.path,"utf-8"),i=Uu(r),c=[];for(let l of i){let u=await Mi(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 Ee.writeFileSync(s,JSON.stringify(e),"utf-8"),e}async function Bu(t,e={}){let{topK:s=3,minSimilarity:o=.3}=e,n=Ci();if(!Ee.existsSync(n))return[];let r;try{r=JSON.parse(Ee.readFileSync(n,"utf-8"))}catch{return[]}let i=await Mi(t),c=[];for(let[l,u]of Object.entries(r.documents||{})){let d=0,f="";for(let p of u.chunks||[]){let h=Fu(i,p.embedding);h>d&&(d=h,f=p.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 Hu(t,e,s={}){let{k:o=60,topK:n=3}=s,r={};return t.forEach((i,c)=>{r[i.name]=(r[i.name]||0)+1/(o+c+1)}),e.forEach((i,c)=>{r[i.name]=(r[i.name]||0)+1/(o+c+1)}),Object.entries(r).map(([i,c])=>({name:i,score:c})).sort((i,c)=>c.score-i.score).slice(0,n)}async function Gu(t,e={}){let{topK:s=3,minScore:o=.1}=e,n=ju(t,{topK:s,minScore:o}),r=n;if(process.env.NEX_BRAIN_EMBEDDINGS!=="false")try{if(await qu()){let c=await Bu(t,{topK:s});r=Hu(n,c,{topK:s})}}catch{}return r.map(i=>{let c=Iu(i.name),l=(c.body||c.content||"").slice(0,300).replace(/\n+/g," ")+"...";return{name:i.name,score:i.score,content:c.content,excerpt:l}})}async function iy(t){if(!t||!t.trim())return"";let e=Dt.join(process.cwd(),".nex","brain");if(!Ee.existsSync(e)||xs().length===0)return"";let o;try{o=await Gu(t,{topK:3})}catch{return""}if(!o||o.length===0)return"";let n;try{n=He().estimateTokens}catch{n=l=>Math.ceil(l.length/4)}let r=25e3,i=[],c=0;for(let l of o){let u=l.content||"",d=n(u);if(c+d>r){let p=r-c;if(p<100)break;let h=p/d;u=u.slice(0,Math.floor(u.length*h))+`
|
|
179
180
|
...(truncated)`}let f=typeof l.score=="number"?l.score.toFixed(2):String(l.score);if(i.push(`--- ${l.name} (relevance: ${f}) ---
|
|
180
181
|
${u}`),c+=n(u),c>=r)break}return i.length===0?"":`KNOWLEDGE BASE (auto-selected):
|
|
181
182
|
|
|
182
183
|
${i.join(`
|
|
183
184
|
|
|
184
|
-
`)}`}
|
|
185
|
-
`;
|
|
186
|
-
`).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
|
|
187
|
-
${i.map(l=>
|
|
188
|
-
`)}`}}catch{}return{fixedPath:null,message:""}}function
|
|
185
|
+
`)}`}Ku.exports={getBrainDir:Fn,listDocuments:xs,readDocument:Iu,writeDocument:ey,removeDocument:ny,buildIndex:Ri,getIndex:Lu,query:Gu,getBrainContext:iy,isEmbeddingAvailable:qu,generateEmbedding:Mi,buildEmbeddingIndex:Wu,semanticQuery:Bu,cosineSimilarity:Fu,_keywordQuery:ju,_extractKeywords:Ai,_chunkText:Uu,parseFrontmatter:ks,tokenize:Do,_fuseResults:Hu}});var Li=G((Vx,Vu)=>{var Ss=require("fs"),Pi=require("path"),Ii=process.env.NEX_AUDIT!=="false",mn=null;function Yu(){return mn||(mn=Pi.join(process.cwd(),".nex","audit"),Ss.existsSync(mn)||Ss.mkdirSync(mn,{recursive:!0}),mn)}function zu(){let t=new Date().toISOString().split("T")[0];return Pi.join(Yu(),`${t}.jsonl`)}function ay(t){if(Ii)try{let e={timestamp:new Date().toISOString(),tool:t.tool,args:Xu(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
|
+
`;Ss.appendFileSync(zu(),s,"utf-8")}catch{}}function Xu(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 Ju(t={}){let e=Yu(),s=t.days||1,o=[];for(let n=0;n<s;n++){let r=t.date||new Date(Date.now()-n*864e5).toISOString().split("T")[0],i=Pi.join(e,`${r}.jsonl`);if(!Ss.existsSync(i))continue;let c=Ss.readFileSync(i,"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 cy(t=1){let e=Ju({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 ly(t){Ii=t}function uy(){return Ii}function dy(){mn=null}Vu.exports={logToolExecution:ay,sanitizeArgs:Xu,readAuditLog:Ju,getAuditSummary:cy,setAuditEnabled:ly,isAuditEnabled:uy,getAuditLogPath:zu,_reset:dy}});var kt=G((ek,ad)=>{var Te=require("fs").promises,Qu=require("fs"),he=require("path"),ge=require("util").promisify(require("child_process").exec),ji=require("util").promisify(require("child_process").execFile),{spawnSync:fy}=require("child_process"),Di=require("axios"),{isForbidden:py,isSSHForbidden:my,isDangerous:hy,isCritical:Zu,isBashPathForbidden:gy,confirm:vt}=Ue(),{showClaudeDiff:Fo,showClaudeNewFile:$y,showEditDiff:Qx,confirmFileChange:Es}=hl(),{C:V,Spinner:yy,getToolSpinnerText:wy}=ve(),{isGitRepo:qi,getCurrentBranch:ed,getStatus:by,getDiff:_y}=Vt(),{recordChange:Uo}=It(),{fuzzyFindText:td,findMostSimilar:Cs}=Yl(),{runDiagnostics:Ts}=Xl(),{findFileInIndex:xy,getFileIndex:Zx}=yi(),{resolveProfile:wt,sshExec:tt,scpUpload:ky,scpDownload:vy}=qn(),{resolveDeployConfig:Sy,loadDeployConfigs:Ey}=xi(),{getEditMode:nd}=No(),Ty=/^(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/,Ry=/^ssh\s/,Cy=/^ssh(?:\s+-\S+)*\s+\S+@?\S+\s+["']?[^-]/;async function ct(t){return Te.access(t).then(()=>!0).catch(()=>!1)}async function Wo(t){if(!t)return{fixedPath:null,message:""};let e=t.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),s=nt(e);if(s&&await ct(s))return{fixedPath:s,message:`(auto-fixed path: ${t} \u2192 ${e})`};let o=[".js",".ts",".jsx",".tsx",".mjs",".cjs",".json"],n=he.extname(t);if(!n)for(let i of o){let c=nt(t+i);if(c&&await ct(c))return{fixedPath:c,message:`(auto-fixed: added ${i} extension)`}}if(n){let i=t.replace(/\.[^.]+$/,"");for(let c of o){if(c===n)continue;let l=nt(i+c);if(l&&await ct(l))return{fixedPath:l,message:`(auto-fixed: ${n} \u2192 ${c})`}}}let r=he.basename(t);if(r&&r.length>2)try{let i=xy(r).map(c=>nt(c));if(i.length===1)return{fixedPath:i[0],message:`(auto-fixed: found ${r} at ${he.relative(process.cwd(),i[0])})`};if(i.length>1&&i.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
|
|
188
|
+
${i.map(l=>he.relative(process.cwd(),l)).map(l=>` - ${l}`).join(`
|
|
189
|
+
`)}`}}catch{}return{fixedPath:null,message:""}}function Ay(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.":/\bsed\s+-n\s+['"]?\d+,\d+p/.test(t)?'sed -n line-range scrolling floods context with irrelevant lines. Use targeted grep instead: grep -n "ERROR\\|pattern" <logfile> | tail -20':""}function rd(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+`
|
|
189
190
|
|
|
190
191
|
`+s.join(`
|
|
191
|
-
`)}function Pu(t,e,s){let o=$s(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 Nu=!1,cn=null;function J$(){cn&&(cn(),cn=null)}var xi=null;function V$(t){xi=t}async function _i(){if(!Nu){Nu=!0;try{let{stdout:t}=await le("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await le('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await le("git stash pop",{cwd:process.cwd(),timeout:1e4}),await le("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var Q$=[/\.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=ue.isAbsolute(t)?ue.resolve(t):ue.resolve(process.cwd(),t);for(let s of Q$)if(s.test(e))return null;return e}var Z$=[{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 (package_action: check|list|install|remove|update|upgrade); 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 gs(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 Mu(t,e,s={}){switch(t){case"bash":{let o=e.command,n=N$(o);if(n){let f=X$(o);return`BLOCKED: Command matches forbidden pattern: ${n}${f?`
|
|
192
|
-
HINT: ${f}`:""}`}let r=
|
|
193
|
-
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?
|
|
194
|
-
${h}`}}case"read_file":{let o=
|
|
195
|
-
`+
|
|
196
|
-
`),d=(e.line_start||1)-1
|
|
197
|
-
`)
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
Most similar text (line ${
|
|
204
|
-
${
|
|
205
|
-
`)
|
|
206
|
-
`).
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
`)
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
192
|
+
`)}function id(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 sd=!1,hn=null;function Oy(){hn&&(hn(),hn=null)}var Ui=null;function Ny(t){Ui=t}async function Fi(){if(!sd){sd=!0;try{let{stdout:t}=await ge("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await ge('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await ge("git stash pop",{cwd:process.cwd(),timeout:1e4}),await ge("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var My=[/\.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 nt(t){let e=he.isAbsolute(t)?he.resolve(t):he.resolve(process.cwd(),t);for(let s of My)if(s.test(e))return null;return e}var Py=[{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)"},staged:{type:"boolean",description:"Search only staged content (git diff --cached). Default: false"}},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 (package_action: check|list|install|remove|update|upgrade); 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 Rs(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 od(t,e,s={}){switch(t){case"bash":{let o=e.command,n=py(o);if(n){let f=Ay(o);return`BLOCKED: Command matches forbidden pattern: ${n}${f?`
|
|
193
|
+
HINT: ${f}`:""}`}let r=gy(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?Zu(o):hy(o)){let f=Zu(o)?"\u26D4":"\u26A0";if(!await vt(` ${f} bash: \`${o}\``,{toolName:"bash"}))return"CANCELLED: User declined to execute this command."}let c;try{c=process.cwd(),Qu.accessSync(c)}catch{c=require("os").homedir(),s.silent||console.log(`${V.yellow} \u26A0 Working directory no longer exists \u2014 running in ${c}${V.reset}`)}let l=Ry.test(o.trim())&&!Cy.test(o.trim());if(Ty.test(o.trim())||l){s.silent||console.log(`${V.dim} \u25B6 interactive: ${o}${V.reset}`);let f=fy("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}=Rn(),d=s.silent?null:new u("bash",o.substring(0,40));d&&d.start();try{let{stdout:f,stderr:p}=await ge(o,{cwd:c,timeout:9e4,maxBuffer:5242880});return d&&d.stop(),f||p||"(no output)"}catch(f){d&&d.stop();let p=(f.stderr||f.stdout||f.message||"").toString().substring(0,5e3),h=rd(p,o);return`EXIT ${f.code||1}
|
|
195
|
+
${h}`}}case"read_file":{let o=nt(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await ct(o)){let k=await Wo(e.path);if(k.fixedPath)o=k.fixedPath,console.log(`${V.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${he.relative(process.cwd(),o)}${V.reset}`);else return`ERROR: File not found: ${e.path}${k.message?`
|
|
196
|
+
`+k.message:""}`}let r=Buffer.alloc(8192),i=await Qu.promises.open(o,"r"),{bytesRead:c}=await i.read(r,0,8192,0);await i.close();for(let k=0;k<c;k++)if(r[k]===0)return`ERROR: ${o} is a binary file (not readable as text)`;let l=await Te.readFile(o,"utf-8");if(!l&&(await Te.stat(o)).size>0)return`WARNING: ${o} is empty or unreadable`;let u=l.split(`
|
|
197
|
+
`),d=await Te.stat(o),f=u.length,p=350,h=!e.line_start&&!e.line_end,m=h&&f>p,g=(e.line_start||1)-1,$=m?p:e.line_end||u.length,y=he.relative(process.cwd(),o),x=m?`showing lines 1-${p} of ${f}`:e.line_start||e.line_end?`lines ${g+1}-${$} of ${f}`:`${f} lines`,_=`File: ${y} (${x}, ${d.size} bytes)`,v=u.slice(g,$).map((k,R)=>`${g+R+1}: ${k}`).join(`
|
|
198
|
+
`),b=m?`
|
|
199
|
+
|
|
200
|
+
[File truncated: showing lines 1-${p} of ${f} total. Use line_start/line_end to read other sections, e.g. line_start=${p+1} line_end=${Math.min(p*2,f)}]`:!h&&f>p?`
|
|
201
|
+
[Large file (${f} lines total) \u2014 use line_start/line_end for other sections]`:"";return`${_}
|
|
202
|
+
${v}${b}`}case"write_file":{await Fi();let o=nt(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let n=await ct(o),r=null;if(s.autoConfirm)n&&(r=await Te.readFile(o,"utf-8"));else if(n){r=await Te.readFile(o,"utf-8");let d=await Ts(o,e.content);if(Fo(o,r,e.content,{annotations:d}),!await Es("Overwrite"))return"CANCELLED: User declined to overwrite file."}else{let d=await Ts(o,e.content);if($y(o,e.content,{annotations:d}),!await Es("Create"))return"CANCELLED: User declined to create file."}let i=he.dirname(o);await ct(i)||await Te.mkdir(i,{recursive:!0}),await Te.writeFile(o,e.content,"utf-8");let l=/[/\\]\.git[/\\]hooks[/\\]/.test(o)||o.endsWith(".sh")||e.content.startsWith("#!");l&&await Te.chmod(o,493),Uo("write_file",o,r,e.content);let u=l?" [chmod +x applied]":"";return`Written: ${o} (${e.content.length} chars)${u}`}case"edit_file":{await Fi();let o=nt(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await ct(o)){let d=await Wo(e.path);if(d.fixedPath)o=d.fixedPath,console.log(`${V.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${he.relative(process.cwd(),o)}${V.reset}`);else return`ERROR: File not found: ${e.path}${d.message?`
|
|
203
|
+
`+d.message:""}`}let r=await Te.readFile(o,"utf-8"),i=e.old_text,c=!1,l=!1;if(!r.includes(e.old_text)){let{getActiveModelId:d,getActiveProviderName:f}=Se();if(nd(d(),f())==="strict"){let m=Cs(r,e.old_text);return m?`ERROR: old_text not found in ${o} (strict mode \u2014 exact match required)
|
|
204
|
+
Most similar text (line ${m.line}, distance ${m.distance}):
|
|
205
|
+
${m.text}`:`ERROR: old_text not found in ${o} (strict mode \u2014 exact match required)`}let h=td(r,e.old_text);if(h)i=h,c=!0,console.log(`${V.dim} \u2713 fuzzy whitespace match applied${V.reset}`);else{let m=id(r,e.old_text,e.new_text);if(m){if(!s.autoConfirm){let _=await Ts(o,m.content);if(Fo(o,r,m.content,{annotations:_}),!await Es(`Apply (auto-fix, line ${m.line}, distance ${m.distance})`))return"CANCELLED: User declined to apply edit."}await Te.writeFile(o,m.content,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(o)||o.endsWith(".sh")||m.content.startsWith("#!"))&&await Te.chmod(o,493),Uo("edit_file",o,r,m.content);let x=m.matchText.length>80?m.matchText.substring(0,77)+"...":m.matchText;return console.log(`${V.dim} \u2713 auto-fixed edit: line ${m.line}, distance ${m.distance}${V.reset}`),`Edited: ${o} (auto-fixed, line ${m.line}, distance ${m.distance}, matched: "${x}")`}let g=Cs(r,e.old_text);if(g){let x=r.split(`
|
|
206
|
+
`),_=Math.max(0,g.line-6),v=Math.min(x.length,g.line+10),b=x.slice(_,v).map((R,O)=>`${_+O+1}: ${R}`).join(`
|
|
207
|
+
`),k=`line_start=${Math.max(1,g.line-5)} line_end=${Math.min(x.length,g.line+15)}`;return`ERROR: old_text not found in ${o} (most similar at line ${g.line}, distance ${g.distance})
|
|
208
|
+
|
|
209
|
+
Actual file content around line ${g.line} \u2014 use this to correct old_text:
|
|
210
|
+
${b}
|
|
211
|
+
|
|
212
|
+
Fix: update old_text to match the exact lines above, then retry. If you need more context: read_file with ${k}`}let $=(e.old_text||"").trim().split(`
|
|
213
|
+
`)[0].slice(0,60),y=$?`
|
|
214
|
+
Recovery: grep -n "${$.replace(/"/g,'\\"')}" <file> to find the line, then re-read that section with line_start/line_end.`:`
|
|
215
|
+
Recovery: use grep -n to locate the text, then re-read that section with line_start/line_end.`;return`ERROR: old_text not found in ${o}${y}`}}if(!s.autoConfirm){let d=r.split(i).join(e.new_text),f=await Ts(o,d);if(Fo(o,r,d,{annotations:f}),!await Es(c?"Apply (fuzzy match)":"Apply"))return"CANCELLED: User declined to apply edit."}let u=r.split(i).join(e.new_text);return await Te.writeFile(o,u,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(o)||o.endsWith(".sh")||u.startsWith("#!"))&&await Te.chmod(o,493),Uo("edit_file",o,r,u),c?`Edited: ${o} (fuzzy match)`:`Edited: ${o}`}case"list_directory":{let o=nt(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await ct(o)){let u=e.path.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),d=nt(u),f=await ct(d);if(d&&f)o=d;else return`ERROR: Directory not found: ${e.path}`}let r=e.max_depth||2,i=null;if(e.pattern)try{let u=e.pattern.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");i=new RegExp(`^${u}$`)}catch{return`ERROR: Invalid pattern: ${e.pattern}`}let c=[],l=async(u,d,f)=>{if(d>r)return;let p;try{p=await Te.readdir(u,{withFileTypes:!0})}catch{return}p=p.filter(h=>!h.name.startsWith(".")&&h.name!=="node_modules");for(let h of p){if(i&&!h.isDirectory()&&!i.test(h.name))continue;let m=h.isDirectory()?"/":"";c.push(`${f}${h.name}${m}`),h.isDirectory()&&await l(he.join(u,h.name),d+1,f+" ")}};return await l(o,1,""),c.join(`
|
|
216
|
+
`)||"(empty)"}case"search_files":{let o=nt(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 ji("grep",n,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),i=r.split("\0"),c=[];for(let l=0;l<i.length;l+=2){let u=i[l],d=i[l+1];if(u&&d){let f=d.split(`
|
|
217
|
+
`).filter(p=>p.trim());for(let p of f)if(c.push(`${u}:${p}`),c.length>=50)break}if(c.length>=50)break}return c.join(`
|
|
218
|
+
`)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let n=process.cwd(),r=e.path?nt(e.path):n,i=e.pattern,c=O=>{let P=O.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"(.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");return new RegExp(`^${P}$`)},l=c(i),u=i.split("/").pop(),d=c(u),{ToolProgress:f}=Rn(),p=new f("glob","Finding files...");p.start();let{getFileIndex:h,getIndexedCwd:m,refreshIndex:g,isIndexValid:$}=yi(),y=h(),x=m();$(r)||(await g(r),y=h());let _=y.filter(O=>l.test(O)||d.test(he.basename(O))).map(O=>he.join(r,O));if(_.length===0)return p.stop(),"(no matches)";let v=await Promise.all(_.slice(0,210).map(async O=>{try{let P=await Te.stat(O);return{path:O,mtime:P.mtimeMs}}catch{return{path:O,mtime:0}}}));v.sort((O,P)=>P.mtime-O.mtime);let b=v.map(O=>O.path),k=_.length>200,R=b.slice(0,200).join(`
|
|
219
|
+
`);return p.update({count:_.length,detail:e.pattern}),p.stop(),k?`${R}
|
|
220
|
+
|
|
221
|
+
\u26A0 Results truncated at 200. Use a more specific pattern.`:R}case"grep":{let o=e.path?nt(e.path):process.cwd();if(e.staged){let{getDiff:l}=Vt(),u=await l(!0);if(!u.trim())return"(no staged changes)";let d=new Set,f=u.split(`
|
|
222
|
+
`);for(let $ of f)if($.startsWith("diff --git")){let y=$.match(/diff --git a\/(.+) b\/(.+)/);y&&d.add(y[2])}let p=["-rn","-E","--null","-H","--exclude=*.md","--exclude=*.txt","--exclude=*.json","--exclude=*.yaml","--exclude=*.yml"];e.ignore_case&&p.push("-i"),e.include&&p.push(`--include=${e.include}`),e.type&&p.push(`--include=*.${e.type}`),e.context?p.push("-C",String(e.context)):(e.before_context&&p.push("-B",String(e.before_context)),e.after_context&&p.push("-A",String(e.after_context))),e.output_mode==="files_with_matches"?p.push("-l"):e.output_mode==="count"&&p.push("-c"),p.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage");let{ToolProgress:h}=Rn(),m=new h("grep","Searching staged content...");m.start();let g=[];for(let $ of d)try{let y=he.join(process.cwd(),$);if(await ct(y)){let x=[...p];x.push(e.pattern,y);let{stdout:_}=await ji("grep",x,{cwd:process.cwd(),timeout:3e4,maxBuffer:2*1024*1024});if(e.output_mode==="files_with_matches"||e.output_mode==="count"){let v=_.trim().split(`
|
|
223
|
+
`).filter(b=>b.trim());g=g.concat(v)}else{let v=_.split("\0");for(let b=0;b<v.length;b+=2){let k=v[b+1];if(k){let R=k.split(`
|
|
224
|
+
`).filter(O=>O.trim());for(let O of R)g.push(`${$}:${O}`)}}}}}catch{}return m.update({count:g.length,detail:"in staged files"}),m.stop(),g.join(`
|
|
225
|
+
`).trim()||"(no matches in staged files)"}let 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}`);let r=20;e.context?n.push("-C",String(Math.min(Number(e.context),r))):(e.before_context&&n.push("-B",String(Math.min(Number(e.before_context),r))),e.after_context&&n.push("-A",String(Math.min(Number(e.after_context),r)))),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:i}=Rn(),c=new i("grep","Searching...");c.start();try{let{stdout:l}=await ji("grep",n,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),u;if(e.output_mode==="files_with_matches"||e.output_mode==="count")u=l.trim().split(`
|
|
226
|
+
`).filter(p=>p.trim());else{let p=l.split("\0");u=[];for(let h=0;h<p.length;h+=2){let m=p[h],g=p[h+1];if(m&&g){let $=g.split(`
|
|
227
|
+
`).filter(y=>y.trim());for(let y of $)u.push(`${m}:${y}`)}}}let d=e.offset||0,f=e.head_limit||(e.output_mode==="files_with_matches"?200:100);return u=u.slice(d,d+f),c.update({count:u.length,detail:`in ${o}`}),c.stop(),u.join(`
|
|
228
|
+
`).trim()||"(no matches)"}catch(l){return c.stop(),l.code===2?`ERROR: Invalid regex pattern: ${e.pattern}`:"(no matches)"}}case"patch_file":{await Fi();let o=nt(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await ct(o)){let y=await Wo(e.path);if(y.fixedPath)o=y.fixedPath,console.log(`${V.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${he.relative(process.cwd(),o)}${V.reset}`);else return`ERROR: File not found: ${e.path}${y.message?`
|
|
229
|
+
`+y.message:""}`}let r=e.patches;if(!Array.isArray(r)||r.length===0)return"ERROR: No patches provided";let i=await Te.readFile(o,"utf-8"),{getActiveModelId:c,getActiveProviderName:l}=Se(),u=nd(c(),l()),d=[],f=!1,p=!1;for(let y=0;y<r.length;y++){let{old_text:x,new_text:_}=r[y];if(i.includes(x))d.push({old_text:x,new_text:_});else if(u==="strict"){let v=Cs(i,x);return v?`ERROR: Patch ${y+1} old_text not found in ${o} (strict mode \u2014 exact match required)
|
|
217
230
|
Most similar text (line ${v.line}, distance ${v.distance}):
|
|
218
|
-
${v.text}
|
|
231
|
+
${v.text}`:`ERROR: Patch ${y+1} old_text not found in ${o} (strict mode \u2014 exact match required)`}else{let v=td(i,x);if(v)d.push({old_text:v,new_text:_}),f=!0;else{let b=Cs(i,x);if(b){let k=Math.max(3,Math.ceil(x.length*.05));if(b.distance<=k)d.push({old_text:b.text,new_text:_}),p=!0;else return`ERROR: Patch ${y+1} old_text not found in ${o}
|
|
232
|
+
Most similar text (line ${b.line}, distance ${b.distance}):
|
|
233
|
+
${b.text}`}else return`ERROR: Patch ${y+1} old_text not found in ${o}`}}}let h=i;for(let{old_text:y,new_text:x}of d)h=h.split(y).join(x);if(!s.autoConfirm){let y=await Ts(o,h);if(Fo(o,i,h,{annotations:y}),!await Es(f?"Apply patches (fuzzy match)":"Apply patches"))return"CANCELLED: User declined to apply patches."}await Te.writeFile(o,h,"utf-8");let m=/[/\\]\.git[/\\]hooks[/\\]/.test(o)||o.endsWith(".sh")||h.startsWith("#!");m&&await Te.chmod(o,493),Uo("patch_file",o,i,h);let g=p?" (auto-fixed)":f?" (fuzzy match)":"",$=m?" [chmod +x applied]":"";return`Patched: ${o} (${r.length} replacements)${g}${$}`}case"web_fetch":{let o=e.url,n=e.max_length||1e4;try{let r=await Di.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 Di.post("https://api.perplexity.ai/chat/completions",{model:"sonar",messages:[{role:"user",content:e.query}],max_tokens:1024,search_recency_filter:"month",return_citations:!0},{timeout:2e4,headers:{Authorization:`Bearer ${process.env.PERPLEXITY_API_KEY}`,"Content-Type":"application/json"}}),r=n.data?.choices?.[0]?.message?.content||"",i=n.data?.citations||[],c=`[Perplexity grounded search]
|
|
219
234
|
|
|
220
235
|
${r}`;return i.length>0&&(c+=`
|
|
221
236
|
|
|
222
237
|
Sources:
|
|
223
238
|
`+i.slice(0,o).map((l,u)=>`${u+1}. ${l}`).join(`
|
|
224
|
-
`)),c}catch(n){console.error(`${
|
|
239
|
+
`)),c}catch(n){console.error(`${V.dim} Perplexity search failed (${n.message}), falling back to DuckDuckGo${V.reset}`)}try{let r=(await Di.get("https://html.duckduckgo.com/html/",{params:{q:e.query},timeout:1e4,responseType:"text",headers:{"User-Agent":"nex-code/0.2.0"}})).data,i=[],c=/<a[^>]*class="result__a"[^>]*href="([^"]*)"[^>]*>([\s\S]*?)<\/a>/gi,l;for(;(l=c.exec(r))!==null&&i.length<o;){let u=l[1].replace(/.*uddg=/,"").split("&")[0],d=l[2].replace(/<[^>]+>/g,"").trim();try{i.push({title:d,url:decodeURIComponent(u)})}catch{i.push({title:d,url:u})}}return i.length===0?"(no results)":i.map((u,d)=>`${d+1}. ${u.title}
|
|
225
240
|
${u.url}`).join(`
|
|
226
241
|
|
|
227
|
-
`)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:o}=
|
|
242
|
+
`)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:o}=ys();try{let n=await o(e.url,{waitFor:e.wait_for}),r=n.links.length>0?`
|
|
228
243
|
|
|
229
244
|
Links:
|
|
230
245
|
`+n.links.map(i=>` ${i.text} \u2192 ${i.href}`).join(`
|
|
231
246
|
`):"";return`Title: ${n.title}
|
|
232
247
|
URL: ${n.url}
|
|
233
248
|
|
|
234
|
-
${n.text}${r}`}catch(n){return`ERROR: ${n.message}`}}case"browser_screenshot":{let{browserScreenshot:o}=
|
|
249
|
+
${n.text}${r}`}catch(n){return`ERROR: ${n.message}`}}case"browser_screenshot":{let{browserScreenshot:o}=ys();try{let n=await o(e.url,{width:e.width,height:e.height,fullPage:e.full_page});return`Screenshot saved: ${n.path}
|
|
235
250
|
Title: ${n.title}
|
|
236
251
|
URL: ${n.url}
|
|
237
252
|
|
|
238
|
-
To analyze visually, paste the path into your next message: ${n.path}`}catch(n){return`ERROR: ${n.message}`}}case"browser_click":{let{browserClick:o}=
|
|
253
|
+
To analyze visually, paste the path into your next message: ${n.path}`}catch(n){return`ERROR: ${n.message}`}}case"browser_click":{let{browserClick:o}=ys();try{return await o(e.url,{selector:e.selector,text:e.text})}catch(n){return`ERROR: ${n.message}`}}case"browser_fill":{let{browserFill:o}=ys();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 Ui?new Promise(r=>{hn=()=>r("CANCELLED"),Ui(o,n).then(i=>{hn=null,r(i||"User did not answer")})}):new Promise(r=>{let i=require("readline").createInterface({input:process.stdin,output:process.stdout});hn=()=>{i.close(),r("CANCELLED")};let c=n.length>0?`
|
|
239
254
|
${n.map((l,u)=>` ${u+1}. ${l}`).join(`
|
|
240
255
|
`)}
|
|
241
256
|
`:"";console.log(`
|
|
242
|
-
${
|
|
257
|
+
${V.cyan}${V.bold} ? ${o}${V.reset}${c}`),i.question(`${V.cyan} > ${V.reset}`,l=>{hn=null,i.close(),r(l.trim()||"(no response)")})})}case"git_status":{if(!await qi())return"ERROR: Not a git repository";let o=await ed()||"(detached)",n=await by();if(n.length===0)return`Branch: ${o}
|
|
243
258
|
Clean working tree (no changes)`;let r=[`Branch: ${o}`,`Changed files (${n.length}):`];for(let i of n){let c=i.status==="M"?"modified":i.status==="A"?"added":i.status==="D"?"deleted":i.status==="??"?"untracked":i.status;r.push(` ${c}: ${i.file}`)}return r.join(`
|
|
244
|
-
`)}case"git_diff":{if(!await
|
|
259
|
+
`)}case"git_diff":{if(!await qi())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 _y(!!e.staged);return o||"(no diff)"}case"git_log":{if(!await qi())return"ERROR: Not a git repository";let n=["log","--oneline",`-${Math.min(e.count||10,50)}`];e.file&&n.push("--",e.file);try{return execFileSync("git",n,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()||"(no commits)"}catch{return"(no commits)"}}case"task_list":{let{createTasks:o,updateTask:n,getTaskList:r,renderTaskList:i,hasActiveTasks:c}=Po(),{getActiveTaskProgress:l}=ve(),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(`
|
|
245
260
|
`+i()),`Created task list "${e.name}" with ${d.length} tasks:
|
|
246
261
|
`+d.map(f=>` ${f.id}: ${f.description}`).join(`
|
|
247
262
|
`)}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(`
|
|
248
263
|
`+i()),`Updated ${e.task_id}: ${e.status}${e.result?" \u2014 "+e.result:""}`):`ERROR: Task not found: ${e.task_id}`;case"get":{let d=r();return d.tasks.length===0?"No active tasks":(u||console.log(`
|
|
249
|
-
`+i()),JSON.stringify(d,null,2))}default:return`ERROR: Unknown task_list action: ${e.action}. Use: create, update, get`}}case"spawn_agents":{let{executeSpawnAgents:o}=
|
|
264
|
+
`+i()),JSON.stringify(d,null,2))}default:return`ERROR: Unknown task_list action: ${e.action}. Use: create, update, get`}}case"spawn_agents":{let{executeSpawnAgents:o}=Nu();return o(e)}case"switch_model":{let{setActiveModel:o,getActiveProviderName:n,getActiveModelId:r}=Se();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 ge(`gh ${n.join(" ")}`,{cwd:process.cwd(),timeout:3e4}),i=JSON.parse(r||"[]");return i.length===0?"No workflow runs found.":i.map(l=>{let u=l.conclusion||l.status||"unknown",d=u==="success"?"\u2713":u==="failure"?"\u2717":u==="in_progress"?"\u283F":"\u25CB",f=l.updatedAt?new Date(l.updatedAt).toISOString().slice(0,16).replace("T"," "):"";return`${d} [${l.databaseId}] ${l.name} \xB7 ${l.headBranch} \xB7 ${u} \xB7 ${f}`}).join(`
|
|
250
265
|
`)}catch(r){let i=(r.stderr||r.message||"").toString();return i.includes("not found")||i.includes("not logged")?"ERROR: gh CLI not found or not authenticated. Run: gh auth login":`ERROR: ${i.split(`
|
|
251
|
-
`)[0]}`}}case"gh_run_view":{if(!e.run_id)return"ERROR: run_id is required";try{if(e.log){let{stdout:i}=await
|
|
252
|
-
...(truncated)`:"")}let{stdout:o}=await
|
|
266
|
+
`)[0]}`}}case"gh_run_view":{if(!e.run_id)return"ERROR: run_id is required";try{if(e.log){let{stdout:i}=await ge(`gh run view ${e.run_id} --log`,{cwd:process.cwd(),timeout:6e4,maxBuffer:5242880});return i.substring(0,8e3)+(i.length>8e3?`
|
|
267
|
+
...(truncated)`:"")}let{stdout:o}=await ge(`gh run view ${e.run_id} --json status,conclusion,name,headBranch,createdAt,updatedAt,jobs`,{cwd:process.cwd(),timeout:3e4}),n=JSON.parse(o),r=[`Run: ${n.name} [${e.run_id}]`,`Branch: ${n.headBranch} Status: ${n.conclusion||n.status}`,`Started: ${n.createdAt} Finished: ${n.updatedAt||"\u2014"}`,"","Jobs:"];for(let i of n.jobs||[]){let c=i.conclusion==="success"?"\u2713":i.conclusion==="failure"?"\u2717":"\u25CB";r.push(` ${c} ${i.name} (${i.conclusion||i.status})`);for(let l of i.steps||[]){if(l.conclusion==="failure"||l.conclusion==="skipped")continue;let u=l.conclusion==="success"?" \u2713":l.conclusion==="failure"?" \u2717":" \u25CB";r.push(` ${u} ${l.name}`)}}return r.join(`
|
|
253
268
|
`)}catch(o){return`ERROR: ${(o.stderr||o.message||"").toString().split(`
|
|
254
|
-
`)[0]}`}}case"gh_workflow_trigger":{if(!e.workflow)return"ERROR: workflow is required";let{confirm:o}=
|
|
255
|
-
${
|
|
256
|
-
`)[0]}`}}case"k8s_pods":{let o=e.namespace?`-n ${e.namespace}`:"-A",n=e.label?`-l ${e.label}`:"",r=
|
|
257
|
-
`)[0];return c.includes("command not found")?"ERROR: kubectl not found. Install kubectl or provide a server with kubectl.":`ERROR: ${c}`}}case"k8s_logs":{if(!e.pod)return"ERROR: pod is required";let o=e.namespace||"default",n=e.tail||100,r=`logs ${e.pod} -n ${o} --tail=${n}`;e.since&&(r+=` --since=${e.since}`),e.container&&(r+=` -c ${e.container}`);let i=
|
|
269
|
+
`)[0]}`}}case"gh_workflow_trigger":{if(!e.workflow)return"ERROR: workflow is required";let{confirm:o}=Ue(),n=e.branch||await ed()||"main",r=e.inputs?Object.entries(e.inputs).map(([l,u])=>`-f ${l}=${u}`).join(" "):"",i=`gh workflow run ${e.workflow} --ref ${n} ${r}`.trim();if(console.log(`
|
|
270
|
+
${V.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${n}${V.reset}`),!await o(" Trigger?"))return"CANCELLED: User declined to trigger workflow.";try{return await ge(i,{cwd:process.cwd(),timeout:3e4}),`Workflow "${e.workflow}" triggered on branch "${n}". Check status with gh_run_list.`}catch(l){return`ERROR: ${(l.stderr||l.message||"").toString().split(`
|
|
271
|
+
`)[0]}`}}case"k8s_pods":{let o=e.namespace?`-n ${e.namespace}`:"-A",n=e.label?`-l ${e.label}`:"",r=Rs(`get pods ${o} ${n} -o wide`.trim(),e);try{let{stdout:i,stderr:c}=await ge(r,{timeout:3e4,maxBuffer:2097152});return(i||c||"(no pods)").trim()}catch(i){let c=(i.stderr||i.message||"").toString().split(`
|
|
272
|
+
`)[0];return c.includes("command not found")?"ERROR: kubectl not found. Install kubectl or provide a server with kubectl.":`ERROR: ${c}`}}case"k8s_logs":{if(!e.pod)return"ERROR: pod is required";let o=e.namespace||"default",n=e.tail||100,r=`logs ${e.pod} -n ${o} --tail=${n}`;e.since&&(r+=` --since=${e.since}`),e.container&&(r+=` -c ${e.container}`);let i=Rs(r,e);try{let{stdout:c,stderr:l}=await ge(i,{timeout:6e4,maxBuffer:5242880}),u=(c||l||"(no logs)").trim();return u.substring(0,2e4)+(u.length>2e4?`
|
|
258
273
|
...(truncated)`:"")}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
|
|
259
274
|
`)[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(`
|
|
260
|
-
${
|
|
275
|
+
${V.yellow} \u26A0 kubectl exec into pod: ${e.pod} (ns: ${o})${V.reset}`),console.log(`${V.dim} Command: ${e.command}${V.reset}`),!await vt(" Execute in pod?"))return"CANCELLED: User declined.";let r=`exec ${e.pod} -n ${o}`;e.container&&(r+=` -c ${e.container}`),r+=` -- sh -c ${JSON.stringify(e.command)}`;let i=Rs(r,e);try{let{stdout:c,stderr:l}=await ge(i,{timeout:6e4,maxBuffer:2097152});return(c||l||"(no output)").trim()}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
|
|
261
276
|
`)[0]}`}}case"k8s_apply":{if(!e.file)return"ERROR: file is required";let o=!!e.dry_run;if(!o){let i=e.file;if(console.log(`
|
|
262
|
-
${
|
|
277
|
+
${V.yellow} \u26A0 kubectl apply: ${i}${e.namespace?` (ns: ${e.namespace})`:""}${V.reset}`),!await vt(" 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=Rs(n,e);try{let{stdout:i,stderr:c}=await ge(r,{timeout:12e4,maxBuffer:2097152});return(i||c||"(no output)").trim()}catch(i){return`ERROR: ${(i.stderr||i.message||"").toString().split(`
|
|
263
278
|
`)[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(`
|
|
264
|
-
${
|
|
265
|
-
`)[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}=
|
|
266
|
-
|
|
267
|
-
`+i:i;return o(r,u),`Appended to brain document: ${r}.md`}return o(r,i),`${c==="create"?"Created":"Updated"} brain document: ${r}.md`}case"ssh_exec":{if(!e.server)return"ERROR: server is required";if(!e.command)return"ERROR: command is required";let o;try{o=
|
|
268
|
-
|
|
269
|
-
|
|
279
|
+
${V.yellow} \u26A0 ${c}: deployment/${e.deployment} (ns: ${o})${V.reset}`),!await vt(` ${c}?`))return"CANCELLED: User declined."}let r=`rollout ${e.action} deployment/${e.deployment} -n ${o}`,i=Rs(r,e);try{let{stdout:c,stderr:l}=await ge(i,{timeout:12e4,maxBuffer:2097152});return(c||l||"(no output)").trim()}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
|
|
280
|
+
`)[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}=vs(),{name:r,content:i,mode:c}=e;if(c==="create"&&n(r).content)return`ERROR: Document "${r}" already exists. Use mode "update" to overwrite.`;if(c==="append"){let l=n(r),u=l.content?l.content+`
|
|
281
|
+
|
|
282
|
+
`+i:i;return o(r,u),`Appended to brain document: ${r}.md`}return o(r,i),`${c==="create"?"Created":"Updated"} brain document: ${r}.md`}case"ssh_exec":{if(!e.server)return"ERROR: server is required";if(!e.command)return"ERROR: command is required";let o;try{o=wt(e.server)}catch(k){return`ERROR: ${k.message}`}let n=e.command,r=!!e.sudo,i=(e.timeout||30)*1e3,c=my(n);if(c)return/\bsed\s+-n\s+['"]?\d+,\d+p/.test(n)?`BLOCKED: sed -n line-range is blocked (floods context). To read specific lines from a remote file use:
|
|
283
|
+
grep -n "pattern" /path/to/file -A 50
|
|
284
|
+
or to read the whole file:
|
|
285
|
+
cat /path/to/file
|
|
286
|
+
NEVER use sed -n again \u2014 it will always be blocked.`:`BLOCKED: Remote command matches SSH secret-exposure pattern: ${c}
|
|
287
|
+
HINT: Do not read .env, credentials, or private key files via ssh_exec \u2014 secrets would appear in tool output. Reference variable names or file paths instead.`;if(n=n.replace(/(-[BAC])\s*(\d+)/g,(k,R,O)=>{let P=Math.min(Number(O),20);return`${R} ${P}`}),n=n.replace(/(--(?:before|after|context)=)(\d+)/g,(k,R,O)=>R+Math.min(Number(O),20)),/\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 k=o.user?`${o.user}@${o.host}`:o.host;if(console.log(`
|
|
288
|
+
${V.yellow} \u26A0 Remote command on ${k}: ${n}${V.reset}`),!await vt(" Execute on remote server?"))return"CANCELLED: User declined to execute remote command."}let{stdout:u,stderr:d,exitCode:f,error:p}=await tt(o,n,{timeout:i,sudo:r}),h=[u,d].filter(Boolean).join(`
|
|
270
289
|
`).trim();if(f!==0)return`EXIT ${f}
|
|
271
|
-
${
|
|
272
|
-
`).filter(
|
|
273
|
-
`));let
|
|
274
|
-
`);
|
|
275
|
-
|
|
276
|
-
`)
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
${
|
|
280
|
-
${
|
|
281
|
-
`).
|
|
282
|
-
${f
|
|
283
|
-
|
|
290
|
+
${p||h||"(no output)"}`;let m=/\bgrep\b/.test(n),g=h;m&&(g=g.split(`
|
|
291
|
+
`).filter(k=>k!=="--").join(`
|
|
292
|
+
`));let $=m?100:200,y=g.split(`
|
|
293
|
+
`);y.length>$&&(g=`(${y.length-$} earlier lines omitted \u2014 showing last ${$})
|
|
294
|
+
`+y.slice(-$).join(`
|
|
295
|
+
`));let x=4,_=g.split(`
|
|
296
|
+
`),v=[],b=0;for(;b<_.length;){let k=b+1;for(;k<_.length&&_[k]===_[b];)k++;let R=k-b;if(v.push(_[b]),R>x)v.push(`... (${R-1} identical lines omitted)`);else for(let O=1;O<R;O++)v.push(_[b]);b=k}return v.join(`
|
|
297
|
+
`)||"(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=wt(e.server)}catch(i){return`ERROR: ${i.message}`}let n=o.user?`${o.user}@${o.host}`:o.host;if(console.log(`
|
|
298
|
+
${V.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${n}:${e.remote_path}${V.reset}`),!await vt(" Upload to remote server?"))return"CANCELLED: User declined upload.";try{return await ky(o,e.local_path,e.remote_path)}catch(i){return`ERROR: ${i.message}`}}case"ssh_download":{if(!e.server||!e.remote_path||!e.local_path)return"ERROR: server, remote_path, and local_path are required";let o;try{o=wt(e.server)}catch(n){return`ERROR: ${n.message}`}try{return await vy(o,e.remote_path,e.local_path)}catch(n){return`ERROR: ${n.message}`}}case"remote_agent":{let o=require("path").join(process.cwd(),".nex","servers.json"),n=null;try{n=JSON.parse(require("fs").readFileSync(o,"utf-8"))[e.server]||null}catch{}let r=n?`${n.user||"root"}@${n.host}`:e.server,i=n?.key?["-i",n.key]:[],c=e.project_path||n?.home||"~",l=e.model||"",d=["TMPFILE=$(mktemp /tmp/nexcode-XXXXXX.txt)",`echo "${Buffer.from(e.task).toString("base64")}" | base64 -d > "$TMPFILE"`,`cd "${c}" 2>/dev/null || true`,l?`nex-code --prompt-file "$TMPFILE" --auto --model "${l}" 2>&1`:'nex-code --prompt-file "$TMPFILE" --auto 2>&1',"EXIT_CODE=$?",'rm -f "$TMPFILE"',"exit $EXIT_CODE"].join(" && "),{spawnSync:f}=require("child_process"),p=f("ssh",[...i,"-o","StrictHostKeyChecking=no","-o","ConnectTimeout=10",r,`bash -c '${d}'`],{encoding:"utf-8",maxBuffer:10*1024*1024,timeout:3e5});if(p.error)return`ERROR: SSH connection failed: ${p.error.message}`;let h=(p.stdout||"")+(p.stderr||"");return p.status!==0?`Remote nex-code exited with code ${p.status}.
|
|
299
|
+
${h.slice(-2e3)}`:h.slice(-5e3)||"Remote nex-code completed (no output)"}case"service_manage":{if(!e.service)return"ERROR: service is required";if(!e.action)return"ERROR: action is required";let o=["status","start","stop","restart","reload","enable","disable"];if(!o.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${o.join(", ")}`;let n=!e.server||e.server==="local"||e.server==="localhost",r=e.action==="status",i=null;if(!n)try{i=wt(e.server)}catch(l){return`ERROR: ${l.message}`}if(!r){let l=n?"local machine":i.user?`${i.user}@${i.host}`:i.host;if(console.log(`
|
|
300
|
+
${V.yellow} \u26A0 Service: systemctl ${e.action} ${e.service} on ${l}${V.reset}`),!await vt(" 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 ge(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}
|
|
301
|
+
${f}`}}else{let{stdout:l,stderr:u,exitCode:d,error:f}=await tt(i,c,{timeout:15e3,sudo:!0}),p=[l,u].filter(Boolean).join(`
|
|
302
|
+
`).trim();return d!==0?/not found|loaded.*not-found/i.test(p)?`ERROR: Service "${e.service}" not found on ${i.host}. Check: ssh_exec to run "systemctl list-units --type=service"`:`EXIT ${d}
|
|
303
|
+
${f||p||"(no output)"}`:p||`systemctl ${e.action} ${e.service}: OK`}}case"service_logs":{if(!e.service)return"ERROR: service is required";let o=!e.server||e.server==="local"||e.server==="localhost",n=e.lines||50,r=e.since?`--since "${e.since}"`:"",i=e.follow?"-f":"",c=`journalctl -u ${e.service} -n ${n} ${r} ${i} --no-pager`.trim().replace(/\s+/g," ");if(o)try{let{stdout:m,stderr:g}=await ge(c,{timeout:15e3});return(m||g||"(no log output)").trim()}catch(m){return`EXIT ${m.code||1}
|
|
304
|
+
${(m.stderr||m.message||"").toString().trim()}`}let l;try{l=wt(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:u,stderr:d,exitCode:f,error:p}=await tt(l,c,{timeout:2e4}),h=[u,d].filter(Boolean).join(`
|
|
284
305
|
`).trim();return f!==0?`EXIT ${f}
|
|
285
|
-
${
|
|
286
|
-
${(
|
|
306
|
+
${p||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:p,stderr:h}=await ge(r,{timeout:1e4});return(p||h||"(no containers)").trim()}catch(p){return`EXIT ${p.code||1}
|
|
307
|
+
${(p.stderr||p.message||"").toString().trim()}`}let i;try{i=wt(e.server)}catch(p){return`ERROR: ${p.message}`}let{stdout:c,stderr:l,exitCode:u,error:d}=await tt(i,r,{timeout:15e3}),f=[c,l].filter(Boolean).join(`
|
|
287
308
|
`).trim();return u!==0?`EXIT ${u}
|
|
288
|
-
${d||f}`:f||"(no containers)"}case"container_logs":{if(!e.container)return"ERROR: container is required";let o=!e.server||e.server==="local"||e.server==="localhost",n=e.lines||50,r=e.since?`--since "${e.since}"`:"",i=`docker logs --tail ${n} ${r} ${e.container} 2>&1`.trim().replace(/\s+/g," ");if(o)try{let{stdout:h,stderr:
|
|
289
|
-
${(h.stderr||h.message||"").toString().trim()}`}let c;try{c=
|
|
309
|
+
${d||f}`:f||"(no containers)"}case"container_logs":{if(!e.container)return"ERROR: container is required";let o=!e.server||e.server==="local"||e.server==="localhost",n=e.lines||50,r=e.since?`--since "${e.since}"`:"",i=`docker logs --tail ${n} ${r} ${e.container} 2>&1`.trim().replace(/\s+/g," ");if(o)try{let{stdout:h,stderr:m}=await ge(i,{timeout:15e3});return(h||m||"(no log output)").trim()}catch(h){return`EXIT ${h.code||1}
|
|
310
|
+
${(h.stderr||h.message||"").toString().trim()}`}let c;try{c=wt(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:l,stderr:u,exitCode:d,error:f}=await tt(c,i,{timeout:2e4}),p=[l,u].filter(Boolean).join(`
|
|
290
311
|
`).trim();return d!==0?`EXIT ${d}
|
|
291
|
-
${f||
|
|
292
|
-
${
|
|
293
|
-
${(h.stderr||h.message||"").toString().trim()}`}let c;try{c=
|
|
312
|
+
${f||p}`:p||"(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(`
|
|
313
|
+
${V.yellow} \u26A0 docker exec in ${e.container} on ${h}: ${e.command}${V.reset}`),!await vt(" Execute?"))return"CANCELLED: User declined."}let i=`docker exec ${e.container} sh -c ${JSON.stringify(e.command)}`;if(o)try{let{stdout:h,stderr:m}=await ge(i,{timeout:3e4});return(h||m||"(no output)").trim()}catch(h){return`EXIT ${h.code||1}
|
|
314
|
+
${(h.stderr||h.message||"").toString().trim()}`}let c;try{c=wt(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:l,stderr:u,exitCode:d,error:f}=await tt(c,i,{timeout:35e3}),p=[l,u].filter(Boolean).join(`
|
|
294
315
|
`).trim();return d!==0?`EXIT ${d}
|
|
295
|
-
${f||
|
|
296
|
-
${
|
|
297
|
-
${(
|
|
316
|
+
${f||p}`:p||"(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 m=n?"local":e.server;if(console.log(`
|
|
317
|
+
${V.yellow} \u26A0 docker ${e.action} ${e.container} on ${m}${V.reset}`),!await vt(" Execute?"))return"CANCELLED: User declined."}let i=e.action==="remove"?"rm":e.action,c=e.action==="inspect"?`docker inspect ${e.container}`:`docker ${i} ${e.container}`;if(n)try{let{stdout:m,stderr:g}=await ge(c,{timeout:3e4});return(m||g||`docker ${e.action} ${e.container}: OK`).trim()}catch(m){return`EXIT ${m.code||1}
|
|
318
|
+
${(m.stderr||m.message||"").toString().trim()}`}let l;try{l=wt(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:u,stderr:d,exitCode:f,error:p}=await tt(l,c,{timeout:35e3}),h=[u,d].filter(Boolean).join(`
|
|
298
319
|
`).trim();return f!==0?`EXIT ${f}
|
|
299
|
-
${
|
|
300
|
-
${
|
|
301
|
-
${
|
|
320
|
+
${p||h}`:h||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...Sy(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=wt(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(`
|
|
321
|
+
${V.yellow} \u26A0 Deploy [git pull]: ${r}:${e.remote_path}${f}${V.reset}`)}else{let f=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`;console.log(`
|
|
322
|
+
${V.yellow} \u26A0 Deploy [rsync]: ${f} \u2192 ${r}:${e.remote_path}${V.reset}`)}if(e.deploy_script&&console.log(`${V.yellow} Then run: ${e.deploy_script}${V.reset}`),e.health_check&&console.log(`${V.yellow} Health check: ${e.health_check}${V.reset}`),!await vt(" Proceed with deployment?"))return"CANCELLED: User declined."}let i="";if(o==="git"){let d=e.branch?`cd ${e.remote_path} && git fetch origin && git checkout ${e.branch} && git pull origin ${e.branch}`:`cd ${e.remote_path} && git pull`;if(e.dry_run)return`DRY RUN [git]: would run on ${r}:
|
|
302
323
|
${d}${e.deploy_script?`
|
|
303
|
-
${e.deploy_script}`:""}`;let{stdout:f,stderr:
|
|
324
|
+
${e.deploy_script}`:""}`;let{stdout:f,stderr:p,exitCode:h,error:m}=await tt(n,d,{timeout:12e4});if(i=[f,p].filter(Boolean).join(`
|
|
304
325
|
`).trim(),h!==0)return`ERROR (git pull, exit ${h}):
|
|
305
|
-
${
|
|
306
|
-
${i||"(nothing to sync)"}`}let c="";if(e.deploy_script){let{stdout:d,stderr:f,exitCode:
|
|
307
|
-
`).trim();if(
|
|
326
|
+
${m||i}`}else{let d=n.key?`-e "ssh -i ${n.key.replace(/^~/,require("os").homedir())}${n.port&&Number(n.port)!==22?` -p ${n.port}`:""}"`:n.port&&Number(n.port)!==22?`-e "ssh -p ${n.port}"`:"",f=(e.exclude||[]).map(g=>`--exclude="${g}"`).join(" "),p=e.dry_run?"--dry-run":"",h=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`,m=`rsync -avz --delete ${p} ${f} ${d} ${h} ${r}:${e.remote_path}`.trim().replace(/\s+/g," ");try{let{stdout:g,stderr:$}=await ge(m,{timeout:12e4});i=(g||$||"").trim()}catch(g){return`ERROR (rsync): ${(g.stderr||g.message||"").toString().trim()}`}if(e.dry_run)return`DRY RUN [rsync]:
|
|
327
|
+
${i||"(nothing to sync)"}`}let c="";if(e.deploy_script){let{stdout:d,stderr:f,exitCode:p,error:h}=await tt(n,e.deploy_script,{timeout:12e4}),m=[d,f].filter(Boolean).join(`
|
|
328
|
+
`).trim();if(p!==0)return`${o==="git"?"git pull":"rsync"} OK
|
|
308
329
|
|
|
309
|
-
ERROR (deploy_script, exit ${
|
|
310
|
-
${h||
|
|
330
|
+
ERROR (deploy_script, exit ${p}):
|
|
331
|
+
${h||m}`;c=`
|
|
311
332
|
|
|
312
333
|
Deploy script output:
|
|
313
|
-
${
|
|
334
|
+
${m||"(no output)"}`}let l="";if(e.health_check){let d=e.health_check.trim();if(/^https?:\/\//.test(d))try{let p=require("node-fetch"),h=await Promise.race([p(d),new Promise((m,g)=>setTimeout(()=>g(new Error("timeout")),15e3))]);if(h.ok)l=`
|
|
314
335
|
|
|
315
336
|
Health check: \u2713 ${d} \u2192 ${h.status}`;else return l=`
|
|
316
337
|
|
|
317
|
-
Health check FAILED: ${d} \u2192 HTTP ${h.status}`,(o==="git"?"git pull OK":"rsync OK")+i+c+l}catch(
|
|
338
|
+
Health check FAILED: ${d} \u2192 HTTP ${h.status}`,(o==="git"?"git pull OK":"rsync OK")+i+c+l}catch(p){return l=`
|
|
318
339
|
|
|
319
|
-
Health check FAILED: ${d} \u2192 ${
|
|
320
|
-
`).trim();if(
|
|
340
|
+
Health check FAILED: ${d} \u2192 ${p.message}`,(o==="git"?"git pull OK":"rsync OK")+i+c+l}else{let{stdout:p,stderr:h,exitCode:m}=await tt(n,d,{timeout:15e3}),g=[p,h].filter(Boolean).join(`
|
|
341
|
+
`).trim();if(m!==0)return l=`
|
|
321
342
|
|
|
322
|
-
Health check FAILED (exit ${
|
|
343
|
+
Health check FAILED (exit ${m}): ${g}`,(o==="git"?"git pull OK":"rsync OK")+i+c+l;l=`
|
|
323
344
|
|
|
324
345
|
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}
|
|
325
|
-
${i}${c}${l}`.trim()}case"deployment_status":{let o=
|
|
346
|
+
${i}${c}${l}`.trim()}case"deployment_status":{let o=Ey(),n=e.config?[e.config]:Object.keys(o);if(n.length===0)return"No deploy configs found. Create .nex/deploy.json to configure deployments.";let r=[];for(let i of n){let c=o[i];if(!c){r.push(`${i}: NOT FOUND`);continue}try{let l=wt(c.server||i),d=(await tt(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 tt(l,`systemctl is-active ${h[1]}`,{timeout:1e4})).stdout.trim()}catch{f="inactive"}}let p="N/A";if(c.health_check){let h=c.health_check.trim();if(/^https?:\/\//.test(h))try{let m=require("node-fetch"),g=await Promise.race([m(h),new Promise(($,y)=>setTimeout(()=>y(new Error("timeout")),1e4))]);p=g.ok?"healthy":`HTTP ${g.status}`}catch(m){p=`unhealthy: ${m.message.substring(0,50)}`}else try{p=(await tt(l,h,{timeout:1e4})).exitCode===0?"healthy":"unhealthy"}catch{p="unhealthy"}}r.push(`${i}: server=${d?"reachable":"unreachable"} service=${f} health=${p}`)}catch(l){r.push(`${i}: ERROR \u2014 ${l.message}`)}}return`Deployment Status:
|
|
326
347
|
${r.join(`
|
|
327
|
-
`)}`}case"frontend_recon":{let o=process.cwd(),n=(e.type||"").toLowerCase(),r=[],i=async(
|
|
328
|
-
`),
|
|
329
|
-
`);return
|
|
330
|
-
... (${
|
|
331
|
-
`).filter(Boolean)}catch{return[]}},d=async(
|
|
348
|
+
`)}`}case"frontend_recon":{let o=process.cwd(),n=(e.type||"").toLowerCase(),r=[],i=async(v,b=120)=>{try{let k=he.isAbsolute(v)?v:he.join(o,v),O=(await Te.readFile(k,"utf8")).split(`
|
|
349
|
+
`),P=O.slice(0,b).join(`
|
|
350
|
+
`);return O.length>b?P+`
|
|
351
|
+
... (${O.length-b} more lines \u2014 use read_file for full content)`:P}catch{return null}},l=["node_modules",".git","dist","build","vendor",".next","__pycache__","venv",".venv"].map(v=>`-not -path "*/${v}/*"`).join(" "),u=async v=>{try{let{stdout:b}=await ge(`find "${o}" -type f -name "${v}" ${l} 2>/dev/null | head -10`,{timeout:8e3});return b.trim().split(`
|
|
352
|
+
`).filter(Boolean)}catch{return[]}},d=async(v,b)=>{try{let{stdout:k}=await ge(`grep -rl "${v}" "${o}" --include="${b}" --exclude-dir=node_modules --exclude-dir=.git --exclude-dir=dist --exclude-dir=build 2>/dev/null | head -5`,{timeout:8e3});return k.trim().split(`
|
|
332
353
|
`).filter(Boolean)}catch{return[]}};r.push(`## STEP 1: Design Tokens
|
|
333
|
-
`);let f=[...await u("tailwind.config.js"),...await u("tailwind.config.ts"),...await u("tailwind.config.mjs")];if(f.length>0){let
|
|
354
|
+
`);let f=[...await u("tailwind.config.js"),...await u("tailwind.config.ts"),...await u("tailwind.config.mjs")];if(f.length>0){let v=await i(f[0],80);v&&r.push(`### Tailwind config (${he.relative(o,f[0])})
|
|
334
355
|
\`\`\`js
|
|
335
|
-
${
|
|
336
|
-
\`\`\``)}else r.push("(no tailwind.config found)");let
|
|
356
|
+
${v}
|
|
357
|
+
\`\`\``)}else r.push("(no tailwind.config found)");let p=["variables.css","_variables.scss","tokens.css","base.css","global.css","main.css","index.css","app.css","style.css","styles.css"],h=!1;for(let v of p){let b=await u(v);for(let k of b){let R=await i(k,100);if(R&&R.includes(":root")){r.push(`### CSS Variables (${he.relative(o,k)})
|
|
337
358
|
\`\`\`css
|
|
338
|
-
${
|
|
339
|
-
\`\`\``),h=!0;break}}if(h)break}if(!h){let
|
|
359
|
+
${R}
|
|
360
|
+
\`\`\``),h=!0;break}}if(h)break}if(!h){let v=await d(":root","*.css");if(v.length>0){let b=await i(v[0],100);b&&r.push(`### CSS Variables (${he.relative(o,v[0])})
|
|
340
361
|
\`\`\`css
|
|
341
|
-
${
|
|
362
|
+
${b}
|
|
342
363
|
\`\`\``),h=!0}}h||r.push("(no CSS custom properties / :root found)"),r.push(`
|
|
343
364
|
## STEP 2: Main Layout / Index Page
|
|
344
|
-
`);let
|
|
365
|
+
`);let m=["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 v of m){let b=await u(v);if(b.length>0){let k=await i(b[0],150);if(k){r.push(`### Main layout: ${he.relative(o,b[0])}
|
|
345
366
|
\`\`\`html
|
|
346
|
-
${
|
|
367
|
+
${k}
|
|
347
368
|
\`\`\``),g=!0;break}}}g||r.push("(no main layout/index file found \u2014 try read_file on your root template manually)"),r.push(`
|
|
348
369
|
## STEP 3: Reference Component (same type)
|
|
349
|
-
`);let
|
|
350
|
-
`).filter(Boolean)}catch{
|
|
370
|
+
`);let $=[];if(n){for(let v of["*.html","*.vue","*.jsx","*.tsx"])if($=await d(n,v),$.length>0)break}if($.length===0)try{let{stdout:v}=await ge(`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});$=v.trim().split(`
|
|
371
|
+
`).filter(Boolean)}catch{$=[]}if($.length>0){let v=$[0],b=await i(v,150);b?r.push(`### Reference: ${he.relative(o,v)}
|
|
351
372
|
\`\`\`html
|
|
352
|
-
${
|
|
373
|
+
${b}
|
|
353
374
|
\`\`\``):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(`
|
|
354
375
|
## STEP 4: Framework Stack
|
|
355
|
-
`);let
|
|
376
|
+
`);let y=[],x=await i(he.join(o,"package.json"),999);if(x){if((x.includes('"react"')||x.includes("'react'"))&&y.push("React"),x.includes('"vue"')||x.includes("'vue'")){let b=x.match(/"vue":\s*"[\^~]?(\d+)/);y.push(b?`Vue.js v${b[1]}`:"Vue.js")}let v=x.match(/"alpinejs":\s*"[\^~]?(\d+)/);v&&y.push(`Alpine.js v${v[1]} (\u26A0 v2 vs v3 API differs!)`),(x.includes('"htmx')||x.includes("'htmx"))&&y.push("HTMX"),x.includes('"tailwindcss"')&&y.push("Tailwind CSS"),x.includes('"bootstrap"')&&y.push("Bootstrap")}if((await ct(he.join(o,"manage.py"))||(await i(he.join(o,"requirements.txt"),50)||"").includes("Django"))&&y.push("Django (server-rendered templates)"),!y.some(v=>v.includes("Alpine"))){let v=await d("alpinejs","*.html");if(v.length>0){let k=(await i(v[0],30)||"").match(/alpinejs[@/]v?(\d)/);y.push(k?`Alpine.js v${k[1]} (via CDN \u2014 \u26A0 v2 vs v3 API differs!)`:"Alpine.js (via CDN \u2014 check version!)")}}return y.some(v=>v.includes("HTMX"))||(await d("htmx","*.html")).length>0&&y.push("HTMX (via CDN)"),y.length>0?(r.push(y.map(v=>`- ${v}`).join(`
|
|
356
377
|
`)),r.push(`
|
|
357
378
|
\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(`
|
|
358
379
|
---
|
|
359
380
|
\u2705 Design recon complete. Now build consistently with the patterns above.`),r.join(`
|
|
360
|
-
`)}case"sysadmin":{if(!e.action)return"ERROR: action is required";let o=!e.server||e.server==="local"||e.server==="localhost",n;if(!o)try{n=
|
|
361
|
-
`).trim();return{out:h&&
|
|
362
|
-
`+
|
|
381
|
+
`)}case"sysadmin":{if(!e.action)return"ERROR: action is required";let o=!e.server||e.server==="local"||e.server==="localhost",n;if(!o)try{n=wt(e.server)}catch(l){return`ERROR: ${l.message}`}let r=async(l,u=3e4)=>{if(o)try{let{stdout:d,stderr:f}=await ge(l,{timeout:u});return{out:(d||f||"").trim(),exitCode:0}}catch(d){return{out:(d.stderr||d.message||"").toString().trim(),exitCode:d.code||1}}else{let{stdout:d,stderr:f,exitCode:p,error:h}=await tt(n,l,{timeout:u}),m=[d,f].filter(Boolean).join(`
|
|
382
|
+
`).trim();return{out:h&&p!==0?(h+`
|
|
383
|
+
`+m).trim():m,exitCode:p}}};if(!(["audit","disk_usage","process_list","network_status","ssl_check","log_tail","find_large","journalctl"].includes(e.action)||e.action==="package"&&e.package_action==="list"||e.action==="user_manage"&&["list","info"].includes(e.user_action)||e.action==="firewall"&&e.firewall_action==="status"||e.action==="cron"&&e.cron_action==="list"||e.action==="service"&&["status","list_failed"].includes(e.service_action))&&!s.autoConfirm){let l=o?"local":e.server;if(!await vt(`sysadmin [${e.action}] on ${l} \u2014 proceed?`))return"Cancelled."}switch(e.action){case"audit":{let l=["echo '=== OS / KERNEL ==='","cat /etc/os-release 2>/dev/null | grep -E '^(NAME|VERSION)=' || uname -a","echo '=== UPTIME / LOAD ==='","uptime","echo '=== MEMORY / SWAP ==='","free -h","echo '=== DISK ==='","df -h --output=target,size,used,avail,pcent 2>/dev/null || df -h","echo '=== TOP 10 PROCESSES (CPU) ==='","ps aux --sort=-%cpu | head -11","echo '=== FAILED SYSTEMD UNITS ==='","systemctl list-units --state=failed --no-legend 2>/dev/null || echo '(systemctl not available)'","echo '=== RECENT ERRORS (journalctl) ==='","journalctl -p err --no-pager -n 15 2>/dev/null || echo '(journalctl not available)'","echo '=== LISTENING PORTS ==='","ss -tlnp 2>/dev/null || netstat -tlnp 2>/dev/null || echo '(ss/netstat not available)'"].join(" && "),{out:u,exitCode:d}=await r(l,45e3);return u||`EXIT ${d}
|
|
363
384
|
(no output)`}case"disk_usage":{let l=e.path||"/",u=`df -h ${l}; echo '--- Top subdirs ---'; du -d1 -x -h ${l} 2>/dev/null | sort -rh | head -20`,{out:d,exitCode:f}=await r(u,3e4);return f!==0?`EXIT ${f}
|
|
364
|
-
${d}`:d}case"process_list":{let l=e.sort_by==="mem"?"4":"3",u=(e.limit||20)+1,d=`ps aux --sort=-${e.sort_by==="mem"?"%mem":"%cpu"} 2>/dev/null | head -${u} || ps aux | awk 'NR==1{print; next} {print | "sort -k${l} -rn"}' | head -${u}`,{out:f,exitCode:
|
|
385
|
+
${d}`:d}case"process_list":{let l=e.sort_by==="mem"?"4":"3",u=(e.limit||20)+1,d=`ps aux --sort=-${e.sort_by==="mem"?"%mem":"%cpu"} 2>/dev/null | head -${u} || ps aux | awk 'NR==1{print; next} {print | "sort -k${l} -rn"}' | head -${u}`,{out:f,exitCode:p}=await r(d,15e3);return p!==0?`EXIT ${p}
|
|
365
386
|
${f}`:f}case"network_status":{let l="ss -tlnp 2>/dev/null || netstat -tlnp 2>/dev/null; echo '--- Active connections ---'; ss -tnp 2>/dev/null | head -30",{out:u,exitCode:d}=await r(l,15e3);return d!==0?`EXIT ${d}
|
|
366
|
-
${u}`:u}case"package":{if(!e.package_action)return"ERROR: package_action is required for action=package";let{out:l}=await r("which dnf 2>/dev/null && echo dnf || (which apt-get 2>/dev/null && echo apt) || echo unknown",1e4),u=l.includes("dnf")?"dnf":l.includes("apt")?"apt":null;if(!u)return"ERROR: No supported package manager found (dnf/apt)";let d=(e.packages||[]).join(" "),f;switch(e.package_action){case"list":f=u==="dnf"?"dnf list installed 2>/dev/null | head -60":"dpkg -l | head -60";break;case"check":{let
|
|
367
|
-
${
|
|
387
|
+
${u}`:u}case"package":{if(!e.package_action)return"ERROR: package_action is required for action=package";let{out:l}=await r("which dnf 2>/dev/null && echo dnf || (which apt-get 2>/dev/null && echo apt) || echo unknown",1e4),u=l.includes("dnf")?"dnf":l.includes("apt")?"apt":null;if(!u)return"ERROR: No supported package manager found (dnf/apt)";let d=(e.packages||[]).join(" "),f;switch(e.package_action){case"list":f=u==="dnf"?"dnf list installed 2>/dev/null | head -60":"dpkg -l | head -60";break;case"check":{let m=u==="dnf"?'dnf check-update 2>/dev/null; EC=$?; [ $EC -eq 100 ] && echo "EXIT_STATUS: updates_available" || ([ $EC -eq 0 ] && echo "EXIT_STATUS: up_to_date" || echo "EXIT_STATUS: error $EC")':"apt-get -s upgrade 2>/dev/null | tail -5",{out:g}=await r(m,6e4);return g||"(no output from package check)"}case"install":if(!d)return"ERROR: packages required for install";f=u==="dnf"?`dnf install -y ${d}`:`apt-get install -y ${d}`;break;case"remove":if(!d)return"ERROR: packages required for remove";f=u==="dnf"?`dnf remove -y ${d}`:`apt-get remove -y ${d}`;break;case"update":if(!d)return"ERROR: packages required for update (use upgrade for full system upgrade)";f=u==="dnf"?`dnf update -y ${d}`:`apt-get install -y --only-upgrade ${d}`;break;case"upgrade":f=u==="dnf"?"dnf upgrade -y":"DEBIAN_FRONTEND=noninteractive apt-get upgrade -y";break;default:return`ERROR: Unknown package_action: ${e.package_action}`}let{out:p,exitCode:h}=await r(f,12e4);return h!==0?`EXIT ${h}
|
|
388
|
+
${p}`:p||`${e.package_action} OK`}case"user_manage":{if(!e.user_action)return"ERROR: user_action is required for action=user_manage";switch(e.user_action){case"list":{let l=`awk -F: '$3 >= 1000 && $1 != "nobody" {print $1, "uid="$3, "gid="$4, "shell="$7}' /etc/passwd`,{out:u,exitCode:d}=await r(l,1e4);return d!==0?`EXIT ${d}
|
|
368
389
|
${u}`:u||"(no regular users)"}case"info":{if(!e.user)return"ERROR: user is required for user_action=info";let l=`id ${e.user} && echo '--- Groups ---' && groups ${e.user} && echo '--- Last login ---' && lastlog -u ${e.user} 2>/dev/null`,{out:u,exitCode:d}=await r(l,1e4);return d!==0?`EXIT ${d}
|
|
369
|
-
${u}`:u}case"create":{if(!e.user)return"ERROR: user is required for user_action=create";let u=`useradd -m ${(e.groups||[]).map(
|
|
390
|
+
${u}`:u}case"create":{if(!e.user)return"ERROR: user is required for user_action=create";let u=`useradd -m ${(e.groups||[]).map(p=>`-G ${p}`).join(" ")} ${e.user} && echo "User ${e.user} created"`,{out:d,exitCode:f}=await r(u,15e3);return f!==0?`EXIT ${f}
|
|
370
391
|
${d}`:d}case"delete":{if(!e.user)return"ERROR: user is required for user_action=delete";let l=`userdel -r ${e.user} && echo "User ${e.user} deleted"`,{out:u,exitCode:d}=await r(l,15e3);return d!==0?`EXIT ${d}
|
|
371
392
|
${u}`:u}case"add_ssh_key":{if(!e.user)return"ERROR: user is required for user_action=add_ssh_key";if(!e.ssh_key)return"ERROR: ssh_key is required for user_action=add_ssh_key";let l=e.ssh_key.replace(/'/g,"'\\''"),u=`mkdir -p /home/${e.user}/.ssh && chmod 700 /home/${e.user}/.ssh && echo '${l}' >> /home/${e.user}/.ssh/authorized_keys && chmod 600 /home/${e.user}/.ssh/authorized_keys && chown -R ${e.user}:${e.user} /home/${e.user}/.ssh && echo "SSH key added for ${e.user}"`,{out:d,exitCode:f}=await r(u,15e3);return f!==0?`EXIT ${f}
|
|
372
|
-
${d}`:d}default:return`ERROR: Unknown user_action: ${e.user_action}`}}case"firewall":{if(!e.firewall_action)return"ERROR: firewall_action is required for action=firewall";let{out:l}=await r("which firewall-cmd 2>/dev/null && echo firewalld || (which ufw 2>/dev/null && echo ufw) || echo iptables",1e4),u=l.includes("firewalld")?"firewalld":l.includes("ufw")?"ufw":"iptables",d;switch(e.firewall_action){case"status":d=u==="firewalld"?"firewall-cmd --state && firewall-cmd --list-all":u==="ufw"?"ufw status verbose":"iptables -L -n --line-numbers | head -60";break;case"allow":if(!e.port)return'ERROR: port is required for firewall allow (e.g. "80/tcp")';d=u==="firewalld"?`firewall-cmd --permanent --add-port=${e.port} && firewall-cmd --reload`:u==="ufw"?`ufw allow ${e.port}`:`iptables -A INPUT -p ${e.port.includes("/")?e.port.split("/")[1]:"tcp"} --dport ${e.port.split("/")[0]} -j ACCEPT`;break;case"deny":if(!e.port)return"ERROR: port is required for firewall deny";d=u==="firewalld"?`firewall-cmd --permanent --remove-port=${e.port} && firewall-cmd --reload`:u==="ufw"?`ufw deny ${e.port}`:`iptables -A INPUT -p ${e.port.includes("/")?e.port.split("/")[1]:"tcp"} --dport ${e.port.split("/")[0]} -j DROP`;break;case"remove":if(!e.port)return"ERROR: port is required for firewall remove";d=u==="firewalld"?`firewall-cmd --permanent --remove-port=${e.port} && firewall-cmd --reload`:u==="ufw"?`ufw delete allow ${e.port}`:`iptables -D INPUT -p ${e.port.includes("/")?e.port.split("/")[1]:"tcp"} --dport ${e.port.split("/")[0]} -j ACCEPT 2>/dev/null || true`;break;case"reload":d=u==="firewalld"?"firewall-cmd --reload":u==="ufw"?"ufw reload":'iptables-restore < /etc/iptables/rules.v4 2>/dev/null || echo "iptables: manual reload not available"';break;default:return`ERROR: Unknown firewall_action: ${e.firewall_action}`}let{out:f,exitCode:
|
|
373
|
-
${f}`:f||`firewall ${e.firewall_action} OK`}case"cron":{if(!e.cron_action)return"ERROR: cron_action is required for action=cron";let l=e.user?`-u ${e.user}`:"";switch(e.cron_action){case"list":{let u=`crontab ${l} -l 2>/dev/null || echo '(no crontab for ${e.user||"current user"})'`,{out:d}=await r(u,1e4);return d||"(empty crontab)"}case"add":{if(!e.schedule)return"ERROR: schedule is required for cron add";if(!e.command)return"ERROR: command is required for cron add";let u=`${e.schedule} ${e.command}`,d=`(crontab ${l} -l 2>/dev/null; echo "${u}") | crontab ${l} - && echo "Cron entry added: ${u}"`,{out:f,exitCode:
|
|
374
|
-
${f}`:f}case"remove":{if(!e.command)return"ERROR: command (substring to match) is required for cron remove";let u=e.command.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),d=`crontab ${l} -l 2>/dev/null | grep -v "${u}" | crontab ${l} - && echo "Matching cron entries removed"`,{out:f,exitCode:
|
|
393
|
+
${d}`:d}default:return`ERROR: Unknown user_action: ${e.user_action}`}}case"firewall":{if(!e.firewall_action)return"ERROR: firewall_action is required for action=firewall";let{out:l}=await r("which firewall-cmd 2>/dev/null && echo firewalld || (which ufw 2>/dev/null && echo ufw) || echo iptables",1e4),u=l.includes("firewalld")?"firewalld":l.includes("ufw")?"ufw":"iptables",d;switch(e.firewall_action){case"status":d=u==="firewalld"?"firewall-cmd --state && firewall-cmd --list-all":u==="ufw"?"ufw status verbose":"iptables -L -n --line-numbers | head -60";break;case"allow":if(!e.port)return'ERROR: port is required for firewall allow (e.g. "80/tcp")';d=u==="firewalld"?`firewall-cmd --permanent --add-port=${e.port} && firewall-cmd --reload`:u==="ufw"?`ufw allow ${e.port}`:`iptables -A INPUT -p ${e.port.includes("/")?e.port.split("/")[1]:"tcp"} --dport ${e.port.split("/")[0]} -j ACCEPT`;break;case"deny":if(!e.port)return"ERROR: port is required for firewall deny";d=u==="firewalld"?`firewall-cmd --permanent --remove-port=${e.port} && firewall-cmd --reload`:u==="ufw"?`ufw deny ${e.port}`:`iptables -A INPUT -p ${e.port.includes("/")?e.port.split("/")[1]:"tcp"} --dport ${e.port.split("/")[0]} -j DROP`;break;case"remove":if(!e.port)return"ERROR: port is required for firewall remove";d=u==="firewalld"?`firewall-cmd --permanent --remove-port=${e.port} && firewall-cmd --reload`:u==="ufw"?`ufw delete allow ${e.port}`:`iptables -D INPUT -p ${e.port.includes("/")?e.port.split("/")[1]:"tcp"} --dport ${e.port.split("/")[0]} -j ACCEPT 2>/dev/null || true`;break;case"reload":d=u==="firewalld"?"firewall-cmd --reload":u==="ufw"?"ufw reload":'iptables-restore < /etc/iptables/rules.v4 2>/dev/null || echo "iptables: manual reload not available"';break;default:return`ERROR: Unknown firewall_action: ${e.firewall_action}`}let{out:f,exitCode:p}=await r(d,3e4);return p!==0?`EXIT ${p}
|
|
394
|
+
${f}`:f||`firewall ${e.firewall_action} OK`}case"cron":{if(!e.cron_action)return"ERROR: cron_action is required for action=cron";let l=e.user?`-u ${e.user}`:"";switch(e.cron_action){case"list":{let u=`crontab ${l} -l 2>/dev/null || echo '(no crontab for ${e.user||"current user"})'`,{out:d}=await r(u,1e4);return d||"(empty crontab)"}case"add":{if(!e.schedule)return"ERROR: schedule is required for cron add";if(!e.command)return"ERROR: command is required for cron add";let u=`${e.schedule} ${e.command}`,d=`(crontab ${l} -l 2>/dev/null; echo "${u}") | crontab ${l} - && echo "Cron entry added: ${u}"`,{out:f,exitCode:p}=await r(d,15e3);return p!==0?`EXIT ${p}
|
|
395
|
+
${f}`:f}case"remove":{if(!e.command)return"ERROR: command (substring to match) is required for cron remove";let u=e.command.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),d=`crontab ${l} -l 2>/dev/null | grep -v "${u}" | crontab ${l} - && echo "Matching cron entries removed"`,{out:f,exitCode:p}=await r(d,15e3);return p!==0?`EXIT ${p}
|
|
375
396
|
${f}`:f}default:return`ERROR: Unknown cron_action: ${e.cron_action}`}}case"ssl_check":{if(!e.domain&&!e.cert_path)return"ERROR: domain or cert_path is required for ssl_check";let l;e.cert_path?l=`
|
|
376
397
|
CERT="${e.cert_path}"
|
|
377
398
|
openssl x509 -in "$CERT" -noout -subject -issuer -startdate -enddate -ext subjectAltName 2>&1 && EXPIRY=$(openssl x509 -in "$CERT" -noout -enddate 2>/dev/null | cut -d= -f2) && DAYS=$(( ( $(date -d "$EXPIRY" +%s 2>/dev/null || date -j -f "%b %d %T %Y %Z" "$EXPIRY" +%s 2>/dev/null) - $(date +%s) ) / 86400 )) && echo "Days until expiry: $DAYS"
|
|
@@ -397,13 +418,13 @@ if [ -n "$EXPIRY" ]; then
|
|
|
397
418
|
fi
|
|
398
419
|
`.trim();let{out:u,exitCode:d}=await r(l,25e3),f=/notAfter=|Days until expiry:/i.test(u);return d!==0&&!f?`EXIT ${d}
|
|
399
420
|
${u}`:u||"(no cert info returned)"}case"log_tail":{if(!e.path)return"ERROR: path is required for log_tail";let u=`tail -n ${e.lines||100} ${e.path} 2>&1`,{out:d,exitCode:f}=await r(u,15e3);return f!==0?`EXIT ${f}
|
|
400
|
-
${d}`:d||"(empty log)"}case"find_large":{let l=e.path||"/",u=e.limit||20,d=e.min_size||"100M",f=`find ${l} -xdev -type f -size +${d} 2>/dev/null | xargs du -sh 2>/dev/null | sort -rh | head -${u}`,{out:
|
|
401
|
-
${
|
|
421
|
+
${d}`:d||"(empty log)"}case"find_large":{let l=e.path||"/",u=e.limit||20,d=e.min_size||"100M",f=`find ${l} -xdev -type f -size +${d} 2>/dev/null | xargs du -sh 2>/dev/null | sort -rh | head -${u}`,{out:p,exitCode:h}=await r(f,6e4);return h!==0?`EXIT ${h}
|
|
422
|
+
${p}`:p||`(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||e.service_action==="status"&&f===3?d||`service ${e.service_action} OK`:`EXIT ${f}
|
|
402
423
|
${d}`}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}
|
|
403
424
|
${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}
|
|
404
|
-
${d}`:d||"(no log entries)"}default:return`ERROR: Unknown sysadmin action: ${e.action}`}}default:{let{executePluginTool:o}=
|
|
405
|
-
`)}function
|
|
406
|
-
`),d=r.map(
|
|
425
|
+
${d}`:d||"(no log entries)"}default:return`ERROR: Unknown sysadmin action: ${e.action}`}}default:{let{executePluginTool:o}=xo(),n=await o(t,e,s);return n!==null?n:`ERROR: Unknown tool: ${t}`}}}async function Iy(t,e,s={}){let{emit:o}=xo(),{logToolExecution:n}=Li(),r=Date.now(),i=s.silent?null:wy(t,e);if(!i){let l=await od(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 yy(i);c.start();try{let l=await od(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}}ad.exports={TOOL_DEFINITIONS:Py,executeTool:Iy,resolvePath:nt,autoFixPath:Wo,autoFixEdit:id,enrichBashError:rd,cancelPendingAskUser:Oy,setAskUserHandler:Ny,fileExists:ct}});var Bi=G((tk,cd)=>{var{loadServerProfiles:Bo}=qn(),Wi={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 Ly(){let t=Bo();if(Object.keys(t).length===0)return null;let s=["## Remote Servers (.nex/servers.json)"];s.push(""),s.push("Available server profiles (use with ssh_exec, ssh_upload, ssh_download, service_manage, service_logs, container_list, container_logs, container_exec, container_manage, deploy):");for(let[n,r]of Object.entries(t)){let i=r.user?`${r.user}@${r.host}`:r.host,c=r.port&&Number(r.port)!==22?`:${r.port}`:"",l=r.os?` \u2014 OS: ${r.os}`:"",u=r.sudo?", sudo available":"";s.push(`- **${n}**: ${i}${c}${l}${u}`)}let o=new Set;for(let n of Object.values(t))n.os&&Wi[n.os]&&o.add(n.os);if(o.size>0){s.push("");for(let n of o){let r={almalinux9:"AlmaLinux 9",almalinux8:"AlmaLinux 8",ubuntu:"Ubuntu",debian:"Debian",macos:"macOS"}[n]||n;s.push(`### ${r} Notes`);for(let i of Wi[n])s.push(`- ${i}`)}}return s.join(`
|
|
426
|
+
`)}function jy(t){let e=Bo();return Object.values(e).some(s=>s.os&&s.os.startsWith(t))}function Dy(){return Object.keys(Bo())}function qy(){let t=require("fs"),s=require("path").join(process.cwd(),"NEX.md"),o="";try{o=t.readFileSync(s,"utf-8")}catch{}let n=Bo(),r=Object.keys(n);if(r.length===0)return null;let i=["server","deploy","remote","ssh","service","systemctl","production","linux","almalinux","ubuntu","debian"],c=o.toLowerCase();if(!i.some(p=>c.includes(p)))return null;let u=r.map(p=>{let h=n[p],m=h.user?`${h.user}@${h.host}`:h.host,g=h.port&&Number(h.port)!==22?`:${h.port}`:"";return` - **${p}**: ${m}${g}${h.os?` (${h.os})`:""}`}).join(`
|
|
427
|
+
`),d=r.map(p=>n[p].log_path).filter(Boolean),f=d.length>0?`
|
|
407
428
|
- Server log paths: ${d.join(", ")}`:"";return`# Deployment Context (Auto-detected)
|
|
408
429
|
|
|
409
430
|
This project is deployed on a **remote server**. The application runs as a service there \u2014 NOT locally.
|
|
@@ -420,38 +441,50 @@ ${u}
|
|
|
420
441
|
- \u274C Do NOT \`read_file\` on paths like \`logs/\` \u2014 these files do not exist locally
|
|
421
442
|
- \u274C Do NOT \`list_directory\` on server paths \u2014 the local project is the source, not the running instance
|
|
422
443
|
|
|
423
|
-
**When in doubt:** If a path contains \`logs/\`, \`/var/log/\`, or \`/home/<user>/\` \u2014 it is on the server. SSH there.`}
|
|
424
|
-
`).map(s=>s.trim()).filter(s=>s&&!s.startsWith("#")&&!s.startsWith("!")).map(s=>s.replace(/\/$/,""))}catch{return[]}}function
|
|
425
|
-
`)}var
|
|
444
|
+
**When in doubt:** If a path contains \`logs/\`, \`/var/log/\`, or \`/home/<user>/\` \u2014 it is on the server. SSH there.`}cd.exports={getServerContext:Ly,getDeploymentContextBlock:qy,hasServerOS:jy,getProfileNames:Dy,OS_HINTS:Wi}});var Ko=G((nk,dd)=>{var St=require("fs").promises,ld=require("fs"),Ke=require("path"),Ho=require("util").promisify(require("child_process").exec),{C:Un}=ve(),{getMergeConflicts:ud}=Vt(),{getServerContext:Fy}=Bi(),Uy=new Set(["node_modules",".git",".svn","dist","build","coverage",".nyc_output","__pycache__",".DS_Store",".next",".nuxt",".turbo",".cache","vendor","tmp","temp"]);function Wy(t){try{return ld.readFileSync(t,"utf-8").split(`
|
|
445
|
+
`).map(s=>s.trim()).filter(s=>s&&!s.startsWith("#")&&!s.startsWith("!")).map(s=>s.replace(/\/$/,""))}catch{return[]}}function By(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 Hy(t,{maxDepth:e=3,maxFiles:s=200,giPatterns:o=[]}={}){let n=Ke.join(t,".gitignore"),r=[...o,...Wy(n)],i=0,c=[Ke.basename(t)+"/"];function l(u,d,f){if(f>e||i>=s)return;let p;try{p=ld.readdirSync(u,{withFileTypes:!0})}catch{return}p.sort((m,g)=>m.isDirectory()!==g.isDirectory()?m.isDirectory()?-1:1:m.name.localeCompare(g.name));let h=p.filter(m=>!(Uy.has(m.name)||m.name.startsWith(".")&&m.name!==".env.example"||By(m.name,r)));for(let m=0;m<h.length;m++){if(i>=s){c.push(`${d}\u2514\u2500\u2500 \u2026 (truncated)`);break}let g=h[m],$=m===h.length-1,y=$?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",x=d+($?" ":"\u2502 "),_=g.isDirectory()?g.name+"/":g.name;c.push(`${d}${y}${_}`),i++,g.isDirectory()&&l(Ke.join(u,g.name),x,f+1)}}return l(t,"",1),c.join(`
|
|
446
|
+
`)}var Hi=new Map,Wn=new Map,Go=null,Gy=3e4;async function Zt(t){try{return await t()}catch{return null}}async function Ky(){if(!Go||Date.now()>Go)return!1;let t=[Ke.join(process.cwd(),"package.json"),Ke.join(process.cwd(),"README.md"),Ke.join(process.cwd(),".gitignore")];for(let e of t)try{let s=await St.stat(e),o=Wn.get(e);if(!o||s.mtimeMs!==o)return!1}catch{if(Wn.has(e))return!1}try{let e=Ke.join(process.cwd(),".git","HEAD"),s=await St.stat(e),o=Wn.get(e);if(!o||s.mtimeMs!==o)return!1}catch{}return!0}async function Yy(){let t=[Ke.join(process.cwd(),"package.json"),Ke.join(process.cwd(),"README.md"),Ke.join(process.cwd(),".gitignore"),Ke.join(process.cwd(),".git","HEAD")];for(let e of t)try{let s=await St.stat(e);Wn.set(e,s.mtimeMs)}catch{Wn.delete(e)}}async function zy(t){let e="fileContext",s=Hi.get(e),o=!1;if(s&&await Ky()&&(o=!0),!o){let u=[],d=Ke.join(t,"package.json");if(await Zt(()=>St.access(d).then(()=>!0).catch(()=>!1)))try{let $=await St.readFile(d,"utf-8"),y=JSON.parse($),x={name:y.name,version:y.version};y.scripts&&(x.scripts=Object.keys(y.scripts).slice(0,15)),y.dependencies&&(x.deps=Object.keys(y.dependencies).length),y.devDependencies&&(x.devDeps=Object.keys(y.devDependencies).length),u.push(`PACKAGE: ${JSON.stringify(x)}`)}catch{}let p=Ke.join(t,"README.md");if(await Zt(()=>St.access(p).then(()=>!0).catch(()=>!1))){let y=(await St.readFile(p,"utf-8")).split(`
|
|
426
447
|
`).slice(0,50);u.push(`README (first 50 lines):
|
|
427
|
-
${
|
|
428
|
-
`)}`)}let
|
|
429
|
-
${
|
|
448
|
+
${y.join(`
|
|
449
|
+
`)}`)}let m=Ke.join(t,".gitignore");if(await Zt(()=>St.access(m).then(()=>!0).catch(()=>!1))){let $=await St.readFile(m,"utf-8");u.push(`GITIGNORE:
|
|
450
|
+
${$.trim()}`)}s=u.join(`
|
|
430
451
|
|
|
431
|
-
`),
|
|
452
|
+
`),Hi.set(e,s),Go=Date.now()+Gy,await Yy()}let n=[s],[r,i,c,l]=await Promise.all([Zt(async()=>{let{stdout:u}=await Ho("git branch --show-current",{cwd:t,timeout:5e3});return u.trim()}),Zt(async()=>{let{stdout:u}=await Ho("git status --short",{cwd:t,timeout:5e3});return u.trim()}),Zt(async()=>{let{stdout:u}=await Ho("git log --oneline -5",{cwd:t,timeout:5e3});return u.trim()}),ud()]);if(r&&n.push(`GIT BRANCH: ${r}`),i&&n.push(`GIT STATUS:
|
|
432
453
|
${i}`),c&&n.push(`RECENT COMMITS:
|
|
433
454
|
${c}`),l&&l.length>0){let u=l.map(d=>` ${d.file}`).join(`
|
|
434
455
|
`);n.push(`MERGE CONFLICTS (resolve before editing these files):
|
|
435
|
-
${u}`)}try{let u=
|
|
456
|
+
${u}`)}try{let u=Fy();u&&n.push(u)}catch{}return n.join(`
|
|
436
457
|
|
|
437
|
-
`)}async function
|
|
438
|
-
${i} Session score: ${c}${
|
|
439
|
-
${u}\u26A0${c} ${i}${g}${c}`;return
|
|
440
|
-
${e}`);let s=
|
|
441
|
-
${s}`);let o=
|
|
458
|
+
`)}async function Xy(t){let e=Ke.join(t,"package.json"),s="";if(await Zt(()=>St.access(e).then(()=>!0).catch(()=>!1)))try{let i=await St.readFile(e,"utf-8"),c=JSON.parse(i);s=`${c.name||"?"} v${c.version||"?"}`}catch{}let[n,r]=await Promise.all([Zt(async()=>{let{stdout:i}=await Ho("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),ud()]);if(r&&r.length>0){console.log(`${Un.red} \u26A0 ${r.length} unresolved merge conflict(s):${Un.reset}`);for(let i of r)console.log(`${Un.red} ${i.file}${Un.reset}`);console.log(`${Un.yellow} \u2192 Resolve conflicts before starting tasks${Un.reset}`)}console.log()}dd.exports={gatherProjectContext:zy,printContext:Xy,generateFileTree:Hy,_clearContextCache:()=>{Hi.clear(),Wn.clear(),Go=null}}});var Et=G((sk,hd)=>{var en=require("fs"),Gi=require("path"),{atomicWrite:Jy}=Xt();function Yo(){return Gi.join(process.cwd(),".nex","sessions")}function fd(){let t=Yo();en.existsSync(t)||en.mkdirSync(t,{recursive:!0})}function Ki(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return Gi.join(Yo(),`${e}.json`)}function Yi(t,e,s={}){fd();let o=Ki(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 Jy(o,JSON.stringify(n,null,2)),{path:o,name:t}}function pd(t){let e=Ki(t);if(!en.existsSync(e))return null;try{return JSON.parse(en.readFileSync(e,"utf-8"))}catch{return null}}function md(){fd();let t=Yo(),e=en.readdirSync(t).filter(o=>o.endsWith(".json")),s=[];for(let o of e)try{let n=JSON.parse(en.readFileSync(Gi.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,score:n.score!=null?n.score:null,scoreGrade:n.scoreGrade||null})}catch{}return s.sort((o,n)=>(n.updatedAt||"").localeCompare(o.updatedAt||""))}function Vy(t){let e=Ki(t);return en.existsSync(e)?(en.unlinkSync(e),!0):!1}function Qy(){let t=md();return t.length===0?null:pd(t[0].name)}var gn=null,qt=null,As=null;function Zy(t,e={}){t.length!==0&&(gn&&clearTimeout(gn),qt=t,As=e||{},gn=setTimeout(()=>{qt&&qt.length>0&&Yi("_autosave",qt,As),gn=null,qt=null,As=null},5e3))}function ew(){gn&&(clearTimeout(gn),gn=null),qt&&qt.length>0&&(Yi("_autosave",qt,As),qt=null,As=null)}hd.exports={saveSession:Yi,loadSession:pd,listSessions:md,deleteSession:Vy,getLastSession:Qy,autoSave:Zy,flushAutoSave:ew,_getSessionsDir:Yo}});var zo=G((ok,kd)=>{"use strict";var Os=require("fs"),gd=require("path");function $d(t){let e=[];return t.forEach((s,o)=>{s.role==="assistant"&&(Array.isArray(s.content)&&s.content.forEach(n=>{n&&n.type==="tool_use"&&e.push({name:n.name||"",input:n.input||{},index:o})}),Array.isArray(s.tool_calls)&&s.tool_calls.forEach(n=>{let r=n.function?.name||n.name||"",i={};try{i=typeof n.function?.arguments=="string"?JSON.parse(n.function.arguments):n.function?.arguments||n.input||{}}catch{}e.push({name:r,input:i,index:o})}))}),e}function yd(t){let e=[];return t.forEach((s,o)=>{if(s.role==="user"&&Array.isArray(s.content)&&s.content.forEach(n=>{if(n&&n.type==="tool_result"){let r=typeof n.content=="string"?n.content:Array.isArray(n.content)?n.content.map(i=>typeof i=="string"?i:i.text||"").join(""):JSON.stringify(n.content||"");e.push({content:r,index:o})}}),s.role==="tool"){let n=typeof s.content=="string"?s.content:JSON.stringify(s.content||"");e.push({content:n,index:o})}}),e}function wd(t){for(let e=t.length-1;e>=0;e--){let s=t[e];if(s.role==="assistant"){if(typeof s.content=="string")return s.content.trim();if(Array.isArray(s.content)){let o=s.content.filter(n=>n&&(n.type==="text"||typeof n=="string")).map(n=>typeof n=="string"?n:n.text||"").join("").trim();if(o)return o}}}return""}function bd(t,e){let s=[];for(let o=t.length-1;o>=0&&s.length<e;o--){let n=t[o];if(n.role!=="assistant")continue;let r="";typeof n.content=="string"?r=n.content.trim():Array.isArray(n.content)&&(r=n.content.filter(i=>i&&(i.type==="text"||typeof i=="string")).map(i=>typeof i=="string"?i:i.text||"").join("").trim()),r&&s.push(r)}return s}function _d(t){let e=new Map;for(let s of t){let o;try{o=JSON.stringify(s.input)}catch{o=String(s.input)}let n=`${s.name}|${o}`;e.set(n,(e.get(n)||0)+1)}return e}function xd(t){if(!Array.isArray(t)||t.length===0)return{score:0,issues:["Empty or invalid session \u2014 no messages to analyse"],summary:"No messages found"};let e=10,s=[],o=$d(t),n=yd(t),r=o.length;t.some(A=>A.role==="user"&&typeof A.content=="string"&&A.content.startsWith("[SYSTEM WARNING]")&&(A.content.includes("edited")||A.content.includes("bash command")||A.content.includes("grep pattern")||A.content.includes("re-read")||A.content.includes("already in your context")))&&(e-=2,s.push("Loop-warning was fired during session (repeated file edits, bash commands, or re-reads)"));let c=o.find(A=>{let M=A.input?.command||A.input?.cmd||"";return/\bsed\s+-n\b/.test(M)});if(c){let A=(c.input?.command||c.input?.cmd||"").slice(0,80);e-=1.5,s.push(`sed -n anti-pattern used: ${A}`)}o.find(A=>{if(A.name!=="grep"&&A.name!=="bash"&&A.name!=="ssh_exec")return!1;let M=A.input?.command||A.input?.cmd||"",D=A.input?.pattern||"",W=`${M} ${D}`;return/(?:-[CAB]|--context|--after|--before)\s*[=\s]?([2-9][1-9]|\d{3,})/.test(W)||/grep.*-[CAB]\s*([2-9][1-9]|\d{3,})/.test(W)})&&(e-=1,s.push("grep used with >20 context lines (context flood risk)"));let u=wd(t);if(!bd(t,3).some(A=>A.length>100&&!/^[^.!]{0,40}\?$/.test(A))&&(u.length<50||/^[^.!]{0,40}\?$/.test(u))){e-=2;let A=u.length>0?`"${u.slice(0,60)}..."`:"(no assistant text found)";s.push(`Session ends without diagnosis \u2014 last response too short or is only a question: ${A}`)}r>40?(e-=1.5,s.push(`Excessive tool calls: ${r} (>40 threshold)`)):r>25&&(e-=.5,s.push(`High tool call count: ${r} (>25 threshold)`)),t.some(A=>{let M=typeof A.content=="string"?A.content:Array.isArray(A.content)?A.content.map(D=>typeof D=="string"?D:D.text||"").join(""):"";return/\[auto-compressed|context compacted|force-compressed/.test(M)})&&(e-=.5,s.push("Auto-compress triggered (context flood indicator)"));let m=_d(o),g=0,$="";for(let[A,M]of m)M>g&&(g=M,$=A);if(g>=3){let[A]=$.split("|");e-=1,s.push(`Same tool call repeated ${g}\xD7 (tool: ${A})`)}let y=!1;for(let A of n)if(A.content&&A.content.includes('"valid":true')&&o.filter(D=>D.index>A.index).length>0){y=!0;break}y&&(e-=1.5,s.push('Stop-trigger ignored: tool result contained "valid":true but session continued with more tool calls'));let x=o.filter(A=>A.name==="ssh_exec");if(x.length>=8){let A=0,M=1;for(let D=1;D<x.length;D++)x[D].index<=x[D-1].index+2?M++:(A=Math.max(A,M),M=1);A=Math.max(A,M),A>=8&&(e-=.5,s.push(`SSH reconnect storm: ${A} consecutive SSH calls`))}let _=new Map;for(let A of o)if(A.name==="read_file"&&A.input?.path){let M=A.input.path;_.set(M,(_.get(M)||0)+1)}let v=0,b="";for(let[A,M]of _)M>v&&(v=M,b=A);if(v>=3){e-=1;let A=b.split("/").slice(-2).join("/");s.push(`read_file loop: "${A}" read ${v}\xD7 (file already in context)`)}let k=new Map;for(let A of o)if(A.name==="grep"&&A.input?.path&&A.input?.pattern){let M=A.input.path;k.has(M)||k.set(M,new Set),k.get(M).add(A.input.pattern)}let R=0,O="";for(let[A,M]of k)M.size>R&&(R=M.size,O=A);if(R>=3){e-=.75;let A=O.split("/").slice(-2).join("/");s.push(`grep flood on single file: "${A}" searched ${R}\xD7 with different patterns (file already in context)`)}let P=n.filter(A=>A.content.startsWith("EXIT")).length;P>=10?(e-=1,s.push(`Bash exit-error storm: ${P} tool results started with EXIT (repeated failing commands)`)):P>=5&&(e-=.5,s.push(`Repeated bash errors: ${P} tool results with non-zero exit code`));for(let A of t){if(A.role!=="assistant")continue;let M="";if(typeof A.content=="string"?M=A.content:Array.isArray(A.content)&&(M=A.content.filter(le=>le&&(le.type==="text"||typeof le=="string")).map(le=>typeof le=="string"?le:le.text||"").join("")),M.length<=5e3)continue;let D=M.split(/(?<=\. )/).filter(le=>le.trim().length>0);if(D.length<6)continue;let W=new Map;for(let le=0;le<=D.length-3;le++){let pt=D.slice(le,le+3).join("").trim();pt.length>30&&W.set(pt,(W.get(pt)||0)+1)}let Q=0,ne="";for(let[le,pt]of W)pt>Q&&(Q=pt,ne=le);if(Q<3)continue;let Re=ne.length*Q/M.length;if(Re>=.4||Q>=10){e-=1.5,s.push(`llm output loop: assistant message repeated content detected (${Q}\xD7 same paragraph, ${Math.round(Re*100)}% repeated)`);break}}{let A=new Set(["read_file","list_directory","search_files","glob","grep"]),M=t.some(W=>Array.isArray(W.tool_calls)?W.tool_calls.some(Q=>A.has(Q.function?.name)):Array.isArray(W.content)?W.content.some(Q=>Q.type==="tool_use"&&A.has(Q.name)):!1);t.some(W=>W.role==="assistant"&&typeof W.content=="string"&&(W.content.includes("## Steps")||W.content.includes("#### ")||W.content.includes("/plan approve")))&&!M&&(e-=2,s.push("plan written without reading any files \u2014 LLM invented data structures from training knowledge (hallucination risk)"))}let F=n.filter(A=>A.content.startsWith("BLOCKED:"));if(F.length>0){let A=Math.min(F.length*.5,1.5);e-=A,s.push(`${F.length} tool call${F.length===1?"":"s"} blocked (agent attempted denied actions)`)}e=Math.max(0,Math.min(10,e)),e=Math.round(e*10)/10;let De=e>=9?"A":e>=8?"B":e>=7?"C":e>=6?"D":"F",me=s.length===0?`Clean session \u2014 no quality issues detected (${r} tool calls)`:`${s.length} issue${s.length===1?"":"s"} found \u2014 ${r} tool calls`;return{score:e,grade:De,issues:s,summary:me}}function tw(t){try{let{loadSession:e}=Et(),s=e(t);return s?xd(s.messages||[]):null}catch{return null}}function nw(t,e=null){let{score:s,grade:o,issues:n,summary:r}=t,i=e?.dim||"",c=e?.reset||"",l=e?.green||"",u=e?.yellow||"",d=e?.red||"",f=e?.cyan||"",p=e?.bold||"",h=s>=8?l:s>=6?u:d,m=`
|
|
459
|
+
${i} Session score: ${c}${p}${h}${s}/10 (${o})${c}`;if(r&&(m+=` ${i}${r}${c}`),n.length>0)for(let g of n)m+=`
|
|
460
|
+
${u}\u26A0${c} ${i}${g}${c}`;return m}function sw(t,e={}){try{let s=gd.join(process.cwd(),".nex");Os.existsSync(s)||Os.mkdirSync(s,{recursive:!0});let o=gd.join(s,"benchmark-history.json"),n=[];if(Os.existsSync(o))try{n=JSON.parse(Os.readFileSync(o,"utf-8"))}catch{n=[]}Array.isArray(n)||(n=[]);let r=t>=9?"A":t>=8?"B":t>=7?"C":t>=6?"D":"F",i={date:new Date().toISOString(),version:e.version||null,model:e.model||null,score:t,grade:r,sessionName:e.sessionName||null,issues:Array.isArray(e.issues)?e.issues:[]};n.push(i),n.length>100&&(n=n.slice(n.length-100)),Os.writeFileSync(o,JSON.stringify(n,null,2))}catch{}}kd.exports={scoreMessages:xd,scoreSession:tw,formatScore:nw,appendScoreHistory:sw,_extractToolCalls:$d,_extractToolResults:yd,_getLastAssistantText:wd,_getLastNAssistantTexts:bd,_countDuplicateToolCalls:_d}});var nn=G((rk,Ad)=>{var tn=require("fs"),Xo=require("path"),ow=require("os"),{atomicWrite:rw,withFileLockSync:vd}=Xt();function zi(){return Xo.join(process.cwd(),".nex","memory")}function Ns(){return Xo.join(zi(),"memory.json")}function iw(){return Xo.join(process.cwd(),"NEX.md")}function Sd(){return Xo.join(ow.homedir(),".nex","NEX.md")}function Xi(){let t=zi();tn.existsSync(t)||tn.mkdirSync(t,{recursive:!0})}function Jo(){let t=Ns();if(!tn.existsSync(t))return{};try{return JSON.parse(tn.readFileSync(t,"utf-8"))}catch{return{}}}function Ed(t){Xi(),rw(Ns(),JSON.stringify(t,null,2))}function aw(t,e){Xi(),vd(Ns(),()=>{let s=Jo();s[t]={value:e,updatedAt:new Date().toISOString()},Ed(s)})}function cw(t){let e=Jo();return e[t]?e[t].value:null}function lw(t){return Xi(),vd(Ns(),()=>{let e=Jo();return t in e?(delete e[t],Ed(e),!0):!1})}function Td(){let t=Jo();return Object.entries(t).map(([e,s])=>({key:e,value:s.value,updatedAt:s.updatedAt}))}function Rd(){let t=Sd();if(!tn.existsSync(t))return"";try{return tn.readFileSync(t,"utf-8").trim()}catch{return""}}function Cd(){let t=iw();if(!tn.existsSync(t))return"";try{return tn.readFileSync(t,"utf-8").trim()}catch{return""}}function uw(){let t=[],e=Rd();e&&t.push(`GLOBAL INSTRUCTIONS (~/.nex/NEX.md):
|
|
461
|
+
${e}`);let s=Cd();s&&t.push(`PROJECT INSTRUCTIONS (NEX.md):
|
|
462
|
+
${s}`);let o=Td();if(o.length>0){let n=o.map(r=>` ${r.key}: ${r.value}`).join(`
|
|
442
463
|
`);t.push(`PROJECT MEMORY:
|
|
443
464
|
${n}`)}return t.join(`
|
|
444
465
|
|
|
445
|
-
`)}
|
|
446
|
-
${
|
|
447
|
-
`);for(let o=0;o<t.steps.length;o++){let n=t.steps[o],r;switch(n.status){case"done":r=`${
|
|
448
|
-
`)}function
|
|
466
|
+
`)}Ad.exports={remember:aw,recall:cw,forget:lw,listMemories:Td,loadGlobalInstructions:Rd,loadProjectInstructions:Cd,getMemoryContext:uw,_getMemoryDir:zi,_getMemoryFile:Ns,_getGlobalNexMdPath:Sd}});var Ps=G((ak,Id)=>{var lt=require("fs"),Bn=require("path"),{C:ik}=ve(),{atomicWrite:dw,withFileLockSync:fw}=Xt(),Vo={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"},Hn={...Vo};function Od(){let t=Bn.join(process.cwd(),".nex","config.json");if(lt.existsSync(t))try{let e=JSON.parse(lt.readFileSync(t,"utf-8"));e.permissions&&(Hn={...Vo,...e.permissions})}catch{}}function pw(){let t=Bn.join(process.cwd(),".nex"),e=Bn.join(t,"config.json");lt.existsSync(t)||lt.mkdirSync(t,{recursive:!0}),fw(e,()=>{let s={};if(lt.existsSync(e))try{s=JSON.parse(lt.readFileSync(e,"utf-8"))}catch{s={}}s.permissions=Hn,dw(e,JSON.stringify(s,null,2))})}function Nd(t){return Hn[t]||"ask"}function mw(t,e){return["allow","ask","deny"].includes(e)?(Hn[t]=e,!0):!1}function hw(t){return Nd(t)}function gw(){return Object.entries(Hn).map(([t,e])=>({tool:t,mode:e}))}function $w(){Hn={...Vo}}var Ms={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 Md(){let t=Bn.join(process.cwd(),".nex","config.json");try{return lt.existsSync(t)&&JSON.parse(lt.readFileSync(t,"utf-8")).teamPermissions||null}catch{return null}}function yw(t){let e=Bn.join(process.cwd(),".nex"),s=Bn.join(e,"config.json");lt.existsSync(e)||lt.mkdirSync(e,{recursive:!0});let o={};try{lt.existsSync(s)&&(o=JSON.parse(lt.readFileSync(s,"utf-8")))}catch{o={}}o.teamPermissions=t,lt.writeFileSync(s,JSON.stringify(o,null,2),"utf-8")}function Pd(){let t=Md();if(!t)return Ms.admin;let e=t.role||"admin",s=Ms[e]||Ms.admin;return{...s,...t.overrides,blockedTools:[...s.blockedTools||[],...t.overrides?.blockedTools||[]]}}function ww(t){let e=Pd();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 bw(){return Object.entries(Ms).map(([t,e])=>({name:t,description:e.description,toolCount:e.allowedTools?`${e.allowedTools.length} allowed`:"all allowed",blockedCount:e.blockedTools.length}))}Od();Id.exports={getPermission:Nd,setPermission:mw,checkPermission:hw,listPermissions:gw,loadPermissions:Od,savePermissions:pw,resetPermissions:$w,DEFAULT_PERMISSIONS:Vo,PERMISSION_PRESETS:Ms,loadPresetConfig:Md,savePresetConfig:yw,getEffectivePreset:Pd,isToolAllowed:ww,listPresets:bw}});var Ft=G((lk,Fd)=>{var yn=require("fs"),Qo=require("path"),ck=require("readline"),{C:pe}=ve(),de=null,Vi=!1,Qi=null,Ld=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 Zo(){return Qo.join(process.cwd(),".nex","plans")}function jd(){let t=Zo();yn.existsSync(t)||yn.mkdirSync(t,{recursive:!0})}function _w(t,e=[]){return de={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()},de}function xw(){return de}function kw(t){Vi=t}function vw(){return Vi}function Sw(){return!de||de.status!=="draft"?!1:(de.status="approved",de.updatedAt=new Date().toISOString(),!0)}function Ew(){return!de||de.status!=="approved"?!1:(de.status="executing",!0)}function Ji(t,e){return!de||t<0||t>=de.steps.length?!1:(de.steps[t].status=e,de.updatedAt=new Date().toISOString(),de.steps.every(s=>s.status==="done"||s.status==="skipped")&&(de.status="completed"),!0)}function Tw(t){if(!t)return`${pe.dim}No active plan${pe.reset}`;let e={draft:`${pe.yellow}DRAFT${pe.reset}`,approved:`${pe.green}APPROVED${pe.reset}`,executing:`${pe.blue}EXECUTING${pe.reset}`,completed:`${pe.green}COMPLETED${pe.reset}`},s=[];s.push(`
|
|
467
|
+
${pe.bold}${pe.cyan}Plan: ${t.task}${pe.reset}`),s.push(`${pe.dim}Status: ${e[t.status]||t.status}${pe.reset}
|
|
468
|
+
`);for(let o=0;o<t.steps.length;o++){let n=t.steps[o],r;switch(n.status){case"done":r=`${pe.green}\u2713${pe.reset}`;break;case"in_progress":r=`${pe.blue}\u2192${pe.reset}`;break;case"skipped":r=`${pe.dim}\u25CB${pe.reset}`;break;default:r=`${pe.dim} ${pe.reset}`}s.push(` ${r} ${pe.bold}Step ${o+1}:${pe.reset} ${n.description}`),n.files.length>0&&s.push(` ${pe.dim}Files: ${n.files.join(", ")}${pe.reset}`)}return s.push(""),s.join(`
|
|
469
|
+
`)}function Rw(t){if(t||(t=de),!t)return null;jd();let e=Qo.join(Zo(),`${t.name}.json`);return yn.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function Cw(t){let e=Qo.join(Zo(),`${t}.json`);if(!yn.existsSync(e))return null;try{let s=JSON.parse(yn.readFileSync(e,"utf-8"));return de=s,s}catch{return null}}function Aw(){jd();let t=Zo(),e=yn.readdirSync(t).filter(o=>o.endsWith(".json")),s=[];for(let o of e)try{let n=JSON.parse(yn.readFileSync(Qo.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 Ow(t){if(!t)return[];let e=[],s=t.match(/##\s+Steps?\s*\n([\s\S]*?)(?:\n##|\s*$)/i),o=s?s[1]:t,n=/^\s*(\d+)[.)]\s+(.+)/gm,r;for(;(r=n.exec(o))!==null;){let c=r[2].trim().replace(/^\*\*What\*\*:\s*/i,"").replace(/^\*\*\d+\.\*\*\s*/,"").replace(/\*\*/g,"").trim();c.length>3&&e.push({description:c,files:[],status:"pending"})}if(e.length===0){let i=/\*\*Step\s+\d+[:.]\*\*\s*(.+)/gi;for(;(r=i.exec(t))!==null;){let c=r[1].replace(/\*\*/g,"").trim();c.length>3&&e.push({description:c,files:[],status:"pending"})}}if(e.length>0){let i=/\*\*(?:Where|Files?)\*\*:\s*(.+)/gi,c=[...t.matchAll(i)];for(let l=0;l<Math.min(e.length,c.length);l++){let u=c[l][1];e[l].files=u.split(/[,\s]+/).filter(d=>/[./]/.test(d)).slice(0,5)}}return e}function Nw(t){Qi=t}function Mw(){return Qi}function Pw(){de=null,Vi=!1,Qi=null,Dw()}function Iw(){return`
|
|
449
470
|
PLAN MODE ACTIVE: You are in analysis-only mode. You MUST NOT execute any changes.
|
|
450
471
|
|
|
451
472
|
# Allowed Tools (read-only)
|
|
452
|
-
You may ONLY use these tools: ${[...
|
|
473
|
+
You may ONLY use these tools: ${[...Ld].join(", ")}
|
|
453
474
|
Any other tool call will be blocked and returned with an error.
|
|
454
475
|
|
|
476
|
+
# MANDATORY: Read Before You Plan
|
|
477
|
+
You MUST call at least 2 read-only tools before writing any plan. NEVER assume:
|
|
478
|
+
- What database type is used (SQLite vs JSON files vs MongoDB \u2014 READ to find out)
|
|
479
|
+
- What file contains existing routes (check with glob/read_file first)
|
|
480
|
+
- What methods a module exposes (read the module file first)
|
|
481
|
+
- What the existing code structure looks like (read it, don't invent it)
|
|
482
|
+
|
|
483
|
+
For any task involving a named module (e.g. "fitness", "calendar", "reminder"):
|
|
484
|
+
1. FIRST: glob for the module file and read it to see actual methods/data structures
|
|
485
|
+
2. THEN: read the route file if it exists
|
|
486
|
+
3. ONLY THEN: write the plan based on what you actually found
|
|
487
|
+
|
|
455
488
|
# Analysis Phase
|
|
456
489
|
Thoroughly investigate before writing a plan:
|
|
457
490
|
- Scope: What files and modules are affected?
|
|
@@ -480,45 +513,51 @@ Bullet list of potential issues and mitigations.
|
|
|
480
513
|
# Important
|
|
481
514
|
- Order steps by dependency (later steps may depend on earlier ones).
|
|
482
515
|
- After presenting the plan, tell the user to type \`/plan approve\` to proceed.
|
|
483
|
-
- Do NOT make any file changes \u2014 your role is analysis and planning only.`}var
|
|
484
|
-
`),s=[],o=!1,n="";for(let r of e){let i=
|
|
485
|
-
`)}function
|
|
516
|
+
- Do NOT make any file changes \u2014 your role is analysis and planning only.`}var $n=0;function Lw(){!de||de.status!=="executing"||($n>0&&Ji($n-1,"done"),$n<de.steps.length&&(Ji($n,"in_progress"),$n++))}function jw(){if(!de||de.status!=="executing"||de.steps.length===0)return null;let t=Math.min($n,de.steps.length),e=de.steps.length,s=Math.max(0,t-1),o=de.steps[s]?.description||"";return{current:t,total:e,description:o}}function Dw(){$n=0}var Dd=["interactive","semi-auto","autonomous"],qd="interactive";function qw(t){return Dd.includes(t)?(qd=t,!0):!1}function Fw(){return qd}Fd.exports={createPlan:_w,getActivePlan:xw,setPlanMode:kw,isPlanMode:vw,approvePlan:Sw,startExecution:Ew,updateStep:Ji,formatPlan:Tw,savePlan:Rw,loadPlan:Cw,listPlans:Aw,clearPlan:Pw,getPlanModePrompt:Iw,setPlanContent:Nw,getPlanContent:Mw,extractStepsFromText:Ow,advancePlanStep:Lw,getPlanStepInfo:jw,PLAN_MODE_ALLOWED_TOOLS:Ld,setAutonomyLevel:qw,getAutonomyLevel:Fw,AUTONOMY_LEVELS:Dd}});var Vd=G((uk,Jd)=>{var{C:S}=ve();function Ud(){return Math.max(10,(process.stdout.columns||80)-2)}function Uw(t){if(!t)return"";let e=t.split(`
|
|
517
|
+
`),s=[],o=!1,n="";for(let r of e){let i=Ud();if(r.trim().startsWith("```")){if(o)s.push(`${S.dim}${"\u2500".repeat(40)}${S.reset}`),o=!1,n="";else{o=!0,n=r.trim().substring(3).trim();let c=n?` ${n} `:"";s.push(`${S.dim}${"\u2500".repeat(3)}${c}${"\u2500".repeat(Math.max(0,37-c.length))}${S.reset}`)}continue}if(o){s.push(` ${ea(r,n)}`);continue}if(r.startsWith("### ")){s.push(`${S.bold}${S.cyan} ${wn(r.substring(4))}${S.reset}`);continue}if(r.startsWith("## ")){s.push(`${S.bold}${S.cyan} ${wn(r.substring(3))}${S.reset}`);continue}if(r.startsWith("# ")){s.push(`${S.bold}${S.cyan}${wn(r.substring(2))}${S.reset}`);continue}if(/^\s*[-*]\s/.test(r)){let c=r.match(/^(\s*)/)[1],l=r.replace(/^\s*[-*]\s/,""),u=`${c}${S.cyan}\u2022${S.reset} ${bn(l)}`;s.push(_n(u,i,c+" "));continue}if(/^\s*\d+\.\s/.test(r)){let c=r.match(/^(\s*)(\d+)\.\s(.*)/);if(c){let l=c[1],u=c[2],d=c[3],f=`${l}${S.cyan}${u}.${S.reset} ${bn(d)}`,p=l+" ".repeat(u.length+2);s.push(_n(f,i,p));continue}}s.push(_n(bn(r),i))}return s.join(`
|
|
518
|
+
`)}function wn(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function bn(t){return t?t.replace(/`([^`]+)`/g,`${S.cyan}$1${S.reset}`).replace(/\*\*([^*]+)\*\*/g,`${S.bold}$1${S.reset}`).replace(/\*([^*]+)\*/g,`${S.dim}$1${S.reset}`).replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${S.cyan}$1${S.reset} ${S.dim}($2)${S.reset}`):""}function ea(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?Wd(t):e==="bash"||e==="sh"||e==="shell"||e==="zsh"?Bd(t):e==="json"||e==="jsonc"?Hd(t):e==="python"||e==="py"?Gd(t):e==="go"||e==="golang"?Kd(t):e==="rust"||e==="rs"?Yd(t):e==="css"||e==="scss"||e==="less"?zd(t):e==="html"||e==="xml"||e==="svg"||e==="htm"?Xd(t):t:""}function Wd(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,`${S.yellow}$1${S.reset}`),r=r.replace(e,`${S.magenta}$1${S.reset}`),r=r.replace(s,`${S.green}$&${S.reset}`),r=r.replace(o,`${S.dim}$1${S.reset}`),r}function Bd(t){let e=/^(\s*)([\w-]+)/,s=/(--?\w[\w-]*)/g,o=/(["'])(?:(?=(\\?))\2.)*?\1/g,n=/(#.*$)/,r=t;return r=r.replace(s,`${S.cyan}$1${S.reset}`),r=r.replace(e,`$1${S.green}$2${S.reset}`),r=r.replace(o,`${S.yellow}$&${S.reset}`),r=r.replace(n,`${S.dim}$1${S.reset}`),r}function Hd(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,`${S.cyan}$1${S.reset}:`),r=r.replace(s,`: ${S.green}$1${S.reset}`),r=r.replace(o,`: ${S.yellow}$1${S.reset}`),r=r.replace(n,`: ${S.magenta}$1${S.reset}`),r}function Gd(t){let e=/\b(def|class|if|elif|else|for|while|return|import|from|as|try|except|finally|raise|with|yield|lambda|pass|break|continue|and|or|not|in|is|None|True|False|self|async|await|nonlocal|global)\b/g,s=/("""[\s\S]*?"""|'''[\s\S]*?'''|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')/g,o=/(#.*$)/,n=/\b(\d+\.?\d*)\b/g,r=/^(\s*@\w+)/,i=t;return i=i.replace(n,`${S.yellow}$1${S.reset}`),i=i.replace(e,`${S.magenta}$1${S.reset}`),i=i.replace(r,`${S.cyan}$1${S.reset}`),i=i.replace(s,`${S.green}$&${S.reset}`),i=i.replace(o,`${S.dim}$1${S.reset}`),i}function Kd(t){let e=/\b(func|package|import|var|const|type|struct|interface|map|chan|go|defer|return|if|else|for|range|switch|case|default|break|continue|select|fallthrough|nil|true|false|make|new|len|cap|append|copy|delete|panic|recover)\b/g,s=/\b(string|int|int8|int16|int32|int64|uint|uint8|uint16|uint32|uint64|float32|float64|bool|byte|rune|error|any)\b/g,o=/(["'`])(?:(?=(\\?))\2.)*?\1/g,n=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,i=t;return i=i.replace(r,`${S.yellow}$1${S.reset}`),i=i.replace(s,`${S.cyan}$1${S.reset}`),i=i.replace(e,`${S.magenta}$1${S.reset}`),i=i.replace(o,`${S.green}$&${S.reset}`),i=i.replace(n,`${S.dim}$1${S.reset}`),i}function Yd(t){let e=/\b(fn|let|mut|const|struct|enum|impl|trait|pub|use|mod|crate|self|super|match|if|else|for|while|loop|return|break|continue|where|as|in|ref|move|async|await|unsafe|extern|type|static|dyn|macro_rules)\b/g,s=/\b(i8|i16|i32|i64|i128|u8|u16|u32|u64|u128|f32|f64|bool|char|str|String|Vec|Option|Result|Box|Rc|Arc|Self|Some|None|Ok|Err|true|false)\b/g,o=/(["'])(?:(?=(\\?))\2.)*?\1/g,n=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,i=/\b(\w+!)/g,c=t;return c=c.replace(r,`${S.yellow}$1${S.reset}`),c=c.replace(s,`${S.cyan}$1${S.reset}`),c=c.replace(e,`${S.magenta}$1${S.reset}`),c=c.replace(i,`${S.yellow}$1${S.reset}`),c=c.replace(o,`${S.green}$&${S.reset}`),c=c.replace(n,`${S.dim}$1${S.reset}`),c}function zd(t){let e=/^(\s*)([\w-]+)\s*:/,s=/:\s*([^;]+)/,o=/^(\s*[.#@][\w-]+)/,n=/\b(\d+\.?\d*(px|em|rem|%|vh|vw|s|ms|deg|fr)?)\b/g,r=/(\/\*.*?\*\/|\/\/.*$)/,i=/(#[0-9a-fA-F]{3,8})\b/g,c=t;return c=c.replace(i,`${S.yellow}$1${S.reset}`),c=c.replace(n,`${S.yellow}$1${S.reset}`),c=c.replace(e,`$1${S.cyan}$2${S.reset}:`),c=c.replace(o,`$1${S.magenta}$&${S.reset}`),c=c.replace(r,`${S.dim}$1${S.reset}`),c}function Xd(t){let e=/<\/?(\w[\w-]*)/g,s=/\s([\w-]+)=/g,o=/(["'])(?:(?=(\\?))\2.)*?\1/g,n=/(<!--.*?-->)/g,r=/(&\w+;)/g,i=t;return i=i.replace(n,`${S.dim}$1${S.reset}`),i=i.replace(o,`${S.green}$&${S.reset}`),i=i.replace(e,`<${S.magenta}$1${S.reset}`),i=i.replace(s,` ${S.cyan}$1${S.reset}=`),i=i.replace(r,`${S.yellow}$1${S.reset}`),i}function _n(t,e,s=""){if(!e||e<10)return t;let o="",n=0,r=-1,i=0,c=0,l=t.length;for(;i<l;){if(t[i]==="\x1B"){let u=i+1;if(u<l&&t[u]==="["){for(u++;u<l&&!/[a-zA-Z]/.test(t[u]);)u++;u<l&&u++}i=u;continue}if(t[i]===" "&&(r=i),n++,n>e&&r!==-1){o+=t.slice(c,r)+`
|
|
486
519
|
`+s,c=r+1,i=c,n=s.length,r=-1;continue}n>e&&r===-1&&(o+=t.slice(c,i)+`
|
|
487
|
-
`+s,c=i,n=s.length+1),i++}return o+=t.slice(c),o}function
|
|
488
|
-
`)}function
|
|
489
|
-
`))!==-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(`${
|
|
490
|
-
`),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){let s=
|
|
491
|
-
`),this.inCodeBlock=!1,this.codeBlockLang="";else{this.inCodeBlock=!0,this.codeBlockLang=e.trim().substring(3).trim();let n=this.codeBlockLang?` ${this.codeBlockLang} `:"";this._safeWrite(`${
|
|
492
|
-
`)}return}if(this.inCodeBlock){this._safeWrite(` ${
|
|
493
|
-
`);return}if(e.startsWith("### ")){this._safeWrite(`${
|
|
494
|
-
`);return}if(e.startsWith("## ")){this._safeWrite(`${
|
|
495
|
-
`);return}if(e.startsWith("# ")){this._safeWrite(`${
|
|
496
|
-
`);return}if(/^\s*[-*]\s/.test(e)){let n=e.match(/^(\s*)/)[1],r=e.replace(/^\s*[-*]\s/,""),i=`${n}${
|
|
497
|
-
`);return}if(/^\s*\d+\.\s/.test(e)){let n=e.match(/^(\s*)(\d+)\.\s(.*)/);if(n){let r=n[1],i=n[2],c=n[3],l=`${r}${
|
|
498
|
-
`);return}}let o=
|
|
499
|
-
`)}};
|
|
500
|
-
`)}var
|
|
520
|
+
`+s,c=i,n=s.length+1),i++}return o+=t.slice(c),o}function Ww(t,e){if(!t||t.length===0)return"";let s=t.map((i,c)=>{let l=e.reduce((u,d)=>Math.max(u,(d[c]||"").length),0);return Math.max(i.length,l)}),o=s.map(i=>"\u2500".repeat(i+2)).join("\u253C"),n=t.map((i,c)=>` ${S.bold}${i.padEnd(s[c])}${S.reset} `).join("\u2502"),r=[];r.push(`${S.dim}\u250C${o.replace(/┼/g,"\u252C")}\u2510${S.reset}`),r.push(`${S.dim}\u2502${S.reset}${n}${S.dim}\u2502${S.reset}`),r.push(`${S.dim}\u251C${o}\u2524${S.reset}`);for(let i of e){let c=t.map((l,u)=>` ${(i[u]||"").padEnd(s[u])} `).join(`${S.dim}\u2502${S.reset}`);r.push(`${S.dim}\u2502${S.reset}${c}${S.dim}\u2502${S.reset}`)}return r.push(`${S.dim}\u2514${o.replace(/┼/g,"\u2534")}\u2518${S.reset}`),r.join(`
|
|
521
|
+
`)}function Bw(t,e,s,o=30){let n=s>0?Math.round(e/s*100):0,r=Math.round(n/100*o),i=o-r,c=n>=100?S.green:n>50?S.yellow:S.cyan;return` ${t} ${c}${"\u2588".repeat(r)}${S.dim}${"\u2591".repeat(i)}${S.reset} ${n}% (${e}/${s})`}var Zi=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(`
|
|
522
|
+
`))!==-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(`${S.dim}${"\u2500".repeat(40)}${S.reset}
|
|
523
|
+
`),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){let s=Ud();if(e.trim().startsWith("```")){if(this.inCodeBlock)this._safeWrite(`${S.dim}${"\u2500".repeat(40)}${S.reset}
|
|
524
|
+
`),this.inCodeBlock=!1,this.codeBlockLang="";else{this.inCodeBlock=!0,this.codeBlockLang=e.trim().substring(3).trim();let n=this.codeBlockLang?` ${this.codeBlockLang} `:"";this._safeWrite(`${S.dim}${"\u2500".repeat(3)}${n}${"\u2500".repeat(Math.max(0,37-n.length))}${S.reset}
|
|
525
|
+
`)}return}if(this.inCodeBlock){this._safeWrite(` ${ea(e,this.codeBlockLang)}
|
|
526
|
+
`);return}if(e.startsWith("### ")){this._safeWrite(`${S.bold}${S.cyan} ${wn(e.substring(4))}${S.reset}
|
|
527
|
+
`);return}if(e.startsWith("## ")){this._safeWrite(`${S.bold}${S.cyan} ${wn(e.substring(3))}${S.reset}
|
|
528
|
+
`);return}if(e.startsWith("# ")){this._safeWrite(`${S.bold}${S.cyan}${wn(e.substring(2))}${S.reset}
|
|
529
|
+
`);return}if(/^\s*[-*]\s/.test(e)){let n=e.match(/^(\s*)/)[1],r=e.replace(/^\s*[-*]\s/,""),i=`${n}${S.cyan}\u2022${S.reset} ${bn(r)}`,c=_n(i,s,n+" ");this._safeWrite(`${c}
|
|
530
|
+
`);return}if(/^\s*\d+\.\s/.test(e)){let n=e.match(/^(\s*)(\d+)\.\s(.*)/);if(n){let r=n[1],i=n[2],c=n[3],l=`${r}${S.cyan}${i}.${S.reset} ${bn(c)}`,u=r+" ".repeat(i.length+2),d=_n(l,s,u);this._safeWrite(`${d}
|
|
531
|
+
`);return}}let o=_n(bn(e),s);this._safeWrite(`${o}
|
|
532
|
+
`)}};Jd.exports={renderMarkdown:Uw,renderInline:bn,stripHeadingMarkers:wn,highlightCode:ea,highlightJS:Wd,highlightBash:Bd,highlightJSON:Hd,highlightPython:Gd,highlightGo:Kd,highlightRust:Yd,highlightCSS:zd,highlightHTML:Xd,renderTable:Ww,renderProgress:Bw,wrapAnsi:_n,StreamRenderer:Zi}});var sa=G((dk,tf)=>{var{execSync:Hw}=require("child_process"),ta=require("path"),Is=require("fs"),na=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function Qd(){return ta.join(process.cwd(),".nex","hooks")}function Gw(){return ta.join(process.cwd(),".nex","config.json")}function Zd(){let t=Gw();if(!Is.existsSync(t))return{};try{return JSON.parse(Is.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function er(t){if(!na.includes(t))return[];let e=[],s=Qd(),o=ta.join(s,t);Is.existsSync(o)&&e.push(o);let n=Zd();if(n[t]){let r=Array.isArray(n[t])?n[t]:[n[t]];e.push(...r)}return e}function ef(t,e={},s=3e4){try{return{success:!0,output:Hw(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 Kw(t,e={}){let s=er(t);if(s.length===0)return[];let o={};for(let[r,i]of Object.entries(e))o[`NEX_${r.toUpperCase()}`]=String(i);let n=[];for(let r of s){let i=ef(r,o);if(n.push({command:r,...i}),!i.success&&t.startsWith("pre-"))break}return n}function Yw(t){return er(t).length>0}function zw(){let t=[];for(let e of na){let s=er(e);s.length>0&&t.push({event:e,commands:s})}return t}function Xw(){let t=Qd();return Is.existsSync(t)||Is.mkdirSync(t,{recursive:!0}),t}tf.exports={HOOK_EVENTS:na,loadHookConfig:Zd,getHooksForEvent:er,executeHook:ef,runHooks:Kw,hasHooks:Yw,listHooks:zw,initHooksDir:Xw}});var $e=G((gk,_f)=>{var{C:w,Spinner:Kn,TaskProgress:Jw,formatToolCall:Vw,formatToolSummary:uf,formatSectionHeader:oa,formatMilestone:Qw,setActiveTaskProgress:fk}=ve(),{MilestoneTracker:Zw}=dl(),{callStream:e0}=Se(),{parseToolArgs:t0}=Pn(),{executeTool:n0}=kt(),{gatherProjectContext:s0}=Ko(),{fitToContext:o0,forceCompress:Nt,getUsage:Tt,estimateTokens:r0}=He(),{autoSave:i0,flushAutoSave:a0}=Et(),{scoreMessages:c0,formatScore:l0,appendScoreHistory:u0}=zo();function Ie(t){i0(t),a0()}function nf(t){try{if(!t.some(o=>o.role!=="assistant"?!1:!!(Array.isArray(o.content)&&o.content.some(n=>n&&n.type==="tool_use")||Array.isArray(o.tool_calls)&&o.tool_calls.length>0)))return;let s=c0(t);if(!s)return;console.log(l0(s,w));try{let{_getSessionsDir:o}=Et(),n=require("fs"),r=require("path").join(o(),"_autosave.json");if(n.existsSync(r)){let i=JSON.parse(n.readFileSync(r,"utf-8"));i.score=s.score,i.scoreGrade=s.grade,i.scoreIssues=s.issues,n.writeFileSync(r,JSON.stringify(i,null,2))}}catch{}try{let{getActiveModel:o}=Pn(),n=Sn();u0(s.score,{version:n.version,model:o?o():null,sessionName:"_autosave",issues:s.issues})}catch{}}catch{}}var{getMemoryContext:d0}=nn(),{getDeploymentContextBlock:f0}=Bi(),{checkPermission:p0,setPermission:m0,savePermissions:h0}=Ps(),{confirm:df,setAllowAlwaysHandler:g0,getAutoConfirm:$0}=Ue(),{isPlanMode:qs,getPlanModePrompt:y0,PLAN_MODE_ALLOWED_TOOLS:ff,setPlanContent:w0,extractStepsFromText:b0,createPlan:_0,getActivePlan:pk,startExecution:mk,advancePlanStep:x0,getPlanStepInfo:k0}=Ft(),{StreamRenderer:v0}=Vd(),{runHooks:sf}=sa(),{routeMCPCall:S0,getMCPToolDefinitions:E0}=bo(),{getSkillInstructions:T0,getSkillToolDefinitions:R0,routeSkillCall:C0}=Qt(),{trackUsage:A0}=Mn(),{validateToolArgs:O0}=fi(),{filterToolsForModel:of,getModelTier:N0,PROVIDER_DEFAULT_TIER:hk}=No(),{getConfiguredProviders:M0,getActiveProviderName:Ls,getActiveModelId:Yn,setActiveModel:rf,MODEL_EQUIVALENTS:ar}=Se(),$a=require("fs"),ya=require("path"),P0=(()=>{let t=parseInt(process.env.NEX_MILESTONE_STEPS??"5",10);return Number.isFinite(t)&&t>=0?t:5})();function I0(t){let e=Qw(t.phaseName,t.stepCount,t.toolCounts,t.elapsed,t.filesRead,t.filesModified);process.stdout.write(`${e}
|
|
533
|
+
`)}var af=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi;function L0(t){let e=[],s;for(af.lastIndex=0;(s=af.exec(t))!==null;){let o=s[1].trim(),n=o.startsWith("~")?o.replace("~",process.env.HOME||""):ya.resolve(o);$a.existsSync(n)&&e.push({raw:o,abs:n})}return e}function j0(t){let e=$a.readFileSync(t),s=ya.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 pf(t){let e=L0(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}=j0(o.abs);s.push({type:"image",media_type:r,data:n})}catch{}return s.length>1?s:t}function D0(t){if(!t||t.length<200)return{text:t,truncated:!1,repeatCount:0};let s=t.split(/(?<=\. )/).filter(l=>l.trim().length>0);if(s.length<6)return{text:t,truncated:!1,repeatCount:0};let o=new Map;for(let l=0;l<=s.length-3;l++){let u=s.slice(l,l+3).join("").trim();u.length>30&&o.set(u,(o.get(u)||0)+1)}let n=0,r="";for(let[l,u]of o)u>n&&(n=u,r=l);if(n<3)return{text:t,truncated:!1,repeatCount:n};let i=`
|
|
534
|
+
|
|
535
|
+
[SYSTEM: Output repetition detected \u2014 response truncated (${n}\xD7 repeated paragraph)]`,c;if(t.length>8e3)c=t.slice(0,3e3)+i;else{let l=0,u=-1,d=0;for(;l<2;){let f=t.indexOf(r,d);if(f===-1)break;l++,u=f+r.length,d=f+1}c=u>0?t.slice(0,u)+i:t.slice(0,3e3)+i}return{text:c,truncated:!0,repeatCount:n}}function da(t,e=5){if(!t||t.length<40)return{text:t,truncated:!1,repeatCount:0};let s=t.split(`
|
|
536
|
+
`),o=new Map;for(let f of s){let p=f.trim();p.length>=20&&o.set(p,(o.get(p)||0)+1)}let n=0,r="";for(let[f,p]of o)p>n&&(n=p,r=f);if(n<=e)return{text:t,truncated:!1,repeatCount:n};let i=`
|
|
537
|
+
|
|
538
|
+
\u26A0 [Response truncated: repeated paragraph detected (${n}\xD7)]`,c=0,l=-1,u=0;for(;c<e;){let f=t.indexOf(r,u);if(f===-1)break;c++,l=f+r.length,u=f+1}return{text:l>0?t.slice(0,l)+i:t.slice(0,2e3)+i,truncated:!0,repeatCount:n}}var ra=null,ia=null,aa=null;function We(){if(ra===null){let{TOOL_DEFINITIONS:t}=kt();ra=t}return ia===null&&(ia=R0()),aa===null&&(aa=E0()),[...ra,...ia,...aa]}var fa=50;function q0(t){Number.isFinite(t)&&t>0&&(fa=t)}var nr=()=>null;function F0(t){nr=t}var js=null,pa=null,zn=null,sr=new Map,U0=1e4,W0=6e3,B0=/\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 H0(t){return!t||typeof t!="string"?t:t.replace(B0,(e,s)=>`${s}=***REDACTED***`)}var G0=7e3,K0=4e3;function Y0(t,e=null){let s=H0(t),o=r0(s),n=e==="read_file"?G0:U0,r=e==="read_file"?K0:W0;if(o>n)try{let{compressToolResult:i}=He();return i(s,r)}catch{return s}return s}function mf(t){try{let{getActiveModel:e}=Se(),s=e(),o=s?`${s.provider}:${s.id}`:"default";if(sr.has(o))return sr.get(o);let n=of(t);return sr.set(o,n),n}catch{return of(t)}}function z0(){sr.clear()}async function hf(){try{let t=require("fs").promises,e=require("path"),s=[e.join(process.cwd(),"package.json"),e.join(process.cwd(),".git","HEAD"),e.join(process.cwd(),"README.md"),e.join(process.cwd(),"NEX.md")],n=(await Promise.allSettled(s.map(r=>t.stat(r).then(i=>`${r}:${i.mtimeMs}`)))).filter(r=>r.status==="fulfilled").map(r=>r.value);try{let{getMemoryContextHash:r}=nn(),i=r();i&&n.push(`memory:${i}`)}catch{}try{let r=e.join(process.cwd(),".nex","brain");if($a.existsSync(r)){let i=await t.stat(r);n.push(`brain:${i.mtimeMs}`)}}catch{}return n.join("|")}catch{return`fallback:${Date.now()}`}}function gf(){js=null,pa=null,zn=null}var X0=new Set(["spawn_agents"]),ca=5,la=3,tr=2,J0=parseInt(process.env.NEX_STALE_WARN_MS||"60000",10),cf=parseInt(process.env.NEX_STALE_ABORT_MS||"120000",10),V0=process.env.NEX_STALE_AUTO_SWITCH!=="0";function Q0(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{}}g0(t=>{m0(t,"allow"),h0(),console.log(`${w.green} \u2713 ${t}: always allow${w.reset}`)});async function Z0(t){let e=t.function.name,s=t0(t.function.arguments),o=t.id||`cli-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!s){let l=We().find(d=>d.function.name===e),u=l?JSON.stringify(l.function.parameters,null,2):"unknown";return console.log(`${w.yellow} \u26A0 ${e}: malformed arguments, sending schema hint${w.reset}`),{callId:o,fnName:e,args:null,canExecute:!1,errorResult:{role:"tool",content:`ERROR: Malformed tool arguments. Could not parse your arguments as JSON.
|
|
501
539
|
Raw input: ${typeof t.function.arguments=="string"?t.function.arguments.substring(0,200):"N/A"}
|
|
502
540
|
|
|
503
541
|
Expected JSON schema for "${e}":
|
|
504
542
|
${u}
|
|
505
543
|
|
|
506
|
-
Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:o}}}let n=
|
|
507
|
-
`)[0]}${
|
|
544
|
+
Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:o}}}let n=O0(e,s);if(!n.valid)return console.log(`${w.yellow} \u26A0 ${e}: ${n.error.split(`
|
|
545
|
+
`)[0]}${w.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(`${w.dim} \u2713 ${e}: corrected args (${u.join(", ")})${w.reset}`)}if(qs()&&!ff.has(e))return console.log(`${w.yellow} \u2717 ${e}: blocked in plan mode${w.reset}`),{callId:o,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`PLAN MODE: '${e}' is blocked. Only read-only tools are allowed. Present your plan as text output instead of making changes.`,tool_call_id:o}};let i=p0(e);if(i==="deny")return console.log(`${w.red} \u2717 ${e}: denied by permissions${w.reset}`),{callId:o,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`DENIED: Tool '${e}' is blocked by permissions`,tool_call_id:o}};if(i==="ask"){let c=` Allow ${e}?`;return e==="bash"&&r.command&&(c=` bash: \`${r.command.substring(0,80)}${r.command.length>80?"\u2026":""}\`?`),await df(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 eb(t,e,s={}){let o=await C0(t,e);if(o!==null)return o;let n=await S0(t,e);return n!==null?n:n0(t,e,s)}function tb(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 ua(t,e=!1){e||console.log(Vw(t.fnName,t.args));let s=sf("pre-tool",{tool_name:t.fnName});if(!e&&s.length>0)for(let p of s)p.success?console.log(`${w.dim} [hook pre-tool] ${p.command} \u2192 ${p.output||"ok"}${w.reset}`):console.log(`${w.yellow} [hook pre-tool] ${p.command} \u2192 ERROR: ${p.error}${w.reset}`);Mt?.onToolStart&&Mt.onToolStart(t.fnName,t.args);let o=await eb(t.fnName,t.args,{silent:!0,autoConfirm:t.confirmedByUser===!0}),n=String(o??""),r=n.length>5e4?n.substring(0,5e4)+`
|
|
508
546
|
...(truncated ${n.length-5e4} chars)`:n,i=r.split(`
|
|
509
|
-
`)[0],c=i.startsWith("ERROR")||i.includes("CANCELLED")||i.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(r)&&/✗ Agent/.test(r),l=
|
|
510
|
-
`)}function
|
|
547
|
+
`)[0],c=i.startsWith("ERROR")||i.includes("CANCELLED")||i.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(r)&&/✗ Agent/.test(r),l=uf(t.fnName,t.args,r,c);e||console.log(l),Mt?.onToolEnd&&Mt.onToolEnd(t.fnName,l,!c);let u=sf("post-tool",{tool_name:t.fnName});if(!e&&u.length>0)for(let p of u)p.success?console.log(`${w.dim} [hook post-tool] ${p.command} \u2192 ${p.output||"ok"}${w.reset}`):console.log(`${w.yellow} [hook post-tool] ${p.command} \u2192 ERROR: ${p.error}${w.reset}`);return{msg:{role:"tool",content:Y0(r,t.fnName),tool_call_id:t.callId},summary:l}}async function nb(t,e=!1,s={}){let o=new Array(t.length),n=[],r=[],i=null;if(e&&!s.skipSpinner){let l=t.filter(u=>u.canExecute);if(l.length>0){let u;if(l.length===1){let d=l[0],f=tb(d.fnName,d.args);u=`\u25CF ${d.fnName}${f?`(${f})`:""}`}else{let d=l.map(f=>f.fnName).join(", ");u=`\u25CF ${l.length} tools: ${d.length>60?d.substring(0,57)+"\u2026":d}`}i=new Kn(u),i.start()}}async function c(){if(r.length!==0){if(r.length===1){let l=r[0],{msg:u,summary:d}=await ua(t[l],e);o[l]=u,n.push(d)}else{let l=r.map(d=>ua(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(uf(u.fnName,u.args||{},u.errorResult.content,!0));continue}if(X0.has(u.fnName)){await c(),u.fnName==="spawn_agents"&&i&&(i.stop(),i=null);let{msg:d,summary:f}=await ua(u,e);o[l]=d,n.push(f)}else r.push(l)}if(await c(),i&&i.stop(),e&&n.length>0&&!s.skipSummaries)for(let l of n)console.log(l);return{results:o,summaries:n}}var X=[],lf=300,$f=new Map,yf=new Map,ma=new Map,ha=new Map,wf=new Map,Xn=new Map,Jn=new Map,Rt=0,Ds=0,or=0,ga="",rr=0,Vn=!1;function Gn(t,e){t===ga?(rr++,process.stdout.write(`\x1B[1A\x1B[2K${e} \u26A0 ${t} (\xD7${rr})${w.reset}
|
|
548
|
+
`)):(ga=t,rr=1,console.log(`${e} \u26A0 ${t}${w.reset}`))}var ir=[];function sb(t){ir.push(t.trim())}function ob(){return ir.length===0?null:ir.splice(0,ir.length).join(`
|
|
549
|
+
`)}function rb(){let t=process.env.NEX_LANGUAGE,e=process.env.NEX_CODE_LANGUAGE,s=process.env.NEX_COMMIT_LANGUAGE,o=!t||t==="auto"?null:t,n=[`# Language Rules (CRITICAL \u2014 enforce strictly)
|
|
511
550
|
`];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||"English";n.push(`CODE LANGUAGE: Write all code comments, docstrings, variable descriptions, and inline documentation in ${r}.`);let i=s||"English";return n.push(`COMMIT MESSAGES: Write all git commit messages in ${i}.`),o&&n.push(`
|
|
512
551
|
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(`
|
|
513
552
|
`)+`
|
|
514
553
|
|
|
515
|
-
`}function
|
|
554
|
+
`}function ib(){if(zn!==null)return zn;try{let e=M0().flatMap(n=>n.models.map(r=>({spec:`${n.name}:${r.id}`,tier:N0(r.id,n.name),name:r.name})));if(e.length<2)return zn="","";let s={full:"complex tasks (refactor, implement, generate)",standard:"regular tasks (edit, fix, analyze)",essential:"simple tasks (read, search, list)"},o=`
|
|
516
555
|
# Sub-Agent Model Routing
|
|
517
556
|
|
|
518
557
|
`;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 |
|
|
519
558
|
|---|---|---|
|
|
520
559
|
`;for(let n of e)o+=`| ${n.spec} | ${n.tier} | ${s[n.tier]||n.tier} |
|
|
521
|
-
`;return
|
|
560
|
+
`;return zn=o,o}catch(t){return process.env.NEX_DEBUG&&console.error("[agent] model routing guide failed:",t.message),zn="",""}}async function bf(){let t=await hf();if(js!==null&&t===pa)return js;let e=await s0(process.cwd()),s=d0(),o=T0(),n=qs()?y0():"",r=rb(),i=f0();return js=`You are Nex Code, an expert coding assistant. You help with programming tasks by reading, writing, and editing files, running commands, and answering questions.
|
|
522
561
|
|
|
523
562
|
WORKING DIRECTORY: ${process.cwd()}
|
|
524
563
|
All relative paths resolve from this directory.
|
|
@@ -534,7 +573,28 @@ ${n}
|
|
|
534
573
|
${r?`${r}
|
|
535
574
|
`:""}${i?`${i}
|
|
536
575
|
|
|
537
|
-
`:""}
|
|
576
|
+
`:""}${$0()?`# YOLO Mode \u2014 Auto-Execute
|
|
577
|
+
|
|
578
|
+
You are in YOLO mode (autoConfirm=true). All tool calls are pre-approved.
|
|
579
|
+
- NEVER ask for confirmation \u2014 just execute tasks directly
|
|
580
|
+
- NEVER end responses with questions like "Soll ich...?", "M\xF6chtest du...?", "Shall I...?"
|
|
581
|
+
- When you have enough information, implement the fix immediately \u2014 do not propose or ask
|
|
582
|
+
- If something is ambiguous, make a reasonable assumption and state it, then proceed
|
|
583
|
+
- OVERRIDE "simple questions": If the user pastes any server error or Jarvis message, SSH investigate FIRST \u2014 NEVER answer from training knowledge alone
|
|
584
|
+
- After identifying root cause via SSH: IMMEDIATELY fix it (edit file + restart service). Do NOT write "Empfohlene L\xF6sungen" or ask "M\xF6chten Sie...?" \u2014 just execute the fix now.
|
|
585
|
+
|
|
586
|
+
`:""}# Jarvis Debugging Rules
|
|
587
|
+
|
|
588
|
+
- Jarvis errors (set_reminder, cron, Google Auth, SmartThings) come from the DEPLOYED server at 94.130.37.43
|
|
589
|
+
- ALWAYS use ssh_exec to investigate: ssh_exec on 94.130.37.43, check /home/jarvis/jarvis-agent/logs/
|
|
590
|
+
- NEVER run local bash/find/sqlite3 commands when debugging Jarvis issues
|
|
591
|
+
- Local jarvis-agent/ is just source code \u2014 the running system is on the server
|
|
592
|
+
- CRITICAL: When the user pastes a Jarvis error message ("jarvisFehler:", "jarvisEinige Fehler", error logs), this is NEVER a "simple question" to answer from training knowledge. You MUST ssh_exec to verify if the error is still occurring BEFORE writing any explanation. Do NOT explain from memory \u2014 investigate first, always.
|
|
593
|
+
- LOG FILES: Always check the CURRENT log first: /home/jarvis/jarvis-agent/logs/api-error.log (no date suffix). Log files WITH a date suffix (e.g. api-error.log-20260322) are ROTATED/OLD \u2014 errors there may already be fixed. Only look at dated logs if the current log is empty or the error is absent from the current log.
|
|
594
|
+
- FIX WORKFLOW (YOLO): Once you identify a fixable bug via SSH investigation: (1) edit the file on server using ssh_exec with tee or sed -i (NOT sed -n), (2) restart the affected service with systemctl restart, (3) verify with tail logs. Do NOT produce a report \u2014 execute the fix.
|
|
595
|
+
- READING REMOTE FILES: NEVER use sed -n (always blocked). To read a specific function in a remote file: ssh_exec 'grep -n "functionName" /path/file -A 50'. To read the whole file: ssh_exec 'cat /path/file'. These are the only two options.
|
|
596
|
+
|
|
597
|
+
# Core Behavior
|
|
538
598
|
|
|
539
599
|
- You can use tools OR respond with text. For simple questions, answer directly.
|
|
540
600
|
- For coding tasks, use tools to read files, make changes, run tests, etc.
|
|
@@ -610,8 +670,12 @@ When performing audits, code reviews, bug hunts, or security reviews:
|
|
|
610
670
|
"Imported by \`main.js:42\`, reading \`utils/parse.js\` to trace the call..."
|
|
611
671
|
This helps the user follow your investigation chain without seeing raw tool output.
|
|
612
672
|
|
|
613
|
-
**2. Selective reading \u2014
|
|
614
|
-
|
|
673
|
+
**2. Selective reading \u2014 MANDATORY for large files:**
|
|
674
|
+
read_file automatically truncates at 350 lines for unbounded reads. To read a large file:
|
|
675
|
+
- First scan the top: line_start=1 line_end=80 to see structure/exports
|
|
676
|
+
- Then read only the section you need (e.g. last 100 lines: line_start=950 line_end=1049)
|
|
677
|
+
- NEVER call read_file without line_start/line_end on a file you know has >350 lines
|
|
678
|
+
- A file showing "showing lines 1-350 of 1049" means 699 lines are hidden \u2014 use line ranges to reach them
|
|
615
679
|
|
|
616
680
|
**3. Audit summary table \u2014 end every audit with a findings table:**
|
|
617
681
|
After completing an audit, code review, or bug hunt, ALWAYS append a Markdown table summarizing results:
|
|
@@ -722,7 +786,7 @@ This applies to bash output, SSH output, grep results, and all other tool output
|
|
|
722
786
|
- Good for: reading multiple files, analyzing separate modules.
|
|
723
787
|
- Bad for: tasks that depend on each other or modify the same file.
|
|
724
788
|
- Max 5 parallel agents.
|
|
725
|
-
${
|
|
789
|
+
${ib()}
|
|
726
790
|
|
|
727
791
|
# Edit Reliability (Critical)
|
|
728
792
|
|
|
@@ -738,7 +802,7 @@ ${k0()}
|
|
|
738
802
|
# Error Recovery
|
|
739
803
|
|
|
740
804
|
When a tool call returns ERROR:
|
|
741
|
-
- edit_file/patch_file "old_text not found":
|
|
805
|
+
- edit_file/patch_file "old_text not found": Use the line number from the error ("Most similar text (line N)") to re-read with line_start=N-5 line_end=N+15 to see the actual content. Then retry the edit with exact text from that targeted read. Do NOT re-read the full file.
|
|
742
806
|
- bash non-zero exit: Read the error output. Fix the root cause (missing dependency, wrong path, syntax error) rather than retrying the same command.
|
|
743
807
|
- "File not found": Use glob or list_directory to find the correct path. Do not guess.
|
|
744
808
|
- After 2 failed attempts at the same operation, stop and explain the issue to the user.
|
|
@@ -773,54 +837,74 @@ You have access to a persistent knowledge base in .nex/brain/.
|
|
|
773
837
|
- Include tags in frontmatter for better retrieval
|
|
774
838
|
- The user reviews all brain writes via /brain review or git diff
|
|
775
839
|
|
|
776
|
-
`,
|
|
777
|
-
`):[]).filter(f=>{let
|
|
778
|
-
\u{1F4E6} ${h}${
|
|
779
|
-
${
|
|
780
|
-
`),
|
|
781
|
-
`+
|
|
782
|
-
`)}catch(
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
`)
|
|
786
|
-
`)
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
840
|
+
`,pa=t,js}function ab(){X=[],$f.clear(),yf.clear(),ma.clear(),ha.clear(),wf.clear(),Xn.clear(),Jn.clear(),Rt=0,Ds=0,or=0,Vn=!1,ga="",rr=0}function cb(){X.length>lf&&X.splice(0,X.length-lf)}function lb(){return X.length}function ub(){return X}function db(t){X=t}async function fb(){let{execFile:t}=require("child_process"),e=require("fs"),s=process.cwd(),o=(f,p)=>new Promise(h=>{t(f,p,{cwd:s,timeout:3e3},(m,g)=>{h(m?"":(g||"").trim())})}),[n]=await Promise.all([o("find",[".","-type","f","-not","-path","*/node_modules/*","-not","-path","*/.git/*","-not","-path","*/dist/*","-not","-path","*/.next/*","-not","-path","*/build/*","-not","-path","*/__pycache__/*","-not","-path","*/vendor/*"])]),r=new Set(["js","ts","jsx","tsx","py","go","rs","rb","java","cpp","c","cs"]),i=(n?n.split(`
|
|
841
|
+
`):[]).filter(f=>{let p=f.split(".").pop();return r.has(p)});if(i.length<3)return null;let c={};for(let f of i){let p=f.split(".").pop();c[p]=(c[p]||0)+1}let u=` \u{1F4C1} ${Object.entries(c).sort((f,p)=>p[1]-f[1]).slice(0,4).map(([f,p])=>`${p} .${f}`).join(" \xB7 ")}`,d=ya.join(s,"package.json");if(e.existsSync(d))try{let f=JSON.parse(e.readFileSync(d,"utf-8")),p=Object.keys({...f.dependencies||{},...f.devDependencies||{}});if(p.length>0){let h=p.slice(0,5).join(" \xB7 "),m=p.length>5?` +${p.length-5}`:"";u+=`
|
|
842
|
+
\u{1F4E6} ${h}${m}`}}catch{}return u}function pb(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 Le(t,e,s,o,n,{suppressHint:r=!1}={}){if(t<1)return;let i=[...e.values()].reduce((u,d)=>u+d,0),c=`\u2500\u2500 ${t} ${t===1?"step":"steps"} \xB7 ${i} ${i===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(`
|
|
843
|
+
${w.dim} ${c}${w.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`;pb(u)}s.size>0?console.log(`${w.dim} \u{1F4A1} /diff \xB7 /commit \xB7 /undo${w.reset}`):!r&&o.size>=5&&s.size===0&&t>=3?console.log(`${w.dim} \u{1F4A1} Found issues? Say "fix 1" or "apply all fixes"${w.reset}`):o.size>0&&t>=2&&console.log(`${w.dim} \u{1F4A1} /save \xB7 /clear${w.reset}`)}async function mb(){if(!process.stdout.isTTY)return{action:"quit"};let t=Ls(),e=Yn(),s=ar.fast?.[t],o=ar.strong?.[t],n=s&&s!==e,r=o&&o!==e&&o!==s,i=[];i.push({key:"r",label:`Retry with current model ${w.dim}(${e})${w.reset}`}),n&&i.push({key:"f",label:`Switch to ${w.bold}${s}${w.reset} ${w.dim}\u2014 fast, low latency${w.reset}`,model:s}),r&&i.push({key:"s",label:`Switch to ${w.bold}${o}${w.reset} ${w.dim}\u2014 reliable tool-calling, medium speed${w.reset}`,model:o}),i.push({key:"q",label:`${w.dim}Quit${w.reset}`}),console.log(),console.log(`${w.yellow} Stream stale \u2014 all retries exhausted.${w.reset} What would you like to do?`);for(let c of i)console.log(` ${w.cyan}[${c.key}]${w.reset} ${c.label}`);return process.stdout.write(` ${w.yellow}> ${w.reset}`),new Promise(c=>{let l=process.stdin,u=l.isRaw;l.setRawMode(!0),l.resume(),l.setEncoding("utf8");let d=!1,f=p=>{if(d)return;d=!0,l.removeListener("data",f),l.setRawMode(u||!1),l.pause();let h=p.toLowerCase().trim();if(process.stdout.write(`${h}
|
|
844
|
+
`),p==="")return c({action:"quit"});let m=i.find(g=>g.key===h);!m||m.key==="q"||!m.model&&m.key!=="r"?c({action:"quit"}):m.key==="r"?c({action:"retry"}):c({action:"switch",model:m.model,provider:t})};l.on("data",f)})}var Mt=null;async function hb(t,e=null){Mt=e;let s=pf(t);X.push({role:"user",content:s}),cb();let{setOnChange:o}=Po(),n=null,r=0;o((Fe,Ce)=>{Fe==="create"?(n&&n.stop(),n=new Jw(Ce.name,Ce.tasks),n.setStats({tokens:r}),n.start()):Fe==="update"&&n?n.updateTask(Ce.id,Ce.status):Fe==="clear"&&n&&(n.stop(),n=null)});let i=await bf(),c=i;try{let{getBrainContext:Fe}=vs(),Ce=await Fe(t);Ce&&(c=i+`
|
|
845
|
+
`+Ce+`
|
|
846
|
+
`)}catch(Fe){process.env.NEX_DEBUG&&console.error("[agent] brain context failed:",Fe.message)}let l=[{role:"system",content:c},...X],u=new Kn("Thinking...");u.start();let f=X.length===1?fb().catch(()=>null):Promise.resolve(null),p=We(),[{messages:h,compressed:m,compacted:g,tokensRemoved:$},y]=await Promise.all([o0(l,p),f]),x=Tt(l,p);if(u.stop(),y&&console.log(`${w.dim}${y}${w.reset}`),g)console.log(`${w.dim} [context compacted \u2014 summary (~${$} tokens freed)]${w.reset}`);else if(m){let Fe=x.limit>0?Math.round($/x.limit*100):0;console.log(`${w.dim} [context compressed \u2014 ~${$} tokens freed (${Fe}%)]${w.reset}`)}x.percentage>85&&console.log(`${w.yellow} \u26A0 Context ${Math.round(x.percentage)}% used (${Math.round(100-x.percentage)}% remaining) \u2014 consider /clear or /save + start fresh${w.reset}`);let _=h;if(Tt(_,We()).percentage>=65){let{messages:Ce,tokensRemoved:ht}=Nt(_,We());ht>0&&(_=Ce,console.log(`${w.dim} [pre-flight compress \u2014 ${ht} tokens freed, now ${Math.round(Tt(_,We()).percentage)}% used]${w.reset}`))}let v=0,b=0,k=0,R=0,O=0,P=9,F=0,De=(()=>{let Fe=X.find(Ce=>Ce.role==="user");return typeof Fe?.content=="string"?Fe.content:""})(),me=/set_reminder|google.?auth|cron:|api\.log|jarvis.{0,30}(fehler|error|fail|broken|crash|nicht.{0,10}(funktioniert|läuft)|debug)|(?:fehler|error|crash|broken).{0,30}jarvis/i.test(De),A=0,M=0,D=new Map,W=new Set,Q=new Set,ne=Date.now(),qe=new Zw(P0),Re=wf,le=2,pt=4,U=$f,K=5,te=8,se=yf,Z=4,ie=7,oe=ma,ue=3,ce=5,Oe=ha,Je=2,xt=3,Be=0,ss=6,Ap=10,Xs=0,Op=5,on=0,Np=2,Mp=3,kr=0,vr=8,Pp=12,mt,Js=fa,Sr=0,Ka=3,Er=!1;e:for(;;){for(Er=!1,mt=0;mt<Js&&!nr()?.aborted;mt++){{let T=We(),C=Tt(_,T),z=M===0?65:78;if(C.percentage>=z){let{messages:j,tokensRemoved:J}=Nt(_,T,M===0);J>0&&(_=j,J>50&&console.log(`${w.dim} [auto-compressed \u2014 ~${J} tokens freed, now ${Math.round(Tt(_,T).percentage)}%]${w.reset}`))}}let Ce=!0;M>0&&x0();let ht=null;if(n&&n.isActive())n._paused&&n.resume();else if(!n){let T,C=k0();if(C&&C.total>1){let z=C.description.length>40?C.description.slice(0,37)+"\u2026":C.description;T=`Plan step ${C.current}/${C.total}: ${z}`}else T=M>0?`Thinking... (step ${M+1})`:"Thinking...";ht=new Kn(T),ht.start()}let Tr=!0,Ht="",Rr=!1,rt=new v0,Gt,Cr=Date.now(),Vs=!1,Ar=new AbortController,Ya=setInterval(()=>{let T=Date.now()-Cr;if(T>=cf)rt._clearCursorLine(),console.log(`${w.yellow} \u26A0 Stream stale for ${Math.round(T/1e3)}s \u2014 aborting and retrying${w.reset}`),Ar.abort();else if(T>=J0&&!Vs){Vs=!0,rt._clearCursorLine();let C=ar.fast?.[Ls()],z=k>0?` (retry ${k+1}/${tr})`:"",j=Math.round((cf-T)/1e3);console.log(`${w.yellow} \u26A0 No tokens received for ${Math.round(T/1e3)}s \u2014 waiting...${z}${w.reset}`),C&&C!==Yn()?console.log(`${w.dim} \u{1F4A1} Will auto-switch to ${C} in ~${j}s if no tokens arrive${w.reset}`):console.log(`${w.dim} \u{1F4A1} Ctrl+C to abort \xB7 auto-abort in ~${j}s${w.reset}`)}},5e3),gt="",Pt=null;try{let T=mf(We()),C=qs()?T.filter(J=>ff.has(J.function.name)):T,z=nr(),j=new AbortController;z&&z.addEventListener("abort",()=>j.abort(),{once:!0}),Ar.signal.addEventListener("abort",()=>j.abort(),{once:!0}),Gt=await e0(_,C,{signal:j.signal,onThinkingToken:()=>{Cr=Date.now(),Vs=!1,Mt?.onThinkingToken&&Mt.onThinkingToken()},onToken:J=>{if(Cr=Date.now(),Vs=!1,Mt?.onToken){Mt.onToken(J),Ht+=J;return}if(Ht+=J,!Rr&&Ht.length>400&&Ht.length%250<J.length+1){let re=da(Ht,3);re.truncated&&(Rr=!0,rt._clearCursorLine?.(),console.log(`${w.yellow} \u26A0 LLM stream loop detected (${re.repeatCount}\xD7 repeated) \u2014 suppressing display${w.reset}`))}Rr||(gt+=J,process.stdout.isTTY?Pt||(Pt=setTimeout(()=>{gt&&rt&&rt.push(gt),gt="",Pt=null},50)):(rt.push(gt),gt=""),Tr&&(n&&!n._paused?n.pause():ht&&ht.stop(),Ce||(Ce=!0),rt.startCursor(),Tr=!1))}})}catch(T){if(clearInterval(Ya),Pt&&(clearTimeout(Pt),Pt=null),gt&&rt&&(rt.push(gt),gt=""),n&&!n._paused&&n.pause(),ht&&ht.stop(),rt.stopCursor(),Ar.signal.aborted&&!nr()?.aborted){if(k++,k>tr){if(R<1){R++,Gn("Stale retries exhausted \u2014 last-resort force-compress...",w.yellow);let q=We(),{messages:Y,tokensRemoved:ee}=Nt(_,q);_=Y,ee>50&&console.log(`${w.dim} [force-compressed \u2014 ~${ee} tokens freed]${w.reset}`),k=0,mt--;continue}n&&(n.stop(),n=null);let re=await mb();if(re.action==="quit"){o(null),Le(M,D,W,Q,ne),Ie(X);break}re.action==="switch"&&(rf(`${re.provider}:${re.model}`),console.log(`${w.green} \u2713 Switched to ${re.provider}:${re.model}${w.reset}`)),k=0,mt--;continue}let j=k===1?3e3:5e3;if(k>=1&&F<1){F++,Gn(`Stale retry ${k}/${tr} \u2014 force-compressing before retry...`,w.yellow);let re=We(),{messages:q,tokensRemoved:Y}=Nt(_,re,!0);if(_=q,Y>0&&Y>50&&console.log(`${w.dim} [force-compressed \u2014 ~${Y} tokens freed]${w.reset}`),V0){let ee=ar.fast?.[Ls()];ee&&ee!==Yn()&&(rf(`${Ls()}:${ee}`),console.log(`${w.cyan} \u26A1 Auto-switched to ${ee} to avoid further stale timeouts${w.reset}`),console.log(`${w.dim} (disable with NEX_STALE_AUTO_SWITCH=0)${w.reset}`))}}else console.log(`${w.yellow} \u26A0 Stale retry ${k}/${tr} \u2014 retrying in ${j/1e3}s...${w.reset}`);let J=new Kn(`Waiting ${j/1e3}s before retry...`);J.start(),await new Promise(re=>setTimeout(re,j)),J.stop(),mt--;continue}if(T.name==="AbortError"||T.name==="CanceledError"||T.message?.includes("canceled")||T.message?.includes("aborted")){n&&(n.stop(),n=null),o(null),Le(M,D,W,Q,ne),Ie(X);break}let C=T.message;if(T.code==="ECONNREFUSED"||T.message.includes("ECONNREFUSED"))C="Connection refused \u2014 please check your internet connection or API endpoint";else if(T.code==="ENOTFOUND"||T.message.includes("ENOTFOUND"))C="Network error \u2014 could not reach the API server. Please check your connection";else if(T.code==="ETIMEDOUT"||T.message.includes("timeout"))C="Request timed out \u2014 the API server took too long to respond. Please try again";else if(T.message.includes("401")||T.message.includes("Unauthorized"))C="Authentication failed \u2014 please check your API key in the .env file";else if(T.message.includes("403")||T.message.includes("Forbidden"))C="Access denied \u2014 your API key may not have permission for this model";else if(T.message.includes("404")){C=`Model not found (404): ${Yn?Yn():"unknown"} \u2014 check your .env MODEL setting or run /models to list available models`,console.log(`${w.red} \u2717 ${C}${w.reset}`),n&&(n.stop(),n=null),o(null),Le(M,D,W,Q,ne),Ie(X);break}else if(T.message.includes("400")){if(R<3&&O<P){R++,O++;let j=M===0&&R===1,J=j||R===3||F>0;j?(R=3,Gn("Bad request (400) \u2014 system prompt too large, compressing...",w.yellow)):Gn(J?`Bad request (400) \u2014 nuclear compression (attempt ${R}/3, dropping history)...`:`Bad request (400) \u2014 force-compressing and retrying... (attempt ${R}/3)`,w.yellow);let re=We(),{messages:q,tokensRemoved:Y}=Nt(_,re,J);_=q,Y>50&&console.log(`${w.dim} [force-compressed \u2014 ~${Y} tokens freed]${w.reset}`),mt--;continue}{let j=_.find(_e=>_e.role==="system"),J=_.find(_e=>_e.role==="user"&&!String(_e.content).startsWith("[SYSTEM")&&!String(_e.content).startsWith("BLOCKED:")),re=[j,J].filter(Boolean),{getUsage:q}=He(),Y=He().estimateMessagesTokens(re),ee=He().estimateMessagesTokens(_);if(Y<ee){let _e=[],it=X.filter(ae=>ae.role==="assistant"&&typeof ae.content=="string"&&ae.content.trim().length>30).slice(-3).map(ae=>ae.content.trim().slice(0,120).replace(/\n+/g," "));it.length>0&&_e.push(`Key findings:
|
|
847
|
+
`+it.map(ae=>`- ${ae}`).join(`
|
|
848
|
+
`));let rs=X.filter(ae=>ae.role==="tool"&&typeof ae.content=="string"&&!ae.content.startsWith("BLOCKED:")&&ae.content.trim().length>10).slice(-3).map(ae=>ae.content.trim().split(`
|
|
849
|
+
`).slice(0,3).join(`
|
|
850
|
+
`).slice(0,200));if(rs.length>0&&_e.push(`Tool results summary:
|
|
851
|
+
`+rs.map(ae=>`- ${ae}`).join(`
|
|
852
|
+
`)),W.size>0){let ae=[...W].map(Kt=>Kt.split("/").slice(-2).join("/")).join(", ");_e.unshift(`Already modified: ${ae} \u2014 use edit_file to add missing pieces only, DO NOT use write_file on these files.`)}if(_e.length>0){let ae={role:"user",content:`[SYSTEM: Findings from investigation before context wipe]
|
|
853
|
+
${_e.join(`
|
|
854
|
+
`)}
|
|
855
|
+
Continue implementing the fixes based on these findings.`};re.push(ae)}if(Ds>=3){let ae=W.size>0?`
|
|
856
|
+
Files modified so far: ${[...W].map(Kt=>Kt.split("/").slice(-1)[0]).join(", ")}`:"";console.log(`${w.red} \u2717 Super-nuclear limit reached (3\xD7) \u2014 aborting to prevent runaway context loop${w.reset}`),console.log(`${w.yellow} \u{1F4A1} Task may exceed model context. Try /clear and break it into smaller steps.${ae?w.dim+ae:""}${w.reset}`),n&&(n.stop(),n=null),o(null),Le(M,D,W,Q,ne,{suppressHint:!0}),Ie(X);break}if(_=re,Ds++,Rt=0,A=0,ha.clear(),Xn.clear(),Jn.clear(),ma.clear(),Gn(`Super-nuclear compression \u2014 dropped all history, keeping original task only (${ee-Y} tokens freed)`,w.yellow),Ds>=1){let ae={role:"user",content:`[SYSTEM WARNING] Context wiped ${Ds}\xD7. SKIP investigation \u2014 implement directly using findings above. Max 5 tool calls total, then finish.
|
|
857
|
+
|
|
858
|
+
CRITICAL: If you must re-read a file, use line_start/line_end to read ONLY the section you need (e.g. last 50 lines). Never read a full large file again \u2014 that is what caused the context overflow.`};X.push(ae),_.push(ae)}R=0,mt--;continue}}C="Context too large to compress \u2014 use /clear to start fresh"}else T.message.includes("500")||T.message.includes("502")||T.message.includes("503")||T.message.includes("504")?C="API server error \u2014 the provider is experiencing issues. Please try again in a moment":(T.message.includes("fetch failed")||T.message.includes("fetch"))&&(C="Network request failed \u2014 please check your internet connection");if(console.log(`${w.red} \u2717 ${C}${w.reset}`),T.message.includes("429")){if(v++,v>ca){console.log(`${w.red} Rate limit: max retries (${ca}) exceeded. Try again later or use /budget to check your limits.${w.reset}`),n&&(n.stop(),n=null),o(null),Le(M,D,W,Q,ne),Ie(X);break}let j=Math.min(1e4*Math.pow(2,v-1),12e4),J=new Kn(`Rate limit \u2014 waiting ${Math.round(j/1e3)}s (retry ${v}/${ca})`);J.start(),await new Promise(re=>setTimeout(re,j)),J.stop();continue}if(T.message.includes("socket disconnected")||T.message.includes("TLS")||T.message.includes("ECONNRESET")||T.message.includes("ECONNABORTED")||T.message.includes("ETIMEDOUT")||T.code==="ECONNRESET"||T.code==="ECONNABORTED"){if(b++,b>la){console.log(`${w.red} Network error: max retries (${la}) exceeded. Check your connection and try again.${w.reset}`),n&&(n.stop(),n=null),o(null),Le(M,D,W,Q,ne),Ie(X);break}let j=Math.min(2e3*Math.pow(2,b-1),3e4),J=new Kn(`Network error \u2014 retrying in ${Math.round(j/1e3)}s (${b}/${la})`);J.start(),await new Promise(re=>setTimeout(re,j)),J.stop(),mt--;continue}n&&(n.stop(),n=null),o(null),Le(M,D,W,Q,ne),Ie(X);break}clearInterval(Ya),v=0,b=0,Tr&&(n&&!n._paused&&n.pause(),ht&&ht.stop()),Pt&&(clearTimeout(Pt),Pt=null),gt&&rt&&(rt.push(gt),gt=""),Ht&&rt.flush(),b=0,k=0,Gt&&Gt.usage&&(A0(Ls(),Yn(),Gt.usage.prompt_tokens||0,Gt.usage.completion_tokens||0),r+=(Gt.usage.prompt_tokens||0)+(Gt.usage.completion_tokens||0),n&&n.setStats({tokens:r}));let{content:za,tool_calls:rn}=Gt,Qs=da(za||""),Xa=Qs.truncated?Qs.text:za;Qs.truncated&&console.log(`${w.yellow} \u26A0 LLM output loop detected (${Qs.repeatCount}\xD7 repeated paragraph) \u2014 response truncated${w.reset}`);let Zs=D0(Xa||""),eo=Zs.truncated?Zs.text:Xa;Zs.truncated&&console.log(`${w.yellow} \u26A0 LLM output loop detected (${Zs.repeatCount}\xD7 repeated window) \u2014 response truncated${w.reset}`);let Or={role:"assistant",content:eo||""};if(rn&&rn.length>0&&(Or.tool_calls=rn),X.push(Or),_.push(Or),!rn||rn.length===0){let T=(eo||"").trim().length>0||Ht.trim().length>0,C=!1;if(Vn&&T&&(Vn=!1,Rt=0,C=!0),C&&T){let z=(eo||"").trim();if(z.endsWith("?")||/\b(Wo |Bitte |Kannst du|Soll ich)\b/.test(z.slice(-200))){let J={role:"user",content:"[SYSTEM] Continue. Do not ask questions \u2014 implement the fix yourself using SSH. The server is at 94.130.37.43."};_.push(J),X.push(J);continue}}if(!T&&M>0&&mt<fa-1){let z={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."};_.push(z),X.push(z);continue}if(qs()&&T&&M===0)if(or++,or>2)console.log(`${w.yellow} \u26A0 Plan accepted despite no file reads (rejection loop cap reached)${w.reset}`);else{let z={role:"user",content:`[SYSTEM] You wrote a plan without reading any files. This plan may be based on incorrect assumptions (wrong database type, wrong file structure, etc.).
|
|
859
|
+
|
|
860
|
+
MANDATORY: Use read_file, glob, or grep to investigate the actual codebase first. Read at least the relevant module file and route file before writing the plan.`};X.push(z),_.push(z),console.log(`${w.yellow} \u26A0 Plan rejected (${or}/2): no files read \u2014 forcing investigation${w.reset}`);continue}if(qs()&&T){let z=(eo||Ht||"").trim();w0(z),Q0(z);let j=b0(z);if(j.length>0){let J=X.find(ee=>ee.role==="user"),re=typeof J?.content=="string"?J.content.slice(0,120):"Task";_0(re,j);let q=j.length===1?"step":"steps",Y=!1;if(process.stdout.isTTY&&process.stdin.isTTY){let{approvePlan:ee,startExecution:_e,setPlanMode:it}=Ft();process.stdout.write(`
|
|
861
|
+
${w.cyan}${w.bold}Plan ready${w.reset} ${w.dim}(${j.length} ${q})${w.reset} ${w.green}[A]${w.reset}${w.dim}pprove${w.reset} ${w.yellow}[E]${w.reset}${w.dim}dit${w.reset} ${w.red}[R]${w.reset}${w.dim}eject${w.reset} ${w.dim}[\u21B5 = approve]:${w.reset} `);let rs=process.stdin.isRaw,ae=await new Promise(Kt=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",Za=>{try{process.stdin.setRawMode(rs||!1)}catch{}let jp=Za.toString().toLowerCase()[0]||"\r";Kt(jp)})});if(process.stdout.write(`
|
|
862
|
+
`),ae==="r")console.log(`${w.red}Plan rejected.${w.reset} Ask follow-up questions to refine.`);else if(ae==="e")console.log(`${w.yellow}Type /plan edit to open in editor, or give feedback.${w.reset}`);else if(ee()){_e(),it(!1),gf(),console.log(`${w.green}${w.bold}Approved!${w.reset} Executing ${j.length} ${q}...`);let Kt=`[PLAN APPROVED \u2014 EXECUTE NOW]
|
|
863
|
+
|
|
864
|
+
Implement the following plan step by step. All tools are now available.
|
|
865
|
+
|
|
866
|
+
${z}`;X.push({role:"user",content:Kt}),_.push({role:"user",content:Kt}),Y=!0}}else console.log(`
|
|
867
|
+
${w.cyan}${w.bold}Plan ready${w.reset} ${w.dim}(${j.length} ${q} extracted).${w.reset} Type ${w.cyan}/plan approve${w.reset}${w.dim} to execute, or ${w.reset}${w.cyan}/plan edit${w.reset}${w.dim} to review.${w.reset}`);if(Y){n&&(n.stop(),n=null),mt--;continue}}else console.log(`
|
|
868
|
+
${w.cyan}${w.bold}Plan ready.${w.reset} ${w.dim}Type ${w.reset}${w.cyan}/plan approve${w.reset}${w.dim} to execute, or ask follow-up questions to refine.${w.reset}`)}n&&(n.stop(),n=null),o(null),Le(M,D,W,Q,ne),Ie(X),nf(X);return}M++,M>=1&&(Ce=!1);for(let T of rn){let C=T.function.name;D.set(C,(D.get(C)||0)+1)}let Ae=await Promise.all(rn.map(T=>Z0(T)));{let T=Tt(_,We()),C=T.percentage,z=Ae.some(q=>q.canExecute&&q.fnName==="read_file"&&!q.args?.line_end),j=Ae.filter(q=>q.canExecute&&q.fnName==="read_file"&&q.args?.path&&Oe.get(q.args.path)>=1&&!q.args?.line_start).map(q=>q.args.path.split("/").slice(-2).join("/")),J=j.length>0;if(C>=70&&z&&kr<70||C>=85&&kr<85||J){kr=C;let q=C>=85?"URGENT":"WARNING",Y;J?(q="WARNING",Y=`Unbounded re-read of ${j.join(", ")} \u2014 already in context. Use line_start/line_end to read specific sections instead.`):z?Y=`Unbounded read at ${Math.round(C)}% context \u2014 use line_start/line_end to avoid overflow.`:Y=`Context ${Math.round(C)}% used. Avoid large reads, wrap up with what you have.`;let ee={role:"user",content:`[SYSTEM ${q}] Context ${Math.round(C)}% used (${T.used}/${T.limit} tokens). ${Y}`};if(X.push(ee),_.push(ee),C>=85){let _e=J?` (re-read of: ${j.join(", ")})`:"";console.log(`${w.yellow} \u26A0 Context ${Math.round(C)}% used \u2014 agent warned to use targeted reads${_e}${w.reset}`)}}}for(let T of Ae){if(!T.canExecute||T.fnName!=="read_file")continue;let C=T.args?.path;if(!C)continue;let z=Oe.get(C)||0,j=T.args?.line_start!=null,J=Xn.get(C)===!0,re=6;if(z>=re){let q=C.split("/").slice(-2).join("/"),Y=(Jn.get(C)||0)+1;Jn.set(C,Y),Y===1&&console.log(`${w.red} \u2716 Blocked: "${q}" read ${z}\xD7 \u2014 hard cap (${re}) reached${w.reset}`),T.canExecute=!1,T.errorResult={role:"tool",content:`BLOCKED: read_file("${C}") denied \u2014 file already read ${z}\xD7 (hard cap: ${re}). You have seen enough of this file. Use grep to find specific content or proceed with what you know.`,tool_call_id:T.callId}}else if(z>=1&&j){if(J){let q=C.split("/").slice(-2).join("/");console.log(`${w.cyan} \u21A9 Targeted re-read: "${q}" (line_start=${T.args.line_start}) \u2014 edit recovery${w.reset}`),Xn.delete(C)}}else if(z>=1){let q=C.split("/").slice(-2).join("/"),Y=(Jn.get(C)||0)+1;Jn.set(C,Y),Y===1&&console.log(`${w.red} \u2716 Blocked unbounded re-read: "${q}" \u2014 already in context. Use line_start/line_end for specific sections.${w.reset}`),T.canExecute=!1,T.errorResult={role:"tool",content:`BLOCKED: read_file("${C}") denied \u2014 file already in context (read ${z}\xD7). Use line_start/line_end to read a specific section instead of the full file.`,tool_call_id:T.callId}}}for(let T of Ae)T.canExecute&&(T.fnName!=="ssh_exec"&&T.fnName!=="bash"||/\bsed\s+-n\b/.test(T.args?.command||"")&&(console.log(`${w.red} \u2716 Blocked sed -n: use grep -n "pattern" <file> | head -30 instead${w.reset}`),T.canExecute=!1,T.errorResult={role:"tool",content:'BLOCKED: sed -n is forbidden \u2014 it floods context with line ranges. Use grep -n "pattern" <file> | head -30 to read a specific section, or cat <file> for the full file.',tool_call_id:T.callId}));for(let T of Ae){if(!T.canExecute||T.fnName!=="write_file")continue;let C=T.args?.path,z=T.args?.content||"";if(C)try{let j=require("fs"),J=require("path").resolve(process.cwd(),C);if(j.existsSync(J)){let re=j.statSync(J).size,q=Buffer.byteLength(z,"utf8"),Y=re>0?q/re:1;if(Y<.6&&re>200){let ee=C.split("/").slice(-2).join("/");console.log(`${w.red} \u2716 write_file shrink guard: "${ee}" would shrink to ${Math.round(Y*100)}% of original \u2014 likely context loss${w.reset}`),T.canExecute=!1,T.errorResult={role:"tool",content:`BLOCKED: write_file("${C}") denied \u2014 new content is only ${Math.round(Y*100)}% of current file size (${re} \u2192 ${q} bytes). This looks like a partial rewrite after context loss. Use edit_file/patch_file to add only the new code, or read the file first to see full content before replacing.`,tool_call_id:T.callId}}}}catch{}}for(let T of Ae){if(!T.canExecute||T.fnName!=="grep")continue;let C=T.args?.path;if(!C)continue;let z=oe.get(C)||0;if(z>=ce){let j=C.split("/").slice(-2).join("/");console.log(`${w.red} \u2716 Blocked grep: "${j}" grepped ${z}\xD7 with different patterns \u2014 flood threshold exceeded${w.reset}`),T.canExecute=!1,T.errorResult={role:"tool",content:`BLOCKED: grep("${C}") denied \u2014 ${z} patterns already tried. Use existing results.`,tool_call_id:T.callId}}}if(Vn){let T=Ae.filter(j=>j.canExecute&&j.fnName==="ssh_exec"),C=Ae.some(j=>j.canExecute&&j.fnName!=="ssh_exec"),z=me&&A<3;if(T.length>0&&!C&&z)Vn=!1,Rt=Math.max(0,vr-2),console.log(`${w.dim} [dual-block deadlock: SSH storm relaxed \u2014 allowing SSH call]${w.reset}`);else for(let j of T)j.canExecute=!1,j.errorResult={role:"tool",content:`BLOCKED: ssh_exec denied \u2014 SSH storm (${vr}+ calls). Synthesize findings now.`,tool_call_id:j.callId}}if(me&&A<3){for(let T of Ae)if(T.canExecute&&["bash","read_file","find_files"].includes(T.fnName)){A++;{let C=We(),{messages:z}=Nt(_,C);_=z}console.log(`${w.yellow} \u26A0 Jarvis-local guard: blocking local ${T.fnName} \u2014 use ssh_exec on 94.130.37.43${w.reset}`),T.canExecute=!1,T.errorResult={role:"tool",content:`BLOCKED: ${T.fnName} denied \u2014 this is a server issue. Use ssh_exec on 94.130.37.43 instead.`,tool_call_id:T.callId};break}}let os=n?{skipSpinner:!0,skipSummaries:!0}:{},Ip=Ae.some(T=>T.fnName==="ask_user"),Ja=!os.skipSummaries&&!Ce,Nr=null;Ja&&!Ip?(Ce=!0,os.skipSpinner=!0,process.stdout.isTTY?(process.stdout.write(oa(Ae,M,!1,"blink")),Nr=!0):Mt||process.stdout.write(oa(Ae,M,!1)+`
|
|
869
|
+
`)):Ja&&(Ce=!0,os.skipSpinner=!0),n&&n._paused&&n.resume();let{results:Va,summaries:Lp}=await nb(Ae,!0,{...os,skipSummaries:!0});if(Nr&&(Nr=null,process.stdout.write(`\r\x1B[2K${oa(Ae,M,!1)}
|
|
870
|
+
`)),!os.skipSummaries){let T=Lp.filter((j,J)=>!(Ae[J]&&Ae[J].fnName==="ask_user"));for(let j of T)console.log(j);console.log("");let C=Ae.filter(j=>j&&j.fnName!=="ask_user").map(j=>j.fnName),z=qe.record(0,C,Q,W);z&&I0(z)}for(let T=0;T<Ae.length;T++){let C=Ae[T];if(!C.canExecute)continue;let z=Va[T].content,j=z.split(`
|
|
871
|
+
`)[0],J=!j.startsWith("ERROR")&&!j.startsWith("CANCELLED")&&!j.startsWith("Command failed")&&!j.startsWith("EXIT");if(!J&&(C.fnName==="edit_file"||C.fnName==="patch_file")&&C.args?.path&&j.includes("old_text not found")&&Xn.set(C.args.path,!0),J&&["write_file","edit_file","patch_file"].includes(C.fnName)&&C.args&&C.args.path){Xn.delete(C.args.path),W.add(C.args.path);let q=(Re.get(C.args.path)||0)+1;Re.set(C.args.path,q);let Y=C.args.path.split("/").slice(-2).join("/");if(q===le){console.log(`${w.yellow} \u26A0 Loop warning: "${Y}" edited ${q}\xD7 \u2014 possible edit loop${w.reset}`);let ee={role:"user",content:`[SYSTEM WARNING] "${C.args.path}" edited ${q}\xD7. One more edit max, then move on.`};X.push(ee),_.push(ee)}else if(q>=pt){console.log(`${w.red} \u2716 Loop abort: "${Y}" edited ${q}\xD7 \u2014 aborting to prevent runaway loop${w.reset}`),n&&(n.stop(),n=null),o(null),Le(M,D,W,Q,ne,{suppressHint:!0}),Ie(X);return}}if((C.fnName==="bash"||C.fnName==="ssh_exec")&&C.args&&C.args.command){let q=C.args.command.replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),Y=(U.get(q)||0)+1;if(U.set(q,Y),Y===K){console.log(`${w.yellow} \u26A0 Loop warning: same bash command run ${Y}\xD7 \u2014 possible debug loop${w.reset}`);let ee={role:"user",content:`[SYSTEM WARNING] Same bash command ${Y}\xD7. Debug loop detected \u2014 try a different approach.`};X.push(ee),_.push(ee)}else if(Y>=te){console.log(`${w.red} \u2716 Loop abort: same bash command run ${Y}\xD7 \u2014 aborting runaway debug loop${w.reset}`),n&&(n.stop(),n=null),o(null),Le(M,D,W,Q,ne,{suppressHint:!0}),Ie(X);return}}if(C.fnName==="ssh_exec"){if(Rt++,Rt>=Pp){console.log(`${w.red} \u2716 SSH storm abort: ${Rt} consecutive ssh_exec calls \u2014 aborting${w.reset}`),n&&(n.stop(),n=null),o(null),Le(M,D,W,Q,ne,{suppressHint:!0}),Ie(X);return}else if(Rt===vr){{let Y=We(),{messages:ee}=Nt(_,Y);_=ee}Vn=!0,console.log(`${w.yellow} \u26A0 SSH storm warning: ${Rt} consecutive ssh_exec calls \u2014 blocking further SSH${w.reset}`);let q={role:"user",content:`[SYSTEM WARNING] ${Rt} consecutive SSH calls. Synthesize findings now \u2014 no more SSH.`};X.push(q),_.push(q)}}else C.canExecute&&(Rt=0);if(J&&C.fnName==="grep"&&C.args&&C.args.pattern){let q=`${C.args.pattern}|${C.args.path||""}`,Y=(se.get(q)||0)+1;if(se.set(q,Y),Y===Z){console.log(`${w.yellow} \u26A0 Loop warning: grep pattern "${C.args.pattern.slice(0,40)}" run ${Y}\xD7 \u2014 possible search loop${w.reset}`);let ee={role:"user",content:`[SYSTEM WARNING] Same grep pattern ${Y}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};X.push(ee),_.push(ee)}else if(Y>=ie){console.log(`${w.red} \u2716 Loop abort: grep pattern run ${Y}\xD7 \u2014 aborting runaway search loop${w.reset}`),n&&(n.stop(),n=null),o(null),Le(M,D,W,Q,ne,{suppressHint:!0}),Ie(X);return}if(C.args.path){let ee=(oe.get(C.args.path)||0)+1;if(oe.set(C.args.path,ee),ee===ue){let _e=C.args.path.split("/").slice(-2).join("/");console.log(`${w.yellow} \u26A0 Loop warning: "${_e}" grepped ${ee}\xD7 with different patterns \u2014 context flood risk${w.reset}`);let it={role:"user",content:`[SYSTEM WARNING] "${C.args.path}" grepped ${ee}\xD7 \u2014 file already in context. Use existing data, stop searching.`};X.push(it),_.push(it)}}}if(J&&(C.fnName==="bash"||C.fnName==="ssh_exec")&&z.includes('"valid":true')){{let Y=We();if(Tt(_,Y).percentage>=60){let{messages:_e,tokensRemoved:it}=Nt(_,Y);it>0&&(_=_e,console.log(`${w.dim} [pre-stop-compress \u2014 ~${it} tokens freed before STOP injection, now ${Math.round(Tt(_,Y).percentage)}%]${w.reset}`))}}let q={role:"user",content:'[SYSTEM STOP] Tool result contains {"valid":true}. The token/service is valid and reachable. STOP all further investigation immediately. Report to the user that the token is valid, the service is healthy, and no fix is needed. Do NOT read any more log files.'};X.push(q),_.push(q),console.log(`${w.cyan} \u2713 Health-check stop signal detected \u2014 injecting STOP instruction${w.reset}`)}if(z.startsWith("BLOCKED:")){if(Xs++,Xs>=Op){console.log(`${w.red} \u2716 Loop abort: ${Xs} consecutive blocked calls \u2014 model not heeding BLOCKED messages${w.reset}`),n&&(n.stop(),n=null),o(null),Le(M,D,W,Q,ne,{suppressHint:!0}),Ie(X);return}}else Xs=0;if(J)Be=0,Er=!0;else if(Be++,Be===ss){console.log(`${w.yellow} \u26A0 Loop warning: ${Be} consecutive tool errors \u2014 possible stuck loop${w.reset}`);let q={role:"user",content:`[SYSTEM WARNING] ${Be} consecutive errors. Stuck loop \u2014 try fundamentally different approach or declare done.`};X.push(q),_.push(q)}else if(Be>=Ap){console.log(`${w.red} \u2716 Loop abort: ${Be} consecutive errors \u2014 aborting stuck loop${w.reset}`),n&&(n.stop(),n=null),o(null),Le(M,D,W,Q,ne,{suppressHint:!0}),Ie(X);return}if(J&&C.fnName==="read_file"&&C.args&&C.args.path){Q.add(C.args.path);let q=(Oe.get(C.args.path)||0)+1;Oe.set(C.args.path,q);let Y=C.args.path.split("/").slice(-2).join("/"),ee=!C.args?.line_start&&!C.args?.line_end;if(ee&&q===Je){{let it=We();if(Tt(_,it).percentage>=60){let{messages:ae}=Nt(_,it);_=ae}}console.log(`${w.yellow} \u26A0 Loop warning: "${Y}" read unbounded ${q}\xD7 \u2014 use line_start/line_end${w.reset}`);let _e={role:"user",content:`[SYSTEM WARNING] "${C.args.path}" read ${q}\xD7 without line ranges. Use line_start/line_end to read specific sections \u2014 do not re-read the full file.`};X.push(_e),_.push(_e)}else if(ee&&q>=xt){console.log(`${w.red} \u2716 Loop abort: "${Y}" read unbounded ${q}\xD7 \u2014 aborting runaway read loop${w.reset}`),n&&(n.stop(),n=null),o(null),Le(M,D,W,Q,ne,{suppressHint:!0}),Ie(X);return}}if(C.fnName==="spawn_agents"){let q=(z.match(/\bStatus: done\b/g)||[]).length;if((z.match(/\bStatus: truncated\b/g)||[]).length>0&&q===0){if(on++,on===Np){console.log(`${w.yellow} \u26A0 Swarm warning: all sub-agents hit iteration limit ${on}\xD7 in a row${w.reset}`);let ee={role:"user",content:`[SYSTEM WARNING] Sub-agents truncated ${on}\xD7 in a row. Stop spawning \u2014 try different approach or report findings.`};X.push(ee),_.push(ee)}else if(on>=Mp){console.log(`${w.red} \u2716 Swarm abort: all sub-agents hit iteration limit ${on}\xD7 \u2014 aborting stuck swarm${w.reset}`),n&&(n.stop(),n=null),o(null),Le(M,D,W,Q,ne,{suppressHint:!0}),Ie(X);return}}else q>0&&(on=0)}}for(let T of Va)X.push(T),_.push(T);{let T=We();if(Tt(_,T).percentage>=78){let{messages:z,tokensRemoved:j}=Nt(_,T);j>0&&(_=z,console.log(`${w.dim} [auto-compressed \u2014 ~${j} tokens freed, now ${Math.round(Tt(_,T).percentage)}%]${w.reset}`))}}let Qa=ob();if(Qa){let T={role:"user",content:`[User note mid-run]: ${Qa}`};X.push(T),_.push(T),console.log(`${w.cyan} \u270E Context added${w.reset}`)}}if(mt>=Js){n&&(n.stop(),n=null),o(null),Le(M,D,W,Q,ne),Ie(X),nf(X);let{getActiveProviderName:Fe}=Se();if(Fe()==="ollama"&&Sr<Ka){if(W.size===0&&!Er){console.log(`${w.yellow} \u26A0 Max iterations reached with no progress. Stopping.${w.reset}`);break e}Sr++,Js=20,console.log(`${w.dim} \u2500\u2500 auto-extending (+20 turns, ext ${Sr}/${Ka}) \u2500\u2500${w.reset}`);continue e}if(console.log(`
|
|
872
|
+
${w.yellow}\u26A0 Max iterations reached.${w.reset}`),await df(" Continue for 20 more turns?")){Js=20;continue e}console.log(`${w.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${w.reset}`)}break e}}_f.exports={processInput:hb,clearConversation:ab,getConversationLength:lb,getConversationMessages:ub,setConversationMessages:db,setAbortSignalGetter:F0,setMaxIterations:q0,invalidateSystemPromptCache:gf,clearToolFilterCache:z0,getCachedFilteredTools:mf,buildSystemPrompt:bf,getProjectContextHash:hf,buildUserContent:pf,detectAndTruncateLoop:da,injectMidRunNote:sb}});var Se=G(($k,Ef)=>{var{OllamaProvider:gb}=kc(),{OpenAIProvider:$b}=Wc(),{AnthropicProvider:yb}=Kc(),{GeminiProvider:wb}=Jc(),{LocalProvider:bb}=Zc(),{checkBudget:_b}=Mn(),wa={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"}},xf={};for(let[t,e]of Object.entries(wa))for(let s of Object.values(e))xf[s]=t;function kf(t,e){let s=xf[t];return s&&wa[s][e]||t}var je={},st=null,Ne=null,Fs=[];function bt(){if(Object.keys(je).length>0)return;Qn("ollama",new gb),Qn("openai",new $b),Qn("anthropic",new yb),Qn("gemini",new wb),Qn("local",new bb);let t=process.env.DEFAULT_PROVIDER||"ollama",e=process.env.DEFAULT_MODEL||null;je[t]?(st=t,Ne=e||je[t].defaultModel):(st="ollama",Ne="kimi-k2.5");let s=process.env.FALLBACK_CHAIN;s&&(Fs=s.split(",").map(o=>o.trim()).filter(Boolean))}function Qn(t,e){je[t]=e}function xb(t){return bt(),je[t]||null}function ba(){return bt(),je[st]||null}function kb(){return bt(),st}function vb(){return bt(),Ne}function Sb(){bt();let t=ba();if(!t)return{id:Ne,name:Ne,provider:st};let e=t.getModel(Ne);return e?{...e,provider:st}:{id:Ne,name:Ne,provider:st}}function vf(t){if(!t)return{provider:null,model:null};let e=t.indexOf(":");if(e>0){let s=t.slice(0,e);if(je[s]||["ollama","openai","anthropic","gemini","local"].includes(s))return{provider:s,model:t.slice(e+1)}}return{provider:null,model:t}}function Eb(t){bt();let{provider:e,model:s}=vf(t);if(e){let n=je[e];return n&&(n.getModel(s)||e==="local"||e==="ollama")?(st=e,Ne=s,cr(),!0):!1}let o=ba();if(o&&o.getModel(s))return Ne=s,cr(),!0;for(let[n,r]of Object.entries(je))if(r.getModel(s))return st=n,Ne=s,cr(),!0;return!1}function cr(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=$e();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=He();t()}catch{}}function Tb(){bt();let t=new Set;for(let e of Object.values(je))for(let s of e.getModelNames())t.add(s);return Array.from(t)}function Rb(){return bt(),Object.entries(je).map(([t,e])=>({provider:t,configured:e.isConfigured(),models:Object.values(e.getModels()).map(s=>({...s,active:t===st&&s.id===Ne}))}))}function Cb(){bt();let t=[];for(let[e,s]of Object.entries(je)){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 Ab(t){Fs=Array.isArray(t)?t:[]}function Ob(){return[...Fs]}function Nb(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 Sf(t){let e=[st,...Fs.filter(r=>r!==st)],s,o=0,n=0;for(let r=0;r<e.length;r++){let i=e[r],c=je[i];if(!c||!c.isConfigured())continue;n++;let l=_b(i);if(!l.allowed){o++,s=new Error(`Budget limit reached for ${i}: $${l.spent.toFixed(2)} / $${l.limit.toFixed(2)}`);continue}try{let u=r>0,d=u?kf(Ne,i):Ne;return u&&d!==Ne&&process.stderr.write(` [fallback: ${i}:${d}]
|
|
873
|
+
`),await t(c,i,d)}catch(u){if(s=u,Nb(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 Mb(t,e,s={}){return bt(),Sf((o,n,r)=>o.stream(t,e,{model:r,signal:s.signal,...s}))}async function Pb(t,e,s={}){if(bt(),s.provider){let o=je[s.provider];if(!o||!o.isConfigured())throw new Error(`Provider '${s.provider}' is not available`);let n={model:s.model||Ne,...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 Sf(async(o,n,r)=>{try{return await o.chat(t,e,{model:r,...s})}catch(i){if(typeof o.stream=="function")try{return await o.stream(t,e,{model:r,...s,onToken:()=>{}})}catch{}throw i}})}function Ib(){bt();let t=[];for(let[e,s]of Object.entries(je))s.isConfigured()&&t.push({name:e,models:Object.values(s.getModels())});return t}function Lb(){for(let t of Object.keys(je))delete je[t];st=null,Ne=null,Fs=[]}Ef.exports={registerProvider:Qn,getProvider:xb,getActiveProvider:ba,getActiveProviderName:kb,getActiveModelId:vb,getActiveModel:Sb,setActiveModel:Eb,getModelNames:Tb,parseModelSpec:vf,listProviders:Rb,listAllModels:Cb,callStream:Mb,callChat:Pb,getConfiguredProviders:Ib,setFallbackChain:Ab,getFallbackChain:Ob,resolveModelForProvider:kf,MODEL_EQUIVALENTS:wa,_reset:Lb}});var xa=G((yk,Tf)=>{"use strict";var Ut=require("fs"),lr=require("path"),jb=require("readline"),fe="\x1B[0m",_a="\x1B[1m",ut="\x1B[2m",ur="\x1B[33m",Zn="\x1B[36m",dr="\x1B[32m";function Db(t){return(e,s="")=>new Promise(o=>{let n=s?` ${ut}[${s}]${fe}`:"";t.question(` ${Zn}${e}${n}${fe}: `,r=>o(r.trim()||s))})}function fr(t,e){return new Promise(s=>{e&&e.pause(),process.stdout.write(` ${Zn}${t}${fe}: `);let o=process.stdin,n=o.isRaw,r="";o.setRawMode(!0),o.resume(),o.setEncoding("utf8");let i=c=>{c==="\r"||c===`
|
|
790
874
|
`?(o.setRawMode(n||!1),o.removeListener("data",i),process.stdout.write(`
|
|
791
875
|
`),e&&e.resume(),s(r)):c===""?(process.stdout.write(`
|
|
792
|
-
`),process.exit(0)):c==="\x7F"?r.length>0&&(r=r.slice(0,-1),process.stdout.write("\b \b")):(r+=c,process.stdout.write("*"))};o.on("data",i)})}async function
|
|
793
|
-
`),console.log(` ${
|
|
794
|
-
`),console.log(` ${
|
|
795
|
-
${
|
|
796
|
-
`);return}if(i==="1"){console.log();let
|
|
797
|
-
${
|
|
798
|
-
`);return}let h=await n("Default model","claude-sonnet-4-6");c.push("DEFAULT_PROVIDER=anthropic",`DEFAULT_MODEL=${h}`,`ANTHROPIC_API_KEY=${
|
|
799
|
-
${
|
|
800
|
-
`);return}let h=await n("Default model","gpt-4o");c.push("DEFAULT_PROVIDER=openai",`DEFAULT_MODEL=${h}`,`OPENAI_API_KEY=${
|
|
801
|
-
${
|
|
802
|
-
`);return}let h=await n("Default model","gemini-2.0-flash");c.push("DEFAULT_PROVIDER=gemini",`DEFAULT_MODEL=${h}`,`GEMINI_API_KEY=${
|
|
803
|
-
|
|
804
|
-
`:"";
|
|
876
|
+
`),process.exit(0)):c==="\x7F"?r.length>0&&(r=r.slice(0,-1),process.stdout.write("\b \b")):(r+=c,process.stdout.write("*"))};o.on("data",i)})}async function qb({rl:t=null,force:e=!1}={}){if(!e){let p=Ut.existsSync(lr.join(process.cwd(),".env"))||Ut.existsSync(lr.join(__dirname,"..",".env")),h=process.env.ANTHROPIC_API_KEY||process.env.OPENAI_API_KEY||process.env.GEMINI_API_KEY||process.env.OPENROUTER_API_KEY,m=process.env.DEFAULT_PROVIDER||process.env.DEFAULT_MODEL;if(p||h||m)return}let s=!t,o=t||jb.createInterface({input:process.stdin,output:process.stdout,terminal:!0}),n=Db(o),r=!e;console.log(),console.log(r?`${ur}${_a} \u2726 Welcome to nex-code! No configuration found.${fe}`:`${Zn}${_a} \u2726 nex-code \u2014 Provider & API Key Setup${fe}`),console.log(`${ut} \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500${fe}`),r&&console.log(` Let's set you up in 60 seconds.
|
|
877
|
+
`),console.log(` ${_a}Which AI provider do you want to use?${fe}
|
|
878
|
+
`),console.log(` ${dr}1)${fe} Ollama ${ut}local/cloud \u2014 no API key needed${fe}`),console.log(` ${Zn}2)${fe} Anthropic ${ut}Claude (claude-sonnet-4-6 etc.)${fe}`),console.log(` ${Zn}3)${fe} OpenAI ${ut}GPT-4o, GPT-4.1 etc.${fe}`),console.log(` ${Zn}4)${fe} Gemini ${ut}Google Gemini 2.x${fe}`),console.log(` ${ut}5) Skip / Cancel${fe}`),console.log();let i=await n("Enter number","1"),c=[];if(i==="5"){s&&o.close(),console.log(`
|
|
879
|
+
${ut} Cancelled \u2014 no changes made.${fe}
|
|
880
|
+
`);return}if(i==="1"){console.log();let p=await n("Ollama host","http://localhost:11434"),h=await n("Default model","qwen3-coder");c.push("DEFAULT_PROVIDER=ollama",`DEFAULT_MODEL=${h}`,`OLLAMA_HOST=${p}`),process.env.DEFAULT_PROVIDER="ollama",process.env.DEFAULT_MODEL=h,process.env.OLLAMA_HOST=p}else if(i==="2"){console.log(),console.log(` ${ut}Get your key: https://console.anthropic.com/settings/keys${fe}`);let p=await fr("ANTHROPIC_API_KEY",t);if(!p){s&&o.close(),console.log(`
|
|
881
|
+
${ur} No key entered \u2014 cancelled.${fe}
|
|
882
|
+
`);return}let h=await n("Default model","claude-sonnet-4-6");c.push("DEFAULT_PROVIDER=anthropic",`DEFAULT_MODEL=${h}`,`ANTHROPIC_API_KEY=${p}`),process.env.DEFAULT_PROVIDER="anthropic",process.env.DEFAULT_MODEL=h,process.env.ANTHROPIC_API_KEY=p}else if(i==="3"){console.log(),console.log(` ${ut}Get your key: https://platform.openai.com/api-keys${fe}`);let p=await fr("OPENAI_API_KEY",t);if(!p){s&&o.close(),console.log(`
|
|
883
|
+
${ur} No key entered \u2014 cancelled.${fe}
|
|
884
|
+
`);return}let h=await n("Default model","gpt-4o");c.push("DEFAULT_PROVIDER=openai",`DEFAULT_MODEL=${h}`,`OPENAI_API_KEY=${p}`),process.env.DEFAULT_PROVIDER="openai",process.env.DEFAULT_MODEL=h,process.env.OPENAI_API_KEY=p}else if(i==="4"){console.log(),console.log(` ${ut}Get your key: https://aistudio.google.com/app/apikey${fe}`);let p=await fr("GEMINI_API_KEY",t);if(!p){s&&o.close(),console.log(`
|
|
885
|
+
${ur} No key entered \u2014 cancelled.${fe}
|
|
886
|
+
`);return}let h=await n("Default model","gemini-2.0-flash");c.push("DEFAULT_PROVIDER=gemini",`DEFAULT_MODEL=${h}`,`GEMINI_API_KEY=${p}`),process.env.DEFAULT_PROVIDER="gemini",process.env.DEFAULT_MODEL=h,process.env.GEMINI_API_KEY=p}if(console.log(),(await n("Add Perplexity key for grounded web search? (y/N)","n")).toLowerCase()==="y"){console.log(` ${ut}Get your key: https://www.perplexity.ai/settings/api${fe}`);let p=await fr("PERPLEXITY_API_KEY",t);p&&(c.push(`PERPLEXITY_API_KEY=${p}`),process.env.PERPLEXITY_API_KEY=p)}console.log();let u=lr.join(process.cwd(),".env"),d=(Ut.existsSync(u),"y"),f=await n(`Save to ${u}? (Y/n)`,d);if(s&&o.close(),f.toLowerCase()!=="n"){let p=Ut.existsSync(u)?Ut.readFileSync(u,"utf-8").trimEnd()+`
|
|
887
|
+
|
|
888
|
+
`:"";Ut.writeFileSync(u,p+c.join(`
|
|
805
889
|
`)+`
|
|
806
|
-
`);let h=
|
|
807
|
-
`).some(g=>g.trim()===".env")||
|
|
890
|
+
`);let h=lr.join(process.cwd(),".gitignore");Ut.existsSync(h)&&(Ut.readFileSync(h,"utf-8").split(`
|
|
891
|
+
`).some(g=>g.trim()===".env")||Ut.appendFileSync(h,`
|
|
808
892
|
.env
|
|
809
893
|
`)),console.log(`
|
|
810
|
-
${
|
|
811
|
-
${
|
|
812
|
-
`)}
|
|
813
|
-
`)}function
|
|
814
|
-
`);console.log=t,console.warn=t,console.info=t;let{setConfirmHook:e}=
|
|
815
|
-
`))}function
|
|
816
|
-
`).replace(/[\x00-\x08\x0b-\x1f\x7f]/g,o=>`<${o.charCodeAt(0).toString(16).padStart(2,"0")}>`);
|
|
817
|
-
`)}function
|
|
818
|
-
`)&&
|
|
819
|
-
`)&&!
|
|
820
|
-
`);for(let
|
|
821
|
-
`);process.stdout.write(`\x1B[${
|
|
822
|
-
`);process.stdout.write(
|
|
823
|
-
`),
|
|
894
|
+
${dr} \u2713 Saved to ${u}${fe}`),c.some(m=>m.includes("API_KEY"))&&console.log(`${ut} (key stored locally \u2014 never committed)${fe}`)}if(process.env.DEFAULT_PROVIDER)try{let{setActiveModel:p}=Se(),h=process.env.DEFAULT_MODEL?`${process.env.DEFAULT_PROVIDER}:${process.env.DEFAULT_MODEL}`:process.env.DEFAULT_PROVIDER;p(h),console.log(`${dr} \u2713 Switched to ${h} for this session${fe}`)}catch{}console.log(`
|
|
895
|
+
${dr} \u2713 Setup complete!${fe}
|
|
896
|
+
`)}Tf.exports={runSetupWizard:qb}});var Cf=G((wk,Rf)=>{"use strict";var Fb=require("readline");function xn(t){process.stdout.write(JSON.stringify(t)+`
|
|
897
|
+
`)}function Ub(){process.env.NEX_SERVER="1";let t=(...c)=>process.stderr.write(c.map(String).join(" ")+`
|
|
898
|
+
`);console.log=t,console.warn=t,console.info=t;let{setConfirmHook:e}=Ue(),s=new Map,o=0;e((c,l)=>{let u="cfm-"+ ++o,d=l?.toolName||"",f=!1;try{let{isCritical:p}=Ue();f=p(c)}catch{}return xn({type:"confirm_request",id:u,question:c,tool:d,critical:f}),new Promise(p=>{s.set(u,p)})});let n=null,r={onToken(c){n&&xn({type:"token",id:n,text:c})},onThinkingToken(){},onToolStart(c,l){n&&xn({type:"tool_start",id:n,tool:c,args:l||{}})},onToolEnd(c,l,u){n&&xn({type:"tool_end",id:n,tool:c,summary:l||"",ok:!!u})}},i=Fb.createInterface({input:process.stdin,output:null,terminal:!1});xn({type:"ready"}),i.on("line",async c=>{let l=c.trim();if(!l)return;let u;try{u=JSON.parse(l)}catch{return}switch(u.type){case"chat":{let d=u.id||"msg-"+Date.now();n=d;let{processInput:f}=$e();try{await f(u.text,r),xn({type:"done",id:d})}catch(p){xn({type:"error",id:d,message:p?.message||String(p)})}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}=$e();d();for(let[f,p]of s)s.delete(f),p(!1);break}default:break}}),i.on("close",()=>{process.exit(0)})}Rf.exports={startServerMode:Ub}});var Mf=G((bk,Nf)=>{"use strict";var pr=require("fs"),{T:Ct,isDark:Wb}=an(),dt="\x1B[0m",Bb=!Wb,Hb=process.env.FOOTER_DEBUG==="1"||process.env.FOOTER_DEBUG==="2",Gb=process.env.FOOTER_DEBUG==="2",es=null;function sn(...t){Hb&&(es||(es=pr.openSync("/tmp/footer-debug.log","w")),pr.writeSync(es,t.join(" ")+`
|
|
899
|
+
`))}function Af(t,e){if(!Gb||typeof e!="string")return;es||(es=pr.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>
|
|
900
|
+
`).replace(/[\x00-\x08\x0b-\x1f\x7f]/g,o=>`<${o.charCodeAt(0).toString(16).padStart(2,"0")}>`);pr.writeSync(es,`${t}: ${s}
|
|
901
|
+
`)}function Of(t){return t.replace(/\x1b\[[^a-zA-Z]*[a-zA-Z]/g,"").length}var ka=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="",this._statusMode=""}setStatusInfo({model:e,branch:s,project:o,mode:n}={}){e!==void 0&&(this._statusModel=e),s!==void 0&&(this._statusBranch=s),o!==void 0&&(this._statusProject=o),n!==void 0&&(this._statusMode=n),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,r=this._statusMode;if(!s)return Ct.footer_sep+"\u2500".repeat(e)+dt;let i=` ${Ct.footer_divider}\xB7${dt} `,c=[];s&&c.push(`${Ct.footer_model}${s}${dt}`),o&&c.push(`${Ct.footer_branch}${o}${dt}`),n&&c.push(`${Ct.footer_project}${n}${dt}`);let l=c.join(i),u=[s,o,n].filter(Boolean).join(" \xB7 ").length,d="\u2500 ";if(r){let h=r.length,m=Math.max(0,e-d.length-u-1-1-h-3),g="\u2500".repeat(m);return`${Ct.footer_sep}${d}${dt}${l}${Ct.footer_sep} ${g} ${dt}${Ct.footer_mode}${r}${dt}${Ct.footer_sep} \u2500\u2500${dt}`}let f=Math.max(0,e-d.length-u-2),p="\u2500".repeat(f);return`${Ct.footer_sep}${d}${dt}${l}${Ct.footer_sep} ${p}${dt}`}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(Bb)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 Af("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);sn("RELAYOUT:",e,"rows="+o,"cols="+n,"scrollEnd="+r,"cursorOnInput="+this._cursorOnInputRow),this._prevTermRows=o,this._prevTermCols=n;let i=Math.min(this._lastOutputRow+1,r+1),c="";for(let l=i;l<=o;l++)c+=this._goto(l)+"\x1B[2K";s(c),this._setScrollRegion(),this._lastOutputRow=Math.min(this._lastOutputRow,r),this.drawFooter(),this._cursorOnInputRow&&this._rl&&this._rl.prompt(!0),this._dirty=!1}activate(e){if(!process.stdout.isTTY)return;this._rl=e,this._origWrite=process.stdout.write.bind(process.stdout),this._active=!0,this._prevTermRows=this._rows,this._prevTermCols=this._cols,this._origWrite("\x1B[r"),this._setScrollRegion(),this._lastOutputRow=1,this.drawFooter();let s=this,o=process.stdout.write.bind(process.stdout);this._origWrite=o,process.stdout.write=function(m,...g){if(Af("PATCH",m),!s._active||typeof m!="string")return o(m,...g);if(s._inRefreshLine){let v=m.replace(/\n/g,"");return v?o(v,...g):!0}if(s._cursorOnInputRow)if(m.includes(`
|
|
902
|
+
`)&&m.length>4&&!m.includes("\r"))sn("STDOUT: agent output, leaving input row, data="+JSON.stringify(m).slice(0,100)),s._cursorOnInputRow=!1,o(s._goto(Math.min(s._lastOutputRow+1,s._scrollEnd)));else{if(m.length<=4&&!m.includes(`
|
|
903
|
+
`)&&!m.includes("\r")&&!/[\x00-\x1f\x7f]/.test(m))return sn("STDOUT: char intercept:",JSON.stringify(m)),s._origRefreshLine&&s._doRefreshLine(),!0;{let v=m.replace(/\n/g,"");return v?o(v,...g):!0}}let $=s._cols||80,y=0,x=m.split(`
|
|
904
|
+
`);for(let v=0;v<x.length;v++){let b=Of(x[v]);b>0&&(y+=Math.floor((b-1)/$))}let _=x.length-1;return _+y>0&&(s._lastOutputRow=Math.min(s._lastOutputRow+_+y,s._scrollEnd)),o(m,...g)},this._cursorOnInputRow=!1,this._origStderrWrite=process.stderr.write.bind(process.stderr),process.stderr.write=function(m,...g){if(!s._active)return s._origStderrWrite(m,...g);if(typeof m=="string"&&m.includes("\r")){let $=Math.min(s._lastOutputRow+1,s._scrollEnd);if(s._cursorOnInputRow){s._origWrite("\x1B7"),s._origWrite(s._goto($));let y=s._origStderrWrite(m,...g);return s._origWrite("\x1B8"),y}s._origWrite(s._goto($))}return s._origStderrWrite(m,...g)},this._origLog=console.log,this._origError=console.error;function n(...m){if(!s._active){s._origLog(...m);return}s._origWrite(s._goto(Math.min(s._lastOutputRow+1,s._scrollEnd))),s._cursorOnInputRow=!1,s._origLog(...m),s.drawFooter(),o(s._goto(s._rowInput)+"\x1B[2K"),s._cursorOnInputRow=!0}function r(...m){if(!s._active){s._origError(...m);return}s._origWrite(s._goto(Math.min(s._lastOutputRow+1,s._scrollEnd))),s._cursorOnInputRow=!1,s._origError(...m),s.drawFooter(),o(s._goto(s._rowInput)+"\x1B[2K"),s._cursorOnInputRow=!0}console.log=n,console.error=r,this._origSetPr=e.setPrompt.bind(e),e.setPrompt=function(m){s._origSetPr(m),s._active&&s.drawFooter(m)},this._origPrompt=e.prompt.bind(e),e.prompt=function(m){if(!s._active)return s._origPrompt(m);sn("PROMPT: goto rowInput="+s._rowInput),e.prevRows=0,o(s._goto(s._rowInput)+dt+"\x1B[2K"),s._cursorOnInputRow=!0,s._origPrompt(m)};let i=e.question.bind(e);e.question=function(m,g){if(!s._active)return i(m,g);o(s._goto(s._rowInput)+"\x1B[2K"),e.prevRows=0,s._cursorOnInputRow=!0,i(m,$=>{o(s._goto(s._rowInput)+"\x1B[2K"),s._cursorOnInputRow=!1,s.drawFooter(),g($)})};let c=Object.getPrototypeOf(e),l=Object.getOwnPropertySymbols(c).find(m=>m.toString()==="Symbol(_refreshLine)"),u=l?c[l].bind(e):e._refreshLine?e._refreshLine.bind(e):null;if(this._origRefreshLine=u,this._doRefreshLine=function(){if(!s._active||!u)return;if(s._rows!==s._prevTermRows||s._cols!==s._prevTermCols){s._dirty=!0;return}e.prevRows=0,o(s._goto(s._rowInput)+dt+"\x1B[2K");let m=s._cols,g=e._prompt||"",$=Of(g),y=m-$-1;s._inRefreshLine=!0;try{if(e.line.length<=y){sn("REFRESH: short line, len="+e.line.length),u();return}sn("REFRESH: long line, len="+e.line.length+", max="+y);let x=e.line,_=e.cursor,v=Math.max(1,y-1),b=Math.max(0,_-v),k=(b>0?"\xAB":"")+x.slice(b,b+v+(b>0?0:1));e.line=k,e.cursor=k.length,u(),e.line=x,e.cursor=_}finally{s._inRefreshLine=!1}},u){let m=this._doRefreshLine;l&&Object.defineProperty(e,l,{value:m,writable:!0,configurable:!0}),e._refreshLine=m}e.on("line",()=>{s._active&&(sn("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,p=()=>{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(p,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 m=s._rows,g=s._cols;(s._dirty||m!==s._prevTermRows||g!==s._prevTermCols)&&(sn("CONSISTENCY: dirty="+s._dirty+" rows="+m+"/"+s._prevTermRows+" cols="+g+"/"+s._prevTermCols),s._relayout("consistency"))},800)}deactivate(){if(this._active){if(this._active=!1,this._offResize&&(this._offResize(),this._offResize=null),this._consistencyTimer&&(clearInterval(this._consistencyTimer),this._consistencyTimer=null),this._origStderrWrite&&(process.stderr.write=this._origStderrWrite,this._origStderrWrite=null),this._origLog&&(console.log=this._origLog,this._origLog=null),this._origError&&(console.error=this._origError,this._origError=null),this._origWrite&&(process.stdout.write=this._origWrite),this._rl&&(this._origPrompt&&(this._rl.prompt=this._origPrompt,this._origPrompt=null),this._origSetPr&&(this._rl.setPrompt=this._origSetPr,this._origSetPr=null),this._origRefreshLine)){let e=Object.getOwnPropertySymbols(Object.getPrototypeOf(this._rl)).find(s=>s.toString()==="Symbol(_refreshLine)");e&&delete this._rl[e],delete this._rl._refreshLine,this._origRefreshLine=null}this._eraseStatus(),this._clearScrollRegion(),this._origWrite=null}}};Nf.exports={StickyFooter:ka}});var Lf=G((_k,If)=>{var{C:be}=ve(),{listProviders:Kb,getActiveProviderName:Yb,getActiveModelId:zb,setActiveModel:Xb}=Se();function Pf(t,e,s={}){let{title:o="Select",hint:n="\u2191\u2193 navigate \xB7 Enter select \xB7 Esc cancel"}=s;return new Promise(r=>{let i=e.map((y,x)=>y.isHeader?-1:x).filter(y=>y>=0);if(i.length===0){r(null);return}let c=e.findIndex(y=>y.isCurrent),l=c>=0?i.indexOf(c):0;l<0&&(l=0);let u=process.stdout.rows?Math.max(process.stdout.rows-6,5):20,d=0;function f(){let y=i[l];return y<d?d=y:y>=d+u&&(d=y-u+1),{start:d,end:Math.min(e.length,d+u)}}let p=0;function h(){if(p>0){process.stdout.write(`\x1B[${p}A`);for(let b=0;b<p;b++)process.stdout.write(`\x1B[2K
|
|
905
|
+
`);process.stdout.write(`\x1B[${p}A`)}let y=[];y.push(` ${be.bold}${be.cyan}${o}${be.reset}`),y.push(` ${be.dim}${n}${be.reset}`),y.push("");let{start:x,end:_}=f();x>0&&y.push(` ${be.dim}\u2191 more${be.reset}`);for(let b=x;b<_;b++){let k=e[b];if(k.isHeader){y.push(` ${be.bold}${be.dim}${k.label}${be.reset}`);continue}let R=i[l]===b,O=R?`${be.cyan}> `:" ",P=k.isCurrent?` ${be.yellow}<current>${be.reset}`:"";R?y.push(`${O}${be.bold}${k.label}${be.reset}${P}`):y.push(`${O}${be.dim}${k.label}${be.reset}${P}`)}_<e.length&&y.push(` ${be.dim}\u2193 more${be.reset}`);let v=y.join(`
|
|
906
|
+
`);process.stdout.write(v+`
|
|
907
|
+
`),p=y.length}t.pause();let m=process.stdin.isRaw;process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume();function g(){process.stdin.removeListener("keypress",$),process.stdin.isTTY&&m!==void 0&&process.stdin.setRawMode(m),t.resume()}function $(y,x){if(x){if(x.name==="up"||x.ctrl&&x.name==="p"){l>0&&(l--,h());return}if(x.name==="down"||x.ctrl&&x.name==="n"){l<i.length-1&&(l++,h());return}if(x.name==="return"){let _=e[i[l]];g(),r(_?_.value:null);return}if(x.name==="escape"||x.ctrl&&x.name==="c"){g(),r(null);return}}}process.stdin.on("keypress",$),h()})}async function Jb(t){let e=Kb(),s=Yb(),o=zb(),n=[];for(let i of e)if(i.models.length!==0){n.push({label:i.provider,value:null,isHeader:!0});for(let c of i.models){let l=i.provider===s&&c.id===o;n.push({label:` ${c.name} (${i.provider}:${c.id})`,value:`${i.provider}:${c.id}`,isCurrent:l})}}let r=await Pf(t,n,{title:"Select Model"});return r?(Xb(r),console.log(`${be.green}Switched to ${r}${be.reset}`),!0):(console.log(`${be.dim}Cancelled${be.reset}`),!1)}If.exports={pickFromList:Pf,showModelPicker:Jb}});var Sa=G((kk,Hf)=>{var jf=require("fs"),Vb=require("path"),{atomicWrite:Qb,withFileLockSync:Zb}=Xt(),{callChat:Df}=Se(),{remember:e_,listMemories:xk,recall:t_}=nn(),va=4,n_=`You are a memory optimization agent for an AI coding assistant called nex-code.
|
|
824
908
|
Analyze this conversation history and extract actionable learnings the assistant should remember.
|
|
825
909
|
|
|
826
910
|
Return ONLY valid JSON in this exact format:
|
|
@@ -846,15 +930,15 @@ Rules:
|
|
|
846
930
|
- value: concise actionable instruction, max 120 chars
|
|
847
931
|
- nex_additions: project-level instructions/conventions only (not personal preferences)
|
|
848
932
|
- If nothing significant to learn, return {"memories": [], "nex_additions": [], "summary": "..."}
|
|
849
|
-
- Return ONLY the JSON, no markdown, no explanation`;function
|
|
933
|
+
- Return ONLY the JSON, no markdown, no explanation`;function qf(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(`
|
|
850
934
|
|
|
851
|
-
`)}async function
|
|
935
|
+
`)}async function Ff(t){if(t.filter(n=>n.role==="user").length<va)return{memories:[],nex_additions:[],summary:null,skipped:!0};let s=qf(t);if(!s.trim())return{memories:[],nex_additions:[],summary:null,skipped:!0};let o=[{role:"system",content:n_},{role:"user",content:`Conversation to analyze:
|
|
852
936
|
|
|
853
|
-
${s}`}];try{let i=((await
|
|
937
|
+
${s}`}];try{let i=((await Df(o,[],{temperature:0,maxTokens:800})).content||"").trim().match(/\{[\s\S]*\}/);if(!i)return{memories:[],nex_additions:[],summary:null,error:"No JSON in response"};let c=JSON.parse(i[0]);return{memories:Array.isArray(c.memories)?c.memories:[],nex_additions:Array.isArray(c.nex_additions)?c.nex_additions:[],summary:typeof c.summary=="string"?c.summary:null}}catch(n){return{memories:[],nex_additions:[],summary:null,error:n.message}}}function Uf(t){let e=[];for(let{key:s,value:o}of t||[]){if(!s||!o||typeof s!="string"||typeof o!="string")continue;let n=s.trim().replace(/\s+/g,"-").substring(0,60),r=o.trim().substring(0,200);if(!n||!r)continue;let i=t_(n);i!==r&&(e_(n,r),e.push({key:n,value:r,action:i?"updated":"added"}))}return e}function Wf(t){if(!t||t.length===0)return[];let e=Vb.join(process.cwd(),"NEX.md");return Zb(e,()=>{let s="";try{jf.existsSync(e)&&(s=jf.readFileSync(e,"utf-8"))}catch{}let o=[],n=s;for(let r of t){if(!r||typeof r!="string")continue;let i=r.trim();if(!i)continue;let c=i.substring(0,35).toLowerCase();s.toLowerCase().includes(c)||(o.push(i),n=n?n.endsWith(`
|
|
854
938
|
`)?n+i:n+`
|
|
855
939
|
`+i:i)}return o.length>0&&(n.endsWith(`
|
|
856
940
|
`)||(n+=`
|
|
857
|
-
`),
|
|
941
|
+
`),Qb(e,n)),o})}async function s_(t){let e=await Ff(t);if(e.skipped)return{applied:[],nexAdded:[],summary:null,skipped:!0};if(e.error)return{applied:[],nexAdded:[],summary:null,error:e.error};let s=Uf(e.memories),o=Wf(e.nex_additions);return{applied:s,nexAdded:o,summary:e.summary}}var o_=`You are a knowledge base agent for an AI coding assistant called nex-code.
|
|
858
942
|
Analyze this conversation and extract knowledge worth persisting in the project knowledge base (.nex/brain/).
|
|
859
943
|
|
|
860
944
|
Return ONLY valid JSON in this exact format:
|
|
@@ -888,36 +972,36 @@ Rules:
|
|
|
888
972
|
---
|
|
889
973
|
- Maximum 3 documents per session. Quality over quantity.
|
|
890
974
|
- If nothing worth persisting: return {"documents": [], "skip_reason": "..."}
|
|
891
|
-
- Return ONLY the JSON, no markdown fences, no explanation`;async function
|
|
975
|
+
- Return ONLY the JSON, no markdown fences, no explanation`;async function Bf(t){if(t.filter(n=>n.role==="user").length<va)return{documents:[],skip_reason:"Session too short"};let s=qf(t);if(!s.trim())return{documents:[],skip_reason:"No usable content"};let o=[{role:"system",content:o_},{role:"user",content:`Conversation to analyze:
|
|
892
976
|
|
|
893
|
-
${s}`}];try{let i=((await
|
|
977
|
+
${s}`}];try{let i=((await Df(o,[],{temperature:0,maxTokens:2e3})).content||"").trim().match(/\{[\s\S]*\}/);if(!i)return{documents:[],error:"No JSON in response"};let c=JSON.parse(i[0]);return{documents:Array.isArray(c.documents)?c.documents:[],skip_reason:c.skip_reason}}catch(n){return{documents:[],error:n.message}}}async function r_(t){let e=await Bf(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}=vs(),n=[],r=[];for(let i of e.documents){if(!i.name||!i.content)continue;let c=i.name.trim().replace(/\.md$/,"").replace(/[^a-z0-9-]/g,"-").substring(0,60);if(!c)continue;let l=o(c);if(l.content){let d=`
|
|
894
978
|
|
|
895
979
|
## Update ${new Date().toISOString().split("T")[0]}
|
|
896
980
|
|
|
897
|
-
${i.content}`;s(c,l.content+d),n.push({name:c,reason:i.reason||"",action:"updated"})}else s(c,i.content),n.push({name:c,reason:i.reason||"",action:"created"})}return{written:n,skipped:r}}
|
|
898
|
-
${
|
|
899
|
-
`);let o=Object.keys(s);if(o.length>0&&(console.log(`${
|
|
981
|
+
${i.content}`;s(c,l.content+d),n.push({name:c,reason:i.reason||"",action:"updated"})}else s(c,i.content),n.push({name:c,reason:i.reason||"",action:"created"})}return{written:n,skipped:r}}Hf.exports={learnFromSession:s_,learnBrainFromSession:r_,reflectOnSession:Ff,reflectBrain:Bf,applyMemories:Uf,applyNexAdditions:Wf,LEARN_MIN_MESSAGES:va}});var zf=G((Sk,Yf)=>{var Ye=require("fs"),ns=require("path"),vk=require("os"),i_=require("readline"),{C:H}=ve(),Gf=".nex",Ea=null;function a_(t){Ea=t}function ze(t,e=""){let s=e?` ${H.dim}[${e}]${H.reset}`:"",o=` ${H.cyan}${t}${s}${H.reset}: `;return new Promise(n=>{let r=i=>{let c=i.trim()||e;n(c)};if(Ea)Ea.question(o,r);else{let i=i_.createInterface({input:process.stdin,output:process.stdout});i.question(o,c=>{i.close(),r(c)})}})}function ts(t,e=!0){return ze(`${t} (${e?"Y/n":"y/N"})`,e?"y":"n").then(o=>o.toLowerCase()!=="n"&&o.toLowerCase()!=="no")}async function Ta(t,e,s){let o=e.map((c,l)=>`${H.dim}${l+1})${H.reset} ${c}`).join(" ");console.log(` ${H.cyan}${t}${H.reset}`),console.log(` ${o}`);let n=s?e.indexOf(s)+1:1,r=await ze("Enter number",String(n)),i=parseInt(r,10)-1;return e[Math.max(0,Math.min(i,e.length-1))]}async function c_(){let t=ns.join(process.cwd(),Gf),e=ns.join(t,"servers.json"),s={};if(Ye.existsSync(e))try{s=JSON.parse(Ye.readFileSync(e,"utf-8"))}catch{}console.log(`
|
|
982
|
+
${H.bold}${H.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${H.reset}`),console.log(`${H.bold}${H.cyan}\u2551 nex-code Server Setup Wizard \u2551${H.reset}`),console.log(`${H.bold}${H.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${H.reset}
|
|
983
|
+
`);let o=Object.keys(s);if(o.length>0&&(console.log(`${H.dim}Existing profiles: ${o.join(", ")}${H.reset}`),!await ts("Add or update a server profile?",!0))){console.log(`${H.dim}No changes made.${H.reset}
|
|
900
984
|
`);return}let n={...s},r=!0;for(;r;){console.log(`
|
|
901
|
-
${
|
|
902
|
-
${
|
|
903
|
-
Add another server?`,!1)}
|
|
985
|
+
${H.bold}\u2500\u2500\u2500 New Server Profile \u2500\u2500\u2500${H.reset}`);let l=await ze("Profile name (e.g. prod, staging, macbook)");if(!l){console.log(`${H.red} Name is required.${H.reset}`);continue}let u=await ze("Host / IP address");if(!u){console.log(`${H.red} Host is required.${H.reset}`);continue}let d=await ze("SSH user","root"),f=await ze("SSH port","22"),p=parseInt(f,10)||22,h=await ze("SSH key path (leave empty for SSH agent)",""),m=await Ta("Operating system",["almalinux9","macos","ubuntu","debian","other"],"almalinux9"),g=await ts("Allow sudo commands?",!0),$={host:u,user:d};p!==22&&($.port=p),h&&($.key=h),m!=="other"&&($.os=m),g&&($.sudo=!0),n[l]=$,console.log(`
|
|
986
|
+
${H.green}\u2713${H.reset} Profile "${l}" added: ${d}@${u}${p!==22?`:${p}`:""}${m!=="other"?` [${m}]`:""}`),r=await ts(`
|
|
987
|
+
Add another server?`,!1)}Ye.existsSync(t)||Ye.mkdirSync(t,{recursive:!0}),Ye.writeFileSync(e,JSON.stringify(n,null,2)+`
|
|
904
988
|
`,"utf-8"),console.log(`
|
|
905
|
-
${
|
|
989
|
+
${H.green}\u2713 Saved .nex/servers.json (${Object.keys(n).length} profile${Object.keys(n).length!==1?"s":""})${H.reset}`);let i=ns.join(process.cwd(),".gitignore");Ye.existsSync(i)&&(Ye.readFileSync(i,"utf-8").includes(".nex/")||await ts("Add .nex/ to .gitignore?",!0)&&(Ye.appendFileSync(i,`
|
|
906
990
|
# nex-code server profiles
|
|
907
991
|
.nex/
|
|
908
|
-
`),console.log(`${
|
|
909
|
-
Set up deploy configs (.nex/deploy.json)?`,!1)&&await
|
|
910
|
-
${
|
|
911
|
-
`)}async function
|
|
912
|
-
${
|
|
913
|
-
`);let i=Object.keys(n);i.length>0&&console.log(`${
|
|
914
|
-
${
|
|
915
|
-
${
|
|
916
|
-
Add another deploy config?`,!1)}
|
|
992
|
+
`),console.log(`${H.green}\u2713 Added .nex/ to .gitignore${H.reset}`))),await ts(`
|
|
993
|
+
Set up deploy configs (.nex/deploy.json)?`,!1)&&await Kf(n,t),console.log(`
|
|
994
|
+
${H.dim}Use /servers to list profiles, /servers ping to check connectivity.${H.reset}
|
|
995
|
+
`)}async function Kf(t,e){let s=e||ns.join(process.cwd(),Gf),o=ns.join(s,"deploy.json"),n={};if(Ye.existsSync(o))try{n=JSON.parse(Ye.readFileSync(o,"utf-8"))}catch{}if(!t){let u=ns.join(s,"servers.json");if(Ye.existsSync(u))try{t=JSON.parse(Ye.readFileSync(u,"utf-8"))}catch{t={}}else t={}}let r=Object.keys(t);console.log(`
|
|
996
|
+
${H.bold}${H.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${H.reset}`),console.log(`${H.bold}${H.cyan}\u2551 Deploy Config Wizard \u2551${H.reset}`),console.log(`${H.bold}${H.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${H.reset}
|
|
997
|
+
`);let i=Object.keys(n);i.length>0&&console.log(`${H.dim}Existing deploy configs: ${i.join(", ")}${H.reset}`);let c={...n},l=!0;for(;l;){console.log(`
|
|
998
|
+
${H.bold}\u2500\u2500\u2500 New Deploy Config \u2500\u2500\u2500${H.reset}`);let u=await ze("Config name (e.g. prod, staging)");if(!u){console.log(`${H.red} Name is required.${H.reset}`);continue}let d;r.length>0?d=await Ta("Target server",r,r[0]):d=await ze("Target server (profile name or user@host)");let f=await Ta("Deploy method",["rsync","git"],"rsync"),p="",h=[],m="";if(f==="rsync"){p=await ze("Local path to sync (e.g. dist/ or ./build)","dist/");let v=await ze("Exclude paths (comma-separated, e.g. node_modules,.env)","node_modules,.env");h=v?v.split(",").map(b=>b.trim()).filter(Boolean):[]}else m=await ze("Branch to pull (leave empty for current remote branch)","main");let g=await ze(f==="git"?"Remote repo path (e.g. /home/jarvis/my-app)":"Remote destination path (e.g. /var/www/app)");if(!g){console.log(`${H.red} Remote path is required.${H.reset}`);continue}let $=await ze("Command to run on remote after deploy (leave empty to skip)",""),y=await ze("Health check URL or remote command (leave empty to skip)",""),x={server:d,method:f,remote_path:g};f==="rsync"?(x.local_path=p,h.length>0&&(x.exclude=h)):m&&(x.branch=m),$&&(x.deploy_script=$),y&&(x.health_check=y),c[u]=x;let _=f==="git"?`${d}:${g}${m?` (${m})`:""}`:`${p.endsWith("/")?p:p+"/"} \u2192 ${d}:${g}`;console.log(`
|
|
999
|
+
${H.green}\u2713${H.reset} Deploy config "${u}": [${f}] ${_}`),$&&console.log(` ${H.dim} Then: ${$}${H.reset}`),y&&console.log(` ${H.dim} Health: ${y}${H.reset}`),l=await ts(`
|
|
1000
|
+
Add another deploy config?`,!1)}Ye.existsSync(s)||Ye.mkdirSync(s,{recursive:!0}),Ye.writeFileSync(o,JSON.stringify(c,null,2)+`
|
|
917
1001
|
`,"utf-8"),console.log(`
|
|
918
|
-
${
|
|
919
|
-
`)}
|
|
920
|
-
`);return`${
|
|
1002
|
+
${H.green}\u2713 Saved .nex/deploy.json (${Object.keys(c).length} config${Object.keys(c).length!==1?"s":""})${H.reset}`),console.log(`${H.dim}Use: deploy prod (or with explicit params)${H.reset}
|
|
1003
|
+
`)}Yf.exports={runServerWizard:c_,runDeployWizard:Kf,setWizardRL:a_}});var Ra=G((Ek,Qf)=>{"use strict";var l_=require("os"),Xf=require("path"),Us=require("fs"),Ws=Xf.join(l_.homedir(),".nex-code","model-routing.json"),mr={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}},Jf=["agentic","frontend","sysadmin","data","coding"];function u_(t){if(!t||t.length<8)return null;for(let e of Jf){let s=mr[e];if(!s.pattern||s.pattern.test(t))return s}return mr.coding}function Vf(){try{if(Us.existsSync(Ws))return JSON.parse(Us.readFileSync(Ws,"utf-8"))}catch{}return{}}function d_(t){let e=mr[t];return e?.envVar&&process.env[e.envVar]?process.env[e.envVar]:Vf()[t]||null}function f_(t){let e=Xf.dirname(Ws);Us.existsSync(e)||Us.mkdirSync(e,{recursive:!0}),Us.writeFileSync(Ws,JSON.stringify(t,null,2))}Qf.exports={CATEGORIES:mr,DETECTION_ORDER:Jf,detectCategory:u_,getModelForCategory:d_,saveRoutingConfig:f_,loadRoutingConfig:Vf,ROUTING_CONFIG_PATH:Ws}});var yr=G((Tk,tp)=>{"use strict";var Ca=require("os"),$r=require("path"),ot=require("fs"),p_=require("axios"),m_=require("https"),hr=$r.join(Ca.homedir(),".nex-code","known-models.json"),h_="https://ollama.com/api/tags",g_=60,$_={"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 Aa(){try{if(ot.existsSync(hr))return JSON.parse(ot.readFileSync(hr,"utf-8"))}catch{}return{benchmarked:[],lastChecked:null}}function y_(t){let e=$r.dirname(hr);ot.existsSync(e)||ot.mkdirSync(e,{recursive:!0}),ot.writeFileSync(hr,JSON.stringify(t,null,2))}function w_(t){let e=Aa(),s=new Set(e.benchmarked);for(let o of t)s.add(o);e.benchmarked=[...s],e.lastChecked=new Date().toISOString(),y_(e)}async function Zf(){let t=process.env.OLLAMA_API_KEY;if(!t)throw new Error("OLLAMA_API_KEY not set");let e=new m_.Agent({keepAlive:!0});return((await p_.get(h_,{headers:{Authorization:`Bearer ${t}`},timeout:15e3,httpsAgent:e})).data?.models||[]).map(o=>(o.name||o.model||"").replace(/:latest$/,"")).filter(Boolean)}async function b_(){let t=await Zf(),e=Aa(),s=new Set(e.benchmarked),o=t.filter(n=>!s.has(n));return{allCloud:t,newModels:o,store:e}}var Oa="<!-- nex-benchmark-start -->",gr="<!-- nex-benchmark-end -->",__={"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 x_(t){return t?t>=25e4?"256K":t>=19e4?"200K":t>=128e3?"131K":t>=64e3?"64K":`${Math.round(t/1024)}K`:"?"}function ep(t,e){let s=["\u{1F947}","\u{1F948}","\u{1F949}"],o=(e||new Date().toISOString()).split("T")[0],n=t.filter(r=>r.score>=g_).map((r,i)=>{let c=s[i]||"\u2014",l=x_($_[r.model]),u=__[r.model]||"\u2014",d=`${(r.avgLatency/1e3).toFixed(1)}s`,f=i===0?`**${r.score}**`:String(r.score);return`| ${c} | \`${r.model}\` | ${f} | ${d} | ${l} | ${u} |`}).join(`
|
|
1004
|
+
`);return`${Oa}
|
|
921
1005
|
<!-- Updated: ${o} \u2014 run \`/benchmark --discover\` after new Ollama Cloud releases -->
|
|
922
1006
|
|
|
923
1007
|
| Rank | Model | Score | Avg Latency | Context | Best For |
|
|
@@ -926,17 +1010,17 @@ ${n}
|
|
|
926
1010
|
|
|
927
1011
|
> Rankings are nex-code-specific: tool name accuracy, argument validity, schema compliance.
|
|
928
1012
|
> Toolathon (Minimax SOTA) measures different task types \u2014 run \`/benchmark --discover\` after model releases.
|
|
929
|
-
${
|
|
930
|
-
`),d="# \u2500\u2500 Task-type routing (auto-updated by /benchmark) \u2500\u2500",f="# \u2500\u2500 end routing \u2500\u2500";if(c.includes(d)){let
|
|
1013
|
+
${gr}`}function k_(t,e){if(!ot.existsSync(e))return!1;let s=ot.readFileSync(e,"utf-8"),o=s.indexOf(Oa),n=s.indexOf(gr);if(o===-1||n===-1)return!1;let r=s.slice(0,o),i=s.slice(n+gr.length),c=ep(t);return ot.writeFileSync(e,r+c+i),!0}function v_(t){let e=$r.join(Ca.homedir(),".nex-code","models.env");if(!ot.existsSync(e)||t.length===0)return{updated:!1,reason:"models.env not found or empty summary"};let s=t[0],o=ot.readFileSync(e,"utf-8"),r=o.match(/^DEFAULT_MODEL=(\S+)/m)?.[1];if(r===s.model)return{updated:!1,reason:"winner unchanged"};let i=t.find(l=>l.model===r);if(i&&s.score-i.score<5)return{updated:!1,reason:`margin ${(s.score-i.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)`),ot.writeFileSync(e,o),{updated:!0,previousModel:r,newModel:s.model}}function S_(t){let{saveRoutingConfig:e}=Ra(),s=$r.join(Ca.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 i=!1;if(ot.existsSync(s)){let c=ot.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(([p])=>t[p]&&t[p].score>0).map(([p,h])=>`${h}=${t[p].model} # ${p} score: ${t[p].score}/100`).join(`
|
|
1014
|
+
`),d="# \u2500\u2500 Task-type routing (auto-updated by /benchmark) \u2500\u2500",f="# \u2500\u2500 end routing \u2500\u2500";if(c.includes(d)){let p=c.indexOf(d),h=c.indexOf(f);h!==-1&&(c=c.slice(0,p)+`${d}
|
|
931
1015
|
${u}
|
|
932
1016
|
${f}`+c.slice(h+f.length))}else c+=`
|
|
933
1017
|
${d}
|
|
934
1018
|
${u}
|
|
935
1019
|
${f}
|
|
936
|
-
`;ze.writeFileSync(s,c),i=!0}return{saved:!0,envUpdated:i,changes:o}}Af.exports={findNewModels:Db,fetchCloudModels:Rf,loadKnownModels:aa,markBenchmarked:jb,updateReadme:Ub,updateModelsEnv:Wb,updateRoutingConfig:Bb,generateBenchmarkBlock:Cf,SENTINEL_START:ca,SENTINEL_END:er}});var gn=q((Gx,Df)=>{"use strict";var{C:I}=be(),Hb=_e(),{TOOL_DEFINITIONS:Of}=ht(),Cs=[{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"],Mf=["minimax-m2.7:cloud","qwen3-coder:480b","devstral-2:123b"],Gb=7,sr={producedToolCall:.2,correctTool:.35,validArgs:.3,schemaCompliant:.15},Kb="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 If(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:Kb},{role:"user",content:t.prompt}],n=Date.now();try{let r=await Hb.callChat(o,Of,{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=Of.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 As(t){return t.error?0:((t.producedToolCall?sr.producedToolCall:0)+(t.correctTool?sr.correctTool:0)+(t.validArgs?sr.validArgs:0)+(t.schemaCompliant?sr.schemaCompliant:0))*100}var Yb={coding:"coding",search:"coding",shell:"coding",schema:"coding","multi-step":"coding",reasoning:"coding",frontend:"frontend",sysadmin:"sysadmin",data:"data",agentic:"agentic"};function la(t){return Object.entries(t).map(([e,s])=>{let o=s.map(As),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=>Yb[d.category]===c);if(l.length===0)continue;let u=l.map(As).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 zb(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 Pf(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(`
|
|
937
|
-
${
|
|
938
|
-
${
|
|
939
|
-
${
|
|
1020
|
+
`;ot.writeFileSync(s,c),i=!0}return{saved:!0,envUpdated:i,changes:o}}tp.exports={findNewModels:b_,fetchCloudModels:Zf,loadKnownModels:Aa,markBenchmarked:w_,updateReadme:k_,updateModelsEnv:v_,updateRoutingConfig:S_,generateBenchmarkBlock:ep,SENTINEL_START:Oa,SENTINEL_END:gr}});var kn=G((Rk,lp)=>{"use strict";var{C:L}=ve(),E_=Se(),{TOOL_DEFINITIONS:np}=kt(),Bs=[{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"))}],sp=["minimax-m2.7:cloud","qwen3-coder:480b","kimi-k2:1t","devstral-2:123b","devstral-small-2:24b"],op=["minimax-m2.7:cloud","qwen3-coder:480b","devstral-2:123b"],T_=7,wr={producedToolCall:.2,correctTool:.35,validArgs:.3,schemaCompliant:.15},R_="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 rp(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:R_},{role:"user",content:t.prompt}],n=Date.now();try{let r=await E_.callChat(o,np,{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=np.find(p=>p.function?.name===l);if(s.validArgs=!!t.validateArgs(u,f),f){let p=f.function?.parameters||{},h=p.required||[],m=Object.keys(p.properties||{});s.schemaCompliant=h.every(g=>u[g]!==void 0)&&Object.keys(u).every(g=>m.includes(g))}}}}catch(r){s.latencyMs=Date.now()-n,s.error=r.message.slice(0,120)}return s}function Hs(t){return t.error?0:((t.producedToolCall?wr.producedToolCall:0)+(t.correctTool?wr.correctTool:0)+(t.validArgs?wr.validArgs:0)+(t.schemaCompliant?wr.schemaCompliant:0))*100}var C_={coding:"coding",search:"coding",shell:"coding",schema:"coding","multi-step":"coding",reasoning:"coding",frontend:"frontend",sysadmin:"sysadmin",data:"data",agentic:"agentic"};function Na(t){return Object.entries(t).map(([e,s])=>{let o=s.map(Hs),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=>C_[d.category]===c);if(l.length===0)continue;let u=l.map(Hs).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 A_(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 ip(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(`
|
|
1021
|
+
${L.bold}${s}${L.reset}`),console.log(r);let i=o.map(u=>u.label.padEnd(u.width)).join(" ");if(console.log(`${L.dim}${i}${L.reset}`),console.log(r),t.forEach((u,d)=>{let f=String(d+1).padEnd(o[0].width),p=u.model.slice(0,o[1].width).padEnd(o[1].width),h=String(u.score).padEnd(o[2].width),m=`${u.toolCallRate}%`.padEnd(o[3].width),g=`${u.correctRate}%`.padEnd(o[4].width),$=`${u.validArgsRate}%`.padEnd(o[5].width),y=`${u.schemaRate}%`.padEnd(o[6].width),x=`${(u.avgLatency/1e3).toFixed(1)}s`.padEnd(o[7].width),_=u.errorCount>0?`${L.red}${u.errorCount}${L.reset}`:`${L.dim}0${L.reset}`,v=u.score>=80?L.green:u.score>=60?L.yellow:L.red,b=d===0?`${L.yellow}${f}${L.reset}`:`${L.dim}${f}${L.reset}`;console.log(`${b} ${v}${p}${L.reset} ${L.bold}${v}${h}${L.reset} ${m} ${g} ${$} ${y} ${L.dim}${x}${L.reset} ${_}`)}),console.log(r),t.length>0){let u=t[0];if(console.log(`
|
|
1022
|
+
${L.bold}${L.green}Winner: ${u.model}${L.reset} score ${u.score}/100`),t.length>1){let d=(u.score-t[1].score).toFixed(1);console.log(`${L.dim}+${d} pts over ${t[1].model}${L.reset}`)}}let c=["coding","frontend","sysadmin","data","agentic"];if(t.some(u=>Object.keys(u.categoryScores).length>1)){console.log(`
|
|
1023
|
+
${L.bold}Best model per task type:${L.reset}`);for(let u of c){let d=t.filter(m=>m.categoryScores[u]!==void 0).sort((m,g)=>g.categoryScores[u]-m.categoryScores[u]);if(d.length===0)continue;let f=d[0],p=f.categoryScores[u],h=p>=80?L.green:p>=60?L.yellow:L.red;console.log(` ${L.dim}${u.padEnd(10)}${L.reset} ${h}${f.model}${L.reset} ${L.dim}${p}/100${L.reset}`)}}console.log()}async function O_({models:t,quick:e=!1,onProgress:s}={}){let o=e?Bs.slice(0,T_):Bs,n=t?.length>0?t:e?op:sp,r={};for(let c of n){r[c]=[];for(let l of o){s?.({model:c,task:l.id,done:!1});let u=await rp(l,c);r[c].push(u),s?.({model:c,task:l.id,done:!0,score:Hs(u),error:u.error})}}let i=Na(r);return ip(i,o.length),i}async function N_({newModels:t,existingRanking:e=[],onProgress:s}={}){if(!t||t.length===0)return e;let o={};for(let i of t){o[i]=[];for(let c of Bs){s?.({model:i,task:c.id,done:!1});let l=await rp(c,i);o[i].push(l),s?.({model:i,task:c.id,done:!0,score:Hs(l),error:l.error})}}let r=[...Na(o)];for(let i of e)r.find(c=>c.model===i.model)||r.push(i);return r.sort((i,c)=>c.score-i.score),ip(r,Bs.length),r}var br=[{id:"simple_question",name:"Simple Convergence",prompt:"What is 2+2?",maxTurns:3,successCriteria:["4"]}];function ap(t){let e=require("fs"),o=require("path").join(t||process.cwd(),".nex","benchmark-config.json");if(!e.existsSync(o))return console.log(`${L.yellow}No scenarios configured.${L.reset} Create ${L.dim}.nex/benchmark-config.json${L.reset} to define your benchmark scenarios.
|
|
940
1024
|
Example:
|
|
941
1025
|
{
|
|
942
1026
|
"scenarios": [
|
|
@@ -949,19 +1033,19 @@ ${I.bold}Best model per task type:${I.reset}`);for(let u of c){let d=t.filter(p=
|
|
|
949
1033
|
}
|
|
950
1034
|
]
|
|
951
1035
|
}
|
|
952
|
-
`),
|
|
953
|
-
`),
|
|
954
|
-
`),
|
|
955
|
-
\u250C\u2500 Benchmark Results ${"\u2500".repeat(r-19)}\u2510`);for(let l of t){let u=l.id.padEnd(20),d=l.name.substring(0,26).padEnd(26),f=`${l.score}/10`.padStart(6),
|
|
956
|
-
`)}function
|
|
957
|
-
`);return}let n=[];try{n=JSON.parse(e.readFileSync(o,"utf-8"))}catch{n=[]}if(!Array.isArray(n)||n.length===0){console.log(`${
|
|
1036
|
+
`),br;try{let n=JSON.parse(e.readFileSync(o,"utf-8"));return!Array.isArray(n.scenarios)||n.scenarios.length===0?(console.log(`${L.yellow}benchmark-config.json has no scenarios \u2014 using defaults.${L.reset}
|
|
1037
|
+
`),br):n.scenarios}catch(n){return console.log(`${L.yellow}Failed to parse benchmark-config.json: ${n.message}${L.reset}
|
|
1038
|
+
`),br}}function cp(t,e){let{scoreMessages:s,_extractToolCalls:o,_getLastAssistantText:n}=zo(),r=s(t),i=r.score,c=[],l=n(t).toLowerCase();e.successCriteria.every(p=>l.includes(p.toLowerCase()))&&(i=Math.min(10,i+1),c.push("+1.0 all success criteria met"));let d=o(t);d.length<e.maxTurns/2&&(i=Math.min(10,i+.5),c.push(`+0.5 efficient (${d.length} tool calls < ${e.maxTurns/2})`)),i=Math.round(i*10)/10;let f=i>=9?"A":i>=8?"B":i>=7?"C":i>=6?"D":"F";return{score:i,grade:f,issues:r.issues,summary:r.summary,bonuses:c}}async function M_(t,e={}){let{spawn:s}=require("child_process"),o=require("fs"),n=require("path"),r=require("os"),i=n.join(r.tmpdir(),`nex-bench-${t.id}-${Date.now()}.txt`);o.writeFileSync(i,t.prompt,"utf-8");let c=n.resolve(__dirname,"..","bin","nex-code.js"),l=e.cwd||process.cwd(),u=[c,"--prompt-file",i,"--delete-prompt-file","--auto","--max-turns",String(t.maxTurns)];return e.model&&u.push("--model",e.model),new Promise(d=>{let f=s(process.execPath,u,{cwd:l,stdio:["ignore","pipe","pipe"],env:{...process.env}}),p=t.maxTurns*60*1e3,h=!1,m=setTimeout(()=>{h=!0;try{f.kill("SIGTERM")}catch{}},p);f.on("close",g=>{clearTimeout(m);try{o.unlinkSync(i)}catch{}let $=n.join(l,".nex","sessions","_autosave.json"),y=[];if(o.existsSync($))try{y=JSON.parse(o.readFileSync($,"utf-8")).messages||[]}catch{}d({messages:y,exitCode:g||0,timedOut:h})}),f.stdout.resume(),f.stderr.resume()})}function P_(t,e,s){let o=t.length>0?Math.round(t.reduce((l,u)=>l+u.score,0)/t.length*10)/10:0,n=o>=9?"A":o>=8?"B":o>=7?"C":o>=6?"D":"F",r=57,i="\u2500".repeat(r);console.log(`
|
|
1039
|
+
\u250C\u2500 Benchmark Results ${"\u2500".repeat(r-19)}\u2510`);for(let l of t){let u=l.id.padEnd(20),d=l.name.substring(0,26).padEnd(26),f=`${l.score}/10`.padStart(6),p=l.grade.padStart(2);console.log(`\u2502 ${u} ${d} ${f} ${p} \u2502`)}console.log(`\u2502 ${" ".repeat(r-2)} \u2502`);let c=`Overall: ${o}/10 (${n}) \xB7 v${e} \xB7 ${s}`;console.log(`\u2502 ${c.substring(0,r-4).padEnd(r-4)} \u2502`),console.log(`\u2514${"\u2500".repeat(r+1)}\u2518
|
|
1040
|
+
`)}function I_(t=10){let e=require("fs"),o=require("path").join(process.cwd(),".nex","benchmark-history.json");if(!e.existsSync(o)){console.log(`${L.yellow}No score history yet. Run a session first.${L.reset}
|
|
1041
|
+
`);return}let n=[];try{n=JSON.parse(e.readFileSync(o,"utf-8"))}catch{n=[]}if(!Array.isArray(n)||n.length===0){console.log(`${L.yellow}Score history is empty.${L.reset}
|
|
958
1042
|
`);return}let r=n.slice(-t);console.log(`
|
|
959
|
-
${
|
|
960
|
-
${
|
|
961
|
-
`);for(let l of r)console.log(` ${
|
|
962
|
-
${
|
|
1043
|
+
${L.bold}Score History (last ${r.length} session${r.length===1?"":"s"}):${L.reset}`);for(let i of r){let c=(i.date||"").replace("T"," ").substring(0,16),l=(i.version||"?").padEnd(8),u=(i.model||"?").substring(0,12).padEnd(12),d=`${i.score}/10`.padStart(6),f=i.grade||"?",p=i.issues&&i.issues.length>0?`${L.yellow}\u26A0 ${i.issues.slice(0,2).map(m=>m.substring(0,30)).join(", ")}${L.reset}`:`${L.green}\u2713${L.reset}`,h=i.score>=8?L.green:i.score>=6?L.yellow:L.red;console.log(` ${L.dim}${c}${L.reset} ${L.dim}v${l}${L.reset} ${L.dim}${u}${L.reset} ${h}${d} ${f}${L.reset} ${p}`)}console.log()}async function L_({dryRun:t=!1,model:e,cwd:s,onProgress:o}={}){let n=Sn(),r=ap(s);if(t){console.log(`
|
|
1044
|
+
${L.bold}Jarvis Benchmark \u2014 Scenarios (dry-run):${L.reset}
|
|
1045
|
+
`);for(let l of r)console.log(` ${L.cyan}${l.id.padEnd(20)}${L.reset} ${L.dim}${l.name}${L.reset} maxTurns=${l.maxTurns}`),console.log(` ${L.dim}${l.prompt.substring(0,80)}${L.reset}`);return console.log(),[]}let i=(()=>{if(e)return e;try{let{getActiveModel:l}=Pn();return l&&l()||"unknown"}catch{return"unknown"}})(),c=[];for(let l of r){o?.({id:l.id,name:l.name,done:!1}),console.log(`
|
|
1046
|
+
${L.dim}Running scenario: ${l.name}...${L.reset}`);let{messages:u,timedOut:d}=await M_(l,{model:i,cwd:s}),f;d||u.length===0?f={score:0,grade:"F",issues:[d?"Scenario timed out":"No messages produced"],summary:"No output",bonuses:[]}:f=cp(u,l);let p={id:l.id,name:l.name,score:f.score,grade:f.grade,issues:f.issues,bonuses:f.bonuses};c.push(p),o?.({id:l.id,name:l.name,done:!0,score:f.score,grade:f.grade});try{let{appendScoreHistory:h}=zo();h(f.score,{version:n.version,model:i,sessionName:`bench:${l.id}`,issues:f.issues})}catch{}}return P_(c,n.version,i),c}lp.exports={runBenchmark:O_,runDiscoverBenchmark:N_,buildSummary:Na,buildCategoryWinners:A_,TASKS:Bs,scoreResult:Hs,DEFAULT_MODELS:sp,QUICK_MODELS:op,runJarvisBenchmark:L_,showScoreTrend:I_,loadScenarios:ap,DEFAULT_SCENARIOS:br,scoreJarvisScenario:cp}});var fp=G((Ck,dp)=>{var j_=require("axios"),Gs=require("fs"),up=require("path"),D_="nex-code",Ma=up.join(process.cwd(),".nex"),Pa=up.join(Ma,"last-version-check");Gs.existsSync(Ma)||Gs.mkdirSync(Ma,{recursive:!0});async function q_(){try{let t=U_(),e=Date.now();if(t&&e-t<1440*60*1e3)return{hasNewVersion:!1};W_(e);let s=F_(),n=(await j_.get(`https://registry.npmjs.org/${D_}/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 F_(){return Sn().version}function U_(){try{if(Gs.existsSync(Pa)){let t=Gs.readFileSync(Pa,"utf8");return parseInt(t,10)}}catch{}return null}function W_(t){try{Gs.writeFileSync(Pa,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}}dp.exports={checkForNewVersion:q_}});var Ep=G((Ok,Sp)=>{var H_=require("readline"),Xe=require("fs"),Me=require("path"),{C:a,banner:G_,cleanupTerminal:pp}=ve(),{isDark:K_}=an(),{listProviders:La,getActiveProviderName:vn,listAllModels:Ak,setFallbackChain:Y_,getFallbackChain:z_,getProvider:X_}=Se(),{flushAutoSave:mp}=Et(),{getActiveModel:Bt,setActiveModel:ja}=Pn(),{printContext:hp}=Ko(),{loadAllSkills:J_,getSkillCommands:xr,handleSkillCommand:V_}=Qt(),{setReadlineInterface:Q_,setAutoConfirm:Z_,getAutoConfirm:gp,setAllowAlwaysHandler:ex}=Ue(),{StickyFooter:tx}=Mf(),_t=process.cwd(),Wt=null;function $p(){return Wt?.signal??null}var zs=[{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:"/bench [--dry-run] [--model=<spec>]",desc:"Run Jarvis scenario benchmark (5 agentic tasks)"},{cmd:"/trend [n]",desc:"Show score history trend (default: last 10 sessions)"},{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 yp(){let t=xr(),e=[...zs,...t],s=Math.max(...e.map(o=>o.cmd.length));console.log("");for(let{cmd:o,desc:n}of zs)console.log(` ${a.cyan}${o.padEnd(s+2)}${a.reset}${a.dim}${n}${a.reset}`);for(let{cmd:o,desc:n}of t)console.log(` ${a.cyan}${o.padEnd(s+2)}${a.reset}${a.dim}${n} ${a.yellow}[skill]${a.reset}`);console.log(`
|
|
963
1047
|
${a.dim}Type /help for detailed usage${a.reset}
|
|
964
|
-
`)}function
|
|
1048
|
+
`)}function wp(t){try{let e,s;t.endsWith("/")||t.endsWith(Me.sep)?(e=t,s=""):(e=Me.dirname(t),s=Me.basename(t)),e.startsWith("~")&&(e=Me.join(require("os").homedir(),e.slice(1)));let o=Me.isAbsolute(e)?e:Me.resolve(_t,e);if(!Xe.existsSync(o)||!Xe.statSync(o).isDirectory())return[];let n=Xe.readdirSync(o,{withFileTypes:!0}),r=[];for(let i of n){if(i.name.startsWith(".")||i.name==="node_modules"||s&&!i.name.startsWith(s))continue;let c=t.endsWith("/")||t.endsWith(Me.sep)?t:Me.dirname(t)+"/",l=c==="./"&&!t.startsWith("./")?i.name:c+i.name;r.push(i.isDirectory()?l+"/":l)}return r}catch{return[]}}function bp(t){if(t.startsWith("/")){let o=[...zs,...xr()],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("~"))?[wp(s),s]:[[],t]}function _p(){console.log(`
|
|
965
1049
|
${a.bold}${a.cyan}Commands:${a.reset}
|
|
966
1050
|
${a.cyan}/help${a.reset} ${a.dim}Show this help${a.reset}
|
|
967
1051
|
${a.cyan}/model [spec]${a.reset} ${a.dim}Show/switch model (e.g. openai:gpt-4o, claude-sonnet)${a.reset}
|
|
@@ -1026,54 +1110,59 @@ ${a.bold}${a.cyan}Undo / Redo:${a.reset}
|
|
|
1026
1110
|
${a.cyan}/benchmark --models=a,b${a.reset}${a.dim} Custom model list${a.reset}
|
|
1027
1111
|
|
|
1028
1112
|
${a.cyan}/exit${a.reset} ${a.dim}Quit${a.reset}
|
|
1029
|
-
`)}function
|
|
1030
|
-
${a.bold}${a.cyan}Providers:${a.reset}`);for(let o of t){let n=o.provider===e,r=o.configured?`${a.green}\u2713${a.reset}`:`${a.red}\u2717${a.reset}`,i=n?` ${a.cyan}(active)${a.reset}`:"";console.log(` ${r} ${a.bold}${o.provider}${a.reset}${i}`);for(let c of o.models){let l=c.id===s.id&&n?` ${a.yellow}\u25C4${a.reset}`:"";console.log(` ${a.dim}${c.id}${a.reset} \u2014 ${c.name}${l}`)}}console.log()}async function
|
|
1031
|
-
${a.bold}${a.cyan}Token Usage:${a.reset}`),console.log(` ${a.dim}Model:${a.reset} ${d}:${u.id} (${(l.limit/1e3).toFixed(0)}k context)`),console.log(` ${a.dim}Used:${a.reset} ${l.used.toLocaleString()} / ${l.limit.toLocaleString()} (${l.percentage}%)`);let f=
|
|
1032
|
-
${a.dim}Breakdown:${a.reset}`),console.log(` System prompt: ${l.breakdown.system.toLocaleString()} tokens`),console.log(` Conversation: ${l.breakdown.conversation.toLocaleString()} tokens`),console.log(` Tool results: ${l.breakdown.toolResults.toLocaleString()} tokens`),console.log(` Tool definitions: ${l.breakdown.toolDefinitions.toLocaleString()} tokens`),console.log(` Messages: ${l.messageCount}`),console.log(),!0}case"/costs":{let{formatCosts:n,resetCosts:r}=
|
|
1113
|
+
`)}function xp(t){let s=Math.round(t/100*30),o=30-s;return` ${t>80?a.red:t>50?a.yellow:a.green}${"\u2588".repeat(s)}${a.dim}${"\u2591".repeat(o)}${a.reset} ${t}%`}function Ia(){let t=La(),e=vn(),s=Bt();console.log(`
|
|
1114
|
+
${a.bold}${a.cyan}Providers:${a.reset}`);for(let o of t){let n=o.provider===e,r=o.configured?`${a.green}\u2713${a.reset}`:`${a.red}\u2717${a.reset}`,i=n?` ${a.cyan}(active)${a.reset}`:"";console.log(` ${r} ${a.bold}${o.provider}${a.reset}${i}`);for(let c of o.models){let l=c.id===s.id&&n?` ${a.yellow}\u25C4${a.reset}`:"";console.log(` ${a.dim}${c.id}${a.reset} \u2014 ${c.name}${l}`)}}console.log()}async function kp(t,e){let[s,...o]=t.split(/\s+/);switch(s){case"/help":return _p(),!0;case"/model":{let n=o.join(" ").trim();if(!n){if(e){let{showModelPicker:r}=Lf();await r(e)}else{let r=Bt(),i=vn();console.log(`${a.bold}${a.cyan}Active model:${a.reset} ${a.dim}${i}:${r.id} (${r.name})${a.reset}`),console.log(`${a.gray}Use /model <provider:model> to switch. /providers to see all.${a.reset}`)}return!0}if(n==="list")return Ia(),!0;if(ja(n)){let r=Bt(),i=vn();console.log(`${a.green}Switched to ${i}:${r.id} (${r.name})${a.reset}`)}else console.log(`${a.red}Unknown model: ${n}${a.reset}`),console.log(`${a.gray}Use /providers to see available models${a.reset}`);return!0}case"/providers":return Ia(),!0;case"/fallback":{let n=o.join(" ").trim();if(!n){let i=z_();return i.length===0?(console.log(`${a.dim}No fallback chain configured${a.reset}`),console.log(`${a.dim}Use /fallback anthropic,openai,local to set${a.reset}`)):console.log(`${a.bold}${a.cyan}Fallback chain:${a.reset} ${i.join(" \u2192 ")}`),!0}let r=n.split(",").map(i=>i.trim()).filter(Boolean);return Y_(r),console.log(`${a.green}Fallback chain: ${r.join(" \u2192 ")}${a.reset}`),!0}case"/tokens":{let{getConversationMessages:n}=$e(),{getUsage:r}=He(),{TOOL_DEFINITIONS:i}=kt(),c=n(),l=r(c,i),u=Bt(),d=vn();console.log(`
|
|
1115
|
+
${a.bold}${a.cyan}Token Usage:${a.reset}`),console.log(` ${a.dim}Model:${a.reset} ${d}:${u.id} (${(l.limit/1e3).toFixed(0)}k context)`),console.log(` ${a.dim}Used:${a.reset} ${l.used.toLocaleString()} / ${l.limit.toLocaleString()} (${l.percentage}%)`);let f=xp(l.percentage);return console.log(` ${f}`),console.log(`
|
|
1116
|
+
${a.dim}Breakdown:${a.reset}`),console.log(` System prompt: ${l.breakdown.system.toLocaleString()} tokens`),console.log(` Conversation: ${l.breakdown.conversation.toLocaleString()} tokens`),console.log(` Tool results: ${l.breakdown.toolResults.toLocaleString()} tokens`),console.log(` Tool definitions: ${l.breakdown.toolDefinitions.toLocaleString()} tokens`),console.log(` Messages: ${l.messageCount}`),console.log(),!0}case"/costs":{let{formatCosts:n,resetCosts:r}=Mn();return o.join(" ").trim()==="reset"?(r(),console.log(`${a.green}Cost tracking reset${a.reset}`),!0):(console.log(`
|
|
1033
1117
|
${n()}
|
|
1034
|
-
`),!0)}case"/budget":{let{getCostLimits:n,getProviderSpend:r,checkBudget:i,removeCostLimit:c,saveCostLimits:l,setCostLimit:u}=
|
|
1035
|
-
${a.bold}${a.cyan}Cost Limits:${a.reset}`);let g=!1;for(let
|
|
1118
|
+
`),!0)}case"/budget":{let{getCostLimits:n,getProviderSpend:r,checkBudget:i,removeCostLimit:c,saveCostLimits:l,setCostLimit:u}=Mn(),d=o[0];if(!d){let h=n(),m=La();console.log(`
|
|
1119
|
+
${a.bold}${a.cyan}Cost Limits:${a.reset}`);let g=!1;for(let $ of m){let y=r($.provider),x=h[$.provider];if(x!==void 0){g=!0;let _=Math.min(100,Math.round(y/x*100)),v=10,b=Math.round(_/100*v),k=v-b,O=`${_>=100?a.red:_>=80?a.yellow:a.green}${"\u2588".repeat(b)}${a.dim}${"\u2591".repeat(k)}${a.reset}`;console.log(` ${a.bold}${$.provider}:${a.reset} $${y.toFixed(2)} / $${x.toFixed(2)} (${_}%) ${O}`)}else $.provider==="ollama"||$.provider==="local"?console.log(` ${a.bold}${$.provider}:${a.reset} ${a.dim}free (no limit)${a.reset}`):y>0&&console.log(` ${a.bold}${$.provider}:${a.reset} $${y.toFixed(2)} ${a.dim}(no limit)${a.reset}`)}return g||console.log(` ${a.dim}No limits set. Use /budget <provider> <amount> to set one.${a.reset}`),console.log(),!0}let f=o[1];if(!f){let h=i(d);return h.limit!==null?console.log(`${a.bold}${d}:${a.reset} $${h.spent.toFixed(2)} / $${h.limit.toFixed(2)} ($${h.remaining.toFixed(2)} remaining)`):console.log(`${a.bold}${d}:${a.reset} $${h.spent.toFixed(2)} ${a.dim}(no limit)${a.reset}`),!0}if(f==="off"||f==="remove"||f==="clear")return c(d),l(),console.log(`${a.green}Removed cost limit for ${d}${a.reset}`),!0;let p=parseFloat(f);return isNaN(p)||p<=0?(console.log(`${a.red}Invalid amount: ${f}. Use a positive number or 'off'.${a.reset}`),!0):(u(d,p),l(),console.log(`${a.green}Set ${d} budget limit: $${p.toFixed(2)}${a.reset}`),!0)}case"/clear":{let{clearConversation:n,getConversationMessages:r}=$e(),{clearHistory:i}=It(),c=r();if(c.filter(d=>d.role==="user").length>=4){process.stdout.write(`${a.dim}Reflecting on session...${a.reset} `);let{learnFromSession:d}=Sa();d(c).then(f=>{if(!f.skipped&&!f.error&&(f.applied.length>0||f.nexAdded.length>0)){let p=f.applied.length+f.nexAdded.length;process.stdout.write(`${a.green}${p} learning(s) saved${a.reset}
|
|
1036
1120
|
`)}else process.stdout.write(`${a.dim}nothing new${a.reset}
|
|
1037
1121
|
`)}).catch(()=>process.stdout.write(`
|
|
1038
|
-
`))}n(),i();let{deleteSession:u}=
|
|
1122
|
+
`))}n(),i();let{deleteSession:u}=Et();return u("_autosave"),console.log(`${a.green}Conversation cleared${a.reset}`),!0}case"/context":return await hp(_t),!0;case"/tree":{let{generateFileTree:n}=Ko(),r=parseInt(o.join(" ").trim(),10),i=!isNaN(r)&&r>0?Math.min(r,8):3,c=n(_t,{maxDepth:i,maxFiles:300});return console.log(`
|
|
1039
1123
|
${a.bold}${a.cyan}Project tree${a.reset}${a.dim} (depth ${i})${a.reset}
|
|
1040
1124
|
`),console.log(`${a.dim}${c}${a.reset}
|
|
1041
|
-
`),!0}case"/autoconfirm":{let n=!
|
|
1042
|
-
${a.bold}${a.cyan}Sessions:${a.reset}`);for(let i of r){let c=i.updatedAt?new Date(i.updatedAt).toLocaleString():"?",l=i.name==="_autosave"?` ${a.dim}(auto)${a.reset}`:"",u=i.score!=null?` \xB7 score ${i.score}/10${i.scoreGrade?` (${i.scoreGrade})`:""}`:"";console.log(` ${a.cyan}${i.name}${a.reset}${l} \u2014 ${i.messageCount} msgs, ${c}${a.dim}${u}${a.reset}`)}return console.log(),!0}case"/resume":{let{getLastSession:n}=
|
|
1043
|
-
${a.bold}${a.cyan}Memory:${a.reset}`);for(let i of r)console.log(` ${a.cyan}${i.key}${a.reset} = ${i.value}`);return console.log(),!0}case"/brain":{let{listDocuments:n,readDocument:r,writeDocument:i,removeDocument:c,buildIndex:l,buildEmbeddingIndex:u,isEmbeddingAvailable:d,query:f}=
|
|
1044
|
-
|
|
1045
|
-
`);let g=require("path").join(process.cwd(),".nex","brain",`${h}.md`);console.log(`${a.green}Created .nex/brain/${h}.md${a.reset}`),console.log(`${a.dim}Edit it directly at: ${g}${a.reset}`)}else{let g=h.substring(0,
|
|
1046
|
-
${a.bold}${a.cyan}Brain Documents:${a.reset}`);let g=Math.max(8,...
|
|
1047
|
-
${a.bold}${a.cyan}Brain Search: "${h}"${a.reset}`);for(let g of
|
|
1048
|
-
${a.cyan}${g.name}${a.reset} ${a.dim}(score: ${
|
|
1125
|
+
`),!0}case"/autoconfirm":{let n=!gp();return Z_(n),console.log(`${a.green}Auto-confirm: ${n?"ON":"OFF"}${a.reset}`),n&&console.log(`${a.yellow} \u26A0 File changes will be applied without confirmation${a.reset}`),Ks(),!0}case"/save":{let{saveSession:n}=Et(),{getConversationMessages:r}=$e(),i=o.join(" ").trim()||`session-${Date.now()}`,c=r();if(c.length===0)return console.log(`${a.yellow}No conversation to save${a.reset}`),!0;let l=Bt(),u=vn();return n(i,c,{model:l.id,provider:u}),console.log(`${a.green}Session saved: ${i} (${c.length} messages)${a.reset}`),!0}case"/load":{let{loadSession:n}=Et(),{setConversationMessages:r}=$e(),i=o.join(" ").trim();if(!i)return console.log(`${a.red}Usage: /load <name>${a.reset}`),!0;let c=n(i);return c?(r(c.messages),console.log(`${a.green}Loaded session: ${c.name} (${c.messageCount} messages)${a.reset}`),!0):(console.log(`${a.red}Session not found: ${i}${a.reset}`),!0)}case"/sessions":{let{listSessions:n}=Et(),r=n();if(r.length===0)return console.log(`${a.dim}No saved sessions${a.reset}`),!0;console.log(`
|
|
1126
|
+
${a.bold}${a.cyan}Sessions:${a.reset}`);for(let i of r){let c=i.updatedAt?new Date(i.updatedAt).toLocaleString():"?",l=i.name==="_autosave"?` ${a.dim}(auto)${a.reset}`:"",u=i.score!=null?` \xB7 score ${i.score}/10${i.scoreGrade?` (${i.scoreGrade})`:""}`:"";console.log(` ${a.cyan}${i.name}${a.reset}${l} \u2014 ${i.messageCount} msgs, ${c}${a.dim}${u}${a.reset}`)}return console.log(),!0}case"/resume":{let{getLastSession:n}=Et(),{setConversationMessages:r}=$e(),i=n();return i?(r(i.messages),console.log(`${a.green}Resumed: ${i.name} (${i.messageCount} messages)${a.reset}`),!0):(console.log(`${a.yellow}No session to resume${a.reset}`),!0)}case"/remember":{let{remember:n}=nn(),r=o.join(" ").trim();if(!r)return console.log(`${a.red}Usage: /remember <key>=<value> or /remember <text>${a.reset}`),!0;let i=r.indexOf("="),c,l;return i>0?(c=r.substring(0,i).trim(),l=r.substring(i+1).trim()):(c=r.substring(0,40).replace(/\s+/g,"-"),l=r),n(c,l),console.log(`${a.green}Remembered: ${c}${a.reset}`),!0}case"/forget":{let{forget:n}=nn(),r=o.join(" ").trim();return r?(n(r)?console.log(`${a.green}Forgotten: ${r}${a.reset}`):console.log(`${a.red}Memory not found: ${r}${a.reset}`),!0):(console.log(`${a.red}Usage: /forget <key>${a.reset}`),!0)}case"/memory":{let{listMemories:n}=nn(),r=n();if(r.length===0)return console.log(`${a.dim}No memories saved${a.reset}`),!0;console.log(`
|
|
1127
|
+
${a.bold}${a.cyan}Memory:${a.reset}`);for(let i of r)console.log(` ${a.cyan}${i.key}${a.reset} = ${i.value}`);return console.log(),!0}case"/brain":{let{listDocuments:n,readDocument:r,writeDocument:i,removeDocument:c,buildIndex:l,buildEmbeddingIndex:u,isEmbeddingAvailable:d,query:f}=vs(),p=o[0],h=o.slice(1).join(" ").trim();switch(p){case"add":{if(!h)return console.log(`${a.red}Usage: /brain add <name> [content]${a.reset}`),console.log(`${a.dim} /brain add api-notes \u2014 creates empty file${a.reset}`),console.log(`${a.dim} /brain add api-notes This is content \u2014 writes directly${a.reset}`),!0;let m=h.indexOf(" ");if(m<0){i(h,`# ${h}
|
|
1128
|
+
|
|
1129
|
+
`);let g=require("path").join(process.cwd(),".nex","brain",`${h}.md`);console.log(`${a.green}Created .nex/brain/${h}.md${a.reset}`),console.log(`${a.dim}Edit it directly at: ${g}${a.reset}`)}else{let g=h.substring(0,m),$=h.substring(m+1);i(g,$),console.log(`${a.green}Added to brain: ${g}${a.reset}`)}return!0}case"list":{let m=n();if(m.length===0)return console.log(`${a.dim}No brain documents yet. Use /brain add <name> to create one.${a.reset}`),!0;console.log(`
|
|
1130
|
+
${a.bold}${a.cyan}Brain Documents:${a.reset}`);let g=Math.max(8,...m.map(y=>y.name.length)),$=20;console.log(` ${"Name".padEnd(g+2)}${"Tags".padEnd($)}${"Size".padStart(7)} Modified`),console.log(` ${"-".repeat(g+2)}${"-".repeat($)}${"-".repeat(7)} --------`);for(let y of m){let{frontmatter:x}=r(y.name),_=Array.isArray(x.tags)?x.tags.join(", "):"",v=y.size<1024?`${y.size}B`:`${(y.size/1024).toFixed(1)}K`,b=y.modified.toLocaleDateString();console.log(` ${a.cyan}${y.name.padEnd(g+2)}${a.reset}${a.dim}${_.substring(0,$-1).padEnd($)}${v.padStart(7)} ${b}${a.reset}`)}return console.log(),!0}case"search":{if(!h)return console.log(`${a.red}Usage: /brain search <query>${a.reset}`),!0;let m=await f(h,{topK:5});if(m.length===0)return console.log(`${a.dim}No matching brain documents for: ${h}${a.reset}`),!0;console.log(`
|
|
1131
|
+
${a.bold}${a.cyan}Brain Search: "${h}"${a.reset}`);for(let g of m){let $=typeof g.score=="number"?g.score.toFixed(2):g.score;console.log(`
|
|
1132
|
+
${a.cyan}${g.name}${a.reset} ${a.dim}(score: ${$})${a.reset}`),console.log(` ${a.dim}${g.excerpt||""}${a.reset}`)}return console.log(),!0}case"show":{if(!h)return console.log(`${a.red}Usage: /brain show <name>${a.reset}`),!0;let m=r(h);return m.content?(console.log(`
|
|
1049
1133
|
${a.bold}${a.cyan}${h}.md${a.reset}
|
|
1050
|
-
`),console.log(
|
|
1051
|
-
${a.bold}${a.cyan}Brain Status${a.reset}`),console.log(` Documents: ${
|
|
1134
|
+
`),console.log(m.content),!0):(console.log(`${a.red}Document not found: ${h}${a.reset}`),!0)}case"remove":{if(!h)return console.log(`${a.red}Usage: /brain remove <name>${a.reset}`),!0;let{confirm:m}=Ue();if(!await m(`Remove brain document "${h}"?`))return console.log(`${a.dim}Cancelled${a.reset}`),!0;let $=c(h);return console.log($?`${a.green}Removed: ${h}.md${a.reset}`:`${a.red}Document not found: ${h}${a.reset}`),!0}case"rebuild":{let m=l(),g=Object.keys(m.documents).length;return console.log(`${a.green}Index rebuilt: ${g} document(s)${a.reset}`),!0}case"embed":{if(!await d())return console.log(`${a.yellow}Ollama embedding model not available.${a.reset}`),console.log(`${a.dim}Set NEX_EMBED_MODEL env var (default: nomic-embed-text) and ensure Ollama is running.${a.reset}`),!0;console.log(`${a.dim}Building embedding index...${a.reset}`);try{let g=await u(),$=Object.keys(g.documents||{}).length;console.log(`${a.green}Embedding index built: ${$} document(s)${a.reset}`)}catch(g){console.log(`${a.red}Embedding failed: ${g.message}${a.reset}`)}return!0}case"status":{let m=n(),g=require("fs"),$=require("path"),y=$.join(process.cwd(),".nex","brain",".brain-index.json"),x=$.join(process.cwd(),".nex","brain",".embeddings.json");if(console.log(`
|
|
1135
|
+
${a.bold}${a.cyan}Brain Status${a.reset}`),console.log(` Documents: ${m.length}`),console.log(` Index: ${g.existsSync(y)?a.green+"present"+a.reset:a.dim+"not built"+a.reset}`),console.log(` Embeddings: ${g.existsSync(x)?a.green+"present"+a.reset:a.dim+"not built (run /brain embed)"+a.reset}`),m.length>0){let _=m.reduce((v,b)=>v+b.size,0);console.log(` Total size: ${_<1024?_+"B":(_/1024).toFixed(1)+"K"}`)}return console.log(),!0}case"review":{let{exec:m}=require("child_process"),{promisify:g}=require("util"),$=g(m);try{let{stdout:y}=await $("git diff .nex/brain/",{cwd:process.cwd()});y.trim()?(console.log(`
|
|
1052
1136
|
${a.bold}${a.cyan}Brain Changes (git diff):${a.reset}
|
|
1053
|
-
`),console.log(
|
|
1137
|
+
`),console.log(y)):console.log(`${a.dim}No pending brain changes (clean git state)${a.reset}`)}catch{console.log(`${a.dim}Not a git repo or no brain dir${a.reset}`)}return!0}case"undo":{let m=require("fs"),$=require("path").join(process.cwd(),".nex","brain");if(!m.existsSync($))return console.log(`${a.dim}No brain directory found${a.reset}`),!0;let y=n();if(y.length===0)return console.log(`${a.dim}No brain documents to undo${a.reset}`),!0;let x=y[0],{exec:_}=require("child_process"),{promisify:v}=require("util"),b=v(_);try{await b(`git checkout -- ".nex/brain/${x.name}.md"`,{cwd:process.cwd()}),l(),console.log(`${a.green}Undone: restored ${x.name}.md from git${a.reset}`)}catch{console.log(`${a.red}Could not undo \u2014 not tracked in git or no prior version${a.reset}`)}return!0}default:{let m=n();if(m.length===0)console.log(`
|
|
1054
1138
|
${a.bold}${a.cyan}Brain Knowledge Base${a.reset}`),console.log(`${a.dim}No documents yet. Create with /brain add <name>${a.reset}`),console.log(`
|
|
1055
1139
|
${a.dim}Commands: add \xB7 list \xB7 search \xB7 show \xB7 remove \xB7 rebuild \xB7 embed \xB7 status \xB7 review \xB7 undo${a.reset}
|
|
1056
1140
|
`);else{console.log(`
|
|
1057
|
-
${a.bold}${a.cyan}Brain: ${
|
|
1141
|
+
${a.bold}${a.cyan}Brain: ${m.length} document(s)${a.reset}`);for(let g of m){let{frontmatter:$}=r(g.name),y=Array.isArray($.tags)?` [${$.tags.join(", ")}]`:"";console.log(` ${a.cyan}${g.name}${a.reset}${a.dim}${y}${a.reset}`)}console.log(`
|
|
1058
1142
|
${a.dim}Use /brain search <query> \xB7 /brain show <name> \xB7 /brain add <name>${a.reset}
|
|
1059
|
-
`)}return!0}}}case"/learn":{let{learnFromSession:n,learnBrainFromSession:r}=
|
|
1143
|
+
`)}return!0}}}case"/learn":{let{learnFromSession:n,learnBrainFromSession:r}=Sa(),{getConversationMessages:i}=$e(),c=i(),l=c.filter(u=>u.role==="user").length;if(l<4)return console.log(`${a.yellow}Session too short to learn from (need 4+ user messages, have ${l})${a.reset}`),!0;console.log(`${a.dim}Analyzing session for learnings...${a.reset}`);try{let[u,d]=await Promise.all([n(c),r(c)]);if(u.skipped&&(!d.written||d.written.length===0))return console.log(`${a.dim}Session too short${a.reset}`),!0;u.error&&console.log(`${a.red}Reflection error: ${u.error}${a.reset}`),console.log(""),u.summary&&(console.log(`${a.bold}Session:${a.reset} ${a.dim}${u.summary}${a.reset}`),console.log(""));let f=u.applied&&u.applied.length>0,p=u.nexAdded&&u.nexAdded.length>0,h=d.written&&d.written.length>0;if(!f&&!p&&!h)console.log(`${a.dim}No new learnings extracted from this session${a.reset}`);else{if(f){console.log(`${a.bold}${a.cyan}Memory updates:${a.reset}`);for(let{key:m,value:g,action:$}of u.applied){let y=$==="updated"?`${a.yellow}~${a.reset}`:`${a.green}+${a.reset}`;console.log(` ${y} ${a.bold}${m}${a.reset} = ${g}`)}}if(p){console.log(`${a.bold}${a.cyan}Added to NEX.md:${a.reset}`);for(let m of u.nexAdded)console.log(` ${a.green}+${a.reset} ${m}`)}if(h){console.log(`${a.bold}${a.cyan}Brain documents:${a.reset}`);for(let{name:m,reason:g,action:$}of d.written){let y=$==="updated"?`${a.yellow}~${a.reset}`:`${a.green}+${a.reset}`;console.log(` ${y} ${a.bold}${m}.md${a.reset}${g?a.dim+" \u2014 "+g+a.reset:""}`)}}}console.log("")}catch(u){console.log(`${a.red}Learn failed: ${u.message}${a.reset}`)}return!0}case"/optimize":{let{getConversationMessages:n}=$e(),{getUsage:r}=He(),{TOOL_DEFINITIONS:i}=kt(),{listMemories:c}=nn(),l=n(),u=r(l,i),d=Bt(),f=vn(),p=c();console.log(`
|
|
1060
1144
|
${a.bold}${a.cyan}Optimization Report${a.reset}
|
|
1061
1145
|
`);let h=u.percentage>80?a.red:u.percentage>50?a.yellow:a.green;if(console.log(`${a.bold}Context Window:${a.reset} ${h}${u.percentage}%${a.reset} used (${u.used.toLocaleString()} / ${u.limit.toLocaleString()} tokens)`),u.percentage>75?console.log(` ${a.yellow}\u2192 Tip: Use /clear to free context (auto-learns first)${a.reset}`):u.percentage>50?console.log(` ${a.dim}\u2192 Context is filling up, consider /clear soon${a.reset}`):console.log(` ${a.green}\u2192 Context healthy${a.reset}`),console.log(`
|
|
1062
|
-
${a.bold}Memory:${a.reset} ${
|
|
1063
|
-
${a.bold}Active Model:${a.reset} ${f}:${d.id}`);let
|
|
1064
|
-
${a.bold}Session:${a.reset} ${g} turns, ${l.length} messages total`),g>=4&&g%10===0&&console.log(` ${a.cyan}\u2192 Good time to /learn and capture session insights${a.reset}`);let y=
|
|
1065
|
-
${a.bold}Quick Wins:${a.reset}`);for(let
|
|
1146
|
+
${a.bold}Memory:${a.reset} ${p.length} entries`),p.length===0)console.log(` ${a.yellow}\u2192 No memories yet. Use /learn after sessions or /remember key=value${a.reset}`);else{let _=[...p].sort((k,R)=>new Date(R.updatedAt)-new Date(k.updatedAt))[0],v=_?Math.round((Date.now()-new Date(_.updatedAt))/6e4):null,b=v!==null?v<60?`${v}m ago`:`${Math.round(v/60)}h ago`:"?";console.log(` ${a.dim}Latest update: ${b}${a.reset}`),p.length>30&&console.log(` ${a.yellow}\u2192 Many memories (${p.length}) \u2014 consider pruning with /forget${a.reset}`)}console.log(`
|
|
1147
|
+
${a.bold}Active Model:${a.reset} ${f}:${d.id}`);let m=d.contextWindow||d.maxTokens||0;m>0&&m<32e3&&l.length>10?console.log(` ${a.yellow}\u2192 Small context window (${(m/1e3).toFixed(0)}k). Consider /model for larger context${a.reset}`):m>=128e3&&console.log(` ${a.green}\u2192 Large context window (${(m/1e3).toFixed(0)}k) \u2014 good for long sessions${a.reset}`);let g=l.filter(x=>x.role==="user").length;console.log(`
|
|
1148
|
+
${a.bold}Session:${a.reset} ${g} turns, ${l.length} messages total`),g>=4&&g%10===0&&console.log(` ${a.cyan}\u2192 Good time to /learn and capture session insights${a.reset}`);let $=[],y=require("path").join(process.cwd(),"NEX.md");if(require("fs").existsSync(y)||$.push("Create NEX.md in project root to give nex-code project-specific instructions"),$.length>0){console.log(`
|
|
1149
|
+
${a.bold}Quick Wins:${a.reset}`);for(let x of $)console.log(` ${a.cyan}\u2192${a.reset} ${x}`)}return console.log(""),!0}case"/plan":{let{getActivePlan:n,approvePlan:r,startExecution:i,setPlanMode:c,getPlanContent:l,getPlanContent:u,formatPlan:d,extractStepsFromText:f,createPlan:p}=Ft(),{invalidateSystemPromptCache:h}=$e(),m=o.join(" ").trim();if(m==="status"){let g=n();return console.log(d(g)),!0}if(m==="edit"){let g=l();if(!g)return console.log(`${a.yellow}No plan to edit. Generate a plan first with /plan${a.reset}`),!0;let $=require("os"),y=require("path").join($.tmpdir(),`nex-plan-${Date.now()}.md`);require("fs").writeFileSync(y,g,"utf-8");let x=process.env.EDITOR||process.env.VISUAL||"nano",{spawnSync:_}=require("child_process");if(console.log(`${a.dim}Opening plan in ${x}... (save and close to update)${a.reset}`),_(x,[y],{stdio:"inherit"}).status===0){let{setPlanContent:b}=Ft(),k=require("fs").readFileSync(y,"utf-8");b(k);let R=f(k);if(R.length>0){let P=n()?.task||"Task";p(P,R),console.log(`${a.green}Plan updated \u2014 ${R.length} steps extracted.${a.reset}`)}else console.log(`${a.green}Plan updated.${a.reset}`)}else console.log(`${a.yellow}Editor exited with error \u2014 plan unchanged.${a.reset}`);try{require("fs").unlinkSync(y)}catch{}return!0}if(m==="approve"){let g=l();if(r()){i(),c(!1),Ks(),h();let y=n()?.steps?.length||0,x=y>0?` (${y} steps)`:"";if(console.log(`${a.green}${a.bold}Plan approved!${a.reset}${x} Executing...`),console.log(`${a.dim}Plan mode disabled \u2014 all tools now available.${a.reset}`),g){let{processInput:_}=$e(),v=`[PLAN APPROVED \u2014 EXECUTE NOW]
|
|
1150
|
+
|
|
1151
|
+
Implement the following plan step by step. All tools are now available.
|
|
1152
|
+
|
|
1153
|
+
${g}`;try{await _(v)}catch(b){console.log(`${a.red}Error: ${b.message?.split(`
|
|
1154
|
+
`)[0]}${a.reset}`)}}}else console.log(`${a.red}No plan to approve. Enter plan mode first with /plan${a.reset}`);return!0}return c(!0),Ks(),h(),console.log(`
|
|
1066
1155
|
${a.cyan}${a.bold}\u250C\u2500 PLAN MODE \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510${a.reset}
|
|
1067
1156
|
${a.cyan}${a.bold}\u2502${a.reset} Analysis only \u2014 no file changes until approved ${a.cyan}${a.bold}\u2502${a.reset}
|
|
1068
1157
|
${a.cyan}${a.bold}\u2502${a.reset} ${a.dim}Read-only tools only \xB7 /plan approve to execute${a.reset} ${a.cyan}${a.bold}\u2502${a.reset}
|
|
1069
|
-
${a.cyan}${a.bold}\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518${a.reset}`),
|
|
1070
|
-
${a.bold}${a.cyan}Plans:${a.reset}`);for(let i of r){let c=i.status==="completed"?`${a.green}\u2713`:i.status==="executing"?`${a.blue}\u2192`:`${a.dim}\u25CB`;console.log(` ${c} ${a.reset}${a.bold}${i.name}${a.reset} \u2014 ${i.task||"?"} (${i.steps} steps, ${i.status})`)}return console.log(),!0}case"/auto":{let{getAutonomyLevel:n,setAutonomyLevel:r,AUTONOMY_LEVELS:i}=
|
|
1158
|
+
${a.cyan}${a.bold}\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518${a.reset}`),m&&console.log(`${a.dim}Task: ${m}${a.reset}`),!0}case"/plans":{let{listPlans:n}=Ft(),r=n();if(r.length===0)return console.log(`${a.dim}No saved plans${a.reset}`),!0;console.log(`
|
|
1159
|
+
${a.bold}${a.cyan}Plans:${a.reset}`);for(let i of r){let c=i.status==="completed"?`${a.green}\u2713`:i.status==="executing"?`${a.blue}\u2192`:`${a.dim}\u25CB`;console.log(` ${c} ${a.reset}${a.bold}${i.name}${a.reset} \u2014 ${i.task||"?"} (${i.steps} steps, ${i.status})`)}return console.log(),!0}case"/auto":{let{getAutonomyLevel:n,setAutonomyLevel:r,AUTONOMY_LEVELS:i}=Ft(),c=o.join(" ").trim();return c?(r(c)?(console.log(`${a.green}Autonomy: ${c}${a.reset}`),Ks()):console.log(`${a.red}Unknown level: ${c}. Use: ${i.join(", ")}${a.reset}`),!0):(console.log(`${a.bold}${a.cyan}Autonomy:${a.reset} ${n()}`),console.log(`${a.dim}Levels: ${i.join(", ")}${a.reset}`),!0)}case"/permissions":{let{listPermissions:n}=Ps(),r=n();console.log(`
|
|
1071
1160
|
${a.bold}${a.cyan}Tool Permissions:${a.reset}`);for(let i of r){let c=i.mode==="allow"?`${a.green}\u2713`:i.mode==="deny"?`${a.red}\u2717`:`${a.yellow}?`;console.log(` ${c} ${a.reset}${a.bold}${i.tool}${a.reset} ${a.dim}(${i.mode})${a.reset}`)}return console.log(`
|
|
1072
1161
|
${a.dim}Use /allow <tool> or /deny <tool> to change${a.reset}
|
|
1073
|
-
`),!0}case"/allow":{let{setPermission:n,savePermissions:r}=
|
|
1162
|
+
`),!0}case"/allow":{let{setPermission:n,savePermissions:r}=Ps(),i=o.join(" ").trim();return i?(n(i,"allow"),r(),console.log(`${a.green}${i}: allow${a.reset}`),!0):(console.log(`${a.red}Usage: /allow <tool>${a.reset}`),!0)}case"/deny":{let{setPermission:n,savePermissions:r}=Ps(),i=o.join(" ").trim();return i?(n(i,"deny"),r(),console.log(`${a.red}${i}: deny${a.reset}`),!0):(console.log(`${a.red}Usage: /deny <tool>${a.reset}`),!0)}case"/audit":{let{getAuditSummary:n,isAuditEnabled:r}=Li();if(!r())return console.log(`${a.yellow}Audit logging is disabled (set NEX_AUDIT=true to enable)${a.reset}`),!0;let i=parseInt(o.join(" ").trim())||1,c=n(i);if(console.log(`
|
|
1074
1163
|
${a.bold}${a.cyan}Audit Summary (${i} day${i>1?"s":""})${a.reset}
|
|
1075
1164
|
`),console.log(` Total tool calls: ${a.bold}${c.totalCalls}${a.reset}`),console.log(` Avg duration: ${a.dim}${c.avgDuration}ms${a.reset}`),console.log(` Success rate: ${c.successRate>=.95?a.green:a.yellow}${Math.round(c.successRate*100)}%${a.reset}`),Object.keys(c.byTool).length>0){console.log(`
|
|
1076
|
-
${a.dim}Tool${" ".repeat(25)}Count${a.reset}`),console.log(` ${a.dim}${"\u2500".repeat(35)}${a.reset}`);let l=Object.entries(c.byTool).sort((u,d)=>d[1]-u[1]);for(let[u,d]of l.slice(0,15))console.log(` ${u.padEnd(30)}${d}`)}return console.log(),!0}case"/commit":{let{isGitRepo:n,commit:r,analyzeDiff:i,formatDiffSummary:c}=
|
|
1165
|
+
${a.dim}Tool${" ".repeat(25)}Count${a.reset}`),console.log(` ${a.dim}${"\u2500".repeat(35)}${a.reset}`);let l=Object.entries(c.byTool).sort((u,d)=>d[1]-u[1]);for(let[u,d]of l.slice(0,15))console.log(` ${u.padEnd(30)}${d}`)}return console.log(),!0}case"/commit":{let{isGitRepo:n,commit:r,analyzeDiff:i,formatDiffSummary:c}=Vt(),{confirm:l}=Ue();if(!n())return console.log(`${a.red}Not a git repository${a.reset}`),!0;let u=o.join(" ").trim();if(u){let m=await r(u);return console.log(m?`${a.green}Committed: ${m} \u2014 ${u}${a.reset}`:`${a.red}Commit failed${a.reset}`),!0}if(!i())return console.log(`${a.yellow}No changes to commit${a.reset}`),!0;let f=await c();if(console.log(f),!await l(" Commit changes?"))return!0;let h=await r("nex-code update");return h&&console.log(`${a.green} \u2713 Committed: ${h}${a.reset}`),!0}case"/diff":{let{isGitRepo:n,formatDiffSummary:r}=Vt();return n()?(console.log(r()),!0):(console.log(`${a.red}Not a git repository${a.reset}`),!0)}case"/review":{let{isGitRepo:n,getDiff:r}=Vt(),{processInput:i}=$e(),c=o.join(" ").trim(),l=c.includes("--strict"),u=c.replace("--strict","").trim(),f=`## Review Protocol
|
|
1077
1166
|
|
|
1078
1167
|
**Phase 1 \u2014 Broad Scan:** Read the target code and identify all issues at a high level.
|
|
1079
1168
|
|
|
@@ -1108,109 +1197,108 @@ For each issue, include:
|
|
|
1108
1197
|
+ fixed code
|
|
1109
1198
|
\`\`\`${l?`
|
|
1110
1199
|
|
|
1111
|
-
\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.`:""}`,
|
|
1200
|
+
\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.`:""}`,p;if(u)p=`Do a thorough code review of \`${u}\`.
|
|
1112
1201
|
|
|
1113
|
-
${f}`;else{if(!n())return console.log(`${a.red}Not a git repository \u2014 try /review <file>${a.reset}`),!0;let[h,
|
|
1202
|
+
${f}`;else{if(!n())return console.log(`${a.red}Not a git repository \u2014 try /review <file>${a.reset}`),!0;let[h,m]=await Promise.all([r(!1),r(!0)]),g=m||h;if(!g||!g.trim())return console.log(`${a.yellow}No changes to review \u2014 commit something or specify a file: /review <file>${a.reset}`),!0;p=`Review the following code diff.
|
|
1114
1203
|
|
|
1115
1204
|
${f}
|
|
1116
1205
|
|
|
1117
1206
|
\`\`\`diff
|
|
1118
1207
|
${g.substring(0,2e4)}
|
|
1119
|
-
\`\`\``}return await i(
|
|
1208
|
+
\`\`\``}return await i(p),!0}case"/branch":{let{isGitRepo:n,getCurrentBranch:r,createBranch:i}=Vt();if(!n())return console.log(`${a.red}Not a git repository${a.reset}`),!0;let c=o.join(" ").trim();if(!c){let u=r();return console.log(`${a.bold}${a.cyan}Branch:${a.reset} ${u||"(detached)"}`),!0}let l=i(c);return console.log(l?`${a.green}Created and switched to: ${l}${a.reset}`:`${a.red}Failed to create branch${a.reset}`),!0}case"/mcp":{let{listServers:n,connectAll:r,disconnectAll:i}=bo(),c=o.join(" ").trim();if(c==="connect")return console.log(`${a.dim}Connecting MCP servers...${a.reset}`),r().then(u=>{for(let d of u)d.error?console.log(` ${a.red}\u2717${a.reset} ${d.name}: ${d.error}`):console.log(` ${a.green}\u2713${a.reset} ${d.name}: ${d.tools} tools`);u.length===0&&console.log(`${a.dim}No MCP servers configured in .nex/config.json${a.reset}`)}).catch(u=>{console.log(`${a.red}MCP connection error: ${u.message}${a.reset}`)}),!0;if(c==="disconnect")return i(),console.log(`${a.green}All MCP servers disconnected${a.reset}`),!0;let l=n();if(l.length===0)return console.log(`${a.dim}No MCP servers configured${a.reset}`),console.log(`${a.dim}Add servers to .nex/config.json under "mcpServers"${a.reset}`),!0;console.log(`
|
|
1120
1209
|
${a.bold}${a.cyan}MCP Servers:${a.reset}`);for(let u of l){let d=u.connected?`${a.green}\u2713 connected${a.reset}`:`${a.dim}\u25CB disconnected${a.reset}`;console.log(` ${d} ${a.bold}${u.name}${a.reset} (${u.command}) \u2014 ${u.toolCount} tools`)}return console.log(`
|
|
1121
1210
|
${a.dim}Use /mcp connect to connect all servers${a.reset}
|
|
1122
|
-
`),!0}case"/hooks":{let{listHooks:n}=
|
|
1123
|
-
${a.bold}${a.cyan}Hooks:${a.reset}`);for(let i of r){console.log(` ${a.cyan}${i.event}${a.reset}`);for(let c of i.commands)console.log(` ${a.dim}\u2192 ${c}${a.reset}`)}return console.log(),!0}case"/skills":{let{listSkills:n,enableSkill:r,disableSkill:i}=
|
|
1124
|
-
${a.bold}${a.cyan}Skills:${a.reset}`);for(let u of l){let d=u.enabled?`${a.green}\u2713${a.reset}`:`${a.red}\u2717${a.reset}`,f=u.type==="prompt"?`${a.dim}(prompt)${a.reset}`:`${a.dim}(script)${a.reset}`,
|
|
1211
|
+
`),!0}case"/hooks":{let{listHooks:n}=sa(),r=n();if(r.length===0)return console.log(`${a.dim}No hooks configured${a.reset}`),console.log(`${a.dim}Add hooks to .nex/config.json or .nex/hooks/${a.reset}`),!0;console.log(`
|
|
1212
|
+
${a.bold}${a.cyan}Hooks:${a.reset}`);for(let i of r){console.log(` ${a.cyan}${i.event}${a.reset}`);for(let c of i.commands)console.log(` ${a.dim}\u2192 ${c}${a.reset}`)}return console.log(),!0}case"/skills":{let{listSkills:n,enableSkill:r,disableSkill:i}=Qt(),c=o.join(" ").trim();if(c.startsWith("enable ")){let u=c.substring(7).trim();return r(u)?console.log(`${a.green}Skill enabled: ${u}${a.reset}`):console.log(`${a.red}Skill not found: ${u}${a.reset}`),!0}if(c.startsWith("disable ")){let u=c.substring(8).trim();return i(u)?console.log(`${a.yellow}Skill disabled: ${u}${a.reset}`):console.log(`${a.red}Skill not found: ${u}${a.reset}`),!0}let l=n();if(l.length===0)return console.log(`${a.dim}No skills loaded${a.reset}`),console.log(`${a.dim}Add .md or .js files to .nex/skills/${a.reset}`),!0;console.log(`
|
|
1213
|
+
${a.bold}${a.cyan}Skills:${a.reset}`);for(let u of l){let d=u.enabled?`${a.green}\u2713${a.reset}`:`${a.red}\u2717${a.reset}`,f=u.type==="prompt"?`${a.dim}(prompt)${a.reset}`:`${a.dim}(script)${a.reset}`,p=[];u.commands>0&&p.push(`${u.commands} cmd`),u.tools>0&&p.push(`${u.tools} tools`);let h=p.length>0?` \u2014 ${p.join(", ")}`:"";console.log(` ${d} ${a.bold}${u.name}${a.reset} ${f}${h}`)}return console.log(`
|
|
1125
1214
|
${a.dim}Use /skills enable <name> or /skills disable <name>${a.reset}
|
|
1126
|
-
`),!0}case"/install-skill":{let n=o.join(" ").trim();if(!n)return console.log(`${a.yellow}Usage: /install-skill <git-url-or-user/repo>${a.reset}`),!0;let{installSkill:r}=
|
|
1215
|
+
`),!0}case"/install-skill":{let n=o.join(" ").trim();if(!n)return console.log(`${a.yellow}Usage: /install-skill <git-url-or-user/repo>${a.reset}`),!0;let{installSkill:r}=Qt();console.log(`${a.dim}Installing skill from ${n}...${a.reset}`);let i=await r(n);return i.ok?(console.log(`${a.green}Skill "${i.name}" installed successfully${a.reset}`),console.log(`${a.dim}Reload with /skills to see it${a.reset}`)):console.log(`${a.red}Failed: ${i.error}${a.reset}`),!0}case"/search-skill":{let n=o.join(" ").trim();if(!n)return console.log(`${a.yellow}Usage: /search-skill <query>${a.reset}`),!0;let{searchSkills:r}=Qt();console.log(`${a.dim}Searching for "${n}"...${a.reset}`);let i=await r(n);if(i.length===0)console.log(`${a.yellow}No skills found matching "${n}"${a.reset}`);else{console.log(`
|
|
1127
1216
|
${a.bold}Skills matching "${n}":${a.reset}
|
|
1128
1217
|
`);for(let c of i)c.name==="error"?console.log(` ${a.red}${c.description}${a.reset}`):(console.log(` ${a.cyan}${c.owner}/${c.name}${a.reset} ${a.dim}\u2605${c.stars}${a.reset}`),console.log(` ${c.description}`),console.log(` ${a.dim}/install-skill ${c.url}${a.reset}
|
|
1129
|
-
`))}return!0}case"/remove-skill":{let n=o.join(" ").trim();if(!n)return console.log(`${a.yellow}Usage: /remove-skill <name>${a.reset}`),!0;let{removeSkill:r}=
|
|
1218
|
+
`))}return!0}case"/remove-skill":{let n=o.join(" ").trim();if(!n)return console.log(`${a.yellow}Usage: /remove-skill <name>${a.reset}`),!0;let{removeSkill:r}=Qt(),i=r(n);return i.ok?console.log(`${a.green}Skill "${n}" removed${a.reset}`):console.log(`${a.red}${i.error}${a.reset}`),!0}case"/tasks":{let{renderTaskList:n,clearTasks:r}=Po();return o.join(" ").trim()==="clear"?(r(),console.log(`${a.green}Tasks cleared${a.reset}`),!0):(console.log(`
|
|
1130
1219
|
`+n()+`
|
|
1131
|
-
`),!0)}case"/undo":{let{undo:n,getUndoCount:r}=
|
|
1220
|
+
`),!0)}case"/undo":{let{undo:n,getUndoCount:r}=It(),i=n();if(!i)return console.log(`${a.yellow}Nothing to undo${a.reset}`),!0;i.wasCreated?console.log(`${a.green}Undone: deleted ${i.filePath} (was created by ${i.tool})${a.reset}`):console.log(`${a.green}Undone: restored ${i.filePath} (${i.tool})${a.reset}`);let c=r();return c>0&&console.log(`${a.dim}${c} more change(s) to undo${a.reset}`),!0}case"/redo":{let{redo:n,getRedoCount:r}=It(),i=n();if(!i)return console.log(`${a.yellow}Nothing to redo${a.reset}`),!0;console.log(`${a.green}Redone: ${i.filePath} (${i.tool})${a.reset}`);let c=r();return c>0&&console.log(`${a.dim}${c} more change(s) to redo${a.reset}`),!0}case"/history":{let{getHistory:n,getUndoCount:r,getRedoCount:i}=It(),c=n(20);if(c.length===0)return console.log(`${a.dim}No file changes in this session${a.reset}`),!0;console.log(`
|
|
1132
1221
|
${a.bold}File Change History${a.reset}
|
|
1133
1222
|
`);for(let l of c){let u=new Date(l.timestamp).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});console.log(` ${a.dim}${u}${a.reset} ${a.yellow}${l.tool}${a.reset} ${l.filePath}`)}return console.log(`
|
|
1134
1223
|
${a.dim}${r()} undo / ${i()} redo available${a.reset}
|
|
1135
|
-
`),!0}case"/snapshot":{let{createSnapshot:n,listSnapshots:r}=
|
|
1136
|
-
${a.bold}${a.cyan}Snapshots:${a.reset}`);for(let u of l)console.log(` ${a.cyan}#${u.index}${a.reset} ${a.bold}${u.shortName}${a.reset}`);console.log()}return!0}let c=n(i,
|
|
1224
|
+
`),!0}case"/snapshot":{let{createSnapshot:n,listSnapshots:r}=It(),i=o.join(" ").trim()||void 0;if(i==="list"){let l=r(_t);if(l.length===0)console.log(`${a.dim}No snapshots found${a.reset}`);else{console.log(`
|
|
1225
|
+
${a.bold}${a.cyan}Snapshots:${a.reset}`);for(let u of l)console.log(` ${a.cyan}#${u.index}${a.reset} ${a.bold}${u.shortName}${a.reset}`);console.log()}return!0}let c=n(i,_t);return c.ok?(console.log(`${a.green}Snapshot created:${a.reset} ${c.label}`),console.log(`${a.dim}Use /restore to apply it later${a.reset}`)):console.log(`${a.yellow}${c.error}${a.reset}`),!0}case"/restore":{let{restoreSnapshot:n,listSnapshots:r}=It(),i=o.join(" ").trim()||"last";if(i==="list"){let l=r(_t);if(l.length===0)console.log(`${a.dim}No snapshots available${a.reset}`);else{console.log(`
|
|
1137
1226
|
${a.bold}${a.cyan}Available snapshots:${a.reset}`);for(let u of l)console.log(` ${a.cyan}#${u.index}${a.reset} ${a.bold}${u.shortName}${a.reset}`);console.log(`
|
|
1138
1227
|
${a.dim}Usage: /restore <name|last>${a.reset}
|
|
1139
|
-
`)}return!0}let c=n(i,
|
|
1228
|
+
`)}return!0}let c=n(i,_t);return c.ok?(console.log(`${a.green}Restored snapshot:${a.reset} ${c.label}`),console.log(`${a.dim}Working tree updated. Use /undo for in-session file undos.${a.reset}`)):(console.log(`${a.red}Restore failed:${a.reset} ${c.error}`),console.log(`${a.dim}Use /snapshot list to see available snapshots${a.reset}`)),!0}case"/k8s":{let n=o.join(" ").trim(),{exec:r}=require("child_process"),{promisify:i}=require("util"),c=i(r),l=n||null,u=l?`ssh -o ConnectTimeout=10 -o BatchMode=yes ${l.replace(/[^a-zA-Z0-9@._-]/g,"")} `:"",d=f=>l?`${u}"${f.replace(/"/g,'\\"')}"`:f;console.log(`
|
|
1140
1229
|
${a.bold}${a.cyan}Kubernetes Overview${a.reset}${l?a.dim+" (remote: "+l+")"+a.reset:""}
|
|
1141
|
-
`);try{let{stdout:f}=await c(d("kubectl get namespaces --no-headers -o custom-columns=NAME:.metadata.name"),{timeout:15e3}),
|
|
1142
|
-
`).filter(Boolean);console.log(`${a.bold}Namespaces (${
|
|
1143
|
-
`),!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}),
|
|
1144
|
-
`).filter(Boolean),h=
|
|
1145
|
-
`);let
|
|
1230
|
+
`);try{let{stdout:f}=await c(d("kubectl get namespaces --no-headers -o custom-columns=NAME:.metadata.name"),{timeout:15e3}),p=f.trim().split(`
|
|
1231
|
+
`).filter(Boolean);console.log(`${a.bold}Namespaces (${p.length}):${a.reset}`);for(let h of p)console.log(` ${a.cyan}${h}${a.reset}`);console.log()}catch{return console.log(`${a.dim}Could not reach cluster \u2014 is kubectl configured?${a.reset}
|
|
1232
|
+
`),!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}),p=f.trim().split(`
|
|
1233
|
+
`).filter(Boolean),h=p.filter(y=>y.includes("Running")).length,m=p.filter(y=>y.includes("Pending")).length,g=p.filter(y=>y.includes("Failed")||y.includes("Error")||y.includes("CrashLoop")).length;console.log(`${a.bold}Pods: ${p.length} total ${a.green}${h} running${a.reset} ${a.yellow}${m} pending${a.reset} ${a.red}${g} unhealthy${a.reset}
|
|
1234
|
+
`);let $=p.filter(y=>!y.includes("Running")&&!y.includes("<none>"));if($.length>0){console.log(`${a.bold}${a.red}Unhealthy Pods:${a.reset}`);for(let y of $)console.log(` ${a.red}${y}${a.reset}`);console.log()}console.log(`${a.dim}Use k8s_pods / k8s_logs / k8s_exec tools for details${a.reset}`),console.log(`${a.dim}Or: /k8s user@host to query a remote cluster${a.reset}
|
|
1146
1235
|
`)}catch(f){console.log(`${a.dim}Could not list pods: ${f.message}${a.reset}
|
|
1147
|
-
`)}return!0}case"/servers":{let{loadServerProfiles:n,resolveProfile:r,sshExec:i}=
|
|
1236
|
+
`)}return!0}case"/servers":{let{loadServerProfiles:n,resolveProfile:r,sshExec:i}=qn(),c=n(),l=Object.keys(c);if(l.length===0)return console.log(`
|
|
1148
1237
|
${a.dim}No servers configured. Create .nex/servers.json:${a.reset}`),console.log(`${a.dim} { "prod": { "host": "1.2.3.4", "user": "jarvis", "os": "almalinux9" } }${a.reset}
|
|
1149
1238
|
`),!0;if(o[0]==="ping"){let f=o[1]?[o[1]]:l;return console.log(`
|
|
1150
|
-
${a.bold}${a.cyan}Server connectivity:${a.reset}`),await Promise.all(f.map(async
|
|
1239
|
+
${a.bold}${a.cyan}Server connectivity:${a.reset}`),await Promise.all(f.map(async p=>{if(!c[p]){console.log(` ${a.red}\u2717${a.reset} ${p} \u2014 unknown profile`);return}try{let h={...c[p],_name:p},{exitCode:m}=await i(h,"echo ok",{timeout:8e3});console.log(m===0?` ${a.green}\u2713${a.reset} ${p} (${h.user?h.user+"@":""}${h.host})`:` ${a.red}\u2717${a.reset} ${p} (${h.host}) \u2014 SSH failed (exit ${m})`)}catch(h){console.log(` ${a.red}\u2717${a.reset} ${p} \u2014 ${h.message}`)}})),console.log(""),!0}let{formatProfile:d}=qn();console.log(`
|
|
1151
1240
|
${a.bold}${a.cyan}Configured servers (${l.length}):${a.reset}`);for(let f of l)console.log(` ${a.green}${f}${a.reset} ${a.dim}${d(f,c[f])}${a.reset}`);return console.log(`
|
|
1152
1241
|
${a.dim}/servers ping \u2014 check SSH connectivity for all servers${a.reset}`),console.log(`${a.dim}/servers ping <name> \u2014 check a specific server${a.reset}
|
|
1153
|
-
`),!0}case"/docker":{let{loadServerProfiles:n,sshExec:r}=
|
|
1154
|
-
${a.bold}${a.cyan}Docker Containers:${a.reset}`);for(let[
|
|
1155
|
-
`).forEach(
|
|
1242
|
+
`),!0}case"/docker":{let{loadServerProfiles:n,sshExec:r}=qn(),{exec:i}=require("child_process"),{promisify:c}=require("util"),l=c(i),u=o[0]==="-a"||o[0]==="--all"?'docker ps -a --format "table {{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}"':'docker ps --format "table {{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}"',d=n(),f=[["local",null],...Object.entries(d)];console.log(`
|
|
1243
|
+
${a.bold}${a.cyan}Docker Containers:${a.reset}`);for(let[p,h]of f){let m=p==="local"?`${a.dim}local${a.reset}`:`${a.cyan}${p}${a.reset}`;try{let g;if(p==="local"){let{stdout:$}=await l(u,{timeout:8e3});g=($||"").trim()}else{let $=await r(h,u,{timeout:1e4});if(g=[$.stdout,$.stderr].filter(Boolean).join("").trim(),$.exitCode!==0){console.log(` ${m}: ${a.red}SSH error (${$.exitCode})${a.reset}`);continue}}!g||g==="NAMES IMAGE STATUS PORTS"?console.log(` ${m}: ${a.dim}(no containers)${a.reset}`):(console.log(` ${m}:`),g.split(`
|
|
1244
|
+
`).forEach($=>console.log(` ${a.dim}${$}${a.reset}`)))}catch(g){console.log(` ${m}: ${a.red}${g.message}${a.reset}`)}}return console.log(""),!0}case"/deploy":{let{loadDeployConfigs:n}=xi(),r=n(),i=Object.keys(r),c=o[0];if(c&&i.includes(c)){let l=o.includes("--dry-run")||o.includes("-n"),u=r[c],{executeTool:d}=kt();console.log(`
|
|
1156
1245
|
${a.bold}Running deploy: ${c}${l?" (dry run)":""}${a.reset}`);let f=await d("deploy",{...u,dry_run:l});return console.log(f),!0}if(i.length===0)return console.log(`
|
|
1157
1246
|
${a.dim}No deploy configs. Run /init to create .nex/deploy.json${a.reset}
|
|
1158
1247
|
`),!0;console.log(`
|
|
1159
|
-
${a.bold}${a.cyan}Deploy configs (${i.length}):${a.reset}`);for(let[l,u]of Object.entries(r)){let d=u.method||"rsync",f=`[${d}]`,
|
|
1248
|
+
${a.bold}${a.cyan}Deploy configs (${i.length}):${a.reset}`);for(let[l,u]of Object.entries(r)){let d=u.method||"rsync",f=`[${d}]`,p=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(m=>` ${a.dim}\u2192 ${m}${a.reset}`).join("");console.log(` ${a.green}${l}${a.reset} ${a.dim}${f} ${p}${a.reset}${h}`)}return console.log(`
|
|
1160
1249
|
${a.dim}/deploy <name> \u2014 run a named deploy${a.reset}`),console.log(`${a.dim}/deploy <name> --dry-run \u2014 preview without syncing${a.reset}
|
|
1161
|
-
`),!0}case"/init":{let{runServerWizard:n,runDeployWizard:r,setWizardRL:i}=
|
|
1162
|
-
${a.bold}${a.cyan}OpenClaw Nightly Results (${
|
|
1163
|
-
`),console.log(` ${a.dim}${"Date".padEnd(12)} ${"Model".padEnd(25)} ${"Score".padEnd(8)} ${"Pass".padEnd(8)}${a.reset}`),console.log(` ${a.dim}${"\u2500".repeat(58)}${a.reset}`);let
|
|
1164
|
-
${a.bold}Trend:${a.reset} ${
|
|
1165
|
-
${a.bold}Checking Ollama Cloud for new models...${a.reset}`);let
|
|
1166
|
-
`);break}console.log(`${a.cyan}New models to benchmark (${
|
|
1167
|
-
`);let
|
|
1168
|
-
`),
|
|
1169
|
-
`);try{
|
|
1250
|
+
`),!0}case"/init":{let{runServerWizard:n,runDeployWizard:r,setWizardRL:i}=zf();return i(e),o[0]==="deploy"?await r():await n(),!0}case"/setup":{let{runSetupWizard:n}=xa();return await n({rl:e,force:!0}),!0}case"/benchmark":{if(o.includes("--history")){let $=require("os"),y=Me.join($.homedir(),"Coding","nex-code-benchmarks","results");if(!Xe.existsSync(y)){console.log(`${a.yellow}No nightly results at ${y}${a.reset}`),console.log(`${a.dim}Use /benchmark (no flags) to run a live model comparison.${a.reset}`);break}let x=Xe.readdirSync(y).filter(v=>v.endsWith(".json")).sort().slice(-7);if(x.length===0){console.log(`${a.yellow}No result files found${a.reset}`);break}console.log(`
|
|
1251
|
+
${a.bold}${a.cyan}OpenClaw Nightly Results (${x.length}-day trend)${a.reset}
|
|
1252
|
+
`),console.log(` ${a.dim}${"Date".padEnd(12)} ${"Model".padEnd(25)} ${"Score".padEnd(8)} ${"Pass".padEnd(8)}${a.reset}`),console.log(` ${a.dim}${"\u2500".repeat(58)}${a.reset}`);let _=[];for(let v of x)try{let b=JSON.parse(Xe.readFileSync(Me.join(y,v),"utf-8")),k=v.replace(".json",""),R=b.tasks?.length||b.total||0,O=b.tasks?.filter(me=>me.passed||me.score>=.7)?.length||b.passed||0,P=b.score??b.overall_score??(R>0?Math.round(O/R*100):"N/A"),F=b.model||b.config?.model||"unknown";_.push({date:k,model:F,total:R,passed:O,score:P});let De=typeof P=="number"?P>=80?a.green:P>=60?a.yellow:a.red:a.dim;console.log(` ${k.padEnd(12)} ${F.substring(0,24).padEnd(25)} ${De}${String(P).padEnd(8)}${a.reset} ${O}/${R}`)}catch{}if(_.length>=2){let v=_[0].score,b=_[_.length-1].score;if(typeof v=="number"&&typeof b=="number"){let k=b-v,R=k>0?`${a.green}\u25B2 +${k}`:k<0?`${a.red}\u25BC ${k}`:`${a.dim}\u2192 stable`;console.log(`
|
|
1253
|
+
${a.bold}Trend:${a.reset} ${R}${a.reset} over ${_.length} days`)}}console.log();break}if(o.includes("--discover")){let{findNewModels:$,markBenchmarked:y,updateReadme:x,updateModelsEnv:_}=yr(),{runDiscoverBenchmark:v,buildSummary:b}=kn();console.log(`
|
|
1254
|
+
${a.bold}Checking Ollama Cloud for new models...${a.reset}`);let k;try{k=await $()}catch(le){console.log(`${a.red}Discovery failed: ${le.message}${a.reset}`);break}let{newModels:R,allCloud:O}=k;if(console.log(`${a.dim}${O.length} models available on cloud${a.reset}`),R.length===0){console.log(`${a.green}No new models since last benchmark run.${a.reset}
|
|
1255
|
+
`);break}console.log(`${a.cyan}New models to benchmark (${R.length}):${a.reset} ${R.join(", ")}
|
|
1256
|
+
`);let P=require("os"),F=Me.join(P.homedir(),".nex-code","benchmark-results.json"),De=[];try{Xe.existsSync(F)&&(De=JSON.parse(Xe.readFileSync(F,"utf-8")))}catch{}let me="",A=await v({newModels:R,existingRanking:De,onProgress:({model:le,task:pt,done:U,score:K,error:te})=>{if(!U){le!==me&&(me&&process.stdout.write(`
|
|
1257
|
+
`),me=le,process.stdout.write(`${a.cyan}${le}${a.reset} `));return}let se=te?`${a.red}\u2717${a.reset}`:K>=80?`${a.green}\xB7${a.reset}`:K>=40?`${a.yellow}\xB7${a.reset}`:`${a.red}\xB7${a.reset}`;process.stdout.write(se)}});me&&process.stdout.write(`
|
|
1258
|
+
`);try{Xe.writeFileSync(F,JSON.stringify(A,null,2))}catch{}y(O);let M=Me.join(process.cwd(),"README.md"),D=x(A,M),W=_(A),{buildCategoryWinners:Q}=kn(),{updateRoutingConfig:ne}=yr(),qe=Q(A),Re=ne(qe);if(D&&console.log(`${a.green}README.md benchmark table updated${a.reset}`),W.updated?console.log(`${a.green}DEFAULT_MODEL: ${W.previousModel} \u2192 ${W.newModel}${a.reset}`):W.reason&&console.log(`${a.dim}models.env unchanged: ${W.reason}${a.reset}`),Re.changes.length>0){console.log(`${a.green}Routing updated:${a.reset}`);for(let le of Re.changes)console.log(` ${a.dim}${le}${a.reset}`)}return console.log(),!0}let{runBenchmark:n,DEFAULT_MODELS:r,QUICK_MODELS:i}=kn(),c=o.includes("--quick"),l=o.find($=>$.startsWith("--models=")),u=l?l.replace("--models=","").split(",").map($=>$.trim()).filter(Boolean):[],d=c?7:15,f=u.length>0?u:c?i:r;console.log(`
|
|
1170
1259
|
${a.bold}Starting benchmark${a.reset} ${a.dim}${d} tasks \xB7 ${f.length} models \xB7 ollama cloud${a.reset}`),console.log(`${a.dim}Models: ${f.join(", ")}${a.reset}
|
|
1171
|
-
`);let
|
|
1172
|
-
`),
|
|
1173
|
-
`),!c&&g&&g.length>0){let{buildCategoryWinners
|
|
1174
|
-
${a.bold}Per-category routing saved:${a.reset}`);for(let
|
|
1260
|
+
`);let p="",h=0,m=d*f.length,g=await n({models:f,quick:c,onProgress:({model:$,task:y,done:x,score:_,error:v})=>{if(!x){$!==p&&(p&&process.stdout.write(`
|
|
1261
|
+
`),p=$,process.stdout.write(`${a.cyan}${$}${a.reset} `));return}h++;let b=v?`${a.red}\u2717${a.reset}`:_>=80?`${a.green}\xB7${a.reset}`:_>=40?`${a.yellow}\xB7${a.reset}`:`${a.red}\xB7${a.reset}`;process.stdout.write(b)}});if(p&&process.stdout.write(`
|
|
1262
|
+
`),!c&&g&&g.length>0){let{buildCategoryWinners:$}=kn(),{updateRoutingConfig:y,updateReadme:x,updateModelsEnv:_}=yr(),v=$(g),b=y(v);if(b.changes.length>0){console.log(`
|
|
1263
|
+
${a.bold}Per-category routing saved:${a.reset}`);for(let P of b.changes)console.log(` ${a.dim}${P}${a.reset}`)}let k=Me.join(process.cwd(),"README.md");x(g,k)&&console.log(`${a.green}README.md updated${a.reset}`),_(g);let R=require("os"),O=Me.join(R.homedir(),".nex-code","benchmark-results.json");try{Xe.writeFileSync(O,JSON.stringify(g,null,2))}catch{}}return!0}case"/bench":{let{runJarvisBenchmark:n}=kn(),r=o.includes("--dry-run"),i=o.find(l=>l.startsWith("--model=")),c=i?i.replace("--model=","").trim():void 0;return r||console.log(`
|
|
1175
1264
|
${a.bold}Jarvis Benchmark${a.reset} ${a.dim}5 agentic scenarios \xB7 each run as child process${a.reset}
|
|
1176
|
-
`),await n({dryRun:r,model:c,cwd:
|
|
1177
|
-
`)}}}),!0}case"/trend":{let{showScoreTrend:n}=
|
|
1178
|
-
`).filter(Boolean).slice(-
|
|
1179
|
-
`)}catch{}}function
|
|
1180
|
-
`),!0):!1)(),c=(async()=>{if(process.env.NEX_DISABLE_UPDATE_CHECK==="1")return{hasNewVersion:!1};try{let{checkForNewVersion:
|
|
1265
|
+
`),await n({dryRun:r,model:c,cwd:_t,onProgress:({id:l,name:u,done:d,score:f,grade:p})=>{if(!d)process.stdout.write(`${a.dim} \u2192 ${u}...${a.reset}`);else{let h=f>=8?a.green:f>=6?a.yellow:a.red;process.stdout.write(` ${h}${f}/10 (${p})${a.reset}
|
|
1266
|
+
`)}}}),!0}case"/trend":{let{showScoreTrend:n}=kn(),r=parseInt(o[0],10)||10;return n(r),!0}case"/exit":case"/quit":process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J"),process.exit(0);default:if(V_(t))return!0;{let n=[...zs,...xr()].map(l=>l.cmd.split(" ")[0]),r=(l,u)=>{let d=l.length,f=u.length,p=Array.from({length:d+1},(h,m)=>Array.from({length:f+1},(g,$)=>m===0?$:$===0?m:0));for(let h=1;h<=d;h++)for(let m=1;m<=f;m++)p[h][m]=l[h-1]===u[m-1]?p[h-1][m-1]:1+Math.min(p[h-1][m],p[h][m-1],p[h-1][m-1]);return p[d][f]},i=null,c=3;for(let l of n){let u=r(s,l);u<c&&(c=u,i=l)}console.log(i?`${a.red}Unknown command: ${s}.${a.reset} ${a.dim}Did you mean ${a.reset}${a.cyan}${i}${a.reset}${a.dim}? Type /help for all commands.${a.reset}`:`${a.red}Unknown command: ${s}. Type /help${a.reset}`)}return!0}}var Da=1e3;function qa(){return Me.join(process.cwd(),".nex","repl_history")}function vp(){try{let t=qa();if(Xe.existsSync(t))return Xe.readFileSync(t,"utf-8").split(`
|
|
1267
|
+
`).filter(Boolean).slice(-Da)}catch{}return[]}function _r(t){try{let e=qa(),s=Me.dirname(e);Xe.existsSync(s)||Xe.mkdirSync(s,{recursive:!0}),Xe.appendFileSync(e,t+`
|
|
1268
|
+
`)}catch{}}function ft(){return`${a.bold}${a.cyan}>${a.reset} `}function Ks(){if(!global._nexFooter)return;let{isPlanMode:t,getAutonomyLevel:e}=Ft(),{getAutoConfirm:s}=Ue(),o=[];t()&&o.push("plan");let n=e();n==="semi-auto"&&o.push("semi"),n==="autonomous"&&o.push("auto"),s()&&o.push("always"),global._nexFooter.setStatusInfo({mode:o.join(" \xB7 ")})}var Fa="\x1B[200~",Ua="\x1B[201~";function nx(t){return typeof t=="string"&&t.includes(Fa)}function sx(t){return typeof t=="string"&&t.includes(Ua)}function Ys(t){return typeof t!="string"?t:t.split(Fa).join("").split(Ua).join("")}async function ox(){if(!X_("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"),ja("local:llama3"),!0}catch{return!1}}async function rx(){let{setAbortSignalGetter:t,getConversationLength:e,processInput:s}=$e();t($p);let n=La().some(U=>U.configured),r=(async()=>{J_();let U=Bt(),K=vn();return{model:U,providerName:K}})(),i=(async()=>n?!0:await ox()?(console.log(`${a.green}\u2713 Local Ollama detected \u2014 using local models${a.reset}`),console.log(`${a.dim}Tip: Set API keys for cloud providers for more model options (OPENAI_API_KEY, ANTHROPIC_API_KEY, etc.)${a.reset}
|
|
1269
|
+
`),!0):!1)(),c=(async()=>{if(process.env.NEX_DISABLE_UPDATE_CHECK==="1")return{hasNewVersion:!1};try{let{checkForNewVersion:U}=fp();return await U()}catch{return{hasNewVersion:!1}}})(),[l,u,d]=await Promise.all([r,i,c]);!u&&!n&&(console.error(`
|
|
1181
1270
|
${a.red}\u2717 No provider configured and no local Ollama detected.${a.reset}
|
|
1182
|
-
`),process.exit(1));let{loadPersistedHistory:f,pruneHistory:
|
|
1183
|
-
${
|
|
1271
|
+
`),process.exit(1));let{loadPersistedHistory:f,pruneHistory:p}=It();f().then(U=>{}),p().catch(()=>{});let h=vp(),m=H_.createInterface({input:process.stdin,output:process.stdout,prompt:ft(),completer:bp,history:h,historySize:Da});Q_(m);let{setAskUserHandler:g}=kt();g(async(U,K)=>{let te="\x1B[0m",se="\x1B[1m",Z="\x1B[2m",ie="\x1B[36m";return process.stdout.write(`
|
|
1272
|
+
${se}\x1B[33m\u2753${te} ${se}${U}${te}
|
|
1184
1273
|
|
|
1185
|
-
`),
|
|
1186
|
-
`)}),process.stdout.write(` ${
|
|
1274
|
+
`),K.forEach((ue,ce)=>{process.stdout.write(` ${ie}${ce+1}${te} ${ue}
|
|
1275
|
+
`)}),process.stdout.write(` ${Z}${K.length+1}${te} ${Z}Eigene Antwort\u2026${te}
|
|
1187
1276
|
`),process.stdout.write(`
|
|
1188
|
-
${
|
|
1189
|
-
`),
|
|
1277
|
+
${ie}[1-${K.length+1}]${te} \u203A `),new Promise(ue=>{m.pause(),process.stdin.isTTY&&process.stdin.setRawMode(!0);let ce=Je=>{let xt=Je.toString();if(xt===""){process.stdout.write(`
|
|
1278
|
+
`),Oe(),ue("");return}let Be=parseInt(xt);Be>=1&&Be<=K.length?(process.stdout.write(`${se}${K[Be-1]}${te}
|
|
1190
1279
|
|
|
1191
|
-
`),
|
|
1280
|
+
`),Oe(),ue(K[Be-1])):(Be===K.length+1||xt==="\r"||xt===`
|
|
1192
1281
|
`)&&(process.stdout.write(`
|
|
1193
|
-
`),process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.removeListener("data",
|
|
1194
|
-
`),
|
|
1195
|
-
`),await
|
|
1196
|
-
${a.yellow} Task cancelled. Press Ctrl+C again to exit.${a.reset}`),
|
|
1197
|
-
`).replace(/\r/g,"").trim();if(
|
|
1198
|
-
`).length,
|
|
1199
|
-
`)),
|
|
1200
|
-
`)),!0}if(
|
|
1201
|
-
`)),
|
|
1202
|
-
`)),!0}return
|
|
1203
|
-
`)&&
|
|
1204
|
-
`)),
|
|
1205
|
-
${
|
|
1206
|
-
`))}}
|
|
1207
|
-
`)
|
|
1208
|
-
`).
|
|
1209
|
-
`)
|
|
1210
|
-
`).
|
|
1211
|
-
`)
|
|
1212
|
-
`)
|
|
1213
|
-
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${re}${a.reset}`)}}w=!1;let{getConversationLength:V}=me(),Q=V();Q>0&&process.stdout.write(`${a.gray}[${Q} messages] ${a.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)})}ep.exports={startREPL:v_,getPrompt:Ze,loadHistory:Zf,appendHistory:rr,getHistoryPath:ga,HISTORY_MAX:ha,showCommandList:Yf,completer:Xf,completeFilePath:zf,handleSlashCommand:Qf,showProviders:fa,showHelp:Jf,renderBar:Vf,hasPasteStart:b_,hasPasteEnd:__,stripPasteSequences:Ms,getAbortSignal:Kf}});var xa=require("path");require("dotenv").config({path:xa.join(__dirname,"..",".env")});require("dotenv").config();var $e=process.argv.slice(2);($e.includes("--help")||$e.includes("-h"))&&(console.log(`Usage: nex-code [options]
|
|
1282
|
+
`),process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.removeListener("data",ce),process.stdout.write(` ${ie}\u203A${te} `),m.resume(),m.once("line",ss=>{process.stdout.write(`
|
|
1283
|
+
`),ue(ss.trim()||"")}))};function Oe(){process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.removeListener("data",ce),m.resume()}process.stdin.on("data",ce)})});let $=new tx;$.activate(m),global._nexFooter=$,global._nexRawWrite=U=>$.rawWrite(U),ex(()=>Ks()),process.stdout.isTTY&&process.stdout.write("\x1B[H\x1B[2J\x1B[3J");let y=l.providerName==="ollama"?l.model.id:`${l.providerName}:${l.model.id}`;G_(y,_t,{yolo:gp()});{$.setStatusInfo({model:y,branch:"",project:Me.basename(_t)});let{execFile:U}=require("child_process");U("git",["rev-parse","--abbrev-ref","HEAD"],{encoding:"utf8"},(K,te)=>{!K&&te&&$.setStatusInfo({model:y,branch:te.trim(),project:Me.basename(_t)})})}d.hasNewVersion&&console.log(`${a.yellow}\u{1F4A1} New version available!${a.reset} Run ${a.cyan}npm update -g nex-code${a.reset} to upgrade from ${a.dim}${d.currentVersion}${a.reset} to ${a.green}${d.latestVersion}${a.reset}
|
|
1284
|
+
`),await hp(_t);let x=!1,_=0,v=!1,b=null;function k(){mp(),$.deactivate(),pp(),process.stdin.isTTY&&process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J"),process.exit(0)}process.on("SIGTERM",k),process.on("exit",()=>{mp()}),m.on("SIGINT",()=>{if(pp(),_++,_>=2){k();return}if(x){Wt&&Wt.abort();let{cancelPendingAskUser:U}=kt();U(),console.log(`
|
|
1285
|
+
${a.yellow} Task cancelled. Press Ctrl+C again to exit.${a.reset}`),x=!1,m.setPrompt(ft()),m.prompt()}else console.log(`${a.dim} (Press Ctrl+C again to exit)${a.reset}`),m.setPrompt(ft()),m.prompt(),b&&clearTimeout(b),b=setTimeout(()=>{_=0,b=null},2e3)}),process.on("SIGINT",()=>{process.stdin.isTTY?(_++,_>=2&&k()):k()});let R=!1,O=[],P=0,F={},De=!1;function me(){let U=O.join(`
|
|
1286
|
+
`).replace(/\r/g,"").trim();if(O=[],R=!1,!U)return!0;P++,De=!0;let K=P;F[K]=U;let te=U.split(`
|
|
1287
|
+
`).length,se=te>1?`[Pasted content #${K} \u2014 ${te} lines]`:`[Pasted content #${K}]`,Z=m.line||"",ie=Z&&!Z.endsWith(" ")?" ":"",oe=Z+ie+se;return m.setPrompt(ft()),m.prompt(),m.line=oe,m.cursor=oe.length,m._refreshLine(),!0}function A(U){return U.replace(/\[Pasted content #(\d+)(?:[^\]]*)\]/g,(K,te)=>F[Number(te)]||"")}function M(){P=0,F={},De=!1}if(process.stdin.isTTY){process.stdout.write("\x1B[?2004h");let U=process.stdin.emit.bind(process.stdin);process.stdin.emit=function(K,...te){if(K!=="data")return U.call(process.stdin,K,...te);let se=te[0];if(Buffer.isBuffer(se)&&(se=se.toString("utf8")),typeof se!="string")return U.call(process.stdin,K,...te);let Z=se.includes(Fa),ie=se.includes(Ua);if(Z&&ie){let oe=Ys(se);return oe&&O.push(...oe.split(`
|
|
1288
|
+
`)),me()}if(Z){R=!0,O=[];let oe=Ys(se);return oe&&O.push(...oe.split(`
|
|
1289
|
+
`)),!0}if(ie){let oe=Ys(se);return oe&&O.push(...oe.split(`
|
|
1290
|
+
`)),me()}if(R){let oe=Ys(se);return oe&&O.push(...oe.split(`
|
|
1291
|
+
`)),!0}return se.includes(`
|
|
1292
|
+
`)&&se.length>40&&!R?(O.push(...se.replace(/\r/g,"").split(`
|
|
1293
|
+
`)),me()):U.call(process.stdin,K,...te)}}let D=0;function W(){if(D>0){let U=$._scrollEnd,K="\x1B7";for(let te=0;te<D;te++)K+=`\x1B[${U-D+1+te};1H\x1B[2K`;K+="\x1B8",$.rawWrite(K),D=0}}function Q(U){let K=[...zs,...xr()].filter(ce=>ce.cmd.startsWith(U));if(!K.length||K.length===1&&K[0].cmd===U)return;let te=$._scrollEnd,se=Math.min(10,te-2);if(se<1)return;let Z=K.slice(0,se),ie=Math.max(...Z.map(ce=>ce.cmd.length));D=Z.length,K.length>se&&D++;let oe=te-D+1,ue="\x1B7";for(let ce=0;ce<Z.length;ce++){let{cmd:Oe,desc:Je}=Z[ce],xt=Oe.substring(0,U.length),Be=Oe.substring(U.length),ss=" ".repeat(Math.max(0,ie-Oe.length+2));ue+=`\x1B[${oe+ce};1H\x1B[2K ${a.cyan}${xt}${a.reset}${a.dim}${Be}${ss}${Je}${a.reset}`}K.length>se&&(ue+=`\x1B[${oe+Z.length};1H\x1B[2K ${a.dim}\u2026 +${K.length-se} more${a.reset}`),ue+="\x1B8",$.rawWrite(ue)}process.stdin.isTTY&&process.stdin.on("keypress",(U,K)=>{W(),!(K&&(K.name==="tab"||K.name==="return"))&&setImmediate(()=>{m.line&&m.line.startsWith("/")&&Q(m.line)})});let ne=null,qe=`${a.dim}...${a.reset} `;function Re(U){return(U.match(/[^\s\d](\d{1,2})\.\s+\S/g)||[]).length<2?U:U.replace(/([^\s\d])(\d{1,2})\.\s+/g,(te,se,Z)=>`${se}
|
|
1294
|
+
${Z}. `).trim()}let{loadSession:le}=Et(),{setConversationMessages:pt}=$e();if(e()===0){let U=le("_autosave");if(U&&U.messages&&U.messages.length>0&&Date.now()-new Date(U.updatedAt).getTime()<1440*60*1e3){let{confirm:te}=Ue();if(await te("Previous session found. Resume?")){let ie=U.messages,oe=ie.length>20?ie.slice(-20):ie;pt(oe);let{getUsage:ue,forceCompress:ce}=He();if(ue(oe,[]).percentage>=30){let{messages:Je}=ce(oe,[]);pt(Je)}}}}m.setPrompt(ft()),m.prompt(),m.on("line",async U=>{if(W(),Object.keys(F).length>0&&(U=A(U),M(),m.setPrompt(ft())),x){let Z=U.trim();if(Z){let{injectMidRunNote:ie}=$e();ie(Z),process.stdout.write(`${a.cyan} \u270E Queued \u2014 will be applied in the next step${a.reset}
|
|
1295
|
+
`),m.prompt()}return}if(ne!==null){if(ne._mode==="triple"){if(U.trim()==='"""'){let Z=ne.join(`
|
|
1296
|
+
`).trim();if(ne=null,Z){_r(Z.replace(/\n/g,"\\n")),x=!0,m.prompt(),_=0,v=!1,b&&(clearTimeout(b),b=null),Wt=new AbortController;try{await s(Z)}catch(oe){if(!Wt?.signal?.aborted){let ue=oe.message?.split(`
|
|
1297
|
+
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${ue}${a.reset}`)}}x=!1;let ie=te();ie>0&&process.stdout.write(`${a.gray}[${ie} messages] ${a.reset}`)}m.setPrompt(ft()),m.prompt();return}ne.push(U),m.setPrompt(qe),m.prompt();return}if(U.endsWith("\\"))ne.push(U.slice(0,-1));else{ne.push(U);let Z=ne.join(`
|
|
1298
|
+
`).trim();if(ne=null,Z){_r(Z.replace(/\n/g,"\\n")),x=!0,m.prompt(),_=0,v=!1,b&&(clearTimeout(b),b=null),Wt=new AbortController;try{await s(Z)}catch(ue){if(!Wt?.signal?.aborted){let ce=ue.message?.split(`
|
|
1299
|
+
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${ce}${a.reset}`)}}let{getConversationLength:ie}=$e();x=!1;let oe=ie();oe>0&&process.stdout.write(`${a.gray}[${oe} messages] ${a.reset}`)}m.setPrompt(ft()),m.prompt();return}m.setPrompt(qe),m.prompt();return}if(U.trim()==='"""'||U.trim().startsWith('"""')){let Z=U.trim().substring(3);ne=Z?[Z]:[],ne._mode="triple",m.setPrompt(qe),m.prompt();return}if(U.endsWith("\\")){ne=[U.slice(0,-1)],ne._mode="backslash",m.setPrompt(qe),m.prompt();return}let K=Re(U.trim());if(!K){m.setPrompt(ft()),m.prompt();return}if(_r(K),K==="/"){yp(),m.setPrompt(ft()),m.prompt();return}if(K.startsWith("/")){await kp(K,m),m.setPrompt(ft()),m.prompt();return}{let Z=K_?"\x1B[48;5;237m":"\x1B[48;2;220;225;235m",ie=process.stdout.columns||80;K.split(`
|
|
1300
|
+
`).forEach((ue,ce)=>{let Oe=ce===0?"\x1B[1;36m\u203A\x1B[22;39m":" ",Je=2+ue.length,xt=" ".repeat(Math.max(0,ie-Je));console.log(`${Z}${Oe} ${ue}${xt}\x1B[0m`)})}if(process.env.NEX_AUTO_PLAN!=="0"){let{isPlanMode:Z,setPlanMode:ie}=Ft(),{invalidateSystemPromptCache:oe}=$e(),ue=/\b(implement|refactor|migrate|redesign)\b/i,ce=/\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,Je=/\b(spawn[_\s]?agents?|swarm)\b/i;!Oe.test(K)&&!Je.test(K)&&(ue.test(K)||ce.test(K)&&K.split(/\s+/).length>=5)&&!Z()&&(ie(!0),oe(),console.log(`${a.cyan}${a.bold}\u2387 Auto Plan Mode${a.reset}${a.dim} \u2014 implementation task detected \xB7 read-only until /plan approve${a.reset}`))}{let{getConversationLength:Z}=$e();if(Z()===0)try{let{detectCategory:ie,getModelForCategory:oe}=Ra(),ue=ie(K);if(ue&&ue.id!=="coding"){let ce=oe(ue.id),Oe=Bt();if(ce&&ce!==Oe?.id&&ja(ce)){let Je=Bt();console.log(`${a.dim}\u21B3 ${ue.icon} ${ue.label} task \u2014 routing to ${Je?.name||ce}${a.reset}`),global._nexFooter&&global._nexFooter.setStatusInfo({model:Je?.name||ce})}}}catch{}}x=!0,m.prompt(),_=0,v=!1,b&&(clearTimeout(b),b=null),Wt=new AbortController;try{await s(K)}catch(Z){if(!Wt?.signal?.aborted){let ie=Z.message?.split(`
|
|
1301
|
+
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${ie}${a.reset}`)}}x=!1;let{getConversationLength:te}=$e(),se=te();se>0&&process.stdout.write(`${a.gray}[${se} messages] ${a.reset}`),m.setPrompt(ft()),m.prompt()}),m.on("close",()=>{process.stdin.isTTY&&process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J"),process.exit(0)})}Sp.exports={startREPL:rx,getPrompt:ft,loadHistory:vp,appendHistory:_r,getHistoryPath:qa,HISTORY_MAX:Da,showCommandList:yp,completer:bp,completeFilePath:wp,handleSlashCommand:kp,showProviders:Ia,showHelp:_p,renderBar:xp,hasPasteStart:nx,hasPasteEnd:sx,stripPasteSequences:Ys,getAbortSignal:$p}});var Ga=require("path");require("dotenv").config({path:Ga.join(__dirname,"..",".env")});require("dotenv").config();var xe=process.argv.slice(2);(xe.includes("--help")||xe.includes("-h"))&&(console.log(`Usage: nex-code [options]
|
|
1214
1302
|
|
|
1215
1303
|
Options:
|
|
1216
1304
|
--task <prompt> Run a single task and exit (headless mode)
|
|
@@ -1224,4 +1312,4 @@ Options:
|
|
|
1224
1312
|
--json Output result as JSON (for CI parsing)
|
|
1225
1313
|
-h, --help Show this help
|
|
1226
1314
|
-v, --version Show version
|
|
1227
|
-
`),process.exit(0));if(
|
|
1315
|
+
`),process.exit(0));if(xe.includes("-v")||xe.includes("--version")){let t=Sn();console.log(t.version),process.exit(0)}var Cp=xe.includes("--yolo")||xe.includes("-yolo");if(Cp){let{setAutoConfirm:t}=Ue();t(!0)}if(!Cp)try{let t=require("fs"),e=Ga.join(process.cwd(),".nex","config.json");if(t.existsSync(e)&&JSON.parse(t.readFileSync(e,"utf-8")).yolo===!0){let{setAutoConfirm:o}=Ue();o(!0)}}catch{}var Wa=xe.indexOf("--model");if(Wa!==-1&&xe[Wa+1]){let{setActiveModel:t}=Se();t(xe[Wa+1])}var Ba=xe.indexOf("--max-turns");if(Ba!==-1&&xe[Ba+1]){let t=parseInt(xe[Ba+1],10);if(t>0){let{setMaxIterations:e}=$e();e(t)}}else try{let t=require("fs"),e=Ga.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}=$e();n(o)}}}catch{}function Ha(){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 ix(){let{runSetupWizard:t}=xa();await t()}function Tp(t){if(xe.includes("--auto")){let{setAutoConfirm:n}=Ue();n(!0)}if(!xe.includes("--model")){let{setActiveModel:n}=Se(),r=process.env.HEADLESS_MODEL||"devstral-small-2:24b";n(r)}let{processInput:s,getConversationMessages:o}=$e();s(t).then(()=>{if(xe.includes("--json")){let r=o().filter(i=>i.role==="assistant").pop();console.log(JSON.stringify({success:!0,response:r?.content||""}))}process.exit(0)}).catch(n=>{xe.includes("--json")?console.log(JSON.stringify({success:!1,error:n.message})):console.error(n.message),process.exit(1)})}if(xe.includes("--server")){let{setAutoConfirm:t}=Ue();t(!0),Cf().startServerMode();return}var Rp=xe.indexOf("--prompt-file");if(Rp!==-1){let t=xe[Rp+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)),xe.includes("--delete-prompt-file"))try{e.unlinkSync(t)}catch{}Ha(),Tp(s)}else{let t=xe.indexOf("--task");if(t!==-1){let e=xe[t+1];(!e||e.startsWith("--"))&&(console.error("--task requires a prompt"),process.exit(1)),Ha(),Tp(e)}else ix().then(()=>{Ha();let{startREPL:e}=Ep();e()})}
|