nex-code 0.4.30 → 0.4.32

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.
@@ -0,0 +1,1235 @@
1
+ "use strict";var se=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var ks=se((rk,Jc)=>{"use strict";var Gc="\x1B[0m",Yc="\x1B[1m",Wn="\x1B[2m";function Y(t,e,s){return`\x1B[38;2;${t};${e};${s}m`}function Zh(){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(`
2
+ `),o=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(o){let r=parseInt(o[1].slice(0,2),16),i=parseInt(o[2].slice(0,2),16),a=parseInt(o[3].slice(0,2),16);return .299*r+.587*i+.114*a<128}}catch{}return null}function Kc(){let t=require("os");return require("path").join(t.homedir(),".nex-code",".theme_cache.json")}function Qh(t){try{let s=require("fs").readFileSync(Kc(),"utf8"),n=JSON.parse(s);if(n&&typeof n[t]=="boolean")return n[t]}catch{}return null}function em(t,e){try{let s=require("fs"),n=require("path"),o=Kc(),r=n.dirname(o),i={};try{i=JSON.parse(s.readFileSync(o,"utf8"))}catch{}i[t]=e;let a=Object.keys(i);a.length>50&&a.slice(0,a.length-50).forEach(c=>delete i[c]),s.existsSync(r)||s.mkdirSync(r,{recursive:!0}),s.writeFileSync(o,JSON.stringify(i),"utf8")}catch{}}function tm(){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(";"),a=parseInt(i[i.length-1],10);if(!isNaN(a))return a<8}let s=process.env.TERM_SESSION_ID||"default",n=Qh(s);if(n!==null)return n;let o=Zh(),r=o!==null?o:!0;return em(s,r),r}var zc=tm(),Xc={reset:Gc,bold:Yc,dim:Wn,primary:Y(80,190,255),secondary:Y(60,170,190),success:Y(80,210,120),warning:Y(245,175,50),error:Y(230,80,80),muted:Wn,subtle:Y(130,130,145),tool_read:Y(80,190,255),tool_write:Y(245,165,55),tool_exec:Y(185,100,235),tool_search:Y(70,185,190),tool_git:Y(90,210,100),tool_web:Y(100,215,250),tool_sysadmin:Y(225,150,75),tool_default:Y(100,205,115),syn_keyword:Y(185,100,235),syn_string:Y(90,210,120),syn_number:Y(245,175,50),syn_comment:Wn,syn_key:Y(80,190,255),diff_add:Y(80,210,120),diff_rem:Y(230,80,80),banner_logo:Y(80,200,255),banner_name:Y(80,200,255),banner_version:Wn,banner_model:Wn,banner_yolo:Y(245,175,50),footer_sep:Wn,footer_model:Y(80,175,235),footer_branch:Y(80,210,100),footer_project:Y(130,130,145),footer_divider:Y(80,80,95),footer_mode:Y(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"},Vc={reset:Gc,bold:Yc,dim:Y(110,110,120),primary:Y(0,110,190),secondary:Y(0,125,148),success:Y(0,148,62),warning:Y(168,92,0),error:Y(188,32,32),muted:Y(110,110,120),subtle:Y(155,155,165),tool_read:Y(0,110,190),tool_write:Y(168,92,0),tool_exec:Y(128,42,188),tool_search:Y(0,122,148),tool_git:Y(0,138,62),tool_web:Y(0,112,178),tool_sysadmin:Y(168,82,0),tool_default:Y(0,138,62),syn_keyword:Y(128,42,188),syn_string:Y(0,138,62),syn_number:Y(168,92,0),syn_comment:Y(135,135,148),syn_key:Y(0,110,190),diff_add:Y(0,148,62),diff_rem:Y(188,32,32),banner_logo:Y(0,122,205),banner_name:Y(0,122,205),banner_version:Y(100,100,118),banner_model:Y(100,100,118),banner_yolo:Y(168,62,0),footer_sep:Y(168,168,178),footer_model:Y(0,102,175),footer_branch:Y(0,138,62),footer_project:Y(135,135,148),footer_divider:Y(168,168,178),footer_mode:Y(148,88,0),white:Y(40,40,52),red:Y(188,32,32),green:Y(0,148,62),yellow:Y(168,92,0),blue:Y(0,110,190),magenta:Y(128,42,188),cyan:Y(0,125,148),gray:Y(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:Y(0,158,182),brightMagenta:Y(158,52,208),brightBlue:Y(0,112,208)},nm=zc?Xc:Vc;Jc.exports={T:nm,isDark:zc,DARK:Xc,LIGHT:Vc}});var No=se((ik,sm)=>{sm.exports={name:"nex-code",version:"0.4.32",description:"Run 400B+ open coding models on your codebase without the hardware bill. Ollama Cloud first \u2014 OpenAI, Anthropic, and Gemini when you need them.",bin:{"nex-code":"./dist/nex-code.js"},files:["dist/","examples/","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 && esbuild cli/benchmark.js --bundle --platform=node --target=node18 --outfile=dist/benchmark.js --minify --external:axios --external:dotenv --external:playwright && rm -rf dist/skills && cp -r cli/skills dist/skills",dev:"esbuild bin/nex-code.js --bundle --platform=node --target=node18 --outfile=dist/nex-code.js --external:axios --external:dotenv --external:playwright --watch",test:"jest --forceExit","test:orchestrator":"jest tests/orchestrator.test.js --forceExit",coverage:"jest --coverage --forceExit","test:watch":"jest --watch",typecheck:"tsc --noEmit",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","extract-examples":"node scripts/extract-examples.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",typescript:"^5.9.3"},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 Hn=se((ak,Qc)=>{var{T:Z}=ks(),Po=5,Un=(()=>{let t=[];for(let e=0;e<Po;e++)t.push(e);for(let e=Po-2;e>=1;e--)t.push(e);return t})(),Zc=["\u273D","\u2726","\u2727","\u2726"],gi=class{constructor(e="Thinking..."){this.text=e,this.frame=0,this.interval=null,this.startTime=null}_render(){if(this._stopped)return;let e=Un[this.frame%Un.length],s="";for(let o=0;o<Po;o++)s+=o===e?`${Z.cyan}\u25CF${Z.reset}`:" ";let n="";if(this.startTime){let o=Math.floor((Date.now()-this.startTime)/1e3);if(o>=60){let r=Math.floor(o/60),i=o%60;n=` ${Z.dim}${r}m ${String(i).padStart(2,"0")}s${Z.reset}`}else o>=1&&(n=` ${Z.dim}${o}s${Z.reset}`)}process.stderr.write(`\x1B[2K\r${s} ${Z.dim}${this.text}${Z.reset}${n}`),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),process.stderr.isTTY&&(process.stderr.write("\x1B[?25l"),this._render(),this.interval=setInterval(()=>this._render(),100))}update(e){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}},yi=class{constructor(e){this.labels=e,this.statuses=e.map(()=>"running"),this.frame=0,this.interval=null,this.startTime=null,this.lineCount=e.length}_formatElapsed(){if(!this.startTime)return"";let e=Math.floor((Date.now()-this.startTime)/1e3);if(e<1)return"";let s=Math.floor(e/60),n=e%60;return s>0?`${s}m ${String(n).padStart(2,"0")}s`:`${n}s`}_render(){if(this._stopped)return;let e=Un[this.frame%Un.length],s=`${Z.cyan}\u25CF${Z.reset}`,n=this._formatElapsed(),o=n?` ${Z.dim}${n}${Z.reset}`:"",r=process.stderr.columns||80,i="";for(let a=0;a<this.labels.length;a++){let c,l;switch(this.statuses[a]){case"done":c=`${Z.green}\u2713${Z.reset}`,l=Z.dim;break;case"error":c=`${Z.red}\u2717${Z.reset}`,l=Z.dim;break;case"retry":c=`${Z.yellow}\u21BB${Z.reset}`,l=Z.yellow;break;default:c=a===e?s:" ",l=""}let u=a===this.labels.length-1?o:"",d=r-4-(u?n.length+1:0),f=this.labels[a].length>d?this.labels[a].substring(0,Math.max(10,d-3))+"...":this.labels[a];i+=`\x1B[2K ${c} ${l}${f}${Z.reset}${u}
3
+ `}this.lineCount>0&&(i+=`\x1B[${this.lineCount}A`),process.stderr.write(i),this.frame++}start(){this._stopped=!1,this.startTime=Date.now();let e="\x1B[?25l";for(let s=0;s<this.lineCount;s++)e+=`
4
+ `;this.lineCount>0&&(e+=`\x1B[${this.lineCount}A`),process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),100)}update(e,s){e>=0&&e<this.statuses.length&&(this.statuses[e]=s)}stop(e={}){if(this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),!e.silent)this._renderFinal();else{let s="";for(let n=0;n<this.lineCount;n++)s+=`\x1B[2K
5
+ `;this.lineCount>0&&(s+=`\x1B[${this.lineCount}A`),process.stderr.write(s)}process.stderr.write("\x1B[?25h")}_renderFinal(){let e=this._formatElapsed(),s=e?` ${Z.dim}${e}${Z.reset}`:"",n=process.stderr.columns||80,o="";for(let r=0;r<this.labels.length;r++){let i;switch(this.statuses[r]){case"done":i=`${Z.green}\u2713${Z.reset}`;break;case"error":i=`${Z.red}\u2717${Z.reset}`;break;case"retry":i=`${Z.yellow}\u21BB${Z.reset}`;break;default:i=`${Z.yellow}\u25CB${Z.reset}`}let a=r===this.labels.length-1?s:"",c=n-4-(a?e.length+1:0),l=this.labels[r].length>c?this.labels[r].substring(0,Math.max(10,c-3))+"...":this.labels[r];o+=`\x1B[2K ${i} ${Z.dim}${l}${Z.reset}${a}
6
+ `}process.stderr.write(o)}},Mo={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},Lo={done:Z.green,in_progress:Z.cyan,pending:Z.dim,failed:Z.red},Xt=null,$i=class{constructor(e,s){this.name=e,this.tasks=s.map(n=>({id:n.id,description:n.description,status:n.status||"pending"})),this.frame=0,this.interval=null,this.startTime=null,this.tokens=0,this.lineCount=1+this.tasks.length,this._paused=!1}_formatElapsed(){if(!this.startTime)return"";let e=Math.floor((Date.now()-this.startTime)/1e3);if(e<1)return"";let s=Math.floor(e/60),n=e%60;return s>0?`${s}m ${String(n).padStart(2,"0")}s`:`${n}s`}_formatTokens(){return this.tokens<=0?"":this.tokens>=1e3?`${(this.tokens/1e3).toFixed(1)}k`:String(this.tokens)}_render(){if(this._stopped)return;let e=Zc[this.frame%Zc.length],s=this._formatElapsed(),n=this._formatTokens(),o=[s,n?`\u2193 ${n} tokens`:""].filter(Boolean).join(" \xB7 "),r=o?` ${Z.dim}(${o})${Z.reset}`:"",i=`\x1B[2K${Z.cyan}${e}${Z.reset} ${this.name}\u2026${r}
7
+ `;for(let a=0;a<this.tasks.length;a++){let c=this.tasks[a],l=a===0?"\u23BF":" ",u=Mo[c.status]||Mo.pending,d=Lo[c.status]||Lo.pending,f=c.description.length>55?c.description.substring(0,52)+"...":c.description;i+=`\x1B[2K ${Z.dim}${l}${Z.reset} ${d}${u}${Z.reset} ${f}
8
+ `}i+=`\x1B[${this.lineCount}A`,process.stderr.write(i),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),this._paused=!1;let e="\x1B[?25l";for(let s=0;s<this.lineCount;s++)e+=`
9
+ `;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120),Xt=this}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),this._paused||this._renderFinal(),process.stderr.write("\x1B[?25h"),this._paused=!1,Xt===this&&(Xt=null)}pause(){if(this._paused)return;this.interval&&(clearInterval(this.interval),this.interval=null);let e="";for(let s=0;s<this.lineCount;s++)e+=`\x1B[2K
10
+ `;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._paused=!0}resume(){if(!this._paused)return;this._paused=!1;let e="\x1B[?25l";for(let s=0;s<this.lineCount;s++)e+=`
11
+ `;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120)}updateTask(e,s){let n=this.tasks.find(o=>o.id===e);n&&(n.status=s)}setStats({tokens:e}){e!==void 0&&(this.tokens=e)}isActive(){return this.interval!==null||this._paused}_renderFinal(){let e=this._formatElapsed(),s=this.tasks.filter(a=>a.status==="done").length,n=this.tasks.filter(a=>a.status==="failed").length,o=this.tasks.length,r=n>0?`${s}/${o} done, ${n} failed`:`${s}/${o} done`,i=`\x1B[2K${Z.green}\u2714${Z.reset} ${this.name} ${Z.dim}(${e} \xB7 ${r})${Z.reset}
12
+ `;for(let a=0;a<this.tasks.length;a++){let c=this.tasks[a],l=a===0?"\u23BF":" ",u=Mo[c.status]||Mo.pending,d=Lo[c.status]||Lo.pending,f=c.description.length>55?c.description.substring(0,52)+"...":c.description;i+=`\x1B[2K ${Z.dim}${l}${Z.reset} ${d}${u}${Z.reset} ${Z.dim}${f}${Z.reset}
13
+ `}process.stderr.write(i)}},wi=class{constructor(e,s){this.toolName=e,this.message=s||`Running ${e}...`,this.count=0,this.total=null,this.detail="",this.frame=0,this.interval=null,this.startTime=null,this._stopped=!1}_render(){if(this._stopped||!process.stderr.isTTY)return;let e=Un[this.frame%Un.length],s="";for(let r=0;r<Po;r++)s+=r===e?`${Z.cyan}\u25CF${Z.reset}`:" ";let n=this.message;this.count>0&&(n+=` ${Z.cyan}${this.count}${Z.reset}`,this.total&&(n+=`/${this.total}`),this.detail&&(n+=` ${Z.dim}${this.detail}${Z.reset}`));let o="";if(this.startTime){let r=Math.floor((Date.now()-this.startTime)/1e3);r>=1&&(o=` ${Z.dim}${r}s${Z.reset}`)}process.stderr.write(`\x1B[2K\r${s} ${Z.dim}${n}${Z.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){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 om(t){Xt=t}function rm(){return Xt}function im(){Xt&&(Xt.stop(),Xt=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}Qc.exports={C:Z,Spinner:gi,MultiProgress:yi,TaskProgress:$i,ToolProgress:wi,setActiveTaskProgress:om,getActiveTaskProgress:rm,cleanupTerminal:im}});var bi=se((ck,sl)=>{"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"},el={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"])},am={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 tl(t){if(!t)return null;let e=t.split(".").pop().toLowerCase();return am[e]||null}function cm(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 lm(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,s,n)=>s+ie.type+n+ie.reset).replace(/\s([a-zA-Z][a-zA-Z0-9-]*)=/g,(e,s)=>" "+ie.kw+s+ie.reset+"=").replace(/"([^"]*)"/g,e=>ie.str+e+ie.reset)}function um(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,s,n)=>ie.num+s+ie.reset+n).replace(/([a-z][a-z-]*)(\s*:)/g,(e,s,n)=>ie.type+s+ie.reset+n).replace(/"[^"]*"|'[^']*'/g,e=>ie.str+e+ie.reset)}function nl(t,e,s){if(e==="json")return cm(t);if(e==="html"||e==="xml")return lm(t);if(e==="css")return um(t);if(e==="md")return t;let n=el[e]||el.js,o="",r=0;if(s.inBlockComment){let i=t.indexOf("*/");if(i===-1)return ie.cmt+t+ie.reset;if(o+=ie.cmt+t.slice(0,i+2)+ie.reset,s.inBlockComment=!1,r=i+2,r>=t.length)return o}if(s.inString==="`"){let i=t.indexOf("`");if(i===-1)return ie.str+t+ie.reset;if(o+=ie.str+t.slice(0,i+1)+ie.reset,s.inString=null,r=i+1,r>=t.length)return o}for(;r<t.length;){let i=t[r];if(!s.inString&&i==="/"&&t[r+1]==="*"){let a=t.indexOf("*/",r+2);if(a===-1)return o+=ie.cmt+t.slice(r)+ie.reset,s.inBlockComment=!0,o;o+=ie.cmt+t.slice(r,a+2)+ie.reset,r=a+2;continue}if(!s.inString&&((e==="js"||e==="go"||e==="rs"||e==="java")&&i==="/"&&t[r+1]==="/"||(e==="py"||e==="sh")&&i==="#"))return o+=ie.cmt+t.slice(r)+ie.reset,o;if(!s.inString&&(i==='"'||i==="'"||i==="`")){s.inString=i,o+=ie.str+i,r++;continue}if(s.inString){if(i==="\\"&&r+1<t.length){o+=i+t[r+1],r+=2;continue}if(i===s.inString){o+=i+ie.reset,s.inString=null,r++;continue}o+=i,r++;continue}if(/[0-9]/.test(i)&&(r===0||!/[a-zA-Z0-9_$]/.test(t[r-1]))){let a="";for(;r<t.length&&/[0-9a-fA-F_.xXoObBeE+-]/.test(t[r])&&!(a.length>0&&/[eE]/.test(t[r-1])&&/[^+-]/.test(i));)a+=t[r++];o+=ie.num+a+ie.reset;continue}if(i==="@"&&(e==="js"||e==="java"||e==="py")){let a="@";for(r++;r<t.length&&/[a-zA-Z0-9_$.]/.test(t[r]);)a+=t[r++];o+=ie.punct+a+ie.reset;continue}if(/[a-zA-Z_$]/.test(i)){let a="";for(;r<t.length&&/[a-zA-Z0-9_$]/.test(t[r]);)a+=t[r++];n.has(a)?o+=ie.kw+a+ie.reset:/^[A-Z][A-Za-z0-9]*$/.test(a)&&e!=="sh"?o+=ie.type+a+ie.reset:o+=a;continue}o+=i,r++}return s.inString&&s.inString!=="`"&&(o+=ie.reset,s.inString=null),o}function dm(t,e){let s=tl(e);if(!s)return t.split(`
14
+ `);let n=t.split(`
15
+ `),o={inString:null,inBlockComment:!1};return n.map(r=>nl(r,s,o))}function fm(t,e){return e?nl(t,e,{inString:null,inBlockComment:!1}):t}sl.exports={detectLang:tl,highlightLine:fm,highlightLines:dm}});var rl=se((lk,ol)=>{var{T:E}=ks(),Je=E,pm={read_file:E.tool_read,list_directory:E.tool_read,write_file:E.tool_write,edit_file:E.tool_write,patch_file:E.tool_write,bash:E.tool_exec,grep:E.tool_search,search_files:E.tool_search,glob:E.tool_search,git_commit:E.tool_git,git_push:E.tool_git,git_pull:E.tool_git,git_status:E.tool_git,git_diff:E.tool_git,git_log:E.tool_git,git_branch:E.tool_git,git_stash:E.tool_git,web_fetch:E.tool_web,web_search:E.tool_web,sysadmin:E.tool_sysadmin,ssh_exec:E.tool_sysadmin,ssh_upload:E.tool_sysadmin,ssh_download:E.tool_sysadmin,deploy:E.tool_sysadmin},_i={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 Io(t,e=!1,s=null){if(e)return`${E.error}\u23FA${E.reset}`;let n=pm[t]||E.tool_default;return s==="blink"?`${n}\x1B[5m\u23FA\x1B[25m${E.reset}`:`${n}${s!==null?s:"\u23FA"}${E.reset}`}function hm(t,e,s=!1,n=null){let o=(t||[]).filter(c=>c&&c.canExecute!==!1);if(o.length===0)return`${Io("",s,n)} Step ${e}`;if(o.length===1){let c=o[0],l=c.args||{},u=_i[c.fnName]||c.fnName.replace(/_/g," "),d="";l.path?d=l.path:l.command?d=String(l.command).substring(0,80):l.query?d=String(l.query).substring(0,60):l.pattern?d=String(l.pattern).substring(0,60):l.url&&(d=String(l.url).substring(0,60));let f=d?`(${Je.dim}${d}${Je.reset})`:"";return`${Io(c.fnName,s,n)} ${Je.bold}${u}${Je.reset}${f}`}let r=o[0].fnName,i=[...new Set(o.map(c=>_i[c.fnName]||c.fnName.replace(/_/g," ")))],a=i.length<=3?i.join(", "):`${o.length} tools`;return`${Io(r,s,n)} ${Je.bold}${a}${Je.reset}`}function mm(t,e){let s;switch(t){case"write_file":case"edit_file":case"patch_file":case"read_file":case"list_directory":s=e.path||"";break;case"bash":case"ssh_exec":s=(e.command||"").substring(0,80);break;case"grep":case"search_files":s=e.pattern?`"${e.pattern}"${e.path?` in ${e.path}`:""}`:"";break;case"glob":s=e.pattern||"";break;case"web_fetch":s=(e.url||"").substring(0,60);break;case"web_search":s=(e.query||"").substring(0,50);break;default:s=JSON.stringify(e).substring(0,80)}let n=_i[t]||t.replace(/_/g," "),o=s?`(${Je.dim}${s}${Je.reset})`:"";return`${Io(t)} ${Je.bold}${n}${Je.reset}${o}`}function gm(t,e=8){let s=t.split(`
16
+ `),n=s.slice(0,e),o=s.length-e,r=`${E.muted} \u23BF ${E.reset}`,i=" ",a=n.map((c,l)=>`${l===0?r:i}${E.success}${c}${E.reset}`).join(`
17
+ `);return o>0&&(a+=`
18
+ ${E.subtle} \u2026 +${o} lines${E.reset}`),a}function ym(t,e){switch(t){case"bash":case"ask_user":case"write_file":case"edit_file":case"patch_file":case"task_list":case"spawn_agents":return null;case"read_file":return`Reading: ${e.path||"file"}`;case"list_directory":return`Listing: ${e.path||"."}`;case"search_files":return`Searching: ${e.pattern||"..."}`;case"glob":return`Glob: ${e.pattern||"..."}`;case"grep":return`Grep: ${e.pattern||"..."}`;case"web_fetch":return`Fetching: ${(e.url||"").substring(0,60)}`;case"web_search":return`Searching web: ${(e.query||"").substring(0,50)}`;case"git_status":return"Git status...";case"git_diff":return`Git diff${e.file?`: ${e.file}`:""}...`;case"git_log":return`Git log${e.file?`: ${e.file}`:""}...`;case"gh_run_list":return`GitHub Actions: listing runs${e.workflow?` (${e.workflow})`:""}...`;case"gh_run_view":return`GitHub Actions: run ${e.run_id}...`;case"gh_workflow_trigger":return`GitHub Actions: trigger ${e.workflow}...`;case"browser_open":return`Browser: opening ${(e.url||"").substring(0,60)}...`;case"browser_screenshot":return`Browser: screenshot ${(e.url||"").substring(0,60)}...`;case"browser_click":return`Browser: clicking ${e.text||e.selector||"element"}...`;case"browser_fill":return`Browser: filling ${e.selector||"field"}...`;case"sysadmin":{let s=e.server&&e.server!=="local"?` [${e.server}]`:"";switch(e.action){case"audit":return`Sysadmin${s}: full audit...`;case"disk_usage":return`Sysadmin${s}: disk usage ${e.path||"/"}...`;case"process_list":return`Sysadmin${s}: top processes (${e.sort_by||"cpu"})...`;case"network_status":return`Sysadmin${s}: network status...`;case"ssl_check":return`Sysadmin${s}: SSL check ${e.domain||e.cert_path||""}...`;case"log_tail":return`Sysadmin${s}: tail ${e.path||"log"}...`;case"find_large":return`Sysadmin${s}: find large files in ${e.path||"/"}...`;case"service":return`Sysadmin${s}: service ${e.service_action||""} ${e.service_name||""}...`;case"kill_process":return`Sysadmin${s}: kill PID ${e.pid||e.process_name||"?"}...`;case"journalctl":return`Sysadmin${s}: journal ${e.unit?`[${e.unit}]`:""}${e.since?` since ${e.since}`:""}...`;case"package":return`Sysadmin${s}: package ${e.package_action||""} ${(e.packages||[]).join(" ")}...`;case"firewall":return`Sysadmin${s}: firewall ${e.firewall_action||""}...`;case"user_manage":return`Sysadmin${s}: user ${e.user_action||""} ${e.user||""}...`;case"cron":return`Sysadmin${s}: cron ${e.cron_action||""}...`;default:return`Sysadmin${s}: ${e.action}...`}}default:return`Running: ${t}`}}function $m(t,e,s,n){let o=String(s||"");if(n){let a=o.split(`
19
+ `)[0];if(a.startsWith("BLOCKED:")){let d=a.replace(/^BLOCKED:\s*/,"").replace(/\s*—.*$/,"").replace(/\s*\(hard cap:.*?\)/,"").trim().substring(0,70);return` ${E.muted}\u23BF blocked: ${d}${E.reset}`}let c=a.replace(/^ERROR:\s*/i,"").substring(0,80),l=o.match(/\nHINT: (.+)/),u=l?`
20
+ ${E.muted}${l[1].substring(0,100)}${E.reset}`:"";return` ${E.error}\u23BF ${c}${E.reset}${u}`}let r;switch(t){case"read_file":{let c=o.split(`
21
+ `).filter(Boolean).filter(g=>!/^File:\s/.test(g)&&!/^\[LARGE FILE:/.test(g)),l=c.length,u=c[c.length-1],d=u?parseInt(u.match(/^(\d+):/)?.[1]||"0"):0,f=e.line_start||e.line_end,h=e.path?require("path").basename(e.path):null,m=h?` ${E.muted}from ${h}${E.reset}`:"";f&&d>l?r=`Read lines ${e.line_start||1}\u2013${d}${m}`:r=`Read ${l} line${l!==1?"s":""}${m}`;break}case"write_file":{let c=(e.content||"").split(`
22
+ `).length,l=e.path?require("path").basename(e.path):null,u=l?`Wrote ${l} \xB7 ${c} line${c!==1?"s":""}`:`Wrote ${c} line${c!==1?"s":""}`,{highlightLines:d}=bi(),f=d(e.content||"",e.path||null),h=40,m=8;if(c<=h){let g=f.map(b=>` ${b}`).join(`
23
+ `);r=`${u}
24
+ ${g}`}else{let g=f.slice(0,m).map(b=>` ${b}`).join(`
25
+ `);r=`${u}
26
+ ${g}
27
+ ${E.subtle}\u2026 +${c-m} lines${E.reset}`}break}case"edit_file":{let a=(e.old_text||"").split(`
28
+ `),c=(e.new_text||"").split(`
29
+ `),l=a.length,u=c.length,d=e.path?require("path").basename(e.path):null,f=d?` ${E.muted}${d}${E.reset}`:"",h=a.find(U=>U.trim()),m=c.find(U=>U.trim()),{highlightLine:g,detectLang:b}=bi(),v=b(e.path||null),O=[];h&&O.push(` ${E.diff_rem}- ${E.reset}${g(h.trimEnd().substring(0,72),v)}${E.reset}`),m&&O.push(` ${E.diff_add}+ ${E.reset}${g(m.trimEnd().substring(0,72),v)}${E.reset}`),r=`${E.diff_rem}\u2212${l}${E.reset} ${E.diff_add}+${u}${E.reset}${f}`+(O.length>0?`
30
+ `+O.join(`
31
+ `):"");break}case"patch_file":{let a=e.patches||[],c=a.reduce((u,d)=>u+(d.old_text||"").split(`
32
+ `).length,0),l=a.reduce((u,d)=>u+(d.new_text||"").split(`
33
+ `).length,0);r=`${E.reset}${a.length} patch${a.length!==1?"es":""} ${E.diff_rem}\u2212${c}${E.reset} ${E.diff_add}+${l}${E.reset}`;break}case"bash":{let c=o.match(/^EXIT (\d+)/),l=o.split(`
34
+ `).filter(f=>f&&!f.startsWith("EXIT ")&&!f.startsWith("HINT:")&&f.trim()),u=c?c[1]==="0"?`${E.success}\u2713${E.reset}`:`${E.error}\u2717 Exit ${c[1]}${E.reset}`:`${E.success}\u2713${E.reset}`,d=o.match(/\nHINT: (.+)/);if(d)r=`${u} ${E.muted}\u2014 ${d[1].substring(0,100)}${E.reset}`;else if(l.length===0)r=u;else{let f=c&&c[1]!=="0",h=f?l.slice(-3):l.slice(0,3),m=l.length-3,g=h.map((b,v)=>v===0?`${u} ${E.muted}${b.substring(0,120)}${E.reset}`:` ${E.muted}${b.substring(0,120)}${E.reset}`);if(m>0){let b=f?` ${E.subtle}${m} lines above\u2026${E.reset}`:` ${E.subtle}\u2026 +${m} lines${E.reset}`;f?g.unshift(b):g.push(b)}r=g.join(`
35
+ `)}break}case"grep":case"search_files":{if(o.includes("(no matches)")||o==="no matches")r=`No matches${e.pattern?` ${E.muted}"${String(e.pattern).substring(0,40)}"${E.reset}`:""}`;else{let m=function(v){let O=v.indexOf(":");if(O===-1)return`${E.muted}${v.substring(0,90)}${E.reset}`;let U=v.substring(0,O),L=v.substring(O+1),R=L.match(/^(\d+)[:-](.*)/s),C=R?`:${R[1]}`:"",K=(R?R[2]:L).trim(),Q=`${E.subtle}${a.basename(U)}${C}${E.reset}`,re=`${E.muted}${K.substring(0,80)}${K.length>80?"\u2026":""}${E.reset}`;return`${Q} ${re}`};var i=m;let a=require("path"),c=o.split(`
36
+ `).filter(Boolean),l=c.length,d=new Set(c.map(v=>v.split(":")[0]).filter(Boolean)).size,f=e.pattern?` ${E.muted}"${String(e.pattern).substring(0,40)}"${E.reset}`:"",h=d>1?`${l} match${l!==1?"es":""} in ${d} files${f}`:`${l} match${l!==1?"es":""}${f}`,g=c.slice(0,3).map((v,O)=>O===0?`${h}
37
+ ${m(v)}`:` ${m(v)}`),b=c.length-3;b>0&&g.push(` ${E.subtle}\u2026 +${b} lines${E.reset}`),r=g.join(`
38
+ `)}break}case"glob":{let a=e.pattern?` ${E.muted}${String(e.pattern).substring(0,50)}${E.reset}`:"";if(o==="(no matches)")r=`No files found${a}`;else{let c=require("path"),l=o.split(`
39
+ `).filter(Boolean),u=l.length,d=l.slice(0,5).map(m=>c.basename(m)),f=u-d.length,h=d.join(", ")+(f>0?`, +${f} more`:"");r=`${u} file${u!==1?"s":""}${a} \u2014 ${E.muted}${h}${E.reset}`}break}case"list_directory":{if(o==="(empty)")r="0 entries";else{let a=o.split(`
40
+ `).filter(Boolean),c=a.length,l=a.slice(0,6).join(", "),u=c-6;r=u>0?`${c} entries \u2014 ${E.muted}${l}, +${u} more${E.reset}`:`${c} entr${c!==1?"ies":"y"} \u2014 ${E.muted}${l}${E.reset}`}break}case"git_status":{let a=o.match(/Branch:\s*(\S+)/),c=o.split(`
41
+ `).filter(l=>/^\s*[MADRCU?!]/.test(l)).length;r=a?`${a[1]} \xB7 ${c} change${c!==1?"s":""}`:"Done";break}case"git_diff":{let a=(o.match(/^\+[^+]/gm)||[]).length,c=(o.match(/^-[^-]/gm)||[]).length;r=a||c?`+${a} \u2212${c} lines`:"No diff";break}case"git_log":{let a=o.split(`
42
+ `).filter(d=>/^commit\s+[0-9a-f]{7}/.test(d)),c=a.length,l=a[0]?a[0].replace(/^commit\s+/,"").substring(0,7):null,u=(()=>{let d=o.indexOf(a[0]||"\0");return d===-1?null:o.substring(d).split(`
43
+ `).find((h,m)=>m>0&&h.trim()&&!h.startsWith("Author:")&&!h.startsWith("Date:")&&!h.startsWith("Merge:"))})();if(c===0)r="Log retrieved";else if(l&&u){let d=c>1?` ${E.muted}+${c-1} more${E.reset}`:"";r=`${l} ${E.muted}${u.trim().substring(0,60)}${E.reset}${d}`}else r=`${c} commit${c!==1?"s":""}`;break}case"git_commit":{let a=o.match(/\[[\w./\-]+ ([0-9a-f]{7,})\]/),c=o.match(/\[[\w./\-]+ [0-9a-f]+\]\s+(.+)/);r=a?`${a[1]}${c?` \u2014 ${c[1].substring(0,55)}`:""}`:"Committed";break}case"git_push":{let a=o.match(/(?:->|→)\s*(\S+)/);r=a?`\u2192 ${a[1]}`:"Pushed";break}case"git_pull":{if(/Already up.to.date/i.test(o))r="Already up to date";else{let a=(o.match(/^\+/gm)||[]).length;r=a>0?`Pulled \xB7 +${a} lines`:"Pulled"}break}case"web_fetch":{let a=o.match(/<title[^>]*>([^<]{1,80})<\/title>/i),c=o.match(/^#\s+(.{1,80})/m),l=e.url||"",u="";try{u=new URL(l).hostname}catch{u=l.substring(0,60)}let d=a?a[1].trim():c?c[1].trim():null;r=d?`${u} \u2014 ${E.muted}${d.substring(0,70)}${E.reset}`:`Fetched ${u}`;break}case"web_search":{let a=o.split(`
44
+
45
+ `).filter(Boolean),c=a.length,l=a[0]?a[0].split(`
46
+ `)[0].replace(/^\d+\.\s*/,"").trim():null,u=l?` ${E.muted}\u2014 ${l.substring(0,70)}${E.reset}`:"";r=`${c} result${c!==1?"s":""}${u}`;break}case"task_list":r="Done";break;case"spawn_agents":{let a=(o.match(/✓ Agent/g)||[]).length,c=(o.match(/✗ Agent/g)||[]).length;r=c>0?`${a} done, ${c} failed`:`${a} agent${a!==1?"s":""} done`;break}case"switch_model":{let a=o.match(/Switched to (.+)/);r=a?`\u2192 ${a[1]}`:"Done";break}case"ssh_exec":{let c=o.startsWith("EXIT ")||o.startsWith("Command failed"),l=o.split(`
47
+ `).filter(d=>d.trim()&&!d.startsWith("EXIT ")),u=c?`${E.error}\u2717${E.reset}`:`${E.success}\u2713${E.reset}`;if(l.length===0)r=u;else{if(l.length>2&&l.every(g=>/^\[/.test(g.trim()))){r=`${u} ${l.length} log lines`;break}let f=c?l.slice(-3):l.slice(0,3),h=l.length-3,m=f.map((g,b)=>b===0?`${u} ${E.muted}${g.substring(0,120)}${E.reset}`:` ${E.muted}${g.substring(0,120)}${E.reset}`);if(h>0){let g=c?` ${E.subtle}${h} lines above\u2026${E.reset}`:` ${E.subtle}\u2026 +${h} lines${E.reset}`;c?m.unshift(g):m.push(g)}r=m.join(`
48
+ `)}break}default:{let a=o.split(`
49
+ `).filter(c=>c.trim()&&!c.startsWith("EXIT ")&&!c.startsWith("HINT:"));if(a.length>0){let c=a[0].trim().substring(0,90),l=a.length>1?` ${E.subtle}\u2026 +${a.length-1} lines${E.reset}`:"";r=`${E.muted}${c}${E.reset}${l}`}else r="Done"}}return` ${E.muted}\u23BF ${r}${E.reset}`}function wm(t,e,s,n,o,r){let i=Math.round(n/1e3),a=i>=60?`${Math.floor(i/60)}m ${i%60}s`:`${i}s`,c=`
50
+ ${E.success}\u25C6${Je.reset} ${Je.bold}${t}${Je.reset}`;return c+=`${Je.dim} \xB7 ${a}`,r.size>0&&(c+=` \xB7 ${r.size} file${r.size!==1?"s":""} modified`),c+=Je.reset,c}ol.exports={C:Je,formatToolCall:mm,formatResult:gm,getToolSpinnerText:ym,formatToolSummary:$m,formatSectionHeader:hm,formatMilestone:wm}});var Ue=se((uk,al)=>{var{T:an}=ks(),xi=an,il=["01100110","01111110","01111110","01011010","01111110","00111100"];function bm(t,e){let s=[];for(let n=0;n<t.length;n+=2){let o="";for(let r=0;r<t[0].length;r++){let i=t[n][r]==="1",a=n+1<t.length&&t[n+1][r]==="1";i&&a?o+=`${e}\u2588\x1B[0m`:i&&!a?o+=`${e}\u2580\x1B[0m`:!i&&a?o+=`${e}\u2584\x1B[0m`:o+=" "}s.push(o)}return s}function _m(t,e,s={}){let n=xi.bold,o=xi.reset,r=bm(il,an.banner_logo),i=s.yolo?` ${n}${an.banner_yolo}\u26A1 YOLO${o}`:"",a=No().version,c=[` ${an.banner_name}${n}nex-code${o} ${an.banner_version}v${a}${o}`,` ${an.banner_model}${t}${o} ${an.muted}\xB7 /help${o}${i}`,""],l=Math.max(r.length,c.length),u=Math.floor((l-r.length)/2),d=Math.floor((l-c.length)/2),f=il[0].length,h=[];for(let m=0;m<l;m++){let g=r[m-u]??" ".repeat(f),b=c[m-d]??"";h.push(g+b)}console.log(`
51
+ `+h.join(`
52
+ `)+`
53
+ `)}var{Spinner:xm,MultiProgress:km,TaskProgress:vm,ToolProgress:Sm,setActiveTaskProgress:Em,getActiveTaskProgress:Tm,cleanupTerminal:Rm}=Hn(),{formatToolCall:Cm,formatResult:Am,getToolSpinnerText:Om,formatToolSummary:Nm,formatSectionHeader:Mm,formatMilestone:Lm}=rl();al.exports={C:xi,banner:_m,Spinner:xm,MultiProgress:km,TaskProgress:vm,ToolProgress:Sm,setActiveTaskProgress:Em,getActiveTaskProgress:Tm,cleanupTerminal:Rm,formatToolCall:Cm,formatResult:Am,getToolSpinnerText:Om,formatToolSummary:Nm,formatSectionHeader:Mm,formatMilestone:Lm}});var Gn=se((dk,cl)=>{async function Pm(t,e){if(!t.response?.data)return t.message;let s=t.response.data;if(typeof s=="object"&&s!==null&&typeof s.pipe!="function")return e(s)||t.message;try{let n=await new Promise((r,i)=>{let a=[];s.on("data",c=>a.push(c)),s.on("end",()=>r(Buffer.concat(a).toString("utf8"))),s.on("error",i)}),o=JSON.parse(n);return e(o)||n||t.message}catch{return t.message}}var ki=class t{constructor(e={}){if(new.target===t)throw new Error("BaseProvider is abstract \u2014 use a concrete provider");this.name=e.name||"unknown",this.baseUrl=e.baseUrl||"",this.models=e.models||{},this.defaultModel=e.defaultModel||null}isConfigured(){throw new Error(`${this.name}: isConfigured() not implemented`)}getApiKey(){return null}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}getModel(e){return this.models[e]||null}async chat(e,s,n={}){throw new Error(`${this.name}: chat() not implemented`)}async stream(e,s,n={}){throw new Error(`${this.name}: stream() not implemented`)}formatMessages(e){return{messages:e}}formatTools(e){return e}normalizeResponse(e){throw new Error(`${this.name}: normalizeResponse() not implemented`)}};cl.exports={BaseProvider:ki,readStreamErrorBody:Pm}});var zn=se((fk,ll)=>{var Yn=class{buildRequestBody(e){throw new Error("buildRequestBody() not implemented")}getEndpoint(){throw new Error("getEndpoint() not implemented")}formatTools(e){return e}normalizeResponse(e){throw new Error("normalizeResponse() not implemented")}createStreamParser(e,s={}){throw new Error("createStreamParser() not implemented")}},Kn=class{constructor(e,s={}){this.onToken=e,this.callbacks=s,this.content="",this.buffer=""}feed(e){this.buffer+=e;let s=this.buffer.split(`
54
+ `);this.buffer=s.pop()||"";for(let n of s){let o=this.parseLine(n);if(o?.done)return o}return{done:!1}}flush(){return this.buffer.trim()&&(this.parseLine(this.buffer),this.buffer=""),this.getResult()}parseLine(e){throw new Error("parseLine() not implemented")}getResult(){throw new Error("getResult() not implemented")}},jo=class extends Kn{constructor(e,s={}){super(e,s),this.toolCallsMap={}}parseLine(e){let s=e.trim();if(!s||!s.startsWith("data: "))return{done:!1};let n=s.slice(6);if(n==="[DONE]")return{done:!0,result:this.getResult()};let o;try{o=JSON.parse(n)}catch{return{done:!1}}let r=o.choices?.[0]?.delta;if(!r)return{done:!1};if(r.content&&(this.onToken(r.content),this.content+=r.content),r.tool_calls)for(let i of r.tool_calls){let a=i.index??0;this.toolCallsMap[a]||(this.toolCallsMap[a]={id:i.id||"",name:"",arguments:""}),i.id&&(this.toolCallsMap[a].id=i.id),i.function?.name&&(this.toolCallsMap[a].name+=i.function.name),i.function?.arguments&&(this.toolCallsMap[a].arguments+=i.function.arguments)}return{done:!1}}getResult(){return{content:this.content,tool_calls:Object.values(this.toolCallsMap).filter(e=>e.name).map(e=>({id:e.id||`call-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,function:{name:e.name,arguments:e.arguments}}))}}},Do=class extends Yn{getEndpoint(){return"/chat/completions"}buildRequestBody({model:e,messages:s,tools:n,maxTokens:o,temperature:r,stream:i}){let a={model:e,messages:s,max_tokens:o,temperature:r};return i&&(a.stream=!0),n&&n.length>0&&(a.tools=n),a}normalizeResponse(e){let s=e.choices?.[0]?.message||{},n=(s.tool_calls||[]).map(o=>({id:o.id,function:{name:o.function.name,arguments:o.function.arguments}}));return{content:s.content||"",tool_calls:n}}createStreamParser(e,s={}){return new jo(e,s)}},qo=class extends Kn{constructor(e,s={}){super(e,s),this.toolUses=[],this.currentToolIndex=-1}parseLine(e){let s=e.trim();if(!s.startsWith("data: "))return{done:!1};let n=s.slice(6),o;try{o=JSON.parse(n)}catch{return{done:!1}}switch(o.type){case"content_block_start":{let r=o.content_block;r?.type==="tool_use"&&(this.currentToolIndex=this.toolUses.length,this.toolUses.push({id:r.id,name:r.name,inputJson:""}));break}case"content_block_delta":{let r=o.delta;r?.type==="text_delta"&&r.text&&(this.onToken(r.text),this.content+=r.text),r?.type==="input_json_delta"&&r.partial_json!==void 0&&this.currentToolIndex>=0&&(this.toolUses[this.currentToolIndex].inputJson+=r.partial_json);break}case"content_block_stop":this.currentToolIndex=-1;break;case"message_stop":return{done:!0,result:this.getResult()}}return{done:!1}}getResult(){return{content:this.content,tool_calls:this.toolUses.filter(e=>e.name).map(e=>{let s={};if(e.inputJson)try{s=JSON.parse(e.inputJson)}catch{s=e.inputJson}return{id:e.id||`anthropic-${Date.now()}`,function:{name:e.name,arguments:s}}})}}},Fo=class extends Yn{getEndpoint(){return"/messages"}buildRequestBody({model:e,messages:s,tools:n,maxTokens:o,temperature:r,stream:i,extra:a}){let c={model:e,messages:s,max_tokens:o,temperature:r};return i&&(c.stream=!0),a?.system&&(c.system=a.system),n&&n.length>0&&(c.tools=n),c}formatTools(e){return!e||e.length===0?[]:e.map(s=>({name:s.function.name,description:s.function.description||"",input_schema:s.function.parameters||{type:"object",properties:{}}}))}normalizeResponse(e){let s="",n=[];for(let o of e.content||[])o.type==="text"?s+=o.text:o.type==="tool_use"&&n.push({id:o.id,function:{name:o.name,arguments:o.input}});return{content:s,tool_calls:n}}createStreamParser(e,s={}){return new qo(e,s)}},Bo=class extends Kn{constructor(e,s={}){super(e,s),this.toolCalls=[],this.onThinkingToken=s.onThinkingToken||(()=>{})}parseLine(e){if(!e.trim())return{done:!1};let s;try{s=JSON.parse(e)}catch{return{done:!1}}return s.message?.thinking&&this.onThinkingToken(s.message.thinking),s.message?.content&&(this.onToken(s.message.content),this.content+=s.message.content),s.message?.tool_calls&&(this.toolCalls=this.toolCalls.concat(s.message.tool_calls)),s.done?{done:!0,result:this.getResult()}:{done:!1}}getResult(){return{content:this.content,tool_calls:this.toolCalls.map((e,s)=>({id:e.id||`ollama-${Date.now()}-${s}`,function:{name:e.function?.name||e.name||"unknown",arguments:e.function?.arguments||e.arguments||{}}}))}}},Wo=class extends Yn{getEndpoint(){return"/api/chat"}buildRequestBody({model:e,messages:s,tools:n,maxTokens:o,temperature:r,stream:i,extra:a}){let c={model:e,messages:s,stream:i,options:{temperature:r,num_predict:o,repeat_penalty:a?.repeat_penalty??1.05}};return n&&n.length>0&&(c.tools=n),c}normalizeResponse(e){let s=e.message||{};return{content:s.content||"",tool_calls:(s.tool_calls||[]).map((n,o)=>({id:n.id||`ollama-${Date.now()}-${o}`,function:{name:n.function?.name||n.name||"unknown",arguments:n.function?.arguments||n.arguments||{}}}))}}createStreamParser(e,s={}){return new Bo(e,s)}},Im=new Do,jm=new Fo,Dm=new Wo;ll.exports={WireProtocol:Yn,StreamParser:Kn,OpenAICompatibleProtocol:Do,AnthropicProtocol:Fo,OllamaChatProtocol:Wo,OpenAIStreamParser:jo,AnthropicStreamParser:qo,OllamaStreamParser:Bo,openaiProtocol:Im,anthropicProtocol:jm,ollamaProtocol:Dm}});var fl=se((pk,dl)=>{var Uo=require("axios"),qm=require("http"),Fm=require("https"),{BaseProvider:Bm,readStreamErrorBody:Wm}=Gn(),{ollamaProtocol:cn}=zn(),Ho=new qm.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Go=new Fm.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),ul={"qwen3-coder:480b":{id:"qwen3-coder:480b",name:"Qwen3 Coder 480B",maxTokens:16384,contextWindow:131072},"qwen3-coder-next":{id:"qwen3-coder-next",name:"Qwen3 Coder Next",maxTokens:16384,contextWindow:262144},"devstral-2:123b":{id:"devstral-2:123b",name:"Devstral 2 123B",maxTokens:16384,contextWindow:131072},"devstral-small-2:24b":{id:"devstral-small-2:24b",name:"Devstral Small 2 24B",maxTokens:16384,contextWindow:131072},"minimax-m2.7:cloud":{id:"minimax-m2.7:cloud",name:"MiniMax M2.7 Cloud",maxTokens:16384,contextWindow:131072},"kimi-k2.5":{id:"kimi-k2.5",name:"Kimi K2.5",maxTokens:16384,contextWindow:256e3},"kimi-k2:1t":{id:"kimi-k2:1t",name:"Kimi K2 1T",maxTokens:16384,contextWindow:256e3},"kimi-k2-thinking":{id:"kimi-k2-thinking",name:"Kimi K2 Thinking",maxTokens:16384,contextWindow:256e3},"deepseek-v3.2":{id:"deepseek-v3.2",name:"DeepSeek V3.2",maxTokens:16384,contextWindow:131072},"deepseek-v3.1:671b":{id:"deepseek-v3.1:671b",name:"DeepSeek V3.1 671B",maxTokens:16384,contextWindow:131072},"cogito-2.1:671b":{id:"cogito-2.1:671b",name:"Cogito 2.1 671B",maxTokens:16384,contextWindow:131072},"qwen3.5:397b-cloud":{id:"qwen3.5:397b-cloud",name:"Qwen3.5 397B Cloud",maxTokens:16384,contextWindow:262144},"qwen3.5:397b":{id:"qwen3.5:397b",name:"Qwen3.5 397B",maxTokens:16384,contextWindow:262144},"qwen3.5:122b-a10b":{id:"qwen3.5:122b-a10b",name:"Qwen3.5 122B-A10B",maxTokens:16384,contextWindow:262144},"qwen3.5:35b-a3b":{id:"qwen3.5:35b-a3b",name:"Qwen3.5 35B-A3B",maxTokens:16384,contextWindow:262144},"qwen3.5:27b":{id:"qwen3.5:27b",name:"Qwen3.5 27B",maxTokens:16384,contextWindow:262144},"qwen3-next:80b":{id:"qwen3-next:80b",name:"Qwen3 Next 80B",maxTokens:16384,contextWindow:131072},"mistral-large-3:675b":{id:"mistral-large-3:675b",name:"Mistral Large 3 675B",maxTokens:16384,contextWindow:131072},"gpt-oss:120b":{id:"gpt-oss:120b",name:"GPT-OSS 120B",maxTokens:16384,contextWindow:131072},"minimax-m2.5":{id:"minimax-m2.5",name:"MiniMax M2.5",maxTokens:16384,contextWindow:131072},"glm-5:cloud":{id:"glm-5:cloud",name:"GLM 5 Cloud",maxTokens:16384,contextWindow:2e5},"glm-5":{id:"glm-5",name:"GLM 5",maxTokens:16384,contextWindow:2e5},"glm-4.6":{id:"glm-4.6",name:"GLM 4.6",maxTokens:16384,contextWindow:2e5},"glm-4.7":{id:"glm-4.7",name:"GLM 4.7",maxTokens:16384,contextWindow:128e3},"nemotron-3-super:cloud":{id:"nemotron-3-super:cloud",name:"Nemotron 3 Super Cloud",maxTokens:16384,contextWindow:262144},"qwen3.5:9b":{id:"qwen3.5:9b",name:"Qwen3.5 9B",maxTokens:8192,contextWindow:262144},"qwen3.5:4b":{id:"qwen3.5:4b",name:"Qwen3.5 4B",maxTokens:8192,contextWindow:262144},"qwen3.5:2b":{id:"qwen3.5:2b",name:"Qwen3.5 2B",maxTokens:8192,contextWindow:262144},"qwen3.5:0.8b":{id:"qwen3.5:0.8b",name:"Qwen3.5 0.8B",maxTokens:8192,contextWindow:262144},"gemma3:27b":{id:"gemma3:27b",name:"Gemma 3 27B",maxTokens:8192,contextWindow:131072},"gemma3:12b":{id:"gemma3:12b",name:"Gemma 3 12B",maxTokens:8192,contextWindow:131072},"gemma3:4b":{id:"gemma3:4b",name:"Gemma 3 4B",maxTokens:8192,contextWindow:131072},"ministral-3:14b":{id:"ministral-3:14b",name:"Ministral 3 14B",maxTokens:8192,contextWindow:131072},"ministral-3:8b":{id:"ministral-3:8b",name:"Ministral 3 8B",maxTokens:8192,contextWindow:131072},"gemini-3-flash-preview":{id:"gemini-3-flash-preview",name:"Gemini 3 Flash Preview",maxTokens:16384,contextWindow:131072}},vi=class extends Bm{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||ul,defaultModel:e.defaultModel||"qwen3-coder:480b",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this._discovered=!1}async discoverModels(){if(!this._discovered){if(this._discovered=!0,!process.stdout.isTTY){Uo.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Ho,httpsAgent:Go}).then(e=>{let s=e.data?.models||[];for(let n of s){let o=(n.name||n.model||"").replace(/:latest$/,"");!o||this.models[o]||(this.models[o]={id:o,name:n.name||o,maxTokens:16384,contextWindow:131072})}}).catch(()=>{});return}try{let s=(await Uo.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Ho,httpsAgent:Go})).data?.models||[];for(let n of s){let o=(n.name||n.model||"").replace(/:latest$/,"");!o||this.models[o]||(this.models[o]={id:o,name:n.name||o,maxTokens:16384,contextWindow:131072})}}catch{}}}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OLLAMA_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OLLAMA_API_KEY not set");return{Authorization:`Bearer ${e}`}}_formatMessages(e){return e.map(s=>{if(s.role==="user"&&Array.isArray(s.content)){let n=[],o=[];for(let i of s.content)i.type==="text"?n.push(i.text??""):i.type==="image"&&i.data&&o.push(i.data);let r={role:"user",content:n.join(`
55
+ `)};return o.length>0&&(r.images=o),r}return s})}async chat(e,s,n={}){await this.discoverModels();let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||16384,a=cn.buildRequestBody({model:o,messages:this._formatMessages(e),tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!1,extra:{repeat_penalty:n.repeat_penalty}}),c;try{c=await Uo.post(`${this.baseUrl}${cn.getEndpoint()}`,a,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),httpAgent:Ho,httpsAgent:Go})}catch(l){if(l.name==="CanceledError"||l.name==="AbortError"||l.code==="ERR_CANCELED")throw l;let u=l.response?.status?` [HTTP ${l.response.status}]`:"",d=l.response?.data?.error||l.message;throw new Error(`API Error${u}: ${d}`)}return cn.normalizeResponse(c.data)}async stream(e,s,n={}){await this.discoverModels();let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||16384,a=n.onToken||(()=>{}),c=n.onThinkingToken||(()=>{}),l=cn.buildRequestBody({model:o,messages:this._formatMessages(e),tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!0,extra:{repeat_penalty:n.repeat_penalty}}),u;try{u=await Uo.post(`${this.baseUrl}${cn.getEndpoint()}`,l,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal,httpAgent:Ho,httpsAgent:Go})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let h=f.response?.status?` [HTTP ${f.response.status}]`:"",m=await Wm(f,g=>g?.error);throw new Error(`API Error${h}: ${m}`)}let d=cn.createStreamParser(a,{onThinkingToken:c});return new Promise((f,h)=>{n.signal&&n.signal.addEventListener("abort",()=>{u.data.destroy(),h(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",m=>{let{done:g,result:b}=d.feed(m.toString());g&&f(b)}),u.data.on("error",m=>{n.signal?.aborted||h(new Error(`Stream error: ${m.message}`))}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return cn.normalizeResponse(e)}};dl.exports={OllamaProvider:vi,OLLAMA_MODELS:ul}});var gl=se((hk,ml)=>{var pl=require("axios"),{BaseProvider:Um,readStreamErrorBody:Hm}=Gn(),{openaiProtocol:ln}=zn(),hl={"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}},Si=class extends Um{constructor(e={}){super({name:"openai",baseUrl:e.baseUrl||"https://api.openai.com/v1",models:e.models||hl,defaultModel:e.defaultModel||"gpt-4o",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OPENAI_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OPENAI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let s=[];for(let n of e){if(this._messageFormatCache.has(n)){s.push(this._messageFormatCache.get(n));continue}let o=this._getMessageCacheKey(n);if(this._messageStringCache.has(o)){let i=this._messageStringCache.get(o);this._messageFormatCache.set(n,i),s.push(i);continue}let r=this._formatSingleMessage(n);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(o,r),this._messageFormatCache.set(n,r),s.push(r)}return{messages:s}}_getMessageCacheKey(e){let s=e.role||"",n=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${s}:${n.length}:${o}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||null,tool_calls:e.tool_calls.map(s=>({id:s.id||`call-${Date.now()}`,type:"function",function:{name:s.function.name,arguments:typeof s.function.arguments=="string"?s.function.arguments:JSON.stringify(s.function.arguments)}}))};if(e.role==="tool")return{role:"tool",content:typeof e.content=="string"?e.content:JSON.stringify(e.content),tool_call_id:e.tool_call_id};if(e.role==="user"&&Array.isArray(e.content)){let s=[];for(let n of e.content)if(n.type==="text")s.push({type:"text",text:n.text??""});else if(n.type==="image"&&n.data){let o=n.data.startsWith("data:")?n.data:`data:${n.media_type||"image/png"};base64,${n.data}`;s.push({type:"image_url",image_url:{url:o,detail:"auto"}})}return{role:"user",content:s}}return{role:e.role,content:e.content}}async chat(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||16384,{messages:a}=this.formatMessages(e),c=ln.buildRequestBody({model:o,messages:a,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!1}),l;try{l=await pl.post(`${this.baseUrl}${ln.getEndpoint()}`,c,{timeout:n.timeout||this.timeout,headers:this._getHeaders()})}catch(u){if(u.name==="CanceledError"||u.name==="AbortError"||u.code==="ERR_CANCELED")throw u;let d=u.response?.status?` [HTTP ${u.response.status}]`:"",f=u.response?.data?.error?.message||u.response?.data?.error||u.message;throw new Error(`API Error${d}: ${f}`)}return ln.normalizeResponse(l.data)}async stream(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||16384,a=n.onToken||(()=>{}),{messages:c}=this.formatMessages(e),l=ln.buildRequestBody({model:o,messages:c,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!0}),u;try{u=await pl.post(`${this.baseUrl}${ln.getEndpoint()}`,l,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let h=f.response?.status?` [HTTP ${f.response.status}]`:"",m=await Hm(f,g=>g?.error?.message||g?.error);throw new Error(`API Error${h}: ${m}`)}let d=ln.createStreamParser(a);return new Promise((f,h)=>{n.signal&&n.signal.addEventListener("abort",()=>{u.data.destroy(),h(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",m=>{let{done:g,result:b}=d.feed(m.toString());g&&f(b)}),u.data.on("error",m=>{n.signal?.aborted||h(new Error(`Stream error: ${m.message}`))}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return ln.normalizeResponse(e)}};ml.exports={OpenAIProvider:Si,OPENAI_MODELS:hl}});var bl=se((mk,wl)=>{var yl=require("axios"),{BaseProvider:Gm,readStreamErrorBody:Ym}=Gn(),{anthropicProtocol:Vt}=zn(),$l={"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}},Km="2023-06-01",Ei=class extends Gm{constructor(e={}){super({name:"anthropic",baseUrl:e.baseUrl||"https://api.anthropic.com/v1",models:e.models||$l,defaultModel:e.defaultModel||"claude-sonnet",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this.apiVersion=e.apiVersion||Km}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.ANTHROPIC_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("ANTHROPIC_API_KEY not set");return{"x-api-key":e,"anthropic-version":this.apiVersion,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let s="",n=[];for(let o of e){if(o.role==="system"){s+=(s?`
56
+
57
+ `:"")+o.content;continue}if(o.role!=="system"&&o.role!=="tool"&&this._messageFormatCache.has(o)){n.push(this._messageFormatCache.get(o));continue}let r=this._formatSingleMessage(o,n);if(r){if(o.role!=="system"&&o.role!=="tool"&&this._messageStringCache.size<this._maxCacheSize){let i=this._getMessageCacheKey(o);this._messageStringCache.set(i,r),this._messageFormatCache.set(o,r)}n.push(r)}}for(let o=n.length-1;o>0;o--)n[o].role==="user"&&n[o-1].role==="user"&&n.splice(o,0,{role:"assistant",content:[{type:"text",text:"[continuing]"}]});return{messages:n,system:s}}_getMessageCacheKey(e){let s=e.role||"",n=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${s}:${n.length}:${o}`}_formatSingleMessage(e,s=[]){if(e.role==="assistant"){let n=[];if(e.content&&n.push({type:"text",text:e.content}),e.tool_calls)for(let o of e.tool_calls)n.push({type:"tool_use",id:o.id||`toolu-${Date.now()}`,name:o.function.name,input:typeof o.function.arguments=="string"?JSON.parse(o.function.arguments||"{}"):o.function.arguments||{}});return{role:"assistant",content:n.length>0?n:[{type:"text",text:""}]}}if(e.role==="tool"){let n=s[s.length-1],o={type:"tool_result",tool_use_id:e.tool_call_id,content:typeof e.content=="string"?e.content:JSON.stringify(e.content)};return n&&n.role==="user"&&Array.isArray(n.content)&&n.content[0]?.type==="tool_result"?(n.content.push(o),null):{role:"user",content:[o]}}if(Array.isArray(e.content)){let n=[];for(let o of e.content)o.type==="text"?n.push({type:"text",text:o.text??""}):o.type==="image"&&o.data&&n.push({type:"image",source:{type:"base64",media_type:o.media_type||"image/png",data:o.data}});return{role:"user",content:n}}return{role:"user",content:e.content}}formatTools(e){return Vt.formatTools(e)}_resolveModelId(e){return this.getModel(e)?.id||e}async chat(e,s,n={}){let o=n.model||this.defaultModel,r=this._resolveModelId(o),i=this.getModel(o),a=n.maxTokens||i?.maxTokens||8192,{messages:c,system:l}=this.formatMessages(e),u=this.formatTools(s),d=Vt.buildRequestBody({model:r,messages:c,tools:u,maxTokens:a,temperature:n.temperature??this.temperature,stream:!1,extra:{system:l}}),f;try{f=await yl.post(`${this.baseUrl}${Vt.getEndpoint()}`,d,{timeout:n.timeout||this.timeout,headers:this._getHeaders()})}catch(h){if(h.name==="CanceledError"||h.name==="AbortError"||h.code==="ERR_CANCELED")throw h;let m=h.response?.status?` [HTTP ${h.response.status}]`:"",g=h.response?.data?.error?.message||h.response?.data?.error||h.message;throw new Error(`API Error${m}: ${g}`)}return Vt.normalizeResponse(f.data)}async stream(e,s,n={}){let o=n.model||this.defaultModel,r=this._resolveModelId(o),i=this.getModel(o),a=n.maxTokens||i?.maxTokens||8192,c=n.onToken||(()=>{}),{messages:l,system:u}=this.formatMessages(e),d=this.formatTools(s),f=Vt.buildRequestBody({model:r,messages:l,tools:d,maxTokens:a,temperature:n.temperature??this.temperature,stream:!0,extra:{system:u}}),h;try{h=await yl.post(`${this.baseUrl}${Vt.getEndpoint()}`,f,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(g){if(g.name==="CanceledError"||g.name==="AbortError"||g.code==="ERR_CANCELED")throw g;let b=g.response?.status?` [HTTP ${g.response.status}]`:"",v=await Ym(g,O=>O?.error?.message||O?.error);throw new Error(`API Error${b}: ${v}`)}let m=Vt.createStreamParser(c);return new Promise((g,b)=>{n.signal&&n.signal.addEventListener("abort",()=>{h.data.destroy(),b(new DOMException("The operation was aborted","AbortError"))},{once:!0}),h.data.on("data",v=>{let{done:O,result:U}=m.feed(v.toString());O&&g(U)}),h.data.on("error",v=>{n.signal?.aborted||b(new Error(`Stream error: ${v.message}`))}),h.data.on("end",()=>{g(m.flush())})})}normalizeResponse(e){return Vt.normalizeResponse(e)}};wl.exports={AnthropicProvider:Ei,ANTHROPIC_MODELS:$l}});var vl=se((gk,kl)=>{var _l=require("axios"),{BaseProvider:zm,readStreamErrorBody:Xm}=Gn(),{openaiProtocol:un}=zn(),xl={"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}},Ti=class extends zm{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||xl,defaultModel:e.defaultModel||"gemini-2.5-flash",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("GEMINI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let s=[];for(let n of e){if(this._messageFormatCache.has(n)){s.push(this._messageFormatCache.get(n));continue}let o=this._getMessageCacheKey(n);if(this._messageStringCache.has(o)){let i=this._messageStringCache.get(o);this._messageFormatCache.set(n,i),s.push(i);continue}let r=this._formatSingleMessage(n);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(o,r),this._messageFormatCache.set(n,r),s.push(r)}return{messages:s}}_getMessageCacheKey(e){let s=e.role||"",n=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${s}:${n.length}:${o}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||"",tool_calls:e.tool_calls.map(s=>({id:s.id||`call-${Date.now()}`,type:"function",function:{name:s.function.name,arguments:typeof s.function.arguments=="string"?s.function.arguments:JSON.stringify(s.function.arguments)}}))};if(e.role==="tool")return{role:"tool",content:typeof e.content=="string"?e.content:JSON.stringify(e.content),tool_call_id:e.tool_call_id};if(e.role==="user"&&Array.isArray(e.content)){let s=[];for(let n of e.content)if(n.type==="text")s.push({type:"text",text:n.text??""});else if(n.type==="image"&&n.data){let o=n.data.startsWith("data:")?n.data:`data:${n.media_type||"image/png"};base64,${n.data}`;s.push({type:"image_url",image_url:{url:o,detail:"auto"}})}return{role:"user",content:s}}return{role:e.role,content:e.content}}async chat(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||8192,{messages:a}=this.formatMessages(e),c=un.buildRequestBody({model:o,messages:a,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!1}),l;try{l=await _l.post(`${this.baseUrl}${un.getEndpoint()}`,c,{timeout:n.timeout||this.timeout,headers:this._getHeaders()})}catch(u){if(u.name==="CanceledError"||u.name==="AbortError"||u.code==="ERR_CANCELED")throw u;let d=u.response?.status?` [HTTP ${u.response.status}]`:"",f=u.response?.data?.error?.message||u.response?.data?.error||u.message;throw new Error(`API Error${d}: ${f}`)}return un.normalizeResponse(l.data)}async stream(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||8192,a=n.onToken||(()=>{}),{messages:c}=this.formatMessages(e),l=un.buildRequestBody({model:o,messages:c,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!0}),u;try{u=await _l.post(`${this.baseUrl}${un.getEndpoint()}`,l,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let h=f.response?.status?` [HTTP ${f.response.status}]`:"",m=await Xm(f,g=>g?.error?.message||g?.error);throw new Error(`API Error${h}: ${m}`)}let d=un.createStreamParser(a);return new Promise((f,h)=>{n.signal&&n.signal.addEventListener("abort",()=>{u.data.destroy(),h(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",m=>{let{done:g,result:b}=d.feed(m.toString());g&&f(b)}),u.data.on("error",m=>{n.signal?.aborted||h(new Error(`Stream error: ${m.message}`))}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return un.normalizeResponse(e)}};kl.exports={GeminiProvider:Ti,GEMINI_MODELS:xl}});var Tl=se((yk,El)=>{var Yo=require("axios"),{BaseProvider:Vm,readStreamErrorBody:Jm}=Gn(),{ollamaProtocol:dn}=zn(),Sl="http://localhost:11434",Ri=class extends Vm{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||Sl,models:e.models||{},defaultModel:e.defaultModel||null,...e}),this.timeout=e.timeout||3e5,this.temperature=e.temperature??.2,this._modelsLoaded=!1}isConfigured(){return!0}async loadModels(){if(this._modelsLoaded)return this.models;try{let s=(await Yo.get(`${this.baseUrl}/api/tags`,{timeout:5e3})).data?.models||[];this.models={};for(let n of s){let o=n.name||n.model;if(!o)continue;let r=o.replace(/:latest$/,""),i=32768;try{let a=await Yo.post(`${this.baseUrl}/api/show`,{name:o},{timeout:5e3}),c=a.data?.model_info||a.data?.details||{};i=c["general.context_length"]||c["llama.context_length"]||this._parseContextFromModelfile(a.data?.modelfile)||32768}catch{}this.models[r]={id:r,name:n.name,maxTokens:Math.min(8192,Math.floor(i*.1)),contextWindow:i}}!this.defaultModel&&Object.keys(this.models).length>0&&(this.defaultModel=Object.keys(this.models)[0]),this._modelsLoaded=!0}catch{this.models={},this._modelsLoaded=!1}return this.models}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}_formatMessages(e){return e.map(s=>{if(s.role==="user"&&Array.isArray(s.content)){let n=[],o=[];for(let i of s.content)i.type==="text"?n.push(i.text??""):i.type==="image"&&i.data&&o.push(i.data);let r={role:"user",content:n.join(`
58
+ `)};return o.length>0&&(r.images=o),r}return s})}async chat(e,s,n={}){this._modelsLoaded||await this.loadModels();let o=n.model||this.defaultModel;if(!o)throw new Error("No local model available. Is Ollama running?");let r=dn.buildRequestBody({model:o,messages:this._formatMessages(e),tools:s,maxTokens:n.maxTokens||8192,temperature:n.temperature??this.temperature,stream:!1}),i;try{i=await Yo.post(`${this.baseUrl}${dn.getEndpoint()}`,r,{timeout:n.timeout||this.timeout})}catch(a){if(a.name==="CanceledError"||a.name==="AbortError"||a.code==="ERR_CANCELED")throw a;let c=a.response?.status?` [HTTP ${a.response.status}]`:"",l=a.response?.data?.error||a.message;throw new Error(`API Error${c}: ${l}`)}return dn.normalizeResponse(i.data)}async stream(e,s,n={}){this._modelsLoaded||await this.loadModels();let o=n.model||this.defaultModel;if(!o)throw new Error("No local model available. Is Ollama running?");let r=n.onToken||(()=>{}),i=dn.buildRequestBody({model:o,messages:this._formatMessages(e),tools:s,maxTokens:n.maxTokens||8192,temperature:n.temperature??this.temperature,stream:!0}),a;try{a=await Yo.post(`${this.baseUrl}${dn.getEndpoint()}`,i,{timeout:n.timeout||this.timeout,responseType:"stream",signal:n.signal})}catch(l){if(l.name==="CanceledError"||l.name==="AbortError"||l.code==="ERR_CANCELED")throw l;let u=l.response?.status?` [HTTP ${l.response.status}]`:"",d=await Jm(l,f=>f?.error);throw new Error(`API Error${u}: ${d}`)}let c=dn.createStreamParser(r);return new Promise((l,u)=>{n.signal&&n.signal.addEventListener("abort",()=>{a.data.destroy(),u(new DOMException("The operation was aborted","AbortError"))},{once:!0}),a.data.on("data",d=>{let{done:f,result:h}=c.feed(d.toString());f&&l(h)}),a.data.on("error",d=>{n.signal?.aborted||u(new Error(`Stream error: ${d.message}`))}),a.data.on("end",()=>{l(c.flush())})})}normalizeResponse(e){return dn.normalizeResponse(e)}_parseContextFromModelfile(e){if(!e)return null;let s=e.match(/PARAMETER\s+num_ctx\s+(\d+)/i);return s?parseInt(s[1],10):null}};El.exports={LocalProvider:Ri,DEFAULT_LOCAL_URL:Sl}});var fn=se(($k,Cl)=>{"use strict";var ut=require("fs"),Rl=require("path");function Zm(t){if(!t||isNaN(t))return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function Qm(t){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}catch{let e=Date.now()+t;for(;Date.now()<e;);}}function eg(t,e){let s=Rl.dirname(t),n=Rl.join(s,`.nex-tmp.${process.pid}.${Date.now()}`);try{ut.existsSync(s)||ut.mkdirSync(s,{recursive:!0}),ut.writeFileSync(n,e,"utf-8"),ut.renameSync(n,t)}catch(o){try{ut.unlinkSync(n)}catch{}throw o}}function tg(t,e,{timeout:s=5e3,retryMs:n=50}={}){let o=t+".lock",r=Date.now()+s;for(;;){let i=-1;try{i=ut.openSync(o,"wx"),ut.writeSync(i,Buffer.from(String(process.pid))),ut.closeSync(i),i=-1;try{return e()}finally{try{ut.unlinkSync(o)}catch{}}}catch(a){if(i!==-1)try{ut.closeSync(i)}catch{}if(a.code!=="EEXIST")throw a;try{let c=ut.readFileSync(o,"utf-8").trim(),l=parseInt(c,10);if(!Zm(l)){try{ut.unlinkSync(o)}catch{}continue}}catch(c){if(c.code&&c.code!=="ENOENT")throw c;continue}if(Date.now()>=r){try{ut.unlinkSync(o)}catch{}return e()}Qm(n)}}}Cl.exports={atomicWrite:eg,withFileLockSync:tg}});var zo=se((wk,Il)=>{var Xn=require("fs"),Ci=require("path"),{atomicWrite:ng,withFileLockSync:sg}=fn(),Al={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:{}},Ko=[],Jt={};function og(t,e,s,n){if(Ko.push({provider:t,model:e,input:s,output:n}),Jt[t]!==void 0){let o=Ll(t);o.allowed||process.stderr.write(`\x1B[33m\u26A0 Budget limit reached for ${t}: $${o.spent.toFixed(2)} / $${o.limit.toFixed(2)}\x1B[0m
59
+ `)}}function Ai(t,e){let s=Al[t];return s?s[e]||{input:0,output:0}:{input:0,output:0}}function Ol(t){let e=Ai(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function Nl(){let t={};for(let r of Ko){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:Ol(r)})),s=e.reduce((r,i)=>r+i.cost,0),n=e.reduce((r,i)=>r+i.input,0),o=e.reduce((r,i)=>r+i.output,0);return{totalCost:s,totalInput:n,totalOutput:o,breakdown:e}}function rg(){let{totalCost:t,totalInput:e,totalOutput:s,breakdown:n}=Nl();if(n.length===0)return"No token usage recorded this session.";let o=[];o.push("Session Token Usage:"),o.push("");for(let r of n){let i=r.cost>0?`$${r.cost.toFixed(4)}`:"free";o.push(` ${r.provider}:${r.model}`),o.push(` Input: ${r.input.toLocaleString()} tokens`),o.push(` Output: ${r.output.toLocaleString()} tokens`),o.push(` Cost: ${i}`)}return o.push(""),o.push(` Total: ${e.toLocaleString()} in + ${s.toLocaleString()} out = $${t.toFixed(4)}`),o.join(`
60
+ `)}function ig(t){return!t||typeof t!="string"?0:Math.ceil(t.length/4)}function ag(t,e,s,n){let o=Ai(t,e),r=(s*o.input+n*o.output)/1e6;return r<=0?"":`[~$${r.toFixed(4)}]`}function cg(){Ko=[]}function lg(t,e){Jt[t]=e}function ug(t){delete Jt[t]}function dg(){return{...Jt}}function Ml(t){let e=0;for(let s of Ko)s.provider===t&&(e+=Ol(s));return e}function Ll(t){let e=Ml(t),s=Jt[t];if(s===void 0)return{allowed:!0,spent:e,limit:null,remaining:null};let n=Math.max(0,s-e);return{allowed:e<s,spent:e,limit:s,remaining:n}}function Pl(){let t=Ci.join(process.cwd(),".nex","config.json");if(Xn.existsSync(t))try{let e=JSON.parse(Xn.readFileSync(t,"utf-8"));e.costLimits&&typeof e.costLimits=="object"&&(Jt={...e.costLimits})}catch{}}function fg(){let t=Ci.join(process.cwd(),".nex"),e=Ci.join(t,"config.json");Xn.existsSync(t)||Xn.mkdirSync(t,{recursive:!0}),sg(e,()=>{let s={};if(Xn.existsSync(e))try{s=JSON.parse(Xn.readFileSync(e,"utf-8"))}catch{s={}}s.costLimits=Jt,ng(e,JSON.stringify(s,null,2))})}function pg(){Jt={}}Pl();Il.exports={PRICING:Al,trackUsage:og,getSessionCosts:Nl,formatCosts:rg,formatCostHint:ag,resetCosts:cg,getPricing:Ai,setCostLimit:lg,removeCostLimit:ug,getCostLimits:dg,getProviderSpend:Ml,checkBudget:Ll,loadCostLimits:Pl,saveCostLimits:fg,resetCostLimits:pg,estimateTokens:ig}});var Xo=se((bk,jl)=>{function Oi(){return process.env.NEX_DEBUG==="true"||process.argv.includes("--debug")}var hg=Oi();function mg(...t){Oi()&&console.log(...t)}function gg(...t){Oi()&&console.warn(...t)}jl.exports={DEBUG:hg,debugLog:mg,warnLog:gg}});var Fl=se((_k,ql)=>{"use strict";var yg=new Set(["read_file","grep","glob","search_files","list_directory"]),$g=new Set(["write_file","edit_file","patch_file"]),wg=new Set(["bash"]),bg=new Set(["web_search","web_fetch","perplexity_search"]);function Dl(t,e){let s=0,n=0,o=0,r=0,i=0;for(let[a,c]of t)i+=c,yg.has(a)&&(s+=c),$g.has(a)&&(n+=c),wg.has(a)&&(o+=c),bg.has(a)&&(r+=c);return i===0?`Phase ${e}`:r/i>.5?"Research":s/i>.5?"Exploration":n/i>.3?"Implementation":o/i>.3&&n/i<.15?"Verification":`Phase ${e}`}var Ni=class{constructor(e){this._N=e,this._disabled=e<=0,this._phaseNum=0,this._stepsThisPhase=0,this._phaseCounts=new Map,this._phaseStart=Date.now()}record(e,s,n,o){if(this._disabled)return null;this._stepsThisPhase++;for(let i of s)this._phaseCounts.set(i,(this._phaseCounts.get(i)||0)+1);if(this._stepsThisPhase<this._N)return null;this._phaseNum++;let r={phaseNum:this._phaseNum,phaseName:Dl(this._phaseCounts,this._phaseNum),stepCount:this._stepsThisPhase,toolCounts:new Map(this._phaseCounts),elapsed:Date.now()-this._phaseStart,filesRead:new Set(n),filesModified:new Set(o)};return this._stepsThisPhase=0,this._phaseCounts=new Map,this._phaseStart=Date.now(),r}};ql.exports={MilestoneTracker:Ni,_phaseName:Dl}});var Ss=se((xk,Bl)=>{var vs=He(),_g={"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 xg(){return vs.getActiveModel()}function kg(t){return vs.setActiveModel(t)}function vg(){return vs.getModelNames()}function Sg(t){if(!t)return null;if(typeof t=="object")return t;try{return JSON.parse(t)}catch{}try{let n=t.replace(/,\s*([}\]])/g,"$1").replace(/'/g,'"');return JSON.parse(n)}catch{}let e=t.match(/\{[\s\S]*\}/);if(e)try{return JSON.parse(e[0])}catch{}try{let n=t.replace(/(\{|,)\s*([a-zA-Z_]\w*)\s*:/g,'$1"$2":');return JSON.parse(n)}catch{}let s=t.match(/```(?:json)?\s*([\s\S]*?)```/);if(s)try{return JSON.parse(s[1].trim())}catch{}return null}async function Eg(t,e){let{C:s}=Ue(),{Spinner:n}=Ue(),o=new n("Thinking...");o.start();let r=!0,i="";try{let a=await vs.callStream(t,e,{onToken:c=>{r&&(o.stop(),process.stdout.write(`${s.blue}`),r=!1),process.stdout.write(c),i+=c}});return r?o.stop():process.stdout.write(`${s.reset}
61
+ `),a}catch(a){throw o.stop(),a}}async function Tg(t,e){return vs.callChat(t,e)}Bl.exports={MODELS:_g,getActiveModel:xg,setActiveModel:kg,getModelNames:vg,callOllamaStream:Eg,callOllama:Tg,parseToolArgs:Sg}});var Es=se((kk,Kl)=>{var Rg=require("readline"),{C:Mt}=Ue(),Pi=[/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/],Wl=[...Pi,/\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 Cg(t){for(let e of Wl)if(e.test(t))return e;return null}var Ul=[/\.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)/],Ag=/\b(?:rm|rmdir|unlink|truncate|shred|mv|cp)\b/,Mi=[/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 Hl(t){let e=t.match(/ssh\s+[^"]*"([^"]+)"/)?.[1]||t.match(/ssh\s+[^']*'([^']+)'/)?.[1];if(!e)return!1;let n=e.replace(/\bfor\s[\s\S]*?\bdone\b/g,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(n.length===0)return!1;let o=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 a=r.match(/\bdo\s+([\s\S]*?)\s*(?:done|$)/)?.[1];return a?a.split(/\s*;\s*/).map(l=>l.trim()).filter(Boolean).every(l=>o(l)):Mi.some(c=>c.test(r))}return/^\w+=\$?\(/.test(i)||/^\w+=["']/.test(i)||/^\w+=\S/.test(i)?!0:Mi.some(a=>a.test(i))};return n.every(o)}var Ii=[/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)/],Gl=[/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/],Yl=[...Ii,...Gl],ji=!1,pn=null,Li=null;function Og(t){ji=t}function Ng(t){Li=t}function Mg(){return ji}function Lg(t){pn=t}function Pg(t){for(let e of Pi)if(e.test(t))return e;return null}function Ig(t){if(/ssh\s/.test(t)&&Hl(t))return!1;for(let e of Yl)if(e.test(t))return!0;return!1}function jg(t){for(let e of Ii)if(e.test(t))return!0;return!1}function Dg(t){if(process.env.NEX_UNPROTECT==="1"||!Ag.test(t))return null;for(let e of Ul)if(e.test(t))return e;return null}function qg(t,e={}){if(ji)return Promise.resolve(!0);if(Li)return Li(t,e);if(!process.stdout.isTTY||!process.stdin.isTTY)return Fg(t,e);let s=e.toolName?["Yes","No","Always allow"]:["Yes","No"];return new Promise(n=>{let o=0;pn&&pn.pause();let r=global._nexRawWrite||(d=>process.stdout.write(d)),i=()=>{let d=process.stdout.rows||24;return Math.max(1,d-s.length-2)},a=()=>{let d=i(),f=`\x1B[${d};1H\x1B[2K${Mt.yellow}${t}${Mt.reset}`;for(let h=0;h<s.length;h++){let m=h===o,g=m?`${Mt.yellow}\u276F${Mt.reset}`:" ",b=m?`${Mt.yellow}${s[h]}${Mt.reset}`:s[h];f+=`\x1B[${d+1+h};1H\x1B[2K ${g} ${b}`}r(f)},c=d=>{process.stdin.setRawMode(!1),process.stdin.pause(),process.stdin.removeListener("data",u);let f=global._nexRawWrite||(g=>process.stdout.write(g)),h=i(),m="";for(let g=0;g<s.length+1;g++)m+=`\x1B[${h+g};1H\x1B[2K`;f(m),global._nexFooter&&global._nexFooter.drawFooter(),pn&&pn.resume(),n(d)},l=d=>{if(d===1){c(!1);return}d===2&&e.toolName&&Vo(e.toolName),c(!0)},u=d=>{if(d[0]===3){c(!1);return}let f=d.toString();if(f==="\r"||f===`
62
+ `){l(o);return}if(f==="\x1B[A"){o=(o-1+s.length)%s.length,a();return}if(f==="\x1B[B"){o=(o+1)%s.length,a();return}let h=f.toLowerCase().trim();if(h==="y"){c(!0);return}if(h==="n"){c(!1);return}if(h==="a"&&e.toolName){Vo(e.toolName),c(!0);return}};a(),process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",u)})}function Fg(t,e){let s=e.toolName?"[Y/n/a] ":"[Y/n] ";return new Promise(n=>{let o=r=>{let i=r.trim().toLowerCase();i==="a"&&e.toolName?(Vo(e.toolName),n(!0)):n(i!=="n")};if(pn)pn.question(`${Mt.yellow}${t} ${s}${Mt.reset}`,o);else{let r=Rg.createInterface({input:process.stdin,output:process.stdout});r.question(`${Mt.yellow}${t} ${s}${Mt.reset}`,i=>{r.close(),o(i)})}})}var Vo=()=>{};function Bg(t){Vo=t}Kl.exports={FORBIDDEN_PATTERNS:Pi,SSH_FORBIDDEN_PATTERNS:Wl,BASH_PROTECTED_PATHS:Ul,SSH_SAFE_PATTERNS:Mi,isSSHReadOnly:Hl,DANGEROUS_BASH:Yl,CRITICAL_BASH:Ii,NOTABLE_BASH:Gl,isForbidden:Pg,isSSHForbidden:Cg,isDangerous:Ig,isCritical:jg,isBashPathForbidden:Dg,confirm:qg,setAutoConfirm:Og,getAutoConfirm:Mg,setConfirmHook:Ng,setReadlineInterface:Lg,setAllowAlwaysHandler:Bg}});var Vl=se((Sk,Xl)=>{var Jo=require("path"),{C:M}=Ue(),{T:Di,isDark:vk}=ks(),{confirm:Wg,getAutoConfirm:Ug}=Es(),zl=2e3;function Ts(t,e){let s=t.split(`
63
+ `),n=e.split(`
64
+ `),o=[],r=s.length,i=n.length;if(r>zl||i>zl){for(let d of s)o.push({type:"remove",line:d});for(let d of n)o.push({type:"add",line:d});return o}let a=Array.from({length:r+1},()=>new Array(i+1).fill(0));for(let d=1;d<=r;d++)for(let f=1;f<=i;f++)s[d-1]===n[f-1]?a[d][f]=a[d-1][f-1]+1:a[d][f]=Math.max(a[d-1][f],a[d][f-1]);let c=r,l=i,u=[];for(;c>0||l>0;)c>0&&l>0&&s[c-1]===n[l-1]?(u.unshift({type:"same",line:s[c-1]}),c--,l--):l>0&&(c===0||a[c][l-1]>=a[c-1][l])?(u.unshift({type:"add",line:n[l-1]}),l--):(u.unshift({type:"remove",line:s[c-1]}),c--);return u}function Hg(t,e,s,n=3){console.log(`
65
+ ${M.bold}${M.cyan} Diff: ${t}${M.reset}`);let o=Ts(e,s),r=[];if(o.forEach((c,l)=>{c.type!=="same"&&r.push(l)}),r.length===0){console.log(`${M.gray} (no changes)${M.reset}`);return}let i=Math.max(0,r[0]-n),a=Math.min(o.length,r[r.length-1]+n+1);i>0&&console.log(`${M.gray} ...${M.reset}`);for(let c=i;c<a;c++){let l=o[c];switch(l.type){case"remove":console.log(`${M.red} - ${l.line}${M.reset}`);break;case"add":console.log(`${M.green} + ${l.line}${M.reset}`);break;default:console.log(`${M.gray} ${l.line}${M.reset}`)}}a<o.length&&console.log(`${M.gray} ...${M.reset}`),console.log()}function Gg(t,e,s){console.log(`
66
+ ${M.bold}${M.cyan} File exists \u2014 showing changes: ${t}${M.reset}`);let n=Ts(e,s),o=0;for(let i of n)i.type!=="same"&&o++;if(o===0){console.log(`${M.gray} (identical content)${M.reset}`);return}let r=0;for(let i of n){if(r>=30){console.log(`${M.gray} ...(${o-r} more changes)${M.reset}`);break}switch(i.type){case"remove":console.log(`${M.red} - ${i.line}${M.reset}`),r++;break;case"add":console.log(`${M.green} + ${i.line}${M.reset}`),r++;break;default:r>0&&console.log(`${M.gray} ${i.line}${M.reset}`)}}console.log()}function Yg(t,e){console.log(`
67
+ ${M.bold}${M.cyan} New file: ${t}${M.reset}`);let s=e.split(`
68
+ `),n=s.slice(0,20);for(let o of n)console.log(`${M.green} + ${o}${M.reset}`);s.length>20&&console.log(`${M.gray} ...+${s.length-20} more lines${M.reset}`),console.log()}async function Kg(t){return Ug()?!0:Wg(` ${t}?`)}function zg(t,e,s,n){let o=n||process.stdout.columns||80,r=Math.floor((o-3)/2);console.log(`
69
+ ${M.bold}${M.cyan} Side-by-side: ${t}${M.reset}`),console.log(` ${M.dim}${"\u2500".repeat(r)}\u252C${"\u2500".repeat(r)}${M.reset}`);let i=Ts(e,s),a=[],c=0;for(;c<i.length;)if(i[c].type==="same")a.push({left:i[c].line,right:i[c].line,type:"same"}),c++;else if(i[c].type==="remove"){let h=[];for(;c<i.length&&i[c].type==="remove";)h.push(i[c].line),c++;let m=[];for(;c<i.length&&i[c].type==="add";)m.push(i[c].line),c++;let g=Math.max(h.length,m.length);for(let b=0;b<g;b++)a.push({left:b<h.length?h[b]:"",right:b<m.length?m[b]:"",type:"changed"})}else i[c].type==="add"&&(a.push({left:"",right:i[c].line,type:"changed"}),c++);let l=a.map((h,m)=>h.type!=="same"?m:-1).filter(h=>h>=0);if(l.length===0){console.log(` ${M.gray}(no changes)${M.reset}`);return}let u=Math.max(0,l[0]-2),d=Math.min(a.length,l[l.length-1]+3),f=(h,m)=>{let g=h.replace(/\x1b\[[0-9;]*m/g,"");return g.length>=m?h.substring(0,m):h+" ".repeat(m-g.length)};u>0&&console.log(` ${M.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${M.reset}`);for(let h=u;h<d;h++){let m=a[h];if(m.type==="same")console.log(` ${M.gray}${f(m.left,r)}${M.reset}\u2502${M.gray}${f(m.right,r)}${M.reset}`);else{let g=m.left?`${M.red}${f(m.left,r)}${M.reset}`:`${f("",r)}`,b=m.right?`${M.green}${f(m.right,r)}${M.reset}`:`${f("",r)}`;console.log(` ${g}\u2502${b}`)}}d<a.length&&console.log(` ${M.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${M.reset}`),console.log(` ${M.dim}${"\u2500".repeat(r)}\u2534${"\u2500".repeat(r)}${M.reset}
70
+ `)}function Xg(t,e,s,n={}){let o=n.label||"Update",r=n.context||3,i=n.annotations||[],a=Jo.isAbsolute(t)?Jo.relative(process.cwd(),t):t,c=Ts(e,s),l=1,u=1;for(let C of c)C.type==="same"?(C.oldLine=l++,C.newLine=u++):C.type==="remove"?(C.oldLine=l++,C.newLine=null):(C.oldLine=null,C.newLine=u++);let d=0,f=0;for(let C of c)C.type==="add"?d++:C.type==="remove"&&f++;if(console.log(`
71
+ ${M.green}\u23FA${M.reset} ${M.bold}${o}(${a})${M.reset}`),d===0&&f===0){console.log(` ${M.dim}\u23BF (no changes)${M.reset}
72
+ `);return}let h=[];if(d>0&&h.push(`Added ${d} line${d!==1?"s":""}`),f>0&&h.push(`removed ${f} line${f!==1?"s":""}`),i.length>0){let C=i.filter(V=>V.severity==="error").length,K=i.filter(V=>V.severity==="warn").length,Q=i.filter(V=>V.severity==="info").length,re=[];C>0&&re.push(`${M.red}${C} error${C!==1?"s":""}${M.dim}`),K>0&&re.push(`${M.yellow}${K} warning${K!==1?"s":""}${M.dim}`),Q>0&&re.push(`${M.cyan}${Q} info${Q!==1?"s":""}${M.dim}`),h.push(`found ${re.join(", ")}`)}console.log(` ${M.dim}\u23BF ${h.join(", ")}${M.reset}`);let g=[];c.forEach((C,K)=>{C.type!=="same"&&g.push(K)});let b=[],v=null,O=null;for(let C of g){let K=Math.max(0,C-r),Q=Math.min(c.length-1,C+r);v===null?(v=K,O=Q):(K<=O+1||(b.push([v,O]),v=K),O=Q)}v!==null&&b.push([v,O]);let U=" ",L=process.stdout.columns||120;function R(C,K,Q){let re=Q.replace(/\x1b\[[0-9;]*m/g,""),V=Q+" ".repeat(Math.max(0,L-re.length));return`${C}${K}${V}${M.reset}`}for(let C=0;C<b.length;C++){C>0&&console.log(`${U}${M.dim}\xB7\xB7\xB7${M.reset}`);let[K,Q]=b[C];for(let re=K;re<=Q;re++){let V=c[re],H=V.newLine!=null?V.newLine:V.oldLine,_=String(H).padStart(4),he=V.type!=="remove"?i.filter(de=>de.line===V.newLine):[];V.type==="remove"?console.log(R(Di.diff_rem_bg,M.red,`${U}${_} - ${V.line}`)):V.type==="add"?console.log(R(Di.diff_add_bg,M.green,`${U}${_} + ${V.line}`)):console.log(`${U}${M.dim}${_} ${M.reset}${V.line}`);for(let de of he){let me=M.cyan,ge="\u2139";de.severity==="error"?(me=M.red,ge="\u2716"):de.severity==="warn"&&(me=M.yellow,ge="\u26A0"),console.log(`${U} ${me}${ge} ${de.message}${M.reset}`)}}}console.log()}function Vg(t,e,s={}){let n=Jo.isAbsolute(t)?Jo.relative(process.cwd(),t):t,o=e.split(`
73
+ `),r=s.annotations||[];console.log(`
74
+ ${M.green}\u23FA${M.reset} ${M.bold}Create(${n})${M.reset}`);let i=[`${o.length} line${o.length!==1?"s":""}`];if(r.length>0){let d=r.filter(g=>g.severity==="error").length,f=r.filter(g=>g.severity==="warn").length,h=r.filter(g=>g.severity==="info").length,m=[];d>0&&m.push(`${M.red}${d} error${d!==1?"s":""}${M.dim}`),f>0&&m.push(`${M.yellow}${f} warning${f!==1?"s":""}${M.dim}`),h>0&&m.push(`${M.cyan}${h} info${h!==1?"s":""}${M.dim}`),i.push(`found ${m.join(", ")}`)}console.log(` ${M.dim}\u23BF ${i.join(", ")}${M.reset}`);let c=" ",l=process.stdout.columns||120,u=Math.min(o.length,20);for(let d=0;d<u;d++){let f=String(d+1).padStart(4),h=d+1,m=r.filter(O=>O.line===h),g=`${c}${f} + ${o[d]}`,b=g.replace(/\x1b\[[0-9;]*m/g,""),v=g+" ".repeat(Math.max(0,l-b.length));console.log(`${Di.diff_add_bg}${M.green}${v}${M.reset}`);for(let O of m){let U=M.cyan,L="\u2139";O.severity==="error"?(U=M.red,L="\u2716"):O.severity==="warn"&&(U=M.yellow,L="\u26A0"),console.log(`${c} ${U}${L} ${O.message}${M.reset}`)}}o.length>20&&console.log(`${c}${M.dim} ...+${o.length-20} more lines${M.reset}`),console.log()}Xl.exports={diffLines:Ts,showEditDiff:Hg,showWriteDiff:Gg,showNewFilePreview:Yg,confirmFileChange:Kg,showSideBySideDiff:zg,showClaudeDiff:Xg,showClaudeNewFile:Vg}});var er=se((Ek,Ql)=>{var Jl=require("util").promisify(require("child_process").exec),Jg=require("util").promisify(require("child_process").execFile),{C:Le}=Ue();async function qi(t){try{let{stdout:e}=await Jl(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function Zo(...t){try{let{stdout:e}=await Jg("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function Zg(){return await qi("git rev-parse --is-inside-work-tree")==="true"}async function Qg(){return await qi("git branch --show-current")}async function Fi(){try{let{stdout:t}=await Jl("git status --porcelain",{cwd:process.cwd(),timeout:3e4});return!t||!t.trim()?[]:t.split(`
75
+ `).filter(Boolean).map(e=>{let s=e.substring(0,2).trim(),n=e.substring(3);return{status:s,file:n}})}catch{return[]}}async function Qo(t=!1){return await qi(`git diff ${t?"--cached":""}`)||""}async function Bi(){return(await Fi()).map(e=>e.file)}async function Zl(){let t=await Bi();if(t.length===0)return null;let e=await Qo(),n=await Qo(!0)||e,o=0,r=0;if(n){let u=n.split(`
76
+ `);for(let d of u)d.startsWith("+")&&!d.startsWith("+++")&&o++,d.startsWith("-")&&!d.startsWith("---")&&r++}else o=t.length;let i="chore",a=t.join(" ").toLowerCase();a.includes("test")?i="test":a.includes("readme")||a.includes("doc")?i="docs":o>r*2?i="feat":r>o?i="refactor":i="fix";let c=t.slice(0,3).map(u=>u.split("/").pop());return{summary:`${i}: update ${c.join(", ")}${t.length>3?` (+${t.length-3} more)`:""}`,type:i,files:t,stats:{additions:o,deletions:r}}}async function ey(t){let s=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await Zo("checkout","-b",s)!==null?s:null}async function ty(t){return await Zo("add","-A"),await Zo("commit","-m",t)?await Zo("rev-parse","--short","HEAD"):null}async function ny(){let t=await Zl();if(!t)return`${Le.dim}No changes${Le.reset}`;let e=[];e.push(`
77
+ ${Le.bold}${Le.cyan}Git Diff Summary:${Le.reset}`),e.push(` ${Le.green}+${t.stats.additions}${Le.reset} ${Le.red}-${t.stats.deletions}${Le.reset} in ${t.files.length} file(s)`),e.push(`
78
+ ${Le.bold}${Le.cyan}Files:${Le.reset}`);for(let s of t.files.slice(0,20))e.push(` ${Le.dim}${s}${Le.reset}`);return t.files.length>20&&e.push(` ${Le.dim}...+${t.files.length-20} more${Le.reset}`),e.push(`
79
+ ${Le.bold}${Le.cyan}Suggested message:${Le.reset}`),e.push(` ${Le.cyan}${t.summary}${Le.reset}
80
+ `),e.join(`
81
+ `)}async function sy(){return(await Fi()).filter(e=>e.status==="UU"||e.status==="AA"||e.status==="DD")}async function oy(){let t=await Bi();if(t.length===0)return"";let e=[`CHANGED FILES (${t.length}):`];for(let n of t.slice(0,10))e.push(` ${n}`);let s=await Qo();if(s){let n=s.length>5e3?s.substring(0,5e3)+`
82
+ ...(truncated)`:s;e.push(`
83
+ DIFF:
84
+ ${n}`)}return e.join(`
85
+ `)}Ql.exports={isGitRepo:Zg,getCurrentBranch:Qg,getStatus:Fi,getDiff:Qo,getChangedFiles:Bi,analyzeDiff:Zl,createBranch:ey,commit:ty,formatDiffSummary:ny,getDiffContext:oy,getMergeConflicts:sy}});var iu=se((Rk,ru)=>{var Ge=require("fs").promises,Tk=require("fs"),gt=require("path"),ry=require("crypto"),{execSync:Rs}=require("child_process"),iy=100*1024,nu=50,nt=[],Vn=[];function ay(t,e,s,n){for(nt.push({tool:t,filePath:e,oldContent:s,newContent:n,timestamp:Date.now()});nt.length>nu;)nt.shift();Vn.length=0,su(nt[nt.length-1]).catch(()=>{})}async function cy(){if(nt.length===0)return null;let t=nt.pop();if(t.oldContent===null)try{await Ge.unlink(t.filePath)}catch{}else await Ge.writeFile(t.filePath,t.oldContent,"utf-8");return Vn.push(t),{tool:t.tool,filePath:t.filePath,wasCreated:t.oldContent===null}}async function ly(){if(Vn.length===0)return null;let t=Vn.pop();return await Ge.writeFile(t.filePath,t.newContent,"utf-8"),nt.push(t),{tool:t.tool,filePath:t.filePath}}function uy(t=10){return nt.slice(-t).reverse().map(e=>({tool:e.tool,filePath:e.filePath,timestamp:e.timestamp}))}function dy(){return nt.length}function fy(){return Vn.length}function py({diskToo:t=!0}={}){if(nt.length=0,Vn.length=0,t){let e=nr();Ge.readdir(e).then(s=>{for(let n of s)n.endsWith(".json")&&Ge.unlink(gt.join(e,n)).catch(()=>{})}).catch(()=>{})}}function nr(){return gt.join(process.cwd(),".nex","history")}async function eu(t,e){if(t==null)return{inline:!0,content:t};if(Buffer.byteLength(t,"utf-8")<=iy)return{inline:!0,content:t};let s=ry.createHash("sha256").update(t,"utf-8").digest("hex"),n=gt.join(e,"blobs");return await Ge.mkdir(n,{recursive:!0}),await Ge.writeFile(gt.join(n,s),t,"utf-8"),{inline:!1,hash:s}}async function su(t){let e=nr();await Ge.mkdir(e,{recursive:!0});let s=gt.basename(t.filePath).replace(/[^a-zA-Z0-9]/g,"-"),n=`${t.timestamp}-${s}.json`,o=await eu(t.oldContent,e),r=await eu(t.newContent,e),i={tool:t.tool,filePath:t.filePath,timestamp:t.timestamp,oldContent:o.inline?{inline:!0,content:o.content}:{inline:!1,hash:o.hash},newContent:r.inline?{inline:!0,content:r.content}:{inline:!1,hash:r.hash}};await Ge.writeFile(gt.join(e,n),JSON.stringify(i),"utf-8")}async function tu(t,e){if(!t)return null;if(t.inline)return t.content;let s=gt.join(e,"blobs",t.hash);return Ge.readFile(s,"utf-8")}async function hy(){let t=nr(),e;try{e=await Ge.readdir(t)}catch{return 0}let s=e.filter(o=>o.endsWith(".json")).sort(),n=0;for(let o of s)try{let r=await Ge.readFile(gt.join(t,o),"utf-8"),i=JSON.parse(r),a=await tu(i.oldContent,t),c=await tu(i.newContent,t);nt.push({tool:i.tool,filePath:i.filePath,timestamp:i.timestamp,oldContent:a,newContent:c}),n++}catch{}for(;nt.length>nu;)nt.shift();return n}async function my(t=7){let e=nr(),s;try{s=await Ge.readdir(e)}catch{return 0}let n=Date.now()-t*24*60*60*1e3,o=s.filter(l=>l.endsWith(".json")),r=0,i=new Set,a=[];for(let l of o)try{let u=await Ge.readFile(gt.join(e,l),"utf-8"),d=JSON.parse(u);d.timestamp<n?(a.push(l),r++):(d.oldContent&&!d.oldContent.inline&&d.oldContent.hash&&i.add(d.oldContent.hash),d.newContent&&!d.newContent.inline&&d.newContent.hash&&i.add(d.newContent.hash))}catch{}for(let l of a)try{await Ge.unlink(gt.join(e,l))}catch{}let c=gt.join(e,"blobs");try{let l=await Ge.readdir(c);for(let u of l)if(!i.has(u))try{await Ge.unlink(gt.join(c,u))}catch{}}catch{}return r}var tr="nex-snapshot";function gy(t,e=process.cwd()){let s=t?`${tr}-${t.replace(/[^a-zA-Z0-9_-]/g,"-")}`:`${tr}-${Date.now()}`;try{return Rs("git status --porcelain",{cwd:e,timeout:1e4}).toString().trim()?(Rs(`git stash push -u -m "${s}"`,{cwd:e,timeout:15e3}),Rs("git stash pop",{cwd:e,timeout:1e4}),{name:s,label:s,ok:!0}):{name:s,label:s,ok:!1,error:"No changes to snapshot (working tree clean)"}}catch(n){return{name:s,label:s,ok:!1,error:n.message}}}function ou(t=process.cwd()){try{let e=Rs("git stash list",{cwd:t,timeout:1e4}).toString().trim();return e?e.split(`
86
+ `).map(s=>{let n=s.match(/^stash@\{(\d+)\}:\s+(?:WIP on [^:]+:\s+\S+\s+|On \S+:\s+)(.*)/);if(!n)return null;let o=n[2].trim();return o.startsWith(tr)?{index:parseInt(n[1],10),label:o,shortName:o.replace(`${tr}-`,""),date:s}:null}).filter(Boolean):[]}catch{return[]}}function yy(t,e=process.cwd()){try{let s=ou(e);if(s.length===0)return{ok:!1,error:"No snapshots found"};let n;return t===void 0||t==="last"?n=s[0]:typeof t=="number"?n=s.find(o=>o.index===t):n=s.find(o=>o.label===t||o.shortName===t||o.shortName.includes(String(t))),n?(Rs(`git stash apply stash@{${n.index}}`,{cwd:e,timeout:15e3}),{ok:!0,label:n.label}):{ok:!1,error:`Snapshot not found: ${t}`}}catch(s){return{ok:!1,error:s.message}}}ru.exports={recordChange:ay,undo:cy,redo:ly,getHistory:uy,getUndoCount:dy,getRedoCount:fy,clearHistory:py,persistEntry:su,loadPersistedHistory:hy,pruneHistory:my,createSnapshot:gy,listSnapshots:ou,restoreSnapshot:yy}});var Yi=se((Ck,fu)=>{var Ae=require("fs"),st=require("path"),{atomicWrite:$y,withFileLockSync:wy}=fn(),Qe=[];function Cs(){return st.join(process.cwd(),".nex","skills")}function au(){return st.join(process.cwd(),".nex","config.json")}function cu(){let t=Cs();return Ae.existsSync(t)||Ae.mkdirSync(t,{recursive:!0}),t}function Hi(){let t=au();if(!Ae.existsSync(t))return[];try{let e=JSON.parse(Ae.readFileSync(t,"utf-8"));return e.skills&&Array.isArray(e.skills.disabled)?e.skills.disabled:[]}catch{return[]}}function lu(t){let e=au(),s=st.dirname(e);Ae.existsSync(s)||Ae.mkdirSync(s,{recursive:!0}),wy(e,()=>{let n={};if(Ae.existsSync(e))try{n=JSON.parse(Ae.readFileSync(e,"utf-8"))}catch{n={}}n.skills||(n.skills={}),n.skills.disabled=t,$y(e,JSON.stringify(n,null,2))})}function uu(t,e){let s=[];if(typeof t!="object"||t===null)return{valid:!1,errors:["Module must export an object"]};if(t.name!==void 0&&typeof t.name!="string"&&s.push("name must be a string"),t.description!==void 0&&typeof t.description!="string"&&s.push("description must be a string"),t.instructions!==void 0&&typeof t.instructions!="string"&&s.push("instructions must be a string"),t.commands!==void 0)if(!Array.isArray(t.commands))s.push("commands must be an array");else for(let n=0;n<t.commands.length;n++){let o=t.commands[n];(!o.cmd||typeof o.cmd!="string")&&s.push(`commands[${n}].cmd must be a non-empty string`),o.handler!==void 0&&typeof o.handler!="function"&&s.push(`commands[${n}].handler must be a function`)}if(t.tools!==void 0)if(!Array.isArray(t.tools))s.push("tools must be an array");else for(let n=0;n<t.tools.length;n++){let o=t.tools[n];(!o.function||!o.function.name||typeof o.function.name!="string")&&s.push(`tools[${n}].function.name must be a non-empty string`),o.execute!==void 0&&typeof o.execute!="function"&&s.push(`tools[${n}].execute must be a function`)}return{valid:s.length===0,errors:s}}function du(t){let e=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(!e)return{triggers:[],body:t};let s=e[1],n=e[2].trim(),o=[],r=!1;for(let i of s.split(`
87
+ `)){let a=i.trim();if(/^trigger:\s*$/i.test(a)){r=!0;continue}r&&a.startsWith("- ")?o.push(a.slice(2).trim().replace(/^["']|["']$/g,"")):r&&a&&!a.startsWith("#")&&(r=!1)}return{triggers:o,body:n}}function Wi(t){try{let e=Ae.readFileSync(t,"utf-8").trim();if(!e)return null;let s=st.basename(t,".md"),{triggers:n,body:o}=du(e);return{name:s,type:"prompt",filePath:t,instructions:o||e,triggers:n,commands:[],tools:[]}}catch{return null}}function Ui(t){try{let e=require(t),{valid:s,errors:n}=uu(e,t);return s?{name:e.name||st.basename(t,".js"),type:"script",filePath:t,description:e.description||"",instructions:e.instructions||"",commands:(e.commands||[]).map(r=>({cmd:r.cmd.startsWith("/")?r.cmd:`/${r.cmd}`,desc:r.desc||r.description||"",handler:r.handler||null})),tools:(e.tools||[]).map(r=>({type:r.type||"function",function:{name:r.function.name,description:r.function.description||"",parameters:r.function.parameters||{type:"object",properties:{}}},execute:r.execute||null}))}:(console.error(`Skill validation failed: ${t}
88
+ ${n.join(`
89
+ `)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function Gi(){Qe=[];let t=Hi(),e=Cs(),s=[];if(Ae.existsSync(e))try{s=Ae.readdirSync(e)}catch{s=[]}for(let o of s){let r=st.join(e,o),i;try{i=Ae.statSync(r)}catch{continue}if(!i.isFile())continue;let a=null;o.endsWith(".md")?a=Wi(r):o.endsWith(".js")&&(a=Ui(r)),a&&(a.enabled=!t.includes(a.name),Qe.push(a))}let n=st.join(__dirname,"skills");if(!process.env.NEX_SKIP_BUILTIN_SKILLS&&Ae.existsSync(n)){let o;try{o=Ae.readdirSync(n).filter(r=>r.endsWith(".md")||r.endsWith(".js"))}catch{o=[]}for(let r of o){let i=st.join(n,r),a=st.basename(r,st.extname(r));if(Qe.some(u=>u.name===a))continue;let c;try{c=Ae.statSync(i)}catch{continue}if(!c.isFile())continue;let l=r.endsWith(".md")?Wi(i):Ui(i);l&&(l._builtin=!0,l.enabled=!t.includes(l.name),Qe.push(l))}}return Qe}function by(){let t=[];for(let e of Qe)!e.enabled||!e.instructions||t.push(`[Skill: ${e.name}]
90
+ ${e.instructions}`);return t.length===0?"":`SKILL INSTRUCTIONS:
91
+ ${t.join(`
92
+
93
+ `)}`}function _y(){let t=[];for(let e of Qe)if(e.enabled)for(let s of e.commands)t.push({cmd:s.cmd,desc:s.desc||`[skill: ${e.name}]`});return t}function xy(){let t=[];for(let e of Qe)if(e.enabled)for(let s of e.tools)t.push({type:"function",function:{name:`skill_${s.function.name}`,description:`[Skill:${e.name}] ${s.function.description}`,parameters:s.function.parameters}});return t}async function ky(t,e){if(!t.startsWith("skill_"))return null;let s=t.substring(6);for(let n of Qe)if(n.enabled){for(let o of n.tools)if(o.function.name===s&&o.execute)try{let r=await o.execute(e);return typeof r=="string"?r:JSON.stringify(r)}catch(r){return`ERROR: Skill tool '${s}' failed: ${r.message}`}}return`ERROR: Skill tool '${s}' not found`}function vy(t){let[e,...s]=t.split(/\s+/),n=s.join(" ").trim();for(let o of Qe)if(o.enabled){for(let r of o.commands)if(r.cmd===e&&r.handler){try{let i=r.handler(n);if(typeof i=="string"&&i.length>0)return{handled:!0,agentPrompt:i}}catch(i){console.error(`Skill command error (${e}): ${i.message}`)}return{handled:!0}}}return!1}function Sy(){return Qe.map(t=>({name:t.name,type:t.type,enabled:t.enabled,description:t.description||"",commands:t.commands.length,tools:t.tools.length,filePath:t.filePath}))}function Ey(t){let e=Qe.find(n=>n.name===t);if(!e)return!1;e.enabled=!0;let s=Hi().filter(n=>n!==t);return lu(s),!0}function Ty(t){let e=Qe.find(n=>n.name===t);if(!e)return!1;e.enabled=!1;let s=Hi();return s.includes(t)||(s.push(t),lu(s)),!0}function Ry(){return Qe}async function Cy(t,e={}){let{execSync:s}=require("child_process"),n=cu(),o=t;/^[\w-]+\/[\w.-]+$/.test(t)&&(o=`https://github.com/${t}.git`);let r=e.name||st.basename(o,".git").replace(/^nex-skill-/,""),i=st.join(n,r);if(Ae.existsSync(i))return{ok:!1,name:r,error:`Skill "${r}" is already installed at ${i}. Remove it first to reinstall.`};try{if(!/^https?:\/\/[a-zA-Z0-9._\-/:@#?=&%+~]+$/.test(o))throw new Error(`Invalid git URL: ${o}`);let u=i.replace(/'/g,"'\\''");s(`git clone --depth 1 '${o}' '${u}'`,{timeout:3e4,stdio:"pipe"})}catch(u){return{ok:!1,name:r,error:`Git clone failed: ${u.stderr?.toString().trim()||u.message}`}}let a=st.join(i,"skill.json"),c=Ae.existsSync(a),l=Ae.readdirSync(i).some(u=>(u.endsWith(".md")||u.endsWith(".js"))&&!u.startsWith("."));if(!c&&!l){try{Ae.rmSync(i,{recursive:!0,force:!0})}catch{}return{ok:!1,name:r,error:"No skill.json manifest or .md/.js skill file found in repository"}}if(c)try{let u=JSON.parse(Ae.readFileSync(a,"utf-8"));u.name||(u.name=r)}catch{try{Ae.rmSync(i,{recursive:!0,force:!0})}catch{}return{ok:!1,name:r,error:"Invalid skill.json \u2014 not valid JSON"}}return Gi(),{ok:!0,name:r}}async function Ay(t){let e=require("axios");try{let s=encodeURIComponent(`nex-skill ${t} OR nex-code-skill ${t}`);return((await e.get(`https://api.github.com/search/repositories?q=${s}&sort=stars&per_page=10`,{timeout:1e4,headers:{Accept:"application/vnd.github.v3+json"}})).data.items||[]).map(o=>({name:o.name.replace(/^nex-skill-/,""),description:o.description||"(no description)",url:o.clone_url,stars:o.stargazers_count,owner:o.owner.login}))}catch(s){return[{name:"error",description:`Search failed: ${s.message}`,url:"",stars:0,owner:""}]}}function Oy(t){let e=st.join(Cs(),t);if(!Ae.existsSync(e))return{ok:!1,error:`Skill "${t}" not found in ${Cs()}`};try{return Ae.rmSync(e,{recursive:!0,force:!0}),Gi(),{ok:!0}}catch(s){return{ok:!1,error:s.message}}}function Ny(t){if(!t)return[];let e=t.toLowerCase(),s=[];for(let n of Qe){if(!n.enabled||!n.triggers||n.triggers.length===0)continue;if(n.triggers.some(r=>e.includes(r.toLowerCase()))){let r=(n.instructions||"").split(`
94
+ `).slice(0,3).join(`
95
+ `);s.push({name:n.name,instructions:r})}}return s}fu.exports={initSkillsDir:cu,loadAllSkills:Gi,getSkillInstructions:by,getSkillCommands:_y,getSkillToolDefinitions:xy,routeSkillCall:ky,handleSkillCommand:vy,listSkills:Sy,enableSkill:Ey,disableSkill:Ty,getLoadedSkills:Ry,installSkill:Cy,searchSkills:Ay,removeSkill:Oy,matchSkillTriggers:Ny,_getSkillsDir:Cs,_validateScriptSkill:uu,_loadMarkdownSkill:Wi,_loadScriptSkill:Ui,_parseFrontmatter:du}});var zi=se((Ak,$u)=>{var{spawn:My}=require("child_process"),Ly=require("path"),pu=require("fs"),Ut=new Map;function Py(){return Ly.join(process.cwd(),".nex","config.json")}function Ki(){let t=Py();if(!pu.existsSync(t))return{};try{return JSON.parse(pu.readFileSync(t,"utf-8")).mcpServers||{}}catch{return{}}}function sr(t,e,s={},n=1e4){return new Promise((o,r)=>{let i=`${Date.now()}-${Math.random().toString(36).slice(2,6)}`,a=JSON.stringify({jsonrpc:"2.0",id:i,method:e,params:s})+`
96
+ `,c="",l=setTimeout(()=>{d(),r(new Error(`MCP request timeout: ${e}`))},n);function u(f){c+=f.toString();let h=c.split(`
97
+ `);for(let m of h)if(m.trim())try{let g=JSON.parse(m);if(g.id===i){d(),g.error?r(new Error(`MCP error: ${g.error.message||JSON.stringify(g.error)}`)):o(g.result);return}}catch{}c=h[h.length-1]||""}function d(){clearTimeout(l),t.stdout.removeListener("data",u)}t.stdout.on("data",u);try{t.stdin.write(a)}catch(f){d(),r(new Error(`MCP write failed: ${f.message}`))}})}async function hu(t,e){if(Ut.has(t))return Ut.get(t);let s=["PATH","HOME","USER","SHELL","LANG","TERM","NODE_ENV"],n={};for(let i of s)process.env[i]&&(n[i]=process.env[i]);let o=My(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:{...n,...e.env||{}}}),r={name:t,proc:o,tools:[],config:e};try{await sr(o,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.2.0"}});let i=await sr(o,"tools/list",{});return r.tools=i&&i.tools||[],Ut.set(t,r),r}catch(i){throw o.kill(),new Error(`Failed to connect MCP server '${t}': ${i.message}`)}}function mu(t){let e=Ut.get(t);if(!e)return!1;try{e.proc.kill()}catch{}return Ut.delete(t),!0}function Iy(){for(let[t]of Ut)mu(t)}async function gu(t,e,s={}){let n=Ut.get(t);if(!n)throw new Error(`MCP server not connected: ${t}`);let o=await sr(n.proc,"tools/call",{name:e,arguments:s});return o&&Array.isArray(o.content)?o.content.filter(r=>r.type==="text").map(r=>r.text).join(`
98
+ `):JSON.stringify(o)}function yu(){let t=[];for(let[e,s]of Ut)for(let n of s.tools)t.push({server:e,name:n.name,description:n.description||"",inputSchema:n.inputSchema||{type:"object",properties:{}}});return t}function jy(){return yu().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function Dy(t,e){if(!t.startsWith("mcp_"))return null;let s=t.substring(4).split("_");if(s.length<2)return null;let n=s[0],o=s.slice(1).join("_");return gu(n,o,e)}function qy(){let t=Ki();return Object.entries(t).map(([e,s])=>{let n=Ut.get(e);return{name:e,command:s.command,connected:!!n,toolCount:n?n.tools.length:0}})}async function Fy(){let t=Ki(),e=[];for(let[s,n]of Object.entries(t))try{let o=await hu(s,n);e.push({name:s,tools:o.tools.length})}catch(o){e.push({name:s,tools:0,error:o.message})}return e}$u.exports={loadMCPConfig:Ki,sendRequest:sr,connectServer:hu,disconnectServer:mu,disconnectAll:Iy,callTool:gu,getAllTools:yu,getMCPToolDefinitions:jy,routeMCPCall:Dy,listServers:qy,connectAll:Fy}});var rr=se((Ok,xu)=>{var wu=require("fs"),Xi=require("path"),or=[],As=[],hn={},Os=["onToolResult","onModelResponse","onSessionStart","onSessionEnd","onFileChange","beforeToolExec","afterToolExec"];function bu(t,e){if(!t||!t.function||!t.function.name)return{ok:!1,error:"Tool definition must have function.name"};if(typeof e!="function")return{ok:!1,error:"Handler must be a function"};let s=t.function.name;return As.some(n=>n.definition.function.name===s)?{ok:!1,error:`Tool "${s}" is already registered`}:(As.push({definition:{type:"function",...t},handler:e}),{ok:!0})}function _u(t,e){return Os.includes(t)?typeof e!="function"?{ok:!1,error:"Handler must be a function"}:(hn[t]||(hn[t]=[]),hn[t].push(e),{ok:!0}):{ok:!1,error:`Unknown event "${t}". Available: ${Os.join(", ")}`}}async function Vi(t,e){let s=hn[t]||[],n=e;for(let o of s)try{let r=await o(n);r!==void 0&&(n=r)}catch(r){process.env.NEX_DEBUG&&console.error(`[plugin] Hook error on ${t}: ${r.message}`)}return n}function By(){let t=Xi.join(process.cwd(),".nex","plugins"),e=[];if(!wu.existsSync(t))return{loaded:0,errors:[]};let s=wu.readdirSync(t).filter(o=>o.endsWith(".js")),n={registerTool:bu,registerHook:_u,EVENTS:Os};for(let o of s){let r=Xi.join(t,o);try{let i=require(r);if(typeof i=="function")i(n);else if(typeof i.setup=="function")i.setup(n);else{e.push(`${o}: Plugin must export a function or { setup: function }`);continue}or.push({name:i.name||Xi.basename(o,".js"),filePath:r})}catch(i){e.push(`${o}: ${i.message}`)}}return{loaded:or.length,errors:e}}function Wy(){return As.map(t=>t.definition)}async function Uy(t,e,s={}){let n=As.find(a=>a.definition.function.name===t);if(!n)return null;let o=await Vi("beforeToolExec",{name:t,args:e,options:s}),r=await n.handler(o.args||e,s);return(await Vi("afterToolExec",{name:t,args:e,result:r})).result||r}function Hy(){return[...or]}function Gy(){let t={};for(let e of Os)t[e]=(hn[e]||[]).length;return t}function Yy(){or.length=0,As.length=0;for(let t of Object.keys(hn))delete hn[t]}xu.exports={registerTool:bu,registerHook:_u,emit:Vi,loadPlugins:By,getPluginToolDefinitions:Wy,executePluginTool:Uy,getLoadedPlugins:Hy,getHookCounts:Gy,clearPlugins:Yy,EVENTS:Os}});var Ji=se((Nk,Eu)=>{var{getSkillToolDefinitions:Ky}=Yi(),{getMCPToolDefinitions:zy}=zi(),{getPluginToolDefinitions:Xy}=rr(),ir=new Map;function ku(){let{TOOL_DEFINITIONS:t}=Jn();return[...t,...Ky(),...zy(),...Xy()]}function vu(t){if(ir.has(t))return ir.get(t);let s=ku().find(o=>o.function.name===t);if(!s)return null;let n=s.function.parameters;return ir.set(t,n),n}function Vy(){ir.clear()}function ar(t,e){if(!t||e.length===0)return null;let s=null,n=1/0;for(let o of e){let r=Su(t.toLowerCase(),o.toLowerCase());r<n&&(n=r,s=o)}return n<=Math.ceil(t.length/2)?s:null}function Su(t,e){let s=t.length,n=e.length,o=Array.from({length:s+1},()=>Array(n+1).fill(0));for(let r=0;r<=s;r++)o[r][0]=r;for(let r=0;r<=n;r++)o[0][r]=r;for(let r=1;r<=s;r++)for(let i=1;i<=n;i++)o[r][i]=t[r-1]===e[i-1]?o[r-1][i-1]:1+Math.min(o[r-1][i],o[r][i-1],o[r-1][i-1]);return o[s][n]}function Jy(t,e){let s=vu(t);if(s===null){let d=ku().map(h=>h.function.name),f=ar(t,d);return{valid:!1,error:`Unknown tool "${t}".${f?` Did you mean "${f}"?`:""}
99
+ Available tools: ${d.join(", ")}`}}if(!s||!s.properties)return{valid:!0};let n=s.required||[],o=Object.keys(s.properties),r=Object.keys(e),i=[],a={...e},c=!1;for(let u of n)if(!(u in e)||e[u]===void 0||e[u]===null){let d=ar(u,r);d&&!o.includes(d)?(a[u]=e[d],delete a[d],c=!0):i.push(`Missing required parameter "${u}" (${s.properties[u]?.description||s.properties[u]?.type||"unknown"})`)}new Set(["grep","grep_search","search_files"]).has(t)&&(("-n"in a||"n"in a)&&!o.includes("-n")&&(delete a["-n"],delete a.n,c=!0),("-i"in a||"--ignore-case"in a)&&"ignore_case"in(s.properties||{})&&(a.ignore_case=!0,delete a["-i"],delete a["--ignore-case"],c=!0),("-r"in a||"--recursive"in a)&&(delete a["-r"],delete a["--recursive"],c=!0)),t==="read_file"&&("offset"in a&&!("line_start"in a)&&(a.line_start=a.offset,delete a.offset,c=!0),"start_line"in a&&!("line_start"in a)&&(a.line_start=a.start_line,delete a.start_line,c=!0),"end_line"in a&&!("line_end"in a)&&(a.line_end=a.end_line,delete a.end_line,c=!0));for(let u of Object.keys(a))if(!o.includes(u)){let d=ar(u,o);if(d&&!(d in a))a[d]=a[u],delete a[u],c=!0;else if(!c){let f=d?` Did you mean "${d}"?`:"";i.push(`Unknown parameter "${u}".${f}`)}}for(let u of Object.keys(a)){if(!s.properties[u])continue;let d=s.properties[u].type,f=typeof a[u];d==="string"&&f==="number"?(a[u]=String(a[u]),c=!0):d==="number"&&f==="string"&&!isNaN(a[u])?(a[u]=Number(a[u]),c=!0):d==="boolean"&&f==="string"&&(a[u]=a[u]==="true",c=!0)}return i.length>0&&!c?{valid:!1,error:`Tool "${t}" argument errors:
100
+ `+i.map(u=>` - ${u}`).join(`
101
+ `)+`
102
+
103
+ Expected parameters: ${JSON.stringify(s.properties,null,2)}`}:{valid:!0,corrected:c?a:null}}function Zy(t,e){let s=[],n={...t};if(!n.function&&!n.name)return s.push('Tool call missing both "function" and "name" fields'),{valid:!1,normalized:n,errors:s};if(!n.function&&n.name&&(n.function={name:n.name,arguments:n.arguments||n.args||{}},delete n.name,delete n.args),n.function&&n.function.args!==void 0&&n.function.arguments===void 0&&(n.function.arguments=n.function.args,delete n.function.args),n.function&&(n.function.arguments===void 0||n.function.arguments===null)&&(n.function.arguments={}),n.function&&typeof n.function.arguments=="string"){let o=n.function.arguments;if(o.trim()==="")n.function.arguments={};else try{n.function.arguments=JSON.parse(o)}catch(r){return s.push(`Invalid JSON in arguments${e?` (${e})`:""}: ${r.message}`),{valid:!1,normalized:n,errors:s}}}return n.function&&typeof n.function.arguments!="object"?(s.push(`Arguments must be an object, got ${typeof n.function.arguments}`),{valid:!1,normalized:n,errors:s}):!n.function.name||typeof n.function.name!="string"?(s.push("Tool call function name must be a non-empty string"),{valid:!1,normalized:n,errors:s}):{valid:s.length===0,normalized:n,errors:s}}Eu.exports={validateToolArgs:Jy,validateToolCallFormat:Zy,closestMatch:ar,levenshtein:Su,getCachedSchema:vu,clearSchemaCache:Vy}});var Au=se((Mk,Cu)=>{var{levenshtein:cr}=Ji(),Qy=200,e$=.3,t$=2;function Zi(t){return t.replace(/\r\n/g,`
104
+ `).replace(/\r/g,`
105
+ `).replace(/\t/g," ".repeat(t$)).split(`
106
+ `).map(e=>{let s=e.replace(/\s+$/,""),n=s.match(/^(\s*)(.*)/);if(!n)return s;let[,o,r]=n;return o+r.replace(/ {2,}/g," ")}).join(`
107
+ `)}function n$(t,e){if(t.includes(e))return e;if(e.length<10)return null;let s=Zi(t),n=Zi(e);if(!s.includes(n))return null;let o=t.split(`
108
+ `),r=s.split(`
109
+ `),i=n.split(`
110
+ `),a=i[0],c=i[i.length-1];for(let l=0;l<=r.length-i.length;l++){let u=!0;for(let d=0;d<i.length;d++)if(r[l+d]!==i[d]){u=!1;break}if(u)return o.slice(l,l+i.length).join(`
111
+ `)}if(i.length===1){for(let l=0;l<r.length;l++)if(r[l].indexOf(n)!==-1)return o[l]}return null}function s$(t,e){if(!t||!e)return null;let s=t.split(`
112
+ `),o=e.split(`
113
+ `).length;return s.length===0||o===0?null:o===1?o$(s,e):i$(s,e,o)}function Tu(t){return Math.max(1,Math.floor(t/Qy))}function Ru(t,e){return t<=Math.ceil(e*e$)}function o$(t,e){let s=e.trim(),n=Tu(t.length),o=null,r=1/0;for(let i=0;i<t.length;i+=n){let a=t[i];if(!a.trim())continue;let c=cr(a.trim(),s);c<r&&(r=c,o={text:a,distance:c,line:i+1})}return o&&n>1&&(o=r$(t,s,o,n)||o,r=o.distance),Ru(r,e.length)?o:null}function r$(t,e,s,n){let o=s.line-1,r=Math.max(0,o-n),i=Math.min(t.length-1,o+n),a=s.distance,c=null;for(let l=r;l<=i;l++){let u=t[l];if(!u.trim())continue;let d=cr(u.trim(),e);d<a&&(a=d,c={text:u,distance:d,line:l+1})}return c}function i$(t,e,s){let n=t.length-s+1;if(n<=0)return null;let o=Tu(n),r=null,i=1/0;for(let a=0;a<n;a+=o){let c=t.slice(a,a+s).join(`
114
+ `),l=cr(c,e);l<i&&(i=l,r={text:c,distance:l,line:a+1})}return r&&o>1&&(r=a$(t,e,r,o,s,n)||r,i=r.distance),Ru(i,e.length)?r:null}function a$(t,e,s,n,o,r){let i=s.line-1,a=Math.max(0,i-n),c=Math.min(r-1,i+n),l=s.distance,u=null;for(let d=a;d<=c;d++){let f=t.slice(d,d+o).join(`
115
+ `),h=cr(f,e);h<l&&(l=h,u={text:f,distance:h,line:d+1})}return u}Cu.exports={normalizeWhitespace:Zi,fuzzyFindText:n$,findMostSimilar:s$}});var Nu=se((Pk,Ou)=>{var{C:Lk}=Ue(),c$=[{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}],l$=[{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 u$(t,e){let s=e.split(`
116
+ `),n=[],o=t?`.${t.split(".").pop()}`:"";for(let r=0;r<s.length;r++){let i=s[r],a=r+1;for(let c of c$)c.regex.test(i)&&n.push({line:a,message:`Potential secret detected: ${c.name}`,severity:"error"});for(let c of l$)c.ext&&!c.ext.includes(o)||c.regex.test(i)&&n.push({line:a,message:c.message||`Found ${c.name}`,severity:c.severity||"warn"})}return s.length>500&&n.push({line:0,message:`Large file detected (${s.length} lines). Consider refactoring.`,severity:"info"}),n}function d$(){let t=process.memoryUsage();return{rss:Math.round(t.rss/1024/1024*100)/100,heapUsed:Math.round(t.heapUsed/1024/1024*100)/100}}Ou.exports={runDiagnostics:u$,getMemoryUsage:d$}});var sa=se((Ik,Du)=>{var Zn=require("fs").promises,Qn=require("path"),{exec:f$}=require("util").promisify(require("child_process").exec),es=[],na=null,lr=!1,ea=0,p$=6e4;function Lu(t){return!(es.length===0||na!==t||Date.now()-ea>p$)}async function Pu(t){if(!lr&&!Lu(t)){lr=!0,na=t;try{try{let{stdout:n}=await f$("rg --files",{cwd:t,timeout:5e3});es=n.split(`
117
+ `).filter(Boolean),ea=Date.now(),lr=!1;return}catch{}let e=[],s=async(n,o)=>{let r;try{r=await Zn.readdir(n,{withFileTypes:!0})}catch{return}for(let i of r){if(i.name==="node_modules"||i.name===".git"||i.name.startsWith("."))continue;let a=o?`${o}/${i.name}`:i.name;i.isDirectory()?await s(Qn.join(n,i.name),a):e.push(a)}};await s(t,""),es=e,ea=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{lr=!1}}}function ta(){return es}function h$(){return na}function m$(t){return es.filter(e=>Qn.basename(e)===t)}function g$(t){let e=t.toLowerCase();return es.filter(s=>s.toLowerCase().includes(e)).slice(0,20)}var Qi=null,Mu=0,y$=12e4,$$=new Set([".js",".ts",".jsx",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".rb"]);function Iu(t,e){let s=[],n=t.split(`
118
+ `);for(let o=0;o<n.length;o++){let r=n[o],i=o+1;if([".js",".ts",".jsx",".tsx",".mjs",".cjs"].includes(e)){let a=r.match(/(?:export\s+)?(?:async\s+)?function\s+(\w+)/);a&&s.push({type:"function",name:a[1],line:i});let c=r.match(/(?:export\s+)?class\s+(\w+)/);c&&s.push({type:"class",name:c[1],line:i});let l=r.match(/(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?(?:\([^)]*\)|[\w$]+)\s*=>/);l&&s.push({type:"function",name:l[1],line:i});let u=r.match(/module\.exports\s*=\s*\{([^}]+)\}/);if(u){let f=u[1].split(",").map(h=>h.trim().split(":")[0].trim()).filter(Boolean);for(let h of f)/^\w+$/.test(h)&&s.push({type:"export",name:h,line:i})}let d=r.match(/(?:require\(['"]([^'"]+)['"]\)|from\s+['"]([^'"]+)['"])/);if(d){let f=d[1]||d[2];s.push({type:"import",name:f,line:i})}}if(e===".py"){let a=r.match(/^(?:async\s+)?def\s+(\w+)/);a&&s.push({type:"function",name:a[1],line:i});let c=r.match(/^class\s+(\w+)/);c&&s.push({type:"class",name:c[1],line:i});let l=r.match(/^(?:from\s+(\S+)\s+)?import\s+(\S+)/);l&&s.push({type:"import",name:l[1]||l[2],line:i})}if(e===".go"){let a=r.match(/^func\s+(?:\([^)]+\)\s+)?(\w+)/);a&&s.push({type:"function",name:a[1],line:i});let c=r.match(/^type\s+(\w+)\s+struct/);c&&s.push({type:"class",name:c[1],line:i})}}return s}async function ju(t){t=t||process.cwd();let e=Qn.join(t,".nex","index","content-index.json"),s={};if(Qi&&Date.now()-Mu<y$)return Qi;try{let i=await Zn.readFile(e,"utf-8");s=JSON.parse(i)}catch{s={files:{}}}ta().length===0&&await Pu(t);let o={files:{}},r=!1;for(let i of ta()){let a=Qn.extname(i);if(!$$.has(a))continue;let c=Qn.join(t,i);try{let u=(await Zn.stat(c)).mtimeMs;if(s.files[i]&&s.files[i].mtime===u){o.files[i]=s.files[i];continue}let d=await Zn.readFile(c,"utf-8"),f=Iu(d,a);o.files[i]={defs:f,mtime:u},r=!0}catch{}}if(r){let i=Qn.join(t,".nex","index");await Zn.mkdir(i,{recursive:!0}),await Zn.writeFile(e,JSON.stringify(o),"utf-8")}return Qi=o,Mu=Date.now(),o}async function w$(t,e){let s=await ju(),n=[],o=t.toLowerCase();for(let[r,i]of Object.entries(s.files))for(let a of i.defs)e&&a.type!==e||a.name.toLowerCase().includes(o)&&n.push({file:r,type:a.type,name:a.name,line:a.line});return n.sort((r,i)=>{let a=r.name.toLowerCase()===o?0:1,c=i.name.toLowerCase()===o?0:1;if(a!==c)return a-c;let l=r.name.toLowerCase().startsWith(o)?0:1,u=i.name.toLowerCase().startsWith(o)?0:1;return l-u}),n.slice(0,50)}Du.exports={refreshIndex:Pu,getFileIndex:ta,getIndexedCwd:h$,findFileInIndex:m$,searchIndex:g$,isIndexValid:Lu,buildContentIndex:ju,searchContentIndex:w$,extractDefinitions:Iu}});var ra=se((jk,Wu)=>{var ur=require("fs"),fr=require("path"),pr=require("os"),{execFile:b$}=require("child_process"),{promisify:_$}=require("util"),oa=_$(b$),x$=fr.join(pr.homedir(),".nex","servers.json"),dr=fr.join(pr.tmpdir(),"nex-ssh-sockets");function k$(){return fr.join(process.cwd(),".nex","servers.json")}function qu(){let t=n=>{if(!ur.existsSync(n))return{};try{return JSON.parse(ur.readFileSync(n,"utf-8"))}catch{return{}}},e=t(x$),s=t(k$());return{...e,...s}}function v$(t){let e=qu();if(e[t])return{...e[t],_name:t};if(/^[\w.-]+@[\w.-]+$/.test(t)||/[\w-]+\.[\w.-]+/.test(t)||t==="localhost"){let[o,r]=t.includes("@")?t.split("@"):[void 0,t];return{host:r,user:o}}let s=Object.keys(e),n=s.length?`Available profiles: ${s.join(", ")}`:"No profiles configured. Create .nex/servers.json (project) or ~/.nex/servers.json (global)";throw new Error(`Unknown server: "${t}". ${n}`)}function S$(){ur.existsSync(dr)||ur.mkdirSync(dr,{recursive:!0})}function Fu(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-o","ServerAliveInterval=30"];t.key&&e.push("-i",t.key.replace(/^~/,pr.homedir())),t.port&&Number(t.port)!==22&&e.push("-p",String(t.port)),S$();let s=t.user?`${t.user}@${t.host}`:t.host,n=fr.join(dr,s.replace(/[@.:]/g,"_"));return e.push("-o","ControlMaster=auto","-o",`ControlPath=${n}`,"-o","ControlPersist=120"),e.push(s),{args:e,target:s}}function Bu(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-r"];return t.key&&e.push("-i",t.key.replace(/^~/,pr.homedir())),t.port&&Number(t.port)!==22&&e.push("-P",String(t.port)),e}async function E$(t,e,{timeout:s=3e4,sudo:n=!1}={}){let{args:o}=Fu(t),r=n&&t.sudo?`sudo sh -c ${JSON.stringify(e)}`:e;try{let{stdout:i,stderr:a}=await oa("ssh",[...o,r],{timeout:s,maxBuffer:4194304});return{stdout:i||"",stderr:a||"",exitCode:0}}catch(i){let a=typeof i.code=="number"?i.code:1,c=(i.stderr||i.message||"").toString();return{stdout:(i.stdout||"").toString(),stderr:c,exitCode:a,error:hr(c,t)}}}async function T$(t,e,s,{timeout:n=12e4}={}){let o=Bu(t),r=t.user?`${t.user}@${t.host}`:t.host;o.push(e,`${r}:${s}`);try{let{stdout:i,stderr:a}=await oa("scp",o,{timeout:n,maxBuffer:1048576});return i||a||`Uploaded ${e} \u2192 ${r}:${s}`}catch(i){let a=(i.stderr||i.message||"").toString();throw new Error(hr(a,t)||a)}}async function R$(t,e,s,{timeout:n=12e4}={}){let o=Bu(t),r=t.user?`${t.user}@${t.host}`:t.host;o.push(`${r}:${e}`,s);try{let{stdout:i,stderr:a}=await oa("scp",o,{timeout:n,maxBuffer:1048576});return i||a||`Downloaded ${r}:${e} \u2192 ${s}`}catch(i){let a=(i.stderr||i.message||"").toString();throw new Error(hr(a,t)||a)}}function hr(t,e){if(!t)return"";if(/connection refused/i.test(t)){let s=e.port||22;return`${t}
119
+ HINT: Connection refused on ${e.host}:${s}. Check: server is running, SSH service is active (systemctl status sshd), firewall allows port ${s} (firewall-cmd --list-ports).`}if(/permission denied/i.test(t)){let s=e.key?`key: ${e.key}`:"SSH agent";return`${t}
120
+ HINT: Auth failed using ${s} as user "${e.user||"root"}". Check: authorized_keys on server, correct username, key passphrase.`}return/no route to host|network unreachable|name or service not known/i.test(t)?`${t}
121
+ HINT: Cannot reach ${e.host}. Check: network connection, correct hostname/IP, DNS resolution.`:/host key verification failed/i.test(t)?`${t}
122
+ HINT: Host key changed for ${e.host}. To reset: ssh-keygen -R ${e.host}`:/timed out/i.test(t)?`${t}
123
+ HINT: Connection timed out to ${e.host}. Check firewall rules and network connectivity.`:/too many authentication failures/i.test(t)?`${t}
124
+ HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function C$(t,e){let s=e.user?`${e.user}@${e.host}`:e.host,n=e.port&&Number(e.port)!==22?`:${e.port}`:"",o=e.os?` [${e.os}]`:"",r=e.key?` key:${e.key}`:"",i=e.sudo?" sudo:yes":"";return`${t}: ${s}${n}${o}${r}${i}`}Wu.exports={loadServerProfiles:qu,resolveProfile:v$,buildSSHArgs:Fu,sshExec:E$,scpUpload:T$,scpDownload:R$,enrichSSHError:hr,formatProfile:C$,SSH_SOCKET_DIR:dr}});var Gu=se((Dk,Hu)=>{var Ns=require("fs"),ia=require("path"),A$=ia.join(".nex","deploy.json");function aa(){return ia.join(process.cwd(),A$)}function Uu(){let t=aa();if(!Ns.existsSync(t))return{};try{return JSON.parse(Ns.readFileSync(t,"utf-8"))}catch{return{}}}function O$(t){let e=Uu();if(e[t])return{...e[t],_name:t};let s=Object.keys(e),n=s.length?`Available: ${s.join(", ")}`:"No deploy configs found. Create .nex/deploy.json or use explicit params.";throw new Error(`Unknown deploy config: "${t}". ${n}`)}function N$(t){let e=ia.join(process.cwd(),".nex");Ns.existsSync(e)||Ns.mkdirSync(e,{recursive:!0}),Ns.writeFileSync(aa(),JSON.stringify(t,null,2)+`
125
+ `,"utf-8")}Hu.exports={loadDeployConfigs:Uu,resolveDeployConfig:O$,saveDeployConfigs:N$,getDeployConfigPath:aa}});var Is=se((qk,zu)=>{var{getActiveModel:M$,getActiveProviderName:L$}=He(),Ms={essential:["bash","read_file","write_file","edit_file","list_directory"],standard:["bash","read_file","write_file","edit_file","list_directory","search_files","glob","grep","ask_user","git_status","git_diff","git_log","task_list","ssh_exec","service_manage","service_logs","container_list","container_logs","container_exec","container_manage","deploy"],full:null},Ls={"qwen3-coder:480b":"full","qwen3-coder-next":"full","kimi-k2.5":"full","kimi-k2:1t":"full","kimi-k2-thinking":"full","deepseek-v3.2":"full","deepseek-v3.1:671b":"full","devstral-2:123b":"full","devstral-small-2:24b":"standard","cogito-2.1:671b":"full","qwen3-next:80b":"full","qwen3.5:397b-cloud":"full","qwen3.5:397b":"full","qwen3.5:122b-a10b":"full","qwen3.5:35b-a3b":"full","qwen3.5:27b":"full","qwen3.5:9b":"standard","qwen3.5:4b":"essential","qwen3.5:2b":"essential","qwen3.5:0.8b":"essential","mistral-large-3:675b":"full","gpt-oss:120b":"full","minimax-m2.5":"full","glm-5":"full","glm-4.7":"standard","gemma3:27b":"standard","gemma3:12b":"essential","gemma3:4b":"essential","ministral-3:14b":"standard","ministral-3:8b":"essential","gpt-4o":"full","gpt-4.1":"full",o1:"full",o3:"full","o4-mini":"full","claude-sonnet":"full","claude-sonnet-4-5":"full","claude-opus":"full","claude-haiku":"standard","claude-sonnet-4":"full","gemini-3.1-pro-preview":"full","gemini-3-flash-preview":"full","gemini-2.5-pro":"full","gemini-2.5-flash":"full","gemini-2.0-flash":"standard","gemini-2.0-flash-lite":"essential"},Ps={ollama:"full",openai:"full",anthropic:"full",gemini:"full",local:"essential"},Lt={};function Ku(){try{let t=require("fs"),s=require("path").join(process.cwd(),".nex","config.json");t.existsSync(s)&&(Lt=JSON.parse(t.readFileSync(s,"utf-8")).toolTiers||{})}catch{Lt={}}}Ku();function ca(){let e=M$()?.id,s=L$();return e&&Lt[e]?Lt[e]:s&&Lt[`${s}:*`]?Lt[`${s}:*`]:e&&Ls[e]?Ls[e]:s&&Ps[s]?Ps[s]:"full"}var P$=new Set(["claude-sonnet","claude-sonnet-4-5","claude-sonnet-4","claude-opus","claude-haiku","gpt-4o","gpt-4.1","o1","o3","o4-mini","kimi-k2:1t","kimi-k2.5","kimi-k2-thinking","qwen3-coder:480b","qwen3-coder-next","deepseek-v3.2","deepseek-v3.1:671b"]),Yu={anthropic:"strict",openai:"strict",gemini:"strict",ollama:"fuzzy",local:"fuzzy"};function I$(t,e){return t&&(P$.has(t)||t.startsWith("claude-"))?"strict":e&&Yu[e]?Yu[e]:"fuzzy"}function j$(t,e){return t&&Lt[t]?Lt[t]:e&&Lt[`${e}:*`]?Lt[`${e}:*`]:t&&Ls[t]?Ls[t]:e&&Ps[e]?Ps[e]:"full"}function D$(t,e){let s=e||ca();if(s==="full"||!Ms[s])return t;let n=new Set(Ms[s]);return t.filter(o=>n.has(o.function.name))}function q$(){let t=ca(),e=Ms[t]?Ms[t].length:"all";return{tier:t,toolCount:e}}zu.exports={filterToolsForModel:D$,getActiveTier:ca,getModelTier:j$,getEditMode:I$,getTierInfo:q$,TIERS:Ms,MODEL_TIERS:Ls,PROVIDER_DEFAULT_TIER:Ps,loadConfigOverrides:Ku}});var Ds=se((Fk,Ju)=>{var la=null,Ht=null,js=null,Xu=`Playwright is not installed. Install with:
126
+ npm install playwright && npx playwright install chromium
127
+ Then restart nex-code.`;function Vu(){if(js!==null)return js;try{require("playwright"),js=!0}catch{js=!1}return js}async function mr(){if(!Vu())throw new Error(Xu);return la||(la=require("playwright")),(!Ht||!Ht.isConnected())&&(Ht=await la.chromium.launch({headless:!0})),Ht}async function F$(){if(Ht){try{await Ht.close()}catch{}Ht=null}}process.on("exit",()=>{if(Ht)try{Ht.close()}catch{}});async function B$(t,{timeout:e=3e4,waitFor:s="domcontentloaded"}={}){let o=await(await mr()).newPage();try{await o.goto(t,{waitUntil:s,timeout:e});let r=await o.title(),i=await o.evaluate(()=>(document.querySelectorAll("script,style,nav,footer,header,aside,[role=navigation]").forEach(l=>l.remove()),document.body?.innerText||"")),a=await o.evaluate(()=>Array.from(document.querySelectorAll("a[href]")).slice(0,30).map(c=>({text:(c.innerText||c.textContent||"").trim().substring(0,80),href:c.href})).filter(c=>c.text&&c.href&&!c.href.startsWith("javascript:")));return{title:r,url:o.url(),text:i.substring(0,8e3)+(i.length>8e3?`
128
+ ...(truncated)`:""),links:a.slice(0,20)}}finally{await o.close()}}async function W$(t,{width:e=1280,height:s=800,fullPage:n=!1,timeout:o=3e4}={}){let i=await(await mr()).newPage();try{await i.setViewportSize({width:e,height:s}),await i.goto(t,{waitUntil:"networkidle",timeout:o});let a=await i.screenshot({type:"png",fullPage:n}),c=require("os"),l=require("path"),u=require("fs"),d=l.join(c.tmpdir(),`nex-screenshot-${Date.now()}.png`);return u.writeFileSync(d,a),{path:d,base64:a.toString("base64"),media_type:"image/png",title:await i.title(),url:i.url()}}finally{await i.close()}}async function U$(t,{selector:e,text:s,timeout:n=3e4}={}){if(!e&&!s)throw new Error("selector or text is required");let r=await(await mr()).newPage();try{await r.goto(t,{waitUntil:"domcontentloaded",timeout:n}),s?await r.getByText(s,{exact:!1}).first().click({timeout:1e4}):await r.locator(e).first().click({timeout:1e4}),await r.waitForLoadState("domcontentloaded");let i=await r.title();return`Clicked \u2014 now at: ${r.url()} (${i})`}finally{await r.close()}}async function H$(t,{selector:e,value:s,submit:n=!1,timeout:o=3e4}={}){if(!e||s===void 0)throw new Error("selector and value are required");let i=await(await mr()).newPage();try{return await i.goto(t,{waitUntil:"domcontentloaded",timeout:o}),await i.fill(e,String(s)),n&&(await i.keyboard.press("Enter"),await i.waitForLoadState("domcontentloaded")),`Filled "${e}" with value. ${n?`Submitted \u2192 ${i.url()}`:"Not submitted."}`}finally{await i.close()}}Ju.exports={isPlaywrightAvailable:Vu,browserNavigate:B$,browserScreenshot:W$,browserClick:U$,browserFill:H$,closeBrowser:F$,INSTALL_MSG:Xu}});var ua=se((Bk,Zu)=>{var{C:Oe}=Ue(),Fs="",et=[],qs=0,mn=null;function G$(t){mn=t}function Y$(t,e){Fs=t,et=[],qs=0;for(let n of e){qs++;let o=`t${qs}`;et.push({id:o,description:n.description||n.title||n.name||n.task||`Task ${qs}`,status:"pending",dependsOn:n.depends_on||[],result:null})}let s=et.map(n=>({...n}));return mn&&mn("create",{name:t,tasks:s}),s}function K$(t,e,s){let n=et.find(o=>o.id===t);return n?(n.status=e,s!==void 0&&(n.result=s),mn&&mn("update",{id:t,status:e,result:s}),{...n}):null}function z$(){return{name:Fs,tasks:et.map(t=>({...t}))}}function X$(){Fs="",et=[],qs=0,mn&&mn("clear",{})}function V$(){return et.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let s=et.find(n=>n.id===e);return s&&s.status==="done"}))}function J$(){if(et.length===0)return`${Oe.dim}No active tasks${Oe.reset}`;let t=[];Fs&&(t.push(` ${Oe.bold}${Oe.cyan}Tasks: ${Fs}${Oe.reset}`),t.push(` ${Oe.dim}${"\u2500".repeat(40)}${Oe.reset}`));for(let o of et){let r,i;switch(o.status){case"done":r="\u2713",i=Oe.green;break;case"in_progress":r="\u2192",i=Oe.cyan;break;case"failed":r="\u2717",i=Oe.red;break;default:r="\xB7",i=Oe.dim}let a=o.dependsOn.length>0?` ${Oe.dim}(after: ${o.dependsOn.join(", ")})${Oe.reset}`:"",c=`[${o.status}]`,l=o.description.length>50?o.description.substring(0,47)+"...":o.description;if(t.push(` ${i}${r}${Oe.reset} ${Oe.bold}${o.id}${Oe.reset} ${l.padEnd(40)} ${i}${c}${Oe.reset}${a}`),o.result&&o.status==="done"){let u=o.result.length>60?o.result.substring(0,57)+"...":o.result;t.push(` ${Oe.dim}\u2192 ${u}${Oe.reset}`)}}let e=et.filter(o=>o.status==="done").length,s=et.filter(o=>o.status==="failed").length,n=et.length;return t.push(` ${Oe.dim}${"\u2500".repeat(40)}${Oe.reset}`),t.push(` ${Oe.dim}${e}/${n} done${s>0?`, ${s} failed`:""}${Oe.reset}`),t.join(`
129
+ `)}function Z$(){return et.length>0&&et.some(t=>t.status==="pending"||t.status==="in_progress")}Zu.exports={createTasks:Y$,updateTask:K$,getTaskList:z$,clearTasks:X$,getReadyTasks:V$,renderTaskList:J$,setOnChange:G$,hasActiveTasks:Z$}});var gr=se((Wk,ed)=>{var Bs={"devstral-2":{staleWarn:3e4,staleAbort:9e4,investigationCap:12,postEditCap:10,briefing:`You are devstral-2, a strong coding model optimized for agentic tasks.
130
+ Use tools confidently and without hesitation \u2014 tool use is the expected workflow.
131
+ You excel at sysadmin, frontend, and multi-step coding tasks.
132
+ Prefer action over narration \u2014 read, fix, verify, done.`},"devstral-small":{staleWarn:2e4,staleAbort:6e4,investigationCap:10,postEditCap:8,briefing:`You are devstral-small, a fast and lightweight coding model.
133
+ Be decisive \u2014 read only what you need, then fix immediately.
134
+ Keep investigation short: identify the target file, edit it, move on.`},"qwen3-coder":{staleWarn:6e4,staleAbort:18e4,investigationCap:15,postEditCap:12,briefing:`You are qwen3-coder, a top-ranked model for complex multi-step tasks.
135
+ Trust your reasoning and use tools thoroughly when the task demands it.
136
+ You handle large codebases and data tasks well \u2014 don't cut corners prematurely.`},"kimi-k2":{staleWarn:45e3,staleAbort:12e4,investigationCap:15,postEditCap:12,briefing:`You are kimi-k2, a large-context model with strong reasoning.
137
+ Use your context window effectively \u2014 read broadly when needed, then act decisively.
138
+ Focus on correctness over speed.`},"ministral-3":{staleWarn:2e4,staleAbort:6e4,investigationCap:10,postEditCap:8,briefing:`You are ministral-3, one of the fastest coding models available.
139
+ Prioritize decisive, targeted edits. Read only what you need, then fix.
140
+ Stay on-scope \u2014 your strength is focused, efficient coding tasks.`},"qwen3-vl":{staleWarn:6e4,staleAbort:18e4,investigationCap:15,postEditCap:12,briefing:`You are qwen3-vl, the highest-ranked model for data, frontend, and agentic tasks.
141
+ Trust your reasoning. Use tools thoroughly when the task demands it.
142
+ You handle complex multi-step tasks well \u2014 don't cut corners prematurely.`}},Qu={staleWarn:6e4,staleAbort:12e4,investigationCap:12,postEditCap:10};function Q$(t){let e=(t||"").toLowerCase(),s=null,n=0;for(let r of Object.keys(Bs))e.startsWith(r)&&r.length>n&&(s=r,n=r.length);let o=s?{...Bs[s]}:{...Qu};for(let[r,i]of[["NEX_STALE_WARN_MS","staleWarn"],["NEX_STALE_ABORT_MS","staleAbort"]])if(process.env[r]){let a=parseInt(process.env[r],10);Number.isInteger(a)&&a>=1e3&&a<=3e5&&(o[i]=a)}return o}function ew(t){let e=(t||"").toLowerCase(),s=null,n=0;for(let o of Object.keys(Bs))e.startsWith(o)&&o.length>n&&(s=o,n=o.length);return s&&Bs[s].briefing||""}ed.exports={getModelProfile:Q$,getModelBriefing:ew,PROFILES:Bs,DEFAULTS:Qu}});var id=se((Uk,rd)=>{var{callChat:tw}=He(),{estimateTokens:da}=Pt(),td=process.env.NEX_COMPACTION!=="false",nd=6,sd=500,nw=`Summarize this conversation history concisely. Focus on:
143
+ - What files were read, created, or modified
144
+ - Key decisions made and their rationale
145
+ - Current state of the task (what's done, what's pending)
146
+ - Any errors encountered and how they were resolved
147
+ Be factual and brief. Use bullet points. Max 300 words.`;async function sw(t){if(!td||t.length<nd)return null;let e=[{role:"system",content:nw},{role:"user",content:od(t)}];try{let n=((await tw(e,[],{temperature:0,maxTokens:sd})).content||"").trim();if(!n)return null;let o=t.reduce((i,a)=>i+da(a.content||"")+(a.tool_calls?da(JSON.stringify(a.tool_calls)):0),0),r=da(n);return r>=o*.8?null:{message:{role:"system",content:`[Conversation Summary \u2014 ${t.length} messages compacted]
148
+ ${n}`,_compacted:!0,_originalCount:t.length},tokensRemoved:o-r}}catch{return null}}function od(t){return t.map(e=>{let s=e.role==="tool"?"tool_result":e.role,n=(e.content||"").substring(0,500);if(e.tool_calls){let o=e.tool_calls.map(r=>r.function?.name).join(", ");return`[${s}] ${n}
149
+ tools: ${o}`}return`[${s}] ${n}`}).join(`
150
+
151
+ `)}rd.exports={compactMessages:sw,formatMessagesForSummary:od,COMPACTION_ENABLED:td,COMPACTION_MIN_MESSAGES:nd,COMPACTION_SUMMARY_BUDGET:sd}});var Pt=se((Hk,gd)=>{var ow=require("path");function cd(){return He().getActiveModel()}var rw={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},iw={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},gn=new Map,ad=1e3,fa=new WeakMap,yn=null;function aw(){if(yn!==null)return yn;try{let t=cd(),e=t?.provider||"ollama",s=(t?.id||"").toLowerCase();for(let[n,o]of Object.entries(iw))if(s.startsWith(n))return yn=o,yn;return yn=rw[e]||4,yn}catch{return 4}}function cw(){yn=null}function $n(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)}`,s=gn.get(e);if(s!==void 0)return gn.delete(e),gn.set(e,s),s;let n=Math.ceil(t.length/aw());if(gn.size>=ad){let o=ad>>1,r=gn.keys();for(let i=0;i<o;i++)gn.delete(r.next().value)}return gn.set(e,n),n}function lw(t){if(fa.has(t))return fa.get(t);let e=JSON.stringify(t);return fa.set(t,e),e}function ss(t){let s=4;if(t.content&&(s+=$n(t.content)),t.tool_calls)for(let n of t.tool_calls){s+=4,s+=$n(n.function?.name||"");let o=n.function?.arguments;typeof o=="string"?s+=$n(o):o&&(s+=$n(JSON.stringify(o)))}return s}function yt(t){let e=0;for(let s of t)e+=ss(s);return e}function uw(t,e){if(t&&t.length===e.length){let r=!1;for(let i=0;i<e.length;i++)if(t[i]!==e[i]){r=!0;break}if(!r)return 0}let s=t?t.length:0,n=e.length,o=0;for(let r=s;r<n;r++)o+=ss(e[r]);return o}function yr(t){return!t||t.length===0?0:$n(JSON.stringify(t))}function $r(){return cd()?.contextWindow||32768}function dw(t,e){let s=yt(t),n=yr(e),o=s+n,r=$r(),i=r>0?o/r*100:0,a=0,c=0,l=0;for(let u of t){let d=ss(u);u.role==="system"?a+=d:u.role==="tool"?l+=d:c+=d}return{used:o,limit:r,percentage:Math.round(i*10)/10,breakdown:{system:a,conversation:c,toolResults:l,toolDefinitions:n},messageCount:t.length}}var Ws=parseFloat(process.env.NEX_COMPRESSION_THRESHOLD)||.75,ld=parseFloat(process.env.NEX_SAFETY_MARGIN)||.1,ud=parseInt(process.env.NEX_KEEP_RECENT,10)||10,dd={essential:.6,standard:.7,full:Ws};function fd(){if(process.env.NEX_COMPRESSION_THRESHOLD)return Ws;try{let{getActiveTier:t}=Is(),e=t();return dd[e]??Ws}catch{return Ws}}var fw=200,pw=1e3;function pd(t,e){if(!t||t.length<=e)return t;let n=/^(ERROR|EXIT|BLOCKED|CANCELLED)/i.test(t)?e*3:e;if(t.length<=n)return t;let o=t.split(`
152
+ `);if(o.length<=10){let m=Math.floor(n*.6),g=Math.floor(n*.4),b=t.substring(0,m),v=t.substring(t.length-g);return b+`
153
+ ...(${t.length} chars total)...
154
+ `+v}let r=Math.floor(o.length*.4),i=Math.floor(o.length*.4),a=[],c=0,l=Math.floor(n*.4);for(let m=0;m<r&&c<l;m++)if(c+o[m].length+1>l&&o[m].trim().startsWith("```")){a.push(o[m]),c+=o[m].length+1;let g=m+1;for(;g<o.length&&c<l*1.5&&!o[g].trim().startsWith("```");)a.push(o[g]),c+=o[g].length+1,g++;g<o.length&&o[g].trim().startsWith("```")&&(a.push(o[g]),c+=o[g].length+1),m=g}else a.push(o[m]),c+=o[m].length+1;let u=[],d=0,f=Math.floor(n*.4);for(let m=o.length-1;m>=o.length-i&&d<f;m--)if(d+o[m].length+1>f&&o[m].trim().startsWith("```")){u.push(o[m]),d+=o[m].length+1;let g=m-1;for(;g>=0&&d<f*1.5&&!o[g].trim().startsWith("```");)u.push(o[g]),d+=o[g].length+1,g--;g>=0&&o[g].trim().startsWith("```")&&(u.push(o[g]),d+=o[g].length+1),m=g}else u.push(o[m]),d+=o[m].length+1;u.reverse();let h=o.length-a.length-u.length;return a.join(`
155
+ `)+`
156
+ ...(${h} lines omitted, ${o.length} total)...
157
+ `+u.join(`
158
+ `)}function ns(t,e="light"){let s=e==="aggressive"?100:e==="medium"?200:pw,n=e==="aggressive"?50:e==="medium"?100:fw;if(t.role==="tool"){let o=typeof t.content=="string"?t.content:JSON.stringify(t.content);return o.length>n?{...t,content:pd(o,n)}:t}if(t.role==="assistant"){let o={...t};return o.content&&o.content.length>s&&(o.content=o.content.substring(0,s)+`
159
+ ...(truncated)`),o.tool_calls&&e==="aggressive"&&(o.tool_calls=o.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}}))),o}return t}function hd(t,e,s,n){let o=0;if(t.role==="system")return 100;if(t.role==="user")o+=35;else if(t.role==="tool"){let i=typeof t.content=="string"?t.content:JSON.stringify(t.content||"");/^(ERROR|BLOCKED|CANCELLED)/i.test(i)?o+=30:o+=15}else t.role==="assistant"&&(o+=t.tool_calls?20:10);let r=s>1?e/(s-1):1;if(o+=Math.round(r*30),n&&n.size>0){let i=typeof t.content=="string"?t.content:JSON.stringify(t.content||""),a=0;for(let c of n)(i.includes(c)||i.includes(ow.basename(c)))&&a++;o+=Math.min(30,a*10)}return Math.min(100,o)}function md(t,e=10){let s=new Set,n=t.slice(-e),o=/(?:\/[\w.-]+)+\.\w+/g;for(let r of n){let a=(typeof r.content=="string"?r.content:JSON.stringify(r.content||"")).match(o);a&&a.forEach(c=>s.add(c))}return s}var ts={msgCount:-1,lastMsgRef:null,result:null};function hw(){ts={msgCount:-1,lastMsgRef:null,result:null}}async function mw(t,e,s={}){let n=t.length>0?t[t.length-1]:null;if(!s.force&&ts.result&&t.length===ts.msgCount&&n===ts.lastMsgRef)return ts.result;let o=s.threshold??fd(),r=s.safetyMargin??ld,i=s.keepRecent??ud,a=$r(),c=yr(e),l=Math.floor(a*(o-r)),u=l-c,d=yt(t),f=d+c;if(f<=l){let V={messages:t,compressed:!1,compacted:!1,tokensRemoved:0};return ts={msgCount:t.length,lastMsgRef:n,result:V},V}let h=d,m=null,g=0;t.length>0&&t[0].role==="system"&&(m=t[0],g=1);let b=Math.max(g,t.length-i),v=t.slice(g,b),O=t.slice(b),U=v.filter(V=>!V._compacted);if(U.length>=6)try{let{compactMessages:V}=id(),H=await V(U);if(H){let he=[...v.filter(ge=>ge._compacted),H.message],de=Zt(m,he,O),me=yt(de);if(me+c<=l)return{messages:de,compressed:!0,compacted:!0,tokensRemoved:h-me};v=he}}catch(V){process.env.NEX_DEBUG&&console.error("[context-engine] LLM compacting failed:",V.message)}let L=(f-l)/l,R=v.map(V=>ns(V,"light")),C=Zt(m,R,O),K=yt(C);if(K+c<=l)return{messages:C,compressed:!0,compacted:!1,tokensRemoved:h-K};if(R=v.map(V=>ns(V,"medium")),C=Zt(m,R,O),K=yt(C),K+c<=l)return{messages:C,compressed:!0,compacted:!1,tokensRemoved:h-K};if(R=v.map(V=>ns(V,"aggressive")),C=Zt(m,R,O),K=yt(C),K+c<=l)return{messages:C,compressed:!0,compacted:!1,tokensRemoved:h-K};let Q=md([...R,...O]),re=R.map((V,H)=>({msg:V,score:hd(V,H,R.length,Q),tokens:ss(V)}));for(;re.length>0&&K>u;){let V=0;for(let H=1;H<re.length;H++)re[H].score<re[V].score&&(V=H);K-=re[V].tokens,re.splice(V,1)}return R=re.map(V=>V.msg),C=Zt(m,R,O),K=yt(C),{messages:C,compressed:!0,compacted:!1,tokensRemoved:h-K}}function Zt(t,e,s){let n=[];return t&&n.push(t),n.push(...e,...s),n}function gw(t,e){if(!t)return"";if($n(t)<=e)return t;let n=e*4,o=t.split(`
160
+ `),r=Math.floor(n*.6),i=Math.floor(n*.4),a="",c=0;for(let h of o){if(a.length+h.length+1>r)break;a+=(a?`
161
+ `:"")+h,c++}let l="",u=0;for(let h=o.length-1;h>=c;h--){let m=o[h]+(l?`
162
+ `:"")+l;if(m.length>i)break;l=m,u++}let f=`
163
+
164
+ ... (${o.length-c-u} lines omitted, ${o.length} total) ...
165
+
166
+ `;return a+f+l}var yw=6;function $w(t,e,s=!1){let n=$r(),o=yr(e),r=Math.floor(n*(s?.35:.5))-o,i=yt(t),a=Math.floor(i*(s?.5:.8));r>a&&(r=a);let c=null,l=0;t.length>0&&t[0].role==="system"&&(c=t[0],l=1);let u=s?2:yw,d=Math.max(l,t.length-u),f=t.slice(l,d),h=t.slice(d),m=f.map(R=>ns(R,"aggressive"));s&&(h=h.map(R=>ns(R,"aggressive")));let g=Zt(c,m,h),b=yt(g);for(;m.length>0&&b>r;){let R=m.shift();b-=ss(R)}s&&b>r&&(h=h.filter(C=>C.role==="user").slice(-1),g=Zt(c,[],h),b=yt(g)),g=Zt(c,m,h);let v=t.filter(R=>R.role==="user"),O=R=>{let C=typeof R.content=="string"?R.content:"";return C.startsWith("[SYSTEM WARNING]")||C.startsWith("[SYSTEM:")||C.startsWith("BLOCKED:")},U=v.find(R=>!O(R)),L=[...v].reverse().find(R=>!O(R));if(U&&!g.find(R=>R===U)){let R=g.findIndex(K=>K.role==="system"),C=R>=0?R+1:0;g.splice(C,0,U)}return L&&L!==U&&!g.find(R=>R===L)&&g.push(L),{messages:g,tokensRemoved:i-yt(g)}}gd.exports={estimateTokens:$n,estimateMessageTokens:ss,estimateMessagesTokens:yt,estimateDeltaTokens:uw,estimateToolsTokens:yr,serializeMessage:lw,getContextWindow:$r,getUsage:dw,compressMessage:ns,compressToolResult:pd,scoreMessageRelevance:hd,extractActiveFiles:md,fitToContext:mw,forceCompress:$w,truncateFileContent:gw,invalidateTokenRatioCache:cw,invalidateFitToContextCache:hw,getEffectiveCompressionThreshold:fd,COMPRESSION_THRESHOLD:Ws,TIER_COMPRESSION_THRESHOLDS:dd,SAFETY_MARGIN:ld,KEEP_RECENT:ud}});var ga=se((Yk,Dd)=>{var{callStream:ww,getActiveProviderName:br,getActiveModelId:yd,getConfiguredProviders:bw,getProvider:$d,getActiveProvider:wd,parseModelSpec:bd}=He(),{parseToolArgs:_d}=Ss(),{filterToolsForModel:_w,getModelTier:wr}=Is(),{getModelBriefing:xw}=gr(),{trackUsage:xd,estimateTokens:kd}=zo(),{MultiProgress:kw,C:Gk}=Ue();function vd(t){return!t||typeof t!="string"?0:typeof kd=="function"?kd(t):Math.ceil(t.length/4)}var Td=15,vw=5,Sd=3,Rd=8,Sw=2,_r=new Map,Cd=600*1e3;function Ew(t,e){let s=_r.get(t);return s&&s.agentId!==e&&Date.now()-s.timestamp<Cd?!1:(_r.set(t,{agentId:e,timestamp:Date.now()}),!0)}function Us(t){_r.delete(t)}function pa(){_r.clear()}function ha(t){let e=(t.message||"").toLowerCase(),s=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":e.includes("timed out")||e.includes("timeout")?"timeout":s==="ECONNRESET"||s==="ECONNABORTED"||s==="ETIMEDOUT"||s==="ECONNREFUSED"||s==="ENOTFOUND"||e.includes("socket disconnected")||e.includes("tls")||e.includes("econnreset")||e.includes("fetch failed")||e.includes("etimedout")||e.includes("enotfound")?"network":"unknown"}function Ad(t){let e=ha(t);return e==="rate_limit"||e==="server"||e==="network"||e==="timeout"}async function Od(t,e,s){let n;for(let o=0;o<=Sd;o++)try{return await ww(t,e,s)}catch(r){n=r;let i=ha(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(o<Sd&&Ad(r)){let c=i==="rate_limit"?Math.min(2e3*Math.pow(2,o),15e3):Math.min(500*Math.pow(2,o),4e3);await new Promise(l=>setTimeout(l,c).unref());continue}throw r}throw n}var Ed=new Set(["ask_user","task_list"]);function Nd(t){return t>=2?new Set([...Ed,"spawn_agents"]):Ed}var Tw=new Set(["write_file","edit_file","patch_file"]),Md={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:""}},Rw=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,Cw=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function Ld(t){return Cw.test(t)?"full":Rw.test(t)?"essential":t.length>300?"full":"standard"}function Pd(t){let e=bw(),s=br(),n=[...e].sort((o,r)=>(o.name===s?-1:1)-(r.name===s?-1:1));for(let o of n)for(let r of o.models)if(wr(r.id,o.name)===t)return{provider:o.name,model:r.id};return null}var Aw={essential:process.env.NEX_FAST_MODEL||null,standard:process.env.NEX_STANDARD_MODEL||null,full:process.env.NEX_HEAVY_MODEL||null};function ma(t){if(t.model){let{provider:o,model:r}=bd(t.model),i=o?$d(o):wd(),a=o||br();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let c=wr(r,a);return{provider:a,model:r,tier:c}}}let e=Ld(t.task),s=Aw[e];if(s){let{provider:o,model:r}=bd(s),i=o?$d(o):wd(),a=o||br();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let c=wr(r,a);return{provider:a,model:r,tier:c}}}let n=Pd(e);if(n){let o=wr(n.model,n.provider);return{provider:n.provider,model:n.model,tier:o}}return{provider:null,model:null,tier:null}}async function Id(t,e={},s=0){let n=s===0?Td:Rd,o=Math.min(t.max_iterations||10,n),r=`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,i=[],a={input:0,output:0},c=new Set,l=new Map,u=t._systemPrompt||`You are a focused sub-agent. Complete this specific task efficiently.
167
+
168
+ TASK: ${t.task}
169
+ ${t.context?`
170
+ CONTEXT: ${t.context}`:""}
171
+
172
+ WORKING DIRECTORY: ${process.cwd()}
173
+
174
+ RULES:
175
+ - Focus only on your assigned task. Be concise and efficient.
176
+ - When done, respond with a clear summary of what you did and the result.
177
+ - Do not ask questions \u2014 make reasonable decisions.
178
+ - Use relative paths when possible.
179
+
180
+ TOOL STRATEGY:
181
+ - Use read_file to read files (not bash cat). Use edit_file/patch_file to modify (not bash sed).
182
+ - Use glob to find files by name. Use grep to search contents. Only use bash for shell operations.
183
+ - ALWAYS read a file with read_file before editing it. edit_file old_text must match exactly.
184
+
185
+ ERROR RECOVERY:
186
+ - If edit_file fails with "old_text not found": read the file again, compare, and retry with exact text.
187
+ - If bash fails: read the error, fix the root cause, then retry.
188
+ - After 2 failed attempts at the same operation, summarize the issue and stop.`,d=t.type&&Md[t.type],f=d&&d.systemSuffix?`
189
+
190
+ ${d.systemSuffix}`:"",h=ma(t),m=h.provider,g=h.model,b=h.tier,v=xw(g||yd()),U=[{role:"system",content:(v?`## Model Briefing
191
+ ${v}
192
+
193
+ ---
194
+
195
+ `:"")+u+f}];U.push({role:"user",content:t.task});let{TOOL_DEFINITIONS:L,executeTool:R}=Jn(),C=Nd(s),K=_w(L.filter(re=>!C.has(re.function.name)),b);if(d&&d.allowedTools&&(K=K.filter(re=>d.allowedTools.has(re.function.name))),g&&!t._skipLog){let re=b?` (${b})`:"";process.stderr.write(` [sub-agent: ${m}:${g}${re}]
196
+ `)}let Q={};m&&(Q.provider=m),g&&(Q.model=g);try{for(let V=0;V<o;V++){let H=await Od(U,K,Q);if(!H||typeof H!="object")throw new Error("Empty or invalid response from provider");{let we=m||br(),Se=g||yd();if(H.usage){let fe=H.usage.prompt_tokens||0,Pe=H.usage.completion_tokens||0;a.input+=fe,a.output+=Pe,xd(we,Se,fe,Pe)}else{let fe=H.content||"",Pe=U.map(k=>typeof k.content=="string"?k.content:Array.isArray(k.content)?k.content.map(N=>typeof N=="string"?N:N.text||"").join(""):"").join(" "),w=vd(Pe),P=vd(fe);a.input+=w,a.output+=P,a._estimated=!0,xd(we,Se,w,P)}}let _=H.content||"",he=H.tool_calls,de={role:"assistant",content:_||""};if(he&&he.length>0&&(de.tool_calls=he),U.push(de),!he||he.length===0){for(let we of c)Us(we);return{task:t.task,status:"done",result:_||"(no response)",toolsUsed:i,tokensUsed:a,modelSpec:m&&g?`${m}:${g}`:null}}let me=he.map(we=>{let Se=we.function.name,fe=_d(we.function.arguments),Pe=we.id||`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!fe)return Promise.resolve({role:"tool",content:`ERROR: Malformed tool arguments for ${Se}`,tool_call_id:Pe});let w=null;if(Tw.has(Se)&&fe.path){let k=require("path"),N=k.isAbsolute(fe.path)?fe.path:k.resolve(process.cwd(),fe.path);if(t._readOnlyFiles&&t._readOnlyFiles.length>0){let T=k.relative(process.cwd(),N);if(t._readOnlyFiles.some(J=>T===J||T.startsWith(J+"/")||N===J||N.startsWith(J+"/")))return Promise.resolve({role:"tool",content:`ERROR: File '${fe.path}' is owned by another agent and is READ ONLY. Write to your own scope files instead.`,tool_call_id:Pe})}if(c.has(N)||!Ew(N,r))return Promise.resolve({role:"tool",content:`ERROR: File '${fe.path}' is locked by another operation. Try a different approach or skip this file.`,tool_call_id:Pe});c.add(N),w=N}return i.push(Se),e.onUpdate&&e.onUpdate({type:"tool_call",tool:Se,agentId:r}),(Se==="spawn_agents"?jd(fe,s+1):R(Se,fe,{autoConfirm:!0,silent:!0})).then(k=>{w&&(Us(w),c.delete(w));let N=String(k??"");return{role:"tool",content:N.length>2e4?N.substring(0,2e4)+`
197
+ ...(truncated)`:N,tool_call_id:Pe}}).catch(k=>(w&&(Us(w),c.delete(w)),{role:"tool",content:`ERROR: ${k.message}`,tool_call_id:Pe}))}),ge=await Promise.all(me);if(U.push(...ge),V>=7&&U.length>12)try{let{compressMessage:we}=Pt(),Se=U.length-6;for(let fe=1;fe<Se;fe++)U[fe]._subAgentCompressed||(U[fe]={...we(U[fe],"light"),_subAgentCompressed:!0})}catch{}for(let we=0;we<he.length;we++){let Se=he[we];if(Se.function.name==="bash_exec"){let fe=_d(Se.function.arguments);if((ge[we]?.content||"").startsWith("ERROR")&&fe&&fe.command){let w=fe.command.replace(/\s+/g," ").trim().slice(0,100);l.set(w,(l.get(w)||0)+1)}}}e.onUpdate&&e.onUpdate(`step ${V+1}/${o}`)}for(let V of c)Us(V);let re=[...l.entries()].filter(([,V])=>V>=3).sort((V,H)=>H[1]-V[1]).slice(0,3).map(([V,H])=>`"${V}" (failed ${H}\xD7)`);return{task:t.task,status:"truncated",abortReason:"iteration_limit",repeatedFailures:re,result:U[U.length-1]?.content||"(max iterations reached)",toolsUsed:i,tokensUsed:a,modelSpec:m&&g?`${m}:${g}`:null}}catch(re){for(let V of c)Us(V);return{task:t.task,status:"failed",result:`Error: ${re.message}`,toolsUsed:i,tokensUsed:a,modelSpec:m&&g?`${m}:${g}`:null}}}async function jd(t,e=0){if(e>=2)return"ERROR: max agent nesting depth (2) reached \u2014 reviewer agents cannot spawn further agents.";let s=e===0?vw:Sw,n=e===0?Td:Rd,o=(t.agents||[]).slice(0,s);if(o.length===0)return"ERROR: No agents specified";let r=e>0?" \u21B3 ":"",i=e>0?38:44,a=o.map(u=>ma(u)),c=o.map((u,d)=>{let f=a[d],h=f.model?` [${f.model}]`:"",m=u.task.substring(0,i-h.length);return`${r}Agent ${d+1}${h}: ${m}${u.task.length>m.length?"...":""}`}),l=new kw(c);l.start();try{let u=o.map((g,b)=>{let v=a[b],O=Math.min(g.max_iterations||n,n),U=v.model?{...g,model:`${v.provider}:${v.model}`,_skipLog:!0,max_iterations:O}:{...g,_skipLog:!0,max_iterations:O};return Id(U,{onUpdate:()=>{}},e).then(L=>(l.update(b,L.status==="failed"?"error":"done"),L)).catch(L=>(l.update(b,"error"),{task:g.task,status:"failed",result:`Error: ${L.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}))}),d=await Promise.all(u);l.stop(),pa();let f=["Sub-agent results:",""],h=0,m=0;for(let g=0;g<d.length;g++){let b=d[g],v=b.status==="done"?"\u2713":b.status==="truncated"?"\u26A0":"\u2717",O=b.modelSpec?` [${b.modelSpec}]`:"";f.push(`${v} Agent ${g+1}${O}: ${b.task}`),f.push(` Status: ${b.status}`),f.push(` Tools used: ${b.toolsUsed.length>0?b.toolsUsed.join(", "):"none"}`),f.push(` Result: ${b.result}`),b.repeatedFailures&&b.repeatedFailures.length>0&&f.push(` Repeated failures: ${b.repeatedFailures.join("; ")}`),f.push(""),h+=b.tokensUsed.input,m+=b.tokensUsed.output}return f.push(`Total sub-agent tokens: ${h} input + ${m} output`),f.join(`
198
+ `)}catch(u){return l.stop(),pa(),`ERROR: Sub-agent execution failed: ${u.message}`}}Dd.exports={runSubAgent:Id,executeSpawnAgents:jd,clearAllLocks:pa,classifyTask:Ld,pickModelForTier:Pd,resolveSubAgentModel:ma,classifyError:ha,isRetryableError:Ad,callWithRetry:Od,getExcludedTools:Nd,LOCK_TIMEOUT_MS:Cd,SUB_AGENT_TYPES:Md}});var va=se((Kk,Zd)=>{var Ie=require("fs"),Gt=require("path"),{atomicWrite:qd,withFileLockSync:Fd}=fn(),Ow=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 rs(){let t=Gt.join(process.cwd(),".nex","brain");return Ie.existsSync(t)||Ie.mkdirSync(t,{recursive:!0}),t}function kr(){return Gt.join(rs(),".brain-index.json")}function wa(){return Gt.join(rs(),".embeddings.json")}function Hs(){let t=Gt.join(process.cwd(),".nex","brain");if(!Ie.existsSync(t))return[];try{return Ie.readdirSync(t).filter(e=>e.endsWith(".md")&&!e.startsWith(".")).map(e=>{let s=Gt.join(t,e),n=Ie.statSync(s);return{name:e.replace(/\.md$/,""),path:s,size:n.size,modified:new Date(n.mtimeMs)}}).sort((e,s)=>s.modified-e.modified)}catch{return[]}}function Gs(t){let e={},s=t,n=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(n){let o=n[1].split(`
199
+ `);for(let r of o){let i=r.match(/^(\w+):\s*(.+)$/);if(!i)continue;let a=i[1].trim(),c=i[2].trim();c.startsWith("[")&&c.endsWith("]")?e[a]=c.slice(1,-1).split(",").map(l=>l.trim()).filter(Boolean):e[a]=c}s=n[2]}return{frontmatter:e,body:s}}function Bd(t){let e=Gt.join(rs(),`${t}.md`);if(!Ie.existsSync(e))return{name:t,content:"",body:"",frontmatter:{}};let s=Ie.readFileSync(e,"utf-8"),{frontmatter:n,body:o}=Gs(s);return{name:t,content:s,body:o,frontmatter:n}}function Nw(t,e){let s=Gt.join(rs(),`${t}.md`);qd(s,e),Pw(t,e),Mw()}function Mw(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return;let t=wa();Ie.existsSync(t)&&setImmediate(async()=>{try{await zd()}catch{}})}function Lw(t){let e=Gt.join(rs(),`${t}.md`);return Ie.existsSync(e)?(Ie.unlinkSync(e),Iw(t),!0):!1}function xr(t){return t.toLowerCase().replace(/[^a-z0-9äöüß\s-]/g," ").split(/[\s-]+/).filter(e=>e.length>2&&!Ow.has(e))}function ba(t){let e={},{frontmatter:s,body:n}=Gs(t),o=Array.isArray(s.tags)?s.tags:[];for(let i of o){let a=i.toLowerCase().replace(/[^a-z0-9-]/g,"");a.length>1&&(e[a]=(e[a]||0)+5)}let r=(n||t).split(`
200
+ `);for(let i of r)if(i.startsWith("#")){let a=i.replace(/^#+\s*/,"");for(let c of xr(a))e[c]=(e[c]||0)+3}for(let i of xr(n||t))e[i]=(e[i]||0)+1;return e}function _a(){let t=kr();if(!Ie.existsSync(t))return{documents:{}};try{return JSON.parse(Ie.readFileSync(t,"utf-8"))}catch{return{documents:{}}}}function xa(t){qd(kr(),JSON.stringify(t,null,2))}function Pw(t,e){Fd(kr(),()=>{let s=_a(),{frontmatter:n}=Gs(e),o=Array.isArray(n.tags)?n.tags:[];s.documents[t]={keywords:ba(e),tags:o,modified:new Date().toISOString()},xa(s)})}function Iw(t){Fd(kr(),()=>{let e=_a();delete e.documents[t],xa(e)})}function $a(){let t=Hs(),e={documents:{}};for(let s of t){let n=Ie.readFileSync(s.path,"utf-8"),{frontmatter:o}=Gs(n),r=Array.isArray(o.tags)?o.tags:[];e.documents[s.name]={keywords:ba(n),tags:r,modified:s.modified.toISOString()}}return xa(e),e}function Wd(){let t=_a(),e=Hs();for(let s of e){let n=t.documents[s.name];if(!n||new Date(n.modified)<s.modified)return $a()}for(let s of Object.keys(t.documents))if(!e.some(n=>n.name===s))return $a();return t}function Ud(t,e={}){let{topK:s=3,minScore:n=.1}=e,o=xr(t);if(o.length===0)return[];let r=Wd(),i=[];for(let[a,c]of Object.entries(r.documents)){let l=0;for(let u of o){c.keywords[u]&&(l+=c.keywords[u]);for(let[d,f]of Object.entries(c.keywords))d!==u&&d.length>3&&u.length>3&&(d.includes(u)||u.includes(d))&&(l+=f*.3)}l>=n&&i.push({name:a,score:l})}return i.sort((a,c)=>c.score-a.score),i.slice(0,s)}var Hd=process.env.NEX_EMBED_MODEL||"nomic-embed-text",ya=400,jw=50;async function Gd(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return!1;try{let t=process.env.OLLAMA_HOST||"http://localhost:11434",e=require("http"),s=require("https"),n=new URL(`${t}/api/tags`),o=n.protocol==="https:"?s:e;return((await new Promise((a,c)=>{let l=o.get(n.toString(),{timeout:2e3},u=>{let d="";u.on("data",f=>d+=f),u.on("end",()=>{try{a(JSON.parse(d))}catch{c(new Error("bad json"))}})});l.on("error",c),l.on("timeout",()=>{l.destroy(),c(new Error("timeout"))})})).models||[]).map(a=>a.name).some(a=>a.startsWith(Hd.split(":")[0]))}catch{return!1}}async function ka(t){let e=process.env.OLLAMA_HOST||"http://localhost:11434",s=require("http"),n=require("https"),o=new URL(`${e}/api/embeddings`),r=o.protocol==="https:"?n:s,i=JSON.stringify({model:Hd,prompt:t});return new Promise((a,c)=>{let l=r.request(o,{method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(i)},timeout:3e4},u=>{let d="";u.on("data",f=>d+=f),u.on("end",()=>{try{a(JSON.parse(d).embedding||[])}catch(f){c(f)}})});l.on("error",c),l.on("timeout",()=>{l.destroy(),c(new Error("embedding timeout"))}),l.write(i),l.end()})}function Yd(t,e){if(!t||!e||t.length!==e.length)return 0;let s=0,n=0,o=0;for(let i=0;i<t.length;i++)s+=t[i]*e[i],n+=t[i]*t[i],o+=e[i]*e[i];let r=Math.sqrt(n)*Math.sqrt(o);return r===0?0:s/r}function Kd(t){let e=t.split(/\s+/),s=[],n=0;for(;n<e.length;){let o=e.slice(n,n+ya).join(" ");if(s.push({text:o,offset:n}),n+ya>=e.length)break;n+=ya-jw}return s}async function zd(){let t=Hs(),e={documents:{}},s=wa();if(Ie.existsSync(s))try{e=JSON.parse(Ie.readFileSync(s,"utf-8"))}catch{}for(let n of t){let o=e.documents[n.name];if(o&&new Date(o.modified)>=n.modified)continue;let r=Ie.readFileSync(n.path,"utf-8"),i=Kd(r),a=[];for(let c of i){let l=await ka(c.text);a.push({text:c.text,embedding:l,offset:c.offset})}e.documents[n.name]={chunks:a,modified:n.modified.toISOString()}}for(let n of Object.keys(e.documents))t.some(o=>o.name===n)||delete e.documents[n];return Ie.writeFileSync(s,JSON.stringify(e),"utf-8"),e}async function Xd(t,e={}){let{topK:s=3,minSimilarity:n=.3}=e,o=wa();if(!Ie.existsSync(o))return[];let r;try{r=JSON.parse(Ie.readFileSync(o,"utf-8"))}catch{return[]}let i=await ka(t),a=[];for(let[c,l]of Object.entries(r.documents||{})){let u=0,d="";for(let f of l.chunks||[]){let h=Yd(i,f.embedding);h>u&&(u=h,d=f.text)}u>=n&&a.push({name:c,score:u,bestChunk:d})}return a.sort((c,l)=>l.score-c.score),a.slice(0,s)}function Vd(t,e,s={}){let{k:n=60,topK:o=3}=s,r={};return t.forEach((i,a)=>{r[i.name]=(r[i.name]||0)+1/(n+a+1)}),e.forEach((i,a)=>{r[i.name]=(r[i.name]||0)+1/(n+a+1)}),Object.entries(r).map(([i,a])=>({name:i,score:a})).sort((i,a)=>a.score-i.score).slice(0,o)}async function Jd(t,e={}){let{topK:s=3,minScore:n=.1}=e,o=Ud(t,{topK:s,minScore:n}),r=o;if(process.env.NEX_BRAIN_EMBEDDINGS!=="false")try{if(await Gd()){let a=await Xd(t,{topK:s});r=Vd(o,a,{topK:s})}}catch{}return r.map(i=>{let a=Bd(i.name),c=(a.body||a.content||"").slice(0,300).replace(/\n+/g," ")+"...";return{name:i.name,score:i.score,content:a.content,excerpt:c}})}var os={queryKey:null,result:null,ts:0},Dw=3e5;async function qw(t){if(!t||!t.trim())return"";let e=Gt.join(process.cwd(),".nex","brain");if(!Ie.existsSync(e)||Hs().length===0)return"";let n=t.trim().toLowerCase().slice(0,200);if(os.result!==null&&os.queryKey===n&&Date.now()-os.ts<Dw)return os.result;let o;try{o=await Jd(t,{topK:3})}catch{return""}if(!o||o.length===0)return"";let r;try{r=Pt().estimateTokens}catch{r=u=>Math.ceil(u.length/4)}let i=25e3,a=[],c=0;for(let u of o){let d=u.content||"",f=r(d);if(c+f>i){let m=i-c;if(m<100)break;let g=m/f;d=d.slice(0,Math.floor(d.length*g))+`
201
+ ...(truncated)`}let h=typeof u.score=="number"?u.score.toFixed(2):String(u.score);if(a.push(`--- ${u.name} (relevance: ${h}) ---
202
+ ${d}`),c+=r(d),c>=i)break}if(a.length===0)return os={queryKey:n,result:"",ts:Date.now()},"";let l=`KNOWLEDGE BASE (auto-selected):
203
+
204
+ ${a.join(`
205
+
206
+ `)}`;return os={queryKey:n,result:l,ts:Date.now()},l}Zd.exports={getBrainDir:rs,listDocuments:Hs,readDocument:Bd,writeDocument:Nw,removeDocument:Lw,buildIndex:$a,getIndex:Wd,query:Jd,getBrainContext:qw,isEmbeddingAvailable:Gd,generateEmbedding:ka,buildEmbeddingIndex:zd,semanticQuery:Xd,cosineSimilarity:Yd,_keywordQuery:Ud,_extractKeywords:ba,_chunkText:Kd,parseFrontmatter:Gs,tokenize:xr,_fuseResults:Vd}});var zs=se((zk,df)=>{var Me=require("fs"),dt=require("path"),Fw=require("os"),{atomicWrite:vr,withFileLockSync:Qd}=fn(),Ys=["user","feedback","project","reference"],Bw=50;function wn(){return dt.join(process.cwd(),".nex","memory")}function is(){return dt.join(wn(),"memory.json")}function ef(){return dt.join(wn(),"MEMORY.md")}function Ww(){return dt.join(process.cwd(),"NEX.md")}function tf(){return dt.join(Fw.homedir(),".nex","NEX.md")}function Sr(){let t=wn();Me.existsSync(t)||Me.mkdirSync(t,{recursive:!0})}function nf(t){let e=dt.join(wn(),t);return Me.existsSync(e)||Me.mkdirSync(e,{recursive:!0}),e}function Ks(){let t=is();if(!Me.existsSync(t))return{};try{return JSON.parse(Me.readFileSync(t,"utf-8"))}catch{return{}}}function sf(t){Sr(),vr(is(),JSON.stringify(t,null,2))}function of(){let t=is();if(!Me.existsSync(t))return;let e=Ks(),s=Object.keys(e);if(s.length===0){try{Me.renameSync(t,t+".bak")}catch{}return}for(let n of s){let o=e[n],r=o.value||String(o),i=n.replace(/[^a-z0-9_-]/gi,"-").toLowerCase().replace(/-+/g,"-").replace(/^-|-$/g,"");if(!i)continue;let a=nf("project"),c=dt.join(a,`${i}.md`),l=r.split(`
207
+ `)[0].slice(0,100),u=`---
208
+ name: ${n}
209
+ description: ${l}
210
+ type: project
211
+ ---
212
+
213
+ ${r}
214
+ `;vr(c,u)}Er();try{Me.renameSync(t,t+".bak")}catch{}}function Uw(t,e,s,n){if(!Ys.includes(t))return{ok:!1,path:"",error:`Invalid type: ${t}. Must be one of: ${Ys.join(", ")}`};if(!e||typeof e!="string")return{ok:!1,path:"",error:"name must be a non-empty string"};if(!s||typeof s!="string"||s.trim().length<5)return{ok:!1,path:"",error:"content must be at least 5 characters"};let o=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase().replace(/-+/g,"-").replace(/^-|-$/g,"");if(!o)return{ok:!1,path:"",error:"name produces empty slug after sanitization"};let r=nf(t),i=dt.join(r,`${o}.md`);if(Me.existsSync(i))try{if(Sa(Me.readFileSync(i,"utf-8")).body.slice(0,200)===s.slice(0,200))return{ok:!0,path:i,updated:!1}}catch{}let a=n||s.split(`
215
+ `)[0].slice(0,100),c=`---
216
+ name: ${e}
217
+ description: ${a}
218
+ type: ${t}
219
+ ---
220
+
221
+ ${s}
222
+ `;return vr(i,c),Er(),{ok:!0,path:i,updated:!0}}function Hw(t,e){if(!Ys.includes(t))return!1;let s=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase(),n=dt.join(wn(),t,`${s}.md`);if(!Me.existsSync(n))return!1;try{return Me.unlinkSync(n),Er(),!0}catch{return!1}}function Sa(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 s=e[1],n=(e[2]||"").trim(),o=r=>{let i=s.match(new RegExp(`^${r}:\\s*(.+)$`,"m"));return i?i[1].trim():""};return{name:o("name"),description:o("description"),type:o("type"),body:n}}function rf(){let t=[],e=wn();for(let s of Ys){let n=dt.join(e,s);if(!Me.existsSync(n))continue;let o;try{o=Me.readdirSync(n).filter(r=>r.endsWith(".md"))}catch{continue}for(let r of o){let i=dt.join(n,r);try{let a=Me.readFileSync(i,"utf-8"),c=Sa(a);t.push({type:s,name:c.name||dt.basename(r,".md"),description:c.description,filePath:i})}catch{}}}return t}function Er(){let t=rf(),e=["# Project Memory Index",""];for(let s of t){if(e.length>=Bw+2)break;let n=`${s.type}/${dt.basename(s.filePath)}`;e.push(`- [${s.name}](${n}) \u2014 ${s.description||"(no description)"}`)}Sr(),vr(ef(),e.join(`
223
+ `)+`
224
+ `)}function af(){let t=ef();if(!Me.existsSync(t))return"";try{return Me.readFileSync(t,"utf-8").trim()}catch{return""}}function Gw(t,e){Sr(),Qd(is(),()=>{let s=Ks();s[t]={value:e,updatedAt:new Date().toISOString()},sf(s)})}function Yw(t){let e=Ks();return e[t]?e[t].value:null}function Kw(t){return Sr(),Qd(is(),()=>{let e=Ks();return t in e?(delete e[t],sf(e),!0):!1})}function cf(){let t=Ks();return Object.entries(t).map(([e,s])=>({key:e,value:s.value,updatedAt:s.updatedAt}))}function lf(){let t=tf();if(!Me.existsSync(t))return"";try{return Me.readFileSync(t,"utf-8").trim()}catch{return""}}function uf(){let t=Ww();if(!Me.existsSync(t))return"";try{return Me.readFileSync(t,"utf-8").trim()}catch{return""}}function zw(){of();let t=[],e=lf();e&&t.push(`GLOBAL INSTRUCTIONS (~/.nex/NEX.md):
225
+ ${e}`);let s=uf();s&&t.push(`PROJECT INSTRUCTIONS (NEX.md):
226
+ ${s}`);let n="",o=af();if(o)n=o;else{let d=cf();d.length>0&&(n=`PROJECT MEMORY:
227
+ ${d.map(h=>` ${h.key}: ${h.value}`).join(`
228
+ `)}`)}let r=t.join(`
229
+
230
+ `),i="You can save insights with save_memory(type, name, content) and remove them with delete_memory(type, name).",l=Math.max(1500,16e3-r.length-i.length-10);if(n.length>l&&l>200){let d=n.split(`
231
+ `),f="";for(let h of d){if(f.length+h.length+1>l-60)break;f+=h+`
232
+ `}n=f.trimEnd()+`
233
+ [Memory index truncated \u2014 use delete_memory to prune old entries]`}else n.length>l&&(n="");let u=[...t];return n&&u.push(n),u.length>0&&u.push(i),u.join(`
234
+
235
+ `)}df.exports={saveMemory:Uw,deleteMemory:Hw,scanMemories:rf,rebuildIndex:Er,loadMemoryIndex:af,remember:Gw,recall:Yw,forget:Kw,listMemories:cf,loadGlobalInstructions:lf,loadProjectInstructions:uf,getMemoryContext:zw,_getMemoryDir:wn,_getMemoryFile:is,_getGlobalNexMdPath:tf,_parseMemoryFile:Sa,_migrateIfNeeded:of,VALID_TYPES:Ys}});var yf=se((Xk,gf)=>{var Xs=require("fs"),Ea=require("path"),Ta=process.env.NEX_AUDIT!=="false",bn=null;function ff(){return bn||(bn=Ea.join(process.cwd(),".nex","audit"),Xs.existsSync(bn)||Xs.mkdirSync(bn,{recursive:!0}),bn)}function pf(){let t=new Date().toISOString().split("T")[0];return Ea.join(ff(),`${t}.jsonl`)}function Xw(t){if(Ta)try{let e={timestamp:new Date().toISOString(),tool:t.tool,args:hf(t.args),resultLength:typeof t.result=="string"?t.result.length:0,resultPreview:typeof t.result=="string"?t.result.substring(0,200):"",duration:t.duration||0,success:t.success!==!1,model:t.model||null,provider:t.provider||null},s=JSON.stringify(e)+`
236
+ `;Xs.appendFileSync(pf(),s,"utf-8")}catch{}}function hf(t){if(!t||typeof t!="object")return{};let e={};for(let[s,n]of Object.entries(t))/key|token|password|secret|credential/i.test(s)?e[s]="***":typeof n=="string"&&n.length>500?e[s]=n.substring(0,500)+`... (${n.length} chars)`:e[s]=n;return e}function mf(t={}){let e=ff(),s=t.days||1,n=[];for(let o=0;o<s;o++){let r=t.date||new Date(Date.now()-o*864e5).toISOString().split("T")[0],i=Ea.join(e,`${r}.jsonl`);if(!Xs.existsSync(i))continue;let a=Xs.readFileSync(i,"utf-8").split(`
237
+ `).filter(c=>c.trim());for(let c of a)try{let l=JSON.parse(c);if(t.tool&&l.tool!==t.tool)continue;n.push(l)}catch{}if(t.date)break}return n}function Vw(t=1){let e=mf({days:t});if(e.length===0)return{totalCalls:0,byTool:{},avgDuration:0,successRate:1};let s={},n=0,o=0;for(let r of e)s[r.tool]=(s[r.tool]||0)+1,n+=r.duration||0,r.success&&o++;return{totalCalls:e.length,byTool:s,avgDuration:Math.round(n/e.length),successRate:o/e.length}}function Jw(t){Ta=t}function Zw(){return Ta}function Qw(){bn=null}gf.exports={logToolExecution:Xw,sanitizeArgs:hf,readAuditLog:mf,getAuditSummary:Vw,setAuditEnabled:Jw,isAuditEnabled:Zw,getAuditLogPath:pf,_reset:Qw}});var Rf=se((Zk,Tf)=>{var je=require("fs").promises,$f=require("fs"),ve=require("path"),Ee=require("util").promisify(require("child_process").exec),Ra=require("util").promisify(require("child_process").execFile),{spawnSync:e0}=require("child_process"),Ca=require("axios"),{isForbidden:t0,isSSHForbidden:n0,isDangerous:s0,isCritical:wf,isBashPathForbidden:o0,confirm:kt}=Es(),{showClaudeDiff:Tr,showClaudeNewFile:r0,showEditDiff:Vk,confirmFileChange:Vs}=Vl(),{C:ae,Spinner:i0,getToolSpinnerText:a0}=Ue(),{isGitRepo:Aa,getCurrentBranch:bf,getStatus:c0,getDiff:l0}=er(),{recordChange:Rr}=iu(),{fuzzyFindText:_f,findMostSimilar:Qs}=Au(),{runDiagnostics:Js}=Nu(),{findFileInIndex:u0,getFileIndex:Jk}=sa(),{resolveProfile:$t,sshExec:ot,scpUpload:d0,scpDownload:f0}=ra(),{resolveDeployConfig:p0,loadDeployConfigs:h0}=Gu(),{getEditMode:xf}=Is(),m0=/^(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/,g0=/^ssh\s/,y0=/^ssh(?:\s+-\S+)*\s+\S+@?\S+\s+["']?[^-]/;async function ft(t){return je.access(t).then(()=>!0).catch(()=>!1)}async function Cr(t){if(!t)return{fixedPath:null,message:""};let e=t.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),s=rt(e);if(s&&await ft(s))return{fixedPath:s,message:`(auto-fixed path: ${t} \u2192 ${e})`};let n=[".js",".ts",".jsx",".tsx",".mjs",".cjs",".json"],o=ve.extname(t);if(!o)for(let i of n){let a=rt(t+i);if(a&&await ft(a))return{fixedPath:a,message:`(auto-fixed: added ${i} extension)`}}if(o){let i=t.replace(/\.[^.]+$/,"");for(let a of n){if(a===o)continue;let c=rt(i+a);if(c&&await ft(c))return{fixedPath:c,message:`(auto-fixed: ${o} \u2192 ${a})`}}}let r=ve.basename(t);if(r&&r.length>2)try{let i=u0(r).map(a=>rt(a));if(i.length===1)return{fixedPath:i[0],message:`(auto-fixed: found ${r} at ${ve.relative(process.cwd(),i[0])})`};if(i.length>1&&i.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
238
+ ${i.map(c=>ve.relative(process.cwd(),c)).map(c=>` - ${c}`).join(`
239
+ `)}`}}catch{}return{fixedPath:null,message:""}}function $0(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 Sf(t,e){let s=[];if(/command not found|: not found|not recognized/i.test(t)){let n=e.match(/^(\S+)/),o=n?n[1]:"";/^(npx|npm|node|yarn|pnpm|bun)$/.test(o)?s.push("HINT: Node.js/npm may not be in PATH. Check your Node.js installation."):/^(python|python3|pip|pip3)$/.test(o)?s.push("HINT: Python may not be installed. Try: brew install python3 (macOS) or apt install python3 (Linux)"):s.push(`HINT: "${o}" is not installed. Try installing it with your package manager.`)}if(/Cannot find module|MODULE_NOT_FOUND/i.test(t)){let n=t.match(/Cannot find module '([^']+)'/),o=n?n[1]:"";o&&!o.startsWith(".")&&!o.startsWith("/")?s.push(`HINT: Missing npm package "${o}". Run: npm install ${o}`):s.push("HINT: Module not found. Check the import path or run npm install.")}if(/permission denied|EACCES/i.test(t)&&s.push("HINT: Permission denied. Check file permissions or try a different approach."),/EADDRINUSE|address already in use/i.test(t)){let n=t.match(/port (\d+)|:(\d+)/),o=n?n[1]||n[2]:"";s.push(`HINT: Port ${o||""} is already in use. Kill the process or use a different port.`)}if(/SyntaxError|Unexpected token/i.test(t)&&s.push("HINT: Syntax error in the code. Check the file at the line number shown above."),/TS\d{4}:/i.test(t)&&s.push("HINT: TypeScript compilation error. Fix the type issue at the indicated line."),/Test Suites:.*failed|Tests:.*failed/i.test(t)&&s.push("HINT: Test failures detected. Read the error output above to identify failing tests."),/fatal: not a git repository/i.test(t)&&s.push("HINT: Not inside a git repository. Run git init or cd to a git project."),/^curl\b/.test(e)){let n=t.match(/curl:\s*\((\d+)\)/),o=n?parseInt(n[1],10):null;o===6||/Could not resolve host/i.test(t)?s.push("HINT: Hostname could not be resolved. Check DNS or use an IP address directly."):o===7||/Failed to connect|Connection refused/i.test(t)?s.push("HINT: Service not running or port wrong. Check if the service is up and the port is correct."):o===22||/HTTP error/i.test(t)?s.push("HINT: HTTP 4xx/5xx response. The endpoint exists but returned an error status."):o===28||/timed out/i.test(t)?s.push("HINT: Request timed out. The host may be unreachable or the service is slow."):(o===35||/SSL.*error/i.test(t))&&s.push("HINT: SSL/TLS handshake failed. Try with --insecure to bypass, or check the certificate.")}if(/remote port forwarding failed/i.test(t)){let n=t.match(/port (\d+)/),o=n?n[1]:"";s.push(`HINT: SSH remote port forwarding failed for port ${o}. The port may already be bound on the server. Check with: ssh server "ss -tuln | grep ${o}" and kill any lingering process with that port.`)}return/bind.*Cannot assign requested address|Address already in use/i.test(t)&&s.push("HINT: Port is already in use. Find the process with: ss -tuln | grep <port> and kill it, then retry."),/Connection.*timed out|ssh.*timeout/i.test(t)&&/^ssh\b/.test(e)&&s.push("HINT: SSH connection timed out. Check if the host is reachable: ping <host> and verify the port with: nc -zv <host> 22"),/spawn \/bin\/sh ENOENT|spawn sh ENOENT/i.test(t)&&s.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)&&s.push('HINT: Using both cp with .bak and sed -i.bak creates double backups (.bak.bak). Choose one method: either cp "$f" "$f.bak" OR sed -i.bak, not both.'),s.length===0?t:t+`
240
+
241
+ `+s.join(`
242
+ `)}function Ef(t,e,s){let n=Qs(t,e);if(!n)return null;let o=Math.max(2,Math.ceil(e.length*.03));return n.distance>o?null:{autoFixed:!0,matchText:n.text,content:t.split(n.text).join(s),distance:n.distance,line:n.line}}var kf=!1,_n=null;function w0(){_n&&(_n(),_n=null)}var Na=null;function b0(t){Na=t}async function Oa(){if(!kf){kf=!0;try{let{stdout:t}=await Ee("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await Ee('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await Ee("git stash pop",{cwd:process.cwd(),timeout:1e4}),await Ee("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var _0=[/\.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 rt(t){let e=ve.isAbsolute(t)?ve.resolve(t):ve.resolve(process.cwd(),t);for(let s of _0)if(s.test(e))return null;return e}var x0=[{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 Zs(t,{server:e,context:s}={}){let n=e?e.replace(/[^a-zA-Z0-9@._-]/g,""):null,o=s?s.replace(/[^a-zA-Z0-9._/-]/g,""):null,r="kubectl";if(o&&(r+=` --context ${o}`),r+=` ${t}`,n){let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`ssh -o ConnectTimeout=10 -o BatchMode=yes ${n} "${i}"`}return r}async function vf(t,e,s={}){switch(t){case"bash":{let n=e.command,o=t0(n);if(o){let d=$0(n);return`BLOCKED: Command matches forbidden pattern: ${o}${d?`
243
+ HINT: ${d}`:""}`}let r=o0(n);if(r)return`BLOCKED: Destructive operation on protected path: ${r}
244
+ HINT: Protected files (.env, credentials, venv, .ssh, etc.) cannot be deleted or moved via bash. Override with NEX_UNPROTECT=1 if intentional.`;if(s.autoConfirm?wf(n):s0(n)){let d=wf(n)?"\u26D4":"\u26A0";if(!await kt(` ${d} bash: \`${n}\``,{toolName:"bash"}))return"CANCELLED: User declined to execute this command."}let a;try{a=process.cwd(),$f.accessSync(a)}catch{a=require("os").homedir(),s.silent||console.log(`${ae.yellow} \u26A0 Working directory no longer exists \u2014 running in ${a}${ae.reset}`)}let c=g0.test(n.trim())&&!y0.test(n.trim());if(m0.test(n.trim())||c){s.silent||console.log(`${ae.dim} \u25B6 interactive: ${n}${ae.reset}`);let d=e0("sh",["-c",n],{stdio:"inherit",cwd:a});return d.error?`ERROR: ${d.error.message}`:d.status===0?"(interactive command completed successfully)":`(interactive command exited with code ${d.status})`}let{ToolProgress:l}=Hn(),u=s.silent?null:new l("bash",n.substring(0,40));u&&u.start();try{let{stdout:d,stderr:f}=await Ee(n,{cwd:a,timeout:9e4,maxBuffer:5242880});return u&&u.stop(),d||f||"(no output)"}catch(d){u&&u.stop();let f=(d.stderr||d.stdout||d.message||"").toString().substring(0,5e3),h=Sf(f,n);return`EXIT ${d.code||1}
245
+ ${h}`}}case"read_file":{let n=rt(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await ft(n)){let C=await Cr(e.path);if(C.fixedPath)n=C.fixedPath,console.log(`${ae.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ve.relative(process.cwd(),n)}${ae.reset}`);else return`ERROR: File not found: ${e.path}${C.message?`
246
+ `+C.message:""}`}let r=Buffer.alloc(8192),i=await $f.promises.open(n,"r"),{bytesRead:a}=await i.read(r,0,8192,0);await i.close();for(let C=0;C<a;C++)if(r[C]===0)return`ERROR: ${n} is a binary file (not readable as text)`;let c=await je.readFile(n,"utf-8");if(!c&&(await je.stat(n)).size>0)return`WARNING: ${n} is empty or unreadable`;let l=c.split(`
247
+ `),u=await je.stat(n),d=l.length,f=350,h=!e.line_start&&!e.line_end,m=h&&d>f,g=(e.line_start||1)-1,b=m?f:e.line_end||l.length,v=ve.relative(process.cwd(),n),O=m?`showing lines 1-${f} of ${d}`:e.line_start||e.line_end?`lines ${g+1}-${b} of ${d}`:`${d} lines`,U=`File: ${v} (${O}, ${u.size} bytes)`,L=l.slice(g,b).map((C,K)=>`${g+K+1}: ${C}`).join(`
248
+ `),R=m?`
249
+
250
+ [File truncated: showing lines 1-${f} of ${d} total. Use line_start/line_end to read other sections, e.g. line_start=${f+1} line_end=${Math.min(f*2,d)}]`:!h&&d>f?`
251
+ [Large file (${d} lines total) \u2014 use line_start/line_end for other sections]`:"";return`${U}
252
+ ${L}${R}`}case"write_file":{await Oa();let n=rt(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let o=await ft(n),r=null;if(s.autoConfirm)o&&(r=await je.readFile(n,"utf-8"));else if(o){r=await je.readFile(n,"utf-8");let u=await Js(n,e.content);if(Tr(n,r,e.content,{annotations:u}),!await Vs("Overwrite"))return"CANCELLED: User declined to overwrite file."}else{let u=await Js(n,e.content);if(r0(n,e.content,{annotations:u}),!await Vs("Create"))return"CANCELLED: User declined to create file."}let i=ve.dirname(n);await ft(i)||await je.mkdir(i,{recursive:!0}),await je.writeFile(n,e.content,"utf-8");let c=/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||e.content.startsWith("#!");c&&await je.chmod(n,493),Rr("write_file",n,r,e.content);let l=c?" [chmod +x applied]":"";return`Written: ${n} (${e.content.length} chars)${l}`}case"edit_file":{await Oa();let n=rt(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await ft(n)){let u=await Cr(e.path);if(u.fixedPath)n=u.fixedPath,console.log(`${ae.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ve.relative(process.cwd(),n)}${ae.reset}`);else return`ERROR: File not found: ${e.path}${u.message?`
253
+ `+u.message:""}`}let r=await je.readFile(n,"utf-8"),i=e.old_text,a=!1,c=!1;if(!r.includes(e.old_text)){let{getActiveModelId:u,getActiveProviderName:d}=He();if(xf(u(),d())==="strict"){let m=Qs(r,e.old_text);return m?`ERROR: old_text not found in ${n} (strict mode \u2014 exact match required)
254
+ Most similar text (line ${m.line}, distance ${m.distance}):
255
+ ${m.text}`:`ERROR: old_text not found in ${n} (strict mode \u2014 exact match required)`}let h=_f(r,e.old_text);if(h)i=h,a=!0,console.log(`${ae.dim} \u2713 fuzzy whitespace match applied${ae.reset}`);else{let m=Ef(r,e.old_text,e.new_text);if(m){if(!s.autoConfirm){let U=await Js(n,m.content);if(Tr(n,r,m.content,{annotations:U}),!await Vs(`Apply (auto-fix, line ${m.line}, distance ${m.distance})`))return"CANCELLED: User declined to apply edit."}await je.writeFile(n,m.content,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||m.content.startsWith("#!"))&&await je.chmod(n,493),Rr("edit_file",n,r,m.content);let O=m.matchText.length>80?m.matchText.substring(0,77)+"...":m.matchText;return console.log(`${ae.dim} \u2713 auto-fixed edit: line ${m.line}, distance ${m.distance}${ae.reset}`),`Edited: ${n} (auto-fixed, line ${m.line}, distance ${m.distance}, matched: "${O}")`}let g=Qs(r,e.old_text);if(g){let O=r.split(`
256
+ `),U=Math.max(0,g.line-6),L=Math.min(O.length,g.line+10),R=O.slice(U,L).map((K,Q)=>`${U+Q+1}: ${K}`).join(`
257
+ `),C=`line_start=${Math.max(1,g.line-5)} line_end=${Math.min(O.length,g.line+15)}`;return`ERROR: old_text not found in ${n} (most similar at line ${g.line}, distance ${g.distance})
258
+
259
+ Actual file content around line ${g.line} \u2014 use this to correct old_text:
260
+ ${R}
261
+
262
+ Fix: update old_text to match the exact lines above, then retry. If you need more context: read_file with ${C}`}let b=(e.old_text||"").trim().split(`
263
+ `)[0].slice(0,60),v=b?`
264
+ Recovery: grep -n "${b.replace(/"/g,'\\"')}" <file> to find the line, then re-read that section with line_start/line_end.`:`
265
+ 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 ${n}${v}`}}if(!s.autoConfirm){let u=r.split(i).join(e.new_text),d=await Js(n,u);if(Tr(n,r,u,{annotations:d}),!await Vs(a?"Apply (fuzzy match)":"Apply"))return"CANCELLED: User declined to apply edit."}let l=r.split(i).join(e.new_text);return await je.writeFile(n,l,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||l.startsWith("#!"))&&await je.chmod(n,493),Rr("edit_file",n,r,l),a?`Edited: ${n} (fuzzy match)`:`Edited: ${n}`}case"list_directory":{let n=rt(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await ft(n)){let l=e.path.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),u=rt(l),d=await ft(u);if(u&&d)n=u;else return`ERROR: Directory not found: ${e.path}`}let r=e.max_depth||2,i=null;if(e.pattern)try{let l=e.pattern.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");i=new RegExp(`^${l}$`)}catch{return`ERROR: Invalid pattern: ${e.pattern}`}let a=[],c=async(l,u,d)=>{if(u>r)return;let f;try{f=await je.readdir(l,{withFileTypes:!0})}catch{return}f=f.filter(h=>!h.name.startsWith(".")&&h.name!=="node_modules");for(let h of f){if(i&&!h.isDirectory()&&!i.test(h.name))continue;let m=h.isDirectory()?"/":"";a.push(`${d}${h.name}${m}`),h.isDirectory()&&await c(ve.join(l,h.name),u+1,d+" ")}};return await c(n,1,""),a.join(`
266
+ `)||"(empty)"}case"search_files":{let n=rt(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let o=["-rn","--null","-H"];e.file_pattern&&o.push(`--include=${e.file_pattern}`),o.push(e.pattern,n);try{let{stdout:r}=await Ra("grep",o,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),i=r.split("\0"),a=[];for(let c=0;c<i.length;c+=2){let l=i[c],u=i[c+1];if(l&&u){let d=u.split(`
267
+ `).filter(f=>f.trim());for(let f of d)if(a.push(`${l}:${f}`),a.length>=50)break}if(a.length>=50)break}return a.join(`
268
+ `)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let o=process.cwd(),r=e.path?rt(e.path):o,i=e.pattern,a=Q=>{let re=Q.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"(.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");return new RegExp(`^${re}$`)},c=a(i),l=i.split("/").pop(),u=a(l),{ToolProgress:d}=Hn(),f=new d("glob","Finding files...");f.start();let{getFileIndex:h,getIndexedCwd:m,refreshIndex:g,isIndexValid:b}=sa(),v=h(),O=m();b(r)||(await g(r),v=h());let U=v.filter(Q=>c.test(Q)||u.test(ve.basename(Q))).map(Q=>ve.join(r,Q));if(U.length===0)return f.stop(),"(no matches)";let L=await Promise.all(U.slice(0,210).map(async Q=>{try{let re=await je.stat(Q);return{path:Q,mtime:re.mtimeMs}}catch{return{path:Q,mtime:0}}}));L.sort((Q,re)=>re.mtime-Q.mtime);let R=L.map(Q=>Q.path),C=U.length>200,K=R.slice(0,200).join(`
269
+ `);return f.update({count:U.length,detail:e.pattern}),f.stop(),C?`${K}
270
+
271
+ \u26A0 Results truncated at 200. Use a more specific pattern.`:K}case"grep":{let n=e.path?rt(e.path):process.cwd();if(e.staged){let{getDiff:c}=er(),l=await c(!0);if(!l.trim())return"(no staged changes)";let u=new Set,d=l.split(`
272
+ `);for(let b of d)if(b.startsWith("diff --git")){let v=b.match(/diff --git a\/(.+) b\/(.+)/);v&&u.add(v[2])}let f=["-rn","-E","--null","-H","--exclude=*.md","--exclude=*.txt","--exclude=*.json","--exclude=*.yaml","--exclude=*.yml"];e.ignore_case&&f.push("-i"),e.include&&f.push(`--include=${e.include}`),e.type&&f.push(`--include=*.${e.type}`),e.context?f.push("-C",String(e.context)):(e.before_context&&f.push("-B",String(e.before_context)),e.after_context&&f.push("-A",String(e.after_context))),e.output_mode==="files_with_matches"?f.push("-l"):e.output_mode==="count"&&f.push("-c"),f.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage");let{ToolProgress:h}=Hn(),m=new h("grep","Searching staged content...");m.start();let g=[];for(let b of u)try{let v=ve.join(process.cwd(),b);if(await ft(v)){let O=[...f];O.push(e.pattern,v);let{stdout:U}=await Ra("grep",O,{cwd:process.cwd(),timeout:3e4,maxBuffer:2*1024*1024});if(e.output_mode==="files_with_matches"||e.output_mode==="count"){let L=U.trim().split(`
273
+ `).filter(R=>R.trim());g=g.concat(L)}else{let L=U.split("\0");for(let R=0;R<L.length;R+=2){let C=L[R+1];if(C){let K=C.split(`
274
+ `).filter(Q=>Q.trim());for(let Q of K)g.push(`${b}:${Q}`)}}}}}catch{}return m.update({count:g.length,detail:"in staged files"}),m.stop(),g.join(`
275
+ `).trim()||"(no matches in staged files)"}let o=["-rn","-E","--null","-H"];e.ignore_case&&o.push("-i"),e.include&&o.push(`--include=${e.include}`),e.type&&o.push(`--include=*.${e.type}`);let r=20;e.context?o.push("-C",String(Math.min(Number(e.context),r))):(e.before_context&&o.push("-B",String(Math.min(Number(e.before_context),r))),e.after_context&&o.push("-A",String(Math.min(Number(e.after_context),r)))),e.output_mode==="files_with_matches"?o.push("-l"):e.output_mode==="count"&&o.push("-c"),o.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage"),o.push(e.pattern,n);let{ToolProgress:i}=Hn(),a=new i("grep","Searching...");a.start();try{let{stdout:c}=await Ra("grep",o,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),l;if(e.output_mode==="files_with_matches"||e.output_mode==="count")l=c.trim().split(`
276
+ `).filter(f=>f.trim());else{let f=c.split("\0");l=[];for(let h=0;h<f.length;h+=2){let m=f[h],g=f[h+1];if(m&&g){let b=g.split(`
277
+ `).filter(v=>v.trim());for(let v of b)l.push(`${m}:${v}`)}}}let u=e.offset||0,d=e.head_limit||(e.output_mode==="files_with_matches"?200:100);return l=l.slice(u,u+d),a.update({count:l.length,detail:`in ${n}`}),a.stop(),l.join(`
278
+ `).trim()||"(no matches)"}catch(c){return a.stop(),c.code===2?`ERROR: Invalid regex pattern: ${e.pattern}`:"(no matches)"}}case"patch_file":{await Oa();let n=rt(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await ft(n)){let v=await Cr(e.path);if(v.fixedPath)n=v.fixedPath,console.log(`${ae.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ve.relative(process.cwd(),n)}${ae.reset}`);else return`ERROR: File not found: ${e.path}${v.message?`
279
+ `+v.message:""}`}let r=e.patches;if(!Array.isArray(r)||r.length===0)return"ERROR: No patches provided";let i=await je.readFile(n,"utf-8"),{getActiveModelId:a,getActiveProviderName:c}=He(),l=xf(a(),c()),u=[],d=!1,f=!1;for(let v=0;v<r.length;v++){let{old_text:O,new_text:U}=r[v];if(i.includes(O))u.push({old_text:O,new_text:U});else if(l==="strict"){let L=Qs(i,O);return L?`ERROR: Patch ${v+1} old_text not found in ${n} (strict mode \u2014 exact match required)
280
+ Most similar text (line ${L.line}, distance ${L.distance}):
281
+ ${L.text}`:`ERROR: Patch ${v+1} old_text not found in ${n} (strict mode \u2014 exact match required)`}else{let L=_f(i,O);if(L)u.push({old_text:L,new_text:U}),d=!0;else{let R=Qs(i,O);if(R){let C=Math.max(3,Math.ceil(O.length*.05));if(R.distance<=C)u.push({old_text:R.text,new_text:U}),f=!0;else return`ERROR: Patch ${v+1} old_text not found in ${n}
282
+ Most similar text (line ${R.line}, distance ${R.distance}):
283
+ ${R.text}`}else return`ERROR: Patch ${v+1} old_text not found in ${n}`}}}let h=i;for(let{old_text:v,new_text:O}of u)h=h.split(v).join(O);if(!s.autoConfirm){let v=await Js(n,h);if(Tr(n,i,h,{annotations:v}),!await Vs(d?"Apply patches (fuzzy match)":"Apply patches"))return"CANCELLED: User declined to apply patches."}await je.writeFile(n,h,"utf-8");let m=/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||h.startsWith("#!");m&&await je.chmod(n,493),Rr("patch_file",n,i,h);let g=f?" (auto-fixed)":d?" (fuzzy match)":"",b=m?" [chmod +x applied]":"";return`Patched: ${n} (${r.length} replacements)${g}${b}`}case"web_fetch":{let n=e.url,o=e.max_length||1e4;try{let r=await Ca.get(n,{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,o)||"(empty response)"}catch(r){return`ERROR: Failed to fetch ${n}: ${r.message}`}}case"web_search":{let n=e.max_results||5;if(process.env.PERPLEXITY_API_KEY)try{let o=await Ca.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=o.data?.choices?.[0]?.message?.content||"",i=o.data?.citations||[],a=`[Perplexity grounded search]
284
+
285
+ ${r}`;return i.length>0&&(a+=`
286
+
287
+ Sources:
288
+ `+i.slice(0,n).map((c,l)=>`${l+1}. ${c}`).join(`
289
+ `)),a}catch(o){console.error(`${ae.dim} Perplexity search failed (${o.message}), falling back to DuckDuckGo${ae.reset}`)}try{let r=(await Ca.get("https://html.duckduckgo.com/html/",{params:{q:e.query},timeout:1e4,responseType:"text",headers:{"User-Agent":"nex-code/0.2.0"}})).data,i=[],a=/<a[^>]*class="result__a"[^>]*href="([^"]*)"[^>]*>([\s\S]*?)<\/a>/gi,c;for(;(c=a.exec(r))!==null&&i.length<n;){let l=c[1].replace(/.*uddg=/,"").split("&")[0],u=c[2].replace(/<[^>]+>/g,"").trim();try{i.push({title:u,url:decodeURIComponent(l)})}catch{i.push({title:u,url:l})}}return i.length===0?"(no results)":i.map((l,u)=>`${u+1}. ${l.title}
290
+ ${l.url}`).join(`
291
+
292
+ `)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:n}=Ds();try{let o=await n(e.url,{waitFor:e.wait_for}),r=o.links.length>0?`
293
+
294
+ Links:
295
+ `+o.links.map(i=>` ${i.text} \u2192 ${i.href}`).join(`
296
+ `):"";return`Title: ${o.title}
297
+ URL: ${o.url}
298
+
299
+ ${o.text}${r}`}catch(o){return`ERROR: ${o.message}`}}case"browser_screenshot":{let{browserScreenshot:n}=Ds();try{let o=await n(e.url,{width:e.width,height:e.height,fullPage:e.full_page});return`Screenshot saved: ${o.path}
300
+ Title: ${o.title}
301
+ URL: ${o.url}
302
+
303
+ To analyze visually, paste the path into your next message: ${o.path}`}catch(o){return`ERROR: ${o.message}`}}case"browser_click":{let{browserClick:n}=Ds();try{return await n(e.url,{selector:e.selector,text:e.text})}catch(o){return`ERROR: ${o.message}`}}case"browser_fill":{let{browserFill:n}=Ds();try{return await n(e.url,{selector:e.selector,value:e.value,submit:e.submit})}catch(o){return`ERROR: ${o.message}`}}case"ask_user":{let{question:n,options:o=[]}=e;return Na?new Promise(r=>{_n=()=>r("CANCELLED"),Na(n,o).then(i=>{_n=null,r(i||"User did not answer")})}):new Promise(r=>{let i=require("readline").createInterface({input:process.stdin,output:process.stdout});_n=()=>{i.close(),r("CANCELLED")};let a=o.length>0?`
304
+ ${o.map((c,l)=>` ${l+1}. ${c}`).join(`
305
+ `)}
306
+ `:"";console.log(`
307
+ ${ae.cyan}${ae.bold} ? ${n}${ae.reset}${a}`),i.question(`${ae.cyan} > ${ae.reset}`,c=>{_n=null,i.close(),r(c.trim()||"(no response)")})})}case"git_status":{if(!await Aa())return"ERROR: Not a git repository";let n=await bf()||"(detached)",o=await c0();if(o.length===0)return`Branch: ${n}
308
+ Clean working tree (no changes)`;let r=[`Branch: ${n}`,`Changed files (${o.length}):`];for(let i of o){let a=i.status==="M"?"modified":i.status==="A"?"added":i.status==="D"?"deleted":i.status==="??"?"untracked":i.status;r.push(` ${a}: ${i.file}`)}return r.join(`
309
+ `)}case"git_diff":{if(!await Aa())return"ERROR: Not a git repository";let n;if(e.file){let o=["diff"];e.staged&&o.push("--cached"),o.push("--",e.file);try{n=execFileSync("git",o,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()}catch{n=""}}else n=await l0(!!e.staged);return n||"(no diff)"}case"git_log":{if(!await Aa())return"ERROR: Not a git repository";let o=["log","--oneline",`-${Math.min(e.count||10,50)}`];e.file&&o.push("--",e.file);try{return execFileSync("git",o,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()||"(no commits)"}catch{return"(no commits)"}}case"task_list":{let{createTasks:n,updateTask:o,getTaskList:r,renderTaskList:i,hasActiveTasks:a}=ua(),{getActiveTaskProgress:c}=Ue(),l=c();switch(e.action){case"create":{if(!e.name||!e.tasks)return"ERROR: task_list create requires name and tasks";let u=n(e.name,e.tasks);return l||console.log(`
310
+ `+i()),`Created task list "${e.name}" with ${u.length} tasks:
311
+ `+u.map(d=>` ${d.id}: ${d.description}`).join(`
312
+ `)}case"update":return!e.task_id||!e.status?"ERROR: task_list update requires task_id and status":o(e.task_id,e.status,e.result)?(l||console.log(`
313
+ `+i()),`Updated ${e.task_id}: ${e.status}${e.result?" \u2014 "+e.result:""}`):`ERROR: Task not found: ${e.task_id}`;case"get":{let u=r();return u.tasks.length===0?"No active tasks":(l||console.log(`
314
+ `+i()),JSON.stringify(u,null,2))}default:return`ERROR: Unknown task_list action: ${e.action}. Use: create, update, get`}}case"spawn_agents":{let{executeSpawnAgents:n}=ga();return n(e)}case"switch_model":{let{setActiveModel:n,getActiveProviderName:o,getActiveModelId:r}=He();return n(e.model)?`Switched to ${o()}:${r()}`:`ERROR: Unknown model: ${e.model}. Use /providers to see available models.`}case"gh_run_list":{let n=Math.min(e.limit||10,30),o=["run","list","--limit",String(n),"--json","databaseId,status,conclusion,name,headBranch,createdAt,updatedAt,event"];e.workflow&&o.push("--workflow",e.workflow),e.branch&&o.push("--branch",e.branch),e.status&&o.push("--status",e.status);try{let{stdout:r}=await Ee(`gh ${o.join(" ")}`,{cwd:process.cwd(),timeout:3e4}),i=JSON.parse(r||"[]");return i.length===0?"No workflow runs found.":i.map(c=>{let l=c.conclusion||c.status||"unknown",u=l==="success"?"\u2713":l==="failure"?"\u2717":l==="in_progress"?"\u283F":"\u25CB",d=c.updatedAt?new Date(c.updatedAt).toISOString().slice(0,16).replace("T"," "):"";return`${u} [${c.databaseId}] ${c.name} \xB7 ${c.headBranch} \xB7 ${l} \xB7 ${d}`}).join(`
315
+ `)}catch(r){let i=(r.stderr||r.message||"").toString();return i.includes("not found")||i.includes("not logged")?"ERROR: gh CLI not found or not authenticated. Run: gh auth login":`ERROR: ${i.split(`
316
+ `)[0]}`}}case"gh_run_view":{if(!e.run_id)return"ERROR: run_id is required";try{if(e.log){let{stdout:i}=await Ee(`gh run view ${e.run_id} --log`,{cwd:process.cwd(),timeout:6e4,maxBuffer:5242880});return i.substring(0,8e3)+(i.length>8e3?`
317
+ ...(truncated)`:"")}let{stdout:n}=await Ee(`gh run view ${e.run_id} --json status,conclusion,name,headBranch,createdAt,updatedAt,jobs`,{cwd:process.cwd(),timeout:3e4}),o=JSON.parse(n),r=[`Run: ${o.name} [${e.run_id}]`,`Branch: ${o.headBranch} Status: ${o.conclusion||o.status}`,`Started: ${o.createdAt} Finished: ${o.updatedAt||"\u2014"}`,"","Jobs:"];for(let i of o.jobs||[]){let a=i.conclusion==="success"?"\u2713":i.conclusion==="failure"?"\u2717":"\u25CB";r.push(` ${a} ${i.name} (${i.conclusion||i.status})`);for(let c of i.steps||[]){if(c.conclusion==="failure"||c.conclusion==="skipped")continue;let l=c.conclusion==="success"?" \u2713":c.conclusion==="failure"?" \u2717":" \u25CB";r.push(` ${l} ${c.name}`)}}return r.join(`
318
+ `)}catch(n){return`ERROR: ${(n.stderr||n.message||"").toString().split(`
319
+ `)[0]}`}}case"gh_workflow_trigger":{if(!e.workflow)return"ERROR: workflow is required";let{confirm:n}=Es(),o=e.branch||await bf()||"main",r=e.inputs?Object.entries(e.inputs).map(([c,l])=>`-f ${c}=${l}`).join(" "):"",i=`gh workflow run ${e.workflow} --ref ${o} ${r}`.trim();if(console.log(`
320
+ ${ae.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${o}${ae.reset}`),!await n(" Trigger?"))return"CANCELLED: User declined to trigger workflow.";try{return await Ee(i,{cwd:process.cwd(),timeout:3e4}),`Workflow "${e.workflow}" triggered on branch "${o}". Check status with gh_run_list.`}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
321
+ `)[0]}`}}case"k8s_pods":{let n=e.namespace?`-n ${e.namespace}`:"-A",o=e.label?`-l ${e.label}`:"",r=Zs(`get pods ${n} ${o} -o wide`.trim(),e);try{let{stdout:i,stderr:a}=await Ee(r,{timeout:3e4,maxBuffer:2097152});return(i||a||"(no pods)").trim()}catch(i){let a=(i.stderr||i.message||"").toString().split(`
322
+ `)[0];return a.includes("command not found")?"ERROR: kubectl not found. Install kubectl or provide a server with kubectl.":`ERROR: ${a}`}}case"k8s_logs":{if(!e.pod)return"ERROR: pod is required";let n=e.namespace||"default",o=e.tail||100,r=`logs ${e.pod} -n ${n} --tail=${o}`;e.since&&(r+=` --since=${e.since}`),e.container&&(r+=` -c ${e.container}`);let i=Zs(r,e);try{let{stdout:a,stderr:c}=await Ee(i,{timeout:6e4,maxBuffer:5242880}),l=(a||c||"(no logs)").trim();return l.substring(0,2e4)+(l.length>2e4?`
323
+ ...(truncated)`:"")}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
324
+ `)[0]}`}}case"k8s_exec":{if(!e.pod)return"ERROR: pod is required";if(!e.command)return"ERROR: command is required";let n=e.namespace||"default";if(console.log(`
325
+ ${ae.yellow} \u26A0 kubectl exec into pod: ${e.pod} (ns: ${n})${ae.reset}`),console.log(`${ae.dim} Command: ${e.command}${ae.reset}`),!await kt(" Execute in pod?"))return"CANCELLED: User declined.";let r=`exec ${e.pod} -n ${n}`;e.container&&(r+=` -c ${e.container}`),r+=` -- sh -c ${JSON.stringify(e.command)}`;let i=Zs(r,e);try{let{stdout:a,stderr:c}=await Ee(i,{timeout:6e4,maxBuffer:2097152});return(a||c||"(no output)").trim()}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
326
+ `)[0]}`}}case"k8s_apply":{if(!e.file)return"ERROR: file is required";let n=!!e.dry_run;if(!n){let i=e.file;if(console.log(`
327
+ ${ae.yellow} \u26A0 kubectl apply: ${i}${e.namespace?` (ns: ${e.namespace})`:""}${ae.reset}`),!await kt(" Apply to cluster?"))return"CANCELLED: User declined."}let o=`apply -f ${e.file}`;e.namespace&&(o+=` -n ${e.namespace}`),n&&(o+=" --dry-run=client");let r=Zs(o,e);try{let{stdout:i,stderr:a}=await Ee(r,{timeout:12e4,maxBuffer:2097152});return(i||a||"(no output)").trim()}catch(i){return`ERROR: ${(i.stderr||i.message||"").toString().split(`
328
+ `)[0]}`}}case"k8s_rollout":{if(!e.action)return"ERROR: action is required";if(!e.deployment)return"ERROR: deployment is required";let n=e.namespace||"default";if(e.action==="restart"||e.action==="undo"){let a=e.action==="restart"?"Rolling restart":"Rollback (undo)";if(console.log(`
329
+ ${ae.yellow} \u26A0 ${a}: deployment/${e.deployment} (ns: ${n})${ae.reset}`),!await kt(` ${a}?`))return"CANCELLED: User declined."}let r=`rollout ${e.action} deployment/${e.deployment} -n ${n}`,i=Zs(r,e);try{let{stdout:a,stderr:c}=await Ee(i,{timeout:12e4,maxBuffer:2097152});return(a||c||"(no output)").trim()}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
330
+ `)[0]}`}}case"brain_write":{if(!e.name)return"ERROR: name is required";if(!e.content)return"ERROR: content is required";if(!e.mode)return"ERROR: mode is required (create, update, append)";let{writeDocument:n,readDocument:o}=va(),{name:r,content:i,mode:a}=e;if(a==="create"&&o(r).content)return`ERROR: Document "${r}" already exists. Use mode "update" to overwrite.`;if(a==="append"){let c=o(r),l=c.content?c.content+`
331
+
332
+ `+i:i;return n(r,l),`Appended to brain document: ${r}.md`}return n(r,i),`${a==="create"?"Created":"Updated"} brain document: ${r}.md`}case"ssh_exec":{if(!e.server)return"ERROR: server is required";if(!e.command)return"ERROR: command is required";let n;try{n=$t(e.server)}catch(C){return`ERROR: ${C.message}`}let o=e.command,r=!!e.sudo,i=(e.timeout||30)*1e3,a=n0(o);if(a)return/\bsed\s+-n\s+['"]?\d+,\d+p/.test(o)?`BLOCKED: sed -n line-range is blocked (floods context). To read specific lines from a remote file use:
333
+ grep -n "pattern" /path/to/file -A 50
334
+ or to read the whole file:
335
+ cat /path/to/file
336
+ NEVER use sed -n again \u2014 it will always be blocked.`:`BLOCKED: Remote command matches SSH secret-exposure pattern: ${a}
337
+ HINT: Do not read .env, credentials, or private key files via ssh_exec \u2014 secrets would appear in tool output. Reference variable names or file paths instead.`;if(o=o.replace(/(-[BAC])\s*(\d+)/g,(C,K,Q)=>{let re=Math.min(Number(Q),20);return`${K} ${re}`}),o=o.replace(/(--(?:before|after|context)=)(\d+)/g,(C,K,Q)=>K+Math.min(Number(Q),20)),/\b(rm|rmdir|mv|cp|chmod|chown|dd|mkfs|systemctl\s+(start|stop|restart|reload|enable|disable)|dnf\s+(install|remove|update|upgrade)|yum\s+(install|remove)|apt(-get)?\s+(install|remove|purge)|pip\s+install|pip3\s+install|firewall-cmd\s+--permanent|semanage|setsebool|passwd|userdel|useradd|nginx\s+-s\s+(reload|stop)|service\s+\w+\s+(start|stop|restart))\b/.test(o)){let C=n.user?`${n.user}@${n.host}`:n.host;if(console.log(`
338
+ ${ae.yellow} \u26A0 Remote command on ${C}: ${o}${ae.reset}`),!await kt(" Execute on remote server?"))return"CANCELLED: User declined to execute remote command."}let{stdout:l,stderr:u,exitCode:d,error:f}=await ot(n,o,{timeout:i,sudo:r}),h=[l,u].filter(Boolean).join(`
339
+ `).trim();if(d!==0)return`EXIT ${d}
340
+ ${f||h||"(no output)"}`;let m=/\bgrep\b/.test(o),g=h;m&&(g=g.split(`
341
+ `).filter(C=>C!=="--").join(`
342
+ `));let b=m?60:100,v=g.split(`
343
+ `);v.length>b&&(g=`(${v.length-b} earlier lines omitted \u2014 showing last ${b})
344
+ `+v.slice(-b).join(`
345
+ `));let O=4,U=g.split(`
346
+ `),L=[],R=0;for(;R<U.length;){let C=R+1;for(;C<U.length&&U[C]===U[R];)C++;let K=C-R;if(L.push(U[R]),K>O)L.push(`... (${K-1} identical lines omitted)`);else for(let Q=1;Q<K;Q++)L.push(U[R]);R=C}return L.join(`
347
+ `)||"(command completed, no output)"}case"ssh_upload":{if(!e.server||!e.local_path||!e.remote_path)return"ERROR: server, local_path, and remote_path are required";let n;try{n=$t(e.server)}catch(i){return`ERROR: ${i.message}`}let o=n.user?`${n.user}@${n.host}`:n.host;if(console.log(`
348
+ ${ae.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${o}:${e.remote_path}${ae.reset}`),!await kt(" Upload to remote server?"))return"CANCELLED: User declined upload.";try{return await d0(n,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 n;try{n=$t(e.server)}catch(o){return`ERROR: ${o.message}`}try{return await f0(n,e.remote_path,e.local_path)}catch(o){return`ERROR: ${o.message}`}}case"remote_agent":{let n=require("path").join(process.cwd(),".nex","servers.json"),o=null;try{o=JSON.parse(require("fs").readFileSync(n,"utf-8"))[e.server]||null}catch{}let r=o?`${o.user||"root"}@${o.host}`:e.server,i=o?.key?["-i",o.key]:[],a=e.project_path||o?.home||"~",c=e.model||"",u=["TMPFILE=$(mktemp /tmp/nexcode-XXXXXX.txt)",`echo "${Buffer.from(e.task).toString("base64")}" | base64 -d > "$TMPFILE"`,`cd "${a}" 2>/dev/null || true`,c?`nex-code --prompt-file "$TMPFILE" --auto --model "${c}" 2>&1`:'nex-code --prompt-file "$TMPFILE" --auto 2>&1',"EXIT_CODE=$?",'rm -f "$TMPFILE"',"exit $EXIT_CODE"].join(" && "),{spawnSync:d}=require("child_process"),f=d("ssh",[...i,"-o","StrictHostKeyChecking=no","-o","ConnectTimeout=10",r,`bash -c '${u}'`],{encoding:"utf-8",maxBuffer:10*1024*1024,timeout:3e5});if(f.error)return`ERROR: SSH connection failed: ${f.error.message}`;let h=(f.stdout||"")+(f.stderr||"");return f.status!==0?`Remote nex-code exited with code ${f.status}.
349
+ ${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 n=["status","start","stop","restart","reload","enable","disable"];if(!n.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${n.join(", ")}`;let o=!e.server||e.server==="local"||e.server==="localhost",r=e.action==="status",i=null;if(!o)try{i=$t(e.server)}catch(c){return`ERROR: ${c.message}`}if(!r){let c=o?"local machine":i.user?`${i.user}@${i.host}`:i.host;if(console.log(`
350
+ ${ae.yellow} \u26A0 Service: systemctl ${e.action} ${e.service} on ${c}${ae.reset}`),!await kt(" Execute?"))return"CANCELLED: User declined service action."}let a=`systemctl ${e.action} ${e.service}`;if(o){let l=e.action!=="status"?`sudo ${a}`:a;try{let{stdout:u,stderr:d}=await Ee(l,{timeout:15e3});return(u||d||`systemctl ${e.action} ${e.service}: OK`).trim()}catch(u){let d=(u.stderr||u.message||"").toString().trim();return/not found|loaded.*not-found/i.test(d)?`ERROR: Service "${e.service}" not found. Check: systemctl list-units --type=service`:`EXIT ${u.code||1}
351
+ ${d}`}}else{let{stdout:c,stderr:l,exitCode:u,error:d}=await ot(i,a,{timeout:15e3,sudo:!0}),f=[c,l].filter(Boolean).join(`
352
+ `).trim();return u!==0?/not found|loaded.*not-found/i.test(f)?`ERROR: Service "${e.service}" not found on ${i.host}. Check: ssh_exec to run "systemctl list-units --type=service"`:`EXIT ${u}
353
+ ${d||f||"(no output)"}`:f||`systemctl ${e.action} ${e.service}: OK`}}case"service_logs":{if(!e.service)return"ERROR: service is required";let n=!e.server||e.server==="local"||e.server==="localhost",o=e.lines||50,r=e.since?`--since "${e.since}"`:"",i=e.follow?"-f":"",a=`journalctl -u ${e.service} -n ${o} ${r} ${i} --no-pager`.trim().replace(/\s+/g," ");if(n)try{let{stdout:m,stderr:g}=await Ee(a,{timeout:15e3});return(m||g||"(no log output)").trim()}catch(m){return`EXIT ${m.code||1}
354
+ ${(m.stderr||m.message||"").toString().trim()}`}let c;try{c=$t(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:l,stderr:u,exitCode:d,error:f}=await ot(c,a,{timeout:2e4}),h=[l,u].filter(Boolean).join(`
355
+ `).trim();return d!==0?`EXIT ${d}
356
+ ${f||h||"(no output)"}`:h||"(no log output)"}case"container_list":{let n=!e.server||e.server==="local"||e.server==="localhost",r=`docker ps ${e.all?"-a":""} --format "table {{.ID}}\\t{{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}"`.trim().replace(/\s+/g," ");if(n)try{let{stdout:f,stderr:h}=await Ee(r,{timeout:1e4});return(f||h||"(no containers)").trim()}catch(f){return`EXIT ${f.code||1}
357
+ ${(f.stderr||f.message||"").toString().trim()}`}let i;try{i=$t(e.server)}catch(f){return`ERROR: ${f.message}`}let{stdout:a,stderr:c,exitCode:l,error:u}=await ot(i,r,{timeout:15e3}),d=[a,c].filter(Boolean).join(`
358
+ `).trim();return l!==0?`EXIT ${l}
359
+ ${u||d}`:d||"(no containers)"}case"container_logs":{if(!e.container)return"ERROR: container is required";let n=!e.server||e.server==="local"||e.server==="localhost",o=e.lines||50,r=e.since?`--since "${e.since}"`:"",i=`docker logs --tail ${o} ${r} ${e.container} 2>&1`.trim().replace(/\s+/g," ");if(n)try{let{stdout:h,stderr:m}=await Ee(i,{timeout:15e3});return(h||m||"(no log output)").trim()}catch(h){return`EXIT ${h.code||1}
360
+ ${(h.stderr||h.message||"").toString().trim()}`}let a;try{a=$t(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:c,stderr:l,exitCode:u,error:d}=await ot(a,i,{timeout:2e4}),f=[c,l].filter(Boolean).join(`
361
+ `).trim();return u!==0?`EXIT ${u}
362
+ ${d||f}`:f||"(no log output)"}case"container_exec":{if(!e.container)return"ERROR: container is required";if(!e.command)return"ERROR: command is required";let n=!e.server||e.server==="local"||e.server==="localhost",o=/^(cat|ls|echo|env|printenv|df|du|ps|id|whoami|uname|hostname|date|pwd|which|find\s|head\s|tail\s|grep\s|curl\s+-[A-Za-z]*G|curl\s+https?:\/\/[^\s]+$)/;if(!s.autoConfirm&&!o.test(e.command.trim())){let m=n?"local":e.server;if(console.log(`
363
+ ${ae.yellow} \u26A0 docker exec in ${e.container} on ${m}: ${e.command}${ae.reset}`),!await kt(" Execute?"))return"CANCELLED: User declined."}let i=(e.container||"").replace(/[^a-zA-Z0-9._\/-]/g,"");if(!i)return"ERROR: Invalid container name";let a=`docker exec ${i} sh -c ${JSON.stringify(e.command)}`;if(n)try{let{stdout:m,stderr:g}=await Ee(a,{timeout:3e4});return(m||g||"(no output)").trim()}catch(m){return`EXIT ${m.code||1}
364
+ ${(m.stderr||m.message||"").toString().trim()}`}let c;try{c=$t(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:l,stderr:u,exitCode:d,error:f}=await ot(c,a,{timeout:35e3}),h=[l,u].filter(Boolean).join(`
365
+ `).trim();return d!==0?`EXIT ${d}
366
+ ${f||h}`:h||"(no output)"}case"container_manage":{if(!e.container)return"ERROR: container is required";if(!e.action)return"ERROR: action is required";let n=["start","stop","restart","remove","inspect"];if(!n.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${n.join(", ")}`;let o=!e.server||e.server==="local"||e.server==="localhost";if(!(e.action==="inspect")&&!s.autoConfirm){let m=o?"local":e.server;if(console.log(`
367
+ ${ae.yellow} \u26A0 docker ${e.action} ${e.container} on ${m}${ae.reset}`),!await kt(" Execute?"))return"CANCELLED: User declined."}let i=e.action==="remove"?"rm":e.action,a=e.action==="inspect"?`docker inspect ${e.container}`:`docker ${i} ${e.container}`;if(o)try{let{stdout:m,stderr:g}=await Ee(a,{timeout:3e4});return(m||g||`docker ${e.action} ${e.container}: OK`).trim()}catch(m){return`EXIT ${m.code||1}
368
+ ${(m.stderr||m.message||"").toString().trim()}`}let c;try{c=$t(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:l,stderr:u,exitCode:d,error:f}=await ot(c,a,{timeout:35e3}),h=[l,u].filter(Boolean).join(`
369
+ `).trim();return d!==0?`EXIT ${d}
370
+ ${f||h}`:h||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...p0(e.config),...e},delete e.config,delete e._name}catch(u){return`ERROR: ${u.message}`}if(!e.server)return'ERROR: server is required (or use config: "<name>")';if(!e.remote_path)return"ERROR: remote_path is required";let n=e.method||"rsync";if(n==="rsync"&&!e.local_path)return"ERROR: local_path is required for rsync method";let o;try{o=$t(e.server)}catch(u){return`ERROR: ${u.message}`}let r=o.user?`${o.user}@${o.host}`:o.host;if(!e.dry_run&&!s.autoConfirm){if(n==="git"){let d=e.branch?` (branch: ${e.branch})`:"";console.log(`
371
+ ${ae.yellow} \u26A0 Deploy [git pull]: ${r}:${e.remote_path}${d}${ae.reset}`)}else{let d=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`;console.log(`
372
+ ${ae.yellow} \u26A0 Deploy [rsync]: ${d} \u2192 ${r}:${e.remote_path}${ae.reset}`)}if(e.deploy_script&&console.log(`${ae.yellow} Then run: ${e.deploy_script}${ae.reset}`),e.health_check&&console.log(`${ae.yellow} Health check: ${e.health_check}${ae.reset}`),!await kt(" Proceed with deployment?"))return"CANCELLED: User declined."}let i="";if(n==="git"){let u=(e.branch||"").replace(/[^a-zA-Z0-9._\/-]/g,"");if(e.branch&&u!==e.branch)return`ERROR: Invalid branch name: ${e.branch}`;let d=(e.remote_path||"").replace(/'/g,"'\\''"),f=u?`cd '${d}' && git fetch origin && git checkout '${u}' && git pull origin '${u}'`:`cd '${d}' && git pull`;if(e.dry_run)return`DRY RUN [git]: would run on ${r}:
373
+ ${f}${e.deploy_script?`
374
+ ${e.deploy_script}`:""}`;let{stdout:h,stderr:m,exitCode:g,error:b}=await ot(o,f,{timeout:12e4});if(i=[h,m].filter(Boolean).join(`
375
+ `).trim(),g!==0)return`ERROR (git pull, exit ${g}):
376
+ ${b||i}`}else{let u=o.key?`-e "ssh -i ${o.key.replace(/^~/,require("os").homedir())}${o.port&&Number(o.port)!==22?` -p ${o.port}`:""}"`:o.port&&Number(o.port)!==22?`-e "ssh -p ${o.port}"`:"",d=(e.exclude||[]).map(g=>`--exclude="${g}"`).join(" "),f=e.dry_run?"--dry-run":"",h=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`,m=`rsync -avz --delete ${f} ${d} ${u} ${h} ${r}:${e.remote_path}`.trim().replace(/\s+/g," ");try{let{stdout:g,stderr:b}=await Ee(m,{timeout:12e4});i=(g||b||"").trim()}catch(g){return`ERROR (rsync): ${(g.stderr||g.message||"").toString().trim()}`}if(e.dry_run)return`DRY RUN [rsync]:
377
+ ${i||"(nothing to sync)"}`}let a="";if(e.deploy_script){let{stdout:u,stderr:d,exitCode:f,error:h}=await ot(o,e.deploy_script,{timeout:12e4}),m=[u,d].filter(Boolean).join(`
378
+ `).trim();if(f!==0)return`${n==="git"?"git pull":"rsync"} OK
379
+
380
+ ERROR (deploy_script, exit ${f}):
381
+ ${h||m}`;a=`
382
+
383
+ Deploy script output:
384
+ ${m||"(no output)"}`}let c="";if(e.health_check){let u=e.health_check.trim();if(/^https?:\/\//.test(u))try{let f=require("node-fetch"),h=await Promise.race([f(u),new Promise((m,g)=>setTimeout(()=>g(new Error("timeout")),15e3))]);if(h.ok)c=`
385
+
386
+ Health check: \u2713 ${u} \u2192 ${h.status}`;else return c=`
387
+
388
+ Health check FAILED: ${u} \u2192 HTTP ${h.status}`,(n==="git"?"git pull OK":"rsync OK")+i+a+c}catch(f){return c=`
389
+
390
+ Health check FAILED: ${u} \u2192 ${f.message}`,(n==="git"?"git pull OK":"rsync OK")+i+a+c}else{let{stdout:f,stderr:h,exitCode:m}=await ot(o,u,{timeout:15e3}),g=[f,h].filter(Boolean).join(`
391
+ `).trim();if(m!==0)return c=`
392
+
393
+ Health check FAILED (exit ${m}): ${g}`,(n==="git"?"git pull OK":"rsync OK")+i+a+c;c=`
394
+
395
+ Health check: \u2713 ${g||"(exit 0)"}`}}let l=n==="git"?`${r}:${e.remote_path}`:`${e.local_path} \u2192 ${r}:${e.remote_path}`;return`Deployed [${n}] ${l}
396
+ ${i}${a}${c}`.trim()}case"deployment_status":{let n=h0(),o=e.config?[e.config]:Object.keys(n);if(o.length===0)return"No deploy configs found. Create .nex/deploy.json to configure deployments.";let r=[];for(let i of o){let a=n[i];if(!a){r.push(`${i}: NOT FOUND`);continue}try{let c=$t(a.server||i),u=(await ot(c,"echo OK",{timeout:1e4})).stdout.trim()==="OK",d="unknown";if(u&&a.deploy_script){let h=a.deploy_script.match(/systemctl\s+\w+\s+(\S+)/);if(h)try{d=(await ot(c,`systemctl is-active ${h[1]}`,{timeout:1e4})).stdout.trim()}catch{d="inactive"}}let f="N/A";if(a.health_check){let h=a.health_check.trim();if(/^https?:\/\//.test(h))try{let m=require("node-fetch"),g=await Promise.race([m(h),new Promise((b,v)=>setTimeout(()=>v(new Error("timeout")),1e4))]);f=g.ok?"healthy":`HTTP ${g.status}`}catch(m){f=`unhealthy: ${m.message.substring(0,50)}`}else try{f=(await ot(c,h,{timeout:1e4})).exitCode===0?"healthy":"unhealthy"}catch{f="unhealthy"}}r.push(`${i}: server=${u?"reachable":"unreachable"} service=${d} health=${f}`)}catch(c){r.push(`${i}: ERROR \u2014 ${c.message}`)}}return`Deployment Status:
397
+ ${r.join(`
398
+ `)}`}case"frontend_recon":{let n=process.cwd(),o=(e.type||"").toLowerCase(),r=[],i=async(L,R=120)=>{try{let C=ve.isAbsolute(L)?L:ve.join(n,L),Q=(await je.readFile(C,"utf8")).split(`
399
+ `),re=Q.slice(0,R).join(`
400
+ `);return Q.length>R?re+`
401
+ ... (${Q.length-R} more lines \u2014 use read_file for full content)`:re}catch{return null}},c=["node_modules",".git","dist","build","vendor",".next","__pycache__","venv",".venv"].map(L=>`-not -path "*/${L}/*"`).join(" "),l=async L=>{try{let{stdout:R}=await Ee(`find "${n}" -type f -name "${L}" ${c} 2>/dev/null | head -10`,{timeout:8e3});return R.trim().split(`
402
+ `).filter(Boolean)}catch{return[]}},u=async(L,R)=>{try{let{stdout:C}=await Ee(`grep -rl "${L}" "${n}" --include="${R}" --exclude-dir=node_modules --exclude-dir=.git --exclude-dir=dist --exclude-dir=build 2>/dev/null | head -5`,{timeout:8e3});return C.trim().split(`
403
+ `).filter(Boolean)}catch{return[]}};r.push(`## STEP 1: Design Tokens
404
+ `);let d=[...await l("tailwind.config.js"),...await l("tailwind.config.ts"),...await l("tailwind.config.mjs")];if(d.length>0){let L=await i(d[0],80);L&&r.push(`### Tailwind config (${ve.relative(n,d[0])})
405
+ \`\`\`js
406
+ ${L}
407
+ \`\`\``)}else r.push("(no tailwind.config found)");let f=["variables.css","_variables.scss","tokens.css","base.css","global.css","main.css","index.css","app.css","style.css","styles.css"],h=!1;for(let L of f){let R=await l(L);for(let C of R){let K=await i(C,100);if(K&&K.includes(":root")){r.push(`### CSS Variables (${ve.relative(n,C)})
408
+ \`\`\`css
409
+ ${K}
410
+ \`\`\``),h=!0;break}}if(h)break}if(!h){let L=await u(":root","*.css");if(L.length>0){let R=await i(L[0],100);R&&r.push(`### CSS Variables (${ve.relative(n,L[0])})
411
+ \`\`\`css
412
+ ${R}
413
+ \`\`\``),h=!0}}h||r.push("(no CSS custom properties / :root found)"),r.push(`
414
+ ## STEP 2: Main Layout / Index Page
415
+ `);let m=["base.html","_base.html","layout.html","base.jinja","App.vue","App.jsx","App.tsx","_app.jsx","_app.tsx","_app.js","layout.vue","index.html"],g=!1;for(let L of m){let R=await l(L);if(R.length>0){let C=await i(R[0],150);if(C){r.push(`### Main layout: ${ve.relative(n,R[0])}
416
+ \`\`\`html
417
+ ${C}
418
+ \`\`\``),g=!0;break}}}g||r.push("(no main layout/index file found \u2014 try read_file on your root template manually)"),r.push(`
419
+ ## STEP 3: Reference Component (same type)
420
+ `);let b=[];if(o){for(let L of["*.html","*.vue","*.jsx","*.tsx"])if(b=await u(o,L),b.length>0)break}if(b.length===0)try{let{stdout:L}=await Ee(`find "${n}" -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});b=L.trim().split(`
421
+ `).filter(Boolean)}catch{b=[]}if(b.length>0){let L=b[0],R=await i(L,150);R?r.push(`### Reference: ${ve.relative(n,L)}
422
+ \`\`\`html
423
+ ${R}
424
+ \`\`\``):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(`
425
+ ## STEP 4: Framework Stack
426
+ `);let v=[],O=await i(ve.join(n,"package.json"),999);if(O){if((O.includes('"react"')||O.includes("'react'"))&&v.push("React"),O.includes('"vue"')||O.includes("'vue'")){let R=O.match(/"vue":\s*"[\^~]?(\d+)/);v.push(R?`Vue.js v${R[1]}`:"Vue.js")}let L=O.match(/"alpinejs":\s*"[\^~]?(\d+)/);L&&v.push(`Alpine.js v${L[1]} (\u26A0 v2 vs v3 API differs!)`),(O.includes('"htmx')||O.includes("'htmx"))&&v.push("HTMX"),O.includes('"tailwindcss"')&&v.push("Tailwind CSS"),O.includes('"bootstrap"')&&v.push("Bootstrap")}if((await ft(ve.join(n,"manage.py"))||(await i(ve.join(n,"requirements.txt"),50)||"").includes("Django"))&&v.push("Django (server-rendered templates)"),!v.some(L=>L.includes("Alpine"))){let L=await u("alpinejs","*.html");if(L.length>0){let C=(await i(L[0],30)||"").match(/alpinejs[@/]v?(\d)/);v.push(C?`Alpine.js v${C[1]} (via CDN \u2014 \u26A0 v2 vs v3 API differs!)`:"Alpine.js (via CDN \u2014 check version!)")}}return v.some(L=>L.includes("HTMX"))||(await u("htmx","*.html")).length>0&&v.push("HTMX (via CDN)"),v.length>0?(r.push(v.map(L=>`- ${L}`).join(`
427
+ `)),r.push(`
428
+ \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(`
429
+ ---
430
+ \u2705 Design recon complete. Now build consistently with the patterns above.`),r.join(`
431
+ `)}case"sysadmin":{if(!e.action)return"ERROR: action is required";let n=!e.server||e.server==="local"||e.server==="localhost",o;if(!n)try{o=$t(e.server)}catch(c){return`ERROR: ${c.message}`}let r=async(c,l=3e4)=>{if(n)try{let{stdout:u,stderr:d}=await Ee(c,{timeout:l});return{out:(u||d||"").trim(),exitCode:0}}catch(u){return{out:(u.stderr||u.message||"").toString().trim(),exitCode:u.code||1}}else{let{stdout:u,stderr:d,exitCode:f,error:h}=await ot(o,c,{timeout:l}),m=[u,d].filter(Boolean).join(`
432
+ `).trim();return{out:h&&f!==0&&!u.trim()?(h+`
433
+ `+m).trim():m,exitCode:f}}};if(!(["audit","disk_usage","process_list","network_status","ssl_check","log_tail","find_large","journalctl"].includes(e.action)||e.action==="package"&&e.package_action==="list"||e.action==="user_manage"&&["list","info"].includes(e.user_action)||e.action==="firewall"&&e.firewall_action==="status"||e.action==="cron"&&e.cron_action==="list"||e.action==="service"&&["status","list_failed"].includes(e.service_action))&&!s.autoConfirm){let c=n?"local":e.server;if(!await kt(`sysadmin [${e.action}] on ${c} \u2014 proceed?`))return"Cancelled."}switch(e.action){case"audit":{let c=["echo '=== OS / KERNEL ==='","cat /etc/os-release 2>/dev/null | grep -E '^(NAME|VERSION)=' || uname -a","echo '=== UPTIME / LOAD ==='","uptime","echo '=== MEMORY / SWAP ==='","free -h","echo '=== DISK ==='","df -h --output=target,size,used,avail,pcent 2>/dev/null || df -h","echo '=== TOP 10 PROCESSES (CPU) ==='","ps aux --sort=-%cpu | head -11","echo '=== FAILED SYSTEMD UNITS ==='","systemctl list-units --state=failed --no-legend 2>/dev/null || echo '(systemctl not available)'","echo '=== RECENT ERRORS (journalctl) ==='","journalctl -p err --no-pager -n 15 2>/dev/null || echo '(journalctl not available)'","echo '=== LISTENING PORTS ==='","ss -tlnp 2>/dev/null || netstat -tlnp 2>/dev/null || echo '(ss/netstat not available)'"].join(" && "),{out:l,exitCode:u}=await r(c,45e3);return l||`EXIT ${u}
434
+ (no output)`}case"disk_usage":{let c=e.path||"/",l=`df -h ${c}; echo '--- Top subdirs ---'; du -d1 -x -h ${c} 2>/dev/null | sort -rh | head -20`,{out:u,exitCode:d}=await r(l,3e4);return d!==0?`EXIT ${d}
435
+ ${u}`:u}case"process_list":{let c=e.sort_by==="mem"?"4":"3",l=(e.limit||20)+1,u=`ps aux --sort=-${e.sort_by==="mem"?"%mem":"%cpu"} 2>/dev/null | head -${l} || ps aux | awk 'NR==1{print; next} {print | "sort -k${c} -rn"}' | head -${l}`,{out:d,exitCode:f}=await r(u,15e3);return f!==0?`EXIT ${f}
436
+ ${d}`:d}case"network_status":{let c="ss -tlnp 2>/dev/null || netstat -tlnp 2>/dev/null; echo '--- Active connections ---'; ss -tnp 2>/dev/null | head -30",{out:l,exitCode:u}=await r(c,15e3);return u!==0?`EXIT ${u}
437
+ ${l}`:l}case"package":{if(!e.package_action)return"ERROR: package_action is required for action=package";let{out:c}=await r("which dnf 2>/dev/null && echo dnf || (which apt-get 2>/dev/null && echo apt) || echo unknown",1e4),l=c.includes("dnf")?"dnf":c.includes("apt")?"apt":null;if(!l)return"ERROR: No supported package manager found (dnf/apt)";let u=(e.packages||[]).join(" "),d;switch(e.package_action){case"list":d=l==="dnf"?"dnf list installed 2>/dev/null | head -60":"dpkg -l | head -60";break;case"check":{let m=l==="dnf"?'dnf check-update 2>/dev/null; EC=$?; [ $EC -eq 100 ] && echo "EXIT_STATUS: updates_available" || ([ $EC -eq 0 ] && echo "EXIT_STATUS: up_to_date" || echo "EXIT_STATUS: error $EC")':"apt-get -s upgrade 2>/dev/null | tail -5",{out:g}=await r(m,6e4);return g||"(no output from package check)"}case"install":if(!u)return"ERROR: packages required for install";d=l==="dnf"?`dnf install -y ${u}`:`apt-get install -y ${u}`;break;case"remove":if(!u)return"ERROR: packages required for remove";d=l==="dnf"?`dnf remove -y ${u}`:`apt-get remove -y ${u}`;break;case"update":if(!u)return"ERROR: packages required for update (use upgrade for full system upgrade)";d=l==="dnf"?`dnf update -y ${u}`:`apt-get install -y --only-upgrade ${u}`;break;case"upgrade":d=l==="dnf"?"dnf upgrade -y":"DEBIAN_FRONTEND=noninteractive apt-get upgrade -y";break;default:return`ERROR: Unknown package_action: ${e.package_action}`}let{out:f,exitCode:h}=await r(d,12e4);return h!==0?`EXIT ${h}
438
+ ${f}`:f||`${e.package_action} OK`}case"user_manage":{if(!e.user_action)return"ERROR: user_action is required for action=user_manage";switch(e.user_action){case"list":{let c=`awk -F: '$3 >= 1000 && $1 != "nobody" {print $1, "uid="$3, "gid="$4, "shell="$7}' /etc/passwd`,{out:l,exitCode:u}=await r(c,1e4);return u!==0?`EXIT ${u}
439
+ ${l}`:l||"(no regular users)"}case"info":{if(!e.user)return"ERROR: user is required for user_action=info";let c=`id ${e.user} && echo '--- Groups ---' && groups ${e.user} && echo '--- Last login ---' && lastlog -u ${e.user} 2>/dev/null`,{out:l,exitCode:u}=await r(c,1e4);return u!==0?`EXIT ${u}
440
+ ${l}`:l}case"create":{if(!e.user)return"ERROR: user is required for user_action=create";let l=`useradd -m ${(e.groups||[]).map(f=>`-G ${f}`).join(" ")} ${e.user} && echo "User ${e.user} created"`,{out:u,exitCode:d}=await r(l,15e3);return d!==0?`EXIT ${d}
441
+ ${u}`:u}case"delete":{if(!e.user)return"ERROR: user is required for user_action=delete";let c=`userdel -r ${e.user} && echo "User ${e.user} deleted"`,{out:l,exitCode:u}=await r(c,15e3);return u!==0?`EXIT ${u}
442
+ ${l}`:l}case"add_ssh_key":{if(!e.user)return"ERROR: user is required for user_action=add_ssh_key";if(!e.ssh_key)return"ERROR: ssh_key is required for user_action=add_ssh_key";let c=e.ssh_key.replace(/'/g,"'\\''"),l=`mkdir -p /home/${e.user}/.ssh && chmod 700 /home/${e.user}/.ssh && echo '${c}' >> /home/${e.user}/.ssh/authorized_keys && chmod 600 /home/${e.user}/.ssh/authorized_keys && chown -R ${e.user}:${e.user} /home/${e.user}/.ssh && echo "SSH key added for ${e.user}"`,{out:u,exitCode:d}=await r(l,15e3);return d!==0?`EXIT ${d}
443
+ ${u}`:u}default:return`ERROR: Unknown user_action: ${e.user_action}`}}case"firewall":{if(!e.firewall_action)return"ERROR: firewall_action is required for action=firewall";let{out:c}=await r("which firewall-cmd 2>/dev/null && echo firewalld || (which ufw 2>/dev/null && echo ufw) || echo iptables",1e4),l=c.includes("firewalld")?"firewalld":c.includes("ufw")?"ufw":"iptables",u;switch(e.firewall_action){case"status":u=l==="firewalld"?"firewall-cmd --state && firewall-cmd --list-all":l==="ufw"?"ufw status verbose":"iptables -L -n --line-numbers | head -60";break;case"allow":if(!e.port)return'ERROR: port is required for firewall allow (e.g. "80/tcp")';u=l==="firewalld"?`firewall-cmd --permanent --add-port=${e.port} && firewall-cmd --reload`:l==="ufw"?`ufw allow ${e.port}`:`iptables -A INPUT -p ${e.port.includes("/")?e.port.split("/")[1]:"tcp"} --dport ${e.port.split("/")[0]} -j ACCEPT`;break;case"deny":if(!e.port)return"ERROR: port is required for firewall deny";u=l==="firewalld"?`firewall-cmd --permanent --remove-port=${e.port} && firewall-cmd --reload`:l==="ufw"?`ufw deny ${e.port}`:`iptables -A INPUT -p ${e.port.includes("/")?e.port.split("/")[1]:"tcp"} --dport ${e.port.split("/")[0]} -j DROP`;break;case"remove":if(!e.port)return"ERROR: port is required for firewall remove";u=l==="firewalld"?`firewall-cmd --permanent --remove-port=${e.port} && firewall-cmd --reload`:l==="ufw"?`ufw delete allow ${e.port}`:`iptables -D INPUT -p ${e.port.includes("/")?e.port.split("/")[1]:"tcp"} --dport ${e.port.split("/")[0]} -j ACCEPT 2>/dev/null || true`;break;case"reload":u=l==="firewalld"?"firewall-cmd --reload":l==="ufw"?"ufw reload":'iptables-restore < /etc/iptables/rules.v4 2>/dev/null || echo "iptables: manual reload not available"';break;default:return`ERROR: Unknown firewall_action: ${e.firewall_action}`}let{out:d,exitCode:f}=await r(u,3e4);return f!==0?`EXIT ${f}
444
+ ${d}`:d||`firewall ${e.firewall_action} OK`}case"cron":{if(!e.cron_action)return"ERROR: cron_action is required for action=cron";let c=e.user?`-u ${e.user}`:"";switch(e.cron_action){case"list":{let l=`crontab ${c} -l 2>/dev/null || echo '(no crontab for ${e.user||"current user"})'`,{out:u}=await r(l,1e4);return u||"(empty crontab)"}case"add":{if(!e.schedule)return"ERROR: schedule is required for cron add";if(!e.command)return"ERROR: command is required for cron add";let l=`${e.schedule} ${e.command}`,u=`(crontab ${c} -l 2>/dev/null; echo "${l}") | crontab ${c} - && echo "Cron entry added: ${l}"`,{out:d,exitCode:f}=await r(u,15e3);return f!==0?`EXIT ${f}
445
+ ${d}`:d}case"remove":{if(!e.command)return"ERROR: command (substring to match) is required for cron remove";let l=e.command.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),u=`crontab ${c} -l 2>/dev/null | grep -v "${l}" | crontab ${c} - && echo "Matching cron entries removed"`,{out:d,exitCode:f}=await r(u,15e3);return f!==0?`EXIT ${f}
446
+ ${d}`:d}default:return`ERROR: Unknown cron_action: ${e.cron_action}`}}case"ssl_check":{if(!e.domain&&!e.cert_path)return"ERROR: domain or cert_path is required for ssl_check";let c;e.cert_path?c=`
447
+ CERT="${e.cert_path}"
448
+ openssl x509 -in "$CERT" -noout -subject -issuer -startdate -enddate -ext subjectAltName 2>&1 && EXPIRY=$(openssl x509 -in "$CERT" -noout -enddate 2>/dev/null | cut -d= -f2) && DAYS=$(( ( $(date -d "$EXPIRY" +%s 2>/dev/null || date -j -f "%b %d %T %Y %Z" "$EXPIRY" +%s 2>/dev/null) - $(date +%s) ) / 86400 )) && echo "Days until expiry: $DAYS"
449
+ `.trim():c=`
450
+ DOMAIN="${e.domain}"
451
+ LECP="/etc/letsencrypt/live/$DOMAIN/cert.pem"
452
+ if [ -f "$LECP" ]; then
453
+ echo "Source: Let's Encrypt $LECP"
454
+ openssl x509 -in "$LECP" -noout -subject -issuer -startdate -enddate -ext subjectAltName 2>&1
455
+ EXPIRY=$(openssl x509 -in "$LECP" -noout -enddate 2>/dev/null | cut -d= -f2)
456
+ else
457
+ echo "Source: live TLS probe"
458
+ CERT=$(echo | openssl s_client -connect "$DOMAIN":443 -servername "$DOMAIN" 2>/dev/null)
459
+ if [ -z "$CERT" ]; then echo "ERROR: Could not connect to $DOMAIN:443 (port closed or DNS unresolvable)"; exit 1; fi
460
+ echo "$CERT" | openssl x509 -noout -subject -issuer -startdate -enddate -ext subjectAltName 2>&1
461
+ EXPIRY=$(echo "$CERT" | openssl x509 -noout -enddate 2>/dev/null | cut -d= -f2)
462
+ fi
463
+ if [ -n "$EXPIRY" ]; then
464
+ DAYS=$(( ( $(date -d "$EXPIRY" +%s 2>/dev/null || date -j -f "%b %d %T %Y %Z" "$EXPIRY" +%s 2>/dev/null) - $(date +%s) ) / 86400 ))
465
+ echo "Days until expiry: $DAYS"
466
+ [ "$DAYS" -lt 14 ] && echo "WARNING: Certificate expires in less than 14 days!"
467
+ [ "$DAYS" -lt 0 ] && echo "CRITICAL: Certificate has EXPIRED!"
468
+ fi
469
+ `.trim();let{out:l,exitCode:u}=await r(c,25e3),d=/notAfter=|Days until expiry:/i.test(l);return u!==0&&!d?`EXIT ${u}
470
+ ${l}`:l||"(no cert info returned)"}case"log_tail":{if(!e.path)return"ERROR: path is required for log_tail";let l=`tail -n ${e.lines||100} ${e.path} 2>&1`,{out:u,exitCode:d}=await r(l,15e3);return d!==0?`EXIT ${d}
471
+ ${u}`:u||"(empty log)"}case"find_large":{let c=e.path||"/",l=e.limit||20,u=e.min_size||"100M",d=`find ${c} -xdev -type f -size +${u} 2>/dev/null | xargs du -sh 2>/dev/null | sort -rh | head -${l}`,{out:f,exitCode:h}=await r(d,6e4);return h!==0?`EXIT ${h}
472
+ ${f}`:f||`(no files larger than ${u} in ${c})`}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 c=e.service_name?e.service_name.includes(".")?e.service_name:`${e.service_name}.service`:"",l;switch(e.service_action){case"status":l=`systemctl status ${c} --no-pager -l 2>&1 | head -40`;break;case"list_failed":l="systemctl list-units --state=failed --no-legend 2>/dev/null";break;case"start":l=`systemctl start ${c} && systemctl status ${c} --no-pager -l 2>&1 | head -20`;break;case"stop":l=`systemctl stop ${c} && echo "${c} stopped"`;break;case"restart":l=`systemctl restart ${c} && systemctl status ${c} --no-pager -l 2>&1 | head -20`;break;case"reload":l=`systemctl reload ${c} 2>&1 || systemctl reload-or-restart ${c} 2>&1`;break;case"enable":l=`systemctl enable ${c} && echo "${c} enabled"`;break;case"disable":l=`systemctl disable ${c} && echo "${c} disabled"`;break;default:return`ERROR: Unknown service_action: ${e.service_action}`}let{out:u,exitCode:d}=await r(l,3e4);return d===0||e.service_action==="status"&&d===3?u||`service ${e.service_action} OK`:`EXIT ${d}
473
+ ${u}`}case"kill_process":{if(!e.pid&&!e.process_name)return"ERROR: pid or process_name is required for kill_process";let c=e.signal||"SIGTERM",l;e.pid?l=`ps -p ${e.pid} -o pid,user,%cpu,%mem,etime,cmd 2>/dev/null && kill -${c} ${e.pid} && echo "Sent ${c} to PID ${e.pid}"`:l=`pgrep -a "${e.process_name}" 2>/dev/null | head -5 && pkill -${c} "${e.process_name}" && echo "Sent ${c} to all '${e.process_name}' processes"`;let{out:u,exitCode:d}=await r(l,15e3);return d!==0?`EXIT ${d}
474
+ ${u}`:u}case"journalctl":{let c=e.lines||100,l=["journalctl","--no-pager","-n",String(c)];e.unit&&l.push("-u",e.unit.includes(".")?e.unit:`${e.unit}.service`),e.priority&&l.push("-p",e.priority),e.since&&l.push(`--since="${e.since}"`),l.push('2>/dev/null || echo "(journalctl not available)"');let{out:u,exitCode:d}=await r(l.join(" "),2e4);return d!==0?`EXIT ${d}
475
+ ${u}`:u||"(no log entries)"}default:return`ERROR: Unknown sysadmin action: ${e.action}`}}case"save_memory":{let{saveMemory:n}=zs(),o=n(e.type,e.name,e.content,e.description);return o.ok?o.updated===!1?`Memory unchanged (duplicate): ${e.type}/${e.name}`:`Memory saved: ${e.type}/${e.name} \u2192 ${o.path}`:`ERROR: ${o.error}`}case"delete_memory":{let{deleteMemory:n}=zs();return n(e.type,e.name)?`Memory deleted: ${e.type}/${e.name}`:`Memory not found: ${e.type}/${e.name}`}default:{let{executePluginTool:n}=rr(),o=await n(t,e,s);return o!==null?o:`ERROR: Unknown tool: ${t}`}}}async function k0(t,e,s={}){let{emit:n}=rr(),{logToolExecution:o}=yf(),r=Date.now(),i=s.silent?null:a0(t,e);if(!i){let c=await vf(t,e,s);return o({tool:t,args:e,result:c,duration:Date.now()-r,success:!c.startsWith?.("ERROR")}),await n("onToolResult",{tool:t,args:e,result:c}),c}let a=new i0(i);a.start();try{let c=await vf(t,e,s);return a.stop(),o({tool:t,args:e,result:c,duration:Date.now()-r,success:!c.startsWith?.("ERROR")}),await n("onToolResult",{tool:t,args:e,result:c}),c}catch(c){throw a.stop(),o({tool:t,args:e,result:c.message,duration:Date.now()-r,success:!1}),c}}Tf.exports={TOOL_DEFINITIONS:x0,executeTool:k0,resolvePath:rt,autoFixPath:Cr,autoFixEdit:Ef,enrichBashError:Sf,cancelPendingAskUser:w0,setAskUserHandler:b0,fileExists:ft}});var Jn=se((Qk,Cf)=>{Cf.exports=Rf()});var La=se((tv,Af)=>{var{loadServerProfiles:eo,resolveProfile:ev,sshExec:v0}=ra(),Ma={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 S0(){let t=eo();if(Object.keys(t).length===0)return null;let s=["## Remote Servers (.nex/servers.json)"];s.push(""),s.push("Available server profiles (use with ssh_exec, ssh_upload, ssh_download, service_manage, service_logs, container_list, container_logs, container_exec, container_manage, deploy):");for(let[o,r]of Object.entries(t)){let i=r.user?`${r.user}@${r.host}`:r.host,a=r.port&&Number(r.port)!==22?`:${r.port}`:"",c=r.os?` \u2014 OS: ${r.os}`:"",l=r.sudo?", sudo available":"";s.push(`- **${o}**: ${i}${a}${c}${l}`)}let n=new Set;for(let o of Object.values(t))o.os&&Ma[o.os]&&n.add(o.os);if(n.size>0){s.push("");for(let o of n){let r={almalinux9:"AlmaLinux 9",almalinux8:"AlmaLinux 8",ubuntu:"Ubuntu",debian:"Debian",macos:"macOS"}[o]||o;s.push(`### ${r} Notes`);for(let i of Ma[o])s.push(`- ${i}`)}}return s.join(`
476
+ `)}function E0(t){let e=eo();return Object.values(e).some(s=>s.os&&s.os.startsWith(t))}function T0(){return Object.keys(eo())}function R0(){let t=require("fs"),s=require("path").join(process.cwd(),"NEX.md"),n="";try{n=t.readFileSync(s,"utf-8")}catch{}let o=eo(),r=Object.keys(o);if(r.length===0)return null;let i=["server","deploy","remote","ssh","service","systemctl","production","linux","almalinux","ubuntu","debian"],a=n.toLowerCase();if(!i.some(f=>a.includes(f)))return null;let l=r.map(f=>{let h=o[f],m=h.user?`${h.user}@${h.host}`:h.host,g=h.port&&Number(h.port)!==22?`:${h.port}`:"";return` - **${f}**: ${m}${g}${h.os?` (${h.os})`:""}`}).join(`
477
+ `),u=r.map(f=>o[f].log_path).filter(Boolean),d=u.length>0?`
478
+ - Server log paths: ${u.join(", ")}`:"";return`# Deployment Context (Auto-detected)
479
+
480
+ This project is deployed on a **remote server**. The application runs as a service there \u2014 NOT locally.
481
+
482
+ ## Configured Servers
483
+ ${l}
484
+
485
+ ## Critical Debugging Rules
486
+
487
+ **When you receive an error or warning from the running application** (e.g. "500 ERR_BAD_RESPONSE", "\u26A0\uFE0F service error", health check failures, service alerts):
488
+ - \u2705 Use \`ssh_exec\` or \`service_logs\` to investigate on the remote server
489
+ - \u2705 \`ssh_exec\` example: \`tail -50 /path/to/logs/api.log\`
490
+ - \u2705 \`service_logs\` or \`bash\` with \`ssh\` to check \`systemctl status <service>\`${d}
491
+ - \u274C Do NOT \`read_file\` on paths like \`logs/\` \u2014 these files do not exist locally
492
+ - \u274C Do NOT \`list_directory\` on server paths \u2014 the local project is the source, not the running instance
493
+
494
+ **When in doubt:** If a path contains \`logs/\`, \`/var/log/\`, or \`/home/<user>/\` \u2014 it is on the server. SSH there.${C0(o)}`}function C0(t){return Object.values(t).some(s=>s.host==="94.130.37.43")?`
495
+
496
+ ## Jarvis Debugging Rules
497
+
498
+ - Jarvis errors (set_reminder, cron, Google Auth, SmartThings) come from the DEPLOYED server at 94.130.37.43
499
+ - ALWAYS use ssh_exec to investigate: ssh_exec on 94.130.37.43, check /home/jarvis/jarvis-agent/logs/
500
+ - NEVER run local bash/find/sqlite3 commands when debugging Jarvis issues
501
+ - Local jarvis-agent/ is just source code \u2014 the running system is on the server
502
+ - CRITICAL: When the user pastes a Jarvis error message ("jarvisFehler:", "jarvisEinige Fehler", error logs), this is NEVER a "simple question" to answer from training knowledge. You MUST ssh_exec to verify if the error is still occurring BEFORE writing any explanation. Do NOT explain from memory \u2014 investigate first, always.
503
+ - LOG FILES: Always check the CURRENT log first: /home/jarvis/jarvis-agent/logs/api-error.log (no date suffix). Log files WITH a date suffix (e.g. api-error.log-20260322) are ROTATED/OLD \u2014 errors there may already be fixed. Only look at dated logs if the current log is empty or the error is absent from the current log.
504
+ - FIX WORKFLOW (YOLO): Once you identify a fixable bug via SSH investigation: (1) edit the file on server using ssh_exec with tee or sed -i (NOT sed -n), (2) restart the affected service with systemctl restart, (3) verify with tail logs. Do NOT produce a report \u2014 execute the fix.
505
+ - READING REMOTE FILES: NEVER use sed -n (always blocked). To read a specific function in a remote file: ssh_exec 'grep -n "functionName" /path/file -A 50'. To read the whole file: ssh_exec 'cat /path/file'. These are the only two options.`:""}async function A0(t){if(typeof t!="string")return null;let e=[...t.matchAll(/https?:\/\/([a-zA-Z0-9._-]+)/g)];if(e.length===0)return null;let s=eo();if(Object.keys(s).length===0)return null;let n=null,o=null;for(let[,i]of e){let a=i.toLowerCase().split(".");for(let[c,l]of Object.entries(s))if(a.includes(c.toLowerCase())){n=l,o=c;break}if(n)break;for(let[c,l]of Object.entries(s))if(l.host===i){n=l,o=c;break}if(n)break}if(!n||!o)return null;let r=["ss -tlnp 2>/dev/null | awk 'NR>1{print $4}' | grep -oE ':[0-9]+$' | sort -u | head -8","echo '---services---'","ps aux 2>/dev/null | grep -E '(node |python3 |gunicorn|uvicorn|ruby |java )' | grep -v grep | awk '{print $11, $12, $13}' | head -6","echo '---data---'","find /home -maxdepth 5 -name 'data' -type d 2>/dev/null | head -6"].join("; ");try{let{stdout:i}=await v0(n,r,{timeout:4e3});if(!i||i.trim().length<5)return null;let a=n.user?`${n.user}@${n.host}`:n.host;return`[Server context for "${o}" (${a}) \u2014 probed at task start]
506
+ `+i.trim()}catch{return null}}Af.exports={getServerContext:S0,getDeploymentContextBlock:R0,hasServerOS:E0,getProfileNames:T0,probeUrlServer:A0,OS_HINTS:Ma}});var Lf=se((nv,Mf)=>{var vt=require("fs").promises,Of=require("fs"),tt=require("path"),Ar=require("util").promisify(require("child_process").exec),{C:as}=Ue(),{getMergeConflicts:Nf}=er(),{getServerContext:O0}=La(),N0=new Set(["node_modules",".git",".svn","dist","build","coverage",".nyc_output","__pycache__",".DS_Store",".next",".nuxt",".turbo",".cache","vendor","tmp","temp"]);function M0(t){try{return Of.readFileSync(t,"utf-8").split(`
507
+ `).map(s=>s.trim()).filter(s=>s&&!s.startsWith("#")&&!s.startsWith("!")).map(s=>s.replace(/\/$/,""))}catch{return[]}}function L0(t,e){for(let s of e)if(s===t||s.includes("*")&&new RegExp("^"+s.replace(/\./g,"\\.").replace(/\*/g,".*")+"$").test(t))return!0;return!1}function P0(t,{maxDepth:e=3,maxFiles:s=200,giPatterns:n=[]}={}){let o=tt.join(t,".gitignore"),r=[...n,...M0(o)],i=0,a=[tt.basename(t)+"/"];function c(l,u,d){if(d>e||i>=s)return;let f;try{f=Of.readdirSync(l,{withFileTypes:!0})}catch{return}f.sort((m,g)=>m.isDirectory()!==g.isDirectory()?m.isDirectory()?-1:1:m.name.localeCompare(g.name));let h=f.filter(m=>!(N0.has(m.name)||m.name.startsWith(".")&&m.name!==".env.example"||L0(m.name,r)));for(let m=0;m<h.length;m++){if(i>=s){a.push(`${u}\u2514\u2500\u2500 \u2026 (truncated)`);break}let g=h[m],b=m===h.length-1,v=b?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",O=u+(b?" ":"\u2502 "),U=g.isDirectory()?g.name+"/":g.name;a.push(`${u}${v}${U}`),i++,g.isDirectory()&&c(tt.join(l,g.name),O,d+1)}}return c(t,"",1),a.join(`
508
+ `)}var Pa=new Map,cs=new Map,Or=null,I0=3e4;async function Qt(t){try{return await t()}catch{return null}}async function j0(){if(!Or||Date.now()>Or)return!1;let t=[tt.join(process.cwd(),"package.json"),tt.join(process.cwd(),"README.md"),tt.join(process.cwd(),".gitignore")];for(let e of t)try{let s=await vt.stat(e),n=cs.get(e);if(!n||s.mtimeMs!==n)return!1}catch{if(cs.has(e))return!1}try{let e=tt.join(process.cwd(),".git","HEAD"),s=await vt.stat(e),n=cs.get(e);if(!n||s.mtimeMs!==n)return!1}catch{}return!0}async function D0(){let t=[tt.join(process.cwd(),"package.json"),tt.join(process.cwd(),"README.md"),tt.join(process.cwd(),".gitignore"),tt.join(process.cwd(),".git","HEAD")];for(let e of t)try{let s=await vt.stat(e);cs.set(e,s.mtimeMs)}catch{cs.delete(e)}}async function q0(t){let e="fileContext",s=Pa.get(e),n=!1;if(s&&await j0()&&(n=!0),!n){let l=[],u=tt.join(t,"package.json");if(await Qt(()=>vt.access(u).then(()=>!0).catch(()=>!1)))try{let b=await vt.readFile(u,"utf-8"),v=JSON.parse(b),O={name:v.name,version:v.version};v.scripts&&(O.scripts=Object.keys(v.scripts).slice(0,15)),v.dependencies&&(O.deps=Object.keys(v.dependencies).length),v.devDependencies&&(O.devDeps=Object.keys(v.devDependencies).length),l.push(`PACKAGE: ${JSON.stringify(O)}`)}catch{}let f=tt.join(t,"README.md");if(await Qt(()=>vt.access(f).then(()=>!0).catch(()=>!1))){let v=(await vt.readFile(f,"utf-8")).split(`
509
+ `).slice(0,50);l.push(`README (first 50 lines):
510
+ ${v.join(`
511
+ `)}`)}let m=tt.join(t,".gitignore");if(await Qt(()=>vt.access(m).then(()=>!0).catch(()=>!1))){let b=await vt.readFile(m,"utf-8");l.push(`GITIGNORE:
512
+ ${b.trim()}`)}s=l.join(`
513
+
514
+ `),Pa.set(e,s),Or=Date.now()+I0,await D0()}let o=[s],[r,i,a,c]=await Promise.all([Qt(async()=>{let{stdout:l}=await Ar("git branch --show-current",{cwd:t,timeout:5e3});return l.trim()}),Qt(async()=>{let{stdout:l}=await Ar("git status --short",{cwd:t,timeout:5e3});return l.trim()}),Qt(async()=>{let{stdout:l}=await Ar("git log --oneline -5",{cwd:t,timeout:5e3});return l.trim()}),Nf()]);if(r&&o.push(`GIT BRANCH: ${r}`),i&&o.push(`GIT STATUS:
515
+ ${i}`),a&&o.push(`RECENT COMMITS:
516
+ ${a}`),c&&c.length>0){let l=c.map(u=>` ${u.file}`).join(`
517
+ `);o.push(`MERGE CONFLICTS (resolve before editing these files):
518
+ ${l}`)}try{let l=O0();l&&o.push(l)}catch{}return o.join(`
519
+
520
+ `)}async function F0(t){let e=tt.join(t,"package.json"),s="";if(await Qt(()=>vt.access(e).then(()=>!0).catch(()=>!1)))try{let i=await vt.readFile(e,"utf-8"),a=JSON.parse(i);s=`${a.name||"?"} v${a.version||"?"}`}catch{}let[o,r]=await Promise.all([Qt(async()=>{let{stdout:i}=await Ar("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),Nf()]);if(r&&r.length>0){console.log(`${as.red} \u26A0 ${r.length} unresolved merge conflict(s):${as.reset}`);for(let i of r)console.log(`${as.red} ${i.file}${as.reset}`);console.log(`${as.yellow} \u2192 Resolve conflicts before starting tasks${as.reset}`)}console.log()}Mf.exports={gatherProjectContext:q0,printContext:F0,generateFileTree:P0,_clearContextCache:()=>{Pa.clear(),cs.clear(),Or=null}}});var Mr=se((sv,jf)=>{var St=require("fs"),Nr=require("path"),{atomicWrite:B0}=fn();function no(){return Nr.join(process.cwd(),".nex","sessions")}function Ia(){let t=no();St.existsSync(t)||St.mkdirSync(t,{recursive:!0})}function ja(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return Nr.join(no(),`${e}.json`)}function Da(t,e,s={}){Ia();let n=ja(t),o={name:t,createdAt:s.createdAt||new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:e.length,model:s.model||null,provider:s.provider||null,messages:e};return B0(n,JSON.stringify(o,null,2)),{path:n,name:t}}function Pf(t){let e=ja(t);if(!St.existsSync(e))return null;try{return JSON.parse(St.readFileSync(e,"utf-8"))}catch{return null}}function If(){Ia();let t=no(),e=St.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(St.readFileSync(Nr.join(t,n),"utf-8"));s.push({name:o.name||n.replace(".json",""),createdAt:o.createdAt,updatedAt:o.updatedAt,messageCount:o.messageCount||0,model:o.model,provider:o.provider,score:o.score!=null?o.score:null,scoreGrade:o.scoreGrade||null})}catch{}return s.sort((n,o)=>(o.updatedAt||"").localeCompare(n.updatedAt||""))}function W0(t){let e=ja(t);return St.existsSync(e)?(St.unlinkSync(e),!0):!1}function U0(){let t=If();return t.length===0?null:Pf(t[0].name)}var xn=null,Yt=null,to=null;function H0(t,e={}){t.length!==0&&(xn&&clearTimeout(xn),Yt=t,to=e||{},xn=setTimeout(()=>{Yt&&Yt.length>0&&Da("_autosave",Yt,to),xn=null,Yt=null,to=null},5e3))}function G0(){xn&&(clearTimeout(xn),xn=null),Yt&&Yt.length>0&&(Da("_autosave",Yt,to),Yt=null,to=null)}function Y0(){Ia();let t=no(),e=St.readdirSync(t).filter(r=>r.endsWith(".json")),s=new Date,n=new Date(s.getTime()-720*60*60*1e3),o=0;for(let r of e){let i=Nr.join(t,r);try{let a=St.statSync(i);new Date(a.mtime)<n&&(St.unlinkSync(i),o++)}catch{}}return o}jf.exports={saveSession:Da,loadSession:Pf,listSessions:If,deleteSession:W0,getLastSession:U0,autoSave:H0,flushAutoSave:G0,clearOldSessions:Y0,_getSessionsDir:no}});var Lr=se((ov,Gf)=>{"use strict";var so=require("fs"),Df=require("path");function qf(t){let e=[];return t.forEach((s,n)=>{s.role==="assistant"&&(Array.isArray(s.content)&&s.content.forEach(o=>{o&&o.type==="tool_use"&&e.push({name:o.name||"",input:o.input||{},index:n,id:o.id||null})}),Array.isArray(s.tool_calls)&&s.tool_calls.forEach(o=>{let r=o.function?.name||o.name||"",i={};try{i=typeof o.function?.arguments=="string"?JSON.parse(o.function.arguments):o.function?.arguments||o.input||{}}catch{}e.push({name:r,input:i,index:n,id:o.id||null})}))}),e}function K0(t){let e=new Set;return t.forEach(s=>{s.role==="tool"&&typeof s.content=="string"&&s.content.startsWith("BLOCKED:")&&s.tool_call_id&&e.add(s.tool_call_id),s.role==="user"&&Array.isArray(s.content)&&s.content.forEach(n=>{n&&n.type==="tool_result"&&n.tool_use_id&&typeof n.content=="string"&&n.content.startsWith("BLOCKED:")&&e.add(n.tool_use_id)})}),e}function Ff(t){let e=[];return t.forEach((s,n)=>{if(s.role==="user"&&Array.isArray(s.content)&&s.content.forEach(o=>{if(o&&o.type==="tool_result"){let r=typeof o.content=="string"?o.content:Array.isArray(o.content)?o.content.map(i=>typeof i=="string"?i:i.text||"").join(""):JSON.stringify(o.content||"");e.push({content:r,index:n})}}),s.role==="tool"){let o=typeof s.content=="string"?s.content:JSON.stringify(s.content||"");e.push({content:o,index:n})}}),e}function Bf(t){for(let e=t.length-1;e>=0;e--){let s=t[e];if(s.role==="assistant"){if(typeof s.content=="string")return s.content.trim();if(Array.isArray(s.content)){let n=s.content.filter(o=>o&&(o.type==="text"||typeof o=="string")).map(o=>typeof o=="string"?o:o.text||"").join("").trim();if(n)return n}}}return""}function Wf(t,e){let s=[];for(let n=t.length-1;n>=0&&s.length<e;n--){let o=t[n];if(o.role!=="assistant")continue;let r="";typeof o.content=="string"?r=o.content.trim():Array.isArray(o.content)&&(r=o.content.filter(i=>i&&(i.type==="text"||typeof i=="string")).map(i=>typeof i=="string"?i:i.text||"").join("").trim()),r&&s.push(r)}return s}function Uf(t){let e=new Map;for(let s of t){let n;try{n=JSON.stringify(s.input)}catch{n=String(s.input)}let o=`${s.name}|${n}`;e.set(o,(e.get(o)||0)+1)}return e}function Hf(t){if(!Array.isArray(t)||t.length===0)return{score:0,issues:["Empty or invalid session \u2014 no messages to analyse"],summary:"No messages found"};let e=10,s=[],n=qf(t),o=Ff(t),r=n.length,i=K0(t),a=n.filter(w=>!w.id||!i.has(w.id));t.some(w=>w.role==="user"&&typeof w.content=="string"&&w.content.startsWith("[SYSTEM WARNING]")&&(w.content.includes("edited")||w.content.includes("bash command")||w.content.includes("grep pattern")||w.content.includes("re-read")||w.content.includes("already in your context")))&&(e-=2,s.push("Loop-warning was fired during session (repeated file edits, bash commands, or re-reads)"));let l=n.find(w=>{let P=w.input?.command||w.input?.cmd||"";return/\bsed\s+-n\b/.test(P)});if(l){let w=(l.input?.command||l.input?.cmd||"").slice(0,80);o.some(k=>k.content.includes("BLOCKED: sed -n is forbidden")||k.content.includes("BLOCKED: sed -n"))?(e-=.25,s.push(`sed -n attempted but blocked by agent guard: ${w}`)):(e-=1.5,s.push(`sed -n anti-pattern used: ${w}`))}n.find(w=>{if(w.name!=="grep"&&w.name!=="bash"&&w.name!=="ssh_exec")return!1;let P=w.input?.command||w.input?.cmd||"",k=w.input?.pattern||"",N=`${P} ${k}`;return/(?:-[CAB]|--context|--after|--before)\s*[=\s]?([2-9][1-9]|\d{3,})/.test(N)||/grep.*-[CAB]\s*([2-9][1-9]|\d{3,})/.test(N)})&&(e-=1,s.push("grep used with >20 context lines (context flood risk)"));let d=t.some(w=>w.role==="assistant"),f=Bf(t),m=Wf(t,3).some(w=>w.length>100&&!/^[^.!]{0,40}\?$/.test(w));if(d&&!m&&(f.length<80||/^[^.!]{0,40}\?$/.test(f))){e-=2;let w=f.length>0?`"${f.slice(0,60)}..."`:"(no assistant text found)";s.push(`Session ends without diagnosis \u2014 last response too short or is only a question: ${w}`)}r>40?(e-=1.5,s.push(`Excessive tool calls: ${r} (>40 threshold)`)):r>25&&(e-=.5,s.push(`High tool call count: ${r} (>25 threshold)`)),t.some(w=>{let P=typeof w.content=="string"?w.content:Array.isArray(w.content)?w.content.map(k=>typeof k=="string"?k:k.text||"").join(""):"";return/\[auto-compressed|context compacted|force-compressed/.test(P)})&&(e-=.5,s.push("Auto-compress triggered (context flood indicator)"));let v=Uf(a),O=0,U="";for(let[w,P]of v)P>O&&(O=P,U=w);if(O>=3){let[w]=U.split("|");e-=1,s.push(`Same tool call repeated ${O}\xD7 (tool: ${w})`)}let L=!1,R=t.findIndex(w=>w.role==="user"&&typeof w.content=="string"&&w.content.includes("[SYSTEM STOP]")&&w.content.includes('"valid":true'));R>=0&&n.filter(P=>P.index>R).length>0&&(L=!0),L&&(e-=1.5,s.push('Stop-trigger ignored: tool result contained "valid":true but session continued with more tool calls'));let C=n.filter(w=>w.name==="ssh_exec");if(C.length>=8){let w=0,P=1;for(let k=1;k<C.length;k++)C[k].index<=C[k-1].index+2?P++:(w=Math.max(w,P),P=1);w=Math.max(w,P),w>=8&&(e-=.5,s.push(`SSH reconnect storm: ${w} consecutive SSH calls`))}d&&C.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(f)&&(e-=2,s.push("Surrender: model asked user to manually provide server output instead of gathering it"));let K=new Map;for(let w of a)if(w.name==="read_file"&&w.input?.path){let P=w.input.path;K.has(P)||K.set(P,{count:0,ranges:[]});let k=K.get(P);if(k.count++,w.input.line_start!=null){let N=w.input.line_start||1,T=w.input.line_end||N+350;k.ranges.push([N,T])}}function Q(w,P,k){for(let[N,T]of k){let S=Math.max(w,N),J=Math.min(P,T);if(J>S){let Re=J-S,Ce=P-w||1;if(Re/Ce>=.7)return!0}}return!1}let re=0,V="";for(let[w,P]of K){if(P.count<3)continue;if(P.ranges.length===P.count){let T=!1,S=[];for(let[J,Re]of P.ranges){if(S.length>0&&Q(J,Re,S)){T=!0;break}S.push([J,Re])}if(!T)continue}if(P.count-P.ranges.length<=2&&P.ranges.length>=1){let T=!1,S=[];for(let[J,Re]of P.ranges){if(S.length>0&&Q(J,Re,S)){T=!0;break}S.push([J,Re])}if(!T)continue}P.count>re&&(re=P.count,V=w)}if(re>=3){e-=1;let w=V.split("/").slice(-2).join("/");s.push(`read_file loop: "${w}" read ${re}\xD7 (file already in context)`)}let H=0,_="";for(let[w,P]of K){if(P.ranges.length<4)continue;let k=[],N=!1;for(let[T,S]of P.ranges){if(k.length>0&&Q(T,S,k)){N=!0;break}k.push([T,S])}!N&&P.ranges.length>H&&(H=P.ranges.length,_=w)}if(H>=4){e-=.5;let w=_.split("/").slice(-2).join("/");s.push(`File-scroll pattern: "${w}" read in ${H} sequential sections \u2014 use grep instead`)}let he=new Map;for(let w of a)if(w.name==="grep"&&w.input?.path&&w.input?.pattern){let P=w.input.path;he.has(P)||he.set(P,new Set),he.get(P).add(w.input.pattern)}let de=0,me="";for(let[w,P]of he)w.split("/").pop().includes(".")&&P.size>de&&(de=P.size,me=w);if(de>=3){e-=.75;let w=me.split("/").slice(-2).join("/");s.push(`grep flood on single file: "${w}" searched ${de}\xD7 with different patterns (file already in context)`)}{let w=new Set,P=new Set,k=/^(test_|demo_|temp_|tmp_|scratch_)/;for(let T of n){if(T.name==="write_file"&&T.input?.path){let S=T.input.path.split("/").pop(),J=T.input.path.includes("/tests/");k.test(S)&&!J&&w.add(T.input.path)}if((T.name==="bash"||T.name==="ssh_exec")&&T.input?.command){let S=T.input.command.match(/\brm\s+(?:-\w+\s+)?(\S+)/g);if(S)for(let J of S){let Re=J.split(/\s+/),Ce=Re[Re.length-1];for(let ye of w)(ye.endsWith(Ce)||Ce.endsWith(ye.split("/").pop()))&&P.add(ye)}}}let N=P.size;if(N>=1){let T=Math.min(N*.25,.5);e-=T;let S=[...P].map(J=>J.split("/").pop()).join(", ");s.push(`Temp file write-then-delete: ${S} \u2014 write inline logic or use tests/ instead`)}}let ge=o.filter(w=>w.content.startsWith("EXIT")).length;ge>=10?(e-=1,s.push(`Bash exit-error storm: ${ge} tool results started with EXIT (repeated failing commands)`)):ge>=5&&(e-=.5,s.push(`Repeated bash errors: ${ge} tool results with non-zero exit code`));for(let w of t){if(w.role!=="assistant")continue;let P="";if(typeof w.content=="string"?P=w.content:Array.isArray(w.content)&&(P=w.content.filter(Ce=>Ce&&(Ce.type==="text"||typeof Ce=="string")).map(Ce=>typeof Ce=="string"?Ce:Ce.text||"").join("")),P.length<=5e3)continue;let k=P.split(/(?<=\. )/).filter(Ce=>Ce.trim().length>0);if(k.length<6)continue;let N=new Map;for(let Ce=0;Ce<=k.length-3;Ce++){let ye=k.slice(Ce,Ce+3).join("").trim();ye.length>30&&N.set(ye,(N.get(ye)||0)+1)}let T=0,S="";for(let[Ce,ye]of N)ye>T&&(T=ye,S=Ce);if(T<3)continue;let Re=S.length*T/P.length;if(Re>=.4||T>=10){e-=1.5,s.push(`llm output loop: assistant message repeated content detected (${T}\xD7 same paragraph, ${Math.round(Re*100)}% repeated)`);break}}{let w=new Set(["read_file","list_directory","search_files","glob","grep"]),P=t.some(N=>Array.isArray(N.tool_calls)?N.tool_calls.some(T=>w.has(T.function?.name)):Array.isArray(N.content)?N.content.some(T=>T.type==="tool_use"&&w.has(T.name)):!1);t.some(N=>N.role==="assistant"&&typeof N.content=="string"&&(N.content.includes("## Steps")||N.content.includes("/plan approve")))&&!P&&(e-=2,s.push("plan written without reading any files \u2014 LLM invented data structures from training knowledge (hallucination risk)"))}let we=o.filter(w=>w.content.startsWith("BLOCKED:")&&!w.content.includes("BLOCKED: sed -n")&&!w.content.includes("SSH paused")&&!w.content.includes("SSH temporarily paused"));if(we.length>0){let w=Math.min(we.length*.5,1.5);e-=w,s.push(`${we.length} tool call${we.length===1?"":"s"} blocked (agent attempted denied actions)`)}let Se=t.filter(w=>{let P=typeof w.content=="string"?w.content:"";return/\[SYSTEM WARNING\] Context wiped \d+×/.test(P)}).length;if(Se>0){let w=Math.min(Se*1,2);e-=w,s.push(`Super-nuclear context wipe fired ${Se}\xD7 (context collapse \u2014 task too large or read loops)`)}{let w=!1,P=!1,k=!1;for(let T of n){if(T.name!=="bash")continue;let S=(T.input?.command||T.input?.cmd||"").trim();!(/cat\s*>/.test(S)||/<</.test(S))&&/\bcat\s+\S/.test(S)&&(w=!0),/^\s*ls(\s|$)/.test(S)&&!/npm|yarn|pnpm|make|git\b/.test(S)&&(P=!0),/\bfind\s+\S/.test(S)&&!/git\b|npm\b|-exec\b/.test(S)&&(k=!0)}let N=[w,P,k].filter(Boolean).length;if(N>0){let T=Math.min(N*.25,.75);e-=T;let S=[];w&&S.push("cat (use read_file)"),P&&S.push("ls (use list_directory)"),k&&S.push("find (use glob)"),s.push(`bash used instead of dedicated tool: ${S.join(", ")}`)}}{let w=n.some(S=>(S.name==="write_file"||S.name==="Write")&&S.input?.path&&(S.input.path.endsWith("requirements.txt")||S.input.path.endsWith("Pipfile")||S.input.path.endsWith("pyproject.toml"))),P=n.some(S=>(S.name==="write_file"||S.name==="Write")&&S.input?.path&&S.input.path.endsWith("package.json")),k=n.filter(S=>(S.name==="bash"||S.name==="Bash")&&S.input?.command).map(S=>S.input.command),N=k.some(S=>/pip\s+install|python\s+-m\s+venv/.test(S)),T=k.some(S=>/npm\s+install/.test(S));w&&!N?(e-=1,s.push("wrote requirements.txt but never ran pip install \u2014 environment not bootstrapped")):P&&!T&&n.some(J=>(J.name==="write_file"||J.name==="Write")&&J.input?.path&&/(\/src\/|index\.js|App\.js|main\.js)/.test(J.input.path))&&(e-=.75,s.push("created new React/Node project but never ran npm install \u2014 project is not runnable"))}if(d){let w=t.find(S=>S.role==="assistant"),P="";w&&(typeof w.content=="string"?P=w.content:Array.isArray(w.content)&&(P=w.content.filter(S=>S&&(S.type==="text"||typeof S=="string")).map(S=>typeof S=="string"?S:S.text||"").join("")));let k=P.slice(0,400),N=/^[\d\s\+\-\*\/×÷\(\)\.]+\s*=\s*[\d\s\+\-\*\/×÷\(\)\.]+[.\n]/m,T=k.split(`
521
+ `).find(S=>{let J=S.trim();return J.length>0&&J.length<=30&&/^\d/.test(J)&&/=/.test(J)&&!/[a-zA-Z]/.test(J)});if(N.test(k)||T){e-=1.5;let S=(T||k.split(`
522
+ `)[0]).trim().slice(0,40);s.push(`Thinking-chain leak: non-sequitur artifact at response start: "${S}"`)}}if(d&&r>0){let w=t.findIndex(k=>k.role==="assistant"),P=t.findIndex(k=>!!(Array.isArray(k.tool_calls)&&k.tool_calls.length>0||Array.isArray(k.content)&&k.content.some(N=>N&&N.type==="tool_use")));if(w!==-1&&P!==-1&&w<P){let k=t[w],N="";typeof k.content=="string"?N=k.content:Array.isArray(k.content)&&(N=k.content.filter(J=>J&&(J.type==="text"||typeof J=="string")).map(J=>typeof J=="string"?J:J.text||"").join(""));let T=/ssh\s+\S+@\S+\s+"[^"]*\/[^"]*\./.test(N),S=/\/(?:home|var|etc|usr|opt|root|srv|data)\/[a-zA-Z0-9_.\-\/]+\.[a-zA-Z]{2,5}/.test(N);(T||S)&&(e-=1,s.push("Answer-before-verify: model gave concrete file paths/SSH commands before making any tool calls (paths guessed, not verified)"))}}if(d){let w=f;if(w.length>100){let k=(w.match(/^```/gm)||[]).length%2!==0,N=/"\s*:\s*$/.test(w.trimEnd()),T=/[,\[{]\s*$/.test(w.trimEnd());(k||N||T)&&(e-=.75,s.push("Truncated response: last assistant message ends mid-code-block or mid-JSON (model hit token limit)"))}}{let w=[];t.forEach((k,N)=>{let T=[];Array.isArray(k.tool_calls)&&k.tool_calls.forEach(S=>{if((S.function?.name||S.name||"")==="read_file"){let Re={};try{Re=typeof S.function?.arguments=="string"?JSON.parse(S.function.arguments):S.function?.arguments||{}}catch{}(Re.path||"").endsWith(".json")&&T.push({id:S.id,path:Re.path})}}),Array.isArray(k.content)&&k.content.forEach(S=>{S&&S.type==="tool_use"&&S.name==="read_file"&&(S.input?.path||"").endsWith(".json")&&T.push({id:S.id,path:S.input.path})}),T.forEach(S=>w.push({...S,msgIdx:N}))});let P=0;for(let k of w){let N=null;for(let S of t){if(S.role==="tool"&&S.tool_call_id===k.id&&typeof S.content=="string"){N=S.content;break}if(S.role==="user"&&Array.isArray(S.content)){let J=S.content.find(Re=>Re&&Re.type==="tool_result"&&Re.tool_use_id===k.id);if(J){N=typeof J.content=="string"?J.content:"";break}}}if(!N)continue;N.split(`
523
+ `).filter(S=>S.trim()).length<5&&/^\s*\[/.test(N)&&!/\]\s*$/.test(N.trimEnd())&&P++}P>=1&&(e-=.75,s.push(`Shallow JSON read: ${P} .json file${P>1?"s":""} read with < 5 lines \u2014 array was incomplete, model drew conclusions from truncated data`))}{let w=o.filter(P=>/argument errors?/i.test(P.content)||/missing required (argument|parameter)/i.test(P.content)||/invalid argument/i.test(P.content));w.length>=3?(e-=.75,s.push(`Repeated tool argument errors: ${w.length} tool calls returned argument errors \u2014 model couldn't correct its tool usage`)):w.length>=2&&(e-=.25,s.push(`Tool argument errors: ${w.length} tool calls returned argument errors`))}{let w=!1,P=0,k=0;for(let N of a){if((N.name==="bash"||N.name==="Bash")&&N.input?.command&&/git\s+commit\b/.test(N.input.command)){w&&(k=Math.max(k,P)),w=!0,P=0;continue}w&&(N.name==="bash"||N.name==="Bash")&&N.input?.command&&/git\s+(status|diff|log|show)\b/.test(N.input.command)&&P++}k=Math.max(k,P),k>=3&&(e-=.75,s.push(`Post-commit verification waste: ${k} git status/diff/log calls after commit`))}e=Math.max(0,Math.min(10,e)),e=Math.round(e*10)/10;let fe=e>=9?"A":e>=8?"B":e>=7?"C":e>=6?"D":"F",Pe=s.length===0?`Clean session \u2014 no quality issues detected (${r} tool calls)`:`${s.length} issue${s.length===1?"":"s"} found \u2014 ${r} tool calls`;return{score:e,grade:fe,issues:s,summary:Pe}}function z0(t){try{let{loadSession:e}=Mr(),s=e(t);return s?Hf(s.messages||[]):null}catch{return null}}function X0(t,e=null){let{score:s,issues:n}=t,o=e?.dim||"",r=e?.reset||"",i=e?.yellow||"";if(s>=8||n.length===0)return"";let a=n.map(u=>u.replace(/:\s+\d+.*$/,"").replace(/\s*\(.*?\)/,"").replace(/\s*—.*$/,""));if(s>=6){let u=a.slice(0,3),d=a.length-u.length,f=u.join(" \xB7 ");return d>0&&(f+=` (+${d})`),`
524
+ ${o}${f}${r}`}let c="";for(let u of a.slice(0,4))c+=`
525
+ ${i}\u26A0${r} ${o}${u}${r}`;let l=a.length-4;return l>0&&(c+=`
526
+ ${o}(+${l} more)${r}`),c}function V0(t,e={}){try{let s=Df.join(process.cwd(),".nex");so.existsSync(s)||so.mkdirSync(s,{recursive:!0});let n=Df.join(s,"benchmark-history.json"),o=[];if(so.existsSync(n))try{o=JSON.parse(so.readFileSync(n,"utf-8"))}catch{o=[]}Array.isArray(o)||(o=[]);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:[]};o.push(i),o.length>100&&(o=o.slice(o.length-100)),so.writeFileSync(n,JSON.stringify(o,null,2))}catch{}}Gf.exports={scoreMessages:Hf,scoreSession:z0,formatScore:X0,appendScoreHistory:V0,_extractToolCalls:qf,_extractToolResults:Ff,_getLastAssistantText:Bf,_getLastNAssistantTexts:Wf,_countDuplicateToolCalls:Uf}});var ls=se((rv,Jf)=>{"use strict";var J0=require("os"),Yf=require("path"),oo=require("fs"),ro=Yf.join(J0.homedir(),".nex-code","model-routing.json"),Pr={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}},Kf=["agentic","frontend","sysadmin","data","coding"];function Z0(t){if(!t||t.length<8)return null;for(let e of Kf){let s=Pr[e];if(!s.pattern||s.pattern.test(t))return s}return Pr.coding}function io(){try{if(oo.existsSync(ro))return JSON.parse(oo.readFileSync(ro,"utf-8"))}catch{}return{}}function zf(t){let e=Pr[t];return e?.envVar&&process.env[e.envVar]?process.env[e.envVar]:io()[t]||null}var Xf={plan:10,implement:35,verify:8},qa={plan:"qwen3-coder:480b",implement:null,verify:"devstral-small-2:24b"};function Vf(){let t=io();if(t.phases&&Object.keys(t.phases).length>0)return t.phases;try{let{getActiveProviderName:e}=He();if(e()==="ollama")return qa}catch{}return process.env.NEX_PHASE_ROUTING==="1"?qa:null}function Q0(t,e){let s=Vf();return s?.[t]?s[t]:e?zf(e):null}function eb(t){return io().phaseBudgets?.[t]||Xf[t]||20}function tb(){return process.env.NEX_PHASE_ROUTING==="0"?!1:Vf()!==null}function nb(t){let e=Yf.dirname(ro);oo.existsSync(e)||oo.mkdirSync(e,{recursive:!0});let s=io(),n={...s,...t};!t.phases&&s.phases&&(n.phases=s.phases),!t.phaseBudgets&&s.phaseBudgets&&(n.phaseBudgets=s.phaseBudgets),oo.writeFileSync(ro,JSON.stringify(n,null,2))}Jf.exports={CATEGORIES:Pr,DETECTION_ORDER:Kf,detectCategory:Z0,getModelForCategory:zf,getModelForPhase:Q0,getPhaseBudget:eb,isPhaseRoutingEnabled:tb,DEFAULT_PHASE_BUDGETS:Xf,BUILTIN_PHASE_DEFAULTS:qa,saveRoutingConfig:nb,loadRoutingConfig:io,ROUTING_CONFIG_PATH:ro}});var tp=se((iv,ep)=>{"use strict";var kn=require("fs"),ao=require("path"),sb=require("os"),{detectCategory:ob}=ls(),us=ao.join(sb.homedir(),".nex-code","examples"),Fa=ao.join(__dirname,"..","examples");function Zf(t){try{let s=kn.readFileSync(t,"utf-8").replace(/<!--[\s\S]*?-->/g,"").trim(),n=s.match(/^user:\s*(.+)$/m);if(!n)return null;let o=n[1].trim(),r=s.indexOf(`
527
+ A: |`);if(r===-1)return null;let i=s.slice(r+5),a=[],c=0;for(let u of i.split(`
528
+ `))if(u.startsWith(" ")){for(;c>0;)a.push(""),c--;a.push(u.slice(2))}else if(u.trim()==="")a.length>0&&c++;else break;if(a.length===0)return null;let l=a.join(`
529
+ `).trim();return{user:o,assistant:l}}catch{return null}}function Qf(t){let e=`${t}.md`,s=ao.join(us,e);if(kn.existsSync(s)){let o=Zf(s);if(o)return o}let n=ao.join(Fa,e);return kn.existsSync(n)?Zf(n):null}function rb(t){if(process.env.NEX_FEW_SHOT==="0"||!t||t.length<8)return null;let e=ob(t);return e?Qf(e.id):null}function ib(){let t=new Set;for(let e of[us,Fa])try{for(let s of kn.readdirSync(e))s.endsWith(".md")&&t.add(s.replace(".md",""))}catch{}return[...t].sort()}function ab(t,e){kn.existsSync(us)||kn.mkdirSync(us,{recursive:!0});let s=`<!-- Auto-extracted from high-scoring session \u2014 edit as needed -->
530
+
531
+ user: ${e.user}
532
+
533
+ A: |
534
+ ${e.assistant.split(`
535
+ `).map(n=>` ${n}`).join(`
536
+ `)}
537
+ `;kn.writeFileSync(ao.join(us,`${t}.md`),s,"utf-8")}ep.exports={getFewShotForInput:rb,loadExampleForCategory:Qf,listAvailableExamples:ib,savePrivateExample:ab,PRIVATE_EXAMPLES_DIR:us,BUNDLED_EXAMPLES_DIR:Fa}});var ap=se((cv,ip)=>{var pt=require("fs"),ds=require("path"),{C:av}=Ue(),{atomicWrite:cb,withFileLockSync:lb}=fn(),Ir={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",ssh_exec:"allow",ssh_upload:"ask",ssh_download:"ask"},fs={...Ir};function np(){let t=ds.join(process.cwd(),".nex","config.json");if(pt.existsSync(t))try{let e=JSON.parse(pt.readFileSync(t,"utf-8"));e.permissions&&(fs={...Ir,...e.permissions})}catch{}}function ub(){let t=ds.join(process.cwd(),".nex"),e=ds.join(t,"config.json");pt.existsSync(t)||pt.mkdirSync(t,{recursive:!0}),lb(e,()=>{let s={};if(pt.existsSync(e))try{s=JSON.parse(pt.readFileSync(e,"utf-8"))}catch{s={}}s.permissions=fs,cb(e,JSON.stringify(s,null,2))})}function sp(t){return fs[t]||"ask"}function db(t,e){return["allow","ask","deny"].includes(e)?(fs[t]=e,!0):!1}function fb(t){return sp(t)}function pb(){return Object.entries(fs).map(([t,e])=>({tool:t,mode:e}))}function hb(){fs={...Ir}}var co={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 op(){let t=ds.join(process.cwd(),".nex","config.json");try{return pt.existsSync(t)&&JSON.parse(pt.readFileSync(t,"utf-8")).teamPermissions||null}catch{return null}}function mb(t){let e=ds.join(process.cwd(),".nex"),s=ds.join(e,"config.json");pt.existsSync(e)||pt.mkdirSync(e,{recursive:!0});let n={};try{pt.existsSync(s)&&(n=JSON.parse(pt.readFileSync(s,"utf-8")))}catch{n={}}n.teamPermissions=t,pt.writeFileSync(s,JSON.stringify(n,null,2),"utf-8")}function rp(){let t=op();if(!t)return co.admin;let e=t.role||"admin",s=co[e]||co.admin;return{...s,...t.overrides,blockedTools:[...s.blockedTools||[],...t.overrides?.blockedTools||[]]}}function gb(t){let e=rp();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 yb(){return Object.entries(co).map(([t,e])=>({name:t,description:e.description,toolCount:e.allowedTools?`${e.allowedTools.length} allowed`:"all allowed",blockedCount:e.blockedTools.length}))}np();ip.exports={getPermission:sp,setPermission:db,checkPermission:fb,listPermissions:pb,loadPermissions:np,savePermissions:ub,resetPermissions:hb,DEFAULT_PERMISSIONS:Ir,PERMISSION_PRESETS:co,loadPresetConfig:op,savePresetConfig:mb,getEffectivePreset:rp,isToolAllowed:gb,listPresets:yb}});var qr=se((uv,fp)=>{var Sn=require("fs"),jr=require("path"),lv=require("readline"),{C:ke}=Ue(),_e=null,Wa=!1,Ua=null,cp=new Set(["read_file","list_directory","search_files","glob","grep","web_search","web_fetch","git_status","git_diff","git_log","git_show"]);function Dr(){return jr.join(process.cwd(),".nex","plans")}function lp(){let t=Dr();Sn.existsSync(t)||Sn.mkdirSync(t,{recursive:!0})}function $b(t,e=[]){return _e={name:`plan-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,task:t,steps:e.map(s=>({description:s.description||s,files:s.files||[],status:"pending"})),status:"draft",createdAt:new Date().toISOString()},_e}function wb(){return _e}function bb(t){Wa=t}function _b(){return Wa}function xb(){return!_e||_e.status!=="draft"?!1:(_e.status="approved",_e.updatedAt=new Date().toISOString(),!0)}function kb(){return!_e||_e.status!=="approved"?!1:(_e.status="executing",!0)}function Ba(t,e){return!_e||t<0||t>=_e.steps.length?!1:(_e.steps[t].status=e,_e.updatedAt=new Date().toISOString(),_e.steps.every(s=>s.status==="done"||s.status==="skipped")&&(_e.status="completed"),!0)}function vb(t){if(!t)return`${ke.dim}No active plan${ke.reset}`;let e={draft:`${ke.yellow}DRAFT${ke.reset}`,approved:`${ke.green}APPROVED${ke.reset}`,executing:`${ke.blue}EXECUTING${ke.reset}`,completed:`${ke.green}COMPLETED${ke.reset}`},s=[];s.push(`
538
+ ${ke.bold}${ke.cyan}Plan: ${t.task}${ke.reset}`),s.push(`${ke.dim}Status: ${e[t.status]||t.status}${ke.reset}
539
+ `);for(let n=0;n<t.steps.length;n++){let o=t.steps[n],r;switch(o.status){case"done":r=`${ke.green}\u2713${ke.reset}`;break;case"in_progress":r=`${ke.blue}\u2192${ke.reset}`;break;case"skipped":r=`${ke.dim}\u25CB${ke.reset}`;break;default:r=`${ke.dim} ${ke.reset}`}s.push(` ${r} ${ke.bold}Step ${n+1}:${ke.reset} ${o.description}`),o.files.length>0&&s.push(` ${ke.dim}Files: ${o.files.join(", ")}${ke.reset}`)}return s.push(""),s.join(`
540
+ `)}function Sb(t){if(t||(t=_e),!t)return null;lp();let e=jr.join(Dr(),`${t.name}.json`);return Sn.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function Eb(t){let e=jr.join(Dr(),`${t}.json`);if(!Sn.existsSync(e))return null;try{let s=JSON.parse(Sn.readFileSync(e,"utf-8"));return _e=s,s}catch{return null}}function Tb(){lp();let t=Dr(),e=Sn.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(Sn.readFileSync(jr.join(t,n),"utf-8"));s.push({name:o.name,task:o.task,status:o.status,steps:o.steps?o.steps.length:0,createdAt:o.createdAt})}catch{}return s.sort((n,o)=>(o.createdAt||"").localeCompare(n.createdAt||""))}function Rb(t){if(!t)return[];let e=[],s=t.match(/##\s+Steps?\s*\n([\s\S]*?)(?:\n##|\s*$)/i),n=s?s[1]:t,o=/^\s*(\d+)[.)]\s+(.+)/gm,r;for(;(r=o.exec(n))!==null;){let a=r[2].trim().replace(/^\*\*What\*\*:\s*/i,"").replace(/^\*\*\d+\.\*\*\s*/,"").replace(/\*\*/g,"").trim();a.length>3&&e.push({description:a,files:[],status:"pending"})}if(e.length===0){let i=/\*\*Step\s+\d+[:.]\*\*\s*(.+)/gi;for(;(r=i.exec(t))!==null;){let a=r[1].replace(/\*\*/g,"").trim();a.length>3&&e.push({description:a,files:[],status:"pending"})}}if(e.length>0){let i=/\*\*(?:Where|Files?)\*\*:\s*(.+)/gi,a=[...t.matchAll(i)];for(let c=0;c<Math.min(e.length,a.length);c++){let l=a[c][1];e[c].files=l.split(/[,\s]+/).filter(u=>/[./]/.test(u)).slice(0,5)}}return e}function Cb(t){Ua=t}function Ab(){return Ua}function Ob(){_e=null,Wa=!1,Ua=null,Pb()}function Nb(){return`
541
+ PLAN MODE ACTIVE: You are in analysis-only mode. You MUST NOT execute any changes.
542
+
543
+ # Allowed Tools (read-only)
544
+ You may ONLY use these tools: ${[...cp].join(", ")}
545
+ Any other tool call will be blocked and returned with an error.
546
+
547
+ # MANDATORY: Read Before You Plan
548
+ You MUST call at least 2 read-only tools before writing any plan. NEVER assume:
549
+ - What database type is used (SQLite vs JSON files vs MongoDB \u2014 READ to find out)
550
+ - What file contains existing routes (check with glob/read_file first)
551
+ - What methods a module exposes (read the module file first)
552
+ - What the existing code structure looks like (read it, don't invent it)
553
+
554
+ For any task involving a named module (e.g. "fitness", "calendar", "reminder"):
555
+ 1. FIRST: glob for the module file and read it to see actual methods/data structures
556
+ 2. THEN: read the route file if it exists
557
+ 3. ONLY THEN: write the plan based on what you actually found
558
+
559
+ # Analysis Phase
560
+ Thoroughly investigate before writing a plan:
561
+ - Scope: What files and modules are affected?
562
+ - Architecture: How does the current code work? What patterns does it follow?
563
+ - Dependencies: What depends on the code being changed? What might break?
564
+ - Tests: What test coverage exists? What new tests are needed?
565
+
566
+ # Required Plan Format
567
+ After analysis, output a plan in this exact markdown format:
568
+
569
+ ## Summary
570
+ One paragraph describing the overall goal.
571
+
572
+ ## Steps
573
+ Numbered list. Each step:
574
+ - **What**: Clear description of the change
575
+ - **Where**: Specific file(s) and line ranges
576
+ - **How**: Implementation approach (edit, create, delete)
577
+
578
+ ## Files Affected
579
+ Bullet list of all files that will be modified or created.
580
+
581
+ ## Risks
582
+ Bullet list of potential issues and mitigations.
583
+
584
+ # Important
585
+ - Order steps by dependency (later steps may depend on earlier ones).
586
+ - After presenting the plan, tell the user to type \`/plan approve\` to proceed.
587
+ - Do NOT make any file changes \u2014 your role is analysis and planning only.
588
+ - 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 vn=0;function Mb(){!_e||_e.status!=="executing"||(vn>0&&Ba(vn-1,"done"),vn<_e.steps.length&&(Ba(vn,"in_progress"),vn++))}function Lb(){if(!_e||_e.status!=="executing"||_e.steps.length===0)return null;let t=Math.min(vn,_e.steps.length),e=_e.steps.length,s=Math.max(0,t-1),n=_e.steps[s]?.description||"";return{current:t,total:e,description:n}}function Pb(){vn=0}var up=["interactive","semi-auto","autonomous"],dp="interactive";function Ib(t){return up.includes(t)?(dp=t,!0):!1}function jb(){return dp}fp.exports={createPlan:$b,getActivePlan:wb,setPlanMode:bb,isPlanMode:_b,approvePlan:xb,startExecution:kb,updateStep:Ba,formatPlan:vb,savePlan:Sb,loadPlan:Eb,listPlans:Tb,clearPlan:Ob,getPlanModePrompt:Nb,setPlanContent:Cb,getPlanContent:Ab,extractStepsFromText:Rb,advancePlanStep:Mb,getPlanStepInfo:Lb,PLAN_MODE_ALLOWED_TOOLS:cp,setAutonomyLevel:Ib,getAutonomyLevel:jb,AUTONOMY_LEVELS:up}});var kp=se((dv,xp)=>{var{C:x}=Ue();function pp(){return Math.max(10,(process.stdout.columns||80)-2)}function Db(t){if(!t)return"";let e=t.split(`
589
+ `),s=[],n=!1,o="";for(let r of e){let i=pp();if(r.trim().startsWith("```")){if(n)s.push(`${x.dim}${"\u2500".repeat(40)}${x.reset}`),n=!1,o="";else{n=!0,o=r.trim().substring(3).trim();let a=o?` ${o} `:"";s.push(`${x.dim}${"\u2500".repeat(3)}${a}${"\u2500".repeat(Math.max(0,37-a.length))}${x.reset}`)}continue}if(n){s.push(` ${Ga(r,o)}`);continue}if(r.startsWith("### ")){s.push(`${x.bold}${x.cyan} ${En(r.substring(4))}${x.reset}`);continue}if(r.startsWith("## ")){s.push(`${x.bold}${x.cyan} ${En(r.substring(3))}${x.reset}`);continue}if(r.startsWith("# ")){s.push(`${x.bold}${x.cyan}${En(r.substring(2))}${x.reset}`);continue}if(/^\s*[-*]\s/.test(r)){let a=r.match(/^(\s*)/)[1],c=r.replace(/^\s*[-*]\s/,""),l=`${a}${x.cyan}\u2022${x.reset} ${Tn(c)}`;s.push(Rn(l,i,a+" "));continue}if(/^\s*\d+\.\s/.test(r)){let a=r.match(/^(\s*)(\d+)\.\s(.*)/);if(a){let c=a[1],l=a[2],u=a[3],d=`${c}${x.cyan}${l}.${x.reset} ${Tn(u)}`,f=c+" ".repeat(l.length+2);s.push(Rn(d,i,f));continue}}s.push(Rn(Tn(r),i))}return s.join(`
590
+ `)}function En(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function Tn(t){return t?t.replace(/`([^`]+)`/g,`${x.cyan}$1${x.reset}`).replace(/\*\*([^*]+)\*\*/g,`${x.bold}$1${x.reset}`).replace(/\*([^*]+)\*/g,`${x.dim}$1${x.reset}`).replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${x.cyan}$1${x.reset} ${x.dim}($2)${x.reset}`):""}function Ga(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?hp(t):e==="bash"||e==="sh"||e==="shell"||e==="zsh"?mp(t):e==="json"||e==="jsonc"?gp(t):e==="python"||e==="py"?yp(t):e==="go"||e==="golang"?$p(t):e==="rust"||e==="rs"?wp(t):e==="css"||e==="scss"||e==="less"?bp(t):e==="html"||e==="xml"||e==="svg"||e==="htm"?_p(t):t:""}function hp(t){let e=/\b(const|let|var|function|return|if|else|for|while|class|import|export|from|require|async|await|new|this|throw|try|catch|switch|case|break|default|typeof|instanceof)\b/g,s=/(["'`])(?:(?=(\\?))\2.)*?\1/g,n=/(\/\/.*$)/,o=/\b(\d+\.?\d*)\b/g,r=t;return r=r.replace(o,`${x.yellow}$1${x.reset}`),r=r.replace(e,`${x.magenta}$1${x.reset}`),r=r.replace(s,`${x.green}$&${x.reset}`),r=r.replace(n,`${x.dim}$1${x.reset}`),r}function mp(t){let e=/^(\s*)([\w-]+)/,s=/(--?\w[\w-]*)/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(#.*$)/,r=t;return r=r.replace(s,`${x.cyan}$1${x.reset}`),r=r.replace(e,`$1${x.green}$2${x.reset}`),r=r.replace(n,`${x.yellow}$&${x.reset}`),r=r.replace(o,`${x.dim}$1${x.reset}`),r}function gp(t){let e=/("[\w-]+")\s*:/g,s=/:\s*("(?:[^"\\]|\\.)*")/g,n=/:\s*(\d+\.?\d*)/g,o=/:\s*(true|false|null)/g,r=t;return r=r.replace(e,`${x.cyan}$1${x.reset}:`),r=r.replace(s,`: ${x.green}$1${x.reset}`),r=r.replace(n,`: ${x.yellow}$1${x.reset}`),r=r.replace(o,`: ${x.magenta}$1${x.reset}`),r}function yp(t){let e=/\b(def|class|if|elif|else|for|while|return|import|from|as|try|except|finally|raise|with|yield|lambda|pass|break|continue|and|or|not|in|is|None|True|False|self|async|await|nonlocal|global)\b/g,s=/("""[\s\S]*?"""|'''[\s\S]*?'''|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')/g,n=/(#.*$)/,o=/\b(\d+\.?\d*)\b/g,r=/^(\s*@\w+)/,i=t;return i=i.replace(o,`${x.yellow}$1${x.reset}`),i=i.replace(e,`${x.magenta}$1${x.reset}`),i=i.replace(r,`${x.cyan}$1${x.reset}`),i=i.replace(s,`${x.green}$&${x.reset}`),i=i.replace(n,`${x.dim}$1${x.reset}`),i}function $p(t){let e=/\b(func|package|import|var|const|type|struct|interface|map|chan|go|defer|return|if|else|for|range|switch|case|default|break|continue|select|fallthrough|nil|true|false|make|new|len|cap|append|copy|delete|panic|recover)\b/g,s=/\b(string|int|int8|int16|int32|int64|uint|uint8|uint16|uint32|uint64|float32|float64|bool|byte|rune|error|any)\b/g,n=/(["'`])(?:(?=(\\?))\2.)*?\1/g,o=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,i=t;return i=i.replace(r,`${x.yellow}$1${x.reset}`),i=i.replace(s,`${x.cyan}$1${x.reset}`),i=i.replace(e,`${x.magenta}$1${x.reset}`),i=i.replace(n,`${x.green}$&${x.reset}`),i=i.replace(o,`${x.dim}$1${x.reset}`),i}function wp(t){let e=/\b(fn|let|mut|const|struct|enum|impl|trait|pub|use|mod|crate|self|super|match|if|else|for|while|loop|return|break|continue|where|as|in|ref|move|async|await|unsafe|extern|type|static|dyn|macro_rules)\b/g,s=/\b(i8|i16|i32|i64|i128|u8|u16|u32|u64|u128|f32|f64|bool|char|str|String|Vec|Option|Result|Box|Rc|Arc|Self|Some|None|Ok|Err|true|false)\b/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,i=/\b(\w+!)/g,a=t;return a=a.replace(r,`${x.yellow}$1${x.reset}`),a=a.replace(s,`${x.cyan}$1${x.reset}`),a=a.replace(e,`${x.magenta}$1${x.reset}`),a=a.replace(i,`${x.yellow}$1${x.reset}`),a=a.replace(n,`${x.green}$&${x.reset}`),a=a.replace(o,`${x.dim}$1${x.reset}`),a}function bp(t){let e=/^(\s*)([\w-]+)\s*:/,s=/:\s*([^;]+)/,n=/^(\s*[.#@][\w-]+)/,o=/\b(\d+\.?\d*(px|em|rem|%|vh|vw|s|ms|deg|fr)?)\b/g,r=/(\/\*.*?\*\/|\/\/.*$)/,i=/(#[0-9a-fA-F]{3,8})\b/g,a=t;return a=a.replace(i,`${x.yellow}$1${x.reset}`),a=a.replace(o,`${x.yellow}$1${x.reset}`),a=a.replace(e,`$1${x.cyan}$2${x.reset}:`),a=a.replace(n,`$1${x.magenta}$&${x.reset}`),a=a.replace(r,`${x.dim}$1${x.reset}`),a}function _p(t){let e=/<\/?(\w[\w-]*)/g,s=/\s([\w-]+)=/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(<!--.*?-->)/g,r=/(&\w+;)/g,i=t;return i=i.replace(o,`${x.dim}$1${x.reset}`),i=i.replace(n,`${x.green}$&${x.reset}`),i=i.replace(e,`<${x.magenta}$1${x.reset}`),i=i.replace(s,` ${x.cyan}$1${x.reset}=`),i=i.replace(r,`${x.yellow}$1${x.reset}`),i}function Rn(t,e,s=""){if(!e||e<10)return t;let n="",o=0,r=-1,i=0,a=0,c=t.length;for(;i<c;){if(t[i]==="\x1B"){let l=i+1;if(l<c&&t[l]==="["){for(l++;l<c&&!/[a-zA-Z]/.test(t[l]);)l++;l<c&&l++}i=l;continue}if(t[i]===" "&&(r=i),o++,o>e&&r!==-1){n+=t.slice(a,r)+`
591
+ `+s,a=r+1,i=a,o=s.length,r=-1;continue}o>e&&r===-1&&(n+=t.slice(a,i)+`
592
+ `+s,a=i,o=s.length+1),i++}return n+=t.slice(a),n}function qb(t,e){if(!t||t.length===0)return"";let s=t.map((i,a)=>{let c=e.reduce((l,u)=>Math.max(l,(u[a]||"").length),0);return Math.max(i.length,c)}),n=s.map(i=>"\u2500".repeat(i+2)).join("\u253C"),o=t.map((i,a)=>` ${x.bold}${i.padEnd(s[a])}${x.reset} `).join("\u2502"),r=[];r.push(`${x.dim}\u250C${n.replace(/┼/g,"\u252C")}\u2510${x.reset}`),r.push(`${x.dim}\u2502${x.reset}${o}${x.dim}\u2502${x.reset}`),r.push(`${x.dim}\u251C${n}\u2524${x.reset}`);for(let i of e){let a=t.map((c,l)=>` ${(i[l]||"").padEnd(s[l])} `).join(`${x.dim}\u2502${x.reset}`);r.push(`${x.dim}\u2502${x.reset}${a}${x.dim}\u2502${x.reset}`)}return r.push(`${x.dim}\u2514${n.replace(/┼/g,"\u2534")}\u2518${x.reset}`),r.join(`
593
+ `)}function Fb(t,e,s,n=30){let o=s>0?Math.round(e/s*100):0,r=Math.round(o/100*n),i=n-r,a=o>=100?x.green:o>50?x.yellow:x.cyan;return` ${t} ${a}${"\u2588".repeat(r)}${x.dim}${"\u2591".repeat(i)}${x.reset} ${o}% (${e}/${s})`}var Ha=class{constructor(){this.buffer="",this.inCodeBlock=!1,this.codeBlockLang="",this.lineCount=0,this._cursorTimer=null,this._cursorFrame=0,this._cursorActive=!1}_safeWrite(e){try{this.lineCount+=(e.match(/\n/g)||[]).length,process.stdout.write(e)}catch(s){if(s.code!=="EPIPE")throw s}}_cursorWrite(e){try{process.stderr.write(e)}catch(s){if(s.code!=="EPIPE")throw s}}startCursor(){process.stderr.isTTY&&(this._cursorActive=!0,this._cursorFrame=0,this._cursorWrite("\x1B[?25l"),this._renderCursor(),this._cursorTimer=setInterval(()=>this._renderCursor(),100))}_renderCursor(){let s=[0,1,2,3,4,3,2,1],n=s[this._cursorFrame%s.length],o="";for(let r=0;r<5;r++)o+=r===n?"\x1B[36m\u25CF\x1B[0m":" ";this._cursorWrite(`\x1B[2K\r${o}`),this._cursorFrame++}_clearCursorLine(){this._cursorActive&&this._cursorWrite("\x1B[2K\r")}stopCursor(){this._cursorTimer&&(clearInterval(this._cursorTimer),this._cursorTimer=null),this._cursorActive&&(this._cursorWrite("\x1B[2K\r\x1B[?25h"),this._cursorActive=!1)}push(e){if(!e)return;this._clearCursorLine(),this.buffer+=e;let s;for(;(s=this.buffer.indexOf(`
594
+ `))!==-1;){let n=this.buffer.substring(0,s);this.buffer=this.buffer.substring(s+1),this._renderLine(n)}this._cursorActive&&(this._renderCursor(),this._cursorTimer&&clearInterval(this._cursorTimer),this._cursorTimer=setInterval(()=>this._renderCursor(),100))}flush(){this.stopCursor(),this.buffer&&(this._renderLine(this.buffer),this.buffer=""),this.inCodeBlock&&(this._safeWrite(`${x.dim}${"\u2500".repeat(40)}${x.reset}
595
+ `),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){let s=pp();if(e.trim().startsWith("```")){if(this.inCodeBlock)this._safeWrite(`${x.dim}${"\u2500".repeat(40)}${x.reset}
596
+ `),this.inCodeBlock=!1,this.codeBlockLang="";else{this.inCodeBlock=!0,this.codeBlockLang=e.trim().substring(3).trim();let o=this.codeBlockLang?` ${this.codeBlockLang} `:"";this._safeWrite(`${x.dim}${"\u2500".repeat(3)}${o}${"\u2500".repeat(Math.max(0,37-o.length))}${x.reset}
597
+ `)}return}if(this.inCodeBlock){this._safeWrite(` ${Ga(e,this.codeBlockLang)}
598
+ `);return}if(e.startsWith("### ")){this._safeWrite(`${x.bold}${x.cyan} ${En(e.substring(4))}${x.reset}
599
+ `);return}if(e.startsWith("## ")){this._safeWrite(`${x.bold}${x.cyan} ${En(e.substring(3))}${x.reset}
600
+ `);return}if(e.startsWith("# ")){this._safeWrite(`${x.bold}${x.cyan}${En(e.substring(2))}${x.reset}
601
+ `);return}if(/^\s*[-*]\s/.test(e)){let o=e.match(/^(\s*)/)[1],r=e.replace(/^\s*[-*]\s/,""),i=`${o}${x.cyan}\u2022${x.reset} ${Tn(r)}`,a=Rn(i,s,o+" ");this._safeWrite(`${a}
602
+ `);return}if(/^\s*\d+\.\s/.test(e)){let o=e.match(/^(\s*)(\d+)\.\s(.*)/);if(o){let r=o[1],i=o[2],a=o[3],c=`${r}${x.cyan}${i}.${x.reset} ${Tn(a)}`,l=r+" ".repeat(i.length+2),u=Rn(c,s,l);this._safeWrite(`${u}
603
+ `);return}}let n=Rn(Tn(e),s);this._safeWrite(`${n}
604
+ `)}};xp.exports={renderMarkdown:Db,renderInline:Tn,stripHeadingMarkers:En,highlightCode:Ga,highlightJS:hp,highlightBash:mp,highlightJSON:gp,highlightPython:yp,highlightGo:$p,highlightRust:wp,highlightCSS:bp,highlightHTML:_p,renderTable:qb,renderProgress:Fb,wrapAnsi:Rn,StreamRenderer:Ha}});var Rp=se((fv,Tp)=>{var{execSync:Bb}=require("child_process"),Ya=require("path"),lo=require("fs"),Ka=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function vp(){return Ya.join(process.cwd(),".nex","hooks")}function Wb(){return Ya.join(process.cwd(),".nex","config.json")}function Sp(){let t=Wb();if(!lo.existsSync(t))return{};try{return JSON.parse(lo.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function Fr(t){if(!Ka.includes(t))return[];let e=[],s=vp(),n=Ya.join(s,t);lo.existsSync(n)&&e.push(n);let o=Sp();if(o[t]){let r=Array.isArray(o[t])?o[t]:[o[t]];e.push(...r)}return e}function Ep(t,e={},s=3e4){try{return{success:!0,output:Bb(t,{cwd:process.cwd(),encoding:"utf-8",timeout:s,env:{...process.env,...e},stdio:["pipe","pipe","pipe"]}).trim()}}catch(n){return{success:!1,error:n.stderr?n.stderr.trim():n.message}}}function Ub(t,e={}){let s=Fr(t);if(s.length===0)return[];let n={};for(let[r,i]of Object.entries(e))n[`NEX_${r.toUpperCase()}`]=String(i);let o=[];for(let r of s){let i=Ep(r,n);if(o.push({command:r,...i}),!i.success&&t.startsWith("pre-"))break}return o}function Hb(t){return Fr(t).length>0}function Gb(){let t=[];for(let e of Ka){let s=Fr(e);s.length>0&&t.push({event:e,commands:s})}return t}function Yb(){let t=vp();return lo.existsSync(t)||lo.mkdirSync(t,{recursive:!0}),t}Tp.exports={HOOK_EVENTS:Ka,loadHookConfig:Sp,getHooksForEvent:Fr,executeHook:Ep,runHooks:Ub,hasHooks:Hb,listHooks:Gb,initHooksDir:Yb}});var Wp=se((gv,Bp)=>{"use strict";var{callWithRetry:Ap,runSubAgent:Kb,clearAllLocks:zb}=ga(),{parseModelSpec:Op,getActiveProviderName:pv,getActiveModelId:hv}=He(),{detectCategory:Xb,getModelForCategory:Cp}=ls(),{MultiProgress:Vb,C:ce}=Ue(),{getModelBriefing:mv}=gr(),Np=parseInt(process.env.NEX_MAX_PARALLEL||"4",10),Br=parseInt(process.env.NEX_MAX_SUBTASKS||"8",10),Mp="devstral-2:123b",Lp="kimi-k2.5",Pp=`You are a task decomposition engine. Given a complex user request, split it into independent, atomic sub-tasks.
605
+
606
+ RULES:
607
+ - Output ONLY a JSON array, no markdown fences, no explanation.
608
+ - Each sub-task must be independently solvable by a specialized agent (coding, sysadmin, etc.).
609
+ - Maximum {maxSubTasks} sub-tasks. Merge closely related items.
610
+ - Each sub-task object must have these fields:
611
+ { "id": "t1", "task": "description", "scope": ["resource1", "resource2"], "estimatedCalls": 5, "priority": 1 }
612
+ - "scope" lists resources the agent should focus on (e.g., files, services, servers, commands).
613
+ - "estimatedCalls" is a rough count of tool invocations needed (max 15).
614
+ - "priority" is 1 (highest) to N (lowest) \u2014 controls execution order; set higher priority for prerequisite steps (e.g., stop service before config change).
615
+ - For system administration workflows, ensure sequential dependencies are captured via priority; overlapping resource scopes are allowed if ordered by priority.
616
+ - If the request is simple (single goal), return an array with exactly 1 item.
617
+
618
+ USER REQUEST:
619
+ {prompt}`,Ip=`You are a result synthesis engine. Given the results of multiple sub-agents that worked on parts of a larger task, produce a unified summary.
620
+
621
+ RULES:
622
+ - Output ONLY a JSON object with these fields:
623
+ { "summary": "what was done", "conflicts": ["file.js: agent 1 and 2 both modified line 42"], "commitMessage": "fix: ...", "resourcesChanged": ["resource1", "resource2"] }
624
+ - "conflicts" is an array of resource conflicts where multiple agents modified the same resource (e.g., services, servers, config files). Empty array if none.
625
+ - "commitMessage" follows conventional commits (fix:, feat:, refactor:, etc.).
626
+ - "resourcesChanged" is a deduplicated list of all resources (files, services, servers, etc.) modified across all agents.
627
+ - "summary" is a concise paragraph describing the overall result.
628
+
629
+ ORIGINAL REQUEST:
630
+ {prompt}
631
+
632
+ SUB-AGENT RESULTS:
633
+ {results}`;async function jp(t,e=1,s=2e3){for(let n=0;n<=e;n++)try{return await t()}catch(o){if(n===e)throw o;await new Promise(r=>setTimeout(r,s))}}function Dp(t){let e=0,s=[];return function(){return new Promise(o=>{let r=()=>{e<t?(e++,o(()=>{e--,s.length>0&&s.shift()()})):s.push(r)};r()})}}function Jb(t){if(!t||typeof t!="string")return{isComplex:!1,estimatedGoals:0,reason:"empty"};let e=0,s=[],n=t.match(/(?:(?:^|\n)\s*|\s)(?:\d+[.)]\s|[(]\d+[)][\s,]|[(][a-z][)][\s,])/g);n&&n.length>=2&&(e=Math.max(e,n.length),s.push(`${n.length} numbered items`));let o=t.match(/(?:^|\n)\s*[-*]\s+\S/g);o&&o.length>=3&&(e=Math.max(e,o.length),s.push(`${o.length} bullet points`));let r=t.split(/;\s*/).filter(l=>l.trim().length>10);r.length>=3&&(e=Math.max(e,r.length),s.push(`${r.length} semicolon-separated goals`));let i=t.match(/\b(also|additionally|and\s+(?:fix|add|update|create|implement|remove|refactor))\b/gi);i&&i.length>=2&&(e=Math.max(e,i.length+1),s.push(`${i.length} transition keywords`));let a=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10);return{isComplex:e>=a,estimatedGoals:e,reason:s.length>0?s.join(", "):"single goal"}}function za(t){if(!t||typeof t!="string")throw new Error("Empty response from orchestrator model");let e=t.trim();try{return JSON.parse(e)}catch{}let s=e.match(/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/);if(s)try{return JSON.parse(s[1].trim())}catch{}let n=e.search(/[[\{]/);if(n>=0){let o=e.slice(n);try{return JSON.parse(o)}catch{}}throw new Error(`Could not extract valid JSON from response:
634
+ ${e.slice(0,200)}`)}async function qp(t,e,s={}){let n=s.maxSubTasks||Br,r=[{role:"system",content:Pp.replace("{maxSubTasks}",String(n)).replace("{prompt}",t)},{role:"user",content:t}],i={};if(e){let g=Op(e);g.provider&&(i.provider=g.provider),g.model&&(i.model=g.model)}let c=(await Ap(r,[],i)).content||"",l=za(c);if(!Array.isArray(l))throw new Error(`Decompose returned non-array: ${typeof l}`);let u=10,f=l.slice(0,n).map((g,b)=>({id:g.id||`t${b+1}`,task:String(g.task||""),scope:Array.isArray(g.scope)?g.scope:[],estimatedCalls:typeof g.estimatedCalls=="number"?Math.min(g.estimatedCalls,u):8,priority:typeof g.priority=="number"?g.priority:b+1})).filter(g=>g.task.length>0),h=f.reduce((g,b)=>g+b.estimatedCalls,0),m=Br*u;if(h>m){let{debugLog:g}=Xo();g(`\x1B[33m \u26A0 Orchestrator: total estimated calls ${h} > ${m} \u2014 consider raising maxSubTasks\x1B[0m`)}return f}async function Fp(t,e,s){if(!t||t.length===0)return{summary:"No sub-tasks were executed.",conflicts:[],commitMessage:"",resourcesChanged:[]};let n=t.map((u,d)=>{let f=u.status==="done"?"SUCCESS":u.status==="truncated"?"PARTIAL":"FAILED";return`--- Agent ${d+1} [${f}] ---
635
+ Task: ${u.task}
636
+ Result: ${u.result}
637
+ Tools: ${(u.toolsUsed||[]).join(", ")||"none"}`}).join(`
638
+
639
+ `),r=[{role:"system",content:Ip.replace("{prompt}",e).replace("{results}",n)},{role:"user",content:"Synthesize the sub-agent results above."}],i={};if(s){let u=Op(s);u.provider&&(i.provider=u.provider),u.model&&(i.model=u.model)}let c=(await Ap(r,[],i)).content||"",l=za(c);return{summary:String(l.summary||""),conflicts:Array.isArray(l.conflicts)?l.conflicts:[],commitMessage:String(l.commitMessage||""),filesChanged:Array.isArray(l.filesChanged)?l.filesChanged:[]}}async function Zb(t,e={}){let s=e.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL||Lp,n=e.workerModel||Mp,o=e.maxParallel||Np,r=e.maxSubTasks||Br,i=e.onProgress||(()=>{}),a={input:0,output:0};console.log(`
640
+ ${ce.bold}Orchestrator${ce.reset} ${ce.dim}model: ${s} | workers: ${n} | max parallel: ${o}${ce.reset}
641
+ `),i("decomposing"),console.log(`${ce.dim}Phase 1: Decomposing prompt into sub-tasks...${ce.reset}`);let c;try{c=await qp(t,s,{maxSubTasks:r})}catch(H){return console.log(`${ce.red}Decompose failed: ${H.message}${ce.reset}`),{results:[],synthesis:{summary:`Decompose failed: ${H.message}`,conflicts:[],commitMessage:"",resourcesChanged:[]},totalTokens:a}}if(c.length===0)return console.log(`${ce.yellow}No sub-tasks generated. Prompt may be too simple for orchestration.${ce.reset}`),{results:[],synthesis:{summary:"No sub-tasks generated.",conflicts:[],commitMessage:"",resourcesChanged:[]},totalTokens:a};console.log(`${ce.green}Decomposed into ${c.length} sub-tasks:${ce.reset}`);for(let H of c){console.log(` ${ce.dim}${H.id}:${ce.reset} ${H.task}`);let _=H.scope.filter(Boolean);_.length>0&&console.log(` ${ce.dim}scope: ${_.join(", ")}${ce.reset}`)}console.log("");let l=new Map;for(let H=0;H<c.length;H++)for(let _ of c[H].scope)_&&!l.has(_)&&l.set(_,H);i("executing"),console.log(`${ce.dim}Phase 2: Running ${c.length} sub-agents (max ${o} parallel)...${ce.reset}
642
+ `);let u=Date.now(),d=Dp(o),f={findings:[],_lock:!1},h=c.map(H=>{let _=Xb(H.task);return(_?Cp(_.id):null)||n}),m=c.map((H,_)=>{let he=`Agent ${_+1} [${h[_]}]: `,de=Math.max(20,60-he.length),me=H.task.substring(0,de)+(H.task.length>de?"...":"");return he+me}),g=new Vb(m);g.start();let b=`
643
+ You are a focused coding agent executing ONE specific sub-task.
644
+ Your scope is limited to the files listed in your task definition.
645
+
646
+ WORKING DIRECTORY: ${process.cwd()}
647
+ Use paths relative to this directory (e.g. "cli/agent.js", not "nex-code/cli/agent.js").
648
+
649
+ CRITICAL RULE: Do not search for whether something exists before acting.
650
+ - If your task says "ensure X is in file Y" \u2192 read Y, add X if missing, done.
651
+ - If your task says "document X" \u2192 write the documentation now.
652
+ - Searching is only allowed to find WHERE to insert content, not WHETHER to insert.
653
+ - After max 3 tool calls: you must write/edit something or you have failed.
654
+
655
+ RULES:
656
+ - NEVER use external CLI tools for analysis (aspell, jq, sed, awk, grep for reading).
657
+ Use read_file + your own reasoning instead.
658
+ - Be PROACTIVE: if something is missing, ADD it. Do not just search and report.
659
+ - If your task says "fix typos" \u2014 read the file, find typos yourself, edit them.
660
+ - If your task says "add X to README" \u2014 add it, don't check if it exists first.
661
+ - Max 10 tool calls. If you need more, you are doing too much \u2014 narrow your scope.
662
+ - When done: stop calling tools and write a one-line summary of what you changed.
663
+ `,v=c.map(async(H,_)=>{let he=await d();try{let de=f.findings.filter(k=>k.agentId!==H.id).map(k=>`Agent ${k.agentId} found: ${k.summary}`).join(`
664
+ `),me=[...l.entries()].filter(([,k])=>k===_).map(([k])=>k),ge=[...l.entries()].filter(([,k])=>k!==_).map(([k])=>k),we=[de?`Prior agent findings:
665
+ ${de}
666
+ `:"",H.scope.length>0?`Focus on files: ${H.scope.join(", ")}`:"",me.length>0?`You OWN these files (may read+write): ${me.join(", ")}`:"",ge.length>0?`READ ONLY (owned by other agents, do NOT write): ${ge.join(", ")}`:""].filter(Boolean),Se=h[_],fe=process.env.NEX_FALLBACK_MODEL||Cp("agentic")||n,Pe=0,w=await jp(async()=>{let k=Pe>0;k&&(g.update(_,"retry"),process.stderr.write(` ${ce.dim}[Agent ${_+1}] retrying after error...${ce.reset}
667
+ `)),Pe++;let N=k&&Se!==fe?fe:Se;return Kb({task:H.task,context:we.length>0?we.join(`
668
+ `):void 0,max_iterations:Math.min(H.estimatedCalls||10,15),model:N,_skipLog:!0,_systemPrompt:b,_readOnlyFiles:ge},{onUpdate:T=>{if(T&&T.type==="tool_call"&&process.stderr.isTTY){let S=`Agent ${_+1} [${N}]`,J=T.tool||"...";g.labels[_]=`${S}: ${J}`}}})},1,2e3),P=typeof w.result=="string"?w.result.slice(0,200):String(w.result||"").slice(0,200);return f.findings.push({agentId:H.id,summary:P,files:Array.isArray(H.scope)?H.scope:[]}),g.labels[_]=m[_],g.update(_,w.status==="failed"?"error":"done"),a.input+=w.tokensUsed?.input||0,a.output+=w.tokensUsed?.output||0,w.tokensUsed?._estimated&&(a._estimated=!0),{...w,_scope:H.scope,_idx:_}}catch(de){return g.labels[_]=m[_],g.update(_,"error"),{task:H.task,status:"failed",result:`Error: ${de.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}}finally{he()}}),O;try{O=await Promise.all(v)}finally{g.stop({silent:!0}),zb()}console.log("");let U=Math.round((Date.now()-u)/1e3),L=U>=60?`${Math.floor(U/60)}m ${U%60}s`:`${U}s`;for(let H=0;H<O.length;H++){let _=O[H],de=_.status==="done"||_.status==="truncated"&&_.result&&!_.result.startsWith("Error")?`${ce.green}\u2713${ce.reset}`:`${ce.red}\u2717${ce.reset}`,me=_._scope&&_._scope.length>0?_._scope.map(Se=>Se.replace(/^.*\//,"").replace(/\/$/,"")).filter(Boolean):[],ge=me.length>0?me.join(", "):_.task.substring(0,35)+(_.task.length>35?"...":""),we=H===O.length-1;console.log(` ${de} Agent ${H+1} ${ce.dim}${ge}${ce.reset}${we?` ${ce.dim}${L}${ce.reset}`:""}`)}console.log(""),i("synthesizing"),console.log(`${ce.dim}Phase 3: Synthesizing results...${ce.reset}`);let R;try{R=await Fp(O,t,s)}catch(H){console.log(`${ce.yellow}Synthesize failed: ${H.message} \u2014 using raw results.${ce.reset}`),R={summary:O.map(_=>_.result).join(`
669
+ `),conflicts:[],commitMessage:"",resourcesChanged:[]}}let C=f.findings.flatMap(H=>H.files),K=new Map;for(let H of C)K.set(H,(K.get(H)||0)+1);let Q=[...K.values()].some(H=>H>1),re=f.findings.length>1&&Q?` ${ce.dim}(agents shared context)${ce.reset}`:"";if(console.log(`
670
+ ${ce.bold}Summary:${ce.reset} ${R.summary}${re}`),R.conflicts.length>0){console.log(`${ce.yellow}Conflicts:${ce.reset}`);for(let H of R.conflicts)console.log(` - ${H}`)}R.commitMessage&&console.log(`${ce.dim}Suggested commit: ${R.commitMessage}${ce.reset}`);let V=a.input===0&&a.output===0?"n/a (provider does not report token counts)":a._estimated?`~${a.input} input / ~${a.output} output (est.)`:`${a.input} input + ${a.output} output`;return console.log(`${ce.dim}Tokens: ${V}${ce.reset}
671
+ `),{results:O,synthesis:R,totalTokens:a}}Bp.exports={runOrchestrated:Zb,decompose:qp,synthesize:Fp,detectComplexPrompt:Jb,extractJSON:za,createSemaphore:Dp,DECOMPOSE_PROMPT:Pp,SYNTHESIZE_PROMPT:Ip,DEFAULT_ORCHESTRATOR_MODEL:Lp,DEFAULT_WORKER_MODEL:Mp,DEFAULT_MAX_PARALLEL:Np,DEFAULT_MAX_SUBTASKS:Br,withRetry:jp}});var fh=se((xv,dh)=>{var{C:p,Spinner:hs,TaskProgress:Qb,formatToolCall:e_,formatToolSummary:sh,formatSectionHeader:Wr,formatMilestone:t_,setActiveTaskProgress:yv}=Ue(),{debugLog:D,warnLog:$v}=Xo(),{MilestoneTracker:n_}=Fl(),{callStream:Up}=He(),{parseToolArgs:s_}=Ss(),{executeTool:o_}=Jn(),{gatherProjectContext:r_}=Lf(),{fitToContext:i_,forceCompress:It,getUsage:Et,estimateTokens:a_}=Pt(),{autoSave:c_,flushAutoSave:l_}=Mr(),{scoreMessages:u_,formatScore:d_,appendScoreHistory:f_}=Lr(),{detectCategory:p_,getModelForPhase:oc,getPhaseBudget:Cn,isPhaseRoutingEnabled:h_}=ls();function Be(t){c_(t),l_()}function m_(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 Hp(t){try{if(!t.some(n=>n.role!=="assistant"?!1:!!(Array.isArray(n.content)&&n.content.some(o=>o&&o.type==="tool_use")||Array.isArray(n.tool_calls)&&n.tool_calls.length>0)))return;let s=u_(t);if(!s)return;console.log(d_(s,p));try{let{_getSessionsDir:n}=Mr(),o=require("fs"),r=require("path").join(n(),"_autosave.json");if(o.existsSync(r)){let i=JSON.parse(o.readFileSync(r,"utf-8"));i.score=s.score,i.scoreGrade=s.grade,i.scoreIssues=s.issues,o.writeFileSync(r,JSON.stringify(i,null,2))}}catch{}try{let{getActiveModel:n}=Ss(),o=No();f_(s.score,{version:o.version,model:n?n():null,sessionName:"_autosave",issues:s.issues})}catch{}}catch{}}var{getMemoryContext:g_}=zs(),{getDeploymentContextBlock:y_,probeUrlServer:$_}=La(),{getFewShotForInput:w_}=tp(),{checkPermission:b_,setPermission:__,savePermissions:x_}=ap(),{confirm:oh,setAllowAlwaysHandler:k_,getAutoConfirm:v_}=Es(),{isPlanMode:wo,getPlanModePrompt:S_,PLAN_MODE_ALLOWED_TOOLS:rh,setPlanContent:E_,extractStepsFromText:T_,createPlan:R_,getActivePlan:wv,startExecution:bv,advancePlanStep:C_,getPlanStepInfo:A_}=qr(),{StreamRenderer:O_}=kp(),{runHooks:Gp}=Rp(),{routeMCPCall:N_,getMCPToolDefinitions:M_}=zi(),{getSkillInstructions:L_,getSkillToolDefinitions:P_,routeSkillCall:I_,matchSkillTriggers:j_}=Yi(),{trackUsage:Yp,estimateTokens:Kp}=zo();function zp(t){return!t||typeof t!="string"?0:typeof Kp=="function"?Kp(t):Math.ceil(t.length/4)}var{validateToolArgs:D_}=Ji(),{filterToolsForModel:Xp,getModelTier:q_,PROVIDER_DEFAULT_TIER:_v}=Is(),{getConfiguredProviders:F_,getActiveProviderName:ms,getActiveModelId:Dt,setActiveModel:Vp,MODEL_EQUIVALENTS:ti}=He(),{getModelProfile:B_,getModelBriefing:W_}=gr(),mc=require("fs"),gc=require("path"),U_=(()=>{let t=parseInt(process.env.NEX_MILESTONE_STEPS??"5",10);return Number.isFinite(t)&&t>=0?t:5})();function H_(t){let e=t_(t.phaseName,t.stepCount,t.toolCounts,t.elapsed,t.filesRead,t.filesModified);process.stdout.write(`${e}
672
+ `)}var Jp=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi;function G_(t){let e=[],s;for(Jp.lastIndex=0;(s=Jp.exec(t))!==null;){let n=s[1].trim(),o=n.startsWith("~")?n.replace("~",process.env.HOME||""):gc.resolve(n);mc.existsSync(o)&&e.push({raw:n,abs:o})}return e}function Y_(t){let e=mc.readFileSync(t),s=gc.extname(t).toLowerCase().replace(".",""),n=s==="jpg"||s==="jpeg"?"image/jpeg":s==="png"?"image/png":s==="gif"?"image/gif":s==="webp"?"image/webp":"image/png";return{data:e.toString("base64"),media_type:n}}function ih(t){let e=G_(t);if(e.length===0)return t;let s=[{type:"text",text:t}];for(let n of e)try{let{data:o,media_type:r}=Y_(n.abs);s.push({type:"image",media_type:r,data:o})}catch{}return s.length>1?s:t}function K_(t){if(!t||t.length<200)return{text:t,truncated:!1,repeatCount:0};let s=t.split(/(?<=\. )/).filter(c=>c.trim().length>0);if(s.length<6)return{text:t,truncated:!1,repeatCount:0};let n=new Map;for(let c=0;c<=s.length-3;c++){let l=s.slice(c,c+3).join("").trim();l.length>30&&n.set(l,(n.get(l)||0)+1)}let o=0,r="";for(let[c,l]of n)l>o&&(o=l,r=c);if(o<3)return{text:t,truncated:!1,repeatCount:o};let i=`
673
+
674
+ [SYSTEM: Output repetition detected \u2014 response truncated (${o}\xD7 repeated paragraph)]`,a;if(t.length>8e3)a=t.slice(0,3e3)+i;else{let c=0,l=-1,u=0;for(;c<2;){let d=t.indexOf(r,u);if(d===-1)break;c++,l=d+r.length,u=d+1}a=l>0?t.slice(0,l)+i:t.slice(0,3e3)+i}return{text:a,truncated:!0,repeatCount:o}}function rc(t,e=5){if(!t||t.length<40)return{text:t,truncated:!1,repeatCount:0};let s=t.split(`
675
+ `),n=new Map;for(let d of s){let f=d.trim();f.length>=20&&n.set(f,(n.get(f)||0)+1)}let o=0,r="";for(let[d,f]of n)f>o&&(o=f,r=d);if(o<=e)return{text:t,truncated:!1,repeatCount:o};let i=`
676
+
677
+ \u26A0 [Response truncated: repeated paragraph detected (${o}\xD7)]`,a=0,c=-1,l=0;for(;a<e;){let d=t.indexOf(r,l);if(d===-1)break;a++,c=d+r.length,l=d+1}return{text:c>0?t.slice(0,c)+i:t.slice(0,2e3)+i,truncated:!0,repeatCount:o}}var Xa=null,Va=null,Ja=null;function Ze(){if(Xa===null){let{TOOL_DEFINITIONS:t}=Jn();Xa=t}return Va===null&&(Va=P_()),Ja===null&&(Ja=M_()),[...Xa,...Va,...Ja]}var ic=50;function z_(t){Number.isFinite(t)&&t>0&&(ic=t)}var Gr=()=>null;function X_(t){Gr=t}var po=null,ac=null,gs=null,Yr=new Map,V_=1e4,J_=6e3,Z_=/\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 Q_(t){return!t||typeof t!="string"?t:t.replace(Z_,(e,s)=>`${s}=***REDACTED***`)}var ex=7e3,tx=4e3;function nx(t,e=null){let s=Q_(t),n=a_(s),o=e==="read_file"?ex:V_,r=e==="read_file"?tx:J_;if(n>o)try{let{compressToolResult:i}=Pt();return i(s,r)}catch{return s}return s}function ah(t){try{let{getActiveModel:e}=He(),s=e(),n=s?`${s.provider}:${s.id}`:"default";if(Yr.has(n))return Yr.get(n);let o=Xp(t);return Yr.set(n,o),o}catch{return Xp(t)}}function sx(){Yr.clear()}var ho={hash:null,ts:0},ox=3e4;async function ch(){if(ho.hash&&Date.now()-ho.ts<ox)return ho.hash;try{let t=require("fs").promises,e=require("path"),s=[e.join(process.cwd(),"package.json"),e.join(process.cwd(),".git","HEAD"),e.join(process.cwd(),"README.md"),e.join(process.cwd(),"NEX.md")],o=(await Promise.allSettled(s.map(i=>t.stat(i).then(a=>`${i}:${a.mtimeMs}`)))).filter(i=>i.status==="fulfilled").map(i=>i.value);try{let{getMemoryContextHash:i}=zs(),a=i();a&&o.push(`memory:${a}`)}catch{}try{let i=e.join(process.cwd(),".nex","brain");if(mc.existsSync(i)){let a=await t.stat(i);o.push(`brain:${a.mtimeMs}`)}}catch{}let r=o.join("|");return ho={hash:r,ts:Date.now()},r}catch{return`fallback:${Date.now()}`}}function cc(){po=null,ac=null,ho={hash:null,ts:0},gs=null}var rx=new Set(["spawn_agents"]),Za=5,Qa=3,Ur=2,Zp=6e4,ec=12e4,ix=process.env.NEX_STALE_AUTO_SWITCH!=="0";function ax(t){try{let e=require("fs"),s=require("path"),n=s.join(process.cwd(),".nex","plans");e.existsSync(n)||e.mkdirSync(n,{recursive:!0});let o=s.join(n,"current-plan.md");e.writeFileSync(o,t,"utf-8")}catch{}}k_(t=>{__(t,"allow"),x_(),console.log(`${p.green} \u2713 ${t}: always allow${p.reset}`)});async function cx(t){let e=t.function.name,s=s_(t.function.arguments),n=t.id||`cli-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!s){let u=Ze().find(f=>f.function.name===e),d=u?JSON.stringify(u.function.parameters,null,2):"unknown";return D(`${p.yellow} \u26A0 ${e}: malformed arguments, sending schema hint${p.reset}`),{callId:n,fnName:e,args:null,canExecute:!1,errorResult:{role:"tool",content:`ERROR: Malformed tool arguments. Could not parse your arguments as JSON.
678
+ Raw input: ${typeof t.function.arguments=="string"?t.function.arguments.substring(0,200):"N/A"}
679
+
680
+ Expected JSON schema for "${e}":
681
+ ${d}
682
+
683
+ Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:n}}}let o=D_(e,s);if(!o.valid){D(`${p.yellow} \u26A0 ${e}: ${o.error.split(`
684
+ `)[0]}${p.reset}`);let l=(th.get(e)||0)+1;th.set(e,l);let u=l>=2?`${o.error}
685
+
686
+ [SYSTEM: This is argument error #${l} for "${e}". Study the "Expected parameters" schema above and correct your call \u2014 do not repeat the same mistake.]`:o.error;return{callId:n,fnName:e,args:s,canExecute:!1,errorResult:{role:"tool",content:u,tool_call_id:n}}}let r=o.corrected||s;if(o.corrected){let l=Object.keys(s),u=Object.keys(o.corrected),d=l.filter(f=>!u.includes(f));d.length&&console.log(`${p.dim} \u2713 ${e}: corrected args (${d.join(", ")})${p.reset}`)}if(wo()&&!rh.has(e))return console.log(`${p.yellow} \u2717 ${e}: blocked in plan mode${p.reset}`),{callId:n,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:n}};let i=new Set(["read_file","list_directory","search_files","glob","grep","git_status","git_diff","git_log","git_show","ssh_exec"]),a=new Set(["read_file","list_directory","glob","grep","bash","git_status","git_diff","git_log","ssh_exec"]);if($e&&De==="plan"&&!i.has(e))return nn++,D(`${p.yellow} \u2717 ${e}: blocked in plan phase (read-only, block #${nn})${p.reset}`),{callId:n,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`PLAN PHASE: '${e}' is blocked. Analyze the codebase using read-only tools, then present your findings as text. Edits happen in the next phase.`,tool_call_id:n}};if($e&&De==="verify"&&!a.has(e))return D(`${p.yellow} \u2717 ${e}: blocked in verify phase (read + bash only)${p.reset}`),{callId:n,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`VERIFY PHASE: '${e}' is blocked. Use read_file and bash (for tests/linters) to verify changes. Report PASS or FAIL.`,tool_call_id:n}};let c=b_(e);if(c==="deny")return console.log(`${p.red} \u2717 ${e}: denied by permissions${p.reset}`),{callId:n,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`DENIED: Tool '${e}' is blocked by permissions`,tool_call_id:n}};if(c==="ask"){let l=` Allow ${e}?`;return e==="bash"&&r.command&&(l=` bash: \`${r.command.substring(0,80)}${r.command.length>80?"\u2026":""}\`?`),await oh(l,{toolName:e})?{callId:n,fnName:e,args:r,canExecute:!0,confirmedByUser:!0,errorResult:null}:{callId:n,fnName:e,args:r,canExecute:!1,confirmedByUser:!1,errorResult:{role:"tool",content:`CANCELLED: User declined ${e}`,tool_call_id:n}}}return{callId:n,fnName:e,args:r,canExecute:!0,confirmedByUser:!0,errorResult:null}}async function lx(t,e,s={}){let n=await I_(t,e);if(n!==null)return n;let o=await N_(t,e);return o!==null?o:o_(t,e,s)}function ux(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 tc(t,e=!1){e||console.log(e_(t.fnName,t.args));let s=Gp("pre-tool",{tool_name:t.fnName});if(!e&&s.length>0)for(let h of s)h.success?console.log(`${p.dim} [hook pre-tool] ${h.command} \u2192 ${h.output||"ok"}${p.reset}`):console.log(`${p.yellow} [hook pre-tool] ${h.command} \u2192 ERROR: ${h.error}${p.reset}`);qt?.onToolStart&&qt.onToolStart(t.fnName,t.args);let n=await lx(t.fnName,t.args,{silent:!0,autoConfirm:t.confirmedByUser===!0}),o=String(n??""),r=o.length>5e4?o.substring(0,5e4)+`
687
+ ...(truncated ${o.length-5e4} chars)`:o,i=r.split(`
688
+ `)[0],a=i.startsWith("ERROR")||i.includes("CANCELLED")||i.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(r)&&/✗ Agent/.test(r),c=sh(t.fnName,t.args,r,a);e||console.log(c),qt?.onToolEnd&&qt.onToolEnd(t.fnName,c,!a);let l=Gp("post-tool",{tool_name:t.fnName});if(!e&&l.length>0)for(let h of l)h.success?console.log(`${p.dim} [hook post-tool] ${h.command} \u2192 ${h.output||"ok"}${p.reset}`):console.log(`${p.yellow} [hook post-tool] ${h.command} \u2192 ERROR: ${h.error}${p.reset}`);let d=nx(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)?d+=`
689
+ 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)?d+=`
690
+ 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)&&(d+=`
691
+ 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:d,tool_call_id:t.callId},summary:c}}var dx=[{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 nc(t){for(let{re:e,label:s}of dx){let n=t.match(e);if(n){let o=(n[1]||"").trim();return o?`${s}: ${o}`:s}}return null}async function fx(t,e=!1,s={}){let n=new Array(t.length),o=[],r=[],i=null;if(e&&!s.skipSpinner){let c=t.filter(l=>l.canExecute);if(c.length>0){let l;if(c.length===1){let u=c[0],d=ux(u.fnName,u.args);l=`\u23FA ${u.fnName}${d?`(${d})`:""}`}else{let u=c.map(d=>d.fnName).join(", ");l=`\u23FA ${c.length} tools: ${u.length>60?u.substring(0,57)+"\u2026":u}`}i=new hs(l),i.start()}}async function a(){if(r.length!==0){if(r.length===1){let c=r[0],{msg:l,summary:u}=await tc(t[c],e);n[c]=l,o.push(u)}else{let c=r.map(u=>tc(t[u],e)),l=await Promise.all(c);for(let u=0;u<r.length;u++)n[r[u]]=l[u].msg,o.push(l[u].summary)}r=[]}}for(let c=0;c<t.length;c++){let l=t[c];if(!l.canExecute){await a(),n[c]=l.errorResult,o.push(sh(l.fnName,l.args||{},l.errorResult.content,!0));continue}if(rx.has(l.fnName)){await a(),l.fnName==="spawn_agents"&&i&&(i.stop(),i=null);let{msg:u,summary:d}=await tc(l,e);n[c]=u,o.push(d)}else r.push(c)}if(await a(),i&&i.stop(),e&&o.length>0&&!s.skipSummaries)for(let c of o)console.log(c);return{results:n,summaries:o}}var q=[],Qp=300,lh=900*1e3;function An(t,e){let s=t.get(e);return s?Date.now()-s.ts>lh?(t.delete(e),0):s.count:0}function On(t,e){let s=t.get(e),n=s&&Date.now()-s.ts<=lh?s.count+1:1;return t.set(e,{count:n,ts:Date.now()}),n}function eh(t,e,s){t.set(e,{count:s,ts:Date.now()})}var yc=new Map,$c=new Map,bo=new Map,wc=new Map,_o=new Map,In=new Map,tn=new Map,bc=new Map,Nn=new Map,jn=new Map,th=new Map,ni=new Map,si=new Map,wt=0,mo=0,Kr=0,lc="",zr=0,ht=!1,Hr=0,Xr=0,Mn=-1,uc=!1,Vr=0,Jr=!1,jt=0,Tt=!1,Kt=0,Rt=0,Ye=!1,it="",go=0,en=0,Zr="",Ln=0,Pn=0,Qr="",bt=!1,dc=!1,xo=new Map,ko=new Set,yo=null,sc=!1,uo=0,nh=!1,De="plan",oi=0,$e=!1,nn=0,zt=null,fc=null,pc=null,$o=0,ys=null;function ps(t,e){t===lc?(zr++,Xo().DEBUG&&process.stdout.write(`\x1B[1A\x1B[2K${e} \u26A0 ${t} (\xD7${zr})${p.reset}
692
+ `)):(lc=t,zr=1,D(`${e} \u26A0 ${t}${p.reset}`))}var ei=[];function px(t){ei.push(t.trim())}function hx(){return ei.length===0?null:ei.splice(0,ei.length).join(`
693
+ `)}function fo(t,e,s,n){if(!$e)return null;let o=De;De=t,oi=0,zt=oc(t,ys),jt=0,Tt=!1,Kt=0,Rt=0,In.clear(),tn.clear(),jn.clear(),ni.clear(),si.clear(),$c.clear(),bo.clear(),wc.clear(),_o.clear(),yc.clear(),bc.clear();let r;if(t==="implement")fc=e?.slice(0,800)||"",r=`[PHASE: IMPLEMENTATION] Analysis complete. Based on the analysis:
694
+ ${fc}
695
+
696
+ Now implement the fix/changes. Do not investigate further \u2014 edit files directly.`;else if(t==="verify"){pc=e?.slice(0,500)||"";let i=s?[...s].join(", "):"none";r=`[PHASE: VERIFICATION] Implementation complete. Verify the changes:
697
+ 1. Read each modified file and confirm changes are correct
698
+ 2. If test command exists (npm test / pytest): run it
699
+ 3. If linter exists: run it
700
+ 4. Does the implementation address: "${(n||"").slice(0,200)}"?
701
+ Report PASS (all good) or FAIL (list specific issues).
702
+
703
+ Files modified: ${i}
704
+ Summary: ${pc}`}return D(`${p.cyan} \u21B3 Phase transition: ${o} \u2192 ${t} (model: ${zt||"default"})${p.reset}`),r?{role:"user",content:r}:null}function mx(){let t=process.env.NEX_LANGUAGE,e=process.env.NEX_CODE_LANGUAGE,s=process.env.NEX_COMMIT_LANGUAGE,n=!t||t==="auto"?null:t,o=[`# Language Rules (CRITICAL \u2014 enforce strictly)
705
+ `];n?o.push(`RESPONSE LANGUAGE: You MUST always respond in ${n}. This overrides any language defaults from your training. Never output Chinese, Japanese, or any other language in your responses \u2014 even when summarizing or thinking. ${n} only.`):o.push("RESPONSE LANGUAGE: Always respond in the same language as the user's message. If the user writes in German, respond in German; if in English, respond in English; etc."),o.push("CODE EXAMPLES: Always show actual, working code examples \u2014 never pseudocode or placeholder snippets."),o.push("COMPLETENESS RULES:"),o.push(" \u2022 ALWAYS show actual code when explaining implementations \u2014 never describe without showing"),o.push(" \u2022 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."),o.push(" \u2022 Include complete examples with full context (imports, function signatures, error handling)"),o.push(' \u2022 Show alternative approaches when relevant (e.g., "Alternative: use util.promisify instead")'),o.push(" \u2022 Include edge cases in explanations (empty input, null values, boundary conditions)"),o.push(" \u2022 Provide platform-specific guidance when commands differ by OS (Linux/macOS/Windows)"),o.push(' \u2022 For Makefiles, 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.'),o.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."),o.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."),o.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.'),o.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).'),o.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)."),o.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."),o.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."),o.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.'),o.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";o.push(`CODE LANGUAGE: Write all code comments, docstrings, variable descriptions, and inline documentation in ${r}.`);let i=s||"English";return o.push(`COMMIT MESSAGES: Write all git commit messages in ${i}.`),n&&o.push(`
706
+ This is a hard requirement. Always respond in ${n}. 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 ${n}.`),o.join(`
707
+ `)+`
708
+
709
+ `}function gx(){if(gs!==null)return gs;try{let e=F_().flatMap(o=>o.models.map(r=>({spec:`${o.name}:${r.id}`,tier:q_(r.id,o.name),name:r.name})));if(e.length<2)return gs="","";let s={full:"complex tasks (refactor, implement, generate)",standard:"regular tasks (edit, fix, analyze)",essential:"simple tasks (read, search, list)"},n=`
710
+ # Sub-Agent Model Routing
711
+
712
+ `;n+='Sub-agents auto-select models by task complexity. Override with `model: "provider:model"` in agent definition.\n\n',n+=`| Model | Tier | Auto-assigned for |
713
+ |---|---|---|
714
+ `;for(let o of e)n+=`| ${o.spec} | ${o.tier} | ${s[o.tier]||o.tier} |
715
+ `;return gs=n,n}catch(t){return process.env.NEX_DEBUG&&console.error("[agent] model routing guide failed:",t.message),gs="",""}}async function hc(){let t=await ch()+":"+Dt();if(po!==null&&t===ac)return po;let e=await r_(process.cwd()),s=g_(),n=L_(),o=wo()?S_():"",r=mx(),i=y_(),a=W_(Dt());return po=`${a?`## Model Briefing
716
+ ${a}
717
+
718
+ ---
719
+
720
+ `:""}You are Nex Code, an expert coding assistant. You help with programming tasks by reading, writing, and editing files, running commands, and answering questions.
721
+
722
+ WORKING DIRECTORY: ${process.cwd()}
723
+ All relative paths resolve from this directory.
724
+ PROJECT CONTEXT:
725
+ ${e}
726
+ ${s?`
727
+ ${s}
728
+ `:""}${n?`
729
+ ${n}
730
+ `:""}${o?`
731
+ ${o}
732
+ `:""}
733
+ ${r?`${r}
734
+ `:""}${i?`${i}
735
+
736
+ `:""}${v_()?`# YOLO Mode \u2014 Auto-Execute
737
+
738
+ You are in YOLO mode (autoConfirm=true). All tool calls are pre-approved.
739
+ - NEVER ask for confirmation \u2014 just execute tasks directly
740
+ - NEVER end responses with questions like "Soll ich...?", "M\xF6chtest du...?", "Shall I...?"
741
+ - When you have enough information, implement the fix immediately \u2014 do not propose or ask
742
+ - If something is ambiguous, make a reasonable assumption and state it, then proceed
743
+ - OVERRIDE "simple questions": If the user pastes any server error or Jarvis message, SSH investigate FIRST \u2014 NEVER answer from training knowledge alone
744
+ - **Inline code tasks**: If the prompt contains a code snippet and asks you to modify/add to/improve it, answer DIRECTLY with the improved code \u2014 do NOT search for files. The snippet is self-contained
745
+ - After identifying root cause via SSH: IMMEDIATELY fix it (edit file + restart service). Do NOT write "Empfohlene L\xF6sungen" or ask "M\xF6chten Sie...?" \u2014 just execute the fix now.
746
+
747
+ `:""}
748
+
749
+ # Plan Mode
750
+
751
+ Plan mode is ONLY active when explicitly activated via the /plan command or shown in your system prompt as "PLAN MODE ACTIVE". If you do NOT see "PLAN MODE ACTIVE" in your instructions, you are NOT in plan mode \u2014 you have full tool access and MUST execute tasks directly. Never claim to be in plan mode unless you see that explicit marker.
752
+
753
+ # Core Behavior
754
+
755
+ - You can use tools OR respond with text. For simple questions, answer directly.
756
+ - For coding tasks, use tools to read files, make changes, run tests, etc.
757
+ - Be concise but complete. Keep responses focused while ensuring the user gets the information they asked for.
758
+ - When referencing code, include file:line (e.g. src/app.js:42) so the user can navigate.
759
+ - Do not make up file paths or URLs. Use tools to discover them.
760
+
761
+ # Response Quality (Critical)
762
+
763
+ \u26A0 CRITICAL: The user CANNOT see tool output. They only see your text + 1-line summaries like "\u2713 bash ssh ... \u2192 ok".
764
+ If you run tools but write NO text \u2192 the user sees NOTHING useful. This is the #1 quality failure.
765
+
766
+ MANDATORY RULE: After ANY tool call that gathers information (bash, read_file, grep, ssh commands, etc.), you MUST write a text response summarizing the findings. NEVER end your response with only tool calls and no text.
767
+
768
+ CODE DISPLAY RULE: Always show actual code examples, not just descriptions. When explaining code:
769
+ \u2022 Show the complete code snippet, not just describe it
770
+ \u2022 Include file paths and line numbers (e.g., "src/app.js:42")
771
+ \u2022 For regex patterns, show both the pattern and example matches. Be precise \u2014 test the pattern mentally. When rewriting for readability, use named constants or a commented breakdown (e.g. const OCTET = ...), NOT named capture groups \u2014 named group syntax varies by engine and is a frequent source of errors. NEVER claim functional equivalence without verifying edge cases (e.g. leading zeros, boundary values).
772
+ \u2022 For Makefiles: (1) Output the COMPLETE Makefile in a fenced \`\`\`makefile code block IN YOUR TEXT first \u2014 before any tool calls. (2) Then optionally write it to disk. FORBIDDEN: using write_file for a Makefile and then only describing it in text \u2014 the code block in text is mandatory. The user CANNOT see write_file output. (3) Use EXACTLY the command from the description: "runs jest" \u2192 recipe is "jest" (NOT "npm test", NOT "npx jest"); "runs tsc" \u2192 recipe is "tsc". (4) Never suggest alternatives to the specified tool \u2014 if the task says tsc, only tsc appears in the Makefile.
773
+ \u2022 For dataclasses, show the COMPLETE implementation \u2014 all fields with types, __post_init__ validation, and any defaults. Never describe without showing the code.
774
+ \u2022 For cron expressions, quote the exact time constraint from the task verbatim, then write the expression. Verify boundary values (e.g., "8-18h" \u2192 hours 8 through 18 inclusive).
775
+ \u2022 For regex character classes with numeric ranges: after writing the expression, re-read the task requirement and verify each range boundary matches exactly. Common pitfalls: "8 to 18" \u2192 [8-9]|1[0-8] not [8-17]; hour ranges are 0-23, month ranges are 1-12, day ranges are 1-31. Count the values your range covers and compare to the requirement before finalizing.
776
+
777
+ - Use markdown formatting: **bold** for key points, headers for sections, bullet lists for multiple items, \`code\` for identifiers. The terminal renders markdown with syntax highlighting.
778
+ - Structure longer responses with headers (## Section) so the user can scan quickly.
779
+
780
+ Response patterns by request type:
781
+ - **Questions / analysis / "status" / "explain" / "what is"**: Gather data with tools, then respond with a clear, structured summary. NEVER just run tools and stop.
782
+ - **Coding tasks (implement, fix, refactor)**: Brief confirmation of what you'll do, then use tools. After changes, summarize what you did and any important details. When diagnosing a bug (memory leak, race condition, logic error): always proceed from diagnosis to concrete fix \u2014 write the corrected code and apply it. Do not stop after identifying the root cause unless the user explicitly asked for analysis only.
783
+ - **Simple questions ("what does X do?")**: Answer directly without tools when you have enough context.
784
+ - **Ambiguous requests**: When a request is vague AND lacks sufficient detail to act (e.g. just "optimize this" or "improve performance" with no further context), ask clarifying questions using ask_user. However, if the user's message already contains specific details \u2014 file names, concrete steps, exercises, numbers, examples \u2014 proceed directly without asking. Only block when you genuinely cannot determine what to do without more information. When the user's request is ambiguous or could be interpreted in multiple ways, call the ask_user tool BEFORE starting work. Provide 2-3 specific, actionable options that cover the most likely intents. Do NOT ask open-ended questions in chat \u2014 always use ask_user with concrete options.
785
+ - **Server/SSH commands**: When the user asks about a server issue, crash, or status \u2014 your FIRST tool call must be ssh_exec. Combine commands with ; to get everything in one call. Example: ssh_exec("systemctl status svc --no-pager; echo '==='; journalctl -u svc -n 50 --no-pager; echo '==='; tail -30 /path/to/app.log"). Analyze the output, state the root cause, then fix it. Only read local files if you need to edit them for a fix.
786
+ - **Regex explanations**: Show the original pattern, test it with concrete examples, then provide BOTH: (1) a named-constant rewrite (e.g. const OCTET = '...'; const IP_RE = new RegExp(...)) AND (2) a step-by-step validation function that replaces the regex entirely using split/conditions \u2014 this is often the most readable alternative. Named groups are engine-specific \u2014 prefer named constants or the validation function. Verify the rewrite matches all edge cases of the original before claiming equivalence.
787
+ - **Encoding/buffer handling**: When discussing file operations, mention utf8 encoding or buffer considerations. Use correct flags like --zero instead of -0 for null-delimited output.
788
+ - **Hook implementations (Git, bash scripts)**: Answer ENTIRELY in text \u2014 do NOT use any tools. Write the complete, correct script in your first and only response. Think through ALL edge cases (e.g. console.log in comments or strings vs real calls) before writing \u2014 handle them in the initial script, never iterate. Show the full file content and how to install it (chmod +x, correct .git/hooks/ path). For pre-commit hooks that check staged content: always use 'git diff --cached' to get only staged changes \u2014 never grep full file content, which would catch unstaged lines. Use '--diff-filter=ACM' to target added/copied/modified files \u2014 NEVER use '--diff-filter=D' (that shows ONLY deleted files, opposite of intent). NEVER use 'set -e' in pre-commit hooks \u2014 grep exits 1 on no match, which kills the entire script under set -e. Use explicit 'if git diff --cached ... | grep -q ...; then' flow control instead, and check exit codes explicitly. REGEX FALSE POSITIVES IN DIFF OUTPUT: Diff lines start with '+' (added) or '-' (removed) \u2014 the actual code content comes AFTER the leading '+'/'-'. This means 'grep -v "^s*//"' does NOT exclude comment lines in diff output because the line starts with '+', not with whitespace. CORRECT pipeline for detecting console.log in staged .js changes while excluding comment lines: 'git diff --cached -- "*.js" | grep "^+" | grep -v "^+++" | grep -v "^+[[:space:]]*//" | grep -q "console.log"'. The key pattern is '^+[[:space:]]*//' \u2014 match lines where after the '+' prefix comes optional whitespace then '//'. Always use this exact pipeline, never 'grep -v "^s*//"' on diff output. CONSOLE METHODS: When a task asks to block console.log, explicitly address whether console.warn, console.error, console.debug, and console.info should also be blocked \u2014 if the intent is "no console output in production", block all console methods with a single pattern like 'console.(log|warn|error|debug|info)'.
789
+ - **Memory leak explanations**: Show the problematic code, then present the primary fix (move emitter.on() outside the loop, registered once) with the original setInterval kept intact for its intended purpose. Then briefly mention 2 alternatives: (1) emitter.once() if only one event needs handling, (2) removeAllListeners() (or emitter.off(event, handler)) BEFORE re-registering inside the loop. CRITICAL for alternative 2: you MUST call removeAllListeners() or off() BEFORE the new emitter.on() \u2014 if you call emitter.on() inside an interval without first removing the previous listener, a new listener accumulates on every tick, which is the same leak as the original. Always show the removal step explicitly. Do NOT replace the setInterval body with an empty callback \u2014 keep the interval doing its original work.
790
+ - **Makefile tasks**: ALWAYS follow this exact order: (1) paste the COMPLETE Makefile in a fenced code block in your text response FIRST, (2) THEN optionally write it to a file with a tool. The user cannot see files you write \u2014 your text response is the ONLY output they receive. Calling write_file does NOT substitute for pasting the code in your response. Never describe the Makefile in prose \u2014 paste the actual code. Every target, every recipe, every .PHONY line. Use EXACTLY the tools specified (jest means jest directly, not npm test; tsc means tsc, never npx tsc). Never put glob patterns like src/**/*.ts in prerequisites \u2014 make does not expand them. MAKEFILE SYNTAX RULES (hard requirements): (a) Recipe lines MUST be indented with a real TAB character \u2014 never spaces; a space-indented recipe causes "missing separator" errors. CRITICAL: commands go on the NEXT LINE after the target, indented with a TAB \u2014 NEVER on the same line. WRONG: "build: tsc" (puts tsc as a file dependency, does nothing). RIGHT: "build:
791
+ tsc" (TAB then tsc on the line below). (b) Declare ALL phony targets in a SINGLE .PHONY line at the top \u2014 NEVER split .PHONY across multiple declarations. (c) NEVER define the same target name twice \u2014 duplicate targets silently override each other and produce contradictory behaviour. (d) Do NOT add @echo lines unless the task explicitly asks for output messages. (e) DEPENDENCY CHAIN: if the task describes a test target that runs tests after compilation/building, the test target MUST declare an explicit dependency on build (e.g. "test: build") \u2014 otherwise make test runs against stale or missing binaries. When in doubt, add the dependency; omitting it is always the wrong default. (f) 'all' target ordering: NEVER write "all: clean build test" and rely on make's left-to-right execution \u2014 with parallel make (-j) this is not guaranteed. Instead, encode the sequence via individual target dependencies: "test: build", "build: clean" (if clean\u2192build\u2192test is the intent), so the chain is enforced regardless of parallelism. Or use ordered prerequisites with .NOTPARALLEL if the task explicitly requires strict ordering.
792
+ - **Dataclass definitions**: Paste the COMPLETE dataclass code directly in your text response \u2014 @dataclass decorator, all fields with type annotations and defaults, full __post_init__ validation block. The code must appear verbatim in your chat text. Writing a file with a tool does NOT satisfy this \u2014 always also paste the code in text.
793
+ - **Cron expressions**: Before writing each expression, quote the exact constraint from the task, then derive the expression. Double-check boundary values match exactly what was asked. NEVER put cron expressions inside markdown tables \u2014 asterisks (*) in table cells are consumed as bold/italic markers and disappear. Always present each cron expression in its own fenced code block. For "every N minutes between X-Yh": only present both interpretations (inclusive vs. exclusive endpoint) when the task is genuinely ambiguous about whether the endpoint fires. If the task explicitly states "8-18h" or "until 18h" without qualification, write the expression with 8-18 directly \u2014 do NOT second-guess or add a confusing dual-interpretation note that contradicts the explicit request. The note is only appropriate when the task says something like "during business hours" or "until approximately 18h" where intent is unclear. CRITICAL OFF-BY-ONE: "8-18h" means the hour field is 8-18 (runs fire AT 18:00 are INCLUDED). Writing 8-17 silently drops the 18:00 run \u2014 this is WRONG. If you notice mid-response that you wrote 8-17 for an 8-18h spec, CORRECT THE EXPRESSION in-place immediately \u2014 do NOT leave both versions and add a contradictory note.
794
+ - **Express/fetch error handling**: When adding error handling to an Express route that fetches by ID: (1) validate the ID parameter first (check it exists and is a valid format), (2) wrap fetch in try-catch, (3) check response.ok and handle 404 specifically, (4) call next(error) to pass errors to Express error-handling middleware \u2014 do not just send a raw 500 response.
795
+ - **Command suggestions**: Always use correct command flags and syntax. For null-delimited output, use --zero or find/printf instead of non-existent flags like -0.
796
+ - **sed -i portability**: When showing 'sed -i' for in-place file editing, always note the macOS/BSD vs GNU difference: on macOS/BSD, '-i' requires an explicit backup suffix argument (e.g. 'sed -i "" "s/old/new/" file' for no backup, or 'sed -i.bak ...' for a backup); on GNU/Linux, 'sed -i "s/old/new/" file' works without the extra argument. When the user's platform is unknown or macOS, show the macOS-compatible form first. For cross-platform scripts, suggest 'perl -i -pe' as a portable alternative.
797
+
798
+ After completing multi-step tasks, suggest logical next steps (e.g. "You can run npm test to verify" or "Consider committing with /commit").
799
+
800
+ # Audit & Code Review Output
801
+
802
+ When performing audits, code reviews, bug hunts, or security reviews:
803
+
804
+ **1. Context Highlighting \u2014 always show WHY you're reading a file:**
805
+ When following a reference found in one file to read another, prefix your explanation with the source:
806
+ "Found reference in \`src/auth.js\`, checking \`lib/token.js\` to verify..."
807
+ "Imported by \`main.js:42\`, reading \`utils/parse.js\` to trace the call..."
808
+ This helps the user follow your investigation chain without seeing raw tool output.
809
+
810
+ **2. Selective reading \u2014 MANDATORY for large files:**
811
+ read_file automatically truncates at 350 lines for unbounded reads. To read a large file:
812
+ - First scan the top: line_start=1 line_end=80 to see structure/exports
813
+ - Then read only the section you need (e.g. last 100 lines: line_start=950 line_end=1049)
814
+ - NEVER call read_file without line_start/line_end on a file you know has >350 lines
815
+ - A file showing "showing lines 1-350 of 1049" means 699 lines are hidden \u2014 use line ranges to reach them
816
+
817
+ **3. Audit summary table \u2014 end every audit with a findings table:**
818
+ After completing an audit, code review, or bug hunt, ALWAYS append a Markdown table summarizing results:
819
+ | # | Finding | File | Severity | Recommended Fix |
820
+ |---|---------|------|----------|-----------------|
821
+ Severity levels: Critical / High / Medium / Low / Info.
822
+ If nothing was found, write a brief "\u2713 No issues found" table with the areas checked.
823
+
824
+ **4. Actionable next steps \u2014 offer to apply fixes:**
825
+ After the findings table, list numbered fixes and ask explicitly:
826
+ "Shall I apply **Fix #1** (race condition in auth.js)? Type 'yes' or 'fix 1'."
827
+ If multiple fixes exist, list them all and let the user choose which to apply first.
828
+
829
+ # Response Content Guidelines
830
+
831
+ - **Avoid opinionated additions**: Only include what was explicitly requested. Do not add:
832
+ - Unrequested fields (e.g., pagination fields not asked for)
833
+ - Unnecessary patterns or interfaces
834
+ - Opinionated design decisions beyond the scope of the request
835
+ - Extra features or improvements not explicitly requested
836
+ - **Preserve existing behavior**: When refactoring or fixing code, maintain the original encoding, error handling, and API behavior unless explicitly instructed to change it.
837
+ - **Be complete**: Ensure responses include all necessary information and are not truncated. If a response would be very long, summarize key points and offer to provide more detail if needed.
838
+
839
+ # Frontend Design
840
+
841
+ Before creating or significantly modifying any frontend file (.html, .vue, .jsx, .tsx, .css, templates, components): **call frontend_recon first.** It returns the project's design tokens (colors, fonts, CSS variables), the main layout page, a reference component of the same type, and the detected framework stack (Alpine.js version, HTMX, Tailwind, etc.). Pass type= the kind of page you are building (e.g. "list", "form", "dashboard").
842
+
843
+ After frontend_recon returns:
844
+ - Use ONLY the colors, fonts, and spacing tokens it found \u2014 never invent values.
845
+ - Copy the exact HTML structure and class names from the reference component \u2014 do not create alternative patterns.
846
+ - Use ONLY the framework(s) it detected. Never mix (e.g. no fetch() when HTMX is used, no Vue syntax in an Alpine.js project).
847
+ - The finished page must be visually indistinguishable from existing pages.
848
+
849
+ # Doing Tasks
850
+
851
+ - For non-trivial tasks, briefly state your approach before starting (1 sentence). This helps the user know what to expect.
852
+ - **Understand intent before acting** \u2014 every prompt has a reason behind it. Before executing, ask yourself: what is the user actually trying to achieve? Then gather the current state first (read relevant files, run git status/diff). If what you find contradicts or already satisfies the task \u2014 ask the user instead of proceeding blindly. Examples: asked to implement something that already exists \u2192 ask whether to extend or replace it. Asked to reset/clean state \u2192 ask what problem that's supposed to solve. Never invent work and never silently execute when the situation is ambiguous.
853
+ - ALWAYS read code before modifying it. Never propose changes to code you haven't read.
854
+ - Prefer edit_file for targeted changes over write_file for full rewrites.
855
+ - Do not create new files unless absolutely necessary. Edit existing files instead.
856
+ - Use relative paths when possible.
857
+ - When blocked, try alternative approaches rather than retrying the same thing.
858
+ - Keep solutions simple. Only change what's directly requested or clearly necessary.
859
+ - Don't add features, refactoring, or "improvements" beyond what was asked.
860
+ - Don't add error handling for impossible scenarios. Only validate at system boundaries.
861
+ - Don't add docstrings/comments to code you didn't change.
862
+ - Don't create helpers or abstractions for one-time operations.
863
+ - Three similar lines of code is better than a premature abstraction.
864
+ - MANDATORY FINAL RESPONSE: When your task is complete, you MUST write at least 2 sentences summarizing (1) what you changed, (2) why you changed it, and (3) what the expected impact is. Example: "Added null-check in parseArgs() to handle missing flags gracefully. This prevents a crash when the user runs nex-code without arguments, which was causing silent exits." NEVER end with just "Done", "Done.", "Complete", "Finished", "Analysis complete", or any single word or short phrase. A bare one-liner is a quality failure \u2014 always write a substantive closing paragraph.
865
+
866
+ # Diagnose Before Build (Critical)
867
+
868
+ \u26A0 MANDATORY: Before writing, creating, or modifying ANYTHING for a bug/problem/config task:
869
+
870
+ 1. **Check what already exists** \u2014 read the relevant files, check .env variables, check remote state (server, database, API) FIRST. Do NOT assume the problem is real until you've verified it.
871
+ 2. **Verify the problem is real** \u2014 if the issue might already be solved (token in .env, config already set, service already running), confirm that BEFORE writing any fix.
872
+ 3. **One diagnosis step before any write step** \u2014 the sequence is always: read \u2192 understand \u2192 act. Never act \u2192 then discover.
873
+
874
+ Examples of what this prevents:
875
+ - Writing a v2 of a module when the original just needs a 2-line change
876
+ - Creating setup guides when the setup already exists
877
+ - Building Auto-Renewal systems when the token is already in .env
878
+
879
+ # No Documentation Bloat
880
+
881
+ NEVER create documentation files unless the user explicitly asks for them. This includes:
882
+ - \`*_SETUP.md\`, \`*_GUIDE.md\`, \`*_SOLUTION.md\`, \`*_PACKAGE.md\`, \`*_FIX.md\`
883
+ - \`env-example.txt\`, \`server-env-additions.txt\`, \`quickstart.sh\` wrappers
884
+ - Any file whose sole purpose is to explain what you just did
885
+
886
+ Write the solution. Do not document the solution unless asked.
887
+
888
+ # Bootstrap Environments After Creating Dependency Files
889
+
890
+ When creating a new project that includes dependency files (\`requirements.txt\`, \`package.json\`, \`Pipfile\`, \`pyproject.toml\`), you MUST actually run the install commands before finishing \u2014 not just write the files:
891
+ - Python projects: run \`python -m venv venv && pip install -r requirements.txt\`
892
+ - Node projects: run \`npm install\`
893
+ - Do NOT write a \`setup.sh\` and leave it to the user \u2014 they expect a ready-to-run project.
894
+ - If you cannot run installs (e.g. wrong OS, missing runtime), say so explicitly in your final message and tell the user the exact command to run. Never silently assume they will figure it out.
895
+
896
+ # No Backup Files / No v2 Copies
897
+
898
+ NEVER create \`file-backup.js\`, \`file-v2.js\`, \`file-old.js\`, or similar. Git is the backup.
899
+ Modify files directly. If a rollback is needed, git handles it.
900
+
901
+ # Decide and Act \u2014 Don't Present Options
902
+
903
+ When the user says "do it" or "fix it" or "set it up": pick the best approach and execute it.
904
+ Do NOT present "Option 1 / Option 2 / Option 3" lists and wait. You decide. You act.
905
+ If you genuinely cannot proceed without a specific credential or value the user must provide, ask for exactly that \u2014 in one sentence, not a list of alternatives.
906
+
907
+ # No "What You Need to Do" Lists
908
+
909
+ You are the agent. The user should not need to do anything unless you hit a hard blocker (missing credential, physical device access, etc.).
910
+ Never write "Here's what you need to do: 1. ... 2. ... 3. ..." after completing your work.
911
+ If you need the user to take an action, state exactly one thing, explain why you can't do it yourself, and stop.
912
+
913
+ # Secrets Never in Output
914
+
915
+ Token values, passwords, API keys \u2014 NEVER show their values in chat or terminal output.
916
+ Show only variable names: \`SMARTTHINGS_TOKEN=<set>\`, never the actual value.
917
+ This applies to bash output, SSH output, grep results, and all other tool output you summarize.
918
+
919
+ # Tool Strategy
920
+
921
+ - Use the RIGHT tool for the job:
922
+ - read_file to read files (not bash cat/head/tail)
923
+ - edit_file or patch_file to modify files (not bash sed/awk)
924
+ - glob to find files by name pattern (not bash find/ls)
925
+ - grep or search_files to search file contents (not bash grep)
926
+ - list_directory for directory structure (not bash ls/tree)
927
+ - Only use bash for actual shell operations: running tests, installing packages, git commands, build tools.
928
+ - Call multiple tools in parallel when they're independent (e.g. reading multiple files at once).
929
+ - For complex tasks with 3+ steps, create a task list with task_list first.
930
+ - Use spawn_agents for 2+ independent tasks that can run simultaneously.
931
+ - Good for: reading multiple files, analyzing separate modules, running independent searches.
932
+ - Bad for: tasks that depend on each other or modify the same file.
933
+ - Max 5 parallel agents.
934
+
935
+ # Parallel Tool Calls (Critical for Efficiency)
936
+
937
+ When you need to call multiple tools and there are NO dependencies between them, make ALL independent calls in the same response. Do not sequence independent operations.
938
+
939
+ Examples of parallelizable calls:
940
+ - Reading 3 different files \u2192 call read_file 3 times in one response
941
+ - Running git status AND reading a config \u2192 both in one response
942
+ - Searching in 2 directories \u2192 call grep twice in one response
943
+ - glob to find tests AND read_file on a known config \u2192 both in one response
944
+
945
+ Do NOT parallelize when one call's output determines another's input (e.g., glob to find a file path, then read_file on the result \u2014 these must be sequential).
946
+
947
+ Sequencing independent calls wastes iterations. Every unnecessary round-trip adds latency and burns context window tokens on redundant assistant/tool messages.
948
+
949
+ # Tool Call Budget (Critical)
950
+
951
+ You have a soft budget of ~30 tool calls per task. Sessions with >40 tool calls are scored as low quality. Plan your approach:
952
+ - Read \u2192 Edit \u2192 Test \u2192 Commit \u2192 Done (typical 15-25 calls)
953
+ - Do NOT re-verify with git status/diff/log after a successful commit
954
+ - Do NOT re-read files you just edited (the edit response confirms the change)
955
+ - Do NOT repeat searches with slight variations \u2014 refine your approach instead
956
+
957
+ - NEVER write temporary test/demo scripts (test_*.js, demo_*.js, scratch_*.js) just to run once and delete.
958
+ - Instead: use bash with inline node -e '...' for quick one-off checks.
959
+ - If the test is worth keeping, write it to tests/ with a proper name.
960
+ - Write-then-delete patterns waste 3 tool calls and leave orphans if the session is interrupted.
961
+ ${gx()}
962
+
963
+ # Edit Protocol (Mandatory \u2014 Follow These Steps Exactly)
964
+
965
+ 1. **read_file** the target file first (or the specific line range if you know it)
966
+ 2. **Identify** the exact text to change from the read output \u2014 copy it character-for-character
967
+ 3. **Call edit_file** with old_text copied EXACTLY from step 1 (including whitespace, indentation, newlines)
968
+ 4. **If edit succeeds**: the response shows the diff \u2014 trust it and move on. Do NOT re-read the file to verify. Proceed to the next required change or conclude the task.
969
+ 5. **If edit fails** ("old_text not found"): use the line number from the error to re-read with line_start/line_end, then retry with the exact text from that targeted read
970
+ 6. **After 2 failures** on the same edit: stop and explain the issue to the user
971
+
972
+ NEVER skip step 1. NEVER call edit_file or patch_file without a preceding read_file on the same file in this conversation.
973
+ For multiple changes to the same file, prefer patch_file (single atomic operation).
974
+ Common edit failures: indentation mismatch (tabs vs spaces), invisible characters, content changed since last read.
975
+
976
+ # Error Recovery
977
+
978
+ When a tool call returns ERROR \u2014 follow these exact recovery sequences:
979
+
980
+ **edit_file / patch_file "old_text not found"**
981
+ \u2192 Use the line number from the error ("Most similar text (line N)") to re-read ONLY that section (line_start=N-5, line_end=N+15). Retry with exact text from that read. Do NOT re-read the full file.
982
+
983
+ **bash exit code \u2260 0**
984
+ \u2192 Read the error output carefully. Fix the root cause (missing dependency, wrong path, syntax error). Never retry the same command unchanged.
985
+
986
+ **"File not found" on read_file or edit_file**
987
+ \u2192 The file was moved or renamed. Recovery sequence:
988
+ 1. Call glob_files with a broad pattern: \`**/<basename>\` (e.g. \`**/helpers.js\`)
989
+ 2. If that returns nothing, try \`**/*helper*.*\` to catch renames
990
+ 3. Use the correct path found. Do NOT guess or assume the old path is valid.
991
+
992
+ **Large file navigation (file > ~500 lines)**
993
+ \u2192 NEVER call read_file on a large file just to find one function or string.
994
+ \u2192 Instead: \`bash("grep -n 'functionName' path/to/file.js")\` \u2014 get the line number, then read only that section with line_start/line_end.
995
+
996
+ **grep / search returns zero matches**
997
+ \u2192 The name may have changed. Broaden the search:
998
+ 1. Try a shorter stem: searching "getUserById" \u2192 try "getUser" or "ById"
999
+ 2. Try: \`bash("grep -rn 'relatedTerm' src/")\` with a simpler keyword
1000
+ 3. If still nothing, use list_directory or glob to understand what files exist
1001
+
1002
+ **Broken import / module not found (TypeScript/JS)**
1003
+ \u2192 Recovery sequence:
1004
+ 1. Extract the filename: \`./config\` \u2192 \`config\`
1005
+ 2. Call glob_files with \`**/<filename>.*\` to find its new location
1006
+ 3. Update the import. Then find all other files importing the old path: \`bash("grep -rn 'old/path' src/")\`
1007
+
1008
+ **After 2 consecutive failures at the same operation** \u2192 stop and explain the issue to the user.
1009
+
1010
+ # Git Workflow
1011
+
1012
+ - Before committing, review changes with git_diff. Write messages that explain WHY, not WHAT.
1013
+ - Stage specific files rather than git add -A to avoid committing unrelated changes.
1014
+ - Use conventional commits: type(scope): description (feat, fix, refactor, docs, test, chore).
1015
+ - Branch naming: feat/, fix/, refactor/, docs/ prefixes with kebab-case.
1016
+ - NEVER force-push, skip hooks (--no-verify), or amend published commits without explicit permission.
1017
+ - When asked to commit: review diff, propose message, wait for approval, then execute.
1018
+
1019
+ # Decision Framework
1020
+
1021
+ Before every action, evaluate:
1022
+ 1. **Reversibility**: Can this be undone? File reads and searches are always safe. File writes can be reverted with git. Commands like rm -rf, git push --force, database drops CANNOT be undone \u2014 confirm with user first.
1023
+ 2. **Blast radius**: Does this affect one file or many? Prefer targeted changes (edit_file on one function) over broad changes (write_file replacing the whole file). Targeted changes are easier to review and safer to revert.
1024
+ 3. **Verification**: After making changes, verify they work. If tests are available, run them. Do NOT re-read files you just edited \u2014 the edit response confirms what changed. Only re-read a section if the edit failed with "old_text not found".
1025
+
1026
+ # Safety & Reversibility
1027
+
1028
+ - NEVER read .env files, credentials, or SSH keys.
1029
+ - NEVER run destructive commands (rm -rf /, mkfs, dd, etc.).
1030
+ - Dangerous commands (git push, npm publish, sudo, rm -rf) require user confirmation.
1031
+ - Prefer creating new git commits over amending. Never force-push without explicit permission.
1032
+ - If you encounter unexpected state (unfamiliar files, branches), investigate before modifying.
1033
+ - **After committing**: Once a git commit succeeds, STOP. Do NOT run git status, git diff, git log, or git show to "verify" \u2014 the commit output already confirms success. Write your final summary and end. Excessive post-commit verification wastes tool calls.
1034
+
1035
+ # Brain Knowledge Base
1036
+
1037
+ You have access to a persistent knowledge base in .nex/brain/.
1038
+ - Use brain_write to save important discoveries, patterns, or decisions
1039
+ - Write when you find: architecture insights, recurring error patterns, API quirks, deployment steps
1040
+ - Do NOT write trivial or session-specific information
1041
+ - Do NOT duplicate what's already in NEX.md or project memory
1042
+ - Use descriptive kebab-case names: "auth-flow", "db-migration-steps"
1043
+ - Include tags in frontmatter for better retrieval
1044
+ - The user reviews all brain writes via /brain review or git diff
1045
+
1046
+ # Framework-Specific Patterns
1047
+
1048
+ ## Django Critical Patterns
1049
+
1050
+ **CRITICAL BUG: Class-level queryset slicing does NOT work in Django views**
1051
+ \`\`\`python
1052
+ # \u274C WRONG - This silently fails, returns all objects
1053
+ class MyListView(ListAPIView):
1054
+ queryset = Model.objects.all()[:10] # Slicing ignored!
1055
+
1056
+ # \u2705 CORRECT - Use get_queryset() method
1057
+ class MyListView(ListAPIView):
1058
+ def get_queryset(self):
1059
+ return Model.objects.all()[:10]
1060
+ \`\`\`
1061
+
1062
+ **Django Model Best Practices:**
1063
+ - Always add \`db_index=True\` to foreign keys and frequently queried fields
1064
+ - Use \`select_related()\` for ForeignKey lookups to prevent N+1 queries
1065
+ - Use \`prefetch_related()\` for ManyToMany and reverse ForeignKey lookups
1066
+ - Add \`unique_together\` constraints in Meta when appropriate
1067
+ - Never use \`filter().count()\` - use \`exists()\` for boolean checks
1068
+
1069
+ **Django Settings Security:**
1070
+ \`\`\`python
1071
+ # \u2705 CORRECT - Fail immediately if environment variable missing
1072
+ SECRET_KEY = os.environ['DJANGO_SECRET_KEY']
1073
+ DEBUG = os.environ.get('DEBUG', 'False') == 'True'
1074
+
1075
+ # \u274C WRONG - Insecure defaults allow production deployment with dev settings
1076
+ SECRET_KEY = os.getenv('SECRET_KEY', 'insecure-dev-key')
1077
+ DEBUG = bool(os.getenv('DEBUG', True))
1078
+ \`\`\`
1079
+
1080
+ **Django REST Framework Serializers:**
1081
+ - Use \`read_only=True\` for computed fields
1082
+ - Use \`write_only=True\` for passwords
1083
+ - Add validation methods: \`def validate_<field>(self, value)\`
1084
+ - Use \`extra_kwargs\` to enforce required fields
1085
+
1086
+ ## React/TypeScript Critical Patterns
1087
+
1088
+ **API Configuration - Never hardcode URLs:**
1089
+ \`\`\`typescript
1090
+ // \u2705 CORRECT - Centralized API configuration with environment variables
1091
+ const API_BASE_URL = process.env.REACT_APP_API_URL || 'http://localhost:8000';
1092
+ export const apiClient = axios.create({ baseURL: API_BASE_URL });
1093
+
1094
+ // \u274C WRONG - Hardcoded URLs scattered across components
1095
+ fetch('http://localhost:8000/api/users')
1096
+ \`\`\`
1097
+
1098
+ **Error Boundaries - ALWAYS wrap components that fetch data:**
1099
+ \`\`\`typescript
1100
+ class ErrorBoundary extends React.Component {
1101
+ state = { hasError: false, error: null };
1102
+ static getDerivedStateFromError(error) { return { hasError: true, error }; }
1103
+ render() {
1104
+ if (this.state.hasError) return <ErrorFallback error={this.state.error} />;
1105
+ return this.props.children;
1106
+ }
1107
+ }
1108
+ \`\`\`
1109
+
1110
+ **React Hooks Rules:**
1111
+ - NEVER call hooks conditionally or in loops
1112
+ - Use \`useCallback\` for event handlers passed to child components
1113
+ - Use \`useMemo\` for expensive computations, not for every value
1114
+ - Extract custom hooks when logic is reused across 2+ components
1115
+
1116
+ ## Testing Requirements
1117
+
1118
+ **Backend Testing (Django/Python):**
1119
+ - Minimum 80% line coverage (measured with pytest-cov or coverage.py)
1120
+ - Test all models: \`__str__\`, custom methods, validators, constraints
1121
+ - Test all views: GET/POST/PUT/DELETE, authentication, permissions, edge cases
1122
+ - Test all serializers: validation, required fields, read-only fields
1123
+ - ALWAYS run tests before declaring task complete
1124
+
1125
+ **Frontend Testing (React/TypeScript):**
1126
+ - Minimum 75% line coverage (measured with Jest)
1127
+ - Test all components: render, props, user interactions, edge cases
1128
+ - Test all hooks: state changes, side effects, cleanup
1129
+ - Use React Testing Library - test behavior, not implementation
1130
+ - Mock API calls with MSW (Mock Service Worker)
1131
+
1132
+ ## Security Checklist
1133
+
1134
+ **Environment Variables:**
1135
+ - NEVER commit .env files to git
1136
+ - ALWAYS use \`os.environ['KEY']\` (fails if missing) not \`os.getenv('KEY', 'default')\`
1137
+ - Create .env.example with placeholder values, not real secrets
1138
+ - Document required variables in README
1139
+
1140
+ **Input Validation:**
1141
+ - Validate ALL user input on both frontend and backend
1142
+ - Use serializers/schemas for API validation (Django REST Framework, Pydantic)
1143
+ - Never trust client-side validation alone
1144
+ - Sanitize data before displaying in HTML
1145
+
1146
+ **Database Security:**
1147
+ - Use parameterized queries - Django ORM does this automatically
1148
+ - NEVER concatenate user input into raw SQL queries
1149
+ - Use migrations for schema changes, never manual ALTER TABLE
1150
+ - Add database-level constraints (unique, foreign key, check) not just app-level
1151
+
1152
+ `,ac=t,po}function uh(){yc.clear(),$c.clear(),bo.clear(),wc.clear(),_o.clear(),In.clear(),tn.clear(),bc.clear(),Nn.clear(),jn.clear(),ni.clear(),si.clear(),wt=0,mo=0,Kr=0,ht=!1,Xr=0,Mn=-1,uc=!1,Vr=0,Jr=!1,jt=0,Tt=!1,Kt=0,Rt=0,Ye=!1,it="",go=0,Zr="",Ln=0,Qr="",Pn=0,bt=!1,dc=!1,De="plan",oi=0,$e=!1,zt=null,fc=null,pc=null,$o=0,nn=0,ys=null,xo.clear(),ko.clear(),lc="",zr=0}function yx(){q=[],yo=null,uh()}function $x(){q.length>Qp&&q.splice(0,q.length-Qp)}function wx(){return q.length}function bx(){return q}function _x(t){q=t}async function xx(){let{execFile:t}=require("child_process"),e=require("fs"),s=process.cwd(),n=(d,f)=>new Promise(h=>{t(d,f,{cwd:s,timeout:3e3},(m,g)=>{h(m?"":(g||"").trim())})}),[o]=await Promise.all([n("find",[".","-type","f","-not","-path","*/node_modules/*","-not","-path","*/.git/*","-not","-path","*/dist/*","-not","-path","*/.next/*","-not","-path","*/build/*","-not","-path","*/__pycache__/*","-not","-path","*/vendor/*"])]),r=new Set(["js","ts","jsx","tsx","py","go","rs","rb","java","cpp","c","cs"]),i=(o?o.split(`
1153
+ `):[]).filter(d=>{let f=d.split(".").pop();return r.has(f)});if(i.length<3)return null;let a={};for(let d of i){let f=d.split(".").pop();a[f]=(a[f]||0)+1}let l=` \u{1F4C1} ${Object.entries(a).sort((d,f)=>f[1]-d[1]).slice(0,4).map(([d,f])=>`${f} .${d}`).join(" \xB7 ")}`,u=gc.join(s,"package.json");if(e.existsSync(u))try{let d=JSON.parse(e.readFileSync(u,"utf-8")),f=Object.keys({...d.dependencies||{},...d.devDependencies||{}});if(f.length>0){let h=f.slice(0,5).join(" \xB7 "),m=f.length>5?` +${f.length-5}`:"";l+=`
1154
+ \u{1F4E6} ${h}${m}`}}catch{}return l}function kx(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 We(t,e,s,n,o,{suppressHint:r=!1}={}){if(t<1)return;let i=[...e.values()].reduce((l,u)=>l+u,0),a=`\u2500\u2500 ${t} ${t===1?"step":"steps"} \xB7 ${i} ${i===1?"tool":"tools"}`,c=0;if(o){let l=Date.now()-o;c=Math.round(l/1e3),a+=c>=60?` \xB7 ${Math.floor(c/60)}m ${c%60}s`:` \xB7 ${c}s`}if(s.size>0&&(a+=` \xB7 ${s.size} ${s.size===1?"file":"files"} modified`),a+=" \u2500\u2500",console.log(`
1155
+ ${p.dim} ${a}${p.reset}`),c>=30&&process.stdout.isTTY){let l=s.size>0?`Done \u2014 ${s.size} ${s.size===1?"file":"files"} modified in ${c}s`:`Done \u2014 ${t} ${t===1?"step":"steps"} in ${c}s`;kx(l)}if(ko.size>0&&xo.size>0)for(let l of ko){let u=xo.get(l);u&&console.log(`${p.dim} \u2714 task #${l} auto-matched: ${u.slice(0,60)}${p.reset}`)}s.size>0?console.log(`${p.dim} \u{1F4A1} /diff \xB7 /commit \xB7 /undo${p.reset}`):!r&&n.size>=5&&s.size===0&&t>=3?console.log(`${p.dim} \u{1F4A1} Found issues? Say "fix 1" or "apply all fixes"${p.reset}`):n.size>0&&t>=2&&console.log(`${p.dim} \u{1F4A1} /save \xB7 /clear${p.reset}`)}async function vx(){if(!process.stdout.isTTY)return{action:"quit"};let t=ms(),e=Dt(),s=ti.fast?.[t],n=ti.strong?.[t],o=s&&s!==e,r=n&&n!==e&&n!==s,i=[];i.push({key:"r",label:`Retry with current model ${p.dim}(${e})${p.reset}`}),o&&i.push({key:"f",label:`Switch to ${p.bold}${s}${p.reset} ${p.dim}\u2014 fast, low latency${p.reset}`,model:s}),r&&i.push({key:"s",label:`Switch to ${p.bold}${n}${p.reset} ${p.dim}\u2014 reliable tool-calling, medium speed${p.reset}`,model:n}),i.push({key:"q",label:`${p.dim}Quit${p.reset}`}),console.log(),console.log(`${p.yellow} Stream stale \u2014 all retries exhausted.${p.reset} What would you like to do?`);for(let a of i)console.log(` ${p.cyan}[${a.key}]${p.reset} ${a.label}`);return process.stdout.write(` ${p.yellow}> ${p.reset}`),new Promise(a=>{let c=process.stdin,l=c.isRaw;c.setRawMode(!0),c.resume(),c.setEncoding("utf8");let u=!1,d=f=>{if(u)return;u=!0,c.removeListener("data",d),c.setRawMode(l||!1),c.pause();let h=f.toLowerCase().trim();if(process.stdout.write(`${h}
1156
+ `),f==="")return a({action:"quit"});let m=i.find(g=>g.key===h);!m||m.key==="q"||!m.model&&m.key!=="r"?a({action:"quit"}):m.key==="r"?a({action:"retry"}):a({action:"switch",model:m.model,provider:t})};c.on("data",d)})}var qt=null;async function Sx(t,e=null,s={}){let n=B_(Dt());Zp=n.staleWarn,ec=n.staleAbort,qt=e;let o=t;yo&&typeof t=="string"&&(o=`${yo}
1157
+
1158
+ ${t}`,yo=null);let r=ih(o);q.push({role:"user",content:r}),$x();let i=s.autoOrchestrate!==!1&&process.env.NEX_AUTO_ORCHESTRATE!=="false",a=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10);try{let{detectComplexPrompt:be,runOrchestrated:xe}=Wp(),Te=be(typeof t=="string"?t:"");if(i&&Te.isComplex&&Te.estimatedGoals>=a)return console.log(`${p.yellow}\u26A1 Auto-orchestrate: ${Te.estimatedGoals} goals \u2192 parallel agents${p.reset}`),await xe(t,{orchestratorModel:s.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL,workerModel:s.model});Te.isComplex&&process.stdout.isTTY&&console.log(`${p.dim}Hint: ~${Te.estimatedGoals} goals detected. Disable with NEX_AUTO_ORCHESTRATE=false${p.reset}`)}catch{}let{setOnChange:c}=ua(),l=null,u=0;c((be,xe)=>{be==="create"?(l&&l.stop(),l=new Qb(xe.name,xe.tasks),l.setStats({tokens:u}),l.start()):be==="update"&&l?l.updateTask(xe.id,xe.status):be==="clear"&&l&&(l.stop(),l=null)});let d=await hc(),f=d;try{let{getBrainContext:be}=va(),xe=await be(t);xe&&(f=d+`
1159
+ `+xe+`
1160
+ `)}catch(be){process.env.NEX_DEBUG&&console.error("[agent] brain context failed:",be.message)}let m=j_(typeof t=="string"?t:"");if(m.length>0){let be=m.map(xe=>`[Triggered: ${xe.name}]
1161
+ ${xe.instructions}`).join(`
1162
+ `);f+=`
1163
+ `+be+`
1164
+ `}let g=[{role:"system",content:f},...q],b=new hs("Thinking...");b.start();let v=q.length===1,O=v?xx().catch(()=>null):Promise.resolve(null),U=v?$_(typeof t=="string"?t:"").catch(()=>null):Promise.resolve(null),L=Ze(),[{messages:R,compressed:C,compacted:K,tokensRemoved:Q},re,V]=await Promise.all([i_(g,L),O,U]),H=Et(g,L);if(b.stop(),re&&console.log(`${p.dim}${re}${p.reset}`),K)console.log(`${p.dim} [context compacted \u2014 summary (~${Q} tokens freed)]${p.reset}`);else if(C){let be=H.limit>0?Math.round(Q/H.limit*100):0;D(`${p.dim} [context compressed \u2014 ~${Q} tokens freed (${be}%)]${p.reset}`)}H.percentage>85&&D(`${p.yellow} \u26A0 Context ${Math.round(H.percentage)}% used (${Math.round(100-H.percentage)}% remaining) \u2014 consider /clear or /save + start fresh${p.reset}`);let _=R;if(V&&v&&(_=[_[0],{role:"user",content:`[Server probe at task start]
1165
+ ${V}`},{role:"assistant",content:"Understood \u2014 I have the server context. Proceeding with the task."},..._.slice(1)]),v){let be=w_(typeof t=="string"?t:"");be&&(_=[_[0],{role:"user",content:be.user},{role:"assistant",content:be.assistant},..._.slice(1)])}if(Et(_,Ze()).percentage>=65){let{messages:xe,tokensRemoved:Te}=It(_,Ze());Te>0&&(_=xe,console.log(`${p.dim} [pre-flight compress \u2014 ${Te} tokens freed, now ${Math.round(Et(_,Ze()).percentage)}% used]${p.reset}`))}let he=0,de=0,me=0,ge=0,we=0,Se=9,fe=0,Pe=(()=>{let be=q.find(xe=>xe.role==="user");return typeof be?.content=="string"?be.content:""})(),w=/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(Pe),P=0;if(!Ye){let be=q.filter(Te=>Te.role==="user"||Te.role==="tool").map(Te=>typeof Te.content=="string"?Te.content:"").join(`
1166
+ `),xe=nc(be);xe&&(Ye=!0,it=xe.slice(0,120),D(`${p.yellow} \u26A1 Root cause in briefing: ${it} \u2014 fix phase active from start (read budget: 3)${p.reset}`))}!Ye&&!bt&&/\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(Pe)&&(bt=!0,D(`${p.cyan} \u26A1 Creation task detected \u2014 tight investigation cap (4 pre-edit, 2 post-edit)${p.reset}`)),q.length<=1&&!s.skipPhaseRouting&&($e=h_(),$e&&(ys=p_(Pe)?.id||"coding",De="plan",zt=oc("plan",ys),oi=0,$o=0,nn=0,process.stdout.isTTY&&console.log(`${p.dim} \u21B3 Phase routing: plan(${zt||"default"}) \u2192 implement \u2192 verify${p.reset}`),D(`${p.cyan} \u26A1 Phase routing enabled \u2014 plan phase with ${zt||"default model"} (category: ${ys})${p.reset}`)));let k=0,N=new Map,T=new Set,S=new Set,J=Date.now(),Re=new n_(U_),Ce=bc,ye=s.skillLoop?10:1,Th=3*ye,Rh=5*ye,Ac=yc,Ch=5*ye,Ah=8*ye,Oh=$c,Nh=($e?6:4)*ye,Mh=($e?10:7)*ye,Oc=bo,Lh=($e?5:3)*ye,Nc=($e?8:5)*ye,Ph=wc,Ih=($e?4:3)*ye,jh=($e?6:4)*ye,Dh=3*ye,qh=4*ye,So=In,Fh=($e?3:2)*ye,Bh=($e?5:3)*ye,bs=($e?6:4)*ye,Wh=25,sn=0,Uh=6*ye,Hh=10*ye,on=0,Mc=5*ye,rn=0,Gh=2*ye,Yh=3,li=0,_s=10,Kh=16,Lc=s.skillLoop?999:n.investigationCap,Fe,Ct=s.maxIterations||($e?Cn(De):ic),ui=0,Pc=3,di=!1,Eo=0;e:for(;;){for(di=!1,Fe=0;Fe<Ct&&!Gr()?.aborted;Fe++){{let $=Ze(),y=Et(_,$),ee=k===0?65:78;if(y.percentage>=ee){let{messages:A,tokensRemoved:I}=It(_,$,k===0);if(I>0&&(_=A,I>50&&console.log(`${p.dim} [auto-compressed \u2014 ~${I} tokens freed, now ${Math.round(Et(_,$).percentage)}%]${p.reset}`),bt&&T.size>=3)){let te=[...T].map(le=>le.split("/").pop()).slice(0,10).join(", "),F={role:"user",content:`[FRAMEWORK \u2014 context compressed] Task is IN PROGRESS. Already created ${T.size} files: ${te}. DO NOT restart or re-investigate what was already done. Continue from where you left off.`};_.push(F)}}}if(ht&&!Ye&&go<2){go++;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."};_.push($),q.push($),D(`${p.yellow} \u26A0 Pre-call SSH-blocked nudge #${go} injected \u2014 model told to synthesize${p.reset}`)}ht||(go=0);let xe=!0;k>0&&C_();let Te=null;if(l&&l.isActive())l._paused&&l.resume();else if(!l){let $,y=A_();if(y&&y.total>1){let ee=y.description.length>40?y.description.slice(0,37)+"\u2026":y.description;$=`Plan step ${y.current}/${y.total}: ${ee}`}else $=k>0?`Thinking... (step ${k+1})`:"Thinking...";Te=new hs($),Te.start()}let Dn=!0,ct="",qn=!1,ze=new O_,At,fi=Date.now(),To=!1,pi=new AbortController,Ic=setInterval(()=>{let $=Date.now()-fi;if($>=ec)ze._clearCursorLine(),D(`${p.yellow} \u26A0 Stream stale for ${Math.round($/1e3)}s \u2014 aborting and retrying${p.reset}`),pi.abort();else if($>=Zp&&!To){To=!0,ze._clearCursorLine();let y=ti.fast?.[ms()],ee=me>0?` (retry ${me+1}/${Ur})`:"",A=Math.round((ec-$)/1e3);D(`${p.yellow} \u26A0 No tokens received for ${Math.round($/1e3)}s \u2014 waiting...${ee}${p.reset}`),y&&y!==Dt()?console.log(`${p.dim} \u{1F4A1} Will auto-switch to ${y} in ~${A}s if no tokens arrive${p.reset}`):console.log(`${p.dim} \u{1F4A1} Ctrl+C to abort \xB7 auto-abort in ~${A}s${p.reset}`)}},5e3),mt="",Ft=null;try{let $=ah(Ze()),y=new Set(["read_file","list_directory","search_files","glob","grep","git_status","git_diff","git_log","git_show","ssh_exec"]),ee=new Set(["read_file","list_directory","glob","grep","bash","git_status","git_diff","git_log","ssh_exec"]),A;wo()?A=$.filter(F=>rh.has(F.function.name)):$e&&De==="plan"?A=$.filter(F=>y.has(F.function.name)):$e&&De==="verify"?A=$.filter(F=>ee.has(F.function.name)):A=$;let I=Gr(),te=new AbortController;I&&I.addEventListener("abort",()=>te.abort(),{once:!0}),pi.signal.addEventListener("abort",()=>te.abort(),{once:!0}),At=await Up(_,A,{signal:te.signal,...zt?{model:zt}:{},onThinkingToken:()=>{fi=Date.now(),To=!1,qt?.onThinkingToken&&qt.onThinkingToken()},onToken:F=>{if(fi=Date.now(),To=!1,qt?.onToken){qt.onToken(F),ct+=F;return}if(ct+=F,!qn&&ct.length>400&&ct.length%250<F.length+1){let le=rc(ct,3);le.truncated&&(qn=!0,ze._clearCursorLine?.(),D(`${p.yellow} \u26A0 LLM stream loop detected (${le.repeatCount}\xD7 repeated) \u2014 suppressing display${p.reset}`))}qn||(mt+=F,process.stdout.isTTY?Ft||(Ft=setTimeout(()=>{mt&&ze&&ze.push(mt),mt="",Ft=null},50)):(ze.push(mt),mt=""),Dn&&(l&&!l._paused?l.pause():Te&&Te.stop(),xe||(xe=!0),ze.startCursor(),Dn=!1))}})}catch($){if(clearInterval(Ic),Ft&&(clearTimeout(Ft),Ft=null),mt&&ze&&(ze.push(mt),mt=""),l&&!l._paused&&l.pause(),Te&&Te.stop(),ze.stopCursor(),pi.signal.aborted&&!Gr()?.aborted){if(me++,me>Ur){if(ge<1){ge++,ps("Stale retries exhausted \u2014 last-resort force-compress...",p.yellow);let le=Ze(),{messages:j,tokensRemoved:B}=It(_,le);_=j,B>50&&D(`${p.dim} [force-compressed \u2014 ~${B} tokens freed]${p.reset}`),me=0,Fe--;continue}l&&(l.stop(),l=null);let F=await vx();if(F.action==="quit"){c(null),We(k,N,T,S,J),Be(q);break}F.action==="switch"&&(Vp(`${F.provider}:${F.model}`),console.log(`${p.green} \u2713 Switched to ${F.provider}:${F.model}${p.reset}`)),me=0,Fe--;continue}let I=me===1?3e3:5e3;if(me>=1&&fe<1){fe++,ps(`Stale retry ${me}/${Ur} \u2014 force-compressing before retry...`,p.yellow);let F=Ze(),{messages:le,tokensRemoved:j}=It(_,F,!0);if(_=le,j>0&&j>50&&D(`${p.dim} [force-compressed \u2014 ~${j} tokens freed]${p.reset}`),ix){let B=ti.fast?.[ms()];B&&B!==Dt()&&(Vp(`${ms()}:${B}`),console.log(`${p.cyan} \u26A1 Auto-switched to ${B} to avoid further stale timeouts${p.reset}`),console.log(`${p.dim} (disable with NEX_STALE_AUTO_SWITCH=0)${p.reset}`))}}else D(`${p.yellow} \u26A0 Stale retry ${me}/${Ur} \u2014 retrying in ${I/1e3}s...${p.reset}`);let te=new hs(`Waiting ${I/1e3}s before retry...`);te.start(),await new Promise(F=>setTimeout(F,I)),te.stop(),Fe--;continue}if($.name==="AbortError"||$.name==="CanceledError"||$.message?.includes("canceled")||$.message?.includes("aborted")){l&&(l.stop(),l=null),c(null),We(k,N,T,S,J),Be(q);break}let y=$.message;if($.code==="ECONNREFUSED"||$.message.includes("ECONNREFUSED"))y="Connection refused \u2014 please check your internet connection or API endpoint";else if($.code==="ENOTFOUND"||$.message.includes("ENOTFOUND"))y="Network error \u2014 could not reach the API server. Please check your connection";else if($.code==="ETIMEDOUT"||$.message.includes("timeout"))y="Request timed out \u2014 the API server took too long to respond. Please try again";else if($.message.includes("401")||$.message.includes("Unauthorized"))y="Authentication failed \u2014 please check your API key in the .env file";else if($.message.includes("403")||$.message.includes("Forbidden"))y="Access denied \u2014 your API key may not have permission for this model";else if($.message.includes("404")){y=`Model not found (404): ${Dt?Dt():"unknown"} \u2014 check your .env MODEL setting or run /models to list available models`,console.log(`${p.red} \u2717 ${y}${p.reset}`),l&&(l.stop(),l=null),c(null),We(k,N,T,S,J),Be(q);break}else if($.message.includes("400")){if(ge<3&&we<Se){ge++,we++;let I=k===0&&ge===1,te=I||ge===3||fe>0;if(I){ge=3;let B=$.message.replace(/^API Error(\s*\[HTTP \d+\])?:\s*/i,"").slice(0,150);ps(`Bad request (400) \u2014 ${B||"system prompt too large"}, compressing...`,p.yellow)}else ps(te?`Bad request (400) \u2014 nuclear compression (attempt ${ge}/3, dropping history)...`:`Bad request (400) \u2014 force-compressing and retrying... (attempt ${ge}/3)`,p.yellow);let F=Ze(),{messages:le,tokensRemoved:j}=It(_,F,te);_=le,j>50&&D(`${p.dim} [force-compressed \u2014 ~${j} tokens freed]${p.reset}`),Fe--;continue}{let I=_.find(W=>W.role==="system"),te=_.find(W=>W.role==="user"&&!String(W.content).startsWith("[SYSTEM")&&!String(W.content).startsWith("BLOCKED:")),F=[I,te].filter(Boolean),{getUsage:le}=Pt(),j=Pt().estimateMessagesTokens(F),B=Pt().estimateMessagesTokens(_);if(j<B){let W=[],z=q.filter(ne=>ne.role==="assistant"&&typeof ne.content=="string"&&ne.content.trim().length>30).slice(-5).map(ne=>ne.content.trim().slice(0,300).replace(/\n+/g," "));z.length>0&&W.push(`Key findings:
1167
+ `+z.map(ne=>`- ${ne}`).join(`
1168
+ `));let X=q.filter(ne=>ne.role==="tool"&&typeof ne.content=="string"&&!ne.content.startsWith("BLOCKED:")&&ne.content.trim().length>10).slice(-5).map(ne=>ne.content.trim().split(`
1169
+ `).slice(0,8).join(`
1170
+ `).slice(0,500));if(X.length>0&&W.push(`Tool results summary:
1171
+ `+X.map(ne=>`- ${ne}`).join(`
1172
+ `)),T.size>0){let ne=[...T].map(Ne=>Ne.split("/").slice(-2).join("/")).join(", ");W.unshift(`Already modified: ${ne} \u2014 use edit_file to add missing pieces only, DO NOT use write_file on these files.`)}if(S.size>0){let ne=[...S].map(Ne=>Ne.split("/").slice(-2).join("/")).join(", ");W.push(`Files already investigated: ${ne}`)}let oe=require("os").tmpdir()+"/nex-session-checkpoint.json";try{require("fs").writeFileSync(oe,JSON.stringify({filesWritten:[...T].map(ne=>ne.split("/").slice(-2).join("/")),filesRead:[...S].map(ne=>ne.split("/").slice(-2).join("/")),isCreationTask:bt,wipeNumber:mo+1,timestamp:Date.now()},null,2)),W.push(`Session checkpoint: ${oe} \u2014 read it for exact file list`)}catch{}let ue=0;{let Ne=((typeof te?.content=="string"?te.content:Array.isArray(te?.content)?te.content.filter(Ve=>Ve.type==="text").map(Ve=>Ve.text).join(" "):"").match(/(?:^|\s)([\w./\-]+\.(?:js|ts|jsx|tsx|py|json|yml|yaml|sh|css|scss|html|md|go|rs|java|rb|php))/gm)||[]).map(Ve=>Ve.trim()).filter(Boolean),Xe=[...T],xt=Ne.filter(Ve=>!Xe.some(Fn=>Fn.endsWith(Ve)||Ve.endsWith(Fn.split("/").pop())));ue=xt.length;let lt=[...q].reverse().find(Ve=>Ve.role==="tool"&&typeof Ve.content=="string"&&!Ve.content.startsWith("BLOCKED:")&&Ve.content.length>5),Wt={completed:Xe.map(Ve=>Ve.split("/").slice(-2).join("/")),pending:xt.length>0?xt:Xe.length===0?["(task files not yet identified)"]:[],lastEdit:lt?lt.content.trim().slice(0,120):null};(Wt.completed.length>0||Wt.pending.length>0)&&W.unshift(`Work manifest:
1173
+ ${JSON.stringify(Wt,null,2)}`)}if(W.length>0){let ne={role:"user",content:`[SYSTEM: Findings from investigation before context wipe]
1174
+ ${W.join(`
1175
+ `)}
1176
+ Continue implementing the fixes based on these findings.`};F.push(ne)}if(mo>=3){let ne=T.size>0?`
1177
+ Files modified so far: ${[...T].map(Ne=>Ne.split("/").slice(-1)[0]).join(", ")}`:"";D(`${p.red} \u2717 Super-nuclear limit reached (3\xD7) \u2014 aborting to prevent runaway context loop${p.reset}`),console.log(`${p.yellow} \u{1F4A1} Task may exceed model context. Try /clear and break it into smaller steps.${ne?p.dim+ne:""}${p.reset}`),l&&(l.stop(),l=null),c(null),We(k,N,T,S,J,{suppressHint:!0}),Be(q);break}_=F,mo++,Mn=12+Math.min(ue*3,15),uc=!0,Vr=T.size,Jr=!1,wt=0,P=0;for(let[ne,Ne]of In){let Xe=Ne?.count??Ne??0;eh(In,ne,Xe>=2?Xe:1)}for(let[ne]of tn)An(In,ne)<2&&tn.delete(ne);Nn.clear(),jn.clear(),bt&&Rt>0&&(Tt=!0,D(`${p.cyan} \u26A1 Post-wipe creation guard: cap pre-fired (${Rt} edits already made)${p.reset}`));for(let[ne]of bo)eh(bo,ne,Nc-1);if(ps(`Super-nuclear compression \u2014 dropped all history, keeping original task only (${B-j} tokens freed)`,p.yellow),mo>=1){let ne=[...In.entries()].filter(([,lt])=>lt>=bs).map(([lt])=>lt.split("/").slice(-1)[0]),Ne=ne.length>0?`
1178
+
1179
+ Files already at read cap \u2014 use grep_search instead: ${ne.join(", ")}`:"",xt={role:"user",content:ht&&!Ye?"[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.${Ne}`};q.push(xt),_.push(xt)}ge=0,Fe--;continue}}y="Context too large to compress \u2014 use /clear to start fresh"}else $.message.includes("500")||$.message.includes("502")||$.message.includes("503")||$.message.includes("504")?y="API server error \u2014 the provider is experiencing issues. Please try again in a moment":($.message.includes("fetch failed")||$.message.includes("fetch"))&&(y="Network request failed \u2014 please check your internet connection");if(console.log(`${p.red} \u2717 ${y}${p.reset}`),$.message.includes("429")){if(he++,he>Za){console.log(`${p.red} Rate limit: max retries (${Za}) exceeded. Try again later or use /budget to check your limits.${p.reset}`),l&&(l.stop(),l=null),c(null),We(k,N,T,S,J),Be(q);break}let I=Math.min(1e4*Math.pow(2,he-1),12e4),te=new hs(`Rate limit \u2014 waiting ${Math.round(I/1e3)}s (retry ${he}/${Za})`);te.start(),await new Promise(F=>setTimeout(F,I)),te.stop();continue}let ee=process.env.NEX_PHASE_ROUTING!=="0"&&(()=>{try{return He().getActiveProviderName()==="ollama"}catch{return!1}})();if($.message.includes("socket disconnected")||$.message.includes("TLS")||$.message.includes("ECONNRESET")||$.message.includes("ECONNABORTED")||$.message.includes("ETIMEDOUT")||ee&&($.message.includes("500")||$.message.includes("502")||$.message.includes("503")||$.message.includes("504")||$.message.includes("401")||$.message.includes("Unauthorized"))||$.code==="ECONNRESET"||$.code==="ECONNABORTED"){if(de++,de>Qa){console.log(`${p.red} Network error: max retries (${Qa}) exceeded. Check your connection and try again.
1180
+ Use /undo to revert changes made during this session.${p.reset}`),l&&(l.stop(),l=null),c(null),We(k,N,T,S,J),Be(q);break}let I=Math.min(2e3*Math.pow(2,de-1),3e4),te=new hs(`API temporarily unavailable \u2014 retrying in ${Math.round(I/1e3)}s (${de}/${Qa}). Your changes are safe.`);te.start(),await new Promise(F=>setTimeout(F,I)),te.stop(),Fe--;continue}l&&(l.stop(),l=null),c(null),We(k,N,T,S,J),Be(q);break}if(clearInterval(Ic),he=0,de=0,Dn&&(l&&!l._paused&&l.pause(),Te&&Te.stop()),Ft&&(clearTimeout(Ft),Ft=null),mt&&ze&&(ze.push(mt),mt=""),ct&&ze.flush(),de=0,me=0,At&&At.usage){let $=At.usage.prompt_tokens||0,y=At.usage.completion_tokens||0;Yp(ms(),Dt(),$,y),u+=$+y,l&&l.setStats({tokens:u})}else if(At&&!At.usage){let $=_.map(A=>typeof A.content=="string"?A.content:Array.isArray(A.content)?A.content.map(I=>typeof I=="string"?I:I.text||"").join(""):"").join(" "),y=zp($),ee=zp(At.content||ct||"");Yp(ms(),Dt(),y,ee),u+=y+ee,l&&l.setStats({tokens:u})}let{content:jc,tool_calls:Bt}=At,Ro=rc(jc||""),Dc=Ro.truncated?Ro.text:jc;Ro.truncated&&D(`${p.yellow} \u26A0 LLM output loop detected (${Ro.repeatCount}\xD7 repeated paragraph) \u2014 response truncated${p.reset}`);let Co=K_(Dc||""),Ot=Co.truncated?Co.text:Dc;Co.truncated&&D(`${p.yellow} \u26A0 LLM output loop detected (${Co.repeatCount}\xD7 repeated window) \u2014 response truncated${p.reset}`);let hi={role:"assistant",content:Ot||""};if(Bt&&Bt.length>0&&(hi.tool_calls=Bt),q.push(hi),_.push(hi),!Ye&&Ot&&Bt&&Bt.length>0){let $=nc(Ot);if($){Ye=!0,it=$.slice(0,120),jt=0,Tt=!1,Kt=0,D(`${p.yellow} \u26A1 Root cause in model analysis: ${it} \u2014 fix phase (read budget: 3)${p.reset}`);let y={role:"user",content:`[SYSTEM] Root cause identified: ${it}. Read only the file that needs fixing, then edit it. Do not read other files.`};q.push(y),_.push(y)}}if(!Bt||Bt.length===0){let $=(Ot||"").trim().length>0||ct.trim().length>0,y=!1;if(ht&&$&&(Hr>=2?D(`${p.yellow} \u26A0 SSH permanently blocked after ${Hr} storm warnings \u2014 no further SSH calls allowed${p.reset}`):(ht=!1,wt=_s-4,y=!0)),y&&$){let A=(Ot||"").trim();if(A.endsWith("?")||/\b(Wo |Bitte |Kannst du|Soll ich)\b/.test(A.slice(-200))){let te={role:"user",content:"[SYSTEM] Continue. Do not ask questions \u2014 implement the fix yourself using SSH. The server is at 94.130.37.43."};_.push(te),q.push(te);continue}}if(!$&&k>0&&Fe<ic-1){let A={role:"user",content:"[SYSTEM] You ran tools but produced no visible output. The user CANNOT see tool results \u2014 only your text. Please summarize your findings now."};_.push(A),q.push(A);continue}let ee=/keine.*Tool|can.?t use.*tool|Tool.?Budget|nicht.*zugreifen|cannot.*access|no.*tool.*access|keine.*Werkzeug|da ich keine.*kann/i;if($&&Fe<3&&ee.test((Ot||"").slice(0,600)))if(uc&&Mn<=0||ht){D(`${p.yellow} \u26A0 Tool avoidance (constrained context) \u2014 telling model to ask user${p.reset}`);let I={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."};_.push(I),q.push(I);continue}else{D(`${p.yellow} \u26A0 Tool avoidance detected \u2014 nudging model to use tools${p.reset}`);let I={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."};_.push(I),q.push(I);continue}if(s.skillLoop&&$&&k>3&&Eo<5){let A=(Ot||ct||"").toLowerCase();if(/\b(i.ll stop|stop the|stopped|done with|complet|summar|conclud|no more|finish|end of|that.s all|final|wrapped up|no further|mindful of|reached.*limit|tool call limit|at this point|recommend keep)/.test(A.slice(-600))){Eo=(Eo||0)+1,D(`${p.yellow} \u26A0 Skill loop: model tried to stop \u2014 continuation nudge #${Eo}${p.reset}`);let te={role:"user",content:"[SYSTEM] Do NOT stop. You are in an autonomous experiment loop. The user is away and expects you to keep running experiments indefinitely until they interrupt with Ctrl+C. Start the next experiment NOW: hypothesize a new change, checkpoint, edit, run, measure, keep or revert. Think harder \u2014 try a completely different optimization approach."};_.push(te),q.push(te);continue}}if($e&&De==="plan"&&nn>=2){D(`${p.cyan} \u21B3 Plan phase: ${nn} consecutive blocks \u2014 auto-advancing to implement${p.reset}`),nn=0;let A=fo("implement","[auto-advance: task only requires direct action]");if(A){q.push(A),_.push(A),Fe=0,Ct=Cn("implement");continue}}if($e&&$){let A=(Ot||ct||"").trim();if(De==="plan"){let I=fo("implement",A);if(I){q.push(I),_.push(I),Fe=0,Ct=Cn("implement");continue}}else if(De==="implement"&&T.size>0){let I=q.find(le=>le.role==="user"),te=typeof I?.content=="string"?I.content:"",F=fo("verify",A,T,te);if(F){q.push(F),_.push(F),Fe=0,Ct=Math.min(Cn("verify")+Math.max(0,(T.size-2)*2),20);continue}}else if(De==="verify"){let te=/\bFAIL\b|test.*fail|error|broken|missing|incorrect/i.test(A.slice(0,500));if(te&&$o<1){$o++;let F={role:"user",content:`[PHASE: RE-IMPLEMENTATION] Verification found issues:
1181
+ ${A.slice(0,400)}
1182
+
1183
+ Fix the identified issues. This is the final attempt.`};De="implement",zt=oc("implement",ys),q.push(F),_.push(F),Fe=0,Ct=Cn("implement"),D(`${p.yellow} \u21B3 Verify \u2192 implement loop-back #${$o} (issues found)${p.reset}`);continue}D(`${p.green} \u2713 Verification phase complete${te?" (loop-back exhausted)":" (PASS)"}${p.reset}`)}}if(wo()&&$&&k===0)if(Kr++,Kr>2)D(`${p.yellow} \u26A0 Plan accepted despite no file reads (rejection loop cap reached)${p.reset}`);else{let A={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.).
1184
+
1185
+ MANDATORY: Use read_file, glob, or grep to investigate the actual codebase first. Read at least the relevant module file and route file before writing the plan.`};q.push(A),_.push(A),D(`${p.yellow} \u26A0 Plan rejected (${Kr}/2): no files read \u2014 forcing investigation${p.reset}`);continue}if(wo()&&$){let A=(Ot||ct||"").trim();E_(A),ax(A);let I=T_(A);if(I.length>0){let te=q.find(B=>B.role==="user"),F=typeof te?.content=="string"?te.content.slice(0,120):"Task";R_(F,I);let le=I.length===1?"step":"steps",j=!1;if(process.stdout.isTTY&&process.stdin.isTTY){let{approvePlan:B,startExecution:W,setPlanMode:z}=qr();process.stdout.write(`
1186
+ ${p.cyan}${p.bold}Plan ready${p.reset} ${p.dim}(${I.length} ${le})${p.reset} ${p.green}[A]${p.reset}${p.dim}pprove${p.reset} ${p.yellow}[E]${p.reset}${p.dim}dit${p.reset} ${p.red}[R]${p.reset}${p.dim}eject${p.reset} ${p.dim}[\u21B5 = approve]:${p.reset} `);let X=process.stdin.isRaw,oe=await new Promise(ue=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",ne=>{try{process.stdin.setRawMode(X||!1)}catch{}let Ne=ne.toString().toLowerCase()[0]||"\r";ue(Ne)})});if(process.stdout.write(`
1187
+ `),oe==="r")console.log(`${p.red}Plan rejected.${p.reset} Ask follow-up questions to refine.`);else if(oe==="e")console.log(`${p.yellow}Type /plan edit to open in editor, or give feedback.${p.reset}`);else if(B()){W(),z(!1),cc(),console.log(`${p.green}${p.bold}Approved!${p.reset} Executing ${I.length} ${le}...`);let ue=`[PLAN APPROVED \u2014 EXECUTE NOW]
1188
+
1189
+ Implement the following plan step by step. All tools are now available.
1190
+
1191
+ ${A}`;q.push({role:"user",content:ue}),_.push({role:"user",content:ue}),j=!0}}else console.log(`
1192
+ ${p.cyan}${p.bold}Plan ready${p.reset} ${p.dim}(${I.length} ${le} extracted).${p.reset} Type ${p.cyan}/plan approve${p.reset}${p.dim} to execute, or ${p.reset}${p.cyan}/plan edit${p.reset}${p.dim} to review.${p.reset}`);if(j){l&&(l.stop(),l=null),Fe--;continue}}else{let te=!1;if(process.stdout.isTTY&&process.stdin.isTTY){let{approvePlan:F,startExecution:le,setPlanMode:j}=qr();process.stdout.write(`
1193
+ ${p.cyan}${p.bold}Plan ready.${p.reset} ${p.green}[A]${p.reset}${p.dim}pprove${p.reset} ${p.red}[R]${p.reset}${p.dim}eject${p.reset} ${p.dim}[\u21B5 = approve]:${p.reset} `);let B=process.stdin.isRaw,W=await new Promise(z=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",X=>{try{process.stdin.setRawMode(B||!1)}catch{}z(X.toString().toLowerCase()[0]||"\r")})});if(process.stdout.write(`
1194
+ `),W==="r")console.log(`${p.red}Plan rejected.${p.reset} Ask follow-up questions to refine.`);else if(F()){le(),j(!1),cc(),console.log(`${p.green}${p.bold}Approved!${p.reset} Executing...`);let X=`[PLAN APPROVED \u2014 EXECUTE NOW]
1195
+
1196
+ Implement the following plan step by step. All tools are now available.
1197
+
1198
+ ${getPlanContent()||At.content}`;q.push({role:"user",content:X}),_.push({role:"user",content:X}),te=!0}}else console.log(`
1199
+ ${p.cyan}${p.bold}Plan ready.${p.reset} ${p.dim}Type ${p.reset}${p.cyan}/plan approve${p.reset}${p.dim} to execute, or ask follow-up questions to refine.${p.reset}`);if(te){l&&(l.stop(),l=null),Fe--;continue}}}if(l&&(l.stop(),l=null),c(null),We(k,N,T,S,J),bt&&T.size>=3){let A=[...T].map(j=>j.split("/").pop()).slice(0,8).join(", "),I=[...T].some(j=>j.endsWith("package.json")),te=[...T].some(j=>j.endsWith("requirements.txt")),F=[...T].some(j=>j.endsWith("package-lock.json")||j.endsWith("yarn.lock")||j.endsWith("pnpm-lock.yaml")),le=I&&!F?"npm install not yet run":te?"pip install not yet run":null;yo=`[Previous session created ${T.size} files: ${A}`+(le?` \u2014 ${le}`:"")+". Use this context to answer follow-up questions without re-reading files.]"}if(bt&&!dc&&k>0){let A=[...T].some(X=>X.endsWith("package.json")),I=[...T].some(X=>X.endsWith("requirements.txt")||X.endsWith("Pipfile")||X.endsWith("pyproject.toml")),te=[...T].some(X=>X.endsWith("package-lock.json")||X.endsWith("yarn.lock")||X.endsWith("pnpm-lock.yaml")),F=q.flatMap(X=>{let oe=Array.isArray(X.tool_calls)?X.tool_calls:[],ue=Array.isArray(X.content)?X.content.filter(ne=>ne?.type==="tool_use"):[];return[...oe,...ue]}).filter(X=>{let oe=X.function?.name||X.name||"";return oe==="bash"||oe==="Bash"}).map(X=>{try{let oe=X.function?.arguments??X.input??{};return(typeof oe=="string"?JSON.parse(oe):oe)?.command||""}catch{return""}}),le=F.some(X=>/pip\s+install|python\s+-m\s+venv/.test(X)),j=F.some(X=>/npm\s+install/.test(X)),W=[...T].some(X=>/\/App\.(js|ts|jsx|tsx)$/.test(X))&&!A&&!j;if(I&&!le||A&&!te&&!j||W){dc=!0;let X=[];I&&!le&&X.push("python -m venv venv && source venv/bin/activate && pip install -r requirements.txt"),W?X.push("create package.json for the React frontend (with react, react-dom, react-scripts dependencies), then run npm install"):A&&!te&&!j&&X.push("npm install");let oe=`[FRAMEWORK \u2014 post-creation check] You wrote dependency files but never ran the installer. Run now: ${X.join(" && ")}. Verify it succeeds, fix any errors, then write a closing summary.`;D(`${p.dim} [post-creation] bootstrapping environment (${X.join(", ")})${p.reset}`),q.push({role:"user",content:oe}),_.push({role:"user",content:oe});continue}}if(k>0&&!s._isSummaryTurn&&m_(Ot))try{D(`${p.dim} [post-turn] terse ending \u2014 requesting diagnosis/summary${p.reset}`);let A=T.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.",I=[..._,{role:"user",content:A}],F=((await Up(I,[],{}))?.content||"").trim();F&&(console.log(`
1200
+ ${F}`),q.push({role:"user",content:A},{role:"assistant",content:F}))}catch{}Be(q),Hp(q);return}k++,oi++,k>=1&&(xe=!1);for(let $ of Bt){let y=$.function.name;N.set(y,(N.get(y)||0)+1)}if(k>=30&&!nh){nh=!0,D(`${p.yellow} \u26A0 Tool budget warning: ${k} tool calls used \u2014 nudging model to wrap up${p.reset}`);let $={role:"user",content:"[SYSTEM] \u26A0 You have used "+k+" tool calls. This is approaching the quality threshold (40). Wrap up NOW: write your final summary and stop. Do NOT run additional verification commands (git status, git diff, git log) \u2014 your changes are already committed and verified. Further tool calls will hurt session quality."};q.push($),_.push($)}let pe=await Promise.all(Bt.map($=>cx($)));{let $=Et(_,Ze()),y=$.percentage,ee=pe.some(F=>F.canExecute&&F.fnName==="read_file"&&!F.args?.line_end),A=pe.filter(F=>F.canExecute&&F.fnName==="read_file"&&F.args?.path&&An(So,F.args.path)>=1&&!F.args?.line_start).map(F=>F.args.path.split("/").slice(-2).join("/")),I=A.length>0;if(y>=70&&ee&&li<70||y>=85&&li<85||I){li=y;let F=y>=85?"URGENT":"WARNING",le;I?(F="WARNING",le=`Full-file read of ${A.join(", ")} already done \u2014 use line_start/line_end for specific sections instead.`):ee?le=`Unbounded read at ${Math.round(y)}% context \u2014 use line_start/line_end to avoid overflow.`:le="Use targeted reads (line_start/line_end) to save space.";let j={role:"user",content:`[SYSTEM ${F}] Context ${Math.round(y)}% used (${$.used}/${$.limit} tokens). ${le}`};if(q.push(j),_.push(j),y>=85){let B=I?` (re-read of: ${A.join(", ")})`:"";D(`${p.yellow} \u26A0 Context ${Math.round(y)}% used \u2014 agent warned to use targeted reads${B}${p.reset}`)}}}let mi=new Map;for(let $ of pe){if(!$.canExecute||$.fnName!=="read_file")continue;let y=$.args?.path;if(!y)continue;let ee=An(So,y),A=mi.get(y)||0,I=ee+A,te=$.args?.line_start!=null,F=Nn.get(y)||0,le=F>0,j=2;if(I>=bs){let B=y.split("/").slice(-2).join("/"),W=(jn.get(y)||0)+1;if(jn.set(y,W),W===1)D(`${p.red} \u2716 Blocked: "${B}" read ${I}\xD7 \u2014 hard cap (${bs}) reached${p.reset}`);else if(W===2){D(`${p.red} \u2716 Escalated block: "${B}" \u2014 model ignored BLOCKED, injecting system warning${p.reset}`);let z={role:"user",content:`[SYSTEM WARNING] You already received a BLOCKED error for read_file("${y}") and tried again anyway. This file has reached its read cap (${bs}\xD7). Do NOT attempt to read it again. Use grep_search to find specific content, or proceed with what you already know.`};q.push(z),_.push(z)}$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 file already read ${I}\xD7 (hard cap: ${bs}). 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(I>=1&&te)if(le&&F<=j){let B=y.split("/").slice(-2).join("/");console.log(`${p.cyan} \u21A9 Targeted re-read: "${B}" (line_start=${$.args.line_start}) \u2014 edit recovery #${F}${p.reset}`),Nn.set(y,F-1)}else if(le&&F>j){let B=y.split("/").slice(-2).join("/");D(`${p.red} \u2716 Edit recovery blocked: "${B}" \u2014 ${j} recovery reads already used. Use grep to find the exact line numbers, then retry.${p.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 edit recovery budget exhausted (${j} 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 B=$.args.line_start||1,W=$.args.line_end||B+350,z=tn.get(y)||[],X=!1;for(let[oe,ue]of z){let ne=Math.max(B,oe),Ne=Math.min(W,ue);if(Ne>ne){let Xe=Ne-ne,xt=W-B||1,lt=ue-oe||1,Wt=Xe/lt>=.7&&Xe/xt<.7;if(!(W-B<=Wh)&&(Xe/xt>=.7||Xe/lt>=.7)){let Fn=y.split("/").slice(-2).join("/"),Uc=`${y}:${B}-${W}`,Bn=(ni.get(Uc)||0)+1;if(ni.set(Uc,Bn),D(Wt?`${p.red} \u2716 Blocked superread: "${Fn}" lines ${B}-${W} subsumes already-read ${oe}-${ue} \u2014 use line_start=${ue+1} to skip known content (block #${Bn})${p.reset}`:`${p.red} \u2716 Blocked duplicate read: "${Fn}" lines ${B}-${W} (\u226570% overlap with lines ${oe}-${ue} already in context, block #${Bn})${p.reset}`),Bn>=2){D(`${p.red} \u2716 Escalated range-block: "${Fn}" lines ${B}-${W} \u2014 model ignored BLOCKED, injecting system warning${p.reset}`);let Hc={role:"user",content:Wt?`[SYSTEM] Read blocked ${Bn}\xD7 for read_file("${y}", lines ${B}-${W}). Lines ${oe}-${ue} were already read. Use line_start=${ue+1} to read only new content, or use grep_search for specific lines.`:`[SYSTEM] Read blocked ${Bn}\xD7 for read_file("${y}", lines ${B}-${W}). Lines ${oe}-${ue} were already read and will NOT change. Use grep_search to find specific content instead.`};q.push(Hc),_.push(Hc)}$.canExecute=!1,$.errorResult={role:"tool",content:Wt?`BLOCKED: read_file("${y}", lines ${B}-${W}) re-reads lines ${oe}-${ue} already in context. Use line_start=${ue+1} to read only the new content beyond line ${ue}.`:`BLOCKED: read_file("${y}", lines ${B}-${W}) is a duplicate \u2014 lines ${oe}-${ue} are already in your context (\u226570% overlap). Use grep to find specific content instead of re-reading.`,tool_call_id:$.callId},X=!0;break}}}if(!X){let oe=z.length,ue=2;if(oe>=3){let Ne=y.split("/").slice(-2).join("/");D(`${p.red} \u2716 Blocked file-scroll: "${Ne}" \u2014 ${oe} sections already read. Use grep to find specific content.${p.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 you have already read ${oe} 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 oe>=ue&&($._scrollWarn={sectionCount:oe+1,path:y})}}else if(I>=1){let B=y.split("/").slice(-2).join("/"),W=(jn.get(y)||0)+1;if(jn.set(y,W),W===1)D(`${p.red} \u2716 Blocked unbounded re-read: "${B}" \u2014 already in context. Use line_start/line_end for specific sections.${p.reset}`);else if(W===2){D(`${p.red} \u2716 Escalated block: "${B}" \u2014 model ignored unbounded re-read block, injecting system warning${p.reset}`);let z={role:"user",content:`[SYSTEM] read_file("${y}") 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.`};q.push(z),_.push(z)}$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 file already in context (read ${I}\xD7). Use line_start/line_end to read a specific section instead of the full file.`,tool_call_id:$.callId}}$.canExecute&&mi.set(y,(mi.get(y)||0)+1)}if(en>=3)for(let $ of pe)$.canExecute&&($.fnName!=="read_file"&&$.fnName!=="edit_file"||(D(`${p.red} \u2716 Blocked ${$.fnName} \u2014 ${en} consecutive file-not-found errors, must search first${p.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: ${en} consecutive "File not found" errors. You must call search_files or glob_files to locate the correct path before reading or editing. Do not guess file paths.`,tool_call_id:$.callId}));for(let $ of pe){if(!$.canExecute||$.fnName!=="bash")continue;let y=($.args?.command||"").trim();if(/^\s*ls(\s+-[a-zA-Z]+)*(\s+\S+)?\s*$/.test(y)&&!/npm|yarn|pnpm|make|git/.test(y)){D(`${p.red} \u2716 Blocked bash ls \u2014 use list_directory tool instead${p.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(y)&&!/git\s|npm\s|yarn\s|-exec\s+\S|-execdir/.test(y)&&(D(`${p.red} \u2716 Blocked bash find \u2014 use glob tool with a pattern instead${p.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 pe)$.canExecute&&($.fnName!=="ssh_exec"&&$.fnName!=="bash"||/\bsed\s+-n\b/.test($.args?.command||"")&&(D(`${p.red} \u2716 Blocked sed -n: use grep -n "pattern" <file> | head -30 instead${p.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 pe){if(!$.canExecute||$.fnName!=="write_file")continue;let y=$.args?.path,ee=$.args?.content||"";if(y)try{let A=require("fs"),I=require("path").resolve(process.cwd(),y);if(A.existsSync(I)){let te=A.statSync(I).size,F=Buffer.byteLength(ee,"utf8"),le=te>0?F/te:1;if(le<.6&&te>200){let j=y.split("/").slice(-2).join("/");console.log(`${p.red} \u2716 write_file shrink guard: "${j}" would shrink to ${Math.round(le*100)}% of original \u2014 likely context loss${p.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: write_file("${y}") denied \u2014 new content is only ${Math.round(le*100)}% of current file size (${te} \u2192 ${F} 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 qc=new Map;for(let $ of pe){if(!$.canExecute||$.fnName!=="grep")continue;let y=$.args?.path;if(!y)continue;let ee=qc.get(y)||0,A=An(Oc,y)+ee;if(A>=Nc){let I=y.split("/").slice(-2).join("/");D(`${p.red} \u2716 Blocked grep: "${I}" grepped ${A}\xD7 with different patterns \u2014 flood threshold exceeded${p.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: grep("${y}") denied \u2014 ${A} patterns already tried. Use existing results or read the file instead.`,tool_call_id:$.callId}}$.canExecute&&qc.set(y,ee+1)}let zh=5,Fc=new Map;for(let $ of pe){if(!$.canExecute||$.fnName!=="ssh_exec")continue;let ee=($.args?.command||"").replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),A=Fc.get(ee)||0,I=An(Ac,ee)+A;I>=zh&&(D(`${p.yellow} \u26A0 Blocked ssh_exec: same command run ${I}\xD7 \u2014 result already in context${p.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: ssh_exec denied \u2014 this command has already run ${I} times and the output is in your context. Use existing results, try a different command, or run it as a local bash call: bash("ssh user@host 'your command'").`,tool_call_id:$.callId}),$.canExecute&&Fc.set(ee,A+1)}if(ht){let $=pe.filter(A=>A.canExecute&&A.fnName==="ssh_exec"),y=pe.some(A=>A.canExecute&&A.fnName!=="ssh_exec"),ee=w&&P<3;if($.length>0&&!y&&ee&&Xr<1)ht=!1,Xr++,wt=Math.max(0,_s-2),D(`${p.dim} [dual-block deadlock: SSH storm relaxed \u2014 allowing 1 SSH call (relax ${Xr}/1)]${p.reset}`);else for(let A of $)A.canExecute=!1,A.errorResult={role:"tool",content:Ye?`BLOCKED: ssh_exec denied \u2014 SSH paused (${_s}+ calls). Root cause is known (${it}). Edit the file now. You can still use bash("ssh user@host 'cmd'") for a single targeted lookup if essential.`:`BLOCKED: ssh_exec denied \u2014 SSH temporarily paused (${_s}+ calls). Provide a text summary of your findings first. Do NOT ask the user to run commands. SSH re-enables after your summary. For one-off lookups use bash("ssh user@host 'cmd'") instead.`,tool_call_id:A.callId}}if(w&&P<3&&!ht){for(let $ of pe)if($.canExecute&&["bash","read_file","find_files"].includes($.fnName)){P++;{let y=Ze(),{messages:ee}=It(_,y);_=ee}D(`${p.yellow} \u26A0 Jarvis-local guard: blocking local ${$.fnName} \u2014 use ssh_exec on 94.130.37.43${p.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(!$e&&Tt&&bt&&Rt>=1){let $=["read_file","grep","search_files","glob","list_directory","find_files"];for(let y of pe)y.canExecute&&$.includes(y.fnName)&&(D(`${p.red} \u2716 Creation hard-block: ${y.fnName} denied \u2014 cap fired, files already written${p.reset}`),y.canExecute=!1,y.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:y.callId})}if(Mn>=0){let $=pe.filter(y=>y.canExecute).length;if($>0&&(Mn-=$,Mn<0))if(!Jr&&T.size>Vr){Jr=!0,Mn=5,D(`${p.green} \u2713 Post-wipe progress detected (${T.size-Vr} files modified) \u2014 granting 5 bonus tool calls${p.reset}`);let y={role:"user",content:"[SYSTEM] Progress detected \u2014 5 bonus tool calls granted. Budget: 5 remaining."};q.push(y),_.push(y)}else{D(`${p.red} \u2716 Post-wipe tool budget exhausted \u2014 blocking all tool calls${p.reset}`);for(let ee of pe)ee.canExecute&&(ee.canExecute=!1,ee.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:ee.callId});let y={role:"user",content:"[SYSTEM] Post-wipe tool budget exhausted. All tool calls are now blocked. Respond with a final summary of what was done and stop \u2014 do not attempt any more tool calls."};q.push(y),_.push(y)}}let Xh=new Set(["edit_file","write_file","bash","ssh_exec","ask_user","spawn_agents","browser_click","browser_fill","browser_open","skill_ar_run_experiment","skill_ar_run_benchmark","skill_ar_checkpoint","skill_ar_revert","skill_ar_log_experiment","skill_ar_extract_metric"]);for(let $ of pe){if(!$.canExecute||Xh.has($.fnName))continue;let y=JSON.stringify($.args||{}),ee=`${$.fnName}|${y}`,A=An(si,ee);A>=2?(D(`${p.red} \u2716 Blocked duplicate: ${$.fnName}(${y.substring(0,80)}) \u2014 called ${A+1}\xD7 with identical args${p.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: ${$.fnName}() with these exact arguments has already been called ${A}\xD7 \u2014 the result is already in your context. Use the existing output instead of repeating the same call.`,tool_call_id:$.callId}):A===1&&D(`${p.yellow} \u26A0 Duplicate tool call: ${$.fnName}(${y.substring(0,80)}) \u2014 2nd call with identical args${p.reset}`),On(si,ee)}let xs=l?{skipSpinner:!0,skipSummaries:!0}:{},Vh=pe.some($=>$.fnName==="ask_user"),Bc=!xs.skipSummaries&&!xe,Ao=null;Bc&&!Vh?(xe=!0,xs.skipSpinner=!0,process.stdout.isTTY?(process.stdout.write(Wr(pe,k,!1,"blink")),Ao=!0):qt||process.stdout.write(Wr(pe,k,!1)+`
1201
+ `)):Bc&&(xe=!0,xs.skipSpinner=!0),l&&l._paused&&l.resume();let Oo=null;if(Ao&&process.stdout.isTTY&&pe.some(y=>y.canExecute&&(y.fnName==="bash"||y.fnName==="ssh_exec"))){let y=Date.now();Oo=setInterval(()=>{let ee=Math.round((Date.now()-y)/1e3);ee>=3&&process.stdout.write(`\r\x1B[2K${Wr(pe,k,!1,"blink")} ${p.dim}[${ee}s]${p.reset}`)},1e3)}let{results:Nt,summaries:Jh}=await fx(pe,!0,{...xs,skipSummaries:!0});if(Oo&&(clearInterval(Oo),Oo=null),Ao&&(Ao=null,process.stdout.write(`\r\x1B[2K${Wr(pe,k,!1)}
1202
+ `)),!xs.skipSummaries){let $=Jh.filter((A,I)=>!(pe[I]&&pe[I].fnName==="ask_user"));for(let A of $)console.log(A);console.log("");let y=pe.filter(A=>A&&A.fnName!=="ask_user").map(A=>A.fnName),ee=Re.record(0,y,S,T);ee&&H_(ee)}for(let $ of pe){if($.canExecute||!$.errorResult)continue;let y=typeof $.errorResult.content=="string"?$.errorResult.content:"";if((y.startsWith("BLOCKED:")||y.startsWith("PLAN MODE:"))&&(on++,on>=Mc)){D(`${p.red} \u2716 Loop abort: ${on} consecutive blocked calls (pre-execution) \u2014 model not heeding BLOCKED messages${p.reset}`),l&&(l.stop(),l=null),c(null),We(k,N,T,S,J,{suppressHint:!0}),Be(q);return}}for(let $=0;$<pe.length;$++){let y=pe[$];if(!y.canExecute)continue;let ee=Nt[$].content,A=ee.split(`
1203
+ `)[0],I=!A.startsWith("ERROR")&&!A.startsWith("CANCELLED")&&!A.startsWith("Command failed")&&!A.startsWith("EXIT");if(!I&&(y.fnName==="edit_file"||y.fnName==="patch_file")&&y.args?.path&&A.includes("old_text not found")){let j=Nn.get(y.args.path)||0;Nn.set(y.args.path,j+1)}if(!I&&(y.fnName==="read_file"||y.fnName==="edit_file")&&/file not found|does not exist|ENOENT/i.test(A)){if(en++,en>=2){D(`${p.yellow} \u26A0 File-not-found streak: ${en} consecutive misses \u2014 forcing search${p.reset}`);let j={role:"user",content:`[SYSTEM] ${en} consecutive "File not found" errors. STOP guessing paths. Use search_files or glob_files to locate the correct file first, then read/edit the path returned by the search.`};q.push(j),_.push(j)}}else I&&(y.fnName==="read_file"||y.fnName==="edit_file"||y.fnName==="search_files"||y.fnName==="glob_files")&&(en=0);if(I&&y.fnName==="write_file"&&y.args?.path){let j=y.args.path.split("/").pop(),B=y.args.path.includes("/tests/")||y.args.path.includes("\\tests\\");if(/^(test_|demo_|temp_|tmp_|scratch_)/.test(j)&&!B){D(`${p.yellow} \u26A0 Temp file: "${j}" \u2014 delete with bash rm when done to keep the workspace clean${p.reset}`);let z={role:"user",content:`[HINT] "${y.args.path}" looks like a temporary test/demo file. Delete it with bash("rm ${y.args.path}") as soon as you're done \u2014 orphaned temp files count against session quality.`};q.push(z),_.push(z)}}if(I&&["write_file","edit_file","patch_file"].includes(y.fnName)&&y.args&&y.args.path){Nn.delete(y.args.path),T.add(y.args.path);let j=On(Ce,y.args.path),B=y.args.path.split("/").slice(-2).join("/");if(j===Th){D(`${p.yellow} \u26A0 Loop warning: "${B}" edited ${j}\xD7 \u2014 possible edit loop${p.reset}`);let W={role:"user",content:`[SYSTEM WARNING] "${y.args.path}" edited ${j}\xD7. One more edit max, then move on.`};q.push(W),_.push(W)}else if(j>=Rh){D(`${p.red} \u2716 Loop abort: "${B}" edited ${j}\xD7 \u2014 aborting to prevent runaway loop${p.reset}`),l&&(l.stop(),l=null),c(null),We(k,N,T,S,J,{suppressHint:!0}),Be(q);return}}if(I&&y.canExecute&&$e&&(nn=0),I&&y.canExecute&&!($e&&De==="plan")){let j=["read_file","grep","search_files","glob","list_directory","ssh_exec","find_files"];["write_file","edit_file","patch_file"].includes(y.fnName)?(jt=0,Tt=!1,Kt=0,Rt++):j.includes(y.fnName)&&(jt++,Tt&&Kt++);let W=n.postEditCap,z=$e&&De==="implement"?Math.min(Lc,6):Lc,X=Ye?3:bt?Rt>0?2:4:Rt>0?W:z,oe=3;if(!$e&&Tt&&(Ye||bt&&Rt>=1||Kt>=oe)&&j.includes(y.fnName)){let ne=Ye?`root cause already identified (${it})`:Kt>=oe?`${jt} consecutive reads without an edit`:`${Rt} file edit(s) already made`;D(`${p.red} \u2716 Blocked read-only tool: cap fired, ${ne}${p.reset}`),y.canExecute=!1,y.errorResult={role:"tool",content:Ye?`BLOCKED: root cause already identified (${it}). Use edit_file to fix the issue \u2014 do not read more files.`:bt?"BLOCKED: files already written \u2014 continue with write_file or edit_file to finish the remaining tasks. Do not read more files.":Kt>=oe?`BLOCKED: You have read ${jt} files without making any edits. Stop investigating and either implement a fix with edit_file/write_file, or write your diagnosis as text output. Do not read more files.`:`BLOCKED: ${Rt} 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:y.callId}}else if(jt>=X&&!Tt){if(Tt=!0,D(`${p.yellow} \u26A0 Investigation cap: ${jt} read-only calls without an edit \u2014 forcing implementation${p.reset}`),$e&&De==="plan"){let Xe=[..._].reverse().find(Wt=>Wt.role==="assistant"),xt=typeof Xe?.content=="string"?Xe.content:"",lt=fo("implement",xt);lt&&(q.push(lt),_.push(lt),Fe=0,Ct=Cn("implement"))}let ne;Ye?ne=`[SYSTEM] Root cause was already identified (${it}). Edit the file now \u2014 do not read more files.`:ht?ne="[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.":ne="[SYSTEM] You have read enough files. Now implement your fix using edit_file.";let Ne={role:"user",content:ne};q.push(Ne),_.push(Ne)}}if((y.fnName==="bash"||y.fnName==="ssh_exec")&&y.args&&y.args.command){let j=y.args.command.replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),B=On(Ac,j);if(B===Ch){D(`${p.yellow} \u26A0 Loop warning: same bash command run ${B}\xD7 \u2014 possible debug loop${p.reset}`);let W={role:"user",content:`[SYSTEM WARNING] Same bash command ${B}\xD7. Debug loop detected \u2014 try a different approach.`};q.push(W),_.push(W)}else if(B>=Ah){D(`${p.red} \u2716 Loop abort: same bash command run ${B}\xD7 \u2014 aborting runaway debug loop${p.reset}`),l&&(l.stop(),l=null),c(null),We(k,N,T,S,J,{suppressHint:!0}),Be(q);return}}if(y.fnName==="ssh_exec"){wt++;{let W=(Nt[$]?.content??"").split(`
1204
+ `).map(z=>z.trim()).find(z=>z.length>0&&!z.startsWith("**")&&(z.startsWith("EXIT")||/^[\w./-]+:\s/.test(z)||z.startsWith("bash:")||z.startsWith("sh:")))??"";if(W){if(W===Zr?Ln++:(Zr=W,Ln=1),Ln===3&&!ht){D(`${p.yellow} \u26A0 SSH repeated-error: "${W.slice(0,60)}" returned ${Ln}\xD7 \u2014 nudging to change approach${p.reset}`);let z={role:"user",content:`[SYSTEM WARNING] The last ${Ln} SSH commands all failed with the same error: "${W}". Retrying variants of the same command will not help. Switch to a different approach to accomplish the task (e.g. use a different tool, read a local file, or change the command syntax entirely).`};q.push(z),_.push(z)}}else Zr="",Ln=0}if(wt>=Kh){D(`${p.red} \u2716 SSH storm abort: ${wt} consecutive ssh_exec calls \u2014 aborting${p.reset}`),l&&(l.stop(),l=null),c(null),We(k,N,T,S,J,{suppressHint:!0}),Be(q);return}else if(wt===_s){{let W=Ze(),{messages:z}=It(_,W);_=z}ht=!0,Hr++,D(`${p.yellow} \u26A0 SSH storm warning (#${Hr}): ${wt} consecutive ssh_exec calls \u2014 blocking further SSH${p.reset}`);let B={role:"user",content:Ye?`[SYSTEM WARNING] ${wt} consecutive SSH calls. Root cause identified (${it}). Read the file that needs fixing, then edit it.`:`[SYSTEM WARNING] ${wt} 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.`};q.push(B),_.push(B)}}else y.canExecute&&(wt=0);if(y.fnName==="bash"&&y.canExecute){let W=(Nt[$]?.content??"").split(`
1205
+ `).map(z=>z.trim()).find(z=>z.length>0&&(z.startsWith("EXIT")||/^[\w./-]+:\s/.test(z)||z.startsWith("bash:")||z.startsWith("sh:")))??"";if(W){if(W===Qr?Pn++:(Qr=W,Pn=1),Pn===3){D(`${p.yellow} \u26A0 Bash repeated-error: "${W.slice(0,60)}" returned ${Pn}\xD7 \u2014 nudging to change approach${p.reset}`);let z={role:"user",content:`[SYSTEM WARNING] The last ${Pn} bash commands all failed with the same error: "${W}". Retrying variants of the same command will not help. Switch to a completely different approach (e.g. use a different tool, change the command syntax, or use ssh_exec to run the command on the remote server instead).`};q.push(z),_.push(z)}}else Qr="",Pn=0}if(y.fnName==="bash"&&y.canExecute&&!sc&&y.args?.command){let j=Nt[$]?.content??"";if(/git\s+commit\b/.test(y.args.command)&&!j.startsWith("EXIT")&&!j.startsWith("ERROR")&&(/\[\S+\s+[a-f0-9]+\]/.test(j)||j.includes("files changed")||j.includes("file changed")||j.includes("insertions(+)")||j.includes("create mode"))){sc=!0,uo=0,D(`${p.green} \u2713 Git commit detected \u2014 post-commit verification cap active (max 2 git status/diff/log)${p.reset}`);let z={role:"user",content:"[SYSTEM] \u2713 Git commit succeeded. Your changes are committed. Do NOT run further git status / git diff / git log calls \u2014 the commit is done. Write your final summary and stop. Running extra verification commands wastes tool calls and hurts session quality."};q.push(z),_.push(z)}}if(sc&&y.fnName==="bash"&&y.args?.command&&/git\s+(status|diff|log|show)\b/.test(y.args.command)&&(uo++,uo>2)){D(`${p.yellow} \u26A0 Post-commit git verification blocked (call ${uo})${p.reset}`);let B={role:"user",content:"[SYSTEM] \u26A0 STOP: You already ran "+(uo-1)+" git verification commands after committing. The commit is confirmed. Write your final summary NOW and do not make any more tool calls."};q.push(B),_.push(B)}if(I&&y.fnName==="grep"&&y.args&&y.args.pattern){let j=`${y.args.pattern}|${y.args.path||""}`,B=On(Oh,j);if(B===Nh){D(`${p.yellow} \u26A0 Loop warning: grep pattern "${y.args.pattern.slice(0,40)}" run ${B}\xD7 \u2014 possible search loop${p.reset}`);let W={role:"user",content:`[SYSTEM WARNING] Same grep pattern ${B}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};q.push(W),_.push(W)}else if(B>=Mh){D(`${p.red} \u2716 Loop abort: grep pattern run ${B}\xD7 \u2014 aborting runaway search loop${p.reset}`),l&&(l.stop(),l=null),c(null),We(k,N,T,S,J,{suppressHint:!0}),Be(q);return}if(y.args.path){let W=On(Oc,y.args.path),z=An(So,y.args.path)>=1;if(W===(z?1:Lh)){let oe=y.args.path.split("/").slice(-2).join("/");D(`${p.yellow} \u26A0 Loop warning: "${oe}" grepped ${W}\xD7 with different patterns \u2014 context flood risk${p.reset}`);let ue={role:"user",content:z?`[SYSTEM NOTE] "${y.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] "${y.args.path}" grepped ${W}\xD7 \u2014 use the search results already in context instead of searching again.`};q.push(ue),_.push(ue)}}}if(I&&(y.fnName==="glob"||y.fnName==="glob_files"||y.fnName==="search_files")&&y.args){let j=y.args.pattern||y.args.query||y.args.path||"",B=On(Ph,j);if(B===Ih){D(`${p.yellow} \u26A0 Loop warning: glob pattern "${j.slice(0,40)}" run ${B}\xD7 \u2014 possible search loop${p.reset}`);let z={role:"user",content:`[SYSTEM WARNING] Same glob/search pattern ${B}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};q.push(z),_.push(z)}else if(B>=jh){D(`${p.red} \u2716 Loop abort: glob pattern run ${B}\xD7 \u2014 aborting runaway search loop${p.reset}`),l&&(l.stop(),l=null),c(null),We(k,N,T,S,J,{suppressHint:!0}),Be(q);return}let W=j.replace(/\*+/g," ").replace(/[{}()\[\],.\/\\]/g," ").split(/\s+/).filter(z=>z.length>=4&&!/^\.(js|ts|py|json|md|yaml|yml|txt|css|html|sh)$/.test(z));for(let z of W){let X=z.toLowerCase();_o.has(X)||_o.set(X,new Set);let oe=_o.get(X);if(oe.add(j),oe.size===qh){D(`${p.red} \u2716 Glob core-term block: ${oe.size} different patterns all searching for "${X}" \u2014 search loop${p.reset}`);let ue={role:"user",content:`[SYSTEM WARNING] You have searched for "${X}" using ${oe.size} different glob patterns. This is a search loop \u2014 the file you are looking for likely does not exist. Stop searching and work with the files you have already found, or ask the user for clarification.`};q.push(ue),_.push(ue)}else if(oe.size===Dh){D(`${p.yellow} \u26A0 Glob core-term warning: ${oe.size} different patterns searching for "${X}"${p.reset}`);let ue={role:"user",content:`[SYSTEM WARNING] ${oe.size} different glob patterns all target "${X}". If previous searches returned no results, the file probably does not exist \u2014 stop searching and proceed with available information.`};q.push(ue),_.push(ue)}}}let te=(y.args?.command||y.args?.cmd||y.args?.script||"").toLowerCase(),F=/\b(health|healthcheck|health-check|status|check|ping|validate|alive|ready)\b/.test(te)||/\/(health|status|ping|ready|alive)\b/.test(te);if(I&&(y.fnName==="bash"||y.fnName==="ssh_exec")&&F&&ee.includes('"valid":true')){{let B=Ze();if(Et(_,B).percentage>=60){let{messages:z,tokensRemoved:X}=It(_,B);X>0&&(_=z,console.log(`${p.dim} [pre-stop-compress \u2014 ~${X} tokens freed before STOP injection, now ${Math.round(Et(_,B).percentage)}%]${p.reset}`))}}let j={role:"user",content:'[SYSTEM STOP] Tool result contains {"valid":true}. The token/service is valid and reachable. STOP all further investigation immediately. Report to the user that the token is valid, the service is healthy, and no fix is needed. Do NOT read any more log files.'};q.push(j),_.push(j),console.log(`${p.cyan} \u2713 Health-check stop signal detected \u2014 injecting STOP instruction${p.reset}`)}if(ee.startsWith("BLOCKED:")){if(on++,on>=Mc){D(`${p.red} \u2716 Loop abort: ${on} consecutive blocked calls \u2014 model not heeding BLOCKED messages${p.reset}`),l&&(l.stop(),l=null),c(null),We(k,N,T,S,J,{suppressHint:!0}),Be(q);return}}else on=0;if(I)sn=0,di=!0;else if(sn++,sn===Uh){D(`${p.yellow} \u26A0 Loop warning: ${sn} consecutive tool errors \u2014 possible stuck loop${p.reset}`);let j={role:"user",content:`[SYSTEM WARNING] ${sn} consecutive errors. Stuck loop \u2014 try fundamentally different approach or declare done.`};q.push(j),_.push(j)}else if(sn>=Hh){D(`${p.red} \u2716 Loop abort: ${sn} consecutive errors \u2014 aborting stuck loop${p.reset}`),l&&(l.stop(),l=null),c(null),We(k,N,T,S,J,{suppressHint:!0}),Be(q);return}if(I&&y.fnName==="read_file"&&y.args&&y.args.path){S.add(y.args.path);let j=On(So,y.args.path);if(y.args.line_start!=null){let X=y.args.line_start||1,oe=y.args.line_end||X+350;tn.has(y.args.path)||tn.set(y.args.path,[]),tn.get(y.args.path).push([X,oe])}if(y._scrollWarn){let{sectionCount:X,path:oe}=y._scrollWarn,ue={role:"user",content:`[SYSTEM WARNING] "${oe}" \u2014 you have now read ${X} different sections of this file. This is a file-scroll pattern. Stop reading sections and use grep_search to find the specific lines you need instead.`};q.push(ue),_.push(ue),D(`${p.yellow} \u26A0 Scroll warning: "${oe.split("/").slice(-2).join("/")}" \u2014 ${X} sections read \u2014 use grep instead${p.reset}`)}let B=y.args.path.split("/").slice(-2).join("/"),W=!y.args?.line_start&&!y.args?.line_end,z=$e&&De==="plan";if(!z&&W&&j===Fh){{let oe=Ze();if(Et(_,oe).percentage>=60){let{messages:ne}=It(_,oe);_=ne}}D(`${p.yellow} \u26A0 Loop warning: "${B}" read unbounded ${j}\xD7 \u2014 use line_start/line_end${p.reset}`);let X={role:"user",content:`[SYSTEM WARNING] "${y.args.path}" read ${j}\xD7 without line ranges. Use line_start/line_end to read specific sections \u2014 do not re-read the full file.`};q.push(X),_.push(X)}else if(!z&&W&&j>=Bh){D(`${p.red} \u2716 Loop abort: "${B}" read unbounded ${j}\xD7 \u2014 aborting runaway read loop${p.reset}`),l&&(l.stop(),l=null),c(null),We(k,N,T,S,J,{suppressHint:!0}),Be(q);return}}if(y.fnName==="spawn_agents"){let j=(ee.match(/\bStatus: done\b/g)||[]).length;if((ee.match(/\bStatus: truncated\b/g)||[]).length>0&&j===0){if(rn++,rn===Gh){D(`${p.yellow} \u26A0 Swarm warning: all sub-agents hit iteration limit ${rn}\xD7 in a row${p.reset}`);let W={role:"user",content:`[SYSTEM WARNING] Sub-agents truncated ${rn}\xD7 in a row. Stop spawning \u2014 try different approach or report findings.`};q.push(W),_.push(W)}else if(rn>=Yh){console.log(`${p.red} \u2716 Swarm abort: all sub-agents hit iteration limit ${rn}\xD7 \u2014 aborting stuck swarm${p.reset}`),l&&(l.stop(),l=null),c(null),We(k,N,T,S,J,{suppressHint:!0}),Be(q);return}}else j>0&&(rn=0)}}for(let $ of Nt)q.push($),_.push($);if(!Ye)for(let $=0;$<Nt.length;$++){if(!pe[$]||pe[$].fnName!=="ssh_exec")continue;let y=Nt[$];if(!y||typeof y.content!="string")continue;let ee=nc(y.content);if(ee){Ye=!0,it=ee.slice(0,120),jt=0,Tt=!1,Kt=0,D(`${p.yellow} \u26A1 Root cause detected: ${it} \u2014 fix phase (read budget: 3)${p.reset}`);let A={role:"user",content:`[SYSTEM] Root cause identified: ${it}. Read only the file that needs fixing, then edit it. Do not read other files.`};q.push(A),_.push(A);break}}for(let $=0;$<Nt.length;$++){let y=pe[$];if(!y)continue;let ee=typeof Nt[$]?.content=="string"?Nt[$].content:"";if(y.fnName==="create_task"){let A=ee.match(/Task #(\d+) created/),I=typeof y.args?.subject=="string"?y.args.subject:"";A&&I&&xo.set(A[1],I)}else if((y.fnName==="write_file"||y.fnName==="edit_file")&&!ee.startsWith("BLOCKED:")&&ee.trim().length>0){let I=(typeof y.args?.path=="string"?y.args.path:typeof y.args?.file_path=="string"?y.args.file_path:"").split("/").pop().toLowerCase(),te=I.split(/[._\-/]/).filter(F=>F.length>2);for(let[F,le]of xo){if(ko.has(F))continue;let j=le.toLowerCase().split(/\W+/).filter(W=>W.length>3);te.filter(W=>j.some(z=>z.includes(W)||W.includes(z))).length>=1&&(ko.add(F),D(`${p.green} \u2714 Auto-matched task #${F} to ${I}: ${le.slice(0,60)}${p.reset}`))}}}{let $=Ze();if(Et(_,$).percentage>=78){let{messages:ee,tokensRemoved:A}=It(_,$);A>0&&(_=ee,console.log(`${p.dim} [auto-compressed \u2014 ~${A} tokens freed, now ${Math.round(Et(_,$).percentage)}%]${p.reset}`))}}let Wc=hx();if(Wc){let $={role:"user",content:`[User note mid-run]: ${Wc}`};q.push($),_.push($),console.log(`${p.cyan} \u270E Context added${p.reset}`)}}if(Fe>=Ct){if(l&&(l.stop(),l=null),c(null),We(k,N,T,S,J),Be(q),Hp(q),$e&&De==="plan"){let Dn=[...q].reverse().find(ze=>ze.role==="assistant"),ct=typeof Dn?.content=="string"?Dn.content:"",qn=fo("implement",ct);if(qn){q.push(qn),_=[{role:"system",content:await hc()},...q],Ct=Cn("implement"),D(`${p.yellow} \u26A0 Plan budget exhausted \u2014 auto-transitioning to implement${p.reset}`);continue e}}else if($e&&De==="verify"){D(`${p.yellow} \u26A0 Verify budget exhausted \u2014 completing session${p.reset}`);break e}let{getActiveProviderName:be}=He();if(be()==="ollama"&&ui<Pc){if(T.size===0&&!di){console.log(`${p.yellow} \u26A0 Max iterations reached with no progress. Stopping.${p.reset}`);break e}ui++,Ct=20,console.log(`${p.dim} \u2500\u2500 auto-extending (+20 turns, ext ${ui}/${Pc}) \u2500\u2500${p.reset}`);continue e}if(console.log(`
1206
+ ${p.yellow}\u26A0 Max iterations reached.${p.reset}`),await oh(" Continue for 20 more turns?")){Ct=20;continue e}console.log(`${p.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${p.reset}`)}break e}}dh.exports={processInput:Sx,clearConversation:yx,getConversationLength:wx,getConversationMessages:bx,setConversationMessages:_x,setAbortSignalGetter:X_,setMaxIterations:z_,invalidateSystemPromptCache:cc,clearToolFilterCache:sx,getCachedFilteredTools:ah,buildSystemPrompt:hc,getProjectContextHash:ch,buildUserContent:ih,detectAndTruncateLoop:rc,injectMidRunNote:px,resetSessionTracking:uh}});var He=se((kv,yh)=>{var{OllamaProvider:Ex}=fl(),{OpenAIProvider:Tx}=gl(),{AnthropicProvider:Rx}=bl(),{GeminiProvider:Cx}=vl(),{LocalProvider:Ax}=Tl(),{checkBudget:Ox}=zo(),kc={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"}},_c=(process.env.OLLAMA_FALLBACK_CHAIN||"").split(",").map(t=>t.trim()).filter(Boolean),hh={};for(let[t,e]of Object.entries(kc))for(let s of Object.values(e))hh[s]=t;function xc(t,e){let s=hh[t];return s&&kc[s][e]||t}var Ke={},at=null,qe=null,vo=[];function _t(){if(Object.keys(Ke).length>0)return;$s("ollama",new Ex),$s("openai",new Tx),$s("anthropic",new Rx),$s("gemini",new Cx),$s("local",new Ax);let t=process.env.DEFAULT_PROVIDER||"ollama",e=process.env.DEFAULT_MODEL||null;Ke[t]?(at=t,qe=e||Ke[t].defaultModel):(at="ollama",qe="kimi-k2.5");let s=process.env.FALLBACK_CHAIN;s&&(vo=s.split(",").map(n=>n.trim()).filter(Boolean))}function $s(t,e){Ke[t]=e}function Nx(t){return _t(),Ke[t]||null}function vc(){return _t(),Ke[at]||null}function Mx(){return _t(),at}function Lx(){return _t(),qe}function Px(){_t();let t=vc();if(!t)return{id:qe,name:qe,provider:at};let e=t.getModel(qe);return e?{...e,provider:at}:{id:qe,name:qe,provider:at}}function mh(t){if(!t)return{provider:null,model:null};let e=t.indexOf(":");if(e>0){let s=t.slice(0,e);if(Ke[s]||["ollama","openai","anthropic","gemini","local"].includes(s))return{provider:s,model:t.slice(e+1)}}return{provider:null,model:t}}function Ix(t){_t();let{provider:e,model:s}=mh(t);if(e){let o=Ke[e];return o&&(o.getModel(s)||e==="local"||e==="ollama")?(at=e,qe=s,ri(),!0):!1}let n=vc();if(n&&n.getModel(s))return qe=s,ri(),!0;for(let[o,r]of Object.entries(Ke))if(r.getModel(s))return at=o,qe=s,ri(),!0;return!1}function ri(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=fh();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=Pt();t()}catch{}}function jx(){_t();let t=new Set;for(let e of Object.values(Ke))for(let s of e.getModelNames())t.add(s);return Array.from(t)}function Dx(){return _t(),Object.entries(Ke).map(([t,e])=>({provider:t,configured:e.isConfigured(),models:Object.values(e.getModels()).map(s=>({...s,active:t===at&&s.id===qe}))}))}function qx(){_t();let t=[];for(let[e,s]of Object.entries(Ke)){let n=s.isConfigured();for(let o of Object.values(s.getModels()))t.push({spec:`${e}:${o.id}`,name:o.name,provider:e,configured:n})}return t}function Fx(t){vo=Array.isArray(t)?t:[]}function Bx(){return[...vo]}function ph(t){let e=t.message||"",s=t.code||"";return!!(e.includes("429")||e.includes("500")||e.includes("502")||e.includes("503")||e.includes("504")||s==="ECONNABORTED"||s==="ETIMEDOUT"||s==="ECONNREFUSED"||s==="ECONNRESET"||s==="EHOSTUNREACH"||s==="ENETUNREACH"||s==="EPIPE"||s==="ERR_SOCKET_CONNECTION_TIMEOUT"||e.includes("socket disconnected")||e.includes("TLS")||e.includes("ECONNRESET")||e.includes("ECONNABORTED")||e.includes("network")||e.includes("ETIMEDOUT"))}async function gh(t){let e=[at,...vo.filter(r=>r!==at)],s,n=0,o=0;for(let r=0;r<e.length;r++){let i=e[r],a=Ke[i];if(!a||!a.isConfigured())continue;o++;let c=Ox(i);if(!c.allowed){n++,s=new Error(`Budget limit reached for ${i}: $${c.spent.toFixed(2)} / $${c.limit.toFixed(2)}`);continue}try{let l=r>0,u=l?xc(qe,i):qe;return l&&u!==qe&&process.stderr.write(` [fallback: ${i}:${u}]
1207
+ `),await t(a,i,u)}catch(l){if(s=l,!ph(l)||r>=e.length-1)throw l;if(i==="ollama"&&_c.length>0){let u=isFallback?xc(qe,i):qe;for(let d of _c)if(d!==u)try{return process.stderr.write(` [ollama fallback: ${d}]
1208
+ `),await t(a,i,d)}catch(f){if(s=f,!ph(f))throw f}}continue}}throw n>0&&n===o?new Error("All providers are over budget. Use /budget to check limits or /budget <provider> off to remove a limit."):o===0?new Error("No configured provider available"):s||new Error("No configured provider available")}async function Wx(t,e,s={}){return _t(),gh((n,o,r)=>n.stream(t,e,{model:r,signal:s.signal,...s}))}async function Ux(t,e,s={}){if(_t(),s.provider){let n=Ke[s.provider];if(!n||!n.isConfigured())throw new Error(`Provider '${s.provider}' is not available`);let o={model:s.model||qe,...s};try{return await n.chat(t,e,o)}catch(r){if(typeof n.stream=="function")try{return await n.stream(t,e,{...o,onToken:()=>{}})}catch{}throw r}}return gh(async(n,o,r)=>{try{return await n.chat(t,e,{model:r,...s})}catch(i){if(typeof n.stream=="function")try{return await n.stream(t,e,{model:r,...s,onToken:()=>{}})}catch{}throw i}})}function Hx(){_t();let t=[];for(let[e,s]of Object.entries(Ke))s.isConfigured()&&t.push({name:e,models:Object.values(s.getModels())});return t}function Gx(){for(let t of Object.keys(Ke))delete Ke[t];at=null,qe=null,vo=[]}yh.exports={registerProvider:$s,getProvider:Nx,getActiveProvider:vc,getActiveProviderName:Mx,getActiveModelId:Lx,getActiveModel:Px,setActiveModel:Ix,getModelNames:jx,parseModelSpec:mh,listProviders:Dx,listAllModels:qx,callStream:Wx,callChat:Ux,getConfiguredProviders:Hx,setFallbackChain:Fx,getFallbackChain:Bx,resolveModelForProvider:xc,MODEL_EQUIVALENTS:kc,OLLAMA_FALLBACK_MODELS:_c,_reset:Gx}});var{C:G}=Ue(),Yx=He(),{TOOL_DEFINITIONS:$h}=Jn(),{saveRoutingConfig:Kx}=ls(),Tc=[{id:"read-package",category:"file-ops",prompt:"Read the file package.json and show me its contents.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("package.json")},{id:"write-file",category:"file-ops",prompt:'Create a file at /tmp/nex-bench-test.txt with the content "benchmark run".',expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&typeof t.content=="string"},{id:"edit-file",category:"file-ops",prompt:'In the file src/config.js, replace the string "debug: false" with "debug: true".',expectedTool:["edit_file","patch_file"],validateArgs:t=>!!(t.path&&t.old_string!==void 0&&t.new_string!==void 0||t.path&&Array.isArray(t.patches)&&t.patches.length>0)},{id:"list-directory",category:"file-ops",prompt:"Show me all files and folders in the cli/ directory.",expectedTool:["list_directory","glob"],validateArgs:t=>!!(typeof t.path=="string"&&t.path.includes("cli")||typeof t.pattern=="string"&&t.pattern.includes("cli"))},{id:"glob-js-files",category:"file-ops",prompt:"Find all JavaScript files (*.js) recursively in the cli/ directory.",expectedTool:"glob",validateArgs:t=>typeof t.pattern=="string"&&t.pattern.includes(".js")},{id:"search-constant",category:"search",prompt:'Search for the string "DEFAULT_MODEL" across all files in the project.',expectedTool:["search_files","grep"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("DEFAULT_MODEL")},{id:"grep-function-def",category:"search",prompt:'Find where the function "callStream" is defined in the codebase.',expectedTool:["grep","search_files"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("callStream")},{id:"search-todos",category:"search",prompt:"Find all TODO comments in the source code.",expectedTool:["grep","search_files","bash"],validateArgs:t=>JSON.stringify(t).toUpperCase().includes("TODO")},{id:"git-branch",category:"shell",prompt:"What git branch am I currently on?",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("git")},{id:"git-status",category:"shell",prompt:"Show me the current git status of the repository.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("git status")},{id:"npm-install",category:"shell",prompt:"Run npm install to install project dependencies.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("npm")},{id:"schema-strict",category:"schema",prompt:"Read the file README.md",expectedTool:"read_file",validateArgs:(t,e)=>{let s=e?.function?.parameters||{},n=s.required||[],o=Object.keys(s.properties||{});return n.every(r=>t[r]!==void 0)&&Object.keys(t).every(r=>o.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:"data-find-schema",category:"data",prompt:"Find where the database schema or models are defined in this project.",expectedTool:["grep","glob"],validateArgs:t=>!!(t.pattern&&/schema|model|migration/i.test(t.pattern)||t.pattern&&/schema|model|migration/i.test(t.pattern))},{id:"data-write-query",category:"data",prompt:"Write a SQL query to find all users who registered in the last 30 days and save it to queries/recent-users.sql.",expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes(".sql")},{id:"data-read-env",category:"data",prompt:"Read the .env file to find the database connection string.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&/\.env|env\./i.test(t.path)},{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}],wh=[{id:"phase-plan-diagnosis",category:"phase-plan",prompt:"The server returns 500 on /api/users. The error log shows: TypeError: Cannot read property 'map' of undefined at routes/users.js:42. Read the relevant file to diagnose the root cause.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&/users/i.test(t.path)},{id:"phase-plan-search",category:"phase-plan",prompt:"We're getting CORS errors in production. Search the codebase for where CORS middleware is configured.",expectedTool:"grep",validateArgs:t=>typeof t.pattern=="string"&&/cors/i.test(t.pattern)},{id:"phase-plan-context",category:"phase-plan",prompt:"The login page shows a blank screen after the last deploy. Check git log for recent changes that might have broken it.",expectedTool:"git_log",validateArgs:()=>!0},{id:"phase-verify-test",category:"phase-verify",prompt:"The file src/utils.js was modified to fix a null pointer bug. Run the test suite to verify the fix works correctly.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&/test|jest|npm\s+test|pytest|mocha/.test(t.command)},{id:"phase-verify-read",category:"phase-verify",prompt:"A patch was applied to config/database.js to fix the connection pool. Read the file to verify the changes look correct.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&/database/i.test(t.path)},{id:"phase-verify-lint",category:"phase-verify",prompt:"Code was modified in src/components/Header.tsx. Run the linter to check for any style violations.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&/lint|eslint|prettier|tsc/.test(t.command)},{id:"phase-plan-git-blame",category:"phase-plan",prompt:"A production bug was introduced 2 days ago. Use git log to find commits from the last 2 days to identify what changed.",expectedTool:"git_log",validateArgs:()=>!0},{id:"phase-plan-error-trace",category:"phase-plan",prompt:"The error stack trace mentions src/middleware/auth.js line 87. Read the file around that line to understand the bug.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&/auth/i.test(t.path)},{id:"phase-plan-grep-config",category:"phase-plan",prompt:"Users report the app is using wrong API keys in staging. Search for where API_KEY is loaded from environment.",expectedTool:"grep",validateArgs:t=>typeof t.pattern=="string"&&/api.?key|env/i.test(t.pattern)},{id:"phase-verify-build",category:"phase-verify",prompt:"The TypeScript source was modified. Run the build command to verify there are no compilation errors.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&/build|tsc|compile/.test(t.command)},{id:"phase-verify-git-diff",category:"phase-verify",prompt:"Changes were just committed. Show the git diff of the last commit to verify only the intended files were modified.",expectedTool:["git_diff","bash"],validateArgs:t=>(t.command&&/git.*diff|diff.*HEAD/.test(t.command),!0)},{id:"phase-verify-read-config",category:"phase-verify",prompt:"The deployment config was updated. Read config/production.json to verify the changes are correct before deploying.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&/config|production|deploy/i.test(t.path)}],ci=[...Tc,...wh],Sc=["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"];function zx(){try{let s=require("path").join(require("os").homedir(),".nex-code","benchmark-results.json");if(!require("fs").existsSync(s))return Sc;let n=JSON.parse(require("fs").readFileSync(s,"utf-8"));return!Array.isArray(n)||n.length===0?Sc:n.filter(o=>typeof o.score=="number"&&o.score>=60).sort((o,r)=>r.score-o.score).slice(0,12).map(o=>o.model)}catch{return Sc}}var Rc=zx(),Xx=["minimax-m2.7:cloud","qwen3-coder:480b","devstral-2:123b"],bh=(()=>{let t=Rc.slice(0,3);return t.length>=3?t:Xx})(),Vx=7,ii={producedToolCall:.2,correctTool:.35,validArgs:.3,schemaCompliant:.15},Jx="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 Ec(t,e){let s={taskId:t.id,category:t.category,model:e,producedToolCall:!1,correctTool:!1,validArgs:!1,schemaCompliant:!1,toolCalled:null,error:null,latencyMs:0},n=[{role:"system",content:Jx},{role:"user",content:t.prompt}],o=Date.now();try{let r=await Yx.callChat(n,$h,{provider:"ollama",model:e,temperature:0,timeout:9e4});s.latencyMs=Date.now()-o;let i=r.tool_calls||[];if(t.expectedTool===null){let a=i.length===0;s.producedToolCall=a,s.correctTool=a,s.validArgs=!0,s.schemaCompliant=!0}else if(i.length>0){let a=i[0],c=a.function?.name||"unknown",l=a.function?.arguments||{};s.producedToolCall=!0,s.toolCalled=c;let u=Array.isArray(t.expectedTool)?t.expectedTool:[t.expectedTool];if(s.correctTool=u.includes(c),s.correctTool){let d=$h.find(f=>f.function?.name===c);if(s.validArgs=!!t.validateArgs(l,d),d){let f=d.function?.parameters||{},h=f.required||[],m=Object.keys(f.properties||{});s.schemaCompliant=h.every(g=>l[g]!==void 0)&&Object.keys(l).every(g=>m.includes(g))}}}}catch(r){s.latencyMs=Date.now()-o,s.error=r.message.slice(0,120)}return s}function ws(t){return t.error?0:((t.producedToolCall?ii.producedToolCall:0)+(t.correctTool?ii.correctTool:0)+(t.validArgs?ii.validArgs:0)+(t.schemaCompliant?ii.schemaCompliant:0))*100}var _h={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","phase-plan":"plan","phase-verify":"verify"};function Cc(t){return Object.entries(t).map(([e,s])=>{let n=s.map(ws),o=n.reduce((a,c)=>a+c,0)/n.length,r=a=>Math.round(s.filter(a).length/s.length*100),i={};for(let a of["coding","frontend","sysadmin","data","agentic","plan","verify"]){let c=s.filter(u=>_h[u.category]===a);if(c.length===0)continue;let l=c.map(ws).reduce((u,d)=>u+d,0)/c.length;i[a]=Math.round(l*10)/10}return{model:e,score:Math.round(o*10)/10,toolCallRate:r(a=>!a.error&&(a.producedToolCall||a.category==="reasoning")),correctRate:r(a=>a.correctTool),validArgsRate:r(a=>a.validArgs),schemaRate:r(a=>a.schemaCompliant),avgLatency:Math.round(s.reduce((a,c)=>a+c.latencyMs,0)/s.length),errorCount:s.filter(a=>a.error).length,categoryScores:i,results:s}}).sort((e,s)=>s.score-e.score)}function xh(t){let e={};for(let a of["coding","frontend","sysadmin","data","agentic","plan","verify"]){let c=t.filter(g=>g.categoryScores[a]!==void 0&&g.score>=65).sort((g,b)=>b.categoryScores[a]-g.categoryScores[a]);if(c.length===0)continue;let u=(c[0]?.results||[]).filter(g=>_h[g.category]===a).length;if(u<4)continue;let d=c[0],f=c[1];if(d.categoryScores[a]>=95&&u<8&&f&&d.categoryScores[a]-f.categoryScores[a]<15){let b=t.filter(v=>v.categoryScores[a]!==void 0).find(v=>v.categoryScores[a]<95);b&&(e[a]={model:b.model,score:b.categoryScores[a],avgLatency:b.avgLatency,_flukePrevented:!0});continue}let m=c.filter(g=>d.categoryScores[a]-g.categoryScores[a]<=5).sort((g,b)=>g.avgLatency-b.avgLatency)[0];e[a]={model:m.model,score:m.categoryScores[a],avgLatency:m.avgLatency}}return e}function kh(t,e){let s=`nex-code Model Benchmark (${e} tasks \xB7 ollama cloud)`,n=[{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}],o=n.reduce((l,u)=>l+u.width+1,0)+1,r="\u2500".repeat(o);console.log(`
1209
+ ${G.bold}${s}${G.reset}`),console.log(r);let i=n.map(l=>l.label.padEnd(l.width)).join(" ");if(console.log(`${G.dim}${i}${G.reset}`),console.log(r),t.forEach((l,u)=>{let d=String(u+1).padEnd(n[0].width),f=l.model.slice(0,n[1].width).padEnd(n[1].width),h=String(l.score).padEnd(n[2].width),m=`${l.toolCallRate}%`.padEnd(n[3].width),g=`${l.correctRate}%`.padEnd(n[4].width),b=`${l.validArgsRate}%`.padEnd(n[5].width),v=`${l.schemaRate}%`.padEnd(n[6].width),O=`${(l.avgLatency/1e3).toFixed(1)}s`.padEnd(n[7].width),U=l.errorCount>0?`${G.red}${l.errorCount}${G.reset}`:`${G.dim}0${G.reset}`,L=l.score>=80?G.green:l.score>=60?G.yellow:G.red,R=u===0?`${G.yellow}${d}${G.reset}`:`${G.dim}${d}${G.reset}`;console.log(`${R} ${L}${f}${G.reset} ${G.bold}${L}${h}${G.reset} ${m} ${g} ${b} ${v} ${G.dim}${O}${G.reset} ${U}`)}),console.log(r),t.length>0){let l=t[0];if(console.log(`
1210
+ ${G.bold}${G.green}Winner: ${l.model}${G.reset} score ${l.score}/100`),t.length>1){let u=(l.score-t[1].score).toFixed(1);console.log(`${G.dim}+${u} pts over ${t[1].model}${G.reset}`)}}let a=["coding","frontend","sysadmin","data","agentic"];if(t.some(l=>Object.keys(l.categoryScores).length>1)){console.log(`
1211
+ ${G.bold}Best model per task type:${G.reset}`);for(let l of a){let u=t.filter(m=>m.categoryScores[l]!==void 0).sort((m,g)=>g.categoryScores[l]-m.categoryScores[l]);if(u.length===0)continue;let d=u[0],f=d.categoryScores[l],h=f>=80?G.green:f>=60?G.yellow:G.red;console.log(` ${G.dim}${l.padEnd(10)}${G.reset} ${h}${d.model}${G.reset} ${G.dim}${f}/100${G.reset}`)}}console.log()}function vh(t){if(!(!t||t.length<2))try{let e=xh(t),{loadRoutingConfig:s}=ls(),n=s(),o={...n},r=[],i=new Set(["plan","verify"]);for(let[a,{model:c,score:l}]of Object.entries(e)){let u=i.has(a),d=u?n.phases&&n.phases[a]:n[a];d&&d!==c&&!t.find(h=>h.model===d)||(u?(o.phases||(o.phases={}),o.phases[a]!==c&&(o.phases[a]=c,r.push(`phase:${a}\u2192${c}`))):o[a]!==c&&(o[a]=c,r.push(`${a}\u2192${c}`)))}r.length>0&&(Kx(o),console.log(`
1212
+ ${G.dim} Routing updated: ${r.join(", ")}${G.reset}`))}catch{}}async function Zx({models:t,quick:e=!1,onProgress:s,parallelModels:n=1}={}){let o=e?Tc.slice(0,Vx):ci,r=t?.length>0?t:e?bh:Rc,i={};for(let c of r)i[c]=[];if(n<=1)for(let c of r)for(let l of o){s?.({model:c,task:l.id,done:!1});let u=await Ec(l,c);i[c].push(u),s?.({model:c,task:l.id,done:!0,score:ws(u),error:u.error})}else{let c=Math.min(n,r.length),l=[...r],u=Array.from({length:c},async()=>{for(;l.length>0;){let d=l.shift();if(!d)break;for(let f of o){s?.({model:d,task:f.id,done:!1});let h=await Ec(f,d);i[d].push(h),s?.({model:d,task:f.id,done:!0,score:ws(h),error:h.error})}}});await Promise.all(u)}let a=Cc(i);return kh(a,o.length),vh(a),a}async function Qx({newModels:t,existingRanking:e=[],onProgress:s}={}){if(!t||t.length===0)return e;let n={};for(let i of t){n[i]=[];for(let a of ci){s?.({model:i,task:a.id,done:!1});let c=await Ec(a,i);n[i].push(c),s?.({model:i,task:a.id,done:!0,score:ws(c),error:c.error})}}let r=[...Cc(n)];for(let i of e)r.find(a=>a.model===i.model)||r.push(i);return r.sort((i,a)=>a.score-i.score),kh(r,ci.length),vh(r),r}var ai=[{id:"simple_question",name:"Simple Convergence",prompt:"What is 2+2?",maxTurns:3,successCriteria:["4"]}];function Sh(t){let e=require("fs"),n=require("path").join(t||process.cwd(),".nex","benchmark-config.json");if(!e.existsSync(n))return console.log(`${G.yellow}No scenarios configured.${G.reset} Create ${G.dim}.nex/benchmark-config.json${G.reset} to define your benchmark scenarios.
1213
+ Example:
1214
+ {
1215
+ "scenarios": [
1216
+ {
1217
+ "id": "health_check",
1218
+ "name": "Service Health Check",
1219
+ "prompt": "Check if my-api is running on <your-server> and report status",
1220
+ "maxTurns": 10,
1221
+ "successCriteria": ["running", "healthy", "OK"]
1222
+ }
1223
+ ]
1224
+ }
1225
+ `),ai;try{let o=JSON.parse(e.readFileSync(n,"utf-8"));return!Array.isArray(o.scenarios)||o.scenarios.length===0?(console.log(`${G.yellow}benchmark-config.json has no scenarios \u2014 using defaults.${G.reset}
1226
+ `),ai):o.scenarios}catch(o){return console.log(`${G.yellow}Failed to parse benchmark-config.json: ${o.message}${G.reset}
1227
+ `),ai}}function Eh(t,e){let{scoreMessages:s,_extractToolCalls:n,_getLastAssistantText:o}=Lr(),r=s(t),i=r.score,a=[],c=o(t).toLowerCase();e.successCriteria.every(f=>c.includes(f.toLowerCase()))&&(i=Math.min(10,i+1),a.push("+1.0 all success criteria met"));let u=n(t);u.length<e.maxTurns/2&&(i=Math.min(10,i+.5),a.push(`+0.5 efficient (${u.length} tool calls < ${e.maxTurns/2})`)),i=Math.round(i*10)/10;let d=i>=9?"A":i>=8?"B":i>=7?"C":i>=6?"D":"F";return{score:i,grade:d,issues:r.issues,summary:r.summary,bonuses:a}}async function ek(t,e={}){let{spawn:s}=require("child_process"),n=require("fs"),o=require("path"),r=require("os"),i=o.join(r.tmpdir(),`nex-bench-${t.id}-${Date.now()}.txt`);n.writeFileSync(i,t.prompt,"utf-8");let a=o.resolve(__dirname,"..","bin","nex-code.js"),c=e.cwd||process.cwd(),l=[a,"--prompt-file",i,"--delete-prompt-file","--auto","--max-turns",String(t.maxTurns)];return e.model&&l.push("--model",e.model),new Promise(u=>{let d=s(process.execPath,l,{cwd:c,stdio:["ignore","pipe","pipe"],env:{...process.env}}),f=t.maxTurns*60*1e3,h=!1,m=setTimeout(()=>{h=!0;try{d.kill("SIGTERM")}catch{}},f);d.on("close",g=>{clearTimeout(m);try{n.unlinkSync(i)}catch{}let b=o.join(c,".nex","sessions","_autosave.json"),v=[];if(n.existsSync(b))try{v=JSON.parse(n.readFileSync(b,"utf-8")).messages||[]}catch{}u({messages:v,exitCode:g||0,timedOut:h})}),d.stdout.resume(),d.stderr.resume()})}function tk(t,e,s){let n=t.length>0?Math.round(t.reduce((c,l)=>c+l.score,0)/t.length*10)/10:0,o=n>=9?"A":n>=8?"B":n>=7?"C":n>=6?"D":"F",r=57,i="\u2500".repeat(r);console.log(`
1228
+ \u250C\u2500 Benchmark Results ${"\u2500".repeat(r-19)}\u2510`);for(let c of t){let l=c.id.padEnd(20),u=c.name.substring(0,26).padEnd(26),d=`${c.score}/10`.padStart(6),f=c.grade.padStart(2);console.log(`\u2502 ${l} ${u} ${d} ${f} \u2502`)}console.log(`\u2502 ${" ".repeat(r-2)} \u2502`);let a=`Overall: ${n}/10 (${o}) \xB7 v${e} \xB7 ${s}`;console.log(`\u2502 ${a.substring(0,r-4).padEnd(r-4)} \u2502`),console.log(`\u2514${"\u2500".repeat(r+1)}\u2518
1229
+ `)}function nk(t=10){let e=require("fs"),n=require("path").join(process.cwd(),".nex","benchmark-history.json");if(!e.existsSync(n)){console.log(`${G.yellow}No score history yet. Run a session first.${G.reset}
1230
+ `);return}let o=[];try{o=JSON.parse(e.readFileSync(n,"utf-8"))}catch{o=[]}if(!Array.isArray(o)||o.length===0){console.log(`${G.yellow}Score history is empty.${G.reset}
1231
+ `);return}let r=o.slice(-t);console.log(`
1232
+ ${G.bold}Score History (last ${r.length} session${r.length===1?"":"s"}):${G.reset}`);for(let i of r){let a=(i.date||"").replace("T"," ").substring(0,16),c=(i.version||"?").padEnd(8),l=(i.model||"?").substring(0,12).padEnd(12),u=`${i.score}/10`.padStart(6),d=i.grade||"?",f=i.issues&&i.issues.length>0?`${G.yellow}\u26A0 ${i.issues.slice(0,2).map(m=>m.substring(0,30)).join(", ")}${G.reset}`:`${G.green}\u2713${G.reset}`,h=i.score>=8?G.green:i.score>=6?G.yellow:G.red;console.log(` ${G.dim}${a}${G.reset} ${G.dim}v${c}${G.reset} ${G.dim}${l}${G.reset} ${h}${u} ${d}${G.reset} ${f}`)}console.log()}async function sk({dryRun:t=!1,model:e,cwd:s,onProgress:n}={}){let o=No(),r=Sh(s);if(t){console.log(`
1233
+ ${G.bold}Jarvis Benchmark \u2014 Scenarios (dry-run):${G.reset}
1234
+ `);for(let c of r)console.log(` ${G.cyan}${c.id.padEnd(20)}${G.reset} ${G.dim}${c.name}${G.reset} maxTurns=${c.maxTurns}`),console.log(` ${G.dim}${c.prompt.substring(0,80)}${G.reset}`);return console.log(),[]}let i=(()=>{if(e)return typeof e=="object"?e.id||"unknown":e;try{let{getActiveModel:c}=Ss(),l=c?c():null;return l?typeof l=="object"?l.id||"unknown":l:"unknown"}catch{return"unknown"}})(),a=[];for(let c of r){n?.({id:c.id,name:c.name,done:!1}),console.log(`
1235
+ ${G.dim}Running scenario: ${c.name}...${G.reset}`);let{messages:l,timedOut:u}=await ek(c,{model:i,cwd:s}),d;u||l.length===0?d={score:0,grade:"F",issues:[u?"Scenario timed out":"No messages produced"],summary:"No output",bonuses:[]}:d=Eh(l,c);let f={id:c.id,name:c.name,score:d.score,grade:d.grade,issues:d.issues,bonuses:d.bonuses};a.push(f),n?.({id:c.id,name:c.name,done:!0,score:d.score,grade:d.grade});try{let{appendScoreHistory:h}=Lr();h(d.score,{version:o.version,model:i,sessionName:`bench:${c.id}`,issues:d.issues})}catch{}}return tk(a,o.version,i),a}module.exports={runBenchmark:Zx,runDiscoverBenchmark:Qx,buildSummary:Cc,buildCategoryWinners:xh,TASKS:Tc,PHASE_TASKS:wh,ALL_TASKS:ci,scoreResult:ws,DEFAULT_MODELS:Rc,QUICK_MODELS:bh,runJarvisBenchmark:sk,showScoreTrend:nk,loadScenarios:Sh,DEFAULT_SCENARIOS:ai,scoreJarvisScenario:Eh};