nex-code 0.4.15 → 0.4.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +42 -43
- package/dist/nex-code.js +433 -430
- package/package.json +1 -1
package/dist/nex-code.js
CHANGED
|
@@ -1,156 +1,156 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var G=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var
|
|
3
|
-
`),s=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(s){let r=parseInt(s[1].slice(0,2),16),i=parseInt(s[2].slice(0,2),16),c=parseInt(s[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 In=G((Zk,nh)=>{nh.exports={name:"nex-code",version:"0.4.17",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","test:orchestrator":"jest tests/orchestrator.test.js --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",prettier:"^3.8.1"},jest:{coverageThreshold:{global:{lines:45,functions:30,branches:35},"./cli/sub-agent.js":{lines:70,functions:60,branches:55}}}}});var hn=G((ev,jc)=>{"use strict";var Nc="\x1B[0m",Mc="\x1B[1m",Ln="\x1B[2m";function j(t,e,n){return`\x1B[38;2;${t};${e};${n}m`}function sh(){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
|
+
`),s=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(s){let r=parseInt(s[1].slice(0,2),16),i=parseInt(s[2].slice(0,2),16),c=parseInt(s[3].slice(0,2),16);return .299*r+.587*i+.114*c<128}}catch{}return null}function Pc(){let t=require("os");return require("path").join(t.homedir(),".nex-code",".theme_cache.json")}function oh(t){try{let n=require("fs").readFileSync(Pc(),"utf8"),o=JSON.parse(n);if(o&&typeof o[t]=="boolean")return o[t]}catch{}return null}function rh(t,e){try{let n=require("fs"),o=require("path"),s=Pc(),r=o.dirname(s),i={};try{i=JSON.parse(n.readFileSync(s,"utf8"))}catch{}i[t]=e;let c=Object.keys(i);c.length>50&&c.slice(0,c.length-50).forEach(l=>delete i[l]),n.existsSync(r)||n.mkdirSync(r,{recursive:!0}),n.writeFileSync(s,JSON.stringify(i),"utf8")}catch{}}function ih(){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 n=process.env.TERM_SESSION_ID||"default",o=oh(n);if(o!==null)return o;let s=sh(),r=s!==null?s:!0;return rh(n,r),r}var Ic=ih(),Lc={reset:Nc,bold:Mc,dim:Ln,primary:j(80,190,255),secondary:j(60,170,190),success:j(80,210,120),warning:j(245,175,50),error:j(230,80,80),muted:Ln,subtle:j(130,130,145),tool_read:j(80,190,255),tool_write:j(245,165,55),tool_exec:j(185,100,235),tool_search:j(70,185,190),tool_git:j(90,210,100),tool_web:j(100,215,250),tool_sysadmin:j(225,150,75),tool_default:j(100,205,115),syn_keyword:j(185,100,235),syn_string:j(90,210,120),syn_number:j(245,175,50),syn_comment:Ln,syn_key:j(80,190,255),diff_add:j(80,210,120),diff_rem:j(230,80,80),banner_logo:j(80,200,255),banner_name:j(80,200,255),banner_version:Ln,banner_model:Ln,banner_yolo:j(245,175,50),footer_sep:Ln,footer_model:j(80,175,235),footer_branch:j(80,210,100),footer_project:j(130,130,145),footer_divider:j(80,80,95),footer_mode:j(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"},Dc={reset:Nc,bold:Mc,dim:j(110,110,120),primary:j(0,110,190),secondary:j(0,125,148),success:j(0,148,62),warning:j(168,92,0),error:j(188,32,32),muted:j(110,110,120),subtle:j(155,155,165),tool_read:j(0,110,190),tool_write:j(168,92,0),tool_exec:j(128,42,188),tool_search:j(0,122,148),tool_git:j(0,138,62),tool_web:j(0,112,178),tool_sysadmin:j(168,82,0),tool_default:j(0,138,62),syn_keyword:j(128,42,188),syn_string:j(0,138,62),syn_number:j(168,92,0),syn_comment:j(135,135,148),syn_key:j(0,110,190),diff_add:j(0,148,62),diff_rem:j(188,32,32),banner_logo:j(0,122,205),banner_name:j(0,122,205),banner_version:j(100,100,118),banner_model:j(100,100,118),banner_yolo:j(168,62,0),footer_sep:j(168,168,178),footer_model:j(0,102,175),footer_branch:j(0,138,62),footer_project:j(135,135,148),footer_divider:j(168,168,178),footer_mode:j(148,88,0),white:j(40,40,52),red:j(188,32,32),green:j(0,148,62),yellow:j(168,92,0),blue:j(0,110,190),magenta:j(128,42,188),cyan:j(0,125,148),gray:j(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:j(0,158,182),brightMagenta:j(158,52,208),brightBlue:j(0,112,208)},ah=Ic?Lc:Dc;jc.exports={T:ah,isDark:Ic,DARK:Lc,LIGHT:Dc}});var jn=G((tv,Fc)=>{var{T:B}=hn(),xo=5,Dn=(()=>{let t=[];for(let e=0;e<xo;e++)t.push(e);for(let e=xo-2;e>=1;e--)t.push(e);return t})(),qc=["\u273D","\u2726","\u2727","\u2726"],oi=class{constructor(e="Thinking..."){this.text=e,this.frame=0,this.interval=null,this.startTime=null}_render(){if(this._stopped)return;let e=Dn[this.frame%Dn.length],n="";for(let s=0;s<xo;s++)n+=s===e?`${B.cyan}\u25CF${B.reset}`:" ";let o="";if(this.startTime){let s=Math.floor((Date.now()-this.startTime)/1e3);if(s>=60){let r=Math.floor(s/60),i=s%60;o=` ${B.dim}${r}m ${String(i).padStart(2,"0")}s${B.reset}`}else s>=1&&(o=` ${B.dim}${s}s${B.reset}`)}process.stderr.write(`\x1B[2K\r${n} ${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}},ri=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 n=Math.floor(e/60),o=e%60;return n>0?`${n}m ${String(o).padStart(2,"0")}s`:`${o}s`}_render(){if(this._stopped)return;let e=Dn[this.frame%Dn.length],n=`${B.cyan}\u25CF${B.reset}`,o=`${B.dim}\u25CB${B.reset}`,s=this._formatElapsed(),r=s?` ${B.dim}${s}${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;case"retry":l=`${B.yellow}\u21BB${B.reset}`,u=B.yellow;break;default:l=c===e?n:" ",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 n=0;n<this.lineCount;n++)e+=`
|
|
5
5
|
`;this.lineCount>0&&(e+=`\x1B[${this.lineCount}A`),process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),100)}update(e,n){e>=0&&e<this.statuses.length&&(this.statuses[e]=n)}stop(e={}){if(this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),!e.silent)this._renderFinal();else{let n="";for(let o=0;o<this.lineCount;o++)n+=`\x1B[2K
|
|
6
6
|
`;this.lineCount>0&&(n+=`\x1B[${this.lineCount}A`),process.stderr.write(n)}process.stderr.write("\x1B[?25h")}_renderFinal(){let e=this._formatElapsed(),n=e?` ${B.dim}${e}${B.reset}`:"",o="";for(let s=0;s<this.labels.length;s++){let r;switch(this.statuses[s]){case"done":r=`${B.green}\u2713${B.reset}`;break;case"error":r=`${B.red}\u2717${B.reset}`;break;case"retry":r=`${B.yellow}\u21BB${B.reset}`;break;default:r=`${B.yellow}\u25CB${B.reset}`}let i=s===this.labels.length-1?n:"";o+=`\x1B[2K ${r} ${B.dim}${this.labels[s]}${B.reset}${i}
|
|
7
|
-
`}process.stderr.write(o)}},
|
|
8
|
-
`;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=
|
|
7
|
+
`}process.stderr.write(o)}},bo={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},_o={done:B.green,in_progress:B.cyan,pending:B.dim,failed:B.red},Qt=null,ii=class{constructor(e,n){this.name=e,this.tasks=n.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 n=Math.floor(e/60),o=e%60;return n>0?`${n}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=qc[this.frame%qc.length],n=this._formatElapsed(),o=this._formatTokens(),s=[n,o?`\u2193 ${o} tokens`:""].filter(Boolean).join(" \xB7 "),r=s?` ${B.dim}(${s})${B.reset}`:"",i=`\x1B[2K${B.cyan}${e}${B.reset} ${this.name}\u2026${r}
|
|
8
|
+
`;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=bo[l.status]||bo.pending,f=_o[l.status]||_o.pending,m=l.description.length>55?l.description.substring(0,52)+"...":l.description;i+=`\x1B[2K ${B.dim}${u}${B.reset} ${f}${d}${B.reset} ${m}
|
|
9
9
|
`}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 n=0;n<this.lineCount;n++)e+=`
|
|
10
|
-
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120),
|
|
10
|
+
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120),Qt=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,Qt===this&&(Qt=null)}pause(){if(this._paused)return;this.interval&&(clearInterval(this.interval),this.interval=null);let e="";for(let n=0;n<this.lineCount;n++)e+=`\x1B[2K
|
|
11
11
|
`;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 n=0;n<this.lineCount;n++)e+=`
|
|
12
12
|
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120)}updateTask(e,n){let o=this.tasks.find(s=>s.id===e);o&&(o.status=n)}setStats({tokens:e}){e!==void 0&&(this.tokens=e)}isActive(){return this.interval!==null||this._paused}_renderFinal(){let e=this._formatElapsed(),n=this.tasks.filter(c=>c.status==="done").length,o=this.tasks.filter(c=>c.status==="failed").length,s=this.tasks.length,r=o>0?`${n}/${s} done, ${o} failed`:`${n}/${s} done`,i=`\x1B[2K${B.green}\u2714${B.reset} ${this.name} ${B.dim}(${e} \xB7 ${r})${B.reset}
|
|
13
|
-
`;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=
|
|
14
|
-
`}process.stderr.write(i)}},
|
|
15
|
-
`),o=n.slice(0,e),s=n.length-e,r=`${
|
|
13
|
+
`;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=bo[l.status]||bo.pending,f=_o[l.status]||_o.pending,m=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}${m}${B.reset}
|
|
14
|
+
`}process.stderr.write(i)}},ai=class{constructor(e,n){this.toolName=e,this.message=n||`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=Dn[this.frame%Dn.length],n="";for(let r=0;r<xo;r++)n+=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 s="";if(this.startTime){let r=Math.floor((Date.now()-this.startTime)/1e3);r>=1&&(s=` ${B.dim}${r}s${B.reset}`)}process.stderr.write(`\x1B[2K\r${n} ${B.dim}${o}${B.reset}${s}`),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),process.stderr.isTTY&&(process.stderr.write("\x1B[?25l"),this._render(),this.interval=setInterval(()=>this._render(),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 ch(t){Qt=t}function lh(){return Qt}function uh(){Qt&&(Qt.stop(),Qt=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}Fc.exports={C:B,Spinner:oi,MultiProgress:ri,TaskProgress:ii,ToolProgress:ai,setActiveTaskProgress:ch,getActiveTaskProgress:lh,cleanupTerminal:uh}});var Bc=G((nv,Wc)=>{var{T:C}=hn(),rt=C;function Uc(t){if(!t)return"";let e=t.replace(/^\.\//,"").split("/");return e.length>1?e.slice(-2).join("/"):e[0]}var dh={read_file:C.tool_read,list_directory:C.tool_read,write_file:C.tool_write,edit_file:C.tool_write,patch_file:C.tool_write,bash:C.tool_exec,grep:C.tool_search,search_files:C.tool_search,glob:C.tool_search,git_commit:C.tool_git,git_push:C.tool_git,git_pull:C.tool_git,git_status:C.tool_git,git_diff:C.tool_git,git_log:C.tool_git,git_branch:C.tool_git,git_stash:C.tool_git,web_fetch:C.tool_web,web_search:C.tool_web,sysadmin:C.tool_sysadmin,ssh_exec:C.tool_sysadmin,ssh_upload:C.tool_sysadmin,ssh_download:C.tool_sysadmin,deploy:C.tool_sysadmin},ci={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 ko(t,e=!1,n=null){if(e)return`${C.error}\u25CF${C.reset}`;let o=dh[t]||C.tool_default;return n==="blink"?`${o}\x1B[5m\u25CF\x1B[25m${C.reset}`:`${o}${n!==null?n:"\u25CF"}${C.reset}`}function fh(t,e,n=!1,o=null){let s=(t||[]).filter(l=>l&&l.canExecute!==!1);if(s.length===0)return`${ko("",n,o)} Step ${e}`;if(s.length===1){let l=s[0],u=l.args||{},d=ci[l.fnName]||l.fnName.replace(/_/g," "),f="";u.path?f=Uc(u.path):u.command?f=String(u.command).substring(0,60):u.query?f=String(u.query).substring(0,50):u.pattern&&(f=String(u.pattern).substring(0,50));let m=f?`${rt.dim}(${f})${rt.reset}`:"";return`${ko(l.fnName,n,o)} ${rt.bold}${d}${rt.reset} ${m}`}let r=s[0].fnName,i=[...new Set(s.map(l=>ci[l.fnName]||l.fnName.replace(/_/g," ")))],c=i.length<=3?i.join(" \xB7 "):`${s.length} actions`;return`${ko(r,n,o)} ${c}`}function ph(t,e){let n;switch(t){case"write_file":case"edit_file":case"patch_file":case"read_file":case"list_directory":n=Uc(e.path);break;case"bash":case"ssh_exec":n=(e.command||"").substring(0,80);break;case"grep":case"search_files":n=e.pattern?`"${e.pattern}"${e.path?` in ${e.path}`:""}`:"";break;case"glob":n=e.pattern||"";break;case"web_fetch":n=(e.url||"").substring(0,60);break;case"web_search":n=(e.query||"").substring(0,50);break;default:n=JSON.stringify(e).substring(0,80)}let o=ci[t]||t.replace(/_/g," "),s=n?` ${rt.dim}(${n})${rt.reset}`:"";return`${ko(t)} ${rt.bold}${o}${rt.reset}${s}`}function mh(t,e=8){let n=t.split(`
|
|
15
|
+
`),o=n.slice(0,e),s=n.length-e,r=`${C.muted} \u2514 ${C.reset}`,i=" ",c=o.map((l,u)=>`${u===0?r:i}${C.success}${l}${C.reset}`).join(`
|
|
16
16
|
`);return s>0&&(c+=`
|
|
17
|
-
${
|
|
17
|
+
${C.subtle} \u2026 +${s} lines${C.reset}`),c}function hh(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 n=e.server&&e.server!=="local"?` [${e.server}]`:"";switch(e.action){case"audit":return`Sysadmin${n}: full audit...`;case"disk_usage":return`Sysadmin${n}: disk usage ${e.path||"/"}...`;case"process_list":return`Sysadmin${n}: top processes (${e.sort_by||"cpu"})...`;case"network_status":return`Sysadmin${n}: network status...`;case"ssl_check":return`Sysadmin${n}: SSL check ${e.domain||e.cert_path||""}...`;case"log_tail":return`Sysadmin${n}: tail ${e.path||"log"}...`;case"find_large":return`Sysadmin${n}: find large files in ${e.path||"/"}...`;case"service":return`Sysadmin${n}: service ${e.service_action||""} ${e.service_name||""}...`;case"kill_process":return`Sysadmin${n}: kill PID ${e.pid||e.process_name||"?"}...`;case"journalctl":return`Sysadmin${n}: journal ${e.unit?`[${e.unit}]`:""}${e.since?` since ${e.since}`:""}...`;case"package":return`Sysadmin${n}: package ${e.package_action||""} ${(e.packages||[]).join(" ")}...`;case"firewall":return`Sysadmin${n}: firewall ${e.firewall_action||""}...`;case"user_manage":return`Sysadmin${n}: user ${e.user_action||""} ${e.user||""}...`;case"cron":return`Sysadmin${n}: cron ${e.cron_action||""}...`;default:return`Sysadmin${n}: ${e.action}...`}}default:return`Running: ${t}`}}function gh(t,e,n,o){let s=String(n||"");if(o){let c=s.split(`
|
|
18
18
|
`)[0].replace(/^ERROR:\s*/i,"").substring(0,80),l=s.match(/\nHINT: (.+)/),u=l?`
|
|
19
|
-
${
|
|
20
|
-
`).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,m=e.line_start||e.line_end,h=e.path?require("path").basename(e.path):null,p=h?` ${
|
|
21
|
-
`),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,m=8;if(l<=f){let h=c.map(p=>` ${
|
|
19
|
+
${C.muted}${l[1].substring(0,100)}${C.reset}`:"";return` ${C.error}\u2514 ${c}${C.reset}${u}`}let r;switch(t){case"read_file":{let l=s.split(`
|
|
20
|
+
`).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,m=e.line_start||e.line_end,h=e.path?require("path").basename(e.path):null,p=h?` ${C.muted}from ${h}${C.reset}`:"";m&&f>u?r=`Read lines ${e.line_start||1}\u2013${f}${p}`:r=`Read ${u} line${u!==1?"s":""}${p}`;break}case"write_file":{let c=(e.content||"").split(`
|
|
21
|
+
`),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,m=8;if(l<=f){let h=c.map(p=>` ${C.muted}${p}${C.reset}`).join(`
|
|
22
22
|
`);r=`${d}
|
|
23
|
-
${h}`}else{let h=c.slice(0,m).map(p=>` ${
|
|
23
|
+
${h}`}else{let h=c.slice(0,m).map(p=>` ${C.muted}${p}${C.reset}`).join(`
|
|
24
24
|
`);r=`${d}
|
|
25
25
|
${h}
|
|
26
|
-
${
|
|
26
|
+
${C.subtle}\u2026 +${l-m} lines${C.reset}`}break}case"edit_file":{let c=(e.old_text||"").split(`
|
|
27
27
|
`),l=(e.new_text||"").split(`
|
|
28
|
-
`),u=c.length,d=l.length,f=e.path?require("path").basename(e.path):null,m=f?` ${
|
|
28
|
+
`),u=c.length,d=l.length,f=e.path?require("path").basename(e.path):null,m=f?` ${C.muted}${f}${C.reset}`:"",h=c.find(y=>y.trim()),p=l.find(y=>y.trim()),g=[];h&&g.push(` ${C.diff_rem}- ${C.reset}${C.muted}${h.trimEnd().substring(0,72)}${C.reset}`),p&&g.push(` ${C.diff_add}+ ${C.reset}${C.muted}${p.trimEnd().substring(0,72)}${C.reset}`),r=`${C.diff_rem}\u2212${u}${C.reset} ${C.diff_add}+${d}${C.reset}${m}`+(g.length>0?`
|
|
29
29
|
`+g.join(`
|
|
30
30
|
`):"");break}case"patch_file":{let c=e.patches||[],l=c.reduce((d,f)=>d+(f.old_text||"").split(`
|
|
31
31
|
`).length,0),u=c.reduce((d,f)=>d+(f.new_text||"").split(`
|
|
32
|
-
`).length,0);r=`${
|
|
33
|
-
`).filter(m=>m&&!m.startsWith("EXIT ")&&!m.startsWith("HINT:")&&m.trim()),d=l?l[1]==="0"?`${
|
|
34
|
-
`)}break}case"grep":case"search_files":{if(s.includes("(no matches)")||s==="no matches")r=`No matches${e.pattern?` ${
|
|
35
|
-
`).filter(Boolean),u=l.length,f=new Set(l.map(w=>w.split(":")[0]).filter(Boolean)).size,m=e.pattern?` ${
|
|
36
|
-
${p(w)}`:` ${p(w)}`),y=l.length-3;y>0&&g.push(` ${
|
|
37
|
-
`)}break}case"glob":{let c=e.pattern?` ${
|
|
38
|
-
`).filter(Boolean),d=u.length,f=u.slice(0,5).map(p=>l.basename(p)),m=d-f.length,h=f.join(", ")+(m>0?`, +${m} more`:"");r=`${d} file${d!==1?"s":""}${c} \u2014 ${
|
|
39
|
-
`).filter(Boolean),l=c.length,u=c.slice(0,6).join(", "),d=l-6;r=d>0?`${l} entries \u2014 ${
|
|
32
|
+
`).length,0);r=`${C.reset}${c.length} patch${c.length!==1?"es":""} ${C.diff_rem}\u2212${l}${C.reset} ${C.diff_add}+${u}${C.reset}`;break}case"bash":{let l=s.match(/^EXIT (\d+)/),u=s.split(`
|
|
33
|
+
`).filter(m=>m&&!m.startsWith("EXIT ")&&!m.startsWith("HINT:")&&m.trim()),d=l?l[1]==="0"?`${C.success}\u2713${C.reset}`:`${C.error}\u2717 Exit ${l[1]}${C.reset}`:`${C.success}\u2713${C.reset}`,f=s.match(/\nHINT: (.+)/);if(f)r=`${d} ${C.muted}\u2014 ${f[1].substring(0,100)}${C.reset}`;else if(u.length===0)r=d;else{let m=l&&l[1]!=="0",h=m?u.slice(-3):u.slice(0,3),p=u.length-3,g=h.map((y,w)=>w===0?`${d} ${C.muted}${y.substring(0,120)}${C.reset}`:` ${C.muted}${y.substring(0,120)}${C.reset}`);if(p>0){let y=m?` ${C.subtle}${p} lines above\u2026${C.reset}`:` ${C.subtle}\u2026 +${p} lines${C.reset}`;m?g.unshift(y):g.push(y)}r=g.join(`
|
|
34
|
+
`)}break}case"grep":case"search_files":{if(s.includes("(no matches)")||s==="no matches")r=`No matches${e.pattern?` ${C.muted}"${String(e.pattern).substring(0,40)}"${C.reset}`:""}`;else{let p=function(w){let x=w.indexOf(":");if(x===-1)return`${C.muted}${w.substring(0,90)}${C.reset}`;let R=w.substring(0,x),k=w.substring(x+1),_=k.match(/^(\d+)[:-](.*)/s),b=_?`:${_[1]}`:"",A=(_?_[2]:k).trim(),M=`${C.subtle}${c.basename(R)}${b}${C.reset}`,O=`${C.muted}${A.substring(0,80)}${A.length>80?"\u2026":""}${C.reset}`;return`${M} ${O}`};var i=p;let c=require("path"),l=s.split(`
|
|
35
|
+
`).filter(Boolean),u=l.length,f=new Set(l.map(w=>w.split(":")[0]).filter(Boolean)).size,m=e.pattern?` ${C.muted}"${String(e.pattern).substring(0,40)}"${C.reset}`:"",h=f>1?`${u} match${u!==1?"es":""} in ${f} files${m}`:`${u} match${u!==1?"es":""}${m}`,g=l.slice(0,3).map((w,x)=>x===0?`${h}
|
|
36
|
+
${p(w)}`:` ${p(w)}`),y=l.length-3;y>0&&g.push(` ${C.subtle}\u2026 +${y} lines${C.reset}`),r=g.join(`
|
|
37
|
+
`)}break}case"glob":{let c=e.pattern?` ${C.muted}${String(e.pattern).substring(0,50)}${C.reset}`:"";if(s==="(no matches)")r=`No files found${c}`;else{let l=require("path"),u=s.split(`
|
|
38
|
+
`).filter(Boolean),d=u.length,f=u.slice(0,5).map(p=>l.basename(p)),m=d-f.length,h=f.join(", ")+(m>0?`, +${m} more`:"");r=`${d} file${d!==1?"s":""}${c} \u2014 ${C.muted}${h}${C.reset}`}break}case"list_directory":{if(s==="(empty)")r="0 entries";else{let c=s.split(`
|
|
39
|
+
`).filter(Boolean),l=c.length,u=c.slice(0,6).join(", "),d=l-6;r=d>0?`${l} entries \u2014 ${C.muted}${u}, +${d} more${C.reset}`:`${l} entr${l!==1?"ies":"y"} \u2014 ${C.muted}${u}${C.reset}`}break}case"git_status":{let c=s.match(/Branch:\s*(\S+)/),l=s.split(`
|
|
40
40
|
`).filter(u=>/^\s*[MADRCU?!]/.test(u)).length;r=c?`${c[1]} \xB7 ${l} change${l!==1?"s":""}`:"Done";break}case"git_diff":{let c=(s.match(/^\+[^+]/gm)||[]).length,l=(s.match(/^-[^-]/gm)||[]).length;r=c||l?`+${c} \u2212${l} lines`:"No diff";break}case"git_log":{let c=s.split(`
|
|
41
41
|
`).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=s.indexOf(c[0]||"\0");return f===-1?null:s.substring(f).split(`
|
|
42
|
-
`).find((h,p)=>p>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?` ${
|
|
42
|
+
`).find((h,p)=>p>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?` ${C.muted}+${l-1} more${C.reset}`:"";r=`${u} ${C.muted}${d.trim().substring(0,60)}${C.reset}${f}`}else r=`${l} commit${l!==1?"s":""}`;break}case"git_commit":{let c=s.match(/\[[\w./\-]+ ([0-9a-f]{7,})\]/),l=s.match(/\[[\w./\-]+ [0-9a-f]+\]\s+(.+)/);r=c?`${c[1]}${l?` \u2014 ${l[1].substring(0,55)}`:""}`:"Committed";break}case"git_push":{let c=s.match(/(?:->|→)\s*(\S+)/);r=c?`\u2192 ${c[1]}`:"Pushed";break}case"git_pull":{if(/Already up.to.date/i.test(s))r="Already up to date";else{let c=(s.match(/^\+/gm)||[]).length;r=c>0?`Pulled \xB7 +${c} lines`:"Pulled"}break}case"web_fetch":{let c=s.match(/<title[^>]*>([^<]{1,80})<\/title>/i),l=s.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 ${C.muted}${f.substring(0,70)}${C.reset}`:`Fetched ${d}`;break}case"web_search":{let c=s.split(`
|
|
43
43
|
|
|
44
44
|
`).filter(Boolean),l=c.length,u=c[0]?c[0].split(`
|
|
45
|
-
`)[0].replace(/^\d+\.\s*/,"").trim():null,d=u?` ${
|
|
46
|
-
`).filter(f=>f.trim()&&!f.startsWith("EXIT ")),d=l?`${
|
|
45
|
+
`)[0].replace(/^\d+\.\s*/,"").trim():null,d=u?` ${C.muted}\u2014 ${u.substring(0,70)}${C.reset}`:"";r=`${l} result${l!==1?"s":""}${d}`;break}case"task_list":r="Done";break;case"spawn_agents":{let c=(s.match(/✓ Agent/g)||[]).length,l=(s.match(/✗ Agent/g)||[]).length;r=l>0?`${c} done, ${l} failed`:`${c} agent${c!==1?"s":""} done`;break}case"switch_model":{let c=s.match(/Switched to (.+)/);r=c?`\u2192 ${c[1]}`:"Done";break}case"ssh_exec":{let l=s.startsWith("EXIT ")||s.startsWith("Command failed"),u=s.split(`
|
|
46
|
+
`).filter(f=>f.trim()&&!f.startsWith("EXIT ")),d=l?`${C.error}\u2717${C.reset}`:`${C.success}\u2713${C.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 m=l?u.slice(-3):u.slice(0,3),h=u.length-3,p=m.map((g,y)=>y===0?`${d} ${C.muted}${g.substring(0,120)}${C.reset}`:` ${C.muted}${g.substring(0,120)}${C.reset}`);if(h>0){let g=l?` ${C.subtle}${h} lines above\u2026${C.reset}`:` ${C.subtle}\u2026 +${h} lines${C.reset}`;l?p.unshift(g):p.push(g)}r=p.join(`
|
|
47
47
|
`)}break}default:{let c=s.split(`
|
|
48
|
-
`).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?` ${
|
|
49
|
-
${
|
|
48
|
+
`).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?` ${C.subtle}\u2026 +${c.length-1} lines${C.reset}`:"";r=`${C.muted}${l}${C.reset}${u}`}else r="Done"}}return` ${C.muted}\u2514 ${r}${C.reset}`}function $h(t,e,n,o,s,r){let i=[...n.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=`
|
|
49
|
+
${C.success}\u25C6${rt.reset} ${rt.bold}${t}${rt.reset}`;return u+=`${rt.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+=rt.reset,u}Wc.exports={C:rt,formatToolCall:ph,formatResult:mh,getToolSpinnerText:hh,formatToolSummary:gh,formatSectionHeader:fh,formatMilestone:$h}});var Me=G((sv,Gc)=>{var{T:gn}=hn(),li=gn,Hc=["01100110","01111110","01111110","01011010","01111110","00111100"];function yh(t,e){let n=[];for(let o=0;o<t.length;o+=2){let s="";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?s+=`${e}\u2588\x1B[0m`:i&&!c?s+=`${e}\u2580\x1B[0m`:!i&&c?s+=`${e}\u2584\x1B[0m`:s+=" "}n.push(s)}return n}function wh(t,e,n={}){let o=li.bold,s=li.reset,r=yh(Hc,gn.banner_logo),i=n.yolo?` ${o}${gn.banner_yolo}\u26A1 YOLO${s}`:"",c=In().version,l=[` ${gn.banner_name}${o}nex-code${s} ${gn.banner_version}v${c}${s}`,` ${gn.banner_model}${t}${s} ${gn.muted}\xB7 /help${s}${i}`,""],u=Math.max(r.length,l.length),d=Math.floor((u-r.length)/2),f=Math.floor((u-l.length)/2),m=Hc[0].length,h=[];for(let p=0;p<u;p++){let g=r[p-d]??" ".repeat(m),y=l[p-f]??"";h.push(g+y)}console.log(`
|
|
50
50
|
`+h.join(`
|
|
51
51
|
`)+`
|
|
52
|
-
`)}var{Spinner:
|
|
53
|
-
`){u(s);return}if(m==="\x1B[A"){s=(s-1+n.length)%n.length,c();return}if(m==="\x1B[B"){s=(s+1)%n.length,c();return}let h=m.toLowerCase().trim();if(h==="y"){l(!0);return}if(h==="n"){l(!1);return}if(h==="a"&&e.toolName){
|
|
54
|
-
`)};return s.length>0&&(r.images=s),r}return n})}async chat(e,n,o={}){await this.discoverModels();let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||16384,c;try{c=await
|
|
55
|
-
`);p=y.pop()||"";for(let w of y){if(!w.trim())continue;let
|
|
52
|
+
`)}var{Spinner:bh,MultiProgress:_h,TaskProgress:xh,ToolProgress:kh,setActiveTaskProgress:vh,getActiveTaskProgress:Sh,cleanupTerminal:Eh}=jn(),{formatToolCall:Th,formatResult:Rh,getToolSpinnerText:Ch,formatToolSummary:Ah,formatSectionHeader:Oh,formatMilestone:Nh}=Bc();Gc.exports={C:li,banner:wh,Spinner:bh,MultiProgress:_h,TaskProgress:xh,ToolProgress:kh,setActiveTaskProgress:vh,getActiveTaskProgress:Sh,cleanupTerminal:Eh,formatToolCall:Th,formatResult:Rh,getToolSpinnerText:Ch,formatToolSummary:Ah,formatSectionHeader:Oh,formatMilestone:Nh}});var Je=G((ov,Vc)=>{var Mh=require("readline"),{C:Lt}=Me(),fi=[/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/],Kc=[...fi,/\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 Ph(t){for(let e of Kc)if(e.test(t))return e;return null}var Yc=[/\.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)/],Ih=/\b(?:rm|rmdir|unlink|truncate|shred|mv|cp)\b/,ui=[/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 zc(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 s=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=>s(u)):ui.some(l=>l.test(r))}return/^\w+=\$?\(/.test(i)||/^\w+=["']/.test(i)||/^\w+=\S/.test(i)?!0:ui.some(c=>c.test(i))};return o.every(s)}var pi=[/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)/],Xc=[/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/],Jc=[...pi,...Xc],mi=!1,$n=null,di=null;function Lh(t){mi=t}function Dh(t){di=t}function jh(){return mi}function qh(t){$n=t}function Fh(t){for(let e of fi)if(e.test(t))return e;return null}function Uh(t){if(/ssh\s/.test(t)&&zc(t))return!1;for(let e of Jc)if(e.test(t))return!0;return!1}function Wh(t){for(let e of pi)if(e.test(t))return!0;return!1}function Bh(t){if(process.env.NEX_UNPROTECT==="1"||!Ih.test(t))return null;for(let e of Yc)if(e.test(t))return e;return null}function Hh(t,e={}){if(mi)return Promise.resolve(!0);if(di)return di(t,e);if(!process.stdout.isTTY||!process.stdin.isTTY)return Gh(t,e);let n=e.toolName?["Yes","No","Always allow"]:["Yes","No"];return new Promise(o=>{let s=0;$n&&$n.pause();let r=global._nexRawWrite||(f=>process.stdout.write(f)),i=()=>{let f=process.stdout.rows||24;return Math.max(1,f-n.length-2)},c=()=>{let f=i(),m=`\x1B[${f};1H\x1B[2K${Lt.yellow}${t}${Lt.reset}`;for(let h=0;h<n.length;h++){let p=h===s,g=p?`${Lt.yellow}\u276F${Lt.reset}`:" ",y=p?`${Lt.yellow}${n[h]}${Lt.reset}`:n[h];m+=`\x1B[${f+1+h};1H\x1B[2K ${g} ${y}`}r(m)},l=f=>{process.stdin.setRawMode(!1),process.stdin.pause(),process.stdin.removeListener("data",d);let m=global._nexRawWrite||(g=>process.stdout.write(g)),h=i(),p="";for(let g=0;g<n.length+1;g++)p+=`\x1B[${h+g};1H\x1B[2K`;m(p),global._nexFooter&&global._nexFooter.drawFooter(),$n&&$n.resume(),o(f)},u=f=>{if(f===1){l(!1);return}f===2&&e.toolName&&vo(e.toolName),l(!0)},d=f=>{if(f[0]===3){l(!1);return}let m=f.toString();if(m==="\r"||m===`
|
|
53
|
+
`){u(s);return}if(m==="\x1B[A"){s=(s-1+n.length)%n.length,c();return}if(m==="\x1B[B"){s=(s+1)%n.length,c();return}let h=m.toLowerCase().trim();if(h==="y"){l(!0);return}if(h==="n"){l(!1);return}if(h==="a"&&e.toolName){vo(e.toolName),l(!0);return}};c(),process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",d)})}function Gh(t,e){let n=e.toolName?"[Y/n/a] ":"[Y/n] ";return new Promise(o=>{let s=r=>{let i=r.trim().toLowerCase();i==="a"&&e.toolName?(vo(e.toolName),o(!0)):o(i!=="n")};if($n)$n.question(`${Lt.yellow}${t} ${n}${Lt.reset}`,s);else{let r=Mh.createInterface({input:process.stdin,output:process.stdout});r.question(`${Lt.yellow}${t} ${n}${Lt.reset}`,i=>{r.close(),s(i)})}})}var vo=()=>{};function Kh(t){vo=t}Vc.exports={FORBIDDEN_PATTERNS:fi,SSH_FORBIDDEN_PATTERNS:Kc,BASH_PROTECTED_PATHS:Yc,SSH_SAFE_PATTERNS:ui,isSSHReadOnly:zc,DANGEROUS_BASH:Jc,CRITICAL_BASH:pi,NOTABLE_BASH:Xc,isForbidden:Fh,isSSHForbidden:Ph,isDangerous:Uh,isCritical:Wh,isBashPathForbidden:Bh,confirm:Hh,setAutoConfirm:Lh,getAutoConfirm:jh,setConfirmHook:Dh,setReadlineInterface:qh,setAllowAlwaysHandler:Kh}});var qn=G((rv,Qc)=>{async function Yh(t,e){if(!t.response?.data)return t.message;let n=t.response.data;if(typeof n=="object"&&n!==null&&typeof n.pipe!="function")return e(n)||t.message;try{let o=await new Promise((r,i)=>{let c=[];n.on("data",l=>c.push(l)),n.on("end",()=>r(Buffer.concat(c).toString("utf8"))),n.on("error",i)}),s=JSON.parse(o);return e(s)||o||t.message}catch{return t.message}}var hi=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,n,o={}){throw new Error(`${this.name}: chat() not implemented`)}async stream(e,n,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`)}};Qc.exports={BaseProvider:hi,readStreamErrorBody:Yh}});var tl=G((iv,el)=>{var So=require("axios"),zh=require("http"),Xh=require("https"),{BaseProvider:Jh,readStreamErrorBody:Vh}=qn(),Eo=new zh.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),To=new Xh.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Zc={"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}},gi=class extends Jh{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||Zc,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){So.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Eo,httpsAgent:To}).then(e=>{let n=e.data?.models||[];for(let o of n){let s=(o.name||o.model||"").replace(/:latest$/,"");!s||this.models[s]||(this.models[s]={id:s,name:o.name||s,maxTokens:16384,contextWindow:131072})}}).catch(()=>{});return}try{let n=(await So.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Eo,httpsAgent:To})).data?.models||[];for(let o of n){let s=(o.name||o.model||"").replace(/:latest$/,"");!s||this.models[s]||(this.models[s]={id:s,name:o.name||s,maxTokens:16384,contextWindow:131072})}}catch{}}}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OLLAMA_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OLLAMA_API_KEY not set");return{Authorization:`Bearer ${e}`}}_formatMessages(e){return e.map(n=>{if(n.role==="user"&&Array.isArray(n.content)){let o=[],s=[];for(let i of n.content)i.type==="text"?o.push(i.text??""):i.type==="image"&&i.data&&s.push(i.data);let r={role:"user",content:o.join(`
|
|
54
|
+
`)};return s.length>0&&(r.images=s),r}return n})}async chat(e,n,o={}){await this.discoverModels();let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||16384,c;try{c=await So.post(`${this.baseUrl}/api/chat`,{model:s,messages:this._formatMessages(e),tools:n&&n.length>0?n:void 0,stream:!1,options:{temperature:o.temperature??this.temperature,num_predict:i}},{timeout:o.timeout||this.timeout,headers:this._getHeaders(),httpAgent:Eo,httpsAgent:To})}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,n,o={}){await this.discoverModels();let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||16384,c=o.onToken||(()=>{}),l=o.onThinkingToken||(()=>{}),u;try{u=await So.post(`${this.baseUrl}/api/chat`,{model:s,messages:this._formatMessages(e),tools:n&&n.length>0?n: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:Eo,httpsAgent:To})}catch(d){if(d.name==="CanceledError"||d.name==="AbortError"||d.code==="ERR_CANCELED")throw d;let f=d.response?.status?` [HTTP ${d.response.status}]`:"",m=await Vh(d,h=>h?.error);throw new Error(`API Error${f}: ${m}`)}return new Promise((d,f)=>{let m="",h=[],p="";o.signal&&o.signal.addEventListener("abort",()=>{u.data.destroy(),f(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",g=>{p+=g.toString();let y=p.split(`
|
|
55
|
+
`);p=y.pop()||"";for(let w of y){if(!w.trim())continue;let x;try{x=JSON.parse(w)}catch{continue}if(x.message?.thinking&&l(x.message.thinking),x.message?.content&&(c(x.message.content),m+=x.message.content),x.message?.tool_calls&&(h=h.concat(x.message.tool_calls)),x.done){d({content:m,tool_calls:this._normalizeToolCalls(h)});return}}}),u.data.on("error",g=>{o.signal?.aborted||f(new Error(`Stream error: ${g.message}`))}),u.data.on("end",()=>{if(p.trim())try{let g=JSON.parse(p);g.message?.thinking&&l(g.message.thinking),g.message?.content&&(c(g.message.content),m+=g.message.content),g.message?.tool_calls&&(h=h.concat(g.message.tool_calls))}catch{}d({content:m,tool_calls:this._normalizeToolCalls(h)})})})}normalizeResponse(e){let n=e.message||{};return{content:n.content||"",tool_calls:this._normalizeToolCalls(n.tool_calls||[])}}_normalizeToolCalls(e){return e.map((n,o)=>({id:n.id||`ollama-${Date.now()}-${o}`,function:{name:n.function?.name||n.name||"unknown",arguments:n.function?.arguments||n.arguments||{}}}))}};el.exports={OllamaProvider:gi,OLLAMA_MODELS:Zc}});var al=G((av,il)=>{var{callChat:Qh}=Re(),{estimateTokens:$i}=Ve(),nl=process.env.NEX_COMPACTION!=="false",sl=6,ol=500,Zh=`Summarize this conversation history concisely. Focus on:
|
|
56
56
|
- What files were read, created, or modified
|
|
57
57
|
- Key decisions made and their rationale
|
|
58
58
|
- Current state of the task (what's done, what's pending)
|
|
59
59
|
- Any errors encountered and how they were resolved
|
|
60
|
-
Be factual and brief. Use bullet points. Max 300 words.`;async function
|
|
61
|
-
${o}`,_compacted:!0,_originalCount:t.length},tokensRemoved:s-r}}catch{return null}}function
|
|
60
|
+
Be factual and brief. Use bullet points. Max 300 words.`;async function eg(t){if(!nl||t.length<sl)return null;let e=[{role:"system",content:Zh},{role:"user",content:rl(t)}];try{let o=((await Qh(e,[],{temperature:0,maxTokens:ol})).content||"").trim();if(!o)return null;let s=t.reduce((i,c)=>i+$i(c.content||"")+(c.tool_calls?$i(JSON.stringify(c.tool_calls)):0),0),r=$i(o);return r>=s*.8?null:{message:{role:"system",content:`[Conversation Summary \u2014 ${t.length} messages compacted]
|
|
61
|
+
${o}`,_compacted:!0,_originalCount:t.length},tokensRemoved:s-r}}catch{return null}}function rl(t){return t.map(e=>{let n=e.role==="tool"?"tool_result":e.role,o=(e.content||"").substring(0,500);if(e.tool_calls){let s=e.tool_calls.map(r=>r.function?.name).join(", ");return`[${n}] ${o}
|
|
62
62
|
tools: ${s}`}return`[${n}] ${o}`}).join(`
|
|
63
63
|
|
|
64
|
-
`)}
|
|
64
|
+
`)}il.exports={compactMessages:eg,formatMessagesForSummary:rl,COMPACTION_ENABLED:nl,COMPACTION_MIN_MESSAGES:sl,COMPACTION_SUMMARY_BUDGET:ol}});var Ve=G((cv,gl)=>{var tg=require("path");function ll(){return Re().getActiveModel()}var ng={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},yn=new Map,cl=1e3,yi=new WeakMap,ws=null;function sg(){if(ws!==null)return ws;try{let e=ll()?.provider||"ollama";return ws=ng[e]||4,ws}catch{return 4}}function og(){ws=null}function wn(t){if(!t)return 0;typeof t!="string"&&(t=JSON.stringify(t));let e=t.length<=120?t:`${t.length}:${t.substring(0,60)}:${t.substring(t.length>>1,(t.length>>1)+30)}:${t.substring(t.length-30)}`,n=yn.get(e);if(n!==void 0)return yn.delete(e),yn.set(e,n),n;let o=Math.ceil(t.length/sg());if(yn.size>=cl){let s=cl>>1,r=yn.keys();for(let i=0;i<s;i++)yn.delete(r.next().value)}return yn.set(e,o),o}function rg(t){if(yi.has(t))return yi.get(t);let e=JSON.stringify(t);return yi.set(t,e),e}function Wn(t){let n=4;if(t.content&&(n+=wn(t.content)),t.tool_calls)for(let o of t.tool_calls){n+=4,n+=wn(o.function?.name||"");let s=o.function?.arguments;typeof s=="string"?n+=wn(s):s&&(n+=wn(JSON.stringify(s)))}return n}function xt(t){let e=0;for(let n of t)e+=Wn(n);return e}function ig(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 n=t?t.length:0,o=e.length,s=0;for(let r=n;r<o;r++)s+=Wn(e[r]);return s}function Ro(t){return!t||t.length===0?0:wn(JSON.stringify(t))}function Co(){return ll()?.contextWindow||32768}function ag(t,e){let n=xt(t),o=Ro(e),s=n+o,r=Co(),i=r>0?s/r*100:0,c=0,l=0,u=0;for(let d of t){let f=Wn(d);d.role==="system"?c+=f:d.role==="tool"?u+=f:l+=f}return{used:s,limit:r,percentage:Math.round(i*10)/10,breakdown:{system:c,conversation:l,toolResults:u,toolDefinitions:o},messageCount:t.length}}var ul=parseFloat(process.env.NEX_COMPRESSION_THRESHOLD)||.75,dl=parseFloat(process.env.NEX_SAFETY_MARGIN)||.1,fl=parseInt(process.env.NEX_KEEP_RECENT,10)||10,cg=200,lg=1e3;function pl(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 s=t.split(`
|
|
65
65
|
`);if(s.length<=10){let p=Math.floor(o*.6),g=Math.floor(o*.4),y=t.substring(0,p),w=t.substring(t.length-g);return y+`
|
|
66
66
|
...(${t.length} chars total)...
|
|
67
67
|
`+w}let r=Math.floor(s.length*.4),i=Math.floor(s.length*.4),c=[],l=0,u=Math.floor(o*.4);for(let p=0;p<r&&l<u;p++)if(l+s[p].length+1>u&&s[p].trim().startsWith("```")){c.push(s[p]),l+=s[p].length+1;let g=p+1;for(;g<s.length&&l<u*1.5&&!s[g].trim().startsWith("```");)c.push(s[g]),l+=s[g].length+1,g++;g<s.length&&s[g].trim().startsWith("```")&&(c.push(s[g]),l+=s[g].length+1),p=g}else c.push(s[p]),l+=s[p].length+1;let d=[],f=0,m=Math.floor(o*.4);for(let p=s.length-1;p>=s.length-i&&f<m;p--)if(f+s[p].length+1>m&&s[p].trim().startsWith("```")){d.push(s[p]),f+=s[p].length+1;let g=p-1;for(;g>=0&&f<m*1.5&&!s[g].trim().startsWith("```");)d.push(s[g]),f+=s[g].length+1,g--;g>=0&&s[g].trim().startsWith("```")&&(d.push(s[g]),f+=s[g].length+1),p=g}else d.push(s[p]),f+=s[p].length+1;d.reverse();let h=s.length-c.length-d.length;return c.join(`
|
|
68
68
|
`)+`
|
|
69
69
|
...(${h} lines omitted, ${s.length} total)...
|
|
70
70
|
`+d.join(`
|
|
71
|
-
`)}function
|
|
72
|
-
...(truncated)`),s.tool_calls&&e==="aggressive"&&(s.tool_calls=s.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}}))),s}return t}function
|
|
71
|
+
`)}function Un(t,e="light"){let n=e==="aggressive"?100:e==="medium"?200:lg,o=e==="aggressive"?50:e==="medium"?100:cg;if(t.role==="tool"){let s=typeof t.content=="string"?t.content:JSON.stringify(t.content);return s.length>o?{...t,content:pl(s,o)}:t}if(t.role==="assistant"){let s={...t};return s.content&&s.content.length>n&&(s.content=s.content.substring(0,n)+`
|
|
72
|
+
...(truncated)`),s.tool_calls&&e==="aggressive"&&(s.tool_calls=s.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}}))),s}return t}function ml(t,e,n,o){let s=0;if(t.role==="system")return 100;if(t.role==="user")s+=35;else if(t.role==="tool"){let i=typeof t.content=="string"?t.content:JSON.stringify(t.content||"");/^(ERROR|BLOCKED|CANCELLED)/i.test(i)?s+=30:s+=15}else t.role==="assistant"&&(s+=t.tool_calls?20:10);let r=n>1?e/(n-1):1;if(s+=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(tg.basename(l)))&&c++;s+=Math.min(30,c*10)}return Math.min(100,s)}function hl(t,e=10){let n=new Set,o=t.slice(-e),s=/(?:\/[\w.-]+)+\.\w+/g;for(let r of o){let c=(typeof r.content=="string"?r.content:JSON.stringify(r.content||"")).match(s);c&&c.forEach(l=>n.add(l))}return n}var Fn={msgCount:-1,lastMsgRef:null,result:null};function ug(){Fn={msgCount:-1,lastMsgRef:null,result:null}}async function dg(t,e,n={}){let o=t.length>0?t[t.length-1]:null;if(!n.force&&Fn.result&&t.length===Fn.msgCount&&o===Fn.lastMsgRef)return Fn.result;let s=n.threshold??ul,r=n.safetyMargin??dl,i=n.keepRecent??fl,c=Co(),l=Ro(e),u=Math.floor(c*(s-r)),d=u-l,f=xt(t),m=f+l;if(m<=u){let N={messages:t,compressed:!1,compacted:!1,tokensRemoved:0};return Fn={msgCount:t.length,lastMsgRef:o,result:N},N}let h=f,p=null,g=0;t.length>0&&t[0].role==="system"&&(p=t[0],g=1);let y=Math.max(g,t.length-i),w=t.slice(g,y),x=t.slice(y),R=w.filter(N=>!N._compacted);if(R.length>=6)try{let{compactMessages:N}=al(),he=await N(R);if(he){let ce=[...w.filter(de=>de._compacted),he.message],ue=Zt(p,ce,x),Z=xt(ue);if(Z+l<=u)return{messages:ue,compressed:!0,compacted:!0,tokensRemoved:h-Z};w=ce}}catch(N){process.env.NEX_DEBUG&&console.error("[context-engine] LLM compacting failed:",N.message)}let k=(m-u)/u,_=w.map(N=>Un(N,"light")),b=Zt(p,_,x),A=xt(b);if(A+l<=u)return{messages:b,compressed:!0,compacted:!1,tokensRemoved:h-A};if(_=w.map(N=>Un(N,"medium")),b=Zt(p,_,x),A=xt(b),A+l<=u)return{messages:b,compressed:!0,compacted:!1,tokensRemoved:h-A};if(_=w.map(N=>Un(N,"aggressive")),b=Zt(p,_,x),A=xt(b),A+l<=u)return{messages:b,compressed:!0,compacted:!1,tokensRemoved:h-A};let M=hl([..._,...x]),O=_.map((N,he)=>({msg:N,score:ml(N,he,_.length,M),tokens:Wn(N)}));for(;O.length>0&&A>d;){let N=0;for(let he=1;he<O.length;he++)O[he].score<O[N].score&&(N=he);A-=O[N].tokens,O.splice(N,1)}return _=O.map(N=>N.msg),b=Zt(p,_,x),A=xt(b),{messages:b,compressed:!0,compacted:!1,tokensRemoved:h-A}}function Zt(t,e,n){let o=[];return t&&o.push(t),o.push(...e,...n),o}function fg(t,e){if(!t)return"";if(wn(t)<=e)return t;let o=e*4,s=t.split(`
|
|
73
73
|
`),r=Math.floor(o*.6),i=Math.floor(o*.4),c="",l=0;for(let h of s){if(c.length+h.length+1>r)break;c+=(c?`
|
|
74
74
|
`:"")+h,l++}let u="",d=0;for(let h=s.length-1;h>=l;h--){let p=s[h]+(u?`
|
|
75
75
|
`:"")+u;if(p.length>i)break;u=p,d++}let m=`
|
|
76
76
|
|
|
77
77
|
... (${s.length-l-d} lines omitted, ${s.length} total) ...
|
|
78
78
|
|
|
79
|
-
`;return c+m+u}var
|
|
80
|
-
`);g=w.pop()||"";for(let
|
|
81
|
-
|
|
82
|
-
`:"")+s.content;continue}if(s.role!=="system"&&s.role!=="tool"&&this._messageFormatCache.has(s)){o.push(this._messageFormatCache.get(s));continue}let r=this._formatSingleMessage(s,o);if(r){if(s.role!=="system"&&s.role!=="tool"&&this._messageStringCache.size<this._maxCacheSize){let i=this._getMessageCacheKey(s);this._messageStringCache.set(i,r),this._messageFormatCache.set(s,r)}o.push(r)}}for(let s=o.length-1;s>0;s--)o[s].role==="user"&&o[s-1].role==="user"&&o.splice(s,0,{role:"assistant",content:[{type:"text",text:"[continuing]"}]});return{messages:o,system:n}}_getMessageCacheKey(e){let n=e.role||"",o=typeof e.content=="string"?e.content.substring(0,100):"",s=e.tool_calls?e.tool_calls.length:0;return`${n}:${o.length}:${s}`}_formatSingleMessage(e,n=[]){if(e.role==="assistant"){let o=[];if(e.content&&o.push({type:"text",text:e.content}),e.tool_calls)for(let s of e.tool_calls)o.push({type:"tool_use",id:s.id||`toolu-${Date.now()}`,name:s.function.name,input:typeof s.function.arguments=="string"?JSON.parse(s.function.arguments||"{}"):s.function.arguments||{}});return{role:"assistant",content:o.length>0?o:[{type:"text",text:""}]}}if(e.role==="tool"){let o=n[n.length-1],s={type:"tool_result",tool_use_id:e.tool_call_id,content:typeof e.content=="string"?e.content:JSON.stringify(e.content)};return o&&o.role==="user"&&Array.isArray(o.content)&&o.content[0]?.type==="tool_result"?(o.content.push(s),null):{role:"user",content:[s]}}if(Array.isArray(e.content)){let o=[];for(let s of e.content)s.type==="text"?o.push({type:"text",text:s.text??""}):s.type==="image"&&s.data&&o.push({type:"image",source:{type:"base64",media_type:s.media_type||"image/png",data:s.data}});return{role:"user",content:o}}return{role:"user",content:e.content}}formatTools(e){return!e||e.length===0?[]:e.map(n=>({name:n.function.name,description:n.function.description||"",input_schema:n.function.parameters||{type:"object",properties:{}}}))}_resolveModelId(e){return this.getModel(e)?.id||e}async chat(e,n,o={}){let s=o.model||this.defaultModel,r=this._resolveModelId(s),i=this.getModel(s),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(n);f.length>0&&(d.tools=f);let m;try{m=await
|
|
83
|
-
`);R=_.pop()||"";for(let b of _){let
|
|
84
|
-
`);g=w.pop()||"";for(let
|
|
85
|
-
`)};return s.length>0&&(r.images=s),r}return n})}async chat(e,n,o={}){this._modelsLoaded||await this.loadModels();let s=o.model||this.defaultModel;if(!s)throw new Error("No local model available. Is Ollama running?");let r;try{r=await
|
|
86
|
-
`);f=h.pop()||"";for(let p of h){if(!p.trim())continue;let g;try{g=JSON.parse(p)}catch{continue}if(g.message?.content&&(r(g.message.content),u+=g.message.content),g.message?.tool_calls&&(d=d.concat(g.message.tool_calls)),g.done){c({content:u,tool_calls:this._normalizeToolCalls(d)});return}}}),i.data.on("error",m=>{o.signal?.aborted||l(new Error(`Stream error: ${m.message}`))}),i.data.on("end",()=>{if(f.trim())try{let m=JSON.parse(f);m.message?.content&&(r(m.message.content),u+=m.message.content),m.message?.tool_calls&&(d=d.concat(m.message.tool_calls))}catch{}c({content:u,tool_calls:this._normalizeToolCalls(d)})})})}normalizeResponse(e){let n=e.message||{};return{content:n.content||"",tool_calls:this._normalizeToolCalls(n.tool_calls||[])}}_parseContextFromModelfile(e){if(!e)return null;let n=e.match(/PARAMETER\s+num_ctx\s+(\d+)/i);return n?parseInt(n[1],10):null}_normalizeToolCalls(e){return e.map((n,o)=>({id:n.id||`local-${Date.now()}-${o}`,function:{name:n.function?.name||n.name||"unknown",arguments:n.function?.arguments||n.arguments||{}}}))}};
|
|
87
|
-
`)}}function
|
|
88
|
-
`)}function
|
|
89
|
-
`),c}catch(c){throw s.stop(),c}}async function
|
|
79
|
+
`;return c+m+u}var pg=6;function mg(t,e,n=!1){let o=Co(),s=Ro(e),r=Math.floor(o*(n?.35:.5))-s,i=xt(t),c=Math.floor(i*(n?.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=n?2:pg,f=Math.max(u,t.length-d),m=t.slice(u,f),h=t.slice(f),p=m.map(_=>Un(_,"aggressive"));n&&(h=h.map(_=>Un(_,"aggressive")));let g=Zt(l,p,h),y=xt(g);for(;p.length>0&&y>r;){let _=p.shift();y-=Wn(_)}n&&y>r&&(h=h.filter(b=>b.role==="user").slice(-1),g=Zt(l,[],h),y=xt(g)),g=Zt(l,p,h);let w=t.filter(_=>_.role==="user"),x=_=>{let b=typeof _.content=="string"?_.content:"";return b.startsWith("[SYSTEM WARNING]")||b.startsWith("[SYSTEM:")||b.startsWith("BLOCKED:")},R=w.find(_=>!x(_)),k=[...w].reverse().find(_=>!x(_));if(R&&!g.find(_=>_===R)){let _=g.findIndex(A=>A.role==="system"),b=_>=0?_+1:0;g.splice(b,0,R)}return k&&k!==R&&!g.find(_=>_===k)&&g.push(k),{messages:g,tokensRemoved:i-xt(g)}}gl.exports={estimateTokens:wn,estimateMessageTokens:Wn,estimateMessagesTokens:xt,estimateDeltaTokens:ig,estimateToolsTokens:Ro,serializeMessage:rg,getContextWindow:Co,getUsage:ag,compressMessage:Un,compressToolResult:pl,scoreMessageRelevance:ml,extractActiveFiles:hl,fitToContext:dg,forceCompress:mg,truncateFileContent:fg,invalidateTokenRatioCache:og,invalidateFitToContextCache:ug,COMPRESSION_THRESHOLD:ul,SAFETY_MARGIN:dl,KEEP_RECENT:fl}});var bl=G((uv,wl)=>{var $l=require("axios"),{BaseProvider:hg,readStreamErrorBody:gg}=qn(),{serializeMessage:lv}=Ve(),yl={"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}},wi=class extends hg{constructor(e={}){super({name:"openai",baseUrl:e.baseUrl||"https://api.openai.com/v1",models:e.models||yl,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 n=[];for(let o of e){if(this._messageFormatCache.has(o)){n.push(this._messageFormatCache.get(o));continue}let s=this._getMessageCacheKey(o);if(this._messageStringCache.has(s)){let i=this._messageStringCache.get(s);this._messageFormatCache.set(o,i),n.push(i);continue}let r=this._formatSingleMessage(o);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(s,r),this._messageFormatCache.set(o,r),n.push(r)}return{messages:n}}_getMessageCacheKey(e){let n=e.role||"",o=typeof e.content=="string"?e.content.substring(0,100):"",s=e.tool_calls?e.tool_calls.length:0;return`${n}:${o.length}:${s}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||null,tool_calls:e.tool_calls.map(n=>({id:n.id||`call-${Date.now()}`,type:"function",function:{name:n.function.name,arguments:typeof n.function.arguments=="string"?n.function.arguments:JSON.stringify(n.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 n=[];for(let o of e.content)if(o.type==="text")n.push({type:"text",text:o.text??""});else if(o.type==="image"&&o.data){let s=o.data.startsWith("data:")?o.data:`data:${o.media_type||"image/png"};base64,${o.data}`;n.push({type:"image_url",image_url:{url:s,detail:"auto"}})}return{role:"user",content:n}}return{role:e.role,content:e.content}}async chat(e,n,o={}){let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||16384,{messages:c}=this.formatMessages(e),l={model:s,messages:c,max_tokens:i,temperature:o.temperature??this.temperature};n&&n.length>0&&(l.tools=n);let u;try{u=await $l.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}]`:"",m=d.response?.data?.error?.message||d.response?.data?.error||d.message;throw new Error(`API Error${f}: ${m}`)}return this.normalizeResponse(u.data)}async stream(e,n,o={}){let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||16384,c=o.onToken||(()=>{}),{messages:l}=this.formatMessages(e),u={model:s,messages:l,max_tokens:i,temperature:o.temperature??this.temperature,stream:!0};n&&n.length>0&&(u.tools=n);let d;try{d=await $l.post(`${this.baseUrl}/chat/completions`,u,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let m=f.response?.status?` [HTTP ${f.response.status}]`:"",h=await gg(f,p=>p?.error?.message||p?.error);throw new Error(`API Error${m}: ${h}`)}return new Promise((f,m)=>{let h="",p={},g="";o.signal&&o.signal.addEventListener("abort",()=>{d.data.destroy(),m(new DOMException("The operation was aborted","AbortError"))},{once:!0}),d.data.on("data",y=>{g+=y.toString();let w=g.split(`
|
|
80
|
+
`);g=w.pop()||"";for(let x of w){let R=x.trim();if(!R||!R.startsWith("data: "))continue;let k=R.slice(6);if(k==="[DONE]"){f({content:h,tool_calls:this._buildToolCalls(p)});return}let _;try{_=JSON.parse(k)}catch{continue}let b=_.choices?.[0]?.delta;if(b&&(b.content&&(c(b.content),h+=b.content),b.tool_calls))for(let A of b.tool_calls){let M=A.index??0;p[M]||(p[M]={id:A.id||"",name:"",arguments:""}),A.id&&(p[M].id=A.id),A.function?.name&&(p[M].name+=A.function.name),A.function?.arguments&&(p[M].arguments+=A.function.arguments)}}}),d.data.on("error",y=>{o.signal?.aborted||m(new Error(`Stream error: ${y.message}`))}),d.data.on("end",()=>{f({content:h,tool_calls:this._buildToolCalls(p)})})})}normalizeResponse(e){let n=e.choices?.[0]?.message||{},o=(n.tool_calls||[]).map(s=>({id:s.id,function:{name:s.function.name,arguments:s.function.arguments}}));return{content:n.content||"",tool_calls:o}}_buildToolCalls(e){return Object.values(e).filter(n=>n.name).map(n=>({id:n.id||`openai-${Date.now()}`,function:{name:n.name,arguments:n.arguments}}))}};wl.exports={OpenAIProvider:wi,OPENAI_MODELS:yl}});var vl=G((fv,kl)=>{var _l=require("axios"),{BaseProvider:$g,readStreamErrorBody:yg}=qn(),{serializeMessage:dv}=Ve(),xl={"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}},wg="2023-06-01",bi=class extends $g{constructor(e={}){super({name:"anthropic",baseUrl:e.baseUrl||"https://api.anthropic.com/v1",models:e.models||xl,defaultModel:e.defaultModel||"claude-sonnet",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this.apiVersion=e.apiVersion||wg}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 n="",o=[];for(let s of e){if(s.role==="system"){n+=(n?`
|
|
81
|
+
|
|
82
|
+
`:"")+s.content;continue}if(s.role!=="system"&&s.role!=="tool"&&this._messageFormatCache.has(s)){o.push(this._messageFormatCache.get(s));continue}let r=this._formatSingleMessage(s,o);if(r){if(s.role!=="system"&&s.role!=="tool"&&this._messageStringCache.size<this._maxCacheSize){let i=this._getMessageCacheKey(s);this._messageStringCache.set(i,r),this._messageFormatCache.set(s,r)}o.push(r)}}for(let s=o.length-1;s>0;s--)o[s].role==="user"&&o[s-1].role==="user"&&o.splice(s,0,{role:"assistant",content:[{type:"text",text:"[continuing]"}]});return{messages:o,system:n}}_getMessageCacheKey(e){let n=e.role||"",o=typeof e.content=="string"?e.content.substring(0,100):"",s=e.tool_calls?e.tool_calls.length:0;return`${n}:${o.length}:${s}`}_formatSingleMessage(e,n=[]){if(e.role==="assistant"){let o=[];if(e.content&&o.push({type:"text",text:e.content}),e.tool_calls)for(let s of e.tool_calls)o.push({type:"tool_use",id:s.id||`toolu-${Date.now()}`,name:s.function.name,input:typeof s.function.arguments=="string"?JSON.parse(s.function.arguments||"{}"):s.function.arguments||{}});return{role:"assistant",content:o.length>0?o:[{type:"text",text:""}]}}if(e.role==="tool"){let o=n[n.length-1],s={type:"tool_result",tool_use_id:e.tool_call_id,content:typeof e.content=="string"?e.content:JSON.stringify(e.content)};return o&&o.role==="user"&&Array.isArray(o.content)&&o.content[0]?.type==="tool_result"?(o.content.push(s),null):{role:"user",content:[s]}}if(Array.isArray(e.content)){let o=[];for(let s of e.content)s.type==="text"?o.push({type:"text",text:s.text??""}):s.type==="image"&&s.data&&o.push({type:"image",source:{type:"base64",media_type:s.media_type||"image/png",data:s.data}});return{role:"user",content:o}}return{role:"user",content:e.content}}formatTools(e){return!e||e.length===0?[]:e.map(n=>({name:n.function.name,description:n.function.description||"",input_schema:n.function.parameters||{type:"object",properties:{}}}))}_resolveModelId(e){return this.getModel(e)?.id||e}async chat(e,n,o={}){let s=o.model||this.defaultModel,r=this._resolveModelId(s),i=this.getModel(s),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(n);f.length>0&&(d.tools=f);let m;try{m=await _l.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 p=h.response?.status?` [HTTP ${h.response.status}]`:"",g=h.response?.data?.error?.message||h.response?.data?.error||h.message;throw new Error(`API Error${p}: ${g}`)}return this.normalizeResponse(m.data)}async stream(e,n,o={}){let s=o.model||this.defaultModel,r=this._resolveModelId(s),i=this.getModel(s),c=o.maxTokens||i?.maxTokens||8192,l=o.onToken||(()=>{}),{messages:u,system:d}=this.formatMessages(e),f={model:r,messages:u,max_tokens:c,temperature:o.temperature??this.temperature,stream:!0};d&&(f.system=d);let m=this.formatTools(n);m.length>0&&(f.tools=m);let h;try{h=await _l.post(`${this.baseUrl}/messages`,f,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal})}catch(p){if(p.name==="CanceledError"||p.name==="AbortError"||p.code==="ERR_CANCELED")throw p;let g=p.response?.status?` [HTTP ${p.response.status}]`:"",y=await yg(p,w=>w?.error?.message||w?.error);throw new Error(`API Error${g}: ${y}`)}return new Promise((p,g)=>{let y="",w=[],x=-1,R="";o.signal&&o.signal.addEventListener("abort",()=>{h.data.destroy(),g(new DOMException("The operation was aborted","AbortError"))},{once:!0}),h.data.on("data",k=>{R+=k.toString();let _=R.split(`
|
|
83
|
+
`);R=_.pop()||"";for(let b of _){let A=b.trim();if(A.startsWith("data: ")){let M=A.slice(6),O;try{O=JSON.parse(M)}catch{continue}switch(O.type){case"content_block_start":{let N=O.content_block;N?.type==="tool_use"&&(x=w.length,w.push({id:N.id,name:N.name,inputJson:""}));break}case"content_block_delta":{let N=O.delta;N?.type==="text_delta"&&N.text&&(l(N.text),y+=N.text),N?.type==="input_json_delta"&&N.partial_json!==void 0&&x>=0&&(w[x].inputJson+=N.partial_json);break}case"content_block_stop":x=-1;break;case"message_stop":p({content:y,tool_calls:this._buildToolCalls(w)});return}}}}),h.data.on("error",k=>{o.signal?.aborted||g(new Error(`Stream error: ${k.message}`))}),h.data.on("end",()=>{p({content:y,tool_calls:this._buildToolCalls(w)})})})}normalizeResponse(e){let n="",o=[];for(let s of e.content||[])s.type==="text"?n+=s.text:s.type==="tool_use"&&o.push({id:s.id,function:{name:s.name,arguments:s.input}});return{content:n,tool_calls:o}}_buildToolCalls(e){return e.filter(n=>n.name).map(n=>{let o={};if(n.inputJson)try{o=JSON.parse(n.inputJson)}catch{o=n.inputJson}return{id:n.id||`anthropic-${Date.now()}`,function:{name:n.name,arguments:o}}})}};kl.exports={AnthropicProvider:bi,ANTHROPIC_MODELS:xl}});var Rl=G((mv,Tl)=>{var Sl=require("axios"),{BaseProvider:bg,readStreamErrorBody:_g}=qn(),{serializeMessage:pv}=Ve(),El={"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}},_i=class extends bg{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||El,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 n=[];for(let o of e){if(this._messageFormatCache.has(o)){n.push(this._messageFormatCache.get(o));continue}let s=this._getMessageCacheKey(o);if(this._messageStringCache.has(s)){let i=this._messageStringCache.get(s);this._messageFormatCache.set(o,i),n.push(i);continue}let r=this._formatSingleMessage(o);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(s,r),this._messageFormatCache.set(o,r),n.push(r)}return{messages:n}}_getMessageCacheKey(e){let n=e.role||"",o=typeof e.content=="string"?e.content.substring(0,100):"",s=e.tool_calls?e.tool_calls.length:0;return`${n}:${o.length}:${s}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||"",tool_calls:e.tool_calls.map(n=>({id:n.id||`call-${Date.now()}`,type:"function",function:{name:n.function.name,arguments:typeof n.function.arguments=="string"?n.function.arguments:JSON.stringify(n.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 n=[];for(let o of e.content)if(o.type==="text")n.push({type:"text",text:o.text??""});else if(o.type==="image"&&o.data){let s=o.data.startsWith("data:")?o.data:`data:${o.media_type||"image/png"};base64,${o.data}`;n.push({type:"image_url",image_url:{url:s,detail:"auto"}})}return{role:"user",content:n}}return{role:e.role,content:e.content}}async chat(e,n,o={}){let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||8192,{messages:c}=this.formatMessages(e),l={model:s,messages:c,max_tokens:i,temperature:o.temperature??this.temperature};n&&n.length>0&&(l.tools=n);let u;try{u=await Sl.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}]`:"",m=d.response?.data?.error?.message||d.response?.data?.error||d.message;throw new Error(`API Error${f}: ${m}`)}return this.normalizeResponse(u.data)}async stream(e,n,o={}){let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||8192,c=o.onToken||(()=>{}),{messages:l}=this.formatMessages(e),u={model:s,messages:l,max_tokens:i,temperature:o.temperature??this.temperature,stream:!0};n&&n.length>0&&(u.tools=n);let d;try{d=await Sl.post(`${this.baseUrl}/chat/completions`,u,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let m=f.response?.status?` [HTTP ${f.response.status}]`:"",h=await _g(f,p=>p?.error?.message||p?.error);throw new Error(`API Error${m}: ${h}`)}return new Promise((f,m)=>{let h="",p={},g="";o.signal&&o.signal.addEventListener("abort",()=>{d.data.destroy(),m(new DOMException("The operation was aborted","AbortError"))},{once:!0}),d.data.on("data",y=>{g+=y.toString();let w=g.split(`
|
|
84
|
+
`);g=w.pop()||"";for(let x of w){let R=x.trim();if(!R||!R.startsWith("data: "))continue;let k=R.slice(6);if(k==="[DONE]"){f({content:h,tool_calls:this._buildToolCalls(p)});return}let _;try{_=JSON.parse(k)}catch{continue}let b=_.choices?.[0]?.delta;if(b&&(b.content&&(c(b.content),h+=b.content),b.tool_calls))for(let A of b.tool_calls){let M=A.index??0;p[M]||(p[M]={id:A.id||"",name:"",arguments:""}),A.id&&(p[M].id=A.id),A.function?.name&&(p[M].name+=A.function.name),A.function?.arguments&&(p[M].arguments+=A.function.arguments)}}}),d.data.on("error",y=>{o.signal?.aborted||m(new Error(`Stream error: ${y.message}`))}),d.data.on("end",()=>{f({content:h,tool_calls:this._buildToolCalls(p)})})})}normalizeResponse(e){let n=e.choices?.[0]?.message||{},o=(n.tool_calls||[]).map(s=>({id:s.id,function:{name:s.function.name,arguments:s.function.arguments}}));return{content:n.content||"",tool_calls:o}}_buildToolCalls(e){return Object.values(e).filter(n=>n.name).map(n=>({id:n.id||`call-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,function:{name:n.name,arguments:n.arguments}}))}};Tl.exports={GeminiProvider:_i,GEMINI_MODELS:El}});var Ol=G((hv,Al)=>{var Ao=require("axios"),{BaseProvider:xg,readStreamErrorBody:kg}=qn(),Cl="http://localhost:11434",xi=class extends xg{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||Cl,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 n=(await Ao.get(`${this.baseUrl}/api/tags`,{timeout:5e3})).data?.models||[];this.models={};for(let o of n){let s=o.name||o.model;if(!s)continue;let r=s.replace(/:latest$/,""),i=32768;try{let c=await Ao.post(`${this.baseUrl}/api/show`,{name:s},{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(n=>{if(n.role==="user"&&Array.isArray(n.content)){let o=[],s=[];for(let i of n.content)i.type==="text"?o.push(i.text??""):i.type==="image"&&i.data&&s.push(i.data);let r={role:"user",content:o.join(`
|
|
85
|
+
`)};return s.length>0&&(r.images=s),r}return n})}async chat(e,n,o={}){this._modelsLoaded||await this.loadModels();let s=o.model||this.defaultModel;if(!s)throw new Error("No local model available. Is Ollama running?");let r;try{r=await Ao.post(`${this.baseUrl}/api/chat`,{model:s,messages:this._formatMessages(e),tools:n&&n.length>0?n: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,n,o={}){this._modelsLoaded||await this.loadModels();let s=o.model||this.defaultModel;if(!s)throw new Error("No local model available. Is Ollama running?");let r=o.onToken||(()=>{}),i;try{i=await Ao.post(`${this.baseUrl}/api/chat`,{model:s,messages:this._formatMessages(e),tools:n&&n.length>0?n: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 kg(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",m=>{f+=m.toString();let h=f.split(`
|
|
86
|
+
`);f=h.pop()||"";for(let p of h){if(!p.trim())continue;let g;try{g=JSON.parse(p)}catch{continue}if(g.message?.content&&(r(g.message.content),u+=g.message.content),g.message?.tool_calls&&(d=d.concat(g.message.tool_calls)),g.done){c({content:u,tool_calls:this._normalizeToolCalls(d)});return}}}),i.data.on("error",m=>{o.signal?.aborted||l(new Error(`Stream error: ${m.message}`))}),i.data.on("end",()=>{if(f.trim())try{let m=JSON.parse(f);m.message?.content&&(r(m.message.content),u+=m.message.content),m.message?.tool_calls&&(d=d.concat(m.message.tool_calls))}catch{}c({content:u,tool_calls:this._normalizeToolCalls(d)})})})}normalizeResponse(e){let n=e.message||{};return{content:n.content||"",tool_calls:this._normalizeToolCalls(n.tool_calls||[])}}_parseContextFromModelfile(e){if(!e)return null;let n=e.match(/PARAMETER\s+num_ctx\s+(\d+)/i);return n?parseInt(n[1],10):null}_normalizeToolCalls(e){return e.map((n,o)=>({id:n.id||`local-${Date.now()}-${o}`,function:{name:n.function?.name||n.name||"unknown",arguments:n.function?.arguments||n.arguments||{}}}))}};Al.exports={LocalProvider:xi,DEFAULT_LOCAL_URL:Cl}});var en=G((gv,Ml)=>{"use strict";var ht=require("fs"),Nl=require("path");function vg(t){if(!t||isNaN(t))return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function Sg(t){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}catch{let e=Date.now()+t;for(;Date.now()<e;);}}function Eg(t,e){let n=Nl.dirname(t),o=Nl.join(n,`.nex-tmp.${process.pid}.${Date.now()}`);try{ht.existsSync(n)||ht.mkdirSync(n,{recursive:!0}),ht.writeFileSync(o,e,"utf-8"),ht.renameSync(o,t)}catch(s){try{ht.unlinkSync(o)}catch{}throw s}}function Tg(t,e,{timeout:n=5e3,retryMs:o=50}={}){let s=t+".lock",r=Date.now()+n;for(;;){let i=-1;try{i=ht.openSync(s,"wx"),ht.writeSync(i,Buffer.from(String(process.pid))),ht.closeSync(i),i=-1;try{return e()}finally{try{ht.unlinkSync(s)}catch{}}}catch(c){if(i!==-1)try{ht.closeSync(i)}catch{}if(c.code!=="EEXIST")throw c;try{let l=ht.readFileSync(s,"utf-8").trim(),u=parseInt(l,10);if(!vg(u)){try{ht.unlinkSync(s)}catch{}continue}}catch(l){if(l.code&&l.code!=="ENOENT")throw l;continue}if(Date.now()>=r){try{ht.unlinkSync(s)}catch{}return e()}Sg(o)}}}Ml.exports={atomicWrite:Eg,withFileLockSync:Tg}});var Hn=G(($v,Fl)=>{var Bn=require("fs"),ki=require("path"),{atomicWrite:Rg,withFileLockSync:Cg}=en(),Pl={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:{}},Oo=[],tn={};function Ag(t,e,n,o){if(Oo.push({provider:t,model:e,input:n,output:o}),tn[t]!==void 0){let s=jl(t);s.allowed||process.stderr.write(`\x1B[33m\u26A0 Budget limit reached for ${t}: $${s.spent.toFixed(2)} / $${s.limit.toFixed(2)}\x1B[0m
|
|
87
|
+
`)}}function vi(t,e){let n=Pl[t];return n?n[e]||{input:0,output:0}:{input:0,output:0}}function Il(t){let e=vi(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function Ll(){let t={};for(let r of Oo){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:Il(r)})),n=e.reduce((r,i)=>r+i.cost,0),o=e.reduce((r,i)=>r+i.input,0),s=e.reduce((r,i)=>r+i.output,0);return{totalCost:n,totalInput:o,totalOutput:s,breakdown:e}}function Og(){let{totalCost:t,totalInput:e,totalOutput:n,breakdown:o}=Ll();if(o.length===0)return"No token usage recorded this session.";let s=[];s.push("Session Token Usage:"),s.push("");for(let r of o){let i=r.cost>0?`$${r.cost.toFixed(4)}`:"free";s.push(` ${r.provider}:${r.model}`),s.push(` Input: ${r.input.toLocaleString()} tokens`),s.push(` Output: ${r.output.toLocaleString()} tokens`),s.push(` Cost: ${i}`)}return s.push(""),s.push(` Total: ${e.toLocaleString()} in + ${n.toLocaleString()} out = $${t.toFixed(4)}`),s.join(`
|
|
88
|
+
`)}function Ng(t){return!t||typeof t!="string"?0:Math.ceil(t.length/4)}function Mg(t,e,n,o){let s=vi(t,e),r=(n*s.input+o*s.output)/1e6;return r<=0?"":`[~$${r.toFixed(4)}]`}function Pg(){Oo=[]}function Ig(t,e){tn[t]=e}function Lg(t){delete tn[t]}function Dg(){return{...tn}}function Dl(t){let e=0;for(let n of Oo)n.provider===t&&(e+=Il(n));return e}function jl(t){let e=Dl(t),n=tn[t];if(n===void 0)return{allowed:!0,spent:e,limit:null,remaining:null};let o=Math.max(0,n-e);return{allowed:e<n,spent:e,limit:n,remaining:o}}function ql(){let t=ki.join(process.cwd(),".nex","config.json");if(Bn.existsSync(t))try{let e=JSON.parse(Bn.readFileSync(t,"utf-8"));e.costLimits&&typeof e.costLimits=="object"&&(tn={...e.costLimits})}catch{}}function jg(){let t=ki.join(process.cwd(),".nex"),e=ki.join(t,"config.json");Bn.existsSync(t)||Bn.mkdirSync(t,{recursive:!0}),Cg(e,()=>{let n={};if(Bn.existsSync(e))try{n=JSON.parse(Bn.readFileSync(e,"utf-8"))}catch{n={}}n.costLimits=tn,Rg(e,JSON.stringify(n,null,2))})}function qg(){tn={}}ql();Fl.exports={PRICING:Pl,trackUsage:Ag,getSessionCosts:Ll,formatCosts:Og,formatCostHint:Mg,resetCosts:Pg,getPricing:vi,setCostLimit:Ig,removeCostLimit:Lg,getCostLimits:Dg,getProviderSpend:Dl,checkBudget:jl,loadCostLimits:ql,saveCostLimits:jg,resetCostLimits:qg,estimateTokens:Ng}});var Ei=G((yv,Ul)=>{function Si(){return process.env.NEX_DEBUG==="true"||process.argv.includes("--debug")}var Fg=Si();function Ug(...t){Si()&&console.log(...t)}function Wg(...t){Si()&&console.warn(...t)}Ul.exports={DEBUG:Fg,debugLog:Ug,warnLog:Wg}});var Hl=G((wv,Bl)=>{"use strict";var Bg=new Set(["read_file","grep","glob","search_files","list_directory"]),Hg=new Set(["write_file","edit_file","patch_file"]),Gg=new Set(["bash"]),Kg=new Set(["web_search","web_fetch","perplexity_search"]);function Wl(t,e){let n=0,o=0,s=0,r=0,i=0;for(let[c,l]of t)i+=l,Bg.has(c)&&(n+=l),Hg.has(c)&&(o+=l),Gg.has(c)&&(s+=l),Kg.has(c)&&(r+=l);return i===0?`Phase ${e}`:r/i>.5?"Research":n/i>.5?"Exploration":o/i>.3?"Implementation":s/i>.3&&o/i<.15?"Verification":`Phase ${e}`}var Ti=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,n,o,s){if(this._disabled)return null;this._stepsThisPhase++;for(let i of n)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:Wl(this._phaseCounts,this._phaseNum),stepCount:this._stepsThisPhase,toolCounts:new Map(this._phaseCounts),elapsed:Date.now()-this._phaseStart,filesRead:new Set(o),filesModified:new Set(s)};return this._stepsThisPhase=0,this._phaseCounts=new Map,this._phaseStart=Date.now(),r}};Bl.exports={MilestoneTracker:Ti,_phaseName:Wl}});var Gn=G((bv,Gl)=>{var bs=Re(),Yg={"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 zg(){return bs.getActiveModel()}function Xg(t){return bs.setActiveModel(t)}function Jg(){return bs.getModelNames()}function Vg(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 n=t.match(/```(?:json)?\s*([\s\S]*?)```/);if(n)try{return JSON.parse(n[1].trim())}catch{}return null}async function Qg(t,e){let{C:n}=Me(),{Spinner:o}=Me(),s=new o("Thinking...");s.start();let r=!0,i="";try{let c=await bs.callStream(t,e,{onToken:l=>{r&&(s.stop(),process.stdout.write(`${n.blue}`),r=!1),process.stdout.write(l),i+=l}});return r?s.stop():process.stdout.write(`${n.reset}
|
|
89
|
+
`),c}catch(c){throw s.stop(),c}}async function Zg(t,e){return bs.callChat(t,e)}Gl.exports={MODELS:Yg,getActiveModel:zg,setActiveModel:Xg,getModelNames:Jg,callOllamaStream:Qg,callOllama:Zg,parseToolArgs:Vg}});var zl=G((xv,Yl)=>{var No=require("path"),{C:I}=Me(),{T:Ri,isDark:_v}=hn(),{confirm:e$,getAutoConfirm:t$}=Je(),Kl=2e3;function _s(t,e){let n=t.split(`
|
|
90
90
|
`),o=e.split(`
|
|
91
|
-
`),s=[],r=n.length,i=o.length;if(r>
|
|
92
|
-
${
|
|
93
|
-
${
|
|
94
|
-
${
|
|
95
|
-
`),o=n.slice(0,20);for(let s of o)console.log(`${
|
|
96
|
-
${
|
|
97
|
-
`)}function
|
|
98
|
-
${
|
|
99
|
-
`);return}let h=[];if(f>0&&h.push(`Added ${f} line${f!==1?"s":""}`),m>0&&h.push(`removed ${m} line${m!==1?"s":""}`),i.length>0){let b=i.filter(
|
|
91
|
+
`),s=[],r=n.length,i=o.length;if(r>Kl||i>Kl){for(let f of n)s.push({type:"remove",line:f});for(let f of o)s.push({type:"add",line:f});return s}let c=Array.from({length:r+1},()=>new Array(i+1).fill(0));for(let f=1;f<=r;f++)for(let m=1;m<=i;m++)n[f-1]===o[m-1]?c[f][m]=c[f-1][m-1]+1:c[f][m]=Math.max(c[f-1][m],c[f][m-1]);let l=r,u=i,d=[];for(;l>0||u>0;)l>0&&u>0&&n[l-1]===o[u-1]?(d.unshift({type:"same",line:n[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:n[l-1]}),l--);return d}function n$(t,e,n,o=3){console.log(`
|
|
92
|
+
${I.bold}${I.cyan} Diff: ${t}${I.reset}`);let s=_s(e,n),r=[];if(s.forEach((l,u)=>{l.type!=="same"&&r.push(u)}),r.length===0){console.log(`${I.gray} (no changes)${I.reset}`);return}let i=Math.max(0,r[0]-o),c=Math.min(s.length,r[r.length-1]+o+1);i>0&&console.log(`${I.gray} ...${I.reset}`);for(let l=i;l<c;l++){let u=s[l];switch(u.type){case"remove":console.log(`${I.red} - ${u.line}${I.reset}`);break;case"add":console.log(`${I.green} + ${u.line}${I.reset}`);break;default:console.log(`${I.gray} ${u.line}${I.reset}`)}}c<s.length&&console.log(`${I.gray} ...${I.reset}`),console.log()}function s$(t,e,n){console.log(`
|
|
93
|
+
${I.bold}${I.cyan} File exists \u2014 showing changes: ${t}${I.reset}`);let o=_s(e,n),s=0;for(let i of o)i.type!=="same"&&s++;if(s===0){console.log(`${I.gray} (identical content)${I.reset}`);return}let r=0;for(let i of o){if(r>=30){console.log(`${I.gray} ...(${s-r} more changes)${I.reset}`);break}switch(i.type){case"remove":console.log(`${I.red} - ${i.line}${I.reset}`),r++;break;case"add":console.log(`${I.green} + ${i.line}${I.reset}`),r++;break;default:r>0&&console.log(`${I.gray} ${i.line}${I.reset}`)}}console.log()}function o$(t,e){console.log(`
|
|
94
|
+
${I.bold}${I.cyan} New file: ${t}${I.reset}`);let n=e.split(`
|
|
95
|
+
`),o=n.slice(0,20);for(let s of o)console.log(`${I.green} + ${s}${I.reset}`);n.length>20&&console.log(`${I.gray} ...+${n.length-20} more lines${I.reset}`),console.log()}async function r$(t){return t$()?!0:e$(` ${t}?`)}function i$(t,e,n,o){let s=o||process.stdout.columns||80,r=Math.floor((s-3)/2);console.log(`
|
|
96
|
+
${I.bold}${I.cyan} Side-by-side: ${t}${I.reset}`),console.log(` ${I.dim}${"\u2500".repeat(r)}\u252C${"\u2500".repeat(r)}${I.reset}`);let i=_s(e,n),c=[],l=0;for(;l<i.length;)if(i[l].type==="same")c.push({left:i[l].line,right:i[l].line,type:"same"}),l++;else if(i[l].type==="remove"){let h=[];for(;l<i.length&&i[l].type==="remove";)h.push(i[l].line),l++;let p=[];for(;l<i.length&&i[l].type==="add";)p.push(i[l].line),l++;let g=Math.max(h.length,p.length);for(let y=0;y<g;y++)c.push({left:y<h.length?h[y]:"",right:y<p.length?p[y]:"",type:"changed"})}else i[l].type==="add"&&(c.push({left:"",right:i[l].line,type:"changed"}),l++);let u=c.map((h,p)=>h.type!=="same"?p:-1).filter(h=>h>=0);if(u.length===0){console.log(` ${I.gray}(no changes)${I.reset}`);return}let d=Math.max(0,u[0]-2),f=Math.min(c.length,u[u.length-1]+3),m=(h,p)=>{let g=h.replace(/\x1b\[[0-9;]*m/g,"");return g.length>=p?h.substring(0,p):h+" ".repeat(p-g.length)};d>0&&console.log(` ${I.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${I.reset}`);for(let h=d;h<f;h++){let p=c[h];if(p.type==="same")console.log(` ${I.gray}${m(p.left,r)}${I.reset}\u2502${I.gray}${m(p.right,r)}${I.reset}`);else{let g=p.left?`${I.red}${m(p.left,r)}${I.reset}`:`${m("",r)}`,y=p.right?`${I.green}${m(p.right,r)}${I.reset}`:`${m("",r)}`;console.log(` ${g}\u2502${y}`)}}f<c.length&&console.log(` ${I.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${I.reset}`),console.log(` ${I.dim}${"\u2500".repeat(r)}\u2534${"\u2500".repeat(r)}${I.reset}
|
|
97
|
+
`)}function a$(t,e,n,o={}){let s=o.label||"Update",r=o.context||3,i=o.annotations||[],c=No.isAbsolute(t)?No.relative(process.cwd(),t):t,l=_s(e,n),u=1,d=1;for(let b of l)b.type==="same"?(b.oldLine=u++,b.newLine=d++):b.type==="remove"?(b.oldLine=u++,b.newLine=null):(b.oldLine=null,b.newLine=d++);let f=0,m=0;for(let b of l)b.type==="add"?f++:b.type==="remove"&&m++;if(console.log(`
|
|
98
|
+
${I.green}\u25CF${I.reset} ${I.bold}${s}(${c})${I.reset}`),f===0&&m===0){console.log(` ${I.dim}\u2514 (no changes)${I.reset}
|
|
99
|
+
`);return}let h=[];if(f>0&&h.push(`Added ${f} line${f!==1?"s":""}`),m>0&&h.push(`removed ${m} line${m!==1?"s":""}`),i.length>0){let b=i.filter(N=>N.severity==="error").length,A=i.filter(N=>N.severity==="warn").length,M=i.filter(N=>N.severity==="info").length,O=[];b>0&&O.push(`${I.red}${b} error${b!==1?"s":""}${I.dim}`),A>0&&O.push(`${I.yellow}${A} warning${A!==1?"s":""}${I.dim}`),M>0&&O.push(`${I.cyan}${M} info${M!==1?"s":""}${I.dim}`),h.push(`found ${O.join(", ")}`)}console.log(` ${I.dim}\u2514 ${h.join(", ")}${I.reset}`);let g=[];l.forEach((b,A)=>{b.type!=="same"&&g.push(A)});let y=[],w=null,x=null;for(let b of g){let A=Math.max(0,b-r),M=Math.min(l.length-1,b+r);w===null?(w=A,x=M):(A<=x+1||(y.push([w,x]),w=A),x=M)}w!==null&&y.push([w,x]);let R=" ",k=process.stdout.columns||120;function _(b,A,M){let O=M.replace(/\x1b\[[0-9;]*m/g,""),N=M+" ".repeat(Math.max(0,k-O.length));return`${b}${A}${N}${I.reset}`}for(let b=0;b<y.length;b++){b>0&&console.log(`${R}${I.dim}\xB7\xB7\xB7${I.reset}`);let[A,M]=y[b];for(let O=A;O<=M;O++){let N=l[O],he=N.newLine!=null?N.newLine:N.oldLine,ge=String(he).padStart(4),ce=N.type!=="remove"?i.filter(ue=>ue.line===N.newLine):[];N.type==="remove"?console.log(_(Ri.diff_rem_bg,I.red,`${R}${ge} - ${N.line}`)):N.type==="add"?console.log(_(Ri.diff_add_bg,I.green,`${R}${ge} + ${N.line}`)):console.log(`${R}${I.dim}${ge} ${I.reset}${N.line}`);for(let ue of ce){let Z=I.cyan,de="\u2139";ue.severity==="error"?(Z=I.red,de="\u2716"):ue.severity==="warn"&&(Z=I.yellow,de="\u26A0"),console.log(`${R} ${Z}${de} ${ue.message}${I.reset}`)}}}console.log()}function c$(t,e,n={}){let o=No.isAbsolute(t)?No.relative(process.cwd(),t):t,s=e.split(`
|
|
100
100
|
`),r=n.annotations||[];console.log(`
|
|
101
|
-
${
|
|
102
|
-
`).filter(Boolean).map(e=>{let n=e.substring(0,2).trim(),o=e.substring(3);return{status:n,file:o}})}catch{return[]}}async function
|
|
103
|
-
`);for(let f of d)f.startsWith("+")&&!f.startsWith("+++")&&s++,f.startsWith("-")&&!f.startsWith("---")&&r++}else s=t.length;let i="chore",c=t.join(" ").toLowerCase();c.includes("test")?i="test":c.includes("readme")||c.includes("doc")?i="docs":s>r*2?i="feat":r>s?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:s,deletions:r}}}async function
|
|
104
|
-
${
|
|
105
|
-
${
|
|
106
|
-
${
|
|
101
|
+
${I.green}\u25CF${I.reset} ${I.bold}Create(${o})${I.reset}`);let i=[`${s.length} line${s.length!==1?"s":""}`];if(r.length>0){let f=r.filter(g=>g.severity==="error").length,m=r.filter(g=>g.severity==="warn").length,h=r.filter(g=>g.severity==="info").length,p=[];f>0&&p.push(`${I.red}${f} error${f!==1?"s":""}${I.dim}`),m>0&&p.push(`${I.yellow}${m} warning${m!==1?"s":""}${I.dim}`),h>0&&p.push(`${I.cyan}${h} info${h!==1?"s":""}${I.dim}`),i.push(`found ${p.join(", ")}`)}console.log(` ${I.dim}\u2514 ${i.join(", ")}${I.reset}`);let l=" ",u=process.stdout.columns||120,d=Math.min(s.length,20);for(let f=0;f<d;f++){let m=String(f+1).padStart(4),h=f+1,p=r.filter(x=>x.line===h),g=`${l}${m} + ${s[f]}`,y=g.replace(/\x1b\[[0-9;]*m/g,""),w=g+" ".repeat(Math.max(0,u-y.length));console.log(`${Ri.diff_add_bg}${I.green}${w}${I.reset}`);for(let x of p){let R=I.cyan,k="\u2139";x.severity==="error"?(R=I.red,k="\u2716"):x.severity==="warn"&&(R=I.yellow,k="\u26A0"),console.log(`${l} ${R}${k} ${x.message}${I.reset}`)}}s.length>20&&console.log(`${l}${I.dim} ...+${s.length-20} more lines${I.reset}`),console.log()}Yl.exports={diffLines:_s,showEditDiff:n$,showWriteDiff:s$,showNewFilePreview:o$,confirmFileChange:r$,showSideBySideDiff:i$,showClaudeDiff:a$,showClaudeNewFile:c$}});var nn=G((kv,Vl)=>{var Xl=require("util").promisify(require("child_process").exec),l$=require("util").promisify(require("child_process").execFile),{C:Ie}=Me();async function Ci(t){try{let{stdout:e}=await Xl(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function Mo(...t){try{let{stdout:e}=await l$("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function u$(){return await Ci("git rev-parse --is-inside-work-tree")==="true"}async function d$(){return await Ci("git branch --show-current")}async function Ai(){try{let{stdout:t}=await Xl("git status --porcelain",{cwd:process.cwd(),timeout:3e4});return!t||!t.trim()?[]:t.split(`
|
|
102
|
+
`).filter(Boolean).map(e=>{let n=e.substring(0,2).trim(),o=e.substring(3);return{status:n,file:o}})}catch{return[]}}async function Po(t=!1){return await Ci(`git diff ${t?"--cached":""}`)||""}async function Oi(){return(await Ai()).map(e=>e.file)}async function Jl(){let t=await Oi();if(t.length===0)return null;let e=await Po(),o=await Po(!0)||e,s=0,r=0;if(o){let d=o.split(`
|
|
103
|
+
`);for(let f of d)f.startsWith("+")&&!f.startsWith("+++")&&s++,f.startsWith("-")&&!f.startsWith("---")&&r++}else s=t.length;let i="chore",c=t.join(" ").toLowerCase();c.includes("test")?i="test":c.includes("readme")||c.includes("doc")?i="docs":s>r*2?i="feat":r>s?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:s,deletions:r}}}async function f$(t){let n=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await Mo("checkout","-b",n)!==null?n:null}async function p$(t){return await Mo("add","-A"),await Mo("commit","-m",t)?await Mo("rev-parse","--short","HEAD"):null}async function m$(){let t=await Jl();if(!t)return`${Ie.dim}No changes${Ie.reset}`;let e=[];e.push(`
|
|
104
|
+
${Ie.bold}${Ie.cyan}Git Diff Summary:${Ie.reset}`),e.push(` ${Ie.green}+${t.stats.additions}${Ie.reset} ${Ie.red}-${t.stats.deletions}${Ie.reset} in ${t.files.length} file(s)`),e.push(`
|
|
105
|
+
${Ie.bold}${Ie.cyan}Files:${Ie.reset}`);for(let n of t.files.slice(0,20))e.push(` ${Ie.dim}${n}${Ie.reset}`);return t.files.length>20&&e.push(` ${Ie.dim}...+${t.files.length-20} more${Ie.reset}`),e.push(`
|
|
106
|
+
${Ie.bold}${Ie.cyan}Suggested message:${Ie.reset}`),e.push(` ${Ie.cyan}${t.summary}${Ie.reset}
|
|
107
107
|
`),e.join(`
|
|
108
|
-
`)}async function
|
|
108
|
+
`)}async function h$(){return(await Ai()).filter(e=>e.status==="UU"||e.status==="AA"||e.status==="DD")}async function g$(){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 n=await Po();if(n){let o=n.length>5e3?n.substring(0,5e3)+`
|
|
109
109
|
...(truncated)`:n;e.push(`
|
|
110
110
|
DIFF:
|
|
111
111
|
${o}`)}return e.join(`
|
|
112
|
-
`)}
|
|
113
|
-
`).map(n=>{let o=n.match(/^stash@\{(\d+)\}:\s+(?:WIP on [^:]+:\s+\S+\s+|On \S+:\s+)(.*)/);if(!o)return null;let s=o[2].trim();return s.startsWith(
|
|
112
|
+
`)}Vl.exports={isGitRepo:u$,getCurrentBranch:d$,getStatus:Ai,getDiff:Po,getChangedFiles:Oi,analyzeDiff:Jl,createBranch:f$,commit:p$,formatDiffSummary:m$,getDiffContext:g$,getMergeConflicts:h$}});var Ht=G((Sv,su)=>{var Ye=require("fs").promises,vv=require("fs"),kt=require("path"),$$=require("crypto"),{execSync:xs}=require("child_process"),y$=100*1024,eu=50,it=[],Kn=[];function w$(t,e,n,o){for(it.push({tool:t,filePath:e,oldContent:n,newContent:o,timestamp:Date.now()});it.length>eu;)it.shift();Kn.length=0,tu(it[it.length-1]).catch(()=>{})}async function b$(){if(it.length===0)return null;let t=it.pop();if(t.oldContent===null)try{await Ye.unlink(t.filePath)}catch{}else await Ye.writeFile(t.filePath,t.oldContent,"utf-8");return Kn.push(t),{tool:t.tool,filePath:t.filePath,wasCreated:t.oldContent===null}}async function _$(){if(Kn.length===0)return null;let t=Kn.pop();return await Ye.writeFile(t.filePath,t.newContent,"utf-8"),it.push(t),{tool:t.tool,filePath:t.filePath}}function x$(t=10){return it.slice(-t).reverse().map(e=>({tool:e.tool,filePath:e.filePath,timestamp:e.timestamp}))}function k$(){return it.length}function v$(){return Kn.length}function S$({diskToo:t=!0}={}){if(it.length=0,Kn.length=0,t){let e=Lo();Ye.readdir(e).then(n=>{for(let o of n)o.endsWith(".json")&&Ye.unlink(kt.join(e,o)).catch(()=>{})}).catch(()=>{})}}function Lo(){return kt.join(process.cwd(),".nex","history")}async function Ql(t,e){if(t==null)return{inline:!0,content:t};if(Buffer.byteLength(t,"utf-8")<=y$)return{inline:!0,content:t};let n=$$.createHash("sha256").update(t,"utf-8").digest("hex"),o=kt.join(e,"blobs");return await Ye.mkdir(o,{recursive:!0}),await Ye.writeFile(kt.join(o,n),t,"utf-8"),{inline:!1,hash:n}}async function tu(t){let e=Lo();await Ye.mkdir(e,{recursive:!0});let n=kt.basename(t.filePath).replace(/[^a-zA-Z0-9]/g,"-"),o=`${t.timestamp}-${n}.json`,s=await Ql(t.oldContent,e),r=await Ql(t.newContent,e),i={tool:t.tool,filePath:t.filePath,timestamp:t.timestamp,oldContent:s.inline?{inline:!0,content:s.content}:{inline:!1,hash:s.hash},newContent:r.inline?{inline:!0,content:r.content}:{inline:!1,hash:r.hash}};await Ye.writeFile(kt.join(e,o),JSON.stringify(i),"utf-8")}async function Zl(t,e){if(!t)return null;if(t.inline)return t.content;let n=kt.join(e,"blobs",t.hash);return Ye.readFile(n,"utf-8")}async function E$(){let t=Lo(),e;try{e=await Ye.readdir(t)}catch{return 0}let n=e.filter(s=>s.endsWith(".json")).sort(),o=0;for(let s of n)try{let r=await Ye.readFile(kt.join(t,s),"utf-8"),i=JSON.parse(r),c=await Zl(i.oldContent,t),l=await Zl(i.newContent,t);it.push({tool:i.tool,filePath:i.filePath,timestamp:i.timestamp,oldContent:c,newContent:l}),o++}catch{}for(;it.length>eu;)it.shift();return o}async function T$(t=7){let e=Lo(),n;try{n=await Ye.readdir(e)}catch{return 0}let o=Date.now()-t*24*60*60*1e3,s=n.filter(u=>u.endsWith(".json")),r=0,i=new Set,c=[];for(let u of s)try{let d=await Ye.readFile(kt.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 Ye.unlink(kt.join(e,u))}catch{}let l=kt.join(e,"blobs");try{let u=await Ye.readdir(l);for(let d of u)if(!i.has(d))try{await Ye.unlink(kt.join(l,d))}catch{}}catch{}return r}var Io="nex-snapshot";function R$(t,e=process.cwd()){let n=t?`${Io}-${t.replace(/[^a-zA-Z0-9_-]/g,"-")}`:`${Io}-${Date.now()}`;try{return xs("git status --porcelain",{cwd:e,timeout:1e4}).toString().trim()?(xs(`git stash push -u -m "${n}"`,{cwd:e,timeout:15e3}),xs("git stash pop",{cwd:e,timeout:1e4}),{name:n,label:n,ok:!0}):{name:n,label:n,ok:!1,error:"No changes to snapshot (working tree clean)"}}catch(o){return{name:n,label:n,ok:!1,error:o.message}}}function nu(t=process.cwd()){try{let e=xs("git stash list",{cwd:t,timeout:1e4}).toString().trim();return e?e.split(`
|
|
113
|
+
`).map(n=>{let o=n.match(/^stash@\{(\d+)\}:\s+(?:WIP on [^:]+:\s+\S+\s+|On \S+:\s+)(.*)/);if(!o)return null;let s=o[2].trim();return s.startsWith(Io)?{index:parseInt(o[1],10),label:s,shortName:s.replace(`${Io}-`,""),date:n}:null}).filter(Boolean):[]}catch{return[]}}function C$(t,e=process.cwd()){try{let n=nu(e);if(n.length===0)return{ok:!1,error:"No snapshots found"};let o;return t===void 0||t==="last"?o=n[0]:typeof t=="number"?o=n.find(s=>s.index===t):o=n.find(s=>s.label===t||s.shortName===t||s.shortName.includes(String(t))),o?(xs(`git stash apply stash@{${o.index}}`,{cwd:e,timeout:15e3}),{ok:!0,label:o.label}):{ok:!1,error:`Snapshot not found: ${t}`}}catch(n){return{ok:!1,error:n.message}}}su.exports={recordChange:w$,undo:b$,redo:_$,getHistory:x$,getUndoCount:k$,getRedoCount:v$,clearHistory:S$,persistEntry:tu,loadPersistedHistory:E$,pruneHistory:T$,createSnapshot:R$,listSnapshots:nu,restoreSnapshot:C$}});var sn=G((Ev,cu)=>{var Ce=require("fs"),at=require("path"),{atomicWrite:A$,withFileLockSync:O$}=en(),ct=[];function ks(){return at.join(process.cwd(),".nex","skills")}function ou(){return at.join(process.cwd(),".nex","config.json")}function ru(){let t=ks();return Ce.existsSync(t)||Ce.mkdirSync(t,{recursive:!0}),t}function Pi(){let t=ou();if(!Ce.existsSync(t))return[];try{let e=JSON.parse(Ce.readFileSync(t,"utf-8"));return e.skills&&Array.isArray(e.skills.disabled)?e.skills.disabled:[]}catch{return[]}}function iu(t){let e=ou(),n=at.dirname(e);Ce.existsSync(n)||Ce.mkdirSync(n,{recursive:!0}),O$(e,()=>{let o={};if(Ce.existsSync(e))try{o=JSON.parse(Ce.readFileSync(e,"utf-8"))}catch{o={}}o.skills||(o.skills={}),o.skills.disabled=t,A$(e,JSON.stringify(o,null,2))})}function au(t,e){let n=[];if(typeof t!="object"||t===null)return{valid:!1,errors:["Module must export an object"]};if(t.name!==void 0&&typeof t.name!="string"&&n.push("name must be a string"),t.description!==void 0&&typeof t.description!="string"&&n.push("description must be a string"),t.instructions!==void 0&&typeof t.instructions!="string"&&n.push("instructions must be a string"),t.commands!==void 0)if(!Array.isArray(t.commands))n.push("commands must be an array");else for(let o=0;o<t.commands.length;o++){let s=t.commands[o];(!s.cmd||typeof s.cmd!="string")&&n.push(`commands[${o}].cmd must be a non-empty string`),s.handler!==void 0&&typeof s.handler!="function"&&n.push(`commands[${o}].handler must be a function`)}if(t.tools!==void 0)if(!Array.isArray(t.tools))n.push("tools must be an array");else for(let o=0;o<t.tools.length;o++){let s=t.tools[o];(!s.function||!s.function.name||typeof s.function.name!="string")&&n.push(`tools[${o}].function.name must be a non-empty string`),s.execute!==void 0&&typeof s.execute!="function"&&n.push(`tools[${o}].execute must be a function`)}return{valid:n.length===0,errors:n}}function Ni(t){try{let e=Ce.readFileSync(t,"utf-8").trim();return e?{name:at.basename(t,".md"),type:"prompt",filePath:t,instructions:e,commands:[],tools:[]}:null}catch{return null}}function Mi(t){try{let e=require(t),{valid:n,errors:o}=au(e,t);return n?{name:e.name||at.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}
|
|
114
114
|
${o.join(`
|
|
115
|
-
`)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function
|
|
115
|
+
`)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function Ii(){ct=[];let t=Pi(),e=ks(),n=[];if(Ce.existsSync(e))try{n=Ce.readdirSync(e)}catch{n=[]}for(let s of n){let r=at.join(e,s),i;try{i=Ce.statSync(r)}catch{continue}if(!i.isFile())continue;let c=null;s.endsWith(".md")?c=Ni(r):s.endsWith(".js")&&(c=Mi(r)),c&&(c.enabled=!t.includes(c.name),ct.push(c))}let o=at.join(__dirname,"skills");if(!process.env.NEX_SKIP_BUILTIN_SKILLS&&Ce.existsSync(o)){let s;try{s=Ce.readdirSync(o).filter(r=>r.endsWith(".md")||r.endsWith(".js"))}catch{s=[]}for(let r of s){let i=at.join(o,r),c=at.basename(r,at.extname(r));if(ct.some(d=>d.name===c))continue;let l;try{l=Ce.statSync(i)}catch{continue}if(!l.isFile())continue;let u=r.endsWith(".md")?Ni(i):Mi(i);u&&(u._builtin=!0,u.enabled=!t.includes(u.name),ct.push(u))}}return ct}function N$(){let t=[];for(let e of ct)!e.enabled||!e.instructions||t.push(`[Skill: ${e.name}]
|
|
116
116
|
${e.instructions}`);return t.length===0?"":`SKILL INSTRUCTIONS:
|
|
117
117
|
${t.join(`
|
|
118
118
|
|
|
119
|
-
`)}`}function
|
|
119
|
+
`)}`}function M$(){let t=[];for(let e of ct)if(e.enabled)for(let n of e.commands)t.push({cmd:n.cmd,desc:n.desc||`[skill: ${e.name}]`});return t}function P$(){let t=[];for(let e of ct)if(e.enabled)for(let n of e.tools)t.push({type:"function",function:{name:`skill_${n.function.name}`,description:`[Skill:${e.name}] ${n.function.description}`,parameters:n.function.parameters}});return t}async function I$(t,e){if(!t.startsWith("skill_"))return null;let n=t.substring(6);for(let o of ct)if(o.enabled){for(let s of o.tools)if(s.function.name===n&&s.execute)try{let r=await s.execute(e);return typeof r=="string"?r:JSON.stringify(r)}catch(r){return`ERROR: Skill tool '${n}' failed: ${r.message}`}}return`ERROR: Skill tool '${n}' not found`}function L$(t){let[e,...n]=t.split(/\s+/),o=n.join(" ").trim();for(let s of ct)if(s.enabled){for(let r of s.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 D$(){return ct.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 j$(t){let e=ct.find(o=>o.name===t);if(!e)return!1;e.enabled=!0;let n=Pi().filter(o=>o!==t);return iu(n),!0}function q$(t){let e=ct.find(o=>o.name===t);if(!e)return!1;e.enabled=!1;let n=Pi();return n.includes(t)||(n.push(t),iu(n)),!0}function F$(){return ct}async function U$(t,e={}){let{execSync:n}=require("child_process"),o=ru(),s=t;/^[\w-]+\/[\w.-]+$/.test(t)&&(s=`https://github.com/${t}.git`);let r=e.name||at.basename(s,".git").replace(/^nex-skill-/,""),i=at.join(o,r);if(Ce.existsSync(i))return{ok:!1,name:r,error:`Skill "${r}" is already installed at ${i}. Remove it first to reinstall.`};try{if(!/^https?:\/\/[a-zA-Z0-9._\-/:@#?=&%+~]+$/.test(s))throw new Error(`Invalid git URL: ${s}`);let d=i.replace(/'/g,"'\\''");n(`git clone --depth 1 '${s}' '${d}'`,{timeout:3e4,stdio:"pipe"})}catch(d){return{ok:!1,name:r,error:`Git clone failed: ${d.stderr?.toString().trim()||d.message}`}}let c=at.join(i,"skill.json"),l=Ce.existsSync(c),u=Ce.readdirSync(i).some(d=>(d.endsWith(".md")||d.endsWith(".js"))&&!d.startsWith("."));if(!l&&!u){try{Ce.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(Ce.readFileSync(c,"utf-8"));d.name||(d.name=r)}catch{try{Ce.rmSync(i,{recursive:!0,force:!0})}catch{}return{ok:!1,name:r,error:"Invalid skill.json \u2014 not valid JSON"}}return Ii(),{ok:!0,name:r}}async function W$(t){let e=require("axios");try{let n=encodeURIComponent(`nex-skill ${t} OR nex-code-skill ${t}`);return((await e.get(`https://api.github.com/search/repositories?q=${n}&sort=stars&per_page=10`,{timeout:1e4,headers:{Accept:"application/vnd.github.v3+json"}})).data.items||[]).map(s=>({name:s.name.replace(/^nex-skill-/,""),description:s.description||"(no description)",url:s.clone_url,stars:s.stargazers_count,owner:s.owner.login}))}catch(n){return[{name:"error",description:`Search failed: ${n.message}`,url:"",stars:0,owner:""}]}}function B$(t){let e=at.join(ks(),t);if(!Ce.existsSync(e))return{ok:!1,error:`Skill "${t}" not found in ${ks()}`};try{return Ce.rmSync(e,{recursive:!0,force:!0}),Ii(),{ok:!0}}catch(n){return{ok:!1,error:n.message}}}cu.exports={initSkillsDir:ru,loadAllSkills:Ii,getSkillInstructions:N$,getSkillCommands:M$,getSkillToolDefinitions:P$,routeSkillCall:I$,handleSkillCommand:L$,listSkills:D$,enableSkill:j$,disableSkill:q$,getLoadedSkills:F$,installSkill:U$,searchSkills:W$,removeSkill:B$,_getSkillsDir:ks,_validateScriptSkill:au,_loadMarkdownSkill:Ni,_loadScriptSkill:Mi}});var jo=G((Tv,mu)=>{var{spawn:H$}=require("child_process"),G$=require("path"),lu=require("fs"),Gt=new Map;function K$(){return G$.join(process.cwd(),".nex","config.json")}function Li(){let t=K$();if(!lu.existsSync(t))return{};try{return JSON.parse(lu.readFileSync(t,"utf-8")).mcpServers||{}}catch{return{}}}function Do(t,e,n={},o=1e4){return new Promise((s,r)=>{let i=`${Date.now()}-${Math.random().toString(36).slice(2,6)}`,c=JSON.stringify({jsonrpc:"2.0",id:i,method:e,params:n})+`
|
|
120
120
|
`,l="",u=setTimeout(()=>{f(),r(new Error(`MCP request timeout: ${e}`))},o);function d(m){l+=m.toString();let h=l.split(`
|
|
121
|
-
`);for(let p of h)if(p.trim())try{let g=JSON.parse(p);if(g.id===i){f(),g.error?r(new Error(`MCP error: ${g.error.message||JSON.stringify(g.error)}`)):s(g.result);return}}catch{}l=h[h.length-1]||""}function f(){clearTimeout(u),t.stdout.removeListener("data",d)}t.stdout.on("data",d);try{t.stdin.write(c)}catch(m){f(),r(new Error(`MCP write failed: ${m.message}`))}})}async function
|
|
122
|
-
`):JSON.stringify(s)}function
|
|
123
|
-
Available tools: ${d.join(", ")}`}}if(!n||!n.properties)return{valid:!0};let o=n.required||[],s=Object.keys(n.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=
|
|
121
|
+
`);for(let p of h)if(p.trim())try{let g=JSON.parse(p);if(g.id===i){f(),g.error?r(new Error(`MCP error: ${g.error.message||JSON.stringify(g.error)}`)):s(g.result);return}}catch{}l=h[h.length-1]||""}function f(){clearTimeout(u),t.stdout.removeListener("data",d)}t.stdout.on("data",d);try{t.stdin.write(c)}catch(m){f(),r(new Error(`MCP write failed: ${m.message}`))}})}async function uu(t,e){if(Gt.has(t))return Gt.get(t);let n=["PATH","HOME","USER","SHELL","LANG","TERM","NODE_ENV"],o={};for(let i of n)process.env[i]&&(o[i]=process.env[i]);let s=H$(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:{...o,...e.env||{}}}),r={name:t,proc:s,tools:[],config:e};try{await Do(s,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.2.0"}});let i=await Do(s,"tools/list",{});return r.tools=i&&i.tools||[],Gt.set(t,r),r}catch(i){throw s.kill(),new Error(`Failed to connect MCP server '${t}': ${i.message}`)}}function du(t){let e=Gt.get(t);if(!e)return!1;try{e.proc.kill()}catch{}return Gt.delete(t),!0}function Y$(){for(let[t]of Gt)du(t)}async function fu(t,e,n={}){let o=Gt.get(t);if(!o)throw new Error(`MCP server not connected: ${t}`);let s=await Do(o.proc,"tools/call",{name:e,arguments:n});return s&&Array.isArray(s.content)?s.content.filter(r=>r.type==="text").map(r=>r.text).join(`
|
|
122
|
+
`):JSON.stringify(s)}function pu(){let t=[];for(let[e,n]of Gt)for(let o of n.tools)t.push({server:e,name:o.name,description:o.description||"",inputSchema:o.inputSchema||{type:"object",properties:{}}});return t}function z$(){return pu().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function X$(t,e){if(!t.startsWith("mcp_"))return null;let n=t.substring(4).split("_");if(n.length<2)return null;let o=n[0],s=n.slice(1).join("_");return fu(o,s,e)}function J$(){let t=Li();return Object.entries(t).map(([e,n])=>{let o=Gt.get(e);return{name:e,command:n.command,connected:!!o,toolCount:o?o.tools.length:0}})}async function V$(){let t=Li(),e=[];for(let[n,o]of Object.entries(t))try{let s=await uu(n,o);e.push({name:n,tools:s.tools.length})}catch(s){e.push({name:n,tools:0,error:s.message})}return e}mu.exports={loadMCPConfig:Li,sendRequest:Do,connectServer:uu,disconnectServer:du,disconnectAll:Y$,callTool:fu,getAllTools:pu,getMCPToolDefinitions:z$,routeMCPCall:X$,listServers:J$,connectAll:V$}});var Fo=G((Rv,yu)=>{var hu=require("fs"),Di=require("path"),qo=[],vs=[],bn={},Ss=["onToolResult","onModelResponse","onSessionStart","onSessionEnd","onFileChange","beforeToolExec","afterToolExec"];function gu(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 n=t.function.name;return vs.some(o=>o.definition.function.name===n)?{ok:!1,error:`Tool "${n}" is already registered`}:(vs.push({definition:{type:"function",...t},handler:e}),{ok:!0})}function $u(t,e){return Ss.includes(t)?typeof e!="function"?{ok:!1,error:"Handler must be a function"}:(bn[t]||(bn[t]=[]),bn[t].push(e),{ok:!0}):{ok:!1,error:`Unknown event "${t}". Available: ${Ss.join(", ")}`}}async function ji(t,e){let n=bn[t]||[],o=e;for(let s of n)try{let r=await s(o);r!==void 0&&(o=r)}catch(r){process.env.NEX_DEBUG&&console.error(`[plugin] Hook error on ${t}: ${r.message}`)}return o}function Q$(){let t=Di.join(process.cwd(),".nex","plugins"),e=[];if(!hu.existsSync(t))return{loaded:0,errors:[]};let n=hu.readdirSync(t).filter(s=>s.endsWith(".js")),o={registerTool:gu,registerHook:$u,EVENTS:Ss};for(let s of n){let r=Di.join(t,s);try{let i=require(r);if(typeof i=="function")i(o);else if(typeof i.setup=="function")i.setup(o);else{e.push(`${s}: Plugin must export a function or { setup: function }`);continue}qo.push({name:i.name||Di.basename(s,".js"),filePath:r})}catch(i){e.push(`${s}: ${i.message}`)}}return{loaded:qo.length,errors:e}}function Z$(){return vs.map(t=>t.definition)}async function ey(t,e,n={}){let o=vs.find(c=>c.definition.function.name===t);if(!o)return null;let s=await ji("beforeToolExec",{name:t,args:e,options:n}),r=await o.handler(s.args||e,n);return(await ji("afterToolExec",{name:t,args:e,result:r})).result||r}function ty(){return[...qo]}function ny(){let t={};for(let e of Ss)t[e]=(bn[e]||[]).length;return t}function sy(){qo.length=0,vs.length=0;for(let t of Object.keys(bn))delete bn[t]}yu.exports={registerTool:gu,registerHook:$u,emit:ji,loadPlugins:Q$,getPluginToolDefinitions:Z$,executePluginTool:ey,getLoadedPlugins:ty,getHookCounts:ny,clearPlugins:sy,EVENTS:Ss}});var qi=G((Cv,xu)=>{var{getSkillToolDefinitions:oy}=sn(),{getMCPToolDefinitions:ry}=jo(),{getPluginToolDefinitions:iy}=Fo(),Uo=new Map;function wu(){let{TOOL_DEFINITIONS:t}=Tt();return[...t,...oy(),...ry(),...iy()]}function bu(t){if(Uo.has(t))return Uo.get(t);let n=wu().find(s=>s.function.name===t);if(!n)return null;let o=n.function.parameters;return Uo.set(t,o),o}function ay(){Uo.clear()}function Wo(t,e){if(!t||e.length===0)return null;let n=null,o=1/0;for(let s of e){let r=_u(t.toLowerCase(),s.toLowerCase());r<o&&(o=r,n=s)}return o<=Math.ceil(t.length/2)?n:null}function _u(t,e){let n=t.length,o=e.length,s=Array.from({length:n+1},()=>Array(o+1).fill(0));for(let r=0;r<=n;r++)s[r][0]=r;for(let r=0;r<=o;r++)s[0][r]=r;for(let r=1;r<=n;r++)for(let i=1;i<=o;i++)s[r][i]=t[r-1]===e[i-1]?s[r-1][i-1]:1+Math.min(s[r-1][i],s[r][i-1],s[r-1][i-1]);return s[n][o]}function cy(t,e){let n=bu(t);if(n===null){let d=wu().map(m=>m.function.name),f=Wo(t,d);return{valid:!1,error:`Unknown tool "${t}".${f?` Did you mean "${f}"?`:""}
|
|
123
|
+
Available tools: ${d.join(", ")}`}}if(!n||!n.properties)return{valid:!0};let o=n.required||[],s=Object.keys(n.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=Wo(u,r);d&&!s.includes(d)?(c[u]=e[d],delete c[d],l=!0):i.push(`Missing required parameter "${u}" (${n.properties[u]?.description||n.properties[u]?.type||"unknown"})`)}for(let u of r)if(!s.includes(u)){let d=Wo(u,s);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(!n.properties[u])continue;let d=n.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:
|
|
124
124
|
`+i.map(u=>` - ${u}`).join(`
|
|
125
125
|
`)+`
|
|
126
126
|
|
|
127
|
-
Expected parameters: ${JSON.stringify(n.properties,null,2)}`}:{valid:!0,corrected:l?c:null}}function
|
|
127
|
+
Expected parameters: ${JSON.stringify(n.properties,null,2)}`}:{valid:!0,corrected:l?c:null}}function ly(t,e){let n=[],o={...t};if(!o.function&&!o.name)return n.push('Tool call missing both "function" and "name" fields'),{valid:!1,normalized:o,errors:n};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 s=o.function.arguments;if(s.trim()==="")o.function.arguments={};else try{o.function.arguments=JSON.parse(s)}catch(r){return n.push(`Invalid JSON in arguments${e?` (${e})`:""}: ${r.message}`),{valid:!1,normalized:o,errors:n}}}return o.function&&typeof o.function.arguments!="object"?(n.push(`Arguments must be an object, got ${typeof o.function.arguments}`),{valid:!1,normalized:o,errors:n}):!o.function.name||typeof o.function.name!="string"?(n.push("Tool call function name must be a non-empty string"),{valid:!1,normalized:o,errors:n}):{valid:n.length===0,normalized:o,errors:n}}xu.exports={validateToolArgs:cy,validateToolCallFormat:ly,closestMatch:Wo,levenshtein:_u,getCachedSchema:bu,clearSchemaCache:ay}});var Eu=G((Av,Su)=>{var{levenshtein:Bo}=qi(),uy=200,dy=.3,fy=2;function Fi(t){return t.replace(/\r\n/g,`
|
|
128
128
|
`).replace(/\r/g,`
|
|
129
|
-
`).replace(/\t/g," ".repeat(
|
|
129
|
+
`).replace(/\t/g," ".repeat(fy)).split(`
|
|
130
130
|
`).map(e=>{let n=e.replace(/\s+$/,""),o=n.match(/^(\s*)(.*)/);if(!o)return n;let[,s,r]=o;return s+r.replace(/ {2,}/g," ")}).join(`
|
|
131
|
-
`)}function
|
|
131
|
+
`)}function py(t,e){if(t.includes(e))return e;if(e.length<10)return null;let n=Fi(t),o=Fi(e);if(!n.includes(o))return null;let s=t.split(`
|
|
132
132
|
`),r=n.split(`
|
|
133
133
|
`),i=o.split(`
|
|
134
134
|
`),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 s.slice(u,u+i.length).join(`
|
|
135
|
-
`)}if(i.length===1){for(let u=0;u<r.length;u++)if(r[u].indexOf(o)!==-1)return s[u]}return null}function
|
|
135
|
+
`)}if(i.length===1){for(let u=0;u<r.length;u++)if(r[u].indexOf(o)!==-1)return s[u]}return null}function my(t,e){if(!t||!e)return null;let n=t.split(`
|
|
136
136
|
`),s=e.split(`
|
|
137
|
-
`).length;return n.length===0||s===0?null:s===1?
|
|
138
|
-
`),u=
|
|
139
|
-
`),h=
|
|
140
|
-
`),o=[],s=t?`.${t.split(".").pop()}`:"";for(let r=0;r<n.length;r++){let i=n[r],c=r+1;for(let l of
|
|
141
|
-
`).filter(Boolean),
|
|
142
|
-
`);for(let s=0;s<o.length;s++){let r=o[s],i=s+1;if([".js",".ts",".jsx",".tsx",".mjs",".cjs"].includes(e)){let c=r.match(/(?:export\s+)?(?:async\s+)?function\s+(\w+)/);c&&n.push({type:"function",name:c[1],line:i});let l=r.match(/(?:export\s+)?class\s+(\w+)/);l&&n.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&&n.push({type:"function",name:u[1],line:i});let d=r.match(/module\.exports\s*=\s*\{([^}]+)\}/);if(d){let m=d[1].split(",").map(h=>h.trim().split(":")[0].trim()).filter(Boolean);for(let h of m)/^\w+$/.test(h)&&n.push({type:"export",name:h,line:i})}let f=r.match(/(?:require\(['"]([^'"]+)['"]\)|from\s+['"]([^'"]+)['"])/);if(f){let m=f[1]||f[2];n.push({type:"import",name:m,line:i})}}if(e===".py"){let c=r.match(/^(?:async\s+)?def\s+(\w+)/);c&&n.push({type:"function",name:c[1],line:i});let l=r.match(/^class\s+(\w+)/);l&&n.push({type:"class",name:l[1],line:i});let u=r.match(/^(?:from\s+(\S+)\s+)?import\s+(\S+)/);u&&n.push({type:"import",name:u[1]||u[2],line:i})}if(e===".go"){let c=r.match(/^func\s+(?:\([^)]+\)\s+)?(\w+)/);c&&n.push({type:"function",name:c[1],line:i});let l=r.match(/^type\s+(\w+)\s+struct/);l&&n.push({type:"class",name:l[1],line:i})}}return n}async function
|
|
137
|
+
`).length;return n.length===0||s===0?null:s===1?hy(n,e):$y(n,e,s)}function ku(t){return Math.max(1,Math.floor(t/uy))}function vu(t,e){return t<=Math.ceil(e*dy)}function hy(t,e){let n=e.trim(),o=ku(t.length),s=null,r=1/0;for(let i=0;i<t.length;i+=o){let c=t[i];if(!c.trim())continue;let l=Bo(c.trim(),n);l<r&&(r=l,s={text:c,distance:l,line:i+1})}return s&&o>1&&(s=gy(t,n,s,o)||s,r=s.distance),vu(r,e.length)?s:null}function gy(t,e,n,o){let s=n.line-1,r=Math.max(0,s-o),i=Math.min(t.length-1,s+o),c=n.distance,l=null;for(let u=r;u<=i;u++){let d=t[u];if(!d.trim())continue;let f=Bo(d.trim(),e);f<c&&(c=f,l={text:d,distance:f,line:u+1})}return l}function $y(t,e,n){let o=t.length-n+1;if(o<=0)return null;let s=ku(o),r=null,i=1/0;for(let c=0;c<o;c+=s){let l=t.slice(c,c+n).join(`
|
|
138
|
+
`),u=Bo(l,e);u<i&&(i=u,r={text:l,distance:u,line:c+1})}return r&&s>1&&(r=yy(t,e,r,s,n,o)||r,i=r.distance),vu(i,e.length)?r:null}function yy(t,e,n,o,s,r){let i=n.line-1,c=Math.max(0,i-o),l=Math.min(r-1,i+o),u=n.distance,d=null;for(let f=c;f<=l;f++){let m=t.slice(f,f+s).join(`
|
|
139
|
+
`),h=Bo(m,e);h<u&&(u=h,d={text:m,distance:h,line:f+1})}return d}Su.exports={normalizeWhitespace:Fi,fuzzyFindText:py,findMostSimilar:my}});var Ru=G((Nv,Tu)=>{var{C:Ov}=Me(),wy=[{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}],by=[{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 _y(t,e){let n=e.split(`
|
|
140
|
+
`),o=[],s=t?`.${t.split(".").pop()}`:"";for(let r=0;r<n.length;r++){let i=n[r],c=r+1;for(let l of wy)l.regex.test(i)&&o.push({line:c,message:`Potential secret detected: ${l.name}`,severity:"error"});for(let l of by)l.ext&&!l.ext.includes(s)||l.regex.test(i)&&o.push({line:c,message:l.message||`Found ${l.name}`,severity:l.severity||"warn"})}return n.length>500&&o.push({line:0,message:`Large file detected (${n.length} lines). Consider refactoring.`,severity:"info"}),o}function xy(){let t=process.memoryUsage();return{rss:Math.round(t.rss/1024/1024*100)/100,heapUsed:Math.round(t.heapUsed/1024/1024*100)/100}}Tu.exports={runDiagnostics:_y,getMemoryUsage:xy}});var Gi=G((Mv,Pu)=>{var Yn=require("fs").promises,zn=require("path"),{exec:ky}=require("util").promisify(require("child_process").exec),Xn=[],Hi=null,Ho=!1,Wi=0,vy=6e4;function Au(t){return!(Xn.length===0||Hi!==t||Date.now()-Wi>vy)}async function Ou(t){if(!Ho&&!Au(t)){Ho=!0,Hi=t;try{try{let{stdout:o}=await ky("rg --files",{cwd:t,timeout:5e3});Xn=o.split(`
|
|
141
|
+
`).filter(Boolean),Wi=Date.now(),Ho=!1;return}catch{}let e=[],n=async(o,s)=>{let r;try{r=await Yn.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=s?`${s}/${i.name}`:i.name;i.isDirectory()?await n(zn.join(o,i.name),c):e.push(c)}};await n(t,""),Xn=e,Wi=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{Ho=!1}}}function Bi(){return Xn}function Sy(){return Hi}function Ey(t){return Xn.filter(e=>zn.basename(e)===t)}function Ty(t){let e=t.toLowerCase();return Xn.filter(n=>n.toLowerCase().includes(e)).slice(0,20)}var Ui=null,Cu=0,Ry=12e4,Cy=new Set([".js",".ts",".jsx",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".rb"]);function Nu(t,e){let n=[],o=t.split(`
|
|
142
|
+
`);for(let s=0;s<o.length;s++){let r=o[s],i=s+1;if([".js",".ts",".jsx",".tsx",".mjs",".cjs"].includes(e)){let c=r.match(/(?:export\s+)?(?:async\s+)?function\s+(\w+)/);c&&n.push({type:"function",name:c[1],line:i});let l=r.match(/(?:export\s+)?class\s+(\w+)/);l&&n.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&&n.push({type:"function",name:u[1],line:i});let d=r.match(/module\.exports\s*=\s*\{([^}]+)\}/);if(d){let m=d[1].split(",").map(h=>h.trim().split(":")[0].trim()).filter(Boolean);for(let h of m)/^\w+$/.test(h)&&n.push({type:"export",name:h,line:i})}let f=r.match(/(?:require\(['"]([^'"]+)['"]\)|from\s+['"]([^'"]+)['"])/);if(f){let m=f[1]||f[2];n.push({type:"import",name:m,line:i})}}if(e===".py"){let c=r.match(/^(?:async\s+)?def\s+(\w+)/);c&&n.push({type:"function",name:c[1],line:i});let l=r.match(/^class\s+(\w+)/);l&&n.push({type:"class",name:l[1],line:i});let u=r.match(/^(?:from\s+(\S+)\s+)?import\s+(\S+)/);u&&n.push({type:"import",name:u[1]||u[2],line:i})}if(e===".go"){let c=r.match(/^func\s+(?:\([^)]+\)\s+)?(\w+)/);c&&n.push({type:"function",name:c[1],line:i});let l=r.match(/^type\s+(\w+)\s+struct/);l&&n.push({type:"class",name:l[1],line:i})}}return n}async function Mu(t){t=t||process.cwd();let e=zn.join(t,".nex","index","content-index.json"),n={};if(Ui&&Date.now()-Cu<Ry)return Ui;try{let i=await Yn.readFile(e,"utf-8");n=JSON.parse(i)}catch{n={files:{}}}Bi().length===0&&await Ou(t);let s={files:{}},r=!1;for(let i of Bi()){let c=zn.extname(i);if(!Cy.has(c))continue;let l=zn.join(t,i);try{let d=(await Yn.stat(l)).mtimeMs;if(n.files[i]&&n.files[i].mtime===d){s.files[i]=n.files[i];continue}let f=await Yn.readFile(l,"utf-8"),m=Nu(f,c);s.files[i]={defs:m,mtime:d},r=!0}catch{}}if(r){let i=zn.join(t,".nex","index");await Yn.mkdir(i,{recursive:!0}),await Yn.writeFile(e,JSON.stringify(s),"utf-8")}return Ui=s,Cu=Date.now(),s}async function Ay(t,e){let n=await Mu(),o=[],s=t.toLowerCase();for(let[r,i]of Object.entries(n.files))for(let c of i.defs)e&&c.type!==e||c.name.toLowerCase().includes(s)&&o.push({file:r,type:c.type,name:c.name,line:c.line});return o.sort((r,i)=>{let c=r.name.toLowerCase()===s?0:1,l=i.name.toLowerCase()===s?0:1;if(c!==l)return c-l;let u=r.name.toLowerCase().startsWith(s)?0:1,d=i.name.toLowerCase().startsWith(s)?0:1;return u-d}),o.slice(0,50)}Pu.exports={refreshIndex:Ou,getFileIndex:Bi,getIndexedCwd:Sy,findFileInIndex:Ey,searchIndex:Ty,isIndexValid:Au,buildContentIndex:Mu,searchContentIndex:Ay,extractDefinitions:Nu}});var Jn=G((Pv,ju)=>{var Go=require("fs"),Yo=require("path"),zo=require("os"),{execFile:Oy}=require("child_process"),{promisify:Ny}=require("util"),Ki=Ny(Oy),My=Yo.join(zo.homedir(),".nex","servers.json"),Ko=Yo.join(zo.tmpdir(),"nex-ssh-sockets");function Py(){return Yo.join(process.cwd(),".nex","servers.json")}function Iu(){let t=o=>{if(!Go.existsSync(o))return{};try{return JSON.parse(Go.readFileSync(o,"utf-8"))}catch{return{}}},e=t(My),n=t(Py());return{...e,...n}}function Iy(t){let e=Iu();if(e[t])return{...e[t],_name:t};if(/^[\w.-]+@[\w.-]+$/.test(t)||/[\w-]+\.[\w.-]+/.test(t)||t==="localhost"){let[s,r]=t.includes("@")?t.split("@"):[void 0,t];return{host:r,user:s}}let n=Object.keys(e),o=n.length?`Available profiles: ${n.join(", ")}`:"No profiles configured. Create .nex/servers.json (project) or ~/.nex/servers.json (global)";throw new Error(`Unknown server: "${t}". ${o}`)}function Ly(){Go.existsSync(Ko)||Go.mkdirSync(Ko,{recursive:!0})}function Lu(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-o","ServerAliveInterval=30"];t.key&&e.push("-i",t.key.replace(/^~/,zo.homedir())),t.port&&Number(t.port)!==22&&e.push("-p",String(t.port)),Ly();let n=t.user?`${t.user}@${t.host}`:t.host,o=Yo.join(Ko,n.replace(/[@.:]/g,"_"));return e.push("-o","ControlMaster=auto","-o",`ControlPath=${o}`,"-o","ControlPersist=120"),e.push(n),{args:e,target:n}}function Du(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-r"];return t.key&&e.push("-i",t.key.replace(/^~/,zo.homedir())),t.port&&Number(t.port)!==22&&e.push("-P",String(t.port)),e}async function Dy(t,e,{timeout:n=3e4,sudo:o=!1}={}){let{args:s}=Lu(t),r=o&&t.sudo?`sudo sh -c ${JSON.stringify(e)}`:e;try{let{stdout:i,stderr:c}=await Ki("ssh",[...s,r],{timeout:n,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:Xo(l,t)}}}async function jy(t,e,n,{timeout:o=12e4}={}){let s=Du(t),r=t.user?`${t.user}@${t.host}`:t.host;s.push(e,`${r}:${n}`);try{let{stdout:i,stderr:c}=await Ki("scp",s,{timeout:o,maxBuffer:1048576});return i||c||`Uploaded ${e} \u2192 ${r}:${n}`}catch(i){let c=(i.stderr||i.message||"").toString();throw new Error(Xo(c,t)||c)}}async function qy(t,e,n,{timeout:o=12e4}={}){let s=Du(t),r=t.user?`${t.user}@${t.host}`:t.host;s.push(`${r}:${e}`,n);try{let{stdout:i,stderr:c}=await Ki("scp",s,{timeout:o,maxBuffer:1048576});return i||c||`Downloaded ${r}:${e} \u2192 ${n}`}catch(i){let c=(i.stderr||i.message||"").toString();throw new Error(Xo(c,t)||c)}}function Xo(t,e){if(!t)return"";if(/connection refused/i.test(t)){let n=e.port||22;return`${t}
|
|
143
143
|
HINT: Connection refused on ${e.host}:${n}. Check: server is running, SSH service is active (systemctl status sshd), firewall allows port ${n} (firewall-cmd --list-ports).`}if(/permission denied/i.test(t)){let n=e.key?`key: ${e.key}`:"SSH agent";return`${t}
|
|
144
144
|
HINT: Auth failed using ${n} 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}
|
|
145
145
|
HINT: Cannot reach ${e.host}. Check: network connection, correct hostname/IP, DNS resolution.`:/host key verification failed/i.test(t)?`${t}
|
|
146
146
|
HINT: Host key changed for ${e.host}. To reset: ssh-keygen -R ${e.host}`:/timed out/i.test(t)?`${t}
|
|
147
147
|
HINT: Connection timed out to ${e.host}. Check firewall rules and network connectivity.`:/too many authentication failures/i.test(t)?`${t}
|
|
148
|
-
HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function
|
|
149
|
-
`,"utf-8")}
|
|
148
|
+
HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function Fy(t,e){let n=e.user?`${e.user}@${e.host}`:e.host,o=e.port&&Number(e.port)!==22?`:${e.port}`:"",s=e.os?` [${e.os}]`:"",r=e.key?` key:${e.key}`:"",i=e.sudo?" sudo:yes":"";return`${t}: ${n}${o}${s}${r}${i}`}ju.exports={loadServerProfiles:Iu,resolveProfile:Iy,buildSSHArgs:Lu,sshExec:Dy,scpUpload:jy,scpDownload:qy,enrichSSHError:Xo,formatProfile:Fy,SSH_SOCKET_DIR:Ko}});var Xi=G((Iv,Fu)=>{var Es=require("fs"),Yi=require("path"),Uy=Yi.join(".nex","deploy.json");function zi(){return Yi.join(process.cwd(),Uy)}function qu(){let t=zi();if(!Es.existsSync(t))return{};try{return JSON.parse(Es.readFileSync(t,"utf-8"))}catch{return{}}}function Wy(t){let e=qu();if(e[t])return{...e[t],_name:t};let n=Object.keys(e),o=n.length?`Available: ${n.join(", ")}`:"No deploy configs found. Create .nex/deploy.json or use explicit params.";throw new Error(`Unknown deploy config: "${t}". ${o}`)}function By(t){let e=Yi.join(process.cwd(),".nex");Es.existsSync(e)||Es.mkdirSync(e,{recursive:!0}),Es.writeFileSync(zi(),JSON.stringify(t,null,2)+`
|
|
149
|
+
`,"utf-8")}Fu.exports={loadDeployConfigs:qu,resolveDeployConfig:Wy,saveDeployConfigs:By,getDeployConfigPath:zi}});var Jo=G((Lv,Bu)=>{var{getActiveModel:Hy,getActiveProviderName:Gy}=Re(),Ts={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},Rs={"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"},Cs={ollama:"full",openai:"full",anthropic:"full",gemini:"full",local:"essential"},Dt={};function Wu(){try{let t=require("fs"),n=require("path").join(process.cwd(),".nex","config.json");t.existsSync(n)&&(Dt=JSON.parse(t.readFileSync(n,"utf-8")).toolTiers||{})}catch{Dt={}}}Wu();function Ji(){let e=Hy()?.id,n=Gy();return e&&Dt[e]?Dt[e]:n&&Dt[`${n}:*`]?Dt[`${n}:*`]:e&&Rs[e]?Rs[e]:n&&Cs[n]?Cs[n]:"full"}var Ky=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"]),Uu={anthropic:"strict",openai:"strict",gemini:"strict",ollama:"fuzzy",local:"fuzzy"};function Yy(t,e){return t&&(Ky.has(t)||t.startsWith("claude-"))?"strict":e&&Uu[e]?Uu[e]:"fuzzy"}function zy(t,e){return t&&Dt[t]?Dt[t]:e&&Dt[`${e}:*`]?Dt[`${e}:*`]:t&&Rs[t]?Rs[t]:e&&Cs[e]?Cs[e]:"full"}function Xy(t,e){let n=e||Ji();if(n==="full"||!Ts[n])return t;let o=new Set(Ts[n]);return t.filter(s=>o.has(s.function.name))}function Jy(){let t=Ji(),e=Ts[t]?Ts[t].length:"all";return{tier:t,toolCount:e}}Bu.exports={filterToolsForModel:Xy,getActiveTier:Ji,getModelTier:zy,getEditMode:Yy,getTierInfo:Jy,TIERS:Ts,MODEL_TIERS:Rs,PROVIDER_DEFAULT_TIER:Cs,loadConfigOverrides:Wu}});var Os=G((Dv,Ku)=>{var Vi=null,Kt=null,As=null,Hu=`Playwright is not installed. Install with:
|
|
150
150
|
npm install playwright && npx playwright install chromium
|
|
151
|
-
Then restart nex-code.`;function
|
|
152
|
-
...(truncated)`:""),links:c.slice(0,20)}}finally{await s.close()}}async function
|
|
153
|
-
`)}function
|
|
151
|
+
Then restart nex-code.`;function Gu(){if(As!==null)return As;try{require("playwright"),As=!0}catch{As=!1}return As}async function Vo(){if(!Gu())throw new Error(Hu);return Vi||(Vi=require("playwright")),(!Kt||!Kt.isConnected())&&(Kt=await Vi.chromium.launch({headless:!0})),Kt}async function Vy(){if(Kt){try{await Kt.close()}catch{}Kt=null}}process.on("exit",()=>{if(Kt)try{Kt.close()}catch{}});async function Qy(t,{timeout:e=3e4,waitFor:n="domcontentloaded"}={}){let s=await(await Vo()).newPage();try{await s.goto(t,{waitUntil:n,timeout:e});let r=await s.title(),i=await s.evaluate(()=>(document.querySelectorAll("script,style,nav,footer,header,aside,[role=navigation]").forEach(u=>u.remove()),document.body?.innerText||"")),c=await s.evaluate(()=>Array.from(document.querySelectorAll("a[href]")).slice(0,30).map(l=>({text:(l.innerText||l.textContent||"").trim().substring(0,80),href:l.href})).filter(l=>l.text&&l.href&&!l.href.startsWith("javascript:")));return{title:r,url:s.url(),text:i.substring(0,8e3)+(i.length>8e3?`
|
|
152
|
+
...(truncated)`:""),links:c.slice(0,20)}}finally{await s.close()}}async function Zy(t,{width:e=1280,height:n=800,fullPage:o=!1,timeout:s=3e4}={}){let i=await(await Vo()).newPage();try{await i.setViewportSize({width:e,height:n}),await i.goto(t,{waitUntil:"networkidle",timeout:s});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 ew(t,{selector:e,text:n,timeout:o=3e4}={}){if(!e&&!n)throw new Error("selector or text is required");let r=await(await Vo()).newPage();try{await r.goto(t,{waitUntil:"domcontentloaded",timeout:o}),n?await r.getByText(n,{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 tw(t,{selector:e,value:n,submit:o=!1,timeout:s=3e4}={}){if(!e||n===void 0)throw new Error("selector and value are required");let i=await(await Vo()).newPage();try{return await i.goto(t,{waitUntil:"domcontentloaded",timeout:s}),await i.fill(e,String(n)),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()}}Ku.exports={isPlaywrightAvailable:Gu,browserNavigate:Qy,browserScreenshot:Zy,browserClick:ew,browserFill:tw,closeBrowser:Vy,INSTALL_MSG:Hu}});var Qo=G((jv,Yu)=>{var{C:Ae}=Me(),Ms="",et=[],Ns=0,_n=null;function nw(t){_n=t}function sw(t,e){Ms=t,et=[],Ns=0;for(let o of e){Ns++;let s=`t${Ns}`;et.push({id:s,description:o.description||o.title||o.name||o.task||`Task ${Ns}`,status:"pending",dependsOn:o.depends_on||[],result:null})}let n=et.map(o=>({...o}));return _n&&_n("create",{name:t,tasks:n}),n}function ow(t,e,n){let o=et.find(s=>s.id===t);return o?(o.status=e,n!==void 0&&(o.result=n),_n&&_n("update",{id:t,status:e,result:n}),{...o}):null}function rw(){return{name:Ms,tasks:et.map(t=>({...t}))}}function iw(){Ms="",et=[],Ns=0,_n&&_n("clear",{})}function aw(){return et.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let n=et.find(o=>o.id===e);return n&&n.status==="done"}))}function cw(){if(et.length===0)return`${Ae.dim}No active tasks${Ae.reset}`;let t=[];Ms&&(t.push(` ${Ae.bold}${Ae.cyan}Tasks: ${Ms}${Ae.reset}`),t.push(` ${Ae.dim}${"\u2500".repeat(40)}${Ae.reset}`));for(let s of et){let r,i;switch(s.status){case"done":r="\u2713",i=Ae.green;break;case"in_progress":r="\u2192",i=Ae.cyan;break;case"failed":r="\u2717",i=Ae.red;break;default:r="\xB7",i=Ae.dim}let c=s.dependsOn.length>0?` ${Ae.dim}(after: ${s.dependsOn.join(", ")})${Ae.reset}`:"",l=`[${s.status}]`,u=s.description.length>50?s.description.substring(0,47)+"...":s.description;if(t.push(` ${i}${r}${Ae.reset} ${Ae.bold}${s.id}${Ae.reset} ${u.padEnd(40)} ${i}${l}${Ae.reset}${c}`),s.result&&s.status==="done"){let d=s.result.length>60?s.result.substring(0,57)+"...":s.result;t.push(` ${Ae.dim}\u2192 ${d}${Ae.reset}`)}}let e=et.filter(s=>s.status==="done").length,n=et.filter(s=>s.status==="failed").length,o=et.length;return t.push(` ${Ae.dim}${"\u2500".repeat(40)}${Ae.reset}`),t.push(` ${Ae.dim}${e}/${o} done${n>0?`, ${n} failed`:""}${Ae.reset}`),t.join(`
|
|
153
|
+
`)}function lw(){return et.length>0&&et.some(t=>t.status==="pending"||t.status==="in_progress")}Yu.exports={createTasks:sw,updateTask:ow,getTaskList:rw,clearTasks:iw,getReadyTasks:aw,renderTaskList:cw,setOnChange:nw,hasActiveTasks:lw}});var nr=G((Fv,pd)=>{var{callStream:uw,getActiveProviderName:er,getActiveModelId:dw,getConfiguredProviders:fw,getProvider:zu,getActiveProvider:Xu,parseModelSpec:Ju}=Re(),{parseToolArgs:Vu}=Gn(),{filterToolsForModel:pw,getModelTier:Zo}=Jo(),{trackUsage:Qu,estimateTokens:Zu}=Hn(),{MultiProgress:mw,C:qv}=Me();function ed(t){return!t||typeof t!="string"?0:typeof Zu=="function"?Zu(t):Math.ceil(t.length/4)}var sd=15,hw=5,td=3,od=8,gw=2,tr=new Map,rd=600*1e3;function $w(t,e){let n=tr.get(t);return n&&n.agentId!==e&&Date.now()-n.timestamp<rd?!1:(tr.set(t,{agentId:e,timestamp:Date.now()}),!0)}function Ps(t){tr.delete(t)}function Qi(){tr.clear()}function Zi(t){let e=(t.message||"").toLowerCase(),n=t.code||"";return e.includes("429")||e.includes("rate limit")?"rate_limit":e.includes("401")||e.includes("403")||e.includes("unauthorized")||e.includes("forbidden")?"auth":e.includes("context")&&(e.includes("too long")||e.includes("overflow")||e.includes("maximum"))||e.includes("400")&&(e.includes("content")||e.includes("length"))?"context_overflow":e.includes("500")||e.includes("502")||e.includes("503")||e.includes("504")?"server":n==="ECONNRESET"||n==="ECONNABORTED"||n==="ETIMEDOUT"||n==="ECONNREFUSED"||n==="ENOTFOUND"||e.includes("socket disconnected")||e.includes("tls")||e.includes("econnreset")||e.includes("fetch failed")||e.includes("etimedout")||e.includes("enotfound")?"network":"unknown"}function id(t){let e=Zi(t);return e==="rate_limit"||e==="server"||e==="network"}async function ad(t,e,n){let o;for(let s=0;s<=td;s++)try{return await uw(t,e,n)}catch(r){o=r;let i=Zi(r);if(i==="auth")throw r.message=`Authentication failed \u2014 check your API key or permissions. (${r.message})`,r;if(i==="context_overflow")throw r.message=`Context window exceeded \u2014 reduce message history or use a model with a larger context. (${r.message})`,r;if(s<td&&id(r)){let l=i==="rate_limit"?Math.min(2e3*Math.pow(2,s),15e3):Math.min(500*Math.pow(2,s),4e3);await new Promise(u=>setTimeout(u,l).unref());continue}throw r}throw o}var nd=new Set(["ask_user","task_list"]);function cd(t){return t>=2?new Set([...nd,"spawn_agents"]):nd}var yw=new Set(["write_file","edit_file","patch_file"]),ww=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,bw=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function ld(t){return bw.test(t)?"full":ww.test(t)?"essential":t.length>300?"full":"standard"}function ud(t){let e=fw(),n=er(),o=[...e].sort((s,r)=>(s.name===n?-1:1)-(r.name===n?-1:1));for(let s of o)for(let r of s.models)if(Zo(r.id,s.name)===t)return{provider:s.name,model:r.id};return null}var _w={essential:process.env.NEX_FAST_MODEL||null,standard:process.env.NEX_STANDARD_MODEL||null,full:process.env.NEX_HEAVY_MODEL||null};function ea(t){if(t.model){let{provider:s,model:r}=Ju(t.model),i=s?zu(s):Xu(),c=s||er();if(i&&i.isConfigured()&&(i.getModel(r)||c==="local")){let l=Zo(r,c);return{provider:c,model:r,tier:l}}}let e=ld(t.task),n=_w[e];if(n){let{provider:s,model:r}=Ju(n),i=s?zu(s):Xu(),c=s||er();if(i&&i.isConfigured()&&(i.getModel(r)||c==="local")){let l=Zo(r,c);return{provider:c,model:r,tier:l}}}let o=ud(e);if(o){let s=Zo(o.model,o.provider);return{provider:o.provider,model:o.model,tier:s}}return{provider:null,model:null,tier:null}}async function dd(t,e={},n=0){let o=n===0?sd:od,s=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:t._systemPrompt||`You are a focused sub-agent. Complete this specific task efficiently.
|
|
154
154
|
|
|
155
155
|
TASK: ${t.task}
|
|
156
156
|
${t.context?`
|
|
@@ -172,40 +172,40 @@ TOOL STRATEGY:
|
|
|
172
172
|
ERROR RECOVERY:
|
|
173
173
|
- If edit_file fails with "old_text not found": read the file again, compare, and retry with exact text.
|
|
174
174
|
- If bash fails: read the error, fix the root cause, then retry.
|
|
175
|
-
- After 2 failed attempts at the same operation, summarize the issue and stop.`}];f.push({role:"user",content:t.task});let m=
|
|
176
|
-
`)}let
|
|
177
|
-
...(truncated)`:
|
|
178
|
-
`)}catch(d){return u.stop(),
|
|
179
|
-
`);for(let r of s){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}n=o[2]}return{frontmatter:e,body:n}}function
|
|
180
|
-
`);for(let i of r)if(i.startsWith("#")){let c=i.replace(/^#+\s*/,"");for(let l of
|
|
181
|
-
...(truncated)`}let
|
|
182
|
-
${
|
|
183
|
-
|
|
184
|
-
${
|
|
185
|
-
|
|
186
|
-
`)}
|
|
187
|
-
`;
|
|
188
|
-
`).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
|
|
175
|
+
- After 2 failed attempts at the same operation, summarize the issue and stop.`}];f.push({role:"user",content:t.task});let m=ea(t),h=m.provider,p=m.model,g=m.tier,{TOOL_DEFINITIONS:y,executeTool:w}=Tt(),x=cd(n),R=pw(y.filter(_=>!x.has(_.function.name)),g);if(p&&!t._skipLog){let _=g?` (${g})`:"";process.stderr.write(` [sub-agent: ${h}:${p}${_}]
|
|
176
|
+
`)}let k={};h&&(k.provider=h),p&&(k.model=p);try{for(let b=0;b<s;b++){let A=await ad(f,R,k);if(!A||typeof A!="object")throw new Error("Empty or invalid response from provider");{let ce=h||er(),ue=p||dw();if(A.usage){let Z=A.usage.prompt_tokens||0,de=A.usage.completion_tokens||0;c.input+=Z,c.output+=de,Qu(ce,ue,Z,de)}else{let Z=A.content||"",de=f.map(P=>typeof P.content=="string"?P.content:Array.isArray(P.content)?P.content.map(F=>typeof F=="string"?F:F.text||"").join(""):"").join(" "),X=ed(de),E=ed(Z);c.input+=X,c.output+=E,c._estimated=!0,Qu(ce,ue,X,E)}}let M=A.content||"",O=A.tool_calls,N={role:"assistant",content:M||""};if(O&&O.length>0&&(N.tool_calls=O),f.push(N),!O||O.length===0){for(let ce of l)Ps(ce);return{task:t.task,status:"done",result:M||"(no response)",toolsUsed:i,tokensUsed:c,modelSpec:h&&p?`${h}:${p}`:null}}let he=O.map(ce=>{let ue=ce.function.name,Z=Vu(ce.function.arguments),de=ce.id||`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!Z)return Promise.resolve({role:"tool",content:`ERROR: Malformed tool arguments for ${ue}`,tool_call_id:de});let X=null;if(yw.has(ue)&&Z.path){let P=require("path"),F=P.isAbsolute(Z.path)?Z.path:P.resolve(process.cwd(),Z.path);if(l.has(F)||!$w(F,r))return Promise.resolve({role:"tool",content:`ERROR: File '${Z.path}' is locked by another operation. Try a different approach or skip this file.`,tool_call_id:de});l.add(F),X=F}return i.push(ue),e.onUpdate&&e.onUpdate({type:"tool_call",tool:ue,agentId:r}),(ue==="spawn_agents"?fd(Z,n+1):w(ue,Z,{autoConfirm:!0,silent:!0})).then(P=>{X&&(Ps(X),l.delete(X));let F=String(P??"");return{role:"tool",content:F.length>2e4?F.substring(0,2e4)+`
|
|
177
|
+
...(truncated)`:F,tool_call_id:de}}).catch(P=>(X&&(Ps(X),l.delete(X)),{role:"tool",content:`ERROR: ${P.message}`,tool_call_id:de}))}),ge=await Promise.all(he);if(f.push(...ge),b>=7&&f.length>12)try{let{compressMessage:ce}=Ve(),ue=f.length-6;for(let Z=1;Z<ue;Z++)f[Z]._subAgentCompressed||(f[Z]={...ce(f[Z],"light"),_subAgentCompressed:!0})}catch{}for(let ce=0;ce<O.length;ce++){let ue=O[ce];if(ue.function.name==="bash_exec"){let Z=Vu(ue.function.arguments);if((ge[ce]?.content||"").startsWith("ERROR")&&Z&&Z.command){let X=Z.command.replace(/\s+/g," ").trim().slice(0,100);u.set(X,(u.get(X)||0)+1)}}}e.onUpdate&&e.onUpdate(`step ${b+1}/${s}`)}for(let b of l)Ps(b);let _=[...u.entries()].filter(([,b])=>b>=3).sort((b,A)=>A[1]-b[1]).slice(0,3).map(([b,A])=>`"${b}" (failed ${A}\xD7)`);return{task:t.task,status:"truncated",abortReason:"iteration_limit",repeatedFailures:_,result:f[f.length-1]?.content||"(max iterations reached)",toolsUsed:i,tokensUsed:c,modelSpec:h&&p?`${h}:${p}`:null}}catch(_){for(let b of l)Ps(b);return{task:t.task,status:"failed",result:`Error: ${_.message}`,toolsUsed:i,tokensUsed:c,modelSpec:h&&p?`${h}:${p}`:null}}}async function fd(t,e=0){if(e>=2)return"ERROR: max agent nesting depth (2) reached \u2014 reviewer agents cannot spawn further agents.";let n=e===0?hw:gw,o=e===0?sd:od,s=(t.agents||[]).slice(0,n);if(s.length===0)return"ERROR: No agents specified";let r=e>0?" \u21B3 ":"",i=e>0?38:44,c=s.map(d=>ea(d)),l=s.map((d,f)=>{let m=c[f],h=m.model?` [${m.model}]`:"",p=d.task.substring(0,i-h.length);return`${r}Agent ${f+1}${h}: ${p}${d.task.length>p.length?"...":""}`}),u=new mw(l);u.start();try{let d=s.map((g,y)=>{let w=c[y],x=Math.min(g.max_iterations||o,o),R=w.model?{...g,model:`${w.provider}:${w.model}`,_skipLog:!0,max_iterations:x}:{...g,_skipLog:!0,max_iterations:x};return dd(R,{onUpdate:()=>{}},e).then(k=>(u.update(y,k.status==="failed"?"error":"done"),k)).catch(k=>(u.update(y,"error"),{task:g.task,status:"failed",result:`Error: ${k.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}))}),f=await Promise.all(d);u.stop(),Qi();let m=["Sub-agent results:",""],h=0,p=0;for(let g=0;g<f.length;g++){let y=f[g],w=y.status==="done"?"\u2713":y.status==="truncated"?"\u26A0":"\u2717",x=y.modelSpec?` [${y.modelSpec}]`:"";m.push(`${w} Agent ${g+1}${x}: ${y.task}`),m.push(` Status: ${y.status}`),m.push(` Tools used: ${y.toolsUsed.length>0?y.toolsUsed.join(", "):"none"}`),m.push(` Result: ${y.result}`),y.repeatedFailures&&y.repeatedFailures.length>0&&m.push(` Repeated failures: ${y.repeatedFailures.join("; ")}`),m.push(""),h+=y.tokensUsed.input,p+=y.tokensUsed.output}return m.push(`Total sub-agent tokens: ${h} input + ${p} output`),m.join(`
|
|
178
|
+
`)}catch(d){return u.stop(),Qi(),`ERROR: Sub-agent execution failed: ${d.message}`}}pd.exports={runSubAgent:dd,executeSpawnAgents:fd,clearAllLocks:Qi,classifyTask:ld,pickModelForTier:ud,resolveSubAgentModel:ea,classifyError:Zi,isRetryableError:id,callWithRetry:ad,getExcludedTools:cd,LOCK_TIMEOUT_MS:rd}});var Ds=G((Uv,Td)=>{var Le=require("fs"),Yt=require("path"),{atomicWrite:md,withFileLockSync:hd}=en(),xw=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 Qn(){let t=Yt.join(process.cwd(),".nex","brain");return Le.existsSync(t)||Le.mkdirSync(t,{recursive:!0}),t}function or(){return Yt.join(Qn(),".brain-index.json")}function sa(){return Yt.join(Qn(),".embeddings.json")}function Is(){let t=Yt.join(process.cwd(),".nex","brain");if(!Le.existsSync(t))return[];try{return Le.readdirSync(t).filter(e=>e.endsWith(".md")&&!e.startsWith(".")).map(e=>{let n=Yt.join(t,e),o=Le.statSync(n);return{name:e.replace(/\.md$/,""),path:n,size:o.size,modified:new Date(o.mtimeMs)}}).sort((e,n)=>n.modified-e.modified)}catch{return[]}}function Ls(t){let e={},n=t,o=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(o){let s=o[1].split(`
|
|
179
|
+
`);for(let r of s){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}n=o[2]}return{frontmatter:e,body:n}}function gd(t){let e=Yt.join(Qn(),`${t}.md`);if(!Le.existsSync(e))return{name:t,content:"",body:"",frontmatter:{}};let n=Le.readFileSync(e,"utf-8"),{frontmatter:o,body:s}=Ls(n);return{name:t,content:n,body:s,frontmatter:o}}function kw(t,e){let n=Yt.join(Qn(),`${t}.md`);md(n,e),Ew(t,e),vw()}function vw(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return;let t=sa();Le.existsSync(t)&&setImmediate(async()=>{try{await kd()}catch{}})}function Sw(t){let e=Yt.join(Qn(),`${t}.md`);return Le.existsSync(e)?(Le.unlinkSync(e),Tw(t),!0):!1}function sr(t){return t.toLowerCase().replace(/[^a-z0-9äöüß\s-]/g," ").split(/[\s-]+/).filter(e=>e.length>2&&!xw.has(e))}function oa(t){let e={},{frontmatter:n,body:o}=Ls(t),s=Array.isArray(n.tags)?n.tags:[];for(let i of s){let c=i.toLowerCase().replace(/[^a-z0-9-]/g,"");c.length>1&&(e[c]=(e[c]||0)+5)}let r=(o||t).split(`
|
|
180
|
+
`);for(let i of r)if(i.startsWith("#")){let c=i.replace(/^#+\s*/,"");for(let l of sr(c))e[l]=(e[l]||0)+3}for(let i of sr(o||t))e[i]=(e[i]||0)+1;return e}function ra(){let t=or();if(!Le.existsSync(t))return{documents:{}};try{return JSON.parse(Le.readFileSync(t,"utf-8"))}catch{return{documents:{}}}}function ia(t){md(or(),JSON.stringify(t,null,2))}function Ew(t,e){hd(or(),()=>{let n=ra(),{frontmatter:o}=Ls(e),s=Array.isArray(o.tags)?o.tags:[];n.documents[t]={keywords:oa(e),tags:s,modified:new Date().toISOString()},ia(n)})}function Tw(t){hd(or(),()=>{let e=ra();delete e.documents[t],ia(e)})}function na(){let t=Is(),e={documents:{}};for(let n of t){let o=Le.readFileSync(n.path,"utf-8"),{frontmatter:s}=Ls(o),r=Array.isArray(s.tags)?s.tags:[];e.documents[n.name]={keywords:oa(o),tags:r,modified:n.modified.toISOString()}}return ia(e),e}function $d(){let t=ra(),e=Is();for(let n of e){let o=t.documents[n.name];if(!o||new Date(o.modified)<n.modified)return na()}for(let n of Object.keys(t.documents))if(!e.some(o=>o.name===n))return na();return t}function yd(t,e={}){let{topK:n=3,minScore:o=.1}=e,s=sr(t);if(s.length===0)return[];let r=$d(),i=[];for(let[c,l]of Object.entries(r.documents)){let u=0;for(let d of s){l.keywords[d]&&(u+=l.keywords[d]);for(let[f,m]of Object.entries(l.keywords))f!==d&&f.length>3&&d.length>3&&(f.includes(d)||d.includes(f))&&(u+=m*.3)}u>=o&&i.push({name:c,score:u})}return i.sort((c,l)=>l.score-c.score),i.slice(0,n)}var wd=process.env.NEX_EMBED_MODEL||"nomic-embed-text",ta=400,Rw=50;async function bd(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return!1;try{let t=process.env.OLLAMA_HOST||"http://localhost:11434",e=require("http"),n=require("https"),o=new URL(`${t}/api/tags`),s=o.protocol==="https:"?n:e;return((await new Promise((c,l)=>{let u=s.get(o.toString(),{timeout:2e3},d=>{let f="";d.on("data",m=>f+=m),d.on("end",()=>{try{c(JSON.parse(f))}catch{l(new Error("bad json"))}})});u.on("error",l),u.on("timeout",()=>{u.destroy(),l(new Error("timeout"))})})).models||[]).map(c=>c.name).some(c=>c.startsWith(wd.split(":")[0]))}catch{return!1}}async function aa(t){let e=process.env.OLLAMA_HOST||"http://localhost:11434",n=require("http"),o=require("https"),s=new URL(`${e}/api/embeddings`),r=s.protocol==="https:"?o:n,i=JSON.stringify({model:wd,prompt:t});return new Promise((c,l)=>{let u=r.request(s,{method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(i)},timeout:3e4},d=>{let f="";d.on("data",m=>f+=m),d.on("end",()=>{try{c(JSON.parse(f).embedding||[])}catch(m){l(m)}})});u.on("error",l),u.on("timeout",()=>{u.destroy(),l(new Error("embedding timeout"))}),u.write(i),u.end()})}function _d(t,e){if(!t||!e||t.length!==e.length)return 0;let n=0,o=0,s=0;for(let i=0;i<t.length;i++)n+=t[i]*e[i],o+=t[i]*t[i],s+=e[i]*e[i];let r=Math.sqrt(o)*Math.sqrt(s);return r===0?0:n/r}function xd(t){let e=t.split(/\s+/),n=[],o=0;for(;o<e.length;){let s=e.slice(o,o+ta).join(" ");if(n.push({text:s,offset:o}),o+ta>=e.length)break;o+=ta-Rw}return n}async function kd(){let t=Is(),e={documents:{}},n=sa();if(Le.existsSync(n))try{e=JSON.parse(Le.readFileSync(n,"utf-8"))}catch{}for(let o of t){let s=e.documents[o.name];if(s&&new Date(s.modified)>=o.modified)continue;let r=Le.readFileSync(o.path,"utf-8"),i=xd(r),c=[];for(let l of i){let u=await aa(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(s=>s.name===o)||delete e.documents[o];return Le.writeFileSync(n,JSON.stringify(e),"utf-8"),e}async function vd(t,e={}){let{topK:n=3,minSimilarity:o=.3}=e,s=sa();if(!Le.existsSync(s))return[];let r;try{r=JSON.parse(Le.readFileSync(s,"utf-8"))}catch{return[]}let i=await aa(t),c=[];for(let[l,u]of Object.entries(r.documents||{})){let d=0,f="";for(let m of u.chunks||[]){let h=_d(i,m.embedding);h>d&&(d=h,f=m.text)}d>=o&&c.push({name:l,score:d,bestChunk:f})}return c.sort((l,u)=>u.score-l.score),c.slice(0,n)}function Sd(t,e,n={}){let{k:o=60,topK:s=3}=n,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,s)}async function Ed(t,e={}){let{topK:n=3,minScore:o=.1}=e,s=yd(t,{topK:n,minScore:o}),r=s;if(process.env.NEX_BRAIN_EMBEDDINGS!=="false")try{if(await bd()){let c=await vd(t,{topK:n});r=Sd(s,c,{topK:n})}}catch{}return r.map(i=>{let c=gd(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}})}var Vn={queryKey:null,result:null,ts:0},Cw=3e5;async function Aw(t){if(!t||!t.trim())return"";let e=Yt.join(process.cwd(),".nex","brain");if(!Le.existsSync(e)||Is().length===0)return"";let o=t.trim().toLowerCase().slice(0,200);if(Vn.result!==null&&Vn.queryKey===o&&Date.now()-Vn.ts<Cw)return Vn.result;let s;try{s=await Ed(t,{topK:3})}catch{return""}if(!s||s.length===0)return"";let r;try{r=Ve().estimateTokens}catch{r=d=>Math.ceil(d.length/4)}let i=25e3,c=[],l=0;for(let d of s){let f=d.content||"",m=r(f);if(l+m>i){let p=i-l;if(p<100)break;let g=p/m;f=f.slice(0,Math.floor(f.length*g))+`
|
|
181
|
+
...(truncated)`}let h=typeof d.score=="number"?d.score.toFixed(2):String(d.score);if(c.push(`--- ${d.name} (relevance: ${h}) ---
|
|
182
|
+
${f}`),l+=r(f),l>=i)break}if(c.length===0)return Vn={queryKey:o,result:"",ts:Date.now()},"";let u=`KNOWLEDGE BASE (auto-selected):
|
|
183
|
+
|
|
184
|
+
${c.join(`
|
|
185
|
+
|
|
186
|
+
`)}`;return Vn={queryKey:o,result:u,ts:Date.now()},u}Td.exports={getBrainDir:Qn,listDocuments:Is,readDocument:gd,writeDocument:kw,removeDocument:Sw,buildIndex:na,getIndex:$d,query:Ed,getBrainContext:Aw,isEmbeddingAvailable:bd,generateEmbedding:aa,buildEmbeddingIndex:kd,semanticQuery:vd,cosineSimilarity:_d,_keywordQuery:yd,_extractKeywords:oa,_chunkText:xd,parseFrontmatter:Ls,tokenize:sr,_fuseResults:Sd}});var ua=G((Wv,Nd)=>{var js=require("fs"),ca=require("path"),la=process.env.NEX_AUDIT!=="false",xn=null;function Rd(){return xn||(xn=ca.join(process.cwd(),".nex","audit"),js.existsSync(xn)||js.mkdirSync(xn,{recursive:!0}),xn)}function Cd(){let t=new Date().toISOString().split("T")[0];return ca.join(Rd(),`${t}.jsonl`)}function Ow(t){if(la)try{let e={timestamp:new Date().toISOString(),tool:t.tool,args:Ad(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},n=JSON.stringify(e)+`
|
|
187
|
+
`;js.appendFileSync(Cd(),n,"utf-8")}catch{}}function Ad(t){if(!t||typeof t!="object")return{};let e={};for(let[n,o]of Object.entries(t))/key|token|password|secret|credential/i.test(n)?e[n]="***":typeof o=="string"&&o.length>500?e[n]=o.substring(0,500)+`... (${o.length} chars)`:e[n]=o;return e}function Od(t={}){let e=Rd(),n=t.days||1,o=[];for(let s=0;s<n;s++){let r=t.date||new Date(Date.now()-s*864e5).toISOString().split("T")[0],i=ca.join(e,`${r}.jsonl`);if(!js.existsSync(i))continue;let c=js.readFileSync(i,"utf-8").split(`
|
|
188
|
+
`).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 Nw(t=1){let e=Od({days:t});if(e.length===0)return{totalCalls:0,byTool:{},avgDuration:0,successRate:1};let n={},o=0,s=0;for(let r of e)n[r.tool]=(n[r.tool]||0)+1,o+=r.duration||0,r.success&&s++;return{totalCalls:e.length,byTool:n,avgDuration:Math.round(o/e.length),successRate:s/e.length}}function Mw(t){la=t}function Pw(){return la}function Iw(){xn=null}Nd.exports={logToolExecution:Ow,sanitizeArgs:Ad,readAuditLog:Od,getAuditSummary:Nw,setAuditEnabled:Mw,isAuditEnabled:Pw,getAuditLogPath:Cd,_reset:Iw}});var Bd=G((Gv,Wd)=>{var De=require("fs").promises,Md=require("fs"),ke=require("path"),Se=require("util").promisify(require("child_process").exec),da=require("util").promisify(require("child_process").execFile),{spawnSync:Lw}=require("child_process"),fa=require("axios"),{isForbidden:Dw,isSSHForbidden:jw,isDangerous:qw,isCritical:Pd,isBashPathForbidden:Fw,confirm:Rt}=Je(),{showClaudeDiff:rr,showClaudeNewFile:Uw,showEditDiff:Bv,confirmFileChange:qs}=zl(),{C:ne,Spinner:Ww,getToolSpinnerText:Bw}=Me(),{isGitRepo:pa,getCurrentBranch:Id,getStatus:Hw,getDiff:Gw}=nn(),{recordChange:ir}=Ht(),{fuzzyFindText:Ld,findMostSimilar:Ws}=Eu(),{runDiagnostics:Fs}=Ru(),{findFileInIndex:Kw,getFileIndex:Hv}=Gi(),{resolveProfile:vt,sshExec:lt,scpUpload:Yw,scpDownload:zw}=Jn(),{resolveDeployConfig:Xw,loadDeployConfigs:Jw}=Xi(),{getEditMode:Dd}=Jo(),Vw=/^(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/,Qw=/^ssh\s/,Zw=/^ssh(?:\s+-\S+)*\s+\S+@?\S+\s+["']?[^-]/;async function gt(t){return De.access(t).then(()=>!0).catch(()=>!1)}async function ar(t){if(!t)return{fixedPath:null,message:""};let e=t.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),n=ut(e);if(n&&await gt(n))return{fixedPath:n,message:`(auto-fixed path: ${t} \u2192 ${e})`};let o=[".js",".ts",".jsx",".tsx",".mjs",".cjs",".json"],s=ke.extname(t);if(!s)for(let i of o){let c=ut(t+i);if(c&&await gt(c))return{fixedPath:c,message:`(auto-fixed: added ${i} extension)`}}if(s){let i=t.replace(/\.[^.]+$/,"");for(let c of o){if(c===s)continue;let l=ut(i+c);if(l&&await gt(l))return{fixedPath:l,message:`(auto-fixed: ${s} \u2192 ${c})`}}}let r=ke.basename(t);if(r&&r.length>2)try{let i=Kw(r).map(c=>ut(c));if(i.length===1)return{fixedPath:i[0],message:`(auto-fixed: found ${r} at ${ke.relative(process.cwd(),i[0])})`};if(i.length>1&&i.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
|
|
189
189
|
${i.map(l=>ke.relative(process.cwd(),l)).map(l=>` - ${l}`).join(`
|
|
190
|
-
`)}`}}catch{}return{fixedPath:null,message:""}}function
|
|
190
|
+
`)}`}}catch{}return{fixedPath:null,message:""}}function e0(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 Fd(t,e){let n=[];if(/command not found|: not found|not recognized/i.test(t)){let o=e.match(/^(\S+)/),s=o?o[1]:"";/^(npx|npm|node|yarn|pnpm|bun)$/.test(s)?n.push("HINT: Node.js/npm may not be in PATH. Check your Node.js installation."):/^(python|python3|pip|pip3)$/.test(s)?n.push("HINT: Python may not be installed. Try: brew install python3 (macOS) or apt install python3 (Linux)"):n.push(`HINT: "${s}" 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 '([^']+)'/),s=o?o[1]:"";s&&!s.startsWith(".")&&!s.startsWith("/")?n.push(`HINT: Missing npm package "${s}". Run: npm install ${s}`):n.push("HINT: Module not found. Check the import path or run npm install.")}if(/permission denied|EACCES/i.test(t)&&n.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+)/),s=o?o[1]||o[2]:"";n.push(`HINT: Port ${s||""} is already in use. Kill the process or use a different port.`)}if(/SyntaxError|Unexpected token/i.test(t)&&n.push("HINT: Syntax error in the code. Check the file at the line number shown above."),/TS\d{4}:/i.test(t)&&n.push("HINT: TypeScript compilation error. Fix the type issue at the indicated line."),/Test Suites:.*failed|Tests:.*failed/i.test(t)&&n.push("HINT: Test failures detected. Read the error output above to identify failing tests."),/fatal: not a git repository/i.test(t)&&n.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+)\)/),s=o?parseInt(o[1],10):null;s===6||/Could not resolve host/i.test(t)?n.push("HINT: Hostname could not be resolved. Check DNS or use an IP address directly."):s===7||/Failed to connect|Connection refused/i.test(t)?n.push("HINT: Service not running or port wrong. Check if the service is up and the port is correct."):s===22||/HTTP error/i.test(t)?n.push("HINT: HTTP 4xx/5xx response. The endpoint exists but returned an error status."):s===28||/timed out/i.test(t)?n.push("HINT: Request timed out. The host may be unreachable or the service is slow."):(s===35||/SSL.*error/i.test(t))&&n.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+)/),s=o?o[1]:"";n.push(`HINT: SSH remote port forwarding failed for port ${s}. The port may already be bound on the server. Check with: ssh server "ss -tuln | grep ${s}" and kill any lingering process with that port.`)}return/bind.*Cannot assign requested address|Address already in use/i.test(t)&&n.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)&&n.push("HINT: SSH connection timed out. Check if the host is reachable: ping <host> and verify the port with: nc -zv <host> 22"),/spawn \/bin\/sh ENOENT|spawn sh ENOENT/i.test(t)&&n.push("HINT: The working directory was deleted during this session \u2014 bash cannot execute commands in a non-existent cwd. Previous rm/delete commands succeeded. Use list_directory or glob to verify the state instead of retrying bash."),/cp.*\$f.*\$f\.bak.*sed.*-i\.bak|sed.*-i\.bak.*cp.*\$f.*\$f\.bak/i.test(e)&&n.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.'),n.length===0?t:t+`
|
|
191
191
|
|
|
192
192
|
`+n.join(`
|
|
193
|
-
`)}function Nd(t,e,n){let o=Is(t,e);if(!o)return null;let s=Math.max(2,Math.ceil(e.length*.03));return o.distance>s?null:{autoFixed:!0,matchText:o.text,content:t.split(o.text).join(n),distance:o.distance,line:o.line}}var Cd=!1,_n=null;function Uw(){_n&&(_n(),_n=null)}var oa=null;function Ww(t){oa=t}async function sa(){if(!Cd){Cd=!0;try{let{stdout:t}=await Se("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await Se('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await Se("git stash pop",{cwd:process.cwd(),timeout:1e4}),await Se("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var Bw=[/\.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 lt(t){let e=ke.isAbsolute(t)?ke.resolve(t):ke.resolve(process.cwd(),t);for(let n of Bw)if(n.test(e))return null;return e}var Hw=[{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 Ps(t,{server:e,context:n}={}){let o=e?e.replace(/[^a-zA-Z0-9@._-]/g,""):null,s=n?n.replace(/[^a-zA-Z0-9._/-]/g,""):null,r="kubectl";if(s&&(r+=` --context ${s}`),r+=` ${t}`,o){let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`ssh -o ConnectTimeout=10 -o BatchMode=yes ${o} "${i}"`}return r}async function Ad(t,e,n={}){switch(t){case"bash":{let o=e.command,s=kw(o);if(s){let f=Fw(o);return`BLOCKED: Command matches forbidden pattern: ${s}${f?`
|
|
194
|
-
HINT: ${f}`:""}`}let r=
|
|
195
|
-
HINT: Protected files (.env, credentials, venv, .ssh, etc.) cannot be deleted or moved via bash. Override with NEX_UNPROTECT=1 if intentional.`;if(n.autoConfirm?
|
|
196
|
-
${h}`}}case"read_file":{let o=
|
|
197
|
-
`+b.message:""}`}let r=Buffer.alloc(8192),i=await
|
|
198
|
-
`),d=await De.stat(o),f=u.length,m=350,h=!e.line_start&&!e.line_end,p=h&&f>m,g=(e.line_start||1)-1,y=p?m:e.line_end||u.length,w=ke.relative(process.cwd(),o),
|
|
193
|
+
`)}function Ud(t,e,n){let o=Ws(t,e);if(!o)return null;let s=Math.max(2,Math.ceil(e.length*.03));return o.distance>s?null:{autoFixed:!0,matchText:o.text,content:t.split(o.text).join(n),distance:o.distance,line:o.line}}var jd=!1,kn=null;function t0(){kn&&(kn(),kn=null)}var ha=null;function n0(t){ha=t}async function ma(){if(!jd){jd=!0;try{let{stdout:t}=await Se("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await Se('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await Se("git stash pop",{cwd:process.cwd(),timeout:1e4}),await Se("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var s0=[/\.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 ut(t){let e=ke.isAbsolute(t)?ke.resolve(t):ke.resolve(process.cwd(),t);for(let n of s0)if(n.test(e))return null;return e}var o0=[{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 Us(t,{server:e,context:n}={}){let o=e?e.replace(/[^a-zA-Z0-9@._-]/g,""):null,s=n?n.replace(/[^a-zA-Z0-9._/-]/g,""):null,r="kubectl";if(s&&(r+=` --context ${s}`),r+=` ${t}`,o){let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`ssh -o ConnectTimeout=10 -o BatchMode=yes ${o} "${i}"`}return r}async function qd(t,e,n={}){switch(t){case"bash":{let o=e.command,s=Dw(o);if(s){let f=e0(o);return`BLOCKED: Command matches forbidden pattern: ${s}${f?`
|
|
194
|
+
HINT: ${f}`:""}`}let r=Fw(o);if(r)return`BLOCKED: Destructive operation on protected path: ${r}
|
|
195
|
+
HINT: Protected files (.env, credentials, venv, .ssh, etc.) cannot be deleted or moved via bash. Override with NEX_UNPROTECT=1 if intentional.`;if(n.autoConfirm?Pd(o):qw(o)){let f=Pd(o)?"\u26D4":"\u26A0";if(!await Rt(` ${f} bash: \`${o}\``,{toolName:"bash"}))return"CANCELLED: User declined to execute this command."}let c;try{c=process.cwd(),Md.accessSync(c)}catch{c=require("os").homedir(),n.silent||console.log(`${ne.yellow} \u26A0 Working directory no longer exists \u2014 running in ${c}${ne.reset}`)}let l=Qw.test(o.trim())&&!Zw.test(o.trim());if(Vw.test(o.trim())||l){n.silent||console.log(`${ne.dim} \u25B6 interactive: ${o}${ne.reset}`);let f=Lw("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}=jn(),d=n.silent?null:new u("bash",o.substring(0,40));d&&d.start();try{let{stdout:f,stderr:m}=await Se(o,{cwd:c,timeout:9e4,maxBuffer:5242880});return d&&d.stop(),f||m||"(no output)"}catch(f){d&&d.stop();let m=(f.stderr||f.stdout||f.message||"").toString().substring(0,5e3),h=Fd(m,o);return`EXIT ${f.code||1}
|
|
196
|
+
${h}`}}case"read_file":{let o=ut(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await gt(o)){let b=await ar(e.path);if(b.fixedPath)o=b.fixedPath,console.log(`${ne.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ke.relative(process.cwd(),o)}${ne.reset}`);else return`ERROR: File not found: ${e.path}${b.message?`
|
|
197
|
+
`+b.message:""}`}let r=Buffer.alloc(8192),i=await Md.promises.open(o,"r"),{bytesRead:c}=await i.read(r,0,8192,0);await i.close();for(let b=0;b<c;b++)if(r[b]===0)return`ERROR: ${o} is a binary file (not readable as text)`;let l=await De.readFile(o,"utf-8");if(!l&&(await De.stat(o)).size>0)return`WARNING: ${o} is empty or unreadable`;let u=l.split(`
|
|
198
|
+
`),d=await De.stat(o),f=u.length,m=350,h=!e.line_start&&!e.line_end,p=h&&f>m,g=(e.line_start||1)-1,y=p?m:e.line_end||u.length,w=ke.relative(process.cwd(),o),x=p?`showing lines 1-${m} of ${f}`:e.line_start||e.line_end?`lines ${g+1}-${y} of ${f}`:`${f} lines`,R=`File: ${w} (${x}, ${d.size} bytes)`,k=u.slice(g,y).map((b,A)=>`${g+A+1}: ${b}`).join(`
|
|
199
199
|
`),_=p?`
|
|
200
200
|
|
|
201
201
|
[File truncated: showing lines 1-${m} of ${f} total. Use line_start/line_end to read other sections, e.g. line_start=${m+1} line_end=${Math.min(m*2,f)}]`:!h&&f>m?`
|
|
202
202
|
[Large file (${f} lines total) \u2014 use line_start/line_end for other sections]`:"";return`${R}
|
|
203
|
-
${
|
|
204
|
-
`+d.message:""}`}let r=await De.readFile(o,"utf-8"),i=e.old_text,c=!1,l=!1;if(!r.includes(e.old_text)){let{getActiveModelId:d,getActiveProviderName:f}=
|
|
203
|
+
${k}${_}`}case"write_file":{await ma();let o=ut(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let s=await gt(o),r=null;if(n.autoConfirm)s&&(r=await De.readFile(o,"utf-8"));else if(s){r=await De.readFile(o,"utf-8");let d=await Fs(o,e.content);if(rr(o,r,e.content,{annotations:d}),!await qs("Overwrite"))return"CANCELLED: User declined to overwrite file."}else{let d=await Fs(o,e.content);if(Uw(o,e.content,{annotations:d}),!await qs("Create"))return"CANCELLED: User declined to create file."}let i=ke.dirname(o);await gt(i)||await De.mkdir(i,{recursive:!0}),await De.writeFile(o,e.content,"utf-8");let l=/[/\\]\.git[/\\]hooks[/\\]/.test(o)||o.endsWith(".sh")||e.content.startsWith("#!");l&&await De.chmod(o,493),ir("write_file",o,r,e.content);let u=l?" [chmod +x applied]":"";return`Written: ${o} (${e.content.length} chars)${u}`}case"edit_file":{await ma();let o=ut(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await gt(o)){let d=await ar(e.path);if(d.fixedPath)o=d.fixedPath,console.log(`${ne.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ke.relative(process.cwd(),o)}${ne.reset}`);else return`ERROR: File not found: ${e.path}${d.message?`
|
|
204
|
+
`+d.message:""}`}let r=await De.readFile(o,"utf-8"),i=e.old_text,c=!1,l=!1;if(!r.includes(e.old_text)){let{getActiveModelId:d,getActiveProviderName:f}=Re();if(Dd(d(),f())==="strict"){let p=Ws(r,e.old_text);return p?`ERROR: old_text not found in ${o} (strict mode \u2014 exact match required)
|
|
205
205
|
Most similar text (line ${p.line}, distance ${p.distance}):
|
|
206
|
-
${p.text}`:`ERROR: old_text not found in ${o} (strict mode \u2014 exact match required)`}let h=
|
|
207
|
-
`),R=Math.max(0,g.line-6),
|
|
208
|
-
`),b=`line_start=${Math.max(1,g.line-5)} line_end=${Math.min(
|
|
206
|
+
${p.text}`:`ERROR: old_text not found in ${o} (strict mode \u2014 exact match required)`}let h=Ld(r,e.old_text);if(h)i=h,c=!0,console.log(`${ne.dim} \u2713 fuzzy whitespace match applied${ne.reset}`);else{let p=Ud(r,e.old_text,e.new_text);if(p){if(!n.autoConfirm){let R=await Fs(o,p.content);if(rr(o,r,p.content,{annotations:R}),!await qs(`Apply (auto-fix, line ${p.line}, distance ${p.distance})`))return"CANCELLED: User declined to apply edit."}await De.writeFile(o,p.content,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(o)||o.endsWith(".sh")||p.content.startsWith("#!"))&&await De.chmod(o,493),ir("edit_file",o,r,p.content);let x=p.matchText.length>80?p.matchText.substring(0,77)+"...":p.matchText;return console.log(`${ne.dim} \u2713 auto-fixed edit: line ${p.line}, distance ${p.distance}${ne.reset}`),`Edited: ${o} (auto-fixed, line ${p.line}, distance ${p.distance}, matched: "${x}")`}let g=Ws(r,e.old_text);if(g){let x=r.split(`
|
|
207
|
+
`),R=Math.max(0,g.line-6),k=Math.min(x.length,g.line+10),_=x.slice(R,k).map((A,M)=>`${R+M+1}: ${A}`).join(`
|
|
208
|
+
`),b=`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})
|
|
209
209
|
|
|
210
210
|
Actual file content around line ${g.line} \u2014 use this to correct old_text:
|
|
211
211
|
${_}
|
|
@@ -213,119 +213,119 @@ ${_}
|
|
|
213
213
|
Fix: update old_text to match the exact lines above, then retry. If you need more context: read_file with ${b}`}let y=(e.old_text||"").trim().split(`
|
|
214
214
|
`)[0].slice(0,60),w=y?`
|
|
215
215
|
Recovery: grep -n "${y.replace(/"/g,'\\"')}" <file> to find the line, then re-read that section with line_start/line_end.`:`
|
|
216
|
-
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}${w}`}}if(!n.autoConfirm){let d=r.split(i).join(e.new_text),f=await
|
|
217
|
-
`)||"(empty)"}case"search_files":{let o=
|
|
216
|
+
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}${w}`}}if(!n.autoConfirm){let d=r.split(i).join(e.new_text),f=await Fs(o,d);if(rr(o,r,d,{annotations:f}),!await qs(c?"Apply (fuzzy match)":"Apply"))return"CANCELLED: User declined to apply edit."}let u=r.split(i).join(e.new_text);return await De.writeFile(o,u,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(o)||o.endsWith(".sh")||u.startsWith("#!"))&&await De.chmod(o,493),ir("edit_file",o,r,u),c?`Edited: ${o} (fuzzy match)`:`Edited: ${o}`}case"list_directory":{let o=ut(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await gt(o)){let u=e.path.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),d=ut(u),f=await gt(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 m;try{m=await De.readdir(u,{withFileTypes:!0})}catch{return}m=m.filter(h=>!h.name.startsWith(".")&&h.name!=="node_modules");for(let h of m){if(i&&!h.isDirectory()&&!i.test(h.name))continue;let p=h.isDirectory()?"/":"";c.push(`${f}${h.name}${p}`),h.isDirectory()&&await l(ke.join(u,h.name),d+1,f+" ")}};return await l(o,1,""),c.join(`
|
|
217
|
+
`)||"(empty)"}case"search_files":{let o=ut(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let s=["-rn","--null","-H"];e.file_pattern&&s.push(`--include=${e.file_pattern}`),s.push(e.pattern,o);try{let{stdout:r}=await da("grep",s,{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(`
|
|
218
218
|
`).filter(m=>m.trim());for(let m of f)if(c.push(`${u}:${m}`),c.length>=50)break}if(c.length>=50)break}return c.join(`
|
|
219
|
-
`)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let s=process.cwd(),r=e.path?
|
|
220
|
-
`);return m.update({count:R.length,detail:e.pattern}),m.stop(),b?`${
|
|
221
|
-
|
|
222
|
-
\u26A0 Results truncated at 200. Use a more specific pattern.`:
|
|
223
|
-
`);for(let y of f)if(y.startsWith("diff --git")){let w=y.match(/diff --git a\/(.+) b\/(.+)/);w&&d.add(w[2])}let m=["-rn","-E","--null","-H","--exclude=*.md","--exclude=*.txt","--exclude=*.json","--exclude=*.yaml","--exclude=*.yml"];e.ignore_case&&m.push("-i"),e.include&&m.push(`--include=${e.include}`),e.type&&m.push(`--include=*.${e.type}`),e.context?m.push("-C",String(e.context)):(e.before_context&&m.push("-B",String(e.before_context)),e.after_context&&m.push("-A",String(e.after_context))),e.output_mode==="files_with_matches"?m.push("-l"):e.output_mode==="count"&&m.push("-c"),m.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage");let{ToolProgress:h}=
|
|
224
|
-
`).filter(_=>_.trim());g=g.concat(
|
|
225
|
-
`).filter(
|
|
226
|
-
`).trim()||"(no matches in staged files)"}let s=["-rn","-E","--null","-H"];e.ignore_case&&s.push("-i"),e.include&&s.push(`--include=${e.include}`),e.type&&s.push(`--include=*.${e.type}`);let r=20;e.context?s.push("-C",String(Math.min(Number(e.context),r))):(e.before_context&&s.push("-B",String(Math.min(Number(e.before_context),r))),e.after_context&&s.push("-A",String(Math.min(Number(e.after_context),r)))),e.output_mode==="files_with_matches"?s.push("-l"):e.output_mode==="count"&&s.push("-c"),s.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage"),s.push(e.pattern,o);let{ToolProgress:i}=
|
|
219
|
+
`)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let s=process.cwd(),r=e.path?ut(e.path):s,i=e.pattern,c=M=>{let O=M.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"(.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");return new RegExp(`^${O}$`)},l=c(i),u=i.split("/").pop(),d=c(u),{ToolProgress:f}=jn(),m=new f("glob","Finding files...");m.start();let{getFileIndex:h,getIndexedCwd:p,refreshIndex:g,isIndexValid:y}=Gi(),w=h(),x=p();y(r)||(await g(r),w=h());let R=w.filter(M=>l.test(M)||d.test(ke.basename(M))).map(M=>ke.join(r,M));if(R.length===0)return m.stop(),"(no matches)";let k=await Promise.all(R.slice(0,210).map(async M=>{try{let O=await De.stat(M);return{path:M,mtime:O.mtimeMs}}catch{return{path:M,mtime:0}}}));k.sort((M,O)=>O.mtime-M.mtime);let _=k.map(M=>M.path),b=R.length>200,A=_.slice(0,200).join(`
|
|
220
|
+
`);return m.update({count:R.length,detail:e.pattern}),m.stop(),b?`${A}
|
|
221
|
+
|
|
222
|
+
\u26A0 Results truncated at 200. Use a more specific pattern.`:A}case"grep":{let o=e.path?ut(e.path):process.cwd();if(e.staged){let{getDiff:l}=nn(),u=await l(!0);if(!u.trim())return"(no staged changes)";let d=new Set,f=u.split(`
|
|
223
|
+
`);for(let y of f)if(y.startsWith("diff --git")){let w=y.match(/diff --git a\/(.+) b\/(.+)/);w&&d.add(w[2])}let m=["-rn","-E","--null","-H","--exclude=*.md","--exclude=*.txt","--exclude=*.json","--exclude=*.yaml","--exclude=*.yml"];e.ignore_case&&m.push("-i"),e.include&&m.push(`--include=${e.include}`),e.type&&m.push(`--include=*.${e.type}`),e.context?m.push("-C",String(e.context)):(e.before_context&&m.push("-B",String(e.before_context)),e.after_context&&m.push("-A",String(e.after_context))),e.output_mode==="files_with_matches"?m.push("-l"):e.output_mode==="count"&&m.push("-c"),m.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage");let{ToolProgress:h}=jn(),p=new h("grep","Searching staged content...");p.start();let g=[];for(let y of d)try{let w=ke.join(process.cwd(),y);if(await gt(w)){let x=[...m];x.push(e.pattern,w);let{stdout:R}=await da("grep",x,{cwd:process.cwd(),timeout:3e4,maxBuffer:2*1024*1024});if(e.output_mode==="files_with_matches"||e.output_mode==="count"){let k=R.trim().split(`
|
|
224
|
+
`).filter(_=>_.trim());g=g.concat(k)}else{let k=R.split("\0");for(let _=0;_<k.length;_+=2){let b=k[_+1];if(b){let A=b.split(`
|
|
225
|
+
`).filter(M=>M.trim());for(let M of A)g.push(`${y}:${M}`)}}}}}catch{}return p.update({count:g.length,detail:"in staged files"}),p.stop(),g.join(`
|
|
226
|
+
`).trim()||"(no matches in staged files)"}let s=["-rn","-E","--null","-H"];e.ignore_case&&s.push("-i"),e.include&&s.push(`--include=${e.include}`),e.type&&s.push(`--include=*.${e.type}`);let r=20;e.context?s.push("-C",String(Math.min(Number(e.context),r))):(e.before_context&&s.push("-B",String(Math.min(Number(e.before_context),r))),e.after_context&&s.push("-A",String(Math.min(Number(e.after_context),r)))),e.output_mode==="files_with_matches"?s.push("-l"):e.output_mode==="count"&&s.push("-c"),s.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage"),s.push(e.pattern,o);let{ToolProgress:i}=jn(),c=new i("grep","Searching...");c.start();try{let{stdout:l}=await da("grep",s,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),u;if(e.output_mode==="files_with_matches"||e.output_mode==="count")u=l.trim().split(`
|
|
227
227
|
`).filter(m=>m.trim());else{let m=l.split("\0");u=[];for(let h=0;h<m.length;h+=2){let p=m[h],g=m[h+1];if(p&&g){let y=g.split(`
|
|
228
228
|
`).filter(w=>w.trim());for(let w of y)u.push(`${p}:${w}`)}}}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(`
|
|
229
|
-
`).trim()||"(no matches)"}catch(l){return c.stop(),l.code===2?`ERROR: Invalid regex pattern: ${e.pattern}`:"(no matches)"}}case"patch_file":{await
|
|
230
|
-
`+w.message:""}`}let r=e.patches;if(!Array.isArray(r)||r.length===0)return"ERROR: No patches provided";let i=await De.readFile(o,"utf-8"),{getActiveModelId:c,getActiveProviderName:l}=
|
|
231
|
-
Most similar text (line ${
|
|
232
|
-
${
|
|
229
|
+
`).trim()||"(no matches)"}catch(l){return c.stop(),l.code===2?`ERROR: Invalid regex pattern: ${e.pattern}`:"(no matches)"}}case"patch_file":{await ma();let o=ut(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await gt(o)){let w=await ar(e.path);if(w.fixedPath)o=w.fixedPath,console.log(`${ne.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ke.relative(process.cwd(),o)}${ne.reset}`);else return`ERROR: File not found: ${e.path}${w.message?`
|
|
230
|
+
`+w.message:""}`}let r=e.patches;if(!Array.isArray(r)||r.length===0)return"ERROR: No patches provided";let i=await De.readFile(o,"utf-8"),{getActiveModelId:c,getActiveProviderName:l}=Re(),u=Dd(c(),l()),d=[],f=!1,m=!1;for(let w=0;w<r.length;w++){let{old_text:x,new_text:R}=r[w];if(i.includes(x))d.push({old_text:x,new_text:R});else if(u==="strict"){let k=Ws(i,x);return k?`ERROR: Patch ${w+1} old_text not found in ${o} (strict mode \u2014 exact match required)
|
|
231
|
+
Most similar text (line ${k.line}, distance ${k.distance}):
|
|
232
|
+
${k.text}`:`ERROR: Patch ${w+1} old_text not found in ${o} (strict mode \u2014 exact match required)`}else{let k=Ld(i,x);if(k)d.push({old_text:k,new_text:R}),f=!0;else{let _=Ws(i,x);if(_){let b=Math.max(3,Math.ceil(x.length*.05));if(_.distance<=b)d.push({old_text:_.text,new_text:R}),m=!0;else return`ERROR: Patch ${w+1} old_text not found in ${o}
|
|
233
233
|
Most similar text (line ${_.line}, distance ${_.distance}):
|
|
234
|
-
${_.text}`}else return`ERROR: Patch ${w+1} old_text not found in ${o}`}}}let h=i;for(let{old_text:w,new_text:
|
|
234
|
+
${_.text}`}else return`ERROR: Patch ${w+1} old_text not found in ${o}`}}}let h=i;for(let{old_text:w,new_text:x}of d)h=h.split(w).join(x);if(!n.autoConfirm){let w=await Fs(o,h);if(rr(o,i,h,{annotations:w}),!await qs(f?"Apply patches (fuzzy match)":"Apply patches"))return"CANCELLED: User declined to apply patches."}await De.writeFile(o,h,"utf-8");let p=/[/\\]\.git[/\\]hooks[/\\]/.test(o)||o.endsWith(".sh")||h.startsWith("#!");p&&await De.chmod(o,493),ir("patch_file",o,i,h);let g=m?" (auto-fixed)":f?" (fuzzy match)":"",y=p?" [chmod +x applied]":"";return`Patched: ${o} (${r.length} replacements)${g}${y}`}case"web_fetch":{let o=e.url,s=e.max_length||1e4;try{let r=await fa.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,s)||"(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 s=await fa.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=s.data?.choices?.[0]?.message?.content||"",i=s.data?.citations||[],c=`[Perplexity grounded search]
|
|
235
235
|
|
|
236
236
|
${r}`;return i.length>0&&(c+=`
|
|
237
237
|
|
|
238
238
|
Sources:
|
|
239
239
|
`+i.slice(0,o).map((l,u)=>`${u+1}. ${l}`).join(`
|
|
240
|
-
`)),c}catch(s){console.error(`${ne.dim} Perplexity search failed (${s.message}), falling back to DuckDuckGo${ne.reset}`)}try{let r=(await
|
|
240
|
+
`)),c}catch(s){console.error(`${ne.dim} Perplexity search failed (${s.message}), falling back to DuckDuckGo${ne.reset}`)}try{let r=(await fa.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}
|
|
241
241
|
${u.url}`).join(`
|
|
242
242
|
|
|
243
|
-
`)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:o}=
|
|
243
|
+
`)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:o}=Os();try{let s=await o(e.url,{waitFor:e.wait_for}),r=s.links.length>0?`
|
|
244
244
|
|
|
245
245
|
Links:
|
|
246
246
|
`+s.links.map(i=>` ${i.text} \u2192 ${i.href}`).join(`
|
|
247
247
|
`):"";return`Title: ${s.title}
|
|
248
248
|
URL: ${s.url}
|
|
249
249
|
|
|
250
|
-
${s.text}${r}`}catch(s){return`ERROR: ${s.message}`}}case"browser_screenshot":{let{browserScreenshot:o}=
|
|
250
|
+
${s.text}${r}`}catch(s){return`ERROR: ${s.message}`}}case"browser_screenshot":{let{browserScreenshot:o}=Os();try{let s=await o(e.url,{width:e.width,height:e.height,fullPage:e.full_page});return`Screenshot saved: ${s.path}
|
|
251
251
|
Title: ${s.title}
|
|
252
252
|
URL: ${s.url}
|
|
253
253
|
|
|
254
|
-
To analyze visually, paste the path into your next message: ${s.path}`}catch(s){return`ERROR: ${s.message}`}}case"browser_click":{let{browserClick:o}=
|
|
254
|
+
To analyze visually, paste the path into your next message: ${s.path}`}catch(s){return`ERROR: ${s.message}`}}case"browser_click":{let{browserClick:o}=Os();try{return await o(e.url,{selector:e.selector,text:e.text})}catch(s){return`ERROR: ${s.message}`}}case"browser_fill":{let{browserFill:o}=Os();try{return await o(e.url,{selector:e.selector,value:e.value,submit:e.submit})}catch(s){return`ERROR: ${s.message}`}}case"ask_user":{let{question:o,options:s=[]}=e;return ha?new Promise(r=>{kn=()=>r("CANCELLED"),ha(o,s).then(i=>{kn=null,r(i||"User did not answer")})}):new Promise(r=>{let i=require("readline").createInterface({input:process.stdin,output:process.stdout});kn=()=>{i.close(),r("CANCELLED")};let c=s.length>0?`
|
|
255
255
|
${s.map((l,u)=>` ${u+1}. ${l}`).join(`
|
|
256
256
|
`)}
|
|
257
257
|
`:"";console.log(`
|
|
258
|
-
${ne.cyan}${ne.bold} ? ${o}${ne.reset}${c}`),i.question(`${ne.cyan} > ${ne.reset}`,l=>{
|
|
258
|
+
${ne.cyan}${ne.bold} ? ${o}${ne.reset}${c}`),i.question(`${ne.cyan} > ${ne.reset}`,l=>{kn=null,i.close(),r(l.trim()||"(no response)")})})}case"git_status":{if(!await pa())return"ERROR: Not a git repository";let o=await Id()||"(detached)",s=await Hw();if(s.length===0)return`Branch: ${o}
|
|
259
259
|
Clean working tree (no changes)`;let r=[`Branch: ${o}`,`Changed files (${s.length}):`];for(let i of s){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(`
|
|
260
|
-
`)}case"git_diff":{if(!await
|
|
260
|
+
`)}case"git_diff":{if(!await pa())return"ERROR: Not a git repository";let o;if(e.file){let s=["diff"];e.staged&&s.push("--cached"),s.push("--",e.file);try{o=execFileSync("git",s,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()}catch{o=""}}else o=await Gw(!!e.staged);return o||"(no diff)"}case"git_log":{if(!await pa())return"ERROR: Not a git repository";let s=["log","--oneline",`-${Math.min(e.count||10,50)}`];e.file&&s.push("--",e.file);try{return execFileSync("git",s,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()||"(no commits)"}catch{return"(no commits)"}}case"task_list":{let{createTasks:o,updateTask:s,getTaskList:r,renderTaskList:i,hasActiveTasks:c}=Qo(),{getActiveTaskProgress:l}=Me(),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(`
|
|
261
261
|
`+i()),`Created task list "${e.name}" with ${d.length} tasks:
|
|
262
262
|
`+d.map(f=>` ${f.id}: ${f.description}`).join(`
|
|
263
263
|
`)}case"update":return!e.task_id||!e.status?"ERROR: task_list update requires task_id and status":s(e.task_id,e.status,e.result)?(u||console.log(`
|
|
264
264
|
`+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(`
|
|
265
|
-
`+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}=
|
|
265
|
+
`+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}=nr();return o(e)}case"switch_model":{let{setActiveModel:o,getActiveProviderName:s,getActiveModelId:r}=Re();return o(e.model)?`Switched to ${s()}:${r()}`:`ERROR: Unknown model: ${e.model}. Use /providers to see available models.`}case"gh_run_list":{let o=Math.min(e.limit||10,30),s=["run","list","--limit",String(o),"--json","databaseId,status,conclusion,name,headBranch,createdAt,updatedAt,event"];e.workflow&&s.push("--workflow",e.workflow),e.branch&&s.push("--branch",e.branch),e.status&&s.push("--status",e.status);try{let{stdout:r}=await Se(`gh ${s.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(`
|
|
266
266
|
`)}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(`
|
|
267
267
|
`)[0]}`}}case"gh_run_view":{if(!e.run_id)return"ERROR: run_id is required";try{if(e.log){let{stdout:i}=await Se(`gh run view ${e.run_id} --log`,{cwd:process.cwd(),timeout:6e4,maxBuffer:5242880});return i.substring(0,8e3)+(i.length>8e3?`
|
|
268
268
|
...(truncated)`:"")}let{stdout:o}=await Se(`gh run view ${e.run_id} --json status,conclusion,name,headBranch,createdAt,updatedAt,jobs`,{cwd:process.cwd(),timeout:3e4}),s=JSON.parse(o),r=[`Run: ${s.name} [${e.run_id}]`,`Branch: ${s.headBranch} Status: ${s.conclusion||s.status}`,`Started: ${s.createdAt} Finished: ${s.updatedAt||"\u2014"}`,"","Jobs:"];for(let i of s.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(`
|
|
269
269
|
`)}catch(o){return`ERROR: ${(o.stderr||o.message||"").toString().split(`
|
|
270
|
-
`)[0]}`}}case"gh_workflow_trigger":{if(!e.workflow)return"ERROR: workflow is required";let{confirm:o}=
|
|
270
|
+
`)[0]}`}}case"gh_workflow_trigger":{if(!e.workflow)return"ERROR: workflow is required";let{confirm:o}=Je(),s=e.branch||await Id()||"main",r=e.inputs?Object.entries(e.inputs).map(([l,u])=>`-f ${l}=${u}`).join(" "):"",i=`gh workflow run ${e.workflow} --ref ${s} ${r}`.trim();if(console.log(`
|
|
271
271
|
${ne.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${s}${ne.reset}`),!await o(" Trigger?"))return"CANCELLED: User declined to trigger workflow.";try{return await Se(i,{cwd:process.cwd(),timeout:3e4}),`Workflow "${e.workflow}" triggered on branch "${s}". Check status with gh_run_list.`}catch(l){return`ERROR: ${(l.stderr||l.message||"").toString().split(`
|
|
272
|
-
`)[0]}`}}case"k8s_pods":{let o=e.namespace?`-n ${e.namespace}`:"-A",s=e.label?`-l ${e.label}`:"",r=
|
|
273
|
-
`)[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",s=e.tail||100,r=`logs ${e.pod} -n ${o} --tail=${s}`;e.since&&(r+=` --since=${e.since}`),e.container&&(r+=` -c ${e.container}`);let i=
|
|
272
|
+
`)[0]}`}}case"k8s_pods":{let o=e.namespace?`-n ${e.namespace}`:"-A",s=e.label?`-l ${e.label}`:"",r=Us(`get pods ${o} ${s} -o wide`.trim(),e);try{let{stdout:i,stderr:c}=await Se(r,{timeout:3e4,maxBuffer:2097152});return(i||c||"(no pods)").trim()}catch(i){let c=(i.stderr||i.message||"").toString().split(`
|
|
273
|
+
`)[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",s=e.tail||100,r=`logs ${e.pod} -n ${o} --tail=${s}`;e.since&&(r+=` --since=${e.since}`),e.container&&(r+=` -c ${e.container}`);let i=Us(r,e);try{let{stdout:c,stderr:l}=await Se(i,{timeout:6e4,maxBuffer:5242880}),u=(c||l||"(no logs)").trim();return u.substring(0,2e4)+(u.length>2e4?`
|
|
274
274
|
...(truncated)`:"")}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
|
|
275
275
|
`)[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(`
|
|
276
|
-
${ne.yellow} \u26A0 kubectl exec into pod: ${e.pod} (ns: ${o})${ne.reset}`),console.log(`${ne.dim} Command: ${e.command}${ne.reset}`),!await
|
|
276
|
+
${ne.yellow} \u26A0 kubectl exec into pod: ${e.pod} (ns: ${o})${ne.reset}`),console.log(`${ne.dim} Command: ${e.command}${ne.reset}`),!await Rt(" 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=Us(r,e);try{let{stdout:c,stderr:l}=await Se(i,{timeout:6e4,maxBuffer:2097152});return(c||l||"(no output)").trim()}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
|
|
277
277
|
`)[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(`
|
|
278
|
-
${ne.yellow} \u26A0 kubectl apply: ${i}${e.namespace?` (ns: ${e.namespace})`:""}${ne.reset}`),!await
|
|
278
|
+
${ne.yellow} \u26A0 kubectl apply: ${i}${e.namespace?` (ns: ${e.namespace})`:""}${ne.reset}`),!await Rt(" Apply to cluster?"))return"CANCELLED: User declined."}let s=`apply -f ${e.file}`;e.namespace&&(s+=` -n ${e.namespace}`),o&&(s+=" --dry-run=client");let r=Us(s,e);try{let{stdout:i,stderr:c}=await Se(r,{timeout:12e4,maxBuffer:2097152});return(i||c||"(no output)").trim()}catch(i){return`ERROR: ${(i.stderr||i.message||"").toString().split(`
|
|
279
279
|
`)[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(`
|
|
280
|
-
${ne.yellow} \u26A0 ${c}: deployment/${e.deployment} (ns: ${o})${ne.reset}`),!await
|
|
281
|
-
`)[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:s}=
|
|
280
|
+
${ne.yellow} \u26A0 ${c}: deployment/${e.deployment} (ns: ${o})${ne.reset}`),!await Rt(` ${c}?`))return"CANCELLED: User declined."}let r=`rollout ${e.action} deployment/${e.deployment} -n ${o}`,i=Us(r,e);try{let{stdout:c,stderr:l}=await Se(i,{timeout:12e4,maxBuffer:2097152});return(c||l||"(no output)").trim()}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
|
|
281
|
+
`)[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:s}=Ds(),{name:r,content:i,mode:c}=e;if(c==="create"&&s(r).content)return`ERROR: Document "${r}" already exists. Use mode "update" to overwrite.`;if(c==="append"){let l=s(r),u=l.content?l.content+`
|
|
282
282
|
|
|
283
|
-
`+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=
|
|
283
|
+
`+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=vt(e.server)}catch(b){return`ERROR: ${b.message}`}let s=e.command,r=!!e.sudo,i=(e.timeout||30)*1e3,c=jw(s);if(c)return/\bsed\s+-n\s+['"]?\d+,\d+p/.test(s)?`BLOCKED: sed -n line-range is blocked (floods context). To read specific lines from a remote file use:
|
|
284
284
|
grep -n "pattern" /path/to/file -A 50
|
|
285
285
|
or to read the whole file:
|
|
286
286
|
cat /path/to/file
|
|
287
287
|
NEVER use sed -n again \u2014 it will always be blocked.`:`BLOCKED: Remote command matches SSH secret-exposure pattern: ${c}
|
|
288
|
-
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(s=s.replace(/(-[BAC])\s*(\d+)/g,(b,
|
|
289
|
-
${ne.yellow} \u26A0 Remote command on ${b}: ${s}${ne.reset}`),!await
|
|
288
|
+
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(s=s.replace(/(-[BAC])\s*(\d+)/g,(b,A,M)=>{let O=Math.min(Number(M),20);return`${A} ${O}`}),s=s.replace(/(--(?:before|after|context)=)(\d+)/g,(b,A,M)=>A+Math.min(Number(M),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(s)){let b=o.user?`${o.user}@${o.host}`:o.host;if(console.log(`
|
|
289
|
+
${ne.yellow} \u26A0 Remote command on ${b}: ${s}${ne.reset}`),!await Rt(" Execute on remote server?"))return"CANCELLED: User declined to execute remote command."}let{stdout:u,stderr:d,exitCode:f,error:m}=await lt(o,s,{timeout:i,sudo:r}),h=[u,d].filter(Boolean).join(`
|
|
290
290
|
`).trim();if(f!==0)return`EXIT ${f}
|
|
291
291
|
${m||h||"(no output)"}`;let p=/\bgrep\b/.test(s),g=h;p&&(g=g.split(`
|
|
292
292
|
`).filter(b=>b!=="--").join(`
|
|
293
293
|
`));let y=p?100:200,w=g.split(`
|
|
294
294
|
`);w.length>y&&(g=`(${w.length-y} earlier lines omitted \u2014 showing last ${y})
|
|
295
295
|
`+w.slice(-y).join(`
|
|
296
|
-
`));let
|
|
297
|
-
`),
|
|
298
|
-
`)||"(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=
|
|
299
|
-
${ne.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${s}:${e.remote_path}${ne.reset}`),!await
|
|
300
|
-
${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 s=!e.server||e.server==="local"||e.server==="localhost",r=e.action==="status",i=null;if(!s)try{i=
|
|
301
|
-
${ne.yellow} \u26A0 Service: systemctl ${e.action} ${e.service} on ${l}${ne.reset}`),!await
|
|
302
|
-
${f}`}}else{let{stdout:l,stderr:u,exitCode:d,error:f}=await
|
|
296
|
+
`));let x=4,R=g.split(`
|
|
297
|
+
`),k=[],_=0;for(;_<R.length;){let b=_+1;for(;b<R.length&&R[b]===R[_];)b++;let A=b-_;if(k.push(R[_]),A>x)k.push(`... (${A-1} identical lines omitted)`);else for(let M=1;M<A;M++)k.push(R[_]);_=b}return k.join(`
|
|
298
|
+
`)||"(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=vt(e.server)}catch(i){return`ERROR: ${i.message}`}let s=o.user?`${o.user}@${o.host}`:o.host;if(console.log(`
|
|
299
|
+
${ne.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${s}:${e.remote_path}${ne.reset}`),!await Rt(" Upload to remote server?"))return"CANCELLED: User declined upload.";try{return await Yw(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=vt(e.server)}catch(s){return`ERROR: ${s.message}`}try{return await zw(o,e.remote_path,e.local_path)}catch(s){return`ERROR: ${s.message}`}}case"remote_agent":{let o=require("path").join(process.cwd(),".nex","servers.json"),s=null;try{s=JSON.parse(require("fs").readFileSync(o,"utf-8"))[e.server]||null}catch{}let r=s?`${s.user||"root"}@${s.host}`:e.server,i=s?.key?["-i",s.key]:[],c=e.project_path||s?.home||"~",l=e.model||"",d=["TMPFILE=$(mktemp /tmp/nexcode-XXXXXX.txt)",`echo "${Buffer.from(e.task).toString("base64")}" | base64 -d > "$TMPFILE"`,`cd "${c}" 2>/dev/null || true`,l?`nex-code --prompt-file "$TMPFILE" --auto --model "${l}" 2>&1`:'nex-code --prompt-file "$TMPFILE" --auto 2>&1',"EXIT_CODE=$?",'rm -f "$TMPFILE"',"exit $EXIT_CODE"].join(" && "),{spawnSync:f}=require("child_process"),m=f("ssh",[...i,"-o","StrictHostKeyChecking=no","-o","ConnectTimeout=10",r,`bash -c '${d}'`],{encoding:"utf-8",maxBuffer:10*1024*1024,timeout:3e5});if(m.error)return`ERROR: SSH connection failed: ${m.error.message}`;let h=(m.stdout||"")+(m.stderr||"");return m.status!==0?`Remote nex-code exited with code ${m.status}.
|
|
300
|
+
${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 s=!e.server||e.server==="local"||e.server==="localhost",r=e.action==="status",i=null;if(!s)try{i=vt(e.server)}catch(l){return`ERROR: ${l.message}`}if(!r){let l=s?"local machine":i.user?`${i.user}@${i.host}`:i.host;if(console.log(`
|
|
301
|
+
${ne.yellow} \u26A0 Service: systemctl ${e.action} ${e.service} on ${l}${ne.reset}`),!await Rt(" Execute?"))return"CANCELLED: User declined service action."}let c=`systemctl ${e.action} ${e.service}`;if(s){let u=e.action!=="status"?`sudo ${c}`:c;try{let{stdout:d,stderr:f}=await Se(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}
|
|
302
|
+
${f}`}}else{let{stdout:l,stderr:u,exitCode:d,error:f}=await lt(i,c,{timeout:15e3,sudo:!0}),m=[l,u].filter(Boolean).join(`
|
|
303
303
|
`).trim();return d!==0?/not found|loaded.*not-found/i.test(m)?`ERROR: Service "${e.service}" not found on ${i.host}. Check: ssh_exec to run "systemctl list-units --type=service"`:`EXIT ${d}
|
|
304
304
|
${f||m||"(no output)"}`:m||`systemctl ${e.action} ${e.service}: OK`}}case"service_logs":{if(!e.service)return"ERROR: service is required";let o=!e.server||e.server==="local"||e.server==="localhost",s=e.lines||50,r=e.since?`--since "${e.since}"`:"",i=e.follow?"-f":"",c=`journalctl -u ${e.service} -n ${s} ${r} ${i} --no-pager`.trim().replace(/\s+/g," ");if(o)try{let{stdout:p,stderr:g}=await Se(c,{timeout:15e3});return(p||g||"(no log output)").trim()}catch(p){return`EXIT ${p.code||1}
|
|
305
|
-
${(p.stderr||p.message||"").toString().trim()}`}let l;try{l=
|
|
305
|
+
${(p.stderr||p.message||"").toString().trim()}`}let l;try{l=vt(e.server)}catch(p){return`ERROR: ${p.message}`}let{stdout:u,stderr:d,exitCode:f,error:m}=await lt(l,c,{timeout:2e4}),h=[u,d].filter(Boolean).join(`
|
|
306
306
|
`).trim();return f!==0?`EXIT ${f}
|
|
307
307
|
${m||h||"(no output)"}`:h||"(no log output)"}case"container_list":{let o=!e.server||e.server==="local"||e.server==="localhost",r=`docker ps ${e.all?"-a":""} --format "table {{.ID}}\\t{{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}"`.trim().replace(/\s+/g," ");if(o)try{let{stdout:m,stderr:h}=await Se(r,{timeout:1e4});return(m||h||"(no containers)").trim()}catch(m){return`EXIT ${m.code||1}
|
|
308
|
-
${(m.stderr||m.message||"").toString().trim()}`}let i;try{i=
|
|
308
|
+
${(m.stderr||m.message||"").toString().trim()}`}let i;try{i=vt(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:c,stderr:l,exitCode:u,error:d}=await lt(i,r,{timeout:15e3}),f=[c,l].filter(Boolean).join(`
|
|
309
309
|
`).trim();return u!==0?`EXIT ${u}
|
|
310
310
|
${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",s=e.lines||50,r=e.since?`--since "${e.since}"`:"",i=`docker logs --tail ${s} ${r} ${e.container} 2>&1`.trim().replace(/\s+/g," ");if(o)try{let{stdout:h,stderr:p}=await Se(i,{timeout:15e3});return(h||p||"(no log output)").trim()}catch(h){return`EXIT ${h.code||1}
|
|
311
|
-
${(h.stderr||h.message||"").toString().trim()}`}let c;try{c=
|
|
311
|
+
${(h.stderr||h.message||"").toString().trim()}`}let c;try{c=vt(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:l,stderr:u,exitCode:d,error:f}=await lt(c,i,{timeout:2e4}),m=[l,u].filter(Boolean).join(`
|
|
312
312
|
`).trim();return d!==0?`EXIT ${d}
|
|
313
313
|
${f||m}`:m||"(no log output)"}case"container_exec":{if(!e.container)return"ERROR: container is required";if(!e.command)return"ERROR: command is required";let o=!e.server||e.server==="local"||e.server==="localhost",s=/^(cat|ls|echo|env|printenv|df|du|ps|id|whoami|uname|hostname|date|pwd|which|find\s|head\s|tail\s|grep\s|curl\s+-[A-Za-z]*G|curl\s+https?:\/\/[^\s]+$)/;if(!n.autoConfirm&&!s.test(e.command.trim())){let p=o?"local":e.server;if(console.log(`
|
|
314
|
-
${ne.yellow} \u26A0 docker exec in ${e.container} on ${p}: ${e.command}${ne.reset}`),!await
|
|
315
|
-
${(p.stderr||p.message||"").toString().trim()}`}let l;try{l=
|
|
314
|
+
${ne.yellow} \u26A0 docker exec in ${e.container} on ${p}: ${e.command}${ne.reset}`),!await Rt(" Execute?"))return"CANCELLED: User declined."}let i=(e.container||"").replace(/[^a-zA-Z0-9._\/-]/g,"");if(!i)return"ERROR: Invalid container name";let c=`docker exec ${i} sh -c ${JSON.stringify(e.command)}`;if(o)try{let{stdout:p,stderr:g}=await Se(c,{timeout:3e4});return(p||g||"(no output)").trim()}catch(p){return`EXIT ${p.code||1}
|
|
315
|
+
${(p.stderr||p.message||"").toString().trim()}`}let l;try{l=vt(e.server)}catch(p){return`ERROR: ${p.message}`}let{stdout:u,stderr:d,exitCode:f,error:m}=await lt(l,c,{timeout:35e3}),h=[u,d].filter(Boolean).join(`
|
|
316
316
|
`).trim();return f!==0?`EXIT ${f}
|
|
317
317
|
${m||h}`:h||"(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 s=!e.server||e.server==="local"||e.server==="localhost";if(!(e.action==="inspect")&&!n.autoConfirm){let p=s?"local":e.server;if(console.log(`
|
|
318
|
-
${ne.yellow} \u26A0 docker ${e.action} ${e.container} on ${p}${ne.reset}`),!await
|
|
319
|
-
${(p.stderr||p.message||"").toString().trim()}`}let l;try{l=
|
|
318
|
+
${ne.yellow} \u26A0 docker ${e.action} ${e.container} on ${p}${ne.reset}`),!await Rt(" 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(s)try{let{stdout:p,stderr:g}=await Se(c,{timeout:3e4});return(p||g||`docker ${e.action} ${e.container}: OK`).trim()}catch(p){return`EXIT ${p.code||1}
|
|
319
|
+
${(p.stderr||p.message||"").toString().trim()}`}let l;try{l=vt(e.server)}catch(p){return`ERROR: ${p.message}`}let{stdout:u,stderr:d,exitCode:f,error:m}=await lt(l,c,{timeout:35e3}),h=[u,d].filter(Boolean).join(`
|
|
320
320
|
`).trim();return f!==0?`EXIT ${f}
|
|
321
|
-
${m||h}`:h||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...
|
|
321
|
+
${m||h}`:h||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...Xw(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 s;try{s=vt(e.server)}catch(d){return`ERROR: ${d.message}`}let r=s.user?`${s.user}@${s.host}`:s.host;if(!e.dry_run&&!n.autoConfirm){if(o==="git"){let f=e.branch?` (branch: ${e.branch})`:"";console.log(`
|
|
322
322
|
${ne.yellow} \u26A0 Deploy [git pull]: ${r}:${e.remote_path}${f}${ne.reset}`)}else{let f=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`;console.log(`
|
|
323
|
-
${ne.yellow} \u26A0 Deploy [rsync]: ${f} \u2192 ${r}:${e.remote_path}${ne.reset}`)}if(e.deploy_script&&console.log(`${ne.yellow} Then run: ${e.deploy_script}${ne.reset}`),e.health_check&&console.log(`${ne.yellow} Health check: ${e.health_check}${ne.reset}`),!await
|
|
323
|
+
${ne.yellow} \u26A0 Deploy [rsync]: ${f} \u2192 ${r}:${e.remote_path}${ne.reset}`)}if(e.deploy_script&&console.log(`${ne.yellow} Then run: ${e.deploy_script}${ne.reset}`),e.health_check&&console.log(`${ne.yellow} Health check: ${e.health_check}${ne.reset}`),!await Rt(" Proceed with deployment?"))return"CANCELLED: User declined."}let i="";if(o==="git"){let d=(e.branch||"").replace(/[^a-zA-Z0-9._\/-]/g,"");if(e.branch&&d!==e.branch)return`ERROR: Invalid branch name: ${e.branch}`;let f=(e.remote_path||"").replace(/'/g,"'\\''"),m=d?`cd '${f}' && git fetch origin && git checkout '${d}' && git pull origin '${d}'`:`cd '${f}' && git pull`;if(e.dry_run)return`DRY RUN [git]: would run on ${r}:
|
|
324
324
|
${m}${e.deploy_script?`
|
|
325
|
-
${e.deploy_script}`:""}`;let{stdout:h,stderr:p,exitCode:g,error:y}=await
|
|
325
|
+
${e.deploy_script}`:""}`;let{stdout:h,stderr:p,exitCode:g,error:y}=await lt(s,m,{timeout:12e4});if(i=[h,p].filter(Boolean).join(`
|
|
326
326
|
`).trim(),g!==0)return`ERROR (git pull, exit ${g}):
|
|
327
327
|
${y||i}`}else{let d=s.key?`-e "ssh -i ${s.key.replace(/^~/,require("os").homedir())}${s.port&&Number(s.port)!==22?` -p ${s.port}`:""}"`:s.port&&Number(s.port)!==22?`-e "ssh -p ${s.port}"`:"",f=(e.exclude||[]).map(g=>`--exclude="${g}"`).join(" "),m=e.dry_run?"--dry-run":"",h=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`,p=`rsync -avz --delete ${m} ${f} ${d} ${h} ${r}:${e.remote_path}`.trim().replace(/\s+/g," ");try{let{stdout:g,stderr:y}=await Se(p,{timeout:12e4});i=(g||y||"").trim()}catch(g){return`ERROR (rsync): ${(g.stderr||g.message||"").toString().trim()}`}if(e.dry_run)return`DRY RUN [rsync]:
|
|
328
|
-
${i||"(nothing to sync)"}`}let c="";if(e.deploy_script){let{stdout:d,stderr:f,exitCode:m,error:h}=await
|
|
328
|
+
${i||"(nothing to sync)"}`}let c="";if(e.deploy_script){let{stdout:d,stderr:f,exitCode:m,error:h}=await lt(s,e.deploy_script,{timeout:12e4}),p=[d,f].filter(Boolean).join(`
|
|
329
329
|
`).trim();if(m!==0)return`${o==="git"?"git pull":"rsync"} OK
|
|
330
330
|
|
|
331
331
|
ERROR (deploy_script, exit ${m}):
|
|
@@ -338,50 +338,50 @@ Health check: \u2713 ${d} \u2192 ${h.status}`;else return l=`
|
|
|
338
338
|
|
|
339
339
|
Health check FAILED: ${d} \u2192 HTTP ${h.status}`,(o==="git"?"git pull OK":"rsync OK")+i+c+l}catch(m){return l=`
|
|
340
340
|
|
|
341
|
-
Health check FAILED: ${d} \u2192 ${m.message}`,(o==="git"?"git pull OK":"rsync OK")+i+c+l}else{let{stdout:m,stderr:h,exitCode:p}=await
|
|
341
|
+
Health check FAILED: ${d} \u2192 ${m.message}`,(o==="git"?"git pull OK":"rsync OK")+i+c+l}else{let{stdout:m,stderr:h,exitCode:p}=await lt(s,d,{timeout:15e3}),g=[m,h].filter(Boolean).join(`
|
|
342
342
|
`).trim();if(p!==0)return l=`
|
|
343
343
|
|
|
344
344
|
Health check FAILED (exit ${p}): ${g}`,(o==="git"?"git pull OK":"rsync OK")+i+c+l;l=`
|
|
345
345
|
|
|
346
346
|
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}
|
|
347
|
-
${i}${c}${l}`.trim()}case"deployment_status":{let o=
|
|
347
|
+
${i}${c}${l}`.trim()}case"deployment_status":{let o=Jw(),s=e.config?[e.config]:Object.keys(o);if(s.length===0)return"No deploy configs found. Create .nex/deploy.json to configure deployments.";let r=[];for(let i of s){let c=o[i];if(!c){r.push(`${i}: NOT FOUND`);continue}try{let l=vt(c.server||i),d=(await lt(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 lt(l,`systemctl is-active ${h[1]}`,{timeout:1e4})).stdout.trim()}catch{f="inactive"}}let m="N/A";if(c.health_check){let h=c.health_check.trim();if(/^https?:\/\//.test(h))try{let p=require("node-fetch"),g=await Promise.race([p(h),new Promise((y,w)=>setTimeout(()=>w(new Error("timeout")),1e4))]);m=g.ok?"healthy":`HTTP ${g.status}`}catch(p){m=`unhealthy: ${p.message.substring(0,50)}`}else try{m=(await lt(l,h,{timeout:1e4})).exitCode===0?"healthy":"unhealthy"}catch{m="unhealthy"}}r.push(`${i}: server=${d?"reachable":"unreachable"} service=${f} health=${m}`)}catch(l){r.push(`${i}: ERROR \u2014 ${l.message}`)}}return`Deployment Status:
|
|
348
348
|
${r.join(`
|
|
349
|
-
`)}`}case"frontend_recon":{let o=process.cwd(),s=(e.type||"").toLowerCase(),r=[],i=async(
|
|
350
|
-
`),
|
|
351
|
-
`);return
|
|
352
|
-
... (${
|
|
353
|
-
`).filter(Boolean)}catch{return[]}},d=async(
|
|
349
|
+
`)}`}case"frontend_recon":{let o=process.cwd(),s=(e.type||"").toLowerCase(),r=[],i=async(k,_=120)=>{try{let b=ke.isAbsolute(k)?k:ke.join(o,k),M=(await De.readFile(b,"utf8")).split(`
|
|
350
|
+
`),O=M.slice(0,_).join(`
|
|
351
|
+
`);return M.length>_?O+`
|
|
352
|
+
... (${M.length-_} more lines \u2014 use read_file for full content)`:O}catch{return null}},l=["node_modules",".git","dist","build","vendor",".next","__pycache__","venv",".venv"].map(k=>`-not -path "*/${k}/*"`).join(" "),u=async k=>{try{let{stdout:_}=await Se(`find "${o}" -type f -name "${k}" ${l} 2>/dev/null | head -10`,{timeout:8e3});return _.trim().split(`
|
|
353
|
+
`).filter(Boolean)}catch{return[]}},d=async(k,_)=>{try{let{stdout:b}=await Se(`grep -rl "${k}" "${o}" --include="${_}" --exclude-dir=node_modules --exclude-dir=.git --exclude-dir=dist --exclude-dir=build 2>/dev/null | head -5`,{timeout:8e3});return b.trim().split(`
|
|
354
354
|
`).filter(Boolean)}catch{return[]}};r.push(`## STEP 1: Design Tokens
|
|
355
|
-
`);let f=[...await u("tailwind.config.js"),...await u("tailwind.config.ts"),...await u("tailwind.config.mjs")];if(f.length>0){let
|
|
355
|
+
`);let f=[...await u("tailwind.config.js"),...await u("tailwind.config.ts"),...await u("tailwind.config.mjs")];if(f.length>0){let k=await i(f[0],80);k&&r.push(`### Tailwind config (${ke.relative(o,f[0])})
|
|
356
356
|
\`\`\`js
|
|
357
|
-
${
|
|
358
|
-
\`\`\``)}else r.push("(no tailwind.config found)");let m=["variables.css","_variables.scss","tokens.css","base.css","global.css","main.css","index.css","app.css","style.css","styles.css"],h=!1;for(let
|
|
357
|
+
${k}
|
|
358
|
+
\`\`\``)}else r.push("(no tailwind.config found)");let m=["variables.css","_variables.scss","tokens.css","base.css","global.css","main.css","index.css","app.css","style.css","styles.css"],h=!1;for(let k of m){let _=await u(k);for(let b of _){let A=await i(b,100);if(A&&A.includes(":root")){r.push(`### CSS Variables (${ke.relative(o,b)})
|
|
359
359
|
\`\`\`css
|
|
360
|
-
${
|
|
361
|
-
\`\`\``),h=!0;break}}if(h)break}if(!h){let
|
|
360
|
+
${A}
|
|
361
|
+
\`\`\``),h=!0;break}}if(h)break}if(!h){let k=await d(":root","*.css");if(k.length>0){let _=await i(k[0],100);_&&r.push(`### CSS Variables (${ke.relative(o,k[0])})
|
|
362
362
|
\`\`\`css
|
|
363
363
|
${_}
|
|
364
364
|
\`\`\``),h=!0}}h||r.push("(no CSS custom properties / :root found)"),r.push(`
|
|
365
365
|
## STEP 2: Main Layout / Index Page
|
|
366
|
-
`);let p=["base.html","_base.html","layout.html","base.jinja","App.vue","App.jsx","App.tsx","_app.jsx","_app.tsx","_app.js","layout.vue","index.html"],g=!1;for(let
|
|
366
|
+
`);let p=["base.html","_base.html","layout.html","base.jinja","App.vue","App.jsx","App.tsx","_app.jsx","_app.tsx","_app.js","layout.vue","index.html"],g=!1;for(let k of p){let _=await u(k);if(_.length>0){let b=await i(_[0],150);if(b){r.push(`### Main layout: ${ke.relative(o,_[0])}
|
|
367
367
|
\`\`\`html
|
|
368
368
|
${b}
|
|
369
369
|
\`\`\``),g=!0;break}}}g||r.push("(no main layout/index file found \u2014 try read_file on your root template manually)"),r.push(`
|
|
370
370
|
## STEP 3: Reference Component (same type)
|
|
371
|
-
`);let y=[];if(s){for(let
|
|
372
|
-
`).filter(Boolean)}catch{y=[]}if(y.length>0){let
|
|
371
|
+
`);let y=[];if(s){for(let k of["*.html","*.vue","*.jsx","*.tsx"])if(y=await d(s,k),y.length>0)break}if(y.length===0)try{let{stdout:k}=await Se(`find "${o}" -type f \\( -name "*.html" -o -name "*.vue" -o -name "*.jsx" -o -name "*.tsx" \\) -not -path "*/node_modules/*" -not -path "*/.git/*" -not -path "*/dist/*" -not -path "*/build/*" -not -name "base.html" -not -name "_base.html" -not -name "layout.html" -not -name "App.vue" -not -name "App.jsx" 2>/dev/null | head -20`,{timeout:8e3});y=k.trim().split(`
|
|
372
|
+
`).filter(Boolean)}catch{y=[]}if(y.length>0){let k=y[0],_=await i(k,150);_?r.push(`### Reference: ${ke.relative(o,k)}
|
|
373
373
|
\`\`\`html
|
|
374
374
|
${_}
|
|
375
375
|
\`\`\``):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(`
|
|
376
376
|
## STEP 4: Framework Stack
|
|
377
|
-
`);let w=[],
|
|
377
|
+
`);let w=[],x=await i(ke.join(o,"package.json"),999);if(x){if((x.includes('"react"')||x.includes("'react'"))&&w.push("React"),x.includes('"vue"')||x.includes("'vue'")){let _=x.match(/"vue":\s*"[\^~]?(\d+)/);w.push(_?`Vue.js v${_[1]}`:"Vue.js")}let k=x.match(/"alpinejs":\s*"[\^~]?(\d+)/);k&&w.push(`Alpine.js v${k[1]} (\u26A0 v2 vs v3 API differs!)`),(x.includes('"htmx')||x.includes("'htmx"))&&w.push("HTMX"),x.includes('"tailwindcss"')&&w.push("Tailwind CSS"),x.includes('"bootstrap"')&&w.push("Bootstrap")}if((await gt(ke.join(o,"manage.py"))||(await i(ke.join(o,"requirements.txt"),50)||"").includes("Django"))&&w.push("Django (server-rendered templates)"),!w.some(k=>k.includes("Alpine"))){let k=await d("alpinejs","*.html");if(k.length>0){let b=(await i(k[0],30)||"").match(/alpinejs[@/]v?(\d)/);w.push(b?`Alpine.js v${b[1]} (via CDN \u2014 \u26A0 v2 vs v3 API differs!)`:"Alpine.js (via CDN \u2014 check version!)")}}return w.some(k=>k.includes("HTMX"))||(await d("htmx","*.html")).length>0&&w.push("HTMX (via CDN)"),w.length>0?(r.push(w.map(k=>`- ${k}`).join(`
|
|
378
378
|
`)),r.push(`
|
|
379
379
|
\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(`
|
|
380
380
|
---
|
|
381
381
|
\u2705 Design recon complete. Now build consistently with the patterns above.`),r.join(`
|
|
382
|
-
`)}case"sysadmin":{if(!e.action)return"ERROR: action is required";let o=!e.server||e.server==="local"||e.server==="localhost",s;if(!o)try{s=
|
|
382
|
+
`)}case"sysadmin":{if(!e.action)return"ERROR: action is required";let o=!e.server||e.server==="local"||e.server==="localhost",s;if(!o)try{s=vt(e.server)}catch(l){return`ERROR: ${l.message}`}let r=async(l,u=3e4)=>{if(o)try{let{stdout:d,stderr:f}=await Se(l,{timeout:u});return{out:(d||f||"").trim(),exitCode:0}}catch(d){return{out:(d.stderr||d.message||"").toString().trim(),exitCode:d.code||1}}else{let{stdout:d,stderr:f,exitCode:m,error:h}=await lt(s,l,{timeout:u}),p=[d,f].filter(Boolean).join(`
|
|
383
383
|
`).trim();return{out:h&&m!==0&&!d.trim()?(h+`
|
|
384
|
-
`+p).trim():p,exitCode:m}}};if(!(["audit","disk_usage","process_list","network_status","ssl_check","log_tail","find_large","journalctl"].includes(e.action)||e.action==="package"&&e.package_action==="list"||e.action==="user_manage"&&["list","info"].includes(e.user_action)||e.action==="firewall"&&e.firewall_action==="status"||e.action==="cron"&&e.cron_action==="list"||e.action==="service"&&["status","list_failed"].includes(e.service_action))&&!n.autoConfirm){let l=o?"local":e.server;if(!await
|
|
384
|
+
`+p).trim():p,exitCode:m}}};if(!(["audit","disk_usage","process_list","network_status","ssl_check","log_tail","find_large","journalctl"].includes(e.action)||e.action==="package"&&e.package_action==="list"||e.action==="user_manage"&&["list","info"].includes(e.user_action)||e.action==="firewall"&&e.firewall_action==="status"||e.action==="cron"&&e.cron_action==="list"||e.action==="service"&&["status","list_failed"].includes(e.service_action))&&!n.autoConfirm){let l=o?"local":e.server;if(!await Rt(`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}
|
|
385
385
|
(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}
|
|
386
386
|
${d}`:d}case"process_list":{let l=e.sort_by==="mem"?"4":"3",u=(e.limit||20)+1,d=`ps aux --sort=-${e.sort_by==="mem"?"%mem":"%cpu"} 2>/dev/null | head -${u} || ps aux | awk 'NR==1{print; next} {print | "sort -k${l} -rn"}' | head -${u}`,{out:f,exitCode:m}=await r(d,15e3);return m!==0?`EXIT ${m}
|
|
387
387
|
${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}
|
|
@@ -423,8 +423,8 @@ ${d}`:d||"(empty log)"}case"find_large":{let l=e.path||"/",u=e.limit||20,d=e.min
|
|
|
423
423
|
${m}`:m||`(no files larger than ${d} in ${l})`}case"service":{if(!e.service_action)return"ERROR: service_action is required for action=service";if(e.service_action!=="list_failed"&&!e.service_name)return"ERROR: service_name is required (except for list_failed)";let l=e.service_name?e.service_name.includes(".")?e.service_name:`${e.service_name}.service`:"",u;switch(e.service_action){case"status":u=`systemctl status ${l} --no-pager -l 2>&1 | head -40`;break;case"list_failed":u="systemctl list-units --state=failed --no-legend 2>/dev/null";break;case"start":u=`systemctl start ${l} && systemctl status ${l} --no-pager -l 2>&1 | head -20`;break;case"stop":u=`systemctl stop ${l} && echo "${l} stopped"`;break;case"restart":u=`systemctl restart ${l} && systemctl status ${l} --no-pager -l 2>&1 | head -20`;break;case"reload":u=`systemctl reload ${l} 2>&1 || systemctl reload-or-restart ${l} 2>&1`;break;case"enable":u=`systemctl enable ${l} && echo "${l} enabled"`;break;case"disable":u=`systemctl disable ${l} && echo "${l} disabled"`;break;default:return`ERROR: Unknown service_action: ${e.service_action}`}let{out:d,exitCode:f}=await r(u,3e4);return f===0||e.service_action==="status"&&f===3?d||`service ${e.service_action} OK`:`EXIT ${f}
|
|
424
424
|
${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}
|
|
425
425
|
${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}
|
|
426
|
-
${d}`:d||"(no log entries)"}default:return`ERROR: Unknown sysadmin action: ${e.action}`}}default:{let{executePluginTool:o}=
|
|
427
|
-
`)}function
|
|
426
|
+
${d}`:d||"(no log entries)"}default:return`ERROR: Unknown sysadmin action: ${e.action}`}}default:{let{executePluginTool:o}=Fo(),s=await o(t,e,n);return s!==null?s:`ERROR: Unknown tool: ${t}`}}}async function r0(t,e,n={}){let{emit:o}=Fo(),{logToolExecution:s}=ua(),r=Date.now(),i=n.silent?null:Bw(t,e);if(!i){let l=await qd(t,e,n);return s({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 Ww(i);c.start();try{let l=await qd(t,e,n);return c.stop(),s({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(),s({tool:t,args:e,result:l.message,duration:Date.now()-r,success:!1}),l}}Wd.exports={TOOL_DEFINITIONS:o0,executeTool:r0,resolvePath:ut,autoFixPath:ar,autoFixEdit:Ud,enrichBashError:Fd,cancelPendingAskUser:t0,setAskUserHandler:n0,fileExists:gt}});var Tt=G((Kv,Hd)=>{Hd.exports=Bd()});var $a=G((Yv,Gd)=>{var{loadServerProfiles:cr}=Jn(),ga={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 i0(){let t=cr();if(Object.keys(t).length===0)return null;let n=["## Remote Servers (.nex/servers.json)"];n.push(""),n.push("Available server profiles (use with ssh_exec, ssh_upload, ssh_download, service_manage, service_logs, container_list, container_logs, container_exec, container_manage, deploy):");for(let[s,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":"";n.push(`- **${s}**: ${i}${c}${l}${u}`)}let o=new Set;for(let s of Object.values(t))s.os&&ga[s.os]&&o.add(s.os);if(o.size>0){n.push("");for(let s of o){let r={almalinux9:"AlmaLinux 9",almalinux8:"AlmaLinux 8",ubuntu:"Ubuntu",debian:"Debian",macos:"macOS"}[s]||s;n.push(`### ${r} Notes`);for(let i of ga[s])n.push(`- ${i}`)}}return n.join(`
|
|
427
|
+
`)}function a0(t){let e=cr();return Object.values(e).some(n=>n.os&&n.os.startsWith(t))}function c0(){return Object.keys(cr())}function l0(){let t=require("fs"),n=require("path").join(process.cwd(),"NEX.md"),o="";try{o=t.readFileSync(n,"utf-8")}catch{}let s=cr(),r=Object.keys(s);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(m=>c.includes(m)))return null;let u=r.map(m=>{let h=s[m],p=h.user?`${h.user}@${h.host}`:h.host,g=h.port&&Number(h.port)!==22?`:${h.port}`:"";return` - **${m}**: ${p}${g}${h.os?` (${h.os})`:""}`}).join(`
|
|
428
428
|
`),d=r.map(m=>s[m].log_path).filter(Boolean),f=d.length>0?`
|
|
429
429
|
- Server log paths: ${d.join(", ")}`:"";return`# Deployment Context (Auto-detected)
|
|
430
430
|
|
|
@@ -442,36 +442,36 @@ ${u}
|
|
|
442
442
|
- \u274C Do NOT \`read_file\` on paths like \`logs/\` \u2014 these files do not exist locally
|
|
443
443
|
- \u274C Do NOT \`list_directory\` on server paths \u2014 the local project is the source, not the running instance
|
|
444
444
|
|
|
445
|
-
**When in doubt:** If a path contains \`logs/\`, \`/var/log/\`, or \`/home/<user>/\` \u2014 it is on the server. SSH there.`}
|
|
446
|
-
`).map(n=>n.trim()).filter(n=>n&&!n.startsWith("#")&&!n.startsWith("!")).map(n=>n.replace(/\/$/,""))}catch{return[]}}function
|
|
447
|
-
`)}var
|
|
445
|
+
**When in doubt:** If a path contains \`logs/\`, \`/var/log/\`, or \`/home/<user>/\` \u2014 it is on the server. SSH there.`}Gd.exports={getServerContext:i0,getDeploymentContextBlock:l0,hasServerOS:a0,getProfileNames:c0,OS_HINTS:ga}});var dr=G((zv,zd)=>{var Ct=require("fs").promises,Kd=require("fs"),tt=require("path"),lr=require("util").promisify(require("child_process").exec),{C:Zn}=Me(),{getMergeConflicts:Yd}=nn(),{getServerContext:u0}=$a(),d0=new Set(["node_modules",".git",".svn","dist","build","coverage",".nyc_output","__pycache__",".DS_Store",".next",".nuxt",".turbo",".cache","vendor","tmp","temp"]);function f0(t){try{return Kd.readFileSync(t,"utf-8").split(`
|
|
446
|
+
`).map(n=>n.trim()).filter(n=>n&&!n.startsWith("#")&&!n.startsWith("!")).map(n=>n.replace(/\/$/,""))}catch{return[]}}function p0(t,e){for(let n of e)if(n===t||n.includes("*")&&new RegExp("^"+n.replace(/\./g,"\\.").replace(/\*/g,".*")+"$").test(t))return!0;return!1}function m0(t,{maxDepth:e=3,maxFiles:n=200,giPatterns:o=[]}={}){let s=tt.join(t,".gitignore"),r=[...o,...f0(s)],i=0,c=[tt.basename(t)+"/"];function l(u,d,f){if(f>e||i>=n)return;let m;try{m=Kd.readdirSync(u,{withFileTypes:!0})}catch{return}m.sort((p,g)=>p.isDirectory()!==g.isDirectory()?p.isDirectory()?-1:1:p.name.localeCompare(g.name));let h=m.filter(p=>!(d0.has(p.name)||p.name.startsWith(".")&&p.name!==".env.example"||p0(p.name,r)));for(let p=0;p<h.length;p++){if(i>=n){c.push(`${d}\u2514\u2500\u2500 \u2026 (truncated)`);break}let g=h[p],y=p===h.length-1,w=y?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",x=d+(y?" ":"\u2502 "),R=g.isDirectory()?g.name+"/":g.name;c.push(`${d}${w}${R}`),i++,g.isDirectory()&&l(tt.join(u,g.name),x,f+1)}}return l(t,"",1),c.join(`
|
|
447
|
+
`)}var ya=new Map,es=new Map,ur=null,h0=3e4;async function on(t){try{return await t()}catch{return null}}async function g0(){if(!ur||Date.now()>ur)return!1;let t=[tt.join(process.cwd(),"package.json"),tt.join(process.cwd(),"README.md"),tt.join(process.cwd(),".gitignore")];for(let e of t)try{let n=await Ct.stat(e),o=es.get(e);if(!o||n.mtimeMs!==o)return!1}catch{if(es.has(e))return!1}try{let e=tt.join(process.cwd(),".git","HEAD"),n=await Ct.stat(e),o=es.get(e);if(!o||n.mtimeMs!==o)return!1}catch{}return!0}async function $0(){let t=[tt.join(process.cwd(),"package.json"),tt.join(process.cwd(),"README.md"),tt.join(process.cwd(),".gitignore"),tt.join(process.cwd(),".git","HEAD")];for(let e of t)try{let n=await Ct.stat(e);es.set(e,n.mtimeMs)}catch{es.delete(e)}}async function y0(t){let e="fileContext",n=ya.get(e),o=!1;if(n&&await g0()&&(o=!0),!o){let u=[],d=tt.join(t,"package.json");if(await on(()=>Ct.access(d).then(()=>!0).catch(()=>!1)))try{let y=await Ct.readFile(d,"utf-8"),w=JSON.parse(y),x={name:w.name,version:w.version};w.scripts&&(x.scripts=Object.keys(w.scripts).slice(0,15)),w.dependencies&&(x.deps=Object.keys(w.dependencies).length),w.devDependencies&&(x.devDeps=Object.keys(w.devDependencies).length),u.push(`PACKAGE: ${JSON.stringify(x)}`)}catch{}let m=tt.join(t,"README.md");if(await on(()=>Ct.access(m).then(()=>!0).catch(()=>!1))){let w=(await Ct.readFile(m,"utf-8")).split(`
|
|
448
448
|
`).slice(0,50);u.push(`README (first 50 lines):
|
|
449
449
|
${w.join(`
|
|
450
|
-
`)}`)}let p=
|
|
450
|
+
`)}`)}let p=tt.join(t,".gitignore");if(await on(()=>Ct.access(p).then(()=>!0).catch(()=>!1))){let y=await Ct.readFile(p,"utf-8");u.push(`GITIGNORE:
|
|
451
451
|
${y.trim()}`)}n=u.join(`
|
|
452
452
|
|
|
453
|
-
`),
|
|
453
|
+
`),ya.set(e,n),ur=Date.now()+h0,await $0()}let s=[n],[r,i,c,l]=await Promise.all([on(async()=>{let{stdout:u}=await lr("git branch --show-current",{cwd:t,timeout:5e3});return u.trim()}),on(async()=>{let{stdout:u}=await lr("git status --short",{cwd:t,timeout:5e3});return u.trim()}),on(async()=>{let{stdout:u}=await lr("git log --oneline -5",{cwd:t,timeout:5e3});return u.trim()}),Yd()]);if(r&&s.push(`GIT BRANCH: ${r}`),i&&s.push(`GIT STATUS:
|
|
454
454
|
${i}`),c&&s.push(`RECENT COMMITS:
|
|
455
455
|
${c}`),l&&l.length>0){let u=l.map(d=>` ${d.file}`).join(`
|
|
456
456
|
`);s.push(`MERGE CONFLICTS (resolve before editing these files):
|
|
457
|
-
${u}`)}try{let u=
|
|
457
|
+
${u}`)}try{let u=u0();u&&s.push(u)}catch{}return s.join(`
|
|
458
458
|
|
|
459
|
-
`)}async function r0(t){let e=et.join(t,"package.json"),n="";if(await sn(()=>Rt.access(e).then(()=>!0).catch(()=>!1)))try{let i=await Rt.readFile(e,"utf-8"),c=JSON.parse(i);n=`${c.name||"?"} v${c.version||"?"}`}catch{}let[s,r]=await Promise.all([sn(async()=>{let{stdout:i}=await tr("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),jd()]);if(r&&r.length>0){console.log(`${Xn.red} \u26A0 ${r.length} unresolved merge conflict(s):${Xn.reset}`);for(let i of r)console.log(`${Xn.red} ${i.file}${Xn.reset}`);console.log(`${Xn.yellow} \u2192 Resolve conflicts before starting tasks${Xn.reset}`)}console.log()}qd.exports={gatherProjectContext:o0,printContext:r0,generateFileTree:e0,_clearContextCache:()=>{aa.clear(),Jn.clear(),nr=null}}});var At=G((Pv,Wd)=>{var Ct=require("fs"),or=require("path"),{atomicWrite:i0}=Zt();function Ds(){return or.join(process.cwd(),".nex","sessions")}function ca(){let t=Ds();Ct.existsSync(t)||Ct.mkdirSync(t,{recursive:!0})}function la(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return or.join(Ds(),`${e}.json`)}function ua(t,e,n={}){ca();let o=la(t),s={name:t,createdAt:n.createdAt||new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:e.length,model:n.model||null,provider:n.provider||null,messages:e};return i0(o,JSON.stringify(s,null,2)),{path:o,name:t}}function Fd(t){let e=la(t);if(!Ct.existsSync(e))return null;try{return JSON.parse(Ct.readFileSync(e,"utf-8"))}catch{return null}}function Ud(){ca();let t=Ds(),e=Ct.readdirSync(t).filter(o=>o.endsWith(".json")),n=[];for(let o of e)try{let s=JSON.parse(Ct.readFileSync(or.join(t,o),"utf-8"));n.push({name:s.name||o.replace(".json",""),createdAt:s.createdAt,updatedAt:s.updatedAt,messageCount:s.messageCount||0,model:s.model,provider:s.provider,score:s.score!=null?s.score:null,scoreGrade:s.scoreGrade||null})}catch{}return n.sort((o,s)=>(s.updatedAt||"").localeCompare(o.updatedAt||""))}function a0(t){let e=la(t);return Ct.existsSync(e)?(Ct.unlinkSync(e),!0):!1}function c0(){let t=Ud();return t.length===0?null:Fd(t[0].name)}var xn=null,Kt=null,Ls=null;function l0(t,e={}){t.length!==0&&(xn&&clearTimeout(xn),Kt=t,Ls=e||{},xn=setTimeout(()=>{Kt&&Kt.length>0&&ua("_autosave",Kt,Ls),xn=null,Kt=null,Ls=null},5e3))}function u0(){xn&&(clearTimeout(xn),xn=null),Kt&&Kt.length>0&&(ua("_autosave",Kt,Ls),Kt=null,Ls=null)}function d0(){ca();let t=Ds(),e=Ct.readdirSync(t).filter(r=>r.endsWith(".json")),n=new Date,o=new Date(n.getTime()-720*60*60*1e3),s=0;for(let r of e){let i=or.join(t,r);try{let c=Ct.statSync(i);new Date(c.mtime)<o&&(Ct.unlinkSync(i),s++)}catch{}}return s}Wd.exports={saveSession:ua,loadSession:Fd,listSessions:Ud,deleteSession:a0,getLastSession:c0,autoSave:l0,flushAutoSave:u0,clearOldSessions:d0,_getSessionsDir:Ds}});var rr=G((Iv,Jd)=>{"use strict";var js=require("fs"),Bd=require("path");function Hd(t){let e=[];return t.forEach((n,o)=>{n.role==="assistant"&&(Array.isArray(n.content)&&n.content.forEach(s=>{s&&s.type==="tool_use"&&e.push({name:s.name||"",input:s.input||{},index:o})}),Array.isArray(n.tool_calls)&&n.tool_calls.forEach(s=>{let r=s.function?.name||s.name||"",i={};try{i=typeof s.function?.arguments=="string"?JSON.parse(s.function.arguments):s.function?.arguments||s.input||{}}catch{}e.push({name:r,input:i,index:o})}))}),e}function Gd(t){let e=[];return t.forEach((n,o)=>{if(n.role==="user"&&Array.isArray(n.content)&&n.content.forEach(s=>{if(s&&s.type==="tool_result"){let r=typeof s.content=="string"?s.content:Array.isArray(s.content)?s.content.map(i=>typeof i=="string"?i:i.text||"").join(""):JSON.stringify(s.content||"");e.push({content:r,index:o})}}),n.role==="tool"){let s=typeof n.content=="string"?n.content:JSON.stringify(n.content||"");e.push({content:s,index:o})}}),e}function Kd(t){for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role==="assistant"){if(typeof n.content=="string")return n.content.trim();if(Array.isArray(n.content)){let o=n.content.filter(s=>s&&(s.type==="text"||typeof s=="string")).map(s=>typeof s=="string"?s:s.text||"").join("").trim();if(o)return o}}}return""}function Yd(t,e){let n=[];for(let o=t.length-1;o>=0&&n.length<e;o--){let s=t[o];if(s.role!=="assistant")continue;let r="";typeof s.content=="string"?r=s.content.trim():Array.isArray(s.content)&&(r=s.content.filter(i=>i&&(i.type==="text"||typeof i=="string")).map(i=>typeof i=="string"?i:i.text||"").join("").trim()),r&&n.push(r)}return n}function zd(t){let e=new Map;for(let n of t){let o;try{o=JSON.stringify(n.input)}catch{o=String(n.input)}let s=`${n.name}|${o}`;e.set(s,(e.get(s)||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,n=[],o=Hd(t),s=Gd(t),r=o.length;t.some(S=>S.role==="user"&&typeof S.content=="string"&&S.content.startsWith("[SYSTEM WARNING]")&&(S.content.includes("edited")||S.content.includes("bash command")||S.content.includes("grep pattern")||S.content.includes("re-read")||S.content.includes("already in your context")))&&(e-=2,n.push("Loop-warning was fired during session (repeated file edits, bash commands, or re-reads)"));let c=o.find(S=>{let M=S.input?.command||S.input?.cmd||"";return/\bsed\s+-n\b/.test(M)});if(c){let S=(c.input?.command||c.input?.cmd||"").slice(0,80);e-=1.5,n.push(`sed -n anti-pattern used: ${S}`)}o.find(S=>{if(S.name!=="grep"&&S.name!=="bash"&&S.name!=="ssh_exec")return!1;let M=S.input?.command||S.input?.cmd||"",U=S.input?.pattern||"",K=`${M} ${U}`;return/(?:-[CAB]|--context|--after|--before)\s*[=\s]?([2-9][1-9]|\d{3,})/.test(K)||/grep.*-[CAB]\s*([2-9][1-9]|\d{3,})/.test(K)})&&(e-=1,n.push("grep used with >20 context lines (context flood risk)"));let u=t.some(S=>S.role==="assistant"),d=Kd(t),m=Yd(t,3).some(S=>S.length>100&&!/^[^.!]{0,40}\?$/.test(S));if(u&&!m&&(d.length<80||/^[^.!]{0,40}\?$/.test(d))){e-=2;let S=d.length>0?`"${d.slice(0,60)}..."`:"(no assistant text found)";n.push(`Session ends without diagnosis \u2014 last response too short or is only a question: ${S}`)}r>40?(e-=1.5,n.push(`Excessive tool calls: ${r} (>40 threshold)`)):r>25&&(e-=.5,n.push(`High tool call count: ${r} (>25 threshold)`)),t.some(S=>{let M=typeof S.content=="string"?S.content:Array.isArray(S.content)?S.content.map(U=>typeof U=="string"?U:U.text||"").join(""):"";return/\[auto-compressed|context compacted|force-compressed/.test(M)})&&(e-=.5,n.push("Auto-compress triggered (context flood indicator)"));let g=zd(o),y=0,w="";for(let[S,M]of g)M>y&&(y=M,w=S);if(y>=3){let[S]=w.split("|");e-=1,n.push(`Same tool call repeated ${y}\xD7 (tool: ${S})`)}let k=!1;for(let S of s)if(S.content&&S.content.includes('"valid":true')&&o.filter(U=>U.index>S.index).length>0){k=!0;break}k&&(e-=1.5,n.push('Stop-trigger ignored: tool result contained "valid":true but session continued with more tool calls'));let R=o.filter(S=>S.name==="ssh_exec");if(R.length>=8){let S=0,M=1;for(let U=1;U<R.length;U++)R[U].index<=R[U-1].index+2?M++:(S=Math.max(S,M),M=1);S=Math.max(S,M),S>=8&&(e-=.5,n.push(`SSH reconnect storm: ${S} consecutive SSH calls`))}let x=new Map;for(let S of o)if(S.name==="read_file"&&S.input?.path){let M=S.input.path;x.has(M)||x.set(M,{count:0,ranges:[]});let U=x.get(M);if(U.count++,S.input.line_start!=null){let K=S.input.line_start||1,se=S.input.line_end||K+350;U.ranges.push([K,se])}}function _(S,M,U){for(let[K,se]of U){let I=Math.max(S,K),W=Math.min(M,se);if(W>I){let oe=W-I,V=M-S||1;if(oe/V>=.7)return!0}}return!1}let b=0,O="";for(let[S,M]of x){if(M.count<3)continue;if(M.ranges.length===M.count){let K=!1,se=[];for(let[I,W]of M.ranges){if(se.length>0&&_(I,W,se)){K=!0;break}se.push([I,W])}if(!K)continue}M.count>b&&(b=M.count,O=S)}if(b>=3){e-=1;let S=O.split("/").slice(-2).join("/");n.push(`read_file loop: "${S}" read ${b}\xD7 (file already in context)`)}let N=0,C="";for(let[S,M]of x){if(M.ranges.length<4)continue;let U=[],K=!1;for(let[se,I]of M.ranges){if(U.length>0&&_(se,I,U)){K=!0;break}U.push([se,I])}!K&&M.ranges.length>N&&(N=M.ranges.length,C=S)}if(N>=4){e-=.5;let S=C.split("/").slice(-2).join("/");n.push(`File-scroll pattern: "${S}" read in ${N} sequential sections \u2014 use grep instead`)}let L=new Map;for(let S of o)if(S.name==="grep"&&S.input?.path&&S.input?.pattern){let M=S.input.path;L.has(M)||L.set(M,new Set),L.get(M).add(S.input.pattern)}let Ee=0,me="";for(let[S,M]of L)M.size>Ee&&(Ee=M.size,me=S);if(Ee>=3){e-=.75;let S=me.split("/").slice(-2).join("/");n.push(`grep flood on single file: "${S}" searched ${Ee}\xD7 with different patterns (file already in context)`)}{let S=new Set,M=new Set,U=/^(test_|demo_|temp_|tmp_|scratch_)/;for(let se of o){if(se.name==="write_file"&&se.input?.path){let I=se.input.path.split("/").pop(),W=se.input.path.includes("/tests/");U.test(I)&&!W&&S.add(se.input.path)}if((se.name==="bash"||se.name==="ssh_exec")&&se.input?.command){let I=se.input.command.match(/\brm\s+(?:-\w+\s+)?(\S+)/g);if(I)for(let W of I){let oe=W.split(/\s+/),V=oe[oe.length-1];for(let Z of S)(Z.endsWith(V)||V.endsWith(Z.split("/").pop()))&&M.add(Z)}}}let K=M.size;if(K>=1){let se=Math.min(K*.25,.5);e-=se;let I=[...M].map(W=>W.split("/").pop()).join(", ");n.push(`Temp file write-then-delete: ${I} \u2014 write inline logic or use tests/ instead`)}}let ae=s.filter(S=>S.content.startsWith("EXIT")).length;ae>=10?(e-=1,n.push(`Bash exit-error storm: ${ae} tool results started with EXIT (repeated failing commands)`)):ae>=5&&(e-=.5,n.push(`Repeated bash errors: ${ae} tool results with non-zero exit code`));for(let S of t){if(S.role!=="assistant")continue;let M="";if(typeof S.content=="string"?M=S.content:Array.isArray(S.content)&&(M=S.content.filter(V=>V&&(V.type==="text"||typeof V=="string")).map(V=>typeof V=="string"?V:V.text||"").join("")),M.length<=5e3)continue;let U=M.split(/(?<=\. )/).filter(V=>V.trim().length>0);if(U.length<6)continue;let K=new Map;for(let V=0;V<=U.length-3;V++){let Z=U.slice(V,V+3).join("").trim();Z.length>30&&K.set(Z,(K.get(Z)||0)+1)}let se=0,I="";for(let[V,Z]of K)Z>se&&(se=Z,I=V);if(se<3)continue;let oe=I.length*se/M.length;if(oe>=.4||se>=10){e-=1.5,n.push(`llm output loop: assistant message repeated content detected (${se}\xD7 same paragraph, ${Math.round(oe*100)}% repeated)`);break}}{let S=new Set(["read_file","list_directory","search_files","glob","grep"]),M=t.some(K=>Array.isArray(K.tool_calls)?K.tool_calls.some(se=>S.has(se.function?.name)):Array.isArray(K.content)?K.content.some(se=>se.type==="tool_use"&&S.has(se.name)):!1);t.some(K=>K.role==="assistant"&&typeof K.content=="string"&&(K.content.includes("## Steps")||K.content.includes("/plan approve")))&&!M&&(e-=2,n.push("plan written without reading any files \u2014 LLM invented data structures from training knowledge (hallucination risk)"))}let le=s.filter(S=>S.content.startsWith("BLOCKED:"));if(le.length>0){let S=Math.min(le.length*.5,1.5);e-=S,n.push(`${le.length} tool call${le.length===1?"":"s"} blocked (agent attempted denied actions)`)}let ee=t.filter(S=>{let M=typeof S.content=="string"?S.content:"";return/\[SYSTEM WARNING\] Context wiped \d+×/.test(M)}).length;if(ee>0){let S=Math.min(ee*1,2);e-=S,n.push(`Super-nuclear context wipe fired ${ee}\xD7 (context collapse \u2014 task too large or read loops)`)}{let S=!1,M=!1,U=!1;for(let se of o){if(se.name!=="bash")continue;let I=(se.input?.command||se.input?.cmd||"").trim();!(/cat\s*>/.test(I)||/<</.test(I))&&/\bcat\s+\S/.test(I)&&(S=!0),/^\s*ls(\s|$)/.test(I)&&!/npm|yarn|pnpm|make|git\b/.test(I)&&(M=!0),/\bfind\s+\S/.test(I)&&!/git\b|npm\b|-exec\b/.test(I)&&(U=!0)}let K=[S,M,U].filter(Boolean).length;if(K>0){let se=Math.min(K*.25,.75);e-=se;let I=[];S&&I.push("cat (use read_file)"),M&&I.push("ls (use list_directory)"),U&&I.push("find (use glob)"),n.push(`bash used instead of dedicated tool: ${I.join(", ")}`)}}e=Math.max(0,Math.min(10,e)),e=Math.round(e*10)/10;let pe=e>=9?"A":e>=8?"B":e>=7?"C":e>=6?"D":"F",X=n.length===0?`Clean session \u2014 no quality issues detected (${r} tool calls)`:`${n.length} issue${n.length===1?"":"s"} found \u2014 ${r} tool calls`;return{score:e,grade:pe,issues:n,summary:X}}function f0(t){try{let{loadSession:e}=At(),n=e(t);return n?Xd(n.messages||[]):null}catch{return null}}function p0(t,e=null){let{score:n,grade:o,issues:s,summary:r}=t,i=e?.dim||"",c=e?.reset||"",l=e?.green||"",u=e?.yellow||"",d=e?.red||"",f=e?.cyan||"",m=e?.bold||"",h=n>=8?l:n>=6?u:d,p=`
|
|
459
|
+
`)}async function w0(t){let e=tt.join(t,"package.json"),n="";if(await on(()=>Ct.access(e).then(()=>!0).catch(()=>!1)))try{let i=await Ct.readFile(e,"utf-8"),c=JSON.parse(i);n=`${c.name||"?"} v${c.version||"?"}`}catch{}let[s,r]=await Promise.all([on(async()=>{let{stdout:i}=await lr("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),Yd()]);if(r&&r.length>0){console.log(`${Zn.red} \u26A0 ${r.length} unresolved merge conflict(s):${Zn.reset}`);for(let i of r)console.log(`${Zn.red} ${i.file}${Zn.reset}`);console.log(`${Zn.yellow} \u2192 Resolve conflicts before starting tasks${Zn.reset}`)}console.log()}zd.exports={gatherProjectContext:y0,printContext:w0,generateFileTree:m0,_clearContextCache:()=>{ya.clear(),es.clear(),ur=null}}});var Ot=G((Xv,Vd)=>{var At=require("fs"),fr=require("path"),{atomicWrite:b0}=en();function Hs(){return fr.join(process.cwd(),".nex","sessions")}function wa(){let t=Hs();At.existsSync(t)||At.mkdirSync(t,{recursive:!0})}function ba(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return fr.join(Hs(),`${e}.json`)}function _a(t,e,n={}){wa();let o=ba(t),s={name:t,createdAt:n.createdAt||new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:e.length,model:n.model||null,provider:n.provider||null,messages:e};return b0(o,JSON.stringify(s,null,2)),{path:o,name:t}}function Xd(t){let e=ba(t);if(!At.existsSync(e))return null;try{return JSON.parse(At.readFileSync(e,"utf-8"))}catch{return null}}function Jd(){wa();let t=Hs(),e=At.readdirSync(t).filter(o=>o.endsWith(".json")),n=[];for(let o of e)try{let s=JSON.parse(At.readFileSync(fr.join(t,o),"utf-8"));n.push({name:s.name||o.replace(".json",""),createdAt:s.createdAt,updatedAt:s.updatedAt,messageCount:s.messageCount||0,model:s.model,provider:s.provider,score:s.score!=null?s.score:null,scoreGrade:s.scoreGrade||null})}catch{}return n.sort((o,s)=>(s.updatedAt||"").localeCompare(o.updatedAt||""))}function _0(t){let e=ba(t);return At.existsSync(e)?(At.unlinkSync(e),!0):!1}function x0(){let t=Jd();return t.length===0?null:Xd(t[0].name)}var vn=null,zt=null,Bs=null;function k0(t,e={}){t.length!==0&&(vn&&clearTimeout(vn),zt=t,Bs=e||{},vn=setTimeout(()=>{zt&&zt.length>0&&_a("_autosave",zt,Bs),vn=null,zt=null,Bs=null},5e3))}function v0(){vn&&(clearTimeout(vn),vn=null),zt&&zt.length>0&&(_a("_autosave",zt,Bs),zt=null,Bs=null)}function S0(){wa();let t=Hs(),e=At.readdirSync(t).filter(r=>r.endsWith(".json")),n=new Date,o=new Date(n.getTime()-720*60*60*1e3),s=0;for(let r of e){let i=fr.join(t,r);try{let c=At.statSync(i);new Date(c.mtime)<o&&(At.unlinkSync(i),s++)}catch{}}return s}Vd.exports={saveSession:_a,loadSession:Xd,listSessions:Jd,deleteSession:_0,getLastSession:x0,autoSave:k0,flushAutoSave:v0,clearOldSessions:S0,_getSessionsDir:Hs}});var pr=G((Jv,rf)=>{"use strict";var Gs=require("fs"),Qd=require("path");function Zd(t){let e=[];return t.forEach((n,o)=>{n.role==="assistant"&&(Array.isArray(n.content)&&n.content.forEach(s=>{s&&s.type==="tool_use"&&e.push({name:s.name||"",input:s.input||{},index:o})}),Array.isArray(n.tool_calls)&&n.tool_calls.forEach(s=>{let r=s.function?.name||s.name||"",i={};try{i=typeof s.function?.arguments=="string"?JSON.parse(s.function.arguments):s.function?.arguments||s.input||{}}catch{}e.push({name:r,input:i,index:o})}))}),e}function ef(t){let e=[];return t.forEach((n,o)=>{if(n.role==="user"&&Array.isArray(n.content)&&n.content.forEach(s=>{if(s&&s.type==="tool_result"){let r=typeof s.content=="string"?s.content:Array.isArray(s.content)?s.content.map(i=>typeof i=="string"?i:i.text||"").join(""):JSON.stringify(s.content||"");e.push({content:r,index:o})}}),n.role==="tool"){let s=typeof n.content=="string"?n.content:JSON.stringify(n.content||"");e.push({content:s,index:o})}}),e}function tf(t){for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role==="assistant"){if(typeof n.content=="string")return n.content.trim();if(Array.isArray(n.content)){let o=n.content.filter(s=>s&&(s.type==="text"||typeof s=="string")).map(s=>typeof s=="string"?s:s.text||"").join("").trim();if(o)return o}}}return""}function nf(t,e){let n=[];for(let o=t.length-1;o>=0&&n.length<e;o--){let s=t[o];if(s.role!=="assistant")continue;let r="";typeof s.content=="string"?r=s.content.trim():Array.isArray(s.content)&&(r=s.content.filter(i=>i&&(i.type==="text"||typeof i=="string")).map(i=>typeof i=="string"?i:i.text||"").join("").trim()),r&&n.push(r)}return n}function sf(t){let e=new Map;for(let n of t){let o;try{o=JSON.stringify(n.input)}catch{o=String(n.input)}let s=`${n.name}|${o}`;e.set(s,(e.get(s)||0)+1)}return e}function of(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,n=[],o=Zd(t),s=ef(t),r=o.length;t.some(E=>E.role==="user"&&typeof E.content=="string"&&E.content.startsWith("[SYSTEM WARNING]")&&(E.content.includes("edited")||E.content.includes("bash command")||E.content.includes("grep pattern")||E.content.includes("re-read")||E.content.includes("already in your context")))&&(e-=2,n.push("Loop-warning was fired during session (repeated file edits, bash commands, or re-reads)"));let c=o.find(E=>{let P=E.input?.command||E.input?.cmd||"";return/\bsed\s+-n\b/.test(P)});if(c){let E=(c.input?.command||c.input?.cmd||"").slice(0,80);e-=1.5,n.push(`sed -n anti-pattern used: ${E}`)}o.find(E=>{if(E.name!=="grep"&&E.name!=="bash"&&E.name!=="ssh_exec")return!1;let P=E.input?.command||E.input?.cmd||"",F=E.input?.pattern||"",K=`${P} ${F}`;return/(?:-[CAB]|--context|--after|--before)\s*[=\s]?([2-9][1-9]|\d{3,})/.test(K)||/grep.*-[CAB]\s*([2-9][1-9]|\d{3,})/.test(K)})&&(e-=1,n.push("grep used with >20 context lines (context flood risk)"));let u=t.some(E=>E.role==="assistant"),d=tf(t),m=nf(t,3).some(E=>E.length>100&&!/^[^.!]{0,40}\?$/.test(E));if(u&&!m&&(d.length<80||/^[^.!]{0,40}\?$/.test(d))){e-=2;let E=d.length>0?`"${d.slice(0,60)}..."`:"(no assistant text found)";n.push(`Session ends without diagnosis \u2014 last response too short or is only a question: ${E}`)}r>40?(e-=1.5,n.push(`Excessive tool calls: ${r} (>40 threshold)`)):r>25&&(e-=.5,n.push(`High tool call count: ${r} (>25 threshold)`)),t.some(E=>{let P=typeof E.content=="string"?E.content:Array.isArray(E.content)?E.content.map(F=>typeof F=="string"?F:F.text||"").join(""):"";return/\[auto-compressed|context compacted|force-compressed/.test(P)})&&(e-=.5,n.push("Auto-compress triggered (context flood indicator)"));let g=sf(o),y=0,w="";for(let[E,P]of g)P>y&&(y=P,w=E);if(y>=3){let[E]=w.split("|");e-=1,n.push(`Same tool call repeated ${y}\xD7 (tool: ${E})`)}let x=!1;for(let E of s)if(E.content&&E.content.includes('"valid":true')&&o.filter(F=>F.index>E.index).length>0){x=!0;break}x&&(e-=1.5,n.push('Stop-trigger ignored: tool result contained "valid":true but session continued with more tool calls'));let R=o.filter(E=>E.name==="ssh_exec");if(R.length>=8){let E=0,P=1;for(let F=1;F<R.length;F++)R[F].index<=R[F-1].index+2?P++:(E=Math.max(E,P),P=1);E=Math.max(E,P),E>=8&&(e-=.5,n.push(`SSH reconnect storm: ${E} consecutive SSH calls`))}let k=new Map;for(let E of o)if(E.name==="read_file"&&E.input?.path){let P=E.input.path;k.has(P)||k.set(P,{count:0,ranges:[]});let F=k.get(P);if(F.count++,E.input.line_start!=null){let K=E.input.line_start||1,oe=E.input.line_end||K+350;F.ranges.push([K,oe])}}function _(E,P,F){for(let[K,oe]of F){let L=Math.max(E,K),U=Math.min(P,oe);if(U>L){let re=U-L,ee=P-E||1;if(re/ee>=.7)return!0}}return!1}let b=0,A="";for(let[E,P]of k){if(P.count<3)continue;if(P.ranges.length===P.count){let K=!1,oe=[];for(let[L,U]of P.ranges){if(oe.length>0&&_(L,U,oe)){K=!0;break}oe.push([L,U])}if(!K)continue}P.count>b&&(b=P.count,A=E)}if(b>=3){e-=1;let E=A.split("/").slice(-2).join("/");n.push(`read_file loop: "${E}" read ${b}\xD7 (file already in context)`)}let M=0,O="";for(let[E,P]of k){if(P.ranges.length<4)continue;let F=[],K=!1;for(let[oe,L]of P.ranges){if(F.length>0&&_(oe,L,F)){K=!0;break}F.push([oe,L])}!K&&P.ranges.length>M&&(M=P.ranges.length,O=E)}if(M>=4){e-=.5;let E=O.split("/").slice(-2).join("/");n.push(`File-scroll pattern: "${E}" read in ${M} sequential sections \u2014 use grep instead`)}let N=new Map;for(let E of o)if(E.name==="grep"&&E.input?.path&&E.input?.pattern){let P=E.input.path;N.has(P)||N.set(P,new Set),N.get(P).add(E.input.pattern)}let he=0,ge="";for(let[E,P]of N)P.size>he&&(he=P.size,ge=E);if(he>=3){e-=.75;let E=ge.split("/").slice(-2).join("/");n.push(`grep flood on single file: "${E}" searched ${he}\xD7 with different patterns (file already in context)`)}{let E=new Set,P=new Set,F=/^(test_|demo_|temp_|tmp_|scratch_)/;for(let oe of o){if(oe.name==="write_file"&&oe.input?.path){let L=oe.input.path.split("/").pop(),U=oe.input.path.includes("/tests/");F.test(L)&&!U&&E.add(oe.input.path)}if((oe.name==="bash"||oe.name==="ssh_exec")&&oe.input?.command){let L=oe.input.command.match(/\brm\s+(?:-\w+\s+)?(\S+)/g);if(L)for(let U of L){let re=U.split(/\s+/),ee=re[re.length-1];for(let te of E)(te.endsWith(ee)||ee.endsWith(te.split("/").pop()))&&P.add(te)}}}let K=P.size;if(K>=1){let oe=Math.min(K*.25,.5);e-=oe;let L=[...P].map(U=>U.split("/").pop()).join(", ");n.push(`Temp file write-then-delete: ${L} \u2014 write inline logic or use tests/ instead`)}}let ce=s.filter(E=>E.content.startsWith("EXIT")).length;ce>=10?(e-=1,n.push(`Bash exit-error storm: ${ce} tool results started with EXIT (repeated failing commands)`)):ce>=5&&(e-=.5,n.push(`Repeated bash errors: ${ce} tool results with non-zero exit code`));for(let E of t){if(E.role!=="assistant")continue;let P="";if(typeof E.content=="string"?P=E.content:Array.isArray(E.content)&&(P=E.content.filter(ee=>ee&&(ee.type==="text"||typeof ee=="string")).map(ee=>typeof ee=="string"?ee:ee.text||"").join("")),P.length<=5e3)continue;let F=P.split(/(?<=\. )/).filter(ee=>ee.trim().length>0);if(F.length<6)continue;let K=new Map;for(let ee=0;ee<=F.length-3;ee++){let te=F.slice(ee,ee+3).join("").trim();te.length>30&&K.set(te,(K.get(te)||0)+1)}let oe=0,L="";for(let[ee,te]of K)te>oe&&(oe=te,L=ee);if(oe<3)continue;let re=L.length*oe/P.length;if(re>=.4||oe>=10){e-=1.5,n.push(`llm output loop: assistant message repeated content detected (${oe}\xD7 same paragraph, ${Math.round(re*100)}% repeated)`);break}}{let E=new Set(["read_file","list_directory","search_files","glob","grep"]),P=t.some(K=>Array.isArray(K.tool_calls)?K.tool_calls.some(oe=>E.has(oe.function?.name)):Array.isArray(K.content)?K.content.some(oe=>oe.type==="tool_use"&&E.has(oe.name)):!1);t.some(K=>K.role==="assistant"&&typeof K.content=="string"&&(K.content.includes("## Steps")||K.content.includes("/plan approve")))&&!P&&(e-=2,n.push("plan written without reading any files \u2014 LLM invented data structures from training knowledge (hallucination risk)"))}let ue=s.filter(E=>E.content.startsWith("BLOCKED:"));if(ue.length>0){let E=Math.min(ue.length*.5,1.5);e-=E,n.push(`${ue.length} tool call${ue.length===1?"":"s"} blocked (agent attempted denied actions)`)}let Z=t.filter(E=>{let P=typeof E.content=="string"?E.content:"";return/\[SYSTEM WARNING\] Context wiped \d+×/.test(P)}).length;if(Z>0){let E=Math.min(Z*1,2);e-=E,n.push(`Super-nuclear context wipe fired ${Z}\xD7 (context collapse \u2014 task too large or read loops)`)}{let E=!1,P=!1,F=!1;for(let oe of o){if(oe.name!=="bash")continue;let L=(oe.input?.command||oe.input?.cmd||"").trim();!(/cat\s*>/.test(L)||/<</.test(L))&&/\bcat\s+\S/.test(L)&&(E=!0),/^\s*ls(\s|$)/.test(L)&&!/npm|yarn|pnpm|make|git\b/.test(L)&&(P=!0),/\bfind\s+\S/.test(L)&&!/git\b|npm\b|-exec\b/.test(L)&&(F=!0)}let K=[E,P,F].filter(Boolean).length;if(K>0){let oe=Math.min(K*.25,.75);e-=oe;let L=[];E&&L.push("cat (use read_file)"),P&&L.push("ls (use list_directory)"),F&&L.push("find (use glob)"),n.push(`bash used instead of dedicated tool: ${L.join(", ")}`)}}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",X=n.length===0?`Clean session \u2014 no quality issues detected (${r} tool calls)`:`${n.length} issue${n.length===1?"":"s"} found \u2014 ${r} tool calls`;return{score:e,grade:de,issues:n,summary:X}}function E0(t){try{let{loadSession:e}=Ot(),n=e(t);return n?of(n.messages||[]):null}catch{return null}}function T0(t,e=null){let{score:n,grade:o,issues:s,summary:r}=t,i=e?.dim||"",c=e?.reset||"",l=e?.green||"",u=e?.yellow||"",d=e?.red||"",f=e?.cyan||"",m=e?.bold||"",h=n>=8?l:n>=6?u:d,p=`
|
|
460
460
|
${i} Session score: ${c}${m}${h}${n}/10 (${o})${c}`;if(r&&(p+=` ${i}${r}${c}`),s.length>0)for(let g of s)p+=`
|
|
461
|
-
${u}\u26A0${c} ${i}${g}${c}`;return p}function
|
|
462
|
-
${e}`);let n=
|
|
463
|
-
${n}`);let o=
|
|
461
|
+
${u}\u26A0${c} ${i}${g}${c}`;return p}function R0(t,e={}){try{let n=Qd.join(process.cwd(),".nex");Gs.existsSync(n)||Gs.mkdirSync(n,{recursive:!0});let o=Qd.join(n,"benchmark-history.json"),s=[];if(Gs.existsSync(o))try{s=JSON.parse(Gs.readFileSync(o,"utf-8"))}catch{s=[]}Array.isArray(s)||(s=[]);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:[]};s.push(i),s.length>100&&(s=s.slice(s.length-100)),Gs.writeFileSync(o,JSON.stringify(s,null,2))}catch{}}rf.exports={scoreMessages:of,scoreSession:E0,formatScore:T0,appendScoreHistory:R0,_extractToolCalls:Zd,_extractToolResults:ef,_getLastAssistantText:tf,_getLastNAssistantTexts:nf,_countDuplicateToolCalls:sf}});var an=G((Vv,pf)=>{var rn=require("fs"),mr=require("path"),C0=require("os"),{atomicWrite:A0,withFileLockSync:af}=en();function xa(){return mr.join(process.cwd(),".nex","memory")}function Ks(){return mr.join(xa(),"memory.json")}function O0(){return mr.join(process.cwd(),"NEX.md")}function cf(){return mr.join(C0.homedir(),".nex","NEX.md")}function ka(){let t=xa();rn.existsSync(t)||rn.mkdirSync(t,{recursive:!0})}function hr(){let t=Ks();if(!rn.existsSync(t))return{};try{return JSON.parse(rn.readFileSync(t,"utf-8"))}catch{return{}}}function lf(t){ka(),A0(Ks(),JSON.stringify(t,null,2))}function N0(t,e){ka(),af(Ks(),()=>{let n=hr();n[t]={value:e,updatedAt:new Date().toISOString()},lf(n)})}function M0(t){let e=hr();return e[t]?e[t].value:null}function P0(t){return ka(),af(Ks(),()=>{let e=hr();return t in e?(delete e[t],lf(e),!0):!1})}function uf(){let t=hr();return Object.entries(t).map(([e,n])=>({key:e,value:n.value,updatedAt:n.updatedAt}))}function df(){let t=cf();if(!rn.existsSync(t))return"";try{return rn.readFileSync(t,"utf-8").trim()}catch{return""}}function ff(){let t=O0();if(!rn.existsSync(t))return"";try{return rn.readFileSync(t,"utf-8").trim()}catch{return""}}function I0(){let t=[],e=df();e&&t.push(`GLOBAL INSTRUCTIONS (~/.nex/NEX.md):
|
|
462
|
+
${e}`);let n=ff();n&&t.push(`PROJECT INSTRUCTIONS (NEX.md):
|
|
463
|
+
${n}`);let o=uf();if(o.length>0){let s=o.map(r=>` ${r.key}: ${r.value}`).join(`
|
|
464
464
|
`);t.push(`PROJECT MEMORY:
|
|
465
465
|
${s}`)}return t.join(`
|
|
466
466
|
|
|
467
|
-
`)}
|
|
467
|
+
`)}pf.exports={remember:N0,recall:M0,forget:P0,listMemories:uf,loadGlobalInstructions:df,loadProjectInstructions:ff,getMemoryContext:I0,_getMemoryDir:xa,_getMemoryFile:Ks,_getGlobalNexMdPath:cf}});var zs=G((Zv,yf)=>{var $t=require("fs"),ts=require("path"),{C:Qv}=Me(),{atomicWrite:L0,withFileLockSync:D0}=en(),gr={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"},ns={...gr};function mf(){let t=ts.join(process.cwd(),".nex","config.json");if($t.existsSync(t))try{let e=JSON.parse($t.readFileSync(t,"utf-8"));e.permissions&&(ns={...gr,...e.permissions})}catch{}}function j0(){let t=ts.join(process.cwd(),".nex"),e=ts.join(t,"config.json");$t.existsSync(t)||$t.mkdirSync(t,{recursive:!0}),D0(e,()=>{let n={};if($t.existsSync(e))try{n=JSON.parse($t.readFileSync(e,"utf-8"))}catch{n={}}n.permissions=ns,L0(e,JSON.stringify(n,null,2))})}function hf(t){return ns[t]||"ask"}function q0(t,e){return["allow","ask","deny"].includes(e)?(ns[t]=e,!0):!1}function F0(t){return hf(t)}function U0(){return Object.entries(ns).map(([t,e])=>({tool:t,mode:e}))}function W0(){ns={...gr}}var Ys={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 gf(){let t=ts.join(process.cwd(),".nex","config.json");try{return $t.existsSync(t)&&JSON.parse($t.readFileSync(t,"utf-8")).teamPermissions||null}catch{return null}}function B0(t){let e=ts.join(process.cwd(),".nex"),n=ts.join(e,"config.json");$t.existsSync(e)||$t.mkdirSync(e,{recursive:!0});let o={};try{$t.existsSync(n)&&(o=JSON.parse($t.readFileSync(n,"utf-8")))}catch{o={}}o.teamPermissions=t,$t.writeFileSync(n,JSON.stringify(o,null,2),"utf-8")}function $f(){let t=gf();if(!t)return Ys.admin;let e=t.role||"admin",n=Ys[e]||Ys.admin;return{...n,...t.overrides,blockedTools:[...n.blockedTools||[],...t.overrides?.blockedTools||[]]}}function H0(t){let e=$f();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 G0(){return Object.entries(Ys).map(([t,e])=>({name:t,description:e.description,toolCount:e.allowedTools?`${e.allowedTools.length} allowed`:"all allowed",blockedCount:e.blockedTools.length}))}mf();yf.exports={getPermission:hf,setPermission:q0,checkPermission:F0,listPermissions:U0,loadPermissions:mf,savePermissions:j0,resetPermissions:W0,DEFAULT_PERMISSIONS:gr,PERMISSION_PRESETS:Ys,loadPresetConfig:gf,savePresetConfig:B0,getEffectivePreset:$f,isToolAllowed:H0,listPresets:G0}});var jt=G((tS,kf)=>{var En=require("fs"),$r=require("path"),eS=require("readline"),{C:xe}=Me(),_e=null,Sa=!1,Ea=null,wf=new Set(["read_file","list_directory","search_files","glob","grep","web_search","web_fetch","git_status","git_diff","git_log","git_show"]);function yr(){return $r.join(process.cwd(),".nex","plans")}function bf(){let t=yr();En.existsSync(t)||En.mkdirSync(t,{recursive:!0})}function K0(t,e=[]){return _e={name:`plan-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,task:t,steps:e.map(n=>({description:n.description||n,files:n.files||[],status:"pending"})),status:"draft",createdAt:new Date().toISOString()},_e}function Y0(){return _e}function z0(t){Sa=t}function X0(){return Sa}function J0(){return!_e||_e.status!=="draft"?!1:(_e.status="approved",_e.updatedAt=new Date().toISOString(),!0)}function V0(){return!_e||_e.status!=="approved"?!1:(_e.status="executing",!0)}function va(t,e){return!_e||t<0||t>=_e.steps.length?!1:(_e.steps[t].status=e,_e.updatedAt=new Date().toISOString(),_e.steps.every(n=>n.status==="done"||n.status==="skipped")&&(_e.status="completed"),!0)}function Q0(t){if(!t)return`${xe.dim}No active plan${xe.reset}`;let e={draft:`${xe.yellow}DRAFT${xe.reset}`,approved:`${xe.green}APPROVED${xe.reset}`,executing:`${xe.blue}EXECUTING${xe.reset}`,completed:`${xe.green}COMPLETED${xe.reset}`},n=[];n.push(`
|
|
468
468
|
${xe.bold}${xe.cyan}Plan: ${t.task}${xe.reset}`),n.push(`${xe.dim}Status: ${e[t.status]||t.status}${xe.reset}
|
|
469
469
|
`);for(let o=0;o<t.steps.length;o++){let s=t.steps[o],r;switch(s.status){case"done":r=`${xe.green}\u2713${xe.reset}`;break;case"in_progress":r=`${xe.blue}\u2192${xe.reset}`;break;case"skipped":r=`${xe.dim}\u25CB${xe.reset}`;break;default:r=`${xe.dim} ${xe.reset}`}n.push(` ${r} ${xe.bold}Step ${o+1}:${xe.reset} ${s.description}`),s.files.length>0&&n.push(` ${xe.dim}Files: ${s.files.join(", ")}${xe.reset}`)}return n.push(""),n.join(`
|
|
470
|
-
`)}function
|
|
470
|
+
`)}function Z0(t){if(t||(t=_e),!t)return null;bf();let e=$r.join(yr(),`${t.name}.json`);return En.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function eb(t){let e=$r.join(yr(),`${t}.json`);if(!En.existsSync(e))return null;try{let n=JSON.parse(En.readFileSync(e,"utf-8"));return _e=n,n}catch{return null}}function tb(){bf();let t=yr(),e=En.readdirSync(t).filter(o=>o.endsWith(".json")),n=[];for(let o of e)try{let s=JSON.parse(En.readFileSync($r.join(t,o),"utf-8"));n.push({name:s.name,task:s.task,status:s.status,steps:s.steps?s.steps.length:0,createdAt:s.createdAt})}catch{}return n.sort((o,s)=>(s.createdAt||"").localeCompare(o.createdAt||""))}function nb(t){if(!t)return[];let e=[],n=t.match(/##\s+Steps?\s*\n([\s\S]*?)(?:\n##|\s*$)/i),o=n?n[1]:t,s=/^\s*(\d+)[.)]\s+(.+)/gm,r;for(;(r=s.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 sb(t){Ea=t}function ob(){return Ea}function rb(){_e=null,Sa=!1,Ea=null,lb()}function ib(){return`
|
|
471
471
|
PLAN MODE ACTIVE: You are in analysis-only mode. You MUST NOT execute any changes.
|
|
472
472
|
|
|
473
473
|
# Allowed Tools (read-only)
|
|
474
|
-
You may ONLY use these tools: ${[...
|
|
474
|
+
You may ONLY use these tools: ${[...wf].join(", ")}
|
|
475
475
|
Any other tool call will be blocked and returned with an error.
|
|
476
476
|
|
|
477
477
|
# MANDATORY: Read Before You Plan
|
|
@@ -515,23 +515,23 @@ Bullet list of potential issues and mitigations.
|
|
|
515
515
|
- Order steps by dependency (later steps may depend on earlier ones).
|
|
516
516
|
- After presenting the plan, tell the user to type \`/plan approve\` to proceed.
|
|
517
517
|
- Do NOT make any file changes \u2014 your role is analysis and planning only.
|
|
518
|
-
- Do NOT call ask_user. If anything is ambiguous, add an "## Assumptions" section to the plan and state your assumption. The user approves or rejects the whole plan \u2014 that is the only gate.`}var
|
|
519
|
-
`),n=[],o=!1,s="";for(let r of e){let i=
|
|
520
|
-
`)}function
|
|
518
|
+
- Do NOT call ask_user. If anything is ambiguous, add an "## Assumptions" section to the plan and state your assumption. The user approves or rejects the whole plan \u2014 that is the only gate.`}var Sn=0;function ab(){!_e||_e.status!=="executing"||(Sn>0&&va(Sn-1,"done"),Sn<_e.steps.length&&(va(Sn,"in_progress"),Sn++))}function cb(){if(!_e||_e.status!=="executing"||_e.steps.length===0)return null;let t=Math.min(Sn,_e.steps.length),e=_e.steps.length,n=Math.max(0,t-1),o=_e.steps[n]?.description||"";return{current:t,total:e,description:o}}function lb(){Sn=0}var _f=["interactive","semi-auto","autonomous"],xf="interactive";function ub(t){return _f.includes(t)?(xf=t,!0):!1}function db(){return xf}kf.exports={createPlan:K0,getActivePlan:Y0,setPlanMode:z0,isPlanMode:X0,approvePlan:J0,startExecution:V0,updateStep:va,formatPlan:Q0,savePlan:Z0,loadPlan:eb,listPlans:tb,clearPlan:rb,getPlanModePrompt:ib,setPlanContent:sb,getPlanContent:ob,extractStepsFromText:nb,advancePlanStep:ab,getPlanStepInfo:cb,PLAN_MODE_ALLOWED_TOOLS:wf,setAutonomyLevel:ub,getAutonomyLevel:db,AUTONOMY_LEVELS:_f}});var Pf=G((nS,Mf)=>{var{C:T}=Me();function vf(){return Math.max(10,(process.stdout.columns||80)-2)}function fb(t){if(!t)return"";let e=t.split(`
|
|
519
|
+
`),n=[],o=!1,s="";for(let r of e){let i=vf();if(r.trim().startsWith("```")){if(o)n.push(`${T.dim}${"\u2500".repeat(40)}${T.reset}`),o=!1,s="";else{o=!0,s=r.trim().substring(3).trim();let c=s?` ${s} `:"";n.push(`${T.dim}${"\u2500".repeat(3)}${c}${"\u2500".repeat(Math.max(0,37-c.length))}${T.reset}`)}continue}if(o){n.push(` ${Ra(r,s)}`);continue}if(r.startsWith("### ")){n.push(`${T.bold}${T.cyan} ${Tn(r.substring(4))}${T.reset}`);continue}if(r.startsWith("## ")){n.push(`${T.bold}${T.cyan} ${Tn(r.substring(3))}${T.reset}`);continue}if(r.startsWith("# ")){n.push(`${T.bold}${T.cyan}${Tn(r.substring(2))}${T.reset}`);continue}if(/^\s*[-*]\s/.test(r)){let c=r.match(/^(\s*)/)[1],l=r.replace(/^\s*[-*]\s/,""),u=`${c}${T.cyan}\u2022${T.reset} ${Rn(l)}`;n.push(Cn(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}${T.cyan}${u}.${T.reset} ${Rn(d)}`,m=l+" ".repeat(u.length+2);n.push(Cn(f,i,m));continue}}n.push(Cn(Rn(r),i))}return n.join(`
|
|
520
|
+
`)}function Tn(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function Rn(t){return t?t.replace(/`([^`]+)`/g,`${T.cyan}$1${T.reset}`).replace(/\*\*([^*]+)\*\*/g,`${T.bold}$1${T.reset}`).replace(/\*([^*]+)\*/g,`${T.dim}$1${T.reset}`).replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${T.cyan}$1${T.reset} ${T.dim}($2)${T.reset}`):""}function Ra(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?Sf(t):e==="bash"||e==="sh"||e==="shell"||e==="zsh"?Ef(t):e==="json"||e==="jsonc"?Tf(t):e==="python"||e==="py"?Rf(t):e==="go"||e==="golang"?Cf(t):e==="rust"||e==="rs"?Af(t):e==="css"||e==="scss"||e==="less"?Of(t):e==="html"||e==="xml"||e==="svg"||e==="htm"?Nf(t):t:""}function Sf(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,n=/(["'`])(?:(?=(\\?))\2.)*?\1/g,o=/(\/\/.*$)/,s=/\b(\d+\.?\d*)\b/g,r=t;return r=r.replace(s,`${T.yellow}$1${T.reset}`),r=r.replace(e,`${T.magenta}$1${T.reset}`),r=r.replace(n,`${T.green}$&${T.reset}`),r=r.replace(o,`${T.dim}$1${T.reset}`),r}function Ef(t){let e=/^(\s*)([\w-]+)/,n=/(--?\w[\w-]*)/g,o=/(["'])(?:(?=(\\?))\2.)*?\1/g,s=/(#.*$)/,r=t;return r=r.replace(n,`${T.cyan}$1${T.reset}`),r=r.replace(e,`$1${T.green}$2${T.reset}`),r=r.replace(o,`${T.yellow}$&${T.reset}`),r=r.replace(s,`${T.dim}$1${T.reset}`),r}function Tf(t){let e=/("[\w-]+")\s*:/g,n=/:\s*("(?:[^"\\]|\\.)*")/g,o=/:\s*(\d+\.?\d*)/g,s=/:\s*(true|false|null)/g,r=t;return r=r.replace(e,`${T.cyan}$1${T.reset}:`),r=r.replace(n,`: ${T.green}$1${T.reset}`),r=r.replace(o,`: ${T.yellow}$1${T.reset}`),r=r.replace(s,`: ${T.magenta}$1${T.reset}`),r}function Rf(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,n=/("""[\s\S]*?"""|'''[\s\S]*?'''|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')/g,o=/(#.*$)/,s=/\b(\d+\.?\d*)\b/g,r=/^(\s*@\w+)/,i=t;return i=i.replace(s,`${T.yellow}$1${T.reset}`),i=i.replace(e,`${T.magenta}$1${T.reset}`),i=i.replace(r,`${T.cyan}$1${T.reset}`),i=i.replace(n,`${T.green}$&${T.reset}`),i=i.replace(o,`${T.dim}$1${T.reset}`),i}function Cf(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,n=/\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,s=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,i=t;return i=i.replace(r,`${T.yellow}$1${T.reset}`),i=i.replace(n,`${T.cyan}$1${T.reset}`),i=i.replace(e,`${T.magenta}$1${T.reset}`),i=i.replace(o,`${T.green}$&${T.reset}`),i=i.replace(s,`${T.dim}$1${T.reset}`),i}function Af(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,n=/\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,s=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,i=/\b(\w+!)/g,c=t;return c=c.replace(r,`${T.yellow}$1${T.reset}`),c=c.replace(n,`${T.cyan}$1${T.reset}`),c=c.replace(e,`${T.magenta}$1${T.reset}`),c=c.replace(i,`${T.yellow}$1${T.reset}`),c=c.replace(o,`${T.green}$&${T.reset}`),c=c.replace(s,`${T.dim}$1${T.reset}`),c}function Of(t){let e=/^(\s*)([\w-]+)\s*:/,n=/:\s*([^;]+)/,o=/^(\s*[.#@][\w-]+)/,s=/\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,`${T.yellow}$1${T.reset}`),c=c.replace(s,`${T.yellow}$1${T.reset}`),c=c.replace(e,`$1${T.cyan}$2${T.reset}:`),c=c.replace(o,`$1${T.magenta}$&${T.reset}`),c=c.replace(r,`${T.dim}$1${T.reset}`),c}function Nf(t){let e=/<\/?(\w[\w-]*)/g,n=/\s([\w-]+)=/g,o=/(["'])(?:(?=(\\?))\2.)*?\1/g,s=/(<!--.*?-->)/g,r=/(&\w+;)/g,i=t;return i=i.replace(s,`${T.dim}$1${T.reset}`),i=i.replace(o,`${T.green}$&${T.reset}`),i=i.replace(e,`<${T.magenta}$1${T.reset}`),i=i.replace(n,` ${T.cyan}$1${T.reset}=`),i=i.replace(r,`${T.yellow}$1${T.reset}`),i}function Cn(t,e,n=""){if(!e||e<10)return t;let o="",s=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),s++,s>e&&r!==-1){o+=t.slice(c,r)+`
|
|
521
521
|
`+n,c=r+1,i=c,s=n.length,r=-1;continue}s>e&&r===-1&&(o+=t.slice(c,i)+`
|
|
522
|
-
`+n,c=i,s=n.length+1),i++}return o+=t.slice(c),o}function
|
|
523
|
-
`)}function
|
|
522
|
+
`+n,c=i,s=n.length+1),i++}return o+=t.slice(c),o}function pb(t,e){if(!t||t.length===0)return"";let n=t.map((i,c)=>{let l=e.reduce((u,d)=>Math.max(u,(d[c]||"").length),0);return Math.max(i.length,l)}),o=n.map(i=>"\u2500".repeat(i+2)).join("\u253C"),s=t.map((i,c)=>` ${T.bold}${i.padEnd(n[c])}${T.reset} `).join("\u2502"),r=[];r.push(`${T.dim}\u250C${o.replace(/┼/g,"\u252C")}\u2510${T.reset}`),r.push(`${T.dim}\u2502${T.reset}${s}${T.dim}\u2502${T.reset}`),r.push(`${T.dim}\u251C${o}\u2524${T.reset}`);for(let i of e){let c=t.map((l,u)=>` ${(i[u]||"").padEnd(n[u])} `).join(`${T.dim}\u2502${T.reset}`);r.push(`${T.dim}\u2502${T.reset}${c}${T.dim}\u2502${T.reset}`)}return r.push(`${T.dim}\u2514${o.replace(/┼/g,"\u2534")}\u2518${T.reset}`),r.join(`
|
|
523
|
+
`)}function mb(t,e,n,o=30){let s=n>0?Math.round(e/n*100):0,r=Math.round(s/100*o),i=o-r,c=s>=100?T.green:s>50?T.yellow:T.cyan;return` ${t} ${c}${"\u2588".repeat(r)}${T.dim}${"\u2591".repeat(i)}${T.reset} ${s}% (${e}/${n})`}var Ta=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(n){if(n.code!=="EPIPE")throw n}}_cursorWrite(e){try{process.stderr.write(e)}catch(n){if(n.code!=="EPIPE")throw n}}startCursor(){process.stderr.isTTY&&(this._cursorActive=!0,this._cursorFrame=0,this._cursorWrite("\x1B[?25l"),this._renderCursor(),this._cursorTimer=setInterval(()=>this._renderCursor(),100))}_renderCursor(){let n=[0,1,2,3,4,3,2,1],o=n[this._cursorFrame%n.length],s="";for(let r=0;r<5;r++)s+=r===o?"\x1B[36m\u25CF\x1B[0m":" ";this._cursorWrite(`\x1B[2K\r${s}`),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 n;for(;(n=this.buffer.indexOf(`
|
|
524
524
|
`))!==-1;){let o=this.buffer.substring(0,n);this.buffer=this.buffer.substring(n+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(`${T.dim}${"\u2500".repeat(40)}${T.reset}
|
|
525
|
-
`),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){let n=
|
|
525
|
+
`),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){let n=vf();if(e.trim().startsWith("```")){if(this.inCodeBlock)this._safeWrite(`${T.dim}${"\u2500".repeat(40)}${T.reset}
|
|
526
526
|
`),this.inCodeBlock=!1,this.codeBlockLang="";else{this.inCodeBlock=!0,this.codeBlockLang=e.trim().substring(3).trim();let s=this.codeBlockLang?` ${this.codeBlockLang} `:"";this._safeWrite(`${T.dim}${"\u2500".repeat(3)}${s}${"\u2500".repeat(Math.max(0,37-s.length))}${T.reset}
|
|
527
|
-
`)}return}if(this.inCodeBlock){this._safeWrite(` ${
|
|
528
|
-
`);return}if(e.startsWith("### ")){this._safeWrite(`${T.bold}${T.cyan} ${
|
|
529
|
-
`);return}if(e.startsWith("## ")){this._safeWrite(`${T.bold}${T.cyan} ${
|
|
530
|
-
`);return}if(e.startsWith("# ")){this._safeWrite(`${T.bold}${T.cyan}${
|
|
531
|
-
`);return}if(/^\s*[-*]\s/.test(e)){let s=e.match(/^(\s*)/)[1],r=e.replace(/^\s*[-*]\s/,""),i=`${s}${T.cyan}\u2022${T.reset} ${
|
|
532
|
-
`);return}if(/^\s*\d+\.\s/.test(e)){let s=e.match(/^(\s*)(\d+)\.\s(.*)/);if(s){let r=s[1],i=s[2],c=s[3],l=`${r}${T.cyan}${i}.${T.reset} ${
|
|
533
|
-
`);return}}let o=
|
|
534
|
-
`)}};
|
|
527
|
+
`)}return}if(this.inCodeBlock){this._safeWrite(` ${Ra(e,this.codeBlockLang)}
|
|
528
|
+
`);return}if(e.startsWith("### ")){this._safeWrite(`${T.bold}${T.cyan} ${Tn(e.substring(4))}${T.reset}
|
|
529
|
+
`);return}if(e.startsWith("## ")){this._safeWrite(`${T.bold}${T.cyan} ${Tn(e.substring(3))}${T.reset}
|
|
530
|
+
`);return}if(e.startsWith("# ")){this._safeWrite(`${T.bold}${T.cyan}${Tn(e.substring(2))}${T.reset}
|
|
531
|
+
`);return}if(/^\s*[-*]\s/.test(e)){let s=e.match(/^(\s*)/)[1],r=e.replace(/^\s*[-*]\s/,""),i=`${s}${T.cyan}\u2022${T.reset} ${Rn(r)}`,c=Cn(i,n,s+" ");this._safeWrite(`${c}
|
|
532
|
+
`);return}if(/^\s*\d+\.\s/.test(e)){let s=e.match(/^(\s*)(\d+)\.\s(.*)/);if(s){let r=s[1],i=s[2],c=s[3],l=`${r}${T.cyan}${i}.${T.reset} ${Rn(c)}`,u=r+" ".repeat(i.length+2),d=Cn(l,n,u);this._safeWrite(`${d}
|
|
533
|
+
`);return}}let o=Cn(Rn(e),n);this._safeWrite(`${o}
|
|
534
|
+
`)}};Mf.exports={renderMarkdown:fb,renderInline:Rn,stripHeadingMarkers:Tn,highlightCode:Ra,highlightJS:Sf,highlightBash:Ef,highlightJSON:Tf,highlightPython:Rf,highlightGo:Cf,highlightRust:Af,highlightCSS:Of,highlightHTML:Nf,renderTable:pb,renderProgress:mb,wrapAnsi:Cn,StreamRenderer:Ta}});var Oa=G((sS,jf)=>{var{execSync:hb}=require("child_process"),Ca=require("path"),Xs=require("fs"),Aa=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function If(){return Ca.join(process.cwd(),".nex","hooks")}function gb(){return Ca.join(process.cwd(),".nex","config.json")}function Lf(){let t=gb();if(!Xs.existsSync(t))return{};try{return JSON.parse(Xs.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function wr(t){if(!Aa.includes(t))return[];let e=[],n=If(),o=Ca.join(n,t);Xs.existsSync(o)&&e.push(o);let s=Lf();if(s[t]){let r=Array.isArray(s[t])?s[t]:[s[t]];e.push(...r)}return e}function Df(t,e={},n=3e4){try{return{success:!0,output:hb(t,{cwd:process.cwd(),encoding:"utf-8",timeout:n,env:{...process.env,...e},stdio:["pipe","pipe","pipe"]}).trim()}}catch(o){return{success:!1,error:o.stderr?o.stderr.trim():o.message}}}function $b(t,e={}){let n=wr(t);if(n.length===0)return[];let o={};for(let[r,i]of Object.entries(e))o[`NEX_${r.toUpperCase()}`]=String(i);let s=[];for(let r of n){let i=Df(r,o);if(s.push({command:r,...i}),!i.success&&t.startsWith("pre-"))break}return s}function yb(t){return wr(t).length>0}function wb(){let t=[];for(let e of Aa){let n=wr(e);n.length>0&&t.push({event:e,commands:n})}return t}function bb(){let t=If();return Xs.existsSync(t)||Xs.mkdirSync(t,{recursive:!0}),t}jf.exports={HOOK_EVENTS:Aa,loadHookConfig:Lf,getHooksForEvent:wr,executeHook:Df,runHooks:$b,hasHooks:yb,listHooks:wb,initHooksDir:bb}});var Js=G((iS,Jf)=>{"use strict";var{callWithRetry:qf,runSubAgent:_b,clearAllLocks:xb}=nr(),{parseModelSpec:Ff,getActiveProviderName:oS,getActiveModelId:rS}=Re(),{MultiProgress:kb,C:ae}=Me(),Uf=3,Na=4,Wf="devstral-2:123b",Bf="kimi-k2.5",Hf=`You are a task decomposition engine. Given a complex user request, split it into independent, atomic sub-tasks.
|
|
535
535
|
|
|
536
536
|
RULES:
|
|
537
537
|
- Output ONLY a JSON array, no markdown fences, no explanation.
|
|
@@ -546,7 +546,7 @@ RULES:
|
|
|
546
546
|
- If the request is simple (single goal), return an array with exactly 1 item.
|
|
547
547
|
|
|
548
548
|
USER REQUEST:
|
|
549
|
-
{prompt}`,
|
|
549
|
+
{prompt}`,Gf=`You are a result synthesis engine. Given the results of multiple sub-agents that worked on parts of a larger task, produce a unified summary.
|
|
550
550
|
|
|
551
551
|
RULES:
|
|
552
552
|
- Output ONLY a JSON object with these fields:
|
|
@@ -560,16 +560,16 @@ ORIGINAL REQUEST:
|
|
|
560
560
|
{prompt}
|
|
561
561
|
|
|
562
562
|
SUB-AGENT RESULTS:
|
|
563
|
-
{results}`;async function
|
|
564
|
-
${e.slice(0,200)}`)}async function
|
|
563
|
+
{results}`;async function Kf(t,e=1,n=2e3){for(let o=0;o<=e;o++)try{return await t()}catch(s){if(o===e)throw s;await new Promise(r=>setTimeout(r,n))}}function Yf(t){let e=0,n=[];return function(){return new Promise(s=>{let r=()=>{e<t?(e++,s(()=>{e--,n.length>0&&n.shift()()})):n.push(r)};r()})}}function vb(t){if(!t||typeof t!="string")return{isComplex:!1,estimatedGoals:0,reason:"empty"};let e=0,n=[],o=t.match(/(?:(?:^|\n)\s*|\s)(?:\d+[.)]\s|[(]\d+[)][\s,]|[(][a-z][)][\s,])/g);o&&o.length>=2&&(e=Math.max(e,o.length),n.push(`${o.length} numbered items`));let s=t.match(/(?:^|\n)\s*[-*]\s+\S/g);s&&s.length>=3&&(e=Math.max(e,s.length),n.push(`${s.length} bullet points`));let r=t.split(/;\s*/).filter(u=>u.trim().length>10);r.length>=3&&(e=Math.max(e,r.length),n.push(`${r.length} semicolon-separated goals`));let i=t.match(/\b(also|additionally|and\s+(?:fix|add|update|create|implement|remove|refactor))\b/gi);i&&i.length>=2&&(e=Math.max(e,i.length+1),n.push(`${i.length} transition keywords`));let c=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10);return{isComplex:e>=c,estimatedGoals:e,reason:n.length>0?n.join(", "):"single goal"}}function Ma(t){if(!t||typeof t!="string")throw new Error("Empty response from orchestrator model");let e=t.trim();try{return JSON.parse(e)}catch{}let n=e.match(/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/);if(n)try{return JSON.parse(n[1].trim())}catch{}let o=e.search(/[[\{]/);if(o>=0){let s=e.slice(o);try{return JSON.parse(s)}catch{}}throw new Error(`Could not extract valid JSON from response:
|
|
564
|
+
${e.slice(0,200)}`)}async function zf(t,e,n={}){let o=n.maxSubTasks||Na,r=[{role:"system",content:Hf.replace("{maxSubTasks}",String(o)).replace("{prompt}",t)},{role:"user",content:t}],i={};if(e){let f=Ff(e);f.provider&&(i.provider=f.provider),f.model&&(i.model=f.model)}let l=(await qf(r,[],i)).content||"",u=Ma(l);if(!Array.isArray(u))throw new Error(`Decompose returned non-array: ${typeof u}`);return u.slice(0,o).map((f,m)=>({id:f.id||`t${m+1}`,task:String(f.task||""),scope:Array.isArray(f.scope)?f.scope:[],estimatedCalls:typeof f.estimatedCalls=="number"?Math.min(f.estimatedCalls,15):10,priority:typeof f.priority=="number"?f.priority:m+1})).filter(f=>f.task.length>0)}async function Xf(t,e,n){if(!t||t.length===0)return{summary:"No sub-tasks were executed.",conflicts:[],commitMessage:"",filesChanged:[]};let o=t.map((d,f)=>{let m=d.status==="done"?"SUCCESS":d.status==="truncated"?"PARTIAL":"FAILED";return`--- Agent ${f+1} [${m}] ---
|
|
565
565
|
Task: ${d.task}
|
|
566
566
|
Result: ${d.result}
|
|
567
567
|
Tools: ${(d.toolsUsed||[]).join(", ")||"none"}`}).join(`
|
|
568
568
|
|
|
569
|
-
`),r=[{role:"system",content:
|
|
570
|
-
${
|
|
571
|
-
`),i("decomposing"),console.log(`${
|
|
572
|
-
`);let u=Date.now(),d=
|
|
569
|
+
`),r=[{role:"system",content:Gf.replace("{prompt}",e).replace("{results}",o)},{role:"user",content:"Synthesize the sub-agent results above."}],i={};if(n){let d=Ff(n);d.provider&&(i.provider=d.provider),d.model&&(i.model=d.model)}let l=(await qf(r,[],i)).content||"",u=Ma(l);return{summary:String(u.summary||""),conflicts:Array.isArray(u.conflicts)?u.conflicts:[],commitMessage:String(u.commitMessage||""),filesChanged:Array.isArray(u.filesChanged)?u.filesChanged:[]}}async function Sb(t,e={}){let n=e.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL||Bf,o=e.workerModel||Wf,s=e.maxParallel||Uf,r=e.maxSubTasks||Na,i=e.onProgress||(()=>{}),c={input:0,output:0};console.log(`
|
|
570
|
+
${ae.bold}Orchestrator${ae.reset} ${ae.dim}model: ${n} | workers: ${o} | max parallel: ${s}${ae.reset}
|
|
571
|
+
`),i("decomposing"),console.log(`${ae.dim}Phase 1: Decomposing prompt into sub-tasks...${ae.reset}`);let l;try{l=await zf(t,n,{maxSubTasks:r})}catch(O){return console.log(`${ae.red}Decompose failed: ${O.message}${ae.reset}`),{results:[],synthesis:{summary:`Decompose failed: ${O.message}`,conflicts:[],commitMessage:"",filesChanged:[]},totalTokens:c}}if(l.length===0)return console.log(`${ae.yellow}No sub-tasks generated. Prompt may be too simple for orchestration.${ae.reset}`),{results:[],synthesis:{summary:"No sub-tasks generated.",conflicts:[],commitMessage:"",filesChanged:[]},totalTokens:c};console.log(`${ae.green}Decomposed into ${l.length} sub-tasks:${ae.reset}`);for(let O of l){console.log(` ${ae.dim}${O.id}:${ae.reset} ${O.task}`);let N=O.scope.filter(Boolean);N.length>0&&console.log(` ${ae.dim}scope: ${N.join(", ")}${ae.reset}`)}console.log(""),i("executing"),console.log(`${ae.dim}Phase 2: Running ${l.length} sub-agents (max ${s} parallel)...${ae.reset}
|
|
572
|
+
`);let u=Date.now(),d=Yf(s),f={findings:[],_lock:!1},m=l.map((O,N)=>`Agent ${N+1} [${o}]: ${O.task.substring(0,40)}${O.task.length>40?"...":""}`),h=new kb(m);h.start();let p=`
|
|
573
573
|
You are a focused coding agent executing ONE specific sub-task.
|
|
574
574
|
Your scope is limited to the files listed in your task definition.
|
|
575
575
|
|
|
@@ -587,46 +587,47 @@ RULES:
|
|
|
587
587
|
- If your task says "add X to README" \u2014 add it, don't check if it exists first.
|
|
588
588
|
- Max 10 tool calls. If you need more, you are doing too much \u2014 narrow your scope.
|
|
589
589
|
- When done: stop calling tools and write a one-line summary of what you changed.
|
|
590
|
-
`,g=l.map(async(
|
|
591
|
-
`),
|
|
592
|
-
${
|
|
593
|
-
`:"",
|
|
594
|
-
`)),
|
|
595
|
-
`):void 0,max_iterations:Math.min(
|
|
596
|
-
`)}}})),1,2e3),
|
|
597
|
-
`),conflicts:[],commitMessage:"",filesChanged:[]}}let
|
|
598
|
-
${
|
|
599
|
-
`),{results:y,synthesis:R,totalTokens:c}}
|
|
600
|
-
`)}var
|
|
601
|
-
|
|
602
|
-
[SYSTEM: Output repetition detected \u2014 response truncated (${s}\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:s}}function
|
|
590
|
+
`,g=l.map(async(O,N)=>{let he=await d();try{let ge=f.findings.filter(X=>X.agentId!==O.id).map(X=>`Agent ${X.agentId} found: ${X.summary}`).join(`
|
|
591
|
+
`),ce=[ge?`Prior agent findings:
|
|
592
|
+
${ge}
|
|
593
|
+
`:"",O.scope.length>0?`Focus on files: ${O.scope.join(", ")}`:""].filter(Boolean),ue=0,Z=await Kf(async()=>(ue>0&&(h.update(N,"retry"),process.stderr.write(` ${ae.dim}[Agent ${N+1}] retrying after error...${ae.reset}
|
|
594
|
+
`)),ue++,_b({task:O.task,context:ce.length>0?ce.join(`
|
|
595
|
+
`):void 0,max_iterations:Math.min(O.estimatedCalls||10,15),model:o,_skipLog:!0,_systemPrompt:p},{onUpdate:X=>{if(X&&X.type==="tool_call"&&process.stderr.isTTY){let E=` ${ae.dim}[Agent ${N+1}] ${X.tool}${ae.reset}`;process.stderr.write(E+`
|
|
596
|
+
`)}}})),1,2e3),de=typeof Z.result=="string"?Z.result.slice(0,200):String(Z.result||"").slice(0,200);return f.findings.push({agentId:O.id,summary:de,files:Array.isArray(O.scope)?O.scope:[]}),h.update(N,Z.status==="failed"?"error":"done"),c.input+=Z.tokensUsed?.input||0,c.output+=Z.tokensUsed?.output||0,Z.tokensUsed?._estimated&&(c._estimated=!0),{...Z,_scope:O.scope,_idx:N}}catch(ge){return h.update(N,"error"),{task:O.task,status:"failed",result:`Error: ${ge.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}}finally{he()}}),y;try{y=await Promise.all(g)}finally{h.stop({silent:!0}),xb()}console.log("");let w=Math.round((Date.now()-u)/1e3),x=w>=60?`${Math.floor(w/60)}m ${w%60}s`:`${w}s`;for(let O=0;O<y.length;O++){let N=y[O],ge=N.status==="done"||N.status==="truncated"&&N.result&&!N.result.startsWith("Error")?`${ae.green}\u2713${ae.reset}`:`${ae.red}\u2717${ae.reset}`,ce=N._scope&&N._scope.length>0?N._scope.map(de=>de.replace(/^.*\//,"").replace(/\/$/,"")).filter(Boolean):[],ue=ce.length>0?ce.join(", "):N.task.substring(0,35)+(N.task.length>35?"...":""),Z=O===y.length-1;console.log(` ${ge} Agent ${O+1} ${ae.dim}${ue}${ae.reset}${Z?` ${ae.dim}${x}${ae.reset}`:""}`)}console.log(""),i("synthesizing"),console.log(`${ae.dim}Phase 3: Synthesizing results...${ae.reset}`);let R;try{R=await Xf(y,t,n)}catch(O){console.log(`${ae.yellow}Synthesize failed: ${O.message} \u2014 using raw results.${ae.reset}`),R={summary:y.map(N=>N.result).join(`
|
|
597
|
+
`),conflicts:[],commitMessage:"",filesChanged:[]}}let k=f.findings.flatMap(O=>O.files),_=new Map;for(let O of k)_.set(O,(_.get(O)||0)+1);let b=[..._.values()].some(O=>O>1),A=f.findings.length>1&&b?` ${ae.dim}(agents shared context)${ae.reset}`:"";if(console.log(`
|
|
598
|
+
${ae.bold}Summary:${ae.reset} ${R.summary}${A}`),R.conflicts.length>0){console.log(`${ae.yellow}Conflicts:${ae.reset}`);for(let O of R.conflicts)console.log(` - ${O}`)}R.commitMessage&&console.log(`${ae.dim}Suggested commit: ${R.commitMessage}${ae.reset}`);let M=c.input===0&&c.output===0?"n/a (provider does not report token counts)":c._estimated?`~${c.input} input / ~${c.output} output (est.)`:`${c.input} input + ${c.output} output`;return console.log(`${ae.dim}Tokens: ${M}${ae.reset}
|
|
599
|
+
`),{results:y,synthesis:R,totalTokens:c}}Jf.exports={runOrchestrated:Sb,decompose:zf,synthesize:Xf,detectComplexPrompt:vb,extractJSON:Ma,createSemaphore:Yf,DECOMPOSE_PROMPT:Hf,SYNTHESIZE_PROMPT:Gf,DEFAULT_ORCHESTRATOR_MODEL:Bf,DEFAULT_WORKER_MODEL:Wf,DEFAULT_MAX_PARALLEL:Uf,DEFAULT_MAX_SUBTASKS:Na,withRetry:Kf}});var ve=G((fS,xp)=>{var{C:$,Spinner:os,TaskProgress:Eb,formatToolCall:Tb,formatToolSummary:lp,formatSectionHeader:Pa,formatMilestone:Rb,setActiveTaskProgress:aS}=Me(),{debugLog:se,warnLog:cS}=Ei(),{MilestoneTracker:Cb}=Hl(),{callStream:Vf}=Re(),{parseToolArgs:Ab}=Gn(),{executeTool:Ob}=Tt(),{gatherProjectContext:Nb}=dr(),{fitToContext:Mb,forceCompress:qt,getUsage:Nt,estimateTokens:Pb}=Ve(),{autoSave:Ib,flushAutoSave:Lb}=Ot(),{scoreMessages:Db,formatScore:jb,appendScoreHistory:qb}=pr();function Fe(t){Ib(t),Lb()}function Fb(t){if(!t||typeof t!="string")return!0;let e=t.trim();return!!(e.length<80||/^(done|complete|finished|all done|analysis complete|finally done)[.!]*$/i.test(e))}function Qf(t){try{if(!t.some(o=>o.role!=="assistant"?!1:!!(Array.isArray(o.content)&&o.content.some(s=>s&&s.type==="tool_use")||Array.isArray(o.tool_calls)&&o.tool_calls.length>0)))return;let n=Db(t);if(!n)return;console.log(jb(n,$));try{let{_getSessionsDir:o}=Ot(),s=require("fs"),r=require("path").join(o(),"_autosave.json");if(s.existsSync(r)){let i=JSON.parse(s.readFileSync(r,"utf-8"));i.score=n.score,i.scoreGrade=n.grade,i.scoreIssues=n.issues,s.writeFileSync(r,JSON.stringify(i,null,2))}}catch{}try{let{getActiveModel:o}=Gn(),s=In();qb(n.score,{version:s.version,model:o?o():null,sessionName:"_autosave",issues:n.issues})}catch{}}catch{}}var{getMemoryContext:Ub}=an(),{getDeploymentContextBlock:Wb}=$a(),{checkPermission:Bb,setPermission:Hb,savePermissions:Gb}=zs(),{confirm:up,setAllowAlwaysHandler:Kb,getAutoConfirm:dp}=Je(),{isPlanMode:no,getPlanModePrompt:Yb,PLAN_MODE_ALLOWED_TOOLS:fp,setPlanContent:zb,extractStepsFromText:Xb,createPlan:Jb,getActivePlan:lS,startExecution:uS,advancePlanStep:Vb,getPlanStepInfo:Qb}=jt(),{StreamRenderer:Zb}=Pf(),{runHooks:Zf}=Oa(),{routeMCPCall:e_,getMCPToolDefinitions:t_}=jo(),{getSkillInstructions:n_,getSkillToolDefinitions:s_,routeSkillCall:o_}=sn(),{trackUsage:ep,estimateTokens:tp}=Hn();function np(t){return!t||typeof t!="string"?0:typeof tp=="function"?tp(t):Math.ceil(t.length/4)}var{validateToolArgs:r_}=qi(),{filterToolsForModel:sp,getModelTier:i_,PROVIDER_DEFAULT_TIER:dS}=Jo(),{getConfiguredProviders:a_,getActiveProviderName:rs,getActiveModelId:An,setActiveModel:op,MODEL_EQUIVALENTS:Cr}=Re(),Ka=require("fs"),Ya=require("path"),c_=(()=>{let t=parseInt(process.env.NEX_MILESTONE_STEPS??"5",10);return Number.isFinite(t)&&t>=0?t:5})();function l_(t){let e=Rb(t.phaseName,t.stepCount,t.toolCounts,t.elapsed,t.filesRead,t.filesModified);process.stdout.write(`${e}
|
|
600
|
+
`)}var rp=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi;function u_(t){let e=[],n;for(rp.lastIndex=0;(n=rp.exec(t))!==null;){let o=n[1].trim(),s=o.startsWith("~")?o.replace("~",process.env.HOME||""):Ya.resolve(o);Ka.existsSync(s)&&e.push({raw:o,abs:s})}return e}function d_(t){let e=Ka.readFileSync(t),n=Ya.extname(t).toLowerCase().replace(".",""),o=n==="jpg"||n==="jpeg"?"image/jpeg":n==="png"?"image/png":n==="gif"?"image/gif":n==="webp"?"image/webp":"image/png";return{data:e.toString("base64"),media_type:o}}function pp(t){let e=u_(t);if(e.length===0)return t;let n=[{type:"text",text:t}];for(let o of e)try{let{data:s,media_type:r}=d_(o.abs);n.push({type:"image",media_type:r,data:s})}catch{}return n.length>1?n:t}function f_(t){if(!t||t.length<200)return{text:t,truncated:!1,repeatCount:0};let n=t.split(/(?<=\. )/).filter(l=>l.trim().length>0);if(n.length<6)return{text:t,truncated:!1,repeatCount:0};let o=new Map;for(let l=0;l<=n.length-3;l++){let u=n.slice(l,l+3).join("").trim();u.length>30&&o.set(u,(o.get(u)||0)+1)}let s=0,r="";for(let[l,u]of o)u>s&&(s=u,r=l);if(s<3)return{text:t,truncated:!1,repeatCount:s};let i=`
|
|
601
|
+
|
|
602
|
+
[SYSTEM: Output repetition detected \u2014 response truncated (${s}\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:s}}function Ua(t,e=5){if(!t||t.length<40)return{text:t,truncated:!1,repeatCount:0};let n=t.split(`
|
|
603
603
|
`),o=new Map;for(let f of n){let m=f.trim();m.length>=20&&o.set(m,(o.get(m)||0)+1)}let s=0,r="";for(let[f,m]of o)m>s&&(s=m,r=f);if(s<=e)return{text:t,truncated:!1,repeatCount:s};let i=`
|
|
604
604
|
|
|
605
|
-
\u26A0 [Response truncated: repeated paragraph detected (${s}\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:s}}var
|
|
605
|
+
\u26A0 [Response truncated: repeated paragraph detected (${s}\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:s}}var Ia=null,La=null,Da=null;function Qe(){if(Ia===null){let{TOOL_DEFINITIONS:t}=Tt();Ia=t}return La===null&&(La=s_()),Da===null&&(Da=t_()),[...Ia,...La,...Da]}var Wa=50;function p_(t){Number.isFinite(t)&&t>0&&(Wa=t)}var xr=()=>null;function m_(t){xr=t}var Qs=null,Ba=null,is=null,kr=new Map,h_=1e4,g_=6e3,$_=/\b((?:API|ACCESS|AUTH|BEARER|CLIENT|GITHUB|GITLAB|SLACK|STRIPE|TWILIO|SENDGRID|AWS|GCP|AZURE|OPENAI|ANTHROPIC|GEMINI|OLLAMA)[_A-Z0-9]*(?:KEY|TOKEN|SECRET|PASS(?:WORD)?|CREDENTIAL)[_A-Z0-9]*)\s*=\s*["']?([A-Za-z0-9\-_.+/=]{10,})["']?/g;function y_(t){return!t||typeof t!="string"?t:t.replace($_,(e,n)=>`${n}=***REDACTED***`)}var w_=7e3,b_=4e3;function __(t,e=null){let n=y_(t),o=Pb(n),s=e==="read_file"?w_:h_,r=e==="read_file"?b_:g_;if(o>s)try{let{compressToolResult:i}=Ve();return i(n,r)}catch{return n}return n}function mp(t){try{let{getActiveModel:e}=Re(),n=e(),o=n?`${n.provider}:${n.id}`:"default";if(kr.has(o))return kr.get(o);let s=sp(t);return kr.set(o,s),s}catch{return sp(t)}}function x_(){kr.clear()}var Zs={hash:null,ts:0},k_=3e4;async function hp(){if(Zs.hash&&Date.now()-Zs.ts<k_)return Zs.hash;try{let t=require("fs").promises,e=require("path"),n=[e.join(process.cwd(),"package.json"),e.join(process.cwd(),".git","HEAD"),e.join(process.cwd(),"README.md"),e.join(process.cwd(),"NEX.md")],s=(await Promise.allSettled(n.map(i=>t.stat(i).then(c=>`${i}:${c.mtimeMs}`)))).filter(i=>i.status==="fulfilled").map(i=>i.value);try{let{getMemoryContextHash:i}=an(),c=i();c&&s.push(`memory:${c}`)}catch{}try{let i=e.join(process.cwd(),".nex","brain");if(Ka.existsSync(i)){let c=await t.stat(i);s.push(`brain:${c.mtimeMs}`)}}catch{}let r=s.join("|");return Zs={hash:r,ts:Date.now()},r}catch{return`fallback:${Date.now()}`}}function Ha(){Qs=null,Ba=null,Zs={hash:null,ts:0},is=null}var v_=new Set(["spawn_agents"]),ja=5,qa=3,br=2,S_=parseInt(process.env.NEX_STALE_WARN_MS||"60000",10),ip=parseInt(process.env.NEX_STALE_ABORT_MS||"120000",10),E_=process.env.NEX_STALE_AUTO_SWITCH!=="0";function T_(t){try{let e=require("fs"),n=require("path"),o=n.join(process.cwd(),".nex","plans");e.existsSync(o)||e.mkdirSync(o,{recursive:!0});let s=n.join(o,"current-plan.md");e.writeFileSync(s,t,"utf-8")}catch{}}Kb(t=>{Hb(t,"allow"),Gb(),console.log(`${$.green} \u2713 ${t}: always allow${$.reset}`)});async function R_(t){let e=t.function.name,n=Ab(t.function.arguments),o=t.id||`cli-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!n){let l=Qe().find(d=>d.function.name===e),u=l?JSON.stringify(l.function.parameters,null,2):"unknown";return se(`${$.yellow} \u26A0 ${e}: malformed arguments, sending schema hint${$.reset}`),{callId:o,fnName:e,args:null,canExecute:!1,errorResult:{role:"tool",content:`ERROR: Malformed tool arguments. Could not parse your arguments as JSON.
|
|
606
606
|
Raw input: ${typeof t.function.arguments=="string"?t.function.arguments.substring(0,200):"N/A"}
|
|
607
607
|
|
|
608
608
|
Expected JSON schema for "${e}":
|
|
609
609
|
${u}
|
|
610
610
|
|
|
611
|
-
Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:o}}}let s=
|
|
612
|
-
`)[0]}${$.reset}`),{callId:o,fnName:e,args:n,canExecute:!1,errorResult:{role:"tool",content:s.error,tool_call_id:o}};let r=s.corrected||n;if(s.corrected){let c=Object.keys(n),l=Object.keys(s.corrected),u=c.filter(d=>!l.includes(d));u.length&&console.log(`${$.dim} \u2713 ${e}: corrected args (${u.join(", ")})${$.reset}`)}if(
|
|
611
|
+
Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:o}}}let s=r_(e,n);if(!s.valid)return se(`${$.yellow} \u26A0 ${e}: ${s.error.split(`
|
|
612
|
+
`)[0]}${$.reset}`),{callId:o,fnName:e,args:n,canExecute:!1,errorResult:{role:"tool",content:s.error,tool_call_id:o}};let r=s.corrected||n;if(s.corrected){let c=Object.keys(n),l=Object.keys(s.corrected),u=c.filter(d=>!l.includes(d));u.length&&console.log(`${$.dim} \u2713 ${e}: corrected args (${u.join(", ")})${$.reset}`)}if(no()&&!fp.has(e))return console.log(`${$.yellow} \u2717 ${e}: blocked in plan mode${$.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=Bb(e);if(i==="deny")return console.log(`${$.red} \u2717 ${e}: denied by permissions${$.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 up(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 C_(t,e,n={}){let o=await o_(t,e);if(o!==null)return o;let s=await e_(t,e);return s!==null?s:Ob(t,e,n)}function A_(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 Fa(t,e=!1){e||console.log(Tb(t.fnName,t.args));let n=Zf("pre-tool",{tool_name:t.fnName});if(!e&&n.length>0)for(let h of n)h.success?console.log(`${$.dim} [hook pre-tool] ${h.command} \u2192 ${h.output||"ok"}${$.reset}`):console.log(`${$.yellow} [hook pre-tool] ${h.command} \u2192 ERROR: ${h.error}${$.reset}`);Ft?.onToolStart&&Ft.onToolStart(t.fnName,t.args);let o=await C_(t.fnName,t.args,{silent:!0,autoConfirm:t.confirmedByUser===!0}),s=String(o??""),r=s.length>5e4?s.substring(0,5e4)+`
|
|
613
613
|
...(truncated ${s.length-5e4} chars)`:s,i=r.split(`
|
|
614
|
-
`)[0],c=i.startsWith("ERROR")||i.includes("CANCELLED")||i.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(r)&&/✗ Agent/.test(r),l=
|
|
615
|
-
HINT: use read_file instead of bash cat \u2014 it is faster, context-efficient, and the preferred tool for reading files.`:/^\s*ls(\s|$)/.test(h)&&!/npm|yarn|pnpm|make|git\b/.test(h)
|
|
616
|
-
HINT: use list_directory instead of bash ls \u2014 it is the preferred tool for listing directory contents
|
|
617
|
-
|
|
618
|
-
`)}function
|
|
614
|
+
`)[0],c=i.startsWith("ERROR")||i.includes("CANCELLED")||i.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(r)&&/✗ Agent/.test(r),l=lp(t.fnName,t.args,r,c);e||console.log(l),Ft?.onToolEnd&&Ft.onToolEnd(t.fnName,l,!c);let u=Zf("post-tool",{tool_name:t.fnName});if(!e&&u.length>0)for(let h of u)h.success?console.log(`${$.dim} [hook post-tool] ${h.command} \u2192 ${h.output||"ok"}${$.reset}`):console.log(`${$.yellow} [hook post-tool] ${h.command} \u2192 ERROR: ${h.error}${$.reset}`);let f=__(r,t.fnName);if(t.fnName==="bash"&&t.args?.command){let h=t.args.command.trim();!/cat\s*>|<</.test(h)&&/\bcat\s+\S/.test(h)?f+=`
|
|
615
|
+
HINT: use read_file instead of bash cat \u2014 it is faster, context-efficient, and the preferred tool for reading files.`:/^\s*ls(\s|$)/.test(h)&&!/npm|yarn|pnpm|make|git\b/.test(h)?f+=`
|
|
616
|
+
HINT: use list_directory instead of bash ls \u2014 it is the preferred tool for listing directory contents.`:/\bfind\s+\S/.test(h)&&!/git\b|npm\b|-exec\b|-delete\b|-print0\b/.test(h)&&(f+=`
|
|
617
|
+
HINT: use glob instead of bash find for file discovery \u2014 it is faster and the preferred tool (e.g. glob('**/*.jsx')).`)}return{msg:{role:"tool",content:f,tool_call_id:t.callId},summary:l}}async function O_(t,e=!1,n={}){let o=new Array(t.length),s=[],r=[],i=null;if(e&&!n.skipSpinner){let l=t.filter(u=>u.canExecute);if(l.length>0){let u;if(l.length===1){let d=l[0],f=A_(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 os(u),i.start()}}async function c(){if(r.length!==0){if(r.length===1){let l=r[0],{msg:u,summary:d}=await Fa(t[l],e);o[l]=u,s.push(d)}else{let l=r.map(d=>Fa(t[d],e)),u=await Promise.all(l);for(let d=0;d<r.length;d++)o[r[d]]=u[d].msg,s.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,s.push(lp(u.fnName,u.args||{},u.errorResult.content,!0));continue}if(v_.has(u.fnName)){await c(),u.fnName==="spawn_agents"&&i&&(i.stop(),i=null);let{msg:d,summary:f}=await Fa(u,e);o[l]=d,s.push(f)}else r.push(l)}if(await c(),i&&i.stop(),e&&s.length>0&&!n.skipSummaries)for(let l of s)console.log(l);return{results:o,summaries:s}}var Q=[],ap=300,gp=900*1e3;function _r(t,e){let n=t.get(e);return n?Date.now()-n.ts>gp?(t.delete(e),0):n.count:0}function Vs(t,e){let n=t.get(e),o=n&&Date.now()-n.ts<=gp?n.count+1:1;return t.set(e,{count:o,ts:Date.now()}),o}function cp(t,e,n){t.set(e,{count:n,ts:Date.now()})}var $p=new Map,yp=new Map,vr=new Map,as=new Map,On=new Map,wp=new Map,cs=new Map,ls=new Map,Mt=0,eo=0,Sr=0,Ga="",Er=0,us=!1,Tr=0,to=-1;function ss(t,e){t===Ga?(Er++,Ei().DEBUG&&process.stdout.write(`\x1B[1A\x1B[2K${e} \u26A0 ${t} (\xD7${Er})${$.reset}
|
|
618
|
+
`)):(Ga=t,Er=1,se(`${e} \u26A0 ${t}${$.reset}`))}var Rr=[];function N_(t){Rr.push(t.trim())}function M_(){return Rr.length===0?null:Rr.splice(0,Rr.length).join(`
|
|
619
|
+
`)}function P_(){let t=process.env.NEX_LANGUAGE,e=process.env.NEX_CODE_LANGUAGE,n=process.env.NEX_COMMIT_LANGUAGE,o=!t||t==="auto"?null:t,s=[`# Language Rules (CRITICAL \u2014 enforce strictly)
|
|
619
620
|
`];o?s.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.`):s.push("RESPONSE LANGUAGE: Always respond in the same language as the user's message. If the user writes in German, respond in German; if in English, respond in English; etc."),s.push("CODE EXAMPLES: Always show actual, working code examples \u2014 never pseudocode or placeholder snippets."),s.push("COMPLETENESS RULES:"),s.push(" \u2022 ALWAYS show actual code when explaining implementations \u2014 never describe without showing"),s.push(" \u2022 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."),s.push(" \u2022 Include complete examples with full context (imports, function signatures, error handling)"),s.push(' \u2022 Show alternative approaches when relevant (e.g., "Alternative: use util.promisify instead")'),s.push(" \u2022 Include edge cases in explanations (empty input, null values, boundary conditions)"),s.push(" \u2022 Provide platform-specific guidance when commands differ by OS (Linux/macOS/Windows)"),s.push(' \u2022 For Makefiles, 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.'),s.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."),s.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."),s.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.'),s.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).'),s.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)."),s.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."),s.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."),s.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.'),s.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";s.push(`CODE LANGUAGE: Write all code comments, docstrings, variable descriptions, and inline documentation in ${r}.`);let i=n||"English";return s.push(`COMMIT MESSAGES: Write all git commit messages in ${i}.`),o&&s.push(`
|
|
620
621
|
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}.`),s.join(`
|
|
621
622
|
`)+`
|
|
622
623
|
|
|
623
|
-
`}function
|
|
624
|
+
`}function I_(){if(is!==null)return is;try{let e=a_().flatMap(s=>s.models.map(r=>({spec:`${s.name}:${r.id}`,tier:i_(r.id,s.name),name:r.name})));if(e.length<2)return is="","";let n={full:"complex tasks (refactor, implement, generate)",standard:"regular tasks (edit, fix, analyze)",essential:"simple tasks (read, search, list)"},o=`
|
|
624
625
|
# Sub-Agent Model Routing
|
|
625
626
|
|
|
626
627
|
`;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 |
|
|
627
628
|
|---|---|---|
|
|
628
629
|
`;for(let s of e)o+=`| ${s.spec} | ${s.tier} | ${n[s.tier]||s.tier} |
|
|
629
|
-
`;return
|
|
630
|
+
`;return is=o,o}catch(t){return process.env.NEX_DEBUG&&console.error("[agent] model routing guide failed:",t.message),is="",""}}async function bp(){let t=await hp();if(Qs!==null&&t===Ba)return Qs;let e=await Nb(process.cwd()),n=Ub(),o=n_(),s=no()?Yb():"",r=P_(),i=Wb();return Qs=`You are Nex Code, an expert coding assistant. You help with programming tasks by reading, writing, and editing files, running commands, and answering questions.
|
|
630
631
|
|
|
631
632
|
WORKING DIRECTORY: ${process.cwd()}
|
|
632
633
|
All relative paths resolve from this directory.
|
|
@@ -642,7 +643,7 @@ ${s}
|
|
|
642
643
|
${r?`${r}
|
|
643
644
|
`:""}${i?`${i}
|
|
644
645
|
|
|
645
|
-
`:""}${
|
|
646
|
+
`:""}${dp()?`# YOLO Mode \u2014 Auto-Execute
|
|
646
647
|
|
|
647
648
|
You are in YOLO mode (autoConfirm=true). All tool calls are pre-approved.
|
|
648
649
|
- NEVER ask for confirmation \u2014 just execute tasks directly
|
|
@@ -864,7 +865,7 @@ This applies to bash output, SSH output, grep results, and all other tool output
|
|
|
864
865
|
- Instead: use bash with inline node -e '...' for quick one-off checks.
|
|
865
866
|
- If the test is worth keeping, write it to tests/ with a proper name.
|
|
866
867
|
- Write-then-delete patterns waste 3 tool calls and leave orphans if the session is interrupted.
|
|
867
|
-
${
|
|
868
|
+
${I_()}
|
|
868
869
|
|
|
869
870
|
# Edit Reliability (Critical)
|
|
870
871
|
|
|
@@ -915,83 +916,85 @@ You have access to a persistent knowledge base in .nex/brain/.
|
|
|
915
916
|
- Include tags in frontmatter for better retrieval
|
|
916
917
|
- The user reviews all brain writes via /brain review or git diff
|
|
917
918
|
|
|
918
|
-
`,
|
|
919
|
-
`):[]).filter(f=>{let m=f.split(".").pop();return r.has(m)});if(i.length<3)return null;let c={};for(let f of i){let m=f.split(".").pop();c[m]=(c[m]||0)+1}let u=` \u{1F4C1} ${Object.entries(c).sort((f,m)=>m[1]-f[1]).slice(0,4).map(([f,m])=>`${m} .${f}`).join(" \xB7 ")}`,d=
|
|
920
|
-
\u{1F4E6} ${h}${p}`}}catch{}return u}function
|
|
921
|
-
${$.dim} ${c}${$.reset}`),l>=30&&process.stdout.isTTY){let u=n.size>0?`Done \u2014 ${n.size} ${n.size===1?"file":"files"} modified in ${l}s`:`Done \u2014 ${t} ${t===1?"step":"steps"} in ${l}s`;
|
|
922
|
-
`),m==="")return c({action:"quit"});let p=i.find(g=>g.key===h);!p||p.key==="q"||!p.model&&p.key!=="r"?c({action:"quit"}):p.key==="r"?c({action:"retry"}):c({action:"switch",model:p.model,provider:t})};l.on("data",f)})}var
|
|
923
|
-
`+
|
|
924
|
-
`)}catch(
|
|
925
|
-
|
|
926
|
-
`));let
|
|
919
|
+
`,Ba=t,Qs}function _p(){$p.clear(),yp.clear(),vr.clear(),as.clear(),On.clear(),wp.clear(),cs.clear(),ls.clear(),Mt=0,eo=0,Sr=0,us=!1,Tr=0,to=-1,Ga="",Er=0}function L_(){Q=[],_p()}function D_(){Q.length>ap&&Q.splice(0,Q.length-ap)}function j_(){return Q.length}function q_(){return Q}function F_(t){Q=t}async function U_(){let{execFile:t}=require("child_process"),e=require("fs"),n=process.cwd(),o=(f,m)=>new Promise(h=>{t(f,m,{cwd:n,timeout:3e3},(p,g)=>{h(p?"":(g||"").trim())})}),[s]=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=(s?s.split(`
|
|
920
|
+
`):[]).filter(f=>{let m=f.split(".").pop();return r.has(m)});if(i.length<3)return null;let c={};for(let f of i){let m=f.split(".").pop();c[m]=(c[m]||0)+1}let u=` \u{1F4C1} ${Object.entries(c).sort((f,m)=>m[1]-f[1]).slice(0,4).map(([f,m])=>`${m} .${f}`).join(" \xB7 ")}`,d=Ya.join(n,"package.json");if(e.existsSync(d))try{let f=JSON.parse(e.readFileSync(d,"utf-8")),m=Object.keys({...f.dependencies||{},...f.devDependencies||{}});if(m.length>0){let h=m.slice(0,5).join(" \xB7 "),p=m.length>5?` +${m.length-5}`:"";u+=`
|
|
921
|
+
\u{1F4E6} ${h}${p}`}}catch{}return u}function W_(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 Ue(t,e,n,o,s,{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(s){let u=Date.now()-s;l=Math.round(u/1e3),c+=l>=60?` \xB7 ${Math.floor(l/60)}m ${l%60}s`:` \xB7 ${l}s`}if(n.size>0&&(c+=` \xB7 ${n.size} ${n.size===1?"file":"files"} modified`),c+=" \u2500\u2500",console.log(`
|
|
922
|
+
${$.dim} ${c}${$.reset}`),l>=30&&process.stdout.isTTY){let u=n.size>0?`Done \u2014 ${n.size} ${n.size===1?"file":"files"} modified in ${l}s`:`Done \u2014 ${t} ${t===1?"step":"steps"} in ${l}s`;W_(u)}n.size>0?console.log(`${$.dim} \u{1F4A1} /diff \xB7 /commit \xB7 /undo${$.reset}`):!r&&o.size>=5&&n.size===0&&t>=3?console.log(`${$.dim} \u{1F4A1} Found issues? Say "fix 1" or "apply all fixes"${$.reset}`):o.size>0&&t>=2&&console.log(`${$.dim} \u{1F4A1} /save \xB7 /clear${$.reset}`)}async function B_(){if(!process.stdout.isTTY)return{action:"quit"};let t=rs(),e=An(),n=Cr.fast?.[t],o=Cr.strong?.[t],s=n&&n!==e,r=o&&o!==e&&o!==n,i=[];i.push({key:"r",label:`Retry with current model ${$.dim}(${e})${$.reset}`}),s&&i.push({key:"f",label:`Switch to ${$.bold}${n}${$.reset} ${$.dim}\u2014 fast, low latency${$.reset}`,model:n}),r&&i.push({key:"s",label:`Switch to ${$.bold}${o}${$.reset} ${$.dim}\u2014 reliable tool-calling, medium speed${$.reset}`,model:o}),i.push({key:"q",label:`${$.dim}Quit${$.reset}`}),console.log(),console.log(`${$.yellow} Stream stale \u2014 all retries exhausted.${$.reset} What would you like to do?`);for(let c of i)console.log(` ${$.cyan}[${c.key}]${$.reset} ${c.label}`);return process.stdout.write(` ${$.yellow}> ${$.reset}`),new Promise(c=>{let l=process.stdin,u=l.isRaw;l.setRawMode(!0),l.resume(),l.setEncoding("utf8");let d=!1,f=m=>{if(d)return;d=!0,l.removeListener("data",f),l.setRawMode(u||!1),l.pause();let h=m.toLowerCase().trim();if(process.stdout.write(`${h}
|
|
923
|
+
`),m==="")return c({action:"quit"});let p=i.find(g=>g.key===h);!p||p.key==="q"||!p.model&&p.key!=="r"?c({action:"quit"}):p.key==="r"?c({action:"retry"}):c({action:"switch",model:p.model,provider:t})};l.on("data",f)})}var Ft=null;async function H_(t,e=null,n={}){Ft=e;let o=pp(t);Q.push({role:"user",content:o}),D_();let s=n.autoOrchestrate!==!1&&process.env.NEX_AUTO_ORCHESTRATE!=="false",r=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10);try{let{detectComplexPrompt:je,runOrchestrated:Pe}=Js(),qe=je(typeof t=="string"?t:"");if(s&&qe.isComplex&&qe.estimatedGoals>=r)return console.log(`${$.yellow}\u26A1 Auto-orchestrate: ${qe.estimatedGoals} goals \u2192 parallel agents${$.reset}`),await Pe(t,{orchestratorModel:n.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL,workerModel:n.model});qe.isComplex&&console.log(`${$.dim}Hint: ~${qe.estimatedGoals} goals detected. Disable with NEX_AUTO_ORCHESTRATE=false${$.reset}`)}catch{}let{setOnChange:i}=Qo(),c=null,l=0;i((je,Pe)=>{je==="create"?(c&&c.stop(),c=new Eb(Pe.name,Pe.tasks),c.setStats({tokens:l}),c.start()):je==="update"&&c?c.updateTask(Pe.id,Pe.status):je==="clear"&&c&&(c.stop(),c=null)});let u=await bp(),d=u;try{let{getBrainContext:je}=Ds(),Pe=await je(t);Pe&&(d=u+`
|
|
924
|
+
`+Pe+`
|
|
925
|
+
`)}catch(je){process.env.NEX_DEBUG&&console.error("[agent] brain context failed:",je.message)}let f=[{role:"system",content:d},...Q],m=new os("Thinking...");m.start();let p=Q.length===1?U_().catch(()=>null):Promise.resolve(null),g=Qe(),[{messages:y,compressed:w,compacted:x,tokensRemoved:R},k]=await Promise.all([Mb(f,g),p]),_=Nt(f,g);if(m.stop(),k&&console.log(`${$.dim}${k}${$.reset}`),x)console.log(`${$.dim} [context compacted \u2014 summary (~${R} tokens freed)]${$.reset}`);else if(w){let je=_.limit>0?Math.round(R/_.limit*100):0;se(`${$.dim} [context compressed \u2014 ~${R} tokens freed (${je}%)]${$.reset}`)}_.percentage>85&&se(`${$.yellow} \u26A0 Context ${Math.round(_.percentage)}% used (${Math.round(100-_.percentage)}% remaining) \u2014 consider /clear or /save + start fresh${$.reset}`);let b=y;if(Nt(b,Qe()).percentage>=65){let{messages:Pe,tokensRemoved:qe}=qt(b,Qe());qe>0&&(b=Pe,console.log(`${$.dim} [pre-flight compress \u2014 ${qe} tokens freed, now ${Math.round(Nt(b,Qe()).percentage)}% used]${$.reset}`))}let A=0,M=0,O=0,N=0,he=0,ge=9,ce=0,ue=(()=>{let je=Q.find(Pe=>Pe.role==="user");return typeof je?.content=="string"?je.content:""})(),Z=/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(ue),de=0,X=0,E=new Map,P=new Set,F=new Set,K=Date.now(),oe=new Cb(c_),L=wp,U=2,re=4,ee=$p,te=5,$e=8,pe=yp,we=4,be=7,He=vr,Ge=3,Ut=4,hs=as,Kr=2,Ym=3,gs=4,un=0,zm=6,Xm=10,dn=0,kc=5,fn=0,Jm=2,Vm=3,Yr=0,zr=8,Qm=12,ft,go=Wa,Xr=0,vc=3,Jr=!1;e:for(;;){for(Jr=!1,ft=0;ft<go&&!xr()?.aborted;ft++){{let S=Qe(),v=Nt(b,S),J=X===0?65:78;if(v.percentage>=J){let{messages:D,tokensRemoved:W}=qt(b,S,X===0);W>0&&(b=D,W>50&&console.log(`${$.dim} [auto-compressed \u2014 ~${W} tokens freed, now ${Math.round(Nt(b,S).percentage)}%]${$.reset}`))}}let Pe=!0;X>0&&Vb();let qe=null;if(c&&c.isActive())c._paused&&c.resume();else if(!c){let S,v=Qb();if(v&&v.total>1){let J=v.description.length>40?v.description.slice(0,37)+"\u2026":v.description;S=`Plan step ${v.current}/${v.total}: ${J}`}else S=X>0?`Thinking... (step ${X+1})`:"Thinking...";qe=new os(S),qe.start()}let Vr=!0,Wt="",Qr=!1,pt=new Zb,It,Zr=Date.now(),$o=!1,ei=new AbortController,Sc=setInterval(()=>{let S=Date.now()-Zr;if(S>=ip)pt._clearCursorLine(),se(`${$.yellow} \u26A0 Stream stale for ${Math.round(S/1e3)}s \u2014 aborting and retrying${$.reset}`),ei.abort();else if(S>=S_&&!$o){$o=!0,pt._clearCursorLine();let v=Cr.fast?.[rs()],J=O>0?` (retry ${O+1}/${br})`:"",D=Math.round((ip-S)/1e3);se(`${$.yellow} \u26A0 No tokens received for ${Math.round(S/1e3)}s \u2014 waiting...${J}${$.reset}`),v&&v!==An()?console.log(`${$.dim} \u{1F4A1} Will auto-switch to ${v} in ~${D}s if no tokens arrive${$.reset}`):console.log(`${$.dim} \u{1F4A1} Ctrl+C to abort \xB7 auto-abort in ~${D}s${$.reset}`)}},5e3),_t="",Bt=null;try{let S=mp(Qe()),v=no()?S.filter(W=>fp.has(W.function.name)):S,J=xr(),D=new AbortController;J&&J.addEventListener("abort",()=>D.abort(),{once:!0}),ei.signal.addEventListener("abort",()=>D.abort(),{once:!0}),It=await Vf(b,v,{signal:D.signal,onThinkingToken:()=>{Zr=Date.now(),$o=!1,Ft?.onThinkingToken&&Ft.onThinkingToken()},onToken:W=>{if(Zr=Date.now(),$o=!1,Ft?.onToken){Ft.onToken(W),Wt+=W;return}if(Wt+=W,!Qr&&Wt.length>400&&Wt.length%250<W.length+1){let fe=Ua(Wt,3);fe.truncated&&(Qr=!0,pt._clearCursorLine?.(),se(`${$.yellow} \u26A0 LLM stream loop detected (${fe.repeatCount}\xD7 repeated) \u2014 suppressing display${$.reset}`))}Qr||(_t+=W,process.stdout.isTTY?Bt||(Bt=setTimeout(()=>{_t&&pt&&pt.push(_t),_t="",Bt=null},50)):(pt.push(_t),_t=""),Vr&&(c&&!c._paused?c.pause():qe&&qe.stop(),Pe||(Pe=!0),pt.startCursor(),Vr=!1))}})}catch(S){if(clearInterval(Sc),Bt&&(clearTimeout(Bt),Bt=null),_t&&pt&&(pt.push(_t),_t=""),c&&!c._paused&&c.pause(),qe&&qe.stop(),pt.stopCursor(),ei.signal.aborted&&!xr()?.aborted){if(O++,O>br){if(N<1){N++,ss("Stale retries exhausted \u2014 last-resort force-compress...",$.yellow);let Y=Qe(),{messages:H,tokensRemoved:V}=qt(b,Y);b=H,V>50&&se(`${$.dim} [force-compressed \u2014 ~${V} tokens freed]${$.reset}`),O=0,ft--;continue}c&&(c.stop(),c=null);let fe=await B_();if(fe.action==="quit"){i(null),Ue(X,E,P,F,K),Fe(Q);break}fe.action==="switch"&&(op(`${fe.provider}:${fe.model}`),console.log(`${$.green} \u2713 Switched to ${fe.provider}:${fe.model}${$.reset}`)),O=0,ft--;continue}let D=O===1?3e3:5e3;if(O>=1&&ce<1){ce++,ss(`Stale retry ${O}/${br} \u2014 force-compressing before retry...`,$.yellow);let fe=Qe(),{messages:Y,tokensRemoved:H}=qt(b,fe,!0);if(b=Y,H>0&&H>50&&se(`${$.dim} [force-compressed \u2014 ~${H} tokens freed]${$.reset}`),E_){let V=Cr.fast?.[rs()];V&&V!==An()&&(op(`${rs()}:${V}`),console.log(`${$.cyan} \u26A1 Auto-switched to ${V} to avoid further stale timeouts${$.reset}`),console.log(`${$.dim} (disable with NEX_STALE_AUTO_SWITCH=0)${$.reset}`))}}else se(`${$.yellow} \u26A0 Stale retry ${O}/${br} \u2014 retrying in ${D/1e3}s...${$.reset}`);let W=new os(`Waiting ${D/1e3}s before retry...`);W.start(),await new Promise(fe=>setTimeout(fe,D)),W.stop(),ft--;continue}if(S.name==="AbortError"||S.name==="CanceledError"||S.message?.includes("canceled")||S.message?.includes("aborted")){c&&(c.stop(),c=null),i(null),Ue(X,E,P,F,K),Fe(Q);break}let v=S.message;if(S.code==="ECONNREFUSED"||S.message.includes("ECONNREFUSED"))v="Connection refused \u2014 please check your internet connection or API endpoint";else if(S.code==="ENOTFOUND"||S.message.includes("ENOTFOUND"))v="Network error \u2014 could not reach the API server. Please check your connection";else if(S.code==="ETIMEDOUT"||S.message.includes("timeout"))v="Request timed out \u2014 the API server took too long to respond. Please try again";else if(S.message.includes("401")||S.message.includes("Unauthorized"))v="Authentication failed \u2014 please check your API key in the .env file";else if(S.message.includes("403")||S.message.includes("Forbidden"))v="Access denied \u2014 your API key may not have permission for this model";else if(S.message.includes("404")){v=`Model not found (404): ${An?An():"unknown"} \u2014 check your .env MODEL setting or run /models to list available models`,console.log(`${$.red} \u2717 ${v}${$.reset}`),c&&(c.stop(),c=null),i(null),Ue(X,E,P,F,K),Fe(Q);break}else if(S.message.includes("400")){if(N<3&&he<ge){N++,he++;let D=X===0&&N===1,W=D||N===3||ce>0;if(D){N=3;let V=S.message.replace(/^API Error(\s*\[HTTP \d+\])?:\s*/i,"").slice(0,150);ss(`Bad request (400) \u2014 ${V||"system prompt too large"}, compressing...`,$.yellow)}else ss(W?`Bad request (400) \u2014 nuclear compression (attempt ${N}/3, dropping history)...`:`Bad request (400) \u2014 force-compressing and retrying... (attempt ${N}/3)`,$.yellow);let fe=Qe(),{messages:Y,tokensRemoved:H}=qt(b,fe,W);b=Y,H>50&&se(`${$.dim} [force-compressed \u2014 ~${H} tokens freed]${$.reset}`),ft--;continue}{let D=b.find(le=>le.role==="system"),W=b.find(le=>le.role==="user"&&!String(le.content).startsWith("[SYSTEM")&&!String(le.content).startsWith("BLOCKED:")),fe=[D,W].filter(Boolean),{getUsage:Y}=Ve(),H=Ve().estimateMessagesTokens(fe),V=Ve().estimateMessagesTokens(b);if(H<V){let le=[],Ee=Q.filter(ie=>ie.role==="assistant"&&typeof ie.content=="string"&&ie.content.trim().length>30).slice(-3).map(ie=>ie.content.trim().slice(0,120).replace(/\n+/g," "));Ee.length>0&&le.push(`Key findings:
|
|
926
|
+
`+Ee.map(ie=>`- ${ie}`).join(`
|
|
927
|
+
`));let Te=Q.filter(ie=>ie.role==="tool"&&typeof ie.content=="string"&&!ie.content.startsWith("BLOCKED:")&&ie.content.trim().length>10).slice(-3).map(ie=>ie.content.trim().split(`
|
|
927
928
|
`).slice(0,3).join(`
|
|
928
|
-
`).slice(0,200));if(
|
|
929
|
-
`+
|
|
930
|
-
`)),
|
|
931
|
-
${
|
|
929
|
+
`).slice(0,200));if(Te.length>0&&le.push(`Tool results summary:
|
|
930
|
+
`+Te.map(ie=>`- ${ie}`).join(`
|
|
931
|
+
`)),P.size>0){let ie=[...P].map(Ke=>Ke.split("/").slice(-2).join("/")).join(", ");le.unshift(`Already modified: ${ie} \u2014 use edit_file to add missing pieces only, DO NOT use write_file on these files.`)}if(le.length>0){let ie={role:"user",content:`[SYSTEM: Findings from investigation before context wipe]
|
|
932
|
+
${le.join(`
|
|
932
933
|
`)}
|
|
933
|
-
Continue implementing the fixes based on these findings.`};
|
|
934
|
-
Files modified so far: ${[...
|
|
934
|
+
Continue implementing the fixes based on these findings.`};fe.push(ie)}if(eo>=3){let ie=P.size>0?`
|
|
935
|
+
Files modified so far: ${[...P].map(Ke=>Ke.split("/").slice(-1)[0]).join(", ")}`:"";se(`${$.red} \u2717 Super-nuclear limit reached (3\xD7) \u2014 aborting to prevent runaway context loop${$.reset}`),console.log(`${$.yellow} \u{1F4A1} Task may exceed model context. Try /clear and break it into smaller steps.${ie?$.dim+ie:""}${$.reset}`),c&&(c.stop(),c=null),i(null),Ue(X,E,P,F,K,{suppressHint:!0}),Fe(Q);break}b=fe,eo++,to=5,Mt=0,de=0;for(let[ie,Ke]of as){let mt=Ke?.count??Ke??0;cp(as,ie,mt>=2?mt:1)}for(let[ie]of On)_r(as,ie)<2&&On.delete(ie);cs.clear(),ls.clear();for(let[ie]of vr)cp(vr,ie,Ut-1);if(ss(`Super-nuclear compression \u2014 dropped all history, keeping original task only (${V-H} tokens freed)`,$.yellow),eo>=1){let ie=[...as.entries()].filter(([,mn])=>mn>=gs).map(([mn])=>mn.split("/").slice(-1)[0]),Ke=ie.length>0?`
|
|
935
936
|
|
|
936
|
-
|
|
937
|
+
Files already at read cap \u2014 use grep_search instead: ${ie.join(", ")}`:"",mt={role:"user",content:`[SYSTEM WARNING] Context wiped ${eo}\xD7. SKIP investigation \u2014 implement directly using findings above. Budget: 5 tool calls remaining (enforced \u2014 all further calls are blocked once exhausted).
|
|
937
938
|
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
939
|
+
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.${Ke}`};Q.push(mt),b.push(mt)}N=0,ft--;continue}}v="Context too large to compress \u2014 use /clear to start fresh"}else S.message.includes("500")||S.message.includes("502")||S.message.includes("503")||S.message.includes("504")?v="API server error \u2014 the provider is experiencing issues. Please try again in a moment":(S.message.includes("fetch failed")||S.message.includes("fetch"))&&(v="Network request failed \u2014 please check your internet connection");if(console.log(`${$.red} \u2717 ${v}${$.reset}`),S.message.includes("429")){if(A++,A>ja){console.log(`${$.red} Rate limit: max retries (${ja}) exceeded. Try again later or use /budget to check your limits.${$.reset}`),c&&(c.stop(),c=null),i(null),Ue(X,E,P,F,K),Fe(Q);break}let D=Math.min(1e4*Math.pow(2,A-1),12e4),W=new os(`Rate limit \u2014 waiting ${Math.round(D/1e3)}s (retry ${A}/${ja})`);W.start(),await new Promise(fe=>setTimeout(fe,D)),W.stop();continue}if(S.message.includes("socket disconnected")||S.message.includes("TLS")||S.message.includes("ECONNRESET")||S.message.includes("ECONNABORTED")||S.message.includes("ETIMEDOUT")||S.code==="ECONNRESET"||S.code==="ECONNABORTED"){if(M++,M>qa){console.log(`${$.red} Network error: max retries (${qa}) exceeded. Check your connection and try again.${$.reset}`),c&&(c.stop(),c=null),i(null),Ue(X,E,P,F,K),Fe(Q);break}let D=Math.min(2e3*Math.pow(2,M-1),3e4),W=new os(`Network error \u2014 retrying in ${Math.round(D/1e3)}s (${M}/${qa})`);W.start(),await new Promise(fe=>setTimeout(fe,D)),W.stop(),ft--;continue}c&&(c.stop(),c=null),i(null),Ue(X,E,P,F,K),Fe(Q);break}if(clearInterval(Sc),A=0,M=0,Vr&&(c&&!c._paused&&c.pause(),qe&&qe.stop()),Bt&&(clearTimeout(Bt),Bt=null),_t&&pt&&(pt.push(_t),_t=""),Wt&&pt.flush(),M=0,O=0,It&&It.usage){let S=It.usage.prompt_tokens||0,v=It.usage.completion_tokens||0;ep(rs(),An(),S,v),l+=S+v,c&&c.setStats({tokens:l})}else if(It&&!It.usage){let S=b.map(D=>typeof D.content=="string"?D.content:Array.isArray(D.content)?D.content.map(W=>typeof W=="string"?W:W.text||"").join(""):"").join(" "),v=np(S),J=np(It.content||Wt||"");ep(rs(),An(),v,J),l+=v+J,c&&c.setStats({tokens:l})}let{content:Ec,tool_calls:pn}=It,yo=Ua(Ec||""),Tc=yo.truncated?yo.text:Ec;yo.truncated&&se(`${$.yellow} \u26A0 LLM output loop detected (${yo.repeatCount}\xD7 repeated paragraph) \u2014 response truncated${$.reset}`);let wo=f_(Tc||""),$s=wo.truncated?wo.text:Tc;wo.truncated&&se(`${$.yellow} \u26A0 LLM output loop detected (${wo.repeatCount}\xD7 repeated window) \u2014 response truncated${$.reset}`);let ti={role:"assistant",content:$s||""};if(pn&&pn.length>0&&(ti.tool_calls=pn),Q.push(ti),b.push(ti),!pn||pn.length===0){let S=($s||"").trim().length>0||Wt.trim().length>0,v=!1;if(us&&S&&(us=!1,Mt=0,v=!0),v&&S){let J=($s||"").trim();if(J.endsWith("?")||/\b(Wo |Bitte |Kannst du|Soll ich)\b/.test(J.slice(-200))){let W={role:"user",content:"[SYSTEM] Continue. Do not ask questions \u2014 implement the fix yourself using SSH. The server is at 94.130.37.43."};b.push(W),Q.push(W);continue}}if(!S&&X>0&&ft<Wa-1){let J={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."};b.push(J),Q.push(J);continue}if(no()&&S&&X===0)if(Sr++,Sr>2)se(`${$.yellow} \u26A0 Plan accepted despite no file reads (rejection loop cap reached)${$.reset}`);else{let J={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.).
|
|
940
|
+
|
|
941
|
+
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.`};Q.push(J),b.push(J),se(`${$.yellow} \u26A0 Plan rejected (${Sr}/2): no files read \u2014 forcing investigation${$.reset}`);continue}if(no()&&S){let J=($s||Wt||"").trim();zb(J),T_(J);let D=Xb(J);if(D.length>0){let W=Q.find(V=>V.role==="user"),fe=typeof W?.content=="string"?W.content.slice(0,120):"Task";Jb(fe,D);let Y=D.length===1?"step":"steps",H=!1;if(process.stdout.isTTY&&process.stdin.isTTY){let{approvePlan:V,startExecution:le,setPlanMode:Ee}=jt();process.stdout.write(`
|
|
942
|
+
${$.cyan}${$.bold}Plan ready${$.reset} ${$.dim}(${D.length} ${Y})${$.reset} ${$.green}[A]${$.reset}${$.dim}pprove${$.reset} ${$.yellow}[E]${$.reset}${$.dim}dit${$.reset} ${$.red}[R]${$.reset}${$.dim}eject${$.reset} ${$.dim}[\u21B5 = approve]:${$.reset} `);let Te=process.stdin.isRaw,ie=await new Promise(Ke=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",mt=>{try{process.stdin.setRawMode(Te||!1)}catch{}let mn=mt.toString().toLowerCase()[0]||"\r";Ke(mn)})});if(process.stdout.write(`
|
|
943
|
+
`),ie==="r")console.log(`${$.red}Plan rejected.${$.reset} Ask follow-up questions to refine.`);else if(ie==="e")console.log(`${$.yellow}Type /plan edit to open in editor, or give feedback.${$.reset}`);else if(V()){le(),Ee(!1),Ha(),console.log(`${$.green}${$.bold}Approved!${$.reset} Executing ${D.length} ${Y}...`);let Ke=`[PLAN APPROVED \u2014 EXECUTE NOW]
|
|
941
944
|
|
|
942
945
|
Implement the following plan step by step. All tools are now available.
|
|
943
946
|
|
|
944
|
-
${J}`;Q.push({role:"user",content:
|
|
945
|
-
${$.cyan}${$.bold}Plan ready${$.reset} ${$.dim}(${D.length} ${
|
|
946
|
-
${$.cyan}${$.bold}Plan ready.${$.reset} ${$.green}[A]${$.reset}${$.dim}pprove${$.reset} ${$.red}[R]${$.reset}${$.dim}eject${$.reset} ${$.dim}[\u21B5 = approve]:${$.reset} `);let
|
|
947
|
-
`),
|
|
947
|
+
${J}`;Q.push({role:"user",content:Ke}),b.push({role:"user",content:Ke}),H=!0}}else console.log(`
|
|
948
|
+
${$.cyan}${$.bold}Plan ready${$.reset} ${$.dim}(${D.length} ${Y} extracted).${$.reset} Type ${$.cyan}/plan approve${$.reset}${$.dim} to execute, or ${$.reset}${$.cyan}/plan edit${$.reset}${$.dim} to review.${$.reset}`);if(H){c&&(c.stop(),c=null),ft--;continue}}else{let W=!1;if(process.stdout.isTTY&&process.stdin.isTTY){let{approvePlan:fe,startExecution:Y,setPlanMode:H}=jt();process.stdout.write(`
|
|
949
|
+
${$.cyan}${$.bold}Plan ready.${$.reset} ${$.green}[A]${$.reset}${$.dim}pprove${$.reset} ${$.red}[R]${$.reset}${$.dim}eject${$.reset} ${$.dim}[\u21B5 = approve]:${$.reset} `);let V=process.stdin.isRaw,le=await new Promise(Ee=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",Te=>{try{process.stdin.setRawMode(V||!1)}catch{}Ee(Te.toString().toLowerCase()[0]||"\r")})});if(process.stdout.write(`
|
|
950
|
+
`),le==="r")console.log(`${$.red}Plan rejected.${$.reset} Ask follow-up questions to refine.`);else if(fe()){Y(),H(!1),Ha(),console.log(`${$.green}${$.bold}Approved!${$.reset} Executing...`);let Te=`[PLAN APPROVED \u2014 EXECUTE NOW]
|
|
948
951
|
|
|
949
952
|
Implement the following plan step by step. All tools are now available.
|
|
950
953
|
|
|
951
|
-
${getPlanContent()||
|
|
952
|
-
${$.cyan}${$.bold}Plan ready.${$.reset} ${$.dim}Type ${$.reset}${$.cyan}/plan approve${$.reset}${$.dim} to execute, or ask follow-up questions to refine.${$.reset}`);if(
|
|
953
|
-
${
|
|
954
|
-
`)):
|
|
955
|
-
`)),!
|
|
956
|
-
`)[0],
|
|
957
|
-
${$.yellow}\u26A0 Max iterations reached.${$.reset}`),await
|
|
958
|
-
`),await t(c,i,d)}catch(u){if(n=u,
|
|
954
|
+
${getPlanContent()||It.content}`;Q.push({role:"user",content:Te}),b.push({role:"user",content:Te}),W=!0}}else console.log(`
|
|
955
|
+
${$.cyan}${$.bold}Plan ready.${$.reset} ${$.dim}Type ${$.reset}${$.cyan}/plan approve${$.reset}${$.dim} to execute, or ask follow-up questions to refine.${$.reset}`);if(W){c&&(c.stop(),c=null),ft--;continue}}}if(c&&(c.stop(),c=null),i(null),Ue(X,E,P,F,K),X>0&&!n._isSummaryTurn&&dp()&&Fb($s))try{se(`${$.dim} [post-turn] terse ending \u2014 requesting summary${$.reset}`);let J=[...b,{role:"user",content:"Please summarize what you just did in 2-3 sentences."}],W=((await Vf(J,[],{}))?.content||"").trim();W&&(console.log(`
|
|
956
|
+
${W}`),Q.push({role:"user",content:"Please summarize what you just did in 2-3 sentences."},{role:"assistant",content:W}))}catch{}Fe(Q),Qf(Q);return}X++,X>=1&&(Pe=!1);for(let S of pn){let v=S.function.name;E.set(v,(E.get(v)||0)+1)}let Ne=await Promise.all(pn.map(S=>R_(S)));{let S=Nt(b,Qe()),v=S.percentage,J=Ne.some(Y=>Y.canExecute&&Y.fnName==="read_file"&&!Y.args?.line_end),D=Ne.filter(Y=>Y.canExecute&&Y.fnName==="read_file"&&Y.args?.path&&_r(hs,Y.args.path)>=1&&!Y.args?.line_start).map(Y=>Y.args.path.split("/").slice(-2).join("/")),W=D.length>0;if(v>=70&&J&&Yr<70||v>=85&&Yr<85||W){Yr=v;let Y=v>=85?"URGENT":"WARNING",H;W?(Y="WARNING",H=`Unbounded re-read of ${D.join(", ")} \u2014 already in context. Use line_start/line_end to read specific sections instead.`):J?H=`Unbounded read at ${Math.round(v)}% context \u2014 use line_start/line_end to avoid overflow.`:H=`Context ${Math.round(v)}% used. Avoid large reads, wrap up with what you have.`;let V={role:"user",content:`[SYSTEM ${Y}] Context ${Math.round(v)}% used (${S.used}/${S.limit} tokens). ${H}`};if(Q.push(V),b.push(V),v>=85){let le=W?` (re-read of: ${D.join(", ")})`:"";se(`${$.yellow} \u26A0 Context ${Math.round(v)}% used \u2014 agent warned to use targeted reads${le}${$.reset}`)}}}let ni=new Map;for(let S of Ne){if(!S.canExecute||S.fnName!=="read_file")continue;let v=S.args?.path;if(!v)continue;let J=_r(hs,v),D=ni.get(v)||0,W=J+D,fe=S.args?.line_start!=null,Y=cs.get(v)===!0;if(W>=gs){let H=v.split("/").slice(-2).join("/"),V=(ls.get(v)||0)+1;if(ls.set(v,V),V===1)se(`${$.red} \u2716 Blocked: "${H}" read ${W}\xD7 \u2014 hard cap (${gs}) reached${$.reset}`);else if(V===2){se(`${$.red} \u2716 Escalated block: "${H}" \u2014 model ignored BLOCKED, injecting system warning${$.reset}`);let le={role:"user",content:`[SYSTEM WARNING] You already received a BLOCKED error for read_file("${v}") and tried again anyway. This file has reached its read cap (${gs}\xD7). Do NOT attempt to read it again. Use grep_search to find specific content, or proceed with what you already know.`};Q.push(le),b.push(le)}S.canExecute=!1,S.errorResult={role:"tool",content:`BLOCKED: read_file("${v}") denied \u2014 file already read ${W}\xD7 (hard cap: ${gs}). You have seen enough of this file. Use grep to find specific content or proceed with what you know.`,tool_call_id:S.callId}}else if(W>=1&&fe)if(Y){let H=v.split("/").slice(-2).join("/");console.log(`${$.cyan} \u21A9 Targeted re-read: "${H}" (line_start=${S.args.line_start}) \u2014 edit recovery${$.reset}`),cs.delete(v)}else{let H=S.args.line_start||1,V=S.args.line_end||H+350,le=On.get(v)||[],Ee=!1;for(let[Te,ie]of le){let Ke=Math.max(H,Te),mt=Math.min(V,ie);if(mt>Ke){let mn=mt-Ke,Oc=V-H||1;if(mn/Oc>=.7){let th=v.split("/").slice(-2).join("/");se(`${$.red} \u2716 Blocked duplicate read: "${th}" lines ${H}-${V} (\u226570% overlap with lines ${Te}-${ie} already in context)${$.reset}`),S.canExecute=!1,S.errorResult={role:"tool",content:`BLOCKED: read_file("${v}", lines ${H}-${V}) is a duplicate \u2014 lines ${Te}-${ie} are already in your context (\u226570% overlap). Use grep to find specific content instead of re-reading.`,tool_call_id:S.callId},Ee=!0;break}}}if(!Ee){let Te=le.length,ie=2;if(Te>=3){let mt=v.split("/").slice(-2).join("/");se(`${$.red} \u2716 Blocked file-scroll: "${mt}" \u2014 ${Te} sections already read. Use grep to find specific content.${$.reset}`),S.canExecute=!1,S.errorResult={role:"tool",content:`BLOCKED: read_file("${v}") denied \u2014 you have already read ${Te} different sections of this file (file-scroll pattern). You have seen most of this file. Use grep_search to find the exact lines you need instead of continuing to scroll.`,tool_call_id:S.callId}}else Te>=ie&&(S._scrollWarn={sectionCount:Te+1,path:v})}}else if(W>=1){let H=v.split("/").slice(-2).join("/"),V=(ls.get(v)||0)+1;if(ls.set(v,V),V===1)se(`${$.red} \u2716 Blocked unbounded re-read: "${H}" \u2014 already in context. Use line_start/line_end for specific sections.${$.reset}`);else if(V===2){se(`${$.red} \u2716 Escalated block: "${H}" \u2014 model ignored unbounded re-read block, injecting system warning${$.reset}`);let le={role:"user",content:`[SYSTEM WARNING] You already received a BLOCKED error for read_file("${v}") and tried again without line ranges. Full-file re-reads are permanently blocked for this file. Use line_start/line_end to read a specific section, or use grep_search to find what you need.`};Q.push(le),b.push(le)}S.canExecute=!1,S.errorResult={role:"tool",content:`BLOCKED: read_file("${v}") denied \u2014 file already in context (read ${W}\xD7). Use line_start/line_end to read a specific section instead of the full file.`,tool_call_id:S.callId}}S.canExecute&&ni.set(v,(ni.get(v)||0)+1)}for(let S of Ne)S.canExecute&&(S.fnName!=="ssh_exec"&&S.fnName!=="bash"||/\bsed\s+-n\b/.test(S.args?.command||"")&&(se(`${$.red} \u2716 Blocked sed -n: use grep -n "pattern" <file> | head -30 instead${$.reset}`),S.canExecute=!1,S.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:S.callId}));for(let S of Ne){if(!S.canExecute||S.fnName!=="write_file")continue;let v=S.args?.path,J=S.args?.content||"";if(v)try{let D=require("fs"),W=require("path").resolve(process.cwd(),v);if(D.existsSync(W)){let fe=D.statSync(W).size,Y=Buffer.byteLength(J,"utf8"),H=fe>0?Y/fe:1;if(H<.6&&fe>200){let V=v.split("/").slice(-2).join("/");console.log(`${$.red} \u2716 write_file shrink guard: "${V}" would shrink to ${Math.round(H*100)}% of original \u2014 likely context loss${$.reset}`),S.canExecute=!1,S.errorResult={role:"tool",content:`BLOCKED: write_file("${v}") denied \u2014 new content is only ${Math.round(H*100)}% of current file size (${fe} \u2192 ${Y} 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:S.callId}}}}catch{}}for(let S of Ne){if(!S.canExecute||S.fnName!=="grep")continue;let v=S.args?.path;if(!v)continue;let J=_r(He,v);if(J>=Ut){let D=v.split("/").slice(-2).join("/");se(`${$.red} \u2716 Blocked grep: "${D}" grepped ${J}\xD7 with different patterns \u2014 flood threshold exceeded${$.reset}`),S.canExecute=!1,S.errorResult={role:"tool",content:`BLOCKED: grep("${v}") denied \u2014 ${J} patterns already tried. Use existing results.`,tool_call_id:S.callId}}}if(us){let S=Ne.filter(D=>D.canExecute&&D.fnName==="ssh_exec"),v=Ne.some(D=>D.canExecute&&D.fnName!=="ssh_exec"),J=Z&&de<3;if(S.length>0&&!v&&J&&Tr<1)us=!1,Tr++,Mt=Math.max(0,zr-2),se(`${$.dim} [dual-block deadlock: SSH storm relaxed \u2014 allowing 1 SSH call (relax ${Tr}/1)]${$.reset}`);else for(let D of S)D.canExecute=!1,D.errorResult={role:"tool",content:`BLOCKED: ssh_exec denied \u2014 SSH storm (${zr}+ calls). Synthesize findings now.`,tool_call_id:D.callId}}if(Z&&de<3){for(let S of Ne)if(S.canExecute&&["bash","read_file","find_files"].includes(S.fnName)){de++;{let v=Qe(),{messages:J}=qt(b,v);b=J}se(`${$.yellow} \u26A0 Jarvis-local guard: blocking local ${S.fnName} \u2014 use ssh_exec on 94.130.37.43${$.reset}`),S.canExecute=!1,S.errorResult={role:"tool",content:`BLOCKED: ${S.fnName} denied \u2014 this is a server issue. Use ssh_exec on 94.130.37.43 instead.`,tool_call_id:S.callId};break}}if(to>=0){let S=Ne.filter(v=>v.canExecute).length;if(S>0&&(to-=S,to<0)){se(`${$.red} \u2716 Post-wipe tool budget exhausted \u2014 blocking all tool calls${$.reset}`);for(let J of Ne)J.canExecute&&(J.canExecute=!1,J.errorResult={role:"tool",content:"BLOCKED: post-wipe tool budget exhausted. No further tool calls are allowed. Summarise what was accomplished and stop.",tool_call_id:J.callId});let v={role:"user",content:"[SYSTEM] Post-wipe tool budget exhausted. All tool calls are now blocked. Respond with a final summary of what was done and stop \u2014 do not attempt any more tool calls."};Q.push(v),b.push(v)}}let ys=c?{skipSpinner:!0,skipSummaries:!0}:{},Zm=Ne.some(S=>S.fnName==="ask_user"),Rc=!ys.skipSummaries&&!Pe,si=null;Rc&&!Zm?(Pe=!0,ys.skipSpinner=!0,process.stdout.isTTY?(process.stdout.write(Pa(Ne,X,!1,"blink")),si=!0):Ft||process.stdout.write(Pa(Ne,X,!1)+`
|
|
957
|
+
`)):Rc&&(Pe=!0,ys.skipSpinner=!0),c&&c._paused&&c.resume();let{results:Cc,summaries:eh}=await O_(Ne,!0,{...ys,skipSummaries:!0});if(si&&(si=null,process.stdout.write(`\r\x1B[2K${Pa(Ne,X,!1)}
|
|
958
|
+
`)),!ys.skipSummaries){let S=eh.filter((D,W)=>!(Ne[W]&&Ne[W].fnName==="ask_user"));for(let D of S)console.log(D);console.log("");let v=Ne.filter(D=>D&&D.fnName!=="ask_user").map(D=>D.fnName),J=oe.record(0,v,F,P);J&&l_(J)}for(let S of Ne){if(S.canExecute||!S.errorResult)continue;let v=typeof S.errorResult.content=="string"?S.errorResult.content:"";if((v.startsWith("BLOCKED:")||v.startsWith("PLAN MODE:"))&&(dn++,dn>=kc)){se(`${$.red} \u2716 Loop abort: ${dn} consecutive blocked calls (pre-execution) \u2014 model not heeding BLOCKED messages${$.reset}`),c&&(c.stop(),c=null),i(null),Ue(X,E,P,F,K,{suppressHint:!0}),Fe(Q);return}}for(let S=0;S<Ne.length;S++){let v=Ne[S];if(!v.canExecute)continue;let J=Cc[S].content,D=J.split(`
|
|
959
|
+
`)[0],W=!D.startsWith("ERROR")&&!D.startsWith("CANCELLED")&&!D.startsWith("Command failed")&&!D.startsWith("EXIT");if(!W&&(v.fnName==="edit_file"||v.fnName==="patch_file")&&v.args?.path&&D.includes("old_text not found")&&cs.set(v.args.path,!0),W&&v.fnName==="write_file"&&v.args?.path){let Y=v.args.path.split("/").pop(),H=v.args.path.includes("/tests/")||v.args.path.includes("\\tests\\");if(/^(test_|demo_|temp_|tmp_|scratch_)/.test(Y)&&!H){se(`${$.yellow} \u26A0 Temp file: "${Y}" \u2014 delete with bash rm when done to keep the workspace clean${$.reset}`);let le={role:"user",content:`[HINT] "${v.args.path}" looks like a temporary test/demo file. Delete it with bash("rm ${v.args.path}") as soon as you're done \u2014 orphaned temp files count against session quality.`};Q.push(le),b.push(le)}}if(W&&["write_file","edit_file","patch_file"].includes(v.fnName)&&v.args&&v.args.path){cs.delete(v.args.path),P.add(v.args.path);let Y=Vs(L,v.args.path),H=v.args.path.split("/").slice(-2).join("/");if(Y===U){se(`${$.yellow} \u26A0 Loop warning: "${H}" edited ${Y}\xD7 \u2014 possible edit loop${$.reset}`);let V={role:"user",content:`[SYSTEM WARNING] "${v.args.path}" edited ${Y}\xD7. One more edit max, then move on.`};Q.push(V),b.push(V)}else if(Y>=re){se(`${$.red} \u2716 Loop abort: "${H}" edited ${Y}\xD7 \u2014 aborting to prevent runaway loop${$.reset}`),c&&(c.stop(),c=null),i(null),Ue(X,E,P,F,K,{suppressHint:!0}),Fe(Q);return}}if((v.fnName==="bash"||v.fnName==="ssh_exec")&&v.args&&v.args.command){let Y=v.args.command.replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),H=Vs(ee,Y);if(H===te){se(`${$.yellow} \u26A0 Loop warning: same bash command run ${H}\xD7 \u2014 possible debug loop${$.reset}`);let V={role:"user",content:`[SYSTEM WARNING] Same bash command ${H}\xD7. Debug loop detected \u2014 try a different approach.`};Q.push(V),b.push(V)}else if(H>=$e){se(`${$.red} \u2716 Loop abort: same bash command run ${H}\xD7 \u2014 aborting runaway debug loop${$.reset}`),c&&(c.stop(),c=null),i(null),Ue(X,E,P,F,K,{suppressHint:!0}),Fe(Q);return}}if(v.fnName==="ssh_exec"){if(Mt++,Mt>=Qm){se(`${$.red} \u2716 SSH storm abort: ${Mt} consecutive ssh_exec calls \u2014 aborting${$.reset}`),c&&(c.stop(),c=null),i(null),Ue(X,E,P,F,K,{suppressHint:!0}),Fe(Q);return}else if(Mt===zr){{let H=Qe(),{messages:V}=qt(b,H);b=V}us=!0,se(`${$.yellow} \u26A0 SSH storm warning: ${Mt} consecutive ssh_exec calls \u2014 blocking further SSH${$.reset}`);let Y={role:"user",content:`[SYSTEM WARNING] ${Mt} consecutive SSH calls. Synthesize findings now \u2014 no more SSH.`};Q.push(Y),b.push(Y)}}else v.canExecute&&(Mt=0);if(W&&v.fnName==="grep"&&v.args&&v.args.pattern){let Y=`${v.args.pattern}|${v.args.path||""}`,H=Vs(pe,Y);if(H===we){se(`${$.yellow} \u26A0 Loop warning: grep pattern "${v.args.pattern.slice(0,40)}" run ${H}\xD7 \u2014 possible search loop${$.reset}`);let V={role:"user",content:`[SYSTEM WARNING] Same grep pattern ${H}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};Q.push(V),b.push(V)}else if(H>=be){se(`${$.red} \u2716 Loop abort: grep pattern run ${H}\xD7 \u2014 aborting runaway search loop${$.reset}`),c&&(c.stop(),c=null),i(null),Ue(X,E,P,F,K,{suppressHint:!0}),Fe(Q);return}if(v.args.path){let V=Vs(He,v.args.path);if(V===Ge){let le=v.args.path.split("/").slice(-2).join("/");se(`${$.yellow} \u26A0 Loop warning: "${le}" grepped ${V}\xD7 with different patterns \u2014 context flood risk${$.reset}`);let Ee={role:"user",content:`[SYSTEM WARNING] "${v.args.path}" grepped ${V}\xD7 \u2014 file already in context. Use existing data, stop searching.`};Q.push(Ee),b.push(Ee)}}}if(W&&(v.fnName==="bash"||v.fnName==="ssh_exec")&&J.includes('"valid":true')){{let H=Qe();if(Nt(b,H).percentage>=60){let{messages:le,tokensRemoved:Ee}=qt(b,H);Ee>0&&(b=le,console.log(`${$.dim} [pre-stop-compress \u2014 ~${Ee} tokens freed before STOP injection, now ${Math.round(Nt(b,H).percentage)}%]${$.reset}`))}}let Y={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.'};Q.push(Y),b.push(Y),console.log(`${$.cyan} \u2713 Health-check stop signal detected \u2014 injecting STOP instruction${$.reset}`)}if(J.startsWith("BLOCKED:")){if(dn++,dn>=kc){se(`${$.red} \u2716 Loop abort: ${dn} consecutive blocked calls \u2014 model not heeding BLOCKED messages${$.reset}`),c&&(c.stop(),c=null),i(null),Ue(X,E,P,F,K,{suppressHint:!0}),Fe(Q);return}}else dn=0;if(W)un=0,Jr=!0;else if(un++,un===zm){se(`${$.yellow} \u26A0 Loop warning: ${un} consecutive tool errors \u2014 possible stuck loop${$.reset}`);let Y={role:"user",content:`[SYSTEM WARNING] ${un} consecutive errors. Stuck loop \u2014 try fundamentally different approach or declare done.`};Q.push(Y),b.push(Y)}else if(un>=Xm){se(`${$.red} \u2716 Loop abort: ${un} consecutive errors \u2014 aborting stuck loop${$.reset}`),c&&(c.stop(),c=null),i(null),Ue(X,E,P,F,K,{suppressHint:!0}),Fe(Q);return}if(W&&v.fnName==="read_file"&&v.args&&v.args.path){F.add(v.args.path);let Y=Vs(hs,v.args.path);if(v.args.line_start!=null){let le=v.args.line_start||1,Ee=v.args.line_end||le+350;On.has(v.args.path)||On.set(v.args.path,[]),On.get(v.args.path).push([le,Ee])}if(v._scrollWarn){let{sectionCount:le,path:Ee}=v._scrollWarn,Te={role:"user",content:`[SYSTEM WARNING] "${Ee}" \u2014 you have now read ${le} different sections of this file. This is a file-scroll pattern. Stop reading sections and use grep_search to find the specific lines you need instead.`};Q.push(Te),b.push(Te),se(`${$.yellow} \u26A0 Scroll warning: "${Ee.split("/").slice(-2).join("/")}" \u2014 ${le} sections read \u2014 use grep instead${$.reset}`)}let H=v.args.path.split("/").slice(-2).join("/"),V=!v.args?.line_start&&!v.args?.line_end;if(V&&Y===Kr){{let Ee=Qe();if(Nt(b,Ee).percentage>=60){let{messages:ie}=qt(b,Ee);b=ie}}se(`${$.yellow} \u26A0 Loop warning: "${H}" read unbounded ${Y}\xD7 \u2014 use line_start/line_end${$.reset}`);let le={role:"user",content:`[SYSTEM WARNING] "${v.args.path}" read ${Y}\xD7 without line ranges. Use line_start/line_end to read specific sections \u2014 do not re-read the full file.`};Q.push(le),b.push(le)}else if(V&&Y>=Ym){se(`${$.red} \u2716 Loop abort: "${H}" read unbounded ${Y}\xD7 \u2014 aborting runaway read loop${$.reset}`),c&&(c.stop(),c=null),i(null),Ue(X,E,P,F,K,{suppressHint:!0}),Fe(Q);return}}if(v.fnName==="spawn_agents"){let Y=(J.match(/\bStatus: done\b/g)||[]).length;if((J.match(/\bStatus: truncated\b/g)||[]).length>0&&Y===0){if(fn++,fn===Jm){se(`${$.yellow} \u26A0 Swarm warning: all sub-agents hit iteration limit ${fn}\xD7 in a row${$.reset}`);let V={role:"user",content:`[SYSTEM WARNING] Sub-agents truncated ${fn}\xD7 in a row. Stop spawning \u2014 try different approach or report findings.`};Q.push(V),b.push(V)}else if(fn>=Vm){console.log(`${$.red} \u2716 Swarm abort: all sub-agents hit iteration limit ${fn}\xD7 \u2014 aborting stuck swarm${$.reset}`),c&&(c.stop(),c=null),i(null),Ue(X,E,P,F,K,{suppressHint:!0}),Fe(Q);return}}else Y>0&&(fn=0)}}for(let S of Cc)Q.push(S),b.push(S);{let S=Qe();if(Nt(b,S).percentage>=78){let{messages:J,tokensRemoved:D}=qt(b,S);D>0&&(b=J,console.log(`${$.dim} [auto-compressed \u2014 ~${D} tokens freed, now ${Math.round(Nt(b,S).percentage)}%]${$.reset}`))}}let Ac=M_();if(Ac){let S={role:"user",content:`[User note mid-run]: ${Ac}`};Q.push(S),b.push(S),console.log(`${$.cyan} \u270E Context added${$.reset}`)}}if(ft>=go){c&&(c.stop(),c=null),i(null),Ue(X,E,P,F,K),Fe(Q),Qf(Q);let{getActiveProviderName:je}=Re();if(je()==="ollama"&&Xr<vc){if(P.size===0&&!Jr){console.log(`${$.yellow} \u26A0 Max iterations reached with no progress. Stopping.${$.reset}`);break e}Xr++,go=20,console.log(`${$.dim} \u2500\u2500 auto-extending (+20 turns, ext ${Xr}/${vc}) \u2500\u2500${$.reset}`);continue e}if(console.log(`
|
|
960
|
+
${$.yellow}\u26A0 Max iterations reached.${$.reset}`),await up(" Continue for 20 more turns?")){go=20;continue e}console.log(`${$.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${$.reset}`)}break e}}xp.exports={processInput:H_,clearConversation:L_,getConversationLength:j_,getConversationMessages:q_,setConversationMessages:F_,setAbortSignalGetter:m_,setMaxIterations:p_,invalidateSystemPromptCache:Ha,clearToolFilterCache:x_,getCachedFilteredTools:mp,buildSystemPrompt:bp,getProjectContextHash:hp,buildUserContent:pp,detectAndTruncateLoop:Ua,injectMidRunNote:N_,resetSessionTracking:_p}});var Re=G((pS,Tp)=>{var{OllamaProvider:G_}=tl(),{OpenAIProvider:K_}=bl(),{AnthropicProvider:Y_}=vl(),{GeminiProvider:z_}=Rl(),{LocalProvider:X_}=Ol(),{checkBudget:J_}=Hn(),za={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"}},kp={};for(let[t,e]of Object.entries(za))for(let n of Object.values(e))kp[n]=t;function vp(t,e){let n=kp[t];return n&&za[n][e]||t}var ze={},dt=null,We=null,so=[];function St(){if(Object.keys(ze).length>0)return;ds("ollama",new G_),ds("openai",new K_),ds("anthropic",new Y_),ds("gemini",new z_),ds("local",new X_);let t=process.env.DEFAULT_PROVIDER||"ollama",e=process.env.DEFAULT_MODEL||null;ze[t]?(dt=t,We=e||ze[t].defaultModel):(dt="ollama",We="kimi-k2.5");let n=process.env.FALLBACK_CHAIN;n&&(so=n.split(",").map(o=>o.trim()).filter(Boolean))}function ds(t,e){ze[t]=e}function V_(t){return St(),ze[t]||null}function Xa(){return St(),ze[dt]||null}function Q_(){return St(),dt}function Z_(){return St(),We}function ex(){St();let t=Xa();if(!t)return{id:We,name:We,provider:dt};let e=t.getModel(We);return e?{...e,provider:dt}:{id:We,name:We,provider:dt}}function Sp(t){if(!t)return{provider:null,model:null};let e=t.indexOf(":");if(e>0){let n=t.slice(0,e);if(ze[n]||["ollama","openai","anthropic","gemini","local"].includes(n))return{provider:n,model:t.slice(e+1)}}return{provider:null,model:t}}function tx(t){St();let{provider:e,model:n}=Sp(t);if(e){let s=ze[e];return s&&(s.getModel(n)||e==="local"||e==="ollama")?(dt=e,We=n,Ar(),!0):!1}let o=Xa();if(o&&o.getModel(n))return We=n,Ar(),!0;for(let[s,r]of Object.entries(ze))if(r.getModel(n))return dt=s,We=n,Ar(),!0;return!1}function Ar(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=ve();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=Ve();t()}catch{}}function nx(){St();let t=new Set;for(let e of Object.values(ze))for(let n of e.getModelNames())t.add(n);return Array.from(t)}function sx(){return St(),Object.entries(ze).map(([t,e])=>({provider:t,configured:e.isConfigured(),models:Object.values(e.getModels()).map(n=>({...n,active:t===dt&&n.id===We}))}))}function ox(){St();let t=[];for(let[e,n]of Object.entries(ze)){let o=n.isConfigured();for(let s of Object.values(n.getModels()))t.push({spec:`${e}:${s.id}`,name:s.name,provider:e,configured:o})}return t}function rx(t){so=Array.isArray(t)?t:[]}function ix(){return[...so]}function ax(t){let e=t.message||"",n=t.code||"";return!!(e.includes("429")||e.includes("500")||e.includes("502")||e.includes("503")||e.includes("504")||n==="ECONNABORTED"||n==="ETIMEDOUT"||n==="ECONNREFUSED"||n==="ECONNRESET"||n==="EHOSTUNREACH"||n==="ENETUNREACH"||n==="EPIPE"||n==="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 Ep(t){let e=[dt,...so.filter(r=>r!==dt)],n,o=0,s=0;for(let r=0;r<e.length;r++){let i=e[r],c=ze[i];if(!c||!c.isConfigured())continue;s++;let l=J_(i);if(!l.allowed){o++,n=new Error(`Budget limit reached for ${i}: $${l.spent.toFixed(2)} / $${l.limit.toFixed(2)}`);continue}try{let u=r>0,d=u?vp(We,i):We;return u&&d!==We&&process.stderr.write(` [fallback: ${i}:${d}]
|
|
961
|
+
`),await t(c,i,d)}catch(u){if(n=u,ax(u)&&r<e.length-1)continue;throw u}}throw o>0&&o===s?new Error("All providers are over budget. Use /budget to check limits or /budget <provider> off to remove a limit."):s===0?new Error("No configured provider available"):n||new Error("No configured provider available")}async function cx(t,e,n={}){return St(),Ep((o,s,r)=>o.stream(t,e,{model:r,signal:n.signal,...n}))}async function lx(t,e,n={}){if(St(),n.provider){let o=ze[n.provider];if(!o||!o.isConfigured())throw new Error(`Provider '${n.provider}' is not available`);let s={model:n.model||We,...n};try{return await o.chat(t,e,s)}catch(r){if(typeof o.stream=="function")try{return await o.stream(t,e,{...s,onToken:()=>{}})}catch{}throw r}}return Ep(async(o,s,r)=>{try{return await o.chat(t,e,{model:r,...n})}catch(i){if(typeof o.stream=="function")try{return await o.stream(t,e,{model:r,...n,onToken:()=>{}})}catch{}throw i}})}function ux(){St();let t=[];for(let[e,n]of Object.entries(ze))n.isConfigured()&&t.push({name:e,models:Object.values(n.getModels())});return t}function dx(){for(let t of Object.keys(ze))delete ze[t];dt=null,We=null,so=[]}Tp.exports={registerProvider:ds,getProvider:V_,getActiveProvider:Xa,getActiveProviderName:Q_,getActiveModelId:Z_,getActiveModel:ex,setActiveModel:tx,getModelNames:nx,parseModelSpec:Sp,listProviders:sx,listAllModels:ox,callStream:cx,callChat:lx,getConfiguredProviders:ux,setFallbackChain:rx,getFallbackChain:ix,resolveModelForProvider:vp,MODEL_EQUIVALENTS:za,_reset:dx}});var Va=G((mS,Rp)=>{"use strict";var Xt=require("fs"),Or=require("path"),fx=require("readline"),ye="\x1B[0m",Nr="\x1B[1m",Ze="\x1B[2m",Mr="\x1B[33m",Ja="\x1B[36m",oo="\x1B[32m";function px(t){return(e,n="")=>new Promise(o=>{let s=n?` ${Ze}[${n}]${ye}`:"";t.question(` ${Ja}${e}${s}${ye}: `,r=>o(r.trim()||n))})}function ro(t,e){return new Promise(n=>{e&&e.pause(),process.stdout.write(` ${Ja}${t}${ye}: `);let o=process.stdin,s=o.isRaw,r="";o.setRawMode(!0),o.resume(),o.setEncoding("utf8");let i=c=>{c==="\r"||c===`
|
|
959
962
|
`?(o.setRawMode(s||!1),o.removeListener("data",i),process.stdout.write(`
|
|
960
963
|
`),e&&e.resume(),n(r)):c===""?(process.stdout.write(`
|
|
961
|
-
`),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
|
|
962
|
-
`),console.log(` ${
|
|
963
|
-
`),console.log(` ${
|
|
964
|
-
${
|
|
964
|
+
`),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 mx({rl:t=null,force:e=!1}={}){if(!e){let m=Xt.existsSync(Or.join(process.cwd(),".env"))||Xt.existsSync(Or.join(__dirname,"..",".env")),h=process.env.ANTHROPIC_API_KEY||process.env.OPENAI_API_KEY||process.env.GEMINI_API_KEY||process.env.OPENROUTER_API_KEY,p=process.env.DEFAULT_PROVIDER||process.env.DEFAULT_MODEL;if(m||h||p)return}let n=!t,o=t||fx.createInterface({input:process.stdin,output:process.stdout,terminal:!0}),s=px(o),r=!e;console.log(),console.log(r?`${Mr}${Nr} \u2726 Welcome to nex-code! No configuration found.${ye}`:`${Ja}${Nr} \u2726 nex-code \u2014 Provider & API Key Setup${ye}`),console.log(`${Ze} \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500${ye}`),r&&console.log(` Let's set you up in 60 seconds.
|
|
965
|
+
`),console.log(` ${Nr}Which AI provider do you want to use?${ye}
|
|
966
|
+
`),console.log(` ${oo}1)${ye} ${Nr}Ollama Cloud${ye} ${Ze}recommended \u2014 devstral-2:123b, no API key needed${ye}`),console.log(` ${Ze} (also works with a local Ollama server)${ye}`),console.log(` ${Ze}2) Anthropic Claude (claude-sonnet-4-6 etc.)${ye}`),console.log(` ${Ze}3) OpenAI GPT-4o, GPT-4.1 etc.${ye}`),console.log(` ${Ze}4) Gemini Google Gemini 2.x${ye}`),console.log(` ${Ze}5) Skip / Cancel${ye}`),console.log();let i=await s("Enter number","1"),c=[];if(i==="5"){n&&o.close(),console.log(`
|
|
967
|
+
${Ze} Cancelled \u2014 no changes made.${ye}
|
|
965
968
|
`);return}if(i==="1"){console.log(),console.log(`
|
|
966
|
-
${
|
|
967
|
-
`);let m=await
|
|
968
|
-
${
|
|
969
|
-
`);return}let h=await s("Default model","claude-sonnet-4-6");c.push("DEFAULT_PROVIDER=anthropic",`DEFAULT_MODEL=${h}`,`ANTHROPIC_API_KEY=${m}`),process.env.DEFAULT_PROVIDER="anthropic",process.env.DEFAULT_MODEL=h,process.env.ANTHROPIC_API_KEY=m}else if(i==="3"){console.log(),console.log(` ${
|
|
970
|
-
${
|
|
971
|
-
`);return}let h=await s("Default model","gpt-4o");c.push("DEFAULT_PROVIDER=openai",`DEFAULT_MODEL=${h}`,`OPENAI_API_KEY=${m}`),process.env.DEFAULT_PROVIDER="openai",process.env.DEFAULT_MODEL=h,process.env.OPENAI_API_KEY=m}else if(i==="4"){console.log(),console.log(` ${
|
|
972
|
-
${
|
|
973
|
-
`);return}let h=await s("Default model","gemini-2.0-flash");c.push("DEFAULT_PROVIDER=gemini",`DEFAULT_MODEL=${h}`,`GEMINI_API_KEY=${m}`),process.env.DEFAULT_PROVIDER="gemini",process.env.DEFAULT_MODEL=h,process.env.GEMINI_API_KEY=m}if(console.log(),(await s("Add Perplexity key for grounded web search? (y/N)","n")).toLowerCase()==="y"){console.log(` ${
|
|
974
|
-
|
|
975
|
-
`:"";
|
|
969
|
+
${oo}Ollama Cloud${ye} ${Ze}(recommended): uses ollama.com API \u2014 flat-rate, 47+ models.${ye}`),console.log(` ${Ze}Get your API key at: https://ollama.com/settings/api-keys${ye}
|
|
970
|
+
`);let m=await ro("OLLAMA_API_KEY (leave blank for local)",t),h=m?"https://ollama.com":await s("Ollama host","http://localhost:11434"),p=await s("Default model",m?"devstral-2:123b":"qwen3-coder");c.push("DEFAULT_PROVIDER=ollama",`DEFAULT_MODEL=${p}`,`OLLAMA_HOST=${h}`),m&&c.push(`OLLAMA_API_KEY=${m}`),process.env.DEFAULT_PROVIDER="ollama",process.env.DEFAULT_MODEL=p,process.env.OLLAMA_HOST=h,m&&(process.env.OLLAMA_API_KEY=m)}else if(i==="2"){console.log(),console.log(` ${Ze}Get your key: https://console.anthropic.com/settings/keys${ye}`);let m=await ro("ANTHROPIC_API_KEY",t);if(!m){n&&o.close(),console.log(`
|
|
971
|
+
${Mr} No key entered \u2014 cancelled.${ye}
|
|
972
|
+
`);return}let h=await s("Default model","claude-sonnet-4-6");c.push("DEFAULT_PROVIDER=anthropic",`DEFAULT_MODEL=${h}`,`ANTHROPIC_API_KEY=${m}`),process.env.DEFAULT_PROVIDER="anthropic",process.env.DEFAULT_MODEL=h,process.env.ANTHROPIC_API_KEY=m}else if(i==="3"){console.log(),console.log(` ${Ze}Get your key: https://platform.openai.com/api-keys${ye}`);let m=await ro("OPENAI_API_KEY",t);if(!m){n&&o.close(),console.log(`
|
|
973
|
+
${Mr} No key entered \u2014 cancelled.${ye}
|
|
974
|
+
`);return}let h=await s("Default model","gpt-4o");c.push("DEFAULT_PROVIDER=openai",`DEFAULT_MODEL=${h}`,`OPENAI_API_KEY=${m}`),process.env.DEFAULT_PROVIDER="openai",process.env.DEFAULT_MODEL=h,process.env.OPENAI_API_KEY=m}else if(i==="4"){console.log(),console.log(` ${Ze}Get your key: https://aistudio.google.com/app/apikey${ye}`);let m=await ro("GEMINI_API_KEY",t);if(!m){n&&o.close(),console.log(`
|
|
975
|
+
${Mr} No key entered \u2014 cancelled.${ye}
|
|
976
|
+
`);return}let h=await s("Default model","gemini-2.0-flash");c.push("DEFAULT_PROVIDER=gemini",`DEFAULT_MODEL=${h}`,`GEMINI_API_KEY=${m}`),process.env.DEFAULT_PROVIDER="gemini",process.env.DEFAULT_MODEL=h,process.env.GEMINI_API_KEY=m}if(console.log(),(await s("Add Perplexity key for grounded web search? (y/N)","n")).toLowerCase()==="y"){console.log(` ${Ze}Get your key: https://www.perplexity.ai/settings/api${ye}`);let m=await ro("PERPLEXITY_API_KEY",t);m&&(c.push(`PERPLEXITY_API_KEY=${m}`),process.env.PERPLEXITY_API_KEY=m)}console.log();let u=Or.join(process.cwd(),".env"),d=(Xt.existsSync(u),"y"),f=await s(`Save to ${u}? (Y/n)`,d);if(n&&o.close(),f.toLowerCase()!=="n"){let m=Xt.existsSync(u)?Xt.readFileSync(u,"utf-8").trimEnd()+`
|
|
977
|
+
|
|
978
|
+
`:"";Xt.writeFileSync(u,m+c.join(`
|
|
976
979
|
`)+`
|
|
977
|
-
`);let h=
|
|
978
|
-
`).some(g=>g.trim()===".env")||
|
|
980
|
+
`);let h=Or.join(process.cwd(),".gitignore");Xt.existsSync(h)&&(Xt.readFileSync(h,"utf-8").split(`
|
|
981
|
+
`).some(g=>g.trim()===".env")||Xt.appendFileSync(h,`
|
|
979
982
|
.env
|
|
980
983
|
`)),console.log(`
|
|
981
|
-
${
|
|
982
|
-
${
|
|
983
|
-
`)}
|
|
984
|
-
`)}function
|
|
985
|
-
`);console.log=t,console.warn=t,console.info=t;let{setConfirmHook:e}=
|
|
986
|
-
`))}function
|
|
987
|
-
`).replace(/[\x00-\x08\x0b-\x1f\x7f]/g,o=>`<${o.charCodeAt(0).toString(16).padStart(2,"0")}>`);
|
|
988
|
-
`)}function
|
|
989
|
-
`)&&p.length>4&&!p.includes("\r"))
|
|
990
|
-
`)&&!p.includes("\r")&&!/[\x00-\x1f\x7f]/.test(p))return
|
|
991
|
-
`);for(let
|
|
992
|
-
`);process.stdout.write(`\x1B[${m}A`)}let w=[];w.push(` ${
|
|
993
|
-
`);process.stdout.write(
|
|
994
|
-
`),m=w.length}t.pause();let p=process.stdin.isRaw;process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume();function g(){process.stdin.removeListener("keypress",y),process.stdin.isTTY&&p!==void 0&&process.stdin.setRawMode(p),t.resume()}function y(w,
|
|
984
|
+
${oo} \u2713 Saved to ${u}${ye}`),c.some(p=>p.includes("API_KEY"))&&console.log(`${Ze} (key stored locally \u2014 never committed)${ye}`)}if(process.env.DEFAULT_PROVIDER)try{let{setActiveModel:m}=Re(),h=process.env.DEFAULT_MODEL?`${process.env.DEFAULT_PROVIDER}:${process.env.DEFAULT_MODEL}`:process.env.DEFAULT_PROVIDER;m(h),console.log(`${oo} \u2713 Switched to ${h} for this session${ye}`)}catch{}console.log(`
|
|
985
|
+
${oo} \u2713 Setup complete!${ye}
|
|
986
|
+
`)}Rp.exports={runSetupWizard:mx}});var Ap=G((hS,Cp)=>{"use strict";var hx=require("readline");function Nn(t){process.stdout.write(JSON.stringify(t)+`
|
|
987
|
+
`)}function gx(){process.env.NEX_SERVER="1";let t=(...c)=>process.stderr.write(c.map(String).join(" ")+`
|
|
988
|
+
`);console.log=t,console.warn=t,console.info=t;let{setConfirmHook:e}=Je(),n=new Map,o=0;e((c,l)=>{let u="cfm-"+ ++o,d=l?.toolName||"",f=!1;try{let{isCritical:m}=Je();f=m(c)}catch{}return Nn({type:"confirm_request",id:u,question:c,tool:d,critical:f}),new Promise(m=>{n.set(u,m)})});let s=null,r={onToken(c){s&&Nn({type:"token",id:s,text:c})},onThinkingToken(){},onToolStart(c,l){s&&Nn({type:"tool_start",id:s,tool:c,args:l||{}})},onToolEnd(c,l,u){s&&Nn({type:"tool_end",id:s,tool:c,summary:l||"",ok:!!u})}},i=hx.createInterface({input:process.stdin,output:null,terminal:!1});Nn({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();s=d;let{processInput:f}=ve();try{await f(u.text,r),Nn({type:"done",id:d})}catch(m){Nn({type:"error",id:d,message:m?.message||String(m)})}finally{s=null}break}case"confirm":{let d=n.get(u.id);d&&(n.delete(u.id),d(!!u.answer));break}case"cancel":{for(let[d,f]of n)n.delete(d),f(!1);break}case"clear":{let{clearConversation:d}=ve();d();for(let[f,m]of n)n.delete(f),m(!1);break}default:break}}),i.on("close",()=>{process.exit(0)})}Cp.exports={startServerMode:gx}});var Pp=G((gS,Mp)=>{"use strict";var Pr=require("fs"),{T:Pt,isDark:$x}=hn(),yt="\x1B[0m",yx=!$x,wx=process.env.FOOTER_DEBUG==="1"||process.env.FOOTER_DEBUG==="2",bx=process.env.FOOTER_DEBUG==="2",fs=null;function cn(...t){wx&&(fs||(fs=Pr.openSync("/tmp/footer-debug.log","w")),Pr.writeSync(fs,t.join(" ")+`
|
|
989
|
+
`))}function Op(t,e){if(!bx||typeof e!="string")return;fs||(fs=Pr.openSync("/tmp/footer-debug.log","w"));let n=e.replace(/\x1b\[([^a-zA-Z]*)([a-zA-Z])/g,(o,s,r)=>`<ESC[${s}${r}>`).replace(/\x1b([^[])/g,(o,s)=>`<ESC${s}>`).replace(/\r/g,"<CR>").replace(/\n/g,`<LF>
|
|
990
|
+
`).replace(/[\x00-\x08\x0b-\x1f\x7f]/g,o=>`<${o.charCodeAt(0).toString(16).padStart(2,"0")}>`);Pr.writeSync(fs,`${t}: ${n}
|
|
991
|
+
`)}function Np(t){return t.replace(/\x1b\[[^a-zA-Z]*[a-zA-Z]/g,"").length}var Qa=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:n,project:o,mode:s}={}){e!==void 0&&(this._statusModel=e),n!==void 0&&(this._statusBranch=n),o!==void 0&&(this._statusProject=o),s!==void 0&&(this._statusMode=s),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,n=1){return`\x1B[${e};${n}H`}_statusLine(){let e=this._cols,n=this._statusModel,o=this._statusBranch,s=this._statusProject,r=this._statusMode;if(!n)return Pt.footer_sep+"\u2500".repeat(e)+yt;let i=` ${Pt.footer_divider}\xB7${yt} `,c=[];n&&c.push(`${Pt.footer_model}${n}${yt}`),o&&c.push(`${Pt.footer_branch}${o}${yt}`),s&&c.push(`${Pt.footer_project}${s}${yt}`);let l=c.join(i),u=[n,o,s].filter(Boolean).join(" \xB7 ").length,d="\u2500 ";if(r){let h=r.length,p=Math.max(0,e-d.length-u-1-1-h-3),g="\u2500".repeat(p);return`${Pt.footer_sep}${d}${yt}${l}${Pt.footer_sep} ${g} ${yt}${Pt.footer_mode}${r}${yt}${Pt.footer_sep} \u2500\u2500${yt}`}let f=Math.max(0,e-d.length-u-2),m="\u2500".repeat(f);return`${Pt.footer_sep}${d}${yt}${l}${Pt.footer_sep} ${m}${yt}`}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(yx)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 Op("RAW",e),this._origWrite?this._origWrite(e):process.stdout.write(e)}_relayout(e){if(!this._origWrite)return;let n=this._origWrite,o=this._rows,s=this._cols,r=Math.max(1,o-2);cn("RELAYOUT:",e,"rows="+o,"cols="+s,"scrollEnd="+r,"cursorOnInput="+this._cursorOnInputRow),this._prevTermRows=o,this._prevTermCols=s;let i=Math.min(this._lastOutputRow+1,r+1),c="";for(let l=i;l<=o;l++)c+=this._goto(l)+"\x1B[2K";n(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 n=this,o=process.stdout.write.bind(process.stdout);this._origWrite=o,process.stdout.write=function(p,...g){if(Op("PATCH",p),!n._active||typeof p!="string")return o(p,...g);if(n._inRefreshLine){let k=p.replace(/\n/g,"");return k?o(k,...g):!0}if(n._cursorOnInputRow)if(p.includes(`
|
|
992
|
+
`)&&p.length>4&&!p.includes("\r"))cn("STDOUT: agent output, leaving input row, data="+JSON.stringify(p).slice(0,100)),n._cursorOnInputRow=!1,o(n._goto(Math.min(n._lastOutputRow+1,n._scrollEnd)));else{if(p.length<=4&&!p.includes(`
|
|
993
|
+
`)&&!p.includes("\r")&&!/[\x00-\x1f\x7f]/.test(p))return cn("STDOUT: char intercept:",JSON.stringify(p)),n._origRefreshLine&&n._doRefreshLine(),!0;{let k=p.replace(/\n/g,"");return k?o(k,...g):!0}}let y=n._cols||80,w=0,x=p.split(`
|
|
994
|
+
`);for(let k=0;k<x.length;k++){let _=Np(x[k]);_>0&&(w+=Math.floor((_-1)/y))}let R=x.length-1;return R+w>0&&(n._lastOutputRow=Math.min(n._lastOutputRow+R+w,n._scrollEnd)),o(p,...g)},this._cursorOnInputRow=!1,this._origStderrWrite=process.stderr.write.bind(process.stderr),process.stderr.write=function(p,...g){if(!n._active)return n._origStderrWrite(p,...g);if(typeof p=="string"&&p.includes("\r")){let y=Math.min(n._lastOutputRow+1,n._scrollEnd);if(n._cursorOnInputRow){n._origWrite("\x1B7"),n._origWrite(n._goto(y));let w=n._origStderrWrite(p,...g);return n._origWrite("\x1B8"),w}n._origWrite(n._goto(y))}return n._origStderrWrite(p,...g)},this._origLog=console.log,this._origError=console.error;function s(...p){if(!n._active){n._origLog(...p);return}n._origWrite(n._goto(Math.min(n._lastOutputRow+1,n._scrollEnd))),n._cursorOnInputRow=!1,n._origLog(...p),n.drawFooter(),o(n._goto(n._rowInput)+"\x1B[2K"),n._cursorOnInputRow=!0}function r(...p){if(!n._active){n._origError(...p);return}n._origWrite(n._goto(Math.min(n._lastOutputRow+1,n._scrollEnd))),n._cursorOnInputRow=!1,n._origError(...p),n.drawFooter(),o(n._goto(n._rowInput)+"\x1B[2K"),n._cursorOnInputRow=!0}console.log=s,console.error=r,this._origSetPr=e.setPrompt.bind(e),e.setPrompt=function(p){n._origSetPr(p),n._active&&n.drawFooter(p)},this._origPrompt=e.prompt.bind(e),e.prompt=function(p){if(!n._active)return n._origPrompt(p);cn("PROMPT: goto rowInput="+n._rowInput),e.prevRows=0,o(n._goto(n._rowInput)+yt+"\x1B[2K"),n._cursorOnInputRow=!0,n._origPrompt(p)};let i=e.question.bind(e);e.question=function(p,g){if(!n._active)return i(p,g);o(n._goto(n._rowInput)+"\x1B[2K"),e.prevRows=0,n._cursorOnInputRow=!0,i(p,y=>{o(n._goto(n._rowInput)+"\x1B[2K"),n._cursorOnInputRow=!1,n.drawFooter(),g(y)})};let c=Object.getPrototypeOf(e),l=Object.getOwnPropertySymbols(c).find(p=>p.toString()==="Symbol(_refreshLine)"),u=l?c[l].bind(e):e._refreshLine?e._refreshLine.bind(e):null;if(this._origRefreshLine=u,this._doRefreshLine=function(){if(!n._active||!u)return;if(n._rows!==n._prevTermRows||n._cols!==n._prevTermCols){n._dirty=!0;return}e.prevRows=0,o(n._goto(n._rowInput)+yt+"\x1B[2K");let p=n._cols,g=e._prompt||"",y=Np(g),w=p-y-1;n._inRefreshLine=!0;try{if(e.line.length<=w){cn("REFRESH: short line, len="+e.line.length),u();return}cn("REFRESH: long line, len="+e.line.length+", max="+w);let x=e.line,R=e.cursor,k=Math.max(1,w-1),_=Math.max(0,R-k),b=(_>0?"\xAB":"")+x.slice(_,_+k+(_>0?0:1));e.line=b,e.cursor=b.length,u(),e.line=x,e.cursor=R}finally{n._inRefreshLine=!1}},u){let p=this._doRefreshLine;l&&Object.defineProperty(e,l,{value:p,writable:!0,configurable:!0}),e._refreshLine=p}e.on("line",()=>{n._active&&(cn("LINE: leaving input row"),n._cursorOnInputRow=!1,o(n._goto(n._rowInput)+"\x1B[2K"),o(n._goto(Math.min(n._lastOutputRow+1,n._scrollEnd))),n.drawFooter())});let d=null,f=null,m=()=>{d=null,n._relayout("resize"),f&&clearTimeout(f),f=setTimeout(()=>{f=null,n._relayout("resize-cleanup")},300)},h=()=>{n._dirty=!0,d&&clearTimeout(d),d=setTimeout(m,80)};process.stdout.on("resize",h),this._offResize=()=>{process.stdout.off("resize",h),d&&(clearTimeout(d),d=null),f&&(clearTimeout(f),f=null)},this._consistencyTimer=setInterval(()=>{if(!n._active)return;let p=n._rows,g=n._cols;(n._dirty||p!==n._prevTermRows||g!==n._prevTermCols)&&(cn("CONSISTENCY: dirty="+n._dirty+" rows="+p+"/"+n._prevTermRows+" cols="+g+"/"+n._prevTermCols),n._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(n=>n.toString()==="Symbol(_refreshLine)");e&&delete this._rl[e],delete this._rl._refreshLine,this._origRefreshLine=null}this._eraseStatus(),this._clearScrollRegion(),this._origWrite=null}}};Mp.exports={StickyFooter:Qa}});var Dp=G(($S,Lp)=>{var{C:Oe}=Me(),{listProviders:_x,getActiveProviderName:xx,getActiveModelId:kx,setActiveModel:vx}=Re();function Ip(t,e,n={}){let{title:o="Select",hint:s="\u2191\u2193 navigate \xB7 Enter select \xB7 Esc cancel"}=n;return new Promise(r=>{let i=e.map((w,x)=>w.isHeader?-1:x).filter(w=>w>=0);if(i.length===0){r(null);return}let c=e.findIndex(w=>w.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 w=i[l];return w<d?d=w:w>=d+u&&(d=w-u+1),{start:d,end:Math.min(e.length,d+u)}}let m=0;function h(){if(m>0){process.stdout.write(`\x1B[${m}A`);for(let _=0;_<m;_++)process.stdout.write(`\x1B[2K
|
|
995
|
+
`);process.stdout.write(`\x1B[${m}A`)}let w=[];w.push(` ${Oe.bold}${Oe.cyan}${o}${Oe.reset}`),w.push(` ${Oe.dim}${s}${Oe.reset}`),w.push("");let{start:x,end:R}=f();x>0&&w.push(` ${Oe.dim}\u2191 more${Oe.reset}`);for(let _=x;_<R;_++){let b=e[_];if(b.isHeader){w.push(` ${Oe.bold}${Oe.dim}${b.label}${Oe.reset}`);continue}let A=i[l]===_,M=A?`${Oe.cyan}> `:" ",O=b.isCurrent?` ${Oe.yellow}<current>${Oe.reset}`:"";A?w.push(`${M}${Oe.bold}${b.label}${Oe.reset}${O}`):w.push(`${M}${Oe.dim}${b.label}${Oe.reset}${O}`)}R<e.length&&w.push(` ${Oe.dim}\u2193 more${Oe.reset}`);let k=w.join(`
|
|
996
|
+
`);process.stdout.write(k+`
|
|
997
|
+
`),m=w.length}t.pause();let p=process.stdin.isRaw;process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume();function g(){process.stdin.removeListener("keypress",y),process.stdin.isTTY&&p!==void 0&&process.stdin.setRawMode(p),t.resume()}function y(w,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 R=e[i[l]];g(),r(R?R.value:null);return}if(x.name==="escape"||x.ctrl&&x.name==="c"){g(),r(null);return}}}process.stdin.on("keypress",y),h()})}async function Sx(t){let e=_x(),n=xx(),o=kx(),s=[];for(let i of e)if(i.models.length!==0){s.push({label:i.provider,value:null,isHeader:!0});for(let c of i.models){let l=i.provider===n&&c.id===o;s.push({label:` ${c.name} (${i.provider}:${c.id})`,value:`${i.provider}:${c.id}`,isCurrent:l})}}let r=await Ip(t,s,{title:"Select Model"});return r?(vx(r),console.log(`${Oe.green}Switched to ${r}${Oe.reset}`),!0):(console.log(`${Oe.dim}Cancelled${Oe.reset}`),!1)}Lp.exports={pickFromList:Ip,showModelPicker:Sx}});var ec=G((wS,Gp)=>{var jp=require("fs"),Ex=require("path"),{atomicWrite:Tx,withFileLockSync:Rx}=en(),{callChat:qp}=Re(),{remember:Cx,listMemories:yS,recall:Ax}=an(),Za=4,Ox=`You are a memory optimization agent for an AI coding assistant called nex-code.
|
|
995
998
|
Analyze this conversation history and extract actionable learnings the assistant should remember.
|
|
996
999
|
|
|
997
1000
|
Return ONLY valid JSON in this exact format:
|
|
@@ -1017,15 +1020,15 @@ Rules:
|
|
|
1017
1020
|
- value: concise actionable instruction, max 120 chars
|
|
1018
1021
|
- nex_additions: project-level instructions/conventions only (not personal preferences)
|
|
1019
1022
|
- If nothing significant to learn, return {"memories": [], "nex_additions": [], "summary": "..."}
|
|
1020
|
-
- Return ONLY the JSON, no markdown, no explanation`;function
|
|
1023
|
+
- Return ONLY the JSON, no markdown, no explanation`;function Fp(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(`
|
|
1021
1024
|
|
|
1022
|
-
`)}async function
|
|
1025
|
+
`)}async function Up(t){if(t.filter(s=>s.role==="user").length<Za)return{memories:[],nex_additions:[],summary:null,skipped:!0};let n=Fp(t);if(!n.trim())return{memories:[],nex_additions:[],summary:null,skipped:!0};let o=[{role:"system",content:Ox},{role:"user",content:`Conversation to analyze:
|
|
1023
1026
|
|
|
1024
|
-
${n}`}];try{let i=((await
|
|
1027
|
+
${n}`}];try{let i=((await qp(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(s){return{memories:[],nex_additions:[],summary:null,error:s.message}}}function Wp(t){let e=[];for(let{key:n,value:o}of t||[]){if(!n||!o||typeof n!="string"||typeof o!="string")continue;let s=n.trim().replace(/\s+/g,"-").substring(0,60),r=o.trim().substring(0,200);if(!s||!r)continue;let i=Ax(s);i!==r&&(Cx(s,r),e.push({key:s,value:r,action:i?"updated":"added"}))}return e}function Bp(t){if(!t||t.length===0)return[];let e=Ex.join(process.cwd(),"NEX.md");return Rx(e,()=>{let n="";try{jp.existsSync(e)&&(n=jp.readFileSync(e,"utf-8"))}catch{}let o=[],s=n;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();n.toLowerCase().includes(c)||(o.push(i),s=s?s.endsWith(`
|
|
1025
1028
|
`)?s+i:s+`
|
|
1026
1029
|
`+i:i)}return o.length>0&&(s.endsWith(`
|
|
1027
1030
|
`)||(s+=`
|
|
1028
|
-
`),
|
|
1031
|
+
`),Tx(e,s)),o})}async function Nx(t){let e=await Up(t);if(e.skipped)return{applied:[],nexAdded:[],summary:null,skipped:!0};if(e.error)return{applied:[],nexAdded:[],summary:null,error:e.error};let n=Wp(e.memories),o=Bp(e.nex_additions);return{applied:n,nexAdded:o,summary:e.summary}}var Mx=`You are a knowledge base agent for an AI coding assistant called nex-code.
|
|
1029
1032
|
Analyze this conversation and extract knowledge worth persisting in the project knowledge base (.nex/brain/).
|
|
1030
1033
|
|
|
1031
1034
|
Return ONLY valid JSON in this exact format:
|
|
@@ -1059,39 +1062,39 @@ Rules:
|
|
|
1059
1062
|
---
|
|
1060
1063
|
- Maximum 3 documents per session. Quality over quantity.
|
|
1061
1064
|
- If nothing worth persisting: return {"documents": [], "skip_reason": "..."}
|
|
1062
|
-
- Return ONLY the JSON, no markdown fences, no explanation`;async function
|
|
1065
|
+
- Return ONLY the JSON, no markdown fences, no explanation`;async function Hp(t){if(t.filter(s=>s.role==="user").length<Za)return{documents:[],skip_reason:"Session too short"};let n=Fp(t);if(!n.trim())return{documents:[],skip_reason:"No usable content"};let o=[{role:"system",content:Mx},{role:"user",content:`Conversation to analyze:
|
|
1063
1066
|
|
|
1064
|
-
${n}`}];try{let i=((await
|
|
1067
|
+
${n}`}];try{let i=((await qp(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(s){return{documents:[],error:s.message}}}async function Px(t){let e=await Hp(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:n,readDocument:o}=Ds(),s=[],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=`
|
|
1065
1068
|
|
|
1066
1069
|
## Update ${new Date().toISOString().split("T")[0]}
|
|
1067
1070
|
|
|
1068
|
-
${i.content}`;n(c,l.content+d),s.push({name:c,reason:i.reason||"",action:"updated"})}else n(c,i.content),s.push({name:c,reason:i.reason||"",action:"created"})}return{written:s,skipped:r}}
|
|
1071
|
+
${i.content}`;n(c,l.content+d),s.push({name:c,reason:i.reason||"",action:"updated"})}else n(c,i.content),s.push({name:c,reason:i.reason||"",action:"created"})}return{written:s,skipped:r}}Gp.exports={learnFromSession:Nx,learnBrainFromSession:Px,reflectOnSession:Up,reflectBrain:Hp,applyMemories:Wp,applyNexAdditions:Bp,LEARN_MIN_MESSAGES:Za}});var Vp=G((bS,Jp)=>{var{spawn:Ix}=require("child_process"),Kp=require("path"),Yp=require("fs"),Lx=require("os"),ln=new Map;function zp(t){return typeof t!="string"?t:t.replace(/\$\{([^}]+)\}/g,(e,n)=>process.env[n]!==void 0?process.env[n]:"")}function Xp(t){let e=t||process.env.NEX_MCP_CONFIG||null,n=e?[e]:[Kp.join(process.cwd(),".nex","mcp.json"),Kp.join(Lx.homedir(),".nex","mcp.json")];for(let o of n)if(Yp.existsSync(o))try{return JSON.parse(Yp.readFileSync(o,"utf-8"))}catch{}return{servers:{}}}function Ir(t,e,n={},o=1e4){return new Promise((s,r)=>{let i=`${Date.now()}-${Math.random().toString(36).slice(2,6)}`,c=JSON.stringify({jsonrpc:"2.0",id:i,method:e,params:n})+`
|
|
1069
1072
|
`,l="",u=setTimeout(()=>{f(),r(new Error(`MCP request timeout: ${e}`))},o);function d(m){l+=m.toString();let h=l.split(`
|
|
1070
|
-
`);for(let p of h)if(p.trim())try{let g=JSON.parse(p);if(g.id===i){f(),g.error?r(new Error(`MCP error: ${g.error.message||JSON.stringify(g.error)}`)):s(g.result);return}}catch{}l=h[h.length-1]||""}function f(){clearTimeout(u),t.stdout.removeListener("data",d)}t.stdout.on("data",d);try{t.stdin.write(c)}catch(m){f(),r(new Error(`MCP write failed: ${m.message}`))}})}async function
|
|
1071
|
-
`):JSON.stringify(s)}function
|
|
1073
|
+
`);for(let p of h)if(p.trim())try{let g=JSON.parse(p);if(g.id===i){f(),g.error?r(new Error(`MCP error: ${g.error.message||JSON.stringify(g.error)}`)):s(g.result);return}}catch{}l=h[h.length-1]||""}function f(){clearTimeout(u),t.stdout.removeListener("data",d)}t.stdout.on("data",d);try{t.stdin.write(c)}catch(m){f(),r(new Error(`MCP write failed: ${m.message}`))}})}async function Dx(t){let n=Xp(t).servers||{},o=[];for(let[s,r]of Object.entries(n)){if(ln.has(s)){let d=ln.get(s);o.push({name:s,tools:d.tools.length});continue}let i={};for(let[d,f]of Object.entries(r.env||{}))i[d]=zp(f);let c=["PATH","HOME","USER","SHELL","LANG","TERM","NODE_ENV"],l={};for(let d of c)process.env[d]!==void 0&&(l[d]=process.env[d]);let u;try{u=Ix(r.command,r.args||[],{stdio:["pipe","pipe","pipe"],env:{...l,...i}})}catch(d){console.warn(`[mcp-client] Failed to spawn '${s}': ${d.message}`),o.push({name:s,tools:0,error:d.message});continue}try{await Ir(u,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.4.8"}});let d=await Ir(u,"tools/list",{}),f=d&&d.tools||[];ln.set(s,{name:s,proc:u,tools:f,config:r}),o.push({name:s,tools:f.length})}catch(d){console.warn(`[mcp-client] Server '${s}' failed to initialize: ${d.message}`);try{u.kill()}catch{}o.push({name:s,tools:0,error:d.message})}}return o}async function jx(t,e,n={}){let o=ln.get(t);if(!o)throw new Error(`MCP server not connected: ${t}`);let s=await Ir(o.proc,"tools/call",{name:e,arguments:n});return s&&Array.isArray(s.content)?s.content.filter(r=>r.type==="text").map(r=>r.text).join(`
|
|
1074
|
+
`):JSON.stringify(s)}function qx(){let t=[];for(let[e,n]of ln)for(let o of n.tools)t.push({type:"function",function:{name:`mcp_${e}_${o.name}`,description:`[MCP:${e}] ${o.description||""}`,parameters:o.inputSchema||{type:"object",properties:{}}}});return t}function Fx(){for(let[t,e]of ln){try{e.proc.kill()}catch{}ln.delete(t)}}function Ux(){let t=[];for(let[e,n]of ln)t.push({name:e,connected:!0,toolCount:n.tools.length});return t}Jp.exports={loadMcpServers:Dx,callMcpTool:jx,getMcpTools:qx,shutdownMcpServers:Fx,listMcpServers:Ux,_interpolateEnv:zp,_readConfig:Xp,_sendRequest:Ir}});var tm=G((xS,em)=>{var nt=require("fs"),ms=require("path"),_S=require("os"),Wx=require("readline"),{C:z}=Me(),Qp=".nex",tc=null;function Bx(t){tc=t}function st(t,e=""){let n=e?` ${z.dim}[${e}]${z.reset}`:"",o=` ${z.cyan}${t}${n}${z.reset}: `;return new Promise(s=>{let r=i=>{let c=i.trim()||e;s(c)};if(tc)tc.question(o,r);else{let i=Wx.createInterface({input:process.stdin,output:process.stdout});i.question(o,c=>{i.close(),r(c)})}})}function ps(t,e=!0){return st(`${t} (${e?"Y/n":"y/N"})`,e?"y":"n").then(o=>o.toLowerCase()!=="n"&&o.toLowerCase()!=="no")}async function nc(t,e,n){let o=e.map((c,l)=>`${z.dim}${l+1})${z.reset} ${c}`).join(" ");console.log(` ${z.cyan}${t}${z.reset}`),console.log(` ${o}`);let s=n?e.indexOf(n)+1:1,r=await st("Enter number",String(s)),i=parseInt(r,10)-1;return e[Math.max(0,Math.min(i,e.length-1))]}async function Hx(){let t=ms.join(process.cwd(),Qp),e=ms.join(t,"servers.json"),n={};if(nt.existsSync(e))try{n=JSON.parse(nt.readFileSync(e,"utf-8"))}catch{}console.log(`
|
|
1072
1075
|
${z.bold}${z.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${z.reset}`),console.log(`${z.bold}${z.cyan}\u2551 nex-code Server Setup Wizard \u2551${z.reset}`),console.log(`${z.bold}${z.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${z.reset}
|
|
1073
|
-
`);let o=Object.keys(n);if(o.length>0&&(console.log(`${z.dim}Existing profiles: ${o.join(", ")}${z.reset}`),!await
|
|
1076
|
+
`);let o=Object.keys(n);if(o.length>0&&(console.log(`${z.dim}Existing profiles: ${o.join(", ")}${z.reset}`),!await ps("Add or update a server profile?",!0))){console.log(`${z.dim}No changes made.${z.reset}
|
|
1074
1077
|
`);return}let s={...n},r=!0;for(;r;){console.log(`
|
|
1075
|
-
${z.bold}\u2500\u2500\u2500 New Server Profile \u2500\u2500\u2500${z.reset}`);let l=await
|
|
1076
|
-
${z.green}\u2713${z.reset} Profile "${l}" added: ${d}@${u}${m!==22?`:${m}`:""}${p!=="other"?` [${p}]`:""}`),r=await
|
|
1077
|
-
Add another server?`,!1)}
|
|
1078
|
+
${z.bold}\u2500\u2500\u2500 New Server Profile \u2500\u2500\u2500${z.reset}`);let l=await st("Profile name (e.g. prod, staging, macbook)");if(!l){console.log(`${z.red} Name is required.${z.reset}`);continue}let u=await st("Host / IP address");if(!u){console.log(`${z.red} Host is required.${z.reset}`);continue}let d=await st("SSH user","root"),f=await st("SSH port","22"),m=parseInt(f,10)||22,h=await st("SSH key path (leave empty for SSH agent)",""),p=await nc("Operating system",["almalinux9","macos","ubuntu","debian","other"],"almalinux9"),g=await ps("Allow sudo commands?",!0),y={host:u,user:d};m!==22&&(y.port=m),h&&(y.key=h),p!=="other"&&(y.os=p),g&&(y.sudo=!0),s[l]=y,console.log(`
|
|
1079
|
+
${z.green}\u2713${z.reset} Profile "${l}" added: ${d}@${u}${m!==22?`:${m}`:""}${p!=="other"?` [${p}]`:""}`),r=await ps(`
|
|
1080
|
+
Add another server?`,!1)}nt.existsSync(t)||nt.mkdirSync(t,{recursive:!0}),nt.writeFileSync(e,JSON.stringify(s,null,2)+`
|
|
1078
1081
|
`,"utf-8"),console.log(`
|
|
1079
|
-
${z.green}\u2713 Saved .nex/servers.json (${Object.keys(s).length} profile${Object.keys(s).length!==1?"s":""})${z.reset}`);let i=
|
|
1082
|
+
${z.green}\u2713 Saved .nex/servers.json (${Object.keys(s).length} profile${Object.keys(s).length!==1?"s":""})${z.reset}`);let i=ms.join(process.cwd(),".gitignore");nt.existsSync(i)&&(nt.readFileSync(i,"utf-8").includes(".nex/")||await ps("Add .nex/ to .gitignore?",!0)&&(nt.appendFileSync(i,`
|
|
1080
1083
|
# nex-code server profiles
|
|
1081
1084
|
.nex/
|
|
1082
|
-
`),console.log(`${z.green}\u2713 Added .nex/ to .gitignore${z.reset}`))),await
|
|
1083
|
-
Set up deploy configs (.nex/deploy.json)?`,!1)&&await
|
|
1085
|
+
`),console.log(`${z.green}\u2713 Added .nex/ to .gitignore${z.reset}`))),await ps(`
|
|
1086
|
+
Set up deploy configs (.nex/deploy.json)?`,!1)&&await Zp(s,t),console.log(`
|
|
1084
1087
|
${z.dim}Use /servers to list profiles, /servers ping to check connectivity.${z.reset}
|
|
1085
|
-
`)}async function
|
|
1088
|
+
`)}async function Zp(t,e){let n=e||ms.join(process.cwd(),Qp),o=ms.join(n,"deploy.json"),s={};if(nt.existsSync(o))try{s=JSON.parse(nt.readFileSync(o,"utf-8"))}catch{}if(!t){let u=ms.join(n,"servers.json");if(nt.existsSync(u))try{t=JSON.parse(nt.readFileSync(u,"utf-8"))}catch{t={}}else t={}}let r=Object.keys(t);console.log(`
|
|
1086
1089
|
${z.bold}${z.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${z.reset}`),console.log(`${z.bold}${z.cyan}\u2551 Deploy Config Wizard \u2551${z.reset}`),console.log(`${z.bold}${z.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${z.reset}
|
|
1087
1090
|
`);let i=Object.keys(s);i.length>0&&console.log(`${z.dim}Existing deploy configs: ${i.join(", ")}${z.reset}`);let c={...s},l=!0;for(;l;){console.log(`
|
|
1088
|
-
${z.bold}\u2500\u2500\u2500 New Deploy Config \u2500\u2500\u2500${z.reset}`);let u=await
|
|
1089
|
-
${z.green}\u2713${z.reset} Deploy config "${u}": [${f}] ${R}`),y&&console.log(` ${z.dim} Then: ${y}${z.reset}`),w&&console.log(` ${z.dim} Health: ${w}${z.reset}`),l=await
|
|
1090
|
-
Add another deploy config?`,!1)}
|
|
1091
|
+
${z.bold}\u2500\u2500\u2500 New Deploy Config \u2500\u2500\u2500${z.reset}`);let u=await st("Config name (e.g. prod, staging)");if(!u){console.log(`${z.red} Name is required.${z.reset}`);continue}let d;r.length>0?d=await nc("Target server",r,r[0]):d=await st("Target server (profile name or user@host)");let f=await nc("Deploy method",["rsync","git"],"rsync"),m="",h=[],p="";if(f==="rsync"){m=await st("Local path to sync (e.g. dist/ or ./build)","dist/");let k=await st("Exclude paths (comma-separated, e.g. node_modules,.env)","node_modules,.env");h=k?k.split(",").map(_=>_.trim()).filter(Boolean):[]}else p=await st("Branch to pull (leave empty for current remote branch)","main");let g=await st(f==="git"?"Remote repo path (e.g. /home/jarvis/my-app)":"Remote destination path (e.g. /var/www/app)");if(!g){console.log(`${z.red} Remote path is required.${z.reset}`);continue}let y=await st("Command to run on remote after deploy (leave empty to skip)",""),w=await st("Health check URL or remote command (leave empty to skip)",""),x={server:d,method:f,remote_path:g};f==="rsync"?(x.local_path=m,h.length>0&&(x.exclude=h)):p&&(x.branch=p),y&&(x.deploy_script=y),w&&(x.health_check=w),c[u]=x;let R=f==="git"?`${d}:${g}${p?` (${p})`:""}`:`${m.endsWith("/")?m:m+"/"} \u2192 ${d}:${g}`;console.log(`
|
|
1092
|
+
${z.green}\u2713${z.reset} Deploy config "${u}": [${f}] ${R}`),y&&console.log(` ${z.dim} Then: ${y}${z.reset}`),w&&console.log(` ${z.dim} Health: ${w}${z.reset}`),l=await ps(`
|
|
1093
|
+
Add another deploy config?`,!1)}nt.existsSync(n)||nt.mkdirSync(n,{recursive:!0}),nt.writeFileSync(o,JSON.stringify(c,null,2)+`
|
|
1091
1094
|
`,"utf-8"),console.log(`
|
|
1092
1095
|
${z.green}\u2713 Saved .nex/deploy.json (${Object.keys(c).length} config${Object.keys(c).length!==1?"s":""})${z.reset}`),console.log(`${z.dim}Use: deploy prod (or with explicit params)${z.reset}
|
|
1093
|
-
`)}
|
|
1094
|
-
`);return`${
|
|
1096
|
+
`)}em.exports={runServerWizard:Hx,runDeployWizard:Zp,setWizardRL:Bx}});var sc=G((kS,rm)=>{"use strict";var Gx=require("os"),nm=require("path"),io=require("fs"),ao=nm.join(Gx.homedir(),".nex-code","model-routing.json"),Lr={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}},sm=["agentic","frontend","sysadmin","data","coding"];function Kx(t){if(!t||t.length<8)return null;for(let e of sm){let n=Lr[e];if(!n.pattern||n.pattern.test(t))return n}return Lr.coding}function om(){try{if(io.existsSync(ao))return JSON.parse(io.readFileSync(ao,"utf-8"))}catch{}return{}}function Yx(t){let e=Lr[t];return e?.envVar&&process.env[e.envVar]?process.env[e.envVar]:om()[t]||null}function zx(t){let e=nm.dirname(ao);io.existsSync(e)||io.mkdirSync(e,{recursive:!0}),io.writeFileSync(ao,JSON.stringify(t,null,2))}rm.exports={CATEGORIES:Lr,DETECTION_ORDER:sm,detectCategory:Kx,getModelForCategory:Yx,saveRoutingConfig:zx,loadRoutingConfig:om,ROUTING_CONFIG_PATH:ao}});var Fr=G((vS,cm)=>{"use strict";var qr=require("os"),co=require("path"),Xe=require("fs"),Xx=require("axios"),Jx=require("https"),Dr=co.join(qr.homedir(),".nex-code","known-models.json"),Vx="https://ollama.com/api/tags",Qx=60,Zx={"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 oc(){try{if(Xe.existsSync(Dr))return JSON.parse(Xe.readFileSync(Dr,"utf-8"))}catch{}return{benchmarked:[],lastChecked:null}}function ek(t){let e=co.dirname(Dr);Xe.existsSync(e)||Xe.mkdirSync(e,{recursive:!0}),Xe.writeFileSync(Dr,JSON.stringify(t,null,2))}function tk(t){let e=oc(),n=new Set(e.benchmarked);for(let o of t)n.add(o);e.benchmarked=[...n],e.lastChecked=new Date().toISOString(),ek(e)}async function im(){let t=process.env.OLLAMA_API_KEY;if(!t)throw new Error("OLLAMA_API_KEY not set");let e=new Jx.Agent({keepAlive:!0});return((await Xx.get(Vx,{headers:{Authorization:`Bearer ${t}`},timeout:15e3,httpsAgent:e})).data?.models||[]).map(o=>(o.name||o.model||"").replace(/:latest$/,"")).filter(Boolean)}async function nk(){let t=await im(),e=oc(),n=new Set(e.benchmarked),o=t.filter(s=>!n.has(s));return{allCloud:t,newModels:o,store:e}}var rc="<!-- nex-benchmark-start -->",jr="<!-- nex-benchmark-end -->",sk={"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 ok(t){return t?t>=25e4?"256K":t>=19e4?"200K":t>=128e3?"131K":t>=64e3?"64K":`${Math.round(t/1024)}K`:"?"}function am(t,e){let n=["\u{1F947}","\u{1F948}","\u{1F949}"],o=(e||new Date().toISOString()).split("T")[0],s=t.filter(r=>r.score>=Qx).map((r,i)=>{let c=n[i]||"\u2014",l=ok(Zx[r.model]),u=sk[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(`
|
|
1097
|
+
`);return`${rc}
|
|
1095
1098
|
<!-- Updated: ${o} \u2014 run \`/benchmark --discover\` after new Ollama Cloud releases -->
|
|
1096
1099
|
|
|
1097
1100
|
| Rank | Model | Score | Avg Latency | Context | Best For |
|
|
@@ -1100,19 +1103,19 @@ ${s}
|
|
|
1100
1103
|
|
|
1101
1104
|
> Rankings are nex-code-specific: tool name accuracy, argument validity, schema compliance.
|
|
1102
1105
|
> Toolathon (Minimax SOTA) measures different task types \u2014 run \`/benchmark --discover\` after model releases.
|
|
1103
|
-
${
|
|
1106
|
+
${jr}`}function rk(t,e){if(!Xe.existsSync(e))return!1;let n=Xe.readFileSync(e,"utf-8"),o=n.indexOf(rc),s=n.indexOf(jr);if(o===-1||s===-1)return!1;let r=n.slice(0,o),i=n.slice(s+jr.length),c=am(t);return Xe.writeFileSync(e,r+c+i),!0}function ik(t){let e=co.join(qr.homedir(),".nex-code","models.env");if(!Xe.existsSync(e)||t.length===0)return{updated:!1,reason:"models.env not found or empty summary"};let n=t[0],o=Xe.readFileSync(e,"utf-8"),r=o.match(/^DEFAULT_MODEL=(\S+)/m)?.[1];if(r===n.model)return{updated:!1,reason:"winner unchanged"};let i=t.find(l=>l.model===r);if(i&&n.score-i.score<5)return{updated:!1,reason:`margin ${(n.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=${n.model}`).replace(/^# Last reviewed:.*$/m,`# Last reviewed: ${c} (after /benchmark, ${n.model} wins nex-code tasks)`),Xe.writeFileSync(e,o),{updated:!0,previousModel:r,newModel:n.model}}function ak(t){let{saveRoutingConfig:e}=sc(),n=co.join(qr.homedir(),".nex-code","models.env"),o=[],s=Object.entries(t).filter(([,c])=>c.score>0);if(s.length===0)return{saved:!1,envUpdated:!1,changes:[]};let r={};for(let[c,l]of s)r[c]=l.model,o.push(`${c}: ${l.model} (${l.score}/100)`);e(r);let i=!1;if(Xe.existsSync(n)){let c=Xe.readFileSync(n,"utf-8"),u=Object.entries({coding:"NEX_ROUTE_CODING",frontend:"NEX_ROUTE_FRONTEND",sysadmin:"NEX_ROUTE_SYSADMIN",data:"NEX_ROUTE_DATA",agentic:"NEX_ROUTE_AGENTIC"}).filter(([m])=>t[m]&&t[m].score>0).map(([m,h])=>`${h}=${t[m].model} # ${m} score: ${t[m].score}/100`).join(`
|
|
1104
1107
|
`),d="# \u2500\u2500 Task-type routing (auto-updated by /benchmark) \u2500\u2500",f="# \u2500\u2500 end routing \u2500\u2500";if(c.includes(d)){let m=c.indexOf(d),h=c.indexOf(f);h!==-1&&(c=c.slice(0,m)+`${d}
|
|
1105
1108
|
${u}
|
|
1106
1109
|
${f}`+c.slice(h+f.length))}else c+=`
|
|
1107
1110
|
${d}
|
|
1108
1111
|
${u}
|
|
1109
1112
|
${f}
|
|
1110
|
-
`;
|
|
1113
|
+
`;Xe.writeFileSync(n,c),i=!0}return{saved:!0,envUpdated:i,changes:o}}var ck=/thinking|reasoning|instruct|planner|orchestrat/i;function lk(t){return ck.test(t)}function uk(t){if(!t||t.length===0)return{updated:!1};let e=co.join(qr.homedir(),".nex-code","models.env");if(!Xe.existsSync(e))return{updated:!1};let n=Xe.readFileSync(e,"utf-8"),o=n.match(/^NEX_ORCHESTRATOR_MODEL=(.+)$/m),s=o?o[1].trim():null,i=[...t].sort((d,f)=>f.overall-d.overall)[0],c=s?t.find(d=>d.model===s):null,l=c?c.overall:0;if(i.model===s)return{updated:!1};if(l>0&&i.overall<l*1.05)return{updated:!1};let u=`NEX_ORCHESTRATOR_MODEL=${i.model}`;return o?n=n.replace(/^NEX_ORCHESTRATOR_MODEL=.+$/m,u):n+=`
|
|
1111
1114
|
${u}
|
|
1112
|
-
`,ze.writeFileSync(e,n),{updated:!0,previousModel:s,newModel:i.model}}Vp.exports={findNewModels:Ux,fetchCloudModels:Xp,loadKnownModels:Xa,markBenchmarked:Fx,updateReadme:Hx,updateModelsEnv:Gx,updateRoutingConfig:Kx,generateBenchmarkBlock:Jp,checkOrchestratorCandidate:zx,updateOrchestratorModel:Xx,SENTINEL_START:Ja,SENTINEL_END:Rr}});var An=G((uS,rm)=>{"use strict";var{C:F}=Oe(),Jx=Te(),{TOOL_DEFINITIONS:Qp}=Et(),eo=[{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 n=e?.function?.parameters||{},o=n.required||[],s=Object.keys(n.properties||{});return o.every(r=>t[r]!==void 0)&&Object.keys(t).every(r=>s.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"))}],Zp=["minimax-m2.7:cloud","qwen3-coder:480b","kimi-k2:1t","devstral-2:123b","devstral-small-2:24b"],em=["minimax-m2.7:cloud","qwen3-coder:480b","devstral-2:123b"],Vx=7,Or={producedToolCall:.2,correctTool:.35,validArgs:.3,schemaCompliant:.15},Qx="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 tm(t,e){let n={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:Qx},{role:"user",content:t.prompt}],s=Date.now();try{let r=await Jx.callChat(o,Qp,{provider:"ollama",model:e,temperature:0,timeout:9e4});n.latencyMs=Date.now()-s;let i=r.tool_calls||[];if(t.expectedTool===null){let c=i.length===0;n.producedToolCall=c,n.correctTool=c,n.validArgs=!0,n.schemaCompliant=!0}else if(i.length>0){let c=i[0],l=c.function?.name||"unknown",u=c.function?.arguments||{};n.producedToolCall=!0,n.toolCalled=l;let d=Array.isArray(t.expectedTool)?t.expectedTool:[t.expectedTool];if(n.correctTool=d.includes(l),n.correctTool){let f=Qp.find(m=>m.function?.name===l);if(n.validArgs=!!t.validateArgs(u,f),f){let m=f.function?.parameters||{},h=m.required||[],p=Object.keys(m.properties||{});n.schemaCompliant=h.every(g=>u[g]!==void 0)&&Object.keys(u).every(g=>p.includes(g))}}}}catch(r){n.latencyMs=Date.now()-s,n.error=r.message.slice(0,120)}return n}function to(t){return t.error?0:((t.producedToolCall?Or.producedToolCall:0)+(t.correctTool?Or.correctTool:0)+(t.validArgs?Or.validArgs:0)+(t.schemaCompliant?Or.schemaCompliant:0))*100}var Zx={coding:"coding",search:"coding",shell:"coding",schema:"coding","multi-step":"coding",reasoning:"coding",frontend:"frontend",sysadmin:"sysadmin",data:"data",agentic:"agentic"};function Va(t){return Object.entries(t).map(([e,n])=>{let o=n.map(to),s=o.reduce((c,l)=>c+l,0)/o.length,r=c=>Math.round(n.filter(c).length/n.length*100),i={};for(let c of["coding","frontend","sysadmin","data","agentic"]){let l=n.filter(d=>Zx[d.category]===c);if(l.length===0)continue;let u=l.map(to).reduce((d,f)=>d+f,0)/l.length;i[c]=Math.round(u*10)/10}return{model:e,score:Math.round(s*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(n.reduce((c,l)=>c+l.latencyMs,0)/n.length),errorCount:n.filter(c=>c.error).length,categoryScores:i,results:n}}).sort((e,n)=>n.score-e.score)}function ek(t){let e={};for(let n of["coding","frontend","sysadmin","data","agentic"]){let o=t.filter(s=>s.categoryScores[n]!==void 0).sort((s,r)=>r.categoryScores[n]-s.categoryScores[n]);o.length>0&&(e[n]={model:o[0].model,score:o[0].categoryScores[n]})}return e}function nm(t,e){let n=`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}],s=o.reduce((u,d)=>u+d.width+1,0)+1,r="\u2500".repeat(s);console.log(`
|
|
1113
|
-
${
|
|
1114
|
-
${
|
|
1115
|
-
${
|
|
1115
|
+
`,Xe.writeFileSync(e,n),{updated:!0,previousModel:s,newModel:i.model}}cm.exports={findNewModels:nk,fetchCloudModels:im,loadKnownModels:oc,markBenchmarked:tk,updateReadme:rk,updateModelsEnv:ik,updateRoutingConfig:ak,generateBenchmarkBlock:am,checkOrchestratorCandidate:lk,updateOrchestratorModel:uk,SENTINEL_START:rc,SENTINEL_END:jr}});var Mn=G((SS,gm)=>{"use strict";var{C:q}=Me(),dk=Re(),{TOOL_DEFINITIONS:lm}=Tt(),lo=[{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 n=e?.function?.parameters||{},o=n.required||[],s=Object.keys(n.properties||{});return o.every(r=>t[r]!==void 0)&&Object.keys(t).every(r=>s.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"))}],um=["minimax-m2.7:cloud","qwen3-coder:480b","kimi-k2:1t","devstral-2:123b","devstral-small-2:24b"],dm=["minimax-m2.7:cloud","qwen3-coder:480b","devstral-2:123b"],fk=7,Ur={producedToolCall:.2,correctTool:.35,validArgs:.3,schemaCompliant:.15},pk="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 fm(t,e){let n={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:pk},{role:"user",content:t.prompt}],s=Date.now();try{let r=await dk.callChat(o,lm,{provider:"ollama",model:e,temperature:0,timeout:9e4});n.latencyMs=Date.now()-s;let i=r.tool_calls||[];if(t.expectedTool===null){let c=i.length===0;n.producedToolCall=c,n.correctTool=c,n.validArgs=!0,n.schemaCompliant=!0}else if(i.length>0){let c=i[0],l=c.function?.name||"unknown",u=c.function?.arguments||{};n.producedToolCall=!0,n.toolCalled=l;let d=Array.isArray(t.expectedTool)?t.expectedTool:[t.expectedTool];if(n.correctTool=d.includes(l),n.correctTool){let f=lm.find(m=>m.function?.name===l);if(n.validArgs=!!t.validateArgs(u,f),f){let m=f.function?.parameters||{},h=m.required||[],p=Object.keys(m.properties||{});n.schemaCompliant=h.every(g=>u[g]!==void 0)&&Object.keys(u).every(g=>p.includes(g))}}}}catch(r){n.latencyMs=Date.now()-s,n.error=r.message.slice(0,120)}return n}function uo(t){return t.error?0:((t.producedToolCall?Ur.producedToolCall:0)+(t.correctTool?Ur.correctTool:0)+(t.validArgs?Ur.validArgs:0)+(t.schemaCompliant?Ur.schemaCompliant:0))*100}var mk={coding:"coding",search:"coding",shell:"coding",schema:"coding","multi-step":"coding",reasoning:"coding",frontend:"frontend",sysadmin:"sysadmin",data:"data",agentic:"agentic"};function ic(t){return Object.entries(t).map(([e,n])=>{let o=n.map(uo),s=o.reduce((c,l)=>c+l,0)/o.length,r=c=>Math.round(n.filter(c).length/n.length*100),i={};for(let c of["coding","frontend","sysadmin","data","agentic"]){let l=n.filter(d=>mk[d.category]===c);if(l.length===0)continue;let u=l.map(uo).reduce((d,f)=>d+f,0)/l.length;i[c]=Math.round(u*10)/10}return{model:e,score:Math.round(s*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(n.reduce((c,l)=>c+l.latencyMs,0)/n.length),errorCount:n.filter(c=>c.error).length,categoryScores:i,results:n}}).sort((e,n)=>n.score-e.score)}function hk(t){let e={};for(let n of["coding","frontend","sysadmin","data","agentic"]){let o=t.filter(s=>s.categoryScores[n]!==void 0).sort((s,r)=>r.categoryScores[n]-s.categoryScores[n]);o.length>0&&(e[n]={model:o[0].model,score:o[0].categoryScores[n]})}return e}function pm(t,e){let n=`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}],s=o.reduce((u,d)=>u+d.width+1,0)+1,r="\u2500".repeat(s);console.log(`
|
|
1116
|
+
${q.bold}${n}${q.reset}`),console.log(r);let i=o.map(u=>u.label.padEnd(u.width)).join(" ");if(console.log(`${q.dim}${i}${q.reset}`),console.log(r),t.forEach((u,d)=>{let f=String(d+1).padEnd(o[0].width),m=u.model.slice(0,o[1].width).padEnd(o[1].width),h=String(u.score).padEnd(o[2].width),p=`${u.toolCallRate}%`.padEnd(o[3].width),g=`${u.correctRate}%`.padEnd(o[4].width),y=`${u.validArgsRate}%`.padEnd(o[5].width),w=`${u.schemaRate}%`.padEnd(o[6].width),x=`${(u.avgLatency/1e3).toFixed(1)}s`.padEnd(o[7].width),R=u.errorCount>0?`${q.red}${u.errorCount}${q.reset}`:`${q.dim}0${q.reset}`,k=u.score>=80?q.green:u.score>=60?q.yellow:q.red,_=d===0?`${q.yellow}${f}${q.reset}`:`${q.dim}${f}${q.reset}`;console.log(`${_} ${k}${m}${q.reset} ${q.bold}${k}${h}${q.reset} ${p} ${g} ${y} ${w} ${q.dim}${x}${q.reset} ${R}`)}),console.log(r),t.length>0){let u=t[0];if(console.log(`
|
|
1117
|
+
${q.bold}${q.green}Winner: ${u.model}${q.reset} score ${u.score}/100`),t.length>1){let d=(u.score-t[1].score).toFixed(1);console.log(`${q.dim}+${d} pts over ${t[1].model}${q.reset}`)}}let c=["coding","frontend","sysadmin","data","agentic"];if(t.some(u=>Object.keys(u.categoryScores).length>1)){console.log(`
|
|
1118
|
+
${q.bold}Best model per task type:${q.reset}`);for(let u of c){let d=t.filter(p=>p.categoryScores[u]!==void 0).sort((p,g)=>g.categoryScores[u]-p.categoryScores[u]);if(d.length===0)continue;let f=d[0],m=f.categoryScores[u],h=m>=80?q.green:m>=60?q.yellow:q.red;console.log(` ${q.dim}${u.padEnd(10)}${q.reset} ${h}${f.model}${q.reset} ${q.dim}${m}/100${q.reset}`)}}console.log()}async function gk({models:t,quick:e=!1,onProgress:n}={}){let o=e?lo.slice(0,fk):lo,s=t?.length>0?t:e?dm:um,r={};for(let c of s){r[c]=[];for(let l of o){n?.({model:c,task:l.id,done:!1});let u=await fm(l,c);r[c].push(u),n?.({model:c,task:l.id,done:!0,score:uo(u),error:u.error})}}let i=ic(r);return pm(i,o.length),i}async function $k({newModels:t,existingRanking:e=[],onProgress:n}={}){if(!t||t.length===0)return e;let o={};for(let i of t){o[i]=[];for(let c of lo){n?.({model:i,task:c.id,done:!1});let l=await fm(c,i);o[i].push(l),n?.({model:i,task:c.id,done:!0,score:uo(l),error:l.error})}}let r=[...ic(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),pm(r,lo.length),r}var Wr=[{id:"simple_question",name:"Simple Convergence",prompt:"What is 2+2?",maxTurns:3,successCriteria:["4"]}];function mm(t){let e=require("fs"),o=require("path").join(t||process.cwd(),".nex","benchmark-config.json");if(!e.existsSync(o))return console.log(`${q.yellow}No scenarios configured.${q.reset} Create ${q.dim}.nex/benchmark-config.json${q.reset} to define your benchmark scenarios.
|
|
1116
1119
|
Example:
|
|
1117
1120
|
{
|
|
1118
1121
|
"scenarios": [
|
|
@@ -1125,28 +1128,28 @@ ${F.bold}Best model per task type:${F.reset}`);for(let u of c){let d=t.filter(p=
|
|
|
1125
1128
|
}
|
|
1126
1129
|
]
|
|
1127
1130
|
}
|
|
1128
|
-
`),
|
|
1129
|
-
`),
|
|
1130
|
-
`),
|
|
1131
|
+
`),Wr;try{let s=JSON.parse(e.readFileSync(o,"utf-8"));return!Array.isArray(s.scenarios)||s.scenarios.length===0?(console.log(`${q.yellow}benchmark-config.json has no scenarios \u2014 using defaults.${q.reset}
|
|
1132
|
+
`),Wr):s.scenarios}catch(s){return console.log(`${q.yellow}Failed to parse benchmark-config.json: ${s.message}${q.reset}
|
|
1133
|
+
`),Wr}}function hm(t,e){let{scoreMessages:n,_extractToolCalls:o,_getLastAssistantText:s}=pr(),r=n(t),i=r.score,c=[],l=s(t).toLowerCase();e.successCriteria.every(m=>l.includes(m.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 yk(t,e={}){let{spawn:n}=require("child_process"),o=require("fs"),s=require("path"),r=require("os"),i=s.join(r.tmpdir(),`nex-bench-${t.id}-${Date.now()}.txt`);o.writeFileSync(i,t.prompt,"utf-8");let c=s.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=n(process.execPath,u,{cwd:l,stdio:["ignore","pipe","pipe"],env:{...process.env}}),m=t.maxTurns*60*1e3,h=!1,p=setTimeout(()=>{h=!0;try{f.kill("SIGTERM")}catch{}},m);f.on("close",g=>{clearTimeout(p);try{o.unlinkSync(i)}catch{}let y=s.join(l,".nex","sessions","_autosave.json"),w=[];if(o.existsSync(y))try{w=JSON.parse(o.readFileSync(y,"utf-8")).messages||[]}catch{}d({messages:w,exitCode:g||0,timedOut:h})}),f.stdout.resume(),f.stderr.resume()})}function wk(t,e,n){let o=t.length>0?Math.round(t.reduce((l,u)=>l+u.score,0)/t.length*10)/10:0,s=o>=9?"A":o>=8?"B":o>=7?"C":o>=6?"D":"F",r=57,i="\u2500".repeat(r);console.log(`
|
|
1131
1134
|
\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),m=l.grade.padStart(2);console.log(`\u2502 ${u} ${d} ${f} ${m} \u2502`)}console.log(`\u2502 ${" ".repeat(r-2)} \u2502`);let c=`Overall: ${o}/10 (${s}) \xB7 v${e} \xB7 ${n}`;console.log(`\u2502 ${c.substring(0,r-4).padEnd(r-4)} \u2502`),console.log(`\u2514${"\u2500".repeat(r+1)}\u2518
|
|
1132
|
-
`)}function
|
|
1133
|
-
`);return}let s=[];try{s=JSON.parse(e.readFileSync(o,"utf-8"))}catch{s=[]}if(!Array.isArray(s)||s.length===0){console.log(`${
|
|
1135
|
+
`)}function bk(t=10){let e=require("fs"),o=require("path").join(process.cwd(),".nex","benchmark-history.json");if(!e.existsSync(o)){console.log(`${q.yellow}No score history yet. Run a session first.${q.reset}
|
|
1136
|
+
`);return}let s=[];try{s=JSON.parse(e.readFileSync(o,"utf-8"))}catch{s=[]}if(!Array.isArray(s)||s.length===0){console.log(`${q.yellow}Score history is empty.${q.reset}
|
|
1134
1137
|
`);return}let r=s.slice(-t);console.log(`
|
|
1135
|
-
${
|
|
1136
|
-
${
|
|
1137
|
-
`);for(let l of r)console.log(` ${
|
|
1138
|
-
${
|
|
1138
|
+
${q.bold}Score History (last ${r.length} session${r.length===1?"":"s"}):${q.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||"?",m=i.issues&&i.issues.length>0?`${q.yellow}\u26A0 ${i.issues.slice(0,2).map(p=>p.substring(0,30)).join(", ")}${q.reset}`:`${q.green}\u2713${q.reset}`,h=i.score>=8?q.green:i.score>=6?q.yellow:q.red;console.log(` ${q.dim}${c}${q.reset} ${q.dim}v${l}${q.reset} ${q.dim}${u}${q.reset} ${h}${d} ${f}${q.reset} ${m}`)}console.log()}async function _k({dryRun:t=!1,model:e,cwd:n,onProgress:o}={}){let s=In(),r=mm(n);if(t){console.log(`
|
|
1139
|
+
${q.bold}Jarvis Benchmark \u2014 Scenarios (dry-run):${q.reset}
|
|
1140
|
+
`);for(let l of r)console.log(` ${q.cyan}${l.id.padEnd(20)}${q.reset} ${q.dim}${l.name}${q.reset} maxTurns=${l.maxTurns}`),console.log(` ${q.dim}${l.prompt.substring(0,80)}${q.reset}`);return console.log(),[]}let i=(()=>{if(e)return e;try{let{getActiveModel:l}=Gn();return l&&l()||"unknown"}catch{return"unknown"}})(),c=[];for(let l of r){o?.({id:l.id,name:l.name,done:!1}),console.log(`
|
|
1141
|
+
${q.dim}Running scenario: ${l.name}...${q.reset}`);let{messages:u,timedOut:d}=await yk(l,{model:i,cwd:n}),f;d||u.length===0?f={score:0,grade:"F",issues:[d?"Scenario timed out":"No messages produced"],summary:"No output",bonuses:[]}:f=hm(u,l);let m={id:l.id,name:l.name,score:f.score,grade:f.grade,issues:f.issues,bonuses:f.bonuses};c.push(m),o?.({id:l.id,name:l.name,done:!0,score:f.score,grade:f.grade});try{let{appendScoreHistory:h}=pr();h(f.score,{version:s.version,model:i,sessionName:`bench:${l.id}`,issues:f.issues})}catch{}}return wk(c,s.version,i),c}gm.exports={runBenchmark:gk,runDiscoverBenchmark:$k,buildSummary:ic,buildCategoryWinners:hk,TASKS:lo,scoreResult:uo,DEFAULT_MODELS:um,QUICK_MODELS:dm,runJarvisBenchmark:_k,showScoreTrend:bk,loadScenarios:mm,DEFAULT_SCENARIOS:Wr,scoreJarvisScenario:hm}});var Sm=G((ES,vm)=>{"use strict";var xk=require("os"),wm=require("path"),ac=require("fs"),{callWithRetry:$m}=nr(),{parseModelSpec:kk}=Re(),{extractJSON:ym,DECOMPOSE_PROMPT:vk,SYNTHESIZE_PROMPT:Sk}=Js(),{C:wt}=Me(),Br=wm.join(xk.homedir(),".nex-code","orchestrator-bench.json"),bm=[{id:"decompose_multi_bug",type:"decompose",prompt:"Fix 4 bugs: (1) 500 error on SmartThings API call, (2) invalid time format on Sunday schedule, (3) Google Auth callback fails with CORS, (4) contact search returns empty",expectedSubTasks:4,maxSubTasks:5},{id:"decompose_feature_mix",type:"decompose",prompt:"Add dark mode toggle to settings page, fix the broken login redirect, improve search performance by adding an index, update API docs for the new endpoints",expectedSubTasks:4,maxSubTasks:5},{id:"decompose_overlapping",type:"decompose",prompt:"Refactor auth.js to use JWT instead of sessions, update all tests that import auth.js, and add rate limiting to the login endpoint in auth.js",expectedSubTasks:3,maxSubTasks:4},{id:"decompose_single",type:"decompose",prompt:"Fix the broken CSS on the login page \u2014 the submit button is not aligned",expectedSubTasks:1,maxSubTasks:4},{id:"synthesize_clean",type:"synthesize",prompt:"Fix login and search bugs",subResults:[{task:"Fix login redirect",status:"done",result:"Changed auth.js line 42: fixed redirect URL to use req.originalUrl instead of hardcoded /",toolsUsed:["read_file","edit_file"]},{task:"Fix search index",status:"done",result:"Added index on users.email column in migration 20260323. Updated search.js to use indexed query.",toolsUsed:["write_file","edit_file"]}],expectedConflicts:0},{id:"synthesize_conflicts",type:"synthesize",prompt:"Fix config loading and add env validation",subResults:[{task:"Fix config loading",status:"done",result:"Modified config.js: changed loadConfig() to handle missing .env gracefully",toolsUsed:["edit_file"]},{task:"Add env validation",status:"done",result:"Modified config.js: added validateEnv() function that throws on missing required vars",toolsUsed:["edit_file"]}],expectedConflicts:1}];function _m(t,e){if(!Array.isArray(t))return 0;let n=0;n+=1.5;let o=Math.abs(t.length-e.expectedSubTasks);o===0?n+=3:o===1&&(n+=1.5),t.every(l=>l.task&&typeof l.task=="string"&&l.task.length>0)&&(n+=2);let r=t.flatMap(l=>Array.isArray(l.scope)?l.scope:[]),i=new Set(r);return r.length===i.size&&(n+=2),t.every(l=>typeof l.estimatedCalls=="number"||typeof l.estimatedSshCalls=="number")&&(n+=1.5),Math.min(10,Math.round(n*10)/10)}function xm(t,e){if(!t||typeof t!="object")return 0;let n=0;n+=1.5,t.summary&&t.summary.length>10&&(n+=2),t.commitMessage&&t.commitMessage.length>5&&(n+=2);let o=Array.isArray(t.conflicts)?t.conflicts:[];return e.expectedConflicts===0&&o.length===0||e.expectedConflicts>0&&o.length>0?n+=2.5:e.expectedConflicts>0&&o.length===0&&(n+=0),Array.isArray(t.filesChanged)&&t.filesChanged.length>0&&(n+=2),Math.min(10,Math.round(n*10)/10)}async function km(t,e){let n={};if(e){let s=kk(e);s.provider&&(n.provider=s.provider),s.model&&(n.model=s.model)}let o=Date.now();try{if(t.type==="decompose"){let s=vk.replace("{maxSubTasks}",String(t.maxSubTasks)).replace("{prompt}",t.prompt),r=await $m([{role:"system",content:s},{role:"user",content:t.prompt}],[],n),i=ym(r.content||""),c=Date.now()-o;return{score:_m(i,t),latencyMs:c}}if(t.type==="synthesize"){let s=t.subResults.map((d,f)=>{let m=d.status==="done"?"SUCCESS":"FAILED";return`--- Agent ${f+1} [${m}] ---
|
|
1139
1142
|
Task: ${d.task}
|
|
1140
1143
|
Result: ${d.result}
|
|
1141
1144
|
Tools: ${d.toolsUsed.join(", ")}`}).join(`
|
|
1142
1145
|
|
|
1143
|
-
`),r=
|
|
1144
|
-
${
|
|
1145
|
-
`);let e=` ${"Model".padEnd(25)} ${"Decompose".padEnd(10)} ${"Synthesize".padEnd(11)} ${"Speed".padEnd(8)} ${"Score".padEnd(8)}`;console.log(`${
|
|
1146
|
-
${
|
|
1147
|
-
`))}
|
|
1146
|
+
`),r=Sk.replace("{prompt}",t.prompt).replace("{results}",s),i=await $m([{role:"system",content:r},{role:"user",content:"Synthesize the sub-agent results above."}],[],n),c=ym(i.content||""),l=Date.now()-o;return{score:xm(c,t),latencyMs:l}}return{score:0,latencyMs:0,error:`Unknown scenario type: ${t.type}`}}catch(s){return{score:0,latencyMs:Date.now()-o,error:s.message}}}async function Ek(t={}){let e=t.models||["kimi-k2.5","qwen3.5:397b","minimax-m2.7:cloud"],n=t.onProgress||(()=>{}),o=[];for(let r of e){let i={model:r,scores:[],latencies:[]},c=[],l=[];for(let h of bm){n({model:r,scenario:h.id,done:!1});let p=await km(h,r);i.scores.push(p.score),i.latencies.push(p.latencyMs),h.type==="decompose"&&c.push(p.score),h.type==="synthesize"&&l.push(p.score),n({model:r,scenario:h.id,done:!0,score:p.score,error:p.error})}let u=c.length>0?c.reduce((h,p)=>h+p,0)/c.length:0,d=l.length>0?l.reduce((h,p)=>h+p,0)/l.length:0,f=i.latencies.reduce((h,p)=>h+p,0)/i.latencies.length,m=u*.6+d*.4;o.push({model:r,decompose:Math.round(u*10)/10,synthesize:Math.round(d*10)/10,avgLatency:Math.round(f),overall:Math.round(m*10)/10})}o.sort((r,i)=>i.overall-r.overall);let s=wm.dirname(Br);return ac.existsSync(s)||ac.mkdirSync(s,{recursive:!0}),ac.writeFileSync(Br,JSON.stringify({date:new Date().toISOString().slice(0,10),results:o},null,2)),o}function Tk(t){console.log(`
|
|
1147
|
+
${wt.bold}${wt.cyan}Orchestrator Model Benchmark${wt.reset}
|
|
1148
|
+
`);let e=` ${"Model".padEnd(25)} ${"Decompose".padEnd(10)} ${"Synthesize".padEnd(11)} ${"Speed".padEnd(8)} ${"Score".padEnd(8)}`;console.log(`${wt.dim}${e}${wt.reset}`),console.log(` ${wt.dim}${"\u2500".repeat(65)}${wt.reset}`);for(let n of t){let o=t.indexOf(n)===0?"\u{1F947}":t.indexOf(n)===1?"\u{1F948}":t.indexOf(n)===2?"\u{1F949}":" ",s=`${(n.avgLatency/1e3).toFixed(1)}s`;console.log(`${o} ${n.model.padEnd(25)} ${(n.decompose+"/10").padEnd(10)} ${(n.synthesize+"/10").padEnd(11)} ${s.padEnd(8)} ${wt.bold}${n.overall}/10${wt.reset}`)}t.length>0&&(console.log(`
|
|
1149
|
+
${wt.green}Best orchestrator: ${t[0].model} (${t[0].overall}/10)${wt.reset}`),console.log(` ${wt.dim}Saved to ${Br}${wt.reset}
|
|
1150
|
+
`))}vm.exports={runOrchestratorBenchmark:Ek,ORCHESTRATOR_SCENARIOS:bm,scoreDecompose:_m,scoreSynthesize:xm,runScenario:km,printResults:Tk,RESULTS_PATH:Br}});var Rm=G((TS,Tm)=>{var Rk=require("axios"),fo=require("fs"),Em=require("path"),Ck="nex-code",cc=Em.join(process.cwd(),".nex"),lc=Em.join(cc,"last-version-check");fo.existsSync(cc)||fo.mkdirSync(cc,{recursive:!0});async function Ak(){try{let t=Nk(),e=Date.now();if(t&&e-t<1440*60*1e3)return{hasNewVersion:!1};Mk(e);let n=Ok(),s=(await Rk.get(`https://registry.npmjs.org/${Ck}/latest`,{timeout:5e3})).data.version,r=Pk(s,n);return{hasNewVersion:r,latestVersion:r?s:void 0,currentVersion:r?n:void 0}}catch{return{hasNewVersion:!1}}}function Ok(){return In().version}function Nk(){try{if(fo.existsSync(lc)){let t=fo.readFileSync(lc,"utf8");return parseInt(t,10)}}catch{}return null}function Mk(t){try{fo.writeFileSync(lc,t.toString())}catch{}}function Pk(t,e){try{let n=t.split(".").map(Number),o=e.split(".").map(Number);return n[0]>o[0]?!0:n[0]<o[0]?!1:n[1]>o[1]?!0:n[1]<o[1]?!1:n[2]>o[2]}catch{return!1}}Tm.exports={checkForNewVersion:Ak}});var Um=G((CS,Fm)=>{var Ik=require("readline"),ot=require("fs"),Be=require("path"),{C:a,banner:Lk,cleanupTerminal:Cm}=Me(),{isDark:Dk}=hn(),{listProviders:fc,getActiveProviderName:Pn,listAllModels:RS,setFallbackChain:jk,getFallbackChain:qk,getProvider:Fk}=Re(),{flushAutoSave:Am}=Ot(),{getActiveModel:Vt,setActiveModel:pc}=Gn(),{printContext:Om}=dr(),{loadAllSkills:Uk,getSkillCommands:Gr,handleSkillCommand:Wk}=sn(),{setReadlineInterface:Bk,setAutoConfirm:Hk,getAutoConfirm:uc,setAllowAlwaysHandler:Gk}=Je(),{StickyFooter:Kk}=Pp(),Et=process.cwd(),Jt=null;function Nm(){return Jt?.signal??null}var ho=[{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:"/mcp list",desc:"List connected MCP servers and their tools"},{cmd:"/mcp status",desc:"Show which MCP servers are running"},{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:"/retry [--model <id>]",desc:"Retry last user turn (optionally with a different model)"},{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:"/orchestrate <prompt>",desc:"Decompose prompt into parallel sub-tasks, run, synthesize"},{cmd:"/bench-orchestrator",desc:"Benchmark models for orchestrator role"},{cmd:"/audit",desc:"Show tool execution audit log"},{cmd:"/k8s",desc:"Kubernetes overview: namespaces and pods"},{cmd:"/exit",desc:"Quit"}];function Mm(){let t=Gr(),e=[...ho,...t],n=Math.max(...e.map(o=>o.cmd.length));console.log("");for(let{cmd:o,desc:s}of ho)console.log(` ${a.cyan}${o.padEnd(n+2)}${a.reset}${a.dim}${s}${a.reset}`);for(let{cmd:o,desc:s}of t)console.log(` ${a.cyan}${o.padEnd(n+2)}${a.reset}${a.dim}${s} ${a.yellow}[skill]${a.reset}`);console.log(`
|
|
1148
1151
|
${a.dim}Type /help for detailed usage${a.reset}
|
|
1149
|
-
`)}function
|
|
1152
|
+
`)}function Pm(t){try{let e,n;t.endsWith("/")||t.endsWith(Be.sep)?(e=t,n=""):(e=Be.dirname(t),n=Be.basename(t)),e.startsWith("~")&&(e=Be.join(require("os").homedir(),e.slice(1)));let o=Be.isAbsolute(e)?e:Be.resolve(Et,e);if(!ot.existsSync(o)||!ot.statSync(o).isDirectory())return[];let s=ot.readdirSync(o,{withFileTypes:!0}),r=[];for(let i of s){if(i.name.startsWith(".")||i.name==="node_modules"||n&&!i.name.startsWith(n))continue;let c=t.endsWith("/")||t.endsWith(Be.sep)?t:Be.dirname(t)+"/",l=c==="./"&&!t.startsWith("./")?i.name:c+i.name;r.push(i.isDirectory()?l+"/":l)}return r}catch{return[]}}function Im(t){if(t.startsWith("/")){let o=[...ho,...Gr()],s=o.map(r=>r.cmd).filter(r=>r.startsWith(t));return[s.length?s:o.map(r=>r.cmd),t]}let e=t.split(/\s+/),n=e[e.length-1]||"";return n&&(n.includes("/")||n.startsWith("./")||n.startsWith("../")||n.startsWith("~"))?[Pm(n),n]:[[],t]}function Lm(){console.log(`
|
|
1150
1153
|
${a.bold}${a.cyan}Commands:${a.reset}
|
|
1151
1154
|
${a.cyan}/help${a.reset} ${a.dim}Show this help${a.reset}
|
|
1152
1155
|
${a.cyan}/model [spec]${a.reset} ${a.dim}Show/switch model (e.g. openai:gpt-4o, claude-sonnet)${a.reset}
|
|
@@ -1217,60 +1220,60 @@ ${a.bold}${a.cyan}Undo / Redo:${a.reset}
|
|
|
1217
1220
|
${a.cyan}/benchmark --models=a,b${a.reset}${a.dim} Custom model list${a.reset}
|
|
1218
1221
|
|
|
1219
1222
|
${a.cyan}/exit${a.reset} ${a.dim}Quit${a.reset}
|
|
1220
|
-
`)}function
|
|
1221
|
-
${a.bold}${a.cyan}Providers:${a.reset}`);for(let o of t){let s=o.provider===e,r=o.configured?`${a.green}\u2713${a.reset}`:`${a.red}\u2717${a.reset}`,i=s?` ${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===n.id&&s?` ${a.yellow}\u25C4${a.reset}`:"";console.log(` ${a.dim}${c.id}${a.reset} \u2014 ${c.name}${l}`)}}console.log()}async function
|
|
1222
|
-
${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=
|
|
1223
|
-
${a.dim}Breakdown:${a.reset}`),console.log(` System prompt: ${l.breakdown.system.toLocaleString()} tokens`),console.log(` Conversation: ${l.breakdown.conversation.toLocaleString()} tokens`),console.log(` Tool results: ${l.breakdown.toolResults.toLocaleString()} tokens`),console.log(` Tool definitions: ${l.breakdown.toolDefinitions.toLocaleString()} tokens`),console.log(` Messages: ${l.messageCount}`),console.log(),!0}case"/costs":{let{formatCosts:s,resetCosts:r}=
|
|
1223
|
+
`)}function Dm(t){let n=Math.round(t/100*30),o=30-n;return` ${t>80?a.red:t>50?a.yellow:a.green}${"\u2588".repeat(n)}${a.dim}${"\u2591".repeat(o)}${a.reset} ${t}%`}function dc(){let t=fc(),e=Pn(),n=Vt();console.log(`
|
|
1224
|
+
${a.bold}${a.cyan}Providers:${a.reset}`);for(let o of t){let s=o.provider===e,r=o.configured?`${a.green}\u2713${a.reset}`:`${a.red}\u2717${a.reset}`,i=s?` ${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===n.id&&s?` ${a.yellow}\u25C4${a.reset}`:"";console.log(` ${a.dim}${c.id}${a.reset} \u2014 ${c.name}${l}`)}}console.log()}async function jm(t,e){let[n,...o]=t.split(/\s+/);switch(n){case"/help":return Lm(),!0;case"/model":{let s=o.join(" ").trim();if(!s){if(e){let{showModelPicker:r}=Dp();await r(e)}else{let r=Vt(),i=Pn();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(s==="list")return dc(),!0;if(pc(s)){let r=Vt(),i=Pn();console.log(`${a.green}Switched to ${i}:${r.id} (${r.name})${a.reset}`)}else console.log(`${a.red}Unknown model: ${s}${a.reset}`),console.log(`${a.gray}Use /providers to see available models${a.reset}`);return!0}case"/providers":return dc(),!0;case"/fallback":{let s=o.join(" ").trim();if(!s){let i=qk();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=s.split(",").map(i=>i.trim()).filter(Boolean);return jk(r),console.log(`${a.green}Fallback chain: ${r.join(" \u2192 ")}${a.reset}`),!0}case"/tokens":{let{getConversationMessages:s}=ve(),{getUsage:r}=Ve(),{TOOL_DEFINITIONS:i}=Tt(),c=s(),l=r(c,i),u=Vt(),d=Pn();console.log(`
|
|
1225
|
+
${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=Dm(l.percentage);return console.log(` ${f}`),console.log(`
|
|
1226
|
+
${a.dim}Breakdown:${a.reset}`),console.log(` System prompt: ${l.breakdown.system.toLocaleString()} tokens`),console.log(` Conversation: ${l.breakdown.conversation.toLocaleString()} tokens`),console.log(` Tool results: ${l.breakdown.toolResults.toLocaleString()} tokens`),console.log(` Tool definitions: ${l.breakdown.toolDefinitions.toLocaleString()} tokens`),console.log(` Messages: ${l.messageCount}`),console.log(),!0}case"/costs":{let{formatCosts:s,resetCosts:r}=Hn();return o.join(" ").trim()==="reset"?(r(),console.log(`${a.green}Cost tracking reset${a.reset}`),!0):(console.log(`
|
|
1224
1227
|
${s()}
|
|
1225
|
-
`),!0)}case"/budget":{let{getCostLimits:s,getProviderSpend:r,checkBudget:i,removeCostLimit:c,saveCostLimits:l,setCostLimit:u}=
|
|
1226
|
-
${a.bold}${a.cyan}Cost Limits:${a.reset}`);let g=!1;for(let y of p){let w=r(y.provider),
|
|
1228
|
+
`),!0)}case"/budget":{let{getCostLimits:s,getProviderSpend:r,checkBudget:i,removeCostLimit:c,saveCostLimits:l,setCostLimit:u}=Hn(),d=o[0];if(!d){let h=s(),p=fc();console.log(`
|
|
1229
|
+
${a.bold}${a.cyan}Cost Limits:${a.reset}`);let g=!1;for(let y of p){let w=r(y.provider),x=h[y.provider];if(x!==void 0){g=!0;let R=Math.min(100,Math.round(w/x*100)),k=10,_=Math.round(R/100*k),b=k-_,M=`${R>=100?a.red:R>=80?a.yellow:a.green}${"\u2588".repeat(_)}${a.dim}${"\u2591".repeat(b)}${a.reset}`;console.log(` ${a.bold}${y.provider}:${a.reset} $${w.toFixed(2)} / $${x.toFixed(2)} (${R}%) ${M}`)}else y.provider==="ollama"||y.provider==="local"?console.log(` ${a.bold}${y.provider}:${a.reset} ${a.dim}free (no limit)${a.reset}`):w>0&&console.log(` ${a.bold}${y.provider}:${a.reset} $${w.toFixed(2)} ${a.dim}(no limit)${a.reset}`)}return g||console.log(` ${a.dim}No limits set. Use /budget <provider> <amount> to set one.${a.reset}`),console.log(),!0}let f=o[1];if(!f){let h=i(d);return h.limit!==null?console.log(`${a.bold}${d}:${a.reset} $${h.spent.toFixed(2)} / $${h.limit.toFixed(2)} ($${h.remaining.toFixed(2)} remaining)`):console.log(`${a.bold}${d}:${a.reset} $${h.spent.toFixed(2)} ${a.dim}(no limit)${a.reset}`),!0}if(f==="off"||f==="remove"||f==="clear")return c(d),l(),console.log(`${a.green}Removed cost limit for ${d}${a.reset}`),!0;let m=parseFloat(f);return isNaN(m)||m<=0?(console.log(`${a.red}Invalid amount: ${f}. Use a positive number or 'off'.${a.reset}`),!0):(u(d,m),l(),console.log(`${a.green}Set ${d} budget limit: $${m.toFixed(2)}${a.reset}`),!0)}case"/clear":{let{clearConversation:s,getConversationMessages:r}=ve(),{clearHistory:i}=Ht(),c=r();if(c.filter(d=>d.role==="user").length>=4){process.stdout.write(`${a.dim}Reflecting on session...${a.reset} `);let{learnFromSession:d}=ec();d(c).then(f=>{if(!f.skipped&&!f.error&&(f.applied.length>0||f.nexAdded.length>0)){let m=f.applied.length+f.nexAdded.length;process.stdout.write(`${a.green}${m} learning(s) saved${a.reset}
|
|
1227
1230
|
`)}else process.stdout.write(`${a.dim}nothing new${a.reset}
|
|
1228
1231
|
`)}).catch(()=>process.stdout.write(`
|
|
1229
|
-
`))}s(),i();let{deleteSession:u}=
|
|
1230
|
-
`):m=String(f.content),r(c.slice(0,l));let{resetSessionTracking:h}=ve();h();let p=d||"current model";return console.log(`${a.cyan}Retrying with ${p}...${a.reset}`),await i(m),!0}case"/context":return await
|
|
1232
|
+
`))}s(),i();let{deleteSession:u}=Ot();return u("_autosave"),console.log(`${a.green}Conversation cleared${a.reset}`),!0}case"/retry":{let{getConversationMessages:s,setConversationMessages:r,processInput:i}=ve(),c=s(),l=c.map(g=>g.role).lastIndexOf("user");if(l===-1)return console.log(`${a.yellow}Nothing to retry \u2014 no user message found.${a.reset}`),!0;let u=o.indexOf("--model"),d=u!==-1&&o[u+1]?o[u+1]:null;if(d){let{setActiveModel:g}=Re();if(!g(d))return console.log(`${a.red}Unknown model: ${d}. Use /providers to see available models.${a.reset}`),!0;console.log(`${a.cyan}Switched to model: ${d}${a.reset}`)}let f=c[l],m;typeof f.content=="string"?m=f.content:Array.isArray(f.content)?m=f.content.filter(g=>g&&g.type==="text").map(g=>g.text).join(`
|
|
1233
|
+
`):m=String(f.content),r(c.slice(0,l));let{resetSessionTracking:h}=ve();h();let p=d||"current model";return console.log(`${a.cyan}Retrying with ${p}...${a.reset}`),await i(m),!0}case"/context":return await Om(Et),!0;case"/tree":{let{generateFileTree:s}=dr(),r=parseInt(o.join(" ").trim(),10),i=!isNaN(r)&&r>0?Math.min(r,8):3,c=s(Et,{maxDepth:i,maxFiles:300});return console.log(`
|
|
1231
1234
|
${a.bold}${a.cyan}Project tree${a.reset}${a.dim} (depth ${i})${a.reset}
|
|
1232
1235
|
`),console.log(`${a.dim}${c}${a.reset}
|
|
1233
|
-
`),!0}case"/autoconfirm":{let s=!
|
|
1234
|
-
${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:s}=
|
|
1235
|
-
${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:s,readDocument:r,writeDocument:i,removeDocument:c,buildIndex:l,buildEmbeddingIndex:u,isEmbeddingAvailable:d,query:f}=
|
|
1236
|
+
`),!0}case"/autoconfirm":{let s=!uc();return Hk(s),console.log(`${a.green}Auto-confirm: ${s?"ON":"OFF"}${a.reset}`),s&&console.log(`${a.yellow} \u26A0 File changes will be applied without confirmation${a.reset}`),po(),!0}case"/save":{let{saveSession:s}=Ot(),{getConversationMessages:r}=ve(),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=Vt(),u=Pn();return s(i,c,{model:l.id,provider:u}),console.log(`${a.green}Session saved: ${i} (${c.length} messages)${a.reset}`),!0}case"/load":{let{loadSession:s}=Ot(),{setConversationMessages:r}=ve(),i=o.join(" ").trim();if(!i)return console.log(`${a.red}Usage: /load <name>${a.reset}`),!0;let c=s(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:s}=Ot(),r=s();if(r.length===0)return console.log(`${a.dim}No saved sessions${a.reset}`),!0;console.log(`
|
|
1237
|
+
${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:s}=Ot(),{setConversationMessages:r}=ve(),i=s();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:s}=an(),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),s(c,l),console.log(`${a.green}Remembered: ${c}${a.reset}`),!0}case"/forget":{let{forget:s}=an(),r=o.join(" ").trim();return r?(s(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:s}=an(),r=s();if(r.length===0)return console.log(`${a.dim}No memories saved${a.reset}`),!0;console.log(`
|
|
1238
|
+
${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:s,readDocument:r,writeDocument:i,removeDocument:c,buildIndex:l,buildEmbeddingIndex:u,isEmbeddingAvailable:d,query:f}=Ds(),m=o[0],h=o.slice(1).join(" ").trim();switch(m){case"add":{if(!h)return console.log(`${a.red}Usage: /brain add <name> [content]${a.reset}`),console.log(`${a.dim} /brain add api-notes \u2014 creates empty file${a.reset}`),console.log(`${a.dim} /brain add api-notes This is content \u2014 writes directly${a.reset}`),!0;let p=h.indexOf(" ");if(p<0){i(h,`# ${h}
|
|
1236
1239
|
|
|
1237
1240
|
`);let g=require("path").join(process.cwd(),".nex","brain",`${h}.md`);console.log(`${a.green}Created .nex/brain/${h}.md${a.reset}`),console.log(`${a.dim}Edit it directly at: ${g}${a.reset}`)}else{let g=h.substring(0,p),y=h.substring(p+1);i(g,y),console.log(`${a.green}Added to brain: ${g}${a.reset}`)}return!0}case"list":{let p=s();if(p.length===0)return console.log(`${a.dim}No brain documents yet. Use /brain add <name> to create one.${a.reset}`),!0;console.log(`
|
|
1238
|
-
${a.bold}${a.cyan}Brain Documents:${a.reset}`);let g=Math.max(8,...p.map(w=>w.name.length)),y=20;console.log(` ${"Name".padEnd(g+2)}${"Tags".padEnd(y)}${"Size".padStart(7)} Modified`),console.log(` ${"-".repeat(g+2)}${"-".repeat(y)}${"-".repeat(7)} --------`);for(let w of p){let{frontmatter:
|
|
1241
|
+
${a.bold}${a.cyan}Brain Documents:${a.reset}`);let g=Math.max(8,...p.map(w=>w.name.length)),y=20;console.log(` ${"Name".padEnd(g+2)}${"Tags".padEnd(y)}${"Size".padStart(7)} Modified`),console.log(` ${"-".repeat(g+2)}${"-".repeat(y)}${"-".repeat(7)} --------`);for(let w of p){let{frontmatter:x}=r(w.name),R=Array.isArray(x.tags)?x.tags.join(", "):"",k=w.size<1024?`${w.size}B`:`${(w.size/1024).toFixed(1)}K`,_=w.modified.toLocaleDateString();console.log(` ${a.cyan}${w.name.padEnd(g+2)}${a.reset}${a.dim}${R.substring(0,y-1).padEnd(y)}${k.padStart(7)} ${_}${a.reset}`)}return console.log(),!0}case"search":{if(!h)return console.log(`${a.red}Usage: /brain search <query>${a.reset}`),!0;let p=await f(h,{topK:5});if(p.length===0)return console.log(`${a.dim}No matching brain documents for: ${h}${a.reset}`),!0;console.log(`
|
|
1239
1242
|
${a.bold}${a.cyan}Brain Search: "${h}"${a.reset}`);for(let g of p){let y=typeof g.score=="number"?g.score.toFixed(2):g.score;console.log(`
|
|
1240
1243
|
${a.cyan}${g.name}${a.reset} ${a.dim}(score: ${y})${a.reset}`),console.log(` ${a.dim}${g.excerpt||""}${a.reset}`)}return console.log(),!0}case"show":{if(!h)return console.log(`${a.red}Usage: /brain show <name>${a.reset}`),!0;let p=r(h);return p.content?(console.log(`
|
|
1241
1244
|
${a.bold}${a.cyan}${h}.md${a.reset}
|
|
1242
|
-
`),console.log(p.content),!0):(console.log(`${a.red}Document not found: ${h}${a.reset}`),!0)}case"remove":{if(!h)return console.log(`${a.red}Usage: /brain remove <name>${a.reset}`),!0;let{confirm:p}=
|
|
1243
|
-
${a.bold}${a.cyan}Brain Status${a.reset}`),console.log(` Documents: ${p.length}`),console.log(` Index: ${g.existsSync(w)?a.green+"present"+a.reset:a.dim+"not built"+a.reset}`),console.log(` Embeddings: ${g.existsSync(
|
|
1245
|
+
`),console.log(p.content),!0):(console.log(`${a.red}Document not found: ${h}${a.reset}`),!0)}case"remove":{if(!h)return console.log(`${a.red}Usage: /brain remove <name>${a.reset}`),!0;let{confirm:p}=Je();if(!await p(`Remove brain document "${h}"?`))return console.log(`${a.dim}Cancelled${a.reset}`),!0;let y=c(h);return console.log(y?`${a.green}Removed: ${h}.md${a.reset}`:`${a.red}Document not found: ${h}${a.reset}`),!0}case"rebuild":{let p=l(),g=Object.keys(p.documents).length;return console.log(`${a.green}Index rebuilt: ${g} document(s)${a.reset}`),!0}case"embed":{if(!await d())return console.log(`${a.yellow}Ollama embedding model not available.${a.reset}`),console.log(`${a.dim}Set NEX_EMBED_MODEL env var (default: nomic-embed-text) and ensure Ollama is running.${a.reset}`),!0;console.log(`${a.dim}Building embedding index...${a.reset}`);try{let g=await u(),y=Object.keys(g.documents||{}).length;console.log(`${a.green}Embedding index built: ${y} document(s)${a.reset}`)}catch(g){console.log(`${a.red}Embedding failed: ${g.message}${a.reset}`)}return!0}case"status":{let p=s(),g=require("fs"),y=require("path"),w=y.join(process.cwd(),".nex","brain",".brain-index.json"),x=y.join(process.cwd(),".nex","brain",".embeddings.json");if(console.log(`
|
|
1246
|
+
${a.bold}${a.cyan}Brain Status${a.reset}`),console.log(` Documents: ${p.length}`),console.log(` Index: ${g.existsSync(w)?a.green+"present"+a.reset:a.dim+"not built"+a.reset}`),console.log(` Embeddings: ${g.existsSync(x)?a.green+"present"+a.reset:a.dim+"not built (run /brain embed)"+a.reset}`),p.length>0){let R=p.reduce((k,_)=>k+_.size,0);console.log(` Total size: ${R<1024?R+"B":(R/1024).toFixed(1)+"K"}`)}return console.log(),!0}case"review":{let{exec:p}=require("child_process"),{promisify:g}=require("util"),y=g(p);try{let{stdout:w}=await y("git diff .nex/brain/",{cwd:process.cwd()});w.trim()?(console.log(`
|
|
1244
1247
|
${a.bold}${a.cyan}Brain Changes (git diff):${a.reset}
|
|
1245
|
-
`),console.log(w)):console.log(`${a.dim}No pending brain changes (clean git state)${a.reset}`)}catch{console.log(`${a.dim}Not a git repo or no brain dir${a.reset}`)}return!0}case"undo":{let p=require("fs"),y=require("path").join(process.cwd(),".nex","brain");if(!p.existsSync(y))return console.log(`${a.dim}No brain directory found${a.reset}`),!0;let w=s();if(w.length===0)return console.log(`${a.dim}No brain documents to undo${a.reset}`),!0;let
|
|
1248
|
+
`),console.log(w)):console.log(`${a.dim}No pending brain changes (clean git state)${a.reset}`)}catch{console.log(`${a.dim}Not a git repo or no brain dir${a.reset}`)}return!0}case"undo":{let p=require("fs"),y=require("path").join(process.cwd(),".nex","brain");if(!p.existsSync(y))return console.log(`${a.dim}No brain directory found${a.reset}`),!0;let w=s();if(w.length===0)return console.log(`${a.dim}No brain documents to undo${a.reset}`),!0;let x=w[0],{exec:R}=require("child_process"),{promisify:k}=require("util"),_=k(R);try{await _(`git checkout -- ".nex/brain/${x.name}.md"`,{cwd:process.cwd()}),l(),console.log(`${a.green}Undone: restored ${x.name}.md from git${a.reset}`)}catch{console.log(`${a.red}Could not undo \u2014 not tracked in git or no prior version${a.reset}`)}return!0}default:{let p=s();if(p.length===0)console.log(`
|
|
1246
1249
|
${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(`
|
|
1247
1250
|
${a.dim}Commands: add \xB7 list \xB7 search \xB7 show \xB7 remove \xB7 rebuild \xB7 embed \xB7 status \xB7 review \xB7 undo${a.reset}
|
|
1248
1251
|
`);else{console.log(`
|
|
1249
1252
|
${a.bold}${a.cyan}Brain: ${p.length} document(s)${a.reset}`);for(let g of p){let{frontmatter:y}=r(g.name),w=Array.isArray(y.tags)?` [${y.tags.join(", ")}]`:"";console.log(` ${a.cyan}${g.name}${a.reset}${a.dim}${w}${a.reset}`)}console.log(`
|
|
1250
1253
|
${a.dim}Use /brain search <query> \xB7 /brain show <name> \xB7 /brain add <name>${a.reset}
|
|
1251
|
-
`)}return!0}}}case"/learn":{let{learnFromSession:s,learnBrainFromSession:r}=
|
|
1254
|
+
`)}return!0}}}case"/learn":{let{learnFromSession:s,learnBrainFromSession:r}=ec(),{getConversationMessages:i}=ve(),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([s(c),r(c)]);if(u.skipped&&(!d.written||d.written.length===0))return console.log(`${a.dim}Session too short${a.reset}`),!0;u.error&&console.log(`${a.red}Reflection error: ${u.error}${a.reset}`),console.log(""),u.summary&&(console.log(`${a.bold}Session:${a.reset} ${a.dim}${u.summary}${a.reset}`),console.log(""));let f=u.applied&&u.applied.length>0,m=u.nexAdded&&u.nexAdded.length>0,h=d.written&&d.written.length>0;if(!f&&!m&&!h)console.log(`${a.dim}No new learnings extracted from this session${a.reset}`);else{if(f){console.log(`${a.bold}${a.cyan}Memory updates:${a.reset}`);for(let{key:p,value:g,action:y}of u.applied){let w=y==="updated"?`${a.yellow}~${a.reset}`:`${a.green}+${a.reset}`;console.log(` ${w} ${a.bold}${p}${a.reset} = ${g}`)}}if(m){console.log(`${a.bold}${a.cyan}Added to NEX.md:${a.reset}`);for(let p of u.nexAdded)console.log(` ${a.green}+${a.reset} ${p}`)}if(h){console.log(`${a.bold}${a.cyan}Brain documents:${a.reset}`);for(let{name:p,reason:g,action:y}of d.written){let w=y==="updated"?`${a.yellow}~${a.reset}`:`${a.green}+${a.reset}`;console.log(` ${w} ${a.bold}${p}.md${a.reset}${g?a.dim+" \u2014 "+g+a.reset:""}`)}}}console.log("")}catch(u){console.log(`${a.red}Learn failed: ${u.message}${a.reset}`)}return!0}case"/optimize":{let{getConversationMessages:s}=ve(),{getUsage:r}=Ve(),{TOOL_DEFINITIONS:i}=Tt(),{listMemories:c}=an(),l=s(),u=r(l,i),d=Vt(),f=Pn(),m=c();console.log(`
|
|
1252
1255
|
${a.bold}${a.cyan}Optimization Report${a.reset}
|
|
1253
1256
|
`);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(`
|
|
1254
|
-
${a.bold}Memory:${a.reset} ${m.length} entries`),m.length===0)console.log(` ${a.yellow}\u2192 No memories yet. Use /learn after sessions or /remember key=value${a.reset}`);else{let R=[...m].sort((b,
|
|
1255
|
-
${a.bold}Active Model:${a.reset} ${f}:${d.id}`);let p=d.contextWindow||d.maxTokens||0;p>0&&p<32e3&&l.length>10?console.log(` ${a.yellow}\u2192 Small context window (${(p/1e3).toFixed(0)}k). Consider /model for larger context${a.reset}`):p>=128e3&&console.log(` ${a.green}\u2192 Large context window (${(p/1e3).toFixed(0)}k) \u2014 good for long sessions${a.reset}`);let g=l.filter(
|
|
1257
|
+
${a.bold}Memory:${a.reset} ${m.length} entries`),m.length===0)console.log(` ${a.yellow}\u2192 No memories yet. Use /learn after sessions or /remember key=value${a.reset}`);else{let R=[...m].sort((b,A)=>new Date(A.updatedAt)-new Date(b.updatedAt))[0],k=R?Math.round((Date.now()-new Date(R.updatedAt))/6e4):null,_=k!==null?k<60?`${k}m ago`:`${Math.round(k/60)}h ago`:"?";console.log(` ${a.dim}Latest update: ${_}${a.reset}`),m.length>30&&console.log(` ${a.yellow}\u2192 Many memories (${m.length}) \u2014 consider pruning with /forget${a.reset}`)}console.log(`
|
|
1258
|
+
${a.bold}Active Model:${a.reset} ${f}:${d.id}`);let p=d.contextWindow||d.maxTokens||0;p>0&&p<32e3&&l.length>10?console.log(` ${a.yellow}\u2192 Small context window (${(p/1e3).toFixed(0)}k). Consider /model for larger context${a.reset}`):p>=128e3&&console.log(` ${a.green}\u2192 Large context window (${(p/1e3).toFixed(0)}k) \u2014 good for long sessions${a.reset}`);let g=l.filter(x=>x.role==="user").length;console.log(`
|
|
1256
1259
|
${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=[],w=require("path").join(process.cwd(),"NEX.md");if(require("fs").existsSync(w)||y.push("Create NEX.md in project root to give nex-code project-specific instructions"),y.length>0){console.log(`
|
|
1257
|
-
${a.bold}Quick Wins:${a.reset}`);for(let
|
|
1260
|
+
${a.bold}Quick Wins:${a.reset}`);for(let x of y)console.log(` ${a.cyan}\u2192${a.reset} ${x}`)}return console.log(""),!0}case"/plan":{let{getActivePlan:s,approvePlan:r,startExecution:i,setPlanMode:c,getPlanContent:l,getPlanContent:u,formatPlan:d,extractStepsFromText:f,createPlan:m}=jt(),{invalidateSystemPromptCache:h}=ve(),p=o.join(" ").trim();if(p==="status"){let g=s();return console.log(d(g)),!0}if(p==="edit"){let g=l();if(!g)return console.log(`${a.yellow}No plan to edit. Generate a plan first with /plan${a.reset}`),!0;let y=require("os"),w=require("path").join(y.tmpdir(),`nex-plan-${Date.now()}.md`);require("fs").writeFileSync(w,g,"utf-8");let x=process.env.EDITOR||process.env.VISUAL||"nano",{spawnSync:R}=require("child_process");if(console.log(`${a.dim}Opening plan in ${x}... (save and close to update)${a.reset}`),R(x,[w],{stdio:"inherit"}).status===0){let{setPlanContent:_}=jt(),b=require("fs").readFileSync(w,"utf-8");_(b);let A=f(b);if(A.length>0){let O=s()?.task||"Task";m(O,A),console.log(`${a.green}Plan updated \u2014 ${A.length} steps extracted.${a.reset}`)}else console.log(`${a.green}Plan updated.${a.reset}`)}else console.log(`${a.yellow}Editor exited with error \u2014 plan unchanged.${a.reset}`);try{require("fs").unlinkSync(w)}catch{}return!0}if(p==="approve"){let g=l();if(r()){i(),c(!1),po(),h();let w=s()?.steps?.length||0,x=w>0?` (${w} 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:R}=ve(),k=`[PLAN APPROVED \u2014 EXECUTE NOW]
|
|
1258
1261
|
|
|
1259
1262
|
Implement the following plan step by step. All tools are now available.
|
|
1260
1263
|
|
|
1261
|
-
${g}`;try{await R(
|
|
1262
|
-
`)[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),
|
|
1264
|
+
${g}`;try{await R(k)}catch(_){console.log(`${a.red}Error: ${_.message?.split(`
|
|
1265
|
+
`)[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),po(),h(),console.log(`
|
|
1263
1266
|
${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}
|
|
1264
1267
|
${a.cyan}${a.bold}\u2502${a.reset} Analysis only \u2014 no file changes until approved ${a.cyan}${a.bold}\u2502${a.reset}
|
|
1265
1268
|
${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}
|
|
1266
|
-
${a.cyan}${a.bold}\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518${a.reset}`),p&&console.log(`${a.dim}Task: ${p}${a.reset}`),!0}case"/plans":{let{listPlans:s}=
|
|
1267
|
-
${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:s,setAutonomyLevel:r,AUTONOMY_LEVELS:i}=
|
|
1269
|
+
${a.cyan}${a.bold}\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518${a.reset}`),p&&console.log(`${a.dim}Task: ${p}${a.reset}`),!0}case"/plans":{let{listPlans:s}=jt(),r=s();if(r.length===0)return console.log(`${a.dim}No saved plans${a.reset}`),!0;console.log(`
|
|
1270
|
+
${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:s,setAutonomyLevel:r,AUTONOMY_LEVELS:i}=jt(),c=o.join(" ").trim();return c?(r(c)?(console.log(`${a.green}Autonomy: ${c}${a.reset}`),po()):console.log(`${a.red}Unknown level: ${c}. Use: ${i.join(", ")}${a.reset}`),!0):(console.log(`${a.bold}${a.cyan}Autonomy:${a.reset} ${s()}`),console.log(`${a.dim}Levels: ${i.join(", ")}${a.reset}`),!0)}case"/permissions":{let{listPermissions:s}=zs(),r=s();console.log(`
|
|
1268
1271
|
${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(`
|
|
1269
1272
|
${a.dim}Use /allow <tool> or /deny <tool> to change${a.reset}
|
|
1270
|
-
`),!0}case"/allow":{let{setPermission:s,savePermissions:r}=
|
|
1273
|
+
`),!0}case"/allow":{let{setPermission:s,savePermissions:r}=zs(),i=o.join(" ").trim();return i?(s(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:s,savePermissions:r}=zs(),i=o.join(" ").trim();return i?(s(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:s,isAuditEnabled:r}=ua();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=s(i);if(console.log(`
|
|
1271
1274
|
${a.bold}${a.cyan}Audit Summary (${i} day${i>1?"s":""})${a.reset}
|
|
1272
1275
|
`),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(`
|
|
1273
|
-
${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:s,commit:r,analyzeDiff:i,formatDiffSummary:c}=
|
|
1276
|
+
${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:s,commit:r,analyzeDiff:i,formatDiffSummary:c}=nn(),{confirm:l}=Je();if(!s())return console.log(`${a.red}Not a git repository${a.reset}`),!0;let u=o.join(" ").trim();if(u){let p=await r(u);return console.log(p?`${a.green}Committed: ${p} \u2014 ${u}${a.reset}`:`${a.red}Commit failed${a.reset}`),!0}if(!i())return console.log(`${a.yellow}No changes to commit${a.reset}`),!0;let f=await c();if(console.log(f),!await l(" Commit changes?"))return!0;let h=await r("nex-code update");return h&&console.log(`${a.green} \u2713 Committed: ${h}${a.reset}`),!0}case"/diff":{let{isGitRepo:s,formatDiffSummary:r}=nn();return s()?(console.log(r()),!0):(console.log(`${a.red}Not a git repository${a.reset}`),!0)}case"/review":{let{isGitRepo:s,getDiff:r}=nn(),{processInput:i}=ve(),c=o.join(" ").trim(),l=c.includes("--strict"),u=c.replace("--strict","").trim(),f=`## Review Protocol
|
|
1274
1277
|
|
|
1275
1278
|
**Phase 1 \u2014 Broad Scan:** Read the target code and identify all issues at a high level.
|
|
1276
1279
|
|
|
@@ -1313,29 +1316,29 @@ ${f}
|
|
|
1313
1316
|
|
|
1314
1317
|
\`\`\`diff
|
|
1315
1318
|
${g.substring(0,2e4)}
|
|
1316
|
-
\`\`\``}return await i(m),!0}case"/branch":{let{isGitRepo:s,getCurrentBranch:r,createBranch:i}=
|
|
1319
|
+
\`\`\``}return await i(m),!0}case"/branch":{let{isGitRepo:s,getCurrentBranch:r,createBranch:i}=nn();if(!s())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:s,connectAll:r,disconnectAll:i}=jo(),{getMcpTools:c,listMcpServers:l}=Vp(),u=o.join(" ").trim();if(u==="list"){let f=l(),m=s();if(f.length===0&&m.length===0)return console.log(`${a.dim}No MCP servers connected${a.reset}`),console.log(`${a.dim}Configure servers in .nex/mcp.json then run /mcp connect${a.reset}`),!0;console.log(`
|
|
1317
1320
|
${a.bold}${a.cyan}Connected MCP Servers:${a.reset}`),f.length===0&&console.log(` ${a.dim}(none connected \u2014 run /mcp connect)${a.reset}`);for(let h of f){console.log(` ${a.green}\u2713${a.reset} ${a.bold}${h.name}${a.reset} \u2014 ${h.toolCount} tool(s)`);let p=c().filter(g=>g.function.name.startsWith(`mcp_${h.name}_`));for(let g of p)console.log(` ${a.cyan}${g.function.name}${a.reset} ${a.dim}${g.function.description}${a.reset}`)}return console.log(),!0}if(u==="status"){let f=s(),m=l(),h=new Set(m.map(p=>p.name));if(f.length===0&&m.length===0)return console.log(`${a.dim}No MCP servers configured${a.reset}`),console.log(`${a.dim}Add a .nex/mcp.json file with a "servers" block${a.reset}`),!0;console.log(`
|
|
1318
1321
|
${a.bold}${a.cyan}MCP Server Status:${a.reset}`);for(let p of f){let g=p.connected?`${a.green}\u2713 connected${a.reset}`:`${a.dim}\u25CB disconnected${a.reset}`;console.log(` ${g} ${a.bold}${p.name}${a.reset} (${p.command}) \u2014 ${p.toolCount} tools`)}for(let p of m)f.find(g=>g.name===p.name)||console.log(` ${a.green}\u2713 connected${a.reset} ${a.bold}${p.name}${a.reset} \u2014 ${p.toolCount} tools`);return console.log(),!0}if(u==="connect")return console.log(`${a.dim}Connecting MCP servers...${a.reset}`),r().then(f=>{for(let m of f)m.error?console.log(` ${a.red}\u2717${a.reset} ${m.name}: ${m.error}`):console.log(` ${a.green}\u2713${a.reset} ${m.name}: ${m.tools} tools`);f.length===0&&console.log(`${a.dim}No MCP servers configured in .nex/config.json${a.reset}`)}).catch(f=>{console.log(`${a.red}MCP connection error: ${f.message}${a.reset}`)}),!0;if(u==="disconnect")return i(),console.log(`${a.green}All MCP servers disconnected${a.reset}`),!0;let d=s();if(d.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(`
|
|
1319
1322
|
${a.bold}${a.cyan}MCP Servers:${a.reset}`);for(let f of d){let m=f.connected?`${a.green}\u2713 connected${a.reset}`:`${a.dim}\u25CB disconnected${a.reset}`;console.log(` ${m} ${a.bold}${f.name}${a.reset} (${f.command}) \u2014 ${f.toolCount} tools`)}return console.log(`
|
|
1320
1323
|
${a.dim}Use /mcp connect to connect all servers${a.reset}
|
|
1321
|
-
`),!0}case"/hooks":{let{listHooks:s}=
|
|
1322
|
-
${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:s,enableSkill:r,disableSkill:i}=
|
|
1324
|
+
`),!0}case"/hooks":{let{listHooks:s}=Oa(),r=s();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(`
|
|
1325
|
+
${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:s,enableSkill:r,disableSkill:i}=sn(),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=s();if(l.length===0)return console.log(`${a.dim}No skills loaded${a.reset}`),console.log(`${a.dim}Add .md or .js files to .nex/skills/${a.reset}`),!0;console.log(`
|
|
1323
1326
|
${a.bold}${a.cyan}Skills:${a.reset}`);for(let u of l){let d=u.enabled?`${a.green}\u2713${a.reset}`:`${a.red}\u2717${a.reset}`,f=u.type==="prompt"?`${a.dim}(prompt)${a.reset}`:`${a.dim}(script)${a.reset}`,m=[];u.commands>0&&m.push(`${u.commands} cmd`),u.tools>0&&m.push(`${u.tools} tools`);let h=m.length>0?` \u2014 ${m.join(", ")}`:"";console.log(` ${d} ${a.bold}${u.name}${a.reset} ${f}${h}`)}return console.log(`
|
|
1324
1327
|
${a.dim}Use /skills enable <name> or /skills disable <name>${a.reset}
|
|
1325
|
-
`),!0}case"/install-skill":{let s=o.join(" ").trim();if(!s)return console.log(`${a.yellow}Usage: /install-skill <git-url-or-user/repo>${a.reset}`),!0;let{installSkill:r}=
|
|
1328
|
+
`),!0}case"/install-skill":{let s=o.join(" ").trim();if(!s)return console.log(`${a.yellow}Usage: /install-skill <git-url-or-user/repo>${a.reset}`),!0;let{installSkill:r}=sn();console.log(`${a.dim}Installing skill from ${s}...${a.reset}`);let i=await r(s);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 s=o.join(" ").trim();if(!s)return console.log(`${a.yellow}Usage: /search-skill <query>${a.reset}`),!0;let{searchSkills:r}=sn();console.log(`${a.dim}Searching for "${s}"...${a.reset}`);let i=await r(s);if(i.length===0)console.log(`${a.yellow}No skills found matching "${s}"${a.reset}`);else{console.log(`
|
|
1326
1329
|
${a.bold}Skills matching "${s}":${a.reset}
|
|
1327
1330
|
`);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}
|
|
1328
|
-
`))}return!0}case"/remove-skill":{let s=o.join(" ").trim();if(!s)return console.log(`${a.yellow}Usage: /remove-skill <name>${a.reset}`),!0;let{removeSkill:r}=
|
|
1331
|
+
`))}return!0}case"/remove-skill":{let s=o.join(" ").trim();if(!s)return console.log(`${a.yellow}Usage: /remove-skill <name>${a.reset}`),!0;let{removeSkill:r}=sn(),i=r(s);return i.ok?console.log(`${a.green}Skill "${s}" removed${a.reset}`):console.log(`${a.red}${i.error}${a.reset}`),!0}case"/tasks":{let{renderTaskList:s,clearTasks:r}=Qo();return o.join(" ").trim()==="clear"?(r(),console.log(`${a.green}Tasks cleared${a.reset}`),!0):(console.log(`
|
|
1329
1332
|
`+s()+`
|
|
1330
|
-
`),!0)}case"/undo":{let{undo:s,getUndoCount:r}=
|
|
1333
|
+
`),!0)}case"/undo":{let{undo:s,getUndoCount:r}=Ht(),i=s();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:s,getRedoCount:r}=Ht(),i=s();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:s,getUndoCount:r,getRedoCount:i}=Ht(),c=s(20);if(c.length===0)return console.log(`${a.dim}No file changes in this session${a.reset}`),!0;console.log(`
|
|
1331
1334
|
${a.bold}File Change History${a.reset}
|
|
1332
1335
|
`);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(`
|
|
1333
1336
|
${a.dim}${r()} undo / ${i()} redo available${a.reset}
|
|
1334
|
-
`),!0}case"/snapshot":{let{createSnapshot:s,listSnapshots:r}=
|
|
1335
|
-
${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=s(i,
|
|
1337
|
+
`),!0}case"/snapshot":{let{createSnapshot:s,listSnapshots:r}=Ht(),i=o.join(" ").trim()||void 0;if(i==="list"){let l=r(Et);if(l.length===0)console.log(`${a.dim}No snapshots found${a.reset}`);else{console.log(`
|
|
1338
|
+
${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=s(i,Et);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:s,listSnapshots:r}=Ht(),i=o.join(" ").trim()||"last";if(i==="list"){let l=r(Et);if(l.length===0)console.log(`${a.dim}No snapshots available${a.reset}`);else{console.log(`
|
|
1336
1339
|
${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(`
|
|
1337
1340
|
${a.dim}Usage: /restore <name|last>${a.reset}
|
|
1338
|
-
`)}return!0}let c=s(i,
|
|
1341
|
+
`)}return!0}let c=s(i,Et);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 s=o.join(" ").trim(),{exec:r}=require("child_process"),{promisify:i}=require("util"),c=i(r),l=s||null,u=l?`ssh -o ConnectTimeout=10 -o BatchMode=yes ${l.replace(/[^a-zA-Z0-9@._-]/g,"")} `:"",d=f=>l?`${u}"${f.replace(/"/g,'\\"')}"`:f;console.log(`
|
|
1339
1342
|
${a.bold}${a.cyan}Kubernetes Overview${a.reset}${l?a.dim+" (remote: "+l+")"+a.reset:""}
|
|
1340
1343
|
`);try{let{stdout:f}=await c(d("kubectl get namespaces --no-headers -o custom-columns=NAME:.metadata.name"),{timeout:15e3}),m=f.trim().split(`
|
|
1341
1344
|
`).filter(Boolean);console.log(`${a.bold}Namespaces (${m.length}):${a.reset}`);for(let h of m)console.log(` ${a.cyan}${h}${a.reset}`);console.log()}catch{return console.log(`${a.dim}Could not reach cluster \u2014 is kubectl configured?${a.reset}
|
|
@@ -1343,71 +1346,71 @@ ${a.bold}${a.cyan}Kubernetes Overview${a.reset}${l?a.dim+" (remote: "+l+")"+a.re
|
|
|
1343
1346
|
`).filter(Boolean),h=m.filter(w=>w.includes("Running")).length,p=m.filter(w=>w.includes("Pending")).length,g=m.filter(w=>w.includes("Failed")||w.includes("Error")||w.includes("CrashLoop")).length;console.log(`${a.bold}Pods: ${m.length} total ${a.green}${h} running${a.reset} ${a.yellow}${p} pending${a.reset} ${a.red}${g} unhealthy${a.reset}
|
|
1344
1347
|
`);let y=m.filter(w=>!w.includes("Running")&&!w.includes("<none>"));if(y.length>0){console.log(`${a.bold}${a.red}Unhealthy Pods:${a.reset}`);for(let w of y)console.log(` ${a.red}${w}${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}
|
|
1345
1348
|
`)}catch(f){console.log(`${a.dim}Could not list pods: ${f.message}${a.reset}
|
|
1346
|
-
`)}return!0}case"/servers":{let{loadServerProfiles:s,resolveProfile:r,sshExec:i}=
|
|
1349
|
+
`)}return!0}case"/servers":{let{loadServerProfiles:s,resolveProfile:r,sshExec:i}=Jn(),c=s(),l=Object.keys(c);if(l.length===0)return console.log(`
|
|
1347
1350
|
${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}
|
|
1348
1351
|
`),!0;if(o[0]==="ping"){let f=o[1]?[o[1]]:l;return console.log(`
|
|
1349
|
-
${a.bold}${a.cyan}Server connectivity:${a.reset}`),await Promise.all(f.map(async m=>{if(!c[m]){console.log(` ${a.red}\u2717${a.reset} ${m} \u2014 unknown profile`);return}try{let h={...c[m],_name:m},{exitCode:p}=await i(h,"echo ok",{timeout:8e3});console.log(p===0?` ${a.green}\u2713${a.reset} ${m} (${h.user?h.user+"@":""}${h.host})`:` ${a.red}\u2717${a.reset} ${m} (${h.host}) \u2014 SSH failed (exit ${p})`)}catch(h){console.log(` ${a.red}\u2717${a.reset} ${m} \u2014 ${h.message}`)}})),console.log(""),!0}let{formatProfile:d}=
|
|
1352
|
+
${a.bold}${a.cyan}Server connectivity:${a.reset}`),await Promise.all(f.map(async m=>{if(!c[m]){console.log(` ${a.red}\u2717${a.reset} ${m} \u2014 unknown profile`);return}try{let h={...c[m],_name:m},{exitCode:p}=await i(h,"echo ok",{timeout:8e3});console.log(p===0?` ${a.green}\u2713${a.reset} ${m} (${h.user?h.user+"@":""}${h.host})`:` ${a.red}\u2717${a.reset} ${m} (${h.host}) \u2014 SSH failed (exit ${p})`)}catch(h){console.log(` ${a.red}\u2717${a.reset} ${m} \u2014 ${h.message}`)}})),console.log(""),!0}let{formatProfile:d}=Jn();console.log(`
|
|
1350
1353
|
${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(`
|
|
1351
1354
|
${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}
|
|
1352
|
-
`),!0}case"/docker":{let{loadServerProfiles:s,sshExec:r}=
|
|
1355
|
+
`),!0}case"/docker":{let{loadServerProfiles:s,sshExec:r}=Jn(),{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=s(),f=[["local",null],...Object.entries(d)];console.log(`
|
|
1353
1356
|
${a.bold}${a.cyan}Docker Containers:${a.reset}`);for(let[m,h]of f){let p=m==="local"?`${a.dim}local${a.reset}`:`${a.cyan}${m}${a.reset}`;try{let g;if(m==="local"){let{stdout:y}=await l(u,{timeout:8e3});g=(y||"").trim()}else{let y=await r(h,u,{timeout:1e4});if(g=[y.stdout,y.stderr].filter(Boolean).join("").trim(),y.exitCode!==0){console.log(` ${p}: ${a.red}SSH error (${y.exitCode})${a.reset}`);continue}}!g||g==="NAMES IMAGE STATUS PORTS"?console.log(` ${p}: ${a.dim}(no containers)${a.reset}`):(console.log(` ${p}:`),g.split(`
|
|
1354
|
-
`).forEach(y=>console.log(` ${a.dim}${y}${a.reset}`)))}catch(g){console.log(` ${p}: ${a.red}${g.message}${a.reset}`)}}return console.log(""),!0}case"/deploy":{let{loadDeployConfigs:s}=
|
|
1357
|
+
`).forEach(y=>console.log(` ${a.dim}${y}${a.reset}`)))}catch(g){console.log(` ${p}: ${a.red}${g.message}${a.reset}`)}}return console.log(""),!0}case"/deploy":{let{loadDeployConfigs:s}=Xi(),r=s(),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}=Tt();console.log(`
|
|
1355
1358
|
${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(`
|
|
1356
1359
|
${a.dim}No deploy configs. Run /init to create .nex/deploy.json${a.reset}
|
|
1357
1360
|
`),!0;console.log(`
|
|
1358
1361
|
${a.bold}${a.cyan}Deploy configs (${i.length}):${a.reset}`);for(let[l,u]of Object.entries(r)){let d=u.method||"rsync",f=`[${d}]`,m=d==="git"?`${u.server}:${u.remote_path}${u.branch?` (${u.branch})`:""}`:`${u.local_path||""} \u2192 ${u.server}:${u.remote_path}`,h=[u.deploy_script?`script: ${u.deploy_script}`:null,u.health_check?`health: ${u.health_check}`:null].filter(Boolean).map(p=>` ${a.dim}\u2192 ${p}${a.reset}`).join("");console.log(` ${a.green}${l}${a.reset} ${a.dim}${f} ${m}${a.reset}${h}`)}return console.log(`
|
|
1359
1362
|
${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}
|
|
1360
|
-
`),!0}case"/init":{let{runServerWizard:s,runDeployWizard:r,setWizardRL:i}=
|
|
1361
|
-
${a.bold}${a.cyan}OpenClaw Nightly Results (${
|
|
1362
|
-
`),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 R=[];for(let
|
|
1363
|
-
${a.bold}Trend:${a.reset} ${
|
|
1364
|
-
${a.bold}Checking Ollama Cloud for new models...${a.reset}`);let b;try{b=await y()}catch(K){console.log(`${a.red}Discovery failed: ${K.message}${a.reset}`);break}let{newModels:
|
|
1365
|
-
`);break}console.log(`${a.cyan}New models to benchmark (${
|
|
1366
|
-
`);let
|
|
1367
|
-
`),
|
|
1368
|
-
`);try{
|
|
1363
|
+
`),!0}case"/init":{let{runServerWizard:s,runDeployWizard:r,setWizardRL:i}=tm();return i(e),o[0]==="deploy"?await r():await s(),!0}case"/setup":{let{runSetupWizard:s}=Va();return await s({rl:e,force:!0}),!0}case"/benchmark":{if(o.includes("--history")){let y=require("os"),w=Be.join(y.homedir(),"Coding","nex-code-benchmarks","results");if(!ot.existsSync(w)){console.log(`${a.yellow}No nightly results at ${w}${a.reset}`),console.log(`${a.dim}Use /benchmark (no flags) to run a live model comparison.${a.reset}`);break}let x=ot.readdirSync(w).filter(k=>k.endsWith(".json")).sort().slice(-7);if(x.length===0){console.log(`${a.yellow}No result files found${a.reset}`);break}console.log(`
|
|
1364
|
+
${a.bold}${a.cyan}OpenClaw Nightly Results (${x.length}-day trend)${a.reset}
|
|
1365
|
+
`),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 R=[];for(let k of x)try{let _=JSON.parse(ot.readFileSync(Be.join(w,k),"utf-8")),b=k.replace(".json",""),A=_.tasks?.length||_.total||0,M=_.tasks?.filter(ge=>ge.passed||ge.score>=.7)?.length||_.passed||0,O=_.score??_.overall_score??(A>0?Math.round(M/A*100):"N/A"),N=_.model||_.config?.model||"unknown";R.push({date:b,model:N,total:A,passed:M,score:O});let he=typeof O=="number"?O>=80?a.green:O>=60?a.yellow:a.red:a.dim;console.log(` ${b.padEnd(12)} ${N.substring(0,24).padEnd(25)} ${he}${String(O).padEnd(8)}${a.reset} ${M}/${A}`)}catch{}if(R.length>=2){let k=R[0].score,_=R[R.length-1].score;if(typeof k=="number"&&typeof _=="number"){let b=_-k,A=b>0?`${a.green}\u25B2 +${b}`:b<0?`${a.red}\u25BC ${b}`:`${a.dim}\u2192 stable`;console.log(`
|
|
1366
|
+
${a.bold}Trend:${a.reset} ${A}${a.reset} over ${R.length} days`)}}console.log();break}if(o.includes("--discover")){let{findNewModels:y,markBenchmarked:w,updateReadme:x,updateModelsEnv:R}=Fr(),{runDiscoverBenchmark:k,buildSummary:_}=Mn();console.log(`
|
|
1367
|
+
${a.bold}Checking Ollama Cloud for new models...${a.reset}`);let b;try{b=await y()}catch(K){console.log(`${a.red}Discovery failed: ${K.message}${a.reset}`);break}let{newModels:A,allCloud:M}=b;if(console.log(`${a.dim}${M.length} models available on cloud${a.reset}`),A.length===0){console.log(`${a.green}No new models since last benchmark run.${a.reset}
|
|
1368
|
+
`);break}console.log(`${a.cyan}New models to benchmark (${A.length}):${a.reset} ${A.join(", ")}
|
|
1369
|
+
`);let O=require("os"),N=Be.join(O.homedir(),".nex-code","benchmark-results.json"),he=[];try{ot.existsSync(N)&&(he=JSON.parse(ot.readFileSync(N,"utf-8")))}catch{}let ge="",ce=await k({newModels:A,existingRanking:he,onProgress:({model:K,task:oe,done:L,score:U,error:re})=>{if(!L){K!==ge&&(ge&&process.stdout.write(`
|
|
1370
|
+
`),ge=K,process.stdout.write(`${a.cyan}${K}${a.reset} `));return}let ee=re?`${a.red}\u2717${a.reset}`:U>=80?`${a.green}\xB7${a.reset}`:U>=40?`${a.yellow}\xB7${a.reset}`:`${a.red}\xB7${a.reset}`;process.stdout.write(ee)}});ge&&process.stdout.write(`
|
|
1371
|
+
`);try{ot.writeFileSync(N,JSON.stringify(ce,null,2))}catch{}w(M);let ue=Be.join(process.cwd(),"README.md"),Z=x(ce,ue),de=R(ce),{buildCategoryWinners:X}=Mn(),{updateRoutingConfig:E}=Fr(),P=X(ce),F=E(P);if(Z&&console.log(`${a.green}README.md benchmark table updated${a.reset}`),de.updated?console.log(`${a.green}DEFAULT_MODEL: ${de.previousModel} \u2192 ${de.newModel}${a.reset}`):de.reason&&console.log(`${a.dim}models.env unchanged: ${de.reason}${a.reset}`),F.changes.length>0){console.log(`${a.green}Routing updated:${a.reset}`);for(let K of F.changes)console.log(` ${a.dim}${K}${a.reset}`)}return console.log(),!0}let{runBenchmark:s,DEFAULT_MODELS:r,QUICK_MODELS:i}=Mn(),c=o.includes("--quick"),l=o.find(y=>y.startsWith("--models=")),u=l?l.replace("--models=","").split(",").map(y=>y.trim()).filter(Boolean):[],d=c?7:15,f=u.length>0?u:c?i:r;console.log(`
|
|
1369
1372
|
${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}
|
|
1370
|
-
`);let m="",h=0,p=d*f.length,g=await s({models:f,quick:c,onProgress:({model:y,task:w,done:
|
|
1371
|
-
`),m=y,process.stdout.write(`${a.cyan}${y}${a.reset} `));return}h++;let _=
|
|
1372
|
-
`),!c&&g&&g.length>0){let{buildCategoryWinners:y}=
|
|
1373
|
-
${a.bold}Per-category routing saved:${a.reset}`);for(let
|
|
1373
|
+
`);let m="",h=0,p=d*f.length,g=await s({models:f,quick:c,onProgress:({model:y,task:w,done:x,score:R,error:k})=>{if(!x){y!==m&&(m&&process.stdout.write(`
|
|
1374
|
+
`),m=y,process.stdout.write(`${a.cyan}${y}${a.reset} `));return}h++;let _=k?`${a.red}\u2717${a.reset}`:R>=80?`${a.green}\xB7${a.reset}`:R>=40?`${a.yellow}\xB7${a.reset}`:`${a.red}\xB7${a.reset}`;process.stdout.write(_)}});if(m&&process.stdout.write(`
|
|
1375
|
+
`),!c&&g&&g.length>0){let{buildCategoryWinners:y}=Mn(),{updateRoutingConfig:w,updateReadme:x,updateModelsEnv:R}=Fr(),k=y(g),_=w(k);if(_.changes.length>0){console.log(`
|
|
1376
|
+
${a.bold}Per-category routing saved:${a.reset}`);for(let O of _.changes)console.log(` ${a.dim}${O}${a.reset}`)}let b=Be.join(process.cwd(),"README.md");x(g,b)&&console.log(`${a.green}README.md updated${a.reset}`),R(g);let A=require("os"),M=Be.join(A.homedir(),".nex-code","benchmark-results.json");try{ot.writeFileSync(M,JSON.stringify(g,null,2))}catch{}}return!0}case"/bench":{let{runJarvisBenchmark:s}=Mn(),r=o.includes("--dry-run"),i=o.find(l=>l.startsWith("--model=")),c=i?i.replace("--model=","").trim():void 0;return r||console.log(`
|
|
1374
1377
|
${a.bold}Jarvis Benchmark${a.reset} ${a.dim}5 agentic scenarios \xB7 each run as child process${a.reset}
|
|
1375
|
-
`),await s({dryRun:r,model:c,cwd:
|
|
1376
|
-
`)}}}),!0}case"/trend":{let{showScoreTrend:s}=
|
|
1378
|
+
`),await s({dryRun:r,model:c,cwd:Et,onProgress:({id:l,name:u,done:d,score:f,grade:m})=>{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 (${m})${a.reset}
|
|
1379
|
+
`)}}}),!0}case"/trend":{let{showScoreTrend:s}=Mn(),r=parseInt(o[0],10)||10;return s(r),!0}case"/orchestrate":{let s=o.join(" ").trim();if(!s)return console.log(`${a.yellow}Usage: /orchestrate <prompt>${a.reset}`),console.log(`${a.dim}Example: /orchestrate fix login bug, update docs, add dark mode${a.reset}`),!0;let{runOrchestrated:r}=Js();return await r(s),!0}case"/bench-orchestrator":{let{runOrchestratorBenchmark:s,printResults:r}=Sm(),i=o.find(u=>u.startsWith("--models=")),c=i?i.replace("--models=","").split(",").map(u=>u.trim()):void 0,l=await s({models:c,onProgress:({model:u,scenario:d,done:f,score:m,error:h})=>{f?h?process.stdout.write(` ${a.red}ERR${a.reset}
|
|
1377
1380
|
`):process.stdout.write(` ${a.green}${m}/10${a.reset}
|
|
1378
|
-
`):process.stdout.write(`${a.dim} \u2192 ${u}: ${d}...${a.reset}`)}});return r(l),!0}case"/exit":case"/quit":process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J"),process.exit(0);default:if(
|
|
1379
|
-
`).filter(Boolean).slice(-
|
|
1380
|
-
`)}catch{}}function
|
|
1381
|
-
`),!0):!1)(),c=(async()=>{if(process.env.NEX_DISABLE_UPDATE_CHECK==="1")return{hasNewVersion:!1};try{let{checkForNewVersion:
|
|
1381
|
+
`):process.stdout.write(`${a.dim} \u2192 ${u}: ${d}...${a.reset}`)}});return r(l),!0}case"/exit":case"/quit":process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J"),process.exit(0);default:if(Wk(t))return!0;{let s=[...ho,...Gr()].map(l=>l.cmd.split(" ")[0]),r=(l,u)=>{let d=l.length,f=u.length,m=Array.from({length:d+1},(h,p)=>Array.from({length:f+1},(g,y)=>p===0?y:y===0?p:0));for(let h=1;h<=d;h++)for(let p=1;p<=f;p++)m[h][p]=l[h-1]===u[p-1]?m[h-1][p-1]:1+Math.min(m[h-1][p],m[h][p-1],m[h-1][p-1]);return m[d][f]},i=null,c=3;for(let l of s){let u=r(n,l);u<c&&(c=u,i=l)}console.log(i?`${a.red}Unknown command: ${n}.${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: ${n}. Type /help${a.reset}`)}return!0}}var mc=1e3;function hc(){return Be.join(process.cwd(),".nex","repl_history")}function qm(){try{let t=hc();if(ot.existsSync(t))return ot.readFileSync(t,"utf-8").split(`
|
|
1382
|
+
`).filter(Boolean).slice(-mc)}catch{}return[]}function Hr(t){try{let e=hc(),n=Be.dirname(e);ot.existsSync(n)||ot.mkdirSync(n,{recursive:!0}),ot.appendFileSync(e,t+`
|
|
1383
|
+
`)}catch{}}function bt(){return`${a.bold}${a.cyan}>${a.reset} `}function po(){if(!global._nexFooter)return;let{isPlanMode:t,getAutonomyLevel:e}=jt(),{getAutoConfirm:n}=Je(),o=[];t()&&o.push("plan");let s=e();s==="semi-auto"&&o.push("semi"),s==="autonomous"&&o.push("auto"),n()&&o.push("always"),global._nexFooter.setStatusInfo({mode:o.join(" \xB7 ")})}var gc="\x1B[200~",$c="\x1B[201~";function Yk(t){return typeof t=="string"&&t.includes(gc)}function zk(t){return typeof t=="string"&&t.includes($c)}function mo(t){return typeof t!="string"?t:t.split(gc).join("").split($c).join("")}async function Xk(){if(!Fk("local"))return!1;try{let{exec:e}=require("child_process"),{promisify:n}=require("util");return await n(e)("curl -s --max-time 1 http://localhost:11434/api/tags"),pc("local:llama3"),!0}catch{return!1}}async function Jk(){let{setAbortSignalGetter:t,getConversationLength:e,processInput:n}=ve();t(Nm);let s=fc().some(L=>L.configured),r=(async()=>{Uk();let L=Vt(),U=Pn();return{model:L,providerName:U}})(),i=(async()=>s?!0:await Xk()?(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}
|
|
1384
|
+
`),!0):!1)(),c=(async()=>{if(process.env.NEX_DISABLE_UPDATE_CHECK==="1")return{hasNewVersion:!1};try{let{checkForNewVersion:L}=Rm();return await L()}catch{return{hasNewVersion:!1}}})(),[l,u,d]=await Promise.all([r,i,c]);!u&&!s&&(console.error(`
|
|
1382
1385
|
${a.red}\u2717 No provider configured and no local Ollama detected.${a.reset}
|
|
1383
|
-
`),process.exit(1));let{loadPersistedHistory:f,pruneHistory:m}=
|
|
1384
|
-
${
|
|
1386
|
+
`),process.exit(1));let{loadPersistedHistory:f,pruneHistory:m}=Ht();f().then(L=>{}),m().catch(()=>{});let h=qm(),p=Ik.createInterface({input:process.stdin,output:process.stdout,prompt:bt(),completer:Im,history:h,historySize:mc});Bk(p);let{setAskUserHandler:g}=Tt();g(async(L,U)=>{let re="\x1B[0m",ee="\x1B[1m",te="\x1B[2m",$e="\x1B[36m";return process.stdout.write(`
|
|
1387
|
+
${ee}\x1B[33m\u2753${re} ${ee}${L}${re}
|
|
1385
1388
|
|
|
1386
|
-
`),
|
|
1387
|
-
`)}),process.stdout.write(` ${
|
|
1389
|
+
`),U.forEach((we,be)=>{process.stdout.write(` ${$e}${be+1}${re} ${we}
|
|
1390
|
+
`)}),process.stdout.write(` ${te}${U.length+1}${re} ${te}Eigene Antwort\u2026${re}
|
|
1388
1391
|
`),process.stdout.write(`
|
|
1389
|
-
${
|
|
1390
|
-
`),we(
|
|
1391
|
-
`),we(
|
|
1392
|
-
`),we(
|
|
1393
|
-
`),await
|
|
1394
|
-
${a.yellow} Task cancelled. Press Ctrl+C again to exit.${a.reset}`),
|
|
1395
|
-
`).replace(/\r/g,"").trim();if(
|
|
1396
|
-
`).length,
|
|
1397
|
-
`)),
|
|
1398
|
-
`)),!0}if(
|
|
1399
|
-
`)),
|
|
1400
|
-
`)),!0}return
|
|
1401
|
-
`)&&
|
|
1402
|
-
`)),
|
|
1403
|
-
${
|
|
1404
|
-
`),p.prompt()}return}if(
|
|
1405
|
-
`).trim();if(
|
|
1406
|
-
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${we}${a.reset}`)}}
|
|
1407
|
-
`).trim();if(
|
|
1408
|
-
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${be}${a.reset}`)}}let{getConversationLength
|
|
1409
|
-
`).forEach((we,be)=>{let
|
|
1410
|
-
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${
|
|
1392
|
+
${$e}[1-${U.length+1}]${re} \u203A `),new Promise(we=>{p.resume(),p.once("line",be=>{let He=be.trim(),Ge=parseInt(He);Ge>=1&&Ge<=U.length?(process.stdout.write(`
|
|
1393
|
+
`),we(U[Ge-1])):Ge===U.length+1||He===""?(process.stdout.write(` ${$e}\u203A${re} `),p.once("line",Ut=>{process.stdout.write(`
|
|
1394
|
+
`),we(Ut.trim()||"")})):(process.stdout.write(`
|
|
1395
|
+
`),we(He))})})});let y=new Kk;y.activate(p),global._nexFooter=y,global._nexRawWrite=L=>y.rawWrite(L),Gk(()=>po()),process.stdout.isTTY&&process.stdout.write("\x1B[H\x1B[2J\x1B[3J");let w=l.providerName==="ollama"?l.model.id:`${l.providerName}:${l.model.id}`;Lk(w,Et,{yolo:uc()});{y.setStatusInfo({model:w,branch:"",project:Be.basename(Et)});let{execFile:L}=require("child_process");L("git",["rev-parse","--abbrev-ref","HEAD"],{encoding:"utf8"},(U,re)=>{!U&&re&&y.setStatusInfo({model:w,branch:re.trim(),project:Be.basename(Et)})})}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}
|
|
1396
|
+
`),await Om(Et);let x=!1,R=0,k=!1,_=null;function b(){Am(),y.deactivate(),Cm(),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",b),process.on("exit",()=>{Am()}),p.on("SIGINT",()=>{if(Cm(),R++,R>=2){b();return}if(x){Jt&&Jt.abort();let{cancelPendingAskUser:L}=Tt();L(),console.log(`
|
|
1397
|
+
${a.yellow} Task cancelled. Press Ctrl+C again to exit.${a.reset}`),x=!1,p.setPrompt(bt()),p.prompt()}else console.log(`${a.dim} (Press Ctrl+C again to exit)${a.reset}`),p.setPrompt(bt()),p.prompt(),_&&clearTimeout(_),_=setTimeout(()=>{R=0,_=null},2e3)}),process.on("SIGINT",()=>{process.stdin.isTTY?(R++,R>=2&&b()):b()});let A=!1,M=[],O=0,N={},he=!1;function ge(){let L=M.join(`
|
|
1398
|
+
`).replace(/\r/g,"").trim();if(M=[],A=!1,!L)return!0;O++,he=!0;let U=O;N[U]=L;let re=L.split(`
|
|
1399
|
+
`).length,ee=re>1?`[Pasted content #${U} \u2014 ${re} lines]`:`[Pasted content #${U}]`,te=p.line||"",$e=te&&!te.endsWith(" ")?" ":"",pe=te+$e+ee;return p.setPrompt(bt()),p.prompt(),p.line=pe,p.cursor=pe.length,p._refreshLine(),!0}function ce(L){return L.replace(/\[Pasted content #(\d+)(?:[^\]]*)\]/g,(U,re)=>N[Number(re)]||"")}function ue(){O=0,N={},he=!1}if(process.stdin.isTTY){process.stdout.write("\x1B[?2004h");let L=process.stdin.emit.bind(process.stdin);process.stdin.emit=function(U,...re){if(U!=="data")return L.call(process.stdin,U,...re);let ee=re[0];if(Buffer.isBuffer(ee)&&(ee=ee.toString("utf8")),typeof ee!="string")return L.call(process.stdin,U,...re);let te=ee.includes(gc),$e=ee.includes($c);if(te&&$e){let pe=mo(ee);return pe&&M.push(...pe.split(`
|
|
1400
|
+
`)),ge()}if(te){A=!0,M=[];let pe=mo(ee);return pe&&M.push(...pe.split(`
|
|
1401
|
+
`)),!0}if($e){let pe=mo(ee);return pe&&M.push(...pe.split(`
|
|
1402
|
+
`)),ge()}if(A){let pe=mo(ee);return pe&&M.push(...pe.split(`
|
|
1403
|
+
`)),!0}return ee.includes(`
|
|
1404
|
+
`)&&ee.length>40&&!A?(M.push(...ee.replace(/\r/g,"").split(`
|
|
1405
|
+
`)),ge()):L.call(process.stdin,U,...re)}}let Z=0;function de(){if(Z>0){let L=y._scrollEnd,U="\x1B7";for(let re=0;re<Z;re++)U+=`\x1B[${L-Z+1+re};1H\x1B[2K`;U+="\x1B8",y.rawWrite(U),Z=0}}function X(L){let U=[...ho,...Gr()].filter(be=>be.cmd.startsWith(L));if(!U.length||U.length===1&&U[0].cmd===L)return;let re=y._scrollEnd,ee=Math.min(10,re-2);if(ee<1)return;let te=U.slice(0,ee),$e=Math.max(...te.map(be=>be.cmd.length));Z=te.length,U.length>ee&&Z++;let pe=re-Z+1,we="\x1B7";for(let be=0;be<te.length;be++){let{cmd:He,desc:Ge}=te[be],Ut=He.substring(0,L.length),hs=He.substring(L.length),Kr=" ".repeat(Math.max(0,$e-He.length+2));we+=`\x1B[${pe+be};1H\x1B[2K ${a.cyan}${Ut}${a.reset}${a.dim}${hs}${Kr}${Ge}${a.reset}`}U.length>ee&&(we+=`\x1B[${pe+te.length};1H\x1B[2K ${a.dim}\u2026 +${U.length-ee} more${a.reset}`),we+="\x1B8",y.rawWrite(we)}process.stdin.isTTY&&process.stdin.on("keypress",(L,U)=>{de(),!(U&&(U.name==="tab"||U.name==="return"))&&setImmediate(()=>{p.line&&p.line.startsWith("/")&&X(p.line)})});let E=null,P=`${a.dim}...${a.reset} `;function F(L){return(L.match(/[^\s\d](\d{1,2})\.\s+\S/g)||[]).length<2?L:L.replace(/([^\s\d])(\d{1,2})\.\s+/g,(re,ee,te)=>`${ee}
|
|
1406
|
+
${te}. `).trim()}let{loadSession:K}=Ot(),{setConversationMessages:oe}=ve();if(e()===0){let L=K("_autosave");if(L&&L.messages&&L.messages.length>0&&Date.now()-new Date(L.updatedAt).getTime()<1440*60*1e3){let{confirm:re}=Je();if(await re("Previous session found. Resume?")){let $e=L.messages,pe=$e.length>20?$e.slice(-20):$e;oe(pe);let{getUsage:we,forceCompress:be}=Ve();if(we(pe,[]).percentage>=30){let{messages:Ge}=be(pe,[]);oe(Ge)}}}}p.setPrompt(bt()),p.prompt(),p.on("line",async L=>{if(de(),Object.keys(N).length>0&&(L=ce(L),ue(),p.setPrompt(bt())),x){let te=L.trim();if(te){let{injectMidRunNote:$e}=ve();$e(te),process.stdout.write(`${a.cyan} \u270E Queued \u2014 will be applied in the next step${a.reset}
|
|
1407
|
+
`),p.prompt()}return}if(E!==null){if(E._mode==="triple"){if(L.trim()==='"""'){let te=E.join(`
|
|
1408
|
+
`).trim();if(E=null,te){Hr(te.replace(/\n/g,"\\n")),x=!0,p.prompt(),R=0,k=!1,_&&(clearTimeout(_),_=null),Jt=new AbortController;try{await n(te)}catch(pe){if(!Jt?.signal?.aborted){let we=pe.message?.split(`
|
|
1409
|
+
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${we}${a.reset}`)}}x=!1;let $e=re();$e>0&&process.stdout.write(`${a.gray}[${$e} messages] ${a.reset}`)}p.setPrompt(bt()),p.prompt();return}E.push(L),p.setPrompt(P),p.prompt();return}if(L.endsWith("\\"))E.push(L.slice(0,-1));else{E.push(L);let te=E.join(`
|
|
1410
|
+
`).trim();if(E=null,te){Hr(te.replace(/\n/g,"\\n")),x=!0,p.prompt(),R=0,k=!1,_&&(clearTimeout(_),_=null),Jt=new AbortController;try{await n(te)}catch(we){if(!Jt?.signal?.aborted){let be=we.message?.split(`
|
|
1411
|
+
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${be}${a.reset}`)}}let{getConversationLength:$e}=ve();x=!1;let pe=$e();pe>0&&process.stdout.write(`${a.gray}[${pe} messages] ${a.reset}`)}p.setPrompt(bt()),p.prompt();return}p.setPrompt(P),p.prompt();return}if(L.trim()==='"""'||L.trim().startsWith('"""')){let te=L.trim().substring(3);E=te?[te]:[],E._mode="triple",p.setPrompt(P),p.prompt();return}if(L.endsWith("\\")){E=[L.slice(0,-1)],E._mode="backslash",p.setPrompt(P),p.prompt();return}let U=F(L.trim());if(!U){p.setPrompt(bt()),p.prompt();return}if(Hr(U),U==="/"){Mm(),p.setPrompt(bt()),p.prompt();return}if(U.startsWith("/")){await jm(U,p),p.setPrompt(bt()),p.prompt();return}{let te=Dk?"\x1B[48;5;237m":"\x1B[48;2;220;225;235m",$e=process.stdout.columns||80;U.split(`
|
|
1412
|
+
`).forEach((we,be)=>{let He=be===0?"\x1B[1;36m\u203A\x1B[22;39m":" ",Ge=2+we.length,Ut=" ".repeat(Math.max(0,$e-Ge));console.log(`${te}${He} ${we}${Ut}\x1B[0m`)})}if(process.env.NEX_AUTO_PLAN!=="0"&&!uc()){let{isPlanMode:te,setPlanMode:$e}=jt(),{invalidateSystemPromptCache:pe}=ve(),we=/\b(implement|refactor|migrate|redesign)\b/i,be=/\b(create|build|add|write|introduce|develop|set\s+up)\b/i,He=/^(how|what|why|when|where|which|explain|show|list|tell|describe|can\s+you|could\s+you|do\s+you)\b/i,Ge=/\b(spawn[_\s]?agents?|swarm)\b/i;!He.test(U)&&!Ge.test(U)&&(we.test(U)||be.test(U)&&U.split(/\s+/).length>=5)&&!te()&&($e(!0),pe(),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:te}=ve();if(te()===0)try{let{detectCategory:$e,getModelForCategory:pe}=sc(),we=$e(U);if(we&&we.id!=="coding"){let be=pe(we.id),He=Vt();if(be&&be!==He?.id&&pc(be)){let Ge=Vt();console.log(`${a.dim}\u21B3 ${we.icon} ${we.label} task \u2014 routing to ${Ge?.name||be}${a.reset}`),global._nexFooter&&global._nexFooter.setStatusInfo({model:Ge?.name||be})}}}catch{}}x=!0,p.prompt(),R=0,k=!1,_&&(clearTimeout(_),_=null),Jt=new AbortController;try{await n(U)}catch(te){if(!Jt?.signal?.aborted){let $e=te.message?.split(`
|
|
1413
|
+
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${$e}${a.reset}`)}}x=!1;let{getConversationLength:re}=ve(),ee=re();ee>0&&process.stdout.write(`${a.gray}[${ee} messages] ${a.reset}`),p.setPrompt(bt()),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)})}Fm.exports={startREPL:Jk,getPrompt:bt,loadHistory:qm,appendHistory:Hr,getHistoryPath:hc,HISTORY_MAX:mc,showCommandList:Mm,completer:Im,completeFilePath:Pm,handleSlashCommand:jm,showProviders:dc,showHelp:Lm,renderBar:Dm,hasPasteStart:Yk,hasPasteEnd:zk,stripPasteSequences:mo,getAbortSignal:Nm}});var Bm=G((AS,Wm)=>{Wm.exports=Um()});var xc=require("path");require("dotenv").config({path:xc.join(__dirname,"..",".env")});require("dotenv").config();var me=process.argv.slice(2);(me.includes("--help")||me.includes("-h"))&&(console.log(`Usage: nex-code [options]
|
|
1411
1414
|
|
|
1412
1415
|
Options:
|
|
1413
1416
|
--task <prompt> Run a single task and exit (headless mode)
|
|
@@ -1420,11 +1423,11 @@ Options:
|
|
|
1420
1423
|
--model <spec> Set model (e.g. openai:gpt-4o)
|
|
1421
1424
|
--max-turns <n> Max agentic loop iterations (default: 50)
|
|
1422
1425
|
--orchestrate Use multi-agent orchestrator (with --task)
|
|
1423
|
-
--auto-orchestrate
|
|
1426
|
+
--no-auto-orchestrate Disable auto-orchestration for multi-goal prompts (on by default)
|
|
1424
1427
|
--orchestrator-model <m> Model for orchestrator (default: kimi-k2.5)
|
|
1425
1428
|
--debug Show internal diagnostic messages (compression, loop detection, guards)
|
|
1426
1429
|
--json Output result as JSON (for CI parsing)
|
|
1427
1430
|
--mcp-config <path> Path to MCP server config (default: .nex/mcp.json)
|
|
1428
1431
|
-h, --help Show this help
|
|
1429
1432
|
-v, --version Show version
|
|
1430
|
-
`),process.exit(0));if(
|
|
1433
|
+
`),process.exit(0));if(me.includes("-v")||me.includes("--version")){let t=In();console.log(t.version),process.exit(0)}var Km=me.includes("--yolo")||me.includes("-yolo");if(Km){let{setAutoConfirm:t}=Je();t(!0)}if(!Km)try{let t=require("fs"),e=xc.join(process.cwd(),".nex","config.json");if(t.existsSync(e)&&JSON.parse(t.readFileSync(e,"utf-8")).yolo===!0){let{setAutoConfirm:o}=Je();o(!0)}}catch{}var yc=me.indexOf("--model");if(yc!==-1&&me[yc+1]){let{setActiveModel:t}=Re();t(me[yc+1])}var wc=me.indexOf("--max-turns");if(wc!==-1&&me[wc+1]){let t=parseInt(me[wc+1],10);if(t>0){let{setMaxIterations:e}=ve();e(t)}}else try{let t=require("fs"),e=xc.join(process.cwd(),".nex","config.json");if(t.existsSync(e)){let n=JSON.parse(t.readFileSync(e,"utf-8")),o=parseInt(n.maxIterations,10);if(o>0){let{setMaxIterations:s}=ve();s(o)}}}catch{}var bc=me.indexOf("--mcp-config");bc!==-1&&me[bc+1]&&(process.env.NEX_MCP_CONFIG=me[bc+1]);function _c(){if(process.platform==="darwin")try{let{spawn:t}=require("child_process"),e=t("caffeinate",["-i","-m"],{stdio:"ignore",detached:!1});e.unref();let n=()=>{try{e.kill()}catch{}};process.on("exit",n),process.on("SIGINT",n),process.on("SIGTERM",n)}catch{}}async function Vk(){let{runSetupWizard:t}=Va();await t()}function Hm(t){if(me.includes("--auto")){let{setAutoConfirm:c}=Je();c(!0)}if(!me.includes("--model")){let{setActiveModel:c}=Re(),l=process.env.HEADLESS_MODEL||"devstral-small-2:24b";c(l)}let n=!me.includes("--no-auto-orchestrate")&&process.env.NEX_AUTO_ORCHESTRATE!=="false",o=me.indexOf("--orchestrator-model"),s=o!==-1?me[o+1]:void 0,{processInput:r,getConversationMessages:i}=ve();r(t,null,{autoOrchestrate:n,orchestratorModel:s}).then(()=>{if(me.includes("--json")){let l=i().filter(u=>u.role==="assistant").pop();console.log(JSON.stringify({success:!0,response:l?.content||""}))}process.exit(0)}).catch(c=>{me.includes("--json")?console.log(JSON.stringify({success:!1,error:c.message})):console.error(c.message),process.exit(1)})}if(me.includes("--server")){let{setAutoConfirm:t}=Je();t(!0),Ap().startServerMode();return}var Gm=me.indexOf("--prompt-file");if(Gm!==-1){let t=me[Gm+1];(!t||t.startsWith("--"))&&(console.error("--prompt-file requires a file path"),process.exit(1));let e=require("fs"),n;try{n=e.readFileSync(t,"utf-8").trim()}catch(o){console.error(`--prompt-file: cannot read file: ${o.message}`),process.exit(1)}if(n||(console.error("--prompt-file: file is empty"),process.exit(1)),me.includes("--delete-prompt-file"))try{e.unlinkSync(t)}catch{}_c(),Hm(n)}else{let t=me.indexOf("--task")!==-1?me.indexOf("--task"):me.indexOf("--prompt");if(t!==-1){let e=me[t+1];if((!e||e.startsWith("--"))&&(console.error("--task/--prompt requires a prompt"),process.exit(1)),_c(),me.includes("--orchestrate")){let n=me.indexOf("--orchestrator-model"),o=n!==-1?me[n+1]:void 0,{runOrchestrated:s}=Js();s(e,{orchestratorModel:o}).then(()=>{process.exit(0)}).catch(r=>{console.error(`Orchestrator error: ${r.message}`),process.exit(1)})}else Hm(e)}else Vk().then(()=>{_c();let{startREPL:e}=Bm();e()})}
|