nex-code 0.5.1 → 0.5.4

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,38 +1,38 @@
1
- "use strict";var ea=Object.defineProperty;var Sy=Object.getOwnPropertyDescriptor;var vy=Object.getOwnPropertyNames;var Ey=Object.prototype.hasOwnProperty;var Ty=(t,e)=>()=>(t&&(e=t(t=0)),e);var z=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Ry=(t,e)=>{for(var s in e)ea(t,s,{get:e[s],enumerable:!0})},Cy=(t,e,s,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of vy(e))!Ey.call(t,o)&&o!==s&&ea(t,o,{get:()=>e[o],enumerable:!(n=Sy(e,o))||n.enumerable});return t};var Ay=t=>Cy(ea({},"__esModule",{value:!0}),t);var Nt=z((bT,cu)=>{"use strict";var su="\x1B[0m",ou="\x1B[1m",hs="\x1B[2m";function G(t,e,s){return`\x1B[38;2;${t};${e};${s}m`}function Oy(){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 ru(){let t=require("os");return require("path").join(t.homedir(),".nex-code",".theme_cache.json")}function Ny(t){try{let s=require("fs").readFileSync(ru(),"utf8"),n=JSON.parse(s);if(n&&typeof n[t]=="boolean")return n[t]}catch{}return null}function My(t,e){try{let s=require("fs"),n=require("path"),o=ru(),r=n.dirname(o),i={};try{i=JSON.parse(s.readFileSync(o,"utf8"))}catch{}i[t]=e;let a=Object.keys(i);a.length>50&&a.slice(0,a.length-50).forEach(l=>delete i[l]),s.existsSync(r)||s.mkdirSync(r,{recursive:!0}),s.writeFileSync(o,JSON.stringify(i),"utf8")}catch{}}function Py(){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=Ny(s);if(n!==null)return n;let o=Oy(),r=o!==null?o:!0;return My(s,r),r}var iu=Py(),au={reset:su,bold:ou,dim:hs,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:hs,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:hs,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:hs,banner_model:hs,banner_yolo:G(245,175,50),footer_sep:hs,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)},lu={reset:su,bold:ou,dim:G(110,110,120),primary:G(0,110,190),secondary:G(0,125,148),success:G(0,148,62),warning:G(168,92,0),error:G(188,32,32),muted:G(110,110,120),subtle:G(155,155,165),tool_read:G(0,110,190),tool_write:G(168,92,0),tool_exec:G(128,42,188),tool_search:G(0,122,148),tool_git:G(0,138,62),tool_web:G(0,112,178),tool_sysadmin:G(168,82,0),tool_default:G(0,138,62),syn_keyword:G(128,42,188),syn_string:G(0,138,62),syn_number:G(168,92,0),syn_comment:G(135,135,148),syn_key:G(0,110,190),diff_add:G(0,148,62),diff_rem:G(188,32,32),banner_logo:G(0,122,205),banner_name:G(0,122,205),banner_version:G(100,100,118),banner_model:G(100,100,118),banner_yolo:G(168,62,0),footer_sep:G(168,168,178),footer_model:G(0,102,175),footer_branch:G(0,138,62),footer_project:G(135,135,148),footer_divider:G(168,168,178),footer_mode:G(148,88,0),white:G(40,40,52),red:G(188,32,32),green:G(0,148,62),yellow:G(168,92,0),blue:G(0,110,190),magenta:G(128,42,188),cyan:G(0,125,148),gray:G(132,132,142),bgRed:"\x1B[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)},Ly=iu?au:lu;cu.exports={T:Ly,isDark:iu,DARK:au,LIGHT:lu}});var ir=z((xT,Iy)=>{Iy.exports={name:"nex-code",version:"0.5.1",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-push .git/hooks/pre-push && chmod +x .git/hooks/pre-push && ln -sf ../../hooks/post-merge .git/hooks/post-merge && chmod +x .git/hooks/post-merge && echo 'Hooks installed (pre-push, post-merge).'",prepublishOnly:"npm run build && npm test","merge-to-main":"bash scripts/merge-to-main.sh",improve:"node scripts/improve.js","extract-examples":"node scripts/extract-examples.js","benchmark:realworld":"node scripts/benchmark-realworld.js","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.7.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 gs=z((kT,du)=>{var{T:te}=Nt(),cr=5,ms=(()=>{let t=[];for(let e=0;e<cr;e++)t.push(e);for(let e=cr-2;e>=1;e--)t.push(e);return t})(),uu=["\u273D","\u2726","\u2727","\u2726"],ta=class{constructor(e="Thinking..."){this.text=e,this.frame=0,this.interval=null,this.startTime=null}_render(){if(this._stopped)return;let e=ms[this.frame%ms.length],s="";for(let o=0;o<cr;o++)s+=o===e?`${te.cyan}\u25CF${te.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=` ${te.dim}${r}m ${String(i).padStart(2,"0")}s${te.reset}`}else o>=1&&(n=` ${te.dim}${o}s${te.reset}`)}process.stderr.write(`\x1B[2K\r${s} ${te.dim}${this.text}${te.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}},na=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=ms[this.frame%ms.length],s=`${te.cyan}\u25CF${te.reset}`,n=this._formatElapsed(),o=n?` ${te.dim}${n}${te.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=`${te.green}\u2713${te.reset}`,c=te.dim;break;case"error":l=`${te.red}\u2717${te.reset}`,c=te.dim;break;case"retry":l=`${te.yellow}\u21BB${te.reset}`,c=te.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}${te.reset}${u}
1
+ "use strict";var na=Object.defineProperty;var vy=Object.getOwnPropertyDescriptor;var Ey=Object.getOwnPropertyNames;var Ty=Object.prototype.hasOwnProperty;var Ry=(t,e)=>()=>(t&&(e=t(t=0)),e);var z=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Cy=(t,e)=>{for(var s in e)na(t,s,{get:e[s],enumerable:!0})},Ay=(t,e,s,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ey(e))!Ty.call(t,o)&&o!==s&&na(t,o,{get:()=>e[o],enumerable:!(n=vy(e,o))||n.enumerable});return t};var Oy=t=>Ay(na({},"__esModule",{value:!0}),t);var Dt=z((xT,uu)=>{"use strict";var ou="\x1B[0m",ru="\x1B[1m",hs="\x1B[2m";function G(t,e,s){return`\x1B[38;2;${t};${e};${s}m`}function Ny(){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 iu(){let t=require("os");return require("path").join(t.homedir(),".nex-code",".theme_cache.json")}function My(t){try{let s=require("fs").readFileSync(iu(),"utf8"),n=JSON.parse(s);if(n&&typeof n[t]=="boolean")return n[t]}catch{}return null}function Py(t,e){try{let s=require("fs"),n=require("path"),o=iu(),r=n.dirname(o),i={};try{i=JSON.parse(s.readFileSync(o,"utf8"))}catch{}i[t]=e;let a=Object.keys(i);a.length>50&&a.slice(0,a.length-50).forEach(l=>delete i[l]),s.existsSync(r)||s.mkdirSync(r,{recursive:!0}),s.writeFileSync(o,JSON.stringify(i),"utf8")}catch{}}function Ly(){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=My(s);if(n!==null)return n;let o=Ny(),r=o!==null?o:!0;return Py(s,r),r}var au=Ly(),lu={reset:ou,bold:ru,dim:hs,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:hs,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:hs,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:hs,banner_model:hs,banner_yolo:G(245,175,50),footer_sep:hs,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)},cu={reset:ou,bold:ru,dim:G(110,110,120),primary:G(0,110,190),secondary:G(0,125,148),success:G(0,148,62),warning:G(168,92,0),error:G(188,32,32),muted:G(110,110,120),subtle:G(155,155,165),tool_read:G(0,110,190),tool_write:G(168,92,0),tool_exec:G(128,42,188),tool_search:G(0,122,148),tool_git:G(0,138,62),tool_web:G(0,112,178),tool_sysadmin:G(168,82,0),tool_default:G(0,138,62),syn_keyword:G(128,42,188),syn_string:G(0,138,62),syn_number:G(168,92,0),syn_comment:G(135,135,148),syn_key:G(0,110,190),diff_add:G(0,148,62),diff_rem:G(188,32,32),banner_logo:G(0,122,205),banner_name:G(0,122,205),banner_version:G(100,100,118),banner_model:G(100,100,118),banner_yolo:G(168,62,0),footer_sep:G(168,168,178),footer_model:G(0,102,175),footer_branch:G(0,138,62),footer_project:G(135,135,148),footer_divider:G(168,168,178),footer_mode:G(148,88,0),white:G(40,40,52),red:G(188,32,32),green:G(0,148,62),yellow:G(168,92,0),blue:G(0,110,190),magenta:G(128,42,188),cyan:G(0,125,148),gray:G(132,132,142),bgRed:"\x1B[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)},Iy=au?lu:cu;uu.exports={T:Iy,isDark:au,DARK:lu,LIGHT:cu}});var ar=z((kT,Dy)=>{Dy.exports={name:"nex-code",version:"0.5.4",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-push .git/hooks/pre-push && chmod +x .git/hooks/pre-push && ln -sf ../../hooks/post-merge .git/hooks/post-merge && chmod +x .git/hooks/post-merge && echo 'Hooks installed (pre-push, post-merge).'",prepublishOnly:"npm run build && npm test","merge-to-main":"bash scripts/merge-to-main.sh",improve:"node scripts/improve.js","extract-examples":"node scripts/extract-examples.js","benchmark:realworld":"node scripts/benchmark-realworld.js","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.7.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 gs=z((ST,fu)=>{var{T:ne}=Dt(),ur=5,ms=(()=>{let t=[];for(let e=0;e<ur;e++)t.push(e);for(let e=ur-2;e>=1;e--)t.push(e);return t})(),du=["\u273D","\u2726","\u2727","\u2726"],sa=class{constructor(e="Thinking..."){this.text=e,this.frame=0,this.interval=null,this.startTime=null}_render(){if(this._stopped)return;let e=ms[this.frame%ms.length],s="";for(let o=0;o<ur;o++)s+=o===e?`${ne.cyan}\u25CF${ne.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=` ${ne.dim}${r}m ${String(i).padStart(2,"0")}s${ne.reset}`}else o>=1&&(n=` ${ne.dim}${o}s${ne.reset}`)}process.stderr.write(`\x1B[2K\r${s} ${ne.dim}${this.text}${ne.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}},oa=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=ms[this.frame%ms.length],s=`${ne.cyan}\u25CF${ne.reset}`,n=this._formatElapsed(),o=n?` ${ne.dim}${n}${ne.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=`${ne.green}\u2713${ne.reset}`,c=ne.dim;break;case"error":l=`${ne.red}\u2717${ne.reset}`,c=ne.dim;break;case"retry":l=`${ne.yellow}\u21BB${ne.reset}`,c=ne.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}${ne.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?` ${te.dim}${e}${te.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=`${te.green}\u2713${te.reset}`;break;case"error":i=`${te.red}\u2717${te.reset}`;break;case"retry":i=`${te.yellow}\u21BB${te.reset}`;break;default:i=`${te.yellow}\u25CB${te.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} ${te.dim}${c}${te.reset}${a}
6
- `}process.stderr.write(o)}},ar={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},lr={done:te.green,in_progress:te.cyan,pending:te.dim,failed:te.red},hn=null,sa=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=uu[this.frame%uu.length],s=this._formatElapsed(),n=this._formatTokens(),o=[s,n?`\u2193 ${n} tokens`:""].filter(Boolean).join(" \xB7 "),r=o?` ${te.dim}(${o})${te.reset}`:"",i=`\x1B[2K${te.cyan}${e}${te.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=ar[l.status]||ar.pending,d=lr[l.status]||lr.pending,f=l.description.length>55?l.description.substring(0,52)+"...":l.description;i+=`\x1B[2K ${te.dim}${c}${te.reset} ${d}${u}${te.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?` ${ne.dim}${e}${ne.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=`${ne.green}\u2713${ne.reset}`;break;case"error":i=`${ne.red}\u2717${ne.reset}`;break;case"retry":i=`${ne.yellow}\u21BB${ne.reset}`;break;default:i=`${ne.yellow}\u25CB${ne.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} ${ne.dim}${c}${ne.reset}${a}
6
+ `}process.stderr.write(o)}},lr={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},cr={done:ne.green,in_progress:ne.cyan,pending:ne.dim,failed:ne.red},gn=null,ra=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=du[this.frame%du.length],s=this._formatElapsed(),n=this._formatTokens(),o=[s,n?`\u2193 ${n} tokens`:""].filter(Boolean).join(" \xB7 "),r=o?` ${ne.dim}(${o})${ne.reset}`:"",i=`\x1B[2K${ne.cyan}${e}${ne.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=lr[l.status]||lr.pending,d=cr[l.status]||cr.pending,f=l.description.length>55?l.description.substring(0,52)+"...":l.description;i+=`\x1B[2K ${ne.dim}${c}${ne.reset} ${d}${u}${ne.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),hn=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,hn===this&&(hn=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),gn=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,gn===this&&(gn=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${te.green}\u2714${te.reset} ${this.name} ${te.dim}(${e} \xB7 ${r})${te.reset}
12
- `;for(let a=0;a<this.tasks.length;a++){let l=this.tasks[a],c=a===0?"\u23BF":" ",u=ar[l.status]||ar.pending,d=lr[l.status]||lr.pending,f=l.description.length>55?l.description.substring(0,52)+"...":l.description;i+=`\x1B[2K ${te.dim}${c}${te.reset} ${d}${u}${te.reset} ${te.dim}${f}${te.reset}
13
- `}process.stderr.write(i)}},oa=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=ms[this.frame%ms.length],s="";for(let r=0;r<cr;r++)s+=r===e?`${te.cyan}\u25CF${te.reset}`:" ";let n=this.message;this.count>0&&(n+=` ${te.cyan}${this.count}${te.reset}`,this.total&&(n+=`/${this.total}`),this.detail&&(n+=` ${te.dim}${this.detail}${te.reset}`));let o="";if(this.startTime){let r=Math.floor((Date.now()-this.startTime)/1e3);r>=1&&(o=` ${te.dim}${r}s${te.reset}`)}process.stderr.write(`\x1B[2K\r${s} ${te.dim}${n}${te.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 Dy(t){hn=t}function jy(){return hn}function qy(){hn&&(hn.stop(),hn=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}du.exports={C:te,Spinner:ta,MultiProgress:na,TaskProgress:sa,ToolProgress:oa,setActiveTaskProgress:Dy,getActiveTaskProgress:jy,cleanupTerminal:qy}});var ra=z((ST,gu)=>{"use strict";var{T:Rn}=Nt(),ie={kw:Rn.syn_keyword,str:Rn.syn_string,cmt:Rn.syn_comment,num:Rn.syn_number,type:Rn.cyan,punct:Rn.magenta,reset:Rn.reset},fu={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"])},Fy={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 hu(t){if(!t)return null;let e=t.split(".").pop().toLowerCase();return Fy[e]||null}var pu=/\x1b\[[0-9;]*m/g;function sn(t,e,s){let n=t.split(pu),o=t.match(pu)||[],r="";for(let i=0;i<n.length;i++)r+=n[i].replace(e,s),i<o.length&&(r+=o[i]);return r}function By(t){let e=t;return e=e.replace(/"([^"\\]|\\.)*"\s*:/g,s=>ie.type+s+ie.reset),e=sn(e,/"([^"\\]|\\.)*"/g,s=>ie.str+s+ie.reset),e=sn(e,/\b-?(\d+(\.\d+)?([eE][+-]?\d+)?)\b/g,s=>ie.num+s+ie.reset),e=sn(e,/\b(true|false|null)\b/g,s=>ie.kw+s+ie.reset),e}function Uy(t){if(/<!--/.test(t))return t.replace(/<!--[\s\S]*?(?:-->|$)/g,s=>ie.cmt+s+ie.reset);let e=t;return e=e.replace(/(<\/?)([a-zA-Z][a-zA-Z0-9.-]*)/g,(s,n,o)=>n+ie.type+o+ie.reset),e=sn(e,/\s([a-zA-Z][a-zA-Z0-9-]*)=/g,(s,n)=>" "+ie.kw+n+ie.reset+"="),e=sn(e,/"([^"]*)"/g,s=>ie.str+s+ie.reset),e}function Wy(t){let e=t;return e=e.replace(/\/\*[\s\S]*?(?:\*\/|$)/g,s=>ie.cmt+s+ie.reset),e=sn(e,/#[0-9a-fA-F]{3,8}\b/g,s=>ie.num+s+ie.reset),e=sn(e,/\b(-?\d+(?:\.\d+)?)(px|em|rem|vh|vw|vmin|vmax|%|s|ms|deg|fr)\b/g,(s,n,o)=>ie.num+n+ie.reset+o),e=sn(e,/([a-z][a-z-]*)(\s*:)/g,(s,n,o)=>ie.type+n+ie.reset+o),e=sn(e,/"[^"]*"|'[^']*'/g,s=>ie.str+s+ie.reset),e}function mu(t,e,s){if(e==="json")return By(t);if(e==="html"||e==="xml")return Uy(t);if(e==="css")return Wy(t);if(e==="md")return t;let n=fu[e]||fu.js,o="",r=0;if(s.inBlockComment){let i=t.indexOf("*/");if(i===-1)return ie.cmt+t+ie.reset;if(o+=ie.cmt+t.slice(0,i+2)+ie.reset,s.inBlockComment=!1,r=i+2,r>=t.length)return o}if(s.inString==="`"){let i=t.indexOf("`");if(i===-1)return ie.str+t+ie.reset;if(o+=ie.str+t.slice(0,i+1)+ie.reset,s.inString=null,r=i+1,r>=t.length)return o}for(;r<t.length;){let i=t[r];if(!s.inString&&i==="/"&&t[r+1]==="*"){let a=t.indexOf("*/",r+2);if(a===-1)return o+=ie.cmt+t.slice(r)+ie.reset,s.inBlockComment=!0,o;o+=ie.cmt+t.slice(r,a+2)+ie.reset,r=a+2;continue}if(!s.inString&&((e==="js"||e==="go"||e==="rs"||e==="java")&&i==="/"&&t[r+1]==="/"||(e==="py"||e==="sh")&&i==="#"))return o+=ie.cmt+t.slice(r)+ie.reset,o;if(!s.inString&&(i==='"'||i==="'"||i==="`")){s.inString=i,o+=ie.str+i,r++;continue}if(s.inString){if(i==="\\"&&r+1<t.length){o+=i+t[r+1],r+=2;continue}if(i===s.inString){o+=i+ie.reset,s.inString=null,r++;continue}o+=i,r++;continue}if(/[0-9]/.test(i)&&(r===0||!/[a-zA-Z0-9_$]/.test(t[r-1]))){let a="";for(;r<t.length&&/[0-9a-fA-F_.xXoObBeE+-]/.test(t[r])&&!(a.length>0&&/[eE]/.test(t[r-1])&&/[^+-]/.test(i));)a+=t[r++];o+=ie.num+a+ie.reset;continue}if(i==="@"&&(e==="js"||e==="java"||e==="py")){let a="@";for(r++;r<t.length&&/[a-zA-Z0-9_$.]/.test(t[r]);)a+=t[r++];o+=ie.punct+a+ie.reset;continue}if(/[a-zA-Z_$]/.test(i)){let a="";for(;r<t.length&&/[a-zA-Z0-9_$]/.test(t[r]);)a+=t[r++];n.has(a)?o+=ie.kw+a+ie.reset:/^[A-Z][A-Za-z0-9]*$/.test(a)&&e!=="sh"?o+=ie.type+a+ie.reset:o+=a;continue}o+=i,r++}return s.inString&&s.inString!=="`"&&(o+=ie.reset,s.inString=null),o}function Hy(t,e){let s=hu(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${ne.green}\u2714${ne.reset} ${this.name} ${ne.dim}(${e} \xB7 ${r})${ne.reset}
12
+ `;for(let a=0;a<this.tasks.length;a++){let l=this.tasks[a],c=a===0?"\u23BF":" ",u=lr[l.status]||lr.pending,d=cr[l.status]||cr.pending,f=l.description.length>55?l.description.substring(0,52)+"...":l.description;i+=`\x1B[2K ${ne.dim}${c}${ne.reset} ${d}${u}${ne.reset} ${ne.dim}${f}${ne.reset}
13
+ `}process.stderr.write(i)}},ia=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=ms[this.frame%ms.length],s="";for(let r=0;r<ur;r++)s+=r===e?`${ne.cyan}\u25CF${ne.reset}`:" ";let n=this.message;this.count>0&&(n+=` ${ne.cyan}${this.count}${ne.reset}`,this.total&&(n+=`/${this.total}`),this.detail&&(n+=` ${ne.dim}${this.detail}${ne.reset}`));let o="";if(this.startTime){let r=Math.floor((Date.now()-this.startTime)/1e3);r>=1&&(o=` ${ne.dim}${r}s${ne.reset}`)}process.stderr.write(`\x1B[2K\r${s} ${ne.dim}${n}${ne.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 jy(t){gn=t}function qy(){return gn}function Fy(){gn&&(gn.stop(),gn=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}fu.exports={C:ne,Spinner:sa,MultiProgress:oa,TaskProgress:ra,ToolProgress:ia,setActiveTaskProgress:jy,getActiveTaskProgress:qy,cleanupTerminal:Fy}});var aa=z((vT,yu)=>{"use strict";var{T:An}=Dt(),ie={kw:An.syn_keyword,str:An.syn_string,cmt:An.syn_comment,num:An.syn_number,type:An.cyan,punct:An.magenta,reset:An.reset},pu={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"])},By={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 By[e]||null}var hu=/\x1b\[[0-9;]*m/g;function on(t,e,s){let n=t.split(hu),o=t.match(hu)||[],r="";for(let i=0;i<n.length;i++)r+=n[i].replace(e,s),i<o.length&&(r+=o[i]);return r}function Uy(t){let e=t;return e=e.replace(/"([^"\\]|\\.)*"\s*:/g,s=>ie.type+s+ie.reset),e=on(e,/"([^"\\]|\\.)*"/g,s=>ie.str+s+ie.reset),e=on(e,/\b-?(\d+(\.\d+)?([eE][+-]?\d+)?)\b/g,s=>ie.num+s+ie.reset),e=on(e,/\b(true|false|null)\b/g,s=>ie.kw+s+ie.reset),e}function Wy(t){if(/<!--/.test(t))return t.replace(/<!--[\s\S]*?(?:-->|$)/g,s=>ie.cmt+s+ie.reset);let e=t;return e=e.replace(/(<\/?)([a-zA-Z][a-zA-Z0-9.-]*)/g,(s,n,o)=>n+ie.type+o+ie.reset),e=on(e,/\s([a-zA-Z][a-zA-Z0-9-]*)=/g,(s,n)=>" "+ie.kw+n+ie.reset+"="),e=on(e,/"([^"]*)"/g,s=>ie.str+s+ie.reset),e}function Hy(t){let e=t;return e=e.replace(/\/\*[\s\S]*?(?:\*\/|$)/g,s=>ie.cmt+s+ie.reset),e=on(e,/#[0-9a-fA-F]{3,8}\b/g,s=>ie.num+s+ie.reset),e=on(e,/\b(-?\d+(?:\.\d+)?)(px|em|rem|vh|vw|vmin|vmax|%|s|ms|deg|fr)\b/g,(s,n,o)=>ie.num+n+ie.reset+o),e=on(e,/([a-z][a-z-]*)(\s*:)/g,(s,n,o)=>ie.type+n+ie.reset+o),e=on(e,/"[^"]*"|'[^']*'/g,s=>ie.str+s+ie.reset),e}function gu(t,e,s){if(e==="json")return Uy(t);if(e==="html"||e==="xml")return Wy(t);if(e==="css")return Hy(t);if(e==="md")return t;let n=pu[e]||pu.js,o="",r=0;if(s.inBlockComment){let i=t.indexOf("*/");if(i===-1)return ie.cmt+t+ie.reset;if(o+=ie.cmt+t.slice(0,i+2)+ie.reset,s.inBlockComment=!1,r=i+2,r>=t.length)return o}if(s.inString==="`"){let i=t.indexOf("`");if(i===-1)return ie.str+t+ie.reset;if(o+=ie.str+t.slice(0,i+1)+ie.reset,s.inString=null,r=i+1,r>=t.length)return o}for(;r<t.length;){let i=t[r];if(!s.inString&&i==="/"&&t[r+1]==="*"){let a=t.indexOf("*/",r+2);if(a===-1)return o+=ie.cmt+t.slice(r)+ie.reset,s.inBlockComment=!0,o;o+=ie.cmt+t.slice(r,a+2)+ie.reset,r=a+2;continue}if(!s.inString&&((e==="js"||e==="go"||e==="rs"||e==="java")&&i==="/"&&t[r+1]==="/"||(e==="py"||e==="sh")&&i==="#"))return o+=ie.cmt+t.slice(r)+ie.reset,o;if(!s.inString&&(i==='"'||i==="'"||i==="`")){s.inString=i,o+=ie.str+i,r++;continue}if(s.inString){if(i==="\\"&&r+1<t.length){o+=i+t[r+1],r+=2;continue}if(i===s.inString){o+=i+ie.reset,s.inString=null,r++;continue}o+=i,r++;continue}if(/[0-9]/.test(i)&&(r===0||!/[a-zA-Z0-9_$]/.test(t[r-1]))){let a="";for(;r<t.length&&/[0-9a-fA-F_.xXoObBeE+-]/.test(t[r])&&!(a.length>0&&/[eE]/.test(t[r-1])&&/[^+-]/.test(i));)a+=t[r++];o+=ie.num+a+ie.reset;continue}if(i==="@"&&(e==="js"||e==="java"||e==="py")){let a="@";for(r++;r<t.length&&/[a-zA-Z0-9_$.]/.test(t[r]);)a+=t[r++];o+=ie.punct+a+ie.reset;continue}if(/[a-zA-Z_$]/.test(i)){let a="";for(;r<t.length&&/[a-zA-Z0-9_$]/.test(t[r]);)a+=t[r++];n.has(a)?o+=ie.kw+a+ie.reset:/^[A-Z][A-Za-z0-9]*$/.test(a)&&e!=="sh"?o+=ie.type+a+ie.reset:o+=a;continue}o+=i,r++}return s.inString&&s.inString!=="`"&&(o+=ie.reset,s.inString=null),o}function Yy(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=>mu(r,s,o))}function Yy(t,e){return e?mu(t,e,{inString:null,inBlockComment:!1}):t}gu.exports={detectLang:hu,highlightLine:Yy,highlightLines:Hy}});var _u=z((vT,wu)=>{var{T:A}=Nt(),nt=A,Gy={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},ia={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 ur(t,e=!1,s=null){if(e)return`${A.error}\u23FA${A.reset}`;let n=Gy[t]||A.tool_default;return s==="blink"?`${n}\x1B[5m\u23FA\x1B[25m${A.reset}`:`${n}${s!==null?s:"\u23FA"}${A.reset}`}function zy(t,e,s=!1,n=null){let o=(t||[]).filter(l=>l&&l.canExecute!==!1);if(o.length===0)return`${ur("",s,n)} Step ${e}`;if(o.length===1){let l=o[0],c=l.args||{},u=ia[l.fnName]||l.fnName.replace(/_/g," "),d="";c.path?d=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?`(${nt.dim}${d}${nt.reset})`:"";return`${ur(l.fnName,s,n)} ${nt.bold}${u}${nt.reset}${f}`}let r=o[0].fnName,i=[...new Set(o.map(l=>ia[l.fnName]||l.fnName.replace(/_/g," ")))],a=i.length<=3?i.join(", "):`${o.length} tools`;return`${ur(r,s,n)} ${nt.bold}${a}${nt.reset}`}function Ky(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=ia[t]||t.replace(/_/g," "),o=s?`(${nt.dim}${s}${nt.reset})`:"";return`${ur(t)} ${nt.bold}${n}${nt.reset}${o}`}function Xy(t,e=8){let s=t.split(`
15
+ `),o={inString:null,inBlockComment:!1};return n.map(r=>gu(r,s,o))}function Gy(t,e){return e?gu(t,e,{inString:null,inBlockComment:!1}):t}yu.exports={detectLang:mu,highlightLine:Gy,highlightLines:Yy}});var $u=z((ET,_u)=>{var{T:A}=Dt(),st=A,zy={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},la={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 dr(t,e=!1,s=null){if(e)return`${A.error}\u23FA${A.reset}`;let n=zy[t]||A.tool_default;return s==="blink"?`${n}\x1B[5m\u23FA\x1B[25m${A.reset}`:`${n}${s!==null?s:"\u23FA"}${A.reset}`}function Ky(t,e,s=!1,n=null){let o=(t||[]).filter(l=>l&&l.canExecute!==!1);if(o.length===0)return`${dr("",s,n)} Step ${e}`;if(o.length===1){let l=o[0],c=l.args||{},u=la[l.fnName]||l.fnName.replace(/_/g," "),d="";c.path?d=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?`(${st.dim}${d}${st.reset})`:"";return`${dr(l.fnName,s,n)} ${st.bold}${u}${st.reset}${f}`}let r=o[0].fnName,i=[...new Set(o.map(l=>la[l.fnName]||l.fnName.replace(/_/g," ")))],a=i.length<=3?i.join(", "):`${o.length} tools`;return`${dr(r,s,n)} ${st.bold}${a}${st.reset}`}function Xy(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=la[t]||t.replace(/_/g," "),o=s?`(${st.dim}${s}${st.reset})`:"";return`${dr(t)} ${st.bold}${n}${st.reset}${o}`}function Vy(t,e=8){let s=t.split(`
16
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(`
17
17
  `);return o>0&&(a+=`
18
- ${A.subtle} \u2026 +${o} lines${A.reset}`),a}var dr=["Sampling","Decoding","Attending","Inferring","Generating","Routing","Embedding","Reasoning","Tokenizing","Predicting"],yu=Math.floor(Math.random()*dr.length),aa=null;function Vy(t){aa=t}function Jy(){let t=dr[yu%dr.length];yu++;let e=aa?` \xB7 ${aa}`:"";return`${t}${e}`}function Zy(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 Qy(t,e,s,n){let o=String(s||"");if(n){let a=o.split(`
18
+ ${A.subtle} \u2026 +${o} lines${A.reset}`),a}var fr=["Sampling","Decoding","Attending","Inferring","Generating","Routing","Embedding","Reasoning","Tokenizing","Predicting"],wu=Math.floor(Math.random()*fr.length),ca=null;function Jy(t){ca=t}function Zy(){let t=fr[wu%fr.length];wu++;let e=ca?` \xB7 ${ca}`:"";return`${t}${e}`}function Qy(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 e0(t,e,s,n){let o=String(s||"");if(n){let a=o.split(`
19
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
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
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}=ra(),f=d(e.content||"",e.path||null),p=40,h=8;if(l<=p){let g=f.map(_=>` ${_}`).join(`
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}=aa(),f=d(e.content||"",e.path||null),p=40,h=8;if(l<=p){let g=f.map(_=>` ${_}`).join(`
23
23
  `);r=`${u}
24
24
  ${g}`}else{let g=f.slice(0,h).map(_=>` ${_}`).join(`
25
25
  `);r=`${u}
26
26
  ${g}
27
27
  ${A.subtle}\u2026 +${l-h} lines${A.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:_}=ra(),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?`
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:_}=aa(),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
30
  `+O.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
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
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),k=b.substring(O+1),E=k.match(/^(\d+)[:-](.*)/s),N=E?`:${E[1]}`:"",ee=(E?E[2]:k).trim(),X=`${A.subtle}${a.basename(M)}${N}${A.reset}`,ce=`${A.muted}${ee.substring(0,80)}${ee.length>80?"\u2026":""}${A.reset}`;return`${X} ${ce}`};var i=h;let a=require("path"),l=o.split(`
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),k=b.substring(O+1),E=k.match(/^(\d+)[:-](.*)/s),N=E?`:${E[1]}`:"",te=(E?E[2]:k).trim(),X=`${A.subtle}${a.basename(M)}${N}${A.reset}`,ce=`${A.muted}${te.substring(0,80)}${te.length>80?"\u2026":""}${A.reset}`;return`${X} ${ce}`};var i=h;let a=require("path"),l=o.split(`
36
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
37
  ${h(b)}`:` ${h(b)}`),_=l.length-3;_>0&&g.push(` ${A.subtle}\u2026 +${_} lines${A.reset}`),r=g.join(`
38
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(`
@@ -46,88 +46,88 @@ ${g}
46
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
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(`
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 e0(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${nt.reset} ${nt.bold}${t}${nt.reset}`;return l+=`${nt.dim} \xB7 ${a}`,r.size>0&&(l+=` \xB7 ${r.size} file${r.size!==1?"s":""} modified`),l+=nt.reset,l}wu.exports={C:nt,formatToolCall:Ky,formatResult:Xy,getToolSpinnerText:Zy,formatToolSummary:Qy,formatSectionHeader:zy,formatMilestone:e0,getThinkingVerb:Jy,setActiveModelForSpinner:Vy,THINKING_VERBS:dr}});var ze=z((ET,bu)=>{var{T:Cn}=Nt(),la=Cn,$u=["01100110","01111110","01111110","01011010","01111110","00111100"];function t0(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 n0(t,e,s={}){let n=la.bold,o=la.reset,r=t0($u,Cn.banner_logo),i=s.yolo?` ${n}${Cn.banner_yolo}\u26A1 YOLO${o}`:"",a=ir().version,l=[` ${Cn.banner_name}${n}nex-code${o} ${Cn.banner_version}v${a}${o}`,` ${Cn.banner_model}${t}${o} ${Cn.muted}\xB7 /help${o}${i}`,""],c=Math.max(r.length,l.length),u=Math.floor((c-r.length)/2),d=Math.floor((c-l.length)/2),f=$u[0].length,p=[];for(let h=0;h<c;h++){let g=r[h-u]??" ".repeat(f),_=l[h-d]??"";p.push(g+_)}console.log(`
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 t0(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${st.reset} ${st.bold}${t}${st.reset}`;return l+=`${st.dim} \xB7 ${a}`,r.size>0&&(l+=` \xB7 ${r.size} file${r.size!==1?"s":""} modified`),l+=st.reset,l}_u.exports={C:st,formatToolCall:Xy,formatResult:Vy,getToolSpinnerText:Qy,formatToolSummary:e0,formatSectionHeader:Ky,formatMilestone:t0,getThinkingVerb:Zy,setActiveModelForSpinner:Jy,THINKING_VERBS:fr}});var Ke=z((TT,xu)=>{var{T:On}=Dt(),ua=On,bu=["01100110","01111110","01111110","01011010","01111110","00111100"];function n0(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 s0(t,e,s={}){let n=ua.bold,o=ua.reset,r=n0(bu,On.banner_logo),i=s.yolo?` ${n}${On.banner_yolo}\u26A1 YOLO${o}`:"",a=ar().version,l=[` ${On.banner_name}${n}nex-code${o} ${On.banner_version}v${a}${o}`,` ${On.banner_model}${t}${o} ${On.muted}\xB7 /help${o}${i}`,""],c=Math.max(r.length,l.length),u=Math.floor((c-r.length)/2),d=Math.floor((c-l.length)/2),f=bu[0].length,p=[];for(let h=0;h<c;h++){let g=r[h-u]??" ".repeat(f),_=l[h-d]??"";p.push(g+_)}console.log(`
51
51
  `+p.join(`
52
52
  `)+`
53
- `)}var{Spinner:s0,MultiProgress:o0,TaskProgress:r0,ToolProgress:i0,setActiveTaskProgress:a0,getActiveTaskProgress:l0,cleanupTerminal:c0}=gs(),{formatToolCall:u0,formatResult:d0,getToolSpinnerText:f0,formatToolSummary:p0,formatSectionHeader:h0,formatMilestone:m0,getThinkingVerb:g0,setActiveModelForSpinner:y0}=_u();bu.exports={C:la,banner:n0,Spinner:s0,MultiProgress:o0,TaskProgress:r0,ToolProgress:i0,setActiveTaskProgress:a0,getActiveTaskProgress:l0,cleanupTerminal:c0,formatToolCall:u0,formatResult:d0,getToolSpinnerText:f0,formatToolSummary:p0,formatSectionHeader:h0,formatMilestone:m0,getThinkingVerb:g0,setActiveModelForSpinner:y0}});var ys=z((TT,xu)=>{async function w0(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 ca=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`)}};xu.exports={BaseProvider:ca,readStreamErrorBody:w0}});var $s=z((RT,Su)=>{var ws=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")}},_s=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")}},fr=class extends _s{constructor(e,s={}){super(e,s),this.toolCallsMap={}}parseLine(e){let s=e.trim();if(!s||!s.startsWith("data: "))return{done:!1};let n=s.slice(6);if(n==="[DONE]")return{done:!0,result:this.getResult()};let o;try{o=JSON.parse(n)}catch{return{done:!1}}let r=o.choices?.[0]?.delta;if(!r)return{done:!1};if(r.content&&(this.onToken(r.content),this.content+=r.content),r.tool_calls)for(let i of r.tool_calls){let a=i.index??0;this.toolCallsMap[a]||(this.toolCallsMap[a]={id:i.id||"",name:"",arguments:""}),i.id&&(this.toolCallsMap[a].id=i.id),i.function?.name&&(this.toolCallsMap[a].name+=i.function.name),i.function?.arguments&&(this.toolCallsMap[a].arguments+=i.function.arguments)}return{done:!1}}getResult(){return{content:this.content,tool_calls:Object.values(this.toolCallsMap).filter(e=>e.name).map(e=>({id:e.id||`call-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,function:{name:e.name,arguments:e.arguments}}))}}},pr=class extends ws{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 fr(e,s)}},hr=class extends _s{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}}})}}},ua="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->",mr=class extends ws{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(ua);if(u!==-1){let d=c.slice(0,u).trimEnd(),f=c.slice(u+ua.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 hr(e,s)}};function ku(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 gr=class extends _s{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:ku(e.function?.arguments??e.arguments)}}))}}},yr=class extends ws{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:ku(n.function?.arguments??n.arguments)}}))}}createStreamParser(e,s={}){return new gr(e,s)}},_0=new pr,$0=new mr,b0=new yr;Su.exports={ANTHROPIC_CACHE_BOUNDARY:ua,WireProtocol:ws,StreamParser:_s,OpenAICompatibleProtocol:pr,AnthropicProtocol:mr,OllamaChatProtocol:yr,OpenAIStreamParser:fr,AnthropicStreamParser:hr,OllamaStreamParser:gr,openaiProtocol:_0,anthropicProtocol:$0,ollamaProtocol:b0}});var Tu=z((CT,Eu)=>{var wr=require("axios"),x0=require("http"),k0=require("https"),{BaseProvider:S0,readStreamErrorBody:v0}=ys(),{ollamaProtocol:An}=$s(),_r=new x0.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),$r=new k0.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),vu={"qwen3-coder:480b":{id:"qwen3-coder:480b",name:"Qwen3 Coder 480B",maxTokens:16384,contextWindow:131072},"qwen3-coder-next":{id:"qwen3-coder-next",name:"Qwen3 Coder Next",maxTokens:16384,contextWindow:262144},"devstral-2:123b":{id:"devstral-2:123b",name:"Devstral 2 123B",maxTokens:16384,contextWindow:131072},"devstral-small-2:24b":{id:"devstral-small-2:24b",name:"Devstral Small 2 24B",maxTokens:16384,contextWindow:131072},"minimax-m2.7:cloud":{id:"minimax-m2.7:cloud",name:"MiniMax M2.7 Cloud",maxTokens:16384,contextWindow:131072},"kimi-k2.5":{id:"kimi-k2.5",name:"Kimi K2.5",maxTokens:16384,contextWindow:256e3},"kimi-k2:1t":{id:"kimi-k2:1t",name:"Kimi K2 1T",maxTokens:16384,contextWindow:256e3},"kimi-k2-thinking":{id:"kimi-k2-thinking",name:"Kimi K2 Thinking",maxTokens:16384,contextWindow:256e3},"deepseek-v3.2":{id:"deepseek-v3.2",name:"DeepSeek V3.2",maxTokens:16384,contextWindow:131072},"deepseek-v3.1:671b":{id:"deepseek-v3.1:671b",name:"DeepSeek V3.1 671B",maxTokens:16384,contextWindow:131072},"cogito-2.1:671b":{id:"cogito-2.1:671b",name:"Cogito 2.1 671B",maxTokens:16384,contextWindow:131072},"qwen3.5:397b-cloud":{id:"qwen3.5:397b-cloud",name:"Qwen3.5 397B Cloud",maxTokens:16384,contextWindow:262144},"qwen3.5:397b":{id:"qwen3.5:397b",name:"Qwen3.5 397B",maxTokens:16384,contextWindow:262144},"qwen3.5:122b-a10b":{id:"qwen3.5:122b-a10b",name:"Qwen3.5 122B-A10B",maxTokens:16384,contextWindow:262144},"qwen3.5:35b-a3b":{id:"qwen3.5:35b-a3b",name:"Qwen3.5 35B-A3B",maxTokens:16384,contextWindow:262144},"qwen3.5:27b":{id:"qwen3.5:27b",name:"Qwen3.5 27B",maxTokens:16384,contextWindow:262144},"qwen3-next:80b":{id:"qwen3-next:80b",name:"Qwen3 Next 80B",maxTokens:16384,contextWindow:131072},"mistral-large-3:675b":{id:"mistral-large-3:675b",name:"Mistral Large 3 675B",maxTokens:16384,contextWindow:131072},"gpt-oss:120b":{id:"gpt-oss:120b",name:"GPT-OSS 120B",maxTokens:16384,contextWindow:131072},"minimax-m2.5":{id:"minimax-m2.5",name:"MiniMax M2.5",maxTokens:16384,contextWindow:131072},"glm-5:cloud":{id:"glm-5:cloud",name:"GLM 5 Cloud",maxTokens:16384,contextWindow:2e5},"glm-5":{id:"glm-5",name:"GLM 5",maxTokens:16384,contextWindow:2e5},"glm-4.6":{id:"glm-4.6",name:"GLM 4.6",maxTokens:16384,contextWindow:2e5},"glm-4.7":{id:"glm-4.7",name:"GLM 4.7",maxTokens:16384,contextWindow:128e3},"nemotron-3-super:cloud":{id:"nemotron-3-super:cloud",name:"Nemotron 3 Super Cloud",maxTokens:16384,contextWindow:262144},"qwen3.5:9b":{id:"qwen3.5:9b",name:"Qwen3.5 9B",maxTokens:8192,contextWindow:262144},"qwen3.5:4b":{id:"qwen3.5:4b",name:"Qwen3.5 4B",maxTokens:8192,contextWindow:262144},"qwen3.5:2b":{id:"qwen3.5:2b",name:"Qwen3.5 2B",maxTokens:8192,contextWindow:262144},"qwen3.5:0.8b":{id:"qwen3.5:0.8b",name:"Qwen3.5 0.8B",maxTokens:8192,contextWindow:262144},"gemma3:27b":{id:"gemma3:27b",name:"Gemma 3 27B",maxTokens:8192,contextWindow:131072},"gemma3:12b":{id:"gemma3:12b",name:"Gemma 3 12B",maxTokens:8192,contextWindow:131072},"gemma3:4b":{id:"gemma3:4b",name:"Gemma 3 4B",maxTokens:8192,contextWindow:131072},"ministral-3:14b":{id:"ministral-3:14b",name:"Ministral 3 14B",maxTokens:8192,contextWindow:131072},"ministral-3:8b":{id:"ministral-3:8b",name:"Ministral 3 8B",maxTokens:8192,contextWindow:131072},"gemini-3-flash-preview":{id:"gemini-3-flash-preview",name:"Gemini 3 Flash Preview",maxTokens:16384,contextWindow:131072}},da=class extends S0{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||vu,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){wr.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:_r,httpsAgent:$r}).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 wr.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:_r,httpsAgent:$r})).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=An.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 wr.post(`${this.baseUrl}${An.getEndpoint()}`,a,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),httpAgent:_r,httpsAgent:$r})}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 An.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=An.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 wr.post(`${this.baseUrl}${An.getEndpoint()}`,c,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal,httpAgent:_r,httpsAgent:$r})}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 v0(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=An.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 An.normalizeResponse(e)}};Eu.exports={OllamaProvider:da,OLLAMA_MODELS:vu}});var Ou=z((AT,Au)=>{var Ru=require("axios"),{BaseProvider:E0,readStreamErrorBody:T0}=ys(),{openaiProtocol:On}=$s(),Cu={"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}},fa=class extends E0{constructor(e={}){super({name:"openai",baseUrl:e.baseUrl||"https://api.openai.com/v1",models:e.models||Cu,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=On.buildRequestBody({model:o,messages:a,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!1}),c;try{c=await Ru.post(`${this.baseUrl}${On.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 On.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=On.buildRequestBody({model:o,messages:l,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!0}),u;try{u=await Ru.post(`${this.baseUrl}${On.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 T0(f,g=>g?.error?.message||g?.error);throw new Error(`API Error${p}: ${h}`)}let d=On.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 On.normalizeResponse(e)}};Au.exports={OpenAIProvider:fa,OPENAI_MODELS:Cu}});var Lu=z((OT,Pu)=>{var Nu=require("axios"),{BaseProvider:R0,readStreamErrorBody:C0}=ys(),{anthropicProtocol:mn}=$s(),Mu={"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}},A0="2023-06-01",pa=class extends R0{constructor(e={}){super({name:"anthropic",baseUrl:e.baseUrl||"https://api.anthropic.com/v1",models:e.models||Mu,defaultModel:e.defaultModel||"claude-sonnet",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this.apiVersion=e.apiVersion||A0}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 mn.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=mn.buildRequestBody({model:r,messages:l,tools:u,maxTokens:a,temperature:n.temperature??this.temperature,stream:!1,extra:{system:c}}),f;try{f=await Nu.post(`${this.baseUrl}${mn.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 mn.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=mn.buildRequestBody({model:r,messages:c,tools:d,maxTokens:a,temperature:n.temperature??this.temperature,stream:!0,extra:{system:u}}),p;try{p=await Nu.post(`${this.baseUrl}${mn.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 C0(g,O=>O?.error?.message||O?.error);throw new Error(`API Error${_}: ${b}`)}let h=mn.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 mn.normalizeResponse(e)}};Pu.exports={AnthropicProvider:pa,ANTHROPIC_MODELS:Mu}});var qu=z((NT,ju)=>{var Iu=require("axios"),{BaseProvider:O0,readStreamErrorBody:N0}=ys(),{openaiProtocol:Nn}=$s(),Du={"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}},ha=class extends O0{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||Du,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=Nn.buildRequestBody({model:o,messages:a,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!1}),c;try{c=await Iu.post(`${this.baseUrl}${Nn.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 Nn.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=Nn.buildRequestBody({model:o,messages:l,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!0}),u;try{u=await Iu.post(`${this.baseUrl}${Nn.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 N0(f,g=>g?.error?.message||g?.error);throw new Error(`API Error${p}: ${h}`)}let d=Nn.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 Nn.normalizeResponse(e)}};ju.exports={GeminiProvider:ha,GEMINI_MODELS:Du}});var Uu=z((MT,Bu)=>{var br=require("axios"),{BaseProvider:M0,readStreamErrorBody:P0}=ys(),{ollamaProtocol:Mn}=$s(),Fu="http://localhost:11434",ma=class extends M0{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||Fu,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 br.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 br.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=Mn.buildRequestBody({model:o,messages:this._formatMessages(e),tools:s,maxTokens:n.maxTokens||8192,temperature:n.temperature??this.temperature,stream:!1}),i;try{i=await br.post(`${this.baseUrl}${Mn.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 Mn.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=Mn.buildRequestBody({model:o,messages:this._formatMessages(e),tools:s,maxTokens:n.maxTokens||8192,temperature:n.temperature??this.temperature,stream:!0}),a;try{a=await br.post(`${this.baseUrl}${Mn.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 P0(c,f=>f?.error);throw new Error(`API Error${u}: ${d}`)}let l=Mn.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 Mn.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}};Bu.exports={LocalProvider:ma,DEFAULT_LOCAL_URL:Fu}});var Pn=z((PT,Hu)=>{"use strict";var wt=require("fs"),Wu=require("path");function L0(t){if(!t||isNaN(t))return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function I0(t){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}catch{let e=Date.now()+t;for(;Date.now()<e;);}}function D0(t,e){let s=Wu.dirname(t),n=Wu.join(s,`.nex-tmp.${process.pid}.${Date.now()}`);try{wt.existsSync(s)||wt.mkdirSync(s,{recursive:!0,mode:448}),wt.writeFileSync(n,e,{encoding:"utf-8",mode:384}),wt.renameSync(n,t)}catch(o){try{wt.unlinkSync(n)}catch{}throw o}}function j0(t,e,{timeout:s=5e3,retryMs:n=50}={}){let o=t+".lock",r=Date.now()+s;for(;;){let i=-1;try{i=wt.openSync(o,"wx"),wt.writeSync(i,Buffer.from(String(process.pid))),wt.closeSync(i),i=-1;try{return e()}finally{try{wt.unlinkSync(o)}catch{}}}catch(a){if(i!==-1)try{wt.closeSync(i)}catch{}if(a.code!=="EEXIST")throw a;try{let l=wt.readFileSync(o,"utf-8").trim(),c=parseInt(l,10);if(!L0(c)){try{wt.unlinkSync(o)}catch{}continue}}catch(l){if(l.code&&l.code!=="ENOENT")throw l;continue}if(Date.now()>=r){try{wt.unlinkSync(o)}catch{}return e()}I0(n)}}}Hu.exports={atomicWrite:D0,withFileLockSync:j0}});var kr=z((LT,Zu)=>{var bs=require("fs"),ga=require("path"),{T:Yu}=Nt(),{atomicWrite:q0,withFileLockSync:F0}=Pn(),Gu={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:{}},xr=[],gn={};function B0(t,e,s,n){if(xr.push({provider:t,model:e,input:s,output:n}),gn[t]!==void 0){let o=Vu(t);o.allowed||process.stderr.write(`${Yu.yellow}\u26A0 Budget limit reached for ${t}: $${o.spent.toFixed(2)} / $${o.limit.toFixed(2)}${Yu.reset}
60
- `)}}function ya(t,e){let s=Gu[t];return s?s[e]||{input:0,output:0}:{input:0,output:0}}function zu(t){let e=ya(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function Ku(){let t={};for(let r of xr){let i=`${r.provider}:${r.model}`;t[i]||(t[i]={provider:r.provider,model:r.model,input:0,output:0}),t[i].input+=r.input,t[i].output+=r.output}let e=Object.values(t).map(r=>({...r,cost:zu(r)})),s=e.reduce((r,i)=>r+i.cost,0),n=e.reduce((r,i)=>r+i.input,0),o=e.reduce((r,i)=>r+i.output,0);return{totalCost:s,totalInput:n,totalOutput:o,breakdown:e}}function U0(){let{totalCost:t,totalInput:e,totalOutput:s,breakdown:n}=Ku();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 W0(t){return!t||typeof t!="string"?0:Math.ceil(t.length/4)}function H0(t,e,s,n){let o=ya(t,e),r=(s*o.input+n*o.output)/1e6;return r<=0?"":`[~$${r.toFixed(4)}]`}function Y0(){xr=[]}function G0(t,e){gn[t]=e}function z0(t){delete gn[t]}function K0(){return{...gn}}function Xu(t){let e=0;for(let s of xr)s.provider===t&&(e+=zu(s));return e}function Vu(t){let e=Xu(t),s=gn[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 Ju(){let t=ga.join(process.cwd(),".nex","config.json");if(bs.existsSync(t))try{let e=JSON.parse(bs.readFileSync(t,"utf-8"));e.costLimits&&typeof e.costLimits=="object"&&(gn={...e.costLimits})}catch{}}function X0(){let t=ga.join(process.cwd(),".nex"),e=ga.join(t,"config.json");bs.existsSync(t)||bs.mkdirSync(t,{recursive:!0}),F0(e,()=>{let s={};if(bs.existsSync(e))try{s=JSON.parse(bs.readFileSync(e,"utf-8"))}catch{s={}}s.costLimits=gn,q0(e,JSON.stringify(s,null,2))})}function V0(){gn={}}Ju();Zu.exports={PRICING:Gu,trackUsage:B0,getSessionCosts:Ku,formatCosts:U0,formatCostHint:H0,resetCosts:Y0,getPricing:ya,setCostLimit:G0,removeCostLimit:z0,getCostLimits:K0,getProviderSpend:Xu,checkBudget:Vu,loadCostLimits:Ju,saveCostLimits:X0,resetCostLimits:V0,estimateTokens:W0}});var Sr=z((IT,Qu)=>{function wa(){return process.env.NEX_DEBUG==="true"||process.argv.includes("--debug")}var J0=wa();function Z0(...t){wa()&&console.log(...t)}function Q0(...t){wa()&&console.warn(...t)}Qu.exports={DEBUG:J0,debugLog:Z0,warnLog:Q0}});var nd=z((DT,td)=>{"use strict";var ew=new Set(["read_file","grep","glob","search_files","list_directory"]),tw=new Set(["write_file","edit_file","patch_file"]),nw=new Set(["bash"]),sw=new Set(["web_search","web_fetch","perplexity_search"]);function ed(t,e){let s=0,n=0,o=0,r=0,i=0;for(let[a,l]of t)i+=l,ew.has(a)&&(s+=l),tw.has(a)&&(n+=l),nw.has(a)&&(o+=l),sw.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 _a=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:ed(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}};td.exports={MilestoneTracker:_a,_phaseName:ed}});var Zs=z((jT,sd)=>{var Js=Ve(),ow={"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 rw(){return Js.getActiveModel()}function iw(t){return Js.setActiveModel(t)}function aw(){return Js.getModelNames()}function lw(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 cw(t,e){let{C:s}=ze(),{Spinner:n}=ze(),o=new n("Thinking...");o.start();let r=!0,i="";try{let a=await Js.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 uw(t,e){return Js.callChat(t,e)}sd.exports={MODELS:ow,getActiveModel:rw,setActiveModel:iw,getModelNames:aw,callOllamaStream:cw,callOllama:uw,parseToolArgs:lw}});var eo=z((qT,cd)=>{var dw=require("readline"),{C:Ht}=ze(),fw=/[\u200B\u200C\u200D\uFEFF\u2060\u00AD]/g,pw=/^=([\w-]+)/;function Qs(t){return typeof t!="string"?t:t.replace(fw,"").replace(pw,"$1")}var xa=[/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/],od=[...xa,/\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 hw(t){for(let e of od)if(e.test(t))return e;return null}var rd=[/\.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)/],mw=/\b(?:rm|rmdir|unlink|truncate|shred|mv|cp)\b/,$a=[/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 id(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)):$a.some(l=>l.test(r))}return/^\w+=\$?\(/.test(i)||/^\w+=["']/.test(i)||/^\w+=\S/.test(i)?!0:$a.some(a=>a.test(i))};return n.every(o)}var ka=[/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)/],ad=[/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/],ld=[...ka,...ad],Sa=!1,Ln=null,ba=null;function gw(t){Sa=t}function yw(t){ba=t}function ww(){return Sa}function _w(t){Ln=t}function $w(t){let e=Qs(t);for(let s of xa)if(s.test(e))return s;return null}function bw(t){let e=Qs(t);if(/ssh\s/.test(e)&&id(e))return!1;for(let s of ld)if(s.test(e))return!0;return!1}function xw(t){let e=Qs(t);for(let s of ka)if(s.test(e))return!0;return!1}function kw(t){if(process.env.NEX_UNPROTECT==="1")return null;let e=Qs(t);if(!mw.test(e))return null;for(let s of rd)if(s.test(e))return s;return null}function Sw(t,e={}){if(Sa)return Promise.resolve(!0);if(ba)return ba(t,e);if(!process.stdout.isTTY||!process.stdin.isTTY)return vw(t,e);let s=e.toolName?["Yes","No","Always allow"]:["Yes","No"];return new Promise(n=>{let o=0;Ln&&Ln.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${Ht.yellow}${t}${Ht.reset}`;for(let p=0;p<s.length;p++){let h=p===o,g=h?`${Ht.yellow}\u276F${Ht.reset}`:" ",_=h?`${Ht.yellow}${s[p]}${Ht.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(),Ln&&Ln.resume(),n(d)},c=d=>{if(d===1){l(!1);return}d===2&&e.toolName&&vr(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){vr(e.toolName),l(!0);return}};a(),process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",u)})}function vw(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?(vr(e.toolName),n(!0)):n(i!=="n")};if(Ln)Ln.question(`${Ht.yellow}${t} ${s}${Ht.reset}`,o);else{let r=dw.createInterface({input:process.stdin,output:process.stdout});r.question(`${Ht.yellow}${t} ${s}${Ht.reset}`,i=>{r.close(),o(i)})}})}var vr=()=>{};function Ew(t){vr=t}cd.exports={sanitizeBashCommand:Qs,FORBIDDEN_PATTERNS:xa,SSH_FORBIDDEN_PATTERNS:od,BASH_PROTECTED_PATHS:rd,SSH_SAFE_PATTERNS:$a,isSSHReadOnly:id,DANGEROUS_BASH:ld,CRITICAL_BASH:ka,NOTABLE_BASH:ad,isForbidden:$w,isSSHForbidden:hw,isDangerous:bw,isCritical:xw,isBashPathForbidden:kw,confirm:Sw,setAutoConfirm:gw,getAutoConfirm:ww,setConfirmHook:yw,setReadlineInterface:_w,setAllowAlwaysHandler:Ew}});var fd=z((BT,dd)=>{var Er=require("path"),{C:D}=ze(),{T:va,isDark:FT}=Nt(),{confirm:Tw,getAutoConfirm:Rw}=eo(),ud=2e3;function to(t,e){let s=t.split(`
53
+ `)}var{Spinner:o0,MultiProgress:r0,TaskProgress:i0,ToolProgress:a0,setActiveTaskProgress:l0,getActiveTaskProgress:c0,cleanupTerminal:u0}=gs(),{formatToolCall:d0,formatResult:f0,getToolSpinnerText:p0,formatToolSummary:h0,formatSectionHeader:m0,formatMilestone:g0,getThinkingVerb:y0,setActiveModelForSpinner:w0}=$u();xu.exports={C:ua,banner:s0,Spinner:o0,MultiProgress:r0,TaskProgress:i0,ToolProgress:a0,setActiveTaskProgress:l0,getActiveTaskProgress:c0,cleanupTerminal:u0,formatToolCall:d0,formatResult:f0,getToolSpinnerText:p0,formatToolSummary:h0,formatSectionHeader:m0,formatMilestone:g0,getThinkingVerb:y0,setActiveModelForSpinner:w0}});var ys=z((RT,ku)=>{async function _0(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 da=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`)}};ku.exports={BaseProvider:da,readStreamErrorBody:_0}});var $s=z((CT,vu)=>{var ws=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")}},_s=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")}},pr=class extends _s{constructor(e,s={}){super(e,s),this.toolCallsMap={}}parseLine(e){let s=e.trim();if(!s||!s.startsWith("data: "))return{done:!1};let n=s.slice(6);if(n==="[DONE]")return{done:!0,result:this.getResult()};let o;try{o=JSON.parse(n)}catch{return{done:!1}}let r=o.choices?.[0]?.delta;if(!r)return{done:!1};if(r.content&&(this.onToken(r.content),this.content+=r.content),r.tool_calls)for(let i of r.tool_calls){let a=i.index??0;this.toolCallsMap[a]||(this.toolCallsMap[a]={id:i.id||"",name:"",arguments:""}),i.id&&(this.toolCallsMap[a].id=i.id),i.function?.name&&(this.toolCallsMap[a].name+=i.function.name),i.function?.arguments&&(this.toolCallsMap[a].arguments+=i.function.arguments)}return{done:!1}}getResult(){return{content:this.content,tool_calls:Object.values(this.toolCallsMap).filter(e=>e.name).map(e=>({id:e.id||`call-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,function:{name:e.name,arguments:e.arguments}}))}}},hr=class extends ws{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 pr(e,s)}},mr=class extends _s{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}}})}}},fa="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->",gr=class extends ws{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(fa);if(u!==-1){let d=c.slice(0,u).trimEnd(),f=c.slice(u+fa.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 mr(e,s)}};function Su(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 yr=class extends _s{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:Su(e.function?.arguments??e.arguments)}}))}}},wr=class extends ws{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:Su(n.function?.arguments??n.arguments)}}))}}createStreamParser(e,s={}){return new yr(e,s)}},$0=new hr,b0=new gr,x0=new wr;vu.exports={ANTHROPIC_CACHE_BOUNDARY:fa,WireProtocol:ws,StreamParser:_s,OpenAICompatibleProtocol:hr,AnthropicProtocol:gr,OllamaChatProtocol:wr,OpenAIStreamParser:pr,AnthropicStreamParser:mr,OllamaStreamParser:yr,openaiProtocol:$0,anthropicProtocol:b0,ollamaProtocol:x0}});var Ru=z((AT,Tu)=>{var _r=require("axios"),k0=require("http"),S0=require("https"),{BaseProvider:v0,readStreamErrorBody:E0}=ys(),{ollamaProtocol:Nn}=$s(),$r=new k0.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),br=new S0.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Eu={"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}},pa=class extends v0{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||Eu,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){_r.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:$r,httpsAgent:br}).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 _r.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:$r,httpsAgent:br})).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=Nn.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 _r.post(`${this.baseUrl}${Nn.getEndpoint()}`,a,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),httpAgent:$r,httpsAgent:br})}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 Nn.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=Nn.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 _r.post(`${this.baseUrl}${Nn.getEndpoint()}`,c,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal,httpAgent:$r,httpsAgent:br})}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 E0(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=Nn.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 Nn.normalizeResponse(e)}};Tu.exports={OllamaProvider:pa,OLLAMA_MODELS:Eu}});var Nu=z((OT,Ou)=>{var Cu=require("axios"),{BaseProvider:T0,readStreamErrorBody:R0}=ys(),{openaiProtocol:Mn}=$s(),Au={"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}},ha=class extends T0{constructor(e={}){super({name:"openai",baseUrl:e.baseUrl||"https://api.openai.com/v1",models:e.models||Au,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=Mn.buildRequestBody({model:o,messages:a,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!1}),c;try{c=await Cu.post(`${this.baseUrl}${Mn.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 Mn.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=Mn.buildRequestBody({model:o,messages:l,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!0}),u;try{u=await Cu.post(`${this.baseUrl}${Mn.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 R0(f,g=>g?.error?.message||g?.error);throw new Error(`API Error${p}: ${h}`)}let d=Mn.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 Mn.normalizeResponse(e)}};Ou.exports={OpenAIProvider:ha,OPENAI_MODELS:Au}});var Iu=z((NT,Lu)=>{var Mu=require("axios"),{BaseProvider:C0,readStreamErrorBody:A0}=ys(),{anthropicProtocol:yn}=$s(),Pu={"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}},O0="2023-06-01",ma=class extends C0{constructor(e={}){super({name:"anthropic",baseUrl:e.baseUrl||"https://api.anthropic.com/v1",models:e.models||Pu,defaultModel:e.defaultModel||"claude-sonnet",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this.apiVersion=e.apiVersion||O0}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 yn.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=yn.buildRequestBody({model:r,messages:l,tools:u,maxTokens:a,temperature:n.temperature??this.temperature,stream:!1,extra:{system:c}}),f;try{f=await Mu.post(`${this.baseUrl}${yn.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 yn.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=yn.buildRequestBody({model:r,messages:c,tools:d,maxTokens:a,temperature:n.temperature??this.temperature,stream:!0,extra:{system:u}}),p;try{p=await Mu.post(`${this.baseUrl}${yn.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 A0(g,O=>O?.error?.message||O?.error);throw new Error(`API Error${_}: ${b}`)}let h=yn.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 yn.normalizeResponse(e)}};Lu.exports={AnthropicProvider:ma,ANTHROPIC_MODELS:Pu}});var Fu=z((MT,qu)=>{var Du=require("axios"),{BaseProvider:N0,readStreamErrorBody:M0}=ys(),{openaiProtocol:Pn}=$s(),ju={"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}},ga=class extends N0{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||ju,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=Pn.buildRequestBody({model:o,messages:a,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!1}),c;try{c=await Du.post(`${this.baseUrl}${Pn.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 Pn.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=Pn.buildRequestBody({model:o,messages:l,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!0}),u;try{u=await Du.post(`${this.baseUrl}${Pn.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 M0(f,g=>g?.error?.message||g?.error);throw new Error(`API Error${p}: ${h}`)}let d=Pn.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 Pn.normalizeResponse(e)}};qu.exports={GeminiProvider:ga,GEMINI_MODELS:ju}});var Wu=z((PT,Uu)=>{var xr=require("axios"),{BaseProvider:P0,readStreamErrorBody:L0}=ys(),{ollamaProtocol:Ln}=$s(),Bu="http://localhost:11434",ya=class extends P0{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||Bu,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 xr.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 xr.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=Ln.buildRequestBody({model:o,messages:this._formatMessages(e),tools:s,maxTokens:n.maxTokens||8192,temperature:n.temperature??this.temperature,stream:!1}),i;try{i=await xr.post(`${this.baseUrl}${Ln.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 Ln.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=Ln.buildRequestBody({model:o,messages:this._formatMessages(e),tools:s,maxTokens:n.maxTokens||8192,temperature:n.temperature??this.temperature,stream:!0}),a;try{a=await xr.post(`${this.baseUrl}${Ln.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 L0(c,f=>f?.error);throw new Error(`API Error${u}: ${d}`)}let l=Ln.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 Ln.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}};Uu.exports={LocalProvider:ya,DEFAULT_LOCAL_URL:Bu}});var In=z((LT,Yu)=>{"use strict";var $t=require("fs"),Hu=require("path");function I0(t){if(!t||isNaN(t))return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function D0(t){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}catch{let e=Date.now()+t;for(;Date.now()<e;);}}function j0(t,e){let s=Hu.dirname(t),n=Hu.join(s,`.nex-tmp.${process.pid}.${Date.now()}`);try{$t.existsSync(s)||$t.mkdirSync(s,{recursive:!0,mode:448}),$t.writeFileSync(n,e,{encoding:"utf-8",mode:384}),$t.renameSync(n,t)}catch(o){try{$t.unlinkSync(n)}catch{}throw o}}function q0(t,e,{timeout:s=5e3,retryMs:n=50}={}){let o=t+".lock",r=Date.now()+s;for(;;){let i=-1;try{i=$t.openSync(o,"wx"),$t.writeSync(i,Buffer.from(String(process.pid))),$t.closeSync(i),i=-1;try{return e()}finally{try{$t.unlinkSync(o)}catch{}}}catch(a){if(i!==-1)try{$t.closeSync(i)}catch{}if(a.code!=="EEXIST")throw a;try{let l=$t.readFileSync(o,"utf-8").trim(),c=parseInt(l,10);if(!I0(c)){try{$t.unlinkSync(o)}catch{}continue}}catch(l){if(l.code&&l.code!=="ENOENT")throw l;continue}if(Date.now()>=r){try{$t.unlinkSync(o)}catch{}return e()}D0(n)}}}Yu.exports={atomicWrite:j0,withFileLockSync:q0}});var Sr=z((IT,Qu)=>{var bs=require("fs"),wa=require("path"),{T:Gu}=Dt(),{atomicWrite:F0,withFileLockSync:B0}=In(),zu={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:{}},kr=[],wn={};function U0(t,e,s,n){if(kr.push({provider:t,model:e,input:s,output:n}),wn[t]!==void 0){let o=Ju(t);o.allowed||process.stderr.write(`${Gu.yellow}\u26A0 Budget limit reached for ${t}: $${o.spent.toFixed(2)} / $${o.limit.toFixed(2)}${Gu.reset}
60
+ `)}}function _a(t,e){let s=zu[t];return s?s[e]||{input:0,output:0}:{input:0,output:0}}function Ku(t){let e=_a(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function Xu(){let t={};for(let r of kr){let i=`${r.provider}:${r.model}`;t[i]||(t[i]={provider:r.provider,model:r.model,input:0,output:0}),t[i].input+=r.input,t[i].output+=r.output}let e=Object.values(t).map(r=>({...r,cost:Ku(r)})),s=e.reduce((r,i)=>r+i.cost,0),n=e.reduce((r,i)=>r+i.input,0),o=e.reduce((r,i)=>r+i.output,0);return{totalCost:s,totalInput:n,totalOutput:o,breakdown:e}}function W0(){let{totalCost:t,totalInput:e,totalOutput:s,breakdown:n}=Xu();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 H0(t){return!t||typeof t!="string"?0:Math.ceil(t.length/4)}function Y0(t,e,s,n){let o=_a(t,e),r=(s*o.input+n*o.output)/1e6;return r<=0?"":`[~$${r.toFixed(4)}]`}function G0(){kr=[]}function z0(t,e){wn[t]=e}function K0(t){delete wn[t]}function X0(){return{...wn}}function Vu(t){let e=0;for(let s of kr)s.provider===t&&(e+=Ku(s));return e}function Ju(t){let e=Vu(t),s=wn[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 Zu(){let t=wa.join(process.cwd(),".nex","config.json");if(bs.existsSync(t))try{let e=JSON.parse(bs.readFileSync(t,"utf-8"));e.costLimits&&typeof e.costLimits=="object"&&(wn={...e.costLimits})}catch{}}function V0(){let t=wa.join(process.cwd(),".nex"),e=wa.join(t,"config.json");bs.existsSync(t)||bs.mkdirSync(t,{recursive:!0}),B0(e,()=>{let s={};if(bs.existsSync(e))try{s=JSON.parse(bs.readFileSync(e,"utf-8"))}catch{s={}}s.costLimits=wn,F0(e,JSON.stringify(s,null,2))})}function J0(){wn={}}Zu();Qu.exports={PRICING:zu,trackUsage:U0,getSessionCosts:Xu,formatCosts:W0,formatCostHint:Y0,resetCosts:G0,getPricing:_a,setCostLimit:z0,removeCostLimit:K0,getCostLimits:X0,getProviderSpend:Vu,checkBudget:Ju,loadCostLimits:Zu,saveCostLimits:V0,resetCostLimits:J0,estimateTokens:H0}});var vr=z((DT,ed)=>{function $a(){return process.env.NEX_DEBUG==="true"||process.argv.includes("--debug")}var Z0=$a();function Q0(...t){$a()&&console.log(...t)}function ew(...t){$a()&&console.warn(...t)}ed.exports={DEBUG:Z0,debugLog:Q0,warnLog:ew}});var sd=z((jT,nd)=>{"use strict";var tw=new Set(["read_file","grep","glob","search_files","list_directory"]),nw=new Set(["write_file","edit_file","patch_file"]),sw=new Set(["bash"]),ow=new Set(["web_search","web_fetch","perplexity_search"]);function td(t,e){let s=0,n=0,o=0,r=0,i=0;for(let[a,l]of t)i+=l,tw.has(a)&&(s+=l),nw.has(a)&&(n+=l),sw.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 ba=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:td(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}};nd.exports={MilestoneTracker:ba,_phaseName:td}});var Zs=z((qT,od)=>{var Js=Ze(),rw={"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 iw(){return Js.getActiveModel()}function aw(t){return Js.setActiveModel(t)}function lw(){return Js.getModelNames()}function cw(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 uw(t,e){let{C:s}=Ke(),{Spinner:n}=Ke(),o=new n("Thinking...");o.start();let r=!0,i="";try{let a=await Js.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 dw(t,e){return Js.callChat(t,e)}od.exports={MODELS:rw,getActiveModel:iw,setActiveModel:aw,getModelNames:lw,callOllamaStream:uw,callOllama:dw,parseToolArgs:cw}});var eo=z((FT,ud)=>{var fw=require("readline"),{C:zt}=Ke(),pw=/[\u200B\u200C\u200D\uFEFF\u2060\u00AD]/g,hw=/^=([\w-]+)/;function Qs(t){return typeof t!="string"?t:t.replace(pw,"").replace(hw,"$1")}var Sa=[/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/],rd=[...Sa,/\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 rd)if(e.test(t))return e;return null}var id=[/\.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)/],gw=/\b(?:rm|rmdir|unlink|truncate|shred|mv|cp)\b/,xa=[/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 ad(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)):xa.some(l=>l.test(r))}return/^\w+=\$?\(/.test(i)||/^\w+=["']/.test(i)||/^\w+=\S/.test(i)?!0:xa.some(a=>a.test(i))};return n.every(o)}var va=[/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)/],ld=[/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/],cd=[...va,...ld],Ea=!1,Dn=null,ka=null;function yw(t){Ea=t}function ww(t){ka=t}function _w(){return Ea}function $w(t){Dn=t}function bw(t){let e=Qs(t);for(let s of Sa)if(s.test(e))return s;return null}function xw(t){let e=Qs(t);if(/ssh\s/.test(e)&&ad(e))return!1;for(let s of cd)if(s.test(e))return!0;return!1}function kw(t){let e=Qs(t);for(let s of va)if(s.test(e))return!0;return!1}function Sw(t){if(process.env.NEX_UNPROTECT==="1")return null;let e=Qs(t);if(!gw.test(e))return null;for(let s of id)if(s.test(e))return s;return null}function vw(t,e={}){if(Ea)return Promise.resolve(!0);if(ka)return ka(t,e);if(!process.stdout.isTTY||!process.stdin.isTTY)return Ew(t,e);let s=e.toolName?["Yes","No","Always allow"]:["Yes","No"];return new Promise(n=>{let o=0;Dn&&Dn.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${zt.yellow}${t}${zt.reset}`;for(let p=0;p<s.length;p++){let h=p===o,g=h?`${zt.yellow}\u276F${zt.reset}`:" ",_=h?`${zt.yellow}${s[p]}${zt.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(),Dn&&Dn.resume(),n(d)},c=d=>{if(d===1){l(!1);return}d===2&&e.toolName&&Er(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){Er(e.toolName),l(!0);return}};a(),process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",u)})}function Ew(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?(Er(e.toolName),n(!0)):n(i!=="n")};if(Dn)Dn.question(`${zt.yellow}${t} ${s}${zt.reset}`,o);else{let r=fw.createInterface({input:process.stdin,output:process.stdout});r.question(`${zt.yellow}${t} ${s}${zt.reset}`,i=>{r.close(),o(i)})}})}var Er=()=>{};function Tw(t){Er=t}ud.exports={sanitizeBashCommand:Qs,FORBIDDEN_PATTERNS:Sa,SSH_FORBIDDEN_PATTERNS:rd,BASH_PROTECTED_PATHS:id,SSH_SAFE_PATTERNS:xa,isSSHReadOnly:ad,DANGEROUS_BASH:cd,CRITICAL_BASH:va,NOTABLE_BASH:ld,isForbidden:bw,isSSHForbidden:mw,isDangerous:xw,isCritical:kw,isBashPathForbidden:Sw,confirm:vw,setAutoConfirm:yw,getAutoConfirm:_w,setConfirmHook:ww,setReadlineInterface:$w,setAllowAlwaysHandler:Tw}});var pd=z((UT,fd)=>{var Tr=require("path"),{C:j}=Ke(),{T:Ta,isDark:BT}=Dt(),{confirm:Rw,getAutoConfirm:Cw}=eo(),dd=2e3;function to(t,e){let s=t.split(`
64
64
  `),n=e.split(`
65
- `),o=[],r=s.length,i=n.length;if(r>ud||i>ud){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 Cw(t,e,s,n=3){console.log(`
66
- ${D.bold}${D.cyan} Diff: ${t}${D.reset}`);let o=to(e,s),r=[];if(o.forEach((l,c)=>{l.type!=="same"&&r.push(c)}),r.length===0){console.log(`${D.gray} (no changes)${D.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(`${D.gray} ...${D.reset}`);for(let l=i;l<a;l++){let c=o[l];switch(c.type){case"remove":console.log(`${D.red} - ${c.line}${D.reset}`);break;case"add":console.log(`${D.green} + ${c.line}${D.reset}`);break;default:console.log(`${D.gray} ${c.line}${D.reset}`)}}a<o.length&&console.log(`${D.gray} ...${D.reset}`),console.log()}function Aw(t,e,s){console.log(`
67
- ${D.bold}${D.cyan} File exists \u2014 showing changes: ${t}${D.reset}`);let n=to(e,s),o=0;for(let i of n)i.type!=="same"&&o++;if(o===0){console.log(`${D.gray} (identical content)${D.reset}`);return}let r=0;for(let i of n){if(r>=30){console.log(`${D.gray} ...(${o-r} more changes)${D.reset}`);break}switch(i.type){case"remove":console.log(`${D.red} - ${i.line}${D.reset}`),r++;break;case"add":console.log(`${D.green} + ${i.line}${D.reset}`),r++;break;default:r>0&&console.log(`${D.gray} ${i.line}${D.reset}`)}}console.log()}function Ow(t,e){console.log(`
68
- ${D.bold}${D.cyan} New file: ${t}${D.reset}`);let s=e.split(`
69
- `),n=s.slice(0,20);for(let o of n)console.log(`${D.green} + ${o}${D.reset}`);s.length>20&&console.log(`${D.gray} ...+${s.length-20} more lines${D.reset}`),console.log()}async function Nw(t){return Rw()?!0:Tw(` ${t}?`)}function Mw(t,e,s,n){let o=n||process.stdout.columns||80,r=Math.floor((o-3)/2);console.log(`
70
- ${D.bold}${D.cyan} Side-by-side: ${t}${D.reset}`),console.log(` ${D.dim}${"\u2500".repeat(r)}\u252C${"\u2500".repeat(r)}${D.reset}`);let i=to(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(` ${D.gray}(no changes)${D.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(` ${D.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${D.reset}`);for(let p=u;p<d;p++){let h=a[p];if(h.type==="same")console.log(` ${D.gray}${f(h.left,r)}${D.reset}\u2502${D.gray}${f(h.right,r)}${D.reset}`);else{let g=h.left?`${D.red}${f(h.left,r)}${D.reset}`:`${f("",r)}`,_=h.right?`${D.green}${f(h.right,r)}${D.reset}`:`${f("",r)}`;console.log(` ${g}\u2502${_}`)}}d<a.length&&console.log(` ${D.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${D.reset}`),console.log(` ${D.dim}${"\u2500".repeat(r)}\u2534${"\u2500".repeat(r)}${D.reset}
71
- `)}function Pw(t,e,s,n={}){let o=n.label||"Update",r=n.context||3,i=n.annotations||[],a=Er.isAbsolute(t)?Er.relative(process.cwd(),t):t,l=to(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(`
72
- ${D.green}\u23FA${D.reset} ${D.bold}${o}(${a})${D.reset}`),d===0&&f===0){console.log(` ${D.dim}\u23BF (no changes)${D.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(ae=>ae.severity==="error").length,ee=i.filter(ae=>ae.severity==="warn").length,X=i.filter(ae=>ae.severity==="info").length,ce=[];N>0&&ce.push(`${D.red}${N} error${N!==1?"s":""}${D.dim}`),ee>0&&ce.push(`${D.yellow}${ee} warning${ee!==1?"s":""}${D.dim}`),X>0&&ce.push(`${D.cyan}${X} info${X!==1?"s":""}${D.dim}`),p.push(`found ${ce.join(", ")}`)}console.log(` ${D.dim}\u23BF ${p.join(", ")}${D.reset}`);let g=[];l.forEach((N,ee)=>{N.type!=="same"&&g.push(ee)});let _=[],b=null,O=null;for(let N of g){let ee=Math.max(0,N-r),X=Math.min(l.length-1,N+r);b===null?(b=ee,O=X):(ee<=O+1||(_.push([b,O]),b=ee),O=X)}b!==null&&_.push([b,O]);let M=" ",k=process.stdout.columns||120;function E(N,ee,X){let ce=X.replace(/\x1b\[[0-9;]*m/g,""),ae=X+" ".repeat(Math.max(0,k-ce.length));return`${N}${ee}${ae}${D.reset}`}for(let N=0;N<_.length;N++){N>0&&console.log(`${M}${D.dim}\xB7\xB7\xB7${D.reset}`);let[ee,X]=_[N];for(let ce=ee;ce<=X;ce++){let ae=l[ce],ne=ae.newLine!=null?ae.newLine:ae.oldLine,S=String(ne).padStart(4),Te=ae.type!=="remove"?i.filter(H=>H.line===ae.newLine):[];ae.type==="remove"?console.log(E(va.diff_rem_bg,D.red,`${M}${S} - ${ae.line}`)):ae.type==="add"?console.log(E(va.diff_add_bg,D.green,`${M}${S} + ${ae.line}`)):console.log(`${M}${D.dim}${S} ${D.reset}${ae.line}`);for(let H of Te){let K=D.cyan,pe="\u2139";H.severity==="error"?(K=D.red,pe="\u2716"):H.severity==="warn"&&(K=D.yellow,pe="\u26A0"),console.log(`${M} ${K}${pe} ${H.message}${D.reset}`)}}}console.log()}function Lw(t,e,s={}){let n=Er.isAbsolute(t)?Er.relative(process.cwd(),t):t,o=e.split(`
65
+ `),o=[],r=s.length,i=n.length;if(r>dd||i>dd){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 Aw(t,e,s,n=3){console.log(`
66
+ ${j.bold}${j.cyan} Diff: ${t}${j.reset}`);let o=to(e,s),r=[];if(o.forEach((l,c)=>{l.type!=="same"&&r.push(c)}),r.length===0){console.log(`${j.gray} (no changes)${j.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(`${j.gray} ...${j.reset}`);for(let l=i;l<a;l++){let c=o[l];switch(c.type){case"remove":console.log(`${j.red} - ${c.line}${j.reset}`);break;case"add":console.log(`${j.green} + ${c.line}${j.reset}`);break;default:console.log(`${j.gray} ${c.line}${j.reset}`)}}a<o.length&&console.log(`${j.gray} ...${j.reset}`),console.log()}function Ow(t,e,s){console.log(`
67
+ ${j.bold}${j.cyan} File exists \u2014 showing changes: ${t}${j.reset}`);let n=to(e,s),o=0;for(let i of n)i.type!=="same"&&o++;if(o===0){console.log(`${j.gray} (identical content)${j.reset}`);return}let r=0;for(let i of n){if(r>=30){console.log(`${j.gray} ...(${o-r} more changes)${j.reset}`);break}switch(i.type){case"remove":console.log(`${j.red} - ${i.line}${j.reset}`),r++;break;case"add":console.log(`${j.green} + ${i.line}${j.reset}`),r++;break;default:r>0&&console.log(`${j.gray} ${i.line}${j.reset}`)}}console.log()}function Nw(t,e){console.log(`
68
+ ${j.bold}${j.cyan} New file: ${t}${j.reset}`);let s=e.split(`
69
+ `),n=s.slice(0,20);for(let o of n)console.log(`${j.green} + ${o}${j.reset}`);s.length>20&&console.log(`${j.gray} ...+${s.length-20} more lines${j.reset}`),console.log()}async function Mw(t){return Cw()?!0:Rw(` ${t}?`)}function Pw(t,e,s,n){let o=n||process.stdout.columns||80,r=Math.floor((o-3)/2);console.log(`
70
+ ${j.bold}${j.cyan} Side-by-side: ${t}${j.reset}`),console.log(` ${j.dim}${"\u2500".repeat(r)}\u252C${"\u2500".repeat(r)}${j.reset}`);let i=to(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(` ${j.gray}(no changes)${j.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(` ${j.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${j.reset}`);for(let p=u;p<d;p++){let h=a[p];if(h.type==="same")console.log(` ${j.gray}${f(h.left,r)}${j.reset}\u2502${j.gray}${f(h.right,r)}${j.reset}`);else{let g=h.left?`${j.red}${f(h.left,r)}${j.reset}`:`${f("",r)}`,_=h.right?`${j.green}${f(h.right,r)}${j.reset}`:`${f("",r)}`;console.log(` ${g}\u2502${_}`)}}d<a.length&&console.log(` ${j.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${j.reset}`),console.log(` ${j.dim}${"\u2500".repeat(r)}\u2534${"\u2500".repeat(r)}${j.reset}
71
+ `)}function Lw(t,e,s,n={}){let o=n.label||"Update",r=n.context||3,i=n.annotations||[],a=Tr.isAbsolute(t)?Tr.relative(process.cwd(),t):t,l=to(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(`
72
+ ${j.green}\u23FA${j.reset} ${j.bold}${o}(${a})${j.reset}`),d===0&&f===0){console.log(` ${j.dim}\u23BF (no changes)${j.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(ae=>ae.severity==="error").length,te=i.filter(ae=>ae.severity==="warn").length,X=i.filter(ae=>ae.severity==="info").length,ce=[];N>0&&ce.push(`${j.red}${N} error${N!==1?"s":""}${j.dim}`),te>0&&ce.push(`${j.yellow}${te} warning${te!==1?"s":""}${j.dim}`),X>0&&ce.push(`${j.cyan}${X} info${X!==1?"s":""}${j.dim}`),p.push(`found ${ce.join(", ")}`)}console.log(` ${j.dim}\u23BF ${p.join(", ")}${j.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),X=Math.min(l.length-1,N+r);b===null?(b=te,O=X):(te<=O+1||(_.push([b,O]),b=te),O=X)}b!==null&&_.push([b,O]);let M=" ",k=process.stdout.columns||120;function E(N,te,X){let ce=X.replace(/\x1b\[[0-9;]*m/g,""),ae=X+" ".repeat(Math.max(0,k-ce.length));return`${N}${te}${ae}${j.reset}`}for(let N=0;N<_.length;N++){N>0&&console.log(`${M}${j.dim}\xB7\xB7\xB7${j.reset}`);let[te,X]=_[N];for(let ce=te;ce<=X;ce++){let ae=l[ce],se=ae.newLine!=null?ae.newLine:ae.oldLine,S=String(se).padStart(4),Re=ae.type!=="remove"?i.filter(H=>H.line===ae.newLine):[];ae.type==="remove"?console.log(E(Ta.diff_rem_bg,j.red,`${M}${S} - ${ae.line}`)):ae.type==="add"?console.log(E(Ta.diff_add_bg,j.green,`${M}${S} + ${ae.line}`)):console.log(`${M}${j.dim}${S} ${j.reset}${ae.line}`);for(let H of Re){let K=j.cyan,pe="\u2139";H.severity==="error"?(K=j.red,pe="\u2716"):H.severity==="warn"&&(K=j.yellow,pe="\u26A0"),console.log(`${M} ${K}${pe} ${H.message}${j.reset}`)}}}console.log()}function Iw(t,e,s={}){let n=Tr.isAbsolute(t)?Tr.relative(process.cwd(),t):t,o=e.split(`
74
74
  `),r=s.annotations||[];console.log(`
75
- ${D.green}\u23FA${D.reset} ${D.bold}Create(${n})${D.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(`${D.red}${d} error${d!==1?"s":""}${D.dim}`),f>0&&h.push(`${D.yellow}${f} warning${f!==1?"s":""}${D.dim}`),p>0&&h.push(`${D.cyan}${p} info${p!==1?"s":""}${D.dim}`),i.push(`found ${h.join(", ")}`)}console.log(` ${D.dim}\u23BF ${i.join(", ")}${D.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(`${va.diff_add_bg}${D.green}${b}${D.reset}`);for(let O of h){let M=D.cyan,k="\u2139";O.severity==="error"?(M=D.red,k="\u2716"):O.severity==="warn"&&(M=D.yellow,k="\u26A0"),console.log(`${l} ${M}${k} ${O.message}${D.reset}`)}}o.length>20&&console.log(`${l}${D.dim} ...+${o.length-20} more lines${D.reset}`),console.log()}dd.exports={diffLines:to,showEditDiff:Cw,showWriteDiff:Aw,showNewFilePreview:Ow,confirmFileChange:Nw,showSideBySideDiff:Mw,showDiff:Pw,showNewFile:Lw}});var Cr=z((UT,md)=>{var pd=require("util").promisify(require("child_process").exec),Iw=require("util").promisify(require("child_process").execFile),{C:Ie}=ze();async function Ea(t){try{let{stdout:e}=await pd(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function Tr(...t){try{let{stdout:e}=await Iw("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function Dw(){return await Ea("git rev-parse --is-inside-work-tree")==="true"}async function jw(){return await Ea("git branch --show-current")}async function Ta(){try{let{stdout:t}=await pd("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 Rr(t=!1){return await Ea(`git diff ${t?"--cached":""}`)||""}async function Ra(){return(await Ta()).map(e=>e.file)}async function hd(){let t=await Ra();if(t.length===0)return null;let e=await Rr(),n=await Rr(!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 qw(t){let s=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await Tr("checkout","-b",s)!==null?s:null}async function Fw(t){return await Tr("add","-A"),await Tr("commit","-m",t)?await Tr("rev-parse","--short","HEAD"):null}async function Bw(){let t=await hd();if(!t)return`${Ie.dim}No changes${Ie.reset}`;let e=[];e.push(`
78
- ${Ie.bold}${Ie.cyan}Git Diff Summary:${Ie.reset}`),e.push(` ${Ie.green}+${t.stats.additions}${Ie.reset} ${Ie.red}-${t.stats.deletions}${Ie.reset} in ${t.files.length} file(s)`),e.push(`
79
- ${Ie.bold}${Ie.cyan}Files:${Ie.reset}`);for(let s of t.files.slice(0,20))e.push(` ${Ie.dim}${s}${Ie.reset}`);return t.files.length>20&&e.push(` ${Ie.dim}...+${t.files.length-20} more${Ie.reset}`),e.push(`
80
- ${Ie.bold}${Ie.cyan}Suggested message:${Ie.reset}`),e.push(` ${Ie.cyan}${t.summary}${Ie.reset}
75
+ ${j.green}\u23FA${j.reset} ${j.bold}Create(${n})${j.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(`${j.red}${d} error${d!==1?"s":""}${j.dim}`),f>0&&h.push(`${j.yellow}${f} warning${f!==1?"s":""}${j.dim}`),p>0&&h.push(`${j.cyan}${p} info${p!==1?"s":""}${j.dim}`),i.push(`found ${h.join(", ")}`)}console.log(` ${j.dim}\u23BF ${i.join(", ")}${j.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(`${Ta.diff_add_bg}${j.green}${b}${j.reset}`);for(let O of h){let M=j.cyan,k="\u2139";O.severity==="error"?(M=j.red,k="\u2716"):O.severity==="warn"&&(M=j.yellow,k="\u26A0"),console.log(`${l} ${M}${k} ${O.message}${j.reset}`)}}o.length>20&&console.log(`${l}${j.dim} ...+${o.length-20} more lines${j.reset}`),console.log()}fd.exports={diffLines:to,showEditDiff:Aw,showWriteDiff:Ow,showNewFilePreview:Nw,confirmFileChange:Mw,showSideBySideDiff:Pw,showDiff:Lw,showNewFile:Iw}});var Ar=z((WT,gd)=>{var hd=require("util").promisify(require("child_process").exec),Dw=require("util").promisify(require("child_process").execFile),{C:De}=Ke();async function Ra(t){try{let{stdout:e}=await hd(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function Rr(...t){try{let{stdout:e}=await Dw("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function jw(){return await Ra("git rev-parse --is-inside-work-tree")==="true"}async function qw(){return await Ra("git branch --show-current")}async function Ca(){try{let{stdout:t}=await hd("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 Cr(t=!1){return await Ra(`git diff ${t?"--cached":""}`)||""}async function Aa(){return(await Ca()).map(e=>e.file)}async function md(){let t=await Aa();if(t.length===0)return null;let e=await Cr(),n=await Cr(!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 Fw(t){let s=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await Rr("checkout","-b",s)!==null?s:null}async function Bw(t){return await Rr("add","-A"),await Rr("commit","-m",t)?await Rr("rev-parse","--short","HEAD"):null}async function Uw(){let t=await md();if(!t)return`${De.dim}No changes${De.reset}`;let e=[];e.push(`
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
+ ${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
+ ${De.bold}${De.cyan}Suggested message:${De.reset}`),e.push(` ${De.cyan}${t.summary}${De.reset}
81
81
  `),e.join(`
82
- `)}async function Uw(){return(await Ta()).filter(e=>e.status==="UU"||e.status==="AA"||e.status==="DD")}async function Ww(){let t=await Ra();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 Rr();if(s){let n=s.length>5e3?s.substring(0,5e3)+`
82
+ `)}async function Ww(){return(await Ca()).filter(e=>e.status==="UU"||e.status==="AA"||e.status==="DD")}async function Hw(){let t=await Aa();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 Cr();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
- `)}md.exports={isGitRepo:Dw,getCurrentBranch:jw,getStatus:Ta,getDiff:Rr,getChangedFiles:Ra,analyzeDiff:hd,createBranch:qw,commit:Fw,formatDiffSummary:Bw,getDiffContext:Ww,getMergeConflicts:Uw}});var kd=z((HT,xd)=>{var Je=require("fs").promises,WT=require("fs"),vt=require("path"),Hw=require("crypto"),{execSync:Ca,execFileSync:wd}=require("child_process"),Yw=100*1024,_d=50,ut=[],xs=[];function Gw(t,e,s,n){for(ut.push({tool:t,filePath:e,oldContent:s,newContent:n,timestamp:Date.now()});ut.length>_d;)ut.shift();xs.length=0,$d(ut[ut.length-1]).catch(()=>{})}async function zw(){if(ut.length===0)return null;let t=ut.pop();if(t.oldContent===null)try{await Je.unlink(t.filePath)}catch{}else await Je.writeFile(t.filePath,t.oldContent,"utf-8");return xs.push(t),{tool:t.tool,filePath:t.filePath,wasCreated:t.oldContent===null}}async function Kw(){if(xs.length===0)return null;let t=xs.pop();return await Je.writeFile(t.filePath,t.newContent,"utf-8"),ut.push(t),{tool:t.tool,filePath:t.filePath}}function Xw(t=10){return ut.slice(-t).reverse().map(e=>({tool:e.tool,filePath:e.filePath,timestamp:e.timestamp}))}function Vw(){return ut.length}function Jw(){return xs.length}function Zw({diskToo:t=!0}={}){if(ut.length=0,xs.length=0,t){let e=Or();Je.readdir(e).then(s=>{for(let n of s)n.endsWith(".json")&&Je.unlink(vt.join(e,n)).catch(()=>{})}).catch(()=>{})}}function Or(){return vt.join(process.cwd(),".nex","history")}async function gd(t,e){if(t==null)return{inline:!0,content:t};if(Buffer.byteLength(t,"utf-8")<=Yw)return{inline:!0,content:t};let s=Hw.createHash("sha256").update(t,"utf-8").digest("hex"),n=vt.join(e,"blobs");return await Je.mkdir(n,{recursive:!0}),await Je.writeFile(vt.join(n,s),t,"utf-8"),{inline:!1,hash:s}}async function $d(t){let e=Or();await Je.mkdir(e,{recursive:!0});let s=vt.basename(t.filePath).replace(/[^a-zA-Z0-9]/g,"-"),n=`${t.timestamp}-${s}.json`,o=await gd(t.oldContent,e),r=await gd(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 Je.writeFile(vt.join(e,n),JSON.stringify(i),"utf-8")}async function yd(t,e){if(!t)return null;if(t.inline)return t.content;let s=vt.join(e,"blobs",t.hash);return Je.readFile(s,"utf-8")}async function Qw(){let t=Or(),e;try{e=await Je.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 Je.readFile(vt.join(t,o),"utf-8"),i=JSON.parse(r),a=await yd(i.oldContent,t),l=await yd(i.newContent,t);ut.push({tool:i.tool,filePath:i.filePath,timestamp:i.timestamp,oldContent:a,newContent:l}),n++}catch{}for(;ut.length>_d;)ut.shift();return n}async function e_(t=7){let e=Or(),s;try{s=await Je.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 Je.readFile(vt.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 Je.unlink(vt.join(e,c))}catch{}let l=vt.join(e,"blobs");try{let c=await Je.readdir(l);for(let u of c)if(!i.has(u))try{await Je.unlink(vt.join(l,u))}catch{}}catch{}return r}var Ar="nex-snapshot";function t_(t,e=process.cwd()){let s=t?`${Ar}-${t.replace(/[^a-zA-Z0-9_-]/g,"-")}`:`${Ar}-${Date.now()}`;try{return Ca("git status --porcelain",{cwd:e,timeout:1e4}).toString().trim()?(wd("git",["stash","push","-u","-m",s],{cwd:e,timeout:15e3}),Ca("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 bd(t=process.cwd()){try{let e=Ca("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(Ar)?{index:parseInt(n[1],10),label:o,shortName:o.replace(`${Ar}-`,""),date:s}:null}).filter(Boolean):[]}catch{return[]}}function n_(t,e=process.cwd()){try{let s=bd(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?(wd("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}}}xd.exports={recordChange:Gw,undo:zw,redo:Kw,getHistory:Xw,getUndoCount:Vw,getRedoCount:Jw,clearHistory:Zw,persistEntry:$d,loadPersistedHistory:Qw,pruneHistory:e_,createSnapshot:t_,listSnapshots:bd,restoreSnapshot:n_}});var Pa=z((YT,Cd)=>{var Ce=require("fs"),dt=require("path"),{atomicWrite:s_,withFileLockSync:o_}=Pn(),rt=[];function no(){return dt.join(process.cwd(),".nex","skills")}function Sd(){return dt.join(process.cwd(),".nex","config.json")}function vd(){let t=no();return Ce.existsSync(t)||Ce.mkdirSync(t,{recursive:!0}),t}function Na(){let t=Sd();if(!Ce.existsSync(t))return[];try{let e=JSON.parse(Ce.readFileSync(t,"utf-8"));return e.skills&&Array.isArray(e.skills.disabled)?e.skills.disabled:[]}catch{return[]}}function Ed(t){let e=Sd(),s=dt.dirname(e);Ce.existsSync(s)||Ce.mkdirSync(s,{recursive:!0}),o_(e,()=>{let n={};if(Ce.existsSync(e))try{n=JSON.parse(Ce.readFileSync(e,"utf-8"))}catch{n={}}n.skills||(n.skills={}),n.skills.disabled=t,s_(e,JSON.stringify(n,null,2))})}function Td(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 Rd(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 Aa(t){try{let e=Ce.readFileSync(t,"utf-8").trim();if(!e)return null;let s=dt.basename(t,".md"),{triggers:n,body:o}=Rd(e);return{name:s,type:"prompt",filePath:t,instructions:o||e,triggers:n,commands:[],tools:[]}}catch{return null}}function Oa(t){try{let e=require(t),{valid:s,errors:n}=Td(e,t);return s?{name:e.name||dt.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
+ `)}gd.exports={isGitRepo:jw,getCurrentBranch:qw,getStatus:Ca,getDiff:Cr,getChangedFiles:Aa,analyzeDiff:md,createBranch:Fw,commit:Bw,formatDiffSummary:Uw,getDiffContext:Hw,getMergeConflicts:Ww}});var Sd=z((YT,kd)=>{var Qe=require("fs").promises,HT=require("fs"),Rt=require("path"),Yw=require("crypto"),{execSync:Oa,execFileSync:_d}=require("child_process"),Gw=100*1024,$d=50,ht=[],xs=[];function zw(t,e,s,n){for(ht.push({tool:t,filePath:e,oldContent:s,newContent:n,timestamp:Date.now()});ht.length>$d;)ht.shift();xs.length=0,bd(ht[ht.length-1]).catch(()=>{})}async function Kw(){if(ht.length===0)return null;let t=ht.pop();if(t.oldContent===null)try{await Qe.unlink(t.filePath)}catch{}else await Qe.writeFile(t.filePath,t.oldContent,"utf-8");return xs.push(t),{tool:t.tool,filePath:t.filePath,wasCreated:t.oldContent===null}}async function Xw(){if(xs.length===0)return null;let t=xs.pop();return await Qe.writeFile(t.filePath,t.newContent,"utf-8"),ht.push(t),{tool:t.tool,filePath:t.filePath}}function Vw(t=10){return ht.slice(-t).reverse().map(e=>({tool:e.tool,filePath:e.filePath,timestamp:e.timestamp}))}function Jw(){return ht.length}function Zw(){return xs.length}function Qw({diskToo:t=!0}={}){if(ht.length=0,xs.length=0,t){let e=Nr();Qe.readdir(e).then(s=>{for(let n of s)n.endsWith(".json")&&Qe.unlink(Rt.join(e,n)).catch(()=>{})}).catch(()=>{})}}function Nr(){return Rt.join(process.cwd(),".nex","history")}async function yd(t,e){if(t==null)return{inline:!0,content:t};if(Buffer.byteLength(t,"utf-8")<=Gw)return{inline:!0,content:t};let s=Yw.createHash("sha256").update(t,"utf-8").digest("hex"),n=Rt.join(e,"blobs");return await Qe.mkdir(n,{recursive:!0}),await Qe.writeFile(Rt.join(n,s),t,"utf-8"),{inline:!1,hash:s}}async function bd(t){let e=Nr();await Qe.mkdir(e,{recursive:!0});let s=Rt.basename(t.filePath).replace(/[^a-zA-Z0-9]/g,"-"),n=`${t.timestamp}-${s}.json`,o=await yd(t.oldContent,e),r=await yd(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(Rt.join(e,n),JSON.stringify(i),"utf-8")}async function wd(t,e){if(!t)return null;if(t.inline)return t.content;let s=Rt.join(e,"blobs",t.hash);return Qe.readFile(s,"utf-8")}async function e_(){let t=Nr(),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(Rt.join(t,o),"utf-8"),i=JSON.parse(r),a=await wd(i.oldContent,t),l=await wd(i.newContent,t);ht.push({tool:i.tool,filePath:i.filePath,timestamp:i.timestamp,oldContent:a,newContent:l}),n++}catch{}for(;ht.length>$d;)ht.shift();return n}async function t_(t=7){let e=Nr(),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(Rt.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(Rt.join(e,c))}catch{}let l=Rt.join(e,"blobs");try{let c=await Qe.readdir(l);for(let u of c)if(!i.has(u))try{await Qe.unlink(Rt.join(l,u))}catch{}}catch{}return r}var Or="nex-snapshot";function n_(t,e=process.cwd()){let s=t?`${Or}-${t.replace(/[^a-zA-Z0-9_-]/g,"-")}`:`${Or}-${Date.now()}`;try{return Oa("git status --porcelain",{cwd:e,timeout:1e4}).toString().trim()?(_d("git",["stash","push","-u","-m",s],{cwd:e,timeout:15e3}),Oa("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 xd(t=process.cwd()){try{let e=Oa("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(Or)?{index:parseInt(n[1],10),label:o,shortName:o.replace(`${Or}-`,""),date:s}:null}).filter(Boolean):[]}catch{return[]}}function s_(t,e=process.cwd()){try{let s=xd(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?(_d("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}}}kd.exports={recordChange:zw,undo:Kw,redo:Xw,getHistory:Vw,getUndoCount:Jw,getRedoCount:Zw,clearHistory:Qw,persistEntry:bd,loadPersistedHistory:e_,pruneHistory:t_,createSnapshot:n_,listSnapshots:xd,restoreSnapshot:s_}});var Ia=z((GT,Ad)=>{var Ae=require("fs"),mt=require("path"),{atomicWrite:o_,withFileLockSync:r_}=In(),lt=[];function no(){return mt.join(process.cwd(),".nex","skills")}function vd(){return mt.join(process.cwd(),".nex","config.json")}function Ed(){let t=no();return Ae.existsSync(t)||Ae.mkdirSync(t,{recursive:!0}),t}function Pa(){let t=vd();if(!Ae.existsSync(t))return[];try{let e=JSON.parse(Ae.readFileSync(t,"utf-8"));return e.skills&&Array.isArray(e.skills.disabled)?e.skills.disabled:[]}catch{return[]}}function Td(t){let e=vd(),s=mt.dirname(e);Ae.existsSync(s)||Ae.mkdirSync(s,{recursive:!0}),r_(e,()=>{let n={};if(Ae.existsSync(e))try{n=JSON.parse(Ae.readFileSync(e,"utf-8"))}catch{n={}}n.skills||(n.skills={}),n.skills.disabled=t,o_(e,JSON.stringify(n,null,2))})}function Rd(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 Cd(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 Na(t){try{let e=Ae.readFileSync(t,"utf-8").trim();if(!e)return null;let s=mt.basename(t,".md"),{triggers:n,body:o}=Cd(e);return{name:s,type:"prompt",filePath:t,instructions:o||e,triggers:n,commands:[],tools:[]}}catch{return null}}function Ma(t){try{let e=require(t),{valid:s,errors:n}=Rd(e,t);return s?{name:e.name||mt.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 Ma(){rt=[];let t=Na(),e=no(),s=[];if(Ce.existsSync(e))try{s=Ce.readdirSync(e)}catch{s=[]}for(let o of s){let r=dt.join(e,o),i;try{i=Ce.statSync(r)}catch{continue}if(!i.isFile())continue;let a=null;o.endsWith(".md")?a=Aa(r):o.endsWith(".js")&&(a=Oa(r)),a&&(a.enabled=!t.includes(a.name),rt.push(a))}let n=dt.join(__dirname,"skills");if(!process.env.NEX_SKIP_BUILTIN_SKILLS&&Ce.existsSync(n)){let o;try{o=Ce.readdirSync(n).filter(r=>r.endsWith(".md")||r.endsWith(".js"))}catch{o=[]}for(let r of o){let i=dt.join(n,r),a=dt.basename(r,dt.extname(r));if(rt.some(u=>u.name===a))continue;let l;try{l=Ce.statSync(i)}catch{continue}if(!l.isFile())continue;let c=r.endsWith(".md")?Aa(i):Oa(i);c&&(c._builtin=!0,c.enabled=!t.includes(c.name),rt.push(c))}}return rt}function r_(){let t=[];for(let e of rt)!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 La(){lt=[];let t=Pa(),e=no(),s=[];if(Ae.existsSync(e))try{s=Ae.readdirSync(e)}catch{s=[]}for(let o of s){let r=mt.join(e,o),i;try{i=Ae.statSync(r)}catch{continue}if(!i.isFile())continue;let a=null;o.endsWith(".md")?a=Na(r):o.endsWith(".js")&&(a=Ma(r)),a&&(a.enabled=!t.includes(a.name),lt.push(a))}let n=mt.join(__dirname,"skills");if(!process.env.NEX_SKIP_BUILTIN_SKILLS&&Ae.existsSync(n)){let o;try{o=Ae.readdirSync(n).filter(r=>r.endsWith(".md")||r.endsWith(".js"))}catch{o=[]}for(let r of o){let i=mt.join(n,r),a=mt.basename(r,mt.extname(r));if(lt.some(u=>u.name===a))continue;let l;try{l=Ae.statSync(i)}catch{continue}if(!l.isFile())continue;let c=r.endsWith(".md")?Na(i):Ma(i);c&&(c._builtin=!0,c.enabled=!t.includes(c.name),lt.push(c))}}return lt}function i_(){let t=[];for(let e of lt)!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 i_(){let t=[];for(let e of rt)if(e.enabled)for(let s of e.commands)t.push({cmd:s.cmd,desc:s.desc||`[skill: ${e.name}]`});return t}function a_(){let t=[];for(let e of rt)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 l_(t,e){if(!t.startsWith("skill_"))return null;let s=t.substring(6);for(let n of rt)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 c_(t){let[e,...s]=t.split(/\s+/),n=s.join(" ").trim();for(let o of rt)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 u_(){return rt.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 d_(t){let e=rt.find(n=>n.name===t);if(!e)return!1;e.enabled=!0;let s=Na().filter(n=>n!==t);return Ed(s),!0}function f_(t){let e=rt.find(n=>n.name===t);if(!e)return!1;e.enabled=!1;let s=Na();return s.includes(t)||(s.push(t),Ed(s)),!0}function p_(){return rt}async function h_(t,e={}){let{execFileSync:s}=require("child_process"),n=vd(),o=t;/^[\w-]+\/[\w.-]+$/.test(t)&&(o=`https://github.com/${t}.git`);let r=e.name||dt.basename(o,".git").replace(/^nex-skill-/,""),i=dt.join(n,r);if(Ce.existsSync(i))return{ok:!1,name:r,error:`Skill "${r}" is already installed at ${i}. Remove it first to reinstall.`};try{if(!/^https?:\/\/[a-zA-Z0-9._\-/:.@]+$/.test(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=dt.join(i,"skill.json"),l=Ce.existsSync(a),c=Ce.readdirSync(i).some(u=>(u.endsWith(".md")||u.endsWith(".js"))&&!u.startsWith("."));if(!l&&!c){try{Ce.rmSync(i,{recursive:!0,force:!0})}catch{}return{ok:!1,name:r,error:"No skill.json manifest or .md/.js skill file found in repository"}}if(l)try{let u=JSON.parse(Ce.readFileSync(a,"utf-8"));u.name||(u.name=r)}catch{try{Ce.rmSync(i,{recursive:!0,force:!0})}catch{}return{ok:!1,name:r,error:"Invalid skill.json \u2014 not valid JSON"}}return Ma(),{ok:!0,name:r}}async function m_(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 g_(t){let e=dt.join(no(),t);if(!Ce.existsSync(e))return{ok:!1,error:`Skill "${t}" not found in ${no()}`};try{return Ce.rmSync(e,{recursive:!0,force:!0}),Ma(),{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 rt){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 a_(){let t=[];for(let e of lt)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 lt)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 c_(t,e){if(!t.startsWith("skill_"))return null;let s=t.substring(6);for(let n of lt)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 u_(t){let[e,...s]=t.split(/\s+/),n=s.join(" ").trim();for(let o of lt)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 d_(){return lt.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 f_(t){let e=lt.find(n=>n.name===t);if(!e)return!1;e.enabled=!0;let s=Pa().filter(n=>n!==t);return Td(s),!0}function p_(t){let e=lt.find(n=>n.name===t);if(!e)return!1;e.enabled=!1;let s=Pa();return s.includes(t)||(s.push(t),Td(s)),!0}function h_(){return lt}async function m_(t,e={}){let{execFileSync:s}=require("child_process"),n=Ed(),o=t;/^[\w-]+\/[\w.-]+$/.test(t)&&(o=`https://github.com/${t}.git`);let r=e.name||mt.basename(o,".git").replace(/^nex-skill-/,""),i=mt.join(n,r);if(Ae.existsSync(i))return{ok:!1,name:r,error:`Skill "${r}" is already installed at ${i}. Remove it first to reinstall.`};try{if(!/^https?:\/\/[a-zA-Z0-9._\-/:.@]+$/.test(o))throw new Error(`Invalid git URL: ${o}`);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=mt.join(i,"skill.json"),l=Ae.existsSync(a),c=Ae.readdirSync(i).some(u=>(u.endsWith(".md")||u.endsWith(".js"))&&!u.startsWith("."));if(!l&&!c){try{Ae.rmSync(i,{recursive:!0,force:!0})}catch{}return{ok:!1,name:r,error:"No skill.json manifest or .md/.js skill file found in repository"}}if(l)try{let u=JSON.parse(Ae.readFileSync(a,"utf-8"));u.name||(u.name=r)}catch{try{Ae.rmSync(i,{recursive:!0,force:!0})}catch{}return{ok:!1,name:r,error:"Invalid skill.json \u2014 not valid JSON"}}return La(),{ok:!0,name:r}}async function g_(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 y_(t){let e=mt.join(no(),t);if(!Ae.existsSync(e))return{ok:!1,error:`Skill "${t}" not found in ${no()}`};try{return Ae.rmSync(e,{recursive:!0,force:!0}),La(),{ok:!0}}catch(s){return{ok:!1,error:s.message}}}function w_(t){if(!t)return[];let e=t.toLowerCase(),s=[];for(let n of lt){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}Cd.exports={initSkillsDir:vd,loadAllSkills:Ma,getSkillInstructions:r_,getSkillCommands:i_,getSkillToolDefinitions:a_,routeSkillCall:l_,handleSkillCommand:c_,listSkills:u_,enableSkill:d_,disableSkill:f_,getLoadedSkills:p_,installSkill:h_,searchSkills:m_,removeSkill:g_,matchSkillTriggers:y_,_getSkillsDir:no,_validateScriptSkill:Td,_loadMarkdownSkill:Aa,_loadScriptSkill:Oa,_parseFrontmatter:Rd}});var Ia=z((GT,Ld)=>{var{spawn:w_}=require("child_process"),__=require("path"),Ad=require("fs"),on=new Map;function $_(){return __.join(process.cwd(),".nex","config.json")}function La(){let t=$_();if(!Ad.existsSync(t))return{};try{return JSON.parse(Ad.readFileSync(t,"utf-8")).mcpServers||{}}catch{return{}}}function Nr(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}Ad.exports={initSkillsDir:Ed,loadAllSkills:La,getSkillInstructions:i_,getSkillCommands:a_,getSkillToolDefinitions:l_,routeSkillCall:c_,handleSkillCommand:u_,listSkills:d_,enableSkill:f_,disableSkill:p_,getLoadedSkills:h_,installSkill:m_,searchSkills:g_,removeSkill:y_,matchSkillTriggers:w_,_getSkillsDir:no,_validateScriptSkill:Rd,_loadMarkdownSkill:Na,_loadScriptSkill:Ma,_parseFrontmatter:Cd}});var ja=z((zT,Id)=>{var{spawn:__}=require("child_process"),$_=require("path"),Od=require("fs"),rn=new Map;function b_(){return $_.join(process.cwd(),".nex","config.json")}function Da(){let t=b_();if(!Od.existsSync(t))return{};try{return JSON.parse(Od.readFileSync(t,"utf-8")).mcpServers||{}}catch{return{}}}function Mr(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 Od(t,e){if(on.has(t))return on.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=w_(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:{...n,...e.env||{}}}),r={name:t,proc:o,tools:[],config:e};try{await Nr(o,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.2.0"}});let i=await Nr(o,"tools/list",{});return r.tools=i&&i.tools||[],on.set(t,r),r}catch(i){throw o.kill(),new Error(`Failed to connect MCP server '${t}': ${i.message}`)}}function Nd(t){let e=on.get(t);if(!e)return!1;try{e.proc.kill()}catch{}return on.delete(t),!0}function b_(){for(let[t]of on)Nd(t)}async function Md(t,e,s={}){let n=on.get(t);if(!n)throw new Error(`MCP server not connected: ${t}`);let o=await Nr(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 Pd(){let t=[];for(let[e,s]of on)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 x_(){return Pd().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function k_(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 Md(n,o,e)}function S_(){let t=La();return Object.entries(t).map(([e,s])=>{let n=on.get(e);return{name:e,command:s.command,connected:!!n,toolCount:n?n.tools.length:0}})}async function v_(){let t=La(),e=[];for(let[s,n]of Object.entries(t))try{let o=await Od(s,n);e.push({name:s,tools:o.tools.length})}catch(o){e.push({name:s,tools:0,error:o.message})}return e}Ld.exports={loadMCPConfig:La,sendRequest:Nr,connectServer:Od,disconnectServer:Nd,disconnectAll:b_,callTool:Md,getAllTools:Pd,getMCPToolDefinitions:x_,routeMCPCall:k_,listServers:S_,connectAll:v_}});var Pr=z((zT,qd)=>{var Id=require("fs"),Da=require("path"),Mr=[],so=[],In={},oo=["onToolResult","onModelResponse","onSessionStart","onSessionEnd","onFileChange","beforeToolExec","afterToolExec"];function Dd(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 so.some(n=>n.definition.function.name===s)?{ok:!1,error:`Tool "${s}" is already registered`}:(so.push({definition:{type:"function",...t},handler:e}),{ok:!0})}function jd(t,e){return oo.includes(t)?typeof e!="function"?{ok:!1,error:"Handler must be a function"}:(In[t]||(In[t]=[]),In[t].push(e),{ok:!0}):{ok:!1,error:`Unknown event "${t}". Available: ${oo.join(", ")}`}}async function ja(t,e){let s=In[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=Da.join(process.cwd(),".nex","plugins"),e=[];if(!Id.existsSync(t))return{loaded:0,errors:[]};let s=Id.readdirSync(t).filter(o=>o.endsWith(".js")),n={registerTool:Dd,registerHook:jd,EVENTS:oo};for(let o of s){let r=Da.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}Mr.push({name:i.name||Da.basename(o,".js"),filePath:r})}catch(i){e.push(`${o}: ${i.message}`)}}return{loaded:Mr.length,errors:e}}function T_(){return so.map(t=>t.definition)}async function R_(t,e,s={}){let n=so.find(a=>a.definition.function.name===t);if(!n)return null;let o=await ja("beforeToolExec",{name:t,args:e,options:s}),r=await n.handler(o.args||e,s);return(await ja("afterToolExec",{name:t,args:e,result:r})).result||r}function C_(){return[...Mr]}function A_(){let t={};for(let e of oo)t[e]=(In[e]||[]).length;return t}function O_(){Mr.length=0,so.length=0;for(let t of Object.keys(In))delete In[t]}qd.exports={registerTool:Dd,registerHook:jd,emit:ja,loadPlugins:E_,getPluginToolDefinitions:T_,executePluginTool:R_,getLoadedPlugins:C_,getHookCounts:A_,clearPlugins:O_,EVENTS:oo}});var qa=z((KT,Wd)=>{var{getSkillToolDefinitions:N_}=Pa(),{getMCPToolDefinitions:M_}=Ia(),{getPluginToolDefinitions:P_}=Pr(),Lr=new Map;function Fd(){let{TOOL_DEFINITIONS:t}=ks();return[...t,...N_(),...M_(),...P_()]}function Bd(t){if(Lr.has(t))return Lr.get(t);let s=Fd().find(o=>o.function.name===t);if(!s)return null;let n=s.function.parameters;return Lr.set(t,n),n}function L_(){Lr.clear()}function Ir(t,e){if(!t||e.length===0)return null;let s=null,n=1/0;for(let o of e){let r=Ud(t.toLowerCase(),o.toLowerCase());r<n&&(n=r,s=o)}return n<=Math.ceil(t.length/2)?s:null}function Ud(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 I_(t,e){let s=Bd(t);if(s===null){let d=Fd().map(p=>p.function.name),f=Ir(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=Ir(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=Ir(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 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 Nd(t,e){if(rn.has(t))return rn.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=__(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:{...n,...e.env||{}}}),r={name:t,proc:o,tools:[],config:e};try{await Mr(o,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.2.0"}});let i=await Mr(o,"tools/list",{});return r.tools=i&&i.tools||[],rn.set(t,r),r}catch(i){throw o.kill(),new Error(`Failed to connect MCP server '${t}': ${i.message}`)}}function Md(t){let e=rn.get(t);if(!e)return!1;try{e.proc.kill()}catch{}return rn.delete(t),!0}function x_(){for(let[t]of rn)Md(t)}async function Pd(t,e,s={}){let n=rn.get(t);if(!n)throw new Error(`MCP server not connected: ${t}`);let o=await Mr(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 Ld(){let t=[];for(let[e,s]of rn)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 k_(){return Ld().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function S_(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 Pd(n,o,e)}function v_(){let t=Da();return Object.entries(t).map(([e,s])=>{let n=rn.get(e);return{name:e,command:s.command,connected:!!n,toolCount:n?n.tools.length:0}})}async function E_(){let t=Da(),e=[];for(let[s,n]of Object.entries(t))try{let o=await Nd(s,n);e.push({name:s,tools:o.tools.length})}catch(o){e.push({name:s,tools:0,error:o.message})}return e}Id.exports={loadMCPConfig:Da,sendRequest:Mr,connectServer:Nd,disconnectServer:Md,disconnectAll:x_,callTool:Pd,getAllTools:Ld,getMCPToolDefinitions:k_,routeMCPCall:S_,listServers:v_,connectAll:E_}});var Lr=z((KT,Fd)=>{var Dd=require("fs"),qa=require("path"),Pr=[],so=[],jn={},oo=["onToolResult","onModelResponse","onSessionStart","onSessionEnd","onFileChange","beforeToolExec","afterToolExec"];function jd(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 so.some(n=>n.definition.function.name===s)?{ok:!1,error:`Tool "${s}" is already registered`}:(so.push({definition:{type:"function",...t},handler:e}),{ok:!0})}function qd(t,e){return oo.includes(t)?typeof e!="function"?{ok:!1,error:"Handler must be a function"}:(jn[t]||(jn[t]=[]),jn[t].push(e),{ok:!0}):{ok:!1,error:`Unknown event "${t}". Available: ${oo.join(", ")}`}}async function Fa(t,e){let s=jn[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 T_(){let t=qa.join(process.cwd(),".nex","plugins"),e=[];if(!Dd.existsSync(t))return{loaded:0,errors:[]};let s=Dd.readdirSync(t).filter(o=>o.endsWith(".js")),n={registerTool:jd,registerHook:qd,EVENTS:oo};for(let o of s){let r=qa.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}Pr.push({name:i.name||qa.basename(o,".js"),filePath:r})}catch(i){e.push(`${o}: ${i.message}`)}}return{loaded:Pr.length,errors:e}}function R_(){return so.map(t=>t.definition)}async function C_(t,e,s={}){let n=so.find(a=>a.definition.function.name===t);if(!n)return null;let o=await Fa("beforeToolExec",{name:t,args:e,options:s}),r=await n.handler(o.args||e,s);return(await Fa("afterToolExec",{name:t,args:e,result:r})).result||r}function A_(){return[...Pr]}function O_(){let t={};for(let e of oo)t[e]=(jn[e]||[]).length;return t}function N_(){Pr.length=0,so.length=0;for(let t of Object.keys(jn))delete jn[t]}Fd.exports={registerTool:jd,registerHook:qd,emit:Fa,loadPlugins:T_,getPluginToolDefinitions:R_,executePluginTool:C_,getLoadedPlugins:A_,getHookCounts:O_,clearPlugins:N_,EVENTS:oo}});var Ba=z((XT,Hd)=>{var{getSkillToolDefinitions:M_}=Ia(),{getMCPToolDefinitions:P_}=ja(),{getPluginToolDefinitions:L_}=Lr(),Ir=new Map;function Bd(){let{TOOL_DEFINITIONS:t}=ks();return[...t,...M_(),...P_(),...L_()]}function Ud(t){if(Ir.has(t))return Ir.get(t);let s=Bd().find(o=>o.function.name===t);if(!s)return null;let n=s.function.parameters;return Ir.set(t,n),n}function I_(){Ir.clear()}function Dr(t,e){if(!t||e.length===0)return null;let s=null,n=1/0;for(let o of e){let r=Wd(t.toLowerCase(),o.toLowerCase());r<n&&(n=r,s=o)}return n<=Math.ceil(t.length/2)?s:null}function Wd(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 D_(t,e){let s=Ud(t);if(s===null){let d=Bd().map(p=>p.function.name),f=Dr(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=Dr(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=Dr(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 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}}Wd.exports={validateToolArgs:I_,validateToolCallFormat:D_,closestMatch:Ir,levenshtein:Ud,getCachedSchema:Bd,clearSchemaCache:L_}});var zd=z((XT,Gd)=>{var{levenshtein:Dr}=qa(),j_=200,q_=.3,F_=2;function Fa(t){return t.replace(/\r\n/g,`
104
+ Expected parameters: ${JSON.stringify(s.properties,null,2)}`}:{valid:!0,corrected:l?a:null}}function j_(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}}Hd.exports={validateToolArgs:D_,validateToolCallFormat:j_,closestMatch:Dr,levenshtein:Wd,getCachedSchema:Ud,clearSchemaCache:I_}});var Kd=z((VT,zd)=>{var{levenshtein:jr}=Ba(),q_=200,F_=.3,B_=2;function Ua(t){return t.replace(/\r\n/g,`
105
105
  `).replace(/\r/g,`
106
- `).replace(/\t/g," ".repeat(F_)).split(`
106
+ `).replace(/\t/g," ".repeat(B_)).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 B_(t,e){if(t.includes(e))return e;if(e.length<10)return null;let s=Fa(t),n=Fa(e);if(!s.includes(n))return null;let o=t.split(`
108
+ `)}function U_(t,e){if(t.includes(e))return e;if(e.length<10)return null;let s=Ua(t),n=Ua(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 U_(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 W_(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?W_(s,e):Y_(s,e,o)}function Hd(t){return Math.max(1,Math.floor(t/j_))}function Yd(t,e){return t<=Math.ceil(e*q_)}function W_(t,e){let s=e.trim(),n=Hd(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=Dr(a.trim(),s);l<r&&(r=l,o={text:a,distance:l,line:i+1})}return o&&n>1&&(o=H_(t,s,o,n)||o,r=o.distance),Yd(r,e.length)?o:null}function H_(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=Dr(u.trim(),e);d<a&&(a=d,l={text:u,distance:d,line:c+1})}return l}function Y_(t,e,s){let n=t.length-s+1;if(n<=0)return null;let o=Hd(n),r=null,i=1/0;for(let a=0;a<n;a+=o){let l=t.slice(a,a+s).join(`
115
- `),c=Dr(l,e);c<i&&(i=c,r={text:l,distance:c,line:a+1})}return r&&o>1&&(r=G_(t,e,r,o,s,n)||r,i=r.distance),Yd(i,e.length)?r:null}function G_(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=Dr(f,e);p<c&&(c=p,u={text:f,distance:p,line:d+1})}return u}Gd.exports={normalizeWhitespace:Fa,fuzzyFindText:B_,findMostSimilar:U_}});var Xd=z((JT,Kd)=>{var{C:VT}=ze(),z_=[{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}],K_=[{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 X_(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 z_)l.regex.test(i)&&n.push({line:a,message:`Potential secret detected: ${l.name}`,severity:"error"});for(let l of K_)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 V_(){let t=process.memoryUsage();return{rss:Math.round(t.rss/1024/1024*100)/100,heapUsed:Math.round(t.heapUsed/1024/1024*100)/100}}Kd.exports={runDiagnostics:X_,getMemoryUsage:V_}});var Ya=z((ZT,tf)=>{var Ss=require("fs").promises,vs=require("path"),{exec:J_}=require("util").promisify(require("child_process").exec),Es=[],Ha=null,jr=!1,Ua=0,Z_=6e4;function Jd(t){return!(Es.length===0||Ha!==t||Date.now()-Ua>Z_)}async function Zd(t){if(!jr&&!Jd(t)){jr=!0,Ha=t;try{try{let{stdout:n}=await J_("rg --files",{cwd:t,timeout:5e3});Es=n.split(`
118
- `).filter(Boolean),Ua=Date.now(),jr=!1;return}catch{}let e=[],s=async(n,o)=>{let r;try{r=await Ss.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(vs.join(n,i.name),a):e.push(a)}};await s(t,""),Es=e,Ua=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{jr=!1}}}function Wa(){return Es}function Q_(){return Ha}function e$(t){return Es.filter(e=>vs.basename(e)===t)}function t$(t){let e=t.toLowerCase();return Es.filter(s=>s.toLowerCase().includes(e)).slice(0,20)}var Ba=null,Vd=0,n$=12e4,s$=new Set([".js",".ts",".jsx",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".rb"]);function Qd(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 ef(t){t=t||process.cwd();let e=vs.join(t,".nex","index","content-index.json"),s={};if(Ba&&Date.now()-Vd<n$)return Ba;try{let i=await Ss.readFile(e,"utf-8");s=JSON.parse(i)}catch{s={files:{}}}Wa().length===0&&await Zd(t);let o={files:{}},r=!1;for(let i of Wa()){let a=vs.extname(i);if(!s$.has(a))continue;let l=vs.join(t,i);try{let u=(await Ss.stat(l)).mtimeMs;if(s.files[i]&&s.files[i].mtime===u){o.files[i]=s.files[i];continue}let d=await Ss.readFile(l,"utf-8"),f=Qd(d,a);o.files[i]={defs:f,mtime:u},r=!0}catch{}}if(r){let i=vs.join(t,".nex","index");await Ss.mkdir(i,{recursive:!0}),await Ss.writeFile(e,JSON.stringify(o),"utf-8")}return Ba=o,Vd=Date.now(),o}async function o$(t,e){let s=await ef(),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)}tf.exports={refreshIndex:Zd,getFileIndex:Wa,getIndexedCwd:Q_,findFileInIndex:e$,searchIndex:t$,isIndexValid:Jd,buildContentIndex:ef,searchContentIndex:o$,extractDefinitions:Qd}});var za=z((QT,rf)=>{var qr=require("fs"),Br=require("path"),Ur=require("os"),{execFile:r$}=require("child_process"),{promisify:i$}=require("util"),Ga=i$(r$),a$=Br.join(Ur.homedir(),".nex","servers.json"),Fr=Br.join(Ur.tmpdir(),"nex-ssh-sockets");function l$(){return Br.join(process.cwd(),".nex","servers.json")}function nf(){let t=n=>{if(!qr.existsSync(n))return{};try{return JSON.parse(qr.readFileSync(n,"utf-8"))}catch{return{}}},e=t(a$),s=t(l$());return{...e,...s}}function c$(t){let e=nf();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 u$(){qr.existsSync(Fr)||qr.mkdirSync(Fr,{recursive:!0})}function sf(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-o","ServerAliveInterval=30"];t.key&&e.push("-i",t.key.replace(/^~/,Ur.homedir())),t.port&&Number(t.port)!==22&&e.push("-p",String(t.port)),u$();let s=t.user?`${t.user}@${t.host}`:t.host,n=Br.join(Fr,s.replace(/[@.:]/g,"_"));return e.push("-o","ControlMaster=auto","-o",`ControlPath=${n}`,"-o","ControlPersist=120"),e.push(s),{args:e,target:s}}function of(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-r"];return t.key&&e.push("-i",t.key.replace(/^~/,Ur.homedir())),t.port&&Number(t.port)!==22&&e.push("-P",String(t.port)),e}async function d$(t,e,{timeout:s=3e4,sudo:n=!1}={}){let{args:o}=sf(t),r=n&&t.sudo?`sudo sh -c ${JSON.stringify(e)}`:e;try{let{stdout:i,stderr:a}=await Ga("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:Wr(l,t)}}}async function f$(t,e,s,{timeout:n=12e4}={}){let o=of(t),r=t.user?`${t.user}@${t.host}`:t.host;o.push(e,`${r}:${s}`);try{let{stdout:i,stderr:a}=await Ga("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(Wr(a,t)||a)}}async function p$(t,e,s,{timeout:n=12e4}={}){let o=of(t),r=t.user?`${t.user}@${t.host}`:t.host;o.push(`${r}:${e}`,s);try{let{stdout:i,stderr:a}=await Ga("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(Wr(a,t)||a)}}function Wr(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?H_(s,e):G_(s,e,o)}function Yd(t){return Math.max(1,Math.floor(t/q_))}function Gd(t,e){return t<=Math.ceil(e*F_)}function H_(t,e){let s=e.trim(),n=Yd(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=jr(a.trim(),s);l<r&&(r=l,o={text:a,distance:l,line:i+1})}return o&&n>1&&(o=Y_(t,s,o,n)||o,r=o.distance),Gd(r,e.length)?o:null}function Y_(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=jr(u.trim(),e);d<a&&(a=d,l={text:u,distance:d,line:c+1})}return l}function G_(t,e,s){let n=t.length-s+1;if(n<=0)return null;let o=Yd(n),r=null,i=1/0;for(let a=0;a<n;a+=o){let l=t.slice(a,a+s).join(`
115
+ `),c=jr(l,e);c<i&&(i=c,r={text:l,distance:c,line:a+1})}return r&&o>1&&(r=z_(t,e,r,o,s,n)||r,i=r.distance),Gd(i,e.length)?r:null}function z_(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=jr(f,e);p<c&&(c=p,u={text:f,distance:p,line:d+1})}return u}zd.exports={normalizeWhitespace:Ua,fuzzyFindText:U_,findMostSimilar:W_}});var Vd=z((ZT,Xd)=>{var{C:JT}=Ke(),K_=[{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 V_(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 K_)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 J_(){let t=process.memoryUsage();return{rss:Math.round(t.rss/1024/1024*100)/100,heapUsed:Math.round(t.heapUsed/1024/1024*100)/100}}Xd.exports={runDiagnostics:V_,getMemoryUsage:J_}});var za=z((QT,nf)=>{var Ss=require("fs").promises,vs=require("path"),{exec:Z_}=require("util").promisify(require("child_process").exec),Es=[],Ga=null,qr=!1,Ha=0,Q_=6e4;function Zd(t){return!(Es.length===0||Ga!==t||Date.now()-Ha>Q_)}async function Qd(t){if(!qr&&!Zd(t)){qr=!0,Ga=t;try{try{let{stdout:n}=await Z_("rg --files",{cwd:t,timeout:5e3});Es=n.split(`
118
+ `).filter(Boolean),Ha=Date.now(),qr=!1;return}catch{}let e=[],s=async(n,o)=>{let r;try{r=await Ss.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(vs.join(n,i.name),a):e.push(a)}};await s(t,""),Es=e,Ha=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{qr=!1}}}function Ya(){return Es}function e$(){return Ga}function t$(t){return Es.filter(e=>vs.basename(e)===t)}function n$(t){let e=t.toLowerCase();return Es.filter(s=>s.toLowerCase().includes(e)).slice(0,20)}var Wa=null,Jd=0,s$=12e4,o$=new Set([".js",".ts",".jsx",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".rb"]);function ef(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 tf(t){t=t||process.cwd();let e=vs.join(t,".nex","index","content-index.json"),s={};if(Wa&&Date.now()-Jd<s$)return Wa;try{let i=await Ss.readFile(e,"utf-8");s=JSON.parse(i)}catch{s={files:{}}}Ya().length===0&&await Qd(t);let o={files:{}},r=!1;for(let i of Ya()){let a=vs.extname(i);if(!o$.has(a))continue;let l=vs.join(t,i);try{let u=(await Ss.stat(l)).mtimeMs;if(s.files[i]&&s.files[i].mtime===u){o.files[i]=s.files[i];continue}let d=await Ss.readFile(l,"utf-8"),f=ef(d,a);o.files[i]={defs:f,mtime:u},r=!0}catch{}}if(r){let i=vs.join(t,".nex","index");await Ss.mkdir(i,{recursive:!0}),await Ss.writeFile(e,JSON.stringify(o),"utf-8")}return Wa=o,Jd=Date.now(),o}async function r$(t,e){let s=await tf(),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)}nf.exports={refreshIndex:Qd,getFileIndex:Ya,getIndexedCwd:e$,findFileInIndex:t$,searchIndex:n$,isIndexValid:Zd,buildContentIndex:tf,searchContentIndex:r$,extractDefinitions:ef}});var Xa=z((eR,af)=>{var Fr=require("fs"),Ur=require("path"),Wr=require("os"),{execFile:i$}=require("child_process"),{promisify:a$}=require("util"),Ka=a$(i$),l$=Ur.join(Wr.homedir(),".nex","servers.json"),Br=Ur.join(Wr.tmpdir(),"nex-ssh-sockets");function c$(){return Ur.join(process.cwd(),".nex","servers.json")}function sf(){let t=n=>{if(!Fr.existsSync(n))return{};try{return JSON.parse(Fr.readFileSync(n,"utf-8"))}catch{return{}}},e=t(l$),s=t(c$());return{...e,...s}}function u$(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 d$(){Fr.existsSync(Br)||Fr.mkdirSync(Br,{recursive:!0})}function of(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-o","ServerAliveInterval=30"];t.key&&e.push("-i",t.key.replace(/^~/,Wr.homedir())),t.port&&Number(t.port)!==22&&e.push("-p",String(t.port)),d$();let s=t.user?`${t.user}@${t.host}`:t.host,n=Ur.join(Br,s.replace(/[@.:]/g,"_"));return e.push("-o","ControlMaster=auto","-o",`ControlPath=${n}`,"-o","ControlPersist=120"),e.push(s),{args:e,target:s}}function rf(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-r"];return t.key&&e.push("-i",t.key.replace(/^~/,Wr.homedir())),t.port&&Number(t.port)!==22&&e.push("-P",String(t.port)),e}async function f$(t,e,{timeout:s=3e4,sudo:n=!1}={}){let{args:o}=of(t),r=n&&t.sudo?`sudo sh -c ${JSON.stringify(e)}`:e;try{let{stdout:i,stderr:a}=await Ka("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:Hr(l,t)}}}async function p$(t,e,s,{timeout:n=12e4}={}){let o=rf(t),r=t.user?`${t.user}@${t.host}`:t.host;o.push(e,`${r}:${s}`);try{let{stdout:i,stderr:a}=await Ka("scp",o,{timeout:n,maxBuffer:1048576});return i||a||`Uploaded ${e} \u2192 ${r}:${s}`}catch(i){let a=(i.stderr||i.message||"").toString();throw new Error(Hr(a,t)||a)}}async function h$(t,e,s,{timeout:n=12e4}={}){let o=rf(t),r=t.user?`${t.user}@${t.host}`:t.host;o.push(`${r}:${e}`,s);try{let{stdout:i,stderr:a}=await Ka("scp",o,{timeout:n,maxBuffer:1048576});return i||a||`Downloaded ${r}:${e} \u2192 ${s}`}catch(i){let a=(i.stderr||i.message||"").toString();throw new Error(Hr(a,t)||a)}}function Hr(t,e){if(!t)return"";if(/connection refused/i.test(t)){let s=e.port||22;return`${t}
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 h$(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}`}rf.exports={loadServerProfiles:nf,resolveProfile:c$,buildSSHArgs:sf,sshExec:d$,scpUpload:f$,scpDownload:p$,enrichSSHError:Wr,formatProfile:h$,SSH_SOCKET_DIR:Fr}});var cf=z((eR,lf)=>{var ro=require("fs"),Ka=require("path"),m$=Ka.join(".nex","deploy.json");function Xa(){return Ka.join(process.cwd(),m$)}function af(){let t=Xa();if(!ro.existsSync(t))return{};try{return JSON.parse(ro.readFileSync(t,"utf-8"))}catch{return{}}}function g$(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 y$(t){let e=Ka.join(process.cwd(),".nex");ro.existsSync(e)||ro.mkdirSync(e,{recursive:!0}),ro.writeFileSync(Xa(),JSON.stringify(t,null,2)+`
126
- `,"utf-8")}lf.exports={loadDeployConfigs:af,resolveDeployConfig:g$,saveDeployConfigs:y$,getDeployConfigPath:Xa}});var co=z((tR,ff)=>{var{getActiveModel:w$,getActiveProviderName:_$}=Ve(),io={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},ao={"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"},lo={ollama:"full",openai:"full",anthropic:"full",gemini:"full",local:"essential"},Yt={};function df(){try{let t=require("fs"),s=require("path").join(process.cwd(),".nex","config.json");t.existsSync(s)&&(Yt=JSON.parse(t.readFileSync(s,"utf-8")).toolTiers||{})}catch{Yt={}}}df();function Va(){let e=w$()?.id,s=_$();return e&&Yt[e]?Yt[e]:s&&Yt[`${s}:*`]?Yt[`${s}:*`]:e&&ao[e]?ao[e]:s&&lo[s]?lo[s]:"full"}var $$=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"]),uf={anthropic:"strict",openai:"strict",gemini:"strict",ollama:"fuzzy",local:"fuzzy"};function b$(t,e){return t&&($$.has(t)||t.startsWith("claude-"))?"strict":e&&uf[e]?uf[e]:"fuzzy"}function x$(t,e){return t&&Yt[t]?Yt[t]:e&&Yt[`${e}:*`]?Yt[`${e}:*`]:t&&ao[t]?ao[t]:e&&lo[e]?lo[e]:"full"}function k$(t,e){let s=e||Va();if(s==="full"||!io[s])return t;let n=new Set(io[s]);return t.filter(o=>n.has(o.function.name))}function S$(){let t=Va(),e=io[t]?io[t].length:"all";return{tier:t,toolCount:e}}ff.exports={filterToolsForModel:k$,getActiveTier:Va,getModelTier:x$,getEditMode:b$,getTierInfo:S$,TIERS:io,MODEL_TIERS:ao,PROVIDER_DEFAULT_TIER:lo,loadConfigOverrides:df}});var an=z((nR,mf)=>{var Ja=null,rn=null,uo=null,pf=`Playwright is not installed. Install with:
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}`}af.exports={loadServerProfiles:sf,resolveProfile:u$,buildSSHArgs:of,sshExec:f$,scpUpload:p$,scpDownload:h$,enrichSSHError:Hr,formatProfile:m$,SSH_SOCKET_DIR:Br}});var uf=z((tR,cf)=>{var ro=require("fs"),Va=require("path"),g$=Va.join(".nex","deploy.json");function Ja(){return Va.join(process.cwd(),g$)}function lf(){let t=Ja();if(!ro.existsSync(t))return{};try{return JSON.parse(ro.readFileSync(t,"utf-8"))}catch{return{}}}function y$(t){let e=lf();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 w$(t){let e=Va.join(process.cwd(),".nex");ro.existsSync(e)||ro.mkdirSync(e,{recursive:!0}),ro.writeFileSync(Ja(),JSON.stringify(t,null,2)+`
126
+ `,"utf-8")}cf.exports={loadDeployConfigs:lf,resolveDeployConfig:y$,saveDeployConfigs:w$,getDeployConfigPath:Ja}});var co=z((nR,pf)=>{var{getActiveModel:_$,getActiveProviderName:$$}=Ze(),io={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},ao={"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"},lo={ollama:"full",openai:"full",anthropic:"full",gemini:"full",local:"essential"},Kt={};function ff(){try{let t=require("fs"),s=require("path").join(process.cwd(),".nex","config.json");t.existsSync(s)&&(Kt=JSON.parse(t.readFileSync(s,"utf-8")).toolTiers||{})}catch{Kt={}}}ff();function Za(){let e=_$()?.id,s=$$();return e&&Kt[e]?Kt[e]:s&&Kt[`${s}:*`]?Kt[`${s}:*`]:e&&ao[e]?ao[e]:s&&lo[s]?lo[s]:"full"}var b$=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"]),df={anthropic:"strict",openai:"strict",gemini:"strict",ollama:"fuzzy",local:"fuzzy"};function x$(t,e){return t&&(b$.has(t)||t.startsWith("claude-"))?"strict":e&&df[e]?df[e]:"fuzzy"}function k$(t,e){return t&&Kt[t]?Kt[t]:e&&Kt[`${e}:*`]?Kt[`${e}:*`]:t&&ao[t]?ao[t]:e&&lo[e]?lo[e]:"full"}function S$(t,e){let s=e||Za();if(s==="full"||!io[s])return t;let n=new Set(io[s]);return t.filter(o=>n.has(o.function.name))}function v$(){let t=Za(),e=io[t]?io[t].length:"all";return{tier:t,toolCount:e}}pf.exports={filterToolsForModel:S$,getActiveTier:Za,getModelTier:k$,getEditMode:x$,getTierInfo:v$,TIERS:io,MODEL_TIERS:ao,PROVIDER_DEFAULT_TIER:lo,loadConfigOverrides:ff}});var ln=z((sR,gf)=>{var Qa=null,an=null,uo=null,hf=`Playwright is not installed. Install with:
127
127
  npm install playwright && npx playwright install chromium
128
- Then restart nex-code.`;function hf(){if(uo!==null)return uo;try{require("playwright"),uo=!0}catch{uo=!1}return uo}async function Hr(){if(!hf())throw new Error(pf);return Ja||(Ja=require("playwright")),(!rn||!rn.isConnected())&&(rn=await Ja.chromium.launch({headless:!0})),rn}async function v$(){if(rn){try{await rn.close()}catch{}rn=null}}process.on("exit",()=>{if(rn)try{rn.close()}catch{}});async function E$(t,{timeout:e=3e4,waitFor:s="domcontentloaded"}={}){let o=await(await Hr()).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?`
129
- ...(truncated)`:""),links:a.slice(0,20)}}finally{await o.close()}}async function T$(t,{width:e=1280,height:s=800,fullPage:n=!1,timeout:o=3e4}={}){let i=await(await Hr()).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 R$(t,{selector:e,text:s,timeout:n=3e4}={}){if(!e&&!s)throw new Error("selector or text is required");let r=await(await Hr()).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 C$(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 Hr()).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()}}mf.exports={isPlaywrightAvailable:hf,browserNavigate:E$,browserScreenshot:T$,browserClick:R$,browserFill:C$,closeBrowser:v$,INSTALL_MSG:pf}});var Za=z((sR,yf)=>{"use strict";var A$=require("util"),gf=require("stream"),Mt=yf.exports=function(){gf.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};A$.inherits(Mt,gf);Mt.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))};Mt.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};Mt.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()))};Mt.prototype.destroySoon=Mt.prototype.end;Mt.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};Mt.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};Mt.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))};Mt.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)};Mt.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 el=z(Qa=>{"use strict";var yn=[{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]}];Qa.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<yn.length;a++){let l=yn[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};Qa.getInterlaceIterator=function(t){return function(e,s,n){let o=e%yn[n].x.length,r=(e-o)/yn[n].x.length*8+yn[n].x[o],i=s%yn[n].y.length,a=(s-i)/yn[n].y.length*8+yn[n].y[i];return r*4+a*t*4}}});var tl=z((rR,wf)=>{"use strict";wf.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 nl=z((iR,$f)=>{"use strict";var O$=el(),N$=tl();function _f(t,e,s){let n=t*e;return s!==8&&(n=Math.ceil(n/(8/s))),n}var Ts=$f.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=O$.getImagePasses(s,n);for(let l=0;l<a.length;l++)this._images.push({byteWidth:_f(a[l].width,r,i),height:a[l].height,lineIndex:0})}else this._images.push({byteWidth:_f(s,r,i),height:n,lineIndex:0});i===8?this._xComparison=r:i===16?this._xComparison=r*2:this._xComparison=1};Ts.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};Ts.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}};Ts.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}};Ts.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}};Ts.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=N$(c,l,u);e[i]=a+d}};Ts.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 kf=z((aR,xf)=>{"use strict";var M$=require("util"),bf=Za(),P$=nl(),L$=xf.exports=function(t){bf.call(this);let e=[],s=this;this._filter=new P$(t,{read:this.read.bind(this),write:function(n){e.push(n)},complete:function(){s.emit("complete",Buffer.concat(e))}}),this._filter.start()};M$.inherits(L$,bf)});var Rs=z((lR,Sf)=>{"use strict";Sf.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 rl=z((cR,vf)=>{"use strict";var sl=[];(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;sl[t]=e}})();var ol=vf.exports=function(){this._crc=-1};ol.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=sl[(this._crc^t[e])&255]^this._crc>>>8;return!0};ol.prototype.crc32=function(){return this._crc^-1};ol.crc32=function(t){let e=-1;for(let s=0;s<t.length;s++)e=sl[(e^t[s])&255]^e>>>8;return e^-1}});var il=z((uR,Ef)=>{"use strict";var Ye=Rs(),I$=rl(),Ke=Ef.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(){}};Ke.prototype.start=function(){this.read(Ye.PNG_SIGNATURE.length,this._parseSignature.bind(this))};Ke.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))};Ke.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 I$,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))};Ke.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};Ke.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};Ke.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))};Ke.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};Ke.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()};Ke.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};Ke.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()};Ke.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};Ke.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()};Ke.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};Ke.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/Ye.GAMMA_DIVISION),this._handleChunkEnd()};Ke.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};Ke.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()};Ke.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};Ke.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var al=z(Rf=>{"use strict";var Tf=el(),D$=[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]}],j$=[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 q$(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 F$(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);D$[n](e,o,d,r),r+=n}return r}function B$(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);j$[n](e,d,f,r)}o.resetAfterLine()}}Rf.dataToBitMap=function(t,e){let s=e.width,n=e.height,o=e.depth,r=e.bpp,i=e.interlace,a;o!==8&&(a=q$(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=Tf.getImagePasses(s,n),f=Tf.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=F$(d[p],l,f,r,t,u):B$(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 ll=z((fR,Cf)=>{"use strict";function U$(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 W$(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 H$(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}}Cf.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?U$(t,c,o,r,l):(a&&W$(t,c,o,r,a),n!==8&&!s&&(n===16&&(c=Buffer.alloc(o*r*4)),H$(t,c,o,r,n))),c}});var Nf=z((pR,Of)=>{"use strict";var Y$=require("util"),cl=require("zlib"),Af=Za(),G$=kf(),z$=il(),K$=al(),X$=ll(),Gt=Of.exports=function(t){Af.call(this),this._parser=new z$(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()};Y$.inherits(Gt,Af);Gt.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};Gt.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=cl.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,cl.Z_MIN_CHUNK);this._inflate=cl.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)};Gt.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new G$(this._bitmapInfo)};Gt.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};Gt.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};Gt.prototype._simpleTransparency=function(){this._metaData.alpha=!0};Gt.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};Gt.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};Gt.prototype._complete=function(t){if(this.errord)return;let e;try{let s=K$.dataToBitMap(t,this._bitmapInfo);e=X$(s,this._bitmapInfo,this._options.skipRescale),s=null}catch(s){this._handleError(s);return}this.emit("parsed",e)}});var Pf=z((hR,Mf)=>{"use strict";var Et=Rs();Mf.exports=function(t,e,s,n){let o=[Et.COLORTYPE_COLOR_ALPHA,Et.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=Et.COLORTYPE_TO_BPP_MAP[n.inputColorType];a===4&&!n.inputHasAlpha&&(a=3);let l=Et.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 Et.COLORTYPE_COLOR_ALPHA:b=r[u+3],h=r[u],g=r[u+1],_=r[u+2];break;case Et.COLORTYPE_COLOR:h=r[u],g=r[u+1],_=r[u+2];break;case Et.COLORTYPE_ALPHA:b=r[u+1],h=r[u],g=h,_=h;break;case Et.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 Et.COLORTYPE_COLOR_ALPHA:case Et.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 Et.COLORTYPE_ALPHA:case Et.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 Df=z((mR,If)=>{"use strict";var Lf=tl();function V$(t,e,s,n,o){for(let r=0;r<s;r++)n[o+r]=t[e+r]}function J$(t,e,s){let n=0,o=e+s;for(let r=e;r<o;r++)n+=Math.abs(t[r]);return n}function Z$(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 Q$(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 eb(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 tb(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 nb(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 sb(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 ob(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]-Lf(a,l,c);n[o+i]=u}}function rb(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]-Lf(i,a,l);o+=Math.abs(c)}return o}var ib={0:V$,1:Z$,2:eb,3:nb,4:ob},ab={0:J$,1:Q$,2:tb,3:sb,4:rb};If.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=ab[r[p]](t,l,i,o);h<f&&(u=r[p],f=h)}}c[a]=u,a++,ib[u](t,l,i,c,a,o),a+=i,l+=i}return c}});var ul=z((gR,jf)=>{"use strict";var st=Rs(),lb=rl(),cb=Pf(),ub=Df(),db=require("zlib"),wn=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||db.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:st.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:st.COLORTYPE_COLOR_ALPHA,[st.COLORTYPE_GRAYSCALE,st.COLORTYPE_COLOR,st.COLORTYPE_COLOR_ALPHA,st.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([st.COLORTYPE_GRAYSCALE,st.COLORTYPE_COLOR,st.COLORTYPE_COLOR_ALPHA,st.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")};wn.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};wn.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};wn.prototype.filterData=function(t,e,s){let n=cb(t,e,s,this._options),o=st.COLORTYPE_TO_BPP_MAP[this._options.colorType];return ub(n,e,s,this._options,o)};wn.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(lb.crc32(n.slice(4,n.length-4)),n.length-4),n};wn.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*st.GAMMA_DIVISION),0),this._packChunk(st.TYPE_gAMA,e)};wn.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(st.TYPE_IHDR,s)};wn.prototype.packIDAT=function(t){return this._packChunk(st.TYPE_IDAT,t)};wn.prototype.packIEND=function(){return this._packChunk(st.TYPE_IEND,null)}});var Uf=z((yR,Bf)=>{"use strict";var fb=require("util"),qf=require("stream"),pb=Rs(),hb=ul(),Ff=Bf.exports=function(t){qf.call(this);let e=t||{};this._packer=new hb(e),this._deflate=this._packer.createDeflate(),this.readable=!0};fb.inherits(Ff,qf);Ff.prototype.pack=function(t,e,s,n){this.emit("data",Buffer.from(pb.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 Kf=z((fo,zf)=>{"use strict";var Wf=require("assert").ok,Cs=require("zlib"),mb=require("util"),Hf=require("buffer").kMaxLength;function Dn(t){if(!(this instanceof Dn))return new Dn(t);t&&t.chunkSize<Cs.Z_MIN_CHUNK&&(t.chunkSize=Cs.Z_MIN_CHUNK),Cs.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 gb(t){return new Dn(t)}function Yf(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}Dn.prototype._processChunk=function(t,e,s){if(typeof s=="function")return Cs.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(Wf(_>=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}Wf(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>=Hf)throw Yf(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+Hf.toString(16)+" bytes");let p=Buffer.concat(l,c);return Yf(this),p};mb.inherits(Dn,Cs.Inflate);function yb(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=Cs.Z_FINISH),t._processChunk(e,s)}function Gf(t,e){return yb(new Dn(e),t)}zf.exports=fo=Gf;fo.Inflate=Dn;fo.createInflate=gb;fo.inflateSync=Gf});var dl=z((wR,Vf)=>{"use strict";var Xf=Vf.exports=function(t){this._buffer=t,this._reads=[]};Xf.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};Xf.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 Zf=z(Jf=>{"use strict";var wb=dl(),_b=nl();Jf.process=function(t,e){let s=[],n=new wb(t);return new _b(e,{read:n.read.bind(n),write:function(r){s.push(r)},complete:function(){}}).start(),n.process(),Buffer.concat(s)}});var np=z(($R,tp)=>{"use strict";var Qf=!0,ep=require("zlib"),$b=Kf();ep.deflateSync||(Qf=!1);var bb=dl(),xb=Zf(),kb=il(),Sb=al(),vb=ll();tp.exports=function(t,e){if(!Qf)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(k){s=k}let o;function r(k){o=k}function i(k){o.transColor=k}function a(k){o.palette=k}function l(){o.alpha=!0}let c;function u(k){c=k}let d=[];function f(k){d.push(k)}let p=new bb(t);if(new kb(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)_=ep.inflateSync(g);else{let E=((o.width*o.bpp*o.depth+7>>3)+1)*o.height;_=$b(g,{chunkSize:E,maxLength:E})}if(g=null,!_||!_.length)throw new Error("bad png - invalid inflate data response");let b=xb.process(_,o);g=null;let O=Sb.dataToBitMap(b,o);b=null;let M=vb(O,o,e.skipRescale);return o.data=M,o.gamma=c||0,o}});var ip=z((bR,rp)=>{"use strict";var sp=!0,op=require("zlib");op.deflateSync||(sp=!1);var Eb=Rs(),Tb=ul();rp.exports=function(t,e){if(!sp)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 Tb(s),o=[];o.push(Buffer.from(Eb.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=op.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=z(fl=>{"use strict";var Rb=np(),Cb=ip();fl.read=function(t,e){return Rb(t,e||{})};fl.write=function(t,e){return Cb(t,e)}});var up=z(cp=>{"use strict";var Ab=require("util"),lp=require("stream"),Ob=Nf(),Nb=Uf(),Mb=ap(),it=cp.PNG=function(t){lp.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 Ob(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 Nb(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"))};Ab.inherits(it,lp);it.sync=Mb;it.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)};it.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};it.prototype.write=function(t){return this._parser.write(t),!0};it.prototype.end=function(t){this._parser.end(t)};it.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};it.prototype._gamma=function(t){this.gamma=t};it.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};it.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)};it.prototype.bitblt=function(t,e,s,n,o,r,i){return it.bitblt(this,t,e,s,n,o,r,i),this};it.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}};it.prototype.adjustGamma=function(){it.adjustGamma(this)}});var mp={};Ry(mp,{default:()=>pp});function pp(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(!pl(t)||!pl(e)||s&&!pl(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 S=0;S<p;S++)if(h[S]!==g[S]){_=!1;break}if(_){if(s&&!f)for(let S=0;S<p;S++)fp(t,4*S,a,s);return 0}let b=35215*i*i,[O,M,k]=l,[E,N,ee]=c,[X,ce,ae]=d||c,ne=0;for(let S=0;S<o;S++)for(let Te=0;Te<n;Te++){let H=S*n+Te,K=H*4,pe=h[H]===g[H]?0:hp(t,e,K,K,!1);if(Math.abs(pe)>b){let ve=dp(t,Te,S,n,o,h,g)||dp(e,Te,S,n,o,g,h);!u&&ve?s&&!f&&Gr(s,K,O,M,k):(s&&(pe<0?Gr(s,K,X,ce,ae):Gr(s,K,E,N,ee)),ne++)}else s&&!f&&fp(t,K,a,s)}return ne}function pl(t){return ArrayBuffer.isView(t)&&t.BYTES_PER_ELEMENT===1}function dp(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 k=l;k<=u;k++){if(M===e&&k===s)continue;let E=hp(t,t,d*4,(k*n+M)*4,!0);if(E===0){if(f++,f>2)return!1}else E<p?(p=E,g=M,_=k):E>h&&(h=E,b=M,O=k)}return p===0||h===0?!1:Yr(r,g,_,n,o)&&Yr(i,g,_,n,o)||Yr(r,b,O,n,o)&&Yr(i,b,O,n,o)}function Yr(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 hp(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 E=48+159*(s%2),N=48+159*((s/1.618033988749895|0)%2),ee=48+159*((s/2.618033988749895|0)%2);p=(r*l-c*f-E*_)/255,h=(i*l-u*f-N*_)/255,g=(a*l-d*f-ee*_)/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,k=.5053*b*b+.299*O*O+.1957*M*M;return b>0?-k:k}function Gr(t,e,s,n,o){t[e+0]=s,t[e+1]=n,t[e+2]=o,t[e+3]=255}function fp(t,e,s,n){let o=255+(t[e]*.29889531+t[e+1]*.58662247+t[e+2]*.11448223-255)*s*t[e+3]/255;Gr(n,e,o,o,o)}var gp=Ty(()=>{});var jn=z((SR,bp)=>{var ln=require("fs"),Pb=require("path"),Lb=require("os"),Ib="nex-visual-";function wp(t){return Pb.join(Lb.tmpdir(),`${Ib}${Date.now()}-${t}`)}var hl=null;function zr(){return hl||(hl=up().PNG),hl}var ml=null;function Db(){if(!ml){let t=(gp(),Ay(mp));ml=t.default||t}return ml}function wl(t,e,{threshold:s=.1}={}){let n=zr(),o=Db(),r=n.sync.read(ln.readFileSync(t)),i=n.sync.read(ln.readFileSync(e)),a=Math.max(r.width,i.width),l=Math.max(r.height,i.height),c=yp(r,a,l),u=yp(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=jb(d.data,a,l,3,3),_=wp("diff.png");return ln.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 yp(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 jb(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 _p=[{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 qb(t,{viewports:e=_p,height:s=800,fullPage:n=!1,timeout:o=3e4}={}){let{browserScreenshot:r}=an(),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 $p(t,e=[]){let s=zr(),n=s.sync.read(ln.readFileSync(t));for(let i of e){let a=Fb(i.color||"#FF0000");i.type==="box"?(Bb(n,i.x||0,i.y||0,i.width||50,i.height||50,a,i.thickness||3),i.label&&yl(n,i.x||0,(i.y||0)-14,i.label,a)):i.type==="arrow"?(Ub(n,i.x||0,i.y||0,i.toX||i.x+50,i.toY||i.y,a,i.thickness||3),i.label&&yl(n,i.x||0,(i.y||0)-14,i.label,a)):i.type==="circle"&&(Wb(n,i.x||0,i.y||0,i.radius||20,a,i.thickness||3),i.label&&yl(n,(i.x||0)-(i.radius||20),(i.y||0)-(i.radius||20)-14,i.label,a))}let o=wp("annotated.png");ln.writeFileSync(o,s.sync.write(n),{mode:384});let r=ln.readFileSync(o).toString("base64");return{path:o,base64:r,media_type:"image/png"}}function Fb(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 zt(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 Bb(t,e,s,n,o,r,i=3){for(let a=0;a<i;a++){for(let l=0;l<n;l++)zt(t,e+l,s+a,r),zt(t,e+l,s+o-1-a,r);for(let l=0;l<o;l++)zt(t,e+a,s+l,r),zt(t,e+n-1-a,s+l,r)}}function gl(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++)zt(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 Ub(t,e,s,n,o,r,i=3){gl(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;gl(t,n,o,Math.round(n+l*Math.cos(c)),Math.round(o+l*Math.sin(c)),r,i),gl(t,n,o,Math.round(n+l*Math.cos(u)),Math.round(o+l*Math.sin(u)),r,i)}function Wb(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));zt(t,u,d,o)}}}function yl(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++)zt(t,e+c,s+l,{r:0,g:0,b:0,a:200});for(let l=0;l<i;l++)zt(t,e+l,s+a-1,o),zt(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++)zt(t,c+d,s+u,o)}}async function*Hb(t,e,{maxIterations:s=20,hmrDelay:n=1500,width:o=1280,height:r=800,timeout:i=3e4}={}){let{browserScreenshot:a}=an(),l=Yb("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 zb(()=>d,3e5),d=!1,u++,await Gb(n);let p=await a(t,{width:o,height:r,timeout:i}),h=null;try{h=wl(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 Yb(t){try{return require(t)}catch{return null}}function Gb(t){return new Promise(e=>setTimeout(e,t))}function zb(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 Kb(t,{sampleRate:e=4}={}){let n=zr().sync.read(ln.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:Xb(d,f,p),rgb:`rgb(${d}, ${f}, ${p})`,frequency:parseFloat((u/i*100).toFixed(1)),category:Vb(d,f,p)}}),l=Jb(n);return{colors:a,spacing:l,dimensions:{width:n.width,height:n.height},imagePath:t}}function Xb(t,e,s){return"#"+[t,e,s].map(n=>Math.min(255,n).toString(16).padStart(2,"0")).join("")}function Vb(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 Jb(t){let e=[],s=!1,n=0,o=Zb(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 Zb(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 Qb(t,e,{width:s,height:n=800,fullPage:o=!1,threshold:r=.1,timeout:i=3e4}={}){let{browserScreenshot:a}=an(),c=zr().sync.read(ln.readFileSync(e)),u=s||c.width,d=n||c.height,f=await a(t,{width:u,height:d,fullPage:o,timeout:i}),p=wl(e,f.path,{threshold:r}),h=$p(f.path,p.regionSummary.filter(g=>g.changedPercent>1).map((g,_)=>{let M=Math.ceil(p.width/3),k=Math.ceil(p.height/3),E=[["top-left","top-center","top-right"],["middle-left","center","middle-right"],["bottom-left","bottom-center","bottom-right"]],N=0,ee=0;for(let X=0;X<3;X++)for(let ce=0;ce<3;ce++)E[X][ce]===g.name&&(N=ce,ee=X);return{type:"box",x:N*M+2,y:ee*k+2,width:M-4,height:k-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:ln.readFileSync(p.diffPath).toString("base64"),annotatedBase64:h.base64}}bp.exports={pixelDiff:wl,responsiveSweep:qb,annotateImage:$p,visualWatch:Hb,extractDesignTokens:Kb,designCompare:Qb,DEFAULT_VIEWPORTS:_p}});var _l=z((vR,xp)=>{var{C:Ae}=ze(),ho="",at=[],po=0,qn=null;function ex(t){qn=t}function tx(t,e){ho=t,at=[],po=0;for(let n of e){po++;let o=`t${po}`;at.push({id:o,description:n.description||n.title||n.name||n.task||`Task ${po}`,status:"pending",dependsOn:n.depends_on||[],result:null})}let s=at.map(n=>({...n}));return qn&&qn("create",{name:t,tasks:s}),s}function nx(t,e,s){let n=at.find(o=>o.id===t);return n?(n.status=e,s!==void 0&&(n.result=s),qn&&qn("update",{id:t,status:e,result:s}),{...n}):null}function sx(){return{name:ho,tasks:at.map(t=>({...t}))}}function ox(){ho="",at=[],po=0,qn&&qn("clear",{})}function rx(){return at.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let s=at.find(n=>n.id===e);return s&&s.status==="done"}))}function ix(){if(at.length===0)return`${Ae.dim}No active tasks${Ae.reset}`;let t=[];ho&&(t.push(` ${Ae.bold}${Ae.cyan}Tasks: ${ho}${Ae.reset}`),t.push(` ${Ae.dim}${"\u2500".repeat(40)}${Ae.reset}`));for(let o of at){let r,i;switch(o.status){case"done":r="\u2713",i=Ae.green;break;case"in_progress":r="\u2192",i=Ae.cyan;break;case"failed":r="\u2717",i=Ae.red;break;default:r="\xB7",i=Ae.dim}let a=o.dependsOn.length>0?` ${Ae.dim}(after: ${o.dependsOn.join(", ")})${Ae.reset}`:"",l=`[${o.status}]`,c=o.description.length>50?o.description.substring(0,47)+"...":o.description;if(t.push(` ${i}${r}${Ae.reset} ${Ae.bold}${o.id}${Ae.reset} ${c.padEnd(40)} ${i}${l}${Ae.reset}${a}`),o.result&&o.status==="done"){let u=o.result.length>60?o.result.substring(0,57)+"...":o.result;t.push(` ${Ae.dim}\u2192 ${u}${Ae.reset}`)}}let e=at.filter(o=>o.status==="done").length,s=at.filter(o=>o.status==="failed").length,n=at.length;return t.push(` ${Ae.dim}${"\u2500".repeat(40)}${Ae.reset}`),t.push(` ${Ae.dim}${e}/${n} done${s>0?`, ${s} failed`:""}${Ae.reset}`),t.join(`
130
- `)}function ax(){return at.length>0&&at.some(t=>t.status==="pending"||t.status==="in_progress")}xp.exports={createTasks:tx,updateTask:nx,getTaskList:sx,clearTasks:ox,getReadyTasks:rx,renderTaskList:ix,setOnChange:ex,hasActiveTasks:ax}});var Kr=z((ER,Sp)=>{var mo={"devstral-2":{staleWarn:3e4,staleAbort:9e4,investigationCap:18,postEditCap:10,briefing:`You are devstral-2, a strong coding model optimized for agentic tasks.
128
+ Then restart nex-code.`;function mf(){if(uo!==null)return uo;try{require("playwright"),uo=!0}catch{uo=!1}return uo}async function Yr(){if(!mf())throw new Error(hf);return Qa||(Qa=require("playwright")),(!an||!an.isConnected())&&(an=await Qa.chromium.launch({headless:!0})),an}async function E$(){if(an){try{await an.close()}catch{}an=null}}process.on("exit",()=>{if(an)try{an.close()}catch{}});async function T$(t,{timeout:e=3e4,waitFor:s="domcontentloaded"}={}){let o=await(await Yr()).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?`
129
+ ...(truncated)`:""),links:a.slice(0,20)}}finally{await o.close()}}async function R$(t,{width:e=1280,height:s=800,fullPage:n=!1,timeout:o=3e4}={}){let i=await(await Yr()).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 C$(t,{selector:e,text:s,timeout:n=3e4}={}){if(!e&&!s)throw new Error("selector or text is required");let r=await(await Yr()).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 A$(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 Yr()).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()}}gf.exports={isPlaywrightAvailable:mf,browserNavigate:T$,browserScreenshot:R$,browserClick:C$,browserFill:A$,closeBrowser:E$,INSTALL_MSG:hf}});var el=z((oR,wf)=>{"use strict";var O$=require("util"),yf=require("stream"),jt=wf.exports=function(){yf.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};O$.inherits(jt,yf);jt.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))};jt.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};jt.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()))};jt.prototype.destroySoon=jt.prototype.end;jt.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};jt.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};jt.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))};jt.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)};jt.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 nl=z(tl=>{"use strict";var _n=[{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]}];tl.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<_n.length;a++){let l=_n[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};tl.getInterlaceIterator=function(t){return function(e,s,n){let o=e%_n[n].x.length,r=(e-o)/_n[n].x.length*8+_n[n].x[o],i=s%_n[n].y.length,a=(s-i)/_n[n].y.length*8+_n[n].y[i];return r*4+a*t*4}}});var sl=z((iR,_f)=>{"use strict";_f.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 ol=z((aR,bf)=>{"use strict";var N$=nl(),M$=sl();function $f(t,e,s){let n=t*e;return s!==8&&(n=Math.ceil(n/(8/s))),n}var Ts=bf.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=N$.getImagePasses(s,n);for(let l=0;l<a.length;l++)this._images.push({byteWidth:$f(a[l].width,r,i),height:a[l].height,lineIndex:0})}else this._images.push({byteWidth:$f(s,r,i),height:n,lineIndex:0});i===8?this._xComparison=r:i===16?this._xComparison=r*2:this._xComparison=1};Ts.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};Ts.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}};Ts.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}};Ts.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}};Ts.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=M$(c,l,u);e[i]=a+d}};Ts.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 Sf=z((lR,kf)=>{"use strict";var P$=require("util"),xf=el(),L$=ol(),I$=kf.exports=function(t){xf.call(this);let e=[],s=this;this._filter=new L$(t,{read:this.read.bind(this),write:function(n){e.push(n)},complete:function(){s.emit("complete",Buffer.concat(e))}}),this._filter.start()};P$.inherits(I$,xf)});var Rs=z((cR,vf)=>{"use strict";vf.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 al=z((uR,Ef)=>{"use strict";var rl=[];(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;rl[t]=e}})();var il=Ef.exports=function(){this._crc=-1};il.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=rl[(this._crc^t[e])&255]^this._crc>>>8;return!0};il.prototype.crc32=function(){return this._crc^-1};il.crc32=function(t){let e=-1;for(let s=0;s<t.length;s++)e=rl[(e^t[s])&255]^e>>>8;return e^-1}});var ll=z((dR,Tf)=>{"use strict";var Ye=Rs(),D$=al(),Xe=Tf.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 D$,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 cl=z(Cf=>{"use strict";var Rf=nl(),j$=[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]}],q$=[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 F$(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 B$(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);j$[n](e,o,d,r),r+=n}return r}function U$(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);q$[n](e,d,f,r)}o.resetAfterLine()}}Cf.dataToBitMap=function(t,e){let s=e.width,n=e.height,o=e.depth,r=e.bpp,i=e.interlace,a;o!==8&&(a=F$(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=Rf.getImagePasses(s,n),f=Rf.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=B$(d[p],l,f,r,t,u):U$(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 ul=z((pR,Af)=>{"use strict";function W$(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 H$(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 Y$(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}}Af.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?W$(t,c,o,r,l):(a&&H$(t,c,o,r,a),n!==8&&!s&&(n===16&&(c=Buffer.alloc(o*r*4)),Y$(t,c,o,r,n))),c}});var Mf=z((hR,Nf)=>{"use strict";var G$=require("util"),dl=require("zlib"),Of=el(),z$=Sf(),K$=ll(),X$=cl(),V$=ul(),Xt=Nf.exports=function(t){Of.call(this),this._parser=new K$(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()};G$.inherits(Xt,Of);Xt.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};Xt.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=dl.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,dl.Z_MIN_CHUNK);this._inflate=dl.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)};Xt.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new z$(this._bitmapInfo)};Xt.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};Xt.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};Xt.prototype._simpleTransparency=function(){this._metaData.alpha=!0};Xt.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};Xt.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};Xt.prototype._complete=function(t){if(this.errord)return;let e;try{let s=X$.dataToBitMap(t,this._bitmapInfo);e=V$(s,this._bitmapInfo,this._options.skipRescale),s=null}catch(s){this._handleError(s);return}this.emit("parsed",e)}});var Lf=z((mR,Pf)=>{"use strict";var Ct=Rs();Pf.exports=function(t,e,s,n){let o=[Ct.COLORTYPE_COLOR_ALPHA,Ct.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=Ct.COLORTYPE_TO_BPP_MAP[n.inputColorType];a===4&&!n.inputHasAlpha&&(a=3);let l=Ct.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 Ct.COLORTYPE_COLOR_ALPHA:b=r[u+3],h=r[u],g=r[u+1],_=r[u+2];break;case Ct.COLORTYPE_COLOR:h=r[u],g=r[u+1],_=r[u+2];break;case Ct.COLORTYPE_ALPHA:b=r[u+1],h=r[u],g=h,_=h;break;case Ct.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 Ct.COLORTYPE_COLOR_ALPHA:case Ct.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 Ct.COLORTYPE_ALPHA:case Ct.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 jf=z((gR,Df)=>{"use strict";var If=sl();function J$(t,e,s,n,o){for(let r=0;r<s;r++)n[o+r]=t[e+r]}function Z$(t,e,s){let n=0,o=e+s;for(let r=e;r<o;r++)n+=Math.abs(t[r]);return n}function Q$(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 eb(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 tb(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 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 ob(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 rb(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]-If(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]-If(i,a,l);o+=Math.abs(c)}return o}var ab={0:J$,1:Q$,2:tb,3:sb,4:rb},lb={0:Z$,1:eb,2:nb,3:ob,4:ib};Df.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=lb[r[p]](t,l,i,o);h<f&&(u=r[p],f=h)}}c[a]=u,a++,ab[u](t,l,i,c,a,o),a+=i,l+=i}return c}});var fl=z((yR,qf)=>{"use strict";var ot=Rs(),cb=al(),ub=Lf(),db=jf(),fb=require("zlib"),$n=qf.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||fb.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:ot.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:ot.COLORTYPE_COLOR_ALPHA,[ot.COLORTYPE_GRAYSCALE,ot.COLORTYPE_COLOR,ot.COLORTYPE_COLOR_ALPHA,ot.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([ot.COLORTYPE_GRAYSCALE,ot.COLORTYPE_COLOR,ot.COLORTYPE_COLOR_ALPHA,ot.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")};$n.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};$n.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};$n.prototype.filterData=function(t,e,s){let n=ub(t,e,s,this._options),o=ot.COLORTYPE_TO_BPP_MAP[this._options.colorType];return db(n,e,s,this._options,o)};$n.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(cb.crc32(n.slice(4,n.length-4)),n.length-4),n};$n.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*ot.GAMMA_DIVISION),0),this._packChunk(ot.TYPE_gAMA,e)};$n.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(ot.TYPE_IHDR,s)};$n.prototype.packIDAT=function(t){return this._packChunk(ot.TYPE_IDAT,t)};$n.prototype.packIEND=function(){return this._packChunk(ot.TYPE_IEND,null)}});var Wf=z((wR,Uf)=>{"use strict";var pb=require("util"),Ff=require("stream"),hb=Rs(),mb=fl(),Bf=Uf.exports=function(t){Ff.call(this);let e=t||{};this._packer=new mb(e),this._deflate=this._packer.createDeflate(),this.readable=!0};pb.inherits(Bf,Ff);Bf.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 Xf=z((fo,Kf)=>{"use strict";var Hf=require("assert").ok,Cs=require("zlib"),gb=require("util"),Yf=require("buffer").kMaxLength;function qn(t){if(!(this instanceof qn))return new qn(t);t&&t.chunkSize<Cs.Z_MIN_CHUNK&&(t.chunkSize=Cs.Z_MIN_CHUNK),Cs.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 yb(t){return new qn(t)}function Gf(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}qn.prototype._processChunk=function(t,e,s){if(typeof s=="function")return Cs.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(Hf(_>=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}Hf(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>=Yf)throw Gf(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+Yf.toString(16)+" bytes");let p=Buffer.concat(l,c);return Gf(this),p};gb.inherits(qn,Cs.Inflate);function wb(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=Cs.Z_FINISH),t._processChunk(e,s)}function zf(t,e){return wb(new qn(e),t)}Kf.exports=fo=zf;fo.Inflate=qn;fo.createInflate=yb;fo.inflateSync=zf});var pl=z((_R,Jf)=>{"use strict";var Vf=Jf.exports=function(t){this._buffer=t,this._reads=[]};Vf.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};Vf.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 Qf=z(Zf=>{"use strict";var _b=pl(),$b=ol();Zf.process=function(t,e){let s=[],n=new _b(t);return new $b(e,{read:n.read.bind(n),write:function(r){s.push(r)},complete:function(){}}).start(),n.process(),Buffer.concat(s)}});var sp=z((bR,np)=>{"use strict";var ep=!0,tp=require("zlib"),bb=Xf();tp.deflateSync||(ep=!1);var xb=pl(),kb=Qf(),Sb=ll(),vb=cl(),Eb=ul();np.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;function n(k){s=k}let o;function r(k){o=k}function i(k){o.transColor=k}function a(k){o.palette=k}function l(){o.alpha=!0}let c;function u(k){c=k}let d=[];function f(k){d.push(k)}let p=new xb(t);if(new Sb(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)_=tp.inflateSync(g);else{let E=((o.width*o.bpp*o.depth+7>>3)+1)*o.height;_=bb(g,{chunkSize:E,maxLength:E})}if(g=null,!_||!_.length)throw new Error("bad png - invalid inflate data response");let b=kb.process(_,o);g=null;let O=vb.dataToBitMap(b,o);b=null;let M=Eb(O,o,e.skipRescale);return o.data=M,o.gamma=c||0,o}});var ap=z((xR,ip)=>{"use strict";var op=!0,rp=require("zlib");rp.deflateSync||(op=!1);var Tb=Rs(),Rb=fl();ip.exports=function(t,e){if(!op)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 Rb(s),o=[];o.push(Buffer.from(Tb.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=rp.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 lp=z(hl=>{"use strict";var Cb=sp(),Ab=ap();hl.read=function(t,e){return Cb(t,e||{})};hl.write=function(t,e){return Ab(t,e)}});var dp=z(up=>{"use strict";var Ob=require("util"),cp=require("stream"),Nb=Mf(),Mb=Wf(),Pb=lp(),ct=up.PNG=function(t){cp.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 Nb(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 Mb(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"))};Ob.inherits(ct,cp);ct.sync=Pb;ct.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)};ct.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};ct.prototype.write=function(t){return this._parser.write(t),!0};ct.prototype.end=function(t){this._parser.end(t)};ct.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};ct.prototype._gamma=function(t){this.gamma=t};ct.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};ct.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)};ct.prototype.bitblt=function(t,e,s,n,o,r,i){return ct.bitblt(this,t,e,s,n,o,r,i),this};ct.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}};ct.prototype.adjustGamma=function(){ct.adjustGamma(this)}});var gp={};Cy(gp,{default:()=>hp});function hp(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(!ml(t)||!ml(e)||s&&!ml(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 S=0;S<p;S++)if(h[S]!==g[S]){_=!1;break}if(_){if(s&&!f)for(let S=0;S<p;S++)pp(t,4*S,a,s);return 0}let b=35215*i*i,[O,M,k]=l,[E,N,te]=c,[X,ce,ae]=d||c,se=0;for(let S=0;S<o;S++)for(let Re=0;Re<n;Re++){let H=S*n+Re,K=H*4,pe=h[H]===g[H]?0:mp(t,e,K,K,!1);if(Math.abs(pe)>b){let ve=fp(t,Re,S,n,o,h,g)||fp(e,Re,S,n,o,g,h);!u&&ve?s&&!f&&zr(s,K,O,M,k):(s&&(pe<0?zr(s,K,X,ce,ae):zr(s,K,E,N,te)),se++)}else s&&!f&&pp(t,K,a,s)}return se}function ml(t){return ArrayBuffer.isView(t)&&t.BYTES_PER_ELEMENT===1}function fp(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 k=l;k<=u;k++){if(M===e&&k===s)continue;let E=mp(t,t,d*4,(k*n+M)*4,!0);if(E===0){if(f++,f>2)return!1}else E<p?(p=E,g=M,_=k):E>h&&(h=E,b=M,O=k)}return p===0||h===0?!1:Gr(r,g,_,n,o)&&Gr(i,g,_,n,o)||Gr(r,b,O,n,o)&&Gr(i,b,O,n,o)}function Gr(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 mp(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 E=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-E*_)/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,k=.5053*b*b+.299*O*O+.1957*M*M;return b>0?-k:k}function zr(t,e,s,n,o){t[e+0]=s,t[e+1]=n,t[e+2]=o,t[e+3]=255}function pp(t,e,s,n){let o=255+(t[e]*.29889531+t[e+1]*.58662247+t[e+2]*.11448223-255)*s*t[e+3]/255;zr(n,e,o,o,o)}var yp=Ry(()=>{});var Fn=z((vR,xp)=>{var cn=require("fs"),Lb=require("path"),Ib=require("os"),Db="nex-visual-";function _p(t){return Lb.join(Ib.tmpdir(),`${Db}${Date.now()}-${t}`)}var gl=null;function Kr(){return gl||(gl=dp().PNG),gl}var yl=null;function jb(){if(!yl){let t=(yp(),Oy(gp));yl=t.default||t}return yl}function $l(t,e,{threshold:s=.1}={}){let n=Kr(),o=jb(),r=n.sync.read(cn.readFileSync(t)),i=n.sync.read(cn.readFileSync(e)),a=Math.max(r.width,i.width),l=Math.max(r.height,i.height),c=wp(r,a,l),u=wp(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=qb(d.data,a,l,3,3),_=_p("diff.png");return cn.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 wp(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 qb(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 $p=[{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 Fb(t,{viewports:e=$p,height:s=800,fullPage:n=!1,timeout:o=3e4}={}){let{browserScreenshot:r}=ln(),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 bp(t,e=[]){let s=Kr(),n=s.sync.read(cn.readFileSync(t));for(let i of e){let a=Bb(i.color||"#FF0000");i.type==="box"?(Ub(n,i.x||0,i.y||0,i.width||50,i.height||50,a,i.thickness||3),i.label&&_l(n,i.x||0,(i.y||0)-14,i.label,a)):i.type==="arrow"?(Wb(n,i.x||0,i.y||0,i.toX||i.x+50,i.toY||i.y,a,i.thickness||3),i.label&&_l(n,i.x||0,(i.y||0)-14,i.label,a)):i.type==="circle"&&(Hb(n,i.x||0,i.y||0,i.radius||20,a,i.thickness||3),i.label&&_l(n,(i.x||0)-(i.radius||20),(i.y||0)-(i.radius||20)-14,i.label,a))}let o=_p("annotated.png");cn.writeFileSync(o,s.sync.write(n),{mode:384});let r=cn.readFileSync(o).toString("base64");return{path:o,base64:r,media_type:"image/png"}}function Bb(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 Vt(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 Ub(t,e,s,n,o,r,i=3){for(let a=0;a<i;a++){for(let l=0;l<n;l++)Vt(t,e+l,s+a,r),Vt(t,e+l,s+o-1-a,r);for(let l=0;l<o;l++)Vt(t,e+a,s+l,r),Vt(t,e+n-1-a,s+l,r)}}function wl(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++)Vt(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 Wb(t,e,s,n,o,r,i=3){wl(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;wl(t,n,o,Math.round(n+l*Math.cos(c)),Math.round(o+l*Math.sin(c)),r,i),wl(t,n,o,Math.round(n+l*Math.cos(u)),Math.round(o+l*Math.sin(u)),r,i)}function Hb(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));Vt(t,u,d,o)}}}function _l(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++)Vt(t,e+c,s+l,{r:0,g:0,b:0,a:200});for(let l=0;l<i;l++)Vt(t,e+l,s+a-1,o),Vt(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++)Vt(t,c+d,s+u,o)}}async function*Yb(t,e,{maxIterations:s=20,hmrDelay:n=1500,width:o=1280,height:r=800,timeout:i=3e4}={}){let{browserScreenshot:a}=ln(),l=Gb("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 Kb(()=>d,3e5),d=!1,u++,await zb(n);let p=await a(t,{width:o,height:r,timeout:i}),h=null;try{h=$l(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 Gb(t){try{return require(t)}catch{return null}}function zb(t){return new Promise(e=>setTimeout(e,t))}function Kb(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 Xb(t,{sampleRate:e=4}={}){let n=Kr().sync.read(cn.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:Vb(d,f,p),rgb:`rgb(${d}, ${f}, ${p})`,frequency:parseFloat((u/i*100).toFixed(1)),category:Jb(d,f,p)}}),l=Zb(n);return{colors:a,spacing:l,dimensions:{width:n.width,height:n.height},imagePath:t}}function Vb(t,e,s){return"#"+[t,e,s].map(n=>Math.min(255,n).toString(16).padStart(2,"0")).join("")}function Jb(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 Zb(t){let e=[],s=!1,n=0,o=Qb(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 Qb(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 ex(t,e,{width:s,height:n=800,fullPage:o=!1,threshold:r=.1,timeout:i=3e4}={}){let{browserScreenshot:a}=ln(),c=Kr().sync.read(cn.readFileSync(e)),u=s||c.width,d=n||c.height,f=await a(t,{width:u,height:d,fullPage:o,timeout:i}),p=$l(e,f.path,{threshold:r}),h=bp(f.path,p.regionSummary.filter(g=>g.changedPercent>1).map((g,_)=>{let M=Math.ceil(p.width/3),k=Math.ceil(p.height/3),E=[["top-left","top-center","top-right"],["middle-left","center","middle-right"],["bottom-left","bottom-center","bottom-right"]],N=0,te=0;for(let X=0;X<3;X++)for(let ce=0;ce<3;ce++)E[X][ce]===g.name&&(N=ce,te=X);return{type:"box",x:N*M+2,y:te*k+2,width:M-4,height:k-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:cn.readFileSync(p.diffPath).toString("base64"),annotatedBase64:h.base64}}xp.exports={pixelDiff:$l,responsiveSweep:Fb,annotateImage:bp,visualWatch:Yb,extractDesignTokens:Xb,designCompare:ex,DEFAULT_VIEWPORTS:$p}});var bl=z((ER,kp)=>{var{C:Oe}=Ke(),ho="",ut=[],po=0,Bn=null;function tx(t){Bn=t}function nx(t,e){ho=t,ut=[],po=0;for(let n of e){po++;let o=`t${po}`;ut.push({id:o,description:n.description||n.title||n.name||n.task||`Task ${po}`,status:"pending",dependsOn:n.depends_on||[],result:null})}let s=ut.map(n=>({...n}));return Bn&&Bn("create",{name:t,tasks:s}),s}function sx(t,e,s){let n=ut.find(o=>o.id===t);return n?(n.status=e,s!==void 0&&(n.result=s),Bn&&Bn("update",{id:t,status:e,result:s}),{...n}):null}function ox(){return{name:ho,tasks:ut.map(t=>({...t}))}}function rx(){ho="",ut=[],po=0,Bn&&Bn("clear",{})}function ix(){return ut.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let s=ut.find(n=>n.id===e);return s&&s.status==="done"}))}function ax(){if(ut.length===0)return`${Oe.dim}No active tasks${Oe.reset}`;let t=[];ho&&(t.push(` ${Oe.bold}${Oe.cyan}Tasks: ${ho}${Oe.reset}`),t.push(` ${Oe.dim}${"\u2500".repeat(40)}${Oe.reset}`));for(let o of ut){let r,i;switch(o.status){case"done":r="\u2713",i=Oe.green;break;case"in_progress":r="\u2192",i=Oe.cyan;break;case"failed":r="\u2717",i=Oe.red;break;default:r="\xB7",i=Oe.dim}let a=o.dependsOn.length>0?` ${Oe.dim}(after: ${o.dependsOn.join(", ")})${Oe.reset}`:"",l=`[${o.status}]`,c=o.description.length>50?o.description.substring(0,47)+"...":o.description;if(t.push(` ${i}${r}${Oe.reset} ${Oe.bold}${o.id}${Oe.reset} ${c.padEnd(40)} ${i}${l}${Oe.reset}${a}`),o.result&&o.status==="done"){let u=o.result.length>60?o.result.substring(0,57)+"...":o.result;t.push(` ${Oe.dim}\u2192 ${u}${Oe.reset}`)}}let e=ut.filter(o=>o.status==="done").length,s=ut.filter(o=>o.status==="failed").length,n=ut.length;return t.push(` ${Oe.dim}${"\u2500".repeat(40)}${Oe.reset}`),t.push(` ${Oe.dim}${e}/${n} done${s>0?`, ${s} failed`:""}${Oe.reset}`),t.join(`
130
+ `)}function lx(){return ut.length>0&&ut.some(t=>t.status==="pending"||t.status==="in_progress")}kp.exports={createTasks:nx,updateTask:sx,getTaskList:ox,clearTasks:rx,getReadyTasks:ix,renderTaskList:ax,setOnChange:tx,hasActiveTasks:lx}});var Xr=z((TR,vp)=>{var mo={"devstral-2":{staleWarn:3e4,staleAbort:9e4,investigationCap:18,postEditCap:10,briefing:`You are devstral-2, a strong coding model optimized for agentic tasks.
131
131
  Use tools confidently and without hesitation \u2014 tool use is the expected workflow.
132
132
  You excel at sysadmin, frontend, and multi-step coding tasks.
133
133
  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.
@@ -140,7 +140,7 @@ Focus on correctness over speed.`},"ministral-3":{staleWarn:2e4,staleAbort:6e4,i
140
140
  Prioritize decisive, targeted edits. Read only what you need, then fix.
141
141
  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.
142
142
  Trust your reasoning. Use tools thoroughly when the task demands it.
143
- You handle complex multi-step tasks well \u2014 don't cut corners prematurely.`}},kp={staleWarn:6e4,staleAbort:12e4,investigationCap:18,postEditCap:10};function lx(t){let e=(t||"").toLowerCase(),s=null,n=0;for(let r of Object.keys(mo))e.startsWith(r)&&r.length>n&&(s=r,n=r.length);let o=s?{...mo[s]}:{...kp};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 cx(t){let e=(t||"").toLowerCase(),s=null,n=0;for(let o of Object.keys(mo))e.startsWith(o)&&o.length>n&&(s=o,n=o.length);return s&&mo[s].briefing||""}Sp.exports={getModelProfile:lx,getModelBriefing:cx,PROFILES:mo,DEFAULTS:kp}});var bl=z((TR,Ap)=>{var{callChat:ux}=Ve(),{estimateTokens:$l}=Kt(),vp=process.env.NEX_COMPACTION!=="false",Ep=6,Tp=2e3,Rp=3,dx=`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.
143
+ You handle complex multi-step tasks well \u2014 don't cut corners prematurely.`}},Sp={staleWarn:6e4,staleAbort:12e4,investigationCap:18,postEditCap:10};function cx(t){let e=(t||"").toLowerCase(),s=null,n=0;for(let r of Object.keys(mo))e.startsWith(r)&&r.length>n&&(s=r,n=r.length);let o=s?{...mo[s]}:{...Sp};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 ux(t){let e=(t||"").toLowerCase(),s=null,n=0;for(let o of Object.keys(mo))e.startsWith(o)&&o.length>n&&(s=o,n=o.length);return s&&mo[s].briefing||""}vp.exports={getModelProfile:cx,getModelBriefing:ux,PROFILES:mo,DEFAULTS:Sp}});var kl=z((RR,Op)=>{var{callChat:dx}=Ze(),{estimateTokens:xl}=Jt(),Ep=process.env.NEX_COMPACTION!=="false",Tp=6,Rp=2e3,Cp=3,fx=`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.
144
144
  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.
145
145
 
146
146
  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:
@@ -172,30 +172,30 @@ Format your output as:
172
172
 
173
173
  <summary>
174
174
  [Sections 1-9 above]
175
- </summary>`,Fn=0;async function fx(t){if(!vp||t.length<Ep||Fn>=Rp)return null;let e=[{role:"system",content:dx},{role:"user",content:Cp(t)}];try{let n=((await ux(e,[],{temperature:0,maxTokens:Tp})).content||"").trim();if(!n)return Fn++,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 Fn++,null;let r=t.reduce((a,l)=>a+$l(l.content||"")+(l.tool_calls?$l(JSON.stringify(l.tool_calls)):0),0),i=$l(n);return i>=r*.8?(Fn++,null):(Fn=0,{message:{role:"system",content:`[Conversation Summary \u2014 ${t.length} messages compacted]
176
- ${n}`,_compacted:!0,_originalCount:t.length},tokensRemoved:r-i})}catch{return Fn++,null}}function px(){Fn=0}function Cp(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}
175
+ </summary>`,Un=0;async function px(t){if(!Ep||t.length<Tp||Un>=Cp)return null;let e=[{role:"system",content:fx},{role:"user",content:Ap(t)}];try{let n=((await dx(e,[],{temperature:0,maxTokens:Rp})).content||"").trim();if(!n)return Un++,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 Un++,null;let r=t.reduce((a,l)=>a+xl(l.content||"")+(l.tool_calls?xl(JSON.stringify(l.tool_calls)):0),0),i=xl(n);return i>=r*.8?(Un++,null):(Un=0,{message:{role:"system",content:`[Conversation Summary \u2014 ${t.length} messages compacted]
176
+ ${n}`,_compacted:!0,_originalCount:t.length},tokensRemoved:r-i})}catch{return Un++,null}}function hx(){Un=0}function Ap(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}
177
177
  tools: ${o}`}return`[${s}] ${n}`}).join(`
178
178
 
179
- `)}Ap.exports={compactMessages:fx,formatMessagesForSummary:Cp,resetCompactionFailures:px,COMPACTION_ENABLED:vp,COMPACTION_MIN_MESSAGES:Ep,COMPACTION_SUMMARY_BUDGET:Tp,MAX_CONSECUTIVE_FAILURES:Rp}});var Kt=z((RR,Fp)=>{var hx=require("path");function Np(){return Ve().getActiveModel()}var mx={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},gx={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},Bn=new Map,Op=1e3,xl=new WeakMap,Un=null;function yx(){if(Un!==null)return Un;try{let t=Np(),e=t?.provider||"ollama",s=(t?.id||"").toLowerCase();for(let[n,o]of Object.entries(gx))if(s.startsWith(n))return Un=o,Un;return Un=mx[e]||4,Un}catch{return 4}}function wx(){Un=null}function Wn(t){if(!t)return 0;typeof t!="string"&&(t=JSON.stringify(t));let e=t.length<=120?t:`${t.length}:${t.substring(0,60)}:${t.substring(t.length>>1,(t.length>>1)+30)}:${t.substring(t.length-30)}`,s=Bn.get(e);if(s!==void 0)return Bn.delete(e),Bn.set(e,s),s;let n=Math.ceil(t.length/yx());if(Bn.size>=Op){let o=Op>>1,r=Bn.keys();for(let i=0;i<o;i++)Bn.delete(r.next().value)}return Bn.set(e,n),n}function _x(t){if(xl.has(t))return xl.get(t);let e=JSON.stringify(t);return xl.set(t,e),e}function Hn(t){let s=4;if(t.content&&(s+=Wn(t.content)),t.tool_calls)for(let n of t.tool_calls){s+=4,s+=Wn(n.function?.name||"");let o=n.function?.arguments;typeof o=="string"?s+=Wn(o):o&&(s+=Wn(JSON.stringify(o)))}return s}function Pt(t){let e=0;for(let s of t)e+=Hn(s);return e}function $x(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+=Hn(e[r]);return o}var kl=new WeakMap;function Xr(t){if(!t||t.length===0)return 0;if(kl.has(t))return kl.get(t);let e=Wn(JSON.stringify(t));return kl.set(t,e),e}function Vr(){return Np()?.contextWindow||32768}var lt={msgCount:-1,lastMsgRef:null,toolCount:-1,result:null,messagesRef:null,messageTokens:0,systemTokens:0,conversationTokens:0,toolResultTokens:0};function bx(t,e){let s=t.length>0?t[t.length-1]:null,n=e?e.length:0;if(lt.result&&t.length===lt.msgCount&&s===lt.lastMsgRef&&n===lt.toolCount)return lt.result;let o,r,i,a;if(lt.messagesRef===t&&t.length>lt.msgCount&&lt.msgCount>=0){o=lt.messageTokens,r=lt.systemTokens,i=lt.conversationTokens,a=lt.toolResultTokens;for(let p=lt.msgCount;p<t.length;p++){let h=Hn(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=Hn(p);o+=h,p.role==="system"?r+=h:p.role==="tool"?a+=h:i+=h}}let l=Xr(e),c=o+l,u=Vr(),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 lt={msgCount:t.length,lastMsgRef:s,toolCount:n,result:f,messagesRef:t,messageTokens:o,systemTokens:r,conversationTokens:i,toolResultTokens:a},f}var go=parseFloat(process.env.NEX_COMPRESSION_THRESHOLD)||.75,Mp=parseFloat(process.env.NEX_SAFETY_MARGIN)||.1,Pp=parseInt(process.env.NEX_KEEP_RECENT,10)||10,Lp={essential:.6,standard:.65,full:Math.min(go,.75)};function Ip(){if(process.env.NEX_COMPRESSION_THRESHOLD)return go;try{let{getActiveTier:t}=co(),e=t();return Lp[e]??go}catch{return go}}var xx=200,kx=1e3;function Dp(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(`
179
+ `)}Op.exports={compactMessages:px,formatMessagesForSummary:Ap,resetCompactionFailures:hx,COMPACTION_ENABLED:Ep,COMPACTION_MIN_MESSAGES:Tp,COMPACTION_SUMMARY_BUDGET:Rp,MAX_CONSECUTIVE_FAILURES:Cp}});var Jt=z((CR,Bp)=>{var mx=require("path");function Mp(){return Ze().getActiveModel()}var gx={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},yx={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},Wn=new Map,Np=1e3,Sl=new WeakMap,Hn=null;function wx(){if(Hn!==null)return Hn;try{let t=Mp(),e=t?.provider||"ollama",s=(t?.id||"").toLowerCase();for(let[n,o]of Object.entries(yx))if(s.startsWith(n))return Hn=o,Hn;return Hn=gx[e]||4,Hn}catch{return 4}}function _x(){Hn=null}function Yn(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=Wn.get(e);if(s!==void 0)return Wn.delete(e),Wn.set(e,s),s;let n=Math.ceil(t.length/wx());if(Wn.size>=Np){let o=Np>>1,r=Wn.keys();for(let i=0;i<o;i++)Wn.delete(r.next().value)}return Wn.set(e,n),n}function $x(t){if(Sl.has(t))return Sl.get(t);let e=JSON.stringify(t);return Sl.set(t,e),e}function Gn(t){let s=4;if(t.content&&(s+=Yn(t.content)),t.tool_calls)for(let n of t.tool_calls){s+=4,s+=Yn(n.function?.name||"");let o=n.function?.arguments;typeof o=="string"?s+=Yn(o):o&&(s+=Yn(JSON.stringify(o)))}return s}function qt(t){let e=0;for(let s of t)e+=Gn(s);return e}function bx(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+=Gn(e[r]);return o}var vl=new WeakMap;function Vr(t){if(!t||t.length===0)return 0;if(vl.has(t))return vl.get(t);let e=Yn(JSON.stringify(t));return vl.set(t,e),e}function Jr(){return Mp()?.contextWindow||32768}var dt={msgCount:-1,lastMsgRef:null,toolCount:-1,result:null,messagesRef:null,messageTokens:0,systemTokens:0,conversationTokens:0,toolResultTokens:0};function xx(t,e){let s=t.length>0?t[t.length-1]:null,n=e?e.length:0;if(dt.result&&t.length===dt.msgCount&&s===dt.lastMsgRef&&n===dt.toolCount)return dt.result;let o,r,i,a;if(dt.messagesRef===t&&t.length>dt.msgCount&&dt.msgCount>=0){o=dt.messageTokens,r=dt.systemTokens,i=dt.conversationTokens,a=dt.toolResultTokens;for(let p=dt.msgCount;p<t.length;p++){let h=Gn(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=Gn(p);o+=h,p.role==="system"?r+=h:p.role==="tool"?a+=h:i+=h}}let l=Vr(e),c=o+l,u=Jr(),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 dt={msgCount:t.length,lastMsgRef:s,toolCount:n,result:f,messagesRef:t,messageTokens:o,systemTokens:r,conversationTokens:i,toolResultTokens:a},f}var go=parseFloat(process.env.NEX_COMPRESSION_THRESHOLD)||.75,Pp=parseFloat(process.env.NEX_SAFETY_MARGIN)||.1,Lp=parseInt(process.env.NEX_KEEP_RECENT,10)||10,Ip={essential:.6,standard:.65,full:Math.min(go,.75)};function Dp(){if(process.env.NEX_COMPRESSION_THRESHOLD)return go;try{let{getActiveTier:t}=co(),e=t();return Ip[e]??go}catch{return go}}var kx=200,Sx=1e3;function jp(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(`
180
180
  `);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 _+`
181
181
  ...(${t.length} chars total)...
182
182
  `+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(`
183
183
  `)+`
184
184
  ...(${p} lines omitted, ${o.length} total)...
185
185
  `+u.join(`
186
- `)}function Os(t,e="light"){let s=e==="aggressive"?100:e==="medium"?200:kx,n=e==="aggressive"?50:e==="medium"?100:xx;if(t.role==="tool"){let o=typeof t.content=="string"?t.content:JSON.stringify(t.content);return o.length>n?{...t,content:Dp(o,n)}:t}if(t.role==="assistant"){let o={...t};return o.content&&o.content.length>s&&(o.content=o.content.substring(0,s)+`
187
- ...(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(hx.basename(l)))&&a++;o+=Math.min(30,a*10)}return Math.min(100,o)}function qp(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 Sx(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:
186
+ `)}function Os(t,e="light"){let s=e==="aggressive"?100:e==="medium"?200:Sx,n=e==="aggressive"?50:e==="medium"?100:kx;if(t.role==="tool"){let o=typeof t.content=="string"?t.content:JSON.stringify(t.content);return o.length>n?{...t,content:jp(o,n)}:t}if(t.role==="assistant"){let o={...t};return o.content&&o.content.length>s&&(o.content=o.content.substring(0,s)+`
187
+ ...(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 qp(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(mx.basename(l)))&&a++;o+=Math.min(30,a*10)}return Math.min(100,o)}function Fp(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 vx(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:
188
188
  `+o.map(r=>`- ${r}`).join(`
189
189
  `)),n.length===0?null:{role:"system",content:`## Progress State (preserved through compression)
190
190
  ${n.join(`
191
- `)}`,_pinned:!0,_progressSnapshot:!0}}var As={msgCount:-1,lastMsgRef:null,result:null};function vx(){As={msgCount:-1,lastMsgRef:null,result:null},lt={msgCount:-1,lastMsgRef:null,toolCount:-1,result:null,messagesRef:null,messageTokens:0,systemTokens:0,conversationTokens:0,toolResultTokens:0}}async function Ex(t,e,s={}){let n=t.length>0?t[t.length-1]:null;if(!s.force&&As.result&&t.length===As.msgCount&&n===As.lastMsgRef)return As.result;let o=s.threshold??Ip(),r=s.safetyMargin??Mp,i=s.keepRecent??Pp,a=Vr(),l=Xr(e),c=Math.floor(a*(o-r)),u=c-l,d=Pt(t);if(d+l<=c){let ne={messages:t,compressed:!1,compacted:!1,tokensRemoved:0};return As={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=>Os(ne,"light")),k=_n(h,M,O),E=Pt(k);if(E+l<=c)return{messages:k,compressed:!0,compacted:!1,tokensRemoved:p-E};if(M=b.map(ne=>Os(ne,"medium")),k=_n(h,M,O),E=Pt(k),E+l<=c)return{messages:k,compressed:!0,compacted:!1,tokensRemoved:p-E};if(M=b.map(ne=>Os(ne,"aggressive")),k=_n(h,M,O),E=Pt(k),E+l<=c)return{messages:k,compressed:!0,compacted:!1,tokensRemoved:p-E};let N=process.env.NEX_SKIP_COMPACTOR==="1",ee=b.filter(ne=>ne._pinned),X=b.filter(ne=>!ne._compacted&&!ne._pinned);if(!N&&X.length>=6)try{let{compactMessages:ne}=bl(),S=await ne(X);if(S){let Te=b.filter(ve=>ve._compacted&&!ve._pinned),H=[...ee,...Te,S.message],K=_n(h,H,O),pe=Pt(K);if(pe+l<=c)return{messages:K,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 ce=qp([...M,...O]),ae=M.map((ne,S)=>({msg:ne,score:ne._pinned?1/0:jp(ne,S,M.length,ce),tokens:Hn(ne)}));for(;ae.length>0&&E>u;){let ne=-1;for(let S=0;S<ae.length;S++)ae[S].score!==1/0&&(ne===-1||ae[S].score<ae[ne].score)&&(ne=S);if(ne===-1)break;E-=ae[ne].tokens,ae.splice(ne,1)}return M=ae.map(ne=>ne.msg),k=_n(h,M,O),E=Pt(k),{messages:k,compressed:!0,compacted:!1,tokensRemoved:p-E}}function _n(t,e,s){let n=[];return t&&n.push(t),n.push(...e,...s),n}function Tx(t,e){if(!t)return"";if(Wn(t)<=e)return t;let n=e*4,o=t.split(`
191
+ `)}`,_pinned:!0,_progressSnapshot:!0}}var As={msgCount:-1,lastMsgRef:null,result:null};function Ex(){As={msgCount:-1,lastMsgRef:null,result:null},dt={msgCount:-1,lastMsgRef:null,toolCount:-1,result:null,messagesRef:null,messageTokens:0,systemTokens:0,conversationTokens:0,toolResultTokens:0}}async function Tx(t,e,s={}){let n=t.length>0?t[t.length-1]:null;if(!s.force&&As.result&&t.length===As.msgCount&&n===As.lastMsgRef)return As.result;let o=s.threshold??Dp(),r=s.safetyMargin??Pp,i=s.keepRecent??Lp,a=Jr(),l=Vr(e),c=Math.floor(a*(o-r)),u=c-l,d=qt(t);if(d+l<=c){let se={messages:t,compressed:!1,compacted:!1,tokensRemoved:0};return As={msgCount:t.length,lastMsgRef:n,result:se},se}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(se=>Os(se,"light")),k=bn(h,M,O),E=qt(k);if(E+l<=c)return{messages:k,compressed:!0,compacted:!1,tokensRemoved:p-E};if(M=b.map(se=>Os(se,"medium")),k=bn(h,M,O),E=qt(k),E+l<=c)return{messages:k,compressed:!0,compacted:!1,tokensRemoved:p-E};if(M=b.map(se=>Os(se,"aggressive")),k=bn(h,M,O),E=qt(k),E+l<=c)return{messages:k,compressed:!0,compacted:!1,tokensRemoved:p-E};let N=process.env.NEX_SKIP_COMPACTOR==="1",te=b.filter(se=>se._pinned),X=b.filter(se=>!se._compacted&&!se._pinned);if(!N&&X.length>=6)try{let{compactMessages:se}=kl(),S=await se(X);if(S){let Re=b.filter(ve=>ve._compacted&&!ve._pinned),H=[...te,...Re,S.message],K=bn(h,H,O),pe=qt(K);if(pe+l<=c)return{messages:K,compressed:!0,compacted:!0,tokensRemoved:p-pe};b=H}}catch(se){process.env.NEX_DEBUG&&console.error("[context-engine] LLM compacting failed:",se.message)}let ce=Fp([...M,...O]),ae=M.map((se,S)=>({msg:se,score:se._pinned?1/0:qp(se,S,M.length,ce),tokens:Gn(se)}));for(;ae.length>0&&E>u;){let se=-1;for(let S=0;S<ae.length;S++)ae[S].score!==1/0&&(se===-1||ae[S].score<ae[se].score)&&(se=S);if(se===-1)break;E-=ae[se].tokens,ae.splice(se,1)}return M=ae.map(se=>se.msg),k=bn(h,M,O),E=qt(k),{messages:k,compressed:!0,compacted:!1,tokensRemoved:p-E}}function bn(t,e,s){let n=[];return t&&n.push(t),n.push(...e,...s),n}function Rx(t,e){if(!t)return"";if(Yn(t)<=e)return t;let n=e*4,o=t.split(`
192
192
  `),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?`
193
193
  `:"")+p,l++}let c="",u=0;for(let p=o.length-1;p>=l;p--){let h=o[p]+(c?`
194
194
  `:"")+c;if(h.length>i)break;c=h,u++}let f=`
195
195
 
196
196
  ... (${o.length-l-u} lines omitted, ${o.length} total) ...
197
197
 
198
- `;return a+f+c}var Rx=6;function Cx(t,e,s=!1){let n=Vr(),o=Xr(e),r=Math.floor(n*(s?.35:.5))-o,i=Pt(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:Rx,d=Math.max(c,t.length-u),f=t.slice(c,d),p=t.slice(d),h=f.map(E=>Os(E,"aggressive"));s&&(p=p.map(E=>Os(E,"aggressive")));let g=_n(l,h,p),_=Pt(g);for(;h.length>0&&_>r;){let E=h.shift();_-=Hn(E)}s&&_>r&&(p=p.filter(N=>N.role==="user").slice(-1),g=_n(l,[],p),_=Pt(g)),g=_n(l,h,p);let b=t.filter(E=>E.role==="user"),O=E=>{let N=typeof E.content=="string"?E.content:"";return N.startsWith("[SYSTEM WARNING]")||N.startsWith("[SYSTEM:")||N.startsWith("BLOCKED:")},M=b.find(E=>!O(E)),k=[...b].reverse().find(E=>!O(E));if(M&&!g.find(E=>E===M)){let E=g.findIndex(ee=>ee.role==="system"),N=E>=0?E+1:0;g.splice(N,0,M)}return k&&k!==M&&!g.find(E=>E===k)&&g.push(k),{messages:g,tokensRemoved:i-Pt(g)}}Fp.exports={estimateTokens:Wn,estimateMessageTokens:Hn,estimateMessagesTokens:Pt,estimateDeltaTokens:$x,estimateToolsTokens:Xr,serializeMessage:_x,getContextWindow:Vr,getUsage:bx,compressMessage:Os,compressToolResult:Dp,scoreMessageRelevance:jp,extractActiveFiles:qp,buildProgressSnapshot:Sx,fitToContext:Ex,forceCompress:Cx,truncateFileContent:Tx,invalidateTokenRatioCache:wx,invalidateFitToContextCache:vx,getEffectiveCompressionThreshold:Ip,COMPRESSION_THRESHOLD:go,TIER_COMPRESSION_THRESHOLDS:Lp,SAFETY_MARGIN:Mp,KEEP_RECENT:Pp}});var Tl=z((AR,lh)=>{var{callStream:Ax,getActiveProviderName:Zr,getActiveModelId:Bp,getConfiguredProviders:Ox,getProvider:Up,getActiveProvider:Wp,parseModelSpec:Hp}=Ve(),{parseToolArgs:Yp}=Zs(),{filterToolsForModel:Nx,getModelTier:Jr}=co(),{getModelBriefing:Mx}=Kr(),{trackUsage:Gp,estimateTokens:zp}=kr(),{MultiProgress:Px,C:CR}=ze();function Kp(t){return!t||typeof t!="string"?0:typeof zp=="function"?zp(t):Math.ceil(t.length/4)}var Jp=15,Lx=parseInt(process.env.NEX_MAX_PARALLEL||"5",10),Xp=parseInt(process.env.NEX_MAX_CHAT_RETRIES||"3",10),Zp=8,Ix=2,Qr=new Map,Qp=600*1e3;function Dx(t,e){let s=Qr.get(t);return s&&s.agentId!==e&&Date.now()-s.timestamp<Qp?!1:(Qr.set(t,{agentId:e,timestamp:Date.now()}),!0)}function yo(t){Qr.delete(t)}function Sl(){Qr.clear()}function vl(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 eh(t){let e=vl(t);return e==="rate_limit"||e==="server"||e==="network"||e==="timeout"}async function th(t,e,s){let n;for(let o=0;o<=Xp;o++)try{return await Ax(t,e,s)}catch(r){n=r;let i=vl(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<Xp&&eh(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 Vp=new Set(["ask_user","task_list"]);function nh(t){return t>=2?new Set([...Vp,"spawn_agents"]):Vp}var jx=new Set(["write_file","edit_file","patch_file"]),sh={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:""}},qx=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,Fx=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function oh(t){return Fx.test(t)?"full":qx.test(t)?"essential":t.length>300?"full":"standard"}function rh(t){let e=Ox(),s=Zr(),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(Jr(r.id,o.name)===t)return{provider:o.name,model:r.id};return null}var Bx={essential:process.env.NEX_FAST_MODEL||null,standard:process.env.NEX_STANDARD_MODEL||null,full:process.env.NEX_HEAVY_MODEL||null};function El(t){if(t.model){let{provider:o,model:r}=Hp(t.model),i=o?Up(o):Wp(),a=o||Zr();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let l=Jr(r,a);return{provider:a,model:r,tier:l}}}let e=oh(t.task),s=Bx[e];if(s){let{provider:o,model:r}=Hp(s),i=o?Up(o):Wp(),a=o||Zr();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let l=Jr(r,a);return{provider:a,model:r,tier:l}}}let n=rh(e);if(n){let o=Jr(n.model,n.provider);return{provider:n.provider,model:n.model,tier:o}}return{provider:null,model:null,tier:null}}async function ih(t,e={},s=0){let n=s===0?Jp:Zp,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.
198
+ `;return a+f+c}var Cx=6;function Ax(t,e,s=!1){let n=Jr(),o=Vr(e),r=Math.floor(n*(s?.35:.5))-o,i=qt(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:Cx,d=Math.max(c,t.length-u),f=t.slice(c,d),p=t.slice(d),h=f.map(E=>Os(E,"aggressive"));s&&(p=p.map(E=>Os(E,"aggressive")));let g=bn(l,h,p),_=qt(g);for(;h.length>0&&_>r;){let E=h.shift();_-=Gn(E)}s&&_>r&&(p=p.filter(N=>N.role==="user").slice(-1),g=bn(l,[],p),_=qt(g)),g=bn(l,h,p);let b=t.filter(E=>E.role==="user"),O=E=>{let N=typeof E.content=="string"?E.content:"";return N.startsWith("[SYSTEM WARNING]")||N.startsWith("[SYSTEM:")||N.startsWith("BLOCKED:")},M=b.find(E=>!O(E)),k=[...b].reverse().find(E=>!O(E));if(M&&!g.find(E=>E===M)){let E=g.findIndex(te=>te.role==="system"),N=E>=0?E+1:0;g.splice(N,0,M)}return k&&k!==M&&!g.find(E=>E===k)&&g.push(k),{messages:g,tokensRemoved:i-qt(g)}}Bp.exports={estimateTokens:Yn,estimateMessageTokens:Gn,estimateMessagesTokens:qt,estimateDeltaTokens:bx,estimateToolsTokens:Vr,serializeMessage:$x,getContextWindow:Jr,getUsage:xx,compressMessage:Os,compressToolResult:jp,scoreMessageRelevance:qp,extractActiveFiles:Fp,buildProgressSnapshot:vx,fitToContext:Tx,forceCompress:Ax,truncateFileContent:Rx,invalidateTokenRatioCache:_x,invalidateFitToContextCache:Ex,getEffectiveCompressionThreshold:Dp,COMPRESSION_THRESHOLD:go,TIER_COMPRESSION_THRESHOLDS:Ip,SAFETY_MARGIN:Pp,KEEP_RECENT:Lp}});var Cl=z((OR,ch)=>{var{callStream:Ox,getActiveProviderName:Qr,getActiveModelId:Up,getConfiguredProviders:Nx,getProvider:Wp,getActiveProvider:Hp,parseModelSpec:Yp}=Ze(),{parseToolArgs:Gp}=Zs(),{filterToolsForModel:Mx,getModelTier:Zr}=co(),{getModelBriefing:Px}=Xr(),{trackUsage:zp,estimateTokens:Kp}=Sr(),{MultiProgress:Lx,C:AR}=Ke();function Xp(t){return!t||typeof t!="string"?0:typeof Kp=="function"?Kp(t):Math.ceil(t.length/4)}var Zp=15,Ix=parseInt(process.env.NEX_MAX_PARALLEL||"5",10),Vp=parseInt(process.env.NEX_MAX_CHAT_RETRIES||"3",10),Qp=8,Dx=2,ei=new Map,eh=600*1e3;function jx(t,e){let s=ei.get(t);return s&&s.agentId!==e&&Date.now()-s.timestamp<eh?!1:(ei.set(t,{agentId:e,timestamp:Date.now()}),!0)}function yo(t){ei.delete(t)}function El(){ei.clear()}function Tl(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 th(t){let e=Tl(t);return e==="rate_limit"||e==="server"||e==="network"||e==="timeout"}async function nh(t,e,s){let n;for(let o=0;o<=Vp;o++)try{return await Ox(t,e,s)}catch(r){n=r;let i=Tl(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<Vp&&th(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 Jp=new Set(["ask_user","task_list"]);function sh(t){return t>=2?new Set([...Jp,"spawn_agents"]):Jp}var qx=new Set(["write_file","edit_file","patch_file"]),oh={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:""}},Fx=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,Bx=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function rh(t){return Bx.test(t)?"full":Fx.test(t)?"essential":t.length>300?"full":"standard"}function ih(t){let e=Nx(),s=Qr(),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(Zr(r.id,o.name)===t)return{provider:o.name,model:r.id};return null}var Ux={essential:process.env.NEX_FAST_MODEL||null,standard:process.env.NEX_STANDARD_MODEL||null,full:process.env.NEX_HEAVY_MODEL||null};function Rl(t){if(t.model){let{provider:o,model:r}=Yp(t.model),i=o?Wp(o):Hp(),a=o||Qr();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let l=Zr(r,a);return{provider:a,model:r,tier:l}}}let e=rh(t.task),s=Ux[e];if(s){let{provider:o,model:r}=Yp(s),i=o?Wp(o):Hp(),a=o||Qr();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let l=Zr(r,a);return{provider:a,model:r,tier:l}}}let n=ih(e);if(n){let o=Zr(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?Zp:Qp,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.
199
199
 
200
200
  TASK: ${t.task}
201
201
  ${t.context?`
@@ -217,25 +217,25 @@ TOOL STRATEGY:
217
217
  ERROR RECOVERY:
218
218
  - If edit_file fails with "old_text not found": read the file again, compare, and retry with exact text.
219
219
  - If bash fails: read the error, fix the root cause, then retry.
220
- - After 2 failed attempts at the same operation, summarize the issue and stop.`,d=t.type&&sh[t.type],f=d&&d.systemSuffix?`
220
+ - After 2 failed attempts at the same operation, summarize the issue and stop.`,d=t.type&&oh[t.type],f=d&&d.systemSuffix?`
221
221
 
222
- ${d.systemSuffix}`:"",p=El(t),h=p.provider,g=p.model,_=p.tier,b=Mx(g||Bp()),M=[{role:"system",content:(b?`## Model Briefing
222
+ ${d.systemSuffix}`:"",p=Rl(t),h=p.provider,g=p.model,_=p.tier,b=Px(g||Up()),M=[{role:"system",content:(b?`## Model Briefing
223
223
  ${b}
224
224
 
225
225
  ---
226
226
 
227
- `:"")+u+f}];M.push({role:"user",content:t.task});let{TOOL_DEFINITIONS:k,executeTool:E}=ks(),N=nh(s),ee=Nx(k.filter(ae=>!N.has(ae.function.name)),_);if(d&&d.allowedTools&&(ee=ee.filter(ae=>d.allowedTools.has(ae.function.name))),g&&!t._skipLog){let ae=_?` (${_})`:"";process.stderr.write(` [sub-agent: ${h}:${g}${ae}]
228
- `)}let X={};h&&(X.provider=h),g&&(X.model=g);let ce=new Set;try{for(let ne=0;ne<o;ne++){let S=await th(M,ee,X);if(!S||typeof S!="object")throw new Error("Empty or invalid response from provider");{let $e=h||Zr(),ye=g||Bp();if(S.usage){let $=S.usage.prompt_tokens||0,P=S.usage.completion_tokens||0;a.input+=$,a.output+=P,Gp($e,ye,$,P)}else{let $=S.content||"",P=M.map(T=>typeof T.content=="string"?T.content:Array.isArray(T.content)?T.content.map(x=>typeof x=="string"?x:x.text||"").join(""):"").join(" "),R=Kp(P),B=Kp($);a.input+=R,a.output+=B,a._estimated=!0,Gp($e,ye,R,B)}}let Te=S.content||"",H=S.tool_calls,K={role:"assistant",content:Te||""};if(H&&H.length>0&&(K.tool_calls=H),M.push(K),!H||H.length===0){for(let $e of l)yo($e);return{task:t.task,status:"done",result:Te||"(no response)",toolsUsed:i,tokensUsed:a,modelSpec:h&&g?`${h}:${g}`:null}}let pe=new Set,ve=H.map($e=>{let ye=$e.function.name,$=Yp($e.function.arguments),P=$e.id||`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!$)return Promise.resolve({role:"tool",content:`ERROR: Malformed tool arguments for ${ye}`,tool_call_id:P});if(["edit_file","patch_file"].includes(ye)&&$.path){if(ce.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:P});pe.add($.path)}let R=null;if(jx.has(ye)&&$.path){let T=require("path"),x=T.isAbsolute($.path)?$.path:T.resolve(process.cwd(),$.path);if(t._readOnlyFiles&&t._readOnlyFiles.length>0){let se=T.relative(process.cwd(),x);if(t._readOnlyFiles.some(ge=>se===ge||se.startsWith(ge+"/")||x===ge||x.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:P})}if(l.has(x)||!Dx(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:P});l.add(x),R=x}return i.push(ye),e.onUpdate&&e.onUpdate({type:"tool_call",tool:ye,agentId:r}),(ye==="spawn_agents"?ah($,s+1):E(ye,$,{autoConfirm:!0,silent:!0})).then(T=>{R&&(yo(R),l.delete(R));let x=String(T??"");return $&&$.path&&(["edit_file","patch_file","write_file"].includes(ye)&&x.startsWith("Edited:")?ce.add($.path):ye==="read_file"&&!x.startsWith("ERROR")&&ce.delete($.path)),{role:"tool",content:x.length>2e4?x.substring(0,2e4)+`
229
- ...(truncated)`:x,tool_call_id:P}}).catch(T=>(R&&(yo(R),l.delete(R)),{role:"tool",content:`ERROR: ${T.message}`,tool_call_id:P}))}),Be=await Promise.all(ve);if(M.push(...Be),ne>=7&&M.length>12)try{let{compressMessage:$e}=Kt(),ye=M.length-6;for(let $=1;$<ye;$++)M[$]._subAgentCompressed||(M[$]={...$e(M[$],"light"),_subAgentCompressed:!0})}catch{}for(let $e=0;$e<H.length;$e++){let ye=H[$e];if(ye.function.name==="bash_exec"){let $=Yp(ye.function.arguments);if((Be[$e]?.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)yo(ne);let ae=[...c.entries()].filter(([,ne])=>ne>=3).sort((ne,S)=>S[1]-ne[1]).slice(0,3).map(([ne,S])=>`"${ne}" (failed ${S}\xD7)`);return{task:t.task,status:"truncated",abortReason:"iteration_limit",repeatedFailures:ae,result:M[M.length-1]?.content||"(max iterations reached)",toolsUsed:i,tokensUsed:a,modelSpec:h&&g?`${h}:${g}`:null}}catch(ae){for(let ne of l)yo(ne);return{task:t.task,status:"failed",result:`Error: ${ae.message}`,toolsUsed:i,tokensUsed:a,modelSpec:h&&g?`${h}:${g}`:null}}}async function ah(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?Lx:Ix,n=e===0?Jp:Zp,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=>El(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 Px(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 ih(M,{onUpdate:()=>{}},e).then(k=>(c.update(_,k.status==="failed"?"error":"done"),k)).catch(k=>(c.update(_,"error"),{task:g.task,status:"failed",result:`Error: ${k.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}))}),d=await Promise.all(u);c.stop(),Sl();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(`
230
- `)}catch(u){return c.stop(),Sl(),`ERROR: Sub-agent execution failed: ${u.message}`}}lh.exports={runSubAgent:ih,executeSpawnAgents:ah,clearAllLocks:Sl,classifyTask:oh,pickModelForTier:rh,resolveSubAgentModel:El,classifyError:vl,isRetryableError:eh,callWithRetry:th,getExcludedTools:nh,LOCK_TIMEOUT_MS:Qp,SUB_AGENT_TYPES:sh}});var Ll=z((OR,xh)=>{var je=require("fs"),cn=require("path"),{atomicWrite:ch,withFileLockSync:uh}=Pn(),Ux=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 Ms(){let t=cn.join(process.cwd(),".nex","brain");return je.existsSync(t)||je.mkdirSync(t,{recursive:!0}),t}function ti(){return cn.join(Ms(),".brain-index.json")}function Al(){return cn.join(Ms(),".embeddings.json")}function wo(){let t=cn.join(process.cwd(),".nex","brain");if(!je.existsSync(t))return[];try{return je.readdirSync(t).filter(e=>e.endsWith(".md")&&!e.startsWith(".")).map(e=>{let s=cn.join(t,e),n=je.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 _o(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(`
231
- `);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 dh(t){let e=cn.join(Ms(),`${t}.md`);if(!je.existsSync(e))return{name:t,content:"",body:"",frontmatter:{}};let s=je.readFileSync(e,"utf-8"),{frontmatter:n,body:o}=_o(s);return{name:t,content:s,body:o,frontmatter:n}}function Wx(t,e){let s=cn.join(Ms(),`${t}.md`);ch(s,e),Gx(t,e),Hx()}function Hx(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return;let t=Al();je.existsSync(t)&&setImmediate(async()=>{try{await wh()}catch{}})}function Yx(t){let e=cn.join(Ms(),`${t}.md`);return je.existsSync(e)?(je.unlinkSync(e),zx(t),!0):!1}function ei(t){return t.toLowerCase().replace(/[^a-z0-9äöüß\s-]/g," ").split(/[\s-]+/).filter(e=>e.length>2&&!Ux.has(e))}function Ol(t){let e={},{frontmatter:s,body:n}=_o(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(`
232
- `);for(let i of r)if(i.startsWith("#")){let a=i.replace(/^#+\s*/,"");for(let l of ei(a))e[l]=(e[l]||0)+3}for(let i of ei(n||t))e[i]=(e[i]||0)+1;return e}function Nl(){let t=ti();if(!je.existsSync(t))return{documents:{}};try{return JSON.parse(je.readFileSync(t,"utf-8"))}catch{return{documents:{}}}}function Ml(t){ch(ti(),JSON.stringify(t,null,2))}function Gx(t,e){uh(ti(),()=>{let s=Nl(),{frontmatter:n}=_o(e),o=Array.isArray(n.tags)?n.tags:[];s.documents[t]={keywords:Ol(e),tags:o,modified:new Date().toISOString()},Ml(s)})}function zx(t){uh(ti(),()=>{let e=Nl();delete e.documents[t],Ml(e)})}function Cl(){let t=wo(),e={documents:{}};for(let s of t){let n=je.readFileSync(s.path,"utf-8"),{frontmatter:o}=_o(n),r=Array.isArray(o.tags)?o.tags:[];e.documents[s.name]={keywords:Ol(n),tags:r,modified:s.modified.toISOString()}}return Ml(e),e}function fh(){let t=Nl(),e=wo();for(let s of e){let n=t.documents[s.name];if(!n||new Date(n.modified)<s.modified)return Cl()}for(let s of Object.keys(t.documents))if(!e.some(n=>n.name===s))return Cl();return t}function ph(t,e={}){let{topK:s=3,minScore:n=.1}=e,o=ei(t);if(o.length===0)return[];let r=fh(),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 hh=process.env.NEX_EMBED_MODEL||"nomic-embed-text",Rl=400,Kx=50;async function mh(){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(hh.split(":")[0]))}catch{return!1}}async function Pl(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:hh,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 gh(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 yh(t){let e=t.split(/\s+/),s=[],n=0;for(;n<e.length;){let o=e.slice(n,n+Rl).join(" ");if(s.push({text:o,offset:n}),n+Rl>=e.length)break;n+=Rl-Kx}return s}async function wh(){let t=wo(),e={documents:{}},s=Al();if(je.existsSync(s))try{e=JSON.parse(je.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=je.readFileSync(n.path,"utf-8"),i=yh(r),a=[];for(let l of i){let c=await Pl(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 je.writeFileSync(s,JSON.stringify(e),"utf-8"),e}async function _h(t,e={}){let{topK:s=3,minSimilarity:n=.3}=e,o=Al();if(!je.existsSync(o))return[];let r;try{r=JSON.parse(je.readFileSync(o,"utf-8"))}catch{return[]}let i=await Pl(t),a=[];for(let[l,c]of Object.entries(r.documents||{})){let u=0,d="";for(let f of c.chunks||[]){let p=gh(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 $h(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 bh(t,e={}){let{topK:s=3,minScore:n=.1}=e,o=ph(t,{topK:s,minScore:n}),r=o;if(process.env.NEX_BRAIN_EMBEDDINGS!=="false")try{if(await mh()){let a=await _h(t,{topK:s});r=$h(o,a,{topK:s})}}catch{}return r.map(i=>{let a=dh(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 Ns={queryKey:null,result:null,ts:0},Xx=3e5;async function Vx(t){if(!t||!t.trim())return"";let e=cn.join(process.cwd(),".nex","brain");if(!je.existsSync(e)||wo().length===0)return"";let n=t.trim().toLowerCase().slice(0,200);if(Ns.result!==null&&Ns.queryKey===n&&Date.now()-Ns.ts<Xx)return Ns.result;let o;try{o=await bh(t,{topK:3})}catch{return""}if(!o||o.length===0)return"";let r;try{r=Kt().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))+`
227
+ `:"")+u+f}];M.push({role:"user",content:t.task});let{TOOL_DEFINITIONS:k,executeTool:E}=ks(),N=sh(s),te=Mx(k.filter(ae=>!N.has(ae.function.name)),_);if(d&&d.allowedTools&&(te=te.filter(ae=>d.allowedTools.has(ae.function.name))),g&&!t._skipLog){let ae=_?` (${_})`:"";process.stderr.write(` [sub-agent: ${h}:${g}${ae}]
228
+ `)}let X={};h&&(X.provider=h),g&&(X.model=g);let ce=new Set;try{for(let se=0;se<o;se++){let S=await nh(M,te,X);if(!S||typeof S!="object")throw new Error("Empty or invalid response from provider");{let $e=h||Qr(),ye=g||Up();if(S.usage){let $=S.usage.prompt_tokens||0,P=S.usage.completion_tokens||0;a.input+=$,a.output+=P,zp($e,ye,$,P)}else{let $=S.content||"",P=M.map(T=>typeof T.content=="string"?T.content:Array.isArray(T.content)?T.content.map(x=>typeof x=="string"?x:x.text||"").join(""):"").join(" "),R=Xp(P),B=Xp($);a.input+=R,a.output+=B,a._estimated=!0,zp($e,ye,R,B)}}let Re=S.content||"",H=S.tool_calls,K={role:"assistant",content:Re||""};if(H&&H.length>0&&(K.tool_calls=H),M.push(K),!H||H.length===0){for(let $e of l)yo($e);return{task:t.task,status:"done",result:Re||"(no response)",toolsUsed:i,tokensUsed:a,modelSpec:h&&g?`${h}:${g}`:null}}let pe=new Set,ve=H.map($e=>{let ye=$e.function.name,$=Gp($e.function.arguments),P=$e.id||`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!$)return Promise.resolve({role:"tool",content:`ERROR: Malformed tool arguments for ${ye}`,tool_call_id:P});if(["edit_file","patch_file"].includes(ye)&&$.path){if(ce.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:P});pe.add($.path)}let R=null;if(qx.has(ye)&&$.path){let T=require("path"),x=T.isAbsolute($.path)?$.path:T.resolve(process.cwd(),$.path);if(t._readOnlyFiles&&t._readOnlyFiles.length>0){let oe=T.relative(process.cwd(),x);if(t._readOnlyFiles.some(ge=>oe===ge||oe.startsWith(ge+"/")||x===ge||x.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:P})}if(l.has(x)||!jx(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:P});l.add(x),R=x}return i.push(ye),e.onUpdate&&e.onUpdate({type:"tool_call",tool:ye,agentId:r}),(ye==="spawn_agents"?lh($,s+1):E(ye,$,{autoConfirm:!0,silent:!0})).then(T=>{R&&(yo(R),l.delete(R));let x=String(T??"");return $&&$.path&&(["edit_file","patch_file","write_file"].includes(ye)&&x.startsWith("Edited:")?ce.add($.path):ye==="read_file"&&!x.startsWith("ERROR")&&ce.delete($.path)),{role:"tool",content:x.length>2e4?x.substring(0,2e4)+`
229
+ ...(truncated)`:x,tool_call_id:P}}).catch(T=>(R&&(yo(R),l.delete(R)),{role:"tool",content:`ERROR: ${T.message}`,tool_call_id:P}))}),Ue=await Promise.all(ve);if(M.push(...Ue),se>=7&&M.length>12)try{let{compressMessage:$e}=Jt(),ye=M.length-6;for(let $=1;$<ye;$++)M[$]._subAgentCompressed||(M[$]={...$e(M[$],"light"),_subAgentCompressed:!0})}catch{}for(let $e=0;$e<H.length;$e++){let ye=H[$e];if(ye.function.name==="bash_exec"){let $=Gp(ye.function.arguments);if((Ue[$e]?.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 ${se+1}/${o}`)}for(let se of l)yo(se);let ae=[...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:ae,result:M[M.length-1]?.content||"(max iterations reached)",toolsUsed:i,tokensUsed:a,modelSpec:h&&g?`${h}:${g}`:null}}catch(ae){for(let se of l)yo(se);return{task:t.task,status:"failed",result:`Error: ${ae.message}`,toolsUsed:i,tokensUsed:a,modelSpec:h&&g?`${h}:${g}`:null}}}async function lh(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?Ix:Dx,n=e===0?Zp:Qp,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=>Rl(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 Lx(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 ah(M,{onUpdate:()=>{}},e).then(k=>(c.update(_,k.status==="failed"?"error":"done"),k)).catch(k=>(c.update(_,"error"),{task:g.task,status:"failed",result:`Error: ${k.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}))}),d=await Promise.all(u);c.stop(),El();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(`
230
+ `)}catch(u){return c.stop(),El(),`ERROR: Sub-agent execution failed: ${u.message}`}}ch.exports={runSubAgent:ah,executeSpawnAgents:lh,clearAllLocks:El,classifyTask:rh,pickModelForTier:ih,resolveSubAgentModel:Rl,classifyError:Tl,isRetryableError:th,callWithRetry:nh,getExcludedTools:sh,LOCK_TIMEOUT_MS:eh,SUB_AGENT_TYPES:oh}});var Dl=z((NR,kh)=>{var qe=require("fs"),un=require("path"),{atomicWrite:uh,withFileLockSync:dh}=In(),Wx=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 Ms(){let t=un.join(process.cwd(),".nex","brain");return qe.existsSync(t)||qe.mkdirSync(t,{recursive:!0}),t}function ni(){return un.join(Ms(),".brain-index.json")}function Nl(){return un.join(Ms(),".embeddings.json")}function wo(){let t=un.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=un.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 _o(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(`
231
+ `);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 fh(t){let e=un.join(Ms(),`${t}.md`);if(!qe.existsSync(e))return{name:t,content:"",body:"",frontmatter:{}};let s=qe.readFileSync(e,"utf-8"),{frontmatter:n,body:o}=_o(s);return{name:t,content:s,body:o,frontmatter:n}}function Hx(t,e){let s=un.join(Ms(),`${t}.md`);uh(s,e),zx(t,e),Yx()}function Yx(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return;let t=Nl();qe.existsSync(t)&&setImmediate(async()=>{try{await _h()}catch{}})}function Gx(t){let e=un.join(Ms(),`${t}.md`);return qe.existsSync(e)?(qe.unlinkSync(e),Kx(t),!0):!1}function ti(t){return t.toLowerCase().replace(/[^a-z0-9äöüß\s-]/g," ").split(/[\s-]+/).filter(e=>e.length>2&&!Wx.has(e))}function Ml(t){let e={},{frontmatter:s,body:n}=_o(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(`
232
+ `);for(let i of r)if(i.startsWith("#")){let a=i.replace(/^#+\s*/,"");for(let l of ti(a))e[l]=(e[l]||0)+3}for(let i of ti(n||t))e[i]=(e[i]||0)+1;return e}function Pl(){let t=ni();if(!qe.existsSync(t))return{documents:{}};try{return JSON.parse(qe.readFileSync(t,"utf-8"))}catch{return{documents:{}}}}function Ll(t){uh(ni(),JSON.stringify(t,null,2))}function zx(t,e){dh(ni(),()=>{let s=Pl(),{frontmatter:n}=_o(e),o=Array.isArray(n.tags)?n.tags:[];s.documents[t]={keywords:Ml(e),tags:o,modified:new Date().toISOString()},Ll(s)})}function Kx(t){dh(ni(),()=>{let e=Pl();delete e.documents[t],Ll(e)})}function Ol(){let t=wo(),e={documents:{}};for(let s of t){let n=qe.readFileSync(s.path,"utf-8"),{frontmatter:o}=_o(n),r=Array.isArray(o.tags)?o.tags:[];e.documents[s.name]={keywords:Ml(n),tags:r,modified:s.modified.toISOString()}}return Ll(e),e}function ph(){let t=Pl(),e=wo();for(let s of e){let n=t.documents[s.name];if(!n||new Date(n.modified)<s.modified)return Ol()}for(let s of Object.keys(t.documents))if(!e.some(n=>n.name===s))return Ol();return t}function hh(t,e={}){let{topK:s=3,minScore:n=.1}=e,o=ti(t);if(o.length===0)return[];let r=ph(),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 mh=process.env.NEX_EMBED_MODEL||"nomic-embed-text",Al=400,Xx=50;async function gh(){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(mh.split(":")[0]))}catch{return!1}}async function Il(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:mh,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 yh(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 wh(t){let e=t.split(/\s+/),s=[],n=0;for(;n<e.length;){let o=e.slice(n,n+Al).join(" ");if(s.push({text:o,offset:n}),n+Al>=e.length)break;n+=Al-Xx}return s}async function _h(){let t=wo(),e={documents:{}},s=Nl();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=wh(r),a=[];for(let l of i){let c=await Il(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 $h(t,e={}){let{topK:s=3,minSimilarity:n=.3}=e,o=Nl();if(!qe.existsSync(o))return[];let r;try{r=JSON.parse(qe.readFileSync(o,"utf-8"))}catch{return[]}let i=await Il(t),a=[];for(let[l,c]of Object.entries(r.documents||{})){let u=0,d="";for(let f of c.chunks||[]){let p=yh(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 bh(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 xh(t,e={}){let{topK:s=3,minScore:n=.1}=e,o=hh(t,{topK:s,minScore:n}),r=o;if(process.env.NEX_BRAIN_EMBEDDINGS!=="false")try{if(await gh()){let a=await $h(t,{topK:s});r=bh(o,a,{topK:s})}}catch{}return r.map(i=>{let a=fh(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 Ns={queryKey:null,result:null,ts:0},Vx=3e5;async function Jx(t){if(!t||!t.trim())return"";let e=un.join(process.cwd(),".nex","brain");if(!qe.existsSync(e)||wo().length===0)return"";let n=t.trim().toLowerCase().slice(0,200);if(Ns.result!==null&&Ns.queryKey===n&&Date.now()-Ns.ts<Vx)return Ns.result;let o;try{o=await xh(t,{topK:3})}catch{return""}if(!o||o.length===0)return"";let r;try{r=Jt().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))+`
233
233
  ...(truncated)`}let p=typeof u.score=="number"?u.score.toFixed(2):String(u.score);if(a.push(`--- ${u.name} (relevance: ${p}) ---
234
234
  ${d}`),l+=r(d),l>=i)break}if(a.length===0)return Ns={queryKey:n,result:"",ts:Date.now()},"";let c=`KNOWLEDGE BASE (auto-selected):
235
235
 
236
236
  ${a.join(`
237
237
 
238
- `)}`;return Ns={queryKey:n,result:c,ts:Date.now()},c}xh.exports={getBrainDir:Ms,listDocuments:wo,readDocument:dh,writeDocument:Wx,removeDocument:Yx,buildIndex:Cl,getIndex:fh,query:bh,getBrainContext:Vx,isEmbeddingAvailable:mh,generateEmbedding:Pl,buildEmbeddingIndex:wh,semanticQuery:_h,cosineSimilarity:gh,_keywordQuery:ph,_extractKeywords:Ol,_chunkText:yh,parseFrontmatter:_o,tokenize:ei,_fuseResults:$h}});var xo=z((NR,Ph)=>{var Ne=require("fs"),_t=require("path"),Jx=require("os"),{atomicWrite:ni,withFileLockSync:kh}=Pn(),$o=["user","feedback","project","reference"],Zx=50;function Yn(){return _t.join(process.cwd(),".nex","memory")}function Ps(){return _t.join(Yn(),"memory.json")}function Sh(){return _t.join(Yn(),"MEMORY.md")}function Qx(){return _t.join(process.cwd(),"NEX.md")}function vh(){return _t.join(Jx.homedir(),".nex","NEX.md")}function si(){let t=Yn();Ne.existsSync(t)||Ne.mkdirSync(t,{recursive:!0})}function Eh(t){let e=_t.join(Yn(),t);return Ne.existsSync(e)||Ne.mkdirSync(e,{recursive:!0}),e}function bo(){let t=Ps();if(!Ne.existsSync(t))return{};try{return JSON.parse(Ne.readFileSync(t,"utf-8"))}catch{return{}}}function Th(t){si(),ni(Ps(),JSON.stringify(t,null,2))}function Rh(){let t=Ps();if(!Ne.existsSync(t))return;let e=bo(),s=Object.keys(e);if(s.length===0){try{Ne.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=Eh("project"),l=_t.join(a,`${i}.md`),c=r.split(`
238
+ `)}`;return Ns={queryKey:n,result:c,ts:Date.now()},c}kh.exports={getBrainDir:Ms,listDocuments:wo,readDocument:fh,writeDocument:Hx,removeDocument:Gx,buildIndex:Ol,getIndex:ph,query:xh,getBrainContext:Jx,isEmbeddingAvailable:gh,generateEmbedding:Il,buildEmbeddingIndex:_h,semanticQuery:$h,cosineSimilarity:yh,_keywordQuery:hh,_extractKeywords:Ml,_chunkText:wh,parseFrontmatter:_o,tokenize:ti,_fuseResults:bh}});var xo=z((MR,Lh)=>{var Me=require("fs"),bt=require("path"),Zx=require("os"),{atomicWrite:si,withFileLockSync:Sh}=In(),$o=["user","feedback","project","reference"],Qx=50;function zn(){return bt.join(process.cwd(),".nex","memory")}function Ps(){return bt.join(zn(),"memory.json")}function vh(){return bt.join(zn(),"MEMORY.md")}function ek(){return bt.join(process.cwd(),"NEX.md")}function Eh(){return bt.join(Zx.homedir(),".nex","NEX.md")}function oi(){let t=zn();Me.existsSync(t)||Me.mkdirSync(t,{recursive:!0})}function Th(t){let e=bt.join(zn(),t);return Me.existsSync(e)||Me.mkdirSync(e,{recursive:!0}),e}function bo(){let t=Ps();if(!Me.existsSync(t))return{};try{return JSON.parse(Me.readFileSync(t,"utf-8"))}catch{return{}}}function Rh(t){oi(),si(Ps(),JSON.stringify(t,null,2))}function Ch(){let t=Ps();if(!Me.existsSync(t))return;let e=bo(),s=Object.keys(e);if(s.length===0){try{Me.renameSync(t,t+".bak")}catch{}return}for(let n of s){let o=e[n],r=o.value||String(o),i=n.replace(/[^a-z0-9_-]/gi,"-").toLowerCase().replace(/-+/g,"-").replace(/^-|-$/g,"");if(!i)continue;let a=Th("project"),l=bt.join(a,`${i}.md`),c=r.split(`
239
239
  `)[0].slice(0,100),u=`---
240
240
  name: ${n}
241
241
  description: ${c}
@@ -243,7 +243,7 @@ type: project
243
243
  ---
244
244
 
245
245
  ${r}
246
- `;ni(l,u)}oi();try{Ne.renameSync(t,t+".bak")}catch{}}function ek(t,e,s,n){if(!$o.includes(t))return{ok:!1,path:"",error:`Invalid type: ${t}. Must be one of: ${$o.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=Eh(t),i=_t.join(r,`${o}.md`);if(Ne.existsSync(i))try{if(Il(Ne.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(`
246
+ `;si(l,u)}ri();try{Me.renameSync(t,t+".bak")}catch{}}function tk(t,e,s,n){if(!$o.includes(t))return{ok:!1,path:"",error:`Invalid type: ${t}. Must be one of: ${$o.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=Th(t),i=bt.join(r,`${o}.md`);if(Me.existsSync(i))try{if(jl(Me.readFileSync(i,"utf-8")).body.slice(0,200)===s.slice(0,200))return{ok:!0,path:i,updated:!1}}catch{}let a=n||s.split(`
247
247
  `)[0].slice(0,100),l=`---
248
248
  name: ${e}
249
249
  description: ${a}
@@ -251,11 +251,11 @@ type: ${t}
251
251
  ---
252
252
 
253
253
  ${s}
254
- `;return ni(i,l),oi(),{ok:!0,path:i,updated:!0}}function tk(t,e){if(!$o.includes(t))return!1;let s=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase(),n=_t.join(Yn(),t,`${s}.md`);if(!Ne.existsSync(n))return!1;try{return Ne.unlinkSync(n),oi(),!0}catch{return!1}}function Il(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 Ch(){let t=[],e=Yn();for(let s of $o){let n=_t.join(e,s);if(!Ne.existsSync(n))continue;let o;try{o=Ne.readdirSync(n).filter(r=>r.endsWith(".md"))}catch{continue}for(let r of o){let i=_t.join(n,r);try{let a=Ne.readFileSync(i,"utf-8"),l=Il(a);t.push({type:s,name:l.name||_t.basename(r,".md"),description:l.description,filePath:i})}catch{}}}return t}function oi(){let t=Ch(),e=["# Project Memory Index",""];for(let s of t){if(e.length>=Zx+2)break;let n=`${s.type}/${_t.basename(s.filePath)}`;e.push(`- [${s.name}](${n}) \u2014 ${s.description||"(no description)"}`)}si(),ni(Sh(),e.join(`
254
+ `;return si(i,l),ri(),{ok:!0,path:i,updated:!0}}function nk(t,e){if(!$o.includes(t))return!1;let s=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase(),n=bt.join(zn(),t,`${s}.md`);if(!Me.existsSync(n))return!1;try{return Me.unlinkSync(n),ri(),!0}catch{return!1}}function jl(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 Ah(){let t=[],e=zn();for(let s of $o){let n=bt.join(e,s);if(!Me.existsSync(n))continue;let o;try{o=Me.readdirSync(n).filter(r=>r.endsWith(".md"))}catch{continue}for(let r of o){let i=bt.join(n,r);try{let a=Me.readFileSync(i,"utf-8"),l=jl(a);t.push({type:s,name:l.name||bt.basename(r,".md"),description:l.description,filePath:i})}catch{}}}return t}function ri(){let t=Ah(),e=["# Project Memory Index",""];for(let s of t){if(e.length>=Qx+2)break;let n=`${s.type}/${bt.basename(s.filePath)}`;e.push(`- [${s.name}](${n}) \u2014 ${s.description||"(no description)"}`)}oi(),si(vh(),e.join(`
255
255
  `)+`
256
- `)}function Ah(){let t=Sh();if(!Ne.existsSync(t))return"";try{return Ne.readFileSync(t,"utf-8").trim()}catch{return""}}function nk(t,e){si(),kh(Ps(),()=>{let s=bo();s[t]={value:e,updatedAt:new Date().toISOString()},Th(s)})}function sk(t){let e=bo();return e[t]?e[t].value:null}function ok(t){return si(),kh(Ps(),()=>{let e=bo();return t in e?(delete e[t],Th(e),!0):!1})}function Oh(){let t=bo();return Object.entries(t).map(([e,s])=>({key:e,value:s.value,updatedAt:s.updatedAt}))}function Nh(){let t=vh();if(!Ne.existsSync(t))return"";try{return Ne.readFileSync(t,"utf-8").trim()}catch{return""}}function Mh(){let t=Qx();if(!Ne.existsSync(t))return"";try{return Ne.readFileSync(t,"utf-8").trim()}catch{return""}}function rk(){Rh();let t=[],e=Nh();e&&t.push(`GLOBAL INSTRUCTIONS (~/.nex/NEX.md):
257
- ${e}`);let s=Mh();s&&t.push(`PROJECT INSTRUCTIONS (NEX.md):
258
- ${s}`);let n="",o=Ah();if(o)n=o;else{let d=Oh();d.length>0&&(n=`PROJECT MEMORY:
256
+ `)}function Oh(){let t=vh();if(!Me.existsSync(t))return"";try{return Me.readFileSync(t,"utf-8").trim()}catch{return""}}function sk(t,e){oi(),Sh(Ps(),()=>{let s=bo();s[t]={value:e,updatedAt:new Date().toISOString()},Rh(s)})}function ok(t){let e=bo();return e[t]?e[t].value:null}function rk(t){return oi(),Sh(Ps(),()=>{let e=bo();return t in e?(delete e[t],Rh(e),!0):!1})}function Nh(){let t=bo();return Object.entries(t).map(([e,s])=>({key:e,value:s.value,updatedAt:s.updatedAt}))}function Mh(){let t=Eh();if(!Me.existsSync(t))return"";try{return Me.readFileSync(t,"utf-8").trim()}catch{return""}}function Ph(){let t=ek();if(!Me.existsSync(t))return"";try{return Me.readFileSync(t,"utf-8").trim()}catch{return""}}function ik(){Ch();let t=[],e=Mh();e&&t.push(`GLOBAL INSTRUCTIONS (~/.nex/NEX.md):
257
+ ${e}`);let s=Ph();s&&t.push(`PROJECT INSTRUCTIONS (NEX.md):
258
+ ${s}`);let n="",o=Oh();if(o)n=o;else{let d=Nh();d.length>0&&(n=`PROJECT MEMORY:
259
259
  ${d.map(p=>` ${p.key}: ${p.value}`).join(`
260
260
  `)}`)}let r=t.join(`
261
261
 
@@ -264,28 +264,28 @@ ${d.map(p=>` ${p.key}: ${p.value}`).join(`
264
264
  `}n=f.trimEnd()+`
265
265
  [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(`
266
266
 
267
- `)}Ph.exports={saveMemory:ek,deleteMemory:tk,scanMemories:Ch,rebuildIndex:oi,loadMemoryIndex:Ah,remember:nk,recall:sk,forget:ok,listMemories:Oh,loadGlobalInstructions:Nh,loadProjectInstructions:Mh,getMemoryContext:rk,_getMemoryDir:Yn,_getMemoryFile:Ps,_getGlobalNexMdPath:vh,_parseMemoryFile:Il,_migrateIfNeeded:Rh,VALID_TYPES:$o}});var Fh=z((MR,qh)=>{var ko=require("fs"),Dl=require("path"),jl=process.env.NEX_AUDIT!=="false",Gn=null;function Lh(){return Gn||(Gn=Dl.join(process.cwd(),".nex","audit"),ko.existsSync(Gn)||ko.mkdirSync(Gn,{recursive:!0}),Gn)}function Ih(){let t=new Date().toISOString().split("T")[0];return Dl.join(Lh(),`${t}.jsonl`)}function ik(t){if(jl)try{let e={timestamp:new Date().toISOString(),tool:t.tool,args:Dh(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)+`
268
- `;ko.appendFileSync(Ih(),s,"utf-8")}catch{}}function Dh(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=Lh(),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=Dl.join(e,`${r}.jsonl`);if(!ko.existsSync(i))continue;let a=ko.readFileSync(i,"utf-8").split(`
269
- `).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 ak(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 lk(t){jl=t}function ck(){return jl}function uk(){Gn=null}qh.exports={logToolExecution:ik,sanitizeArgs:Dh,readAuditLog:jh,getAuditSummary:ak,setAuditEnabled:lk,isAuditEnabled:ck,getAuditLogPath:Ih,_reset:uk}});var Vh=z((IR,Xh)=>{var qe=require("fs").promises,So=require("fs"),Ee=require("path"),De=require("util").promisify(require("child_process").exec),zn=require("util").promisify(require("child_process").execFile),{spawnSync:dk}=require("child_process"),ql=require("axios"),{isForbidden:fk,isSSHForbidden:pk,isDangerous:hk,isCritical:Bh,isBashPathForbidden:mk,confirm:Lt}=eo(),{showDiff:ri,showNewFile:gk,showEditDiff:PR,confirmFileChange:vo}=fd(),{C:le,Spinner:yk,getToolSpinnerText:wk}=ze(),{isGitRepo:Fl,getCurrentBranch:Uh,getStatus:_k,getDiff:$k}=Cr(),{recordChange:ii}=kd(),{fuzzyFindText:Wh,findMostSimilar:Ro}=zd(),{runDiagnostics:Eo}=Xd(),{findFileInIndex:bk,getFileIndex:LR}=Ya(),{resolveProfile:Tt,sshExec:ft,scpUpload:xk,scpDownload:kk}=za(),{resolveDeployConfig:Sk,loadDeployConfigs:vk}=cf(),{getEditMode:Hh}=co(),Ek=/^(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/,Tk=/^ssh\s/,Rk=/^ssh(?:\s+-\S+)*\s+\S+@?\S+\s+["']?[^-]/;async function $t(t){return qe.access(t).then(()=>!0).catch(()=>!1)}async function ai(t){if(!t)return{fixedPath:null,message:""};let e=t.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),s=pt(e);if(s&&await $t(s))return{fixedPath:s,message:`(auto-fixed path: ${t} \u2192 ${e})`};let n=[".js",".ts",".jsx",".tsx",".mjs",".cjs",".json"],o=Ee.extname(t);if(!o)for(let i of n){let a=pt(t+i);if(a&&await $t(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=pt(i+a);if(l&&await $t(l))return{fixedPath:l,message:`(auto-fixed: ${o} \u2192 ${a})`}}}let r=Ee.basename(t);if(r&&r.length>2)try{let i=bk(r).map(a=>pt(a));if(i.length===1)return{fixedPath:i[0],message:`(auto-fixed: found ${r} at ${Ee.relative(process.cwd(),i[0])})`};if(i.length>1&&i.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
270
- ${i.map(l=>Ee.relative(process.cwd(),l)).map(l=>` - ${l}`).join(`
271
- `)}`}}catch{}return{fixedPath:null,message:""}}function Ck(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 zh(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+`
267
+ `)}Lh.exports={saveMemory:tk,deleteMemory:nk,scanMemories:Ah,rebuildIndex:ri,loadMemoryIndex:Oh,remember:sk,recall:ok,forget:rk,listMemories:Nh,loadGlobalInstructions:Mh,loadProjectInstructions:Ph,getMemoryContext:ik,_getMemoryDir:zn,_getMemoryFile:Ps,_getGlobalNexMdPath:Eh,_parseMemoryFile:jl,_migrateIfNeeded:Ch,VALID_TYPES:$o}});var Bh=z((PR,Fh)=>{var ko=require("fs"),ql=require("path"),Fl=process.env.NEX_AUDIT!=="false",Kn=null;function Ih(){return Kn||(Kn=ql.join(process.cwd(),".nex","audit"),ko.existsSync(Kn)||ko.mkdirSync(Kn,{recursive:!0}),Kn)}function Dh(){let t=new Date().toISOString().split("T")[0];return ql.join(Ih(),`${t}.jsonl`)}function ak(t){if(Fl)try{let e={timestamp:new Date().toISOString(),tool:t.tool,args:jh(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)+`
268
+ `;ko.appendFileSync(Dh(),s,"utf-8")}catch{}}function jh(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 qh(t={}){let e=Ih(),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(!ko.existsSync(i))continue;let a=ko.readFileSync(i,"utf-8").split(`
269
+ `).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 lk(t=1){let e=qh({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 ck(t){Fl=t}function uk(){return Fl}function dk(){Kn=null}Fh.exports={logToolExecution:ak,sanitizeArgs:jh,readAuditLog:qh,getAuditSummary:lk,setAuditEnabled:ck,isAuditEnabled:uk,getAuditLogPath:Dh,_reset:dk}});var Jh=z((DR,Vh)=>{var Fe=require("fs").promises,So=require("fs"),Te=require("path"),je=require("util").promisify(require("child_process").exec),Xn=require("util").promisify(require("child_process").execFile),{spawnSync:fk}=require("child_process"),Bl=require("axios"),{isForbidden:pk,isSSHForbidden:hk,isDangerous:mk,isCritical:Uh,isBashPathForbidden:gk,confirm:Ft}=eo(),{showDiff:ii,showNewFile:yk,showEditDiff:LR,confirmFileChange:vo}=pd(),{C:le,Spinner:wk,getToolSpinnerText:_k}=Ke(),{isGitRepo:Ul,getCurrentBranch:Wh,getStatus:$k,getDiff:bk}=Ar(),{recordChange:ai}=Sd(),{fuzzyFindText:Hh,findMostSimilar:Ro}=Kd(),{runDiagnostics:Eo}=Vd(),{findFileInIndex:xk,getFileIndex:IR}=za(),{resolveProfile:At,sshExec:gt,scpUpload:kk,scpDownload:Sk}=Xa(),{resolveDeployConfig:vk,loadDeployConfigs:Ek}=uf(),{getEditMode:Yh}=co(),Tk=/^(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/,Rk=/^ssh\s/,Ck=/^ssh(?:\s+-\S+)*\s+\S+@?\S+\s+["']?[^-]/;async function xt(t){return Fe.access(t).then(()=>!0).catch(()=>!1)}async function li(t){if(!t)return{fixedPath:null,message:""};let e=t.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),s=yt(e);if(s&&await xt(s))return{fixedPath:s,message:`(auto-fixed path: ${t} \u2192 ${e})`};let n=[".js",".ts",".jsx",".tsx",".mjs",".cjs",".json"],o=Te.extname(t);if(!o)for(let i of n){let a=yt(t+i);if(a&&await xt(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=yt(i+a);if(l&&await xt(l))return{fixedPath:l,message:`(auto-fixed: ${o} \u2192 ${a})`}}}let r=Te.basename(t);if(r&&r.length>2)try{let i=xk(r).map(a=>yt(a));if(i.length===1)return{fixedPath:i[0],message:`(auto-fixed: found ${r} at ${Te.relative(process.cwd(),i[0])})`};if(i.length>1&&i.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
270
+ ${i.map(l=>Te.relative(process.cwd(),l)).map(l=>` - ${l}`).join(`
271
+ `)}`}}catch{}return{fixedPath:null,message:""}}function Ak(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 Kh(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+`
272
272
 
273
273
  `+s.join(`
274
- `)}function Kh(t,e,s){let n=Ro(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 Yh=!1,Kn=null;function Ak(){Kn&&(Kn(),Kn=null)}var Ul=null;function Ok(t){Ul=t}async function Bl(){if(!Yh){Yh=!0;try{let{stdout:t}=await De("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await De('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await De("git stash pop",{cwd:process.cwd(),timeout:1e4}),await De("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var Nk=[/\.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 pt(t){let e=Ee.isAbsolute(t)?Ee.resolve(t):Ee.resolve(process.cwd(),t);for(let s of Nk)if(s.test(e))return null;return e}var Mk=[{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. Use include to filter by file type (e.g. '*.js'). 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 To(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 Gh(t,e,s={}){switch(t){case"bash":{let n=e.command,o=fk(n);if(o){let d=Ck(n);return`BLOCKED: Command matches forbidden pattern: ${o}${d?`
275
- HINT: ${d}`:""}`}let r=mk(n);if(r)return`BLOCKED: Destructive operation on protected path: ${r}
276
- 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?Bh(n):hk(n)){let d=Bh(n)?"\u26D4":"\u26A0";if(!await Lt(` ${d} bash: \`${n}\``,{toolName:"bash"}))return"CANCELLED: User declined to execute this command."}let a;try{a=process.cwd(),So.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=Tk.test(n.trim())&&!Rk.test(n.trim());if(Ek.test(n.trim())||l){s.silent||console.log(`${le.dim} \u25B6 interactive: ${n}${le.reset}`);let d=dk("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}=gs(),u=s.silent?null:new c("bash",n.substring(0,40));u&&u.start();try{let{stdout:d,stderr:f}=await De(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=zh(f,n);return`EXIT ${d.code||1}
277
- ${p}`}}case"read_file":{let n=pt(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await $t(n)){let N=await ai(e.path);if(N.fixedPath)n=N.fixedPath,console.log(`${le.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${Ee.relative(process.cwd(),n)}${le.reset}`);else return`ERROR: File not found: ${e.path}${N.message?`
278
- `+N.message:""}`}let r=Buffer.alloc(8192),i=await So.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 qe.readFile(n,"utf-8");if(!l&&(await qe.stat(n)).size>0)return`WARNING: ${n} is empty or unreadable`;let c=l.split(`
279
- `),u=await qe.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=Ee.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)`,k=c.slice(g,_).map((N,ee)=>`${g+ee+1}: ${N}`).join(`
274
+ `)}function Xh(t,e,s){let n=Ro(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 Gh=!1,Vn=null;function Ok(){Vn&&(Vn(),Vn=null)}var Hl=null;function Nk(t){Hl=t}async function Wl(){if(!Gh){Gh=!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 Mk=[/\.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 yt(t){let e=Te.isAbsolute(t)?Te.resolve(t):Te.resolve(process.cwd(),t);for(let s of Mk)if(s.test(e))return null;return e}var Pk=[{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. Use include to filter by file type (e.g. '*.js'). 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 To(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 zh(t,e,s={}){switch(t){case"bash":{let n=e.command,o=pk(n);if(o){let d=Ak(n);return`BLOCKED: Command matches forbidden pattern: ${o}${d?`
275
+ HINT: ${d}`:""}`}let r=gk(n);if(r)return`BLOCKED: Destructive operation on protected path: ${r}
276
+ 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?Uh(n):mk(n)){let d=Uh(n)?"\u26D4":"\u26A0";if(!await Ft(` ${d} bash: \`${n}\``,{toolName:"bash"}))return"CANCELLED: User declined to execute this command."}let a;try{a=process.cwd(),So.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=Rk.test(n.trim())&&!Ck.test(n.trim());if(Tk.test(n.trim())||l){s.silent||console.log(`${le.dim} \u25B6 interactive: ${n}${le.reset}`);let d=fk("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}=gs(),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=Kh(f,n);return`EXIT ${d.code||1}
277
+ ${p}`}}case"read_file":{let n=yt(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await xt(n)){let N=await li(e.path);if(N.fixedPath)n=N.fixedPath,console.log(`${le.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${Te.relative(process.cwd(),n)}${le.reset}`);else return`ERROR: File not found: ${e.path}${N.message?`
278
+ `+N.message:""}`}let r=Buffer.alloc(8192),i=await So.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(`
279
+ `),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=Te.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)`,k=c.slice(g,_).map((N,te)=>`${g+te+1}: ${N}`).join(`
280
280
  `),E=h?`
281
281
 
282
282
  [File truncated: showing lines 1-${f} of ${d} total. Use line_start/line_end to read other sections, e.g. line_start=${f+1} line_end=${Math.min(f*2,d)}]`:!p&&d>f?`
283
283
  [Large file (${d} lines total) \u2014 use line_start/line_end for other sections]`:"";return`${M}
284
- ${k}${E}`}case"write_file":{await Bl();let n=pt(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let o=await $t(n),r=null;if(s.autoConfirm)o&&(r=await qe.readFile(n,"utf-8"));else if(o){r=await qe.readFile(n,"utf-8");let u=await Eo(n,e.content);if(ri(n,r,e.content,{annotations:u}),!await vo("Overwrite"))return"CANCELLED: User declined to overwrite file."}else{let u=await Eo(n,e.content);if(gk(n,e.content,{annotations:u}),!await vo("Create"))return"CANCELLED: User declined to create file."}let i=Ee.dirname(n);await $t(i)||await qe.mkdir(i,{recursive:!0}),await qe.writeFile(n,e.content,"utf-8");let l=/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||e.content.startsWith("#!");l&&await qe.chmod(n,493),ii("write_file",n,r,e.content);let c=l?" [chmod +x applied]":"";return`Written: ${n} (${e.content.length} chars)${c}`}case"edit_file":{await Bl();let n=pt(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await $t(n)){let u=await ai(e.path);if(u.fixedPath)n=u.fixedPath,console.log(`${le.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${Ee.relative(process.cwd(),n)}${le.reset}`);else return`ERROR: File not found: ${e.path}${u.message?`
285
- `+u.message:""}`}let r=await qe.readFile(n,"utf-8"),i=e.old_text,a=!1,l=!1;if(!r.includes(e.old_text)){let{getActiveModelId:u,getActiveProviderName:d}=Ve();if(Hh(u(),d())==="strict"){let h=Ro(r,e.old_text);return h?`ERROR: old_text not found in ${n} (strict mode \u2014 exact match required)
284
+ ${k}${E}`}case"write_file":{await Wl();let n=yt(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let o=await xt(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 Eo(n,e.content);if(ii(n,r,e.content,{annotations:u}),!await vo("Overwrite"))return"CANCELLED: User declined to overwrite file."}else{let u=await Eo(n,e.content);if(yk(n,e.content,{annotations:u}),!await vo("Create"))return"CANCELLED: User declined to create file."}let i=Te.dirname(n);await xt(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),ai("write_file",n,r,e.content);let c=l?" [chmod +x applied]":"";return`Written: ${n} (${e.content.length} chars)${c}`}case"edit_file":{await Wl();let n=yt(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await xt(n)){let u=await li(e.path);if(u.fixedPath)n=u.fixedPath,console.log(`${le.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${Te.relative(process.cwd(),n)}${le.reset}`);else return`ERROR: File not found: ${e.path}${u.message?`
285
+ `+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(Yh(u(),d())==="strict"){let h=Ro(r,e.old_text);return h?`ERROR: old_text not found in ${n} (strict mode \u2014 exact match required)
286
286
  Most similar text (line ${h.line}, distance ${h.distance}):
287
- ${h.text}`:`ERROR: old_text not found in ${n} (strict mode \u2014 exact match required)`}let p=Wh(r,e.old_text);if(p)i=p,a=!0,console.log(`${le.dim} \u2713 fuzzy whitespace match applied${le.reset}`);else{let h=Kh(r,e.old_text,e.new_text);if(h){if(!s.autoConfirm){let M=await Eo(n,h.content);if(ri(n,r,h.content,{annotations:M}),!await vo(`Apply (auto-fix, line ${h.line}, distance ${h.distance})`))return"CANCELLED: User declined to apply edit."}await qe.writeFile(n,h.content,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||h.content.startsWith("#!"))&&await qe.chmod(n,493),ii("edit_file",n,r,h.content);let O=h.matchText.length>80?h.matchText.substring(0,77)+"...":h.matchText;return console.log(`${le.dim} \u2713 auto-fixed edit: line ${h.line}, distance ${h.distance}${le.reset}`),`Edited: ${n} (auto-fixed, line ${h.line}, distance ${h.distance}, matched: "${O}")`}let g=Ro(r,e.old_text);if(g){let O=r.split(`
288
- `),M=Math.max(0,g.line-6),k=Math.min(O.length,g.line+10),E=O.slice(M,k).map((ee,X)=>`${M+X+1}: ${ee}`).join(`
287
+ ${h.text}`:`ERROR: old_text not found in ${n} (strict mode \u2014 exact match required)`}let p=Hh(r,e.old_text);if(p)i=p,a=!0,console.log(`${le.dim} \u2713 fuzzy whitespace match applied${le.reset}`);else{let h=Xh(r,e.old_text,e.new_text);if(h){if(!s.autoConfirm){let M=await Eo(n,h.content);if(ii(n,r,h.content,{annotations:M}),!await vo(`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),ai("edit_file",n,r,h.content);let O=h.matchText.length>80?h.matchText.substring(0,77)+"...":h.matchText;return console.log(`${le.dim} \u2713 auto-fixed edit: line ${h.line}, distance ${h.distance}${le.reset}`),`Edited: ${n} (auto-fixed, line ${h.line}, distance ${h.distance}, matched: "${O}")`}let g=Ro(r,e.old_text);if(g){let O=r.split(`
288
+ `),M=Math.max(0,g.line-6),k=Math.min(O.length,g.line+10),E=O.slice(M,k).map((te,X)=>`${M+X+1}: ${te}`).join(`
289
289
  `),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})
290
290
 
291
291
  Actual file content around line ${g.line} \u2014 use this to correct old_text:
@@ -294,45 +294,45 @@ ${E}
294
294
  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(`
295
295
  `)[0].slice(0,60),b=_?`
296
296
  Recovery: grep -n "${_.replace(/"/g,'\\"')}" <file> to find the line, then re-read that section with line_start/line_end.`:`
297
- 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 Eo(n,u);if(ri(n,r,u,{annotations:d}),!await vo(a?"Apply (fuzzy match)":"Apply"))return"CANCELLED: User declined to apply edit."}let c=r.split(i).join(e.new_text);return await qe.writeFile(n,c,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||c.startsWith("#!"))&&await qe.chmod(n,493),ii("edit_file",n,r,c),a?`Edited: ${n} (fuzzy match)`:`Edited: ${n}`}case"list_directory":{let n=pt(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await $t(n)){let c=e.path.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),u=pt(c),d=await $t(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 qe.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(Ee.join(c,p.name),u+1,d+" ")}};return await l(n,1,""),a.join(`
298
- `)||"(empty)"}case"search_files":{let n=pt(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 zn("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(`
297
+ 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 Eo(n,u);if(ii(n,r,u,{annotations:d}),!await vo(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),ai("edit_file",n,r,c),a?`Edited: ${n} (fuzzy match)`:`Edited: ${n}`}case"list_directory":{let n=yt(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await xt(n)){let c=e.path.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),u=yt(c),d=await xt(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(Te.join(c,p.name),u+1,d+" ")}};return await l(n,1,""),a.join(`
298
+ `)||"(empty)"}case"search_files":{let n=yt(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 Xn("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(`
299
299
  `).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(`
300
- `)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let o=process.cwd(),r=e.path?pt(e.path):o,i=e.pattern,a=X=>{let ce=X.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"(.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");return new RegExp(`^${ce}$`)},l=a(i),c=i.split("/").pop(),u=a(c),{ToolProgress:d}=gs(),f=new d("glob","Finding files...");f.start();let{getFileIndex:p,getIndexedCwd:h,refreshIndex:g,isIndexValid:_}=Ya(),b=p(),O=h();_(r)||(await g(r),b=p());let M=b.filter(X=>l.test(X)||u.test(Ee.basename(X))).map(X=>Ee.join(r,X));if(M.length===0)return f.stop(),"(no matches)";let k=await Promise.all(M.slice(0,210).map(async X=>{try{let ce=await qe.stat(X);return{path:X,mtime:ce.mtimeMs}}catch{return{path:X,mtime:0}}}));k.sort((X,ce)=>ce.mtime-X.mtime);let E=k.map(X=>X.path),N=M.length>200,ee=E.slice(0,200).join(`
301
- `);return f.update({count:M.length,detail:e.pattern}),f.stop(),N?`${ee}
302
-
303
- \u26A0 Results truncated at 200. Use a more specific pattern.`:ee}case"grep":{let n=e.path?pt(e.path):process.cwd();if(e.staged){let{getDiff:l}=Cr(),c=await l(!0);if(!c.trim())return"(no staged changes)";let u=new Set,d=c.split(`
304
- `);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}=gs(),h=new p("grep","Searching staged content...");h.start();let g=[];for(let _ of u)try{let b=Ee.join(process.cwd(),_);if(await $t(b)){let O=[...f];O.push(e.pattern,b);let{stdout:M}=await zn("grep",O,{cwd:process.cwd(),timeout:3e4,maxBuffer:2*1024*1024});if(e.output_mode==="files_with_matches"||e.output_mode==="count"){let k=M.trim().split(`
305
- `).filter(E=>E.trim());g=g.concat(k)}else{let k=M.split("\0");for(let E=0;E<k.length;E+=2){let N=k[E+1];if(N){let ee=N.split(`
306
- `).filter(X=>X.trim());for(let X of ee)g.push(`${_}:${X}`)}}}}}catch{}return h.update({count:g.length,detail:"in staged files"}),h.stop(),g.join(`
307
- `).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}=gs(),a=new i("grep","Searching...");a.start();try{let{stdout:l}=await zn("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(`
300
+ `)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let o=process.cwd(),r=e.path?yt(e.path):o,i=e.pattern,a=X=>{let ce=X.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"(.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");return new RegExp(`^${ce}$`)},l=a(i),c=i.split("/").pop(),u=a(c),{ToolProgress:d}=gs(),f=new d("glob","Finding files...");f.start();let{getFileIndex:p,getIndexedCwd:h,refreshIndex:g,isIndexValid:_}=za(),b=p(),O=h();_(r)||(await g(r),b=p());let M=b.filter(X=>l.test(X)||u.test(Te.basename(X))).map(X=>Te.join(r,X));if(M.length===0)return f.stop(),"(no matches)";let k=await Promise.all(M.slice(0,210).map(async X=>{try{let ce=await Fe.stat(X);return{path:X,mtime:ce.mtimeMs}}catch{return{path:X,mtime:0}}}));k.sort((X,ce)=>ce.mtime-X.mtime);let E=k.map(X=>X.path),N=M.length>200,te=E.slice(0,200).join(`
301
+ `);return f.update({count:M.length,detail:e.pattern}),f.stop(),N?`${te}
302
+
303
+ \u26A0 Results truncated at 200. Use a more specific pattern.`:te}case"grep":{let n=e.path?yt(e.path):process.cwd();if(e.staged){let{getDiff:l}=Ar(),c=await l(!0);if(!c.trim())return"(no staged changes)";let u=new Set,d=c.split(`
304
+ `);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}=gs(),h=new p("grep","Searching staged content...");h.start();let g=[];for(let _ of u)try{let b=Te.join(process.cwd(),_);if(await xt(b)){let O=[...f];O.push(e.pattern,b);let{stdout:M}=await Xn("grep",O,{cwd:process.cwd(),timeout:3e4,maxBuffer:2*1024*1024});if(e.output_mode==="files_with_matches"||e.output_mode==="count"){let k=M.trim().split(`
305
+ `).filter(E=>E.trim());g=g.concat(k)}else{let k=M.split("\0");for(let E=0;E<k.length;E+=2){let N=k[E+1];if(N){let te=N.split(`
306
+ `).filter(X=>X.trim());for(let X of te)g.push(`${_}:${X}`)}}}}}catch{}return h.update({count:g.length,detail:"in staged files"}),h.stop(),g.join(`
307
+ `).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}=gs(),a=new i("grep","Searching...");a.start();try{let{stdout:l}=await Xn("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(`
308
308
  `).filter(f=>f.trim());else{let f=l.split("\0");c=[];for(let p=0;p<f.length;p+=2){let h=f[p],g=f[p+1];if(h&&g){let _=g.split(`
309
309
  `).filter(b=>b.trim());for(let b of _)c.push(`${h}:${b}`)}}}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(`
310
- `).trim()||"(no matches)"}catch(l){return a.stop(),l.code===2?`ERROR: Invalid regex pattern: ${e.pattern}`:"(no matches)"}}case"patch_file":{await Bl();let n=pt(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await $t(n)){let b=await ai(e.path);if(b.fixedPath)n=b.fixedPath,console.log(`${le.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${Ee.relative(process.cwd(),n)}${le.reset}`);else return`ERROR: File not found: ${e.path}${b.message?`
311
- `+b.message:""}`}let r=e.patches;if(!Array.isArray(r)||r.length===0)return"ERROR: No patches provided";let i=await qe.readFile(n,"utf-8"),{getActiveModelId:a,getActiveProviderName:l}=Ve(),c=Hh(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 k=Ro(i,O);return k?`ERROR: Patch ${b+1} old_text not found in ${n} (strict mode \u2014 exact match required)
310
+ `).trim()||"(no matches)"}catch(l){return a.stop(),l.code===2?`ERROR: Invalid regex pattern: ${e.pattern}`:"(no matches)"}}case"patch_file":{await Wl();let n=yt(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await xt(n)){let b=await li(e.path);if(b.fixedPath)n=b.fixedPath,console.log(`${le.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${Te.relative(process.cwd(),n)}${le.reset}`);else return`ERROR: File not found: ${e.path}${b.message?`
311
+ `+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=Yh(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 k=Ro(i,O);return k?`ERROR: Patch ${b+1} old_text not found in ${n} (strict mode \u2014 exact match required)
312
312
  Most similar text (line ${k.line}, distance ${k.distance}):
313
- ${k.text}`:`ERROR: Patch ${b+1} old_text not found in ${n} (strict mode \u2014 exact match required)`}else{let k=Wh(i,O);if(k)u.push({old_text:k,new_text:M}),d=!0;else{let E=Ro(i,O);if(E){let N=Math.max(3,Math.ceil(O.length*.05));if(E.distance<=N)u.push({old_text:E.text,new_text:M}),f=!0;else return`ERROR: Patch ${b+1} old_text not found in ${n}
313
+ ${k.text}`:`ERROR: Patch ${b+1} old_text not found in ${n} (strict mode \u2014 exact match required)`}else{let k=Hh(i,O);if(k)u.push({old_text:k,new_text:M}),d=!0;else{let E=Ro(i,O);if(E){let N=Math.max(3,Math.ceil(O.length*.05));if(E.distance<=N)u.push({old_text:E.text,new_text:M}),f=!0;else return`ERROR: Patch ${b+1} old_text not found in ${n}
314
314
  Most similar text (line ${E.line}, distance ${E.distance}):
315
- ${E.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 Eo(n,p);if(ri(n,i,p,{annotations:b}),!await vo(d?"Apply patches (fuzzy match)":"Apply patches"))return"CANCELLED: User declined to apply patches."}await qe.writeFile(n,p,"utf-8");let h=/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||p.startsWith("#!");h&&await qe.chmod(n,493),ii("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 ql.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 ql.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]
315
+ ${E.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 Eo(n,p);if(ii(n,i,p,{annotations:b}),!await vo(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),ai("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 Bl.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 Bl.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]
316
316
 
317
317
  ${r}`;return i.length>0&&(a+=`
318
318
 
319
319
  Sources:
320
320
  `+i.slice(0,n).map((l,c)=>`${c+1}. ${l}`).join(`
321
- `)),a}catch(o){console.error(`${le.dim} Perplexity search failed (${o.message}), falling back to DuckDuckGo${le.reset}`)}try{let r=(await ql.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}
321
+ `)),a}catch(o){console.error(`${le.dim} Perplexity search failed (${o.message}), falling back to DuckDuckGo${le.reset}`)}try{let r=(await Bl.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}
322
322
  ${c.url}`).join(`
323
323
 
324
- `)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:n}=an();try{let o=await n(e.url,{waitFor:e.wait_for}),r=o.links.length>0?`
324
+ `)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:n}=ln();try{let o=await n(e.url,{waitFor:e.wait_for}),r=o.links.length>0?`
325
325
 
326
326
  Links:
327
327
  `+o.links.map(i=>` ${i.text} \u2192 ${i.href}`).join(`
328
328
  `):"";return`Title: ${o.title}
329
329
  URL: ${o.url}
330
330
 
331
- ${o.text}${r}`}catch(o){return`ERROR: ${o.message}`}}case"browser_screenshot":{let{browserScreenshot:n}=an();try{let o=await n(e.url,{width:e.width,height:e.height,fullPage:e.full_page});return`Screenshot saved: ${o.path}
331
+ ${o.text}${r}`}catch(o){return`ERROR: ${o.message}`}}case"browser_screenshot":{let{browserScreenshot:n}=ln();try{let o=await n(e.url,{width:e.width,height:e.height,fullPage:e.full_page});return`Screenshot saved: ${o.path}
332
332
  Title: ${o.title}
333
333
  URL: ${o.url}
334
334
 
335
- To analyze visually, paste the path into your next message: ${o.path}`}catch(o){return`ERROR: ${o.message}`}}case"visual_review":{let{browserScreenshot:n}=an();try{let o=await n(e.url,{width:e.width||1280,height:e.height||800,fullPage:e.full_page||!1}),r=e.focus||"general layout, spacing, typography, colors, and usability",i=`VISUAL REVIEW \u2014 Screenshot captured
335
+ To analyze visually, paste the path into your next message: ${o.path}`}catch(o){return`ERROR: ${o.message}`}}case"visual_review":{let{browserScreenshot:n}=ln();try{let o=await n(e.url,{width:e.width||1280,height:e.height||800,fullPage:e.full_page||!1}),r=e.focus||"general layout, spacing, typography, colors, and usability",i=`VISUAL REVIEW \u2014 Screenshot captured
336
336
  URL: ${o.url}
337
337
  Title: ${o.title}
338
338
  Screenshot: ${o.path}
@@ -349,10 +349,10 @@ Analyze the screenshot above and provide structured feedback:
349
349
  4. Responsiveness concerns at this viewport
350
350
  5. Specific issues related to: ${r}`;return e.compare_with&&So.existsSync(e.compare_with)&&(i+=`
351
351
 
352
- 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}=Wl(),o=n();return o?{text:`Clipboard image captured: ${o.path}
352
+ 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}=Yl(),o=n();return o?{text:`Clipboard image captured: ${o.path}
353
353
  Size: ${Math.round(Buffer.from(o.data,"base64").length/1024)} KB
354
354
 
355
- [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}=an();try{return await n(e.url,{selector:e.selector,text:e.text})}catch(o){return`ERROR: ${o.message}`}}case"browser_fill":{let{browserFill:n}=an();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}=jn(),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(`
355
+ [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}=ln();try{return await n(e.url,{selector:e.selector,text:e.text})}catch(o){return`ERROR: ${o.message}`}}case"browser_fill":{let{browserFill:n}=ln();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}=Fn(),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(`
356
356
  `):" No significant regional changes";return{text:`VISUAL DIFF \u2014 ${o.diffPercent}% of pixels changed
357
357
  Changed: ${o.changedPixels.toLocaleString()} / ${o.totalPixels.toLocaleString()} pixels
358
358
  Canvas: ${o.width}\xD7${o.height}
@@ -361,7 +361,7 @@ Diff image: ${o.diffPath}
361
361
  Regional breakdown:
362
362
  ${i}
363
363
 
364
- [Diff image attached \u2014 red/magenta pixels indicate changes]`,images:[{path:o.diffPath,base64:So.readFileSync(o.diffPath).toString("base64"),media_type:"image/png"}]}}catch(n){return`ERROR: ${n.message}`}case"responsive_sweep":try{let{responsiveSweep:n}=jn(),o=await n(e.url,{viewports:e.viewports,fullPage:e.full_page}),r=o.map(i=>` ${i.label} (${i.width}px): ${i.path}`).join(`
364
+ [Diff image attached \u2014 red/magenta pixels indicate changes]`,images:[{path:o.diffPath,base64:So.readFileSync(o.diffPath).toString("base64"),media_type:"image/png"}]}}catch(n){return`ERROR: ${n.message}`}case"responsive_sweep":try{let{responsiveSweep:n}=Fn(),o=await n(e.url,{viewports:e.viewports,fullPage:e.full_page}),r=o.map(i=>` ${i.label} (${i.width}px): ${i.path}`).join(`
365
365
  `);return{text:`RESPONSIVE SWEEP \u2014 ${o.length} viewports captured
366
366
  URL: ${e.url}
367
367
 
@@ -375,15 +375,15 @@ Analyze these screenshots for:
375
375
  2. Typography scaling (text too small on mobile, too large on desktop)
376
376
  3. Navigation pattern changes across viewports
377
377
  4. Image/media sizing and aspect ratio issues
378
- 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}=jn(),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})
378
+ 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}=Fn(),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})
379
379
  Source: ${e.image}
380
380
  Output: ${o.path}
381
381
 
382
- [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}=jn(),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:So.readFileSync(l.diff.diffPath).toString("base64"),media_type:"image/png"}),{text:i.join(`
382
+ [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}=Fn(),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:So.readFileSync(l.diff.diffPath).toString("base64"),media_type:"image/png"}),{text:i.join(`
383
383
  `),images:c}}return{text:i.join(`
384
384
  `)+`
385
385
 
386
- 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}=jn(),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(`
386
+ 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}=Fn(),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(`
387
387
  `),i=o.spacing.length?o.spacing.map(a=>` ${a.px}px (${a.occurrences} occurrences)`).join(`
388
388
  `):" No clear spacing pattern detected";return`DESIGN TOKENS \u2014 extracted from ${o.dimensions.width}\xD7${o.dimensions.height} image
389
389
  Source: ${o.imagePath}
@@ -397,7 +397,7 @@ ${i}
397
397
  Use these values to:
398
398
  - Compare against CSS variables / design system tokens
399
399
  - Identify inconsistent colors or spacing
400
- - Generate a color palette from the rendered output`}catch(n){return`ERROR: ${n.message}`}case"design_compare":try{let{designCompare:n}=jn(),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(`
400
+ - Generate a color palette from the rendered output`}catch(n){return`ERROR: ${n.message}`}case"design_compare":try{let{designCompare:n}=Fn(),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(`
401
401
  `)||" All regions match within tolerance";return{text:`DESIGN COMPARISON \u2014 ${o.diffPercent}% deviation from reference
402
402
  Reference: ${o.referencePath}
403
403
  Live: ${o.livePath}
@@ -409,42 +409,42 @@ Pixel deviation: ${o.changedPixels.toLocaleString()} / ${o.totalPixels.toLocaleS
409
409
  Regional breakdown:
410
410
  ${r}
411
411
 
412
- [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 Ul?new Promise(r=>{Kn=()=>r("CANCELLED"),Ul(n,o).then(i=>{Kn=null,r(i||"User did not answer")})}):new Promise(r=>{let i=require("readline").createInterface({input:process.stdin,output:process.stdout});Kn=()=>{i.close(),r("CANCELLED")};let a=o.length>0?`
412
+ [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 Hl?new Promise(r=>{Vn=()=>r("CANCELLED"),Hl(n,o).then(i=>{Vn=null,r(i||"User did not answer")})}):new Promise(r=>{let i=require("readline").createInterface({input:process.stdin,output:process.stdout});Vn=()=>{i.close(),r("CANCELLED")};let a=o.length>0?`
413
413
  ${o.map((l,c)=>` ${c+1}. ${l}`).join(`
414
414
  `)}
415
415
  `:"";console.log(`
416
- ${le.cyan}${le.bold} ? ${n}${le.reset}${a}`),i.question(`${le.cyan} > ${le.reset}`,l=>{Kn=null,i.close(),r(l.trim()||"(no response)")})})}case"git_status":{if(!await Fl())return"ERROR: Not a git repository";let n=await Uh()||"(detached)",o=await _k();if(o.length===0)return`Branch: ${n}
416
+ ${le.cyan}${le.bold} ? ${n}${le.reset}${a}`),i.question(`${le.cyan} > ${le.reset}`,l=>{Vn=null,i.close(),r(l.trim()||"(no response)")})})}case"git_status":{if(!await Ul())return"ERROR: Not a git repository";let n=await Wh()||"(detached)",o=await $k();if(o.length===0)return`Branch: ${n}
417
417
  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(`
418
- `)}case"git_diff":{if(!await Fl())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 $k(!!e.staged);return n||"(no diff)"}case"git_log":{if(!await Fl())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}=_l(),{getActiveTaskProgress:l}=ze(),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(`
418
+ `)}case"git_diff":{if(!await Ul())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 bk(!!e.staged);return n||"(no diff)"}case"git_log":{if(!await Ul())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}=bl(),{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(`
419
419
  `+i()),`Created task list "${e.name}" with ${u.length} tasks:
420
420
  `+u.map(d=>` ${d.id}: ${d.description}`).join(`
421
421
  `)}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(`
422
422
  `+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(`
423
- `+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}=Tl();return n(e)}case"switch_model":{let{setActiveModel:n,getActiveProviderName:o,getActiveModelId:r}=Ve();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 zn("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(`
423
+ `+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}=Cl();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 Xn("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(`
424
424
  `)}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(`
425
- `)[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 zn("gh",["run","view",String(e.run_id),"--log"],{cwd:process.cwd(),timeout:6e4,maxBuffer:5242880});return i.substring(0,8e3)+(i.length>8e3?`
426
- ...(truncated)`:"")}let{stdout:n}=await zn("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(`
425
+ `)[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 Xn("gh",["run","view",String(e.run_id),"--log"],{cwd:process.cwd(),timeout:6e4,maxBuffer:5242880});return i.substring(0,8e3)+(i.length>8e3?`
426
+ ...(truncated)`:"")}let{stdout:n}=await Xn("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(`
427
427
  `)}catch(n){return`ERROR: ${(n.stderr||n.message||"").toString().split(`
428
- `)[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}=eo(),o=e.branch||await Uh()||"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(`
429
- ${le.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${o}${le.reset}`),!await n(" Trigger?"))return"CANCELLED: User declined to trigger workflow.";try{return await zn("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(`
430
- `)[0]}`}}case"k8s_pods":{let n=e.namespace?`-n ${e.namespace}`:"-A",o=e.label?`-l ${e.label}`:"",r=To(`get pods ${n} ${o} -o wide`.trim(),e);try{let{stdout:i,stderr:a}=await De(r,{timeout:3e4,maxBuffer:2097152});return(i||a||"(no pods)").trim()}catch(i){let a=(i.stderr||i.message||"").toString().split(`
431
- `)[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=To(r,e);try{let{stdout:a,stderr:l}=await De(i,{timeout:6e4,maxBuffer:5242880}),c=(a||l||"(no logs)").trim();return c.substring(0,2e4)+(c.length>2e4?`
428
+ `)[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}=eo(),o=e.branch||await Wh()||"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(`
429
+ ${le.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${o}${le.reset}`),!await n(" Trigger?"))return"CANCELLED: User declined to trigger workflow.";try{return await Xn("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(`
430
+ `)[0]}`}}case"k8s_pods":{let n=e.namespace?`-n ${e.namespace}`:"-A",o=e.label?`-l ${e.label}`:"",r=To(`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(`
431
+ `)[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=To(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?`
432
432
  ...(truncated)`:"")}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
433
433
  `)[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(`
434
- ${le.yellow} \u26A0 kubectl exec into pod: ${e.pod} (ns: ${n})${le.reset}`),console.log(`${le.dim} Command: ${e.command}${le.reset}`),!await Lt(" 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=To(r,e);try{let{stdout:a,stderr:l}=await De(i,{timeout:6e4,maxBuffer:2097152});return(a||l||"(no output)").trim()}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
434
+ ${le.yellow} \u26A0 kubectl exec into pod: ${e.pod} (ns: ${n})${le.reset}`),console.log(`${le.dim} Command: ${e.command}${le.reset}`),!await Ft(" 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=To(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(`
435
435
  `)[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(`
436
- ${le.yellow} \u26A0 kubectl apply: ${i}${e.namespace?` (ns: ${e.namespace})`:""}${le.reset}`),!await Lt(" 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=To(o,e);try{let{stdout:i,stderr:a}=await De(r,{timeout:12e4,maxBuffer:2097152});return(i||a||"(no output)").trim()}catch(i){return`ERROR: ${(i.stderr||i.message||"").toString().split(`
436
+ ${le.yellow} \u26A0 kubectl apply: ${i}${e.namespace?` (ns: ${e.namespace})`:""}${le.reset}`),!await Ft(" 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=To(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(`
437
437
  `)[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(`
438
- ${le.yellow} \u26A0 ${a}: deployment/${e.deployment} (ns: ${n})${le.reset}`),!await Lt(` ${a}?`))return"CANCELLED: User declined."}let r=`rollout ${e.action} deployment/${e.deployment} -n ${n}`,i=To(r,e);try{let{stdout:a,stderr:l}=await De(i,{timeout:12e4,maxBuffer:2097152});return(a||l||"(no output)").trim()}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
439
- `)[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}=Ll(),{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+`
438
+ ${le.yellow} \u26A0 ${a}: deployment/${e.deployment} (ns: ${n})${le.reset}`),!await Ft(` ${a}?`))return"CANCELLED: User declined."}let r=`rollout ${e.action} deployment/${e.deployment} -n ${n}`,i=To(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(`
439
+ `)[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}=Dl(),{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+`
440
440
 
441
- `+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=Tt(e.server)}catch(N){return`ERROR: ${N.message}`}let o=e.command,r=!!e.sudo,i=(e.timeout||30)*1e3,a=pk(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:
441
+ `+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=At(e.server)}catch(N){return`ERROR: ${N.message}`}let o=e.command,r=!!e.sudo,i=(e.timeout||30)*1e3,a=hk(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:
442
442
  grep -n "pattern" /path/to/file -A 50
443
443
  or to read the whole file:
444
444
  cat /path/to/file
445
445
  NEVER use sed -n again \u2014 it will always be blocked.`:`BLOCKED: Remote command matches SSH secret-exposure pattern: ${a}
446
- 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,ee,X)=>{let ce=Math.min(Number(X),20);return`${ee} ${ce}`}),o=o.replace(/(--(?:before|after|context)=)(\d+)/g,(N,ee,X)=>ee+Math.min(Number(X),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(`
447
- ${le.yellow} \u26A0 Remote command on ${N}: ${o}${le.reset}`),!await Lt(" Execute on remote server?"))return"CANCELLED: User declined to execute remote command."}let{stdout:c,stderr:u,exitCode:d,error:f}=await ft(n,o,{timeout:i,sudo:r}),p=[c,u].filter(Boolean).join(`
446
+ 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,X)=>{let ce=Math.min(Number(X),20);return`${te} ${ce}`}),o=o.replace(/(--(?:before|after|context)=)(\d+)/g,(N,te,X)=>te+Math.min(Number(X),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(`
447
+ ${le.yellow} \u26A0 Remote command on ${N}: ${o}${le.reset}`),!await Ft(" Execute on remote server?"))return"CANCELLED: User declined to execute remote command."}let{stdout:c,stderr:u,exitCode:d,error:f}=await gt(n,o,{timeout:i,sudo:r}),p=[c,u].filter(Boolean).join(`
448
448
  `).trim();if(d!==0)return`EXIT ${d}
449
449
  ${f||p||"(no output)"}`;let h=/\bgrep\b/.test(o),g=p;h&&(g=g.split(`
450
450
  `).filter(N=>N!=="--").join(`
@@ -452,38 +452,38 @@ ${f||p||"(no output)"}`;let h=/\bgrep\b/.test(o),g=p;h&&(g=g.split(`
452
452
  `);b.length>_&&(g=`(${b.length-_} earlier lines omitted \u2014 showing last ${_})
453
453
  `+b.slice(-_).join(`
454
454
  `));let O=4,M=g.split(`
455
- `),k=[],E=0;for(;E<M.length;){let N=E+1;for(;N<M.length&&M[N]===M[E];)N++;let ee=N-E;if(k.push(M[E]),ee>O)k.push(`... (${ee-1} identical lines omitted)`);else for(let X=1;X<ee;X++)k.push(M[E]);E=N}return k.join(`
456
- `)||"(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=Tt(e.server)}catch(i){return`ERROR: ${i.message}`}let o=n.user?`${n.user}@${n.host}`:n.host;if(console.log(`
457
- ${le.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${o}:${e.remote_path}${le.reset}`),!await Lt(" Upload to remote server?"))return"CANCELLED: User declined upload.";try{return await xk(n,e.local_path,e.remote_path)}catch(i){return`ERROR: ${i.message}`}}case"ssh_download":{if(!e.server||!e.remote_path||!e.local_path)return"ERROR: server, remote_path, and local_path are required";let n;try{n=Tt(e.server)}catch(o){return`ERROR: ${o.message}`}try{return await kk(n,e.remote_path,e.local_path)}catch(o){return`ERROR: ${o.message}`}}case"remote_agent":{let n=require("path").join(process.cwd(),".nex","servers.json"),o=null;try{o=JSON.parse(require("fs").readFileSync(n,"utf-8"))[e.server]||null}catch{}let r=o?`${o.user||"root"}@${o.host}`:e.server,i=o?.key?["-i",o.key]:[],a=(e.project_path||o?.home||"~").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}.
458
- ${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=Tt(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(`
459
- ${le.yellow} \u26A0 Service: systemctl ${e.action} ${e.service} on ${l}${le.reset}`),!await Lt(" 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 De(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}
460
- ${d}`}}else{let{stdout:l,stderr:c,exitCode:u,error:d}=await ft(i,a,{timeout:15e3,sudo:!0}),f=[l,c].filter(Boolean).join(`
455
+ `),k=[],E=0;for(;E<M.length;){let N=E+1;for(;N<M.length&&M[N]===M[E];)N++;let te=N-E;if(k.push(M[E]),te>O)k.push(`... (${te-1} identical lines omitted)`);else for(let X=1;X<te;X++)k.push(M[E]);E=N}return k.join(`
456
+ `)||"(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=At(e.server)}catch(i){return`ERROR: ${i.message}`}let o=n.user?`${n.user}@${n.host}`:n.host;if(console.log(`
457
+ ${le.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${o}:${e.remote_path}${le.reset}`),!await Ft(" Upload to remote server?"))return"CANCELLED: User declined upload.";try{return await kk(n,e.local_path,e.remote_path)}catch(i){return`ERROR: ${i.message}`}}case"ssh_download":{if(!e.server||!e.remote_path||!e.local_path)return"ERROR: server, remote_path, and local_path are required";let n;try{n=At(e.server)}catch(o){return`ERROR: ${o.message}`}try{return await Sk(n,e.remote_path,e.local_path)}catch(o){return`ERROR: ${o.message}`}}case"remote_agent":{let n=require("path").join(process.cwd(),".nex","servers.json"),o=null;try{o=JSON.parse(require("fs").readFileSync(n,"utf-8"))[e.server]||null}catch{}let r=o?`${o.user||"root"}@${o.host}`:e.server,i=o?.key?["-i",o.key]:[],a=(e.project_path||o?.home||"~").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}.
458
+ ${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=At(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(`
459
+ ${le.yellow} \u26A0 Service: systemctl ${e.action} ${e.service} on ${l}${le.reset}`),!await Ft(" 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}
460
+ ${d}`}}else{let{stdout:l,stderr:c,exitCode:u,error:d}=await gt(i,a,{timeout:15e3,sudo:!0}),f=[l,c].filter(Boolean).join(`
461
461
  `).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}
462
- ${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 De(a,{timeout:15e3});return(h||g||"(no log output)").trim()}catch(h){return`EXIT ${h.code||1}
463
- ${(h.stderr||h.message||"").toString().trim()}`}let l;try{l=Tt(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:c,stderr:u,exitCode:d,error:f}=await ft(l,a,{timeout:2e4}),p=[c,u].filter(Boolean).join(`
462
+ ${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}
463
+ ${(h.stderr||h.message||"").toString().trim()}`}let l;try{l=At(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:c,stderr:u,exitCode:d,error:f}=await gt(l,a,{timeout:2e4}),p=[c,u].filter(Boolean).join(`
464
464
  `).trim();return d!==0?`EXIT ${d}
465
- ${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 De(r,{timeout:1e4});return(f||p||"(no containers)").trim()}catch(f){return`EXIT ${f.code||1}
466
- ${(f.stderr||f.message||"").toString().trim()}`}let i;try{i=Tt(e.server)}catch(f){return`ERROR: ${f.message}`}let{stdout:a,stderr:l,exitCode:c,error:u}=await ft(i,r,{timeout:15e3}),d=[a,l].filter(Boolean).join(`
465
+ ${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}
466
+ ${(f.stderr||f.message||"").toString().trim()}`}let i;try{i=At(e.server)}catch(f){return`ERROR: ${f.message}`}let{stdout:a,stderr:l,exitCode:c,error:u}=await gt(i,r,{timeout:15e3}),d=[a,l].filter(Boolean).join(`
467
467
  `).trim();return c!==0?`EXIT ${c}
468
- ${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 De(i,{timeout:15e3});return(p||h||"(no log output)").trim()}catch(p){return`EXIT ${p.code||1}
469
- ${(p.stderr||p.message||"").toString().trim()}`}let a;try{a=Tt(e.server)}catch(p){return`ERROR: ${p.message}`}let{stdout:l,stderr:c,exitCode:u,error:d}=await ft(a,i,{timeout:2e4}),f=[l,c].filter(Boolean).join(`
468
+ ${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}
469
+ ${(p.stderr||p.message||"").toString().trim()}`}let a;try{a=At(e.server)}catch(p){return`ERROR: ${p.message}`}let{stdout:l,stderr:c,exitCode:u,error:d}=await gt(a,i,{timeout:2e4}),f=[l,c].filter(Boolean).join(`
470
470
  `).trim();return u!==0?`EXIT ${u}
471
471
  ${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(`
472
- ${le.yellow} \u26A0 docker exec in ${e.container} on ${h}: ${e.command}${le.reset}`),!await Lt(" 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 De(a,{timeout:3e4});return(h||g||"(no output)").trim()}catch(h){return`EXIT ${h.code||1}
473
- ${(h.stderr||h.message||"").toString().trim()}`}let l;try{l=Tt(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:c,stderr:u,exitCode:d,error:f}=await ft(l,a,{timeout:35e3}),p=[c,u].filter(Boolean).join(`
472
+ ${le.yellow} \u26A0 docker exec in ${e.container} on ${h}: ${e.command}${le.reset}`),!await Ft(" 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}
473
+ ${(h.stderr||h.message||"").toString().trim()}`}let l;try{l=At(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:c,stderr:u,exitCode:d,error:f}=await gt(l,a,{timeout:35e3}),p=[c,u].filter(Boolean).join(`
474
474
  `).trim();return d!==0?`EXIT ${d}
475
475
  ${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(`
476
- ${le.yellow} \u26A0 docker ${e.action} ${e.container} on ${h}${le.reset}`),!await Lt(" 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 De(a,{timeout:3e4});return(h||g||`docker ${e.action} ${e.container}: OK`).trim()}catch(h){return`EXIT ${h.code||1}
477
- ${(h.stderr||h.message||"").toString().trim()}`}let l;try{l=Tt(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:c,stderr:u,exitCode:d,error:f}=await ft(l,a,{timeout:35e3}),p=[c,u].filter(Boolean).join(`
476
+ ${le.yellow} \u26A0 docker ${e.action} ${e.container} on ${h}${le.reset}`),!await Ft(" 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}
477
+ ${(h.stderr||h.message||"").toString().trim()}`}let l;try{l=At(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:c,stderr:u,exitCode:d,error:f}=await gt(l,a,{timeout:35e3}),p=[c,u].filter(Boolean).join(`
478
478
  `).trim();return d!==0?`EXIT ${d}
479
- ${f||p}`:p||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...Sk(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=Tt(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(`
479
+ ${f||p}`:p||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...vk(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=At(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(`
480
480
  ${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(`
481
- ${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 Lt(" 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}:
481
+ ${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 Ft(" 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}:
482
482
  ${f}${e.deploy_script?`
483
- ${e.deploy_script}`:""}`;let{stdout:p,stderr:h,exitCode:g,error:_}=await ft(o,f,{timeout:12e4});if(i=[p,h].filter(Boolean).join(`
483
+ ${e.deploy_script}`:""}`;let{stdout:p,stderr:h,exitCode:g,error:_}=await gt(o,f,{timeout:12e4});if(i=[p,h].filter(Boolean).join(`
484
484
  `).trim(),g!==0)return`ERROR (git pull, exit ${g}):
485
- ${_||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 De(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]:
486
- ${i||"(nothing to sync)"}`}let a="";if(e.deploy_script){let{stdout:u,stderr:d,exitCode:f,error:p}=await ft(o,e.deploy_script,{timeout:12e4}),h=[u,d].filter(Boolean).join(`
485
+ ${_||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]:
486
+ ${i||"(nothing to sync)"}`}let a="";if(e.deploy_script){let{stdout:u,stderr:d,exitCode:f,error:p}=await gt(o,e.deploy_script,{timeout:12e4}),h=[u,d].filter(Boolean).join(`
487
487
  `).trim();if(f!==0)return`${n==="git"?"git pull":"rsync"} OK
488
488
 
489
489
  ERROR (deploy_script, exit ${f}):
@@ -496,50 +496,50 @@ Health check: \u2713 ${u} \u2192 ${p.status}`;else return l=`
496
496
 
497
497
  Health check FAILED: ${u} \u2192 HTTP ${p.status}`,(n==="git"?"git pull OK":"rsync OK")+i+a+l}catch(f){return l=`
498
498
 
499
- 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 ft(o,u,{timeout:15e3}),g=[f,p].filter(Boolean).join(`
499
+ 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 gt(o,u,{timeout:15e3}),g=[f,p].filter(Boolean).join(`
500
500
  `).trim();if(h!==0)return l=`
501
501
 
502
502
  Health check FAILED (exit ${h}): ${g}`,(n==="git"?"git pull OK":"rsync OK")+i+a+l;l=`
503
503
 
504
504
  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}
505
- ${i}${a}${l}`.trim()}case"deployment_status":{let n=vk(),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=Tt(a.server||i),u=(await ft(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 ft(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 ft(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:
505
+ ${i}${a}${l}`.trim()}case"deployment_status":{let n=Ek(),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=At(a.server||i),u=(await gt(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 gt(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 gt(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:
506
506
  ${r.join(`
507
- `)}`}case"frontend_recon":{let n=process.cwd(),o=(e.type||"").toLowerCase(),r=[],i=async(k,E=120)=>{try{let N=Ee.isAbsolute(k)?k:Ee.join(n,k),X=(await qe.readFile(N,"utf8")).split(`
507
+ `)}`}case"frontend_recon":{let n=process.cwd(),o=(e.type||"").toLowerCase(),r=[],i=async(k,E=120)=>{try{let N=Te.isAbsolute(k)?k:Te.join(n,k),X=(await Fe.readFile(N,"utf8")).split(`
508
508
  `),ce=X.slice(0,E).join(`
509
509
  `);return X.length>E?ce+`
510
- ... (${X.length-E} more lines \u2014 use read_file for full content)`:ce}catch{return null}},l=["node_modules",".git","dist","build","vendor",".next","__pycache__","venv",".venv"].map(k=>`-not -path "*/${k}/*"`).join(" "),c=async k=>{try{let{stdout:E}=await De(`find "${n}" -type f -name "${k}" ${l} 2>/dev/null | head -10`,{timeout:8e3});return E.trim().split(`
511
- `).filter(Boolean)}catch{return[]}},u=async(k,E)=>{try{let{stdout:N}=await De(`grep -rl "${k}" "${n}" --include="${E}" --exclude-dir=node_modules --exclude-dir=.git --exclude-dir=dist --exclude-dir=build 2>/dev/null | head -5`,{timeout:8e3});return N.trim().split(`
510
+ ... (${X.length-E} more lines \u2014 use read_file for full content)`:ce}catch{return null}},l=["node_modules",".git","dist","build","vendor",".next","__pycache__","venv",".venv"].map(k=>`-not -path "*/${k}/*"`).join(" "),c=async k=>{try{let{stdout:E}=await je(`find "${n}" -type f -name "${k}" ${l} 2>/dev/null | head -10`,{timeout:8e3});return E.trim().split(`
511
+ `).filter(Boolean)}catch{return[]}},u=async(k,E)=>{try{let{stdout:N}=await je(`grep -rl "${k}" "${n}" --include="${E}" --exclude-dir=node_modules --exclude-dir=.git --exclude-dir=dist --exclude-dir=build 2>/dev/null | head -5`,{timeout:8e3});return N.trim().split(`
512
512
  `).filter(Boolean)}catch{return[]}};r.push(`## STEP 1: Design Tokens
513
- `);let d=[...await c("tailwind.config.js"),...await c("tailwind.config.ts"),...await c("tailwind.config.mjs")];if(d.length>0){let k=await i(d[0],80);k&&r.push(`### Tailwind config (${Ee.relative(n,d[0])})
513
+ `);let d=[...await c("tailwind.config.js"),...await c("tailwind.config.ts"),...await c("tailwind.config.mjs")];if(d.length>0){let k=await i(d[0],80);k&&r.push(`### Tailwind config (${Te.relative(n,d[0])})
514
514
  \`\`\`js
515
515
  ${k}
516
- \`\`\``)}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 k of f){let E=await c(k);for(let N of E){let ee=await i(N,100);if(ee&&ee.includes(":root")){r.push(`### CSS Variables (${Ee.relative(n,N)})
516
+ \`\`\``)}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 k of f){let E=await c(k);for(let N of E){let te=await i(N,100);if(te&&te.includes(":root")){r.push(`### CSS Variables (${Te.relative(n,N)})
517
517
  \`\`\`css
518
- ${ee}
519
- \`\`\``),p=!0;break}}if(p)break}if(!p){let k=await u(":root","*.css");if(k.length>0){let E=await i(k[0],100);E&&r.push(`### CSS Variables (${Ee.relative(n,k[0])})
518
+ ${te}
519
+ \`\`\``),p=!0;break}}if(p)break}if(!p){let k=await u(":root","*.css");if(k.length>0){let E=await i(k[0],100);E&&r.push(`### CSS Variables (${Te.relative(n,k[0])})
520
520
  \`\`\`css
521
521
  ${E}
522
522
  \`\`\``),p=!0}}p||r.push("(no CSS custom properties / :root found)"),r.push(`
523
523
  ## STEP 2: Main Layout / Index Page
524
- `);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 k of h){let E=await c(k);if(E.length>0){let N=await i(E[0],150);if(N){r.push(`### Main layout: ${Ee.relative(n,E[0])}
524
+ `);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 k of h){let E=await c(k);if(E.length>0){let N=await i(E[0],150);if(N){r.push(`### Main layout: ${Te.relative(n,E[0])}
525
525
  \`\`\`html
526
526
  ${N}
527
527
  \`\`\``),g=!0;break}}}g||r.push("(no main layout/index file found \u2014 try read_file on your root template manually)"),r.push(`
528
528
  ## STEP 3: Reference Component (same type)
529
- `);let _=[];if(o){for(let k of["*.html","*.vue","*.jsx","*.tsx"])if(_=await u(o,k),_.length>0)break}if(_.length===0)try{let{stdout:k}=await De(`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});_=k.trim().split(`
530
- `).filter(Boolean)}catch{_=[]}if(_.length>0){let k=_[0],E=await i(k,150);E?r.push(`### Reference: ${Ee.relative(n,k)}
529
+ `);let _=[];if(o){for(let k of["*.html","*.vue","*.jsx","*.tsx"])if(_=await u(o,k),_.length>0)break}if(_.length===0)try{let{stdout:k}=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});_=k.trim().split(`
530
+ `).filter(Boolean)}catch{_=[]}if(_.length>0){let k=_[0],E=await i(k,150);E?r.push(`### Reference: ${Te.relative(n,k)}
531
531
  \`\`\`html
532
532
  ${E}
533
533
  \`\`\``):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(`
534
534
  ## STEP 4: Framework Stack
535
- `);let b=[],O=await i(Ee.join(n,"package.json"),999);if(O){if((O.includes('"react"')||O.includes("'react'"))&&b.push("React"),O.includes('"vue"')||O.includes("'vue'")){let E=O.match(/"vue":\s*"[\^~]?(\d+)/);b.push(E?`Vue.js v${E[1]}`:"Vue.js")}let k=O.match(/"alpinejs":\s*"[\^~]?(\d+)/);k&&b.push(`Alpine.js v${k[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 $t(Ee.join(n,"manage.py"))||(await i(Ee.join(n,"requirements.txt"),50)||"").includes("Django"))&&b.push("Django (server-rendered templates)"),!b.some(k=>k.includes("Alpine"))){let k=await u("alpinejs","*.html");if(k.length>0){let N=(await i(k[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(k=>k.includes("HTMX"))||(await u("htmx","*.html")).length>0&&b.push("HTMX (via CDN)"),b.length>0?(r.push(b.map(k=>`- ${k}`).join(`
535
+ `);let b=[],O=await i(Te.join(n,"package.json"),999);if(O){if((O.includes('"react"')||O.includes("'react'"))&&b.push("React"),O.includes('"vue"')||O.includes("'vue'")){let E=O.match(/"vue":\s*"[\^~]?(\d+)/);b.push(E?`Vue.js v${E[1]}`:"Vue.js")}let k=O.match(/"alpinejs":\s*"[\^~]?(\d+)/);k&&b.push(`Alpine.js v${k[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 xt(Te.join(n,"manage.py"))||(await i(Te.join(n,"requirements.txt"),50)||"").includes("Django"))&&b.push("Django (server-rendered templates)"),!b.some(k=>k.includes("Alpine"))){let k=await u("alpinejs","*.html");if(k.length>0){let N=(await i(k[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(k=>k.includes("HTMX"))||(await u("htmx","*.html")).length>0&&b.push("HTMX (via CDN)"),b.length>0?(r.push(b.map(k=>`- ${k}`).join(`
536
536
  `)),r.push(`
537
537
  \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(`
538
538
  ---
539
539
  \u2705 Design recon complete. Now build consistently with the patterns above.`),r.join(`
540
- `)}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=Tt(e.server)}catch(l){return`ERROR: ${l.message}`}let r=async(l,c=3e4)=>{if(n)try{let{stdout:u,stderr:d}=await De(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 ft(o,l,{timeout:c}),h=[u,d].filter(Boolean).join(`
540
+ `)}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=At(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 gt(o,l,{timeout:c}),h=[u,d].filter(Boolean).join(`
541
541
  `).trim();return{out:p&&f!==0&&!u.trim()?(p+`
542
- `+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 Lt(`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}
542
+ `+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 Ft(`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}
543
543
  (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}
544
544
  ${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}
545
545
  ${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}
@@ -581,8 +581,8 @@ ${u}`:u||"(empty log)"}case"find_large":{let l=e.path||"/",c=e.limit||20,u=e.min
581
581
  ${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}
582
582
  ${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}
583
583
  ${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}
584
- ${u}`:u||"(no log entries)"}default:return`ERROR: Unknown sysadmin action: ${e.action}`}}case"save_memory":{let{saveMemory:n}=xo(),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}=xo();return n(e.type,e.name)?`Memory deleted: ${e.type}/${e.name}`:`Memory not found: ${e.type}/${e.name}`}default:{let{executePluginTool:n}=Pr(),o=await n(t,e,s);return o!==null?o:`ERROR: Unknown tool: ${t}`}}}async function Pk(t,e,s={}){let{emit:n}=Pr(),{logToolExecution:o}=Fh(),r=Date.now(),i=s.silent?null:wk(t,e);if(!i){let l=await Gh(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 yk(i);a.start();try{let l=await Gh(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}}Xh.exports={TOOL_DEFINITIONS:Mk,executeTool:Pk,resolvePath:pt,autoFixPath:ai,autoFixEdit:Kh,enrichBashError:zh,cancelPendingAskUser:Ak,setAskUserHandler:Ok,fileExists:$t}});var ks=z((DR,Jh)=>{Jh.exports=Vh()});var Yl=z((qR,Zh)=>{var{loadServerProfiles:Co,resolveProfile:jR,sshExec:Lk}=za(),Hl={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 Ik(){let t=Co();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&&Hl[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 Hl[o])s.push(`- ${i}`)}}return s.join(`
585
- `)}function Dk(t){let e=Co();return Object.values(e).some(s=>s.os&&s.os.startsWith(t))}function jk(){return Object.keys(Co())}function qk(){let t=require("fs"),s=require("path").join(process.cwd(),"NEX.md"),n="";try{n=t.readFileSync(s,"utf-8")}catch{}let o=Co(),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(`
584
+ ${u}`:u||"(no log entries)"}default:return`ERROR: Unknown sysadmin action: ${e.action}`}}case"save_memory":{let{saveMemory:n}=xo(),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}=xo();return n(e.type,e.name)?`Memory deleted: ${e.type}/${e.name}`:`Memory not found: ${e.type}/${e.name}`}default:{let{executePluginTool:n}=Lr(),o=await n(t,e,s);return o!==null?o:`ERROR: Unknown tool: ${t}`}}}async function Lk(t,e,s={}){let{emit:n}=Lr(),{logToolExecution:o}=Bh(),r=Date.now(),i=s.silent?null:_k(t,e);if(!i){let l=await zh(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 wk(i);a.start();try{let l=await zh(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}}Vh.exports={TOOL_DEFINITIONS:Pk,executeTool:Lk,resolvePath:yt,autoFixPath:li,autoFixEdit:Xh,enrichBashError:Kh,cancelPendingAskUser:Ok,setAskUserHandler:Nk,fileExists:xt}});var ks=z((jR,Zh)=>{Zh.exports=Jh()});var zl=z((FR,Qh)=>{var{loadServerProfiles:Co,resolveProfile:qR,sshExec:Ik}=Xa(),Gl={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 Dk(){let t=Co();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&&Gl[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 Gl[o])s.push(`- ${i}`)}}return s.join(`
585
+ `)}function jk(t){let e=Co();return Object.values(e).some(s=>s.os&&s.os.startsWith(t))}function qk(){return Object.keys(Co())}function Fk(){let t=require("fs"),s=require("path").join(process.cwd(),"NEX.md"),n="";try{n=t.readFileSync(s,"utf-8")}catch{}let o=Co(),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(`
586
586
  `),u=r.map(f=>o[f].log_path).filter(Boolean),d=u.length>0?`
587
587
  - Server log paths: ${u.join(", ")}`:"";return`# Deployment Context (Auto-detected)
588
588
 
@@ -600,7 +600,7 @@ ${c}
600
600
  - \u274C Do NOT \`read_file\` on paths like \`logs/\` \u2014 these files do not exist locally
601
601
  - \u274C Do NOT \`list_directory\` on server paths \u2014 the local project is the source, not the running instance
602
602
 
603
- **When in doubt:** If a path contains \`logs/\`, \`/var/log/\`, or \`/home/<user>/\` \u2014 it is on the server. SSH there.${Fk(o)}`}function Fk(t){return Object.values(t).some(s=>s.host==="94.130.37.43")?`
603
+ **When in doubt:** If a path contains \`logs/\`, \`/var/log/\`, or \`/home/<user>/\` \u2014 it is on the server. SSH there.${Bk(o)}`}function Bk(t){return Object.values(t).some(s=>s.host==="94.130.37.43")?`
604
604
 
605
605
  ## Server Debugging Rules
606
606
 
@@ -611,35 +611,35 @@ ${c}
611
611
  - 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.
612
612
  - 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.
613
613
  - 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.
614
- - 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 Bk(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=Co();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 Lk(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]
615
- `+i.trim()}catch{return null}}Zh.exports={getServerContext:Ik,getDeploymentContextBlock:qk,hasServerOS:Dk,getProfileNames:jk,probeUrlServer:Bk,OS_HINTS:Hl}});var sm=z((FR,nm)=>{var ct=require("fs").promises,em=require("fs"),Ge=require("path"),li=require("util").promisify(require("child_process").exec),{C:Ls}=ze(),{getMergeConflicts:tm}=Cr(),{getServerContext:Uk}=Yl(),Wk=new Set(["node_modules",".git",".svn","dist","build","coverage",".nyc_output","__pycache__",".DS_Store",".next",".nuxt",".turbo",".cache","vendor","tmp","temp"]);function Hk(t){try{return em.readFileSync(t,"utf-8").split(`
616
- `).map(s=>s.trim()).filter(s=>s&&!s.startsWith("#")&&!s.startsWith("!")).map(s=>s.replace(/\/$/,""))}catch{return[]}}function Yk(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 Gk(t,{maxDepth:e=3,maxFiles:s=200,giPatterns:n=[]}={}){let o=Ge.join(t,".gitignore"),r=[...n,...Hk(o)],i=0,a=[Ge.basename(t)+"/"];function l(c,u,d){if(d>e||i>=s)return;let f;try{f=em.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=>!(Wk.has(h.name)||h.name.startsWith(".")&&h.name!==".env.example"||Yk(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(`
617
- `)}var Gl=new Map,Ds=new Map,ci=null,Qh=3e4,Is={result:null,expiry:0,cwd:null};async function Xt(t){try{return await t()}catch{return null}}async function zk(){if(!ci||Date.now()>ci)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 ct.stat(e),n=Ds.get(e);if(!n||s.mtimeMs!==n)return!1}catch{if(Ds.has(e))return!1}try{let e=Ge.join(process.cwd(),".git","HEAD"),s=await ct.stat(e),n=Ds.get(e);if(!n||s.mtimeMs!==n)return!1}catch{}return!0}async function Kk(){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 ct.stat(e);Ds.set(e,s.mtimeMs)}catch{Ds.delete(e)}}async function Xk(t){let e="fileContext",s=Gl.get(e),n=!1;if(s&&await zk()&&(n=!0),!n){let c=[],u=Ge.join(t,"package.json");if(await Xt(()=>ct.access(u).then(()=>!0).catch(()=>!1)))try{let k=await ct.readFile(u,"utf-8"),E=JSON.parse(k),N={name:E.name,version:E.version};E.scripts&&(N.scripts=Object.keys(E.scripts).slice(0,15)),E.dependencies&&(N.deps=Object.keys(E.dependencies).length),E.devDependencies&&(N.devDeps=Object.keys(E.devDependencies).length),c.push(`PACKAGE: ${JSON.stringify(N)}`)}catch{}let f=Ge.join(t,"README.md");if(await Xt(()=>ct.access(f).then(()=>!0).catch(()=>!1))){let E=(await ct.readFile(f,"utf-8")).split(`
614
+ - 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 Uk(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=Co();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 Ik(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]
615
+ `+i.trim()}catch{return null}}Qh.exports={getServerContext:Dk,getDeploymentContextBlock:Fk,hasServerOS:jk,getProfileNames:qk,probeUrlServer:Uk,OS_HINTS:Gl}});var om=z((BR,sm)=>{var ft=require("fs").promises,tm=require("fs"),Ge=require("path"),ci=require("util").promisify(require("child_process").exec),{C:Ls}=Ke(),{getMergeConflicts:nm}=Ar(),{getServerContext:Wk}=zl(),Hk=new Set(["node_modules",".git",".svn","dist","build","coverage",".nyc_output","__pycache__",".DS_Store",".next",".nuxt",".turbo",".cache","vendor","tmp","temp"]);function Yk(t){try{return tm.readFileSync(t,"utf-8").split(`
616
+ `).map(s=>s.trim()).filter(s=>s&&!s.startsWith("#")&&!s.startsWith("!")).map(s=>s.replace(/\/$/,""))}catch{return[]}}function Gk(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 zk(t,{maxDepth:e=3,maxFiles:s=200,giPatterns:n=[]}={}){let o=Ge.join(t,".gitignore"),r=[...n,...Yk(o)],i=0,a=[Ge.basename(t)+"/"];function l(c,u,d){if(d>e||i>=s)return;let f;try{f=tm.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=>!(Hk.has(h.name)||h.name.startsWith(".")&&h.name!==".env.example"||Gk(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(`
617
+ `)}var Kl=new Map,Ds=new Map,ui=null,em=3e4,Is={result:null,expiry:0,cwd:null};async function Zt(t){try{return await t()}catch{return null}}async function Kk(){if(!ui||Date.now()>ui)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 ft.stat(e),n=Ds.get(e);if(!n||s.mtimeMs!==n)return!1}catch{if(Ds.has(e))return!1}try{let e=Ge.join(process.cwd(),".git","HEAD"),s=await ft.stat(e),n=Ds.get(e);if(!n||s.mtimeMs!==n)return!1}catch{}return!0}async function Xk(){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 ft.stat(e);Ds.set(e,s.mtimeMs)}catch{Ds.delete(e)}}async function Vk(t){let e="fileContext",s=Kl.get(e),n=!1;if(s&&await Kk()&&(n=!0),!n){let c=[],u=Ge.join(t,"package.json");if(await Zt(()=>ft.access(u).then(()=>!0).catch(()=>!1)))try{let k=await ft.readFile(u,"utf-8"),E=JSON.parse(k),N={name:E.name,version:E.version};E.scripts&&(N.scripts=Object.keys(E.scripts).slice(0,15)),E.dependencies&&(N.deps=Object.keys(E.dependencies).length),E.devDependencies&&(N.devDeps=Object.keys(E.devDependencies).length),c.push(`PACKAGE: ${JSON.stringify(N)}`)}catch{}let f=Ge.join(t,"README.md");if(await Zt(()=>ft.access(f).then(()=>!0).catch(()=>!1))){let E=(await ft.readFile(f,"utf-8")).split(`
618
618
  `).slice(0,50);c.push(`README (first 50 lines):
619
619
  ${E.join(`
620
- `)}`)}let h=Ge.join(t,".gitignore");if(await Xt(()=>ct.access(h).then(()=>!0).catch(()=>!1))){let k=await ct.readFile(h,"utf-8");c.push(`GITIGNORE:
621
- ${k.trim()}`)}let _=Ge.join(t,"CLAUDE.md");if(await Xt(()=>ct.access(_).then(()=>!0).catch(()=>!1))){let k=await ct.readFile(_,"utf-8");k.trim()&&c.push(`PROJECT INSTRUCTIONS (CLAUDE.md):
622
- ${k.trim()}`)}let O=Ge.join(t,".nex","CLAUDE.md");if(await Xt(()=>ct.access(O).then(()=>!0).catch(()=>!1))){let k=await ct.readFile(O,"utf-8");k.trim()&&c.push(`PRIVATE PROJECT INSTRUCTIONS (.nex/CLAUDE.md):
620
+ `)}`)}let h=Ge.join(t,".gitignore");if(await Zt(()=>ft.access(h).then(()=>!0).catch(()=>!1))){let k=await ft.readFile(h,"utf-8");c.push(`GITIGNORE:
621
+ ${k.trim()}`)}let _=Ge.join(t,"CLAUDE.md");if(await Zt(()=>ft.access(_).then(()=>!0).catch(()=>!1))){let k=await ft.readFile(_,"utf-8");k.trim()&&c.push(`PROJECT INSTRUCTIONS (CLAUDE.md):
622
+ ${k.trim()}`)}let O=Ge.join(t,".nex","CLAUDE.md");if(await Zt(()=>ft.access(O).then(()=>!0).catch(()=>!1))){let k=await ft.readFile(O,"utf-8");k.trim()&&c.push(`PRIVATE PROJECT INSTRUCTIONS (.nex/CLAUDE.md):
623
623
  ${k.trim()}`)}s=c.join(`
624
624
 
625
- `),Gl.set(e,s),ci=Date.now()+Qh,await Kk()}let o=[s],r,i,a,l;if(Is.result&&Date.now()<Is.expiry&&Is.cwd===t?{branch:r,status:i,log:a,conflicts:l}=Is.result:([r,i,a,l]=await Promise.all([Xt(async()=>{let{stdout:c}=await li("git branch --show-current",{cwd:t,timeout:5e3});return c.trim()}),Xt(async()=>{let{stdout:c}=await li("git status --short",{cwd:t,timeout:5e3});return c.trim()}),Xt(async()=>{let{stdout:c}=await li("git log --oneline -5",{cwd:t,timeout:5e3});return c.trim()}),tm()]),Is={result:{branch:r,status:i,log:a,conflicts:l},expiry:Date.now()+Qh,cwd:t}),r&&o.push(`GIT BRANCH: ${r}`),i&&o.push(`GIT STATUS:
625
+ `),Kl.set(e,s),ui=Date.now()+em,await Xk()}let o=[s],r,i,a,l;if(Is.result&&Date.now()<Is.expiry&&Is.cwd===t?{branch:r,status:i,log:a,conflicts:l}=Is.result:([r,i,a,l]=await Promise.all([Zt(async()=>{let{stdout:c}=await ci("git branch --show-current",{cwd:t,timeout:5e3});return c.trim()}),Zt(async()=>{let{stdout:c}=await ci("git status --short",{cwd:t,timeout:5e3});return c.trim()}),Zt(async()=>{let{stdout:c}=await ci("git log --oneline -5",{cwd:t,timeout:5e3});return c.trim()}),nm()]),Is={result:{branch:r,status:i,log:a,conflicts:l},expiry:Date.now()+em,cwd:t}),r&&o.push(`GIT BRANCH: ${r}`),i&&o.push(`GIT STATUS:
626
626
  ${i}`),a&&o.push(`RECENT COMMITS:
627
627
  ${a}`),l&&l.length>0){let c=l.map(u=>` ${u.file}`).join(`
628
628
  `);o.push(`MERGE CONFLICTS (resolve before editing these files):
629
- ${c}`)}try{let c=Uk();c&&o.push(c)}catch{}return o.join(`
629
+ ${c}`)}try{let c=Wk();c&&o.push(c)}catch{}return o.join(`
630
630
 
631
- `)}async function Vk(t){let e=Ge.join(t,"package.json"),s="";if(await Xt(()=>ct.access(e).then(()=>!0).catch(()=>!1)))try{let i=await ct.readFile(e,"utf-8"),a=JSON.parse(i);s=`${a.name||"?"} v${a.version||"?"}`}catch{}let[o,r]=await Promise.all([Xt(async()=>{let{stdout:i}=await li("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),tm()]);if(r&&r.length>0){console.log(`${Ls.red} \u26A0 ${r.length} unresolved merge conflict(s):${Ls.reset}`);for(let i of r)console.log(`${Ls.red} ${i.file}${Ls.reset}`);console.log(`${Ls.yellow} \u2192 Resolve conflicts before starting tasks${Ls.reset}`)}console.log()}nm.exports={gatherProjectContext:Xk,printContext:Vk,generateFileTree:Gk,_clearContextCache:()=>{Gl.clear(),Ds.clear(),ci=null,Is={result:null,expiry:0,cwd:null}}}});var di=z((BR,im)=>{var It=require("fs"),ui=require("path"),{atomicWrite:Jk}=Pn();function Oo(){return ui.join(process.cwd(),".nex","sessions")}function zl(){let t=Oo();It.existsSync(t)||It.mkdirSync(t,{recursive:!0,mode:448})}function Kl(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return ui.join(Oo(),`${e}.json`)}function Xl(t,e,s={}){zl();let n=Kl(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 Jk(n,JSON.stringify(o,null,2)),{path:n,name:t}}function om(t){let e=Kl(t);if(!It.existsSync(e))return null;try{return JSON.parse(It.readFileSync(e,"utf-8"))}catch{return null}}function rm(){zl();let t=Oo(),e=It.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(It.readFileSync(ui.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 Zk(t){let e=Kl(t);return It.existsSync(e)?(It.unlinkSync(e),!0):!1}function Qk(){let t=rm();return t.length===0?null:om(t[0].name)}var Xn=null,un=null,Ao=null;function eS(t,e={}){t.length!==0&&(Xn&&clearTimeout(Xn),un=t,Ao=e||{},Xn=setTimeout(()=>{un&&un.length>0&&Xl("_autosave",un,Ao),Xn=null,un=null,Ao=null},5e3))}function tS(){Xn&&(clearTimeout(Xn),Xn=null),un&&un.length>0&&(Xl("_autosave",un,Ao),un=null,Ao=null)}function nS(){zl();let t=Oo(),e=It.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=ui.join(t,r);try{let a=It.statSync(i);new Date(a.mtime)<n&&(It.unlinkSync(i),o++)}catch{}}return o}im.exports={saveSession:Xl,loadSession:om,listSessions:rm,deleteSession:Zk,getLastSession:Qk,autoSave:eS,flushAutoSave:tS,clearOldSessions:nS,_getSessionsDir:Oo}});var fi=z((UR,hm)=>{"use strict";var No=require("fs"),am=require("path");function lm(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 sS(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 cm(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 um(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 dm(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 fm(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 pm(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=lm(t),o=cm(t),r=n.length,i=sS(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 P=$.input?.command||$.input?.cmd||"";return/\bsed\s+-n\b/.test(P)});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 P=$.input?.command||$.input?.cmd||"",R=$.input?.pattern||"",B=`${P} ${R}`;return/(?:-[CAB]|--context|--after|--before)\s*[=\s]?([2-9][1-9]|\d{3,})/.test(B)||/grep.*-[CAB]\s*([2-9][1-9]|\d{3,})/.test(B)})&&(e-=1,s.push("grep used with >20 context lines (context flood risk)"));let d=t.some($=>$.role==="assistant"),f=um(t),h=dm(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 P=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(P)})&&(e-=.5,s.push("Auto-compress triggered (context flood indicator)"));let b=fm(a),O=0,M="";for(let[$,P]of b)P>O&&(O=P,M=$);if(O>=3){let[$]=M.split("|");e-=1,s.push(`Same tool call repeated ${O}\xD7 (tool: ${$})`)}let k=!1,E=t.findIndex($=>$.role==="user"&&typeof $.content=="string"&&$.content.includes("[SYSTEM STOP]")&&$.content.includes('"valid":true'));E>=0&&n.filter(P=>P.index>E).length>0&&(k=!0),k&&(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,P=1;for(let R=1;R<N.length;R++)N[R].index<=N[R-1].index+2?P++:($=Math.max($,P),P=1);$=Math.max($,P),$>=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 ee=new Map;for(let $ of a)if($.name==="read_file"&&$.input?.path){let P=$.input.path;ee.has(P)||ee.set(P,{count:0,ranges:[]});let R=ee.get(P);if(R.count++,$.input.line_start!=null){let B=$.input.line_start||1,T=$.input.line_end||B+350;R.ranges.push([B,T])}}function X($,P,R){for(let[B,T]of R){let x=Math.max($,B),se=Math.min(P,T);if(se>x){let we=se-x,ge=P-$||1;if(we/ge>=.7)return!0}}return!1}let ce=0,ae="";for(let[$,P]of ee){if(P.count<3)continue;if(P.ranges.length===P.count){let T=!1,x=[];for(let[se,we]of P.ranges){if(x.length>0&&X(se,we,x)){T=!0;break}x.push([se,we])}if(!T)continue}if(P.count-P.ranges.length<=2&&P.ranges.length>=1){let T=!1,x=[];for(let[se,we]of P.ranges){if(x.length>0&&X(se,we,x)){T=!0;break}x.push([se,we])}if(!T)continue}P.count>ce&&(ce=P.count,ae=$)}if(ce>=3){e-=1;let $=ae.split("/").slice(-2).join("/");s.push(`read_file loop: "${$}" read ${ce}\xD7 (file already in context)`)}let ne=0,S="";for(let[$,P]of ee){if(P.ranges.length<4)continue;let R=[],B=!1;for(let[T,x]of P.ranges){if(R.length>0&&X(T,x,R)){B=!0;break}R.push([T,x])}!B&&P.ranges.length>ne&&(ne=P.ranges.length,S=$)}if(ne>=4){e-=.5;let $=S.split("/").slice(-2).join("/");s.push(`File-scroll pattern: "${$}" read in ${ne} sequential sections \u2014 use grep instead`)}let Te=new Map;for(let $ of a)if($.name==="grep"&&$.input?.path&&$.input?.pattern){let P=$.input.path;Te.has(P)||Te.set(P,new Set),Te.get(P).add($.input.pattern)}let H=0,K="";for(let[$,P]of Te)$.split("/").pop().includes(".")&&P.size>H&&(H=P.size,K=$);if(H>=3){e-=.75;let $=K.split("/").slice(-2).join("/");s.push(`grep flood on single file: "${$}" searched ${H}\xD7 with different patterns (file already in context)`)}{let $=new Set,P=new Set,R=/^(test_|demo_|temp_|tmp_|scratch_)/;for(let T of n){if(T.name==="write_file"&&T.input?.path){let x=T.input.path.split("/").pop(),se=T.input.path.includes("/tests/");R.test(x)&&!se&&$.add(T.input.path)}if((T.name==="bash"||T.name==="ssh_exec")&&T.input?.command){let x=T.input.command.match(/\brm\s+(?:-\w+\s+)?(\S+)/g);if(x)for(let se of x){let we=se.split(/\s+/),ge=we[we.length-1];for(let he of $)(he.endsWith(ge)||ge.endsWith(he.split("/").pop()))&&P.add(he)}}}let B=P.size;if(B>=1){let T=Math.min(B*.25,.5);e-=T;let x=[...P].map(se=>se.split("/").pop()).join(", ");s.push(`Temp file write-then-delete: ${x} \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 P="";if(typeof $.content=="string"?P=$.content:Array.isArray($.content)&&(P=$.content.filter(ge=>ge&&(ge.type==="text"||typeof ge=="string")).map(ge=>typeof ge=="string"?ge:ge.text||"").join("")),P.length<=5e3)continue;let R=P.split(/(?<=\. )/).filter(ge=>ge.trim().length>0);if(R.length<6)continue;let B=new Map;for(let ge=0;ge<=R.length-3;ge++){let he=R.slice(ge,ge+3).join("").trim();he.length>30&&B.set(he,(B.get(he)||0)+1)}let T=0,x="";for(let[ge,he]of B)he>T&&(T=he,x=ge);if(T<3)continue;let we=x.length*T/P.length;if(we>=.4||T>=10){e-=1.5,s.push(`llm output loop: assistant message repeated content detected (${T}\xD7 same paragraph, ${Math.round(we*100)}% repeated)`);break}}{let $=new Set(["read_file","list_directory","search_files","glob","grep"]),P=t.some(B=>Array.isArray(B.tool_calls)?B.tool_calls.some(T=>$.has(T.function?.name)):Array.isArray(B.content)?B.content.some(T=>T.type==="tool_use"&&$.has(T.name)):!1);t.some(B=>B.role==="assistant"&&typeof B.content=="string"&&(B.content.includes("## Steps")||B.content.includes("/plan approve")))&&!P&&(e-=2,s.push("plan written without reading any files \u2014 LLM invented data structures from training knowledge (hallucination risk)"))}let ve=o.filter($=>$.content.startsWith("BLOCKED:")&&!$.content.includes("BLOCKED: sed -n")&&!$.content.includes("SSH paused")&&!$.content.includes("SSH temporarily paused"));if(ve.length>0){let $=Math.min(ve.length*.5,1.5);e-=$,s.push(`${ve.length} tool call${ve.length===1?"":"s"} blocked (agent attempted denied actions)`)}let Be=t.filter($=>{let P=typeof $.content=="string"?$.content:"";return/\[SYSTEM WARNING\] Context wiped \d+×/.test(P)}).length;if(Be>0){let $=Math.min(Be*1,2);e-=$,s.push(`Super-nuclear context wipe fired ${Be}\xD7 (context collapse \u2014 task too large or read loops)`)}{let $=!1,P=!1,R=!1;for(let T of n){if(T.name!=="bash")continue;let x=(T.input?.command||T.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)&&(P=!0),/\bfind\s+\S/.test(x)&&!/git\b|npm\b|-exec\b/.test(x)&&(R=!0)}let B=[$,P,R].filter(Boolean).length;if(B>0){let T=Math.min(B*.25,.75);e-=T;let x=[];$&&x.push("cat (use read_file)"),P&&x.push("ls (use list_directory)"),R&&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"))),P=n.some(x=>(x.name==="write_file"||x.name==="Write")&&x.input?.path&&x.input.path.endsWith("package.json")),R=n.filter(x=>(x.name==="bash"||x.name==="Bash")&&x.input?.command).map(x=>x.input.command),B=R.some(x=>/pip\s+install|python\s+-m\s+venv/.test(x)),T=R.some(x=>/npm\s+install/.test(x));$&&!B?(e-=1,s.push("wrote requirements.txt but never ran pip install \u2014 environment not bootstrapped")):P&&!T&&n.some(se=>(se.name==="write_file"||se.name==="Write")&&se.input?.path&&/(\/src\/|index\.js|App\.js|main\.js)/.test(se.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"),P="";$&&(typeof $.content=="string"?P=$.content:Array.isArray($.content)&&(P=$.content.filter(x=>x&&(x.type==="text"||typeof x=="string")).map(x=>typeof x=="string"?x:x.text||"").join("")));let R=P.slice(0,400),B=/^[\d\s\+\-\*\/×÷\(\)\.]+\s*=\s*[\d\s\+\-\*\/×÷\(\)\.]+[.\n]/m,T=R.split(`
632
- `).find(x=>{let se=x.trim();return se.length>0&&se.length<=30&&/^\d/.test(se)&&/=/.test(se)&&!/[a-zA-Z]/.test(se)});if(B.test(R)||T){e-=1.5;let x=(T||R.split(`
633
- `)[0]).trim().slice(0,40);s.push(`Thinking-chain leak: non-sequitur artifact at response start: "${x}"`)}}if(d&&r>0){let $=t.findIndex(R=>R.role==="assistant"),P=t.findIndex(R=>!!(Array.isArray(R.tool_calls)&&R.tool_calls.length>0||Array.isArray(R.content)&&R.content.some(B=>B&&B.type==="tool_use")));if($!==-1&&P!==-1&&$<P){let R=t[$],B="";typeof R.content=="string"?B=R.content:Array.isArray(R.content)&&(B=R.content.filter(se=>se&&(se.type==="text"||typeof se=="string")).map(se=>typeof se=="string"?se:se.text||"").join(""));let T=/ssh\s+\S+@\S+\s+"[^"]*\/[^"]*\./.test(B),x=/\/(?:home|var|etc|usr|opt|root|srv|data)\/[a-zA-Z0-9_.\-\/]+\.[a-zA-Z]{2,5}/.test(B);(T||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 R=($.match(/^```/gm)||[]).length%2!==0,B=/"\s*:\s*$/.test($.trimEnd()),T=/[,\[{]\s*$/.test($.trimEnd());(R||B||T)&&(e-=.75,s.push("Truncated response: last assistant message ends mid-code-block or mid-JSON (model hit token limit)"))}}{let $=[];t.forEach((R,B)=>{let T=[];Array.isArray(R.tool_calls)&&R.tool_calls.forEach(x=>{if((x.function?.name||x.name||"")==="read_file"){let we={};try{we=typeof x.function?.arguments=="string"?JSON.parse(x.function.arguments):x.function?.arguments||{}}catch{}(we.path||"").endsWith(".json")&&T.push({id:x.id,path:we.path})}}),Array.isArray(R.content)&&R.content.forEach(x=>{x&&x.type==="tool_use"&&x.name==="read_file"&&(x.input?.path||"").endsWith(".json")&&T.push({id:x.id,path:x.input.path})}),T.forEach(x=>$.push({...x,msgIdx:B}))});let P=0;for(let R of $){let B=null;for(let x of t){if(x.role==="tool"&&x.tool_call_id===R.id&&typeof x.content=="string"){B=x.content;break}if(x.role==="user"&&Array.isArray(x.content)){let se=x.content.find(we=>we&&we.type==="tool_result"&&we.tool_use_id===R.id);if(se){B=typeof se.content=="string"?se.content:"";break}}}if(!B)continue;B.split(`
634
- `).filter(x=>x.trim()).length<5&&/^\s*\[/.test(B)&&!/\]\s*$/.test(B.trimEnd())&&P++}P>=1&&(e-=.75,s.push(`Shallow JSON read: ${P} .json file${P>1?"s":""} read with < 5 lines \u2014 array was incomplete, model drew conclusions from truncated data`))}{let $=o.filter(P=>/argument errors?/i.test(P.content)||/missing required (argument|parameter)/i.test(P.content)||/invalid argument/i.test(P.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,P=0,R=0;for(let B of a){if((B.name==="bash"||B.name==="Bash")&&B.input?.command&&/git\s+commit\b/.test(B.input.command)){$&&(R=Math.max(R,P)),$=!0,P=0;continue}$&&(B.name==="bash"||B.name==="Bash")&&B.input?.command&&/git\s+(status|diff|log|show)\b/.test(B.input.command)&&P++}R=Math.max(R,P),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 $e=e>=9?"A":e>=8?"B":e>=7?"C":e>=6?"D":"F",ye=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:$e,issues:s,summary:ye}}function oS(t){try{let{loadSession:e}=di(),s=e(t);return s?pm(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})`),`
631
+ `)}async function Jk(t){let e=Ge.join(t,"package.json"),s="";if(await Zt(()=>ft.access(e).then(()=>!0).catch(()=>!1)))try{let i=await ft.readFile(e,"utf-8"),a=JSON.parse(i);s=`${a.name||"?"} v${a.version||"?"}`}catch{}let[o,r]=await Promise.all([Zt(async()=>{let{stdout:i}=await ci("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),nm()]);if(r&&r.length>0){console.log(`${Ls.red} \u26A0 ${r.length} unresolved merge conflict(s):${Ls.reset}`);for(let i of r)console.log(`${Ls.red} ${i.file}${Ls.reset}`);console.log(`${Ls.yellow} \u2192 Resolve conflicts before starting tasks${Ls.reset}`)}console.log()}sm.exports={gatherProjectContext:Vk,printContext:Jk,generateFileTree:zk,_clearContextCache:()=>{Kl.clear(),Ds.clear(),ui=null,Is={result:null,expiry:0,cwd:null}}}});var fi=z((UR,am)=>{var Bt=require("fs"),di=require("path"),{atomicWrite:Zk}=In();function Oo(){return di.join(process.cwd(),".nex","sessions")}function Xl(){let t=Oo();Bt.existsSync(t)||Bt.mkdirSync(t,{recursive:!0,mode:448})}function Vl(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return di.join(Oo(),`${e}.json`)}function Jl(t,e,s={}){Xl();let n=Vl(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 Zk(n,JSON.stringify(o,null,2)),{path:n,name:t}}function rm(t){let e=Vl(t);if(!Bt.existsSync(e))return null;try{return JSON.parse(Bt.readFileSync(e,"utf-8"))}catch{return null}}function im(){Xl();let t=Oo(),e=Bt.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(Bt.readFileSync(di.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 Qk(t){let e=Vl(t);return Bt.existsSync(e)?(Bt.unlinkSync(e),!0):!1}function eS(){let t=im();return t.length===0?null:rm(t[0].name)}var Jn=null,dn=null,Ao=null;function tS(t,e={}){t.length!==0&&(Jn&&clearTimeout(Jn),dn=t,Ao=e||{},Jn=setTimeout(()=>{dn&&dn.length>0&&Jl("_autosave",dn,Ao),Jn=null,dn=null,Ao=null},5e3))}function nS(){Jn&&(clearTimeout(Jn),Jn=null),dn&&dn.length>0&&(Jl("_autosave",dn,Ao),dn=null,Ao=null)}function sS(){Xl();let t=Oo(),e=Bt.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=di.join(t,r);try{let a=Bt.statSync(i);new Date(a.mtime)<n&&(Bt.unlinkSync(i),o++)}catch{}}return o}am.exports={saveSession:Jl,loadSession:rm,listSessions:im,deleteSession:Qk,getLastSession:eS,autoSave:tS,flushAutoSave:nS,clearOldSessions:sS,_getSessionsDir:Oo}});var pi=z((WR,mm)=>{"use strict";var No=require("fs"),lm=require("path");function cm(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 oS(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 um(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 dm(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 fm(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 pm(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 hm(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=cm(t),o=um(t),r=n.length,i=oS(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 P=$.input?.command||$.input?.cmd||"";return/\bsed\s+-n\b/.test(P)});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 P=$.input?.command||$.input?.cmd||"",R=$.input?.pattern||"",B=`${P} ${R}`;return/(?:-[CAB]|--context|--after|--before)\s*[=\s]?([2-9][1-9]|\d{3,})/.test(B)||/grep.*-[CAB]\s*([2-9][1-9]|\d{3,})/.test(B)})&&(e-=1,s.push("grep used with >20 context lines (context flood risk)"));let d=t.some($=>$.role==="assistant"),f=dm(t),h=fm(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 P=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(P)})&&(e-=.5,s.push("Auto-compress triggered (context flood indicator)"));let b=pm(a),O=0,M="";for(let[$,P]of b)P>O&&(O=P,M=$);if(O>=3){let[$]=M.split("|");e-=1,s.push(`Same tool call repeated ${O}\xD7 (tool: ${$})`)}let k=!1,E=t.findIndex($=>$.role==="user"&&typeof $.content=="string"&&$.content.includes("[SYSTEM STOP]")&&$.content.includes('"valid":true'));E>=0&&n.filter(P=>P.index>E).length>0&&(k=!0),k&&(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,P=1;for(let R=1;R<N.length;R++)N[R].index<=N[R-1].index+2?P++:($=Math.max($,P),P=1);$=Math.max($,P),$>=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 P=$.input.path;te.has(P)||te.set(P,{count:0,ranges:[]});let R=te.get(P);if(R.count++,$.input.line_start!=null){let B=$.input.line_start||1,T=$.input.line_end||B+350;R.ranges.push([B,T])}}function X($,P,R){for(let[B,T]of R){let x=Math.max($,B),oe=Math.min(P,T);if(oe>x){let we=oe-x,ge=P-$||1;if(we/ge>=.7)return!0}}return!1}let ce=0,ae="";for(let[$,P]of te){if(P.count<3)continue;if(P.ranges.length===P.count){let T=!1,x=[];for(let[oe,we]of P.ranges){if(x.length>0&&X(oe,we,x)){T=!0;break}x.push([oe,we])}if(!T)continue}if(P.count-P.ranges.length<=2&&P.ranges.length>=1){let T=!1,x=[];for(let[oe,we]of P.ranges){if(x.length>0&&X(oe,we,x)){T=!0;break}x.push([oe,we])}if(!T)continue}P.count>ce&&(ce=P.count,ae=$)}if(ce>=3){e-=1;let $=ae.split("/").slice(-2).join("/");s.push(`read_file loop: "${$}" read ${ce}\xD7 (file already in context)`)}let se=0,S="";for(let[$,P]of te){if(P.ranges.length<4)continue;let R=[],B=!1;for(let[T,x]of P.ranges){if(R.length>0&&X(T,x,R)){B=!0;break}R.push([T,x])}!B&&P.ranges.length>se&&(se=P.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 Re=new Map;for(let $ of a)if($.name==="grep"&&$.input?.path&&$.input?.pattern){let P=$.input.path;Re.has(P)||Re.set(P,new Set),Re.get(P).add($.input.pattern)}let H=0,K="";for(let[$,P]of Re)$.split("/").pop().includes(".")&&P.size>H&&(H=P.size,K=$);if(H>=3){e-=.75;let $=K.split("/").slice(-2).join("/");s.push(`grep flood on single file: "${$}" searched ${H}\xD7 with different patterns (file already in context)`)}{let $=new Set,P=new Set,R=/^(test_|demo_|temp_|tmp_|scratch_)/;for(let T of n){if(T.name==="write_file"&&T.input?.path){let x=T.input.path.split("/").pop(),oe=T.input.path.includes("/tests/");R.test(x)&&!oe&&$.add(T.input.path)}if((T.name==="bash"||T.name==="ssh_exec")&&T.input?.command){let x=T.input.command.match(/\brm\s+(?:-\w+\s+)?(\S+)/g);if(x)for(let oe of x){let we=oe.split(/\s+/),ge=we[we.length-1];for(let he of $)(he.endsWith(ge)||ge.endsWith(he.split("/").pop()))&&P.add(he)}}}let B=P.size;if(B>=1){let T=Math.min(B*.25,.5);e-=T;let x=[...P].map(oe=>oe.split("/").pop()).join(", ");s.push(`Temp file write-then-delete: ${x} \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 P="";if(typeof $.content=="string"?P=$.content:Array.isArray($.content)&&(P=$.content.filter(ge=>ge&&(ge.type==="text"||typeof ge=="string")).map(ge=>typeof ge=="string"?ge:ge.text||"").join("")),P.length<=5e3)continue;let R=P.split(/(?<=\. )/).filter(ge=>ge.trim().length>0);if(R.length<6)continue;let B=new Map;for(let ge=0;ge<=R.length-3;ge++){let he=R.slice(ge,ge+3).join("").trim();he.length>30&&B.set(he,(B.get(he)||0)+1)}let T=0,x="";for(let[ge,he]of B)he>T&&(T=he,x=ge);if(T<3)continue;let we=x.length*T/P.length;if(we>=.4||T>=10){e-=1.5,s.push(`llm output loop: assistant message repeated content detected (${T}\xD7 same paragraph, ${Math.round(we*100)}% repeated)`);break}}{let $=new Set(["read_file","list_directory","search_files","glob","grep"]),P=t.some(B=>Array.isArray(B.tool_calls)?B.tool_calls.some(T=>$.has(T.function?.name)):Array.isArray(B.content)?B.content.some(T=>T.type==="tool_use"&&$.has(T.name)):!1);t.some(B=>B.role==="assistant"&&typeof B.content=="string"&&(B.content.includes("## Steps")||B.content.includes("/plan approve")))&&!P&&(e-=2,s.push("plan written without reading any files \u2014 LLM invented data structures from training knowledge (hallucination risk)"))}let ve=o.filter($=>$.content.startsWith("BLOCKED:")&&!$.content.includes("BLOCKED: sed -n")&&!$.content.includes("SSH paused")&&!$.content.includes("SSH temporarily paused"));if(ve.length>0){let $=Math.min(ve.length*.5,1.5);e-=$,s.push(`${ve.length} tool call${ve.length===1?"":"s"} blocked (agent attempted denied actions)`)}let Ue=t.filter($=>{let P=typeof $.content=="string"?$.content:"";return/\[SYSTEM WARNING\] Context wiped \d+×/.test(P)}).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,P=!1,R=!1;for(let T of n){if(T.name!=="bash")continue;let x=(T.input?.command||T.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)&&(P=!0),/\bfind\s+\S/.test(x)&&!/git\b|npm\b|-exec\b/.test(x)&&(R=!0)}let B=[$,P,R].filter(Boolean).length;if(B>0){let T=Math.min(B*.25,.75);e-=T;let x=[];$&&x.push("cat (use read_file)"),P&&x.push("ls (use list_directory)"),R&&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"))),P=n.some(x=>(x.name==="write_file"||x.name==="Write")&&x.input?.path&&x.input.path.endsWith("package.json")),R=n.filter(x=>(x.name==="bash"||x.name==="Bash")&&x.input?.command).map(x=>x.input.command),B=R.some(x=>/pip\s+install|python\s+-m\s+venv/.test(x)),T=R.some(x=>/npm\s+install/.test(x));$&&!B?(e-=1,s.push("wrote requirements.txt but never ran pip install \u2014 environment not bootstrapped")):P&&!T&&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(x=>x.role==="assistant"),P="";$&&(typeof $.content=="string"?P=$.content:Array.isArray($.content)&&(P=$.content.filter(x=>x&&(x.type==="text"||typeof x=="string")).map(x=>typeof x=="string"?x:x.text||"").join("")));let R=P.slice(0,400),B=/^[\d\s\+\-\*\/×÷\(\)\.]+\s*=\s*[\d\s\+\-\*\/×÷\(\)\.]+[.\n]/m,T=R.split(`
632
+ `).find(x=>{let oe=x.trim();return oe.length>0&&oe.length<=30&&/^\d/.test(oe)&&/=/.test(oe)&&!/[a-zA-Z]/.test(oe)});if(B.test(R)||T){e-=1.5;let x=(T||R.split(`
633
+ `)[0]).trim().slice(0,40);s.push(`Thinking-chain leak: non-sequitur artifact at response start: "${x}"`)}}if(d&&r>0){let $=t.findIndex(R=>R.role==="assistant"),P=t.findIndex(R=>!!(Array.isArray(R.tool_calls)&&R.tool_calls.length>0||Array.isArray(R.content)&&R.content.some(B=>B&&B.type==="tool_use")));if($!==-1&&P!==-1&&$<P){let R=t[$],B="";typeof R.content=="string"?B=R.content:Array.isArray(R.content)&&(B=R.content.filter(oe=>oe&&(oe.type==="text"||typeof oe=="string")).map(oe=>typeof oe=="string"?oe:oe.text||"").join(""));let T=/ssh\s+\S+@\S+\s+"[^"]*\/[^"]*\./.test(B),x=/\/(?:home|var|etc|usr|opt|root|srv|data)\/[a-zA-Z0-9_.\-\/]+\.[a-zA-Z]{2,5}/.test(B);(T||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 R=($.match(/^```/gm)||[]).length%2!==0,B=/"\s*:\s*$/.test($.trimEnd()),T=/[,\[{]\s*$/.test($.trimEnd());(R||B||T)&&(e-=.75,s.push("Truncated response: last assistant message ends mid-code-block or mid-JSON (model hit token limit)"))}}{let $=[];t.forEach((R,B)=>{let T=[];Array.isArray(R.tool_calls)&&R.tool_calls.forEach(x=>{if((x.function?.name||x.name||"")==="read_file"){let we={};try{we=typeof x.function?.arguments=="string"?JSON.parse(x.function.arguments):x.function?.arguments||{}}catch{}(we.path||"").endsWith(".json")&&T.push({id:x.id,path:we.path})}}),Array.isArray(R.content)&&R.content.forEach(x=>{x&&x.type==="tool_use"&&x.name==="read_file"&&(x.input?.path||"").endsWith(".json")&&T.push({id:x.id,path:x.input.path})}),T.forEach(x=>$.push({...x,msgIdx:B}))});let P=0;for(let R of $){let B=null;for(let x of t){if(x.role==="tool"&&x.tool_call_id===R.id&&typeof x.content=="string"){B=x.content;break}if(x.role==="user"&&Array.isArray(x.content)){let oe=x.content.find(we=>we&&we.type==="tool_result"&&we.tool_use_id===R.id);if(oe){B=typeof oe.content=="string"?oe.content:"";break}}}if(!B)continue;B.split(`
634
+ `).filter(x=>x.trim()).length<5&&/^\s*\[/.test(B)&&!/\]\s*$/.test(B.trimEnd())&&P++}P>=1&&(e-=.75,s.push(`Shallow JSON read: ${P} .json file${P>1?"s":""} read with < 5 lines \u2014 array was incomplete, model drew conclusions from truncated data`))}{let $=o.filter(P=>/argument errors?/i.test(P.content)||/missing required (argument|parameter)/i.test(P.content)||/invalid argument/i.test(P.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,P=0,R=0;for(let B of a){if((B.name==="bash"||B.name==="Bash")&&B.input?.command&&/git\s+commit\b/.test(B.input.command)){$&&(R=Math.max(R,P)),$=!0,P=0;continue}$&&(B.name==="bash"||B.name==="Bash")&&B.input?.command&&/git\s+(status|diff|log|show)\b/.test(B.input.command)&&P++}R=Math.max(R,P),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 $e=e>=9?"A":e>=8?"B":e>=7?"C":e>=6?"D":"F",ye=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:$e,issues:s,summary:ye}}function rS(t){try{let{loadSession:e}=fi(),s=e(t);return s?hm(s.messages||[]):null}catch{return null}}function iS(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})`),`
635
635
  ${o}${f}${r}`}let l="";for(let u of a.slice(0,4))l+=`
636
636
  ${i}\u26A0${r} ${o}${u}${r}`;let c=a.length-4;return c>0&&(l+=`
637
- ${o}(+${c} more)${r}`),l}function iS(t,e={}){try{let s=am.join(process.cwd(),".nex");No.existsSync(s)||No.mkdirSync(s,{recursive:!0});let n=am.join(s,"benchmark-history.json"),o=[];if(No.existsSync(n))try{o=JSON.parse(No.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)),No.writeFileSync(n,JSON.stringify(o,null,2))}catch{}}hm.exports={scoreMessages:pm,scoreSession:oS,formatScore:rS,appendScoreHistory:iS,_extractToolCalls:lm,_extractToolResults:cm,_getLastAssistantText:um,_getLastNAssistantTexts:dm,_countDuplicateToolCalls:fm}});var js=z((WR,_m)=>{"use strict";var aS=require("os"),Vl=require("path"),$n=require("fs"),Mo=Vl.join(aS.homedir(),".nex-code","model-routing.json"),pi={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}},mm=["agentic","frontend","sysadmin","data","coding"];function lS(t){if(!t||t.length<8)return null;for(let e of mm){let s=pi[e];if(!s.pattern||s.pattern.test(t))return s}return pi.coding}function Po(){try{if($n.existsSync(Mo))return JSON.parse($n.readFileSync(Mo,"utf-8"))}catch{}return{}}function gm(t){let e=pi[t];return e?.envVar&&process.env[e.envVar]?process.env[e.envVar]:Po()[t]||null}var ym={plan:10,implement:35,verify:8},Jl={plan:"qwen3-coder:480b",implement:null,verify:"devstral-small-2:24b"};function wm(){let t=Po();if(t.phases&&Object.keys(t.phases).length>0)return t.phases;try{let{getActiveProviderName:e}=Ve();if(e()==="ollama")return Jl}catch{}return process.env.NEX_PHASE_ROUTING==="1"?Jl:null}function cS(t,e){let s=wm();return s?.[t]?s[t]:e?gm(e):null}function uS(t){return Po().phaseBudgets?.[t]||ym[t]||20}function dS(){return process.env.NEX_PHASE_ROUTING==="0"?!1:wm()!==null}function fS(t){let e=Vl.dirname(Mo);$n.existsSync(e)||$n.mkdirSync(e,{recursive:!0});let s=Po(),n={...s,...t};!t.phases&&s.phases&&(n.phases=s.phases),!t.phaseBudgets&&s.phaseBudgets&&(n.phaseBudgets=s.phaseBudgets),$n.writeFileSync(Mo,JSON.stringify(n,null,2));try{let o=Vl.join(e,".env"),r="";$n.existsSync(o)&&(r=$n.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)),$n.writeFileSync(o,i.filter(l=>l.trim()!=="").join(`
637
+ ${o}(+${c} more)${r}`),l}function aS(t,e={}){try{let s=lm.join(process.cwd(),".nex");No.existsSync(s)||No.mkdirSync(s,{recursive:!0});let n=lm.join(s,"benchmark-history.json"),o=[];if(No.existsSync(n))try{o=JSON.parse(No.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)),No.writeFileSync(n,JSON.stringify(o,null,2))}catch{}}mm.exports={scoreMessages:hm,scoreSession:rS,formatScore:iS,appendScoreHistory:aS,_extractToolCalls:cm,_extractToolResults:um,_getLastAssistantText:dm,_getLastNAssistantTexts:fm,_countDuplicateToolCalls:pm}});var js=z((HR,$m)=>{"use strict";var lS=require("os"),Zl=require("path"),xn=require("fs"),Mo=Zl.join(lS.homedir(),".nex-code","model-routing.json"),hi={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}},gm=["agentic","frontend","sysadmin","data","coding"];function cS(t){if(!t||t.length<8)return null;for(let e of gm){let s=hi[e];if(!s.pattern||s.pattern.test(t))return s}return hi.coding}function Po(){try{if(xn.existsSync(Mo))return JSON.parse(xn.readFileSync(Mo,"utf-8"))}catch{}return{}}function ym(t){let e=hi[t];return e?.envVar&&process.env[e.envVar]?process.env[e.envVar]:Po()[t]||null}var wm={plan:10,implement:35,verify:8},Ql={plan:"qwen3-coder:480b",implement:null,verify:"devstral-small-2:24b"};function _m(){let t=Po();if(t.phases&&Object.keys(t.phases).length>0)return t.phases;try{let{getActiveProviderName:e}=Ze();if(e()==="ollama")return Ql}catch{}return process.env.NEX_PHASE_ROUTING==="1"?Ql:null}function uS(t,e){let s=_m();return s?.[t]?s[t]:e?ym(e):null}function dS(t){return Po().phaseBudgets?.[t]||wm[t]||20}function fS(){return process.env.NEX_PHASE_ROUTING==="0"?!1:_m()!==null}function pS(t){let e=Zl.dirname(Mo);xn.existsSync(e)||xn.mkdirSync(e,{recursive:!0});let s=Po(),n={...s,...t};!t.phases&&s.phases&&(n.phases=s.phases),!t.phaseBudgets&&s.phaseBudgets&&(n.phaseBudgets=s.phaseBudgets),xn.writeFileSync(Mo,JSON.stringify(n,null,2));try{let o=Zl.join(e,".env"),r="";xn.existsSync(o)&&(r=xn.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)),xn.writeFileSync(o,i.filter(l=>l.trim()!=="").join(`
638
638
  `)+`
639
- `)}catch{}}_m.exports={CATEGORIES:pi,DETECTION_ORDER:mm,detectCategory:lS,getModelForCategory:gm,getModelForPhase:cS,getPhaseBudget:uS,isPhaseRoutingEnabled:dS,DEFAULT_PHASE_BUDGETS:ym,BUILTIN_PHASE_DEFAULTS:Jl,saveRoutingConfig:fS,loadRoutingConfig:Po,ROUTING_CONFIG_PATH:Mo}});var km=z((HR,xm)=>{"use strict";var Vn=require("fs"),Lo=require("path"),pS=require("os"),{detectCategory:hS}=js(),qs=Lo.join(pS.homedir(),".nex-code","examples"),Zl=Lo.join(__dirname,"..","examples");function $m(t){try{let s=Vn.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(`
639
+ `)}catch{}}$m.exports={CATEGORIES:hi,DETECTION_ORDER:gm,detectCategory:cS,getModelForCategory:ym,getModelForPhase:uS,getPhaseBudget:dS,isPhaseRoutingEnabled:fS,DEFAULT_PHASE_BUDGETS:wm,BUILTIN_PHASE_DEFAULTS:Ql,saveRoutingConfig:pS,loadRoutingConfig:Po,ROUTING_CONFIG_PATH:Mo}});var Sm=z((YR,km)=>{"use strict";var Zn=require("fs"),Lo=require("path"),hS=require("os"),{detectCategory:mS}=js(),qs=Lo.join(hS.homedir(),".nex-code","examples"),ec=Lo.join(__dirname,"..","examples");function bm(t){try{let s=Zn.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(`
640
640
  A: |`);if(r===-1)return null;let i=s.slice(r+5),a=[],l=0;for(let u of i.split(`
641
641
  `))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(`
642
- `).trim();return{user:o,assistant:c}}catch{return null}}function bm(t){let e=`${t}.md`,s=Lo.join(qs,e);if(Vn.existsSync(s)){let o=$m(s);if(o)return o}let n=Lo.join(Zl,e);return Vn.existsSync(n)?$m(n):null}function mS(t){if(process.env.NEX_FEW_SHOT==="0"||!t||t.length<8)return null;let e=hS(t);return e?bm(e.id):null}function gS(){let t=new Set;for(let e of[qs,Zl])try{for(let s of Vn.readdirSync(e))s.endsWith(".md")&&t.add(s.replace(".md",""))}catch{}return[...t].sort()}function yS(t,e){Vn.existsSync(qs)||Vn.mkdirSync(qs,{recursive:!0});let s=`<!-- Auto-extracted from high-scoring session \u2014 edit as needed -->
642
+ `).trim();return{user:o,assistant:c}}catch{return null}}function xm(t){let e=`${t}.md`,s=Lo.join(qs,e);if(Zn.existsSync(s)){let o=bm(s);if(o)return o}let n=Lo.join(ec,e);return Zn.existsSync(n)?bm(n):null}function gS(t){if(process.env.NEX_FEW_SHOT==="0"||!t||t.length<8)return null;let e=mS(t);return e?xm(e.id):null}function yS(){let t=new Set;for(let e of[qs,ec])try{for(let s of Zn.readdirSync(e))s.endsWith(".md")&&t.add(s.replace(".md",""))}catch{}return[...t].sort()}function wS(t,e){Zn.existsSync(qs)||Zn.mkdirSync(qs,{recursive:!0});let s=`<!-- Auto-extracted from high-scoring session \u2014 edit as needed -->
643
643
 
644
644
  user: ${e.user}
645
645
 
@@ -647,14 +647,14 @@ A: |
647
647
  ${e.assistant.split(`
648
648
  `).map(n=>` ${n}`).join(`
649
649
  `)}
650
- `;Vn.writeFileSync(Lo.join(qs,`${t}.md`),s,"utf-8")}xm.exports={getFewShotForInput:mS,loadExampleForCategory:bm,listAvailableExamples:gS,savePrivateExample:yS,PRIVATE_EXAMPLES_DIR:qs,BUNDLED_EXAMPLES_DIR:Zl}});var Cm=z((GR,Rm)=>{var bt=require("fs"),Fs=require("path"),{C:YR}=ze(),{atomicWrite:wS,withFileLockSync:_S}=Pn(),hi={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"},Bs={...hi};function Sm(){let t=Fs.join(process.cwd(),".nex","config.json");if(bt.existsSync(t))try{let e=JSON.parse(bt.readFileSync(t,"utf-8"));e.permissions&&(Bs={...hi,...e.permissions})}catch{}}function $S(){let t=Fs.join(process.cwd(),".nex"),e=Fs.join(t,"config.json");bt.existsSync(t)||bt.mkdirSync(t,{recursive:!0}),_S(e,()=>{let s={};if(bt.existsSync(e))try{s=JSON.parse(bt.readFileSync(e,"utf-8"))}catch{s={}}s.permissions=Bs,wS(e,JSON.stringify(s,null,2))})}function vm(t){return Bs[t]||"ask"}function bS(t,e){return["allow","ask","deny"].includes(e)?(Bs[t]=e,!0):!1}function xS(t){return vm(t)}function kS(){return Object.entries(Bs).map(([t,e])=>({tool:t,mode:e}))}function SS(){Bs={...hi}}var Io={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 Em(){let t=Fs.join(process.cwd(),".nex","config.json");try{return bt.existsSync(t)&&JSON.parse(bt.readFileSync(t,"utf-8")).teamPermissions||null}catch{return null}}function vS(t){let e=Fs.join(process.cwd(),".nex"),s=Fs.join(e,"config.json");bt.existsSync(e)||bt.mkdirSync(e,{recursive:!0});let n={};try{bt.existsSync(s)&&(n=JSON.parse(bt.readFileSync(s,"utf-8")))}catch{n={}}n.teamPermissions=t,bt.writeFileSync(s,JSON.stringify(n,null,2),"utf-8")}function Tm(){let t=Em();if(!t)return Io.admin;let e=t.role||"admin",s=Io[e]||Io.admin;return{...s,...t.overrides,blockedTools:[...s.blockedTools||[],...t.overrides?.blockedTools||[]]}}function ES(t){let e=Tm();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 TS(){return Object.entries(Io).map(([t,e])=>({name:t,description:e.description,toolCount:e.allowedTools?`${e.allowedTools.length} allowed`:"all allowed",blockedCount:e.blockedTools.length}))}Sm();Rm.exports={getPermission:vm,setPermission:bS,checkPermission:xS,listPermissions:kS,loadPermissions:Sm,savePermissions:$S,resetPermissions:SS,DEFAULT_PERMISSIONS:hi,PERMISSION_PRESETS:Io,loadPresetConfig:Em,savePresetConfig:vS,getEffectivePreset:Tm,isToolAllowed:ES,listPresets:TS}});var yi=z((KR,Pm)=>{var Zn=require("fs"),mi=require("path"),zR=require("readline"),{C:Se}=ze(),xe=null,ec=!1,tc=null,Am=new Set(["read_file","list_directory","search_files","glob","grep","web_search","web_fetch","git_status","git_diff","git_log","git_show"]);function gi(){return mi.join(process.cwd(),".nex","plans")}function Om(){let t=gi();Zn.existsSync(t)||Zn.mkdirSync(t,{recursive:!0})}function RS(t,e=[]){return xe={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()},xe}function CS(){return xe}function AS(t){ec=t}function OS(){return ec}function NS(){return!xe||xe.status!=="draft"?!1:(xe.status="approved",xe.updatedAt=new Date().toISOString(),!0)}function MS(){return!xe||xe.status!=="approved"?!1:(xe.status="executing",!0)}function Ql(t,e){return!xe||t<0||t>=xe.steps.length?!1:(xe.steps[t].status=e,xe.updatedAt=new Date().toISOString(),xe.steps.every(s=>s.status==="done"||s.status==="skipped")&&(xe.status="completed"),!0)}function PS(t){if(!t)return`${Se.dim}No active plan${Se.reset}`;let e={draft:`${Se.yellow}DRAFT${Se.reset}`,approved:`${Se.green}APPROVED${Se.reset}`,executing:`${Se.blue}EXECUTING${Se.reset}`,completed:`${Se.green}COMPLETED${Se.reset}`},s=[];s.push(`
650
+ `;Zn.writeFileSync(Lo.join(qs,`${t}.md`),s,"utf-8")}km.exports={getFewShotForInput:gS,loadExampleForCategory:xm,listAvailableExamples:yS,savePrivateExample:wS,PRIVATE_EXAMPLES_DIR:qs,BUNDLED_EXAMPLES_DIR:ec}});var Am=z((zR,Cm)=>{var kt=require("fs"),Fs=require("path"),{C:GR}=Ke(),{atomicWrite:_S,withFileLockSync:$S}=In(),mi={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"},Bs={...mi};function vm(){let t=Fs.join(process.cwd(),".nex","config.json");if(kt.existsSync(t))try{let e=JSON.parse(kt.readFileSync(t,"utf-8"));e.permissions&&(Bs={...mi,...e.permissions})}catch{}}function bS(){let t=Fs.join(process.cwd(),".nex"),e=Fs.join(t,"config.json");kt.existsSync(t)||kt.mkdirSync(t,{recursive:!0}),$S(e,()=>{let s={};if(kt.existsSync(e))try{s=JSON.parse(kt.readFileSync(e,"utf-8"))}catch{s={}}s.permissions=Bs,_S(e,JSON.stringify(s,null,2))})}function Em(t){return Bs[t]||"ask"}function xS(t,e){return["allow","ask","deny"].includes(e)?(Bs[t]=e,!0):!1}function kS(t){return Em(t)}function SS(){return Object.entries(Bs).map(([t,e])=>({tool:t,mode:e}))}function vS(){Bs={...mi}}var Io={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 Tm(){let t=Fs.join(process.cwd(),".nex","config.json");try{return kt.existsSync(t)&&JSON.parse(kt.readFileSync(t,"utf-8")).teamPermissions||null}catch{return null}}function ES(t){let e=Fs.join(process.cwd(),".nex"),s=Fs.join(e,"config.json");kt.existsSync(e)||kt.mkdirSync(e,{recursive:!0});let n={};try{kt.existsSync(s)&&(n=JSON.parse(kt.readFileSync(s,"utf-8")))}catch{n={}}n.teamPermissions=t,kt.writeFileSync(s,JSON.stringify(n,null,2),"utf-8")}function Rm(){let t=Tm();if(!t)return Io.admin;let e=t.role||"admin",s=Io[e]||Io.admin;return{...s,...t.overrides,blockedTools:[...s.blockedTools||[],...t.overrides?.blockedTools||[]]}}function TS(t){let e=Rm();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 RS(){return Object.entries(Io).map(([t,e])=>({name:t,description:e.description,toolCount:e.allowedTools?`${e.allowedTools.length} allowed`:"all allowed",blockedCount:e.blockedTools.length}))}vm();Cm.exports={getPermission:Em,setPermission:xS,checkPermission:kS,listPermissions:SS,loadPermissions:vm,savePermissions:bS,resetPermissions:vS,DEFAULT_PERMISSIONS:mi,PERMISSION_PRESETS:Io,loadPresetConfig:Tm,savePresetConfig:ES,getEffectivePreset:Rm,isToolAllowed:TS,listPresets:RS}});var wi=z((XR,Lm)=>{var es=require("fs"),gi=require("path"),KR=require("readline"),{C:Se}=Ke(),xe=null,nc=!1,sc=null,Om=new Set(["read_file","list_directory","search_files","glob","grep","web_search","web_fetch","git_status","git_diff","git_log","git_show"]);function yi(){return gi.join(process.cwd(),".nex","plans")}function Nm(){let t=yi();es.existsSync(t)||es.mkdirSync(t,{recursive:!0})}function CS(t,e=[]){return xe={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()},xe}function AS(){return xe}function OS(t){nc=t}function NS(){return nc}function MS(){return!xe||xe.status!=="draft"?!1:(xe.status="approved",xe.updatedAt=new Date().toISOString(),!0)}function PS(){return!xe||xe.status!=="approved"?!1:(xe.status="executing",!0)}function tc(t,e){return!xe||t<0||t>=xe.steps.length?!1:(xe.steps[t].status=e,xe.updatedAt=new Date().toISOString(),xe.steps.every(s=>s.status==="done"||s.status==="skipped")&&(xe.status="completed"),!0)}function LS(t){if(!t)return`${Se.dim}No active plan${Se.reset}`;let e={draft:`${Se.yellow}DRAFT${Se.reset}`,approved:`${Se.green}APPROVED${Se.reset}`,executing:`${Se.blue}EXECUTING${Se.reset}`,completed:`${Se.green}COMPLETED${Se.reset}`},s=[];s.push(`
651
651
  ${Se.bold}${Se.cyan}Plan: ${t.task}${Se.reset}`),s.push(`${Se.dim}Status: ${e[t.status]||t.status}${Se.reset}
652
652
  `);for(let n=0;n<t.steps.length;n++){let o=t.steps[n],r;switch(o.status){case"done":r=`${Se.green}\u2713${Se.reset}`;break;case"in_progress":r=`${Se.blue}\u2192${Se.reset}`;break;case"skipped":r=`${Se.dim}\u25CB${Se.reset}`;break;default:r=`${Se.dim} ${Se.reset}`}s.push(` ${r} ${Se.bold}Step ${n+1}:${Se.reset} ${o.description}`),o.files.length>0&&s.push(` ${Se.dim}Files: ${o.files.join(", ")}${Se.reset}`)}return s.push(""),s.join(`
653
- `)}function LS(t){if(t||(t=xe),!t)return null;Om();let e=mi.join(gi(),`${t.name}.json`);return Zn.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function IS(t){let e=mi.join(gi(),`${t}.json`);if(!Zn.existsSync(e))return null;try{let s=JSON.parse(Zn.readFileSync(e,"utf-8"));return xe=s,s}catch{return null}}function DS(){Om();let t=gi(),e=Zn.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(Zn.readFileSync(mi.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 jS(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 qS(t){tc=t}function FS(){return tc}function BS(){xe=null,ec=!1,tc=null,YS()}function US(){return`
653
+ `)}function IS(t){if(t||(t=xe),!t)return null;Nm();let e=gi.join(yi(),`${t.name}.json`);return es.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function DS(t){let e=gi.join(yi(),`${t}.json`);if(!es.existsSync(e))return null;try{let s=JSON.parse(es.readFileSync(e,"utf-8"));return xe=s,s}catch{return null}}function jS(){Nm();let t=yi(),e=es.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(es.readFileSync(gi.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 qS(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 FS(t){sc=t}function BS(){return sc}function US(){xe=null,nc=!1,sc=null,GS()}function WS(){return`
654
654
  PLAN MODE ACTIVE: You are in analysis-only mode. You MUST NOT execute any changes.
655
655
 
656
656
  # Allowed Tools (read-only)
657
- You may ONLY use these tools: ${[...Am].join(", ")}
657
+ You may ONLY use these tools: ${[...Om].join(", ")}
658
658
  Any other tool call will be blocked and returned with an error.
659
659
 
660
660
  # MANDATORY: Read Before You Plan
@@ -698,23 +698,23 @@ Bullet list of potential issues and mitigations.
698
698
  - Order steps by dependency (later steps may depend on earlier ones).
699
699
  - After presenting the plan, tell the user to type \`/plan approve\` to proceed.
700
700
  - Do NOT make any file changes \u2014 your role is analysis and planning only.
701
- - 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 Jn=0;function WS(){!xe||xe.status!=="executing"||(Jn>0&&Ql(Jn-1,"done"),Jn<xe.steps.length&&(Ql(Jn,"in_progress"),Jn++))}function HS(){if(!xe||xe.status!=="executing"||xe.steps.length===0)return null;let t=Math.min(Jn,xe.steps.length),e=xe.steps.length,s=Math.max(0,t-1),n=xe.steps[s]?.description||"";return{current:t,total:e,description:n}}function YS(){Jn=0}var Nm=["interactive","semi-auto","autonomous"],Mm="interactive";function GS(t){return Nm.includes(t)?(Mm=t,!0):!1}function zS(){return Mm}Pm.exports={createPlan:RS,getActivePlan:CS,setPlanMode:AS,isPlanMode:OS,approvePlan:NS,startExecution:MS,updateStep:Ql,formatPlan:PS,savePlan:LS,loadPlan:IS,listPlans:DS,clearPlan:BS,getPlanModePrompt:US,setPlanContent:qS,getPlanContent:FS,extractStepsFromText:jS,advancePlanStep:WS,getPlanStepInfo:HS,PLAN_MODE_ALLOWED_TOOLS:Am,setAutonomyLevel:GS,getAutonomyLevel:zS,AUTONOMY_LEVELS:Nm}});var Ym=z((XR,Hm)=>{var{C:v}=ze();function Lm(){return Math.max(10,(process.stdout.columns||80)-2)}function KS(t){if(!t)return"";let e=t.split(`
702
- `),s=[],n=!1,o="";for(let r of e){let i=Lm();if(r.trim().startsWith("```")){if(n)s.push(`${v.dim}${"\u2500".repeat(40)}${v.reset}`),n=!1,o="";else{n=!0,o=r.trim().substring(3).trim();let a=o?` ${o} `:"";s.push(`${v.dim}${"\u2500".repeat(3)}${a}${"\u2500".repeat(Math.max(0,37-a.length))}${v.reset}`)}continue}if(n){s.push(` ${sc(r,o)}`);continue}if(r.startsWith("### ")){s.push(`${v.bold}${v.cyan} ${Qn(r.substring(4))}${v.reset}`);continue}if(r.startsWith("## ")){s.push(`${v.bold}${v.cyan} ${Qn(r.substring(3))}${v.reset}`);continue}if(r.startsWith("# ")){s.push(`${v.bold}${v.cyan}${Qn(r.substring(2))}${v.reset}`);continue}if(/^\s*[-*]\s/.test(r)){let a=r.match(/^(\s*)/)[1],l=r.replace(/^\s*[-*]\s/,""),c=`${a}${v.cyan}\u2022${v.reset} ${es(l)}`;s.push(ts(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}${v.cyan}${c}.${v.reset} ${es(u)}`,f=l+" ".repeat(c.length+2);s.push(ts(d,i,f));continue}}s.push(ts(es(r),i))}return s.join(`
703
- `)}function Qn(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function es(t){return t?t.replace(/`([^`]+)`/g,`${v.cyan}$1${v.reset}`).replace(/\*\*([^*]+)\*\*/g,`${v.bold}$1${v.reset}`).replace(/\*([^*]+)\*/g,`${v.dim}$1${v.reset}`).replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${v.cyan}$1${v.reset} ${v.dim}($2)${v.reset}`):""}function sc(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?Im(t):e==="bash"||e==="sh"||e==="shell"||e==="zsh"?Dm(t):e==="json"||e==="jsonc"?jm(t):e==="python"||e==="py"?qm(t):e==="go"||e==="golang"?Fm(t):e==="rust"||e==="rs"?Bm(t):e==="css"||e==="scss"||e==="less"?Um(t):e==="html"||e==="xml"||e==="svg"||e==="htm"?Wm(t):t:""}function Im(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,`${v.yellow}$1${v.reset}`),r=r.replace(e,`${v.magenta}$1${v.reset}`),r=r.replace(s,`${v.green}$&${v.reset}`),r=r.replace(n,`${v.dim}$1${v.reset}`),r}function Dm(t){let e=/^(\s*)([\w-]+)/,s=/(--?\w[\w-]*)/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(#.*$)/,r=t;return r=r.replace(s,`${v.cyan}$1${v.reset}`),r=r.replace(e,`$1${v.green}$2${v.reset}`),r=r.replace(n,`${v.yellow}$&${v.reset}`),r=r.replace(o,`${v.dim}$1${v.reset}`),r}function jm(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,`${v.cyan}$1${v.reset}:`),r=r.replace(s,`: ${v.green}$1${v.reset}`),r=r.replace(n,`: ${v.yellow}$1${v.reset}`),r=r.replace(o,`: ${v.magenta}$1${v.reset}`),r}function qm(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,`${v.yellow}$1${v.reset}`),i=i.replace(e,`${v.magenta}$1${v.reset}`),i=i.replace(r,`${v.cyan}$1${v.reset}`),i=i.replace(s,`${v.green}$&${v.reset}`),i=i.replace(n,`${v.dim}$1${v.reset}`),i}function Fm(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,`${v.yellow}$1${v.reset}`),i=i.replace(s,`${v.cyan}$1${v.reset}`),i=i.replace(e,`${v.magenta}$1${v.reset}`),i=i.replace(n,`${v.green}$&${v.reset}`),i=i.replace(o,`${v.dim}$1${v.reset}`),i}function Bm(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,`${v.yellow}$1${v.reset}`),a=a.replace(s,`${v.cyan}$1${v.reset}`),a=a.replace(e,`${v.magenta}$1${v.reset}`),a=a.replace(i,`${v.yellow}$1${v.reset}`),a=a.replace(n,`${v.green}$&${v.reset}`),a=a.replace(o,`${v.dim}$1${v.reset}`),a}function Um(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,`${v.yellow}$1${v.reset}`),a=a.replace(o,`${v.yellow}$1${v.reset}`),a=a.replace(e,`$1${v.cyan}$2${v.reset}:`),a=a.replace(n,`$1${v.magenta}$&${v.reset}`),a=a.replace(r,`${v.dim}$1${v.reset}`),a}function Wm(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,`${v.dim}$1${v.reset}`),i=i.replace(n,`${v.green}$&${v.reset}`),i=i.replace(e,`<${v.magenta}$1${v.reset}`),i=i.replace(s,` ${v.cyan}$1${v.reset}=`),i=i.replace(r,`${v.yellow}$1${v.reset}`),i}function ts(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)+`
701
+ - 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 Qn=0;function HS(){!xe||xe.status!=="executing"||(Qn>0&&tc(Qn-1,"done"),Qn<xe.steps.length&&(tc(Qn,"in_progress"),Qn++))}function YS(){if(!xe||xe.status!=="executing"||xe.steps.length===0)return null;let t=Math.min(Qn,xe.steps.length),e=xe.steps.length,s=Math.max(0,t-1),n=xe.steps[s]?.description||"";return{current:t,total:e,description:n}}function GS(){Qn=0}var Mm=["interactive","semi-auto","autonomous"],Pm="interactive";function zS(t){return Mm.includes(t)?(Pm=t,!0):!1}function KS(){return Pm}Lm.exports={createPlan:CS,getActivePlan:AS,setPlanMode:OS,isPlanMode:NS,approvePlan:MS,startExecution:PS,updateStep:tc,formatPlan:LS,savePlan:IS,loadPlan:DS,listPlans:jS,clearPlan:US,getPlanModePrompt:WS,setPlanContent:FS,getPlanContent:BS,extractStepsFromText:qS,advancePlanStep:HS,getPlanStepInfo:YS,PLAN_MODE_ALLOWED_TOOLS:Om,setAutonomyLevel:zS,getAutonomyLevel:KS,AUTONOMY_LEVELS:Mm}});var Gm=z((VR,Ym)=>{var{C:v}=Ke();function Im(){return Math.max(10,(process.stdout.columns||80)-2)}function XS(t){if(!t)return"";let e=t.split(`
702
+ `),s=[],n=!1,o="";for(let r of e){let i=Im();if(r.trim().startsWith("```")){if(n)s.push(`${v.dim}${"\u2500".repeat(40)}${v.reset}`),n=!1,o="";else{n=!0,o=r.trim().substring(3).trim();let a=o?` ${o} `:"";s.push(`${v.dim}${"\u2500".repeat(3)}${a}${"\u2500".repeat(Math.max(0,37-a.length))}${v.reset}`)}continue}if(n){s.push(` ${rc(r,o)}`);continue}if(r.startsWith("### ")){s.push(`${v.bold}${v.cyan} ${ts(r.substring(4))}${v.reset}`);continue}if(r.startsWith("## ")){s.push(`${v.bold}${v.cyan} ${ts(r.substring(3))}${v.reset}`);continue}if(r.startsWith("# ")){s.push(`${v.bold}${v.cyan}${ts(r.substring(2))}${v.reset}`);continue}if(/^\s*[-*]\s/.test(r)){let a=r.match(/^(\s*)/)[1],l=r.replace(/^\s*[-*]\s/,""),c=`${a}${v.cyan}\u2022${v.reset} ${ns(l)}`;s.push(ss(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}${v.cyan}${c}.${v.reset} ${ns(u)}`,f=l+" ".repeat(c.length+2);s.push(ss(d,i,f));continue}}s.push(ss(ns(r),i))}return s.join(`
703
+ `)}function ts(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function ns(t){return t?t.replace(/`([^`]+)`/g,`${v.cyan}$1${v.reset}`).replace(/\*\*([^*]+)\*\*/g,`${v.bold}$1${v.reset}`).replace(/\*([^*]+)\*/g,`${v.dim}$1${v.reset}`).replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${v.cyan}$1${v.reset} ${v.dim}($2)${v.reset}`):""}function rc(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?Dm(t):e==="bash"||e==="sh"||e==="shell"||e==="zsh"?jm(t):e==="json"||e==="jsonc"?qm(t):e==="python"||e==="py"?Fm(t):e==="go"||e==="golang"?Bm(t):e==="rust"||e==="rs"?Um(t):e==="css"||e==="scss"||e==="less"?Wm(t):e==="html"||e==="xml"||e==="svg"||e==="htm"?Hm(t):t:""}function Dm(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,`${v.yellow}$1${v.reset}`),r=r.replace(e,`${v.magenta}$1${v.reset}`),r=r.replace(s,`${v.green}$&${v.reset}`),r=r.replace(n,`${v.dim}$1${v.reset}`),r}function jm(t){let e=/^(\s*)([\w-]+)/,s=/(--?\w[\w-]*)/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(#.*$)/,r=t;return r=r.replace(s,`${v.cyan}$1${v.reset}`),r=r.replace(e,`$1${v.green}$2${v.reset}`),r=r.replace(n,`${v.yellow}$&${v.reset}`),r=r.replace(o,`${v.dim}$1${v.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,`${v.cyan}$1${v.reset}:`),r=r.replace(s,`: ${v.green}$1${v.reset}`),r=r.replace(n,`: ${v.yellow}$1${v.reset}`),r=r.replace(o,`: ${v.magenta}$1${v.reset}`),r}function Fm(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,`${v.yellow}$1${v.reset}`),i=i.replace(e,`${v.magenta}$1${v.reset}`),i=i.replace(r,`${v.cyan}$1${v.reset}`),i=i.replace(s,`${v.green}$&${v.reset}`),i=i.replace(n,`${v.dim}$1${v.reset}`),i}function Bm(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,`${v.yellow}$1${v.reset}`),i=i.replace(s,`${v.cyan}$1${v.reset}`),i=i.replace(e,`${v.magenta}$1${v.reset}`),i=i.replace(n,`${v.green}$&${v.reset}`),i=i.replace(o,`${v.dim}$1${v.reset}`),i}function Um(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,`${v.yellow}$1${v.reset}`),a=a.replace(s,`${v.cyan}$1${v.reset}`),a=a.replace(e,`${v.magenta}$1${v.reset}`),a=a.replace(i,`${v.yellow}$1${v.reset}`),a=a.replace(n,`${v.green}$&${v.reset}`),a=a.replace(o,`${v.dim}$1${v.reset}`),a}function Wm(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,`${v.yellow}$1${v.reset}`),a=a.replace(o,`${v.yellow}$1${v.reset}`),a=a.replace(e,`$1${v.cyan}$2${v.reset}:`),a=a.replace(n,`$1${v.magenta}$&${v.reset}`),a=a.replace(r,`${v.dim}$1${v.reset}`),a}function Hm(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,`${v.dim}$1${v.reset}`),i=i.replace(n,`${v.green}$&${v.reset}`),i=i.replace(e,`<${v.magenta}$1${v.reset}`),i=i.replace(s,` ${v.cyan}$1${v.reset}=`),i=i.replace(r,`${v.yellow}$1${v.reset}`),i}function ss(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)+`
704
704
  `+s,a=r+1,i=a,o=s.length,r=-1;continue}o>e&&r===-1&&(n+=t.slice(a,i)+`
705
- `+s,a=i,o=s.length+1),i++}return n+=t.slice(a),n}function XS(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)=>` ${v.bold}${i.padEnd(s[a])}${v.reset} `).join("\u2502"),r=[];r.push(`${v.dim}\u250C${n.replace(/┼/g,"\u252C")}\u2510${v.reset}`),r.push(`${v.dim}\u2502${v.reset}${o}${v.dim}\u2502${v.reset}`),r.push(`${v.dim}\u251C${n}\u2524${v.reset}`);for(let i of e){let a=t.map((l,c)=>` ${(i[c]||"").padEnd(s[c])} `).join(`${v.dim}\u2502${v.reset}`);r.push(`${v.dim}\u2502${v.reset}${a}${v.dim}\u2502${v.reset}`)}return r.push(`${v.dim}\u2514${n.replace(/┼/g,"\u2534")}\u2518${v.reset}`),r.join(`
706
- `)}function VS(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?v.green:o>50?v.yellow:v.cyan;return` ${t} ${a}${"\u2588".repeat(r)}${v.dim}${"\u2591".repeat(i)}${v.reset} ${o}% (${e}/${s})`}var nc=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?`${Nt().T.cyan}\u25CF${Nt().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(`
705
+ `+s,a=i,o=s.length+1),i++}return n+=t.slice(a),n}function VS(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)=>` ${v.bold}${i.padEnd(s[a])}${v.reset} `).join("\u2502"),r=[];r.push(`${v.dim}\u250C${n.replace(/┼/g,"\u252C")}\u2510${v.reset}`),r.push(`${v.dim}\u2502${v.reset}${o}${v.dim}\u2502${v.reset}`),r.push(`${v.dim}\u251C${n}\u2524${v.reset}`);for(let i of e){let a=t.map((l,c)=>` ${(i[c]||"").padEnd(s[c])} `).join(`${v.dim}\u2502${v.reset}`);r.push(`${v.dim}\u2502${v.reset}${a}${v.dim}\u2502${v.reset}`)}return r.push(`${v.dim}\u2514${n.replace(/┼/g,"\u2534")}\u2518${v.reset}`),r.join(`
706
+ `)}function JS(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?v.green:o>50?v.yellow:v.cyan;return` ${t} ${a}${"\u2588".repeat(r)}${v.dim}${"\u2591".repeat(i)}${v.reset} ${o}% (${e}/${s})`}var oc=class{constructor(){this.buffer="",this.inCodeBlock=!1,this.codeBlockLang="",this.lineCount=0,this._cursorTimer=null,this._cursorFrame=0,this._cursorActive=!1}_safeWrite(e){try{this.lineCount+=(e.match(/\n/g)||[]).length,process.stdout.write(e)}catch(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?`${Dt().T.cyan}\u25CF${Dt().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(`
707
707
  `))!==-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(`${v.dim}${"\u2500".repeat(40)}${v.reset}
708
- `),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){let s=Lm();if(e.trim().startsWith("```")){if(this.inCodeBlock)this._safeWrite(`${v.dim}${"\u2500".repeat(40)}${v.reset}
708
+ `),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){let s=Im();if(e.trim().startsWith("```")){if(this.inCodeBlock)this._safeWrite(`${v.dim}${"\u2500".repeat(40)}${v.reset}
709
709
  `),this.inCodeBlock=!1,this.codeBlockLang="";else{this.inCodeBlock=!0,this.codeBlockLang=e.trim().substring(3).trim();let o=this.codeBlockLang?` ${this.codeBlockLang} `:"";this._safeWrite(`${v.dim}${"\u2500".repeat(3)}${o}${"\u2500".repeat(Math.max(0,37-o.length))}${v.reset}
710
- `)}return}if(this.inCodeBlock){this._safeWrite(` ${sc(e,this.codeBlockLang)}
711
- `);return}if(e.startsWith("### ")){this._safeWrite(`${v.bold}${v.cyan} ${Qn(e.substring(4))}${v.reset}
712
- `);return}if(e.startsWith("## ")){this._safeWrite(`${v.bold}${v.cyan} ${Qn(e.substring(3))}${v.reset}
713
- `);return}if(e.startsWith("# ")){this._safeWrite(`${v.bold}${v.cyan}${Qn(e.substring(2))}${v.reset}
714
- `);return}if(/^\s*[-*]\s/.test(e)){let o=e.match(/^(\s*)/)[1],r=e.replace(/^\s*[-*]\s/,""),i=`${o}${v.cyan}\u2022${v.reset} ${es(r)}`,a=ts(i,s,o+" ");this._safeWrite(`${a}
715
- `);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}${v.cyan}${i}.${v.reset} ${es(a)}`,c=r+" ".repeat(i.length+2),u=ts(l,s,c);this._safeWrite(`${u}
716
- `);return}}let n=ts(es(e),s);this._safeWrite(`${n}
717
- `)}};Hm.exports={renderMarkdown:KS,renderInline:es,stripHeadingMarkers:Qn,highlightCode:sc,highlightJS:Im,highlightBash:Dm,highlightJSON:jm,highlightPython:qm,highlightGo:Fm,highlightRust:Bm,highlightCSS:Um,highlightHTML:Wm,renderTable:XS,renderProgress:VS,wrapAnsi:ts,StreamRenderer:nc}});var Vm=z((VR,Xm)=>{var{execSync:JS}=require("child_process"),oc=require("path"),Do=require("fs"),rc=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function Gm(){return oc.join(process.cwd(),".nex","hooks")}function ZS(){return oc.join(process.cwd(),".nex","config.json")}function zm(){let t=ZS();if(!Do.existsSync(t))return{};try{return JSON.parse(Do.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function wi(t){if(!rc.includes(t))return[];let e=[],s=Gm(),n=oc.join(s,t);Do.existsSync(n)&&e.push(n);let o=zm();if(o[t]){let r=Array.isArray(o[t])?o[t]:[o[t]];e.push(...r)}return e}function Km(t,e={},s=3e4){try{return{success:!0,exitCode:0,output:JS(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 QS(t,e={}){let s=wi(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=Km(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 ev(t){return wi(t).length>0}function tv(){let t=[];for(let e of rc){let s=wi(e);s.length>0&&t.push({event:e,commands:s})}return t}function nv(){let t=Gm();return Do.existsSync(t)||Do.mkdirSync(t,{recursive:!0}),t}Xm.exports={HOOK_EVENTS:rc,loadHookConfig:zm,getHooksForEvent:wi,executeHook:Km,runHooks:QS,hasHooks:ev,listHooks:tv,initHooksDir:nv}});var dg=z((e1,ug)=>{"use strict";var{callWithRetry:Zm,runSubAgent:sv,clearAllLocks:ov}=Tl(),{parseModelSpec:Qm,getActiveProviderName:JR,getActiveModelId:ZR}=Ve(),{detectCategory:rv,getModelForCategory:Jm}=js(),{MultiProgress:iv,C:de}=ze(),{getModelBriefing:QR}=Kr(),eg=parseInt(process.env.NEX_MAX_PARALLEL||"4",10),_i=parseInt(process.env.NEX_MAX_SUBTASKS||"8",10),tg="devstral-2:123b",ng="kimi-k2.5",sg=`You are a task decomposition engine. Given a complex user request, split it into independent, atomic sub-tasks.
710
+ `)}return}if(this.inCodeBlock){this._safeWrite(` ${rc(e,this.codeBlockLang)}
711
+ `);return}if(e.startsWith("### ")){this._safeWrite(`${v.bold}${v.cyan} ${ts(e.substring(4))}${v.reset}
712
+ `);return}if(e.startsWith("## ")){this._safeWrite(`${v.bold}${v.cyan} ${ts(e.substring(3))}${v.reset}
713
+ `);return}if(e.startsWith("# ")){this._safeWrite(`${v.bold}${v.cyan}${ts(e.substring(2))}${v.reset}
714
+ `);return}if(/^\s*[-*]\s/.test(e)){let o=e.match(/^(\s*)/)[1],r=e.replace(/^\s*[-*]\s/,""),i=`${o}${v.cyan}\u2022${v.reset} ${ns(r)}`,a=ss(i,s,o+" ");this._safeWrite(`${a}
715
+ `);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}${v.cyan}${i}.${v.reset} ${ns(a)}`,c=r+" ".repeat(i.length+2),u=ss(l,s,c);this._safeWrite(`${u}
716
+ `);return}}let n=ss(ns(e),s);this._safeWrite(`${n}
717
+ `)}};Ym.exports={renderMarkdown:XS,renderInline:ns,stripHeadingMarkers:ts,highlightCode:rc,highlightJS:Dm,highlightBash:jm,highlightJSON:qm,highlightPython:Fm,highlightGo:Bm,highlightRust:Um,highlightCSS:Wm,highlightHTML:Hm,renderTable:VS,renderProgress:JS,wrapAnsi:ss,StreamRenderer:oc}});var Jm=z((JR,Vm)=>{var{execSync:ZS}=require("child_process"),ic=require("path"),Do=require("fs"),ac=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function zm(){return ic.join(process.cwd(),".nex","hooks")}function QS(){return ic.join(process.cwd(),".nex","config.json")}function Km(){let t=QS();if(!Do.existsSync(t))return{};try{return JSON.parse(Do.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function _i(t){if(!ac.includes(t))return[];let e=[],s=zm(),n=ic.join(s,t);Do.existsSync(n)&&e.push(n);let o=Km();if(o[t]){let r=Array.isArray(o[t])?o[t]:[o[t]];e.push(...r)}return e}function Xm(t,e={},s=3e4){try{return{success:!0,exitCode:0,output:ZS(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 ev(t,e={}){let s=_i(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=Xm(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 tv(t){return _i(t).length>0}function nv(){let t=[];for(let e of ac){let s=_i(e);s.length>0&&t.push({event:e,commands:s})}return t}function sv(){let t=zm();return Do.existsSync(t)||Do.mkdirSync(t,{recursive:!0}),t}Vm.exports={HOOK_EVENTS:ac,loadHookConfig:Km,getHooksForEvent:_i,executeHook:Xm,runHooks:ev,hasHooks:tv,listHooks:nv,initHooksDir:sv}});var fg=z((t1,dg)=>{"use strict";var{callWithRetry:Qm,runSubAgent:ov,clearAllLocks:rv}=Cl(),{parseModelSpec:eg,getActiveProviderName:ZR,getActiveModelId:QR}=Ze(),{detectCategory:iv,getModelForCategory:Zm}=js(),{MultiProgress:av,C:de}=Ke(),{getModelBriefing:e1}=Xr(),tg=parseInt(process.env.NEX_MAX_PARALLEL||"4",10),$i=parseInt(process.env.NEX_MAX_SUBTASKS||"8",10),ng="devstral-2:123b",sg="kimi-k2.5",og=`You are a task decomposition engine. Given a complex user request, split it into independent, atomic sub-tasks.
718
718
 
719
719
  RULES:
720
720
  - Output ONLY a JSON array, no markdown fences, no explanation.
@@ -729,7 +729,7 @@ RULES:
729
729
  - If the request is simple (single goal), return an array with exactly 1 item.
730
730
 
731
731
  USER REQUEST:
732
- {prompt}`,og=`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.
732
+ {prompt}`,rg=`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.
733
733
 
734
734
  RULES:
735
735
  - Output ONLY a JSON object with these fields:
@@ -743,16 +743,16 @@ ORIGINAL REQUEST:
743
743
  {prompt}
744
744
 
745
745
  SUB-AGENT RESULTS:
746
- {results}`;async function rg(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 ig(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 ic(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:
747
- ${e.slice(0,200)}`)}async function ag(t,e,s={}){let n=s.maxSubTasks||_i,r=[{role:"system",content:sg.replace("{maxSubTasks}",String(n)).replace("{prompt}",t)},{role:"user",content:t}],i={};if(e){let g=Qm(e);g.provider&&(i.provider=g.provider),g.model&&(i.model=g.model)}let l=(await Zm(r,[],i)).content||"",c=ic(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=_i*u;if(p>h){let{debugLog:g}=Sr();g(`${Nt().T.yellow} \u26A0 Orchestrator: total estimated calls ${p} > ${h} \u2014 consider raising maxSubTasks${Nt().T.reset}`)}return f}async function lg(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}] ---
746
+ {results}`;async function ig(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 ag(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 lv(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 lc(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:
747
+ ${e.slice(0,200)}`)}async function lg(t,e,s={}){let n=s.maxSubTasks||$i,r=[{role:"system",content:og.replace("{maxSubTasks}",String(n)).replace("{prompt}",t)},{role:"user",content:t}],i={};if(e){let g=eg(e);g.provider&&(i.provider=g.provider),g.model&&(i.model=g.model)}let l=(await Qm(r,[],i)).content||"",c=lc(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=$i*u;if(p>h){let{debugLog:g}=vr();g(`${Dt().T.yellow} \u26A0 Orchestrator: total estimated calls ${p} > ${h} \u2014 consider raising maxSubTasks${Dt().T.reset}`)}return f}async function cg(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}] ---
748
748
  Task: ${u.task}
749
749
  Result: ${u.result}
750
750
  Tools: ${(u.toolsUsed||[]).join(", ")||"none"}`}).join(`
751
751
 
752
- `),r=[{role:"system",content:og.replace("{prompt}",e).replace("{results}",n)},{role:"user",content:"Synthesize the sub-agent results above."}],i={};if(s){let u=Qm(s);u.provider&&(i.provider=u.provider),u.model&&(i.model=u.model)}let l=(await Zm(r,[],i)).content||"",c=ic(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 lv(t,e={}){let s=e.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL||ng,n=e.workerModel||tg,o=e.maxParallel||eg,r=e.maxSubTasks||_i,i=e.onProgress||(()=>{}),a={input:0,output:0};console.log(`
752
+ `),r=[{role:"system",content:rg.replace("{prompt}",e).replace("{results}",n)},{role:"user",content:"Synthesize the sub-agent results above."}],i={};if(s){let u=eg(s);u.provider&&(i.provider=u.provider),u.model&&(i.model=u.model)}let l=(await Qm(r,[],i)).content||"",c=lc(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 cv(t,e={}){let s=e.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL||sg,n=e.workerModel||ng,o=e.maxParallel||tg,r=e.maxSubTasks||$i,i=e.onProgress||(()=>{}),a={input:0,output:0};console.log(`
753
753
  ${de.bold}Orchestrator${de.reset} ${de.dim}model: ${s} | workers: ${n} | max parallel: ${o}${de.reset}
754
- `),i("decomposing"),console.log(`${de.dim}Phase 1: Decomposing prompt into sub-tasks...${de.reset}`);let l;try{l=await ag(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 K=H.scope.filter(Boolean);K.length>0&&console.log(` ${de.dim}scope: ${K.join(", ")}${de.reset}`)}console.log("");let c=new Map;for(let H=0;H<l.length;H++)for(let K of l[H].scope)K&&!c.has(K)&&c.set(K,H);i("executing"),console.log(`${de.dim}Phase 2: Running ${l.length} sub-agents (max ${o} parallel)...${de.reset}
755
- `);let u=Date.now(),d=ig(o),f={findings:[],_lock:!1},p=l.map(H=>{let K=rv(H.task);return(K?Jm(K.id):null)||n}),h=l.map((H,K)=>{let pe=`Agent ${K+1} [${p[K]}]: `,ve=Math.max(20,60-pe.length),Be=H.task.substring(0,ve)+(H.task.length>ve?"...":"");return pe+Be}),g=new iv(h);g.start();let _=`
754
+ `),i("decomposing"),console.log(`${de.dim}Phase 1: Decomposing prompt into sub-tasks...${de.reset}`);let l;try{l=await lg(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 K=H.scope.filter(Boolean);K.length>0&&console.log(` ${de.dim}scope: ${K.join(", ")}${de.reset}`)}console.log("");let c=new Map;for(let H=0;H<l.length;H++)for(let K of l[H].scope)K&&!c.has(K)&&c.set(K,H);i("executing"),console.log(`${de.dim}Phase 2: Running ${l.length} sub-agents (max ${o} parallel)...${de.reset}
755
+ `);let u=Date.now(),d=ag(o),f={findings:[],_lock:!1},p=l.map(H=>{let K=iv(H.task);return(K?Zm(K.id):null)||n}),h=l.map((H,K)=>{let pe=`Agent ${K+1} [${p[K]}]: `,ve=Math.max(20,60-pe.length),Ue=H.task.substring(0,ve)+(H.task.length>ve?"...":"");return pe+Ue}),g=new av(h);g.start();let _=`
756
756
  You are a focused coding agent executing ONE specific sub-task.
757
757
  Your scope is limited to the files listed in your task definition.
758
758
 
@@ -773,16 +773,16 @@ RULES:
773
773
  - If your task says "add X to README" \u2014 add it, don't check if it exists first.
774
774
  - Max 10 tool calls. If you need more, you are doing too much \u2014 narrow your scope.
775
775
  - When done: stop calling tools and write a one-line summary of what you changed.
776
- `,b=new Map;for(let H=0;H<l.length;H++){let K=l[H].priority||1;b.has(K)||b.set(K,[]),b.get(K).push({st:l[H],idx:H})}let O=[...b.keys()].sort((H,K)=>H-K),M=new Array(l.length);for(let H of O){let pe=b.get(H).map(async({st:ve,idx:Be})=>{let $e=await d();try{let ye=await k(ve,Be,{acquire:d,subTaskModels:p,labels:h,progress:g,sharedContext:f,_fileOwnership:c,workerModel:n,WORKER_SYSTEM_PROMPT:_});return M[Be]=ye,ye}finally{$e()}});await Promise.all(pe)}async function k(H,K,pe){try{let ve=f.findings.filter(se=>se.agentId!==H.id).map(se=>`Agent ${se.agentId} found: ${se.summary}`).join(`
777
- `),Be=[...c.entries()].filter(([,se])=>se===K).map(([se])=>se),$e=[...c.entries()].filter(([,se])=>se!==K).map(([se])=>se),ye=[ve?`Prior agent findings:
776
+ `,b=new Map;for(let H=0;H<l.length;H++){let K=l[H].priority||1;b.has(K)||b.set(K,[]),b.get(K).push({st:l[H],idx:H})}let O=[...b.keys()].sort((H,K)=>H-K),M=new Array(l.length);for(let H of O){let pe=b.get(H).map(async({st:ve,idx:Ue})=>{let $e=await d();try{let ye=await k(ve,Ue,{acquire:d,subTaskModels:p,labels:h,progress:g,sharedContext:f,_fileOwnership:c,workerModel:n,WORKER_SYSTEM_PROMPT:_});return M[Ue]=ye,ye}finally{$e()}});await Promise.all(pe)}async function k(H,K,pe){try{let ve=f.findings.filter(oe=>oe.agentId!==H.id).map(oe=>`Agent ${oe.agentId} found: ${oe.summary}`).join(`
777
+ `),Ue=[...c.entries()].filter(([,oe])=>oe===K).map(([oe])=>oe),$e=[...c.entries()].filter(([,oe])=>oe!==K).map(([oe])=>oe),ye=[ve?`Prior agent findings:
778
778
  ${ve}
779
- `:"",H.scope.length>0?`Focus on files: ${H.scope.join(", ")}`:"",Be.length>0?`You OWN these files (may read+write): ${Be.join(", ")}`:"",$e.length>0?`READ ONLY (owned by other agents, do NOT write): ${$e.join(", ")}`:""].filter(Boolean),$=cg(H.task),P=p[K],R=process.env.NEX_FALLBACK_MODEL||Jm("agentic")||n,B=0,T=await rg(async()=>{let se=B>0;se&&(g.update(K,"retry"),process.stderr.write(` ${de.dim}[Agent ${K+1}] retrying after error...${de.reset}
780
- `)),B++;let we=se&&P!==R?R:P;return sv({task:H.task,type:$,context:ye.length>0?ye.join(`
781
- `):void 0,max_iterations:Math.min(H.estimatedCalls||10,15),model:we,_skipLog:!0,_systemPrompt:_,_readOnlyFiles:$e},{onUpdate:ge=>{if(ge&&ge.type==="tool_call"&&process.stderr.isTTY){let he=`Agent ${K+1} [${we}]`,Wi=ge.tool||"...";g.labels[K]=`${he}: ${Wi}`}}})},1,2e3),x=typeof T.result=="string"?T.result.slice(0,200):String(T.result||"").slice(0,200);return f.findings.push({agentId:H.id,summary:x,files:Array.isArray(H.scope)?H.scope:[]}),g.labels[K]=h[K],g.update(K,T.status==="failed"?"error":"done"),a.input+=T.tokensUsed?.input||0,a.output+=T.tokensUsed?.output||0,T.tokensUsed?._estimated&&(a._estimated=!0),{...T,_scope:H.scope,_idx:K}}catch(ve){return g.labels[K]=h[K],g.update(K,"error"),{task:H.task,status:"failed",result:`Error: ${ve.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}}}let E;try{E=M}finally{g.stop({silent:!0}),ov()}console.log("");let N=Math.round((Date.now()-u)/1e3),ee=N>=60?`${Math.floor(N/60)}m ${N%60}s`:`${N}s`;for(let H=0;H<E.length;H++){let K=E[H],ve=K.status==="done"||K.status==="truncated"&&K.result&&!K.result.startsWith("Error")?`${de.green}\u2713${de.reset}`:`${de.red}\u2717${de.reset}`,Be=K._scope&&K._scope.length>0?K._scope.map($=>$.replace(/^.*\//,"").replace(/\/$/,"")).filter(Boolean):[],$e=Be.length>0?Be.join(", "):K.task.substring(0,35)+(K.task.length>35?"...":""),ye=H===E.length-1;console.log(` ${ve} Agent ${H+1} ${de.dim}${$e}${de.reset}${ye?` ${de.dim}${ee}${de.reset}`:""}`)}console.log(""),i("synthesizing"),console.log(`${de.dim}Phase 3: Synthesizing results...${de.reset}`);let X;try{X=await lg(E,t,s)}catch(H){console.log(`${de.yellow}Synthesize failed: ${H.message} \u2014 using raw results.${de.reset}`),X={summary:E.map(K=>K.result).join(`
782
- `),conflicts:[],commitMessage:"",resourcesChanged:[]}}let ce=f.findings.flatMap(H=>H.files),ae=new Map;for(let H of ce)ae.set(H,(ae.get(H)||0)+1);let ne=[...ae.values()].some(H=>H>1),S=f.findings.length>1&&ne?` ${de.dim}(agents shared context)${de.reset}`:"";if(console.log(`
783
- ${de.bold}Summary:${de.reset} ${X.summary}${S}`),X.conflicts.length>0){console.log(`${de.yellow}Conflicts:${de.reset}`);for(let H of X.conflicts)console.log(` - ${H}`)}X.commitMessage&&console.log(`${de.dim}Suggested commit: ${X.commitMessage}${de.reset}`);let Te=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: ${Te}${de.reset}
784
- `),{results:E,synthesis:X,totalTokens:a}}var cv=/\b(research|analyze|investigate|check|verify|review|audit|read|find|search|discover|look|examine|inspect|scan|list)\b/i,uv=/\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 cg(t){if(!t)return"implement";let e=cv.test(t);return uv.test(t)?"implement":e?"explore":"implement"}ug.exports={runOrchestrated:lv,decompose:ag,synthesize:lg,detectComplexPrompt:av,extractJSON:ic,createSemaphore:ig,DECOMPOSE_PROMPT:sg,SYNTHESIZE_PROMPT:og,DEFAULT_ORCHESTRATOR_MODEL:ng,DEFAULT_WORKER_MODEL:tg,DEFAULT_MAX_PARALLEL:eg,DEFAULT_MAX_SUBTASKS:_i,withRetry:rg,_classifyWorkerType:cg}});var Wl=z((i1,Dg)=>{var{C:m,Spinner:Ws,TaskProgress:dv,formatToolCall:fv,formatToolSummary:_c,formatSectionHeader:$i,formatMilestone:pv,setActiveTaskProgress:t1,getThinkingVerb:ac,setActiveModelForSpinner:hv}=ze(),{debugLog:F,warnLog:n1}=Sr(),{MilestoneTracker:mv}=nd(),{callStream:fg}=Ve(),{parseToolArgs:gv}=Zs(),{executeTool:yv}=ks(),{gatherProjectContext:wv}=sm(),{fitToContext:_v,forceCompress:Vt,getUsage:Dt,estimateTokens:$v,buildProgressSnapshot:bv}=Kt(),{autoSave:xv,flushAutoSave:kv}=di(),{scoreMessages:Sv,formatScore:vv,appendScoreHistory:Ev}=fi(),{detectCategory:Tv,getModelForPhase:$c,getPhaseBudget:ns,isPhaseRoutingEnabled:Rv}=js();function Me(t){xv(t),kv()}function Cv(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 lc(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=Sv(t);if(!s)return;console.log(vv(s,m));try{let{_getSessionsDir:n}=di(),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}=Zs(),o=ir();Ev(s.score,{version:o.version,model:n?n():null,sessionName:"_autosave",issues:s.issues})}catch{}}catch{}}var{getMemoryContext:Av}=xo(),{getDeploymentContextBlock:Ov,probeUrlServer:Nv}=Yl(),{getFewShotForInput:Mv}=km(),{checkPermission:Pv,setPermission:Lv,savePermissions:Iv}=Cm(),{confirm:Eg,setAllowAlwaysHandler:Dv,getAutoConfirm:Mi}=eo(),{isPlanMode:Go,getPlanModePrompt:jv,PLAN_MODE_ALLOWED_TOOLS:Tg,setPlanContent:qv,extractStepsFromText:Fv,createPlan:Bv,getActivePlan:s1,startExecution:o1,advancePlanStep:Uv,getPlanStepInfo:Wv}=yi(),{StreamRenderer:Hv}=Ym(),{runHooks:pg}=Vm(),{routeMCPCall:Yv,getMCPToolDefinitions:Gv}=Ia(),{getSkillInstructions:zv,getSkillToolDefinitions:Kv,routeSkillCall:Xv,matchSkillTriggers:Vv}=Pa(),{trackUsage:hg,estimateTokens:mg}=kr();function gg(t){return!t||typeof t!="string"?0:typeof mg=="function"?mg(t):Math.ceil(t.length/4)}var{validateToolArgs:Jv}=qa(),{filterToolsForModel:yg,getModelTier:Zv,PROVIDER_DEFAULT_TIER:r1}=co(),{getConfiguredProviders:Qv,getActiveProviderName:Hs,getActiveModelId:Ft,setActiveModel:wg,MODEL_EQUIVALENTS:Pi}=Ve(),{getModelProfile:eE,getModelBriefing:tE}=Kr(),kn=require("fs"),ji=require("path"),nE=(()=>{let t=parseInt(process.env.NEX_MILESTONE_STEPS??"5",10);return Number.isFinite(t)&&t>=0?t:5})();function sE(t){let e=pv(t.phaseName,t.stepCount,t.toolCounts,t.elapsed,t.filesRead,t.filesModified);process.stdout.write(`${e}
785
- `)}var _g=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi,$g=/(?:^|\s)(https?:\/\/[^\s]+\.(?:png|jpe?g|gif|webp)(?:\?[^\s]*)?)(?:\s|$)/gi,oE=/\b(?:clipboard|pasteboard|zwischenablage|screenshot aus clipboard)\b/i;function rE(t){let e=[],s;for(_g.lastIndex=0;(s=_g.exec(t))!==null;){let n=s[1].trim(),o=n.startsWith("~")?n.replace("~",process.env.HOME||""):ji.resolve(n);kn.existsSync(o)&&e.push({raw:n,abs:o})}return e}function Rg(t){let e=[],s;for($g.lastIndex=0;(s=$g.exec(t))!==null;)e.push(s[1].trim());return e}async function Cg(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]:iE(t);return{data:Buffer.from(s.data).toString("base64"),media_type:o}}catch{return null}}function iE(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 Ag(){if(process.platform!=="darwin")return null;let{spawnSync:t}=require("child_process"),e=ji.join(require("os").tmpdir(),`nex-clipboard-${Date.now()}.png`);if(t("pngpaste",[e],{timeout:3e3}).status===0&&kn.existsSync(e)){let o=kn.readFileSync(e);if(o.length>100)return{data:o.toString("base64"),media_type:"image/png",path:e};try{kn.unlinkSync(e)}catch{}}let n=t("osascript",["-e",`try
779
+ `:"",H.scope.length>0?`Focus on files: ${H.scope.join(", ")}`:"",Ue.length>0?`You OWN these files (may read+write): ${Ue.join(", ")}`:"",$e.length>0?`READ ONLY (owned by other agents, do NOT write): ${$e.join(", ")}`:""].filter(Boolean),$=ug(H.task),P=p[K],R=process.env.NEX_FALLBACK_MODEL||Zm("agentic")||n,B=0,T=await ig(async()=>{let oe=B>0;oe&&(g.update(K,"retry"),process.stderr.write(` ${de.dim}[Agent ${K+1}] retrying after error...${de.reset}
780
+ `)),B++;let we=oe&&P!==R?R:P;return ov({task:H.task,type:$,context:ye.length>0?ye.join(`
781
+ `):void 0,max_iterations:Math.min(H.estimatedCalls||10,15),model:we,_skipLog:!0,_systemPrompt:_,_readOnlyFiles:$e},{onUpdate:ge=>{if(ge&&ge.type==="tool_call"&&process.stderr.isTTY){let he=`Agent ${K+1} [${we}]`,Yi=ge.tool||"...";g.labels[K]=`${he}: ${Yi}`}}})},1,2e3),x=typeof T.result=="string"?T.result.slice(0,200):String(T.result||"").slice(0,200);return f.findings.push({agentId:H.id,summary:x,files:Array.isArray(H.scope)?H.scope:[]}),g.labels[K]=h[K],g.update(K,T.status==="failed"?"error":"done"),a.input+=T.tokensUsed?.input||0,a.output+=T.tokensUsed?.output||0,T.tokensUsed?._estimated&&(a._estimated=!0),{...T,_scope:H.scope,_idx:K}}catch(ve){return g.labels[K]=h[K],g.update(K,"error"),{task:H.task,status:"failed",result:`Error: ${ve.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}}}let E;try{E=M}finally{g.stop({silent:!0}),rv()}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<E.length;H++){let K=E[H],ve=K.status==="done"||K.status==="truncated"&&K.result&&!K.result.startsWith("Error")?`${de.green}\u2713${de.reset}`:`${de.red}\u2717${de.reset}`,Ue=K._scope&&K._scope.length>0?K._scope.map($=>$.replace(/^.*\//,"").replace(/\/$/,"")).filter(Boolean):[],$e=Ue.length>0?Ue.join(", "):K.task.substring(0,35)+(K.task.length>35?"...":""),ye=H===E.length-1;console.log(` ${ve} Agent ${H+1} ${de.dim}${$e}${de.reset}${ye?` ${de.dim}${te}${de.reset}`:""}`)}console.log(""),i("synthesizing"),console.log(`${de.dim}Phase 3: Synthesizing results...${de.reset}`);let X;try{X=await cg(E,t,s)}catch(H){console.log(`${de.yellow}Synthesize failed: ${H.message} \u2014 using raw results.${de.reset}`),X={summary:E.map(K=>K.result).join(`
782
+ `),conflicts:[],commitMessage:"",resourcesChanged:[]}}let ce=f.findings.flatMap(H=>H.files),ae=new Map;for(let H of ce)ae.set(H,(ae.get(H)||0)+1);let se=[...ae.values()].some(H=>H>1),S=f.findings.length>1&&se?` ${de.dim}(agents shared context)${de.reset}`:"";if(console.log(`
783
+ ${de.bold}Summary:${de.reset} ${X.summary}${S}`),X.conflicts.length>0){console.log(`${de.yellow}Conflicts:${de.reset}`);for(let H of X.conflicts)console.log(` - ${H}`)}X.commitMessage&&console.log(`${de.dim}Suggested commit: ${X.commitMessage}${de.reset}`);let Re=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: ${Re}${de.reset}
784
+ `),{results:E,synthesis:X,totalTokens:a}}var uv=/\b(research|analyze|investigate|check|verify|review|audit|read|find|search|discover|look|examine|inspect|scan|list)\b/i,dv=/\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 ug(t){if(!t)return"implement";let e=uv.test(t);return dv.test(t)?"implement":e?"explore":"implement"}dg.exports={runOrchestrated:cv,decompose:lg,synthesize:cg,detectComplexPrompt:lv,extractJSON:lc,createSemaphore:ag,DECOMPOSE_PROMPT:og,SYNTHESIZE_PROMPT:rg,DEFAULT_ORCHESTRATOR_MODEL:sg,DEFAULT_WORKER_MODEL:ng,DEFAULT_MAX_PARALLEL:tg,DEFAULT_MAX_SUBTASKS:$i,withRetry:ig,_classifyWorkerType:ug}});var Yl=z((a1,jg)=>{var{C:m,Spinner:Ws,TaskProgress:fv,formatToolCall:pv,formatToolSummary:$c,formatSectionHeader:bi,formatMilestone:hv,setActiveTaskProgress:n1,getThinkingVerb:cc,setActiveModelForSpinner:mv}=Ke(),{debugLog:q,warnLog:s1}=vr(),{MilestoneTracker:gv}=sd(),{callStream:pg}=Ze(),{parseToolArgs:yv}=Zs(),{executeTool:wv}=ks(),{gatherProjectContext:_v}=om(),{fitToContext:$v,forceCompress:Qt,getUsage:Ut,estimateTokens:bv,buildProgressSnapshot:xv}=Jt(),{autoSave:kv,flushAutoSave:Sv}=fi(),{scoreMessages:vv,formatScore:Ev,appendScoreHistory:Tv}=pi(),{detectCategory:Rv,getModelForPhase:bc,getPhaseBudget:os,isPhaseRoutingEnabled:Cv}=js();function Ne(t){kv(t),Sv()}function Av(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 xi(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=vv(t);if(!s)return;console.log(Ev(s,m));try{let{_getSessionsDir:n}=fi(),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}=Zs(),o=ar();Tv(s.score,{version:o.version,model:n?n():null,sessionName:"_autosave",issues:s.issues})}catch{}}catch{}}var{getMemoryContext:Ov}=xo(),{getDeploymentContextBlock:Nv,probeUrlServer:Mv}=zl(),{getFewShotForInput:Pv}=Sm(),{checkPermission:Lv,setPermission:Iv,savePermissions:Dv}=Am(),{confirm:Tg,setAllowAlwaysHandler:jv,getAutoConfirm:Li}=eo(),{isPlanMode:zo,getPlanModePrompt:qv,PLAN_MODE_ALLOWED_TOOLS:Rg,setPlanContent:Fv,extractStepsFromText:Bv,createPlan:Uv,getActivePlan:o1,startExecution:r1,advancePlanStep:Wv,getPlanStepInfo:Hv}=wi(),{StreamRenderer:Yv}=Gm(),{runHooks:hg}=Jm(),{routeMCPCall:Gv,getMCPToolDefinitions:zv}=ja(),{getSkillInstructions:Kv,getSkillToolDefinitions:Xv,routeSkillCall:Vv,matchSkillTriggers:Jv}=Ia(),{trackUsage:mg,estimateTokens:gg}=Sr();function yg(t){return!t||typeof t!="string"?0:typeof gg=="function"?gg(t):Math.ceil(t.length/4)}var{validateToolArgs:Zv}=Ba(),{filterToolsForModel:wg,getModelTier:Qv,PROVIDER_DEFAULT_TIER:i1}=co(),{getConfiguredProviders:eE,getActiveProviderName:Hs,getActiveModelId:Ht,setActiveModel:_g,MODEL_EQUIVALENTS:Ii}=Ze(),{getModelProfile:tE,getModelBriefing:nE}=Xr(),vn=require("fs"),Fi=require("path"),sE=(()=>{let t=parseInt(process.env.NEX_MILESTONE_STEPS??"5",10);return Number.isFinite(t)&&t>=0?t:5})();function oE(t){let e=hv(t.phaseName,t.stepCount,t.toolCounts,t.elapsed,t.filesRead,t.filesModified);process.stdout.write(`${e}
785
+ `)}var $g=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi,bg=/(?:^|\s)(https?:\/\/[^\s]+\.(?:png|jpe?g|gif|webp)(?:\?[^\s]*)?)(?:\s|$)/gi,rE=/\b(?:clipboard|pasteboard|zwischenablage|screenshot aus clipboard)\b/i;function iE(t){let e=[],s;for($g.lastIndex=0;(s=$g.exec(t))!==null;){let n=s[1].trim(),o=n.startsWith("~")?n.replace("~",process.env.HOME||""):Fi.resolve(n);vn.existsSync(o)&&e.push({raw:n,abs:o})}return e}function Cg(t){let e=[],s;for(bg.lastIndex=0;(s=bg.exec(t))!==null;)e.push(s[1].trim());return e}async function Ag(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]:aE(t);return{data:Buffer.from(s.data).toString("base64"),media_type:o}}catch{return null}}function aE(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 Og(){if(process.platform!=="darwin")return null;let{spawnSync:t}=require("child_process"),e=Fi.join(require("os").tmpdir(),`nex-clipboard-${Date.now()}.png`);if(t("pngpaste",[e],{timeout:3e3}).status===0&&vn.existsSync(e)){let o=vn.readFileSync(e);if(o.length>100)return{data:o.toString("base64"),media_type:"image/png",path:e};try{vn.unlinkSync(e)}catch{}}let n=t("osascript",["-e",`try
786
786
  set imgData to the clipboard as \xABclass PNGf\xBB
787
787
  return "has_image"
788
788
  on error
@@ -793,33 +793,33 @@ end try`],{timeout:3e3});if(n.stdout&&n.stdout.toString().trim()==="has_image"){
793
793
  set fRef to open for access filePath with write permission
794
794
  write imgData to fRef
795
795
  close access fRef
796
- `;if(t("osascript",["-e",o],{timeout:5e3}).status===0&&kn.existsSync(e)){let i=kn.readFileSync(e);if(i.length>100)return{data:i.toString("base64"),media_type:"image/png",path:e}}}return null}function bg(t){let e=kn.readFileSync(t),s=ji.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 Og(t){let e=rE(t),s=Rg(t),n=oE.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}=bg(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}=bg(i.abs);r.push({type:"image",media_type:l,data:a})}catch{}if(s.length>0){let i=await Promise.all(s.map(Cg));for(let a of i)a&&r.push({type:"image",media_type:a.media_type,data:a.data})}if(n){let i=Ag();i?(r.push({type:"image",media_type:i.media_type,data:i.data}),r[0].text+=`
796
+ `;if(t("osascript",["-e",o],{timeout:5e3}).status===0&&vn.existsSync(e)){let i=vn.readFileSync(e);if(i.length>100)return{data:i.toString("base64"),media_type:"image/png",path:e}}}return null}function xg(t){let e=vn.readFileSync(t),s=Fi.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 Ng(t){let e=iE(t),s=Cg(t),n=rE.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}=xg(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}=xg(i.abs);r.push({type:"image",media_type:l,data:a})}catch{}if(s.length>0){let i=await Promise.all(s.map(Ag));for(let a of i)a&&r.push({type:"image",media_type:a.media_type,data:a.data})}if(n){let i=Og();i?(r.push({type:"image",media_type:i.media_type,data:i.data}),r[0].text+=`
797
797
  [Clipboard image attached: ${i.path}]`):r[0].text+=`
798
- [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 Ng(t){return typeof t!="string"||!t?!1:aE.some(e=>e.test(t))}function lE(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=`
798
+ [No image found in clipboard]`}return r.length>1?r:t})()}var lE=[/\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 Mg(t){return typeof t!="string"||!t?!1:lE.some(e=>e.test(t))}function cE(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=`
799
799
 
800
- [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 bc(t,e=5){if(!t||t.length<40)return{text:t,truncated:!1,repeatCount:0};let s=t.split(`
800
+ [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 xc(t,e=5){if(!t||t.length<40)return{text:t,truncated:!1,repeatCount:0};let s=t.split(`
801
801
  `),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=`
802
802
 
803
- \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 cc=null,uc=null,dc=null;function ot(){if(cc===null){let{TOOL_DEFINITIONS:t}=ks();cc=t}return uc===null&&(uc=Kv()),dc===null&&(dc=Gv()),[...cc,...uc,...dc]}var xc=50;function cE(t){Number.isFinite(t)&&t>0&&(xc=t)}var ki=()=>null;function uE(t){ki=t}var Fo=null,kc=null,Ys=null,Si=new Map,dE=1e4,fE=6e3,pE=/\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 hE(t){return!t||typeof t!="string"?t:t.replace(pE,(e,s)=>`${s}=***REDACTED***`)}var mE=7e3,gE=4e3;function yE(t,e=null){let s=hE(t),n=$v(s),o=e==="read_file"?mE:dE,r=e==="read_file"?gE:fE;if(n>o)try{let{compressToolResult:i}=Kt();return i(s,r)}catch{return s}return s}function Mg(t){try{let{getActiveModel:e}=Ve(),s=e(),n=s?`${s.provider}:${s.id}`:"default";if(Si.has(n))return Si.get(n);let o=yg(t);return Si.set(n,o),o}catch{return yg(t)}}function wE(){Si.clear()}var Bo={hash:null,ts:0},_E=3e4;async function Pg(){if(Bo.hash&&Date.now()-Bo.ts<_E)return Bo.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}=xo(),a=i();a&&o.push(`memory:${a}`)}catch{}try{let i=e.join(process.cwd(),".nex","brain");if(kn.existsSync(i)){let a=await t.stat(i);o.push(`brain:${a.mtimeMs}`)}}catch{}let r=o.join("|");return Bo={hash:r,ts:Date.now()},r}catch{return`fallback:${Date.now()}`}}function Sc(){Fo=null,kc=null,Bo={hash:null,ts:0},Ys=null}var $E=new Set(["spawn_agents"]),fc=5,pc=3,bi=2,xg=6e4,hc=12e4,bE=process.env.NEX_STALE_AUTO_SWITCH!=="0";function xE(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{}}Dv(t=>{Lv(t,"allow"),Iv(),console.log(`${m.green} \u2713 ${t}: always allow${m.reset}`)});async function kE(t){let e=t.function.name,s=gv(t.function.arguments),n=t.id||`cli-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!s){let u=ot().find(f=>f.function.name===e),d=u?JSON.stringify(u.function.parameters,null,2):"unknown";return F(`${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.
803
+ \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 uc=null,dc=null,fc=null;function rt(){if(uc===null){let{TOOL_DEFINITIONS:t}=ks();uc=t}return dc===null&&(dc=Xv()),fc===null&&(fc=zv()),[...uc,...dc,...fc]}var kc=50;function uE(t){Number.isFinite(t)&&t>0&&(kc=t)}var vi=()=>null;function dE(t){vi=t}var Bo=null,Sc=null,Ys=null,Ei=new Map,fE=1e4,pE=6e3,hE=/\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 mE(t){return!t||typeof t!="string"?t:t.replace(hE,(e,s)=>`${s}=***REDACTED***`)}var gE=7e3,yE=4e3;function wE(t,e=null){let s=mE(t),n=bv(s),o=e==="read_file"?gE:fE,r=e==="read_file"?yE:pE;if(n>o)try{let{compressToolResult:i}=Jt();return i(s,r)}catch{return s}return s}function Pg(t){try{let{getActiveModel:e}=Ze(),s=e(),n=s?`${s.provider}:${s.id}`:"default";if(Ei.has(n))return Ei.get(n);let o=wg(t);return Ei.set(n,o),o}catch{return wg(t)}}function _E(){Ei.clear()}var Uo={hash:null,ts:0},$E=3e4;async function Lg(){if(Uo.hash&&Date.now()-Uo.ts<$E)return Uo.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}=xo(),a=i();a&&o.push(`memory:${a}`)}catch{}try{let i=e.join(process.cwd(),".nex","brain");if(vn.existsSync(i)){let a=await t.stat(i);o.push(`brain:${a.mtimeMs}`)}}catch{}let r=o.join("|");return Uo={hash:r,ts:Date.now()},r}catch{return`fallback:${Date.now()}`}}function vc(){Bo=null,Sc=null,Uo={hash:null,ts:0},Ys=null}var bE=new Set(["spawn_agents"]),pc=5,hc=3,ki=2,kg=6e4,mc=12e4,xE=process.env.NEX_STALE_AUTO_SWITCH!=="0";function kE(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{}}jv(t=>{Iv(t,"allow"),Dv(),console.log(`${m.green} \u2713 ${t}: always allow${m.reset}`)});async function SE(t){let e=t.function.name,s=yv(t.function.arguments),n=t.id||`cli-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!s){let u=rt().find(f=>f.function.name===e),d=u?JSON.stringify(u.function.parameters,null,2):"unknown";return q(`${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.
804
804
  Raw input: ${typeof t.function.arguments=="string"?t.function.arguments.substring(0,200):"N/A"}
805
805
 
806
806
  Expected JSON schema for "${e}":
807
807
  ${d}
808
808
 
809
- Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:n}}}let o=Jv(e,s);if(!o.valid){F(`${m.yellow} \u26A0 ${e}: ${o.error.split(`
810
- `)[0]}${m.reset}`);let c=(Sg.get(e)||0)+1;Sg.set(e,c);let u=c>=2?`${o.error}
809
+ Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:n}}}let o=Zv(e,s);if(!o.valid){q(`${m.yellow} \u26A0 ${e}: ${o.error.split(`
810
+ `)[0]}${m.reset}`);let c=(vg.get(e)||0)+1;vg.set(e,c);let u=c>=2?`${o.error}
811
811
 
812
- [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(Go()&&!Tg.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(_e&&Le==="plan"&&!i.has(e)&&!e.startsWith("skill_"))return Sn++,F(`${m.yellow} \u2717 ${e}: blocked in plan phase (read-only, block #${Sn})${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(_e&&Le==="verify"&&!a.has(e)&&!e.startsWith("skill_"))return F(`${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=Pv(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 Eg(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 SE(t,e,s={}){let n=await Xv(t,e);if(n!==null)return n;let o=await Yv(t,e);return o!==null?o:yv(t,e,s)}function vE(t,e){switch(t){case"read_file":case"write_file":case"edit_file":case"patch_file":case"list_directory":return e.path||"";case"bash":return(e.command||"").substring(0,60);case"grep":case"search_files":case"glob":return e.pattern||"";case"web_fetch":return(e.url||"").substring(0,50);case"web_search":return(e.query||"").substring(0,40);default:return""}}async function mc(t,e=!1){e||console.log(fv(t.fnName,t.args));let s=pg("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=_c(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}`);Qt?.onToolStart&&Qt.onToolStart(t.fnName,t.args);let o=await SE(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)+`
812
+ [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(zo()&&!Rg.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(_e&&Le==="plan"&&!i.has(e)&&!e.startsWith("skill_"))return En++,q(`${m.yellow} \u2717 ${e}: blocked in plan phase (read-only, block #${En})${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(_e&&Le==="verify"&&!a.has(e)&&!e.startsWith("skill_"))return q(`${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=Lv(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 Tg(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 vE(t,e,s={}){let n=await Vv(t,e);if(n!==null)return n;let o=await Gv(t,e);return o!==null?o:wv(t,e,s)}function EE(t,e){switch(t){case"read_file":case"write_file":case"edit_file":case"patch_file":case"list_directory":return e.path||"";case"bash":return(e.command||"").substring(0,60);case"grep":case"search_files":case"glob":return e.pattern||"";case"web_fetch":return(e.url||"").substring(0,50);case"web_search":return(e.query||"").substring(0,40);default:return""}}async function gc(t,e=!1){e||console.log(pv(t.fnName,t.args));let s=hg("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=$c(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}`);tn?.onToolStart&&tn.onToolStart(t.fnName,t.args);let o=await vE(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)+`
813
813
  ...(truncated ${i.length-5e4} chars)`:i,l=a.split(`
814
- `)[0],c=l.startsWith("ERROR")||l.includes("CANCELLED")||l.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(a)&&/✗ Agent/.test(a),u=_c(t.fnName,t.args,a,c);e||console.log(u),Qt?.onToolEnd&&Qt.onToolEnd(t.fnName,u,!c);let f=pg("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=yE(a,t.fnName);if(t.fnName==="bash"&&t.args?.command){let _=t.args.command.trim();!/cat\s*>|<</.test(_)&&/\bcat\s+\S/.test(_)?h+=`
814
+ `)[0],c=l.startsWith("ERROR")||l.includes("CANCELLED")||l.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(a)&&/✗ Agent/.test(a),u=$c(t.fnName,t.args,a,c);e||console.log(u),tn?.onToolEnd&&tn.onToolEnd(t.fnName,u,!c);let f=hg("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=wE(a,t.fnName);if(t.fnName==="bash"&&t.args?.command){let _=t.args.command.trim();!/cat\s*>|<</.test(_)&&/\bcat\s+\S/.test(_)?h+=`
815
815
  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+=`
816
816
  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+=`
817
- 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 EE=[{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 gc(t){for(let{re:e,label:s}of EE){let n=t.match(e);if(n){let o=(n[1]||"").trim();return o?`${s}: ${o}`:s}}return null}async function TE(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=vE(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 Ws(c),i.start()}}async function a(){if(r.length!==0){if(r.length===1){let l=r[0],{msg:c,summary:u}=await mc(t[l],e);n[l]=c,o.push(u)}else{let l=r.map(u=>mc(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(_c(c.fnName,c.args||{},c.errorResult.content,!0));continue}if($E.has(c.fnName)){await a(),c.fnName==="spawn_agents"&&i&&(i.stop(),i=null);let{msg:u,summary:d}=await mc(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=[],kg=300,Lg=900*1e3;function Jt(t,e){let s=t.get(e);return s?Date.now()-s.ts>Lg?(t.delete(e),0):s.count:0}function ss(t,e){let s=t.get(e),n=s&&Date.now()-s.ts<=Lg?s.count+1:1;return t.set(e,{count:n,ts:Date.now()}),n}function yc(t,e,s){t.set(e,{count:s,ts:Date.now()})}var Nc=new Map,Mc=new Map,zo=new Map,Pc=new Map,Ko=new Map,xn=new Map,dn=new Map,Xo=new Map,Rt=new Map,as=new Map,Sg=new Map,Li=new Map,Ii=new Map,Ct=0,Uo=0,vi=0,vc="",Ei=0,xt=!1,xi=0,Ti=0,os=-1,Ec=!1,Ri=0,Ci=!1,Zt=0,jt=!1,fn=0,qt=0,Ze=!1,ht="",Wo=0,bn=0,Ai="",rs=0,is=0,Oi="",At=!1,Tc=!1,Vo=new Map,Jo=new Set,Ho=null,wc=!1,jo=0,vg=!1,Le="plan",Di=0,_e=!1,Sn=0,pn=null,Rc=null,Cc=null,Yo=0,Gs=null;function Us(t,e){t===vc?(Ei++,Sr().DEBUG&&process.stdout.write(`\x1B[1A\x1B[2K${e} \u26A0 ${t} (\xD7${Ei})${m.reset}
818
- `)):(vc=t,Ei=1,F(`${e} \u26A0 ${t}${m.reset}`))}var Ni=[];function RE(t){Ni.push(t.trim())}function CE(){return Ni.length===0?null:Ni.splice(0,Ni.length).join(`
819
- `)}function qo(t,e,s,n){if(!_e)return null;let o=Le;Le=t,Di=0,pn=$c(t,Gs),Zt=0,jt=!1,fn=0,qt=0,xn.clear(),dn.clear(),as.clear(),Li.clear(),Ii.clear(),Mc.clear(),zo.clear(),Pc.clear(),Ko.clear(),Nc.clear(),Xo.clear();let r;if(t==="implement")Rc=e?.slice(0,800)||"",r=`[PHASE: IMPLEMENTATION] Analysis complete. Based on the analysis:
820
- ${Rc}
817
+ 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 TE=[{re:/TypeError:\s*([^\n]{0,120})/i,label:"TypeError"},{re:/SyntaxError:\s*([^\n]{0,120})/i,label:"SyntaxError"},{re:/ReferenceError:\s*([^\n]{0,120})/i,label:"ReferenceError"},{re:/Cannot find module\s*'([^']+)'/i,label:"Cannot find module"},{re:/Error:\s*ENOENT[^\n]{0,120}/i,label:"ENOENT"},{re:/Error:\s*EACCES[^\n]{0,120}/i,label:"EACCES"},{re:/Error:\s*EADDRINUSE[^\n]{0,120}/i,label:"EADDRINUSE"},{re:/ImportError:\s*([^\n]{0,120})/i,label:"ImportError"},{re:/ModuleNotFoundError:\s*([^\n]{0,120})/i,label:"ModuleNotFoundError"},{re:/NameError:\s*([^\n]{0,120})/i,label:"NameError"},{re:/AttributeError:\s*([^\n]{0,120})/i,label:"AttributeError"},{re:/KeyError:\s*([^\n]{0,120})/i,label:"KeyError"},{re:/ValueError:\s*([^\n]{0,120})/i,label:"ValueError"},{re:/panic:\s*([^\n]{0,120})/i,label:"Go panic"},{re:/java\.lang\.\w+Exception[^\n]{0,80}/i,label:"Java exception"}];function yc(t){for(let{re:e,label:s}of TE){let n=t.match(e);if(n){let o=(n[1]||"").trim();return o?`${s}: ${o}`:s}}return null}async function RE(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=EE(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 Ws(c),i.start()}}async function a(){if(r.length!==0){if(r.length===1){let l=r[0],{msg:c,summary:u}=await gc(t[l],e);n[l]=c,o.push(u)}else{let l=r.map(u=>gc(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($c(c.fnName,c.args||{},c.errorResult.content,!0));continue}if(bE.has(c.fnName)){await a(),c.fnName==="spawn_agents"&&i&&(i.stop(),i=null);let{msg:u,summary:d}=await gc(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 D=[],Sg=300,Ig=900*1e3;function en(t,e){let s=t.get(e);return s?Date.now()-s.ts>Ig?(t.delete(e),0):s.count:0}function rs(t,e){let s=t.get(e),n=s&&Date.now()-s.ts<=Ig?s.count+1:1;return t.set(e,{count:n,ts:Date.now()}),n}function wc(t,e,s){t.set(e,{count:s,ts:Date.now()})}var Mc=new Map,Pc=new Map,Ko=new Map,Lc=new Map,Xo=new Map,Sn=new Map,fn=new Map,Vo=new Map,Ot=new Map,cs=new Map,vg=new Map,Di=new Map,ji=new Map,Nt=0,Wo=0,Ti=0,Ec="",Ri=0,St=!1,Si=0,Ci=0,is=-1,Tc=!1,Ai=0,Oi=!1,Pt=0,Lt=!1,pn=0,Wt=0,et=!1,wt="",Ho=0,kn=0,Ni="",as=0,ls=0,Mi="",jo=0,Mt=!1,Rc=!1,Jo=new Map,Zo=new Set,Yo=null,_c=!1,qo=0,Eg=!1,Le="plan",qi=0,_e=!1,En=0,hn=null,Cc=null,Ac=null,Go=0,Gs=null;function Us(t,e){t===Ec?(Ri++,vr().DEBUG&&process.stdout.write(`\x1B[1A\x1B[2K${e} \u26A0 ${t} (\xD7${Ri})${m.reset}
818
+ `)):(Ec=t,Ri=1,q(`${e} \u26A0 ${t}${m.reset}`))}var Pi=[];function CE(t){Pi.push(t.trim())}function AE(){return Pi.length===0?null:Pi.splice(0,Pi.length).join(`
819
+ `)}function Fo(t,e,s,n){if(!_e)return null;let o=Le;Le=t,qi=0,hn=bc(t,Gs),Pt=0,Lt=!1,pn=0,Wt=0,Sn.clear(),fn.clear(),cs.clear(),Di.clear(),ji.clear(),Pc.clear(),Ko.clear(),Lc.clear(),Xo.clear(),Mc.clear(),Vo.clear();let r;if(t==="implement")Cc=e?.slice(0,800)||"",r=`[PHASE: IMPLEMENTATION] Analysis complete. Based on the analysis:
820
+ ${Cc}
821
821
 
822
- Now implement the fix/changes. Do not investigate further \u2014 edit files directly.`;else if(t==="verify"){Cc=e?.slice(0,500)||"";let i=s?[...s].join(", "):"none";r=`[PHASE: VERIFICATION] Implementation complete. Verify the changes:
822
+ Now implement the fix/changes. Do not investigate further \u2014 edit files directly.`;else if(t==="verify"){Ac=e?.slice(0,500)||"";let i=s?[...s].join(", "):"none";r=`[PHASE: VERIFICATION] Implementation complete. Verify the changes:
823
823
  1. Read each modified file and confirm changes are correct
824
824
  2. If test command exists (npm test / pytest): run it
825
825
  3. If linter exists: run it
@@ -827,18 +827,18 @@ Now implement the fix/changes. Do not investigate further \u2014 edit files dire
827
827
  Report PASS (all good) or FAIL (list specific issues).
828
828
 
829
829
  Files modified: ${i}
830
- Summary: ${Cc}`}return F(`${m.cyan} \u21B3 Phase transition: ${o} \u2192 ${t} (model: ${pn||"default"})${m.reset}`),r?{role:"user",content:r}:null}function AE(){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)
831
- `];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"),Mi()?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(`
830
+ Summary: ${Ac}`}return q(`${m.cyan} \u21B3 Phase transition: ${o} \u2192 ${t} (model: ${hn||"default"})${m.reset}`),r?{role:"user",content:r}:null}function OE(){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)
831
+ `];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"),Li()?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(`
832
832
  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(`
833
833
  `)+`
834
834
 
835
- `}function OE(){if(Ys!==null)return Ys;try{let e=Qv().flatMap(o=>o.models.map(r=>({spec:`${o.name}:${r.id}`,tier:Zv(r.id,o.name),name:r.name})));if(e.length<2)return Ys="","";let s={full:"complex tasks (refactor, implement, generate)",standard:"regular tasks (edit, fix, analyze)",essential:"simple tasks (read, search, list)"},n=`
835
+ `}function NE(){if(Ys!==null)return Ys;try{let e=eE().flatMap(o=>o.models.map(r=>({spec:`${o.name}:${r.id}`,tier:Qv(r.id,o.name),name:r.name})));if(e.length<2)return Ys="","";let s={full:"complex tasks (refactor, implement, generate)",standard:"regular tasks (edit, fix, analyze)",essential:"simple tasks (read, search, list)"},n=`
836
836
  # Sub-Agent Model Routing
837
837
 
838
838
  `;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 |
839
839
  |---|---|---|
840
840
  `;for(let o of e)n+=`| ${o.spec} | ${o.tier} | ${s[o.tier]||o.tier} |
841
- `;return Ys=n,n}catch(t){return process.env.NEX_DEBUG&&console.error("[agent] model routing guide failed:",t.message),Ys="",""}}var Ac="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->";function NE(t){let e=t.indexOf(Ac);return e===-1?{dynamic:t,static:""}:{dynamic:t.slice(0,e).trimEnd(),static:t.slice(e+Ac.length).trimStart()}}async function Oc(){let t=await Pg()+":"+Ft();if(Fo!==null&&t===kc)return Fo;let e=await wv(process.cwd()),s=Av(),n=zv(),o=Go()?jv():"",r=AE(),i=Ov(),a=tE(Ft());return Fo=`${a?`## Model Briefing
841
+ `;return Ys=n,n}catch(t){return process.env.NEX_DEBUG&&console.error("[agent] model routing guide failed:",t.message),Ys="",""}}var Oc="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->";function ME(t){let e=t.indexOf(Oc);return e===-1?{dynamic:t,static:""}:{dynamic:t.slice(0,e).trimEnd(),static:t.slice(e+Oc.length).trimStart()}}async function Nc(){let t=await Lg()+":"+Ht();if(Bo!==null&&t===Sc)return Bo;let e=await _v(process.cwd()),s=Ov(),n=Kv(),o=zo()?qv():"",r=OE(),i=Nv(),a=nE(Ht());return Bo=`${a?`## Model Briefing
842
842
  ${a}
843
843
 
844
844
  ---
@@ -859,7 +859,7 @@ ${o}
859
859
  ${r?`${r}
860
860
  `:""}${i?`${i}
861
861
 
862
- `:""}${Mi()?`# YOLO Mode \u2014 Auto-Execute
862
+ `:""}${Li()?`# YOLO Mode \u2014 Auto-Execute
863
863
 
864
864
  You are in YOLO mode (autoConfirm=true). All tool calls are pre-approved.
865
865
  - NEVER ask for confirmation \u2014 just execute tasks directly
@@ -917,9 +917,9 @@ Response patterns by request type:
917
917
  - **Hook implementations (Git, bash scripts)**: Answer ENTIRELY in text \u2014 do NOT use any tools. Write the complete, correct script in your first and only response. Think through ALL edge cases (e.g. console.log in comments or strings vs real calls) before writing \u2014 handle them in the initial script, never iterate. Show the full file content and how to install it (chmod +x, correct .git/hooks/ path). For pre-commit hooks that check staged content: always use 'git diff --cached' to get only staged changes \u2014 never grep full file content, which would catch unstaged lines. Use '--diff-filter=ACM' to target added/copied/modified files \u2014 NEVER use '--diff-filter=D' (that shows ONLY deleted files, opposite of intent). NEVER use 'set -e' in pre-commit hooks \u2014 grep exits 1 on no match, which kills the entire script under set -e. Use explicit 'if git diff --cached ... | grep -q ...; then' flow control instead, and check exit codes explicitly. REGEX FALSE POSITIVES IN DIFF OUTPUT: Diff lines start with '+' (added) or '-' (removed) \u2014 the actual code content comes AFTER the leading '+'/'-'. This means 'grep -v "^s*//"' does NOT exclude comment lines in diff output because the line starts with '+', not with whitespace. CORRECT pipeline for detecting console.log in staged .js changes while excluding comment lines: 'git diff --cached -- "*.js" | grep "^+" | grep -v "^+++" | grep -v "^+[[:space:]]*//" | grep -q "console.log"'. The key pattern is '^+[[:space:]]*//' \u2014 match lines where after the '+' prefix comes optional whitespace then '//'. Always use this exact pipeline, never 'grep -v "^s*//"' on diff output. CONSOLE METHODS: When a task asks to block console.log, explicitly address whether console.warn, console.error, console.debug, and console.info should also be blocked \u2014 if the intent is "no console output in production", block all console methods with a single pattern like 'console.(log|warn|error|debug|info)'.
918
918
  - **Memory leak explanations**: Show the problematic code, then present the primary fix (move emitter.on() outside the loop, registered once) with the original setInterval kept intact for its intended purpose. Then briefly mention 2 alternatives: (1) emitter.once() if only one event needs handling, (2) removeAllListeners() (or emitter.off(event, handler)) BEFORE re-registering inside the loop. CRITICAL for alternative 2: you MUST call removeAllListeners() or off() BEFORE the new emitter.on() \u2014 if you call emitter.on() inside an interval without first removing the previous listener, a new listener accumulates on every tick, which is the same leak as the original. Always show the removal step explicitly. Do NOT replace the setInterval body with an empty callback \u2014 keep the interval doing its original work.
919
919
  - **Makefile tasks**: ALWAYS follow this exact order: (1) paste the COMPLETE Makefile in a fenced code block in your text response FIRST, (2) THEN optionally write it to a file with a tool. The user cannot see files you write \u2014 your text response is the ONLY output they receive. Calling write_file does NOT substitute for pasting the code in your response. Never describe the Makefile in prose \u2014 paste the actual code. Every target, every recipe, every .PHONY line. Use EXACTLY the tools specified (jest means jest directly, not npm test; tsc means tsc, never npx tsc). Never put glob patterns like src/**/*.ts in prerequisites \u2014 make does not expand them. MAKEFILE SYNTAX RULES (hard requirements): (a) Recipe lines MUST be indented with a real TAB character \u2014 never spaces; a space-indented recipe causes "missing separator" errors. CRITICAL: commands go on the NEXT LINE after the target, indented with a TAB \u2014 NEVER on the same line. WRONG: "build: tsc" (puts tsc as a file dependency, does nothing). RIGHT: "build:
920
- tsc" (TAB then tsc on the line below). (b) Declare ALL phony targets in a SINGLE .PHONY line at the top \u2014 NEVER split .PHONY across multiple declarations. (c) NEVER define the same target name twice \u2014 duplicate targets silently override each other and produce contradictory behaviour. (d) Do NOT add @echo lines unless the task explicitly asks for output messages. (e) DEPENDENCY CHAIN: if the task describes a test target that runs tests after compilation/building, the test target MUST declare an explicit dependency on build (e.g. "test: build") \u2014 otherwise make test runs against stale or missing binaries. When in doubt, add the dependency; omitting it is always the wrong default. (f) 'all' target ordering: NEVER write "all: clean build test" and rely on make's left-to-right execution \u2014 with parallel make (-j) this is not guaranteed. Instead, encode the sequence via individual target dependencies: "test: build", "build: clean" (if clean\u2192build\u2192test is the intent), so the chain is enforced regardless of parallelism. Or use ordered prerequisites with .NOTPARALLEL if the task explicitly requires strict ordering.
920
+ tsc" (TAB then tsc on the line below). (b) Declare ALL phony targets in a SINGLE .PHONY line at the top \u2014 NEVER split .PHONY across multiple declarations. (c) NEVER define the same target name twice \u2014 duplicate targets silently override each other and produce contradictory behaviour. (d) Do NOT add @echo lines unless the task explicitly asks for output messages. (e) DEPENDENCY CHAIN: if the task describes a test target that runs tests after compilation/building, the test target MUST declare an explicit dependency on build (e.g. "test: build") \u2014 otherwise make test runs against stale or missing binaries. When in doubt, add the dependency; omitting it is always the wrong default. (f) 'all' target ordering: NEVER write "all: clean build test" and rely on make's left-to-right execution \u2014 with parallel make (-j) this is not guaranteed. Instead, encode the sequence via individual target dependencies: "test: build", "build: dist" (if clean\u2192build\u2192test is the intent), so the chain is enforced regardless of parallelism. Or use ordered prerequisites with .NOTPARALLEL if the task explicitly requires strict ordering. NEVER make 'build' depend on 'clean' \u2014 this causes 'build' to always wipe the output directory, and 'all' will trigger 'clean' twice due to redundant dependency chaining.
921
921
  - **Dataclass definitions**: Paste the COMPLETE dataclass code directly in your text response \u2014 @dataclass decorator, all fields with type annotations and defaults, full __post_init__ validation block. The code must appear verbatim in your chat text. Writing a file with a tool does NOT satisfy this \u2014 always also paste the code in text.
922
- - **Cron expressions**: Before writing each expression, quote the exact constraint from the task, then derive the expression. Double-check boundary values match exactly what was asked. NEVER put cron expressions inside markdown tables \u2014 asterisks (*) in table cells are consumed as bold/italic markers and disappear. Always present each cron expression in its own fenced code block. For "every N minutes between X-Yh": only present both interpretations (inclusive vs. exclusive endpoint) when the task is genuinely ambiguous about whether the endpoint fires. If the task explicitly states "8-18h" or "until 18h" without qualification, write the expression with 8-18 directly \u2014 do NOT second-guess or add a confusing dual-interpretation note that contradicts the explicit request. The note is only appropriate when the task says something like "during business hours" or "until approximately 18h" where intent is unclear. CRITICAL OFF-BY-ONE: "8-18h" means the hour field is 8-18 (runs fire AT 18:00 are INCLUDED). Writing 8-17 silently drops the 18:00 run \u2014 this is WRONG. If you notice mid-response that you wrote 8-17 for an 8-18h spec, CORRECT THE EXPRESSION in-place immediately \u2014 do NOT leave both versions and add a contradictory note.
922
+ - **Cron expressions**: Before writing each expression, quote the exact constraint from the task, then derive the expression. Double-check boundary values match exactly what was asked. NEVER put cron expressions inside markdown tables \u2014 asterisks (*) in table cells are consumed as bold/italic markers and disappear. Always present each cron expression in its own fenced code block. For "every N minutes between X-Yh": only present both interpretations (inclusive vs. exclusive endpoint) when the task is genuinely ambiguous about whether the endpoint fires. If the task explicitly states "8-18h" or "until 18h" without qualification, write the expression with 8-18 directly \u2014 do NOT second-guess or add a confusing dual-interpretation note that contradicts the explicit request. The note is only appropriate when the task says something like "during business hours" or "until approximately 18h" where intent is unclear. CRITICAL OFF-BY-ONE: "8-18h" means the hour field is 8-18 (runs fire AT 18:00 are INCLUDED). Writing 8-17 silently drops the 18:00 run \u2014 this is WRONG. If you notice mid-response that you wrote 8-17 for an 8-18h spec, CORRECT THE EXPRESSION in-place immediately \u2014 do NOT leave both versions and add a contradictory note. When correcting, explicitly state the fix: "8-18h \u2192 8-18" to avoid any ambiguity.
923
923
  - **Express/fetch error handling**: When adding error handling to an Express route that fetches by ID: (1) validate the ID parameter first (check it exists and is a valid format), (2) wrap fetch in try-catch, (3) check response.ok and handle 404 specifically, (4) call next(error) to pass errors to Express error-handling middleware \u2014 do not just send a raw 500 response.
924
924
  - **Command suggestions**: Always use correct command flags and syntax. For null-delimited output, use --zero or find/printf instead of non-existent flags like -0.
925
925
  - **sed -i portability**: When showing 'sed -i' for in-place file editing, always note the macOS/BSD vs GNU difference: on macOS/BSD, '-i' requires an explicit backup suffix argument (e.g. 'sed -i "" "s/old/new/" file' for no backup, or 'sed -i.bak ...' for a backup); on GNU/Linux, 'sed -i "s/old/new/" file' works without the extra argument. When the user's platform is unknown or macOS, show the macOS-compatible form first. For cross-platform scripts, suggest 'perl -i -pe' as a portable alternative.
@@ -1087,7 +1087,7 @@ You have a soft budget of ~30 tool calls per task. Sessions with >40 tool calls
1087
1087
  - Instead: use bash with inline node -e '...' for quick one-off checks.
1088
1088
  - If the test is worth keeping, write it to tests/ with a proper name.
1089
1089
  - Write-then-delete patterns waste 3 tool calls and leave orphans if the session is interrupted.
1090
- ${OE()}
1090
+ ${NE()}
1091
1091
 
1092
1092
  # Edit Protocol (Mandatory \u2014 Follow These Steps Exactly)
1093
1093
 
@@ -1278,72 +1278,78 @@ class ErrorBoundary extends React.Component {
1278
1278
  - Use migrations for schema changes, never manual ALTER TABLE
1279
1279
  - Add database-level constraints (unique, foreign key, check) not just app-level
1280
1280
 
1281
- `,kc=t,Fo}function Ig(){Nc.clear(),Mc.clear(),zo.clear(),Pc.clear(),Ko.clear(),xn.clear(),dn.clear(),Xo.clear(),Rt.clear(),as.clear(),Li.clear(),Ii.clear(),Ct=0,Uo=0,vi=0,xt=!1,Ti=0,os=-1,Ec=!1,Ri=0,Ci=!1,Zt=0,jt=!1,fn=0,qt=0,Ze=!1,ht="",Wo=0,Ai="",rs=0,Oi="",is=0,At=!1,Tc=!1,Le="plan",Di=0,_e=!1,pn=null,Rc=null,Cc=null,Yo=0,Sn=0,Gs=null,Vo.clear(),Jo.clear(),vc="",Ei=0}function ME(){j=[],Ho=null,Ig();try{let{resetCompactionFailures:t}=bl();t()}catch{}}function PE(){j.length>kg&&j.splice(0,j.length-kg)}function LE(){return j.length}function IE(){return j}function DE(t){j=t}async function jE(){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(`
1282
- `):[]).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=ji.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+=`
1283
- \u{1F4E6} ${p}${h}`}}catch{}return c}function qE(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 Pe(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(`
1284
- ${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`;qE(c)}if(Jo.size>0&&Vo.size>0)for(let c of Jo){let u=Vo.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 FE(){if(!process.stdout.isTTY)return{action:"quit"};let t=Hs(),e=Ft(),s=Pi.fast?.[t],n=Pi.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}
1285
- `),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)})}var Qt=null;async function BE(t,e=null,s={}){let n=eE(Ft());xg=n.staleWarn,hc=n.staleAbort,Qt=e;let o=t;Ho&&typeof t=="string"&&(o=`${Ho}
1281
+ `,Sc=t,Bo}function Dg(){Mc.clear(),Pc.clear(),Ko.clear(),Lc.clear(),Xo.clear(),Sn.clear(),fn.clear(),Vo.clear(),Ot.clear(),cs.clear(),Di.clear(),ji.clear(),Nt=0,Wo=0,Ti=0,St=!1,Ci=0,is=-1,Tc=!1,Ai=0,Oi=!1,Pt=0,Lt=!1,pn=0,Wt=0,et=!1,wt="",Ho=0,Ni="",as=0,Mi="",ls=0,Mt=!1,Rc=!1,Le="plan",qi=0,_e=!1,hn=null,Cc=null,Ac=null,Go=0,En=0,Gs=null,Jo.clear(),Zo.clear(),Ec="",Ri=0}function PE(){D=[],Yo=null,Dg();try{let{resetCompactionFailures:t}=kl();t()}catch{}}function LE(){D.length>Sg&&D.splice(0,D.length-Sg)}function IE(){return D.length}function DE(){return D}function jE(t){D=t}async function qE(){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(`
1282
+ `):[]).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=Fi.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+=`
1283
+ \u{1F4E6} ${p}${h}`}}catch{}return c}function FE(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 Pe(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(`
1284
+ ${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`;FE(c)}if(Zo.size>0&&Jo.size>0)for(let c of Zo){let u=Jo.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 BE(){if(!process.stdout.isTTY)return{action:"quit"};let t=Hs(),e=Ht(),s=Ii.fast?.[t],n=Ii.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}
1285
+ `),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)})}var tn=null;async function UE(t,e=null,s={}){let n=tE(Ht());kg=n.staleWarn,mc=n.staleAbort,tn=e;let o=t;Yo&&typeof t=="string"&&(o=`${Yo}
1286
1286
 
1287
- ${t}`,Ho=null),typeof o=="string"&&Ng(o)&&(o+=`
1287
+ ${t}`,Yo=null),typeof o=="string"&&Mg(o)&&(o+=`
1288
1288
 
1289
- [Note for assistant: the user appears frustrated \u2014 acknowledge their concern briefly and empathetically before proceeding]`);let r=Og(o);r&&typeof r.then=="function"&&(r=await r),j.push({role:"user",content:r}),PE();let i=s.autoOrchestrate!==!1&&process.env.NEX_AUTO_ORCHESTRATE!=="false",a=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10);try{let{detectComplexPrompt:be,runOrchestrated:ke}=dg(),Re=be(typeof t=="string"?t:"");if(i&&Re.isComplex&&Re.estimatedGoals>=a)return console.log(`${m.yellow}\u26A1 Auto-orchestrate: ${Re.estimatedGoals} goals \u2192 parallel agents${m.reset}`),await ke(t,{orchestratorModel:s.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL,workerModel:s.model});Re.isComplex&&process.stdout.isTTY&&console.log(`${m.dim}Hint: ~${Re.estimatedGoals} goals detected. Disable with NEX_AUTO_ORCHESTRATE=false${m.reset}`)}catch{}let{setOnChange:l}=_l(),c=null,u=0;l((be,ke)=>{be==="create"?(c&&c.stop(),c=new dv(ke.name,ke.tasks),c.setStats({tokens:u}),c.start()):be==="update"&&c?c.updateTask(ke.id,ke.status):be==="clear"&&c&&(c.stop(),c=null)});let d=await Oc(),f=d;try{let{getBrainContext:be}=Ll(),ke=await be(t);ke&&(f=d+`
1289
+ [Note for assistant: the user appears frustrated \u2014 acknowledge their concern briefly and empathetically before proceeding]`);let r=Ng(o);r&&typeof r.then=="function"&&(r=await r),D.push({role:"user",content:r}),LE();let i=s.autoOrchestrate!==!1&&process.env.NEX_AUTO_ORCHESTRATE!=="false",a=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10);try{let{detectComplexPrompt:be,runOrchestrated:ke}=fg(),Ce=be(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 it=await ke(t,{orchestratorModel:s.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL,workerModel:s.model});if(it&&it.synthesis){let at=it.synthesis.summary||"",mn=it.synthesis.filesChanged?.length?`
1290
+
1291
+ Files changed: ${it.synthesis.filesChanged.join(", ")}`:"",ze=it.synthesis.conflicts?.length?`
1292
+
1293
+ Conflicts:
1294
+ ${it.synthesis.conflicts.map(vt=>`- ${vt}`).join(`
1295
+ `)}`:"";D.push({role:"assistant",content:at+mn+ze}),Ne(D),xi(D)}return it}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}=bl(),c=null,u=0;l((be,ke)=>{be==="create"?(c&&c.stop(),c=new fv(ke.name,ke.tasks),c.setStats({tokens:u}),c.start()):be==="update"&&c?c.updateTask(ke.id,ke.status):be==="clear"&&c&&(c.stop(),c=null)});let d=await Nc(),f=d;try{let{getBrainContext:be}=Dl(),ke=await be(t);ke&&(f=d+`
1290
1296
  `+ke+`
1291
- `)}catch(be){process.env.NEX_DEBUG&&console.error("[agent] brain context failed:",be.message)}let h=Vv(typeof t=="string"?t:"");if(h.length>0){let be=h.map(ke=>`[Triggered: ${ke.name}]
1297
+ `)}catch(be){process.env.NEX_DEBUG&&console.error("[agent] brain context failed:",be.message)}let h=Jv(typeof t=="string"?t:"");if(h.length>0){let be=h.map(ke=>`[Triggered: ${ke.name}]
1292
1298
  ${ke.instructions}`).join(`
1293
1299
  `);f+=`
1294
1300
  `+be+`
1295
- `}let g=[{role:"system",content:f},...j];hv(Ft());let _=new Ws(ac());_.start();let b=j.length===1,O=b?jE().catch(()=>null):Promise.resolve(null),M=b?Nv(typeof t=="string"?t:"").catch(()=>null):Promise.resolve(null),k=ot(),[{messages:E,compressed:N,compacted:ee,tokensRemoved:X},ce,ae]=await Promise.all([_v(g,k),O,M]),ne=Dt(g,k);if(_.stop(),ce&&console.log(`${m.dim}${ce}${m.reset}`),ee)console.log(`${m.dim} [context compacted \u2014 summary (~${X} tokens freed)]${m.reset}`);else if(N){let be=ne.limit>0?Math.round(X/ne.limit*100):0;F(`${m.dim} [context compressed \u2014 ~${X} tokens freed (${be}%)]${m.reset}`)}ne.percentage>85&&F(`${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 S=E;if(ae&&b&&(S=[S[0],{role:"user",content:`[Server probe at task start]
1296
- ${ae}`},{role:"assistant",content:"Understood \u2014 I have the server context. Proceeding with the task."},...S.slice(1)]),b){let be=Mv(typeof t=="string"?t:"");be&&(S=[S[0],{role:"user",content:be.user},{role:"assistant",content:be.assistant},...S.slice(1)])}if(Dt(S,ot()).percentage>=65){let{messages:ke,tokensRemoved:Re}=Vt(S,ot());Re>0&&(S=ke,console.log(`${m.dim} [pre-flight compress \u2014 ${Re} tokens freed, now ${Math.round(Dt(S,ot()).percentage)}% used]${m.reset}`))}let Te=0,H=0,K=0,pe=0,ve=0,Be=9,$e=0,ye=(()=>{let be=j.find(ke=>ke.role==="user");return typeof be?.content=="string"?be.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(ye),P=0;if(!Ze){let be=j.filter(Re=>Re.role==="user"||Re.role==="tool").map(Re=>typeof Re.content=="string"?Re.content:"").join(`
1297
- `),ke=gc(be);ke&&(Ze=!0,ht=ke.slice(0,120),F(`${m.yellow} \u26A1 Root cause in briefing: ${ht} \u2014 fix phase active from start (read budget: 3)${m.reset}`))}!Ze&&!At&&/\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(ye)&&(At=!0,F(`${m.cyan} \u26A1 Creation task detected \u2014 tight investigation cap (4 pre-edit, 2 post-edit)${m.reset}`)),j.length<=1&&!s.skipPhaseRouting&&(_e=Rv(),_e&&(Gs=Tv(ye)?.id||"coding",Le="plan",pn=$c("plan",Gs),Di=0,Yo=0,Sn=0,process.stdout.isTTY&&console.log(`${m.dim} \u21B3 Phase routing: plan(${pn||"default"}) \u2192 implement \u2192 verify${m.reset}`),F(`${m.cyan} \u26A1 Phase routing enabled \u2014 plan phase with ${pn||"default model"} (category: ${Gs})${m.reset}`)));let R=0,B=new Map,T=new Set,x=new Set,se=new Set,we=0,ge=0,he=Date.now(),Wi=new mv(nE),Zg=Xo,Ue=s.skillLoop?10:1,Qg=3*Ue,ey=5*Ue,Hc=Nc,ty=5*Ue,ny=8*Ue,sy=Mc,oy=(_e?6:4)*Ue,ry=(_e?10:7)*Ue,Hi=zo,iy=(_e?5:3)*Ue,Qo=(_e?8:5)*Ue,ay=Pc,ly=(_e?4:3)*Ue,cy=(_e?6:4)*Ue,uy=3*Ue,dy=4*Ue,ls=xn,fy=(_e?3:2)*Ue,py=(_e?5:3)*Ue,cs=(_e?6:4)*Ue,hy=25,vn=0,my=6*Ue,gy=10*Ue,En=0,Yc=5*Ue,Tn=0,yy=2*Ue,wy=3,Yi=0,Xs=10,_y=16,Gc=s.skillLoop?999:n.investigationCap,We,Bt=s.maxIterations||(_e?ns(Le):xc),Gi=0,zc=3,zi=!1,er=0;e:for(;;){for(zi=!1,We=0;We<Bt&&!ki()?.aborted;We++){{let w=ot(),y=Dt(S,w),J=R===0?65:78;if(y.percentage>=J){if(T.size>0||_e&&Le!=="plan"){let Q=bv(j,{filesModified:T,currentPhase:_e?Le:null});if(Q){let q=S.findIndex(I=>I._progressSnapshot);q!==-1&&S.splice(q,1);let ue=S.findIndex(I=>I.role==="system");S.splice(ue+1,0,Q)}}let{messages:C,tokensRemoved:L}=Vt(S,w,R===0);if(L>0&&(S=C,L>50&&console.log(`${m.dim} [auto-compressed \u2014 ~${L} tokens freed, now ${Math.round(Dt(S,w).percentage)}%]${m.reset}`),At&&T.size>=3)){let Q=[...T].map(ue=>ue.split("/").pop()).slice(0,10).join(", "),q={role:"user",content:`[FRAMEWORK \u2014 context compressed] Task is IN PROGRESS. Already created ${T.size} files: ${Q}. DO NOT restart or re-investigate what was already done. Continue from where you left off.`};S.push(q)}}}if(xt&&!Ze&&Wo<2){Wo++;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),j.push(w),F(`${m.yellow} \u26A0 Pre-call SSH-blocked nudge #${Wo} injected \u2014 model told to synthesize${m.reset}`)}xt||(Wo=0);let ke=!0;R>0&&Uv();let Re=null;if(c&&c.isActive())c._paused&&c.resume();else if(!c){let w,y=Wv();if(y&&y.total>1){let J=y.description.length>40?y.description.slice(0,37)+"\u2026":y.description;w=`Plan step ${y.current}/${y.total}: ${J}`}else w=R>0?`${ac()} (step ${R+1})`:ac();Re=new Ws(w),Re.start()}let us=!0,gt="",ds=!1,et=new Hv,Ut,Ki=Date.now(),tr=!1,Xi=new AbortController,Kc=setInterval(()=>{let w=Date.now()-Ki;if(w>=hc)et._clearCursorLine(),F(`${m.yellow} \u26A0 Stream stale for ${Math.round(w/1e3)}s \u2014 aborting and retrying${m.reset}`),Xi.abort();else if(w>=xg&&!tr){tr=!0,et._clearCursorLine();let y=Pi.fast?.[Hs()],J=K>0?` (retry ${K+1}/${bi})`:"",C=Math.round((hc-w)/1e3);F(`${m.yellow} \u26A0 No tokens received for ${Math.round(w/1e3)}s \u2014 waiting...${J}${m.reset}`),y&&y!==Ft()?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),kt="",en=null;try{let w=Mg(ot()),y=new Set(["read_file","list_directory","search_files","glob","grep","git_status","git_diff","git_log","git_show","ssh_exec"]),J=new Set(["read_file","list_directory","glob","grep","bash","git_status","git_diff","git_log","ssh_exec"]),C;Go()?C=w.filter(q=>Tg.has(q.function.name)):_e&&Le==="plan"?C=w.filter(q=>y.has(q.function.name)):_e&&Le==="verify"?C=w.filter(q=>J.has(q.function.name)):C=w;let L=ki(),Q=new AbortController;L&&L.addEventListener("abort",()=>Q.abort(),{once:!0}),Xi.signal.addEventListener("abort",()=>Q.abort(),{once:!0}),Ut=await fg(S,C,{signal:Q.signal,...pn?{model:pn}:{},onThinkingToken:()=>{Ki=Date.now(),tr=!1,Qt?.onThinkingToken&&Qt.onThinkingToken()},onToken:q=>{if(Ki=Date.now(),tr=!1,Qt?.onToken){Qt.onToken(q),gt+=q;return}if(gt+=q,!ds&&gt.length>400&&gt.length%250<q.length+1){let ue=bc(gt,3);ue.truncated&&(ds=!0,et._clearCursorLine?.(),F(`${m.yellow} \u26A0 LLM stream loop detected (${ue.repeatCount}\xD7 repeated) \u2014 suppressing display${m.reset}`))}ds||(kt+=q,process.stdout.isTTY?en||(en=setTimeout(()=>{kt&&et&&et.push(kt),kt="",en=null},50)):(et.push(kt),kt=""),us&&(c&&!c._paused?c.pause():Re&&Re.stop(),ke||(ke=!0),et.startCursor(),us=!1))}})}catch(w){if(clearInterval(Kc),en&&(clearTimeout(en),en=null),kt&&et&&(et.push(kt),kt=""),c&&!c._paused&&c.pause(),Re&&Re.stop(),et.stopCursor(),Xi.signal.aborted&&!ki()?.aborted){if(K++,K>bi){if(pe<1){pe++,Us("Stale retries exhausted \u2014 last-resort force-compress...",m.yellow);let ue=ot(),{messages:I,tokensRemoved:U}=Vt(S,ue);S=I,U>50&&F(`${m.dim} [force-compressed \u2014 ~${U} tokens freed]${m.reset}`),K=0,We--;continue}c&&(c.stop(),c=null);let q=await FE();if(q.action==="quit"){l(null),Pe(R,B,T,x,he),Me(j);break}q.action==="switch"&&(wg(`${q.provider}:${q.model}`),console.log(`${m.green} \u2713 Switched to ${q.provider}:${q.model}${m.reset}`)),K=0,We--;continue}let L=K===1?3e3:5e3;if(K>=1&&$e<1){$e++,Us(`Stale retry ${K}/${bi} \u2014 force-compressing before retry...`,m.yellow);let q=ot(),{messages:ue,tokensRemoved:I}=Vt(S,q,!0);if(S=ue,I>0&&I>50&&F(`${m.dim} [force-compressed \u2014 ~${I} tokens freed]${m.reset}`),bE){let U=Pi.fast?.[Hs()];U&&U!==Ft()&&(wg(`${Hs()}:${U}`),console.log(`${m.cyan} \u26A1 Auto-switched to ${U} to avoid further stale timeouts${m.reset}`),console.log(`${m.dim} (disable with NEX_STALE_AUTO_SWITCH=0)${m.reset}`))}}else F(`${m.yellow} \u26A0 Stale retry ${K}/${bi} \u2014 retrying in ${L/1e3}s...${m.reset}`);let Q=new Ws(`Waiting ${L/1e3}s before retry...`);Q.start(),await new Promise(q=>setTimeout(q,L)),Q.stop(),We--;continue}if(w.name==="AbortError"||w.name==="CanceledError"||w.message?.includes("canceled")||w.message?.includes("aborted")){c&&(c.stop(),c=null),l(null),Pe(R,B,T,x,he),Me(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): ${Ft?Ft():"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),Pe(R,B,T,x,he),Me(j);break}else if(w.message.includes("400")){if(pe<3&&ve<Be){pe++,ve++;let L=R===0&&pe===1,Q=L||pe===3||$e>0;if(L){pe=3;let U=w.message.replace(/^API Error(\s*\[HTTP \d+\])?:\s*/i,"").slice(0,150);Us(`Bad request (400) \u2014 ${U||"system prompt too large"}, compressing...`,m.yellow)}else Us(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 q=ot(),{messages:ue,tokensRemoved:I}=Vt(S,q,Q);S=ue,I>50&&F(`${m.dim} [force-compressed \u2014 ~${I} tokens freed]${m.reset}`),We--;continue}{let L=S.find(W=>W.role==="system"),Q=S.find(W=>W.role==="user"&&!String(W.content).startsWith("[SYSTEM")&&!String(W.content).startsWith("BLOCKED:")),q=[L,Q].filter(Boolean),{getUsage:ue}=Kt(),I=Kt().estimateMessagesTokens(q),U=Kt().estimateMessagesTokens(S);if(I<U){let W=[],V=j.filter(oe=>oe.role==="assistant"&&typeof oe.content=="string"&&oe.content.trim().length>30).slice(-5).map(oe=>oe.content.trim().slice(0,300).replace(/\n+/g," "));V.length>0&&W.push(`Key findings:
1298
- `+V.map(oe=>`- ${oe}`).join(`
1299
- `));let Z=j.filter(oe=>oe.role==="tool"&&typeof oe.content=="string"&&!oe.content.startsWith("BLOCKED:")&&oe.content.trim().length>10).slice(-5).map(oe=>oe.content.trim().split(`
1301
+ `}let g=[{role:"system",content:f},...D];mv(Ht());let _=new Ws(cc());_.start();let b=D.length===1,O=b?qE().catch(()=>null):Promise.resolve(null),M=b?Mv(typeof t=="string"?t:"").catch(()=>null):Promise.resolve(null),k=rt(),[{messages:E,compressed:N,compacted:te,tokensRemoved:X},ce,ae]=await Promise.all([$v(g,k),O,M]),se=Ut(g,k);if(_.stop(),ce&&console.log(`${m.dim}${ce}${m.reset}`),te)console.log(`${m.dim} [context compacted \u2014 summary (~${X} tokens freed)]${m.reset}`);else if(N){let be=se.limit>0?Math.round(X/se.limit*100):0;q(`${m.dim} [context compressed \u2014 ~${X} tokens freed (${be}%)]${m.reset}`)}se.percentage>85&&q(`${m.yellow} \u26A0 Context ${Math.round(se.percentage)}% used (${Math.round(100-se.percentage)}% remaining) \u2014 consider /clear or /save + start fresh${m.reset}`);let S=E;if(ae&&b&&(S=[S[0],{role:"user",content:`[Server probe at task start]
1302
+ ${ae}`},{role:"assistant",content:"Understood \u2014 I have the server context. Proceeding with the task."},...S.slice(1)]),b){let be=Pv(typeof t=="string"?t:"");be&&(S=[S[0],{role:"user",content:be.user},{role:"assistant",content:be.assistant},...S.slice(1)])}if(Ut(S,rt()).percentage>=65){let{messages:ke,tokensRemoved:Ce}=Qt(S,rt());Ce>0&&(S=ke,console.log(`${m.dim} [pre-flight compress \u2014 ${Ce} tokens freed, now ${Math.round(Ut(S,rt()).percentage)}% used]${m.reset}`))}let Re=0,H=0,K=0,pe=0,ve=0,Ue=9,$e=0,ye=(()=>{let be=D.find(ke=>ke.role==="user");return typeof be?.content=="string"?be.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(ye),P=0;if(!et){let be=D.filter(Ce=>Ce.role==="user"||Ce.role==="tool").map(Ce=>typeof Ce.content=="string"?Ce.content:"").join(`
1303
+ `),ke=yc(be);ke&&(et=!0,wt=ke.slice(0,120),q(`${m.yellow} \u26A1 Root cause in briefing: ${wt} \u2014 fix phase active from start (read budget: 3)${m.reset}`))}!et&&!Mt&&/\b(create|build|generate|implement|write|make|develop|set\s*up|scaffold|add)\b.{0,80}\b(app|component|page|game|api|backend|frontend|server|service|module|class|function|feature|project|system|bot|script|tool)\b/i.test(ye)&&(Mt=!0,q(`${m.cyan} \u26A1 Creation task detected \u2014 tight investigation cap (4 pre-edit, 2 post-edit)${m.reset}`)),D.length<=1&&!s.skipPhaseRouting&&(_e=Cv(),_e&&(Gs=Rv(ye)?.id||"coding",Le="plan",hn=bc("plan",Gs),qi=0,Go=0,En=0,process.stdout.isTTY&&console.log(`${m.dim} \u21B3 Phase routing: plan(${hn||"default"}) \u2192 implement \u2192 verify${m.reset}`),q(`${m.cyan} \u26A1 Phase routing enabled \u2014 plan phase with ${hn||"default model"} (category: ${Gs})${m.reset}`)));let R=0,B=new Map,T=new Set,x=new Set,oe=new Set,we=0,ge=0,he=Date.now(),Yi=new gv(sE),Qg=Vo,We=s.skillLoop?10:1,ey=3*We,ty=5*We,Yc=Mc,ny=5*We,sy=8*We,oy=Pc,ry=(_e?6:4)*We,iy=(_e?10:7)*We,Gi=Ko,ay=(_e?5:3)*We,er=(_e?8:5)*We,ly=Lc,cy=(_e?4:3)*We,uy=(_e?6:4)*We,dy=3*We,fy=4*We,us=Sn,py=(_e?3:2)*We,hy=(_e?5:3)*We,ds=(_e?6:4)*We,my=25,Tn=0,gy=6*We,yy=10*We,Rn=0,Gc=5*We,Cn=0,wy=2*We,_y=3,zi=0,Xs=10,$y=16,zc=s.skillLoop?999:n.investigationCap,He,Yt=s.maxIterations||(_e?os(Le):kc),Ki=0,Kc=3,Xi=!1,tr=0;e:for(;;){for(Xi=!1,He=0;He<Yt&&!vi()?.aborted;He++){{let w=rt(),y=Ut(S,w),J=R===0?65:78;if(y.percentage>=J){if(T.size>0||_e&&Le!=="plan"){let ee=xv(D,{filesModified:T,currentPhase:_e?Le:null});if(ee){let F=S.findIndex(I=>I._progressSnapshot);F!==-1&&S.splice(F,1);let ue=S.findIndex(I=>I.role==="system");S.splice(ue+1,0,ee)}}let{messages:C,tokensRemoved:L}=Qt(S,w,R===0);if(L>0&&(S=C,L>50&&console.log(`${m.dim} [auto-compressed \u2014 ~${L} tokens freed, now ${Math.round(Ut(S,w).percentage)}%]${m.reset}`),Mt&&T.size>=3)){let ee=[...T].map(ue=>ue.split("/").pop()).slice(0,10).join(", "),F={role:"user",content:`[FRAMEWORK \u2014 context compressed] Task is IN PROGRESS. Already created ${T.size} files: ${ee}. DO NOT restart or re-investigate what was already done. Continue from where you left off.`};S.push(F)}}}if(St&&!et&&Ho<2){Ho++;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),D.push(w),q(`${m.yellow} \u26A0 Pre-call SSH-blocked nudge #${Ho} injected \u2014 model told to synthesize${m.reset}`)}St||(Ho=0);let ke=!0;R>0&&Wv();let Ce=null;if(c&&c.isActive())c._paused&&c.resume();else if(!c){let w,y=Hv();if(y&&y.total>1){let J=y.description.length>40?y.description.slice(0,37)+"\u2026":y.description;w=`Plan step ${y.current}/${y.total}: ${J}`}else w=R>0?`${cc()} (step ${R+1})`:cc();Ce=new Ws(w),Ce.start()}let it=!0,at="",mn=!1,ze=new Yv,vt,Vi=Date.now(),nr=!1,Ji=new AbortController,Xc=setInterval(()=>{let w=Date.now()-Vi;if(w>=mc)ze._clearCursorLine(),q(`${m.yellow} \u26A0 Stream stale for ${Math.round(w/1e3)}s \u2014 aborting and retrying${m.reset}`),Ji.abort();else if(w>=kg&&!nr){nr=!0,ze._clearCursorLine();let y=Ii.fast?.[Hs()],J=K>0?` (retry ${K+1}/${ki})`:"",C=Math.round((mc-w)/1e3);q(`${m.yellow} \u26A0 No tokens received for ${Math.round(w/1e3)}s \u2014 waiting...${J}${m.reset}`),y&&y!==Ht()?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),Et="",nn=null;try{let w=Pg(rt()),y=new Set(["read_file","list_directory","search_files","glob","grep","git_status","git_diff","git_log","git_show","ssh_exec"]),J=new Set(["read_file","list_directory","glob","grep","bash","git_status","git_diff","git_log","ssh_exec"]),C;zo()?C=w.filter(F=>Rg.has(F.function.name)):_e&&Le==="plan"?C=w.filter(F=>y.has(F.function.name)):_e&&Le==="verify"?C=w.filter(F=>J.has(F.function.name)):C=w;let L=vi(),ee=new AbortController;L&&L.addEventListener("abort",()=>ee.abort(),{once:!0}),Ji.signal.addEventListener("abort",()=>ee.abort(),{once:!0}),vt=await pg(S,C,{signal:ee.signal,...hn?{model:hn}:{},onThinkingToken:()=>{Vi=Date.now(),nr=!1,tn?.onThinkingToken&&tn.onThinkingToken()},onToken:F=>{if(Vi=Date.now(),nr=!1,tn?.onToken){tn.onToken(F),at+=F;return}if(at+=F,!mn&&at.length>400&&at.length%250<F.length+1){let ue=xc(at,3);ue.truncated&&(mn=!0,ze._clearCursorLine?.(),q(`${m.yellow} \u26A0 LLM stream loop detected (${ue.repeatCount}\xD7 repeated) \u2014 suppressing display${m.reset}`))}mn||(Et+=F,process.stdout.isTTY?nn||(nn=setTimeout(()=>{Et&&ze&&ze.push(Et),Et="",nn=null},50)):(ze.push(Et),Et=""),it&&(c&&!c._paused?c.pause():Ce&&Ce.stop(),ke||(ke=!0),ze.startCursor(),it=!1))}})}catch(w){if(clearInterval(Xc),nn&&(clearTimeout(nn),nn=null),Et&&ze&&(ze.push(Et),Et=""),c&&!c._paused&&c.pause(),Ce&&Ce.stop(),ze.stopCursor(),Ji.signal.aborted&&!vi()?.aborted){if(K++,K>ki){if(pe<1){pe++,Us("Stale retries exhausted \u2014 last-resort force-compress...",m.yellow);let ue=rt(),{messages:I,tokensRemoved:U}=Qt(S,ue);S=I,U>50&&q(`${m.dim} [force-compressed \u2014 ~${U} tokens freed]${m.reset}`),K=0,He--;continue}c&&(c.stop(),c=null);let F=await BE();if(F.action==="quit"){l(null),Pe(R,B,T,x,he),Ne(D);break}F.action==="switch"&&(_g(`${F.provider}:${F.model}`),console.log(`${m.green} \u2713 Switched to ${F.provider}:${F.model}${m.reset}`)),K=0,He--;continue}let L=K===1?3e3:5e3;if(K>=1&&$e<1){$e++,Us(`Stale retry ${K}/${ki} \u2014 force-compressing before retry...`,m.yellow);let F=rt(),{messages:ue,tokensRemoved:I}=Qt(S,F,!0);if(S=ue,I>0&&I>50&&q(`${m.dim} [force-compressed \u2014 ~${I} tokens freed]${m.reset}`),xE){let U=Ii.fast?.[Hs()];U&&U!==Ht()&&(_g(`${Hs()}:${U}`),console.log(`${m.cyan} \u26A1 Auto-switched to ${U} to avoid further stale timeouts${m.reset}`),console.log(`${m.dim} (disable with NEX_STALE_AUTO_SWITCH=0)${m.reset}`))}}else q(`${m.yellow} \u26A0 Stale retry ${K}/${ki} \u2014 retrying in ${L/1e3}s...${m.reset}`);let ee=new Ws(`Waiting ${L/1e3}s before retry...`);ee.start(),await new Promise(F=>setTimeout(F,L)),ee.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),Pe(R,B,T,x,he),Ne(D);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): ${Ht?Ht():"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),Pe(R,B,T,x,he),Ne(D);break}else if(w.message.includes("400")){if(pe<3&&ve<Ue){pe++,ve++;let L=R===0&&pe===1,ee=L||pe===3||$e>0;if(L){pe=3;let U=w.message.replace(/^API Error(\s*\[HTTP \d+\])?:\s*/i,"").slice(0,150);Us(`Bad request (400) \u2014 ${U||"system prompt too large"}, compressing...`,m.yellow)}else Us(ee?`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 F=rt(),{messages:ue,tokensRemoved:I}=Qt(S,F,ee);S=ue,I>50&&q(`${m.dim} [force-compressed \u2014 ~${I} tokens freed]${m.reset}`),He--;continue}{let L=S.find(W=>W.role==="system"),ee=S.find(W=>W.role==="user"&&!String(W.content).startsWith("[SYSTEM")&&!String(W.content).startsWith("BLOCKED:")),F=[L,ee].filter(Boolean),{getUsage:ue}=Jt(),I=Jt().estimateMessagesTokens(F),U=Jt().estimateMessagesTokens(S);if(I<U){let W=[],V=D.filter(Q=>Q.role==="assistant"&&typeof Q.content=="string"&&Q.content.trim().length>30).slice(-5).map(Q=>Q.content.trim().slice(0,300).replace(/\n+/g," "));V.length>0&&W.push(`Key findings:
1304
+ `+V.map(Q=>`- ${Q}`).join(`
1305
+ `));let Z=D.filter(Q=>Q.role==="tool"&&typeof Q.content=="string"&&!Q.content.startsWith("BLOCKED:")&&Q.content.trim().length>10).slice(-5).map(Q=>Q.content.trim().split(`
1300
1306
  `).slice(0,8).join(`
1301
1307
  `).slice(0,500));if(Z.length>0&&W.push(`Tool results summary:
1302
- `+Z.map(oe=>`- ${oe}`).join(`
1303
- `)),T.size>0){let oe=[...T].map(Oe=>Oe.split("/").slice(-2).join("/")).join(", ");W.unshift(`Already modified: ${oe} \u2014 use edit_file to add missing pieces only, DO NOT use write_file on these files.`)}if(x.size>0){let oe=[...x].map(Oe=>Oe.split("/").slice(-2).join("/")).join(", ");W.push(`Files already investigated: ${oe}`)}let re=require("os").tmpdir()+"/nex-session-checkpoint.json";try{require("fs").writeFileSync(re,JSON.stringify({filesWritten:[...T].map(oe=>oe.split("/").slice(-2).join("/")),filesRead:[...x].map(oe=>oe.split("/").slice(-2).join("/")),isCreationTask:At,wipeNumber:Uo+1,timestamp:Date.now()},null,2)),W.push(`Session checkpoint: ${re} \u2014 read it for exact file list`)}catch{}let fe=0;{let Oe=((typeof Q?.content=="string"?Q.content:Array.isArray(Q?.content)?Q.content.filter(Xe=>Xe.type==="text").map(Xe=>Xe.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(Xe=>Xe.trim()).filter(Boolean),He=[...T],St=Oe.filter(Xe=>!He.some(Zi=>Zi.endsWith(Xe)||Xe.endsWith(Zi.split("/").pop())));fe=St.length;let yt=[...j].reverse().find(Xe=>Xe.role==="tool"&&typeof Xe.content=="string"&&!Xe.content.startsWith("BLOCKED:")&&Xe.content.length>5),nn={completed:He.map(Xe=>Xe.split("/").slice(-2).join("/")),pending:St.length>0?St:He.length===0?["(task files not yet identified)"]:[],lastEdit:yt?yt.content.trim().slice(0,120):null};(nn.completed.length>0||nn.pending.length>0)&&W.unshift(`Work manifest:
1304
- ${JSON.stringify(nn,null,2)}`)}if(W.length>0){let oe={role:"user",content:`[SYSTEM: Findings from investigation before context wipe]
1308
+ `+Z.map(Q=>`- ${Q}`).join(`
1309
+ `)),T.size>0){let Q=[...T].map(Ee=>Ee.split("/").slice(-2).join("/")).join(", ");W.unshift(`Already modified: ${Q} \u2014 use edit_file to add missing pieces only, DO NOT use write_file on these files.`)}if(x.size>0){let Q=[...x].map(Ee=>Ee.split("/").slice(-2).join("/")).join(", ");W.push(`Files already investigated: ${Q}`)}let re=require("os").tmpdir()+"/nex-session-checkpoint.json";try{require("fs").writeFileSync(re,JSON.stringify({filesWritten:[...T].map(Q=>Q.split("/").slice(-2).join("/")),filesRead:[...x].map(Q=>Q.split("/").slice(-2).join("/")),isCreationTask:Mt,wipeNumber:Wo+1,timestamp:Date.now()},null,2)),W.push(`Session checkpoint: ${re} \u2014 read it for exact file list`)}catch{}let fe=0;{let Ee=((typeof ee?.content=="string"?ee.content:Array.isArray(ee?.content)?ee.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),Ie=[...T],pt=Ee.filter(Je=>!Ie.some(ea=>ea.endsWith(Je)||Je.endsWith(ea.split("/").pop())));fe=pt.length;let Ve=[...D].reverse().find(Je=>Je.role==="tool"&&typeof Je.content=="string"&&!Je.content.startsWith("BLOCKED:")&&Je.content.length>5),Tt={completed:Ie.map(Je=>Je.split("/").slice(-2).join("/")),pending:pt.length>0?pt:Ie.length===0?["(task files not yet identified)"]:[],lastEdit:Ve?Ve.content.trim().slice(0,120):null};(Tt.completed.length>0||Tt.pending.length>0)&&W.unshift(`Work manifest:
1310
+ ${JSON.stringify(Tt,null,2)}`)}if(W.length>0){let Q={role:"user",content:`[SYSTEM: Findings from investigation before context wipe]
1305
1311
  ${W.join(`
1306
1312
  `)}
1307
- Continue implementing the fixes based on these findings.`};q.push(oe)}if(Uo>=3){let oe=T.size>0?`
1308
- Files modified so far: ${[...T].map(Oe=>Oe.split("/").slice(-1)[0]).join(", ")}`:"";F(`${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.${oe?m.dim+oe:""}${m.reset}`),c&&(c.stop(),c=null),l(null),Pe(R,B,T,x,he,{suppressHint:!0}),Me(j);break}S=q,Uo++,os=10+Math.min(fe*3,7),Ec=!0,Ri=T.size,Ci=!1,Ct=0,P=0;for(let[oe,Oe]of xn){let He=Oe?.count??Oe??0;yc(xn,oe,He>=2?He:1)}for(let[oe]of dn)Jt(xn,oe)<2&&dn.delete(oe);Rt.clear(),as.clear(),At&&qt>0&&(jt=!0,F(`${m.cyan} \u26A1 Post-wipe creation guard: cap pre-fired (${qt} edits already made)${m.reset}`));for(let[oe]of zo)yc(zo,oe,Qo-1);if(Us(`Super-nuclear compression \u2014 dropped all history, keeping original task only (${U-I} tokens freed)`,m.yellow),Uo>=1){let oe=[...xn.entries()].filter(([,yt])=>yt>=cs).map(([yt])=>yt.split("/").slice(-1)[0]),Oe=oe.length>0?`
1313
+ Continue implementing the fixes based on these findings.`};F.push(Q)}if(Wo>=3){let Q=T.size>0?`
1314
+ Files modified so far: ${[...T].map(Ee=>Ee.split("/").slice(-1)[0]).join(", ")}`:"";q(`${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.${Q?m.dim+Q:""}${m.reset}`),c&&(c.stop(),c=null),l(null),Pe(R,B,T,x,he,{suppressHint:!0}),Ne(D);break}S=F,Wo++,is=10+Math.min(fe*3,7),Tc=!0,Ai=T.size,Oi=!1,Nt=0,P=0;for(let[Q,Ee]of Sn){let Ie=Ee?.count??Ee??0;wc(Sn,Q,Ie>=2?Ie:1)}for(let[Q]of fn)en(Sn,Q)<2&&fn.delete(Q);Ot.clear(),cs.clear(),Mt&&Wt>0&&(Lt=!0,q(`${m.cyan} \u26A1 Post-wipe creation guard: cap pre-fired (${Wt} edits already made)${m.reset}`));for(let[Q]of Ko)wc(Ko,Q,er-1);if(Us(`Super-nuclear compression \u2014 dropped all history, keeping original task only (${U-I} tokens freed)`,m.yellow),Wo>=1){let Q=[...Sn.entries()].filter(([,Ve])=>Ve>=ds).map(([Ve])=>Ve.split("/").slice(-1)[0]),Ee=Q.length>0?`
1309
1315
 
1310
- Files already at read cap \u2014 use grep_search instead: ${oe.join(", ")}`:"",St={role:"user",content:xt&&!Ze?"[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.${Oe}`};j.push(St),S.push(St)}pe=0,We--;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(Te++,Te>fc){console.log(`${m.red} Rate limit: max retries (${fc}) exceeded. Try again later or use /budget to check your limits.${m.reset}`),c&&(c.stop(),c=null),l(null),Pe(R,B,T,x,he),Me(j);break}let L=Math.min(1e4*Math.pow(2,Te-1),12e4),Q=new Ws(`Rate limit \u2014 waiting ${Math.round(L/1e3)}s (retry ${Te}/${fc})`);Q.start(),await new Promise(q=>setTimeout(q,L)),Q.stop();continue}let J=process.env.NEX_PHASE_ROUTING!=="0"&&(()=>{try{return Ve().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")||J&&(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>pc){console.log(`${m.red} Network error: max retries (${pc}) exceeded. Check your connection and try again.
1311
- Use /undo to revert changes made during this session.${m.reset}`),c&&(c.stop(),c=null),l(null),Pe(R,B,T,x,he),Me(j);break}let L=Math.min(2e3*Math.pow(2,H-1),3e4),Q=new Ws(`API temporarily unavailable \u2014 retrying in ${Math.round(L/1e3)}s (${H}/${pc}). Your changes are safe.`);Q.start(),await new Promise(q=>setTimeout(q,L)),Q.stop(),We--;continue}c&&(c.stop(),c=null),l(null),Pe(R,B,T,x,he),Me(j);break}if(clearInterval(Kc),Te=0,H=0,us&&(c&&!c._paused&&c.pause(),Re&&Re.stop()),en&&(clearTimeout(en),en=null),kt&&et&&(et.push(kt),kt=""),gt&&et.flush(),H=0,K=0,Ut&&Ut.usage){let w=Ut.usage.prompt_tokens||0,y=Ut.usage.completion_tokens||0;hg(Hs(),Ft(),w,y),u+=w+y,c&&c.setStats({tokens:u})}else if(Ut&&!Ut.usage){let w=S.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=gg(w),J=gg(Ut.content||gt||"");hg(Hs(),Ft(),y,J),u+=y+J,c&&c.setStats({tokens:u})}let{content:Xc,tool_calls:tn}=Ut,nr=bc(Xc||""),Vc=nr.truncated?nr.text:Xc;nr.truncated&&F(`${m.yellow} \u26A0 LLM output loop detected (${nr.repeatCount}\xD7 repeated paragraph) \u2014 response truncated${m.reset}`);let sr=lE(Vc||""),Wt=sr.truncated?sr.text:Vc;sr.truncated&&F(`${m.yellow} \u26A0 LLM output loop detected (${sr.repeatCount}\xD7 repeated window) \u2014 response truncated${m.reset}`);let Vi={role:"assistant",content:Wt||""};if(tn&&tn.length>0&&(Vi.tool_calls=tn),j.push(Vi),S.push(Vi),!Ze&&Wt&&tn&&tn.length>0){let w=gc(Wt);if(w){Ze=!0,ht=w.slice(0,120),Zt=0,jt=!1,fn=0,F(`${m.yellow} \u26A1 Root cause in model analysis: ${ht} \u2014 fix phase (read budget: 3)${m.reset}`);let y={role:"user",content:`[SYSTEM] Root cause identified: ${ht}. Read only the file that needs fixing, then edit it. Do not read other files.`};j.push(y),S.push(y)}}if(!tn||tn.length===0){let w=(Wt||"").trim().length>0||gt.trim().length>0,y=!1;if(xt&&w&&(xi>=2?F(`${m.yellow} \u26A0 SSH permanently blocked after ${xi} storm warnings \u2014 no further SSH calls allowed${m.reset}`):(xt=!1,Ct=Xs-4,y=!0)),y&&w){let C=(Wt||"").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."};S.push(Q),j.push(Q);continue}}if(!w&&R>0&&We<xc-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."};S.push(C),j.push(C);continue}let J=/keine.*Tool|can.?t use.*tool|Tool.?Budget|nicht.*zugreifen|cannot.*access|no.*tool.*access|keine.*Werkzeug|da ich keine.*kann/i;if(w&&We<3&&J.test((Wt||"").slice(0,600)))if(Ec&&os<=0||xt){F(`${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."};S.push(L),j.push(L);continue}else{F(`${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."};S.push(L),j.push(L);continue}if(s.skillLoop&&w&&R>3&&er<5){let C=(Wt||gt||"").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))){er=(er||0)+1,F(`${m.yellow} \u26A0 Skill loop: model tried to stop \u2014 continuation nudge #${er}${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."};S.push(Q),j.push(Q);continue}}if(Mi()&&!s.skillLoop&&T.size>0&&w&&R>=2){F(`${m.green} \u2713 Headless early exit: ${T.size} file(s) modified, text response received${m.reset}`),Pe(R,B,T,x,he),Me(j);break e}if(_e&&Le==="plan"&&Sn>=2){F(`${m.cyan} \u21B3 Plan phase: ${Sn} consecutive blocks \u2014 auto-advancing to implement${m.reset}`),Sn=0;let C=qo("implement","[auto-advance: task only requires direct action]");if(C){j.push(C),S.push(C),We=0,Bt=ns("implement");continue}}if(_e&&w){let C=(Wt||gt||"").trim();if(Le==="plan"){let L=qo("implement",C);if(L){j.push(L),S.push(L),We=0,Bt=ns("implement");continue}}else if(Le==="implement"&&T.size>0){let L=j.find(ue=>ue.role==="user"),Q=typeof L?.content=="string"?L.content:"",q=qo("verify",C,T,Q);if(q){j.push(q),S.push(q),We=0,Bt=Math.min(ns("verify")+Math.max(0,(T.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&&Yo<1){Yo++;let q={role:"user",content:`[PHASE: RE-IMPLEMENTATION] Verification found issues:
1316
+ Files already at read cap \u2014 use grep_search instead: ${Q.join(", ")}`:"",pt={role:"user",content:St&&!et?"[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.${Ee}`};D.push(pt),S.push(pt)}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(Re++,Re>pc){console.log(`${m.red} Rate limit: max retries (${pc}) exceeded. Try again later or use /budget to check your limits.${m.reset}`),c&&(c.stop(),c=null),l(null),Pe(R,B,T,x,he),Ne(D);break}let L=Math.min(1e4*Math.pow(2,Re-1),12e4),ee=new Ws(`Rate limit \u2014 waiting ${Math.round(L/1e3)}s (retry ${Re}/${pc})`);ee.start(),await new Promise(F=>setTimeout(F,L)),ee.stop();continue}let J=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")||J&&(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>hc){console.log(`${m.red} Network error: max retries (${hc}) exceeded. Check your connection and try again.
1317
+ Use /undo to revert changes made during this session.${m.reset}`),c&&(c.stop(),c=null),l(null),Pe(R,B,T,x,he),Ne(D);break}let L=Math.min(2e3*Math.pow(2,H-1),3e4),ee=new Ws(`API temporarily unavailable \u2014 retrying in ${Math.round(L/1e3)}s (${H}/${hc}). Your changes are safe.`);ee.start(),await new Promise(F=>setTimeout(F,L)),ee.stop(),He--;continue}c&&(c.stop(),c=null),l(null),Pe(R,B,T,x,he),Ne(D);break}if(clearInterval(Xc),Re=0,H=0,it&&(c&&!c._paused&&c.pause(),Ce&&Ce.stop()),nn&&(clearTimeout(nn),nn=null),Et&&ze&&(ze.push(Et),Et=""),at&&ze.flush(),H=0,K=0,vt&&vt.usage){let w=vt.usage.prompt_tokens||0,y=vt.usage.completion_tokens||0;mg(Hs(),Ht(),w,y),u+=w+y,c&&c.setStats({tokens:u})}else if(vt&&!vt.usage){let w=S.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=yg(w),J=yg(vt.content||at||"");mg(Hs(),Ht(),y,J),u+=y+J,c&&c.setStats({tokens:u})}let{content:Vc,tool_calls:sn}=vt,sr=xc(Vc||""),Jc=sr.truncated?sr.text:Vc;sr.truncated&&q(`${m.yellow} \u26A0 LLM output loop detected (${sr.repeatCount}\xD7 repeated paragraph) \u2014 response truncated${m.reset}`);let or=cE(Jc||""),Gt=or.truncated?or.text:Jc;or.truncated&&q(`${m.yellow} \u26A0 LLM output loop detected (${or.repeatCount}\xD7 repeated window) \u2014 response truncated${m.reset}`);let Zi={role:"assistant",content:Gt||""};if(sn&&sn.length>0&&(Zi.tool_calls=sn),D.push(Zi),S.push(Zi),!et&&Gt&&sn&&sn.length>0){let w=yc(Gt);if(w){et=!0,wt=w.slice(0,120),Pt=0,Lt=!1,pn=0,q(`${m.yellow} \u26A1 Root cause in model analysis: ${wt} \u2014 fix phase (read budget: 3)${m.reset}`);let y={role:"user",content:`[SYSTEM] Root cause identified: ${wt}. Read only the file that needs fixing, then edit it. Do not read other files.`};D.push(y),S.push(y)}}if(!sn||sn.length===0){let w=(Gt||"").trim().length>0||at.trim().length>0,y=!1;if(St&&w&&(Si>=2?q(`${m.yellow} \u26A0 SSH permanently blocked after ${Si} storm warnings \u2014 no further SSH calls allowed${m.reset}`):(St=!1,Nt=Xs-4,y=!0)),y&&w){let C=(Gt||"").trim();if(C.endsWith("?")||/\b(Wo |Bitte |Kannst du|Soll ich)\b/.test(C.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),D.push(ee);continue}}if(!w&&R>0&&He<kc-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."};S.push(C),D.push(C);continue}let J=/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&&J.test((Gt||"").slice(0,600)))if(Tc&&is<=0||St){q(`${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."};S.push(L),D.push(L);continue}else{q(`${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."};S.push(L),D.push(L);continue}if(s.skillLoop&&w&&R>3&&tr<5){let C=(Gt||at||"").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))){tr=(tr||0)+1,q(`${m.yellow} \u26A0 Skill loop: model tried to stop \u2014 continuation nudge #${tr}${m.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),D.push(ee);continue}}if(Li()&&!s.skillLoop&&T.size>0&&w&&R>=2){q(`${m.green} \u2713 Headless early exit: ${T.size} file(s) modified, text response received${m.reset}`),Pe(R,B,T,x,he),Ne(D);break e}if(_e&&Le==="plan"&&En>=2){q(`${m.cyan} \u21B3 Plan phase: ${En} consecutive blocks \u2014 auto-advancing to implement${m.reset}`),En=0;let C=Fo("implement","[auto-advance: task only requires direct action]");if(C){D.push(C),S.push(C),He=0,Yt=os("implement");continue}}if(_e&&w){let C=(Gt||at||"").trim();if(Le==="plan"){let L=Fo("implement",C);if(L){D.push(L),S.push(L),He=0,Yt=os("implement");continue}}else if(Le==="implement"&&T.size>0){let L=D.find(ue=>ue.role==="user"),ee=typeof L?.content=="string"?L.content:"",F=Fo("verify",C,T,ee);if(F){D.push(F),S.push(F),He=0,Yt=Math.min(os("verify")+Math.max(0,(T.size-2)*2),20);continue}}else if(Le==="verify"){let ee=/\bFAIL\b|test.*fail|error|broken|missing|incorrect/i.test(C.slice(0,500));if(ee&&Go<1){Go++;let F={role:"user",content:`[PHASE: RE-IMPLEMENTATION] Verification found issues:
1312
1318
  ${C.slice(0,400)}
1313
1319
 
1314
- Fix the identified issues. This is the final attempt.`};Le="implement",pn=$c("implement",Gs),j.push(q),S.push(q),We=0,Bt=ns("implement"),F(`${m.yellow} \u21B3 Verify \u2192 implement loop-back #${Yo} (issues found)${m.reset}`);continue}if(F(`${m.green} \u2713 Verification phase complete${Q?" (loop-back exhausted)":" (PASS)"}${m.reset}`),!Q){Pe(R,B,T,x,he),Me(j),lc(j);break e}}}if(Go()&&w&&R===0)if(vi++,vi>2)F(`${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.).
1320
+ Fix the identified issues. This is the final attempt.`};Le="implement",hn=bc("implement",Gs),D.push(F),S.push(F),He=0,Yt=os("implement"),q(`${m.yellow} \u21B3 Verify \u2192 implement loop-back #${Go} (issues found)${m.reset}`);continue}if(q(`${m.green} \u2713 Verification phase complete${ee?" (loop-back exhausted)":" (PASS)"}${m.reset}`),!ee){Pe(R,B,T,x,he),Ne(D),xi(D);break e}}}if(zo()&&w&&R===0)if(Ti++,Ti>2)q(`${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.).
1315
1321
 
1316
- 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),S.push(C),F(`${m.yellow} \u26A0 Plan rejected (${vi}/2): no files read \u2014 forcing investigation${m.reset}`);continue}if(Go()&&w){let C=(Wt||gt||"").trim();qv(C),xE(C);let L=Fv(C);if(L.length>0){let Q=j.find(U=>U.role==="user"),q=typeof Q?.content=="string"?Q.content.slice(0,120):"Task";Bv(q,L);let ue=L.length===1?"step":"steps",I=!1;if(process.stdout.isTTY&&process.stdin.isTTY){let{approvePlan:U,startExecution:W,setPlanMode:V}=yi();process.stdout.write(`
1317
- ${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 Z=process.stdin.isRaw,re=await new Promise(fe=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",oe=>{try{process.stdin.setRawMode(Z||!1)}catch{}let Oe=oe.toString().toLowerCase()[0]||"\r";fe(Oe)})});if(process.stdout.write(`
1318
- `),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(U()){W(),V(!1),Sc(),console.log(`${m.green}${m.bold}Approved!${m.reset} Executing ${L.length} ${ue}...`);let fe=`[PLAN APPROVED \u2014 EXECUTE NOW]
1322
+ 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.`};D.push(C),S.push(C),q(`${m.yellow} \u26A0 Plan rejected (${Ti}/2): no files read \u2014 forcing investigation${m.reset}`);continue}if(zo()&&w){let C=(Gt||at||"").trim();Fv(C),kE(C);let L=Bv(C);if(L.length>0){let ee=D.find(U=>U.role==="user"),F=typeof ee?.content=="string"?ee.content.slice(0,120):"Task";Uv(F,L);let ue=L.length===1?"step":"steps",I=!1;if(process.stdout.isTTY&&process.stdin.isTTY){let{approvePlan:U,startExecution:W,setPlanMode:V}=wi();process.stdout.write(`
1323
+ ${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 Z=process.stdin.isRaw,re=await new Promise(fe=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",Q=>{try{process.stdin.setRawMode(Z||!1)}catch{}let Ee=Q.toString().toLowerCase()[0]||"\r";fe(Ee)})});if(process.stdout.write(`
1324
+ `),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(U()){W(),V(!1),vc(),console.log(`${m.green}${m.bold}Approved!${m.reset} Executing ${L.length} ${ue}...`);let fe=`[PLAN APPROVED \u2014 EXECUTE NOW]
1319
1325
 
1320
1326
  Implement the following plan step by step. All tools are now available.
1321
1327
 
1322
- ${C}`;j.push({role:"user",content:fe}),S.push({role:"user",content:fe}),I=!0}}else console.log(`
1323
- ${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(I){c&&(c.stop(),c=null),We--;continue}}else{let Q=!1;if(process.stdout.isTTY&&process.stdin.isTTY){let{approvePlan:q,startExecution:ue,setPlanMode:I}=yi();process.stdout.write(`
1328
+ ${C}`;D.push({role:"user",content:fe}),S.push({role:"user",content:fe}),I=!0}}else console.log(`
1329
+ ${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(I){c&&(c.stop(),c=null),He--;continue}}else{let ee=!1;if(process.stdout.isTTY&&process.stdin.isTTY){let{approvePlan:F,startExecution:ue,setPlanMode:I}=wi();process.stdout.write(`
1324
1330
  ${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 U=process.stdin.isRaw,W=await new Promise(V=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",Z=>{try{process.stdin.setRawMode(U||!1)}catch{}V(Z.toString().toLowerCase()[0]||"\r")})});if(process.stdout.write(`
1325
- `),W==="r")console.log(`${m.red}Plan rejected.${m.reset} Ask follow-up questions to refine.`);else if(q()){ue(),I(!1),Sc(),console.log(`${m.green}${m.bold}Approved!${m.reset} Executing...`);let Z=`[PLAN APPROVED \u2014 EXECUTE NOW]
1331
+ `),W==="r")console.log(`${m.red}Plan rejected.${m.reset} Ask follow-up questions to refine.`);else if(F()){ue(),I(!1),vc(),console.log(`${m.green}${m.bold}Approved!${m.reset} Executing...`);let Z=`[PLAN APPROVED \u2014 EXECUTE NOW]
1326
1332
 
1327
1333
  Implement the following plan step by step. All tools are now available.
1328
1334
 
1329
- ${getPlanContent()||Ut.content}`;j.push({role:"user",content:Z}),S.push({role:"user",content:Z}),Q=!0}}else console.log(`
1330
- ${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),We--;continue}}}if(c&&(c.stop(),c=null),l(null),Pe(R,B,T,x,he),At&&T.size>=3){let C=[...T].map(I=>I.split("/").pop()).slice(0,8).join(", "),L=[...T].some(I=>I.endsWith("package.json")),Q=[...T].some(I=>I.endsWith("requirements.txt")),q=[...T].some(I=>I.endsWith("package-lock.json")||I.endsWith("yarn.lock")||I.endsWith("pnpm-lock.yaml")),ue=L&&!q?"npm install not yet run":Q?"pip install not yet run":null;Ho=`[Previous session created ${T.size} files: ${C}`+(ue?` \u2014 ${ue}`:"")+". Use this context to answer follow-up questions without re-reading files.]"}if(At&&!Tc&&R>0){let C=[...T].some(Z=>Z.endsWith("package.json")),L=[...T].some(Z=>Z.endsWith("requirements.txt")||Z.endsWith("Pipfile")||Z.endsWith("pyproject.toml")),Q=[...T].some(Z=>Z.endsWith("package-lock.json")||Z.endsWith("yarn.lock")||Z.endsWith("pnpm-lock.yaml")),q=j.flatMap(Z=>{let re=Array.isArray(Z.tool_calls)?Z.tool_calls:[],fe=Array.isArray(Z.content)?Z.content.filter(oe=>oe?.type==="tool_use"):[];return[...re,...fe]}).filter(Z=>{let re=Z.function?.name||Z.name||"";return re==="bash"||re==="Bash"}).map(Z=>{try{let re=Z.function?.arguments??Z.input??{};return(typeof re=="string"?JSON.parse(re):re)?.command||""}catch{return""}}),ue=q.some(Z=>/pip\s+install|python\s+-m\s+venv/.test(Z)),I=q.some(Z=>/npm\s+install/.test(Z)),W=[...T].some(Z=>/\/App\.(js|ts|jsx|tsx)$/.test(Z))&&!C&&!I;if(L&&!ue||C&&!Q&&!I||W){Tc=!0;let Z=[];L&&!ue&&Z.push("python -m venv venv && source venv/bin/activate && pip install -r requirements.txt"),W?Z.push("create package.json for the React frontend (with react, react-dom, react-scripts dependencies), then run npm install"):C&&!Q&&!I&&Z.push("npm install");let re=`[FRAMEWORK \u2014 post-creation check] You wrote dependency files but never ran the installer. Run now: ${Z.join(" && ")}. Verify it succeeds, fix any errors, then write a closing summary.`;F(`${m.dim} [post-creation] bootstrapping environment (${Z.join(", ")})${m.reset}`),j.push({role:"user",content:re}),S.push({role:"user",content:re});continue}}if(R>0&&!s._isSummaryTurn&&Cv(Wt))try{F(`${m.dim} [post-turn] terse ending \u2014 requesting diagnosis/summary${m.reset}`);let C=T.size>0?"Write a closing summary (3+ sentences): what files changed and why, what the result is, anything the user should know or do next.":"Write a closing diagnosis (3+ sentences): what you investigated, what you found, and what the user should do next or what the root cause is.",L=[...S,{role:"user",content:C}],q=((await fg(L,[],{}))?.content||"").trim();q&&(console.log(`
1331
- ${q}`),j.push({role:"user",content:C},{role:"assistant",content:q}))}catch{}Me(j),lc(j);return}R++,Di++,R>=1&&(ke=!1);for(let w of tn){let y=w.function.name;B.set(y,(B.get(y)||0)+1)}if(R>=30&&!vg){vg=!0,F(`${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),S.push(w)}let me=await Promise.all(tn.map(w=>kE(w)));{let w=Dt(S,ot()),y=w.percentage,J=me.some(q=>q.canExecute&&q.fnName==="read_file"&&!q.args?.line_end),C=me.filter(q=>q.canExecute&&q.fnName==="read_file"&&q.args?.path&&Jt(ls,q.args.path)>=1&&!q.args?.line_start).map(q=>q.args.path.split("/").slice(-2).join("/")),L=C.length>0;if(y>=70&&J&&Yi<70||y>=85&&Yi<85||L){Yi=y;let q=y>=85?"URGENT":"WARNING",ue;L?(q="WARNING",ue=`Full-file read of ${C.join(", ")} already done \u2014 use line_start/line_end for specific sections instead.`):J?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 I={role:"user",content:`[SYSTEM ${q}] Context ${Math.round(y)}% used (${w.used}/${w.limit} tokens). ${ue}`};if(j.push(I),S.push(I),y>=85){let U=L?` (re-read of: ${C.join(", ")})`:"";F(`${m.yellow} \u26A0 Context ${Math.round(y)}% used \u2014 agent warned to use targeted reads${U}${m.reset}`)}}}let Ji=new Map;for(let w of me){if(!w.canExecute||w.fnName!=="read_file")continue;let y=w.args?.path;if(!y)continue;let J=Jt(ls,y),C=Ji.get(y)||0,L=J+C,Q=w.args?.line_start!=null,q=Rt.get(y)||0,ue=q>0,I=2;if(L>=cs){let U=y.split("/").slice(-2).join("/"),W=(as.get(y)||0)+1;if(as.set(y,W),W===1)F(`${m.red} \u2716 Blocked: "${U}" read ${L}\xD7 \u2014 hard cap (${cs}) reached${m.reset}`);else if(W===2){F(`${m.red} \u2716 Escalated block: "${U}" \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 (${cs}\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),S.push(V)}w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 file already read ${L}\xD7 (hard cap: ${cs}). 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&&q<=I){let U=y.split("/").slice(-2).join("/");console.log(`${m.cyan} \u21A9 Targeted re-read: "${U}" (line_start=${w.args.line_start}) \u2014 edit recovery #${q}${m.reset}`),Rt.set(y,q-1)}else if(ue&&q>I){let U=y.split("/").slice(-2).join("/");F(`${m.red} \u2716 Edit recovery blocked: "${U}" \u2014 ${I} 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 (${I} 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 U=w.args.line_start||1,W=w.args.line_end||U+350,V=dn.get(y)||[],Z=!1;for(let[re,fe]of V){let oe=Math.max(U,re),Oe=Math.min(W,fe);if(Oe>oe){let He=Oe-oe,St=W-U||1,yt=fe-re||1,nn=He/yt>=.7&&He/St<.7,Xe=W-U<=hy;if(He>=St||!Xe&&(He/St>=.7||He/yt>=.7)){let Qi=y.split("/").slice(-2).join("/"),tu=`${y}:${U}-${W}`,ps=(Li.get(tu)||0)+1;if(Li.set(tu,ps),F(nn?`${m.red} \u2716 Blocked superread: "${Qi}" lines ${U}-${W} subsumes already-read ${re}-${fe} \u2014 use line_start=${fe+1} to skip known content (block #${ps})${m.reset}`:`${m.red} \u2716 Blocked duplicate read: "${Qi}" lines ${U}-${W} (\u226570% overlap with lines ${re}-${fe} already in context, block #${ps})${m.reset}`),ps>=2){F(`${m.red} \u2716 Escalated range-block: "${Qi}" lines ${U}-${W} \u2014 model ignored BLOCKED, injecting system warning${m.reset}`);let nu={role:"user",content:nn?`[SYSTEM] Read blocked ${ps}\xD7 for read_file("${y}", lines ${U}-${W}). 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 ${ps}\xD7 for read_file("${y}", lines ${U}-${W}). Lines ${re}-${fe} were already read and will NOT change. Use grep_search to find specific content instead.`};j.push(nu),S.push(nu)}w.canExecute=!1,w.errorResult={role:"tool",content:nn?`BLOCKED: read_file("${y}", lines ${U}-${W}) 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 ${U}-${W}) 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},Z=!0;break}}}if(!Z){let re=V.length,fe=2;if(re>=3){let Oe=y.split("/").slice(-2).join("/");F(`${m.red} \u2716 Blocked file-scroll: "${Oe}" \u2014 ${re} sections already read. Use grep to find specific content.${m.reset}`);let He=Jt(Hi,y)>=Qo;w.canExecute=!1,w.errorResult={role:"tool",content:He?`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 U=Rt.get(y)||0;if(U>0){let W=y.split("/").slice(-2).join("/");console.log(`${m.cyan} \u21A9 Full re-read: "${W}" \u2014 test-failure recovery (${U} remaining)${m.reset}`);let V=U-1;V<=0?Rt.delete(y):Rt.set(y,V)}else{let W=y.split("/").slice(-2).join("/"),V=(as.get(y)||0)+1;if(as.set(y,V),V===1)F(`${m.red} \u2716 Blocked unbounded re-read: "${W}" \u2014 already in context. Use line_start/line_end for specific sections.${m.reset}`);else if(V===2){F(`${m.red} \u2716 Escalated block: "${W}" \u2014 model ignored unbounded re-read block, injecting system warning${m.reset}`);let Z={role:"user",content:`[SYSTEM] read_file("${y}") was blocked again \u2014 full-file reads are disabled after the first read. Use line_start/line_end for a specific section, or use grep_search to find what you need.`};j.push(Z),S.push(Z)}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&&Ji.set(y,(Ji.get(y)||0)+1)}if(bn>=3)for(let w of me)w.canExecute&&(w.fnName!=="read_file"&&w.fnName!=="edit_file"||(F(`${m.red} \u2716 Blocked ${w.fnName} \u2014 ${bn} consecutive file-not-found errors, must search first${m.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: ${bn} 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)){F(`${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)&&(F(`${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||"")&&(F(`${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,J=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,q=Buffer.byteLength(J,"utf8"),ue=Q>0?q/Q:1;if(ue<.6&&Q>200){let I=y.split("/").slice(-2).join("/");console.log(`${m.red} \u2716 write_file shrink guard: "${I}" 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 ${q} bytes). This looks like a partial rewrite after context loss. Use edit_file/patch_file to add only the new code, or read the file first to see full content before replacing.`,tool_call_id:w.callId}}}}catch{}}let Jc=new Map;for(let w of me){if(!w.canExecute||w.fnName!=="grep")continue;let y=w.args?.path;if(!y)continue;let J=Jc.get(y)||0,C=Jt(Hi,y)+J,L=Jt(ls,y)>=1,Q=L?Math.min(3,Qo):Qo;if(C>=Q){let q=y.split("/").slice(-2).join("/");F(`${m.red} \u2716 Blocked grep: "${q}" grepped ${C}\xD7 with different patterns \u2014 flood threshold exceeded${m.reset}`);let ue=Jt(ls,y),I=ue>=cs;if(I){let U={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(U),S.push(U),F(`${m.red} \u2716 Deadlock detected: "${q}" \u2014 both read and grep blocked, injecting deadlock-break${m.reset}`)}w.canExecute=!1,w.errorResult={role:"tool",content:I?`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&&Jc.set(y,J+1)}let $y=5,Zc=new Map;for(let w of me){if(!w.canExecute||w.fnName!=="ssh_exec")continue;let J=(w.args?.command||"").replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),C=Zc.get(J)||0,L=Jt(Hc,J)+C;L>=$y&&(F(`${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&&Zc.set(J,C+1)}if(xt){let w=me.filter(C=>C.canExecute&&C.fnName==="ssh_exec"),y=me.some(C=>C.canExecute&&C.fnName!=="ssh_exec"),J=$&&P<3;if(w.length>0&&!y&&J&&Ti<1)xt=!1,Ti++,Ct=Math.max(0,Xs-2),F(`${m.dim} [dual-block deadlock: SSH storm relaxed \u2014 allowing 1 SSH call (relax ${Ti}/1)]${m.reset}`);else for(let C of w)C.canExecute=!1,C.errorResult={role:"tool",content:Ze?`BLOCKED: ssh_exec denied \u2014 SSH paused (${Xs}+ calls). Root cause is known (${ht}). 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 (${Xs}+ 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($&&P<3&&!xt){for(let w of me)if(w.canExecute&&["bash","read_file","find_files"].includes(w.fnName)){P++;{let y=ot(),{messages:J}=Vt(S,y);S=J}F(`${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(!_e&&jt&&At&&qt>=1){let w=["read_file","grep","search_files","glob","list_directory","find_files"];for(let y of me)y.canExecute&&w.includes(y.fnName)&&(F(`${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(os>=0){let w=me.filter(y=>y.canExecute).length;if(w>0&&(os-=w,os<0))if(!Ci&&T.size>Ri){Ci=!0,os=5,F(`${m.green} \u2713 Post-wipe progress detected (${T.size-Ri} 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),S.push(y)}else{F(`${m.red} \u2716 Post-wipe tool budget exhausted \u2014 blocking all tool calls${m.reset}`);for(let J of me)J.canExecute&&(J.canExecute=!1,J.errorResult={role:"tool",content:"BLOCKED: post-wipe tool budget exhausted. No further tool calls are allowed. Summarise what was accomplished and stop.",tool_call_id:J.callId});let 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),S.push(y)}}let by=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||by.has(w.fnName))continue;let y=JSON.stringify(w.args||{}),J=`${w.fnName}|${y}`,C=Jt(Ii,J);C>=2?(F(`${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&&F(`${m.yellow} \u26A0 Duplicate tool call: ${w.fnName}(${y.substring(0,80)}) \u2014 2nd call with identical args${m.reset}`),ss(Ii,J)}{let w=new Set;for(let y of me){if(!y.canExecute||!["edit_file","patch_file"].includes(y.fnName))continue;let J=y.args?.path;J&&(se.has(J)||w.has(J)?(y.canExecute=!1,y.errorResult={role:"tool",content:`BLOCKED: "${J}" 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},F(`${m.yellow} \u26A0 Map-first gate: blocked re-edit of "${J.split("/").slice(-1)[0]}" \u2014 re-read required${m.reset}`)):w.add(J))}}let Vs=c?{skipSpinner:!0,skipSummaries:!0}:{},xy=me.some(w=>w.fnName==="ask_user"),Qc=!Vs.skipSummaries&&!ke,or=null,fs=null;Qc&&!xy?(ke=!0,Vs.skipSpinner=!0,process.stdout.isTTY?(global._nexFooter&&(fs=Math.min(global._nexFooter._lastOutputRow+1,global._nexFooter._scrollEnd)),process.stdout.write($i(me,R,!1,"blink")),or=!0):Qt||process.stdout.write($i(me,R,!1)+`
1332
- `)):Qc&&(ke=!0,Vs.skipSpinner=!0),c&&c._paused&&c.resume();let rr=null;if(or&&process.stdout.isTTY&&me.some(y=>y.canExecute&&(y.fnName==="bash"||y.fnName==="ssh_exec"))){let y=Date.now();rr=setInterval(()=>{let J=Math.round((Date.now()-y)/1e3);if(J>=3){let C=`${$i(me,R,!1,"blink")} ${m.dim}[${J}s]${m.reset}`;fs!==null?process.stdout.write(`\x1B[${fs};1H\x1B[2K${C}`):process.stdout.write(`\r\x1B[2K${C}`)}},1e3)}let{results:tt,summaries:ky}=await TE(me,!0,{...Vs,skipSummaries:!0});if(rr&&(clearInterval(rr),rr=null),or){or=null;let w=$i(me,R,!1);fs!==null?process.stdout.write(`\x1B[${fs};1H\x1B[2K${w}
1335
+ ${getPlanContent()||vt.content}`;D.push({role:"user",content:Z}),S.push({role:"user",content:Z}),ee=!0}}else console.log(`
1336
+ ${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(ee){c&&(c.stop(),c=null),He--;continue}}}if(c&&(c.stop(),c=null),l(null),Pe(R,B,T,x,he),Mt&&T.size>=3){let C=[...T].map(I=>I.split("/").pop()).slice(0,8).join(", "),L=[...T].some(I=>I.endsWith("package.json")),ee=[...T].some(I=>I.endsWith("requirements.txt")),F=[...T].some(I=>I.endsWith("package-lock.json")||I.endsWith("yarn.lock")||I.endsWith("pnpm-lock.yaml")),ue=L&&!F?"npm install not yet run":ee?"pip install not yet run":null;Yo=`[Previous session created ${T.size} files: ${C}`+(ue?` \u2014 ${ue}`:"")+". Use this context to answer follow-up questions without re-reading files.]"}if(Mt&&!Rc&&R>0){let C=[...T].some(Z=>Z.endsWith("package.json")),L=[...T].some(Z=>Z.endsWith("requirements.txt")||Z.endsWith("Pipfile")||Z.endsWith("pyproject.toml")),ee=[...T].some(Z=>Z.endsWith("package-lock.json")||Z.endsWith("yarn.lock")||Z.endsWith("pnpm-lock.yaml")),F=D.flatMap(Z=>{let re=Array.isArray(Z.tool_calls)?Z.tool_calls:[],fe=Array.isArray(Z.content)?Z.content.filter(Q=>Q?.type==="tool_use"):[];return[...re,...fe]}).filter(Z=>{let re=Z.function?.name||Z.name||"";return re==="bash"||re==="Bash"}).map(Z=>{try{let re=Z.function?.arguments??Z.input??{};return(typeof re=="string"?JSON.parse(re):re)?.command||""}catch{return""}}),ue=F.some(Z=>/pip\s+install|python\s+-m\s+venv/.test(Z)),I=F.some(Z=>/npm\s+install/.test(Z)),W=[...T].some(Z=>/\/App\.(js|ts|jsx|tsx)$/.test(Z))&&!C&&!I;if(L&&!ue||C&&!ee&&!I||W){Rc=!0;let Z=[];L&&!ue&&Z.push("python -m venv venv && source venv/bin/activate && pip install -r requirements.txt"),W?Z.push("create package.json for the React frontend (with react, react-dom, react-scripts dependencies), then run npm install"):C&&!ee&&!I&&Z.push("npm install");let re=`[FRAMEWORK \u2014 post-creation check] You wrote dependency files but never ran the installer. Run now: ${Z.join(" && ")}. Verify it succeeds, fix any errors, then write a closing summary.`;q(`${m.dim} [post-creation] bootstrapping environment (${Z.join(", ")})${m.reset}`),D.push({role:"user",content:re}),S.push({role:"user",content:re});continue}}if(R>0&&!s._isSummaryTurn&&Av(Gt))try{q(`${m.dim} [post-turn] terse ending \u2014 requesting diagnosis/summary${m.reset}`);let C=T.size>0?"Write a closing summary (3+ sentences): what files changed and why, what the result is, anything the user should know or do next.":"Write a closing diagnosis (3+ sentences): what you investigated, what you found, and what the user should do next or what the root cause is.",L=[...S,{role:"user",content:C}],F=((await pg(L,[],{}))?.content||"").trim();F&&(console.log(`
1337
+ ${F}`),D.push({role:"user",content:C},{role:"assistant",content:F}))}catch{}Ne(D),xi(D);return}R++,qi++,R>=1&&(ke=!1);for(let w of sn){let y=w.function.name;B.set(y,(B.get(y)||0)+1)}if(R>=30&&!Eg){Eg=!0,q(`${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."};D.push(w),S.push(w)}let me=await Promise.all(sn.map(w=>SE(w)));{let w=Ut(S,rt()),y=w.percentage,J=me.some(F=>F.canExecute&&F.fnName==="read_file"&&!F.args?.line_end),C=me.filter(F=>F.canExecute&&F.fnName==="read_file"&&F.args?.path&&en(us,F.args.path)>=1&&!F.args?.line_start).map(F=>F.args.path.split("/").slice(-2).join("/")),L=C.length>0;if(y>=70&&J&&zi<70||y>=85&&zi<85||L){zi=y;let F=y>=85?"URGENT":"WARNING",ue;L?(F="WARNING",ue=`Full-file read of ${C.join(", ")} already done \u2014 use line_start/line_end for specific sections instead.`):J?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 I={role:"user",content:`[SYSTEM ${F}] Context ${Math.round(y)}% used (${w.used}/${w.limit} tokens). ${ue}`};if(D.push(I),S.push(I),y>=85){let U=L?` (re-read of: ${C.join(", ")})`:"";q(`${m.yellow} \u26A0 Context ${Math.round(y)}% used \u2014 agent warned to use targeted reads${U}${m.reset}`)}}}let Qi=new Map;for(let w of me){if(!w.canExecute||w.fnName!=="read_file")continue;let y=w.args?.path;if(!y)continue;let J=en(us,y),C=Qi.get(y)||0,L=J+C,ee=w.args?.line_start!=null,F=Ot.get(y)||0,ue=F>0,I=2;if(L>=ds){let U=y.split("/").slice(-2).join("/"),W=(cs.get(y)||0)+1;if(cs.set(y,W),W===1)q(`${m.red} \u2716 Blocked: "${U}" read ${L}\xD7 \u2014 hard cap (${ds}) reached${m.reset}`);else if(W===2){q(`${m.red} \u2716 Escalated block: "${U}" \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 (${ds}\xD7). Do NOT attempt to read it again. Use grep_search to find specific content, or proceed with what you already know.`};D.push(V),S.push(V)}w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 file already read ${L}\xD7 (hard cap: ${ds}). 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&&ee)if(ue&&F<=I){let U=y.split("/").slice(-2).join("/");console.log(`${m.cyan} \u21A9 Targeted re-read: "${U}" (line_start=${w.args.line_start}) \u2014 edit recovery #${F}${m.reset}`),Ot.set(y,F-1)}else if(ue&&F>I){let U=y.split("/").slice(-2).join("/");q(`${m.red} \u2716 Edit recovery blocked: "${U}" \u2014 ${I} 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 (${I} 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 U=w.args.line_start||1,W=w.args.line_end||U+350,V=fn.get(y)||[],Z=!1;for(let[re,fe]of V){let Q=Math.max(U,re),Ee=Math.min(W,fe);if(Ee>Q){let Ie=Ee-Q,pt=W-U||1,Ve=fe-re||1,Tt=Ie/Ve>=.7&&Ie/pt<.7,Je=W-U<=my;if(Ie>=pt||!Je&&(Ie/pt>=.7||Ie/Ve>=.7)){let ta=y.split("/").slice(-2).join("/"),nu=`${y}:${U}-${W}`,ps=(Di.get(nu)||0)+1;if(Di.set(nu,ps),q(Tt?`${m.red} \u2716 Blocked superread: "${ta}" lines ${U}-${W} subsumes already-read ${re}-${fe} \u2014 use line_start=${fe+1} to skip known content (block #${ps})${m.reset}`:`${m.red} \u2716 Blocked duplicate read: "${ta}" lines ${U}-${W} (\u226570% overlap with lines ${re}-${fe} already in context, block #${ps})${m.reset}`),ps>=2){q(`${m.red} \u2716 Escalated range-block: "${ta}" lines ${U}-${W} \u2014 model ignored BLOCKED, injecting system warning${m.reset}`);let su={role:"user",content:Tt?`[SYSTEM] Read blocked ${ps}\xD7 for read_file("${y}", lines ${U}-${W}). 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 ${ps}\xD7 for read_file("${y}", lines ${U}-${W}). Lines ${re}-${fe} were already read and will NOT change. Use grep_search to find specific content instead.`};D.push(su),S.push(su)}w.canExecute=!1,w.errorResult={role:"tool",content:Tt?`BLOCKED: read_file("${y}", lines ${U}-${W}) 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 ${U}-${W}) 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},Z=!0;break}}}if(!Z){let re=V.length,fe=2;if(re>=3){let Ee=y.split("/").slice(-2).join("/");q(`${m.red} \u2716 Blocked file-scroll: "${Ee}" \u2014 ${re} sections already read. Use grep to find specific content.${m.reset}`);let Ie=en(Gi,y)>=er;w.canExecute=!1,w.errorResult={role:"tool",content:Ie?`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 U=Ot.get(y)||0;if(U>0){let W=y.split("/").slice(-2).join("/");console.log(`${m.cyan} \u21A9 Full re-read: "${W}" \u2014 test-failure recovery (${U} remaining)${m.reset}`);let V=U-1;V<=0?Ot.delete(y):Ot.set(y,V)}else{let W=y.split("/").slice(-2).join("/"),V=(cs.get(y)||0)+1;if(cs.set(y,V),V===1)q(`${m.red} \u2716 Blocked unbounded re-read: "${W}" \u2014 already in context. Use line_start/line_end for specific sections.${m.reset}`);else if(V===2){q(`${m.red} \u2716 Escalated block: "${W}" \u2014 model ignored unbounded re-read block, injecting system warning${m.reset}`);let Z={role:"user",content:`[SYSTEM] read_file("${y}") was blocked again \u2014 full-file reads are disabled after the first read. Use line_start/line_end for a specific section, or use grep_search to find what you need.`};D.push(Z),S.push(Z)}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&&Qi.set(y,(Qi.get(y)||0)+1)}if(kn>=3)for(let w of me)w.canExecute&&(w.fnName!=="read_file"&&w.fnName!=="edit_file"||(q(`${m.red} \u2716 Blocked ${w.fnName} \u2014 ${kn} consecutive file-not-found errors, must search first${m.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: ${kn} 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)){q(`${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)&&(q(`${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||"")&&(q(`${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,J=w.args?.content||"";if(y)try{let C=require("fs"),L=require("path").resolve(process.cwd(),y);if(C.existsSync(L)){let ee=C.statSync(L).size,F=Buffer.byteLength(J,"utf8"),ue=ee>0?F/ee:1;if(ue<.6&&ee>200){let I=y.split("/").slice(-2).join("/");console.log(`${m.red} \u2716 write_file shrink guard: "${I}" 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 (${ee} \u2192 ${F} bytes). This looks like a partial rewrite after context loss. Use edit_file/patch_file to add only the new code, or read the file first to see full content before replacing.`,tool_call_id:w.callId}}}}catch{}}let Zc=new Map;for(let w of me){if(!w.canExecute||w.fnName!=="grep")continue;let y=w.args?.path;if(!y)continue;let J=Zc.get(y)||0,C=en(Gi,y)+J,L=en(us,y)>=1,ee=L?Math.min(3,er):er;if(C>=ee){let F=y.split("/").slice(-2).join("/");q(`${m.red} \u2716 Blocked grep: "${F}" grepped ${C}\xD7 with different patterns \u2014 flood threshold exceeded${m.reset}`);let ue=en(us,y),I=ue>=ds;if(I){let U={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.`};D.push(U),S.push(U),q(`${m.red} \u2716 Deadlock detected: "${F}" \u2014 both read and grep blocked, injecting deadlock-break${m.reset}`)}w.canExecute=!1,w.errorResult={role:"tool",content:I?`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&&Zc.set(y,J+1)}let by=5,Qc=new Map;for(let w of me){if(!w.canExecute||w.fnName!=="ssh_exec")continue;let J=(w.args?.command||"").replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),C=Qc.get(J)||0,L=en(Yc,J)+C;L>=by&&(q(`${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&&Qc.set(J,C+1)}if(St){let w=me.filter(C=>C.canExecute&&C.fnName==="ssh_exec"),y=me.some(C=>C.canExecute&&C.fnName!=="ssh_exec"),J=$&&P<3;if(w.length>0&&!y&&J&&Ci<1)St=!1,Ci++,Nt=Math.max(0,Xs-2),q(`${m.dim} [dual-block deadlock: SSH storm relaxed \u2014 allowing 1 SSH call (relax ${Ci}/1)]${m.reset}`);else for(let C of w)C.canExecute=!1,C.errorResult={role:"tool",content:et?`BLOCKED: ssh_exec denied \u2014 SSH paused (${Xs}+ calls). Root cause is known (${wt}). 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 (${Xs}+ 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($&&P<3&&!St){for(let w of me)if(w.canExecute&&["bash","read_file","find_files"].includes(w.fnName)){P++;{let y=rt(),{messages:J}=Qt(S,y);S=J}q(`${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(!_e&&Lt&&Mt&&Wt>=1){let w=["read_file","grep","search_files","glob","list_directory","find_files"];for(let y of me)y.canExecute&&w.includes(y.fnName)&&(q(`${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(is>=0){let w=me.filter(y=>y.canExecute).length;if(w>0&&(is-=w,is<0))if(!Oi&&T.size>Ai){Oi=!0,is=5,q(`${m.green} \u2713 Post-wipe progress detected (${T.size-Ai} 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."};D.push(y),S.push(y)}else{q(`${m.red} \u2716 Post-wipe tool budget exhausted \u2014 blocking all tool calls${m.reset}`);for(let J of me)J.canExecute&&(J.canExecute=!1,J.errorResult={role:"tool",content:"BLOCKED: post-wipe tool budget exhausted. No further tool calls are allowed. Summarise what was accomplished and stop.",tool_call_id:J.callId});let 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."};D.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 me){if(!w.canExecute||xy.has(w.fnName))continue;let y=JSON.stringify(w.args||{}),J=`${w.fnName}|${y}`,C=en(ji,J);C>=2?(q(`${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&&q(`${m.yellow} \u26A0 Duplicate tool call: ${w.fnName}(${y.substring(0,80)}) \u2014 2nd call with identical args${m.reset}`),rs(ji,J)}{let w=new Set;for(let y of me){if(!y.canExecute||!["edit_file","patch_file"].includes(y.fnName))continue;let J=y.args?.path;J&&(oe.has(J)||w.has(J)?(y.canExecute=!1,y.errorResult={role:"tool",content:`BLOCKED: "${J}" 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},q(`${m.yellow} \u26A0 Map-first gate: blocked re-edit of "${J.split("/").slice(-1)[0]}" \u2014 re-read required${m.reset}`)):w.add(J))}}let Vs=c?{skipSpinner:!0,skipSummaries:!0}:{},ky=me.some(w=>w.fnName==="ask_user"),eu=!Vs.skipSummaries&&!ke,rr=null,fs=null;eu&&!ky?(ke=!0,Vs.skipSpinner=!0,process.stdout.isTTY?(global._nexFooter&&(fs=Math.min(global._nexFooter._lastOutputRow+1,global._nexFooter._scrollEnd)),process.stdout.write(bi(me,R,!1,"blink")),rr=!0):tn||process.stdout.write(bi(me,R,!1)+`
1338
+ `)):eu&&(ke=!0,Vs.skipSpinner=!0),c&&c._paused&&c.resume();let ir=null;if(rr&&process.stdout.isTTY&&me.some(y=>y.canExecute&&(y.fnName==="bash"||y.fnName==="ssh_exec"))){let y=Date.now();ir=setInterval(()=>{let J=Math.round((Date.now()-y)/1e3);if(J>=3){let C=`${bi(me,R,!1,"blink")} ${m.dim}[${J}s]${m.reset}`;fs!==null?process.stdout.write(`\x1B[${fs};1H\x1B[2K${C}`):process.stdout.write(`\r\x1B[2K${C}`)}},1e3)}let{results:nt,summaries:Sy}=await RE(me,!0,{...Vs,skipSummaries:!0});if(ir&&(clearInterval(ir),ir=null),rr){rr=null;let w=bi(me,R,!1);fs!==null?process.stdout.write(`\x1B[${fs};1H\x1B[2K${w}
1333
1339
  `):process.stdout.write(`\r\x1B[2K${w}
1334
- `),fs=null}if(!Vs.skipSummaries){let w=ky.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),J=Wi.record(0,y,x,T);J&&sE(J)}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:"))&&(En++,En>=Yc)){F(`${m.red} \u2716 Loop abort: ${En} consecutive blocked calls (pre-execution) \u2014 model not heeding BLOCKED messages${m.reset}`),c&&(c.stop(),c=null),l(null),Pe(R,B,T,x,he,{suppressHint:!0}),Me(j);return}}for(let w=0;w<me.length;w++){let y=me[w];if(!y.canExecute)continue;let J=tt[w].content,C=J.split(`
1335
- `)[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 I=Rt.get(y.args.path)||0;Rt.set(y.args.path,I+1)}if(!L&&y.fnName==="bash"&&Xo.size>0){let I=(y.args?.command||"").toLowerCase();if(/\b(test|jest|vitest|pytest|mocha|tsc|build|lint|eslint|check)\b/.test(I))for(let[W]of Xo)Rt.has(W)||(Rt.set(W,1),F(`${m.cyan} \u21A9 Test failure \u2014 queuing recovery re-read: "${W.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(bn++,bn>=2){F(`${m.yellow} \u26A0 File-not-found streak: ${bn} consecutive misses \u2014 forcing search${m.reset}`);let I={role:"user",content:`[SYSTEM] ${bn} 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(I),S.push(I)}}else L&&(y.fnName==="read_file"||y.fnName==="edit_file"||y.fnName==="search_files"||y.fnName==="glob_files")&&(bn=0);if(L&&y.fnName==="write_file"&&y.args?.path){let I=y.args.path.split("/").pop(),U=y.args.path.includes("/tests/")||y.args.path.includes("\\tests\\");if(/^(test_|demo_|temp_|tmp_|scratch_)/.test(I)&&!U){F(`${m.yellow} \u26A0 Temp file: "${I}" \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),S.push(V)}}if(L&&["write_file","edit_file","patch_file"].includes(y.fnName)&&y.args&&y.args.path){Rt.delete(y.args.path),T.add(y.args.path);let I=ss(Zg,y.args.path),U=y.args.path.split("/").slice(-2).join("/");if(I===Qg){F(`${m.yellow} \u26A0 Loop warning: "${U}" edited ${I}\xD7 \u2014 possible edit loop${m.reset}`);let W={role:"user",content:`[SYSTEM WARNING] "${y.args.path}" edited ${I}\xD7. One more edit max, then move on.`};j.push(W),S.push(W)}else if(I>=ey){F(`${m.red} \u2716 Loop abort: "${U}" edited ${I}\xD7 \u2014 aborting to prevent runaway loop${m.reset}`),c&&(c.stop(),c=null),l(null),Pe(R,B,T,x,he,{suppressHint:!0}),Me(j);return}}if(L&&y.canExecute&&_e&&(Sn=0),L&&y.canExecute&&!(_e&&Le==="plan")){let I=["read_file","grep","search_files","glob","list_directory","ssh_exec","find_files"];if(["write_file","edit_file","patch_file"].includes(y.fnName)){Zt=0,jt=!1,fn=0,qt++;let oe=y.args?.path||y.args?.file_path;oe&&(yc(xn,oe,1),dn.delete(oe),se.add(oe))}else I.includes(y.fnName)&&(Zt++,jt&&fn++);let W=n.postEditCap,V=_e&&Le==="implement"?Math.min(Gc,6):Gc,Z=Ze?3:At?qt>0?2:4:qt>0?W:V,re=3;if(!_e&&jt&&(Ze||At&&qt>=1||fn>=re)&&I.includes(y.fnName)){let oe=Ze?`root cause already identified (${ht})`:fn>=re?`${Zt} consecutive reads without an edit`:`${qt} file edit(s) already made`;F(`${m.red} \u2716 Blocked read-only tool: cap fired, ${oe}${m.reset}`),y.canExecute=!1,y.errorResult={role:"tool",content:Ze?`BLOCKED: root cause already identified (${ht}). Use edit_file to fix the issue \u2014 do not read more files.`:At?"BLOCKED: files already written \u2014 continue with write_file or edit_file to finish the remaining tasks. Do not read more files.":fn>=re?`BLOCKED: You have read ${Zt} 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: ${qt} 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(Zt>=Z&&!jt){if(jt=!0,F(`${m.yellow} \u26A0 Investigation cap: ${Zt} read-only calls without an edit \u2014 forcing implementation${m.reset}`),_e&&Le==="plan"){let He=[...S].reverse().find(nn=>nn.role==="assistant"),St=typeof He?.content=="string"?He.content:"",yt=qo("implement",St);yt&&(j.push(yt),S.push(yt),We=0,Bt=ns("implement"))}let oe;Ze?oe=`[SYSTEM] Root cause was already identified (${ht}). Edit the file now \u2014 do not read more files.`:xt?oe="[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.":oe="[SYSTEM] You have read enough files. Now implement your fix using edit_file.";let Oe={role:"user",content:oe};j.push(Oe),S.push(Oe)}}if((y.fnName==="bash"||y.fnName==="ssh_exec")&&y.args&&y.args.command){let I=y.args.command.replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),U=ss(Hc,I);if(U===ty){F(`${m.yellow} \u26A0 Loop warning: same bash command run ${U}\xD7 \u2014 possible debug loop${m.reset}`);let W={role:"user",content:`[SYSTEM WARNING] Same bash command ${U}\xD7. Debug loop detected \u2014 try a different approach.`};j.push(W),S.push(W)}else if(U>=ny){F(`${m.red} \u2716 Loop abort: same bash command run ${U}\xD7 \u2014 aborting runaway debug loop${m.reset}`),c&&(c.stop(),c=null),l(null),Pe(R,B,T,x,he,{suppressHint:!0}),Me(j);return}}if(y.fnName==="ssh_exec"){Ct++;{let W=(tt[w]?.content??"").split(`
1336
- `).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(W){if(W===Ai?rs++:(Ai=W,rs=1),rs===3&&!xt){F(`${m.yellow} \u26A0 SSH repeated-error: "${W.slice(0,60)}" returned ${rs}\xD7 \u2014 nudging to change approach${m.reset}`);let V={role:"user",content:`[SYSTEM WARNING] The last ${rs} SSH commands all failed with the same error: "${W}". Retrying variants of the same command will not help. Switch to a different approach to accomplish the task (e.g. use a different tool, read a local file, or change the command syntax entirely).`};j.push(V),S.push(V)}}else Ai="",rs=0}if(Ct>=_y){F(`${m.red} \u2716 SSH storm abort: ${Ct} consecutive ssh_exec calls \u2014 aborting${m.reset}`),c&&(c.stop(),c=null),l(null),Pe(R,B,T,x,he,{suppressHint:!0}),Me(j);return}else if(Ct===Xs){{let W=ot(),{messages:V}=Vt(S,W);S=V}xt=!0,xi++,F(`${m.yellow} \u26A0 SSH storm warning (#${xi}): ${Ct} consecutive ssh_exec calls \u2014 blocking further SSH${m.reset}`);let U={role:"user",content:Ze?`[SYSTEM WARNING] ${Ct} consecutive SSH calls. Root cause identified (${ht}). Read the file that needs fixing, then edit it.`:`[SYSTEM WARNING] ${Ct} 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(U),S.push(U)}}else y.canExecute&&(Ct=0);if(y.fnName==="bash"&&y.canExecute){let W=(tt[w]?.content??"").split(`
1337
- `).map(V=>V.trim()).find(V=>V.length>0&&(V.startsWith("EXIT")||/^[\w./-]+:\s/.test(V)||V.startsWith("bash:")||V.startsWith("sh:")))??"";if(W){if(W===Oi?is++:(Oi=W,is=1),is===3){F(`${m.yellow} \u26A0 Bash repeated-error: "${W.slice(0,60)}" returned ${is}\xD7 \u2014 nudging to change approach${m.reset}`);let V={role:"user",content:`[SYSTEM WARNING] The last ${is} bash commands all failed with the same error: "${W}". Retrying variants of the same command will not help. Switch to a completely different approach (e.g. use a different tool, change the command syntax, or use ssh_exec to run the command on the remote server instead).`};j.push(V),S.push(V)}}else Oi="",is=0}if(y.fnName==="bash"&&y.canExecute&&!wc&&y.args?.command){let I=tt[w]?.content??"";if(/git\s+commit\b/.test(y.args.command)&&!I.startsWith("EXIT")&&!I.startsWith("ERROR")&&(/\[\S+\s+[a-f0-9]+\]/.test(I)||I.includes("files changed")||I.includes("file changed")||I.includes("insertions(+)")||I.includes("create mode"))){wc=!0,jo=0,F(`${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),S.push(V)}}if(wc&&y.fnName==="bash"&&y.args?.command&&/git\s+(status|diff|log|show)\b/.test(y.args.command)&&(jo++,jo>2)){F(`${m.yellow} \u26A0 Post-commit git verification blocked (call ${jo})${m.reset}`);let U={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."};j.push(U),S.push(U)}if(L&&y.fnName==="grep"&&y.args&&y.args.pattern){let I=`${y.args.pattern}|${y.args.path||""}`,U=ss(sy,I);if(U===oy){F(`${m.yellow} \u26A0 Loop warning: grep pattern "${y.args.pattern.slice(0,40)}" run ${U}\xD7 \u2014 possible search loop${m.reset}`);let W={role:"user",content:`[SYSTEM WARNING] Same grep pattern ${U}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};j.push(W),S.push(W)}else if(U>=ry){F(`${m.red} \u2716 Loop abort: grep pattern run ${U}\xD7 \u2014 aborting runaway search loop${m.reset}`),c&&(c.stop(),c=null),l(null),Pe(R,B,T,x,he,{suppressHint:!0}),Me(j);return}if(y.args.path){let W=ss(Hi,y.args.path),V=Jt(ls,y.args.path)>=1;if(W===(V?1:iy)){let re=y.args.path.split("/").slice(-2).join("/");F(`${m.yellow} \u26A0 Loop warning: "${re}" grepped ${W}\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 ${W}\xD7 \u2014 use the search results already in context instead of searching again.`};j.push(fe),S.push(fe)}}}if(L&&(y.fnName==="glob"||y.fnName==="glob_files"||y.fnName==="search_files")&&y.args){let I=y.args.pattern||y.args.query||y.args.path||"",U=ss(ay,I);if(U===ly){F(`${m.yellow} \u26A0 Loop warning: glob pattern "${I.slice(0,40)}" run ${U}\xD7 \u2014 possible search loop${m.reset}`);let V={role:"user",content:`[SYSTEM WARNING] Same glob/search pattern ${U}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};j.push(V),S.push(V)}else if(U>=cy){F(`${m.red} \u2716 Loop abort: glob pattern run ${U}\xD7 \u2014 aborting runaway search loop${m.reset}`),c&&(c.stop(),c=null),l(null),Pe(R,B,T,x,he,{suppressHint:!0}),Me(j);return}let W=I.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 W){let Z=V.toLowerCase();Ko.has(Z)||Ko.set(Z,new Set);let re=Ko.get(Z);if(re.add(I),re.size===dy){F(`${m.red} \u2716 Glob core-term block: ${re.size} different patterns all searching for "${Z}" \u2014 search loop${m.reset}`);let fe={role:"user",content:`[SYSTEM WARNING] You have searched for "${Z}" 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),S.push(fe)}else if(re.size===uy){F(`${m.yellow} \u26A0 Glob core-term warning: ${re.size} different patterns searching for "${Z}"${m.reset}`);let fe={role:"user",content:`[SYSTEM WARNING] ${re.size} different glob patterns all target "${Z}". If previous searches returned no results, the file probably does not exist \u2014 stop searching and proceed with available information.`};j.push(fe),S.push(fe)}}}let Q=(y.args?.command||y.args?.cmd||y.args?.script||"").toLowerCase(),q=/\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")&&q&&J.includes('"valid":true')){{let U=ot();if(Dt(S,U).percentage>=60){let{messages:V,tokensRemoved:Z}=Vt(S,U);Z>0&&(S=V,console.log(`${m.dim} [pre-stop-compress \u2014 ~${Z} tokens freed before STOP injection, now ${Math.round(Dt(S,U).percentage)}%]${m.reset}`))}}let I={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(I),S.push(I),console.log(`${m.cyan} \u2713 Health-check stop signal detected \u2014 injecting STOP instruction${m.reset}`)}if(J.startsWith("BLOCKED:")){if(En++,En>=Yc){F(`${m.red} \u2716 Loop abort: ${En} consecutive blocked calls \u2014 model not heeding BLOCKED messages${m.reset}`),c&&(c.stop(),c=null),l(null),Pe(R,B,T,x,he,{suppressHint:!0}),Me(j);return}}else En=0;if(L)vn=0,zi=!0;else if(vn++,vn===my){F(`${m.yellow} \u26A0 Loop warning: ${vn} consecutive tool errors \u2014 possible stuck loop${m.reset}`);let I={role:"user",content:`[SYSTEM WARNING] ${vn} consecutive errors. Stuck loop \u2014 try fundamentally different approach or declare done.`};j.push(I),S.push(I)}else if(vn>=gy){F(`${m.red} \u2716 Loop abort: ${vn} consecutive errors \u2014 aborting stuck loop${m.reset}`),c&&(c.stop(),c=null),l(null),Pe(R,B,T,x,he,{suppressHint:!0}),Me(j);return}if(L&&y.fnName==="read_file"&&y.args&&y.args.path){x.add(y.args.path),se.delete(y.args.path);let I=ss(ls,y.args.path);{let Z=y.args.line_start!=null&&y.args.line_start||1,re=y.args.line_start!=null?y.args.line_end||Z+350:350;dn.has(y.args.path)||dn.set(y.args.path,[]),dn.get(y.args.path).push([Z,re])}if(y._scrollWarn){let{sectionCount:Z,path:re}=y._scrollWarn,fe={role:"user",content:`[SYSTEM WARNING] "${re}" \u2014 you have now read ${Z} 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),S.push(fe),F(`${m.yellow} \u26A0 Scroll warning: "${re.split("/").slice(-2).join("/")}" \u2014 ${Z} sections read \u2014 use grep instead${m.reset}`)}let U=y.args.path.split("/").slice(-2).join("/"),W=!y.args?.line_start&&!y.args?.line_end,V=_e&&Le==="plan";if(!V&&W&&I===fy){{let re=ot();if(Dt(S,re).percentage>=60){let{messages:oe}=Vt(S,re);S=oe}}F(`${m.yellow} \u26A0 Loop warning: "${U}" read unbounded ${I}\xD7 \u2014 use line_start/line_end${m.reset}`);let Z={role:"user",content:`[SYSTEM WARNING] "${y.args.path}" read ${I}\xD7 without line ranges. Use line_start/line_end to read specific sections \u2014 do not re-read the full file.`};j.push(Z),S.push(Z)}else if(!V&&W&&I>=py){F(`${m.red} \u2716 Loop abort: "${U}" read unbounded ${I}\xD7 \u2014 aborting runaway read loop${m.reset}`),c&&(c.stop(),c=null),l(null),Pe(R,B,T,x,he,{suppressHint:!0}),Me(j);return}}if(y.fnName==="spawn_agents"){let I=(J.match(/\bStatus: done\b/g)||[]).length;if((J.match(/\bStatus: truncated\b/g)||[]).length>0&&I===0){if(Tn++,Tn===yy){F(`${m.yellow} \u26A0 Swarm warning: all sub-agents hit iteration limit ${Tn}\xD7 in a row${m.reset}`);let W={role:"user",content:`[SYSTEM WARNING] Sub-agents truncated ${Tn}\xD7 in a row. Stop spawning \u2014 try different approach or report findings.`};j.push(W),S.push(W)}else if(Tn>=wy){console.log(`${m.red} \u2716 Swarm abort: all sub-agents hit iteration limit ${Tn}\xD7 \u2014 aborting stuck swarm${m.reset}`),c&&(c.stop(),c=null),l(null),Pe(R,B,T,x,he,{suppressHint:!0}),Me(j);return}}else I>0&&(Tn=0)}}{let y=tt.reduce((J,C)=>J+(typeof C.content=="string"?C.content.length:0),0);if(y>2e5){let J=tt.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 J){if(y<=2e5)break;let Q=y-2e5,q=Math.max(L-Q,500);q<L&&typeof tt[C].content=="string"&&(tt[C]={...tt[C],content:tt[C].content.substring(0,q)+`
1338
- ...(truncated ${L-q} chars \u2014 per-message budget)`},y-=L-q)}}}for(let w of tt)j.push(w),S.push(w);if(!Ze)for(let w=0;w<tt.length;w++){if(!me[w]||me[w].fnName!=="ssh_exec")continue;let y=tt[w];if(!y||typeof y.content!="string")continue;let J=gc(y.content);if(J){Ze=!0,ht=J.slice(0,120),Zt=0,jt=!1,fn=0,F(`${m.yellow} \u26A1 Root cause detected: ${ht} \u2014 fix phase (read budget: 3)${m.reset}`);let C={role:"user",content:`[SYSTEM] Root cause identified: ${ht}. Read only the file that needs fixing, then edit it. Do not read other files.`};j.push(C),S.push(C);break}}for(let w=0;w<tt.length;w++){let y=me[w];if(!y)continue;let J=typeof tt[w]?.content=="string"?tt[w].content:"";if(y.fnName==="create_task"){let C=J.match(/Task #(\d+) created/),L=typeof y.args?.subject=="string"?y.args.subject:"";C&&L&&Vo.set(C[1],L)}else if((y.fnName==="write_file"||y.fnName==="edit_file")&&!J.startsWith("BLOCKED:")&&J.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(q=>q.length>2);for(let[q,ue]of Vo){if(Jo.has(q))continue;let I=ue.toLowerCase().split(/\W+/).filter(W=>W.length>3);Q.filter(W=>I.some(V=>V.includes(W)||W.includes(V))).length>=1&&(Jo.add(q),F(`${m.green} \u2714 Auto-matched task #${q} to ${L}: ${ue.slice(0,60)}${m.reset}`))}}}{let w=ot();if(Dt(S,w).percentage>=78){let{messages:J,tokensRemoved:C}=Vt(S,w);C>0&&(S=J,console.log(`${m.dim} [auto-compressed \u2014 ~${C} tokens freed, now ${Math.round(Dt(S,w).percentage)}%]${m.reset}`))}}if(Mi()&&!s.skillLoop&&(me.some(y=>y&&["write_file","edit_file","patch_file"].includes(y.fnName))?we=0:(we===0&&(ge=T.size),we++),we>=8&&R>=4&&T.size===ge)){F(`${m.green} \u2713 Stagnation exit: ${we} read-only iterations, no new file changes${m.reset}`),c&&(c.stop(),c=null),l(null),Pe(R,B,T,x,he),Me(j);break e}let eu=CE();if(eu){let w={role:"user",content:`[User note mid-run]: ${eu}`};j.push(w),S.push(w),console.log(`${m.cyan} \u270E Context added${m.reset}`)}}if(We>=Bt){if(c&&(c.stop(),c=null),l(null),Pe(R,B,T,x,he),Me(j),lc(j),_e&&Le==="plan"){let us=[...j].reverse().find(et=>et.role==="assistant"),gt=typeof us?.content=="string"?us.content:"",ds=qo("implement",gt);if(ds){j.push(ds),S=[{role:"system",content:await Oc()},...j],Bt=ns("implement"),F(`${m.yellow} \u26A0 Plan budget exhausted \u2014 auto-transitioning to implement${m.reset}`);continue e}}else if(_e&&Le==="verify"){F(`${m.yellow} \u26A0 Verify budget exhausted \u2014 completing session${m.reset}`);break e}let{getActiveProviderName:be}=Ve();if(be()==="ollama"&&Gi<zc){if(T.size===0&&!zi){console.log(`${m.yellow} \u26A0 Max iterations reached with no progress. Stopping.${m.reset}`);break e}Gi++,Bt=20,console.log(`${m.dim} \u2500\u2500 auto-extending (+20 turns, ext ${Gi}/${zc}) \u2500\u2500${m.reset}`);continue e}if(console.log(`
1339
- ${m.yellow}\u26A0 Max iterations reached.${m.reset}`),await Eg(" 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}}Dg.exports={processInput:BE,clearConversation:ME,getConversationLength:LE,getConversationMessages:IE,setConversationMessages:DE,setAbortSignalGetter:uE,setMaxIterations:cE,invalidateSystemPromptCache:Sc,clearToolFilterCache:wE,getCachedFilteredTools:Mg,buildSystemPrompt:Oc,splitSystemPrompt:NE,SYSTEM_PROMPT_DYNAMIC_BOUNDARY:Ac,getProjectContextHash:Pg,buildUserContent:Og,_detectImageURLs:Rg,_downloadImageURL:Cg,_grabClipboardImage:Ag,detectFrustration:Ng,detectAndTruncateLoop:bc,injectMidRunNote:RE,resetSessionTracking:Ig}});var Ve=z((a1,Ug)=>{var{OllamaProvider:UE}=Tu(),{OpenAIProvider:WE}=Ou(),{AnthropicProvider:HE}=Lu(),{GeminiProvider:YE}=qu(),{LocalProvider:GE}=Uu(),{checkBudget:zE}=kr(),Dc={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"}},Lc=(process.env.OLLAMA_FALLBACK_CHAIN||"").split(",").map(t=>t.trim()).filter(Boolean),qg={};for(let[t,e]of Object.entries(Dc))for(let s of Object.values(e))qg[s]=t;function Ic(t,e){let s=qg[t];return s&&Dc[s][e]||t}var Qe={},mt=null,Fe=null,Zo=[];function Ot(){if(Object.keys(Qe).length>0)return;zs("ollama",new UE),zs("openai",new WE),zs("anthropic",new HE),zs("gemini",new YE),zs("local",new GE);let t=process.env.DEFAULT_PROVIDER||"ollama",e=process.env.DEFAULT_MODEL||null;Qe[t]?(mt=t,Fe=e||Qe[t].defaultModel):(mt="ollama",Fe="kimi-k2.5");let s=process.env.FALLBACK_CHAIN;s&&(Zo=s.split(",").map(n=>n.trim()).filter(Boolean))}function zs(t,e){Qe[t]=e}function KE(t){return Ot(),Qe[t]||null}function jc(){return Ot(),Qe[mt]||null}function XE(){return Ot(),mt}function VE(){return Ot(),Fe}function JE(){Ot();let t=jc();if(!t)return{id:Fe,name:Fe,provider:mt};let e=t.getModel(Fe);return e?{...e,provider:mt}:{id:Fe,name:Fe,provider:mt}}function Fg(t){if(!t)return{provider:null,model:null};let e=t.indexOf(":");if(e>0){let s=t.slice(0,e);if(Qe[s]||["ollama","openai","anthropic","gemini","local"].includes(s))return{provider:s,model:t.slice(e+1)}}return{provider:null,model:t}}function ZE(t){Ot();let{provider:e,model:s}=Fg(t);if(e){let o=Qe[e];return o&&(o.getModel(s)||e==="local"||e==="ollama")?(mt=e,Fe=s,qi(),!0):!1}let n=jc();if(n&&n.getModel(s))return Fe=s,qi(),!0;for(let[o,r]of Object.entries(Qe))if(r.getModel(s))return mt=o,Fe=s,qi(),!0;return!1}function qi(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=Wl();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=Kt();t()}catch{}}function QE(){Ot();let t=new Set;for(let e of Object.values(Qe))for(let s of e.getModelNames())t.add(s);return Array.from(t)}function eT(){return Ot(),Object.entries(Qe).map(([t,e])=>({provider:t,configured:e.isConfigured(),models:Object.values(e.getModels()).map(s=>({...s,active:t===mt&&s.id===Fe}))}))}function tT(){Ot();let t=[];for(let[e,s]of Object.entries(Qe)){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 nT(t){Zo=Array.isArray(t)?t:[]}function sT(){return[...Zo]}function jg(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 Bg(t){let e=[mt,...Zo.filter(r=>r!==mt)],s,n=0,o=0;for(let r=0;r<e.length;r++){let i=e[r],a=Qe[i];if(!a||!a.isConfigured())continue;o++;let l=zE(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?Ic(Fe,i):Fe;return c&&u!==Fe&&process.stderr.write(` [fallback: ${i}:${u}]
1340
- `),await t(a,i,u)}catch(c){if(s=c,!jg(c)||r>=e.length-1)throw c;if(i==="ollama"&&Lc.length>0){let u=isFallback?Ic(Fe,i):Fe;for(let d of Lc)if(d!==u)try{return process.stderr.write(` [ollama fallback: ${d}]
1341
- `),await t(a,i,d)}catch(f){if(s=f,!jg(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 oT(t,e,s={}){return Ot(),Bg((n,o,r)=>n.stream(t,e,{model:r,signal:s.signal,...s}))}async function rT(t,e,s={}){if(Ot(),s.provider){let n=Qe[s.provider];if(!n||!n.isConfigured())throw new Error(`Provider '${s.provider}' is not available`);let o={model:s.model||Fe,...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 Bg(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 iT(){Ot();let t=[];for(let[e,s]of Object.entries(Qe))s.isConfigured()&&t.push({name:e,models:Object.values(s.getModels())});return t}function aT(){for(let t of Object.keys(Qe))delete Qe[t];mt=null,Fe=null,Zo=[]}Ug.exports={registerProvider:zs,getProvider:KE,getActiveProvider:jc,getActiveProviderName:XE,getActiveModelId:VE,getActiveModel:JE,setActiveModel:ZE,getModelNames:QE,parseModelSpec:Fg,listProviders:eT,listAllModels:tT,callStream:oT,callChat:rT,getConfiguredProviders:iT,setFallbackChain:nT,getFallbackChain:sT,resolveModelForProvider:Ic,MODEL_EQUIVALENTS:Dc,OLLAMA_FALLBACK_MODELS:Lc,_reset:aT}});var{C:Y}=ze(),lT=Ve(),{TOOL_DEFINITIONS:Wg}=ks(),{saveRoutingConfig:cT}=js(),Bc=[{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}],Hg=[{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)}],Ui=[...Bc,...Hg],qc=["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 uT(){try{let s=require("path").join(require("os").homedir(),".nex-code","benchmark-results.json");if(!require("fs").existsSync(s))return qc;let n=JSON.parse(require("fs").readFileSync(s,"utf-8"));return!Array.isArray(n)||n.length===0?qc: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 qc}}var Uc=uT(),dT=["minimax-m2.7:cloud","qwen3-coder:480b","devstral-2:123b"],Yg=(()=>{let t=Uc.slice(0,3);return t.length>=3?t:dT})(),fT=14,Fi={producedToolCall:.2,correctTool:.35,validArgs:.3,schemaCompliant:.15},pT="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 Fc(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:pT},{role:"user",content:t.prompt}],o=Date.now();try{let r=await lT.callChat(n,Wg,{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=Wg.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 Ks(t){return t.error?0:((t.producedToolCall?Fi.producedToolCall:0)+(t.correctTool?Fi.correctTool:0)+(t.validArgs?Fi.validArgs:0)+(t.schemaCompliant?Fi.schemaCompliant:0))*100}var Gg={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 Wc(t){return Object.entries(t).map(([e,s])=>{let n=s.map(Ks),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=>Gg[u.category]===a);if(l.length===0)continue;let c=l.map(Ks).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 zg(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=>Gg[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 Kg(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(`
1340
+ `),fs=null}if(!Vs.skipSummaries){let w=Sy.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),J=Yi.record(0,y,x,T);J&&oE(J)}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:"))&&(Rn++,Rn>=Gc)){q(`${m.red} \u2716 Loop abort: ${Rn} consecutive blocked calls (pre-execution) \u2014 model not heeding BLOCKED messages${m.reset}`),c&&(c.stop(),c=null),l(null),Pe(R,B,T,x,he,{suppressHint:!0}),Ne(D);return}}for(let w=0;w<me.length;w++){let y=me[w];if(!y.canExecute)continue;let J=nt[w].content,C=J.split(`
1341
+ `)[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 I=Ot.get(y.args.path)||0;Ot.set(y.args.path,I+1)}if(!L&&y.fnName==="bash"&&Vo.size>0){let I=(y.args?.command||"").toLowerCase();if(/\b(test|jest|vitest|pytest|mocha|tsc|build|lint|eslint|check)\b/.test(I))for(let[W]of Vo)Ot.has(W)||(Ot.set(W,1),q(`${m.cyan} \u21A9 Test failure \u2014 queuing recovery re-read: "${W.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(kn++,kn>=2){q(`${m.yellow} \u26A0 File-not-found streak: ${kn} consecutive misses \u2014 forcing search${m.reset}`);let I={role:"user",content:`[SYSTEM] ${kn} 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.`};D.push(I),S.push(I)}}else L&&(y.fnName==="read_file"||y.fnName==="edit_file"||y.fnName==="search_files"||y.fnName==="glob_files")&&(kn=0);if(L&&y.fnName==="write_file"&&y.args?.path){let I=y.args.path.split("/").pop(),U=y.args.path.includes("/tests/")||y.args.path.includes("\\tests\\");if(/^(test_|demo_|temp_|tmp_|scratch_)/.test(I)&&!U){q(`${m.yellow} \u26A0 Temp file: "${I}" \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.`};D.push(V),S.push(V)}}if(L&&["write_file","edit_file","patch_file"].includes(y.fnName)&&y.args&&y.args.path){Ot.delete(y.args.path),T.add(y.args.path);let I=rs(Qg,y.args.path),U=y.args.path.split("/").slice(-2).join("/");if(I===ey){q(`${m.yellow} \u26A0 Loop warning: "${U}" edited ${I}\xD7 \u2014 possible edit loop${m.reset}`);let W={role:"user",content:`[SYSTEM WARNING] "${y.args.path}" edited ${I}\xD7. One more edit max, then move on.`};D.push(W),S.push(W)}else if(I>=ty){q(`${m.red} \u2716 Loop abort: "${U}" edited ${I}\xD7 \u2014 aborting to prevent runaway loop${m.reset}`),c&&(c.stop(),c=null),l(null),Pe(R,B,T,x,he,{suppressHint:!0}),Ne(D);return}}if(L&&y.canExecute&&_e&&(En=0),L&&y.canExecute&&!(_e&&Le==="plan")){let I=["read_file","grep","search_files","glob","list_directory","ssh_exec","find_files"];if(["write_file","edit_file","patch_file"].includes(y.fnName)){Pt=0,Lt=!1,pn=0,Wt++;let Q=y.args?.path||y.args?.file_path;Q&&(wc(Sn,Q,1),fn.delete(Q),oe.add(Q))}else I.includes(y.fnName)&&(Pt++,Lt&&pn++);let W=n.postEditCap,V=_e&&Le==="implement"?Math.min(zc,6):zc,Z=et?3:Mt?Wt>0?2:4:Wt>0?W:V,re=3,fe=!_e&&Lt&&(et||Mt&&Wt>=1||pn>=re);if(jo<2&&!Lt&&Pt>=3&&T.size===0){let Q=parseInt(process.env.NEX_TASK_TIMEOUT_MS,10)||0,Ee=Date.now()-he,Ie=jo===0?.4:.65;if(Q>0&&Ee>Q*Ie){jo++;let pt=Math.round(Ee/6e4),Ve=Math.round(Ee/Q*100);q(`${m.yellow} \u26A0 Time nudge #${jo}: ${pt}m elapsed (${Ve}%), ${Pt} reads, 0 edits${m.reset}`);let Tt={role:"user",content:jo===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.`};D.push(Tt),S.push(Tt)}}if(fe&&I.includes(y.fnName)){let Q=et?`root cause already identified (${wt})`:pn>=re?`${Pt} consecutive reads without an edit`:`${Wt} file edit(s) already made`;q(`${m.red} \u2716 Blocked read-only tool: cap fired, ${Q}${m.reset}`),y.canExecute=!1,y.errorResult={role:"tool",content:et?`BLOCKED: root cause already identified (${wt}). Use edit_file to fix the issue \u2014 do not read more files.`:Mt?"BLOCKED: files already written \u2014 continue with write_file or edit_file to finish the remaining tasks. Do not read more files.":pn>=re?`BLOCKED: You have read ${Pt} 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: ${Wt} 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(Pt>=Z&&!Lt){if(Lt=!0,q(`${m.yellow} \u26A0 Investigation cap: ${Pt} read-only calls without an edit \u2014 forcing implementation${m.reset}`),_e&&Le==="plan"){let Ie=[...S].reverse().find(Tt=>Tt.role==="assistant"),pt=typeof Ie?.content=="string"?Ie.content:"",Ve=Fo("implement",pt);Ve&&(D.push(Ve),S.push(Ve),He=0,Yt=os("implement"))}let Q;et?Q=`[SYSTEM] Root cause was already identified (${wt}). Edit the file now \u2014 do not read more files.`:St?Q="[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.":Q="[SYSTEM] You have read enough files. Now implement your fix using edit_file.";let Ee={role:"user",content:Q};D.push(Ee),S.push(Ee)}}if((y.fnName==="bash"||y.fnName==="ssh_exec")&&y.args&&y.args.command){let I=y.args.command.replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),U=rs(Yc,I);if(U===ny){q(`${m.yellow} \u26A0 Loop warning: same bash command run ${U}\xD7 \u2014 possible debug loop${m.reset}`);let W={role:"user",content:`[SYSTEM WARNING] Same bash command ${U}\xD7. Debug loop detected \u2014 try a different approach.`};D.push(W),S.push(W)}else if(U>=sy){q(`${m.red} \u2716 Loop abort: same bash command run ${U}\xD7 \u2014 aborting runaway debug loop${m.reset}`),c&&(c.stop(),c=null),l(null),Pe(R,B,T,x,he,{suppressHint:!0}),Ne(D);return}}if(y.fnName==="ssh_exec"){Nt++;{let W=(nt[w]?.content??"").split(`
1342
+ `).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(W){if(W===Ni?as++:(Ni=W,as=1),as===3&&!St){q(`${m.yellow} \u26A0 SSH repeated-error: "${W.slice(0,60)}" returned ${as}\xD7 \u2014 nudging to change approach${m.reset}`);let V={role:"user",content:`[SYSTEM WARNING] The last ${as} SSH commands all failed with the same error: "${W}". Retrying variants of the same command will not help. Switch to a different approach to accomplish the task (e.g. use a different tool, read a local file, or change the command syntax entirely).`};D.push(V),S.push(V)}}else Ni="",as=0}if(Nt>=$y){q(`${m.red} \u2716 SSH storm abort: ${Nt} consecutive ssh_exec calls \u2014 aborting${m.reset}`),c&&(c.stop(),c=null),l(null),Pe(R,B,T,x,he,{suppressHint:!0}),Ne(D);return}else if(Nt===Xs){{let W=rt(),{messages:V}=Qt(S,W);S=V}St=!0,Si++,q(`${m.yellow} \u26A0 SSH storm warning (#${Si}): ${Nt} consecutive ssh_exec calls \u2014 blocking further SSH${m.reset}`);let U={role:"user",content:et?`[SYSTEM WARNING] ${Nt} consecutive SSH calls. Root cause identified (${wt}). Read the file that needs fixing, then edit it.`:`[SYSTEM WARNING] ${Nt} 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.`};D.push(U),S.push(U)}}else y.canExecute&&(Nt=0);if(y.fnName==="bash"&&y.canExecute){let W=(nt[w]?.content??"").split(`
1343
+ `).map(V=>V.trim()).find(V=>V.length>0&&(V.startsWith("EXIT")||/^[\w./-]+:\s/.test(V)||V.startsWith("bash:")||V.startsWith("sh:")))??"";if(W){if(W===Mi?ls++:(Mi=W,ls=1),ls===3){q(`${m.yellow} \u26A0 Bash repeated-error: "${W.slice(0,60)}" returned ${ls}\xD7 \u2014 nudging to change approach${m.reset}`);let V={role:"user",content:`[SYSTEM WARNING] The last ${ls} bash commands all failed with the same error: "${W}". Retrying variants of the same command will not help. Switch to a completely different approach (e.g. use a different tool, change the command syntax, or use ssh_exec to run the command on the remote server instead).`};D.push(V),S.push(V)}}else Mi="",ls=0}if(y.fnName==="bash"&&y.canExecute&&!_c&&y.args?.command){let I=nt[w]?.content??"";if(/git\s+commit\b/.test(y.args.command)&&!I.startsWith("EXIT")&&!I.startsWith("ERROR")&&(/\[\S+\s+[a-f0-9]+\]/.test(I)||I.includes("files changed")||I.includes("file changed")||I.includes("insertions(+)")||I.includes("create mode"))){_c=!0,qo=0,q(`${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."};D.push(V),S.push(V)}}if(_c&&y.fnName==="bash"&&y.args?.command&&/git\s+(status|diff|log|show)\b/.test(y.args.command)&&(qo++,qo>2)){q(`${m.yellow} \u26A0 Post-commit git verification blocked (call ${qo})${m.reset}`);let U={role:"user",content:"[SYSTEM] \u26A0 STOP: You already ran "+(qo-1)+" git verification commands after committing. The commit is confirmed. Write your final summary NOW and do not make any more tool calls."};D.push(U),S.push(U)}if(L&&y.fnName==="grep"&&y.args&&y.args.pattern){let I=`${y.args.pattern}|${y.args.path||""}`,U=rs(oy,I);if(U===ry){q(`${m.yellow} \u26A0 Loop warning: grep pattern "${y.args.pattern.slice(0,40)}" run ${U}\xD7 \u2014 possible search loop${m.reset}`);let W={role:"user",content:`[SYSTEM WARNING] Same grep pattern ${U}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};D.push(W),S.push(W)}else if(U>=iy){q(`${m.red} \u2716 Loop abort: grep pattern run ${U}\xD7 \u2014 aborting runaway search loop${m.reset}`),c&&(c.stop(),c=null),l(null),Pe(R,B,T,x,he,{suppressHint:!0}),Ne(D);return}if(y.args.path){let W=rs(Gi,y.args.path),V=en(us,y.args.path)>=1;if(W===(V?1:ay)){let re=y.args.path.split("/").slice(-2).join("/");q(`${m.yellow} \u26A0 Loop warning: "${re}" grepped ${W}\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 ${W}\xD7 \u2014 use the search results already in context instead of searching again.`};D.push(fe),S.push(fe)}}}if(L&&(y.fnName==="glob"||y.fnName==="glob_files"||y.fnName==="search_files")&&y.args){let I=y.args.pattern||y.args.query||y.args.path||"",U=rs(ly,I);if(U===cy){q(`${m.yellow} \u26A0 Loop warning: glob pattern "${I.slice(0,40)}" run ${U}\xD7 \u2014 possible search loop${m.reset}`);let V={role:"user",content:`[SYSTEM WARNING] Same glob/search pattern ${U}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};D.push(V),S.push(V)}else if(U>=uy){q(`${m.red} \u2716 Loop abort: glob pattern run ${U}\xD7 \u2014 aborting runaway search loop${m.reset}`),c&&(c.stop(),c=null),l(null),Pe(R,B,T,x,he,{suppressHint:!0}),Ne(D);return}let W=I.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 W){let Z=V.toLowerCase();Xo.has(Z)||Xo.set(Z,new Set);let re=Xo.get(Z);if(re.add(I),re.size===fy){q(`${m.red} \u2716 Glob core-term block: ${re.size} different patterns all searching for "${Z}" \u2014 search loop${m.reset}`);let fe={role:"user",content:`[SYSTEM WARNING] You have searched for "${Z}" 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.`};D.push(fe),S.push(fe)}else if(re.size===dy){q(`${m.yellow} \u26A0 Glob core-term warning: ${re.size} different patterns searching for "${Z}"${m.reset}`);let fe={role:"user",content:`[SYSTEM WARNING] ${re.size} different glob patterns all target "${Z}". If previous searches returned no results, the file probably does not exist \u2014 stop searching and proceed with available information.`};D.push(fe),S.push(fe)}}}let ee=(y.args?.command||y.args?.cmd||y.args?.script||"").toLowerCase(),F=/\b(health|healthcheck|health-check|status|check|ping|validate|alive|ready)\b/.test(ee)||/\/(health|status|ping|ready|alive)\b/.test(ee);if(L&&(y.fnName==="bash"||y.fnName==="ssh_exec")&&F&&J.includes('"valid":true')){{let U=rt();if(Ut(S,U).percentage>=60){let{messages:V,tokensRemoved:Z}=Qt(S,U);Z>0&&(S=V,console.log(`${m.dim} [pre-stop-compress \u2014 ~${Z} tokens freed before STOP injection, now ${Math.round(Ut(S,U).percentage)}%]${m.reset}`))}}let I={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.'};D.push(I),S.push(I),console.log(`${m.cyan} \u2713 Health-check stop signal detected \u2014 injecting STOP instruction${m.reset}`)}if(J.startsWith("BLOCKED:")){if(Rn++,Rn>=Gc){q(`${m.red} \u2716 Loop abort: ${Rn} consecutive blocked calls \u2014 model not heeding BLOCKED messages${m.reset}`),c&&(c.stop(),c=null),l(null),Pe(R,B,T,x,he,{suppressHint:!0}),Ne(D);return}}else Rn=0;if(L)Tn=0,Xi=!0;else if(Tn++,Tn===gy){q(`${m.yellow} \u26A0 Loop warning: ${Tn} consecutive tool errors \u2014 possible stuck loop${m.reset}`);let I={role:"user",content:`[SYSTEM WARNING] ${Tn} consecutive errors. Stuck loop \u2014 try fundamentally different approach or declare done.`};D.push(I),S.push(I)}else if(Tn>=yy){q(`${m.red} \u2716 Loop abort: ${Tn} consecutive errors \u2014 aborting stuck loop${m.reset}`),c&&(c.stop(),c=null),l(null),Pe(R,B,T,x,he,{suppressHint:!0}),Ne(D);return}if(L&&y.fnName==="read_file"&&y.args&&y.args.path){x.add(y.args.path),oe.delete(y.args.path);let I=rs(us,y.args.path);{let Z=y.args.line_start!=null&&y.args.line_start||1,re=y.args.line_start!=null?y.args.line_end||Z+350:350;fn.has(y.args.path)||fn.set(y.args.path,[]),fn.get(y.args.path).push([Z,re])}if(y._scrollWarn){let{sectionCount:Z,path:re}=y._scrollWarn,fe={role:"user",content:`[SYSTEM WARNING] "${re}" \u2014 you have now read ${Z} 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.`};D.push(fe),S.push(fe),q(`${m.yellow} \u26A0 Scroll warning: "${re.split("/").slice(-2).join("/")}" \u2014 ${Z} sections read \u2014 use grep instead${m.reset}`)}let U=y.args.path.split("/").slice(-2).join("/"),W=!y.args?.line_start&&!y.args?.line_end,V=_e&&Le==="plan";if(!V&&W&&I===py){{let re=rt();if(Ut(S,re).percentage>=60){let{messages:Q}=Qt(S,re);S=Q}}q(`${m.yellow} \u26A0 Loop warning: "${U}" read unbounded ${I}\xD7 \u2014 use line_start/line_end${m.reset}`);let Z={role:"user",content:`[SYSTEM WARNING] "${y.args.path}" read ${I}\xD7 without line ranges. Use line_start/line_end to read specific sections \u2014 do not re-read the full file.`};D.push(Z),S.push(Z)}else if(!V&&W&&I>=hy){q(`${m.red} \u2716 Loop abort: "${U}" read unbounded ${I}\xD7 \u2014 aborting runaway read loop${m.reset}`),c&&(c.stop(),c=null),l(null),Pe(R,B,T,x,he,{suppressHint:!0}),Ne(D);return}}if(y.fnName==="spawn_agents"){let I=(J.match(/\bStatus: done\b/g)||[]).length;if((J.match(/\bStatus: truncated\b/g)||[]).length>0&&I===0){if(Cn++,Cn===wy){q(`${m.yellow} \u26A0 Swarm warning: all sub-agents hit iteration limit ${Cn}\xD7 in a row${m.reset}`);let W={role:"user",content:`[SYSTEM WARNING] Sub-agents truncated ${Cn}\xD7 in a row. Stop spawning \u2014 try different approach or report findings.`};D.push(W),S.push(W)}else if(Cn>=_y){console.log(`${m.red} \u2716 Swarm abort: all sub-agents hit iteration limit ${Cn}\xD7 \u2014 aborting stuck swarm${m.reset}`),c&&(c.stop(),c=null),l(null),Pe(R,B,T,x,he,{suppressHint:!0}),Ne(D);return}}else I>0&&(Cn=0)}}{let y=nt.reduce((J,C)=>J+(typeof C.content=="string"?C.content.length:0),0);if(y>2e5){let J=nt.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 J){if(y<=2e5)break;let ee=y-2e5,F=Math.max(L-ee,500);F<L&&typeof nt[C].content=="string"&&(nt[C]={...nt[C],content:nt[C].content.substring(0,F)+`
1344
+ ...(truncated ${L-F} chars \u2014 per-message budget)`},y-=L-F)}}}for(let w of nt)D.push(w),S.push(w);if(!et)for(let w=0;w<nt.length;w++){if(!me[w]||me[w].fnName!=="ssh_exec")continue;let y=nt[w];if(!y||typeof y.content!="string")continue;let J=yc(y.content);if(J){et=!0,wt=J.slice(0,120),Pt=0,Lt=!1,pn=0,q(`${m.yellow} \u26A1 Root cause detected: ${wt} \u2014 fix phase (read budget: 3)${m.reset}`);let C={role:"user",content:`[SYSTEM] Root cause identified: ${wt}. Read only the file that needs fixing, then edit it. Do not read other files.`};D.push(C),S.push(C);break}}for(let w=0;w<nt.length;w++){let y=me[w];if(!y)continue;let J=typeof nt[w]?.content=="string"?nt[w].content:"";if(y.fnName==="create_task"){let C=J.match(/Task #(\d+) created/),L=typeof y.args?.subject=="string"?y.args.subject:"";C&&L&&Jo.set(C[1],L)}else if((y.fnName==="write_file"||y.fnName==="edit_file")&&!J.startsWith("BLOCKED:")&&J.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(),ee=L.split(/[._\-/]/).filter(F=>F.length>2);for(let[F,ue]of Jo){if(Zo.has(F))continue;let I=ue.toLowerCase().split(/\W+/).filter(W=>W.length>3);ee.filter(W=>I.some(V=>V.includes(W)||W.includes(V))).length>=1&&(Zo.add(F),q(`${m.green} \u2714 Auto-matched task #${F} to ${L}: ${ue.slice(0,60)}${m.reset}`))}}}{let w=rt();if(Ut(S,w).percentage>=78){let{messages:J,tokensRemoved:C}=Qt(S,w);C>0&&(S=J,console.log(`${m.dim} [auto-compressed \u2014 ~${C} tokens freed, now ${Math.round(Ut(S,w).percentage)}%]${m.reset}`))}}if(Li()&&!s.skillLoop&&(me.some(y=>y&&["write_file","edit_file","patch_file"].includes(y.fnName))?we=0:(we===0&&(ge=T.size),we++),we>=8&&R>=4&&T.size===ge)){q(`${m.green} \u2713 Stagnation exit: ${we} read-only iterations, no new file changes${m.reset}`),c&&(c.stop(),c=null),l(null),Pe(R,B,T,x,he),Ne(D);break e}let tu=AE();if(tu){let w={role:"user",content:`[User note mid-run]: ${tu}`};D.push(w),S.push(w),console.log(`${m.cyan} \u270E Context added${m.reset}`)}}if(He>=Yt){if(c&&(c.stop(),c=null),l(null),Pe(R,B,T,x,he),Ne(D),xi(D),_e&&Le==="plan"){let it=[...D].reverse().find(ze=>ze.role==="assistant"),at=typeof it?.content=="string"?it.content:"",mn=Fo("implement",at);if(mn){D.push(mn),S=[{role:"system",content:await Nc()},...D],Yt=os("implement"),q(`${m.yellow} \u26A0 Plan budget exhausted \u2014 auto-transitioning to implement${m.reset}`);continue e}}else if(_e&&Le==="verify"){q(`${m.yellow} \u26A0 Verify budget exhausted \u2014 completing session${m.reset}`);break e}let{getActiveProviderName:be}=Ze();if(be()==="ollama"&&Ki<Kc){if(T.size===0&&!Xi){console.log(`${m.yellow} \u26A0 Max iterations reached with no progress. Stopping.${m.reset}`);break e}Ki++,Yt=20,console.log(`${m.dim} \u2500\u2500 auto-extending (+20 turns, ext ${Ki}/${Kc}) \u2500\u2500${m.reset}`);continue e}if(console.log(`
1345
+ ${m.yellow}\u26A0 Max iterations reached.${m.reset}`),await Tg(" Continue for 20 more turns?")){Yt=20;continue e}console.log(`${m.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${m.reset}`)}break e}}jg.exports={processInput:UE,clearConversation:PE,getConversationLength:IE,getConversationMessages:DE,setConversationMessages:jE,setAbortSignalGetter:dE,setMaxIterations:uE,invalidateSystemPromptCache:vc,clearToolFilterCache:_E,getCachedFilteredTools:Pg,buildSystemPrompt:Nc,splitSystemPrompt:ME,SYSTEM_PROMPT_DYNAMIC_BOUNDARY:Oc,getProjectContextHash:Lg,buildUserContent:Ng,_detectImageURLs:Cg,_downloadImageURL:Ag,_grabClipboardImage:Og,detectFrustration:Mg,detectAndTruncateLoop:xc,injectMidRunNote:CE,resetSessionTracking:Dg}});var Ze=z((l1,Wg)=>{var{OllamaProvider:WE}=Ru(),{OpenAIProvider:HE}=Nu(),{AnthropicProvider:YE}=Iu(),{GeminiProvider:GE}=Fu(),{LocalProvider:zE}=Wu(),{checkBudget:KE}=Sr(),jc={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"}},Ic=(process.env.OLLAMA_FALLBACK_CHAIN||"").split(",").map(t=>t.trim()).filter(Boolean),Fg={};for(let[t,e]of Object.entries(jc))for(let s of Object.values(e))Fg[s]=t;function Dc(t,e){let s=Fg[t];return s&&jc[s][e]||t}var tt={},_t=null,Be=null,Qo=[];function It(){if(Object.keys(tt).length>0)return;zs("ollama",new WE),zs("openai",new HE),zs("anthropic",new YE),zs("gemini",new GE),zs("local",new zE);let t=process.env.DEFAULT_PROVIDER||"ollama",e=process.env.DEFAULT_MODEL||null;tt[t]?(_t=t,Be=e||tt[t].defaultModel):(_t="ollama",Be="kimi-k2.5");let s=process.env.FALLBACK_CHAIN;s&&(Qo=s.split(",").map(n=>n.trim()).filter(Boolean))}function zs(t,e){tt[t]=e}function XE(t){return It(),tt[t]||null}function qc(){return It(),tt[_t]||null}function VE(){return It(),_t}function JE(){return It(),Be}function ZE(){It();let t=qc();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 Bg(t){if(!t)return{provider:null,model:null};let e=t.indexOf(":");if(e>0){let s=t.slice(0,e);if(tt[s]||["ollama","openai","anthropic","gemini","local"].includes(s))return{provider:s,model:t.slice(e+1)}}return{provider:null,model:t}}function QE(t){It();let{provider:e,model:s}=Bg(t);if(e){let o=tt[e];return o&&(o.getModel(s)||e==="local"||e==="ollama")?(_t=e,Be=s,Bi(),!0):!1}let n=qc();if(n&&n.getModel(s))return Be=s,Bi(),!0;for(let[o,r]of Object.entries(tt))if(r.getModel(s))return _t=o,Be=s,Bi(),!0;return!1}function Bi(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=Yl();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=Jt();t()}catch{}}function eT(){It();let t=new Set;for(let e of Object.values(tt))for(let s of e.getModelNames())t.add(s);return Array.from(t)}function tT(){return It(),Object.entries(tt).map(([t,e])=>({provider:t,configured:e.isConfigured(),models:Object.values(e.getModels()).map(s=>({...s,active:t===_t&&s.id===Be}))}))}function nT(){It();let t=[];for(let[e,s]of Object.entries(tt)){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 sT(t){Qo=Array.isArray(t)?t:[]}function oT(){return[...Qo]}function qg(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 Ug(t){let e=[_t,...Qo.filter(r=>r!==_t)],s,n=0,o=0;for(let r=0;r<e.length;r++){let i=e[r],a=tt[i];if(!a||!a.isConfigured())continue;o++;let l=KE(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?Dc(Be,i):Be;return c&&u!==Be&&process.stderr.write(` [fallback: ${i}:${u}]
1346
+ `),await t(a,i,u)}catch(c){if(s=c,!qg(c)||r>=e.length-1)throw c;if(i==="ollama"&&Ic.length>0){let u=isFallback?Dc(Be,i):Be;for(let d of Ic)if(d!==u)try{return process.stderr.write(` [ollama fallback: ${d}]
1347
+ `),await t(a,i,d)}catch(f){if(s=f,!qg(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 rT(t,e,s={}){return It(),Ug((n,o,r)=>n.stream(t,e,{model:r,signal:s.signal,...s}))}async function iT(t,e,s={}){if(It(),s.provider){let n=tt[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 Ug(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 aT(){It();let t=[];for(let[e,s]of Object.entries(tt))s.isConfigured()&&t.push({name:e,models:Object.values(s.getModels())});return t}function lT(){for(let t of Object.keys(tt))delete tt[t];_t=null,Be=null,Qo=[]}Wg.exports={registerProvider:zs,getProvider:XE,getActiveProvider:qc,getActiveProviderName:VE,getActiveModelId:JE,getActiveModel:ZE,setActiveModel:QE,getModelNames:eT,parseModelSpec:Bg,listProviders:tT,listAllModels:nT,callStream:rT,callChat:iT,getConfiguredProviders:aT,setFallbackChain:sT,getFallbackChain:oT,resolveModelForProvider:Dc,MODEL_EQUIVALENTS:jc,OLLAMA_FALLBACK_MODELS:Ic,_reset:lT}});var{C:Y}=Ke(),cT=Ze(),{TOOL_DEFINITIONS:Hg}=ks(),{saveRoutingConfig:uT}=js(),Uc=[{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}],Yg=[{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)}],Hi=[...Uc,...Yg],Fc=["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 dT(){try{let s=require("path").join(require("os").homedir(),".nex-code","benchmark-results.json");if(!require("fs").existsSync(s))return Fc;let n=JSON.parse(require("fs").readFileSync(s,"utf-8"));return!Array.isArray(n)||n.length===0?Fc: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 Fc}}var Wc=dT(),fT=["minimax-m2.7:cloud","qwen3-coder:480b","devstral-2:123b"],Gg=(()=>{let t=Wc.slice(0,3);return t.length>=3?t:fT})(),pT=14,Ui={producedToolCall:.2,correctTool:.35,validArgs:.3,schemaCompliant:.15},hT="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 Bc(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:hT},{role:"user",content:t.prompt}],o=Date.now();try{let r=await cT.callChat(n,Hg,{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=Hg.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 Ks(t){return t.error?0:((t.producedToolCall?Ui.producedToolCall:0)+(t.correctTool?Ui.correctTool:0)+(t.validArgs?Ui.validArgs:0)+(t.schemaCompliant?Ui.schemaCompliant:0))*100}var zg={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 Hc(t){return Object.entries(t).map(([e,s])=>{let n=s.map(Ks),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=>zg[u.category]===a);if(l.length===0)continue;let c=l.map(Ks).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 Kg(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=>zg[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 Xg(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(`
1342
1348
  ${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),k=u.errorCount>0?`${Y.red}${u.errorCount}${Y.reset}`:`${Y.dim}0${Y.reset}`,E=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} ${E}${p}${Y.reset} ${Y.bold}${E}${h}${Y.reset} ${g} ${_} ${b} ${O} ${Y.dim}${M}${Y.reset} ${k}`)}),console.log(r),t.length>0){let u=t[0];if(console.log(`
1343
1349
  ${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(`
1344
- ${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 Xg(t){if(!(!t||t.length<2))try{let e=zg(t),{loadRoutingConfig:s}=js(),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&&(cT(o),console.log(`
1350
+ ${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 Vg(t){if(!(!t||t.length<2))try{let e=Kg(t),{loadRoutingConfig:s}=js(),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&&(uT(o),console.log(`
1345
1351
  ${Y.dim} Routing updated: ${r.join(", ")}${Y.reset}`),console.log(`
1346
- ${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 hT({models:t,quick:e=!1,onProgress:s,parallelModels:n=1}={}){let o=e?Bc.slice(0,fT):Ui,r=t?.length>0?t:e?Yg:Uc,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 Fc(c,l);i[l].push(u),s?.({model:l,task:c.id,done:!0,score:Ks(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 Fc(f,d);i[d].push(p),s?.({model:d,task:f.id,done:!0,score:Ks(p),error:p.error})}}});await Promise.all(u)}let a=Wc(i);return Kg(a,o.length),Xg(a),a}async function mT({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 Ui){s?.({model:i,task:a.id,done:!1});let l=await Fc(a,i);n[i].push(l),s?.({model:i,task:a.id,done:!0,score:Ks(l),error:l.error})}}let r=[...Wc(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),Kg(r,Ui.length),Xg(r),r}var Bi=[{id:"simple_question",name:"Simple Convergence",prompt:"What is 2+2?",maxTurns:3,successCriteria:["4"]}];function Vg(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.
1352
+ ${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 mT({models:t,quick:e=!1,onProgress:s,parallelModels:n=1}={}){let o=e?Uc.slice(0,pT):Hi,r=t?.length>0?t:e?Gg:Wc,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 Bc(c,l);i[l].push(u),s?.({model:l,task:c.id,done:!0,score:Ks(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 Bc(f,d);i[d].push(p),s?.({model:d,task:f.id,done:!0,score:Ks(p),error:p.error})}}});await Promise.all(u)}let a=Hc(i);return Xg(a,o.length),Vg(a),a}async function gT({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 Hi){s?.({model:i,task:a.id,done:!1});let l=await Bc(a,i);n[i].push(l),s?.({model:i,task:a.id,done:!0,score:Ks(l),error:l.error})}}let r=[...Hc(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),Xg(r,Hi.length),Vg(r),r}var Wi=[{id:"simple_question",name:"Simple Convergence",prompt:"What is 2+2?",maxTurns:3,successCriteria:["4"]}];function Jg(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.
1347
1353
  Example:
1348
1354
  {
1349
1355
  "scenarios": [
@@ -1356,14 +1362,14 @@ ${Y.green}\u{1F4A1} The best models have been saved to ~/.nex-code/.env and will
1356
1362
  }
1357
1363
  ]
1358
1364
  }
1359
- `),Bi;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}
1360
- `),Bi):o.scenarios}catch(o){return console.log(`${Y.yellow}Failed to parse benchmark-config.json: ${o.message}${Y.reset}
1361
- `),Bi}}function Jg(t,e){let{scoreMessages:s,_extractToolCalls:n,_getLastAssistantText:o}=fi(),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 gT(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 yT(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(`
1365
+ `),Wi;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}
1366
+ `),Wi):o.scenarios}catch(o){return console.log(`${Y.yellow}Failed to parse benchmark-config.json: ${o.message}${Y.reset}
1367
+ `),Wi}}function Zg(t,e){let{scoreMessages:s,_extractToolCalls:n,_getLastAssistantText:o}=pi(),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 yT(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 wT(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(`
1362
1368
  \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
1363
- `)}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}
1369
+ `)}function _T(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}
1364
1370
  `);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}
1365
1371
  `);return}let r=o.slice(-t);console.log(`
1366
- ${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 _T({dryRun:t=!1,model:e,cwd:s,onProgress:n}={}){let o=ir(),r=Vg(s);if(t){console.log(`
1372
+ ${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 $T({dryRun:t=!1,model:e,cwd:s,onProgress:n}={}){let o=ar(),r=Jg(s);if(t){console.log(`
1367
1373
  ${Y.bold}Scenario Benchmark \u2014 Scenarios (dry-run):${Y.reset}
1368
1374
  `);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}=Zs(),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(`
1369
- ${Y.dim}Running scenario: ${l.name}...${Y.reset}`);let{messages:c,timedOut:u}=await gT(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=Jg(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}=fi();p(d.score,{version:o.version,model:i,sessionName:`bench:${l.id}`,issues:d.issues})}catch{}}return yT(a,o.version,i),a}module.exports={runBenchmark:hT,runDiscoverBenchmark:mT,buildSummary:Wc,buildCategoryWinners:zg,TASKS:Bc,PHASE_TASKS:Hg,ALL_TASKS:Ui,scoreResult:Ks,DEFAULT_MODELS:Uc,QUICK_MODELS:Yg,runScenarioBenchmark:_T,showScoreTrend:wT,loadScenarios:Vg,DEFAULT_SCENARIOS:Bi,scoreScenario:Jg};
1375
+ ${Y.dim}Running scenario: ${l.name}...${Y.reset}`);let{messages:c,timedOut:u}=await yT(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=Zg(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}=pi();p(d.score,{version:o.version,model:i,sessionName:`bench:${l.id}`,issues:d.issues})}catch{}}return wT(a,o.version,i),a}module.exports={runBenchmark:mT,runDiscoverBenchmark:gT,buildSummary:Hc,buildCategoryWinners:Kg,TASKS:Uc,PHASE_TASKS:Yg,ALL_TASKS:Hi,scoreResult:Ks,DEFAULT_MODELS:Wc,QUICK_MODELS:Gg,runScenarioBenchmark:$T,showScoreTrend:_T,loadScenarios:Jg,DEFAULT_SCENARIOS:Wi,scoreScenario:Zg};