nex-code 0.4.18 → 0.4.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/nex-code.js +178 -178
- package/package.json +1 -1
package/dist/nex-code.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var J=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Qn=J((_S,cg)=>{cg.exports={name:"nex-code",version:"0.4.
|
|
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 xl(){let t=require("os");return require("path").join(t.homedir(),".nex-code",".theme_cache.json")}function ug(t){try{let n=require("fs").readFileSync(xl(),"utf8"),o=JSON.parse(n);if(o&&typeof o[t]=="boolean")return o[t]}catch{}return null}function dg(t,e){try{let n=require("fs"),o=require("path"),s=xl(),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 fg(){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=ug(n);if(o!==null)return o;let s=lg(),r=s!==null?s:!0;return dg(n,r),r}var
|
|
2
|
+
var J=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Qn=J((_S,cg)=>{cg.exports={name:"nex-code",version:"0.4.19",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",improve:"node scripts/improve.js","benchmark:realworld":"node scripts/benchmark-realworld.js",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"},overrides:{"brace-expansion":">=5.0.5",picomatch:">=4.0.4"},jest:{coverageThreshold:{global:{lines:45,functions:30,branches:35},"./cli/sub-agent.js":{lines:70,functions:60,branches:55}}}}});var Rn=J((xS,El)=>{"use strict";var bl="\x1B[0m",_l="\x1B[1m",es="\x1B[2m";function G(t,e,n){return`\x1B[38;2;${t};${e};${n}m`}function lg(){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 xl(){let t=require("os");return require("path").join(t.homedir(),".nex-code",".theme_cache.json")}function ug(t){try{let n=require("fs").readFileSync(xl(),"utf8"),o=JSON.parse(n);if(o&&typeof o[t]=="boolean")return o[t]}catch{}return null}function dg(t,e){try{let n=require("fs"),o=require("path"),s=xl(),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 fg(){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=ug(n);if(o!==null)return o;let s=lg(),r=s!==null?s:!0;return dg(n,r),r}var vl=fg(),kl={reset:bl,bold:_l,dim:es,primary:G(80,190,255),secondary:G(60,170,190),success:G(80,210,120),warning:G(245,175,50),error:G(230,80,80),muted:es,subtle:G(130,130,145),tool_read:G(80,190,255),tool_write:G(245,165,55),tool_exec:G(185,100,235),tool_search:G(70,185,190),tool_git:G(90,210,100),tool_web:G(100,215,250),tool_sysadmin:G(225,150,75),tool_default:G(100,205,115),syn_keyword:G(185,100,235),syn_string:G(90,210,120),syn_number:G(245,175,50),syn_comment:es,syn_key:G(80,190,255),diff_add:G(80,210,120),diff_rem:G(230,80,80),banner_logo:G(80,200,255),banner_name:G(80,200,255),banner_version:es,banner_model:es,banner_yolo:G(245,175,50),footer_sep:es,footer_model:G(80,175,235),footer_branch:G(80,210,100),footer_project:G(130,130,145),footer_divider:G(80,80,95),footer_mode:G(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"},Sl={reset:bl,bold:_l,dim:G(110,110,120),primary:G(0,110,190),secondary:G(0,125,148),success:G(0,148,62),warning:G(168,92,0),error:G(188,32,32),muted:G(110,110,120),subtle:G(155,155,165),tool_read:G(0,110,190),tool_write:G(168,92,0),tool_exec:G(128,42,188),tool_search:G(0,122,148),tool_git:G(0,138,62),tool_web:G(0,112,178),tool_sysadmin:G(168,82,0),tool_default:G(0,138,62),syn_keyword:G(128,42,188),syn_string:G(0,138,62),syn_number:G(168,92,0),syn_comment:G(135,135,148),syn_key:G(0,110,190),diff_add:G(0,148,62),diff_rem:G(188,32,32),banner_logo:G(0,122,205),banner_name:G(0,122,205),banner_version:G(100,100,118),banner_model:G(100,100,118),banner_yolo:G(168,62,0),footer_sep:G(168,168,178),footer_model:G(0,102,175),footer_branch:G(0,138,62),footer_project:G(135,135,148),footer_divider:G(168,168,178),footer_mode:G(148,88,0),white:G(40,40,52),red:G(188,32,32),green:G(0,148,62),yellow:G(168,92,0),blue:G(0,110,190),magenta:G(128,42,188),cyan:G(0,125,148),gray:G(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:G(0,158,182),brightMagenta:G(158,52,208),brightBlue:G(0,112,208)},pg=vl?kl:Sl;El.exports={T:pg,isDark:vl,DARK:kl,LIGHT:Sl}});var ns=J((vS,Rl)=>{var{T:V}=Rn(),Xo=5,ts=(()=>{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})(),Tl=["\u273D","\u2726","\u2727","\u2726"],Ii=class{constructor(e="Thinking..."){this.text=e,this.frame=0,this.interval=null,this.startTime=null}_render(){if(this._stopped)return;let e=ts[this.frame%ts.length],n="";for(let s=0;s<Xo;s++)n+=s===e?`${V.cyan}\u25CF${V.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=` ${V.dim}${r}m ${String(i).padStart(2,"0")}s${V.reset}`}else s>=1&&(o=` ${V.dim}${s}s${V.reset}`)}process.stderr.write(`\x1B[2K\r${n} ${V.dim}${this.text}${V.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}},ji=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=ts[this.frame%ts.length],n=`${V.cyan}\u25CF${V.reset}`,o=`${V.dim}\u25CB${V.reset}`,s=this._formatElapsed(),r=s?` ${V.dim}${s}${V.reset}`:"",i="";for(let c=0;c<this.labels.length;c++){let l,u;switch(this.statuses[c]){case"done":l=`${V.green}\u2713${V.reset}`,u=V.dim;break;case"error":l=`${V.red}\u2717${V.reset}`,u=V.dim;break;case"retry":l=`${V.yellow}\u21BB${V.reset}`,u=V.yellow;break;default:l=c===e?n:" ",u=""}let d=c===this.labels.length-1?r:"";i+=`\x1B[2K ${l} ${u}${this.labels[c]}${V.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?` ${V.dim}${e}${V.reset}`:"",o="";for(let s=0;s<this.labels.length;s++){let r;switch(this.statuses[s]){case"done":r=`${V.green}\u2713${V.reset}`;break;case"error":r=`${V.red}\u2717${V.reset}`;break;case"retry":r=`${V.yellow}\u21BB${V.reset}`;break;default:r=`${V.yellow}\u25CB${V.reset}`}let i=s===this.labels.length-1?n:"";o+=`\x1B[2K ${r} ${V.dim}${this.labels[s]}${V.reset}${i}
|
|
@@ -11,9 +11,9 @@ var J=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Qn=J((_S,cg)=>
|
|
|
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${V.green}\u2714${V.reset} ${this.name} ${V.dim}(${e} \xB7 ${r})${V.reset}
|
|
13
13
|
`;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=Yo[l.status]||Yo.pending,f=zo[l.status]||zo.pending,m=l.description.length>55?l.description.substring(0,52)+"...":l.description;i+=`\x1B[2K ${V.dim}${u}${V.reset} ${f}${d}${V.reset} ${V.dim}${m}${V.reset}
|
|
14
|
-
`}process.stderr.write(i)}},qi=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=ts[this.frame%ts.length],n="";for(let r=0;r<Xo;r++)n+=r===e?`${V.cyan}\u25CF${V.reset}`:" ";let o=this.message;this.count>0&&(o+=` ${V.cyan}${this.count}${V.reset}`,this.total&&(o+=`/${this.total}`),this.detail&&(o+=` ${V.dim}${this.detail}${V.reset}`));let s="";if(this.startTime){let r=Math.floor((Date.now()-this.startTime)/1e3);r>=1&&(s=` ${V.dim}${r}s${V.reset}`)}process.stderr.write(`\x1B[2K\r${n} ${V.dim}${o}${V.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 mg(t){mn=t}function hg(){return mn}function gg(){mn&&(mn.stop(),mn=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}Rl.exports={C:V,Spinner:Ii,MultiProgress:ji,TaskProgress:Di,ToolProgress:qi,setActiveTaskProgress:mg,getActiveTaskProgress:hg,cleanupTerminal:gg}});var Fi=J((
|
|
14
|
+
`}process.stderr.write(i)}},qi=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=ts[this.frame%ts.length],n="";for(let r=0;r<Xo;r++)n+=r===e?`${V.cyan}\u25CF${V.reset}`:" ";let o=this.message;this.count>0&&(o+=` ${V.cyan}${this.count}${V.reset}`,this.total&&(o+=`/${this.total}`),this.detail&&(o+=` ${V.dim}${this.detail}${V.reset}`));let s="";if(this.startTime){let r=Math.floor((Date.now()-this.startTime)/1e3);r>=1&&(s=` ${V.dim}${r}s${V.reset}`)}process.stderr.write(`\x1B[2K\r${n} ${V.dim}${o}${V.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 mg(t){mn=t}function hg(){return mn}function gg(){mn&&(mn.stop(),mn=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}Rl.exports={C:V,Spinner:Ii,MultiProgress:ji,TaskProgress:Di,ToolProgress:qi,setActiveTaskProgress:mg,getActiveTaskProgress:hg,cleanupTerminal:gg}});var Fi=J((kS,Nl)=>{"use strict";var ie={kw:"\x1B[34m",str:"\x1B[32m",cmt:"\x1B[90m",num:"\x1B[33m",type:"\x1B[36m",punct:"\x1B[35m",reset:"\x1B[0m"},Cl={js:new Set(["const","let","var","function","return","if","else","for","while","do","class","new","this","import","export","from","default","async","await","try","catch","finally","throw","typeof","instanceof","in","of","switch","case","break","continue","null","undefined","true","false","extends","super","static","get","set","delete","void","yield","interface","type","enum","namespace","abstract","implements","declare","module","require","readonly","keyof","infer","never","unknown","any","as","satisfies"]),py:new Set(["def","class","return","if","elif","else","for","while","with","as","import","from","pass","break","continue","try","except","finally","raise","in","not","and","or","is","lambda","yield","global","nonlocal","del","assert","True","False","None","async","await","self","cls","print","range","len","type","list","dict","set","tuple","str","int","float","bool","open","super","property","staticmethod","classmethod"]),sh:new Set(["if","then","else","elif","fi","for","while","do","done","case","esac","in","function","return","local","export","source","echo","exit","break","continue","readonly","unset","shift","trap","read"]),go:new Set(["func","return","if","else","for","range","type","struct","interface","import","package","var","const","defer","go","chan","select","case","default","break","continue","fallthrough","nil","true","false","make","new","len","cap","append","copy","delete","panic","recover","map","error","string","int","int64","int32","uint","bool","byte","rune"]),rs:new Set(["fn","let","mut","return","if","else","for","while","loop","match","use","mod","pub","struct","enum","impl","trait","where","const","static","type","move","ref","in","as","unsafe","extern","crate","self","Self","super","true","false","None","Some","Ok","Err","i32","i64","u32","u64","usize","f32","f64","bool","str","String","Vec"]),java:new Set(["class","interface","extends","implements","import","package","return","if","else","for","while","do","switch","case","break","continue","new","this","super","null","true","false","public","private","protected","static","final","abstract","void","int","long","double","float","boolean","char","byte","short","try","catch","finally","throw","throws","synchronized","volatile","transient","instanceof","enum","record"])},$g={js:"js",jsx:"js",ts:"js",tsx:"js",mjs:"js",cjs:"js",py:"py",css:"css",scss:"css",less:"css",sh:"sh",bash:"sh",zsh:"sh",go:"go",rs:"rs",java:"java",json:"json",html:"html",htm:"html",xml:"xml",md:"md"};function Al(t){if(!t)return null;let e=t.split(".").pop().toLowerCase();return $g[e]||null}function yg(t){return t.replace(/"([^"\\]|\\.)*"\s*:/g,e=>ie.type+e+ie.reset).replace(/"([^"\\]|\\.)*"/g,e=>ie.str+e+ie.reset).replace(/\b-?(\d+(\.\d+)?([eE][+-]?\d+)?)\b/g,e=>ie.num+e+ie.reset).replace(/\b(true|false|null)\b/g,e=>ie.kw+e+ie.reset)}function wg(t){return/<!--/.test(t)?t.replace(/<!--[\s\S]*?(?:-->|$)/g,e=>ie.cmt+e+ie.reset):t.replace(/(<\/?)([a-zA-Z][a-zA-Z0-9.-]*)/g,(e,n,o)=>n+ie.type+o+ie.reset).replace(/\s([a-zA-Z][a-zA-Z0-9-]*)=/g,(e,n)=>" "+ie.kw+n+ie.reset+"=").replace(/"([^"]*)"/g,e=>ie.str+e+ie.reset)}function bg(t){return t.replace(/\/\*[\s\S]*?(?:\*\/|$)/g,e=>ie.cmt+e+ie.reset).replace(/#[0-9a-fA-F]{3,8}\b/g,e=>ie.num+e+ie.reset).replace(/\b(-?\d+(?:\.\d+)?)(px|em|rem|vh|vw|vmin|vmax|%|s|ms|deg|fr)\b/g,(e,n,o)=>ie.num+n+ie.reset+o).replace(/([a-z][a-z-]*)(\s*:)/g,(e,n,o)=>ie.type+n+ie.reset+o).replace(/"[^"]*"|'[^']*'/g,e=>ie.str+e+ie.reset)}function Ol(t,e,n){if(e==="json")return yg(t);if(e==="html"||e==="xml")return wg(t);if(e==="css")return bg(t);if(e==="md")return t;let o=Cl[e]||Cl.js,s="",r=0;if(n.inBlockComment){let i=t.indexOf("*/");if(i===-1)return ie.cmt+t+ie.reset;if(s+=ie.cmt+t.slice(0,i+2)+ie.reset,n.inBlockComment=!1,r=i+2,r>=t.length)return s}if(n.inString==="`"){let i=t.indexOf("`");if(i===-1)return ie.str+t+ie.reset;if(s+=ie.str+t.slice(0,i+1)+ie.reset,n.inString=null,r=i+1,r>=t.length)return s}for(;r<t.length;){let i=t[r];if(!n.inString&&i==="/"&&t[r+1]==="*"){let c=t.indexOf("*/",r+2);if(c===-1)return s+=ie.cmt+t.slice(r)+ie.reset,n.inBlockComment=!0,s;s+=ie.cmt+t.slice(r,c+2)+ie.reset,r=c+2;continue}if(!n.inString&&((e==="js"||e==="go"||e==="rs"||e==="java")&&i==="/"&&t[r+1]==="/"||(e==="py"||e==="sh")&&i==="#"))return s+=ie.cmt+t.slice(r)+ie.reset,s;if(!n.inString&&(i==='"'||i==="'"||i==="`")){n.inString=i,s+=ie.str+i,r++;continue}if(n.inString){if(i==="\\"&&r+1<t.length){s+=i+t[r+1],r+=2;continue}if(i===n.inString){s+=i+ie.reset,n.inString=null,r++;continue}s+=i,r++;continue}if(/[0-9]/.test(i)&&(r===0||!/[a-zA-Z0-9_$]/.test(t[r-1]))){let c="";for(;r<t.length&&/[0-9a-fA-F_.xXoObBeE+-]/.test(t[r])&&!(c.length>0&&/[eE]/.test(t[r-1])&&/[^+-]/.test(i));)c+=t[r++];s+=ie.num+c+ie.reset;continue}if(i==="@"&&(e==="js"||e==="java"||e==="py")){let c="@";for(r++;r<t.length&&/[a-zA-Z0-9_$.]/.test(t[r]);)c+=t[r++];s+=ie.punct+c+ie.reset;continue}if(/[a-zA-Z_$]/.test(i)){let c="";for(;r<t.length&&/[a-zA-Z0-9_$]/.test(t[r]);)c+=t[r++];o.has(c)?s+=ie.kw+c+ie.reset:/^[A-Z][A-Za-z0-9]*$/.test(c)&&e!=="sh"?s+=ie.type+c+ie.reset:s+=c;continue}s+=i,r++}return n.inString&&n.inString!=="`"&&(s+=ie.reset,n.inString=null),s}function _g(t,e){let n=Al(e);if(!n)return t.split(`
|
|
15
15
|
`);let o=t.split(`
|
|
16
|
-
`),s={inString:null,inBlockComment:!1};return o.map(r=>Ol(r,n,s))}function xg(t,e){return e?Ol(t,e,{inString:null,inBlockComment:!1}):t}Nl.exports={detectLang:Al,highlightLine:xg,highlightLines:_g}});var Pl=J((SS,Ml)=>{var{T:N}=Rn(),et=N,
|
|
16
|
+
`),s={inString:null,inBlockComment:!1};return o.map(r=>Ol(r,n,s))}function xg(t,e){return e?Ol(t,e,{inString:null,inBlockComment:!1}):t}Nl.exports={detectLang:Al,highlightLine:xg,highlightLines:_g}});var Pl=J((SS,Ml)=>{var{T:N}=Rn(),et=N,vg={read_file:N.tool_read,list_directory:N.tool_read,write_file:N.tool_write,edit_file:N.tool_write,patch_file:N.tool_write,bash:N.tool_exec,grep:N.tool_search,search_files:N.tool_search,glob:N.tool_search,git_commit:N.tool_git,git_push:N.tool_git,git_pull:N.tool_git,git_status:N.tool_git,git_diff:N.tool_git,git_log:N.tool_git,git_branch:N.tool_git,git_stash:N.tool_git,web_fetch:N.tool_web,web_search:N.tool_web,sysadmin:N.tool_sysadmin,ssh_exec:N.tool_sysadmin,ssh_upload:N.tool_sysadmin,ssh_download:N.tool_sysadmin,deploy:N.tool_sysadmin},Ui={read_file:"Read",write_file:"Write",edit_file:"Edit",patch_file:"Edit",list_directory:"List",bash:"Bash",grep:"Grep",search_files:"Search",glob:"Glob",web_fetch:"WebFetch",web_search:"WebSearch",git_status:"Bash",git_diff:"Bash",git_log:"Bash",git_commit:"Bash",git_push:"Bash",git_pull:"Bash",git_branch:"Bash",git_stash:"Bash",task_list:"TaskList",spawn_agents:"Agent",ask_user:"AskUser",switch_model:"SwitchModel",gh_run_list:"Bash",gh_run_view:"Bash",gh_workflow_trigger:"Bash",browser_open:"Browser",browser_screenshot:"Browser",browser_click:"Browser",browser_fill:"Browser",ssh_exec:"Bash",ssh_upload:"Upload",ssh_download:"Download",service_manage:"Bash",service_logs:"Bash",container_list:"Bash",container_logs:"Bash",container_exec:"Bash",brain_write:"Write",deploy:"Bash",frontend_recon:"Search"};function Jo(t,e=!1,n=null){if(e)return`${N.error}\u23FA${N.reset}`;let o=vg[t]||N.tool_default;return n==="blink"?`${o}\x1B[5m\u23FA\x1B[25m${N.reset}`:`${o}${n!==null?n:"\u23FA"}${N.reset}`}function kg(t,e,n=!1,o=null){let s=(t||[]).filter(l=>l&&l.canExecute!==!1);if(s.length===0)return`${Jo("",n,o)} Step ${e}`;if(s.length===1){let l=s[0],u=l.args||{},d=Ui[l.fnName]||l.fnName.replace(/_/g," "),f="";u.path?f=u.path:u.command?f=String(u.command).substring(0,80):u.query?f=String(u.query).substring(0,60):u.pattern?f=String(u.pattern).substring(0,60):u.url&&(f=String(u.url).substring(0,60));let m=f?`(${et.dim}${f}${et.reset})`:"";return`${Jo(l.fnName,n,o)} ${et.bold}${d}${et.reset}${m}`}let r=s[0].fnName,i=[...new Set(s.map(l=>Ui[l.fnName]||l.fnName.replace(/_/g," ")))],c=i.length<=3?i.join(", "):`${s.length} tools`;return`${Jo(r,n,o)} ${et.bold}${c}${et.reset}`}function Sg(t,e){let n;switch(t){case"write_file":case"edit_file":case"patch_file":case"read_file":case"list_directory":n=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=Ui[t]||t.replace(/_/g," "),s=n?`(${et.dim}${n}${et.reset})`:"";return`${Jo(t)} ${et.bold}${o}${et.reset}${s}`}function Eg(t,e=8){let n=t.split(`
|
|
17
17
|
`),o=n.slice(0,e),s=n.length-e,r=`${N.muted} \u23BF ${N.reset}`,i=" ",c=o.map((l,u)=>`${u===0?r:i}${N.success}${l}${N.reset}`).join(`
|
|
18
18
|
`);return s>0&&(c+=`
|
|
19
19
|
${N.subtle} \u2026 +${s} lines${N.reset}`),c}function Tg(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 Rg(t,e,n,o){let s=String(n||"");if(o){let c=s.split(`
|
|
@@ -33,7 +33,7 @@ ${g}
|
|
|
33
33
|
`).length,0),u=c.reduce((d,f)=>d+(f.new_text||"").split(`
|
|
34
34
|
`).length,0);r=`${N.reset}${c.length} patch${c.length!==1?"es":""} ${N.diff_rem}\u2212${l}${N.reset} ${N.diff_add}+${u}${N.reset}`;break}case"bash":{let l=s.match(/^EXIT (\d+)/),u=s.split(`
|
|
35
35
|
`).filter(m=>m&&!m.startsWith("EXIT ")&&!m.startsWith("HINT:")&&m.trim()),d=l?l[1]==="0"?`${N.success}\u2713${N.reset}`:`${N.error}\u2717 Exit ${l[1]}${N.reset}`:`${N.success}\u2713${N.reset}`,f=s.match(/\nHINT: (.+)/);if(f)r=`${d} ${N.muted}\u2014 ${f[1].substring(0,100)}${N.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} ${N.muted}${y.substring(0,120)}${N.reset}`:` ${N.muted}${y.substring(0,120)}${N.reset}`);if(p>0){let y=m?` ${N.subtle}${p} lines above\u2026${N.reset}`:` ${N.subtle}\u2026 +${p} lines${N.reset}`;m?g.unshift(y):g.push(y)}r=g.join(`
|
|
36
|
-
`)}break}case"grep":case"search_files":{if(s.includes("(no matches)")||s==="no matches")r=`No matches${e.pattern?` ${N.muted}"${String(e.pattern).substring(0,40)}"${N.reset}`:""}`;else{let p=function(w){let x=w.indexOf(":");if(x===-1)return`${N.muted}${w.substring(0,90)}${N.reset}`;let A=w.substring(0,x),E=w.substring(x+1),
|
|
36
|
+
`)}break}case"grep":case"search_files":{if(s.includes("(no matches)")||s==="no matches")r=`No matches${e.pattern?` ${N.muted}"${String(e.pattern).substring(0,40)}"${N.reset}`:""}`;else{let p=function(w){let x=w.indexOf(":");if(x===-1)return`${N.muted}${w.substring(0,90)}${N.reset}`;let A=w.substring(0,x),E=w.substring(x+1),k=E.match(/^(\d+)[:-](.*)/s),T=k?`:${k[1]}`:"",O=(k?k[2]:E).trim(),P=`${N.subtle}${c.basename(A)}${T}${N.reset}`,W=`${N.muted}${O.substring(0,80)}${O.length>80?"\u2026":""}${N.reset}`;return`${P} ${W}`};var i=p;let c=require("path"),l=s.split(`
|
|
37
37
|
`).filter(Boolean),u=l.length,f=new Set(l.map(w=>w.split(":")[0]).filter(Boolean)).size,m=e.pattern?` ${N.muted}"${String(e.pattern).substring(0,40)}"${N.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}
|
|
38
38
|
${p(w)}`:` ${p(w)}`),y=l.length-3;y>0&&g.push(` ${N.subtle}\u2026 +${y} lines${N.reset}`),r=g.join(`
|
|
39
39
|
`)}break}case"glob":{let c=e.pattern?` ${N.muted}${String(e.pattern).substring(0,50)}${N.reset}`:"";if(s==="(no matches)")r=`No files found${c}`;else{let l=require("path"),u=s.split(`
|
|
@@ -48,7 +48,7 @@ ${g}
|
|
|
48
48
|
`).filter(f=>f.trim()&&!f.startsWith("EXIT ")),d=l?`${N.error}\u2717${N.reset}`:`${N.success}\u2713${N.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} ${N.muted}${g.substring(0,120)}${N.reset}`:` ${N.muted}${g.substring(0,120)}${N.reset}`);if(h>0){let g=l?` ${N.subtle}${h} lines above\u2026${N.reset}`:` ${N.subtle}\u2026 +${h} lines${N.reset}`;l?p.unshift(g):p.push(g)}r=p.join(`
|
|
49
49
|
`)}break}default:{let c=s.split(`
|
|
50
50
|
`).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?` ${N.subtle}\u2026 +${c.length-1} lines${N.reset}`:"";r=`${N.muted}${l}${N.reset}${u}`}else r="Done"}}return` ${N.muted}\u23BF ${r}${N.reset}`}function Cg(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=`
|
|
51
|
-
${N.success}\u25C6${et.reset} ${et.bold}${t}${et.reset}`;return u+=`${et.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+=et.reset,u}Ml.exports={C:et,formatToolCall:Sg,formatResult:Eg,getToolSpinnerText:Tg,formatToolSummary:Rg,formatSectionHeader:
|
|
51
|
+
${N.success}\u25C6${et.reset} ${et.bold}${t}${et.reset}`;return u+=`${et.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+=et.reset,u}Ml.exports={C:et,formatToolCall:Sg,formatResult:Eg,getToolSpinnerText:Tg,formatToolSummary:Rg,formatSectionHeader:kg,formatMilestone:Cg}});var qe=J((ES,Il)=>{var{T:Cn}=Rn(),Wi=Cn,Ll=["01100110","01111110","01111110","01011010","01111110","00111100"];function Ag(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 Og(t,e,n={}){let o=Wi.bold,s=Wi.reset,r=Ag(Ll,Cn.banner_logo),i=n.yolo?` ${o}${Cn.banner_yolo}\u26A1 YOLO${s}`:"",c=Qn().version,l=[` ${Cn.banner_name}${o}nex-code${s} ${Cn.banner_version}v${c}${s}`,` ${Cn.banner_model}${t}${s} ${Cn.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=Ll[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(`
|
|
52
52
|
`+h.join(`
|
|
53
53
|
`)+`
|
|
54
54
|
`)}var{Spinner:Ng,MultiProgress:Mg,TaskProgress:Pg,ToolProgress:Lg,setActiveTaskProgress:Ig,getActiveTaskProgress:jg,cleanupTerminal:Dg}=ns(),{formatToolCall:qg,formatResult:Fg,getToolSpinnerText:Ug,formatToolSummary:Wg,formatSectionHeader:Bg,formatMilestone:Hg}=Pl();Il.exports={C:Wi,banner:Og,Spinner:Ng,MultiProgress:Mg,TaskProgress:Pg,ToolProgress:Lg,setActiveTaskProgress:Ig,getActiveTaskProgress:jg,cleanupTerminal:Dg,formatToolCall:qg,formatResult:Fg,getToolSpinnerText:Ug,formatToolSummary:Wg,formatSectionHeader:Bg,formatMilestone:Hg}});var tt=J((TS,Wl)=>{var Kg=require("readline"),{C:Ht}=qe(),Ki=[/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/],jl=[...Ki,/\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 Gg(t){for(let e of jl)if(e.test(t))return e;return null}var Dl=[/\.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)/],Yg=/\b(?:rm|rmdir|unlink|truncate|shred|mv|cp)\b/,Bi=[/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 ql(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)):Bi.some(l=>l.test(r))}return/^\w+=\$?\(/.test(i)||/^\w+=["']/.test(i)||/^\w+=\S/.test(i)?!0:Bi.some(c=>c.test(i))};return o.every(s)}var Gi=[/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)/],Fl=[/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/],Ul=[...Gi,...Fl],Yi=!1,An=null,Hi=null;function zg(t){Yi=t}function Xg(t){Hi=t}function Jg(){return Yi}function Vg(t){An=t}function Zg(t){for(let e of Ki)if(e.test(t))return e;return null}function Qg(t){if(/ssh\s/.test(t)&&ql(t))return!1;for(let e of Ul)if(e.test(t))return!0;return!1}function e$(t){for(let e of Gi)if(e.test(t))return!0;return!1}function t$(t){if(process.env.NEX_UNPROTECT==="1"||!Yg.test(t))return null;for(let e of Dl)if(e.test(t))return e;return null}function n$(t,e={}){if(Yi)return Promise.resolve(!0);if(Hi)return Hi(t,e);if(!process.stdout.isTTY||!process.stdin.isTTY)return s$(t,e);let n=e.toolName?["Yes","No","Always allow"]:["Yes","No"];return new Promise(o=>{let s=0;An&&An.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${Ht.yellow}${t}${Ht.reset}`;for(let h=0;h<n.length;h++){let p=h===s,g=p?`${Ht.yellow}\u276F${Ht.reset}`:" ",y=p?`${Ht.yellow}${n[h]}${Ht.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(),An&&An.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===`
|
|
@@ -63,7 +63,7 @@ Be factual and brief. Use bullet points. Max 300 words.`;async function w$(t){if
|
|
|
63
63
|
${o}`,_compacted:!0,_originalCount:t.length},tokensRemoved:s-r}}catch{return null}}function Ql(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}
|
|
64
64
|
tools: ${s}`}return`[${n}] ${o}`}).join(`
|
|
65
65
|
|
|
66
|
-
`)}eu.exports={compactMessages:w$,formatMessagesForSummary:Ql,COMPACTION_ENABLED:Jl,COMPACTION_MIN_MESSAGES:Vl,COMPACTION_SUMMARY_BUDGET:Zl}});var nt=J((NS,du)=>{var b$=require("path");function su(){return Le().getActiveModel()}var _$={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},x$={devstral:3.8,mistral:3.8,ministral:3.8,codestral:3.8,qwen:3.5,deepseek:3.6,kimi:3.7,gemma:4,llama:3.8,cogito:3.6,phi:4},On=new Map,nu=1e3,Zi=new WeakMap,Nn=null;function
|
|
66
|
+
`)}eu.exports={compactMessages:w$,formatMessagesForSummary:Ql,COMPACTION_ENABLED:Jl,COMPACTION_MIN_MESSAGES:Vl,COMPACTION_SUMMARY_BUDGET:Zl}});var nt=J((NS,du)=>{var b$=require("path");function su(){return Le().getActiveModel()}var _$={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},x$={devstral:3.8,mistral:3.8,ministral:3.8,codestral:3.8,qwen:3.5,deepseek:3.6,kimi:3.7,gemma:4,llama:3.8,cogito:3.6,phi:4},On=new Map,nu=1e3,Zi=new WeakMap,Nn=null;function v$(){if(Nn!==null)return Nn;try{let t=su(),e=t?.provider||"ollama",n=(t?.id||"").toLowerCase();for(let[o,s]of Object.entries(x$))if(n.startsWith(o))return Nn=s,Nn;return Nn=_$[e]||4,Nn}catch{return 4}}function k$(){Nn=null}function Mn(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=On.get(e);if(n!==void 0)return On.delete(e),On.set(e,n),n;let o=Math.ceil(t.length/v$());if(On.size>=nu){let s=nu>>1,r=On.keys();for(let i=0;i<s;i++)On.delete(r.next().value)}return On.set(e,o),o}function S$(t){if(Zi.has(t))return Zi.get(t);let e=JSON.stringify(t);return Zi.set(t,e),e}function is(t){let n=4;if(t.content&&(n+=Mn(t.content)),t.tool_calls)for(let o of t.tool_calls){n+=4,n+=Mn(o.function?.name||"");let s=o.function?.arguments;typeof s=="string"?n+=Mn(s):s&&(n+=Mn(JSON.stringify(s)))}return n}function Rt(t){let e=0;for(let n of t)e+=is(n);return e}function E$(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+=is(e[r]);return s}function tr(t){return!t||t.length===0?0:Mn(JSON.stringify(t))}function nr(){return su()?.contextWindow||32768}function T$(t,e){let n=Rt(t),o=tr(e),s=n+o,r=nr(),i=r>0?s/r*100:0,c=0,l=0,u=0;for(let d of t){let f=is(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 Us=parseFloat(process.env.NEX_COMPRESSION_THRESHOLD)||.75,ou=parseFloat(process.env.NEX_SAFETY_MARGIN)||.1,ru=parseInt(process.env.NEX_KEEP_RECENT,10)||10,iu={essential:.6,standard:.7,full:Us};function au(){if(process.env.NEX_COMPRESSION_THRESHOLD)return Us;try{let{getActiveTier:t}=Fs(),e=t();return iu[e]??Us}catch{return Us}}var R$=200,C$=1e3;function cu(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(`
|
|
67
67
|
`);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+`
|
|
68
68
|
...(${t.length} chars total)...
|
|
69
69
|
`+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(`
|
|
@@ -71,36 +71,36 @@ ${o}`,_compacted:!0,_originalCount:t.length},tokensRemoved:s-r}}catch{return nul
|
|
|
71
71
|
...(${h} lines omitted, ${s.length} total)...
|
|
72
72
|
`+d.join(`
|
|
73
73
|
`)}function rs(t,e="light"){let n=e==="aggressive"?100:e==="medium"?200:C$,o=e==="aggressive"?50:e==="medium"?100:R$;if(t.role==="tool"){let s=typeof t.content=="string"?t.content:JSON.stringify(t.content);return s.length>o?{...t,content:cu(s,o)}:t}if(t.role==="assistant"){let s={...t};return s.content&&s.content.length>n&&(s.content=s.content.substring(0,n)+`
|
|
74
|
-
...(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 lu(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(b$.basename(l)))&&c++;s+=Math.min(30,c*10)}return Math.min(100,s)}function uu(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 os={msgCount:-1,lastMsgRef:null,result:null};function A$(){os={msgCount:-1,lastMsgRef:null,result:null}}async function O$(t,e,n={}){let o=t.length>0?t[t.length-1]:null;if(!n.force&&os.result&&t.length===os.msgCount&&o===os.lastMsgRef)return os.result;let s=n.threshold??au(),r=n.safetyMargin??ou,i=n.keepRecent??ru,c=nr(),l=tr(e),u=Math.floor(c*(s-r)),d=u-l,f=Rt(t),m=f+l;if(m<=u){let
|
|
74
|
+
...(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 lu(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(b$.basename(l)))&&c++;s+=Math.min(30,c*10)}return Math.min(100,s)}function uu(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 os={msgCount:-1,lastMsgRef:null,result:null};function A$(){os={msgCount:-1,lastMsgRef:null,result:null}}async function O$(t,e,n={}){let o=t.length>0?t[t.length-1]:null;if(!n.force&&os.result&&t.length===os.msgCount&&o===os.lastMsgRef)return os.result;let s=n.threshold??au(),r=n.safetyMargin??ou,i=n.keepRecent??ru,c=nr(),l=tr(e),u=Math.floor(c*(s-r)),d=u-l,f=Rt(t),m=f+l;if(m<=u){let v={messages:t,compressed:!1,compacted:!1,tokensRemoved:0};return os={msgCount:t.length,lastMsgRef:o,result:v},v}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),A=w.filter(v=>!v._compacted);if(A.length>=6)try{let{compactMessages:v}=tu(),X=await v(A);if(X){let ye=[...w.filter(fe=>fe._compacted),X.message],we=hn(p,ye,x),ue=Rt(we);if(ue+l<=u)return{messages:we,compressed:!0,compacted:!0,tokensRemoved:h-ue};w=ye}}catch(v){process.env.NEX_DEBUG&&console.error("[context-engine] LLM compacting failed:",v.message)}let E=(m-u)/u,k=w.map(v=>rs(v,"light")),T=hn(p,k,x),O=Rt(T);if(O+l<=u)return{messages:T,compressed:!0,compacted:!1,tokensRemoved:h-O};if(k=w.map(v=>rs(v,"medium")),T=hn(p,k,x),O=Rt(T),O+l<=u)return{messages:T,compressed:!0,compacted:!1,tokensRemoved:h-O};if(k=w.map(v=>rs(v,"aggressive")),T=hn(p,k,x),O=Rt(T),O+l<=u)return{messages:T,compressed:!0,compacted:!1,tokensRemoved:h-O};let P=uu([...k,...x]),W=k.map((v,X)=>({msg:v,score:lu(v,X,k.length,P),tokens:is(v)}));for(;W.length>0&&O>d;){let v=0;for(let X=1;X<W.length;X++)W[X].score<W[v].score&&(v=X);O-=W[v].tokens,W.splice(v,1)}return k=W.map(v=>v.msg),T=hn(p,k,x),O=Rt(T),{messages:T,compressed:!0,compacted:!1,tokensRemoved:h-O}}function hn(t,e,n){let o=[];return t&&o.push(t),o.push(...e,...n),o}function N$(t,e){if(!t)return"";if(Mn(t)<=e)return t;let o=e*4,s=t.split(`
|
|
75
75
|
`),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?`
|
|
76
76
|
`:"")+h,l++}let u="",d=0;for(let h=s.length-1;h>=l;h--){let p=s[h]+(u?`
|
|
77
77
|
`:"")+u;if(p.length>i)break;u=p,d++}let m=`
|
|
78
78
|
|
|
79
79
|
... (${s.length-l-d} lines omitted, ${s.length} total) ...
|
|
80
80
|
|
|
81
|
-
`;return c+m+u}var M$=6;function P$(t,e,n=!1){let o=nr(),s=tr(e),r=Math.floor(o*(n?.35:.5))-s,i=Rt(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:M$,f=Math.max(u,t.length-d),m=t.slice(u,f),h=t.slice(f),p=m.map(
|
|
82
|
-
`);g=w.pop()||"";for(let x of w){let A=x.trim();if(!A||!A.startsWith("data: "))continue;let E=A.slice(6);if(E==="[DONE]"){f({content:h,tool_calls:this._buildToolCalls(p)});return}let
|
|
81
|
+
`;return c+m+u}var M$=6;function P$(t,e,n=!1){let o=nr(),s=tr(e),r=Math.floor(o*(n?.35:.5))-s,i=Rt(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:M$,f=Math.max(u,t.length-d),m=t.slice(u,f),h=t.slice(f),p=m.map(k=>rs(k,"aggressive"));n&&(h=h.map(k=>rs(k,"aggressive")));let g=hn(l,p,h),y=Rt(g);for(;p.length>0&&y>r;){let k=p.shift();y-=is(k)}n&&y>r&&(h=h.filter(T=>T.role==="user").slice(-1),g=hn(l,[],h),y=Rt(g)),g=hn(l,p,h);let w=t.filter(k=>k.role==="user"),x=k=>{let T=typeof k.content=="string"?k.content:"";return T.startsWith("[SYSTEM WARNING]")||T.startsWith("[SYSTEM:")||T.startsWith("BLOCKED:")},A=w.find(k=>!x(k)),E=[...w].reverse().find(k=>!x(k));if(A&&!g.find(k=>k===A)){let k=g.findIndex(O=>O.role==="system"),T=k>=0?k+1:0;g.splice(T,0,A)}return E&&E!==A&&!g.find(k=>k===E)&&g.push(E),{messages:g,tokensRemoved:i-Rt(g)}}du.exports={estimateTokens:Mn,estimateMessageTokens:is,estimateMessagesTokens:Rt,estimateDeltaTokens:E$,estimateToolsTokens:tr,serializeMessage:S$,getContextWindow:nr,getUsage:T$,compressMessage:rs,compressToolResult:cu,scoreMessageRelevance:lu,extractActiveFiles:uu,fitToContext:O$,forceCompress:P$,truncateFileContent:N$,invalidateTokenRatioCache:k$,invalidateFitToContextCache:A$,getEffectiveCompressionThreshold:au,COMPRESSION_THRESHOLD:Us,TIER_COMPRESSION_THRESHOLDS:iu,SAFETY_MARGIN:ou,KEEP_RECENT:ru}});var hu=J((PS,mu)=>{var fu=require("axios"),{BaseProvider:L$,readStreamErrorBody:I$}=ss(),{serializeMessage:MS}=nt(),pu={"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}},Qi=class extends L${constructor(e={}){super({name:"openai",baseUrl:e.baseUrl||"https://api.openai.com/v1",models:e.models||pu,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 fu.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 fu.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 I$(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(`
|
|
82
|
+
`);g=w.pop()||"";for(let x of w){let A=x.trim();if(!A||!A.startsWith("data: "))continue;let E=A.slice(6);if(E==="[DONE]"){f({content:h,tool_calls:this._buildToolCalls(p)});return}let k;try{k=JSON.parse(E)}catch{continue}let T=k.choices?.[0]?.delta;if(T&&(T.content&&(c(T.content),h+=T.content),T.tool_calls))for(let O of T.tool_calls){let P=O.index??0;p[P]||(p[P]={id:O.id||"",name:"",arguments:""}),O.id&&(p[P].id=O.id),O.function?.name&&(p[P].name+=O.function.name),O.function?.arguments&&(p[P].arguments+=O.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}}))}};mu.exports={OpenAIProvider:Qi,OPENAI_MODELS:pu}});var wu=J((IS,yu)=>{var gu=require("axios"),{BaseProvider:j$,readStreamErrorBody:D$}=ss(),{serializeMessage:LS}=nt(),$u={"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}},q$="2023-06-01",ea=class extends j${constructor(e={}){super({name:"anthropic",baseUrl:e.baseUrl||"https://api.anthropic.com/v1",models:e.models||$u,defaultModel:e.defaultModel||"claude-sonnet",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this.apiVersion=e.apiVersion||q$}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?`
|
|
83
83
|
|
|
84
|
-
`:"")+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 gu.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 gu.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 D$(p,w=>w?.error?.message||w?.error);throw new Error(`API Error${g}: ${y}`)}return new Promise((p,g)=>{let y="",w=[],x=-1,A="";o.signal&&o.signal.addEventListener("abort",()=>{h.data.destroy(),g(new DOMException("The operation was aborted","AbortError"))},{once:!0}),h.data.on("data",E=>{A+=E.toString();let
|
|
85
|
-
`);A=
|
|
86
|
-
`);g=w.pop()||"";for(let x of w){let A=x.trim();if(!A||!A.startsWith("data: "))continue;let E=A.slice(6);if(E==="[DONE]"){f({content:h,tool_calls:this._buildToolCalls(p)});return}let
|
|
84
|
+
`:"")+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 gu.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 gu.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 D$(p,w=>w?.error?.message||w?.error);throw new Error(`API Error${g}: ${y}`)}return new Promise((p,g)=>{let y="",w=[],x=-1,A="";o.signal&&o.signal.addEventListener("abort",()=>{h.data.destroy(),g(new DOMException("The operation was aborted","AbortError"))},{once:!0}),h.data.on("data",E=>{A+=E.toString();let k=A.split(`
|
|
85
|
+
`);A=k.pop()||"";for(let T of k){let O=T.trim();if(O.startsWith("data: ")){let P=O.slice(6),W;try{W=JSON.parse(P)}catch{continue}switch(W.type){case"content_block_start":{let v=W.content_block;v?.type==="tool_use"&&(x=w.length,w.push({id:v.id,name:v.name,inputJson:""}));break}case"content_block_delta":{let v=W.delta;v?.type==="text_delta"&&v.text&&(l(v.text),y+=v.text),v?.type==="input_json_delta"&&v.partial_json!==void 0&&x>=0&&(w[x].inputJson+=v.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",E=>{o.signal?.aborted||g(new Error(`Stream error: ${E.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}}})}};yu.exports={AnthropicProvider:ea,ANTHROPIC_MODELS:$u}});var vu=J((DS,xu)=>{var bu=require("axios"),{BaseProvider:F$,readStreamErrorBody:U$}=ss(),{serializeMessage:jS}=nt(),_u={"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}},ta=class extends F${constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||_u,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 bu.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 bu.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 U$(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(`
|
|
86
|
+
`);g=w.pop()||"";for(let x of w){let A=x.trim();if(!A||!A.startsWith("data: "))continue;let E=A.slice(6);if(E==="[DONE]"){f({content:h,tool_calls:this._buildToolCalls(p)});return}let k;try{k=JSON.parse(E)}catch{continue}let T=k.choices?.[0]?.delta;if(T&&(T.content&&(c(T.content),h+=T.content),T.tool_calls))for(let O of T.tool_calls){let P=O.index??0;p[P]||(p[P]={id:O.id||"",name:"",arguments:""}),O.id&&(p[P].id=O.id),O.function?.name&&(p[P].name+=O.function.name),O.function?.arguments&&(p[P].arguments+=O.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}}))}};xu.exports={GeminiProvider:ta,GEMINI_MODELS:_u}});var Eu=J((qS,Su)=>{var sr=require("axios"),{BaseProvider:W$,readStreamErrorBody:B$}=ss(),ku="http://localhost:11434",na=class extends W${constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||ku,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 sr.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 sr.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(`
|
|
87
87
|
`)};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 sr.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 sr.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 B$(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(`
|
|
88
|
-
`);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||{}}}))}};Su.exports={LocalProvider:na,DEFAULT_LOCAL_URL:
|
|
88
|
+
`);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||{}}}))}};Su.exports={LocalProvider:na,DEFAULT_LOCAL_URL:ku}});var gn=J((FS,Ru)=>{"use strict";var wt=require("fs"),Tu=require("path");function H$(t){if(!t||isNaN(t))return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function K$(t){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}catch{let e=Date.now()+t;for(;Date.now()<e;);}}function G$(t,e){let n=Tu.dirname(t),o=Tu.join(n,`.nex-tmp.${process.pid}.${Date.now()}`);try{wt.existsSync(n)||wt.mkdirSync(n,{recursive:!0}),wt.writeFileSync(o,e,"utf-8"),wt.renameSync(o,t)}catch(s){try{wt.unlinkSync(o)}catch{}throw s}}function Y$(t,e,{timeout:n=5e3,retryMs:o=50}={}){let s=t+".lock",r=Date.now()+n;for(;;){let i=-1;try{i=wt.openSync(s,"wx"),wt.writeSync(i,Buffer.from(String(process.pid))),wt.closeSync(i),i=-1;try{return e()}finally{try{wt.unlinkSync(s)}catch{}}}catch(c){if(i!==-1)try{wt.closeSync(i)}catch{}if(c.code!=="EEXIST")throw c;try{let l=wt.readFileSync(s,"utf-8").trim(),u=parseInt(l,10);if(!H$(u)){try{wt.unlinkSync(s)}catch{}continue}}catch(l){if(l.code&&l.code!=="ENOENT")throw l;continue}if(Date.now()>=r){try{wt.unlinkSync(s)}catch{}return e()}K$(o)}}}Ru.exports={atomicWrite:G$,withFileLockSync:Y$}});var cs=J((US,Lu)=>{var as=require("fs"),sa=require("path"),{atomicWrite:z$,withFileLockSync:X$}=gn(),Cu={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:{}},or=[],$n={};function J$(t,e,n,o){if(or.push({provider:t,model:e,input:n,output:o}),$n[t]!==void 0){let s=Mu(t);s.allowed||process.stderr.write(`\x1B[33m\u26A0 Budget limit reached for ${t}: $${s.spent.toFixed(2)} / $${s.limit.toFixed(2)}\x1B[0m
|
|
89
89
|
`)}}function oa(t,e){let n=Cu[t];return n?n[e]||{input:0,output:0}:{input:0,output:0}}function Au(t){let e=oa(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function Ou(){let t={};for(let r of or){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:Au(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 V$(){let{totalCost:t,totalInput:e,totalOutput:n,breakdown:o}=Ou();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(`
|
|
90
90
|
`)}function Z$(t){return!t||typeof t!="string"?0:Math.ceil(t.length/4)}function Q$(t,e,n,o){let s=oa(t,e),r=(n*s.input+o*s.output)/1e6;return r<=0?"":`[~$${r.toFixed(4)}]`}function ey(){or=[]}function ty(t,e){$n[t]=e}function ny(t){delete $n[t]}function sy(){return{...$n}}function Nu(t){let e=0;for(let n of or)n.provider===t&&(e+=Au(n));return e}function Mu(t){let e=Nu(t),n=$n[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 Pu(){let t=sa.join(process.cwd(),".nex","config.json");if(as.existsSync(t))try{let e=JSON.parse(as.readFileSync(t,"utf-8"));e.costLimits&&typeof e.costLimits=="object"&&($n={...e.costLimits})}catch{}}function oy(){let t=sa.join(process.cwd(),".nex"),e=sa.join(t,"config.json");as.existsSync(t)||as.mkdirSync(t,{recursive:!0}),X$(e,()=>{let n={};if(as.existsSync(e))try{n=JSON.parse(as.readFileSync(e,"utf-8"))}catch{n={}}n.costLimits=$n,z$(e,JSON.stringify(n,null,2))})}function ry(){$n={}}Pu();Lu.exports={PRICING:Cu,trackUsage:J$,getSessionCosts:Ou,formatCosts:V$,formatCostHint:Q$,resetCosts:ey,getPricing:oa,setCostLimit:ty,removeCostLimit:ny,getCostLimits:sy,getProviderSpend:Nu,checkBudget:Mu,loadCostLimits:Pu,saveCostLimits:oy,resetCostLimits:ry,estimateTokens:Z$}});var rr=J((WS,Iu)=>{function ra(){return process.env.NEX_DEBUG==="true"||process.argv.includes("--debug")}var iy=ra();function ay(...t){ra()&&console.log(...t)}function cy(...t){ra()&&console.warn(...t)}Iu.exports={DEBUG:iy,debugLog:ay,warnLog:cy}});var qu=J((BS,Du)=>{"use strict";var ly=new Set(["read_file","grep","glob","search_files","list_directory"]),uy=new Set(["write_file","edit_file","patch_file"]),dy=new Set(["bash"]),fy=new Set(["web_search","web_fetch","perplexity_search"]);function ju(t,e){let n=0,o=0,s=0,r=0,i=0;for(let[c,l]of t)i+=l,ly.has(c)&&(n+=l),uy.has(c)&&(o+=l),dy.has(c)&&(s+=l),fy.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 ia=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:ju(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}};Du.exports={MilestoneTracker:ia,_phaseName:ju}});var ls=J((HS,Fu)=>{var Ws=Le(),py={"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 my(){return Ws.getActiveModel()}function hy(t){return Ws.setActiveModel(t)}function gy(){return Ws.getModelNames()}function $y(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 yy(t,e){let{C:n}=qe(),{Spinner:o}=qe(),s=new o("Thinking...");s.start();let r=!0,i="";try{let c=await Ws.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}
|
|
91
91
|
`),c}catch(c){throw s.stop(),c}}async function wy(t,e){return Ws.callChat(t,e)}Fu.exports={MODELS:py,getActiveModel:my,setActiveModel:hy,getModelNames:gy,callOllamaStream:yy,callOllama:wy,parseToolArgs:$y}});var Bu=J((GS,Wu)=>{var ir=require("path"),{C:j}=qe(),{T:aa,isDark:KS}=Rn(),{confirm:by,getAutoConfirm:_y}=tt(),Uu=2e3;function Bs(t,e){let n=t.split(`
|
|
92
92
|
`),o=e.split(`
|
|
93
93
|
`),s=[],r=n.length,i=o.length;if(r>Uu||i>Uu){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 xy(t,e,n,o=3){console.log(`
|
|
94
|
-
${j.bold}${j.cyan} Diff: ${t}${j.reset}`);let s=Bs(e,n),r=[];if(s.forEach((l,u)=>{l.type!=="same"&&r.push(u)}),r.length===0){console.log(`${j.gray} (no changes)${j.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(`${j.gray} ...${j.reset}`);for(let l=i;l<c;l++){let u=s[l];switch(u.type){case"remove":console.log(`${j.red} - ${u.line}${j.reset}`);break;case"add":console.log(`${j.green} + ${u.line}${j.reset}`);break;default:console.log(`${j.gray} ${u.line}${j.reset}`)}}c<s.length&&console.log(`${j.gray} ...${j.reset}`),console.log()}function
|
|
95
|
-
${j.bold}${j.cyan} File exists \u2014 showing changes: ${t}${j.reset}`);let o=Bs(e,n),s=0;for(let i of o)i.type!=="same"&&s++;if(s===0){console.log(`${j.gray} (identical content)${j.reset}`);return}let r=0;for(let i of o){if(r>=30){console.log(`${j.gray} ...(${s-r} more changes)${j.reset}`);break}switch(i.type){case"remove":console.log(`${j.red} - ${i.line}${j.reset}`),r++;break;case"add":console.log(`${j.green} + ${i.line}${j.reset}`),r++;break;default:r>0&&console.log(`${j.gray} ${i.line}${j.reset}`)}}console.log()}function
|
|
94
|
+
${j.bold}${j.cyan} Diff: ${t}${j.reset}`);let s=Bs(e,n),r=[];if(s.forEach((l,u)=>{l.type!=="same"&&r.push(u)}),r.length===0){console.log(`${j.gray} (no changes)${j.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(`${j.gray} ...${j.reset}`);for(let l=i;l<c;l++){let u=s[l];switch(u.type){case"remove":console.log(`${j.red} - ${u.line}${j.reset}`);break;case"add":console.log(`${j.green} + ${u.line}${j.reset}`);break;default:console.log(`${j.gray} ${u.line}${j.reset}`)}}c<s.length&&console.log(`${j.gray} ...${j.reset}`),console.log()}function vy(t,e,n){console.log(`
|
|
95
|
+
${j.bold}${j.cyan} File exists \u2014 showing changes: ${t}${j.reset}`);let o=Bs(e,n),s=0;for(let i of o)i.type!=="same"&&s++;if(s===0){console.log(`${j.gray} (identical content)${j.reset}`);return}let r=0;for(let i of o){if(r>=30){console.log(`${j.gray} ...(${s-r} more changes)${j.reset}`);break}switch(i.type){case"remove":console.log(`${j.red} - ${i.line}${j.reset}`),r++;break;case"add":console.log(`${j.green} + ${i.line}${j.reset}`),r++;break;default:r>0&&console.log(`${j.gray} ${i.line}${j.reset}`)}}console.log()}function ky(t,e){console.log(`
|
|
96
96
|
${j.bold}${j.cyan} New file: ${t}${j.reset}`);let n=e.split(`
|
|
97
97
|
`),o=n.slice(0,20);for(let s of o)console.log(`${j.green} + ${s}${j.reset}`);n.length>20&&console.log(`${j.gray} ...+${n.length-20} more lines${j.reset}`),console.log()}async function Sy(t){return _y()?!0:by(` ${t}?`)}function Ey(t,e,n,o){let s=o||process.stdout.columns||80,r=Math.floor((s-3)/2);console.log(`
|
|
98
98
|
${j.bold}${j.cyan} Side-by-side: ${t}${j.reset}`),console.log(` ${j.dim}${"\u2500".repeat(r)}\u252C${"\u2500".repeat(r)}${j.reset}`);let i=Bs(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(` ${j.gray}(no changes)${j.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(` ${j.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${j.reset}`);for(let h=d;h<f;h++){let p=c[h];if(p.type==="same")console.log(` ${j.gray}${m(p.left,r)}${j.reset}\u2502${j.gray}${m(p.right,r)}${j.reset}`);else{let g=p.left?`${j.red}${m(p.left,r)}${j.reset}`:`${m("",r)}`,y=p.right?`${j.green}${m(p.right,r)}${j.reset}`:`${m("",r)}`;console.log(` ${g}\u2502${y}`)}}f<c.length&&console.log(` ${j.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${j.reset}`),console.log(` ${j.dim}${"\u2500".repeat(r)}\u2534${"\u2500".repeat(r)}${j.reset}
|
|
99
99
|
`)}function Ty(t,e,n,o={}){let s=o.label||"Update",r=o.context||3,i=o.annotations||[],c=ir.isAbsolute(t)?ir.relative(process.cwd(),t):t,l=Bs(e,n),u=1,d=1;for(let T of l)T.type==="same"?(T.oldLine=u++,T.newLine=d++):T.type==="remove"?(T.oldLine=u++,T.newLine=null):(T.oldLine=null,T.newLine=d++);let f=0,m=0;for(let T of l)T.type==="add"?f++:T.type==="remove"&&m++;if(console.log(`
|
|
100
100
|
${j.green}\u23FA${j.reset} ${j.bold}${s}(${c})${j.reset}`),f===0&&m===0){console.log(` ${j.dim}\u23BF (no changes)${j.reset}
|
|
101
|
-
`);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 T=i.filter(
|
|
101
|
+
`);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 T=i.filter(v=>v.severity==="error").length,O=i.filter(v=>v.severity==="warn").length,P=i.filter(v=>v.severity==="info").length,W=[];T>0&&W.push(`${j.red}${T} error${T!==1?"s":""}${j.dim}`),O>0&&W.push(`${j.yellow}${O} warning${O!==1?"s":""}${j.dim}`),P>0&&W.push(`${j.cyan}${P} info${P!==1?"s":""}${j.dim}`),h.push(`found ${W.join(", ")}`)}console.log(` ${j.dim}\u23BF ${h.join(", ")}${j.reset}`);let g=[];l.forEach((T,O)=>{T.type!=="same"&&g.push(O)});let y=[],w=null,x=null;for(let T of g){let O=Math.max(0,T-r),P=Math.min(l.length-1,T+r);w===null?(w=O,x=P):(O<=x+1||(y.push([w,x]),w=O),x=P)}w!==null&&y.push([w,x]);let A=" ",E=process.stdout.columns||120;function k(T,O,P){let W=P.replace(/\x1b\[[0-9;]*m/g,""),v=P+" ".repeat(Math.max(0,E-W.length));return`${T}${O}${v}${j.reset}`}for(let T=0;T<y.length;T++){T>0&&console.log(`${A}${j.dim}\xB7\xB7\xB7${j.reset}`);let[O,P]=y[T];for(let W=O;W<=P;W++){let v=l[W],X=v.newLine!=null?v.newLine:v.oldLine,be=String(X).padStart(4),ye=v.type!=="remove"?i.filter(we=>we.line===v.newLine):[];v.type==="remove"?console.log(k(aa.diff_rem_bg,j.red,`${A}${be} - ${v.line}`)):v.type==="add"?console.log(k(aa.diff_add_bg,j.green,`${A}${be} + ${v.line}`)):console.log(`${A}${j.dim}${be} ${j.reset}${v.line}`);for(let we of ye){let ue=j.cyan,fe="\u2139";we.severity==="error"?(ue=j.red,fe="\u2716"):we.severity==="warn"&&(ue=j.yellow,fe="\u26A0"),console.log(`${A} ${ue}${fe} ${we.message}${j.reset}`)}}}console.log()}function Ry(t,e,n={}){let o=ir.isAbsolute(t)?ir.relative(process.cwd(),t):t,s=e.split(`
|
|
102
102
|
`),r=n.annotations||[];console.log(`
|
|
103
|
-
${j.green}\u23FA${j.reset} ${j.bold}Create(${o})${j.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(`${j.red}${f} error${f!==1?"s":""}${j.dim}`),m>0&&p.push(`${j.yellow}${m} warning${m!==1?"s":""}${j.dim}`),h>0&&p.push(`${j.cyan}${h} info${h!==1?"s":""}${j.dim}`),i.push(`found ${p.join(", ")}`)}console.log(` ${j.dim}\u23BF ${i.join(", ")}${j.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(`${aa.diff_add_bg}${j.green}${w}${j.reset}`);for(let x of p){let A=j.cyan,E="\u2139";x.severity==="error"?(A=j.red,E="\u2716"):x.severity==="warn"&&(A=j.yellow,E="\u26A0"),console.log(`${l} ${A}${E} ${x.message}${j.reset}`)}}s.length>20&&console.log(`${l}${j.dim} ...+${s.length-20} more lines${j.reset}`),console.log()}Wu.exports={diffLines:Bs,showEditDiff:xy,showWriteDiff:
|
|
103
|
+
${j.green}\u23FA${j.reset} ${j.bold}Create(${o})${j.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(`${j.red}${f} error${f!==1?"s":""}${j.dim}`),m>0&&p.push(`${j.yellow}${m} warning${m!==1?"s":""}${j.dim}`),h>0&&p.push(`${j.cyan}${h} info${h!==1?"s":""}${j.dim}`),i.push(`found ${p.join(", ")}`)}console.log(` ${j.dim}\u23BF ${i.join(", ")}${j.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(`${aa.diff_add_bg}${j.green}${w}${j.reset}`);for(let x of p){let A=j.cyan,E="\u2139";x.severity==="error"?(A=j.red,E="\u2716"):x.severity==="warn"&&(A=j.yellow,E="\u26A0"),console.log(`${l} ${A}${E} ${x.message}${j.reset}`)}}s.length>20&&console.log(`${l}${j.dim} ...+${s.length-20} more lines${j.reset}`),console.log()}Wu.exports={diffLines:Bs,showEditDiff:xy,showWriteDiff:vy,showNewFilePreview:ky,confirmFileChange:Sy,showSideBySideDiff:Ey,showClaudeDiff:Ty,showClaudeNewFile:Ry}});var yn=J((YS,Gu)=>{var Hu=require("util").promisify(require("child_process").exec),Cy=require("util").promisify(require("child_process").execFile),{C:Ue}=qe();async function ca(t){try{let{stdout:e}=await Hu(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function ar(...t){try{let{stdout:e}=await Cy("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function Ay(){return await ca("git rev-parse --is-inside-work-tree")==="true"}async function Oy(){return await ca("git branch --show-current")}async function la(){try{let{stdout:t}=await Hu("git status --porcelain",{cwd:process.cwd(),timeout:3e4});return!t||!t.trim()?[]:t.split(`
|
|
104
104
|
`).filter(Boolean).map(e=>{let n=e.substring(0,2).trim(),o=e.substring(3);return{status:n,file:o}})}catch{return[]}}async function cr(t=!1){return await ca(`git diff ${t?"--cached":""}`)||""}async function ua(){return(await la()).map(e=>e.file)}async function Ku(){let t=await ua();if(t.length===0)return null;let e=await cr(),o=await cr(!0)||e,s=0,r=0;if(o){let d=o.split(`
|
|
105
105
|
`);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 Ny(t){let n=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await ar("checkout","-b",n)!==null?n:null}async function My(t){return await ar("add","-A"),await ar("commit","-m",t)?await ar("rev-parse","--short","HEAD"):null}async function Py(){let t=await Ku();if(!t)return`${Ue.dim}No changes${Ue.reset}`;let e=[];e.push(`
|
|
106
106
|
${Ue.bold}${Ue.cyan}Git Diff Summary:${Ue.reset}`),e.push(` ${Ue.green}+${t.stats.additions}${Ue.reset} ${Ue.red}-${t.stats.deletions}${Ue.reset} in ${t.files.length} file(s)`),e.push(`
|
|
@@ -124,7 +124,7 @@ ${t.join(`
|
|
|
124
124
|
`);n.push({name:o.name,instructions:r})}}return n}od.exports={initSkillsDir:ed,loadAllSkills:ma,getSkillInstructions:Zy,getSkillCommands:Qy,getSkillToolDefinitions:ew,routeSkillCall:tw,handleSkillCommand:nw,listSkills:sw,enableSkill:ow,disableSkill:rw,getLoadedSkills:iw,installSkill:aw,searchSkills:cw,removeSkill:lw,matchSkillTriggers:uw,_getSkillsDir:Ks,_validateScriptSkill:nd,_loadMarkdownSkill:da,_loadScriptSkill:fa,_parseFrontmatter:sd}});var fr=J((VS,ud)=>{var{spawn:dw}=require("child_process"),fw=require("path"),rd=require("fs"),sn=new Map;function pw(){return fw.join(process.cwd(),".nex","config.json")}function ha(){let t=pw();if(!rd.existsSync(t))return{};try{return JSON.parse(rd.readFileSync(t,"utf-8")).mcpServers||{}}catch{return{}}}function dr(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})+`
|
|
125
125
|
`,l="",u=setTimeout(()=>{f(),r(new Error(`MCP request timeout: ${e}`))},o);function d(m){l+=m.toString();let h=l.split(`
|
|
126
126
|
`);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 id(t,e){if(sn.has(t))return sn.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=dw(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:{...o,...e.env||{}}}),r={name:t,proc:s,tools:[],config:e};try{await dr(s,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.2.0"}});let i=await dr(s,"tools/list",{});return r.tools=i&&i.tools||[],sn.set(t,r),r}catch(i){throw s.kill(),new Error(`Failed to connect MCP server '${t}': ${i.message}`)}}function ad(t){let e=sn.get(t);if(!e)return!1;try{e.proc.kill()}catch{}return sn.delete(t),!0}function mw(){for(let[t]of sn)ad(t)}async function cd(t,e,n={}){let o=sn.get(t);if(!o)throw new Error(`MCP server not connected: ${t}`);let s=await dr(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(`
|
|
127
|
-
`):JSON.stringify(s)}function ld(){let t=[];for(let[e,n]of sn)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 hw(){return ld().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function gw(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 cd(o,s,e)}function $w(){let t=ha();return Object.entries(t).map(([e,n])=>{let o=sn.get(e);return{name:e,command:n.command,connected:!!o,toolCount:o?o.tools.length:0}})}async function yw(){let t=ha(),e=[];for(let[n,o]of Object.entries(t))try{let s=await id(n,o);e.push({name:n,tools:s.tools.length})}catch(s){e.push({name:n,tools:0,error:s.message})}return e}ud.exports={loadMCPConfig:ha,sendRequest:dr,connectServer:id,disconnectServer:ad,disconnectAll:mw,callTool:cd,getAllTools:ld,getMCPToolDefinitions:hw,routeMCPCall:gw,listServers:$w,connectAll:yw}});var mr=J((ZS,md)=>{var dd=require("fs"),ga=require("path"),pr=[],Gs=[],Pn={},Ys=["onToolResult","onModelResponse","onSessionStart","onSessionEnd","onFileChange","beforeToolExec","afterToolExec"];function fd(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 Gs.some(o=>o.definition.function.name===n)?{ok:!1,error:`Tool "${n}" is already registered`}:(Gs.push({definition:{type:"function",...t},handler:e}),{ok:!0})}function pd(t,e){return Ys.includes(t)?typeof e!="function"?{ok:!1,error:"Handler must be a function"}:(Pn[t]||(Pn[t]=[]),Pn[t].push(e),{ok:!0}):{ok:!1,error:`Unknown event "${t}". Available: ${Ys.join(", ")}`}}async function $a(t,e){let n=Pn[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 ww(){let t=ga.join(process.cwd(),".nex","plugins"),e=[];if(!dd.existsSync(t))return{loaded:0,errors:[]};let n=dd.readdirSync(t).filter(s=>s.endsWith(".js")),o={registerTool:fd,registerHook:pd,EVENTS:Ys};for(let s of n){let r=ga.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}pr.push({name:i.name||ga.basename(s,".js"),filePath:r})}catch(i){e.push(`${s}: ${i.message}`)}}return{loaded:pr.length,errors:e}}function bw(){return Gs.map(t=>t.definition)}async function _w(t,e,n={}){let o=Gs.find(c=>c.definition.function.name===t);if(!o)return null;let s=await $a("beforeToolExec",{name:t,args:e,options:n}),r=await o.handler(s.args||e,n);return(await $a("afterToolExec",{name:t,args:e,result:r})).result||r}function xw(){return[...pr]}function
|
|
127
|
+
`):JSON.stringify(s)}function ld(){let t=[];for(let[e,n]of sn)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 hw(){return ld().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function gw(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 cd(o,s,e)}function $w(){let t=ha();return Object.entries(t).map(([e,n])=>{let o=sn.get(e);return{name:e,command:n.command,connected:!!o,toolCount:o?o.tools.length:0}})}async function yw(){let t=ha(),e=[];for(let[n,o]of Object.entries(t))try{let s=await id(n,o);e.push({name:n,tools:s.tools.length})}catch(s){e.push({name:n,tools:0,error:s.message})}return e}ud.exports={loadMCPConfig:ha,sendRequest:dr,connectServer:id,disconnectServer:ad,disconnectAll:mw,callTool:cd,getAllTools:ld,getMCPToolDefinitions:hw,routeMCPCall:gw,listServers:$w,connectAll:yw}});var mr=J((ZS,md)=>{var dd=require("fs"),ga=require("path"),pr=[],Gs=[],Pn={},Ys=["onToolResult","onModelResponse","onSessionStart","onSessionEnd","onFileChange","beforeToolExec","afterToolExec"];function fd(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 Gs.some(o=>o.definition.function.name===n)?{ok:!1,error:`Tool "${n}" is already registered`}:(Gs.push({definition:{type:"function",...t},handler:e}),{ok:!0})}function pd(t,e){return Ys.includes(t)?typeof e!="function"?{ok:!1,error:"Handler must be a function"}:(Pn[t]||(Pn[t]=[]),Pn[t].push(e),{ok:!0}):{ok:!1,error:`Unknown event "${t}". Available: ${Ys.join(", ")}`}}async function $a(t,e){let n=Pn[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 ww(){let t=ga.join(process.cwd(),".nex","plugins"),e=[];if(!dd.existsSync(t))return{loaded:0,errors:[]};let n=dd.readdirSync(t).filter(s=>s.endsWith(".js")),o={registerTool:fd,registerHook:pd,EVENTS:Ys};for(let s of n){let r=ga.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}pr.push({name:i.name||ga.basename(s,".js"),filePath:r})}catch(i){e.push(`${s}: ${i.message}`)}}return{loaded:pr.length,errors:e}}function bw(){return Gs.map(t=>t.definition)}async function _w(t,e,n={}){let o=Gs.find(c=>c.definition.function.name===t);if(!o)return null;let s=await $a("beforeToolExec",{name:t,args:e,options:n}),r=await o.handler(s.args||e,n);return(await $a("afterToolExec",{name:t,args:e,result:r})).result||r}function xw(){return[...pr]}function vw(){let t={};for(let e of Ys)t[e]=(Pn[e]||[]).length;return t}function kw(){pr.length=0,Gs.length=0;for(let t of Object.keys(Pn))delete Pn[t]}md.exports={registerTool:fd,registerHook:pd,emit:$a,loadPlugins:ww,getPluginToolDefinitions:bw,executePluginTool:_w,getLoadedPlugins:xw,getHookCounts:vw,clearPlugins:kw,EVENTS:Ys}});var ya=J((QS,yd)=>{var{getSkillToolDefinitions:Sw}=wn(),{getMCPToolDefinitions:Ew}=fr(),{getPluginToolDefinitions:Tw}=mr(),hr=new Map;function hd(){let{TOOL_DEFINITIONS:t}=It();return[...t,...Sw(),...Ew(),...Tw()]}function gd(t){if(hr.has(t))return hr.get(t);let n=hd().find(s=>s.function.name===t);if(!n)return null;let o=n.function.parameters;return hr.set(t,o),o}function Rw(){hr.clear()}function gr(t,e){if(!t||e.length===0)return null;let n=null,o=1/0;for(let s of e){let r=$d(t.toLowerCase(),s.toLowerCase());r<o&&(o=r,n=s)}return o<=Math.ceil(t.length/2)?n:null}function $d(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 Cw(t,e){let n=gd(t);if(n===null){let d=hd().map(m=>m.function.name),f=gr(t,d);return{valid:!1,error:`Unknown tool "${t}".${f?` Did you mean "${f}"?`:""}
|
|
128
128
|
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=gr(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=gr(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:
|
|
129
129
|
`+i.map(u=>` - ${u}`).join(`
|
|
130
130
|
`)+`
|
|
@@ -141,21 +141,21 @@ Expected parameters: ${JSON.stringify(n.properties,null,2)}`}:{valid:!0,correcte
|
|
|
141
141
|
`),s=e.split(`
|
|
142
142
|
`).length;return n.length===0||s===0?null:s===1?Iw(n,e):Dw(n,e,s)}function wd(t){return Math.max(1,Math.floor(t/Ow))}function bd(t,e){return t<=Math.ceil(e*Nw)}function Iw(t,e){let n=e.trim(),o=wd(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=$r(c.trim(),n);l<r&&(r=l,s={text:c,distance:l,line:i+1})}return s&&o>1&&(s=jw(t,n,s,o)||s,r=s.distance),bd(r,e.length)?s:null}function jw(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=$r(d.trim(),e);f<c&&(c=f,l={text:d,distance:f,line:u+1})}return l}function Dw(t,e,n){let o=t.length-n+1;if(o<=0)return null;let s=wd(o),r=null,i=1/0;for(let c=0;c<o;c+=s){let l=t.slice(c,c+n).join(`
|
|
143
143
|
`),u=$r(l,e);u<i&&(i=u,r={text:l,distance:u,line:c+1})}return r&&s>1&&(r=qw(t,e,r,s,n,o)||r,i=r.distance),bd(i,e.length)?r:null}function qw(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(`
|
|
144
|
-
`),h=$r(m,e);h<u&&(u=h,d={text:m,distance:h,line:f+1})}return d}_d.exports={normalizeWhitespace:wa,fuzzyFindText:Pw,findMostSimilar:Lw}});var
|
|
145
|
-
`),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 Fw)l.regex.test(i)&&o.push({line:c,message:`Potential secret detected: ${l.name}`,severity:"error"});for(let l of Uw)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 Bw(){let t=process.memoryUsage();return{rss:Math.round(t.rss/1024/1024*100)/100,heapUsed:Math.round(t.heapUsed/1024/1024*100)/100}}
|
|
146
|
-
`).filter(Boolean),_a=Date.now(),yr=!1;return}catch{}let e=[],n=async(o,s)=>{let r;try{r=await ds.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(fs.join(o,i.name),c):e.push(c)}};await n(t,""),ps=e,_a=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{yr=!1}}}function xa(){return ps}function Gw(){return
|
|
147
|
-
`);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 Cd(t){t=t||process.cwd();let e=fs.join(t,".nex","index","content-index.json"),n={};if(ba&&Date.now()-Sd<Xw)return ba;try{let i=await ds.readFile(e,"utf-8");n=JSON.parse(i)}catch{n={files:{}}}xa().length===0&&await Td(t);let s={files:{}},r=!1;for(let i of xa()){let c=fs.extname(i);if(!Jw.has(c))continue;let l=fs.join(t,i);try{let d=(await ds.stat(l)).mtimeMs;if(n.files[i]&&n.files[i].mtime===d){s.files[i]=n.files[i];continue}let f=await ds.readFile(l,"utf-8"),m=Rd(f,c);s.files[i]={defs:m,mtime:d},r=!0}catch{}}if(r){let i=fs.join(t,".nex","index");await ds.mkdir(i,{recursive:!0}),await ds.writeFile(e,JSON.stringify(s),"utf-8")}return ba=s,Sd=Date.now(),s}async function Vw(t,e){let n=await Cd(),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)}Ad.exports={refreshIndex:Td,getFileIndex:xa,getIndexedCwd:Gw,findFileInIndex:Yw,searchIndex:zw,isIndexValid:Ed,buildContentIndex:Cd,searchContentIndex:Vw,extractDefinitions:Rd}});var ms=J((oE,Pd)=>{var wr=require("fs"),_r=require("path"),xr=require("os"),{execFile:Zw}=require("child_process"),{promisify:Qw}=require("util"),Sa=Qw(Zw),e0=_r.join(xr.homedir(),".nex","servers.json"),br=_r.join(xr.tmpdir(),"nex-ssh-sockets");function t0(){return _r.join(process.cwd(),".nex","servers.json")}function Od(){let t=o=>{if(!wr.existsSync(o))return{};try{return JSON.parse(wr.readFileSync(o,"utf-8"))}catch{return{}}},e=t(e0),n=t(t0());return{...e,...n}}function n0(t){let e=Od();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 s0(){wr.existsSync(br)||wr.mkdirSync(br,{recursive:!0})}function Nd(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-o","ServerAliveInterval=30"];t.key&&e.push("-i",t.key.replace(/^~/,xr.homedir())),t.port&&Number(t.port)!==22&&e.push("-p",String(t.port)),s0();let n=t.user?`${t.user}@${t.host}`:t.host,o=_r.join(br,n.replace(/[@.:]/g,"_"));return e.push("-o","ControlMaster=auto","-o",`ControlPath=${o}`,"-o","ControlPersist=120"),e.push(n),{args:e,target:n}}function Md(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-r"];return t.key&&e.push("-i",t.key.replace(/^~/,xr.homedir())),t.port&&Number(t.port)!==22&&e.push("-P",String(t.port)),e}async function o0(t,e,{timeout:n=3e4,sudo:o=!1}={}){let{args:s}=Nd(t),r=o&&t.sudo?`sudo sh -c ${JSON.stringify(e)}`:e;try{let{stdout:i,stderr:c}=await Sa("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:
|
|
144
|
+
`),h=$r(m,e);h<u&&(u=h,d={text:m,distance:h,line:f+1})}return d}_d.exports={normalizeWhitespace:wa,fuzzyFindText:Pw,findMostSimilar:Lw}});var kd=J((nE,vd)=>{var{C:tE}=qe(),Fw=[{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}],Uw=[{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 Ww(t,e){let n=e.split(`
|
|
145
|
+
`),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 Fw)l.regex.test(i)&&o.push({line:c,message:`Potential secret detected: ${l.name}`,severity:"error"});for(let l of Uw)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 Bw(){let t=process.memoryUsage();return{rss:Math.round(t.rss/1024/1024*100)/100,heapUsed:Math.round(t.heapUsed/1024/1024*100)/100}}vd.exports={runDiagnostics:Ww,getMemoryUsage:Bw}});var ka=J((sE,Ad)=>{var ds=require("fs").promises,fs=require("path"),{exec:Hw}=require("util").promisify(require("child_process").exec),ps=[],va=null,yr=!1,_a=0,Kw=6e4;function Ed(t){return!(ps.length===0||va!==t||Date.now()-_a>Kw)}async function Td(t){if(!yr&&!Ed(t)){yr=!0,va=t;try{try{let{stdout:o}=await Hw("rg --files",{cwd:t,timeout:5e3});ps=o.split(`
|
|
146
|
+
`).filter(Boolean),_a=Date.now(),yr=!1;return}catch{}let e=[],n=async(o,s)=>{let r;try{r=await ds.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(fs.join(o,i.name),c):e.push(c)}};await n(t,""),ps=e,_a=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{yr=!1}}}function xa(){return ps}function Gw(){return va}function Yw(t){return ps.filter(e=>fs.basename(e)===t)}function zw(t){let e=t.toLowerCase();return ps.filter(n=>n.toLowerCase().includes(e)).slice(0,20)}var ba=null,Sd=0,Xw=12e4,Jw=new Set([".js",".ts",".jsx",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".rb"]);function Rd(t,e){let n=[],o=t.split(`
|
|
147
|
+
`);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 Cd(t){t=t||process.cwd();let e=fs.join(t,".nex","index","content-index.json"),n={};if(ba&&Date.now()-Sd<Xw)return ba;try{let i=await ds.readFile(e,"utf-8");n=JSON.parse(i)}catch{n={files:{}}}xa().length===0&&await Td(t);let s={files:{}},r=!1;for(let i of xa()){let c=fs.extname(i);if(!Jw.has(c))continue;let l=fs.join(t,i);try{let d=(await ds.stat(l)).mtimeMs;if(n.files[i]&&n.files[i].mtime===d){s.files[i]=n.files[i];continue}let f=await ds.readFile(l,"utf-8"),m=Rd(f,c);s.files[i]={defs:m,mtime:d},r=!0}catch{}}if(r){let i=fs.join(t,".nex","index");await ds.mkdir(i,{recursive:!0}),await ds.writeFile(e,JSON.stringify(s),"utf-8")}return ba=s,Sd=Date.now(),s}async function Vw(t,e){let n=await Cd(),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)}Ad.exports={refreshIndex:Td,getFileIndex:xa,getIndexedCwd:Gw,findFileInIndex:Yw,searchIndex:zw,isIndexValid:Ed,buildContentIndex:Cd,searchContentIndex:Vw,extractDefinitions:Rd}});var ms=J((oE,Pd)=>{var wr=require("fs"),_r=require("path"),xr=require("os"),{execFile:Zw}=require("child_process"),{promisify:Qw}=require("util"),Sa=Qw(Zw),e0=_r.join(xr.homedir(),".nex","servers.json"),br=_r.join(xr.tmpdir(),"nex-ssh-sockets");function t0(){return _r.join(process.cwd(),".nex","servers.json")}function Od(){let t=o=>{if(!wr.existsSync(o))return{};try{return JSON.parse(wr.readFileSync(o,"utf-8"))}catch{return{}}},e=t(e0),n=t(t0());return{...e,...n}}function n0(t){let e=Od();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 s0(){wr.existsSync(br)||wr.mkdirSync(br,{recursive:!0})}function Nd(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-o","ServerAliveInterval=30"];t.key&&e.push("-i",t.key.replace(/^~/,xr.homedir())),t.port&&Number(t.port)!==22&&e.push("-p",String(t.port)),s0();let n=t.user?`${t.user}@${t.host}`:t.host,o=_r.join(br,n.replace(/[@.:]/g,"_"));return e.push("-o","ControlMaster=auto","-o",`ControlPath=${o}`,"-o","ControlPersist=120"),e.push(n),{args:e,target:n}}function Md(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-r"];return t.key&&e.push("-i",t.key.replace(/^~/,xr.homedir())),t.port&&Number(t.port)!==22&&e.push("-P",String(t.port)),e}async function o0(t,e,{timeout:n=3e4,sudo:o=!1}={}){let{args:s}=Nd(t),r=o&&t.sudo?`sudo sh -c ${JSON.stringify(e)}`:e;try{let{stdout:i,stderr:c}=await Sa("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:vr(l,t)}}}async function r0(t,e,n,{timeout:o=12e4}={}){let s=Md(t),r=t.user?`${t.user}@${t.host}`:t.host;s.push(e,`${r}:${n}`);try{let{stdout:i,stderr:c}=await Sa("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(vr(c,t)||c)}}async function i0(t,e,n,{timeout:o=12e4}={}){let s=Md(t),r=t.user?`${t.user}@${t.host}`:t.host;s.push(`${r}:${e}`,n);try{let{stdout:i,stderr:c}=await Sa("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(vr(c,t)||c)}}function vr(t,e){if(!t)return"";if(/connection refused/i.test(t)){let n=e.port||22;return`${t}
|
|
148
148
|
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}
|
|
149
149
|
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}
|
|
150
150
|
HINT: Cannot reach ${e.host}. Check: network connection, correct hostname/IP, DNS resolution.`:/host key verification failed/i.test(t)?`${t}
|
|
151
151
|
HINT: Host key changed for ${e.host}. To reset: ssh-keygen -R ${e.host}`:/timed out/i.test(t)?`${t}
|
|
152
152
|
HINT: Connection timed out to ${e.host}. Check firewall rules and network connectivity.`:/too many authentication failures/i.test(t)?`${t}
|
|
153
|
-
HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function a0(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}`}Pd.exports={loadServerProfiles:Od,resolveProfile:n0,buildSSHArgs:Nd,sshExec:o0,scpUpload:r0,scpDownload:i0,enrichSSHError:
|
|
153
|
+
HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function a0(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}`}Pd.exports={loadServerProfiles:Od,resolveProfile:n0,buildSSHArgs:Nd,sshExec:o0,scpUpload:r0,scpDownload:i0,enrichSSHError:vr,formatProfile:a0,SSH_SOCKET_DIR:br}});var Ra=J((rE,Id)=>{var zs=require("fs"),Ea=require("path"),c0=Ea.join(".nex","deploy.json");function Ta(){return Ea.join(process.cwd(),c0)}function Ld(){let t=Ta();if(!zs.existsSync(t))return{};try{return JSON.parse(zs.readFileSync(t,"utf-8"))}catch{return{}}}function l0(t){let e=Ld();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 u0(t){let e=Ea.join(process.cwd(),".nex");zs.existsSync(e)||zs.mkdirSync(e,{recursive:!0}),zs.writeFileSync(Ta(),JSON.stringify(t,null,2)+`
|
|
154
154
|
`,"utf-8")}Id.exports={loadDeployConfigs:Ld,resolveDeployConfig:l0,saveDeployConfigs:u0,getDeployConfigPath:Ta}});var Js=J((iE,qd)=>{var Ca=null,on=null,Xs=null,jd=`Playwright is not installed. Install with:
|
|
155
155
|
npm install playwright && npx playwright install chromium
|
|
156
|
-
Then restart nex-code.`;function Dd(){if(Xs!==null)return Xs;try{require("playwright"),Xs=!0}catch{Xs=!1}return Xs}async function
|
|
157
|
-
...(truncated)`:""),links:c.slice(0,20)}}finally{await s.close()}}async function p0(t,{width:e=1280,height:n=800,fullPage:o=!1,timeout:s=3e4}={}){let i=await(await
|
|
158
|
-
`)}function
|
|
156
|
+
Then restart nex-code.`;function Dd(){if(Xs!==null)return Xs;try{require("playwright"),Xs=!0}catch{Xs=!1}return Xs}async function kr(){if(!Dd())throw new Error(jd);return Ca||(Ca=require("playwright")),(!on||!on.isConnected())&&(on=await Ca.chromium.launch({headless:!0})),on}async function d0(){if(on){try{await on.close()}catch{}on=null}}process.on("exit",()=>{if(on)try{on.close()}catch{}});async function f0(t,{timeout:e=3e4,waitFor:n="domcontentloaded"}={}){let s=await(await kr()).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?`
|
|
157
|
+
...(truncated)`:""),links:c.slice(0,20)}}finally{await s.close()}}async function p0(t,{width:e=1280,height:n=800,fullPage:o=!1,timeout:s=3e4}={}){let i=await(await kr()).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 m0(t,{selector:e,text:n,timeout:o=3e4}={}){if(!e&&!n)throw new Error("selector or text is required");let r=await(await kr()).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 h0(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 kr()).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()}}qd.exports={isPlaywrightAvailable:Dd,browserNavigate:f0,browserScreenshot:p0,browserClick:m0,browserFill:h0,closeBrowser:d0,INSTALL_MSG:jd}});var Sr=J((aE,Fd)=>{var{C:je}=qe(),Zs="",it=[],Vs=0,Ln=null;function g0(t){Ln=t}function $0(t,e){Zs=t,it=[],Vs=0;for(let o of e){Vs++;let s=`t${Vs}`;it.push({id:s,description:o.description||o.title||o.name||o.task||`Task ${Vs}`,status:"pending",dependsOn:o.depends_on||[],result:null})}let n=it.map(o=>({...o}));return Ln&&Ln("create",{name:t,tasks:n}),n}function y0(t,e,n){let o=it.find(s=>s.id===t);return o?(o.status=e,n!==void 0&&(o.result=n),Ln&&Ln("update",{id:t,status:e,result:n}),{...o}):null}function w0(){return{name:Zs,tasks:it.map(t=>({...t}))}}function b0(){Zs="",it=[],Vs=0,Ln&&Ln("clear",{})}function _0(){return it.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let n=it.find(o=>o.id===e);return n&&n.status==="done"}))}function x0(){if(it.length===0)return`${je.dim}No active tasks${je.reset}`;let t=[];Zs&&(t.push(` ${je.bold}${je.cyan}Tasks: ${Zs}${je.reset}`),t.push(` ${je.dim}${"\u2500".repeat(40)}${je.reset}`));for(let s of it){let r,i;switch(s.status){case"done":r="\u2713",i=je.green;break;case"in_progress":r="\u2192",i=je.cyan;break;case"failed":r="\u2717",i=je.red;break;default:r="\xB7",i=je.dim}let c=s.dependsOn.length>0?` ${je.dim}(after: ${s.dependsOn.join(", ")})${je.reset}`:"",l=`[${s.status}]`,u=s.description.length>50?s.description.substring(0,47)+"...":s.description;if(t.push(` ${i}${r}${je.reset} ${je.bold}${s.id}${je.reset} ${u.padEnd(40)} ${i}${l}${je.reset}${c}`),s.result&&s.status==="done"){let d=s.result.length>60?s.result.substring(0,57)+"...":s.result;t.push(` ${je.dim}\u2192 ${d}${je.reset}`)}}let e=it.filter(s=>s.status==="done").length,n=it.filter(s=>s.status==="failed").length,o=it.length;return t.push(` ${je.dim}${"\u2500".repeat(40)}${je.reset}`),t.push(` ${je.dim}${e}/${o} done${n>0?`, ${n} failed`:""}${je.reset}`),t.join(`
|
|
158
|
+
`)}function v0(){return it.length>0&&it.some(t=>t.status==="pending"||t.status==="in_progress")}Fd.exports={createTasks:$0,updateTask:y0,getTaskList:w0,clearTasks:b0,getReadyTasks:_0,renderTaskList:x0,setOnChange:g0,hasActiveTasks:v0}});var Cr=J((lE,cf)=>{var{callStream:k0,getActiveProviderName:Tr,getActiveModelId:S0,getConfiguredProviders:E0,getProvider:Ud,getActiveProvider:Wd,parseModelSpec:Bd}=Le(),{parseToolArgs:Hd}=ls(),{filterToolsForModel:T0,getModelTier:Er}=Fs(),{trackUsage:Kd,estimateTokens:Gd}=cs(),{MultiProgress:R0,C:cE}=qe();function Yd(t){return!t||typeof t!="string"?0:typeof Gd=="function"?Gd(t):Math.ceil(t.length/4)}var Jd=15,C0=5,zd=3,Vd=8,A0=2,Rr=new Map,Zd=600*1e3;function O0(t,e){let n=Rr.get(t);return n&&n.agentId!==e&&Date.now()-n.timestamp<Zd?!1:(Rr.set(t,{agentId:e,timestamp:Date.now()}),!0)}function Qs(t){Rr.delete(t)}function Aa(){Rr.clear()}function Oa(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 Qd(t){let e=Oa(t);return e==="rate_limit"||e==="server"||e==="network"}async function ef(t,e,n){let o;for(let s=0;s<=zd;s++)try{return await k0(t,e,n)}catch(r){o=r;let i=Oa(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<zd&&Qd(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 Xd=new Set(["ask_user","task_list"]);function tf(t){return t>=2?new Set([...Xd,"spawn_agents"]):Xd}var N0=new Set(["write_file","edit_file","patch_file"]),nf={explore:{allowedTools:new Set(["bash","read_file","list_directory","glob","grep","search_files","web_fetch","web_search"]),systemSuffix:"You are an exploration agent. Read and search code only. Do NOT modify any files."},review:{allowedTools:new Set(["read_file","list_directory","glob","grep","search_files"]),systemSuffix:"You are a code review agent. Read code and report findings. Do NOT make changes."},implement:{allowedTools:null,systemSuffix:""}},M0=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,P0=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function sf(t){return P0.test(t)?"full":M0.test(t)?"essential":t.length>300?"full":"standard"}function of(t){let e=E0(),n=Tr(),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(Er(r.id,s.name)===t)return{provider:s.name,model:r.id};return null}var L0={essential:process.env.NEX_FAST_MODEL||null,standard:process.env.NEX_STANDARD_MODEL||null,full:process.env.NEX_HEAVY_MODEL||null};function Na(t){if(t.model){let{provider:s,model:r}=Bd(t.model),i=s?Ud(s):Wd(),c=s||Tr();if(i&&i.isConfigured()&&(i.getModel(r)||c==="local")){let l=Er(r,c);return{provider:c,model:r,tier:l}}}let e=sf(t.task),n=L0[e];if(n){let{provider:s,model:r}=Bd(n),i=s?Ud(s):Wd(),c=s||Tr();if(i&&i.isConfigured()&&(i.getModel(r)||c==="local")){let l=Er(r,c);return{provider:c,model:r,tier:l}}}let o=of(e);if(o){let s=Er(o.model,o.provider);return{provider:o.provider,model:o.model,tier:s}}return{provider:null,model:null,tier:null}}async function rf(t,e={},n=0){let o=n===0?Jd:Vd,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,d=t._systemPrompt||`You are a focused sub-agent. Complete this specific task efficiently.
|
|
159
159
|
|
|
160
160
|
TASK: ${t.task}
|
|
161
161
|
${t.context?`
|
|
@@ -179,8 +179,8 @@ ERROR RECOVERY:
|
|
|
179
179
|
- If bash fails: read the error, fix the root cause, then retry.
|
|
180
180
|
- After 2 failed attempts at the same operation, summarize the issue and stop.`,f=t.type&&nf[t.type],m=f&&f.systemSuffix?`
|
|
181
181
|
|
|
182
|
-
${f.systemSuffix}`:"",h=[{role:"system",content:d+m}];h.push({role:"user",content:t.task});let p=Na(t),g=p.provider,y=p.model,w=p.tier,{TOOL_DEFINITIONS:x,executeTool:A}=It(),E=tf(n),
|
|
183
|
-
`)}let T={};g&&(T.provider=g),y&&(T.model=y);try{for(let P=0;P<s;P++){let W=await ef(h,
|
|
182
|
+
${f.systemSuffix}`:"",h=[{role:"system",content:d+m}];h.push({role:"user",content:t.task});let p=Na(t),g=p.provider,y=p.model,w=p.tier,{TOOL_DEFINITIONS:x,executeTool:A}=It(),E=tf(n),k=T0(x.filter(O=>!E.has(O.function.name)),w);if(f&&f.allowedTools&&(k=k.filter(O=>f.allowedTools.has(O.function.name))),y&&!t._skipLog){let O=w?` (${w})`:"";process.stderr.write(` [sub-agent: ${g}:${y}${O}]
|
|
183
|
+
`)}let T={};g&&(T.provider=g),y&&(T.model=y);try{for(let P=0;P<s;P++){let W=await ef(h,k,T);if(!W||typeof W!="object")throw new Error("Empty or invalid response from provider");{let ue=g||Tr(),fe=y||S0();if(W.usage){let pe=W.usage.prompt_tokens||0,de=W.usage.completion_tokens||0;c.input+=pe,c.output+=de,Kd(ue,fe,pe,de)}else{let pe=W.content||"",de=h.map(S=>typeof S.content=="string"?S.content:Array.isArray(S.content)?S.content.map(L=>typeof L=="string"?L:L.text||"").join(""):"").join(" "),Ee=Yd(de),Me=Yd(pe);c.input+=Ee,c.output+=Me,c._estimated=!0,Kd(ue,fe,Ee,Me)}}let v=W.content||"",X=W.tool_calls,be={role:"assistant",content:v||""};if(X&&X.length>0&&(be.tool_calls=X),h.push(be),!X||X.length===0){for(let ue of l)Qs(ue);return{task:t.task,status:"done",result:v||"(no response)",toolsUsed:i,tokensUsed:c,modelSpec:g&&y?`${g}:${y}`:null}}let ye=X.map(ue=>{let fe=ue.function.name,pe=Hd(ue.function.arguments),de=ue.id||`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!pe)return Promise.resolve({role:"tool",content:`ERROR: Malformed tool arguments for ${fe}`,tool_call_id:de});let Ee=null;if(N0.has(fe)&&pe.path){let S=require("path"),L=S.isAbsolute(pe.path)?pe.path:S.resolve(process.cwd(),pe.path);if(l.has(L)||!O0(L,r))return Promise.resolve({role:"tool",content:`ERROR: File '${pe.path}' is locked by another operation. Try a different approach or skip this file.`,tool_call_id:de});l.add(L),Ee=L}return i.push(fe),e.onUpdate&&e.onUpdate({type:"tool_call",tool:fe,agentId:r}),(fe==="spawn_agents"?af(pe,n+1):A(fe,pe,{autoConfirm:!0,silent:!0})).then(S=>{Ee&&(Qs(Ee),l.delete(Ee));let L=String(S??"");return{role:"tool",content:L.length>2e4?L.substring(0,2e4)+`
|
|
184
184
|
...(truncated)`:L,tool_call_id:de}}).catch(S=>(Ee&&(Qs(Ee),l.delete(Ee)),{role:"tool",content:`ERROR: ${S.message}`,tool_call_id:de}))}),we=await Promise.all(ye);if(h.push(...we),P>=7&&h.length>12)try{let{compressMessage:ue}=nt(),fe=h.length-6;for(let pe=1;pe<fe;pe++)h[pe]._subAgentCompressed||(h[pe]={...ue(h[pe],"light"),_subAgentCompressed:!0})}catch{}for(let ue=0;ue<X.length;ue++){let fe=X[ue];if(fe.function.name==="bash_exec"){let pe=Hd(fe.function.arguments);if((we[ue]?.content||"").startsWith("ERROR")&&pe&&pe.command){let Ee=pe.command.replace(/\s+/g," ").trim().slice(0,100);u.set(Ee,(u.get(Ee)||0)+1)}}}e.onUpdate&&e.onUpdate(`step ${P+1}/${s}`)}for(let P of l)Qs(P);let O=[...u.entries()].filter(([,P])=>P>=3).sort((P,W)=>W[1]-P[1]).slice(0,3).map(([P,W])=>`"${P}" (failed ${W}\xD7)`);return{task:t.task,status:"truncated",abortReason:"iteration_limit",repeatedFailures:O,result:h[h.length-1]?.content||"(max iterations reached)",toolsUsed:i,tokensUsed:c,modelSpec:g&&y?`${g}:${y}`:null}}catch(O){for(let P of l)Qs(P);return{task:t.task,status:"failed",result:`Error: ${O.message}`,toolsUsed:i,tokensUsed:c,modelSpec:g&&y?`${g}:${y}`:null}}}async function af(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?C0:A0,o=e===0?Jd:Vd,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=>Na(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 R0(l);u.start();try{let d=s.map((g,y)=>{let w=c[y],x=Math.min(g.max_iterations||o,o),A=w.model?{...g,model:`${w.provider}:${w.model}`,_skipLog:!0,max_iterations:x}:{...g,_skipLog:!0,max_iterations:x};return rf(A,{onUpdate:()=>{}},e).then(E=>(u.update(y,E.status==="failed"?"error":"done"),E)).catch(E=>(u.update(y,"error"),{task:g.task,status:"failed",result:`Error: ${E.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}))}),f=await Promise.all(d);u.stop(),Aa();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(`
|
|
185
185
|
`)}catch(d){return u.stop(),Aa(),`ERROR: Sub-agent execution failed: ${d.message}`}}cf.exports={runSubAgent:rf,executeSpawnAgents:af,clearAllLocks:Aa,classifyTask:sf,pickModelForTier:of,resolveSubAgentModel:Na,classifyError:Oa,isRetryableError:Qd,callWithRetry:ef,getExcludedTools:tf,LOCK_TIMEOUT_MS:Zd,SUB_AGENT_TYPES:nf}});var no=J((uE,xf)=>{var We=require("fs"),rn=require("path"),{atomicWrite:lf,withFileLockSync:uf}=gn(),I0=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 gs(){let t=rn.join(process.cwd(),".nex","brain");return We.existsSync(t)||We.mkdirSync(t,{recursive:!0}),t}function Or(){return rn.join(gs(),".brain-index.json")}function La(){return rn.join(gs(),".embeddings.json")}function eo(){let t=rn.join(process.cwd(),".nex","brain");if(!We.existsSync(t))return[];try{return We.readdirSync(t).filter(e=>e.endsWith(".md")&&!e.startsWith(".")).map(e=>{let n=rn.join(t,e),o=We.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 to(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(`
|
|
186
186
|
`);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 df(t){let e=rn.join(gs(),`${t}.md`);if(!We.existsSync(e))return{name:t,content:"",body:"",frontmatter:{}};let n=We.readFileSync(e,"utf-8"),{frontmatter:o,body:s}=to(n);return{name:t,content:n,body:s,frontmatter:o}}function j0(t,e){let n=rn.join(gs(),`${t}.md`);lf(n,e),F0(t,e),D0()}function D0(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return;let t=La();We.existsSync(t)&&setImmediate(async()=>{try{await yf()}catch{}})}function q0(t){let e=rn.join(gs(),`${t}.md`);return We.existsSync(e)?(We.unlinkSync(e),U0(t),!0):!1}function Ar(t){return t.toLowerCase().replace(/[^a-z0-9äöüß\s-]/g," ").split(/[\s-]+/).filter(e=>e.length>2&&!I0.has(e))}function Ia(t){let e={},{frontmatter:n,body:o}=to(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(`
|
|
@@ -190,7 +190,7 @@ ${f}`),l+=r(f),l>=i)break}if(c.length===0)return hs={queryKey:o,result:"",ts:Dat
|
|
|
190
190
|
|
|
191
191
|
${c.join(`
|
|
192
192
|
|
|
193
|
-
`)}`;return hs={queryKey:o,result:u,ts:Date.now()},u}xf.exports={getBrainDir:gs,listDocuments:eo,readDocument:df,writeDocument:j0,removeDocument:q0,buildIndex:Pa,getIndex:ff,query:_f,getBrainContext:H0,isEmbeddingAvailable:hf,generateEmbedding:qa,buildEmbeddingIndex:yf,semanticQuery:wf,cosineSimilarity:gf,_keywordQuery:pf,_extractKeywords:Ia,_chunkText:$f,parseFrontmatter:to,tokenize:Ar,_fuseResults:bf}});var Gt=J((dE,Pf)=>{var Fe=require("fs"),bt=require("path"),K0=require("os"),{atomicWrite:Nr,withFileLockSync:
|
|
193
|
+
`)}`;return hs={queryKey:o,result:u,ts:Date.now()},u}xf.exports={getBrainDir:gs,listDocuments:eo,readDocument:df,writeDocument:j0,removeDocument:q0,buildIndex:Pa,getIndex:ff,query:_f,getBrainContext:H0,isEmbeddingAvailable:hf,generateEmbedding:qa,buildEmbeddingIndex:yf,semanticQuery:wf,cosineSimilarity:gf,_keywordQuery:pf,_extractKeywords:Ia,_chunkText:$f,parseFrontmatter:to,tokenize:Ar,_fuseResults:bf}});var Gt=J((dE,Pf)=>{var Fe=require("fs"),bt=require("path"),K0=require("os"),{atomicWrite:Nr,withFileLockSync:vf}=gn(),so=["user","feedback","project","reference"],G0=50;function In(){return bt.join(process.cwd(),".nex","memory")}function $s(){return bt.join(In(),"memory.json")}function kf(){return bt.join(In(),"MEMORY.md")}function Y0(){return bt.join(process.cwd(),"NEX.md")}function Sf(){return bt.join(K0.homedir(),".nex","NEX.md")}function Mr(){let t=In();Fe.existsSync(t)||Fe.mkdirSync(t,{recursive:!0})}function Ef(t){let e=bt.join(In(),t);return Fe.existsSync(e)||Fe.mkdirSync(e,{recursive:!0}),e}function oo(){let t=$s();if(!Fe.existsSync(t))return{};try{return JSON.parse(Fe.readFileSync(t,"utf-8"))}catch{return{}}}function Tf(t){Mr(),Nr($s(),JSON.stringify(t,null,2))}function Rf(){let t=$s();if(!Fe.existsSync(t))return;let e=oo(),n=Object.keys(e);if(n.length===0){try{Fe.renameSync(t,t+".bak")}catch{}return}for(let o of n){let s=e[o],r=s.value||String(s),i=o.replace(/[^a-z0-9_-]/gi,"-").toLowerCase().replace(/-+/g,"-").replace(/^-|-$/g,"");if(!i)continue;let c=Ef("project"),l=bt.join(c,`${i}.md`),u=r.split(`
|
|
194
194
|
`)[0].slice(0,100),d=`---
|
|
195
195
|
name: ${o}
|
|
196
196
|
description: ${u}
|
|
@@ -206,9 +206,9 @@ type: ${t}
|
|
|
206
206
|
---
|
|
207
207
|
|
|
208
208
|
${n}
|
|
209
|
-
`;return Nr(i,l),Pr(),{ok:!0,path:i,updated:!0}}function X0(t,e){if(!so.includes(t))return!1;let n=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase(),o=bt.join(In(),t,`${n}.md`);if(!Fe.existsSync(o))return!1;try{return Fe.unlinkSync(o),Pr(),!0}catch{return!1}}function Fa(t){let e=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(!e)return{name:"",description:"",type:"",body:t.trim()};let n=e[1],o=(e[2]||"").trim(),s=r=>{let i=n.match(new RegExp(`^${r}:\\s*(.+)$`,"m"));return i?i[1].trim():""};return{name:s("name"),description:s("description"),type:s("type"),body:o}}function Cf(){let t=[],e=In();for(let n of so){let o=bt.join(e,n);if(!Fe.existsSync(o))continue;let s;try{s=Fe.readdirSync(o).filter(r=>r.endsWith(".md"))}catch{continue}for(let r of s){let i=bt.join(o,r);try{let c=Fe.readFileSync(i,"utf-8"),l=Fa(c);t.push({type:n,name:l.name||bt.basename(r,".md"),description:l.description,filePath:i})}catch{}}}return t}function Pr(){let t=Cf(),e=["# Project Memory Index",""];for(let n of t){if(e.length>=G0+2)break;let o=`${n.type}/${bt.basename(n.filePath)}`;e.push(`- [${n.name}](${o}) \u2014 ${n.description||"(no description)"}`)}Mr(),Nr(
|
|
209
|
+
`;return Nr(i,l),Pr(),{ok:!0,path:i,updated:!0}}function X0(t,e){if(!so.includes(t))return!1;let n=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase(),o=bt.join(In(),t,`${n}.md`);if(!Fe.existsSync(o))return!1;try{return Fe.unlinkSync(o),Pr(),!0}catch{return!1}}function Fa(t){let e=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(!e)return{name:"",description:"",type:"",body:t.trim()};let n=e[1],o=(e[2]||"").trim(),s=r=>{let i=n.match(new RegExp(`^${r}:\\s*(.+)$`,"m"));return i?i[1].trim():""};return{name:s("name"),description:s("description"),type:s("type"),body:o}}function Cf(){let t=[],e=In();for(let n of so){let o=bt.join(e,n);if(!Fe.existsSync(o))continue;let s;try{s=Fe.readdirSync(o).filter(r=>r.endsWith(".md"))}catch{continue}for(let r of s){let i=bt.join(o,r);try{let c=Fe.readFileSync(i,"utf-8"),l=Fa(c);t.push({type:n,name:l.name||bt.basename(r,".md"),description:l.description,filePath:i})}catch{}}}return t}function Pr(){let t=Cf(),e=["# Project Memory Index",""];for(let n of t){if(e.length>=G0+2)break;let o=`${n.type}/${bt.basename(n.filePath)}`;e.push(`- [${n.name}](${o}) \u2014 ${n.description||"(no description)"}`)}Mr(),Nr(kf(),e.join(`
|
|
210
210
|
`)+`
|
|
211
|
-
`)}function Af(){let t=
|
|
211
|
+
`)}function Af(){let t=kf();if(!Fe.existsSync(t))return"";try{return Fe.readFileSync(t,"utf-8").trim()}catch{return""}}function J0(t,e){Mr(),vf($s(),()=>{let n=oo();n[t]={value:e,updatedAt:new Date().toISOString()},Tf(n)})}function V0(t){let e=oo();return e[t]?e[t].value:null}function Z0(t){return Mr(),vf($s(),()=>{let e=oo();return t in e?(delete e[t],Tf(e),!0):!1})}function Of(){let t=oo();return Object.entries(t).map(([e,n])=>({key:e,value:n.value,updatedAt:n.updatedAt}))}function Nf(){let t=Sf();if(!Fe.existsSync(t))return"";try{return Fe.readFileSync(t,"utf-8").trim()}catch{return""}}function Mf(){let t=Y0();if(!Fe.existsSync(t))return"";try{return Fe.readFileSync(t,"utf-8").trim()}catch{return""}}function Q0(){Rf();let t=[],e=Nf();e&&t.push(`GLOBAL INSTRUCTIONS (~/.nex/NEX.md):
|
|
212
212
|
${e}`);let n=Mf();n&&t.push(`PROJECT INSTRUCTIONS (NEX.md):
|
|
213
213
|
${n}`);let o="",s=Af();if(s)o=s;else{let f=Of();f.length>0&&(o=`PROJECT MEMORY:
|
|
214
214
|
${f.map(h=>` ${h.key}: ${h.value}`).join(`
|
|
@@ -221,30 +221,30 @@ ${f.map(h=>` ${h.key}: ${h.value}`).join(`
|
|
|
221
221
|
|
|
222
222
|
`)}Pf.exports={saveMemory:z0,deleteMemory:X0,scanMemories:Cf,rebuildIndex:Pr,loadMemoryIndex:Af,remember:J0,recall:V0,forget:Z0,listMemories:Of,loadGlobalInstructions:Nf,loadProjectInstructions:Mf,getMemoryContext:Q0,_getMemoryDir:In,_getMemoryFile:$s,_getGlobalNexMdPath:Sf,_parseMemoryFile:Fa,_migrateIfNeeded:Rf,VALID_TYPES:so}});var Ba=J((fE,qf)=>{var ro=require("fs"),Ua=require("path"),Wa=process.env.NEX_AUDIT!=="false",jn=null;function Lf(){return jn||(jn=Ua.join(process.cwd(),".nex","audit"),ro.existsSync(jn)||ro.mkdirSync(jn,{recursive:!0}),jn)}function If(){let t=new Date().toISOString().split("T")[0];return Ua.join(Lf(),`${t}.jsonl`)}function eb(t){if(Wa)try{let e={timestamp:new Date().toISOString(),tool:t.tool,args:jf(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)+`
|
|
223
223
|
`;ro.appendFileSync(If(),n,"utf-8")}catch{}}function jf(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 Df(t={}){let e=Lf(),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=Ua.join(e,`${r}.jsonl`);if(!ro.existsSync(i))continue;let c=ro.readFileSync(i,"utf-8").split(`
|
|
224
|
-
`).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 tb(t=1){let e=Df({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 nb(t){Wa=t}function sb(){return Wa}function ob(){jn=null}qf.exports={logToolExecution:eb,sanitizeArgs:jf,readAuditLog:Df,getAuditSummary:tb,setAuditEnabled:nb,isAuditEnabled:sb,getAuditLogPath:If,_reset:ob}});var Jf=J((hE,Xf)=>{var Be=require("fs").promises,Ff=require("fs"),Ce=require("path"),Oe=require("util").promisify(require("child_process").exec),Ha=require("util").promisify(require("child_process").execFile),{spawnSync:rb}=require("child_process"),Ka=require("axios"),{isForbidden:ib,isSSHForbidden:ab,isDangerous:cb,isCritical:Uf,isBashPathForbidden:lb,confirm:jt}=tt(),{showClaudeDiff:Lr,showClaudeNewFile:ub,showEditDiff:pE,confirmFileChange:io}=Bu(),{C:ae,Spinner:db,getToolSpinnerText:fb}=qe(),{isGitRepo:Ga,getCurrentBranch:Wf,getStatus:pb,getDiff:mb}=yn(),{recordChange:Ir}=nn(),{fuzzyFindText:Bf,findMostSimilar:lo}=xd(),{runDiagnostics:ao}=
|
|
224
|
+
`).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 tb(t=1){let e=Df({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 nb(t){Wa=t}function sb(){return Wa}function ob(){jn=null}qf.exports={logToolExecution:eb,sanitizeArgs:jf,readAuditLog:Df,getAuditSummary:tb,setAuditEnabled:nb,isAuditEnabled:sb,getAuditLogPath:If,_reset:ob}});var Jf=J((hE,Xf)=>{var Be=require("fs").promises,Ff=require("fs"),Ce=require("path"),Oe=require("util").promisify(require("child_process").exec),Ha=require("util").promisify(require("child_process").execFile),{spawnSync:rb}=require("child_process"),Ka=require("axios"),{isForbidden:ib,isSSHForbidden:ab,isDangerous:cb,isCritical:Uf,isBashPathForbidden:lb,confirm:jt}=tt(),{showClaudeDiff:Lr,showClaudeNewFile:ub,showEditDiff:pE,confirmFileChange:io}=Bu(),{C:ae,Spinner:db,getToolSpinnerText:fb}=qe(),{isGitRepo:Ga,getCurrentBranch:Wf,getStatus:pb,getDiff:mb}=yn(),{recordChange:Ir}=nn(),{fuzzyFindText:Bf,findMostSimilar:lo}=xd(),{runDiagnostics:ao}=kd(),{findFileInIndex:hb,getFileIndex:mE}=ka(),{resolveProfile:At,sshExec:mt,scpUpload:gb,scpDownload:$b}=ms(),{resolveDeployConfig:yb,loadDeployConfigs:wb}=Ra(),{getEditMode:Hf}=Fs(),bb=/^(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/,_b=/^ssh\s/,xb=/^ssh(?:\s+-\S+)*\s+\S+@?\S+\s+["']?[^-]/;async function _t(t){return Be.access(t).then(()=>!0).catch(()=>!1)}async function jr(t){if(!t)return{fixedPath:null,message:""};let e=t.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),n=ht(e);if(n&&await _t(n))return{fixedPath:n,message:`(auto-fixed path: ${t} \u2192 ${e})`};let o=[".js",".ts",".jsx",".tsx",".mjs",".cjs",".json"],s=Ce.extname(t);if(!s)for(let i of o){let c=ht(t+i);if(c&&await _t(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=ht(i+c);if(l&&await _t(l))return{fixedPath:l,message:`(auto-fixed: ${s} \u2192 ${c})`}}}let r=Ce.basename(t);if(r&&r.length>2)try{let i=hb(r).map(c=>ht(c));if(i.length===1)return{fixedPath:i[0],message:`(auto-fixed: found ${r} at ${Ce.relative(process.cwd(),i[0])})`};if(i.length>1&&i.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
|
|
225
225
|
${i.map(l=>Ce.relative(process.cwd(),l)).map(l=>` - ${l}`).join(`
|
|
226
|
-
`)}`}}catch{}return{fixedPath:null,message:""}}function
|
|
226
|
+
`)}`}}catch{}return{fixedPath:null,message:""}}function vb(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 Yf(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+`
|
|
227
227
|
|
|
228
228
|
`+n.join(`
|
|
229
|
-
`)}function zf(t,e,n){let o=lo(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 Kf=!1,Dn=null;function vb(){Dn&&(Dn(),Dn=null)}var za=null;function Sb(t){za=t}async function Ya(){if(!Kf){Kf=!0;try{let{stdout:t}=await Oe("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await Oe('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await Oe("git stash pop",{cwd:process.cwd(),timeout:1e4}),await Oe("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var Eb=[/\.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 ht(t){let e=Ce.isAbsolute(t)?Ce.resolve(t):Ce.resolve(process.cwd(),t);for(let n of Eb)if(n.test(e))return null;return e}var Tb=[{type:"function",function:{name:"bash",description:"Execute a bash command in the project directory. Timeout: 90s (commands that exceed this are killed). Use for: running tests, installing packages, git commands, build tools, starting servers, compiling code. AVOID using bash for: cat/head/tail (use read_file), sed/awk (use edit_file), find/ls (use glob or list_directory), grep/rg (use grep tool). Using dedicated tools is faster and produces better-formatted output. Always quote file paths containing spaces with double quotes. Check the exit code in output \u2014 non-zero means the command failed. For long-running commands (large builds, full test suites), warn the user if they may exceed 90s. Destructive or dangerous commands (rm -rf, git push, npm publish, sudo) 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. You MUST use this tool at least once on a file BEFORE calling edit_file or patch_file on it \u2014 this ensures you have the exact current content and edits will match. Auto-truncates at 350 lines for unbounded reads. For large files (>350 lines), use line_start/line_end to read specific sections. Prefer this over bash cat/head/tail \u2014 dedicated tools produce better-formatted output. Files are read with UTF-8 encoding.",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. You MUST call read_file on the target file first to see the exact content \u2014 never guess or recall from memory. COMMON FAILURE: old_text doesn't match because you guessed the content instead of reading the file first. If the edit fails with 'old_text not found', use the line number from the error message to re-read that specific region with line_start/line_end, then retry with the exact text. For multiple changes to the same file, prefer patch_file (single atomic operation).",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. Returns paths sorted by modification time. Use this to FIND files before reading them \u2014 never guess file paths, always glob first. Examples: '**/*.test.js' (all test files), 'src/**/*.ts' (all TypeScript in src), 'package.json' (find config). Prefer this over bash find/ls. When you need file contents, glob first to find the path, then read_file to read it.",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. Prefer this over bash grep/rg \u2014 this tool returns structured, formatted output. Use output_mode='files_with_matches' when you only need file paths (faster, less output). Use output_mode='content' (default) for matching lines with context. Use head_limit to cap results and avoid overwhelming output on broad searches. Use include to filter by file type (e.g. '*.js'). Supports context lines (context, before_context, after_context), offset for pagination, type filter, and multiline for cross-line patterns.",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"]}}},{type:"function",function:{name:"save_memory",description:"Save a typed memory for cross-session persistence. Use this to remember user preferences, feedback, project context, or external references.",parameters:{type:"object",properties:{type:{type:"string",enum:["user","feedback","project","reference"],description:"Memory type: user (role/prefs), feedback (approach guidance), project (ongoing work), reference (external pointers)"},name:{type:"string",description:"Short slug identifier for this memory (e.g. 'testing-preference', 'deploy-workflow')"},content:{type:"string",description:"Markdown content of the memory"},description:{type:"string",description:"One-line description for the memory index (optional, defaults to first line of content)"}},required:["type","name","content"]}}},{type:"function",function:{name:"delete_memory",description:"Delete a typed memory entry. Use this to prune outdated or incorrect memories.",parameters:{type:"object",properties:{type:{type:"string",enum:["user","feedback","project","reference"],description:"Memory type to delete from"},name:{type:"string",description:"Slug identifier of the memory to delete"}},required:["type","name"]}}}];function co(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 Gf(t,e,n={}){switch(t){case"bash":{let o=e.command,s=ib(o);if(s){let f=kb(o);return`BLOCKED: Command matches forbidden pattern: ${s}${f?`
|
|
229
|
+
`)}function zf(t,e,n){let o=lo(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 Kf=!1,Dn=null;function kb(){Dn&&(Dn(),Dn=null)}var za=null;function Sb(t){za=t}async function Ya(){if(!Kf){Kf=!0;try{let{stdout:t}=await Oe("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await Oe('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await Oe("git stash pop",{cwd:process.cwd(),timeout:1e4}),await Oe("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var Eb=[/\.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 ht(t){let e=Ce.isAbsolute(t)?Ce.resolve(t):Ce.resolve(process.cwd(),t);for(let n of Eb)if(n.test(e))return null;return e}var Tb=[{type:"function",function:{name:"bash",description:"Execute a bash command in the project directory. Timeout: 90s (commands that exceed this are killed). Use for: running tests, installing packages, git commands, build tools, starting servers, compiling code. AVOID using bash for: cat/head/tail (use read_file), sed/awk (use edit_file), find/ls (use glob or list_directory), grep/rg (use grep tool). Using dedicated tools is faster and produces better-formatted output. Always quote file paths containing spaces with double quotes. Check the exit code in output \u2014 non-zero means the command failed. For long-running commands (large builds, full test suites), warn the user if they may exceed 90s. Destructive or dangerous commands (rm -rf, git push, npm publish, sudo) 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. You MUST use this tool at least once on a file BEFORE calling edit_file or patch_file on it \u2014 this ensures you have the exact current content and edits will match. Auto-truncates at 350 lines for unbounded reads. For large files (>350 lines), use line_start/line_end to read specific sections. Prefer this over bash cat/head/tail \u2014 dedicated tools produce better-formatted output. Files are read with UTF-8 encoding.",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. You MUST call read_file on the target file first to see the exact content \u2014 never guess or recall from memory. COMMON FAILURE: old_text doesn't match because you guessed the content instead of reading the file first. If the edit fails with 'old_text not found', use the line number from the error message to re-read that specific region with line_start/line_end, then retry with the exact text. For multiple changes to the same file, prefer patch_file (single atomic operation).",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. Returns paths sorted by modification time. Use this to FIND files before reading them \u2014 never guess file paths, always glob first. Examples: '**/*.test.js' (all test files), 'src/**/*.ts' (all TypeScript in src), 'package.json' (find config). Prefer this over bash find/ls. When you need file contents, glob first to find the path, then read_file to read it.",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. Prefer this over bash grep/rg \u2014 this tool returns structured, formatted output. Use output_mode='files_with_matches' when you only need file paths (faster, less output). Use output_mode='content' (default) for matching lines with context. Use head_limit to cap results and avoid overwhelming output on broad searches. Use include to filter by file type (e.g. '*.js'). Supports context lines (context, before_context, after_context), offset for pagination, type filter, and multiline for cross-line patterns.",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"]}}},{type:"function",function:{name:"save_memory",description:"Save a typed memory for cross-session persistence. Use this to remember user preferences, feedback, project context, or external references.",parameters:{type:"object",properties:{type:{type:"string",enum:["user","feedback","project","reference"],description:"Memory type: user (role/prefs), feedback (approach guidance), project (ongoing work), reference (external pointers)"},name:{type:"string",description:"Short slug identifier for this memory (e.g. 'testing-preference', 'deploy-workflow')"},content:{type:"string",description:"Markdown content of the memory"},description:{type:"string",description:"One-line description for the memory index (optional, defaults to first line of content)"}},required:["type","name","content"]}}},{type:"function",function:{name:"delete_memory",description:"Delete a typed memory entry. Use this to prune outdated or incorrect memories.",parameters:{type:"object",properties:{type:{type:"string",enum:["user","feedback","project","reference"],description:"Memory type to delete from"},name:{type:"string",description:"Slug identifier of the memory to delete"}},required:["type","name"]}}}];function co(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 Gf(t,e,n={}){switch(t){case"bash":{let o=e.command,s=ib(o);if(s){let f=vb(o);return`BLOCKED: Command matches forbidden pattern: ${s}${f?`
|
|
230
230
|
HINT: ${f}`:""}`}let r=lb(o);if(r)return`BLOCKED: Destructive operation on protected path: ${r}
|
|
231
231
|
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?Uf(o):cb(o)){let f=Uf(o)?"\u26D4":"\u26A0";if(!await jt(` ${f} bash: \`${o}\``,{toolName:"bash"}))return"CANCELLED: User declined to execute this command."}let c;try{c=process.cwd(),Ff.accessSync(c)}catch{c=require("os").homedir(),n.silent||console.log(`${ae.yellow} \u26A0 Working directory no longer exists \u2014 running in ${c}${ae.reset}`)}let l=_b.test(o.trim())&&!xb.test(o.trim());if(bb.test(o.trim())||l){n.silent||console.log(`${ae.dim} \u25B6 interactive: ${o}${ae.reset}`);let f=rb("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}=ns(),d=n.silent?null:new u("bash",o.substring(0,40));d&&d.start();try{let{stdout:f,stderr:m}=await Oe(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=Yf(m,o);return`EXIT ${f.code||1}
|
|
232
232
|
${h}`}}case"read_file":{let o=ht(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await _t(o)){let T=await jr(e.path);if(T.fixedPath)o=T.fixedPath,console.log(`${ae.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${Ce.relative(process.cwd(),o)}${ae.reset}`);else return`ERROR: File not found: ${e.path}${T.message?`
|
|
233
233
|
`+T.message:""}`}let r=Buffer.alloc(8192),i=await Ff.promises.open(o,"r"),{bytesRead:c}=await i.read(r,0,8192,0);await i.close();for(let T=0;T<c;T++)if(r[T]===0)return`ERROR: ${o} is a binary file (not readable as text)`;let l=await Be.readFile(o,"utf-8");if(!l&&(await Be.stat(o)).size>0)return`WARNING: ${o} is empty or unreadable`;let u=l.split(`
|
|
234
234
|
`),d=await Be.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=Ce.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`,A=`File: ${w} (${x}, ${d.size} bytes)`,E=u.slice(g,y).map((T,O)=>`${g+O+1}: ${T}`).join(`
|
|
235
|
-
`),
|
|
235
|
+
`),k=p?`
|
|
236
236
|
|
|
237
237
|
[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?`
|
|
238
238
|
[Large file (${f} lines total) \u2014 use line_start/line_end for other sections]`:"";return`${A}
|
|
239
|
-
${E}${
|
|
239
|
+
${E}${k}`}case"write_file":{await Ya();let o=ht(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let s=await _t(o),r=null;if(n.autoConfirm)s&&(r=await Be.readFile(o,"utf-8"));else if(s){r=await Be.readFile(o,"utf-8");let d=await ao(o,e.content);if(Lr(o,r,e.content,{annotations:d}),!await io("Overwrite"))return"CANCELLED: User declined to overwrite file."}else{let d=await ao(o,e.content);if(ub(o,e.content,{annotations:d}),!await io("Create"))return"CANCELLED: User declined to create file."}let i=Ce.dirname(o);await _t(i)||await Be.mkdir(i,{recursive:!0}),await Be.writeFile(o,e.content,"utf-8");let l=/[/\\]\.git[/\\]hooks[/\\]/.test(o)||o.endsWith(".sh")||e.content.startsWith("#!");l&&await Be.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 Ya();let o=ht(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await _t(o)){let d=await jr(e.path);if(d.fixedPath)o=d.fixedPath,console.log(`${ae.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${Ce.relative(process.cwd(),o)}${ae.reset}`);else return`ERROR: File not found: ${e.path}${d.message?`
|
|
240
240
|
`+d.message:""}`}let r=await Be.readFile(o,"utf-8"),i=e.old_text,c=!1,l=!1;if(!r.includes(e.old_text)){let{getActiveModelId:d,getActiveProviderName:f}=Le();if(Hf(d(),f())==="strict"){let p=lo(r,e.old_text);return p?`ERROR: old_text not found in ${o} (strict mode \u2014 exact match required)
|
|
241
241
|
Most similar text (line ${p.line}, distance ${p.distance}):
|
|
242
242
|
${p.text}`:`ERROR: old_text not found in ${o} (strict mode \u2014 exact match required)`}let h=Bf(r,e.old_text);if(h)i=h,c=!0,console.log(`${ae.dim} \u2713 fuzzy whitespace match applied${ae.reset}`);else{let p=zf(r,e.old_text,e.new_text);if(p){if(!n.autoConfirm){let A=await ao(o,p.content);if(Lr(o,r,p.content,{annotations:A}),!await io(`Apply (auto-fix, line ${p.line}, distance ${p.distance})`))return"CANCELLED: User declined to apply edit."}await Be.writeFile(o,p.content,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(o)||o.endsWith(".sh")||p.content.startsWith("#!"))&&await Be.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(`${ae.dim} \u2713 auto-fixed edit: line ${p.line}, distance ${p.distance}${ae.reset}`),`Edited: ${o} (auto-fixed, line ${p.line}, distance ${p.distance}, matched: "${x}")`}let g=lo(r,e.old_text);if(g){let x=r.split(`
|
|
243
|
-
`),A=Math.max(0,g.line-6),E=Math.min(x.length,g.line+10),
|
|
243
|
+
`),A=Math.max(0,g.line-6),E=Math.min(x.length,g.line+10),k=x.slice(A,E).map((O,P)=>`${A+P+1}: ${O}`).join(`
|
|
244
244
|
`),T=`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})
|
|
245
245
|
|
|
246
246
|
Actual file content around line ${g.line} \u2014 use this to correct old_text:
|
|
247
|
-
${
|
|
247
|
+
${k}
|
|
248
248
|
|
|
249
249
|
Fix: update old_text to match the exact lines above, then retry. If you need more context: read_file with ${T}`}let y=(e.old_text||"").trim().split(`
|
|
250
250
|
`)[0].slice(0,60),w=y?`
|
|
@@ -252,12 +252,12 @@ Recovery: grep -n "${y.replace(/"/g,'\\"')}" <file> to find the line, then re-re
|
|
|
252
252
|
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 ao(o,d);if(Lr(o,r,d,{annotations:f}),!await io(c?"Apply (fuzzy match)":"Apply"))return"CANCELLED: User declined to apply edit."}let u=r.split(i).join(e.new_text);return await Be.writeFile(o,u,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(o)||o.endsWith(".sh")||u.startsWith("#!"))&&await Be.chmod(o,493),Ir("edit_file",o,r,u),c?`Edited: ${o} (fuzzy match)`:`Edited: ${o}`}case"list_directory":{let o=ht(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await _t(o)){let u=e.path.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),d=ht(u),f=await _t(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 Be.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(Ce.join(u,h.name),d+1,f+" ")}};return await l(o,1,""),c.join(`
|
|
253
253
|
`)||"(empty)"}case"search_files":{let o=ht(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 Ha("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(`
|
|
254
254
|
`).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(`
|
|
255
|
-
`)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let s=process.cwd(),r=e.path?ht(e.path):s,i=e.pattern,c=P=>{let W=P.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"(.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");return new RegExp(`^${W}$`)},l=c(i),u=i.split("/").pop(),d=c(u),{ToolProgress:f}=ns(),m=new f("glob","Finding files...");m.start();let{getFileIndex:h,getIndexedCwd:p,refreshIndex:g,isIndexValid:y}=
|
|
255
|
+
`)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let s=process.cwd(),r=e.path?ht(e.path):s,i=e.pattern,c=P=>{let W=P.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"(.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");return new RegExp(`^${W}$`)},l=c(i),u=i.split("/").pop(),d=c(u),{ToolProgress:f}=ns(),m=new f("glob","Finding files...");m.start();let{getFileIndex:h,getIndexedCwd:p,refreshIndex:g,isIndexValid:y}=ka(),w=h(),x=p();y(r)||(await g(r),w=h());let A=w.filter(P=>l.test(P)||d.test(Ce.basename(P))).map(P=>Ce.join(r,P));if(A.length===0)return m.stop(),"(no matches)";let E=await Promise.all(A.slice(0,210).map(async P=>{try{let W=await Be.stat(P);return{path:P,mtime:W.mtimeMs}}catch{return{path:P,mtime:0}}}));E.sort((P,W)=>W.mtime-P.mtime);let k=E.map(P=>P.path),T=A.length>200,O=k.slice(0,200).join(`
|
|
256
256
|
`);return m.update({count:A.length,detail:e.pattern}),m.stop(),T?`${O}
|
|
257
257
|
|
|
258
258
|
\u26A0 Results truncated at 200. Use a more specific pattern.`:O}case"grep":{let o=e.path?ht(e.path):process.cwd();if(e.staged){let{getDiff:l}=yn(),u=await l(!0);if(!u.trim())return"(no staged changes)";let d=new Set,f=u.split(`
|
|
259
259
|
`);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}=ns(),p=new h("grep","Searching staged content...");p.start();let g=[];for(let y of d)try{let w=Ce.join(process.cwd(),y);if(await _t(w)){let x=[...m];x.push(e.pattern,w);let{stdout:A}=await Ha("grep",x,{cwd:process.cwd(),timeout:3e4,maxBuffer:2*1024*1024});if(e.output_mode==="files_with_matches"||e.output_mode==="count"){let E=A.trim().split(`
|
|
260
|
-
`).filter(
|
|
260
|
+
`).filter(k=>k.trim());g=g.concat(E)}else{let E=A.split("\0");for(let k=0;k<E.length;k+=2){let T=E[k+1];if(T){let O=T.split(`
|
|
261
261
|
`).filter(P=>P.trim());for(let P of O)g.push(`${y}:${P}`)}}}}}catch{}return p.update({count:g.length,detail:"in staged files"}),p.stop(),g.join(`
|
|
262
262
|
`).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}=ns(),c=new i("grep","Searching...");c.start();try{let{stdout:l}=await Ha("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(`
|
|
263
263
|
`).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(`
|
|
@@ -265,9 +265,9 @@ Recovery: use grep -n to locate the text, then re-read that section with line_st
|
|
|
265
265
|
`).trim()||"(no matches)"}catch(l){return c.stop(),l.code===2?`ERROR: Invalid regex pattern: ${e.pattern}`:"(no matches)"}}case"patch_file":{await Ya();let o=ht(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await _t(o)){let w=await jr(e.path);if(w.fixedPath)o=w.fixedPath,console.log(`${ae.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${Ce.relative(process.cwd(),o)}${ae.reset}`);else return`ERROR: File not found: ${e.path}${w.message?`
|
|
266
266
|
`+w.message:""}`}let r=e.patches;if(!Array.isArray(r)||r.length===0)return"ERROR: No patches provided";let i=await Be.readFile(o,"utf-8"),{getActiveModelId:c,getActiveProviderName:l}=Le(),u=Hf(c(),l()),d=[],f=!1,m=!1;for(let w=0;w<r.length;w++){let{old_text:x,new_text:A}=r[w];if(i.includes(x))d.push({old_text:x,new_text:A});else if(u==="strict"){let E=lo(i,x);return E?`ERROR: Patch ${w+1} old_text not found in ${o} (strict mode \u2014 exact match required)
|
|
267
267
|
Most similar text (line ${E.line}, distance ${E.distance}):
|
|
268
|
-
${E.text}`:`ERROR: Patch ${w+1} old_text not found in ${o} (strict mode \u2014 exact match required)`}else{let E=Bf(i,x);if(E)d.push({old_text:E,new_text:A}),f=!0;else{let
|
|
269
|
-
Most similar text (line ${
|
|
270
|
-
${
|
|
268
|
+
${E.text}`:`ERROR: Patch ${w+1} old_text not found in ${o} (strict mode \u2014 exact match required)`}else{let E=Bf(i,x);if(E)d.push({old_text:E,new_text:A}),f=!0;else{let k=lo(i,x);if(k){let T=Math.max(3,Math.ceil(x.length*.05));if(k.distance<=T)d.push({old_text:k.text,new_text:A}),m=!0;else return`ERROR: Patch ${w+1} old_text not found in ${o}
|
|
269
|
+
Most similar text (line ${k.line}, distance ${k.distance}):
|
|
270
|
+
${k.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 ao(o,h);if(Lr(o,i,h,{annotations:w}),!await io(f?"Apply patches (fuzzy match)":"Apply patches"))return"CANCELLED: User declined to apply patches."}await Be.writeFile(o,h,"utf-8");let p=/[/\\]\.git[/\\]hooks[/\\]/.test(o)||o.endsWith(".sh")||h.startsWith("#!");p&&await Be.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 Ka.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 Ka.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]
|
|
271
271
|
|
|
272
272
|
${r}`;return i.length>0&&(c+=`
|
|
273
273
|
|
|
@@ -330,7 +330,7 @@ ${m||h||"(no output)"}`;let p=/\bgrep\b/.test(s),g=h;p&&(g=g.split(`
|
|
|
330
330
|
`);w.length>y&&(g=`(${w.length-y} earlier lines omitted \u2014 showing last ${y})
|
|
331
331
|
`+w.slice(-y).join(`
|
|
332
332
|
`));let x=4,A=g.split(`
|
|
333
|
-
`),E=[],
|
|
333
|
+
`),E=[],k=0;for(;k<A.length;){let T=k+1;for(;T<A.length&&A[T]===A[k];)T++;let O=T-k;if(E.push(A[k]),O>x)E.push(`... (${O-1} identical lines omitted)`);else for(let P=1;P<O;P++)E.push(A[k]);k=T}return E.join(`
|
|
334
334
|
`)||"(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=At(e.server)}catch(i){return`ERROR: ${i.message}`}let s=o.user?`${o.user}@${o.host}`:o.host;if(console.log(`
|
|
335
335
|
${ae.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${s}:${e.remote_path}${ae.reset}`),!await jt(" Upload to remote server?"))return"CANCELLED: User declined upload.";try{return await gb(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=At(e.server)}catch(s){return`ERROR: ${s.message}`}try{return await $b(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}.
|
|
336
336
|
${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=At(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(`
|
|
@@ -382,35 +382,35 @@ Health check FAILED (exit ${p}): ${g}`,(o==="git"?"git pull OK":"rsync OK")+i+c+
|
|
|
382
382
|
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}
|
|
383
383
|
${i}${c}${l}`.trim()}case"deployment_status":{let o=wb(),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=At(c.server||i),d=(await mt(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 mt(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 mt(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:
|
|
384
384
|
${r.join(`
|
|
385
|
-
`)}`}case"frontend_recon":{let o=process.cwd(),s=(e.type||"").toLowerCase(),r=[],i=async(E,
|
|
386
|
-
`),W=P.slice(0,
|
|
387
|
-
`);return P.length>
|
|
388
|
-
... (${P.length-
|
|
389
|
-
`).filter(Boolean)}catch{return[]}},d=async(E,
|
|
385
|
+
`)}`}case"frontend_recon":{let o=process.cwd(),s=(e.type||"").toLowerCase(),r=[],i=async(E,k=120)=>{try{let T=Ce.isAbsolute(E)?E:Ce.join(o,E),P=(await Be.readFile(T,"utf8")).split(`
|
|
386
|
+
`),W=P.slice(0,k).join(`
|
|
387
|
+
`);return P.length>k?W+`
|
|
388
|
+
... (${P.length-k} more lines \u2014 use read_file for full content)`:W}catch{return null}},l=["node_modules",".git","dist","build","vendor",".next","__pycache__","venv",".venv"].map(E=>`-not -path "*/${E}/*"`).join(" "),u=async E=>{try{let{stdout:k}=await Oe(`find "${o}" -type f -name "${E}" ${l} 2>/dev/null | head -10`,{timeout:8e3});return k.trim().split(`
|
|
389
|
+
`).filter(Boolean)}catch{return[]}},d=async(E,k)=>{try{let{stdout:T}=await Oe(`grep -rl "${E}" "${o}" --include="${k}" --exclude-dir=node_modules --exclude-dir=.git --exclude-dir=dist --exclude-dir=build 2>/dev/null | head -5`,{timeout:8e3});return T.trim().split(`
|
|
390
390
|
`).filter(Boolean)}catch{return[]}};r.push(`## STEP 1: Design Tokens
|
|
391
391
|
`);let f=[...await u("tailwind.config.js"),...await u("tailwind.config.ts"),...await u("tailwind.config.mjs")];if(f.length>0){let E=await i(f[0],80);E&&r.push(`### Tailwind config (${Ce.relative(o,f[0])})
|
|
392
392
|
\`\`\`js
|
|
393
393
|
${E}
|
|
394
|
-
\`\`\``)}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 E of m){let
|
|
394
|
+
\`\`\``)}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 E of m){let k=await u(E);for(let T of k){let O=await i(T,100);if(O&&O.includes(":root")){r.push(`### CSS Variables (${Ce.relative(o,T)})
|
|
395
395
|
\`\`\`css
|
|
396
396
|
${O}
|
|
397
|
-
\`\`\``),h=!0;break}}if(h)break}if(!h){let E=await d(":root","*.css");if(E.length>0){let
|
|
397
|
+
\`\`\``),h=!0;break}}if(h)break}if(!h){let E=await d(":root","*.css");if(E.length>0){let k=await i(E[0],100);k&&r.push(`### CSS Variables (${Ce.relative(o,E[0])})
|
|
398
398
|
\`\`\`css
|
|
399
|
-
${
|
|
399
|
+
${k}
|
|
400
400
|
\`\`\``),h=!0}}h||r.push("(no CSS custom properties / :root found)"),r.push(`
|
|
401
401
|
## STEP 2: Main Layout / Index Page
|
|
402
|
-
`);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 E of p){let
|
|
402
|
+
`);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 E of p){let k=await u(E);if(k.length>0){let T=await i(k[0],150);if(T){r.push(`### Main layout: ${Ce.relative(o,k[0])}
|
|
403
403
|
\`\`\`html
|
|
404
404
|
${T}
|
|
405
405
|
\`\`\``),g=!0;break}}}g||r.push("(no main layout/index file found \u2014 try read_file on your root template manually)"),r.push(`
|
|
406
406
|
## STEP 3: Reference Component (same type)
|
|
407
407
|
`);let y=[];if(s){for(let E of["*.html","*.vue","*.jsx","*.tsx"])if(y=await d(s,E),y.length>0)break}if(y.length===0)try{let{stdout:E}=await Oe(`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=E.trim().split(`
|
|
408
|
-
`).filter(Boolean)}catch{y=[]}if(y.length>0){let E=y[0],
|
|
408
|
+
`).filter(Boolean)}catch{y=[]}if(y.length>0){let E=y[0],k=await i(E,150);k?r.push(`### Reference: ${Ce.relative(o,E)}
|
|
409
409
|
\`\`\`html
|
|
410
|
-
${
|
|
410
|
+
${k}
|
|
411
411
|
\`\`\``):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(`
|
|
412
412
|
## STEP 4: Framework Stack
|
|
413
|
-
`);let w=[],x=await i(Ce.join(o,"package.json"),999);if(x){if((x.includes('"react"')||x.includes("'react'"))&&w.push("React"),x.includes('"vue"')||x.includes("'vue'")){let
|
|
413
|
+
`);let w=[],x=await i(Ce.join(o,"package.json"),999);if(x){if((x.includes('"react"')||x.includes("'react'"))&&w.push("React"),x.includes('"vue"')||x.includes("'vue'")){let k=x.match(/"vue":\s*"[\^~]?(\d+)/);w.push(k?`Vue.js v${k[1]}`:"Vue.js")}let E=x.match(/"alpinejs":\s*"[\^~]?(\d+)/);E&&w.push(`Alpine.js v${E[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 _t(Ce.join(o,"manage.py"))||(await i(Ce.join(o,"requirements.txt"),50)||"").includes("Django"))&&w.push("Django (server-rendered templates)"),!w.some(E=>E.includes("Alpine"))){let E=await d("alpinejs","*.html");if(E.length>0){let T=(await i(E[0],30)||"").match(/alpinejs[@/]v?(\d)/);w.push(T?`Alpine.js v${T[1]} (via CDN \u2014 \u26A0 v2 vs v3 API differs!)`:"Alpine.js (via CDN \u2014 check version!)")}}return w.some(E=>E.includes("HTMX"))||(await d("htmx","*.html")).length>0&&w.push("HTMX (via CDN)"),w.length>0?(r.push(w.map(E=>`- ${E}`).join(`
|
|
414
414
|
`)),r.push(`
|
|
415
415
|
\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(`
|
|
416
416
|
---
|
|
@@ -459,7 +459,7 @@ ${d}`:d||"(empty log)"}case"find_large":{let l=e.path||"/",u=e.limit||20,d=e.min
|
|
|
459
459
|
${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}
|
|
460
460
|
${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}
|
|
461
461
|
${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}
|
|
462
|
-
${d}`:d||"(no log entries)"}default:return`ERROR: Unknown sysadmin action: ${e.action}`}}case"save_memory":{let{saveMemory:o}=Gt(),s=o(e.type,e.name,e.content,e.description);return s.ok?s.updated===!1?`Memory unchanged (duplicate): ${e.type}/${e.name}`:`Memory saved: ${e.type}/${e.name} \u2192 ${s.path}`:`ERROR: ${s.error}`}case"delete_memory":{let{deleteMemory:o}=Gt();return o(e.type,e.name)?`Memory deleted: ${e.type}/${e.name}`:`Memory not found: ${e.type}/${e.name}`}default:{let{executePluginTool:o}=mr(),s=await o(t,e,n);return s!==null?s:`ERROR: Unknown tool: ${t}`}}}async function Rb(t,e,n={}){let{emit:o}=mr(),{logToolExecution:s}=Ba(),r=Date.now(),i=n.silent?null:fb(t,e);if(!i){let l=await Gf(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 db(i);c.start();try{let l=await Gf(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}}Xf.exports={TOOL_DEFINITIONS:Tb,executeTool:Rb,resolvePath:ht,autoFixPath:jr,autoFixEdit:zf,enrichBashError:Yf,cancelPendingAskUser:
|
|
462
|
+
${d}`:d||"(no log entries)"}default:return`ERROR: Unknown sysadmin action: ${e.action}`}}case"save_memory":{let{saveMemory:o}=Gt(),s=o(e.type,e.name,e.content,e.description);return s.ok?s.updated===!1?`Memory unchanged (duplicate): ${e.type}/${e.name}`:`Memory saved: ${e.type}/${e.name} \u2192 ${s.path}`:`ERROR: ${s.error}`}case"delete_memory":{let{deleteMemory:o}=Gt();return o(e.type,e.name)?`Memory deleted: ${e.type}/${e.name}`:`Memory not found: ${e.type}/${e.name}`}default:{let{executePluginTool:o}=mr(),s=await o(t,e,n);return s!==null?s:`ERROR: Unknown tool: ${t}`}}}async function Rb(t,e,n={}){let{emit:o}=mr(),{logToolExecution:s}=Ba(),r=Date.now(),i=n.silent?null:fb(t,e);if(!i){let l=await Gf(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 db(i);c.start();try{let l=await Gf(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}}Xf.exports={TOOL_DEFINITIONS:Tb,executeTool:Rb,resolvePath:ht,autoFixPath:jr,autoFixEdit:zf,enrichBashError:Yf,cancelPendingAskUser:kb,setAskUserHandler:Sb,fileExists:_t}});var It=J((gE,Vf)=>{Vf.exports=Jf()});var Ja=J(($E,Zf)=>{var{loadServerProfiles:Dr}=ms(),Xa={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 Cb(){let t=Dr();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&&Xa[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 Xa[s])n.push(`- ${i}`)}}return n.join(`
|
|
463
463
|
`)}function Ab(t){let e=Dr();return Object.values(e).some(n=>n.os&&n.os.startsWith(t))}function Ob(){return Object.keys(Dr())}function Nb(){let t=require("fs"),n=require("path").join(process.cwd(),"NEX.md"),o="";try{o=t.readFileSync(n,"utf-8")}catch{}let s=Dr(),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(`
|
|
464
464
|
`),d=r.map(m=>s[m].log_path).filter(Boolean),f=d.length>0?`
|
|
465
465
|
- Server log paths: ${d.join(", ")}`:"";return`# Deployment Context (Auto-detected)
|
|
@@ -503,13 +503,13 @@ ${c}`),l&&l.length>0){let u=l.map(d=>` ${d.file}`).join(`
|
|
|
503
503
|
`);s.push(`MERGE CONFLICTS (resolve before editing these files):
|
|
504
504
|
${u}`)}try{let u=Pb();u&&s.push(u)}catch{}return s.join(`
|
|
505
505
|
|
|
506
|
-
`)}async function Bb(t){let e=at.join(t,"package.json"),n="";if(await bn(()=>Dt.access(e).then(()=>!0).catch(()=>!1)))try{let i=await Dt.readFile(e,"utf-8"),c=JSON.parse(i);n=`${c.name||"?"} v${c.version||"?"}`}catch{}let[s,r]=await Promise.all([bn(async()=>{let{stdout:i}=await qr("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),ep()]);if(r&&r.length>0){console.log(`${ys.red} \u26A0 ${r.length} unresolved merge conflict(s):${ys.reset}`);for(let i of r)console.log(`${ys.red} ${i.file}${ys.reset}`);console.log(`${ys.yellow} \u2192 Resolve conflicts before starting tasks${ys.reset}`)}console.log()}tp.exports={gatherProjectContext:Wb,printContext:Bb,generateFileTree:Db,_clearContextCache:()=>{Va.clear(),ws.clear(),Fr=null}}});var Ft=J((wE,op)=>{var qt=require("fs"),Wr=require("path"),{atomicWrite:Hb}=gn();function fo(){return Wr.join(process.cwd(),".nex","sessions")}function Za(){let t=fo();qt.existsSync(t)||qt.mkdirSync(t,{recursive:!0})}function Qa(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return Wr.join(fo(),`${e}.json`)}function ec(t,e,n={}){Za();let o=Qa(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 Hb(o,JSON.stringify(s,null,2)),{path:o,name:t}}function np(t){let e=Qa(t);if(!qt.existsSync(e))return null;try{return JSON.parse(qt.readFileSync(e,"utf-8"))}catch{return null}}function sp(){Za();let t=fo(),e=qt.readdirSync(t).filter(o=>o.endsWith(".json")),n=[];for(let o of e)try{let s=JSON.parse(qt.readFileSync(Wr.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 Kb(t){let e=Qa(t);return qt.existsSync(e)?(qt.unlinkSync(e),!0):!1}function Gb(){let t=sp();return t.length===0?null:np(t[0].name)}var qn=null,an=null,uo=null;function Yb(t,e={}){t.length!==0&&(qn&&clearTimeout(qn),an=t,uo=e||{},qn=setTimeout(()=>{an&&an.length>0&&ec("_autosave",an,uo),qn=null,an=null,uo=null},5e3))}function zb(){qn&&(clearTimeout(qn),qn=null),an&&an.length>0&&(ec("_autosave",an,uo),an=null,uo=null)}function Xb(){Za();let t=fo(),e=qt.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=Wr.join(t,r);try{let c=qt.statSync(i);new Date(c.mtime)<o&&(qt.unlinkSync(i),s++)}catch{}}return s}op.exports={saveSession:ec,loadSession:np,listSessions:sp,deleteSession:Kb,getLastSession:Gb,autoSave:Yb,flushAutoSave:zb,clearOldSessions:Xb,_getSessionsDir:fo}});var Br=J((bE,fp)=>{"use strict";var po=require("fs"),rp=require("path");function ip(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,id:s.id||null})}),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,id:s.id||null})}))}),e}function Jb(t){let e=new Set;return t.forEach(n=>{n.role==="tool"&&typeof n.content=="string"&&n.content.startsWith("BLOCKED:")&&n.tool_call_id&&e.add(n.tool_call_id),n.role==="user"&&Array.isArray(n.content)&&n.content.forEach(o=>{o&&o.type==="tool_result"&&o.tool_use_id&&typeof o.content=="string"&&o.content.startsWith("BLOCKED:")&&e.add(o.tool_use_id)})}),e}function ap(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 cp(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 lp(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 up(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 dp(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=ip(t),s=ap(t),r=o.length,i=Jb(t),c=o.filter(S=>!S.id||!i.has(S.id));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 u=o.find(S=>{let L=S.input?.command||S.input?.cmd||"";return/\bsed\s+-n\b/.test(L)});if(u){let S=(u.input?.command||u.input?.cmd||"").slice(0,80);s.some(R=>R.content.includes("BLOCKED: sed -n is forbidden")||R.content.includes("BLOCKED: sed -n"))?(e-=.25,n.push(`sed -n attempted but blocked by agent guard: ${S}`)):(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 L=S.input?.command||S.input?.cmd||"",R=S.input?.pattern||"",M=`${L} ${R}`;return/(?:-[CAB]|--context|--after|--before)\s*[=\s]?([2-9][1-9]|\d{3,})/.test(M)||/grep.*-[CAB]\s*([2-9][1-9]|\d{3,})/.test(M)})&&(e-=1,n.push("grep used with >20 context lines (context flood risk)"));let f=t.some(S=>S.role==="assistant"),m=cp(t),p=lp(t,3).some(S=>S.length>100&&!/^[^.!]{0,40}\?$/.test(S));if(f&&!p&&(m.length<80||/^[^.!]{0,40}\?$/.test(m))){e-=2;let S=m.length>0?`"${m.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 L=typeof S.content=="string"?S.content:Array.isArray(S.content)?S.content.map(R=>typeof R=="string"?R:R.text||"").join(""):"";return/\[auto-compressed|context compacted|force-compressed/.test(L)})&&(e-=.5,n.push("Auto-compress triggered (context flood indicator)"));let w=up(c),x=0,A="";for(let[S,L]of w)L>x&&(x=L,A=S);if(x>=3){let[S]=A.split("|");e-=1,n.push(`Same tool call repeated ${x}\xD7 (tool: ${S})`)}let E=!1,v=t.findIndex(S=>S.role==="user"&&typeof S.content=="string"&&S.content.includes("[SYSTEM STOP]")&&S.content.includes('"valid":true'));v>=0&&o.filter(L=>L.index>v).length>0&&(E=!0),E&&(e-=1.5,n.push('Stop-trigger ignored: tool result contained "valid":true but session continued with more tool calls'));let T=o.filter(S=>S.name==="ssh_exec");if(T.length>=8){let S=0,L=1;for(let R=1;R<T.length;R++)T[R].index<=T[R-1].index+2?L++:(S=Math.max(S,L),L=1);S=Math.max(S,L),S>=8&&(e-=.5,n.push(`SSH reconnect storm: ${S} consecutive SSH calls`))}f&&T.length>0&&/\b(Könntest du|könntest du|Bitte (bereitstellen|kopier)|kannst du mir .* bereitstellen|could you (provide|share|paste)|please (provide|share|run .* and paste)|I (cannot|can't) access the server|nicht (auf den Server )?zugreifen|SSH .* (nicht verfügbar|unavailable|temporarily unavailable))\b/i.test(m)&&(e-=2,n.push("Surrender: model asked user to manually provide server output instead of gathering it"));let O=new Map;for(let S of c)if(S.name==="read_file"&&S.input?.path){let L=S.input.path;O.has(L)||O.set(L,{count:0,ranges:[]});let R=O.get(L);if(R.count++,S.input.line_start!=null){let M=S.input.line_start||1,D=S.input.line_end||M+350;R.ranges.push([M,D])}}function P(S,L,R){for(let[M,D]of R){let q=Math.max(S,M),Z=Math.min(L,D);if(Z>q){let ce=Z-q,se=L-S||1;if(ce/se>=.7)return!0}}return!1}let W=0,k="";for(let[S,L]of O){if(L.count<3)continue;if(L.ranges.length===L.count){let D=!1,q=[];for(let[Z,ce]of L.ranges){if(q.length>0&&P(Z,ce,q)){D=!0;break}q.push([Z,ce])}if(!D)continue}if(L.count-L.ranges.length<=1&&L.ranges.length>=1){let D=!1,q=[];for(let[Z,ce]of L.ranges){if(q.length>0&&P(Z,ce,q)){D=!0;break}q.push([Z,ce])}if(!D)continue}L.count>W&&(W=L.count,k=S)}if(W>=3){e-=1;let S=k.split("/").slice(-2).join("/");n.push(`read_file loop: "${S}" read ${W}\xD7 (file already in context)`)}let X=0,be="";for(let[S,L]of O){if(L.ranges.length<4)continue;let R=[],M=!1;for(let[D,q]of L.ranges){if(R.length>0&&P(D,q,R)){M=!0;break}R.push([D,q])}!M&&L.ranges.length>X&&(X=L.ranges.length,be=S)}if(X>=4){e-=.5;let S=be.split("/").slice(-2).join("/");n.push(`File-scroll pattern: "${S}" read in ${X} sequential sections \u2014 use grep instead`)}let ye=new Map;for(let S of c)if(S.name==="grep"&&S.input?.path&&S.input?.pattern){let L=S.input.path;ye.has(L)||ye.set(L,new Set),ye.get(L).add(S.input.pattern)}let we=0,ue="";for(let[S,L]of ye)S.split("/").pop().includes(".")&&L.size>we&&(we=L.size,ue=S);if(we>=3){e-=.75;let S=ue.split("/").slice(-2).join("/");n.push(`grep flood on single file: "${S}" searched ${we}\xD7 with different patterns (file already in context)`)}{let S=new Set,L=new Set,R=/^(test_|demo_|temp_|tmp_|scratch_)/;for(let D of o){if(D.name==="write_file"&&D.input?.path){let q=D.input.path.split("/").pop(),Z=D.input.path.includes("/tests/");R.test(q)&&!Z&&S.add(D.input.path)}if((D.name==="bash"||D.name==="ssh_exec")&&D.input?.command){let q=D.input.command.match(/\brm\s+(?:-\w+\s+)?(\S+)/g);if(q)for(let Z of q){let ce=Z.split(/\s+/),se=ce[ce.length-1];for(let me of S)(me.endsWith(se)||se.endsWith(me.split("/").pop()))&&L.add(me)}}}let M=L.size;if(M>=1){let D=Math.min(M*.25,.5);e-=D;let q=[...L].map(Z=>Z.split("/").pop()).join(", ");n.push(`Temp file write-then-delete: ${q} \u2014 write inline logic or use tests/ instead`)}}let fe=s.filter(S=>S.content.startsWith("EXIT")).length;fe>=10?(e-=1,n.push(`Bash exit-error storm: ${fe} tool results started with EXIT (repeated failing commands)`)):fe>=5&&(e-=.5,n.push(`Repeated bash errors: ${fe} tool results with non-zero exit code`));for(let S of t){if(S.role!=="assistant")continue;let L="";if(typeof S.content=="string"?L=S.content:Array.isArray(S.content)&&(L=S.content.filter(se=>se&&(se.type==="text"||typeof se=="string")).map(se=>typeof se=="string"?se:se.text||"").join("")),L.length<=5e3)continue;let R=L.split(/(?<=\. )/).filter(se=>se.trim().length>0);if(R.length<6)continue;let M=new Map;for(let se=0;se<=R.length-3;se++){let me=R.slice(se,se+3).join("").trim();me.length>30&&M.set(me,(M.get(me)||0)+1)}let D=0,q="";for(let[se,me]of M)me>D&&(D=me,q=se);if(D<3)continue;let ce=q.length*D/L.length;if(ce>=.4||D>=10){e-=1.5,n.push(`llm output loop: assistant message repeated content detected (${D}\xD7 same paragraph, ${Math.round(ce*100)}% repeated)`);break}}{let S=new Set(["read_file","list_directory","search_files","glob","grep"]),L=t.some(M=>Array.isArray(M.tool_calls)?M.tool_calls.some(D=>S.has(D.function?.name)):Array.isArray(M.content)?M.content.some(D=>D.type==="tool_use"&&S.has(D.name)):!1);t.some(M=>M.role==="assistant"&&typeof M.content=="string"&&(M.content.includes("## Steps")||M.content.includes("/plan approve")))&&!L&&(e-=2,n.push("plan written without reading any files \u2014 LLM invented data structures from training knowledge (hallucination risk)"))}let pe=s.filter(S=>S.content.startsWith("BLOCKED:")&&!S.content.includes("BLOCKED: sed -n")&&!S.content.includes("SSH paused")&&!S.content.includes("SSH temporarily paused"));if(pe.length>0){let S=Math.min(pe.length*.5,1.5);e-=S,n.push(`${pe.length} tool call${pe.length===1?"":"s"} blocked (agent attempted denied actions)`)}let de=t.filter(S=>{let L=typeof S.content=="string"?S.content:"";return/\[SYSTEM WARNING\] Context wiped \d+×/.test(L)}).length;if(de>0){let S=Math.min(de*1,2);e-=S,n.push(`Super-nuclear context wipe fired ${de}\xD7 (context collapse \u2014 task too large or read loops)`)}{let S=!1,L=!1,R=!1;for(let D of o){if(D.name!=="bash")continue;let q=(D.input?.command||D.input?.cmd||"").trim();!(/cat\s*>/.test(q)||/<</.test(q))&&/\bcat\s+\S/.test(q)&&(S=!0),/^\s*ls(\s|$)/.test(q)&&!/npm|yarn|pnpm|make|git\b/.test(q)&&(L=!0),/\bfind\s+\S/.test(q)&&!/git\b|npm\b|-exec\b/.test(q)&&(R=!0)}let M=[S,L,R].filter(Boolean).length;if(M>0){let D=Math.min(M*.25,.75);e-=D;let q=[];S&&q.push("cat (use read_file)"),L&&q.push("ls (use list_directory)"),R&&q.push("find (use glob)"),n.push(`bash used instead of dedicated tool: ${q.join(", ")}`)}}{let S=o.some(q=>(q.name==="write_file"||q.name==="Write")&&q.input?.path&&(q.input.path.endsWith("requirements.txt")||q.input.path.endsWith("Pipfile")||q.input.path.endsWith("pyproject.toml"))),L=o.some(q=>(q.name==="write_file"||q.name==="Write")&&q.input?.path&&q.input.path.endsWith("package.json")),R=o.filter(q=>(q.name==="bash"||q.name==="Bash")&&q.input?.command).map(q=>q.input.command),M=R.some(q=>/pip\s+install|python\s+-m\s+venv/.test(q)),D=R.some(q=>/npm\s+install/.test(q));S&&!M?(e-=1,n.push("wrote requirements.txt but never ran pip install \u2014 environment not bootstrapped")):L&&!D&&o.some(Z=>(Z.name==="write_file"||Z.name==="Write")&&Z.input?.path&&/(\/src\/|index\.js|App\.js|main\.js)/.test(Z.input.path))&&(e-=.75,n.push("created new React/Node project but never ran npm install \u2014 project is not runnable"))}e=Math.max(0,Math.min(10,e)),e=Math.round(e*10)/10;let Ee=e>=9?"A":e>=8?"B":e>=7?"C":e>=6?"D":"F",Me=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:Ee,issues:n,summary:Me}}function Vb(t){try{let{loadSession:e}=Ft(),n=e(t);return n?dp(n.messages||[]):null}catch{return null}}function Zb(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=`
|
|
506
|
+
`)}async function Bb(t){let e=at.join(t,"package.json"),n="";if(await bn(()=>Dt.access(e).then(()=>!0).catch(()=>!1)))try{let i=await Dt.readFile(e,"utf-8"),c=JSON.parse(i);n=`${c.name||"?"} v${c.version||"?"}`}catch{}let[s,r]=await Promise.all([bn(async()=>{let{stdout:i}=await qr("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),ep()]);if(r&&r.length>0){console.log(`${ys.red} \u26A0 ${r.length} unresolved merge conflict(s):${ys.reset}`);for(let i of r)console.log(`${ys.red} ${i.file}${ys.reset}`);console.log(`${ys.yellow} \u2192 Resolve conflicts before starting tasks${ys.reset}`)}console.log()}tp.exports={gatherProjectContext:Wb,printContext:Bb,generateFileTree:Db,_clearContextCache:()=>{Va.clear(),ws.clear(),Fr=null}}});var Ft=J((wE,op)=>{var qt=require("fs"),Wr=require("path"),{atomicWrite:Hb}=gn();function fo(){return Wr.join(process.cwd(),".nex","sessions")}function Za(){let t=fo();qt.existsSync(t)||qt.mkdirSync(t,{recursive:!0})}function Qa(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return Wr.join(fo(),`${e}.json`)}function ec(t,e,n={}){Za();let o=Qa(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 Hb(o,JSON.stringify(s,null,2)),{path:o,name:t}}function np(t){let e=Qa(t);if(!qt.existsSync(e))return null;try{return JSON.parse(qt.readFileSync(e,"utf-8"))}catch{return null}}function sp(){Za();let t=fo(),e=qt.readdirSync(t).filter(o=>o.endsWith(".json")),n=[];for(let o of e)try{let s=JSON.parse(qt.readFileSync(Wr.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 Kb(t){let e=Qa(t);return qt.existsSync(e)?(qt.unlinkSync(e),!0):!1}function Gb(){let t=sp();return t.length===0?null:np(t[0].name)}var qn=null,an=null,uo=null;function Yb(t,e={}){t.length!==0&&(qn&&clearTimeout(qn),an=t,uo=e||{},qn=setTimeout(()=>{an&&an.length>0&&ec("_autosave",an,uo),qn=null,an=null,uo=null},5e3))}function zb(){qn&&(clearTimeout(qn),qn=null),an&&an.length>0&&(ec("_autosave",an,uo),an=null,uo=null)}function Xb(){Za();let t=fo(),e=qt.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=Wr.join(t,r);try{let c=qt.statSync(i);new Date(c.mtime)<o&&(qt.unlinkSync(i),s++)}catch{}}return s}op.exports={saveSession:ec,loadSession:np,listSessions:sp,deleteSession:Kb,getLastSession:Gb,autoSave:Yb,flushAutoSave:zb,clearOldSessions:Xb,_getSessionsDir:fo}});var Br=J((bE,fp)=>{"use strict";var po=require("fs"),rp=require("path");function ip(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,id:s.id||null})}),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,id:s.id||null})}))}),e}function Jb(t){let e=new Set;return t.forEach(n=>{n.role==="tool"&&typeof n.content=="string"&&n.content.startsWith("BLOCKED:")&&n.tool_call_id&&e.add(n.tool_call_id),n.role==="user"&&Array.isArray(n.content)&&n.content.forEach(o=>{o&&o.type==="tool_result"&&o.tool_use_id&&typeof o.content=="string"&&o.content.startsWith("BLOCKED:")&&e.add(o.tool_use_id)})}),e}function ap(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 cp(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 lp(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 up(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 dp(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=ip(t),s=ap(t),r=o.length,i=Jb(t),c=o.filter(S=>!S.id||!i.has(S.id));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 u=o.find(S=>{let L=S.input?.command||S.input?.cmd||"";return/\bsed\s+-n\b/.test(L)});if(u){let S=(u.input?.command||u.input?.cmd||"").slice(0,80);s.some(R=>R.content.includes("BLOCKED: sed -n is forbidden")||R.content.includes("BLOCKED: sed -n"))?(e-=.25,n.push(`sed -n attempted but blocked by agent guard: ${S}`)):(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 L=S.input?.command||S.input?.cmd||"",R=S.input?.pattern||"",M=`${L} ${R}`;return/(?:-[CAB]|--context|--after|--before)\s*[=\s]?([2-9][1-9]|\d{3,})/.test(M)||/grep.*-[CAB]\s*([2-9][1-9]|\d{3,})/.test(M)})&&(e-=1,n.push("grep used with >20 context lines (context flood risk)"));let f=t.some(S=>S.role==="assistant"),m=cp(t),p=lp(t,3).some(S=>S.length>100&&!/^[^.!]{0,40}\?$/.test(S));if(f&&!p&&(m.length<80||/^[^.!]{0,40}\?$/.test(m))){e-=2;let S=m.length>0?`"${m.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 L=typeof S.content=="string"?S.content:Array.isArray(S.content)?S.content.map(R=>typeof R=="string"?R:R.text||"").join(""):"";return/\[auto-compressed|context compacted|force-compressed/.test(L)})&&(e-=.5,n.push("Auto-compress triggered (context flood indicator)"));let w=up(c),x=0,A="";for(let[S,L]of w)L>x&&(x=L,A=S);if(x>=3){let[S]=A.split("|");e-=1,n.push(`Same tool call repeated ${x}\xD7 (tool: ${S})`)}let E=!1,k=t.findIndex(S=>S.role==="user"&&typeof S.content=="string"&&S.content.includes("[SYSTEM STOP]")&&S.content.includes('"valid":true'));k>=0&&o.filter(L=>L.index>k).length>0&&(E=!0),E&&(e-=1.5,n.push('Stop-trigger ignored: tool result contained "valid":true but session continued with more tool calls'));let T=o.filter(S=>S.name==="ssh_exec");if(T.length>=8){let S=0,L=1;for(let R=1;R<T.length;R++)T[R].index<=T[R-1].index+2?L++:(S=Math.max(S,L),L=1);S=Math.max(S,L),S>=8&&(e-=.5,n.push(`SSH reconnect storm: ${S} consecutive SSH calls`))}f&&T.length>0&&/\b(Könntest du|könntest du|Bitte (bereitstellen|kopier)|kannst du mir .* bereitstellen|could you (provide|share|paste)|please (provide|share|run .* and paste)|I (cannot|can't) access the server|nicht (auf den Server )?zugreifen|SSH .* (nicht verfügbar|unavailable|temporarily unavailable))\b/i.test(m)&&(e-=2,n.push("Surrender: model asked user to manually provide server output instead of gathering it"));let O=new Map;for(let S of c)if(S.name==="read_file"&&S.input?.path){let L=S.input.path;O.has(L)||O.set(L,{count:0,ranges:[]});let R=O.get(L);if(R.count++,S.input.line_start!=null){let M=S.input.line_start||1,D=S.input.line_end||M+350;R.ranges.push([M,D])}}function P(S,L,R){for(let[M,D]of R){let q=Math.max(S,M),Z=Math.min(L,D);if(Z>q){let ce=Z-q,se=L-S||1;if(ce/se>=.7)return!0}}return!1}let W=0,v="";for(let[S,L]of O){if(L.count<3)continue;if(L.ranges.length===L.count){let D=!1,q=[];for(let[Z,ce]of L.ranges){if(q.length>0&&P(Z,ce,q)){D=!0;break}q.push([Z,ce])}if(!D)continue}if(L.count-L.ranges.length<=1&&L.ranges.length>=1){let D=!1,q=[];for(let[Z,ce]of L.ranges){if(q.length>0&&P(Z,ce,q)){D=!0;break}q.push([Z,ce])}if(!D)continue}L.count>W&&(W=L.count,v=S)}if(W>=3){e-=1;let S=v.split("/").slice(-2).join("/");n.push(`read_file loop: "${S}" read ${W}\xD7 (file already in context)`)}let X=0,be="";for(let[S,L]of O){if(L.ranges.length<4)continue;let R=[],M=!1;for(let[D,q]of L.ranges){if(R.length>0&&P(D,q,R)){M=!0;break}R.push([D,q])}!M&&L.ranges.length>X&&(X=L.ranges.length,be=S)}if(X>=4){e-=.5;let S=be.split("/").slice(-2).join("/");n.push(`File-scroll pattern: "${S}" read in ${X} sequential sections \u2014 use grep instead`)}let ye=new Map;for(let S of c)if(S.name==="grep"&&S.input?.path&&S.input?.pattern){let L=S.input.path;ye.has(L)||ye.set(L,new Set),ye.get(L).add(S.input.pattern)}let we=0,ue="";for(let[S,L]of ye)S.split("/").pop().includes(".")&&L.size>we&&(we=L.size,ue=S);if(we>=3){e-=.75;let S=ue.split("/").slice(-2).join("/");n.push(`grep flood on single file: "${S}" searched ${we}\xD7 with different patterns (file already in context)`)}{let S=new Set,L=new Set,R=/^(test_|demo_|temp_|tmp_|scratch_)/;for(let D of o){if(D.name==="write_file"&&D.input?.path){let q=D.input.path.split("/").pop(),Z=D.input.path.includes("/tests/");R.test(q)&&!Z&&S.add(D.input.path)}if((D.name==="bash"||D.name==="ssh_exec")&&D.input?.command){let q=D.input.command.match(/\brm\s+(?:-\w+\s+)?(\S+)/g);if(q)for(let Z of q){let ce=Z.split(/\s+/),se=ce[ce.length-1];for(let me of S)(me.endsWith(se)||se.endsWith(me.split("/").pop()))&&L.add(me)}}}let M=L.size;if(M>=1){let D=Math.min(M*.25,.5);e-=D;let q=[...L].map(Z=>Z.split("/").pop()).join(", ");n.push(`Temp file write-then-delete: ${q} \u2014 write inline logic or use tests/ instead`)}}let fe=s.filter(S=>S.content.startsWith("EXIT")).length;fe>=10?(e-=1,n.push(`Bash exit-error storm: ${fe} tool results started with EXIT (repeated failing commands)`)):fe>=5&&(e-=.5,n.push(`Repeated bash errors: ${fe} tool results with non-zero exit code`));for(let S of t){if(S.role!=="assistant")continue;let L="";if(typeof S.content=="string"?L=S.content:Array.isArray(S.content)&&(L=S.content.filter(se=>se&&(se.type==="text"||typeof se=="string")).map(se=>typeof se=="string"?se:se.text||"").join("")),L.length<=5e3)continue;let R=L.split(/(?<=\. )/).filter(se=>se.trim().length>0);if(R.length<6)continue;let M=new Map;for(let se=0;se<=R.length-3;se++){let me=R.slice(se,se+3).join("").trim();me.length>30&&M.set(me,(M.get(me)||0)+1)}let D=0,q="";for(let[se,me]of M)me>D&&(D=me,q=se);if(D<3)continue;let ce=q.length*D/L.length;if(ce>=.4||D>=10){e-=1.5,n.push(`llm output loop: assistant message repeated content detected (${D}\xD7 same paragraph, ${Math.round(ce*100)}% repeated)`);break}}{let S=new Set(["read_file","list_directory","search_files","glob","grep"]),L=t.some(M=>Array.isArray(M.tool_calls)?M.tool_calls.some(D=>S.has(D.function?.name)):Array.isArray(M.content)?M.content.some(D=>D.type==="tool_use"&&S.has(D.name)):!1);t.some(M=>M.role==="assistant"&&typeof M.content=="string"&&(M.content.includes("## Steps")||M.content.includes("/plan approve")))&&!L&&(e-=2,n.push("plan written without reading any files \u2014 LLM invented data structures from training knowledge (hallucination risk)"))}let pe=s.filter(S=>S.content.startsWith("BLOCKED:")&&!S.content.includes("BLOCKED: sed -n")&&!S.content.includes("SSH paused")&&!S.content.includes("SSH temporarily paused"));if(pe.length>0){let S=Math.min(pe.length*.5,1.5);e-=S,n.push(`${pe.length} tool call${pe.length===1?"":"s"} blocked (agent attempted denied actions)`)}let de=t.filter(S=>{let L=typeof S.content=="string"?S.content:"";return/\[SYSTEM WARNING\] Context wiped \d+×/.test(L)}).length;if(de>0){let S=Math.min(de*1,2);e-=S,n.push(`Super-nuclear context wipe fired ${de}\xD7 (context collapse \u2014 task too large or read loops)`)}{let S=!1,L=!1,R=!1;for(let D of o){if(D.name!=="bash")continue;let q=(D.input?.command||D.input?.cmd||"").trim();!(/cat\s*>/.test(q)||/<</.test(q))&&/\bcat\s+\S/.test(q)&&(S=!0),/^\s*ls(\s|$)/.test(q)&&!/npm|yarn|pnpm|make|git\b/.test(q)&&(L=!0),/\bfind\s+\S/.test(q)&&!/git\b|npm\b|-exec\b/.test(q)&&(R=!0)}let M=[S,L,R].filter(Boolean).length;if(M>0){let D=Math.min(M*.25,.75);e-=D;let q=[];S&&q.push("cat (use read_file)"),L&&q.push("ls (use list_directory)"),R&&q.push("find (use glob)"),n.push(`bash used instead of dedicated tool: ${q.join(", ")}`)}}{let S=o.some(q=>(q.name==="write_file"||q.name==="Write")&&q.input?.path&&(q.input.path.endsWith("requirements.txt")||q.input.path.endsWith("Pipfile")||q.input.path.endsWith("pyproject.toml"))),L=o.some(q=>(q.name==="write_file"||q.name==="Write")&&q.input?.path&&q.input.path.endsWith("package.json")),R=o.filter(q=>(q.name==="bash"||q.name==="Bash")&&q.input?.command).map(q=>q.input.command),M=R.some(q=>/pip\s+install|python\s+-m\s+venv/.test(q)),D=R.some(q=>/npm\s+install/.test(q));S&&!M?(e-=1,n.push("wrote requirements.txt but never ran pip install \u2014 environment not bootstrapped")):L&&!D&&o.some(Z=>(Z.name==="write_file"||Z.name==="Write")&&Z.input?.path&&/(\/src\/|index\.js|App\.js|main\.js)/.test(Z.input.path))&&(e-=.75,n.push("created new React/Node project but never ran npm install \u2014 project is not runnable"))}e=Math.max(0,Math.min(10,e)),e=Math.round(e*10)/10;let Ee=e>=9?"A":e>=8?"B":e>=7?"C":e>=6?"D":"F",Me=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:Ee,issues:n,summary:Me}}function Vb(t){try{let{loadSession:e}=Ft(),n=e(t);return n?dp(n.messages||[]):null}catch{return null}}function Zb(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=`
|
|
507
507
|
${i} Session score: ${c}${m}${h}${n}/10 (${o})${c}`;if(r&&(p+=` ${i}${r}${c}`),s.length>0)if(n>=7){let g=s.map(y=>y.replace(/:\s+\d+.*$/,"").replace(/\s*\(.*?\)/,"")).join(" \xB7 ");p+=`
|
|
508
508
|
${i}${g}${c}`}else for(let g of s)p+=`
|
|
509
|
-
${u}\u26A0${c} ${i}${g}${c}`;return p}function Qb(t,e={}){try{let n=rp.join(process.cwd(),".nex");po.existsSync(n)||po.mkdirSync(n,{recursive:!0});let o=rp.join(n,"benchmark-history.json"),s=[];if(po.existsSync(o))try{s=JSON.parse(po.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)),po.writeFileSync(o,JSON.stringify(s,null,2))}catch{}}fp.exports={scoreMessages:dp,scoreSession:Vb,formatScore:Zb,appendScoreHistory:Qb,_extractToolCalls:ip,_extractToolResults:ap,_getLastAssistantText:cp,_getLastNAssistantTexts:lp,_countDuplicateToolCalls:up}});var ho=J((xE,$p)=>{var xt=require("fs"),bs=require("path"),{C:_E}=qe(),{atomicWrite:e_,withFileLockSync:t_}=gn(),Hr={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"},_s={...Hr};function pp(){let t=bs.join(process.cwd(),".nex","config.json");if(xt.existsSync(t))try{let e=JSON.parse(xt.readFileSync(t,"utf-8"));e.permissions&&(_s={...Hr,...e.permissions})}catch{}}function n_(){let t=bs.join(process.cwd(),".nex"),e=bs.join(t,"config.json");xt.existsSync(t)||xt.mkdirSync(t,{recursive:!0}),t_(e,()=>{let n={};if(xt.existsSync(e))try{n=JSON.parse(xt.readFileSync(e,"utf-8"))}catch{n={}}n.permissions=_s,e_(e,JSON.stringify(n,null,2))})}function mp(t){return _s[t]||"ask"}function s_(t,e){return["allow","ask","deny"].includes(e)?(_s[t]=e,!0):!1}function o_(t){return mp(t)}function r_(){return Object.entries(_s).map(([t,e])=>({tool:t,mode:e}))}function i_(){_s={...Hr}}var mo={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 hp(){let t=bs.join(process.cwd(),".nex","config.json");try{return xt.existsSync(t)&&JSON.parse(xt.readFileSync(t,"utf-8")).teamPermissions||null}catch{return null}}function a_(t){let e=bs.join(process.cwd(),".nex"),n=bs.join(e,"config.json");xt.existsSync(e)||xt.mkdirSync(e,{recursive:!0});let o={};try{xt.existsSync(n)&&(o=JSON.parse(xt.readFileSync(n,"utf-8")))}catch{o={}}o.teamPermissions=t,xt.writeFileSync(n,JSON.stringify(o,null,2),"utf-8")}function gp(){let t=hp();if(!t)return mo.admin;let e=t.role||"admin",n=mo[e]||mo.admin;return{...n,...t.overrides,blockedTools:[...n.blockedTools||[],...t.overrides?.blockedTools||[]]}}function c_(t){let e=gp();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 l_(){return Object.entries(mo).map(([t,e])=>({name:t,description:e.description,toolCount:e.allowedTools?`${e.allowedTools.length} allowed`:"all allowed",blockedCount:e.blockedTools.length}))}pp();$p.exports={getPermission:mp,setPermission:s_,checkPermission:o_,listPermissions:r_,loadPermissions:pp,savePermissions:n_,resetPermissions:i_,DEFAULT_PERMISSIONS:Hr,PERMISSION_PRESETS:mo,loadPresetConfig:hp,savePresetConfig:a_,getEffectivePreset:gp,isToolAllowed:c_,listPresets:l_}});var Yt=J((
|
|
509
|
+
${u}\u26A0${c} ${i}${g}${c}`;return p}function Qb(t,e={}){try{let n=rp.join(process.cwd(),".nex");po.existsSync(n)||po.mkdirSync(n,{recursive:!0});let o=rp.join(n,"benchmark-history.json"),s=[];if(po.existsSync(o))try{s=JSON.parse(po.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)),po.writeFileSync(o,JSON.stringify(s,null,2))}catch{}}fp.exports={scoreMessages:dp,scoreSession:Vb,formatScore:Zb,appendScoreHistory:Qb,_extractToolCalls:ip,_extractToolResults:ap,_getLastAssistantText:cp,_getLastNAssistantTexts:lp,_countDuplicateToolCalls:up}});var ho=J((xE,$p)=>{var xt=require("fs"),bs=require("path"),{C:_E}=qe(),{atomicWrite:e_,withFileLockSync:t_}=gn(),Hr={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"},_s={...Hr};function pp(){let t=bs.join(process.cwd(),".nex","config.json");if(xt.existsSync(t))try{let e=JSON.parse(xt.readFileSync(t,"utf-8"));e.permissions&&(_s={...Hr,...e.permissions})}catch{}}function n_(){let t=bs.join(process.cwd(),".nex"),e=bs.join(t,"config.json");xt.existsSync(t)||xt.mkdirSync(t,{recursive:!0}),t_(e,()=>{let n={};if(xt.existsSync(e))try{n=JSON.parse(xt.readFileSync(e,"utf-8"))}catch{n={}}n.permissions=_s,e_(e,JSON.stringify(n,null,2))})}function mp(t){return _s[t]||"ask"}function s_(t,e){return["allow","ask","deny"].includes(e)?(_s[t]=e,!0):!1}function o_(t){return mp(t)}function r_(){return Object.entries(_s).map(([t,e])=>({tool:t,mode:e}))}function i_(){_s={...Hr}}var mo={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 hp(){let t=bs.join(process.cwd(),".nex","config.json");try{return xt.existsSync(t)&&JSON.parse(xt.readFileSync(t,"utf-8")).teamPermissions||null}catch{return null}}function a_(t){let e=bs.join(process.cwd(),".nex"),n=bs.join(e,"config.json");xt.existsSync(e)||xt.mkdirSync(e,{recursive:!0});let o={};try{xt.existsSync(n)&&(o=JSON.parse(xt.readFileSync(n,"utf-8")))}catch{o={}}o.teamPermissions=t,xt.writeFileSync(n,JSON.stringify(o,null,2),"utf-8")}function gp(){let t=hp();if(!t)return mo.admin;let e=t.role||"admin",n=mo[e]||mo.admin;return{...n,...t.overrides,blockedTools:[...n.blockedTools||[],...t.overrides?.blockedTools||[]]}}function c_(t){let e=gp();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 l_(){return Object.entries(mo).map(([t,e])=>({name:t,description:e.description,toolCount:e.allowedTools?`${e.allowedTools.length} allowed`:"all allowed",blockedCount:e.blockedTools.length}))}pp();$p.exports={getPermission:mp,setPermission:s_,checkPermission:o_,listPermissions:r_,loadPermissions:pp,savePermissions:n_,resetPermissions:i_,DEFAULT_PERMISSIONS:Hr,PERMISSION_PRESETS:mo,loadPresetConfig:hp,savePresetConfig:a_,getEffectivePreset:gp,isToolAllowed:c_,listPresets:l_}});var Yt=J((kE,xp)=>{var Un=require("fs"),Kr=require("path"),vE=require("readline"),{C:Re}=qe(),Se=null,nc=!1,sc=null,yp=new Set(["read_file","list_directory","search_files","glob","grep","web_search","web_fetch","git_status","git_diff","git_log","git_show"]);function Gr(){return Kr.join(process.cwd(),".nex","plans")}function wp(){let t=Gr();Un.existsSync(t)||Un.mkdirSync(t,{recursive:!0})}function u_(t,e=[]){return Se={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()},Se}function d_(){return Se}function f_(t){nc=t}function p_(){return nc}function m_(){return!Se||Se.status!=="draft"?!1:(Se.status="approved",Se.updatedAt=new Date().toISOString(),!0)}function h_(){return!Se||Se.status!=="approved"?!1:(Se.status="executing",!0)}function tc(t,e){return!Se||t<0||t>=Se.steps.length?!1:(Se.steps[t].status=e,Se.updatedAt=new Date().toISOString(),Se.steps.every(n=>n.status==="done"||n.status==="skipped")&&(Se.status="completed"),!0)}function g_(t){if(!t)return`${Re.dim}No active plan${Re.reset}`;let e={draft:`${Re.yellow}DRAFT${Re.reset}`,approved:`${Re.green}APPROVED${Re.reset}`,executing:`${Re.blue}EXECUTING${Re.reset}`,completed:`${Re.green}COMPLETED${Re.reset}`},n=[];n.push(`
|
|
510
510
|
${Re.bold}${Re.cyan}Plan: ${t.task}${Re.reset}`),n.push(`${Re.dim}Status: ${e[t.status]||t.status}${Re.reset}
|
|
511
511
|
`);for(let o=0;o<t.steps.length;o++){let s=t.steps[o],r;switch(s.status){case"done":r=`${Re.green}\u2713${Re.reset}`;break;case"in_progress":r=`${Re.blue}\u2192${Re.reset}`;break;case"skipped":r=`${Re.dim}\u25CB${Re.reset}`;break;default:r=`${Re.dim} ${Re.reset}`}n.push(` ${r} ${Re.bold}Step ${o+1}:${Re.reset} ${s.description}`),s.files.length>0&&n.push(` ${Re.dim}Files: ${s.files.join(", ")}${Re.reset}`)}return n.push(""),n.join(`
|
|
512
|
-
`)}function $_(t){if(t||(t=Se),!t)return null;wp();let e=Kr.join(Gr(),`${t.name}.json`);return Un.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function y_(t){let e=Kr.join(Gr(),`${t}.json`);if(!Un.existsSync(e))return null;try{let n=JSON.parse(Un.readFileSync(e,"utf-8"));return Se=n,n}catch{return null}}function w_(){wp();let t=Gr(),e=Un.readdirSync(t).filter(o=>o.endsWith(".json")),n=[];for(let o of e)try{let s=JSON.parse(Un.readFileSync(Kr.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 b_(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 __(t){sc=t}function x_(){return sc}function
|
|
512
|
+
`)}function $_(t){if(t||(t=Se),!t)return null;wp();let e=Kr.join(Gr(),`${t.name}.json`);return Un.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function y_(t){let e=Kr.join(Gr(),`${t}.json`);if(!Un.existsSync(e))return null;try{let n=JSON.parse(Un.readFileSync(e,"utf-8"));return Se=n,n}catch{return null}}function w_(){wp();let t=Gr(),e=Un.readdirSync(t).filter(o=>o.endsWith(".json")),n=[];for(let o of e)try{let s=JSON.parse(Un.readFileSync(Kr.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 b_(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 __(t){sc=t}function x_(){return sc}function v_(){Se=null,nc=!1,sc=null,T_()}function k_(){return`
|
|
513
513
|
PLAN MODE ACTIVE: You are in analysis-only mode. You MUST NOT execute any changes.
|
|
514
514
|
|
|
515
515
|
# Allowed Tools (read-only)
|
|
@@ -557,14 +557,14 @@ Bullet list of potential issues and mitigations.
|
|
|
557
557
|
- Order steps by dependency (later steps may depend on earlier ones).
|
|
558
558
|
- After presenting the plan, tell the user to type \`/plan approve\` to proceed.
|
|
559
559
|
- Do NOT make any file changes \u2014 your role is analysis and planning only.
|
|
560
|
-
- 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 Fn=0;function S_(){!Se||Se.status!=="executing"||(Fn>0&&tc(Fn-1,"done"),Fn<Se.steps.length&&(tc(Fn,"in_progress"),Fn++))}function E_(){if(!Se||Se.status!=="executing"||Se.steps.length===0)return null;let t=Math.min(Fn,Se.steps.length),e=Se.steps.length,n=Math.max(0,t-1),o=Se.steps[n]?.description||"";return{current:t,total:e,description:o}}function T_(){Fn=0}var bp=["interactive","semi-auto","autonomous"],_p="interactive";function R_(t){return bp.includes(t)?(_p=t,!0):!1}function C_(){return _p}xp.exports={createPlan:u_,getActivePlan:d_,setPlanMode:f_,isPlanMode:p_,approvePlan:m_,startExecution:h_,updateStep:tc,formatPlan:g_,savePlan:$_,loadPlan:y_,listPlans:w_,clearPlan:
|
|
561
|
-
`),n=[],o=!1,s="";for(let r of e){let i=
|
|
562
|
-
`)}function Wn(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function Bn(t){return t?t.replace(/`([^`]+)`/g,`${C.cyan}$1${C.reset}`).replace(/\*\*([^*]+)\*\*/g,`${C.bold}$1${C.reset}`).replace(/\*([^*]+)\*/g,`${C.dim}$1${C.reset}`).replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${C.cyan}$1${C.reset} ${C.dim}($2)${C.reset}`):""}function rc(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?
|
|
560
|
+
- 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 Fn=0;function S_(){!Se||Se.status!=="executing"||(Fn>0&&tc(Fn-1,"done"),Fn<Se.steps.length&&(tc(Fn,"in_progress"),Fn++))}function E_(){if(!Se||Se.status!=="executing"||Se.steps.length===0)return null;let t=Math.min(Fn,Se.steps.length),e=Se.steps.length,n=Math.max(0,t-1),o=Se.steps[n]?.description||"";return{current:t,total:e,description:o}}function T_(){Fn=0}var bp=["interactive","semi-auto","autonomous"],_p="interactive";function R_(t){return bp.includes(t)?(_p=t,!0):!1}function C_(){return _p}xp.exports={createPlan:u_,getActivePlan:d_,setPlanMode:f_,isPlanMode:p_,approvePlan:m_,startExecution:h_,updateStep:tc,formatPlan:g_,savePlan:$_,loadPlan:y_,listPlans:w_,clearPlan:v_,getPlanModePrompt:k_,setPlanContent:__,getPlanContent:x_,extractStepsFromText:b_,advancePlanStep:S_,getPlanStepInfo:E_,PLAN_MODE_ALLOWED_TOOLS:yp,setAutonomyLevel:R_,getAutonomyLevel:C_,AUTONOMY_LEVELS:bp}});var Mp=J((SE,Np)=>{var{C}=qe();function vp(){return Math.max(10,(process.stdout.columns||80)-2)}function A_(t){if(!t)return"";let e=t.split(`
|
|
561
|
+
`),n=[],o=!1,s="";for(let r of e){let i=vp();if(r.trim().startsWith("```")){if(o)n.push(`${C.dim}${"\u2500".repeat(40)}${C.reset}`),o=!1,s="";else{o=!0,s=r.trim().substring(3).trim();let c=s?` ${s} `:"";n.push(`${C.dim}${"\u2500".repeat(3)}${c}${"\u2500".repeat(Math.max(0,37-c.length))}${C.reset}`)}continue}if(o){n.push(` ${rc(r,s)}`);continue}if(r.startsWith("### ")){n.push(`${C.bold}${C.cyan} ${Wn(r.substring(4))}${C.reset}`);continue}if(r.startsWith("## ")){n.push(`${C.bold}${C.cyan} ${Wn(r.substring(3))}${C.reset}`);continue}if(r.startsWith("# ")){n.push(`${C.bold}${C.cyan}${Wn(r.substring(2))}${C.reset}`);continue}if(/^\s*[-*]\s/.test(r)){let c=r.match(/^(\s*)/)[1],l=r.replace(/^\s*[-*]\s/,""),u=`${c}${C.cyan}\u2022${C.reset} ${Bn(l)}`;n.push(Hn(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}${C.cyan}${u}.${C.reset} ${Bn(d)}`,m=l+" ".repeat(u.length+2);n.push(Hn(f,i,m));continue}}n.push(Hn(Bn(r),i))}return n.join(`
|
|
562
|
+
`)}function Wn(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function Bn(t){return t?t.replace(/`([^`]+)`/g,`${C.cyan}$1${C.reset}`).replace(/\*\*([^*]+)\*\*/g,`${C.bold}$1${C.reset}`).replace(/\*([^*]+)\*/g,`${C.dim}$1${C.reset}`).replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${C.cyan}$1${C.reset} ${C.dim}($2)${C.reset}`):""}function rc(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?kp(t):e==="bash"||e==="sh"||e==="shell"||e==="zsh"?Sp(t):e==="json"||e==="jsonc"?Ep(t):e==="python"||e==="py"?Tp(t):e==="go"||e==="golang"?Rp(t):e==="rust"||e==="rs"?Cp(t):e==="css"||e==="scss"||e==="less"?Ap(t):e==="html"||e==="xml"||e==="svg"||e==="htm"?Op(t):t:""}function kp(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,`${C.yellow}$1${C.reset}`),r=r.replace(e,`${C.magenta}$1${C.reset}`),r=r.replace(n,`${C.green}$&${C.reset}`),r=r.replace(o,`${C.dim}$1${C.reset}`),r}function Sp(t){let e=/^(\s*)([\w-]+)/,n=/(--?\w[\w-]*)/g,o=/(["'])(?:(?=(\\?))\2.)*?\1/g,s=/(#.*$)/,r=t;return r=r.replace(n,`${C.cyan}$1${C.reset}`),r=r.replace(e,`$1${C.green}$2${C.reset}`),r=r.replace(o,`${C.yellow}$&${C.reset}`),r=r.replace(s,`${C.dim}$1${C.reset}`),r}function Ep(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,`${C.cyan}$1${C.reset}:`),r=r.replace(n,`: ${C.green}$1${C.reset}`),r=r.replace(o,`: ${C.yellow}$1${C.reset}`),r=r.replace(s,`: ${C.magenta}$1${C.reset}`),r}function Tp(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,`${C.yellow}$1${C.reset}`),i=i.replace(e,`${C.magenta}$1${C.reset}`),i=i.replace(r,`${C.cyan}$1${C.reset}`),i=i.replace(n,`${C.green}$&${C.reset}`),i=i.replace(o,`${C.dim}$1${C.reset}`),i}function Rp(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,`${C.yellow}$1${C.reset}`),i=i.replace(n,`${C.cyan}$1${C.reset}`),i=i.replace(e,`${C.magenta}$1${C.reset}`),i=i.replace(o,`${C.green}$&${C.reset}`),i=i.replace(s,`${C.dim}$1${C.reset}`),i}function Cp(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,`${C.yellow}$1${C.reset}`),c=c.replace(n,`${C.cyan}$1${C.reset}`),c=c.replace(e,`${C.magenta}$1${C.reset}`),c=c.replace(i,`${C.yellow}$1${C.reset}`),c=c.replace(o,`${C.green}$&${C.reset}`),c=c.replace(s,`${C.dim}$1${C.reset}`),c}function Ap(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,`${C.yellow}$1${C.reset}`),c=c.replace(s,`${C.yellow}$1${C.reset}`),c=c.replace(e,`$1${C.cyan}$2${C.reset}:`),c=c.replace(o,`$1${C.magenta}$&${C.reset}`),c=c.replace(r,`${C.dim}$1${C.reset}`),c}function Op(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,`${C.dim}$1${C.reset}`),i=i.replace(o,`${C.green}$&${C.reset}`),i=i.replace(e,`<${C.magenta}$1${C.reset}`),i=i.replace(n,` ${C.cyan}$1${C.reset}=`),i=i.replace(r,`${C.yellow}$1${C.reset}`),i}function Hn(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)+`
|
|
563
563
|
`+n,c=r+1,i=c,s=n.length,r=-1;continue}s>e&&r===-1&&(o+=t.slice(c,i)+`
|
|
564
564
|
`+n,c=i,s=n.length+1),i++}return o+=t.slice(c),o}function O_(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)=>` ${C.bold}${i.padEnd(n[c])}${C.reset} `).join("\u2502"),r=[];r.push(`${C.dim}\u250C${o.replace(/┼/g,"\u252C")}\u2510${C.reset}`),r.push(`${C.dim}\u2502${C.reset}${s}${C.dim}\u2502${C.reset}`),r.push(`${C.dim}\u251C${o}\u2524${C.reset}`);for(let i of e){let c=t.map((l,u)=>` ${(i[u]||"").padEnd(n[u])} `).join(`${C.dim}\u2502${C.reset}`);r.push(`${C.dim}\u2502${C.reset}${c}${C.dim}\u2502${C.reset}`)}return r.push(`${C.dim}\u2514${o.replace(/┼/g,"\u2534")}\u2518${C.reset}`),r.join(`
|
|
565
565
|
`)}function N_(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?C.green:s>50?C.yellow:C.cyan;return` ${t} ${c}${"\u2588".repeat(r)}${C.dim}${"\u2591".repeat(i)}${C.reset} ${s}% (${e}/${n})`}var oc=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(`
|
|
566
566
|
`))!==-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(`${C.dim}${"\u2500".repeat(40)}${C.reset}
|
|
567
|
-
`),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){let n=
|
|
567
|
+
`),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){let n=vp();if(e.trim().startsWith("```")){if(this.inCodeBlock)this._safeWrite(`${C.dim}${"\u2500".repeat(40)}${C.reset}
|
|
568
568
|
`),this.inCodeBlock=!1,this.codeBlockLang="";else{this.inCodeBlock=!0,this.codeBlockLang=e.trim().substring(3).trim();let s=this.codeBlockLang?` ${this.codeBlockLang} `:"";this._safeWrite(`${C.dim}${"\u2500".repeat(3)}${s}${"\u2500".repeat(Math.max(0,37-s.length))}${C.reset}
|
|
569
569
|
`)}return}if(this.inCodeBlock){this._safeWrite(` ${rc(e,this.codeBlockLang)}
|
|
570
570
|
`);return}if(e.startsWith("### ")){this._safeWrite(`${C.bold}${C.cyan} ${Wn(e.substring(4))}${C.reset}
|
|
@@ -573,7 +573,7 @@ Bullet list of potential issues and mitigations.
|
|
|
573
573
|
`);return}if(/^\s*[-*]\s/.test(e)){let s=e.match(/^(\s*)/)[1],r=e.replace(/^\s*[-*]\s/,""),i=`${s}${C.cyan}\u2022${C.reset} ${Bn(r)}`,c=Hn(i,n,s+" ");this._safeWrite(`${c}
|
|
574
574
|
`);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}${C.cyan}${i}.${C.reset} ${Bn(c)}`,u=r+" ".repeat(i.length+2),d=Hn(l,n,u);this._safeWrite(`${d}
|
|
575
575
|
`);return}}let o=Hn(Bn(e),n);this._safeWrite(`${o}
|
|
576
|
-
`)}};Np.exports={renderMarkdown:A_,renderInline:Bn,stripHeadingMarkers:Wn,highlightCode:rc,highlightJS:
|
|
576
|
+
`)}};Np.exports={renderMarkdown:A_,renderInline:Bn,stripHeadingMarkers:Wn,highlightCode:rc,highlightJS:kp,highlightBash:Sp,highlightJSON:Ep,highlightPython:Tp,highlightGo:Rp,highlightRust:Cp,highlightCSS:Ap,highlightHTML:Op,renderTable:O_,renderProgress:N_,wrapAnsi:Hn,StreamRenderer:oc}});var cc=J((EE,jp)=>{var{execSync:M_}=require("child_process"),ic=require("path"),go=require("fs"),ac=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function Pp(){return ic.join(process.cwd(),".nex","hooks")}function P_(){return ic.join(process.cwd(),".nex","config.json")}function Lp(){let t=P_();if(!go.existsSync(t))return{};try{return JSON.parse(go.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function Yr(t){if(!ac.includes(t))return[];let e=[],n=Pp(),o=ic.join(n,t);go.existsSync(o)&&e.push(o);let s=Lp();if(s[t]){let r=Array.isArray(s[t])?s[t]:[s[t]];e.push(...r)}return e}function Ip(t,e={},n=3e4){try{return{success:!0,output:M_(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 L_(t,e={}){let n=Yr(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=Ip(r,o);if(s.push({command:r,...i}),!i.success&&t.startsWith("pre-"))break}return s}function I_(t){return Yr(t).length>0}function j_(){let t=[];for(let e of ac){let n=Yr(e);n.length>0&&t.push({event:e,commands:n})}return t}function D_(){let t=Pp();return go.existsSync(t)||go.mkdirSync(t,{recursive:!0}),t}jp.exports={HOOK_EVENTS:ac,loadHookConfig:Lp,getHooksForEvent:Yr,executeHook:Ip,runHooks:L_,hasHooks:I_,listHooks:j_,initHooksDir:D_}});var Fp=J((TE,qp)=>{var lc={"devstral-2":{staleWarn:3e4,staleAbort:9e4,investigationCap:12,postEditCap:10},"devstral-small":{staleWarn:2e4,staleAbort:6e4,investigationCap:10,postEditCap:8},"qwen3-coder":{staleWarn:6e4,staleAbort:18e4,investigationCap:15,postEditCap:12},"kimi-k2":{staleWarn:45e3,staleAbort:12e4,investigationCap:15,postEditCap:12}},Dp={staleWarn:6e4,staleAbort:12e4,investigationCap:12,postEditCap:10};function q_(t){let e=(t||"").toLowerCase(),n=null,o=0;for(let r of Object.keys(lc))e.startsWith(r)&&r.length>o&&(n=r,o=r.length);let s=n?{...lc[n]}:{...Dp};for(let[r,i]of[["NEX_STALE_WARN_MS","staleWarn"],["NEX_STALE_ABORT_MS","staleAbort"]])if(process.env[r]){let c=parseInt(process.env[r],10);Number.isInteger(c)&&c>=1e3&&c<=3e5&&(s[i]=c)}return s}qp.exports={getModelProfile:q_,PROFILES:lc,DEFAULTS:Dp}});var xs=J((RE,Hp)=>{"use strict";var F_=require("os"),Up=require("path"),$o=require("fs"),yo=Up.join(F_.homedir(),".nex-code","model-routing.json"),zr={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}},Wp=["agentic","frontend","sysadmin","data","coding"];function U_(t){if(!t||t.length<8)return null;for(let e of Wp){let n=zr[e];if(!n.pattern||n.pattern.test(t))return n}return zr.coding}function Bp(){try{if($o.existsSync(yo))return JSON.parse($o.readFileSync(yo,"utf-8"))}catch{}return{}}function W_(t){let e=zr[t];return e?.envVar&&process.env[e.envVar]?process.env[e.envVar]:Bp()[t]||null}function B_(t){let e=Up.dirname(yo);$o.existsSync(e)||$o.mkdirSync(e,{recursive:!0}),$o.writeFileSync(yo,JSON.stringify(t,null,2))}Hp.exports={CATEGORIES:zr,DETECTION_ORDER:Wp,detectCategory:U_,getModelForCategory:W_,saveRoutingConfig:B_,loadRoutingConfig:Bp,ROUTING_CONFIG_PATH:yo}});var wo=J((OE,sm)=>{"use strict";var{callWithRetry:Gp,runSubAgent:H_,clearAllLocks:K_}=Cr(),{parseModelSpec:Yp,getActiveProviderName:CE,getActiveModelId:AE}=Le(),{detectCategory:G_,getModelForCategory:Kp}=xs(),{MultiProgress:Y_,C:le}=qe(),zp=parseInt(process.env.NEX_MAX_PARALLEL||"4",10),Xr=parseInt(process.env.NEX_MAX_SUBTASKS||"8",10),Xp="devstral-2:123b",Jp="kimi-k2.5",Vp=`You are a task decomposition engine. Given a complex user request, split it into independent, atomic sub-tasks.
|
|
577
577
|
|
|
578
578
|
RULES:
|
|
579
579
|
- Output ONLY a JSON array, no markdown fences, no explanation.
|
|
@@ -610,8 +610,8 @@ Tools: ${(d.toolsUsed||[]).join(", ")||"none"}`}).join(`
|
|
|
610
610
|
|
|
611
611
|
`),r=[{role:"system",content:Zp.replace("{prompt}",e).replace("{results}",o)},{role:"user",content:"Synthesize the sub-agent results above."}],i={};if(n){let d=Yp(n);d.provider&&(i.provider=d.provider),d.model&&(i.model=d.model)}let l=(await Gp(r,[],i)).content||"",u=uc(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 X_(t,e={}){let n=e.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL||Jp,o=e.workerModel||Xp,s=e.maxParallel||zp,r=e.maxSubTasks||Xr,i=e.onProgress||(()=>{}),c={input:0,output:0};console.log(`
|
|
612
612
|
${le.bold}Orchestrator${le.reset} ${le.dim}model: ${n} | workers: ${o} | max parallel: ${s}${le.reset}
|
|
613
|
-
`),i("decomposing"),console.log(`${le.dim}Phase 1: Decomposing prompt into sub-tasks...${le.reset}`);let l;try{l=await tm(t,n,{maxSubTasks:r})}catch(
|
|
614
|
-
`);let u=Date.now(),d=em(s),f={findings:[],_lock:!1},m=l.map(
|
|
613
|
+
`),i("decomposing"),console.log(`${le.dim}Phase 1: Decomposing prompt into sub-tasks...${le.reset}`);let l;try{l=await tm(t,n,{maxSubTasks:r})}catch(v){return console.log(`${le.red}Decompose failed: ${v.message}${le.reset}`),{results:[],synthesis:{summary:`Decompose failed: ${v.message}`,conflicts:[],commitMessage:"",filesChanged:[]},totalTokens:c}}if(l.length===0)return console.log(`${le.yellow}No sub-tasks generated. Prompt may be too simple for orchestration.${le.reset}`),{results:[],synthesis:{summary:"No sub-tasks generated.",conflicts:[],commitMessage:"",filesChanged:[]},totalTokens:c};console.log(`${le.green}Decomposed into ${l.length} sub-tasks:${le.reset}`);for(let v of l){console.log(` ${le.dim}${v.id}:${le.reset} ${v.task}`);let X=v.scope.filter(Boolean);X.length>0&&console.log(` ${le.dim}scope: ${X.join(", ")}${le.reset}`)}console.log(""),i("executing"),console.log(`${le.dim}Phase 2: Running ${l.length} sub-agents (max ${s} parallel)...${le.reset}
|
|
614
|
+
`);let u=Date.now(),d=em(s),f={findings:[],_lock:!1},m=l.map(v=>{let X=G_(v.task);return(X?Kp(X.id):null)||o}),h=l.map((v,X)=>`Agent ${X+1} [${m[X]}]: ${v.task.substring(0,40)}${v.task.length>40?"...":""}`),p=new Y_(h);p.start();let g=`
|
|
615
615
|
You are a focused coding agent executing ONE specific sub-task.
|
|
616
616
|
Your scope is limited to the files listed in your task definition.
|
|
617
617
|
|
|
@@ -629,47 +629,47 @@ RULES:
|
|
|
629
629
|
- If your task says "add X to README" \u2014 add it, don't check if it exists first.
|
|
630
630
|
- Max 10 tool calls. If you need more, you are doing too much \u2014 narrow your scope.
|
|
631
631
|
- When done: stop calling tools and write a one-line summary of what you changed.
|
|
632
|
-
`,y=l.map(async(
|
|
632
|
+
`,y=l.map(async(v,X)=>{let be=await d();try{let ye=f.findings.filter(Me=>Me.agentId!==v.id).map(Me=>`Agent ${Me.agentId} found: ${Me.summary}`).join(`
|
|
633
633
|
`),we=[ye?`Prior agent findings:
|
|
634
634
|
${ye}
|
|
635
|
-
`:"",
|
|
636
|
-
`)),pe++;let S=Me&&ue!==fe?fe:ue;return H_({task:
|
|
637
|
-
`):void 0,max_iterations:Math.min(
|
|
638
|
-
`)}}})},1,2e3),Ee=typeof de.result=="string"?de.result.slice(0,200):String(de.result||"").slice(0,200);return f.findings.push({agentId:
|
|
639
|
-
`),conflicts:[],commitMessage:"",filesChanged:[]}}let
|
|
640
|
-
${le.bold}Summary:${le.reset} ${E.summary}${P}`),E.conflicts.length>0){console.log(`${le.yellow}Conflicts:${le.reset}`);for(let
|
|
641
|
-
`),{results:w,synthesis:E,totalTokens:c}}sm.exports={runOrchestrated:X_,decompose:tm,synthesize:nm,detectComplexPrompt:z_,extractJSON:uc,createSemaphore:em,DECOMPOSE_PROMPT:Vp,SYNTHESIZE_PROMPT:Zp,DEFAULT_ORCHESTRATOR_MODEL:Jp,DEFAULT_WORKER_MODEL:Xp,DEFAULT_MAX_PARALLEL:zp,DEFAULT_MAX_SUBTASKS:Xr,withRetry:Qp}});var Ae=J((jE,Rm)=>{var{C:$,Spinner:Ss,TaskProgress:J_,formatToolCall:V_,formatToolSummary:gm,formatSectionHeader:Jr,formatMilestone:Z_,setActiveTaskProgress:NE}=qe(),{debugLog:z,warnLog:ME}=rr(),{MilestoneTracker:Q_}=qu(),{callStream:om}=Le(),{parseToolArgs:ex}=ls(),{executeTool:tx}=It(),{gatherProjectContext:nx}=Ur(),{fitToContext:sx,forceCompress:zt,getUsage:Ut,estimateTokens:ox}=nt(),{autoSave:rx,flushAutoSave:ix}=Ft(),{scoreMessages:ax,formatScore:cx,appendScoreHistory:lx}=Br();function Ke(t){rx(t),ix()}function ux(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)||/^[^.!]{0,40}\?$/.test(e))}function rm(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=ax(t);if(!n)return;console.log(cx(n,$));try{let{_getSessionsDir:o}=Ft(),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}=ls(),s=Qn();lx(n.score,{version:s.version,model:o?o():null,sessionName:"_autosave",issues:n.issues})}catch{}}catch{}}var{getMemoryContext:dx}=Gt(),{getDeploymentContextBlock:fx}=Ja(),{checkPermission:px,setPermission:mx,savePermissions:hx}=ho(),{confirm:$m,setAllowAlwaysHandler:gx,getAutoConfirm:$x}=tt(),{isPlanMode:Eo,getPlanModePrompt:yx,PLAN_MODE_ALLOWED_TOOLS:ym,setPlanContent:wx,extractStepsFromText:bx,createPlan:_x,getActivePlan:PE,startExecution:LE,advancePlanStep:xx,getPlanStepInfo:
|
|
635
|
+
`:"",v.scope.length>0?`Focus on files: ${v.scope.join(", ")}`:""].filter(Boolean),ue=m[X],fe=process.env.NEX_FALLBACK_MODEL||Kp("agentic")||o,pe=0,de=await Qp(async()=>{let Me=pe>0;Me&&(p.update(X,"retry"),process.stderr.write(` ${le.dim}[Agent ${X+1}] retrying after error...${le.reset}
|
|
636
|
+
`)),pe++;let S=Me&&ue!==fe?fe:ue;return H_({task:v.task,context:we.length>0?we.join(`
|
|
637
|
+
`):void 0,max_iterations:Math.min(v.estimatedCalls||10,15),model:S,_skipLog:!0,_systemPrompt:g},{onUpdate:L=>{if(L&&L.type==="tool_call"&&process.stderr.isTTY){let R=` ${le.dim}[Agent ${X+1}] ${L.tool}${le.reset}`;process.stderr.write(R+`
|
|
638
|
+
`)}}})},1,2e3),Ee=typeof de.result=="string"?de.result.slice(0,200):String(de.result||"").slice(0,200);return f.findings.push({agentId:v.id,summary:Ee,files:Array.isArray(v.scope)?v.scope:[]}),p.update(X,de.status==="failed"?"error":"done"),c.input+=de.tokensUsed?.input||0,c.output+=de.tokensUsed?.output||0,de.tokensUsed?._estimated&&(c._estimated=!0),{...de,_scope:v.scope,_idx:X}}catch(ye){return p.update(X,"error"),{task:v.task,status:"failed",result:`Error: ${ye.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}}finally{be()}}),w;try{w=await Promise.all(y)}finally{p.stop({silent:!0}),K_()}console.log("");let x=Math.round((Date.now()-u)/1e3),A=x>=60?`${Math.floor(x/60)}m ${x%60}s`:`${x}s`;for(let v=0;v<w.length;v++){let X=w[v],ye=X.status==="done"||X.status==="truncated"&&X.result&&!X.result.startsWith("Error")?`${le.green}\u2713${le.reset}`:`${le.red}\u2717${le.reset}`,we=X._scope&&X._scope.length>0?X._scope.map(pe=>pe.replace(/^.*\//,"").replace(/\/$/,"")).filter(Boolean):[],ue=we.length>0?we.join(", "):X.task.substring(0,35)+(X.task.length>35?"...":""),fe=v===w.length-1;console.log(` ${ye} Agent ${v+1} ${le.dim}${ue}${le.reset}${fe?` ${le.dim}${A}${le.reset}`:""}`)}console.log(""),i("synthesizing"),console.log(`${le.dim}Phase 3: Synthesizing results...${le.reset}`);let E;try{E=await nm(w,t,n)}catch(v){console.log(`${le.yellow}Synthesize failed: ${v.message} \u2014 using raw results.${le.reset}`),E={summary:w.map(X=>X.result).join(`
|
|
639
|
+
`),conflicts:[],commitMessage:"",filesChanged:[]}}let k=f.findings.flatMap(v=>v.files),T=new Map;for(let v of k)T.set(v,(T.get(v)||0)+1);let O=[...T.values()].some(v=>v>1),P=f.findings.length>1&&O?` ${le.dim}(agents shared context)${le.reset}`:"";if(console.log(`
|
|
640
|
+
${le.bold}Summary:${le.reset} ${E.summary}${P}`),E.conflicts.length>0){console.log(`${le.yellow}Conflicts:${le.reset}`);for(let v of E.conflicts)console.log(` - ${v}`)}E.commitMessage&&console.log(`${le.dim}Suggested commit: ${E.commitMessage}${le.reset}`);let W=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(`${le.dim}Tokens: ${W}${le.reset}
|
|
641
|
+
`),{results:w,synthesis:E,totalTokens:c}}sm.exports={runOrchestrated:X_,decompose:tm,synthesize:nm,detectComplexPrompt:z_,extractJSON:uc,createSemaphore:em,DECOMPOSE_PROMPT:Vp,SYNTHESIZE_PROMPT:Zp,DEFAULT_ORCHESTRATOR_MODEL:Jp,DEFAULT_WORKER_MODEL:Xp,DEFAULT_MAX_PARALLEL:zp,DEFAULT_MAX_SUBTASKS:Xr,withRetry:Qp}});var Ae=J((jE,Rm)=>{var{C:$,Spinner:Ss,TaskProgress:J_,formatToolCall:V_,formatToolSummary:gm,formatSectionHeader:Jr,formatMilestone:Z_,setActiveTaskProgress:NE}=qe(),{debugLog:z,warnLog:ME}=rr(),{MilestoneTracker:Q_}=qu(),{callStream:om}=Le(),{parseToolArgs:ex}=ls(),{executeTool:tx}=It(),{gatherProjectContext:nx}=Ur(),{fitToContext:sx,forceCompress:zt,getUsage:Ut,estimateTokens:ox}=nt(),{autoSave:rx,flushAutoSave:ix}=Ft(),{scoreMessages:ax,formatScore:cx,appendScoreHistory:lx}=Br();function Ke(t){rx(t),ix()}function ux(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)||/^[^.!]{0,40}\?$/.test(e))}function rm(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=ax(t);if(!n)return;console.log(cx(n,$));try{let{_getSessionsDir:o}=Ft(),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}=ls(),s=Qn();lx(n.score,{version:s.version,model:o?o():null,sessionName:"_autosave",issues:n.issues})}catch{}}catch{}}var{getMemoryContext:dx}=Gt(),{getDeploymentContextBlock:fx}=Ja(),{checkPermission:px,setPermission:mx,savePermissions:hx}=ho(),{confirm:$m,setAllowAlwaysHandler:gx,getAutoConfirm:$x}=tt(),{isPlanMode:Eo,getPlanModePrompt:yx,PLAN_MODE_ALLOWED_TOOLS:ym,setPlanContent:wx,extractStepsFromText:bx,createPlan:_x,getActivePlan:PE,startExecution:LE,advancePlanStep:xx,getPlanStepInfo:vx}=Yt(),{StreamRenderer:kx}=Mp(),{runHooks:im}=cc(),{routeMCPCall:Sx,getMCPToolDefinitions:Ex}=fr(),{getSkillInstructions:Tx,getSkillToolDefinitions:Rx,routeSkillCall:Cx,matchSkillTriggers:Ax}=wn(),{trackUsage:am,estimateTokens:cm}=cs();function lm(t){return!t||typeof t!="string"?0:typeof cm=="function"?cm(t):Math.ceil(t.length/4)}var{validateToolArgs:Ox}=ya(),{filterToolsForModel:um,getModelTier:Nx,PROVIDER_DEFAULT_TIER:IE}=Fs(),{getConfiguredProviders:Mx,getActiveProviderName:Es,getActiveModelId:_n,setActiveModel:dm,MODEL_EQUIVALENTS:ci}=Le(),{getModelProfile:Px}=Fp(),Tc=require("fs"),Rc=require("path"),Lx=(()=>{let t=parseInt(process.env.NEX_MILESTONE_STEPS??"5",10);return Number.isFinite(t)&&t>=0?t:5})();function Ix(t){let e=Z_(t.phaseName,t.stepCount,t.toolCounts,t.elapsed,t.filesRead,t.filesModified);process.stdout.write(`${e}
|
|
642
642
|
`)}var fm=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi;function jx(t){let e=[],n;for(fm.lastIndex=0;(n=fm.exec(t))!==null;){let o=n[1].trim(),s=o.startsWith("~")?o.replace("~",process.env.HOME||""):Rc.resolve(o);Tc.existsSync(s)&&e.push({raw:o,abs:s})}return e}function Dx(t){let e=Tc.readFileSync(t),n=Rc.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 wm(t){let e=jx(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}=Dx(o.abs);n.push({type:"image",media_type:r,data:s})}catch{}return n.length>1?n:t}function qx(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=`
|
|
643
643
|
|
|
644
644
|
[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 wc(t,e=5){if(!t||t.length<40)return{text:t,truncated:!1,repeatCount:0};let n=t.split(`
|
|
645
645
|
`),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=`
|
|
646
646
|
|
|
647
|
-
\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 dc=null,fc=null,pc=null;function st(){if(dc===null){let{TOOL_DEFINITIONS:t}=It();dc=t}return fc===null&&(fc=Rx()),pc===null&&(pc=Ex()),[...dc,...fc,...pc]}var bc=50;function Fx(t){Number.isFinite(t)&&t>0&&(bc=t)}var Qr=()=>null;function Ux(t){Qr=t}var _o=null,_c=null,Ts=null,ei=new Map,Wx=1e4,Bx=6e3,Hx=/\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 Kx(t){return!t||typeof t!="string"?t:t.replace(Hx,(e,n)=>`${n}=***REDACTED***`)}var Gx=7e3,Yx=4e3;function zx(t,e=null){let n=Kx(t),o=ox(n),s=e==="read_file"?Gx:Wx,r=e==="read_file"?Yx:Bx;if(o>s)try{let{compressToolResult:i}=nt();return i(n,r)}catch{return n}return n}function bm(t){try{let{getActiveModel:e}=Le(),n=e(),o=n?`${n.provider}:${n.id}`:"default";if(ei.has(o))return ei.get(o);let s=um(t);return ei.set(o,s),s}catch{return um(t)}}function Xx(){ei.clear()}var xo={hash:null,ts:0},Jx=3e4;async function _m(){if(xo.hash&&Date.now()-xo.ts<Jx)return xo.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}=Gt(),c=i();c&&s.push(`memory:${c}`)}catch{}try{let i=e.join(process.cwd(),".nex","brain");if(Tc.existsSync(i)){let c=await t.stat(i);s.push(`brain:${c.mtimeMs}`)}}catch{}let r=s.join("|");return xo={hash:r,ts:Date.now()},r}catch{return`fallback:${Date.now()}`}}function xc(){_o=null,_c=null,xo={hash:null,ts:0},Ts=null}var Vx=new Set(["spawn_agents"]),mc=5,hc=3,Vr=2,pm=6e4,gc=12e4,Zx=process.env.NEX_STALE_AUTO_SWITCH!=="0";function Qx(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{}}gx(t=>{mx(t,"allow"),hx(),console.log(`${$.green} \u2713 ${t}: always allow${$.reset}`)});async function
|
|
647
|
+
\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 dc=null,fc=null,pc=null;function st(){if(dc===null){let{TOOL_DEFINITIONS:t}=It();dc=t}return fc===null&&(fc=Rx()),pc===null&&(pc=Ex()),[...dc,...fc,...pc]}var bc=50;function Fx(t){Number.isFinite(t)&&t>0&&(bc=t)}var Qr=()=>null;function Ux(t){Qr=t}var _o=null,_c=null,Ts=null,ei=new Map,Wx=1e4,Bx=6e3,Hx=/\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 Kx(t){return!t||typeof t!="string"?t:t.replace(Hx,(e,n)=>`${n}=***REDACTED***`)}var Gx=7e3,Yx=4e3;function zx(t,e=null){let n=Kx(t),o=ox(n),s=e==="read_file"?Gx:Wx,r=e==="read_file"?Yx:Bx;if(o>s)try{let{compressToolResult:i}=nt();return i(n,r)}catch{return n}return n}function bm(t){try{let{getActiveModel:e}=Le(),n=e(),o=n?`${n.provider}:${n.id}`:"default";if(ei.has(o))return ei.get(o);let s=um(t);return ei.set(o,s),s}catch{return um(t)}}function Xx(){ei.clear()}var xo={hash:null,ts:0},Jx=3e4;async function _m(){if(xo.hash&&Date.now()-xo.ts<Jx)return xo.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}=Gt(),c=i();c&&s.push(`memory:${c}`)}catch{}try{let i=e.join(process.cwd(),".nex","brain");if(Tc.existsSync(i)){let c=await t.stat(i);s.push(`brain:${c.mtimeMs}`)}}catch{}let r=s.join("|");return xo={hash:r,ts:Date.now()},r}catch{return`fallback:${Date.now()}`}}function xc(){_o=null,_c=null,xo={hash:null,ts:0},Ts=null}var Vx=new Set(["spawn_agents"]),mc=5,hc=3,Vr=2,pm=6e4,gc=12e4,Zx=process.env.NEX_STALE_AUTO_SWITCH!=="0";function Qx(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{}}gx(t=>{mx(t,"allow"),hx(),console.log(`${$.green} \u2713 ${t}: always allow${$.reset}`)});async function ev(t){let e=t.function.name,n=ex(t.function.arguments),o=t.id||`cli-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!n){let l=st().find(d=>d.function.name===e),u=l?JSON.stringify(l.function.parameters,null,2):"unknown";return z(`${$.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.
|
|
648
648
|
Raw input: ${typeof t.function.arguments=="string"?t.function.arguments.substring(0,200):"N/A"}
|
|
649
649
|
|
|
650
650
|
Expected JSON schema for "${e}":
|
|
651
651
|
${u}
|
|
652
652
|
|
|
653
653
|
Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:o}}}let s=Ox(e,n);if(!s.valid)return z(`${$.yellow} \u26A0 ${e}: ${s.error.split(`
|
|
654
|
-
`)[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(Eo()&&!ym.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=px(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 $m(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
|
|
654
|
+
`)[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(Eo()&&!ym.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=px(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 $m(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 tv(t,e,n={}){let o=await Cx(t,e);if(o!==null)return o;let s=await Sx(t,e);return s!==null?s:tx(t,e,n)}function nv(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 $c(t,e=!1){e||console.log(V_(t.fnName,t.args));let n=im("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}`);Jt?.onToolStart&&Jt.onToolStart(t.fnName,t.args);let o=await tv(t.fnName,t.args,{silent:!0,autoConfirm:t.confirmedByUser===!0}),s=String(o??""),r=s.length>5e4?s.substring(0,5e4)+`
|
|
655
655
|
...(truncated ${s.length-5e4} chars)`:s,i=r.split(`
|
|
656
656
|
`)[0],c=i.startsWith("ERROR")||i.includes("CANCELLED")||i.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(r)&&/✗ Agent/.test(r),l=gm(t.fnName,t.args,r,c);e||console.log(l),Jt?.onToolEnd&&Jt.onToolEnd(t.fnName,l,!c);let u=im("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=zx(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+=`
|
|
657
657
|
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+=`
|
|
658
658
|
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+=`
|
|
659
|
-
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}}var
|
|
660
|
-
`)):(
|
|
661
|
-
`)}function
|
|
659
|
+
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}}var sv=[{re:/TypeError:\s*([^\n]{0,120})/i,label:"TypeError"},{re:/SyntaxError:\s*([^\n]{0,120})/i,label:"SyntaxError"},{re:/ReferenceError:\s*([^\n]{0,120})/i,label:"ReferenceError"},{re:/Cannot find module\s*'([^']+)'/i,label:"Cannot find module"},{re:/Error:\s*ENOENT[^\n]{0,120}/i,label:"ENOENT"},{re:/Error:\s*EACCES[^\n]{0,120}/i,label:"EACCES"},{re:/Error:\s*EADDRINUSE[^\n]{0,120}/i,label:"EADDRINUSE"},{re:/ImportError:\s*([^\n]{0,120})/i,label:"ImportError"},{re:/ModuleNotFoundError:\s*([^\n]{0,120})/i,label:"ModuleNotFoundError"},{re:/NameError:\s*([^\n]{0,120})/i,label:"NameError"},{re:/AttributeError:\s*([^\n]{0,120})/i,label:"AttributeError"},{re:/KeyError:\s*([^\n]{0,120})/i,label:"KeyError"},{re:/ValueError:\s*([^\n]{0,120})/i,label:"ValueError"},{re:/panic:\s*([^\n]{0,120})/i,label:"Go panic"},{re:/java\.lang\.\w+Exception[^\n]{0,80}/i,label:"Java exception"}];function yc(t){for(let{re:e,label:n}of sv){let o=t.match(e);if(o){let s=(o[1]||"").trim();return s?`${n}: ${s}`:n}}return null}async function ov(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=nv(d.fnName,d.args);u=`\u23FA ${d.fnName}${f?`(${f})`:""}`}else{let d=l.map(f=>f.fnName).join(", ");u=`\u23FA ${l.length} tools: ${d.length>60?d.substring(0,57)+"\u2026":d}`}i=new Ss(u),i.start()}}async function c(){if(r.length!==0){if(r.length===1){let l=r[0],{msg:u,summary:d}=await $c(t[l],e);o[l]=u,s.push(d)}else{let l=r.map(d=>$c(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(gm(u.fnName,u.args||{},u.errorResult.content,!0));continue}if(Vx.has(u.fnName)){await c(),u.fnName==="spawn_agents"&&i&&(i.stop(),i=null);let{msg:d,summary:f}=await $c(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 Y=[],mm=300,xm=900*1e3;function vs(t,e){let n=t.get(e);return n?Date.now()-n.ts>xm?(t.delete(e),0):n.count:0}function bo(t,e){let n=t.get(e),o=n&&Date.now()-n.ts<=xm?n.count+1:1;return t.set(e,{count:o,ts:Date.now()}),o}function hm(t,e,n){t.set(e,{count:n,ts:Date.now()})}var vm=new Map,km=new Map,ti=new Map,Rs=new Map,Kn=new Map,Sm=new Map,Gn=new Map,Cs=new Map,vc=new Map,Ot=0,vo=0,ni=0,kc="",si=0,Nt=!1,Zr=0,oi=0,Yn=-1,Sc=!1,ri=0,ii=!1,zn=0,cn=!1,Xt=0,Je=!1,gt="",ko=0,Mt=!1,Ec=!1,To=new Map,Ro=new Set,So=null;function ks(t,e){t===kc?(si++,rr().DEBUG&&process.stdout.write(`\x1B[1A\x1B[2K${e} \u26A0 ${t} (\xD7${si})${$.reset}
|
|
660
|
+
`)):(kc=t,si=1,z(`${e} \u26A0 ${t}${$.reset}`))}var ai=[];function rv(t){ai.push(t.trim())}function iv(){return ai.length===0?null:ai.splice(0,ai.length).join(`
|
|
661
|
+
`)}function av(){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)
|
|
662
662
|
`];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(`
|
|
663
663
|
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(`
|
|
664
664
|
`)+`
|
|
665
665
|
|
|
666
|
-
`}function
|
|
666
|
+
`}function cv(){if(Ts!==null)return Ts;try{let e=Mx().flatMap(s=>s.models.map(r=>({spec:`${s.name}:${r.id}`,tier:Nx(r.id,s.name),name:r.name})));if(e.length<2)return Ts="","";let n={full:"complex tasks (refactor, implement, generate)",standard:"regular tasks (edit, fix, analyze)",essential:"simple tasks (read, search, list)"},o=`
|
|
667
667
|
# Sub-Agent Model Routing
|
|
668
668
|
|
|
669
669
|
`;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 |
|
|
670
670
|
|---|---|---|
|
|
671
671
|
`;for(let s of e)o+=`| ${s.spec} | ${s.tier} | ${n[s.tier]||s.tier} |
|
|
672
|
-
`;return Ts=o,o}catch(t){return process.env.NEX_DEBUG&&console.error("[agent] model routing guide failed:",t.message),Ts="",""}}async function Em(){let t=await _m();if(_o!==null&&t===_c)return _o;let e=await nx(process.cwd()),n=dx(),o=Tx(),s=Eo()?yx():"",r=
|
|
672
|
+
`;return Ts=o,o}catch(t){return process.env.NEX_DEBUG&&console.error("[agent] model routing guide failed:",t.message),Ts="",""}}async function Em(){let t=await _m();if(_o!==null&&t===_c)return _o;let e=await nx(process.cwd()),n=dx(),o=Tx(),s=Eo()?yx():"",r=av(),i=fx();return _o=`You are Nex Code, an expert coding assistant. You help with programming tasks by reading, writing, and editing files, running commands, and answering questions.
|
|
673
673
|
|
|
674
674
|
WORKING DIRECTORY: ${process.cwd()}
|
|
675
675
|
All relative paths resolve from this directory.
|
|
@@ -901,7 +901,7 @@ Sequencing independent calls wastes iterations. Every unnecessary round-trip add
|
|
|
901
901
|
- Instead: use bash with inline node -e '...' for quick one-off checks.
|
|
902
902
|
- If the test is worth keeping, write it to tests/ with a proper name.
|
|
903
903
|
- Write-then-delete patterns waste 3 tool calls and leave orphans if the session is interrupted.
|
|
904
|
-
${
|
|
904
|
+
${cv()}
|
|
905
905
|
|
|
906
906
|
# Edit Protocol (Mandatory \u2014 Follow These Steps Exactly)
|
|
907
907
|
|
|
@@ -1091,70 +1091,70 @@ class ErrorBoundary extends React.Component {
|
|
|
1091
1091
|
- Use migrations for schema changes, never manual ALTER TABLE
|
|
1092
1092
|
- Add database-level constraints (unique, foreign key, check) not just app-level
|
|
1093
1093
|
|
|
1094
|
-
`,_c=t,_o}function Tm(){
|
|
1094
|
+
`,_c=t,_o}function Tm(){vm.clear(),km.clear(),ti.clear(),Rs.clear(),Kn.clear(),Sm.clear(),Gn.clear(),Cs.clear(),vc.clear(),Ot=0,vo=0,ni=0,Nt=!1,oi=0,Yn=-1,Sc=!1,ri=0,ii=!1,zn=0,cn=!1,Xt=0,Je=!1,gt="",ko=0,Mt=!1,Ec=!1,To.clear(),Ro.clear(),kc="",si=0}function lv(){Y=[],So=null,Tm()}function uv(){Y.length>mm&&Y.splice(0,Y.length-mm)}function dv(){return Y.length}function fv(){return Y}function pv(t){Y=t}async function mv(){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(`
|
|
1095
1095
|
`):[]).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=Rc.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+=`
|
|
1096
|
-
\u{1F4E6} ${h}${p}`}}catch{}return u}function
|
|
1097
|
-
${$.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`;
|
|
1098
|
-
`),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 Jt=null;async function $
|
|
1096
|
+
\u{1F4E6} ${h}${p}`}}catch{}return u}function hv(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 Ge(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(`
|
|
1097
|
+
${$.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`;hv(u)}if(Ro.size>0&&To.size>0)for(let u of Ro){let d=To.get(u);d&&console.log(`${$.dim} \u2714 task #${u} auto-matched: ${d.slice(0,60)}${$.reset}`)}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 gv(){if(!process.stdout.isTTY)return{action:"quit"};let t=Es(),e=_n(),n=ci.fast?.[t],o=ci.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}
|
|
1098
|
+
`),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 Jt=null;async function $v(t,e=null,n={}){let o=Px(_n());pm=o.staleWarn,gc=o.staleAbort,Jt=e;let s=t;So&&typeof t=="string"&&(s=`${So}
|
|
1099
1099
|
|
|
1100
|
-
${t}`,So=null);let r=wm(s);Y.push({role:"user",content:r}),
|
|
1100
|
+
${t}`,So=null);let r=wm(s);Y.push({role:"user",content:r}),uv();let i=n.autoOrchestrate!==!1&&process.env.NEX_AUTO_ORCHESTRATE!=="false",c=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10);try{let{detectComplexPrompt:Pe,runOrchestrated:Te}=wo(),Ne=Pe(typeof t=="string"?t:"");if(i&&Ne.isComplex&&Ne.estimatedGoals>=c)return console.log(`${$.yellow}\u26A1 Auto-orchestrate: ${Ne.estimatedGoals} goals \u2192 parallel agents${$.reset}`),await Te(t,{orchestratorModel:n.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL,workerModel:n.model});Ne.isComplex&&process.stdout.isTTY&&console.log(`${$.dim}Hint: ~${Ne.estimatedGoals} goals detected. Disable with NEX_AUTO_ORCHESTRATE=false${$.reset}`)}catch{}let{setOnChange:l}=Sr(),u=null,d=0;l((Pe,Te)=>{Pe==="create"?(u&&u.stop(),u=new J_(Te.name,Te.tasks),u.setStats({tokens:d}),u.start()):Pe==="update"&&u?u.updateTask(Te.id,Te.status):Pe==="clear"&&u&&(u.stop(),u=null)});let f=await Em(),m=f;try{let{getBrainContext:Pe}=no(),Te=await Pe(t);Te&&(m=f+`
|
|
1101
1101
|
`+Te+`
|
|
1102
1102
|
`)}catch(Pe){process.env.NEX_DEBUG&&console.error("[agent] brain context failed:",Pe.message)}let p=Ax(typeof t=="string"?t:"");if(p.length>0){let Pe=p.map(Te=>`[Triggered: ${Te.name}]
|
|
1103
1103
|
${Te.instructions}`).join(`
|
|
1104
1104
|
`);m+=`
|
|
1105
1105
|
`+Pe+`
|
|
1106
|
-
`}let g=[{role:"system",content:m},...Y],y=new Ss("Thinking...");y.start();let x=Y.length===1?
|
|
1107
|
-
`),Te=yc(Pe);Te&&(Je=!0,gt=Te.slice(0,120),z(`${$.yellow} \u26A1 Root cause in briefing: ${gt} \u2014 fix phase active from start (read budget: 3)${$.reset}`))}!Je&&!Mt&&/\b(create|build|generate|implement|write|make|develop|set\s*up|scaffold|add)\b.{0,80}\b(app|component|page|game|api|backend|frontend|server|service|module|class|function|feature|project|system|bot|script|tool)\b/i.test(de)&&(Mt=!0,z(`${$.cyan} \u26A1 Creation task detected \u2014 tight investigation cap (4 pre-edit, 2 post-edit)${$.reset}`));let S=0,L=new Map,R=new Set,M=new Set,D=Date.now(),q=new Q_(Lx),Z=Sm,ce=3,se=5,me=
|
|
1106
|
+
`}let g=[{role:"system",content:m},...Y],y=new Ss("Thinking...");y.start();let x=Y.length===1?mv().catch(()=>null):Promise.resolve(null),A=st(),[{messages:E,compressed:k,compacted:T,tokensRemoved:O},P]=await Promise.all([sx(g,A),x]),W=Ut(g,A);if(y.stop(),P&&console.log(`${$.dim}${P}${$.reset}`),T)console.log(`${$.dim} [context compacted \u2014 summary (~${O} tokens freed)]${$.reset}`);else if(k){let Pe=W.limit>0?Math.round(O/W.limit*100):0;z(`${$.dim} [context compressed \u2014 ~${O} tokens freed (${Pe}%)]${$.reset}`)}W.percentage>85&&z(`${$.yellow} \u26A0 Context ${Math.round(W.percentage)}% used (${Math.round(100-W.percentage)}% remaining) \u2014 consider /clear or /save + start fresh${$.reset}`);let v=E;if(Ut(v,st()).percentage>=65){let{messages:Te,tokensRemoved:Ne}=zt(v,st());Ne>0&&(v=Te,console.log(`${$.dim} [pre-flight compress \u2014 ${Ne} tokens freed, now ${Math.round(Ut(v,st()).percentage)}% used]${$.reset}`))}let X=0,be=0,ye=0,we=0,ue=0,fe=9,pe=0,de=(()=>{let Pe=Y.find(Te=>Te.role==="user");return typeof Pe?.content=="string"?Pe.content:""})(),Ee=/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|gecrasht|abgestürzt).{0,30}jarvis|swarm.{0,30}(agent|crash|gecrasht|abgestürzt|fail)|agent.{0,30}(gecrasht|abgestürzt|crashed|fail)|server.{0,30}(passiert|fehler|crash|problem)|am.server/i.test(de),Me=0;if(!Je){let Pe=Y.filter(Ne=>Ne.role==="user"||Ne.role==="tool").map(Ne=>typeof Ne.content=="string"?Ne.content:"").join(`
|
|
1107
|
+
`),Te=yc(Pe);Te&&(Je=!0,gt=Te.slice(0,120),z(`${$.yellow} \u26A1 Root cause in briefing: ${gt} \u2014 fix phase active from start (read budget: 3)${$.reset}`))}!Je&&!Mt&&/\b(create|build|generate|implement|write|make|develop|set\s*up|scaffold|add)\b.{0,80}\b(app|component|page|game|api|backend|frontend|server|service|module|class|function|feature|project|system|bot|script|tool)\b/i.test(de)&&(Mt=!0,z(`${$.cyan} \u26A1 Creation task detected \u2014 tight investigation cap (4 pre-edit, 2 post-edit)${$.reset}`));let S=0,L=new Map,R=new Set,M=new Set,D=Date.now(),q=new Q_(Lx),Z=Sm,ce=3,se=5,me=vm,ke=5,Qe=8,ze=km,fn=4,ki=7,qo=ti,Jh=3,il=5,Fo=Rs,Vh=2,Zh=3,Ps=6,kn=0,Qh=6,eg=10,Sn=0,al=5,En=0,tg=2,ng=3,Si=0,Ls=10,sg=16,og=o.investigationCap,dt,Uo=bc,Ei=0,cl=3,Ti=!1;e:for(;;){for(Ti=!1,dt=0;dt<Uo&&!Qr()?.aborted;dt++){{let _=st(),b=Ut(v,_),te=S===0?65:78;if(b.percentage>=te){let{messages:I,tokensRemoved:F}=zt(v,_,S===0);if(F>0&&(v=I,F>50&&console.log(`${$.dim} [auto-compressed \u2014 ~${F} tokens freed, now ${Math.round(Ut(v,_).percentage)}%]${$.reset}`),Mt&&R.size>=3)){let oe=[...R].map(he=>he.split("/").pop()).slice(0,10).join(", "),re={role:"user",content:`[FRAMEWORK \u2014 context compressed] Task is IN PROGRESS. Already created ${R.size} files: ${oe}. DO NOT restart or re-investigate what was already done. Continue from where you left off.`};v.push(re)}}}if(Nt&&!Je&&ko<2){ko++;let _={role:"user",content:"[SYSTEM] SSH paused \u2014 you have made many consecutive SSH calls. Synthesize your findings so far: summarize what you learned and what the likely issue is. After your synthesis, SSH will be available again for targeted follow-up commands."};v.push(_),Y.push(_),z(`${$.yellow} \u26A0 Pre-call SSH-blocked nudge #${ko} injected \u2014 model told to synthesize${$.reset}`)}Nt||(ko=0);let Te=!0;S>0&&xx();let Ne=null;if(u&&u.isActive())u._paused&&u.resume();else if(!u){let _,b=vx();if(b&&b.total>1){let te=b.description.length>40?b.description.slice(0,37)+"\u2026":b.description;_=`Plan step ${b.current}/${b.total}: ${te}`}else _=S>0?`Thinking... (step ${S+1})`:"Thinking...";Ne=new Ss(_),Ne.start()}let Ri=!0,Vt="",Ci=!1,yt=new kx,Bt,Ai=Date.now(),Wo=!1,Oi=new AbortController,ll=setInterval(()=>{let _=Date.now()-Ai;if(_>=gc)yt._clearCursorLine(),z(`${$.yellow} \u26A0 Stream stale for ${Math.round(_/1e3)}s \u2014 aborting and retrying${$.reset}`),Oi.abort();else if(_>=pm&&!Wo){Wo=!0,yt._clearCursorLine();let b=ci.fast?.[Es()],te=ye>0?` (retry ${ye+1}/${Vr})`:"",I=Math.round((gc-_)/1e3);z(`${$.yellow} \u26A0 No tokens received for ${Math.round(_/1e3)}s \u2014 waiting...${te}${$.reset}`),b&&b!==_n()?console.log(`${$.dim} \u{1F4A1} Will auto-switch to ${b} in ~${I}s if no tokens arrive${$.reset}`):console.log(`${$.dim} \u{1F4A1} Ctrl+C to abort \xB7 auto-abort in ~${I}s${$.reset}`)}},5e3),Et="",Zt=null;try{let _=bm(st()),b=Eo()?_.filter(F=>ym.has(F.function.name)):_,te=Qr(),I=new AbortController;te&&te.addEventListener("abort",()=>I.abort(),{once:!0}),Oi.signal.addEventListener("abort",()=>I.abort(),{once:!0}),Bt=await om(v,b,{signal:I.signal,onThinkingToken:()=>{Ai=Date.now(),Wo=!1,Jt?.onThinkingToken&&Jt.onThinkingToken()},onToken:F=>{if(Ai=Date.now(),Wo=!1,Jt?.onToken){Jt.onToken(F),Vt+=F;return}if(Vt+=F,!Ci&&Vt.length>400&&Vt.length%250<F.length+1){let oe=wc(Vt,3);oe.truncated&&(Ci=!0,yt._clearCursorLine?.(),z(`${$.yellow} \u26A0 LLM stream loop detected (${oe.repeatCount}\xD7 repeated) \u2014 suppressing display${$.reset}`))}Ci||(Et+=F,process.stdout.isTTY?Zt||(Zt=setTimeout(()=>{Et&&yt&&yt.push(Et),Et="",Zt=null},50)):(yt.push(Et),Et=""),Ri&&(u&&!u._paused?u.pause():Ne&&Ne.stop(),Te||(Te=!0),yt.startCursor(),Ri=!1))}})}catch(_){if(clearInterval(ll),Zt&&(clearTimeout(Zt),Zt=null),Et&&yt&&(yt.push(Et),Et=""),u&&!u._paused&&u.pause(),Ne&&Ne.stop(),yt.stopCursor(),Oi.signal.aborted&&!Qr()?.aborted){if(ye++,ye>Vr){if(we<1){we++,ks("Stale retries exhausted \u2014 last-resort force-compress...",$.yellow);let re=st(),{messages:he,tokensRemoved:B}=zt(v,re);v=he,B>50&&z(`${$.dim} [force-compressed \u2014 ~${B} tokens freed]${$.reset}`),ye=0,dt--;continue}u&&(u.stop(),u=null);let oe=await gv();if(oe.action==="quit"){l(null),Ge(S,L,R,M,D),Ke(Y);break}oe.action==="switch"&&(dm(`${oe.provider}:${oe.model}`),console.log(`${$.green} \u2713 Switched to ${oe.provider}:${oe.model}${$.reset}`)),ye=0,dt--;continue}let I=ye===1?3e3:5e3;if(ye>=1&&pe<1){pe++,ks(`Stale retry ${ye}/${Vr} \u2014 force-compressing before retry...`,$.yellow);let oe=st(),{messages:re,tokensRemoved:he}=zt(v,oe,!0);if(v=re,he>0&&he>50&&z(`${$.dim} [force-compressed \u2014 ~${he} tokens freed]${$.reset}`),Zx){let B=ci.fast?.[Es()];B&&B!==_n()&&(dm(`${Es()}:${B}`),console.log(`${$.cyan} \u26A1 Auto-switched to ${B} to avoid further stale timeouts${$.reset}`),console.log(`${$.dim} (disable with NEX_STALE_AUTO_SWITCH=0)${$.reset}`))}}else z(`${$.yellow} \u26A0 Stale retry ${ye}/${Vr} \u2014 retrying in ${I/1e3}s...${$.reset}`);let F=new Ss(`Waiting ${I/1e3}s before retry...`);F.start(),await new Promise(oe=>setTimeout(oe,I)),F.stop(),dt--;continue}if(_.name==="AbortError"||_.name==="CanceledError"||_.message?.includes("canceled")||_.message?.includes("aborted")){u&&(u.stop(),u=null),l(null),Ge(S,L,R,M,D),Ke(Y);break}let b=_.message;if(_.code==="ECONNREFUSED"||_.message.includes("ECONNREFUSED"))b="Connection refused \u2014 please check your internet connection or API endpoint";else if(_.code==="ENOTFOUND"||_.message.includes("ENOTFOUND"))b="Network error \u2014 could not reach the API server. Please check your connection";else if(_.code==="ETIMEDOUT"||_.message.includes("timeout"))b="Request timed out \u2014 the API server took too long to respond. Please try again";else if(_.message.includes("401")||_.message.includes("Unauthorized"))b="Authentication failed \u2014 please check your API key in the .env file";else if(_.message.includes("403")||_.message.includes("Forbidden"))b="Access denied \u2014 your API key may not have permission for this model";else if(_.message.includes("404")){b=`Model not found (404): ${_n?_n():"unknown"} \u2014 check your .env MODEL setting or run /models to list available models`,console.log(`${$.red} \u2717 ${b}${$.reset}`),u&&(u.stop(),u=null),l(null),Ge(S,L,R,M,D),Ke(Y);break}else if(_.message.includes("400")){if(we<3&&ue<fe){we++,ue++;let I=S===0&&we===1,F=I||we===3||pe>0;if(I){we=3;let B=_.message.replace(/^API Error(\s*\[HTTP \d+\])?:\s*/i,"").slice(0,150);ks(`Bad request (400) \u2014 ${B||"system prompt too large"}, compressing...`,$.yellow)}else ks(F?`Bad request (400) \u2014 nuclear compression (attempt ${we}/3, dropping history)...`:`Bad request (400) \u2014 force-compressing and retrying... (attempt ${we}/3)`,$.yellow);let oe=st(),{messages:re,tokensRemoved:he}=zt(v,oe,F);v=re,he>50&&z(`${$.dim} [force-compressed \u2014 ~${he} tokens freed]${$.reset}`),dt--;continue}{let I=v.find(K=>K.role==="system"),F=v.find(K=>K.role==="user"&&!String(K.content).startsWith("[SYSTEM")&&!String(K.content).startsWith("BLOCKED:")),oe=[I,F].filter(Boolean),{getUsage:re}=nt(),he=nt().estimateMessagesTokens(oe),B=nt().estimateMessagesTokens(v);if(he<B){let K=[],ne=Y.filter(U=>U.role==="assistant"&&typeof U.content=="string"&&U.content.trim().length>30).slice(-5).map(U=>U.content.trim().slice(0,300).replace(/\n+/g," "));ne.length>0&&K.push(`Key findings:
|
|
1108
1108
|
`+ne.map(U=>`- ${U}`).join(`
|
|
1109
1109
|
`));let ge=Y.filter(U=>U.role==="tool"&&typeof U.content=="string"&&!U.content.startsWith("BLOCKED:")&&U.content.trim().length>10).slice(-5).map(U=>U.content.trim().split(`
|
|
1110
1110
|
`).slice(0,8).join(`
|
|
1111
1111
|
`).slice(0,500));if(ge.length>0&&K.push(`Tool results summary:
|
|
1112
1112
|
`+ge.map(U=>`- ${U}`).join(`
|
|
1113
|
-
`)),R.size>0){let U=[...R].map($e=>$e.split("/").slice(-2).join("/")).join(", ");K.unshift(`Already modified: ${U} \u2014 use edit_file to add missing pieces only, DO NOT use write_file on these files.`)}if(M.size>0){let U=[...M].map($e=>$e.split("/").slice(-2).join("/")).join(", ");K.push(`Files already investigated: ${U}`)}let ee=require("os").tmpdir()+"/nex-session-checkpoint.json";try{require("fs").writeFileSync(ee,JSON.stringify({filesWritten:[...R].map(U=>U.split("/").slice(-2).join("/")),filesRead:[...M].map(U=>U.split("/").slice(-2).join("/")),isCreationTask:Mt,wipeNumber:
|
|
1113
|
+
`)),R.size>0){let U=[...R].map($e=>$e.split("/").slice(-2).join("/")).join(", ");K.unshift(`Already modified: ${U} \u2014 use edit_file to add missing pieces only, DO NOT use write_file on these files.`)}if(M.size>0){let U=[...M].map($e=>$e.split("/").slice(-2).join("/")).join(", ");K.push(`Files already investigated: ${U}`)}let ee=require("os").tmpdir()+"/nex-session-checkpoint.json";try{require("fs").writeFileSync(ee,JSON.stringify({filesWritten:[...R].map(U=>U.split("/").slice(-2).join("/")),filesRead:[...M].map(U=>U.split("/").slice(-2).join("/")),isCreationTask:Mt,wipeNumber:vo+1,timestamp:Date.now()},null,2)),K.push(`Session checkpoint: ${ee} \u2014 read it for exact file list`)}catch{}if(K.length>0){let U={role:"user",content:`[SYSTEM: Findings from investigation before context wipe]
|
|
1114
1114
|
${K.join(`
|
|
1115
1115
|
`)}
|
|
1116
|
-
Continue implementing the fixes based on these findings.`};oe.push(U)}if(
|
|
1117
|
-
Files modified so far: ${[...R].map($e=>$e.split("/").slice(-1)[0]).join(", ")}`:"";z(`${$.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.${U?$.dim+U:""}${$.reset}`),u&&(u.stop(),u=null),l(null),Ge(S,L,R,M,D,{suppressHint:!0}),Ke(Y);break}
|
|
1116
|
+
Continue implementing the fixes based on these findings.`};oe.push(U)}if(vo>=3){let U=R.size>0?`
|
|
1117
|
+
Files modified so far: ${[...R].map($e=>$e.split("/").slice(-1)[0]).join(", ")}`:"";z(`${$.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.${U?$.dim+U:""}${$.reset}`),u&&(u.stop(),u=null),l(null),Ge(S,L,R,M,D,{suppressHint:!0}),Ke(Y);break}v=oe,vo++,Yn=12,Sc=!0,ri=R.size,ii=!1,Ot=0,Me=0;for(let[U,$e]of Rs){let Tt=$e?.count??$e??0;hm(Rs,U,Tt>=2?Tt:1)}for(let[U]of Kn)vs(Rs,U)<2&&Kn.delete(U);Gn.clear(),Cs.clear(),Mt&&Xt>0&&(cn=!0,z(`${$.cyan} \u26A1 Post-wipe creation guard: cap pre-fired (${Xt} edits already made)${$.reset}`));for(let[U]of ti)hm(ti,U,il-1);if(ks(`Super-nuclear compression \u2014 dropped all history, keeping original task only (${B-he} tokens freed)`,$.yellow),vo>=1){let U=[...Rs.entries()].filter(([,tn])=>tn>=Ps).map(([tn])=>tn.split("/").slice(-1)[0]),$e=U.length>0?`
|
|
1118
1118
|
|
|
1119
|
-
Files already at read cap \u2014 use grep_search instead: ${U.join(", ")}`:"",en={role:"user",content:Nt&&!Je?"[SYSTEM] Context was compressed. SSH is currently unavailable \u2014 do not read more local files. Summarize what you found and ask the user for the server output you need.":`[SYSTEM] Context was compressed. Use the findings above to implement your fix. If you need to re-read a file, use line_start/line_end for the specific section.${$e}`};Y.push(en),
|
|
1119
|
+
Files already at read cap \u2014 use grep_search instead: ${U.join(", ")}`:"",en={role:"user",content:Nt&&!Je?"[SYSTEM] Context was compressed. SSH is currently unavailable \u2014 do not read more local files. Summarize what you found and ask the user for the server output you need.":`[SYSTEM] Context was compressed. Use the findings above to implement your fix. If you need to re-read a file, use line_start/line_end for the specific section.${$e}`};Y.push(en),v.push(en)}we=0,dt--;continue}}b="Context too large to compress \u2014 use /clear to start fresh"}else _.message.includes("500")||_.message.includes("502")||_.message.includes("503")||_.message.includes("504")?b="API server error \u2014 the provider is experiencing issues. Please try again in a moment":(_.message.includes("fetch failed")||_.message.includes("fetch"))&&(b="Network request failed \u2014 please check your internet connection");if(console.log(`${$.red} \u2717 ${b}${$.reset}`),_.message.includes("429")){if(X++,X>mc){console.log(`${$.red} Rate limit: max retries (${mc}) exceeded. Try again later or use /budget to check your limits.${$.reset}`),u&&(u.stop(),u=null),l(null),Ge(S,L,R,M,D),Ke(Y);break}let I=Math.min(1e4*Math.pow(2,X-1),12e4),F=new Ss(`Rate limit \u2014 waiting ${Math.round(I/1e3)}s (retry ${X}/${mc})`);F.start(),await new Promise(oe=>setTimeout(oe,I)),F.stop();continue}if(_.message.includes("socket disconnected")||_.message.includes("TLS")||_.message.includes("ECONNRESET")||_.message.includes("ECONNABORTED")||_.message.includes("ETIMEDOUT")||_.code==="ECONNRESET"||_.code==="ECONNABORTED"){if(be++,be>hc){console.log(`${$.red} Network error: max retries (${hc}) exceeded. Check your connection and try again.${$.reset}`),u&&(u.stop(),u=null),l(null),Ge(S,L,R,M,D),Ke(Y);break}let I=Math.min(2e3*Math.pow(2,be-1),3e4),F=new Ss(`Network error \u2014 retrying in ${Math.round(I/1e3)}s (${be}/${hc})`);F.start(),await new Promise(oe=>setTimeout(oe,I)),F.stop(),dt--;continue}u&&(u.stop(),u=null),l(null),Ge(S,L,R,M,D),Ke(Y);break}if(clearInterval(ll),X=0,be=0,Ri&&(u&&!u._paused&&u.pause(),Ne&&Ne.stop()),Zt&&(clearTimeout(Zt),Zt=null),Et&&yt&&(yt.push(Et),Et=""),Vt&&yt.flush(),be=0,ye=0,Bt&&Bt.usage){let _=Bt.usage.prompt_tokens||0,b=Bt.usage.completion_tokens||0;am(Es(),_n(),_,b),d+=_+b,u&&u.setStats({tokens:d})}else if(Bt&&!Bt.usage){let _=v.map(I=>typeof I.content=="string"?I.content:Array.isArray(I.content)?I.content.map(F=>typeof F=="string"?F:F.text||"").join(""):"").join(" "),b=lm(_),te=lm(Bt.content||Vt||"");am(Es(),_n(),b,te),d+=b+te,u&&u.setStats({tokens:d})}let{content:ul,tool_calls:Qt}=Bt,Bo=wc(ul||""),dl=Bo.truncated?Bo.text:ul;Bo.truncated&&z(`${$.yellow} \u26A0 LLM output loop detected (${Bo.repeatCount}\xD7 repeated paragraph) \u2014 response truncated${$.reset}`);let Ho=qx(dl||""),pn=Ho.truncated?Ho.text:dl;Ho.truncated&&z(`${$.yellow} \u26A0 LLM output loop detected (${Ho.repeatCount}\xD7 repeated window) \u2014 response truncated${$.reset}`);let Ni={role:"assistant",content:pn||""};if(Qt&&Qt.length>0&&(Ni.tool_calls=Qt),Y.push(Ni),v.push(Ni),!Je&&pn&&Qt&&Qt.length>0){let _=yc(pn);if(_){Je=!0,gt=_.slice(0,120),zn=0,cn=!1,z(`${$.yellow} \u26A1 Root cause in model analysis: ${gt} \u2014 fix phase (read budget: 3)${$.reset}`);let b={role:"user",content:`[SYSTEM] Root cause identified: ${gt}. Read only the file that needs fixing, then edit it. Do not read other files.`};Y.push(b),v.push(b)}}if(!Qt||Qt.length===0){let _=(pn||"").trim().length>0||Vt.trim().length>0,b=!1;if(Nt&&_&&(Zr>=2?z(`${$.yellow} \u26A0 SSH permanently blocked after ${Zr} storm warnings \u2014 no further SSH calls allowed${$.reset}`):(Nt=!1,Ot=Ls-4,b=!0)),b&&_){let I=(pn||"").trim();if(I.endsWith("?")||/\b(Wo |Bitte |Kannst du|Soll ich)\b/.test(I.slice(-200))){let oe={role:"user",content:"[SYSTEM] Continue. Do not ask questions \u2014 implement the fix yourself using SSH. The server is at 94.130.37.43."};v.push(oe),Y.push(oe);continue}}if(!_&&S>0&&dt<bc-1){let I={role:"user",content:"[SYSTEM] You ran tools but produced no visible output. The user CANNOT see tool results \u2014 only your text. Please summarize your findings now."};v.push(I),Y.push(I);continue}let te=/keine.*Tool|can.?t use.*tool|Tool.?Budget|nicht.*zugreifen|cannot.*access|no.*tool.*access|keine.*Werkzeug|da ich keine.*kann/i;if(_&&dt<3&&te.test((pn||"").slice(0,600)))if(Sc&&Yn<=0||Nt){z(`${$.yellow} \u26A0 Tool avoidance (constrained context) \u2014 telling model to ask user${$.reset}`);let F={role:"user",content:"[SYSTEM] Correct \u2014 remote access is currently limited. Summarize what you have found so far and tell the user exactly what specific information (logs, process list, error output) you need from the server to continue."};v.push(F),Y.push(F);continue}else{z(`${$.yellow} \u26A0 Tool avoidance detected \u2014 nudging model to use tools${$.reset}`);let F={role:"user",content:"[SYSTEM] You have full tool access. Use your tools to investigate and implement the fix directly \u2014 do not say you cannot use tools. If SSH is needed, use a single targeted command that captures the most relevant information rather than multiple sequential calls."};v.push(F),Y.push(F);continue}if(Eo()&&_&&S===0)if(ni++,ni>2)z(`${$.yellow} \u26A0 Plan accepted despite no file reads (rejection loop cap reached)${$.reset}`);else{let I={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.).
|
|
1120
1120
|
|
|
1121
|
-
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.`};Y.push(I),
|
|
1121
|
+
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.`};Y.push(I),v.push(I),z(`${$.yellow} \u26A0 Plan rejected (${ni}/2): no files read \u2014 forcing investigation${$.reset}`);continue}if(Eo()&&_){let I=(pn||Vt||"").trim();wx(I),Qx(I);let F=bx(I);if(F.length>0){let oe=Y.find(K=>K.role==="user"),re=typeof oe?.content=="string"?oe.content.slice(0,120):"Task";_x(re,F);let he=F.length===1?"step":"steps",B=!1;if(process.stdout.isTTY&&process.stdin.isTTY){let{approvePlan:K,startExecution:ne,setPlanMode:ge}=Yt();process.stdout.write(`
|
|
1122
1122
|
${$.cyan}${$.bold}Plan ready${$.reset} ${$.dim}(${F.length} ${he})${$.reset} ${$.green}[A]${$.reset}${$.dim}pprove${$.reset} ${$.yellow}[E]${$.reset}${$.dim}dit${$.reset} ${$.red}[R]${$.reset}${$.dim}eject${$.reset} ${$.dim}[\u21B5 = approve]:${$.reset} `);let ee=process.stdin.isRaw,U=await new Promise($e=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",Tt=>{try{process.stdin.setRawMode(ee||!1)}catch{}let en=Tt.toString().toLowerCase()[0]||"\r";$e(en)})});if(process.stdout.write(`
|
|
1123
1123
|
`),U==="r")console.log(`${$.red}Plan rejected.${$.reset} Ask follow-up questions to refine.`);else if(U==="e")console.log(`${$.yellow}Type /plan edit to open in editor, or give feedback.${$.reset}`);else if(K()){ne(),ge(!1),xc(),console.log(`${$.green}${$.bold}Approved!${$.reset} Executing ${F.length} ${he}...`);let $e=`[PLAN APPROVED \u2014 EXECUTE NOW]
|
|
1124
1124
|
|
|
1125
1125
|
Implement the following plan step by step. All tools are now available.
|
|
1126
1126
|
|
|
1127
|
-
${I}`;Y.push({role:"user",content:$e}),
|
|
1127
|
+
${I}`;Y.push({role:"user",content:$e}),v.push({role:"user",content:$e}),B=!0}}else console.log(`
|
|
1128
1128
|
${$.cyan}${$.bold}Plan ready${$.reset} ${$.dim}(${F.length} ${he} extracted).${$.reset} Type ${$.cyan}/plan approve${$.reset}${$.dim} to execute, or ${$.reset}${$.cyan}/plan edit${$.reset}${$.dim} to review.${$.reset}`);if(B){u&&(u.stop(),u=null),dt--;continue}}else{let oe=!1;if(process.stdout.isTTY&&process.stdin.isTTY){let{approvePlan:re,startExecution:he,setPlanMode:B}=Yt();process.stdout.write(`
|
|
1129
1129
|
${$.cyan}${$.bold}Plan ready.${$.reset} ${$.green}[A]${$.reset}${$.dim}pprove${$.reset} ${$.red}[R]${$.reset}${$.dim}eject${$.reset} ${$.dim}[\u21B5 = approve]:${$.reset} `);let K=process.stdin.isRaw,ne=await new Promise(ge=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",ee=>{try{process.stdin.setRawMode(K||!1)}catch{}ge(ee.toString().toLowerCase()[0]||"\r")})});if(process.stdout.write(`
|
|
1130
1130
|
`),ne==="r")console.log(`${$.red}Plan rejected.${$.reset} Ask follow-up questions to refine.`);else if(re()){he(),B(!1),xc(),console.log(`${$.green}${$.bold}Approved!${$.reset} Executing...`);let ee=`[PLAN APPROVED \u2014 EXECUTE NOW]
|
|
1131
1131
|
|
|
1132
1132
|
Implement the following plan step by step. All tools are now available.
|
|
1133
1133
|
|
|
1134
|
-
${getPlanContent()||Bt.content}`;Y.push({role:"user",content:ee}),
|
|
1135
|
-
${$.cyan}${$.bold}Plan ready.${$.reset} ${$.dim}Type ${$.reset}${$.cyan}/plan approve${$.reset}${$.dim} to execute, or ask follow-up questions to refine.${$.reset}`);if(oe){u&&(u.stop(),u=null),dt--;continue}}}if(u&&(u.stop(),u=null),l(null),Ge(S,L,R,M,D),Mt&&R.size>=3){let I=[...R].map(B=>B.split("/").pop()).slice(0,8).join(", "),F=[...R].some(B=>B.endsWith("package.json")),oe=[...R].some(B=>B.endsWith("requirements.txt")),re=[...R].some(B=>B.endsWith("package-lock.json")||B.endsWith("yarn.lock")||B.endsWith("pnpm-lock.yaml")),he=F&&!re?"npm install not yet run":oe?"pip install not yet run":null;So=`[Previous session created ${R.size} files: ${I}`+(he?` \u2014 ${he}`:"")+". Use this context to answer follow-up questions without re-reading files.]"}if(Mt&&!Ec&&S>0){let I=[...R].some(ee=>ee.endsWith("package.json")),F=[...R].some(ee=>ee.endsWith("requirements.txt")||ee.endsWith("Pipfile")||ee.endsWith("pyproject.toml")),oe=[...R].some(ee=>ee.endsWith("package-lock.json")||ee.endsWith("yarn.lock")||ee.endsWith("pnpm-lock.yaml")),re=Y.flatMap(ee=>{let U=Array.isArray(ee.tool_calls)?ee.tool_calls:[],$e=Array.isArray(ee.content)?ee.content.filter(Tt=>Tt?.type==="tool_use"):[];return[...U,...$e]}).filter(ee=>{let U=ee.function?.name||ee.name||"";return U==="bash"||U==="Bash"}).map(ee=>{try{let U=ee.function?.arguments??ee.input??{};return(typeof U=="string"?JSON.parse(U):U)?.command||""}catch{return""}}),he=re.some(ee=>/pip\s+install|python\s+-m\s+venv/.test(ee)),B=re.some(ee=>/npm\s+install/.test(ee)),ne=[...R].some(ee=>/\/App\.(js|ts|jsx|tsx)$/.test(ee))&&!I&&!B;if(F&&!he||I&&!oe&&!B||ne){Ec=!0;let ee=[];F&&!he&&ee.push("python -m venv venv && source venv/bin/activate && pip install -r requirements.txt"),ne?ee.push("create package.json for the React frontend (with react, react-dom, react-scripts dependencies), then run npm install"):I&&!oe&&!B&&ee.push("npm install");let U=`[FRAMEWORK \u2014 post-creation check] You wrote dependency files but never ran the installer. Run now: ${ee.join(" && ")}. Verify it succeeds, fix any errors, then write a closing summary.`;z(`${$.dim} [post-creation] bootstrapping environment (${ee.join(", ")})${$.reset}`),Y.push({role:"user",content:U}),
|
|
1136
|
-
${re}`),Y.push({role:"user",content:I},{role:"assistant",content:re}))}catch{}Ke(Y),rm(Y);return}S++,S>=1&&(Te=!1);for(let _ of Qt){let b=_.function.name;L.set(b,(L.get(b)||0)+1)}let xe=await Promise.all(Qt.map(_=>ek(_)));{let _=Ut(k,st()),b=_.percentage,te=xe.some(re=>re.canExecute&&re.fnName==="read_file"&&!re.args?.line_end),I=xe.filter(re=>re.canExecute&&re.fnName==="read_file"&&re.args?.path&&ks(Fo,re.args.path)>=1&&!re.args?.line_start).map(re=>re.args.path.split("/").slice(-2).join("/")),F=I.length>0;if(b>=70&&te&&Si<70||b>=85&&Si<85||F){Si=b;let re=b>=85?"URGENT":"WARNING",he;F?(re="WARNING",he=`Full-file read of ${I.join(", ")} already done \u2014 use line_start/line_end for specific sections instead.`):te?he=`Unbounded read at ${Math.round(b)}% context \u2014 use line_start/line_end to avoid overflow.`:he="Use targeted reads (line_start/line_end) to save space.";let B={role:"user",content:`[SYSTEM ${re}] Context ${Math.round(b)}% used (${_.used}/${_.limit} tokens). ${he}`};if(Y.push(B),k.push(B),b>=85){let K=F?` (re-read of: ${I.join(", ")})`:"";z(`${$.yellow} \u26A0 Context ${Math.round(b)}% used \u2014 agent warned to use targeted reads${K}${$.reset}`)}}}let Mi=new Map;for(let _ of xe){if(!_.canExecute||_.fnName!=="read_file")continue;let b=_.args?.path;if(!b)continue;let te=ks(Fo,b),I=Mi.get(b)||0,F=te+I,oe=_.args?.line_start!=null,re=Gn.get(b)||0,he=re>0,B=2;if(F>=Ps){let K=b.split("/").slice(-2).join("/"),ne=(Cs.get(b)||0)+1;if(Cs.set(b,ne),ne===1)z(`${$.red} \u2716 Blocked: "${K}" read ${F}\xD7 \u2014 hard cap (${Ps}) reached${$.reset}`);else if(ne===2){z(`${$.red} \u2716 Escalated block: "${K}" \u2014 model ignored BLOCKED, injecting system warning${$.reset}`);let ge={role:"user",content:`[SYSTEM WARNING] You already received a BLOCKED error for read_file("${b}") and tried again anyway. This file has reached its read cap (${Ps}\xD7). Do NOT attempt to read it again. Use grep_search to find specific content, or proceed with what you already know.`};Y.push(ge),k.push(ge)}_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: read_file("${b}") denied \u2014 file already read ${F}\xD7 (hard cap: ${Ps}). You have seen enough of this file. Use grep to find specific content or proceed with what you know.`,tool_call_id:_.callId}}else if(F>=1&&oe)if(he&&re<=B){let K=b.split("/").slice(-2).join("/");console.log(`${$.cyan} \u21A9 Targeted re-read: "${K}" (line_start=${_.args.line_start}) \u2014 edit recovery #${re}${$.reset}`),Gn.set(b,re-1)}else if(he&&re>B){let K=b.split("/").slice(-2).join("/");z(`${$.red} \u2716 Edit recovery blocked: "${K}" \u2014 ${B} recovery reads already used. Use grep to find the exact line numbers, then retry.${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: read_file("${b}") denied \u2014 edit recovery budget exhausted (${B} recovery reads used). You already have the file content. Use grep_search to find the exact line numbers of the text you want to change, then retry edit_file with the exact text shown.`,tool_call_id:_.callId}}else{let K=_.args.line_start||1,ne=_.args.line_end||K+350,ge=Kn.get(b)||[],ee=!1;for(let[U,$e]of ge){let Tt=Math.max(K,U),en=Math.min(ne,$e);if(en>Tt){let tn=en-Tt,gl=ne-K||1,$l=$e-U||1,Pi=tn/$l>=.7&&tn/gl<.7;if(tn/gl>=.7||tn/$l>=.7){let Li=b.split("/").slice(-2).join("/"),yl=`${b}:${K}-${ne}`,Zn=(kc.get(yl)||0)+1;if(kc.set(yl,Zn),z(Pi?`${$.red} \u2716 Blocked superread: "${Li}" lines ${K}-${ne} subsumes already-read ${U}-${$e} \u2014 use line_start=${$e+1} to skip known content (block #${Zn})${$.reset}`:`${$.red} \u2716 Blocked duplicate read: "${Li}" lines ${K}-${ne} (\u226570% overlap with lines ${U}-${$e} already in context, block #${Zn})${$.reset}`),Zn>=2){z(`${$.red} \u2716 Escalated range-block: "${Li}" lines ${K}-${ne} \u2014 model ignored BLOCKED, injecting system warning${$.reset}`);let wl={role:"user",content:Pi?`[SYSTEM] Read blocked ${Zn}\xD7 for read_file("${b}", lines ${K}-${ne}). Lines ${U}-${$e} were already read. Use line_start=${$e+1} to read only new content, or use grep_search for specific lines.`:`[SYSTEM] Read blocked ${Zn}\xD7 for read_file("${b}", lines ${K}-${ne}). Lines ${U}-${$e} were already read and will NOT change. Use grep_search to find specific content instead.`};Y.push(wl),k.push(wl)}_.canExecute=!1,_.errorResult={role:"tool",content:Pi?`BLOCKED: read_file("${b}", lines ${K}-${ne}) re-reads lines ${U}-${$e} already in context. Use line_start=${$e+1} to read only the new content beyond line ${$e}.`:`BLOCKED: read_file("${b}", lines ${K}-${ne}) is a duplicate \u2014 lines ${U}-${$e} are already in your context (\u226570% overlap). Use grep to find specific content instead of re-reading.`,tool_call_id:_.callId},ee=!0;break}}}if(!ee){let U=ge.length,$e=3;if(U>=5){let en=b.split("/").slice(-2).join("/");z(`${$.red} \u2716 Blocked file-scroll: "${en}" \u2014 ${U} sections already read. Use grep to find specific content.${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: read_file("${b}") denied \u2014 you have already read ${U} 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:_.callId}}else U>=$e&&(_._scrollWarn={sectionCount:U+1,path:b})}}else if(F>=1){let K=b.split("/").slice(-2).join("/"),ne=(Cs.get(b)||0)+1;if(Cs.set(b,ne),ne===1)z(`${$.red} \u2716 Blocked unbounded re-read: "${K}" \u2014 already in context. Use line_start/line_end for specific sections.${$.reset}`);else if(ne===2){z(`${$.red} \u2716 Escalated block: "${K}" \u2014 model ignored unbounded re-read block, injecting system warning${$.reset}`);let ge={role:"user",content:`[SYSTEM] read_file("${b}") was blocked again \u2014 full-file reads are disabled after the first read. Use line_start/line_end for a specific section, or use grep_search to find what you need.`};Y.push(ge),k.push(ge)}_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: read_file("${b}") denied \u2014 file already in context (read ${F}\xD7). Use line_start/line_end to read a specific section instead of the full file.`,tool_call_id:_.callId}}_.canExecute&&Mi.set(b,(Mi.get(b)||0)+1)}for(let _ of xe){if(!_.canExecute||_.fnName!=="bash")continue;let b=(_.args?.command||"").trim();if(/^\s*ls(\s+-[a-zA-Z]+)*(\s+\S+)?\s*$/.test(b)&&!/npm|yarn|pnpm|make|git/.test(b)){z(`${$.red} \u2716 Blocked bash ls \u2014 use list_directory tool instead${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:'BLOCKED: bash("ls ...") denied \u2014 use the list_directory tool instead. It returns structured output and does not penalize the session score.',tool_call_id:_.callId};continue}/\bfind\s+[\S.]/.test(b)&&!/git\s|npm\s|yarn\s|-exec\s+\S|-execdir/.test(b)&&(z(`${$.red} \u2716 Blocked bash find \u2014 use glob tool with a pattern instead${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:'BLOCKED: bash("find ...") denied \u2014 use the glob tool with a pattern like "**/*.py" or "src/**/*.js" instead. It is faster and does not penalize the session score.',tool_call_id:_.callId})}for(let _ of xe)_.canExecute&&(_.fnName!=="ssh_exec"&&_.fnName!=="bash"||/\bsed\s+-n\b/.test(_.args?.command||"")&&(z(`${$.red} \u2716 Blocked sed -n: use grep -n "pattern" <file> | head -30 instead${$.reset}`),_.canExecute=!1,_.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:_.callId}));for(let _ of xe){if(!_.canExecute||_.fnName!=="write_file")continue;let b=_.args?.path,te=_.args?.content||"";if(b)try{let I=require("fs"),F=require("path").resolve(process.cwd(),b);if(I.existsSync(F)){let oe=I.statSync(F).size,re=Buffer.byteLength(te,"utf8"),he=oe>0?re/oe:1;if(he<.6&&oe>200){let B=b.split("/").slice(-2).join("/");console.log(`${$.red} \u2716 write_file shrink guard: "${B}" would shrink to ${Math.round(he*100)}% of original \u2014 likely context loss${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: write_file("${b}") denied \u2014 new content is only ${Math.round(he*100)}% of current file size (${oe} \u2192 ${re} 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:_.callId}}}}catch{}}let fl=new Map;for(let _ of xe){if(!_.canExecute||_.fnName!=="grep")continue;let b=_.args?.path;if(!b)continue;let te=fl.get(b)||0,I=ks(qo,b)+te;if(I>=il){let F=b.split("/").slice(-2).join("/");z(`${$.red} \u2716 Blocked grep: "${F}" grepped ${I}\xD7 with different patterns \u2014 flood threshold exceeded${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: grep("${b}") denied \u2014 ${I} patterns already tried. Use existing results or read the file instead.`,tool_call_id:_.callId}}_.canExecute&&fl.set(b,te+1)}let rg=3,pl=new Map;for(let _ of xe){if(!_.canExecute||_.fnName!=="ssh_exec")continue;let te=(_.args?.command||"").replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),I=pl.get(te)||0,F=ks(me,te)+I;F>=rg&&(z(`${$.yellow} \u26A0 Blocked ssh_exec: same command run ${F}\xD7 \u2014 result already in context${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: ssh_exec denied \u2014 this command has already run ${F} times and the output is in your context. Use existing results to proceed or try a different command.`,tool_call_id:_.callId}),_.canExecute&&pl.set(te,I+1)}if(Nt){let _=xe.filter(I=>I.canExecute&&I.fnName==="ssh_exec"),b=xe.some(I=>I.canExecute&&I.fnName!=="ssh_exec"),te=Ee&&Me<3;if(_.length>0&&!b&&te&&oi<1)Nt=!1,oi++,Ot=Math.max(0,Ls-2),z(`${$.dim} [dual-block deadlock: SSH storm relaxed \u2014 allowing 1 SSH call (relax ${oi}/1)]${$.reset}`);else for(let I of _)I.canExecute=!1,I.errorResult={role:"tool",content:Je?`BLOCKED: ssh_exec denied \u2014 SSH paused (${Ls}+ calls). Root cause is known (${gt}). Edit the file now.`:`BLOCKED: ssh_exec denied \u2014 SSH temporarily paused (${Ls}+ calls). Provide a text summary of your findings first. Do NOT ask the user to run commands. SSH re-enables after your summary.`,tool_call_id:I.callId}}if(Ee&&Me<3&&!Nt){for(let _ of xe)if(_.canExecute&&["bash","read_file","find_files"].includes(_.fnName)){Me++;{let b=st(),{messages:te}=zt(k,b);k=te}z(`${$.yellow} \u26A0 Jarvis-local guard: blocking local ${_.fnName} \u2014 use ssh_exec on 94.130.37.43${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: ${_.fnName} denied \u2014 this is a server issue. Use ssh_exec on 94.130.37.43 instead.`,tool_call_id:_.callId};break}}if(cn&&Mt&&Xt>=1){let _=["read_file","grep","search_files","glob","list_directory","find_files"];for(let b of xe)b.canExecute&&_.includes(b.fnName)&&(z(`${$.red} \u2716 Creation hard-block: ${b.fnName} denied \u2014 cap fired, files already written${$.reset}`),b.canExecute=!1,b.errorResult={role:"tool",content:"BLOCKED: files already written \u2014 continue with write_file or edit_file to finish the remaining tasks. Do not read more files.",tool_call_id:b.callId})}if(Yn>=0){let _=xe.filter(b=>b.canExecute).length;if(_>0&&(Yn-=_,Yn<0))if(!ii&&R.size>ri){ii=!0,Yn=5,z(`${$.green} \u2713 Post-wipe progress detected (${R.size-ri} files modified) \u2014 granting 5 bonus tool calls${$.reset}`);let b={role:"user",content:"[SYSTEM] Progress detected \u2014 5 bonus tool calls granted. Budget: 5 remaining."};Y.push(b),k.push(b)}else{z(`${$.red} \u2716 Post-wipe tool budget exhausted \u2014 blocking all tool calls${$.reset}`);for(let te of xe)te.canExecute&&(te.canExecute=!1,te.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:te.callId});let b={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."};Y.push(b),k.push(b)}}let Is=u?{skipSpinner:!0,skipSummaries:!0}:{},ig=xe.some(_=>_.fnName==="ask_user"),ml=!Is.skipSummaries&&!Te,Ko=null;ml&&!ig?(Te=!0,Is.skipSpinner=!0,process.stdout.isTTY?(process.stdout.write(Jr(xe,S,!1,"blink")),Ko=!0):Jt||process.stdout.write(Jr(xe,S,!1)+`
|
|
1137
|
-
`)):ml&&(Te=!0,Is.skipSpinner=!0),u&&u._paused&&u.resume();let Go=null;if(Ko&&process.stdout.isTTY&&xe.some(b=>b.canExecute&&(b.fnName==="bash"||b.fnName==="ssh_exec"))){let b=Date.now();Go=setInterval(()=>{let te=Math.round((Date.now()-b)/1e3);te>=3&&process.stdout.write(`\r\x1B[2K${Jr(xe,S,!1,"blink")} ${$.dim}[${te}s]${$.reset}`)},1e3)}let{results:Tn,summaries:ag}=await
|
|
1134
|
+
${getPlanContent()||Bt.content}`;Y.push({role:"user",content:ee}),v.push({role:"user",content:ee}),oe=!0}}else console.log(`
|
|
1135
|
+
${$.cyan}${$.bold}Plan ready.${$.reset} ${$.dim}Type ${$.reset}${$.cyan}/plan approve${$.reset}${$.dim} to execute, or ask follow-up questions to refine.${$.reset}`);if(oe){u&&(u.stop(),u=null),dt--;continue}}}if(u&&(u.stop(),u=null),l(null),Ge(S,L,R,M,D),Mt&&R.size>=3){let I=[...R].map(B=>B.split("/").pop()).slice(0,8).join(", "),F=[...R].some(B=>B.endsWith("package.json")),oe=[...R].some(B=>B.endsWith("requirements.txt")),re=[...R].some(B=>B.endsWith("package-lock.json")||B.endsWith("yarn.lock")||B.endsWith("pnpm-lock.yaml")),he=F&&!re?"npm install not yet run":oe?"pip install not yet run":null;So=`[Previous session created ${R.size} files: ${I}`+(he?` \u2014 ${he}`:"")+". Use this context to answer follow-up questions without re-reading files.]"}if(Mt&&!Ec&&S>0){let I=[...R].some(ee=>ee.endsWith("package.json")),F=[...R].some(ee=>ee.endsWith("requirements.txt")||ee.endsWith("Pipfile")||ee.endsWith("pyproject.toml")),oe=[...R].some(ee=>ee.endsWith("package-lock.json")||ee.endsWith("yarn.lock")||ee.endsWith("pnpm-lock.yaml")),re=Y.flatMap(ee=>{let U=Array.isArray(ee.tool_calls)?ee.tool_calls:[],$e=Array.isArray(ee.content)?ee.content.filter(Tt=>Tt?.type==="tool_use"):[];return[...U,...$e]}).filter(ee=>{let U=ee.function?.name||ee.name||"";return U==="bash"||U==="Bash"}).map(ee=>{try{let U=ee.function?.arguments??ee.input??{};return(typeof U=="string"?JSON.parse(U):U)?.command||""}catch{return""}}),he=re.some(ee=>/pip\s+install|python\s+-m\s+venv/.test(ee)),B=re.some(ee=>/npm\s+install/.test(ee)),ne=[...R].some(ee=>/\/App\.(js|ts|jsx|tsx)$/.test(ee))&&!I&&!B;if(F&&!he||I&&!oe&&!B||ne){Ec=!0;let ee=[];F&&!he&&ee.push("python -m venv venv && source venv/bin/activate && pip install -r requirements.txt"),ne?ee.push("create package.json for the React frontend (with react, react-dom, react-scripts dependencies), then run npm install"):I&&!oe&&!B&&ee.push("npm install");let U=`[FRAMEWORK \u2014 post-creation check] You wrote dependency files but never ran the installer. Run now: ${ee.join(" && ")}. Verify it succeeds, fix any errors, then write a closing summary.`;z(`${$.dim} [post-creation] bootstrapping environment (${ee.join(", ")})${$.reset}`),Y.push({role:"user",content:U}),v.push({role:"user",content:U});continue}}if(S>0&&!n._isSummaryTurn&&ux(pn))try{z(`${$.dim} [post-turn] terse ending \u2014 requesting diagnosis/summary${$.reset}`);let I=R.size>0?"Write a closing summary (3+ sentences): what files changed and why, what the result is, anything the user should know or do next.":"Write a closing diagnosis (3+ sentences): what you investigated, what you found, and what the user should do next or what the root cause is.",F=[...v,{role:"user",content:I}],re=((await om(F,[],{}))?.content||"").trim();re&&(console.log(`
|
|
1136
|
+
${re}`),Y.push({role:"user",content:I},{role:"assistant",content:re}))}catch{}Ke(Y),rm(Y);return}S++,S>=1&&(Te=!1);for(let _ of Qt){let b=_.function.name;L.set(b,(L.get(b)||0)+1)}let xe=await Promise.all(Qt.map(_=>ev(_)));{let _=Ut(v,st()),b=_.percentage,te=xe.some(re=>re.canExecute&&re.fnName==="read_file"&&!re.args?.line_end),I=xe.filter(re=>re.canExecute&&re.fnName==="read_file"&&re.args?.path&&vs(Fo,re.args.path)>=1&&!re.args?.line_start).map(re=>re.args.path.split("/").slice(-2).join("/")),F=I.length>0;if(b>=70&&te&&Si<70||b>=85&&Si<85||F){Si=b;let re=b>=85?"URGENT":"WARNING",he;F?(re="WARNING",he=`Full-file read of ${I.join(", ")} already done \u2014 use line_start/line_end for specific sections instead.`):te?he=`Unbounded read at ${Math.round(b)}% context \u2014 use line_start/line_end to avoid overflow.`:he="Use targeted reads (line_start/line_end) to save space.";let B={role:"user",content:`[SYSTEM ${re}] Context ${Math.round(b)}% used (${_.used}/${_.limit} tokens). ${he}`};if(Y.push(B),v.push(B),b>=85){let K=F?` (re-read of: ${I.join(", ")})`:"";z(`${$.yellow} \u26A0 Context ${Math.round(b)}% used \u2014 agent warned to use targeted reads${K}${$.reset}`)}}}let Mi=new Map;for(let _ of xe){if(!_.canExecute||_.fnName!=="read_file")continue;let b=_.args?.path;if(!b)continue;let te=vs(Fo,b),I=Mi.get(b)||0,F=te+I,oe=_.args?.line_start!=null,re=Gn.get(b)||0,he=re>0,B=2;if(F>=Ps){let K=b.split("/").slice(-2).join("/"),ne=(Cs.get(b)||0)+1;if(Cs.set(b,ne),ne===1)z(`${$.red} \u2716 Blocked: "${K}" read ${F}\xD7 \u2014 hard cap (${Ps}) reached${$.reset}`);else if(ne===2){z(`${$.red} \u2716 Escalated block: "${K}" \u2014 model ignored BLOCKED, injecting system warning${$.reset}`);let ge={role:"user",content:`[SYSTEM WARNING] You already received a BLOCKED error for read_file("${b}") and tried again anyway. This file has reached its read cap (${Ps}\xD7). Do NOT attempt to read it again. Use grep_search to find specific content, or proceed with what you already know.`};Y.push(ge),v.push(ge)}_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: read_file("${b}") denied \u2014 file already read ${F}\xD7 (hard cap: ${Ps}). You have seen enough of this file. Use grep to find specific content or proceed with what you know.`,tool_call_id:_.callId}}else if(F>=1&&oe)if(he&&re<=B){let K=b.split("/").slice(-2).join("/");console.log(`${$.cyan} \u21A9 Targeted re-read: "${K}" (line_start=${_.args.line_start}) \u2014 edit recovery #${re}${$.reset}`),Gn.set(b,re-1)}else if(he&&re>B){let K=b.split("/").slice(-2).join("/");z(`${$.red} \u2716 Edit recovery blocked: "${K}" \u2014 ${B} recovery reads already used. Use grep to find the exact line numbers, then retry.${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: read_file("${b}") denied \u2014 edit recovery budget exhausted (${B} recovery reads used). You already have the file content. Use grep_search to find the exact line numbers of the text you want to change, then retry edit_file with the exact text shown.`,tool_call_id:_.callId}}else{let K=_.args.line_start||1,ne=_.args.line_end||K+350,ge=Kn.get(b)||[],ee=!1;for(let[U,$e]of ge){let Tt=Math.max(K,U),en=Math.min(ne,$e);if(en>Tt){let tn=en-Tt,gl=ne-K||1,$l=$e-U||1,Pi=tn/$l>=.7&&tn/gl<.7;if(tn/gl>=.7||tn/$l>=.7){let Li=b.split("/").slice(-2).join("/"),yl=`${b}:${K}-${ne}`,Zn=(vc.get(yl)||0)+1;if(vc.set(yl,Zn),z(Pi?`${$.red} \u2716 Blocked superread: "${Li}" lines ${K}-${ne} subsumes already-read ${U}-${$e} \u2014 use line_start=${$e+1} to skip known content (block #${Zn})${$.reset}`:`${$.red} \u2716 Blocked duplicate read: "${Li}" lines ${K}-${ne} (\u226570% overlap with lines ${U}-${$e} already in context, block #${Zn})${$.reset}`),Zn>=2){z(`${$.red} \u2716 Escalated range-block: "${Li}" lines ${K}-${ne} \u2014 model ignored BLOCKED, injecting system warning${$.reset}`);let wl={role:"user",content:Pi?`[SYSTEM] Read blocked ${Zn}\xD7 for read_file("${b}", lines ${K}-${ne}). Lines ${U}-${$e} were already read. Use line_start=${$e+1} to read only new content, or use grep_search for specific lines.`:`[SYSTEM] Read blocked ${Zn}\xD7 for read_file("${b}", lines ${K}-${ne}). Lines ${U}-${$e} were already read and will NOT change. Use grep_search to find specific content instead.`};Y.push(wl),v.push(wl)}_.canExecute=!1,_.errorResult={role:"tool",content:Pi?`BLOCKED: read_file("${b}", lines ${K}-${ne}) re-reads lines ${U}-${$e} already in context. Use line_start=${$e+1} to read only the new content beyond line ${$e}.`:`BLOCKED: read_file("${b}", lines ${K}-${ne}) is a duplicate \u2014 lines ${U}-${$e} are already in your context (\u226570% overlap). Use grep to find specific content instead of re-reading.`,tool_call_id:_.callId},ee=!0;break}}}if(!ee){let U=ge.length,$e=3;if(U>=5){let en=b.split("/").slice(-2).join("/");z(`${$.red} \u2716 Blocked file-scroll: "${en}" \u2014 ${U} sections already read. Use grep to find specific content.${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: read_file("${b}") denied \u2014 you have already read ${U} 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:_.callId}}else U>=$e&&(_._scrollWarn={sectionCount:U+1,path:b})}}else if(F>=1){let K=b.split("/").slice(-2).join("/"),ne=(Cs.get(b)||0)+1;if(Cs.set(b,ne),ne===1)z(`${$.red} \u2716 Blocked unbounded re-read: "${K}" \u2014 already in context. Use line_start/line_end for specific sections.${$.reset}`);else if(ne===2){z(`${$.red} \u2716 Escalated block: "${K}" \u2014 model ignored unbounded re-read block, injecting system warning${$.reset}`);let ge={role:"user",content:`[SYSTEM] read_file("${b}") was blocked again \u2014 full-file reads are disabled after the first read. Use line_start/line_end for a specific section, or use grep_search to find what you need.`};Y.push(ge),v.push(ge)}_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: read_file("${b}") denied \u2014 file already in context (read ${F}\xD7). Use line_start/line_end to read a specific section instead of the full file.`,tool_call_id:_.callId}}_.canExecute&&Mi.set(b,(Mi.get(b)||0)+1)}for(let _ of xe){if(!_.canExecute||_.fnName!=="bash")continue;let b=(_.args?.command||"").trim();if(/^\s*ls(\s+-[a-zA-Z]+)*(\s+\S+)?\s*$/.test(b)&&!/npm|yarn|pnpm|make|git/.test(b)){z(`${$.red} \u2716 Blocked bash ls \u2014 use list_directory tool instead${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:'BLOCKED: bash("ls ...") denied \u2014 use the list_directory tool instead. It returns structured output and does not penalize the session score.',tool_call_id:_.callId};continue}/\bfind\s+[\S.]/.test(b)&&!/git\s|npm\s|yarn\s|-exec\s+\S|-execdir/.test(b)&&(z(`${$.red} \u2716 Blocked bash find \u2014 use glob tool with a pattern instead${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:'BLOCKED: bash("find ...") denied \u2014 use the glob tool with a pattern like "**/*.py" or "src/**/*.js" instead. It is faster and does not penalize the session score.',tool_call_id:_.callId})}for(let _ of xe)_.canExecute&&(_.fnName!=="ssh_exec"&&_.fnName!=="bash"||/\bsed\s+-n\b/.test(_.args?.command||"")&&(z(`${$.red} \u2716 Blocked sed -n: use grep -n "pattern" <file> | head -30 instead${$.reset}`),_.canExecute=!1,_.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:_.callId}));for(let _ of xe){if(!_.canExecute||_.fnName!=="write_file")continue;let b=_.args?.path,te=_.args?.content||"";if(b)try{let I=require("fs"),F=require("path").resolve(process.cwd(),b);if(I.existsSync(F)){let oe=I.statSync(F).size,re=Buffer.byteLength(te,"utf8"),he=oe>0?re/oe:1;if(he<.6&&oe>200){let B=b.split("/").slice(-2).join("/");console.log(`${$.red} \u2716 write_file shrink guard: "${B}" would shrink to ${Math.round(he*100)}% of original \u2014 likely context loss${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: write_file("${b}") denied \u2014 new content is only ${Math.round(he*100)}% of current file size (${oe} \u2192 ${re} 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:_.callId}}}}catch{}}let fl=new Map;for(let _ of xe){if(!_.canExecute||_.fnName!=="grep")continue;let b=_.args?.path;if(!b)continue;let te=fl.get(b)||0,I=vs(qo,b)+te;if(I>=il){let F=b.split("/").slice(-2).join("/");z(`${$.red} \u2716 Blocked grep: "${F}" grepped ${I}\xD7 with different patterns \u2014 flood threshold exceeded${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: grep("${b}") denied \u2014 ${I} patterns already tried. Use existing results or read the file instead.`,tool_call_id:_.callId}}_.canExecute&&fl.set(b,te+1)}let rg=3,pl=new Map;for(let _ of xe){if(!_.canExecute||_.fnName!=="ssh_exec")continue;let te=(_.args?.command||"").replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),I=pl.get(te)||0,F=vs(me,te)+I;F>=rg&&(z(`${$.yellow} \u26A0 Blocked ssh_exec: same command run ${F}\xD7 \u2014 result already in context${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: ssh_exec denied \u2014 this command has already run ${F} times and the output is in your context. Use existing results to proceed or try a different command.`,tool_call_id:_.callId}),_.canExecute&&pl.set(te,I+1)}if(Nt){let _=xe.filter(I=>I.canExecute&&I.fnName==="ssh_exec"),b=xe.some(I=>I.canExecute&&I.fnName!=="ssh_exec"),te=Ee&&Me<3;if(_.length>0&&!b&&te&&oi<1)Nt=!1,oi++,Ot=Math.max(0,Ls-2),z(`${$.dim} [dual-block deadlock: SSH storm relaxed \u2014 allowing 1 SSH call (relax ${oi}/1)]${$.reset}`);else for(let I of _)I.canExecute=!1,I.errorResult={role:"tool",content:Je?`BLOCKED: ssh_exec denied \u2014 SSH paused (${Ls}+ calls). Root cause is known (${gt}). Edit the file now.`:`BLOCKED: ssh_exec denied \u2014 SSH temporarily paused (${Ls}+ calls). Provide a text summary of your findings first. Do NOT ask the user to run commands. SSH re-enables after your summary.`,tool_call_id:I.callId}}if(Ee&&Me<3&&!Nt){for(let _ of xe)if(_.canExecute&&["bash","read_file","find_files"].includes(_.fnName)){Me++;{let b=st(),{messages:te}=zt(v,b);v=te}z(`${$.yellow} \u26A0 Jarvis-local guard: blocking local ${_.fnName} \u2014 use ssh_exec on 94.130.37.43${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: ${_.fnName} denied \u2014 this is a server issue. Use ssh_exec on 94.130.37.43 instead.`,tool_call_id:_.callId};break}}if(cn&&Mt&&Xt>=1){let _=["read_file","grep","search_files","glob","list_directory","find_files"];for(let b of xe)b.canExecute&&_.includes(b.fnName)&&(z(`${$.red} \u2716 Creation hard-block: ${b.fnName} denied \u2014 cap fired, files already written${$.reset}`),b.canExecute=!1,b.errorResult={role:"tool",content:"BLOCKED: files already written \u2014 continue with write_file or edit_file to finish the remaining tasks. Do not read more files.",tool_call_id:b.callId})}if(Yn>=0){let _=xe.filter(b=>b.canExecute).length;if(_>0&&(Yn-=_,Yn<0))if(!ii&&R.size>ri){ii=!0,Yn=5,z(`${$.green} \u2713 Post-wipe progress detected (${R.size-ri} files modified) \u2014 granting 5 bonus tool calls${$.reset}`);let b={role:"user",content:"[SYSTEM] Progress detected \u2014 5 bonus tool calls granted. Budget: 5 remaining."};Y.push(b),v.push(b)}else{z(`${$.red} \u2716 Post-wipe tool budget exhausted \u2014 blocking all tool calls${$.reset}`);for(let te of xe)te.canExecute&&(te.canExecute=!1,te.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:te.callId});let b={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."};Y.push(b),v.push(b)}}let Is=u?{skipSpinner:!0,skipSummaries:!0}:{},ig=xe.some(_=>_.fnName==="ask_user"),ml=!Is.skipSummaries&&!Te,Ko=null;ml&&!ig?(Te=!0,Is.skipSpinner=!0,process.stdout.isTTY?(process.stdout.write(Jr(xe,S,!1,"blink")),Ko=!0):Jt||process.stdout.write(Jr(xe,S,!1)+`
|
|
1137
|
+
`)):ml&&(Te=!0,Is.skipSpinner=!0),u&&u._paused&&u.resume();let Go=null;if(Ko&&process.stdout.isTTY&&xe.some(b=>b.canExecute&&(b.fnName==="bash"||b.fnName==="ssh_exec"))){let b=Date.now();Go=setInterval(()=>{let te=Math.round((Date.now()-b)/1e3);te>=3&&process.stdout.write(`\r\x1B[2K${Jr(xe,S,!1,"blink")} ${$.dim}[${te}s]${$.reset}`)},1e3)}let{results:Tn,summaries:ag}=await ov(xe,!0,{...Is,skipSummaries:!0});if(Go&&(clearInterval(Go),Go=null),Ko&&(Ko=null,process.stdout.write(`\r\x1B[2K${Jr(xe,S,!1)}
|
|
1138
1138
|
`)),!Is.skipSummaries){let _=ag.filter((I,F)=>!(xe[F]&&xe[F].fnName==="ask_user"));for(let I of _)console.log(I);console.log("");let b=xe.filter(I=>I&&I.fnName!=="ask_user").map(I=>I.fnName),te=q.record(0,b,M,R);te&&Ix(te)}for(let _ of xe){if(_.canExecute||!_.errorResult)continue;let b=typeof _.errorResult.content=="string"?_.errorResult.content:"";if((b.startsWith("BLOCKED:")||b.startsWith("PLAN MODE:"))&&(Sn++,Sn>=al)){z(`${$.red} \u2716 Loop abort: ${Sn} consecutive blocked calls (pre-execution) \u2014 model not heeding BLOCKED messages${$.reset}`),u&&(u.stop(),u=null),l(null),Ge(S,L,R,M,D,{suppressHint:!0}),Ke(Y);return}}for(let _=0;_<xe.length;_++){let b=xe[_];if(!b.canExecute)continue;let te=Tn[_].content,I=te.split(`
|
|
1139
|
-
`)[0],F=!I.startsWith("ERROR")&&!I.startsWith("CANCELLED")&&!I.startsWith("Command failed")&&!I.startsWith("EXIT");if(!F&&(b.fnName==="edit_file"||b.fnName==="patch_file")&&b.args?.path&&I.includes("old_text not found")){let B=Gn.get(b.args.path)||0;Gn.set(b.args.path,B+1)}if(F&&b.fnName==="write_file"&&b.args?.path){let B=b.args.path.split("/").pop(),K=b.args.path.includes("/tests/")||b.args.path.includes("\\tests\\");if(/^(test_|demo_|temp_|tmp_|scratch_)/.test(B)&&!K){z(`${$.yellow} \u26A0 Temp file: "${B}" \u2014 delete with bash rm when done to keep the workspace clean${$.reset}`);let ge={role:"user",content:`[HINT] "${b.args.path}" looks like a temporary test/demo file. Delete it with bash("rm ${b.args.path}") as soon as you're done \u2014 orphaned temp files count against session quality.`};Y.push(ge),k.push(ge)}}if(F&&["write_file","edit_file","patch_file"].includes(b.fnName)&&b.args&&b.args.path){Gn.delete(b.args.path),R.add(b.args.path);let B=bo(Z,b.args.path),K=b.args.path.split("/").slice(-2).join("/");if(B===ce){z(`${$.yellow} \u26A0 Loop warning: "${K}" edited ${B}\xD7 \u2014 possible edit loop${$.reset}`);let ne={role:"user",content:`[SYSTEM WARNING] "${b.args.path}" edited ${B}\xD7. One more edit max, then move on.`};Y.push(ne),k.push(ne)}else if(B>=se){z(`${$.red} \u2716 Loop abort: "${K}" edited ${B}\xD7 \u2014 aborting to prevent runaway loop${$.reset}`),u&&(u.stop(),u=null),l(null),Ge(S,L,R,M,D,{suppressHint:!0}),Ke(Y);return}}if(F&&b.canExecute){let B=["read_file","grep","search_files","glob","list_directory","ssh_exec","find_files"];["write_file","edit_file","patch_file"].includes(b.fnName)?(zn=0,cn=!1,Xt++):B.includes(b.fnName)&&zn++;let ne=o.postEditCap,ge=Je?3:Mt?Xt>0?2:4:Xt>0?ne:og;if(cn&&(Je||Mt&&Xt>=1)&&B.includes(b.fnName)){let U=Je?`root cause already identified (${gt})`:`${Xt} file edit(s) already made`;z(`${$.red} \u2716 Blocked read-only tool: cap fired, ${U}${$.reset}`),b.canExecute=!1,b.errorResult={role:"tool",content:Je?`BLOCKED: root cause already identified (${gt}). Use edit_file to fix the issue \u2014 do not read more files.`:Mt?"BLOCKED: files already written \u2014 continue with write_file or edit_file to finish the remaining tasks. Do not read more files.":`BLOCKED: ${Xt} file edit(s) already made and post-edit investigation cap reached. The fix is in place. Do not read more files \u2014 proceed with the task.`,tool_call_id:b.callId}}else if(zn>=ge&&!cn){cn=!0,z(`${$.yellow} \u26A0 Investigation cap: ${zn} read-only calls without an edit \u2014 forcing implementation${$.reset}`);let U;Je?U=`[SYSTEM] Root cause was already identified (${gt}). Edit the file now \u2014 do not read more files.`:Nt?U="[SYSTEM] SSH temporarily paused. Summarize your findings and state the likely diagnosis. Do NOT ask the user to run commands \u2014 SSH re-enables after your summary.":U="[SYSTEM] You have read enough files. Now implement your fix using edit_file.";let $e={role:"user",content:U};Y.push($e),k.push($e)}}if((b.fnName==="bash"||b.fnName==="ssh_exec")&&b.args&&b.args.command){let B=b.args.command.replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),K=bo(me,B);if(K===ve){z(`${$.yellow} \u26A0 Loop warning: same bash command run ${K}\xD7 \u2014 possible debug loop${$.reset}`);let ne={role:"user",content:`[SYSTEM WARNING] Same bash command ${K}\xD7. Debug loop detected \u2014 try a different approach.`};Y.push(ne),k.push(ne)}else if(K>=Qe){z(`${$.red} \u2716 Loop abort: same bash command run ${K}\xD7 \u2014 aborting runaway debug loop${$.reset}`),u&&(u.stop(),u=null),l(null),Ge(S,L,R,M,D,{suppressHint:!0}),Ke(Y);return}}if(b.fnName==="ssh_exec"){if(Ot++,Ot>=sg){z(`${$.red} \u2716 SSH storm abort: ${Ot} consecutive ssh_exec calls \u2014 aborting${$.reset}`),u&&(u.stop(),u=null),l(null),Ge(S,L,R,M,D,{suppressHint:!0}),Ke(Y);return}else if(Ot===Ls){{let ne=st(),{messages:ge}=zt(k,ne);k=ge}Nt=!0,Zr++,z(`${$.yellow} \u26A0 SSH storm warning (#${Zr}): ${Ot} consecutive ssh_exec calls \u2014 blocking further SSH${$.reset}`);let K={role:"user",content:Je?`[SYSTEM WARNING] ${Ot} consecutive SSH calls. Root cause identified (${gt}). Read the file that needs fixing, then edit it.`:`[SYSTEM WARNING] ${Ot} consecutive SSH calls \u2014 SSH temporarily paused for synthesis. Summarize what you found and state the likely diagnosis. Do NOT ask the user to run commands or provide logs. SSH will be re-enabled after your summary so you can continue.`};Y.push(K),k.push(K)}}else b.canExecute&&(Ot=0);if(F&&b.fnName==="grep"&&b.args&&b.args.pattern){let B=`${b.args.pattern}|${b.args.path||""}`,K=bo(ze,B);if(K===fn){z(`${$.yellow} \u26A0 Loop warning: grep pattern "${b.args.pattern.slice(0,40)}" run ${K}\xD7 \u2014 possible search loop${$.reset}`);let ne={role:"user",content:`[SYSTEM WARNING] Same grep pattern ${K}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};Y.push(ne),k.push(ne)}else if(K>=vi){z(`${$.red} \u2716 Loop abort: grep pattern run ${K}\xD7 \u2014 aborting runaway search loop${$.reset}`),u&&(u.stop(),u=null),l(null),Ge(S,L,R,M,D,{suppressHint:!0}),Ke(Y);return}if(b.args.path){let ne=bo(qo,b.args.path),ge=ks(Fo,b.args.path)>=1;if(ne===(ge?1:Jh)){let U=b.args.path.split("/").slice(-2).join("/");z(`${$.yellow} \u26A0 Loop warning: "${U}" grepped ${ne}\xD7 with different patterns \u2014 context flood risk${$.reset}`);let $e={role:"user",content:ge?`[SYSTEM NOTE] "${b.args.path}" was already fully read \u2014 its content is in context. Grepping it again is redundant; use the context you already have.`:`[SYSTEM NOTE] "${b.args.path}" grepped ${ne}\xD7 \u2014 use the search results already in context instead of searching again.`};Y.push($e),k.push($e)}}}let oe=(b.args?.command||b.args?.cmd||b.args?.script||"").toLowerCase(),re=/\b(health|healthcheck|health-check|status|check|ping|validate|alive|ready)\b/.test(oe)||/\/(health|status|ping|ready|alive)\b/.test(oe);if(F&&(b.fnName==="bash"||b.fnName==="ssh_exec")&&re&&te.includes('"valid":true')){{let K=st();if(Ut(k,K).percentage>=60){let{messages:ge,tokensRemoved:ee}=zt(k,K);ee>0&&(k=ge,console.log(`${$.dim} [pre-stop-compress \u2014 ~${ee} tokens freed before STOP injection, now ${Math.round(Ut(k,K).percentage)}%]${$.reset}`))}}let B={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.'};Y.push(B),k.push(B),console.log(`${$.cyan} \u2713 Health-check stop signal detected \u2014 injecting STOP instruction${$.reset}`)}if(te.startsWith("BLOCKED:")){if(Sn++,Sn>=al){z(`${$.red} \u2716 Loop abort: ${Sn} consecutive blocked calls \u2014 model not heeding BLOCKED messages${$.reset}`),u&&(u.stop(),u=null),l(null),Ge(S,L,R,M,D,{suppressHint:!0}),Ke(Y);return}}else Sn=0;if(F)vn=0,Ti=!0;else if(vn++,vn===Qh){z(`${$.yellow} \u26A0 Loop warning: ${vn} consecutive tool errors \u2014 possible stuck loop${$.reset}`);let B={role:"user",content:`[SYSTEM WARNING] ${vn} consecutive errors. Stuck loop \u2014 try fundamentally different approach or declare done.`};Y.push(B),k.push(B)}else if(vn>=eg){z(`${$.red} \u2716 Loop abort: ${vn} consecutive errors \u2014 aborting stuck loop${$.reset}`),u&&(u.stop(),u=null),l(null),Ge(S,L,R,M,D,{suppressHint:!0}),Ke(Y);return}if(F&&b.fnName==="read_file"&&b.args&&b.args.path){M.add(b.args.path);let B=bo(Fo,b.args.path);if(b.args.line_start!=null){let ge=b.args.line_start||1,ee=b.args.line_end||ge+350;Kn.has(b.args.path)||Kn.set(b.args.path,[]),Kn.get(b.args.path).push([ge,ee])}if(b._scrollWarn){let{sectionCount:ge,path:ee}=b._scrollWarn,U={role:"user",content:`[SYSTEM WARNING] "${ee}" \u2014 you have now read ${ge} 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.`};Y.push(U),k.push(U),z(`${$.yellow} \u26A0 Scroll warning: "${ee.split("/").slice(-2).join("/")}" \u2014 ${ge} sections read \u2014 use grep instead${$.reset}`)}let K=b.args.path.split("/").slice(-2).join("/"),ne=!b.args?.line_start&&!b.args?.line_end;if(ne&&B===Vh){{let ee=st();if(Ut(k,ee).percentage>=60){let{messages:$e}=zt(k,ee);k=$e}}z(`${$.yellow} \u26A0 Loop warning: "${K}" read unbounded ${B}\xD7 \u2014 use line_start/line_end${$.reset}`);let ge={role:"user",content:`[SYSTEM WARNING] "${b.args.path}" read ${B}\xD7 without line ranges. Use line_start/line_end to read specific sections \u2014 do not re-read the full file.`};Y.push(ge),k.push(ge)}else if(ne&&B>=Zh){z(`${$.red} \u2716 Loop abort: "${K}" read unbounded ${B}\xD7 \u2014 aborting runaway read loop${$.reset}`),u&&(u.stop(),u=null),l(null),Ge(S,L,R,M,D,{suppressHint:!0}),Ke(Y);return}}if(b.fnName==="spawn_agents"){let B=(te.match(/\bStatus: done\b/g)||[]).length;if((te.match(/\bStatus: truncated\b/g)||[]).length>0&&B===0){if(En++,En===tg){z(`${$.yellow} \u26A0 Swarm warning: all sub-agents hit iteration limit ${En}\xD7 in a row${$.reset}`);let ne={role:"user",content:`[SYSTEM WARNING] Sub-agents truncated ${En}\xD7 in a row. Stop spawning \u2014 try different approach or report findings.`};Y.push(ne),k.push(ne)}else if(En>=ng){console.log(`${$.red} \u2716 Swarm abort: all sub-agents hit iteration limit ${En}\xD7 \u2014 aborting stuck swarm${$.reset}`),u&&(u.stop(),u=null),l(null),Ge(S,L,R,M,D,{suppressHint:!0}),Ke(Y);return}}else B>0&&(En=0)}}for(let _ of Tn)Y.push(_),k.push(_);if(!Je)for(let _=0;_<Tn.length;_++){if(!xe[_]||xe[_].fnName!=="ssh_exec")continue;let b=Tn[_];if(!b||typeof b.content!="string")continue;let te=yc(b.content);if(te){Je=!0,gt=te.slice(0,120),zn=0,cn=!1,z(`${$.yellow} \u26A1 Root cause detected: ${gt} \u2014 fix phase (read budget: 3)${$.reset}`);let I={role:"user",content:`[SYSTEM] Root cause identified: ${gt}. Read only the file that needs fixing, then edit it. Do not read other files.`};Y.push(I),k.push(I);break}}for(let _=0;_<Tn.length;_++){let b=xe[_];if(!b)continue;let te=typeof Tn[_]?.content=="string"?Tn[_].content:"";if(b.fnName==="create_task"){let I=te.match(/Task #(\d+) created/),F=typeof b.args?.subject=="string"?b.args.subject:"";I&&F&&To.set(I[1],F)}else if((b.fnName==="write_file"||b.fnName==="edit_file")&&!te.startsWith("BLOCKED:")&&te.trim().length>0){let F=(typeof b.args?.path=="string"?b.args.path:typeof b.args?.file_path=="string"?b.args.file_path:"").split("/").pop().toLowerCase(),oe=F.split(/[._\-/]/).filter(re=>re.length>2);for(let[re,he]of To){if(Ro.has(re))continue;let B=he.toLowerCase().split(/\W+/).filter(ne=>ne.length>3);oe.filter(ne=>B.some(ge=>ge.includes(ne)||ne.includes(ge))).length>=1&&(Ro.add(re),z(`${$.green} \u2714 Auto-matched task #${re} to ${F}: ${he.slice(0,60)}${$.reset}`))}}}{let _=st();if(Ut(k,_).percentage>=78){let{messages:te,tokensRemoved:I}=zt(k,_);I>0&&(k=te,console.log(`${$.dim} [auto-compressed \u2014 ~${I} tokens freed, now ${Math.round(Ut(k,_).percentage)}%]${$.reset}`))}}let hl=ik();if(hl){let _={role:"user",content:`[User note mid-run]: ${hl}`};Y.push(_),k.push(_),console.log(`${$.cyan} \u270E Context added${$.reset}`)}}if(dt>=Uo){u&&(u.stop(),u=null),l(null),Ge(S,L,R,M,D),Ke(Y),rm(Y);let{getActiveProviderName:Pe}=Le();if(Pe()==="ollama"&&Ei<cl){if(R.size===0&&!Ti){console.log(`${$.yellow} \u26A0 Max iterations reached with no progress. Stopping.${$.reset}`);break e}Ei++,Uo=20,console.log(`${$.dim} \u2500\u2500 auto-extending (+20 turns, ext ${Ei}/${cl}) \u2500\u2500${$.reset}`);continue e}if(console.log(`
|
|
1140
|
-
${$.yellow}\u26A0 Max iterations reached.${$.reset}`),await $m(" Continue for 20 more turns?")){Uo=20;continue e}console.log(`${$.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${$.reset}`)}break e}}Rm.exports={processInput:$
|
|
1139
|
+
`)[0],F=!I.startsWith("ERROR")&&!I.startsWith("CANCELLED")&&!I.startsWith("Command failed")&&!I.startsWith("EXIT");if(!F&&(b.fnName==="edit_file"||b.fnName==="patch_file")&&b.args?.path&&I.includes("old_text not found")){let B=Gn.get(b.args.path)||0;Gn.set(b.args.path,B+1)}if(F&&b.fnName==="write_file"&&b.args?.path){let B=b.args.path.split("/").pop(),K=b.args.path.includes("/tests/")||b.args.path.includes("\\tests\\");if(/^(test_|demo_|temp_|tmp_|scratch_)/.test(B)&&!K){z(`${$.yellow} \u26A0 Temp file: "${B}" \u2014 delete with bash rm when done to keep the workspace clean${$.reset}`);let ge={role:"user",content:`[HINT] "${b.args.path}" looks like a temporary test/demo file. Delete it with bash("rm ${b.args.path}") as soon as you're done \u2014 orphaned temp files count against session quality.`};Y.push(ge),v.push(ge)}}if(F&&["write_file","edit_file","patch_file"].includes(b.fnName)&&b.args&&b.args.path){Gn.delete(b.args.path),R.add(b.args.path);let B=bo(Z,b.args.path),K=b.args.path.split("/").slice(-2).join("/");if(B===ce){z(`${$.yellow} \u26A0 Loop warning: "${K}" edited ${B}\xD7 \u2014 possible edit loop${$.reset}`);let ne={role:"user",content:`[SYSTEM WARNING] "${b.args.path}" edited ${B}\xD7. One more edit max, then move on.`};Y.push(ne),v.push(ne)}else if(B>=se){z(`${$.red} \u2716 Loop abort: "${K}" edited ${B}\xD7 \u2014 aborting to prevent runaway loop${$.reset}`),u&&(u.stop(),u=null),l(null),Ge(S,L,R,M,D,{suppressHint:!0}),Ke(Y);return}}if(F&&b.canExecute){let B=["read_file","grep","search_files","glob","list_directory","ssh_exec","find_files"];["write_file","edit_file","patch_file"].includes(b.fnName)?(zn=0,cn=!1,Xt++):B.includes(b.fnName)&&zn++;let ne=o.postEditCap,ge=Je?3:Mt?Xt>0?2:4:Xt>0?ne:og;if(cn&&(Je||Mt&&Xt>=1)&&B.includes(b.fnName)){let U=Je?`root cause already identified (${gt})`:`${Xt} file edit(s) already made`;z(`${$.red} \u2716 Blocked read-only tool: cap fired, ${U}${$.reset}`),b.canExecute=!1,b.errorResult={role:"tool",content:Je?`BLOCKED: root cause already identified (${gt}). Use edit_file to fix the issue \u2014 do not read more files.`:Mt?"BLOCKED: files already written \u2014 continue with write_file or edit_file to finish the remaining tasks. Do not read more files.":`BLOCKED: ${Xt} file edit(s) already made and post-edit investigation cap reached. The fix is in place. Do not read more files \u2014 proceed with the task.`,tool_call_id:b.callId}}else if(zn>=ge&&!cn){cn=!0,z(`${$.yellow} \u26A0 Investigation cap: ${zn} read-only calls without an edit \u2014 forcing implementation${$.reset}`);let U;Je?U=`[SYSTEM] Root cause was already identified (${gt}). Edit the file now \u2014 do not read more files.`:Nt?U="[SYSTEM] SSH temporarily paused. Summarize your findings and state the likely diagnosis. Do NOT ask the user to run commands \u2014 SSH re-enables after your summary.":U="[SYSTEM] You have read enough files. Now implement your fix using edit_file.";let $e={role:"user",content:U};Y.push($e),v.push($e)}}if((b.fnName==="bash"||b.fnName==="ssh_exec")&&b.args&&b.args.command){let B=b.args.command.replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),K=bo(me,B);if(K===ke){z(`${$.yellow} \u26A0 Loop warning: same bash command run ${K}\xD7 \u2014 possible debug loop${$.reset}`);let ne={role:"user",content:`[SYSTEM WARNING] Same bash command ${K}\xD7. Debug loop detected \u2014 try a different approach.`};Y.push(ne),v.push(ne)}else if(K>=Qe){z(`${$.red} \u2716 Loop abort: same bash command run ${K}\xD7 \u2014 aborting runaway debug loop${$.reset}`),u&&(u.stop(),u=null),l(null),Ge(S,L,R,M,D,{suppressHint:!0}),Ke(Y);return}}if(b.fnName==="ssh_exec"){if(Ot++,Ot>=sg){z(`${$.red} \u2716 SSH storm abort: ${Ot} consecutive ssh_exec calls \u2014 aborting${$.reset}`),u&&(u.stop(),u=null),l(null),Ge(S,L,R,M,D,{suppressHint:!0}),Ke(Y);return}else if(Ot===Ls){{let ne=st(),{messages:ge}=zt(v,ne);v=ge}Nt=!0,Zr++,z(`${$.yellow} \u26A0 SSH storm warning (#${Zr}): ${Ot} consecutive ssh_exec calls \u2014 blocking further SSH${$.reset}`);let K={role:"user",content:Je?`[SYSTEM WARNING] ${Ot} consecutive SSH calls. Root cause identified (${gt}). Read the file that needs fixing, then edit it.`:`[SYSTEM WARNING] ${Ot} consecutive SSH calls \u2014 SSH temporarily paused for synthesis. Summarize what you found and state the likely diagnosis. Do NOT ask the user to run commands or provide logs. SSH will be re-enabled after your summary so you can continue.`};Y.push(K),v.push(K)}}else b.canExecute&&(Ot=0);if(F&&b.fnName==="grep"&&b.args&&b.args.pattern){let B=`${b.args.pattern}|${b.args.path||""}`,K=bo(ze,B);if(K===fn){z(`${$.yellow} \u26A0 Loop warning: grep pattern "${b.args.pattern.slice(0,40)}" run ${K}\xD7 \u2014 possible search loop${$.reset}`);let ne={role:"user",content:`[SYSTEM WARNING] Same grep pattern ${K}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};Y.push(ne),v.push(ne)}else if(K>=ki){z(`${$.red} \u2716 Loop abort: grep pattern run ${K}\xD7 \u2014 aborting runaway search loop${$.reset}`),u&&(u.stop(),u=null),l(null),Ge(S,L,R,M,D,{suppressHint:!0}),Ke(Y);return}if(b.args.path){let ne=bo(qo,b.args.path),ge=vs(Fo,b.args.path)>=1;if(ne===(ge?1:Jh)){let U=b.args.path.split("/").slice(-2).join("/");z(`${$.yellow} \u26A0 Loop warning: "${U}" grepped ${ne}\xD7 with different patterns \u2014 context flood risk${$.reset}`);let $e={role:"user",content:ge?`[SYSTEM NOTE] "${b.args.path}" was already fully read \u2014 its content is in context. Grepping it again is redundant; use the context you already have.`:`[SYSTEM NOTE] "${b.args.path}" grepped ${ne}\xD7 \u2014 use the search results already in context instead of searching again.`};Y.push($e),v.push($e)}}}let oe=(b.args?.command||b.args?.cmd||b.args?.script||"").toLowerCase(),re=/\b(health|healthcheck|health-check|status|check|ping|validate|alive|ready)\b/.test(oe)||/\/(health|status|ping|ready|alive)\b/.test(oe);if(F&&(b.fnName==="bash"||b.fnName==="ssh_exec")&&re&&te.includes('"valid":true')){{let K=st();if(Ut(v,K).percentage>=60){let{messages:ge,tokensRemoved:ee}=zt(v,K);ee>0&&(v=ge,console.log(`${$.dim} [pre-stop-compress \u2014 ~${ee} tokens freed before STOP injection, now ${Math.round(Ut(v,K).percentage)}%]${$.reset}`))}}let B={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.'};Y.push(B),v.push(B),console.log(`${$.cyan} \u2713 Health-check stop signal detected \u2014 injecting STOP instruction${$.reset}`)}if(te.startsWith("BLOCKED:")){if(Sn++,Sn>=al){z(`${$.red} \u2716 Loop abort: ${Sn} consecutive blocked calls \u2014 model not heeding BLOCKED messages${$.reset}`),u&&(u.stop(),u=null),l(null),Ge(S,L,R,M,D,{suppressHint:!0}),Ke(Y);return}}else Sn=0;if(F)kn=0,Ti=!0;else if(kn++,kn===Qh){z(`${$.yellow} \u26A0 Loop warning: ${kn} consecutive tool errors \u2014 possible stuck loop${$.reset}`);let B={role:"user",content:`[SYSTEM WARNING] ${kn} consecutive errors. Stuck loop \u2014 try fundamentally different approach or declare done.`};Y.push(B),v.push(B)}else if(kn>=eg){z(`${$.red} \u2716 Loop abort: ${kn} consecutive errors \u2014 aborting stuck loop${$.reset}`),u&&(u.stop(),u=null),l(null),Ge(S,L,R,M,D,{suppressHint:!0}),Ke(Y);return}if(F&&b.fnName==="read_file"&&b.args&&b.args.path){M.add(b.args.path);let B=bo(Fo,b.args.path);if(b.args.line_start!=null){let ge=b.args.line_start||1,ee=b.args.line_end||ge+350;Kn.has(b.args.path)||Kn.set(b.args.path,[]),Kn.get(b.args.path).push([ge,ee])}if(b._scrollWarn){let{sectionCount:ge,path:ee}=b._scrollWarn,U={role:"user",content:`[SYSTEM WARNING] "${ee}" \u2014 you have now read ${ge} 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.`};Y.push(U),v.push(U),z(`${$.yellow} \u26A0 Scroll warning: "${ee.split("/").slice(-2).join("/")}" \u2014 ${ge} sections read \u2014 use grep instead${$.reset}`)}let K=b.args.path.split("/").slice(-2).join("/"),ne=!b.args?.line_start&&!b.args?.line_end;if(ne&&B===Vh){{let ee=st();if(Ut(v,ee).percentage>=60){let{messages:$e}=zt(v,ee);v=$e}}z(`${$.yellow} \u26A0 Loop warning: "${K}" read unbounded ${B}\xD7 \u2014 use line_start/line_end${$.reset}`);let ge={role:"user",content:`[SYSTEM WARNING] "${b.args.path}" read ${B}\xD7 without line ranges. Use line_start/line_end to read specific sections \u2014 do not re-read the full file.`};Y.push(ge),v.push(ge)}else if(ne&&B>=Zh){z(`${$.red} \u2716 Loop abort: "${K}" read unbounded ${B}\xD7 \u2014 aborting runaway read loop${$.reset}`),u&&(u.stop(),u=null),l(null),Ge(S,L,R,M,D,{suppressHint:!0}),Ke(Y);return}}if(b.fnName==="spawn_agents"){let B=(te.match(/\bStatus: done\b/g)||[]).length;if((te.match(/\bStatus: truncated\b/g)||[]).length>0&&B===0){if(En++,En===tg){z(`${$.yellow} \u26A0 Swarm warning: all sub-agents hit iteration limit ${En}\xD7 in a row${$.reset}`);let ne={role:"user",content:`[SYSTEM WARNING] Sub-agents truncated ${En}\xD7 in a row. Stop spawning \u2014 try different approach or report findings.`};Y.push(ne),v.push(ne)}else if(En>=ng){console.log(`${$.red} \u2716 Swarm abort: all sub-agents hit iteration limit ${En}\xD7 \u2014 aborting stuck swarm${$.reset}`),u&&(u.stop(),u=null),l(null),Ge(S,L,R,M,D,{suppressHint:!0}),Ke(Y);return}}else B>0&&(En=0)}}for(let _ of Tn)Y.push(_),v.push(_);if(!Je)for(let _=0;_<Tn.length;_++){if(!xe[_]||xe[_].fnName!=="ssh_exec")continue;let b=Tn[_];if(!b||typeof b.content!="string")continue;let te=yc(b.content);if(te){Je=!0,gt=te.slice(0,120),zn=0,cn=!1,z(`${$.yellow} \u26A1 Root cause detected: ${gt} \u2014 fix phase (read budget: 3)${$.reset}`);let I={role:"user",content:`[SYSTEM] Root cause identified: ${gt}. Read only the file that needs fixing, then edit it. Do not read other files.`};Y.push(I),v.push(I);break}}for(let _=0;_<Tn.length;_++){let b=xe[_];if(!b)continue;let te=typeof Tn[_]?.content=="string"?Tn[_].content:"";if(b.fnName==="create_task"){let I=te.match(/Task #(\d+) created/),F=typeof b.args?.subject=="string"?b.args.subject:"";I&&F&&To.set(I[1],F)}else if((b.fnName==="write_file"||b.fnName==="edit_file")&&!te.startsWith("BLOCKED:")&&te.trim().length>0){let F=(typeof b.args?.path=="string"?b.args.path:typeof b.args?.file_path=="string"?b.args.file_path:"").split("/").pop().toLowerCase(),oe=F.split(/[._\-/]/).filter(re=>re.length>2);for(let[re,he]of To){if(Ro.has(re))continue;let B=he.toLowerCase().split(/\W+/).filter(ne=>ne.length>3);oe.filter(ne=>B.some(ge=>ge.includes(ne)||ne.includes(ge))).length>=1&&(Ro.add(re),z(`${$.green} \u2714 Auto-matched task #${re} to ${F}: ${he.slice(0,60)}${$.reset}`))}}}{let _=st();if(Ut(v,_).percentage>=78){let{messages:te,tokensRemoved:I}=zt(v,_);I>0&&(v=te,console.log(`${$.dim} [auto-compressed \u2014 ~${I} tokens freed, now ${Math.round(Ut(v,_).percentage)}%]${$.reset}`))}}let hl=iv();if(hl){let _={role:"user",content:`[User note mid-run]: ${hl}`};Y.push(_),v.push(_),console.log(`${$.cyan} \u270E Context added${$.reset}`)}}if(dt>=Uo){u&&(u.stop(),u=null),l(null),Ge(S,L,R,M,D),Ke(Y),rm(Y);let{getActiveProviderName:Pe}=Le();if(Pe()==="ollama"&&Ei<cl){if(R.size===0&&!Ti){console.log(`${$.yellow} \u26A0 Max iterations reached with no progress. Stopping.${$.reset}`);break e}Ei++,Uo=20,console.log(`${$.dim} \u2500\u2500 auto-extending (+20 turns, ext ${Ei}/${cl}) \u2500\u2500${$.reset}`);continue e}if(console.log(`
|
|
1140
|
+
${$.yellow}\u26A0 Max iterations reached.${$.reset}`),await $m(" Continue for 20 more turns?")){Uo=20;continue e}console.log(`${$.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${$.reset}`)}break e}}Rm.exports={processInput:$v,clearConversation:lv,getConversationLength:dv,getConversationMessages:fv,setConversationMessages:pv,setAbortSignalGetter:Ux,setMaxIterations:Fx,invalidateSystemPromptCache:xc,clearToolFilterCache:Xx,getCachedFilteredTools:bm,buildSystemPrompt:Em,getProjectContextHash:_m,buildUserContent:wm,detectAndTruncateLoop:wc,injectMidRunNote:rv,resetSessionTracking:Tm}});var Le=J((DE,Mm)=>{var{OllamaProvider:yv}=Gl(),{OpenAIProvider:wv}=hu(),{AnthropicProvider:bv}=wu(),{GeminiProvider:_v}=vu(),{LocalProvider:xv}=Eu(),{checkBudget:vv}=cs(),Oc={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"}},Cc=(process.env.OLLAMA_FALLBACK_CHAIN||"").split(",").map(t=>t.trim()).filter(Boolean),Am={};for(let[t,e]of Object.entries(Oc))for(let n of Object.values(e))Am[n]=t;function Ac(t,e){let n=Am[t];return n&&Oc[n][e]||t}var Ve={},$t=null,He=null,Co=[];function Pt(){if(Object.keys(Ve).length>0)return;As("ollama",new yv),As("openai",new wv),As("anthropic",new bv),As("gemini",new _v),As("local",new xv);let t=process.env.DEFAULT_PROVIDER||"ollama",e=process.env.DEFAULT_MODEL||null;Ve[t]?($t=t,He=e||Ve[t].defaultModel):($t="ollama",He="kimi-k2.5");let n=process.env.FALLBACK_CHAIN;n&&(Co=n.split(",").map(o=>o.trim()).filter(Boolean))}function As(t,e){Ve[t]=e}function kv(t){return Pt(),Ve[t]||null}function Nc(){return Pt(),Ve[$t]||null}function Sv(){return Pt(),$t}function Ev(){return Pt(),He}function Tv(){Pt();let t=Nc();if(!t)return{id:He,name:He,provider:$t};let e=t.getModel(He);return e?{...e,provider:$t}:{id:He,name:He,provider:$t}}function Om(t){if(!t)return{provider:null,model:null};let e=t.indexOf(":");if(e>0){let n=t.slice(0,e);if(Ve[n]||["ollama","openai","anthropic","gemini","local"].includes(n))return{provider:n,model:t.slice(e+1)}}return{provider:null,model:t}}function Rv(t){Pt();let{provider:e,model:n}=Om(t);if(e){let s=Ve[e];return s&&(s.getModel(n)||e==="local"||e==="ollama")?($t=e,He=n,li(),!0):!1}let o=Nc();if(o&&o.getModel(n))return He=n,li(),!0;for(let[s,r]of Object.entries(Ve))if(r.getModel(n))return $t=s,He=n,li(),!0;return!1}function li(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=Ae();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=nt();t()}catch{}}function Cv(){Pt();let t=new Set;for(let e of Object.values(Ve))for(let n of e.getModelNames())t.add(n);return Array.from(t)}function Av(){return Pt(),Object.entries(Ve).map(([t,e])=>({provider:t,configured:e.isConfigured(),models:Object.values(e.getModels()).map(n=>({...n,active:t===$t&&n.id===He}))}))}function Ov(){Pt();let t=[];for(let[e,n]of Object.entries(Ve)){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 Nv(t){Co=Array.isArray(t)?t:[]}function Mv(){return[...Co]}function Cm(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 Nm(t){let e=[$t,...Co.filter(r=>r!==$t)],n,o=0,s=0;for(let r=0;r<e.length;r++){let i=e[r],c=Ve[i];if(!c||!c.isConfigured())continue;s++;let l=vv(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?Ac(He,i):He;return u&&d!==He&&process.stderr.write(` [fallback: ${i}:${d}]
|
|
1141
1141
|
`),await t(c,i,d)}catch(u){if(n=u,!Cm(u)||r>=e.length-1)throw u;if(i==="ollama"&&Cc.length>0){let d=isFallback?Ac(He,i):He;for(let f of Cc)if(f!==d)try{return process.stderr.write(` [ollama fallback: ${f}]
|
|
1142
|
-
`),await t(c,i,f)}catch(m){if(n=m,!Cm(m))throw m}}continue}}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
|
|
1142
|
+
`),await t(c,i,f)}catch(m){if(n=m,!Cm(m))throw m}}continue}}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 Pv(t,e,n={}){return Pt(),Nm((o,s,r)=>o.stream(t,e,{model:r,signal:n.signal,...n}))}async function Lv(t,e,n={}){if(Pt(),n.provider){let o=Ve[n.provider];if(!o||!o.isConfigured())throw new Error(`Provider '${n.provider}' is not available`);let s={model:n.model||He,...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 Nm(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 Iv(){Pt();let t=[];for(let[e,n]of Object.entries(Ve))n.isConfigured()&&t.push({name:e,models:Object.values(n.getModels())});return t}function jv(){for(let t of Object.keys(Ve))delete Ve[t];$t=null,He=null,Co=[]}Mm.exports={registerProvider:As,getProvider:kv,getActiveProvider:Nc,getActiveProviderName:Sv,getActiveModelId:Ev,getActiveModel:Tv,setActiveModel:Rv,getModelNames:Cv,parseModelSpec:Om,listProviders:Av,listAllModels:Ov,callStream:Pv,callChat:Lv,getConfiguredProviders:Iv,setFallbackChain:Nv,getFallbackChain:Mv,resolveModelForProvider:Ac,MODEL_EQUIVALENTS:Oc,OLLAMA_FALLBACK_MODELS:Cc,_reset:jv}});var Pc=J((qE,Pm)=>{"use strict";var ln=require("fs"),ui=require("path"),Dv=require("readline"),ve="\x1B[0m",di="\x1B[1m",ot="\x1B[2m",fi="\x1B[33m",Mc="\x1B[36m",Ao="\x1B[32m";function qv(t){return(e,n="")=>new Promise(o=>{let s=n?` ${ot}[${n}]${ve}`:"";t.question(` ${Mc}${e}${s}${ve}: `,r=>o(r.trim()||n))})}function Oo(t,e){return new Promise(n=>{e&&e.pause(),process.stdout.write(` ${Mc}${t}${ve}: `);let o=process.stdin,s=o.isRaw,r="";o.setRawMode(!0),o.resume(),o.setEncoding("utf8");let i=c=>{c==="\r"||c===`
|
|
1143
1143
|
`?(o.setRawMode(s||!1),o.removeListener("data",i),process.stdout.write(`
|
|
1144
1144
|
`),e&&e.resume(),n(r)):c===""?(process.stdout.write(`
|
|
1145
|
-
`),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
|
|
1146
|
-
`),console.log(` ${di}Which AI provider do you want to use?${
|
|
1147
|
-
`),console.log(` ${Ao}1)${
|
|
1148
|
-
${ot} Cancelled \u2014 no changes made.${
|
|
1145
|
+
`),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 Fv({rl:t=null,force:e=!1}={}){if(!e){let m=ln.existsSync(ui.join(process.cwd(),".env"))||ln.existsSync(ui.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||Dv.createInterface({input:process.stdin,output:process.stdout,terminal:!0}),s=qv(o),r=!e;console.log(),console.log(r?`${fi}${di} \u2726 Welcome to nex-code! No configuration found.${ve}`:`${Mc}${di} \u2726 nex-code \u2014 Provider & API Key Setup${ve}`),console.log(`${ot} \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500${ve}`),r&&console.log(` Let's set you up in 60 seconds.
|
|
1146
|
+
`),console.log(` ${di}Which AI provider do you want to use?${ve}
|
|
1147
|
+
`),console.log(` ${Ao}1)${ve} ${di}Ollama Cloud${ve} ${ot}recommended \u2014 devstral-2:123b, no API key needed${ve}`),console.log(` ${ot} (also works with a local Ollama server)${ve}`),console.log(` ${ot}2) Anthropic Claude (claude-sonnet-4-6 etc.)${ve}`),console.log(` ${ot}3) OpenAI GPT-4o, GPT-4.1 etc.${ve}`),console.log(` ${ot}4) Gemini Google Gemini 2.x${ve}`),console.log(` ${ot}5) Skip / Cancel${ve}`),console.log();let i=await s("Enter number","1"),c=[];if(i==="5"){n&&o.close(),console.log(`
|
|
1148
|
+
${ot} Cancelled \u2014 no changes made.${ve}
|
|
1149
1149
|
`);return}if(i==="1"){console.log(),console.log(`
|
|
1150
|
-
${Ao}Ollama Cloud${
|
|
1151
|
-
`);let m=await Oo("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(` ${ot}Get your key: https://console.anthropic.com/settings/keys${
|
|
1152
|
-
${fi} No key entered \u2014 cancelled.${
|
|
1153
|
-
`);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(` ${ot}Get your key: https://platform.openai.com/api-keys${
|
|
1154
|
-
${fi} No key entered \u2014 cancelled.${
|
|
1155
|
-
`);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(` ${ot}Get your key: https://aistudio.google.com/app/apikey${
|
|
1156
|
-
${fi} No key entered \u2014 cancelled.${
|
|
1157
|
-
`);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(` ${ot}Get your key: https://www.perplexity.ai/settings/api${
|
|
1150
|
+
${Ao}Ollama Cloud${ve} ${ot}(recommended): uses ollama.com API \u2014 flat-rate, 47+ models.${ve}`),console.log(` ${ot}Get your API key at: https://ollama.com/settings/api-keys${ve}
|
|
1151
|
+
`);let m=await Oo("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(` ${ot}Get your key: https://console.anthropic.com/settings/keys${ve}`);let m=await Oo("ANTHROPIC_API_KEY",t);if(!m){n&&o.close(),console.log(`
|
|
1152
|
+
${fi} No key entered \u2014 cancelled.${ve}
|
|
1153
|
+
`);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(` ${ot}Get your key: https://platform.openai.com/api-keys${ve}`);let m=await Oo("OPENAI_API_KEY",t);if(!m){n&&o.close(),console.log(`
|
|
1154
|
+
${fi} No key entered \u2014 cancelled.${ve}
|
|
1155
|
+
`);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(` ${ot}Get your key: https://aistudio.google.com/app/apikey${ve}`);let m=await Oo("GEMINI_API_KEY",t);if(!m){n&&o.close(),console.log(`
|
|
1156
|
+
${fi} No key entered \u2014 cancelled.${ve}
|
|
1157
|
+
`);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(` ${ot}Get your key: https://www.perplexity.ai/settings/api${ve}`);let m=await Oo("PERPLEXITY_API_KEY",t);m&&(c.push(`PERPLEXITY_API_KEY=${m}`),process.env.PERPLEXITY_API_KEY=m)}console.log();let u=ui.join(process.cwd(),".env"),d=(ln.existsSync(u),"y"),f=await s(`Save to ${u}? (Y/n)`,d);if(n&&o.close(),f.toLowerCase()!=="n"){let m=ln.existsSync(u)?ln.readFileSync(u,"utf-8").trimEnd()+`
|
|
1158
1158
|
|
|
1159
1159
|
`:"";ln.writeFileSync(u,m+c.join(`
|
|
1160
1160
|
`)+`
|
|
@@ -1162,18 +1162,18 @@ ${fi} No key entered \u2014 cancelled.${ke}
|
|
|
1162
1162
|
`).some(g=>g.trim()===".env")||ln.appendFileSync(h,`
|
|
1163
1163
|
.env
|
|
1164
1164
|
`)),console.log(`
|
|
1165
|
-
${Ao} \u2713 Saved to ${u}${
|
|
1166
|
-
${Ao} \u2713 Setup complete!${
|
|
1167
|
-
`)}Pm.exports={runSetupWizard:
|
|
1168
|
-
`))}function Lm(t,e){if(!
|
|
1165
|
+
${Ao} \u2713 Saved to ${u}${ve}`),c.some(p=>p.includes("API_KEY"))&&console.log(`${ot} (key stored locally \u2014 never committed)${ve}`)}if(process.env.DEFAULT_PROVIDER)try{let{setActiveModel:m}=Le(),h=process.env.DEFAULT_MODEL?`${process.env.DEFAULT_PROVIDER}:${process.env.DEFAULT_MODEL}`:process.env.DEFAULT_PROVIDER;m(h),console.log(`${Ao} \u2713 Switched to ${h} for this session${ve}`)}catch{}console.log(`
|
|
1166
|
+
${Ao} \u2713 Setup complete!${ve}
|
|
1167
|
+
`)}Pm.exports={runSetupWizard:Fv}});var Dm=J((FE,jm)=>{"use strict";var pi=require("fs"),{T:Wt,isDark:Uv}=Rn(),vt="\x1B[0m",Wv=!Uv,Bv=process.env.FOOTER_DEBUG==="1"||process.env.FOOTER_DEBUG==="2",Hv=process.env.FOOTER_DEBUG==="2",Os=null;function xn(...t){Bv&&(Os||(Os=pi.openSync("/tmp/footer-debug.log","w")),pi.writeSync(Os,t.join(" ")+`
|
|
1168
|
+
`))}function Lm(t,e){if(!Hv||typeof e!="string")return;Os||(Os=pi.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>
|
|
1169
1169
|
`).replace(/[\x00-\x08\x0b-\x1f\x7f]/g,o=>`<${o.charCodeAt(0).toString(16).padStart(2,"0")}>`);pi.writeSync(Os,`${t}: ${n}
|
|
1170
|
-
`)}function Im(t){return t.replace(/\x1b\[[^a-zA-Z]*[a-zA-Z]/g,"").length}var Lc=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 Wt.footer_sep+"\u2500".repeat(e)+
|
|
1170
|
+
`)}function Im(t){return t.replace(/\x1b\[[^a-zA-Z]*[a-zA-Z]/g,"").length}var Lc=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 Wt.footer_sep+"\u2500".repeat(e)+vt;let i=` ${Wt.footer_divider}\xB7${vt} `,c=[];n&&c.push(`${Wt.footer_model}${n}${vt}`),o&&c.push(`${Wt.footer_branch}${o}${vt}`),s&&c.push(`${Wt.footer_project}${s}${vt}`);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`${Wt.footer_sep}${d}${vt}${l}${Wt.footer_sep} ${g} ${vt}${Wt.footer_mode}${r}${vt}${Wt.footer_sep} \u2500\u2500${vt}`}let f=Math.max(0,e-d.length-u-2),m="\u2500".repeat(f);return`${Wt.footer_sep}${d}${vt}${l}${Wt.footer_sep} ${m}${vt}`}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(Wv)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 Lm("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);xn("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(Lm("PATCH",p),!n._active||typeof p!="string")return o(p,...g);if(n._inRefreshLine){let E=p.replace(/\n/g,"");return E?o(E,...g):!0}if(n._cursorOnInputRow){if(p.length<=4&&!p.includes(`
|
|
1171
1171
|
`)&&!p.includes("\r")&&!/[\x00-\x1f\x7f]/.test(p))return xn("STDOUT: char intercept:",JSON.stringify(p)),n._origRefreshLine&&n._doRefreshLine(),!0;xn("STDOUT: non-echo on input row, anchoring to workspace, data="+JSON.stringify(p).slice(0,100)),n._cursorOnInputRow=!1,o(n._goto(Math.min(n._lastOutputRow+1,n._scrollEnd)))}let y=n._cols||80,w=0,x=p.split(`
|
|
1172
|
-
`);for(let E=0;E<x.length;E++){let
|
|
1173
|
-
`)&&!/\x1b\[\d+A/.test(p)&&n._cursorOnInputRow&&(n.drawFooter(),n._origWrite(n._goto(n._rowInput)+"\x1B[2K")),y},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);xn("PROMPT: goto rowInput="+n._rowInput),e.prevRows=0,o(n._goto(n._rowInput)+
|
|
1174
|
-
`);process.stdout.write(`\x1B[${m}A`)}let w=[];w.push(` ${De.bold}${De.cyan}${o}${De.reset}`),w.push(` ${De.dim}${s}${De.reset}`),w.push("");let{start:x,end:A}=f();x>0&&w.push(` ${De.dim}\u2191 more${De.reset}`);for(let
|
|
1172
|
+
`);for(let E=0;E<x.length;E++){let k=Im(x[E]);k>0&&(w+=Math.floor((k-1)/y))}let A=x.length-1;return A+w>0&&(n._lastOutputRow=Math.min(n._lastOutputRow+A+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 w=Math.min(n._lastOutputRow+1,n._scrollEnd);if(n._cursorOnInputRow){n._origWrite("\x1B7"),n._origWrite(n._goto(w));let x=n._origStderrWrite(p,...g);return n._origWrite("\x1B8"),x}n._origWrite(n._goto(w))}let y=n._origStderrWrite(p,...g);return typeof p=="string"&&p.includes(`
|
|
1173
|
+
`)&&!/\x1b\[\d+A/.test(p)&&n._cursorOnInputRow&&(n.drawFooter(),n._origWrite(n._goto(n._rowInput)+"\x1B[2K")),y},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);xn("PROMPT: goto rowInput="+n._rowInput),e.prevRows=0,o(n._goto(n._rowInput)+vt+"\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)+vt+"\x1B[2K");let p=n._cols,g=e._prompt||"",y=Im(g),w=p-y-1;n._inRefreshLine=!0;try{if(e.line.length<=w){xn("REFRESH: short line, len="+e.line.length),u();return}xn("REFRESH: long line, len="+e.line.length+", max="+w);let x=e.line,A=e.cursor,E=Math.max(1,w-1),k=Math.max(0,A-E),T=(k>0?"\xAB":"")+x.slice(k,k+E+(k>0?0:1));e.line=T,e.cursor=T.length,u(),e.line=x,e.cursor=A}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&&(xn("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)&&(xn("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}}};jm.exports={StickyFooter:Lc}});var Um=J((UE,Fm)=>{var{C:De}=qe(),{listProviders:Kv,getActiveProviderName:Gv,getActiveModelId:Yv,setActiveModel:zv}=Le();function qm(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 k=0;k<m;k++)process.stdout.write(`\x1B[2K
|
|
1174
|
+
`);process.stdout.write(`\x1B[${m}A`)}let w=[];w.push(` ${De.bold}${De.cyan}${o}${De.reset}`),w.push(` ${De.dim}${s}${De.reset}`),w.push("");let{start:x,end:A}=f();x>0&&w.push(` ${De.dim}\u2191 more${De.reset}`);for(let k=x;k<A;k++){let T=e[k];if(T.isHeader){w.push(` ${De.bold}${De.dim}${T.label}${De.reset}`);continue}let O=i[l]===k,P=O?`${De.cyan}> `:" ",W=T.isCurrent?` ${De.yellow}<current>${De.reset}`:"";O?w.push(`${P}${De.bold}${T.label}${De.reset}${W}`):w.push(`${P}${De.dim}${T.label}${De.reset}${W}`)}A<e.length&&w.push(` ${De.dim}\u2193 more${De.reset}`);let E=w.join(`
|
|
1175
1175
|
`);process.stdout.write(E+`
|
|
1176
|
-
`),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 A=e[i[l]];g(),r(A?A.value:null);return}if(x.name==="escape"||x.ctrl&&x.name==="c"){g(),r(null);return}}}process.stdin.on("keypress",y),h()})}async function
|
|
1176
|
+
`),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 A=e[i[l]];g(),r(A?A.value:null);return}if(x.name==="escape"||x.ctrl&&x.name==="c"){g(),r(null);return}}}process.stdin.on("keypress",y),h()})}async function Xv(t){let e=Kv(),n=Gv(),o=Yv(),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 qm(t,s,{title:"Select Model"});return r?(zv(r),console.log(`${De.green}Switched to ${r}${De.reset}`),!0):(console.log(`${De.dim}Cancelled${De.reset}`),!1)}Fm.exports={pickFromList:qm,showModelPicker:Xv}});var jc=J((BE,Xm)=>{var Wm=require("fs"),Jv=require("path"),{atomicWrite:Vv,withFileLockSync:Zv}=gn(),{callChat:Bm}=Le(),{remember:Qv,listMemories:WE,recall:ek}=Gt(),Ic=4,tk=`You are a memory optimization agent for an AI coding assistant called nex-code.
|
|
1177
1177
|
Analyze this conversation history and extract actionable learnings the assistant should remember.
|
|
1178
1178
|
|
|
1179
1179
|
Return ONLY valid JSON in this exact format:
|
|
@@ -1201,13 +1201,13 @@ Rules:
|
|
|
1201
1201
|
- If nothing significant to learn, return {"memories": [], "nex_additions": [], "summary": "..."}
|
|
1202
1202
|
- Return ONLY the JSON, no markdown, no explanation`;function Hm(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(`
|
|
1203
1203
|
|
|
1204
|
-
`)}async function Km(t){if(t.filter(s=>s.role==="user").length<Ic)return{memories:[],nex_additions:[],summary:null,skipped:!0};let n=Hm(t);if(!n.trim())return{memories:[],nex_additions:[],summary:null,skipped:!0};let o=[{role:"system",content:
|
|
1204
|
+
`)}async function Km(t){if(t.filter(s=>s.role==="user").length<Ic)return{memories:[],nex_additions:[],summary:null,skipped:!0};let n=Hm(t);if(!n.trim())return{memories:[],nex_additions:[],summary:null,skipped:!0};let o=[{role:"system",content:tk},{role:"user",content:`Conversation to analyze:
|
|
1205
1205
|
|
|
1206
|
-
${n}`}];try{let i=((await Bm(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 Gm(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=
|
|
1206
|
+
${n}`}];try{let i=((await Bm(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 Gm(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=ek(s);i!==r&&(Qv(s,r),e.push({key:s,value:r,action:i?"updated":"added"}))}return e}function Ym(t){if(!t||t.length===0)return[];let e=Jv.join(process.cwd(),"NEX.md");return Zv(e,()=>{let n="";try{Wm.existsSync(e)&&(n=Wm.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(`
|
|
1207
1207
|
`)?s+i:s+`
|
|
1208
1208
|
`+i:i)}return o.length>0&&(s.endsWith(`
|
|
1209
1209
|
`)||(s+=`
|
|
1210
|
-
`),
|
|
1210
|
+
`),Vv(e,s)),o})}async function nk(t){let e=await Km(t);if(e.skipped)return{applied:[],nexAdded:[],summary:null,skipped:!0};if(e.error)return{applied:[],nexAdded:[],summary:null,error:e.error};let n=Gm(e.memories),o=Ym(e.nex_additions);return{applied:n,nexAdded:o,summary:e.summary}}var sk=`You are a knowledge base agent for an AI coding assistant called nex-code.
|
|
1211
1211
|
Analyze this conversation and extract knowledge worth persisting in the project knowledge base (.nex/brain/).
|
|
1212
1212
|
|
|
1213
1213
|
Return ONLY valid JSON in this exact format:
|
|
@@ -1241,16 +1241,16 @@ Rules:
|
|
|
1241
1241
|
---
|
|
1242
1242
|
- Maximum 3 documents per session. Quality over quantity.
|
|
1243
1243
|
- If nothing worth persisting: return {"documents": [], "skip_reason": "..."}
|
|
1244
|
-
- Return ONLY the JSON, no markdown fences, no explanation`;async function zm(t){if(t.filter(s=>s.role==="user").length<Ic)return{documents:[],skip_reason:"Session too short"};let n=Hm(t);if(!n.trim())return{documents:[],skip_reason:"No usable content"};let o=[{role:"system",content:
|
|
1244
|
+
- Return ONLY the JSON, no markdown fences, no explanation`;async function zm(t){if(t.filter(s=>s.role==="user").length<Ic)return{documents:[],skip_reason:"Session too short"};let n=Hm(t);if(!n.trim())return{documents:[],skip_reason:"No usable content"};let o=[{role:"system",content:sk},{role:"user",content:`Conversation to analyze:
|
|
1245
1245
|
|
|
1246
|
-
${n}`}];try{let i=((await Bm(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
|
|
1246
|
+
${n}`}];try{let i=((await Bm(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 ok(t){let e=await zm(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}=no(),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=`
|
|
1247
1247
|
|
|
1248
1248
|
## Update ${new Date().toISOString().split("T")[0]}
|
|
1249
1249
|
|
|
1250
|
-
${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}}Xm.exports={learnFromSession:
|
|
1250
|
+
${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}}Xm.exports={learnFromSession:nk,learnBrainFromSession:ok,reflectOnSession:Km,reflectBrain:zm,applyMemories:Gm,applyNexAdditions:Ym,LEARN_MIN_MESSAGES:Ic}});var th=J((HE,eh)=>{var{spawn:rk}=require("child_process"),Jm=require("path"),Vm=require("fs"),ik=require("os"),vn=new Map;function Zm(t){return typeof t!="string"?t:t.replace(/\$\{([^}]+)\}/g,(e,n)=>process.env[n]!==void 0?process.env[n]:"")}function Qm(t){let e=t||process.env.NEX_MCP_CONFIG||null,n=e?[e]:[Jm.join(process.cwd(),".nex","mcp.json"),Jm.join(ik.homedir(),".nex","mcp.json")];for(let o of n)if(Vm.existsSync(o))try{return JSON.parse(Vm.readFileSync(o,"utf-8"))}catch{}return{servers:{}}}function mi(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})+`
|
|
1251
1251
|
`,l="",u=setTimeout(()=>{f(),r(new Error(`MCP request timeout: ${e}`))},o);function d(m){l+=m.toString();let h=l.split(`
|
|
1252
|
-
`);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
|
|
1253
|
-
`):JSON.stringify(s)}function
|
|
1252
|
+
`);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 ak(t){let n=Qm(t).servers||{},o=[];for(let[s,r]of Object.entries(n)){if(vn.has(s)){let d=vn.get(s);o.push({name:s,tools:d.tools.length});continue}let i={};for(let[d,f]of Object.entries(r.env||{}))i[d]=Zm(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=rk(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 mi(u,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.4.8"}});let d=await mi(u,"tools/list",{}),f=d&&d.tools||[];vn.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 ck(t,e,n={}){let o=vn.get(t);if(!o)throw new Error(`MCP server not connected: ${t}`);let s=await mi(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(`
|
|
1253
|
+
`):JSON.stringify(s)}function lk(){let t=[];for(let[e,n]of vn)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 uk(){for(let[t,e]of vn){try{e.proc.kill()}catch{}vn.delete(t)}}function dk(){let t=[];for(let[e,n]of vn)t.push({name:e,connected:!0,toolCount:n.tools.length});return t}eh.exports={loadMcpServers:ak,callMcpTool:ck,getMcpTools:lk,shutdownMcpServers:uk,listMcpServers:dk,_interpolateEnv:Zm,_readConfig:Qm,_sendRequest:mi}});var rh=J((GE,oh)=>{var ct=require("fs"),Ms=require("path"),KE=require("os"),fk=require("readline"),{C:Q}=qe(),nh=".nex",Dc=null;function pk(t){Dc=t}function lt(t,e=""){let n=e?` ${Q.dim}[${e}]${Q.reset}`:"",o=` ${Q.cyan}${t}${n}${Q.reset}: `;return new Promise(s=>{let r=i=>{let c=i.trim()||e;s(c)};if(Dc)Dc.question(o,r);else{let i=fk.createInterface({input:process.stdin,output:process.stdout});i.question(o,c=>{i.close(),r(c)})}})}function Ns(t,e=!0){return lt(`${t} (${e?"Y/n":"y/N"})`,e?"y":"n").then(o=>o.toLowerCase()!=="n"&&o.toLowerCase()!=="no")}async function qc(t,e,n){let o=e.map((c,l)=>`${Q.dim}${l+1})${Q.reset} ${c}`).join(" ");console.log(` ${Q.cyan}${t}${Q.reset}`),console.log(` ${o}`);let s=n?e.indexOf(n)+1:1,r=await lt("Enter number",String(s)),i=parseInt(r,10)-1;return e[Math.max(0,Math.min(i,e.length-1))]}async function mk(){let t=Ms.join(process.cwd(),nh),e=Ms.join(t,"servers.json"),n={};if(ct.existsSync(e))try{n=JSON.parse(ct.readFileSync(e,"utf-8"))}catch{}console.log(`
|
|
1254
1254
|
${Q.bold}${Q.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${Q.reset}`),console.log(`${Q.bold}${Q.cyan}\u2551 nex-code Server Setup Wizard \u2551${Q.reset}`),console.log(`${Q.bold}${Q.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${Q.reset}
|
|
1255
1255
|
`);let o=Object.keys(n);if(o.length>0&&(console.log(`${Q.dim}Existing profiles: ${o.join(", ")}${Q.reset}`),!await Ns("Add or update a server profile?",!0))){console.log(`${Q.dim}No changes made.${Q.reset}
|
|
1256
1256
|
`);return}let s={...n},r=!0;for(;r;){console.log(`
|
|
@@ -1267,12 +1267,12 @@ ${Q.dim}Use /servers to list profiles, /servers ping to check connectivity.${Q.r
|
|
|
1267
1267
|
`)}async function sh(t,e){let n=e||Ms.join(process.cwd(),nh),o=Ms.join(n,"deploy.json"),s={};if(ct.existsSync(o))try{s=JSON.parse(ct.readFileSync(o,"utf-8"))}catch{}if(!t){let u=Ms.join(n,"servers.json");if(ct.existsSync(u))try{t=JSON.parse(ct.readFileSync(u,"utf-8"))}catch{t={}}else t={}}let r=Object.keys(t);console.log(`
|
|
1268
1268
|
${Q.bold}${Q.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${Q.reset}`),console.log(`${Q.bold}${Q.cyan}\u2551 Deploy Config Wizard \u2551${Q.reset}`),console.log(`${Q.bold}${Q.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${Q.reset}
|
|
1269
1269
|
`);let i=Object.keys(s);i.length>0&&console.log(`${Q.dim}Existing deploy configs: ${i.join(", ")}${Q.reset}`);let c={...s},l=!0;for(;l;){console.log(`
|
|
1270
|
-
${Q.bold}\u2500\u2500\u2500 New Deploy Config \u2500\u2500\u2500${Q.reset}`);let u=await lt("Config name (e.g. prod, staging)");if(!u){console.log(`${Q.red} Name is required.${Q.reset}`);continue}let d;r.length>0?d=await qc("Target server",r,r[0]):d=await lt("Target server (profile name or user@host)");let f=await qc("Deploy method",["rsync","git"],"rsync"),m="",h=[],p="";if(f==="rsync"){m=await lt("Local path to sync (e.g. dist/ or ./build)","dist/");let E=await lt("Exclude paths (comma-separated, e.g. node_modules,.env)","node_modules,.env");h=E?E.split(",").map(
|
|
1270
|
+
${Q.bold}\u2500\u2500\u2500 New Deploy Config \u2500\u2500\u2500${Q.reset}`);let u=await lt("Config name (e.g. prod, staging)");if(!u){console.log(`${Q.red} Name is required.${Q.reset}`);continue}let d;r.length>0?d=await qc("Target server",r,r[0]):d=await lt("Target server (profile name or user@host)");let f=await qc("Deploy method",["rsync","git"],"rsync"),m="",h=[],p="";if(f==="rsync"){m=await lt("Local path to sync (e.g. dist/ or ./build)","dist/");let E=await lt("Exclude paths (comma-separated, e.g. node_modules,.env)","node_modules,.env");h=E?E.split(",").map(k=>k.trim()).filter(Boolean):[]}else p=await lt("Branch to pull (leave empty for current remote branch)","main");let g=await lt(f==="git"?"Remote repo path (e.g. /home/jarvis/my-app)":"Remote destination path (e.g. /var/www/app)");if(!g){console.log(`${Q.red} Remote path is required.${Q.reset}`);continue}let y=await lt("Command to run on remote after deploy (leave empty to skip)",""),w=await lt("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 A=f==="git"?`${d}:${g}${p?` (${p})`:""}`:`${m.endsWith("/")?m:m+"/"} \u2192 ${d}:${g}`;console.log(`
|
|
1271
1271
|
${Q.green}\u2713${Q.reset} Deploy config "${u}": [${f}] ${A}`),y&&console.log(` ${Q.dim} Then: ${y}${Q.reset}`),w&&console.log(` ${Q.dim} Health: ${w}${Q.reset}`),l=await Ns(`
|
|
1272
1272
|
Add another deploy config?`,!1)}ct.existsSync(n)||ct.mkdirSync(n,{recursive:!0}),ct.writeFileSync(o,JSON.stringify(c,null,2)+`
|
|
1273
1273
|
`,"utf-8"),console.log(`
|
|
1274
1274
|
${Q.green}\u2713 Saved .nex/deploy.json (${Object.keys(c).length} config${Object.keys(c).length!==1?"s":""})${Q.reset}`),console.log(`${Q.dim}Use: deploy prod (or with explicit params)${Q.reset}
|
|
1275
|
-
`)}oh.exports={runServerWizard:
|
|
1275
|
+
`)}oh.exports={runServerWizard:mk,runDeployWizard:sh,setWizardRL:pk}});var yi=J((YE,ch)=>{"use strict";var $i=require("os"),No=require("path"),Ze=require("fs"),hk=require("axios"),gk=require("https"),hi=No.join($i.homedir(),".nex-code","known-models.json"),$k="https://ollama.com/api/tags",yk=60,wk={"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 Fc(){try{if(Ze.existsSync(hi))return JSON.parse(Ze.readFileSync(hi,"utf-8"))}catch{}return{benchmarked:[],lastChecked:null}}function bk(t){let e=No.dirname(hi);Ze.existsSync(e)||Ze.mkdirSync(e,{recursive:!0}),Ze.writeFileSync(hi,JSON.stringify(t,null,2))}function _k(t){let e=Fc(),n=new Set(e.benchmarked);for(let o of t)n.add(o);e.benchmarked=[...n],e.lastChecked=new Date().toISOString(),bk(e)}async function ih(){let t=process.env.OLLAMA_API_KEY;if(!t)throw new Error("OLLAMA_API_KEY not set");let e=new gk.Agent({keepAlive:!0});return((await hk.get($k,{headers:{Authorization:`Bearer ${t}`},timeout:15e3,httpsAgent:e})).data?.models||[]).map(o=>(o.name||o.model||"").replace(/:latest$/,"")).filter(Boolean)}async function xk(){let t=await ih(),e=Fc(),n=new Set(e.benchmarked),o=t.filter(s=>!n.has(s));return{allCloud:t,newModels:o,store:e}}var Uc="<!-- nex-benchmark-start -->",gi="<!-- nex-benchmark-end -->",vk={"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 kk(t){return t?t>=25e4?"256K":t>=19e4?"200K":t>=128e3?"131K":t>=64e3?"64K":`${Math.round(t/1024)}K`:"?"}function ah(t,e){let n=["\u{1F947}","\u{1F948}","\u{1F949}"],o=(e||new Date().toISOString()).split("T")[0],s=t.filter(r=>r.score>=yk).map((r,i)=>{let c=n[i]||"\u2014",l=kk(wk[r.model]),u=vk[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(`
|
|
1276
1276
|
`);return`${Uc}
|
|
1277
1277
|
<!-- Updated: ${o} \u2014 run \`/benchmark --discover\` after new Ollama Cloud releases -->
|
|
1278
1278
|
|
|
@@ -1282,20 +1282,20 @@ ${s}
|
|
|
1282
1282
|
|
|
1283
1283
|
> Rankings are nex-code-specific: tool name accuracy, argument validity, schema compliance.
|
|
1284
1284
|
> Toolathon (Minimax SOTA) measures different task types \u2014 run \`/benchmark --discover\` after model releases.
|
|
1285
|
-
${gi}`}function
|
|
1285
|
+
${gi}`}function Sk(t,e){if(!Ze.existsSync(e))return!1;let n=Ze.readFileSync(e,"utf-8"),o=n.indexOf(Uc),s=n.indexOf(gi);if(o===-1||s===-1)return!1;let r=n.slice(0,o),i=n.slice(s+gi.length),c=ah(t);return Ze.writeFileSync(e,r+c+i),!0}function Ek(t){let e=No.join($i.homedir(),".nex-code","models.env");if(!Ze.existsSync(e)||t.length===0)return{updated:!1,reason:"models.env not found or empty summary"};let n=t[0],o=Ze.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)`),Ze.writeFileSync(e,o),{updated:!0,previousModel:r,newModel:n.model}}function Tk(t){let{saveRoutingConfig:e}=xs(),n=No.join($i.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(Ze.existsSync(n)){let c=Ze.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(`
|
|
1286
1286
|
`),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}
|
|
1287
1287
|
${u}
|
|
1288
1288
|
${f}`+c.slice(h+f.length))}else c+=`
|
|
1289
1289
|
${d}
|
|
1290
1290
|
${u}
|
|
1291
1291
|
${f}
|
|
1292
|
-
`;Ze.writeFileSync(n,c),i=!0}return{saved:!0,envUpdated:i,changes:o}}var
|
|
1292
|
+
`;Ze.writeFileSync(n,c),i=!0}return{saved:!0,envUpdated:i,changes:o}}var Rk=/thinking|reasoning|instruct|planner|orchestrat/i;function Ck(t){return Rk.test(t)}function Ak(t){if(!t||t.length===0)return{updated:!1};let e=No.join($i.homedir(),".nex-code","models.env");if(!Ze.existsSync(e))return{updated:!1};let n=Ze.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+=`
|
|
1293
1293
|
${u}
|
|
1294
|
-
`,Ze.writeFileSync(e,n),{updated:!0,previousModel:s,newModel:i.model}}ch.exports={findNewModels:xv,fetchCloudModels:ih,loadKnownModels:Fc,markBenchmarked:_v,updateReadme:Sv,updateModelsEnv:Ev,updateRoutingConfig:Tv,generateBenchmarkBlock:ah,checkOrchestratorCandidate:Cv,updateOrchestratorModel:Av,SENTINEL_START:Uc,SENTINEL_END:gi}});var Xn=J((zE,yh)=>{"use strict";var{C:H}=qe(),Ov=Le(),{TOOL_DEFINITIONS:lh}=It(),{saveRoutingConfig:Nv}=xs(),Mo=[{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:"resilience-edit-failed",category:"resilience",prompt:"Your edit_file call on server.js failed: old_string 'const PORT = 3000' was not found in the file. What do you do next to recover?",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("server")},{id:"resilience-file-not-found",category:"resilience",prompt:"read_file returned 'file not found' for src/utils/helpers.js. You need to find where the helper functions are now. What tool do you use?",expectedTool:["glob_files","bash"],validateArgs:t=>{let e=JSON.stringify(t).toLowerCase();return e.includes("src")||e.includes("helper")||e.includes("util")||e.includes("*.js")}},{id:"resilience-large-file-nav",category:"resilience",prompt:"The file src/api.js is 2800 lines. You need to locate the authenticateUser function. What is the most efficient tool to use \u2014 read_file or bash with grep?",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("grep")||t.command.includes("rg")||t.command.includes("awk"))},{id:"resilience-broken-import",category:"resilience",prompt:"TypeScript reports: Cannot find module './config'. The file was recently renamed. What tool do you use to find the new location?",expectedTool:["glob_files","bash"],validateArgs:t=>{let e=JSON.stringify(t).toLowerCase();return e.includes("config")||e.includes("*.ts")||e.includes("*.js")||e.includes("find")}},{id:"resilience-bash-error-recover",category:"resilience",prompt:"The command 'npm test' failed with exit code 1. The output contains 'SyntaxError: Unexpected token' in src/parser.js:45. What is your next action?",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("parser")},{id:"resilience-grep-no-match",category:"resilience",prompt:"grep returned zero matches for 'getUserById' in src/. The function exists but may have been renamed. What bash command finds all exported function names in src/ to identify the current name?",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("grep")||t.command.includes("rg")||t.command.includes("src"))},{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"))}],uh=["glm-5:cloud","nemotron-3-super:cloud","minimax-m2.7:cloud","qwen3-coder:480b","kimi-k2:1t","devstral-2:123b","devstral-small-2:24b","qwen3-coder-next"],dh=["minimax-m2.7:cloud","qwen3-coder:480b","devstral-2:123b"],Mv=7,wi={producedToolCall:.2,correctTool:.35,validArgs:.3,schemaCompliant:.15},Pv="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 fh(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:Pv},{role:"user",content:t.prompt}],s=Date.now();try{let r=await Ov.callChat(o,lh,{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=lh.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 Po(t){return t.error?0:((t.producedToolCall?wi.producedToolCall:0)+(t.correctTool?wi.correctTool:0)+(t.validArgs?wi.validArgs:0)+(t.schemaCompliant?wi.schemaCompliant:0))*100}var Lv={coding:"coding",search:"coding",shell:"coding",schema:"coding","multi-step":"coding",reasoning:"coding",frontend:"frontend",sysadmin:"sysadmin",data:"data",agentic:"agentic",resilience:"coding"};function Wc(t){return Object.entries(t).map(([e,n])=>{let o=n.map(Po),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=>Lv[d.category]===c);if(l.length===0)continue;let u=l.map(Po).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 ph(t){let e={};for(let o of["coding","frontend","sysadmin","data","agentic"]){let s=t.filter(l=>l.categoryScores[o]!==void 0).sort((l,u)=>u.categoryScores[o]-l.categoryScores[o]);if(s.length===0)continue;let r=s[0],c=s.filter(l=>r.categoryScores[o]-l.categoryScores[o]<=5).sort((l,u)=>l.avgLatency-u.avgLatency)[0];e[o]={model:c.model,score:c.categoryScores[o],avgLatency:c.avgLatency}}return e}function mh(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(`
|
|
1295
|
-
${H.bold}${n}${H.reset}`),console.log(r);let i=o.map(u=>u.label.padEnd(u.width)).join(" ");if(console.log(`${H.dim}${i}${H.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),A=u.errorCount>0?`${H.red}${u.errorCount}${H.reset}`:`${H.dim}0${H.reset}`,E=u.score>=80?H.green:u.score>=60?H.yellow:H.red,
|
|
1294
|
+
`,Ze.writeFileSync(e,n),{updated:!0,previousModel:s,newModel:i.model}}ch.exports={findNewModels:xk,fetchCloudModels:ih,loadKnownModels:Fc,markBenchmarked:_k,updateReadme:Sk,updateModelsEnv:Ek,updateRoutingConfig:Tk,generateBenchmarkBlock:ah,checkOrchestratorCandidate:Ck,updateOrchestratorModel:Ak,SENTINEL_START:Uc,SENTINEL_END:gi}});var Xn=J((zE,yh)=>{"use strict";var{C:H}=qe(),Ok=Le(),{TOOL_DEFINITIONS:lh}=It(),{saveRoutingConfig:Nk}=xs(),Mo=[{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:"resilience-edit-failed",category:"resilience",prompt:"Your edit_file call on server.js failed: old_string 'const PORT = 3000' was not found in the file. What do you do next to recover?",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("server")},{id:"resilience-file-not-found",category:"resilience",prompt:"read_file returned 'file not found' for src/utils/helpers.js. You need to find where the helper functions are now. What tool do you use?",expectedTool:["glob_files","bash"],validateArgs:t=>{let e=JSON.stringify(t).toLowerCase();return e.includes("src")||e.includes("helper")||e.includes("util")||e.includes("*.js")}},{id:"resilience-large-file-nav",category:"resilience",prompt:"The file src/api.js is 2800 lines. You need to locate the authenticateUser function. What is the most efficient tool to use \u2014 read_file or bash with grep?",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("grep")||t.command.includes("rg")||t.command.includes("awk"))},{id:"resilience-broken-import",category:"resilience",prompt:"TypeScript reports: Cannot find module './config'. The file was recently renamed. What tool do you use to find the new location?",expectedTool:["glob_files","bash"],validateArgs:t=>{let e=JSON.stringify(t).toLowerCase();return e.includes("config")||e.includes("*.ts")||e.includes("*.js")||e.includes("find")}},{id:"resilience-bash-error-recover",category:"resilience",prompt:"The command 'npm test' failed with exit code 1. The output contains 'SyntaxError: Unexpected token' in src/parser.js:45. What is your next action?",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("parser")},{id:"resilience-grep-no-match",category:"resilience",prompt:"grep returned zero matches for 'getUserById' in src/. The function exists but may have been renamed. What bash command finds all exported function names in src/ to identify the current name?",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("grep")||t.command.includes("rg")||t.command.includes("src"))},{id:"ssh-exec-log",category:"ssh",prompt:'Show the last 50 lines of /var/log/nginx/error.log on server "prod-1".',expectedTool:"ssh_exec",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("tail")||t.command.includes("log"))&&(typeof t.host=="string"||typeof t.profile=="string")},{id:"ssh-exec-service",category:"ssh",prompt:'Restart the nginx service on server "prod-1".',expectedTool:"ssh_exec",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("nginx")||t.command.includes("systemctl")||t.command.includes("restart"))&&(typeof t.host=="string"||typeof t.profile=="string")},{id:"ssh-exec-port",category:"ssh",prompt:'Check if port 8080 is listening on server "prod-1".',expectedTool:"ssh_exec",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("8080")||t.command.includes("ss")||t.command.includes("netstat")||t.command.includes("lsof"))&&(typeof t.host=="string"||typeof t.profile=="string")},{id:"ssh-exec-processes",category:"ssh",prompt:'Show the top CPU-consuming processes on server "prod-1".',expectedTool:"ssh_exec",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("top")||t.command.includes("ps")||t.command.includes("htop"))&&(typeof t.host=="string"||typeof t.profile=="string")},{id:"git-diff-staged",category:"git",prompt:"Show all staged changes before committing.",expectedTool:["git_diff","bash"],validateArgs:t=>!!(t.staged===!0||t.staged==="true"||typeof t.command=="string"&&t.command.includes("diff"))},{id:"git-log-recent",category:"git",prompt:"Show the last 5 commit messages with their hashes.",expectedTool:["git_log","bash"],validateArgs:t=>!!(typeof t.limit=="number"||typeof t.n=="number"||typeof t.command=="string"&&t.command.includes("log"))},{id:"git-status-check",category:"git",prompt:"Check if there are any uncommitted changes in the repository.",expectedTool:["git_status","bash"],validateArgs:t=>t.path===void 0&&t.command===void 0?!1:(typeof t.command=="string"&&t.command.includes("status"),!0)},{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"))},{id:"agentic-spawn-parallel",category:"agentic",prompt:"Search for all TODO comments and all FIXME comments across the codebase in parallel using multiple agents.",expectedTool:"spawn_agents",validateArgs:t=>Array.isArray(t.agents)&&t.agents.length>=2},{id:"agentic-multi-investigate",category:"agentic",prompt:"The app is crashing on startup. Spawn parallel agents to check: (1) recent git changes, (2) npm dependency issues, (3) the main entry file for syntax errors.",expectedTool:"spawn_agents",validateArgs:t=>Array.isArray(t.agents)&&t.agents.length>=2}],uh=["devstral-2:123b","kimi-k2.5","glm-5:cloud","qwen3-coder:480b","qwen3-coder-next","ministral-3:14b","minimax-m2.7:cloud","kimi-k2:1t"],dh=["minimax-m2.7:cloud","qwen3-coder:480b","devstral-2:123b"],Mk=7,wi={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 fh(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 Ok.callChat(o,lh,{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=lh.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 Po(t){return t.error?0:((t.producedToolCall?wi.producedToolCall:0)+(t.correctTool?wi.correctTool:0)+(t.validArgs?wi.validArgs:0)+(t.schemaCompliant?wi.schemaCompliant:0))*100}var Lk={coding:"coding",search:"coding",shell:"coding",schema:"coding","multi-step":"coding",reasoning:"coding",frontend:"frontend",sysadmin:"sysadmin",data:"data",agentic:"agentic",resilience:"coding",ssh:"sysadmin",git:"coding"};function Wc(t){return Object.entries(t).map(([e,n])=>{let o=n.map(Po),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=>Lk[d.category]===c);if(l.length===0)continue;let u=l.map(Po).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 ph(t){let e={};for(let o of["coding","frontend","sysadmin","data","agentic"]){let s=t.filter(l=>l.categoryScores[o]!==void 0).sort((l,u)=>u.categoryScores[o]-l.categoryScores[o]);if(s.length===0)continue;let r=s[0],c=s.filter(l=>r.categoryScores[o]-l.categoryScores[o]<=5).sort((l,u)=>l.avgLatency-u.avgLatency)[0];e[o]={model:c.model,score:c.categoryScores[o],avgLatency:c.avgLatency}}return e}function mh(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(`
|
|
1295
|
+
${H.bold}${n}${H.reset}`),console.log(r);let i=o.map(u=>u.label.padEnd(u.width)).join(" ");if(console.log(`${H.dim}${i}${H.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),A=u.errorCount>0?`${H.red}${u.errorCount}${H.reset}`:`${H.dim}0${H.reset}`,E=u.score>=80?H.green:u.score>=60?H.yellow:H.red,k=d===0?`${H.yellow}${f}${H.reset}`:`${H.dim}${f}${H.reset}`;console.log(`${k} ${E}${m}${H.reset} ${H.bold}${E}${h}${H.reset} ${p} ${g} ${y} ${w} ${H.dim}${x}${H.reset} ${A}`)}),console.log(r),t.length>0){let u=t[0];if(console.log(`
|
|
1296
1296
|
${H.bold}${H.green}Winner: ${u.model}${H.reset} score ${u.score}/100`),t.length>1){let d=(u.score-t[1].score).toFixed(1);console.log(`${H.dim}+${d} pts over ${t[1].model}${H.reset}`)}}let c=["coding","frontend","sysadmin","data","agentic"];if(t.some(u=>Object.keys(u.categoryScores).length>1)){console.log(`
|
|
1297
|
-
${H.bold}Best model per task type:${H.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?H.green:m>=60?H.yellow:H.red;console.log(` ${H.dim}${u.padEnd(10)}${H.reset} ${h}${f.model}${H.reset} ${H.dim}${m}/100${H.reset}`)}}console.log()}function hh(t){if(!(!t||t.length<2))try{let e=ph(t),{loadRoutingConfig:n}=xs(),o=n(),s={...o};for(let[i,{model:c}]of Object.entries(e))
|
|
1298
|
-
${H.dim} Routing updated: ${r.join(", ")}${H.reset}`)}catch{}}async function
|
|
1297
|
+
${H.bold}Best model per task type:${H.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?H.green:m>=60?H.yellow:H.red;console.log(` ${H.dim}${u.padEnd(10)}${H.reset} ${h}${f.model}${H.reset} ${H.dim}${m}/100${H.reset}`)}}console.log()}function hh(t){if(!(!t||t.length<2))try{let e=ph(t),{loadRoutingConfig:n}=xs(),o=n(),s={...o},r=[];for(let[i,{model:c,score:l}]of Object.entries(e)){let u=o[i];u&&u!==c&&!t.find(f=>f.model===u)||s[i]!==c&&(s[i]=c,r.push(`${i}\u2192${c}`))}r.length>0&&(Nk(s),console.log(`
|
|
1298
|
+
${H.dim} Routing updated: ${r.join(", ")}${H.reset}`))}catch{}}async function Ik({models:t,quick:e=!1,onProgress:n}={}){let o=e?Mo.slice(0,Mk):Mo,s=t?.length>0?t:e?dh:uh,r={};for(let c of s){r[c]=[];for(let l of o){n?.({model:c,task:l.id,done:!1});let u=await fh(l,c);r[c].push(u),n?.({model:c,task:l.id,done:!0,score:Po(u),error:u.error})}}let i=Wc(r);return mh(i,o.length),hh(i),i}async function jk({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 Mo){n?.({model:i,task:c.id,done:!1});let l=await fh(c,i);o[i].push(l),n?.({model:i,task:c.id,done:!0,score:Po(l),error:l.error})}}let r=[...Wc(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),mh(r,Mo.length),hh(r),r}var bi=[{id:"simple_question",name:"Simple Convergence",prompt:"What is 2+2?",maxTurns:3,successCriteria:["4"]}];function gh(t){let e=require("fs"),o=require("path").join(t||process.cwd(),".nex","benchmark-config.json");if(!e.existsSync(o))return console.log(`${H.yellow}No scenarios configured.${H.reset} Create ${H.dim}.nex/benchmark-config.json${H.reset} to define your benchmark scenarios.
|
|
1299
1299
|
Example:
|
|
1300
1300
|
{
|
|
1301
1301
|
"scenarios": [
|
|
@@ -1310,26 +1310,26 @@ ${H.dim} Routing updated: ${r.join(", ")}${H.reset}`)}catch{}}async function Iv
|
|
|
1310
1310
|
}
|
|
1311
1311
|
`),bi;try{let s=JSON.parse(e.readFileSync(o,"utf-8"));return!Array.isArray(s.scenarios)||s.scenarios.length===0?(console.log(`${H.yellow}benchmark-config.json has no scenarios \u2014 using defaults.${H.reset}
|
|
1312
1312
|
`),bi):s.scenarios}catch(s){return console.log(`${H.yellow}Failed to parse benchmark-config.json: ${s.message}${H.reset}
|
|
1313
|
-
`),bi}}function $h(t,e){let{scoreMessages:n,_extractToolCalls:o,_getLastAssistantText:s}=Br(),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
|
|
1313
|
+
`),bi}}function $h(t,e){let{scoreMessages:n,_extractToolCalls:o,_getLastAssistantText:s}=Br(),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 Dk(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 qk(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(`
|
|
1314
1314
|
\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
|
|
1315
|
-
`)}function
|
|
1315
|
+
`)}function Fk(t=10){let e=require("fs"),o=require("path").join(process.cwd(),".nex","benchmark-history.json");if(!e.existsSync(o)){console.log(`${H.yellow}No score history yet. Run a session first.${H.reset}
|
|
1316
1316
|
`);return}let s=[];try{s=JSON.parse(e.readFileSync(o,"utf-8"))}catch{s=[]}if(!Array.isArray(s)||s.length===0){console.log(`${H.yellow}Score history is empty.${H.reset}
|
|
1317
1317
|
`);return}let r=s.slice(-t);console.log(`
|
|
1318
|
-
${H.bold}Score History (last ${r.length} session${r.length===1?"":"s"}):${H.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?`${H.yellow}\u26A0 ${i.issues.slice(0,2).map(p=>p.substring(0,30)).join(", ")}${H.reset}`:`${H.green}\u2713${H.reset}`,h=i.score>=8?H.green:i.score>=6?H.yellow:H.red;console.log(` ${H.dim}${c}${H.reset} ${H.dim}v${l}${H.reset} ${H.dim}${u}${H.reset} ${h}${d} ${f}${H.reset} ${m}`)}console.log()}async function
|
|
1318
|
+
${H.bold}Score History (last ${r.length} session${r.length===1?"":"s"}):${H.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?`${H.yellow}\u26A0 ${i.issues.slice(0,2).map(p=>p.substring(0,30)).join(", ")}${H.reset}`:`${H.green}\u2713${H.reset}`,h=i.score>=8?H.green:i.score>=6?H.yellow:H.red;console.log(` ${H.dim}${c}${H.reset} ${H.dim}v${l}${H.reset} ${H.dim}${u}${H.reset} ${h}${d} ${f}${H.reset} ${m}`)}console.log()}async function Uk({dryRun:t=!1,model:e,cwd:n,onProgress:o}={}){let s=Qn(),r=gh(n);if(t){console.log(`
|
|
1319
1319
|
${H.bold}Jarvis Benchmark \u2014 Scenarios (dry-run):${H.reset}
|
|
1320
1320
|
`);for(let l of r)console.log(` ${H.cyan}${l.id.padEnd(20)}${H.reset} ${H.dim}${l.name}${H.reset} maxTurns=${l.maxTurns}`),console.log(` ${H.dim}${l.prompt.substring(0,80)}${H.reset}`);return console.log(),[]}let i=(()=>{if(e)return typeof e=="object"?e.id||"unknown":e;try{let{getActiveModel:l}=ls(),u=l?l():null;return u?typeof u=="object"?u.id||"unknown":u:"unknown"}catch{return"unknown"}})(),c=[];for(let l of r){o?.({id:l.id,name:l.name,done:!1}),console.log(`
|
|
1321
|
-
${H.dim}Running scenario: ${l.name}...${H.reset}`);let{messages:u,timedOut:d}=await
|
|
1321
|
+
${H.dim}Running scenario: ${l.name}...${H.reset}`);let{messages:u,timedOut:d}=await Dk(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=$h(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}=Br();h(f.score,{version:s.version,model:i,sessionName:`bench:${l.id}`,issues:f.issues})}catch{}}return qk(c,s.version,i),c}yh.exports={runBenchmark:Ik,runDiscoverBenchmark:jk,buildSummary:Wc,buildCategoryWinners:ph,TASKS:Mo,scoreResult:Po,DEFAULT_MODELS:uh,QUICK_MODELS:dh,runJarvisBenchmark:Uk,showScoreTrend:Fk,loadScenarios:gh,DEFAULT_SCENARIOS:bi,scoreJarvisScenario:$h}});var Th=J((XE,Eh)=>{"use strict";var Wk=require("os"),_h=require("path"),Bc=require("fs"),{callWithRetry:wh}=Cr(),{parseModelSpec:Bk}=Le(),{extractJSON:bh,DECOMPOSE_PROMPT:Hk,SYNTHESIZE_PROMPT:Kk}=wo(),{C:kt}=qe(),_i=_h.join(Wk.homedir(),".nex-code","orchestrator-bench.json"),xh=[{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 vh(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 kh(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 Sh(t,e){let n={};if(e){let s=Bk(e);s.provider&&(n.provider=s.provider),s.model&&(n.model=s.model)}let o=Date.now();try{if(t.type==="decompose"){let s=Hk.replace("{maxSubTasks}",String(t.maxSubTasks)).replace("{prompt}",t.prompt),r=await wh([{role:"system",content:s},{role:"user",content:t.prompt}],[],n),i=bh(r.content||""),c=Date.now()-o;return{score:vh(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}] ---
|
|
1322
1322
|
Task: ${d.task}
|
|
1323
1323
|
Result: ${d.result}
|
|
1324
1324
|
Tools: ${d.toolsUsed.join(", ")}`}).join(`
|
|
1325
1325
|
|
|
1326
|
-
`),r=
|
|
1327
|
-
${
|
|
1328
|
-
`);let e=` ${"Model".padEnd(25)} ${"Decompose".padEnd(10)} ${"Synthesize".padEnd(11)} ${"Speed".padEnd(8)} ${"Score".padEnd(8)}`;console.log(`${
|
|
1329
|
-
${
|
|
1330
|
-
`))}Eh.exports={runOrchestratorBenchmark:
|
|
1326
|
+
`),r=Kk.replace("{prompt}",t.prompt).replace("{results}",s),i=await wh([{role:"system",content:r},{role:"user",content:"Synthesize the sub-agent results above."}],[],n),c=bh(i.content||""),l=Date.now()-o;return{score:kh(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 Gk(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 xh){n({model:r,scenario:h.id,done:!1});let p=await Sh(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=_h.dirname(_i);return Bc.existsSync(s)||Bc.mkdirSync(s,{recursive:!0}),Bc.writeFileSync(_i,JSON.stringify({date:new Date().toISOString().slice(0,10),results:o},null,2)),o}function Yk(t){console.log(`
|
|
1327
|
+
${kt.bold}${kt.cyan}Orchestrator Model Benchmark${kt.reset}
|
|
1328
|
+
`);let e=` ${"Model".padEnd(25)} ${"Decompose".padEnd(10)} ${"Synthesize".padEnd(11)} ${"Speed".padEnd(8)} ${"Score".padEnd(8)}`;console.log(`${kt.dim}${e}${kt.reset}`),console.log(` ${kt.dim}${"\u2500".repeat(65)}${kt.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)} ${kt.bold}${n.overall}/10${kt.reset}`)}t.length>0&&(console.log(`
|
|
1329
|
+
${kt.green}Best orchestrator: ${t[0].model} (${t[0].overall}/10)${kt.reset}`),console.log(` ${kt.dim}Saved to ${_i}${kt.reset}
|
|
1330
|
+
`))}Eh.exports={runOrchestratorBenchmark:Gk,ORCHESTRATOR_SCENARIOS:xh,scoreDecompose:vh,scoreSynthesize:kh,runScenario:Sh,printResults:Yk,RESULTS_PATH:_i}});var Ah=J((JE,Ch)=>{var zk=require("axios"),Lo=require("fs"),Rh=require("path"),Xk="nex-code",Hc=Rh.join(process.cwd(),".nex"),Kc=Rh.join(Hc,"last-version-check");Lo.existsSync(Hc)||Lo.mkdirSync(Hc,{recursive:!0});async function Jk(){try{let t=Zk(),e=Date.now();if(t&&e-t<1440*60*1e3)return{hasNewVersion:!1};Qk(e);let n=Vk(),s=(await zk.get(`https://registry.npmjs.org/${Xk}/latest`,{timeout:5e3})).data.version,r=eS(s,n);return{hasNewVersion:r,latestVersion:r?s:void 0,currentVersion:r?n:void 0}}catch{return{hasNewVersion:!1}}}function Vk(){return Qn().version}function Zk(){try{if(Lo.existsSync(Kc)){let t=Lo.readFileSync(Kc,"utf8");return parseInt(t,10)}}catch{}return null}function Qk(t){try{Lo.writeFileSync(Kc,t.toString())}catch{}}function eS(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}}Ch.exports={checkForNewVersion:Jk}});var el=J((ZE,Wh)=>{var tS=require("readline"),ut=require("fs"),Ye=require("path"),{C:a,banner:nS,cleanupTerminal:Oh}=qe(),{isDark:sS}=Rn(),{listProviders:zc,getActiveProviderName:Jn,listAllModels:VE,setFallbackChain:oS,getFallbackChain:rS,getProvider:iS}=Le(),{flushAutoSave:Nh}=Ft(),{getActiveModel:dn,setActiveModel:Xc}=ls(),{printContext:Mh}=Ur(),{loadAllSkills:aS,getSkillCommands:vi,handleSkillCommand:cS}=wn(),{setReadlineInterface:lS,setAutoConfirm:uS,getAutoConfirm:Gc,setAllowAlwaysHandler:dS}=tt(),{StickyFooter:fS}=Dm(),Lt=process.cwd(),un=null;function Ph(){return un?.signal??null}var Do=[{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 Lh(){let t=vi(),e=[...Do,...t],n=Math.max(...e.map(o=>o.cmd.length));console.log("");for(let{cmd:o,desc:s}of Do)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(`
|
|
1331
1331
|
${a.dim}Type /help for detailed usage${a.reset}
|
|
1332
|
-
`)}function Ih(t){try{let e,n;t.endsWith("/")||t.endsWith(Ye.sep)?(e=t,n=""):(e=Ye.dirname(t),n=Ye.basename(t)),e.startsWith("~")&&(e=Ye.join(require("os").homedir(),e.slice(1)));let o=Ye.isAbsolute(e)?e:Ye.resolve(Lt,e);if(!ut.existsSync(o)||!ut.statSync(o).isDirectory())return[];let s=ut.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(Ye.sep)?t:Ye.dirname(t)+"/",l=c==="./"&&!t.startsWith("./")?i.name:c+i.name;r.push(i.isDirectory()?l+"/":l)}return r}catch{return[]}}function jh(t){if(t.startsWith("/")){let o=[...Do,...
|
|
1332
|
+
`)}function Ih(t){try{let e,n;t.endsWith("/")||t.endsWith(Ye.sep)?(e=t,n=""):(e=Ye.dirname(t),n=Ye.basename(t)),e.startsWith("~")&&(e=Ye.join(require("os").homedir(),e.slice(1)));let o=Ye.isAbsolute(e)?e:Ye.resolve(Lt,e);if(!ut.existsSync(o)||!ut.statSync(o).isDirectory())return[];let s=ut.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(Ye.sep)?t:Ye.dirname(t)+"/",l=c==="./"&&!t.startsWith("./")?i.name:c+i.name;r.push(i.isDirectory()?l+"/":l)}return r}catch{return[]}}function jh(t){if(t.startsWith("/")){let o=[...Do,...vi()],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("~"))?[Ih(n),n]:[[],t]}function Dh(){console.log(`
|
|
1333
1333
|
${a.bold}${a.cyan}Commands:${a.reset}
|
|
1334
1334
|
${a.cyan}/help${a.reset} ${a.dim}Show this help${a.reset}
|
|
1335
1335
|
${a.cyan}/model [spec]${a.reset} ${a.dim}Show/switch model (e.g. openai:gpt-4o, claude-sonnet)${a.reset}
|
|
@@ -1406,7 +1406,7 @@ ${a.bold}${a.cyan}Token Usage:${a.reset}`),console.log(` ${a.dim}Model:${a.rese
|
|
|
1406
1406
|
${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}=cs();return o.join(" ").trim()==="reset"?(r(),console.log(`${a.green}Cost tracking reset${a.reset}`),!0):(console.log(`
|
|
1407
1407
|
${s()}
|
|
1408
1408
|
`),!0)}case"/budget":{let{getCostLimits:s,getProviderSpend:r,checkBudget:i,removeCostLimit:c,saveCostLimits:l,setCostLimit:u}=cs(),d=o[0];if(!d){let h=s(),p=zc();console.log(`
|
|
1409
|
-
${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 A=Math.min(100,Math.round(w/x*100)),E=10,
|
|
1409
|
+
${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 A=Math.min(100,Math.round(w/x*100)),E=10,k=Math.round(A/100*E),T=E-k,P=`${A>=100?a.red:A>=80?a.yellow:a.green}${"\u2588".repeat(k)}${a.dim}${"\u2591".repeat(T)}${a.reset}`;console.log(` ${a.bold}${y.provider}:${a.reset} $${w.toFixed(2)} / $${x.toFixed(2)} (${A}%) ${P}`)}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}=Ae(),{clearHistory:i}=nn(),c=r();if(c.filter(d=>d.role==="user").length>=4){process.stdout.write(`${a.dim}Reflecting on session...${a.reset} `);let{learnFromSession:d}=jc();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}
|
|
1410
1410
|
`)}else process.stdout.write(`${a.dim}nothing new${a.reset}
|
|
1411
1411
|
`)}).catch(()=>process.stdout.write(`
|
|
1412
1412
|
`))}s(),i();let{deleteSession:u}=Ft();return u("_autosave"),console.log(`${a.green}Conversation cleared${a.reset}`),!0}case"/retry":{let{getConversationMessages:s,setConversationMessages:r,processInput:i}=Ae(),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}=Le();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(`
|
|
@@ -1418,14 +1418,14 @@ ${a.bold}${a.cyan}Sessions:${a.reset}`);for(let i of r){let c=i.updatedAt?new Da
|
|
|
1418
1418
|
${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}=no(),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}
|
|
1419
1419
|
|
|
1420
1420
|
`);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(`
|
|
1421
|
-
${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),A=Array.isArray(x.tags)?x.tags.join(", "):"",E=w.size<1024?`${w.size}B`:`${(w.size/1024).toFixed(1)}K`,
|
|
1421
|
+
${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),A=Array.isArray(x.tags)?x.tags.join(", "):"",E=w.size<1024?`${w.size}B`:`${(w.size/1024).toFixed(1)}K`,k=w.modified.toLocaleDateString();console.log(` ${a.cyan}${w.name.padEnd(g+2)}${a.reset}${a.dim}${A.substring(0,y-1).padEnd(y)}${E.padStart(7)} ${k}${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(`
|
|
1422
1422
|
${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(`
|
|
1423
1423
|
${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(`
|
|
1424
1424
|
${a.bold}${a.cyan}${h}.md${a.reset}
|
|
1425
1425
|
`),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}=tt();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(`
|
|
1426
|
-
${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 A=p.reduce((E,
|
|
1426
|
+
${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 A=p.reduce((E,k)=>E+k.size,0);console.log(` Total size: ${A<1024?A+"B":(A/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(`
|
|
1427
1427
|
${a.bold}${a.cyan}Brain Changes (git diff):${a.reset}
|
|
1428
|
-
`),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:A}=require("child_process"),{promisify:E}=require("util"),
|
|
1428
|
+
`),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:A}=require("child_process"),{promisify:E}=require("util"),k=E(A);try{await k(`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(`
|
|
1429
1429
|
${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(`
|
|
1430
1430
|
${a.dim}Commands: add \xB7 list \xB7 search \xB7 show \xB7 remove \xB7 rebuild \xB7 embed \xB7 status \xB7 review \xB7 undo${a.reset}
|
|
1431
1431
|
`);else{console.log(`
|
|
@@ -1434,14 +1434,14 @@ ${a.dim}Use /brain search <query> \xB7 /brain show <name> \xB7 /brain add <name>
|
|
|
1434
1434
|
`)}return!0}}}case"/learn":{let{learnFromSession:s,learnBrainFromSession:r}=jc(),{getConversationMessages:i}=Ae(),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}=Ae(),{getUsage:r}=nt(),{TOOL_DEFINITIONS:i}=It(),{listMemories:c}=Gt(),l=s(),u=r(l,i),d=dn(),f=Jn(),m=c();console.log(`
|
|
1435
1435
|
${a.bold}${a.cyan}Optimization Report${a.reset}
|
|
1436
1436
|
`);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(`
|
|
1437
|
-
${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 A=[...m].sort((T,O)=>new Date(O.updatedAt)-new Date(T.updatedAt))[0],E=A?Math.round((Date.now()-new Date(A.updatedAt))/6e4):null,
|
|
1437
|
+
${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 A=[...m].sort((T,O)=>new Date(O.updatedAt)-new Date(T.updatedAt))[0],E=A?Math.round((Date.now()-new Date(A.updatedAt))/6e4):null,k=E!==null?E<60?`${E}m ago`:`${Math.round(E/60)}h ago`:"?";console.log(` ${a.dim}Latest update: ${k}${a.reset}`),m.length>30&&console.log(` ${a.yellow}\u2192 Many memories (${m.length}) \u2014 consider pruning with /forget${a.reset}`)}console.log(`
|
|
1438
1438
|
${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(`
|
|
1439
1439
|
${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(`
|
|
1440
|
-
${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}=Yt(),{invalidateSystemPromptCache:h}=Ae(),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:A}=require("child_process");if(console.log(`${a.dim}Opening plan in ${x}... (save and close to update)${a.reset}`),A(x,[w],{stdio:"inherit"}).status===0){let{setPlanContent:
|
|
1440
|
+
${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}=Yt(),{invalidateSystemPromptCache:h}=Ae(),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:A}=require("child_process");if(console.log(`${a.dim}Opening plan in ${x}... (save and close to update)${a.reset}`),A(x,[w],{stdio:"inherit"}).status===0){let{setPlanContent:k}=Yt(),T=require("fs").readFileSync(w,"utf-8");k(T);let O=f(T);if(O.length>0){let W=s()?.task||"Task";m(W,O),console.log(`${a.green}Plan updated \u2014 ${O.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),Io(),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:A}=Ae(),E=`[PLAN APPROVED \u2014 EXECUTE NOW]
|
|
1441
1441
|
|
|
1442
1442
|
Implement the following plan step by step. All tools are now available.
|
|
1443
1443
|
|
|
1444
|
-
${g}`;try{await A(E)}catch(
|
|
1444
|
+
${g}`;try{await A(E)}catch(k){console.log(`${a.red}Error: ${k.message?.split(`
|
|
1445
1445
|
`)[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),Io(),h(),console.log(`
|
|
1446
1446
|
${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}
|
|
1447
1447
|
${a.cyan}${a.bold}\u2502${a.reset} Analysis only \u2014 no file changes until approved ${a.cyan}${a.bold}\u2502${a.reset}
|
|
@@ -1542,23 +1542,23 @@ ${a.bold}${a.cyan}Deploy configs (${i.length}):${a.reset}`);for(let[l,u]of Objec
|
|
|
1542
1542
|
${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}
|
|
1543
1543
|
`),!0}case"/init":{let{runServerWizard:s,runDeployWizard:r,setWizardRL:i}=rh();return i(e),o[0]==="deploy"?await r():await s(),!0}case"/setup":{let{runSetupWizard:s}=Pc();return await s({rl:e,force:!0}),!0}case"/benchmark":{if(o.includes("--history")){let y=require("os"),w=Ye.join(y.homedir(),"Coding","nex-code-benchmarks","results");if(!ut.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=ut.readdirSync(w).filter(E=>E.endsWith(".json")).sort().slice(-7);if(x.length===0){console.log(`${a.yellow}No result files found${a.reset}`);break}console.log(`
|
|
1544
1544
|
${a.bold}${a.cyan}OpenClaw Nightly Results (${x.length}-day trend)${a.reset}
|
|
1545
|
-
`),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 A=[];for(let E of x)try{let
|
|
1546
|
-
${a.bold}Trend:${a.reset} ${O}${a.reset} over ${A.length} days`)}}console.log();break}if(o.includes("--discover")){let{findNewModels:y,markBenchmarked:w,updateReadme:x,updateModelsEnv:A}=yi(),{runDiscoverBenchmark:E,buildSummary:
|
|
1545
|
+
`),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 A=[];for(let E of x)try{let k=JSON.parse(ut.readFileSync(Ye.join(w,E),"utf-8")),T=E.replace(".json",""),O=k.tasks?.length||k.total||0,P=k.tasks?.filter(be=>be.passed||be.score>=.7)?.length||k.passed||0,W=k.score??k.overall_score??(O>0?Math.round(P/O*100):"N/A"),v=k.model||k.config?.model||"unknown";A.push({date:T,model:v,total:O,passed:P,score:W});let X=typeof W=="number"?W>=80?a.green:W>=60?a.yellow:a.red:a.dim;console.log(` ${T.padEnd(12)} ${v.substring(0,24).padEnd(25)} ${X}${String(W).padEnd(8)}${a.reset} ${P}/${O}`)}catch{}if(A.length>=2){let E=A[0].score,k=A[A.length-1].score;if(typeof E=="number"&&typeof k=="number"){let T=k-E,O=T>0?`${a.green}\u25B2 +${T}`:T<0?`${a.red}\u25BC ${T}`:`${a.dim}\u2192 stable`;console.log(`
|
|
1546
|
+
${a.bold}Trend:${a.reset} ${O}${a.reset} over ${A.length} days`)}}console.log();break}if(o.includes("--discover")){let{findNewModels:y,markBenchmarked:w,updateReadme:x,updateModelsEnv:A}=yi(),{runDiscoverBenchmark:E,buildSummary:k}=Xn();console.log(`
|
|
1547
1547
|
${a.bold}Checking Ollama Cloud for new models...${a.reset}`);let T;try{T=await y()}catch(S){console.log(`${a.red}Discovery failed: ${S.message}${a.reset}`);break}let{newModels:O,allCloud:P}=T;if(console.log(`${a.dim}${P.length} models available on cloud${a.reset}`),O.length===0){console.log(`${a.green}No new models since last benchmark run.${a.reset}
|
|
1548
1548
|
`);break}console.log(`${a.cyan}New models to benchmark (${O.length}):${a.reset} ${O.join(", ")}
|
|
1549
|
-
`);let W=require("os"),
|
|
1549
|
+
`);let W=require("os"),v=Ye.join(W.homedir(),".nex-code","benchmark-results.json"),X=[];try{ut.existsSync(v)&&(X=JSON.parse(ut.readFileSync(v,"utf-8")))}catch{}let be="",ye=await E({newModels:O,existingRanking:X,onProgress:({model:S,task:L,done:R,score:M,error:D})=>{if(!R){S!==be&&(be&&process.stdout.write(`
|
|
1550
1550
|
`),be=S,process.stdout.write(`${a.cyan}${S}${a.reset} `));return}let q=D?`${a.red}\u2717${a.reset}`:M>=80?`${a.green}\xB7${a.reset}`:M>=40?`${a.yellow}\xB7${a.reset}`:`${a.red}\xB7${a.reset}`;process.stdout.write(q)}});be&&process.stdout.write(`
|
|
1551
|
-
`);try{ut.writeFileSync(
|
|
1551
|
+
`);try{ut.writeFileSync(v,JSON.stringify(ye,null,2))}catch{}w(P);let we=Ye.join(process.cwd(),"README.md"),ue=x(ye,we),fe=A(ye),{buildCategoryWinners:pe}=Xn(),{updateRoutingConfig:de}=yi(),Ee=pe(ye),Me=de(Ee);if(ue&&console.log(`${a.green}README.md benchmark table updated${a.reset}`),fe.updated?console.log(`${a.green}DEFAULT_MODEL: ${fe.previousModel} \u2192 ${fe.newModel}${a.reset}`):fe.reason&&console.log(`${a.dim}models.env unchanged: ${fe.reason}${a.reset}`),Me.changes.length>0){console.log(`${a.green}Routing updated:${a.reset}`);for(let S of Me.changes)console.log(` ${a.dim}${S}${a.reset}`)}return console.log(),!0}let{runBenchmark:s,DEFAULT_MODELS:r,QUICK_MODELS:i}=Xn(),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(`
|
|
1552
1552
|
${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}
|
|
1553
1553
|
`);let m="",h=0,p=d*f.length,g=await s({models:f,quick:c,onProgress:({model:y,task:w,done:x,score:A,error:E})=>{if(!x){y!==m&&(m&&process.stdout.write(`
|
|
1554
|
-
`),m=y,process.stdout.write(`${a.cyan}${y}${a.reset} `));return}h++;let
|
|
1555
|
-
`),!c&&g&&g.length>0){let{buildCategoryWinners:y}=Xn(),{updateRoutingConfig:w,updateReadme:x,updateModelsEnv:A}=yi(),E=y(g),
|
|
1556
|
-
${a.bold}Per-category routing saved:${a.reset}`);for(let W of
|
|
1554
|
+
`),m=y,process.stdout.write(`${a.cyan}${y}${a.reset} `));return}h++;let k=E?`${a.red}\u2717${a.reset}`:A>=80?`${a.green}\xB7${a.reset}`:A>=40?`${a.yellow}\xB7${a.reset}`:`${a.red}\xB7${a.reset}`;process.stdout.write(k)}});if(m&&process.stdout.write(`
|
|
1555
|
+
`),!c&&g&&g.length>0){let{buildCategoryWinners:y}=Xn(),{updateRoutingConfig:w,updateReadme:x,updateModelsEnv:A}=yi(),E=y(g),k=w(E);if(k.changes.length>0){console.log(`
|
|
1556
|
+
${a.bold}Per-category routing saved:${a.reset}`);for(let W of k.changes)console.log(` ${a.dim}${W}${a.reset}`)}let T=Ye.join(process.cwd(),"README.md");x(g,T)&&console.log(`${a.green}README.md updated${a.reset}`),A(g);let O=require("os"),P=Ye.join(O.homedir(),".nex-code","benchmark-results.json");try{ut.writeFileSync(P,JSON.stringify(g,null,2))}catch{}}return!0}case"/bench":{let{runJarvisBenchmark:s}=Xn(),r=o.includes("--dry-run"),i=o.find(l=>l.startsWith("--model=")),c=i?i.replace("--model=","").trim():void 0;return r||console.log(`
|
|
1557
1557
|
${a.bold}Jarvis Benchmark${a.reset} ${a.dim}5 agentic scenarios \xB7 each run as child process${a.reset}
|
|
1558
1558
|
`),await s({dryRun:r,model:c,cwd:Lt,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}
|
|
1559
1559
|
`)}}}),!0}case"/trend":{let{showScoreTrend:s}=Xn(),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}=wo();return await r(s),!0}case"/bench-orchestrator":{let{runOrchestratorBenchmark:s,printResults:r}=Th(),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}
|
|
1560
1560
|
`):process.stdout.write(` ${a.green}${m}/10${a.reset}
|
|
1561
|
-
`):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(cS(t))return!0;{let s=[...Do,...
|
|
1561
|
+
`):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(cS(t))return!0;{let s=[...Do,...vi()].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 Jc=1e3;function Vc(){return Ye.join(process.cwd(),".nex","repl_history")}function Uh(){try{let t=Vc();if(ut.existsSync(t))return ut.readFileSync(t,"utf-8").split(`
|
|
1562
1562
|
`).filter(Boolean).slice(-Jc)}catch{}return[]}function xi(t){try{let e=Vc(),n=Ye.dirname(e);ut.existsSync(n)||ut.mkdirSync(n,{recursive:!0}),ut.appendFileSync(e,t+`
|
|
1563
1563
|
`)}catch{}}function St(){return`${a.bold}${a.cyan}>${a.reset} `}function Io(){if(!global._nexFooter)return;let{isPlanMode:t,getAutonomyLevel:e}=Yt(),{getAutoConfirm:n}=tt(),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 Zc="\x1B[200~",Qc="\x1B[201~";function pS(t){return typeof t=="string"&&t.includes(Zc)}function mS(t){return typeof t=="string"&&t.includes(Qc)}function jo(t){return typeof t!="string"?t:t.split(Zc).join("").split(Qc).join("")}async function hS(){if(!iS("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"),Xc("local:llama3"),!0}catch{return!1}}async function gS(){let{setAbortSignalGetter:t,getConversationLength:e,processInput:n}=Ae();t(Ph);let s=zc().some(R=>R.configured),r=(async()=>{aS();let R=dn(),M=Jn();return{model:R,providerName:M}})(),i=(async()=>s?!0:await hS()?(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}
|
|
1564
1564
|
`),!0):!1)(),c=(async()=>{if(process.env.NEX_DISABLE_UPDATE_CHECK==="1")return{hasNewVersion:!1};try{let{checkForNewVersion:R}=Ah();return await R()}catch{return{hasNewVersion:!1}}})(),[l,u,d]=await Promise.all([r,i,c]);!u&&!s&&(console.error(`
|
|
@@ -1566,30 +1566,30 @@ ${a.red}\u2717 No provider configured and no local Ollama detected.${a.reset}
|
|
|
1566
1566
|
`),process.exit(1));let{loadPersistedHistory:f,pruneHistory:m}=nn();f().then(R=>{}),m().catch(()=>{});let h=Uh(),p=tS.createInterface({input:process.stdin,output:process.stdout,prompt:St(),completer:jh,history:h,historySize:Jc});lS(p);let{setAskUserHandler:g}=It();g(async(R,M)=>{let D="\x1B[0m",q="\x1B[1m",Z="\x1B[2m",ce="\x1B[36m";return process.stdout.write(`
|
|
1567
1567
|
${q}\x1B[33m\u2753${D} ${q}${R}${D}
|
|
1568
1568
|
|
|
1569
|
-
`),M.forEach((me,
|
|
1569
|
+
`),M.forEach((me,ke)=>{process.stdout.write(` ${ce}${ke+1}${D} ${me}
|
|
1570
1570
|
`)}),process.stdout.write(` ${Z}${M.length+1}${D} ${Z}Eigene Antwort\u2026${D}
|
|
1571
1571
|
`),process.stdout.write(`
|
|
1572
|
-
${ce}[1-${M.length+1}]${D} \u203A `),new Promise(me=>{p.resume(),p.once("line",
|
|
1572
|
+
${ce}[1-${M.length+1}]${D} \u203A `),new Promise(me=>{p.resume(),p.once("line",ke=>{let Qe=ke.trim(),ze=parseInt(Qe);ze>=1&&ze<=M.length?(process.stdout.write(`
|
|
1573
1573
|
`),me(M[ze-1])):ze===M.length+1||Qe===""?(process.stdout.write(` ${ce}\u203A${D} `),p.once("line",fn=>{process.stdout.write(`
|
|
1574
1574
|
`),me(fn.trim()||"")})):(process.stdout.write(`
|
|
1575
1575
|
`),me(Qe))})})});let y=new fS;y.activate(p),global._nexFooter=y,global._nexRawWrite=R=>y.rawWrite(R),dS(()=>Io()),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}`;nS(w,Lt,{yolo:Gc()});{y.setStatusInfo({model:w,branch:"",project:Ye.basename(Lt)});let{execFile:R}=require("child_process");R("git",["rev-parse","--abbrev-ref","HEAD"],{encoding:"utf8"},(M,D)=>{!M&&D&&y.setStatusInfo({model:w,branch:D.trim(),project:Ye.basename(Lt)})})}d.hasNewVersion&&console.log(`${a.yellow}\u{1F4A1} New version available!${a.reset} Run ${a.cyan}npm update -g nex-code${a.reset} to upgrade from ${a.dim}${d.currentVersion}${a.reset} to ${a.green}${d.latestVersion}${a.reset}
|
|
1576
|
-
`),await Mh(Lt);let x=!1,A=0,E=!1,
|
|
1577
|
-
${a.yellow} Task cancelled. Press Ctrl+C again to exit.${a.reset}`),x=!1,p.setPrompt(St()),p.prompt()}else console.log(`${a.dim} (Press Ctrl+C again to exit)${a.reset}`),p.setPrompt(St()),p.prompt(),
|
|
1578
|
-
`).replace(/\r/g,"").trim();if(P=[],O=!1,!R)return!0;W++,X=!0;let M=W;
|
|
1579
|
-
`).length,q=D>1?`[Pasted content #${M} \u2014 ${D} lines]`:`[Pasted content #${M}]`,Z=p.line||"",ce=Z&&!Z.endsWith(" ")?" ":"",se=Z+ce+q;return p.setPrompt(St()),p.prompt(),p.line=se,p.cursor=se.length,p._refreshLine(),!0}function ye(R){return R.replace(/\[Pasted content #(\d+)(?:[^\]]*)\]/g,(M,D)=>
|
|
1576
|
+
`),await Mh(Lt);let x=!1,A=0,E=!1,k=null;function T(){Nh(),y.deactivate(),Oh(),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",T),process.on("exit",()=>{Nh()}),p.on("SIGINT",()=>{if(Oh(),A++,A>=2){T();return}if(x){un&&un.abort();let{cancelPendingAskUser:R}=It();R(),console.log(`
|
|
1577
|
+
${a.yellow} Task cancelled. Press Ctrl+C again to exit.${a.reset}`),x=!1,p.setPrompt(St()),p.prompt()}else console.log(`${a.dim} (Press Ctrl+C again to exit)${a.reset}`),p.setPrompt(St()),p.prompt(),k&&clearTimeout(k),k=setTimeout(()=>{A=0,k=null},2e3)}),process.on("SIGINT",()=>{process.stdin.isTTY?(A++,A>=2&&T()):T()});let O=!1,P=[],W=0,v={},X=!1;function be(){let R=P.join(`
|
|
1578
|
+
`).replace(/\r/g,"").trim();if(P=[],O=!1,!R)return!0;W++,X=!0;let M=W;v[M]=R;let D=R.split(`
|
|
1579
|
+
`).length,q=D>1?`[Pasted content #${M} \u2014 ${D} lines]`:`[Pasted content #${M}]`,Z=p.line||"",ce=Z&&!Z.endsWith(" ")?" ":"",se=Z+ce+q;return p.setPrompt(St()),p.prompt(),p.line=se,p.cursor=se.length,p._refreshLine(),!0}function ye(R){return R.replace(/\[Pasted content #(\d+)(?:[^\]]*)\]/g,(M,D)=>v[Number(D)]||"")}function we(){W=0,v={},X=!1}if(process.stdin.isTTY){process.stdout.write("\x1B[?2004h");let R=process.stdin.emit.bind(process.stdin);process.stdin.emit=function(M,...D){if(M!=="data")return R.call(process.stdin,M,...D);let q=D[0];if(Buffer.isBuffer(q)&&(q=q.toString("utf8")),typeof q!="string")return R.call(process.stdin,M,...D);let Z=q.includes(Zc),ce=q.includes(Qc);if(Z&&ce){let se=jo(q);return se&&P.push(...se.split(`
|
|
1580
1580
|
`)),be()}if(Z){O=!0,P=[];let se=jo(q);return se&&P.push(...se.split(`
|
|
1581
1581
|
`)),!0}if(ce){let se=jo(q);return se&&P.push(...se.split(`
|
|
1582
1582
|
`)),be()}if(O){let se=jo(q);return se&&P.push(...se.split(`
|
|
1583
1583
|
`)),!0}return q.includes(`
|
|
1584
1584
|
`)&&q.length>40&&!O?(P.push(...q.replace(/\r/g,"").split(`
|
|
1585
|
-
`)),be()):R.call(process.stdin,M,...D)}}let ue=0;function fe(){if(ue>0){let R=y._scrollEnd,M="\x1B7";for(let D=0;D<ue;D++)M+=`\x1B[${R-ue+1+D};1H\x1B[2K`;M+="\x1B8",y.rawWrite(M),ue=0}}function pe(R){let M=[...Do,...
|
|
1586
|
-
${Z}. `).trim()}let{loadSession:S}=Ft(),{setConversationMessages:L}=Ae();if(e()===0){let R=S("_autosave");if(R&&R.messages&&R.messages.length>0&&Date.now()-new Date(R.updatedAt).getTime()<1440*60*1e3){let{confirm:D}=tt();if(await D("Previous session found. Resume?")){let ce=R.messages,se=ce.length>20?ce.slice(-20):ce;L(se);let{getUsage:me,forceCompress:
|
|
1585
|
+
`)),be()):R.call(process.stdin,M,...D)}}let ue=0;function fe(){if(ue>0){let R=y._scrollEnd,M="\x1B7";for(let D=0;D<ue;D++)M+=`\x1B[${R-ue+1+D};1H\x1B[2K`;M+="\x1B8",y.rawWrite(M),ue=0}}function pe(R){let M=[...Do,...vi()].filter(ke=>ke.cmd.startsWith(R));if(!M.length||M.length===1&&M[0].cmd===R)return;let D=y._scrollEnd,q=Math.min(10,D-2);if(q<1)return;let Z=M.slice(0,q),ce=Math.max(...Z.map(ke=>ke.cmd.length));ue=Z.length,M.length>q&&ue++;let se=D-ue+1,me="\x1B7";for(let ke=0;ke<Z.length;ke++){let{cmd:Qe,desc:ze}=Z[ke],fn=Qe.substring(0,R.length),ki=Qe.substring(R.length),qo=" ".repeat(Math.max(0,ce-Qe.length+2));me+=`\x1B[${se+ke};1H\x1B[2K ${a.cyan}${fn}${a.reset}${a.dim}${ki}${qo}${ze}${a.reset}`}M.length>q&&(me+=`\x1B[${se+Z.length};1H\x1B[2K ${a.dim}\u2026 +${M.length-q} more${a.reset}`),me+="\x1B8",y.rawWrite(me)}process.stdin.isTTY&&process.stdin.on("keypress",(R,M)=>{fe(),!(M&&(M.name==="tab"||M.name==="return"))&&setImmediate(()=>{p.line&&p.line.startsWith("/")&&pe(p.line)})});let de=null,Ee=`${a.dim}...${a.reset} `;function Me(R){return(R.match(/[^\s\d](\d{1,2})\.\s+\S/g)||[]).length<2?R:R.replace(/([^\s\d])(\d{1,2})\.\s+/g,(D,q,Z)=>`${q}
|
|
1586
|
+
${Z}. `).trim()}let{loadSession:S}=Ft(),{setConversationMessages:L}=Ae();if(e()===0){let R=S("_autosave");if(R&&R.messages&&R.messages.length>0&&Date.now()-new Date(R.updatedAt).getTime()<1440*60*1e3){let{confirm:D}=tt();if(await D("Previous session found. Resume?")){let ce=R.messages,se=ce.length>20?ce.slice(-20):ce;L(se);let{getUsage:me,forceCompress:ke}=nt();if(me(se,[]).percentage>=30){let{messages:ze}=ke(se,[]);L(ze)}}}}p.setPrompt(St()),p.prompt(),p.on("line",async R=>{if(fe(),Object.keys(v).length>0&&(R=ye(R),we(),p.setPrompt(St())),x){let Z=R.trim();if(Z){let{injectMidRunNote:ce}=Ae();ce(Z),process.stdout.write(`${a.cyan} \u270E Queued \u2014 will be applied in the next step${a.reset}
|
|
1587
1587
|
`),p.prompt()}return}if(de!==null){if(de._mode==="triple"){if(R.trim()==='"""'){let Z=de.join(`
|
|
1588
|
-
`).trim();if(de=null,Z){xi(Z.replace(/\n/g,"\\n")),x=!0,p.prompt(),A=0,E=!1,
|
|
1588
|
+
`).trim();if(de=null,Z){xi(Z.replace(/\n/g,"\\n")),x=!0,p.prompt(),A=0,E=!1,k&&(clearTimeout(k),k=null),un=new AbortController;try{await n(Z)}catch(se){if(!un?.signal?.aborted){let me=se.message?.split(`
|
|
1589
1589
|
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${me}${a.reset}`)}}x=!1;let ce=D();ce>0&&process.stdout.write(`${a.gray}[${ce} messages] ${a.reset}`)}p.setPrompt(St()),p.prompt();return}de.push(R),p.setPrompt(Ee),p.prompt();return}if(R.endsWith("\\"))de.push(R.slice(0,-1));else{de.push(R);let Z=de.join(`
|
|
1590
|
-
`).trim();if(de=null,Z){xi(Z.replace(/\n/g,"\\n")),x=!0,p.prompt(),A=0,E=!1,
|
|
1591
|
-
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${
|
|
1592
|
-
`).forEach((me,
|
|
1590
|
+
`).trim();if(de=null,Z){xi(Z.replace(/\n/g,"\\n")),x=!0,p.prompt(),A=0,E=!1,k&&(clearTimeout(k),k=null),un=new AbortController;try{await n(Z)}catch(me){if(!un?.signal?.aborted){let ke=me.message?.split(`
|
|
1591
|
+
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${ke}${a.reset}`)}}let{getConversationLength:ce}=Ae();x=!1;let se=ce();se>0&&process.stdout.write(`${a.gray}[${se} messages] ${a.reset}`)}p.setPrompt(St()),p.prompt();return}p.setPrompt(Ee),p.prompt();return}if(R.trim()==='"""'||R.trim().startsWith('"""')){let Z=R.trim().substring(3);de=Z?[Z]:[],de._mode="triple",p.setPrompt(Ee),p.prompt();return}if(R.endsWith("\\")){de=[R.slice(0,-1)],de._mode="backslash",p.setPrompt(Ee),p.prompt();return}let M=Me(R.trim());if(!M){p.setPrompt(St()),p.prompt();return}if(xi(M),M==="/"){Lh(),p.setPrompt(St()),p.prompt();return}if(M.startsWith("/")){await Fh(M,p),p.setPrompt(St()),p.prompt();return}{let Z=sS?"\x1B[48;5;237m":"\x1B[48;2;220;225;235m",ce=process.stdout.columns||80;M.split(`
|
|
1592
|
+
`).forEach((me,ke)=>{let Qe=ke===0?"\x1B[1;36m\u203A\x1B[22;39m":" ",ze=2+me.length,fn=" ".repeat(Math.max(0,ce-ze));console.log(`${Z}${Qe} ${me}${fn}\x1B[0m`)})}if(process.env.NEX_AUTO_PLAN!=="0"&&!Gc()){let{isPlanMode:Z,setPlanMode:ce}=Yt(),{invalidateSystemPromptCache:se}=Ae(),me=/\b(implement|refactor|migrate|redesign)\b/i,ke=/\b(create|build|add|write|introduce|develop|set\s+up)\b/i,Qe=/^(how|what|why|when|where|which|explain|show|list|tell|describe|can\s+you|could\s+you|do\s+you)\b/i,ze=/\b(spawn[_\s]?agents?|swarm)\b/i;!Qe.test(M)&&!ze.test(M)&&(me.test(M)||ke.test(M)&&M.split(/\s+/).length>=5)&&!Z()&&(ce(!0),se(),console.log(`${a.cyan}${a.bold}\u2387 Auto Plan Mode${a.reset}${a.dim} \u2014 implementation task detected \xB7 read-only until /plan approve${a.reset}`))}{let{getConversationLength:Z}=Ae();if(Z()===0)try{let{detectCategory:ce,getModelForCategory:se}=xs(),me=ce(M);if(me&&me.id!=="coding"){let ke=se(me.id),Qe=dn();if(ke&&ke!==Qe?.id&&Xc(ke)){let ze=dn();console.log(`${a.dim}\u21B3 ${me.icon} ${me.label} task \u2014 routing to ${ze?.name||ke}${a.reset}`),global._nexFooter&&global._nexFooter.setStatusInfo({model:ze?.name||ke})}}}catch{}}x=!0,p.prompt(),A=0,E=!1,k&&(clearTimeout(k),k=null),un=new AbortController;try{await n(M)}catch(Z){if(!un?.signal?.aborted){let ce=Z.message?.split(`
|
|
1593
1593
|
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${ce}${a.reset}`)}}x=!1;let{getConversationLength:D}=Ae(),q=D();q>0&&process.stdout.write(`${a.gray}[${q} messages] ${a.reset}`),p.setPrompt(St()),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)})}Wh.exports={startREPL:gS,getPrompt:St,loadHistory:Uh,appendHistory:xi,getHistoryPath:Vc,HISTORY_MAX:Jc,showCommandList:Lh,completer:jh,completeFilePath:Ih,handleSlashCommand:Fh,showProviders:Yc,showHelp:Dh,renderBar:qh,hasPasteStart:pS,hasPasteEnd:mS,stripPasteSequences:jo,getAbortSignal:Ph}});var Hh=J((QE,Bh)=>{"use strict";var $S=require("readline");function Vn(t){process.stdout.write(JSON.stringify(t)+`
|
|
1594
1594
|
`)}function yS(){process.env.NEX_SERVER="1";let t=(...c)=>process.stderr.write(c.map(String).join(" ")+`
|
|
1595
1595
|
`);console.log=t,console.warn=t,console.info=t;let{setConfirmHook:e}=tt(),n=new Map,o=0;e((c,l)=>{let u="cfm-"+ ++o,d=l?.toolName||"",f=!1;try{let{isCritical:m}=tt();f=m(c)}catch{}return Vn({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&&Vn({type:"token",id:s,text:c})},onThinkingToken(){},onToolStart(c,l){s&&Vn({type:"tool_start",id:s,tool:c,args:l||{}})},onToolEnd(c,l,u){s&&Vn({type:"tool_end",id:s,tool:c,summary:l||"",ok:!!u})}},i=$S.createInterface({input:process.stdin,output:null,terminal:!1});Vn({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}=Ae();try{await f(u.text,r),Vn({type:"done",id:d})}catch(m){Vn({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}=Ae();d();for(let[f,m]of n)n.delete(f),m(!1);break}default:break}}),i.on("close",()=>{process.exit(0)})}Bh.exports={startServerMode:yS}});var Gh=J((eT,Kh)=>{Kh.exports=el()});var rl=require("path");require("dotenv").config({path:rl.join(__dirname,"..",".env")});require("dotenv").config();var _e=process.argv.slice(2);(_e.includes("--help")||_e.includes("-h"))&&(console.log(`Usage: nex-code [options]
|