nex-code 0.5.6 → 0.5.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/benchmark.js CHANGED
@@ -1,136 +1,136 @@
1
- "use strict";var ua=Object.defineProperty;var Wy=Object.getOwnPropertyDescriptor;var Hy=Object.getOwnPropertyNames;var Yy=Object.prototype.hasOwnProperty;var Gy=(t,e)=>()=>(t&&(e=t(t=0)),e);var Z=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),zy=(t,e)=>{for(var s in e)ua(t,s,{get:e[s],enumerable:!0})},Ky=(t,e,s,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Hy(e))!Yy.call(t,o)&&o!==s&&ua(t,o,{get:()=>e[o],enumerable:!(n=Wy(e,o))||n.enumerable});return t};var Xy=t=>Ky(ua({},"__esModule",{value:!0}),t);var Bt=Z((GT,wu)=>{"use strict";var fu="\x1B[0m",pu="\x1B[1m",_s="\x1B[2m";function G(t,e,s){return`\x1B[38;2;${t};${e};${s}m`}function Vy(){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 hu(){let t=require("os");return require("path").join(t.homedir(),".nex-code",".theme_cache.json")}function Jy(t){try{let s=require("fs").readFileSync(hu(),"utf8"),n=JSON.parse(s);if(n&&typeof n[t]=="boolean")return n[t]}catch{}return null}function Zy(t,e){try{let s=require("fs"),n=require("path"),o=hu(),r=n.dirname(o),i={};try{i=JSON.parse(s.readFileSync(o,"utf8"))}catch(l){console.error("theme cache failed:",l.message)}i[t]=e;let a=Object.keys(i);a.length>50&&a.slice(0,a.length-50).forEach(l=>delete i[l]),s.existsSync(r)||s.mkdirSync(r,{recursive:!0}),s.writeFileSync(o,JSON.stringify(i),"utf8")}catch{}}function Qy(){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=Jy(s);if(n!==null)return n;let o=Vy(),r=o!==null?o:!0;return Zy(s,r),r}var mu=Qy(),gu={reset:fu,bold:pu,dim:_s,primary:G(80,190,255),secondary:G(60,170,190),success:G(80,210,120),warning:G(245,175,50),error:G(230,80,80),muted:_s,subtle:G(130,130,145),tool_read:G(80,190,255),tool_write:G(245,165,55),tool_exec:G(185,100,235),tool_search:G(70,185,190),tool_git:G(90,210,100),tool_web:G(100,215,250),tool_sysadmin:G(225,150,75),tool_default:G(100,205,115),syn_keyword:G(185,100,235),syn_string:G(90,210,120),syn_number:G(245,175,50),syn_comment:_s,syn_key:G(80,190,255),diff_add:G(80,210,120),diff_rem:G(230,80,80),banner_logo:G(80,200,255),banner_name:G(80,200,255),banner_version:_s,banner_model:_s,banner_yolo:G(245,175,50),banner_gemini:G(138,180,248),footer_sep:_s,footer_model:G(80,175,235),footer_branch:G(80,210,100),footer_project:G(130,130,145),footer_divider:G(80,80,95),footer_mode:G(210,150,50),white:G(210,210,220),red:G(220,85,85),green:G(80,200,110),yellow:G(230,185,60),blue:G(70,140,230),magenta:G(200,120,190),cyan:G(90,200,215),gray:G(120,120,135),bgRed:"\x1B[48;2;140;40;40m",bgGreen:"\x1B[48;2;30;100;50m",diff_add_bg:"\x1B[48;2;10;46;20m",diff_rem_bg:"\x1B[48;2;58;16;16m",brightCyan:G(110,215,230),brightMagenta:G(220,140,210),brightBlue:G(100,160,240)},yu={reset:fu,bold:pu,dim:G(110,110,120),primary:G(0,110,190),secondary:G(0,125,148),success:G(0,148,62),warning:G(168,92,0),error:G(188,32,32),muted:G(110,110,120),subtle:G(155,155,165),tool_read:G(0,110,190),tool_write:G(168,92,0),tool_exec:G(128,42,188),tool_search:G(0,122,148),tool_git:G(0,138,62),tool_web:G(0,112,178),tool_sysadmin:G(168,82,0),tool_default:G(0,138,62),syn_keyword:G(128,42,188),syn_string:G(0,138,62),syn_number:G(168,92,0),syn_comment:G(135,135,148),syn_key:G(0,110,190),diff_add:G(0,148,62),diff_rem:G(188,32,32),banner_logo:G(0,122,205),banner_name:G(0,122,205),banner_version:G(100,100,118),banner_model:G(100,100,118),banner_yolo:G(168,62,0),banner_gemini:G(26,115,232),footer_sep:G(168,168,178),footer_model:G(0,102,175),footer_branch:G(0,138,62),footer_project:G(135,135,148),footer_divider:G(168,168,178),footer_mode:G(148,88,0),white:G(40,40,52),red:G(188,32,32),green:G(0,148,62),yellow:G(168,92,0),blue:G(0,110,190),magenta:G(128,42,188),cyan:G(0,125,148),gray:G(132,132,142),bgRed:"\x1B[48;2;180;50;50m",bgGreen:"\x1B[48;2;30;130;60m",diff_add_bg:"\x1B[48;2;215;245;220m",diff_rem_bg:"\x1B[48;2;255;215;215m",brightCyan:G(0,158,182),brightMagenta:G(158,52,208),brightBlue:G(0,112,208)},e0=mu?gu:yu;wu.exports={T:e0,isDark:mu,DARK:gu,LIGHT:yu}});var mr=Z((zT,t0)=>{t0.exports={name:"nex-code",version:"0.5.6",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:"node scripts/build.js",dev:"node scripts/build.js --dev",test:"jest --forceExit --maxWorkers=50%","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-commit .git/hooks/pre-commit && chmod +x .git/hooks/pre-commit && 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-commit, 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","benchmark:reallife":"node scripts/benchmark-reallife.js","benchmark:report":"node scripts/benchmark-reallife-report.js","improve:reallife":"node scripts/improve-reallife.js","benchmark:gate":"node scripts/benchmark-gate.js",release:"bash scripts/release.sh"},keywords:["ai","cli","coding","agent","ollama","ollama-cloud","openai","anthropic","gemini","llm","gpt","agentic","terminal","coding-assistant","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.15.0",dotenv:"^16.4.0",pixelmatch:"^7.1.0",pngjs:"^7.0.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 bs=Z((KT,$u)=>{var{T:se}=Bt(),wr=5,$s=(()=>{let t=[];for(let e=0;e<wr;e++)t.push(e);for(let e=wr-2;e>=1;e--)t.push(e);return t})(),_u=["\u273D","\u2726","\u2727","\u2726"],da=class{constructor(e="Thinking..."){this.text=e,this.frame=0,this.interval=null,this.startTime=null}_render(){if(this._stopped)return;let e=$s[this.frame%$s.length],s="";for(let o=0;o<wr;o++)s+=o===e?`${se.cyan}\u25CF${se.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=` ${se.dim}${r}m ${String(i).padStart(2,"0")}s${se.reset}`}else o>=1&&(n=` ${se.dim}${o}s${se.reset}`)}process.stderr.write(`\x1B[2K\r${s} ${se.dim}${this.text}${se.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}},fa=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=$s[this.frame%$s.length],s=`${se.cyan}\u25CF${se.reset}`,n=this._formatElapsed(),o=n?` ${se.dim}${n}${se.reset}`:"",r=process.stderr.columns||80,i="";for(let a=0;a<this.labels.length;a++){let l,c;switch(this.statuses[a]){case"done":l=`${se.green}\u2713${se.reset}`,c=se.dim;break;case"error":l=`${se.red}\u2717${se.reset}`,c=se.dim;break;case"retry":l=`${se.yellow}\u21BB${se.reset}`,c=se.yellow;break;default:l=a===e?s:" ",c=""}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 ${l} ${c}${f}${se.reset}${u}
1
+ "use strict";var ga=Object.defineProperty;var Zy=Object.getOwnPropertyDescriptor;var Qy=Object.getOwnPropertyNames;var e0=Object.prototype.hasOwnProperty;var t0=(t,e)=>()=>(t&&(e=t(t=0)),e);var Q=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),n0=(t,e)=>{for(var s in e)ga(t,s,{get:e[s],enumerable:!0})},s0=(t,e,s,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Qy(e))!e0.call(t,o)&&o!==s&&ga(t,o,{get:()=>e[o],enumerable:!(n=Zy(e,o))||n.enumerable});return t};var o0=t=>s0(ga({},"__esModule",{value:!0}),t);var Bt=Q((dR,Ru)=>{"use strict";var xu="\x1B[0m",ku="\x1B[1m",bs="\x1B[2m";function z(t,e,s){return`\x1B[38;2;${t};${e};${s}m`}function r0(){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 Su(){let t=require("os");return require("path").join(t.homedir(),".nex-code",".theme_cache.json")}function i0(t){try{let s=require("fs").readFileSync(Su(),"utf8"),n=JSON.parse(s);if(n&&typeof n[t]=="boolean")return n[t]}catch{}return null}function a0(t,e){try{let s=require("fs"),n=require("path"),o=Su(),r=n.dirname(o),i={};try{i=JSON.parse(s.readFileSync(o,"utf8"))}catch(l){console.error("theme cache failed:",l.message)}i[t]=e;let a=Object.keys(i);a.length>50&&a.slice(0,a.length-50).forEach(l=>delete i[l]),s.existsSync(r)||s.mkdirSync(r,{recursive:!0}),s.writeFileSync(o,JSON.stringify(i),"utf8")}catch{}}function l0(){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=i0(s);if(n!==null)return n;let o=r0(),r=o!==null?o:!0;return a0(s,r),r}var vu=l0(),Eu={reset:xu,bold:ku,dim:bs,primary:z(80,190,255),secondary:z(60,170,190),success:z(80,210,120),warning:z(245,175,50),error:z(230,80,80),muted:bs,subtle:z(130,130,145),tool_read:z(80,190,255),tool_write:z(245,165,55),tool_exec:z(185,100,235),tool_search:z(70,185,190),tool_git:z(90,210,100),tool_web:z(100,215,250),tool_sysadmin:z(225,150,75),tool_default:z(100,205,115),syn_keyword:z(185,100,235),syn_string:z(90,210,120),syn_number:z(245,175,50),syn_comment:bs,syn_key:z(80,190,255),diff_add:z(80,210,120),diff_rem:z(230,80,80),banner_logo:z(80,200,255),banner_name:z(80,200,255),banner_version:bs,banner_model:bs,banner_yolo:z(245,175,50),banner_gemini:z(138,180,248),footer_sep:bs,footer_model:z(80,175,235),footer_branch:z(80,210,100),footer_project:z(130,130,145),footer_divider:z(80,80,95),footer_mode:z(210,150,50),white:z(210,210,220),red:z(220,85,85),green:z(80,200,110),yellow:z(230,185,60),blue:z(70,140,230),magenta:z(200,120,190),cyan:z(90,200,215),gray:z(120,120,135),bgRed:"\x1B[48;2;140;40;40m",bgGreen:"\x1B[48;2;30;100;50m",diff_add_bg:"\x1B[48;2;10;46;20m",diff_rem_bg:"\x1B[48;2;58;16;16m",brightCyan:z(110,215,230),brightMagenta:z(220,140,210),brightBlue:z(100,160,240)},Tu={reset:xu,bold:ku,dim:z(110,110,120),primary:z(0,110,190),secondary:z(0,125,148),success:z(0,148,62),warning:z(168,92,0),error:z(188,32,32),muted:z(110,110,120),subtle:z(155,155,165),tool_read:z(0,110,190),tool_write:z(168,92,0),tool_exec:z(128,42,188),tool_search:z(0,122,148),tool_git:z(0,138,62),tool_web:z(0,112,178),tool_sysadmin:z(168,82,0),tool_default:z(0,138,62),syn_keyword:z(128,42,188),syn_string:z(0,138,62),syn_number:z(168,92,0),syn_comment:z(135,135,148),syn_key:z(0,110,190),diff_add:z(0,148,62),diff_rem:z(188,32,32),banner_logo:z(0,122,205),banner_name:z(0,122,205),banner_version:z(100,100,118),banner_model:z(100,100,118),banner_yolo:z(168,62,0),banner_gemini:z(26,115,232),footer_sep:z(168,168,178),footer_model:z(0,102,175),footer_branch:z(0,138,62),footer_project:z(135,135,148),footer_divider:z(168,168,178),footer_mode:z(148,88,0),white:z(40,40,52),red:z(188,32,32),green:z(0,148,62),yellow:z(168,92,0),blue:z(0,110,190),magenta:z(128,42,188),cyan:z(0,125,148),gray:z(132,132,142),bgRed:"\x1B[48;2;180;50;50m",bgGreen:"\x1B[48;2;30;130;60m",diff_add_bg:"\x1B[48;2;215;245;220m",diff_rem_bg:"\x1B[48;2;255;215;215m",brightCyan:z(0,158,182),brightMagenta:z(158,52,208),brightBlue:z(0,112,208)},c0=vu?Eu:Tu;Ru.exports={T:c0,isDark:vu,DARK:Eu,LIGHT:Tu}});var _r=Q((fR,u0)=>{u0.exports={name:"nex-code",version:"0.5.8",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:"node scripts/build.js",dev:"node scripts/build.js --dev",test:"jest --forceExit --maxWorkers=50%","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-commit .git/hooks/pre-commit && chmod +x .git/hooks/pre-commit && 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-commit, 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","benchmark:reallife":"node scripts/benchmark-reallife.js","benchmark:report":"node scripts/benchmark-reallife-report.js","improve:reallife":"node scripts/improve-reallife.js","benchmark:gate":"node scripts/benchmark-gate.js",release:"bash scripts/release.sh"},keywords:["ai","cli","coding","agent","ollama","ollama-cloud","openai","anthropic","gemini","llm","gpt","agentic","terminal","coding-assistant","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.15.0",dotenv:"^16.4.0",pixelmatch:"^7.1.0",pngjs:"^7.0.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 ks=Q((pR,Au)=>{var{T:oe}=Bt(),xr=5,xs=(()=>{let t=[];for(let e=0;e<xr;e++)t.push(e);for(let e=xr-2;e>=1;e--)t.push(e);return t})(),Cu=["\u273D","\u2726","\u2727","\u2726"],ya=class{constructor(e="Thinking..."){this.text=e,this.frame=0,this.interval=null,this.startTime=null}_render(){if(this._stopped)return;let e=xs[this.frame%xs.length],s="";for(let o=0;o<xr;o++)s+=o===e?`${oe.cyan}\u25CF${oe.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=` ${oe.dim}${r}m ${String(i).padStart(2,"0")}s${oe.reset}`}else o>=1&&(n=` ${oe.dim}${o}s${oe.reset}`)}process.stderr.write(`\x1B[2K\r${s} ${oe.dim}${this.text}${oe.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}},wa=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=xs[this.frame%xs.length],s=`${oe.cyan}\u25CF${oe.reset}`,n=this._formatElapsed(),o=n?` ${oe.dim}${n}${oe.reset}`:"",r=process.stderr.columns||80,i="";for(let a=0;a<this.labels.length;a++){let l,c;switch(this.statuses[a]){case"done":l=`${oe.green}\u2713${oe.reset}`,c=oe.dim;break;case"error":l=`${oe.red}\u2717${oe.reset}`,c=oe.dim;break;case"retry":l=`${oe.yellow}\u21BB${oe.reset}`,c=oe.yellow;break;default:l=a===e?s:" ",c=""}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 ${l} ${c}${f}${oe.reset}${u}
3
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
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?` ${se.dim}${e}${se.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=`${se.green}\u2713${se.reset}`;break;case"error":i=`${se.red}\u2717${se.reset}`;break;case"retry":i=`${se.yellow}\u21BB${se.reset}`;break;default:i=`${se.yellow}\u25CB${se.reset}`}let a=r===this.labels.length-1?s:"",l=n-4-(a?e.length+1:0),c=this.labels[r].length>l?this.labels[r].substring(0,Math.max(10,l-3))+"...":this.labels[r];o+=`\x1B[2K ${i} ${se.dim}${c}${se.reset}${a}
6
- `}process.stderr.write(o)}},gr={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},yr={done:se.green,in_progress:se.cyan,pending:se.dim,failed:se.red},_n=null,pa=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=_u[this.frame%_u.length],s=this._formatElapsed(),n=this._formatTokens(),o=[s,n?`\u2193 ${n} tokens`:""].filter(Boolean).join(" \xB7 "),r=o?` ${se.dim}(${o})${se.reset}`:"",i=`\x1B[2K${se.cyan}${e}${se.reset} ${this.name}\u2026${r}
7
- `;for(let a=0;a<this.tasks.length;a++){let l=this.tasks[a],c=a===0?"\u23BF":" ",u=gr[l.status]||gr.pending,d=yr[l.status]||yr.pending,f=l.description.length>55?l.description.substring(0,52)+"...":l.description;i+=`\x1B[2K ${se.dim}${c}${se.reset} ${d}${u}${se.reset} ${f}
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?` ${oe.dim}${e}${oe.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=`${oe.green}\u2713${oe.reset}`;break;case"error":i=`${oe.red}\u2717${oe.reset}`;break;case"retry":i=`${oe.yellow}\u21BB${oe.reset}`;break;default:i=`${oe.yellow}\u25CB${oe.reset}`}let a=r===this.labels.length-1?s:"",l=n-4-(a?e.length+1:0),c=this.labels[r].length>l?this.labels[r].substring(0,Math.max(10,l-3))+"...":this.labels[r];o+=`\x1B[2K ${i} ${oe.dim}${c}${oe.reset}${a}
6
+ `}process.stderr.write(o)}},$r={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},br={done:oe.green,in_progress:oe.cyan,pending:oe.dim,failed:oe.red},wn=null,_a=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=Cu[this.frame%Cu.length],s=this._formatElapsed(),n=this._formatTokens(),o=[s,n?`\u2193 ${n} tokens`:""].filter(Boolean).join(" \xB7 "),r=o?` ${oe.dim}(${o})${oe.reset}`:"",i=`\x1B[2K${oe.cyan}${e}${oe.reset} ${this.name}\u2026${r}
7
+ `;for(let a=0;a<this.tasks.length;a++){let l=this.tasks[a],c=a===0?"\u23BF":" ",u=$r[l.status]||$r.pending,d=br[l.status]||br.pending,f=l.description.length>55?l.description.substring(0,52)+"...":l.description;i+=`\x1B[2K ${oe.dim}${c}${oe.reset} ${d}${u}${oe.reset} ${f}
8
8
  `}i+=`\x1B[${this.lineCount}A`,process.stderr.write(i),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),this._paused=!1;let e="\x1B[?25l";for(let s=0;s<this.lineCount;s++)e+=`
9
- `;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120),_n=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,_n===this&&(_n=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
9
+ `;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120),wn=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,wn===this&&(wn=null)}pause(){if(this._paused)return;this.interval&&(clearInterval(this.interval),this.interval=null);let e="";for(let s=0;s<this.lineCount;s++)e+=`\x1B[2K
10
10
  `;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._paused=!0}resume(){if(!this._paused)return;this._paused=!1;let e="\x1B[?25l";for(let s=0;s<this.lineCount;s++)e+=`
11
- `;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120)}updateTask(e,s){let 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${se.green}\u2714${se.reset} ${this.name} ${se.dim}(${e} \xB7 ${r})${se.reset}
12
- `;for(let a=0;a<this.tasks.length;a++){let l=this.tasks[a],c=a===0?"\u23BF":" ",u=gr[l.status]||gr.pending,d=yr[l.status]||yr.pending,f=l.description.length>55?l.description.substring(0,52)+"...":l.description;i+=`\x1B[2K ${se.dim}${c}${se.reset} ${d}${u}${se.reset} ${se.dim}${f}${se.reset}
13
- `}process.stderr.write(i)}},ha=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=$s[this.frame%$s.length],s="";for(let r=0;r<wr;r++)s+=r===e?`${se.cyan}\u25CF${se.reset}`:" ";let n=this.message;this.count>0&&(n+=` ${se.cyan}${this.count}${se.reset}`,this.total&&(n+=`/${this.total}`),this.detail&&(n+=` ${se.dim}${this.detail}${se.reset}`));let o="";if(this.startTime){let r=Math.floor((Date.now()-this.startTime)/1e3);r>=1&&(o=` ${se.dim}${r}s${se.reset}`)}process.stderr.write(`\x1B[2K\r${s} ${se.dim}${n}${se.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 n0(t){_n=t}function s0(){return _n}function o0(){_n&&(_n.stop(),_n=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}$u.exports={C:se,Spinner:da,MultiProgress:fa,TaskProgress:pa,ToolProgress:ha,setActiveTaskProgress:n0,getActiveTaskProgress:s0,cleanupTerminal:o0}});var ma=Z((XT,vu)=>{"use strict";var{T:In}=Bt(),ce={kw:In.syn_keyword,str:In.syn_string,cmt:In.syn_comment,num:In.syn_number,type:In.cyan,punct:In.magenta,reset:In.reset},bu={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"])},r0={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 ku(t){if(!t)return null;let e=t.split(".").pop().toLowerCase();return r0[e]||null}var xu=/\x1b\[[0-9;]*m/g;function ln(t,e,s){let n=t.split(xu),o=t.match(xu)||[],r="";for(let i=0;i<n.length;i++)r+=n[i].replace(e,s),i<o.length&&(r+=o[i]);return r}function i0(t){let e=t;return e=e.replace(/"([^"\\]|\\.)*"\s*:/g,s=>ce.type+s+ce.reset),e=ln(e,/"([^"\\]|\\.)*"/g,s=>ce.str+s+ce.reset),e=ln(e,/\b-?(\d+(\.\d+)?([eE][+-]?\d+)?)\b/g,s=>ce.num+s+ce.reset),e=ln(e,/\b(true|false|null)\b/g,s=>ce.kw+s+ce.reset),e}function a0(t){if(/<!--/.test(t))return t.replace(/<!--[\s\S]*?(?:-->|$)/g,s=>ce.cmt+s+ce.reset);let e=t;return e=e.replace(/(<\/?)([a-zA-Z][a-zA-Z0-9.-]*)/g,(s,n,o)=>n+ce.type+o+ce.reset),e=ln(e,/\s([a-zA-Z][a-zA-Z0-9-]*)=/g,(s,n)=>" "+ce.kw+n+ce.reset+"="),e=ln(e,/"([^"]*)"/g,s=>ce.str+s+ce.reset),e}function l0(t){let e=t;return e=e.replace(/\/\*[\s\S]*?(?:\*\/|$)/g,s=>ce.cmt+s+ce.reset),e=ln(e,/#[0-9a-fA-F]{3,8}\b/g,s=>ce.num+s+ce.reset),e=ln(e,/\b(-?\d+(?:\.\d+)?)(px|em|rem|vh|vw|vmin|vmax|%|s|ms|deg|fr)\b/g,(s,n,o)=>ce.num+n+ce.reset+o),e=ln(e,/([a-z][a-z-]*)(\s*:)/g,(s,n,o)=>ce.type+n+ce.reset+o),e=ln(e,/"[^"]*"|'[^']*'/g,s=>ce.str+s+ce.reset),e}function Su(t,e,s){if(e==="json")return i0(t);if(e==="html"||e==="xml")return a0(t);if(e==="css")return l0(t);if(e==="md")return t;let n=bu[e]||bu.js,o="",r=0;if(s.inBlockComment){let i=t.indexOf("*/");if(i===-1)return ce.cmt+t+ce.reset;if(o+=ce.cmt+t.slice(0,i+2)+ce.reset,s.inBlockComment=!1,r=i+2,r>=t.length)return o}if(s.inString==="`"){let i=t.indexOf("`");if(i===-1)return ce.str+t+ce.reset;if(o+=ce.str+t.slice(0,i+1)+ce.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+=ce.cmt+t.slice(r)+ce.reset,s.inBlockComment=!0,o;o+=ce.cmt+t.slice(r,a+2)+ce.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+=ce.cmt+t.slice(r)+ce.reset,o;if(!s.inString&&(i==='"'||i==="'"||i==="`")){s.inString=i,o+=ce.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+ce.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+=ce.num+a+ce.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+=ce.punct+a+ce.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+=ce.kw+a+ce.reset:/^[A-Z][A-Za-z0-9]*$/.test(a)&&e!=="sh"?o+=ce.type+a+ce.reset:o+=a;continue}o+=i,r++}return s.inString&&s.inString!=="`"&&(o+=ce.reset,s.inString=null),o}function c0(t,e){let s=ku(e);if(!s)return t.split(`
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${oe.green}\u2714${oe.reset} ${this.name} ${oe.dim}(${e} \xB7 ${r})${oe.reset}
12
+ `;for(let a=0;a<this.tasks.length;a++){let l=this.tasks[a],c=a===0?"\u23BF":" ",u=$r[l.status]||$r.pending,d=br[l.status]||br.pending,f=l.description.length>55?l.description.substring(0,52)+"...":l.description;i+=`\x1B[2K ${oe.dim}${c}${oe.reset} ${d}${u}${oe.reset} ${oe.dim}${f}${oe.reset}
13
+ `}process.stderr.write(i)}},$a=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=xs[this.frame%xs.length],s="";for(let r=0;r<xr;r++)s+=r===e?`${oe.cyan}\u25CF${oe.reset}`:" ";let n=this.message;this.count>0&&(n+=` ${oe.cyan}${this.count}${oe.reset}`,this.total&&(n+=`/${this.total}`),this.detail&&(n+=` ${oe.dim}${this.detail}${oe.reset}`));let o="";if(this.startTime){let r=Math.floor((Date.now()-this.startTime)/1e3);r>=1&&(o=` ${oe.dim}${r}s${oe.reset}`)}process.stderr.write(`\x1B[2K\r${s} ${oe.dim}${n}${oe.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 d0(t){wn=t}function f0(){return wn}function p0(){wn&&(wn.stop(),wn=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}Au.exports={C:oe,Spinner:ya,MultiProgress:wa,TaskProgress:_a,ToolProgress:$a,setActiveTaskProgress:d0,getActiveTaskProgress:f0,cleanupTerminal:p0}});var ba=Q((hR,Lu)=>{"use strict";var{T:Ln}=Bt(),ue={kw:Ln.syn_keyword,str:Ln.syn_string,cmt:Ln.syn_comment,num:Ln.syn_number,type:Ln.cyan,punct:Ln.magenta,reset:Ln.reset},Ou={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"])},h0={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 Mu(t){if(!t)return null;let e=t.split(".").pop().toLowerCase();return h0[e]||null}var Nu=/\x1b\[[0-9;]*m/g;function ln(t,e,s){let n=t.split(Nu),o=t.match(Nu)||[],r="";for(let i=0;i<n.length;i++)r+=n[i].replace(e,s),i<o.length&&(r+=o[i]);return r}function m0(t){let e=t;return e=e.replace(/"([^"\\]|\\.)*"\s*:/g,s=>ue.type+s+ue.reset),e=ln(e,/"([^"\\]|\\.)*"/g,s=>ue.str+s+ue.reset),e=ln(e,/\b-?(\d+(\.\d+)?([eE][+-]?\d+)?)\b/g,s=>ue.num+s+ue.reset),e=ln(e,/\b(true|false|null)\b/g,s=>ue.kw+s+ue.reset),e}function g0(t){if(/<!--/.test(t))return t.replace(/<!--[\s\S]*?(?:-->|$)/g,s=>ue.cmt+s+ue.reset);let e=t;return e=e.replace(/(<\/?)([a-zA-Z][a-zA-Z0-9.-]*)/g,(s,n,o)=>n+ue.type+o+ue.reset),e=ln(e,/\s([a-zA-Z][a-zA-Z0-9-]*)=/g,(s,n)=>" "+ue.kw+n+ue.reset+"="),e=ln(e,/"([^"]*)"/g,s=>ue.str+s+ue.reset),e}function y0(t){let e=t;return e=e.replace(/\/\*[\s\S]*?(?:\*\/|$)/g,s=>ue.cmt+s+ue.reset),e=ln(e,/#[0-9a-fA-F]{3,8}\b/g,s=>ue.num+s+ue.reset),e=ln(e,/\b(-?\d+(?:\.\d+)?)(px|em|rem|vh|vw|vmin|vmax|%|s|ms|deg|fr)\b/g,(s,n,o)=>ue.num+n+ue.reset+o),e=ln(e,/([a-z][a-z-]*)(\s*:)/g,(s,n,o)=>ue.type+n+ue.reset+o),e=ln(e,/"[^"]*"|'[^']*'/g,s=>ue.str+s+ue.reset),e}function Pu(t,e,s){if(e==="json")return m0(t);if(e==="html"||e==="xml")return g0(t);if(e==="css")return y0(t);if(e==="md")return t;let n=Ou[e]||Ou.js,o="",r=0;if(s.inBlockComment){let i=t.indexOf("*/");if(i===-1)return ue.cmt+t+ue.reset;if(o+=ue.cmt+t.slice(0,i+2)+ue.reset,s.inBlockComment=!1,r=i+2,r>=t.length)return o}if(s.inString==="`"){let i=t.indexOf("`");if(i===-1)return ue.str+t+ue.reset;if(o+=ue.str+t.slice(0,i+1)+ue.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+=ue.cmt+t.slice(r)+ue.reset,s.inBlockComment=!0,o;o+=ue.cmt+t.slice(r,a+2)+ue.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+=ue.cmt+t.slice(r)+ue.reset,o;if(!s.inString&&(i==='"'||i==="'"||i==="`")){s.inString=i,o+=ue.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+ue.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+=ue.num+a+ue.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+=ue.punct+a+ue.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+=ue.kw+a+ue.reset:/^[A-Z][A-Za-z0-9]*$/.test(a)&&e!=="sh"?o+=ue.type+a+ue.reset:o+=a;continue}o+=i,r++}return s.inString&&s.inString!=="`"&&(o+=ue.reset,s.inString=null),o}function w0(t,e){let s=Mu(e);if(!s)return t.split(`
14
14
  `);let n=t.split(`
15
- `),o={inString:null,inBlockComment:!1};return n.map(r=>Su(r,s,o))}function u0(t,e){return e?Su(t,e,{inString:null,inBlockComment:!1}):t}vu.exports={detectLang:ku,highlightLine:u0,highlightLines:c0}});var Ru=Z((VT,Tu)=>{var{T:A}=Bt(),rt=A,d0={read_file:A.tool_read,list_directory:A.tool_read,write_file:A.tool_write,edit_file:A.tool_write,patch_file:A.tool_write,bash:A.tool_exec,grep:A.tool_search,search_files:A.tool_search,glob:A.tool_search,git_commit:A.tool_git,git_push:A.tool_git,git_pull:A.tool_git,git_status:A.tool_git,git_diff:A.tool_git,git_log:A.tool_git,git_branch:A.tool_git,git_stash:A.tool_git,web_fetch:A.tool_web,web_search:A.tool_web,sysadmin:A.tool_sysadmin,ssh_exec:A.tool_sysadmin,ssh_upload:A.tool_sysadmin,ssh_download:A.tool_sysadmin,deploy:A.tool_sysadmin},ga={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 _r(t,e=!1,s=null){if(e)return`${A.error}\u23FA${A.reset}`;let n=d0[t]||A.tool_default;return s==="blink"?`${n}\x1B[5m\u23FA\x1B[25m${A.reset}`:`${n}${s!==null?s:"\u23FA"}${A.reset}`}function f0(t,e,s=!1,n=null){let o=(t||[]).filter(l=>l&&l.canExecute!==!1);if(o.length===0)return`${_r("",s,n)} Step ${e}`;if(o.length===1){let l=o[0],c=l.args||{},u=ga[l.fnName]||l.fnName.replace(/_/g," "),d="";c.path?d=c._originalPath||c.path:c.command?d=String(c.command).substring(0,80):c.query?d=String(c.query).substring(0,60):c.pattern?d=String(c.pattern).substring(0,60):c.url&&(d=String(c.url).substring(0,60));let f=d?`(${rt.dim}${d}${rt.reset})`:"";return`${_r(l.fnName,s,n)} ${rt.bold}${u}${rt.reset}${f}`}let r=o[0].fnName,i=[...new Set(o.map(l=>ga[l.fnName]||l.fnName.replace(/_/g," ")))],a=i.length<=3?i.join(", "):`${o.length} tools`;return`${_r(r,s,n)} ${rt.bold}${a}${rt.reset}`}function p0(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=ga[t]||t.replace(/_/g," "),o=s?`(${rt.dim}${s}${rt.reset})`:"";return`${_r(t)} ${rt.bold}${n}${rt.reset}${o}`}function h0(t,e=8){let s=t.split(`
16
- `),n=s.slice(0,e),o=s.length-e,r=`${A.muted} \u23BF ${A.reset}`,i=" ",a=n.map((l,c)=>`${c===0?r:i}${A.success}${l}${A.reset}`).join(`
15
+ `),o={inString:null,inBlockComment:!1};return n.map(r=>Pu(r,s,o))}function _0(t,e){return e?Pu(t,e,{inString:null,inBlockComment:!1}):t}Lu.exports={detectLang:Mu,highlightLine:_0,highlightLines:w0}});var ju=Q((mR,Du)=>{var{T:R}=Bt(),rt=R,$0={read_file:R.tool_read,list_directory:R.tool_read,write_file:R.tool_write,edit_file:R.tool_write,patch_file:R.tool_write,bash:R.tool_exec,grep:R.tool_search,search_files:R.tool_search,glob:R.tool_search,git_commit:R.tool_git,git_push:R.tool_git,git_pull:R.tool_git,git_status:R.tool_git,git_diff:R.tool_git,git_log:R.tool_git,git_branch:R.tool_git,git_stash:R.tool_git,web_fetch:R.tool_web,web_search:R.tool_web,sysadmin:R.tool_sysadmin,ssh_exec:R.tool_sysadmin,ssh_upload:R.tool_sysadmin,ssh_download:R.tool_sysadmin,deploy:R.tool_sysadmin},xa={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 kr(t,e=!1,s=null){if(e)return`${R.error}\u23FA${R.reset}`;let n=$0[t]||R.tool_default;return s==="blink"?`${n}\x1B[5m\u23FA\x1B[25m${R.reset}`:`${n}${s!==null?s:"\u23FA"}${R.reset}`}function b0(t,e,s=!1,n=null){let o=(t||[]).filter(l=>l&&l.canExecute!==!1);if(o.length===0)return`${kr("",s,n)} Step ${e}`;if(o.length===1){let l=o[0],c=l.args||{},u=xa[l.fnName]||l.fnName.replace(/_/g," "),d="";c.path?d=c._originalPath||c.path:c.command?d=String(c.command).substring(0,80):c.query?d=String(c.query).substring(0,60):c.pattern?d=String(c.pattern).substring(0,60):c.url&&(d=String(c.url).substring(0,60));let f=d?`(${rt.dim}${d}${rt.reset})`:"";return`${kr(l.fnName,s,n)} ${rt.bold}${u}${rt.reset}${f}`}let r=o[0].fnName,i=[...new Set(o.map(l=>xa[l.fnName]||l.fnName.replace(/_/g," ")))],a=i.length<=3?i.join(", "):`${o.length} tools`;return`${kr(r,s,n)} ${rt.bold}${a}${rt.reset}`}function x0(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=xa[t]||t.replace(/_/g," "),o=s?`(${rt.dim}${s}${rt.reset})`:"";return`${kr(t)} ${rt.bold}${n}${rt.reset}${o}`}function k0(t,e=8){let s=t.split(`
16
+ `),n=s.slice(0,e),o=s.length-e,r=`${R.muted} \u23BF ${R.reset}`,i=" ",a=n.map((l,c)=>`${c===0?r:i}${R.success}${l}${R.reset}`).join(`
17
17
  `);return o>0&&(a+=`
18
- ${A.subtle} \u2026 +${o} lines${A.reset}`),a}var $r=["Sampling","Decoding","Attending","Inferring","Generating","Routing","Embedding","Reasoning","Tokenizing","Predicting"],Eu=Math.floor(Math.random()*$r.length),ya=null;function m0(t){ya=t}function g0(){let t=$r[Eu%$r.length];Eu++;let e=ya?` \xB7 ${ya}`:"";return`${t}${e}`}function y0(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`Searching ${e.pattern||"..."}`;case"grep":return`Searching ${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"Checking git status";case"git_diff":return`Diffing${e.file?` ${e.file}`:""}`;case"git_log":return`Reading 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}...`}}case"visual_diff":return"Comparing screenshots (pixel diff)...";case"responsive_sweep":return`Responsive sweep: ${(e.url||"").substring(0,50)}...`;case"visual_annotate":return`Annotating screenshot (${(e.annotations||[]).length} markers)...`;case"visual_watch":return`Visual watch: ${(e.url||"").substring(0,50)}...`;case"design_tokens":return"Extracting design tokens...";case"design_compare":return"Comparing against reference design...";default:return`Running: ${t}`}}function w0(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` ${A.muted}\u23BF blocked: ${d}${A.reset}`}let l=a.replace(/^ERROR:\s*/i,"").substring(0,80),c=o.match(/\nHINT: (.+)/),u=c?`
20
- ${A.muted}${c[1].substring(0,100)}${A.reset}`:"";return` ${A.error}\u23BF ${l}${A.reset}${u}`}let r;switch(t){case"read_file":{let l=o.split(`
21
- `).filter(Boolean).filter(g=>!/^File:\s/.test(g)&&!/^\[LARGE FILE:/.test(g)),c=l.length,u=l[l.length-1],d=u?parseInt(u.match(/^(\d+):/)?.[1]||"0"):0,f=e.line_start||e.line_end,p=e.path?require("path").basename(e.path):null,h=p?` ${A.muted}from ${p}${A.reset}`:"";f&&d>c?r=`Read lines ${e.line_start||1}\u2013${d}${h}`:r=`Read ${c} line${c!==1?"s":""}${h}`;break}case"write_file":{let l=(e.content||"").split(`
22
- `).length,c=e.path?require("path").basename(e.path):null,u=c?`Wrote ${c} \xB7 ${l} line${l!==1?"s":""}`:`Wrote ${l} line${l!==1?"s":""}`,{highlightLines:d}=ma(),f=d(e.content||"",e.path||null),p=40,h=8;if(l<=p){let g=f.map(_=>` ${_}`).join(`
18
+ ${R.subtle} \u2026 +${o} lines${R.reset}`),a}var Sr=["Sampling","Decoding","Attending","Inferring","Generating","Routing","Embedding","Reasoning","Tokenizing","Predicting"],Iu=Math.floor(Math.random()*Sr.length),ka=null;function S0(t){ka=t}function v0(){let t=Sr[Iu%Sr.length];Iu++;let e=ka?` \xB7 ${ka}`:"";return`${t}${e}`}function E0(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`Searching ${e.pattern||"..."}`;case"grep":return`Searching ${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"Checking git status";case"git_diff":return`Diffing${e.file?` ${e.file}`:""}`;case"git_log":return`Reading 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}...`}}case"visual_diff":return"Comparing screenshots (pixel diff)...";case"responsive_sweep":return`Responsive sweep: ${(e.url||"").substring(0,50)}...`;case"visual_annotate":return`Annotating screenshot (${(e.annotations||[]).length} markers)...`;case"visual_watch":return`Visual watch: ${(e.url||"").substring(0,50)}...`;case"design_tokens":return"Extracting design tokens...";case"design_compare":return"Comparing against reference design...";default:return`Running: ${t}`}}function T0(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` ${R.muted}\u23BF blocked: ${d}${R.reset}`}let l=a.replace(/^ERROR:\s*/i,"").substring(0,80),c=o.match(/\nHINT: (.+)/),u=c?`
20
+ ${R.muted}${c[1].substring(0,100)}${R.reset}`:"";return` ${R.error}\u23BF ${l}${R.reset}${u}`}let r;switch(t){case"read_file":{let l=o.split(`
21
+ `).filter(Boolean).filter(g=>!/^File:\s/.test(g)&&!/^\[LARGE FILE:/.test(g)),c=l.length,u=l[l.length-1],d=u?parseInt(u.match(/^(\d+):/)?.[1]||"0"):0,f=e.line_start||e.line_end,p=e.path?require("path").basename(e.path):null,m=p?` ${R.muted}from ${p}${R.reset}`:"";f&&d>c?r=`Read lines ${e.line_start||1}\u2013${d}${m}`:r=`Read ${c} line${c!==1?"s":""}${m}`;break}case"write_file":{let l=(e.content||"").split(`
22
+ `).length,c=e.path?require("path").basename(e.path):null,u=c?`Wrote ${c} \xB7 ${l} line${l!==1?"s":""}`:`Wrote ${l} line${l!==1?"s":""}`,{highlightLines:d}=ba(),f=d(e.content||"",e.path||null),p=40,m=8;if(l<=p){let g=f.map(_=>` ${_}`).join(`
23
23
  `);r=`${u}
24
- ${g}`}else{let g=f.slice(0,h).map(_=>` ${_}`).join(`
24
+ ${g}`}else{let g=f.slice(0,m).map(_=>` ${_}`).join(`
25
25
  `);r=`${u}
26
26
  ${g}
27
- ${A.subtle}\u2026 +${l-h} lines${A.reset}`}break}case"edit_file":{let a=(e.old_text||"").split(`
27
+ ${R.subtle}\u2026 +${l-m} lines${R.reset}`}break}case"edit_file":{let a=(e.old_text||"").split(`
28
28
  `),l=(e.new_text||"").split(`
29
- `),c=a.length,u=l.length,d=e.path?require("path").basename(e.path):null,f=d?` ${A.muted}${d}${A.reset}`:"",p=a.find(M=>M.trim()),h=l.find(M=>M.trim()),{highlightLine:g,detectLang:_}=ma(),b=_(e.path||null),O=[];p&&O.push(` ${A.diff_rem}- ${A.reset}${g(p.trimEnd().substring(0,72),b)}${A.reset}`),h&&O.push(` ${A.diff_add}+ ${A.reset}${g(h.trimEnd().substring(0,72),b)}${A.reset}`),r=`${A.diff_rem}\u2212${c}${A.reset} ${A.diff_add}+${u}${A.reset}${f}`+(O.length>0?`
30
- `+O.join(`
29
+ `),c=a.length,u=l.length,d=e.path?require("path").basename(e.path):null,f=d?` ${R.muted}${d}${R.reset}`:"",p=a.find(P=>P.trim()),m=l.find(P=>P.trim()),{highlightLine:g,detectLang:_}=ba(),b=_(e.path||null),A=[];p&&A.push(` ${R.diff_rem}- ${R.reset}${g(p.trimEnd().substring(0,72),b)}${R.reset}`),m&&A.push(` ${R.diff_add}+ ${R.reset}${g(m.trimEnd().substring(0,72),b)}${R.reset}`),r=`${R.diff_rem}\u2212${c}${R.reset} ${R.diff_add}+${u}${R.reset}${f}`+(A.length>0?`
30
+ `+A.join(`
31
31
  `):"");break}case"patch_file":{let a=e.patches||[],l=a.reduce((u,d)=>u+(d.old_text||"").split(`
32
32
  `).length,0),c=a.reduce((u,d)=>u+(d.new_text||"").split(`
33
- `).length,0);r=`${A.reset}${a.length} patch${a.length!==1?"es":""} ${A.diff_rem}\u2212${l}${A.reset} ${A.diff_add}+${c}${A.reset}`;break}case"bash":{let l=o.match(/^EXIT (\d+)/),c=o.split(`
34
- `).filter(f=>f&&!f.startsWith("EXIT ")&&!f.startsWith("HINT:")&&f.trim()),u=l?l[1]==="0"?`${A.success}\u2713${A.reset}`:`${A.error}\u2717 Exit ${l[1]}${A.reset}`:`${A.success}\u2713${A.reset}`,d=o.match(/\nHINT: (.+)/);if(d)r=`${u} ${A.muted}\u2014 ${d[1].substring(0,100)}${A.reset}`;else if(c.length===0)r=u;else{let f=l&&l[1]!=="0",p=f?c.slice(-3):c.slice(0,3),h=c.length-3,g=p.map((_,b)=>b===0?`${u} ${A.muted}${_.substring(0,120)}${A.reset}`:` ${A.muted}${_.substring(0,120)}${A.reset}`);if(h>0){let _=f?` ${A.subtle}${h} lines above\u2026${A.reset}`:` ${A.subtle}\u2026 +${h} lines${A.reset}`;f?g.unshift(_):g.push(_)}r=g.join(`
35
- `)}break}case"grep":case"search_files":{if(o.includes("(no matches)")||o==="no matches")r=`No matches${e.pattern?` ${A.muted}"${String(e.pattern).substring(0,40)}"${A.reset}`:""}`;else{let h=function(b){let O=b.indexOf(":");if(O===-1)return`${A.muted}${b.substring(0,90)}${A.reset}`;let M=b.substring(0,O),v=b.substring(O+1),T=v.match(/^(\d+)[:-](.*)/s),N=T?`:${T[1]}`:"",te=(T?T[2]:v).trim(),K=`${A.subtle}${a.basename(M)}${N}${A.reset}`,ie=`${A.muted}${te.substring(0,80)}${te.length>80?"\u2026":""}${A.reset}`;return`${K} ${ie}`};var i=h;let a=require("path"),l=o.split(`
36
- `).filter(Boolean),c=l.length,d=new Set(l.map(b=>b.split(":")[0]).filter(Boolean)).size,f=e.pattern?` ${A.muted}"${String(e.pattern).substring(0,40)}"${A.reset}`:"",p=d>1?`${c} match${c!==1?"es":""} in ${d} files${f}`:`${c} match${c!==1?"es":""}${f}`,g=l.slice(0,3).map((b,O)=>O===0?`${p}
37
- ${h(b)}`:` ${h(b)}`),_=l.length-3;_>0&&g.push(` ${A.subtle}\u2026 +${_} lines${A.reset}`),r=g.join(`
38
- `)}break}case"glob":{let a=e.pattern?` ${A.muted}${String(e.pattern).substring(0,50)}${A.reset}`:"";if(o==="(no matches)")r=`No files found${a}`;else{let l=require("path"),c=o.split(`
39
- `).filter(Boolean),u=c.length,d=c.slice(0,5).map(h=>l.basename(h)),f=u-d.length,p=d.join(", ")+(f>0?`, +${f} more`:"");r=`${u} file${u!==1?"s":""}${a} \u2014 ${A.muted}${p}${A.reset}`}break}case"list_directory":{if(o==="(empty)")r="0 entries";else{let a=o.split(`
40
- `).filter(Boolean),l=a.length,c=a.slice(0,6).join(", "),u=l-6;r=u>0?`${l} entries \u2014 ${A.muted}${c}, +${u} more${A.reset}`:`${l} entr${l!==1?"ies":"y"} \u2014 ${A.muted}${c}${A.reset}`}break}case"git_status":{let a=o.match(/Branch:\s*(\S+)/),l=o.split(`
33
+ `).length,0);r=`${R.reset}${a.length} patch${a.length!==1?"es":""} ${R.diff_rem}\u2212${l}${R.reset} ${R.diff_add}+${c}${R.reset}`;break}case"bash":{let l=o.match(/^EXIT (\d+)/),c=o.split(`
34
+ `).filter(f=>f&&!f.startsWith("EXIT ")&&!f.startsWith("HINT:")&&f.trim()),u=l?l[1]==="0"?`${R.success}\u2713${R.reset}`:`${R.error}\u2717 Exit ${l[1]}${R.reset}`:`${R.success}\u2713${R.reset}`,d=o.match(/\nHINT: (.+)/);if(d)r=`${u} ${R.muted}\u2014 ${d[1].substring(0,100)}${R.reset}`;else if(c.length===0)r=u;else{let f=l&&l[1]!=="0",p=f?c.slice(-3):c.slice(0,3),m=c.length-3,g=p.map((_,b)=>b===0?`${u} ${R.muted}${_.substring(0,120)}${R.reset}`:` ${R.muted}${_.substring(0,120)}${R.reset}`);if(m>0){let _=f?` ${R.subtle}${m} lines above\u2026${R.reset}`:` ${R.subtle}\u2026 +${m} lines${R.reset}`;f?g.unshift(_):g.push(_)}r=g.join(`
35
+ `)}break}case"grep":case"search_files":{if(o.includes("(no matches)")||o==="no matches")r=`No matches${e.pattern?` ${R.muted}"${String(e.pattern).substring(0,40)}"${R.reset}`:""}`;else{let m=function(b){let A=b.indexOf(":");if(A===-1)return`${R.muted}${b.substring(0,90)}${R.reset}`;let P=b.substring(0,A),v=b.substring(A+1),E=v.match(/^(\d+)[:-](.*)/s),O=E?`:${E[1]}`:"",ne=(E?E[2]:v).trim(),J=`${R.subtle}${a.basename(P)}${O}${R.reset}`,ie=`${R.muted}${ne.substring(0,80)}${ne.length>80?"\u2026":""}${R.reset}`;return`${J} ${ie}`};var i=m;let a=require("path"),l=o.split(`
36
+ `).filter(Boolean),c=l.length,d=new Set(l.map(b=>b.split(":")[0]).filter(Boolean)).size,f=e.pattern?` ${R.muted}"${String(e.pattern).substring(0,40)}"${R.reset}`:"",p=d>1?`${c} match${c!==1?"es":""} in ${d} files${f}`:`${c} match${c!==1?"es":""}${f}`,g=l.slice(0,3).map((b,A)=>A===0?`${p}
37
+ ${m(b)}`:` ${m(b)}`),_=l.length-3;_>0&&g.push(` ${R.subtle}\u2026 +${_} lines${R.reset}`),r=g.join(`
38
+ `)}break}case"glob":{let a=e.pattern?` ${R.muted}${String(e.pattern).substring(0,50)}${R.reset}`:"";if(o==="(no matches)")r=`No files found${a}`;else{let l=require("path"),c=o.split(`
39
+ `).filter(Boolean),u=c.length,d=c.slice(0,5).map(m=>l.basename(m)),f=u-d.length,p=d.join(", ")+(f>0?`, +${f} more`:"");r=`${u} file${u!==1?"s":""}${a} \u2014 ${R.muted}${p}${R.reset}`}break}case"list_directory":{if(o==="(empty)")r="0 entries";else{let a=o.split(`
40
+ `).filter(Boolean),l=a.length,c=a.slice(0,6).join(", "),u=l-6;r=u>0?`${l} entries \u2014 ${R.muted}${c}, +${u} more${R.reset}`:`${l} entr${l!==1?"ies":"y"} \u2014 ${R.muted}${c}${R.reset}`}break}case"git_status":{let a=o.match(/Branch:\s*(\S+)/),l=o.split(`
41
41
  `).filter(c=>/^\s*[MADRCU?!]/.test(c)).length;r=a?`${a[1]} \xB7 ${l} change${l!==1?"s":""}`:"Done";break}case"git_diff":{let a=(o.match(/^\+[^+]/gm)||[]).length,l=(o.match(/^-[^-]/gm)||[]).length;r=a||l?`+${a} \u2212${l} lines`:"No diff";break}case"git_log":{let a=o.split(`
42
42
  `).filter(d=>/^commit\s+[0-9a-f]{7}/.test(d)),l=a.length,c=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((p,h)=>h>0&&p.trim()&&!p.startsWith("Author:")&&!p.startsWith("Date:")&&!p.startsWith("Merge:"))})();if(l===0)r="Log retrieved";else if(c&&u){let d=l>1?` ${A.muted}+${l-1} more${A.reset}`:"";r=`${c} ${A.muted}${u.trim().substring(0,60)}${A.reset}${d}`}else r=`${l} commit${l!==1?"s":""}`;break}case"git_commit":{let a=o.match(/\[[\w./\-]+ ([0-9a-f]{7,})\]/),l=o.match(/\[[\w./\-]+ [0-9a-f]+\]\s+(.+)/);r=a?`${a[1]}${l?` \u2014 ${l[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),l=o.match(/^#\s+(.{1,80})/m),c=e.url||"",u="";try{u=new URL(c).hostname}catch{u=c.substring(0,60)}let d=a?a[1].trim():l?l[1].trim():null;r=d?`${u} \u2014 ${A.muted}${d.substring(0,70)}${A.reset}`:`Fetched ${u}`;break}case"web_search":{let a=o.split(`
43
+ `).find((p,m)=>m>0&&p.trim()&&!p.startsWith("Author:")&&!p.startsWith("Date:")&&!p.startsWith("Merge:"))})();if(l===0)r="Log retrieved";else if(c&&u){let d=l>1?` ${R.muted}+${l-1} more${R.reset}`:"";r=`${c} ${R.muted}${u.trim().substring(0,60)}${R.reset}${d}`}else r=`${l} commit${l!==1?"s":""}`;break}case"git_commit":{let a=o.match(/\[[\w./\-]+ ([0-9a-f]{7,})\]/),l=o.match(/\[[\w./\-]+ [0-9a-f]+\]\s+(.+)/);r=a?`${a[1]}${l?` \u2014 ${l[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),l=o.match(/^#\s+(.{1,80})/m),c=e.url||"",u="";try{u=new URL(c).hostname}catch{u=c.substring(0,60)}let d=a?a[1].trim():l?l[1].trim():null;r=d?`${u} \u2014 ${R.muted}${d.substring(0,70)}${R.reset}`:`Fetched ${u}`;break}case"web_search":{let a=o.split(`
44
44
 
45
45
  `).filter(Boolean),l=a.length,c=a[0]?a[0].split(`
46
- `)[0].replace(/^\d+\.\s*/,"").trim():null,u=c?` ${A.muted}\u2014 ${c.substring(0,70)}${A.reset}`:"";r=`${l} result${l!==1?"s":""}${u}`;break}case"task_list":r="Done";break;case"spawn_agents":{let a=(o.match(/✓ Agent/g)||[]).length,l=(o.match(/✗ Agent/g)||[]).length;r=l>0?`${a} done, ${l} 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 l=o.startsWith("EXIT ")||o.startsWith("Command failed"),c=o.split(`
47
- `).filter(d=>d.trim()&&!d.startsWith("EXIT ")),u=l?`${A.error}\u2717${A.reset}`:`${A.success}\u2713${A.reset}`;if(c.length===0)r=u;else{if(c.length>2&&c.every(g=>/^\[/.test(g.trim()))){r=`${u} ${c.length} log lines`;break}let f=l?c.slice(-3):c.slice(0,3),p=c.length-3,h=f.map((g,_)=>_===0?`${u} ${A.muted}${g.substring(0,120)}${A.reset}`:` ${A.muted}${g.substring(0,120)}${A.reset}`);if(p>0){let g=l?` ${A.subtle}${p} lines above\u2026${A.reset}`:` ${A.subtle}\u2026 +${p} lines${A.reset}`;l?h.unshift(g):h.push(g)}r=h.join(`
46
+ `)[0].replace(/^\d+\.\s*/,"").trim():null,u=c?` ${R.muted}\u2014 ${c.substring(0,70)}${R.reset}`:"";r=`${l} result${l!==1?"s":""}${u}`;break}case"task_list":r="Done";break;case"spawn_agents":{if(o.includes("Background agents started")){let c=o.match(/\bbg-[\w-]+/g),u=c?c.length:0;r=`${u} bg agent${u!==1?"s":""} started`;break}let a=(o.match(/✓ Agent/g)||[]).length,l=(o.match(/✗ Agent/g)||[]).length;r=l>0?`${a} done, ${l} 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 l=o.startsWith("EXIT ")||o.startsWith("Command failed"),c=o.split(`
47
+ `).filter(d=>d.trim()&&!d.startsWith("EXIT ")),u=l?`${R.error}\u2717${R.reset}`:`${R.success}\u2713${R.reset}`;if(c.length===0)r=u;else{if(c.length>2&&c.every(g=>/^\[/.test(g.trim()))){r=`${u} ${c.length} log lines`;break}let f=l?c.slice(-3):c.slice(0,3),p=c.length-3,m=f.map((g,_)=>_===0?`${u} ${R.muted}${g.substring(0,120)}${R.reset}`:` ${R.muted}${g.substring(0,120)}${R.reset}`);if(p>0){let g=l?` ${R.subtle}${p} lines above\u2026${R.reset}`:` ${R.subtle}\u2026 +${p} lines${R.reset}`;l?m.unshift(g):m.push(g)}r=m.join(`
48
48
  `)}break}default:{let a=o.split(`
49
- `).filter(l=>l.trim()&&!l.startsWith("EXIT ")&&!l.startsWith("HINT:"));if(a.length>0){let l=a[0].trim().substring(0,90),c=a.length>1?` ${A.subtle}\u2026 +${a.length-1} lines${A.reset}`:"";r=`${A.muted}${l}${A.reset}${c}`}else r="Done"}}return` ${A.muted}\u23BF ${r}${A.reset}`}function _0(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`,l=`
50
- ${A.success}\u25C6${rt.reset} ${rt.bold}${t}${rt.reset}`;return l+=`${rt.dim} \xB7 ${a}`,r.size>0&&(l+=` \xB7 ${r.size} file${r.size!==1?"s":""} modified`),l+=rt.reset,l}Tu.exports={C:rt,formatToolCall:p0,formatResult:h0,getToolSpinnerText:y0,formatToolSummary:w0,formatSectionHeader:f0,formatMilestone:_0,getThinkingVerb:g0,setActiveModelForSpinner:m0,THINKING_VERBS:$r}});var Ke=Z((JT,Au)=>{var{T:$n}=Bt(),wa=$n,Cu=["01100110","01111110","01111110","01011010","01111110","00111100"];function $0(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 b0(t,e,s={}){let n=wa.bold,o=wa.reset,r=$0(Cu,$n.banner_logo),i=s.yolo?` ${n}${$n.banner_yolo}\u26A1 YOLO${o}`:"",a=s.gemini?` ${n}${$n.banner_gemini}\u2726 GEMINI${o}`:"",l=mr().version,c=[` ${$n.banner_name}${n}nex-code${o} ${$n.banner_version}v${l}${o}`,` ${$n.banner_model}${t}${o} ${$n.muted}\xB7 /help${o}${a}${i}`,""],u=Math.max(r.length,c.length),d=Math.floor((u-r.length)/2),f=Math.floor((u-c.length)/2),p=Cu[0].length,h=[];for(let g=0;g<u;g++){let _=r[g-d]??" ".repeat(p),b=c[g-f]??"";h.push(_+b)}console.log(`
51
- `+h.join(`
49
+ `).filter(l=>l.trim()&&!l.startsWith("EXIT ")&&!l.startsWith("HINT:"));if(a.length>0){let l=a[0].trim().substring(0,90),c=a.length>1?` ${R.subtle}\u2026 +${a.length-1} lines${R.reset}`:"";r=`${R.muted}${l}${R.reset}${c}`}else r="Done"}}return` ${R.muted}\u23BF ${r}${R.reset}`}function R0(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`,l=`
50
+ ${R.success}\u25C6${rt.reset} ${rt.bold}${t}${rt.reset}`;return l+=`${rt.dim} \xB7 ${a}`,r.size>0&&(l+=` \xB7 ${r.size} file${r.size!==1?"s":""} modified`),l+=rt.reset,l}Du.exports={C:rt,formatToolCall:x0,formatResult:k0,getToolSpinnerText:E0,formatToolSummary:T0,formatSectionHeader:b0,formatMilestone:R0,getThinkingVerb:v0,setActiveModelForSpinner:S0,THINKING_VERBS:Sr}});var Ke=Q((gR,Fu)=>{var{T:_n}=Bt(),Sa=_n,qu=["01100110","01111110","01111110","01011010","01111110","00111100"];function C0(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 A0(t,e,s={}){let n=Sa.bold,o=Sa.reset,r=C0(qu,_n.banner_logo),i=s.yolo?` ${n}${_n.banner_yolo}\u26A1 YOLO${o}`:"",a=s.gemini?` ${n}${_n.banner_gemini}\u2726 GEMINI${o}`:"",l=_r().version,c=[` ${_n.banner_name}${n}nex-code${o} ${_n.banner_version}v${l}${o}`,` ${_n.banner_model}${t}${o} ${_n.muted}\xB7 /help${o}${a}${i}`,""],u=Math.max(r.length,c.length),d=Math.floor((u-r.length)/2),f=Math.floor((u-c.length)/2),p=qu[0].length,m=[];for(let g=0;g<u;g++){let _=r[g-d]??" ".repeat(p),b=c[g-f]??"";m.push(_+b)}console.log(`
51
+ `+m.join(`
52
52
  `)+`
53
- `)}var{Spinner:x0,MultiProgress:k0,TaskProgress:S0,ToolProgress:v0,setActiveTaskProgress:E0,getActiveTaskProgress:T0,cleanupTerminal:R0}=bs(),{formatToolCall:C0,formatResult:A0,getToolSpinnerText:O0,formatToolSummary:N0,formatSectionHeader:M0,formatMilestone:P0,getThinkingVerb:L0,setActiveModelForSpinner:I0}=Ru();Au.exports={C:wa,banner:b0,Spinner:x0,MultiProgress:k0,TaskProgress:S0,ToolProgress:v0,setActiveTaskProgress:E0,getActiveTaskProgress:T0,cleanupTerminal:R0,formatToolCall:C0,formatResult:A0,getToolSpinnerText:O0,formatToolSummary:N0,formatSectionHeader:M0,formatMilestone:P0,getThinkingVerb:L0,setActiveModelForSpinner:I0}});var xs=Z((ZT,Ou)=>{async function D0(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",l=>a.push(l)),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 _a=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`)}};Ou.exports={BaseProvider:_a,readStreamErrorBody:D0}});var vs=Z((QT,Mu)=>{var ks=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")}},Ss=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")}},br=class extends Ss{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!==void 0&&i.index!==null?a=i.index:i.id?a=`id:${i.id}`:a=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}}))}}},xr=class extends ks{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 br(e,s)}},kr=class extends Ss{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}}})}}},$a="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->",Sr=class extends ks{getEndpoint(){return"/messages"}buildRequestBody({model:e,messages:s,tools:n,maxTokens:o,temperature:r,stream:i,extra:a}){let l={model:e,messages:s,max_tokens:o,temperature:r};if(i&&(l.stream=!0),a?.system){let c=a.system,u=c.indexOf($a);if(u!==-1){let d=c.slice(0,u).trimEnd(),f=c.slice(u+$a.length).trimStart();l.system=[{type:"text",text:d},{type:"text",text:f,cache_control:{type:"ephemeral"}}]}else l.system=c}return n&&n.length>0&&(l.tools=n),l}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 kr(e,s)}};function Nu(t){if(t!==null&&typeof t=="object")return t;if(typeof t!="string")return t||{};try{return JSON.parse(t)}catch{}let e=t.replace(/,\s*([}\]])/g,"$1");e=e.replace(/([^\\])\n/g,"$1\\n");try{return JSON.parse(e)}catch{}return{}}var vr=class extends Ss{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:Nu(e.function?.arguments??e.arguments)}}))}}},Er=class extends ks{getEndpoint(){return"/api/chat"}buildRequestBody({model:e,messages:s,tools:n,maxTokens:o,temperature:r,stream:i,extra:a}){let l={model:e,messages:s,stream:i,options:{temperature:r,num_predict:o,repeat_penalty:a?.repeat_penalty??1.05}};return n&&n.length>0&&(l.tools=n),l}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:Nu(n.function?.arguments??n.arguments)}}))}}createStreamParser(e,s={}){return new vr(e,s)}},j0=new xr,q0=new Sr,F0=new Er;Mu.exports={ANTHROPIC_CACHE_BOUNDARY:$a,WireProtocol:ks,StreamParser:Ss,OpenAICompatibleProtocol:xr,AnthropicProtocol:Sr,OllamaChatProtocol:Er,OpenAIStreamParser:br,AnthropicStreamParser:kr,OllamaStreamParser:vr,openaiProtocol:j0,anthropicProtocol:q0,ollamaProtocol:F0}});var Iu=Z((eR,Lu)=>{var Tr=require("axios"),B0=require("http"),U0=require("https"),{BaseProvider:W0,readStreamErrorBody:H0}=xs(),{ollamaProtocol:Dn}=vs(),Rr=new B0.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Cr=new U0.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Pu={"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},"gemma4:e2b":{id:"gemma4:e2b",name:"Gemma 4 E2B",maxTokens:8192,contextWindow:131072},"gemma4:e4b":{id:"gemma4:e4b",name:"Gemma 4 E4B",maxTokens:8192,contextWindow:131072},"gemma4:26b-a4b":{id:"gemma4:26b-a4b",name:"Gemma 4 26B A4B",maxTokens:16384,contextWindow:262144},"gemma4:31b":{id:"gemma4:31b",name:"Gemma 4 31B",maxTokens:16384,contextWindow:262144},"gemma4:31b-cloud":{id:"gemma4:31b-cloud",name:"Gemma 4 31B Cloud",maxTokens:16384,contextWindow:262144},"gemini-3-flash-preview":{id:"gemini-3-flash-preview",name:"Gemini 3 Flash Preview",maxTokens:16384,contextWindow:131072}},ba=class extends W0{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||Pu,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){Tr.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Rr,httpsAgent:Cr}).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 Tr.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Rr,httpsAgent:Cr})).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(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:s.role,content:n.join(`
55
- `)};return o.length>0&&(r.images=o),s.tool_call_id&&(r.tool_call_id=s.tool_call_id),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=Dn.buildRequestBody({model:o,messages:this._formatMessages(e),tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!1,extra:{repeat_penalty:n.repeat_penalty}}),l;try{l=await Tr.post(`${this.baseUrl}${Dn.getEndpoint()}`,a,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),httpAgent:Rr,httpsAgent:Cr})}catch(c){if(c.name==="CanceledError"||c.name==="AbortError"||c.code==="ERR_CANCELED")throw c;let u=c.response?.status?` [HTTP ${c.response.status}]`:"",d=c.response?.data?.error||c.message;throw new Error(`API Error${u}: ${d}`)}return Dn.normalizeResponse(l.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||(()=>{}),l=n.onThinkingToken||(()=>{}),c=Dn.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 Tr.post(`${this.baseUrl}${Dn.getEndpoint()}`,c,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal,httpAgent:Rr,httpsAgent:Cr})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let p=f.response?.status?` [HTTP ${f.response.status}]`:"",h=await H0(f,_=>_?.error),g=new Error(`API Error${p}: ${h}`);throw g.code=f.code||(f.response?.status?`HTTP_${f.response.status}`:void 0),g}let d=Dn.createStreamParser(a,{onThinkingToken:l});return new Promise((f,p)=>{n.signal&&n.signal.addEventListener("abort",()=>{u.data.destroy(),p(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",h=>{let{done:g,result:_}=d.feed(h.toString());g&&f(_)}),u.data.on("error",h=>{if(n.signal?.aborted)return;let g=new Error(`Stream error: ${h.message}`);g.code=h.code||h.name,p(g)}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return Dn.normalizeResponse(e)}};Lu.exports={OllamaProvider:ba,OLLAMA_MODELS:Pu}});var Fu=Z((tR,qu)=>{var Du=require("axios"),{BaseProvider:Y0,readStreamErrorBody:G0}=xs(),{openaiProtocol:jn}=vs(),ju={"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}},xa=class extends Y0{constructor(e={}){super({name:"openai",baseUrl:e.baseUrl||"https://api.openai.com/v1",models:e.models||ju,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"){let s;return Array.isArray(e.content)?s=e.content.filter(o=>o.type==="text").map(o=>o.text).join(`
56
- `)||JSON.stringify(e.content):s=typeof e.content=="string"?e.content:JSON.stringify(e.content),{role:"tool",content:s,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),l=jn.buildRequestBody({model:o,messages:a,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!1}),c;try{c=await Du.post(`${this.baseUrl}${jn.getEndpoint()}`,l,{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 jn.normalizeResponse(c.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:l}=this.formatMessages(e),c=jn.buildRequestBody({model:o,messages:l,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!0}),u;try{u=await Du.post(`${this.baseUrl}${jn.getEndpoint()}`,c,{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 p=f.response?.status?` [HTTP ${f.response.status}]`:"",h=await G0(f,g=>g?.error?.message||g?.error);throw new Error(`API Error${p}: ${h}`)}let d=jn.createStreamParser(a);return new Promise((f,p)=>{n.signal&&n.signal.addEventListener("abort",()=>{u.data.destroy(),p(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",h=>{let{done:g,result:_}=d.feed(h.toString());g&&f(_)}),u.data.on("error",h=>{n.signal?.aborted||p(new Error(`Stream error: ${h.message}`))}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return jn.normalizeResponse(e)}};qu.exports={OpenAIProvider:xa,OPENAI_MODELS:ju}});var Hu=Z((nR,Wu)=>{var Bu=require("axios"),{BaseProvider:z0,readStreamErrorBody:K0}=xs(),{anthropicProtocol:bn}=vs(),Uu={"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}},X0="2023-06-01",ka=class extends z0{constructor(e={}){super({name:"anthropic",baseUrl:e.baseUrl||"https://api.anthropic.com/v1",models:e.models||Uu,defaultModel:e.defaultModel||"claude-sonnet",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this.apiVersion=e.apiVersion||X0}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?`
57
-
58
- `:"")+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;if(Array.isArray(e.content)){let i=[];for(let a of e.content)a.type==="text"?i.push({type:"text",text:a.text??""}):a.type==="image"&&a.data&&i.push({type:"image",source:{type:"base64",media_type:a.media_type||"image/png",data:a.data}});o=i}else o=typeof e.content=="string"?e.content:JSON.stringify(e.content);let r={type:"tool_result",tool_use_id:e.tool_call_id,content:o};return n&&n.role==="user"&&Array.isArray(n.content)&&n.content[0]?.type==="tool_result"?(n.content.push(r),null):{role:"user",content:[r]}}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 bn.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:l,system:c}=this.formatMessages(e),u=this.formatTools(s),d=bn.buildRequestBody({model:r,messages:l,tools:u,maxTokens:a,temperature:n.temperature??this.temperature,stream:!1,extra:{system:c}}),f;try{f=await Bu.post(`${this.baseUrl}${bn.getEndpoint()}`,d,{timeout:n.timeout||this.timeout,headers:this._getHeaders()})}catch(p){if(p.name==="CanceledError"||p.name==="AbortError"||p.code==="ERR_CANCELED")throw p;let h=p.response?.status?` [HTTP ${p.response.status}]`:"",g=p.response?.data?.error?.message||p.response?.data?.error||p.message;throw new Error(`API Error${h}: ${g}`)}return bn.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,l=n.onToken||(()=>{}),{messages:c,system:u}=this.formatMessages(e),d=this.formatTools(s),f=bn.buildRequestBody({model:r,messages:c,tools:d,maxTokens:a,temperature:n.temperature??this.temperature,stream:!0,extra:{system:u}}),p;try{p=await Bu.post(`${this.baseUrl}${bn.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 _=g.response?.status?` [HTTP ${g.response.status}]`:"",b=await K0(g,O=>O?.error?.message||O?.error);throw new Error(`API Error${_}: ${b}`)}let h=bn.createStreamParser(l);return new Promise((g,_)=>{n.signal&&n.signal.addEventListener("abort",()=>{p.data.destroy(),_(new DOMException("The operation was aborted","AbortError"))},{once:!0}),p.data.on("data",b=>{let{done:O,result:M}=h.feed(b.toString());O&&g(M)}),p.data.on("error",b=>{n.signal?.aborted||_(new Error(`Stream error: ${b.message}`))}),p.data.on("end",()=>{g(h.flush())})})}normalizeResponse(e){return bn.normalizeResponse(e)}};Wu.exports={AnthropicProvider:ka,ANTHROPIC_MODELS:Uu}});var Ku=Z((sR,zu)=>{var Yu=require("axios"),{BaseProvider:V0,readStreamErrorBody:J0}=xs(),{openaiProtocol:qn}=vs(),Gu={"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}},Sa=class extends V0{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||Gu,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),l=qn.buildRequestBody({model:o,messages:a,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!1}),c;try{c=await Yu.post(`${this.baseUrl}${qn.getEndpoint()}`,l,{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 qn.normalizeResponse(c.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:l}=this.formatMessages(e),c=qn.buildRequestBody({model:o,messages:l,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!0}),u;try{u=await Yu.post(`${this.baseUrl}${qn.getEndpoint()}`,c,{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 p=f.response?.status?` [HTTP ${f.response.status}]`:"",h=await J0(f,g=>g?.error?.message||g?.error);throw new Error(`API Error${p}: ${h}`)}let d=qn.createStreamParser(a);return new Promise((f,p)=>{n.signal&&n.signal.addEventListener("abort",()=>{u.data.destroy(),p(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",h=>{let{done:g,result:_}=d.feed(h.toString());g&&f(_)}),u.data.on("error",h=>{n.signal?.aborted||p(new Error(`Stream error: ${h.message}`))}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return qn.normalizeResponse(e)}};zu.exports={GeminiProvider:Sa,GEMINI_MODELS:Gu}});var Ju=Z((oR,Vu)=>{var Ar=require("axios"),{BaseProvider:Z0,readStreamErrorBody:Q0}=xs(),{ollamaProtocol:Fn}=vs(),Xu="http://localhost:11434",va=class extends Z0{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||Xu,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 Ar.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 Ar.post(`${this.baseUrl}/api/show`,{name:o},{timeout:5e3}),l=a.data?.model_info||a.data?.details||{};i=l["general.context_length"]||l["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(`
59
- `)};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=Fn.buildRequestBody({model:o,messages:this._formatMessages(e),tools:s,maxTokens:n.maxTokens||8192,temperature:n.temperature??this.temperature,stream:!1}),i;try{i=await Ar.post(`${this.baseUrl}${Fn.getEndpoint()}`,r,{timeout:n.timeout||this.timeout})}catch(a){if(a.name==="CanceledError"||a.name==="AbortError"||a.code==="ERR_CANCELED")throw a;let l=a.response?.status?` [HTTP ${a.response.status}]`:"",c=a.response?.data?.error||a.message;throw new Error(`API Error${l}: ${c}`)}return Fn.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=Fn.buildRequestBody({model:o,messages:this._formatMessages(e),tools:s,maxTokens:n.maxTokens||8192,temperature:n.temperature??this.temperature,stream:!0}),a;try{a=await Ar.post(`${this.baseUrl}${Fn.getEndpoint()}`,i,{timeout:n.timeout||this.timeout,responseType:"stream",signal:n.signal})}catch(c){if(c.name==="CanceledError"||c.name==="AbortError"||c.code==="ERR_CANCELED")throw c;let u=c.response?.status?` [HTTP ${c.response.status}]`:"",d=await Q0(c,f=>f?.error);throw new Error(`API Error${u}: ${d}`)}let l=Fn.createStreamParser(r);return new Promise((c,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:p}=l.feed(d.toString());f&&c(p)}),a.data.on("error",d=>{n.signal?.aborted||u(new Error(`Stream error: ${d.message}`))}),a.data.on("end",()=>{c(l.flush())})})}normalizeResponse(e){return Fn.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}};Vu.exports={LocalProvider:va,DEFAULT_LOCAL_URL:Xu}});var Bn=Z((rR,Qu)=>{"use strict";var xt=require("fs"),Zu=require("path");function ew(t){if(!t||isNaN(t))return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function tw(t){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}catch{let e=Date.now()+t;for(;Date.now()<e;);}}function nw(t,e){let s=Zu.dirname(t),n=Zu.join(s,`.nex-tmp.${process.pid}.${Date.now()}`);try{xt.existsSync(s)||xt.mkdirSync(s,{recursive:!0,mode:448}),xt.writeFileSync(n,e,{encoding:"utf-8",mode:384}),xt.renameSync(n,t)}catch(o){try{xt.unlinkSync(n)}catch{}throw o}}function sw(t,e,{timeout:s=5e3,retryMs:n=50}={}){let o=t+".lock",r=Date.now()+s;for(;;){let i=-1;try{i=xt.openSync(o,"wx"),xt.writeSync(i,Buffer.from(String(process.pid))),xt.closeSync(i),i=-1;try{return e()}finally{try{xt.unlinkSync(o)}catch{}}}catch(a){if(i!==-1)try{xt.closeSync(i)}catch{}if(a.code!=="EEXIST")throw a;try{let l=xt.readFileSync(o,"utf-8").trim(),c=parseInt(l,10);if(!ew(c)){try{xt.unlinkSync(o)}catch{}continue}}catch(l){if(l.code&&l.code!=="ENOENT")throw l;continue}if(Date.now()>=r){try{xt.unlinkSync(o)}catch{}return e()}tw(n)}}}Qu.exports={atomicWrite:nw,withFileLockSync:sw}});var Nr=Z((iR,ad)=>{var Es=require("fs"),Ea=require("path"),{T:ed}=Bt(),{atomicWrite:ow,withFileLockSync:rw}=Bn(),td={openai:{"gpt-4o":{input:2.5,output:10},"gpt-4o-mini":{input:.15,output:.6},"gpt-4.1":{input:2,output:8},"gpt-4.1-mini":{input:.4,output:1.6},"gpt-4.1-nano":{input:.1,output:.4},o1:{input:15,output:60},o3:{input:10,output:40},"o3-mini":{input:1.1,output:4.4},"o4-mini":{input:1.1,output:4.4}},anthropic:{"claude-sonnet":{input:3,output:15},"claude-opus":{input:5,output:25},"claude-haiku":{input:.8,output:4},"claude-sonnet-4-5":{input:3,output:15},"claude-sonnet-4":{input:3,output:15}},gemini:{"gemini-2.5-pro":{input:1.25,output:10},"gemini-2.5-flash":{input:.15,output:.6},"gemini-2.0-flash":{input:.1,output:.4},"gemini-2.0-flash-lite":{input:.075,output:.3}},ollama:{"qwen3-coder:480b":{input:0,output:0},"qwen3-coder-next":{input:0,output:0},"devstral-2:123b":{input:0,output:0},"devstral-small-2:24b":{input:0,output:0},"kimi-k2.5":{input:0,output:0},"kimi-k2:1t":{input:0,output:0},"deepseek-v3.2":{input:0,output:0},"minimax-m2.5":{input:0,output:0},"glm-5":{input:0,output:0},"glm-4.7":{input:0,output:0},"gpt-oss:120b":{input:0,output:0}},local:{}},Or=[],xn={};function iw(t,e,s,n,o=0){if(Or.push({provider:t,model:e,input:s,output:n,cacheRead:o}),xn[t]!==void 0){let r=rd(t);r.allowed||process.stderr.write(`${ed.yellow}\u26A0 Budget limit reached for ${t}: $${r.spent.toFixed(2)} / $${r.limit.toFixed(2)}${ed.reset}
60
- `)}}function Ta(t,e){let s=td[t];return s?s[e]||{input:0,output:0}:{input:0,output:0}}function nd(t){let e=Ta(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function sd(){let t={};for(let i of Or){let a=`${i.provider}:${i.model}`;t[a]||(t[a]={provider:i.provider,model:i.model,requests:0,input:0,output:0,cacheRead:0}),t[a].requests++,t[a].input+=i.input,t[a].output+=i.output,t[a].cacheRead+=i.cacheRead||0}let e=Object.values(t).map(i=>({...i,cost:nd(i)})),s=e.reduce((i,a)=>i+a.cost,0),n=e.reduce((i,a)=>i+a.input,0),o=e.reduce((i,a)=>i+a.output,0),r=e.reduce((i,a)=>i+(a.cacheRead||0),0);return{totalCost:s,totalInput:n,totalOutput:o,totalCacheRead:r,breakdown:e}}function aw(){let{totalCost:t,totalInput:e,totalOutput:s,breakdown:n}=sd();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(`
61
- `)}function lw(t){return!t||typeof t!="string"?0:Math.ceil(t.length/4)}function cw(t,e,s,n){let o=Ta(t,e),r=(s*o.input+n*o.output)/1e6;return r<=0?"":`[~$${r.toFixed(4)}]`}function uw(){Or=[]}function dw(t,e){xn[t]=e}function fw(t){delete xn[t]}function pw(){return{...xn}}function od(t){let e=0;for(let s of Or)s.provider===t&&(e+=nd(s));return e}function rd(t){let e=od(t),s=xn[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 id(){let t=Ea.join(process.cwd(),".nex","config.json");if(Es.existsSync(t))try{let e=JSON.parse(Es.readFileSync(t,"utf-8"));e.costLimits&&typeof e.costLimits=="object"&&(xn={...e.costLimits})}catch{}}function hw(){let t=Ea.join(process.cwd(),".nex"),e=Ea.join(t,"config.json");Es.existsSync(t)||Es.mkdirSync(t,{recursive:!0}),rw(e,()=>{let s={};if(Es.existsSync(e))try{s=JSON.parse(Es.readFileSync(e,"utf-8"))}catch{s={}}s.costLimits=xn,ow(e,JSON.stringify(s,null,2))})}function mw(){xn={}}id();ad.exports={PRICING:td,trackUsage:iw,getSessionCosts:sd,formatCosts:aw,formatCostHint:cw,resetCosts:uw,getPricing:Ta,setCostLimit:dw,removeCostLimit:fw,getCostLimits:pw,getProviderSpend:od,checkBudget:rd,loadCostLimits:id,saveCostLimits:hw,resetCostLimits:mw,estimateTokens:lw}});var Ca=Z((aR,ld)=>{function Ra(){return process.env.NEX_DEBUG==="true"||process.argv.includes("--debug")}var gw=Ra();function yw(...t){Ra()&&console.log(...t)}function ww(...t){Ra()&&console.warn(...t)}ld.exports={DEBUG:gw,debugLog:yw,warnLog:ww}});var dd=Z((lR,ud)=>{"use strict";var _w=new Set(["read_file","grep","glob","search_files","list_directory"]),$w=new Set(["write_file","edit_file","patch_file"]),bw=new Set(["bash"]),xw=new Set(["web_search","web_fetch","perplexity_search"]);function cd(t,e){let s=0,n=0,o=0,r=0,i=0;for(let[a,l]of t)i+=l,_w.has(a)&&(s+=l),$w.has(a)&&(n+=l),bw.has(a)&&(o+=l),xw.has(a)&&(r+=l);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 Aa=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:cd(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}};ud.exports={MilestoneTracker:Aa,_phaseName:cd}});var ao=Z((cR,fd)=>{var io=Ze(),kw={"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 Sw(){return io.getActiveModel()}function vw(t){return io.setActiveModel(t)}function Ew(){return io.getModelNames()}function Tw(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 Rw(t,e){let{C:s}=Ke(),{Spinner:n}=Ke(),o=new n("Thinking...");o.start();let r=!0,i="";try{let a=await io.callStream(t,e,{onToken:l=>{r&&(o.stop(),process.stdout.write(`${s.blue}`),r=!1),process.stdout.write(l),i+=l}});return r?o.stop():process.stdout.write(`${s.reset}
62
- `),a}catch(a){throw o.stop(),a}}async function Cw(t,e){return io.callChat(t,e)}fd.exports={MODELS:kw,getActiveModel:Sw,setActiveModel:vw,getModelNames:Ew,callOllamaStream:Rw,callOllama:Cw,parseToolArgs:Tw}});var co=Z((uR,wd)=>{var Aw=require("readline"),{C:Vt}=Ke(),Ow=/[\u200B\u200C\u200D\uFEFF\u2060\u00AD]/g,Nw=/^=([\w-]+)/;function lo(t){return typeof t!="string"?t:t.replace(Ow,"").replace(Nw,"$1")}var Ma=[/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/],pd=[...Ma,/\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 Mw(t){for(let e of pd)if(e.test(t))return e;return null}var hd=[/\.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)/],Pw=/\b(?:rm|rmdir|unlink|truncate|shred|mv|cp)\b/,Oa=[/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 md(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(c=>c.trim()).filter(Boolean).every(c=>o(c)):Oa.some(l=>l.test(r))}return/^\w+=\$?\(/.test(i)||/^\w+=["']/.test(i)||/^\w+=\S/.test(i)?!0:Oa.some(a=>a.test(i))};return n.every(o)}var Pa=[/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)/,/\b(?:curl|wget|fetch)\b[^|;&`$()]*\|\s*(?:sh|bash|zsh|ksh|dash|python|python3|perl|ruby|node)\b/,/\b(?:curl|wget)\b[^;&`$()]*\$\([^)]*\)/,/\bbase64\s+(?:-d|--decode|-D)\b[^|;&`$()]*\|\s*(?:sh|bash|zsh|python|python3|perl|ruby|node)\b/,/\beval\s+["'`]?\$\(\s*(?:curl|wget|fetch)\b/,/\bbash\s+-i\s*>&?\s*\/dev\/tcp\//,/\bnc\s+(?:-[a-z]*e|-[a-z]*c)\b/,/\bmkfifo\b[^;&`]*;\s*(?:nc|ncat|telnet)\b/],gd=[/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/],yd=[...Pa,...gd],La=!1,Un=null,Na=null;function Lw(t){La=t}function Iw(t){Na=t}function Dw(){return La}function jw(t){Un=t}function qw(t){let e=lo(t);for(let s of Ma)if(s.test(e))return s;return null}function Fw(t){let e=lo(t);if(/ssh\s/.test(e)&&md(e))return!1;for(let s of yd)if(s.test(e))return!0;return!1}function Bw(t){let e=lo(t);for(let s of Pa)if(s.test(e))return!0;return!1}function Uw(t){if(process.env.NEX_UNPROTECT==="1")return null;let e=lo(t);if(!Pw.test(e))return null;for(let s of hd)if(s.test(e))return s;return null}function Ww(t,e={}){if(La)return Promise.resolve(!0);if(Na)return Na(t,e);if(!process.stdout.isTTY||!process.stdin.isTTY)return Hw(t,e);let s=e.toolName?["Yes","No","Always allow"]:["Yes","No"];return new Promise(n=>{let o=0;Un&&Un.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();global._nexRawWrite&&d>1&&global._nexRawWrite(`\x1B[1;${d-1}r`);let f=`\x1B[${d};1H\x1B[2K${Vt.yellow}${t}${Vt.reset}`;for(let p=0;p<s.length;p++){let h=p===o,g=h?`${Vt.yellow}\u276F${Vt.reset}`:" ",_=h?`${Vt.yellow}${s[p]}${Vt.reset}`:s[p];f+=`\x1B[${d+1+p};1H\x1B[2K ${g} ${_}`}r(f)},l=d=>{process.stdin.setRawMode(!1),process.stdin.pause(),process.stdin.removeListener("data",u);let f=global._nexRawWrite||(g=>process.stdout.write(g)),p=i(),h="";for(let g=0;g<s.length+1;g++)h+=`\x1B[${p+g};1H\x1B[2K`;f(h),global._nexRawWrite&&global._nexFooter&&global._nexRawWrite(`\x1B[1;${global._nexFooter._scrollEnd}r`),global._nexFooter&&global._nexFooter.drawFooter(),Un&&Un.resume(),n(d)},c=d=>{if(d===1){l(!1);return}d===2&&e.toolName&&Mr(e.toolName),l(!0)},u=d=>{if(d[0]===3){l(!1);return}let f=d.toString();if(f==="\r"||f===`
63
- `){c(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 p=f.toLowerCase().trim();if(p==="y"){l(!0);return}if(p==="n"){l(!1);return}if(p==="a"&&e.toolName){Mr(e.toolName),l(!0);return}};a(),process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",u)})}function Hw(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?(Mr(e.toolName),n(!0)):n(i!=="n")};if(Un)Un.question(`${Vt.yellow}${t} ${s}${Vt.reset}`,o);else{let r=Aw.createInterface({input:process.stdin,output:process.stdout});r.question(`${Vt.yellow}${t} ${s}${Vt.reset}`,i=>{r.close(),o(i)})}})}var Mr=()=>{};function Yw(t){Mr=t}wd.exports={sanitizeBashCommand:lo,FORBIDDEN_PATTERNS:Ma,SSH_FORBIDDEN_PATTERNS:pd,BASH_PROTECTED_PATHS:hd,SSH_SAFE_PATTERNS:Oa,isSSHReadOnly:md,DANGEROUS_BASH:yd,CRITICAL_BASH:Pa,NOTABLE_BASH:gd,isForbidden:qw,isSSHForbidden:Mw,isDangerous:Fw,isCritical:Bw,isBashPathForbidden:Uw,confirm:Ww,setAutoConfirm:Lw,getAutoConfirm:Dw,setConfirmHook:Iw,setReadlineInterface:jw,setAllowAlwaysHandler:Yw}});var bd=Z((fR,$d)=>{var Pr=require("path"),{C:B}=Ke(),{T:Ia,isDark:dR}=Bt(),{confirm:Gw,getAutoConfirm:zw}=co(),_d=2e3;function uo(t,e){let s=t.split(`
53
+ `)}var{Spinner:O0,MultiProgress:N0,TaskProgress:M0,ToolProgress:P0,setActiveTaskProgress:L0,getActiveTaskProgress:I0,cleanupTerminal:D0}=ks(),{formatToolCall:j0,formatResult:q0,getToolSpinnerText:F0,formatToolSummary:B0,formatSectionHeader:U0,formatMilestone:W0,getThinkingVerb:H0,setActiveModelForSpinner:Y0}=ju();Fu.exports={C:Sa,banner:A0,Spinner:O0,MultiProgress:N0,TaskProgress:M0,ToolProgress:P0,setActiveTaskProgress:L0,getActiveTaskProgress:I0,cleanupTerminal:D0,formatToolCall:j0,formatResult:q0,getToolSpinnerText:F0,formatToolSummary:B0,formatSectionHeader:U0,formatMilestone:W0,getThinkingVerb:H0,setActiveModelForSpinner:Y0}});var Ss=Q((yR,Bu)=>{async function G0(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",l=>a.push(l)),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 va=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`)}};Bu.exports={BaseProvider:va,readStreamErrorBody:G0}});var Ts=Q((wR,Wu)=>{var vs=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")}},Es=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")}},vr=class extends Es{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!==void 0&&i.index!==null?a=i.index:i.id?a=`id:${i.id}`:a=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}}))}}},Er=class extends vs{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 vr(e,s)}},Tr=class extends Es{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}}})}}},Ea="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->",Rr=class extends vs{getEndpoint(){return"/messages"}buildRequestBody({model:e,messages:s,tools:n,maxTokens:o,temperature:r,stream:i,extra:a}){let l={model:e,messages:s,max_tokens:o,temperature:r};if(i&&(l.stream=!0),a?.system){let c=a.system,u=c.indexOf(Ea);if(u!==-1){let d=c.slice(0,u).trimEnd(),f=c.slice(u+Ea.length).trimStart();l.system=[{type:"text",text:d},{type:"text",text:f,cache_control:{type:"ephemeral"}}]}else l.system=c}return n&&n.length>0&&(l.tools=n),l}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 Tr(e,s)}};function Uu(t){if(t!==null&&typeof t=="object")return t;if(typeof t!="string")return t||{};try{return JSON.parse(t)}catch{}let e=t.replace(/,\s*([}\]])/g,"$1");e=e.replace(/([^\\])\n/g,"$1\\n");try{return JSON.parse(e)}catch{}return{}}var Cr=class extends Es{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:Uu(e.function?.arguments??e.arguments)}}))}}},Ar=class extends vs{getEndpoint(){return"/api/chat"}buildRequestBody({model:e,messages:s,tools:n,maxTokens:o,temperature:r,stream:i,extra:a}){let l={model:e,messages:s,stream:i,options:{temperature:r,num_predict:o,repeat_penalty:a?.repeat_penalty??1.05}};return n&&n.length>0&&(l.tools=n),l}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:Uu(n.function?.arguments??n.arguments)}}))}}createStreamParser(e,s={}){return new Cr(e,s)}},z0=new Er,K0=new Rr,X0=new Ar;Wu.exports={ANTHROPIC_CACHE_BOUNDARY:Ea,WireProtocol:vs,StreamParser:Es,OpenAICompatibleProtocol:Er,AnthropicProtocol:Rr,OllamaChatProtocol:Ar,OpenAIStreamParser:vr,AnthropicStreamParser:Tr,OllamaStreamParser:Cr,openaiProtocol:z0,anthropicProtocol:K0,ollamaProtocol:X0}});var Gu=Q((_R,Yu)=>{var Or=require("axios"),V0=require("http"),J0=require("https"),{BaseProvider:Z0,readStreamErrorBody:Q0}=Ss(),{ollamaProtocol:In}=Ts(),Nr=new V0.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Mr=new J0.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Hu={"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},"gemma4:e2b":{id:"gemma4:e2b",name:"Gemma 4 E2B",maxTokens:8192,contextWindow:131072},"gemma4:e4b":{id:"gemma4:e4b",name:"Gemma 4 E4B",maxTokens:8192,contextWindow:131072},"gemma4:26b-a4b":{id:"gemma4:26b-a4b",name:"Gemma 4 26B A4B",maxTokens:16384,contextWindow:262144},"gemma4:31b":{id:"gemma4:31b",name:"Gemma 4 31B",maxTokens:16384,contextWindow:262144},"gemma4:31b-cloud":{id:"gemma4:31b-cloud",name:"Gemma 4 31B Cloud",maxTokens:16384,contextWindow:262144},"gemini-3-flash-preview":{id:"gemini-3-flash-preview",name:"Gemini 3 Flash Preview",maxTokens:16384,contextWindow:131072}},Ta=class extends Z0{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||Hu,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){Or.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Nr,httpsAgent:Mr}).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 Or.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Nr,httpsAgent:Mr})).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(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:s.role,content:n.join(`
55
+ `)};return o.length>0&&(r.images=o),s.tool_call_id&&(r.tool_call_id=s.tool_call_id),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=In.buildRequestBody({model:o,messages:this._formatMessages(e),tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!1,extra:{repeat_penalty:n.repeat_penalty}}),l;try{l=await Or.post(`${this.baseUrl}${In.getEndpoint()}`,a,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),httpAgent:Nr,httpsAgent:Mr})}catch(c){if(c.name==="CanceledError"||c.name==="AbortError"||c.code==="ERR_CANCELED")throw c;let u=c.response?.status?` [HTTP ${c.response.status}]`:"",d=c.response?.data?.error||c.message;throw new Error(`API Error${u}: ${d}`)}return In.normalizeResponse(l.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||(()=>{}),l=n.onThinkingToken||(()=>{}),c=In.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 Or.post(`${this.baseUrl}${In.getEndpoint()}`,c,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal,httpAgent:Nr,httpsAgent:Mr})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let p=f.response?.status?` [HTTP ${f.response.status}]`:"",m=await Q0(f,_=>_?.error),g=new Error(`API Error${p}: ${m}`);throw g.code=f.code||(f.response?.status?`HTTP_${f.response.status}`:void 0),g}let d=In.createStreamParser(a,{onThinkingToken:l});return new Promise((f,p)=>{n.signal&&n.signal.addEventListener("abort",()=>{u.data.destroy(),p(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",m=>{let{done:g,result:_}=d.feed(m.toString());g&&f(_)}),u.data.on("error",m=>{if(n.signal?.aborted)return;let g=new Error(`Stream error: ${m.message}`);g.code=m.code||m.name,p(g)}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return In.normalizeResponse(e)}};Yu.exports={OllamaProvider:Ta,OLLAMA_MODELS:Hu}});var Vu=Q(($R,Xu)=>{var zu=require("axios"),{BaseProvider:ew,readStreamErrorBody:tw}=Ss(),{openaiProtocol:Dn}=Ts(),Ku={"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}},Ra=class extends ew{constructor(e={}){super({name:"openai",baseUrl:e.baseUrl||"https://api.openai.com/v1",models:e.models||Ku,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"){let s;return Array.isArray(e.content)?s=e.content.filter(o=>o.type==="text").map(o=>o.text).join(`
56
+ `)||JSON.stringify(e.content):s=typeof e.content=="string"?e.content:JSON.stringify(e.content),{role:"tool",content:s,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),l=Dn.buildRequestBody({model:o,messages:a,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!1}),c;try{c=await zu.post(`${this.baseUrl}${Dn.getEndpoint()}`,l,{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 Dn.normalizeResponse(c.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:l}=this.formatMessages(e),c=Dn.buildRequestBody({model:o,messages:l,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!0}),u;try{u=await zu.post(`${this.baseUrl}${Dn.getEndpoint()}`,c,{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 p=f.response?.status?` [HTTP ${f.response.status}]`:"",m=await tw(f,g=>g?.error?.message||g?.error);throw new Error(`API Error${p}: ${m}`)}let d=Dn.createStreamParser(a);return new Promise((f,p)=>{n.signal&&n.signal.addEventListener("abort",()=>{u.data.destroy(),p(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",m=>{let{done:g,result:_}=d.feed(m.toString());g&&f(_)}),u.data.on("error",m=>{n.signal?.aborted||p(new Error(`Stream error: ${m.message}`))}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return Dn.normalizeResponse(e)}};Xu.exports={OpenAIProvider:Ra,OPENAI_MODELS:Ku}});var ed=Q((bR,Qu)=>{var Ju=require("axios"),{BaseProvider:nw,readStreamErrorBody:sw}=Ss(),{anthropicProtocol:$n}=Ts(),Zu={"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}},ow="2023-06-01",Ca=class extends nw{constructor(e={}){super({name:"anthropic",baseUrl:e.baseUrl||"https://api.anthropic.com/v1",models:e.models||Zu,defaultModel:e.defaultModel||"claude-sonnet",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this.apiVersion=e.apiVersion||ow}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?`
57
+
58
+ `:"")+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;if(Array.isArray(e.content)){let i=[];for(let a of e.content)a.type==="text"?i.push({type:"text",text:a.text??""}):a.type==="image"&&a.data&&i.push({type:"image",source:{type:"base64",media_type:a.media_type||"image/png",data:a.data}});o=i}else o=typeof e.content=="string"?e.content:JSON.stringify(e.content);let r={type:"tool_result",tool_use_id:e.tool_call_id,content:o};return n&&n.role==="user"&&Array.isArray(n.content)&&n.content[0]?.type==="tool_result"?(n.content.push(r),null):{role:"user",content:[r]}}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 $n.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:l,system:c}=this.formatMessages(e),u=this.formatTools(s),d=$n.buildRequestBody({model:r,messages:l,tools:u,maxTokens:a,temperature:n.temperature??this.temperature,stream:!1,extra:{system:c}}),f;try{f=await Ju.post(`${this.baseUrl}${$n.getEndpoint()}`,d,{timeout:n.timeout||this.timeout,headers:this._getHeaders()})}catch(p){if(p.name==="CanceledError"||p.name==="AbortError"||p.code==="ERR_CANCELED")throw p;let m=p.response?.status?` [HTTP ${p.response.status}]`:"",g=p.response?.data?.error?.message||p.response?.data?.error||p.message;throw new Error(`API Error${m}: ${g}`)}return $n.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,l=n.onToken||(()=>{}),{messages:c,system:u}=this.formatMessages(e),d=this.formatTools(s),f=$n.buildRequestBody({model:r,messages:c,tools:d,maxTokens:a,temperature:n.temperature??this.temperature,stream:!0,extra:{system:u}}),p;try{p=await Ju.post(`${this.baseUrl}${$n.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 _=g.response?.status?` [HTTP ${g.response.status}]`:"",b=await sw(g,A=>A?.error?.message||A?.error);throw new Error(`API Error${_}: ${b}`)}let m=$n.createStreamParser(l);return new Promise((g,_)=>{n.signal&&n.signal.addEventListener("abort",()=>{p.data.destroy(),_(new DOMException("The operation was aborted","AbortError"))},{once:!0}),p.data.on("data",b=>{let{done:A,result:P}=m.feed(b.toString());A&&g(P)}),p.data.on("error",b=>{n.signal?.aborted||_(new Error(`Stream error: ${b.message}`))}),p.data.on("end",()=>{g(m.flush())})})}normalizeResponse(e){return $n.normalizeResponse(e)}};Qu.exports={AnthropicProvider:Ca,ANTHROPIC_MODELS:Zu}});var od=Q((xR,sd)=>{var td=require("axios"),{BaseProvider:rw,readStreamErrorBody:iw}=Ss(),{openaiProtocol:jn}=Ts(),nd={"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}},Aa=class extends rw{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||nd,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),l=jn.buildRequestBody({model:o,messages:a,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!1}),c;try{c=await td.post(`${this.baseUrl}${jn.getEndpoint()}`,l,{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 jn.normalizeResponse(c.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:l}=this.formatMessages(e),c=jn.buildRequestBody({model:o,messages:l,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!0}),u;try{u=await td.post(`${this.baseUrl}${jn.getEndpoint()}`,c,{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 p=f.response?.status?` [HTTP ${f.response.status}]`:"",m=await iw(f,g=>g?.error?.message||g?.error);throw new Error(`API Error${p}: ${m}`)}let d=jn.createStreamParser(a);return new Promise((f,p)=>{n.signal&&n.signal.addEventListener("abort",()=>{u.data.destroy(),p(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",m=>{let{done:g,result:_}=d.feed(m.toString());g&&f(_)}),u.data.on("error",m=>{n.signal?.aborted||p(new Error(`Stream error: ${m.message}`))}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return jn.normalizeResponse(e)}};sd.exports={GeminiProvider:Aa,GEMINI_MODELS:nd}});var ad=Q((kR,id)=>{var Pr=require("axios"),{BaseProvider:aw,readStreamErrorBody:lw}=Ss(),{ollamaProtocol:qn}=Ts(),rd="http://localhost:11434",Oa=class extends aw{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||rd,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 Pr.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 Pr.post(`${this.baseUrl}/api/show`,{name:o},{timeout:5e3}),l=a.data?.model_info||a.data?.details||{};i=l["general.context_length"]||l["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(`
59
+ `)};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=qn.buildRequestBody({model:o,messages:this._formatMessages(e),tools:s,maxTokens:n.maxTokens||8192,temperature:n.temperature??this.temperature,stream:!1}),i;try{i=await Pr.post(`${this.baseUrl}${qn.getEndpoint()}`,r,{timeout:n.timeout||this.timeout})}catch(a){if(a.name==="CanceledError"||a.name==="AbortError"||a.code==="ERR_CANCELED")throw a;let l=a.response?.status?` [HTTP ${a.response.status}]`:"",c=a.response?.data?.error||a.message;throw new Error(`API Error${l}: ${c}`)}return qn.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=qn.buildRequestBody({model:o,messages:this._formatMessages(e),tools:s,maxTokens:n.maxTokens||8192,temperature:n.temperature??this.temperature,stream:!0}),a;try{a=await Pr.post(`${this.baseUrl}${qn.getEndpoint()}`,i,{timeout:n.timeout||this.timeout,responseType:"stream",signal:n.signal})}catch(c){if(c.name==="CanceledError"||c.name==="AbortError"||c.code==="ERR_CANCELED")throw c;let u=c.response?.status?` [HTTP ${c.response.status}]`:"",d=await lw(c,f=>f?.error);throw new Error(`API Error${u}: ${d}`)}let l=qn.createStreamParser(r);return new Promise((c,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:p}=l.feed(d.toString());f&&c(p)}),a.data.on("error",d=>{n.signal?.aborted||u(new Error(`Stream error: ${d.message}`))}),a.data.on("end",()=>{c(l.flush())})})}normalizeResponse(e){return qn.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}};id.exports={LocalProvider:Oa,DEFAULT_LOCAL_URL:rd}});var Fn=Q((SR,cd)=>{"use strict";var xt=require("fs"),ld=require("path");function cw(t){if(!t||isNaN(t))return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function uw(t){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}catch{let e=Date.now()+t;for(;Date.now()<e;);}}function dw(t,e){let s=ld.dirname(t),n=ld.join(s,`.nex-tmp.${process.pid}.${Date.now()}`);try{xt.existsSync(s)||xt.mkdirSync(s,{recursive:!0,mode:448}),xt.writeFileSync(n,e,{encoding:"utf-8",mode:384}),xt.renameSync(n,t)}catch(o){try{xt.unlinkSync(n)}catch{}throw o}}function fw(t,e,{timeout:s=5e3,retryMs:n=50}={}){let o=t+".lock",r=Date.now()+s;for(;;){let i=-1;try{i=xt.openSync(o,"wx"),xt.writeSync(i,Buffer.from(String(process.pid))),xt.closeSync(i),i=-1;try{return e()}finally{try{xt.unlinkSync(o)}catch{}}}catch(a){if(i!==-1)try{xt.closeSync(i)}catch{}if(a.code!=="EEXIST")throw a;try{let l=xt.readFileSync(o,"utf-8").trim(),c=parseInt(l,10);if(!cw(c)){try{xt.unlinkSync(o)}catch{}continue}}catch(l){if(l.code&&l.code!=="ENOENT")throw l;continue}if(Date.now()>=r){try{xt.unlinkSync(o)}catch{}return e()}uw(n)}}}cd.exports={atomicWrite:dw,withFileLockSync:fw}});var Ir=Q((vR,yd)=>{var Rs=require("fs"),Na=require("path"),{T:ud}=Bt(),{atomicWrite:pw,withFileLockSync:hw}=Fn(),dd={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:{}},Lr=[],bn={};function mw(t,e,s,n,o=0){if(Lr.push({provider:t,model:e,input:s,output:n,cacheRead:o}),bn[t]!==void 0){let r=md(t);r.allowed||process.stderr.write(`${ud.yellow}\u26A0 Budget limit reached for ${t}: $${r.spent.toFixed(2)} / $${r.limit.toFixed(2)}${ud.reset}
60
+ `)}}function Ma(t,e){let s=dd[t];return s?s[e]||{input:0,output:0}:{input:0,output:0}}function fd(t){let e=Ma(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function pd(){let t={};for(let i of Lr){let a=`${i.provider}:${i.model}`;t[a]||(t[a]={provider:i.provider,model:i.model,requests:0,input:0,output:0,cacheRead:0}),t[a].requests++,t[a].input+=i.input,t[a].output+=i.output,t[a].cacheRead+=i.cacheRead||0}let e=Object.values(t).map(i=>({...i,cost:fd(i)})),s=e.reduce((i,a)=>i+a.cost,0),n=e.reduce((i,a)=>i+a.input,0),o=e.reduce((i,a)=>i+a.output,0),r=e.reduce((i,a)=>i+(a.cacheRead||0),0);return{totalCost:s,totalInput:n,totalOutput:o,totalCacheRead:r,breakdown:e}}function gw(){let{totalCost:t,totalInput:e,totalOutput:s,breakdown:n}=pd();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(`
61
+ `)}function yw(t){return!t||typeof t!="string"?0:Math.ceil(t.length/4)}function ww(t,e,s,n){let o=Ma(t,e),r=(s*o.input+n*o.output)/1e6;return r<=0?"":`[~$${r.toFixed(4)}]`}function _w(){Lr=[]}function $w(t,e){bn[t]=e}function bw(t){delete bn[t]}function xw(){return{...bn}}function hd(t){let e=0;for(let s of Lr)s.provider===t&&(e+=fd(s));return e}function md(t){let e=hd(t),s=bn[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 gd(){let t=Na.join(process.cwd(),".nex","config.json");if(Rs.existsSync(t))try{let e=JSON.parse(Rs.readFileSync(t,"utf-8"));e.costLimits&&typeof e.costLimits=="object"&&(bn={...e.costLimits})}catch{}}function kw(){let t=Na.join(process.cwd(),".nex"),e=Na.join(t,"config.json");Rs.existsSync(t)||Rs.mkdirSync(t,{recursive:!0}),hw(e,()=>{let s={};if(Rs.existsSync(e))try{s=JSON.parse(Rs.readFileSync(e,"utf-8"))}catch{s={}}s.costLimits=bn,pw(e,JSON.stringify(s,null,2))})}function Sw(){bn={}}gd();yd.exports={PRICING:dd,trackUsage:mw,getSessionCosts:pd,formatCosts:gw,formatCostHint:ww,resetCosts:_w,getPricing:Ma,setCostLimit:$w,removeCostLimit:bw,getCostLimits:xw,getProviderSpend:hd,checkBudget:md,loadCostLimits:gd,saveCostLimits:kw,resetCostLimits:Sw,estimateTokens:yw}});var La=Q((ER,wd)=>{function Pa(){return process.env.NEX_DEBUG==="true"||process.argv.includes("--debug")}var vw=Pa();function Ew(...t){Pa()&&console.log(...t)}function Tw(...t){Pa()&&console.warn(...t)}wd.exports={DEBUG:vw,debugLog:Ew,warnLog:Tw}});var bd=Q((TR,$d)=>{"use strict";var Rw=new Set(["read_file","grep","glob","search_files","list_directory"]),Cw=new Set(["write_file","edit_file","patch_file"]),Aw=new Set(["bash"]),Ow=new Set(["web_search","web_fetch","perplexity_search"]);function _d(t,e){let s=0,n=0,o=0,r=0,i=0;for(let[a,l]of t)i+=l,Rw.has(a)&&(s+=l),Cw.has(a)&&(n+=l),Aw.has(a)&&(o+=l),Ow.has(a)&&(r+=l);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 Ia=class{constructor(e){this._N=e,this._disabled=e<=0,this._phaseNum=0,this._stepsThisPhase=0,this._phaseCounts=new Map,this._phaseStart=Date.now()}record(e,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:_d(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}};$d.exports={MilestoneTracker:Ia,_phaseName:_d}});var fo=Q((RR,xd)=>{var uo=Qe(),Nw={"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 Mw(){return uo.getActiveModel()}function Pw(t){return uo.setActiveModel(t)}function Lw(){return uo.getModelNames()}function Iw(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 Dw(t,e){let{C:s}=Ke(),{Spinner:n}=Ke(),o=new n("Thinking...");o.start();let r=!0,i="";try{let a=await uo.callStream(t,e,{onToken:l=>{r&&(o.stop(),process.stdout.write(`${s.blue}`),r=!1),process.stdout.write(l),i+=l}});return r?o.stop():process.stdout.write(`${s.reset}
62
+ `),a}catch(a){throw o.stop(),a}}async function jw(t,e){return uo.callChat(t,e)}xd.exports={MODELS:Nw,getActiveModel:Mw,setActiveModel:Pw,getModelNames:Lw,callOllamaStream:Dw,callOllama:jw,parseToolArgs:Iw}});var ho=Q((CR,Rd)=>{var qw=require("readline"),{C:Vt}=Ke(),Fw=/[\u200B\u200C\u200D\uFEFF\u2060\u00AD]/g,Bw=/^=([\w-]+)/;function po(t){return typeof t!="string"?t:t.replace(Fw,"").replace(Bw,"$1")}var qa=[/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/],kd=[...qa,/\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 Uw(t){for(let e of kd)if(e.test(t))return e;return null}var Sd=[/\.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)/],Ww=/\b(?:rm|rmdir|unlink|truncate|shred|mv|cp)\b/,Da=[/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 vd(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(c=>c.trim()).filter(Boolean).every(c=>o(c)):Da.some(l=>l.test(r))}return/^\w+=\$?\(/.test(i)||/^\w+=["']/.test(i)||/^\w+=\S/.test(i)?!0:Da.some(a=>a.test(i))};return n.every(o)}var Fa=[/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)/,/\b(?:curl|wget|fetch)\b[^|;&`$()]*\|\s*(?:sh|bash|zsh|ksh|dash|python|python3|perl|ruby|node)\b/,/\b(?:curl|wget)\b[^;&`$()]*\$\([^)]*\)/,/\bbase64\s+(?:-d|--decode|-D)\b[^|;&`$()]*\|\s*(?:sh|bash|zsh|python|python3|perl|ruby|node)\b/,/\beval\s+["'`]?\$\(\s*(?:curl|wget|fetch)\b/,/\bbash\s+-i\s*>&?\s*\/dev\/tcp\//,/\bnc\s+(?:-[a-z]*e|-[a-z]*c)\b/,/\bmkfifo\b[^;&`]*;\s*(?:nc|ncat|telnet)\b/],Ed=[/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/],Td=[...Fa,...Ed],Ba=!1,Bn=null,ja=null;function Hw(t){Ba=t}function Yw(t){ja=t}function Gw(){return Ba}function zw(t){Bn=t}function Kw(t){let e=po(t);for(let s of qa)if(s.test(e))return s;return null}function Xw(t){let e=po(t);if(/ssh\s/.test(e)&&vd(e))return!1;for(let s of Td)if(s.test(e))return!0;return!1}function Vw(t){let e=po(t);for(let s of Fa)if(s.test(e))return!0;return!1}function Jw(t){if(process.env.NEX_UNPROTECT==="1")return null;let e=po(t);if(!Ww.test(e))return null;for(let s of Sd)if(s.test(e))return s;return null}function Zw(t,e={}){if(Ba)return Promise.resolve(!0);if(ja)return ja(t,e);if(!process.stdout.isTTY||!process.stdin.isTTY)return Qw(t,e);let s=e.toolName?["Yes","No","Always allow"]:["Yes","No"];return new Promise(n=>{let o=0;Bn&&Bn.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();global._nexRawWrite&&d>1&&global._nexRawWrite(`\x1B[1;${d-1}r`);let f=`\x1B[${d};1H\x1B[2K${Vt.yellow}${t}${Vt.reset}`;for(let p=0;p<s.length;p++){let m=p===o,g=m?`${Vt.yellow}\u276F${Vt.reset}`:" ",_=m?`${Vt.yellow}${s[p]}${Vt.reset}`:s[p];f+=`\x1B[${d+1+p};1H\x1B[2K ${g} ${_}`}r(f)},l=d=>{process.stdin.setRawMode(!1),process.stdin.pause(),process.stdin.removeListener("data",u);let f=global._nexRawWrite||(g=>process.stdout.write(g)),p=i(),m="";for(let g=0;g<s.length+1;g++)m+=`\x1B[${p+g};1H\x1B[2K`;f(m),global._nexRawWrite&&global._nexFooter&&global._nexRawWrite(`\x1B[1;${global._nexFooter._scrollEnd}r`),global._nexFooter&&global._nexFooter.drawFooter(),Bn&&Bn.resume(),n(d)},c=d=>{if(d===1){l(!1);return}d===2&&e.toolName&&Dr(e.toolName),l(!0)},u=d=>{if(d[0]===3){l(!1);return}let f=d.toString();if(f==="\r"||f===`
63
+ `){c(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 p=f.toLowerCase().trim();if(p==="y"){l(!0);return}if(p==="n"){l(!1);return}if(p==="a"&&e.toolName){Dr(e.toolName),l(!0);return}};a(),process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",u)})}function Qw(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?(Dr(e.toolName),n(!0)):n(i!=="n")};if(Bn)Bn.question(`${Vt.yellow}${t} ${s}${Vt.reset}`,o);else{let r=qw.createInterface({input:process.stdin,output:process.stdout});r.question(`${Vt.yellow}${t} ${s}${Vt.reset}`,i=>{r.close(),o(i)})}})}var Dr=()=>{};function e_(t){Dr=t}Rd.exports={sanitizeBashCommand:po,FORBIDDEN_PATTERNS:qa,SSH_FORBIDDEN_PATTERNS:kd,BASH_PROTECTED_PATHS:Sd,SSH_SAFE_PATTERNS:Da,isSSHReadOnly:vd,DANGEROUS_BASH:Td,CRITICAL_BASH:Fa,NOTABLE_BASH:Ed,isForbidden:Kw,isSSHForbidden:Uw,isDangerous:Xw,isCritical:Vw,isBashPathForbidden:Jw,confirm:Zw,setAutoConfirm:Hw,getAutoConfirm:Gw,setConfirmHook:Yw,setReadlineInterface:zw,setAllowAlwaysHandler:e_}});var Od=Q((OR,Ad)=>{var jr=require("path"),{C:B}=Ke(),{T:Ua,isDark:AR}=Bt(),{confirm:t_,getAutoConfirm:n_}=ho(),Cd=2e3;function mo(t,e){let s=t.split(`
64
64
  `),n=e.split(`
65
- `),o=[],r=s.length,i=n.length;if(r>_d||i>_d){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 l=r,c=i,u=[];for(;l>0||c>0;)l>0&&c>0&&s[l-1]===n[c-1]?(u.unshift({type:"same",line:s[l-1]}),l--,c--):c>0&&(l===0||a[l][c-1]>=a[l-1][c])?(u.unshift({type:"add",line:n[c-1]}),c--):(u.unshift({type:"remove",line:s[l-1]}),l--);return u}function Kw(t,e,s,n=3){console.log(`
66
- ${B.bold}${B.cyan} Diff: ${t}${B.reset}`);let o=uo(e,s),r=[];if(o.forEach((l,c)=>{l.type!=="same"&&r.push(c)}),r.length===0){console.log(`${B.gray} (no changes)${B.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(`${B.gray} ...${B.reset}`);for(let l=i;l<a;l++){let c=o[l];switch(c.type){case"remove":console.log(`${B.red} - ${c.line}${B.reset}`);break;case"add":console.log(`${B.green} + ${c.line}${B.reset}`);break;default:console.log(`${B.gray} ${c.line}${B.reset}`)}}a<o.length&&console.log(`${B.gray} ...${B.reset}`),console.log()}function Xw(t,e,s){console.log(`
67
- ${B.bold}${B.cyan} File exists \u2014 showing changes: ${t}${B.reset}`);let n=uo(e,s),o=0;for(let i of n)i.type!=="same"&&o++;if(o===0){console.log(`${B.gray} (identical content)${B.reset}`);return}let r=0;for(let i of n){if(r>=30){console.log(`${B.gray} ...(${o-r} more changes)${B.reset}`);break}switch(i.type){case"remove":console.log(`${B.red} - ${i.line}${B.reset}`),r++;break;case"add":console.log(`${B.green} + ${i.line}${B.reset}`),r++;break;default:r>0&&console.log(`${B.gray} ${i.line}${B.reset}`)}}console.log()}function Vw(t,e){console.log(`
65
+ `),o=[],r=s.length,i=n.length;if(r>Cd||i>Cd){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 l=r,c=i,u=[];for(;l>0||c>0;)l>0&&c>0&&s[l-1]===n[c-1]?(u.unshift({type:"same",line:s[l-1]}),l--,c--):c>0&&(l===0||a[l][c-1]>=a[l-1][c])?(u.unshift({type:"add",line:n[c-1]}),c--):(u.unshift({type:"remove",line:s[l-1]}),l--);return u}function s_(t,e,s,n=3){console.log(`
66
+ ${B.bold}${B.cyan} Diff: ${t}${B.reset}`);let o=mo(e,s),r=[];if(o.forEach((l,c)=>{l.type!=="same"&&r.push(c)}),r.length===0){console.log(`${B.gray} (no changes)${B.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(`${B.gray} ...${B.reset}`);for(let l=i;l<a;l++){let c=o[l];switch(c.type){case"remove":console.log(`${B.red} - ${c.line}${B.reset}`);break;case"add":console.log(`${B.green} + ${c.line}${B.reset}`);break;default:console.log(`${B.gray} ${c.line}${B.reset}`)}}a<o.length&&console.log(`${B.gray} ...${B.reset}`),console.log()}function o_(t,e,s){console.log(`
67
+ ${B.bold}${B.cyan} File exists \u2014 showing changes: ${t}${B.reset}`);let n=mo(e,s),o=0;for(let i of n)i.type!=="same"&&o++;if(o===0){console.log(`${B.gray} (identical content)${B.reset}`);return}let r=0;for(let i of n){if(r>=30){console.log(`${B.gray} ...(${o-r} more changes)${B.reset}`);break}switch(i.type){case"remove":console.log(`${B.red} - ${i.line}${B.reset}`),r++;break;case"add":console.log(`${B.green} + ${i.line}${B.reset}`),r++;break;default:r>0&&console.log(`${B.gray} ${i.line}${B.reset}`)}}console.log()}function r_(t,e){console.log(`
68
68
  ${B.bold}${B.cyan} New file: ${t}${B.reset}`);let s=e.split(`
69
- `),n=s.slice(0,20);for(let o of n)console.log(`${B.green} + ${o}${B.reset}`);s.length>20&&console.log(`${B.gray} ...+${s.length-20} more lines${B.reset}`),console.log()}async function Jw(t){return zw()?!0:Gw(` ${t}?`)}function Zw(t,e,s,n){let o=n||process.stdout.columns||80,r=Math.floor((o-3)/2);console.log(`
70
- ${B.bold}${B.cyan} Side-by-side: ${t}${B.reset}`),console.log(` ${B.dim}${"\u2500".repeat(r)}\u252C${"\u2500".repeat(r)}${B.reset}`);let i=uo(e,s),a=[],l=0;for(;l<i.length;)if(i[l].type==="same")a.push({left:i[l].line,right:i[l].line,type:"same"}),l++;else if(i[l].type==="remove"){let p=[];for(;l<i.length&&i[l].type==="remove";)p.push(i[l].line),l++;let h=[];for(;l<i.length&&i[l].type==="add";)h.push(i[l].line),l++;let g=Math.max(p.length,h.length);for(let _=0;_<g;_++)a.push({left:_<p.length?p[_]:"",right:_<h.length?h[_]:"",type:"changed"})}else i[l].type==="add"&&(a.push({left:"",right:i[l].line,type:"changed"}),l++);let c=a.map((p,h)=>p.type!=="same"?h:-1).filter(p=>p>=0);if(c.length===0){console.log(` ${B.gray}(no changes)${B.reset}`);return}let u=Math.max(0,c[0]-2),d=Math.min(a.length,c[c.length-1]+3),f=(p,h)=>{let g=p.replace(/\x1b\[[0-9;]*m/g,"");return g.length>=h?p.substring(0,h):p+" ".repeat(h-g.length)};u>0&&console.log(` ${B.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${B.reset}`);for(let p=u;p<d;p++){let h=a[p];if(h.type==="same")console.log(` ${B.gray}${f(h.left,r)}${B.reset}\u2502${B.gray}${f(h.right,r)}${B.reset}`);else{let g=h.left?`${B.red}${f(h.left,r)}${B.reset}`:`${f("",r)}`,_=h.right?`${B.green}${f(h.right,r)}${B.reset}`:`${f("",r)}`;console.log(` ${g}\u2502${_}`)}}d<a.length&&console.log(` ${B.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${B.reset}`),console.log(` ${B.dim}${"\u2500".repeat(r)}\u2534${"\u2500".repeat(r)}${B.reset}
71
- `)}function Qw(t,e,s,n={}){let o=n.label||"Update",r=n.context||3,i=n.annotations||[],a=Pr.isAbsolute(t)?Pr.relative(process.cwd(),t):t,l=uo(e,s),c=1,u=1;for(let N of l)N.type==="same"?(N.oldLine=c++,N.newLine=u++):N.type==="remove"?(N.oldLine=c++,N.newLine=null):(N.oldLine=null,N.newLine=u++);let d=0,f=0;for(let N of l)N.type==="add"?d++:N.type==="remove"&&f++;if(console.log(`
69
+ `),n=s.slice(0,20);for(let o of n)console.log(`${B.green} + ${o}${B.reset}`);s.length>20&&console.log(`${B.gray} ...+${s.length-20} more lines${B.reset}`),console.log()}async function i_(t){return n_()?!0:t_(` ${t}?`)}function a_(t,e,s,n){let o=n||process.stdout.columns||80,r=Math.floor((o-3)/2);console.log(`
70
+ ${B.bold}${B.cyan} Side-by-side: ${t}${B.reset}`),console.log(` ${B.dim}${"\u2500".repeat(r)}\u252C${"\u2500".repeat(r)}${B.reset}`);let i=mo(e,s),a=[],l=0;for(;l<i.length;)if(i[l].type==="same")a.push({left:i[l].line,right:i[l].line,type:"same"}),l++;else if(i[l].type==="remove"){let p=[];for(;l<i.length&&i[l].type==="remove";)p.push(i[l].line),l++;let m=[];for(;l<i.length&&i[l].type==="add";)m.push(i[l].line),l++;let g=Math.max(p.length,m.length);for(let _=0;_<g;_++)a.push({left:_<p.length?p[_]:"",right:_<m.length?m[_]:"",type:"changed"})}else i[l].type==="add"&&(a.push({left:"",right:i[l].line,type:"changed"}),l++);let c=a.map((p,m)=>p.type!=="same"?m:-1).filter(p=>p>=0);if(c.length===0){console.log(` ${B.gray}(no changes)${B.reset}`);return}let u=Math.max(0,c[0]-2),d=Math.min(a.length,c[c.length-1]+3),f=(p,m)=>{let g=p.replace(/\x1b\[[0-9;]*m/g,"");return g.length>=m?p.substring(0,m):p+" ".repeat(m-g.length)};u>0&&console.log(` ${B.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${B.reset}`);for(let p=u;p<d;p++){let m=a[p];if(m.type==="same")console.log(` ${B.gray}${f(m.left,r)}${B.reset}\u2502${B.gray}${f(m.right,r)}${B.reset}`);else{let g=m.left?`${B.red}${f(m.left,r)}${B.reset}`:`${f("",r)}`,_=m.right?`${B.green}${f(m.right,r)}${B.reset}`:`${f("",r)}`;console.log(` ${g}\u2502${_}`)}}d<a.length&&console.log(` ${B.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${B.reset}`),console.log(` ${B.dim}${"\u2500".repeat(r)}\u2534${"\u2500".repeat(r)}${B.reset}
71
+ `)}function l_(t,e,s,n={}){let o=n.label||"Update",r=n.context||3,i=n.annotations||[],a=jr.isAbsolute(t)?jr.relative(process.cwd(),t):t,l=mo(e,s),c=1,u=1;for(let O of l)O.type==="same"?(O.oldLine=c++,O.newLine=u++):O.type==="remove"?(O.oldLine=c++,O.newLine=null):(O.oldLine=null,O.newLine=u++);let d=0,f=0;for(let O of l)O.type==="add"?d++:O.type==="remove"&&f++;if(console.log(`
72
72
  ${B.green}\u23FA${B.reset} ${B.bold}${o}(${a})${B.reset}`),d===0&&f===0){console.log(` ${B.dim}\u23BF (no changes)${B.reset}
73
- `);return}let p=[];if(d>0&&p.push(`Added ${d} line${d!==1?"s":""}`),f>0&&p.push(`removed ${f} line${f!==1?"s":""}`),i.length>0){let N=i.filter(le=>le.severity==="error").length,te=i.filter(le=>le.severity==="warn").length,K=i.filter(le=>le.severity==="info").length,ie=[];N>0&&ie.push(`${B.red}${N} error${N!==1?"s":""}${B.dim}`),te>0&&ie.push(`${B.yellow}${te} warning${te!==1?"s":""}${B.dim}`),K>0&&ie.push(`${B.cyan}${K} info${K!==1?"s":""}${B.dim}`),p.push(`found ${ie.join(", ")}`)}console.log(` ${B.dim}\u23BF ${p.join(", ")}${B.reset}`);let g=[];l.forEach((N,te)=>{N.type!=="same"&&g.push(te)});let _=[],b=null,O=null;for(let N of g){let te=Math.max(0,N-r),K=Math.min(l.length-1,N+r);b===null?(b=te,O=K):(te<=O+1||(_.push([b,O]),b=te),O=K)}b!==null&&_.push([b,O]);let M=" ",v=process.stdout.columns||120;function T(N,te,K){let ie=K.replace(/\x1b\[[0-9;]*m/g,""),le=K+" ".repeat(Math.max(0,v-ie.length));return`${N}${te}${le}${B.reset}`}for(let N=0;N<_.length;N++){N>0&&console.log(`${M}${B.dim}\xB7\xB7\xB7${B.reset}`);let[te,K]=_[N];for(let ie=te;ie<=K;ie++){let le=l[ie],ne=le.newLine!=null?le.newLine:le.oldLine,k=String(ne).padStart(4),ve=le.type!=="remove"?i.filter(H=>H.line===le.newLine):[];le.type==="remove"?console.log(T(Ia.diff_rem_bg,B.red,`${M}${k} - ${le.line}`)):le.type==="add"?console.log(T(Ia.diff_add_bg,B.green,`${M}${k} + ${le.line}`)):console.log(`${M}${B.dim}${k} ${B.reset}${le.line}`);for(let H of ve){let X=B.cyan,pe="\u2139";H.severity==="error"?(X=B.red,pe="\u2716"):H.severity==="warn"&&(X=B.yellow,pe="\u26A0"),console.log(`${M} ${X}${pe} ${H.message}${B.reset}`)}}}console.log()}function e_(t,e,s={}){let n=Pr.isAbsolute(t)?Pr.relative(process.cwd(),t):t,o=e.split(`
73
+ `);return}let p=[];if(d>0&&p.push(`Added ${d} line${d!==1?"s":""}`),f>0&&p.push(`removed ${f} line${f!==1?"s":""}`),i.length>0){let O=i.filter(ce=>ce.severity==="error").length,ne=i.filter(ce=>ce.severity==="warn").length,J=i.filter(ce=>ce.severity==="info").length,ie=[];O>0&&ie.push(`${B.red}${O} error${O!==1?"s":""}${B.dim}`),ne>0&&ie.push(`${B.yellow}${ne} warning${ne!==1?"s":""}${B.dim}`),J>0&&ie.push(`${B.cyan}${J} info${J!==1?"s":""}${B.dim}`),p.push(`found ${ie.join(", ")}`)}console.log(` ${B.dim}\u23BF ${p.join(", ")}${B.reset}`);let g=[];l.forEach((O,ne)=>{O.type!=="same"&&g.push(ne)});let _=[],b=null,A=null;for(let O of g){let ne=Math.max(0,O-r),J=Math.min(l.length-1,O+r);b===null?(b=ne,A=J):(ne<=A+1||(_.push([b,A]),b=ne),A=J)}b!==null&&_.push([b,A]);let P=" ",v=process.stdout.columns||120;function E(O,ne,J){let ie=J.replace(/\x1b\[[0-9;]*m/g,""),ce=J+" ".repeat(Math.max(0,v-ie.length));return`${O}${ne}${ce}${B.reset}`}for(let O=0;O<_.length;O++){O>0&&console.log(`${P}${B.dim}\xB7\xB7\xB7${B.reset}`);let[ne,J]=_[O];for(let ie=ne;ie<=J;ie++){let ce=l[ie],se=ce.newLine!=null?ce.newLine:ce.oldLine,S=String(se).padStart(4),Ee=ce.type!=="remove"?i.filter(W=>W.line===ce.newLine):[];ce.type==="remove"?console.log(E(Ua.diff_rem_bg,B.red,`${P}${S} - ${ce.line}`)):ce.type==="add"?console.log(E(Ua.diff_add_bg,B.green,`${P}${S} + ${ce.line}`)):console.log(`${P}${B.dim}${S} ${B.reset}${ce.line}`);for(let W of Ee){let Z=B.cyan,he="\u2139";W.severity==="error"?(Z=B.red,he="\u2716"):W.severity==="warn"&&(Z=B.yellow,he="\u26A0"),console.log(`${P} ${Z}${he} ${W.message}${B.reset}`)}}}console.log()}function c_(t,e,s={}){let n=jr.isAbsolute(t)?jr.relative(process.cwd(),t):t,o=e.split(`
74
74
  `),r=s.annotations||[];console.log(`
75
- ${B.green}\u23FA${B.reset} ${B.bold}Create(${n})${B.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,p=r.filter(g=>g.severity==="info").length,h=[];d>0&&h.push(`${B.red}${d} error${d!==1?"s":""}${B.dim}`),f>0&&h.push(`${B.yellow}${f} warning${f!==1?"s":""}${B.dim}`),p>0&&h.push(`${B.cyan}${p} info${p!==1?"s":""}${B.dim}`),i.push(`found ${h.join(", ")}`)}console.log(` ${B.dim}\u23BF ${i.join(", ")}${B.reset}`);let l=" ",c=process.stdout.columns||120,u=Math.min(o.length,20);for(let d=0;d<u;d++){let f=String(d+1).padStart(4),p=d+1,h=r.filter(O=>O.line===p),g=`${l}${f} + ${o[d]}`,_=g.replace(/\x1b\[[0-9;]*m/g,""),b=g+" ".repeat(Math.max(0,c-_.length));console.log(`${Ia.diff_add_bg}${B.green}${b}${B.reset}`);for(let O of h){let M=B.cyan,v="\u2139";O.severity==="error"?(M=B.red,v="\u2716"):O.severity==="warn"&&(M=B.yellow,v="\u26A0"),console.log(`${l} ${M}${v} ${O.message}${B.reset}`)}}o.length>20&&console.log(`${l}${B.dim} ...+${o.length-20} more lines${B.reset}`),console.log()}$d.exports={diffLines:uo,showEditDiff:Kw,showWriteDiff:Xw,showNewFilePreview:Vw,confirmFileChange:Jw,showSideBySideDiff:Zw,showDiff:Qw,showNewFile:e_}});var Dr=Z((pR,Sd)=>{var xd=require("util").promisify(require("child_process").exec),t_=require("util").promisify(require("child_process").execFile),{C:De}=Ke();async function Da(t){try{let{stdout:e}=await xd(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function Lr(...t){try{let{stdout:e}=await t_("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function n_(){return await Da("git rev-parse --is-inside-work-tree")==="true"}async function s_(){return await Da("git branch --show-current")}async function ja(){try{let{stdout:t}=await xd("git status --porcelain",{cwd:process.cwd(),timeout:3e4});return!t||!t.trim()?[]:t.split(`
76
- `).filter(Boolean).map(e=>{let s=e.substring(0,2).trim(),n=e.substring(3);return{status:s,file:n}})}catch{return[]}}async function Ir(t=!1){return await Da(`git diff ${t?"--cached":""}`)||""}async function qa(){return(await ja()).map(e=>e.file)}async function kd(){let t=await qa();if(t.length===0)return null;let e=await Ir(),n=await Ir(!0)||e,o=0,r=0;if(n){let u=n.split(`
77
- `);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 l=t.slice(0,3).map(u=>u.split("/").pop());return{summary:`${i}: update ${l.join(", ")}${t.length>3?` (+${t.length-3} more)`:""}`,type:i,files:t,stats:{additions:o,deletions:r}}}async function o_(t){let s=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await Lr("checkout","-b",s)!==null?s:null}async function r_(t){return await Lr("add","-A"),await Lr("commit","-m",t)?await Lr("rev-parse","--short","HEAD"):null}async function i_(){let t=await kd();if(!t)return`${De.dim}No changes${De.reset}`;let e=[];e.push(`
75
+ ${B.green}\u23FA${B.reset} ${B.bold}Create(${n})${B.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,p=r.filter(g=>g.severity==="info").length,m=[];d>0&&m.push(`${B.red}${d} error${d!==1?"s":""}${B.dim}`),f>0&&m.push(`${B.yellow}${f} warning${f!==1?"s":""}${B.dim}`),p>0&&m.push(`${B.cyan}${p} info${p!==1?"s":""}${B.dim}`),i.push(`found ${m.join(", ")}`)}console.log(` ${B.dim}\u23BF ${i.join(", ")}${B.reset}`);let l=" ",c=process.stdout.columns||120,u=Math.min(o.length,20);for(let d=0;d<u;d++){let f=String(d+1).padStart(4),p=d+1,m=r.filter(A=>A.line===p),g=`${l}${f} + ${o[d]}`,_=g.replace(/\x1b\[[0-9;]*m/g,""),b=g+" ".repeat(Math.max(0,c-_.length));console.log(`${Ua.diff_add_bg}${B.green}${b}${B.reset}`);for(let A of m){let P=B.cyan,v="\u2139";A.severity==="error"?(P=B.red,v="\u2716"):A.severity==="warn"&&(P=B.yellow,v="\u26A0"),console.log(`${l} ${P}${v} ${A.message}${B.reset}`)}}o.length>20&&console.log(`${l}${B.dim} ...+${o.length-20} more lines${B.reset}`),console.log()}Ad.exports={diffLines:mo,showEditDiff:s_,showWriteDiff:o_,showNewFilePreview:r_,confirmFileChange:i_,showSideBySideDiff:a_,showDiff:l_,showNewFile:c_}});var Br=Q((NR,Pd)=>{var Nd=require("util").promisify(require("child_process").exec),u_=require("util").promisify(require("child_process").execFile),{C:De}=Ke();async function Wa(t){try{let{stdout:e}=await Nd(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function qr(...t){try{let{stdout:e}=await u_("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function d_(){return await Wa("git rev-parse --is-inside-work-tree")==="true"}async function f_(){return await Wa("git branch --show-current")}async function Ha(){try{let{stdout:t}=await Nd("git status --porcelain",{cwd:process.cwd(),timeout:3e4});return!t||!t.trim()?[]:t.split(`
76
+ `).filter(Boolean).map(e=>{let s=e.substring(0,2).trim(),n=e.substring(3);return{status:s,file:n}})}catch{return[]}}async function Fr(t=!1){return await Wa(`git diff ${t?"--cached":""}`)||""}async function Ya(){return(await Ha()).map(e=>e.file)}async function Md(){let t=await Ya();if(t.length===0)return null;let e=await Fr(),n=await Fr(!0)||e,o=0,r=0;if(n){let u=n.split(`
77
+ `);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 l=t.slice(0,3).map(u=>u.split("/").pop());return{summary:`${i}: update ${l.join(", ")}${t.length>3?` (+${t.length-3} more)`:""}`,type:i,files:t,stats:{additions:o,deletions:r}}}async function p_(t){let s=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await qr("checkout","-b",s)!==null?s:null}async function h_(t){return await qr("add","-A"),await qr("commit","-m",t)?await qr("rev-parse","--short","HEAD"):null}async function m_(){let t=await Md();if(!t)return`${De.dim}No changes${De.reset}`;let e=[];e.push(`
78
78
  ${De.bold}${De.cyan}Git Diff Summary:${De.reset}`),e.push(` ${De.green}+${t.stats.additions}${De.reset} ${De.red}-${t.stats.deletions}${De.reset} in ${t.files.length} file(s)`),e.push(`
79
79
  ${De.bold}${De.cyan}Files:${De.reset}`);for(let s of t.files.slice(0,20))e.push(` ${De.dim}${s}${De.reset}`);return t.files.length>20&&e.push(` ${De.dim}...+${t.files.length-20} more${De.reset}`),e.push(`
80
80
  ${De.bold}${De.cyan}Suggested message:${De.reset}`),e.push(` ${De.cyan}${t.summary}${De.reset}
81
81
  `),e.join(`
82
- `)}async function a_(){return(await ja()).filter(e=>e.status==="UU"||e.status==="AA"||e.status==="DD")}async function l_(){let t=await qa();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 Ir();if(s){let n=s.length>5e3?s.substring(0,5e3)+`
82
+ `)}async function g_(){return(await Ha()).filter(e=>e.status==="UU"||e.status==="AA"||e.status==="DD")}async function y_(){let t=await Ya();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 Fr();if(s){let n=s.length>5e3?s.substring(0,5e3)+`
83
83
  ...(truncated)`:s;e.push(`
84
84
  DIFF:
85
85
  ${n}`)}return e.join(`
86
- `)}Sd.exports={isGitRepo:n_,getCurrentBranch:s_,getStatus:ja,getDiff:Ir,getChangedFiles:qa,analyzeDiff:kd,createBranch:o_,commit:r_,formatDiffSummary:i_,getDiffContext:l_,getMergeConflicts:a_}});var Nd=Z((mR,Od)=>{var Qe=require("fs").promises,hR=require("fs"),Nt=require("path"),c_=require("crypto"),{execSync:Fa,execFileSync:Td}=require("child_process"),u_=100*1024,Rd=50,yt=[],Ts=[];function d_(t,e,s,n){for(yt.push({tool:t,filePath:e,oldContent:s,newContent:n,timestamp:Date.now()});yt.length>Rd;)yt.shift();Ts.length=0,Cd(yt[yt.length-1]).catch(()=>{})}async function f_(){if(yt.length===0)return null;let t=yt.pop();if(t.oldContent===null)try{await Qe.unlink(t.filePath)}catch{}else await Qe.writeFile(t.filePath,t.oldContent,"utf-8");return Ts.push(t),{tool:t.tool,filePath:t.filePath,wasCreated:t.oldContent===null}}async function p_(){if(Ts.length===0)return null;let t=Ts.pop();return await Qe.writeFile(t.filePath,t.newContent,"utf-8"),yt.push(t),{tool:t.tool,filePath:t.filePath}}function h_(t=10){return yt.slice(-t).reverse().map(e=>({tool:e.tool,filePath:e.filePath,timestamp:e.timestamp}))}function m_(){return yt.length}function g_(){return Ts.length}function y_({diskToo:t=!0}={}){if(yt.length=0,Ts.length=0,t){let e=qr();Qe.readdir(e).then(s=>{for(let n of s)n.endsWith(".json")&&Qe.unlink(Nt.join(e,n)).catch(()=>{})}).catch(()=>{})}}function qr(){return Nt.join(process.cwd(),".nex","history")}async function vd(t,e){if(t==null)return{inline:!0,content:t};if(Buffer.byteLength(t,"utf-8")<=u_)return{inline:!0,content:t};let s=c_.createHash("sha256").update(t,"utf-8").digest("hex"),n=Nt.join(e,"blobs");return await Qe.mkdir(n,{recursive:!0}),await Qe.writeFile(Nt.join(n,s),t,"utf-8"),{inline:!1,hash:s}}async function Cd(t){let e=qr();await Qe.mkdir(e,{recursive:!0});let s=Nt.basename(t.filePath).replace(/[^a-zA-Z0-9]/g,"-"),n=`${t.timestamp}-${s}.json`,o=await vd(t.oldContent,e),r=await vd(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 Qe.writeFile(Nt.join(e,n),JSON.stringify(i),"utf-8")}async function Ed(t,e){if(!t)return null;if(t.inline)return t.content;let s=Nt.join(e,"blobs",t.hash);return Qe.readFile(s,"utf-8")}async function w_(){let t=qr(),e;try{e=await Qe.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 Qe.readFile(Nt.join(t,o),"utf-8"),i=JSON.parse(r),a=await Ed(i.oldContent,t),l=await Ed(i.newContent,t);yt.push({tool:i.tool,filePath:i.filePath,timestamp:i.timestamp,oldContent:a,newContent:l}),n++}catch{}for(;yt.length>Rd;)yt.shift();return n}async function __(t=7){let e=qr(),s;try{s=await Qe.readdir(e)}catch{return 0}let n=Date.now()-t*24*60*60*1e3,o=s.filter(c=>c.endsWith(".json")),r=0,i=new Set,a=[];for(let c of o)try{let u=await Qe.readFile(Nt.join(e,c),"utf-8"),d=JSON.parse(u);d.timestamp<n?(a.push(c),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 c of a)try{await Qe.unlink(Nt.join(e,c))}catch{}let l=Nt.join(e,"blobs");try{let c=await Qe.readdir(l);for(let u of c)if(!i.has(u))try{await Qe.unlink(Nt.join(l,u))}catch{}}catch{}return r}var jr="nex-snapshot";function $_(t,e=process.cwd()){let s=t?`${jr}-${t.replace(/[^a-zA-Z0-9_-]/g,"-")}`:`${jr}-${Date.now()}`;try{return Fa("git status --porcelain",{cwd:e,timeout:1e4}).toString().trim()?(Td("git",["stash","push","-u","-m",s],{cwd:e,timeout:15e3}),Fa("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 Ad(t=process.cwd()){try{let e=Fa("git stash list",{cwd:t,timeout:1e4}).toString().trim();return e?e.split(`
87
- `).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(jr)?{index:parseInt(n[1],10),label:o,shortName:o.replace(`${jr}-`,""),date:s}:null}).filter(Boolean):[]}catch{return[]}}function b_(t,e=process.cwd()){try{let s=Ad(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?(Td("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}}}Od.exports={recordChange:d_,undo:f_,redo:p_,getHistory:h_,getUndoCount:m_,getRedoCount:g_,clearHistory:y_,persistEntry:Cd,loadPersistedHistory:w_,pruneHistory:__,createSnapshot:$_,listSnapshots:Ad,restoreSnapshot:b_}});var Ya=Z((gR,jd)=>{var Me=require("fs"),wt=require("path"),{atomicWrite:x_,withFileLockSync:k_}=Bn(),ut=[];function fo(){return wt.join(process.cwd(),".nex","skills")}function Md(){return wt.join(process.cwd(),".nex","config.json")}function Pd(){let t=fo();return Me.existsSync(t)||Me.mkdirSync(t,{recursive:!0}),t}function Wa(){let t=Md();if(!Me.existsSync(t))return[];try{let e=JSON.parse(Me.readFileSync(t,"utf-8"));return e.skills&&Array.isArray(e.skills.disabled)?e.skills.disabled:[]}catch{return[]}}function Ld(t){let e=Md(),s=wt.dirname(e);Me.existsSync(s)||Me.mkdirSync(s,{recursive:!0}),k_(e,()=>{let n={};if(Me.existsSync(e))try{n=JSON.parse(Me.readFileSync(e,"utf-8"))}catch{n={}}n.skills||(n.skills={}),n.skills.disabled=t,x_(e,JSON.stringify(n,null,2))})}function Id(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 Dd(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(`
88
- `)){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 Ba(t){try{let e=Me.readFileSync(t,"utf-8").trim();if(!e)return null;let s=wt.basename(t,".md"),{triggers:n,body:o}=Dd(e);return{name:s,type:"prompt",filePath:t,instructions:o||e,triggers:n,commands:[],tools:[]}}catch{return null}}function Ua(t){try{let e=require(t),{valid:s,errors:n}=Id(e,t);return s?{name:e.name||wt.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}
86
+ `)}Pd.exports={isGitRepo:d_,getCurrentBranch:f_,getStatus:Ha,getDiff:Fr,getChangedFiles:Ya,analyzeDiff:Md,createBranch:p_,commit:h_,formatDiffSummary:m_,getDiffContext:y_,getMergeConflicts:g_}});var Ud=Q((PR,Bd)=>{var et=require("fs").promises,MR=require("fs"),Nt=require("path"),w_=require("crypto"),{execSync:Ga,execFileSync:Dd}=require("child_process"),__=100*1024,jd=50,yt=[],Cs=[];function $_(t,e,s,n){for(yt.push({tool:t,filePath:e,oldContent:s,newContent:n,timestamp:Date.now()});yt.length>jd;)yt.shift();Cs.length=0,qd(yt[yt.length-1]).catch(()=>{})}async function b_(){if(yt.length===0)return null;let t=yt.pop();if(t.oldContent===null)try{await et.unlink(t.filePath)}catch{}else await et.writeFile(t.filePath,t.oldContent,"utf-8");return Cs.push(t),{tool:t.tool,filePath:t.filePath,wasCreated:t.oldContent===null}}async function x_(){if(Cs.length===0)return null;let t=Cs.pop();return await et.writeFile(t.filePath,t.newContent,"utf-8"),yt.push(t),{tool:t.tool,filePath:t.filePath}}function k_(t=10){return yt.slice(-t).reverse().map(e=>({tool:e.tool,filePath:e.filePath,timestamp:e.timestamp}))}function S_(){return yt.length}function v_(){return Cs.length}function E_({diskToo:t=!0}={}){if(yt.length=0,Cs.length=0,t){let e=Wr();et.readdir(e).then(s=>{for(let n of s)n.endsWith(".json")&&et.unlink(Nt.join(e,n)).catch(()=>{})}).catch(()=>{})}}function Wr(){return Nt.join(process.cwd(),".nex","history")}async function Ld(t,e){if(t==null)return{inline:!0,content:t};if(Buffer.byteLength(t,"utf-8")<=__)return{inline:!0,content:t};let s=w_.createHash("sha256").update(t,"utf-8").digest("hex"),n=Nt.join(e,"blobs");return await et.mkdir(n,{recursive:!0}),await et.writeFile(Nt.join(n,s),t,"utf-8"),{inline:!1,hash:s}}async function qd(t){let e=Wr();await et.mkdir(e,{recursive:!0});let s=Nt.basename(t.filePath).replace(/[^a-zA-Z0-9]/g,"-"),n=`${t.timestamp}-${s}.json`,o=await Ld(t.oldContent,e),r=await Ld(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 et.writeFile(Nt.join(e,n),JSON.stringify(i),"utf-8")}async function Id(t,e){if(!t)return null;if(t.inline)return t.content;let s=Nt.join(e,"blobs",t.hash);return et.readFile(s,"utf-8")}async function T_(){let t=Wr(),e;try{e=await et.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 et.readFile(Nt.join(t,o),"utf-8"),i=JSON.parse(r),a=await Id(i.oldContent,t),l=await Id(i.newContent,t);yt.push({tool:i.tool,filePath:i.filePath,timestamp:i.timestamp,oldContent:a,newContent:l}),n++}catch{}for(;yt.length>jd;)yt.shift();return n}async function R_(t=7){let e=Wr(),s;try{s=await et.readdir(e)}catch{return 0}let n=Date.now()-t*24*60*60*1e3,o=s.filter(c=>c.endsWith(".json")),r=0,i=new Set,a=[];for(let c of o)try{let u=await et.readFile(Nt.join(e,c),"utf-8"),d=JSON.parse(u);d.timestamp<n?(a.push(c),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 c of a)try{await et.unlink(Nt.join(e,c))}catch{}let l=Nt.join(e,"blobs");try{let c=await et.readdir(l);for(let u of c)if(!i.has(u))try{await et.unlink(Nt.join(l,u))}catch{}}catch{}return r}var Ur="nex-snapshot";function C_(t,e=process.cwd()){let s=t?`${Ur}-${t.replace(/[^a-zA-Z0-9_-]/g,"-")}`:`${Ur}-${Date.now()}`;try{return Ga("git status --porcelain",{cwd:e,timeout:1e4}).toString().trim()?(Dd("git",["stash","push","-u","-m",s],{cwd:e,timeout:15e3}),Ga("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 Fd(t=process.cwd()){try{let e=Ga("git stash list",{cwd:t,timeout:1e4}).toString().trim();return e?e.split(`
87
+ `).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(Ur)?{index:parseInt(n[1],10),label:o,shortName:o.replace(`${Ur}-`,""),date:s}:null}).filter(Boolean):[]}catch{return[]}}function A_(t,e=process.cwd()){try{let s=Fd(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?(Dd("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}}}Bd.exports={recordChange:$_,undo:b_,redo:x_,getHistory:k_,getUndoCount:S_,getRedoCount:v_,clearHistory:E_,persistEntry:qd,loadPersistedHistory:T_,pruneHistory:R_,createSnapshot:C_,listSnapshots:Fd,restoreSnapshot:A_}});var Ja=Q((LR,Kd)=>{var Me=require("fs"),wt=require("path"),{atomicWrite:O_,withFileLockSync:N_}=Fn(),ut=[];function go(){return wt.join(process.cwd(),".nex","skills")}function Wd(){return wt.join(process.cwd(),".nex","config.json")}function Hd(){let t=go();return Me.existsSync(t)||Me.mkdirSync(t,{recursive:!0}),t}function Xa(){let t=Wd();if(!Me.existsSync(t))return[];try{let e=JSON.parse(Me.readFileSync(t,"utf-8"));return e.skills&&Array.isArray(e.skills.disabled)?e.skills.disabled:[]}catch{return[]}}function Yd(t){let e=Wd(),s=wt.dirname(e);Me.existsSync(s)||Me.mkdirSync(s,{recursive:!0}),N_(e,()=>{let n={};if(Me.existsSync(e))try{n=JSON.parse(Me.readFileSync(e,"utf-8"))}catch{n={}}n.skills||(n.skills={}),n.skills.disabled=t,O_(e,JSON.stringify(n,null,2))})}function Gd(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 zd(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(`
88
+ `)){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 za(t){try{let e=Me.readFileSync(t,"utf-8").trim();if(!e)return null;let s=wt.basename(t,".md"),{triggers:n,body:o}=zd(e);return{name:s,type:"prompt",filePath:t,instructions:o||e,triggers:n,commands:[],tools:[]}}catch{return null}}function Ka(t){try{let e=require(t),{valid:s,errors:n}=Gd(e,t);return s?{name:e.name||wt.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}
89
89
  ${n.join(`
90
- `)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function Ha(){ut=[];let t=Wa(),e=fo(),s=[];if(Me.existsSync(e))try{s=Me.readdirSync(e)}catch{s=[]}for(let o of s){let r=wt.join(e,o),i;try{i=Me.statSync(r)}catch{continue}if(!i.isFile())continue;let a=null;o.endsWith(".md")?a=Ba(r):o.endsWith(".js")&&(a=Ua(r)),a&&(a.enabled=!t.includes(a.name),ut.push(a))}let n=wt.join(__dirname,"skills");if(!process.env.NEX_SKIP_BUILTIN_SKILLS&&Me.existsSync(n)){let o;try{o=Me.readdirSync(n).filter(r=>r.endsWith(".md")||r.endsWith(".js"))}catch{o=[]}for(let r of o){let i=wt.join(n,r),a=wt.basename(r,wt.extname(r));if(ut.some(u=>u.name===a))continue;let l;try{l=Me.statSync(i)}catch{continue}if(!l.isFile())continue;let c=r.endsWith(".md")?Ba(i):Ua(i);c&&(c._builtin=!0,c.enabled=!t.includes(c.name),ut.push(c))}}return ut}function S_(){let t=[];for(let e of ut)!e.enabled||!e.instructions||t.push(`[Skill: ${e.name}]
90
+ `)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function Va(){ut=[];let t=Xa(),e=go(),s=[];if(Me.existsSync(e))try{s=Me.readdirSync(e)}catch{s=[]}for(let o of s){let r=wt.join(e,o),i;try{i=Me.statSync(r)}catch{continue}if(!i.isFile())continue;let a=null;o.endsWith(".md")?a=za(r):o.endsWith(".js")&&(a=Ka(r)),a&&(a.enabled=!t.includes(a.name),ut.push(a))}let n=wt.join(__dirname,"skills");if(!process.env.NEX_SKIP_BUILTIN_SKILLS&&Me.existsSync(n)){let o;try{o=Me.readdirSync(n).filter(r=>r.endsWith(".md")||r.endsWith(".js"))}catch{o=[]}for(let r of o){let i=wt.join(n,r),a=wt.basename(r,wt.extname(r));if(ut.some(u=>u.name===a))continue;let l;try{l=Me.statSync(i)}catch{continue}if(!l.isFile())continue;let c=r.endsWith(".md")?za(i):Ka(i);c&&(c._builtin=!0,c.enabled=!t.includes(c.name),ut.push(c))}}return ut}function M_(){let t=[];for(let e of ut)!e.enabled||!e.instructions||t.push(`[Skill: ${e.name}]
91
91
  ${e.instructions}`);return t.length===0?"":`SKILL INSTRUCTIONS:
92
92
  ${t.join(`
93
93
 
94
- `)}`}function v_(){let t=[];for(let e of ut)if(e.enabled)for(let s of e.commands)t.push({cmd:s.cmd,desc:s.desc||`[skill: ${e.name}]`});return t}function E_(){let t=[];for(let e of ut)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 T_(t,e){if(!t.startsWith("skill_"))return null;let s=t.substring(6);for(let n of ut)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 R_(t){let[e,...s]=t.split(/\s+/),n=s.join(" ").trim();for(let o of ut)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 C_(){return ut.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 A_(t){let e=ut.find(n=>n.name===t);if(!e)return!1;e.enabled=!0;let s=Wa().filter(n=>n!==t);return Ld(s),!0}function O_(t){let e=ut.find(n=>n.name===t);if(!e)return!1;e.enabled=!1;let s=Wa();return s.includes(t)||(s.push(t),Ld(s)),!0}function N_(){return ut}async function M_(t,e={}){let{execFileSync:s}=require("child_process"),n=Pd(),o=t;/^[\w-]+\/[\w.-]+$/.test(t)&&(o=`https://github.com/${t}.git`);let r=e.name||wt.basename(o,".git").replace(/^nex-skill-/,""),i=wt.join(n,r);if(Me.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}`);s("git",["clone","--depth","1",o,i],{timeout:3e4,stdio:"pipe"})}catch(u){return{ok:!1,name:r,error:`Git clone failed: ${u.stderr?.toString().trim()||u.message}`}}let a=wt.join(i,"skill.json"),l=Me.existsSync(a),c=Me.readdirSync(i).some(u=>(u.endsWith(".md")||u.endsWith(".js"))&&!u.startsWith("."));if(!l&&!c){try{Me.rmSync(i,{recursive:!0,force:!0})}catch(u){console.error("skills.js line 562 failed:",u.message)}return{ok:!1,name:r,error:"No skill.json manifest or .md/.js skill file found in repository"}}if(l)try{let u=JSON.parse(Me.readFileSync(a,"utf-8"));u.name||(u.name=r)}catch{try{Me.rmSync(i,{recursive:!0,force:!0})}catch{}return{ok:!1,name:r,error:"Invalid skill.json \u2014 not valid JSON"}}return Ha(),{ok:!0,name:r}}async function P_(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 L_(t){let e=wt.join(fo(),t);if(!Me.existsSync(e))return{ok:!1,error:`Skill "${t}" not found in ${fo()}`};try{return Me.rmSync(e,{recursive:!0,force:!0}),Ha(),{ok:!0}}catch(s){return{ok:!1,error:s.message}}}function I_(t){if(!t)return[];let e=t.toLowerCase(),s=[];for(let n of ut){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
+ `)}`}function P_(){let t=[];for(let e of ut)if(e.enabled)for(let s of e.commands)t.push({cmd:s.cmd,desc:s.desc||`[skill: ${e.name}]`});return t}function L_(){let t=[];for(let e of ut)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 I_(t,e){if(!t.startsWith("skill_"))return null;let s=t.substring(6);for(let n of ut)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 D_(t){let[e,...s]=t.split(/\s+/),n=s.join(" ").trim();for(let o of ut)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 j_(){return ut.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 q_(t){let e=ut.find(n=>n.name===t);if(!e)return!1;e.enabled=!0;let s=Xa().filter(n=>n!==t);return Yd(s),!0}function F_(t){let e=ut.find(n=>n.name===t);if(!e)return!1;e.enabled=!1;let s=Xa();return s.includes(t)||(s.push(t),Yd(s)),!0}function B_(){return ut}async function U_(t,e={}){let{execFileSync:s}=require("child_process"),n=Hd(),o=t;/^[\w-]+\/[\w.-]+$/.test(t)&&(o=`https://github.com/${t}.git`);let r=e.name||wt.basename(o,".git").replace(/^nex-skill-/,""),i=wt.join(n,r);if(Me.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}`);s("git",["clone","--depth","1",o,i],{timeout:3e4,stdio:"pipe"})}catch(u){return{ok:!1,name:r,error:`Git clone failed: ${u.stderr?.toString().trim()||u.message}`}}let a=wt.join(i,"skill.json"),l=Me.existsSync(a),c=Me.readdirSync(i).some(u=>(u.endsWith(".md")||u.endsWith(".js"))&&!u.startsWith("."));if(!l&&!c){try{Me.rmSync(i,{recursive:!0,force:!0})}catch(u){console.error("skills.js line 562 failed:",u.message)}return{ok:!1,name:r,error:"No skill.json manifest or .md/.js skill file found in repository"}}if(l)try{let u=JSON.parse(Me.readFileSync(a,"utf-8"));u.name||(u.name=r)}catch{try{Me.rmSync(i,{recursive:!0,force:!0})}catch{}return{ok:!1,name:r,error:"Invalid skill.json \u2014 not valid JSON"}}return Va(),{ok:!0,name:r}}async function W_(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 H_(t){let e=wt.join(go(),t);if(!Me.existsSync(e))return{ok:!1,error:`Skill "${t}" not found in ${go()}`};try{return Me.rmSync(e,{recursive:!0,force:!0}),Va(),{ok:!0}}catch(s){return{ok:!1,error:s.message}}}function Y_(t){if(!t)return[];let e=t.toLowerCase(),s=[];for(let n of ut){if(!n.enabled||!n.triggers||n.triggers.length===0)continue;if(n.triggers.some(r=>e.includes(r.toLowerCase()))){let r=(n.instructions||"").split(`
95
95
  `).slice(0,3).join(`
96
- `);s.push({name:n.name,instructions:r})}}return s}jd.exports={initSkillsDir:Pd,loadAllSkills:Ha,getSkillInstructions:S_,getSkillCommands:v_,getSkillToolDefinitions:E_,routeSkillCall:T_,handleSkillCommand:R_,listSkills:C_,enableSkill:A_,disableSkill:O_,getLoadedSkills:N_,installSkill:M_,searchSkills:P_,removeSkill:L_,matchSkillTriggers:I_,_getSkillsDir:fo,_validateScriptSkill:Id,_loadMarkdownSkill:Ba,_loadScriptSkill:Ua,_parseFrontmatter:Dd}});var za=Z((yR,Hd)=>{var{spawn:D_}=require("child_process"),j_=require("path"),qd=require("fs"),cn=new Map;function q_(){return j_.join(process.cwd(),".nex","config.json")}function Ga(){let t=q_();if(!qd.existsSync(t))return{};try{return JSON.parse(qd.readFileSync(t,"utf-8")).mcpServers||{}}catch{return{}}}function Fr(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
+ `);s.push({name:n.name,instructions:r})}}return s}Kd.exports={initSkillsDir:Hd,loadAllSkills:Va,getSkillInstructions:M_,getSkillCommands:P_,getSkillToolDefinitions:L_,routeSkillCall:I_,handleSkillCommand:D_,listSkills:j_,enableSkill:q_,disableSkill:F_,getLoadedSkills:B_,installSkill:U_,searchSkills:W_,removeSkill:H_,matchSkillTriggers:Y_,_getSkillsDir:go,_validateScriptSkill:Gd,_loadMarkdownSkill:za,_loadScriptSkill:Ka,_parseFrontmatter:zd}});var Qa=Q((IR,ef)=>{var{spawn:G_}=require("child_process"),z_=require("path"),Xd=require("fs"),cn=new Map;function K_(){return z_.join(process.cwd(),".nex","config.json")}function Za(){let t=K_();if(!Xd.existsSync(t))return{};try{return JSON.parse(Xd.readFileSync(t,"utf-8")).mcpServers||{}}catch{return{}}}function Hr(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})+`
97
97
  `,l="",c=setTimeout(()=>{d(),r(new Error(`MCP request timeout: ${e}`))},n);function u(f){l+=f.toString();let p=l.split(`
98
- `);for(let h of p)if(h.trim())try{let g=JSON.parse(h);if(g.id===i){d(),g.error?r(new Error(`MCP error: ${g.error.message||JSON.stringify(g.error)}`)):o(g.result);return}}catch{}l=p[p.length-1]||""}function d(){clearTimeout(c),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 Fd(t,e){if(cn.has(t))return cn.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=D_(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:{...n,...e.env||{}}}),r={name:t,proc:o,tools:[],config:e};try{await Fr(o,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.2.0"}});let i=await Fr(o,"tools/list",{});return r.tools=i&&i.tools||[],cn.set(t,r),r}catch(i){throw o.kill(),new Error(`Failed to connect MCP server '${t}': ${i.message}`)}}function Bd(t){let e=cn.get(t);if(!e)return!1;try{e.proc.kill()}catch{}return cn.delete(t),!0}function F_(){for(let[t]of cn)Bd(t)}async function Ud(t,e,s={}){let n=cn.get(t);if(!n)throw new Error(`MCP server not connected: ${t}`);let o=await Fr(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(`
99
- `):JSON.stringify(o)}function Wd(){let t=[];for(let[e,s]of cn)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 B_(){return Wd().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function U_(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 Ud(n,o,e)}function W_(){let t=Ga();return Object.entries(t).map(([e,s])=>{let n=cn.get(e);return{name:e,command:s.command,connected:!!n,toolCount:n?n.tools.length:0}})}async function H_(){let t=Ga(),e=[];for(let[s,n]of Object.entries(t))try{let o=await Fd(s,n);e.push({name:s,tools:o.tools.length})}catch(o){e.push({name:s,tools:0,error:o.message})}return e}Hd.exports={loadMCPConfig:Ga,sendRequest:Fr,connectServer:Fd,disconnectServer:Bd,disconnectAll:F_,callTool:Ud,getAllTools:Wd,getMCPToolDefinitions:B_,routeMCPCall:U_,listServers:W_,connectAll:H_}});var Ur=Z((wR,Kd)=>{var Yd=require("fs"),Ka=require("path"),Br=[],po=[],Wn={},ho=["onToolResult","onModelResponse","onSessionStart","onSessionEnd","onFileChange","beforeToolExec","afterToolExec"];function Gd(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 po.some(n=>n.definition.function.name===s)?{ok:!1,error:`Tool "${s}" is already registered`}:(po.push({definition:{type:"function",...t},handler:e}),{ok:!0})}function zd(t,e){return ho.includes(t)?typeof e!="function"?{ok:!1,error:"Handler must be a function"}:(Wn[t]||(Wn[t]=[]),Wn[t].push(e),{ok:!0}):{ok:!1,error:`Unknown event "${t}". Available: ${ho.join(", ")}`}}async function Xa(t,e){let s=Wn[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 Y_(){let t=Ka.join(process.cwd(),".nex","plugins"),e=[];if(!Yd.existsSync(t))return{loaded:0,errors:[]};let s=Yd.readdirSync(t).filter(o=>o.endsWith(".js")),n={registerTool:Gd,registerHook:zd,EVENTS:ho};for(let o of s){let r=Ka.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}Br.push({name:i.name||Ka.basename(o,".js"),filePath:r})}catch(i){e.push(`${o}: ${i.message}`)}}return{loaded:Br.length,errors:e}}function G_(){return po.map(t=>t.definition)}async function z_(t,e,s={}){let n=po.find(a=>a.definition.function.name===t);if(!n)return null;let o=await Xa("beforeToolExec",{name:t,args:e,options:s}),r=await n.handler(o.args||e,s);return(await Xa("afterToolExec",{name:t,args:e,result:r})).result||r}function K_(){return[...Br]}function X_(){let t={};for(let e of ho)t[e]=(Wn[e]||[]).length;return t}function V_(){Br.length=0,po.length=0;for(let t of Object.keys(Wn))delete Wn[t]}Kd.exports={registerTool:Gd,registerHook:zd,emit:Xa,loadPlugins:Y_,getPluginToolDefinitions:G_,executePluginTool:z_,getLoadedPlugins:K_,getHookCounts:X_,clearPlugins:V_,EVENTS:ho}});var Va=Z((_R,Zd)=>{var{getSkillToolDefinitions:J_}=Ya(),{getMCPToolDefinitions:Z_}=za(),{getPluginToolDefinitions:Q_}=Ur(),Wr=new Map;function Xd(){let{TOOL_DEFINITIONS:t}=Rs();return[...t,...J_(),...Z_(),...Q_()]}function Vd(t){if(Wr.has(t))return Wr.get(t);let s=Xd().find(o=>o.function.name===t);if(!s)return null;let n=s.function.parameters;return Wr.set(t,n),n}function e$(){Wr.clear()}function Hr(t,e){if(!t||e.length===0)return null;let s=null,n=1/0;for(let o of e){let r=Jd(t.toLowerCase(),o.toLowerCase());r<n&&(n=r,s=o)}return n<=Math.ceil(t.length/2)?s:null}function Jd(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 t$(t,e){let s=Vd(t);if(s===null){let d=Xd().map(p=>p.function.name),f=Hr(t,d);return{valid:!1,error:`Unknown tool "${t}".${f?` Did you mean "${f}"?`:""}
100
- 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},l=!1;for(let u of n)if(!(u in e)||e[u]===void 0||e[u]===null){let d=Hr(u,r);d&&!o.includes(d)?(a[u]=e[d],delete a[d],l=!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,l=!0),("-i"in a||"--ignore-case"in a)&&"ignore_case"in(s.properties||{})&&(a.ignore_case=!0,delete a["-i"],delete a["--ignore-case"],l=!0),("-r"in a||"--recursive"in a)&&(delete a["-r"],delete a["--recursive"],l=!0)),t==="read_file"&&("offset"in a&&!("line_start"in a)&&(a.line_start=a.offset,delete a.offset,l=!0),"start_line"in a&&!("line_start"in a)&&(a.line_start=a.start_line,delete a.start_line,l=!0),"end_line"in a&&!("line_end"in a)&&(a.line_end=a.end_line,delete a.end_line,l=!0));for(let u of Object.keys(a))if(!o.includes(u)){let d=Hr(u,o);if(d&&!(d in a))a[d]=a[u],delete a[u],l=!0;else if(!l){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]),l=!0):d==="number"&&f==="string"&&!isNaN(a[u])?(a[u]=Number(a[u]),l=!0):d==="boolean"&&f==="string"&&(a[u]=a[u]==="true",l=!0)}return i.length>0&&!l?{valid:!1,error:`Tool "${t}" argument errors:
98
+ `);for(let m of p)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{}l=p[p.length-1]||""}function d(){clearTimeout(c),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 Vd(t,e){if(cn.has(t))return cn.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=G_(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:{...n,...e.env||{}}}),r={name:t,proc:o,tools:[],config:e};try{await Hr(o,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.2.0"}});let i=await Hr(o,"tools/list",{});return r.tools=i&&i.tools||[],cn.set(t,r),r}catch(i){throw o.kill(),new Error(`Failed to connect MCP server '${t}': ${i.message}`)}}function Jd(t){let e=cn.get(t);if(!e)return!1;try{e.proc.kill()}catch{}return cn.delete(t),!0}function X_(){for(let[t]of cn)Jd(t)}async function Zd(t,e,s={}){let n=cn.get(t);if(!n)throw new Error(`MCP server not connected: ${t}`);let o=await Hr(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(`
99
+ `):JSON.stringify(o)}function Qd(){let t=[];for(let[e,s]of cn)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 V_(){return Qd().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function J_(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 Zd(n,o,e)}function Z_(){let t=Za();return Object.entries(t).map(([e,s])=>{let n=cn.get(e);return{name:e,command:s.command,connected:!!n,toolCount:n?n.tools.length:0}})}async function Q_(){let t=Za(),e=[];for(let[s,n]of Object.entries(t))try{let o=await Vd(s,n);e.push({name:s,tools:o.tools.length})}catch(o){e.push({name:s,tools:0,error:o.message})}return e}ef.exports={loadMCPConfig:Za,sendRequest:Hr,connectServer:Vd,disconnectServer:Jd,disconnectAll:X_,callTool:Zd,getAllTools:Qd,getMCPToolDefinitions:V_,routeMCPCall:J_,listServers:Z_,connectAll:Q_}});var Gr=Q((DR,of)=>{var tf=require("fs"),el=require("path"),Yr=[],yo=[],Un={},wo=["onToolResult","onModelResponse","onSessionStart","onSessionEnd","onFileChange","beforeToolExec","afterToolExec"];function nf(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 yo.some(n=>n.definition.function.name===s)?{ok:!1,error:`Tool "${s}" is already registered`}:(yo.push({definition:{type:"function",...t},handler:e}),{ok:!0})}function sf(t,e){return wo.includes(t)?typeof e!="function"?{ok:!1,error:"Handler must be a function"}:(Un[t]||(Un[t]=[]),Un[t].push(e),{ok:!0}):{ok:!1,error:`Unknown event "${t}". Available: ${wo.join(", ")}`}}async function tl(t,e){let s=Un[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 e$(){let t=el.join(process.cwd(),".nex","plugins"),e=[];if(!tf.existsSync(t))return{loaded:0,errors:[]};let s=tf.readdirSync(t).filter(o=>o.endsWith(".js")),n={registerTool:nf,registerHook:sf,EVENTS:wo};for(let o of s){let r=el.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}Yr.push({name:i.name||el.basename(o,".js"),filePath:r})}catch(i){e.push(`${o}: ${i.message}`)}}return{loaded:Yr.length,errors:e}}function t$(){return yo.map(t=>t.definition)}async function n$(t,e,s={}){let n=yo.find(a=>a.definition.function.name===t);if(!n)return null;let o=await tl("beforeToolExec",{name:t,args:e,options:s}),r=await n.handler(o.args||e,s);return(await tl("afterToolExec",{name:t,args:e,result:r})).result||r}function s$(){return[...Yr]}function o$(){let t={};for(let e of wo)t[e]=(Un[e]||[]).length;return t}function r$(){Yr.length=0,yo.length=0;for(let t of Object.keys(Un))delete Un[t]}of.exports={registerTool:nf,registerHook:sf,emit:tl,loadPlugins:e$,getPluginToolDefinitions:t$,executePluginTool:n$,getLoadedPlugins:s$,getHookCounts:o$,clearPlugins:r$,EVENTS:wo}});var nl=Q((jR,cf)=>{var{getSkillToolDefinitions:i$}=Ja(),{getMCPToolDefinitions:a$}=Qa(),{getPluginToolDefinitions:l$}=Gr(),zr=new Map;function rf(){let{TOOL_DEFINITIONS:t}=As();return[...t,...i$(),...a$(),...l$()]}function af(t){if(zr.has(t))return zr.get(t);let s=rf().find(o=>o.function.name===t);if(!s)return null;let n=s.function.parameters;return zr.set(t,n),n}function c$(){zr.clear()}function Kr(t,e){if(!t||e.length===0)return null;let s=null,n=1/0;for(let o of e){let r=lf(t.toLowerCase(),o.toLowerCase());r<n&&(n=r,s=o)}return n<=Math.ceil(t.length/2)?s:null}function lf(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 u$(t,e){let s=af(t);if(s===null){let d=rf().map(p=>p.function.name),f=Kr(t,d);return{valid:!1,error:`Unknown tool "${t}".${f?` Did you mean "${f}"?`:""}
100
+ 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},l=!1;for(let u of n)if(!(u in e)||e[u]===void 0||e[u]===null){let d=Kr(u,r);d&&!o.includes(d)?(a[u]=e[d],delete a[d],l=!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,l=!0),("-i"in a||"--ignore-case"in a)&&"ignore_case"in(s.properties||{})&&(a.ignore_case=!0,delete a["-i"],delete a["--ignore-case"],l=!0),("-r"in a||"--recursive"in a)&&(delete a["-r"],delete a["--recursive"],l=!0)),t==="read_file"&&("offset"in a&&!("line_start"in a)&&(a.line_start=a.offset,delete a.offset,l=!0),"start_line"in a&&!("line_start"in a)&&(a.line_start=a.start_line,delete a.start_line,l=!0),"end_line"in a&&!("line_end"in a)&&(a.line_end=a.end_line,delete a.end_line,l=!0));for(let u of Object.keys(a))if(!o.includes(u)){let d=Kr(u,o);if(d&&!(d in a))a[d]=a[u],delete a[u],l=!0;else if(!l){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]),l=!0):d==="number"&&f==="string"&&!isNaN(a[u])?(a[u]=Number(a[u]),l=!0):d==="boolean"&&f==="string"&&(a[u]=a[u]==="true",l=!0)}return i.length>0&&!l?{valid:!1,error:`Tool "${t}" argument errors:
101
101
  `+i.map(u=>` - ${u}`).join(`
102
102
  `)+`
103
103
 
104
- Expected parameters: ${JSON.stringify(s.properties,null,2)}`}:{valid:!0,corrected:l?a:null}}function n$(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}}Zd.exports={validateToolArgs:t$,validateToolCallFormat:n$,closestMatch:Hr,levenshtein:Jd,getCachedSchema:Vd,clearSchemaCache:e$}});var nf=Z(($R,tf)=>{var{levenshtein:Yr}=Va(),s$=200,o$=.3,r$=2;function Ja(t){return t.replace(/\r\n/g,`
104
+ Expected parameters: ${JSON.stringify(s.properties,null,2)}`}:{valid:!0,corrected:l?a:null}}function d$(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}}cf.exports={validateToolArgs:u$,validateToolCallFormat:d$,closestMatch:Kr,levenshtein:lf,getCachedSchema:af,clearSchemaCache:c$}});var pf=Q((qR,ff)=>{var{levenshtein:Xr}=nl(),f$=200,p$=.3,h$=2;function sl(t){return t.replace(/\r\n/g,`
105
105
  `).replace(/\r/g,`
106
- `).replace(/\t/g," ".repeat(r$)).split(`
106
+ `).replace(/\t/g," ".repeat(h$)).split(`
107
107
  `).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(`
108
- `)}function i$(t,e){if(t.includes(e))return e;if(e.length<10)return null;let s=Ja(t),n=Ja(e);if(!s.includes(n))return null;let o=t.split(`
108
+ `)}function m$(t,e){if(t.includes(e))return e;if(e.length<10)return null;let s=sl(t),n=sl(e);if(!s.includes(n))return null;let o=t.split(`
109
109
  `),r=s.split(`
110
110
  `),i=n.split(`
111
111
  `),a=i[0],l=i[i.length-1];for(let c=0;c<=r.length-i.length;c++){let u=!0;for(let d=0;d<i.length;d++)if(r[c+d]!==i[d]){u=!1;break}if(u)return o.slice(c,c+i.length).join(`
112
- `)}if(i.length===1){for(let c=0;c<r.length;c++)if(r[c].indexOf(n)!==-1)return o[c]}return null}function a$(t,e){if(!t||!e)return null;let s=t.split(`
112
+ `)}if(i.length===1){for(let c=0;c<r.length;c++)if(r[c].indexOf(n)!==-1)return o[c]}return null}function g$(t,e){if(!t||!e)return null;let s=t.split(`
113
113
  `),o=e.split(`
114
- `).length;return s.length===0||o===0?null:o===1?l$(s,e):u$(s,e,o)}function Qd(t){return Math.max(1,Math.floor(t/s$))}function ef(t,e){return t<=Math.ceil(e*o$)}function l$(t,e){let s=e.trim(),n=Qd(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 l=Yr(a.trim(),s);l<r&&(r=l,o={text:a,distance:l,line:i+1})}return o&&n>1&&(o=c$(t,s,o,n)||o,r=o.distance),ef(r,e.length)?o:null}function c$(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,l=null;for(let c=r;c<=i;c++){let u=t[c];if(!u.trim())continue;let d=Yr(u.trim(),e);d<a&&(a=d,l={text:u,distance:d,line:c+1})}return l}function u$(t,e,s){let n=t.length-s+1;if(n<=0)return null;let o=Qd(n),r=null,i=1/0;for(let a=0;a<n;a+=o){let l=t.slice(a,a+s).join(`
115
- `),c=Yr(l,e);c<i&&(i=c,r={text:l,distance:c,line:a+1})}return r&&o>1&&(r=d$(t,e,r,o,s,n)||r,i=r.distance),ef(i,e.length)?r:null}function d$(t,e,s,n,o,r){let i=s.line-1,a=Math.max(0,i-n),l=Math.min(r-1,i+n),c=s.distance,u=null;for(let d=a;d<=l;d++){let f=t.slice(d,d+o).join(`
116
- `),p=Yr(f,e);p<c&&(c=p,u={text:f,distance:p,line:d+1})}return u}tf.exports={normalizeWhitespace:Ja,fuzzyFindText:i$,findMostSimilar:a$}});var of=Z((xR,sf)=>{var{C:bR}=Ke(),f$=[{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}],p$=[{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 h$(t,e){let s=e.split(`
117
- `),n=[],o=t?`.${t.split(".").pop()}`:"";for(let r=0;r<s.length;r++){let i=s[r],a=r+1;for(let l of f$)l.regex.test(i)&&n.push({line:a,message:`Potential secret detected: ${l.name}`,severity:"error"});for(let l of p$)l.ext&&!l.ext.includes(o)||l.regex.test(i)&&n.push({line:a,message:l.message||`Found ${l.name}`,severity:l.severity||"warn"})}return s.length>500&&n.push({line:0,message:`Large file detected (${s.length} lines). Consider refactoring.`,severity:"info"}),n}function m$(){let t=process.memoryUsage();return{rss:Math.round(t.rss/1024/1024*100)/100,heapUsed:Math.round(t.heapUsed/1024/1024*100)/100}}sf.exports={runDiagnostics:h$,getMemoryUsage:m$}});var As=Z((kR,pf)=>{var Cs=require("fs").promises,kn=require("path"),{exec:g$}=require("util").promisify(require("child_process").exec),Sn=[],tl=null,Gr=!1,Qa=0,y$=6e4;function af(t){return!(Sn.length===0||tl!==t||Date.now()-Qa>y$)}async function lf(t){if(!Gr&&!af(t)){Gr=!0,tl=t;try{try{let{stdout:n}=await g$("rg --files",{cwd:t,timeout:5e3});Sn=n.split(`
118
- `).filter(Boolean),Qa=Date.now(),Gr=!1;return}catch{}let e=[],s=async(n,o)=>{let r;try{r=await Cs.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(kn.join(n,i.name),a):e.push(a)}};await s(t,""),Sn=e,Qa=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{Gr=!1}}}function el(){return Sn}function w$(){return tl}function _$(t){return Sn.filter(e=>kn.basename(e)===t)}function $$(t){let e=t.toLowerCase();return Sn.filter(s=>s.toLowerCase().includes(e)).slice(0,20)}function cf(t,e){let s=t.length,n=e.length;if(s===0)return n;if(n===0)return s;let o=Array.from({length:n+1},(r,i)=>i);for(let r=1;r<=s;r++){let i=r-1;o[0]=r;for(let a=1;a<=n;a++){let l=t[r-1]===e[a-1]?i:1+Math.min(o[a],o[a-1],i);i=o[a],o[a]=l}}return o[n]}function uf(t,e){let s=t.toLowerCase(),n=e.toLowerCase();if(s===n)return 1e3;let o=s.split("/").filter(Boolean),r=n.split("/").filter(Boolean),i=0;for(let u=1;u<=Math.min(o.length,r.length)&&o[o.length-u]===r[r.length-u];u++)i=u;if(i>0&&i===r.length)return 500+i*100;let a=kn.basename(t).toLowerCase(),l=kn.basename(e).toLowerCase(),c=0;if(a===l)c+=80;else{let u=Math.max(a.length,l.length);if(u>0&&u<100){let f=1-cf(a,l)/u;f>=.6&&(c+=Math.round(f*50))}}if((s.includes(n)||n.includes(s))&&(c+=20),r.length>1){let u=new Set(o),d=0;for(let f of r)u.has(f)&&d++;c+=d*10}return i>0&&(c+=i*30),c}function b$(t,{limit:e=10,minScore:s=15}={}){if(!t||Sn.length===0)return[];let n=[];for(let o of Sn){let r=uf(o,t);r>=s&&n.push({file:o,score:r})}return n.sort((o,r)=>r.score-o.score),n.slice(0,e)}var Za=null,rf=0,x$=12e4,k$=new Set([".js",".ts",".jsx",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".rb"]);function df(t,e){let s=[],n=t.split(`
119
- `);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 l=r.match(/(?:export\s+)?class\s+(\w+)/);l&&s.push({type:"class",name:l[1],line:i});let c=r.match(/(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?(?:\([^)]*\)|[\w$]+)\s*=>/);c&&s.push({type:"function",name:c[1],line:i});let u=r.match(/module\.exports\s*=\s*\{([^}]+)\}/);if(u){let f=u[1].split(",").map(p=>p.trim().split(":")[0].trim()).filter(Boolean);for(let p of f)/^\w+$/.test(p)&&s.push({type:"export",name:p,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 l=r.match(/^class\s+(\w+)/);l&&s.push({type:"class",name:l[1],line:i});let c=r.match(/^(?:from\s+(\S+)\s+)?import\s+(\S+)/);c&&s.push({type:"import",name:c[1]||c[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 l=r.match(/^type\s+(\w+)\s+struct/);l&&s.push({type:"class",name:l[1],line:i})}}return s}async function ff(t){t=t||process.cwd();let e=kn.join(t,".nex","index","content-index.json"),s={};if(Za&&Date.now()-rf<x$)return Za;try{let i=await Cs.readFile(e,"utf-8");s=JSON.parse(i)}catch{s={files:{}}}el().length===0&&await lf(t);let o={files:{}},r=!1;for(let i of el()){let a=kn.extname(i);if(!k$.has(a))continue;let l=kn.join(t,i);try{let u=(await Cs.stat(l)).mtimeMs;if(s.files[i]&&s.files[i].mtime===u){o.files[i]=s.files[i];continue}let d=await Cs.readFile(l,"utf-8"),f=df(d,a);o.files[i]={defs:f,mtime:u},r=!0}catch{}}if(r){let i=kn.join(t,".nex","index");await Cs.mkdir(i,{recursive:!0}),await Cs.writeFile(e,JSON.stringify(o),"utf-8")}return Za=o,rf=Date.now(),o}async function S$(t,e){let s=await ff(),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,l=i.name.toLowerCase()===o?0:1;if(a!==l)return a-l;let c=r.name.toLowerCase().startsWith(o)?0:1,u=i.name.toLowerCase().startsWith(o)?0:1;return c-u}),n.slice(0,50)}pf.exports={refreshIndex:lf,getFileIndex:el,getIndexedCwd:w$,findFileInIndex:_$,searchIndex:$$,isIndexValid:af,buildContentIndex:ff,searchContentIndex:S$,extractDefinitions:df,smartSearch:b$,scorePathMatch:uf,pathLevenshtein:cf}});var Os=Z((SR,_f)=>{var zr=require("fs"),Jr=require("path"),Zr=require("os"),{execFile:v$}=require("child_process"),{promisify:E$}=require("util"),nl=E$(v$),T$=Jr.join(Zr.homedir(),".nex","servers.json"),Kr=Jr.join(Zr.tmpdir(),"nex-ssh-sockets");function R$(){return Jr.join(process.cwd(),".nex","servers.json")}function hf(){let t=n=>{if(!zr.existsSync(n))return{};try{return JSON.parse(zr.readFileSync(n,"utf-8"))}catch{return{}}},e=t(T$),s=t(R$());return{...e,...s}}function C$(t){let e=hf();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 A$(){zr.existsSync(Kr)||zr.mkdirSync(Kr,{recursive:!0})}function mf(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-o","ServerAliveInterval=30"];t.key&&e.push("-i",t.key.replace(/^~/,Zr.homedir())),t.port&&Number(t.port)!==22&&e.push("-p",String(t.port)),A$();let s=t.user?`${t.user}@${t.host}`:t.host,n=Jr.join(Kr,s.replace(/[@.:]/g,"_"));return e.push("-o","ControlMaster=auto","-o",`ControlPath=${n}`,"-o","ControlPersist=120"),e.push(s),{args:e,target:s}}function gf(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-r"];return t.key&&e.push("-i",t.key.replace(/^~/,Zr.homedir())),t.port&&Number(t.port)!==22&&e.push("-P",String(t.port)),e}async function Xr(t,e,{timeout:s=3e4,sudo:n=!1}={}){let{args:o}=mf(t),r=n&&t.sudo?`sudo sh -c ${JSON.stringify(e)}`:e;try{let{stdout:i,stderr:a}=await nl("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,l=(i.stderr||i.message||"").toString();return{stdout:(i.stdout||"").toString(),stderr:l,exitCode:a,error:Qr(l,t)}}}async function O$(t,e,s,{timeout:n=12e4}={}){let o=gf(t),r=t.user?`${t.user}@${t.host}`:t.host;o.push(e,`${r}:${s}`);try{let{stdout:i,stderr:a}=await nl("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(Qr(a,t)||a)}}async function N$(t,e,s,{timeout:n=12e4}={}){let o=gf(t),r=t.user?`${t.user}@${t.host}`:t.host;o.push(`${r}:${e}`,s);try{let{stdout:i,stderr:a}=await nl("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(Qr(a,t)||a)}}function Qr(t,e){if(!t)return"";if(/connection refused/i.test(t)){let s=e.port||22;return`${t}
114
+ `).length;return s.length===0||o===0?null:o===1?y$(s,e):_$(s,e,o)}function uf(t){return Math.max(1,Math.floor(t/f$))}function df(t,e){return t<=Math.ceil(e*p$)}function y$(t,e){let s=e.trim(),n=uf(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 l=Xr(a.trim(),s);l<r&&(r=l,o={text:a,distance:l,line:i+1})}return o&&n>1&&(o=w$(t,s,o,n)||o,r=o.distance),df(r,e.length)?o:null}function w$(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,l=null;for(let c=r;c<=i;c++){let u=t[c];if(!u.trim())continue;let d=Xr(u.trim(),e);d<a&&(a=d,l={text:u,distance:d,line:c+1})}return l}function _$(t,e,s){let n=t.length-s+1;if(n<=0)return null;let o=uf(n),r=null,i=1/0;for(let a=0;a<n;a+=o){let l=t.slice(a,a+s).join(`
115
+ `),c=Xr(l,e);c<i&&(i=c,r={text:l,distance:c,line:a+1})}return r&&o>1&&(r=$$(t,e,r,o,s,n)||r,i=r.distance),df(i,e.length)?r:null}function $$(t,e,s,n,o,r){let i=s.line-1,a=Math.max(0,i-n),l=Math.min(r-1,i+n),c=s.distance,u=null;for(let d=a;d<=l;d++){let f=t.slice(d,d+o).join(`
116
+ `),p=Xr(f,e);p<c&&(c=p,u={text:f,distance:p,line:d+1})}return u}ff.exports={normalizeWhitespace:sl,fuzzyFindText:m$,findMostSimilar:g$}});var mf=Q((BR,hf)=>{var{C:FR}=Ke(),b$=[{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}],x$=[{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 k$(t,e){let s=e.split(`
117
+ `),n=[],o=t?`.${t.split(".").pop()}`:"";for(let r=0;r<s.length;r++){let i=s[r],a=r+1;for(let l of b$)l.regex.test(i)&&n.push({line:a,message:`Potential secret detected: ${l.name}`,severity:"error"});for(let l of x$)l.ext&&!l.ext.includes(o)||l.regex.test(i)&&n.push({line:a,message:l.message||`Found ${l.name}`,severity:l.severity||"warn"})}return s.length>500&&n.push({line:0,message:`Large file detected (${s.length} lines). Consider refactoring.`,severity:"info"}),n}function S$(){let t=process.memoryUsage();return{rss:Math.round(t.rss/1024/1024*100)/100,heapUsed:Math.round(t.heapUsed/1024/1024*100)/100}}hf.exports={runDiagnostics:k$,getMemoryUsage:S$}});var Ns=Q((UR,kf)=>{var Os=require("fs").promises,xn=require("path"),{exec:v$}=require("util").promisify(require("child_process").exec),kn=[],al=null,Vr=!1,rl=0,E$=6e4;function yf(t){return!(kn.length===0||al!==t||Date.now()-rl>E$)}async function wf(t){if(!Vr&&!yf(t)){Vr=!0,al=t;try{try{let{stdout:n}=await v$("rg --files",{cwd:t,timeout:5e3});kn=n.split(`
118
+ `).filter(Boolean),rl=Date.now(),Vr=!1;return}catch{}let e=[],s=async(n,o)=>{let r;try{r=await Os.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(xn.join(n,i.name),a):e.push(a)}};await s(t,""),kn=e,rl=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{Vr=!1}}}function il(){return kn}function T$(){return al}function R$(t){return kn.filter(e=>xn.basename(e)===t)}function C$(t){let e=t.toLowerCase();return kn.filter(s=>s.toLowerCase().includes(e)).slice(0,20)}function _f(t,e){let s=t.length,n=e.length;if(s===0)return n;if(n===0)return s;let o=Array.from({length:n+1},(r,i)=>i);for(let r=1;r<=s;r++){let i=r-1;o[0]=r;for(let a=1;a<=n;a++){let l=t[r-1]===e[a-1]?i:1+Math.min(o[a],o[a-1],i);i=o[a],o[a]=l}}return o[n]}function $f(t,e){let s=t.toLowerCase(),n=e.toLowerCase();if(s===n)return 1e3;let o=s.split("/").filter(Boolean),r=n.split("/").filter(Boolean),i=0;for(let u=1;u<=Math.min(o.length,r.length)&&o[o.length-u]===r[r.length-u];u++)i=u;if(i>0&&i===r.length)return 500+i*100;let a=xn.basename(t).toLowerCase(),l=xn.basename(e).toLowerCase(),c=0;if(a===l)c+=80;else{let u=Math.max(a.length,l.length);if(u>0&&u<100){let f=1-_f(a,l)/u;f>=.6&&(c+=Math.round(f*50))}}if((s.includes(n)||n.includes(s))&&(c+=20),r.length>1){let u=new Set(o),d=0;for(let f of r)u.has(f)&&d++;c+=d*10}return i>0&&(c+=i*30),c}function A$(t,{limit:e=10,minScore:s=15}={}){if(!t||kn.length===0)return[];let n=[];for(let o of kn){let r=$f(o,t);r>=s&&n.push({file:o,score:r})}return n.sort((o,r)=>r.score-o.score),n.slice(0,e)}var ol=null,gf=0,O$=12e4,N$=new Set([".js",".ts",".jsx",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".rb"]);function bf(t,e){let s=[],n=t.split(`
119
+ `);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 l=r.match(/(?:export\s+)?class\s+(\w+)/);l&&s.push({type:"class",name:l[1],line:i});let c=r.match(/(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?(?:\([^)]*\)|[\w$]+)\s*=>/);c&&s.push({type:"function",name:c[1],line:i});let u=r.match(/module\.exports\s*=\s*\{([^}]+)\}/);if(u){let f=u[1].split(",").map(p=>p.trim().split(":")[0].trim()).filter(Boolean);for(let p of f)/^\w+$/.test(p)&&s.push({type:"export",name:p,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 l=r.match(/^class\s+(\w+)/);l&&s.push({type:"class",name:l[1],line:i});let c=r.match(/^(?:from\s+(\S+)\s+)?import\s+(\S+)/);c&&s.push({type:"import",name:c[1]||c[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 l=r.match(/^type\s+(\w+)\s+struct/);l&&s.push({type:"class",name:l[1],line:i})}}return s}async function xf(t){t=t||process.cwd();let e=xn.join(t,".nex","index","content-index.json"),s={};if(ol&&Date.now()-gf<O$)return ol;try{let i=await Os.readFile(e,"utf-8");s=JSON.parse(i)}catch{s={files:{}}}il().length===0&&await wf(t);let o={files:{}},r=!1;for(let i of il()){let a=xn.extname(i);if(!N$.has(a))continue;let l=xn.join(t,i);try{let u=(await Os.stat(l)).mtimeMs;if(s.files[i]&&s.files[i].mtime===u){o.files[i]=s.files[i];continue}let d=await Os.readFile(l,"utf-8"),f=bf(d,a);o.files[i]={defs:f,mtime:u},r=!0}catch{}}if(r){let i=xn.join(t,".nex","index");await Os.mkdir(i,{recursive:!0}),await Os.writeFile(e,JSON.stringify(o),"utf-8")}return ol=o,gf=Date.now(),o}async function M$(t,e){let s=await xf(),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,l=i.name.toLowerCase()===o?0:1;if(a!==l)return a-l;let c=r.name.toLowerCase().startsWith(o)?0:1,u=i.name.toLowerCase().startsWith(o)?0:1;return c-u}),n.slice(0,50)}kf.exports={refreshIndex:wf,getFileIndex:il,getIndexedCwd:T$,findFileInIndex:R$,searchIndex:C$,isIndexValid:yf,buildContentIndex:xf,searchContentIndex:M$,extractDefinitions:bf,smartSearch:A$,scorePathMatch:$f,pathLevenshtein:_f}});var Ms=Q((WR,Cf)=>{var Jr=require("fs"),ti=require("path"),ni=require("os"),{execFile:P$}=require("child_process"),{promisify:L$}=require("util"),ll=L$(P$),I$=ti.join(ni.homedir(),".nex","servers.json"),Zr=ti.join(ni.tmpdir(),"nex-ssh-sockets");function D$(){return ti.join(process.cwd(),".nex","servers.json")}function Sf(){let t=n=>{if(!Jr.existsSync(n))return{};try{return JSON.parse(Jr.readFileSync(n,"utf-8"))}catch{return{}}},e=t(I$),s=t(D$());return{...e,...s}}function j$(t){let e=Sf();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 q$(){Jr.existsSync(Zr)||Jr.mkdirSync(Zr,{recursive:!0})}function vf(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-o","ServerAliveInterval=30"];t.key&&e.push("-i",t.key.replace(/^~/,ni.homedir())),t.port&&Number(t.port)!==22&&e.push("-p",String(t.port)),q$();let s=t.user?`${t.user}@${t.host}`:t.host,n=ti.join(Zr,s.replace(/[@.:]/g,"_"));return e.push("-o","ControlMaster=auto","-o",`ControlPath=${n}`,"-o","ControlPersist=120"),e.push(s),{args:e,target:s}}function Ef(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-r"];return t.key&&e.push("-i",t.key.replace(/^~/,ni.homedir())),t.port&&Number(t.port)!==22&&e.push("-P",String(t.port)),e}async function Qr(t,e,{timeout:s=3e4,sudo:n=!1}={}){let{args:o}=vf(t),r=n&&t.sudo?`sudo sh -c ${JSON.stringify(e)}`:e;try{let{stdout:i,stderr:a}=await ll("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,l=(i.stderr||i.message||"").toString();return{stdout:(i.stdout||"").toString(),stderr:l,exitCode:a,error:si(l,t)}}}async function F$(t,e,s,{timeout:n=12e4}={}){let o=Ef(t),r=t.user?`${t.user}@${t.host}`:t.host;o.push(e,`${r}:${s}`);try{let{stdout:i,stderr:a}=await ll("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(si(a,t)||a)}}async function B$(t,e,s,{timeout:n=12e4}={}){let o=Ef(t),r=t.user?`${t.user}@${t.host}`:t.host;o.push(`${r}:${e}`,s);try{let{stdout:i,stderr:a}=await ll("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(si(a,t)||a)}}function si(t,e){if(!t)return"";if(/connection refused/i.test(t)){let s=e.port||22;return`${t}
120
120
  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}
121
121
  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}
122
122
  HINT: Cannot reach ${e.host}. Check: network connection, correct hostname/IP, DNS resolution.`:/host key verification failed/i.test(t)?`${t}
123
123
  HINT: Host key changed for ${e.host}. To reset: ssh-keygen -R ${e.host}`:/timed out/i.test(t)?`${t}
124
124
  HINT: Connection timed out to ${e.host}. Check firewall rules and network connectivity.`:/too many authentication failures/i.test(t)?`${t}
125
- HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function M$(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}`}var Vr=new Map,P$=12e4;async function yf(t,e,{force:s=!1}={}){let o=`${t.user?`${t.user}@${t.host}`:t.host}:${e}`,r=Vr.get(o);if(!s&&r&&Date.now()-r.time<P$)return r.files;let i=`find ${e} -maxdepth 6 -type f -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/venv/*' -not -path '*/__pycache__/*' -not -path '*/dist/*' -not -name '*.pyc' 2>/dev/null | head -5000`,{stdout:a,exitCode:l}=await Xr(t,i,{timeout:15e3});if(l!==0||!a.trim())return[];let c=e.endsWith("/")?e:e+"/",u=a.split(`
126
- `).filter(Boolean).map(d=>d.startsWith(c)?d.slice(c.length):d);return Vr.set(o,{files:u,time:Date.now()}),u}async function wf(t,e,s,{limit:n=5,minScore:o=15}={}){let r=await yf(t,e);if(r.length===0)return[];let{scorePathMatch:i}=As(),a=[];for(let l of r){let c=i(l,s);c>=o&&a.push({file:l,score:c})}return a.sort((l,c)=>c.score-l.score),a.slice(0,n)}async function L$(t,e,s){if(!s)return{fixedPath:null,message:""};let n=s.replace(/\/+/g,"/");if(n.startsWith("~/")){let{stdout:r}=await Xr(t,"echo $HOME",{timeout:5e3}),i=r.trim();i&&(n=n.replace("~/",i+"/"))}if(n.startsWith("/")){let{exitCode:r}=await Xr(t,`test -f ${JSON.stringify(n)}`,{timeout:5e3});if(r===0)return{fixedPath:n,message:"(auto-fixed: normalized path)"}}let o=await wf(t,e,s,{limit:5,minScore:15});if(o.length>0){let i=(e.endsWith("/")?e:e+"/")+o[0].file;if(o[0].score>=200||o.length===1&&o[0].score>=50)return{fixedPath:i,message:`(auto-fixed: remote smart match \u2192 ${o[0].file})`};if(o.length>=2&&o[0].score>=80&&o[0].score>=o[1].score*1.5)return{fixedPath:i,message:`(auto-fixed: remote best match \u2192 ${o[0].file})`};if(o.length<=5)return{fixedPath:null,message:`File not found on remote. Did you mean:
125
+ HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function U$(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}`}var ei=new Map,W$=12e4;async function Tf(t,e,{force:s=!1}={}){let o=`${t.user?`${t.user}@${t.host}`:t.host}:${e}`,r=ei.get(o);if(!s&&r&&Date.now()-r.time<W$)return r.files;let i=`find ${e} -maxdepth 6 -type f -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/venv/*' -not -path '*/__pycache__/*' -not -path '*/dist/*' -not -name '*.pyc' 2>/dev/null | head -5000`,{stdout:a,exitCode:l}=await Qr(t,i,{timeout:15e3});if(l!==0||!a.trim())return[];let c=e.endsWith("/")?e:e+"/",u=a.split(`
126
+ `).filter(Boolean).map(d=>d.startsWith(c)?d.slice(c.length):d);return ei.set(o,{files:u,time:Date.now()}),u}async function Rf(t,e,s,{limit:n=5,minScore:o=15}={}){let r=await Tf(t,e);if(r.length===0)return[];let{scorePathMatch:i}=Ns(),a=[];for(let l of r){let c=i(l,s);c>=o&&a.push({file:l,score:c})}return a.sort((l,c)=>c.score-l.score),a.slice(0,n)}async function H$(t,e,s){if(!s)return{fixedPath:null,message:""};let n=s.replace(/\/+/g,"/");if(n.startsWith("~/")){let{stdout:r}=await Qr(t,"echo $HOME",{timeout:5e3}),i=r.trim();i&&(n=n.replace("~/",i+"/"))}if(n.startsWith("/")){let{exitCode:r}=await Qr(t,`test -f ${JSON.stringify(n)}`,{timeout:5e3});if(r===0)return{fixedPath:n,message:"(auto-fixed: normalized path)"}}let o=await Rf(t,e,s,{limit:5,minScore:15});if(o.length>0){let i=(e.endsWith("/")?e:e+"/")+o[0].file;if(o[0].score>=200||o.length===1&&o[0].score>=50)return{fixedPath:i,message:`(auto-fixed: remote smart match \u2192 ${o[0].file})`};if(o.length>=2&&o[0].score>=80&&o[0].score>=o[1].score*1.5)return{fixedPath:i,message:`(auto-fixed: remote best match \u2192 ${o[0].file})`};if(o.length<=5)return{fixedPath:null,message:`File not found on remote. Did you mean:
127
127
  ${o.map(a=>` - ${a.file}`).join(`
128
- `)}`}}return{fixedPath:null,message:""}}function I$(t){t?Vr.delete(t):Vr.clear()}_f.exports={loadServerProfiles:hf,resolveProfile:C$,buildSSHArgs:mf,sshExec:Xr,scpUpload:O$,scpDownload:N$,enrichSSHError:Qr,formatProfile:M$,SSH_SOCKET_DIR:Kr,getRemoteIndex:yf,remoteSmartSearch:wf,remoteAutoFixPath:L$,clearRemoteIndex:I$}});var xf=Z((vR,bf)=>{var mo=require("fs"),sl=require("path"),D$=sl.join(".nex","deploy.json");function ol(){return sl.join(process.cwd(),D$)}function $f(){let t=ol();if(!mo.existsSync(t))return{};try{return JSON.parse(mo.readFileSync(t,"utf-8"))}catch{return{}}}function j$(t){let e=$f();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 q$(t){let e=sl.join(process.cwd(),".nex");mo.existsSync(e)||mo.mkdirSync(e,{recursive:!0}),mo.writeFileSync(ol(),JSON.stringify(t,null,2)+`
129
- `,"utf-8")}bf.exports={loadDeployConfigs:$f,resolveDeployConfig:j$,saveDeployConfigs:q$,getDeployConfigPath:ol}});var _o=Z((ER,vf)=>{var{getActiveModel:F$,getActiveProviderName:B$}=Ze(),go={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},yo={"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"},wo={ollama:"full",openai:"full",anthropic:"full",gemini:"full",local:"essential"},Jt={};function Sf(){try{let t=require("fs"),s=require("path").join(process.cwd(),".nex","config.json");t.existsSync(s)&&(Jt=JSON.parse(t.readFileSync(s,"utf-8")).toolTiers||{})}catch{Jt={}}}Sf();function rl(){let e=F$()?.id,s=B$();return e&&Jt[e]?Jt[e]:s&&Jt[`${s}:*`]?Jt[`${s}:*`]:e&&yo[e]?yo[e]:s&&wo[s]?wo[s]:"full"}var U$=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"]),kf={anthropic:"strict",openai:"strict",gemini:"strict",ollama:"fuzzy",local:"fuzzy"};function W$(t,e){return t&&(U$.has(t)||t.startsWith("claude-"))?"strict":e&&kf[e]?kf[e]:"fuzzy"}function H$(t,e){return t&&Jt[t]?Jt[t]:e&&Jt[`${e}:*`]?Jt[`${e}:*`]:t&&yo[t]?yo[t]:e&&wo[e]?wo[e]:"full"}function Y$(t,e){let s=e||rl();if(s==="full"||!go[s])return t;let n=new Set(go[s]);return t.filter(o=>n.has(o.function.name))}function G$(){let t=rl(),e=go[t]?go[t].length:"all";return{tier:t,toolCount:e}}vf.exports={filterToolsForModel:Y$,getActiveTier:rl,getModelTier:H$,getEditMode:W$,getTierInfo:G$,TIERS:go,MODEL_TIERS:yo,PROVIDER_DEFAULT_TIER:wo,loadConfigOverrides:Sf}});var dn=Z((TR,Rf)=>{var il=null,un=null,$o=null,Ef=`Playwright is not installed. Install with:
128
+ `)}`}}return{fixedPath:null,message:""}}function Y$(t){t?ei.delete(t):ei.clear()}Cf.exports={loadServerProfiles:Sf,resolveProfile:j$,buildSSHArgs:vf,sshExec:Qr,scpUpload:F$,scpDownload:B$,enrichSSHError:si,formatProfile:U$,SSH_SOCKET_DIR:Zr,getRemoteIndex:Tf,remoteSmartSearch:Rf,remoteAutoFixPath:H$,clearRemoteIndex:Y$}});var Nf=Q((HR,Of)=>{var _o=require("fs"),cl=require("path"),G$=cl.join(".nex","deploy.json");function ul(){return cl.join(process.cwd(),G$)}function Af(){let t=ul();if(!_o.existsSync(t))return{};try{return JSON.parse(_o.readFileSync(t,"utf-8"))}catch{return{}}}function z$(t){let e=Af();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 K$(t){let e=cl.join(process.cwd(),".nex");_o.existsSync(e)||_o.mkdirSync(e,{recursive:!0}),_o.writeFileSync(ul(),JSON.stringify(t,null,2)+`
129
+ `,"utf-8")}Of.exports={loadDeployConfigs:Af,resolveDeployConfig:z$,saveDeployConfigs:K$,getDeployConfigPath:ul}});var ko=Q((YR,Lf)=>{var{getActiveModel:X$,getActiveProviderName:V$}=Qe(),$o={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},bo={"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"},xo={ollama:"full",openai:"full",anthropic:"full",gemini:"full",local:"essential"},Jt={};function Pf(){try{let t=require("fs"),s=require("path").join(process.cwd(),".nex","config.json");t.existsSync(s)&&(Jt=JSON.parse(t.readFileSync(s,"utf-8")).toolTiers||{})}catch{Jt={}}}Pf();function dl(){let e=X$()?.id,s=V$();return e&&Jt[e]?Jt[e]:s&&Jt[`${s}:*`]?Jt[`${s}:*`]:e&&bo[e]?bo[e]:s&&xo[s]?xo[s]:"full"}var J$=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"]),Mf={anthropic:"strict",openai:"strict",gemini:"strict",ollama:"fuzzy",local:"fuzzy"};function Z$(t,e){return t&&(J$.has(t)||t.startsWith("claude-"))?"strict":e&&Mf[e]?Mf[e]:"fuzzy"}function Q$(t,e){return t&&Jt[t]?Jt[t]:e&&Jt[`${e}:*`]?Jt[`${e}:*`]:t&&bo[t]?bo[t]:e&&xo[e]?xo[e]:"full"}function eb(t,e){let s=e||dl();if(s==="full"||!$o[s])return t;let n=new Set($o[s]);return t.filter(o=>n.has(o.function.name))}function tb(){let t=dl(),e=$o[t]?$o[t].length:"all";return{tier:t,toolCount:e}}Lf.exports={filterToolsForModel:eb,getActiveTier:dl,getModelTier:Q$,getEditMode:Z$,getTierInfo:tb,TIERS:$o,MODEL_TIERS:bo,PROVIDER_DEFAULT_TIER:xo,loadConfigOverrides:Pf}});var dn=Q((GR,jf)=>{var fl=null,un=null,So=null,If=`Playwright is not installed. Install with:
130
130
  npm install playwright && npx playwright install chromium
131
- Then restart nex-code.`;function Tf(){if($o!==null)return $o;try{require("playwright"),$o=!0}catch{$o=!1}return $o}async function ei(){if(!Tf())throw new Error(Ef);return il||(il=require("playwright")),(!un||!un.isConnected())&&(un=await il.chromium.launch({headless:!0})),un}async function z$(){if(un){try{await un.close()}catch(t){console.error("closeBrowser failed:",t.message)}un=null}}process.on("exit",()=>{if(un)try{un.close()}catch(t){console.error("Error closing browser on exit:",t.message)}});async function K$(t,{timeout:e=3e4,waitFor:s="domcontentloaded"}={}){let o=await(await ei()).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(c=>c.remove()),document.body?.innerText||"")),a=await o.evaluate(()=>Array.from(document.querySelectorAll("a[href]")).slice(0,30).map(l=>({text:(l.innerText||l.textContent||"").trim().substring(0,80),href:l.href})).filter(l=>l.text&&l.href&&!l.href.startsWith("javascript:")));return{title:r,url:o.url(),text:i.substring(0,8e3)+(i.length>8e3?`
132
- ...(truncated)`:""),links:a.slice(0,20)}}finally{await o.close()}}async function X$(t,{width:e=1280,height:s=800,fullPage:n=!1,timeout:o=3e4}={}){let i=await(await ei()).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}),l=require("os"),c=require("path"),u=require("fs"),d=c.join(l.tmpdir(),`nex-screenshot-${Date.now()}.png`);return u.writeFileSync(d,a,{mode:384}),{path:d,base64:a.toString("base64"),media_type:"image/png",title:await i.title(),url:i.url()}}finally{await i.close()}}async function V$(t,{selector:e,text:s,timeout:n=3e4}={}){if(!e&&!s)throw new Error("selector or text is required");let r=await(await ei()).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 J$(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 ei()).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()}}Rf.exports={isPlaywrightAvailable:Tf,browserNavigate:K$,browserScreenshot:X$,browserClick:V$,browserFill:J$,closeBrowser:z$,INSTALL_MSG:Ef}});var al=Z((RR,Af)=>{"use strict";var Z$=require("util"),Cf=require("stream"),Ut=Af.exports=function(){Cf.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};Z$.inherits(Ut,Cf);Ut.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e}),process.nextTick(function(){this._process(),this._paused&&this._reads&&this._reads.length>0&&(this._paused=!1,this.emit("drain"))}.bind(this))};Ut.prototype.write=function(t,e){if(!this.writable)return this.emit("error",new Error("Stream not writable")),!1;let s;return Buffer.isBuffer(t)?s=t:s=Buffer.from(t,e||this._encoding),this._buffers.push(s),this._buffered+=s.length,this._process(),this._reads&&this._reads.length===0&&(this._paused=!0),this.writable&&!this._paused};Ut.prototype.end=function(t,e){t&&this.write(t,e),this.writable=!1,this._buffers&&(this._buffers.length===0?this._end():(this._buffers.push(null),this._process()))};Ut.prototype.destroySoon=Ut.prototype.end;Ut.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};Ut.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};Ut.prototype._processReadAllowingLess=function(t){this._reads.shift();let e=this._buffers[0];e.length>t.length?(this._buffered-=t.length,this._buffers[0]=e.slice(t.length),t.func.call(this,e.slice(0,t.length))):(this._buffered-=e.length,this._buffers.shift(),t.func.call(this,e))};Ut.prototype._processRead=function(t){this._reads.shift();let e=0,s=0,n=Buffer.alloc(t.length);for(;e<t.length;){let o=this._buffers[s++],r=Math.min(o.length,t.length-e);o.copy(n,e,0,r),e+=r,r!==o.length&&(this._buffers[--s]=o.slice(r))}s>0&&this._buffers.splice(0,s),this._buffered-=t.length,t.func.call(this,n)};Ut.prototype._process=function(){try{for(;this._buffered>0&&this._reads&&this._reads.length>0;){let t=this._reads[0];if(t.allowLess)this._processReadAllowingLess(t);else if(this._buffered>=t.length)this._processRead(t);else break}this._buffers&&!this.writable&&this._end()}catch(t){this.emit("error",t)}}});var cl=Z(ll=>{"use strict";var vn=[{x:[0],y:[0]},{x:[4],y:[0]},{x:[0,4],y:[4]},{x:[2,6],y:[0,4]},{x:[0,2,4,6],y:[2,6]},{x:[1,3,5,7],y:[0,2,4,6]},{x:[0,1,2,3,4,5,6,7],y:[1,3,5,7]}];ll.getImagePasses=function(t,e){let s=[],n=t%8,o=e%8,r=(t-n)/8,i=(e-o)/8;for(let a=0;a<vn.length;a++){let l=vn[a],c=r*l.x.length,u=i*l.y.length;for(let d=0;d<l.x.length&&l.x[d]<n;d++)c++;for(let d=0;d<l.y.length&&l.y[d]<o;d++)u++;c>0&&u>0&&s.push({width:c,height:u,index:a})}return s};ll.getInterlaceIterator=function(t){return function(e,s,n){let o=e%vn[n].x.length,r=(e-o)/vn[n].x.length*8+vn[n].x[o],i=s%vn[n].y.length,a=(s-i)/vn[n].y.length*8+vn[n].y[i];return r*4+a*t*4}}});var ul=Z((AR,Of)=>{"use strict";Of.exports=function(e,s,n){let o=e+s-n,r=Math.abs(o-e),i=Math.abs(o-s),a=Math.abs(o-n);return r<=i&&r<=a?e:i<=a?s:n}});var dl=Z((OR,Mf)=>{"use strict";var Q$=cl(),eb=ul();function Nf(t,e,s){let n=t*e;return s!==8&&(n=Math.ceil(n/(8/s))),n}var Ns=Mf.exports=function(t,e){let s=t.width,n=t.height,o=t.interlace,r=t.bpp,i=t.depth;if(this.read=e.read,this.write=e.write,this.complete=e.complete,this._imageIndex=0,this._images=[],o){let a=Q$.getImagePasses(s,n);for(let l=0;l<a.length;l++)this._images.push({byteWidth:Nf(a[l].width,r,i),height:a[l].height,lineIndex:0})}else this._images.push({byteWidth:Nf(s,r,i),height:n,lineIndex:0});i===8?this._xComparison=r:i===16?this._xComparison=r*2:this._xComparison=1};Ns.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};Ns.prototype._unFilterType1=function(t,e,s){let n=this._xComparison,o=n-1;for(let r=0;r<s;r++){let i=t[1+r],a=r>o?e[r-n]:0;e[r]=i+a}};Ns.prototype._unFilterType2=function(t,e,s){let n=this._lastLine;for(let o=0;o<s;o++){let r=t[1+o],i=n?n[o]:0;e[o]=r+i}};Ns.prototype._unFilterType3=function(t,e,s){let n=this._xComparison,o=n-1,r=this._lastLine;for(let i=0;i<s;i++){let a=t[1+i],l=r?r[i]:0,c=i>o?e[i-n]:0,u=Math.floor((c+l)/2);e[i]=a+u}};Ns.prototype._unFilterType4=function(t,e,s){let n=this._xComparison,o=n-1,r=this._lastLine;for(let i=0;i<s;i++){let a=t[1+i],l=r?r[i]:0,c=i>o?e[i-n]:0,u=i>o&&r?r[i-n]:0,d=eb(c,l,u);e[i]=a+d}};Ns.prototype._reverseFilterLine=function(t){let e=t[0],s,n=this._images[this._imageIndex],o=n.byteWidth;if(e===0)s=t.slice(1,o+1);else switch(s=Buffer.alloc(o),e){case 1:this._unFilterType1(t,s,o);break;case 2:this._unFilterType2(t,s,o);break;case 3:this._unFilterType3(t,s,o);break;case 4:this._unFilterType4(t,s,o);break;default:throw new Error("Unrecognised filter type - "+e)}this.write(s),n.lineIndex++,n.lineIndex>=n.height?(this._lastLine=null,this._imageIndex++,n=this._images[this._imageIndex]):this._lastLine=s,n?this.read(n.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}});var If=Z((NR,Lf)=>{"use strict";var tb=require("util"),Pf=al(),nb=dl(),sb=Lf.exports=function(t){Pf.call(this);let e=[],s=this;this._filter=new nb(t,{read:this.read.bind(this),write:function(n){e.push(n)},complete:function(){s.emit("complete",Buffer.concat(e))}}),this._filter.start()};tb.inherits(sb,Pf)});var Ms=Z((MR,Df)=>{"use strict";Df.exports={PNG_SIGNATURE:[137,80,78,71,13,10,26,10],TYPE_IHDR:1229472850,TYPE_IEND:1229278788,TYPE_IDAT:1229209940,TYPE_PLTE:1347179589,TYPE_tRNS:1951551059,TYPE_gAMA:1732332865,COLORTYPE_GRAYSCALE:0,COLORTYPE_PALETTE:1,COLORTYPE_COLOR:2,COLORTYPE_ALPHA:4,COLORTYPE_PALETTE_COLOR:3,COLORTYPE_COLOR_ALPHA:6,COLORTYPE_TO_BPP_MAP:{0:1,2:3,3:1,4:2,6:4},GAMMA_DIVISION:1e5}});var hl=Z((PR,jf)=>{"use strict";var fl=[];(function(){for(let t=0;t<256;t++){let e=t;for(let s=0;s<8;s++)e&1?e=3988292384^e>>>1:e=e>>>1;fl[t]=e}})();var pl=jf.exports=function(){this._crc=-1};pl.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=fl[(this._crc^t[e])&255]^this._crc>>>8;return!0};pl.prototype.crc32=function(){return this._crc^-1};pl.crc32=function(t){let e=-1;for(let s=0;s<t.length;s++)e=fl[(e^t[s])&255]^e>>>8;return e^-1}});var ml=Z((LR,qf)=>{"use strict";var Ye=Ms(),ob=hl(),Xe=qf.exports=function(t,e){this._options=t,t.checkCRC=t.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[Ye.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[Ye.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[Ye.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[Ye.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[Ye.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[Ye.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=e.read,this.error=e.error,this.metadata=e.metadata,this.gamma=e.gamma,this.transColor=e.transColor,this.palette=e.palette,this.parsed=e.parsed,this.inflateData=e.inflateData,this.finished=e.finished,this.simpleTransparency=e.simpleTransparency,this.headersFinished=e.headersFinished||function(){}};Xe.prototype.start=function(){this.read(Ye.PNG_SIGNATURE.length,this._parseSignature.bind(this))};Xe.prototype._parseSignature=function(t){let e=Ye.PNG_SIGNATURE;for(let s=0;s<e.length;s++)if(t[s]!==e[s]){this.error(new Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};Xe.prototype._parseChunkBegin=function(t){let e=t.readUInt32BE(0),s=t.readUInt32BE(4),n="";for(let r=4;r<8;r++)n+=String.fromCharCode(t[r]);let o=!!(t[4]&32);if(!this._hasIHDR&&s!==Ye.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new ob,this._crc.write(Buffer.from(n)),this._chunks[s])return this._chunks[s](e);if(!o){this.error(new Error("Unsupported critical chunk type "+n));return}this.read(e+4,this._skipChunk.bind(this))};Xe.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};Xe.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};Xe.prototype._parseChunkEnd=function(t){let e=t.readInt32BE(0),s=this._crc.crc32();if(this._options.checkCRC&&s!==e){this.error(new Error("Crc error - "+e+" - "+s));return}this._hasIEND||this.read(8,this._parseChunkBegin.bind(this))};Xe.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};Xe.prototype._parseIHDR=function(t){this._crc.write(t);let e=t.readUInt32BE(0),s=t.readUInt32BE(4),n=t[8],o=t[9],r=t[10],i=t[11],a=t[12];if(n!==8&&n!==4&&n!==2&&n!==1&&n!==16){this.error(new Error("Unsupported bit depth "+n));return}if(!(o in Ye.COLORTYPE_TO_BPP_MAP)){this.error(new Error("Unsupported color type"));return}if(r!==0){this.error(new Error("Unsupported compression method"));return}if(i!==0){this.error(new Error("Unsupported filter method"));return}if(a!==0&&a!==1){this.error(new Error("Unsupported interlace method"));return}this._colorType=o;let l=Ye.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:s,depth:n,interlace:!!a,palette:!!(o&Ye.COLORTYPE_PALETTE),color:!!(o&Ye.COLORTYPE_COLOR),alpha:!!(o&Ye.COLORTYPE_ALPHA),bpp:l,colorType:o}),this._handleChunkEnd()};Xe.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};Xe.prototype._parsePLTE=function(t){this._crc.write(t);let e=Math.floor(t.length/3);for(let s=0;s<e;s++)this._palette.push([t[s*3],t[s*3+1],t[s*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};Xe.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};Xe.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===Ye.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(new Error("Transparency chunk must be after palette"));return}if(t.length>this._palette.length){this.error(new Error("More transparent colors than palette size"));return}for(let e=0;e<t.length;e++)this._palette[e][3]=t[e];this.palette(this._palette)}this._colorType===Ye.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===Ye.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};Xe.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};Xe.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/Ye.GAMMA_DIVISION),this._handleChunkEnd()};Xe.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};Xe.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===Ye.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw new Error("Expected palette not found");this.inflateData(e);let s=t-e.length;s>0?this._handleIDAT(s):this._handleChunkEnd()};Xe.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};Xe.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var gl=Z(Bf=>{"use strict";var Ff=cl(),rb=[function(){},function(t,e,s,n){if(n===e.length)throw new Error("Ran out of data");let o=e[n];t[s]=o,t[s+1]=o,t[s+2]=o,t[s+3]=255},function(t,e,s,n){if(n+1>=e.length)throw new Error("Ran out of data");let o=e[n];t[s]=o,t[s+1]=o,t[s+2]=o,t[s+3]=e[n+1]},function(t,e,s,n){if(n+2>=e.length)throw new Error("Ran out of data");t[s]=e[n],t[s+1]=e[n+1],t[s+2]=e[n+2],t[s+3]=255},function(t,e,s,n){if(n+3>=e.length)throw new Error("Ran out of data");t[s]=e[n],t[s+1]=e[n+1],t[s+2]=e[n+2],t[s+3]=e[n+3]}],ib=[function(){},function(t,e,s,n){let o=e[0];t[s]=o,t[s+1]=o,t[s+2]=o,t[s+3]=n},function(t,e,s){let n=e[0];t[s]=n,t[s+1]=n,t[s+2]=n,t[s+3]=e[1]},function(t,e,s,n){t[s]=e[0],t[s+1]=e[1],t[s+2]=e[2],t[s+3]=n},function(t,e,s){t[s]=e[0],t[s+1]=e[1],t[s+2]=e[2],t[s+3]=e[3]}];function ab(t,e){let s=[],n=0;function o(){if(n===t.length)throw new Error("Ran out of data");let r=t[n];n++;let i,a,l,c,u,d,f,p;switch(e){default:throw new Error("unrecognised depth");case 16:f=t[n],n++,s.push((r<<8)+f);break;case 4:f=r&15,p=r>>4,s.push(p,f);break;case 2:u=r&3,d=r>>2&3,f=r>>4&3,p=r>>6&3,s.push(p,f,d,u);break;case 1:i=r&1,a=r>>1&1,l=r>>2&1,c=r>>3&1,u=r>>4&1,d=r>>5&1,f=r>>6&1,p=r>>7&1,s.push(p,f,d,u,c,l,a,i);break}}return{get:function(r){for(;s.length<r;)o();let i=s.slice(0,r);return s=s.slice(r),i},resetAfterLine:function(){s.length=0},end:function(){if(n!==t.length)throw new Error("extra data found")}}}function lb(t,e,s,n,o,r){let i=t.width,a=t.height,l=t.index;for(let c=0;c<a;c++)for(let u=0;u<i;u++){let d=s(u,c,l);rb[n](e,o,d,r),r+=n}return r}function cb(t,e,s,n,o,r){let i=t.width,a=t.height,l=t.index;for(let c=0;c<a;c++){for(let u=0;u<i;u++){let d=o.get(n),f=s(u,c,l);ib[n](e,d,f,r)}o.resetAfterLine()}}Bf.dataToBitMap=function(t,e){let s=e.width,n=e.height,o=e.depth,r=e.bpp,i=e.interlace,a;o!==8&&(a=ab(t,o));let l;o<=8?l=Buffer.alloc(s*n*4):l=new Uint16Array(s*n*4);let c=Math.pow(2,o)-1,u=0,d,f;if(i)d=Ff.getImagePasses(s,n),f=Ff.getInterlaceIterator(s,n);else{let p=0;f=function(){let h=p;return p+=4,h},d=[{width:s,height:n}]}for(let p=0;p<d.length;p++)o===8?u=lb(d[p],l,f,r,t,u):cb(d[p],l,f,r,a,c);if(o===8){if(u!==t.length)throw new Error("extra data found")}else a.end();return l}});var yl=Z((DR,Uf)=>{"use strict";function ub(t,e,s,n,o){let r=0;for(let i=0;i<n;i++)for(let a=0;a<s;a++){let l=o[t[r]];if(!l)throw new Error("index "+t[r]+" not in palette");for(let c=0;c<4;c++)e[r+c]=l[c];r+=4}}function db(t,e,s,n,o){let r=0;for(let i=0;i<n;i++)for(let a=0;a<s;a++){let l=!1;if(o.length===1?o[0]===t[r]&&(l=!0):o[0]===t[r]&&o[1]===t[r+1]&&o[2]===t[r+2]&&(l=!0),l)for(let c=0;c<4;c++)e[r+c]=0;r+=4}}function fb(t,e,s,n,o){let r=255,i=Math.pow(2,o)-1,a=0;for(let l=0;l<n;l++)for(let c=0;c<s;c++){for(let u=0;u<4;u++)e[a+u]=Math.floor(t[a+u]*r/i+.5);a+=4}}Uf.exports=function(t,e,s=!1){let n=e.depth,o=e.width,r=e.height,i=e.colorType,a=e.transColor,l=e.palette,c=t;return i===3?ub(t,c,o,r,l):(a&&db(t,c,o,r,a),n!==8&&!s&&(n===16&&(c=Buffer.alloc(o*r*4)),fb(t,c,o,r,n))),c}});var Yf=Z((jR,Hf)=>{"use strict";var pb=require("util"),wl=require("zlib"),Wf=al(),hb=If(),mb=ml(),gb=gl(),yb=yl(),Zt=Hf.exports=function(t){Wf.call(this),this._parser=new mb(t,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,"gamma"),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this),simpleTransparency:this._simpleTransparency.bind(this),headersFinished:this._headersFinished.bind(this)}),this._options=t,this.writable=!0,this._parser.start()};pb.inherits(Zt,Wf);Zt.prototype._handleError=function(t){this.emit("error",t),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy&&this._inflate.destroy(),this._filter&&(this._filter.destroy(),this._filter.on("error",function(){})),this.errord=!0};Zt.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=wl.createInflate(),this._inflate.on("error",this.emit.bind(this,"error")),this._filter.on("complete",this._complete.bind(this)),this._inflate.pipe(this._filter);else{let s=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,n=Math.max(s,wl.Z_MIN_CHUNK);this._inflate=wl.createInflate({chunkSize:n});let o=s,r=this.emit.bind(this,"error");this._inflate.on("error",function(a){o&&r(a)}),this._filter.on("complete",this._complete.bind(this));let i=this._filter.write.bind(this._filter);this._inflate.on("data",function(a){o&&(a.length>o&&(a=a.slice(0,o)),o-=a.length,i(a))}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};Zt.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new hb(this._bitmapInfo)};Zt.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};Zt.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};Zt.prototype._simpleTransparency=function(){this._metaData.alpha=!0};Zt.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};Zt.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};Zt.prototype._complete=function(t){if(this.errord)return;let e;try{let s=gb.dataToBitMap(t,this._bitmapInfo);e=yb(s,this._bitmapInfo,this._options.skipRescale),s=null}catch(s){this._handleError(s);return}this.emit("parsed",e)}});var zf=Z((qR,Gf)=>{"use strict";var Mt=Ms();Gf.exports=function(t,e,s,n){let o=[Mt.COLORTYPE_COLOR_ALPHA,Mt.COLORTYPE_ALPHA].indexOf(n.colorType)!==-1;if(n.colorType===n.inputColorType){let h=(function(){let g=new ArrayBuffer(2);return new DataView(g).setInt16(0,256,!0),new Int16Array(g)[0]!==256})();if(n.bitDepth===8||n.bitDepth===16&&h)return t}let r=n.bitDepth!==16?t:new Uint16Array(t.buffer),i=255,a=Mt.COLORTYPE_TO_BPP_MAP[n.inputColorType];a===4&&!n.inputHasAlpha&&(a=3);let l=Mt.COLORTYPE_TO_BPP_MAP[n.colorType];n.bitDepth===16&&(i=65535,l*=2);let c=Buffer.alloc(e*s*l),u=0,d=0,f=n.bgColor||{};f.red===void 0&&(f.red=i),f.green===void 0&&(f.green=i),f.blue===void 0&&(f.blue=i);function p(){let h,g,_,b=i;switch(n.inputColorType){case Mt.COLORTYPE_COLOR_ALPHA:b=r[u+3],h=r[u],g=r[u+1],_=r[u+2];break;case Mt.COLORTYPE_COLOR:h=r[u],g=r[u+1],_=r[u+2];break;case Mt.COLORTYPE_ALPHA:b=r[u+1],h=r[u],g=h,_=h;break;case Mt.COLORTYPE_GRAYSCALE:h=r[u],g=h,_=h;break;default:throw new Error("input color type:"+n.inputColorType+" is not supported at present")}return n.inputHasAlpha&&(o||(b/=i,h=Math.min(Math.max(Math.round((1-b)*f.red+b*h),0),i),g=Math.min(Math.max(Math.round((1-b)*f.green+b*g),0),i),_=Math.min(Math.max(Math.round((1-b)*f.blue+b*_),0),i))),{red:h,green:g,blue:_,alpha:b}}for(let h=0;h<s;h++)for(let g=0;g<e;g++){let _=p(r,u);switch(n.colorType){case Mt.COLORTYPE_COLOR_ALPHA:case Mt.COLORTYPE_COLOR:n.bitDepth===8?(c[d]=_.red,c[d+1]=_.green,c[d+2]=_.blue,o&&(c[d+3]=_.alpha)):(c.writeUInt16BE(_.red,d),c.writeUInt16BE(_.green,d+2),c.writeUInt16BE(_.blue,d+4),o&&c.writeUInt16BE(_.alpha,d+6));break;case Mt.COLORTYPE_ALPHA:case Mt.COLORTYPE_GRAYSCALE:{let b=(_.red+_.green+_.blue)/3;n.bitDepth===8?(c[d]=b,o&&(c[d+1]=_.alpha)):(c.writeUInt16BE(b,d),o&&c.writeUInt16BE(_.alpha,d+2));break}default:throw new Error("unrecognised color Type "+n.colorType)}u+=a,d+=l}return c}});var Vf=Z((FR,Xf)=>{"use strict";var Kf=ul();function wb(t,e,s,n,o){for(let r=0;r<s;r++)n[o+r]=t[e+r]}function _b(t,e,s){let n=0,o=e+s;for(let r=e;r<o;r++)n+=Math.abs(t[r]);return n}function $b(t,e,s,n,o,r){for(let i=0;i<s;i++){let a=i>=r?t[e+i-r]:0,l=t[e+i]-a;n[o+i]=l}}function bb(t,e,s,n){let o=0;for(let r=0;r<s;r++){let i=r>=n?t[e+r-n]:0,a=t[e+r]-i;o+=Math.abs(a)}return o}function xb(t,e,s,n,o){for(let r=0;r<s;r++){let i=e>0?t[e+r-s]:0,a=t[e+r]-i;n[o+r]=a}}function kb(t,e,s){let n=0,o=e+s;for(let r=e;r<o;r++){let i=e>0?t[r-s]:0,a=t[r]-i;n+=Math.abs(a)}return n}function Sb(t,e,s,n,o,r){for(let i=0;i<s;i++){let a=i>=r?t[e+i-r]:0,l=e>0?t[e+i-s]:0,c=t[e+i]-(a+l>>1);n[o+i]=c}}function vb(t,e,s,n){let o=0;for(let r=0;r<s;r++){let i=r>=n?t[e+r-n]:0,a=e>0?t[e+r-s]:0,l=t[e+r]-(i+a>>1);o+=Math.abs(l)}return o}function Eb(t,e,s,n,o,r){for(let i=0;i<s;i++){let a=i>=r?t[e+i-r]:0,l=e>0?t[e+i-s]:0,c=e>0&&i>=r?t[e+i-(s+r)]:0,u=t[e+i]-Kf(a,l,c);n[o+i]=u}}function Tb(t,e,s,n){let o=0;for(let r=0;r<s;r++){let i=r>=n?t[e+r-n]:0,a=e>0?t[e+r-s]:0,l=e>0&&r>=n?t[e+r-(s+n)]:0,c=t[e+r]-Kf(i,a,l);o+=Math.abs(c)}return o}var Rb={0:wb,1:$b,2:xb,3:Sb,4:Eb},Cb={0:_b,1:bb,2:kb,3:vb,4:Tb};Xf.exports=function(t,e,s,n,o){let r;if(!("filterType"in n)||n.filterType===-1)r=[0,1,2,3,4];else if(typeof n.filterType=="number")r=[n.filterType];else throw new Error("unrecognised filter types");n.bitDepth===16&&(o*=2);let i=e*o,a=0,l=0,c=Buffer.alloc((i+1)*s),u=r[0];for(let d=0;d<s;d++){if(r.length>1){let f=1/0;for(let p=0;p<r.length;p++){let h=Cb[r[p]](t,l,i,o);h<f&&(u=r[p],f=h)}}c[a]=u,a++,Rb[u](t,l,i,c,a,o),a+=i,l+=i}return c}});var _l=Z((BR,Jf)=>{"use strict";var it=Ms(),Ab=hl(),Ob=zf(),Nb=Vf(),Mb=require("zlib"),En=Jf.exports=function(t){if(this._options=t,t.deflateChunkSize=t.deflateChunkSize||32*1024,t.deflateLevel=t.deflateLevel!=null?t.deflateLevel:9,t.deflateStrategy=t.deflateStrategy!=null?t.deflateStrategy:3,t.inputHasAlpha=t.inputHasAlpha!=null?t.inputHasAlpha:!0,t.deflateFactory=t.deflateFactory||Mb.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:it.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:it.COLORTYPE_COLOR_ALPHA,[it.COLORTYPE_GRAYSCALE,it.COLORTYPE_COLOR,it.COLORTYPE_COLOR_ALPHA,it.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([it.COLORTYPE_GRAYSCALE,it.COLORTYPE_COLOR,it.COLORTYPE_COLOR_ALPHA,it.COLORTYPE_ALPHA].indexOf(t.inputColorType)===-1)throw new Error("option input color type:"+t.inputColorType+" is not supported at present");if(t.bitDepth!==8&&t.bitDepth!==16)throw new Error("option bit depth:"+t.bitDepth+" is not supported at present")};En.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};En.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};En.prototype.filterData=function(t,e,s){let n=Ob(t,e,s,this._options),o=it.COLORTYPE_TO_BPP_MAP[this._options.colorType];return Nb(n,e,s,this._options,o)};En.prototype._packChunk=function(t,e){let s=e?e.length:0,n=Buffer.alloc(s+12);return n.writeUInt32BE(s,0),n.writeUInt32BE(t,4),e&&e.copy(n,8),n.writeInt32BE(Ab.crc32(n.slice(4,n.length-4)),n.length-4),n};En.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*it.GAMMA_DIVISION),0),this._packChunk(it.TYPE_gAMA,e)};En.prototype.packIHDR=function(t,e){let s=Buffer.alloc(13);return s.writeUInt32BE(t,0),s.writeUInt32BE(e,4),s[8]=this._options.bitDepth,s[9]=this._options.colorType,s[10]=0,s[11]=0,s[12]=0,this._packChunk(it.TYPE_IHDR,s)};En.prototype.packIDAT=function(t){return this._packChunk(it.TYPE_IDAT,t)};En.prototype.packIEND=function(){return this._packChunk(it.TYPE_IEND,null)}});var tp=Z((UR,ep)=>{"use strict";var Pb=require("util"),Zf=require("stream"),Lb=Ms(),Ib=_l(),Qf=ep.exports=function(t){Zf.call(this);let e=t||{};this._packer=new Ib(e),this._deflate=this._packer.createDeflate(),this.readable=!0};Pb.inherits(Qf,Zf);Qf.prototype.pack=function(t,e,s,n){this.emit("data",Buffer.from(Lb.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,s)),n&&this.emit("data",this._packer.packGAMA(n));let o=this._packer.filterData(t,e,s);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(r){this.emit("data",this._packer.packIDAT(r))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(o)}});var ap=Z((bo,ip)=>{"use strict";var np=require("assert").ok,Ps=require("zlib"),Db=require("util"),sp=require("buffer").kMaxLength;function Hn(t){if(!(this instanceof Hn))return new Hn(t);t&&t.chunkSize<Ps.Z_MIN_CHUNK&&(t.chunkSize=Ps.Z_MIN_CHUNK),Ps.Inflate.call(this,t),this._offset=this._offset===void 0?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,t&&t.maxLength!=null&&(this._maxLength=t.maxLength)}function jb(t){return new Hn(t)}function op(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}Hn.prototype._processChunk=function(t,e,s){if(typeof s=="function")return Ps.Inflate._processChunk.call(this,t,e,s);let n=this,o=t&&t.length,r=this._chunkSize-this._offset,i=this._maxLength,a=0,l=[],c=0,u;this.on("error",function(h){u=h});function d(h,g){if(n._hadError)return;let _=r-g;if(np(_>=0,"have should not go down"),_>0){let b=n._buffer.slice(n._offset,n._offset+_);if(n._offset+=_,b.length>i&&(b=b.slice(0,i)),l.push(b),c+=b.length,i-=b.length,i===0)return!1}return(g===0||n._offset>=n._chunkSize)&&(r=n._chunkSize,n._offset=0,n._buffer=Buffer.allocUnsafe(n._chunkSize)),g===0?(a+=o-h,o=h,!0):!1}np(this._handle,"zlib binding closed");let f;do f=this._handle.writeSync(e,t,a,o,this._buffer,this._offset,r),f=f||this._writeState;while(!this._hadError&&d(f[0],f[1]));if(this._hadError)throw u;if(c>=sp)throw op(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+sp.toString(16)+" bytes");let p=Buffer.concat(l,c);return op(this),p};Db.inherits(Hn,Ps.Inflate);function qb(t,e){if(typeof e=="string"&&(e=Buffer.from(e)),!(e instanceof Buffer))throw new TypeError("Not a string or buffer");let s=t._finishFlushFlag;return s==null&&(s=Ps.Z_FINISH),t._processChunk(e,s)}function rp(t,e){return qb(new Hn(e),t)}ip.exports=bo=rp;bo.Inflate=Hn;bo.createInflate=jb;bo.inflateSync=rp});var $l=Z((WR,cp)=>{"use strict";var lp=cp.exports=function(t){this._buffer=t,this._reads=[]};lp.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};lp.prototype.process=function(){for(;this._reads.length>0&&this._buffer.length;){let t=this._reads[0];if(this._buffer.length&&(this._buffer.length>=t.length||t.allowLess)){this._reads.shift();let e=this._buffer;this._buffer=e.slice(t.length),t.func.call(this,e.slice(0,t.length))}else break}if(this._reads.length>0)throw new Error("There are some read requests waitng on finished stream");if(this._buffer.length>0)throw new Error("unrecognised content at end of stream")}});var dp=Z(up=>{"use strict";var Fb=$l(),Bb=dl();up.process=function(t,e){let s=[],n=new Fb(t);return new Bb(e,{read:n.read.bind(n),write:function(r){s.push(r)},complete:function(){}}).start(),n.process(),Buffer.concat(s)}});var mp=Z((YR,hp)=>{"use strict";var fp=!0,pp=require("zlib"),Ub=ap();pp.deflateSync||(fp=!1);var Wb=$l(),Hb=dp(),Yb=ml(),Gb=gl(),zb=yl();hp.exports=function(t,e){if(!fp)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let s;function n(v){s=v}let o;function r(v){o=v}function i(v){o.transColor=v}function a(v){o.palette=v}function l(){o.alpha=!0}let c;function u(v){c=v}let d=[];function f(v){d.push(v)}let p=new Wb(t);if(new Yb(e,{read:p.read.bind(p),error:n,metadata:r,gamma:u,palette:a,transColor:i,inflateData:f,simpleTransparency:l}).start(),p.process(),s)throw s;let g=Buffer.concat(d);d.length=0;let _;if(o.interlace)_=pp.inflateSync(g);else{let T=((o.width*o.bpp*o.depth+7>>3)+1)*o.height;_=Ub(g,{chunkSize:T,maxLength:T})}if(g=null,!_||!_.length)throw new Error("bad png - invalid inflate data response");let b=Hb.process(_,o);g=null;let O=Gb.dataToBitMap(b,o);b=null;let M=zb(O,o,e.skipRescale);return o.data=M,o.gamma=c||0,o}});var _p=Z((GR,wp)=>{"use strict";var gp=!0,yp=require("zlib");yp.deflateSync||(gp=!1);var Kb=Ms(),Xb=_l();wp.exports=function(t,e){if(!gp)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let s=e||{},n=new Xb(s),o=[];o.push(Buffer.from(Kb.PNG_SIGNATURE)),o.push(n.packIHDR(t.width,t.height)),t.gamma&&o.push(n.packGAMA(t.gamma));let r=n.filterData(t.data,t.width,t.height),i=yp.deflateSync(r,n.getDeflateOptions());if(r=null,!i||!i.length)throw new Error("bad png - invalid compressed data response");return o.push(n.packIDAT(i)),o.push(n.packIEND()),Buffer.concat(o)}});var $p=Z(bl=>{"use strict";var Vb=mp(),Jb=_p();bl.read=function(t,e){return Vb(t,e||{})};bl.write=function(t,e){return Jb(t,e)}});var kp=Z(xp=>{"use strict";var Zb=require("util"),bp=require("stream"),Qb=Yf(),ex=tp(),tx=$p(),dt=xp.PNG=function(t){bp.call(this),t=t||{},this.width=t.width|0,this.height=t.height|0,this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null,t.fill&&this.data&&this.data.fill(0),this.gamma=0,this.readable=this.writable=!0,this._parser=new Qb(t),this._parser.on("error",this.emit.bind(this,"error")),this._parser.on("close",this._handleClose.bind(this)),this._parser.on("metadata",this._metadata.bind(this)),this._parser.on("gamma",this._gamma.bind(this)),this._parser.on("parsed",function(e){this.data=e,this.emit("parsed",e)}.bind(this)),this._packer=new ex(t),this._packer.on("data",this.emit.bind(this,"data")),this._packer.on("end",this.emit.bind(this,"end")),this._parser.on("close",this._handleClose.bind(this)),this._packer.on("error",this.emit.bind(this,"error"))};Zb.inherits(dt,bp);dt.sync=tx;dt.prototype.pack=function(){return!this.data||!this.data.length?(this.emit("error","No data provided"),this):(process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this)),this)};dt.prototype.parse=function(t,e){if(e){let s,n;s=function(o){this.removeListener("error",n),this.data=o,e(null,this)}.bind(this),n=function(o){this.removeListener("parsed",s),e(o,null)}.bind(this),this.once("parsed",s),this.once("error",n)}return this.end(t),this};dt.prototype.write=function(t){return this._parser.write(t),!0};dt.prototype.end=function(t){this._parser.end(t)};dt.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};dt.prototype._gamma=function(t){this.gamma=t};dt.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};dt.bitblt=function(t,e,s,n,o,r,i,a){if(s|=0,n|=0,o|=0,r|=0,i|=0,a|=0,s>t.width||n>t.height||s+o>t.width||n+r>t.height)throw new Error("bitblt reading outside image");if(i>e.width||a>e.height||i+o>e.width||a+r>e.height)throw new Error("bitblt writing outside image");for(let l=0;l<r;l++)t.data.copy(e.data,(a+l)*e.width+i<<2,(n+l)*t.width+s<<2,(n+l)*t.width+s+o<<2)};dt.prototype.bitblt=function(t,e,s,n,o,r,i){return dt.bitblt(this,t,e,s,n,o,r,i),this};dt.adjustGamma=function(t){if(t.gamma){for(let e=0;e<t.height;e++)for(let s=0;s<t.width;s++){let n=t.width*e+s<<2;for(let o=0;o<3;o++){let r=t.data[n+o]/255;r=Math.pow(r,1/2.2/t.gamma),t.data[n+o]=Math.round(r*255)}}t.gamma=0}};dt.prototype.adjustGamma=function(){dt.adjustGamma(this)}});var Rp={};zy(Rp,{default:()=>Ep});function Ep(t,e,s,n,o,r={}){let{threshold:i=.1,alpha:a=.1,aaColor:l=[255,255,0],diffColor:c=[255,0,0],includeAA:u,diffColorAlt:d,diffMask:f}=r;if(!xl(t)||!xl(e)||s&&!xl(s))throw new Error("Image data: Uint8Array, Uint8ClampedArray or Buffer expected.");if(t.length!==e.length||s&&s.length!==t.length)throw new Error("Image sizes do not match.");if(t.length!==n*o*4)throw new Error("Image data size does not match width/height.");let p=n*o,h=new Uint32Array(t.buffer,t.byteOffset,p),g=new Uint32Array(e.buffer,e.byteOffset,p),_=!0;for(let k=0;k<p;k++)if(h[k]!==g[k]){_=!1;break}if(_){if(s&&!f)for(let k=0;k<p;k++)vp(t,4*k,a,s);return 0}let b=35215*i*i,[O,M,v]=l,[T,N,te]=c,[K,ie,le]=d||c,ne=0;for(let k=0;k<o;k++)for(let ve=0;ve<n;ve++){let H=k*n+ve,X=H*4,pe=h[H]===g[H]?0:Tp(t,e,X,X,!1);if(Math.abs(pe)>b){let Re=Sp(t,ve,k,n,o,h,g)||Sp(e,ve,k,n,o,g,h);!u&&Re?s&&!f&&ni(s,X,O,M,v):(s&&(pe<0?ni(s,X,K,ie,le):ni(s,X,T,N,te)),ne++)}else s&&!f&&vp(t,X,a,s)}return ne}function xl(t){return ArrayBuffer.isView(t)&&t.BYTES_PER_ELEMENT===1}function Sp(t,e,s,n,o,r,i){let a=Math.max(e-1,0),l=Math.max(s-1,0),c=Math.min(e+1,n-1),u=Math.min(s+1,o-1),d=s*n+e,f=e===a||e===c||s===l||s===u?1:0,p=0,h=0,g=0,_=0,b=0,O=0;for(let M=a;M<=c;M++)for(let v=l;v<=u;v++){if(M===e&&v===s)continue;let T=Tp(t,t,d*4,(v*n+M)*4,!0);if(T===0){if(f++,f>2)return!1}else T<p?(p=T,g=M,_=v):T>h&&(h=T,b=M,O=v)}return p===0||h===0?!1:ti(r,g,_,n,o)&&ti(i,g,_,n,o)||ti(r,b,O,n,o)&&ti(i,b,O,n,o)}function ti(t,e,s,n,o){let r=Math.max(e-1,0),i=Math.max(s-1,0),a=Math.min(e+1,n-1),l=Math.min(s+1,o-1),c=t[s*n+e],u=e===r||e===a||s===i||s===l?1:0;for(let d=r;d<=a;d++)for(let f=i;f<=l;f++)if(!(d===e&&f===s)&&(u+=+(c===t[f*n+d]),u>2))return!0;return!1}function Tp(t,e,s,n,o){let r=t[s],i=t[s+1],a=t[s+2],l=t[s+3],c=e[n],u=e[n+1],d=e[n+2],f=e[n+3],p=r-c,h=i-u,g=a-d,_=l-f;if(!p&&!h&&!g&&!_)return 0;if(l<255||f<255){let T=48+159*(s%2),N=48+159*((s/1.618033988749895|0)%2),te=48+159*((s/2.618033988749895|0)%2);p=(r*l-c*f-T*_)/255,h=(i*l-u*f-N*_)/255,g=(a*l-d*f-te*_)/255}let b=p*.29889531+h*.58662247+g*.11448223;if(o)return b;let O=p*.59597799-h*.2741761-g*.32180189,M=p*.21147017-h*.52261711+g*.31114694,v=.5053*b*b+.299*O*O+.1957*M*M;return b>0?-v:v}function ni(t,e,s,n,o){t[e+0]=s,t[e+1]=n,t[e+2]=o,t[e+3]=255}function vp(t,e,s,n){let o=255+(t[e]*.29889531+t[e+1]*.58662247+t[e+2]*.11448223-255)*s*t[e+3]/255;ni(n,e,o,o,o)}var Cp=Gy(()=>{});var Yn=Z((XR,Pp)=>{var fn=require("fs"),nx=require("path"),sx=require("os"),ox="nex-visual-";function Op(t){return nx.join(sx.tmpdir(),`${ox}${Date.now()}-${t}`)}var kl=null;function si(){return kl||(kl=kp().PNG),kl}var Sl=null;function rx(){if(!Sl){let t=(Cp(),Xy(Rp));Sl=t.default||t}return Sl}function Tl(t,e,{threshold:s=.1}={}){let n=si(),o=rx(),r=n.sync.read(fn.readFileSync(t)),i=n.sync.read(fn.readFileSync(e)),a=Math.max(r.width,i.width),l=Math.max(r.height,i.height),c=Ap(r,a,l),u=Ap(i,a,l),d=new n({width:a,height:l}),f=o(c,u,d.data,a,l,{threshold:s,includeAA:!1}),p=a*l,h=(f/p*100).toFixed(1),g=ix(d.data,a,l,3,3),_=Op("diff.png");return fn.writeFileSync(_,n.sync.write(d),{mode:384}),{diffPath:_,diffPercent:parseFloat(h),totalPixels:p,changedPixels:f,regionSummary:g,beforePath:t,afterPath:e,width:a,height:l}}function Ap(t,e,s){if(t.width===e&&t.height===s)return t.data;let n=Buffer.alloc(e*s*4,0);for(let o=0;o<t.height;o++){let r=o*t.width*4,i=o*e*4;t.data.copy(n,i,r,r+t.width*4)}return n}function ix(t,e,s,n,o){let r=[["top-left","top-center","top-right"],["middle-left","center","middle-right"],["bottom-left","bottom-center","bottom-right"]],i=Math.ceil(e/n),a=Math.ceil(s/o),l=[];for(let c=0;c<o;c++)for(let u=0;u<n;u++){let d=0,f=0,p=u*i,h=c*a,g=Math.min(p+i,e),_=Math.min(h+a,s);for(let b=h;b<_;b++)for(let O=p;O<g;O++){f++;let M=(b*e+O)*4;(t[M]>0||t[M+1]>0)&&d++}if(d>0){let b=(d/f*100).toFixed(1),O=r[c]&&r[c][u]?r[c][u]:`row${c}-col${u}`;l.push({name:O,changedPercent:parseFloat(b),changed:d,total:f})}}return l.sort((c,u)=>u.changedPercent-c.changedPercent),l}var Np=[{width:320,label:"mobile-sm"},{width:768,label:"tablet"},{width:1024,label:"desktop-sm"},{width:1440,label:"desktop"},{width:1920,label:"desktop-lg"}];async function ax(t,{viewports:e=Np,height:s=800,fullPage:n=!1,timeout:o=3e4}={}){let{browserScreenshot:r}=dn(),i=[];for(let a of e){let l=await r(t,{width:a.width,height:s,fullPage:n,timeout:o});i.push({label:a.label,width:a.width,path:l.path,base64:l.base64,media_type:l.media_type})}return i}function Mp(t,e=[]){let s=si(),n=s.sync.read(fn.readFileSync(t));for(let i of e){let a=lx(i.color||"#FF0000");i.type==="box"?(cx(n,i.x||0,i.y||0,i.width||50,i.height||50,a,i.thickness||3),i.label&&El(n,i.x||0,(i.y||0)-14,i.label,a)):i.type==="arrow"?(ux(n,i.x||0,i.y||0,i.toX||i.x+50,i.toY||i.y,a,i.thickness||3),i.label&&El(n,i.x||0,(i.y||0)-14,i.label,a)):i.type==="circle"&&(dx(n,i.x||0,i.y||0,i.radius||20,a,i.thickness||3),i.label&&El(n,(i.x||0)-(i.radius||20),(i.y||0)-(i.radius||20)-14,i.label,a))}let o=Op("annotated.png");fn.writeFileSync(o,s.sync.write(n),{mode:384});let r=fn.readFileSync(o).toString("base64");return{path:o,base64:r,media_type:"image/png"}}function lx(t){let e=t.replace("#","");return{r:parseInt(e.substring(0,2),16),g:parseInt(e.substring(2,4),16),b:parseInt(e.substring(4,6),16),a:255}}function Qt(t,e,s,n){if(e<0||s<0||e>=t.width||s>=t.height)return;let o=(s*t.width+e)*4;t.data[o]=n.r,t.data[o+1]=n.g,t.data[o+2]=n.b,t.data[o+3]=n.a}function cx(t,e,s,n,o,r,i=3){for(let a=0;a<i;a++){for(let l=0;l<n;l++)Qt(t,e+l,s+a,r),Qt(t,e+l,s+o-1-a,r);for(let l=0;l<o;l++)Qt(t,e+a,s+l,r),Qt(t,e+n-1-a,s+l,r)}}function vl(t,e,s,n,o,r,i=3){let a=Math.abs(n-e),l=Math.abs(o-s),c=e<n?1:-1,u=s<o?1:-1,d=a-l,f=e,p=s;for(;;){let h=Math.floor(i/2);for(let _=-h;_<=h;_++)for(let b=-h;b<=h;b++)Qt(t,f+_,p+b,r);if(f===n&&p===o)break;let g=2*d;g>-l&&(d-=l,f+=c),g<a&&(d+=a,p+=u)}}function ux(t,e,s,n,o,r,i=3){vl(t,e,s,n,o,r,i);let a=Math.atan2(o-s,n-e),l=15,c=a+Math.PI*.8,u=a-Math.PI*.8;vl(t,n,o,Math.round(n+l*Math.cos(c)),Math.round(o+l*Math.sin(c)),r,i),vl(t,n,o,Math.round(n+l*Math.cos(u)),Math.round(o+l*Math.sin(u)),r,i)}function dx(t,e,s,n,o,r=3){for(let i=0;i<r;i++){let a=n-i;for(let l=0;l<360;l+=.5){let c=l*Math.PI/180,u=Math.round(e+a*Math.cos(c)),d=Math.round(s+a*Math.sin(c));Qt(t,u,d,o)}}}function El(t,e,s,n,o){let i=n.length*6+4,a=12;for(let l=0;l<a;l++)for(let c=0;c<i;c++)Qt(t,e+c,s+l,{r:0,g:0,b:0,a:200});for(let l=0;l<i;l++)Qt(t,e+l,s+a-1,o),Qt(t,e+l,s+a-2,o);for(let l=0;l<n.length;l++){let c=e+2+l*6;for(let u=2;u<9;u++)for(let d=0;d<4;d++)Qt(t,c+d,s+u,o)}}async function*fx(t,e,{maxIterations:s=20,hmrDelay:n=1500,width:o=1280,height:r=800,timeout:i=3e4}={}){let{browserScreenshot:a}=dn(),l=px("chokidar"),c=await a(t,{width:o,height:r,timeout:i});if(yield{iteration:0,type:"baseline",path:c.path,base64:c.base64,media_type:c.media_type},!l){yield{iteration:-1,type:"error",message:"chokidar not installed \u2014 watch mode requires it. Install with: npm install chokidar"};return}let u=0,d=!1,f=l.watch(e,{ignoreInitial:!0,ignored:/(node_modules|\.git|dist)/});f.on("change",()=>{d=!0});try{for(;u<s;){await mx(()=>d,3e5),d=!1,u++,await hx(n);let p=await a(t,{width:o,height:r,timeout:i}),h=null;try{h=Tl(c.path,p.path)}catch{}c=p,yield{iteration:u,type:"change",path:p.path,base64:p.base64,media_type:p.media_type,diff:h?{diffPath:h.diffPath,diffPercent:h.diffPercent,changedPixels:h.changedPixels,regions:h.regionSummary}:null}}}finally{await f.close()}}function px(t){try{return require(t)}catch{return null}}function hx(t){return new Promise(e=>setTimeout(e,t))}function mx(t,e=6e4){return new Promise((s,n)=>{let o=setInterval(()=>{t()&&(clearInterval(o),clearTimeout(r),s())},200),r=setTimeout(()=>{clearInterval(o),n(new Error("Watch timeout \u2014 no file changes detected"))},e)})}function gx(t,{sampleRate:e=4}={}){let n=si().sync.read(fn.readFileSync(t)),o=new Map;for(let c=0;c<n.height;c+=e)for(let u=0;u<n.width;u+=e){let d=(c*n.width+u)*4,f=n.data[d],p=n.data[d+1],h=n.data[d+2];if(n.data[d+3]<128)continue;let _=Math.round(f/8)*8,b=Math.round(p/8)*8,O=Math.round(h/8)*8,M=`${_},${b},${O}`;o.set(M,(o.get(M)||0)+1)}let r=[...o.entries()].sort((c,u)=>u[1]-c[1]).slice(0,20),i=r.reduce((c,u)=>c+u[1],0),a=r.map(([c,u])=>{let[d,f,p]=c.split(",").map(Number);return{hex:yx(d,f,p),rgb:`rgb(${d}, ${f}, ${p})`,frequency:parseFloat((u/i*100).toFixed(1)),category:wx(d,f,p)}}),l=_x(n);return{colors:a,spacing:l,dimensions:{width:n.width,height:n.height},imagePath:t}}function yx(t,e,s){return"#"+[t,e,s].map(n=>Math.min(255,n).toString(16).padStart(2,"0")).join("")}function wx(t,e,s){let n=(t*299+e*587+s*114)/1e3;return n>240?"white/background":n<30?"black/text":n<80?"dark":t>200&&e<100&&s<100?"red/danger":t<100&&e>150&&s<100?"green/success":t<100&&e<100&&s>200?"blue/primary":t>200&&e>200&&s<100?"yellow/warning":t>200&&e>100&&s<50?"orange/accent":n>200?"light/subtle":"midtone"}function _x(t){let e=[],s=!1,n=0,o=$x(t);for(let i=0;i<t.height;i++){let a=!0;for(let l=0;l<t.width;l+=4){let c=(i*t.width+l)*4;if(Math.abs(t.data[c]-o.r)>20||Math.abs(t.data[c+1]-o.g)>20||Math.abs(t.data[c+2]-o.b)>20){a=!1;break}}if(a&&s)s=!1,n=i;else if(!a&&!s&&(s=!0,n>0)){let l=i-n;l>=4&&l<=200&&e.push(l)}}let r=new Map;for(let i of e){let a=Math.round(i/4)*4;r.set(a,(r.get(a)||0)+1)}return[...r.entries()].sort((i,a)=>a[1]-i[1]).slice(0,8).map(([i,a])=>({px:i,occurrences:a}))}function $x(t){let e=[[0,0],[t.width-1,0],[0,t.height-1],[t.width-1,t.height-1]],s=0,n=0,o=0;for(let[r,i]of e){let a=(i*t.width+r)*4;s+=t.data[a],n+=t.data[a+1],o+=t.data[a+2]}return{r:Math.round(s/4),g:Math.round(n/4),b:Math.round(o/4)}}async function bx(t,e,{width:s,height:n=800,fullPage:o=!1,threshold:r=.1,timeout:i=3e4}={}){let{browserScreenshot:a}=dn(),c=si().sync.read(fn.readFileSync(e)),u=s||c.width,d=n||c.height,f=await a(t,{width:u,height:d,fullPage:o,timeout:i}),p=Tl(e,f.path,{threshold:r}),h=Mp(f.path,p.regionSummary.filter(g=>g.changedPercent>1).map((g,_)=>{let M=Math.ceil(p.width/3),v=Math.ceil(p.height/3),T=[["top-left","top-center","top-right"],["middle-left","center","middle-right"],["bottom-left","bottom-center","bottom-right"]],N=0,te=0;for(let K=0;K<3;K++)for(let ie=0;ie<3;ie++)T[K][ie]===g.name&&(N=ie,te=K);return{type:"box",x:N*M+2,y:te*v+2,width:M-4,height:v-4,label:`${g.name}: ${g.changedPercent}%`,color:g.changedPercent>10?"#FF0000":"#FFAA00"}}));return{livePath:f.path,referencePath:e,diffPath:p.diffPath,annotatedPath:h.path,diffPercent:p.diffPercent,changedPixels:p.changedPixels,totalPixels:p.totalPixels,regions:p.regionSummary,liveBase64:f.base64,diffBase64:fn.readFileSync(p.diffPath).toString("base64"),annotatedBase64:h.base64}}Pp.exports={pixelDiff:Tl,responsiveSweep:ax,annotateImage:Mp,visualWatch:fx,extractDesignTokens:gx,designCompare:bx,DEFAULT_VIEWPORTS:Np}});var Rl=Z((VR,Lp)=>{var{C:Pe}=Ke(),ko="",ft=[],xo=0,Gn=null;function xx(t){Gn=t}function kx(t,e){ko=t,ft=[],xo=0;for(let n of e){xo++;let o=`t${xo}`;ft.push({id:o,description:n.description||n.title||n.name||n.task||`Task ${xo}`,status:"pending",dependsOn:n.depends_on||[],result:null})}let s=ft.map(n=>({...n}));return Gn&&Gn("create",{name:t,tasks:s}),s}function Sx(t,e,s){let n=ft.find(o=>o.id===t);return n?(n.status=e,s!==void 0&&(n.result=s),Gn&&Gn("update",{id:t,status:e,result:s}),{...n}):null}function vx(){return{name:ko,tasks:ft.map(t=>({...t}))}}function Ex(){ko="",ft=[],xo=0,Gn&&Gn("clear",{})}function Tx(){return ft.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let s=ft.find(n=>n.id===e);return s&&s.status==="done"}))}function Rx(){if(ft.length===0)return`${Pe.dim}No active tasks${Pe.reset}`;let t=[];ko&&(t.push(` ${Pe.bold}${Pe.cyan}Tasks: ${ko}${Pe.reset}`),t.push(` ${Pe.dim}${"\u2500".repeat(40)}${Pe.reset}`));for(let o of ft){let r,i;switch(o.status){case"done":r="\u2713",i=Pe.green;break;case"in_progress":r="\u2192",i=Pe.cyan;break;case"failed":r="\u2717",i=Pe.red;break;default:r="\xB7",i=Pe.dim}let a=o.dependsOn.length>0?` ${Pe.dim}(after: ${o.dependsOn.join(", ")})${Pe.reset}`:"",l=`[${o.status}]`,c=o.description.length>50?o.description.substring(0,47)+"...":o.description;if(t.push(` ${i}${r}${Pe.reset} ${Pe.bold}${o.id}${Pe.reset} ${c.padEnd(40)} ${i}${l}${Pe.reset}${a}`),o.result&&o.status==="done"){let u=o.result.length>60?o.result.substring(0,57)+"...":o.result;t.push(` ${Pe.dim}\u2192 ${u}${Pe.reset}`)}}let e=ft.filter(o=>o.status==="done").length,s=ft.filter(o=>o.status==="failed").length,n=ft.length;return t.push(` ${Pe.dim}${"\u2500".repeat(40)}${Pe.reset}`),t.push(` ${Pe.dim}${e}/${n} done${s>0?`, ${s} failed`:""}${Pe.reset}`),t.join(`
133
- `)}function Cx(){return ft.length>0&&ft.some(t=>t.status==="pending"||t.status==="in_progress")}Lp.exports={createTasks:kx,updateTask:Sx,getTaskList:vx,clearTasks:Ex,getReadyTasks:Tx,renderTaskList:Rx,setOnChange:xx,hasActiveTasks:Cx}});var oi=Z((JR,Dp)=>{var So={"devstral-2":{staleWarn:3e4,staleAbort:9e4,investigationCap:18,postEditCap:10,briefing:`You are devstral-2, a strong coding model optimized for agentic tasks.
131
+ Then restart nex-code.`;function Df(){if(So!==null)return So;try{require("playwright"),So=!0}catch{So=!1}return So}async function oi(){if(!Df())throw new Error(If);return fl||(fl=require("playwright")),(!un||!un.isConnected())&&(un=await fl.chromium.launch({headless:!0})),un}async function nb(){if(un){try{await un.close()}catch(t){console.error("closeBrowser failed:",t.message)}un=null}}process.on("exit",()=>{if(un)try{un.close()}catch(t){console.error("Error closing browser on exit:",t.message)}});async function sb(t,{timeout:e=3e4,waitFor:s="domcontentloaded"}={}){let o=await(await oi()).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(c=>c.remove()),document.body?.innerText||"")),a=await o.evaluate(()=>Array.from(document.querySelectorAll("a[href]")).slice(0,30).map(l=>({text:(l.innerText||l.textContent||"").trim().substring(0,80),href:l.href})).filter(l=>l.text&&l.href&&!l.href.startsWith("javascript:")));return{title:r,url:o.url(),text:i.substring(0,8e3)+(i.length>8e3?`
132
+ ...(truncated)`:""),links:a.slice(0,20)}}finally{await o.close()}}async function ob(t,{width:e=1280,height:s=800,fullPage:n=!1,timeout:o=3e4}={}){let i=await(await oi()).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}),l=require("os"),c=require("path"),u=require("fs"),d=c.join(l.tmpdir(),`nex-screenshot-${Date.now()}.png`);return u.writeFileSync(d,a,{mode:384}),{path:d,base64:a.toString("base64"),media_type:"image/png",title:await i.title(),url:i.url()}}finally{await i.close()}}async function rb(t,{selector:e,text:s,timeout:n=3e4}={}){if(!e&&!s)throw new Error("selector or text is required");let r=await(await oi()).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 ib(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 oi()).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()}}jf.exports={isPlaywrightAvailable:Df,browserNavigate:sb,browserScreenshot:ob,browserClick:rb,browserFill:ib,closeBrowser:nb,INSTALL_MSG:If}});var pl=Q((zR,Ff)=>{"use strict";var ab=require("util"),qf=require("stream"),Ut=Ff.exports=function(){qf.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};ab.inherits(Ut,qf);Ut.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e}),process.nextTick(function(){this._process(),this._paused&&this._reads&&this._reads.length>0&&(this._paused=!1,this.emit("drain"))}.bind(this))};Ut.prototype.write=function(t,e){if(!this.writable)return this.emit("error",new Error("Stream not writable")),!1;let s;return Buffer.isBuffer(t)?s=t:s=Buffer.from(t,e||this._encoding),this._buffers.push(s),this._buffered+=s.length,this._process(),this._reads&&this._reads.length===0&&(this._paused=!0),this.writable&&!this._paused};Ut.prototype.end=function(t,e){t&&this.write(t,e),this.writable=!1,this._buffers&&(this._buffers.length===0?this._end():(this._buffers.push(null),this._process()))};Ut.prototype.destroySoon=Ut.prototype.end;Ut.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};Ut.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};Ut.prototype._processReadAllowingLess=function(t){this._reads.shift();let e=this._buffers[0];e.length>t.length?(this._buffered-=t.length,this._buffers[0]=e.slice(t.length),t.func.call(this,e.slice(0,t.length))):(this._buffered-=e.length,this._buffers.shift(),t.func.call(this,e))};Ut.prototype._processRead=function(t){this._reads.shift();let e=0,s=0,n=Buffer.alloc(t.length);for(;e<t.length;){let o=this._buffers[s++],r=Math.min(o.length,t.length-e);o.copy(n,e,0,r),e+=r,r!==o.length&&(this._buffers[--s]=o.slice(r))}s>0&&this._buffers.splice(0,s),this._buffered-=t.length,t.func.call(this,n)};Ut.prototype._process=function(){try{for(;this._buffered>0&&this._reads&&this._reads.length>0;){let t=this._reads[0];if(t.allowLess)this._processReadAllowingLess(t);else if(this._buffered>=t.length)this._processRead(t);else break}this._buffers&&!this.writable&&this._end()}catch(t){this.emit("error",t)}}});var ml=Q(hl=>{"use strict";var Sn=[{x:[0],y:[0]},{x:[4],y:[0]},{x:[0,4],y:[4]},{x:[2,6],y:[0,4]},{x:[0,2,4,6],y:[2,6]},{x:[1,3,5,7],y:[0,2,4,6]},{x:[0,1,2,3,4,5,6,7],y:[1,3,5,7]}];hl.getImagePasses=function(t,e){let s=[],n=t%8,o=e%8,r=(t-n)/8,i=(e-o)/8;for(let a=0;a<Sn.length;a++){let l=Sn[a],c=r*l.x.length,u=i*l.y.length;for(let d=0;d<l.x.length&&l.x[d]<n;d++)c++;for(let d=0;d<l.y.length&&l.y[d]<o;d++)u++;c>0&&u>0&&s.push({width:c,height:u,index:a})}return s};hl.getInterlaceIterator=function(t){return function(e,s,n){let o=e%Sn[n].x.length,r=(e-o)/Sn[n].x.length*8+Sn[n].x[o],i=s%Sn[n].y.length,a=(s-i)/Sn[n].y.length*8+Sn[n].y[i];return r*4+a*t*4}}});var gl=Q((XR,Bf)=>{"use strict";Bf.exports=function(e,s,n){let o=e+s-n,r=Math.abs(o-e),i=Math.abs(o-s),a=Math.abs(o-n);return r<=i&&r<=a?e:i<=a?s:n}});var yl=Q((VR,Wf)=>{"use strict";var lb=ml(),cb=gl();function Uf(t,e,s){let n=t*e;return s!==8&&(n=Math.ceil(n/(8/s))),n}var Ps=Wf.exports=function(t,e){let s=t.width,n=t.height,o=t.interlace,r=t.bpp,i=t.depth;if(this.read=e.read,this.write=e.write,this.complete=e.complete,this._imageIndex=0,this._images=[],o){let a=lb.getImagePasses(s,n);for(let l=0;l<a.length;l++)this._images.push({byteWidth:Uf(a[l].width,r,i),height:a[l].height,lineIndex:0})}else this._images.push({byteWidth:Uf(s,r,i),height:n,lineIndex:0});i===8?this._xComparison=r:i===16?this._xComparison=r*2:this._xComparison=1};Ps.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};Ps.prototype._unFilterType1=function(t,e,s){let n=this._xComparison,o=n-1;for(let r=0;r<s;r++){let i=t[1+r],a=r>o?e[r-n]:0;e[r]=i+a}};Ps.prototype._unFilterType2=function(t,e,s){let n=this._lastLine;for(let o=0;o<s;o++){let r=t[1+o],i=n?n[o]:0;e[o]=r+i}};Ps.prototype._unFilterType3=function(t,e,s){let n=this._xComparison,o=n-1,r=this._lastLine;for(let i=0;i<s;i++){let a=t[1+i],l=r?r[i]:0,c=i>o?e[i-n]:0,u=Math.floor((c+l)/2);e[i]=a+u}};Ps.prototype._unFilterType4=function(t,e,s){let n=this._xComparison,o=n-1,r=this._lastLine;for(let i=0;i<s;i++){let a=t[1+i],l=r?r[i]:0,c=i>o?e[i-n]:0,u=i>o&&r?r[i-n]:0,d=cb(c,l,u);e[i]=a+d}};Ps.prototype._reverseFilterLine=function(t){let e=t[0],s,n=this._images[this._imageIndex],o=n.byteWidth;if(e===0)s=t.slice(1,o+1);else switch(s=Buffer.alloc(o),e){case 1:this._unFilterType1(t,s,o);break;case 2:this._unFilterType2(t,s,o);break;case 3:this._unFilterType3(t,s,o);break;case 4:this._unFilterType4(t,s,o);break;default:throw new Error("Unrecognised filter type - "+e)}this.write(s),n.lineIndex++,n.lineIndex>=n.height?(this._lastLine=null,this._imageIndex++,n=this._images[this._imageIndex]):this._lastLine=s,n?this.read(n.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}});var Gf=Q((JR,Yf)=>{"use strict";var ub=require("util"),Hf=pl(),db=yl(),fb=Yf.exports=function(t){Hf.call(this);let e=[],s=this;this._filter=new db(t,{read:this.read.bind(this),write:function(n){e.push(n)},complete:function(){s.emit("complete",Buffer.concat(e))}}),this._filter.start()};ub.inherits(fb,Hf)});var Ls=Q((ZR,zf)=>{"use strict";zf.exports={PNG_SIGNATURE:[137,80,78,71,13,10,26,10],TYPE_IHDR:1229472850,TYPE_IEND:1229278788,TYPE_IDAT:1229209940,TYPE_PLTE:1347179589,TYPE_tRNS:1951551059,TYPE_gAMA:1732332865,COLORTYPE_GRAYSCALE:0,COLORTYPE_PALETTE:1,COLORTYPE_COLOR:2,COLORTYPE_ALPHA:4,COLORTYPE_PALETTE_COLOR:3,COLORTYPE_COLOR_ALPHA:6,COLORTYPE_TO_BPP_MAP:{0:1,2:3,3:1,4:2,6:4},GAMMA_DIVISION:1e5}});var $l=Q((QR,Kf)=>{"use strict";var wl=[];(function(){for(let t=0;t<256;t++){let e=t;for(let s=0;s<8;s++)e&1?e=3988292384^e>>>1:e=e>>>1;wl[t]=e}})();var _l=Kf.exports=function(){this._crc=-1};_l.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=wl[(this._crc^t[e])&255]^this._crc>>>8;return!0};_l.prototype.crc32=function(){return this._crc^-1};_l.crc32=function(t){let e=-1;for(let s=0;s<t.length;s++)e=wl[(e^t[s])&255]^e>>>8;return e^-1}});var bl=Q((e1,Xf)=>{"use strict";var Ye=Ls(),pb=$l(),Xe=Xf.exports=function(t,e){this._options=t,t.checkCRC=t.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[Ye.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[Ye.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[Ye.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[Ye.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[Ye.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[Ye.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=e.read,this.error=e.error,this.metadata=e.metadata,this.gamma=e.gamma,this.transColor=e.transColor,this.palette=e.palette,this.parsed=e.parsed,this.inflateData=e.inflateData,this.finished=e.finished,this.simpleTransparency=e.simpleTransparency,this.headersFinished=e.headersFinished||function(){}};Xe.prototype.start=function(){this.read(Ye.PNG_SIGNATURE.length,this._parseSignature.bind(this))};Xe.prototype._parseSignature=function(t){let e=Ye.PNG_SIGNATURE;for(let s=0;s<e.length;s++)if(t[s]!==e[s]){this.error(new Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};Xe.prototype._parseChunkBegin=function(t){let e=t.readUInt32BE(0),s=t.readUInt32BE(4),n="";for(let r=4;r<8;r++)n+=String.fromCharCode(t[r]);let o=!!(t[4]&32);if(!this._hasIHDR&&s!==Ye.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new pb,this._crc.write(Buffer.from(n)),this._chunks[s])return this._chunks[s](e);if(!o){this.error(new Error("Unsupported critical chunk type "+n));return}this.read(e+4,this._skipChunk.bind(this))};Xe.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};Xe.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};Xe.prototype._parseChunkEnd=function(t){let e=t.readInt32BE(0),s=this._crc.crc32();if(this._options.checkCRC&&s!==e){this.error(new Error("Crc error - "+e+" - "+s));return}this._hasIEND||this.read(8,this._parseChunkBegin.bind(this))};Xe.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};Xe.prototype._parseIHDR=function(t){this._crc.write(t);let e=t.readUInt32BE(0),s=t.readUInt32BE(4),n=t[8],o=t[9],r=t[10],i=t[11],a=t[12];if(n!==8&&n!==4&&n!==2&&n!==1&&n!==16){this.error(new Error("Unsupported bit depth "+n));return}if(!(o in Ye.COLORTYPE_TO_BPP_MAP)){this.error(new Error("Unsupported color type"));return}if(r!==0){this.error(new Error("Unsupported compression method"));return}if(i!==0){this.error(new Error("Unsupported filter method"));return}if(a!==0&&a!==1){this.error(new Error("Unsupported interlace method"));return}this._colorType=o;let l=Ye.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:s,depth:n,interlace:!!a,palette:!!(o&Ye.COLORTYPE_PALETTE),color:!!(o&Ye.COLORTYPE_COLOR),alpha:!!(o&Ye.COLORTYPE_ALPHA),bpp:l,colorType:o}),this._handleChunkEnd()};Xe.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};Xe.prototype._parsePLTE=function(t){this._crc.write(t);let e=Math.floor(t.length/3);for(let s=0;s<e;s++)this._palette.push([t[s*3],t[s*3+1],t[s*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};Xe.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};Xe.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===Ye.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(new Error("Transparency chunk must be after palette"));return}if(t.length>this._palette.length){this.error(new Error("More transparent colors than palette size"));return}for(let e=0;e<t.length;e++)this._palette[e][3]=t[e];this.palette(this._palette)}this._colorType===Ye.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===Ye.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};Xe.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};Xe.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/Ye.GAMMA_DIVISION),this._handleChunkEnd()};Xe.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};Xe.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===Ye.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw new Error("Expected palette not found");this.inflateData(e);let s=t-e.length;s>0?this._handleIDAT(s):this._handleChunkEnd()};Xe.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};Xe.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var xl=Q(Jf=>{"use strict";var Vf=ml(),hb=[function(){},function(t,e,s,n){if(n===e.length)throw new Error("Ran out of data");let o=e[n];t[s]=o,t[s+1]=o,t[s+2]=o,t[s+3]=255},function(t,e,s,n){if(n+1>=e.length)throw new Error("Ran out of data");let o=e[n];t[s]=o,t[s+1]=o,t[s+2]=o,t[s+3]=e[n+1]},function(t,e,s,n){if(n+2>=e.length)throw new Error("Ran out of data");t[s]=e[n],t[s+1]=e[n+1],t[s+2]=e[n+2],t[s+3]=255},function(t,e,s,n){if(n+3>=e.length)throw new Error("Ran out of data");t[s]=e[n],t[s+1]=e[n+1],t[s+2]=e[n+2],t[s+3]=e[n+3]}],mb=[function(){},function(t,e,s,n){let o=e[0];t[s]=o,t[s+1]=o,t[s+2]=o,t[s+3]=n},function(t,e,s){let n=e[0];t[s]=n,t[s+1]=n,t[s+2]=n,t[s+3]=e[1]},function(t,e,s,n){t[s]=e[0],t[s+1]=e[1],t[s+2]=e[2],t[s+3]=n},function(t,e,s){t[s]=e[0],t[s+1]=e[1],t[s+2]=e[2],t[s+3]=e[3]}];function gb(t,e){let s=[],n=0;function o(){if(n===t.length)throw new Error("Ran out of data");let r=t[n];n++;let i,a,l,c,u,d,f,p;switch(e){default:throw new Error("unrecognised depth");case 16:f=t[n],n++,s.push((r<<8)+f);break;case 4:f=r&15,p=r>>4,s.push(p,f);break;case 2:u=r&3,d=r>>2&3,f=r>>4&3,p=r>>6&3,s.push(p,f,d,u);break;case 1:i=r&1,a=r>>1&1,l=r>>2&1,c=r>>3&1,u=r>>4&1,d=r>>5&1,f=r>>6&1,p=r>>7&1,s.push(p,f,d,u,c,l,a,i);break}}return{get:function(r){for(;s.length<r;)o();let i=s.slice(0,r);return s=s.slice(r),i},resetAfterLine:function(){s.length=0},end:function(){if(n!==t.length)throw new Error("extra data found")}}}function yb(t,e,s,n,o,r){let i=t.width,a=t.height,l=t.index;for(let c=0;c<a;c++)for(let u=0;u<i;u++){let d=s(u,c,l);hb[n](e,o,d,r),r+=n}return r}function wb(t,e,s,n,o,r){let i=t.width,a=t.height,l=t.index;for(let c=0;c<a;c++){for(let u=0;u<i;u++){let d=o.get(n),f=s(u,c,l);mb[n](e,d,f,r)}o.resetAfterLine()}}Jf.dataToBitMap=function(t,e){let s=e.width,n=e.height,o=e.depth,r=e.bpp,i=e.interlace,a;o!==8&&(a=gb(t,o));let l;o<=8?l=Buffer.alloc(s*n*4):l=new Uint16Array(s*n*4);let c=Math.pow(2,o)-1,u=0,d,f;if(i)d=Vf.getImagePasses(s,n),f=Vf.getInterlaceIterator(s,n);else{let p=0;f=function(){let m=p;return p+=4,m},d=[{width:s,height:n}]}for(let p=0;p<d.length;p++)o===8?u=yb(d[p],l,f,r,t,u):wb(d[p],l,f,r,a,c);if(o===8){if(u!==t.length)throw new Error("extra data found")}else a.end();return l}});var kl=Q((n1,Zf)=>{"use strict";function _b(t,e,s,n,o){let r=0;for(let i=0;i<n;i++)for(let a=0;a<s;a++){let l=o[t[r]];if(!l)throw new Error("index "+t[r]+" not in palette");for(let c=0;c<4;c++)e[r+c]=l[c];r+=4}}function $b(t,e,s,n,o){let r=0;for(let i=0;i<n;i++)for(let a=0;a<s;a++){let l=!1;if(o.length===1?o[0]===t[r]&&(l=!0):o[0]===t[r]&&o[1]===t[r+1]&&o[2]===t[r+2]&&(l=!0),l)for(let c=0;c<4;c++)e[r+c]=0;r+=4}}function bb(t,e,s,n,o){let r=255,i=Math.pow(2,o)-1,a=0;for(let l=0;l<n;l++)for(let c=0;c<s;c++){for(let u=0;u<4;u++)e[a+u]=Math.floor(t[a+u]*r/i+.5);a+=4}}Zf.exports=function(t,e,s=!1){let n=e.depth,o=e.width,r=e.height,i=e.colorType,a=e.transColor,l=e.palette,c=t;return i===3?_b(t,c,o,r,l):(a&&$b(t,c,o,r,a),n!==8&&!s&&(n===16&&(c=Buffer.alloc(o*r*4)),bb(t,c,o,r,n))),c}});var tp=Q((s1,ep)=>{"use strict";var xb=require("util"),Sl=require("zlib"),Qf=pl(),kb=Gf(),Sb=bl(),vb=xl(),Eb=kl(),Zt=ep.exports=function(t){Qf.call(this),this._parser=new Sb(t,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,"gamma"),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this),simpleTransparency:this._simpleTransparency.bind(this),headersFinished:this._headersFinished.bind(this)}),this._options=t,this.writable=!0,this._parser.start()};xb.inherits(Zt,Qf);Zt.prototype._handleError=function(t){this.emit("error",t),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy&&this._inflate.destroy(),this._filter&&(this._filter.destroy(),this._filter.on("error",function(){})),this.errord=!0};Zt.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=Sl.createInflate(),this._inflate.on("error",this.emit.bind(this,"error")),this._filter.on("complete",this._complete.bind(this)),this._inflate.pipe(this._filter);else{let s=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,n=Math.max(s,Sl.Z_MIN_CHUNK);this._inflate=Sl.createInflate({chunkSize:n});let o=s,r=this.emit.bind(this,"error");this._inflate.on("error",function(a){o&&r(a)}),this._filter.on("complete",this._complete.bind(this));let i=this._filter.write.bind(this._filter);this._inflate.on("data",function(a){o&&(a.length>o&&(a=a.slice(0,o)),o-=a.length,i(a))}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};Zt.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new kb(this._bitmapInfo)};Zt.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};Zt.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};Zt.prototype._simpleTransparency=function(){this._metaData.alpha=!0};Zt.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};Zt.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};Zt.prototype._complete=function(t){if(this.errord)return;let e;try{let s=vb.dataToBitMap(t,this._bitmapInfo);e=Eb(s,this._bitmapInfo,this._options.skipRescale),s=null}catch(s){this._handleError(s);return}this.emit("parsed",e)}});var sp=Q((o1,np)=>{"use strict";var Mt=Ls();np.exports=function(t,e,s,n){let o=[Mt.COLORTYPE_COLOR_ALPHA,Mt.COLORTYPE_ALPHA].indexOf(n.colorType)!==-1;if(n.colorType===n.inputColorType){let m=(function(){let g=new ArrayBuffer(2);return new DataView(g).setInt16(0,256,!0),new Int16Array(g)[0]!==256})();if(n.bitDepth===8||n.bitDepth===16&&m)return t}let r=n.bitDepth!==16?t:new Uint16Array(t.buffer),i=255,a=Mt.COLORTYPE_TO_BPP_MAP[n.inputColorType];a===4&&!n.inputHasAlpha&&(a=3);let l=Mt.COLORTYPE_TO_BPP_MAP[n.colorType];n.bitDepth===16&&(i=65535,l*=2);let c=Buffer.alloc(e*s*l),u=0,d=0,f=n.bgColor||{};f.red===void 0&&(f.red=i),f.green===void 0&&(f.green=i),f.blue===void 0&&(f.blue=i);function p(){let m,g,_,b=i;switch(n.inputColorType){case Mt.COLORTYPE_COLOR_ALPHA:b=r[u+3],m=r[u],g=r[u+1],_=r[u+2];break;case Mt.COLORTYPE_COLOR:m=r[u],g=r[u+1],_=r[u+2];break;case Mt.COLORTYPE_ALPHA:b=r[u+1],m=r[u],g=m,_=m;break;case Mt.COLORTYPE_GRAYSCALE:m=r[u],g=m,_=m;break;default:throw new Error("input color type:"+n.inputColorType+" is not supported at present")}return n.inputHasAlpha&&(o||(b/=i,m=Math.min(Math.max(Math.round((1-b)*f.red+b*m),0),i),g=Math.min(Math.max(Math.round((1-b)*f.green+b*g),0),i),_=Math.min(Math.max(Math.round((1-b)*f.blue+b*_),0),i))),{red:m,green:g,blue:_,alpha:b}}for(let m=0;m<s;m++)for(let g=0;g<e;g++){let _=p(r,u);switch(n.colorType){case Mt.COLORTYPE_COLOR_ALPHA:case Mt.COLORTYPE_COLOR:n.bitDepth===8?(c[d]=_.red,c[d+1]=_.green,c[d+2]=_.blue,o&&(c[d+3]=_.alpha)):(c.writeUInt16BE(_.red,d),c.writeUInt16BE(_.green,d+2),c.writeUInt16BE(_.blue,d+4),o&&c.writeUInt16BE(_.alpha,d+6));break;case Mt.COLORTYPE_ALPHA:case Mt.COLORTYPE_GRAYSCALE:{let b=(_.red+_.green+_.blue)/3;n.bitDepth===8?(c[d]=b,o&&(c[d+1]=_.alpha)):(c.writeUInt16BE(b,d),o&&c.writeUInt16BE(_.alpha,d+2));break}default:throw new Error("unrecognised color Type "+n.colorType)}u+=a,d+=l}return c}});var ip=Q((r1,rp)=>{"use strict";var op=gl();function Tb(t,e,s,n,o){for(let r=0;r<s;r++)n[o+r]=t[e+r]}function Rb(t,e,s){let n=0,o=e+s;for(let r=e;r<o;r++)n+=Math.abs(t[r]);return n}function Cb(t,e,s,n,o,r){for(let i=0;i<s;i++){let a=i>=r?t[e+i-r]:0,l=t[e+i]-a;n[o+i]=l}}function Ab(t,e,s,n){let o=0;for(let r=0;r<s;r++){let i=r>=n?t[e+r-n]:0,a=t[e+r]-i;o+=Math.abs(a)}return o}function Ob(t,e,s,n,o){for(let r=0;r<s;r++){let i=e>0?t[e+r-s]:0,a=t[e+r]-i;n[o+r]=a}}function Nb(t,e,s){let n=0,o=e+s;for(let r=e;r<o;r++){let i=e>0?t[r-s]:0,a=t[r]-i;n+=Math.abs(a)}return n}function Mb(t,e,s,n,o,r){for(let i=0;i<s;i++){let a=i>=r?t[e+i-r]:0,l=e>0?t[e+i-s]:0,c=t[e+i]-(a+l>>1);n[o+i]=c}}function Pb(t,e,s,n){let o=0;for(let r=0;r<s;r++){let i=r>=n?t[e+r-n]:0,a=e>0?t[e+r-s]:0,l=t[e+r]-(i+a>>1);o+=Math.abs(l)}return o}function Lb(t,e,s,n,o,r){for(let i=0;i<s;i++){let a=i>=r?t[e+i-r]:0,l=e>0?t[e+i-s]:0,c=e>0&&i>=r?t[e+i-(s+r)]:0,u=t[e+i]-op(a,l,c);n[o+i]=u}}function Ib(t,e,s,n){let o=0;for(let r=0;r<s;r++){let i=r>=n?t[e+r-n]:0,a=e>0?t[e+r-s]:0,l=e>0&&r>=n?t[e+r-(s+n)]:0,c=t[e+r]-op(i,a,l);o+=Math.abs(c)}return o}var Db={0:Tb,1:Cb,2:Ob,3:Mb,4:Lb},jb={0:Rb,1:Ab,2:Nb,3:Pb,4:Ib};rp.exports=function(t,e,s,n,o){let r;if(!("filterType"in n)||n.filterType===-1)r=[0,1,2,3,4];else if(typeof n.filterType=="number")r=[n.filterType];else throw new Error("unrecognised filter types");n.bitDepth===16&&(o*=2);let i=e*o,a=0,l=0,c=Buffer.alloc((i+1)*s),u=r[0];for(let d=0;d<s;d++){if(r.length>1){let f=1/0;for(let p=0;p<r.length;p++){let m=jb[r[p]](t,l,i,o);m<f&&(u=r[p],f=m)}}c[a]=u,a++,Db[u](t,l,i,c,a,o),a+=i,l+=i}return c}});var vl=Q((i1,ap)=>{"use strict";var it=Ls(),qb=$l(),Fb=sp(),Bb=ip(),Ub=require("zlib"),vn=ap.exports=function(t){if(this._options=t,t.deflateChunkSize=t.deflateChunkSize||32*1024,t.deflateLevel=t.deflateLevel!=null?t.deflateLevel:9,t.deflateStrategy=t.deflateStrategy!=null?t.deflateStrategy:3,t.inputHasAlpha=t.inputHasAlpha!=null?t.inputHasAlpha:!0,t.deflateFactory=t.deflateFactory||Ub.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:it.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:it.COLORTYPE_COLOR_ALPHA,[it.COLORTYPE_GRAYSCALE,it.COLORTYPE_COLOR,it.COLORTYPE_COLOR_ALPHA,it.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([it.COLORTYPE_GRAYSCALE,it.COLORTYPE_COLOR,it.COLORTYPE_COLOR_ALPHA,it.COLORTYPE_ALPHA].indexOf(t.inputColorType)===-1)throw new Error("option input color type:"+t.inputColorType+" is not supported at present");if(t.bitDepth!==8&&t.bitDepth!==16)throw new Error("option bit depth:"+t.bitDepth+" is not supported at present")};vn.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};vn.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};vn.prototype.filterData=function(t,e,s){let n=Fb(t,e,s,this._options),o=it.COLORTYPE_TO_BPP_MAP[this._options.colorType];return Bb(n,e,s,this._options,o)};vn.prototype._packChunk=function(t,e){let s=e?e.length:0,n=Buffer.alloc(s+12);return n.writeUInt32BE(s,0),n.writeUInt32BE(t,4),e&&e.copy(n,8),n.writeInt32BE(qb.crc32(n.slice(4,n.length-4)),n.length-4),n};vn.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*it.GAMMA_DIVISION),0),this._packChunk(it.TYPE_gAMA,e)};vn.prototype.packIHDR=function(t,e){let s=Buffer.alloc(13);return s.writeUInt32BE(t,0),s.writeUInt32BE(e,4),s[8]=this._options.bitDepth,s[9]=this._options.colorType,s[10]=0,s[11]=0,s[12]=0,this._packChunk(it.TYPE_IHDR,s)};vn.prototype.packIDAT=function(t){return this._packChunk(it.TYPE_IDAT,t)};vn.prototype.packIEND=function(){return this._packChunk(it.TYPE_IEND,null)}});var dp=Q((a1,up)=>{"use strict";var Wb=require("util"),lp=require("stream"),Hb=Ls(),Yb=vl(),cp=up.exports=function(t){lp.call(this);let e=t||{};this._packer=new Yb(e),this._deflate=this._packer.createDeflate(),this.readable=!0};Wb.inherits(cp,lp);cp.prototype.pack=function(t,e,s,n){this.emit("data",Buffer.from(Hb.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,s)),n&&this.emit("data",this._packer.packGAMA(n));let o=this._packer.filterData(t,e,s);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(r){this.emit("data",this._packer.packIDAT(r))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(o)}});var yp=Q((vo,gp)=>{"use strict";var fp=require("assert").ok,Is=require("zlib"),Gb=require("util"),pp=require("buffer").kMaxLength;function Wn(t){if(!(this instanceof Wn))return new Wn(t);t&&t.chunkSize<Is.Z_MIN_CHUNK&&(t.chunkSize=Is.Z_MIN_CHUNK),Is.Inflate.call(this,t),this._offset=this._offset===void 0?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,t&&t.maxLength!=null&&(this._maxLength=t.maxLength)}function zb(t){return new Wn(t)}function hp(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}Wn.prototype._processChunk=function(t,e,s){if(typeof s=="function")return Is.Inflate._processChunk.call(this,t,e,s);let n=this,o=t&&t.length,r=this._chunkSize-this._offset,i=this._maxLength,a=0,l=[],c=0,u;this.on("error",function(m){u=m});function d(m,g){if(n._hadError)return;let _=r-g;if(fp(_>=0,"have should not go down"),_>0){let b=n._buffer.slice(n._offset,n._offset+_);if(n._offset+=_,b.length>i&&(b=b.slice(0,i)),l.push(b),c+=b.length,i-=b.length,i===0)return!1}return(g===0||n._offset>=n._chunkSize)&&(r=n._chunkSize,n._offset=0,n._buffer=Buffer.allocUnsafe(n._chunkSize)),g===0?(a+=o-m,o=m,!0):!1}fp(this._handle,"zlib binding closed");let f;do f=this._handle.writeSync(e,t,a,o,this._buffer,this._offset,r),f=f||this._writeState;while(!this._hadError&&d(f[0],f[1]));if(this._hadError)throw u;if(c>=pp)throw hp(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+pp.toString(16)+" bytes");let p=Buffer.concat(l,c);return hp(this),p};Gb.inherits(Wn,Is.Inflate);function Kb(t,e){if(typeof e=="string"&&(e=Buffer.from(e)),!(e instanceof Buffer))throw new TypeError("Not a string or buffer");let s=t._finishFlushFlag;return s==null&&(s=Is.Z_FINISH),t._processChunk(e,s)}function mp(t,e){return Kb(new Wn(e),t)}gp.exports=vo=mp;vo.Inflate=Wn;vo.createInflate=zb;vo.inflateSync=mp});var El=Q((l1,_p)=>{"use strict";var wp=_p.exports=function(t){this._buffer=t,this._reads=[]};wp.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};wp.prototype.process=function(){for(;this._reads.length>0&&this._buffer.length;){let t=this._reads[0];if(this._buffer.length&&(this._buffer.length>=t.length||t.allowLess)){this._reads.shift();let e=this._buffer;this._buffer=e.slice(t.length),t.func.call(this,e.slice(0,t.length))}else break}if(this._reads.length>0)throw new Error("There are some read requests waitng on finished stream");if(this._buffer.length>0)throw new Error("unrecognised content at end of stream")}});var bp=Q($p=>{"use strict";var Xb=El(),Vb=yl();$p.process=function(t,e){let s=[],n=new Xb(t);return new Vb(e,{read:n.read.bind(n),write:function(r){s.push(r)},complete:function(){}}).start(),n.process(),Buffer.concat(s)}});var vp=Q((u1,Sp)=>{"use strict";var xp=!0,kp=require("zlib"),Jb=yp();kp.deflateSync||(xp=!1);var Zb=El(),Qb=bp(),ex=bl(),tx=xl(),nx=kl();Sp.exports=function(t,e){if(!xp)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let s;function n(v){s=v}let o;function r(v){o=v}function i(v){o.transColor=v}function a(v){o.palette=v}function l(){o.alpha=!0}let c;function u(v){c=v}let d=[];function f(v){d.push(v)}let p=new Zb(t);if(new ex(e,{read:p.read.bind(p),error:n,metadata:r,gamma:u,palette:a,transColor:i,inflateData:f,simpleTransparency:l}).start(),p.process(),s)throw s;let g=Buffer.concat(d);d.length=0;let _;if(o.interlace)_=kp.inflateSync(g);else{let E=((o.width*o.bpp*o.depth+7>>3)+1)*o.height;_=Jb(g,{chunkSize:E,maxLength:E})}if(g=null,!_||!_.length)throw new Error("bad png - invalid inflate data response");let b=Qb.process(_,o);g=null;let A=tx.dataToBitMap(b,o);b=null;let P=nx(A,o,e.skipRescale);return o.data=P,o.gamma=c||0,o}});var Cp=Q((d1,Rp)=>{"use strict";var Ep=!0,Tp=require("zlib");Tp.deflateSync||(Ep=!1);var sx=Ls(),ox=vl();Rp.exports=function(t,e){if(!Ep)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let s=e||{},n=new ox(s),o=[];o.push(Buffer.from(sx.PNG_SIGNATURE)),o.push(n.packIHDR(t.width,t.height)),t.gamma&&o.push(n.packGAMA(t.gamma));let r=n.filterData(t.data,t.width,t.height),i=Tp.deflateSync(r,n.getDeflateOptions());if(r=null,!i||!i.length)throw new Error("bad png - invalid compressed data response");return o.push(n.packIDAT(i)),o.push(n.packIEND()),Buffer.concat(o)}});var Ap=Q(Tl=>{"use strict";var rx=vp(),ix=Cp();Tl.read=function(t,e){return rx(t,e||{})};Tl.write=function(t,e){return ix(t,e)}});var Mp=Q(Np=>{"use strict";var ax=require("util"),Op=require("stream"),lx=tp(),cx=dp(),ux=Ap(),dt=Np.PNG=function(t){Op.call(this),t=t||{},this.width=t.width|0,this.height=t.height|0,this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null,t.fill&&this.data&&this.data.fill(0),this.gamma=0,this.readable=this.writable=!0,this._parser=new lx(t),this._parser.on("error",this.emit.bind(this,"error")),this._parser.on("close",this._handleClose.bind(this)),this._parser.on("metadata",this._metadata.bind(this)),this._parser.on("gamma",this._gamma.bind(this)),this._parser.on("parsed",function(e){this.data=e,this.emit("parsed",e)}.bind(this)),this._packer=new cx(t),this._packer.on("data",this.emit.bind(this,"data")),this._packer.on("end",this.emit.bind(this,"end")),this._parser.on("close",this._handleClose.bind(this)),this._packer.on("error",this.emit.bind(this,"error"))};ax.inherits(dt,Op);dt.sync=ux;dt.prototype.pack=function(){return!this.data||!this.data.length?(this.emit("error","No data provided"),this):(process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this)),this)};dt.prototype.parse=function(t,e){if(e){let s,n;s=function(o){this.removeListener("error",n),this.data=o,e(null,this)}.bind(this),n=function(o){this.removeListener("parsed",s),e(o,null)}.bind(this),this.once("parsed",s),this.once("error",n)}return this.end(t),this};dt.prototype.write=function(t){return this._parser.write(t),!0};dt.prototype.end=function(t){this._parser.end(t)};dt.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};dt.prototype._gamma=function(t){this.gamma=t};dt.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};dt.bitblt=function(t,e,s,n,o,r,i,a){if(s|=0,n|=0,o|=0,r|=0,i|=0,a|=0,s>t.width||n>t.height||s+o>t.width||n+r>t.height)throw new Error("bitblt reading outside image");if(i>e.width||a>e.height||i+o>e.width||a+r>e.height)throw new Error("bitblt writing outside image");for(let l=0;l<r;l++)t.data.copy(e.data,(a+l)*e.width+i<<2,(n+l)*t.width+s<<2,(n+l)*t.width+s+o<<2)};dt.prototype.bitblt=function(t,e,s,n,o,r,i){return dt.bitblt(this,t,e,s,n,o,r,i),this};dt.adjustGamma=function(t){if(t.gamma){for(let e=0;e<t.height;e++)for(let s=0;s<t.width;s++){let n=t.width*e+s<<2;for(let o=0;o<3;o++){let r=t.data[n+o]/255;r=Math.pow(r,1/2.2/t.gamma),t.data[n+o]=Math.round(r*255)}}t.gamma=0}};dt.prototype.adjustGamma=function(){dt.adjustGamma(this)}});var jp={};n0(jp,{default:()=>Ip});function Ip(t,e,s,n,o,r={}){let{threshold:i=.1,alpha:a=.1,aaColor:l=[255,255,0],diffColor:c=[255,0,0],includeAA:u,diffColorAlt:d,diffMask:f}=r;if(!Rl(t)||!Rl(e)||s&&!Rl(s))throw new Error("Image data: Uint8Array, Uint8ClampedArray or Buffer expected.");if(t.length!==e.length||s&&s.length!==t.length)throw new Error("Image sizes do not match.");if(t.length!==n*o*4)throw new Error("Image data size does not match width/height.");let p=n*o,m=new Uint32Array(t.buffer,t.byteOffset,p),g=new Uint32Array(e.buffer,e.byteOffset,p),_=!0;for(let S=0;S<p;S++)if(m[S]!==g[S]){_=!1;break}if(_){if(s&&!f)for(let S=0;S<p;S++)Lp(t,4*S,a,s);return 0}let b=35215*i*i,[A,P,v]=l,[E,O,ne]=c,[J,ie,ce]=d||c,se=0;for(let S=0;S<o;S++)for(let Ee=0;Ee<n;Ee++){let W=S*n+Ee,Z=W*4,he=m[W]===g[W]?0:Dp(t,e,Z,Z,!1);if(Math.abs(he)>b){let Ce=Pp(t,Ee,S,n,o,m,g)||Pp(e,Ee,S,n,o,g,m);!u&&Ce?s&&!f&&ii(s,Z,A,P,v):(s&&(he<0?ii(s,Z,J,ie,ce):ii(s,Z,E,O,ne)),se++)}else s&&!f&&Lp(t,Z,a,s)}return se}function Rl(t){return ArrayBuffer.isView(t)&&t.BYTES_PER_ELEMENT===1}function Pp(t,e,s,n,o,r,i){let a=Math.max(e-1,0),l=Math.max(s-1,0),c=Math.min(e+1,n-1),u=Math.min(s+1,o-1),d=s*n+e,f=e===a||e===c||s===l||s===u?1:0,p=0,m=0,g=0,_=0,b=0,A=0;for(let P=a;P<=c;P++)for(let v=l;v<=u;v++){if(P===e&&v===s)continue;let E=Dp(t,t,d*4,(v*n+P)*4,!0);if(E===0){if(f++,f>2)return!1}else E<p?(p=E,g=P,_=v):E>m&&(m=E,b=P,A=v)}return p===0||m===0?!1:ri(r,g,_,n,o)&&ri(i,g,_,n,o)||ri(r,b,A,n,o)&&ri(i,b,A,n,o)}function ri(t,e,s,n,o){let r=Math.max(e-1,0),i=Math.max(s-1,0),a=Math.min(e+1,n-1),l=Math.min(s+1,o-1),c=t[s*n+e],u=e===r||e===a||s===i||s===l?1:0;for(let d=r;d<=a;d++)for(let f=i;f<=l;f++)if(!(d===e&&f===s)&&(u+=+(c===t[f*n+d]),u>2))return!0;return!1}function Dp(t,e,s,n,o){let r=t[s],i=t[s+1],a=t[s+2],l=t[s+3],c=e[n],u=e[n+1],d=e[n+2],f=e[n+3],p=r-c,m=i-u,g=a-d,_=l-f;if(!p&&!m&&!g&&!_)return 0;if(l<255||f<255){let E=48+159*(s%2),O=48+159*((s/1.618033988749895|0)%2),ne=48+159*((s/2.618033988749895|0)%2);p=(r*l-c*f-E*_)/255,m=(i*l-u*f-O*_)/255,g=(a*l-d*f-ne*_)/255}let b=p*.29889531+m*.58662247+g*.11448223;if(o)return b;let A=p*.59597799-m*.2741761-g*.32180189,P=p*.21147017-m*.52261711+g*.31114694,v=.5053*b*b+.299*A*A+.1957*P*P;return b>0?-v:v}function ii(t,e,s,n,o){t[e+0]=s,t[e+1]=n,t[e+2]=o,t[e+3]=255}function Lp(t,e,s,n){let o=255+(t[e]*.29889531+t[e+1]*.58662247+t[e+2]*.11448223-255)*s*t[e+3]/255;ii(n,e,o,o,o)}var qp=t0(()=>{});var Hn=Q((h1,Hp)=>{var fn=require("fs"),dx=require("path"),fx=require("os"),px="nex-visual-";function Bp(t){return dx.join(fx.tmpdir(),`${px}${Date.now()}-${t}`)}var Cl=null;function ai(){return Cl||(Cl=Mp().PNG),Cl}var Al=null;function hx(){if(!Al){let t=(qp(),o0(jp));Al=t.default||t}return Al}function Ml(t,e,{threshold:s=.1}={}){let n=ai(),o=hx(),r=n.sync.read(fn.readFileSync(t)),i=n.sync.read(fn.readFileSync(e)),a=Math.max(r.width,i.width),l=Math.max(r.height,i.height),c=Fp(r,a,l),u=Fp(i,a,l),d=new n({width:a,height:l}),f=o(c,u,d.data,a,l,{threshold:s,includeAA:!1}),p=a*l,m=(f/p*100).toFixed(1),g=mx(d.data,a,l,3,3),_=Bp("diff.png");return fn.writeFileSync(_,n.sync.write(d),{mode:384}),{diffPath:_,diffPercent:parseFloat(m),totalPixels:p,changedPixels:f,regionSummary:g,beforePath:t,afterPath:e,width:a,height:l}}function Fp(t,e,s){if(t.width===e&&t.height===s)return t.data;let n=Buffer.alloc(e*s*4,0);for(let o=0;o<t.height;o++){let r=o*t.width*4,i=o*e*4;t.data.copy(n,i,r,r+t.width*4)}return n}function mx(t,e,s,n,o){let r=[["top-left","top-center","top-right"],["middle-left","center","middle-right"],["bottom-left","bottom-center","bottom-right"]],i=Math.ceil(e/n),a=Math.ceil(s/o),l=[];for(let c=0;c<o;c++)for(let u=0;u<n;u++){let d=0,f=0,p=u*i,m=c*a,g=Math.min(p+i,e),_=Math.min(m+a,s);for(let b=m;b<_;b++)for(let A=p;A<g;A++){f++;let P=(b*e+A)*4;(t[P]>0||t[P+1]>0)&&d++}if(d>0){let b=(d/f*100).toFixed(1),A=r[c]&&r[c][u]?r[c][u]:`row${c}-col${u}`;l.push({name:A,changedPercent:parseFloat(b),changed:d,total:f})}}return l.sort((c,u)=>u.changedPercent-c.changedPercent),l}var Up=[{width:320,label:"mobile-sm"},{width:768,label:"tablet"},{width:1024,label:"desktop-sm"},{width:1440,label:"desktop"},{width:1920,label:"desktop-lg"}];async function gx(t,{viewports:e=Up,height:s=800,fullPage:n=!1,timeout:o=3e4}={}){let{browserScreenshot:r}=dn(),i=[];for(let a of e){let l=await r(t,{width:a.width,height:s,fullPage:n,timeout:o});i.push({label:a.label,width:a.width,path:l.path,base64:l.base64,media_type:l.media_type})}return i}function Wp(t,e=[]){let s=ai(),n=s.sync.read(fn.readFileSync(t));for(let i of e){let a=yx(i.color||"#FF0000");i.type==="box"?(wx(n,i.x||0,i.y||0,i.width||50,i.height||50,a,i.thickness||3),i.label&&Nl(n,i.x||0,(i.y||0)-14,i.label,a)):i.type==="arrow"?(_x(n,i.x||0,i.y||0,i.toX||i.x+50,i.toY||i.y,a,i.thickness||3),i.label&&Nl(n,i.x||0,(i.y||0)-14,i.label,a)):i.type==="circle"&&($x(n,i.x||0,i.y||0,i.radius||20,a,i.thickness||3),i.label&&Nl(n,(i.x||0)-(i.radius||20),(i.y||0)-(i.radius||20)-14,i.label,a))}let o=Bp("annotated.png");fn.writeFileSync(o,s.sync.write(n),{mode:384});let r=fn.readFileSync(o).toString("base64");return{path:o,base64:r,media_type:"image/png"}}function yx(t){let e=t.replace("#","");return{r:parseInt(e.substring(0,2),16),g:parseInt(e.substring(2,4),16),b:parseInt(e.substring(4,6),16),a:255}}function Qt(t,e,s,n){if(e<0||s<0||e>=t.width||s>=t.height)return;let o=(s*t.width+e)*4;t.data[o]=n.r,t.data[o+1]=n.g,t.data[o+2]=n.b,t.data[o+3]=n.a}function wx(t,e,s,n,o,r,i=3){for(let a=0;a<i;a++){for(let l=0;l<n;l++)Qt(t,e+l,s+a,r),Qt(t,e+l,s+o-1-a,r);for(let l=0;l<o;l++)Qt(t,e+a,s+l,r),Qt(t,e+n-1-a,s+l,r)}}function Ol(t,e,s,n,o,r,i=3){let a=Math.abs(n-e),l=Math.abs(o-s),c=e<n?1:-1,u=s<o?1:-1,d=a-l,f=e,p=s;for(;;){let m=Math.floor(i/2);for(let _=-m;_<=m;_++)for(let b=-m;b<=m;b++)Qt(t,f+_,p+b,r);if(f===n&&p===o)break;let g=2*d;g>-l&&(d-=l,f+=c),g<a&&(d+=a,p+=u)}}function _x(t,e,s,n,o,r,i=3){Ol(t,e,s,n,o,r,i);let a=Math.atan2(o-s,n-e),l=15,c=a+Math.PI*.8,u=a-Math.PI*.8;Ol(t,n,o,Math.round(n+l*Math.cos(c)),Math.round(o+l*Math.sin(c)),r,i),Ol(t,n,o,Math.round(n+l*Math.cos(u)),Math.round(o+l*Math.sin(u)),r,i)}function $x(t,e,s,n,o,r=3){for(let i=0;i<r;i++){let a=n-i;for(let l=0;l<360;l+=.5){let c=l*Math.PI/180,u=Math.round(e+a*Math.cos(c)),d=Math.round(s+a*Math.sin(c));Qt(t,u,d,o)}}}function Nl(t,e,s,n,o){let i=n.length*6+4,a=12;for(let l=0;l<a;l++)for(let c=0;c<i;c++)Qt(t,e+c,s+l,{r:0,g:0,b:0,a:200});for(let l=0;l<i;l++)Qt(t,e+l,s+a-1,o),Qt(t,e+l,s+a-2,o);for(let l=0;l<n.length;l++){let c=e+2+l*6;for(let u=2;u<9;u++)for(let d=0;d<4;d++)Qt(t,c+d,s+u,o)}}async function*bx(t,e,{maxIterations:s=20,hmrDelay:n=1500,width:o=1280,height:r=800,timeout:i=3e4}={}){let{browserScreenshot:a}=dn(),l=xx("chokidar"),c=await a(t,{width:o,height:r,timeout:i});if(yield{iteration:0,type:"baseline",path:c.path,base64:c.base64,media_type:c.media_type},!l){yield{iteration:-1,type:"error",message:"chokidar not installed \u2014 watch mode requires it. Install with: npm install chokidar"};return}let u=0,d=!1,f=l.watch(e,{ignoreInitial:!0,ignored:/(node_modules|\.git|dist)/});f.on("change",()=>{d=!0});try{for(;u<s;){await Sx(()=>d,3e5),d=!1,u++,await kx(n);let p=await a(t,{width:o,height:r,timeout:i}),m=null;try{m=Ml(c.path,p.path)}catch{}c=p,yield{iteration:u,type:"change",path:p.path,base64:p.base64,media_type:p.media_type,diff:m?{diffPath:m.diffPath,diffPercent:m.diffPercent,changedPixels:m.changedPixels,regions:m.regionSummary}:null}}}finally{await f.close()}}function xx(t){try{return require(t)}catch{return null}}function kx(t){return new Promise(e=>setTimeout(e,t))}function Sx(t,e=6e4){return new Promise((s,n)=>{let o=setInterval(()=>{t()&&(clearInterval(o),clearTimeout(r),s())},200),r=setTimeout(()=>{clearInterval(o),n(new Error("Watch timeout \u2014 no file changes detected"))},e)})}function vx(t,{sampleRate:e=4}={}){let n=ai().sync.read(fn.readFileSync(t)),o=new Map;for(let c=0;c<n.height;c+=e)for(let u=0;u<n.width;u+=e){let d=(c*n.width+u)*4,f=n.data[d],p=n.data[d+1],m=n.data[d+2];if(n.data[d+3]<128)continue;let _=Math.round(f/8)*8,b=Math.round(p/8)*8,A=Math.round(m/8)*8,P=`${_},${b},${A}`;o.set(P,(o.get(P)||0)+1)}let r=[...o.entries()].sort((c,u)=>u[1]-c[1]).slice(0,20),i=r.reduce((c,u)=>c+u[1],0),a=r.map(([c,u])=>{let[d,f,p]=c.split(",").map(Number);return{hex:Ex(d,f,p),rgb:`rgb(${d}, ${f}, ${p})`,frequency:parseFloat((u/i*100).toFixed(1)),category:Tx(d,f,p)}}),l=Rx(n);return{colors:a,spacing:l,dimensions:{width:n.width,height:n.height},imagePath:t}}function Ex(t,e,s){return"#"+[t,e,s].map(n=>Math.min(255,n).toString(16).padStart(2,"0")).join("")}function Tx(t,e,s){let n=(t*299+e*587+s*114)/1e3;return n>240?"white/background":n<30?"black/text":n<80?"dark":t>200&&e<100&&s<100?"red/danger":t<100&&e>150&&s<100?"green/success":t<100&&e<100&&s>200?"blue/primary":t>200&&e>200&&s<100?"yellow/warning":t>200&&e>100&&s<50?"orange/accent":n>200?"light/subtle":"midtone"}function Rx(t){let e=[],s=!1,n=0,o=Cx(t);for(let i=0;i<t.height;i++){let a=!0;for(let l=0;l<t.width;l+=4){let c=(i*t.width+l)*4;if(Math.abs(t.data[c]-o.r)>20||Math.abs(t.data[c+1]-o.g)>20||Math.abs(t.data[c+2]-o.b)>20){a=!1;break}}if(a&&s)s=!1,n=i;else if(!a&&!s&&(s=!0,n>0)){let l=i-n;l>=4&&l<=200&&e.push(l)}}let r=new Map;for(let i of e){let a=Math.round(i/4)*4;r.set(a,(r.get(a)||0)+1)}return[...r.entries()].sort((i,a)=>a[1]-i[1]).slice(0,8).map(([i,a])=>({px:i,occurrences:a}))}function Cx(t){let e=[[0,0],[t.width-1,0],[0,t.height-1],[t.width-1,t.height-1]],s=0,n=0,o=0;for(let[r,i]of e){let a=(i*t.width+r)*4;s+=t.data[a],n+=t.data[a+1],o+=t.data[a+2]}return{r:Math.round(s/4),g:Math.round(n/4),b:Math.round(o/4)}}async function Ax(t,e,{width:s,height:n=800,fullPage:o=!1,threshold:r=.1,timeout:i=3e4}={}){let{browserScreenshot:a}=dn(),c=ai().sync.read(fn.readFileSync(e)),u=s||c.width,d=n||c.height,f=await a(t,{width:u,height:d,fullPage:o,timeout:i}),p=Ml(e,f.path,{threshold:r}),m=Wp(f.path,p.regionSummary.filter(g=>g.changedPercent>1).map((g,_)=>{let P=Math.ceil(p.width/3),v=Math.ceil(p.height/3),E=[["top-left","top-center","top-right"],["middle-left","center","middle-right"],["bottom-left","bottom-center","bottom-right"]],O=0,ne=0;for(let J=0;J<3;J++)for(let ie=0;ie<3;ie++)E[J][ie]===g.name&&(O=ie,ne=J);return{type:"box",x:O*P+2,y:ne*v+2,width:P-4,height:v-4,label:`${g.name}: ${g.changedPercent}%`,color:g.changedPercent>10?"#FF0000":"#FFAA00"}}));return{livePath:f.path,referencePath:e,diffPath:p.diffPath,annotatedPath:m.path,diffPercent:p.diffPercent,changedPixels:p.changedPixels,totalPixels:p.totalPixels,regions:p.regionSummary,liveBase64:f.base64,diffBase64:fn.readFileSync(p.diffPath).toString("base64"),annotatedBase64:m.base64}}Hp.exports={pixelDiff:Ml,responsiveSweep:gx,annotateImage:Wp,visualWatch:bx,extractDesignTokens:vx,designCompare:Ax,DEFAULT_VIEWPORTS:Up}});var Pl=Q((m1,Yp)=>{var{C:Pe}=Ke(),To="",ft=[],Eo=0,Yn=null;function Ox(t){Yn=t}function Nx(t,e){To=t,ft=[],Eo=0;for(let n of e){Eo++;let o=`t${Eo}`;ft.push({id:o,description:n.description||n.title||n.name||n.task||`Task ${Eo}`,status:"pending",dependsOn:n.depends_on||[],result:null})}let s=ft.map(n=>({...n}));return Yn&&Yn("create",{name:t,tasks:s}),s}function Mx(t,e,s){let n=ft.find(o=>o.id===t);return n?(n.status=e,s!==void 0&&(n.result=s),Yn&&Yn("update",{id:t,status:e,result:s}),{...n}):null}function Px(){return{name:To,tasks:ft.map(t=>({...t}))}}function Lx(){To="",ft=[],Eo=0,Yn&&Yn("clear",{})}function Ix(){return ft.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let s=ft.find(n=>n.id===e);return s&&s.status==="done"}))}function Dx(){if(ft.length===0)return`${Pe.dim}No active tasks${Pe.reset}`;let t=[];To&&(t.push(` ${Pe.bold}${Pe.cyan}Tasks: ${To}${Pe.reset}`),t.push(` ${Pe.dim}${"\u2500".repeat(40)}${Pe.reset}`));for(let o of ft){let r,i;switch(o.status){case"done":r="\u2713",i=Pe.green;break;case"in_progress":r="\u2192",i=Pe.cyan;break;case"failed":r="\u2717",i=Pe.red;break;default:r="\xB7",i=Pe.dim}let a=o.dependsOn.length>0?` ${Pe.dim}(after: ${o.dependsOn.join(", ")})${Pe.reset}`:"",l=`[${o.status}]`,c=o.description.length>50?o.description.substring(0,47)+"...":o.description;if(t.push(` ${i}${r}${Pe.reset} ${Pe.bold}${o.id}${Pe.reset} ${c.padEnd(40)} ${i}${l}${Pe.reset}${a}`),o.result&&o.status==="done"){let u=o.result.length>60?o.result.substring(0,57)+"...":o.result;t.push(` ${Pe.dim}\u2192 ${u}${Pe.reset}`)}}let e=ft.filter(o=>o.status==="done").length,s=ft.filter(o=>o.status==="failed").length,n=ft.length;return t.push(` ${Pe.dim}${"\u2500".repeat(40)}${Pe.reset}`),t.push(` ${Pe.dim}${e}/${n} done${s>0?`, ${s} failed`:""}${Pe.reset}`),t.join(`
133
+ `)}function jx(){return ft.length>0&&ft.some(t=>t.status==="pending"||t.status==="in_progress")}Yp.exports={createTasks:Nx,updateTask:Mx,getTaskList:Px,clearTasks:Lx,getReadyTasks:Ix,renderTaskList:Dx,setOnChange:Ox,hasActiveTasks:jx}});var li=Q((g1,zp)=>{var Ro={"devstral-2":{staleWarn:3e4,staleAbort:9e4,investigationCap:18,postEditCap:10,briefing:`You are devstral-2, a strong coding model optimized for agentic tasks.
134
134
  Use tools confidently and without hesitation \u2014 tool use is the expected workflow.
135
135
  You excel at sysadmin, frontend, and multi-step coding tasks.
136
136
  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.
@@ -143,7 +143,7 @@ Focus on correctness over speed.`},"ministral-3":{staleWarn:2e4,staleAbort:6e4,i
143
143
  Prioritize decisive, targeted edits. Read only what you need, then fix.
144
144
  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.
145
145
  Trust your reasoning. Use tools thoroughly when the task demands it.
146
- You handle complex multi-step tasks well \u2014 don't cut corners prematurely.`}},Ip={staleWarn:6e4,staleAbort:12e4,investigationCap:18,postEditCap:10};function Ax(t){let e=(t||"").toLowerCase(),s=null,n=0;for(let r of Object.keys(So))e.startsWith(r)&&r.length>n&&(s=r,n=r.length);let o=s?{...So[s]}:{...Ip};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 Ox(t){let e=(t||"").toLowerCase(),s=null,n=0;for(let o of Object.keys(So))e.startsWith(o)&&o.length>n&&(s=o,n=o.length);return s&&So[s].briefing||""}Dp.exports={getModelProfile:Ax,getModelBriefing:Ox,PROFILES:So,DEFAULTS:Ip}});var Al=Z((ZR,Wp)=>{var{callChat:Nx}=Ze(),{estimateTokens:Cl}=en(),jp=process.env.NEX_COMPACTION!=="false",qp=6,Fp=2e3,Bp=3,Mx=`Your task is to create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions.
146
+ You handle complex multi-step tasks well \u2014 don't cut corners prematurely.`}},Gp={staleWarn:6e4,staleAbort:12e4,investigationCap:18,postEditCap:10};function qx(t){let e=(t||"").toLowerCase(),s=null,n=0;for(let r of Object.keys(Ro))e.startsWith(r)&&r.length>n&&(s=r,n=r.length);let o=s?{...Ro[s]}:{...Gp};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 Fx(t){let e=(t||"").toLowerCase(),s=null,n=0;for(let o of Object.keys(Ro))e.startsWith(o)&&o.length>n&&(s=o,n=o.length);return s&&Ro[s].briefing||""}zp.exports={getModelProfile:qx,getModelBriefing:Fx,PROFILES:Ro,DEFAULTS:Gp}});var Il=Q((y1,Qp)=>{var{callChat:Bx}=Qe(),{estimateTokens:Ll}=en(),Kp=process.env.NEX_COMPACTION!=="false",Xp=6,Vp=2e3,Jp=3,Ux=`Your task is to create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions.
147
147
  This summary should be thorough in capturing technical details, code patterns, and architectural decisions that would be essential for continuing development work without losing context.
148
148
 
149
149
  Before providing your final summary, wrap your analysis in <analysis> tags to organize your thoughts and ensure you've covered all necessary points. In your analysis process:
@@ -175,30 +175,30 @@ Format your output as:
175
175
 
176
176
  <summary>
177
177
  [Sections 1-9 above]
178
- </summary>`,zn=0;async function Px(t){if(!jp||t.length<qp||zn>=Bp)return null;let e=[{role:"system",content:Mx},{role:"user",content:Up(t)}];try{let n=((await Nx(e,[],{temperature:0,maxTokens:Fp})).content||"").trim();if(!n)return zn++,null;let o=n.match(/<summary>([\s\S]*?)<\/summary>/);if(o?n=o[1].trim():n=n.replace(/<analysis>[\s\S]*?<\/analysis>/g,"").trim(),!n)return zn++,null;let r=t.reduce((a,l)=>a+Cl(l.content||"")+(l.tool_calls?Cl(JSON.stringify(l.tool_calls)):0),0),i=Cl(n);return i>=r*.8?(zn++,null):(zn=0,{message:{role:"system",content:`[Conversation Summary \u2014 ${t.length} messages compacted]
179
- ${n}`,_compacted:!0,_originalCount:t.length},tokensRemoved:r-i})}catch{return zn++,null}}function Lx(){zn=0}function Up(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}
178
+ </summary>`,Gn=0;async function Wx(t){if(!Kp||t.length<Xp||Gn>=Jp)return null;let e=[{role:"system",content:Ux},{role:"user",content:Zp(t)}];try{let n=((await Bx(e,[],{temperature:0,maxTokens:Vp})).content||"").trim();if(!n)return Gn++,null;let o=n.match(/<summary>([\s\S]*?)<\/summary>/);if(o?n=o[1].trim():n=n.replace(/<analysis>[\s\S]*?<\/analysis>/g,"").trim(),!n)return Gn++,null;let r=t.reduce((a,l)=>a+Ll(l.content||"")+(l.tool_calls?Ll(JSON.stringify(l.tool_calls)):0),0),i=Ll(n);return i>=r*.8?(Gn++,null):(Gn=0,{message:{role:"system",content:`[Conversation Summary \u2014 ${t.length} messages compacted]
179
+ ${n}`,_compacted:!0,_originalCount:t.length},tokensRemoved:r-i})}catch{return Gn++,null}}function Hx(){Gn=0}function Zp(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}
180
180
  tools: ${o}`}return`[${s}] ${n}`}).join(`
181
181
 
182
- `)}Wp.exports={compactMessages:Px,formatMessagesForSummary:Up,resetCompactionFailures:Lx,COMPACTION_ENABLED:jp,COMPACTION_MIN_MESSAGES:qp,COMPACTION_SUMMARY_BUDGET:Fp,MAX_CONSECUTIVE_FAILURES:Bp}});var en=Z((QR,Qp)=>{var Ix=require("path");function Yp(){return Ze().getActiveModel()}var Dx={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},jx={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},Kn=new Map,Hp=1e3,Ol=new WeakMap,Xn=null;function qx(){if(Xn!==null)return Xn;try{let t=Yp(),e=t?.provider||"ollama",s=(t?.id||"").toLowerCase();for(let[n,o]of Object.entries(jx))if(s.startsWith(n))return Xn=o,Xn;return Xn=Dx[e]||4,Xn}catch{return 4}}function Fx(){Xn=null}function Vn(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=Kn.get(e);if(s!==void 0)return Kn.delete(e),Kn.set(e,s),s;let n=Math.ceil(t.length/qx());if(Kn.size>=Hp){let o=Hp>>1,r=Kn.keys();for(let i=0;i<o;i++)Kn.delete(r.next().value)}return Kn.set(e,n),n}function Bx(t){if(Ol.has(t))return Ol.get(t);let e=JSON.stringify(t);return Ol.set(t,e),e}function Jn(t){let s=4;if(t.content&&(s+=Vn(t.content)),t.tool_calls)for(let n of t.tool_calls){s+=4,s+=Vn(n.function?.name||"");let o=n.function?.arguments;typeof o=="string"?s+=Vn(o):o&&(s+=Vn(JSON.stringify(o)))}return s}function Wt(t){let e=0;for(let s of t)e+=Jn(s);return e}function Ux(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+=Jn(e[r]);return o}var Nl=new WeakMap;function ri(t){if(!t||t.length===0)return 0;if(Nl.has(t))return Nl.get(t);let e=Vn(JSON.stringify(t));return Nl.set(t,e),e}function ii(){return Yp()?.contextWindow||32768}var pt={msgCount:-1,lastMsgRef:null,toolCount:-1,result:null,messagesRef:null,messageTokens:0,systemTokens:0,conversationTokens:0,toolResultTokens:0};function Wx(t,e){let s=t.length>0?t[t.length-1]:null,n=e?e.length:0;if(pt.result&&t.length===pt.msgCount&&s===pt.lastMsgRef&&n===pt.toolCount)return pt.result;let o,r,i,a;if(pt.messagesRef===t&&t.length>pt.msgCount&&pt.msgCount>=0){o=pt.messageTokens,r=pt.systemTokens,i=pt.conversationTokens,a=pt.toolResultTokens;for(let p=pt.msgCount;p<t.length;p++){let h=Jn(t[p]);o+=h,t[p].role==="system"?r+=h:t[p].role==="tool"?a+=h:i+=h}}else{o=0,r=0,i=0,a=0;for(let p of t){let h=Jn(p);o+=h,p.role==="system"?r+=h:p.role==="tool"?a+=h:i+=h}}let l=ri(e),c=o+l,u=ii(),d=u>0?c/u*100:0,f={used:c,limit:u,percentage:Math.round(d*10)/10,breakdown:{system:r,conversation:i,toolResults:a,toolDefinitions:l},messageCount:t.length};return pt={msgCount:t.length,lastMsgRef:s,toolCount:n,result:f,messagesRef:t,messageTokens:o,systemTokens:r,conversationTokens:i,toolResultTokens:a},f}var vo=parseFloat(process.env.NEX_COMPRESSION_THRESHOLD)||.75,Gp=parseFloat(process.env.NEX_SAFETY_MARGIN)||.1,zp=parseInt(process.env.NEX_KEEP_RECENT,10)||10,Kp={essential:.6,standard:.65,full:Math.min(vo,.75)};function Xp(){if(process.env.NEX_COMPRESSION_THRESHOLD)return vo;try{let{getActiveTier:t}=_o(),e=t();return Kp[e]??vo}catch{return vo}}var Hx=200,Yx=1e3;function Vp(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(`
183
- `);if(o.length<=10){let h=Math.floor(n*.6),g=Math.floor(n*.4),_=t.substring(0,h),b=t.substring(t.length-g);return _+`
182
+ `)}Qp.exports={compactMessages:Wx,formatMessagesForSummary:Zp,resetCompactionFailures:Hx,COMPACTION_ENABLED:Kp,COMPACTION_MIN_MESSAGES:Xp,COMPACTION_SUMMARY_BUDGET:Vp,MAX_CONSECUTIVE_FAILURES:Jp}});var en=Q((w1,ch)=>{var Yx=require("path");function th(){return Qe().getActiveModel()}var Gx={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},zx={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},zn=new Map,eh=1e3,Dl=new WeakMap,Kn=null;function Kx(){if(Kn!==null)return Kn;try{let t=th(),e=t?.provider||"ollama",s=(t?.id||"").toLowerCase();for(let[n,o]of Object.entries(zx))if(s.startsWith(n))return Kn=o,Kn;return Kn=Gx[e]||4,Kn}catch{return 4}}function Xx(){Kn=null}function Xn(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=zn.get(e);if(s!==void 0)return zn.delete(e),zn.set(e,s),s;let n=Math.ceil(t.length/Kx());if(zn.size>=eh){let o=eh>>1,r=zn.keys();for(let i=0;i<o;i++)zn.delete(r.next().value)}return zn.set(e,n),n}function Vx(t){if(Dl.has(t))return Dl.get(t);let e=JSON.stringify(t);return Dl.set(t,e),e}function Vn(t){let s=4;if(t.content&&(s+=Xn(t.content)),t.tool_calls)for(let n of t.tool_calls){s+=4,s+=Xn(n.function?.name||"");let o=n.function?.arguments;typeof o=="string"?s+=Xn(o):o&&(s+=Xn(JSON.stringify(o)))}return s}function Wt(t){let e=0;for(let s of t)e+=Vn(s);return e}function Jx(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+=Vn(e[r]);return o}var jl=new WeakMap;function ci(t){if(!t||t.length===0)return 0;if(jl.has(t))return jl.get(t);let e=Xn(JSON.stringify(t));return jl.set(t,e),e}function ui(){return th()?.contextWindow||32768}var pt={msgCount:-1,lastMsgRef:null,toolCount:-1,result:null,messagesRef:null,messageTokens:0,systemTokens:0,conversationTokens:0,toolResultTokens:0};function Zx(t,e){let s=t.length>0?t[t.length-1]:null,n=e?e.length:0;if(pt.result&&t.length===pt.msgCount&&s===pt.lastMsgRef&&n===pt.toolCount)return pt.result;let o,r,i,a;if(pt.messagesRef===t&&t.length>pt.msgCount&&pt.msgCount>=0){o=pt.messageTokens,r=pt.systemTokens,i=pt.conversationTokens,a=pt.toolResultTokens;for(let p=pt.msgCount;p<t.length;p++){let m=Vn(t[p]);o+=m,t[p].role==="system"?r+=m:t[p].role==="tool"?a+=m:i+=m}}else{o=0,r=0,i=0,a=0;for(let p of t){let m=Vn(p);o+=m,p.role==="system"?r+=m:p.role==="tool"?a+=m:i+=m}}let l=ci(e),c=o+l,u=ui(),d=u>0?c/u*100:0,f={used:c,limit:u,percentage:Math.round(d*10)/10,breakdown:{system:r,conversation:i,toolResults:a,toolDefinitions:l},messageCount:t.length};return pt={msgCount:t.length,lastMsgRef:s,toolCount:n,result:f,messagesRef:t,messageTokens:o,systemTokens:r,conversationTokens:i,toolResultTokens:a},f}var Co=parseFloat(process.env.NEX_COMPRESSION_THRESHOLD)||.75,nh=parseFloat(process.env.NEX_SAFETY_MARGIN)||.1,sh=parseInt(process.env.NEX_KEEP_RECENT,10)||10,oh={essential:.6,standard:.65,full:Math.min(Co,.75)};function rh(){if(process.env.NEX_COMPRESSION_THRESHOLD)return Co;try{let{getActiveTier:t}=ko(),e=t();return oh[e]??Co}catch{return Co}}var Qx=200,ek=1e3;function ih(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(`
183
+ `);if(o.length<=10){let m=Math.floor(n*.6),g=Math.floor(n*.4),_=t.substring(0,m),b=t.substring(t.length-g);return _+`
184
184
  ...(${t.length} chars total)...
185
- `+b}let r=Math.floor(o.length*.4),i=Math.floor(o.length*.4),a=[],l=0,c=Math.floor(n*.4);for(let h=0;h<r&&l<c;h++)if(l+o[h].length+1>c&&o[h].trim().startsWith("```")){a.push(o[h]),l+=o[h].length+1;let g=h+1;for(;g<o.length&&l<c*1.5&&!o[g].trim().startsWith("```");)a.push(o[g]),l+=o[g].length+1,g++;g<o.length&&o[g].trim().startsWith("```")&&(a.push(o[g]),l+=o[g].length+1),h=g}else a.push(o[h]),l+=o[h].length+1;let u=[],d=0,f=Math.floor(n*.4);for(let h=o.length-1;h>=o.length-i&&d<f;h--)if(d+o[h].length+1>f&&o[h].trim().startsWith("```")){u.push(o[h]),d+=o[h].length+1;let g=h-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),h=g}else u.push(o[h]),d+=o[h].length+1;u.reverse();let p=o.length-a.length-u.length;return a.join(`
185
+ `+b}let r=Math.floor(o.length*.4),i=Math.floor(o.length*.4),a=[],l=0,c=Math.floor(n*.4);for(let m=0;m<r&&l<c;m++)if(l+o[m].length+1>c&&o[m].trim().startsWith("```")){a.push(o[m]),l+=o[m].length+1;let g=m+1;for(;g<o.length&&l<c*1.5&&!o[g].trim().startsWith("```");)a.push(o[g]),l+=o[g].length+1,g++;g<o.length&&o[g].trim().startsWith("```")&&(a.push(o[g]),l+=o[g].length+1),m=g}else a.push(o[m]),l+=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 p=o.length-a.length-u.length;return a.join(`
186
186
  `)+`
187
187
  ...(${p} lines omitted, ${o.length} total)...
188
188
  `+u.join(`
189
- `)}function Is(t,e="light"){let s=e==="aggressive"?100:e==="medium"?200:Yx,n=e==="aggressive"?50:e==="medium"?100:Hx;if(t.role==="tool"){let o=typeof t.content=="string"?t.content:JSON.stringify(t.content);return o.length>n?{...t,content:Vp(o,n)}:t}if(t.role==="assistant"){let o={...t};return o.content&&o.content.length>s&&(o.content=o.content.substring(0,s)+`
190
- ...(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 Jp(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 l of n)(i.includes(l)||i.includes(Ix.basename(l)))&&a++;o+=Math.min(30,a*10)}return Math.min(100,o)}function Zp(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(l=>s.add(l))}return s}function Gx(t,{filesModified:e=new Set,currentPhase:s=null}={}){let n=[];if(e.size>0){let r=[...e].map(i=>i.split("/").slice(-2).join("/")).join(", ");n.push(`Files already modified: ${r} \u2014 do NOT rewrite these, use edit_file for additions only.`)}s&&n.push(`Current phase: ${s}`);let o=t.filter(r=>r.role==="assistant"&&typeof r.content=="string"&&r.content.trim().length>30).slice(-3).map(r=>r.content.trim().slice(0,200).replace(/\n+/g," "));return o.length>0&&n.push(`Recent progress:
189
+ `)}function js(t,e="light"){let s=e==="aggressive"?100:e==="medium"?200:ek,n=e==="aggressive"?50:e==="medium"?100:Qx;if(t.role==="tool"){let o=typeof t.content=="string"?t.content:JSON.stringify(t.content);return o.length>n?{...t,content:ih(o,n)}:t}if(t.role==="assistant"){let o={...t};return o.content&&o.content.length>s&&(o.content=o.content.substring(0,s)+`
190
+ ...(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 ah(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 l of n)(i.includes(l)||i.includes(Yx.basename(l)))&&a++;o+=Math.min(30,a*10)}return Math.min(100,o)}function lh(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(l=>s.add(l))}return s}function tk(t,{filesModified:e=new Set,currentPhase:s=null}={}){let n=[];if(e.size>0){let r=[...e].map(i=>i.split("/").slice(-2).join("/")).join(", ");n.push(`Files already modified: ${r} \u2014 do NOT rewrite these, use edit_file for additions only.`)}s&&n.push(`Current phase: ${s}`);let o=t.filter(r=>r.role==="assistant"&&typeof r.content=="string"&&r.content.trim().length>30).slice(-3).map(r=>r.content.trim().slice(0,200).replace(/\n+/g," "));return o.length>0&&n.push(`Recent progress:
191
191
  `+o.map(r=>`- ${r}`).join(`
192
192
  `)),n.length===0?null:{role:"system",content:`## Progress State (preserved through compression)
193
193
  ${n.join(`
194
- `)}`,_pinned:!0,_progressSnapshot:!0}}var Ls={msgCount:-1,lastMsgRef:null,result:null};function zx(){Ls={msgCount:-1,lastMsgRef:null,result:null},pt={msgCount:-1,lastMsgRef:null,toolCount:-1,result:null,messagesRef:null,messageTokens:0,systemTokens:0,conversationTokens:0,toolResultTokens:0}}async function Kx(t,e,s={}){let n=t.length>0?t[t.length-1]:null;if(!s.force&&Ls.result&&t.length===Ls.msgCount&&n===Ls.lastMsgRef)return Ls.result;let o=s.threshold??Xp(),r=s.safetyMargin??Gp,i=s.keepRecent??zp,a=ii(),l=ri(e),c=Math.floor(a*(o-r)),u=c-l,d=Wt(t);if(d+l<=c){let ne={messages:t,compressed:!1,compacted:!1,tokensRemoved:0};return Ls={msgCount:t.length,lastMsgRef:n,result:ne},ne}let p=d,h=null,g=0;t.length>0&&t[0].role==="system"&&(h=t[0],g=1);let _=Math.max(g,t.length-i),b=t.slice(g,_),O=t.slice(_),M=b.map(ne=>Is(ne,"light")),v=Tn(h,M,O),T=Wt(v);if(T+l<=c)return{messages:v,compressed:!0,compacted:!1,tokensRemoved:p-T};if(M=b.map(ne=>Is(ne,"medium")),v=Tn(h,M,O),T=Wt(v),T+l<=c)return{messages:v,compressed:!0,compacted:!1,tokensRemoved:p-T};if(M=b.map(ne=>Is(ne,"aggressive")),v=Tn(h,M,O),T=Wt(v),T+l<=c)return{messages:v,compressed:!0,compacted:!1,tokensRemoved:p-T};let N=process.env.NEX_SKIP_COMPACTOR==="1",te=b.filter(ne=>ne._pinned),K=b.filter(ne=>!ne._compacted&&!ne._pinned);if(!N&&K.length>=6)try{let{compactMessages:ne}=Al(),k=await ne(K);if(k){let ve=b.filter(Re=>Re._compacted&&!Re._pinned),H=[...te,...ve,k.message],X=Tn(h,H,O),pe=Wt(X);if(pe+l<=c)return{messages:X,compressed:!0,compacted:!0,tokensRemoved:p-pe};b=H}}catch(ne){process.env.NEX_DEBUG&&console.error("[context-engine] LLM compacting failed:",ne.message)}let ie=Zp([...M,...O]),le=M.map((ne,k)=>({msg:ne,score:ne._pinned?1/0:Jp(ne,k,M.length,ie),tokens:Jn(ne)}));for(;le.length>0&&T>u;){let ne=-1;for(let k=0;k<le.length;k++)le[k].score!==1/0&&(ne===-1||le[k].score<le[ne].score)&&(ne=k);if(ne===-1)break;T-=le[ne].tokens,le.splice(ne,1)}return M=le.map(ne=>ne.msg),v=Tn(h,M,O),T=Wt(v),{messages:v,compressed:!0,compacted:!1,tokensRemoved:p-T}}function Tn(t,e,s){let n=[];return t&&n.push(t),n.push(...e,...s),n}function Xx(t,e){if(!t)return"";if(Vn(t)<=e)return t;let n=e*4,o=t.split(`
194
+ `)}`,_pinned:!0,_progressSnapshot:!0}}var Ds={msgCount:-1,lastMsgRef:null,result:null};function nk(){Ds={msgCount:-1,lastMsgRef:null,result:null},pt={msgCount:-1,lastMsgRef:null,toolCount:-1,result:null,messagesRef:null,messageTokens:0,systemTokens:0,conversationTokens:0,toolResultTokens:0}}async function sk(t,e,s={}){let n=t.length>0?t[t.length-1]:null;if(!s.force&&Ds.result&&t.length===Ds.msgCount&&n===Ds.lastMsgRef)return Ds.result;let o=s.threshold??rh(),r=s.safetyMargin??nh,i=s.keepRecent??sh,a=ui(),l=ci(e),c=Math.floor(a*(o-r)),u=c-l,d=Wt(t);if(d+l<=c){let se={messages:t,compressed:!1,compacted:!1,tokensRemoved:0};return Ds={msgCount:t.length,lastMsgRef:n,result:se},se}let p=d,m=null,g=0;t.length>0&&t[0].role==="system"&&(m=t[0],g=1);let _=Math.max(g,t.length-i),b=t.slice(g,_),A=t.slice(_),P=b.map(se=>js(se,"light")),v=En(m,P,A),E=Wt(v);if(E+l<=c)return{messages:v,compressed:!0,compacted:!1,tokensRemoved:p-E};if(P=b.map(se=>js(se,"medium")),v=En(m,P,A),E=Wt(v),E+l<=c)return{messages:v,compressed:!0,compacted:!1,tokensRemoved:p-E};if(P=b.map(se=>js(se,"aggressive")),v=En(m,P,A),E=Wt(v),E+l<=c)return{messages:v,compressed:!0,compacted:!1,tokensRemoved:p-E};let O=process.env.NEX_SKIP_COMPACTOR==="1",ne=b.filter(se=>se._pinned),J=b.filter(se=>!se._compacted&&!se._pinned);if(!O&&J.length>=6)try{let{compactMessages:se}=Il(),S=await se(J);if(S){let Ee=b.filter(Ce=>Ce._compacted&&!Ce._pinned),W=[...ne,...Ee,S.message],Z=En(m,W,A),he=Wt(Z);if(he+l<=c)return{messages:Z,compressed:!0,compacted:!0,tokensRemoved:p-he};b=W}}catch(se){process.env.NEX_DEBUG&&console.error("[context-engine] LLM compacting failed:",se.message)}let ie=lh([...P,...A]),ce=P.map((se,S)=>({msg:se,score:se._pinned?1/0:ah(se,S,P.length,ie),tokens:Vn(se)}));for(;ce.length>0&&E>u;){let se=-1;for(let S=0;S<ce.length;S++)ce[S].score!==1/0&&(se===-1||ce[S].score<ce[se].score)&&(se=S);if(se===-1)break;E-=ce[se].tokens,ce.splice(se,1)}return P=ce.map(se=>se.msg),v=En(m,P,A),E=Wt(v),{messages:v,compressed:!0,compacted:!1,tokensRemoved:p-E}}function En(t,e,s){let n=[];return t&&n.push(t),n.push(...e,...s),n}function ok(t,e){if(!t)return"";if(Xn(t)<=e)return t;let n=e*4,o=t.split(`
195
195
  `),r=Math.floor(n*.6),i=Math.floor(n*.4),a="",l=0;for(let p of o){if(a.length+p.length+1>r)break;a+=(a?`
196
- `:"")+p,l++}let c="",u=0;for(let p=o.length-1;p>=l;p--){let h=o[p]+(c?`
197
- `:"")+c;if(h.length>i)break;c=h,u++}let f=`
196
+ `:"")+p,l++}let c="",u=0;for(let p=o.length-1;p>=l;p--){let m=o[p]+(c?`
197
+ `:"")+c;if(m.length>i)break;c=m,u++}let f=`
198
198
 
199
199
  ... (${o.length-l-u} lines omitted, ${o.length} total) ...
200
200
 
201
- `;return a+f+c}var Vx=6;function Jx(t,e,s=!1){let n=ii(),o=ri(e),r=Math.floor(n*(s?.35:.5))-o,i=Wt(t),a=Math.floor(i*(s?.5:.8));r>a&&(r=a);let l=null,c=0;t.length>0&&t[0].role==="system"&&(l=t[0],c=1);let u=s?2:Vx,d=Math.max(c,t.length-u),f=t.slice(c,d),p=t.slice(d),h=f.map(T=>Is(T,"aggressive"));s&&(p=p.map(T=>Is(T,"aggressive")));let g=Tn(l,h,p),_=Wt(g);for(;h.length>0&&_>r;){let T=h.shift();_-=Jn(T)}s&&_>r&&(p=p.filter(N=>N.role==="user").slice(-1),g=Tn(l,[],p),_=Wt(g)),g=Tn(l,h,p);let b=t.filter(T=>T.role==="user"),O=T=>{let N=typeof T.content=="string"?T.content:"";return N.startsWith("[SYSTEM WARNING]")||N.startsWith("[SYSTEM:")||N.startsWith("BLOCKED:")},M=b.find(T=>!O(T)),v=[...b].reverse().find(T=>!O(T));if(M&&!g.find(T=>T===M)){let T=g.findIndex(te=>te.role==="system"),N=T>=0?T+1:0;g.splice(N,0,M)}return v&&v!==M&&!g.find(T=>T===v)&&g.push(v),{messages:g,tokensRemoved:i-Wt(g)}}Qp.exports={estimateTokens:Vn,estimateMessageTokens:Jn,estimateMessagesTokens:Wt,estimateDeltaTokens:Ux,estimateToolsTokens:ri,serializeMessage:Bx,getContextWindow:ii,getUsage:Wx,compressMessage:Is,compressToolResult:Vp,scoreMessageRelevance:Jp,extractActiveFiles:Zp,buildProgressSnapshot:Gx,fitToContext:Kx,forceCompress:Jx,truncateFileContent:Xx,invalidateTokenRatioCache:Fx,invalidateFitToContextCache:zx,getEffectiveCompressionThreshold:Xp,COMPRESSION_THRESHOLD:vo,TIER_COMPRESSION_THRESHOLDS:Kp,SAFETY_MARGIN:Gp,KEEP_RECENT:zp}});var Il=Z((t1,bh)=>{var{callStream:Zx,getActiveProviderName:li,getActiveModelId:eh,getConfiguredProviders:Qx,getProvider:th,getActiveProvider:nh,parseModelSpec:sh}=Ze(),{parseToolArgs:oh}=ao(),{filterToolsForModel:ek,getModelTier:ai}=_o(),{getModelBriefing:tk}=oi(),{trackUsage:rh,estimateTokens:ih}=Nr(),{MultiProgress:nk,C:e1}=Ke();function ah(t){return!t||typeof t!="string"?0:typeof ih=="function"?ih(t):Math.ceil(t.length/4)}var uh=15,sk=parseInt(process.env.NEX_MAX_PARALLEL||"5",10),lh=parseInt(process.env.NEX_MAX_CHAT_RETRIES||"3",10),dh=8,ok=2,ci=new Map,fh=600*1e3;function rk(t,e){let s=ci.get(t);return s&&s.agentId!==e&&Date.now()-s.timestamp<fh?!1:(ci.set(t,{agentId:e,timestamp:Date.now()}),!0)}function Eo(t){ci.delete(t)}function Ml(){ci.clear()}function Pl(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 ph(t){let e=Pl(t);return e==="rate_limit"||e==="server"||e==="network"||e==="timeout"}async function hh(t,e,s){let n;for(let o=0;o<=lh;o++)try{return await Zx(t,e,s)}catch(r){n=r;let i=Pl(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<lh&&ph(r)){let l=i==="rate_limit"?Math.min(2e3*Math.pow(2,o),15e3):Math.min(500*Math.pow(2,o),4e3);await new Promise(c=>setTimeout(c,l).unref());continue}throw r}throw n}var ch=new Set(["ask_user","task_list"]);function mh(t){return t>=2?new Set([...ch,"spawn_agents"]):ch}var ik=new Set(["write_file","edit_file","patch_file"]),gh={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:""}},ak=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,lk=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function yh(t){return lk.test(t)?"full":ak.test(t)?"essential":t.length>300?"full":"standard"}function wh(t){let e=Qx(),s=li(),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(ai(r.id,o.name)===t)return{provider:o.name,model:r.id};return null}var ck={essential:process.env.NEX_FAST_MODEL||null,standard:process.env.NEX_STANDARD_MODEL||null,full:process.env.NEX_HEAVY_MODEL||null};function Ll(t){if(t.model){let{provider:o,model:r}=sh(t.model),i=o?th(o):nh(),a=o||li();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let l=ai(r,a);return{provider:a,model:r,tier:l}}}let e=yh(t.task),s=ck[e];if(s){let{provider:o,model:r}=sh(s),i=o?th(o):nh(),a=o||li();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let l=ai(r,a);return{provider:a,model:r,tier:l}}}let n=wh(e);if(n){let o=ai(n.model,n.provider);return{provider:n.provider,model:n.model,tier:o}}return{provider:null,model:null,tier:null}}async function _h(t,e={},s=0){let n=s===0?uh:dh,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},l=new Set,c=new Map,u=t._systemPrompt||`You are a focused sub-agent. Complete this specific task efficiently.
201
+ `;return a+f+c}var rk=6;function ik(t,e,s=!1){let n=ui(),o=ci(e),r=Math.floor(n*(s?.35:.5))-o,i=Wt(t),a=Math.floor(i*(s?.5:.8));r>a&&(r=a);let l=null,c=0;t.length>0&&t[0].role==="system"&&(l=t[0],c=1);let u=s?2:rk,d=Math.max(c,t.length-u),f=t.slice(c,d),p=t.slice(d),m=f.map(E=>js(E,"aggressive"));s&&(p=p.map(E=>js(E,"aggressive")));let g=En(l,m,p),_=Wt(g);for(;m.length>0&&_>r;){let E=m.shift();_-=Vn(E)}s&&_>r&&(p=p.filter(O=>O.role==="user").slice(-1),g=En(l,[],p),_=Wt(g)),g=En(l,m,p);let b=t.filter(E=>E.role==="user"),A=E=>{let O=typeof E.content=="string"?E.content:"";return O.startsWith("[SYSTEM WARNING]")||O.startsWith("[SYSTEM:")||O.startsWith("BLOCKED:")},P=b.find(E=>!A(E)),v=[...b].reverse().find(E=>!A(E));if(P&&!g.find(E=>E===P)){let E=g.findIndex(ne=>ne.role==="system"),O=E>=0?E+1:0;g.splice(O,0,P)}return v&&v!==P&&!g.find(E=>E===v)&&g.push(v),{messages:g,tokensRemoved:i-Wt(g)}}ch.exports={estimateTokens:Xn,estimateMessageTokens:Vn,estimateMessagesTokens:Wt,estimateDeltaTokens:Jx,estimateToolsTokens:ci,serializeMessage:Vx,getContextWindow:ui,getUsage:Zx,compressMessage:js,compressToolResult:ih,scoreMessageRelevance:ah,extractActiveFiles:lh,buildProgressSnapshot:tk,fitToContext:sk,forceCompress:ik,truncateFileContent:ok,invalidateTokenRatioCache:Xx,invalidateFitToContextCache:nk,getEffectiveCompressionThreshold:rh,COMPRESSION_THRESHOLD:Co,TIER_COMPRESSION_THRESHOLDS:oh,SAFETY_MARGIN:nh,KEEP_RECENT:sh}});var Fs=Q((_1,uh)=>{var{fork:ak}=require("child_process"),lk=require("path"),ck=lk.join(__dirname,"background-worker.js"),Jn=new Map,qs=new Map;function uk(){return`bg-${Date.now()}-${Math.random().toString(36).slice(2,6)}`}function dk(t){let e=uk(),s=ak(ck,[],{silent:!0,env:process.env,cwd:process.cwd()});return s.send({jobId:e,agentDef:t}),s.on("message",n=>{n.type==="result"?ql(e,t,n.payload):n.type==="error"&&ql(e,t,{task:t.task,status:"failed",result:`Background agent error: ${n.error}`,toolsUsed:[],tokensUsed:{input:0,output:0}})}),s.on("exit",(n,o)=>{if(Jn.has(e)){let r=o?`killed (${o})`:`exit code ${n}`;ql(e,t,{task:t.task,status:"failed",result:`Background agent terminated unexpectedly: ${r}`,toolsUsed:[],tokensUsed:{input:0,output:0}})}}),Jn.set(e,{process:s,agentDef:t,startedAt:Date.now()}),e}function ql(t,e,s){Jn.delete(t),qs.set(t,{jobId:t,agentDef:e,result:s,finishedAt:Date.now()})}function fk(){if(qs.size===0)return[];let t=[...qs.values()];return qs.clear(),t}function pk(){return Jn.size>0||qs.size>0}function hk(){let t=Jn.size;return t===0?"":`${t} bg agent${t===1?"":"s"} running`}function mk(){for(let[t,e]of Jn){try{e.process.kill("SIGTERM")}catch{}Jn.delete(t)}qs.clear()}uh.exports={createJob:dk,getCompletedJobs:fk,getPendingJobSummary:hk,hasPendingOrCompletedJobs:pk,cancelAllJobs:mk}});var Wl=Q((b1,Oh)=>{var{callStream:gk,getActiveProviderName:fi,getActiveModelId:dh,getConfiguredProviders:yk,getProvider:fh,getActiveProvider:ph,parseModelSpec:hh}=Qe(),{parseToolArgs:mh}=fo(),{filterToolsForModel:wk,getModelTier:di}=ko(),{getModelBriefing:_k}=li(),{trackUsage:gh,estimateTokens:yh}=Ir(),{MultiProgress:$k,C:$1}=Ke();function wh(t){return!t||typeof t!="string"?0:typeof yh=="function"?yh(t):Math.ceil(t.length/4)}var bh=15,bk=parseInt(process.env.NEX_MAX_PARALLEL||"5",10),_h=parseInt(process.env.NEX_MAX_CHAT_RETRIES||"3",10),xh=8,xk=2,pi=new Map,kh=600*1e3;function kk(t,e){let s=pi.get(t);return s&&s.agentId!==e&&Date.now()-s.timestamp<kh?!1:(pi.set(t,{agentId:e,timestamp:Date.now()}),!0)}function Ao(t){pi.delete(t)}function Fl(){pi.clear()}function Bl(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 Sh(t){let e=Bl(t);return e==="rate_limit"||e==="server"||e==="network"||e==="timeout"}async function vh(t,e,s){let n;for(let o=0;o<=_h;o++)try{return await gk(t,e,s)}catch(r){n=r;let i=Bl(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<_h&&Sh(r)){let l=i==="rate_limit"?Math.min(2e3*Math.pow(2,o),15e3):Math.min(500*Math.pow(2,o),4e3);await new Promise(c=>setTimeout(c,l).unref());continue}throw r}throw n}var $h=new Set(["ask_user","task_list"]);function Eh(t){return t>=2?new Set([...$h,"spawn_agents"]):$h}var Sk=new Set(["write_file","edit_file","patch_file"]),Th={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:""}},vk=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,Ek=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function Rh(t){return Ek.test(t)?"full":vk.test(t)?"essential":t.length>300?"full":"standard"}function Ch(t){let e=yk(),s=fi(),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(di(r.id,o.name)===t)return{provider:o.name,model:r.id};return null}var Tk={essential:process.env.NEX_FAST_MODEL||null,standard:process.env.NEX_STANDARD_MODEL||null,full:process.env.NEX_HEAVY_MODEL||null};function hi(t){if(t.model){let{provider:o,model:r}=hh(t.model),i=o?fh(o):ph(),a=o||fi();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let l=di(r,a);return{provider:a,model:r,tier:l}}}let e=Rh(t.task),s=Tk[e];if(s){let{provider:o,model:r}=hh(s),i=o?fh(o):ph(),a=o||fi();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let l=di(r,a);return{provider:a,model:r,tier:l}}}let n=Ch(e);if(n){let o=di(n.model,n.provider);return{provider:n.provider,model:n.model,tier:o}}return{provider:null,model:null,tier:null}}async function Ah(t,e={},s=0){let n=s===0?bh:xh,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},l=new Set,c=new Map,u=t._systemPrompt||`You are a focused sub-agent. Complete this specific task efficiently.
202
202
 
203
203
  TASK: ${t.task}
204
204
  ${t.context?`
@@ -220,25 +220,30 @@ TOOL STRATEGY:
220
220
  ERROR RECOVERY:
221
221
  - If edit_file fails with "old_text not found": read the file again, compare, and retry with exact text.
222
222
  - If bash fails: read the error, fix the root cause, then retry.
223
- - After 2 failed attempts at the same operation, summarize the issue and stop.`,d=t.type&&gh[t.type],f=d&&d.systemSuffix?`
223
+ - After 2 failed attempts at the same operation, summarize the issue and stop.`,d=t.type&&Th[t.type],f=d&&d.systemSuffix?`
224
224
 
225
- ${d.systemSuffix}`:"",p=Ll(t),h=p.provider,g=p.model,_=p.tier,b=tk(g||eh()),M=[{role:"system",content:(b?`## Model Briefing
225
+ ${d.systemSuffix}`:"",p=hi(t),m=p.provider,g=p.model,_=p.tier,b=_k(g||dh()),P=[{role:"system",content:(b?`## Model Briefing
226
226
  ${b}
227
227
 
228
228
  ---
229
229
 
230
- `:"")+u+f}];M.push({role:"user",content:t.task});let{TOOL_DEFINITIONS:v,executeTool:T}=Rs(),N=mh(s),te=ek(v.filter(le=>!N.has(le.function.name)),_);if(d&&d.allowedTools&&(te=te.filter(le=>d.allowedTools.has(le.function.name))),g&&!t._skipLog){let le=_?` (${_})`:"";process.stderr.write(` [sub-agent: ${h}:${g}${le}]
231
- `)}let K={};h&&(K.provider=h),g&&(K.model=g);let ie=new Set;try{for(let ne=0;ne<o;ne++){let k=await hh(M,te,K);if(!k||typeof k!="object")throw new Error("Empty or invalid response from provider");{let ke=h||li(),$e=g||eh();if(k.usage){let $=k.usage.prompt_tokens||0,I=k.usage.completion_tokens||0;a.input+=$,a.output+=I,rh(ke,$e,$,I)}else{let $=k.content||"",I=M.map(E=>typeof E.content=="string"?E.content:Array.isArray(E.content)?E.content.map(S=>typeof S=="string"?S:S.text||"").join(""):"").join(" "),R=ah(I),W=ah($);a.input+=R,a.output+=W,a._estimated=!0,rh(ke,$e,R,W)}}let ve=k.content||"",H=k.tool_calls,X={role:"assistant",content:ve||""};if(H&&H.length>0&&(X.tool_calls=H),M.push(X),!H||H.length===0){for(let ke of l)Eo(ke);return{task:t.task,status:"done",result:ve||"(no response)",toolsUsed:i,tokensUsed:a,modelSpec:h&&g?`${h}:${g}`:null}}let pe=new Set,Re=H.map(ke=>{let $e=ke.function.name,$=oh(ke.function.arguments),I=ke.id||`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!$)return Promise.resolve({role:"tool",content:`ERROR: Malformed tool arguments for ${$e}`,tool_call_id:I});if(["edit_file","patch_file"].includes($e)&&$.path){if(ie.has($.path)||pe.has($.path))return Promise.resolve({role:"tool",content:`BLOCKED: "${$.path}" was already edited \u2014 re-read the changed section first (read_file with line_start/line_end) before making another edit. The file content has changed and your previous read is stale.`,tool_call_id:I});pe.add($.path)}let R=null;if(ik.has($e)&&$.path){let E=require("path"),S=E.isAbsolute($.path)?$.path:E.resolve(process.cwd(),$.path);if(t._readOnlyFiles&&t._readOnlyFiles.length>0){let oe=E.relative(process.cwd(),S);if(t._readOnlyFiles.some(ge=>oe===ge||oe.startsWith(ge+"/")||S===ge||S.startsWith(ge+"/")))return Promise.resolve({role:"tool",content:`ERROR: File '${$.path}' is owned by another agent and is READ ONLY. Write to your own scope files instead.`,tool_call_id:I})}if(l.has(S)||!rk(S,r))return Promise.resolve({role:"tool",content:`ERROR: File '${$.path}' is locked by another operation. Try a different approach or skip this file.`,tool_call_id:I});l.add(S),R=S}return i.push($e),e.onUpdate&&e.onUpdate({type:"tool_call",tool:$e,agentId:r}),($e==="spawn_agents"?$h($,s+1):T($e,$,{autoConfirm:!0,silent:!0})).then(E=>{R&&(Eo(R),l.delete(R));let S=String(E??"");return $&&$.path&&(["edit_file","patch_file","write_file"].includes($e)&&S.startsWith("Edited:")?ie.add($.path):$e==="read_file"&&!S.startsWith("ERROR")&&ie.delete($.path)),{role:"tool",content:S.length>2e4?S.substring(0,2e4)+`
232
- ...(truncated)`:S,tool_call_id:I}}).catch(E=>(R&&(Eo(R),l.delete(R)),{role:"tool",content:`ERROR: ${E.message}`,tool_call_id:I}))}),Ue=await Promise.all(Re);if(M.push(...Ue),ne>=7&&M.length>12)try{let{compressMessage:ke}=en(),$e=M.length-6;for(let $=1;$<$e;$++)M[$]._subAgentCompressed||(M[$]={...ke(M[$],"light"),_subAgentCompressed:!0})}catch{}for(let ke=0;ke<H.length;ke++){let $e=H[ke];if($e.function.name==="bash_exec"){let $=oh($e.function.arguments);if((Ue[ke]?.content||"").startsWith("ERROR")&&$&&$.command){let R=$.command.replace(/\s+/g," ").trim().slice(0,100);c.set(R,(c.get(R)||0)+1)}}}e.onUpdate&&e.onUpdate(`step ${ne+1}/${o}`)}for(let ne of l)Eo(ne);let le=[...c.entries()].filter(([,ne])=>ne>=3).sort((ne,k)=>k[1]-ne[1]).slice(0,3).map(([ne,k])=>`"${ne}" (failed ${k}\xD7)`);return{task:t.task,status:"truncated",abortReason:"iteration_limit",repeatedFailures:le,result:M[M.length-1]?.content||"(max iterations reached)",toolsUsed:i,tokensUsed:a,modelSpec:h&&g?`${h}:${g}`:null}}catch(le){for(let ne of l)Eo(ne);return{task:t.task,status:"failed",result:`Error: ${le.message}`,toolsUsed:i,tokensUsed:a,modelSpec:h&&g?`${h}:${g}`:null}}}async function $h(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?sk:ok,n=e===0?uh:dh,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=>Ll(u)),l=o.map((u,d)=>{let f=a[d],p=f.model?` [${f.model}]`:"",h=u.task.substring(0,i-p.length);return`${r}Agent ${d+1}${p}: ${h}${u.task.length>h.length?"...":""}`}),c=new nk(l);c.start();try{let u=o.map((g,_)=>{let b=a[_],O=Math.min(g.max_iterations||n,n),M=b.model?{...g,model:`${b.provider}:${b.model}`,_skipLog:!0,max_iterations:O}:{...g,_skipLog:!0,max_iterations:O};return _h(M,{onUpdate:()=>{}},e).then(v=>(c.update(_,v.status==="failed"?"error":"done"),v)).catch(v=>(c.update(_,"error"),{task:g.task,status:"failed",result:`Error: ${v.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}))}),d=await Promise.all(u);c.stop(),Ml();let f=["Sub-agent results:",""],p=0,h=0;for(let g=0;g<d.length;g++){let _=d[g],b=_.status==="done"?"\u2713":_.status==="truncated"?"\u26A0":"\u2717",O=_.modelSpec?` [${_.modelSpec}]`:"";f.push(`${b} Agent ${g+1}${O}: ${_.task}`),f.push(` Status: ${_.status}`),f.push(` Tools used: ${_.toolsUsed.length>0?_.toolsUsed.join(", "):"none"}`),f.push(` Result: ${_.result}`),_.repeatedFailures&&_.repeatedFailures.length>0&&f.push(` Repeated failures: ${_.repeatedFailures.join("; ")}`),f.push(""),p+=_.tokensUsed.input,h+=_.tokensUsed.output}return f.push(`Total sub-agent tokens: ${p} input + ${h} output`),f.join(`
233
- `)}catch(u){return c.stop(),Ml(),`ERROR: Sub-agent execution failed: ${u.message}`}}bh.exports={runSubAgent:_h,executeSpawnAgents:$h,clearAllLocks:Ml,classifyTask:yh,pickModelForTier:wh,resolveSubAgentModel:Ll,classifyError:Pl,isRetryableError:ph,callWithRetry:hh,getExcludedTools:mh,LOCK_TIMEOUT_MS:fh,SUB_AGENT_TYPES:gh}});var Hl=Z((n1,Lh)=>{var qe=require("fs"),pn=require("path"),{atomicWrite:xh,withFileLockSync:kh}=Bn(),uk=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 js(){let t=pn.join(process.cwd(),".nex","brain");return qe.existsSync(t)||qe.mkdirSync(t,{recursive:!0}),t}function di(){return pn.join(js(),".brain-index.json")}function ql(){return pn.join(js(),".embeddings.json")}function To(){let t=pn.join(process.cwd(),".nex","brain");if(!qe.existsSync(t))return[];try{return qe.readdirSync(t).filter(e=>e.endsWith(".md")&&!e.startsWith(".")).map(e=>{let s=pn.join(t,e),n=qe.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 Ro(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(`
234
- `);for(let r of o){let i=r.match(/^(\w+):\s*(.+)$/);if(!i)continue;let a=i[1].trim(),l=i[2].trim();l.startsWith("[")&&l.endsWith("]")?e[a]=l.slice(1,-1).split(",").map(c=>c.trim()).filter(Boolean):e[a]=l}s=n[2]}return{frontmatter:e,body:s}}function Sh(t){let e=pn.join(js(),`${t}.md`);if(!qe.existsSync(e))return{name:t,content:"",body:"",frontmatter:{}};let s=qe.readFileSync(e,"utf-8"),{frontmatter:n,body:o}=Ro(s);return{name:t,content:s,body:o,frontmatter:n}}function dk(t,e){let s=pn.join(js(),`${t}.md`);xh(s,e),hk(t,e),fk()}function fk(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return;let t=ql();qe.existsSync(t)&&setImmediate(async()=>{try{await Oh()}catch{}})}function pk(t){let e=pn.join(js(),`${t}.md`);return qe.existsSync(e)?(qe.unlinkSync(e),mk(t),!0):!1}function ui(t){return t.toLowerCase().replace(/[^a-z0-9äöüß\s-]/g," ").split(/[\s-]+/).filter(e=>e.length>2&&!uk.has(e))}function Fl(t){let e={},{frontmatter:s,body:n}=Ro(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(`
235
- `);for(let i of r)if(i.startsWith("#")){let a=i.replace(/^#+\s*/,"");for(let l of ui(a))e[l]=(e[l]||0)+3}for(let i of ui(n||t))e[i]=(e[i]||0)+1;return e}function Bl(){let t=di();if(!qe.existsSync(t))return{documents:{}};try{return JSON.parse(qe.readFileSync(t,"utf-8"))}catch{return{documents:{}}}}function Ul(t){xh(di(),JSON.stringify(t,null,2))}function hk(t,e){kh(di(),()=>{let s=Bl(),{frontmatter:n}=Ro(e),o=Array.isArray(n.tags)?n.tags:[];s.documents[t]={keywords:Fl(e),tags:o,modified:new Date().toISOString()},Ul(s)})}function mk(t){kh(di(),()=>{let e=Bl();delete e.documents[t],Ul(e)})}function jl(){let t=To(),e={documents:{}};for(let s of t){let n=qe.readFileSync(s.path,"utf-8"),{frontmatter:o}=Ro(n),r=Array.isArray(o.tags)?o.tags:[];e.documents[s.name]={keywords:Fl(n),tags:r,modified:s.modified.toISOString()}}return Ul(e),e}function vh(){let t=Bl(),e=To();for(let s of e){let n=t.documents[s.name];if(!n||new Date(n.modified)<s.modified)return jl()}for(let s of Object.keys(t.documents))if(!e.some(n=>n.name===s))return jl();return t}function Eh(t,e={}){let{topK:s=3,minScore:n=.1}=e,o=ui(t);if(o.length===0)return[];let r=vh(),i=[];for(let[a,l]of Object.entries(r.documents)){let c=0;for(let u of o){l.keywords[u]&&(c+=l.keywords[u]);for(let[d,f]of Object.entries(l.keywords))d!==u&&d.length>3&&u.length>3&&(d.includes(u)||u.includes(d))&&(c+=f*.3)}c>=n&&i.push({name:a,score:c})}return i.sort((a,l)=>l.score-a.score),i.slice(0,s)}var Th=process.env.NEX_EMBED_MODEL||"nomic-embed-text",Dl=400,gk=50;async function Rh(){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,l)=>{let c=o.get(n.toString(),{timeout:2e3},u=>{let d="";u.on("data",f=>d+=f),u.on("end",()=>{try{a(JSON.parse(d))}catch{l(new Error("bad json"))}})});c.on("error",l),c.on("timeout",()=>{c.destroy(),l(new Error("timeout"))})})).models||[]).map(a=>a.name).some(a=>a.startsWith(Th.split(":")[0]))}catch{return!1}}async function Wl(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:Th,prompt:t});return new Promise((a,l)=>{let c=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){l(f)}})});c.on("error",l),c.on("timeout",()=>{c.destroy(),l(new Error("embedding timeout"))}),c.write(i),c.end()})}function Ch(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 Ah(t){let e=t.split(/\s+/),s=[],n=0;for(;n<e.length;){let o=e.slice(n,n+Dl).join(" ");if(s.push({text:o,offset:n}),n+Dl>=e.length)break;n+=Dl-gk}return s}async function Oh(){let t=To(),e={documents:{}},s=ql();if(qe.existsSync(s))try{e=JSON.parse(qe.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=qe.readFileSync(n.path,"utf-8"),i=Ah(r),a=[];for(let l of i){let c=await Wl(l.text);a.push({text:l.text,embedding:c,offset:l.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 qe.writeFileSync(s,JSON.stringify(e),"utf-8"),e}async function Nh(t,e={}){let{topK:s=3,minSimilarity:n=.3}=e,o=ql();if(!qe.existsSync(o))return[];let r;try{r=JSON.parse(qe.readFileSync(o,"utf-8"))}catch{return[]}let i=await Wl(t),a=[];for(let[l,c]of Object.entries(r.documents||{})){let u=0,d="";for(let f of c.chunks||[]){let p=Ch(i,f.embedding);p>u&&(u=p,d=f.text)}u>=n&&a.push({name:l,score:u,bestChunk:d})}return a.sort((l,c)=>c.score-l.score),a.slice(0,s)}function Mh(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 Ph(t,e={}){let{topK:s=3,minScore:n=.1}=e,o=Eh(t,{topK:s,minScore:n}),r=o;if(process.env.NEX_BRAIN_EMBEDDINGS!=="false")try{if(await Rh()){let a=await Nh(t,{topK:s});r=Mh(o,a,{topK:s})}}catch{}return r.map(i=>{let a=Sh(i.name),l=(a.body||a.content||"").slice(0,300).replace(/\n+/g," ")+"...";return{name:i.name,score:i.score,content:a.content,excerpt:l}})}var Ds={queryKey:null,result:null,ts:0},yk=3e5;async function wk(t){if(!t||!t.trim())return"";let e=pn.join(process.cwd(),".nex","brain");if(!qe.existsSync(e)||To().length===0)return"";let n=t.trim().toLowerCase().slice(0,200);if(Ds.result!==null&&Ds.queryKey===n&&Date.now()-Ds.ts<yk)return Ds.result;let o;try{o=await Ph(t,{topK:3})}catch{return""}if(!o||o.length===0)return"";let r;try{r=en().estimateTokens}catch{r=u=>Math.ceil(u.length/4)}let i=25e3,a=[],l=0;for(let u of o){let d=u.content||"",f=r(d);if(l+f>i){let h=i-l;if(h<100)break;let g=h/f;d=d.slice(0,Math.floor(d.length*g))+`
230
+ `:"")+u+f}];P.push({role:"user",content:t.task});let{TOOL_DEFINITIONS:v,executeTool:E}=As(),O=Eh(s),ne=wk(v.filter(ce=>!O.has(ce.function.name)),_);if(d&&d.allowedTools&&(ne=ne.filter(ce=>d.allowedTools.has(ce.function.name))),g&&!t._skipLog){let ce=_?` (${_})`:"";process.stderr.write(` [sub-agent: ${m}:${g}${ce}]
231
+ `)}let J={};m&&(J.provider=m),g&&(J.model=g);let ie=new Set;try{for(let se=0;se<o;se++){let S=await vh(P,ne,J);if(!S||typeof S!="object")throw new Error("Empty or invalid response from provider");{let xe=m||fi(),be=g||dh();if(S.usage){let $=S.usage.prompt_tokens||0,I=S.usage.completion_tokens||0;a.input+=$,a.output+=I,gh(xe,be,$,I)}else{let $=S.content||"",I=P.map(q=>typeof q.content=="string"?q.content:Array.isArray(q.content)?q.content.map(x=>typeof x=="string"?x:x.text||"").join(""):"").join(" "),H=wh(I),N=wh($);a.input+=H,a.output+=N,a._estimated=!0,gh(xe,be,H,N)}}let Ee=S.content||"",W=S.tool_calls,Z={role:"assistant",content:Ee||""};if(W&&W.length>0&&(Z.tool_calls=W),P.push(Z),!W||W.length===0){for(let xe of l)Ao(xe);return{task:t.task,status:"done",result:Ee||"(no response)",toolsUsed:i,tokensUsed:a,modelSpec:m&&g?`${m}:${g}`:null}}let he=new Set,Ce=W.map(xe=>{let be=xe.function.name,$=mh(xe.function.arguments),I=xe.id||`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!$)return Promise.resolve({role:"tool",content:`ERROR: Malformed tool arguments for ${be}`,tool_call_id:I});if(["edit_file","patch_file"].includes(be)&&$.path){if(ie.has($.path)||he.has($.path))return Promise.resolve({role:"tool",content:`BLOCKED: "${$.path}" was already edited \u2014 re-read the changed section first (read_file with line_start/line_end) before making another edit. The file content has changed and your previous read is stale.`,tool_call_id:I});he.add($.path)}let H=null;if(Sk.has(be)&&$.path){let q=require("path"),x=q.isAbsolute($.path)?$.path:q.resolve(process.cwd(),$.path);if(t._readOnlyFiles&&t._readOnlyFiles.length>0){let Y=q.relative(process.cwd(),x);if(t._readOnlyFiles.some(pe=>Y===pe||Y.startsWith(pe+"/")||x===pe||x.startsWith(pe+"/")))return Promise.resolve({role:"tool",content:`ERROR: File '${$.path}' is owned by another agent and is READ ONLY. Write to your own scope files instead.`,tool_call_id:I})}if(l.has(x)||!kk(x,r))return Promise.resolve({role:"tool",content:`ERROR: File '${$.path}' is locked by another operation. Try a different approach or skip this file.`,tool_call_id:I});l.add(x),H=x}return i.push(be),e.onUpdate&&e.onUpdate({type:"tool_call",tool:be,agentId:r}),(be==="spawn_agents"?Ul($,s+1):E(be,$,{autoConfirm:!0,silent:!0})).then(q=>{H&&(Ao(H),l.delete(H));let x=String(q??"");return $&&$.path&&(["edit_file","patch_file","write_file"].includes(be)&&x.startsWith("Edited:")?ie.add($.path):be==="read_file"&&!x.startsWith("ERROR")&&ie.delete($.path)),{role:"tool",content:x.length>2e4?x.substring(0,2e4)+`
232
+ ...(truncated)`:x,tool_call_id:I}}).catch(q=>(H&&(Ao(H),l.delete(H)),{role:"tool",content:`ERROR: ${q.message}`,tool_call_id:I}))}),We=await Promise.all(Ce);if(P.push(...We),se>=7&&P.length>12)try{let{compressMessage:xe}=en(),be=P.length-6;for(let $=1;$<be;$++)P[$]._subAgentCompressed||(P[$]={...xe(P[$],"light"),_subAgentCompressed:!0})}catch{}for(let xe=0;xe<W.length;xe++){let be=W[xe];if(be.function.name==="bash_exec"){let $=mh(be.function.arguments);if((We[xe]?.content||"").startsWith("ERROR")&&$&&$.command){let H=$.command.replace(/\s+/g," ").trim().slice(0,100);c.set(H,(c.get(H)||0)+1)}}}e.onUpdate&&e.onUpdate(`step ${se+1}/${o}`)}for(let se of l)Ao(se);let ce=[...c.entries()].filter(([,se])=>se>=3).sort((se,S)=>S[1]-se[1]).slice(0,3).map(([se,S])=>`"${se}" (failed ${S}\xD7)`);return{task:t.task,status:"truncated",abortReason:"iteration_limit",repeatedFailures:ce,result:P[P.length-1]?.content||"(max iterations reached)",toolsUsed:i,tokensUsed:a,modelSpec:m&&g?`${m}:${g}`:null}}catch(ce){for(let se of l)Ao(se);return{task:t.task,status:"failed",result:`Error: ${ce.message}`,toolsUsed:i,tokensUsed:a,modelSpec:m&&g?`${m}:${g}`:null}}}async function Ul(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?bk:xk,n=e===0?bh:xh,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=>hi(u)),l=o.map((u,d)=>{let f=a[d],p=f.model?` [${f.model}]`:"",m=u.task.substring(0,i-p.length);return`${r}Agent ${d+1}${p}: ${m}${u.task.length>m.length?"...":""}`}),c=new $k(l);c.start();try{let u=o.map((g,_)=>{let b=a[_],A=Math.min(g.max_iterations||n,n),P=b.model?{...g,model:`${b.provider}:${b.model}`,_skipLog:!0,max_iterations:A}:{...g,_skipLog:!0,max_iterations:A};return Ah(P,{onUpdate:()=>{}},e).then(v=>(c.update(_,v.status==="failed"?"error":"done"),v)).catch(v=>(c.update(_,"error"),{task:g.task,status:"failed",result:`Error: ${v.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}))}),d=await Promise.all(u);c.stop(),Fl();let f=["Sub-agent results:",""],p=0,m=0;for(let g=0;g<d.length;g++){let _=d[g],b=_.status==="done"?"\u2713":_.status==="truncated"?"\u26A0":"\u2717",A=_.modelSpec?` [${_.modelSpec}]`:"";f.push(`${b} Agent ${g+1}${A}: ${_.task}`),f.push(` Status: ${_.status}`),f.push(` Tools used: ${_.toolsUsed.length>0?_.toolsUsed.join(", "):"none"}`),f.push(` Result: ${_.result}`),_.repeatedFailures&&_.repeatedFailures.length>0&&f.push(` Repeated failures: ${_.repeatedFailures.join("; ")}`),f.push(""),p+=_.tokensUsed.input,m+=_.tokensUsed.output}return f.push(`Total sub-agent tokens: ${p} input + ${m} output`),f.join(`
233
+ `)}catch(u){return c.stop(),Fl(),`ERROR: Sub-agent execution failed: ${u.message}`}}async function Rk(t){let{createJob:e}=Fs(),s=(t.agents||[]).filter(i=>i.background),n=(t.agents||[]).filter(i=>!i.background),o=s.map(i=>{let a=hi(i),l=a.model?{...i,model:`${a.provider}:${a.model}`,_skipLog:!0}:{...i,_skipLog:!0};return e(l)}),r=[];if(o.length>0&&r.push(`Background agents started: [${o.join(", ")}]
234
+ `+s.map((i,a)=>` ${o[a]}: ${i.task}`).join(`
235
+ `)+`
236
+ Results will be injected into the conversation when each agent completes.`),n.length>0){let i=await Ul({agents:n});r.push(i)}return r.join(`
237
+
238
+ `)||"No agents specified."}Oh.exports={runSubAgent:Ah,executeSpawnAgents:Ul,executeSpawnAgentsBackground:Rk,clearAllLocks:Fl,classifyTask:Rh,pickModelForTier:Ch,resolveSubAgentModel:hi,classifyError:Bl,isRetryableError:Sh,callWithRetry:vh,getExcludedTools:Eh,LOCK_TIMEOUT_MS:kh,SUB_AGENT_TYPES:Th}});var Jl=Q((x1,Yh)=>{var Fe=require("fs"),pn=require("path"),{atomicWrite:Nh,withFileLockSync:Mh}=Fn(),Ck=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 Us(){let t=pn.join(process.cwd(),".nex","brain");return Fe.existsSync(t)||Fe.mkdirSync(t,{recursive:!0}),t}function gi(){return pn.join(Us(),".brain-index.json")}function Gl(){return pn.join(Us(),".embeddings.json")}function Oo(){let t=pn.join(process.cwd(),".nex","brain");if(!Fe.existsSync(t))return[];try{return Fe.readdirSync(t).filter(e=>e.endsWith(".md")&&!e.startsWith(".")).map(e=>{let s=pn.join(t,e),n=Fe.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 No(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(`
239
+ `);for(let r of o){let i=r.match(/^(\w+):\s*(.+)$/);if(!i)continue;let a=i[1].trim(),l=i[2].trim();l.startsWith("[")&&l.endsWith("]")?e[a]=l.slice(1,-1).split(",").map(c=>c.trim()).filter(Boolean):e[a]=l}s=n[2]}return{frontmatter:e,body:s}}function Ph(t){let e=pn.join(Us(),`${t}.md`);if(!Fe.existsSync(e))return{name:t,content:"",body:"",frontmatter:{}};let s=Fe.readFileSync(e,"utf-8"),{frontmatter:n,body:o}=No(s);return{name:t,content:s,body:o,frontmatter:n}}function Ak(t,e){let s=pn.join(Us(),`${t}.md`);Nh(s,e),Mk(t,e),Ok()}function Ok(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return;let t=Gl();Fe.existsSync(t)&&setImmediate(async()=>{try{await Bh()}catch{}})}function Nk(t){let e=pn.join(Us(),`${t}.md`);return Fe.existsSync(e)?(Fe.unlinkSync(e),Pk(t),!0):!1}function mi(t){return t.toLowerCase().replace(/[^a-z0-9äöüß\s-]/g," ").split(/[\s-]+/).filter(e=>e.length>2&&!Ck.has(e))}function zl(t){let e={},{frontmatter:s,body:n}=No(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(`
240
+ `);for(let i of r)if(i.startsWith("#")){let a=i.replace(/^#+\s*/,"");for(let l of mi(a))e[l]=(e[l]||0)+3}for(let i of mi(n||t))e[i]=(e[i]||0)+1;return e}function Kl(){let t=gi();if(!Fe.existsSync(t))return{documents:{}};try{return JSON.parse(Fe.readFileSync(t,"utf-8"))}catch{return{documents:{}}}}function Xl(t){Nh(gi(),JSON.stringify(t,null,2))}function Mk(t,e){Mh(gi(),()=>{let s=Kl(),{frontmatter:n}=No(e),o=Array.isArray(n.tags)?n.tags:[];s.documents[t]={keywords:zl(e),tags:o,modified:new Date().toISOString()},Xl(s)})}function Pk(t){Mh(gi(),()=>{let e=Kl();delete e.documents[t],Xl(e)})}function Yl(){let t=Oo(),e={documents:{}};for(let s of t){let n=Fe.readFileSync(s.path,"utf-8"),{frontmatter:o}=No(n),r=Array.isArray(o.tags)?o.tags:[];e.documents[s.name]={keywords:zl(n),tags:r,modified:s.modified.toISOString()}}return Xl(e),e}function Lh(){let t=Kl(),e=Oo();for(let s of e){let n=t.documents[s.name];if(!n||new Date(n.modified)<s.modified)return Yl()}for(let s of Object.keys(t.documents))if(!e.some(n=>n.name===s))return Yl();return t}function Ih(t,e={}){let{topK:s=3,minScore:n=.1}=e,o=mi(t);if(o.length===0)return[];let r=Lh(),i=[];for(let[a,l]of Object.entries(r.documents)){let c=0;for(let u of o){l.keywords[u]&&(c+=l.keywords[u]);for(let[d,f]of Object.entries(l.keywords))d!==u&&d.length>3&&u.length>3&&(d.includes(u)||u.includes(d))&&(c+=f*.3)}c>=n&&i.push({name:a,score:c})}return i.sort((a,l)=>l.score-a.score),i.slice(0,s)}var Dh=process.env.NEX_EMBED_MODEL||"nomic-embed-text",Hl=400,Lk=50;async function jh(){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,l)=>{let c=o.get(n.toString(),{timeout:2e3},u=>{let d="";u.on("data",f=>d+=f),u.on("end",()=>{try{a(JSON.parse(d))}catch{l(new Error("bad json"))}})});c.on("error",l),c.on("timeout",()=>{c.destroy(),l(new Error("timeout"))})})).models||[]).map(a=>a.name).some(a=>a.startsWith(Dh.split(":")[0]))}catch{return!1}}async function Vl(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:Dh,prompt:t});return new Promise((a,l)=>{let c=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){l(f)}})});c.on("error",l),c.on("timeout",()=>{c.destroy(),l(new Error("embedding timeout"))}),c.write(i),c.end()})}function qh(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 Fh(t){let e=t.split(/\s+/),s=[],n=0;for(;n<e.length;){let o=e.slice(n,n+Hl).join(" ");if(s.push({text:o,offset:n}),n+Hl>=e.length)break;n+=Hl-Lk}return s}async function Bh(){let t=Oo(),e={documents:{}},s=Gl();if(Fe.existsSync(s))try{e=JSON.parse(Fe.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=Fe.readFileSync(n.path,"utf-8"),i=Fh(r),a=[];for(let l of i){let c=await Vl(l.text);a.push({text:l.text,embedding:c,offset:l.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 Fe.writeFileSync(s,JSON.stringify(e),"utf-8"),e}async function Uh(t,e={}){let{topK:s=3,minSimilarity:n=.3}=e,o=Gl();if(!Fe.existsSync(o))return[];let r;try{r=JSON.parse(Fe.readFileSync(o,"utf-8"))}catch{return[]}let i=await Vl(t),a=[];for(let[l,c]of Object.entries(r.documents||{})){let u=0,d="";for(let f of c.chunks||[]){let p=qh(i,f.embedding);p>u&&(u=p,d=f.text)}u>=n&&a.push({name:l,score:u,bestChunk:d})}return a.sort((l,c)=>c.score-l.score),a.slice(0,s)}function Wh(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 Hh(t,e={}){let{topK:s=3,minScore:n=.1}=e,o=Ih(t,{topK:s,minScore:n}),r=o;if(process.env.NEX_BRAIN_EMBEDDINGS!=="false")try{if(await jh()){let a=await Uh(t,{topK:s});r=Wh(o,a,{topK:s})}}catch{}return r.map(i=>{let a=Ph(i.name),l=(a.body||a.content||"").slice(0,300).replace(/\n+/g," ")+"...";return{name:i.name,score:i.score,content:a.content,excerpt:l}})}var Bs={queryKey:null,result:null,ts:0},Ik=3e5;async function Dk(t){if(!t||!t.trim())return"";let e=pn.join(process.cwd(),".nex","brain");if(!Fe.existsSync(e)||Oo().length===0)return"";let n=t.trim().toLowerCase().slice(0,200);if(Bs.result!==null&&Bs.queryKey===n&&Date.now()-Bs.ts<Ik)return Bs.result;let o;try{o=await Hh(t,{topK:3})}catch{return""}if(!o||o.length===0)return"";let r;try{r=en().estimateTokens}catch{r=u=>Math.ceil(u.length/4)}let i=25e3,a=[],l=0;for(let u of o){let d=u.content||"",f=r(d);if(l+f>i){let m=i-l;if(m<100)break;let g=m/f;d=d.slice(0,Math.floor(d.length*g))+`
236
241
  ...(truncated)`}let p=typeof u.score=="number"?u.score.toFixed(2):String(u.score);if(a.push(`--- ${u.name} (relevance: ${p}) ---
237
- ${d}`),l+=r(d),l>=i)break}if(a.length===0)return Ds={queryKey:n,result:"",ts:Date.now()},"";let c=`KNOWLEDGE BASE (auto-selected):
242
+ ${d}`),l+=r(d),l>=i)break}if(a.length===0)return Bs={queryKey:n,result:"",ts:Date.now()},"";let c=`KNOWLEDGE BASE (auto-selected):
238
243
 
239
244
  ${a.join(`
240
245
 
241
- `)}`;return Ds={queryKey:n,result:c,ts:Date.now()},c}Lh.exports={getBrainDir:js,listDocuments:To,readDocument:Sh,writeDocument:dk,removeDocument:pk,buildIndex:jl,getIndex:vh,query:Ph,getBrainContext:wk,isEmbeddingAvailable:Rh,generateEmbedding:Wl,buildEmbeddingIndex:Oh,semanticQuery:Nh,cosineSimilarity:Ch,_keywordQuery:Eh,_extractKeywords:Fl,_chunkText:Ah,parseFrontmatter:Ro,tokenize:ui,_fuseResults:Mh}});var Oo=Z((s1,zh)=>{var Ie=require("fs"),kt=require("path"),_k=require("os"),{atomicWrite:fi,withFileLockSync:Ih}=Bn(),Co=["user","feedback","project","reference"],$k=50;function Zn(){return kt.join(process.cwd(),".nex","memory")}function qs(){return kt.join(Zn(),"memory.json")}function Dh(){return kt.join(Zn(),"MEMORY.md")}function bk(){return kt.join(process.cwd(),"NEX.md")}function jh(){return kt.join(_k.homedir(),".nex","NEX.md")}function pi(){let t=Zn();Ie.existsSync(t)||Ie.mkdirSync(t,{recursive:!0})}function qh(t){let e=kt.join(Zn(),t);return Ie.existsSync(e)||Ie.mkdirSync(e,{recursive:!0}),e}function Ao(){let t=qs();if(!Ie.existsSync(t))return{};try{return JSON.parse(Ie.readFileSync(t,"utf-8"))}catch{return{}}}function Fh(t){pi(),fi(qs(),JSON.stringify(t,null,2))}function Bh(){let t=qs();if(!Ie.existsSync(t))return;let e=Ao(),s=Object.keys(e);if(s.length===0){try{Ie.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=qh("project"),l=kt.join(a,`${i}.md`),c=r.split(`
246
+ `)}`;return Bs={queryKey:n,result:c,ts:Date.now()},c}Yh.exports={getBrainDir:Us,listDocuments:Oo,readDocument:Ph,writeDocument:Ak,removeDocument:Nk,buildIndex:Yl,getIndex:Lh,query:Hh,getBrainContext:Dk,isEmbeddingAvailable:jh,generateEmbedding:Vl,buildEmbeddingIndex:Bh,semanticQuery:Uh,cosineSimilarity:qh,_keywordQuery:Ih,_extractKeywords:zl,_chunkText:Fh,parseFrontmatter:No,tokenize:mi,_fuseResults:Wh}});var Lo=Q((k1,sm)=>{var Ie=require("fs"),kt=require("path"),jk=require("os"),{atomicWrite:yi,withFileLockSync:Gh}=Fn(),Mo=["user","feedback","project","reference"],qk=50;function Zn(){return kt.join(process.cwd(),".nex","memory")}function Ws(){return kt.join(Zn(),"memory.json")}function zh(){return kt.join(Zn(),"MEMORY.md")}function Fk(){return kt.join(process.cwd(),"NEX.md")}function Kh(){return kt.join(jk.homedir(),".nex","NEX.md")}function wi(){let t=Zn();Ie.existsSync(t)||Ie.mkdirSync(t,{recursive:!0})}function Xh(t){let e=kt.join(Zn(),t);return Ie.existsSync(e)||Ie.mkdirSync(e,{recursive:!0}),e}function Po(){let t=Ws();if(!Ie.existsSync(t))return{};try{return JSON.parse(Ie.readFileSync(t,"utf-8"))}catch{return{}}}function Vh(t){wi(),yi(Ws(),JSON.stringify(t,null,2))}function Jh(){let t=Ws();if(!Ie.existsSync(t))return;let e=Po(),s=Object.keys(e);if(s.length===0){try{Ie.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=Xh("project"),l=kt.join(a,`${i}.md`),c=r.split(`
242
247
  `)[0].slice(0,100),u=`---
243
248
  name: ${n}
244
249
  description: ${c}
@@ -246,7 +251,7 @@ type: project
246
251
  ---
247
252
 
248
253
  ${r}
249
- `;fi(l,u)}hi();try{Ie.renameSync(t,t+".bak")}catch{}}function xk(t,e,s,n){if(!Co.includes(t))return{ok:!1,path:"",error:`Invalid type: ${t}. Must be one of: ${Co.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=qh(t),i=kt.join(r,`${o}.md`);if(Ie.existsSync(i))try{if(Yl(Ie.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(`
254
+ `;yi(l,u)}_i();try{Ie.renameSync(t,t+".bak")}catch{}}function Bk(t,e,s,n){if(!Mo.includes(t))return{ok:!1,path:"",error:`Invalid type: ${t}. Must be one of: ${Mo.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=Xh(t),i=kt.join(r,`${o}.md`);if(Ie.existsSync(i))try{if(Zl(Ie.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(`
250
255
  `)[0].slice(0,100),l=`---
251
256
  name: ${e}
252
257
  description: ${a}
@@ -254,11 +259,11 @@ type: ${t}
254
259
  ---
255
260
 
256
261
  ${s}
257
- `;return fi(i,l),hi(),{ok:!0,path:i,updated:!0}}function kk(t,e){if(!Co.includes(t))return!1;let s=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase(),n=kt.join(Zn(),t,`${s}.md`);if(!Ie.existsSync(n))return!1;try{return Ie.unlinkSync(n),hi(),!0}catch{return!1}}function Yl(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 Uh(){let t=[],e=Zn();for(let s of Co){let n=kt.join(e,s);if(!Ie.existsSync(n))continue;let o;try{o=Ie.readdirSync(n).filter(r=>r.endsWith(".md"))}catch{continue}for(let r of o){let i=kt.join(n,r);try{let a=Ie.readFileSync(i,"utf-8"),l=Yl(a);t.push({type:s,name:l.name||kt.basename(r,".md"),description:l.description,filePath:i})}catch{}}}return t}function hi(){let t=Uh(),e=["# Project Memory Index",""];for(let s of t){if(e.length>=$k+2)break;let n=`${s.type}/${kt.basename(s.filePath)}`;e.push(`- [${s.name}](${n}) \u2014 ${s.description||"(no description)"}`)}pi(),fi(Dh(),e.join(`
262
+ `;return yi(i,l),_i(),{ok:!0,path:i,updated:!0}}function Uk(t,e){if(!Mo.includes(t))return!1;let s=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase(),n=kt.join(Zn(),t,`${s}.md`);if(!Ie.existsSync(n))return!1;try{return Ie.unlinkSync(n),_i(),!0}catch{return!1}}function Zl(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 Zh(){let t=[],e=Zn();for(let s of Mo){let n=kt.join(e,s);if(!Ie.existsSync(n))continue;let o;try{o=Ie.readdirSync(n).filter(r=>r.endsWith(".md"))}catch{continue}for(let r of o){let i=kt.join(n,r);try{let a=Ie.readFileSync(i,"utf-8"),l=Zl(a);t.push({type:s,name:l.name||kt.basename(r,".md"),description:l.description,filePath:i})}catch{}}}return t}function _i(){let t=Zh(),e=["# Project Memory Index",""];for(let s of t){if(e.length>=qk+2)break;let n=`${s.type}/${kt.basename(s.filePath)}`;e.push(`- [${s.name}](${n}) \u2014 ${s.description||"(no description)"}`)}wi(),yi(zh(),e.join(`
258
263
  `)+`
259
- `)}function Wh(){let t=Dh();if(!Ie.existsSync(t))return"";try{return Ie.readFileSync(t,"utf-8").trim()}catch{return""}}function Sk(t,e){pi(),Ih(qs(),()=>{let s=Ao();s[t]={value:e,updatedAt:new Date().toISOString()},Fh(s)})}function vk(t){let e=Ao();return e[t]?e[t].value:null}function Ek(t){return pi(),Ih(qs(),()=>{let e=Ao();return t in e?(delete e[t],Fh(e),!0):!1})}function Hh(){let t=Ao();return Object.entries(t).map(([e,s])=>({key:e,value:s.value,updatedAt:s.updatedAt}))}function Yh(){let t=jh();if(!Ie.existsSync(t))return"";try{return Ie.readFileSync(t,"utf-8").trim()}catch{return""}}function Gh(){let t=bk();if(!Ie.existsSync(t))return"";try{return Ie.readFileSync(t,"utf-8").trim()}catch{return""}}function Tk(){Bh();let t=[],e=Yh();e&&t.push(`GLOBAL INSTRUCTIONS (~/.nex/NEX.md):
260
- ${e}`);let s=Gh();s&&t.push(`PROJECT INSTRUCTIONS (NEX.md):
261
- ${s}`);let n="",o=Wh();if(o)n=o;else{let d=Hh();d.length>0&&(n=`PROJECT MEMORY:
264
+ `)}function Qh(){let t=zh();if(!Ie.existsSync(t))return"";try{return Ie.readFileSync(t,"utf-8").trim()}catch{return""}}function Wk(t,e){wi(),Gh(Ws(),()=>{let s=Po();s[t]={value:e,updatedAt:new Date().toISOString()},Vh(s)})}function Hk(t){let e=Po();return e[t]?e[t].value:null}function Yk(t){return wi(),Gh(Ws(),()=>{let e=Po();return t in e?(delete e[t],Vh(e),!0):!1})}function em(){let t=Po();return Object.entries(t).map(([e,s])=>({key:e,value:s.value,updatedAt:s.updatedAt}))}function tm(){let t=Kh();if(!Ie.existsSync(t))return"";try{return Ie.readFileSync(t,"utf-8").trim()}catch{return""}}function nm(){let t=Fk();if(!Ie.existsSync(t))return"";try{return Ie.readFileSync(t,"utf-8").trim()}catch{return""}}function Gk(){Jh();let t=[],e=tm();e&&t.push(`GLOBAL INSTRUCTIONS (~/.nex/NEX.md):
265
+ ${e}`);let s=nm();s&&t.push(`PROJECT INSTRUCTIONS (NEX.md):
266
+ ${s}`);let n="",o=Qh();if(o)n=o;else{let d=em();d.length>0&&(n=`PROJECT MEMORY:
262
267
  ${d.map(p=>` ${p.key}: ${p.value}`).join(`
263
268
  `)}`)}let r=t.join(`
264
269
 
@@ -267,69 +272,69 @@ ${d.map(p=>` ${p.key}: ${p.value}`).join(`
267
272
  `}n=f.trimEnd()+`
268
273
  [Memory index truncated \u2014 use delete_memory to prune old entries]`}else n.length>c&&(n="");let u=[...t];return n&&u.push(n),u.length>0&&u.push(i),u.join(`
269
274
 
270
- `)}zh.exports={saveMemory:xk,deleteMemory:kk,scanMemories:Uh,rebuildIndex:hi,loadMemoryIndex:Wh,remember:Sk,recall:vk,forget:Ek,listMemories:Hh,loadGlobalInstructions:Yh,loadProjectInstructions:Gh,getMemoryContext:Tk,_getMemoryDir:Zn,_getMemoryFile:qs,_getGlobalNexMdPath:jh,_parseMemoryFile:Yl,_migrateIfNeeded:Bh,VALID_TYPES:Co}});var Qh=Z((o1,Zh)=>{var No=require("fs"),Gl=require("path"),zl=process.env.NEX_AUDIT!=="false",Qn=null;function Kh(){return Qn||(Qn=Gl.join(process.cwd(),".nex","audit"),No.existsSync(Qn)||No.mkdirSync(Qn,{recursive:!0}),Qn)}function Xh(){let t=new Date().toISOString().split("T")[0];return Gl.join(Kh(),`${t}.jsonl`)}function Rk(t){if(zl)try{let e={timestamp:new Date().toISOString(),tool:t.tool,args:Vh(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)+`
271
- `;No.appendFileSync(Xh(),s,"utf-8")}catch{}}function Vh(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 Jh(t={}){let e=Kh(),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=Gl.join(e,`${r}.jsonl`);if(!No.existsSync(i))continue;let a=No.readFileSync(i,"utf-8").split(`
272
- `).filter(l=>l.trim());for(let l of a)try{let c=JSON.parse(l);if(t.tool&&c.tool!==t.tool)continue;n.push(c)}catch{}if(t.date)break}return n}function Ck(t=1){let e=Jh({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 Ak(t){zl=t}function Ok(){return zl}function Nk(){Qn=null}Zh.exports={logToolExecution:Rk,sanitizeArgs:Vh,readAuditLog:Jh,getAuditSummary:Ck,setAuditEnabled:Ak,isAuditEnabled:Ok,getAuditLogPath:Xh,_reset:Nk}});var dm=Z((a1,um)=>{var Fe=require("fs").promises,Fs=require("fs"),he=require("path"),je=require("util").promisify(require("child_process").exec),es=require("util").promisify(require("child_process").execFile),{spawnSync:Mk}=require("child_process"),Kl=require("axios"),{isForbidden:Pk,isSSHForbidden:Lk,isDangerous:Ik,isCritical:em,isBashPathForbidden:Dk,confirm:Ht}=co(),{showDiff:mi,showNewFile:jk,showEditDiff:r1,confirmFileChange:Mo}=bd(),{C:ae,Spinner:qk,getToolSpinnerText:Fk}=Ke(),{isGitRepo:Xl,getCurrentBranch:tm,getStatus:Bk,getDiff:Uk}=Dr(),{recordChange:gi}=Nd(),{fuzzyFindText:nm,findMostSimilar:Io}=nf(),{runDiagnostics:Po}=of(),{findFileInIndex:Wk,getFileIndex:i1}=As(),{resolveProfile:Pt,sshExec:ht,scpUpload:Hk,scpDownload:sm}=Os(),{resolveDeployConfig:Yk,loadDeployConfigs:Gk}=xf(),{getEditMode:om}=_o(),zk=/^(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/,Kk=/^ssh\s/,Xk=/^ssh(?:\s+-\S+)*\s+\S+@?\S+\s+["']?[^-]/;async function St(t){return Fe.access(t).then(()=>!0).catch(()=>!1)}var yi=null,rm=0,Vk=12e4;function Jk(){let t=Date.now();if(yi&&t-rm<Vk)return yi;let e=he.dirname(process.cwd());try{let s=Fs.readdirSync(e,{withFileTypes:!0}),n=he.basename(process.cwd()),o=s.filter(r=>r.isDirectory()&&r.name!==n&&!r.name.startsWith(".")).map(r=>r.name).sort();return yi=o.length>0?o:null,rm=t,yi}catch{return null}}function Vl(t){if(t&&he.resolve(t)!==process.cwd())return"";let e=Jk();if(!e)return"";let s=he.dirname(process.cwd());return`
275
+ `)}sm.exports={saveMemory:Bk,deleteMemory:Uk,scanMemories:Zh,rebuildIndex:_i,loadMemoryIndex:Qh,remember:Wk,recall:Hk,forget:Yk,listMemories:em,loadGlobalInstructions:tm,loadProjectInstructions:nm,getMemoryContext:Gk,_getMemoryDir:Zn,_getMemoryFile:Ws,_getGlobalNexMdPath:Kh,_parseMemoryFile:Zl,_migrateIfNeeded:Jh,VALID_TYPES:Mo}});var cm=Q((S1,lm)=>{var Io=require("fs"),Ql=require("path"),ec=process.env.NEX_AUDIT!=="false",Qn=null;function om(){return Qn||(Qn=Ql.join(process.cwd(),".nex","audit"),Io.existsSync(Qn)||Io.mkdirSync(Qn,{recursive:!0}),Qn)}function rm(){let t=new Date().toISOString().split("T")[0];return Ql.join(om(),`${t}.jsonl`)}function zk(t){if(ec)try{let e={timestamp:new Date().toISOString(),tool:t.tool,args:im(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)+`
276
+ `;Io.appendFileSync(rm(),s,"utf-8")}catch{}}function im(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 am(t={}){let e=om(),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=Ql.join(e,`${r}.jsonl`);if(!Io.existsSync(i))continue;let a=Io.readFileSync(i,"utf-8").split(`
277
+ `).filter(l=>l.trim());for(let l of a)try{let c=JSON.parse(l);if(t.tool&&c.tool!==t.tool)continue;n.push(c)}catch{}if(t.date)break}return n}function Kk(t=1){let e=am({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 Xk(t){ec=t}function Vk(){return ec}function Jk(){Qn=null}lm.exports={logToolExecution:zk,sanitizeArgs:im,readAuditLog:am,getAuditSummary:Kk,setAuditEnabled:Xk,isAuditEnabled:Vk,getAuditLogPath:rm,_reset:Jk}});var bm=Q((T1,$m)=>{var Be=require("fs").promises,Hs=require("fs"),me=require("path"),je=require("util").promisify(require("child_process").exec),es=require("util").promisify(require("child_process").execFile),{spawnSync:Zk}=require("child_process"),tc=require("axios"),{isForbidden:Qk,isSSHForbidden:eS,isDangerous:tS,isCritical:um,isBashPathForbidden:nS,confirm:Ht}=ho(),{showDiff:$i,showNewFile:sS,showEditDiff:v1,confirmFileChange:Do}=Od(),{C:le,Spinner:oS,getToolSpinnerText:rS}=Ke(),{isGitRepo:nc,getCurrentBranch:dm,getStatus:iS,getDiff:aS}=Br(),{recordChange:bi}=Ud(),{fuzzyFindText:fm,findMostSimilar:Fo}=pf(),{runDiagnostics:jo}=mf(),{findFileInIndex:lS,getFileIndex:E1}=Ns(),{resolveProfile:Pt,sshExec:ht,scpUpload:cS,scpDownload:pm}=Ms(),{resolveDeployConfig:uS,loadDeployConfigs:dS}=Nf(),{getEditMode:hm}=ko(),fS=/^(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/,pS=/^ssh\s/,hS=/^ssh(?:\s+-\S+)*\s+\S+@?\S+\s+["']?[^-]/;async function St(t){return Be.access(t).then(()=>!0).catch(()=>!1)}var xi=null,mm=0,mS=12e4;function gS(){let t=Date.now();if(xi&&t-mm<mS)return xi;let e=me.dirname(process.cwd());try{let s=Hs.readdirSync(e,{withFileTypes:!0}),n=me.basename(process.cwd()),o=s.filter(r=>r.isDirectory()&&r.name!==n&&!r.name.startsWith(".")).map(r=>r.name).sort();return xi=o.length>0?o:null,mm=t,xi}catch{return null}}function sc(t){if(t&&me.resolve(t)!==process.cwd())return"";let e=gS();if(!e)return"";let s=me.dirname(process.cwd());return`
273
278
  Hint: no matches in current project. Sibling directories in ${s}/:
274
279
  ${e.join(", ")}
275
- You can search there with: grep pattern --path ${s}/<dir>`}async function wi(t){if(!t)return{fixedPath:null,message:""};let e=t.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),s=et(e);if(s&&await St(s))return{fixedPath:s,message:`(auto-fixed path: ${t} \u2192 ${e})`};let n=[".js",".ts",".jsx",".tsx",".mjs",".cjs",".json"],o=he.extname(t);if(!o)for(let i of n){let a=et(t+i);if(a&&await St(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 l=et(i+a);if(l&&await St(l))return{fixedPath:l,message:`(auto-fixed: ${o} \u2192 ${a})`}}}let r=he.basename(t);if(r&&r.length>2)try{let i=Wk(r).map(a=>et(a));if(i.length===1)return{fixedPath:i[0],message:`(auto-fixed: found ${r} at ${he.relative(process.cwd(),i[0])})`};if(i.length>1&&i.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
276
- ${i.map(l=>he.relative(process.cwd(),l)).map(l=>` - ${l}`).join(`
277
- `)}`}}catch{}if(r&&r.length>2)try{let i=r.toLowerCase(),{getFileIndex:a}=As(),l=a().filter(c=>he.basename(c).toLowerCase()===i).map(c=>et(c));if(l.length===1)return{fixedPath:l[0],message:`(auto-fixed: case-insensitive match \u2192 ${he.relative(process.cwd(),l[0])})`};if(l.length>1&&l.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
278
- ${l.map(u=>he.relative(process.cwd(),u)).map(u=>` - ${u}`).join(`
279
- `)}`}}catch{}try{let{smartSearch:i}=As(),a=i(t,{limit:5,minScore:15});if(a.length>0){let l=et(a[0].file);if(a[0].score>=200||a.length===1&&a[0].score>=50)return{fixedPath:l,message:`(auto-fixed: smart matched ${t} \u2192 ${he.relative(process.cwd(),l)})`};if(a.length>=2&&a[0].score>=80&&a[0].score>=a[1].score*1.5)return{fixedPath:l,message:`(auto-fixed: best match ${t} \u2192 ${he.relative(process.cwd(),l)})`};if(a.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
280
- ${a.map(u=>he.relative(process.cwd(),et(u.file))).map(u=>` - ${u}`).join(`
281
- `)}`}}}catch{}return{fixedPath:null,message:""}}function Zk(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 lm(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+`
280
+ You can search there with: grep pattern --path ${s}/<dir>`}async function ki(t){if(!t)return{fixedPath:null,message:""};let e=t.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),s=tt(e);if(s&&await St(s))return{fixedPath:s,message:`(auto-fixed path: ${t} \u2192 ${e})`};let n=[".js",".ts",".jsx",".tsx",".mjs",".cjs",".json"],o=me.extname(t);if(!o)for(let i of n){let a=tt(t+i);if(a&&await St(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 l=tt(i+a);if(l&&await St(l))return{fixedPath:l,message:`(auto-fixed: ${o} \u2192 ${a})`}}}let r=me.basename(t);if(r&&r.length>2)try{let i=lS(r).map(a=>tt(a));if(i.length===1)return{fixedPath:i[0],message:`(auto-fixed: found ${r} at ${me.relative(process.cwd(),i[0])})`};if(i.length>1&&i.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
281
+ ${i.map(l=>me.relative(process.cwd(),l)).map(l=>` - ${l}`).join(`
282
+ `)}`}}catch{}if(r&&r.length>2)try{let i=r.toLowerCase(),{getFileIndex:a}=Ns(),l=a().filter(c=>me.basename(c).toLowerCase()===i).map(c=>tt(c));if(l.length===1)return{fixedPath:l[0],message:`(auto-fixed: case-insensitive match \u2192 ${me.relative(process.cwd(),l[0])})`};if(l.length>1&&l.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
283
+ ${l.map(u=>me.relative(process.cwd(),u)).map(u=>` - ${u}`).join(`
284
+ `)}`}}catch{}try{let{smartSearch:i}=Ns(),a=i(t,{limit:5,minScore:15});if(a.length>0){let l=tt(a[0].file);if(a[0].score>=200||a.length===1&&a[0].score>=50)return{fixedPath:l,message:`(auto-fixed: smart matched ${t} \u2192 ${me.relative(process.cwd(),l)})`};if(a.length>=2&&a[0].score>=80&&a[0].score>=a[1].score*1.5)return{fixedPath:l,message:`(auto-fixed: best match ${t} \u2192 ${me.relative(process.cwd(),l)})`};if(a.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
285
+ ${a.map(u=>me.relative(process.cwd(),tt(u.file))).map(u=>` - ${u}`).join(`
286
+ `)}`}}}catch{}return{fixedPath:null,message:""}}function yS(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 wm(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+`
282
287
 
283
288
  `+s.join(`
284
- `)}function cm(t,e,s){let n=Io(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 im=!1,ts=null;function Qk(){ts&&(ts(),ts=null)}var Zl=null;function eS(t){Zl=t}async function Jl(){if(!im){im=!0;try{let{stdout:t}=await je("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await je('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await je("git stash pop",{cwd:process.cwd(),timeout:1e4}),await je("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var tS=[/\.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 et(t){let e=he.isAbsolute(t)?he.resolve(t):he.resolve(process.cwd(),t);for(let s of tS)if(s.test(e))return null;return e}var nS=[{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. Example: use bash for "npm install" or "git status", but NOT for "cat config.json" (use read_file instead) or "grep -r 'error' src/" (use grep tool instead). 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. ALWAYS read a file before editing it to ensure exact content matching \u2014 edit_file requires the EXACT text including whitespace and newlines. Example: read_file path=src/app.js line_start=10 line_end=20. Auto-truncates at 350 lines for unbounded reads. For large files (>350 lines), use line_start/line_end to read specific sections. Concrete example: read_file(path='src/app.js', line_start=10, line_end=20) reads lines 10-20 of src/app.js. Prefer this over bash cat/head/tail \u2014 dedicated tools produce better-formatted output. Files are read with UTF-8 encoding. IMPORTANT: If you need more than 350 lines, specify line_start and line_end explicitly \u2014 omitting them will truncate the output.",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. Example: use write_file for creating a new config file like .env.example, but NOT for changing one line in an existing file (use edit_file instead). 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. ALWAYS call read_file first to get the exact content \u2014 edit_file requires the EXACT text including whitespace, indentation, and newlines. Example: edit_file(path='src/config.js', old_text='debug: false', new_text='debug: true'). IMPORTANT: old_text must match byte-for-byte \u2014 even a single space or newline difference will cause failure. If the edit fails with 'old_text not found', re-read that region with line_start/line_end then retry. For multiple replacements in one file, prefer patch_file (atomic). For new files, use write_file instead.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},old_text:{type:"string",description:"Exact text to find (must match file content precisely)"},new_text:{type:"string",description:"Replacement text"}},required:["path","old_text","new_text"]}}},{type:"function",function:{name:"list_directory",description:"List files and directories in a tree view. Use this to understand project structure. Example: use list_directory to see the overall layout of the src/ directory, but NOT for finding all .js files (use glob instead). 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. Example: use search_files for finding all occurrences of 'error' in .js files, but NOT for finding all .js files (use glob instead). 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 by name or extension. Returns paths sorted by modification time. ALWAYS use this to locate files BEFORE reading them \u2014 never guess file paths. Example: glob(pattern='src/**/*.test.js') finds all test files in src directory. DO NOT use for content search (e.g. finding 'error' in files) \u2014 use grep tool instead. 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 get the exact 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 \u2014 use this when you need to find text inside files. Example: grep(pattern='callStream') finds files containing the text 'callStream'. Do NOT use glob for this \u2014 glob finds files by NAME pattern, grep searches file CONTENTS. Use output_mode='files_with_matches' for just file paths, output_mode='content' (default) for matching lines. Optionally use include to filter by file type (e.g. '*.js') but OMIT it when first searching \u2014 code may live in .html, .vue, .py or other unexpected file types. Supports context lines, offset pagination, and multiline 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. Example: when changing 3 different variables in the same function, use patch_file with an array of 3 { old_text, new_text } objects instead of 3 separate edit_file calls. This ensures either all changes are applied or none are, preventing partial edits. 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:"visual_review",description:"Screenshot a URL, analyze the visual result, and return structured feedback about layout, design, and usability issues. Use this to visually inspect web pages, check CSS changes, or verify UI fixes. Returns the screenshot path + analysis.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot and analyze"},focus:{type:"string",description:"What to focus on: layout, colors, typography, spacing, responsiveness, accessibility, or a custom description (e.g. 'check the navbar alignment')"},width:{type:"number",description:"Viewport width in px (default: 1280)"},height:{type:"number",description:"Viewport height in px (default: 800)"},full_page:{type:"boolean",description:"Capture full scrollable page (default: false)"},compare_with:{type:"string",description:"Path to a previous screenshot to compare against (optional). Enables before/after analysis."}},required:["url"]}}},{type:"function",function:{name:"clipboard_image",description:"Grab the current image from the system clipboard (macOS). Returns the screenshot path for visual analysis. Use when the user says 'clipboard', 'pasteboard', or wants to analyze a copied screenshot.",parameters:{type:"object",properties:{},required:[]}}},{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:"visual_diff",description:"Compare two screenshots pixel-by-pixel and compute a visual diff. Returns the percentage of changed pixels and which screen regions (top-left, center, bottom-right, etc.) were affected. Use after making CSS/HTML changes to quantify what changed. Example: take a before screenshot, make changes, take an after screenshot, then visual_diff both paths.",parameters:{type:"object",properties:{before:{type:"string",description:"Path to the 'before' screenshot (PNG)"},after:{type:"string",description:"Path to the 'after' screenshot (PNG)"},threshold:{type:"number",description:"Color distance threshold 0-1 (default: 0.1). Lower = more sensitive."}},required:["before","after"]}}},{type:"function",function:{name:"responsive_sweep",description:"Screenshot a URL at 5 viewport widths (320, 768, 1024, 1440, 1920) and return all screenshots for breakpoint analysis. Quickly identifies responsive layout issues across mobile, tablet, and desktop. Returns images for visual analysis.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot at each viewport"},viewports:{type:"array",items:{type:"object",properties:{width:{type:"number"},label:{type:"string"}}},description:"Custom viewport list (default: 320/768/1024/1440/1920)"},full_page:{type:"boolean",description:"Capture full scrollable page at each viewport (default: false)"}},required:["url"]}}},{type:"function",function:{name:"visual_annotate",description:"Draw annotations (red boxes, arrows, circles) directly on a screenshot to mark problem areas. Returns the annotated image. Use instead of describing locations verbally \u2014 visual markers are unambiguous.",parameters:{type:"object",properties:{image:{type:"string",description:"Path to the screenshot (PNG) to annotate"},annotations:{type:"array",items:{type:"object",properties:{type:{type:"string",description:"box, arrow, or circle"},x:{type:"number",description:"X position (px)"},y:{type:"number",description:"Y position (px)"},width:{type:"number",description:"Width for box (px)"},height:{type:"number",description:"Height for box (px)"},toX:{type:"number",description:"Arrow end X (px)"},toY:{type:"number",description:"Arrow end Y (px)"},radius:{type:"number",description:"Circle radius (px)"},label:{type:"string",description:"Text label for the annotation"},color:{type:"string",description:"Hex color (default: #FF0000)"}},required:["type","x","y"]},description:"List of annotations to draw"}},required:["image","annotations"]}}},{type:"function",function:{name:"visual_watch",description:"Hot-reload visual feedback loop: watches source files for changes, waits for HMR to settle, takes a new screenshot, diffs it against the previous one, and reports what changed. Runs up to N iterations (default: 10). Requires a running dev server (Vite, Next, etc.) and chokidar. Use for autonomous visual polish loops.",parameters:{type:"object",properties:{url:{type:"string",description:"Dev server URL to screenshot (e.g. http://localhost:5173)"},watch:{type:"array",items:{type:"string"},description:"File paths or directories to watch for changes (e.g. ['src/components', 'src/styles'])"},max_iterations:{type:"number",description:"Max number of change\u2192screenshot\u2192diff cycles (default: 10)"},hmr_delay:{type:"number",description:"Milliseconds to wait after file change for HMR to settle (default: 1500)"}},required:["url","watch"]}}},{type:"function",function:{name:"design_tokens",description:"Extract design tokens from a screenshot: dominant colors (with hex/rgb/frequency/category), detected vertical spacing values, and image dimensions. Use to audit visual consistency, compare against a design system, or reverse-engineer CSS variables from a rendered page.",parameters:{type:"object",properties:{image:{type:"string",description:"Path to screenshot (PNG) to analyze"},sample_rate:{type:"number",description:"Pixel sampling interval \u2014 lower = more accurate but slower (default: 4)"}},required:["image"]}}},{type:"function",function:{name:"design_compare",description:"Compare a live web page against a reference design (Figma export, mockup PNG). Screenshots the URL at the reference image's dimensions, computes pixel-level diff, and returns annotated images highlighting deviations. Use to verify implementation matches the design spec.",parameters:{type:"object",properties:{url:{type:"string",description:"Live URL to compare against the reference"},reference:{type:"string",description:"Path to reference design image (PNG)"},width:{type:"number",description:"Override viewport width (default: match reference image width)"},height:{type:"number",description:"Override viewport height (default: 800)"},threshold:{type:"number",description:"Color distance threshold 0-1 (default: 0.1)"}},required:["url","reference"]}}},{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) that live on almalinux9. 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/deploy/app). 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", "my-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", "my-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 Lo(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 am(t,e,s={}){switch(t){case"bash":{let n=e.command,o=Pk(n);if(o){let d=Zk(n);return`BLOCKED: Command matches forbidden pattern: ${o}${d?`
285
- HINT: ${d}`:""}`}let r=Dk(n);if(r)return`BLOCKED: Destructive operation on protected path: ${r}
286
- 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?em(n):Ik(n)){let d=em(n)?"\u26D4":"\u26A0";if(!await Ht(` ${d} bash: \`${n}\``,{toolName:"bash"}))return"CANCELLED: User declined to execute this command."}let a;try{a=process.cwd(),Fs.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 l=Kk.test(n.trim())&&!Xk.test(n.trim());if(zk.test(n.trim())||l){s.silent||console.log(`${ae.dim} \u25B6 interactive: ${n}${ae.reset}`);let d=Mk("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:c}=bs(),u=s.silent?null:new c("bash",n.substring(0,40));u&&u.start();try{let{stdout:d,stderr:f}=await je(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),p=lm(f,n);return`EXIT ${d.code||1}
287
- ${p}`}}case"read_file":{let n=et(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await St(n)){let N=await wi(e.path);if(N.fixedPath)n=N.fixedPath,console.log(`${ae.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${he.relative(process.cwd(),n)}${ae.reset}`);else return`ERROR: File not found: ${e.path}${N.message?`
288
- `+N.message:""}`}let r=Buffer.alloc(8192),i=await Fs.promises.open(n,"r"),{bytesRead:a}=await i.read(r,0,8192,0);await i.close();for(let N=0;N<a;N++)if(r[N]===0)return`ERROR: ${n} is a binary file (not readable as text)`;let l=await Fe.readFile(n,"utf-8");if(!l&&(await Fe.stat(n)).size>0)return`WARNING: ${n} is empty or unreadable`;let c=l.split(`
289
- `),u=await Fe.stat(n),d=c.length,f=350,p=!e.line_start&&!e.line_end,h=p&&d>f,g=(e.line_start||1)-1,_=h?f:e.line_end||c.length,b=he.relative(process.cwd(),n),O=h?`showing lines 1-${f} of ${d}`:e.line_start||e.line_end?`lines ${g+1}-${_} of ${d}`:`${d} lines`,M=`File: ${b} (${O}, ${u.size} bytes)`,v=c.slice(g,_).map((N,te)=>`${g+te+1}: ${N}`).join(`
290
- `),T=h?`
289
+ `)}function _m(t,e,s){let n=Fo(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 gm=!1,ts=null;function wS(){ts&&(ts(),ts=null)}var rc=null;function _S(t){rc=t}async function oc(){if(!gm){gm=!0;try{let{stdout:t}=await je("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await je('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await je("git stash pop",{cwd:process.cwd(),timeout:1e4}),await je("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var $S=[/\.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 tt(t){let e=me.isAbsolute(t)?me.resolve(t):me.resolve(process.cwd(),t);for(let s of $S)if(s.test(e))return null;return e}var bS=[{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. Example: use bash for "npm install" or "git status", but NOT for "cat config.json" (use read_file instead) or "grep -r 'error' src/" (use grep tool instead). 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. ALWAYS read a file before editing it to ensure exact content matching \u2014 edit_file requires the EXACT text including whitespace and newlines. Example: read_file path=src/app.js line_start=10 line_end=20. Auto-truncates at 350 lines for unbounded reads. For large files (>350 lines), use line_start/line_end to read specific sections. Concrete example: read_file(path='src/app.js', line_start=10, line_end=20) reads lines 10-20 of src/app.js. Prefer this over bash cat/head/tail \u2014 dedicated tools produce better-formatted output. Files are read with UTF-8 encoding. IMPORTANT: If you need more than 350 lines, specify line_start and line_end explicitly \u2014 omitting them will truncate the output.",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. Example: use write_file for creating a new config file like .env.example, but NOT for changing one line in an existing file (use edit_file instead). 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. ALWAYS call read_file first to get the exact content \u2014 edit_file requires the EXACT text including whitespace, indentation, and newlines. Example: edit_file(path='src/config.js', old_text='debug: false', new_text='debug: true'). IMPORTANT: old_text must match byte-for-byte \u2014 even a single space or newline difference will cause failure. If the edit fails with 'old_text not found', re-read that region with line_start/line_end then retry. For multiple replacements in one file, prefer patch_file (atomic). For new files, use write_file instead.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},old_text:{type:"string",description:"Exact text to find (must match file content precisely)"},new_text:{type:"string",description:"Replacement text"}},required:["path","old_text","new_text"]}}},{type:"function",function:{name:"list_directory",description:"List files and directories in a tree view. Use this to understand project structure. Example: use list_directory to see the overall layout of the src/ directory, but NOT for finding all .js files (use glob instead). 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. Example: use search_files for finding all occurrences of 'error' in .js files, but NOT for finding all .js files (use glob instead). 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 by name or extension. Returns paths sorted by modification time. ALWAYS use this to locate files BEFORE reading them \u2014 never guess file paths. Example: glob(pattern='src/**/*.test.js') finds all test files in src directory. DO NOT use for content search (e.g. finding 'error' in files) \u2014 use grep tool instead. 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 get the exact 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 \u2014 use this when you need to find text inside files. Example: grep(pattern='callStream') finds files containing the text 'callStream'. Do NOT use glob for this \u2014 glob finds files by NAME pattern, grep searches file CONTENTS. Use output_mode='files_with_matches' for just file paths, output_mode='content' (default) for matching lines. Optionally use include to filter by file type (e.g. '*.js') but OMIT it when first searching \u2014 code may live in .html, .vue, .py or other unexpected file types. Supports context lines, offset pagination, and multiline 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. Example: when changing 3 different variables in the same function, use patch_file with an array of 3 { old_text, new_text } objects instead of 3 separate edit_file calls. This ensures either all changes are applied or none are, preventing partial edits. 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:"visual_review",description:"Screenshot a URL, analyze the visual result, and return structured feedback about layout, design, and usability issues. Use this to visually inspect web pages, check CSS changes, or verify UI fixes. Returns the screenshot path + analysis.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot and analyze"},focus:{type:"string",description:"What to focus on: layout, colors, typography, spacing, responsiveness, accessibility, or a custom description (e.g. 'check the navbar alignment')"},width:{type:"number",description:"Viewport width in px (default: 1280)"},height:{type:"number",description:"Viewport height in px (default: 800)"},full_page:{type:"boolean",description:"Capture full scrollable page (default: false)"},compare_with:{type:"string",description:"Path to a previous screenshot to compare against (optional). Enables before/after analysis."}},required:["url"]}}},{type:"function",function:{name:"clipboard_image",description:"Grab the current image from the system clipboard (macOS). Returns the screenshot path for visual analysis. Use when the user says 'clipboard', 'pasteboard', or wants to analyze a copied screenshot.",parameters:{type:"object",properties:{},required:[]}}},{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:"visual_diff",description:"Compare two screenshots pixel-by-pixel and compute a visual diff. Returns the percentage of changed pixels and which screen regions (top-left, center, bottom-right, etc.) were affected. Use after making CSS/HTML changes to quantify what changed. Example: take a before screenshot, make changes, take an after screenshot, then visual_diff both paths.",parameters:{type:"object",properties:{before:{type:"string",description:"Path to the 'before' screenshot (PNG)"},after:{type:"string",description:"Path to the 'after' screenshot (PNG)"},threshold:{type:"number",description:"Color distance threshold 0-1 (default: 0.1). Lower = more sensitive."}},required:["before","after"]}}},{type:"function",function:{name:"responsive_sweep",description:"Screenshot a URL at 5 viewport widths (320, 768, 1024, 1440, 1920) and return all screenshots for breakpoint analysis. Quickly identifies responsive layout issues across mobile, tablet, and desktop. Returns images for visual analysis.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot at each viewport"},viewports:{type:"array",items:{type:"object",properties:{width:{type:"number"},label:{type:"string"}}},description:"Custom viewport list (default: 320/768/1024/1440/1920)"},full_page:{type:"boolean",description:"Capture full scrollable page at each viewport (default: false)"}},required:["url"]}}},{type:"function",function:{name:"visual_annotate",description:"Draw annotations (red boxes, arrows, circles) directly on a screenshot to mark problem areas. Returns the annotated image. Use instead of describing locations verbally \u2014 visual markers are unambiguous.",parameters:{type:"object",properties:{image:{type:"string",description:"Path to the screenshot (PNG) to annotate"},annotations:{type:"array",items:{type:"object",properties:{type:{type:"string",description:"box, arrow, or circle"},x:{type:"number",description:"X position (px)"},y:{type:"number",description:"Y position (px)"},width:{type:"number",description:"Width for box (px)"},height:{type:"number",description:"Height for box (px)"},toX:{type:"number",description:"Arrow end X (px)"},toY:{type:"number",description:"Arrow end Y (px)"},radius:{type:"number",description:"Circle radius (px)"},label:{type:"string",description:"Text label for the annotation"},color:{type:"string",description:"Hex color (default: #FF0000)"}},required:["type","x","y"]},description:"List of annotations to draw"}},required:["image","annotations"]}}},{type:"function",function:{name:"visual_watch",description:"Hot-reload visual feedback loop: watches source files for changes, waits for HMR to settle, takes a new screenshot, diffs it against the previous one, and reports what changed. Runs up to N iterations (default: 10). Requires a running dev server (Vite, Next, etc.) and chokidar. Use for autonomous visual polish loops.",parameters:{type:"object",properties:{url:{type:"string",description:"Dev server URL to screenshot (e.g. http://localhost:5173)"},watch:{type:"array",items:{type:"string"},description:"File paths or directories to watch for changes (e.g. ['src/components', 'src/styles'])"},max_iterations:{type:"number",description:"Max number of change\u2192screenshot\u2192diff cycles (default: 10)"},hmr_delay:{type:"number",description:"Milliseconds to wait after file change for HMR to settle (default: 1500)"}},required:["url","watch"]}}},{type:"function",function:{name:"design_tokens",description:"Extract design tokens from a screenshot: dominant colors (with hex/rgb/frequency/category), detected vertical spacing values, and image dimensions. Use to audit visual consistency, compare against a design system, or reverse-engineer CSS variables from a rendered page.",parameters:{type:"object",properties:{image:{type:"string",description:"Path to screenshot (PNG) to analyze"},sample_rate:{type:"number",description:"Pixel sampling interval \u2014 lower = more accurate but slower (default: 4)"}},required:["image"]}}},{type:"function",function:{name:"design_compare",description:"Compare a live web page against a reference design (Figma export, mockup PNG). Screenshots the URL at the reference image's dimensions, computes pixel-level diff, and returns annotated images highlighting deviations. Use to verify implementation matches the design spec.",parameters:{type:"object",properties:{url:{type:"string",description:"Live URL to compare against the reference"},reference:{type:"string",description:"Path to reference design image (PNG)"},width:{type:"number",description:"Override viewport width (default: match reference image width)"},height:{type:"number",description:"Override viewport height (default: 800)"},threshold:{type:"number",description:"Color distance threshold 0-1 (default: 0.1)"}},required:["url","reference"]}}},{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.'},background:{type:"boolean",description:"Run this agent non-blocking in the background. The main session continues immediately; results are injected as [BACKGROUND AGENT COMPLETED] user messages when the agent finishes. Use for tasks that can run in parallel to your main work."}},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) that live on almalinux9. 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/deploy/app). 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", "my-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", "my-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 qo(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 ym(t,e,s={}){switch(t){case"bash":{let n=e.command,o=Qk(n);if(o){let d=yS(n);return`BLOCKED: Command matches forbidden pattern: ${o}${d?`
290
+ HINT: ${d}`:""}`}let r=nS(n);if(r)return`BLOCKED: Destructive operation on protected path: ${r}
291
+ 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?um(n):tS(n)){let d=um(n)?"\u26D4":"\u26A0";if(!await Ht(` ${d} bash: \`${n}\``,{toolName:"bash"}))return"CANCELLED: User declined to execute this command."}let a;try{a=process.cwd(),Hs.accessSync(a)}catch{a=require("os").homedir(),s.silent||console.log(`${le.yellow} \u26A0 Working directory no longer exists \u2014 running in ${a}${le.reset}`)}let l=pS.test(n.trim())&&!hS.test(n.trim());if(fS.test(n.trim())||l){s.silent||console.log(`${le.dim} \u25B6 interactive: ${n}${le.reset}`);let d=Zk("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:c}=ks(),u=s.silent?null:new c("bash",n.substring(0,40));u&&u.start();try{let{stdout:d,stderr:f}=await je(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),p=wm(f,n);return`EXIT ${d.code||1}
292
+ ${p}`}}case"read_file":{let n=tt(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await St(n)){let O=await ki(e.path);if(O.fixedPath)n=O.fixedPath,console.log(`${le.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${me.relative(process.cwd(),n)}${le.reset}`);else return`ERROR: File not found: ${e.path}${O.message?`
293
+ `+O.message:""}`}let r=Buffer.alloc(8192),i=await Hs.promises.open(n,"r"),{bytesRead:a}=await i.read(r,0,8192,0);await i.close();for(let O=0;O<a;O++)if(r[O]===0)return`ERROR: ${n} is a binary file (not readable as text)`;let l=await Be.readFile(n,"utf-8");if(!l&&(await Be.stat(n)).size>0)return`WARNING: ${n} is empty or unreadable`;let c=l.split(`
294
+ `),u=await Be.stat(n),d=c.length,f=350,p=!e.line_start&&!e.line_end,m=p&&d>f,g=(e.line_start||1)-1,_=m?f:e.line_end||c.length,b=me.relative(process.cwd(),n),A=m?`showing lines 1-${f} of ${d}`:e.line_start||e.line_end?`lines ${g+1}-${_} of ${d}`:`${d} lines`,P=`File: ${b} (${A}, ${u.size} bytes)`,v=c.slice(g,_).map((O,ne)=>`${g+ne+1}: ${O}`).join(`
295
+ `),E=m?`
291
296
 
292
297
  [\u{1F6A8} FILE TRUNCATED: You are only seeing lines 1-${f} of ${d} total lines. The rest of the file is HIDDEN. You MUST use line_start and line_end to read further down (e.g. line_start=${f+1}), or use grep_search to find specific keywords.]`:!p&&d>_?`
293
298
 
294
- [\u{1F6A8} FILE CONTINUES: This is only lines ${g+1} to ${_} of ${d} total. The rest is HIDDEN. Use line_start=${_+1} to read the next section, or grep_search for keywords.]`:"";return`${M}
295
- ${v}${T}`}case"write_file":{await Jl();let n=et(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let o=await St(n),r=null;if(s.autoConfirm)o&&(r=await Fe.readFile(n,"utf-8"));else if(o){r=await Fe.readFile(n,"utf-8");let u=await Po(n,e.content);if(mi(n,r,e.content,{annotations:u}),!await Mo("Overwrite"))return"CANCELLED: User declined to overwrite file."}else{let u=await Po(n,e.content);if(jk(n,e.content,{annotations:u}),!await Mo("Create"))return"CANCELLED: User declined to create file."}let i=he.dirname(n);await St(i)||await Fe.mkdir(i,{recursive:!0}),await Fe.writeFile(n,e.content,"utf-8");let l=/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||e.content.startsWith("#!");l&&await Fe.chmod(n,493),gi("write_file",n,r,e.content);let c=l?" [chmod +x applied]":"";return`Written: ${n} (${e.content.length} chars)${c}`}case"edit_file":{await Jl();let n=et(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await St(n)){let u=await wi(e.path);if(u.fixedPath)n=u.fixedPath,console.log(`${ae.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${he.relative(process.cwd(),n)}${ae.reset}`);else return`ERROR: File not found: ${e.path}${u.message?`
296
- `+u.message:""}`}let r=await Fe.readFile(n,"utf-8"),i=e.old_text,a=!1,l=!1;if(!r.includes(e.old_text)){let{getActiveModelId:u,getActiveProviderName:d}=Ze();if(om(u(),d())==="strict"){let h=Io(r,e.old_text);return h?`ERROR: old_text not found in ${n} (strict mode \u2014 exact match required)
297
- Most similar text (line ${h.line}, distance ${h.distance}):
298
- ${h.text}`:`ERROR: old_text not found in ${n} (strict mode \u2014 exact match required)`}let p=nm(r,e.old_text);if(p)i=p,a=!0,console.log(`${ae.dim} \u2713 fuzzy whitespace match applied${ae.reset}`);else{let h=cm(r,e.old_text,e.new_text);if(h){if(!s.autoConfirm){let M=await Po(n,h.content);if(mi(n,r,h.content,{annotations:M}),!await Mo(`Apply (auto-fix, line ${h.line}, distance ${h.distance})`))return"CANCELLED: User declined to apply edit."}await Fe.writeFile(n,h.content,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||h.content.startsWith("#!"))&&await Fe.chmod(n,493),gi("edit_file",n,r,h.content);let O=h.matchText.length>80?h.matchText.substring(0,77)+"...":h.matchText;return console.log(`${ae.dim} \u2713 auto-fixed edit: line ${h.line}, distance ${h.distance}${ae.reset}`),`Edited: ${n} (auto-fixed, line ${h.line}, distance ${h.distance}, matched: "${O}")`}let g=Io(r,e.old_text);if(g){let O=r.split(`
299
- `),M=Math.max(0,g.line-6),v=Math.min(O.length,g.line+10),T=O.slice(M,v).map((te,K)=>`${M+K+1}: ${te}`).join(`
300
- `),N=`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})
299
+ [\u{1F6A8} FILE CONTINUES: This is only lines ${g+1} to ${_} of ${d} total. The rest is HIDDEN. Use line_start=${_+1} to read the next section, or grep_search for keywords.]`:"";return`${P}
300
+ ${v}${E}`}case"write_file":{await oc();let n=tt(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let o=await St(n),r=null;if(s.autoConfirm)o&&(r=await Be.readFile(n,"utf-8"));else if(o){r=await Be.readFile(n,"utf-8");let u=await jo(n,e.content);if($i(n,r,e.content,{annotations:u}),!await Do("Overwrite"))return"CANCELLED: User declined to overwrite file."}else{let u=await jo(n,e.content);if(sS(n,e.content,{annotations:u}),!await Do("Create"))return"CANCELLED: User declined to create file."}let i=me.dirname(n);await St(i)||await Be.mkdir(i,{recursive:!0}),await Be.writeFile(n,e.content,"utf-8");let l=/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||e.content.startsWith("#!");l&&await Be.chmod(n,493),bi("write_file",n,r,e.content);let c=l?" [chmod +x applied]":"";return`Written: ${n} (${e.content.length} chars)${c}`}case"edit_file":{await oc();let n=tt(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await St(n)){let u=await ki(e.path);if(u.fixedPath)n=u.fixedPath,console.log(`${le.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${me.relative(process.cwd(),n)}${le.reset}`);else return`ERROR: File not found: ${e.path}${u.message?`
301
+ `+u.message:""}`}let r=await Be.readFile(n,"utf-8"),i=e.old_text,a=!1,l=!1;if(!r.includes(e.old_text)){let{getActiveModelId:u,getActiveProviderName:d}=Qe();if(hm(u(),d())==="strict"){let m=Fo(r,e.old_text);return m?`ERROR: old_text not found in ${n} (strict mode \u2014 exact match required)
302
+ Most similar text (line ${m.line}, distance ${m.distance}):
303
+ ${m.text}`:`ERROR: old_text not found in ${n} (strict mode \u2014 exact match required)`}let p=fm(r,e.old_text);if(p)i=p,a=!0,console.log(`${le.dim} \u2713 fuzzy whitespace match applied${le.reset}`);else{let m=_m(r,e.old_text,e.new_text);if(m){if(!s.autoConfirm){let P=await jo(n,m.content);if($i(n,r,m.content,{annotations:P}),!await Do(`Apply (auto-fix, line ${m.line}, distance ${m.distance})`))return"CANCELLED: User declined to apply edit."}await Be.writeFile(n,m.content,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||m.content.startsWith("#!"))&&await Be.chmod(n,493),bi("edit_file",n,r,m.content);let A=m.matchText.length>80?m.matchText.substring(0,77)+"...":m.matchText;return console.log(`${le.dim} \u2713 auto-fixed edit: line ${m.line}, distance ${m.distance}${le.reset}`),`Edited: ${n} (auto-fixed, line ${m.line}, distance ${m.distance}, matched: "${A}")`}let g=Fo(r,e.old_text);if(g){let A=r.split(`
304
+ `),P=Math.max(0,g.line-6),v=Math.min(A.length,g.line+10),E=A.slice(P,v).map((ne,J)=>`${P+J+1}: ${ne}`).join(`
305
+ `),O=`line_start=${Math.max(1,g.line-5)} line_end=${Math.min(A.length,g.line+15)}`;return`ERROR: old_text not found in ${n} (most similar at line ${g.line}, distance ${g.distance})
301
306
 
302
307
  Actual file content around line ${g.line} \u2014 use this to correct old_text:
303
- ${T}
308
+ ${E}
304
309
 
305
- Fix: update old_text to match the exact lines above, then retry. If you need more context: read_file with ${N}`}let _=(e.old_text||"").trim().split(`
310
+ Fix: update old_text to match the exact lines above, then retry. If you need more context: read_file with ${O}`}let _=(e.old_text||"").trim().split(`
306
311
  `)[0].slice(0,60),b=_?`
307
312
  Recovery: grep -n "${_.replace(/"/g,'\\"')}" <file> to find the line, then re-read that section with line_start/line_end.`:`
308
- 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}${b}`}}if(!s.autoConfirm){let u=r.split(i).join(e.new_text),d=await Po(n,u);if(mi(n,r,u,{annotations:d}),!await Mo(a?"Apply (fuzzy match)":"Apply"))return"CANCELLED: User declined to apply edit."}let c=r.split(i).join(e.new_text);return await Fe.writeFile(n,c,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||c.startsWith("#!"))&&await Fe.chmod(n,493),gi("edit_file",n,r,c),a?`Edited: ${n} (fuzzy match)`:`Edited: ${n}`}case"list_directory":{let n=et(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await St(n)){let c=e.path.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),u=et(c),d=await St(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 c=e.pattern.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");i=new RegExp(`^${c}$`)}catch{return`ERROR: Invalid pattern: ${e.pattern}`}let a=[],l=async(c,u,d)=>{if(u>r)return;let f;try{f=await Fe.readdir(c,{withFileTypes:!0})}catch{return}f=f.filter(p=>!p.name.startsWith(".")&&p.name!=="node_modules");for(let p of f){if(i&&!p.isDirectory()&&!i.test(p.name))continue;let h=p.isDirectory()?"/":"";a.push(`${d}${p.name}${h}`),p.isDirectory()&&await l(he.join(c,p.name),u+1,d+" ")}};return await l(n,1,""),a.join(`
309
- `)||"(empty)"}case"search_files":{let n=et(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 es("grep",o,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),i=r.split("\0"),a=[];for(let l=0;l<i.length;l+=2){let c=i[l],u=i[l+1];if(c&&u){let d=u.split(`
313
+ 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}${b}`}}if(!s.autoConfirm){let u=r.split(i).join(e.new_text),d=await jo(n,u);if($i(n,r,u,{annotations:d}),!await Do(a?"Apply (fuzzy match)":"Apply"))return"CANCELLED: User declined to apply edit."}let c=r.split(i).join(e.new_text);return await Be.writeFile(n,c,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||c.startsWith("#!"))&&await Be.chmod(n,493),bi("edit_file",n,r,c),a?`Edited: ${n} (fuzzy match)`:`Edited: ${n}`}case"list_directory":{let n=tt(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await St(n)){let c=e.path.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),u=tt(c),d=await St(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 c=e.pattern.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");i=new RegExp(`^${c}$`)}catch{return`ERROR: Invalid pattern: ${e.pattern}`}let a=[],l=async(c,u,d)=>{if(u>r)return;let f;try{f=await Be.readdir(c,{withFileTypes:!0})}catch{return}f=f.filter(p=>!p.name.startsWith(".")&&p.name!=="node_modules");for(let p of f){if(i&&!p.isDirectory()&&!i.test(p.name))continue;let m=p.isDirectory()?"/":"";a.push(`${d}${p.name}${m}`),p.isDirectory()&&await l(me.join(c,p.name),u+1,d+" ")}};return await l(n,1,""),a.join(`
314
+ `)||"(empty)"}case"search_files":{let n=tt(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 es("grep",o,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),i=r.split("\0"),a=[];for(let l=0;l<i.length;l+=2){let c=i[l],u=i[l+1];if(c&&u){let d=u.split(`
310
315
  `).filter(f=>f.trim());for(let f of d)if(a.push(`${c}:${f}`),a.length>=50)break}if(a.length>=50)break}return a.join(`
311
- `)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let o=process.cwd(),r=e.path?et(e.path):o,i=e.pattern,a=K=>{let ie=K.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"(.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");return new RegExp(`^${ie}$`)},l=a(i),c=i.split("/").pop(),u=a(c),{ToolProgress:d}=bs(),f=new d("glob","Finding files...");f.start();let{getFileIndex:p,getIndexedCwd:h,refreshIndex:g,isIndexValid:_}=As(),b=p(),O=h();_(r)||(await g(r),b=p());let M=b.filter(K=>l.test(K)||u.test(he.basename(K))).map(K=>he.join(r,K));if(M.length===0)return f.stop(),"(no matches)"+Vl(e.path);let v=await Promise.all(M.slice(0,210).map(async K=>{try{let ie=await Fe.stat(K);return{path:K,mtime:ie.mtimeMs}}catch{return{path:K,mtime:0}}}));v.sort((K,ie)=>ie.mtime-K.mtime);let T=v.map(K=>K.path),N=M.length>200,te=T.slice(0,200).join(`
312
- `);return f.update({count:M.length,detail:e.pattern}),f.stop(),N?`${te}
313
-
314
- \u26A0 Results truncated at 200. Use a more specific pattern.`:te}case"grep":{let n=e.path?et(e.path):process.cwd();if(e.staged){let{getDiff:l}=Dr(),c=await l(!0);if(!c.trim())return"(no staged changes)";let u=new Set,d=c.split(`
315
- `);for(let _ of d)if(_.startsWith("diff --git")){let b=_.match(/diff --git a\/(.+) b\/(.+)/);b&&u.add(b[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:p}=bs(),h=new p("grep","Searching staged content...");h.start();let g=[];for(let _ of u)try{let b=he.join(process.cwd(),_);if(await St(b)){let O=[...f];O.push(e.pattern,b);let{stdout:M}=await es("grep",O,{cwd:process.cwd(),timeout:3e4,maxBuffer:2*1024*1024});if(e.output_mode==="files_with_matches"||e.output_mode==="count"){let v=M.trim().split(`
316
- `).filter(T=>T.trim());g=g.concat(v)}else{let v=M.split("\0");for(let T=0;T<v.length;T+=2){let N=v[T+1];if(N){let te=N.split(`
317
- `).filter(K=>K.trim());for(let K of te)g.push(`${_}:${K}`)}}}}}catch{}return h.update({count:g.length,detail:"in staged files"}),h.stop(),g.join(`
318
- `).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}=bs(),a=new i("grep","Searching...");a.start();try{let{stdout:l}=await es("grep",o,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),c;if(e.output_mode==="files_with_matches"||e.output_mode==="count")c=l.trim().split(`
319
- `).filter(p=>p.trim());else{let p=l.split("\0");c=[];for(let h=0;h<p.length;h+=2){let g=p[h],_=p[h+1];if(g&&_){let b=_.split(`
320
- `).filter(O=>O.trim());for(let O of b)c.push(`${g}:${O}`)}}}let u=e.offset||0,d=e.head_limit||(e.output_mode==="files_with_matches"?200:100);return c=c.slice(u,u+d),a.update({count:c.length,detail:`in ${n}`}),a.stop(),c.join(`
321
- `).trim()||"(no matches)"+Vl(e.path)}catch(l){if(a.stop(),l.code===2){let c=(l.stderr||l.message||"").toString().trim();return c.includes("No such file or directory")?`ERROR: Directory not found: ${n}`:c.includes("Invalid")||c.includes("Unmatched")||c.includes("unterminated")||c.includes("unclosed")||c.includes("parse error")||c.includes("brackets")||c.includes("not balanced")?`ERROR: Invalid regex pattern: ${e.pattern}`:`ERROR: grep failed: ${c.slice(0,200)||"exit code 2"}`}return"(no matches)"+Vl(e.path)}}case"patch_file":{await Jl();let n=et(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await St(n)){let b=await wi(e.path);if(b.fixedPath)n=b.fixedPath,console.log(`${ae.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${he.relative(process.cwd(),n)}${ae.reset}`);else return`ERROR: File not found: ${e.path}${b.message?`
322
- `+b.message:""}`}let r=e.patches;if(!Array.isArray(r)||r.length===0)return"ERROR: No patches provided";let i=await Fe.readFile(n,"utf-8"),{getActiveModelId:a,getActiveProviderName:l}=Ze(),c=om(a(),l()),u=[],d=!1,f=!1;for(let b=0;b<r.length;b++){let{old_text:O,new_text:M}=r[b];if(i.includes(O))u.push({old_text:O,new_text:M});else if(c==="strict"){let v=Io(i,O);return v?`ERROR: Patch ${b+1} old_text not found in ${n} (strict mode \u2014 exact match required)
316
+ `)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let o=process.cwd(),r=e.path?tt(e.path):o,i=e.pattern,a=J=>{let ie=J.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"(.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");return new RegExp(`^${ie}$`)},l=a(i),c=i.split("/").pop(),u=a(c),{ToolProgress:d}=ks(),f=new d("glob","Finding files...");f.start();let{getFileIndex:p,getIndexedCwd:m,refreshIndex:g,isIndexValid:_}=Ns(),b=p(),A=m();_(r)||(await g(r),b=p());let P=b.filter(J=>l.test(J)||u.test(me.basename(J))).map(J=>me.join(r,J));if(P.length===0)return f.stop(),"(no matches)"+sc(e.path);let v=await Promise.all(P.slice(0,210).map(async J=>{try{let ie=await Be.stat(J);return{path:J,mtime:ie.mtimeMs}}catch{return{path:J,mtime:0}}}));v.sort((J,ie)=>ie.mtime-J.mtime);let E=v.map(J=>J.path),O=P.length>200,ne=E.slice(0,200).join(`
317
+ `);return f.update({count:P.length,detail:e.pattern}),f.stop(),O?`${ne}
318
+
319
+ \u26A0 Results truncated at 200. Use a more specific pattern.`:ne}case"grep":{let n=e.path?tt(e.path):process.cwd();if(e.staged){let{getDiff:l}=Br(),c=await l(!0);if(!c.trim())return"(no staged changes)";let u=new Set,d=c.split(`
320
+ `);for(let _ of d)if(_.startsWith("diff --git")){let b=_.match(/diff --git a\/(.+) b\/(.+)/);b&&u.add(b[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:p}=ks(),m=new p("grep","Searching staged content...");m.start();let g=[];for(let _ of u)try{let b=me.join(process.cwd(),_);if(await St(b)){let A=[...f];A.push(e.pattern,b);let{stdout:P}=await es("grep",A,{cwd:process.cwd(),timeout:3e4,maxBuffer:2*1024*1024});if(e.output_mode==="files_with_matches"||e.output_mode==="count"){let v=P.trim().split(`
321
+ `).filter(E=>E.trim());g=g.concat(v)}else{let v=P.split("\0");for(let E=0;E<v.length;E+=2){let O=v[E+1];if(O){let ne=O.split(`
322
+ `).filter(J=>J.trim());for(let J of ne)g.push(`${_}:${J}`)}}}}}catch{}return m.update({count:g.length,detail:"in staged files"}),m.stop(),g.join(`
323
+ `).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}=ks(),a=new i("grep","Searching...");a.start();try{let{stdout:l}=await es("grep",o,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),c;if(e.output_mode==="files_with_matches"||e.output_mode==="count")c=l.trim().split(`
324
+ `).filter(p=>p.trim());else{let p=l.split("\0");c=[];for(let m=0;m<p.length;m+=2){let g=p[m],_=p[m+1];if(g&&_){let b=_.split(`
325
+ `).filter(A=>A.trim());for(let A of b)c.push(`${g}:${A}`)}}}let u=e.offset||0,d=e.head_limit||(e.output_mode==="files_with_matches"?200:100);return c=c.slice(u,u+d),a.update({count:c.length,detail:`in ${n}`}),a.stop(),c.join(`
326
+ `).trim()||"(no matches)"+sc(e.path)}catch(l){if(a.stop(),l.code===2){let c=(l.stderr||l.message||"").toString().trim();return c.includes("No such file or directory")?`ERROR: Directory not found: ${n}`:c.includes("Invalid")||c.includes("Unmatched")||c.includes("unterminated")||c.includes("unclosed")||c.includes("parse error")||c.includes("brackets")||c.includes("not balanced")?`ERROR: Invalid regex pattern: ${e.pattern}`:`ERROR: grep failed: ${c.slice(0,200)||"exit code 2"}`}return"(no matches)"+sc(e.path)}}case"patch_file":{await oc();let n=tt(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await St(n)){let b=await ki(e.path);if(b.fixedPath)n=b.fixedPath,console.log(`${le.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${me.relative(process.cwd(),n)}${le.reset}`);else return`ERROR: File not found: ${e.path}${b.message?`
327
+ `+b.message:""}`}let r=e.patches;if(!Array.isArray(r)||r.length===0)return"ERROR: No patches provided";let i=await Be.readFile(n,"utf-8"),{getActiveModelId:a,getActiveProviderName:l}=Qe(),c=hm(a(),l()),u=[],d=!1,f=!1;for(let b=0;b<r.length;b++){let{old_text:A,new_text:P}=r[b];if(i.includes(A))u.push({old_text:A,new_text:P});else if(c==="strict"){let v=Fo(i,A);return v?`ERROR: Patch ${b+1} old_text not found in ${n} (strict mode \u2014 exact match required)
323
328
  Most similar text (line ${v.line}, distance ${v.distance}):
324
- ${v.text}`:`ERROR: Patch ${b+1} old_text not found in ${n} (strict mode \u2014 exact match required)`}else{let v=nm(i,O);if(v)u.push({old_text:v,new_text:M}),d=!0;else{let T=Io(i,O);if(T){let N=Math.max(3,Math.ceil(O.length*.05));if(T.distance<=N)u.push({old_text:T.text,new_text:M}),f=!0;else return`ERROR: Patch ${b+1} old_text not found in ${n}
325
- Most similar text (line ${T.line}, distance ${T.distance}):
326
- ${T.text}`}else return`ERROR: Patch ${b+1} old_text not found in ${n}`}}}let p=i;for(let{old_text:b,new_text:O}of u)p=p.split(b).join(O);if(!s.autoConfirm){let b=await Po(n,p);if(mi(n,i,p,{annotations:b}),!await Mo(d?"Apply patches (fuzzy match)":"Apply patches"))return"CANCELLED: User declined to apply patches."}await Fe.writeFile(n,p,"utf-8");let h=/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||p.startsWith("#!");h&&await Fe.chmod(n,493),gi("patch_file",n,i,p);let g=f?" (auto-fixed)":d?" (fuzzy match)":"",_=h?" [chmod +x applied]":"";return`Patched: ${n} (${r.length} replacements)${g}${_}`}case"web_fetch":{let n=e.url,o=e.max_length||1e4;try{let i=new URL(n).hostname;if(/^(127\.|10\.|172\.(1[6-9]|2\d|3[01])\.|192\.168\.|169\.254\.|0\.|localhost$|\[::1?\]|\[fd|fc)/i.test(i))return"ERROR: Fetching private/internal addresses is not allowed.";let a=await Kl.get(n,{timeout:15e3,maxContentLength:1048576,responseType:"text",headers:{"User-Agent":"nex-code/0.2.0"}});return(typeof a.data=="string"?a.data:JSON.stringify(a.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 Kl.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]
329
+ ${v.text}`:`ERROR: Patch ${b+1} old_text not found in ${n} (strict mode \u2014 exact match required)`}else{let v=fm(i,A);if(v)u.push({old_text:v,new_text:P}),d=!0;else{let E=Fo(i,A);if(E){let O=Math.max(3,Math.ceil(A.length*.05));if(E.distance<=O)u.push({old_text:E.text,new_text:P}),f=!0;else return`ERROR: Patch ${b+1} old_text not found in ${n}
330
+ Most similar text (line ${E.line}, distance ${E.distance}):
331
+ ${E.text}`}else return`ERROR: Patch ${b+1} old_text not found in ${n}`}}}let p=i;for(let{old_text:b,new_text:A}of u)p=p.split(b).join(A);if(!s.autoConfirm){let b=await jo(n,p);if($i(n,i,p,{annotations:b}),!await Do(d?"Apply patches (fuzzy match)":"Apply patches"))return"CANCELLED: User declined to apply patches."}await Be.writeFile(n,p,"utf-8");let m=/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||p.startsWith("#!");m&&await Be.chmod(n,493),bi("patch_file",n,i,p);let g=f?" (auto-fixed)":d?" (fuzzy match)":"",_=m?" [chmod +x applied]":"";return`Patched: ${n} (${r.length} replacements)${g}${_}`}case"web_fetch":{let n=e.url,o=e.max_length||1e4;try{let i=new URL(n).hostname;if(/^(127\.|10\.|172\.(1[6-9]|2\d|3[01])\.|192\.168\.|169\.254\.|0\.|localhost$|\[::1?\]|\[fd|fc)/i.test(i))return"ERROR: Fetching private/internal addresses is not allowed.";let a=await tc.get(n,{timeout:15e3,maxContentLength:1048576,responseType:"text",headers:{"User-Agent":"nex-code/0.2.0"}});return(typeof a.data=="string"?a.data:JSON.stringify(a.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 tc.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]
327
332
 
328
333
  ${r}`;return i.length>0&&(a+=`
329
334
 
330
335
  Sources:
331
336
  `+i.slice(0,n).map((l,c)=>`${c+1}. ${l}`).join(`
332
- `)),a}catch(o){console.error(`${ae.dim} Perplexity search failed (${o.message}), falling back to DuckDuckGo${ae.reset}`)}try{let r=(await Kl.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,l;for(;(l=a.exec(r))!==null&&i.length<n;){let c=l[1].replace(/.*uddg=/,"").split("&")[0],u=l[2].replace(/<[^>]+>/g,"").trim();try{i.push({title:u,url:decodeURIComponent(c)})}catch{i.push({title:u,url:c})}}return i.length===0?"(no results)":i.map((c,u)=>`${u+1}. ${c.title}
337
+ `)),a}catch(o){console.error(`${le.dim} Perplexity search failed (${o.message}), falling back to DuckDuckGo${le.reset}`)}try{let r=(await tc.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,l;for(;(l=a.exec(r))!==null&&i.length<n;){let c=l[1].replace(/.*uddg=/,"").split("&")[0],u=l[2].replace(/<[^>]+>/g,"").trim();try{i.push({title:u,url:decodeURIComponent(c)})}catch{i.push({title:u,url:c})}}return i.length===0?"(no results)":i.map((c,u)=>`${u+1}. ${c.title}
333
338
  ${c.url}`).join(`
334
339
 
335
340
  `)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:n}=dn();try{let o=await n(e.url,{waitFor:e.wait_for}),r=o.links.length>0?`
@@ -358,12 +363,12 @@ Analyze the screenshot above and provide structured feedback:
358
363
  2. Visual hierarchy (typography, contrast, colors)
359
364
  3. Consistency (margins, padding patterns)
360
365
  4. Responsiveness concerns at this viewport
361
- 5. Specific issues related to: ${r}`;return e.compare_with&&Fs.existsSync(e.compare_with)&&(i+=`
366
+ 5. Specific issues related to: ${r}`;return e.compare_with&&Hs.existsSync(e.compare_with)&&(i+=`
362
367
 
363
- COMPARISON: Previous screenshot at ${e.compare_with} \u2014 describe what changed.`),{text:i,images:[{path:o.path,base64:o.base64,media_type:"image/png"}],compare_with:e.compare_with||null}}catch(o){return`ERROR: ${o.message}`}}case"clipboard_image":try{let{_grabClipboardImage:n}=Ql(),o=n();return o?{text:`Clipboard image captured: ${o.path}
368
+ COMPARISON: Previous screenshot at ${e.compare_with} \u2014 describe what changed.`),{text:i,images:[{path:o.path,base64:o.base64,media_type:"image/png"}],compare_with:e.compare_with||null}}catch(o){return`ERROR: ${o.message}`}}case"clipboard_image":try{let{_grabClipboardImage:n}=ic(),o=n();return o?{text:`Clipboard image captured: ${o.path}
364
369
  Size: ${Math.round(Buffer.from(o.data,"base64").length/1024)} KB
365
370
 
366
- [Clipboard image is attached for visual analysis]`,images:[{path:o.path,base64:o.data,media_type:o.media_type}]}:"No image found in clipboard. Copy a screenshot first (Cmd+Shift+4 on macOS), then try again."}catch(n){return`ERROR: ${n.message}`}case"browser_click":{let{browserClick:n}=dn();try{return await n(e.url,{selector:e.selector,text:e.text})}catch(o){return`ERROR: ${o.message}`}}case"browser_fill":{let{browserFill:n}=dn();try{return await n(e.url,{selector:e.selector,value:e.value,submit:e.submit})}catch(o){return`ERROR: ${o.message}`}}case"visual_diff":try{let{pixelDiff:n}=Yn(),o=n(e.before,e.after,{threshold:e.threshold}),r=o.regionSummary.slice(0,5),i=r.length?r.map(a=>` ${a.name}: ${a.changedPercent}% changed`).join(`
371
+ [Clipboard image is attached for visual analysis]`,images:[{path:o.path,base64:o.data,media_type:o.media_type}]}:"No image found in clipboard. Copy a screenshot first (Cmd+Shift+4 on macOS), then try again."}catch(n){return`ERROR: ${n.message}`}case"browser_click":{let{browserClick:n}=dn();try{return await n(e.url,{selector:e.selector,text:e.text})}catch(o){return`ERROR: ${o.message}`}}case"browser_fill":{let{browserFill:n}=dn();try{return await n(e.url,{selector:e.selector,value:e.value,submit:e.submit})}catch(o){return`ERROR: ${o.message}`}}case"visual_diff":try{let{pixelDiff:n}=Hn(),o=n(e.before,e.after,{threshold:e.threshold}),r=o.regionSummary.slice(0,5),i=r.length?r.map(a=>` ${a.name}: ${a.changedPercent}% changed`).join(`
367
372
  `):" No significant regional changes";return{text:`VISUAL DIFF \u2014 ${o.diffPercent}% of pixels changed
368
373
  Changed: ${o.changedPixels.toLocaleString()} / ${o.totalPixels.toLocaleString()} pixels
369
374
  Canvas: ${o.width}\xD7${o.height}
@@ -372,7 +377,7 @@ Diff image: ${o.diffPath}
372
377
  Regional breakdown:
373
378
  ${i}
374
379
 
375
- [Diff image attached \u2014 red/magenta pixels indicate changes]`,images:[{path:o.diffPath,base64:Fs.readFileSync(o.diffPath).toString("base64"),media_type:"image/png"}]}}catch(n){return`ERROR: ${n.message}`}case"responsive_sweep":try{let{responsiveSweep:n}=Yn(),o=await n(e.url,{viewports:e.viewports,fullPage:e.full_page}),r=o.map(i=>` ${i.label} (${i.width}px): ${i.path}`).join(`
380
+ [Diff image attached \u2014 red/magenta pixels indicate changes]`,images:[{path:o.diffPath,base64:Hs.readFileSync(o.diffPath).toString("base64"),media_type:"image/png"}]}}catch(n){return`ERROR: ${n.message}`}case"responsive_sweep":try{let{responsiveSweep:n}=Hn(),o=await n(e.url,{viewports:e.viewports,fullPage:e.full_page}),r=o.map(i=>` ${i.label} (${i.width}px): ${i.path}`).join(`
376
381
  `);return{text:`RESPONSIVE SWEEP \u2014 ${o.length} viewports captured
377
382
  URL: ${e.url}
378
383
 
@@ -386,15 +391,15 @@ Analyze these screenshots for:
386
391
  2. Typography scaling (text too small on mobile, too large on desktop)
387
392
  3. Navigation pattern changes across viewports
388
393
  4. Image/media sizing and aspect ratio issues
389
- 5. Touch target sizes on mobile viewports`,images:o.map(i=>({path:i.path,base64:i.base64,media_type:i.media_type}))}}catch(n){return`ERROR: ${n.message}`}case"visual_annotate":try{let{annotateImage:n}=Yn(),o=n(e.image,e.annotations),r=e.annotations.length,i=[...new Set(e.annotations.map(a=>a.type))].join(", ");return{text:`ANNOTATED IMAGE \u2014 ${r} annotation(s) added (${i})
394
+ 5. Touch target sizes on mobile viewports`,images:o.map(i=>({path:i.path,base64:i.base64,media_type:i.media_type}))}}catch(n){return`ERROR: ${n.message}`}case"visual_annotate":try{let{annotateImage:n}=Hn(),o=n(e.image,e.annotations),r=e.annotations.length,i=[...new Set(e.annotations.map(a=>a.type))].join(", ");return{text:`ANNOTATED IMAGE \u2014 ${r} annotation(s) added (${i})
390
395
  Source: ${e.image}
391
396
  Output: ${o.path}
392
397
 
393
- [Annotated image attached with visual markers]`,images:[{path:o.path,base64:o.base64,media_type:o.media_type}]}}catch(n){return`ERROR: ${n.message}`}case"visual_watch":try{let{visualWatch:n}=Yn(),o=n(e.url,e.watch,{maxIterations:e.max_iterations||10,hmrDelay:e.hmr_delay||1500}),r=await o.next();if(r.value?.type==="error")return`ERROR: ${r.value.message}`;let i=[];i.push(`VISUAL WATCH \u2014 monitoring ${e.watch.length} path(s)`,`URL: ${e.url}`,`Baseline screenshot: ${r.value?.path}`,"","Watching for file changes... (will capture up to "+(e.max_iterations||10)+" iterations)");let a=await o.next();if(!a.done&&a.value){let l=a.value;i.push("",`--- Iteration ${l.iteration} ---`,`Screenshot: ${l.path}`),l.diff&&i.push(`Diff: ${l.diff.diffPercent}% changed (${l.diff.changedPixels} pixels)`,`Regions: ${l.diff.regions.map(u=>`${u.name}:${u.changedPercent}%`).join(", ")}`);let c=[{path:l.path,base64:l.base64,media_type:l.media_type}];return l.diff?.diffPath&&c.push({path:l.diff.diffPath,base64:Fs.readFileSync(l.diff.diffPath).toString("base64"),media_type:"image/png"}),{text:i.join(`
398
+ [Annotated image attached with visual markers]`,images:[{path:o.path,base64:o.base64,media_type:o.media_type}]}}catch(n){return`ERROR: ${n.message}`}case"visual_watch":try{let{visualWatch:n}=Hn(),o=n(e.url,e.watch,{maxIterations:e.max_iterations||10,hmrDelay:e.hmr_delay||1500}),r=await o.next();if(r.value?.type==="error")return`ERROR: ${r.value.message}`;let i=[];i.push(`VISUAL WATCH \u2014 monitoring ${e.watch.length} path(s)`,`URL: ${e.url}`,`Baseline screenshot: ${r.value?.path}`,"","Watching for file changes... (will capture up to "+(e.max_iterations||10)+" iterations)");let a=await o.next();if(!a.done&&a.value){let l=a.value;i.push("",`--- Iteration ${l.iteration} ---`,`Screenshot: ${l.path}`),l.diff&&i.push(`Diff: ${l.diff.diffPercent}% changed (${l.diff.changedPixels} pixels)`,`Regions: ${l.diff.regions.map(u=>`${u.name}:${u.changedPercent}%`).join(", ")}`);let c=[{path:l.path,base64:l.base64,media_type:l.media_type}];return l.diff?.diffPath&&c.push({path:l.diff.diffPath,base64:Hs.readFileSync(l.diff.diffPath).toString("base64"),media_type:"image/png"}),{text:i.join(`
394
399
  `),images:c}}return{text:i.join(`
395
400
  `)+`
396
401
 
397
- No changes detected within timeout.`,images:r.value?.base64?[{path:r.value.path,base64:r.value.base64,media_type:"image/png"}]:[]}}catch(n){return`ERROR: ${n.message}`}case"design_tokens":try{let{extractDesignTokens:n}=Yn(),o=n(e.image,{sampleRate:e.sample_rate}),r=o.colors.slice(0,12).map(a=>` ${a.hex} ${a.rgb.padEnd(20)} ${a.frequency.toString().padStart(5)}% ${a.category}`).join(`
402
+ No changes detected within timeout.`,images:r.value?.base64?[{path:r.value.path,base64:r.value.base64,media_type:"image/png"}]:[]}}catch(n){return`ERROR: ${n.message}`}case"design_tokens":try{let{extractDesignTokens:n}=Hn(),o=n(e.image,{sampleRate:e.sample_rate}),r=o.colors.slice(0,12).map(a=>` ${a.hex} ${a.rgb.padEnd(20)} ${a.frequency.toString().padStart(5)}% ${a.category}`).join(`
398
403
  `),i=o.spacing.length?o.spacing.map(a=>` ${a.px}px (${a.occurrences} occurrences)`).join(`
399
404
  `):" No clear spacing pattern detected";return`DESIGN TOKENS \u2014 extracted from ${o.dimensions.width}\xD7${o.dimensions.height} image
400
405
  Source: ${o.imagePath}
@@ -408,7 +413,7 @@ ${i}
408
413
  Use these values to:
409
414
  - Compare against CSS variables / design system tokens
410
415
  - Identify inconsistent colors or spacing
411
- - Generate a color palette from the rendered output`}catch(n){return`ERROR: ${n.message}`}case"design_compare":try{let{designCompare:n}=Yn(),o=await n(e.url,e.reference,{width:e.width,height:e.height,threshold:e.threshold}),r=o.regions.filter(i=>i.changedPercent>.5).slice(0,6).map(i=>` ${i.name}: ${i.changedPercent}% deviation`).join(`
416
+ - Generate a color palette from the rendered output`}catch(n){return`ERROR: ${n.message}`}case"design_compare":try{let{designCompare:n}=Hn(),o=await n(e.url,e.reference,{width:e.width,height:e.height,threshold:e.threshold}),r=o.regions.filter(i=>i.changedPercent>.5).slice(0,6).map(i=>` ${i.name}: ${i.changedPercent}% deviation`).join(`
412
417
  `)||" All regions match within tolerance";return{text:`DESIGN COMPARISON \u2014 ${o.diffPercent}% deviation from reference
413
418
  Reference: ${o.referencePath}
414
419
  Live: ${o.livePath}
@@ -420,149 +425,149 @@ Pixel deviation: ${o.changedPixels.toLocaleString()} / ${o.totalPixels.toLocaleS
420
425
  Regional breakdown:
421
426
  ${r}
422
427
 
423
- [Three images attached: live screenshot, pixel diff, annotated deviation map]`,images:[{path:o.livePath,base64:o.liveBase64,media_type:"image/png"},{path:o.diffPath,base64:o.diffBase64,media_type:"image/png"},{path:o.annotatedPath,base64:o.annotatedBase64,media_type:"image/png"}]}}catch(n){return`ERROR: ${n.message}`}case"ask_user":{let{question:n,options:o=[]}=e;return Zl?new Promise(r=>{ts=()=>r("CANCELLED"),Zl(n,o).then(i=>{ts=null,r(i||"User did not answer")})}):new Promise(r=>{let i=require("readline").createInterface({input:process.stdin,output:process.stdout});ts=()=>{i.close(),r("CANCELLED")};let a=o.length>0?`
428
+ [Three images attached: live screenshot, pixel diff, annotated deviation map]`,images:[{path:o.livePath,base64:o.liveBase64,media_type:"image/png"},{path:o.diffPath,base64:o.diffBase64,media_type:"image/png"},{path:o.annotatedPath,base64:o.annotatedBase64,media_type:"image/png"}]}}catch(n){return`ERROR: ${n.message}`}case"ask_user":{let{question:n,options:o=[]}=e;return rc?new Promise(r=>{ts=()=>r("CANCELLED"),rc(n,o).then(i=>{ts=null,r(i||"User did not answer")})}):new Promise(r=>{let i=require("readline").createInterface({input:process.stdin,output:process.stdout});ts=()=>{i.close(),r("CANCELLED")};let a=o.length>0?`
424
429
  ${o.map((l,c)=>` ${c+1}. ${l}`).join(`
425
430
  `)}
426
431
  `:"";console.log(`
427
- ${ae.cyan}${ae.bold} ? ${n}${ae.reset}${a}`),i.question(`${ae.cyan} > ${ae.reset}`,l=>{ts=null,i.close(),r(l.trim()||"(no response)")})})}case"git_status":{if(!await Xl())return"ERROR: Not a git repository";let n=await tm()||"(detached)",o=await Bk();if(o.length===0)return`Branch: ${n}
432
+ ${le.cyan}${le.bold} ? ${n}${le.reset}${a}`),i.question(`${le.cyan} > ${le.reset}`,l=>{ts=null,i.close(),r(l.trim()||"(no response)")})})}case"git_status":{if(!await nc())return"ERROR: Not a git repository";let n=await dm()||"(detached)",o=await iS();if(o.length===0)return`Branch: ${n}
428
433
  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(`
429
- `)}case"git_diff":{if(!await Xl())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 Uk(!!e.staged);return n||"(no diff)"}case"git_log":{if(!await Xl())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}=Rl(),{getActiveTaskProgress:l}=Ke(),c=l();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 c||console.log(`
434
+ `)}case"git_diff":{if(!await nc())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 aS(!!e.staged);return n||"(no diff)"}case"git_log":{if(!await nc())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}=Pl(),{getActiveTaskProgress:l}=Ke(),c=l();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 c||console.log(`
430
435
  `+i()),`Created task list "${e.name}" with ${u.length} tasks:
431
436
  `+u.map(d=>` ${d.id}: ${d.description}`).join(`
432
437
  `)}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)?(c||console.log(`
433
438
  `+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":(c||console.log(`
434
- `+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}=Il();return n(e)}case"switch_model":{let{setActiveModel:n,getActiveProviderName:o,getActiveModelId:r}=Ze();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 es("gh",o,{cwd:process.cwd(),timeout:3e4}),i=JSON.parse(r||"[]");return i.length===0?"No workflow runs found.":i.map(l=>{let c=l.conclusion||l.status||"unknown",u=c==="success"?"\u2713":c==="failure"?"\u2717":c==="in_progress"?"\u283F":"\u25CB",d=l.updatedAt?new Date(l.updatedAt).toISOString().slice(0,16).replace("T"," "):"";return`${u} [${l.databaseId}] ${l.name} \xB7 ${l.headBranch} \xB7 ${c} \xB7 ${d}`}).join(`
439
+ `+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,executeSpawnAgentsBackground:o}=Wl();return e.agents?.some(r=>r.background)?o(e):n(e)}case"switch_model":{let{setActiveModel:n,getActiveProviderName:o,getActiveModelId:r}=Qe();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 es("gh",o,{cwd:process.cwd(),timeout:3e4}),i=JSON.parse(r||"[]");return i.length===0?"No workflow runs found.":i.map(l=>{let c=l.conclusion||l.status||"unknown",u=c==="success"?"\u2713":c==="failure"?"\u2717":c==="in_progress"?"\u283F":"\u25CB",d=l.updatedAt?new Date(l.updatedAt).toISOString().slice(0,16).replace("T"," "):"";return`${u} [${l.databaseId}] ${l.name} \xB7 ${l.headBranch} \xB7 ${c} \xB7 ${d}`}).join(`
435
440
  `)}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(`
436
441
  `)[0]}`}}case"gh_run_view":{if(!e.run_id)return"ERROR: run_id is required";if(!/^\d+$/.test(String(e.run_id)))return"ERROR: run_id must be numeric";try{if(e.log){let{stdout:i}=await es("gh",["run","view",String(e.run_id),"--log"],{cwd:process.cwd(),timeout:6e4,maxBuffer:5242880});return i.substring(0,8e3)+(i.length>8e3?`
437
442
  ...(truncated)`:"")}let{stdout:n}=await es("gh",["run","view",String(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 l of i.steps||[]){if(l.conclusion==="failure"||l.conclusion==="skipped")continue;let c=l.conclusion==="success"?" \u2713":l.conclusion==="failure"?" \u2717":" \u25CB";r.push(` ${c} ${l.name}`)}}return r.join(`
438
443
  `)}catch(n){return`ERROR: ${(n.stderr||n.message||"").toString().split(`
439
- `)[0]}`}}case"gh_workflow_trigger":{if(!e.workflow)return"ERROR: workflow is required";if(!/^[\w./-]+$/.test(e.workflow))return"ERROR: invalid workflow name";let{confirm:n}=co(),o=e.branch||await tm()||"main";if(!/^[\w./-]+$/.test(o))return"ERROR: invalid branch name";let r=["workflow","run",e.workflow,"--ref",o];if(e.inputs)for(let[a,l]of Object.entries(e.inputs)){if(!/^[\w-]+$/.test(a))return`ERROR: invalid input key: ${a}`;r.push("-f",`${a}=${l}`)}if(console.log(`
440
- ${ae.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${o}${ae.reset}`),!await n(" Trigger?"))return"CANCELLED: User declined to trigger workflow.";try{return await es("gh",r,{cwd:process.cwd(),timeout:3e4}),`Workflow "${e.workflow}" triggered on branch "${o}". Check status with gh_run_list.`}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
441
- `)[0]}`}}case"k8s_pods":{let n=e.namespace?`-n ${e.namespace}`:"-A",o=e.label?`-l ${e.label}`:"",r=Lo(`get pods ${n} ${o} -o wide`.trim(),e);try{let{stdout:i,stderr:a}=await je(r,{timeout:3e4,maxBuffer:2097152});return(i||a||"(no pods)").trim()}catch(i){let a=(i.stderr||i.message||"").toString().split(`
442
- `)[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=Lo(r,e);try{let{stdout:a,stderr:l}=await je(i,{timeout:6e4,maxBuffer:5242880}),c=(a||l||"(no logs)").trim();return c.substring(0,2e4)+(c.length>2e4?`
444
+ `)[0]}`}}case"gh_workflow_trigger":{if(!e.workflow)return"ERROR: workflow is required";if(!/^[\w./-]+$/.test(e.workflow))return"ERROR: invalid workflow name";let{confirm:n}=ho(),o=e.branch||await dm()||"main";if(!/^[\w./-]+$/.test(o))return"ERROR: invalid branch name";let r=["workflow","run",e.workflow,"--ref",o];if(e.inputs)for(let[a,l]of Object.entries(e.inputs)){if(!/^[\w-]+$/.test(a))return`ERROR: invalid input key: ${a}`;r.push("-f",`${a}=${l}`)}if(console.log(`
445
+ ${le.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${o}${le.reset}`),!await n(" Trigger?"))return"CANCELLED: User declined to trigger workflow.";try{return await es("gh",r,{cwd:process.cwd(),timeout:3e4}),`Workflow "${e.workflow}" triggered on branch "${o}". Check status with gh_run_list.`}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
446
+ `)[0]}`}}case"k8s_pods":{let n=e.namespace?`-n ${e.namespace}`:"-A",o=e.label?`-l ${e.label}`:"",r=qo(`get pods ${n} ${o} -o wide`.trim(),e);try{let{stdout:i,stderr:a}=await je(r,{timeout:3e4,maxBuffer:2097152});return(i||a||"(no pods)").trim()}catch(i){let a=(i.stderr||i.message||"").toString().split(`
447
+ `)[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=qo(r,e);try{let{stdout:a,stderr:l}=await je(i,{timeout:6e4,maxBuffer:5242880}),c=(a||l||"(no logs)").trim();return c.substring(0,2e4)+(c.length>2e4?`
443
448
  ...(truncated)`:"")}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
444
449
  `)[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(`
445
- ${ae.yellow} \u26A0 kubectl exec into pod: ${e.pod} (ns: ${n})${ae.reset}`),console.log(`${ae.dim} Command: ${e.command}${ae.reset}`),!await Ht(" 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=Lo(r,e);try{let{stdout:a,stderr:l}=await je(i,{timeout:6e4,maxBuffer:2097152});return(a||l||"(no output)").trim()}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
450
+ ${le.yellow} \u26A0 kubectl exec into pod: ${e.pod} (ns: ${n})${le.reset}`),console.log(`${le.dim} Command: ${e.command}${le.reset}`),!await Ht(" 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=qo(r,e);try{let{stdout:a,stderr:l}=await je(i,{timeout:6e4,maxBuffer:2097152});return(a||l||"(no output)").trim()}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
446
451
  `)[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(`
447
- ${ae.yellow} \u26A0 kubectl apply: ${i}${e.namespace?` (ns: ${e.namespace})`:""}${ae.reset}`),!await Ht(" 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=Lo(o,e);try{let{stdout:i,stderr:a}=await je(r,{timeout:12e4,maxBuffer:2097152});return(i||a||"(no output)").trim()}catch(i){return`ERROR: ${(i.stderr||i.message||"").toString().split(`
452
+ ${le.yellow} \u26A0 kubectl apply: ${i}${e.namespace?` (ns: ${e.namespace})`:""}${le.reset}`),!await Ht(" 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=qo(o,e);try{let{stdout:i,stderr:a}=await je(r,{timeout:12e4,maxBuffer:2097152});return(i||a||"(no output)").trim()}catch(i){return`ERROR: ${(i.stderr||i.message||"").toString().split(`
448
453
  `)[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(`
449
- ${ae.yellow} \u26A0 ${a}: deployment/${e.deployment} (ns: ${n})${ae.reset}`),!await Ht(` ${a}?`))return"CANCELLED: User declined."}let r=`rollout ${e.action} deployment/${e.deployment} -n ${n}`,i=Lo(r,e);try{let{stdout:a,stderr:l}=await je(i,{timeout:12e4,maxBuffer:2097152});return(a||l||"(no output)").trim()}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
450
- `)[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}=Hl(),{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 l=o(r),c=l.content?l.content+`
454
+ ${le.yellow} \u26A0 ${a}: deployment/${e.deployment} (ns: ${n})${le.reset}`),!await Ht(` ${a}?`))return"CANCELLED: User declined."}let r=`rollout ${e.action} deployment/${e.deployment} -n ${n}`,i=qo(r,e);try{let{stdout:a,stderr:l}=await je(i,{timeout:12e4,maxBuffer:2097152});return(a||l||"(no output)").trim()}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
455
+ `)[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}=Jl(),{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 l=o(r),c=l.content?l.content+`
451
456
 
452
- `+i:i;return n(r,c),`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=Pt(e.server)}catch(N){return`ERROR: ${N.message}`}let o=e.command,r=!!e.sudo,i=(e.timeout||30)*1e3,a=Lk(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:
457
+ `+i:i;return n(r,c),`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=Pt(e.server)}catch(O){return`ERROR: ${O.message}`}let o=e.command,r=!!e.sudo,i=(e.timeout||30)*1e3,a=eS(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:
453
458
  grep -n "pattern" /path/to/file -A 50
454
459
  or to read the whole file:
455
460
  cat /path/to/file
456
461
  NEVER use sed -n again \u2014 it will always be blocked.`:`BLOCKED: Remote command matches SSH secret-exposure pattern: ${a}
457
- 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,(N,te,K)=>{let ie=Math.min(Number(K),20);return`${te} ${ie}`}),o=o.replace(/(--(?:before|after|context)=)(\d+)/g,(N,te,K)=>te+Math.min(Number(K),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 N=n.user?`${n.user}@${n.host}`:n.host;if(console.log(`
458
- ${ae.yellow} \u26A0 Remote command on ${N}: ${o}${ae.reset}`),!await Ht(" Execute on remote server?"))return"CANCELLED: User declined to execute remote command."}let{stdout:c,stderr:u,exitCode:d,error:f}=await ht(n,o,{timeout:i,sudo:r}),p=[c,u].filter(Boolean).join(`
459
- `).trim();if(d!==0){if(/no such file or directory/i.test(p)){let te=p.match(/['"]?([/\w._-]+\.\w+)['"]?:\s*No such file/i),K=o.match(/(?:cat|head|tail|less|grep\s+\S+\s+|ls\s+|stat\s+|wc\s+|file\s+)['"]?([/\w._-]+)['"]?/),ie=te&&te[1]||K&&K[1];if(ie)try{let{remoteAutoFixPath:le}=Os(),ne=ie.startsWith("/")?ie.split("/").slice(0,-1).join("/").replace(/\/[^/]+$/,"")||"/":"/home/"+(n.user||"root"),k=await le(n,ne,ie);if(k.fixedPath){let ve=o.replace(ie,k.fixedPath);console.log(`${ae.dim} \u2713 remote auto-fix: ${ie} \u2192 ${k.fixedPath}${ae.reset}`);let H=await ht(n,ve,{timeout:i,sudo:r}),X=[H.stdout,H.stderr].filter(Boolean).join(`
460
- `).trim();if(H.exitCode===0)return`${k.message}
461
- ${X}`||"(command completed, no output)"}else if(k.message)return`EXIT ${d}
462
+ 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,(O,ne,J)=>{let ie=Math.min(Number(J),20);return`${ne} ${ie}`}),o=o.replace(/(--(?:before|after|context)=)(\d+)/g,(O,ne,J)=>ne+Math.min(Number(J),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 O=n.user?`${n.user}@${n.host}`:n.host;if(console.log(`
463
+ ${le.yellow} \u26A0 Remote command on ${O}: ${o}${le.reset}`),!await Ht(" Execute on remote server?"))return"CANCELLED: User declined to execute remote command."}let{stdout:c,stderr:u,exitCode:d,error:f}=await ht(n,o,{timeout:i,sudo:r}),p=[c,u].filter(Boolean).join(`
464
+ `).trim();if(d!==0){if(/no such file or directory/i.test(p)){let ne=p.match(/['"]?([/\w._-]+\.\w+)['"]?:\s*No such file/i),J=o.match(/(?:cat|head|tail|less|grep\s+\S+\s+|ls\s+|stat\s+|wc\s+|file\s+)['"]?([/\w._-]+)['"]?/),ie=ne&&ne[1]||J&&J[1];if(ie)try{let{remoteAutoFixPath:ce}=Ms(),se=ie.startsWith("/")?ie.split("/").slice(0,-1).join("/").replace(/\/[^/]+$/,"")||"/":"/home/"+(n.user||"root"),S=await ce(n,se,ie);if(S.fixedPath){let Ee=o.replace(ie,S.fixedPath);console.log(`${le.dim} \u2713 remote auto-fix: ${ie} \u2192 ${S.fixedPath}${le.reset}`);let W=await ht(n,Ee,{timeout:i,sudo:r}),Z=[W.stdout,W.stderr].filter(Boolean).join(`
465
+ `).trim();if(W.exitCode===0)return`${S.message}
466
+ ${Z}`||"(command completed, no output)"}else if(S.message)return`EXIT ${d}
462
467
  ${f||p}
463
468
 
464
- ${k.message}`}catch{}}return`EXIT ${d}
465
- ${f||p||"(no output)"}`}let h=/\bgrep\b/.test(o),g=p;h&&(g=g.split(`
466
- `).filter(N=>N!=="--").join(`
467
- `));let _=h?60:100,b=g.split(`
469
+ ${S.message}`}catch{}}return`EXIT ${d}
470
+ ${f||p||"(no output)"}`}let m=/\bgrep\b/.test(o),g=p;m&&(g=g.split(`
471
+ `).filter(O=>O!=="--").join(`
472
+ `));let _=m?60:100,b=g.split(`
468
473
  `);b.length>_&&(g=`(${b.length-_} earlier lines omitted \u2014 showing last ${_})
469
474
  `+b.slice(-_).join(`
470
- `));let O=4,M=g.split(`
471
- `),v=[],T=0;for(;T<M.length;){let N=T+1;for(;N<M.length&&M[N]===M[T];)N++;let te=N-T;if(v.push(M[T]),te>O)v.push(`... (${te-1} identical lines omitted)`);else for(let K=1;K<te;K++)v.push(M[T]);T=N}return v.join(`
475
+ `));let A=4,P=g.split(`
476
+ `),v=[],E=0;for(;E<P.length;){let O=E+1;for(;O<P.length&&P[O]===P[E];)O++;let ne=O-E;if(v.push(P[E]),ne>A)v.push(`... (${ne-1} identical lines omitted)`);else for(let J=1;J<ne;J++)v.push(P[E]);E=O}return v.join(`
472
477
  `)||"(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=Pt(e.server)}catch(i){return`ERROR: ${i.message}`}let o=n.user?`${n.user}@${n.host}`:n.host;if(console.log(`
473
- ${ae.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${o}:${e.remote_path}${ae.reset}`),!await Ht(" Upload to remote server?"))return"CANCELLED: User declined upload.";try{let i=await Hk(n,e.local_path,e.remote_path);try{Os().clearRemoteIndex()}catch{}return i}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=Pt(e.server)}catch(o){return`ERROR: ${o.message}`}try{return await sm(n,e.remote_path,e.local_path)}catch(o){if(/no such file|not found/i.test(o.message))try{let{remoteAutoFixPath:r}=Os(),i=e.remote_path.split("/").slice(0,-1).join("/")||"/",a=await r(n,i,e.remote_path);if(a.fixedPath){console.log(`${ae.dim} \u2713 remote auto-fix: ${e.remote_path} \u2192 ${a.fixedPath}${ae.reset}`);let l=await sm(n,a.fixedPath,e.local_path);return`${a.message}
478
+ ${le.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${o}:${e.remote_path}${le.reset}`),!await Ht(" Upload to remote server?"))return"CANCELLED: User declined upload.";try{let i=await cS(n,e.local_path,e.remote_path);try{Ms().clearRemoteIndex()}catch{}return i}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=Pt(e.server)}catch(o){return`ERROR: ${o.message}`}try{return await pm(n,e.remote_path,e.local_path)}catch(o){if(/no such file|not found/i.test(o.message))try{let{remoteAutoFixPath:r}=Ms(),i=e.remote_path.split("/").slice(0,-1).join("/")||"/",a=await r(n,i,e.remote_path);if(a.fixedPath){console.log(`${le.dim} \u2713 remote auto-fix: ${e.remote_path} \u2192 ${a.fixedPath}${le.reset}`);let l=await pm(n,a.fixedPath,e.local_path);return`${a.message}
474
479
  ${l}`}if(a.message)return`ERROR: ${o.message}
475
480
 
476
481
  ${a.message}`}catch{}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||"~").replace(/[^a-zA-Z0-9_/~.-]/g,""),l=(e.model||"").replace(/[^a-zA-Z0-9_:.-]/g,""),u=['TMPFILE=$(mktemp /tmp/nexcode-XXXXXX.txt) && chmod 600 "$TMPFILE"',`echo "${Buffer.from(e.task).toString("base64")}" | base64 -d > "$TMPFILE"`,`cd "${a}" 2>/dev/null || true`,l?`nex-code --prompt-file "$TMPFILE" --auto --model "${l}" 2>&1`:'nex-code --prompt-file "$TMPFILE" --auto 2>&1',"EXIT_CODE=$?",'rm -f "$TMPFILE"',"exit $EXIT_CODE"].join(" && "),{spawnSync:d}=require("child_process"),f=d("ssh",[...i,"-o","StrictHostKeyChecking=accept-new","-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 p=(f.stdout||"")+(f.stderr||"");return f.status!==0?`Remote nex-code exited with code ${f.status}.
477
482
  ${p.slice(-2e3)}`:p.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=Pt(e.server)}catch(l){return`ERROR: ${l.message}`}if(!r){let l=o?"local machine":i.user?`${i.user}@${i.host}`:i.host;if(console.log(`
478
- ${ae.yellow} \u26A0 Service: systemctl ${e.action} ${e.service} on ${l}${ae.reset}`),!await Ht(" Execute?"))return"CANCELLED: User declined service action."}let a=`systemctl ${e.action} ${e.service}`;if(o){let c=e.action!=="status"?`sudo ${a}`:a;try{let{stdout:u,stderr:d}=await je(c,{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}
483
+ ${le.yellow} \u26A0 Service: systemctl ${e.action} ${e.service} on ${l}${le.reset}`),!await Ht(" Execute?"))return"CANCELLED: User declined service action."}let a=`systemctl ${e.action} ${e.service}`;if(o){let c=e.action!=="status"?`sudo ${a}`:a;try{let{stdout:u,stderr:d}=await je(c,{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}
479
484
  ${d}`}}else{let{stdout:l,stderr:c,exitCode:u,error:d}=await ht(i,a,{timeout:15e3,sudo:!0}),f=[l,c].filter(Boolean).join(`
480
485
  `).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}
481
- ${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:h,stderr:g}=await je(a,{timeout:15e3});return(h||g||"(no log output)").trim()}catch(h){return`EXIT ${h.code||1}
482
- ${(h.stderr||h.message||"").toString().trim()}`}let l;try{l=Pt(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:c,stderr:u,exitCode:d,error:f}=await ht(l,a,{timeout:2e4}),p=[c,u].filter(Boolean).join(`
486
+ ${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 je(a,{timeout:15e3});return(m||g||"(no log output)").trim()}catch(m){return`EXIT ${m.code||1}
487
+ ${(m.stderr||m.message||"").toString().trim()}`}let l;try{l=Pt(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:c,stderr:u,exitCode:d,error:f}=await ht(l,a,{timeout:2e4}),p=[c,u].filter(Boolean).join(`
483
488
  `).trim();return d!==0?`EXIT ${d}
484
489
  ${f||p||"(no output)"}`:p||"(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:p}=await je(r,{timeout:1e4});return(f||p||"(no containers)").trim()}catch(f){return`EXIT ${f.code||1}
485
490
  ${(f.stderr||f.message||"").toString().trim()}`}let i;try{i=Pt(e.server)}catch(f){return`ERROR: ${f.message}`}let{stdout:a,stderr:l,exitCode:c,error:u}=await ht(i,r,{timeout:15e3}),d=[a,l].filter(Boolean).join(`
486
491
  `).trim();return c!==0?`EXIT ${c}
487
- ${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:p,stderr:h}=await je(i,{timeout:15e3});return(p||h||"(no log output)").trim()}catch(p){return`EXIT ${p.code||1}
492
+ ${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:p,stderr:m}=await je(i,{timeout:15e3});return(p||m||"(no log output)").trim()}catch(p){return`EXIT ${p.code||1}
488
493
  ${(p.stderr||p.message||"").toString().trim()}`}let a;try{a=Pt(e.server)}catch(p){return`ERROR: ${p.message}`}let{stdout:l,stderr:c,exitCode:u,error:d}=await ht(a,i,{timeout:2e4}),f=[l,c].filter(Boolean).join(`
489
494
  `).trim();return u!==0?`EXIT ${u}
490
- ${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 h=n?"local":e.server;if(console.log(`
491
- ${ae.yellow} \u26A0 docker exec in ${e.container} on ${h}: ${e.command}${ae.reset}`),!await Ht(" 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:h,stderr:g}=await je(a,{timeout:3e4});return(h||g||"(no output)").trim()}catch(h){return`EXIT ${h.code||1}
492
- ${(h.stderr||h.message||"").toString().trim()}`}let l;try{l=Pt(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:c,stderr:u,exitCode:d,error:f}=await ht(l,a,{timeout:35e3}),p=[c,u].filter(Boolean).join(`
495
+ ${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(`
496
+ ${le.yellow} \u26A0 docker exec in ${e.container} on ${m}: ${e.command}${le.reset}`),!await Ht(" 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 je(a,{timeout:3e4});return(m||g||"(no output)").trim()}catch(m){return`EXIT ${m.code||1}
497
+ ${(m.stderr||m.message||"").toString().trim()}`}let l;try{l=Pt(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:c,stderr:u,exitCode:d,error:f}=await ht(l,a,{timeout:35e3}),p=[c,u].filter(Boolean).join(`
493
498
  `).trim();return d!==0?`EXIT ${d}
494
- ${f||p}`:p||"(no output)"}case"container_manage":{if(!e.container)return"ERROR: container is required";if(!e.action)return"ERROR: action is required";let 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 h=o?"local":e.server;if(console.log(`
495
- ${ae.yellow} \u26A0 docker ${e.action} ${e.container} on ${h}${ae.reset}`),!await Ht(" 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:h,stderr:g}=await je(a,{timeout:3e4});return(h||g||`docker ${e.action} ${e.container}: OK`).trim()}catch(h){return`EXIT ${h.code||1}
496
- ${(h.stderr||h.message||"").toString().trim()}`}let l;try{l=Pt(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:c,stderr:u,exitCode:d,error:f}=await ht(l,a,{timeout:35e3}),p=[c,u].filter(Boolean).join(`
499
+ ${f||p}`:p||"(no output)"}case"container_manage":{if(!e.container)return"ERROR: container is required";if(!e.action)return"ERROR: action is required";let 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(`
500
+ ${le.yellow} \u26A0 docker ${e.action} ${e.container} on ${m}${le.reset}`),!await Ht(" 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 je(a,{timeout:3e4});return(m||g||`docker ${e.action} ${e.container}: OK`).trim()}catch(m){return`EXIT ${m.code||1}
501
+ ${(m.stderr||m.message||"").toString().trim()}`}let l;try{l=Pt(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:c,stderr:u,exitCode:d,error:f}=await ht(l,a,{timeout:35e3}),p=[c,u].filter(Boolean).join(`
497
502
  `).trim();return d!==0?`EXIT ${d}
498
- ${f||p}`:p||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...Yk(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=Pt(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(`
499
- ${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(`
500
- ${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 Ht(" 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}:
503
+ ${f||p}`:p||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...uS(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=Pt(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(`
504
+ ${le.yellow} \u26A0 Deploy [git pull]: ${r}:${e.remote_path}${d}${le.reset}`)}else{let d=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`;console.log(`
505
+ ${le.yellow} \u26A0 Deploy [rsync]: ${d} \u2192 ${r}:${e.remote_path}${le.reset}`)}if(e.deploy_script&&console.log(`${le.yellow} Then run: ${e.deploy_script}${le.reset}`),e.health_check&&console.log(`${le.yellow} Health check: ${e.health_check}${le.reset}`),!await Ht(" 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}:
501
506
  ${f}${e.deploy_script?`
502
- ${e.deploy_script}`:""}`;let{stdout:p,stderr:h,exitCode:g,error:_}=await ht(o,f,{timeout:12e4});if(i=[p,h].filter(Boolean).join(`
507
+ ${e.deploy_script}`:""}`;let{stdout:p,stderr:m,exitCode:g,error:_}=await ht(o,f,{timeout:12e4});if(i=[p,m].filter(Boolean).join(`
503
508
  `).trim(),g!==0)return`ERROR (git pull, exit ${g}):
504
- ${_||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":"",p=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`,h=`rsync -avz --delete ${f} ${d} ${u} ${p} ${r}:${e.remote_path}`.trim().replace(/\s+/g," ");try{let{stdout:g,stderr:_}=await je(h,{timeout:12e4});i=(g||_||"").trim()}catch(g){return`ERROR (rsync): ${(g.stderr||g.message||"").toString().trim()}`}if(e.dry_run)return`DRY RUN [rsync]:
505
- ${i||"(nothing to sync)"}`}let a="";if(e.deploy_script){let{stdout:u,stderr:d,exitCode:f,error:p}=await ht(o,e.deploy_script,{timeout:12e4}),h=[u,d].filter(Boolean).join(`
509
+ ${_||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":"",p=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`,m=`rsync -avz --delete ${f} ${d} ${u} ${p} ${r}:${e.remote_path}`.trim().replace(/\s+/g," ");try{let{stdout:g,stderr:_}=await je(m,{timeout:12e4});i=(g||_||"").trim()}catch(g){return`ERROR (rsync): ${(g.stderr||g.message||"").toString().trim()}`}if(e.dry_run)return`DRY RUN [rsync]:
510
+ ${i||"(nothing to sync)"}`}let a="";if(e.deploy_script){let{stdout:u,stderr:d,exitCode:f,error:p}=await ht(o,e.deploy_script,{timeout:12e4}),m=[u,d].filter(Boolean).join(`
506
511
  `).trim();if(f!==0)return`${n==="git"?"git pull":"rsync"} OK
507
512
 
508
513
  ERROR (deploy_script, exit ${f}):
509
- ${p||h}`;a=`
514
+ ${p||m}`;a=`
510
515
 
511
516
  Deploy script output:
512
- ${h||"(no output)"}`}let l="";if(e.health_check){let u=e.health_check.trim();if(/^https?:\/\//.test(u))try{let f=require("node-fetch"),p=await Promise.race([f(u),new Promise((h,g)=>setTimeout(()=>g(new Error("timeout")),15e3))]);if(p.ok)l=`
517
+ ${m||"(no output)"}`}let l="";if(e.health_check){let u=e.health_check.trim();if(/^https?:\/\//.test(u))try{let f=require("node-fetch"),p=await Promise.race([f(u),new Promise((m,g)=>setTimeout(()=>g(new Error("timeout")),15e3))]);if(p.ok)l=`
513
518
 
514
519
  Health check: \u2713 ${u} \u2192 ${p.status}`;else return l=`
515
520
 
516
521
  Health check FAILED: ${u} \u2192 HTTP ${p.status}`,(n==="git"?"git pull OK":"rsync OK")+i+a+l}catch(f){return l=`
517
522
 
518
- Health check FAILED: ${u} \u2192 ${f.message}`,(n==="git"?"git pull OK":"rsync OK")+i+a+l}else{let{stdout:f,stderr:p,exitCode:h}=await ht(o,u,{timeout:15e3}),g=[f,p].filter(Boolean).join(`
519
- `).trim();if(h!==0)return l=`
523
+ Health check FAILED: ${u} \u2192 ${f.message}`,(n==="git"?"git pull OK":"rsync OK")+i+a+l}else{let{stdout:f,stderr:p,exitCode:m}=await ht(o,u,{timeout:15e3}),g=[f,p].filter(Boolean).join(`
524
+ `).trim();if(m!==0)return l=`
520
525
 
521
- Health check FAILED (exit ${h}): ${g}`,(n==="git"?"git pull OK":"rsync OK")+i+a+l;l=`
526
+ Health check FAILED (exit ${m}): ${g}`,(n==="git"?"git pull OK":"rsync OK")+i+a+l;l=`
522
527
 
523
528
  Health check: \u2713 ${g||"(exit 0)"}`}}let c=n==="git"?`${r}:${e.remote_path}`:`${e.local_path} \u2192 ${r}:${e.remote_path}`;return`Deployed [${n}] ${c}
524
- ${i}${a}${l}`.trim()}case"deployment_status":{let n=Gk(),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 l=Pt(a.server||i),u=(await ht(l,"echo OK",{timeout:1e4})).stdout.trim()==="OK",d="unknown";if(u&&a.deploy_script){let p=a.deploy_script.match(/systemctl\s+\w+\s+(\S+)/);if(p)try{d=(await ht(l,`systemctl is-active ${p[1]}`,{timeout:1e4})).stdout.trim()}catch{d="inactive"}}let f="N/A";if(a.health_check){let p=a.health_check.trim();if(/^https?:\/\//.test(p))try{let h=require("node-fetch"),g=await Promise.race([h(p),new Promise((_,b)=>setTimeout(()=>b(new Error("timeout")),1e4))]);f=g.ok?"healthy":`HTTP ${g.status}`}catch(h){f=`unhealthy: ${h.message.substring(0,50)}`}else try{f=(await ht(l,p,{timeout:1e4})).exitCode===0?"healthy":"unhealthy"}catch{f="unhealthy"}}r.push(`${i}: server=${u?"reachable":"unreachable"} service=${d} health=${f}`)}catch(l){r.push(`${i}: ERROR \u2014 ${l.message}`)}}return`Deployment Status:
529
+ ${i}${a}${l}`.trim()}case"deployment_status":{let n=dS(),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 l=Pt(a.server||i),u=(await ht(l,"echo OK",{timeout:1e4})).stdout.trim()==="OK",d="unknown";if(u&&a.deploy_script){let p=a.deploy_script.match(/systemctl\s+\w+\s+(\S+)/);if(p)try{d=(await ht(l,`systemctl is-active ${p[1]}`,{timeout:1e4})).stdout.trim()}catch{d="inactive"}}let f="N/A";if(a.health_check){let p=a.health_check.trim();if(/^https?:\/\//.test(p))try{let m=require("node-fetch"),g=await Promise.race([m(p),new Promise((_,b)=>setTimeout(()=>b(new Error("timeout")),1e4))]);f=g.ok?"healthy":`HTTP ${g.status}`}catch(m){f=`unhealthy: ${m.message.substring(0,50)}`}else try{f=(await ht(l,p,{timeout:1e4})).exitCode===0?"healthy":"unhealthy"}catch{f="unhealthy"}}r.push(`${i}: server=${u?"reachable":"unreachable"} service=${d} health=${f}`)}catch(l){r.push(`${i}: ERROR \u2014 ${l.message}`)}}return`Deployment Status:
525
530
  ${r.join(`
526
- `)}`}case"frontend_recon":{let n=process.cwd(),o=(e.type||"").toLowerCase(),r=[],i=async(v,T=120)=>{try{let N=he.isAbsolute(v)?v:he.join(n,v),K=(await Fe.readFile(N,"utf8")).split(`
527
- `),ie=K.slice(0,T).join(`
528
- `);return K.length>T?ie+`
529
- ... (${K.length-T} more lines \u2014 use read_file for full content)`:ie}catch{return null}},l=["node_modules",".git","dist","build","vendor",".next","__pycache__","venv",".venv"].map(v=>`-not -path "*/${v}/*"`).join(" "),c=async v=>{try{let{stdout:T}=await je(`find "${n}" -type f -name "${v}" ${l} 2>/dev/null | head -10`,{timeout:8e3});return T.trim().split(`
530
- `).filter(Boolean)}catch{return[]}},u=async(v,T)=>{try{let{stdout:N}=await je(`grep -rl "${v}" "${n}" --include="${T}" --exclude-dir=node_modules --exclude-dir=.git --exclude-dir=dist --exclude-dir=build 2>/dev/null | head -5`,{timeout:8e3});return N.trim().split(`
531
+ `)}`}case"frontend_recon":{let n=process.cwd(),o=(e.type||"").toLowerCase(),r=[],i=async(v,E=120)=>{try{let O=me.isAbsolute(v)?v:me.join(n,v),J=(await Be.readFile(O,"utf8")).split(`
532
+ `),ie=J.slice(0,E).join(`
533
+ `);return J.length>E?ie+`
534
+ ... (${J.length-E} more lines \u2014 use read_file for full content)`:ie}catch{return null}},l=["node_modules",".git","dist","build","vendor",".next","__pycache__","venv",".venv"].map(v=>`-not -path "*/${v}/*"`).join(" "),c=async v=>{try{let{stdout:E}=await je(`find "${n}" -type f -name "${v}" ${l} 2>/dev/null | head -10`,{timeout:8e3});return E.trim().split(`
535
+ `).filter(Boolean)}catch{return[]}},u=async(v,E)=>{try{let{stdout:O}=await je(`grep -rl "${v}" "${n}" --include="${E}" --exclude-dir=node_modules --exclude-dir=.git --exclude-dir=dist --exclude-dir=build 2>/dev/null | head -5`,{timeout:8e3});return O.trim().split(`
531
536
  `).filter(Boolean)}catch{return[]}};r.push(`## STEP 1: Design Tokens
532
- `);let d=[...await c("tailwind.config.js"),...await c("tailwind.config.ts"),...await c("tailwind.config.mjs")];if(d.length>0){let v=await i(d[0],80);v&&r.push(`### Tailwind config (${he.relative(n,d[0])})
537
+ `);let d=[...await c("tailwind.config.js"),...await c("tailwind.config.ts"),...await c("tailwind.config.mjs")];if(d.length>0){let v=await i(d[0],80);v&&r.push(`### Tailwind config (${me.relative(n,d[0])})
533
538
  \`\`\`js
534
539
  ${v}
535
- \`\`\``)}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"],p=!1;for(let v of f){let T=await c(v);for(let N of T){let te=await i(N,100);if(te&&te.includes(":root")){r.push(`### CSS Variables (${he.relative(n,N)})
540
+ \`\`\``)}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"],p=!1;for(let v of f){let E=await c(v);for(let O of E){let ne=await i(O,100);if(ne&&ne.includes(":root")){r.push(`### CSS Variables (${me.relative(n,O)})
536
541
  \`\`\`css
537
- ${te}
538
- \`\`\``),p=!0;break}}if(p)break}if(!p){let v=await u(":root","*.css");if(v.length>0){let T=await i(v[0],100);T&&r.push(`### CSS Variables (${he.relative(n,v[0])})
542
+ ${ne}
543
+ \`\`\``),p=!0;break}}if(p)break}if(!p){let v=await u(":root","*.css");if(v.length>0){let E=await i(v[0],100);E&&r.push(`### CSS Variables (${me.relative(n,v[0])})
539
544
  \`\`\`css
540
- ${T}
545
+ ${E}
541
546
  \`\`\``),p=!0}}p||r.push("(no CSS custom properties / :root found)"),r.push(`
542
547
  ## STEP 2: Main Layout / Index Page
543
- `);let h=["base.html","_base.html","layout.html","base.jinja","App.vue","App.jsx","App.tsx","_app.jsx","_app.tsx","_app.js","layout.vue","index.html"],g=!1;for(let v of h){let T=await c(v);if(T.length>0){let N=await i(T[0],150);if(N){r.push(`### Main layout: ${he.relative(n,T[0])}
548
+ `);let m=["base.html","_base.html","layout.html","base.jinja","App.vue","App.jsx","App.tsx","_app.jsx","_app.tsx","_app.js","layout.vue","index.html"],g=!1;for(let v of m){let E=await c(v);if(E.length>0){let O=await i(E[0],150);if(O){r.push(`### Main layout: ${me.relative(n,E[0])}
544
549
  \`\`\`html
545
- ${N}
550
+ ${O}
546
551
  \`\`\``),g=!0;break}}}g||r.push("(no main layout/index file found \u2014 try read_file on your root template manually)"),r.push(`
547
552
  ## STEP 3: Reference Component (same type)
548
553
  `);let _=[];if(o){for(let v of["*.html","*.vue","*.jsx","*.tsx"])if(_=await u(o,v),_.length>0)break}if(_.length===0)try{let{stdout:v}=await je(`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});_=v.trim().split(`
549
- `).filter(Boolean)}catch{_=[]}if(_.length>0){let v=_[0],T=await i(v,150);T?r.push(`### Reference: ${he.relative(n,v)}
554
+ `).filter(Boolean)}catch{_=[]}if(_.length>0){let v=_[0],E=await i(v,150);E?r.push(`### Reference: ${me.relative(n,v)}
550
555
  \`\`\`html
551
- ${T}
556
+ ${E}
552
557
  \`\`\``):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(`
553
558
  ## STEP 4: Framework Stack
554
- `);let b=[],O=await i(he.join(n,"package.json"),999);if(O){if((O.includes('"react"')||O.includes("'react'"))&&b.push("React"),O.includes('"vue"')||O.includes("'vue'")){let T=O.match(/"vue":\s*"[\^~]?(\d+)/);b.push(T?`Vue.js v${T[1]}`:"Vue.js")}let v=O.match(/"alpinejs":\s*"[\^~]?(\d+)/);v&&b.push(`Alpine.js v${v[1]} (\u26A0 v2 vs v3 API differs!)`),(O.includes('"htmx')||O.includes("'htmx"))&&b.push("HTMX"),O.includes('"tailwindcss"')&&b.push("Tailwind CSS"),O.includes('"bootstrap"')&&b.push("Bootstrap")}if((await St(he.join(n,"manage.py"))||(await i(he.join(n,"requirements.txt"),50)||"").includes("Django"))&&b.push("Django (server-rendered templates)"),!b.some(v=>v.includes("Alpine"))){let v=await u("alpinejs","*.html");if(v.length>0){let N=(await i(v[0],30)||"").match(/alpinejs[@/]v?(\d)/);b.push(N?`Alpine.js v${N[1]} (via CDN \u2014 \u26A0 v2 vs v3 API differs!)`:"Alpine.js (via CDN \u2014 check version!)")}}return b.some(v=>v.includes("HTMX"))||(await u("htmx","*.html")).length>0&&b.push("HTMX (via CDN)"),b.length>0?(r.push(b.map(v=>`- ${v}`).join(`
559
+ `);let b=[],A=await i(me.join(n,"package.json"),999);if(A){if((A.includes('"react"')||A.includes("'react'"))&&b.push("React"),A.includes('"vue"')||A.includes("'vue'")){let E=A.match(/"vue":\s*"[\^~]?(\d+)/);b.push(E?`Vue.js v${E[1]}`:"Vue.js")}let v=A.match(/"alpinejs":\s*"[\^~]?(\d+)/);v&&b.push(`Alpine.js v${v[1]} (\u26A0 v2 vs v3 API differs!)`),(A.includes('"htmx')||A.includes("'htmx"))&&b.push("HTMX"),A.includes('"tailwindcss"')&&b.push("Tailwind CSS"),A.includes('"bootstrap"')&&b.push("Bootstrap")}if((await St(me.join(n,"manage.py"))||(await i(me.join(n,"requirements.txt"),50)||"").includes("Django"))&&b.push("Django (server-rendered templates)"),!b.some(v=>v.includes("Alpine"))){let v=await u("alpinejs","*.html");if(v.length>0){let O=(await i(v[0],30)||"").match(/alpinejs[@/]v?(\d)/);b.push(O?`Alpine.js v${O[1]} (via CDN \u2014 \u26A0 v2 vs v3 API differs!)`:"Alpine.js (via CDN \u2014 check version!)")}}return b.some(v=>v.includes("HTMX"))||(await u("htmx","*.html")).length>0&&b.push("HTMX (via CDN)"),b.length>0?(r.push(b.map(v=>`- ${v}`).join(`
555
560
  `)),r.push(`
556
561
  \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(`
557
562
  ---
558
563
  \u2705 Design recon complete. Now build consistently with the patterns above.`),r.join(`
559
- `)}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=Pt(e.server)}catch(l){return`ERROR: ${l.message}`}let r=async(l,c=3e4)=>{if(n)try{let{stdout:u,stderr:d}=await je(l,{timeout:c});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:p}=await ht(o,l,{timeout:c}),h=[u,d].filter(Boolean).join(`
564
+ `)}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=Pt(e.server)}catch(l){return`ERROR: ${l.message}`}let r=async(l,c=3e4)=>{if(n)try{let{stdout:u,stderr:d}=await je(l,{timeout:c});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:p}=await ht(o,l,{timeout:c}),m=[u,d].filter(Boolean).join(`
560
565
  `).trim();return{out:p&&f!==0&&!u.trim()?(p+`
561
- `+h).trim():h,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 l=n?"local":e.server;if(!await Ht(`sysadmin [${e.action}] on ${l} \u2014 proceed?`))return"Cancelled."}switch(e.action){case"audit":{let l=["echo '=== OS / KERNEL ==='","cat /etc/os-release 2>/dev/null | grep -E '^(NAME|VERSION)=' || uname -a","echo '=== UPTIME / LOAD ==='","uptime","echo '=== MEMORY / SWAP ==='","free -h","echo '=== DISK ==='","df -h --output=target,size,used,avail,pcent 2>/dev/null || df -h","echo '=== TOP 10 PROCESSES (CPU) ==='","ps aux --sort=-%cpu | head -11","echo '=== FAILED SYSTEMD UNITS ==='","systemctl list-units --state=failed --no-legend 2>/dev/null || echo '(systemctl not available)'","echo '=== RECENT ERRORS (journalctl) ==='","journalctl -p err --no-pager -n 15 2>/dev/null || echo '(journalctl not available)'","echo '=== LISTENING PORTS ==='","ss -tlnp 2>/dev/null || netstat -tlnp 2>/dev/null || echo '(ss/netstat not available)'"].join(" && "),{out:c,exitCode:u}=await r(l,45e3);return c||`EXIT ${u}
566
+ `+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 l=n?"local":e.server;if(!await Ht(`sysadmin [${e.action}] on ${l} \u2014 proceed?`))return"Cancelled."}switch(e.action){case"audit":{let l=["echo '=== OS / KERNEL ==='","cat /etc/os-release 2>/dev/null | grep -E '^(NAME|VERSION)=' || uname -a","echo '=== UPTIME / LOAD ==='","uptime","echo '=== MEMORY / SWAP ==='","free -h","echo '=== DISK ==='","df -h --output=target,size,used,avail,pcent 2>/dev/null || df -h","echo '=== TOP 10 PROCESSES (CPU) ==='","ps aux --sort=-%cpu | head -11","echo '=== FAILED SYSTEMD UNITS ==='","systemctl list-units --state=failed --no-legend 2>/dev/null || echo '(systemctl not available)'","echo '=== RECENT ERRORS (journalctl) ==='","journalctl -p err --no-pager -n 15 2>/dev/null || echo '(journalctl not available)'","echo '=== LISTENING PORTS ==='","ss -tlnp 2>/dev/null || netstat -tlnp 2>/dev/null || echo '(ss/netstat not available)'"].join(" && "),{out:c,exitCode:u}=await r(l,45e3);return c||`EXIT ${u}
562
567
  (no output)`}case"disk_usage":{let l=e.path||"/",c=`df -h ${l}; echo '--- Top subdirs ---'; du -d1 -x -h ${l} 2>/dev/null | sort -rh | head -20`,{out:u,exitCode:d}=await r(c,3e4);return d!==0?`EXIT ${d}
563
568
  ${u}`:u}case"process_list":{let l=e.sort_by==="mem"?"4":"3",c=(e.limit||20)+1,u=`ps aux --sort=-${e.sort_by==="mem"?"%mem":"%cpu"} 2>/dev/null | head -${c} || ps aux | awk 'NR==1{print; next} {print | "sort -k${l} -rn"}' | head -${c}`,{out:d,exitCode:f}=await r(u,15e3);return f!==0?`EXIT ${f}
564
569
  ${d}`:d}case"network_status":{let l="ss -tlnp 2>/dev/null || netstat -tlnp 2>/dev/null; echo '--- Active connections ---'; ss -tnp 2>/dev/null | head -30",{out:c,exitCode:u}=await r(l,15e3);return u!==0?`EXIT ${u}
565
- ${c}`:c}case"package":{if(!e.package_action)return"ERROR: package_action is required for action=package";let{out:l}=await r("which dnf 2>/dev/null && echo dnf || (which apt-get 2>/dev/null && echo apt) || echo unknown",1e4),c=l.includes("dnf")?"dnf":l.includes("apt")?"apt":null;if(!c)return"ERROR: No supported package manager found (dnf/apt)";let u=(e.packages||[]).join(" "),d;switch(e.package_action){case"list":d=c==="dnf"?"dnf list installed 2>/dev/null | head -60":"dpkg -l | head -60";break;case"check":{let h=c==="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(h,6e4);return g||"(no output from package check)"}case"install":if(!u)return"ERROR: packages required for install";d=c==="dnf"?`dnf install -y ${u}`:`apt-get install -y ${u}`;break;case"remove":if(!u)return"ERROR: packages required for remove";d=c==="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=c==="dnf"?`dnf update -y ${u}`:`apt-get install -y --only-upgrade ${u}`;break;case"upgrade":d=c==="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:p}=await r(d,12e4);return p!==0?`EXIT ${p}
570
+ ${c}`:c}case"package":{if(!e.package_action)return"ERROR: package_action is required for action=package";let{out:l}=await r("which dnf 2>/dev/null && echo dnf || (which apt-get 2>/dev/null && echo apt) || echo unknown",1e4),c=l.includes("dnf")?"dnf":l.includes("apt")?"apt":null;if(!c)return"ERROR: No supported package manager found (dnf/apt)";let u=(e.packages||[]).join(" "),d;switch(e.package_action){case"list":d=c==="dnf"?"dnf list installed 2>/dev/null | head -60":"dpkg -l | head -60";break;case"check":{let m=c==="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=c==="dnf"?`dnf install -y ${u}`:`apt-get install -y ${u}`;break;case"remove":if(!u)return"ERROR: packages required for remove";d=c==="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=c==="dnf"?`dnf update -y ${u}`:`apt-get install -y --only-upgrade ${u}`;break;case"upgrade":d=c==="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:p}=await r(d,12e4);return p!==0?`EXIT ${p}
566
571
  ${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 l=`awk -F: '$3 >= 1000 && $1 != "nobody" {print $1, "uid="$3, "gid="$4, "shell="$7}' /etc/passwd`,{out:c,exitCode:u}=await r(l,1e4);return u!==0?`EXIT ${u}
567
572
  ${c}`:c||"(no regular users)"}case"info":{if(!e.user)return"ERROR: user is required for user_action=info";let l=`id ${e.user} && echo '--- Groups ---' && groups ${e.user} && echo '--- Last login ---' && lastlog -u ${e.user} 2>/dev/null`,{out:c,exitCode:u}=await r(l,1e4);return u!==0?`EXIT ${u}
568
573
  ${c}`:c}case"create":{if(!e.user)return"ERROR: user is required for user_action=create";let c=`useradd -m ${(e.groups||[]).map(f=>`-G ${f}`).join(" ")} ${e.user} && echo "User ${e.user} created"`,{out:u,exitCode:d}=await r(c,15e3);return d!==0?`EXIT ${d}
@@ -600,8 +605,8 @@ ${u}`:u||"(empty log)"}case"find_large":{let l=e.path||"/",c=e.limit||20,u=e.min
600
605
  ${f}`:f||`(no files larger than ${u} in ${l})`}case"service":{if(!e.service_action)return"ERROR: service_action is required for action=service";if(e.service_action!=="list_failed"&&!e.service_name)return"ERROR: service_name is required (except for list_failed)";let l=e.service_name?e.service_name.includes(".")?e.service_name:`${e.service_name}.service`:"",c;switch(e.service_action){case"status":c=`systemctl status ${l} --no-pager -l 2>&1 | head -40`;break;case"list_failed":c="systemctl list-units --state=failed --no-legend 2>/dev/null";break;case"start":c=`systemctl start ${l} && systemctl status ${l} --no-pager -l 2>&1 | head -20`;break;case"stop":c=`systemctl stop ${l} && echo "${l} stopped"`;break;case"restart":c=`systemctl restart ${l} && systemctl status ${l} --no-pager -l 2>&1 | head -20`;break;case"reload":c=`systemctl reload ${l} 2>&1 || systemctl reload-or-restart ${l} 2>&1`;break;case"enable":c=`systemctl enable ${l} && echo "${l} enabled"`;break;case"disable":c=`systemctl disable ${l} && echo "${l} disabled"`;break;default:return`ERROR: Unknown service_action: ${e.service_action}`}let{out:u,exitCode:d}=await r(c,3e4);return d===0||e.service_action==="status"&&d===3?u||`service ${e.service_action} OK`:`EXIT ${d}
601
606
  ${u}`}case"kill_process":{if(!e.pid&&!e.process_name)return"ERROR: pid or process_name is required for kill_process";let l=e.signal||"SIGTERM",c;e.pid?c=`ps -p ${e.pid} -o pid,user,%cpu,%mem,etime,cmd 2>/dev/null && kill -${l} ${e.pid} && echo "Sent ${l} to PID ${e.pid}"`:c=`pgrep -a "${e.process_name}" 2>/dev/null | head -5 && pkill -${l} "${e.process_name}" && echo "Sent ${l} to all '${e.process_name}' processes"`;let{out:u,exitCode:d}=await r(c,15e3);return d!==0?`EXIT ${d}
602
607
  ${u}`:u}case"journalctl":{let l=e.lines||100,c=["journalctl","--no-pager","-n",String(l)];e.unit&&c.push("-u",e.unit.includes(".")?e.unit:`${e.unit}.service`),e.priority&&c.push("-p",e.priority),e.since&&c.push(`--since="${e.since}"`),c.push('2>/dev/null || echo "(journalctl not available)"');let{out:u,exitCode:d}=await r(c.join(" "),2e4);return d!==0?`EXIT ${d}
603
- ${u}`:u||"(no log entries)"}default:return`ERROR: Unknown sysadmin action: ${e.action}`}}case"save_memory":{let{saveMemory:n}=Oo(),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}=Oo();return n(e.type,e.name)?`Memory deleted: ${e.type}/${e.name}`:`Memory not found: ${e.type}/${e.name}`}default:{let{executePluginTool:n}=Ur(),o=await n(t,e,s);return o!==null?o:`ERROR: Unknown tool: ${t}`}}}async function sS(t,e,s={}){let{emit:n}=Ur(),{logToolExecution:o}=Qh(),r=Date.now(),i=s.silent?null:Fk(t,e);if(!i){let l=await am(t,e,s);return o({tool:t,args:e,result:l,duration:Date.now()-r,success:!l.startsWith?.("ERROR")}),await n("onToolResult",{tool:t,args:e,result:l}),l}let a=new qk(i);a.start();try{let l=await am(t,e,s);return a.stop(),o({tool:t,args:e,result:l,duration:Date.now()-r,success:!l.startsWith?.("ERROR")}),await n("onToolResult",{tool:t,args:e,result:l}),l}catch(l){throw a.stop(),o({tool:t,args:e,result:l.message,duration:Date.now()-r,success:!1}),l}}um.exports={TOOL_DEFINITIONS:nS,executeTool:sS,resolvePath:et,autoFixPath:wi,autoFixEdit:cm,enrichBashError:lm,cancelPendingAskUser:Qk,setAskUserHandler:eS,fileExists:St}});var Rs=Z((l1,fm)=>{fm.exports=dm()});var tc=Z((u1,pm)=>{var{loadServerProfiles:Do,resolveProfile:c1,sshExec:oS}=Os(),ec={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 rS(){let t=Do();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}`:"",l=r.os?` \u2014 OS: ${r.os}`:"",c=r.sudo?", sudo available":"";s.push(`- **${o}**: ${i}${a}${l}${c}`)}let n=new Set;for(let o of Object.values(t))o.os&&ec[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 ec[o])s.push(`- ${i}`)}}return s.join(`
604
- `)}function iS(t){let e=Do();return Object.values(e).some(s=>s.os&&s.os.startsWith(t))}function aS(){return Object.keys(Do())}function lS(){let t=require("fs"),s=require("path").join(process.cwd(),"NEX.md"),n="";try{n=t.readFileSync(s,"utf-8")}catch{}let o=Do(),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 c=r.map(f=>{let p=o[f],h=p.user?`${p.user}@${p.host}`:p.host,g=p.port&&Number(p.port)!==22?`:${p.port}`:"";return` - **${f}**: ${h}${g}${p.os?` (${p.os})`:""}`}).join(`
608
+ ${u}`:u||"(no log entries)"}default:return`ERROR: Unknown sysadmin action: ${e.action}`}}case"save_memory":{let{saveMemory:n}=Lo(),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}=Lo();return n(e.type,e.name)?`Memory deleted: ${e.type}/${e.name}`:`Memory not found: ${e.type}/${e.name}`}default:{let{executePluginTool:n}=Gr(),o=await n(t,e,s);return o!==null?o:`ERROR: Unknown tool: ${t}`}}}async function xS(t,e,s={}){let{emit:n}=Gr(),{logToolExecution:o}=cm(),r=Date.now(),i=s.silent?null:rS(t,e);if(!i){let l=await ym(t,e,s);return o({tool:t,args:e,result:l,duration:Date.now()-r,success:!l.startsWith?.("ERROR")}),await n("onToolResult",{tool:t,args:e,result:l}),l}let a=new oS(i);a.start();try{let l=await ym(t,e,s);return a.stop(),o({tool:t,args:e,result:l,duration:Date.now()-r,success:!l.startsWith?.("ERROR")}),await n("onToolResult",{tool:t,args:e,result:l}),l}catch(l){throw a.stop(),o({tool:t,args:e,result:l.message,duration:Date.now()-r,success:!1}),l}}$m.exports={TOOL_DEFINITIONS:bS,executeTool:xS,resolvePath:tt,autoFixPath:ki,autoFixEdit:_m,enrichBashError:wm,cancelPendingAskUser:wS,setAskUserHandler:_S,fileExists:St}});var As=Q((R1,xm)=>{xm.exports=bm()});var lc=Q((A1,km)=>{var{loadServerProfiles:Bo,resolveProfile:C1,sshExec:kS}=Ms(),ac={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 SS(){let t=Bo();if(Object.keys(t).length===0)return null;let s=["## Remote Servers (.nex/servers.json)"];s.push(""),s.push("Available server profiles (use with ssh_exec, ssh_upload, ssh_download, service_manage, service_logs, container_list, container_logs, container_exec, container_manage, deploy):");for(let[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}`:"",l=r.os?` \u2014 OS: ${r.os}`:"",c=r.sudo?", sudo available":"";s.push(`- **${o}**: ${i}${a}${l}${c}`)}let n=new Set;for(let o of Object.values(t))o.os&&ac[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 ac[o])s.push(`- ${i}`)}}return s.join(`
609
+ `)}function vS(t){let e=Bo();return Object.values(e).some(s=>s.os&&s.os.startsWith(t))}function ES(){return Object.keys(Bo())}function TS(){let t=require("fs"),s=require("path").join(process.cwd(),"NEX.md"),n="";try{n=t.readFileSync(s,"utf-8")}catch{}let o=Bo(),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 c=r.map(f=>{let p=o[f],m=p.user?`${p.user}@${p.host}`:p.host,g=p.port&&Number(p.port)!==22?`:${p.port}`:"";return` - **${f}**: ${m}${g}${p.os?` (${p.os})`:""}`}).join(`
605
610
  `),u=r.map(f=>o[f].log_path).filter(Boolean),d=u.length>0?`
606
611
  - Server log paths: ${u.join(", ")}`:"";return`# Deployment Context (Auto-detected)
607
612
 
@@ -619,7 +624,7 @@ ${c}
619
624
  - \u274C Do NOT \`read_file\` on paths like \`logs/\` \u2014 these files do not exist locally
620
625
  - \u274C Do NOT \`list_directory\` on server paths \u2014 the local project is the source, not the running instance
621
626
 
622
- **When in doubt:** If a path contains \`logs/\`, \`/var/log/\`, or \`/home/<user>/\` \u2014 it is on the server. SSH there.${cS(o)}`}function cS(t){return Object.values(t).some(s=>s.host==="94.130.37.43")?`
627
+ **When in doubt:** If a path contains \`logs/\`, \`/var/log/\`, or \`/home/<user>/\` \u2014 it is on the server. SSH there.${RS(o)}`}function RS(t){return Object.values(t).some(s=>s.host==="94.130.37.43")?`
623
628
 
624
629
  ## Server Debugging Rules
625
630
 
@@ -630,35 +635,35 @@ ${c}
630
635
  - CRITICAL: When the user pastes a server error message (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.
631
636
  - LOG FILES: Always check the CURRENT log first: /home/deploy/server-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.
632
637
  - 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.
633
- - 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 uS(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=Do();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[l,c]of Object.entries(s))if(a.includes(l.toLowerCase())){n=c,o=l;break}if(n)break;for(let[l,c]of Object.entries(s))if(c.host===i){n=c,o=l;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 oS(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]
634
- `+i.trim()}catch{return null}}pm.exports={getServerContext:rS,getDeploymentContextBlock:lS,hasServerOS:iS,getProfileNames:aS,probeUrlServer:uS,OS_HINTS:ec}});var wm=Z((d1,ym)=>{var mt=require("fs").promises,mm=require("fs"),Ge=require("path"),_i=require("util").promisify(require("child_process").exec),{C:Bs}=Ke(),{getMergeConflicts:gm}=Dr(),{getServerContext:dS}=tc(),fS=new Set(["node_modules",".git",".svn","dist","build","coverage",".nyc_output","__pycache__",".DS_Store",".next",".nuxt",".turbo",".cache","vendor","tmp","temp"]);function pS(t){try{return mm.readFileSync(t,"utf-8").split(`
635
- `).map(s=>s.trim()).filter(s=>s&&!s.startsWith("#")&&!s.startsWith("!")).map(s=>s.replace(/\/$/,""))}catch{return[]}}function hS(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 mS(t,{maxDepth:e=3,maxFiles:s=200,giPatterns:n=[]}={}){let o=Ge.join(t,".gitignore"),r=[...n,...pS(o)],i=0,a=[Ge.basename(t)+"/"];function l(c,u,d){if(d>e||i>=s)return;let f;try{f=mm.readdirSync(c,{withFileTypes:!0})}catch{return}f.sort((h,g)=>h.isDirectory()!==g.isDirectory()?h.isDirectory()?-1:1:h.name.localeCompare(g.name));let p=f.filter(h=>!(fS.has(h.name)||h.name.startsWith(".")&&h.name!==".env.example"||hS(h.name,r)));for(let h=0;h<p.length;h++){if(i>=s){a.push(`${u}\u2514\u2500\u2500 \u2026 (truncated)`);break}let g=p[h],_=h===p.length-1,b=_?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",O=u+(_?" ":"\u2502 "),M=g.isDirectory()?g.name+"/":g.name;a.push(`${u}${b}${M}`),i++,g.isDirectory()&&l(Ge.join(c,g.name),O,d+1)}}return l(t,"",1),a.join(`
636
- `)}var nc=new Map,Ws=new Map,$i=null,hm=3e4,Us={result:null,expiry:0,cwd:null};async function tn(t){try{return await t()}catch{return null}}async function gS(){if(!$i||Date.now()>$i)return!1;let t=[Ge.join(process.cwd(),"package.json"),Ge.join(process.cwd(),"README.md"),Ge.join(process.cwd(),".gitignore")];for(let e of t)try{let s=await mt.stat(e),n=Ws.get(e);if(!n||s.mtimeMs!==n)return!1}catch{if(Ws.has(e))return!1}try{let e=Ge.join(process.cwd(),".git","HEAD"),s=await mt.stat(e),n=Ws.get(e);if(!n||s.mtimeMs!==n)return!1}catch{}return!0}async function yS(){let t=[Ge.join(process.cwd(),"package.json"),Ge.join(process.cwd(),"README.md"),Ge.join(process.cwd(),".gitignore"),Ge.join(process.cwd(),".git","HEAD"),Ge.join(process.cwd(),"CLAUDE.md"),Ge.join(process.cwd(),".nex","CLAUDE.md")];for(let e of t)try{let s=await mt.stat(e);Ws.set(e,s.mtimeMs)}catch{Ws.delete(e)}}async function wS(t){let e="fileContext",s=nc.get(e),n=!1;if(s&&await gS()&&(n=!0),!n){let c=[],u=Ge.join(t,"package.json");if(await tn(()=>mt.access(u).then(()=>!0).catch(()=>!1)))try{let v=await mt.readFile(u,"utf-8"),T=JSON.parse(v),N={name:T.name,version:T.version};T.scripts&&(N.scripts=Object.keys(T.scripts).slice(0,15)),T.dependencies&&(N.deps=Object.keys(T.dependencies).length),T.devDependencies&&(N.devDeps=Object.keys(T.devDependencies).length),c.push(`PACKAGE: ${JSON.stringify(N)}`)}catch{}let f=Ge.join(t,"README.md");if(await tn(()=>mt.access(f).then(()=>!0).catch(()=>!1))){let T=(await mt.readFile(f,"utf-8")).split(`
638
+ - 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 CS(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=Bo();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[l,c]of Object.entries(s))if(a.includes(l.toLowerCase())){n=c,o=l;break}if(n)break;for(let[l,c]of Object.entries(s))if(c.host===i){n=c,o=l;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 kS(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]
639
+ `+i.trim()}catch{return null}}km.exports={getServerContext:SS,getDeploymentContextBlock:TS,hasServerOS:vS,getProfileNames:ES,probeUrlServer:CS,OS_HINTS:ac}});var Rm=Q((O1,Tm)=>{var mt=require("fs").promises,vm=require("fs"),Ge=require("path"),Si=require("util").promisify(require("child_process").exec),{C:Ys}=Ke(),{getMergeConflicts:Em}=Br(),{getServerContext:AS}=lc(),OS=new Set(["node_modules",".git",".svn","dist","build","coverage",".nyc_output","__pycache__",".DS_Store",".next",".nuxt",".turbo",".cache","vendor","tmp","temp"]);function NS(t){try{return vm.readFileSync(t,"utf-8").split(`
640
+ `).map(s=>s.trim()).filter(s=>s&&!s.startsWith("#")&&!s.startsWith("!")).map(s=>s.replace(/\/$/,""))}catch{return[]}}function MS(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 PS(t,{maxDepth:e=3,maxFiles:s=200,giPatterns:n=[]}={}){let o=Ge.join(t,".gitignore"),r=[...n,...NS(o)],i=0,a=[Ge.basename(t)+"/"];function l(c,u,d){if(d>e||i>=s)return;let f;try{f=vm.readdirSync(c,{withFileTypes:!0})}catch{return}f.sort((m,g)=>m.isDirectory()!==g.isDirectory()?m.isDirectory()?-1:1:m.name.localeCompare(g.name));let p=f.filter(m=>!(OS.has(m.name)||m.name.startsWith(".")&&m.name!==".env.example"||MS(m.name,r)));for(let m=0;m<p.length;m++){if(i>=s){a.push(`${u}\u2514\u2500\u2500 \u2026 (truncated)`);break}let g=p[m],_=m===p.length-1,b=_?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",A=u+(_?" ":"\u2502 "),P=g.isDirectory()?g.name+"/":g.name;a.push(`${u}${b}${P}`),i++,g.isDirectory()&&l(Ge.join(c,g.name),A,d+1)}}return l(t,"",1),a.join(`
641
+ `)}var cc=new Map,zs=new Map,vi=null,Sm=3e4,Gs={result:null,expiry:0,cwd:null};async function tn(t){try{return await t()}catch{return null}}async function LS(){if(!vi||Date.now()>vi)return!1;let t=[Ge.join(process.cwd(),"package.json"),Ge.join(process.cwd(),"README.md"),Ge.join(process.cwd(),".gitignore")];for(let e of t)try{let s=await mt.stat(e),n=zs.get(e);if(!n||s.mtimeMs!==n)return!1}catch{if(zs.has(e))return!1}try{let e=Ge.join(process.cwd(),".git","HEAD"),s=await mt.stat(e),n=zs.get(e);if(!n||s.mtimeMs!==n)return!1}catch{}return!0}async function IS(){let t=[Ge.join(process.cwd(),"package.json"),Ge.join(process.cwd(),"README.md"),Ge.join(process.cwd(),".gitignore"),Ge.join(process.cwd(),".git","HEAD"),Ge.join(process.cwd(),"CLAUDE.md"),Ge.join(process.cwd(),".nex","CLAUDE.md")];for(let e of t)try{let s=await mt.stat(e);zs.set(e,s.mtimeMs)}catch{zs.delete(e)}}async function DS(t){let e="fileContext",s=cc.get(e),n=!1;if(s&&await LS()&&(n=!0),!n){let c=[],u=Ge.join(t,"package.json");if(await tn(()=>mt.access(u).then(()=>!0).catch(()=>!1)))try{let v=await mt.readFile(u,"utf-8"),E=JSON.parse(v),O={name:E.name,version:E.version};E.scripts&&(O.scripts=Object.keys(E.scripts).slice(0,15)),E.dependencies&&(O.deps=Object.keys(E.dependencies).length),E.devDependencies&&(O.devDeps=Object.keys(E.devDependencies).length),c.push(`PACKAGE: ${JSON.stringify(O)}`)}catch{}let f=Ge.join(t,"README.md");if(await tn(()=>mt.access(f).then(()=>!0).catch(()=>!1))){let E=(await mt.readFile(f,"utf-8")).split(`
637
642
  `).slice(0,50);c.push(`README (first 50 lines):
638
- ${T.join(`
639
- `)}`)}let h=Ge.join(t,".gitignore");if(await tn(()=>mt.access(h).then(()=>!0).catch(()=>!1))){let v=await mt.readFile(h,"utf-8");c.push(`GITIGNORE:
643
+ ${E.join(`
644
+ `)}`)}let m=Ge.join(t,".gitignore");if(await tn(()=>mt.access(m).then(()=>!0).catch(()=>!1))){let v=await mt.readFile(m,"utf-8");c.push(`GITIGNORE:
640
645
  ${v.trim()}`)}let _=Ge.join(t,"CLAUDE.md");if(await tn(()=>mt.access(_).then(()=>!0).catch(()=>!1))){let v=await mt.readFile(_,"utf-8");v.trim()&&c.push(`PROJECT INSTRUCTIONS (CLAUDE.md):
641
- ${v.trim()}`)}let O=Ge.join(t,".nex","CLAUDE.md");if(await tn(()=>mt.access(O).then(()=>!0).catch(()=>!1))){let v=await mt.readFile(O,"utf-8");v.trim()&&c.push(`PRIVATE PROJECT INSTRUCTIONS (.nex/CLAUDE.md):
646
+ ${v.trim()}`)}let A=Ge.join(t,".nex","CLAUDE.md");if(await tn(()=>mt.access(A).then(()=>!0).catch(()=>!1))){let v=await mt.readFile(A,"utf-8");v.trim()&&c.push(`PRIVATE PROJECT INSTRUCTIONS (.nex/CLAUDE.md):
642
647
  ${v.trim()}`)}s=c.join(`
643
648
 
644
- `),nc.set(e,s),$i=Date.now()+hm,await yS()}let o=[s],r,i,a,l;if(Us.result&&Date.now()<Us.expiry&&Us.cwd===t?{branch:r,status:i,log:a,conflicts:l}=Us.result:([r,i,a,l]=await Promise.all([tn(async()=>{let{stdout:c}=await _i("git branch --show-current",{cwd:t,timeout:5e3});return c.trim()}),tn(async()=>{let{stdout:c}=await _i("git status --short",{cwd:t,timeout:5e3});return c.trim()}),tn(async()=>{let{stdout:c}=await _i("git log --oneline -5",{cwd:t,timeout:5e3});return c.trim()}),gm()]),Us={result:{branch:r,status:i,log:a,conflicts:l},expiry:Date.now()+hm,cwd:t}),r&&o.push(`GIT BRANCH: ${r}`),i&&o.push(`GIT STATUS:
649
+ `),cc.set(e,s),vi=Date.now()+Sm,await IS()}let o=[s],r,i,a,l;if(Gs.result&&Date.now()<Gs.expiry&&Gs.cwd===t?{branch:r,status:i,log:a,conflicts:l}=Gs.result:([r,i,a,l]=await Promise.all([tn(async()=>{let{stdout:c}=await Si("git branch --show-current",{cwd:t,timeout:5e3});return c.trim()}),tn(async()=>{let{stdout:c}=await Si("git status --short",{cwd:t,timeout:5e3});return c.trim()}),tn(async()=>{let{stdout:c}=await Si("git log --oneline -5",{cwd:t,timeout:5e3});return c.trim()}),Em()]),Gs={result:{branch:r,status:i,log:a,conflicts:l},expiry:Date.now()+Sm,cwd:t}),r&&o.push(`GIT BRANCH: ${r}`),i&&o.push(`GIT STATUS:
645
650
  ${i}`),a&&o.push(`RECENT COMMITS:
646
651
  ${a}`),l&&l.length>0){let c=l.map(u=>` ${u.file}`).join(`
647
652
  `);o.push(`MERGE CONFLICTS (resolve before editing these files):
648
- ${c}`)}try{let c=dS();c&&o.push(c)}catch{}return o.join(`
653
+ ${c}`)}try{let c=AS();c&&o.push(c)}catch{}return o.join(`
649
654
 
650
- `)}async function _S(t){let e=Ge.join(t,"package.json"),s="";if(await tn(()=>mt.access(e).then(()=>!0).catch(()=>!1)))try{let i=await mt.readFile(e,"utf-8"),a=JSON.parse(i);s=`${a.name||"?"} v${a.version||"?"}`}catch{}let[o,r]=await Promise.all([tn(async()=>{let{stdout:i}=await _i("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),gm()]);if(r&&r.length>0){console.log(`${Bs.red} \u26A0 ${r.length} unresolved merge conflict(s):${Bs.reset}`);for(let i of r)console.log(`${Bs.red} ${i.file}${Bs.reset}`);console.log(`${Bs.yellow} \u2192 Resolve conflicts before starting tasks${Bs.reset}`)}console.log()}ym.exports={gatherProjectContext:wS,printContext:_S,generateFileTree:mS,_clearContextCache:()=>{nc.clear(),Ws.clear(),$i=null,Us={result:null,expiry:0,cwd:null}}}});var xi=Z((f1,bm)=>{var Yt=require("fs"),bi=require("path"),{atomicWrite:$S}=Bn();function qo(){return bi.join(process.cwd(),".nex","sessions")}function sc(){let t=qo();Yt.existsSync(t)||Yt.mkdirSync(t,{recursive:!0,mode:448})}function oc(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return bi.join(qo(),`${e}.json`)}function rc(t,e,s={}){sc();let n=oc(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 $S(n,JSON.stringify(o,null,2)),{path:n,name:t}}function _m(t){let e=oc(t);if(!Yt.existsSync(e))return null;try{return JSON.parse(Yt.readFileSync(e,"utf-8"))}catch{return null}}function $m(){sc();let t=qo(),e=Yt.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(Yt.readFileSync(bi.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 bS(t){let e=oc(t);return Yt.existsSync(e)?(Yt.unlinkSync(e),!0):!1}function xS(){let t=$m();return t.length===0?null:_m(t[0].name)}var ns=null,hn=null,jo=null;function kS(t,e={}){t.length!==0&&(ns&&clearTimeout(ns),hn=t,jo=e||{},ns=setTimeout(()=>{hn&&hn.length>0&&rc("_autosave",hn,jo),ns=null,hn=null,jo=null},5e3))}function SS(){ns&&(clearTimeout(ns),ns=null),hn&&hn.length>0&&(rc("_autosave",hn,jo),hn=null,jo=null)}function vS(){sc();let t=qo(),e=Yt.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=bi.join(t,r);try{let a=Yt.statSync(i);new Date(a.mtime)<n&&(Yt.unlinkSync(i),o++)}catch{}}return o}bm.exports={saveSession:rc,loadSession:_m,listSessions:$m,deleteSession:bS,getLastSession:xS,autoSave:kS,flushAutoSave:SS,clearOldSessions:vS,_getSessionsDir:qo}});var ki=Z((p1,Cm)=>{"use strict";var Fo=require("fs"),xm=require("path");function km(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 ES(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 Sm(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 vm(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 Em(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 Tm(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 Rm(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=km(t),o=Sm(t),r=n.length,i=ES(t),a=n.filter($=>!$.id||!i.has($.id));t.some($=>$.role==="user"&&typeof $.content=="string"&&$.content.startsWith("[SYSTEM WARNING]")&&($.content.includes("edited")||$.content.includes("bash command")||$.content.includes("grep pattern")||$.content.includes("re-read")||$.content.includes("already in your context")))&&(e-=2,s.push("Loop-warning was fired during session (repeated file edits, bash commands, or re-reads)"));let c=n.find($=>{let I=$.input?.command||$.input?.cmd||"";return/\bsed\s+-n\b/.test(I)});if(c){let $=(c.input?.command||c.input?.cmd||"").slice(0,80);o.some(R=>R.content.includes("BLOCKED: sed -n is forbidden")||R.content.includes("BLOCKED: sed -n"))?(e-=.25,s.push(`sed -n attempted but blocked by agent guard: ${$}`)):(e-=1.5,s.push(`sed -n anti-pattern used: ${$}`))}n.find($=>{if($.name!=="grep"&&$.name!=="bash"&&$.name!=="ssh_exec")return!1;let I=$.input?.command||$.input?.cmd||"",R=$.input?.pattern||"",W=`${I} ${R}`;return/(?:-[CAB]|--context|--after|--before)\s*[=\s]?([2-9][1-9]|\d{3,})/.test(W)||/grep.*-[CAB]\s*([2-9][1-9]|\d{3,})/.test(W)})&&(e-=1,s.push("grep used with >20 context lines (context flood risk)"));let d=t.some($=>$.role==="assistant"),f=vm(t),h=Em(t,3).some($=>$.length>100&&!/^[^.!]{0,40}\?$/.test($));if(d&&!h&&(f.length<80||/^[^.!]{0,40}\?$/.test(f))){e-=2;let $=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: ${$}`)}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($=>{let I=typeof $.content=="string"?$.content:Array.isArray($.content)?$.content.map(R=>typeof R=="string"?R:R.text||"").join(""):"";return/\[auto-compressed|context compacted|force-compressed/.test(I)})&&(e-=.5,s.push("Auto-compress triggered (context flood indicator)"));let b=Tm(a),O=0,M="";for(let[$,I]of b)I>O&&(O=I,M=$);if(O>=3){let[$]=M.split("|");e-=1,s.push(`Same tool call repeated ${O}\xD7 (tool: ${$})`)}let v=!1,T=t.findIndex($=>$.role==="user"&&typeof $.content=="string"&&$.content.includes("[SYSTEM STOP]")&&$.content.includes('"valid":true'));T>=0&&n.filter(I=>I.index>T).length>0&&(v=!0),v&&(e-=1.5,s.push('Stop-trigger ignored: tool result contained "valid":true but session continued with more tool calls'));let N=n.filter($=>$.name==="ssh_exec");if(N.length>=8){let $=0,I=1;for(let R=1;R<N.length;R++)N[R].index<=N[R-1].index+2?I++:($=Math.max($,I),I=1);$=Math.max($,I),$>=8&&(e-=.5,s.push(`SSH reconnect storm: ${$} consecutive SSH calls`))}d&&N.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 te=new Map;for(let $ of a)if($.name==="read_file"&&$.input?.path){let I=$.input.path;te.has(I)||te.set(I,{count:0,ranges:[]});let R=te.get(I);if(R.count++,$.input.line_start!=null){let W=$.input.line_start||1,E=$.input.line_end||W+350;R.ranges.push([W,E])}}function K($,I,R){for(let[W,E]of R){let S=Math.max($,W),oe=Math.min(I,E);if(oe>S){let we=oe-S,ge=I-$||1;if(we/ge>=.7)return!0}}return!1}let ie=0,le="";for(let[$,I]of te){if(I.count<3)continue;if(I.ranges.length===I.count){let E=!1,S=[];for(let[oe,we]of I.ranges){if(S.length>0&&K(oe,we,S)){E=!0;break}S.push([oe,we])}if(!E)continue}if(I.count-I.ranges.length<=2&&I.ranges.length>=1){let E=!1,S=[];for(let[oe,we]of I.ranges){if(S.length>0&&K(oe,we,S)){E=!0;break}S.push([oe,we])}if(!E)continue}I.count>ie&&(ie=I.count,le=$)}if(ie>=3){e-=1;let $=le.split("/").slice(-2).join("/");s.push(`read_file loop: "${$}" read ${ie}\xD7 (file already in context)`)}let ne=0,k="";for(let[$,I]of te){if(I.ranges.length<4)continue;let R=[],W=!1;for(let[E,S]of I.ranges){if(R.length>0&&K(E,S,R)){W=!0;break}R.push([E,S])}!W&&I.ranges.length>ne&&(ne=I.ranges.length,k=$)}if(ne>=4){e-=.5;let $=k.split("/").slice(-2).join("/");s.push(`File-scroll pattern: "${$}" read in ${ne} sequential sections \u2014 use grep instead`)}let ve=new Map;for(let $ of a)if($.name==="grep"&&$.input?.path&&$.input?.pattern){let I=$.input.path;ve.has(I)||ve.set(I,new Set),ve.get(I).add($.input.pattern)}let H=0,X="";for(let[$,I]of ve)$.split("/").pop().includes(".")&&I.size>H&&(H=I.size,X=$);if(H>=3){e-=.75;let $=X.split("/").slice(-2).join("/");s.push(`grep flood on single file: "${$}" searched ${H}\xD7 with different patterns (file already in context)`)}{let $=new Set,I=new Set,R=/^(test_|demo_|temp_|tmp_|scratch_)/;for(let E of n){if(E.name==="write_file"&&E.input?.path){let S=E.input.path.split("/").pop(),oe=E.input.path.includes("/tests/");R.test(S)&&!oe&&$.add(E.input.path)}if((E.name==="bash"||E.name==="ssh_exec")&&E.input?.command){let S=E.input.command.match(/\brm\s+(?:-\w+\s+)?(\S+)/g);if(S)for(let oe of S){let we=oe.split(/\s+/),ge=we[we.length-1];for(let st of $)(st.endsWith(ge)||ge.endsWith(st.split("/").pop()))&&I.add(st)}}}let W=I.size;if(W>=1){let E=Math.min(W*.25,.5);e-=E;let S=[...I].map(oe=>oe.split("/").pop()).join(", ");s.push(`Temp file write-then-delete: ${S} \u2014 write inline logic or use tests/ instead`)}}let pe=o.filter($=>$.content.startsWith("EXIT")).length;pe>=10?(e-=1,s.push(`Bash exit-error storm: ${pe} tool results started with EXIT (repeated failing commands)`)):pe>=5&&(e-=.5,s.push(`Repeated bash errors: ${pe} tool results with non-zero exit code`));for(let $ of t){if($.role!=="assistant")continue;let I="";if(typeof $.content=="string"?I=$.content:Array.isArray($.content)&&(I=$.content.filter(ge=>ge&&(ge.type==="text"||typeof ge=="string")).map(ge=>typeof ge=="string"?ge:ge.text||"").join("")),I.length<=5e3)continue;let R=I.split(/(?<=\. )/).filter(ge=>ge.trim().length>0);if(R.length<6)continue;let W=new Map;for(let ge=0;ge<=R.length-3;ge++){let st=R.slice(ge,ge+3).join("").trim();st.length>30&&W.set(st,(W.get(st)||0)+1)}let E=0,S="";for(let[ge,st]of W)st>E&&(E=st,S=ge);if(E<3)continue;let we=S.length*E/I.length;if(we>=.4||E>=10){e-=1.5,s.push(`llm output loop: assistant message repeated content detected (${E}\xD7 same paragraph, ${Math.round(we*100)}% repeated)`);break}}{let $=new Set(["read_file","list_directory","search_files","glob","grep"]),I=t.some(W=>Array.isArray(W.tool_calls)?W.tool_calls.some(E=>$.has(E.function?.name)):Array.isArray(W.content)?W.content.some(E=>E.type==="tool_use"&&$.has(E.name)):!1);t.some(W=>W.role==="assistant"&&typeof W.content=="string"&&(W.content.includes("## Steps")||W.content.includes("/plan approve")))&&!I&&(e-=2,s.push("plan written without reading any files \u2014 LLM invented data structures from training knowledge (hallucination risk)"))}let Re=o.filter($=>$.content.startsWith("BLOCKED:")&&!$.content.includes("BLOCKED: sed -n")&&!$.content.includes("SSH paused")&&!$.content.includes("SSH temporarily paused"));if(Re.length>0){let $=Math.min(Re.length*.5,1.5);e-=$,s.push(`${Re.length} tool call${Re.length===1?"":"s"} blocked (agent attempted denied actions)`)}let Ue=t.filter($=>{let I=typeof $.content=="string"?$.content:"";return/\[SYSTEM WARNING\] Context wiped \d+×/.test(I)}).length;if(Ue>0){let $=Math.min(Ue*1,2);e-=$,s.push(`Super-nuclear context wipe fired ${Ue}\xD7 (context collapse \u2014 task too large or read loops)`)}{let $=!1,I=!1,R=!1;for(let E of n){if(E.name!=="bash")continue;let S=(E.input?.command||E.input?.cmd||"").trim();!(/cat\s*>/.test(S)||/<</.test(S))&&/\bcat\s+\S/.test(S)&&($=!0),/^\s*ls(\s|$)/.test(S)&&!/npm|yarn|pnpm|make|git\b/.test(S)&&(I=!0),/\bfind\s+\S/.test(S)&&!/git\b|npm\b|-exec\b/.test(S)&&(R=!0)}let W=[$,I,R].filter(Boolean).length;if(W>0){let E=Math.min(W*.25,.75);e-=E;let S=[];$&&S.push("cat (use read_file)"),I&&S.push("ls (use list_directory)"),R&&S.push("find (use glob)"),s.push(`bash used instead of dedicated tool: ${S.join(", ")}`)}}{let $=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"))),I=n.some(S=>(S.name==="write_file"||S.name==="Write")&&S.input?.path&&S.input.path.endsWith("package.json")),R=n.filter(S=>(S.name==="bash"||S.name==="Bash")&&S.input?.command).map(S=>S.input.command),W=R.some(S=>/pip\s+install|python\s+-m\s+venv/.test(S)),E=R.some(S=>/npm\s+install/.test(S));$&&!W?(e-=1,s.push("wrote requirements.txt but never ran pip install \u2014 environment not bootstrapped")):I&&!E&&n.some(oe=>(oe.name==="write_file"||oe.name==="Write")&&oe.input?.path&&/(\/src\/|index\.js|App\.js|main\.js)/.test(oe.input.path))&&(e-=.75,s.push("created new React/Node project but never ran npm install \u2014 project is not runnable"))}if(d){let $=t.find(S=>S.role==="assistant"),I="";$&&(typeof $.content=="string"?I=$.content:Array.isArray($.content)&&(I=$.content.filter(S=>S&&(S.type==="text"||typeof S=="string")).map(S=>typeof S=="string"?S:S.text||"").join("")));let R=I.slice(0,400),W=/^[\d\s\+\-\*\/×÷\(\)\.]+\s*=\s*[\d\s\+\-\*\/×÷\(\)\.]+[.\n]/m,E=R.split(`
651
- `).find(S=>{let oe=S.trim();return oe.length>0&&oe.length<=30&&/^\d/.test(oe)&&/=/.test(oe)&&!/[a-zA-Z]/.test(oe)});if(W.test(R)||E){e-=1.5;let S=(E||R.split(`
652
- `)[0]).trim().slice(0,40);s.push(`Thinking-chain leak: non-sequitur artifact at response start: "${S}"`)}}if(d&&r>0){let $=t.findIndex(R=>R.role==="assistant"),I=t.findIndex(R=>!!(Array.isArray(R.tool_calls)&&R.tool_calls.length>0||Array.isArray(R.content)&&R.content.some(W=>W&&W.type==="tool_use")));if($!==-1&&I!==-1&&$<I){let R=t[$],W="";typeof R.content=="string"?W=R.content:Array.isArray(R.content)&&(W=R.content.filter(oe=>oe&&(oe.type==="text"||typeof oe=="string")).map(oe=>typeof oe=="string"?oe:oe.text||"").join(""));let E=/ssh\s+\S+@\S+\s+"[^"]*\/[^"]*\./.test(W),S=/\/(?:home|var|etc|usr|opt|root|srv|data)\/[a-zA-Z0-9_.\-\/]+\.[a-zA-Z]{2,5}/.test(W);(E||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 $=f;if($.length>100){let R=($.match(/^```/gm)||[]).length%2!==0,W=/"\s*:\s*$/.test($.trimEnd()),E=/[,\[{]\s*$/.test($.trimEnd());(R||W||E)&&(e-=.75,s.push("Truncated response: last assistant message ends mid-code-block or mid-JSON (model hit token limit)"))}}{let $=[];t.forEach((R,W)=>{let E=[];Array.isArray(R.tool_calls)&&R.tool_calls.forEach(S=>{if((S.function?.name||S.name||"")==="read_file"){let we={};try{we=typeof S.function?.arguments=="string"?JSON.parse(S.function.arguments):S.function?.arguments||{}}catch{}(we.path||"").endsWith(".json")&&E.push({id:S.id,path:we.path})}}),Array.isArray(R.content)&&R.content.forEach(S=>{S&&S.type==="tool_use"&&S.name==="read_file"&&(S.input?.path||"").endsWith(".json")&&E.push({id:S.id,path:S.input.path})}),E.forEach(S=>$.push({...S,msgIdx:W}))});let I=0;for(let R of $){let W=null;for(let S of t){if(S.role==="tool"&&S.tool_call_id===R.id&&typeof S.content=="string"){W=S.content;break}if(S.role==="user"&&Array.isArray(S.content)){let oe=S.content.find(we=>we&&we.type==="tool_result"&&we.tool_use_id===R.id);if(oe){W=typeof oe.content=="string"?oe.content:"";break}}}if(!W)continue;W.split(`
653
- `).filter(S=>S.trim()).length<5&&/^\s*\[/.test(W)&&!/\]\s*$/.test(W.trimEnd())&&I++}I>=1&&(e-=.75,s.push(`Shallow JSON read: ${I} .json file${I>1?"s":""} read with < 5 lines \u2014 array was incomplete, model drew conclusions from truncated data`))}{let $=o.filter(I=>/argument errors?/i.test(I.content)||/missing required (argument|parameter)/i.test(I.content)||/invalid argument/i.test(I.content));$.length>=3?(e-=.75,s.push(`Repeated tool argument errors: ${$.length} tool calls returned argument errors \u2014 model couldn't correct its tool usage`)):$.length>=2&&(e-=.25,s.push(`Tool argument errors: ${$.length} tool calls returned argument errors`))}{let $=!1,I=0,R=0;for(let W of a){if((W.name==="bash"||W.name==="Bash")&&W.input?.command&&/git\s+commit\b/.test(W.input.command)){$&&(R=Math.max(R,I)),$=!0,I=0;continue}$&&(W.name==="bash"||W.name==="Bash")&&W.input?.command&&/git\s+(status|diff|log|show)\b/.test(W.input.command)&&I++}R=Math.max(R,I),R>=3&&(e-=.75,s.push(`Post-commit verification waste: ${R} git status/diff/log calls after commit`))}e=Math.max(0,Math.min(10,e)),e=Math.round(e*10)/10;let ke=e>=9?"A":e>=8?"B":e>=7?"C":e>=6?"D":"F",$e=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:ke,issues:s,summary:$e}}function TS(t){try{let{loadSession:e}=xi(),s=e(t);return s?Rm(s.messages||[]):null}catch{return null}}function RS(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})`),`
655
+ `)}async function jS(t){let e=Ge.join(t,"package.json"),s="";if(await tn(()=>mt.access(e).then(()=>!0).catch(()=>!1)))try{let i=await mt.readFile(e,"utf-8"),a=JSON.parse(i);s=`${a.name||"?"} v${a.version||"?"}`}catch{}let[o,r]=await Promise.all([tn(async()=>{let{stdout:i}=await Si("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),Em()]);if(r&&r.length>0){console.log(`${Ys.red} \u26A0 ${r.length} unresolved merge conflict(s):${Ys.reset}`);for(let i of r)console.log(`${Ys.red} ${i.file}${Ys.reset}`);console.log(`${Ys.yellow} \u2192 Resolve conflicts before starting tasks${Ys.reset}`)}console.log()}Tm.exports={gatherProjectContext:DS,printContext:jS,generateFileTree:PS,_clearContextCache:()=>{cc.clear(),zs.clear(),vi=null,Gs={result:null,expiry:0,cwd:null}}}});var Ti=Q((N1,Om)=>{var Yt=require("fs"),Ei=require("path"),{atomicWrite:qS}=Fn();function Wo(){return Ei.join(process.cwd(),".nex","sessions")}function uc(){let t=Wo();Yt.existsSync(t)||Yt.mkdirSync(t,{recursive:!0,mode:448})}function dc(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return Ei.join(Wo(),`${e}.json`)}function fc(t,e,s={}){uc();let n=dc(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 qS(n,JSON.stringify(o,null,2)),{path:n,name:t}}function Cm(t){let e=dc(t);if(!Yt.existsSync(e))return null;try{return JSON.parse(Yt.readFileSync(e,"utf-8"))}catch{return null}}function Am(){uc();let t=Wo(),e=Yt.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(Yt.readFileSync(Ei.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 FS(t){let e=dc(t);return Yt.existsSync(e)?(Yt.unlinkSync(e),!0):!1}function BS(){let t=Am();return t.length===0?null:Cm(t[0].name)}var ns=null,hn=null,Uo=null;function US(t,e={}){t.length!==0&&(ns&&clearTimeout(ns),hn=t,Uo=e||{},ns=setTimeout(()=>{hn&&hn.length>0&&fc("_autosave",hn,Uo),ns=null,hn=null,Uo=null},5e3))}function WS(){ns&&(clearTimeout(ns),ns=null),hn&&hn.length>0&&(fc("_autosave",hn,Uo),hn=null,Uo=null)}function HS(){uc();let t=Wo(),e=Yt.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=Ei.join(t,r);try{let a=Yt.statSync(i);new Date(a.mtime)<n&&(Yt.unlinkSync(i),o++)}catch{}}return o}Om.exports={saveSession:fc,loadSession:Cm,listSessions:Am,deleteSession:FS,getLastSession:BS,autoSave:US,flushAutoSave:WS,clearOldSessions:HS,_getSessionsDir:Wo}});var Ri=Q((M1,qm)=>{"use strict";var Ho=require("fs"),Nm=require("path");function Mm(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 YS(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 Pm(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 Lm(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 Im(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 Dm(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 jm(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=Mm(t),o=Pm(t),r=n.length,i=YS(t),a=n.filter($=>!$.id||!i.has($.id));t.some($=>$.role==="user"&&typeof $.content=="string"&&$.content.startsWith("[SYSTEM WARNING]")&&($.content.includes("edited")||$.content.includes("bash command")||$.content.includes("grep pattern")||$.content.includes("re-read")||$.content.includes("already in your context")))&&(e-=2,s.push("Loop-warning was fired during session (repeated file edits, bash commands, or re-reads)"));let c=n.find($=>{let I=$.input?.command||$.input?.cmd||"";return/\bsed\s+-n\b/.test(I)});if(c){let $=(c.input?.command||c.input?.cmd||"").slice(0,80);o.some(H=>H.content.includes("BLOCKED: sed -n is forbidden")||H.content.includes("BLOCKED: sed -n"))?(e-=.25,s.push(`sed -n attempted but blocked by agent guard: ${$}`)):(e-=1.5,s.push(`sed -n anti-pattern used: ${$}`))}n.find($=>{if($.name!=="grep"&&$.name!=="bash"&&$.name!=="ssh_exec")return!1;let I=$.input?.command||$.input?.cmd||"",H=$.input?.pattern||"",N=`${I} ${H}`;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($=>$.role==="assistant"),f=Lm(t),m=Im(t,3).some($=>$.length>100&&!/^[^.!]{0,40}\?$/.test($));if(d&&!m&&(f.length<80||/^[^.!]{0,40}\?$/.test(f))){e-=2;let $=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: ${$}`)}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($=>{let I=typeof $.content=="string"?$.content:Array.isArray($.content)?$.content.map(H=>typeof H=="string"?H:H.text||"").join(""):"";return/\[auto-compressed|context compacted|force-compressed/.test(I)})&&(e-=.5,s.push("Auto-compress triggered (context flood indicator)"));let b=Dm(a),A=0,P="";for(let[$,I]of b)I>A&&(A=I,P=$);if(A>=3){let[$]=P.split("|");e-=1,s.push(`Same tool call repeated ${A}\xD7 (tool: ${$})`)}let v=!1,E=t.findIndex($=>$.role==="user"&&typeof $.content=="string"&&$.content.includes("[SYSTEM STOP]")&&$.content.includes('"valid":true'));E>=0&&n.filter(I=>I.index>E).length>0&&(v=!0),v&&(e-=1.5,s.push('Stop-trigger ignored: tool result contained "valid":true but session continued with more tool calls'));let O=n.filter($=>$.name==="ssh_exec");if(O.length>=8){let $=0,I=1;for(let H=1;H<O.length;H++)O[H].index<=O[H-1].index+2?I++:($=Math.max($,I),I=1);$=Math.max($,I),$>=8&&(e-=.5,s.push(`SSH reconnect storm: ${$} consecutive SSH calls`))}d&&O.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 ne=new Map;for(let $ of a)if($.name==="read_file"&&$.input?.path){let I=$.input.path;ne.has(I)||ne.set(I,{count:0,ranges:[]});let H=ne.get(I);if(H.count++,$.input.line_start!=null){let N=$.input.line_start||1,q=$.input.line_end||N+350;H.ranges.push([N,q])}}function J($,I,H){for(let[N,q]of H){let x=Math.max($,N),Y=Math.min(I,q);if(Y>x){let ke=Y-x,pe=I-$||1;if(ke/pe>=.7)return!0}}return!1}let ie=0,ce="";for(let[$,I]of ne){if(I.count<3)continue;if(I.ranges.length===I.count){let q=!1,x=[];for(let[Y,ke]of I.ranges){if(x.length>0&&J(Y,ke,x)){q=!0;break}x.push([Y,ke])}if(!q)continue}if(I.count-I.ranges.length<=2&&I.ranges.length>=1){let q=!1,x=[];for(let[Y,ke]of I.ranges){if(x.length>0&&J(Y,ke,x)){q=!0;break}x.push([Y,ke])}if(!q)continue}I.count>ie&&(ie=I.count,ce=$)}if(ie>=3){e-=1;let $=ce.split("/").slice(-2).join("/");s.push(`read_file loop: "${$}" read ${ie}\xD7 (file already in context)`)}let se=0,S="";for(let[$,I]of ne){if(I.ranges.length<4)continue;let H=[],N=!1;for(let[q,x]of I.ranges){if(H.length>0&&J(q,x,H)){N=!0;break}H.push([q,x])}!N&&I.ranges.length>se&&(se=I.ranges.length,S=$)}if(se>=4){e-=.5;let $=S.split("/").slice(-2).join("/");s.push(`File-scroll pattern: "${$}" read in ${se} sequential sections \u2014 use grep instead`)}let Ee=new Map;for(let $ of a)if($.name==="grep"&&$.input?.path&&$.input?.pattern){let I=$.input.path;Ee.has(I)||Ee.set(I,new Set),Ee.get(I).add($.input.pattern)}let W=0,Z="";for(let[$,I]of Ee)$.split("/").pop().includes(".")&&I.size>W&&(W=I.size,Z=$);if(W>=3){e-=.75;let $=Z.split("/").slice(-2).join("/");s.push(`grep flood on single file: "${$}" searched ${W}\xD7 with different patterns (file already in context)`)}{let $=new Set,I=new Set,H=/^(test_|demo_|temp_|tmp_|scratch_)/;for(let q of n){if(q.name==="write_file"&&q.input?.path){let x=q.input.path.split("/").pop(),Y=q.input.path.includes("/tests/");H.test(x)&&!Y&&$.add(q.input.path)}if((q.name==="bash"||q.name==="ssh_exec")&&q.input?.command){let x=q.input.command.match(/\brm\s+(?:-\w+\s+)?(\S+)/g);if(x)for(let Y of x){let ke=Y.split(/\s+/),pe=ke[ke.length-1];for(let lt of $)(lt.endsWith(pe)||pe.endsWith(lt.split("/").pop()))&&I.add(lt)}}}let N=I.size;if(N>=1){let q=Math.min(N*.25,.5);e-=q;let x=[...I].map(Y=>Y.split("/").pop()).join(", ");s.push(`Temp file write-then-delete: ${x} \u2014 write inline logic or use tests/ instead`)}}let he=o.filter($=>$.content.startsWith("EXIT")).length;he>=10?(e-=1,s.push(`Bash exit-error storm: ${he} tool results started with EXIT (repeated failing commands)`)):he>=5&&(e-=.5,s.push(`Repeated bash errors: ${he} tool results with non-zero exit code`));for(let $ of t){if($.role!=="assistant")continue;let I="";if(typeof $.content=="string"?I=$.content:Array.isArray($.content)&&(I=$.content.filter(pe=>pe&&(pe.type==="text"||typeof pe=="string")).map(pe=>typeof pe=="string"?pe:pe.text||"").join("")),I.length<=5e3)continue;let H=I.split(/(?<=\. )/).filter(pe=>pe.trim().length>0);if(H.length<6)continue;let N=new Map;for(let pe=0;pe<=H.length-3;pe++){let lt=H.slice(pe,pe+3).join("").trim();lt.length>30&&N.set(lt,(N.get(lt)||0)+1)}let q=0,x="";for(let[pe,lt]of N)lt>q&&(q=lt,x=pe);if(q<3)continue;let ke=x.length*q/I.length;if(ke>=.4||q>=10){e-=1.5,s.push(`llm output loop: assistant message repeated content detected (${q}\xD7 same paragraph, ${Math.round(ke*100)}% repeated)`);break}}{let $=new Set(["read_file","list_directory","search_files","glob","grep"]),I=t.some(N=>Array.isArray(N.tool_calls)?N.tool_calls.some(q=>$.has(q.function?.name)):Array.isArray(N.content)?N.content.some(q=>q.type==="tool_use"&&$.has(q.name)):!1);t.some(N=>N.role==="assistant"&&typeof N.content=="string"&&(N.content.includes("## Steps")||N.content.includes("/plan approve")))&&!I&&(e-=2,s.push("plan written without reading any files \u2014 LLM invented data structures from training knowledge (hallucination risk)"))}let Ce=o.filter($=>$.content.startsWith("BLOCKED:")&&!$.content.includes("BLOCKED: sed -n")&&!$.content.includes("SSH paused")&&!$.content.includes("SSH temporarily paused"));if(Ce.length>0){let $=Math.min(Ce.length*.5,1.5);e-=$,s.push(`${Ce.length} tool call${Ce.length===1?"":"s"} blocked (agent attempted denied actions)`)}let We=t.filter($=>{let I=typeof $.content=="string"?$.content:"";return/\[SYSTEM WARNING\] Context wiped \d+×/.test(I)}).length;if(We>0){let $=Math.min(We*1,2);e-=$,s.push(`Super-nuclear context wipe fired ${We}\xD7 (context collapse \u2014 task too large or read loops)`)}{let $=!1,I=!1,H=!1;for(let q of n){if(q.name!=="bash")continue;let x=(q.input?.command||q.input?.cmd||"").trim();!(/cat\s*>/.test(x)||/<</.test(x))&&/\bcat\s+\S/.test(x)&&($=!0),/^\s*ls(\s|$)/.test(x)&&!/npm|yarn|pnpm|make|git\b/.test(x)&&(I=!0),/\bfind\s+\S/.test(x)&&!/git\b|npm\b|-exec\b/.test(x)&&(H=!0)}let N=[$,I,H].filter(Boolean).length;if(N>0){let q=Math.min(N*.25,.75);e-=q;let x=[];$&&x.push("cat (use read_file)"),I&&x.push("ls (use list_directory)"),H&&x.push("find (use glob)"),s.push(`bash used instead of dedicated tool: ${x.join(", ")}`)}}{let $=n.some(x=>(x.name==="write_file"||x.name==="Write")&&x.input?.path&&(x.input.path.endsWith("requirements.txt")||x.input.path.endsWith("Pipfile")||x.input.path.endsWith("pyproject.toml"))),I=n.some(x=>(x.name==="write_file"||x.name==="Write")&&x.input?.path&&x.input.path.endsWith("package.json")),H=n.filter(x=>(x.name==="bash"||x.name==="Bash")&&x.input?.command).map(x=>x.input.command),N=H.some(x=>/pip\s+install|python\s+-m\s+venv/.test(x)),q=H.some(x=>/npm\s+install/.test(x));$&&!N?(e-=1,s.push("wrote requirements.txt but never ran pip install \u2014 environment not bootstrapped")):I&&!q&&n.some(Y=>(Y.name==="write_file"||Y.name==="Write")&&Y.input?.path&&/(\/src\/|index\.js|App\.js|main\.js)/.test(Y.input.path))&&(e-=.75,s.push("created new React/Node project but never ran npm install \u2014 project is not runnable"))}if(d){let $=t.find(x=>x.role==="assistant"),I="";$&&(typeof $.content=="string"?I=$.content:Array.isArray($.content)&&(I=$.content.filter(x=>x&&(x.type==="text"||typeof x=="string")).map(x=>typeof x=="string"?x:x.text||"").join("")));let H=I.slice(0,400),N=/^[\d\s\+\-\*\/×÷\(\)\.]+\s*=\s*[\d\s\+\-\*\/×÷\(\)\.]+[.\n]/m,q=H.split(`
656
+ `).find(x=>{let Y=x.trim();return Y.length>0&&Y.length<=30&&/^\d/.test(Y)&&/=/.test(Y)&&!/[a-zA-Z]/.test(Y)});if(N.test(H)||q){e-=1.5;let x=(q||H.split(`
657
+ `)[0]).trim().slice(0,40);s.push(`Thinking-chain leak: non-sequitur artifact at response start: "${x}"`)}}if(d&&r>0){let $=t.findIndex(H=>H.role==="assistant"),I=t.findIndex(H=>!!(Array.isArray(H.tool_calls)&&H.tool_calls.length>0||Array.isArray(H.content)&&H.content.some(N=>N&&N.type==="tool_use")));if($!==-1&&I!==-1&&$<I){let H=t[$],N="";typeof H.content=="string"?N=H.content:Array.isArray(H.content)&&(N=H.content.filter(Y=>Y&&(Y.type==="text"||typeof Y=="string")).map(Y=>typeof Y=="string"?Y:Y.text||"").join(""));let q=/ssh\s+\S+@\S+\s+"[^"]*\/[^"]*\./.test(N),x=/\/(?:home|var|etc|usr|opt|root|srv|data)\/[a-zA-Z0-9_.\-\/]+\.[a-zA-Z]{2,5}/.test(N);(q||x)&&(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 $=f;if($.length>100){let H=($.match(/^```/gm)||[]).length%2!==0,N=/"\s*:\s*$/.test($.trimEnd()),q=/[,\[{]\s*$/.test($.trimEnd());(H||N||q)&&(e-=.75,s.push("Truncated response: last assistant message ends mid-code-block or mid-JSON (model hit token limit)"))}}{let $=[];t.forEach((H,N)=>{let q=[];Array.isArray(H.tool_calls)&&H.tool_calls.forEach(x=>{if((x.function?.name||x.name||"")==="read_file"){let ke={};try{ke=typeof x.function?.arguments=="string"?JSON.parse(x.function.arguments):x.function?.arguments||{}}catch{}(ke.path||"").endsWith(".json")&&q.push({id:x.id,path:ke.path})}}),Array.isArray(H.content)&&H.content.forEach(x=>{x&&x.type==="tool_use"&&x.name==="read_file"&&(x.input?.path||"").endsWith(".json")&&q.push({id:x.id,path:x.input.path})}),q.forEach(x=>$.push({...x,msgIdx:N}))});let I=0;for(let H of $){let N=null;for(let x of t){if(x.role==="tool"&&x.tool_call_id===H.id&&typeof x.content=="string"){N=x.content;break}if(x.role==="user"&&Array.isArray(x.content)){let Y=x.content.find(ke=>ke&&ke.type==="tool_result"&&ke.tool_use_id===H.id);if(Y){N=typeof Y.content=="string"?Y.content:"";break}}}if(!N)continue;N.split(`
658
+ `).filter(x=>x.trim()).length<5&&/^\s*\[/.test(N)&&!/\]\s*$/.test(N.trimEnd())&&I++}I>=1&&(e-=.75,s.push(`Shallow JSON read: ${I} .json file${I>1?"s":""} read with < 5 lines \u2014 array was incomplete, model drew conclusions from truncated data`))}{let $=o.filter(I=>/argument errors?/i.test(I.content)||/missing required (argument|parameter)/i.test(I.content)||/invalid argument/i.test(I.content));$.length>=3?(e-=.75,s.push(`Repeated tool argument errors: ${$.length} tool calls returned argument errors \u2014 model couldn't correct its tool usage`)):$.length>=2&&(e-=.25,s.push(`Tool argument errors: ${$.length} tool calls returned argument errors`))}{let $=!1,I=0,H=0;for(let N of a){if((N.name==="bash"||N.name==="Bash")&&N.input?.command&&/git\s+commit\b/.test(N.input.command)){$&&(H=Math.max(H,I)),$=!0,I=0;continue}$&&(N.name==="bash"||N.name==="Bash")&&N.input?.command&&/git\s+(status|diff|log|show)\b/.test(N.input.command)&&I++}H=Math.max(H,I),H>=3&&(e-=.75,s.push(`Post-commit verification waste: ${H} git status/diff/log calls after commit`))}e=Math.max(0,Math.min(10,e)),e=Math.round(e*10)/10;let xe=e>=9?"A":e>=8?"B":e>=7?"C":e>=6?"D":"F",be=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:xe,issues:s,summary:be}}function GS(t){try{let{loadSession:e}=Ti(),s=e(t);return s?jm(s.messages||[]):null}catch{return null}}function zS(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})`),`
654
659
  ${o}${f}${r}`}let l="";for(let u of a.slice(0,4))l+=`
655
660
  ${i}\u26A0${r} ${o}${u}${r}`;let c=a.length-4;return c>0&&(l+=`
656
- ${o}(+${c} more)${r}`),l}function CS(t,e={}){try{let s=xm.join(process.cwd(),".nex");Fo.existsSync(s)||Fo.mkdirSync(s,{recursive:!0});let n=xm.join(s,"benchmark-history.json"),o=[];if(Fo.existsSync(n))try{o=JSON.parse(Fo.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)),Fo.writeFileSync(n,JSON.stringify(o,null,2))}catch{}}Cm.exports={scoreMessages:Rm,scoreSession:TS,formatScore:RS,appendScoreHistory:CS,_extractToolCalls:km,_extractToolResults:Sm,_getLastAssistantText:vm,_getLastNAssistantTexts:Em,_countDuplicateToolCalls:Tm}});var Hs=Z((h1,Pm)=>{"use strict";var AS=require("os"),ic=require("path"),Rn=require("fs"),Bo=ic.join(AS.homedir(),".nex-code","model-routing.json"),Si={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}},Am=["agentic","frontend","sysadmin","data","coding"];function OS(t){if(!t||t.length<8)return null;for(let e of Am){let s=Si[e];if(!s.pattern||s.pattern.test(t))return s}return Si.coding}function Uo(){try{if(Rn.existsSync(Bo))return JSON.parse(Rn.readFileSync(Bo,"utf-8"))}catch{}return{}}function Om(t){if(process.env.NEX_FORCE_MODEL)return process.env.NEX_FORCE_MODEL;let e=Si[t];return e?.envVar&&process.env[e.envVar]?process.env[e.envVar]:Uo()[t]||null}var Nm={explore:10,plan:10,implement:35,verify:8},ac={explore:"devstral-small-2:24b",plan:"qwen3-coder:480b",implement:null,verify:"devstral-small-2:24b"};function Mm(){let t=Uo();if(t.phases&&Object.keys(t.phases).length>0)return t.phases;try{let{getActiveProviderName:e}=Ze();if(e()==="ollama")return ac}catch{}return process.env.NEX_PHASE_ROUTING==="1"?ac:null}function NS(t,e){if(process.env.NEX_FORCE_MODEL)return process.env.NEX_FORCE_MODEL;let s=Mm();return s?.[t]?s[t]:e?Om(e):null}function MS(t){return Uo().phaseBudgets?.[t]||Nm[t]||20}function PS(){return process.env.NEX_PHASE_ROUTING==="0"||process.env.NEX_FORCE_MODEL?!1:Mm()!==null}function LS(t){let e=ic.dirname(Bo);Rn.existsSync(e)||Rn.mkdirSync(e,{recursive:!0});let s=Uo(),n={...s,...t};!t.phases&&s.phases&&(n.phases=s.phases),!t.phaseBudgets&&s.phaseBudgets&&(n.phaseBudgets=s.phaseBudgets),Rn.writeFileSync(Bo,JSON.stringify(n,null,2));try{let o=ic.join(e,".env"),r="";Rn.existsSync(o)&&(r=Rn.readFileSync(o,"utf-8"));let i=r.split(/\r?\n/),a=(l,c)=>{let u=i.findIndex(d=>d.startsWith(l+"="));u>=0?i[u]=`${l}=${c}`:i.push(`${l}=${c}`)};n.coding&&a("NEX_ROUTE_CODING",n.coding),n.frontend&&a("NEX_ROUTE_FRONTEND",n.frontend),n.sysadmin&&a("NEX_ROUTE_SYSADMIN",n.sysadmin),n.data&&a("NEX_ROUTE_DATA",n.data),n.agentic&&a("NEX_ROUTE_AGENTIC",n.agentic),n.phases&&(n.phases.plan&&a("NEX_PHASE_PLAN_MODEL",n.phases.plan),n.phases.implement&&a("NEX_PHASE_IMPLEMENT_MODEL",n.phases.implement),n.phases.verify&&a("NEX_PHASE_VERIFY_MODEL",n.phases.verify)),Rn.writeFileSync(o,i.filter(l=>l.trim()!=="").join(`
661
+ ${o}(+${c} more)${r}`),l}function KS(t,e={}){try{let s=Nm.join(process.cwd(),".nex");Ho.existsSync(s)||Ho.mkdirSync(s,{recursive:!0});let n=Nm.join(s,"benchmark-history.json"),o=[];if(Ho.existsSync(n))try{o=JSON.parse(Ho.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)),Ho.writeFileSync(n,JSON.stringify(o,null,2))}catch{}}qm.exports={scoreMessages:jm,scoreSession:GS,formatScore:zS,appendScoreHistory:KS,_extractToolCalls:Mm,_extractToolResults:Pm,_getLastAssistantText:Lm,_getLastNAssistantTexts:Im,_countDuplicateToolCalls:Dm}});var ss=Q((P1,Hm)=>{"use strict";var XS=require("os"),pc=require("path"),Tn=require("fs"),Yo=pc.join(XS.homedir(),".nex-code","model-routing.json"),Ci={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}},Fm=["agentic","frontend","sysadmin","data","coding"];function VS(t){if(!t||t.length<8)return null;for(let e of Fm){let s=Ci[e];if(!s.pattern||s.pattern.test(t))return s}return Ci.coding}function Go(){try{if(Tn.existsSync(Yo))return JSON.parse(Tn.readFileSync(Yo,"utf-8"))}catch{}return{}}function Bm(t){if(process.env.NEX_FORCE_MODEL)return process.env.NEX_FORCE_MODEL;let e=Ci[t];return e?.envVar&&process.env[e.envVar]?process.env[e.envVar]:Go()[t]||null}var Um={explore:10,plan:10,implement:35,verify:8},hc={explore:"devstral-small-2:24b",plan:"qwen3-coder:480b",implement:null,verify:"devstral-small-2:24b"};function Wm(){let t=Go();if(t.phases&&Object.keys(t.phases).length>0)return t.phases;try{let{getActiveProviderName:e}=Qe();if(e()==="ollama")return hc}catch{}return process.env.NEX_PHASE_ROUTING==="1"?hc:null}function JS(t,e){if(process.env.NEX_FORCE_MODEL)return process.env.NEX_FORCE_MODEL;let s=Wm();return s?.[t]?s[t]:e?Bm(e):null}function ZS(t){return Go().phaseBudgets?.[t]||Um[t]||20}function QS(){return process.env.NEX_PHASE_ROUTING==="0"||process.env.NEX_FORCE_MODEL?!1:Wm()!==null}function ev(t){let e=pc.dirname(Yo);Tn.existsSync(e)||Tn.mkdirSync(e,{recursive:!0});let s=Go(),n={...s,...t};!t.phases&&s.phases&&(n.phases=s.phases),!t.phaseBudgets&&s.phaseBudgets&&(n.phaseBudgets=s.phaseBudgets),Tn.writeFileSync(Yo,JSON.stringify(n,null,2));try{let o=pc.join(e,".env"),r="";Tn.existsSync(o)&&(r=Tn.readFileSync(o,"utf-8"));let i=r.split(/\r?\n/),a=(l,c)=>{let u=i.findIndex(d=>d.startsWith(l+"="));u>=0?i[u]=`${l}=${c}`:i.push(`${l}=${c}`)};n.coding&&a("NEX_ROUTE_CODING",n.coding),n.frontend&&a("NEX_ROUTE_FRONTEND",n.frontend),n.sysadmin&&a("NEX_ROUTE_SYSADMIN",n.sysadmin),n.data&&a("NEX_ROUTE_DATA",n.data),n.agentic&&a("NEX_ROUTE_AGENTIC",n.agentic),n.phases&&(n.phases.plan&&a("NEX_PHASE_PLAN_MODEL",n.phases.plan),n.phases.implement&&a("NEX_PHASE_IMPLEMENT_MODEL",n.phases.implement),n.phases.verify&&a("NEX_PHASE_VERIFY_MODEL",n.phases.verify)),Tn.writeFileSync(o,i.filter(l=>l.trim()!=="").join(`
657
662
  `)+`
658
- `)}catch{}}Pm.exports={CATEGORIES:Si,DETECTION_ORDER:Am,detectCategory:OS,getModelForCategory:Om,getModelForPhase:NS,getPhaseBudget:MS,isPhaseRoutingEnabled:PS,DEFAULT_PHASE_BUDGETS:Nm,BUILTIN_PHASE_DEFAULTS:ac,saveRoutingConfig:LS,loadRoutingConfig:Uo,ROUTING_CONFIG_PATH:Bo}});var jm=Z((m1,Dm)=>{"use strict";var ss=require("fs"),Wo=require("path"),IS=require("os"),{detectCategory:DS}=Hs(),Ys=Wo.join(IS.homedir(),".nex-code","examples"),lc=Wo.join(__dirname,"..","examples");function Lm(t){try{let s=ss.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(`
663
+ `)}catch{}}Hm.exports={CATEGORIES:Ci,DETECTION_ORDER:Fm,detectCategory:VS,getModelForCategory:Bm,getModelForPhase:JS,getPhaseBudget:ZS,isPhaseRoutingEnabled:QS,DEFAULT_PHASE_BUDGETS:Um,BUILTIN_PHASE_DEFAULTS:hc,saveRoutingConfig:ev,loadRoutingConfig:Go,ROUTING_CONFIG_PATH:Yo}});var Km=Q((L1,zm)=>{"use strict";var os=require("fs"),zo=require("path"),tv=require("os"),{detectCategory:nv}=ss(),Ks=zo.join(tv.homedir(),".nex-code","examples"),mc=zo.join(__dirname,"..","examples");function Ym(t){try{let s=os.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(`
659
664
  A: |`);if(r===-1)return null;let i=s.slice(r+5),a=[],l=0;for(let u of i.split(`
660
665
  `))if(u.startsWith(" ")){for(;l>0;)a.push(""),l--;a.push(u.slice(2))}else if(u.trim()==="")a.length>0&&l++;else break;if(a.length===0)return null;let c=a.join(`
661
- `).trim();return{user:o,assistant:c}}catch{return null}}function Im(t){let e=`${t}.md`,s=Wo.join(Ys,e);if(ss.existsSync(s)){let o=Lm(s);if(o)return o}let n=Wo.join(lc,e);return ss.existsSync(n)?Lm(n):null}function jS(t){if(process.env.NEX_FEW_SHOT==="0"||!t||t.length<8)return null;let e=DS(t);return!e||e.id==="coding"&&!/\b(fix|bug|crash|error|implement|add|create|change|update|refactor|rewrite|broken|fail|patch|migrate|port)\b/i.test(t)?null:Im(e.id)}function qS(){let t=new Set;for(let e of[Ys,lc])try{for(let s of ss.readdirSync(e))s.endsWith(".md")&&t.add(s.replace(".md",""))}catch{}return[...t].sort()}function FS(t,e){ss.existsSync(Ys)||ss.mkdirSync(Ys,{recursive:!0});let s=`<!-- Auto-extracted from high-scoring session \u2014 edit as needed -->
666
+ `).trim();return{user:o,assistant:c}}catch{return null}}function Gm(t){let e=`${t}.md`,s=zo.join(Ks,e);if(os.existsSync(s)){let o=Ym(s);if(o)return o}let n=zo.join(mc,e);return os.existsSync(n)?Ym(n):null}function sv(t){if(process.env.NEX_FEW_SHOT==="0"||!t||t.length<8)return null;let e=nv(t);return!e||e.id==="coding"&&!/\b(fix|bug|crash|error|implement|add|create|change|update|refactor|rewrite|broken|fail|patch|migrate|port)\b/i.test(t)?null:Gm(e.id)}function ov(){let t=new Set;for(let e of[Ks,mc])try{for(let s of os.readdirSync(e))s.endsWith(".md")&&t.add(s.replace(".md",""))}catch{}return[...t].sort()}function rv(t,e){os.existsSync(Ks)||os.mkdirSync(Ks,{recursive:!0});let s=`<!-- Auto-extracted from high-scoring session \u2014 edit as needed -->
662
667
 
663
668
  user: ${e.user}
664
669
 
@@ -666,14 +671,14 @@ A: |
666
671
  ${e.assistant.split(`
667
672
  `).map(n=>` ${n}`).join(`
668
673
  `)}
669
- `;ss.writeFileSync(Wo.join(Ys,`${t}.md`),s,"utf-8")}Dm.exports={getFewShotForInput:jS,loadExampleForCategory:Im,listAvailableExamples:qS,savePrivateExample:FS,PRIVATE_EXAMPLES_DIR:Ys,BUNDLED_EXAMPLES_DIR:lc}});var Hm=Z((y1,Wm)=>{var vt=require("fs"),Gs=require("path"),{C:g1}=Ke(),{atomicWrite:BS,withFileLockSync:US}=Bn(),vi={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"},zs={...vi};function qm(){let t=Gs.join(process.cwd(),".nex","config.json");if(vt.existsSync(t))try{let e=JSON.parse(vt.readFileSync(t,"utf-8"));e.permissions&&(zs={...vi,...e.permissions})}catch{}}function WS(){let t=Gs.join(process.cwd(),".nex"),e=Gs.join(t,"config.json");vt.existsSync(t)||vt.mkdirSync(t,{recursive:!0}),US(e,()=>{let s={};if(vt.existsSync(e))try{s=JSON.parse(vt.readFileSync(e,"utf-8"))}catch{s={}}s.permissions=zs,BS(e,JSON.stringify(s,null,2))})}function Fm(t){return zs[t]||"ask"}function HS(t,e){return["allow","ask","deny"].includes(e)?(zs[t]=e,!0):!1}function YS(t){return Fm(t)}function GS(){return Object.entries(zs).map(([t,e])=>({tool:t,mode:e}))}function zS(){zs={...vi}}var Ho={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 Bm(){let t=Gs.join(process.cwd(),".nex","config.json");try{return vt.existsSync(t)&&JSON.parse(vt.readFileSync(t,"utf-8")).teamPermissions||null}catch{return null}}function KS(t){let e=Gs.join(process.cwd(),".nex"),s=Gs.join(e,"config.json");vt.existsSync(e)||vt.mkdirSync(e,{recursive:!0});let n={};try{vt.existsSync(s)&&(n=JSON.parse(vt.readFileSync(s,"utf-8")))}catch{n={}}n.teamPermissions=t,vt.writeFileSync(s,JSON.stringify(n,null,2),"utf-8")}function Um(){let t=Bm();if(!t)return Ho.admin;let e=t.role||"admin",s=Ho[e]||Ho.admin;return{...s,...t.overrides,blockedTools:[...s.blockedTools||[],...t.overrides?.blockedTools||[]]}}function XS(t){let e=Um();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 VS(){return Object.entries(Ho).map(([t,e])=>({name:t,description:e.description,toolCount:e.allowedTools?`${e.allowedTools.length} allowed`:"all allowed",blockedCount:e.blockedTools.length}))}qm();Wm.exports={getPermission:Fm,setPermission:HS,checkPermission:YS,listPermissions:GS,loadPermissions:qm,savePermissions:WS,resetPermissions:zS,DEFAULT_PERMISSIONS:vi,PERMISSION_PRESETS:Ho,loadPresetConfig:Bm,savePresetConfig:KS,getEffectivePreset:Um,isToolAllowed:XS,listPresets:VS}});var Ri=Z((_1,Xm)=>{var rs=require("fs"),Ei=require("path"),w1=require("readline"),{C:Te}=Ke(),Se=null,uc=!1,dc=null,Ym=new Set(["read_file","list_directory","search_files","glob","grep","web_search","web_fetch","git_status","git_diff","git_log","git_show"]);function Ti(){return Ei.join(process.cwd(),".nex","plans")}function Gm(){let t=Ti();rs.existsSync(t)||rs.mkdirSync(t,{recursive:!0})}function JS(t,e=[]){return Se={name:`plan-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,task:t,steps:e.map(s=>({description:s.description||s,files:s.files||[],status:"pending"})),status:"draft",createdAt:new Date().toISOString()},Se}function ZS(){return Se}function QS(t){uc=t}function ev(){return uc}function tv(){return!Se||Se.status!=="draft"?!1:(Se.status="approved",Se.updatedAt=new Date().toISOString(),!0)}function nv(){return!Se||Se.status!=="approved"?!1:(Se.status="executing",!0)}function cc(t,e){return!Se||t<0||t>=Se.steps.length?!1:(Se.steps[t].status=e,Se.updatedAt=new Date().toISOString(),Se.steps.every(s=>s.status==="done"||s.status==="skipped")&&(Se.status="completed"),!0)}function sv(t){if(!t)return`${Te.dim}No active plan${Te.reset}`;let e={draft:`${Te.yellow}DRAFT${Te.reset}`,approved:`${Te.green}APPROVED${Te.reset}`,executing:`${Te.blue}EXECUTING${Te.reset}`,completed:`${Te.green}COMPLETED${Te.reset}`},s=[];s.push(`
670
- ${Te.bold}${Te.cyan}Plan: ${t.task}${Te.reset}`),s.push(`${Te.dim}Status: ${e[t.status]||t.status}${Te.reset}
671
- `);for(let n=0;n<t.steps.length;n++){let o=t.steps[n],r;switch(o.status){case"done":r=`${Te.green}\u2713${Te.reset}`;break;case"in_progress":r=`${Te.blue}\u2192${Te.reset}`;break;case"skipped":r=`${Te.dim}\u25CB${Te.reset}`;break;default:r=`${Te.dim} ${Te.reset}`}s.push(` ${r} ${Te.bold}Step ${n+1}:${Te.reset} ${o.description}`),o.files.length>0&&s.push(` ${Te.dim}Files: ${o.files.join(", ")}${Te.reset}`)}return s.push(""),s.join(`
672
- `)}function ov(t){if(t||(t=Se),!t)return null;Gm();let e=Ei.join(Ti(),`${t.name}.json`);return rs.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function rv(t){let e=Ei.join(Ti(),`${t}.json`);if(!rs.existsSync(e))return null;try{let s=JSON.parse(rs.readFileSync(e,"utf-8"));return Se=s,s}catch{return null}}function iv(){Gm();let t=Ti(),e=rs.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(rs.readFileSync(Ei.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 av(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 l=0;l<Math.min(e.length,a.length);l++){let c=a[l][1];e[l].files=c.split(/[,\s]+/).filter(u=>/[./]/.test(u)).slice(0,5)}}return e}function lv(t){dc=t}function cv(){return dc}function uv(){Se=null,uc=!1,dc=null,hv()}function dv(){return`
674
+ `;os.writeFileSync(zo.join(Ks,`${t}.md`),s,"utf-8")}zm.exports={getFewShotForInput:sv,loadExampleForCategory:Gm,listAvailableExamples:ov,savePrivateExample:rv,PRIVATE_EXAMPLES_DIR:Ks,BUNDLED_EXAMPLES_DIR:mc}});var eg=Q((D1,Qm)=>{var vt=require("fs"),Xs=require("path"),{C:I1}=Ke(),{atomicWrite:iv,withFileLockSync:av}=Fn(),Ai={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"},Vs={...Ai};function Xm(){let t=Xs.join(process.cwd(),".nex","config.json");if(vt.existsSync(t))try{let e=JSON.parse(vt.readFileSync(t,"utf-8"));e.permissions&&(Vs={...Ai,...e.permissions})}catch{}}function lv(){let t=Xs.join(process.cwd(),".nex"),e=Xs.join(t,"config.json");vt.existsSync(t)||vt.mkdirSync(t,{recursive:!0}),av(e,()=>{let s={};if(vt.existsSync(e))try{s=JSON.parse(vt.readFileSync(e,"utf-8"))}catch{s={}}s.permissions=Vs,iv(e,JSON.stringify(s,null,2))})}function Vm(t){return Vs[t]||"ask"}function cv(t,e){return["allow","ask","deny"].includes(e)?(Vs[t]=e,!0):!1}function uv(t){return Vm(t)}function dv(){return Object.entries(Vs).map(([t,e])=>({tool:t,mode:e}))}function fv(){Vs={...Ai}}var Ko={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 Jm(){let t=Xs.join(process.cwd(),".nex","config.json");try{return vt.existsSync(t)&&JSON.parse(vt.readFileSync(t,"utf-8")).teamPermissions||null}catch{return null}}function pv(t){let e=Xs.join(process.cwd(),".nex"),s=Xs.join(e,"config.json");vt.existsSync(e)||vt.mkdirSync(e,{recursive:!0});let n={};try{vt.existsSync(s)&&(n=JSON.parse(vt.readFileSync(s,"utf-8")))}catch{n={}}n.teamPermissions=t,vt.writeFileSync(s,JSON.stringify(n,null,2),"utf-8")}function Zm(){let t=Jm();if(!t)return Ko.admin;let e=t.role||"admin",s=Ko[e]||Ko.admin;return{...s,...t.overrides,blockedTools:[...s.blockedTools||[],...t.overrides?.blockedTools||[]]}}function hv(t){let e=Zm();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 mv(){return Object.entries(Ko).map(([t,e])=>({name:t,description:e.description,toolCount:e.allowedTools?`${e.allowedTools.length} allowed`:"all allowed",blockedCount:e.blockedTools.length}))}Xm();Qm.exports={getPermission:Vm,setPermission:cv,checkPermission:uv,listPermissions:dv,loadPermissions:Xm,savePermissions:lv,resetPermissions:fv,DEFAULT_PERMISSIONS:Ai,PERMISSION_PRESETS:Ko,loadPresetConfig:Jm,savePresetConfig:pv,getEffectivePreset:Zm,isToolAllowed:hv,listPresets:mv}});var Mi=Q((q1,rg)=>{var is=require("fs"),Oi=require("path"),j1=require("readline"),{C:Re}=Ke(),ve=null,yc=!1,wc=null,tg=new Set(["read_file","list_directory","search_files","glob","grep","web_search","web_fetch","git_status","git_diff","git_log","git_show"]);function Ni(){return Oi.join(process.cwd(),".nex","plans")}function ng(){let t=Ni();is.existsSync(t)||is.mkdirSync(t,{recursive:!0})}function gv(t,e=[]){return ve={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()},ve}function yv(){return ve}function wv(t){yc=t}function _v(){return yc}function $v(){return!ve||ve.status!=="draft"?!1:(ve.status="approved",ve.updatedAt=new Date().toISOString(),!0)}function bv(){return!ve||ve.status!=="approved"?!1:(ve.status="executing",!0)}function gc(t,e){return!ve||t<0||t>=ve.steps.length?!1:(ve.steps[t].status=e,ve.updatedAt=new Date().toISOString(),ve.steps.every(s=>s.status==="done"||s.status==="skipped")&&(ve.status="completed"),!0)}function xv(t){if(!t)return`${Re.dim}No active plan${Re.reset}`;let e={draft:`${Re.yellow}DRAFT${Re.reset}`,approved:`${Re.green}APPROVED${Re.reset}`,executing:`${Re.blue}EXECUTING${Re.reset}`,completed:`${Re.green}COMPLETED${Re.reset}`},s=[];s.push(`
675
+ ${Re.bold}${Re.cyan}Plan: ${t.task}${Re.reset}`),s.push(`${Re.dim}Status: ${e[t.status]||t.status}${Re.reset}
676
+ `);for(let n=0;n<t.steps.length;n++){let o=t.steps[n],r;switch(o.status){case"done":r=`${Re.green}\u2713${Re.reset}`;break;case"in_progress":r=`${Re.blue}\u2192${Re.reset}`;break;case"skipped":r=`${Re.dim}\u25CB${Re.reset}`;break;default:r=`${Re.dim} ${Re.reset}`}s.push(` ${r} ${Re.bold}Step ${n+1}:${Re.reset} ${o.description}`),o.files.length>0&&s.push(` ${Re.dim}Files: ${o.files.join(", ")}${Re.reset}`)}return s.push(""),s.join(`
677
+ `)}function kv(t){if(t||(t=ve),!t)return null;ng();let e=Oi.join(Ni(),`${t.name}.json`);return is.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function Sv(t){let e=Oi.join(Ni(),`${t}.json`);if(!is.existsSync(e))return null;try{let s=JSON.parse(is.readFileSync(e,"utf-8"));return ve=s,s}catch{return null}}function vv(){ng();let t=Ni(),e=is.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(is.readFileSync(Oi.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 Ev(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 l=0;l<Math.min(e.length,a.length);l++){let c=a[l][1];e[l].files=c.split(/[,\s]+/).filter(u=>/[./]/.test(u)).slice(0,5)}}return e}function Tv(t){wc=t}function Rv(){return wc}function Cv(){ve=null,yc=!1,wc=null,Mv()}function Av(){return`
673
678
  PLAN MODE ACTIVE: You are in analysis-only mode. You MUST NOT execute any changes.
674
679
 
675
680
  # Allowed Tools (read-only)
676
- You may ONLY use these tools: ${[...Ym].join(", ")}
681
+ You may ONLY use these tools: ${[...tg].join(", ")}
677
682
  Any other tool call will be blocked and returned with an error.
678
683
 
679
684
  # MANDATORY: Read Before You Plan
@@ -717,26 +722,26 @@ Bullet list of potential issues and mitigations.
717
722
  - Order steps by dependency (later steps may depend on earlier ones).
718
723
  - After presenting the plan, tell the user to type \`/plan approve\` to proceed.
719
724
  - Do NOT make any file changes \u2014 your role is analysis and planning only.
720
- - 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 os=0;function fv(){!Se||Se.status!=="executing"||(os>0&&cc(os-1,"done"),os<Se.steps.length&&(cc(os,"in_progress"),os++))}function pv(){if(!Se||Se.status!=="executing"||Se.steps.length===0)return null;let t=Math.min(os,Se.steps.length),e=Se.steps.length,s=Math.max(0,t-1),n=Se.steps[s]?.description||"";return{current:t,total:e,description:n}}function hv(){os=0}var zm=["interactive","semi-auto","autonomous"],Km="interactive";function mv(t){return zm.includes(t)?(Km=t,!0):!1}function gv(){return Km}Xm.exports={createPlan:JS,getActivePlan:ZS,setPlanMode:QS,isPlanMode:ev,approvePlan:tv,startExecution:nv,updateStep:cc,formatPlan:sv,savePlan:ov,loadPlan:rv,listPlans:iv,clearPlan:uv,getPlanModePrompt:dv,setPlanContent:lv,getPlanContent:cv,extractStepsFromText:av,advancePlanStep:fv,getPlanStepInfo:pv,PLAN_MODE_ALLOWED_TOOLS:Ym,setAutonomyLevel:mv,getAutonomyLevel:gv,AUTONOMY_LEVELS:zm}});var ig=Z(($1,rg)=>{var{C:x}=Ke();function Vm(){return Math.max(10,(process.stdout.columns||80)-2)}function yv(t){if(!t)return"";let e=t.split(`
721
- `),s=[],n=!1,o="";for(let r of e){let i=Vm();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(` ${pc(r,o)}`);continue}if(r.startsWith("###### ")){s.push(`${x.bold}${x.cyan} ${Et(r.substring(7))}${x.reset}`);continue}if(r.startsWith("##### ")){s.push(`${x.bold}${x.cyan} ${Et(r.substring(6))}${x.reset}`);continue}if(r.startsWith("#### ")){s.push(`${x.bold}${x.cyan} ${Et(r.substring(5))}${x.reset}`);continue}if(r.startsWith("### ")){s.push(`${x.bold}${x.cyan} ${Et(r.substring(4))}${x.reset}`);continue}if(r.startsWith("## ")){s.push(`${x.bold}${x.cyan} ${Et(r.substring(3))}${x.reset}`);continue}if(r.startsWith("# ")){s.push(`${x.bold}${x.cyan}${Et(r.substring(2))}${x.reset}`);continue}if(/^\s*[-*]\s/.test(r)){let a=r.match(/^(\s*)/)[1],l=r.replace(/^\s*[-*]\s/,""),c=`${a}${x.cyan}\u2022${x.reset} ${is(l)}`;s.push(as(c,i,a+" "));continue}if(/^\s*\d+\.\s/.test(r)){let a=r.match(/^(\s*)(\d+)\.\s(.*)/);if(a){let l=a[1],c=a[2],u=a[3],d=`${l}${x.cyan}${c}.${x.reset} ${is(u)}`,f=l+" ".repeat(c.length+2);s.push(as(d,i,f));continue}}s.push(as(is(r),i))}return s.join(`
722
- `)}function Et(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function is(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 pc(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?Jm(t):e==="bash"||e==="sh"||e==="shell"||e==="zsh"?Zm(t):e==="json"||e==="jsonc"?Qm(t):e==="python"||e==="py"?eg(t):e==="go"||e==="golang"?tg(t):e==="rust"||e==="rs"?ng(t):e==="css"||e==="scss"||e==="less"?sg(t):e==="html"||e==="xml"||e==="svg"||e==="htm"?og(t):t:""}function Jm(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 Zm(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 Qm(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 eg(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 tg(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 ng(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 sg(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 og(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 as(t,e,s=""){if(!e||e<10)return t;let n="",o=0,r=-1,i=0,a=0,l=t.length;for(;i<l;){if(t[i]==="\x1B"){let c=i+1;if(c<l&&t[c]==="["){for(c++;c<l&&!/[a-zA-Z]/.test(t[c]);)c++;c<l&&c++}i=c;continue}if(t[i]===" "&&(r=i),o++,o>e&&r!==-1){n+=t.slice(a,r)+`
725
+ - 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 rs=0;function Ov(){!ve||ve.status!=="executing"||(rs>0&&gc(rs-1,"done"),rs<ve.steps.length&&(gc(rs,"in_progress"),rs++))}function Nv(){if(!ve||ve.status!=="executing"||ve.steps.length===0)return null;let t=Math.min(rs,ve.steps.length),e=ve.steps.length,s=Math.max(0,t-1),n=ve.steps[s]?.description||"";return{current:t,total:e,description:n}}function Mv(){rs=0}var sg=["interactive","semi-auto","autonomous"],og="interactive";function Pv(t){return sg.includes(t)?(og=t,!0):!1}function Lv(){return og}rg.exports={createPlan:gv,getActivePlan:yv,setPlanMode:wv,isPlanMode:_v,approvePlan:$v,startExecution:bv,updateStep:gc,formatPlan:xv,savePlan:kv,loadPlan:Sv,listPlans:vv,clearPlan:Cv,getPlanModePrompt:Av,setPlanContent:Tv,getPlanContent:Rv,extractStepsFromText:Ev,advancePlanStep:Ov,getPlanStepInfo:Nv,PLAN_MODE_ALLOWED_TOOLS:tg,setAutonomyLevel:Pv,getAutonomyLevel:Lv,AUTONOMY_LEVELS:sg}});var gg=Q((F1,mg)=>{var{C:k}=Ke();function ig(){return Math.max(10,(process.stdout.columns||80)-2)}function Iv(t){if(!t)return"";let e=t.split(`
726
+ `),s=[],n=!1,o="";for(let r of e){let i=ig();if(r.trim().startsWith("```")){if(n)s.push(`${k.dim}${"\u2500".repeat(40)}${k.reset}`),n=!1,o="";else{n=!0,o=r.trim().substring(3).trim();let a=o?` ${o} `:"";s.push(`${k.dim}${"\u2500".repeat(3)}${a}${"\u2500".repeat(Math.max(0,37-a.length))}${k.reset}`)}continue}if(n){s.push(` ${$c(r,o)}`);continue}if(r.startsWith("###### ")){s.push(`${k.bold}${k.cyan} ${Et(r.substring(7))}${k.reset}`);continue}if(r.startsWith("##### ")){s.push(`${k.bold}${k.cyan} ${Et(r.substring(6))}${k.reset}`);continue}if(r.startsWith("#### ")){s.push(`${k.bold}${k.cyan} ${Et(r.substring(5))}${k.reset}`);continue}if(r.startsWith("### ")){s.push(`${k.bold}${k.cyan} ${Et(r.substring(4))}${k.reset}`);continue}if(r.startsWith("## ")){s.push(`${k.bold}${k.cyan} ${Et(r.substring(3))}${k.reset}`);continue}if(r.startsWith("# ")){s.push(`${k.bold}${k.cyan}${Et(r.substring(2))}${k.reset}`);continue}if(/^\s*[-*]\s/.test(r)){let a=r.match(/^(\s*)/)[1],l=r.replace(/^\s*[-*]\s/,""),c=`${a}${k.cyan}\u2022${k.reset} ${as(l)}`;s.push(ls(c,i,a+" "));continue}if(/^\s*\d+\.\s/.test(r)){let a=r.match(/^(\s*)(\d+)\.\s(.*)/);if(a){let l=a[1],c=a[2],u=a[3],d=`${l}${k.cyan}${c}.${k.reset} ${as(u)}`,f=l+" ".repeat(c.length+2);s.push(ls(d,i,f));continue}}s.push(ls(as(r),i))}return s.join(`
727
+ `)}function Et(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function as(t){return t?t.replace(/`([^`]+)`/g,`${k.cyan}$1${k.reset}`).replace(/\*\*([^*]+)\*\*/g,`${k.bold}$1${k.reset}`).replace(/\*([^*]+)\*/g,`${k.dim}$1${k.reset}`).replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${k.cyan}$1${k.reset} ${k.dim}($2)${k.reset}`):""}function $c(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?ag(t):e==="bash"||e==="sh"||e==="shell"||e==="zsh"?lg(t):e==="json"||e==="jsonc"?cg(t):e==="python"||e==="py"?ug(t):e==="go"||e==="golang"?dg(t):e==="rust"||e==="rs"?fg(t):e==="css"||e==="scss"||e==="less"?pg(t):e==="html"||e==="xml"||e==="svg"||e==="htm"?hg(t):t:""}function ag(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,`${k.yellow}$1${k.reset}`),r=r.replace(e,`${k.magenta}$1${k.reset}`),r=r.replace(s,`${k.green}$&${k.reset}`),r=r.replace(n,`${k.dim}$1${k.reset}`),r}function lg(t){let e=/^(\s*)([\w-]+)/,s=/(--?\w[\w-]*)/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(#.*$)/,r=t;return r=r.replace(s,`${k.cyan}$1${k.reset}`),r=r.replace(e,`$1${k.green}$2${k.reset}`),r=r.replace(n,`${k.yellow}$&${k.reset}`),r=r.replace(o,`${k.dim}$1${k.reset}`),r}function cg(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,`${k.cyan}$1${k.reset}:`),r=r.replace(s,`: ${k.green}$1${k.reset}`),r=r.replace(n,`: ${k.yellow}$1${k.reset}`),r=r.replace(o,`: ${k.magenta}$1${k.reset}`),r}function ug(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,`${k.yellow}$1${k.reset}`),i=i.replace(e,`${k.magenta}$1${k.reset}`),i=i.replace(r,`${k.cyan}$1${k.reset}`),i=i.replace(s,`${k.green}$&${k.reset}`),i=i.replace(n,`${k.dim}$1${k.reset}`),i}function dg(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,`${k.yellow}$1${k.reset}`),i=i.replace(s,`${k.cyan}$1${k.reset}`),i=i.replace(e,`${k.magenta}$1${k.reset}`),i=i.replace(n,`${k.green}$&${k.reset}`),i=i.replace(o,`${k.dim}$1${k.reset}`),i}function fg(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,`${k.yellow}$1${k.reset}`),a=a.replace(s,`${k.cyan}$1${k.reset}`),a=a.replace(e,`${k.magenta}$1${k.reset}`),a=a.replace(i,`${k.yellow}$1${k.reset}`),a=a.replace(n,`${k.green}$&${k.reset}`),a=a.replace(o,`${k.dim}$1${k.reset}`),a}function pg(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,`${k.yellow}$1${k.reset}`),a=a.replace(o,`${k.yellow}$1${k.reset}`),a=a.replace(e,`$1${k.cyan}$2${k.reset}:`),a=a.replace(n,`$1${k.magenta}$&${k.reset}`),a=a.replace(r,`${k.dim}$1${k.reset}`),a}function hg(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,`${k.dim}$1${k.reset}`),i=i.replace(n,`${k.green}$&${k.reset}`),i=i.replace(e,`<${k.magenta}$1${k.reset}`),i=i.replace(s,` ${k.cyan}$1${k.reset}=`),i=i.replace(r,`${k.yellow}$1${k.reset}`),i}function ls(t,e,s=""){if(!e||e<10)return t;let n="",o=0,r=-1,i=0,a=0,l=t.length;for(;i<l;){if(t[i]==="\x1B"){let c=i+1;if(c<l&&t[c]==="["){for(c++;c<l&&!/[a-zA-Z]/.test(t[c]);)c++;c<l&&c++}i=c;continue}if(t[i]===" "&&(r=i),o++,o>e&&r!==-1){n+=t.slice(a,r)+`
723
728
  `+s,a=r+1,i=a,o=s.length,r=-1;continue}o>e&&r===-1&&(n+=t.slice(a,i)+`
724
- `+s,a=i,o=s.length+1),i++}return n+=t.slice(a),n}function wv(t,e){if(!t||t.length===0)return"";let s=t.map((i,a)=>{let l=e.reduce((c,u)=>Math.max(c,(u[a]||"").length),0);return Math.max(i.length,l)}),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((l,c)=>` ${(i[c]||"").padEnd(s[c])} `).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(`
725
- `)}function _v(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 fc=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?`${Bt().T.cyan}\u25CF${Bt().T.reset}`:" ";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(`
726
- `))!==-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}
727
- `),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){let s=Vm();if(e.trim().startsWith("```")){if(this.inCodeBlock)this._safeWrite(`${x.dim}${"\u2500".repeat(40)}${x.reset}
728
- `),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}
729
- `)}return}if(this.inCodeBlock){this._safeWrite(` ${pc(e,this.codeBlockLang)}
730
- `);return}if(e.startsWith("###### ")){this._safeWrite(`${x.bold}${x.cyan} ${Et(e.substring(7))}${x.reset}
731
- `);return}if(e.startsWith("##### ")){this._safeWrite(`${x.bold}${x.cyan} ${Et(e.substring(6))}${x.reset}
732
- `);return}if(e.startsWith("#### ")){this._safeWrite(`${x.bold}${x.cyan} ${Et(e.substring(5))}${x.reset}
733
- `);return}if(e.startsWith("### ")){this._safeWrite(`${x.bold}${x.cyan} ${Et(e.substring(4))}${x.reset}
734
- `);return}if(e.startsWith("## ")){this._safeWrite(`${x.bold}${x.cyan} ${Et(e.substring(3))}${x.reset}
735
- `);return}if(e.startsWith("# ")){this._safeWrite(`${x.bold}${x.cyan}${Et(e.substring(2))}${x.reset}
736
- `);return}if(/^\s*[-*]\s/.test(e)){let o=e.match(/^(\s*)/)[1],r=e.replace(/^\s*[-*]\s/,""),i=`${o}${x.cyan}\u2022${x.reset} ${is(r)}`,a=as(i,s,o+" ");this._safeWrite(`${a}
737
- `);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],l=`${r}${x.cyan}${i}.${x.reset} ${is(a)}`,c=r+" ".repeat(i.length+2),u=as(l,s,c);this._safeWrite(`${u}
738
- `);return}}let n=as(is(e),s);this._safeWrite(`${n}
739
- `)}};rg.exports={renderMarkdown:yv,renderInline:is,stripHeadingMarkers:Et,highlightCode:pc,highlightJS:Jm,highlightBash:Zm,highlightJSON:Qm,highlightPython:eg,highlightGo:tg,highlightRust:ng,highlightCSS:sg,highlightHTML:og,renderTable:wv,renderProgress:_v,wrapAnsi:as,StreamRenderer:fc}});var dg=Z((b1,ug)=>{var{execSync:$v}=require("child_process"),hc=require("path"),Yo=require("fs"),mc=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function ag(){return hc.join(process.cwd(),".nex","hooks")}function bv(){return hc.join(process.cwd(),".nex","config.json")}function lg(){let t=bv();if(!Yo.existsSync(t))return{};try{return JSON.parse(Yo.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function Ci(t){if(!mc.includes(t))return[];let e=[],s=ag(),n=hc.join(s,t);Yo.existsSync(n)&&e.push(n);let o=lg();if(o[t]){let r=Array.isArray(o[t])?o[t]:[o[t]];e.push(...r)}return e}function cg(t,e={},s=3e4){try{return{success:!0,exitCode:0,output:$v(t,{cwd:process.cwd(),encoding:"utf-8",timeout:s,env:{...process.env,...e},stdio:["pipe","pipe","pipe"]}).trim()}}catch(n){let o=typeof n.status=="number"?n.status:1;return{success:!1,exitCode:o,blocked:o===2,output:n.stdout?n.stdout.trim():"",error:n.stderr?n.stderr.trim():n.message}}}function xv(t,e={}){let s=Ci(t);if(s.length===0)return{results:[],blocked:!1};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=cg(r,n);if(o.push({command:r,...i}),i.blocked&&t.startsWith("pre-")){let a=i.output||i.error||"hook blocked tool call";return{results:o,blocked:!0,blockReason:a}}if(!i.success&&t.startsWith("pre-"))break}return{results:o,blocked:!1}}function kv(t){return Ci(t).length>0}function Sv(){let t=[];for(let e of mc){let s=Ci(e);s.length>0&&t.push({event:e,commands:s})}return t}function vv(){let t=ag();return Yo.existsSync(t)||Yo.mkdirSync(t,{recursive:!0}),t}ug.exports={HOOK_EVENTS:mc,loadHookConfig:lg,getHooksForEvent:Ci,executeHook:cg,runHooks:xv,hasHooks:kv,listHooks:Sv,initHooksDir:vv}});var Eg=Z((v1,vg)=>{"use strict";var{callWithRetry:pg,runSubAgent:Ev,clearAllLocks:Tv}=Il(),{parseModelSpec:hg,getActiveProviderName:x1,getActiveModelId:k1}=Ze(),{detectCategory:Rv,getModelForCategory:fg}=Hs(),{MultiProgress:Cv,C:de}=Ke(),{getModelBriefing:S1}=oi(),mg=parseInt(process.env.NEX_MAX_PARALLEL||"4",10),Ai=parseInt(process.env.NEX_MAX_SUBTASKS||"8",10),gg="devstral-2:123b",yg="kimi-k2.5",wg=`You are a task decomposition engine. Given a complex user request, split it into independent, atomic sub-tasks.
729
+ `+s,a=i,o=s.length+1),i++}return n+=t.slice(a),n}function Dv(t,e){if(!t||t.length===0)return"";let s=t.map((i,a)=>{let l=e.reduce((c,u)=>Math.max(c,(u[a]||"").length),0);return Math.max(i.length,l)}),n=s.map(i=>"\u2500".repeat(i+2)).join("\u253C"),o=t.map((i,a)=>` ${k.bold}${i.padEnd(s[a])}${k.reset} `).join("\u2502"),r=[];r.push(`${k.dim}\u250C${n.replace(/┼/g,"\u252C")}\u2510${k.reset}`),r.push(`${k.dim}\u2502${k.reset}${o}${k.dim}\u2502${k.reset}`),r.push(`${k.dim}\u251C${n}\u2524${k.reset}`);for(let i of e){let a=t.map((l,c)=>` ${(i[c]||"").padEnd(s[c])} `).join(`${k.dim}\u2502${k.reset}`);r.push(`${k.dim}\u2502${k.reset}${a}${k.dim}\u2502${k.reset}`)}return r.push(`${k.dim}\u2514${n.replace(/┼/g,"\u2534")}\u2518${k.reset}`),r.join(`
730
+ `)}function jv(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?k.green:o>50?k.yellow:k.cyan;return` ${t} ${a}${"\u2588".repeat(r)}${k.dim}${"\u2591".repeat(i)}${k.reset} ${o}% (${e}/${s})`}var _c=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?`${Bt().T.cyan}\u25CF${Bt().T.reset}`:" ";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(`
731
+ `))!==-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(`${k.dim}${"\u2500".repeat(40)}${k.reset}
732
+ `),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){let s=ig();if(e.trim().startsWith("```")){if(this.inCodeBlock)this._safeWrite(`${k.dim}${"\u2500".repeat(40)}${k.reset}
733
+ `),this.inCodeBlock=!1,this.codeBlockLang="";else{this.inCodeBlock=!0,this.codeBlockLang=e.trim().substring(3).trim();let o=this.codeBlockLang?` ${this.codeBlockLang} `:"";this._safeWrite(`${k.dim}${"\u2500".repeat(3)}${o}${"\u2500".repeat(Math.max(0,37-o.length))}${k.reset}
734
+ `)}return}if(this.inCodeBlock){this._safeWrite(` ${$c(e,this.codeBlockLang)}
735
+ `);return}if(e.startsWith("###### ")){this._safeWrite(`${k.bold}${k.cyan} ${Et(e.substring(7))}${k.reset}
736
+ `);return}if(e.startsWith("##### ")){this._safeWrite(`${k.bold}${k.cyan} ${Et(e.substring(6))}${k.reset}
737
+ `);return}if(e.startsWith("#### ")){this._safeWrite(`${k.bold}${k.cyan} ${Et(e.substring(5))}${k.reset}
738
+ `);return}if(e.startsWith("### ")){this._safeWrite(`${k.bold}${k.cyan} ${Et(e.substring(4))}${k.reset}
739
+ `);return}if(e.startsWith("## ")){this._safeWrite(`${k.bold}${k.cyan} ${Et(e.substring(3))}${k.reset}
740
+ `);return}if(e.startsWith("# ")){this._safeWrite(`${k.bold}${k.cyan}${Et(e.substring(2))}${k.reset}
741
+ `);return}if(/^\s*[-*]\s/.test(e)){let o=e.match(/^(\s*)/)[1],r=e.replace(/^\s*[-*]\s/,""),i=`${o}${k.cyan}\u2022${k.reset} ${as(r)}`,a=ls(i,s,o+" ");this._safeWrite(`${a}
742
+ `);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],l=`${r}${k.cyan}${i}.${k.reset} ${as(a)}`,c=r+" ".repeat(i.length+2),u=ls(l,s,c);this._safeWrite(`${u}
743
+ `);return}}let n=ls(as(e),s);this._safeWrite(`${n}
744
+ `)}};mg.exports={renderMarkdown:Iv,renderInline:as,stripHeadingMarkers:Et,highlightCode:$c,highlightJS:ag,highlightBash:lg,highlightJSON:cg,highlightPython:ug,highlightGo:dg,highlightRust:fg,highlightCSS:pg,highlightHTML:hg,renderTable:Dv,renderProgress:jv,wrapAnsi:ls,StreamRenderer:_c}});var bg=Q((B1,$g)=>{var{execSync:qv}=require("child_process"),bc=require("path"),Xo=require("fs"),xc=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function yg(){return bc.join(process.cwd(),".nex","hooks")}function Fv(){return bc.join(process.cwd(),".nex","config.json")}function wg(){let t=Fv();if(!Xo.existsSync(t))return{};try{return JSON.parse(Xo.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function Pi(t){if(!xc.includes(t))return[];let e=[],s=yg(),n=bc.join(s,t);Xo.existsSync(n)&&e.push(n);let o=wg();if(o[t]){let r=Array.isArray(o[t])?o[t]:[o[t]];e.push(...r)}return e}function _g(t,e={},s=3e4){try{return{success:!0,exitCode:0,output:qv(t,{cwd:process.cwd(),encoding:"utf-8",timeout:s,env:{...process.env,...e},stdio:["pipe","pipe","pipe"]}).trim()}}catch(n){let o=typeof n.status=="number"?n.status:1;return{success:!1,exitCode:o,blocked:o===2,output:n.stdout?n.stdout.trim():"",error:n.stderr?n.stderr.trim():n.message}}}function Bv(t,e={}){let s=Pi(t);if(s.length===0)return{results:[],blocked:!1};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=_g(r,n);if(o.push({command:r,...i}),i.blocked&&t.startsWith("pre-")){let a=i.output||i.error||"hook blocked tool call";return{results:o,blocked:!0,blockReason:a}}if(!i.success&&t.startsWith("pre-"))break}return{results:o,blocked:!1}}function Uv(t){return Pi(t).length>0}function Wv(){let t=[];for(let e of xc){let s=Pi(e);s.length>0&&t.push({event:e,commands:s})}return t}function Hv(){let t=yg();return Xo.existsSync(t)||Xo.mkdirSync(t,{recursive:!0}),t}$g.exports={HOOK_EVENTS:xc,loadHookConfig:wg,getHooksForEvent:Pi,executeHook:_g,runHooks:Bv,hasHooks:Uv,listHooks:Wv,initHooksDir:Hv}});var Ig=Q((Y1,Lg)=>{"use strict";var{callWithRetry:kg,runSubAgent:Yv,clearAllLocks:Gv}=Wl(),{parseModelSpec:Sg,getActiveProviderName:U1,getActiveModelId:W1}=Qe(),{detectCategory:zv,getModelForCategory:xg}=ss(),{MultiProgress:Kv,C:de}=Ke(),{getModelBriefing:H1}=li(),vg=parseInt(process.env.NEX_MAX_PARALLEL||"4",10),Li=parseInt(process.env.NEX_MAX_SUBTASKS||"8",10),Eg="devstral-2:123b",Tg="kimi-k2.5",Rg=`You are a task decomposition engine. Given a complex user request, split it into independent, atomic sub-tasks.
740
745
 
741
746
  RULES:
742
747
  - Output ONLY a JSON array, no markdown fences, no explanation.
@@ -751,7 +756,7 @@ RULES:
751
756
  - If the request is simple (single goal), return an array with exactly 1 item.
752
757
 
753
758
  USER REQUEST:
754
- {prompt}`,_g=`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.
759
+ {prompt}`,Cg=`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.
755
760
 
756
761
  RULES:
757
762
  - Output ONLY a JSON object with these fields:
@@ -765,16 +770,16 @@ ORIGINAL REQUEST:
765
770
  {prompt}
766
771
 
767
772
  SUB-AGENT RESULTS:
768
- {results}`;async function $g(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 bg(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 Av(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(c=>c.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 gc(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:
769
- ${e.slice(0,200)}`)}async function xg(t,e,s={}){let n=s.maxSubTasks||Ai,r=[{role:"system",content:wg.replace("{maxSubTasks}",String(n)).replace("{prompt}",t)},{role:"user",content:t}],i={};if(e){let g=hg(e);g.provider&&(i.provider=g.provider),g.model&&(i.model=g.model)}let l=(await pg(r,[],i)).content||"",c=gc(l);if(!Array.isArray(c))throw new Error(`Decompose returned non-array: ${typeof c}`);let u=10,f=c.slice(0,n).map((g,_)=>({id:g.id||`t${_+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:_+1})).filter(g=>g.task.length>0),p=f.reduce((g,_)=>g+_.estimatedCalls,0),h=Ai*u;if(p>h){let{debugLog:g}=Ca();g(`${Bt().T.yellow} \u26A0 Orchestrator: total estimated calls ${p} > ${h} \u2014 consider raising maxSubTasks${Bt().T.reset}`)}return f}async function kg(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}] ---
773
+ {results}`;async function Ag(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 Og(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 Xv(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(c=>c.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 kc(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:
774
+ ${e.slice(0,200)}`)}async function Ng(t,e,s={}){let n=s.maxSubTasks||Li,r=[{role:"system",content:Rg.replace("{maxSubTasks}",String(n)).replace("{prompt}",t)},{role:"user",content:t}],i={};if(e){let g=Sg(e);g.provider&&(i.provider=g.provider),g.model&&(i.model=g.model)}let l=(await kg(r,[],i)).content||"",c=kc(l);if(!Array.isArray(c))throw new Error(`Decompose returned non-array: ${typeof c}`);let u=10,f=c.slice(0,n).map((g,_)=>({id:g.id||`t${_+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:_+1})).filter(g=>g.task.length>0),p=f.reduce((g,_)=>g+_.estimatedCalls,0),m=Li*u;if(p>m){let{debugLog:g}=La();g(`${Bt().T.yellow} \u26A0 Orchestrator: total estimated calls ${p} > ${m} \u2014 consider raising maxSubTasks${Bt().T.reset}`)}return f}async function Mg(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}] ---
770
775
  Task: ${u.task}
771
776
  Result: ${u.result}
772
777
  Tools: ${(u.toolsUsed||[]).join(", ")||"none"}`}).join(`
773
778
 
774
- `),r=[{role:"system",content:_g.replace("{prompt}",e).replace("{results}",n)},{role:"user",content:"Synthesize the sub-agent results above."}],i={};if(s){let u=hg(s);u.provider&&(i.provider=u.provider),u.model&&(i.model=u.model)}let l=(await pg(r,[],i)).content||"",c=gc(l);return{summary:String(c.summary||""),conflicts:Array.isArray(c.conflicts)?c.conflicts:[],commitMessage:String(c.commitMessage||""),filesChanged:Array.isArray(c.filesChanged)?c.filesChanged:[]}}async function Ov(t,e={}){let s=e.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL||yg,n=e.workerModel||gg,o=e.maxParallel||mg,r=e.maxSubTasks||Ai,i=e.onProgress||(()=>{}),a={input:0,output:0};console.log(`
779
+ `),r=[{role:"system",content:Cg.replace("{prompt}",e).replace("{results}",n)},{role:"user",content:"Synthesize the sub-agent results above."}],i={};if(s){let u=Sg(s);u.provider&&(i.provider=u.provider),u.model&&(i.model=u.model)}let l=(await kg(r,[],i)).content||"",c=kc(l);return{summary:String(c.summary||""),conflicts:Array.isArray(c.conflicts)?c.conflicts:[],commitMessage:String(c.commitMessage||""),filesChanged:Array.isArray(c.filesChanged)?c.filesChanged:[]}}async function Vv(t,e={}){let s=e.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL||Tg,n=e.workerModel||Eg,o=e.maxParallel||vg,r=e.maxSubTasks||Li,i=e.onProgress||(()=>{}),a={input:0,output:0};console.log(`
775
780
  ${de.bold}Orchestrator${de.reset} ${de.dim}model: ${s} | workers: ${n} | max parallel: ${o}${de.reset}
776
- `),i("decomposing"),console.log(`${de.dim}Phase 1: Decomposing prompt into sub-tasks...${de.reset}`);let l;try{l=await xg(t,s,{maxSubTasks:r})}catch(H){return console.log(`${de.red}Decompose failed: ${H.message}${de.reset}`),{results:[],synthesis:{summary:`Decompose failed: ${H.message}`,conflicts:[],commitMessage:"",resourcesChanged:[]},totalTokens:a}}if(l.length===0)return console.log(`${de.yellow}No sub-tasks generated. Prompt may be too simple for orchestration.${de.reset}`),{results:[],synthesis:{summary:"No sub-tasks generated.",conflicts:[],commitMessage:"",resourcesChanged:[]},totalTokens:a};console.log(`${de.green}Decomposed into ${l.length} sub-tasks:${de.reset}`);for(let H of l){console.log(` ${de.dim}${H.id}:${de.reset} ${H.task}`);let X=H.scope.filter(Boolean);X.length>0&&console.log(` ${de.dim}scope: ${X.join(", ")}${de.reset}`)}console.log("");let c=new Map;for(let H=0;H<l.length;H++)for(let X of l[H].scope)X&&!c.has(X)&&c.set(X,H);i("executing"),console.log(`${de.dim}Phase 2: Running ${l.length} sub-agents (max ${o} parallel)...${de.reset}
777
- `);let u=Date.now(),d=bg(o),f={findings:[],_lock:!1},p=l.map(H=>{let X=Rv(H.task);return(X?fg(X.id):null)||n}),h=l.map((H,X)=>{let pe=`Agent ${X+1} [${p[X]}]: `,Re=Math.max(20,60-pe.length),Ue=H.task.substring(0,Re)+(H.task.length>Re?"...":"");return pe+Ue}),g=new Cv(h);g.start();let _=`
781
+ `),i("decomposing"),console.log(`${de.dim}Phase 1: Decomposing prompt into sub-tasks...${de.reset}`);let l;try{l=await Ng(t,s,{maxSubTasks:r})}catch(W){return console.log(`${de.red}Decompose failed: ${W.message}${de.reset}`),{results:[],synthesis:{summary:`Decompose failed: ${W.message}`,conflicts:[],commitMessage:"",resourcesChanged:[]},totalTokens:a}}if(l.length===0)return console.log(`${de.yellow}No sub-tasks generated. Prompt may be too simple for orchestration.${de.reset}`),{results:[],synthesis:{summary:"No sub-tasks generated.",conflicts:[],commitMessage:"",resourcesChanged:[]},totalTokens:a};console.log(`${de.green}Decomposed into ${l.length} sub-tasks:${de.reset}`);for(let W of l){console.log(` ${de.dim}${W.id}:${de.reset} ${W.task}`);let Z=W.scope.filter(Boolean);Z.length>0&&console.log(` ${de.dim}scope: ${Z.join(", ")}${de.reset}`)}console.log("");let c=new Map;for(let W=0;W<l.length;W++)for(let Z of l[W].scope)Z&&!c.has(Z)&&c.set(Z,W);i("executing"),console.log(`${de.dim}Phase 2: Running ${l.length} sub-agents (max ${o} parallel)...${de.reset}
782
+ `);let u=Date.now(),d=Og(o),f={findings:[],_lock:!1},p=l.map(W=>{let Z=zv(W.task);return(Z?xg(Z.id):null)||n}),m=l.map((W,Z)=>{let he=`Agent ${Z+1} [${p[Z]}]: `,Ce=Math.max(20,60-he.length),We=W.task.substring(0,Ce)+(W.task.length>Ce?"...":"");return he+We}),g=new Kv(m);g.start();let _=`
778
783
  You are a focused coding agent executing ONE specific sub-task.
779
784
  Your scope is limited to the files listed in your task definition.
780
785
 
@@ -795,16 +800,16 @@ RULES:
795
800
  - If your task says "add X to README" \u2014 add it, don't check if it exists first.
796
801
  - Max 10 tool calls. If you need more, you are doing too much \u2014 narrow your scope.
797
802
  - When done: stop calling tools and write a one-line summary of what you changed.
798
- `,b=new Map;for(let H=0;H<l.length;H++){let X=l[H].priority||1;b.has(X)||b.set(X,[]),b.get(X).push({st:l[H],idx:H})}let O=[...b.keys()].sort((H,X)=>H-X),M=new Array(l.length);for(let H of O){let pe=b.get(H).map(async({st:Re,idx:Ue})=>{let ke=await d();try{let $e=await v(Re,Ue,{acquire:d,subTaskModels:p,labels:h,progress:g,sharedContext:f,_fileOwnership:c,workerModel:n,WORKER_SYSTEM_PROMPT:_});return M[Ue]=$e,$e}finally{ke()}});await Promise.all(pe)}async function v(H,X,pe){try{let Re=f.findings.filter(oe=>oe.agentId!==H.id).map(oe=>`Agent ${oe.agentId} found: ${oe.summary}`).join(`
799
- `),Ue=[...c.entries()].filter(([,oe])=>oe===X).map(([oe])=>oe),ke=[...c.entries()].filter(([,oe])=>oe!==X).map(([oe])=>oe),$e=[Re?`Prior agent findings:
800
- ${Re}
801
- `:"",H.scope.length>0?`Focus on files: ${H.scope.join(", ")}`:"",Ue.length>0?`You OWN these files (may read+write): ${Ue.join(", ")}`:"",ke.length>0?`READ ONLY (owned by other agents, do NOT write): ${ke.join(", ")}`:""].filter(Boolean),$=Sg(H.task),I=p[X],R=process.env.NEX_FALLBACK_MODEL||fg("agentic")||n,W=0,E=await $g(async()=>{let oe=W>0;oe&&(g.update(X,"retry"),process.stderr.write(` ${de.dim}[Agent ${X+1}] retrying after error...${de.reset}
802
- `)),W++;let we=oe&&I!==R?R:I;return Ev({task:H.task,type:$,context:$e.length>0?$e.join(`
803
- `):void 0,max_iterations:Math.min(H.estimatedCalls||10,15),model:we,_skipLog:!0,_systemPrompt:_,_readOnlyFiles:ke},{onUpdate:ge=>{if(ge&&ge.type==="tool_call"&&process.stderr.isTTY){let st=`Agent ${X+1} [${we}]`,yn=ge.tool||"...";g.labels[X]=`${st}: ${yn}`}}})},1,2e3),S=typeof E.result=="string"?E.result.slice(0,200):String(E.result||"").slice(0,200);return f.findings.push({agentId:H.id,summary:S,files:Array.isArray(H.scope)?H.scope:[]}),g.labels[X]=h[X],g.update(X,E.status==="failed"?"error":"done"),a.input+=E.tokensUsed?.input||0,a.output+=E.tokensUsed?.output||0,E.tokensUsed?._estimated&&(a._estimated=!0),{...E,_scope:H.scope,_idx:X}}catch(Re){return g.labels[X]=h[X],g.update(X,"error"),{task:H.task,status:"failed",result:`Error: ${Re.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}}}let T;try{T=M}finally{g.stop({silent:!0}),Tv()}console.log("");let N=Math.round((Date.now()-u)/1e3),te=N>=60?`${Math.floor(N/60)}m ${N%60}s`:`${N}s`;for(let H=0;H<T.length;H++){let X=T[H],Re=X.status==="done"||X.status==="truncated"&&X.result&&!X.result.startsWith("Error")?`${de.green}\u2713${de.reset}`:`${de.red}\u2717${de.reset}`,Ue=X._scope&&X._scope.length>0?X._scope.map($=>$.replace(/^.*\//,"").replace(/\/$/,"")).filter(Boolean):[],ke=Ue.length>0?Ue.join(", "):X.task.substring(0,35)+(X.task.length>35?"...":""),$e=H===T.length-1;console.log(` ${Re} Agent ${H+1} ${de.dim}${ke}${de.reset}${$e?` ${de.dim}${te}${de.reset}`:""}`)}console.log(""),i("synthesizing"),console.log(`${de.dim}Phase 3: Synthesizing results...${de.reset}`);let K;try{K=await kg(T,t,s)}catch(H){console.log(`${de.yellow}Synthesize failed: ${H.message} \u2014 using raw results.${de.reset}`),K={summary:T.map(X=>X.result).join(`
804
- `),conflicts:[],commitMessage:"",resourcesChanged:[]}}let ie=f.findings.flatMap(H=>H.files),le=new Map;for(let H of ie)le.set(H,(le.get(H)||0)+1);let ne=[...le.values()].some(H=>H>1),k=f.findings.length>1&&ne?` ${de.dim}(agents shared context)${de.reset}`:"";if(console.log(`
805
- ${de.bold}Summary:${de.reset} ${K.summary}${k}`),K.conflicts.length>0){console.log(`${de.yellow}Conflicts:${de.reset}`);for(let H of K.conflicts)console.log(` - ${H}`)}K.commitMessage&&console.log(`${de.dim}Suggested commit: ${K.commitMessage}${de.reset}`);let ve=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(`${de.dim}Tokens: ${ve}${de.reset}
806
- `),{results:T,synthesis:K,totalTokens:a}}var Nv=/\b(research|analyze|investigate|check|verify|review|audit|read|find|search|discover|look|examine|inspect|scan|list)\b/i,Mv=/\b(fix|implement|create|add|update|modify|change|write|refactor|remove|delete|install|configure|setup|deploy|build|migrate|optimize|improve|patch|rewrite|replace)\b/i;function Sg(t){if(!t)return"implement";let e=Nv.test(t);return Mv.test(t)?"implement":e?"explore":"implement"}vg.exports={runOrchestrated:Ov,decompose:xg,synthesize:kg,detectComplexPrompt:Av,extractJSON:gc,createSemaphore:bg,DECOMPOSE_PROMPT:wg,SYNTHESIZE_PROMPT:_g,DEFAULT_ORCHESTRATOR_MODEL:yg,DEFAULT_WORKER_MODEL:gg,DEFAULT_MAX_PARALLEL:mg,DEFAULT_MAX_SUBTASKS:Ai,withRetry:$g,_classifyWorkerType:Sg}});var Ql=Z((O1,ty)=>{var{C:m,Spinner:Xs,TaskProgress:Pv,formatToolCall:Lv,formatToolSummary:Rc,formatSectionHeader:Oi,formatMilestone:Iv,setActiveTaskProgress:E1,getThinkingVerb:yc,setActiveModelForSpinner:Dv}=Ke(),{debugLog:D,warnLog:T1}=Ca(),{MilestoneTracker:jv}=dd(),{callStream:Tg}=Ze(),{parseToolArgs:qv}=ao(),{executeTool:Fv}=Rs(),{gatherProjectContext:Bv}=wm(),{fitToContext:Uv,forceCompress:nn,getUsage:Gt,estimateTokens:Wv,buildProgressSnapshot:Hv}=en(),{autoSave:Yv,flushAutoSave:Gv}=xi(),{scoreMessages:zv,formatScore:Kv,appendScoreHistory:Xv}=ki(),{detectCategory:Vv,getModelForPhase:Cc,getPhaseBudget:ls,isPhaseRoutingEnabled:Jv}=Hs();function Oe(t){Yv(t),Gv()}function Zv(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 Ni(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=zv(t);if(!s)return;console.log(Kv(s,m));try{let{_getSessionsDir:n}=xi(),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}=ao(),o=mr();Xv(s.score,{version:o.version,model:n?n():null,sessionName:"_autosave",issues:s.issues})}catch{}}catch{}}var{getMemoryContext:Qv}=Oo(),{getDeploymentContextBlock:eE,probeUrlServer:tE}=tc(),{getFewShotForInput:nE}=jm(),{checkPermission:sE,setPermission:oE,savePermissions:rE}=Hm(),{confirm:Bg,setAllowAlwaysHandler:iE,getAutoConfirm:er}=co(),{isPlanMode:tr,getPlanModePrompt:aE,PLAN_MODE_ALLOWED_TOOLS:Ug,setPlanContent:lE,extractStepsFromText:cE,createPlan:uE,getActivePlan:R1,startExecution:C1,advancePlanStep:dE,getPlanStepInfo:fE}=Ri(),{StreamRenderer:pE}=ig(),{runHooks:Rg}=dg(),{routeMCPCall:hE,getMCPToolDefinitions:mE}=za(),{getSkillInstructions:gE,getSkillToolDefinitions:yE,routeSkillCall:wE,matchSkillTriggers:_E}=Ya(),{trackUsage:Cg,estimateTokens:Ag}=Nr();function Og(t){return!t||typeof t!="string"?0:typeof Ag=="function"?Ag(t):Math.ceil(t.length/4)}var{validateToolArgs:$E}=Va(),{filterToolsForModel:Ng,getModelTier:bE,PROVIDER_DEFAULT_TIER:A1}=_o(),{getConfiguredProviders:xE,getActiveProviderName:Vs,getActiveModelId:Xt,setActiveModel:Mg,MODEL_EQUIVALENTS:zi}=Ze(),{getModelProfile:kE,getModelBriefing:SE}=oi(),On=require("fs"),eo=require("path"),vE=(()=>{let t=parseInt(process.env.NEX_MILESTONE_STEPS??"5",10);return Number.isFinite(t)&&t>=0?t:5})();function EE(t){let e=Iv(t.phaseName,t.stepCount,t.toolCounts,t.elapsed,t.filesRead,t.filesModified);process.stdout.write(`${e}
807
- `)}var Pg=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi,Lg=/(?:^|\s)(https?:\/\/[^\s]+\.(?:png|jpe?g|gif|webp)(?:\?[^\s]*)?)(?:\s|$)/gi,TE=/\b(?:clipboard|pasteboard|zwischenablage|screenshot aus clipboard)\b/i;function RE(t){let e=[],s;for(Pg.lastIndex=0;(s=Pg.exec(t))!==null;){let n=s[1].trim(),o=n.startsWith("~")?n.replace("~",process.env.HOME||""):eo.resolve(n);On.existsSync(o)&&e.push({raw:n,abs:o})}return e}function Wg(t){let e=[],s;for(Lg.lastIndex=0;(s=Lg.exec(t))!==null;)e.push(s[1].trim());return e}async function Hg(t){try{let s=await require("axios").get(t,{responseType:"arraybuffer",timeout:1e4,maxContentLength:10*1024*1024,headers:{"User-Agent":"nex-code/vision"}}),n=s.headers["content-type"]||"",o=n.startsWith("image/")?n.split(";")[0]:CE(t);return{data:Buffer.from(s.data).toString("base64"),media_type:o}}catch{return null}}function CE(t){let e=t.toLowerCase();return e.includes(".jpg")||e.includes(".jpeg")?"image/jpeg":e.includes(".gif")?"image/gif":e.includes(".webp")?"image/webp":"image/png"}function Yg(){if(process.platform!=="darwin")return null;let{spawnSync:t}=require("child_process"),e=eo.join(require("os").tmpdir(),`nex-clipboard-${Date.now()}.png`);if(t("pngpaste",[e],{timeout:3e3}).status===0&&On.existsSync(e)){let o=On.readFileSync(e);if(o.length>100)return{data:o.toString("base64"),media_type:"image/png",path:e};try{On.unlinkSync(e)}catch(r){console.error("Failed to unlink temp file:",r)}}let n=t("osascript",["-e",`try
803
+ `,b=new Map;for(let W=0;W<l.length;W++){let Z=l[W].priority||1;b.has(Z)||b.set(Z,[]),b.get(Z).push({st:l[W],idx:W})}let A=[...b.keys()].sort((W,Z)=>W-Z),P=new Array(l.length);for(let W of A){let he=b.get(W).map(async({st:Ce,idx:We})=>{let xe=await d();try{let be=await v(Ce,We,{acquire:d,subTaskModels:p,labels:m,progress:g,sharedContext:f,_fileOwnership:c,workerModel:n,WORKER_SYSTEM_PROMPT:_});return P[We]=be,be}finally{xe()}});await Promise.all(he)}async function v(W,Z,he){try{let Ce=f.findings.filter(Y=>Y.agentId!==W.id).map(Y=>`Agent ${Y.agentId} found: ${Y.summary}`).join(`
804
+ `),We=[...c.entries()].filter(([,Y])=>Y===Z).map(([Y])=>Y),xe=[...c.entries()].filter(([,Y])=>Y!==Z).map(([Y])=>Y),be=[Ce?`Prior agent findings:
805
+ ${Ce}
806
+ `:"",W.scope.length>0?`Focus on files: ${W.scope.join(", ")}`:"",We.length>0?`You OWN these files (may read+write): ${We.join(", ")}`:"",xe.length>0?`READ ONLY (owned by other agents, do NOT write): ${xe.join(", ")}`:""].filter(Boolean),$=Pg(W.task),I=p[Z],H=process.env.NEX_FALLBACK_MODEL||xg("agentic")||n,N=0,q=await Ag(async()=>{let Y=N>0;Y&&(g.update(Z,"retry"),process.stderr.write(` ${de.dim}[Agent ${Z+1}] retrying after error...${de.reset}
807
+ `)),N++;let ke=Y&&I!==H?H:I;return Yv({task:W.task,type:$,context:be.length>0?be.join(`
808
+ `):void 0,max_iterations:Math.min(W.estimatedCalls||10,15),model:ke,_skipLog:!0,_systemPrompt:_,_readOnlyFiles:xe},{onUpdate:pe=>{if(pe&&pe.type==="tool_call"&&process.stderr.isTTY){let lt=`Agent ${Z+1} [${ke}]`,io=pe.tool||"...";g.labels[Z]=`${lt}: ${io}`}}})},1,2e3),x=typeof q.result=="string"?q.result.slice(0,200):String(q.result||"").slice(0,200);return f.findings.push({agentId:W.id,summary:x,files:Array.isArray(W.scope)?W.scope:[]}),g.labels[Z]=m[Z],g.update(Z,q.status==="failed"?"error":"done"),a.input+=q.tokensUsed?.input||0,a.output+=q.tokensUsed?.output||0,q.tokensUsed?._estimated&&(a._estimated=!0),{...q,_scope:W.scope,_idx:Z}}catch(Ce){return g.labels[Z]=m[Z],g.update(Z,"error"),{task:W.task,status:"failed",result:`Error: ${Ce.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}}}let E;try{E=P}finally{g.stop({silent:!0}),Gv()}console.log("");let O=Math.round((Date.now()-u)/1e3),ne=O>=60?`${Math.floor(O/60)}m ${O%60}s`:`${O}s`;for(let W=0;W<E.length;W++){let Z=E[W],Ce=Z.status==="done"||Z.status==="truncated"&&Z.result&&!Z.result.startsWith("Error")?`${de.green}\u2713${de.reset}`:`${de.red}\u2717${de.reset}`,We=Z._scope&&Z._scope.length>0?Z._scope.map($=>$.replace(/^.*\//,"").replace(/\/$/,"")).filter(Boolean):[],xe=We.length>0?We.join(", "):Z.task.substring(0,35)+(Z.task.length>35?"...":""),be=W===E.length-1;console.log(` ${Ce} Agent ${W+1} ${de.dim}${xe}${de.reset}${be?` ${de.dim}${ne}${de.reset}`:""}`)}console.log(""),i("synthesizing"),console.log(`${de.dim}Phase 3: Synthesizing results...${de.reset}`);let J;try{J=await Mg(E,t,s)}catch(W){console.log(`${de.yellow}Synthesize failed: ${W.message} \u2014 using raw results.${de.reset}`),J={summary:E.map(Z=>Z.result).join(`
809
+ `),conflicts:[],commitMessage:"",resourcesChanged:[]}}let ie=f.findings.flatMap(W=>W.files),ce=new Map;for(let W of ie)ce.set(W,(ce.get(W)||0)+1);let se=[...ce.values()].some(W=>W>1),S=f.findings.length>1&&se?` ${de.dim}(agents shared context)${de.reset}`:"";if(console.log(`
810
+ ${de.bold}Summary:${de.reset} ${J.summary}${S}`),J.conflicts.length>0){console.log(`${de.yellow}Conflicts:${de.reset}`);for(let W of J.conflicts)console.log(` - ${W}`)}J.commitMessage&&console.log(`${de.dim}Suggested commit: ${J.commitMessage}${de.reset}`);let Ee=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(`${de.dim}Tokens: ${Ee}${de.reset}
811
+ `),{results:E,synthesis:J,totalTokens:a}}var Jv=/\b(research|analyze|investigate|check|verify|review|audit|read|find|search|discover|look|examine|inspect|scan|list)\b/i,Zv=/\b(fix|implement|create|add|update|modify|change|write|refactor|remove|delete|install|configure|setup|deploy|build|migrate|optimize|improve|patch|rewrite|replace)\b/i;function Pg(t){if(!t)return"implement";let e=Jv.test(t);return Zv.test(t)?"implement":e?"explore":"implement"}Lg.exports={runOrchestrated:Vv,decompose:Ng,synthesize:Mg,detectComplexPrompt:Xv,extractJSON:kc,createSemaphore:Og,DECOMPOSE_PROMPT:Rg,SYNTHESIZE_PROMPT:Cg,DEFAULT_ORCHESTRATOR_MODEL:Tg,DEFAULT_WORKER_MODEL:Eg,DEFAULT_MAX_PARALLEL:vg,DEFAULT_MAX_SUBTASKS:Li,withRetry:Ag,_classifyWorkerType:Pg}});var ic=Q((J1,dy)=>{var{C:h,Spinner:Zs,TaskProgress:Qv,formatToolCall:eE,formatToolSummary:Ic,formatSectionHeader:Ii,formatMilestone:tE,setActiveTaskProgress:G1,getThinkingVerb:Sc,setActiveModelForSpinner:Dg}=Ke(),{debugLog:j,warnLog:z1}=La(),{MilestoneTracker:nE}=bd(),{callStream:jg}=Qe(),{parseToolArgs:sE}=fo(),{executeTool:oE}=As(),{gatherProjectContext:rE}=Rm(),{fitToContext:iE,forceCompress:nn,getUsage:Gt,estimateTokens:aE,buildProgressSnapshot:lE}=en(),{autoSave:cE,flushAutoSave:uE}=Ti(),{scoreMessages:dE,formatScore:fE,appendScoreHistory:pE}=Ri(),{detectCategory:hE,getModelForPhase:Dc,getPhaseBudget:cs,isPhaseRoutingEnabled:mE}=ss();function Ae(t){cE(t),uE()}function gE(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 Di(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=dE(t);if(!s)return;console.log(fE(s,h));try{let{_getSessionsDir:n}=Ti(),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}=fo(),o=_r();pE(s.score,{version:o.version,model:n?n():null,sessionName:"_autosave",issues:s.issues})}catch{}}catch{}}var{getMemoryContext:yE}=Lo(),{getDeploymentContextBlock:wE,probeUrlServer:_E}=lc(),{getFewShotForInput:$E}=Km(),{checkPermission:bE,setPermission:xE,savePermissions:kE}=eg(),{confirm:Jg,setAllowAlwaysHandler:SE,getAutoConfirm:or}=ho(),{isPlanMode:rr,getPlanModePrompt:vE,PLAN_MODE_ALLOWED_TOOLS:Zg,setPlanContent:EE,extractStepsFromText:TE,createPlan:RE,getActivePlan:K1,startExecution:X1,advancePlanStep:CE,getPlanStepInfo:AE}=Mi(),{StreamRenderer:OE}=gg(),{runHooks:qg}=bg(),{routeMCPCall:NE,getMCPToolDefinitions:ME}=Qa(),{getSkillInstructions:PE,getSkillToolDefinitions:LE,routeSkillCall:IE,matchSkillTriggers:DE}=Ja(),{trackUsage:Fg,estimateTokens:Bg}=Ir();function Ug(t){return!t||typeof t!="string"?0:typeof Bg=="function"?Bg(t):Math.ceil(t.length/4)}var{validateToolArgs:jE}=nl(),{filterToolsForModel:Wg,getModelTier:qE,PROVIDER_DEFAULT_TIER:V1}=ko(),{getConfiguredProviders:FE,getActiveProviderName:Qs,getActiveModelId:Xt,setActiveModel:vc,MODEL_EQUIVALENTS:Qi}=Qe(),{getModelProfile:BE,getModelBriefing:UE}=li(),An=require("fs"),so=require("path"),WE=(()=>{let t=parseInt(process.env.NEX_MILESTONE_STEPS??"5",10);return Number.isFinite(t)&&t>=0?t:5})();function HE(t){let e=tE(t.phaseName,t.stepCount,t.toolCounts,t.elapsed,t.filesRead,t.filesModified);process.stdout.write(`${e}
812
+ `)}var Hg=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi,Yg=/(?:^|\s)(https?:\/\/[^\s]+\.(?:png|jpe?g|gif|webp)(?:\?[^\s]*)?)(?:\s|$)/gi,YE=/\b(?:clipboard|pasteboard|zwischenablage|screenshot aus clipboard)\b/i;function GE(t){let e=[],s;for(Hg.lastIndex=0;(s=Hg.exec(t))!==null;){let n=s[1].trim(),o=n.startsWith("~")?n.replace("~",process.env.HOME||""):so.resolve(n);An.existsSync(o)&&e.push({raw:n,abs:o})}return e}function Qg(t){let e=[],s;for(Yg.lastIndex=0;(s=Yg.exec(t))!==null;)e.push(s[1].trim());return e}async function ey(t){try{let s=await require("axios").get(t,{responseType:"arraybuffer",timeout:1e4,maxContentLength:10*1024*1024,headers:{"User-Agent":"nex-code/vision"}}),n=s.headers["content-type"]||"",o=n.startsWith("image/")?n.split(";")[0]:zE(t);return{data:Buffer.from(s.data).toString("base64"),media_type:o}}catch{return null}}function zE(t){let e=t.toLowerCase();return e.includes(".jpg")||e.includes(".jpeg")?"image/jpeg":e.includes(".gif")?"image/gif":e.includes(".webp")?"image/webp":"image/png"}function ty(){if(process.platform!=="darwin")return null;let{spawnSync:t}=require("child_process"),e=so.join(require("os").tmpdir(),`nex-clipboard-${Date.now()}.png`);if(t("pngpaste",[e],{timeout:3e3}).status===0&&An.existsSync(e)){let o=An.readFileSync(e);if(o.length>100)return{data:o.toString("base64"),media_type:"image/png",path:e};try{An.unlinkSync(e)}catch(r){console.error("Failed to unlink temp file:",r)}}let n=t("osascript",["-e",`try
808
813
  set imgData to the clipboard as \xABclass PNGf\xBB
809
814
  return "has_image"
810
815
  on error
@@ -815,38 +820,45 @@ end try`],{timeout:3e3});if(n.stdout&&n.stdout.toString().trim()==="has_image"){
815
820
  set fRef to open for access filePath with write permission
816
821
  write imgData to fRef
817
822
  close access fRef
818
- `;if(t("osascript",["-e",o],{timeout:5e3}).status===0&&On.existsSync(e)){let i=On.readFileSync(e);if(i.length>100)return{data:i.toString("base64"),media_type:"image/png",path:e}}}return null}function Ig(t){let e=On.readFileSync(t),s=eo.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 Gg(t){let e=RE(t),s=Wg(t),n=TE.test(t),o=s.length>0||n;if(e.length===0&&!o)return t;if(!o){let r=[{type:"text",text:t}];for(let i of e)try{let{data:a,media_type:l}=Ig(i.abs);r.push({type:"image",media_type:l,data:a})}catch{}return r.length>1?r:t}return(async()=>{let r=[{type:"text",text:t}];for(let i of e)try{let{data:a,media_type:l}=Ig(i.abs);r.push({type:"image",media_type:l,data:a})}catch(a){D(`${m.yellow} \u26A0 Path resolution failed: ${a.message}${m.reset}`)}if(s.length>0){let i=await Promise.all(s.map(Hg));for(let a of i)a&&r.push({type:"image",media_type:a.media_type,data:a.data})}if(n){let i=Yg();i?(r.push({type:"image",media_type:i.media_type,data:i.data}),r[0].text+=`
823
+ `;if(t("osascript",["-e",o],{timeout:5e3}).status===0&&An.existsSync(e)){let i=An.readFileSync(e);if(i.length>100)return{data:i.toString("base64"),media_type:"image/png",path:e}}}return null}function Gg(t){let e=An.readFileSync(t),s=so.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 ny(t){let e=GE(t),s=Qg(t),n=YE.test(t),o=s.length>0||n;if(e.length===0&&!o)return t;if(!o){let r=[{type:"text",text:t}];for(let i of e)try{let{data:a,media_type:l}=Gg(i.abs);r.push({type:"image",media_type:l,data:a})}catch{}return r.length>1?r:t}return(async()=>{let r=[{type:"text",text:t}];for(let i of e)try{let{data:a,media_type:l}=Gg(i.abs);r.push({type:"image",media_type:l,data:a})}catch(a){j(`${h.yellow} \u26A0 Path resolution failed: ${a.message}${h.reset}`)}if(s.length>0){let i=await Promise.all(s.map(ey));for(let a of i)a&&r.push({type:"image",media_type:a.media_type,data:a.data})}if(n){let i=ty();i?(r.push({type:"image",media_type:i.media_type,data:i.data}),r[0].text+=`
819
824
  [Clipboard image attached: ${i.path}]`):r[0].text+=`
820
- [No image found in clipboard]`}return r.length>1?r:t})()}var AE=[/\bwtf\b/i,/\buff\b/i,/\bugh\b/i,/\bffs\b/i,/\bargh\b/i,/why (?:isn'?t|doesn'?t|won'?t|can'?t|don'?t)/i,/(?:still|again) (?:broken|not working|failing|wrong)/i,/already told you/i,/come on[!.]/i,/seriously\?/i,/how (?:many|much) (?:times|more)/i,/nothing (?:works?|is working)/i];function zg(t){return typeof t!="string"||!t?!1:AE.some(e=>e.test(t))}function OE(t){if(!t||t.length<200)return{text:t,truncated:!1,repeatCount:0};let s=t.split(/(?<=\. )/).filter(l=>l.trim().length>0);if(s.length<6)return{text:t,truncated:!1,repeatCount:0};let n=new Map;for(let l=0;l<=s.length-3;l++){let c=s.slice(l,l+3).join("").trim();c.length>30&&n.set(c,(n.get(c)||0)+1)}let o=0,r="";for(let[l,c]of n)c>o&&(o=c,r=l);if(o<3)return{text:t,truncated:!1,repeatCount:o};let i=`
825
+ [No image found in clipboard]`}return r.length>1?r:t})()}var KE=[/\bwtf\b/i,/\buff\b/i,/\bugh\b/i,/\bffs\b/i,/\bargh\b/i,/why (?:isn'?t|doesn'?t|won'?t|can'?t|don'?t)/i,/(?:still|again) (?:broken|not working|failing|wrong)/i,/already told you/i,/come on[!.]/i,/seriously\?/i,/how (?:many|much) (?:times|more)/i,/nothing (?:works?|is working)/i];function sy(t){return typeof t!="string"||!t?!1:KE.some(e=>e.test(t))}function XE(t){if(!t||t.length<200)return{text:t,truncated:!1,repeatCount:0};let s=t.split(/(?<=\. )/).filter(l=>l.trim().length>0);if(s.length<6)return{text:t,truncated:!1,repeatCount:0};let n=new Map;for(let l=0;l<=s.length-3;l++){let c=s.slice(l,l+3).join("").trim();c.length>30&&n.set(c,(n.get(c)||0)+1)}let o=0,r="";for(let[l,c]of n)c>o&&(o=c,r=l);if(o<3)return{text:t,truncated:!1,repeatCount:o};let i=`
821
826
 
822
- [SYSTEM: Output repetition detected \u2014 response truncated (${o}\xD7 repeated paragraph)]`,a;if(t.length>8e3)a=t.slice(0,3e3)+i;else{let l=0,c=-1,u=0;for(;l<2;){let d=t.indexOf(r,u);if(d===-1)break;l++,c=d+r.length,u=d+1}a=c>0?t.slice(0,c)+i:t.slice(0,3e3)+i}return{text:a,truncated:!0,repeatCount:o}}function Ac(t,e=5){if(!t||t.length<40)return{text:t,truncated:!1,repeatCount:0};let s=t.split(`
823
- `),n=new Map;for(let p of s){let h=p.trim();h.length>=20&&n.set(h,(n.get(h)||0)+1)}let o=0,r="";for(let[p,h]of n)h>o&&(o=h,r=p);let a=r.toLowerCase().includes("read_file")||r.toLowerCase().includes("reading")?2:e;if(o<=a)return{text:t,truncated:!1,repeatCount:o};let l=`
827
+ [SYSTEM: Output repetition detected \u2014 response truncated (${o}\xD7 repeated paragraph)]`,a;if(t.length>8e3)a=t.slice(0,3e3)+i;else{let l=0,c=-1,u=0;for(;l<2;){let d=t.indexOf(r,u);if(d===-1)break;l++,c=d+r.length,u=d+1}a=c>0?t.slice(0,c)+i:t.slice(0,3e3)+i}return{text:a,truncated:!0,repeatCount:o}}function jc(t,e=5){if(!t||t.length<40)return{text:t,truncated:!1,repeatCount:0};let s=t.split(`
828
+ `),n=new Map;for(let p of s){let m=p.trim();m.length>=20&&n.set(m,(n.get(m)||0)+1)}let o=0,r="";for(let[p,m]of n)m>o&&(o=m,r=p);let a=r.toLowerCase().includes("read_file")||r.toLowerCase().includes("reading")?2:e;if(o<=a)return{text:t,truncated:!1,repeatCount:o};let l=`
824
829
 
825
- \u26A0 [Response truncated: repeated paragraph detected (${o}\xD7)]`,c=0,u=-1,d=0;for(;c<e;){let p=t.indexOf(r,d);if(p===-1)break;c++,u=p+r.length,d=p+1}return{text:u>0?t.slice(0,u)+l:t.slice(0,2e3)+l,truncated:!0,repeatCount:o}}var wc=null,_c=null,$c=null;function at(){if(wc===null){let{TOOL_DEFINITIONS:t}=Rs();wc=t}return _c===null&&(_c=yE()),$c===null&&($c=mE()),[...wc,..._c,...$c]}var Oc=50;function NE(t){Number.isFinite(t)&&t>0&&(Oc=t)}var Li=()=>null;function ME(t){Li=t}var Xo=null,Nc=null,Js=null,Ii=new Map,PE=1e4,LE=6e3,IE=/\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 DE(t){return!t||typeof t!="string"?t:t.replace(IE,(e,s)=>`${s}=***REDACTED***`)}var jE=7e3,qE=4e3;function FE(t,e=null){let s=DE(t),n=Wv(s),o=e==="read_file"?jE:PE,r=e==="read_file"?qE:LE;if(n>o)try{let{compressToolResult:i}=en();return i(s,r)}catch{return s}return s}function Kg(t){try{let{getActiveModel:e}=Ze(),s=e(),n=s?`${s.provider}:${s.id}`:"default";if(Ii.has(n))return Ii.get(n);let o=Ng(t);return Ii.set(n,o),o}catch{return Ng(t)}}function BE(){Ii.clear()}var Vo={hash:null,ts:0},UE=3e4;async function Xg(){if(Vo.hash&&Date.now()-Vo.ts<UE)return Vo.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}=Oo(),a=i();a&&o.push(`memory:${a}`)}catch{}try{let i=e.join(process.cwd(),".nex","brain");if(On.existsSync(i)){let a=await t.stat(i);o.push(`brain:${a.mtimeMs}`)}}catch{}let r=o.join("|");return Vo={hash:r,ts:Date.now()},r}catch{return`fallback:${Date.now()}`}}function Mc(){Xo=null,Nc=null,Vo={hash:null,ts:0},Js=null}var WE=new Set(["spawn_agents"]),bc=10,xc=10,Mi=5,Dg=6e4,kc=12e4,HE=process.env.NEX_STALE_AUTO_SWITCH!=="0";function YE(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{}}iE(t=>{oE(t,"allow"),rE(),console.log(`${m.green} \u2713 ${t}: always allow${m.reset}`)});async function GE(t){let e=t.function.name,s=qv(t.function.arguments),n=t.id||`cli-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!s){let u=at().find(f=>f.function.name===e),d=u?JSON.stringify(u.function.parameters,null,2):"unknown";return D(`${m.yellow} \u26A0 ${e}: malformed arguments, sending schema hint${m.reset}`),{callId:n,fnName:e,args:null,canExecute:!1,errorResult:{role:"tool",content:`ERROR: Malformed tool arguments. Could not parse your arguments as JSON.
830
+ \u26A0 [Response truncated: repeated paragraph detected (${o}\xD7)]`,c=0,u=-1,d=0;for(;c<e;){let p=t.indexOf(r,d);if(p===-1)break;c++,u=p+r.length,d=p+1}return{text:u>0?t.slice(0,u)+l:t.slice(0,2e3)+l,truncated:!0,repeatCount:o}}var Ec=null,Tc=null,Rc=null;function at(){if(Ec===null){let{TOOL_DEFINITIONS:t}=As();Ec=t}return Tc===null&&(Tc=LE()),Rc===null&&(Rc=ME()),[...Ec,...Tc,...Rc]}var qc=50;function VE(t){Number.isFinite(t)&&t>0&&(qc=t)}var Bi=()=>null;function JE(t){Bi=t}var Qo=null,Fc=null,eo=null,Ui=new Map,ZE=1e4,QE=6e3,eT=/\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 tT(t){return!t||typeof t!="string"?t:t.replace(eT,(e,s)=>`${s}=***REDACTED***`)}var nT=7e3,sT=4e3;function oT(t,e=null){let s=tT(t),n=aE(s),o=e==="read_file"?nT:ZE,r=e==="read_file"?sT:QE;if(n>o)try{let{compressToolResult:i}=en();return i(s,r)}catch{return s}return s}function oy(t){try{let{getActiveModel:e}=Qe(),s=e(),n=s?`${s.provider}:${s.id}`:"default";if(Ui.has(n))return Ui.get(n);let o=Wg(t);return Ui.set(n,o),o}catch{return Wg(t)}}function rT(){Ui.clear()}var er={hash:null,ts:0},iT=3e4;async function ry(){if(er.hash&&Date.now()-er.ts<iT)return er.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}=Lo(),a=i();a&&o.push(`memory:${a}`)}catch{}try{let i=e.join(process.cwd(),".nex","brain");if(An.existsSync(i)){let a=await t.stat(i);o.push(`brain:${a.mtimeMs}`)}}catch{}let r=o.join("|");return er={hash:r,ts:Date.now()},r}catch{return`fallback:${Date.now()}`}}function Bc(){Qo=null,Fc=null,er={hash:null,ts:0},eo=null}var aT=new Set(["spawn_agents"]),Cc=10,Ac=10,ji=5,zg=6e4,Oc=12e4,lT=process.env.NEX_STALE_AUTO_SWITCH!=="0";function cT(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{}}SE(t=>{xE(t,"allow"),kE(),console.log(`${h.green} \u2713 ${t}: always allow${h.reset}`)});async function uT(t){let e=t.function.name,s=sE(t.function.arguments),n=t.id||`cli-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!s){let d=at().find(p=>p.function.name===e),f=d?JSON.stringify(d.function.parameters,null,2):"unknown";return j(`${h.yellow} \u26A0 ${e}: malformed arguments, sending schema hint${h.reset}`),{callId:n,fnName:e,args:null,canExecute:!1,errorResult:{role:"tool",content:`ERROR: Malformed tool arguments. Could not parse your arguments as JSON.
826
831
  Raw input: ${typeof t.function.arguments=="string"?t.function.arguments.substring(0,200):"N/A"}
827
832
 
828
833
  Expected JSON schema for "${e}":
829
- ${d}
834
+ ${f}
830
835
 
831
- Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:n}}}if(s&&typeof s.path=="string")try{let c=require("os"),u=eo.resolve(process.cwd(),s.path.replace(/^~/,c.homedir())),d=s.path;s.path=eo.relative(process.cwd(),u)||".",Object.defineProperty(s,"_originalPath",{value:d,enumerable:!1})}catch{}let o=$E(e,s);if(!o.valid){D(`${m.yellow} \u26A0 ${e}: ${o.error.split(`
832
- `)[0]}${m.reset}`);let c=(qg.get(e)||0)+1;qg.set(e,c);let u=c>=2?`${o.error}
836
+ Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:n}}}if(s&&typeof s.path=="string")try{let u=require("os"),d=so.resolve(process.cwd(),s.path.replace(/^~/,u.homedir())),f=s.path;s.path=so.relative(process.cwd(),d)||".",Object.defineProperty(s,"_originalPath",{value:f,enumerable:!1})}catch(u){console.error("path resolution failed:",u.message)}let o=jE(e,s);if(!o.valid){j(`${h.yellow} \u26A0 ${e}: ${o.error.split(`
837
+ `)[0]}${h.reset}`);let u=(Xg.get(e)||0)+1;Xg.set(e,u);let d=u>=2?`${o.error}
833
838
 
834
- [SYSTEM: This is argument error #${c} 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 c=Object.keys(s),u=Object.keys(o.corrected),d=c.filter(f=>!u.includes(f));d.length&&console.log(`${m.dim} \u2713 ${e}: corrected args (${d.join(", ")})${m.reset}`)}if(tr()&&!Ug.has(e))return console.log(`${m.yellow} \u2717 ${e}: blocked in plan mode${m.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(ye&&Le==="plan"&&!i.has(e)&&!e.startsWith("skill_"))return Nn++,D(`${m.yellow} \u2717 ${e}: blocked in plan phase (read-only, block #${Nn})${m.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(ye&&Le==="verify"&&!a.has(e)&&!e.startsWith("skill_"))return D(`${m.yellow} \u2717 ${e}: blocked in verify phase (read + bash only)${m.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 l=sE(e);if(l==="deny")return console.log(`${m.red} \u2717 ${e}: denied by permissions${m.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(l==="ask"){let c=` Allow ${e}?`;return e==="bash"&&r.command&&(c=` bash: \`${r.command.substring(0,80)}${r.command.length>80?"\u2026":""}\`?`),await Bg(c,{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 zE(t,e,s={}){let n=await wE(t,e);if(n!==null)return n;let o=await hE(t,e);return o!==null?o:Fv(t,e,s)}function KE(t,e){switch(t){case"read_file":case"write_file":case"edit_file":case"patch_file":case"list_directory":return e._originalPath||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 Sc(t,e=!1){e||console.log(Lv(t.fnName,t.args));let s=Rg("pre-tool",{tool_name:t.fnName}),n=s.results;if(s.blocked){let _=`BLOCKED: pre-tool hook rejected ${t.fnName}: ${s.blockReason}`;e||console.log(`${m.yellow} [hook pre-tool] BLOCKED: ${s.blockReason}${m.reset}`);let b=Rc(t.fnName,t.args,_,!0);return e||console.log(b),{msg:{role:"tool",content:_,tool_call_id:t.callId},summary:b}}if(!e&&n.length>0)for(let _ of n)_.success?console.log(`${m.dim} [hook pre-tool] ${_.command} \u2192 ${_.output||"ok"}${m.reset}`):console.log(`${m.yellow} [hook pre-tool] ${_.command} \u2192 ERROR: ${_.error}${m.reset}`);on?.onToolStart&&on.onToolStart(t.fnName,t.args);let o=await zE(t.fnName,t.args,{silent:!0,autoConfirm:t.confirmedByUser===!0}),r=null,i;o&&typeof o=="object"&&o.text?(i=String(o.text),Array.isArray(o.images)&&o.images.length>0&&(r=o.images)):i=String(o??"");let a=i.length>5e4?i.substring(0,5e4)+`
839
+ [SYSTEM: This is argument error #${u} 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:d,tool_call_id:n}}}let r=o.corrected||s;if(o.corrected){let u=Object.keys(s),d=Object.keys(o.corrected),f=u.filter(p=>!d.includes(p));f.length&&console.log(`${h.dim} \u2713 ${e}: corrected args (${f.join(", ")})${h.reset}`)}if(rr()&&!Zg.has(e))return console.log(`${h.yellow} \u2717 ${e}: blocked in plan mode${h.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"]),l=e==="spawn_agents"&&Array.isArray(r?.agents)&&r.agents.length>0&&r.agents.every(u=>u.background===!0);if(_e&&Le==="plan"&&!i.has(e)&&!e.startsWith("skill_")&&!l)return On++,j(`${h.yellow} \u2717 ${e}: blocked in plan phase (read-only, block #${On})${h.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&&Le==="verify"&&!a.has(e)&&!e.startsWith("skill_"))return j(`${h.yellow} \u2717 ${e}: blocked in verify phase (read + bash only)${h.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=bE(e);if(c==="deny")return console.log(`${h.red} \u2717 ${e}: denied by permissions${h.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 u=` Allow ${e}?`;return e==="bash"&&r.command&&(u=` bash: \`${r.command.substring(0,80)}${r.command.length>80?"\u2026":""}\`?`),await Jg(u,{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 dT(t,e,s={}){let n=await IE(t,e);if(n!==null)return n;let o=await NE(t,e);return o!==null?o:oE(t,e,s)}function fT(t,e){switch(t){case"read_file":case"write_file":case"edit_file":case"patch_file":case"list_directory":return e._originalPath||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 Nc(t,e=!1){e||console.log(eE(t.fnName,t.args));let s=qg("pre-tool",{tool_name:t.fnName}),n=s.results;if(s.blocked){let _=`BLOCKED: pre-tool hook rejected ${t.fnName}: ${s.blockReason}`;e||console.log(`${h.yellow} [hook pre-tool] BLOCKED: ${s.blockReason}${h.reset}`);let b=Ic(t.fnName,t.args,_,!0);return e||console.log(b),{msg:{role:"tool",content:_,tool_call_id:t.callId},summary:b}}if(!e&&n.length>0)for(let _ of n)_.success?console.log(`${h.dim} [hook pre-tool] ${_.command} \u2192 ${_.output||"ok"}${h.reset}`):console.log(`${h.yellow} [hook pre-tool] ${_.command} \u2192 ERROR: ${_.error}${h.reset}`);on?.onToolStart&&on.onToolStart(t.fnName,t.args);let o=await dT(t.fnName,t.args,{silent:!0,autoConfirm:t.confirmedByUser===!0}),r=null,i;o&&typeof o=="object"&&o.text?(i=String(o.text),Array.isArray(o.images)&&o.images.length>0&&(r=o.images)):i=String(o??"");let a=i.length>5e4?i.substring(0,5e4)+`
835
840
  ...(truncated ${i.length-5e4} chars)`:i,l=a.split(`
836
- `)[0],c=l.startsWith("ERROR")||l.includes("CANCELLED")||l.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(a)&&/✗ Agent/.test(a),u=Rc(t.fnName,t.args,a,c);e||console.log(u),on?.onToolEnd&&on.onToolEnd(t.fnName,u,!c);let f=Rg("post-tool",{tool_name:t.fnName}).results;if(!e&&f.length>0)for(let _ of f)_.success?console.log(`${m.dim} [hook post-tool] ${_.command} \u2192 ${_.output||"ok"}${m.reset}`):console.log(`${m.yellow} [hook post-tool] ${_.command} \u2192 ERROR: ${_.error}${m.reset}`);let h=FE(a,t.fnName);if(t.fnName==="bash"&&t.args?.command){let _=t.args.command.trim();!/cat\s*>|<</.test(_)&&/\bcat\s+\S/.test(_)?h+=`
837
- 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(_)&&!/npm|yarn|pnpm|make|git\b/.test(_)?h+=`
838
- HINT: use list_directory instead of bash ls \u2014 it is the preferred tool for listing directory contents.`:/\bfind\s+\S/.test(_)&&!/git\b|npm\b|-exec\b|-delete\b|-print0\b/.test(_)&&(h+=`
839
- 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:r?[{type:"text",text:h},...r.map(_=>({type:"image",media_type:_.media_type,data:_.base64}))]:h,tool_call_id:t.callId},summary:u}}var XE=[{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 vc(t){for(let{re:e,label:s}of XE){let n=t.match(e);if(n){let o=(n[1]||"").trim();return o?`${s}: ${o}`:s}}return null}async function VE(t,e=!1,s={}){let n=new Array(t.length),o=[],r=[],i=null;if(e&&!s.skipSpinner){let l=t.filter(c=>c.canExecute);if(l.length>0){let c;if(l.length===1){let u=l[0],d=KE(u.fnName,u.args);c=`\u23FA ${u.fnName}${d?`(${d})`:""}`}else{let u=l.map(d=>d.fnName).join(", ");c=`\u23FA ${l.length} tools: ${u.length>60?u.substring(0,57)+"\u2026":u}`}i=new Xs(c),i.start()}}async function a(){if(r.length!==0){if(r.length===1){let l=r[0],{msg:c,summary:u}=await Sc(t[l],e);n[l]=c,o.push(u)}else{let l=r.map(u=>Sc(t[u],e)),c=await Promise.all(l);for(let u=0;u<r.length;u++)n[r[u]]=c[u].msg,o.push(c[u].summary)}r=[]}}for(let l=0;l<t.length;l++){let c=t[l];if(!c.canExecute){await a(),n[l]=c.errorResult,o.push(Rc(c.fnName,c.args||{},c.errorResult.content,!0));continue}if(WE.has(c.fnName)){await a(),c.fnName==="spawn_agents"&&i&&(i.stop(),i=null);let{msg:u,summary:d}=await Sc(c,e);n[l]=u,o.push(d)}else r.push(l)}if(await a(),i&&i.stop(),e&&o.length>0&&!s.skipSummaries)for(let l of o)console.log(l);return{results:n,summaries:o}}var j=[],jg=300,Vg=900*1e3;function sn(t,e){let s=t.get(e);return s?Date.now()-s.ts>Vg?(t.delete(e),0):s.count:0}function cs(t,e){let s=t.get(e),n=s&&Date.now()-s.ts<=Vg?s.count+1:1;return t.set(e,{count:n,ts:Date.now()}),n}function Ec(t,e,s){t.set(e,{count:s,ts:Date.now()})}var Uc=new Map,Jg=new Map,Di=new Map,nr=new Set,Zg=new Map,ji=new Map,sr=new Set,mn=new Map,An=new Map,or=new Map,Lt=new Map,ps=new Map,qg=new Map,Ki=new Map,Pc=new Map,It=0,Jo=0,qi=0,Lc="",Fi=0,Tt=!1,Pi=0,Bi=0,us=-1,Ic=!1,Ui=0,Wi=!1,jt=0,qt=!1,zt=0,Kt=0,tt=!1,_t="",Zo=0,Cn=0,Hi="",ds=0,fs=0,Yi="",Go=0,Dt=!1,Dc=!1,rr=new Map,ir=new Set,Qo=null,Tc=!1,zo=0,Fg=!1,Le="plan",Xi=0,ye=!1,Nn=0,gn=null,jc=null,qc=null,Zs=0,Qs=null,hs=[];function Ks(t,e){t===Lc?(Fi++,debug.DEBUG&&process.stdout.write(`\x1B[1A\x1B[2K${e} \u26A0 ${t} (\xD7${Fi})${m.reset}
840
- `)):(Lc=t,Fi=1,D(`${e} \u26A0 ${t}${m.reset}`))}var Gi=[];function JE(t){Gi.push(t.trim())}function ZE(){return Gi.length===0?null:Gi.splice(0,Gi.length).join(`
841
- `)}function Qg(t,e){let s=[],n=new Set([...e.keys(),...nr,...sr]);if(!n.size||!t)return s;for(let o of n){let r=o.split("/").pop();if(r&&(t.includes(r)||t.includes(o))){let a=t.split(`
842
- `).find(l=>l.includes(r)||l.includes(o));s.push({file:o,action:(a||"edit this file").trim().slice(0,200),done:!1})}}return s}function Ko(t,e,s,n){if(!ye)return null;let o=Le;Le=t,Xi=0,gn=Cc(t,Qs),jt=0,qt=!1,zt=0,Kt=0,ps.clear(),Ki.clear(),Uc.clear(),or.clear(),t==="implement"&&(hs=Qg(e||"",mn));let r=hs.length>0?`
841
+ `)[0],c=l.startsWith("ERROR")||l.includes("CANCELLED")||l.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(a)&&/✗ Agent/.test(a),u=Ic(t.fnName,t.args,a,c);e||console.log(u),on?.onToolEnd&&on.onToolEnd(t.fnName,u,!c);let f=qg("post-tool",{tool_name:t.fnName}).results;if(!e&&f.length>0)for(let _ of f)_.success?console.log(`${h.dim} [hook post-tool] ${_.command} \u2192 ${_.output||"ok"}${h.reset}`):console.log(`${h.yellow} [hook post-tool] ${_.command} \u2192 ERROR: ${_.error}${h.reset}`);let m=oT(a,t.fnName);if(t.fnName==="bash"&&t.args?.command){let _=t.args.command.trim();!/cat\s*>|<</.test(_)&&/\bcat\s+\S/.test(_)?m+=`
842
+ 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(_)&&!/npm|yarn|pnpm|make|git\b/.test(_)?m+=`
843
+ HINT: use list_directory instead of bash ls \u2014 it is the preferred tool for listing directory contents.`:/\bfind\s+\S/.test(_)&&!/git\b|npm\b|-exec\b|-delete\b|-print0\b/.test(_)&&(m+=`
844
+ 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:r?[{type:"text",text:m},...r.map(_=>({type:"image",media_type:_.media_type,data:_.base64}))]:m,tool_call_id:t.callId},summary:u}}var pT=[{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 Mc(t){for(let{re:e,label:s}of pT){let n=t.match(e);if(n){let o=(n[1]||"").trim();return o?`${s}: ${o}`:s}}return null}async function hT(t,e=!1,s={}){let n=new Array(t.length),o=[],r=[],i=null;if(e&&!s.skipSpinner){let l=t.filter(c=>c.canExecute);if(l.length>0){let c;if(l.length===1){let u=l[0],d=fT(u.fnName,u.args);c=`\u23FA ${u.fnName}${d?`(${d})`:""}`}else{let u=l.map(d=>d.fnName).join(", ");c=`\u23FA ${l.length} tools: ${u.length>60?u.substring(0,57)+"\u2026":u}`}i=new Zs(c),i.start()}}async function a(){if(r.length!==0){if(r.length===1){let l=r[0],{msg:c,summary:u}=await Nc(t[l],e);n[l]=c,o.push(u)}else{let l=r.map(u=>Nc(t[u],e)),c=await Promise.all(l);for(let u=0;u<r.length;u++)n[r[u]]=c[u].msg,o.push(c[u].summary)}r=[]}}for(let l=0;l<t.length;l++){let c=t[l];if(!c.canExecute){await a(),n[l]=c.errorResult,o.push(Ic(c.fnName,c.args||{},c.errorResult.content,!0));continue}if(aT.has(c.fnName)){await a(),c.fnName==="spawn_agents"&&i&&(i.stop(),i=null);let{msg:u,summary:d}=await Nc(c,e);n[l]=u,o.push(d)}else r.push(l)}if(await a(),i&&i.stop(),e&&o.length>0&&!s.skipSummaries)for(let l of o)console.log(l);return{results:n,summaries:o}}var L=[],Kg=300,iy=900*1e3;function sn(t,e){let s=t.get(e);return s?Date.now()-s.ts>iy?(t.delete(e),0):s.count:0}function us(t,e){let s=t.get(e),n=s&&Date.now()-s.ts<=iy?s.count+1:1;return t.set(e,{count:n,ts:Date.now()}),n}function Pc(t,e,s){t.set(e,{count:s,ts:Date.now()})}var Vc=new Map,ay=new Map,Wi=new Map,ir=new Set,ly=new Map,Hi=new Map,ar=new Set,mn=new Map,Cn=new Map,lr=new Map,Lt=new Map,hs=new Map,Xg=new Map,ea=new Map,Uc=new Map,It=0,tr=0,Yi=0,Wc="",Gi=0,Tt=!1,qi=0,zi=0,ds=-1,Hc=!1,Ki=0,Xi=!1,jt=0,qt=!1,zt=0,Kt=0,nt=!1,_t="",nr=0,Rn=0,Vi="",fs=0,ps=0,Ji="",Vo=0,Dt=!1,Yc=!1,cr=new Map,ur=new Set,sr=null,Lc=!1,Jo=0,Vg=!1,Le="plan",ta=0,_e=!1,On=0,gn=null,Gc=null,zc=null,to=0,no=null,ms=[];function Js(t,e){t===Wc?(Gi++,debug.DEBUG&&process.stdout.write(`\x1B[1A\x1B[2K${e} \u26A0 ${t} (\xD7${Gi})${h.reset}
845
+ `)):(Wc=t,Gi=1,j(`${e} \u26A0 ${t}${h.reset}`))}var Zi=[];function mT(t){Zi.push(t.trim())}function gT(){return Zi.length===0?null:Zi.splice(0,Zi.length).join(`
846
+ `)}function yT(t){let e=t._startedAt?Math.round((t.finishedAt-t._startedAt)/1e3):null,s=e!==null?`
847
+ Duration: ${e}s`:"",n=typeof t.result.result=="string"?t.result.result.slice(0,4e3):JSON.stringify(t.result.result||"").slice(0,4e3),o=t.result.filesModified&&t.result.filesModified.length>0?`
848
+ Files modified: ${t.result.filesModified.join(", ")}`:"";return`[BACKGROUND AGENT COMPLETED]
849
+ Job: ${t.jobId}
850
+ Task: "${t.agentDef.task}"`+s+`
851
+ Status: ${t.result.status||"done"}`+o+`
852
+ Result: ${n}`}function Fi(t,e){let{getCompletedJobs:s}=Fs(),n=s();for(let o of n){let r={role:"user",content:yT(o)};t.push(r),e.push(r);let i=o.result?.status||"done",a=i==="failed"?h.red+" \u2717":h.cyan+" \u2713";process.stderr.write(`${a} Background agent ${i}: ${o.agentDef.task.slice(0,50)} \u2014 ${String(o.result?.result||"").slice(0,80)}${h.reset}
853
+ `)}}function cy(t,e){let s=[],n=new Set([...e.keys(),...ir,...ar]);if(!n.size||!t)return s;for(let o of n){let r=o.split("/").pop();if(r&&(t.includes(r)||t.includes(o))){let a=t.split(`
854
+ `).find(l=>l.includes(r)||l.includes(o));s.push({file:o,action:(a||"edit this file").trim().slice(0,200),done:!1})}}return s}function Zo(t,e,s,n){if(!_e)return null;let o=Le;Le=t,ta=0,gn=Dc(t,no),jt=0,qt=!1,zt=0,Kt=0,hs.clear(),ea.clear(),Vc.clear(),lr.clear(),t==="implement"&&(ms=cy(e||"",mn));let r=ms.length>0?`
843
855
 
844
856
  ACTION ITEMS (execute these in order, do NOT re-read these files):
845
- `+hs.map((a,l)=>`${l+1}. ${a.file} \u2014 ${a.action}`).join(`
846
- `):"",i;if(t==="implement")jc=e?.slice(0,2e3)||"",i=`[PHASE: IMPLEMENTATION] Analysis complete. Based on the analysis:
847
- ${jc}
857
+ `+ms.map((a,l)=>`${l+1}. ${a.file} \u2014 ${a.action}`).join(`
858
+ `):"",i;if(t==="implement")Gc=e?.slice(0,2e3)||"",i=`[PHASE: IMPLEMENTATION] Analysis complete. Based on the analysis:
859
+ ${Gc}
848
860
 
849
- Now implement the fix/changes. Do not investigate further \u2014 edit files directly.`+r;else if(t==="verify"){qc=e?.slice(0,500)||"";let a=s?[...s].join(", "):"none";i=`[PHASE: VERIFICATION] Implementation complete. Verify the changes:
861
+ Now implement the fix/changes. Do not investigate further \u2014 edit files directly.`+r;else if(t==="verify"){zc=e?.slice(0,500)||"";let a=s?[...s].join(", "):"none";i=`[PHASE: VERIFICATION] Implementation complete. Verify the changes:
850
862
  1. Read each modified file and confirm changes are correct
851
863
  2. If test command exists (npm test / pytest): run it
852
864
  3. If linter exists: run it
@@ -854,18 +866,18 @@ Now implement the fix/changes. Do not investigate further \u2014 edit files dire
854
866
  Report PASS (all good) or FAIL (list specific issues).
855
867
 
856
868
  Files modified: ${a}
857
- Summary: ${qc}`}return D(`${m.cyan} \u21B3 Phase transition: ${o} \u2192 ${t} (model: ${gn||"default"})${m.reset}`),i?{role:"user",content:i}:null}function QE(){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)
858
- `];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"),er()?o.push(" \u2022 FILE CREATION TASKS (Makefile, Dockerfile, config files, documentation): ALWAYS use write_file to create the file on disk. In auto mode the user cannot see your text output \u2014 only files on disk matter."):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(`
869
+ Summary: ${zc}`}return j(`${h.cyan} \u21B3 Phase transition: ${o} \u2192 ${t} (model: ${gn||"default"})${h.reset}`),i?{role:"user",content:i}:null}function wT(){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)
870
+ `];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"),or()?o.push(" \u2022 FILE CREATION TASKS (Makefile, Dockerfile, config files, documentation): ALWAYS use write_file to create the file on disk. In auto mode the user cannot see your text output \u2014 only files on disk matter."):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(`
859
871
  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(`
860
872
  `)+`
861
873
 
862
- `}function eT(){if(Js!==null)return Js;try{let e=xE().flatMap(o=>o.models.map(r=>({spec:`${o.name}:${r.id}`,tier:bE(r.id,o.name),name:r.name})));if(e.length<2)return Js="","";let s={full:"complex tasks (refactor, implement, generate)",standard:"regular tasks (edit, fix, analyze)",essential:"simple tasks (read, search, list)"},n=`
874
+ `}function _T(){if(eo!==null)return eo;try{let e=FE().flatMap(o=>o.models.map(r=>({spec:`${o.name}:${r.id}`,tier:qE(r.id,o.name),name:r.name})));if(e.length<2)return eo="","";let s={full:"complex tasks (refactor, implement, generate)",standard:"regular tasks (edit, fix, analyze)",essential:"simple tasks (read, search, list)"},n=`
863
875
  # Sub-Agent Model Routing
864
876
 
865
877
  `;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 |
866
878
  |---|---|---|
867
879
  `;for(let o of e)n+=`| ${o.spec} | ${o.tier} | ${s[o.tier]||o.tier} |
868
- `;return Js=n,n}catch(t){return process.env.NEX_DEBUG&&console.error("[agent] model routing guide failed:",t.message),Js="",""}}var Fc="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->";function tT(t){let e=t.indexOf(Fc);return e===-1?{dynamic:t,static:""}:{dynamic:t.slice(0,e).trimEnd(),static:t.slice(e+Fc.length).trimStart()}}async function Bc(){let t=await Xg()+":"+Xt();if(Xo!==null&&t===Nc)return Xo;let e=await Bv(process.cwd()),s=Qv(),n=gE(),o=tr()?aE():"",r=QE(),i=eE(),a=SE(Xt());return Xo=`${a?`## Model Briefing
880
+ `;return eo=n,n}catch(t){return process.env.NEX_DEBUG&&console.error("[agent] model routing guide failed:",t.message),eo="",""}}var Kc="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->";function $T(t){let e=t.indexOf(Kc);return e===-1?{dynamic:t,static:""}:{dynamic:t.slice(0,e).trimEnd(),static:t.slice(e+Kc.length).trimStart()}}async function Xc(){let t=await ry()+":"+Xt();if(Qo!==null&&t===Fc)return Qo;let e=await rE(process.cwd()),s=yE(),n=PE(),o=rr()?vE():"",r=wT(),i=wE(),a=UE(Xt());return Qo=`${a?`## Model Briefing
869
881
  ${a}
870
882
 
871
883
  ---
@@ -886,7 +898,7 @@ ${o}
886
898
  ${r?`${r}
887
899
  `:""}${i?`${i}
888
900
 
889
- `:""}${er()?`# YOLO Mode \u2014 Auto-Execute
901
+ `:""}${or()?`# YOLO Mode \u2014 Auto-Execute
890
902
 
891
903
  You are in YOLO mode (autoConfirm=true). All tool calls are pre-approved.
892
904
  - NEVER ask for confirmation \u2014 just execute tasks directly
@@ -1092,6 +1104,10 @@ This applies to bash output, SSH output, grep results, and all other tool output
1092
1104
  - Good for: reading multiple files, analyzing separate modules, running independent searches.
1093
1105
  - Bad for: tasks that depend on each other or modify the same file.
1094
1106
  - Max 5 parallel agents.
1107
+ - Background agents: if a task can run in parallel while you do something else (e.g. "analyze X while explaining Y", "run linter in background"), use spawn_agents and set background: true on the parallel task. You decide when this is appropriate \u2014 no explicit user instruction needed.
1108
+ Example: spawn_agents({"agents": [{"task": "analyze package.json", "background": true}, {"task": "explain routing system"}]})
1109
+ The background agent starts immediately; its result arrives as a [BACKGROUND AGENT COMPLETED] user message automatically.
1110
+ There is NO separate "background-agent" tool \u2014 use spawn_agents with background: true on the relevant agents.
1095
1111
 
1096
1112
  # Parallel Tool Calls (Critical for Efficiency)
1097
1113
 
@@ -1119,7 +1135,7 @@ You have a soft budget of ~30 tool calls per task. Sessions with >40 tool calls
1119
1135
  - Instead: use bash with inline node -e '...' for quick one-off checks.
1120
1136
  - If the test is worth keeping, write it to tests/ with a proper name.
1121
1137
  - Write-then-delete patterns waste 3 tool calls and leave orphans if the session is interrupted.
1122
- ${eT()}
1138
+ ${_T()}
1123
1139
 
1124
1140
  # Edit Protocol (Mandatory \u2014 Follow These Steps Exactly)
1125
1141
 
@@ -1231,7 +1247,7 @@ class MyListView(ListAPIView):
1231
1247
  \`\`\`python
1232
1248
  # \u2705 CORRECT - Fail immediately if environment variable missing
1233
1249
  SECRET_KEY = os.environ['DJANGO_SECRET_KEY']
1234
- DEBUG = os.environ.get('DEBUG', 'False') == 'True'
1250
+ DEBUG = os.environ['DEBUG'] == 'True'
1235
1251
 
1236
1252
  # \u274C WRONG - Insecure defaults allow production deployment with dev settings
1237
1253
  SECRET_KEY = os.getenv('SECRET_KEY', 'insecure-dev-key')
@@ -1310,90 +1326,91 @@ class ErrorBoundary extends React.Component {
1310
1326
  - Use migrations for schema changes, never manual ALTER TABLE
1311
1327
  - Add database-level constraints (unique, foreign key, check) not just app-level
1312
1328
 
1313
- `,Nc=t,Xo}function ey(){Uc.clear(),Jg.clear(),Di.clear(),nr.clear(),Zg.clear(),ji.clear(),sr.clear(),mn.clear(),An.clear(),or.clear(),Lt.clear(),ps.clear(),Ki.clear(),Pc.clear(),It=0,Jo=0,qi=0,Tt=!1,Bi=0,us=-1,Ic=!1,Ui=0,Wi=!1,jt=0,qt=!1,zt=0,Kt=0,tt=!1,_t="",Zo=0,Hi="",ds=0,Yi="",fs=0,Dt=!1,Dc=!1,Le="plan",Xi=0,ye=!1,gn=null,jc=null,qc=null,hs=[],Zs=0,Nn=0,Qs=null,rr.clear(),ir.clear(),Lc="",Fi=0}function nT(){j=[],Qo=null,ey();try{let{resetCompactionFailures:t}=Al();t()}catch{}}function sT(){j.length>jg&&j.splice(0,j.length-jg)}function oT(){return j.length}function rT(){return j}function iT(t){j=t}async function aT(){let{execFile:t}=require("child_process"),e=require("fs"),s=process.cwd(),n=(d,f)=>new Promise(p=>{t(d,f,{cwd:s,timeout:3e3},(h,g)=>{p(h?"":(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(`
1314
- `):[]).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 c=` \u{1F4C1} ${Object.entries(a).sort((d,f)=>f[1]-d[1]).slice(0,4).map(([d,f])=>`${f} .${d}`).join(" \xB7 ")}`,u=eo.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 p=f.slice(0,5).join(" \xB7 "),h=f.length>5?` +${f.length-5}`:"";c+=`
1315
- \u{1F4E6} ${p}${h}`}}catch{}return c}function lT(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 Ne(t,e,s,n,o,{suppressHint:r=!1}={}){if(t<1)return;let i=[...e.values()].reduce((c,u)=>c+u,0),a=`\u2500\u2500 ${t} ${t===1?"step":"steps"} \xB7 ${i} ${i===1?"tool":"tools"}`,l=0;if(o){let c=Date.now()-o;l=Math.round(c/1e3),a+=l>=60?` \xB7 ${Math.floor(l/60)}m ${l%60}s`:` \xB7 ${l}s`}if(s.size>0&&(a+=` \xB7 ${s.size} ${s.size===1?"file":"files"} modified`),a+=" \u2500\u2500",console.log(`
1316
- ${m.dim} ${a}${m.reset}`),l>=30&&process.stdout.isTTY){let c=s.size>0?`Done \u2014 ${s.size} ${s.size===1?"file":"files"} modified in ${l}s`:`Done \u2014 ${t} ${t===1?"step":"steps"} in ${l}s`;lT(c)}if(ir.size>0&&rr.size>0)for(let c of ir){let u=rr.get(c);u&&console.log(`${m.dim} \u2714 task #${c} auto-matched: ${u.slice(0,60)}${m.reset}`)}s.size>0?console.log(`${m.dim} \u{1F4A1} /diff \xB7 /commit \xB7 /undo${m.reset}`):!r&&n.size>=5&&s.size===0&&t>=3?console.log(`${m.dim} \u{1F4A1} Found issues? Say "fix 1" or "apply all fixes"${m.reset}`):n.size>0&&t>=2&&console.log(`${m.dim} \u{1F4A1} /save \xB7 /clear${m.reset}`)}async function cT(){if(!process.stdout.isTTY)return{action:"quit"};let t=Vs(),e=Xt(),s=zi.fast?.[t],n=zi.strong?.[t],o=s&&s!==e,r=n&&n!==e&&n!==s,i=[];i.push({key:"r",label:`Retry with current model ${m.dim}(${e})${m.reset}`}),o&&i.push({key:"f",label:`Switch to ${m.bold}${s}${m.reset} ${m.dim}\u2014 fast, low latency${m.reset}`,model:s}),r&&i.push({key:"s",label:`Switch to ${m.bold}${n}${m.reset} ${m.dim}\u2014 reliable tool-calling, medium speed${m.reset}`,model:n}),i.push({key:"q",label:`${m.dim}Quit${m.reset}`}),console.log(),console.log(`${m.yellow} Stream stale \u2014 all retries exhausted.${m.reset} What would you like to do?`);for(let a of i)console.log(` ${m.cyan}[${a.key}]${m.reset} ${a.label}`);return process.stdout.write(` ${m.yellow}> ${m.reset}`),new Promise(a=>{let l=process.stdin,c=l.isRaw;l.setRawMode(!0),l.resume(),l.setEncoding("utf8");let u=!1,d=f=>{if(u)return;u=!0,l.removeListener("data",d),l.setRawMode(c||!1),l.pause();let p=f.toLowerCase().trim();if(process.stdout.write(`${p}
1317
- `),f==="")return a({action:"quit"});let h=i.find(g=>g.key===p);!h||h.key==="q"||!h.model&&h.key!=="r"?a({action:"quit"}):h.key==="r"?a({action:"retry"}):a({action:"switch",model:h.model,provider:t})};l.on("data",d)})}function uT(t){let e=/https?:\/\/[^\s/]+(\/[^\s?#]+)/g,s=new Set,n;for(;(n=e.exec(t))!==null;){let o=n[1].replace(/\/$/,"");o.length>1&&o.split("/").filter(i=>i.length>2).forEach(i=>s.add(i))}return Array.from(s)}function dT(t){let e=[];return(t.includes("@click")||t.includes("x-data")||t.includes("v-if")||t.includes("v-model"))&&e.push("Snippet contains Vue/Alpine.js directives (e.g., @click, v-model). Do not restrict your search to just .js/.ts/.vue files; also search .html and .py (templates) if appropriate."),(t.includes("className=")||t.includes("useEffect"))&&e.push("Snippet appears to be React. Look in .jsx, .tsx, .js, .ts files."),e}var on=null;async function fT(t,e=null,s={}){let n=kE(Xt());Dg=n.staleWarn,kc=n.staleAbort,on=e;let o=t;if(Qo&&typeof t=="string"&&(o=`${Qo}
1329
+ `,Fc=t,Qo}function uy(){Vc.clear(),ay.clear(),Wi.clear(),ir.clear(),ly.clear(),Hi.clear(),ar.clear(),mn.clear(),Cn.clear(),lr.clear(),Lt.clear(),hs.clear(),ea.clear(),Uc.clear(),It=0,tr=0,Yi=0,Tt=!1,zi=0,ds=-1,Hc=!1,Ki=0,Xi=!1,jt=0,qt=!1,zt=0,Kt=0,nt=!1,_t="",nr=0,Vi="",fs=0,Ji="",ps=0,Dt=!1,Yc=!1,Le="plan",ta=0,_e=!1,gn=null,Gc=null,zc=null,ms=[],to=0,On=0,no=null,cr.clear(),ur.clear(),Wc="",Gi=0}function bT(){L=[],sr=null,uy();try{let{resetCompactionFailures:t}=Il();t()}catch{}try{let{cancelAllJobs:t}=Fs();t()}catch{}}function xT(){L.length>Kg&&L.splice(0,L.length-Kg)}function kT(){return L.length}function ST(){return L}function vT(t){L=t}async function ET(){let{execFile:t}=require("child_process"),e=require("fs"),s=process.cwd(),n=(d,f)=>new Promise(p=>{t(d,f,{cwd:s,timeout:3e3},(m,g)=>{p(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(`
1330
+ `):[]).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 c=` \u{1F4C1} ${Object.entries(a).sort((d,f)=>f[1]-d[1]).slice(0,4).map(([d,f])=>`${f} .${d}`).join(" \xB7 ")}`,u=so.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 p=f.slice(0,5).join(" \xB7 "),m=f.length>5?` +${f.length-5}`:"";c+=`
1331
+ \u{1F4E6} ${p}${m}`}}catch{}return c}function TT(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 Ne(t,e,s,n,o,{suppressHint:r=!1}={}){if(t<1)return;let i=[...e.values()].reduce((c,u)=>c+u,0),a=`\u2500\u2500 ${t} ${t===1?"step":"steps"} \xB7 ${i} ${i===1?"tool":"tools"}`,l=0;if(o){let c=Date.now()-o;l=Math.round(c/1e3),a+=l>=60?` \xB7 ${Math.floor(l/60)}m ${l%60}s`:` \xB7 ${l}s`}if(s.size>0&&(a+=` \xB7 ${s.size} ${s.size===1?"file":"files"} modified`),a+=" \u2500\u2500",console.log(`
1332
+ ${h.dim} ${a}${h.reset}`),l>=30&&process.stdout.isTTY){let c=s.size>0?`Done \u2014 ${s.size} ${s.size===1?"file":"files"} modified in ${l}s`:`Done \u2014 ${t} ${t===1?"step":"steps"} in ${l}s`;TT(c)}if(ur.size>0&&cr.size>0)for(let c of ur){let u=cr.get(c);u&&console.log(`${h.dim} \u2714 task #${c} auto-matched: ${u.slice(0,60)}${h.reset}`)}s.size>0?console.log(`${h.dim} \u{1F4A1} /diff \xB7 /commit \xB7 /undo${h.reset}`):!r&&n.size>=5&&s.size===0&&t>=3?console.log(`${h.dim} \u{1F4A1} Found issues? Say "fix 1" or "apply all fixes"${h.reset}`):n.size>0&&t>=2&&console.log(`${h.dim} \u{1F4A1} /save \xB7 /clear${h.reset}`)}async function RT(){if(!process.stdout.isTTY)return{action:"quit"};let t=Qs(),e=Xt(),s=Qi.fast?.[t],n=Qi.strong?.[t],o=s&&s!==e,r=n&&n!==e&&n!==s,i=[];i.push({key:"r",label:`Retry with current model ${h.dim}(${e})${h.reset}`}),o&&i.push({key:"f",label:`Switch to ${h.bold}${s}${h.reset} ${h.dim}\u2014 fast, low latency${h.reset}`,model:s}),r&&i.push({key:"s",label:`Switch to ${h.bold}${n}${h.reset} ${h.dim}\u2014 reliable tool-calling, medium speed${h.reset}`,model:n}),i.push({key:"q",label:`${h.dim}Quit${h.reset}`}),console.log(),console.log(`${h.yellow} Stream stale \u2014 all retries exhausted.${h.reset} What would you like to do?`);for(let a of i)console.log(` ${h.cyan}[${a.key}]${h.reset} ${a.label}`);return process.stdout.write(` ${h.yellow}> ${h.reset}`),new Promise(a=>{let l=process.stdin,c=l.isRaw;l.setRawMode(!0),l.resume(),l.setEncoding("utf8");let u=!1,d=f=>{if(u)return;u=!0,l.removeListener("data",d),l.setRawMode(c||!1),l.pause();let p=f.toLowerCase().trim();if(process.stdout.write(`${p}
1333
+ `),f==="")return a({action:"quit"});let m=i.find(g=>g.key===p);!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})};l.on("data",d)})}function CT(t){let e=/https?:\/\/[^\s/]+(\/[^\s?#]+)/g,s=new Set,n;for(;(n=e.exec(t))!==null;){let o=n[1].replace(/\/$/,"");o.length>1&&o.split("/").filter(i=>i.length>2).forEach(i=>s.add(i))}return Array.from(s)}function AT(t){let e=[];return(t.includes("@click")||t.includes("x-data")||t.includes("v-if")||t.includes("v-model"))&&e.push("Snippet contains Vue/Alpine.js directives (e.g., @click, v-model). Do not restrict your search to just .js/.ts/.vue files; also search .html and .py (templates) if appropriate."),(t.includes("className=")||t.includes("useEffect"))&&e.push("Snippet appears to be React. Look in .jsx, .tsx, .js, .ts files."),e}var on=null;async function OT(t,e=null,s={}){let n=BE(Xt());zg=n.staleWarn,Oc=n.staleAbort,on=e;let o=t;if(sr&&typeof t=="string"&&(o=`${sr}
1318
1334
 
1319
- ${t}`,Qo=null),typeof o=="string"){let _e=uT(o),be=dT(o);(_e.length>0||be.length>0)&&(o+=`
1335
+ ${t}`,sr=null),typeof o=="string"){let ge=CT(o),ye=AT(o);(ge.length>0||ye.length>0)&&(o+=`
1320
1336
 
1321
1337
  [System Note for Assistant: To resolve this task faster, consider these hints:
1322
- `,_e.length>0&&(o+=`- The user mentioned URLs containing the paths/folders: ${_e.join(", ")}. Prioritize searching these folder names using glob or grep first.
1323
- `),be.length>0&&be.forEach(Ce=>{o+=`- ${Ce}
1324
- `}),o+="Always prefer parallel search execution if unsure.]")}typeof o=="string"&&zg(o)&&(o+=`
1338
+ `,ge.length>0&&(o+=`- The user mentioned URLs containing the paths/folders: ${ge.join(", ")}. Prioritize searching these folder names using glob or grep first.
1339
+ `),ye.length>0&&ye.forEach(Se=>{o+=`- ${Se}
1340
+ `}),o+="Always prefer parallel search execution if unsure.]")}typeof o=="string"&&sy(o)&&(o+=`
1325
1341
 
1326
- [Note for assistant: the user appears frustrated \u2014 acknowledge their concern briefly and empathetically before proceeding]`);let r=Gg(o);r&&typeof r.then=="function"&&(r=await r),j.push({role:"user",content:r}),sT();let i=s.autoOrchestrate!==!1&&process.env.NEX_AUTO_ORCHESTRATE!=="false",a=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10);try{let{detectComplexPrompt:_e,runOrchestrated:be}=Eg(),Ce=_e(typeof t=="string"?t:"");if(i&&Ce.isComplex&&Ce.estimatedGoals>=a){console.log(`${m.yellow}\u26A1 Auto-orchestrate: ${Ce.estimatedGoals} goals \u2192 parallel agents${m.reset}`);let lt=await be(t,{orchestratorModel:s.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL,workerModel:s.model});if(lt&&lt.synthesis){let ct=lt.synthesis.summary||"",wn=lt.synthesis.filesChanged?.length?`
1342
+ [Note for assistant: the user appears frustrated \u2014 acknowledge their concern briefly and empathetically before proceeding]`);let r=ny(o);r&&typeof r.then=="function"&&(r=await r),L.push({role:"user",content:r}),xT();let i=s.autoOrchestrate!==!1&&process.env.NEX_AUTO_ORCHESTRATE!=="false",a=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10);try{let{detectComplexPrompt:ge,runOrchestrated:ye}=Ig(),Se=ge(typeof t=="string"?t:"");if(i&&Se.isComplex&&Se.estimatedGoals>=a){console.log(`${h.yellow}\u26A1 Auto-orchestrate: ${Se.estimatedGoals} goals \u2192 parallel agents${h.reset}`);let Ve=await ye(t,{orchestratorModel:s.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL,workerModel:s.model});if(Ve&&Ve.synthesis){let ct=Ve.synthesis.summary||"",yn=Ve.synthesis.filesChanged?.length?`
1327
1343
 
1328
- Files changed: ${lt.synthesis.filesChanged.join(", ")}`:"",ze=lt.synthesis.conflicts?.length?`
1344
+ Files changed: ${Ve.synthesis.filesChanged.join(", ")}`:"",ze=Ve.synthesis.conflicts?.length?`
1329
1345
 
1330
1346
  Conflicts:
1331
- ${lt.synthesis.conflicts.map(Rt=>`- ${Rt}`).join(`
1332
- `)}`:"";j.push({role:"assistant",content:ct+wn+ze}),Oe(j),Ni(j)}return lt}Ce.isComplex&&process.stdout.isTTY&&console.log(`${m.dim}Hint: ~${Ce.estimatedGoals} goals detected. Disable with NEX_AUTO_ORCHESTRATE=false${m.reset}`)}catch{}let{setOnChange:l}=Rl(),c=null,u=0;l((_e,be)=>{_e==="create"?(c&&c.stop(),c=new Pv(be.name,be.tasks),c.setStats({tokens:u}),c.start()):_e==="update"&&c?c.updateTask(be.id,be.status):_e==="clear"&&c&&(c.stop(),c=null)});let d=await Bc(),f=d;try{let{getBrainContext:_e}=Hl(),be=await _e(t);be&&(f=d+`
1333
- `+be+`
1334
- `)}catch(_e){process.env.NEX_DEBUG&&console.error("[agent] brain context failed:",_e.message)}let h=_E(typeof t=="string"?t:"");if(h.length>0){let _e=h.map(be=>`[Triggered: ${be.name}]
1335
- ${be.instructions}`).join(`
1347
+ ${Ve.synthesis.conflicts.map(Rt=>`- ${Rt}`).join(`
1348
+ `)}`:"";L.push({role:"assistant",content:ct+yn+ze}),Ae(L),Di(L)}return Ve}Se.isComplex&&process.stdout.isTTY&&console.log(`${h.dim}Hint: ~${Se.estimatedGoals} goals detected. Disable with NEX_AUTO_ORCHESTRATE=false${h.reset}`)}catch{}let{setOnChange:l}=Pl(),c=null,u=0;l((ge,ye)=>{ge==="create"?(c&&c.stop(),c=new Qv(ye.name,ye.tasks),c.setStats({tokens:u}),c.start()):ge==="update"&&c?c.updateTask(ye.id,ye.status):ge==="clear"&&c&&(c.stop(),c=null)});let d=await Xc(),f=d;try{let{getBrainContext:ge}=Jl(),ye=await ge(t);ye&&(f=d+`
1349
+ `+ye+`
1350
+ `)}catch(ge){process.env.NEX_DEBUG&&console.error("[agent] brain context failed:",ge.message)}let m=DE(typeof t=="string"?t:"");if(m.length>0){let ge=m.map(ye=>`[Triggered: ${ye.name}]
1351
+ ${ye.instructions}`).join(`
1336
1352
  `);f+=`
1337
- `+_e+`
1338
- `}let g=[{role:"system",content:f},...j];Dv(Xt());let _=new Xs(yc());_.start();let b=j.length===1,O=b?aT().catch(()=>null):Promise.resolve(null),M=b?tE(typeof t=="string"?t:"").catch(()=>null):Promise.resolve(null),v=at(),[{messages:T,compressed:N,compacted:te,tokensRemoved:K},ie,le]=await Promise.all([Uv(g,v),O,M]),ne=Gt(g,v);if(_.stop(),ie&&console.log(`${m.dim}${ie}${m.reset}`),te)console.log(`${m.dim} [context compacted \u2014 summary (~${K} tokens freed)]${m.reset}`);else if(N){let _e=ne.limit>0?Math.round(K/ne.limit*100):0;D(`${m.dim} [context compressed \u2014 ~${K} tokens freed (${_e}%)]${m.reset}`)}ne.percentage>85&&D(`${m.yellow} \u26A0 Context ${Math.round(ne.percentage)}% used (${Math.round(100-ne.percentage)}% remaining) \u2014 consider /clear or /save + start fresh${m.reset}`);let k=T;if(le&&b&&(k=[k[0],{role:"user",content:`[Server probe at task start]
1339
- ${le}`},{role:"assistant",content:"Understood \u2014 I have the server context. Proceeding with the task."},...k.slice(1)]),b){let _e=nE(typeof t=="string"?t:"");_e&&(k=[k[0],{role:"user",content:`[EXAMPLE \u2014 illustrative only, not the real task]
1340
- `+_e.user},{role:"assistant",content:_e.assistant+`
1341
- [END EXAMPLE \u2014 wait for the real user request below]`},...k.slice(1)])}if(Gt(k,at()).percentage>=65){let{messages:be,tokensRemoved:Ce}=nn(k,at());Ce>0&&(k=be,console.log(`${m.dim} [pre-flight compress \u2014 ${Ce} tokens freed, now ${Math.round(Gt(k,at()).percentage)}% used]${m.reset}`))}let ve=0,H=0,X=0,pe=0,Re=0,Ue=9,ke=0,$e=(()=>{let _e=j.find(be=>be.role==="user");return typeof _e?.content=="string"?_e.content:""})(),$=/set_reminder|google.?auth|cron:|api\.log|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($e),I=0;if(!tt){let _e=j.filter(Ce=>Ce.role==="user"||Ce.role==="tool").map(Ce=>typeof Ce.content=="string"?Ce.content:"").join(`
1342
- `),be=vc(_e);be&&(tt=!0,_t=be.slice(0,120),D(`${m.yellow} \u26A1 Root cause in briefing: ${_t} \u2014 fix phase active from start (read budget: 3)${m.reset}`))}!tt&&!Dt&&/\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($e)&&(Dt=!0,D(`${m.cyan} \u26A1 Creation task detected \u2014 tight investigation cap (4 pre-edit, 2 post-edit)${m.reset}`)),j.length<=1&&!s.skipPhaseRouting&&(ye=Jv(),ye&&(Qs=Vv($e)?.id||"coding",Le="plan",gn=Cc("plan",Qs),Xi=0,Zs=0,Nn=0,process.stdout.isTTY&&console.log(`${m.dim} \u21B3 Phase routing: plan(${gn||"default"}) \u2192 implement \u2192 verify${m.reset}`),D(`${m.cyan} \u26A1 Phase routing enabled \u2014 plan phase with ${gn||"default model"} (category: ${Qs})${m.reset}`)));let R=0,W=new Map,E=new Set,S=new Set,oe=new Set,we=0,ge=0,st=0,yn=0,Ae=Date.now(),gy=new jv(vE),yy=or,We=s.skillLoop?10:1,wy=3*We,_y=5*We,Zc=Uc,$y=5*We,by=8*We,xy=Jg,ky=(ye?6:4)*We,Sy=(ye?10:7)*We,ea=Di,vy=(ye?5:3)*We,lr=(ye?8:5)*We,Ey=Zg,Ty=(ye?4:3)*We,Ry=(ye?6:4)*We,Cy=3*We,Ay=4*We,ms=mn,Oy=(ye?6:4)*We,Ny=(ye?10:8)*We,gs=(ye?12:10)*We,My=25,Mn=0,Py=10*We,Ly=15*We,Pn=0,Qc=5*We,Ln=0,Iy=2*We,Dy=3,ta=0,so=10,jy=16,eu=s.skillLoop?999:n.investigationCap,na=typeof t=="string"?t.trim():"",tu=na.length>0&&/^\s*(analyze|analyse|analysiere|explain|erkläre|describe|beschreib|review|audit|summari[sz]e|zusammenfass|list|liste|what is|what does|wie funktioniert|wie geht|how does|show me|zeig|show the|show all|tell me about|erzähl)/i.test(na)&&!/\b(fix|bug|crash|error|implement|add|create|change|update|refactor|rewrite|broken|fail|patch|migrate|port|build|edit|write|delete|remove|install|setup|deploy|run)\b/i.test(na),He,bt=s.maxIterations||(ye?ls(Le):Oc);tu&&(bt=Math.min(bt,4),D(`${m.dim} \u21B3 Analysis-only prompt detected \u2014 iter cap=${bt}${m.reset}`));let sa=0,nu=3,oa=!1,cr=0;e:for(;;){for(oa=!1,He=0;He<bt&&!Li()?.aborted;He++){{let w=at(),y=Gt(k,w),z=R===0?65:78;if(y.percentage>=z){if(E.size>0||ye&&Le!=="plan"){let Q=Hv(j,{filesModified:E,currentPhase:ye?Le:null});if(Q){let U=k.findIndex(P=>P._progressSnapshot);U!==-1&&k.splice(U,1);let ue=k.findIndex(P=>P.role==="system");k.splice(ue+1,0,Q)}}let{messages:C,tokensRemoved:L}=nn(k,w,R===0);if(L>0&&(k=C,L>50&&console.log(`${m.dim} [auto-compressed \u2014 ~${L} tokens freed, now ${Math.round(Gt(k,w).percentage)}%]${m.reset}`),Dt&&E.size>=3)){let Q=[...E].map(ue=>ue.split("/").pop()).slice(0,10).join(", "),U={role:"user",content:`[FRAMEWORK \u2014 context compressed] Task is IN PROGRESS. Already created ${E.size} files: ${Q}. DO NOT restart or re-investigate what was already done. Continue from where you left off.`};k.push(U)}}}if(Tt&&!tt&&Zo<2){Zo++;let w={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."};k.push(w),j.push(w),D(`${m.yellow} \u26A0 Pre-call SSH-blocked nudge #${Zo} injected \u2014 model told to synthesize${m.reset}`)}Tt||(Zo=0);let be=!0;R>0&&dE();let Ce=null;if(c&&c.isActive())c._paused&&c.resume();else if(!c){let w,y=fE();if(y&&y.total>1){let z=y.description.length>40?y.description.slice(0,37)+"\u2026":y.description;w=`Plan step ${y.current}/${y.total}: ${z}`}else w=R>0?`${yc()} (step ${R+1})`:yc();Ce=new Xs(w),Ce.start()}let lt=!0,ct="",wn=!1,ze=new pE,Rt,ra=Date.now(),ur=!1,ia=new AbortController,su=setInterval(()=>{let w=Date.now()-ra;if(w>=kc)ze._clearCursorLine(),D(`${m.yellow} \u26A0 Stream stale for ${Math.round(w/1e3)}s \u2014 aborting and retrying${m.reset}`),ia.abort();else if(w>=Dg&&!ur){ur=!0,ze._clearCursorLine();let y=zi.fast?.[Vs()],z=X>0?` (retry ${X+1}/${Mi})`:"",C=Math.round((kc-w)/1e3);D(`${m.yellow} \u26A0 No tokens received for ${Math.round(w/1e3)}s \u2014 waiting...${z}${m.reset}`),y&&y!==Xt()?console.log(`${m.dim} \u{1F4A1} Will auto-switch to ${y} in ~${C}s if no tokens arrive${m.reset}`):console.log(`${m.dim} \u{1F4A1} Ctrl+C to abort \xB7 auto-abort in ~${C}s${m.reset}`)}},5e3),Ct="",rn=null;try{let w=Kg(at()),y=new Set(["read_file","list_directory","search_files","glob","grep","git_status","git_diff","git_log","git_show","ssh_exec"]),z=new Set(["read_file","list_directory","glob","grep","bash","git_status","git_diff","git_log","ssh_exec"]),C;tr()?C=w.filter(U=>Ug.has(U.function.name)):ye&&Le==="plan"?C=w.filter(U=>y.has(U.function.name)):ye&&Le==="verify"?C=w.filter(U=>z.has(U.function.name)):C=w;let L=Li(),Q=new AbortController;L&&L.addEventListener("abort",()=>Q.abort(),{once:!0}),ia.signal.addEventListener("abort",()=>Q.abort(),{once:!0}),Rt=await Tg(k,C,{signal:Q.signal,...gn?{model:gn}:{},onThinkingToken:()=>{ra=Date.now(),ur=!1,on?.onThinkingToken&&on.onThinkingToken()},onToken:U=>{if(ra=Date.now(),ur=!1,on?.onToken){on.onToken(U),ct+=U;return}if(ct+=U,!wn&&ct.length>400&&ct.length%250<U.length+1){let ue=Ac(ct,3);ue.truncated&&(wn=!0,ze._clearCursorLine?.(),D(`${m.yellow} \u26A0 LLM stream loop detected (${ue.repeatCount}\xD7 repeated) \u2014 suppressing display${m.reset}`))}wn||(Ct+=U,process.stdout.isTTY?rn||(rn=setTimeout(()=>{Ct&&ze&&ze.push(Ct),Ct="",rn=null},50)):(ze.push(Ct),Ct=""),lt&&(c&&!c._paused?c.pause():Ce&&Ce.stop(),be||(be=!0),ze.startCursor(),lt=!1))}})}catch(w){if(clearInterval(su),rn&&(clearTimeout(rn),rn=null),Ct&&ze&&(ze.push(Ct),Ct=""),c&&!c._paused&&c.pause(),Ce&&Ce.stop(),ze.stopCursor(),ia.signal.aborted&&!Li()?.aborted){if(X++,X>Mi){if(pe<1){pe++,Ks("Stale retries exhausted \u2014 last-resort force-compress...",m.yellow);let ue=at(),{messages:P,tokensRemoved:q}=nn(k,ue);k=P,q>50&&D(`${m.dim} [force-compressed \u2014 ~${q} tokens freed]${m.reset}`),X=0,He--;continue}c&&(c.stop(),c=null);let U=await cT();if(U.action==="quit"){l(null),Ne(R,W,E,S,Ae),Oe(j);break}U.action==="switch"&&(Mg(`${U.provider}:${U.model}`),console.log(`${m.green} \u2713 Switched to ${U.provider}:${U.model}${m.reset}`)),X=0,He--;continue}let L=X===1?3e3:5e3;if(X>=1&&ke<1){ke++,Ks(`Stale retry ${X}/${Mi} \u2014 force-compressing before retry...`,m.yellow);let U=at(),{messages:ue,tokensRemoved:P}=nn(k,U,!0);if(k=ue,P>0&&P>50&&D(`${m.dim} [force-compressed \u2014 ~${P} tokens freed]${m.reset}`),HE){let q=zi.fast?.[Vs()];q&&q!==Xt()&&(Mg(`${Vs()}:${q}`),console.log(`${m.cyan} \u26A1 Auto-switched to ${q} to avoid further stale timeouts${m.reset}`),console.log(`${m.dim} (disable with NEX_STALE_AUTO_SWITCH=0)${m.reset}`))}}else D(`${m.yellow} \u26A0 Stale retry ${X}/${Mi} \u2014 retrying in ${L/1e3}s...${m.reset}`);let Q=new Xs(`Waiting ${L/1e3}s before retry...`);Q.start(),await new Promise(U=>setTimeout(U,L)),Q.stop(),He--;continue}if(w.name==="AbortError"||w.name==="CanceledError"||w.message?.includes("canceled")||w.message?.includes("aborted")){c&&(c.stop(),c=null),l(null),Ne(R,W,E,S,Ae),Oe(j);break}let y=w.message;if(w.code==="ECONNREFUSED"||w.message.includes("ECONNREFUSED"))y="Connection refused \u2014 please check your internet connection or API endpoint";else if(w.code==="ENOTFOUND"||w.message.includes("ENOTFOUND"))y="Network error \u2014 could not reach the API server. Please check your connection";else if(w.code==="ETIMEDOUT"||w.message.includes("timeout"))y="Request timed out \u2014 the API server took too long to respond. Please try again";else if(w.message.includes("401")||w.message.includes("Unauthorized"))y="Authentication failed \u2014 please check your API key in the .env file";else if(w.message.includes("403")||w.message.includes("Forbidden"))y="Access denied \u2014 your API key may not have permission for this model";else if(w.message.includes("404")){y=`Model not found (404): ${Xt?Xt():"unknown"} \u2014 check your .env MODEL setting or run /models to list available models`,console.log(`${m.red} \u2717 ${y}${m.reset}`),c&&(c.stop(),c=null),l(null),Ne(R,W,E,S,Ae),Oe(j);break}else if(w.message.includes("400")){if(pe<3&&Re<Ue){pe++,Re++;let L=R===0&&pe===1,Q=L||pe===3||ke>0;if(L){pe=3;let q=w.message.replace(/^API Error(\s*\[HTTP \d+\])?:\s*/i,"").slice(0,150);Ks(`Bad request (400) \u2014 ${q||"system prompt too large"}, compressing...`,m.yellow)}else Ks(Q?`Bad request (400) \u2014 nuclear compression (attempt ${pe}/3, dropping history)...`:`Bad request (400) \u2014 force-compressing and retrying... (attempt ${pe}/3)`,m.yellow);let U=at(),{messages:ue,tokensRemoved:P}=nn(k,U,Q);k=ue,P>50&&D(`${m.dim} [force-compressed \u2014 ~${P} tokens freed]${m.reset}`),He--;continue}{let L=k.find(F=>F.role==="system"),Q=k.find(F=>F.role==="user"&&!String(F.content).startsWith("[SYSTEM")&&!String(F.content).startsWith("BLOCKED:")),U=[L,Q].filter(Boolean),{getUsage:ue}=en(),P=en().estimateMessagesTokens(U),q=en().estimateMessagesTokens(k);if(P<q){let F=[],V=j.filter(ee=>ee.role==="assistant"&&typeof ee.content=="string"&&ee.content.trim().length>30).slice(-5).map(ee=>ee.content.trim().slice(0,300).replace(/\n+/g," "));V.length>0&&F.push(`Key findings:
1343
- `+V.map(ee=>`- ${ee}`).join(`
1344
- `));let J=j.filter(ee=>ee.role==="tool"&&typeof ee.content=="string"&&!ee.content.startsWith("BLOCKED:")&&ee.content.trim().length>10).slice(-5).map(ee=>ee.content.trim().split(`
1353
+ `+ge+`
1354
+ `}let g=[{role:"system",content:f},...L];Dg(Xt());let _=new Zs(Sc());_.start();let b=L.length===1,A=b?ET().catch(()=>null):Promise.resolve(null),P=b?_E(typeof t=="string"?t:"").catch(()=>null):Promise.resolve(null),v=at(),[{messages:E,compressed:O,compacted:ne,tokensRemoved:J},ie,ce]=await Promise.all([iE(g,v),A,P]),se=Gt(g,v);if(_.stop(),ie&&console.log(`${h.dim}${ie}${h.reset}`),ne)console.log(`${h.dim} [context compacted \u2014 summary (~${J} tokens freed)]${h.reset}`);else if(O){let ge=se.limit>0?Math.round(J/se.limit*100):0;j(`${h.dim} [context compressed \u2014 ~${J} tokens freed (${ge}%)]${h.reset}`)}se.percentage>85&&j(`${h.yellow} \u26A0 Context ${Math.round(se.percentage)}% used (${Math.round(100-se.percentage)}% remaining) \u2014 consider /clear or /save + start fresh${h.reset}`);let S=E;if(ce&&b&&(S=[S[0],{role:"user",content:`[Server probe at task start]
1355
+ ${ce}`},{role:"assistant",content:"Understood \u2014 I have the server context. Proceeding with the task."},...S.slice(1)]),b){let ge=$E(typeof t=="string"?t:"");ge&&(S=[S[0],{role:"user",content:`[EXAMPLE \u2014 illustrative only, not the real task]
1356
+ `+ge.user},{role:"assistant",content:ge.assistant+`
1357
+ [END EXAMPLE \u2014 wait for the real user request below]`},...S.slice(1)])}if(Gt(S,at()).percentage>=65){let{messages:ye,tokensRemoved:Se}=nn(S,at());Se>0&&(S=ye,console.log(`${h.dim} [pre-flight compress \u2014 ${Se} tokens freed, now ${Math.round(Gt(S,at()).percentage)}% used]${h.reset}`))}let Ee=0,W=0,Z=0,he=0,Ce=0,We=9,xe=0,be=new Set,$=(()=>{let ge=L.find(ye=>ye.role==="user");return typeof ge?.content=="string"?ge.content:""})(),I=/set_reminder|google.?auth|cron:|api\.log|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($),H=0;if(!nt){let ge=L.filter(Se=>Se.role==="user"||Se.role==="tool").map(Se=>typeof Se.content=="string"?Se.content:"").join(`
1358
+ `),ye=Mc(ge);ye&&(nt=!0,_t=ye.slice(0,120),j(`${h.yellow} \u26A1 Root cause in briefing: ${_t} \u2014 fix phase active from start (read budget: 3)${h.reset}`))}!nt&&!Dt&&/\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($)&&(Dt=!0,j(`${h.cyan} \u26A1 Creation task detected \u2014 tight investigation cap (4 pre-edit, 2 post-edit)${h.reset}`)),L.length<=1&&!s.skipPhaseRouting&&(_e=mE(),_e&&(no=hE($)?.id||"coding",Le="plan",gn=Dc("plan",no),ta=0,to=0,On=0,process.stdout.isTTY&&console.log(`${h.dim} \u21B3 Phase routing: plan(${gn||"default"}) \u2192 implement \u2192 verify${h.reset}`),j(`${h.cyan} \u26A1 Phase routing enabled \u2014 plan phase with ${gn||"default model"} (category: ${no})${h.reset}`)));let N=0,q=new Map,x=new Set,Y=new Set,ke=new Set,pe=0,lt=0,io=0,gs=0,Oe=Date.now(),vy=new nE(WE),Ey=lr,He=s.skillLoop?10:1,Ty=3*He,Ry=5*He,au=Vc,Cy=5*He,Ay=8*He,Oy=ay,Ny=(_e?6:4)*He,My=(_e?10:7)*He,ia=Wi,Py=(_e?5:3)*He,fr=(_e?8:5)*He,Ly=ly,Iy=(_e?4:3)*He,Dy=(_e?6:4)*He,jy=3*He,qy=4*He,ys=mn,Fy=(_e?6:4)*He,By=(_e?10:8)*He,ws=(_e?12:10)*He,Uy=25,Nn=0,Wy=10*He,Hy=15*He,Mn=0,lu=5*He,Pn=0,Yy=2*He,Gy=3,aa=0,ao=10,zy=16,cu=s.skillLoop?999:n.investigationCap,uu=async()=>{let{hasPendingOrCompletedJobs:ge,getPendingJobSummary:ye}=Fs();if(ge()){if(ye()){let Se=Date.now()+45e3;for(process.stderr.write(`${h.cyan} \u23F3 Waiting for background agents to finish\u2026${h.reset}
1359
+ `);ye()&&Date.now()<Se;)await new Promise(Ve=>setTimeout(Ve,500).unref()),Fi(L,S)}Fi(L,S),L.length>0&&Ae(L)}},la=typeof t=="string"?t.trim():"",du=la.length>0&&/^\s*(analyze|analyse|analysiere|explain|erkläre|describe|beschreib|review|audit|summari[sz]e|zusammenfass|list|liste|what is|what does|wie funktioniert|wie geht|how does|show me|zeig|show the|show all|tell me about|erzähl)/i.test(la)&&!/\b(fix|bug|crash|error|implement|add|create|change|update|refactor|rewrite|broken|fail|patch|migrate|port|build|edit|write|delete|remove|install|setup|deploy|run)\b/i.test(la),qe,bt=s.maxIterations||(_e?cs(Le):qc);du&&(bt=Math.min(bt,4),j(`${h.dim} \u21B3 Analysis-only prompt detected \u2014 iter cap=${bt}${h.reset}`));let ca=0,fu=3,ua=!1,pr=0;e:for(;;){for(ua=!1,qe=0;qe<bt&&!Bi()?.aborted;qe++){Fi(L,S);{let w=at(),y=Gt(S,w),K=N===0?65:78;if(y.percentage>=K){if(x.size>0||_e&&Le!=="plan"){let ee=lE(L,{filesModified:x,currentPhase:_e?Le:null});if(ee){let U=S.findIndex(C=>C._progressSnapshot);U!==-1&&S.splice(U,1);let ae=S.findIndex(C=>C.role==="system");S.splice(ae+1,0,ee)}}let{messages:T,tokensRemoved:M}=nn(S,w,N===0);if(M>0&&(S=T,M>50&&console.log(`${h.dim} [auto-compressed \u2014 ~${M} tokens freed, now ${Math.round(Gt(S,w).percentage)}%]${h.reset}`),Dt&&x.size>=3)){let ee=[...x].map(ae=>ae.split("/").pop()).slice(0,10).join(", "),U={role:"user",content:`[FRAMEWORK \u2014 context compressed] Task is IN PROGRESS. Already created ${x.size} files: ${ee}. DO NOT restart or re-investigate what was already done. Continue from where you left off.`};S.push(U)}}}if(Tt&&!nt&&nr<2){nr++;let w={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."};S.push(w),L.push(w),j(`${h.yellow} \u26A0 Pre-call SSH-blocked nudge #${nr} injected \u2014 model told to synthesize${h.reset}`)}Tt||(nr=0);let ye=!0;N>0&&CE();let Se=null;if(c&&c.isActive())c._paused&&c.resume();else if(!c){let w,y=AE();if(y&&y.total>1){let M=y.description.length>40?y.description.slice(0,37)+"\u2026":y.description;w=`Plan step ${y.current}/${y.total}: ${M}`}else w=N>0?`${Sc()} (step ${N+1})`:Sc();let{getPendingJobSummary:K}=Fs(),T=K();T&&(w+=` [${T}]`),Se=new Zs(w),Se.start()}let Ve=!0,ct="",yn=!1,ze=new OE,Rt,da=Date.now(),hr=!1,fa=new AbortController,pu=setInterval(()=>{let w=Date.now()-da;if(w>=Oc)ze._clearCursorLine(),j(`${h.yellow} \u26A0 Stream stale for ${Math.round(w/1e3)}s \u2014 aborting and retrying${h.reset}`),fa.abort();else if(w>=zg&&!hr){hr=!0,ze._clearCursorLine();let y=Qi.fast?.[Qs()],K=Z>0?` (retry ${Z+1}/${ji})`:"",T=Math.round((Oc-w)/1e3);j(`${h.yellow} \u26A0 No tokens received for ${Math.round(w/1e3)}s \u2014 waiting...${K}${h.reset}`),y&&y!==Xt()?console.log(`${h.dim} \u{1F4A1} Will auto-switch to ${y} in ~${T}s if no tokens arrive${h.reset}`):console.log(`${h.dim} \u{1F4A1} Ctrl+C to abort \xB7 auto-abort in ~${T}s${h.reset}`)}},5e3),Ct="",rn=null;try{let w=oy(at()),y=new Set(["read_file","list_directory","search_files","glob","grep","git_status","git_diff","git_log","git_show","ssh_exec"]),K=new Set(["read_file","list_directory","glob","grep","bash","git_status","git_diff","git_log","ssh_exec"]),T;rr()?T=w.filter(U=>Zg.has(U.function.name)):_e&&Le==="plan"?T=w.filter(U=>y.has(U.function.name)):_e&&Le==="verify"?T=w.filter(U=>K.has(U.function.name)):T=w;let M=Bi(),ee=new AbortController;M&&M.addEventListener("abort",()=>ee.abort(),{once:!0}),fa.signal.addEventListener("abort",()=>ee.abort(),{once:!0}),Rt=await jg(S,T,{signal:ee.signal,...gn?{model:gn}:{},onThinkingToken:()=>{da=Date.now(),hr=!1,on?.onThinkingToken&&on.onThinkingToken()},onToken:U=>{if(da=Date.now(),hr=!1,on?.onToken){on.onToken(U),ct+=U;return}if(ct+=U,!yn&&ct.length>400&&ct.length%250<U.length+1){let ae=jc(ct,3);ae.truncated&&(yn=!0,ze._clearCursorLine?.(),j(`${h.yellow} \u26A0 LLM stream loop detected (${ae.repeatCount}\xD7 repeated) \u2014 suppressing display${h.reset}`))}yn||(Ct+=U,process.stdout.isTTY?rn||(rn=setTimeout(()=>{Ct&&ze&&ze.push(Ct),Ct="",rn=null},50)):(ze.push(Ct),Ct=""),Ve&&(c&&!c._paused?c.pause():Se&&Se.stop(),ye||(ye=!0),ze.startCursor(),Ve=!1))}})}catch(w){if(clearInterval(pu),rn&&(clearTimeout(rn),rn=null),Ct&&ze&&(ze.push(Ct),Ct=""),c&&!c._paused&&c.pause(),Se&&Se.stop(),ze.stopCursor(),fa.signal.aborted&&!Bi()?.aborted){if(Z++,Z>ji){if(he<1){he++,Js("Stale retries exhausted \u2014 last-resort force-compress...",h.yellow);let ae=at(),{messages:C,tokensRemoved:D}=nn(S,ae);S=C,D>50&&j(`${h.dim} [force-compressed \u2014 ~${D} tokens freed]${h.reset}`),Z=0,qe--;continue}c&&(c.stop(),c=null);let U=await RT();if(U.action==="quit"){l(null),Ne(N,q,x,Y,Oe),Ae(L);break}U.action==="switch"&&(vc(`${U.provider}:${U.model}`),console.log(`${h.green} \u2713 Switched to ${U.provider}:${U.model}${h.reset}`)),Z=0,qe--;continue}let M=Z===1?3e3:5e3;if(Z>=1&&xe<1){xe++,Js(`Stale retry ${Z}/${ji} \u2014 force-compressing before retry...`,h.yellow);let U=at(),{messages:ae,tokensRemoved:C}=nn(S,U,!0);if(S=ae,C>0&&C>50&&j(`${h.dim} [force-compressed \u2014 ~${C} tokens freed]${h.reset}`),lT){let D=Qi.fast?.[Qs()];D&&D!==Xt()&&(vc(`${Qs()}:${D}`),console.log(`${h.cyan} \u26A1 Auto-switched to ${D} to avoid further stale timeouts${h.reset}`),console.log(`${h.dim} (disable with NEX_STALE_AUTO_SWITCH=0)${h.reset}`))}}else j(`${h.yellow} \u26A0 Stale retry ${Z}/${ji} \u2014 retrying in ${M/1e3}s...${h.reset}`);let ee=new Zs(`Waiting ${M/1e3}s before retry...`);ee.start(),await new Promise(U=>setTimeout(U,M)),ee.stop(),qe--;continue}if(w.name==="AbortError"||w.name==="CanceledError"||w.message?.includes("canceled")||w.message?.includes("aborted")){c&&(c.stop(),c=null),l(null),Ne(N,q,x,Y,Oe),Ae(L);break}let y=w.message;if(w.code==="ECONNREFUSED"||w.message.includes("ECONNREFUSED"))y="Connection refused \u2014 please check your internet connection or API endpoint";else if(w.code==="ENOTFOUND"||w.message.includes("ENOTFOUND"))y="Network error \u2014 could not reach the API server. Please check your connection";else if(w.code==="ETIMEDOUT"||w.message.includes("timeout"))y="Request timed out \u2014 the API server took too long to respond. Please try again";else if(w.message.includes("401")||w.message.includes("Unauthorized"))y="Authentication failed \u2014 please check your API key in the .env file";else if(w.message.includes("403")||w.message.includes("Forbidden"))y="Access denied \u2014 your API key may not have permission for this model";else if(w.message.includes("404")){let M=Xt?Xt():"unknown",ee=C=>C.includes(":")&&C.split(":")[0].match(/^[a-z]+$/)&&!C.split(":")[1].includes(":")?C.split(":").slice(1).join(":"):C;be.add(ee(M));let ae=(()=>{let C=[];process.env.NEX_FALLBACK_MODEL&&C.push(process.env.NEX_FALLBACK_MODEL);try{let{getModelForCategory:D}=ss(),F=["agentic","coding","plan","verify","sysadmin","data","frontend"];for(let V of F){let X=D(V);X&&!C.includes(X)&&C.push(X)}}catch{}return C.filter(D=>!be.has(ee(D)))})()[0];if(ae){console.log(`${h.yellow} \u26A0 Model ${M} unavailable (404) \u2014 switching to ${ae}${h.reset}`),vc(ae),Dg(ae),qe--;continue}y=`Model not found (404): ${M} \u2014 no fallback available. Set NEX_FALLBACK_MODEL or run /models to list available models`,console.log(`${h.red} \u2717 ${y}${h.reset}`),c&&(c.stop(),c=null),l(null),Ne(N,q,x,Y,Oe),Ae(L);break}else if(w.message.includes("400")){if(he<3&&Ce<We){he++,Ce++;let M=N===0&&he===1,ee=M||he===3||xe>0;if(M){he=3;let D=w.message.replace(/^API Error(\s*\[HTTP \d+\])?:\s*/i,"").slice(0,150);Js(`Bad request (400) \u2014 ${D||"system prompt too large"}, compressing...`,h.yellow)}else Js(ee?`Bad request (400) \u2014 nuclear compression (attempt ${he}/3, dropping history)...`:`Bad request (400) \u2014 force-compressing and retrying... (attempt ${he}/3)`,h.yellow);let U=at(),{messages:ae,tokensRemoved:C}=nn(S,U,ee);S=ae,C>50&&j(`${h.dim} [force-compressed \u2014 ~${C} tokens freed]${h.reset}`),qe--;continue}{let M=S.find(F=>F.role==="system"),ee=S.find(F=>F.role==="user"&&!String(F.content).startsWith("[SYSTEM")&&!String(F.content).startsWith("BLOCKED:")),U=[M,ee].filter(Boolean),{getUsage:ae}=en(),C=en().estimateMessagesTokens(U),D=en().estimateMessagesTokens(S);if(C<D){let F=[],V=L.filter(te=>te.role==="assistant"&&typeof te.content=="string"&&te.content.trim().length>30).slice(-5).map(te=>te.content.trim().slice(0,300).replace(/\n+/g," "));V.length>0&&F.push(`Key findings:
1360
+ `+V.map(te=>`- ${te}`).join(`
1361
+ `));let X=L.filter(te=>te.role==="tool"&&typeof te.content=="string"&&!te.content.startsWith("BLOCKED:")&&te.content.trim().length>10).slice(-5).map(te=>te.content.trim().split(`
1345
1362
  `).slice(0,8).join(`
1346
- `).slice(0,500));if(J.length>0&&F.push(`Tool results summary:
1347
- `+J.map(ee=>`- ${ee}`).join(`
1348
- `)),E.size>0){let ee=[...E].map(xe=>xe.split("/").slice(-2).join("/")).join(", ");F.unshift(`Already modified: ${ee} \u2014 use edit_file to add missing pieces only, DO NOT use write_file on these files.`)}if(S.size>0){let ee=[...S].map(xe=>xe.split("/").slice(-2).join("/")).join(", ");F.push(`Files already investigated: ${ee}`)}let re=require("os").tmpdir()+"/nex-session-checkpoint.json";try{require("fs").writeFileSync(re,JSON.stringify({filesWritten:[...E].map(ee=>ee.split("/").slice(-2).join("/")),filesRead:[...S].map(ee=>ee.split("/").slice(-2).join("/")),isCreationTask:Dt,wipeNumber:Jo+1,timestamp:Date.now()},null,2)),F.push(`Session checkpoint: ${re} \u2014 read it for exact file list`)}catch{}let fe=0;{let xe=((typeof Q?.content=="string"?Q.content:Array.isArray(Q?.content)?Q.content.filter(Je=>Je.type==="text").map(Je=>Je.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(Je=>Je.trim()).filter(Boolean),Ee=[...E],gt=xe.filter(Je=>!Ee.some(la=>la.endsWith(Je)||Je.endsWith(la.split("/").pop())));fe=gt.length;let Ve=[...j].reverse().find(Je=>Je.role==="tool"&&typeof Je.content=="string"&&!Je.content.startsWith("BLOCKED:")&&Je.content.length>5),Ot={completed:Ee.map(Je=>Je.split("/").slice(-2).join("/")),pending:gt.length>0?gt:Ee.length===0?["(task files not yet identified)"]:[],lastEdit:Ve?Ve.content.trim().slice(0,120):null};(Ot.completed.length>0||Ot.pending.length>0)&&F.unshift(`Work manifest:
1349
- ${JSON.stringify(Ot,null,2)}`)}if(F.length>0){let ee={role:"user",content:`[SYSTEM: Findings from investigation before context wipe]
1363
+ `).slice(0,500));if(X.length>0&&F.push(`Tool results summary:
1364
+ `+X.map(te=>`- ${te}`).join(`
1365
+ `)),x.size>0){let te=[...x].map($e=>$e.split("/").slice(-2).join("/")).join(", ");F.unshift(`Already modified: ${te} \u2014 use edit_file to add missing pieces only, DO NOT use write_file on these files.`)}if(Y.size>0){let te=[...Y].map($e=>$e.split("/").slice(-2).join("/")).join(", ");F.push(`Files already investigated: ${te}`)}let re=require("os").tmpdir()+"/nex-session-checkpoint.json";try{require("fs").writeFileSync(re,JSON.stringify({filesWritten:[...x].map(te=>te.split("/").slice(-2).join("/")),filesRead:[...Y].map(te=>te.split("/").slice(-2).join("/")),isCreationTask:Dt,wipeNumber:tr+1,timestamp:Date.now()},null,2)),F.push(`Session checkpoint: ${re} \u2014 read it for exact file list`)}catch{}let fe=0;{let $e=((typeof ee?.content=="string"?ee.content:Array.isArray(ee?.content)?ee.content.filter(Ze=>Ze.type==="text").map(Ze=>Ze.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(Ze=>Ze.trim()).filter(Boolean),Te=[...x],gt=$e.filter(Ze=>!Te.some(ha=>ha.endsWith(Ze)||Ze.endsWith(ha.split("/").pop())));fe=gt.length;let Je=[...L].reverse().find(Ze=>Ze.role==="tool"&&typeof Ze.content=="string"&&!Ze.content.startsWith("BLOCKED:")&&Ze.content.length>5),Ot={completed:Te.map(Ze=>Ze.split("/").slice(-2).join("/")),pending:gt.length>0?gt:Te.length===0?["(task files not yet identified)"]:[],lastEdit:Je?Je.content.trim().slice(0,120):null};(Ot.completed.length>0||Ot.pending.length>0)&&F.unshift(`Work manifest:
1366
+ ${JSON.stringify(Ot,null,2)}`)}if(F.length>0){let te={role:"user",content:`[SYSTEM: Findings from investigation before context wipe]
1350
1367
  ${F.join(`
1351
1368
  `)}
1352
- Continue implementing the fixes based on these findings.`};U.push(ee)}if(Jo>=3){let ee=E.size>0?`
1353
- Files modified so far: ${[...E].map(xe=>xe.split("/").slice(-1)[0]).join(", ")}`:"";D(`${m.red} \u2717 Super-nuclear limit reached (3\xD7) \u2014 aborting to prevent runaway context loop${m.reset}`),console.log(`${m.yellow} \u{1F4A1} Task may exceed model context. Try /clear and break it into smaller steps.${ee?m.dim+ee:""}${m.reset}`),c&&(c.stop(),c=null),l(null),Ne(R,W,E,S,Ae,{suppressHint:!0}),Oe(j);break}k=U,Jo++,us=10+Math.min(fe*3,7),Ic=!0,Ui=E.size,Wi=!1,It=0,I=0;for(let[ee,xe]of mn){let Ee=xe?.count??xe??0;Ec(mn,ee,Ee>=2?Ee:1)}for(let[ee]of An)sn(mn,ee)<2&&An.delete(ee);Lt.clear(),ps.clear(),Dt&&Kt>0&&(qt=!0,D(`${m.cyan} \u26A1 Post-wipe creation guard: cap pre-fired (${Kt} edits already made)${m.reset}`));for(let[ee]of Di)Ec(Di,ee,lr-1);if(Ks(`Super-nuclear compression \u2014 dropped all history, keeping original task only (${q-P} tokens freed)`,m.yellow),Jo>=1){let ee=[...mn.entries()].filter(([,Ve])=>Ve>=gs).map(([Ve])=>Ve.split("/").slice(-1)[0]),xe=ee.length>0?`
1369
+ Continue implementing the fixes based on these findings.`};U.push(te)}if(tr>=3){let te=x.size>0?`
1370
+ Files modified so far: ${[...x].map($e=>$e.split("/").slice(-1)[0]).join(", ")}`:"";j(`${h.red} \u2717 Super-nuclear limit reached (3\xD7) \u2014 aborting to prevent runaway context loop${h.reset}`),console.log(`${h.yellow} \u{1F4A1} Task may exceed model context. Try /clear and break it into smaller steps.${te?h.dim+te:""}${h.reset}`),c&&(c.stop(),c=null),l(null),Ne(N,q,x,Y,Oe,{suppressHint:!0}),Ae(L);break}S=U,tr++,ds=10+Math.min(fe*3,7),Hc=!0,Ki=x.size,Xi=!1,It=0,H=0;for(let[te,$e]of mn){let Te=$e?.count??$e??0;Pc(mn,te,Te>=2?Te:1)}for(let[te]of Cn)sn(mn,te)<2&&Cn.delete(te);Lt.clear(),hs.clear(),Dt&&Kt>0&&(qt=!0,j(`${h.cyan} \u26A1 Post-wipe creation guard: cap pre-fired (${Kt} edits already made)${h.reset}`));for(let[te]of Wi)Pc(Wi,te,fr-1);if(Js(`Super-nuclear compression \u2014 dropped all history, keeping original task only (${D-C} tokens freed)`,h.yellow),tr>=1){let te=[...mn.entries()].filter(([,Je])=>Je>=ws).map(([Je])=>Je.split("/").slice(-1)[0]),$e=te.length>0?`
1354
1371
 
1355
- Files already at read cap \u2014 use grep_search instead: ${ee.join(", ")}`:"",gt={role:"user",content:Tt&&!tt?"[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.${xe}`};j.push(gt),k.push(gt)}pe=0,He--;continue}}y="Context too large to compress \u2014 use /clear to start fresh"}else w.message.includes("500")||w.message.includes("502")||w.message.includes("503")||w.message.includes("504")?y="API server error \u2014 the provider is experiencing issues. Please try again in a moment":(w.message.includes("fetch failed")||w.message.includes("fetch"))&&(y="Network request failed \u2014 please check your internet connection");if(console.log(`${m.red} \u2717 ${y}${m.reset}`),w.message.includes("429")){if(ve++,ve>bc){console.log(`${m.red} Rate limit: max retries (${bc}) exceeded. Try again later or use /budget to check your limits.${m.reset}`),c&&(c.stop(),c=null),l(null),Ne(R,W,E,S,Ae),Oe(j);break e}let L=Math.min(1e4*Math.pow(2,ve-1),12e4),Q=new Xs(`Rate limit \u2014 waiting ${Math.round(L/1e3)}s (retry ${ve}/${bc})`);Q.start(),await new Promise(U=>setTimeout(U,L)),Q.stop();continue}let z=process.env.NEX_PHASE_ROUTING!=="0"&&(()=>{try{return Ze().getActiveProviderName()==="ollama"}catch{return!1}})();if(w.message.includes("socket disconnected")||w.message.includes("TLS")||w.message.includes("ECONNRESET")||w.message.includes("ECONNABORTED")||w.message.includes("ETIMEDOUT")||z&&(w.message.includes("500")||w.message.includes("502")||w.message.includes("503")||w.message.includes("504")||w.message.includes("401")||w.message.includes("Unauthorized"))||w.code==="ECONNRESET"||w.code==="ECONNABORTED"){if(H++,H>xc){console.log(`${m.red} Network error: max retries (${xc}) exceeded. Check your connection and try again.
1356
- Use /undo to revert changes made during this session.${m.reset}`),c&&(c.stop(),c=null),l(null),Ne(R,W,E,S,Ae),Oe(j);break e}let L=Math.min(2e3*Math.pow(2,H-1),3e4),Q=new Xs(`API temporarily unavailable \u2014 retrying in ${Math.round(L/1e3)}s (${H}/${xc}). Your changes are safe.`);Q.start(),await new Promise(U=>setTimeout(U,L)),Q.stop(),He--;continue}c&&(c.stop(),c=null),l(null),Ne(R,W,E,S,Ae),Oe(j);break}if(clearInterval(su),ve=0,H=0,lt&&(c&&!c._paused&&c.pause(),Ce&&Ce.stop()),rn&&(clearTimeout(rn),rn=null),Ct&&ze&&(ze.push(Ct),Ct=""),ct&&ze.flush(),H=0,X=0,Rt&&Rt.usage){let w=Rt.usage.prompt_tokens||0,y=Rt.usage.completion_tokens||0;Cg(Vs(),Xt(),w,y),u+=w+y,c&&c.setStats({tokens:u})}else if(Rt&&!Rt.usage){let w=k.map(C=>typeof C.content=="string"?C.content:Array.isArray(C.content)?C.content.map(L=>typeof L=="string"?L:L.text||"").join(""):"").join(" "),y=Og(w),z=Og(Rt.content||ct||"");Cg(Vs(),Xt(),y,z),u+=y+z,c&&c.setStats({tokens:u})}let{content:ou,tool_calls:an}=Rt,dr=Ac(ou||""),ru=dr.truncated?dr.text:ou;dr.truncated&&D(`${m.yellow} \u26A0 LLM output loop detected (${dr.repeatCount}\xD7 repeated paragraph) \u2014 response truncated${m.reset}`);let fr=OE(ru||""),At=fr.truncated?fr.text:ru;fr.truncated&&D(`${m.yellow} \u26A0 LLM output loop detected (${fr.repeatCount}\xD7 repeated window) \u2014 response truncated${m.reset}`);let oo={role:"assistant",content:At||""};if(an&&an.length>0&&(oo.tool_calls=an),j.push(oo),k.push(oo),tu&&(At||"").trim().length>1500&&E.size===0&&yn===0){D(`${m.green} \u2713 Analysis-only early exit: ${(At||"").length} chars produced, no file changes${m.reset}`),oo.tool_calls&&delete oo.tool_calls,Ne(R,W,E,S,Ae),Oe(j);break e}if(!tt&&At&&an&&an.length>0){let w=vc(At);if(w){tt=!0,_t=w.slice(0,120),jt=0,qt=!1,zt=0,D(`${m.yellow} \u26A1 Root cause in model analysis: ${_t} \u2014 fix phase (read budget: 3)${m.reset}`);let y={role:"user",content:`[SYSTEM] Root cause identified: ${_t}. Read only the file that needs fixing, then edit it. Do not read other files.`};j.push(y),k.push(y)}}if(!an||an.length===0){let w=(At||"").trim().length>0||ct.trim().length>0,y=!1;if(Tt&&w&&(Pi>=2?D(`${m.yellow} \u26A0 SSH permanently blocked after ${Pi} storm warnings \u2014 no further SSH calls allowed${m.reset}`):(Tt=!1,It=so-4,y=!0)),y&&w){let C=(At||"").trim();if(C.endsWith("?")||/\b(Wo |Bitte |Kannst du|Soll ich)\b/.test(C.slice(-200))){let Q={role:"user",content:"[SYSTEM] Continue. Do not ask questions \u2014 implement the fix yourself using SSH. The server is at 94.130.37.43."};k.push(Q),j.push(Q);continue}}if(!w&&R>0&&He<Oc-1){let C={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."};k.push(C),j.push(C);continue}let z=/keine.*Tool|can.?t use.*tool|Tool.?Budget|nicht.*zugreifen|cannot.*access|no.*tool.*access|keine.*Werkzeug|da ich keine.*kann/i;if(w&&He<3&&z.test((At||"").slice(0,600)))if(Ic&&us<=0||Tt){D(`${m.yellow} \u26A0 Tool avoidance (constrained context) \u2014 telling model to ask user${m.reset}`);let L={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."};k.push(L),j.push(L);continue}else{D(`${m.yellow} \u26A0 Tool avoidance detected \u2014 nudging model to use tools${m.reset}`);let L={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."};k.push(L),j.push(L);continue}if(s.skillLoop&&w&&R>3&&cr<5){let C=(At||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(C.slice(-600))){cr=(cr||0)+1,D(`${m.yellow} \u26A0 Skill loop: model tried to stop \u2014 continuation nudge #${cr}${m.reset}`);let Q={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."};k.push(Q),j.push(Q);continue}}if(er()&&!s.skillLoop&&!ye&&(E.size>0||yn>0)&&w&&R>=2){D(`${m.green} \u2713 Headless early exit: ${E.size} file(s) modified (+ ${yn} bash writes), text response received${m.reset}`),Ne(R,W,E,S,Ae),Oe(j);break e}if(ye&&Le==="plan"&&Nn>=2){D(`${m.cyan} \u21B3 Plan phase: ${Nn} consecutive blocks \u2014 auto-advancing to implement${m.reset}`),Nn=0;let C=Ko("implement","[auto-advance: task only requires direct action]");if(C){j.push(C),k.push(C),He=0,bt=ls("implement");continue}}if(ye&&w){let C=(At||ct||"").trim();if(Le==="plan"){let L=/\b(no match(es)?|not found|couldn'?t find|does not exist|no results|nothing found|no files|keine (Ergebnisse|Treffer|Übereinstimmung|Funde|passenden)|nicht gefunden|nichts gefunden)\b/i,Q=Qg(C,mn).length===0,U=nr.size>0,ue=sr.size>0,P=C.length>1500;if(er()&&Q&&!U&&!ue&&!P&&L.test(C)){D(`${m.yellow} \u26A0 Plan phase: nothing actionable found \u2014 exiting gracefully${m.reset}`),process.stdout.isTTY&&process.stderr.write(`${m.yellow} \u26A0 Could not find the target in this project. The plan phase found no actionable items.${m.reset}
1357
- `),Ne(R,W,E,S,Ae),Oe(j);break e}let q=Ko("implement",C);if(q){j.push(q),k.push(q),He=0,bt=ls("implement");continue}}else if(Le==="implement"&&(E.size>0||yn>0)){let L=j.find(ue=>ue.role==="user"),Q=typeof L?.content=="string"?L.content:"",U=Ko("verify",C,E,Q);if(U){j.push(U),k.push(U),He=0,bt=Math.min(ls("verify")+Math.max(0,(E.size-2)*2),20);continue}}else if(Le==="verify"){let Q=/\bFAIL\b|test.*fail|error|broken|missing|incorrect/i.test(C.slice(0,500));if(Q&&Zs<3){Zs++;let U={role:"user",content:`[PHASE: RE-IMPLEMENTATION] Verification found issues:
1358
- ${C.slice(0,400)}
1372
+ Files already at read cap \u2014 use grep_search instead: ${te.join(", ")}`:"",gt={role:"user",content:Tt&&!nt?"[SYSTEM] Context was compressed. SSH is currently unavailable \u2014 do not read more local files. Summarize what you found and ask the user for the server output you need.":`[SYSTEM] Context was compressed. Use the findings above to implement your fix. If you need to re-read a file, use line_start/line_end for the specific section.${$e}`};L.push(gt),S.push(gt)}he=0,qe--;continue}}y="Context too large to compress \u2014 use /clear to start fresh"}else w.message.includes("500")||w.message.includes("502")||w.message.includes("503")||w.message.includes("504")?y="API server error \u2014 the provider is experiencing issues. Please try again in a moment":(w.message.includes("fetch failed")||w.message.includes("fetch"))&&(y="Network request failed \u2014 please check your internet connection");if(console.log(`${h.red} \u2717 ${y}${h.reset}`),w.message.includes("429")){if(Ee++,Ee>Cc){console.log(`${h.red} Rate limit: max retries (${Cc}) exceeded. Try again later or use /budget to check your limits.${h.reset}`),c&&(c.stop(),c=null),l(null),Ne(N,q,x,Y,Oe),Ae(L);break e}let M=Math.min(1e4*Math.pow(2,Ee-1),12e4),ee=new Zs(`Rate limit \u2014 waiting ${Math.round(M/1e3)}s (retry ${Ee}/${Cc})`);ee.start(),await new Promise(U=>setTimeout(U,M)),ee.stop();continue}let K=process.env.NEX_PHASE_ROUTING!=="0"&&(()=>{try{return Qe().getActiveProviderName()==="ollama"}catch{return!1}})();if(w.message.includes("socket disconnected")||w.message.includes("TLS")||w.message.includes("ECONNRESET")||w.message.includes("ECONNABORTED")||w.message.includes("ETIMEDOUT")||K&&(w.message.includes("500")||w.message.includes("502")||w.message.includes("503")||w.message.includes("504")||w.message.includes("401")||w.message.includes("Unauthorized"))||w.code==="ECONNRESET"||w.code==="ECONNABORTED"){if(W++,W>Ac){console.log(`${h.red} Network error: max retries (${Ac}) exceeded. Check your connection and try again.
1373
+ Use /undo to revert changes made during this session.${h.reset}`),c&&(c.stop(),c=null),l(null),Ne(N,q,x,Y,Oe),Ae(L);break e}let M=Math.min(2e3*Math.pow(2,W-1),3e4),ee=new Zs(`API temporarily unavailable \u2014 retrying in ${Math.round(M/1e3)}s (${W}/${Ac}). Your changes are safe.`);ee.start(),await new Promise(U=>setTimeout(U,M)),ee.stop(),qe--;continue}c&&(c.stop(),c=null),l(null),Ne(N,q,x,Y,Oe),Ae(L);break}if(clearInterval(pu),Ee=0,W=0,Ve&&(c&&!c._paused&&c.pause(),Se&&Se.stop()),rn&&(clearTimeout(rn),rn=null),Ct&&ze&&(ze.push(Ct),Ct=""),ct&&ze.flush(),W=0,Z=0,Rt&&Rt.usage){let w=Rt.usage.prompt_tokens||0,y=Rt.usage.completion_tokens||0;Fg(Qs(),Xt(),w,y),u+=w+y,c&&c.setStats({tokens:u})}else if(Rt&&!Rt.usage){let w=S.map(T=>typeof T.content=="string"?T.content:Array.isArray(T.content)?T.content.map(M=>typeof M=="string"?M:M.text||"").join(""):"").join(" "),y=Ug(w),K=Ug(Rt.content||ct||"");Fg(Qs(),Xt(),y,K),u+=y+K,c&&c.setStats({tokens:u})}let{content:hu,tool_calls:an}=Rt,mr=jc(hu||""),mu=mr.truncated?mr.text:hu;mr.truncated&&j(`${h.yellow} \u26A0 LLM output loop detected (${mr.repeatCount}\xD7 repeated paragraph) \u2014 response truncated${h.reset}`);let gr=XE(mu||""),At=gr.truncated?gr.text:mu;gr.truncated&&j(`${h.yellow} \u26A0 LLM output loop detected (${gr.repeatCount}\xD7 repeated window) \u2014 response truncated${h.reset}`);let lo={role:"assistant",content:At||""};if(an&&an.length>0&&(lo.tool_calls=an),L.push(lo),S.push(lo),du&&(At||"").trim().length>1500&&x.size===0&&gs===0){j(`${h.green} \u2713 Analysis-only early exit: ${(At||"").length} chars produced, no file changes${h.reset}`),lo.tool_calls&&delete lo.tool_calls,Ne(N,q,x,Y,Oe),Ae(L);break e}if(!nt&&At&&an&&an.length>0){let w=Mc(At);if(w){nt=!0,_t=w.slice(0,120),jt=0,qt=!1,zt=0,j(`${h.yellow} \u26A1 Root cause in model analysis: ${_t} \u2014 fix phase (read budget: 3)${h.reset}`);let y={role:"user",content:`[SYSTEM] Root cause identified: ${_t}. Read only the file that needs fixing, then edit it. Do not read other files.`};L.push(y),S.push(y)}}if(!an||an.length===0){let w=(At||"").trim().length>0||ct.trim().length>0,y=!1;if(Tt&&w&&(qi>=2?j(`${h.yellow} \u26A0 SSH permanently blocked after ${qi} storm warnings \u2014 no further SSH calls allowed${h.reset}`):(Tt=!1,It=ao-4,y=!0)),y&&w){let T=(At||"").trim();if(T.endsWith("?")||/\b(Wo |Bitte |Kannst du|Soll ich)\b/.test(T.slice(-200))){let ee={role:"user",content:"[SYSTEM] Continue. Do not ask questions \u2014 implement the fix yourself using SSH. The server is at 94.130.37.43."};S.push(ee),L.push(ee);continue}}if(!w&&N>0&&qe<qc-1){let T={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."};S.push(T),L.push(T);continue}let K=/keine.*Tool|can.?t use.*tool|Tool.?Budget|nicht.*zugreifen|cannot.*access|no.*tool.*access|keine.*Werkzeug|da ich keine.*kann/i;if(w&&qe<3&&K.test((At||"").slice(0,600)))if(Hc&&ds<=0||Tt){j(`${h.yellow} \u26A0 Tool avoidance (constrained context) \u2014 telling model to ask user${h.reset}`);let M={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."};S.push(M),L.push(M);continue}else{j(`${h.yellow} \u26A0 Tool avoidance detected \u2014 nudging model to use tools${h.reset}`);let M={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."};S.push(M),L.push(M);continue}if(s.skillLoop&&w&&N>3&&pr<5){let T=(At||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(T.slice(-600))){pr=(pr||0)+1,j(`${h.yellow} \u26A0 Skill loop: model tried to stop \u2014 continuation nudge #${pr}${h.reset}`);let ee={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."};S.push(ee),L.push(ee);continue}}if(or()&&!s.skillLoop&&!_e&&(x.size>0||gs>0)&&w&&N>=2){j(`${h.green} \u2713 Headless early exit: ${x.size} file(s) modified (+ ${gs} bash writes), text response received${h.reset}`),Ne(N,q,x,Y,Oe),Ae(L);break e}if(_e&&Le==="plan"&&On>=2){j(`${h.cyan} \u21B3 Plan phase: ${On} consecutive blocks \u2014 auto-advancing to implement${h.reset}`),On=0;let T=Zo("implement","[auto-advance: task only requires direct action]");if(T){L.push(T),S.push(T),qe=0,bt=cs("implement");continue}}if(_e&&w){let T=(At||ct||"").trim();if(Le==="plan"){let M=/\b(no match(es)?|not found|couldn'?t find|does not exist|no results|nothing found|no files|keine (Ergebnisse|Treffer|Übereinstimmung|Funde|passenden)|nicht gefunden|nichts gefunden)\b/i,ee=cy(T,mn).length===0,U=ir.size>0,ae=ar.size>0,C=T.length>1500;if(or()&&ee&&!U&&!ae&&!C&&M.test(T)){j(`${h.yellow} \u26A0 Plan phase: nothing actionable found \u2014 exiting gracefully${h.reset}`),process.stdout.isTTY&&process.stderr.write(`${h.yellow} \u26A0 Could not find the target in this project. The plan phase found no actionable items.${h.reset}
1374
+ `),Ne(N,q,x,Y,Oe),Ae(L);break e}let D=Zo("implement",T);if(D){L.push(D),S.push(D),qe=0,bt=cs("implement");continue}}else if(Le==="implement"&&(x.size>0||gs>0)){let M=L.find(ae=>ae.role==="user"),ee=typeof M?.content=="string"?M.content:"",U=Zo("verify",T,x,ee);if(U){L.push(U),S.push(U),qe=0,bt=Math.min(cs("verify")+Math.max(0,(x.size-2)*2),20);continue}}else if(Le==="verify"){let ee=/\bFAIL\b|test.*fail|error|broken|missing|incorrect/i.test(T.slice(0,500));if(ee&&to<3){to++;let U={role:"user",content:`[PHASE: RE-IMPLEMENTATION] Verification found issues:
1375
+ ${T.slice(0,400)}
1359
1376
 
1360
- Fix the identified issues. This is attempt ${Zs}/3.`};Le="implement",gn=Cc("implement",Qs),j.push(U),k.push(U),He=0,bt=ls("implement"),D(`${m.yellow} \u21B3 Verify \u2192 implement loop-back #${Zs} (issues found)${m.reset}`);continue}if(D(`${m.green} \u2713 Verification phase complete${Q?" (loop-back exhausted)":" (PASS)"}${m.reset}`),!Q){Ne(R,W,E,S,Ae),Oe(j),Ni(j);break e}}}if(tr()&&w&&R===0)if(qi++,qi>2)D(`${m.yellow} \u26A0 Plan accepted despite no file reads (rejection loop cap reached)${m.reset}`);else{let C={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.).
1377
+ Fix the identified issues. This is attempt ${to}/3.`};Le="implement",gn=Dc("implement",no),L.push(U),S.push(U),qe=0,bt=cs("implement"),j(`${h.yellow} \u21B3 Verify \u2192 implement loop-back #${to} (issues found)${h.reset}`);continue}if(j(`${h.green} \u2713 Verification phase complete${ee?" (loop-back exhausted)":" (PASS)"}${h.reset}`),!ee){Ne(N,q,x,Y,Oe),Ae(L),Di(L);break e}}}if(rr()&&w&&N===0)if(Yi++,Yi>2)j(`${h.yellow} \u26A0 Plan accepted despite no file reads (rejection loop cap reached)${h.reset}`);else{let T={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.).
1361
1378
 
1362
- 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.`};j.push(C),k.push(C),D(`${m.yellow} \u26A0 Plan rejected (${qi}/2): no files read \u2014 forcing investigation${m.reset}`);continue}if(tr()&&w){let C=(At||ct||"").trim();lE(C),YE(C);let L=cE(C);if(L.length>0){let Q=j.find(q=>q.role==="user"),U=typeof Q?.content=="string"?Q.content.slice(0,120):"Task";uE(U,L);let ue=L.length===1?"step":"steps",P=!1;if(process.stdout.isTTY&&process.stdin.isTTY){let{approvePlan:q,startExecution:F,setPlanMode:V}=Ri();process.stdout.write(`
1363
- ${m.cyan}${m.bold}Plan ready${m.reset} ${m.dim}(${L.length} ${ue})${m.reset} ${m.green}[A]${m.reset}${m.dim}pprove${m.reset} ${m.yellow}[E]${m.reset}${m.dim}dit${m.reset} ${m.red}[R]${m.reset}${m.dim}eject${m.reset} ${m.dim}[\u21B5 = approve]:${m.reset} `);let J=process.stdin.isRaw,re=await new Promise(fe=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",ee=>{try{process.stdin.setRawMode(J||!1)}catch{}let xe=ee.toString().toLowerCase()[0]||"\r";fe(xe)})});if(process.stdout.write(`
1364
- `),re==="r")console.log(`${m.red}Plan rejected.${m.reset} Ask follow-up questions to refine.`);else if(re==="e")console.log(`${m.yellow}Type /plan edit to open in editor, or give feedback.${m.reset}`);else if(q()){F(),V(!1),Mc(),console.log(`${m.green}${m.bold}Approved!${m.reset} Executing ${L.length} ${ue}...`);let fe=`[PLAN APPROVED \u2014 EXECUTE NOW]
1379
+ 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.`};L.push(T),S.push(T),j(`${h.yellow} \u26A0 Plan rejected (${Yi}/2): no files read \u2014 forcing investigation${h.reset}`);continue}if(rr()&&w){let T=(At||ct||"").trim();EE(T),cT(T);let M=TE(T);if(M.length>0){let ee=L.find(D=>D.role==="user"),U=typeof ee?.content=="string"?ee.content.slice(0,120):"Task";RE(U,M);let ae=M.length===1?"step":"steps",C=!1;if(process.stdout.isTTY&&process.stdin.isTTY){let{approvePlan:D,startExecution:F,setPlanMode:V}=Mi();process.stdout.write(`
1380
+ ${h.cyan}${h.bold}Plan ready${h.reset} ${h.dim}(${M.length} ${ae})${h.reset} ${h.green}[A]${h.reset}${h.dim}pprove${h.reset} ${h.yellow}[E]${h.reset}${h.dim}dit${h.reset} ${h.red}[R]${h.reset}${h.dim}eject${h.reset} ${h.dim}[\u21B5 = approve]:${h.reset} `);let X=process.stdin.isRaw,re=await new Promise(fe=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",te=>{try{process.stdin.setRawMode(X||!1)}catch{}let $e=te.toString().toLowerCase()[0]||"\r";fe($e)})});if(process.stdout.write(`
1381
+ `),re==="r")console.log(`${h.red}Plan rejected.${h.reset} Ask follow-up questions to refine.`);else if(re==="e")console.log(`${h.yellow}Type /plan edit to open in editor, or give feedback.${h.reset}`);else if(D()){F(),V(!1),Bc(),console.log(`${h.green}${h.bold}Approved!${h.reset} Executing ${M.length} ${ae}...`);let fe=`[PLAN APPROVED \u2014 EXECUTE NOW]
1365
1382
 
1366
1383
  Implement the following plan step by step. All tools are now available.
1367
1384
 
1368
- ${C}`;j.push({role:"user",content:fe}),k.push({role:"user",content:fe}),P=!0}}else console.log(`
1369
- ${m.cyan}${m.bold}Plan ready${m.reset} ${m.dim}(${L.length} ${ue} extracted).${m.reset} Type ${m.cyan}/plan approve${m.reset}${m.dim} to execute, or ${m.reset}${m.cyan}/plan edit${m.reset}${m.dim} to review.${m.reset}`);if(P){c&&(c.stop(),c=null),He--;continue}}else{let Q=!1;if(process.stdout.isTTY&&process.stdin.isTTY){let{approvePlan:U,startExecution:ue,setPlanMode:P}=Ri();process.stdout.write(`
1370
- ${m.cyan}${m.bold}Plan ready.${m.reset} ${m.green}[A]${m.reset}${m.dim}pprove${m.reset} ${m.red}[R]${m.reset}${m.dim}eject${m.reset} ${m.dim}[\u21B5 = approve]:${m.reset} `);let q=process.stdin.isRaw,F=await new Promise(V=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",J=>{try{process.stdin.setRawMode(q||!1)}catch{}V(J.toString().toLowerCase()[0]||"\r")})});if(process.stdout.write(`
1371
- `),F==="r")console.log(`${m.red}Plan rejected.${m.reset} Ask follow-up questions to refine.`);else if(U()){ue(),P(!1),Mc(),console.log(`${m.green}${m.bold}Approved!${m.reset} Executing...`);let J=`[PLAN APPROVED \u2014 EXECUTE NOW]
1385
+ ${T}`;L.push({role:"user",content:fe}),S.push({role:"user",content:fe}),C=!0}}else console.log(`
1386
+ ${h.cyan}${h.bold}Plan ready${h.reset} ${h.dim}(${M.length} ${ae} extracted).${h.reset} Type ${h.cyan}/plan approve${h.reset}${h.dim} to execute, or ${h.reset}${h.cyan}/plan edit${h.reset}${h.dim} to review.${h.reset}`);if(C){c&&(c.stop(),c=null),qe--;continue}}else{let ee=!1;if(process.stdout.isTTY&&process.stdin.isTTY){let{approvePlan:U,startExecution:ae,setPlanMode:C}=Mi();process.stdout.write(`
1387
+ ${h.cyan}${h.bold}Plan ready.${h.reset} ${h.green}[A]${h.reset}${h.dim}pprove${h.reset} ${h.red}[R]${h.reset}${h.dim}eject${h.reset} ${h.dim}[\u21B5 = approve]:${h.reset} `);let D=process.stdin.isRaw,F=await new Promise(V=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",X=>{try{process.stdin.setRawMode(D||!1)}catch{}V(X.toString().toLowerCase()[0]||"\r")})});if(process.stdout.write(`
1388
+ `),F==="r")console.log(`${h.red}Plan rejected.${h.reset} Ask follow-up questions to refine.`);else if(U()){ae(),C(!1),Bc(),console.log(`${h.green}${h.bold}Approved!${h.reset} Executing...`);let X=`[PLAN APPROVED \u2014 EXECUTE NOW]
1372
1389
 
1373
1390
  Implement the following plan step by step. All tools are now available.
1374
1391
 
1375
- ${getPlanContent()||Rt.content}`;j.push({role:"user",content:J}),k.push({role:"user",content:J}),Q=!0}}else console.log(`
1376
- ${m.cyan}${m.bold}Plan ready.${m.reset} ${m.dim}Type ${m.reset}${m.cyan}/plan approve${m.reset}${m.dim} to execute, or ask follow-up questions to refine.${m.reset}`);if(Q){c&&(c.stop(),c=null),He--;continue}}}if(c&&(c.stop(),c=null),l(null),Ne(R,W,E,S,Ae),Dt&&E.size>=3){let C=[...E].map(P=>P.split("/").pop()).slice(0,8).join(", "),L=[...E].some(P=>P.endsWith("package.json")),Q=[...E].some(P=>P.endsWith("requirements.txt")),U=[...E].some(P=>P.endsWith("package-lock.json")||P.endsWith("yarn.lock")||P.endsWith("pnpm-lock.yaml")),ue=L&&!U?"npm install not yet run":Q?"pip install not yet run":null;Qo=`[Previous session created ${E.size} files: ${C}`+(ue?` \u2014 ${ue}`:"")+". Use this context to answer follow-up questions without re-reading files.]"}if(Dt&&!Dc&&R>0){let C=[...E].some(J=>J.endsWith("package.json")),L=[...E].some(J=>J.endsWith("requirements.txt")||J.endsWith("Pipfile")||J.endsWith("pyproject.toml")),Q=[...E].some(J=>J.endsWith("package-lock.json")||J.endsWith("yarn.lock")||J.endsWith("pnpm-lock.yaml")),U=j.flatMap(J=>{let re=Array.isArray(J.tool_calls)?J.tool_calls:[],fe=Array.isArray(J.content)?J.content.filter(ee=>ee?.type==="tool_use"):[];return[...re,...fe]}).filter(J=>{let re=J.function?.name||J.name||"";return re==="bash"||re==="Bash"}).map(J=>{try{let re=J.function?.arguments??J.input??{};return(typeof re=="string"?JSON.parse(re):re)?.command||""}catch{return""}}),ue=U.some(J=>/pip\s+install|python\s+-m\s+venv/.test(J)),P=U.some(J=>/npm\s+install/.test(J)),F=[...E].some(J=>/\/App\.(js|ts|jsx|tsx)$/.test(J))&&!C&&!P;if(L&&!ue||C&&!Q&&!P||F){Dc=!0;let J=[];L&&!ue&&J.push("python -m venv venv && source venv/bin/activate && pip install -r requirements.txt"),F?J.push("create package.json for the React frontend (with react, react-dom, react-scripts dependencies), then run npm install"):C&&!Q&&!P&&J.push("npm install");let re=`[FRAMEWORK \u2014 post-creation check] You wrote dependency files but never ran the installer. Run now: ${J.join(" && ")}. Verify it succeeds, fix any errors, then write a closing summary.`;D(`${m.dim} [post-creation] bootstrapping environment (${J.join(", ")})${m.reset}`),j.push({role:"user",content:re}),k.push({role:"user",content:re});continue}}if(R>0&&!s._isSummaryTurn&&Zv(At))try{D(`${m.dim} [post-turn] terse ending \u2014 requesting diagnosis/summary${m.reset}`);let C=E.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.",L=[...k,{role:"user",content:C}],U=((await Tg(L,[],{}))?.content||"").trim();U&&(console.log(`
1377
- ${U}`),j.push({role:"user",content:C},{role:"assistant",content:U}))}catch{}Oe(j),Ni(j);return}R++,Xi++,R>=1&&(be=!1);for(let w of an){let y=w.function.name;W.set(y,(W.get(y)||0)+1)}if(R>=30&&!Fg){Fg=!0,D(`${m.yellow} \u26A0 Tool budget warning: ${R} tool calls used \u2014 nudging model to wrap up${m.reset}`);let w={role:"user",content:"[SYSTEM] \u26A0 You have used "+R+" 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."};j.push(w),k.push(w)}let me=await Promise.all(an.map(w=>GE(w)));{let w=Gt(k,at()),y=w.percentage,z=me.some(U=>U.canExecute&&U.fnName==="read_file"&&!U.args?.line_end),C=me.filter(U=>U.canExecute&&U.fnName==="read_file"&&U.args?.path&&sn(ms,U.args.path)>=1&&!U.args?.line_start).map(U=>U.args.path.split("/").slice(-2).join("/")),L=C.length>0;if(y>=70&&z&&ta<70||y>=85&&ta<85||L){ta=y;let U=y>=85?"URGENT":"WARNING",ue;L?(U="WARNING",ue=`Full-file read of ${C.join(", ")} already done \u2014 use line_start/line_end for specific sections instead.`):z?ue=`Unbounded read at ${Math.round(y)}% context \u2014 use line_start/line_end to avoid overflow.`:ue="Use targeted reads (line_start/line_end) to save space.";let P={role:"user",content:`[SYSTEM ${U}] Context ${Math.round(y)}% used (${w.used}/${w.limit} tokens). ${ue}`};if(j.push(P),k.push(P),y>=85){let q=L?` (re-read of: ${C.join(", ")})`:"";D(`${m.yellow} \u26A0 Context ${Math.round(y)}% used \u2014 agent warned to use targeted reads${q}${m.reset}`)}}}let aa=new Map;for(let w of me){if(!w.canExecute||w.fnName!=="read_file")continue;let y=w.args?.path;if(!y)continue;let z=sn(ms,y),C=aa.get(y)||0,L=z+C,Q=w.args?.line_start!=null,U=Lt.get(y)||0,ue=U>0,P=2;if(L>=gs){let q=y.split("/").slice(-2).join("/"),F=(ps.get(y)||0)+1;if(ps.set(y,F),F===1)D(`${m.red} \u2716 Blocked: "${q}" read ${L}\xD7 \u2014 hard cap (${gs}) reached${m.reset}`);else if(F===2){D(`${m.red} \u2716 Escalated block: "${q}" \u2014 model ignored BLOCKED, injecting system warning${m.reset}`);let V={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 (${gs}\xD7). Do NOT attempt to read it again. Use grep_search to find specific content, or proceed with what you already know.`};j.push(V),k.push(V)}w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 file already read ${L}\xD7 (hard cap: ${gs}). You have seen enough of this file. Use grep to find specific content or proceed with what you know.`,tool_call_id:w.callId}}else if(L>=1&&Q)if(ue&&U<=P){let q=y.split("/").slice(-2).join("/");console.log(`${m.cyan} \u21A9 Targeted re-read: "${q}" (line_start=${w.args.line_start}) \u2014 edit recovery #${U}${m.reset}`),Lt.set(y,U-1)}else if(ue&&U>P){let q=y.split("/").slice(-2).join("/");D(`${m.red} \u2716 Edit recovery blocked: "${q}" \u2014 ${P} recovery reads already used. Use grep to find the exact line numbers, then retry.${m.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 edit recovery budget exhausted (${P} 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:w.callId}}else{let q=parseInt(w.args.line_start,10)||1,F=parseInt(w.args.line_end,10)||q+350,V=An.get(y)||[],J=!1;for(let[re,fe]of V){let ee=Math.max(q,re),xe=Math.min(F,fe);if(xe>ee){let Ee=xe-ee,gt=F-q||1,Ve=fe-re||1,Ot=Ee/Ve>=.7&&Ee/gt<.7,Je=F-q<=My;if(Ee>=gt||!Je&&(Ee/gt>=.7||Ee/Ve>=.7)){let ca=y.split("/").slice(-2).join("/"),uu=`${y}:${q}-${F}`,ws=(Ki.get(uu)||0)+1;if(Ki.set(uu,ws),D(Ot?`${m.red} \u2716 Blocked superread: "${ca}" lines ${q}-${F} subsumes already-read ${re}-${fe} \u2014 use line_start=${fe+1} to skip known content (block #${ws})${m.reset}`:`${m.red} \u2716 Blocked duplicate read: "${ca}" lines ${q}-${F} (\u226570% overlap with lines ${re}-${fe} already in context, block #${ws})${m.reset}`),ws>=2){D(`${m.red} \u2716 Escalated range-block: "${ca}" lines ${q}-${F} \u2014 model ignored BLOCKED, injecting system warning${m.reset}`);let du={role:"user",content:Ot?`[SYSTEM] Read blocked ${ws}\xD7 for read_file("${y}", lines ${q}-${F}). Lines ${re}-${fe} were already read. Use line_start=${fe+1} to read only new content, or use grep_search for specific lines.`:`[SYSTEM] Read blocked ${ws}\xD7 for read_file("${y}", lines ${q}-${F}). Lines ${re}-${fe} were already read and will NOT change. Use grep_search to find specific content instead.`};j.push(du),k.push(du)}w.canExecute=!1,w.errorResult={role:"tool",content:Ot?`BLOCKED: read_file("${y}", lines ${q}-${F}) re-reads lines ${re}-${fe} already in context. Use line_start=${fe+1} to read only the new content beyond line ${fe}.`:`BLOCKED: read_file("${y}", lines ${q}-${F}) is a duplicate \u2014 lines ${re}-${fe} are already in your context (\u226570% overlap). Use grep to find specific content instead of re-reading.`,tool_call_id:w.callId},J=!0;break}}}if(!J){let re=V.length,fe=2;if(re>=3){let xe=y.split("/").slice(-2).join("/");D(`${m.red} \u2716 Blocked file-scroll: "${xe}" \u2014 ${re} sections already read. Use grep to find specific content.${m.reset}`);let Ee=sn(ea,y)>=lr;w.canExecute=!1,w.errorResult={role:"tool",content:Ee?`BLOCKED: read_file("${y}") denied \u2014 you have already read ${re} different sections of this file (file-scroll pattern). Grep is also exhausted. The content you need is already in your context \u2014 work with what you have.`:`BLOCKED: read_file("${y}") denied \u2014 you have already read ${re} 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:w.callId}}else re>=fe&&(w._scrollWarn={sectionCount:re+1,path:y})}}else if(L>=1){let q=Lt.get(y)||0;if(q>0){let F=y.split("/").slice(-2).join("/");console.log(`${m.cyan} \u21A9 Full re-read: "${F}" \u2014 test-failure recovery (${q} remaining)${m.reset}`);let V=q-1;V<=0?Lt.delete(y):Lt.set(y,V)}else{let F=y.split("/").slice(-2).join("/"),V=(ps.get(y)||0)+1;if(ps.set(y,V),V===1)D(`${m.red} \u2716 Blocked unbounded re-read: "${F}" \u2014 already in context. Use line_start/line_end for specific sections.${m.reset}`);else if(V===2){D(`${m.red} \u2716 Escalated block: "${F}" \u2014 model ignored unbounded re-read block, injecting system warning${m.reset}`);let J={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.`};j.push(J),k.push(J)}w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 file already in context (read ${L}\xD7). Use line_start/line_end to read a specific section instead of the full file.`,tool_call_id:w.callId}}}w.canExecute&&aa.set(y,(aa.get(y)||0)+1)}if(Cn>=3)for(let w of me)w.canExecute&&(w.fnName!=="read_file"&&w.fnName!=="edit_file"||(D(`${m.red} \u2716 Blocked ${w.fnName} \u2014 ${Cn} consecutive file-not-found errors, must search first${m.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: ${Cn} 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:w.callId}));for(let w of me){if(!w.canExecute||w.fnName!=="bash")continue;let y=(w.args?.command||"").trim();if(/^\s*ls(\s+-[a-zA-Z]+)*(\s+\S+)?\s*$/.test(y)&&!/npm|yarn|pnpm|make|git/.test(y)){D(`${m.red} \u2716 Blocked bash ls \u2014 use list_directory tool instead${m.reset}`),w.canExecute=!1,w.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:w.callId};continue}/\bfind\s+[\S.]/.test(y)&&!/git\s|npm\s|yarn\s|-exec\s+\S|-execdir/.test(y)&&(D(`${m.red} \u2716 Blocked bash find \u2014 use glob tool with a pattern instead${m.reset}`),w.canExecute=!1,w.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:w.callId})}for(let w of me)w.canExecute&&(w.fnName!=="ssh_exec"&&w.fnName!=="bash"||/\bsed\s+-n\b/.test(w.args?.command||"")&&(D(`${m.red} \u2716 Blocked sed -n: use grep -n "pattern" <file> | head -30 instead${m.reset}`),w.canExecute=!1,w.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:w.callId}));for(let w of me){if(!w.canExecute||w.fnName!=="write_file")continue;let y=w.args?.path,z=w.args?.content||"";if(y)try{let C=require("fs"),L=require("path").resolve(process.cwd(),y);if(C.existsSync(L)){let Q=C.statSync(L).size,U=Buffer.byteLength(z,"utf8"),ue=Q>0?U/Q:1;if(ue<.6&&Q>200){let P=y.split("/").slice(-2).join("/");console.log(`${m.red} \u2716 write_file shrink guard: "${P}" would shrink to ${Math.round(ue*100)}% of original \u2014 likely context loss${m.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: write_file("${y}") denied \u2014 new content is only ${Math.round(ue*100)}% of current file size (${Q} \u2192 ${U} 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:w.callId}}}}catch{}}let iu=new Map;for(let w of me){if(!w.canExecute||w.fnName!=="grep")continue;let y=w.args?.path;if(!y)continue;let z=iu.get(y)||0,C=sn(ea,y)+z,L=sn(ms,y)>=1,Q=L?Math.min(3,lr):lr;if(C>=Q){let U=y.split("/").slice(-2).join("/");D(`${m.red} \u2716 Blocked grep: "${U}" grepped ${C}\xD7 with different patterns \u2014 flood threshold exceeded${m.reset}`);let ue=sn(ms,y),P=ue>=gs;if(P){let q={role:"user",content:`[SYSTEM] Both read_file and grep are now blocked for "${y}". You have already read ${ue} sections and tried ${C} grep patterns. Do NOT attempt to read or grep this file again. The content you need is already in your conversation context \u2014 scroll back to find it, or proceed with what you know.`};j.push(q),k.push(q),D(`${m.red} \u2716 Deadlock detected: "${U}" \u2014 both read and grep blocked, injecting deadlock-break${m.reset}`)}w.canExecute=!1,w.errorResult={role:"tool",content:P?`BLOCKED: grep("${y}") denied \u2014 ${C} patterns already tried AND reads are also exhausted. The content is already in your context. Do not attempt to read or grep this file again.`:L?`BLOCKED: grep("${y}") denied \u2014 file was already read and ${C} grep patterns tried. The content is already in your context; use it instead of searching again.`:`BLOCKED: grep("${y}") denied \u2014 ${C} patterns already tried. Work with the grep results already in your context.`,tool_call_id:w.callId}}w.canExecute&&iu.set(y,z+1)}let qy=5,au=new Map;for(let w of me){if(!w.canExecute||w.fnName!=="ssh_exec")continue;let z=(w.args?.command||"").replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),C=au.get(z)||0,L=sn(Zc,z)+C;L>=qy&&(D(`${m.yellow} \u26A0 Blocked ssh_exec: same command run ${L}\xD7 \u2014 result already in context${m.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: ssh_exec denied \u2014 this command has already run ${L} 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:w.callId}),w.canExecute&&au.set(z,C+1)}if(Tt){let w=me.filter(C=>C.canExecute&&C.fnName==="ssh_exec"),y=me.some(C=>C.canExecute&&C.fnName!=="ssh_exec"),z=$&&I<3;if(w.length>0&&!y&&z&&Bi<1)Tt=!1,Bi++,It=Math.max(0,so-2),D(`${m.dim} [dual-block deadlock: SSH storm relaxed \u2014 allowing 1 SSH call (relax ${Bi}/1)]${m.reset}`);else for(let C of w)C.canExecute=!1,C.errorResult={role:"tool",content:tt?`BLOCKED: ssh_exec denied \u2014 SSH paused (${so}+ calls). Root cause is known (${_t}). 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 (${so}+ 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:C.callId}}if($&&I<3&&!Tt){for(let w of me)if(w.canExecute&&["bash","read_file","find_files"].includes(w.fnName)){I++;{let y=at(),{messages:z}=nn(k,y);k=z}D(`${m.yellow} \u26A0 Server-local guard: blocking local ${w.fnName} \u2014 use ssh_exec on 94.130.37.43${m.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: ${w.fnName} denied \u2014 this is a server issue. Use ssh_exec on 94.130.37.43 instead.`,tool_call_id:w.callId};break}}if(!ye&&qt&&Dt&&Kt>=1){let w=["read_file","grep","search_files","glob","list_directory","find_files"];for(let y of me)y.canExecute&&w.includes(y.fnName)&&(D(`${m.red} \u2716 Creation hard-block: ${y.fnName} denied \u2014 cap fired, files already written${m.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(us>=0){let w=me.filter(y=>y.canExecute).length;if(w>0&&(us-=w,us<0))if(!Wi&&E.size>Ui){Wi=!0,us=5,D(`${m.green} \u2713 Post-wipe progress detected (${E.size-Ui} files modified) \u2014 granting 5 bonus tool calls${m.reset}`);let y={role:"user",content:"[SYSTEM] Progress detected \u2014 5 bonus tool calls granted. Budget: 5 remaining."};j.push(y),k.push(y)}else{D(`${m.red} \u2716 Post-wipe tool budget exhausted \u2014 blocking all tool calls${m.reset}`);for(let z of me)z.canExecute&&(z.canExecute=!1,z.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:z.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."};j.push(y),k.push(y)}}let Fy=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 w of me){if(!w.canExecute||Fy.has(w.fnName))continue;let y=JSON.stringify(w.args||{}),z=`${w.fnName}|${y}`,C=sn(Pc,z);C>=2?(D(`${m.red} \u2716 Blocked duplicate: ${w.fnName}(${y.substring(0,80)}) \u2014 called ${C+1}\xD7 with identical args${m.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: ${w.fnName}() with these exact arguments has already been called ${C}\xD7 \u2014 the result is already in your context. Use the existing output instead of repeating the same call.`,tool_call_id:w.callId}):C===1&&D(`${m.yellow} \u26A0 Duplicate tool call: ${w.fnName}(${y.substring(0,80)}) \u2014 2nd call with identical args${m.reset}`),cs(Pc,z)}{let w=new Set;for(let y of me){if(!y.canExecute||!["edit_file","patch_file"].includes(y.fnName))continue;let z=y.args?.path;z&&(oe.has(z)||w.has(z)?(y.canExecute=!1,y.errorResult={role:"tool",content:`BLOCKED: "${z}" was already edited \u2014 re-read the changed section first (read_file with line_start/line_end) before making another edit. The file content has changed and your previous read is stale.`,tool_call_id:y.callId},D(`${m.yellow} \u26A0 Map-first gate: blocked re-edit of "${z.split("/").slice(-1)[0]}" \u2014 re-read required${m.reset}`)):w.add(z))}}let ro=c?{skipSpinner:!0,skipSummaries:!0}:{},By=me.some(w=>w.fnName==="ask_user"),lu=!ro.skipSummaries&&!be,pr=null,ys=null;lu&&!By?(be=!0,ro.skipSpinner=!0,process.stdout.isTTY?(global._nexFooter&&(ys=Math.min(global._nexFooter._lastOutputRow+1,global._nexFooter._scrollEnd)),process.stdout.write(Oi(me,R,!1,"blink")),pr=!0):on||process.stdout.write(Oi(me,R,!1)+`
1378
- `)):lu&&(be=!0,ro.skipSpinner=!0),c&&c._paused&&c.resume();let hr=null;if(pr&&process.stdout.isTTY&&me.some(y=>y.canExecute&&(y.fnName==="bash"||y.fnName==="ssh_exec"))){let y=Date.now();hr=setInterval(()=>{let z=Math.round((Date.now()-y)/1e3);if(z>=3){let C=`${Oi(me,R,!1,"blink")} ${m.dim}[${z}s]${m.reset}`;ys!==null?process.stdout.write(`\x1B[${ys};1H\x1B[2K${C}`):process.stdout.write(`\r\x1B[2K${C}`)}},1e3)}let{results:ot,summaries:Uy}=await VE(me,!0,{...ro,skipSummaries:!0});if(hr&&(clearInterval(hr),hr=null),pr){pr=null;let w=Oi(me,R,!1);ys!==null?process.stdout.write(`\x1B[${ys};1H\x1B[2K${w}
1392
+ ${getPlanContent()||Rt.content}`;L.push({role:"user",content:X}),S.push({role:"user",content:X}),ee=!0}}else console.log(`
1393
+ ${h.cyan}${h.bold}Plan ready.${h.reset} ${h.dim}Type ${h.reset}${h.cyan}/plan approve${h.reset}${h.dim} to execute, or ask follow-up questions to refine.${h.reset}`);if(ee){c&&(c.stop(),c=null),qe--;continue}}}if(c&&(c.stop(),c=null),l(null),Ne(N,q,x,Y,Oe),Dt&&x.size>=3){let T=[...x].map(C=>C.split("/").pop()).slice(0,8).join(", "),M=[...x].some(C=>C.endsWith("package.json")),ee=[...x].some(C=>C.endsWith("requirements.txt")),U=[...x].some(C=>C.endsWith("package-lock.json")||C.endsWith("yarn.lock")||C.endsWith("pnpm-lock.yaml")),ae=M&&!U?"npm install not yet run":ee?"pip install not yet run":null;sr=`[Previous session created ${x.size} files: ${T}`+(ae?` \u2014 ${ae}`:"")+". Use this context to answer follow-up questions without re-reading files.]"}if(Dt&&!Yc&&N>0){let T=[...x].some(X=>X.endsWith("package.json")),M=[...x].some(X=>X.endsWith("requirements.txt")||X.endsWith("Pipfile")||X.endsWith("pyproject.toml")),ee=[...x].some(X=>X.endsWith("package-lock.json")||X.endsWith("yarn.lock")||X.endsWith("pnpm-lock.yaml")),U=L.flatMap(X=>{let re=Array.isArray(X.tool_calls)?X.tool_calls:[],fe=Array.isArray(X.content)?X.content.filter(te=>te?.type==="tool_use"):[];return[...re,...fe]}).filter(X=>{let re=X.function?.name||X.name||"";return re==="bash"||re==="Bash"}).map(X=>{try{let re=X.function?.arguments??X.input??{};return(typeof re=="string"?JSON.parse(re):re)?.command||""}catch{return""}}),ae=U.some(X=>/pip\s+install|python\s+-m\s+venv/.test(X)),C=U.some(X=>/npm\s+install/.test(X)),F=[...x].some(X=>/\/App\.(js|ts|jsx|tsx)$/.test(X))&&!T&&!C;if(M&&!ae||T&&!ee&&!C||F){Yc=!0;let X=[];M&&!ae&&X.push("python -m venv venv && source venv/bin/activate && pip install -r requirements.txt"),F?X.push("create package.json for the React frontend (with react, react-dom, react-scripts dependencies), then run npm install"):T&&!ee&&!C&&X.push("npm install");let re=`[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.`;j(`${h.dim} [post-creation] bootstrapping environment (${X.join(", ")})${h.reset}`),L.push({role:"user",content:re}),S.push({role:"user",content:re});continue}}if(N>0&&!s._isSummaryTurn&&gE(At))try{j(`${h.dim} [post-turn] terse ending \u2014 requesting diagnosis/summary${h.reset}`);let T=x.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.",M=[...S,{role:"user",content:T}],U=((await jg(M,[],{}))?.content||"").trim();U&&(console.log(`
1394
+ ${U}`),L.push({role:"user",content:T},{role:"assistant",content:U}))}catch{}Ae(L),Di(L),await uu();return}N++,ta++,N>=1&&(ye=!1);for(let w of an){let y=w.function.name;q.set(y,(q.get(y)||0)+1)}if(N>=30&&!Vg){Vg=!0,j(`${h.yellow} \u26A0 Tool budget warning: ${N} tool calls used \u2014 nudging model to wrap up${h.reset}`);let w={role:"user",content:"[SYSTEM] \u26A0 You have used "+N+" 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."};L.push(w),S.push(w)}let we=await Promise.all(an.map(w=>uT(w)));{let w=Gt(S,at()),y=w.percentage,K=we.some(U=>U.canExecute&&U.fnName==="read_file"&&!U.args?.line_end),T=we.filter(U=>U.canExecute&&U.fnName==="read_file"&&U.args?.path&&sn(ys,U.args.path)>=1&&!U.args?.line_start).map(U=>U.args.path.split("/").slice(-2).join("/")),M=T.length>0;if(y>=70&&K&&aa<70||y>=85&&aa<85||M){aa=y;let U=y>=85?"URGENT":"WARNING",ae;M?(U="WARNING",ae=`Full-file read of ${T.join(", ")} already done \u2014 use line_start/line_end for specific sections instead.`):K?ae=`Unbounded read at ${Math.round(y)}% context \u2014 use line_start/line_end to avoid overflow.`:ae="Use targeted reads (line_start/line_end) to save space.";let C={role:"user",content:`[SYSTEM ${U}] Context ${Math.round(y)}% used (${w.used}/${w.limit} tokens). ${ae}`};if(L.push(C),S.push(C),y>=85){let D=M?` (re-read of: ${T.join(", ")})`:"";j(`${h.yellow} \u26A0 Context ${Math.round(y)}% used \u2014 agent warned to use targeted reads${D}${h.reset}`)}}}let pa=new Map;for(let w of we){if(!w.canExecute||w.fnName!=="read_file")continue;let y=w.args?.path;if(!y)continue;let K=sn(ys,y),T=pa.get(y)||0,M=K+T,ee=w.args?.line_start!=null,U=Lt.get(y)||0,ae=U>0,C=2;if(M>=ws){let D=y.split("/").slice(-2).join("/"),F=(hs.get(y)||0)+1;if(hs.set(y,F),F===1)j(`${h.red} \u2716 Blocked: "${D}" read ${M}\xD7 \u2014 hard cap (${ws}) reached${h.reset}`);else if(F===2){j(`${h.red} \u2716 Escalated block: "${D}" \u2014 model ignored BLOCKED, injecting system warning${h.reset}`);let V={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 (${ws}\xD7). Do NOT attempt to read it again. Use grep_search to find specific content, or proceed with what you already know.`};L.push(V),S.push(V)}w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 file already read ${M}\xD7 (hard cap: ${ws}). You have seen enough of this file. Use grep to find specific content or proceed with what you know.`,tool_call_id:w.callId}}else if(M>=1&&ee)if(ae&&U<=C){let D=y.split("/").slice(-2).join("/");console.log(`${h.cyan} \u21A9 Targeted re-read: "${D}" (line_start=${w.args.line_start}) \u2014 edit recovery #${U}${h.reset}`),Lt.set(y,U-1)}else if(ae&&U>C){let D=y.split("/").slice(-2).join("/");j(`${h.red} \u2716 Edit recovery blocked: "${D}" \u2014 ${C} recovery reads already used. Use grep to find the exact line numbers, then retry.${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 edit recovery budget exhausted (${C} 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:w.callId}}else{let D=parseInt(w.args.line_start,10)||1,F=parseInt(w.args.line_end,10)||D+350,V=Cn.get(y)||[],X=!1;for(let[re,fe]of V){let te=Math.max(D,re),$e=Math.min(F,fe);if($e>te){let Te=$e-te,gt=F-D||1,Je=fe-re||1,Ot=Te/Je>=.7&&Te/gt<.7,Ze=F-D<=Uy;if(Te>=gt||!Ze&&(Te/gt>=.7||Te/Je>=.7)){let ma=y.split("/").slice(-2).join("/"),$u=`${y}:${D}-${F}`,$s=(ea.get($u)||0)+1;if(ea.set($u,$s),j(Ot?`${h.red} \u2716 Blocked superread: "${ma}" lines ${D}-${F} subsumes already-read ${re}-${fe} \u2014 use line_start=${fe+1} to skip known content (block #${$s})${h.reset}`:`${h.red} \u2716 Blocked duplicate read: "${ma}" lines ${D}-${F} (\u226570% overlap with lines ${re}-${fe} already in context, block #${$s})${h.reset}`),$s>=2){j(`${h.red} \u2716 Escalated range-block: "${ma}" lines ${D}-${F} \u2014 model ignored BLOCKED, injecting system warning${h.reset}`);let bu={role:"user",content:Ot?`[SYSTEM] Read blocked ${$s}\xD7 for read_file("${y}", lines ${D}-${F}). Lines ${re}-${fe} were already read. Use line_start=${fe+1} to read only new content, or use grep_search for specific lines.`:`[SYSTEM] Read blocked ${$s}\xD7 for read_file("${y}", lines ${D}-${F}). Lines ${re}-${fe} were already read and will NOT change. Use grep_search to find specific content instead.`};L.push(bu),S.push(bu)}w.canExecute=!1,w.errorResult={role:"tool",content:Ot?`BLOCKED: read_file("${y}", lines ${D}-${F}) re-reads lines ${re}-${fe} already in context. Use line_start=${fe+1} to read only the new content beyond line ${fe}.`:`BLOCKED: read_file("${y}", lines ${D}-${F}) is a duplicate \u2014 lines ${re}-${fe} are already in your context (\u226570% overlap). Use grep to find specific content instead of re-reading.`,tool_call_id:w.callId},X=!0;break}}}if(!X){let re=V.length,fe=2;if(re>=3){let $e=y.split("/").slice(-2).join("/");j(`${h.red} \u2716 Blocked file-scroll: "${$e}" \u2014 ${re} sections already read. Use grep to find specific content.${h.reset}`);let Te=sn(ia,y)>=fr;w.canExecute=!1,w.errorResult={role:"tool",content:Te?`BLOCKED: read_file("${y}") denied \u2014 you have already read ${re} different sections of this file (file-scroll pattern). Grep is also exhausted. The content you need is already in your context \u2014 work with what you have.`:`BLOCKED: read_file("${y}") denied \u2014 you have already read ${re} 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:w.callId}}else re>=fe&&(w._scrollWarn={sectionCount:re+1,path:y})}}else if(M>=1){let D=Lt.get(y)||0;if(D>0){let F=y.split("/").slice(-2).join("/");console.log(`${h.cyan} \u21A9 Full re-read: "${F}" \u2014 test-failure recovery (${D} remaining)${h.reset}`);let V=D-1;V<=0?Lt.delete(y):Lt.set(y,V)}else{let F=y.split("/").slice(-2).join("/"),V=(hs.get(y)||0)+1;if(hs.set(y,V),V===1)j(`${h.red} \u2716 Blocked unbounded re-read: "${F}" \u2014 already in context. Use line_start/line_end for specific sections.${h.reset}`);else if(V===2){j(`${h.red} \u2716 Escalated block: "${F}" \u2014 model ignored unbounded re-read block, injecting system warning${h.reset}`);let X={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.`};L.push(X),S.push(X)}w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 file already in context (read ${M}\xD7). Use line_start/line_end to read a specific section instead of the full file.`,tool_call_id:w.callId}}}w.canExecute&&pa.set(y,(pa.get(y)||0)+1)}if(Rn>=3)for(let w of we)w.canExecute&&(w.fnName!=="read_file"&&w.fnName!=="edit_file"||(j(`${h.red} \u2716 Blocked ${w.fnName} \u2014 ${Rn} consecutive file-not-found errors, must search first${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: ${Rn} 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:w.callId}));for(let w of we){if(!w.canExecute||w.fnName!=="bash")continue;let y=(w.args?.command||"").trim();if(/^\s*ls(\s+-[a-zA-Z]+)*(\s+\S+)?\s*$/.test(y)&&!/npm|yarn|pnpm|make|git/.test(y)){j(`${h.red} \u2716 Blocked bash ls \u2014 use list_directory tool instead${h.reset}`),w.canExecute=!1,w.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:w.callId};continue}/\bfind\s+[\S.]/.test(y)&&!/git\s|npm\s|yarn\s|-exec\s+\S|-execdir/.test(y)&&(j(`${h.red} \u2716 Blocked bash find \u2014 use glob tool with a pattern instead${h.reset}`),w.canExecute=!1,w.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:w.callId})}for(let w of we)w.canExecute&&(w.fnName!=="ssh_exec"&&w.fnName!=="bash"||/\bsed\s+-n\b/.test(w.args?.command||"")&&(j(`${h.red} \u2716 Blocked sed -n: use grep -n "pattern" <file> | head -30 instead${h.reset}`),w.canExecute=!1,w.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:w.callId}));for(let w of we){if(!w.canExecute||w.fnName!=="write_file")continue;let y=w.args?.path,K=w.args?.content||"";if(y)try{let T=require("fs"),M=require("path").resolve(process.cwd(),y);if(T.existsSync(M)){let ee=T.statSync(M).size,U=Buffer.byteLength(K,"utf8"),ae=ee>0?U/ee:1;if(ae<.6&&ee>200){let C=y.split("/").slice(-2).join("/");console.log(`${h.red} \u2716 write_file shrink guard: "${C}" would shrink to ${Math.round(ae*100)}% of original \u2014 likely context loss${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: write_file("${y}") denied \u2014 new content is only ${Math.round(ae*100)}% of current file size (${ee} \u2192 ${U} 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:w.callId}}}}catch{}}let gu=new Map;for(let w of we){if(!w.canExecute||w.fnName!=="grep")continue;let y=w.args?.path;if(!y)continue;let K=gu.get(y)||0,T=sn(ia,y)+K,M=sn(ys,y)>=1,ee=M?Math.min(3,fr):fr;if(T>=ee){let U=y.split("/").slice(-2).join("/");j(`${h.red} \u2716 Blocked grep: "${U}" grepped ${T}\xD7 with different patterns \u2014 flood threshold exceeded${h.reset}`);let ae=sn(ys,y),C=ae>=ws;if(C){let D={role:"user",content:`[SYSTEM] Both read_file and grep are now blocked for "${y}". You have already read ${ae} sections and tried ${T} grep patterns. Do NOT attempt to read or grep this file again. The content you need is already in your conversation context \u2014 scroll back to find it, or proceed with what you know.`};L.push(D),S.push(D),j(`${h.red} \u2716 Deadlock detected: "${U}" \u2014 both read and grep blocked, injecting deadlock-break${h.reset}`)}w.canExecute=!1,w.errorResult={role:"tool",content:C?`BLOCKED: grep("${y}") denied \u2014 ${T} patterns already tried AND reads are also exhausted. The content is already in your context. Do not attempt to read or grep this file again.`:M?`BLOCKED: grep("${y}") denied \u2014 file was already read and ${T} grep patterns tried. The content is already in your context; use it instead of searching again.`:`BLOCKED: grep("${y}") denied \u2014 ${T} patterns already tried. Work with the grep results already in your context.`,tool_call_id:w.callId}}w.canExecute&&gu.set(y,K+1)}let Ky=5,yu=new Map;for(let w of we){if(!w.canExecute||w.fnName!=="ssh_exec")continue;let K=(w.args?.command||"").replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),T=yu.get(K)||0,M=sn(au,K)+T;M>=Ky&&(j(`${h.yellow} \u26A0 Blocked ssh_exec: same command run ${M}\xD7 \u2014 result already in context${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: ssh_exec denied \u2014 this command has already run ${M} 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:w.callId}),w.canExecute&&yu.set(K,T+1)}if(Tt){let w=we.filter(T=>T.canExecute&&T.fnName==="ssh_exec"),y=we.some(T=>T.canExecute&&T.fnName!=="ssh_exec"),K=I&&H<3;if(w.length>0&&!y&&K&&zi<1)Tt=!1,zi++,It=Math.max(0,ao-2),j(`${h.dim} [dual-block deadlock: SSH storm relaxed \u2014 allowing 1 SSH call (relax ${zi}/1)]${h.reset}`);else for(let T of w)T.canExecute=!1,T.errorResult={role:"tool",content:nt?`BLOCKED: ssh_exec denied \u2014 SSH paused (${ao}+ calls). Root cause is known (${_t}). 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 (${ao}+ 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:T.callId}}if(I&&H<3&&!Tt){for(let w of we)if(w.canExecute&&["bash","read_file","find_files"].includes(w.fnName)){H++;{let y=at(),{messages:K}=nn(S,y);S=K}j(`${h.yellow} \u26A0 Server-local guard: blocking local ${w.fnName} \u2014 use ssh_exec on 94.130.37.43${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: ${w.fnName} denied \u2014 this is a server issue. Use ssh_exec on 94.130.37.43 instead.`,tool_call_id:w.callId};break}}if(!_e&&qt&&Dt&&Kt>=1){let w=["read_file","grep","search_files","glob","list_directory","find_files"];for(let y of we)y.canExecute&&w.includes(y.fnName)&&(j(`${h.red} \u2716 Creation hard-block: ${y.fnName} denied \u2014 cap fired, files already written${h.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(ds>=0){let w=we.filter(y=>y.canExecute).length;if(w>0&&(ds-=w,ds<0))if(!Xi&&x.size>Ki){Xi=!0,ds=5,j(`${h.green} \u2713 Post-wipe progress detected (${x.size-Ki} files modified) \u2014 granting 5 bonus tool calls${h.reset}`);let y={role:"user",content:"[SYSTEM] Progress detected \u2014 5 bonus tool calls granted. Budget: 5 remaining."};L.push(y),S.push(y)}else{j(`${h.red} \u2716 Post-wipe tool budget exhausted \u2014 blocking all tool calls${h.reset}`);for(let K of we)K.canExecute&&(K.canExecute=!1,K.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:K.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."};L.push(y),S.push(y)}}let Xy=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 w of we){if(!w.canExecute||Xy.has(w.fnName))continue;let y=JSON.stringify(w.args||{}),K=`${w.fnName}|${y}`,T=sn(Uc,K);T>=2?(j(`${h.red} \u2716 Blocked duplicate: ${w.fnName}(${y.substring(0,80)}) \u2014 called ${T+1}\xD7 with identical args${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: ${w.fnName}() with these exact arguments has already been called ${T}\xD7 \u2014 the result is already in your context. Use the existing output instead of repeating the same call.`,tool_call_id:w.callId}):T===1&&j(`${h.yellow} \u26A0 Duplicate tool call: ${w.fnName}(${y.substring(0,80)}) \u2014 2nd call with identical args${h.reset}`),us(Uc,K)}{let w=new Set;for(let y of we){if(!y.canExecute||!["edit_file","patch_file"].includes(y.fnName))continue;let K=y.args?.path;K&&(ke.has(K)||w.has(K)?(y.canExecute=!1,y.errorResult={role:"tool",content:`BLOCKED: "${K}" was already edited \u2014 re-read the changed section first (read_file with line_start/line_end) before making another edit. The file content has changed and your previous read is stale.`,tool_call_id:y.callId},j(`${h.yellow} \u26A0 Map-first gate: blocked re-edit of "${K.split("/").slice(-1)[0]}" \u2014 re-read required${h.reset}`)):w.add(K))}}let co=c?{skipSpinner:!0,skipSummaries:!0}:{},Vy=we.some(w=>w.fnName==="ask_user"),wu=!co.skipSummaries&&!ye,yr=null,_s=null;wu&&!Vy?(ye=!0,co.skipSpinner=!0,process.stdout.isTTY?(global._nexFooter&&(_s=Math.min(global._nexFooter._lastOutputRow+1,global._nexFooter._scrollEnd)),process.stdout.write(Ii(we,N,!1,"blink")),yr=!0):on||process.stdout.write(Ii(we,N,!1)+`
1395
+ `)):wu&&(ye=!0,co.skipSpinner=!0),c&&c._paused&&c.resume();let wr=null;if(yr&&process.stdout.isTTY&&we.some(y=>y.canExecute&&(y.fnName==="bash"||y.fnName==="ssh_exec"))){let y=Date.now();wr=setInterval(()=>{let K=Math.round((Date.now()-y)/1e3);if(K>=3){let T=`${Ii(we,N,!1,"blink")} ${h.dim}[${K}s]${h.reset}`;_s!==null?process.stdout.write(`\x1B[${_s};1H\x1B[2K${T}`):process.stdout.write(`\r\x1B[2K${T}`)}},1e3)}let{results:ot,summaries:Jy}=await hT(we,!0,{...co,skipSummaries:!0});if(wr&&(clearInterval(wr),wr=null),yr){yr=null;let w=Ii(we,N,!1);_s!==null?process.stdout.write(`\x1B[${_s};1H\x1B[2K${w}
1379
1396
  `):process.stdout.write(`\r\x1B[2K${w}
1380
- `),ys=null}if(!ro.skipSummaries){let w=Uy.filter((C,L)=>!(me[L]&&me[L].fnName==="ask_user"));for(let C of w)console.log(C);let y=me.filter(C=>C&&C.fnName!=="ask_user").map(C=>C.fnName),z=gy.record(0,y,S,E);z&&EE(z)}for(let w of me){if(w.canExecute||!w.errorResult)continue;let y=typeof w.errorResult.content=="string"?w.errorResult.content:"";if((y.startsWith("BLOCKED:")||y.startsWith("PLAN MODE:")||y.startsWith("PLAN PHASE:"))&&(Pn++,Pn>=Qc)){D(`${m.red} \u2716 Loop abort: ${Pn} consecutive blocked calls (pre-execution) \u2014 model not heeding BLOCKED messages${m.reset}`),c&&(c.stop(),c=null),l(null),Ne(R,W,E,S,Ae,{suppressHint:!0}),Oe(j);return}}for(let w=0;w<me.length;w++){let y=me[w];if(!y.canExecute)continue;let z=ot[w].content,C=z.split(`
1381
- `)[0],L=!C.startsWith("ERROR")&&!C.startsWith("CANCELLED")&&!C.startsWith("Command failed")&&!C.startsWith("EXIT");if(!L&&(y.fnName==="edit_file"||y.fnName==="patch_file")&&y.args?.path&&C.includes("old_text not found")){let P=Lt.get(y.args.path)||0;Lt.set(y.args.path,P+1)}if(!L&&y.fnName==="bash"&&or.size>0){let P=(y.args?.command||"").toLowerCase();if(/\b(test|jest|vitest|pytest|mocha|tsc|build|lint|eslint|check)\b/.test(P))for(let[F]of or)Lt.has(F)||(Lt.set(F,1),D(`${m.cyan} \u21A9 Test failure \u2014 queuing recovery re-read: "${F.split("/").pop()}"${m.reset}`))}if(!L&&(y.fnName==="read_file"||y.fnName==="edit_file")&&/file not found|does not exist|ENOENT/i.test(C)){if(Cn++,Cn>=2){D(`${m.yellow} \u26A0 File-not-found streak: ${Cn} consecutive misses \u2014 forcing search${m.reset}`);let P={role:"user",content:`[SYSTEM] ${Cn} 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.`};j.push(P),k.push(P)}}else L&&(y.fnName==="read_file"||y.fnName==="edit_file"||y.fnName==="search_files"||y.fnName==="glob_files")&&(Cn=0);if(L&&y.fnName==="write_file"&&y.args?.path){let P=y.args.path.split("/").pop(),q=y.args.path.includes("/tests/")||y.args.path.includes("\\tests\\");if(/^(test_|demo_|temp_|tmp_|scratch_)/.test(P)&&!q){D(`${m.yellow} \u26A0 Temp file: "${P}" \u2014 delete with bash rm when done to keep the workspace clean${m.reset}`);let V={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.`};j.push(V),k.push(V)}}if(L&&["write_file","edit_file","patch_file"].includes(y.fnName)&&y.args&&y.args.path){Lt.delete(y.args.path),E.add(y.args.path);for(let F of hs)!F.done&&y.args.path.endsWith(F.file.split("/").pop())&&(F.done=!0,D(`${m.green} \u2713 TODO done: ${F.file}${m.reset}`));let P=cs(yy,y.args.path),q=y.args.path.split("/").slice(-2).join("/");if(P===wy){D(`${m.yellow} \u26A0 Loop warning: "${q}" edited ${P}\xD7 \u2014 possible edit loop${m.reset}`);let F={role:"user",content:`[SYSTEM WARNING] "${y.args.path}" edited ${P}\xD7. One more edit max, then move on.`};j.push(F),k.push(F)}else if(P>=_y){D(`${m.red} \u2716 Loop abort: "${q}" edited ${P}\xD7 \u2014 aborting to prevent runaway loop${m.reset}`),c&&(c.stop(),c=null),l(null),Ne(R,W,E,S,Ae,{suppressHint:!0}),Oe(j);return}}if(L&&y.canExecute&&ye&&(Nn=0),L&&y.canExecute&&!(ye&&Le==="plan")){let P=["read_file","grep","search_files","glob","list_directory","ssh_exec","find_files"];if(["write_file","edit_file","patch_file"].includes(y.fnName)){jt=0,qt=!1,zt=0,Kt++;let ee=y.args?.path||y.args?.file_path;ee&&(Ec(mn,ee,1),An.delete(ee),oe.add(ee))}else if(P.includes(y.fnName)&&(jt++,qt&&zt++,ye&&Le==="implement"&&y.fnName==="read_file"&&hs.length>0)){let ee=y.args?.path||y.args?.file_path||"",xe=hs.find(Ee=>!Ee.done&&ee.endsWith(Ee.file.split("/").pop()));if(xe){let Ee={role:"user",content:`[TODO OBSERVER] You already analyzed "${xe.file}" in the plan phase. Action: ${xe.action}
1382
- Do NOT re-read \u2014 apply the edit directly with edit_file.`};j.push(Ee),k.push(Ee),D(`${m.yellow} \u26A0 TODO nudge: ${xe.file} \u2014 already analyzed, edit directly${m.reset}`)}}let F=n.postEditCap,V=ye&&Le==="implement"?Math.min(eu,10):eu,J=tt?8:Dt?Kt>0?6:10:Kt>0?F:V,re=6,fe=!ye&&qt&&(tt&&zt>=re||Dt&&Kt>=3&&zt>=re||zt>=re);if(Go<2&&!qt&&jt>=3&&E.size===0){let ee=parseInt(process.env.NEX_TASK_TIMEOUT_MS,10)||0,xe=Date.now()-Ae,Ee=Go===0?.4:.65;if(ee>0&&xe>ee*Ee){Go++;let gt=Math.round(xe/6e4),Ve=Math.round(xe/ee*100);D(`${m.yellow} \u26A0 Time nudge #${Go}: ${gt}m elapsed (${Ve}%), ${jt} reads, 0 edits${m.reset}`);let Ot={role:"user",content:Go===1?`[SYSTEM] ${Ve}% of available time used and no files edited yet. Start implementing now using edit_file or write_file \u2014 you have enough context.`:`[SYSTEM] ${Ve}% of time used, still no edits. You MUST write code NOW. Use edit_file or write_file immediately \u2014 any further reading will be blocked.`};j.push(Ot),k.push(Ot)}}if(fe&&P.includes(y.fnName)){let ee=tt?`root cause already identified (${_t})`:zt>=re?`${jt} consecutive reads without an edit`:`${Kt} file edit(s) already made`;D(`${m.red} \u2716 Blocked read-only tool: cap fired, ${ee}${m.reset}`),y.canExecute=!1,y.errorResult={role:"tool",content:tt?`BLOCKED: root cause already identified (${_t}). Use edit_file to fix the issue \u2014 do not read more files.`:Dt?"BLOCKED: files already written \u2014 continue with write_file or edit_file to finish the remaining tasks. Do not read more files.":zt>=re?`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: ${Kt} 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>=J&&!qt){if(qt=!0,D(`${m.yellow} \u26A0 Investigation cap: ${jt} read-only calls without an edit \u2014 forcing implementation${m.reset}`),ye&&Le==="plan"){let Ee=[...k].reverse().find(Ot=>Ot.role==="assistant"),gt=typeof Ee?.content=="string"?Ee.content:"",Ve=Ko("implement",gt);Ve&&(j.push(Ve),k.push(Ve),He=0,bt=ls("implement"))}let ee;tt?ee=`[SYSTEM] Root cause was already identified (${_t}). Edit the file now \u2014 do not read more files.`:Tt?ee="[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.":ee="[SYSTEM] You have read enough files. Now implement your fix using edit_file.";let xe={role:"user",content:ee};j.push(xe),k.push(xe)}}if((y.fnName==="bash"||y.fnName==="ssh_exec")&&y.args&&y.args.command){let P=y.args.command.replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),q=cs(Zc,P);if(q===$y){D(`${m.yellow} \u26A0 Loop warning: same bash command run ${q}\xD7 \u2014 possible debug loop${m.reset}`);let F={role:"user",content:`[SYSTEM WARNING] Same bash command ${q}\xD7. Debug loop detected \u2014 try a different approach.`};j.push(F),k.push(F)}else if(q>=by){D(`${m.red} \u2716 Loop abort: same bash command run ${q}\xD7 \u2014 aborting runaway debug loop${m.reset}`),c&&(c.stop(),c=null),l(null),Ne(R,W,E,S,Ae,{suppressHint:!0}),Oe(j);return}}if(y.fnName==="ssh_exec"){It++;{let F=(ot[w]?.content??"").split(`
1383
- `).map(V=>V.trim()).find(V=>V.length>0&&!V.startsWith("**")&&(V.startsWith("EXIT")||/^[\w./-]+:\s/.test(V)||V.startsWith("bash:")||V.startsWith("sh:")))??"";if(F){if(F===Hi?ds++:(Hi=F,ds=1),ds===3&&!Tt){D(`${m.yellow} \u26A0 SSH repeated-error: "${F.slice(0,60)}" returned ${ds}\xD7 \u2014 nudging to change approach${m.reset}`);let V={role:"user",content:`[SYSTEM WARNING] The last ${ds} SSH commands all failed with the same error: "${F}". 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).`};j.push(V),k.push(V)}}else Hi="",ds=0}if(It>=jy){D(`${m.red} \u2716 SSH storm abort: ${It} consecutive ssh_exec calls \u2014 aborting${m.reset}`),c&&(c.stop(),c=null),l(null),Ne(R,W,E,S,Ae,{suppressHint:!0}),Oe(j);return}else if(It===so){{let F=at(),{messages:V}=nn(k,F);k=V}Tt=!0,Pi++,D(`${m.yellow} \u26A0 SSH storm warning (#${Pi}): ${It} consecutive ssh_exec calls \u2014 blocking further SSH${m.reset}`);let q={role:"user",content:tt?`[SYSTEM WARNING] ${It} consecutive SSH calls. Root cause identified (${_t}). Read the file that needs fixing, then edit it.`:`[SYSTEM WARNING] ${It} 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.`};j.push(q),k.push(q)}}else y.canExecute&&(It=0);if(y.fnName==="bash"&&y.canExecute){let F=(ot[w]?.content??"").split(`
1384
- `).map(V=>V.trim()).find(V=>V.length>0&&(V.startsWith("EXIT")||/^[\w./-]+:\s/.test(V)||V.startsWith("bash:")||V.startsWith("sh:")))??"";if(F){if(F===Yi?fs++:(Yi=F,fs=1),fs===3){D(`${m.yellow} \u26A0 Bash repeated-error: "${F.slice(0,60)}" returned ${fs}\xD7 \u2014 nudging to change approach${m.reset}`);let V={role:"user",content:`[SYSTEM WARNING] The last ${fs} bash commands all failed with the same error: "${F}". 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).`};j.push(V),k.push(V)}}else Yi="",fs=0}if(y.fnName==="bash"&&y.canExecute&&!Tc&&y.args?.command){let P=ot[w]?.content??"";if(/git\s+commit\b/.test(y.args.command)&&!P.startsWith("EXIT")&&!P.startsWith("ERROR")&&(/\[\S+\s+[a-f0-9]+\]/.test(P)||P.includes("files changed")||P.includes("file changed")||P.includes("insertions(+)")||P.includes("create mode"))){Tc=!0,zo=0,D(`${m.green} \u2713 Git commit detected \u2014 post-commit verification cap active (max 2 git status/diff/log)${m.reset}`);let V={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."};j.push(V),k.push(V)}}if(Tc&&y.fnName==="bash"&&y.args?.command&&/git\s+(status|diff|log|show)\b/.test(y.args.command)&&(zo++,zo>2)){D(`${m.yellow} \u26A0 Post-commit git verification blocked (call ${zo})${m.reset}`);let q={role:"user",content:"[SYSTEM] \u26A0 STOP: You already ran "+(zo-1)+" git verification commands after committing. The commit is confirmed. Write your final summary NOW and do not make any more tool calls."};j.push(q),k.push(q)}if(L&&y.fnName==="grep"&&z&&!z.startsWith("(no matches)")){let P=z.split(`
1385
- `);for(let q of P){let F=q.indexOf(":");if(F>0){let V=q.substring(0,F);V.startsWith("/")&&!V.includes(" ")&&nr.add(V)}else q.startsWith("/")&&!q.includes(" ")&&nr.add(q.trim())}}{let P=["grep","search_files","glob","glob_files"].includes(y.fnName);if(P&&L&&z&&(z.startsWith("(no matches)")||z.trim()===""||/^No matches found/.test(z.trim())||/^\(0 results\)/.test(z.trim()))){if(st++,st===3){D(`${m.yellow} \u26A0 3 consecutive empty local searches \u2014 injecting SSH pivot hint${m.reset}`);let F={role:"user",content:"[SYSTEM NOTE] 3 consecutive local searches returned no results. The target files may be on a remote server. If you have an SSH profile configured for this project's server, use ssh_exec to search there (e.g. ssh_exec with grep). Do not keep searching locally if the code does not exist on this machine."};j.push(F),k.push(F)}}else P&&L&&z&&z.trim().length>0&&(st=0)}if(L&&y.fnName==="grep"&&y.args&&y.args.pattern){let P=`${y.args.pattern}|${y.args.path||""}`,q=cs(xy,P);if(q===ky){D(`${m.yellow} \u26A0 Loop warning: grep pattern "${y.args.pattern.slice(0,40)}" run ${q}\xD7 \u2014 possible search loop${m.reset}`);let F={role:"user",content:`[SYSTEM WARNING] Same grep pattern ${q}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};j.push(F),k.push(F)}else if(q>=Sy){D(`${m.red} \u2716 Loop abort: grep pattern run ${q}\xD7 \u2014 aborting runaway search loop${m.reset}`),c&&(c.stop(),c=null),l(null),Ne(R,W,E,S,Ae,{suppressHint:!0}),Oe(j);return}if(y.args.path){let F=cs(ea,y.args.path),V=sn(ms,y.args.path)>=1;if(F===(V?1:vy)){let re=y.args.path.split("/").slice(-2).join("/");D(`${m.yellow} \u26A0 Loop warning: "${re}" grepped ${F}\xD7 with different patterns \u2014 context flood risk${m.reset}`);let fe={role:"user",content:V?`[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 ${F}\xD7 \u2014 use the search results already in context instead of searching again.`};j.push(fe),k.push(fe)}}}if(L&&(y.fnName==="glob"||y.fnName==="glob_files"||y.fnName==="search_files")&&y.args){if(z&&!z.startsWith("(no matches)")){let V=z.split(`
1386
- `);for(let J of V)(J.startsWith("/")&&!J.includes(" ")||!J.includes(":")&&!J.startsWith("["))&&sr.add(J.trim())}let P=y.args.pattern||y.args.query||y.args.path||"",q=cs(Ey,P);if(q===Ty){D(`${m.yellow} \u26A0 Loop warning: glob pattern "${P.slice(0,40)}" run ${q}\xD7 \u2014 possible search loop${m.reset}`);let V={role:"user",content:`[SYSTEM WARNING] Same glob/search pattern ${q}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};j.push(V),k.push(V)}else if(q>=Ry){D(`${m.red} \u2716 Loop abort: glob pattern run ${q}\xD7 \u2014 aborting runaway search loop${m.reset}`),c&&(c.stop(),c=null),l(null),Ne(R,W,E,S,Ae,{suppressHint:!0}),Oe(j);return}let F=P.replace(/\*+/g," ").replace(/[{}()\[\],.\/\\]/g," ").split(/\s+/).filter(V=>V.length>=4&&!/^\.(js|ts|py|json|md|yaml|yml|txt|css|html|sh)$/.test(V));for(let V of F){let J=V.toLowerCase();ji.has(J)||ji.set(J,new Set);let re=ji.get(J);if(re.add(P),re.size===Ay){D(`${m.red} \u2716 Glob core-term block: ${re.size} different patterns all searching for "${J}" \u2014 search loop${m.reset}`);let fe={role:"user",content:`[SYSTEM WARNING] You have searched for "${J}" using ${re.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.`};j.push(fe),k.push(fe)}else if(re.size===Cy){D(`${m.yellow} \u26A0 Glob core-term warning: ${re.size} different patterns searching for "${J}"${m.reset}`);let fe={role:"user",content:`[SYSTEM WARNING] ${re.size} different glob patterns all target "${J}". If previous searches returned no results, the file probably does not exist \u2014 stop searching and proceed with available information.`};j.push(fe),k.push(fe)}}}let Q=(y.args?.command||y.args?.cmd||y.args?.script||"").toLowerCase(),U=/\b(health|healthcheck|health-check|status|check|ping|validate|alive|ready)\b/.test(Q)||/\/(health|status|ping|ready|alive)\b/.test(Q);if(L&&(y.fnName==="bash"||y.fnName==="ssh_exec")&&U&&z.includes('"valid":true')){{let q=at();if(Gt(k,q).percentage>=60){let{messages:V,tokensRemoved:J}=nn(k,q);J>0&&(k=V,console.log(`${m.dim} [pre-stop-compress \u2014 ~${J} tokens freed before STOP injection, now ${Math.round(Gt(k,q).percentage)}%]${m.reset}`))}}let P={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.'};j.push(P),k.push(P),console.log(`${m.cyan} \u2713 Health-check stop signal detected \u2014 injecting STOP instruction${m.reset}`)}if(L&&(y.fnName==="bash"||y.fnName==="ssh_exec")&&Q&&/\bsed\s+-[ie]\b|\btee\b|\bcp\b|\bmv\b|\bpatch\b|\bdd\b|>\s*\S|\becho\b.*>|\bcat\b.*>|\bprintf\b.*>|\bpython[23]?\b.*open\b.*['"'w]|\bnpm\b.*run\b|\byarn\b.*run\b/.test(Q)&&(yn++,D(`${m.dim} [bash write detected: _bashModifiedFiles=${yn}]${m.reset}`)),z.startsWith("BLOCKED:")){if(Pn++,Pn>=Qc){D(`${m.red} \u2716 Loop abort: ${Pn} consecutive blocked calls \u2014 model not heeding BLOCKED messages${m.reset}`),c&&(c.stop(),c=null),l(null),Ne(R,W,E,S,Ae,{suppressHint:!0}),Oe(j);return}}else Pn=0;if(L)Mn=0,oa=!0;else if(Mn++,Mn===Py){D(`${m.yellow} \u26A0 Loop warning: ${Mn} consecutive tool errors \u2014 possible stuck loop${m.reset}`);let P={role:"user",content:`[SYSTEM WARNING] ${Mn} consecutive errors. Stuck loop \u2014 try fundamentally different approach or declare done.`};j.push(P),k.push(P)}else if(Mn>=Ly){D(`${m.red} \u2716 Loop abort: ${Mn} consecutive errors \u2014 aborting stuck loop${m.reset}`),c&&(c.stop(),c=null),l(null),Ne(R,W,E,S,Ae,{suppressHint:!0}),Oe(j);return}if(L&&y.fnName==="read_file"&&y.args&&y.args.path){S.add(y.args.path),oe.delete(y.args.path);let P=cs(ms,y.args.path);{let J=y.args.line_start!=null&&parseInt(y.args.line_start,10)||1,re=y.args.line_start!=null?parseInt(y.args.line_end,10)||J+350:350;An.has(y.args.path)||An.set(y.args.path,[]),An.get(y.args.path).push([J,re])}if(y._scrollWarn){let{sectionCount:J,path:re}=y._scrollWarn,fe={role:"user",content:`[SYSTEM WARNING] "${re}" \u2014 you have now read ${J} 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.`};j.push(fe),k.push(fe),D(`${m.yellow} \u26A0 Scroll warning: "${re.split("/").slice(-2).join("/")}" \u2014 ${J} sections read \u2014 use grep instead${m.reset}`)}let q=y.args.path.split("/").slice(-2).join("/"),F=!y.args?.line_start&&!y.args?.line_end,V=ye&&Le==="plan";if(!V&&F&&P===Oy){{let re=at();if(Gt(k,re).percentage>=60){let{messages:ee}=nn(k,re);k=ee}}D(`${m.yellow} \u26A0 Loop warning: "${q}" read unbounded ${P}\xD7 \u2014 use line_start/line_end${m.reset}`);let J={role:"user",content:`[SYSTEM WARNING] "${y.args.path}" read ${P}\xD7 without line ranges. Use line_start/line_end to read specific sections \u2014 do not re-read the full file.`};j.push(J),k.push(J)}else if(!V&&F&&P>=Ny){D(`${m.red} \u2716 Loop abort: "${q}" read unbounded ${P}\xD7 \u2014 aborting runaway read loop${m.reset}`),c&&(c.stop(),c=null),l(null),Ne(R,W,E,S,Ae,{suppressHint:!0}),Oe(j);return}}if(y.fnName==="spawn_agents"){let P=(z.match(/\bStatus: done\b/g)||[]).length;if((z.match(/\bStatus: truncated\b/g)||[]).length>0&&P===0){if(Ln++,Ln===Iy){D(`${m.yellow} \u26A0 Swarm warning: all sub-agents hit iteration limit ${Ln}\xD7 in a row${m.reset}`);let F={role:"user",content:`[SYSTEM WARNING] Sub-agents truncated ${Ln}\xD7 in a row. Stop spawning \u2014 try different approach or report findings.`};j.push(F),k.push(F)}else if(Ln>=Dy){console.log(`${m.red} \u2716 Swarm abort: all sub-agents hit iteration limit ${Ln}\xD7 \u2014 aborting stuck swarm${m.reset}`),c&&(c.stop(),c=null),l(null),Ne(R,W,E,S,Ae,{suppressHint:!0}),Oe(j);return}}else P>0&&(Ln=0)}}{let y=ot.reduce((z,C)=>z+(typeof C.content=="string"?C.content.length:0),0);if(y>2e5){let z=ot.map((C,L)=>({i:L,len:typeof C.content=="string"?C.content.length:0})).sort((C,L)=>L.len-C.len);for(let{i:C,len:L}of z){if(y<=2e5)break;let Q=y-2e5,U=Math.max(L-Q,500);U<L&&typeof ot[C].content=="string"&&(ot[C]={...ot[C],content:ot[C].content.substring(0,U)+`
1387
- ...(truncated ${L-U} chars \u2014 per-message budget)`},y-=L-U)}}}for(let w of ot)j.push(w),k.push(w);if(!tt)for(let w=0;w<ot.length;w++){if(!me[w]||me[w].fnName!=="ssh_exec")continue;let y=ot[w];if(!y||typeof y.content!="string")continue;let z=vc(y.content);if(z){tt=!0,_t=z.slice(0,120),jt=0,qt=!1,zt=0,D(`${m.yellow} \u26A1 Root cause detected: ${_t} \u2014 fix phase (read budget: 3)${m.reset}`);let C={role:"user",content:`[SYSTEM] Root cause identified: ${_t}. Read only the file that needs fixing, then edit it. Do not read other files.`};j.push(C),k.push(C);break}}for(let w=0;w<ot.length;w++){let y=me[w];if(!y)continue;let z=typeof ot[w]?.content=="string"?ot[w].content:"";if(y.fnName==="create_task"){let C=z.match(/Task #(\d+) created/),L=typeof y.args?.subject=="string"?y.args.subject:"";C&&L&&rr.set(C[1],L)}else if((y.fnName==="write_file"||y.fnName==="edit_file")&&!z.startsWith("BLOCKED:")&&z.trim().length>0){let L=(typeof y.args?.path=="string"?y.args.path:typeof y.args?.file_path=="string"?y.args.file_path:"").split("/").pop().toLowerCase(),Q=L.split(/[._\-/]/).filter(U=>U.length>2);for(let[U,ue]of rr){if(ir.has(U))continue;let P=ue.toLowerCase().split(/\W+/).filter(F=>F.length>3);Q.filter(F=>P.some(V=>V.includes(F)||F.includes(V))).length>=1&&(ir.add(U),D(`${m.green} \u2714 Auto-matched task #${U} to ${L}: ${ue.slice(0,60)}${m.reset}`))}}}{let w=at();if(Gt(k,w).percentage>=78){let{messages:z,tokensRemoved:C}=nn(k,w);C>0&&(k=z,console.log(`${m.dim} [auto-compressed \u2014 ~${C} tokens freed, now ${Math.round(Gt(k,w).percentage)}%]${m.reset}`))}}if(er()&&!s.skillLoop&&(me.some(y=>y&&["write_file","edit_file","patch_file"].includes(y.fnName))?we=0:(we===0&&(ge=E.size),we++),we>=9&&R>=4&&E.size===ge)){D(`${m.green} \u2713 Stagnation exit: ${we} read-only iterations, no new file changes${m.reset}`),process.stdout.isTTY&&process.stderr.write(`${m.yellow} \u26A0 Stagnation detected: ${we} iterations without edits \u2014 exiting. The model investigated but did not apply changes.${m.reset}
1388
- `),c&&(c.stop(),c=null),l(null),Ne(R,W,E,S,Ae),Oe(j);break e}let cu=ZE();if(cu){let w={role:"user",content:`[User note mid-run]: ${cu}`};j.push(w),k.push(w),console.log(`${m.cyan} \u270E Context added${m.reset}`)}}if(He>=bt){if(c&&(c.stop(),c=null),l(null),Ne(R,W,E,S,Ae),Oe(j),Ni(j),ye&&Le==="plan"){let lt=[...j].reverse().find(ze=>ze.role==="assistant"),ct=typeof lt?.content=="string"?lt.content:"",wn=Ko("implement",ct);if(wn){j.push(wn),k=[{role:"system",content:await Bc()},...j],bt=ls("implement"),D(`${m.yellow} \u26A0 Plan budget exhausted \u2014 auto-transitioning to implement${m.reset}`);continue e}}else if(ye&&Le==="verify"){D(`${m.yellow} \u26A0 Verify budget exhausted \u2014 completing session${m.reset}`);break e}let{getActiveProviderName:_e}=Ze();if(_e()==="ollama"&&sa<nu){if(E.size===0&&!oa){console.log(`${m.yellow} \u26A0 Max iterations reached with no progress. Stopping.${m.reset}`);break e}sa++,bt=20,console.log(`${m.dim} \u2500\u2500 auto-extending (+20 turns, ext ${sa}/${nu}) \u2500\u2500${m.reset}`);continue e}if(console.log(`
1389
- ${m.yellow}\u26A0 Max iterations reached.${m.reset}`),await Bg(" Continue for 20 more turns?")){bt=20;continue e}console.log(`${m.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${m.reset}`)}break e}}ty.exports={processInput:fT,clearConversation:nT,getConversationLength:oT,getConversationMessages:rT,setConversationMessages:iT,setAbortSignalGetter:ME,setMaxIterations:NE,invalidateSystemPromptCache:Mc,clearToolFilterCache:BE,getCachedFilteredTools:Kg,buildSystemPrompt:Bc,splitSystemPrompt:tT,SYSTEM_PROMPT_DYNAMIC_BOUNDARY:Fc,getProjectContextHash:Xg,buildUserContent:Gg,_detectImageURLs:Wg,_downloadImageURL:Hg,_grabClipboardImage:Yg,detectFrustration:zg,detectAndTruncateLoop:Ac,injectMidRunNote:JE,resetSessionTracking:ey}});var Ze=Z((N1,iy)=>{var{OllamaProvider:pT}=Iu(),{OpenAIProvider:hT}=Fu(),{AnthropicProvider:mT}=Hu(),{GeminiProvider:gT}=Ku(),{LocalProvider:yT}=Ju(),{checkBudget:wT}=Nr(),Yc={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"}},Wc=(process.env.OLLAMA_FALLBACK_CHAIN||"").split(",").map(t=>t.trim()).filter(Boolean),sy={};for(let[t,e]of Object.entries(Yc))for(let s of Object.values(e))sy[s]=t;function Hc(t,e){let s=sy[t];return s&&Yc[s][e]||t}var nt={},$t=null,Be=null,ar=[];function Ft(){if(Object.keys(nt).length>0)return;to("ollama",new pT),to("openai",new hT),to("anthropic",new mT),to("gemini",new gT),to("local",new yT);let t=process.env.DEFAULT_PROVIDER||"ollama",e=process.env.DEFAULT_MODEL||null;nt[t]?($t=t,Be=e||nt[t].defaultModel):($t="ollama",Be="kimi-k2.5");let s=process.env.FALLBACK_CHAIN;s&&(ar=s.split(",").map(n=>n.trim()).filter(Boolean))}function to(t,e){nt[t]=e}function _T(t){return Ft(),nt[t]||null}function Gc(){return Ft(),nt[$t]||null}function $T(){return Ft(),$t}function bT(){return Ft(),Be}function xT(){Ft();let t=Gc();if(!t)return{id:Be,name:Be,provider:$t};let e=t.getModel(Be);return e?{...e,provider:$t}:{id:Be,name:Be,provider:$t}}function oy(t){if(!t)return{provider:null,model:null};let e=t.indexOf(":");if(e>0){let s=t.slice(0,e);if(nt[s]||["ollama","openai","anthropic","gemini","local"].includes(s))return{provider:s,model:t.slice(e+1)}}return{provider:null,model:t}}function kT(t){Ft();let{provider:e,model:s}=oy(t);if(e){let o=nt[e];return o&&(o.getModel(s)||e==="local"||e==="ollama")?($t=e,Be=s,Vi(),!0):!1}let n=Gc();if(n&&n.getModel(s))return Be=s,Vi(),!0;for(let[o,r]of Object.entries(nt))if(r.getModel(s))return $t=o,Be=s,Vi(),!0;return!1}function Vi(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=Ql();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=en();t()}catch{}}function ST(){Ft();let t=new Set;for(let e of Object.values(nt))for(let s of e.getModelNames())t.add(s);return Array.from(t)}function vT(){return Ft(),Object.entries(nt).map(([t,e])=>({provider:t,configured:e.isConfigured(),models:Object.values(e.getModels()).map(s=>({...s,active:t===$t&&s.id===Be}))}))}function ET(){Ft();let t=[];for(let[e,s]of Object.entries(nt)){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 TT(t){ar=Array.isArray(t)?t:[]}function RT(){return[...ar]}function ny(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 ry(t){let e=[$t,...ar.filter(r=>r!==$t)],s,n=0,o=0;for(let r=0;r<e.length;r++){let i=e[r],a=nt[i];if(!a||!a.isConfigured())continue;o++;let l=wT(i);if(!l.allowed){n++,s=new Error(`Budget limit reached for ${i}: $${l.spent.toFixed(2)} / $${l.limit.toFixed(2)}`);continue}try{let c=r>0,u=c?Hc(Be,i):Be;return c&&u!==Be&&process.stderr.write(` [fallback: ${i}:${u}]
1390
- `),await t(a,i,u)}catch(c){if(s=c,!ny(c)||r>=e.length-1)throw c;if(i==="ollama"&&Wc.length>0){let u=isFallback?Hc(Be,i):Be;for(let d of Wc)if(d!==u)try{return process.stderr.write(` [ollama fallback: ${d}]
1391
- `),await t(a,i,d)}catch(f){if(s=f,!ny(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 CT(t,e,s={}){return Ft(),ry((n,o,r)=>n.stream(t,e,{model:r,signal:s.signal,...s}))}async function AT(t,e,s={}){if(Ft(),s.provider){let n=nt[s.provider];if(!n||!n.isConfigured())throw new Error(`Provider '${s.provider}' is not available`);let o={model:s.model||Be,...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 ry(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 OT(){Ft();let t=[];for(let[e,s]of Object.entries(nt))s.isConfigured()&&t.push({name:e,models:Object.values(s.getModels())});return t}function NT(){for(let t of Object.keys(nt))delete nt[t];$t=null,Be=null,ar=[]}iy.exports={registerProvider:to,getProvider:_T,getActiveProvider:Gc,getActiveProviderName:$T,getActiveModelId:bT,getActiveModel:xT,setActiveModel:kT,getModelNames:ST,parseModelSpec:oy,listProviders:vT,listAllModels:ET,callStream:CT,callChat:AT,getConfiguredProviders:OT,setFallbackChain:TT,getFallbackChain:RT,resolveModelForProvider:Hc,MODEL_EQUIVALENTS:Yc,OLLAMA_FALLBACK_MODELS:Wc,_reset:NT}});var{C:Y}=Ke(),MT=Ze(),{TOOL_DEFINITIONS:ay}=Rs(),{saveRoutingConfig:PT}=Hs(),Xc=[{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:"read-partial",category:"file-ops",prompt:"Read only lines 20 to 40 of src/index.js \u2014 I need to see that specific range.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("index")&&(typeof t.line_start=="number"||typeof t.start_line=="number")},{id:"glob-ts-defs",category:"file-ops",prompt:"Find all TypeScript type definition files (*.d.ts) anywhere in the project.",expectedTool:"glob",validateArgs:t=>typeof t.pattern=="string"&&t.pattern.includes(".d.ts")},{id:"write-gitignore",category:"file-ops",prompt:"Create a .gitignore file at the project root that ignores node_modules/ and dist/.",expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes(".gitignore")&&typeof t.content=="string"&&t.content.includes("node_modules")},{id:"edit-version-bump",category:"file-ops",prompt:'In package.json, change the version field from "1.0.0" to "1.1.0".',expectedTool:["edit_file","patch_file"],validateArgs:t=>!!(t.path&&t.path.includes("package"))},{id:"grep-with-filter",category:"search",prompt:"Search for all calls to require() but only inside .js files in the cli/ directory.",expectedTool:["grep","search_files"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("require")},{id:"no-tool-http-port",category:"reasoning",prompt:"What is the default port used by the HTTP protocol?",expectedTool:null,validateArgs:()=>!0},{id:"bash-node-version",category:"shell",prompt:"Check which version of Node.js is currently installed on this system.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("node")&&(t.command.includes("--version")||t.command.includes("-v"))},{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}],ly=[{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)}],Qi=[...Xc,...ly],zc=["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 LT(){try{let s=require("path").join(require("os").homedir(),".nex-code","benchmark-results.json");if(!require("fs").existsSync(s))return zc;let n=JSON.parse(require("fs").readFileSync(s,"utf-8"));return!Array.isArray(n)||n.length===0?zc: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 zc}}var Vc=LT(),IT=["minimax-m2.7:cloud","qwen3-coder:480b","devstral-2:123b"],cy=(()=>{let t=Vc.slice(0,3);return t.length>=3?t:IT})(),DT=14,Ji={producedToolCall:.2,correctTool:.35,validArgs:.3,schemaCompliant:.15},jT="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 Kc(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:jT},{role:"user",content:t.prompt}],o=Date.now();try{let r=await MT.callChat(n,ay,{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],l=a.function?.name||"unknown",c=a.function?.arguments||{};s.producedToolCall=!0,s.toolCalled=l;let u=Array.isArray(t.expectedTool)?t.expectedTool:[t.expectedTool];if(s.correctTool=u.includes(l),s.correctTool){let d=ay.find(f=>f.function?.name===l);if(s.validArgs=!!t.validateArgs(c,d),d){let f=d.function?.parameters||{},p=f.required||[],h=Object.keys(f.properties||{});s.schemaCompliant=p.every(g=>c[g]!==void 0)&&Object.keys(c).every(g=>h.includes(g))}}}}catch(r){s.latencyMs=Date.now()-o,s.error=r.message.slice(0,120)}return s}function no(t){return t.error?0:((t.producedToolCall?Ji.producedToolCall:0)+(t.correctTool?Ji.correctTool:0)+(t.validArgs?Ji.validArgs:0)+(t.schemaCompliant?Ji.schemaCompliant:0))*100}var uy={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 Jc(t){return Object.entries(t).map(([e,s])=>{let n=s.map(no),o=n.reduce((a,l)=>a+l,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 l=s.filter(u=>uy[u.category]===a);if(l.length===0)continue;let c=l.map(no).reduce((u,d)=>u+d,0)/l.length;i[a]=Math.round(c*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,l)=>a+l.latencyMs,0)/s.length),errorCount:s.filter(a=>a.error).length,categoryScores:i,results:s}}).sort((e,s)=>s.score-e.score)}function dy(t){let e={};for(let a of["coding","frontend","sysadmin","data","agentic","plan","verify"]){let l=t.filter(g=>g.categoryScores[a]!==void 0&&g.score>=65).sort((g,_)=>_.categoryScores[a]-g.categoryScores[a]);if(l.length===0)continue;let u=(l[0]?.results||[]).filter(g=>uy[g.category]===a).length;if(u<4)continue;let d=l[0],f=l[1];if(d.categoryScores[a]>=95&&u<8&&f&&d.categoryScores[a]-f.categoryScores[a]<15){let _=t.filter(b=>b.categoryScores[a]!==void 0).find(b=>b.categoryScores[a]<95);_&&(e[a]={model:_.model,score:_.categoryScores[a],avgLatency:_.avgLatency,_flukePrevented:!0});continue}let h=l.filter(g=>d.categoryScores[a]-g.categoryScores[a]<=5).sort((g,_)=>g.avgLatency-_.avgLatency)[0];e[a]={model:h.model,score:h.categoryScores[a],avgLatency:h.avgLatency}}return e}function fy(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((u,d)=>u+d.width+1,0)+1,r="\u2500".repeat(o);console.log(`
1392
- ${Y.bold}${s}${Y.reset}`),console.log(r);let i=n.map(u=>u.label.padEnd(u.width)).join(" ");if(console.log(`${Y.dim}${i}${Y.reset}`),console.log(r),t.forEach((u,d)=>{let f=String(d+1).padEnd(n[0].width),p=u.model.slice(0,n[1].width).padEnd(n[1].width),h=String(u.score).padEnd(n[2].width),g=`${u.toolCallRate}%`.padEnd(n[3].width),_=`${u.correctRate}%`.padEnd(n[4].width),b=`${u.validArgsRate}%`.padEnd(n[5].width),O=`${u.schemaRate}%`.padEnd(n[6].width),M=`${(u.avgLatency/1e3).toFixed(1)}s`.padEnd(n[7].width),v=u.errorCount>0?`${Y.red}${u.errorCount}${Y.reset}`:`${Y.dim}0${Y.reset}`,T=u.score>=80?Y.green:u.score>=60?Y.yellow:Y.red,N=d===0?`${Y.yellow}${f}${Y.reset}`:`${Y.dim}${f}${Y.reset}`;console.log(`${N} ${T}${p}${Y.reset} ${Y.bold}${T}${h}${Y.reset} ${g} ${_} ${b} ${O} ${Y.dim}${M}${Y.reset} ${v}`)}),console.log(r),t.length>0){let u=t[0];if(console.log(`
1393
- ${Y.bold}${Y.green}Winner: ${u.model}${Y.reset} score ${u.score}/100`),t.length>1){let d=(u.score-t[1].score).toFixed(1);console.log(`${Y.dim}+${d} pts over ${t[1].model}${Y.reset}`)}}let a=t.filter(u=>u.results.some(d=>!d.error&&(!d.correctTool||!d.validArgs)));if(a.length>0){console.log(`${Y.bold}Failing tasks:${Y.reset}`);for(let u of a){let d=u.results.filter(h=>!h.error&&(!h.correctTool||!h.validArgs));if(d.length===0)continue;let f=u.model.slice(0,22),p=d.map(h=>{if(!h.correctTool){let g=h.toolCalled||"(none)";return`${Y.dim}${h.taskId}${Y.reset} ${Y.red}\u2192${g}${Y.reset}`}return`${Y.dim}${h.taskId}${Y.reset} ${Y.yellow}bad-args${Y.reset}`});console.log(` ${Y.dim}${f.padEnd(22)}${Y.reset} ${p.join(" ")}`)}console.log()}let l=["coding","frontend","sysadmin","data","agentic"];if(t.some(u=>Object.keys(u.categoryScores).length>1)){console.log(`
1394
- ${Y.bold}Best model per task type:${Y.reset}`);for(let u of l){let d=t.filter(g=>g.categoryScores[u]!==void 0).sort((g,_)=>_.categoryScores[u]-g.categoryScores[u]);if(d.length===0)continue;let f=d[0],p=f.categoryScores[u],h=p>=80?Y.green:p>=60?Y.yellow:Y.red;console.log(` ${Y.dim}${u.padEnd(10)}${Y.reset} ${h}${f.model}${Y.reset} ${Y.dim}${p}/100${Y.reset}`)}}console.log()}function py(t){if(!(!t||t.length<2))try{let e=dy(t),{loadRoutingConfig:s}=Hs(),n=s(),o={...n},r=[],i=new Set(["plan","verify"]);for(let[a,{model:l,score:c}]of Object.entries(e)){let u=i.has(a),d=u?n.phases&&n.phases[a]:n[a];d&&d!==l&&!t.find(p=>p.model===d)||(u?(o.phases||(o.phases={}),o.phases[a]!==l&&(o.phases[a]=l,r.push(`phase:${a}\u2192${l}`))):o[a]!==l&&(o[a]=l,r.push(`${a}\u2192${l}`)))}r.length>0&&(PT(o),console.log(`
1395
- ${Y.dim} Routing updated: ${r.join(", ")}${Y.reset}`),console.log(`
1396
- ${Y.green}\u{1F4A1} The best models have been saved to ~/.nex-code/.env and will be automatically used by nex-code from now on.${Y.reset}`))}catch{}}async function qT({models:t,quick:e=!1,onProgress:s,parallelModels:n=1}={}){let o=e?Xc.slice(0,DT):Qi,r=t?.length>0?t:e?cy:Vc,i={};for(let l of r)i[l]=[];if(n<=1)for(let l of r)for(let c of o){s?.({model:l,task:c.id,done:!1});let u=await Kc(c,l);i[l].push(u),s?.({model:l,task:c.id,done:!0,score:no(u),error:u.error})}else{let l=Math.min(n,r.length),c=[...r],u=Array.from({length:l},async()=>{for(;c.length>0;){let d=c.shift();if(!d)break;for(let f of o){s?.({model:d,task:f.id,done:!1});let p=await Kc(f,d);i[d].push(p),s?.({model:d,task:f.id,done:!0,score:no(p),error:p.error})}}});await Promise.all(u)}let a=Jc(i);return fy(a,o.length),py(a),a}async function FT({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 Qi){s?.({model:i,task:a.id,done:!1});let l=await Kc(a,i);n[i].push(l),s?.({model:i,task:a.id,done:!0,score:no(l),error:l.error})}}let r=[...Jc(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),fy(r,Qi.length),py(r),r}var Zi=[{id:"simple_question",name:"Simple Convergence",prompt:"What is 2+2?",maxTurns:3,successCriteria:["4"]}];function hy(t){let e=require("fs"),n=require("path").join(t||process.cwd(),".nex","benchmark-config.json");if(!e.existsSync(n))return console.log(`${Y.yellow}No scenarios configured.${Y.reset} Create ${Y.dim}.nex/benchmark-config.json${Y.reset} to define your benchmark scenarios.
1397
+ `),_s=null}if(!co.skipSummaries){let w=Jy.filter((T,M)=>!(we[M]&&we[M].fnName==="ask_user"));for(let T of w)console.log(T);let y=we.filter(T=>T&&T.fnName!=="ask_user").map(T=>T.fnName),K=vy.record(0,y,Y,x);K&&HE(K)}for(let w of we){if(w.canExecute||!w.errorResult)continue;let y=typeof w.errorResult.content=="string"?w.errorResult.content:"";if((y.startsWith("BLOCKED:")||y.startsWith("PLAN MODE:")||y.startsWith("PLAN PHASE:"))&&(Mn++,Mn>=lu)){j(`${h.red} \u2716 Loop abort: ${Mn} consecutive blocked calls (pre-execution) \u2014 model not heeding BLOCKED messages${h.reset}`),c&&(c.stop(),c=null),l(null),Ne(N,q,x,Y,Oe,{suppressHint:!0}),Ae(L);return}}for(let w=0;w<we.length;w++){let y=we[w];if(!y.canExecute)continue;let K=ot[w].content,T=K.split(`
1398
+ `)[0],M=!T.startsWith("ERROR")&&!T.startsWith("CANCELLED")&&!T.startsWith("Command failed")&&!T.startsWith("EXIT");if(!M&&(y.fnName==="edit_file"||y.fnName==="patch_file")&&y.args?.path&&T.includes("old_text not found")){let C=Lt.get(y.args.path)||0;Lt.set(y.args.path,C+1)}if(!M&&y.fnName==="bash"&&lr.size>0){let C=(y.args?.command||"").toLowerCase();if(/\b(test|jest|vitest|pytest|mocha|tsc|build|lint|eslint|check)\b/.test(C))for(let[F]of lr)Lt.has(F)||(Lt.set(F,1),j(`${h.cyan} \u21A9 Test failure \u2014 queuing recovery re-read: "${F.split("/").pop()}"${h.reset}`))}if(!M&&(y.fnName==="read_file"||y.fnName==="edit_file")&&/file not found|does not exist|ENOENT/i.test(T)){if(Rn++,Rn>=2){j(`${h.yellow} \u26A0 File-not-found streak: ${Rn} consecutive misses \u2014 forcing search${h.reset}`);let C={role:"user",content:`[SYSTEM] ${Rn} 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.`};L.push(C),S.push(C)}}else M&&(y.fnName==="read_file"||y.fnName==="edit_file"||y.fnName==="search_files"||y.fnName==="glob_files")&&(Rn=0);if(M&&y.fnName==="write_file"&&y.args?.path){let C=y.args.path.split("/").pop(),D=y.args.path.includes("/tests/")||y.args.path.includes("\\tests\\");if(/^(test_|demo_|temp_|tmp_|scratch_)/.test(C)&&!D){j(`${h.yellow} \u26A0 Temp file: "${C}" \u2014 delete with bash rm when done to keep the workspace clean${h.reset}`);let V={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.`};L.push(V),S.push(V)}}if(M&&["write_file","edit_file","patch_file"].includes(y.fnName)&&y.args&&y.args.path){Lt.delete(y.args.path),x.add(y.args.path);for(let F of ms)!F.done&&y.args.path.endsWith(F.file.split("/").pop())&&(F.done=!0,j(`${h.green} \u2713 TODO done: ${F.file}${h.reset}`));let C=us(Ey,y.args.path),D=y.args.path.split("/").slice(-2).join("/");if(C===Ty){j(`${h.yellow} \u26A0 Loop warning: "${D}" edited ${C}\xD7 \u2014 possible edit loop${h.reset}`);let F={role:"user",content:`[SYSTEM WARNING] "${y.args.path}" edited ${C}\xD7. One more edit max, then move on.`};L.push(F),S.push(F)}else if(C>=Ry){j(`${h.red} \u2716 Loop abort: "${D}" edited ${C}\xD7 \u2014 aborting to prevent runaway loop${h.reset}`),c&&(c.stop(),c=null),l(null),Ne(N,q,x,Y,Oe,{suppressHint:!0}),Ae(L);return}}if(M&&y.canExecute&&_e&&(On=0),M&&y.canExecute&&!(_e&&Le==="plan")){let C=["read_file","grep","search_files","glob","list_directory","ssh_exec","find_files"];if(["write_file","edit_file","patch_file"].includes(y.fnName)){jt=0,qt=!1,zt=0,Kt++;let te=y.args?.path||y.args?.file_path;te&&(Pc(mn,te,1),Cn.delete(te),ke.add(te))}else if(C.includes(y.fnName)&&(jt++,qt&&zt++,_e&&Le==="implement"&&y.fnName==="read_file"&&ms.length>0)){let te=y.args?.path||y.args?.file_path||"",$e=ms.find(Te=>!Te.done&&te.endsWith(Te.file.split("/").pop()));if($e){let Te={role:"user",content:`[TODO OBSERVER] You already analyzed "${$e.file}" in the plan phase. Action: ${$e.action}
1399
+ Do NOT re-read \u2014 apply the edit directly with edit_file.`};L.push(Te),S.push(Te),j(`${h.yellow} \u26A0 TODO nudge: ${$e.file} \u2014 already analyzed, edit directly${h.reset}`)}}let F=n.postEditCap,V=_e&&Le==="implement"?Math.min(cu,10):cu,X=nt?8:Dt?Kt>0?6:10:Kt>0?F:V,re=6,fe=!_e&&qt&&(nt&&zt>=re||Dt&&Kt>=3&&zt>=re||zt>=re);if(Vo<2&&!qt&&jt>=3&&x.size===0){let te=parseInt(process.env.NEX_TASK_TIMEOUT_MS,10)||0,$e=Date.now()-Oe,Te=Vo===0?.4:.65;if(te>0&&$e>te*Te){Vo++;let gt=Math.round($e/6e4),Je=Math.round($e/te*100);j(`${h.yellow} \u26A0 Time nudge #${Vo}: ${gt}m elapsed (${Je}%), ${jt} reads, 0 edits${h.reset}`);let Ot={role:"user",content:Vo===1?`[SYSTEM] ${Je}% of available time used and no files edited yet. Start implementing now using edit_file or write_file \u2014 you have enough context.`:`[SYSTEM] ${Je}% of time used, still no edits. You MUST write code NOW. Use edit_file or write_file immediately \u2014 any further reading will be blocked.`};L.push(Ot),S.push(Ot)}}if(fe&&C.includes(y.fnName)){let te=nt?`root cause already identified (${_t})`:zt>=re?`${jt} consecutive reads without an edit`:`${Kt} file edit(s) already made`;j(`${h.red} \u2716 Blocked read-only tool: cap fired, ${te}${h.reset}`),y.canExecute=!1,y.errorResult={role:"tool",content:nt?`BLOCKED: root cause already identified (${_t}). Use edit_file to fix the issue \u2014 do not read more files.`:Dt?"BLOCKED: files already written \u2014 continue with write_file or edit_file to finish the remaining tasks. Do not read more files.":zt>=re?`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: ${Kt} 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&&!qt){if(qt=!0,j(`${h.yellow} \u26A0 Investigation cap: ${jt} read-only calls without an edit \u2014 forcing implementation${h.reset}`),_e&&Le==="plan"){let Te=[...S].reverse().find(Ot=>Ot.role==="assistant"),gt=typeof Te?.content=="string"?Te.content:"",Je=Zo("implement",gt);Je&&(L.push(Je),S.push(Je),qe=0,bt=cs("implement"))}let te;nt?te=`[SYSTEM] Root cause was already identified (${_t}). Edit the file now \u2014 do not read more files.`:Tt?te="[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.":te="[SYSTEM] You have read enough files. Now implement your fix using edit_file.";let $e={role:"user",content:te};L.push($e),S.push($e)}}if((y.fnName==="bash"||y.fnName==="ssh_exec")&&y.args&&y.args.command){let C=y.args.command.replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),D=us(au,C);if(D===Cy){j(`${h.yellow} \u26A0 Loop warning: same bash command run ${D}\xD7 \u2014 possible debug loop${h.reset}`);let F={role:"user",content:`[SYSTEM WARNING] Same bash command ${D}\xD7. Debug loop detected \u2014 try a different approach.`};L.push(F),S.push(F)}else if(D>=Ay){j(`${h.red} \u2716 Loop abort: same bash command run ${D}\xD7 \u2014 aborting runaway debug loop${h.reset}`),c&&(c.stop(),c=null),l(null),Ne(N,q,x,Y,Oe,{suppressHint:!0}),Ae(L);return}}if(y.fnName==="ssh_exec"){It++;{let F=(ot[w]?.content??"").split(`
1400
+ `).map(V=>V.trim()).find(V=>V.length>0&&!V.startsWith("**")&&(V.startsWith("EXIT")||/^[\w./-]+:\s/.test(V)||V.startsWith("bash:")||V.startsWith("sh:")))??"";if(F){if(F===Vi?fs++:(Vi=F,fs=1),fs===3&&!Tt){j(`${h.yellow} \u26A0 SSH repeated-error: "${F.slice(0,60)}" returned ${fs}\xD7 \u2014 nudging to change approach${h.reset}`);let V={role:"user",content:`[SYSTEM WARNING] The last ${fs} SSH commands all failed with the same error: "${F}". 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).`};L.push(V),S.push(V)}}else Vi="",fs=0}if(It>=zy){j(`${h.red} \u2716 SSH storm abort: ${It} consecutive ssh_exec calls \u2014 aborting${h.reset}`),c&&(c.stop(),c=null),l(null),Ne(N,q,x,Y,Oe,{suppressHint:!0}),Ae(L);return}else if(It===ao){{let F=at(),{messages:V}=nn(S,F);S=V}Tt=!0,qi++,j(`${h.yellow} \u26A0 SSH storm warning (#${qi}): ${It} consecutive ssh_exec calls \u2014 blocking further SSH${h.reset}`);let D={role:"user",content:nt?`[SYSTEM WARNING] ${It} consecutive SSH calls. Root cause identified (${_t}). Read the file that needs fixing, then edit it.`:`[SYSTEM WARNING] ${It} 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.`};L.push(D),S.push(D)}}else y.canExecute&&(It=0);if(y.fnName==="bash"&&y.canExecute){let F=(ot[w]?.content??"").split(`
1401
+ `).map(V=>V.trim()).find(V=>V.length>0&&(V.startsWith("EXIT")||/^[\w./-]+:\s/.test(V)||V.startsWith("bash:")||V.startsWith("sh:")))??"";if(F){if(F===Ji?ps++:(Ji=F,ps=1),ps===3){j(`${h.yellow} \u26A0 Bash repeated-error: "${F.slice(0,60)}" returned ${ps}\xD7 \u2014 nudging to change approach${h.reset}`);let V={role:"user",content:`[SYSTEM WARNING] The last ${ps} bash commands all failed with the same error: "${F}". 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).`};L.push(V),S.push(V)}}else Ji="",ps=0}if(y.fnName==="bash"&&y.canExecute&&!Lc&&y.args?.command){let C=ot[w]?.content??"";if(/git\s+commit\b/.test(y.args.command)&&!C.startsWith("EXIT")&&!C.startsWith("ERROR")&&(/\[\S+\s+[a-f0-9]+\]/.test(C)||C.includes("files changed")||C.includes("file changed")||C.includes("insertions(+)")||C.includes("create mode"))){Lc=!0,Jo=0,j(`${h.green} \u2713 Git commit detected \u2014 post-commit verification cap active (max 2 git status/diff/log)${h.reset}`);let V={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."};L.push(V),S.push(V)}}if(Lc&&y.fnName==="bash"&&y.args?.command&&/git\s+(status|diff|log|show)\b/.test(y.args.command)&&(Jo++,Jo>2)){j(`${h.yellow} \u26A0 Post-commit git verification blocked (call ${Jo})${h.reset}`);let D={role:"user",content:"[SYSTEM] \u26A0 STOP: You already ran "+(Jo-1)+" git verification commands after committing. The commit is confirmed. Write your final summary NOW and do not make any more tool calls."};L.push(D),S.push(D)}if(M&&y.fnName==="grep"&&K&&!K.startsWith("(no matches)")){let C=K.split(`
1402
+ `);for(let D of C){let F=D.indexOf(":");if(F>0){let V=D.substring(0,F);V.startsWith("/")&&!V.includes(" ")&&ir.add(V)}else D.startsWith("/")&&!D.includes(" ")&&ir.add(D.trim())}}{let C=["grep","search_files","glob","glob_files"].includes(y.fnName);if(C&&M&&K&&(K.startsWith("(no matches)")||K.trim()===""||/^No matches found/.test(K.trim())||/^\(0 results\)/.test(K.trim()))){if(io++,io===3){j(`${h.yellow} \u26A0 3 consecutive empty local searches \u2014 injecting SSH pivot hint${h.reset}`);let F={role:"user",content:"[SYSTEM NOTE] 3 consecutive local searches returned no results. The target files may be on a remote server. If you have an SSH profile configured for this project's server, use ssh_exec to search there (e.g. ssh_exec with grep). Do not keep searching locally if the code does not exist on this machine."};L.push(F),S.push(F)}}else C&&M&&K&&K.trim().length>0&&(io=0)}if(M&&y.fnName==="grep"&&y.args&&y.args.pattern){let C=`${y.args.pattern}|${y.args.path||""}`,D=us(Oy,C);if(D===Ny){j(`${h.yellow} \u26A0 Loop warning: grep pattern "${y.args.pattern.slice(0,40)}" run ${D}\xD7 \u2014 possible search loop${h.reset}`);let F={role:"user",content:`[SYSTEM WARNING] Same grep pattern ${D}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};L.push(F),S.push(F)}else if(D>=My){j(`${h.red} \u2716 Loop abort: grep pattern run ${D}\xD7 \u2014 aborting runaway search loop${h.reset}`),c&&(c.stop(),c=null),l(null),Ne(N,q,x,Y,Oe,{suppressHint:!0}),Ae(L);return}if(y.args.path){let F=us(ia,y.args.path),V=sn(ys,y.args.path)>=1;if(F===(V?1:Py)){let re=y.args.path.split("/").slice(-2).join("/");j(`${h.yellow} \u26A0 Loop warning: "${re}" grepped ${F}\xD7 with different patterns \u2014 context flood risk${h.reset}`);let fe={role:"user",content:V?`[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 ${F}\xD7 \u2014 use the search results already in context instead of searching again.`};L.push(fe),S.push(fe)}}}if(M&&(y.fnName==="glob"||y.fnName==="glob_files"||y.fnName==="search_files")&&y.args){if(K&&!K.startsWith("(no matches)")){let V=K.split(`
1403
+ `);for(let X of V)(X.startsWith("/")&&!X.includes(" ")||!X.includes(":")&&!X.startsWith("["))&&ar.add(X.trim())}let C=y.args.pattern||y.args.query||y.args.path||"",D=us(Ly,C);if(D===Iy){j(`${h.yellow} \u26A0 Loop warning: glob pattern "${C.slice(0,40)}" run ${D}\xD7 \u2014 possible search loop${h.reset}`);let V={role:"user",content:`[SYSTEM WARNING] Same glob/search pattern ${D}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};L.push(V),S.push(V)}else if(D>=Dy){j(`${h.red} \u2716 Loop abort: glob pattern run ${D}\xD7 \u2014 aborting runaway search loop${h.reset}`),c&&(c.stop(),c=null),l(null),Ne(N,q,x,Y,Oe,{suppressHint:!0}),Ae(L);return}let F=C.replace(/\*+/g," ").replace(/[{}()\[\],.\/\\]/g," ").split(/\s+/).filter(V=>V.length>=4&&!/^\.(js|ts|py|json|md|yaml|yml|txt|css|html|sh)$/.test(V));for(let V of F){let X=V.toLowerCase();Hi.has(X)||Hi.set(X,new Set);let re=Hi.get(X);if(re.add(C),re.size===qy){j(`${h.red} \u2716 Glob core-term block: ${re.size} different patterns all searching for "${X}" \u2014 search loop${h.reset}`);let fe={role:"user",content:`[SYSTEM WARNING] You have searched for "${X}" using ${re.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.`};L.push(fe),S.push(fe)}else if(re.size===jy){j(`${h.yellow} \u26A0 Glob core-term warning: ${re.size} different patterns searching for "${X}"${h.reset}`);let fe={role:"user",content:`[SYSTEM WARNING] ${re.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.`};L.push(fe),S.push(fe)}}}let ee=(y.args?.command||y.args?.cmd||y.args?.script||"").toLowerCase(),U=/\b(health|healthcheck|health-check|status|check|ping|validate|alive|ready)\b/.test(ee)||/\/(health|status|ping|ready|alive)\b/.test(ee);if(M&&(y.fnName==="bash"||y.fnName==="ssh_exec")&&U&&K.includes('"valid":true')){{let D=at();if(Gt(S,D).percentage>=60){let{messages:V,tokensRemoved:X}=nn(S,D);X>0&&(S=V,console.log(`${h.dim} [pre-stop-compress \u2014 ~${X} tokens freed before STOP injection, now ${Math.round(Gt(S,D).percentage)}%]${h.reset}`))}}let C={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.'};L.push(C),S.push(C),console.log(`${h.cyan} \u2713 Health-check stop signal detected \u2014 injecting STOP instruction${h.reset}`)}if(M&&(y.fnName==="bash"||y.fnName==="ssh_exec")&&ee&&/\bsed\s+-[ie]\b|\btee\b|\bcp\b|\bmv\b|\bpatch\b|\bdd\b|>\s*\S|\becho\b.*>|\bcat\b.*>|\bprintf\b.*>|\bpython[23]?\b.*open\b.*['"'w]|\bnpm\b.*run\b|\byarn\b.*run\b/.test(ee)&&(gs++,j(`${h.dim} [bash write detected: _bashModifiedFiles=${gs}]${h.reset}`)),K.startsWith("BLOCKED:")){if(Mn++,Mn>=lu){j(`${h.red} \u2716 Loop abort: ${Mn} consecutive blocked calls \u2014 model not heeding BLOCKED messages${h.reset}`),c&&(c.stop(),c=null),l(null),Ne(N,q,x,Y,Oe,{suppressHint:!0}),Ae(L);return}}else Mn=0;if(M)Nn=0,ua=!0;else if(Nn++,Nn===Wy){j(`${h.yellow} \u26A0 Loop warning: ${Nn} consecutive tool errors \u2014 possible stuck loop${h.reset}`);let C={role:"user",content:`[SYSTEM WARNING] ${Nn} consecutive errors. Stuck loop \u2014 try fundamentally different approach or declare done.`};L.push(C),S.push(C)}else if(Nn>=Hy){j(`${h.red} \u2716 Loop abort: ${Nn} consecutive errors \u2014 aborting stuck loop${h.reset}`),c&&(c.stop(),c=null),l(null),Ne(N,q,x,Y,Oe,{suppressHint:!0}),Ae(L);return}if(M&&y.fnName==="read_file"&&y.args&&y.args.path){Y.add(y.args.path),ke.delete(y.args.path);let C=us(ys,y.args.path);{let X=y.args.line_start!=null&&parseInt(y.args.line_start,10)||1,re=y.args.line_start!=null?parseInt(y.args.line_end,10)||X+350:350;Cn.has(y.args.path)||Cn.set(y.args.path,[]),Cn.get(y.args.path).push([X,re])}if(y._scrollWarn){let{sectionCount:X,path:re}=y._scrollWarn,fe={role:"user",content:`[SYSTEM WARNING] "${re}" \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.`};L.push(fe),S.push(fe),j(`${h.yellow} \u26A0 Scroll warning: "${re.split("/").slice(-2).join("/")}" \u2014 ${X} sections read \u2014 use grep instead${h.reset}`)}let D=y.args.path.split("/").slice(-2).join("/"),F=!y.args?.line_start&&!y.args?.line_end,V=_e&&Le==="plan";if(!V&&F&&C===Fy){{let re=at();if(Gt(S,re).percentage>=60){let{messages:te}=nn(S,re);S=te}}j(`${h.yellow} \u26A0 Loop warning: "${D}" read unbounded ${C}\xD7 \u2014 use line_start/line_end${h.reset}`);let X={role:"user",content:`[SYSTEM WARNING] "${y.args.path}" read ${C}\xD7 without line ranges. Use line_start/line_end to read specific sections \u2014 do not re-read the full file.`};L.push(X),S.push(X)}else if(!V&&F&&C>=By){j(`${h.red} \u2716 Loop abort: "${D}" read unbounded ${C}\xD7 \u2014 aborting runaway read loop${h.reset}`),c&&(c.stop(),c=null),l(null),Ne(N,q,x,Y,Oe,{suppressHint:!0}),Ae(L);return}}if(y.fnName==="spawn_agents"){let C=(K.match(/\bStatus: done\b/g)||[]).length;if((K.match(/\bStatus: truncated\b/g)||[]).length>0&&C===0){if(Pn++,Pn===Yy){j(`${h.yellow} \u26A0 Swarm warning: all sub-agents hit iteration limit ${Pn}\xD7 in a row${h.reset}`);let F={role:"user",content:`[SYSTEM WARNING] Sub-agents truncated ${Pn}\xD7 in a row. Stop spawning \u2014 try different approach or report findings.`};L.push(F),S.push(F)}else if(Pn>=Gy){console.log(`${h.red} \u2716 Swarm abort: all sub-agents hit iteration limit ${Pn}\xD7 \u2014 aborting stuck swarm${h.reset}`),c&&(c.stop(),c=null),l(null),Ne(N,q,x,Y,Oe,{suppressHint:!0}),Ae(L);return}}else C>0&&(Pn=0)}}{let y=ot.reduce((K,T)=>K+(typeof T.content=="string"?T.content.length:0),0);if(y>2e5){let K=ot.map((T,M)=>({i:M,len:typeof T.content=="string"?T.content.length:0})).sort((T,M)=>M.len-T.len);for(let{i:T,len:M}of K){if(y<=2e5)break;let ee=y-2e5,U=Math.max(M-ee,500);U<M&&typeof ot[T].content=="string"&&(ot[T]={...ot[T],content:ot[T].content.substring(0,U)+`
1404
+ ...(truncated ${M-U} chars \u2014 per-message budget)`},y-=M-U)}}}for(let w of ot)L.push(w),S.push(w);if(Fi(L,S),!nt)for(let w=0;w<ot.length;w++){if(!we[w]||we[w].fnName!=="ssh_exec")continue;let y=ot[w];if(!y||typeof y.content!="string")continue;let K=Mc(y.content);if(K){nt=!0,_t=K.slice(0,120),jt=0,qt=!1,zt=0,j(`${h.yellow} \u26A1 Root cause detected: ${_t} \u2014 fix phase (read budget: 3)${h.reset}`);let T={role:"user",content:`[SYSTEM] Root cause identified: ${_t}. Read only the file that needs fixing, then edit it. Do not read other files.`};L.push(T),S.push(T);break}}for(let w=0;w<ot.length;w++){let y=we[w];if(!y)continue;let K=typeof ot[w]?.content=="string"?ot[w].content:"";if(y.fnName==="create_task"){let T=K.match(/Task #(\d+) created/),M=typeof y.args?.subject=="string"?y.args.subject:"";T&&M&&cr.set(T[1],M)}else if((y.fnName==="write_file"||y.fnName==="edit_file")&&!K.startsWith("BLOCKED:")&&K.trim().length>0){let M=(typeof y.args?.path=="string"?y.args.path:typeof y.args?.file_path=="string"?y.args.file_path:"").split("/").pop().toLowerCase(),ee=M.split(/[._\-/]/).filter(U=>U.length>2);for(let[U,ae]of cr){if(ur.has(U))continue;let C=ae.toLowerCase().split(/\W+/).filter(F=>F.length>3);ee.filter(F=>C.some(V=>V.includes(F)||F.includes(V))).length>=1&&(ur.add(U),j(`${h.green} \u2714 Auto-matched task #${U} to ${M}: ${ae.slice(0,60)}${h.reset}`))}}}{let w=at();if(Gt(S,w).percentage>=78){let{messages:K,tokensRemoved:T}=nn(S,w);T>0&&(S=K,console.log(`${h.dim} [auto-compressed \u2014 ~${T} tokens freed, now ${Math.round(Gt(S,w).percentage)}%]${h.reset}`))}}if(or()&&!s.skillLoop&&(we.some(y=>y&&["write_file","edit_file","patch_file"].includes(y.fnName))?pe=0:(pe===0&&(lt=x.size),pe++),pe>=9&&N>=4&&x.size===lt)){j(`${h.green} \u2713 Stagnation exit: ${pe} read-only iterations, no new file changes${h.reset}`),process.stdout.isTTY&&process.stderr.write(`${h.yellow} \u26A0 Stagnation detected: ${pe} iterations without edits \u2014 exiting. The model investigated but did not apply changes.${h.reset}
1405
+ `),c&&(c.stop(),c=null),l(null),Ne(N,q,x,Y,Oe),Ae(L);break e}let _u=gT();if(_u){let w={role:"user",content:`[User note mid-run]: ${_u}`};L.push(w),S.push(w),console.log(`${h.cyan} \u270E Context added${h.reset}`)}}if(qe>=bt){if(c&&(c.stop(),c=null),l(null),Ne(N,q,x,Y,Oe),Ae(L),Di(L),_e&&Le==="plan"){let Ve=[...L].reverse().find(ze=>ze.role==="assistant"),ct=typeof Ve?.content=="string"?Ve.content:"",yn=Zo("implement",ct);if(yn){L.push(yn),S=[{role:"system",content:await Xc()},...L],bt=cs("implement"),j(`${h.yellow} \u26A0 Plan budget exhausted \u2014 auto-transitioning to implement${h.reset}`);continue e}}else if(_e&&Le==="verify"){j(`${h.yellow} \u26A0 Verify budget exhausted \u2014 completing session${h.reset}`);break e}let{getActiveProviderName:ge}=Qe();if(ge()==="ollama"&&ca<fu){if(x.size===0&&!ua){console.log(`${h.yellow} \u26A0 Max iterations reached with no progress. Stopping.${h.reset}`);break e}ca++,bt=20,console.log(`${h.dim} \u2500\u2500 auto-extending (+20 turns, ext ${ca}/${fu}) \u2500\u2500${h.reset}`);continue e}if(console.log(`
1406
+ ${h.yellow}\u26A0 Max iterations reached.${h.reset}`),await Jg(" Continue for 20 more turns?")){bt=20;continue e}console.log(`${h.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${h.reset}`)}break e}await uu()}dy.exports={processInput:OT,clearConversation:bT,getConversationLength:kT,getConversationMessages:ST,setConversationMessages:vT,setAbortSignalGetter:JE,setMaxIterations:VE,invalidateSystemPromptCache:Bc,clearToolFilterCache:rT,getCachedFilteredTools:oy,buildSystemPrompt:Xc,splitSystemPrompt:$T,SYSTEM_PROMPT_DYNAMIC_BOUNDARY:Kc,getProjectContextHash:ry,buildUserContent:ny,_detectImageURLs:Qg,_downloadImageURL:ey,_grabClipboardImage:ty,detectFrustration:sy,detectAndTruncateLoop:jc,injectMidRunNote:mT,resetSessionTracking:uy}});var Qe=Q((Z1,my)=>{var{OllamaProvider:NT}=Gu(),{OpenAIProvider:MT}=Vu(),{AnthropicProvider:PT}=ed(),{GeminiProvider:LT}=od(),{LocalProvider:IT}=ad(),{checkBudget:DT}=Ir(),Qc={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"}},Jc=(process.env.OLLAMA_FALLBACK_CHAIN||"").split(",").map(t=>t.trim()).filter(Boolean),py={};for(let[t,e]of Object.entries(Qc))for(let s of Object.values(e))py[s]=t;function Zc(t,e){let s=py[t];return s&&Qc[s][e]||t}var st={},$t=null,Ue=null,dr=[];function Ft(){if(Object.keys(st).length>0)return;oo("ollama",new NT),oo("openai",new MT),oo("anthropic",new PT),oo("gemini",new LT),oo("local",new IT);let t=process.env.DEFAULT_PROVIDER||"ollama",e=process.env.DEFAULT_MODEL||null;st[t]?($t=t,Ue=e||st[t].defaultModel):($t="ollama",Ue="kimi-k2.5");let s=process.env.FALLBACK_CHAIN;s&&(dr=s.split(",").map(n=>n.trim()).filter(Boolean))}function oo(t,e){st[t]=e}function jT(t){return Ft(),st[t]||null}function eu(){return Ft(),st[$t]||null}function qT(){return Ft(),$t}function FT(){return Ft(),Ue}function BT(){Ft();let t=eu();if(!t)return{id:Ue,name:Ue,provider:$t};let e=t.getModel(Ue);return e?{...e,provider:$t}:{id:Ue,name:Ue,provider:$t}}function tu(t){if(!t)return{provider:null,model:null};let e=t.indexOf(":");if(e>0){let s=t.slice(0,e);if(st[s]||["ollama","openai","anthropic","gemini","local"].includes(s))return{provider:s,model:t.slice(e+1)}}return{provider:null,model:t}}function UT(t){Ft();let{provider:e,model:s}=tu(t);if(e){let o=st[e];return o&&(o.getModel(s)||e==="local"||e==="ollama")?($t=e,Ue=s,na(),!0):!1}let n=eu();if(n&&n.getModel(s))return Ue=s,na(),!0;for(let[o,r]of Object.entries(st))if(r.getModel(s))return $t=o,Ue=s,na(),!0;return!1}function na(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=ic();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=en();t()}catch{}}function WT(){Ft();let t=new Set;for(let e of Object.values(st))for(let s of e.getModelNames())t.add(s);return Array.from(t)}function HT(){return Ft(),Object.entries(st).map(([t,e])=>({provider:t,configured:e.isConfigured(),models:Object.values(e.getModels()).map(s=>({...s,active:t===$t&&s.id===Ue}))}))}function YT(){Ft();let t=[];for(let[e,s]of Object.entries(st)){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 GT(t){dr=Array.isArray(t)?t:[]}function zT(){return[...dr]}function fy(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 hy(t){let e=[$t,...dr.filter(r=>r!==$t)],s,n=0,o=0;for(let r=0;r<e.length;r++){let i=e[r],a=st[i];if(!a||!a.isConfigured())continue;o++;let l=DT(i);if(!l.allowed){n++,s=new Error(`Budget limit reached for ${i}: $${l.spent.toFixed(2)} / $${l.limit.toFixed(2)}`);continue}try{let c=r>0,u=c?Zc(Ue,i):Ue;return c&&u!==Ue&&process.stderr.write(` [fallback: ${i}:${u}]
1407
+ `),await t(a,i,u)}catch(c){if(s=c,!fy(c)||r>=e.length-1)throw c;if(i==="ollama"&&Jc.length>0){let u=isFallback?Zc(Ue,i):Ue;for(let d of Jc)if(d!==u)try{return process.stderr.write(` [ollama fallback: ${d}]
1408
+ `),await t(a,i,d)}catch(f){if(s=f,!fy(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 KT(t,e,s={}){Ft();let n=s.model,o=n?(()=>{let{model:i}=tu(n);return i||n})():void 0,r=o!==n?{...s,model:o}:s;return hy((i,a,l)=>i.stream(t,e,{model:l,signal:r.signal,...r}))}async function XT(t,e,s={}){if(Ft(),s.provider){let n=st[s.provider];if(!n||!n.isConfigured())throw new Error(`Provider '${s.provider}' is not available`);let o={model:s.model||Ue,...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 hy(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 VT(){Ft();let t=[];for(let[e,s]of Object.entries(st))s.isConfigured()&&t.push({name:e,models:Object.values(s.getModels())});return t}function JT(){for(let t of Object.keys(st))delete st[t];$t=null,Ue=null,dr=[]}my.exports={registerProvider:oo,getProvider:jT,getActiveProvider:eu,getActiveProviderName:qT,getActiveModelId:FT,getActiveModel:BT,setActiveModel:UT,getModelNames:WT,parseModelSpec:tu,listProviders:HT,listAllModels:YT,callStream:KT,callChat:XT,getConfiguredProviders:VT,setFallbackChain:GT,getFallbackChain:zT,resolveModelForProvider:Zc,MODEL_EQUIVALENTS:Qc,OLLAMA_FALLBACK_MODELS:Jc,_reset:JT}});var{C:G}=Ke(),ZT=Qe(),{TOOL_DEFINITIONS:gy}=As(),{saveRoutingConfig:QT}=ss(),ou=[{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:"read-partial",category:"file-ops",prompt:"Read only lines 20 to 40 of src/index.js \u2014 I need to see that specific range.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("index")&&(typeof t.line_start=="number"||typeof t.start_line=="number")},{id:"glob-ts-defs",category:"file-ops",prompt:"Find all TypeScript type definition files (*.d.ts) anywhere in the project.",expectedTool:"glob",validateArgs:t=>typeof t.pattern=="string"&&t.pattern.includes(".d.ts")},{id:"write-gitignore",category:"file-ops",prompt:"Create a .gitignore file at the project root that ignores node_modules/ and dist/.",expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes(".gitignore")&&typeof t.content=="string"&&t.content.includes("node_modules")},{id:"edit-version-bump",category:"file-ops",prompt:'In package.json, change the version field from "1.0.0" to "1.1.0".',expectedTool:["edit_file","patch_file"],validateArgs:t=>!!(t.path&&t.path.includes("package"))},{id:"grep-with-filter",category:"search",prompt:"Search for all calls to require() but only inside .js files in the cli/ directory.",expectedTool:["grep","search_files"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("require")},{id:"no-tool-http-port",category:"reasoning",prompt:"What is the default port used by the HTTP protocol?",expectedTool:null,validateArgs:()=>!0},{id:"bash-node-version",category:"shell",prompt:"Check which version of Node.js is currently installed on this system.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("node")&&(t.command.includes("--version")||t.command.includes("-v"))},{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}],yy=[{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)}],ra=[...ou,...yy],nu=["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 eR(){try{let s=require("path").join(require("os").homedir(),".nex-code","benchmark-results.json");if(!require("fs").existsSync(s))return nu;let n=JSON.parse(require("fs").readFileSync(s,"utf-8"));return!Array.isArray(n)||n.length===0?nu: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 nu}}var ru=eR(),tR=["minimax-m2.7:cloud","qwen3-coder:480b","devstral-2:123b"],wy=(()=>{let t=ru.slice(0,3);return t.length>=3?t:tR})(),nR=14,sa={producedToolCall:.2,correctTool:.35,validArgs:.3,schemaCompliant:.15},sR="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 su(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:sR},{role:"user",content:t.prompt}],o=Date.now();try{let r=await ZT.callChat(n,gy,{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],l=a.function?.name||"unknown",c=a.function?.arguments||{};s.producedToolCall=!0,s.toolCalled=l;let u=Array.isArray(t.expectedTool)?t.expectedTool:[t.expectedTool];if(s.correctTool=u.includes(l),s.correctTool){let d=gy.find(f=>f.function?.name===l);if(s.validArgs=!!t.validateArgs(c,d),d){let f=d.function?.parameters||{},p=f.required||[],m=Object.keys(f.properties||{});s.schemaCompliant=p.every(g=>c[g]!==void 0)&&Object.keys(c).every(g=>m.includes(g))}}}}catch(r){s.latencyMs=Date.now()-o,s.error=r.message.slice(0,120)}return s}function ro(t){return t.error?0:((t.producedToolCall?sa.producedToolCall:0)+(t.correctTool?sa.correctTool:0)+(t.validArgs?sa.validArgs:0)+(t.schemaCompliant?sa.schemaCompliant:0))*100}var _y={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 iu(t){return Object.entries(t).map(([e,s])=>{let n=s.map(ro),o=n.reduce((a,l)=>a+l,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 l=s.filter(u=>_y[u.category]===a);if(l.length===0)continue;let c=l.map(ro).reduce((u,d)=>u+d,0)/l.length;i[a]=Math.round(c*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,l)=>a+l.latencyMs,0)/s.length),errorCount:s.filter(a=>a.error).length,categoryScores:i,results:s}}).sort((e,s)=>s.score-e.score)}function $y(t){let e={};for(let a of["coding","frontend","sysadmin","data","agentic","plan","verify"]){let l=t.filter(g=>g.categoryScores[a]!==void 0&&g.score>=65).sort((g,_)=>_.categoryScores[a]-g.categoryScores[a]);if(l.length===0)continue;let u=(l[0]?.results||[]).filter(g=>_y[g.category]===a).length;if(u<4)continue;let d=l[0],f=l[1];if(d.categoryScores[a]>=95&&u<8&&f&&d.categoryScores[a]-f.categoryScores[a]<15){let _=t.filter(b=>b.categoryScores[a]!==void 0).find(b=>b.categoryScores[a]<95);_&&(e[a]={model:_.model,score:_.categoryScores[a],avgLatency:_.avgLatency,_flukePrevented:!0});continue}let m=l.filter(g=>d.categoryScores[a]-g.categoryScores[a]<=5).sort((g,_)=>g.avgLatency-_.avgLatency)[0];e[a]={model:m.model,score:m.categoryScores[a],avgLatency:m.avgLatency}}return e}function by(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((u,d)=>u+d.width+1,0)+1,r="\u2500".repeat(o);console.log(`
1409
+ ${G.bold}${s}${G.reset}`),console.log(r);let i=n.map(u=>u.label.padEnd(u.width)).join(" ");if(console.log(`${G.dim}${i}${G.reset}`),console.log(r),t.forEach((u,d)=>{let f=String(d+1).padEnd(n[0].width),p=u.model.slice(0,n[1].width).padEnd(n[1].width),m=String(u.score).padEnd(n[2].width),g=`${u.toolCallRate}%`.padEnd(n[3].width),_=`${u.correctRate}%`.padEnd(n[4].width),b=`${u.validArgsRate}%`.padEnd(n[5].width),A=`${u.schemaRate}%`.padEnd(n[6].width),P=`${(u.avgLatency/1e3).toFixed(1)}s`.padEnd(n[7].width),v=u.errorCount>0?`${G.red}${u.errorCount}${G.reset}`:`${G.dim}0${G.reset}`,E=u.score>=80?G.green:u.score>=60?G.yellow:G.red,O=d===0?`${G.yellow}${f}${G.reset}`:`${G.dim}${f}${G.reset}`;console.log(`${O} ${E}${p}${G.reset} ${G.bold}${E}${m}${G.reset} ${g} ${_} ${b} ${A} ${G.dim}${P}${G.reset} ${v}`)}),console.log(r),t.length>0){let u=t[0];if(console.log(`
1410
+ ${G.bold}${G.green}Winner: ${u.model}${G.reset} score ${u.score}/100`),t.length>1){let d=(u.score-t[1].score).toFixed(1);console.log(`${G.dim}+${d} pts over ${t[1].model}${G.reset}`)}}let a=t.filter(u=>u.results.some(d=>!d.error&&(!d.correctTool||!d.validArgs)));if(a.length>0){console.log(`${G.bold}Failing tasks:${G.reset}`);for(let u of a){let d=u.results.filter(m=>!m.error&&(!m.correctTool||!m.validArgs));if(d.length===0)continue;let f=u.model.slice(0,22),p=d.map(m=>{if(!m.correctTool){let g=m.toolCalled||"(none)";return`${G.dim}${m.taskId}${G.reset} ${G.red}\u2192${g}${G.reset}`}return`${G.dim}${m.taskId}${G.reset} ${G.yellow}bad-args${G.reset}`});console.log(` ${G.dim}${f.padEnd(22)}${G.reset} ${p.join(" ")}`)}console.log()}let l=["coding","frontend","sysadmin","data","agentic"];if(t.some(u=>Object.keys(u.categoryScores).length>1)){console.log(`
1411
+ ${G.bold}Best model per task type:${G.reset}`);for(let u of l){let d=t.filter(g=>g.categoryScores[u]!==void 0).sort((g,_)=>_.categoryScores[u]-g.categoryScores[u]);if(d.length===0)continue;let f=d[0],p=f.categoryScores[u],m=p>=80?G.green:p>=60?G.yellow:G.red;console.log(` ${G.dim}${u.padEnd(10)}${G.reset} ${m}${f.model}${G.reset} ${G.dim}${p}/100${G.reset}`)}}console.log()}function xy(t){if(!(!t||t.length<2))try{let e=$y(t),{loadRoutingConfig:s}=ss(),n=s(),o={...n},r=[],i=new Set(["plan","verify"]);for(let[a,{model:l,score:c}]of Object.entries(e)){let u=i.has(a),d=u?n.phases&&n.phases[a]:n[a];d&&d!==l&&!t.find(p=>p.model===d)||(u?(o.phases||(o.phases={}),o.phases[a]!==l&&(o.phases[a]=l,r.push(`phase:${a}\u2192${l}`))):o[a]!==l&&(o[a]=l,r.push(`${a}\u2192${l}`)))}r.length>0&&(QT(o),console.log(`
1412
+ ${G.dim} Routing updated: ${r.join(", ")}${G.reset}`),console.log(`
1413
+ ${G.green}\u{1F4A1} The best models have been saved to ~/.nex-code/.env and will be automatically used by nex-code from now on.${G.reset}`))}catch{}}async function oR({models:t,quick:e=!1,onProgress:s,parallelModels:n=1}={}){let o=e?ou.slice(0,nR):ra,r=t?.length>0?t:e?wy:ru,i={};for(let l of r)i[l]=[];if(n<=1)for(let l of r)for(let c of o){s?.({model:l,task:c.id,done:!1});let u=await su(c,l);i[l].push(u),s?.({model:l,task:c.id,done:!0,score:ro(u),error:u.error})}else{let l=Math.min(n,r.length),c=[...r],u=Array.from({length:l},async()=>{for(;c.length>0;){let d=c.shift();if(!d)break;for(let f of o){s?.({model:d,task:f.id,done:!1});let p=await su(f,d);i[d].push(p),s?.({model:d,task:f.id,done:!0,score:ro(p),error:p.error})}}});await Promise.all(u)}let a=iu(i);return by(a,o.length),xy(a),a}async function rR({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 ra){s?.({model:i,task:a.id,done:!1});let l=await su(a,i);n[i].push(l),s?.({model:i,task:a.id,done:!0,score:ro(l),error:l.error})}}let r=[...iu(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),by(r,ra.length),xy(r),r}var oa=[{id:"simple_question",name:"Simple Convergence",prompt:"What is 2+2?",maxTurns:3,successCriteria:["4"]}];function ky(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.
1397
1414
  Example:
1398
1415
  {
1399
1416
  "scenarios": [
@@ -1406,14 +1423,14 @@ ${Y.green}\u{1F4A1} The best models have been saved to ~/.nex-code/.env and will
1406
1423
  }
1407
1424
  ]
1408
1425
  }
1409
- `),Zi;try{let o=JSON.parse(e.readFileSync(n,"utf-8"));return!Array.isArray(o.scenarios)||o.scenarios.length===0?(console.log(`${Y.yellow}benchmark-config.json has no scenarios \u2014 using defaults.${Y.reset}
1410
- `),Zi):o.scenarios}catch(o){return console.log(`${Y.yellow}Failed to parse benchmark-config.json: ${o.message}${Y.reset}
1411
- `),Zi}}function my(t,e){let{scoreMessages:s,_extractToolCalls:n,_getLastAssistantText:o}=ki(),r=s(t),i=r.score,a=[],l=o(t).toLowerCase();e.successCriteria.every(f=>l.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 BT(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"),l=e.cwd||process.cwd(),c=[a,"--prompt-file",i,"--delete-prompt-file","--auto","--max-turns",String(t.maxTurns)];return e.model&&c.push("--model",e.model),new Promise(u=>{let d=s(process.execPath,c,{cwd:l,stdio:["ignore","pipe","pipe"],env:{...process.env}}),f=t.maxTurns*60*1e3,p=!1,h=setTimeout(()=>{p=!0;try{d.kill("SIGTERM")}catch{}},f);d.on("close",g=>{clearTimeout(h);try{n.unlinkSync(i)}catch{}let _=o.join(l,".nex","sessions","_autosave.json"),b=[];if(n.existsSync(_))try{b=JSON.parse(n.readFileSync(_,"utf-8")).messages||[]}catch{}u({messages:b,exitCode:g||0,timedOut:p})}),d.stdout.resume(),d.stderr.resume()})}function UT(t,e,s){let n=t.length>0?Math.round(t.reduce((l,c)=>l+c.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(`
1426
+ `),oa;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}
1427
+ `),oa):o.scenarios}catch(o){return console.log(`${G.yellow}Failed to parse benchmark-config.json: ${o.message}${G.reset}
1428
+ `),oa}}function Sy(t,e){let{scoreMessages:s,_extractToolCalls:n,_getLastAssistantText:o}=Ri(),r=s(t),i=r.score,a=[],l=o(t).toLowerCase();e.successCriteria.every(f=>l.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 iR(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"),l=e.cwd||process.cwd(),c=[a,"--prompt-file",i,"--delete-prompt-file","--auto","--max-turns",String(t.maxTurns)];return e.model&&c.push("--model",e.model),new Promise(u=>{let d=s(process.execPath,c,{cwd:l,stdio:["ignore","pipe","pipe"],env:{...process.env}}),f=t.maxTurns*60*1e3,p=!1,m=setTimeout(()=>{p=!0;try{d.kill("SIGTERM")}catch{}},f);d.on("close",g=>{clearTimeout(m);try{n.unlinkSync(i)}catch{}let _=o.join(l,".nex","sessions","_autosave.json"),b=[];if(n.existsSync(_))try{b=JSON.parse(n.readFileSync(_,"utf-8")).messages||[]}catch{}u({messages:b,exitCode:g||0,timedOut:p})}),d.stdout.resume(),d.stderr.resume()})}function aR(t,e,s){let n=t.length>0?Math.round(t.reduce((l,c)=>l+c.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(`
1412
1429
  \u250C\u2500 Benchmark Results ${"\u2500".repeat(r-19)}\u2510`);for(let l of t){let c=l.id.padEnd(20),u=l.name.substring(0,26).padEnd(26),d=`${l.score}/10`.padStart(6),f=l.grade.padStart(2);console.log(`\u2502 ${c} ${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
1413
- `)}function WT(t=10){let e=require("fs"),n=require("path").join(process.cwd(),".nex","benchmark-history.json");if(!e.existsSync(n)){console.log(`${Y.yellow}No score history yet. Run a session first.${Y.reset}
1414
- `);return}let o=[];try{o=JSON.parse(e.readFileSync(n,"utf-8"))}catch{o=[]}if(!Array.isArray(o)||o.length===0){console.log(`${Y.yellow}Score history is empty.${Y.reset}
1430
+ `)}function lR(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}
1431
+ `);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}
1415
1432
  `);return}let r=o.slice(-t);console.log(`
1416
- ${Y.bold}Score History (last ${r.length} session${r.length===1?"":"s"}):${Y.reset}`);for(let i of r){let a=(i.date||"").replace("T"," ").substring(0,16),l=(i.version||"?").padEnd(8),c=(i.model||"?").substring(0,12).padEnd(12),u=`${i.score}/10`.padStart(6),d=i.grade||"?",f=i.issues&&i.issues.length>0?`${Y.yellow}\u26A0 ${i.issues.slice(0,2).map(h=>h.substring(0,30)).join(", ")}${Y.reset}`:`${Y.green}\u2713${Y.reset}`,p=i.score>=8?Y.green:i.score>=6?Y.yellow:Y.red;console.log(` ${Y.dim}${a}${Y.reset} ${Y.dim}v${l}${Y.reset} ${Y.dim}${c}${Y.reset} ${p}${u} ${d}${Y.reset} ${f}`)}console.log()}async function HT({dryRun:t=!1,model:e,cwd:s,onProgress:n}={}){let o=mr(),r=hy(s);if(t){console.log(`
1417
- ${Y.bold}Scenario Benchmark \u2014 Scenarios (dry-run):${Y.reset}
1418
- `);for(let l of r)console.log(` ${Y.cyan}${l.id.padEnd(20)}${Y.reset} ${Y.dim}${l.name}${Y.reset} maxTurns=${l.maxTurns}`),console.log(` ${Y.dim}${l.prompt.substring(0,80)}${Y.reset}`);return console.log(),[]}let i=(()=>{if(e)return typeof e=="object"?e.id||"unknown":e;try{let{getActiveModel:l}=ao(),c=l?l():null;return c?typeof c=="object"?c.id||"unknown":c:"unknown"}catch{return"unknown"}})(),a=[];for(let l of r){n?.({id:l.id,name:l.name,done:!1}),console.log(`
1419
- ${Y.dim}Running scenario: ${l.name}...${Y.reset}`);let{messages:c,timedOut:u}=await BT(l,{model:i,cwd:s}),d;u||c.length===0?d={score:0,grade:"F",issues:[u?"Scenario timed out":"No messages produced"],summary:"No output",bonuses:[]}:d=my(c,l);let f={id:l.id,name:l.name,score:d.score,grade:d.grade,issues:d.issues,bonuses:d.bonuses};a.push(f),n?.({id:l.id,name:l.name,done:!0,score:d.score,grade:d.grade});try{let{appendScoreHistory:p}=ki();p(d.score,{version:o.version,model:i,sessionName:`bench:${l.id}`,issues:d.issues})}catch{}}return UT(a,o.version,i),a}module.exports={runBenchmark:qT,runDiscoverBenchmark:FT,buildSummary:Jc,buildCategoryWinners:dy,TASKS:Xc,PHASE_TASKS:ly,ALL_TASKS:Qi,scoreResult:no,DEFAULT_MODELS:Vc,QUICK_MODELS:cy,runScenarioBenchmark:HT,showScoreTrend:WT,loadScenarios:hy,DEFAULT_SCENARIOS:Zi,scoreScenario:my};
1433
+ ${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),l=(i.version||"?").padEnd(8),c=(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}`,p=i.score>=8?G.green:i.score>=6?G.yellow:G.red;console.log(` ${G.dim}${a}${G.reset} ${G.dim}v${l}${G.reset} ${G.dim}${c}${G.reset} ${p}${u} ${d}${G.reset} ${f}`)}console.log()}async function cR({dryRun:t=!1,model:e,cwd:s,onProgress:n}={}){let o=_r(),r=ky(s);if(t){console.log(`
1434
+ ${G.bold}Scenario Benchmark \u2014 Scenarios (dry-run):${G.reset}
1435
+ `);for(let l of r)console.log(` ${G.cyan}${l.id.padEnd(20)}${G.reset} ${G.dim}${l.name}${G.reset} maxTurns=${l.maxTurns}`),console.log(` ${G.dim}${l.prompt.substring(0,80)}${G.reset}`);return console.log(),[]}let i=(()=>{if(e)return typeof e=="object"?e.id||"unknown":e;try{let{getActiveModel:l}=fo(),c=l?l():null;return c?typeof c=="object"?c.id||"unknown":c:"unknown"}catch{return"unknown"}})(),a=[];for(let l of r){n?.({id:l.id,name:l.name,done:!1}),console.log(`
1436
+ ${G.dim}Running scenario: ${l.name}...${G.reset}`);let{messages:c,timedOut:u}=await iR(l,{model:i,cwd:s}),d;u||c.length===0?d={score:0,grade:"F",issues:[u?"Scenario timed out":"No messages produced"],summary:"No output",bonuses:[]}:d=Sy(c,l);let f={id:l.id,name:l.name,score:d.score,grade:d.grade,issues:d.issues,bonuses:d.bonuses};a.push(f),n?.({id:l.id,name:l.name,done:!0,score:d.score,grade:d.grade});try{let{appendScoreHistory:p}=Ri();p(d.score,{version:o.version,model:i,sessionName:`bench:${l.id}`,issues:d.issues})}catch{}}return aR(a,o.version,i),a}module.exports={runBenchmark:oR,runDiscoverBenchmark:rR,buildSummary:iu,buildCategoryWinners:$y,TASKS:ou,PHASE_TASKS:yy,ALL_TASKS:ra,scoreResult:ro,DEFAULT_MODELS:ru,QUICK_MODELS:wy,runScenarioBenchmark:cR,showScoreTrend:lR,loadScenarios:ky,DEFAULT_SCENARIOS:oa,scoreScenario:Sy};