nex-code 0.5.14 → 0.5.15

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,34 +1,34 @@
1
- "use strict";var Ka=Object.defineProperty;var Iw=Object.getOwnPropertyDescriptor;var jw=Object.getOwnPropertyNames;var Dw=Object.prototype.hasOwnProperty;var qw=(t,e)=>()=>(t&&(e=t(t=0)),e);var Q=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Fw=(t,e)=>{for(var n in e)Ka(t,n,{get:e[n],enumerable:!0})},Bw=(t,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of jw(e))!Dw.call(t,s)&&s!==n&&Ka(t,s,{get:()=>e[s],enumerable:!(o=Iw(e,s))||o.enumerable});return t};var Uw=t=>Bw(Ka({},"__esModule",{value:!0}),t);var Kt=Q((iA,_d)=>{"use strict";var md="\x1B[0m",gd="\x1B[1m",qs="\x1B[2m";function V(t,e,n){return`\x1B[38;2;${t};${e};${n}m`}function Ww(){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
- `),s=t("python3",["-c",e],{encoding:"buffer",timeout:400,stdio:["ignore","pipe","ignore"]}).toString("utf8").match(/rgb:([0-9a-fA-F]+)\/([0-9a-fA-F]+)\/([0-9a-fA-F]+)/);if(s){let r=parseInt(s[1].slice(0,2),16),i=parseInt(s[2].slice(0,2),16),a=parseInt(s[3].slice(0,2),16);return .299*r+.587*i+.114*a<128}}catch{}return null}function yd(){let t=require("os");return require("path").join(t.homedir(),".nex-code",".theme_cache.json")}function Hw(t){try{let n=require("fs").readFileSync(yd(),"utf8"),o=JSON.parse(n);if(o&&typeof o[t]=="boolean")return o[t]}catch(e){console.error("readThemeCache failed:",e.message)}return null}function Yw(t,e){try{let n=require("fs"),o=require("path"),s=yd(),r=o.dirname(s),i={};try{i=JSON.parse(n.readFileSync(s,"utf8"))}catch(c){console.error("theme cache failed:",c.message)}i[t]=e;let a=Object.keys(i);a.length>50&&a.slice(0,a.length-50).forEach(c=>delete i[c]),n.existsSync(r)||n.mkdirSync(r,{recursive:!0}),n.writeFileSync(s,JSON.stringify(i),"utf8")}catch{}}function Gw(){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 n=process.env.TERM_SESSION_ID||"default",o=Hw(n);if(o!==null)return o;let s=Ww(),r=s!==null?s:!0;return Yw(n,r),r}var wd=Gw(),bd={reset:md,bold:gd,dim:qs,primary:V(80,190,255),secondary:V(60,170,190),success:V(80,210,120),warning:V(245,175,50),error:V(230,80,80),muted:qs,subtle:V(130,130,145),tool_read:V(80,190,255),tool_write:V(245,165,55),tool_exec:V(185,100,235),tool_search:V(70,185,190),tool_git:V(90,210,100),tool_web:V(100,215,250),tool_sysadmin:V(225,150,75),tool_default:V(100,205,115),syn_keyword:V(185,100,235),syn_string:V(90,210,120),syn_number:V(245,175,50),syn_comment:qs,syn_key:V(80,190,255),diff_add:V(80,210,120),diff_rem:V(230,80,80),banner_logo:V(80,200,255),banner_name:V(80,200,255),banner_version:qs,banner_model:qs,banner_yolo:V(245,175,50),banner_gemini:V(138,180,248),footer_sep:qs,footer_model:V(80,175,235),footer_branch:V(80,210,100),footer_project:V(130,130,145),footer_divider:V(80,80,95),footer_mode:V(210,150,50),white:V(210,210,220),red:V(220,85,85),green:V(80,200,110),yellow:V(230,185,60),blue:V(70,140,230),magenta:V(200,120,190),cyan:V(90,200,215),gray:V(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:V(110,215,230),brightMagenta:V(220,140,210),brightBlue:V(100,160,240)},$d={reset:md,bold:gd,dim:V(110,110,120),primary:V(0,110,190),secondary:V(0,125,148),success:V(0,148,62),warning:V(168,92,0),error:V(188,32,32),muted:V(110,110,120),subtle:V(155,155,165),tool_read:V(0,110,190),tool_write:V(168,92,0),tool_exec:V(128,42,188),tool_search:V(0,122,148),tool_git:V(0,138,62),tool_web:V(0,112,178),tool_sysadmin:V(168,82,0),tool_default:V(0,138,62),syn_keyword:V(128,42,188),syn_string:V(0,138,62),syn_number:V(168,92,0),syn_comment:V(135,135,148),syn_key:V(0,110,190),diff_add:V(0,148,62),diff_rem:V(188,32,32),banner_logo:V(0,122,205),banner_name:V(0,122,205),banner_version:V(100,100,118),banner_model:V(100,100,118),banner_yolo:V(168,62,0),banner_gemini:V(26,115,232),footer_sep:V(168,168,178),footer_model:V(0,102,175),footer_branch:V(0,138,62),footer_project:V(135,135,148),footer_divider:V(168,168,178),footer_mode:V(148,88,0),white:V(40,40,52),red:V(188,32,32),green:V(0,148,62),yellow:V(168,92,0),blue:V(0,110,190),magenta:V(128,42,188),cyan:V(0,125,148),gray:V(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:V(0,158,182),brightMagenta:V(158,52,208),brightBlue:V(0,112,208)},zw=wd?bd:$d;_d.exports={T:zw,isDark:wd,DARK:bd,LIGHT:$d}});var Ur=Q((aA,Kw)=>{Kw.exports={name:"nex-code",version:"0.5.14",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 .","scan:secrets":"node scripts/secret-scan.js --staged","install-hooks":"ln -sf ../../hooks/pre-commit .git/hooks/pre-commit && chmod +x .git/hooks/pre-commit && ln -sf ../../hooks/pre-push .git/hooks/pre-push && chmod +x .git/hooks/pre-push && ln -sf ../../hooks/post-merge .git/hooks/post-merge && chmod +x .git/hooks/post-merge && echo 'Hooks installed (pre-commit, pre-push, post-merge).'",prepublishOnly:"npm run build && npm test","merge-to-main":"bash scripts/merge-to-main.sh",improve:"node scripts/improve.js","extract-examples":"node scripts/extract-examples.js","benchmark:realworld":"node scripts/benchmark-realworld.js","benchmark:reallife":"node scripts/benchmark-reallife.js","benchmark:report":"node scripts/benchmark-reallife-report.js","improve:reallife":"node scripts/improve-reallife.js","benchmark:gate":"node scripts/benchmark-gate.js",release:"bash scripts/release.sh"},keywords:["ai","cli","coding","agent","ollama","ollama-cloud","openai","anthropic","gemini","llm","gpt","agentic","terminal","coding-assistant","open-source","free","qwen3","devstral","kimi-k2","deepseek","local-llm","mcp","model-context-protocol","multi-provider"],repository:{type:"git",url:"https://github.com/hybridpicker/nex-code.git"},bugs:{url:"https://github.com/hybridpicker/nex-code/issues"},homepage:"https://github.com/hybridpicker/nex-code#readme",license:"MIT",dependencies:{axios:"^1.15.0",dotenv:"^16.4.0",pixelmatch:"^7.1.0",pngjs:"^7.0.0"},devDependencies:{esbuild:"^0.27.3",jest:"^29.7.0",prettier:"^3.8.1",typescript:"^5.9.3"},overrides:{"brace-expansion":">=5.0.5",picomatch:">=4.0.4"},jest:{coverageThreshold:{global:{lines:45,functions:30,branches:35},"./cli/sub-agent.js":{lines:70,functions:60,branches:55}}}}});var Yn=Q((cA,Td)=>{var{T:J}=Kt(),Xa=5,Fs=(()=>{let t=[];for(let e=0;e<Xa;e++)t.push(e);for(let e=Xa-2;e>=1;e--)t.push(e);return t})(),xd=["\u273D","\u2726","\u2727","\u2726"],kd=["\xB7 ","\xB7\xB7 ","\xB7\xB7\xB7"," \xB7\xB7"];function vd(t=""){let e=String(t).toLowerCase();return e.includes("search")||e.includes("read")||e.includes("list")||e.includes("inspect")?{glyph:"\u25CC",color:J.cyan,accent:"scan"}:e.includes("write")||e.includes("edit")||e.includes("patch")||e.includes("build")?{glyph:"\u2726",color:J.yellow,accent:"shape"}:e.includes("test")||e.includes("diff")||e.includes("check")||e.includes("verify")?{glyph:"\u25A3",color:J.green,accent:"verify"}:e.includes("wait")||e.includes("github")||e.includes("fetch")||e.includes("browser")?{glyph:"\u25CD",color:J.blue,accent:"wait"}:{glyph:"\u25CF",color:J.cyan,accent:"think"}}function Sd(t,e,n){let o="";for(let s=0;s<Xa;s++)s===t?o+=`${n}${e}${J.reset}`:s===t-1||s===t+1?o+=`${J.dim}\xB7${J.reset}`:o+=`${J.dim}\xB7${J.reset}`;return o}function Ed(t){return`${J.dim}${kd[t%kd.length]}${J.reset}`}var Va=class{constructor(e="Thinking..."){this.text=e,this.frame=0,this.interval=null,this.startTime=null}_render(){if(this._stopped)return;let e=Fs[this.frame%Fs.length],n=vd(this.text),o=Sd(e,n.glyph,n.color),s=Ed(this.frame),r="";if(this.startTime){let i=Math.floor((Date.now()-this.startTime)/1e3);if(i>=60){let a=Math.floor(i/60),c=i%60;r=` ${J.dim}${a}m ${String(c).padStart(2,"0")}s${J.reset}`}else i>=1&&(r=` ${J.dim}${i}s${J.reset}`)}process.stderr.write(`\x1B[2K\r${n.color}${n.accent.toUpperCase()}${J.reset}${s} ${o} ${J.dim}${this.text}${J.reset}${r}`),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}},Ja=class{constructor(e){this.labels=e,this.statuses=e.map(()=>"running"),this.frame=0,this.interval=null,this.startTime=null,this.lineCount=e.length}_formatElapsed(){if(!this.startTime)return"";let e=Math.floor((Date.now()-this.startTime)/1e3);if(e<1)return"";let n=Math.floor(e/60),o=e%60;return n>0?`${n}m ${String(o).padStart(2,"0")}s`:`${o}s`}_render(){if(this._stopped)return;let e=Fs[this.frame%Fs.length],n=`${J.cyan}\u25CC${J.reset}`,o=this._formatElapsed(),s=o?` ${J.dim}${o}${J.reset}`:"",r=process.stderr.columns||80,i="";for(let a=0;a<this.labels.length;a++){let c,u;switch(this.statuses[a]){case"done":c=`${J.green}\u2713${J.reset}`,u=J.dim;break;case"error":c=`${J.red}\u2717${J.reset}`,u=J.dim;break;case"retry":c=`${J.yellow}\u21BB${J.reset}`,u=J.yellow;break;default:c=a===e?n:`${J.dim}\xB7${J.reset}`,u=""}let l=a===this.labels.length-1?s:"",d=r-4-(l?o.length+1:0),f=this.labels[a].length>d?this.labels[a].substring(0,Math.max(10,d-3))+"...":this.labels[a];i+=`\x1B[2K ${c} ${u}${f}${J.reset}${l}
1
+ "use strict";var Ka=Object.defineProperty;var Iw=Object.getOwnPropertyDescriptor;var jw=Object.getOwnPropertyNames;var Dw=Object.prototype.hasOwnProperty;var qw=(t,e)=>()=>(t&&(e=t(t=0)),e);var Q=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Fw=(t,e)=>{for(var n in e)Ka(t,n,{get:e[n],enumerable:!0})},Bw=(t,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of jw(e))!Dw.call(t,s)&&s!==n&&Ka(t,s,{get:()=>e[s],enumerable:!(o=Iw(e,s))||o.enumerable});return t};var Uw=t=>Bw(Ka({},"__esModule",{value:!0}),t);var Kt=Q((aA,xd)=>{"use strict";var gd="\x1B[0m",yd="\x1B[1m",qs="\x1B[2m";function V(t,e,n){return`\x1B[38;2;${t};${e};${n}m`}function Ww(){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
+ `),s=t("python3",["-c",e],{encoding:"buffer",timeout:400,stdio:["ignore","pipe","ignore"]}).toString("utf8").match(/rgb:([0-9a-fA-F]+)\/([0-9a-fA-F]+)\/([0-9a-fA-F]+)/);if(s){let r=parseInt(s[1].slice(0,2),16),i=parseInt(s[2].slice(0,2),16),a=parseInt(s[3].slice(0,2),16);return .299*r+.587*i+.114*a<128}}catch{}return null}function wd(){let t=require("os");return require("path").join(t.homedir(),".nex-code",".theme_cache.json")}function Hw(t){try{let n=require("fs").readFileSync(wd(),"utf8"),o=JSON.parse(n);if(o&&typeof o[t]=="boolean")return o[t]}catch(e){console.error("readThemeCache failed:",e.message)}return null}function Yw(t,e){try{let n=require("fs"),o=require("path"),s=wd(),r=o.dirname(s),i={};try{i=JSON.parse(n.readFileSync(s,"utf8"))}catch(c){console.error("theme cache failed:",c.message)}i[t]=e;let a=Object.keys(i);a.length>50&&a.slice(0,a.length-50).forEach(c=>delete i[c]),n.existsSync(r)||n.mkdirSync(r,{recursive:!0}),n.writeFileSync(s,JSON.stringify(i),"utf8")}catch{}}function Gw(){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 n=process.env.TERM_SESSION_ID||"default",o=Hw(n);if(o!==null)return o;let s=Ww(),r=s!==null?s:!0;return Yw(n,r),r}var bd=Gw(),$d={reset:gd,bold:yd,dim:qs,primary:V(80,190,255),secondary:V(60,170,190),success:V(80,210,120),warning:V(245,175,50),error:V(230,80,80),muted:qs,subtle:V(130,130,145),tool_read:V(80,190,255),tool_write:V(245,165,55),tool_exec:V(185,100,235),tool_search:V(70,185,190),tool_git:V(90,210,100),tool_web:V(100,215,250),tool_sysadmin:V(225,150,75),tool_default:V(100,205,115),syn_keyword:V(185,100,235),syn_string:V(90,210,120),syn_number:V(245,175,50),syn_comment:qs,syn_key:V(80,190,255),diff_add:V(80,210,120),diff_rem:V(230,80,80),banner_logo:V(80,200,255),banner_name:V(80,200,255),banner_version:qs,banner_model:qs,banner_yolo:V(245,175,50),banner_gemini:V(138,180,248),footer_sep:qs,footer_model:V(80,175,235),footer_branch:V(80,210,100),footer_project:V(130,130,145),footer_divider:V(80,80,95),footer_mode:V(210,150,50),white:V(210,210,220),red:V(220,85,85),green:V(80,200,110),yellow:V(230,185,60),blue:V(70,140,230),magenta:V(200,120,190),cyan:V(90,200,215),gray:V(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:V(110,215,230),brightMagenta:V(220,140,210),brightBlue:V(100,160,240)},_d={reset:gd,bold:yd,dim:V(110,110,120),primary:V(0,110,190),secondary:V(0,125,148),success:V(0,148,62),warning:V(168,92,0),error:V(188,32,32),muted:V(110,110,120),subtle:V(155,155,165),tool_read:V(0,110,190),tool_write:V(168,92,0),tool_exec:V(128,42,188),tool_search:V(0,122,148),tool_git:V(0,138,62),tool_web:V(0,112,178),tool_sysadmin:V(168,82,0),tool_default:V(0,138,62),syn_keyword:V(128,42,188),syn_string:V(0,138,62),syn_number:V(168,92,0),syn_comment:V(135,135,148),syn_key:V(0,110,190),diff_add:V(0,148,62),diff_rem:V(188,32,32),banner_logo:V(0,122,205),banner_name:V(0,122,205),banner_version:V(100,100,118),banner_model:V(100,100,118),banner_yolo:V(168,62,0),banner_gemini:V(26,115,232),footer_sep:V(168,168,178),footer_model:V(0,102,175),footer_branch:V(0,138,62),footer_project:V(135,135,148),footer_divider:V(168,168,178),footer_mode:V(148,88,0),white:V(40,40,52),red:V(188,32,32),green:V(0,148,62),yellow:V(168,92,0),blue:V(0,110,190),magenta:V(128,42,188),cyan:V(0,125,148),gray:V(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:V(0,158,182),brightMagenta:V(158,52,208),brightBlue:V(0,112,208)},zw=bd?$d:_d;xd.exports={T:zw,isDark:bd,DARK:$d,LIGHT:_d}});var Ur=Q((cA,Kw)=>{Kw.exports={name:"nex-code",version:"0.5.15",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 .","scan:secrets":"node scripts/secret-scan.js --staged","install-hooks":"ln -sf ../../hooks/pre-commit .git/hooks/pre-commit && chmod +x .git/hooks/pre-commit && ln -sf ../../hooks/pre-push .git/hooks/pre-push && chmod +x .git/hooks/pre-push && ln -sf ../../hooks/post-merge .git/hooks/post-merge && chmod +x .git/hooks/post-merge && echo 'Hooks installed (pre-commit, pre-push, post-merge).'",prepublishOnly:"npm run build && npm test","merge-to-main":"bash scripts/merge-to-main.sh",improve:"node scripts/improve.js","extract-examples":"node scripts/extract-examples.js","benchmark:realworld":"node scripts/benchmark-realworld.js","benchmark:reallife":"node scripts/benchmark-reallife.js","benchmark:report":"node scripts/benchmark-reallife-report.js","improve:reallife":"node scripts/improve-reallife.js","benchmark:gate":"node scripts/benchmark-gate.js",release:"bash scripts/release.sh"},keywords:["ai","cli","coding","agent","ollama","ollama-cloud","openai","anthropic","gemini","llm","gpt","agentic","terminal","coding-assistant","open-source","free","qwen3","devstral","kimi-k2","deepseek","local-llm","mcp","model-context-protocol","multi-provider"],repository:{type:"git",url:"https://github.com/hybridpicker/nex-code.git"},bugs:{url:"https://github.com/hybridpicker/nex-code/issues"},homepage:"https://github.com/hybridpicker/nex-code#readme",license:"MIT",dependencies:{axios:"^1.15.0",dotenv:"^16.4.0",pixelmatch:"^7.1.0",pngjs:"^7.0.0"},devDependencies:{esbuild:"^0.27.3",jest:"^29.7.0",prettier:"^3.8.1",typescript:"^5.9.3"},overrides:{"brace-expansion":">=5.0.5",picomatch:">=4.0.4"},jest:{coverageThreshold:{global:{lines:45,functions:30,branches:35},"./cli/sub-agent.js":{lines:70,functions:60,branches:55}}}}});var Yn=Q((lA,Rd)=>{var{T:J}=Kt(),Xa=5,Fs=(()=>{let t=[];for(let e=0;e<Xa;e++)t.push(e);for(let e=Xa-2;e>=1;e--)t.push(e);return t})(),kd=["\u273D","\u2726","\u2727","\u2726"],vd=["\xB7 ","\xB7\xB7 ","\xB7\xB7\xB7"," \xB7\xB7"];function Sd(t=""){let e=String(t).toLowerCase();return e.includes("search")||e.includes("read")||e.includes("list")||e.includes("inspect")?{glyph:"\u25CC",color:J.cyan,accent:"scan"}:e.includes("write")||e.includes("edit")||e.includes("patch")||e.includes("build")?{glyph:"\u2726",color:J.yellow,accent:"shape"}:e.includes("test")||e.includes("diff")||e.includes("check")||e.includes("verify")?{glyph:"\u25A3",color:J.green,accent:"verify"}:e.includes("wait")||e.includes("github")||e.includes("fetch")||e.includes("browser")?{glyph:"\u25CD",color:J.blue,accent:"wait"}:{glyph:"\u25CF",color:J.cyan,accent:"think"}}function Ed(t,e,n){let o="";for(let s=0;s<Xa;s++)s===t?o+=`${n}${e}${J.reset}`:s===t-1||s===t+1?o+=`${J.dim}\xB7${J.reset}`:o+=`${J.dim}\xB7${J.reset}`;return o}function Td(t){return`${J.dim}${vd[t%vd.length]}${J.reset}`}var Va=class{constructor(e="Thinking..."){this.text=e,this.frame=0,this.interval=null,this.startTime=null}_render(){if(this._stopped)return;let e=Fs[this.frame%Fs.length],n=Sd(this.text),o=Ed(e,n.glyph,n.color),s=Td(this.frame),r="";if(this.startTime){let i=Math.floor((Date.now()-this.startTime)/1e3);if(i>=60){let a=Math.floor(i/60),c=i%60;r=` ${J.dim}${a}m ${String(c).padStart(2,"0")}s${J.reset}`}else i>=1&&(r=` ${J.dim}${i}s${J.reset}`)}process.stderr.write(`\x1B[2K\r${n.color}${n.accent.toUpperCase()}${J.reset}${s} ${o} ${J.dim}${this.text}${J.reset}${r}`),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}},Ja=class{constructor(e){this.labels=e,this.statuses=e.map(()=>"running"),this.frame=0,this.interval=null,this.startTime=null,this.lineCount=e.length}_formatElapsed(){if(!this.startTime)return"";let e=Math.floor((Date.now()-this.startTime)/1e3);if(e<1)return"";let n=Math.floor(e/60),o=e%60;return n>0?`${n}m ${String(o).padStart(2,"0")}s`:`${o}s`}_render(){if(this._stopped)return;let e=Fs[this.frame%Fs.length],n=`${J.cyan}\u25CC${J.reset}`,o=this._formatElapsed(),s=o?` ${J.dim}${o}${J.reset}`:"",r=process.stderr.columns||80,i="";for(let a=0;a<this.labels.length;a++){let c,u;switch(this.statuses[a]){case"done":c=`${J.green}\u2713${J.reset}`,u=J.dim;break;case"error":c=`${J.red}\u2717${J.reset}`,u=J.dim;break;case"retry":c=`${J.yellow}\u21BB${J.reset}`,u=J.yellow;break;default:c=a===e?n:`${J.dim}\xB7${J.reset}`,u=""}let l=a===this.labels.length-1?s:"",d=r-4-(l?o.length+1:0),f=this.labels[a].length>d?this.labels[a].substring(0,Math.max(10,d-3))+"...":this.labels[a];i+=`\x1B[2K ${c} ${u}${f}${J.reset}${l}
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 n=0;n<this.lineCount;n++)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,n){e>=0&&e<this.statuses.length&&(this.statuses[e]=n)}stop(e={}){if(this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),!e.silent)this._renderFinal();else{let n="";for(let o=0;o<this.lineCount;o++)n+=`\x1B[2K
5
5
  `;this.lineCount>0&&(n+=`\x1B[${this.lineCount}A`),process.stderr.write(n)}process.stderr.write("\x1B[?25h")}_renderFinal(){let e=this._formatElapsed(),n=e?` ${J.dim}${e}${J.reset}`:"",o=process.stderr.columns||80,s="";for(let r=0;r<this.labels.length;r++){let i;switch(this.statuses[r]){case"done":i=`${J.green}\u2713${J.reset}`;break;case"error":i=`${J.red}\u2717${J.reset}`;break;case"retry":i=`${J.yellow}\u21BB${J.reset}`;break;default:i=`${J.yellow}\u25CB${J.reset}`}let a=r===this.labels.length-1?n:"",c=o-4-(a?e.length+1:0),u=this.labels[r].length>c?this.labels[r].substring(0,Math.max(10,c-3))+"...":this.labels[r];s+=`\x1B[2K ${i} ${J.dim}${u}${J.reset}${a}
6
- `}process.stderr.write(s)}},Wr={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},Hr={done:J.green,in_progress:J.cyan,pending:J.dim,failed:J.red},On=null,Za=class{constructor(e,n){this.name=e,this.tasks=n.map(o=>({id:o.id,description:o.description,status:o.status||"pending"})),this.frame=0,this.interval=null,this.startTime=null,this.tokens=0,this.lineCount=1+this.tasks.length,this._paused=!1}_formatElapsed(){if(!this.startTime)return"";let e=Math.floor((Date.now()-this.startTime)/1e3);if(e<1)return"";let n=Math.floor(e/60),o=e%60;return n>0?`${n}m ${String(o).padStart(2,"0")}s`:`${o}s`}_formatTokens(){return this.tokens<=0?"":this.tokens>=1e3?`${(this.tokens/1e3).toFixed(1)}k`:String(this.tokens)}_render(){if(this._stopped)return;let e=xd[this.frame%xd.length],n=this._formatElapsed(),o=this._formatTokens(),s=[n,o?`\u2193 ${o} tokens`:""].filter(Boolean).join(" \xB7 "),r=s?` ${J.dim}(${s})${J.reset}`:"",i=`\x1B[2K${J.cyan}${J.bold}${e}${J.reset} ${J.bold}${this.name}${J.reset}${J.dim}\u2026${J.reset}${r}
6
+ `}process.stderr.write(s)}},Wr={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},Hr={done:J.green,in_progress:J.cyan,pending:J.dim,failed:J.red},On=null,Za=class{constructor(e,n){this.name=e,this.tasks=n.map(o=>({id:o.id,description:o.description,status:o.status||"pending"})),this.frame=0,this.interval=null,this.startTime=null,this.tokens=0,this.lineCount=1+this.tasks.length,this._paused=!1}_formatElapsed(){if(!this.startTime)return"";let e=Math.floor((Date.now()-this.startTime)/1e3);if(e<1)return"";let n=Math.floor(e/60),o=e%60;return n>0?`${n}m ${String(o).padStart(2,"0")}s`:`${o}s`}_formatTokens(){return this.tokens<=0?"":this.tokens>=1e3?`${(this.tokens/1e3).toFixed(1)}k`:String(this.tokens)}_render(){if(this._stopped)return;let e=kd[this.frame%kd.length],n=this._formatElapsed(),o=this._formatTokens(),s=[n,o?`\u2193 ${o} tokens`:""].filter(Boolean).join(" \xB7 "),r=s?` ${J.dim}(${s})${J.reset}`:"",i=`\x1B[2K${J.cyan}${J.bold}${e}${J.reset} ${J.bold}${this.name}${J.reset}${J.dim}\u2026${J.reset}${r}
7
7
  `;for(let a=0;a<this.tasks.length;a++){let c=this.tasks[a],u=a===0?"\u23BF":"\u2502",l=Wr[c.status]||Wr.pending,d=Hr[c.status]||Hr.pending,f=c.description.length>55?c.description.substring(0,52)+"...":c.description;i+=`\x1B[2K ${J.dim}${u}${J.reset} ${d}${l}${J.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 n=0;n<this.lineCount;n++)e+=`
9
9
  `;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120),On=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,On===this&&(On=null)}pause(){if(this._paused)return;this.interval&&(clearInterval(this.interval),this.interval=null);let e="";for(let n=0;n<this.lineCount;n++)e+=`\x1B[2K
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 n=0;n<this.lineCount;n++)e+=`
11
11
  `;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120)}updateTask(e,n){let o=this.tasks.find(s=>s.id===e);o&&(o.status=n)}setStats({tokens:e}){e!==void 0&&(this.tokens=e)}isActive(){return this.interval!==null||this._paused}_renderFinal(){let e=this._formatElapsed(),n=this.tasks.filter(a=>a.status==="done").length,o=this.tasks.filter(a=>a.status==="failed").length,s=this.tasks.length,r=o>0?`${n}/${s} done, ${o} failed`:`${n}/${s} done`,i=`\x1B[2K${J.green}${J.bold}\u2714${J.reset} ${J.bold}${this.name}${J.reset} ${J.dim}(${e} \xB7 ${r})${J.reset}
12
12
  `;for(let a=0;a<this.tasks.length;a++){let c=this.tasks[a],u=a===0?"\u23BF":"\u2502",l=Wr[c.status]||Wr.pending,d=Hr[c.status]||Hr.pending,f=c.description.length>55?c.description.substring(0,52)+"...":c.description;i+=`\x1B[2K ${J.dim}${u}${J.reset} ${d}${l}${J.reset} ${J.dim}${f}${J.reset}
13
- `}process.stderr.write(i)}},Qa=class{constructor(e,n){this.toolName=e,this.message=n||`Running ${e}...`,this.count=0,this.total=null,this.detail="",this.frame=0,this.interval=null,this.startTime=null,this._stopped=!1}_render(){if(this._stopped||!process.stderr.isTTY)return;let e=Fs[this.frame%Fs.length],n=vd(this.message),o=Sd(e,n.glyph,n.color),s=Ed(this.frame),r=this.message;this.count>0&&(r+=` ${J.cyan}${this.count}${J.reset}`,this.total&&(r+=`/${this.total}`)),this.detail&&(r+=` ${J.dim}${this.detail}${J.reset}`);let i="";if(this.startTime){let a=Math.floor((Date.now()-this.startTime)/1e3);a>=1&&(i=` ${J.dim}${a}s${J.reset}`)}process.stderr.write(`\x1B[2K\r${n.color}${n.accent.toUpperCase()}${J.reset}${s} ${o} ${J.dim}${r}${J.reset}${i}`),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 Xw(t){On=t}function Vw(){return On}function Jw(){On&&(On.stop(),On=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}Td.exports={C:J,Spinner:Va,MultiProgress:Ja,TaskProgress:Za,ToolProgress:Qa,setActiveTaskProgress:Xw,getActiveTaskProgress:Vw,cleanupTerminal:Jw}});var Yr=Q((lA,Nd)=>{"use strict";var{T:Gn}=Kt(),me={kw:Gn.syn_keyword,str:Gn.syn_string,cmt:Gn.syn_comment,num:Gn.syn_number,type:Gn.cyan,punct:Gn.magenta,reset:Gn.reset},Rd={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"])},Zw={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 Ad(t){if(!t)return null;let e=t.split(".").pop().toLowerCase();return Zw[e]||null}var Cd=/\x1b\[[0-9;]*m/g;function $n(t,e,n){let o=t.split(Cd),s=t.match(Cd)||[],r="";for(let i=0;i<o.length;i++)r+=o[i].replace(e,n),i<s.length&&(r+=s[i]);return r}function Qw(t){let e=t;return e=e.replace(/"([^"\\]|\\.)*"\s*:/g,n=>me.type+n+me.reset),e=$n(e,/"([^"\\]|\\.)*"/g,n=>me.str+n+me.reset),e=$n(e,/\b-?(\d+(\.\d+)?([eE][+-]?\d+)?)\b/g,n=>me.num+n+me.reset),e=$n(e,/\b(true|false|null)\b/g,n=>me.kw+n+me.reset),e}function eb(t){if(/<!--/.test(t))return t.replace(/<!--[\s\S]*?(?:-->|$)/g,n=>me.cmt+n+me.reset);let e=t;return e=e.replace(/(<\/?)([a-zA-Z][a-zA-Z0-9.-]*)/g,(n,o,s)=>o+me.type+s+me.reset),e=$n(e,/\s([a-zA-Z][a-zA-Z0-9-]*)=/g,(n,o)=>" "+me.kw+o+me.reset+"="),e=$n(e,/"([^"]*)"/g,n=>me.str+n+me.reset),e}function tb(t){let e=t;return e=e.replace(/\/\*[\s\S]*?(?:\*\/|$)/g,n=>me.cmt+n+me.reset),e=$n(e,/#[0-9a-fA-F]{3,8}\b/g,n=>me.num+n+me.reset),e=$n(e,/\b(-?\d+(?:\.\d+)?)(px|em|rem|vh|vw|vmin|vmax|%|s|ms|deg|fr)\b/g,(n,o,s)=>me.num+o+me.reset+s),e=$n(e,/([a-z][a-z-]*)(\s*:)/g,(n,o,s)=>me.type+o+me.reset+s),e=$n(e,/"[^"]*"|'[^']*'/g,n=>me.str+n+me.reset),e}function Od(t,e,n){if(e==="json")return Qw(t);if(e==="html"||e==="xml")return eb(t);if(e==="css")return tb(t);if(e==="md")return t;let o=Rd[e]||Rd.js,s="",r=0;if(n.inBlockComment){let i=t.indexOf("*/");if(i===-1)return me.cmt+t+me.reset;if(s+=me.cmt+t.slice(0,i+2)+me.reset,n.inBlockComment=!1,r=i+2,r>=t.length)return s}if(n.inString==="`"){let i=t.indexOf("`");if(i===-1)return me.str+t+me.reset;if(s+=me.str+t.slice(0,i+1)+me.reset,n.inString=null,r=i+1,r>=t.length)return s}for(;r<t.length;){let i=t[r];if(!n.inString&&i==="/"&&t[r+1]==="*"){let a=t.indexOf("*/",r+2);if(a===-1)return s+=me.cmt+t.slice(r)+me.reset,n.inBlockComment=!0,s;s+=me.cmt+t.slice(r,a+2)+me.reset,r=a+2;continue}if(!n.inString&&((e==="js"||e==="go"||e==="rs"||e==="java")&&i==="/"&&t[r+1]==="/"||(e==="py"||e==="sh")&&i==="#"))return s+=me.cmt+t.slice(r)+me.reset,s;if(!n.inString&&(i==='"'||i==="'"||i==="`")){n.inString=i,s+=me.str+i,r++;continue}if(n.inString){if(i==="\\"&&r+1<t.length){s+=i+t[r+1],r+=2;continue}if(i===n.inString){s+=i+me.reset,n.inString=null,r++;continue}s+=i,r++;continue}if(/[0-9]/.test(i)&&(r===0||!/[a-zA-Z0-9_$]/.test(t[r-1]))){let 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++];s+=me.num+a+me.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++];s+=me.punct+a+me.reset;continue}if(/[a-zA-Z_$]/.test(i)){let a="";for(;r<t.length&&/[a-zA-Z0-9_$]/.test(t[r]);)a+=t[r++];o.has(a)?s+=me.kw+a+me.reset:/^[A-Z][A-Za-z0-9]*$/.test(a)&&e!=="sh"?s+=me.type+a+me.reset:s+=a;continue}s+=i,r++}return n.inString&&n.inString!=="`"&&(s+=me.reset,n.inString=null),s}function nb(t,e){let n=Ad(e);if(!n)return t.split(`
13
+ `}process.stderr.write(i)}},Qa=class{constructor(e,n){this.toolName=e,this.message=n||`Running ${e}...`,this.count=0,this.total=null,this.detail="",this.frame=0,this.interval=null,this.startTime=null,this._stopped=!1}_render(){if(this._stopped||!process.stderr.isTTY)return;let e=Fs[this.frame%Fs.length],n=Sd(this.message),o=Ed(e,n.glyph,n.color),s=Td(this.frame),r=this.message;this.count>0&&(r+=` ${J.cyan}${this.count}${J.reset}`,this.total&&(r+=`/${this.total}`)),this.detail&&(r+=` ${J.dim}${this.detail}${J.reset}`);let i="";if(this.startTime){let a=Math.floor((Date.now()-this.startTime)/1e3);a>=1&&(i=` ${J.dim}${a}s${J.reset}`)}process.stderr.write(`\x1B[2K\r${n.color}${n.accent.toUpperCase()}${J.reset}${s} ${o} ${J.dim}${r}${J.reset}${i}`),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 Xw(t){On=t}function Vw(){return On}function Jw(){On&&(On.stop(),On=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}Rd.exports={C:J,Spinner:Va,MultiProgress:Ja,TaskProgress:Za,ToolProgress:Qa,setActiveTaskProgress:Xw,getActiveTaskProgress:Vw,cleanupTerminal:Jw}});var Yr=Q((uA,Md)=>{"use strict";var{T:Gn}=Kt(),me={kw:Gn.syn_keyword,str:Gn.syn_string,cmt:Gn.syn_comment,num:Gn.syn_number,type:Gn.cyan,punct:Gn.magenta,reset:Gn.reset},Cd={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"])},Zw={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 Od(t){if(!t)return null;let e=t.split(".").pop().toLowerCase();return Zw[e]||null}var Ad=/\x1b\[[0-9;]*m/g;function $n(t,e,n){let o=t.split(Ad),s=t.match(Ad)||[],r="";for(let i=0;i<o.length;i++)r+=o[i].replace(e,n),i<s.length&&(r+=s[i]);return r}function Qw(t){let e=t;return e=e.replace(/"([^"\\]|\\.)*"\s*:/g,n=>me.type+n+me.reset),e=$n(e,/"([^"\\]|\\.)*"/g,n=>me.str+n+me.reset),e=$n(e,/\b-?(\d+(\.\d+)?([eE][+-]?\d+)?)\b/g,n=>me.num+n+me.reset),e=$n(e,/\b(true|false|null)\b/g,n=>me.kw+n+me.reset),e}function eb(t){if(/<!--/.test(t))return t.replace(/<!--[\s\S]*?(?:-->|$)/g,n=>me.cmt+n+me.reset);let e=t;return e=e.replace(/(<\/?)([a-zA-Z][a-zA-Z0-9.-]*)/g,(n,o,s)=>o+me.type+s+me.reset),e=$n(e,/\s([a-zA-Z][a-zA-Z0-9-]*)=/g,(n,o)=>" "+me.kw+o+me.reset+"="),e=$n(e,/"([^"]*)"/g,n=>me.str+n+me.reset),e}function tb(t){let e=t;return e=e.replace(/\/\*[\s\S]*?(?:\*\/|$)/g,n=>me.cmt+n+me.reset),e=$n(e,/#[0-9a-fA-F]{3,8}\b/g,n=>me.num+n+me.reset),e=$n(e,/\b(-?\d+(?:\.\d+)?)(px|em|rem|vh|vw|vmin|vmax|%|s|ms|deg|fr)\b/g,(n,o,s)=>me.num+o+me.reset+s),e=$n(e,/([a-z][a-z-]*)(\s*:)/g,(n,o,s)=>me.type+o+me.reset+s),e=$n(e,/"[^"]*"|'[^']*'/g,n=>me.str+n+me.reset),e}function Nd(t,e,n){if(e==="json")return Qw(t);if(e==="html"||e==="xml")return eb(t);if(e==="css")return tb(t);if(e==="md")return t;let o=Cd[e]||Cd.js,s="",r=0;if(n.inBlockComment){let i=t.indexOf("*/");if(i===-1)return me.cmt+t+me.reset;if(s+=me.cmt+t.slice(0,i+2)+me.reset,n.inBlockComment=!1,r=i+2,r>=t.length)return s}if(n.inString==="`"){let i=t.indexOf("`");if(i===-1)return me.str+t+me.reset;if(s+=me.str+t.slice(0,i+1)+me.reset,n.inString=null,r=i+1,r>=t.length)return s}for(;r<t.length;){let i=t[r];if(!n.inString&&i==="/"&&t[r+1]==="*"){let a=t.indexOf("*/",r+2);if(a===-1)return s+=me.cmt+t.slice(r)+me.reset,n.inBlockComment=!0,s;s+=me.cmt+t.slice(r,a+2)+me.reset,r=a+2;continue}if(!n.inString&&((e==="js"||e==="go"||e==="rs"||e==="java")&&i==="/"&&t[r+1]==="/"||(e==="py"||e==="sh")&&i==="#"))return s+=me.cmt+t.slice(r)+me.reset,s;if(!n.inString&&(i==='"'||i==="'"||i==="`")){n.inString=i,s+=me.str+i,r++;continue}if(n.inString){if(i==="\\"&&r+1<t.length){s+=i+t[r+1],r+=2;continue}if(i===n.inString){s+=i+me.reset,n.inString=null,r++;continue}s+=i,r++;continue}if(/[0-9]/.test(i)&&(r===0||!/[a-zA-Z0-9_$]/.test(t[r-1]))){let 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++];s+=me.num+a+me.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++];s+=me.punct+a+me.reset;continue}if(/[a-zA-Z_$]/.test(i)){let a="";for(;r<t.length&&/[a-zA-Z0-9_$]/.test(t[r]);)a+=t[r++];o.has(a)?s+=me.kw+a+me.reset:/^[A-Z][A-Za-z0-9]*$/.test(a)&&e!=="sh"?s+=me.type+a+me.reset:s+=a;continue}s+=i,r++}return n.inString&&n.inString!=="`"&&(s+=me.reset,n.inString=null),s}function nb(t,e){let n=Od(e);if(!n)return t.split(`
14
14
  `);let o=t.split(`
15
- `),s={inString:null,inBlockComment:!1};return o.map(r=>Od(r,n,s))}function sb(t,e){return e?Od(t,e,{inString:null,inBlockComment:!1}):t}Nd.exports={detectLang:Ad,highlightLine:sb,highlightLines:nb}});var Ud=Q((uA,Bd)=>{var{T:$}=Kt(),Ie=$,Md=require("path"),Pd=["\u23FA","\u25C9","\u25CE","\u25C9"];function zr(t){if(!t)return"";let e=t.replace(/^\.\//,"").split("/");return e.length>1?e.slice(-2).join("/"):e[0]}var ob={read_file:$.tool_read,list_directory:$.tool_read,write_file:$.tool_write,edit_file:$.tool_write,patch_file:$.tool_write,bash:$.tool_exec,grep:$.tool_search,search_files:$.tool_search,glob:$.tool_search,git_commit:$.tool_git,git_push:$.tool_git,git_pull:$.tool_git,git_status:$.tool_git,git_diff:$.tool_git,git_log:$.tool_git,git_branch:$.tool_git,git_stash:$.tool_git,web_fetch:$.tool_web,web_search:$.tool_web,sysadmin:$.tool_sysadmin,ssh_exec:$.tool_sysadmin,ssh_upload:$.tool_sysadmin,ssh_download:$.tool_sysadmin,deploy:$.tool_sysadmin},Dd={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"},rb={read_file:{label:"Inspect",accent:$.tool_read,icon:"\u25CC"},list_directory:{label:"Inspect",accent:$.tool_read,icon:"\u25CC"},grep:{label:"Inspect",accent:$.tool_search,icon:"\u25CC"},search_files:{label:"Inspect",accent:$.tool_search,icon:"\u25CC"},glob:{label:"Inspect",accent:$.tool_search,icon:"\u25CC"},web_fetch:{label:"Explore",accent:$.tool_web,icon:"\u25CC"},web_search:{label:"Explore",accent:$.tool_web,icon:"\u25CC"},browser_open:{label:"Explore",accent:$.tool_web,icon:"\u25CC"},browser_screenshot:{label:"Capture",accent:$.tool_web,icon:"\u25CC"},browser_click:{label:"Interact",accent:$.tool_web,icon:"\u25CC"},browser_fill:{label:"Interact",accent:$.tool_web,icon:"\u25CC"},write_file:{label:"Shape",accent:$.tool_write,icon:"\u2726"},edit_file:{label:"Shape",accent:$.tool_write,icon:"\u2726"},patch_file:{label:"Shape",accent:$.tool_write,icon:"\u2726"},bash:{label:"Execute",accent:$.tool_exec,icon:"\u25A3"},sysadmin:{label:"Operate",accent:$.tool_sysadmin,icon:"\u25A3"},ssh_exec:{label:"Operate",accent:$.tool_sysadmin,icon:"\u25A3"},ssh_upload:{label:"Ship",accent:$.tool_sysadmin,icon:"\u25A3"},ssh_download:{label:"Collect",accent:$.tool_sysadmin,icon:"\u25A3"},deploy:{label:"Ship",accent:$.tool_sysadmin,icon:"\u25A3"},git_status:{label:"Verify",accent:$.tool_git,icon:"\u2713"},git_diff:{label:"Verify",accent:$.tool_git,icon:"\u2713"},git_log:{label:"Verify",accent:$.tool_git,icon:"\u2713"},git_commit:{label:"Commit",accent:$.tool_git,icon:"\u2713"},git_push:{label:"Ship",accent:$.tool_git,icon:"\u2713"},git_pull:{label:"Sync",accent:$.tool_git,icon:"\u2713"},git_branch:{label:"Sync",accent:$.tool_git,icon:"\u2713"},git_stash:{label:"Sync",accent:$.tool_git,icon:"\u2713"}};function tc(t){return rb[t]||{label:"Run",accent:$.tool_default,icon:"\u2022"}}function Ld(t){let e=tc(t);return`${e.accent}${Ie.bold}${e.icon} ${e.label.toUpperCase()}${$.reset}`}function ib(t){return t.replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase())}function Id(t,e={}){return e.path?zr(e.path):e.file?zr(e.file):e.query?String(e.query).substring(0,44):e.pattern?String(e.pattern).substring(0,44):e.url?String(e.url).substring(0,44):e.command?String(e.command).substring(0,44):Dd[t]||ib(t)}function ab(t){return String(t||"").split(`
15
+ `),s={inString:null,inBlockComment:!1};return o.map(r=>Nd(r,n,s))}function sb(t,e){return e?Nd(t,e,{inString:null,inBlockComment:!1}):t}Md.exports={detectLang:Od,highlightLine:sb,highlightLines:nb}});var Wd=Q((dA,Ud)=>{var{T:$}=Kt(),Ie=$,Pd=require("path"),Ld=["\u23FA","\u25C9","\u25CE","\u25C9"];function zr(t){if(!t)return"";let e=t.replace(/^\.\//,"").split("/");return e.length>1?e.slice(-2).join("/"):e[0]}var ob={read_file:$.tool_read,list_directory:$.tool_read,write_file:$.tool_write,edit_file:$.tool_write,patch_file:$.tool_write,bash:$.tool_exec,grep:$.tool_search,search_files:$.tool_search,glob:$.tool_search,git_commit:$.tool_git,git_push:$.tool_git,git_pull:$.tool_git,git_status:$.tool_git,git_diff:$.tool_git,git_log:$.tool_git,git_branch:$.tool_git,git_stash:$.tool_git,web_fetch:$.tool_web,web_search:$.tool_web,sysadmin:$.tool_sysadmin,ssh_exec:$.tool_sysadmin,ssh_upload:$.tool_sysadmin,ssh_download:$.tool_sysadmin,deploy:$.tool_sysadmin},qd={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"},rb={read_file:{label:"Inspect",accent:$.tool_read,icon:"\u25CC"},list_directory:{label:"Inspect",accent:$.tool_read,icon:"\u25CC"},grep:{label:"Inspect",accent:$.tool_search,icon:"\u25CC"},search_files:{label:"Inspect",accent:$.tool_search,icon:"\u25CC"},glob:{label:"Inspect",accent:$.tool_search,icon:"\u25CC"},web_fetch:{label:"Explore",accent:$.tool_web,icon:"\u25CC"},web_search:{label:"Explore",accent:$.tool_web,icon:"\u25CC"},browser_open:{label:"Explore",accent:$.tool_web,icon:"\u25CC"},browser_screenshot:{label:"Capture",accent:$.tool_web,icon:"\u25CC"},browser_click:{label:"Interact",accent:$.tool_web,icon:"\u25CC"},browser_fill:{label:"Interact",accent:$.tool_web,icon:"\u25CC"},write_file:{label:"Shape",accent:$.tool_write,icon:"\u2726"},edit_file:{label:"Shape",accent:$.tool_write,icon:"\u2726"},patch_file:{label:"Shape",accent:$.tool_write,icon:"\u2726"},bash:{label:"Execute",accent:$.tool_exec,icon:"\u25A3"},sysadmin:{label:"Operate",accent:$.tool_sysadmin,icon:"\u25A3"},ssh_exec:{label:"Operate",accent:$.tool_sysadmin,icon:"\u25A3"},ssh_upload:{label:"Ship",accent:$.tool_sysadmin,icon:"\u25A3"},ssh_download:{label:"Collect",accent:$.tool_sysadmin,icon:"\u25A3"},deploy:{label:"Ship",accent:$.tool_sysadmin,icon:"\u25A3"},git_status:{label:"Verify",accent:$.tool_git,icon:"\u2713"},git_diff:{label:"Verify",accent:$.tool_git,icon:"\u2713"},git_log:{label:"Verify",accent:$.tool_git,icon:"\u2713"},git_commit:{label:"Commit",accent:$.tool_git,icon:"\u2713"},git_push:{label:"Ship",accent:$.tool_git,icon:"\u2713"},git_pull:{label:"Sync",accent:$.tool_git,icon:"\u2713"},git_branch:{label:"Sync",accent:$.tool_git,icon:"\u2713"},git_stash:{label:"Sync",accent:$.tool_git,icon:"\u2713"}};function tc(t){return rb[t]||{label:"Run",accent:$.tool_default,icon:"\u2022"}}function Id(t){let e=tc(t);return`${e.accent}${Ie.bold}${e.icon} ${e.label.toUpperCase()}${$.reset}`}function ib(t){return t.replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase())}function jd(t,e={}){return e.path?zr(e.path):e.file?zr(e.file):e.query?String(e.query).substring(0,44):e.pattern?String(e.pattern).substring(0,44):e.url?String(e.url).substring(0,44):e.command?String(e.command).substring(0,44):qd[t]||ib(t)}function ab(t){return String(t||"").split(`
16
16
  `).map(e=>{let n=e.match(/^(\d+):\s?(.*)$/s);return n?{lineNumber:n[1],content:n[2]||""}:null}).filter(Boolean)}function cb(t,e,n={}){let{maxLines:o=4,indent:s=" ",maxContent:r=110,includeOverflow:i=!0}=n;if(!Array.isArray(e)||e.length===0)return"";let{highlightLine:a,detectLang:c}=Yr(),u=c(t||null),l=e.slice(0,o),d=l.map(({lineNumber:f,content:p})=>{let h=p.length>r?p.substring(0,r-1)+"\u2026":p;return`${s}${$.subtle}${f}:${$.reset} ${a(h,u)}${$.reset}`});return i&&e.length>l.length&&d.push(`${s}${$.subtle}\u2026 +${e.length-l.length} more line${e.length-l.length!==1?"s":""}${$.reset}`),d.join(`
17
17
  `)}function lb(t,e=96){let n=String(t||"").replace(/\t/g," ").trimEnd();return n.length>e?n.substring(0,Math.max(1,e-1))+"\u2026":n}function ec(t,e={}){let{maxLines:n=3,maxContent:o=96}=e,r=String(t||"").split(`
18
- `).filter((a,c,u)=>a.trim()||u.length===1||c===0),i=r.slice(0,n).map(a=>lb(a,o));return{shown:i,more:Math.max(0,r.length-i.length)}}function qd(t,e={}){let{indent:n=" ",maxLines:o=2,maxContent:s=100}=e;if(!t)return"";let{shown:r,more:i}=ec(t,{maxLines:o,maxContent:s});if(r.length===0)return"";let a=r.map((c,u)=>`${n}${$.subtle}${u===0?"$":">"}${$.reset} ${$.muted}${c}${$.reset}`);return i>0&&a.push(`${n}${$.subtle}\u2026 +${i} more command line${i!==1?"s":""}${$.reset}`),a.join(`
18
+ `).filter((a,c,u)=>a.trim()||u.length===1||c===0),i=r.slice(0,n).map(a=>lb(a,o));return{shown:i,more:Math.max(0,r.length-i.length)}}function Fd(t,e={}){let{indent:n=" ",maxLines:o=2,maxContent:s=100}=e;if(!t)return"";let{shown:r,more:i}=ec(t,{maxLines:o,maxContent:s});if(r.length===0)return"";let a=r.map((c,u)=>`${n}${$.subtle}${u===0?"$":">"}${$.reset} ${$.muted}${c}${$.reset}`);return i>0&&a.push(`${n}${$.subtle}\u2026 +${i} more command line${i!==1?"s":""}${$.reset}`),a.join(`
19
19
  `)}function nc(t,e,n,o={}){let{indent:s=" ",maxLines:r=3,maxContent:i=96,includeLabels:a=!0}=o,{highlightLine:c,detectLang:u}=Yr(),l=u(t||null),{shown:d,more:f}=ec(e,{maxLines:r,maxContent:i}),{shown:p,more:h}=ec(n,{maxLines:r,maxContent:i}),g=[];return d.length>0&&a&&g.push(`${s}${$.subtle}before${$.reset}`),d.forEach(w=>{g.push(`${s}${$.diff_rem}- ${$.reset}${c(w,l)}${$.reset}`)}),f>0&&g.push(`${s}${$.subtle}\u2026 ${f} more removed line${f!==1?"s":""}${$.reset}`),p.length>0&&a&&g.push(`${s}${$.subtle}after${$.reset}`),p.forEach(w=>{g.push(`${s}${$.diff_add}+ ${$.reset}${c(w,l)}${$.reset}`)}),h>0&&g.push(`${s}${$.subtle}\u2026 ${h} more added line${h!==1?"s":""}${$.reset}`),g.join(`
20
- `)}function Fd(t,e,n={}){let{indent:o=" ",maxPatches:s=2,maxLinesPerSide:r=2,maxContent:i=92}=n;if(!Array.isArray(e)||e.length===0)return"";let a=[];return e.slice(0,s).forEach((c,u)=>{a.push(`${o}${$.subtle}patch ${u+1}${$.reset}`);let l=nc(t,c.old_text,c.new_text,{indent:o+" ",maxLines:r,maxContent:i,includeLabels:!1});l&&a.push(l)}),e.length>s&&a.push(`${o}${$.subtle}\u2026 +${e.length-s} more patches${$.reset}`),a.join(`
21
- `)}function ub(t){let e=new Set,n=[];for(let o of t){let s=tc(o.fnName).label;e.has(s)||(e.add(s),n.push(s))}return n.length===0?"":n.length<=3?n.join(`${Ie.dim} \u2192 ${Ie.reset}`):`${n.slice(0,3).join(`${Ie.dim} \u2192 ${Ie.reset}`)}${Ie.dim} \u2192 +${n.length-3}${Ie.reset}`}function Gr(t,e=!1,n=null){if(e)return`${$.error}\u23FA${$.reset}`;let o=ob[t]||$.tool_default;if(n==="blink")return`${o}\x1B[5m\u23FA\x1B[25m${$.reset}`;let s=typeof n=="number"?Pd[n%Pd.length]:n!==null?n:"\u23FA";return`${o}${s}${$.reset}`}function db(t,e,n=!1,o=null){let s=(t||[]).filter(u=>u&&u.canExecute!==!1);if(s.length===0)return`${Gr("",n,o)} Step ${e}`;if(s.length===1){let u=s[0],l=u.args||{},d=Id(u.fnName,{...l,path:l._originalPath||l.path});return`${Gr(u.fnName,n,o)} ${Ld(u.fnName)} ${Ie.bold}${d}${Ie.reset}`}let r=s[0].fnName,i=ub(s)||`${s.length} tools`,a=s.slice(0,2).map(u=>Id(u.fnName,u.args||{})).filter(Boolean).join(`${Ie.dim} \xB7 ${Ie.reset}`),c=a?` ${$.subtle}\xB7${$.reset} ${Ie.dim}${a}${Ie.reset}`:"";return`${Gr(r,n,o)} ${Ld(r)} ${Ie.bold}${i}${Ie.reset}${c}`}function fb(t,e){let n;switch(t){case"write_file":case"edit_file":case"patch_file":case"read_file":case"list_directory":n=e.path||"";break;case"bash":case"ssh_exec":n=(e.command||"").substring(0,44);break;case"grep":case"search_files":n=e.pattern?`"${e.pattern}"${e.path?` in ${e.path}`:""}`:"";break;case"glob":n=e.pattern||"";break;case"web_fetch":n=(e.url||"").substring(0,60);break;case"web_search":n=(e.query||"").substring(0,50);break;default:n=JSON.stringify(e).substring(0,80)}let o=Dd[t]||t.replace(/_/g," "),s=n?`(${Ie.dim}${n}${Ie.reset})`:"",r=`${Gr(t)} ${Ie.bold}${o}${Ie.reset}${s}`;if(t==="bash"||t==="ssh_exec"){let i=qd(e.command,{indent:" ",maxLines:2,maxContent:108});return i?`${r}
20
+ `)}function Bd(t,e,n={}){let{indent:o=" ",maxPatches:s=2,maxLinesPerSide:r=2,maxContent:i=92}=n;if(!Array.isArray(e)||e.length===0)return"";let a=[];return e.slice(0,s).forEach((c,u)=>{a.push(`${o}${$.subtle}patch ${u+1}${$.reset}`);let l=nc(t,c.old_text,c.new_text,{indent:o+" ",maxLines:r,maxContent:i,includeLabels:!1});l&&a.push(l)}),e.length>s&&a.push(`${o}${$.subtle}\u2026 +${e.length-s} more patches${$.reset}`),a.join(`
21
+ `)}function ub(t){let e=new Set,n=[];for(let o of t){let s=tc(o.fnName).label;e.has(s)||(e.add(s),n.push(s))}return n.length===0?"":n.length<=3?n.join(`${Ie.dim} \u2192 ${Ie.reset}`):`${n.slice(0,3).join(`${Ie.dim} \u2192 ${Ie.reset}`)}${Ie.dim} \u2192 +${n.length-3}${Ie.reset}`}function Gr(t,e=!1,n=null){if(e)return`${$.error}\u23FA${$.reset}`;let o=ob[t]||$.tool_default;if(n==="blink")return`${o}\x1B[5m\u23FA\x1B[25m${$.reset}`;let s=typeof n=="number"?Ld[n%Ld.length]:n!==null?n:"\u23FA";return`${o}${s}${$.reset}`}function db(t,e,n=!1,o=null){let s=(t||[]).filter(u=>u&&u.canExecute!==!1);if(s.length===0)return`${Gr("",n,o)} Step ${e}`;if(s.length===1){let u=s[0],l=u.args||{},d=jd(u.fnName,{...l,path:l._originalPath||l.path});return`${Gr(u.fnName,n,o)} ${Id(u.fnName)} ${Ie.bold}${d}${Ie.reset}`}let r=s[0].fnName,i=ub(s)||`${s.length} tools`,a=s.slice(0,2).map(u=>jd(u.fnName,u.args||{})).filter(Boolean).join(`${Ie.dim} \xB7 ${Ie.reset}`),c=a?` ${$.subtle}\xB7${$.reset} ${Ie.dim}${a}${Ie.reset}`:"";return`${Gr(r,n,o)} ${Id(r)} ${Ie.bold}${i}${Ie.reset}${c}`}function fb(t,e){let n;switch(t){case"write_file":case"edit_file":case"patch_file":case"read_file":case"list_directory":n=e.path||"";break;case"bash":case"ssh_exec":n=(e.command||"").substring(0,44);break;case"grep":case"search_files":n=e.pattern?`"${e.pattern}"${e.path?` in ${e.path}`:""}`:"";break;case"glob":n=e.pattern||"";break;case"web_fetch":n=(e.url||"").substring(0,60);break;case"web_search":n=(e.query||"").substring(0,50);break;default:n=JSON.stringify(e).substring(0,80)}let o=qd[t]||t.replace(/_/g," "),s=n?`(${Ie.dim}${n}${Ie.reset})`:"",r=`${Gr(t)} ${Ie.bold}${o}${Ie.reset}${s}`;if(t==="bash"||t==="ssh_exec"){let i=Fd(e.command,{indent:" ",maxLines:2,maxContent:108});return i?`${r}
22
22
  ${i}`:r}if(t==="edit_file"){let i=nc(e.path,e.old_text,e.new_text,{indent:" ",maxLines:2,maxContent:92});return i?`${r}
23
- ${i}`:r}if(t==="patch_file"){let i=Fd(e.path,e.patches,{indent:" ",maxPatches:2,maxLinesPerSide:1,maxContent:90});return i?`${r}
23
+ ${i}`:r}if(t==="patch_file"){let i=Bd(e.path,e.patches,{indent:" ",maxPatches:2,maxLinesPerSide:1,maxContent:90});return i?`${r}
24
24
  ${i}`:r}return r}function pb(t,e=8){let n=t.split(`
25
25
  `),o=n.slice(0,e),s=n.length-e,r=`${$.muted} \u23BF ${$.reset}`,i=" ",a=o.map((c,u)=>`${u===0?r:i}${$.success}${c}${$.reset}`).join(`
26
26
  `);return s>0&&(a+=`
27
- ${$.subtle} \u2026 +${s} lines${$.reset}`),a}var Kr=["Sampling","Decoding","Attending","Inferring","Generating","Routing","Embedding","Reasoning","Tokenizing","Predicting"],jd=Math.floor(Math.random()*Kr.length),hb=null;function mb(t){hb=t}function gb(){let t=Kr[jd%Kr.length];return jd++,t}function yb(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"Analyzing repository 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 n=e.server&&e.server!=="local"?` [${e.server}]`:"";switch(e.action){case"audit":return`Sysadmin${n}: full audit...`;case"disk_usage":return`Sysadmin${n}: disk usage ${e.path||"/"}...`;case"process_list":return`Sysadmin${n}: top processes (${e.sort_by||"cpu"})...`;case"network_status":return`Sysadmin${n}: network status...`;case"ssl_check":return`Sysadmin${n}: SSL check ${e.domain||e.cert_path||""}...`;case"log_tail":return`Sysadmin${n}: tail ${e.path||"log"}...`;case"find_large":return`Sysadmin${n}: find large files in ${e.path||"/"}...`;case"service":return`Sysadmin${n}: service ${e.service_action||""} ${e.service_name||""}...`;case"kill_process":return`Sysadmin${n}: kill PID ${e.pid||e.process_name||"?"}...`;case"journalctl":return`Sysadmin${n}: journal ${e.unit?`[${e.unit}]`:""}${e.since?` since ${e.since}`:""}...`;case"package":return`Sysadmin${n}: package ${e.package_action||""} ${(e.packages||[]).join(" ")}...`;case"firewall":return`Sysadmin${n}: firewall ${e.firewall_action||""}...`;case"user_manage":return`Sysadmin${n}: user ${e.user_action||""} ${e.user||""}...`;case"cron":return`Sysadmin${n}: cron ${e.cron_action||""}...`;default:return`Sysadmin${n}: ${e.action}...`}}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 wb(t,e,n,o){let s=String(n||""),r=tc(t),i=` ${$.subtle}\u2502${$.reset} ${r.accent}${Ie.bold}${r.label}${$.reset} ${$.subtle}\xB7${$.reset} `;if(o){let u=s.split(`
27
+ ${$.subtle} \u2026 +${s} lines${$.reset}`),a}var Kr=["Sampling","Decoding","Attending","Inferring","Generating","Routing","Embedding","Reasoning","Tokenizing","Predicting"],Dd=Math.floor(Math.random()*Kr.length),hb=null;function mb(t){hb=t}function gb(){let t=Kr[Dd%Kr.length];return Dd++,t}function yb(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"Analyzing repository 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 n=e.server&&e.server!=="local"?` [${e.server}]`:"";switch(e.action){case"audit":return`Sysadmin${n}: full audit...`;case"disk_usage":return`Sysadmin${n}: disk usage ${e.path||"/"}...`;case"process_list":return`Sysadmin${n}: top processes (${e.sort_by||"cpu"})...`;case"network_status":return`Sysadmin${n}: network status...`;case"ssl_check":return`Sysadmin${n}: SSL check ${e.domain||e.cert_path||""}...`;case"log_tail":return`Sysadmin${n}: tail ${e.path||"log"}...`;case"find_large":return`Sysadmin${n}: find large files in ${e.path||"/"}...`;case"service":return`Sysadmin${n}: service ${e.service_action||""} ${e.service_name||""}...`;case"kill_process":return`Sysadmin${n}: kill PID ${e.pid||e.process_name||"?"}...`;case"journalctl":return`Sysadmin${n}: journal ${e.unit?`[${e.unit}]`:""}${e.since?` since ${e.since}`:""}...`;case"package":return`Sysadmin${n}: package ${e.package_action||""} ${(e.packages||[]).join(" ")}...`;case"firewall":return`Sysadmin${n}: firewall ${e.firewall_action||""}...`;case"user_manage":return`Sysadmin${n}: user ${e.user_action||""} ${e.user||""}...`;case"cron":return`Sysadmin${n}: cron ${e.cron_action||""}...`;default:return`Sysadmin${n}: ${e.action}...`}}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 wb(t,e,n,o){let s=String(n||""),r=tc(t),i=` ${$.subtle}\u2502${$.reset} ${r.accent}${Ie.bold}${r.label}${$.reset} ${$.subtle}\xB7${$.reset} `;if(o){let u=s.split(`
28
28
  `)[0];if(u.startsWith("BLOCKED:")){let p=u.replace(/^BLOCKED:\s*/,"").replace(/\s*—.*$/,"").replace(/\s*\(hard cap:.*?\)/,"").trim().substring(0,70);return`${i}${$.muted}blocked: ${p}${$.reset}`}let l=u.replace(/^ERROR:\s*/i,"").substring(0,80),d=s.match(/\nHINT: (.+)/),f=d?`
29
- ${$.muted}${d[1].substring(0,100)}${$.reset}`:"";return`${i}${$.error}${l}${$.reset}${f}`}let a;switch(t){case"read_file":{let u=ab(s),l=u.length,d=u[u.length-1],f=d?parseInt(d.lineNumber||"0"):0,p=e.line_start||e.line_end,h=e.path?Md.basename(e.path):null,g=h?` ${$.muted}from ${h}${$.reset}`:"";p&&f>l?a=`Read lines ${e.line_start||1}\u2013${f}${g}`:a=`Read ${l} line${l!==1?"s":""}${g}`;let w=cb(e.path,u,{maxLines:4,maxContent:120});w&&(a+=`
29
+ ${$.muted}${d[1].substring(0,100)}${$.reset}`:"";return`${i}${$.error}${l}${$.reset}${f}`}let a;switch(t){case"read_file":{let u=ab(s),l=u.length,d=u[u.length-1],f=d?parseInt(d.lineNumber||"0"):0,p=e.line_start||e.line_end,h=e.path?Pd.basename(e.path):null,g=h?` ${$.muted}from ${h}${$.reset}`:"";p&&f>l?a=`Read lines ${e.line_start||1}\u2013${f}${g}`:a=`Read ${l} line${l!==1?"s":""}${g}`;let w=cb(e.path,u,{maxLines:4,maxContent:120});w&&(a+=`
30
30
  ${w}`);break}case"write_file":{let l=(e.content||"").split(`
31
- `).length,d=e.path?Md.basename(e.path):null,f=d?`Wrote ${d} \xB7 ${l} line${l!==1?"s":""}`:`Wrote ${l} line${l!==1?"s":""}`,{highlightLines:p}=Yr(),h=p(e.content||"",e.path||null),g=40,w=8;if(l<=g){let _=h.map(S=>` ${S}`).join(`
31
+ `).length,d=e.path?Pd.basename(e.path):null,f=d?`Wrote ${d} \xB7 ${l} line${l!==1?"s":""}`:`Wrote ${l} line${l!==1?"s":""}`,{highlightLines:p}=Yr(),h=p(e.content||"",e.path||null),g=40,w=8;if(l<=g){let _=h.map(S=>` ${S}`).join(`
32
32
  `);a=`${f}
33
33
  ${_}`}else{let _=h.slice(0,w).map(S=>` ${S}`).join(`
34
34
  `);a=`${f}
@@ -38,10 +38,10 @@ ${_}
38
38
  `),d=u.length,f=l.length,p=e.path?zr(e.path):null,h=p?` ${$.muted}${p}${$.reset}`:"",g=nc(e.path,e.old_text,e.new_text,{indent:" ",maxLines:4,maxContent:96});a=`${$.diff_rem}\u2212${d}${$.reset} ${$.diff_add}+${f}${$.reset}${h}`+(g?`
39
39
  `+g:"");break}case"patch_file":{let u=e.patches||[],l=u.reduce((g,w)=>g+(w.old_text||"").split(`
40
40
  `).length,0),d=u.reduce((g,w)=>g+(w.new_text||"").split(`
41
- `).length,0),f=e.path?zr(e.path):null,p=f?` ${$.muted}${f}${$.reset}`:"";a=`${u.length} patch${u.length!==1?"es":""} ${$.diff_rem}\u2212${l}${$.reset} ${$.diff_add}+${d}${$.reset}${p}`;let h=Fd(e.path,u,{indent:" ",maxPatches:3,maxLinesPerSide:2,maxContent:92});h&&(a+=`
41
+ `).length,0),f=e.path?zr(e.path):null,p=f?` ${$.muted}${f}${$.reset}`:"";a=`${u.length} patch${u.length!==1?"es":""} ${$.diff_rem}\u2212${l}${$.reset} ${$.diff_add}+${d}${$.reset}${p}`;let h=Bd(e.path,u,{indent:" ",maxPatches:3,maxLinesPerSide:2,maxContent:92});h&&(a+=`
42
42
  ${h}`);break}case"bash":{let l=s.match(/^EXIT (\d+)/),d=s.split(`
43
43
  `).filter(g=>g&&!g.startsWith("EXIT ")&&!g.startsWith("HINT:")&&g.trim()),f=l?l[1]==="0"?`${$.success}\u2713${$.reset}`:`${$.error}\u2717 Exit ${l[1]}${$.reset}`:`${$.success}\u2713${$.reset}`,p=s.match(/\nHINT: (.+)/);if(p)a=`${f} ${$.muted}\u2014 ${p[1].substring(0,100)}${$.reset}`;else if(d.length===0)a=f;else{let g=l&&l[1]!=="0",w=g?d.slice(-3):d.slice(0,3),_=d.length-3,S=w.map((A,E)=>E===0?`${f} ${$.muted}${A.substring(0,120)}${$.reset}`:` ${$.muted}${A.substring(0,120)}${$.reset}`);if(_>0){let A=g?` ${$.subtle}${_} lines above\u2026${$.reset}`:` ${$.subtle}\u2026 +${_} lines${$.reset}`;g?S.unshift(A):S.push(A)}a=S.join(`
44
- `)}let h=qd(e.command,{indent:" ",maxLines:2,maxContent:108});h&&(a=`${h}
44
+ `)}let h=Fd(e.command,{indent:" ",maxLines:2,maxContent:108});h&&(a=`${h}
45
45
  ${a}`);break}case"grep":case"search_files":{if(s.includes("(no matches)")||s==="no matches")a=`No matches${e.pattern?` ${$.muted}"${String(e.pattern).substring(0,40)}"${$.reset}`:""}`;else{let w=function(E){let v=E.indexOf(":");if(v===-1)return`${$.muted}${E.substring(0,90)}${$.reset}`;let N=E.substring(0,v),ne=E.substring(v+1),oe=ne.match(/^(\d+)[:-](.*)/s),ue=oe?`:${oe[1]}`:"",fe=(oe?oe[2]:ne).trim(),ie=`${$.subtle}${u.basename(N)}${ue}${$.reset}`,le=`${$.muted}${fe.substring(0,80)}${fe.length>80?"\u2026":""}${$.reset}`;return`${ie} ${le}`};var c=w;let u=require("path"),l=s.split(`
46
46
  `).filter(Boolean),d=l.length,p=new Set(l.map(E=>E.split(":")[0]).filter(Boolean)).size,h=e.pattern?` ${$.muted}"${String(e.pattern).substring(0,40)}"${$.reset}`:"",g=p>1?`${d} match${d!==1?"es":""} in ${p} files${h}`:`${d} match${d!==1?"es":""}${h}`,_=e.path?`
47
47
  ${$.subtle}path:${$.reset} ${$.muted}${String(e.path).substring(0,70)}${$.reset}`:"",S=l.slice(0,5).map((E,v)=>v===0?`${g}${_}
@@ -61,22 +61,22 @@ ${g.join(`
61
61
  `).filter(p=>p.trim()&&!p.startsWith("EXIT ")),f=l?`${$.error}\u2717${$.reset}`:`${$.success}\u2713${$.reset}`;if(d.length===0)a=f;else{if(d.length>2&&d.every(_=>/^\[/.test(_.trim()))){a=`${f} ${d.length} log lines`;break}let h=l?d.slice(-3):d.slice(0,3),g=d.length-3,w=h.map((_,S)=>S===0?`${f} ${$.muted}${_.substring(0,120)}${$.reset}`:` ${$.muted}${_.substring(0,120)}${$.reset}`);if(g>0){let _=l?` ${$.subtle}${g} lines above\u2026${$.reset}`:` ${$.subtle}\u2026 +${g} lines${$.reset}`;l?w.unshift(_):w.push(_)}a=w.join(`
62
62
  `)}break}default:{let u=s.split(`
63
63
  `).filter(l=>l.trim()&&!l.startsWith("EXIT ")&&!l.startsWith("HINT:"));if(u.length>0){let l=u[0].trim().substring(0,90),d=u.length>1?` ${$.subtle}\u2026 +${u.length-1} lines${$.reset}`:"";a=`${$.muted}${l}${$.reset}${d}`}else a=`${r.label} complete`}}return`${i}${a}${$.reset}`}function bb(t,e,n,o,s,r){let i=Math.round(o/1e3),a=i>=60?`${Math.floor(i/60)}m ${i%60}s`:`${i}s`,c=`
64
- ${$.success}\u25C6${Ie.reset} ${Ie.bold}${t}${Ie.reset}`;return c+=` ${$.subtle}\u2501\u2501${$.reset} ${Ie.dim}${a}`,r.size>0&&(c+=` \xB7 ${r.size} file${r.size!==1?"s":""} modified`),s.size>0&&(c+=` \xB7 ${s.size} scanned`),c+=Ie.reset,c}Bd.exports={C:Ie,formatToolCall:fb,formatResult:pb,getToolSpinnerText:yb,formatToolSummary:wb,formatSectionHeader:db,formatMilestone:bb,getThinkingVerb:gb,setActiveModelForSpinner:mb,THINKING_VERBS:Kr}});var rt=Q((dA,Hd)=>{var{T:rn}=Kt(),sc=rn,$b=require("path"),Wd=["01100110","01111110","01111110","01011010","01111110","00111100"];function _b(t,e){let n=[];for(let o=0;o<t.length;o+=2){let s="";for(let r=0;r<t[0].length;r++){let i=t[o][r]==="1",a=o+1<t.length&&t[o+1][r]==="1";i&&a?s+=`${e}\u2588\x1B[0m`:i&&!a?s+=`${e}\u2580\x1B[0m`:!i&&a?s+=`${e}\u2584\x1B[0m`:s+=" "}n.push(s)}return n}function xb(t,e,n={}){let o=sc.bold,s=sc.reset,r=_b(Wd,rn.banner_logo),i=n.yolo?` ${o}${rn.banner_yolo}\u26A1 YOLO${s}`:"",a=n.gemini?` ${o}${rn.banner_gemini}\u2726 GEMINI${s}`:"",c=Ur().version,u=e?$b.basename(e):null,l=`${rn.banner_model}[${t||"model"}]${s}`,d=`${rn.banner_version}[${u||"workspace"}]${s}`,f=[` ${rn.banner_name}${o}nex-code${s} ${rn.banner_version}v${c}${s}`,` ${l} ${d}`,` ${rn.banner_logo}${o}terminal workbench${s} ${rn.muted}\xB7 /help${s}${a}${i}`,""],p=Math.max(r.length,f.length),h=Math.floor((p-r.length)/2),g=Math.floor((p-f.length)/2),w=Wd[0].length,_=[];for(let S=0;S<p;S++){let A=r[S-h]??" ".repeat(w),E=f[S-g]??"";_.push(A+E)}console.log(`
64
+ ${$.success}\u25C6${Ie.reset} ${Ie.bold}${t}${Ie.reset}`;return c+=` ${$.subtle}\u2501\u2501${$.reset} ${Ie.dim}${a}`,r.size>0&&(c+=` \xB7 ${r.size} file${r.size!==1?"s":""} modified`),s.size>0&&(c+=` \xB7 ${s.size} scanned`),c+=Ie.reset,c}Ud.exports={C:Ie,formatToolCall:fb,formatResult:pb,getToolSpinnerText:yb,formatToolSummary:wb,formatSectionHeader:db,formatMilestone:bb,getThinkingVerb:gb,setActiveModelForSpinner:mb,THINKING_VERBS:Kr}});var rt=Q((fA,Yd)=>{var{T:rn}=Kt(),sc=rn,$b=require("path"),Hd=["01100110","01111110","01111110","01011010","01111110","00111100"];function _b(t,e){let n=[];for(let o=0;o<t.length;o+=2){let s="";for(let r=0;r<t[0].length;r++){let i=t[o][r]==="1",a=o+1<t.length&&t[o+1][r]==="1";i&&a?s+=`${e}\u2588\x1B[0m`:i&&!a?s+=`${e}\u2580\x1B[0m`:!i&&a?s+=`${e}\u2584\x1B[0m`:s+=" "}n.push(s)}return n}function xb(t,e,n={}){let o=sc.bold,s=sc.reset,r=_b(Hd,rn.banner_logo),i=n.yolo?` ${o}${rn.banner_yolo}\u26A1 YOLO${s}`:"",a=n.gemini?` ${o}${rn.banner_gemini}\u2726 GEMINI${s}`:"",c=Ur().version,u=e?$b.basename(e):null,l=`${rn.banner_model}[${t||"model"}]${s}`,d=`${rn.banner_version}[${u||"workspace"}]${s}`,f=[` ${rn.banner_name}${o}nex-code${s} ${rn.banner_version}v${c}${s}`,` ${l} ${d}`,` ${rn.banner_logo}${o}terminal workbench${s} ${rn.muted}\xB7 /help${s}${a}${i}`,""],p=Math.max(r.length,f.length),h=Math.floor((p-r.length)/2),g=Math.floor((p-f.length)/2),w=Hd[0].length,_=[];for(let S=0;S<p;S++){let A=r[S-h]??" ".repeat(w),E=f[S-g]??"";_.push(A+E)}console.log(`
65
65
  `+_.join(`
66
66
  `)+`
67
- `)}var{Spinner:kb,MultiProgress:vb,TaskProgress:Sb,ToolProgress:Eb,setActiveTaskProgress:Tb,getActiveTaskProgress:Rb,cleanupTerminal:Cb}=Yn(),{formatToolCall:Ab,formatResult:Ob,getToolSpinnerText:Nb,formatToolSummary:Mb,formatSectionHeader:Pb,formatMilestone:Lb,getThinkingVerb:Ib,setActiveModelForSpinner:jb}=Ud();Hd.exports={C:sc,banner:xb,Spinner:kb,MultiProgress:vb,TaskProgress:Sb,ToolProgress:Eb,setActiveTaskProgress:Tb,getActiveTaskProgress:Rb,cleanupTerminal:Cb,formatToolCall:Ab,formatResult:Ob,getToolSpinnerText:Nb,formatToolSummary:Mb,formatSectionHeader:Pb,formatMilestone:Lb,getThinkingVerb:Ib,setActiveModelForSpinner:jb}});var Bs=Q((fA,Yd)=>{async function Db(t,e){if(!t.response?.data)return t.message;let n=t.response.data;if(typeof n=="object"&&n!==null&&typeof n.pipe!="function")return e(n)||t.message;try{let o=await new Promise((r,i)=>{let a=[];n.on("data",c=>a.push(c)),n.on("end",()=>r(Buffer.concat(a).toString("utf8"))),n.on("error",i)}),s=JSON.parse(o);return e(s)||o||t.message}catch{return t.message}}var oc=class t{constructor(e={}){if(new.target===t)throw new Error("BaseProvider is abstract \u2014 use a concrete provider");this.name=e.name||"unknown",this.baseUrl=e.baseUrl||"",this.models=e.models||{},this.defaultModel=e.defaultModel||null}isConfigured(){throw new Error(`${this.name}: isConfigured() not implemented`)}getApiKey(){return null}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}getModel(e){return this.models[e]||null}async chat(e,n,o={}){throw new Error(`${this.name}: chat() not implemented`)}async stream(e,n,o={}){throw new Error(`${this.name}: stream() not implemented`)}formatMessages(e){return{messages:e}}formatTools(e){return e}normalizeResponse(e){throw new Error(`${this.name}: normalizeResponse() not implemented`)}};Yd.exports={BaseProvider:oc,readStreamErrorBody:Db}});var Hs=Q((pA,zd)=>{var Us=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,n={}){throw new Error("createStreamParser() not implemented")}},Ws=class{constructor(e,n={}){this.onToken=e,this.callbacks=n,this.content="",this.buffer=""}feed(e){this.buffer+=e;let n=this.buffer.split(`
68
- `);this.buffer=n.pop()||"";for(let o of n){let s=this.parseLine(o);if(s?.done)return s}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")}},Xr=class extends Ws{constructor(e,n={}){super(e,n),this.toolCallsMap={}}parseLine(e){let n=e.trim();if(!n||!n.startsWith("data: "))return{done:!1};let o=n.slice(6);if(o==="[DONE]")return{done:!0,result:this.getResult()};let s;try{s=JSON.parse(o)}catch{return{done:!1}}let r=s.choices?.[0]?.delta;if(!r)return{done:!1};if(r.content&&(this.onToken(r.content),this.content+=r.content),r.tool_calls)for(let i of r.tool_calls){let a;i.index!==void 0&&i.index!==null?a=i.index:i.id?a=`id:${i.id}`:a=0,this.toolCallsMap[a]||(this.toolCallsMap[a]={id:i.id||"",name:"",arguments:""}),i.id&&(this.toolCallsMap[a].id=i.id),i.function?.name&&(this.toolCallsMap[a].name+=i.function.name),i.function?.arguments&&(this.toolCallsMap[a].arguments+=i.function.arguments)}return{done:!1}}getResult(){return{content:this.content,tool_calls:Object.values(this.toolCallsMap).filter(e=>e.name).map(e=>({id:e.id||`call-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,function:{name:e.name,arguments:e.arguments}}))}}},Vr=class extends Us{getEndpoint(){return"/chat/completions"}buildRequestBody({model:e,messages:n,tools:o,maxTokens:s,temperature:r,stream:i}){let a={model:e,messages:n,max_tokens:s,temperature:r};return i&&(a.stream=!0),o&&o.length>0&&(a.tools=o),a}normalizeResponse(e){let n=e.choices?.[0]?.message||{},o=(n.tool_calls||[]).map(s=>({id:s.id,function:{name:s.function.name,arguments:s.function.arguments}}));return{content:n.content||"",tool_calls:o}}createStreamParser(e,n={}){return new Xr(e,n)}},Jr=class extends Ws{constructor(e,n={}){super(e,n),this.toolUses=[],this.currentToolIndex=-1}parseLine(e){let n=e.trim();if(!n.startsWith("data: "))return{done:!1};let o=n.slice(6),s;try{s=JSON.parse(o)}catch{return{done:!1}}switch(s.type){case"content_block_start":{let r=s.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=s.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 n={};if(e.inputJson)try{n=JSON.parse(e.inputJson)}catch{n=e.inputJson}return{id:e.id||`anthropic-${Date.now()}`,function:{name:e.name,arguments:n}}})}}},rc="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->",Zr=class extends Us{getEndpoint(){return"/messages"}buildRequestBody({model:e,messages:n,tools:o,maxTokens:s,temperature:r,stream:i,extra:a}){let c={model:e,messages:n,max_tokens:s,temperature:r};if(i&&(c.stream=!0),a?.system){let u=a.system,l=u.indexOf(rc);if(l!==-1){let d=u.slice(0,l).trimEnd(),f=u.slice(l+rc.length).trimStart();c.system=[{type:"text",text:d},{type:"text",text:f,cache_control:{type:"ephemeral"}}]}else c.system=u}return o&&o.length>0&&(c.tools=o),c}formatTools(e){return!e||e.length===0?[]:e.map(n=>({name:n.function.name,description:n.function.description||"",input_schema:n.function.parameters||{type:"object",properties:{}}}))}normalizeResponse(e){let n="",o=[];for(let s of e.content||[])s.type==="text"?n+=s.text:s.type==="tool_use"&&o.push({id:s.id,function:{name:s.name,arguments:s.input}});return{content:n,tool_calls:o}}createStreamParser(e,n={}){return new Jr(e,n)}};function Gd(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 Qr=class extends Ws{constructor(e,n={}){super(e,n),this.toolCalls=[],this.onThinkingToken=n.onThinkingToken||(()=>{})}parseLine(e){if(!e.trim())return{done:!1};let n;try{n=JSON.parse(e)}catch{return{done:!1}}return n.message?.thinking&&this.onThinkingToken(n.message.thinking),n.message?.content&&(this.onToken(n.message.content),this.content+=n.message.content),n.message?.tool_calls&&(this.toolCalls=this.toolCalls.concat(n.message.tool_calls)),n.done?{done:!0,result:this.getResult()}:{done:!1}}getResult(){return{content:this.content,tool_calls:this.toolCalls.map((e,n)=>({id:e.id||`ollama-${Date.now()}-${n}`,function:{name:e.function?.name||e.name||"unknown",arguments:Gd(e.function?.arguments??e.arguments)}}))}}},ei=class extends Us{getEndpoint(){return"/api/chat"}buildRequestBody({model:e,messages:n,tools:o,maxTokens:s,temperature:r,stream:i,extra:a}){let c={model:e,messages:n,stream:i,options:{temperature:r,num_predict:s,repeat_penalty:a?.repeat_penalty??1.05}};return o&&o.length>0&&(c.tools=o),c}normalizeResponse(e){let n=e.message||{};return{content:n.content||"",tool_calls:(n.tool_calls||[]).map((o,s)=>({id:o.id||`ollama-${Date.now()}-${s}`,function:{name:o.function?.name||o.name||"unknown",arguments:Gd(o.function?.arguments??o.arguments)}}))}}createStreamParser(e,n={}){return new Qr(e,n)}},qb=new Vr,Fb=new Zr,Bb=new ei;zd.exports={ANTHROPIC_CACHE_BOUNDARY:rc,WireProtocol:Us,StreamParser:Ws,OpenAICompatibleProtocol:Vr,AnthropicProtocol:Zr,OllamaChatProtocol:ei,OpenAIStreamParser:Xr,AnthropicStreamParser:Jr,OllamaStreamParser:Qr,openaiProtocol:qb,anthropicProtocol:Fb,ollamaProtocol:Bb}});var Vd=Q((hA,Xd)=>{var ti=require("axios"),Ub=require("http"),Wb=require("https"),{BaseProvider:Hb,readStreamErrorBody:Yb}=Bs(),{ollamaProtocol:zn}=Hs(),ni=new Ub.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),si=new Wb.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Kd={"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}},ic=class extends Hb{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||Kd,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){ti.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:ni,httpsAgent:si}).then(e=>{let n=e.data?.models||[];for(let o of n){let s=(o.name||o.model||"").replace(/:latest$/,"");!s||this.models[s]||(this.models[s]={id:s,name:o.name||s,maxTokens:16384,contextWindow:131072})}}).catch(()=>{});return}try{let n=(await ti.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:ni,httpsAgent:si})).data?.models||[];for(let o of n){let s=(o.name||o.model||"").replace(/:latest$/,"");!s||this.models[s]||(this.models[s]={id:s,name:o.name||s,maxTokens:16384,contextWindow:131072})}}catch{}}}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OLLAMA_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OLLAMA_API_KEY not set");return{Authorization:`Bearer ${e}`}}_formatMessages(e){return e.map(n=>{if(Array.isArray(n.content)){let o=[],s=[];for(let i of n.content)i.type==="text"?o.push(i.text??""):i.type==="image"&&i.data&&s.push(i.data);let r={role:n.role,content:o.join(`
69
- `)};return s.length>0&&(r.images=s),n.tool_call_id&&(r.tool_call_id=n.tool_call_id),r}return n})}async chat(e,n,o={}){await this.discoverModels();let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||16384,a=zn.buildRequestBody({model:s,messages:this._formatMessages(e),tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!1,extra:{repeat_penalty:o.repeat_penalty}}),c;try{c=await ti.post(`${this.baseUrl}${zn.getEndpoint()}`,a,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),httpAgent:ni,httpsAgent:si})}catch(u){if(u.name==="CanceledError"||u.name==="AbortError"||u.code==="ERR_CANCELED")throw u;let l=u.response?.status?` [HTTP ${u.response.status}]`:"",d=u.response?.data?.error||u.message;throw new Error(`API Error${l}: ${d}`)}return zn.normalizeResponse(c.data)}async stream(e,n,o={}){await this.discoverModels();let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||16384,a=o.onToken||(()=>{}),c=o.onThinkingToken||(()=>{}),u=zn.buildRequestBody({model:s,messages:this._formatMessages(e),tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!0,extra:{repeat_penalty:o.repeat_penalty}}),l;try{l=await ti.post(`${this.baseUrl}${zn.getEndpoint()}`,u,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal,httpAgent:ni,httpsAgent:si})}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 Yb(f,w=>w?.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=zn.createStreamParser(a,{onThinkingToken:c});return new Promise((f,p)=>{o.signal&&o.signal.addEventListener("abort",()=>{l.data.destroy(),p(new DOMException("The operation was aborted","AbortError"))},{once:!0}),l.data.on("data",h=>{let{done:g,result:w}=d.feed(h.toString());g&&f(w)}),l.data.on("error",h=>{if(o.signal?.aborted)return;let g=new Error(`Stream error: ${h.message}`);g.code=h.code||h.name,p(g)}),l.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return zn.normalizeResponse(e)}};Xd.exports={OllamaProvider:ic,OLLAMA_MODELS:Kd}});var ef=Q((mA,Qd)=>{var Jd=require("axios"),{BaseProvider:Gb,readStreamErrorBody:zb}=Bs(),{openaiProtocol:Kn}=Hs(),Zd={"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}},ac=class extends Gb{constructor(e={}){super({name:"openai",baseUrl:e.baseUrl||"https://api.openai.com/v1",models:e.models||Zd,defaultModel:e.defaultModel||"gpt-4o",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OPENAI_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OPENAI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let n=[];for(let o of e){if(this._messageFormatCache.has(o)){n.push(this._messageFormatCache.get(o));continue}let s=this._getMessageCacheKey(o);if(this._messageStringCache.has(s)){let i=this._messageStringCache.get(s);this._messageFormatCache.set(o,i),n.push(i);continue}let r=this._formatSingleMessage(o);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(s,r),this._messageFormatCache.set(o,r),n.push(r)}return{messages:n}}_getMessageCacheKey(e){let n=e.role||"",o=typeof e.content=="string"?e.content.substring(0,100):"",s=e.tool_calls?e.tool_calls.length:0;return`${n}:${o.length}:${s}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||null,tool_calls:e.tool_calls.map(n=>({id:n.id||`call-${Date.now()}`,type:"function",function:{name:n.function.name,arguments:typeof n.function.arguments=="string"?n.function.arguments:JSON.stringify(n.function.arguments)}}))};if(e.role==="tool"){let n;return Array.isArray(e.content)?n=e.content.filter(s=>s.type==="text").map(s=>s.text).join(`
70
- `)||JSON.stringify(e.content):n=typeof e.content=="string"?e.content:JSON.stringify(e.content),{role:"tool",content:n,tool_call_id:e.tool_call_id}}if(e.role==="user"&&Array.isArray(e.content)){let n=[];for(let o of e.content)if(o.type==="text")n.push({type:"text",text:o.text??""});else if(o.type==="image"&&o.data){let s=o.data.startsWith("data:")?o.data:`data:${o.media_type||"image/png"};base64,${o.data}`;n.push({type:"image_url",image_url:{url:s,detail:"auto"}})}return{role:"user",content:n}}return{role:e.role,content:e.content}}async chat(e,n,o={}){let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||16384,{messages:a}=this.formatMessages(e),c=Kn.buildRequestBody({model:s,messages:a,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!1}),u;try{u=await Jd.post(`${this.baseUrl}${Kn.getEndpoint()}`,c,{timeout:o.timeout||this.timeout,headers:this._getHeaders()})}catch(l){if(l.name==="CanceledError"||l.name==="AbortError"||l.code==="ERR_CANCELED")throw l;let d=l.response?.status?` [HTTP ${l.response.status}]`:"",f=l.response?.data?.error?.message||l.response?.data?.error||l.message;throw new Error(`API Error${d}: ${f}`)}return Kn.normalizeResponse(u.data)}async stream(e,n,o={}){let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||16384,a=o.onToken||(()=>{}),{messages:c}=this.formatMessages(e),u=Kn.buildRequestBody({model:s,messages:c,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!0}),l;try{l=await Jd.post(`${this.baseUrl}${Kn.getEndpoint()}`,u,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let p=f.response?.status?` [HTTP ${f.response.status}]`:"",h=await zb(f,g=>g?.error?.message||g?.error);throw new Error(`API Error${p}: ${h}`)}let d=Kn.createStreamParser(a);return new Promise((f,p)=>{o.signal&&o.signal.addEventListener("abort",()=>{l.data.destroy(),p(new DOMException("The operation was aborted","AbortError"))},{once:!0}),l.data.on("data",h=>{let{done:g,result:w}=d.feed(h.toString());g&&f(w)}),l.data.on("error",h=>{o.signal?.aborted||p(new Error(`Stream error: ${h.message}`))}),l.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return Kn.normalizeResponse(e)}};Qd.exports={OpenAIProvider:ac,OPENAI_MODELS:Zd}});var of=Q((gA,sf)=>{var tf=require("axios"),{BaseProvider:Kb,readStreamErrorBody:Xb}=Bs(),{anthropicProtocol:Nn}=Hs(),nf={"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}},Vb="2023-06-01",cc=class extends Kb{constructor(e={}){super({name:"anthropic",baseUrl:e.baseUrl||"https://api.anthropic.com/v1",models:e.models||nf,defaultModel:e.defaultModel||"claude-sonnet",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this.apiVersion=e.apiVersion||Vb}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.ANTHROPIC_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("ANTHROPIC_API_KEY not set");return{"x-api-key":e,"anthropic-version":this.apiVersion,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let n="",o=[];for(let s of e){if(s.role==="system"){n+=(n?`
71
-
72
- `:"")+s.content;continue}if(s.role!=="system"&&s.role!=="tool"&&this._messageFormatCache.has(s)){o.push(this._messageFormatCache.get(s));continue}let r=this._formatSingleMessage(s,o);if(r){if(s.role!=="system"&&s.role!=="tool"&&this._messageStringCache.size<this._maxCacheSize){let i=this._getMessageCacheKey(s);this._messageStringCache.set(i,r),this._messageFormatCache.set(s,r)}o.push(r)}}for(let s=o.length-1;s>0;s--)o[s].role==="user"&&o[s-1].role==="user"&&o.splice(s,0,{role:"assistant",content:[{type:"text",text:"[continuing]"}]});return{messages:o,system:n}}_getMessageCacheKey(e){let n=e.role||"",o=typeof e.content=="string"?e.content.substring(0,100):"",s=e.tool_calls?e.tool_calls.length:0;return`${n}:${o.length}:${s}`}_formatSingleMessage(e,n=[]){if(e.role==="assistant"){let o=[];if(e.content&&o.push({type:"text",text:e.content}),e.tool_calls)for(let s of e.tool_calls)o.push({type:"tool_use",id:s.id||`toolu-${Date.now()}`,name:s.function.name,input:typeof s.function.arguments=="string"?JSON.parse(s.function.arguments||"{}"):s.function.arguments||{}});return{role:"assistant",content:o.length>0?o:[{type:"text",text:""}]}}if(e.role==="tool"){let o=n[n.length-1],s;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}});s=i}else s=typeof e.content=="string"?e.content:JSON.stringify(e.content);let r={type:"tool_result",tool_use_id:e.tool_call_id,content:s};return o&&o.role==="user"&&Array.isArray(o.content)&&o.content[0]?.type==="tool_result"?(o.content.push(r),null):{role:"user",content:[r]}}if(Array.isArray(e.content)){let o=[];for(let s of e.content)s.type==="text"?o.push({type:"text",text:s.text??""}):s.type==="image"&&s.data&&o.push({type:"image",source:{type:"base64",media_type:s.media_type||"image/png",data:s.data}});return{role:"user",content:o}}return{role:"user",content:e.content}}formatTools(e){return Nn.formatTools(e)}_resolveModelId(e){return this.getModel(e)?.id||e}async chat(e,n,o={}){let s=o.model||this.defaultModel,r=this._resolveModelId(s),i=this.getModel(s),a=o.maxTokens||i?.maxTokens||8192,{messages:c,system:u}=this.formatMessages(e),l=this.formatTools(n),d=Nn.buildRequestBody({model:r,messages:c,tools:l,maxTokens:a,temperature:o.temperature??this.temperature,stream:!1,extra:{system:u}}),f;try{f=await tf.post(`${this.baseUrl}${Nn.getEndpoint()}`,d,{timeout:o.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 Nn.normalizeResponse(f.data)}async stream(e,n,o={}){let s=o.model||this.defaultModel,r=this._resolveModelId(s),i=this.getModel(s),a=o.maxTokens||i?.maxTokens||8192,c=o.onToken||(()=>{}),{messages:u,system:l}=this.formatMessages(e),d=this.formatTools(n),f=Nn.buildRequestBody({model:r,messages:u,tools:d,maxTokens:a,temperature:o.temperature??this.temperature,stream:!0,extra:{system:l}}),p;try{p=await tf.post(`${this.baseUrl}${Nn.getEndpoint()}`,f,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal})}catch(g){if(g.name==="CanceledError"||g.name==="AbortError"||g.code==="ERR_CANCELED")throw g;let w=g.response?.status?` [HTTP ${g.response.status}]`:"",_=await Xb(g,S=>S?.error?.message||S?.error);throw new Error(`API Error${w}: ${_}`)}let h=Nn.createStreamParser(c);return new Promise((g,w)=>{o.signal&&o.signal.addEventListener("abort",()=>{p.data.destroy(),w(new DOMException("The operation was aborted","AbortError"))},{once:!0}),p.data.on("data",_=>{let{done:S,result:A}=h.feed(_.toString());S&&g(A)}),p.data.on("error",_=>{o.signal?.aborted||w(new Error(`Stream error: ${_.message}`))}),p.data.on("end",()=>{g(h.flush())})})}normalizeResponse(e){return Nn.normalizeResponse(e)}};sf.exports={AnthropicProvider:cc,ANTHROPIC_MODELS:nf}});var lf=Q((yA,cf)=>{var rf=require("axios"),{BaseProvider:Jb,readStreamErrorBody:Zb}=Bs(),{openaiProtocol:Xn}=Hs(),af={"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}},lc=class extends Jb{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||af,defaultModel:e.defaultModel||"gemini-2.5-flash",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("GEMINI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let n=[];for(let o of e){if(this._messageFormatCache.has(o)){n.push(this._messageFormatCache.get(o));continue}let s=this._getMessageCacheKey(o);if(this._messageStringCache.has(s)){let i=this._messageStringCache.get(s);this._messageFormatCache.set(o,i),n.push(i);continue}let r=this._formatSingleMessage(o);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(s,r),this._messageFormatCache.set(o,r),n.push(r)}return{messages:n}}_getMessageCacheKey(e){let n=e.role||"",o=typeof e.content=="string"?e.content.substring(0,100):"",s=e.tool_calls?e.tool_calls.length:0;return`${n}:${o.length}:${s}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||"",tool_calls:e.tool_calls.map(n=>({id:n.id||`call-${Date.now()}`,type:"function",function:{name:n.function.name,arguments:typeof n.function.arguments=="string"?n.function.arguments:JSON.stringify(n.function.arguments)}}))};if(e.role==="tool")return{role:"tool",content:typeof e.content=="string"?e.content:JSON.stringify(e.content),tool_call_id:e.tool_call_id};if(e.role==="user"&&Array.isArray(e.content)){let n=[];for(let o of e.content)if(o.type==="text")n.push({type:"text",text:o.text??""});else if(o.type==="image"&&o.data){let s=o.data.startsWith("data:")?o.data:`data:${o.media_type||"image/png"};base64,${o.data}`;n.push({type:"image_url",image_url:{url:s,detail:"auto"}})}return{role:"user",content:n}}return{role:e.role,content:e.content}}async chat(e,n,o={}){let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||8192,{messages:a}=this.formatMessages(e),c=Xn.buildRequestBody({model:s,messages:a,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!1}),u;try{u=await rf.post(`${this.baseUrl}${Xn.getEndpoint()}`,c,{timeout:o.timeout||this.timeout,headers:this._getHeaders()})}catch(l){if(l.name==="CanceledError"||l.name==="AbortError"||l.code==="ERR_CANCELED")throw l;let d=l.response?.status?` [HTTP ${l.response.status}]`:"",f=l.response?.data?.error?.message||l.response?.data?.error||l.message;throw new Error(`API Error${d}: ${f}`)}return Xn.normalizeResponse(u.data)}async stream(e,n,o={}){let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||8192,a=o.onToken||(()=>{}),{messages:c}=this.formatMessages(e),u=Xn.buildRequestBody({model:s,messages:c,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!0}),l;try{l=await rf.post(`${this.baseUrl}${Xn.getEndpoint()}`,u,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let p=f.response?.status?` [HTTP ${f.response.status}]`:"",h=await Zb(f,g=>g?.error?.message||g?.error);throw new Error(`API Error${p}: ${h}`)}let d=Xn.createStreamParser(a);return new Promise((f,p)=>{o.signal&&o.signal.addEventListener("abort",()=>{l.data.destroy(),p(new DOMException("The operation was aborted","AbortError"))},{once:!0}),l.data.on("data",h=>{let{done:g,result:w}=d.feed(h.toString());g&&f(w)}),l.data.on("error",h=>{o.signal?.aborted||p(new Error(`Stream error: ${h.message}`))}),l.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return Xn.normalizeResponse(e)}};cf.exports={GeminiProvider:lc,GEMINI_MODELS:af}});var ff=Q((wA,df)=>{var oi=require("axios"),{BaseProvider:Qb,readStreamErrorBody:e$}=Bs(),{ollamaProtocol:Vn}=Hs(),uf="http://localhost:11434",uc=class extends Qb{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||uf,models:e.models||{},defaultModel:e.defaultModel||null,...e}),this.timeout=e.timeout||3e5,this.temperature=e.temperature??.2,this._modelsLoaded=!1}isConfigured(){return!0}async loadModels(){if(this._modelsLoaded)return this.models;try{let n=(await oi.get(`${this.baseUrl}/api/tags`,{timeout:5e3})).data?.models||[];this.models={};for(let o of n){let s=o.name||o.model;if(!s)continue;let r=s.replace(/:latest$/,""),i=32768;try{let a=await oi.post(`${this.baseUrl}/api/show`,{name:s},{timeout:5e3}),c=a.data?.model_info||a.data?.details||{};i=c["general.context_length"]||c["llama.context_length"]||this._parseContextFromModelfile(a.data?.modelfile)||32768}catch{}this.models[r]={id:r,name:o.name,maxTokens:Math.min(8192,Math.floor(i*.1)),contextWindow:i}}!this.defaultModel&&Object.keys(this.models).length>0&&(this.defaultModel=Object.keys(this.models)[0]),this._modelsLoaded=!0}catch{this.models={},this._modelsLoaded=!1}return this.models}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}_formatMessages(e){return e.map(n=>{if(n.role==="user"&&Array.isArray(n.content)){let o=[],s=[];for(let i of n.content)i.type==="text"?o.push(i.text??""):i.type==="image"&&i.data&&s.push(i.data);let r={role:"user",content:o.join(`
73
- `)};return s.length>0&&(r.images=s),r}return n})}async chat(e,n,o={}){this._modelsLoaded||await this.loadModels();let s=o.model||this.defaultModel;if(!s)throw new Error("No local model available. Is Ollama running?");let r=Vn.buildRequestBody({model:s,messages:this._formatMessages(e),tools:n,maxTokens:o.maxTokens||8192,temperature:o.temperature??this.temperature,stream:!1}),i;try{i=await oi.post(`${this.baseUrl}${Vn.getEndpoint()}`,r,{timeout:o.timeout||this.timeout})}catch(a){if(a.name==="CanceledError"||a.name==="AbortError"||a.code==="ERR_CANCELED")throw a;let c=a.response?.status?` [HTTP ${a.response.status}]`:"",u=a.response?.data?.error||a.message;throw new Error(`API Error${c}: ${u}`)}return Vn.normalizeResponse(i.data)}async stream(e,n,o={}){this._modelsLoaded||await this.loadModels();let s=o.model||this.defaultModel;if(!s)throw new Error("No local model available. Is Ollama running?");let r=o.onToken||(()=>{}),i=Vn.buildRequestBody({model:s,messages:this._formatMessages(e),tools:n,maxTokens:o.maxTokens||8192,temperature:o.temperature??this.temperature,stream:!0}),a;try{a=await oi.post(`${this.baseUrl}${Vn.getEndpoint()}`,i,{timeout:o.timeout||this.timeout,responseType:"stream",signal:o.signal})}catch(u){if(u.name==="CanceledError"||u.name==="AbortError"||u.code==="ERR_CANCELED")throw u;let l=u.response?.status?` [HTTP ${u.response.status}]`:"",d=await e$(u,f=>f?.error);throw new Error(`API Error${l}: ${d}`)}let c=Vn.createStreamParser(r);return new Promise((u,l)=>{o.signal&&o.signal.addEventListener("abort",()=>{a.data.destroy(),l(new DOMException("The operation was aborted","AbortError"))},{once:!0}),a.data.on("data",d=>{let{done:f,result:p}=c.feed(d.toString());f&&u(p)}),a.data.on("error",d=>{o.signal?.aborted||l(new Error(`Stream error: ${d.message}`))}),a.data.on("end",()=>{u(c.flush())})})}normalizeResponse(e){return Vn.normalizeResponse(e)}_parseContextFromModelfile(e){if(!e)return null;let n=e.match(/PARAMETER\s+num_ctx\s+(\d+)/i);return n?parseInt(n[1],10):null}};df.exports={LocalProvider:uc,DEFAULT_LOCAL_URL:uf}});var Jn=Q((bA,hf)=>{"use strict";var Rt=require("fs"),pf=require("path");function t$(t){if(!t||isNaN(t))return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function n$(t){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}catch{let e=Date.now()+t;for(;Date.now()<e;);}}function s$(t,e){let n=pf.dirname(t),o=pf.join(n,`.nex-tmp.${process.pid}.${Date.now()}`);try{Rt.existsSync(n)||Rt.mkdirSync(n,{recursive:!0,mode:448}),Rt.writeFileSync(o,e,{encoding:"utf-8",mode:384}),Rt.renameSync(o,t)}catch(s){try{Rt.unlinkSync(o)}catch{}throw s}}function o$(t,e,{timeout:n=5e3,retryMs:o=50}={}){let s=t+".lock",r=Date.now()+n;for(;;){let i=-1;try{i=Rt.openSync(s,"wx"),Rt.writeSync(i,Buffer.from(String(process.pid))),Rt.closeSync(i),i=-1;try{return e()}finally{try{Rt.unlinkSync(s)}catch{}}}catch(a){if(i!==-1)try{Rt.closeSync(i)}catch{}if(a.code!=="EEXIST")throw a;try{let c=Rt.readFileSync(s,"utf-8").trim(),u=parseInt(c,10);if(!t$(u)){try{Rt.unlinkSync(s)}catch{}continue}}catch(c){if(c.code&&c.code!=="ENOENT")throw c;continue}if(Date.now()>=r){try{Rt.unlinkSync(s)}catch{}return e()}n$(o)}}}hf.exports={atomicWrite:s$,withFileLockSync:o$}});var ii=Q(($A,xf)=>{var Ys=require("fs"),dc=require("path"),{T:mf}=Kt(),{atomicWrite:r$,withFileLockSync:i$}=Jn(),gf={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:{}},ri=[],Mn={};function a$(t,e,n,o,s=0){if(ri.push({provider:t,model:e,input:n,output:o,cacheRead:s}),Mn[t]!==void 0){let r=$f(t);r.allowed||process.stderr.write(`${mf.yellow}\u26A0 Budget limit reached for ${t}: $${r.spent.toFixed(2)} / $${r.limit.toFixed(2)}${mf.reset}
74
- `)}}function fc(t,e){let n=gf[t];return n?n[e]||{input:0,output:0}:{input:0,output:0}}function yf(t){let e=fc(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function wf(){let t={};for(let i of ri){let a=`${i.provider}:${i.model}`;t[a]||(t[a]={provider:i.provider,model:i.model,requests:0,input:0,output:0,cacheRead:0}),t[a].requests++,t[a].input+=i.input,t[a].output+=i.output,t[a].cacheRead+=i.cacheRead||0}let e=Object.values(t).map(i=>({...i,cost:yf(i)})),n=e.reduce((i,a)=>i+a.cost,0),o=e.reduce((i,a)=>i+a.input,0),s=e.reduce((i,a)=>i+a.output,0),r=e.reduce((i,a)=>i+(a.cacheRead||0),0);return{totalCost:n,totalInput:o,totalOutput:s,totalCacheRead:r,breakdown:e}}function c$(){let{totalCost:t,totalInput:e,totalOutput:n,breakdown:o}=wf();if(o.length===0)return"No token usage recorded this session.";let s=[];s.push("Session Token Usage:"),s.push("");for(let r of o){let i=r.cost>0?`$${r.cost.toFixed(4)}`:"free";s.push(` ${r.provider}:${r.model}`),s.push(` Input: ${r.input.toLocaleString()} tokens`),s.push(` Output: ${r.output.toLocaleString()} tokens`),s.push(` Cost: ${i}`)}return s.push(""),s.push(` Total: ${e.toLocaleString()} in + ${n.toLocaleString()} out = $${t.toFixed(4)}`),s.join(`
75
- `)}function l$(t){return!t||typeof t!="string"?0:Math.ceil(t.length/4)}function u$(t,e,n,o){let s=fc(t,e),r=(n*s.input+o*s.output)/1e6;return r<=0?"":`[~$${r.toFixed(4)}]`}function d$(){ri=[]}function f$(t,e){Mn[t]=e}function p$(t){delete Mn[t]}function h$(){return{...Mn}}function bf(t){let e=0;for(let n of ri)n.provider===t&&(e+=yf(n));return e}function $f(t){let e=bf(t),n=Mn[t];if(n===void 0)return{allowed:!0,spent:e,limit:null,remaining:null};let o=Math.max(0,n-e);return{allowed:e<n,spent:e,limit:n,remaining:o}}function _f(){let t=dc.join(process.cwd(),".nex","config.json");if(Ys.existsSync(t))try{let e=JSON.parse(Ys.readFileSync(t,"utf-8"));e.costLimits&&typeof e.costLimits=="object"&&(Mn={...e.costLimits})}catch{}}function m$(){let t=dc.join(process.cwd(),".nex"),e=dc.join(t,"config.json");Ys.existsSync(t)||Ys.mkdirSync(t,{recursive:!0}),i$(e,()=>{let n={};if(Ys.existsSync(e))try{n=JSON.parse(Ys.readFileSync(e,"utf-8"))}catch{n={}}n.costLimits=Mn,r$(e,JSON.stringify(n,null,2))})}function g$(){Mn={}}_f();xf.exports={PRICING:gf,trackUsage:a$,getSessionCosts:wf,formatCosts:c$,formatCostHint:u$,resetCosts:d$,getPricing:fc,setCostLimit:f$,removeCostLimit:p$,getCostLimits:h$,getProviderSpend:bf,checkBudget:$f,loadCostLimits:_f,saveCostLimits:m$,resetCostLimits:g$,estimateTokens:l$}});var hc=Q((_A,kf)=>{function pc(){return process.env.NEX_DEBUG==="true"||process.argv.includes("--debug")}var y$=pc();function w$(...t){pc()&&console.log(...t)}function b$(...t){pc()&&console.warn(...t)}kf.exports={DEBUG:y$,debugLog:w$,warnLog:b$}});var Ef=Q((xA,Sf)=>{"use strict";var $$=new Set(["read_file","grep","glob","search_files","list_directory"]),_$=new Set(["write_file","edit_file","patch_file"]),x$=new Set(["bash"]),k$=new Set(["web_search","web_fetch","perplexity_search"]);function vf(t,e){let n=0,o=0,s=0,r=0,i=0;for(let[a,c]of t)i+=c,$$.has(a)&&(n+=c),_$.has(a)&&(o+=c),x$.has(a)&&(s+=c),k$.has(a)&&(r+=c);return i===0?`Phase ${e}`:r/i>.5?"Research":n/i>.5?"Exploration":o/i>.3?"Implementation":s/i>.3&&o/i<.15?"Verification":`Phase ${e}`}var mc=class{constructor(e){this._N=e,this._disabled=e<=0,this._phaseNum=0,this._stepsThisPhase=0,this._phaseCounts=new Map,this._phaseStart=Date.now()}record(e,n,o,s){if(this._disabled)return null;this._stepsThisPhase++;for(let i of n)this._phaseCounts.set(i,(this._phaseCounts.get(i)||0)+1);if(this._stepsThisPhase<this._N)return null;this._phaseNum++;let r={phaseNum:this._phaseNum,phaseName:vf(this._phaseCounts,this._phaseNum),stepCount:this._stepsThisPhase,toolCounts:new Map(this._phaseCounts),elapsed:Date.now()-this._phaseStart,filesRead:new Set(o),filesModified:new Set(s)};return this._stepsThisPhase=0,this._phaseCounts=new Map,this._phaseStart=Date.now(),r}};Sf.exports={MilestoneTracker:mc,_phaseName:vf}});var Ao=Q((kA,Tf)=>{var Co=ct(),v$={"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 S$(){return Co.getActiveModel()}function E$(t){return Co.setActiveModel(t)}function T$(){return Co.getModelNames()}function R$(t){if(!t)return null;if(typeof t=="object")return t;try{return JSON.parse(t)}catch{}try{let o=t.replace(/,\s*([}\]])/g,"$1").replace(/'/g,'"');return JSON.parse(o)}catch{}let e=t.match(/\{[\s\S]*\}/);if(e)try{return JSON.parse(e[0])}catch{}try{let o=t.replace(/(\{|,)\s*([a-zA-Z_]\w*)\s*:/g,'$1"$2":');return JSON.parse(o)}catch{}let n=t.match(/```(?:json)?\s*([\s\S]*?)```/);if(n)try{return JSON.parse(n[1].trim())}catch{}return null}async function C$(t,e){let{C:n}=rt(),{Spinner:o}=rt(),s=new o("Thinking...");s.start();let r=!0,i="";try{let a=await Co.callStream(t,e,{onToken:c=>{r&&(s.stop(),process.stdout.write(`${n.blue}`),r=!1),process.stdout.write(c),i+=c}});return r?s.stop():process.stdout.write(`${n.reset}
76
- `),a}catch(a){throw s.stop(),a}}async function A$(t,e){return Co.callChat(t,e)}Tf.exports={MODELS:v$,getActiveModel:S$,setActiveModel:E$,getModelNames:T$,callOllamaStream:C$,callOllama:A$,parseToolArgs:R$}});var No=Q((vA,Mf)=>{var O$=require("readline"),{C:an}=rt(),N$=/[\u200B\u200C\u200D\uFEFF\u2060\u00AD]/g,M$=/^=([\w-]+)/;function Oo(t){return typeof t!="string"?t:t.replace(N$,"").replace(M$,"$1")}var wc=[/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/],Rf=[...wc,/\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 P$(t){for(let e of Rf)if(e.test(t))return e;return null}var Cf=[/\.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)/],L$=/\b(?:rm|rmdir|unlink|truncate|shred|mv|cp)\b/,gc=[/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 Af(t){let e=t.match(/ssh\s+[^"]*"([^"]+)"/)?.[1]||t.match(/ssh\s+[^']*'([^']+)'/)?.[1];if(!e)return!1;let o=e.replace(/\bfor\s[\s\S]*?\bdone\b/g,r=>r.replace(/;/g,"\0")).replace(/\bwhile\s[\s\S]*?\bdone\b/g,r=>r.replace(/;/g,"\0")).split(/\s*(?:&&|;)\s*/).map(r=>r.replace(/\x00/g,";").trim()).filter(Boolean);if(o.length===0)return!1;let s=r=>{let i=r.replace(/^sudo\s+(?:-[ugCD]\s+\S+\s+|-[A-Za-z]+\s+)*/,"");if(/^\s*(?:echo|printf)\s/.test(i))return!0;if(/^\s*for\s/.test(r)||/^\s*while\s/.test(r)){let a=r.match(/\bdo\s+([\s\S]*?)\s*(?:done|$)/)?.[1];return a?a.split(/\s*;\s*/).map(u=>u.trim()).filter(Boolean).every(u=>s(u)):gc.some(c=>c.test(r))}return/^\w+=\$?\(/.test(i)||/^\w+=["']/.test(i)||/^\w+=\S/.test(i)?!0:gc.some(a=>a.test(i))};return o.every(s)}var bc=[/rm\s+-rf\s/,/docker\s+system\s+prune/,/kubectl\s+delete/,/sudo\s/,/--no-verify\b/,/git\s+reset\s+--hard\b/,/git\s+clean\s+-[a-z]*f/,/git\s+checkout\s+--\s/,/git\s+push\s+(?:--force\b|-f\b)/,/\b(?:curl|wget|fetch)\b[^|;&`$()]*\|\s*(?:sh|bash|zsh|ksh|dash|python|python3|perl|ruby|node)\b/,/\b(?:curl|wget)\b[^;&`$()]*\$\([^)]*\)/,/\bbase64\s+(?:-d|--decode|-D)\b[^|;&`$()]*\|\s*(?:sh|bash|zsh|python|python3|perl|ruby|node)\b/,/\beval\s+["'`]?\$\(\s*(?:curl|wget|fetch)\b/,/\bbash\s+-i\s*>&?\s*\/dev\/tcp\//,/\bnc\s+(?:-[a-z]*e|-[a-z]*c)\b/,/\bmkfifo\b[^;&`]*;\s*(?:nc|ncat|telnet)\b/],Of=[/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/],Nf=[...bc,...Of],$c=!1,Zn=null,yc=null;function I$(t){$c=t}function j$(t){yc=t}function D$(){return $c}function q$(t){Zn=t}function F$(t){let e=Oo(t);for(let n of wc)if(n.test(e))return n;return null}function B$(t){let e=Oo(t);if(/ssh\s/.test(e)&&Af(e))return!1;for(let n of Nf)if(n.test(e))return!0;return!1}function U$(t){let e=Oo(t);for(let n of bc)if(n.test(e))return!0;return!1}function W$(t){if(process.env.NEX_UNPROTECT==="1")return null;let e=Oo(t);if(!L$.test(e))return null;for(let n of Cf)if(n.test(e))return n;return null}function H$(t,e={}){if($c)return Promise.resolve(!0);if(yc)return yc(t,e);if(!process.stdout.isTTY||!process.stdin.isTTY)return Y$(t,e);let n=e.toolName?["Yes","No","Always allow"]:["Yes","No"];return new Promise(o=>{let s=0;Zn&&Zn.pause();let r=global._nexRawWrite||(d=>process.stdout.write(d)),i=()=>{let d=process.stdout.rows||24;return Math.max(1,d-n.length-2)},a=()=>{let d=i();global._nexRawWrite&&d>1&&global._nexRawWrite(`\x1B[1;${d-1}r`);let f=`\x1B[${d};1H\x1B[2K${an.yellow}${t}${an.reset}`;for(let p=0;p<n.length;p++){let h=p===s,g=h?`${an.yellow}\u276F${an.reset}`:" ",w=h?`${an.yellow}${n[p]}${an.reset}`:n[p];f+=`\x1B[${d+1+p};1H\x1B[2K ${g} ${w}`}r(f)},c=d=>{process.stdin.setRawMode(!1),process.stdin.pause(),process.stdin.removeListener("data",l);let f=global._nexRawWrite||(g=>process.stdout.write(g)),p=i(),h="";for(let g=0;g<n.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(),Zn&&Zn.resume(),o(d)},u=d=>{if(d===1){c(!1);return}d===2&&e.toolName&&ai(e.toolName),c(!0)},l=d=>{if(d[0]===3){c(!1);return}let f=d.toString();if(f==="\r"||f===`
77
- `){u(s);return}if(f==="\x1B[A"){s=(s-1+n.length)%n.length,a();return}if(f==="\x1B[B"){s=(s+1)%n.length,a();return}let p=f.toLowerCase().trim();if(p==="y"){c(!0);return}if(p==="n"){c(!1);return}if(p==="a"&&e.toolName){ai(e.toolName),c(!0);return}};a(),process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",l)})}function Y$(t,e){let n=e.toolName?"[Y/n/a] ":"[Y/n] ";return new Promise(o=>{let s=r=>{let i=r.trim().toLowerCase();i==="a"&&e.toolName?(ai(e.toolName),o(!0)):o(i!=="n")};if(Zn)Zn.question(`${an.yellow}${t} ${n}${an.reset}`,s);else{let r=O$.createInterface({input:process.stdin,output:process.stdout});r.question(`${an.yellow}${t} ${n}${an.reset}`,i=>{r.close(),s(i)})}})}var ai=()=>{};function G$(t){ai=t}Mf.exports={sanitizeBashCommand:Oo,FORBIDDEN_PATTERNS:wc,SSH_FORBIDDEN_PATTERNS:Rf,BASH_PROTECTED_PATHS:Cf,SSH_SAFE_PATTERNS:gc,isSSHReadOnly:Af,DANGEROUS_BASH:Nf,CRITICAL_BASH:bc,NOTABLE_BASH:Of,isForbidden:F$,isSSHForbidden:P$,isDangerous:B$,isCritical:U$,isBashPathForbidden:W$,confirm:H$,setAutoConfirm:I$,getAutoConfirm:D$,setConfirmHook:j$,setReadlineInterface:q$,setAllowAlwaysHandler:G$}});var If=Q((EA,Lf)=>{var ci=require("path"),{C:q}=rt(),{T:_c,isDark:SA}=Kt(),{confirm:z$,getAutoConfirm:K$}=No(),Pf=2e3;function Mo(t,e){let n=t.split(`
67
+ `)}var{Spinner:kb,MultiProgress:vb,TaskProgress:Sb,ToolProgress:Eb,setActiveTaskProgress:Tb,getActiveTaskProgress:Rb,cleanupTerminal:Cb}=Yn(),{formatToolCall:Ab,formatResult:Ob,getToolSpinnerText:Nb,formatToolSummary:Mb,formatSectionHeader:Pb,formatMilestone:Lb,getThinkingVerb:Ib,setActiveModelForSpinner:jb}=Wd();Yd.exports={C:sc,banner:xb,Spinner:kb,MultiProgress:vb,TaskProgress:Sb,ToolProgress:Eb,setActiveTaskProgress:Tb,getActiveTaskProgress:Rb,cleanupTerminal:Cb,formatToolCall:Ab,formatResult:Ob,getToolSpinnerText:Nb,formatToolSummary:Mb,formatSectionHeader:Pb,formatMilestone:Lb,getThinkingVerb:Ib,setActiveModelForSpinner:jb}});var Bs=Q((pA,Gd)=>{async function Db(t,e){if(!t.response?.data)return t.message;let n=t.response.data;if(typeof n=="object"&&n!==null&&typeof n.pipe!="function")return e(n)||t.message;try{let o=await new Promise((r,i)=>{let a=[];n.on("data",c=>a.push(c)),n.on("end",()=>r(Buffer.concat(a).toString("utf8"))),n.on("error",i)}),s=JSON.parse(o);return e(s)||o||t.message}catch{return t.message}}var oc=class t{constructor(e={}){if(new.target===t)throw new Error("BaseProvider is abstract \u2014 use a concrete provider");this.name=e.name||"unknown",this.baseUrl=e.baseUrl||"",this.models=e.models||{},this.defaultModel=e.defaultModel||null}isConfigured(){throw new Error(`${this.name}: isConfigured() not implemented`)}getApiKey(){return null}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}getModel(e){return this.models[e]||null}async chat(e,n,o={}){throw new Error(`${this.name}: chat() not implemented`)}async stream(e,n,o={}){throw new Error(`${this.name}: stream() not implemented`)}formatMessages(e){return{messages:e}}formatTools(e){return e}normalizeResponse(e){throw new Error(`${this.name}: normalizeResponse() not implemented`)}};Gd.exports={BaseProvider:oc,readStreamErrorBody:Db}});var Hs=Q((hA,Kd)=>{var Us=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,n={}){throw new Error("createStreamParser() not implemented")}},Ws=class{constructor(e,n={}){this.onToken=e,this.callbacks=n,this.content="",this.buffer=""}feed(e){this.buffer+=e;let n=this.buffer.split(`
68
+ `);this.buffer=n.pop()||"";for(let o of n){let s=this.parseLine(o);if(s?.done)return s}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")}},Xr=class extends Ws{constructor(e,n={}){super(e,n),this.toolCallsMap={}}parseLine(e){let n=e.trim();if(!n||!n.startsWith("data: "))return{done:!1};let o=n.slice(6);if(o==="[DONE]")return{done:!0,result:this.getResult()};let s;try{s=JSON.parse(o)}catch{return{done:!1}}let r=s.choices?.[0]?.delta;if(!r)return{done:!1};if(r.content&&(this.onToken(r.content),this.content+=r.content),r.tool_calls)for(let i of r.tool_calls){let a;i.index!==void 0&&i.index!==null?a=i.index:i.id?a=`id:${i.id}`:a=0,this.toolCallsMap[a]||(this.toolCallsMap[a]={id:i.id||"",name:"",arguments:""}),i.id&&(this.toolCallsMap[a].id=i.id),i.function?.name&&(this.toolCallsMap[a].name+=i.function.name),i.function?.arguments&&(this.toolCallsMap[a].arguments+=i.function.arguments)}return{done:!1}}getResult(){return{content:this.content,tool_calls:Object.values(this.toolCallsMap).filter(e=>e.name).map(e=>({id:e.id||`call-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,function:{name:e.name,arguments:e.arguments}}))}}},Vr=class extends Us{getEndpoint(){return"/chat/completions"}buildRequestBody({model:e,messages:n,tools:o,maxTokens:s,temperature:r,stream:i}){let a={model:e,messages:n,max_tokens:s,temperature:r};return i&&(a.stream=!0),o&&o.length>0&&(a.tools=o),a}normalizeResponse(e){let n=e.choices?.[0]?.message||{},o=(n.tool_calls||[]).map(s=>({id:s.id,function:{name:s.function.name,arguments:s.function.arguments}}));return{content:n.content||"",tool_calls:o}}createStreamParser(e,n={}){return new Xr(e,n)}},Jr=class extends Ws{constructor(e,n={}){super(e,n),this.toolUses=[],this.currentToolIndex=-1}parseLine(e){let n=e.trim();if(!n.startsWith("data: "))return{done:!1};let o=n.slice(6),s;try{s=JSON.parse(o)}catch{return{done:!1}}switch(s.type){case"content_block_start":{let r=s.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=s.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 n={};if(e.inputJson)try{n=JSON.parse(e.inputJson)}catch{n=e.inputJson}return{id:e.id||`anthropic-${Date.now()}`,function:{name:e.name,arguments:n}}})}}},rc="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->",Zr=class extends Us{getEndpoint(){return"/messages"}buildRequestBody({model:e,messages:n,tools:o,maxTokens:s,temperature:r,stream:i,extra:a}){let c={model:e,messages:n,max_tokens:s,temperature:r};if(i&&(c.stream=!0),a?.system){let u=a.system,l=u.indexOf(rc);if(l!==-1){let d=u.slice(0,l).trimEnd(),f=u.slice(l+rc.length).trimStart();c.system=[{type:"text",text:d},{type:"text",text:f,cache_control:{type:"ephemeral"}}]}else c.system=u}return o&&o.length>0&&(c.tools=o),c}formatTools(e){return!e||e.length===0?[]:e.map(n=>({name:n.function.name,description:n.function.description||"",input_schema:n.function.parameters||{type:"object",properties:{}}}))}normalizeResponse(e){let n="",o=[];for(let s of e.content||[])s.type==="text"?n+=s.text:s.type==="tool_use"&&o.push({id:s.id,function:{name:s.name,arguments:s.input}});return{content:n,tool_calls:o}}createStreamParser(e,n={}){return new Jr(e,n)}};function zd(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 Qr=class extends Ws{constructor(e,n={}){super(e,n),this.toolCalls=[],this.onThinkingToken=n.onThinkingToken||(()=>{})}parseLine(e){if(!e.trim())return{done:!1};let n;try{n=JSON.parse(e)}catch{return{done:!1}}return n.message?.thinking&&this.onThinkingToken(n.message.thinking),n.message?.content&&(this.onToken(n.message.content),this.content+=n.message.content),n.message?.tool_calls&&(this.toolCalls=this.toolCalls.concat(n.message.tool_calls)),n.done?{done:!0,result:this.getResult()}:{done:!1}}getResult(){return{content:this.content,tool_calls:this.toolCalls.map((e,n)=>({id:e.id||`ollama-${Date.now()}-${n}`,function:{name:e.function?.name||e.name||"unknown",arguments:zd(e.function?.arguments??e.arguments)}}))}}},ei=class extends Us{getEndpoint(){return"/api/chat"}buildRequestBody({model:e,messages:n,tools:o,maxTokens:s,temperature:r,stream:i,extra:a}){let c={model:e,messages:n,stream:i,options:{temperature:r,num_predict:s,repeat_penalty:a?.repeat_penalty??1.05}};return o&&o.length>0&&(c.tools=o),c}normalizeResponse(e){let n=e.message||{};return{content:n.content||"",tool_calls:(n.tool_calls||[]).map((o,s)=>({id:o.id||`ollama-${Date.now()}-${s}`,function:{name:o.function?.name||o.name||"unknown",arguments:zd(o.function?.arguments??o.arguments)}}))}}createStreamParser(e,n={}){return new Qr(e,n)}},qb=new Vr,Fb=new Zr,Bb=new ei;Kd.exports={ANTHROPIC_CACHE_BOUNDARY:rc,WireProtocol:Us,StreamParser:Ws,OpenAICompatibleProtocol:Vr,AnthropicProtocol:Zr,OllamaChatProtocol:ei,OpenAIStreamParser:Xr,AnthropicStreamParser:Jr,OllamaStreamParser:Qr,openaiProtocol:qb,anthropicProtocol:Fb,ollamaProtocol:Bb}});var Jd=Q((mA,Vd)=>{var ti=require("axios"),Ub=require("http"),Wb=require("https"),{BaseProvider:Hb,readStreamErrorBody:Yb}=Bs(),{ollamaProtocol:zn}=Hs(),ni=new Ub.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),si=new Wb.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Xd={"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}},ic=class extends Hb{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||Xd,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){ti.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:ni,httpsAgent:si}).then(e=>{let n=e.data?.models||[];for(let o of n){let s=(o.name||o.model||"").replace(/:latest$/,"");!s||this.models[s]||(this.models[s]={id:s,name:o.name||s,maxTokens:16384,contextWindow:131072})}}).catch(()=>{});return}try{let n=(await ti.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:ni,httpsAgent:si})).data?.models||[];for(let o of n){let s=(o.name||o.model||"").replace(/:latest$/,"");!s||this.models[s]||(this.models[s]={id:s,name:o.name||s,maxTokens:16384,contextWindow:131072})}}catch{}}}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OLLAMA_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OLLAMA_API_KEY not set");return{Authorization:`Bearer ${e}`}}_formatMessages(e){return e.map(n=>{if(Array.isArray(n.content)){let o=[],s=[];for(let i of n.content)i.type==="text"?o.push(i.text??""):i.type==="image"&&i.data&&s.push(i.data);let r={role:n.role,content:o.join(`
69
+ `)};return s.length>0&&(r.images=s),n.tool_call_id&&(r.tool_call_id=n.tool_call_id),r}return n})}async chat(e,n,o={}){await this.discoverModels();let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||16384,a=zn.buildRequestBody({model:s,messages:this._formatMessages(e),tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!1,extra:{repeat_penalty:o.repeat_penalty}}),c;try{c=await ti.post(`${this.baseUrl}${zn.getEndpoint()}`,a,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),httpAgent:ni,httpsAgent:si})}catch(u){if(u.name==="CanceledError"||u.name==="AbortError"||u.code==="ERR_CANCELED")throw u;let l=u.response?.status?` [HTTP ${u.response.status}]`:"",d=u.response?.data?.error||u.message;throw new Error(`API Error${l}: ${d}`)}return zn.normalizeResponse(c.data)}async stream(e,n,o={}){await this.discoverModels();let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||16384,a=o.onToken||(()=>{}),c=o.onThinkingToken||(()=>{}),u=zn.buildRequestBody({model:s,messages:this._formatMessages(e),tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!0,extra:{repeat_penalty:o.repeat_penalty}}),l;try{l=await ti.post(`${this.baseUrl}${zn.getEndpoint()}`,u,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal,httpAgent:ni,httpsAgent:si})}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 Yb(f,w=>w?.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=zn.createStreamParser(a,{onThinkingToken:c});return new Promise((f,p)=>{o.signal&&o.signal.addEventListener("abort",()=>{l.data.destroy(),p(new DOMException("The operation was aborted","AbortError"))},{once:!0}),l.data.on("data",h=>{let{done:g,result:w}=d.feed(h.toString());g&&f(w)}),l.data.on("error",h=>{if(o.signal?.aborted)return;let g=new Error(`Stream error: ${h.message}`);g.code=h.code||h.name,p(g)}),l.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return zn.normalizeResponse(e)}};Vd.exports={OllamaProvider:ic,OLLAMA_MODELS:Xd}});var tf=Q((gA,ef)=>{var Zd=require("axios"),{BaseProvider:Gb,readStreamErrorBody:zb}=Bs(),{openaiProtocol:Kn}=Hs(),Qd={"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}},ac=class extends Gb{constructor(e={}){super({name:"openai",baseUrl:e.baseUrl||"https://api.openai.com/v1",models:e.models||Qd,defaultModel:e.defaultModel||"gpt-4o",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OPENAI_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OPENAI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let n=[];for(let o of e){if(this._messageFormatCache.has(o)){n.push(this._messageFormatCache.get(o));continue}let s=this._getMessageCacheKey(o);if(this._messageStringCache.has(s)){let i=this._messageStringCache.get(s);this._messageFormatCache.set(o,i),n.push(i);continue}let r=this._formatSingleMessage(o);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(s,r),this._messageFormatCache.set(o,r),n.push(r)}return{messages:n}}_getMessageCacheKey(e){let n=e.role||"",o=typeof e.content=="string"?e.content.substring(0,100):"",s=e.tool_calls?e.tool_calls.length:0;return`${n}:${o.length}:${s}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||null,tool_calls:e.tool_calls.map(n=>({id:n.id||`call-${Date.now()}`,type:"function",function:{name:n.function.name,arguments:typeof n.function.arguments=="string"?n.function.arguments:JSON.stringify(n.function.arguments)}}))};if(e.role==="tool"){let n;return Array.isArray(e.content)?n=e.content.filter(s=>s.type==="text").map(s=>s.text).join(`
70
+ `)||JSON.stringify(e.content):n=typeof e.content=="string"?e.content:JSON.stringify(e.content),{role:"tool",content:n,tool_call_id:e.tool_call_id}}if(e.role==="user"&&Array.isArray(e.content)){let n=[];for(let o of e.content)if(o.type==="text")n.push({type:"text",text:o.text??""});else if(o.type==="image"&&o.data){let s=o.data.startsWith("data:")?o.data:`data:${o.media_type||"image/png"};base64,${o.data}`;n.push({type:"image_url",image_url:{url:s,detail:"auto"}})}return{role:"user",content:n}}return{role:e.role,content:e.content}}async chat(e,n,o={}){let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||16384,{messages:a}=this.formatMessages(e),c=Kn.buildRequestBody({model:s,messages:a,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!1}),u;try{u=await Zd.post(`${this.baseUrl}${Kn.getEndpoint()}`,c,{timeout:o.timeout||this.timeout,headers:this._getHeaders()})}catch(l){if(l.name==="CanceledError"||l.name==="AbortError"||l.code==="ERR_CANCELED")throw l;let d=l.response?.status?` [HTTP ${l.response.status}]`:"",f=l.response?.data?.error?.message||l.response?.data?.error||l.message;throw new Error(`API Error${d}: ${f}`)}return Kn.normalizeResponse(u.data)}async stream(e,n,o={}){let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||16384,a=o.onToken||(()=>{}),{messages:c}=this.formatMessages(e),u=Kn.buildRequestBody({model:s,messages:c,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!0}),l;try{l=await Zd.post(`${this.baseUrl}${Kn.getEndpoint()}`,u,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let p=f.response?.status?` [HTTP ${f.response.status}]`:"",h=await zb(f,g=>g?.error?.message||g?.error);throw new Error(`API Error${p}: ${h}`)}let d=Kn.createStreamParser(a);return new Promise((f,p)=>{o.signal&&o.signal.addEventListener("abort",()=>{l.data.destroy(),p(new DOMException("The operation was aborted","AbortError"))},{once:!0}),l.data.on("data",h=>{let{done:g,result:w}=d.feed(h.toString());g&&f(w)}),l.data.on("error",h=>{o.signal?.aborted||p(new Error(`Stream error: ${h.message}`))}),l.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return Kn.normalizeResponse(e)}};ef.exports={OpenAIProvider:ac,OPENAI_MODELS:Qd}});var rf=Q((yA,of)=>{var nf=require("axios"),{BaseProvider:Kb,readStreamErrorBody:Xb}=Bs(),{anthropicProtocol:Nn}=Hs(),sf={"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}},Vb="2023-06-01",cc=class extends Kb{constructor(e={}){super({name:"anthropic",baseUrl:e.baseUrl||"https://api.anthropic.com/v1",models:e.models||sf,defaultModel:e.defaultModel||"claude-sonnet",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this.apiVersion=e.apiVersion||Vb}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.ANTHROPIC_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("ANTHROPIC_API_KEY not set");return{"x-api-key":e,"anthropic-version":this.apiVersion,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let n="",o=[];for(let s of e){if(s.role==="system"){n+=(n?`
71
+
72
+ `:"")+s.content;continue}if(s.role!=="system"&&s.role!=="tool"&&this._messageFormatCache.has(s)){o.push(this._messageFormatCache.get(s));continue}let r=this._formatSingleMessage(s,o);if(r){if(s.role!=="system"&&s.role!=="tool"&&this._messageStringCache.size<this._maxCacheSize){let i=this._getMessageCacheKey(s);this._messageStringCache.set(i,r),this._messageFormatCache.set(s,r)}o.push(r)}}for(let s=o.length-1;s>0;s--)o[s].role==="user"&&o[s-1].role==="user"&&o.splice(s,0,{role:"assistant",content:[{type:"text",text:"[continuing]"}]});return{messages:o,system:n}}_getMessageCacheKey(e){let n=e.role||"",o=typeof e.content=="string"?e.content.substring(0,100):"",s=e.tool_calls?e.tool_calls.length:0;return`${n}:${o.length}:${s}`}_formatSingleMessage(e,n=[]){if(e.role==="assistant"){let o=[];if(e.content&&o.push({type:"text",text:e.content}),e.tool_calls)for(let s of e.tool_calls)o.push({type:"tool_use",id:s.id||`toolu-${Date.now()}`,name:s.function.name,input:typeof s.function.arguments=="string"?JSON.parse(s.function.arguments||"{}"):s.function.arguments||{}});return{role:"assistant",content:o.length>0?o:[{type:"text",text:""}]}}if(e.role==="tool"){let o=n[n.length-1],s;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}});s=i}else s=typeof e.content=="string"?e.content:JSON.stringify(e.content);let r={type:"tool_result",tool_use_id:e.tool_call_id,content:s};return o&&o.role==="user"&&Array.isArray(o.content)&&o.content[0]?.type==="tool_result"?(o.content.push(r),null):{role:"user",content:[r]}}if(Array.isArray(e.content)){let o=[];for(let s of e.content)s.type==="text"?o.push({type:"text",text:s.text??""}):s.type==="image"&&s.data&&o.push({type:"image",source:{type:"base64",media_type:s.media_type||"image/png",data:s.data}});return{role:"user",content:o}}return{role:"user",content:e.content}}formatTools(e){return Nn.formatTools(e)}_resolveModelId(e){return this.getModel(e)?.id||e}async chat(e,n,o={}){let s=o.model||this.defaultModel,r=this._resolveModelId(s),i=this.getModel(s),a=o.maxTokens||i?.maxTokens||8192,{messages:c,system:u}=this.formatMessages(e),l=this.formatTools(n),d=Nn.buildRequestBody({model:r,messages:c,tools:l,maxTokens:a,temperature:o.temperature??this.temperature,stream:!1,extra:{system:u}}),f;try{f=await nf.post(`${this.baseUrl}${Nn.getEndpoint()}`,d,{timeout:o.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 Nn.normalizeResponse(f.data)}async stream(e,n,o={}){let s=o.model||this.defaultModel,r=this._resolveModelId(s),i=this.getModel(s),a=o.maxTokens||i?.maxTokens||8192,c=o.onToken||(()=>{}),{messages:u,system:l}=this.formatMessages(e),d=this.formatTools(n),f=Nn.buildRequestBody({model:r,messages:u,tools:d,maxTokens:a,temperature:o.temperature??this.temperature,stream:!0,extra:{system:l}}),p;try{p=await nf.post(`${this.baseUrl}${Nn.getEndpoint()}`,f,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal})}catch(g){if(g.name==="CanceledError"||g.name==="AbortError"||g.code==="ERR_CANCELED")throw g;let w=g.response?.status?` [HTTP ${g.response.status}]`:"",_=await Xb(g,S=>S?.error?.message||S?.error);throw new Error(`API Error${w}: ${_}`)}let h=Nn.createStreamParser(c);return new Promise((g,w)=>{o.signal&&o.signal.addEventListener("abort",()=>{p.data.destroy(),w(new DOMException("The operation was aborted","AbortError"))},{once:!0}),p.data.on("data",_=>{let{done:S,result:A}=h.feed(_.toString());S&&g(A)}),p.data.on("error",_=>{o.signal?.aborted||w(new Error(`Stream error: ${_.message}`))}),p.data.on("end",()=>{g(h.flush())})})}normalizeResponse(e){return Nn.normalizeResponse(e)}};of.exports={AnthropicProvider:cc,ANTHROPIC_MODELS:sf}});var uf=Q((wA,lf)=>{var af=require("axios"),{BaseProvider:Jb,readStreamErrorBody:Zb}=Bs(),{openaiProtocol:Xn}=Hs(),cf={"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}},lc=class extends Jb{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||cf,defaultModel:e.defaultModel||"gemini-2.5-flash",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("GEMINI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let n=[];for(let o of e){if(this._messageFormatCache.has(o)){n.push(this._messageFormatCache.get(o));continue}let s=this._getMessageCacheKey(o);if(this._messageStringCache.has(s)){let i=this._messageStringCache.get(s);this._messageFormatCache.set(o,i),n.push(i);continue}let r=this._formatSingleMessage(o);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(s,r),this._messageFormatCache.set(o,r),n.push(r)}return{messages:n}}_getMessageCacheKey(e){let n=e.role||"",o=typeof e.content=="string"?e.content.substring(0,100):"",s=e.tool_calls?e.tool_calls.length:0;return`${n}:${o.length}:${s}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||"",tool_calls:e.tool_calls.map(n=>({id:n.id||`call-${Date.now()}`,type:"function",function:{name:n.function.name,arguments:typeof n.function.arguments=="string"?n.function.arguments:JSON.stringify(n.function.arguments)}}))};if(e.role==="tool")return{role:"tool",content:typeof e.content=="string"?e.content:JSON.stringify(e.content),tool_call_id:e.tool_call_id};if(e.role==="user"&&Array.isArray(e.content)){let n=[];for(let o of e.content)if(o.type==="text")n.push({type:"text",text:o.text??""});else if(o.type==="image"&&o.data){let s=o.data.startsWith("data:")?o.data:`data:${o.media_type||"image/png"};base64,${o.data}`;n.push({type:"image_url",image_url:{url:s,detail:"auto"}})}return{role:"user",content:n}}return{role:e.role,content:e.content}}async chat(e,n,o={}){let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||8192,{messages:a}=this.formatMessages(e),c=Xn.buildRequestBody({model:s,messages:a,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!1}),u;try{u=await af.post(`${this.baseUrl}${Xn.getEndpoint()}`,c,{timeout:o.timeout||this.timeout,headers:this._getHeaders()})}catch(l){if(l.name==="CanceledError"||l.name==="AbortError"||l.code==="ERR_CANCELED")throw l;let d=l.response?.status?` [HTTP ${l.response.status}]`:"",f=l.response?.data?.error?.message||l.response?.data?.error||l.message;throw new Error(`API Error${d}: ${f}`)}return Xn.normalizeResponse(u.data)}async stream(e,n,o={}){let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||8192,a=o.onToken||(()=>{}),{messages:c}=this.formatMessages(e),u=Xn.buildRequestBody({model:s,messages:c,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!0}),l;try{l=await af.post(`${this.baseUrl}${Xn.getEndpoint()}`,u,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let p=f.response?.status?` [HTTP ${f.response.status}]`:"",h=await Zb(f,g=>g?.error?.message||g?.error);throw new Error(`API Error${p}: ${h}`)}let d=Xn.createStreamParser(a);return new Promise((f,p)=>{o.signal&&o.signal.addEventListener("abort",()=>{l.data.destroy(),p(new DOMException("The operation was aborted","AbortError"))},{once:!0}),l.data.on("data",h=>{let{done:g,result:w}=d.feed(h.toString());g&&f(w)}),l.data.on("error",h=>{o.signal?.aborted||p(new Error(`Stream error: ${h.message}`))}),l.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return Xn.normalizeResponse(e)}};lf.exports={GeminiProvider:lc,GEMINI_MODELS:cf}});var pf=Q((bA,ff)=>{var oi=require("axios"),{BaseProvider:Qb,readStreamErrorBody:e$}=Bs(),{ollamaProtocol:Vn}=Hs(),df="http://localhost:11434",uc=class extends Qb{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||df,models:e.models||{},defaultModel:e.defaultModel||null,...e}),this.timeout=e.timeout||3e5,this.temperature=e.temperature??.2,this._modelsLoaded=!1}isConfigured(){return!0}async loadModels(){if(this._modelsLoaded)return this.models;try{let n=(await oi.get(`${this.baseUrl}/api/tags`,{timeout:5e3})).data?.models||[];this.models={};for(let o of n){let s=o.name||o.model;if(!s)continue;let r=s.replace(/:latest$/,""),i=32768;try{let a=await oi.post(`${this.baseUrl}/api/show`,{name:s},{timeout:5e3}),c=a.data?.model_info||a.data?.details||{};i=c["general.context_length"]||c["llama.context_length"]||this._parseContextFromModelfile(a.data?.modelfile)||32768}catch{}this.models[r]={id:r,name:o.name,maxTokens:Math.min(8192,Math.floor(i*.1)),contextWindow:i}}!this.defaultModel&&Object.keys(this.models).length>0&&(this.defaultModel=Object.keys(this.models)[0]),this._modelsLoaded=!0}catch{this.models={},this._modelsLoaded=!1}return this.models}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}_formatMessages(e){return e.map(n=>{if(n.role==="user"&&Array.isArray(n.content)){let o=[],s=[];for(let i of n.content)i.type==="text"?o.push(i.text??""):i.type==="image"&&i.data&&s.push(i.data);let r={role:"user",content:o.join(`
73
+ `)};return s.length>0&&(r.images=s),r}return n})}async chat(e,n,o={}){this._modelsLoaded||await this.loadModels();let s=o.model||this.defaultModel;if(!s)throw new Error("No local model available. Is Ollama running?");let r=Vn.buildRequestBody({model:s,messages:this._formatMessages(e),tools:n,maxTokens:o.maxTokens||8192,temperature:o.temperature??this.temperature,stream:!1}),i;try{i=await oi.post(`${this.baseUrl}${Vn.getEndpoint()}`,r,{timeout:o.timeout||this.timeout})}catch(a){if(a.name==="CanceledError"||a.name==="AbortError"||a.code==="ERR_CANCELED")throw a;let c=a.response?.status?` [HTTP ${a.response.status}]`:"",u=a.response?.data?.error||a.message;throw new Error(`API Error${c}: ${u}`)}return Vn.normalizeResponse(i.data)}async stream(e,n,o={}){this._modelsLoaded||await this.loadModels();let s=o.model||this.defaultModel;if(!s)throw new Error("No local model available. Is Ollama running?");let r=o.onToken||(()=>{}),i=Vn.buildRequestBody({model:s,messages:this._formatMessages(e),tools:n,maxTokens:o.maxTokens||8192,temperature:o.temperature??this.temperature,stream:!0}),a;try{a=await oi.post(`${this.baseUrl}${Vn.getEndpoint()}`,i,{timeout:o.timeout||this.timeout,responseType:"stream",signal:o.signal})}catch(u){if(u.name==="CanceledError"||u.name==="AbortError"||u.code==="ERR_CANCELED")throw u;let l=u.response?.status?` [HTTP ${u.response.status}]`:"",d=await e$(u,f=>f?.error);throw new Error(`API Error${l}: ${d}`)}let c=Vn.createStreamParser(r);return new Promise((u,l)=>{o.signal&&o.signal.addEventListener("abort",()=>{a.data.destroy(),l(new DOMException("The operation was aborted","AbortError"))},{once:!0}),a.data.on("data",d=>{let{done:f,result:p}=c.feed(d.toString());f&&u(p)}),a.data.on("error",d=>{o.signal?.aborted||l(new Error(`Stream error: ${d.message}`))}),a.data.on("end",()=>{u(c.flush())})})}normalizeResponse(e){return Vn.normalizeResponse(e)}_parseContextFromModelfile(e){if(!e)return null;let n=e.match(/PARAMETER\s+num_ctx\s+(\d+)/i);return n?parseInt(n[1],10):null}};ff.exports={LocalProvider:uc,DEFAULT_LOCAL_URL:df}});var Jn=Q(($A,mf)=>{"use strict";var Rt=require("fs"),hf=require("path");function t$(t){if(!t||isNaN(t))return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function n$(t){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}catch{let e=Date.now()+t;for(;Date.now()<e;);}}function s$(t,e){let n=hf.dirname(t),o=hf.join(n,`.nex-tmp.${process.pid}.${Date.now()}`);try{Rt.existsSync(n)||Rt.mkdirSync(n,{recursive:!0,mode:448}),Rt.writeFileSync(o,e,{encoding:"utf-8",mode:384}),Rt.renameSync(o,t)}catch(s){try{Rt.unlinkSync(o)}catch{}throw s}}function o$(t,e,{timeout:n=5e3,retryMs:o=50}={}){let s=t+".lock",r=Date.now()+n;for(;;){let i=-1;try{i=Rt.openSync(s,"wx"),Rt.writeSync(i,Buffer.from(String(process.pid))),Rt.closeSync(i),i=-1;try{return e()}finally{try{Rt.unlinkSync(s)}catch{}}}catch(a){if(i!==-1)try{Rt.closeSync(i)}catch{}if(a.code!=="EEXIST")throw a;try{let c=Rt.readFileSync(s,"utf-8").trim(),u=parseInt(c,10);if(!t$(u)){try{Rt.unlinkSync(s)}catch{}continue}}catch(c){if(c.code&&c.code!=="ENOENT")throw c;continue}if(Date.now()>=r){try{Rt.unlinkSync(s)}catch{}return e()}n$(o)}}}mf.exports={atomicWrite:s$,withFileLockSync:o$}});var ii=Q((_A,kf)=>{var Ys=require("fs"),dc=require("path"),{T:gf}=Kt(),{atomicWrite:r$,withFileLockSync:i$}=Jn(),yf={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:{}},ri=[],Mn={};function a$(t,e,n,o,s=0){if(ri.push({provider:t,model:e,input:n,output:o,cacheRead:s}),Mn[t]!==void 0){let r=_f(t);r.allowed||process.stderr.write(`${gf.yellow}\u26A0 Budget limit reached for ${t}: $${r.spent.toFixed(2)} / $${r.limit.toFixed(2)}${gf.reset}
74
+ `)}}function fc(t,e){let n=yf[t];return n?n[e]||{input:0,output:0}:{input:0,output:0}}function wf(t){let e=fc(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function bf(){let t={};for(let i of ri){let a=`${i.provider}:${i.model}`;t[a]||(t[a]={provider:i.provider,model:i.model,requests:0,input:0,output:0,cacheRead:0}),t[a].requests++,t[a].input+=i.input,t[a].output+=i.output,t[a].cacheRead+=i.cacheRead||0}let e=Object.values(t).map(i=>({...i,cost:wf(i)})),n=e.reduce((i,a)=>i+a.cost,0),o=e.reduce((i,a)=>i+a.input,0),s=e.reduce((i,a)=>i+a.output,0),r=e.reduce((i,a)=>i+(a.cacheRead||0),0);return{totalCost:n,totalInput:o,totalOutput:s,totalCacheRead:r,breakdown:e}}function c$(){let{totalCost:t,totalInput:e,totalOutput:n,breakdown:o}=bf();if(o.length===0)return"No token usage recorded this session.";let s=[];s.push("Session Token Usage:"),s.push("");for(let r of o){let i=r.cost>0?`$${r.cost.toFixed(4)}`:"free";s.push(` ${r.provider}:${r.model}`),s.push(` Input: ${r.input.toLocaleString()} tokens`),s.push(` Output: ${r.output.toLocaleString()} tokens`),s.push(` Cost: ${i}`)}return s.push(""),s.push(` Total: ${e.toLocaleString()} in + ${n.toLocaleString()} out = $${t.toFixed(4)}`),s.join(`
75
+ `)}function l$(t){return!t||typeof t!="string"?0:Math.ceil(t.length/4)}function u$(t,e,n,o){let s=fc(t,e),r=(n*s.input+o*s.output)/1e6;return r<=0?"":`[~$${r.toFixed(4)}]`}function d$(){ri=[]}function f$(t,e){Mn[t]=e}function p$(t){delete Mn[t]}function h$(){return{...Mn}}function $f(t){let e=0;for(let n of ri)n.provider===t&&(e+=wf(n));return e}function _f(t){let e=$f(t),n=Mn[t];if(n===void 0)return{allowed:!0,spent:e,limit:null,remaining:null};let o=Math.max(0,n-e);return{allowed:e<n,spent:e,limit:n,remaining:o}}function xf(){let t=dc.join(process.cwd(),".nex","config.json");if(Ys.existsSync(t))try{let e=JSON.parse(Ys.readFileSync(t,"utf-8"));e.costLimits&&typeof e.costLimits=="object"&&(Mn={...e.costLimits})}catch{}}function m$(){let t=dc.join(process.cwd(),".nex"),e=dc.join(t,"config.json");Ys.existsSync(t)||Ys.mkdirSync(t,{recursive:!0}),i$(e,()=>{let n={};if(Ys.existsSync(e))try{n=JSON.parse(Ys.readFileSync(e,"utf-8"))}catch{n={}}n.costLimits=Mn,r$(e,JSON.stringify(n,null,2))})}function g$(){Mn={}}xf();kf.exports={PRICING:yf,trackUsage:a$,getSessionCosts:bf,formatCosts:c$,formatCostHint:u$,resetCosts:d$,getPricing:fc,setCostLimit:f$,removeCostLimit:p$,getCostLimits:h$,getProviderSpend:$f,checkBudget:_f,loadCostLimits:xf,saveCostLimits:m$,resetCostLimits:g$,estimateTokens:l$}});var hc=Q((xA,vf)=>{function pc(){return process.env.NEX_DEBUG==="true"||process.argv.includes("--debug")}var y$=pc();function w$(...t){pc()&&console.log(...t)}function b$(...t){pc()&&console.warn(...t)}vf.exports={DEBUG:y$,debugLog:w$,warnLog:b$}});var Tf=Q((kA,Ef)=>{"use strict";var $$=new Set(["read_file","grep","glob","search_files","list_directory"]),_$=new Set(["write_file","edit_file","patch_file"]),x$=new Set(["bash"]),k$=new Set(["web_search","web_fetch","perplexity_search"]);function Sf(t,e){let n=0,o=0,s=0,r=0,i=0;for(let[a,c]of t)i+=c,$$.has(a)&&(n+=c),_$.has(a)&&(o+=c),x$.has(a)&&(s+=c),k$.has(a)&&(r+=c);return i===0?`Phase ${e}`:r/i>.5?"Research":n/i>.5?"Exploration":o/i>.3?"Implementation":s/i>.3&&o/i<.15?"Verification":`Phase ${e}`}var mc=class{constructor(e){this._N=e,this._disabled=e<=0,this._phaseNum=0,this._stepsThisPhase=0,this._phaseCounts=new Map,this._phaseStart=Date.now()}record(e,n,o,s){if(this._disabled)return null;this._stepsThisPhase++;for(let i of n)this._phaseCounts.set(i,(this._phaseCounts.get(i)||0)+1);if(this._stepsThisPhase<this._N)return null;this._phaseNum++;let r={phaseNum:this._phaseNum,phaseName:Sf(this._phaseCounts,this._phaseNum),stepCount:this._stepsThisPhase,toolCounts:new Map(this._phaseCounts),elapsed:Date.now()-this._phaseStart,filesRead:new Set(o),filesModified:new Set(s)};return this._stepsThisPhase=0,this._phaseCounts=new Map,this._phaseStart=Date.now(),r}};Ef.exports={MilestoneTracker:mc,_phaseName:Sf}});var Ao=Q((vA,Rf)=>{var Co=ct(),v$={"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 S$(){return Co.getActiveModel()}function E$(t){return Co.setActiveModel(t)}function T$(){return Co.getModelNames()}function R$(t){if(!t)return null;if(typeof t=="object")return t;try{return JSON.parse(t)}catch{}try{let o=t.replace(/,\s*([}\]])/g,"$1").replace(/'/g,'"');return JSON.parse(o)}catch{}let e=t.match(/\{[\s\S]*\}/);if(e)try{return JSON.parse(e[0])}catch{}try{let o=t.replace(/(\{|,)\s*([a-zA-Z_]\w*)\s*:/g,'$1"$2":');return JSON.parse(o)}catch{}let n=t.match(/```(?:json)?\s*([\s\S]*?)```/);if(n)try{return JSON.parse(n[1].trim())}catch{}return null}async function C$(t,e){let{C:n}=rt(),{Spinner:o}=rt(),s=new o("Thinking...");s.start();let r=!0,i="";try{let a=await Co.callStream(t,e,{onToken:c=>{r&&(s.stop(),process.stdout.write(`${n.blue}`),r=!1),process.stdout.write(c),i+=c}});return r?s.stop():process.stdout.write(`${n.reset}
76
+ `),a}catch(a){throw s.stop(),a}}async function A$(t,e){return Co.callChat(t,e)}Rf.exports={MODELS:v$,getActiveModel:S$,setActiveModel:E$,getModelNames:T$,callOllamaStream:C$,callOllama:A$,parseToolArgs:R$}});var No=Q((SA,Pf)=>{var O$=require("readline"),{C:an}=rt(),N$=/[\u200B\u200C\u200D\uFEFF\u2060\u00AD]/g,M$=/^=([\w-]+)/;function Oo(t){return typeof t!="string"?t:t.replace(N$,"").replace(M$,"$1")}var wc=[/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/],Cf=[...wc,/\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 P$(t){for(let e of Cf)if(e.test(t))return e;return null}var Af=[/\.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)/],L$=/\b(?:rm|rmdir|unlink|truncate|shred|mv|cp)\b/,gc=[/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 Of(t){let e=t.match(/ssh\s+[^"]*"([^"]+)"/)?.[1]||t.match(/ssh\s+[^']*'([^']+)'/)?.[1];if(!e)return!1;let o=e.replace(/\bfor\s[\s\S]*?\bdone\b/g,r=>r.replace(/;/g,"\0")).replace(/\bwhile\s[\s\S]*?\bdone\b/g,r=>r.replace(/;/g,"\0")).split(/\s*(?:&&|;)\s*/).map(r=>r.replace(/\x00/g,";").trim()).filter(Boolean);if(o.length===0)return!1;let s=r=>{let i=r.replace(/^sudo\s+(?:-[ugCD]\s+\S+\s+|-[A-Za-z]+\s+)*/,"");if(/^\s*(?:echo|printf)\s/.test(i))return!0;if(/^\s*for\s/.test(r)||/^\s*while\s/.test(r)){let a=r.match(/\bdo\s+([\s\S]*?)\s*(?:done|$)/)?.[1];return a?a.split(/\s*;\s*/).map(u=>u.trim()).filter(Boolean).every(u=>s(u)):gc.some(c=>c.test(r))}return/^\w+=\$?\(/.test(i)||/^\w+=["']/.test(i)||/^\w+=\S/.test(i)?!0:gc.some(a=>a.test(i))};return o.every(s)}var bc=[/rm\s+-rf\s/,/docker\s+system\s+prune/,/kubectl\s+delete/,/sudo\s/,/--no-verify\b/,/git\s+reset\s+--hard\b/,/git\s+clean\s+-[a-z]*f/,/git\s+checkout\s+--\s/,/git\s+push\s+(?:--force\b|-f\b)/,/\b(?:curl|wget|fetch)\b[^|;&`$()]*\|\s*(?:sh|bash|zsh|ksh|dash|python|python3|perl|ruby|node)\b/,/\b(?:curl|wget)\b[^;&`$()]*\$\([^)]*\)/,/\bbase64\s+(?:-d|--decode|-D)\b[^|;&`$()]*\|\s*(?:sh|bash|zsh|python|python3|perl|ruby|node)\b/,/\beval\s+["'`]?\$\(\s*(?:curl|wget|fetch)\b/,/\bbash\s+-i\s*>&?\s*\/dev\/tcp\//,/\bnc\s+(?:-[a-z]*e|-[a-z]*c)\b/,/\bmkfifo\b[^;&`]*;\s*(?:nc|ncat|telnet)\b/],Nf=[/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/],Mf=[...bc,...Nf],$c=!1,Zn=null,yc=null;function I$(t){$c=t}function j$(t){yc=t}function D$(){return $c}function q$(t){Zn=t}function F$(t){let e=Oo(t);for(let n of wc)if(n.test(e))return n;return null}function B$(t){let e=Oo(t);if(/ssh\s/.test(e)&&Of(e))return!1;for(let n of Mf)if(n.test(e))return!0;return!1}function U$(t){let e=Oo(t);for(let n of bc)if(n.test(e))return!0;return!1}function W$(t){if(process.env.NEX_UNPROTECT==="1")return null;let e=Oo(t);if(!L$.test(e))return null;for(let n of Af)if(n.test(e))return n;return null}function H$(t,e={}){if($c)return Promise.resolve(!0);if(yc)return yc(t,e);if(!process.stdout.isTTY||!process.stdin.isTTY)return Y$(t,e);let n=e.toolName?["Yes","No","Always allow"]:["Yes","No"];return new Promise(o=>{let s=0;Zn&&Zn.pause();let r=global._nexRawWrite||(d=>process.stdout.write(d)),i=()=>{let d=process.stdout.rows||24;return Math.max(1,d-n.length-2)},a=()=>{let d=i();global._nexRawWrite&&d>1&&global._nexRawWrite(`\x1B[1;${d-1}r`);let f=`\x1B[${d};1H\x1B[2K${an.yellow}${t}${an.reset}`;for(let p=0;p<n.length;p++){let h=p===s,g=h?`${an.yellow}\u276F${an.reset}`:" ",w=h?`${an.yellow}${n[p]}${an.reset}`:n[p];f+=`\x1B[${d+1+p};1H\x1B[2K ${g} ${w}`}r(f)},c=d=>{process.stdin.setRawMode(!1),process.stdin.pause(),process.stdin.removeListener("data",l);let f=global._nexRawWrite||(g=>process.stdout.write(g)),p=i(),h="";for(let g=0;g<n.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(),Zn&&Zn.resume(),o(d)},u=d=>{if(d===1){c(!1);return}d===2&&e.toolName&&ai(e.toolName),c(!0)},l=d=>{if(d[0]===3){c(!1);return}let f=d.toString();if(f==="\r"||f===`
77
+ `){u(s);return}if(f==="\x1B[A"){s=(s-1+n.length)%n.length,a();return}if(f==="\x1B[B"){s=(s+1)%n.length,a();return}let p=f.toLowerCase().trim();if(p==="y"){c(!0);return}if(p==="n"){c(!1);return}if(p==="a"&&e.toolName){ai(e.toolName),c(!0);return}};a(),process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",l)})}function Y$(t,e){let n=e.toolName?"[Y/n/a] ":"[Y/n] ";return new Promise(o=>{let s=r=>{let i=r.trim().toLowerCase();i==="a"&&e.toolName?(ai(e.toolName),o(!0)):o(i!=="n")};if(Zn)Zn.question(`${an.yellow}${t} ${n}${an.reset}`,s);else{let r=O$.createInterface({input:process.stdin,output:process.stdout});r.question(`${an.yellow}${t} ${n}${an.reset}`,i=>{r.close(),s(i)})}})}var ai=()=>{};function G$(t){ai=t}Pf.exports={sanitizeBashCommand:Oo,FORBIDDEN_PATTERNS:wc,SSH_FORBIDDEN_PATTERNS:Cf,BASH_PROTECTED_PATHS:Af,SSH_SAFE_PATTERNS:gc,isSSHReadOnly:Of,DANGEROUS_BASH:Mf,CRITICAL_BASH:bc,NOTABLE_BASH:Nf,isForbidden:F$,isSSHForbidden:P$,isDangerous:B$,isCritical:U$,isBashPathForbidden:W$,confirm:H$,setAutoConfirm:I$,getAutoConfirm:D$,setConfirmHook:j$,setReadlineInterface:q$,setAllowAlwaysHandler:G$}});var jf=Q((TA,If)=>{var ci=require("path"),{C:q}=rt(),{T:_c,isDark:EA}=Kt(),{confirm:z$,getAutoConfirm:K$}=No(),Lf=2e3;function Mo(t,e){let n=t.split(`
78
78
  `),o=e.split(`
79
- `),s=[],r=n.length,i=o.length;if(r>Pf||i>Pf){for(let d of n)s.push({type:"remove",line:d});for(let d of o)s.push({type:"add",line:d});return s}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++)n[d-1]===o[f-1]?a[d][f]=a[d-1][f-1]+1:a[d][f]=Math.max(a[d-1][f],a[d][f-1]);let c=r,u=i,l=[];for(;c>0||u>0;)c>0&&u>0&&n[c-1]===o[u-1]?(l.unshift({type:"same",line:n[c-1]}),c--,u--):u>0&&(c===0||a[c][u-1]>=a[c-1][u])?(l.unshift({type:"add",line:o[u-1]}),u--):(l.unshift({type:"remove",line:n[c-1]}),c--);return l}function X$(t,e,n,o=3){console.log(`
79
+ `),s=[],r=n.length,i=o.length;if(r>Lf||i>Lf){for(let d of n)s.push({type:"remove",line:d});for(let d of o)s.push({type:"add",line:d});return s}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++)n[d-1]===o[f-1]?a[d][f]=a[d-1][f-1]+1:a[d][f]=Math.max(a[d-1][f],a[d][f-1]);let c=r,u=i,l=[];for(;c>0||u>0;)c>0&&u>0&&n[c-1]===o[u-1]?(l.unshift({type:"same",line:n[c-1]}),c--,u--):u>0&&(c===0||a[c][u-1]>=a[c-1][u])?(l.unshift({type:"add",line:o[u-1]}),u--):(l.unshift({type:"remove",line:n[c-1]}),c--);return l}function X$(t,e,n,o=3){console.log(`
80
80
  ${q.bold}${q.cyan} Diff: ${t}${q.reset}`);let s=Mo(e,n),r=[];if(s.forEach((c,u)=>{c.type!=="same"&&r.push(u)}),r.length===0){console.log(`${q.gray} (no changes)${q.reset}`);return}let i=Math.max(0,r[0]-o),a=Math.min(s.length,r[r.length-1]+o+1);i>0&&console.log(`${q.gray} ...${q.reset}`);for(let c=i;c<a;c++){let u=s[c];switch(u.type){case"remove":console.log(`${q.red} - ${u.line}${q.reset}`);break;case"add":console.log(`${q.green} + ${u.line}${q.reset}`);break;default:console.log(`${q.gray} ${u.line}${q.reset}`)}}a<s.length&&console.log(`${q.gray} ...${q.reset}`),console.log()}function V$(t,e,n){console.log(`
81
81
  ${q.bold}${q.cyan} File exists \u2014 showing changes: ${t}${q.reset}`);let o=Mo(e,n),s=0;for(let i of o)i.type!=="same"&&s++;if(s===0){console.log(`${q.gray} (identical content)${q.reset}`);return}let r=0;for(let i of o){if(r>=30){console.log(`${q.gray} ...(${s-r} more changes)${q.reset}`);break}switch(i.type){case"remove":console.log(`${q.red} - ${i.line}${q.reset}`),r++;break;case"add":console.log(`${q.green} + ${i.line}${q.reset}`),r++;break;default:r>0&&console.log(`${q.gray} ${i.line}${q.reset}`)}}console.log()}function J$(t,e){console.log(`
82
82
  ${q.bold}${q.cyan} New file: ${t}${q.reset}`);let n=e.split(`
@@ -86,9 +86,9 @@ ${q.bold}${q.cyan} Side-by-side: ${t}${q.reset}`),console.log(` ${q.dim}${"\u2
86
86
  ${q.green}\u23FA${q.reset} ${q.bold}${s}(${a})${q.reset}`),d===0&&f===0){console.log(` ${q.dim}\u23BF (no changes)${q.reset}
87
87
  `);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(fe=>fe.severity==="error").length,ne=i.filter(fe=>fe.severity==="warn").length,oe=i.filter(fe=>fe.severity==="info").length,ue=[];N>0&&ue.push(`${q.red}${N} error${N!==1?"s":""}${q.dim}`),ne>0&&ue.push(`${q.yellow}${ne} warning${ne!==1?"s":""}${q.dim}`),oe>0&&ue.push(`${q.cyan}${oe} info${oe!==1?"s":""}${q.dim}`),p.push(`found ${ue.join(", ")}`)}console.log(` ${q.dim}\u23BF ${p.join(", ")}${q.reset}`);let g=[];c.forEach((N,ne)=>{N.type!=="same"&&g.push(ne)});let w=[],_=null,S=null;for(let N of g){let ne=Math.max(0,N-r),oe=Math.min(c.length-1,N+r);_===null?(_=ne,S=oe):(ne<=S+1||(w.push([_,S]),_=ne),S=oe)}_!==null&&w.push([_,S]);let A=" ",E=process.stdout.columns||120;function v(N,ne,oe){let ue=oe.replace(/\x1b\[[0-9;]*m/g,""),fe=oe+" ".repeat(Math.max(0,E-ue.length));return`${N}${ne}${fe}${q.reset}`}for(let N=0;N<w.length;N++){N>0&&console.log(`${A}${q.dim}\xB7\xB7\xB7${q.reset}`);let[ne,oe]=w[N];for(let ue=ne;ue<=oe;ue++){let fe=c[ue],ie=fe.newLine!=null?fe.newLine:fe.oldLine,le=String(ie).padStart(4),T=fe.type!=="remove"?i.filter(F=>F.line===fe.newLine):[];fe.type==="remove"?console.log(v(_c.diff_rem_bg,q.red,`${A}${le} - ${fe.line}`)):fe.type==="add"?console.log(v(_c.diff_add_bg,q.green,`${A}${le} + ${fe.line}`)):console.log(`${A}${q.dim}${le} ${q.reset}${fe.line}`);for(let F of T){let ee=q.cyan,be="\u2139";F.severity==="error"?(ee=q.red,be="\u2716"):F.severity==="warn"&&(ee=q.yellow,be="\u26A0"),console.log(`${A} ${ee}${be} ${F.message}${q.reset}`)}}}console.log()}function t_(t,e,n={}){let o=ci.isAbsolute(t)?ci.relative(process.cwd(),t):t,s=e.split(`
88
88
  `),r=n.annotations||[];console.log(`
89
- ${q.green}\u23FA${q.reset} ${q.bold}Create(${o})${q.reset}`);let i=[`${s.length} line${s.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(`${q.red}${d} error${d!==1?"s":""}${q.dim}`),f>0&&h.push(`${q.yellow}${f} warning${f!==1?"s":""}${q.dim}`),p>0&&h.push(`${q.cyan}${p} info${p!==1?"s":""}${q.dim}`),i.push(`found ${h.join(", ")}`)}console.log(` ${q.dim}\u23BF ${i.join(", ")}${q.reset}`);let c=" ",u=process.stdout.columns||120,l=Math.min(s.length,20);for(let d=0;d<l;d++){let f=String(d+1).padStart(4),p=d+1,h=r.filter(S=>S.line===p),g=`${c}${f} + ${s[d]}`,w=g.replace(/\x1b\[[0-9;]*m/g,""),_=g+" ".repeat(Math.max(0,u-w.length));console.log(`${_c.diff_add_bg}${q.green}${_}${q.reset}`);for(let S of h){let A=q.cyan,E="\u2139";S.severity==="error"?(A=q.red,E="\u2716"):S.severity==="warn"&&(A=q.yellow,E="\u26A0"),console.log(`${c} ${A}${E} ${S.message}${q.reset}`)}}s.length>20&&console.log(`${c}${q.dim} ...+${s.length-20} more lines${q.reset}`),console.log()}Lf.exports={diffLines:Mo,showEditDiff:X$,showWriteDiff:V$,showNewFilePreview:J$,confirmFileChange:Z$,showSideBySideDiff:Q$,showDiff:e_,showNewFile:t_}});var di=Q((TA,qf)=>{var jf=require("util").promisify(require("child_process").exec),n_=require("util").promisify(require("child_process").execFile),{C:He}=rt();async function xc(t){try{let{stdout:e}=await jf(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function li(...t){try{let{stdout:e}=await n_("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function s_(){return await xc("git rev-parse --is-inside-work-tree")==="true"}async function o_(){return await xc("git branch --show-current")}async function kc(){try{let{stdout:t}=await jf("git status --porcelain",{cwd:process.cwd(),timeout:3e4});return!t||!t.trim()?[]:t.split(`
90
- `).filter(Boolean).map(e=>{let n=e.substring(0,2).trim(),o=e.substring(3);return{status:n,file:o}})}catch{return[]}}async function ui(t=!1){return await xc(`git diff ${t?"--cached":""}`)||""}async function vc(){return(await kc()).map(e=>e.file)}async function Df(){let t=await vc();if(t.length===0)return null;let e=await ui(),o=await ui(!0)||e,s=0,r=0;if(o){let l=o.split(`
91
- `);for(let d of l)d.startsWith("+")&&!d.startsWith("+++")&&s++,d.startsWith("-")&&!d.startsWith("---")&&r++}else s=t.length;let i="chore",a=t.join(" ").toLowerCase();a.includes("test")?i="test":a.includes("readme")||a.includes("doc")?i="docs":s>r*2?i="feat":r>s?i="refactor":i="fix";let c=t.slice(0,3).map(l=>l.split("/").pop());return{summary:`${i}: update ${c.join(", ")}${t.length>3?` (+${t.length-3} more)`:""}`,type:i,files:t,stats:{additions:s,deletions:r}}}async function r_(t){let n=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await li("checkout","-b",n)!==null?n:null}async function i_(t){return await li("add","-A"),await li("commit","-m",t)?await li("rev-parse","--short","HEAD"):null}async function a_(){let t=await Df();if(!t)return`${He.dim}No changes${He.reset}`;let e=[];e.push(`
89
+ ${q.green}\u23FA${q.reset} ${q.bold}Create(${o})${q.reset}`);let i=[`${s.length} line${s.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(`${q.red}${d} error${d!==1?"s":""}${q.dim}`),f>0&&h.push(`${q.yellow}${f} warning${f!==1?"s":""}${q.dim}`),p>0&&h.push(`${q.cyan}${p} info${p!==1?"s":""}${q.dim}`),i.push(`found ${h.join(", ")}`)}console.log(` ${q.dim}\u23BF ${i.join(", ")}${q.reset}`);let c=" ",u=process.stdout.columns||120,l=Math.min(s.length,20);for(let d=0;d<l;d++){let f=String(d+1).padStart(4),p=d+1,h=r.filter(S=>S.line===p),g=`${c}${f} + ${s[d]}`,w=g.replace(/\x1b\[[0-9;]*m/g,""),_=g+" ".repeat(Math.max(0,u-w.length));console.log(`${_c.diff_add_bg}${q.green}${_}${q.reset}`);for(let S of h){let A=q.cyan,E="\u2139";S.severity==="error"?(A=q.red,E="\u2716"):S.severity==="warn"&&(A=q.yellow,E="\u26A0"),console.log(`${c} ${A}${E} ${S.message}${q.reset}`)}}s.length>20&&console.log(`${c}${q.dim} ...+${s.length-20} more lines${q.reset}`),console.log()}If.exports={diffLines:Mo,showEditDiff:X$,showWriteDiff:V$,showNewFilePreview:J$,confirmFileChange:Z$,showSideBySideDiff:Q$,showDiff:e_,showNewFile:t_}});var di=Q((RA,Ff)=>{var Df=require("util").promisify(require("child_process").exec),n_=require("util").promisify(require("child_process").execFile),{C:He}=rt();async function xc(t){try{let{stdout:e}=await Df(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function li(...t){try{let{stdout:e}=await n_("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function s_(){return await xc("git rev-parse --is-inside-work-tree")==="true"}async function o_(){return await xc("git branch --show-current")}async function kc(){try{let{stdout:t}=await Df("git status --porcelain",{cwd:process.cwd(),timeout:3e4});return!t||!t.trim()?[]:t.split(`
90
+ `).filter(Boolean).map(e=>{let n=e.substring(0,2).trim(),o=e.substring(3);return{status:n,file:o}})}catch{return[]}}async function ui(t=!1){return await xc(`git diff ${t?"--cached":""}`)||""}async function vc(){return(await kc()).map(e=>e.file)}async function qf(){let t=await vc();if(t.length===0)return null;let e=await ui(),o=await ui(!0)||e,s=0,r=0;if(o){let l=o.split(`
91
+ `);for(let d of l)d.startsWith("+")&&!d.startsWith("+++")&&s++,d.startsWith("-")&&!d.startsWith("---")&&r++}else s=t.length;let i="chore",a=t.join(" ").toLowerCase();a.includes("test")?i="test":a.includes("readme")||a.includes("doc")?i="docs":s>r*2?i="feat":r>s?i="refactor":i="fix";let c=t.slice(0,3).map(l=>l.split("/").pop());return{summary:`${i}: update ${c.join(", ")}${t.length>3?` (+${t.length-3} more)`:""}`,type:i,files:t,stats:{additions:s,deletions:r}}}async function r_(t){let n=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await li("checkout","-b",n)!==null?n:null}async function i_(t){return await li("add","-A"),await li("commit","-m",t)?await li("rev-parse","--short","HEAD"):null}async function a_(){let t=await qf();if(!t)return`${He.dim}No changes${He.reset}`;let e=[];e.push(`
92
92
  ${He.bold}${He.cyan}Git Diff Summary:${He.reset}`),e.push(` ${He.green}+${t.stats.additions}${He.reset} ${He.red}-${t.stats.deletions}${He.reset} in ${t.files.length} file(s)`),e.push(`
93
93
  ${He.bold}${He.cyan}Files:${He.reset}`);for(let n of t.files.slice(0,20))e.push(` ${He.dim}${n}${He.reset}`);return t.files.length>20&&e.push(` ${He.dim}...+${t.files.length-20} more${He.reset}`),e.push(`
94
94
  ${He.bold}${He.cyan}Suggested message:${He.reset}`),e.push(` ${He.cyan}${t.summary}${He.reset}
@@ -97,25 +97,25 @@ ${He.bold}${He.cyan}Suggested message:${He.reset}`),e.push(` ${He.cyan}${t.summ
97
97
  ...(truncated)`:n;e.push(`
98
98
  DIFF:
99
99
  ${o}`)}return e.join(`
100
- `)}qf.exports={isGitRepo:s_,getCurrentBranch:o_,getStatus:kc,getDiff:ui,getChangedFiles:vc,analyzeDiff:Df,createBranch:r_,commit:i_,formatDiffSummary:a_,getDiffContext:l_,getMergeConflicts:c_}});var zf=Q((CA,Gf)=>{var lt=require("fs").promises,RA=require("fs"),jt=require("path"),u_=require("crypto"),{execSync:Sc,execFileSync:Uf}=require("child_process"),d_=100*1024,Wf=50,_t=[],Gs=[];function f_(t,e,n,o){for(_t.push({tool:t,filePath:e,oldContent:n,newContent:o,timestamp:Date.now()});_t.length>Wf;)_t.shift();Gs.length=0,Hf(_t[_t.length-1]).catch(()=>{})}async function p_(){if(_t.length===0)return null;let t=_t.pop();if(t.oldContent===null)try{await lt.unlink(t.filePath)}catch{}else await lt.writeFile(t.filePath,t.oldContent,"utf-8");return Gs.push(t),{tool:t.tool,filePath:t.filePath,wasCreated:t.oldContent===null}}async function h_(){if(Gs.length===0)return null;let t=Gs.pop();return await lt.writeFile(t.filePath,t.newContent,"utf-8"),_t.push(t),{tool:t.tool,filePath:t.filePath}}function m_(t=10){return _t.slice(-t).reverse().map(e=>({tool:e.tool,filePath:e.filePath,timestamp:e.timestamp}))}function g_(){return _t.length}function y_(){return Gs.length}function w_({diskToo:t=!0}={}){if(_t.length=0,Gs.length=0,t){let e=pi();lt.readdir(e).then(n=>{for(let o of n)o.endsWith(".json")&&lt.unlink(jt.join(e,o)).catch(()=>{})}).catch(()=>{})}}function pi(){return jt.join(process.cwd(),".nex","history")}async function Ff(t,e){if(t==null)return{inline:!0,content:t};if(Buffer.byteLength(t,"utf-8")<=d_)return{inline:!0,content:t};let n=u_.createHash("sha256").update(t,"utf-8").digest("hex"),o=jt.join(e,"blobs");return await lt.mkdir(o,{recursive:!0}),await lt.writeFile(jt.join(o,n),t,"utf-8"),{inline:!1,hash:n}}async function Hf(t){let e=pi();await lt.mkdir(e,{recursive:!0});let n=jt.basename(t.filePath).replace(/[^a-zA-Z0-9]/g,"-"),o=`${t.timestamp}-${n}.json`,s=await Ff(t.oldContent,e),r=await Ff(t.newContent,e),i={tool:t.tool,filePath:t.filePath,timestamp:t.timestamp,oldContent:s.inline?{inline:!0,content:s.content}:{inline:!1,hash:s.hash},newContent:r.inline?{inline:!0,content:r.content}:{inline:!1,hash:r.hash}};await lt.writeFile(jt.join(e,o),JSON.stringify(i),"utf-8")}async function Bf(t,e){if(!t)return null;if(t.inline)return t.content;let n=jt.join(e,"blobs",t.hash);return lt.readFile(n,"utf-8")}async function b_(){let t=pi(),e;try{e=await lt.readdir(t)}catch{return 0}let n=e.filter(s=>s.endsWith(".json")).sort(),o=0;for(let s of n)try{let r=await lt.readFile(jt.join(t,s),"utf-8"),i=JSON.parse(r),a=await Bf(i.oldContent,t),c=await Bf(i.newContent,t);_t.push({tool:i.tool,filePath:i.filePath,timestamp:i.timestamp,oldContent:a,newContent:c}),o++}catch{}for(;_t.length>Wf;)_t.shift();return o}async function $_(t=7){let e=pi(),n;try{n=await lt.readdir(e)}catch{return 0}let o=Date.now()-t*24*60*60*1e3,s=n.filter(u=>u.endsWith(".json")),r=0,i=new Set,a=[];for(let u of s)try{let l=await lt.readFile(jt.join(e,u),"utf-8"),d=JSON.parse(l);d.timestamp<o?(a.push(u),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 u of a)try{await lt.unlink(jt.join(e,u))}catch{}let c=jt.join(e,"blobs");try{let u=await lt.readdir(c);for(let l of u)if(!i.has(l))try{await lt.unlink(jt.join(c,l))}catch{}}catch{}return r}var fi="nex-snapshot";function __(t,e=process.cwd()){let n=t?`${fi}-${t.replace(/[^a-zA-Z0-9_-]/g,"-")}`:`${fi}-${Date.now()}`;try{return Sc("git status --porcelain",{cwd:e,timeout:1e4}).toString().trim()?(Uf("git",["stash","push","-u","-m",n],{cwd:e,timeout:15e3}),Sc("git stash pop",{cwd:e,timeout:1e4}),{name:n,label:n,ok:!0}):{name:n,label:n,ok:!1,error:"No changes to snapshot (working tree clean)"}}catch(o){return{name:n,label:n,ok:!1,error:o.message}}}function Yf(t=process.cwd()){try{let e=Sc("git stash list",{cwd:t,timeout:1e4}).toString().trim();return e?e.split(`
101
- `).map(n=>{let o=n.match(/^stash@\{(\d+)\}:\s+(?:WIP on [^:]+:\s+\S+\s+|On \S+:\s+)(.*)/);if(!o)return null;let s=o[2].trim();return s.startsWith(fi)?{index:parseInt(o[1],10),label:s,shortName:s.replace(`${fi}-`,""),date:n}:null}).filter(Boolean):[]}catch{return[]}}function x_(t,e=process.cwd()){try{let n=Yf(e);if(n.length===0)return{ok:!1,error:"No snapshots found"};let o;return t===void 0||t==="last"?o=n[0]:typeof t=="number"?o=n.find(s=>s.index===t):o=n.find(s=>s.label===t||s.shortName===t||s.shortName.includes(String(t))),o?(Uf("git",["stash","apply",`stash@{${o.index}}`],{cwd:e,timeout:15e3}),{ok:!0,label:o.label}):{ok:!1,error:`Snapshot not found: ${t}`}}catch(n){return{ok:!1,error:n.message}}}Gf.exports={recordChange:f_,undo:p_,redo:h_,getHistory:m_,getUndoCount:g_,getRedoCount:y_,clearHistory:w_,persistEntry:Hf,loadPersistedHistory:b_,pruneHistory:$_,createSnapshot:__,listSnapshots:Yf,restoreSnapshot:x_}});var Ac=Q((AA,Qf)=>{var De=require("fs"),xt=require("path"),{atomicWrite:k_,withFileLockSync:v_}=Jn(),mt=[];function Po(){return xt.join(process.cwd(),".nex","skills")}function Kf(){return xt.join(process.cwd(),".nex","config.json")}function Xf(){let t=Po();return De.existsSync(t)||De.mkdirSync(t,{recursive:!0}),t}function Rc(){let t=Kf();if(!De.existsSync(t))return[];try{let e=JSON.parse(De.readFileSync(t,"utf-8"));return e.skills&&Array.isArray(e.skills.disabled)?e.skills.disabled:[]}catch{return[]}}function Vf(t){let e=Kf(),n=xt.dirname(e);De.existsSync(n)||De.mkdirSync(n,{recursive:!0}),v_(e,()=>{let o={};if(De.existsSync(e))try{o=JSON.parse(De.readFileSync(e,"utf-8"))}catch{o={}}o.skills||(o.skills={}),o.skills.disabled=t,k_(e,JSON.stringify(o,null,2))})}function Jf(t,e){let n=[];if(typeof t!="object"||t===null)return{valid:!1,errors:["Module must export an object"]};if(t.name!==void 0&&typeof t.name!="string"&&n.push("name must be a string"),t.description!==void 0&&typeof t.description!="string"&&n.push("description must be a string"),t.instructions!==void 0&&typeof t.instructions!="string"&&n.push("instructions must be a string"),t.commands!==void 0)if(!Array.isArray(t.commands))n.push("commands must be an array");else for(let o=0;o<t.commands.length;o++){let s=t.commands[o];(!s.cmd||typeof s.cmd!="string")&&n.push(`commands[${o}].cmd must be a non-empty string`),s.handler!==void 0&&typeof s.handler!="function"&&n.push(`commands[${o}].handler must be a function`)}if(t.tools!==void 0)if(!Array.isArray(t.tools))n.push("tools must be an array");else for(let o=0;o<t.tools.length;o++){let s=t.tools[o];(!s.function||!s.function.name||typeof s.function.name!="string")&&n.push(`tools[${o}].function.name must be a non-empty string`),s.execute!==void 0&&typeof s.execute!="function"&&n.push(`tools[${o}].execute must be a function`)}return{valid:n.length===0,errors:n}}function Zf(t){let e=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(!e)return{triggers:[],body:t};let n=e[1],o=e[2].trim(),s=[],r=!1;for(let i of n.split(`
102
- `)){let a=i.trim();if(/^trigger:\s*$/i.test(a)){r=!0;continue}r&&a.startsWith("- ")?s.push(a.slice(2).trim().replace(/^["']|["']$/g,"")):r&&a&&!a.startsWith("#")&&(r=!1)}return{triggers:s,body:o}}function Ec(t){try{let e=De.readFileSync(t,"utf-8").trim();if(!e)return null;let n=xt.basename(t,".md"),{triggers:o,body:s}=Zf(e);return{name:n,type:"prompt",filePath:t,instructions:s||e,triggers:o,commands:[],tools:[]}}catch{return null}}function Tc(t){try{let e=require(t),{valid:n,errors:o}=Jf(e,t);return n?{name:e.name||xt.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}
100
+ `)}Ff.exports={isGitRepo:s_,getCurrentBranch:o_,getStatus:kc,getDiff:ui,getChangedFiles:vc,analyzeDiff:qf,createBranch:r_,commit:i_,formatDiffSummary:a_,getDiffContext:l_,getMergeConflicts:c_}});var Kf=Q((AA,zf)=>{var lt=require("fs").promises,CA=require("fs"),jt=require("path"),u_=require("crypto"),{execSync:Sc,execFileSync:Wf}=require("child_process"),d_=100*1024,Hf=50,_t=[],Gs=[];function f_(t,e,n,o){for(_t.push({tool:t,filePath:e,oldContent:n,newContent:o,timestamp:Date.now()});_t.length>Hf;)_t.shift();Gs.length=0,Yf(_t[_t.length-1]).catch(()=>{})}async function p_(){if(_t.length===0)return null;let t=_t.pop();if(t.oldContent===null)try{await lt.unlink(t.filePath)}catch{}else await lt.writeFile(t.filePath,t.oldContent,"utf-8");return Gs.push(t),{tool:t.tool,filePath:t.filePath,wasCreated:t.oldContent===null}}async function h_(){if(Gs.length===0)return null;let t=Gs.pop();return await lt.writeFile(t.filePath,t.newContent,"utf-8"),_t.push(t),{tool:t.tool,filePath:t.filePath}}function m_(t=10){return _t.slice(-t).reverse().map(e=>({tool:e.tool,filePath:e.filePath,timestamp:e.timestamp}))}function g_(){return _t.length}function y_(){return Gs.length}function w_({diskToo:t=!0}={}){if(_t.length=0,Gs.length=0,t){let e=pi();lt.readdir(e).then(n=>{for(let o of n)o.endsWith(".json")&&lt.unlink(jt.join(e,o)).catch(()=>{})}).catch(()=>{})}}function pi(){return jt.join(process.cwd(),".nex","history")}async function Bf(t,e){if(t==null)return{inline:!0,content:t};if(Buffer.byteLength(t,"utf-8")<=d_)return{inline:!0,content:t};let n=u_.createHash("sha256").update(t,"utf-8").digest("hex"),o=jt.join(e,"blobs");return await lt.mkdir(o,{recursive:!0}),await lt.writeFile(jt.join(o,n),t,"utf-8"),{inline:!1,hash:n}}async function Yf(t){let e=pi();await lt.mkdir(e,{recursive:!0});let n=jt.basename(t.filePath).replace(/[^a-zA-Z0-9]/g,"-"),o=`${t.timestamp}-${n}.json`,s=await Bf(t.oldContent,e),r=await Bf(t.newContent,e),i={tool:t.tool,filePath:t.filePath,timestamp:t.timestamp,oldContent:s.inline?{inline:!0,content:s.content}:{inline:!1,hash:s.hash},newContent:r.inline?{inline:!0,content:r.content}:{inline:!1,hash:r.hash}};await lt.writeFile(jt.join(e,o),JSON.stringify(i),"utf-8")}async function Uf(t,e){if(!t)return null;if(t.inline)return t.content;let n=jt.join(e,"blobs",t.hash);return lt.readFile(n,"utf-8")}async function b_(){let t=pi(),e;try{e=await lt.readdir(t)}catch{return 0}let n=e.filter(s=>s.endsWith(".json")).sort(),o=0;for(let s of n)try{let r=await lt.readFile(jt.join(t,s),"utf-8"),i=JSON.parse(r),a=await Uf(i.oldContent,t),c=await Uf(i.newContent,t);_t.push({tool:i.tool,filePath:i.filePath,timestamp:i.timestamp,oldContent:a,newContent:c}),o++}catch{}for(;_t.length>Hf;)_t.shift();return o}async function $_(t=7){let e=pi(),n;try{n=await lt.readdir(e)}catch{return 0}let o=Date.now()-t*24*60*60*1e3,s=n.filter(u=>u.endsWith(".json")),r=0,i=new Set,a=[];for(let u of s)try{let l=await lt.readFile(jt.join(e,u),"utf-8"),d=JSON.parse(l);d.timestamp<o?(a.push(u),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 u of a)try{await lt.unlink(jt.join(e,u))}catch{}let c=jt.join(e,"blobs");try{let u=await lt.readdir(c);for(let l of u)if(!i.has(l))try{await lt.unlink(jt.join(c,l))}catch{}}catch{}return r}var fi="nex-snapshot";function __(t,e=process.cwd()){let n=t?`${fi}-${t.replace(/[^a-zA-Z0-9_-]/g,"-")}`:`${fi}-${Date.now()}`;try{return Sc("git status --porcelain",{cwd:e,timeout:1e4}).toString().trim()?(Wf("git",["stash","push","-u","-m",n],{cwd:e,timeout:15e3}),Sc("git stash pop",{cwd:e,timeout:1e4}),{name:n,label:n,ok:!0}):{name:n,label:n,ok:!1,error:"No changes to snapshot (working tree clean)"}}catch(o){return{name:n,label:n,ok:!1,error:o.message}}}function Gf(t=process.cwd()){try{let e=Sc("git stash list",{cwd:t,timeout:1e4}).toString().trim();return e?e.split(`
101
+ `).map(n=>{let o=n.match(/^stash@\{(\d+)\}:\s+(?:WIP on [^:]+:\s+\S+\s+|On \S+:\s+)(.*)/);if(!o)return null;let s=o[2].trim();return s.startsWith(fi)?{index:parseInt(o[1],10),label:s,shortName:s.replace(`${fi}-`,""),date:n}:null}).filter(Boolean):[]}catch{return[]}}function x_(t,e=process.cwd()){try{let n=Gf(e);if(n.length===0)return{ok:!1,error:"No snapshots found"};let o;return t===void 0||t==="last"?o=n[0]:typeof t=="number"?o=n.find(s=>s.index===t):o=n.find(s=>s.label===t||s.shortName===t||s.shortName.includes(String(t))),o?(Wf("git",["stash","apply",`stash@{${o.index}}`],{cwd:e,timeout:15e3}),{ok:!0,label:o.label}):{ok:!1,error:`Snapshot not found: ${t}`}}catch(n){return{ok:!1,error:n.message}}}zf.exports={recordChange:f_,undo:p_,redo:h_,getHistory:m_,getUndoCount:g_,getRedoCount:y_,clearHistory:w_,persistEntry:Yf,loadPersistedHistory:b_,pruneHistory:$_,createSnapshot:__,listSnapshots:Gf,restoreSnapshot:x_}});var Ac=Q((OA,ep)=>{var De=require("fs"),xt=require("path"),{atomicWrite:k_,withFileLockSync:v_}=Jn(),mt=[];function Po(){return xt.join(process.cwd(),".nex","skills")}function Xf(){return xt.join(process.cwd(),".nex","config.json")}function Vf(){let t=Po();return De.existsSync(t)||De.mkdirSync(t,{recursive:!0}),t}function Rc(){let t=Xf();if(!De.existsSync(t))return[];try{let e=JSON.parse(De.readFileSync(t,"utf-8"));return e.skills&&Array.isArray(e.skills.disabled)?e.skills.disabled:[]}catch{return[]}}function Jf(t){let e=Xf(),n=xt.dirname(e);De.existsSync(n)||De.mkdirSync(n,{recursive:!0}),v_(e,()=>{let o={};if(De.existsSync(e))try{o=JSON.parse(De.readFileSync(e,"utf-8"))}catch{o={}}o.skills||(o.skills={}),o.skills.disabled=t,k_(e,JSON.stringify(o,null,2))})}function Zf(t,e){let n=[];if(typeof t!="object"||t===null)return{valid:!1,errors:["Module must export an object"]};if(t.name!==void 0&&typeof t.name!="string"&&n.push("name must be a string"),t.description!==void 0&&typeof t.description!="string"&&n.push("description must be a string"),t.instructions!==void 0&&typeof t.instructions!="string"&&n.push("instructions must be a string"),t.commands!==void 0)if(!Array.isArray(t.commands))n.push("commands must be an array");else for(let o=0;o<t.commands.length;o++){let s=t.commands[o];(!s.cmd||typeof s.cmd!="string")&&n.push(`commands[${o}].cmd must be a non-empty string`),s.handler!==void 0&&typeof s.handler!="function"&&n.push(`commands[${o}].handler must be a function`)}if(t.tools!==void 0)if(!Array.isArray(t.tools))n.push("tools must be an array");else for(let o=0;o<t.tools.length;o++){let s=t.tools[o];(!s.function||!s.function.name||typeof s.function.name!="string")&&n.push(`tools[${o}].function.name must be a non-empty string`),s.execute!==void 0&&typeof s.execute!="function"&&n.push(`tools[${o}].execute must be a function`)}return{valid:n.length===0,errors:n}}function Qf(t){let e=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(!e)return{triggers:[],body:t};let n=e[1],o=e[2].trim(),s=[],r=!1;for(let i of n.split(`
102
+ `)){let a=i.trim();if(/^trigger:\s*$/i.test(a)){r=!0;continue}r&&a.startsWith("- ")?s.push(a.slice(2).trim().replace(/^["']|["']$/g,"")):r&&a&&!a.startsWith("#")&&(r=!1)}return{triggers:s,body:o}}function Ec(t){try{let e=De.readFileSync(t,"utf-8").trim();if(!e)return null;let n=xt.basename(t,".md"),{triggers:o,body:s}=Qf(e);return{name:n,type:"prompt",filePath:t,instructions:s||e,triggers:o,commands:[],tools:[]}}catch{return null}}function Tc(t){try{let e=require(t),{valid:n,errors:o}=Zf(e,t);return n?{name:e.name||xt.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}
103
103
  ${o.join(`
104
104
  `)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function Cc(){mt=[];let t=Rc(),e=Po(),n=[];if(De.existsSync(e))try{n=De.readdirSync(e)}catch{n=[]}for(let s of n){let r=xt.join(e,s),i;try{i=De.statSync(r)}catch{continue}if(!i.isFile())continue;let a=null;s.endsWith(".md")?a=Ec(r):s.endsWith(".js")&&(a=Tc(r)),a&&(a.enabled=!t.includes(a.name),mt.push(a))}let o=xt.join(__dirname,"skills");if(!process.env.NEX_SKIP_BUILTIN_SKILLS&&De.existsSync(o)){let s;try{s=De.readdirSync(o).filter(r=>r.endsWith(".md")||r.endsWith(".js"))}catch{s=[]}for(let r of s){let i=xt.join(o,r),a=xt.basename(r,xt.extname(r));if(mt.some(l=>l.name===a))continue;let c;try{c=De.statSync(i)}catch{continue}if(!c.isFile())continue;let u=r.endsWith(".md")?Ec(i):Tc(i);u&&(u._builtin=!0,u.enabled=!t.includes(u.name),mt.push(u))}}return mt}function S_(){let t=[];for(let e of mt)!e.enabled||!e.instructions||t.push(`[Skill: ${e.name}]
105
105
  ${e.instructions}`);return t.length===0?"":`SKILL INSTRUCTIONS:
106
106
  ${t.join(`
107
107
 
108
- `)}`}function E_(){let t=[];for(let e of mt)if(e.enabled)for(let n of e.commands)t.push({cmd:n.cmd,desc:n.desc||`[skill: ${e.name}]`});return t}function T_(){let t=[];for(let e of mt)if(e.enabled)for(let n of e.tools)t.push({type:"function",function:{name:`skill_${n.function.name}`,description:`[Skill:${e.name}] ${n.function.description}`,parameters:n.function.parameters}});return t}async function R_(t,e){if(!t.startsWith("skill_"))return null;let n=t.substring(6);for(let o of mt)if(o.enabled){for(let s of o.tools)if(s.function.name===n&&s.execute)try{let r=await s.execute(e);return typeof r=="string"?r:JSON.stringify(r)}catch(r){return`ERROR: Skill tool '${n}' failed: ${r.message}`}}return`ERROR: Skill tool '${n}' not found`}function C_(t){let[e,...n]=t.split(/\s+/),o=n.join(" ").trim();for(let s of mt)if(s.enabled){for(let r of s.commands)if(r.cmd===e&&r.handler){try{let i=r.handler(o);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 A_(){return mt.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 O_(t){let e=mt.find(o=>o.name===t);if(!e)return!1;e.enabled=!0;let n=Rc().filter(o=>o!==t);return Vf(n),!0}function N_(t){let e=mt.find(o=>o.name===t);if(!e)return!1;e.enabled=!1;let n=Rc();return n.includes(t)||(n.push(t),Vf(n)),!0}function M_(){return mt}async function P_(t,e={}){let{execFileSync:n}=require("child_process"),o=Xf(),s=t;/^[\w-]+\/[\w.-]+$/.test(t)&&(s=`https://github.com/${t}.git`);let r=e.name||xt.basename(s,".git").replace(/^nex-skill-/,""),i=xt.join(o,r);if(De.existsSync(i))return{ok:!1,name:r,error:`Skill "${r}" is already installed at ${i}. Remove it first to reinstall.`};try{if(!/^https?:\/\/[a-zA-Z0-9._\-/:.@]+$/.test(s))throw new Error(`Invalid git URL: ${s}`);n("git",["clone","--depth","1",s,i],{timeout:3e4,stdio:"pipe"})}catch(l){return{ok:!1,name:r,error:`Git clone failed: ${l.stderr?.toString().trim()||l.message}`}}let a=xt.join(i,"skill.json"),c=De.existsSync(a),u=De.readdirSync(i).some(l=>(l.endsWith(".md")||l.endsWith(".js"))&&!l.startsWith("."));if(!c&&!u){try{De.rmSync(i,{recursive:!0,force:!0})}catch(l){console.error("skills.js line 562 failed:",l.message)}return{ok:!1,name:r,error:"No skill.json manifest or .md/.js skill file found in repository"}}if(c)try{let l=JSON.parse(De.readFileSync(a,"utf-8"));l.name||(l.name=r)}catch{try{De.rmSync(i,{recursive:!0,force:!0})}catch{}return{ok:!1,name:r,error:"Invalid skill.json \u2014 not valid JSON"}}return Cc(),{ok:!0,name:r}}async function L_(t){let e=require("axios");try{let n=encodeURIComponent(`nex-skill ${t} OR nex-code-skill ${t}`);return((await e.get(`https://api.github.com/search/repositories?q=${n}&sort=stars&per_page=10`,{timeout:1e4,headers:{Accept:"application/vnd.github.v3+json"}})).data.items||[]).map(s=>({name:s.name.replace(/^nex-skill-/,""),description:s.description||"(no description)",url:s.clone_url,stars:s.stargazers_count,owner:s.owner.login}))}catch(n){return[{name:"error",description:`Search failed: ${n.message}`,url:"",stars:0,owner:""}]}}function I_(t){let e=xt.join(Po(),t);if(!De.existsSync(e))return{ok:!1,error:`Skill "${t}" not found in ${Po()}`};try{return De.rmSync(e,{recursive:!0,force:!0}),Cc(),{ok:!0}}catch(n){return{ok:!1,error:n.message}}}function j_(t){if(!t)return[];let e=t.toLowerCase(),n=[];for(let o of mt){if(!o.enabled||!o.triggers||o.triggers.length===0)continue;if(o.triggers.some(r=>e.includes(r.toLowerCase()))){let r=(o.instructions||"").split(`
108
+ `)}`}function E_(){let t=[];for(let e of mt)if(e.enabled)for(let n of e.commands)t.push({cmd:n.cmd,desc:n.desc||`[skill: ${e.name}]`});return t}function T_(){let t=[];for(let e of mt)if(e.enabled)for(let n of e.tools)t.push({type:"function",function:{name:`skill_${n.function.name}`,description:`[Skill:${e.name}] ${n.function.description}`,parameters:n.function.parameters}});return t}async function R_(t,e){if(!t.startsWith("skill_"))return null;let n=t.substring(6);for(let o of mt)if(o.enabled){for(let s of o.tools)if(s.function.name===n&&s.execute)try{let r=await s.execute(e);return typeof r=="string"?r:JSON.stringify(r)}catch(r){return`ERROR: Skill tool '${n}' failed: ${r.message}`}}return`ERROR: Skill tool '${n}' not found`}function C_(t){let[e,...n]=t.split(/\s+/),o=n.join(" ").trim();for(let s of mt)if(s.enabled){for(let r of s.commands)if(r.cmd===e&&r.handler){try{let i=r.handler(o);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 A_(){return mt.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 O_(t){let e=mt.find(o=>o.name===t);if(!e)return!1;e.enabled=!0;let n=Rc().filter(o=>o!==t);return Jf(n),!0}function N_(t){let e=mt.find(o=>o.name===t);if(!e)return!1;e.enabled=!1;let n=Rc();return n.includes(t)||(n.push(t),Jf(n)),!0}function M_(){return mt}async function P_(t,e={}){let{execFileSync:n}=require("child_process"),o=Vf(),s=t;/^[\w-]+\/[\w.-]+$/.test(t)&&(s=`https://github.com/${t}.git`);let r=e.name||xt.basename(s,".git").replace(/^nex-skill-/,""),i=xt.join(o,r);if(De.existsSync(i))return{ok:!1,name:r,error:`Skill "${r}" is already installed at ${i}. Remove it first to reinstall.`};try{if(!/^https?:\/\/[a-zA-Z0-9._\-/:.@]+$/.test(s))throw new Error(`Invalid git URL: ${s}`);n("git",["clone","--depth","1",s,i],{timeout:3e4,stdio:"pipe"})}catch(l){return{ok:!1,name:r,error:`Git clone failed: ${l.stderr?.toString().trim()||l.message}`}}let a=xt.join(i,"skill.json"),c=De.existsSync(a),u=De.readdirSync(i).some(l=>(l.endsWith(".md")||l.endsWith(".js"))&&!l.startsWith("."));if(!c&&!u){try{De.rmSync(i,{recursive:!0,force:!0})}catch(l){console.error("skills.js line 562 failed:",l.message)}return{ok:!1,name:r,error:"No skill.json manifest or .md/.js skill file found in repository"}}if(c)try{let l=JSON.parse(De.readFileSync(a,"utf-8"));l.name||(l.name=r)}catch{try{De.rmSync(i,{recursive:!0,force:!0})}catch{}return{ok:!1,name:r,error:"Invalid skill.json \u2014 not valid JSON"}}return Cc(),{ok:!0,name:r}}async function L_(t){let e=require("axios");try{let n=encodeURIComponent(`nex-skill ${t} OR nex-code-skill ${t}`);return((await e.get(`https://api.github.com/search/repositories?q=${n}&sort=stars&per_page=10`,{timeout:1e4,headers:{Accept:"application/vnd.github.v3+json"}})).data.items||[]).map(s=>({name:s.name.replace(/^nex-skill-/,""),description:s.description||"(no description)",url:s.clone_url,stars:s.stargazers_count,owner:s.owner.login}))}catch(n){return[{name:"error",description:`Search failed: ${n.message}`,url:"",stars:0,owner:""}]}}function I_(t){let e=xt.join(Po(),t);if(!De.existsSync(e))return{ok:!1,error:`Skill "${t}" not found in ${Po()}`};try{return De.rmSync(e,{recursive:!0,force:!0}),Cc(),{ok:!0}}catch(n){return{ok:!1,error:n.message}}}function j_(t){if(!t)return[];let e=t.toLowerCase(),n=[];for(let o of mt){if(!o.enabled||!o.triggers||o.triggers.length===0)continue;if(o.triggers.some(r=>e.includes(r.toLowerCase()))){let r=(o.instructions||"").split(`
109
109
  `).slice(0,3).join(`
110
- `);n.push({name:o.name,instructions:r})}}return n}Qf.exports={initSkillsDir:Xf,loadAllSkills:Cc,getSkillInstructions:S_,getSkillCommands:E_,getSkillToolDefinitions:T_,routeSkillCall:R_,handleSkillCommand:C_,listSkills:A_,enableSkill:O_,disableSkill:N_,getLoadedSkills:M_,installSkill:P_,searchSkills:L_,removeSkill:I_,matchSkillTriggers:j_,_getSkillsDir:Po,_validateScriptSkill:Jf,_loadMarkdownSkill:Ec,_loadScriptSkill:Tc,_parseFrontmatter:Zf}});var Nc=Q((OA,rp)=>{var{spawn:D_}=require("child_process"),q_=require("path"),ep=require("fs"),_n=new Map;function F_(){return q_.join(process.cwd(),".nex","config.json")}function Oc(){let t=F_();if(!ep.existsSync(t))return{};try{return JSON.parse(ep.readFileSync(t,"utf-8")).mcpServers||{}}catch{return{}}}function hi(t,e,n={},o=1e4){return new Promise((s,r)=>{let i=`${Date.now()}-${Math.random().toString(36).slice(2,6)}`,a=JSON.stringify({jsonrpc:"2.0",id:i,method:e,params:n})+`
110
+ `);n.push({name:o.name,instructions:r})}}return n}ep.exports={initSkillsDir:Vf,loadAllSkills:Cc,getSkillInstructions:S_,getSkillCommands:E_,getSkillToolDefinitions:T_,routeSkillCall:R_,handleSkillCommand:C_,listSkills:A_,enableSkill:O_,disableSkill:N_,getLoadedSkills:M_,installSkill:P_,searchSkills:L_,removeSkill:I_,matchSkillTriggers:j_,_getSkillsDir:Po,_validateScriptSkill:Zf,_loadMarkdownSkill:Ec,_loadScriptSkill:Tc,_parseFrontmatter:Qf}});var Nc=Q((NA,ip)=>{var{spawn:D_}=require("child_process"),q_=require("path"),tp=require("fs"),_n=new Map;function F_(){return q_.join(process.cwd(),".nex","config.json")}function Oc(){let t=F_();if(!tp.existsSync(t))return{};try{return JSON.parse(tp.readFileSync(t,"utf-8")).mcpServers||{}}catch{return{}}}function hi(t,e,n={},o=1e4){return new Promise((s,r)=>{let i=`${Date.now()}-${Math.random().toString(36).slice(2,6)}`,a=JSON.stringify({jsonrpc:"2.0",id:i,method:e,params:n})+`
111
111
  `,c="",u=setTimeout(()=>{d(),r(new Error(`MCP request timeout: ${e}`))},o);function l(f){c+=f.toString();let p=c.split(`
112
- `);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)}`)):s(g.result);return}}catch{}c=p[p.length-1]||""}function d(){clearTimeout(u),t.stdout.removeListener("data",l)}t.stdout.on("data",l);try{t.stdin.write(a)}catch(f){d(),r(new Error(`MCP write failed: ${f.message}`))}})}async function tp(t,e){if(_n.has(t))return _n.get(t);let n=["PATH","HOME","USER","SHELL","LANG","TERM","NODE_ENV"],o={};for(let i of n)process.env[i]&&(o[i]=process.env[i]);let s=D_(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:{...o,...e.env||{}}}),r={name:t,proc:s,tools:[],config:e};try{await hi(s,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.2.0"}});let i=await hi(s,"tools/list",{});return r.tools=i&&i.tools||[],_n.set(t,r),r}catch(i){throw s.kill(),new Error(`Failed to connect MCP server '${t}': ${i.message}`)}}function np(t){let e=_n.get(t);if(!e)return!1;try{e.proc.kill()}catch{}return _n.delete(t),!0}function B_(){for(let[t]of _n)np(t)}async function sp(t,e,n={}){let o=_n.get(t);if(!o)throw new Error(`MCP server not connected: ${t}`);let s=await hi(o.proc,"tools/call",{name:e,arguments:n});return s&&Array.isArray(s.content)?s.content.filter(r=>r.type==="text").map(r=>r.text).join(`
113
- `):JSON.stringify(s)}function op(){let t=[];for(let[e,n]of _n)for(let o of n.tools)t.push({server:e,name:o.name,description:o.description||"",inputSchema:o.inputSchema||{type:"object",properties:{}}});return t}function U_(){return op().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function W_(t,e){if(!t.startsWith("mcp_"))return null;let n=t.substring(4).split("_");if(n.length<2)return null;let o=n[0],s=n.slice(1).join("_");return sp(o,s,e)}function H_(){let t=Oc();return Object.entries(t).map(([e,n])=>{let o=_n.get(e);return{name:e,command:n.command,connected:!!o,toolCount:o?o.tools.length:0}})}async function Y_(){let t=Oc(),e=[];for(let[n,o]of Object.entries(t))try{let s=await tp(n,o);e.push({name:n,tools:s.tools.length})}catch(s){e.push({name:n,tools:0,error:s.message})}return e}rp.exports={loadMCPConfig:Oc,sendRequest:hi,connectServer:tp,disconnectServer:np,disconnectAll:B_,callTool:sp,getAllTools:op,getMCPToolDefinitions:U_,routeMCPCall:W_,listServers:H_,connectAll:Y_}});var gi=Q((NA,lp)=>{var ip=require("fs"),Mc=require("path"),mi=[],Lo=[],Qn={},Io=["onToolResult","onModelResponse","onSessionStart","onSessionEnd","onFileChange","beforeToolExec","afterToolExec"];function ap(t,e){if(!t||!t.function||!t.function.name)return{ok:!1,error:"Tool definition must have function.name"};if(typeof e!="function")return{ok:!1,error:"Handler must be a function"};let n=t.function.name;return Lo.some(o=>o.definition.function.name===n)?{ok:!1,error:`Tool "${n}" is already registered`}:(Lo.push({definition:{type:"function",...t},handler:e}),{ok:!0})}function cp(t,e){return Io.includes(t)?typeof e!="function"?{ok:!1,error:"Handler must be a function"}:(Qn[t]||(Qn[t]=[]),Qn[t].push(e),{ok:!0}):{ok:!1,error:`Unknown event "${t}". Available: ${Io.join(", ")}`}}async function Pc(t,e){let n=Qn[t]||[],o=e;for(let s of n)try{let r=await s(o);r!==void 0&&(o=r)}catch(r){process.env.NEX_DEBUG&&console.error(`[plugin] Hook error on ${t}: ${r.message}`)}return o}function G_(){let t=Mc.join(process.cwd(),".nex","plugins"),e=[];if(!ip.existsSync(t))return{loaded:0,errors:[]};let n=ip.readdirSync(t).filter(s=>s.endsWith(".js")),o={registerTool:ap,registerHook:cp,EVENTS:Io};for(let s of n){let r=Mc.join(t,s);try{let i=require(r);if(typeof i=="function")i(o);else if(typeof i.setup=="function")i.setup(o);else{e.push(`${s}: Plugin must export a function or { setup: function }`);continue}mi.push({name:i.name||Mc.basename(s,".js"),filePath:r})}catch(i){e.push(`${s}: ${i.message}`)}}return{loaded:mi.length,errors:e}}function z_(){return Lo.map(t=>t.definition)}async function K_(t,e,n={}){let o=Lo.find(a=>a.definition.function.name===t);if(!o)return null;let s=await Pc("beforeToolExec",{name:t,args:e,options:n}),r=await o.handler(s.args||e,n);return(await Pc("afterToolExec",{name:t,args:e,result:r})).result||r}function X_(){return[...mi]}function V_(){let t={};for(let e of Io)t[e]=(Qn[e]||[]).length;return t}function J_(){mi.length=0,Lo.length=0;for(let t of Object.keys(Qn))delete Qn[t]}lp.exports={registerTool:ap,registerHook:cp,emit:Pc,loadPlugins:G_,getPluginToolDefinitions:z_,executePluginTool:K_,getLoadedPlugins:X_,getHookCounts:V_,clearPlugins:J_,EVENTS:Io}});var Lc=Q((MA,pp)=>{var{getSkillToolDefinitions:Z_}=Ac(),{getMCPToolDefinitions:Q_}=Nc(),{getPluginToolDefinitions:ex}=gi(),yi=new Map;function up(){let{TOOL_DEFINITIONS:t}=zs();return[...t,...Z_(),...Q_(),...ex()]}function dp(t){if(yi.has(t))return yi.get(t);let n=up().find(s=>s.function.name===t);if(!n)return null;let o=n.function.parameters;return yi.set(t,o),o}function tx(){yi.clear()}function wi(t,e){if(!t||e.length===0)return null;let n=null,o=1/0;for(let s of e){let r=fp(t.toLowerCase(),s.toLowerCase());r<o&&(o=r,n=s)}return o<=Math.ceil(t.length/2)?n:null}function fp(t,e){let n=t.length,o=e.length,s=Array.from({length:n+1},()=>Array(o+1).fill(0));for(let r=0;r<=n;r++)s[r][0]=r;for(let r=0;r<=o;r++)s[0][r]=r;for(let r=1;r<=n;r++)for(let i=1;i<=o;i++)s[r][i]=t[r-1]===e[i-1]?s[r-1][i-1]:1+Math.min(s[r-1][i],s[r][i-1],s[r-1][i-1]);return s[n][o]}function nx(t,e){let n=dp(t);if(n===null){let d=up().map(p=>p.function.name),f=wi(t,d);return{valid:!1,error:`Unknown tool "${t}".${f?` Did you mean "${f}"?`:""}
112
+ `);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)}`)):s(g.result);return}}catch{}c=p[p.length-1]||""}function d(){clearTimeout(u),t.stdout.removeListener("data",l)}t.stdout.on("data",l);try{t.stdin.write(a)}catch(f){d(),r(new Error(`MCP write failed: ${f.message}`))}})}async function np(t,e){if(_n.has(t))return _n.get(t);let n=["PATH","HOME","USER","SHELL","LANG","TERM","NODE_ENV"],o={};for(let i of n)process.env[i]&&(o[i]=process.env[i]);let s=D_(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:{...o,...e.env||{}}}),r={name:t,proc:s,tools:[],config:e};try{await hi(s,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.2.0"}});let i=await hi(s,"tools/list",{});return r.tools=i&&i.tools||[],_n.set(t,r),r}catch(i){throw s.kill(),new Error(`Failed to connect MCP server '${t}': ${i.message}`)}}function sp(t){let e=_n.get(t);if(!e)return!1;try{e.proc.kill()}catch{}return _n.delete(t),!0}function B_(){for(let[t]of _n)sp(t)}async function op(t,e,n={}){let o=_n.get(t);if(!o)throw new Error(`MCP server not connected: ${t}`);let s=await hi(o.proc,"tools/call",{name:e,arguments:n});return s&&Array.isArray(s.content)?s.content.filter(r=>r.type==="text").map(r=>r.text).join(`
113
+ `):JSON.stringify(s)}function rp(){let t=[];for(let[e,n]of _n)for(let o of n.tools)t.push({server:e,name:o.name,description:o.description||"",inputSchema:o.inputSchema||{type:"object",properties:{}}});return t}function U_(){return rp().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function W_(t,e){if(!t.startsWith("mcp_"))return null;let n=t.substring(4).split("_");if(n.length<2)return null;let o=n[0],s=n.slice(1).join("_");return op(o,s,e)}function H_(){let t=Oc();return Object.entries(t).map(([e,n])=>{let o=_n.get(e);return{name:e,command:n.command,connected:!!o,toolCount:o?o.tools.length:0}})}async function Y_(){let t=Oc(),e=[];for(let[n,o]of Object.entries(t))try{let s=await np(n,o);e.push({name:n,tools:s.tools.length})}catch(s){e.push({name:n,tools:0,error:s.message})}return e}ip.exports={loadMCPConfig:Oc,sendRequest:hi,connectServer:np,disconnectServer:sp,disconnectAll:B_,callTool:op,getAllTools:rp,getMCPToolDefinitions:U_,routeMCPCall:W_,listServers:H_,connectAll:Y_}});var gi=Q((MA,up)=>{var ap=require("fs"),Mc=require("path"),mi=[],Lo=[],Qn={},Io=["onToolResult","onModelResponse","onSessionStart","onSessionEnd","onFileChange","beforeToolExec","afterToolExec"];function cp(t,e){if(!t||!t.function||!t.function.name)return{ok:!1,error:"Tool definition must have function.name"};if(typeof e!="function")return{ok:!1,error:"Handler must be a function"};let n=t.function.name;return Lo.some(o=>o.definition.function.name===n)?{ok:!1,error:`Tool "${n}" is already registered`}:(Lo.push({definition:{type:"function",...t},handler:e}),{ok:!0})}function lp(t,e){return Io.includes(t)?typeof e!="function"?{ok:!1,error:"Handler must be a function"}:(Qn[t]||(Qn[t]=[]),Qn[t].push(e),{ok:!0}):{ok:!1,error:`Unknown event "${t}". Available: ${Io.join(", ")}`}}async function Pc(t,e){let n=Qn[t]||[],o=e;for(let s of n)try{let r=await s(o);r!==void 0&&(o=r)}catch(r){process.env.NEX_DEBUG&&console.error(`[plugin] Hook error on ${t}: ${r.message}`)}return o}function G_(){let t=Mc.join(process.cwd(),".nex","plugins"),e=[];if(!ap.existsSync(t))return{loaded:0,errors:[]};let n=ap.readdirSync(t).filter(s=>s.endsWith(".js")),o={registerTool:cp,registerHook:lp,EVENTS:Io};for(let s of n){let r=Mc.join(t,s);try{let i=require(r);if(typeof i=="function")i(o);else if(typeof i.setup=="function")i.setup(o);else{e.push(`${s}: Plugin must export a function or { setup: function }`);continue}mi.push({name:i.name||Mc.basename(s,".js"),filePath:r})}catch(i){e.push(`${s}: ${i.message}`)}}return{loaded:mi.length,errors:e}}function z_(){return Lo.map(t=>t.definition)}async function K_(t,e,n={}){let o=Lo.find(a=>a.definition.function.name===t);if(!o)return null;let s=await Pc("beforeToolExec",{name:t,args:e,options:n}),r=await o.handler(s.args||e,n);return(await Pc("afterToolExec",{name:t,args:e,result:r})).result||r}function X_(){return[...mi]}function V_(){let t={};for(let e of Io)t[e]=(Qn[e]||[]).length;return t}function J_(){mi.length=0,Lo.length=0;for(let t of Object.keys(Qn))delete Qn[t]}up.exports={registerTool:cp,registerHook:lp,emit:Pc,loadPlugins:G_,getPluginToolDefinitions:z_,executePluginTool:K_,getLoadedPlugins:X_,getHookCounts:V_,clearPlugins:J_,EVENTS:Io}});var Lc=Q((PA,hp)=>{var{getSkillToolDefinitions:Z_}=Ac(),{getMCPToolDefinitions:Q_}=Nc(),{getPluginToolDefinitions:ex}=gi(),yi=new Map;function dp(){let{TOOL_DEFINITIONS:t}=zs();return[...t,...Z_(),...Q_(),...ex()]}function fp(t){if(yi.has(t))return yi.get(t);let n=dp().find(s=>s.function.name===t);if(!n)return null;let o=n.function.parameters;return yi.set(t,o),o}function tx(){yi.clear()}function wi(t,e){if(!t||e.length===0)return null;let n=null,o=1/0;for(let s of e){let r=pp(t.toLowerCase(),s.toLowerCase());r<o&&(o=r,n=s)}return o<=Math.ceil(t.length/2)?n:null}function pp(t,e){let n=t.length,o=e.length,s=Array.from({length:n+1},()=>Array(o+1).fill(0));for(let r=0;r<=n;r++)s[r][0]=r;for(let r=0;r<=o;r++)s[0][r]=r;for(let r=1;r<=n;r++)for(let i=1;i<=o;i++)s[r][i]=t[r-1]===e[i-1]?s[r-1][i-1]:1+Math.min(s[r-1][i],s[r][i-1],s[r-1][i-1]);return s[n][o]}function nx(t,e){let n=fp(t);if(n===null){let d=dp().map(p=>p.function.name),f=wi(t,d);return{valid:!1,error:`Unknown tool "${t}".${f?` Did you mean "${f}"?`:""}
114
114
  Available tools: ${d.join(", ")}`}}if(!n||!n.properties)return{valid:!0};let o=n.required||[],s=Object.keys(n.properties),r=Object.keys(e),i=[],a={...e},c=!1;for(let l of o)if(!(l in e)||e[l]===void 0||e[l]===null){let d=wi(l,r);d&&!s.includes(d)?(a[l]=e[d],delete a[d],c=!0):i.push(`Missing required parameter "${l}" (${n.properties[l]?.description||n.properties[l]?.type||"unknown"})`)}new Set(["grep","grep_search","search_files"]).has(t)&&(("-n"in a||"n"in a)&&!s.includes("-n")&&(delete a["-n"],delete a.n,c=!0),("-i"in a||"--ignore-case"in a)&&"ignore_case"in(n.properties||{})&&(a.ignore_case=!0,delete a["-i"],delete a["--ignore-case"],c=!0),("-r"in a||"--recursive"in a)&&(delete a["-r"],delete a["--recursive"],c=!0)),t==="read_file"&&("offset"in a&&!("line_start"in a)&&(a.line_start=a.offset,delete a.offset,c=!0),"start_line"in a&&!("line_start"in a)&&(a.line_start=a.start_line,delete a.start_line,c=!0),"end_line"in a&&!("line_end"in a)&&(a.line_end=a.end_line,delete a.end_line,c=!0));for(let l of Object.keys(a))if(!s.includes(l)){let d=wi(l,s);if(d&&!(d in a))a[d]=a[l],delete a[l],c=!0;else if(!c){let f=d?` Did you mean "${d}"?`:"";i.push(`Unknown parameter "${l}".${f}`)}}for(let l of Object.keys(a)){if(!n.properties[l])continue;let d=n.properties[l].type,f=typeof a[l];d==="string"&&f==="number"?(a[l]=String(a[l]),c=!0):d==="number"&&f==="string"&&!isNaN(a[l])?(a[l]=Number(a[l]),c=!0):d==="boolean"&&f==="string"&&(a[l]=a[l]==="true",c=!0)}return i.length>0&&!c?{valid:!1,error:`Tool "${t}" argument errors:
115
115
  `+i.map(l=>` - ${l}`).join(`
116
116
  `)+`
117
117
 
118
- Expected parameters: ${JSON.stringify(n.properties,null,2)}`}:{valid:!0,corrected:c?a:null}}function sx(t,e){let n=[],o={...t};if(!o.function&&!o.name)return n.push('Tool call missing both "function" and "name" fields'),{valid:!1,normalized:o,errors:n};if(!o.function&&o.name&&(o.function={name:o.name,arguments:o.arguments||o.args||{}},delete o.name,delete o.args),o.function&&o.function.args!==void 0&&o.function.arguments===void 0&&(o.function.arguments=o.function.args,delete o.function.args),o.function&&(o.function.arguments===void 0||o.function.arguments===null)&&(o.function.arguments={}),o.function&&typeof o.function.arguments=="string"){let s=o.function.arguments;if(s.trim()==="")o.function.arguments={};else try{o.function.arguments=JSON.parse(s)}catch(r){return n.push(`Invalid JSON in arguments${e?` (${e})`:""}: ${r.message}`),{valid:!1,normalized:o,errors:n}}}return o.function&&typeof o.function.arguments!="object"?(n.push(`Arguments must be an object, got ${typeof o.function.arguments}`),{valid:!1,normalized:o,errors:n}):!o.function.name||typeof o.function.name!="string"?(n.push("Tool call function name must be a non-empty string"),{valid:!1,normalized:o,errors:n}):{valid:n.length===0,normalized:o,errors:n}}pp.exports={validateToolArgs:nx,validateToolCallFormat:sx,closestMatch:wi,levenshtein:fp,getCachedSchema:dp,clearSchemaCache:tx}});var yp=Q((PA,gp)=>{var{levenshtein:bi}=Lc(),ox=200,rx=.3,ix=2;function Ic(t){return t.replace(/\r\n/g,`
118
+ Expected parameters: ${JSON.stringify(n.properties,null,2)}`}:{valid:!0,corrected:c?a:null}}function sx(t,e){let n=[],o={...t};if(!o.function&&!o.name)return n.push('Tool call missing both "function" and "name" fields'),{valid:!1,normalized:o,errors:n};if(!o.function&&o.name&&(o.function={name:o.name,arguments:o.arguments||o.args||{}},delete o.name,delete o.args),o.function&&o.function.args!==void 0&&o.function.arguments===void 0&&(o.function.arguments=o.function.args,delete o.function.args),o.function&&(o.function.arguments===void 0||o.function.arguments===null)&&(o.function.arguments={}),o.function&&typeof o.function.arguments=="string"){let s=o.function.arguments;if(s.trim()==="")o.function.arguments={};else try{o.function.arguments=JSON.parse(s)}catch(r){return n.push(`Invalid JSON in arguments${e?` (${e})`:""}: ${r.message}`),{valid:!1,normalized:o,errors:n}}}return o.function&&typeof o.function.arguments!="object"?(n.push(`Arguments must be an object, got ${typeof o.function.arguments}`),{valid:!1,normalized:o,errors:n}):!o.function.name||typeof o.function.name!="string"?(n.push("Tool call function name must be a non-empty string"),{valid:!1,normalized:o,errors:n}):{valid:n.length===0,normalized:o,errors:n}}hp.exports={validateToolArgs:nx,validateToolCallFormat:sx,closestMatch:wi,levenshtein:pp,getCachedSchema:fp,clearSchemaCache:tx}});var wp=Q((LA,yp)=>{var{levenshtein:bi}=Lc(),ox=200,rx=.3,ix=2;function Ic(t){return t.replace(/\r\n/g,`
119
119
  `).replace(/\r/g,`
120
120
  `).replace(/\t/g," ".repeat(ix)).split(`
121
121
  `).map(e=>{let n=e.replace(/\s+$/,""),o=n.match(/^(\s*)(.*)/);if(!o)return n;let[,s,r]=o;return s+r.replace(/ {2,}/g," ")}).join(`
@@ -125,31 +125,31 @@ Expected parameters: ${JSON.stringify(n.properties,null,2)}`}:{valid:!0,correcte
125
125
  `),a=i[0],c=i[i.length-1];for(let u=0;u<=r.length-i.length;u++){let l=!0;for(let d=0;d<i.length;d++)if(r[u+d]!==i[d]){l=!1;break}if(l)return s.slice(u,u+i.length).join(`
126
126
  `)}if(i.length===1){for(let u=0;u<r.length;u++)if(r[u].indexOf(o)!==-1)return s[u]}return null}function cx(t,e){if(!t||!e)return null;let n=t.split(`
127
127
  `),s=e.split(`
128
- `).length;return n.length===0||s===0?null:s===1?lx(n,e):dx(n,e,s)}function hp(t){return Math.max(1,Math.floor(t/ox))}function mp(t,e){return t<=Math.ceil(e*rx)}function lx(t,e){let n=e.trim(),o=hp(t.length),s=null,r=1/0;for(let i=0;i<t.length;i+=o){let a=t[i];if(!a.trim())continue;let c=bi(a.trim(),n);c<r&&(r=c,s={text:a,distance:c,line:i+1})}return s&&o>1&&(s=ux(t,n,s,o)||s,r=s.distance),mp(r,e.length)?s:null}function ux(t,e,n,o){let s=n.line-1,r=Math.max(0,s-o),i=Math.min(t.length-1,s+o),a=n.distance,c=null;for(let u=r;u<=i;u++){let l=t[u];if(!l.trim())continue;let d=bi(l.trim(),e);d<a&&(a=d,c={text:l,distance:d,line:u+1})}return c}function dx(t,e,n){let o=t.length-n+1;if(o<=0)return null;let s=hp(o),r=null,i=1/0;for(let a=0;a<o;a+=s){let c=t.slice(a,a+n).join(`
129
- `),u=bi(c,e);u<i&&(i=u,r={text:c,distance:u,line:a+1})}return r&&s>1&&(r=fx(t,e,r,s,n,o)||r,i=r.distance),mp(i,e.length)?r:null}function fx(t,e,n,o,s,r){let i=n.line-1,a=Math.max(0,i-o),c=Math.min(r-1,i+o),u=n.distance,l=null;for(let d=a;d<=c;d++){let f=t.slice(d,d+s).join(`
130
- `),p=bi(f,e);p<u&&(u=p,l={text:f,distance:p,line:d+1})}return l}gp.exports={normalizeWhitespace:Ic,fuzzyFindText:ax,findMostSimilar:cx}});var Ep=Q((LA,Dc)=>{var wp=require("fs"),px=require("path"),{execFileSync:hx}=require("child_process"),bp=["--",".",":!*.lock",":!*.min.js",":!*.min.css",":!package-lock.json",":!yarn.lock",":!dist/",":!tests/hooks-pre-push.test.js"],mx=/(^|\/)(tests\/.*\.test\.(js|ts|jsx|tsx)|__tests__\/.*\.(js|ts|jsx|tsx))$/i,$p=[{category:"OpenAI API Key",regex:/sk-[a-zA-Z0-9]{20,}/i},{category:"Anthropic API Key",regex:/sk-ant-api03-[a-zA-Z0-9-]{90,}/i},{category:"Google Gemini API Key",regex:/AIzaSy[a-zA-Z0-9_-]{30,45}/i},{category:"AWS Access Key",regex:/AKIA[A-Z0-9]{16}/i},{category:"GitHub Token (ghp_)",regex:/ghp_[a-zA-Z0-9]{36}/i},{category:"GitHub OAuth (gho_)",regex:/gho_[a-zA-Z0-9]{36}/i},{category:"GitHub App Token (ghs_)",regex:/ghs_[a-zA-Z0-9]{36}/i},{category:"GitHub Fine-Grained Token",regex:/github_pat_[a-zA-Z0-9_]{20,}/i},{category:"Slack Token",regex:/xox[bpors]-[a-zA-Z0-9-]+/i},{category:"Private Key",regex:/BEGIN (RSA|EC|DSA|OPENSSH|PGP) PRIVATE KEY/i},{category:"Database URL",regex:/\b(postgres|mongodb|mysql|redis):\/\/[^"'\s]+/i},{category:"Credential URL",regex:/\b[a-z][a-z0-9+.-]*:\/\/[^/\s:@]+:[^/\s@]+@[^/\s]+/i},{category:"Hardcoded Secret",regex:/(password|secret|token|api_key|apikey|api_secret|access_token|auth_token|credentials)\s*[:=]\s*['"][^'"]{8,}/i},{category:"SSH + IP",regex:/\bssh\s+.*@[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\b/i},{category:"SSH Config HostName",regex:/\bHostName\s+[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\b/i},{category:"Server IP Assignment",regex:/\b(host|hostname|server|server_ip|public_ip|private_ip|vps_ip|ssh_host|remote_host|db_host)\b\s*[:=]\s*['"]?[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+['"]?/i},{category:".env Secret Assignment",regex:/\b(API_KEY|SECRET_KEY|SECRET|TOKEN|PASSWORD|PRIVATE_KEY|ACCESS_KEY|AUTH_TOKEN|DB_PASSWORD|DATABASE_URL)\s*=/i}],gx=/(^|\/)\.env(?:\.[^/]+)?\.(example|sample|template)$/i,_p=[{category:"Sensitive Env File",regex:/(^|\/)\.env(?:\.[^/]+)?$/i},{category:"Private Key File",regex:/(^|\/)(id_(rsa|dsa|ecdsa|ed25519)(\.pub)?|.*\.key)$/i},{category:"Certificate Bundle",regex:/(^|\/).*\.(p12|pfx|mobileprovision)$/i},{category:"Terraform Secrets",regex:/(^|\/).*\.(tfvars|tfstate)(\..+)?$/i},{category:"Credential File",regex:/(^|\/)(\.npmrc|\.netrc)$/i},{category:"Cloud Credentials",regex:/(^|\/)\.(aws\/credentials|kube\/config)$/i}];function $i(t,e=process.cwd()){return hx("git",t,{cwd:e,encoding:"utf8"})}function yx(t=process.cwd()){return $i(["rev-parse","--show-toplevel"],t).trim()}function wx(t){let e=px.join(t,".nex","push-allowlist");return wp.existsSync(e)?wp.readFileSync(e,"utf8").split(`
131
- `).map(n=>n.trim()).filter(n=>n&&!n.startsWith("#")):[]}function jc(t,e){return e.some(n=>t.includes(n))}function xp(t){return gx.test(t)}function kp(t,e){let n=[];for(let o of t)if(!xp(o))for(let s of _p)s.regex.test(o)&&(jc(o,e)||n.push({category:s.category,location:o,preview:o}));return n}function bx(t){let e=t.split(`
132
- `),n=[],o="";for(let s=0;s<e.length;s++){let r=e[s];if(r.startsWith("+++ b/")){o=r.slice(6);continue}!r.startsWith("+")||r.startsWith("+++")||n.push({filePath:o,lineNumber:s+1,text:r.slice(1),raw:r})}return n}function vp(t,e){let n=[];for(let o of bx(t))if(!mx.test(o.filePath||""))for(let s of $p)s.regex.test(o.text)&&(jc(o.raw,e)||jc(o.text,e)||n.push({category:s.category,location:`${o.lineNumber}:${o.raw}`,preview:o.raw}));return n}function $x(t){return $i(["diff","--cached","--name-only","--diff-filter=ACMR","-z"],t).split("\0").filter(Boolean)}function _x(t,e){return $i(["diff",e,...bp],t)}function xx(t){return $i(["diff","--cached",...bp],t)}function Sp({repoRoot:t,mode:e,range:n}){let o=wx(t),s=e==="staged"?$x(t):[],r=kp(s,o),i=e==="range"?_x(t,n):xx(t),a=vp(i,o);return[...r,...a]}function kx(t){return t.map(e=>` [${e.category}]
128
+ `).length;return n.length===0||s===0?null:s===1?lx(n,e):dx(n,e,s)}function mp(t){return Math.max(1,Math.floor(t/ox))}function gp(t,e){return t<=Math.ceil(e*rx)}function lx(t,e){let n=e.trim(),o=mp(t.length),s=null,r=1/0;for(let i=0;i<t.length;i+=o){let a=t[i];if(!a.trim())continue;let c=bi(a.trim(),n);c<r&&(r=c,s={text:a,distance:c,line:i+1})}return s&&o>1&&(s=ux(t,n,s,o)||s,r=s.distance),gp(r,e.length)?s:null}function ux(t,e,n,o){let s=n.line-1,r=Math.max(0,s-o),i=Math.min(t.length-1,s+o),a=n.distance,c=null;for(let u=r;u<=i;u++){let l=t[u];if(!l.trim())continue;let d=bi(l.trim(),e);d<a&&(a=d,c={text:l,distance:d,line:u+1})}return c}function dx(t,e,n){let o=t.length-n+1;if(o<=0)return null;let s=mp(o),r=null,i=1/0;for(let a=0;a<o;a+=s){let c=t.slice(a,a+n).join(`
129
+ `),u=bi(c,e);u<i&&(i=u,r={text:c,distance:u,line:a+1})}return r&&s>1&&(r=fx(t,e,r,s,n,o)||r,i=r.distance),gp(i,e.length)?r:null}function fx(t,e,n,o,s,r){let i=n.line-1,a=Math.max(0,i-o),c=Math.min(r-1,i+o),u=n.distance,l=null;for(let d=a;d<=c;d++){let f=t.slice(d,d+s).join(`
130
+ `),p=bi(f,e);p<u&&(u=p,l={text:f,distance:p,line:d+1})}return l}yp.exports={normalizeWhitespace:Ic,fuzzyFindText:ax,findMostSimilar:cx}});var Tp=Q((IA,Dc)=>{var bp=require("fs"),px=require("path"),{execFileSync:hx}=require("child_process"),$p=["--",".",":!*.lock",":!*.min.js",":!*.min.css",":!package-lock.json",":!yarn.lock",":!dist/",":!tests/hooks-pre-push.test.js"],mx=/(^|\/)(tests\/.*\.test\.(js|ts|jsx|tsx)|__tests__\/.*\.(js|ts|jsx|tsx))$/i,_p=[{category:"OpenAI API Key",regex:/sk-[a-zA-Z0-9]{20,}/i},{category:"Anthropic API Key",regex:/sk-ant-api03-[a-zA-Z0-9-]{90,}/i},{category:"Google Gemini API Key",regex:/AIzaSy[a-zA-Z0-9_-]{30,45}/i},{category:"AWS Access Key",regex:/AKIA[A-Z0-9]{16}/i},{category:"GitHub Token (ghp_)",regex:/ghp_[a-zA-Z0-9]{36}/i},{category:"GitHub OAuth (gho_)",regex:/gho_[a-zA-Z0-9]{36}/i},{category:"GitHub App Token (ghs_)",regex:/ghs_[a-zA-Z0-9]{36}/i},{category:"GitHub Fine-Grained Token",regex:/github_pat_[a-zA-Z0-9_]{20,}/i},{category:"Slack Token",regex:/xox[bpors]-[a-zA-Z0-9-]+/i},{category:"Private Key",regex:/BEGIN (RSA|EC|DSA|OPENSSH|PGP) PRIVATE KEY/i},{category:"Database URL",regex:/\b(postgres|mongodb|mysql|redis):\/\/[^"'\s]+/i},{category:"Credential URL",regex:/\b[a-z][a-z0-9+.-]*:\/\/[^/\s:@]+:[^/\s@]+@[^/\s]+/i},{category:"Hardcoded Secret",regex:/(password|secret|token|api_key|apikey|api_secret|access_token|auth_token|credentials)\s*[:=]\s*['"][^'"]{8,}/i},{category:"SSH + IP",regex:/\bssh\s+.*@[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\b/i},{category:"SSH Config HostName",regex:/\bHostName\s+[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\b/i},{category:"Server IP Assignment",regex:/\b(host|hostname|server|server_ip|public_ip|private_ip|vps_ip|ssh_host|remote_host|db_host)\b\s*[:=]\s*['"]?[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+['"]?/i},{category:".env Secret Assignment",regex:/\b(API_KEY|SECRET_KEY|SECRET|TOKEN|PASSWORD|PRIVATE_KEY|ACCESS_KEY|AUTH_TOKEN|DB_PASSWORD|DATABASE_URL)\s*=/i}],gx=/(^|\/)\.env(?:\.[^/]+)?\.(example|sample|template)$/i,xp=[{category:"Sensitive Env File",regex:/(^|\/)\.env(?:\.[^/]+)?$/i},{category:"Private Key File",regex:/(^|\/)(id_(rsa|dsa|ecdsa|ed25519)(\.pub)?|.*\.key)$/i},{category:"Certificate Bundle",regex:/(^|\/).*\.(p12|pfx|mobileprovision)$/i},{category:"Terraform Secrets",regex:/(^|\/).*\.(tfvars|tfstate)(\..+)?$/i},{category:"Credential File",regex:/(^|\/)(\.npmrc|\.netrc)$/i},{category:"Cloud Credentials",regex:/(^|\/)\.(aws\/credentials|kube\/config)$/i}];function $i(t,e=process.cwd()){return hx("git",t,{cwd:e,encoding:"utf8"})}function yx(t=process.cwd()){return $i(["rev-parse","--show-toplevel"],t).trim()}function wx(t){let e=px.join(t,".nex","push-allowlist");return bp.existsSync(e)?bp.readFileSync(e,"utf8").split(`
131
+ `).map(n=>n.trim()).filter(n=>n&&!n.startsWith("#")):[]}function jc(t,e){return e.some(n=>t.includes(n))}function kp(t){return gx.test(t)}function vp(t,e){let n=[];for(let o of t)if(!kp(o))for(let s of xp)s.regex.test(o)&&(jc(o,e)||n.push({category:s.category,location:o,preview:o}));return n}function bx(t){let e=t.split(`
132
+ `),n=[],o="";for(let s=0;s<e.length;s++){let r=e[s];if(r.startsWith("+++ b/")){o=r.slice(6);continue}!r.startsWith("+")||r.startsWith("+++")||n.push({filePath:o,lineNumber:s+1,text:r.slice(1),raw:r})}return n}function Sp(t,e){let n=[];for(let o of bx(t))if(!mx.test(o.filePath||""))for(let s of _p)s.regex.test(o.text)&&(jc(o.raw,e)||jc(o.text,e)||n.push({category:s.category,location:`${o.lineNumber}:${o.raw}`,preview:o.raw}));return n}function $x(t){return $i(["diff","--cached","--name-only","--diff-filter=ACMR","-z"],t).split("\0").filter(Boolean)}function _x(t,e){return $i(["diff",e,...$p],t)}function xx(t){return $i(["diff","--cached",...$p],t)}function Ep({repoRoot:t,mode:e,range:n}){let o=wx(t),s=e==="staged"?$x(t):[],r=vp(s,o),i=e==="range"?_x(t,n):xx(t),a=Sp(i,o);return[...r,...a]}function kx(t){return t.map(e=>` [${e.category}]
133
133
  ${e.location}`).join(`
134
- `)}function vx(t){let e={mode:"staged",range:""};for(let n=0;n<t.length;n++)t[n]==="--staged"&&(e.mode="staged"),t[n]==="--range"&&(e.mode="range",e.range=t[n+1]||"",n++);return e}function Sx(){let t=vx(process.argv.slice(2)),e=yx(),n=Sp({repoRoot:e,mode:t.mode,range:t.range});if(n.length===0)return;let o=t.mode==="range"?"pushed commits":"staged changes";console.log(""),console.log("\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557"),console.log("\u2551 SECRET DETECTED \u2014 operation blocked \u2551"),console.log("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563"),console.log(`\u2551 Found ${n.length} potential secret(s) in ${o}:`),console.log(kx(n)),console.log("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563"),console.log("\u2551 Remove secrets or move them to local-only config. \u2551"),console.log("\u2551 To allowlist: add a specific pattern to .nex/push-allowlist"),console.log("\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D"),console.log(""),process.exit(1)}require.main===Dc&&Sx();Dc.exports={SECRET_PATTERNS:$p,SENSITIVE_FILE_RULES:_p,scanDiffText:vp,scanFileNames:kp,scanRepo:Sp,isSafeExampleFile:xp}});var Rp=Q((jA,Tp)=>{var{C:IA}=rt(),{SECRET_PATTERNS:Ex}=Ep(),Tx=[{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 Rx(t,e){let n=e.split(`
135
- `),o=[],s=t?`.${t.split(".").pop()}`:"";for(let r=0;r<n.length;r++){let i=n[r],a=r+1;for(let c of Ex)c.regex.test(i)&&o.push({line:a,message:`Potential secret detected: ${c.category}`,severity:"error"});for(let c of Tx)c.ext&&!c.ext.includes(s)||c.regex.test(i)&&o.push({line:a,message:c.message||`Found ${c.name}`,severity:c.severity||"warn"})}return n.length>500&&o.push({line:0,message:`Large file detected (${n.length} lines). Consider refactoring.`,severity:"info"}),o}function Cx(){let t=process.memoryUsage();return{rss:Math.round(t.rss/1024/1024*100)/100,heapUsed:Math.round(t.heapUsed/1024/1024*100)/100}}Tp.exports={runDiagnostics:Rx,getMemoryUsage:Cx}});var cn=Q((DA,Fp)=>{var es=require("fs").promises,kt=require("path"),{exec:Ax}=require("util").promisify(require("child_process").exec),Pn=[],Bc=null,_i=!1,Fc=0,Ox=6e4;function Uc(t){return!(Pn.length===0||Bc!==t||Date.now()-Fc>Ox)}async function Mp(t){if(!_i&&!Uc(t)){_i=!0,Bc=t;try{try{let{stdout:o}=await Ax("rg --files",{cwd:t,timeout:5e3});Pn=o.split(`
136
- `).filter(Boolean),Fc=Date.now(),_i=!1;return}catch{}let e=[],n=async(o,s)=>{let r;try{r=await es.readdir(o,{withFileTypes:!0})}catch{return}for(let i of r){if(i.name==="node_modules"||i.name===".git"||i.name.startsWith("."))continue;let a=s?`${s}/${i.name}`:i.name;i.isDirectory()?await n(kt.join(o,i.name),a):e.push(a)}};await n(t,""),Pn=e,Fc=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{_i=!1}}}function jo(){return Pn}function Nx(){return Bc}function Mx(t){return Pn.filter(e=>kt.basename(e)===t)}function Px(t){let e=t.toLowerCase();return Pn.filter(n=>n.toLowerCase().includes(e)).slice(0,20)}function Pp(t,e){let n=t.length,o=e.length;if(n===0)return o;if(o===0)return n;let s=Array.from({length:o+1},(r,i)=>i);for(let r=1;r<=n;r++){let i=r-1;s[0]=r;for(let a=1;a<=o;a++){let c=t[r-1]===e[a-1]?i:1+Math.min(s[a],s[a-1],i);i=s[a],s[a]=c}}return s[o]}function Lp(t,e){let n=t.toLowerCase(),o=e.toLowerCase();if(n===o)return 1e3;let s=n.split("/").filter(Boolean),r=o.split("/").filter(Boolean),i=0;for(let l=1;l<=Math.min(s.length,r.length)&&s[s.length-l]===r[r.length-l];l++)i=l;if(i>0&&i===r.length)return 500+i*100;let a=kt.basename(t).toLowerCase(),c=kt.basename(e).toLowerCase(),u=0;if(a===c)u+=80;else{let l=Math.max(a.length,c.length);if(l>0&&l<100){let f=1-Pp(a,c)/l;f>=.6&&(u+=Math.round(f*50))}}if((n.includes(o)||o.includes(n))&&(u+=20),r.length>1){let l=new Set(s),d=0;for(let f of r)l.has(f)&&d++;u+=d*10}return i>0&&(u+=i*30),u}function Lx(t,{limit:e=10,minScore:n=15}={}){if(!t||Pn.length===0)return[];let o=[];for(let s of Pn){let r=Lp(s,t);r>=n&&o.push({file:s,score:r})}return o.sort((s,r)=>r.score-s.score),o.slice(0,e)}var qc=null,Cp=0,Ap=null,Ip=12e4,xi=null,Op=0,Np=null,jp=new Set([".js",".ts",".jsx",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".rb"]);function Dp(t,e){let n=[],o=t.split(`
137
- `);for(let s=0;s<o.length;s++){let r=o[s],i=s+1;if([".js",".ts",".jsx",".tsx",".mjs",".cjs"].includes(e)){let a=r.match(/(?:export\s+)?(?:async\s+)?function\s+(\w+)/);a&&n.push({type:"function",name:a[1],line:i});let c=r.match(/(?:export\s+)?class\s+(\w+)/);c&&n.push({type:"class",name:c[1],line:i});let u=r.match(/(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?(?:\([^)]*\)|[\w$]+)\s*=>/);u&&n.push({type:"function",name:u[1],line:i});let l=r.match(/module\.exports\s*=\s*\{([^}]+)\}/);if(l){let f=l[1].split(",").map(p=>p.trim().split(":")[0].trim()).filter(Boolean);for(let p of f)/^\w+$/.test(p)&&n.push({type:"export",name:p,line:i})}let d=r.match(/(?:require\(['"]([^'"]+)['"]\)|from\s+['"]([^'"]+)['"])/);if(d){let f=d[1]||d[2];n.push({type:"import",name:f,line:i})}}if(e===".py"){let a=r.match(/^(?:async\s+)?def\s+(\w+)/);a&&n.push({type:"function",name:a[1],line:i});let c=r.match(/^class\s+(\w+)/);c&&n.push({type:"class",name:c[1],line:i});let u=r.match(/^(?:from\s+(\S+)\s+)?import\s+(\S+)/);u&&n.push({type:"import",name:u[1]||u[2],line:i})}if(e===".go"){let a=r.match(/^func\s+(?:\([^)]+\)\s+)?(\w+)/);a&&n.push({type:"function",name:a[1],line:i});let c=r.match(/^type\s+(\w+)\s+struct/);c&&n.push({type:"class",name:c[1],line:i})}}return n}async function ki(t){t=t||process.cwd();let e=kt.join(t,".nex","index","content-index.json"),n={};if(qc&&Ap===t&&Date.now()-Cp<Ip)return qc;try{let i=await es.readFile(e,"utf-8");n=JSON.parse(i)}catch{n={files:{}}}let o=jo();(!Uc(t)||o.length===0)&&(await Mp(t),o=jo());let s={files:{}},r=!1;for(let i of jo()){let a=kt.extname(i);if(!jp.has(a))continue;let c=kt.join(t,i);try{let l=(await es.stat(c)).mtimeMs;if(n.files[i]&&n.files[i].mtime===l){s.files[i]=n.files[i];continue}let d=await es.readFile(c,"utf-8"),f=Dp(d,a);s.files[i]={defs:f,mtime:l},r=!0}catch{}}if(r){let i=kt.join(t,".nex","index");await es.mkdir(i,{recursive:!0}),await es.writeFile(e,JSON.stringify(s),"utf-8")}return qc=s,Cp=Date.now(),Ap=t,s}async function Ix(t,e,n){let o=await ki(n),s=[],r=t.toLowerCase();for(let[i,a]of Object.entries(o.files))for(let c of a.defs)e&&c.type!==e||c.name.toLowerCase().includes(r)&&s.push({file:i,type:c.type,name:c.name,line:c.line});return s.sort((i,a)=>{let c=i.name.toLowerCase()===r?0:1,u=a.name.toLowerCase()===r?0:1;if(c!==u)return c-u;let l=i.name.toLowerCase().startsWith(r)?0:1,d=a.name.toLowerCase().startsWith(r)?0:1;return l-d}),s.slice(0,50)}function jx(t,e,n){if(!e||!e.startsWith("."))return null;let o=kt.posix.dirname(t.replace(/\\/g,"/")),s=kt.posix.normalize(kt.posix.join(o==="."?"":o,e)),r=[];if(kt.posix.extname(s))r.push(s);else for(let a of jp)r.push(`${s}${a}`),r.push(kt.posix.join(s,`index${a}`));for(let a of r)if(n.has(a))return a;return null}async function Wc(t){if(t=t||process.cwd(),xi&&Np===t&&Date.now()-Op<Ip)return xi;let e=await ki(t),n=jo(),o=new Set(n.map(i=>i.replace(/\\/g,"/"))),s={},r={};for(let i of Object.keys(e.files||{})){let a=i.replace(/\\/g,"/"),c=Array.isArray(e.files[i]?.defs)?e.files[i].defs:[],u=[],l=new Set;for(let d of c){if(d.type!=="import")continue;let f=jx(a,d.name,o);!f||f===a||l.has(f)||(l.add(f),u.push(f),r[f]||(r[f]=[]),r[f].push(a))}s[a]=u}for(let[i,a]of Object.entries(r))r[i]=[...new Set(a)].sort();return xi={importsByFile:s,importedByFile:r},Op=Date.now(),Np=t,xi}async function Dx(t,e,n=6){if(!t)return[];let o=await Wc(e),s=String(t).replace(/\\/g,"/"),r=[...o.importsByFile[s]||[],...o.importedByFile[s]||[]];return[...new Set(r)].filter(i=>i!==s).slice(0,n)}async function qx(t,e=4){let n=await Wc(t),o=new Map;for(let[s,r]of Object.entries(n.importsByFile||{}))o.set(s,(o.get(s)||0)+r.length);for(let[s,r]of Object.entries(n.importedByFile||{}))o.set(s,(o.get(s)||0)+r.length);return[...o.entries()].filter(([,s])=>s>0).sort((s,r)=>r[1]-s[1]||s[0].localeCompare(r[0])).slice(0,e).map(([s,r])=>`${s} (${r} links)`)}function qp(t){return String(t).replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Fx(t,e){let n=qp(e);return[new RegExp(`\\bfunction\\s+${n}\\b`),new RegExp(`\\bclass\\s+${n}\\b`),new RegExp(`\\b(?:const|let|var)\\s+${n}\\b\\s*=`),new RegExp(`\\bdef\\s+${n}\\b`),new RegExp(`\\btype\\s+${n}\\b\\s+struct\\b`),new RegExp(`\\bmodule\\.exports\\b[^\\n]*\\b${n}\\b`),new RegExp(`\\bexport\\b[^\\n]*\\b${n}\\b`)].some(s=>s.test(t))}async function Bx(t,e,n={}){e=e||process.cwd();let{excludeFile:o=null,excludeLine:s=null,limit:r=6}=n;if(!t||typeof t!="string")return[];let i=await ki(e),a=qp(t),c=new RegExp(`\\b${a}\\s*\\(`),u=new RegExp(`\\b${a}\\b`),l=[];for(let d of Object.keys(i.files||{})){let f=d.replace(/\\/g,"/");try{let p=kt.join(e,f),g=(await es.readFile(p,"utf-8")).split(`
138
- `);for(let w=0;w<g.length;w++){let _=g[w],S=w+1;if(!u.test(_)||o&&f===o&&s===S||Fx(_,t))continue;let A=(f===o?0:4)+(c.test(_)?3:1);l.push({file:f,line:S,context:_.trim(),score:A})}}catch{}}return l.sort((d,f)=>f.score!==d.score?f.score-d.score:d.file.localeCompare(f.file)||d.line-f.line),l.slice(0,r)}Fp.exports={refreshIndex:Mp,getFileIndex:jo,getIndexedCwd:Nx,findFileInIndex:Mx,searchIndex:Px,isIndexValid:Uc,buildContentIndex:ki,searchContentIndex:Ix,extractDefinitions:Dp,buildImportGraph:Wc,getRelatedFiles:Dx,summarizeModuleHubs:qx,findSymbolReferences:Bx,smartSearch:Lx,scorePathMatch:Lp,pathLevenshtein:Pp}});var Ks=Q((qA,Gp)=>{var vi=require("fs"),Ri=require("path"),Ci=require("os"),{execFile:Ux}=require("child_process"),{promisify:Wx}=require("util"),Hc=Wx(Ux),Hx=Ri.join(Ci.homedir(),".nex","servers.json"),Si=Ri.join(Ci.tmpdir(),"nex-ssh-sockets");function Yx(){return Ri.join(process.cwd(),".nex","servers.json")}function Bp(){let t=o=>{if(!vi.existsSync(o))return{};try{return JSON.parse(vi.readFileSync(o,"utf-8"))}catch{return{}}},e=t(Hx),n=t(Yx());return{...e,...n}}function Gx(t){let e=Bp();if(e[t])return{...e[t],_name:t};if(/^[\w.-]+@[\w.-]+$/.test(t)||/[\w-]+\.[\w.-]+/.test(t)||t==="localhost"){let[s,r]=t.includes("@")?t.split("@"):[void 0,t];return{host:r,user:s}}let n=Object.keys(e),o=n.length?`Available profiles: ${n.join(", ")}`:"No profiles configured. Create .nex/servers.json (project) or ~/.nex/servers.json (global)";throw new Error(`Unknown server: "${t}". ${o}`)}function zx(){vi.existsSync(Si)||vi.mkdirSync(Si,{recursive:!0})}function Up(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=yes","-o","ServerAliveInterval=30"];t.key&&e.push("-i",t.key.replace(/^~/,Ci.homedir())),t.port&&Number(t.port)!==22&&e.push("-p",String(t.port)),zx();let n=t.user?`${t.user}@${t.host}`:t.host,o=Ri.join(Si,n.replace(/[@.:]/g,"_"));return e.push("-o","ControlMaster=auto","-o",`ControlPath=${o}`,"-o","ControlPersist=120"),e.push(n),{args:e,target:n}}function Wp(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=yes","-r"];return t.key&&e.push("-i",t.key.replace(/^~/,Ci.homedir())),t.port&&Number(t.port)!==22&&e.push("-P",String(t.port)),e}async function Ei(t,e,{timeout:n=3e4,sudo:o=!1}={}){let{args:s}=Up(t),r=o&&t.sudo?`sudo sh -c ${JSON.stringify(e)}`:e;try{let{stdout:i,stderr:a}=await Hc("ssh",[...s,r],{timeout:n,maxBuffer:4194304});return{stdout:i||"",stderr:a||"",exitCode:0}}catch(i){let a=typeof i.code=="number"?i.code:1,c=(i.stderr||i.message||"").toString();return{stdout:(i.stdout||"").toString(),stderr:c,exitCode:a,error:Ai(c,t)}}}async function Kx(t,e,n,{timeout:o=12e4}={}){let s=Wp(t),r=t.user?`${t.user}@${t.host}`:t.host;s.push(e,`${r}:${n}`);try{let{stdout:i,stderr:a}=await Hc("scp",s,{timeout:o,maxBuffer:1048576});return i||a||`Uploaded ${e} \u2192 ${r}:${n}`}catch(i){let a=(i.stderr||i.message||"").toString();throw new Error(Ai(a,t)||a)}}async function Xx(t,e,n,{timeout:o=12e4}={}){let s=Wp(t),r=t.user?`${t.user}@${t.host}`:t.host;s.push(`${r}:${e}`,n);try{let{stdout:i,stderr:a}=await Hc("scp",s,{timeout:o,maxBuffer:1048576});return i||a||`Downloaded ${r}:${e} \u2192 ${n}`}catch(i){let a=(i.stderr||i.message||"").toString();throw new Error(Ai(a,t)||a)}}function Ai(t,e){if(!t)return"";if(/connection refused/i.test(t)){let n=e.port||22;return`${t}
134
+ `)}function vx(t){let e={mode:"staged",range:""};for(let n=0;n<t.length;n++)t[n]==="--staged"&&(e.mode="staged"),t[n]==="--range"&&(e.mode="range",e.range=t[n+1]||"",n++);return e}function Sx(){let t=vx(process.argv.slice(2)),e=yx(),n=Ep({repoRoot:e,mode:t.mode,range:t.range});if(n.length===0)return;let o=t.mode==="range"?"pushed commits":"staged changes";console.log(""),console.log("\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557"),console.log("\u2551 SECRET DETECTED \u2014 operation blocked \u2551"),console.log("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563"),console.log(`\u2551 Found ${n.length} potential secret(s) in ${o}:`),console.log(kx(n)),console.log("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563"),console.log("\u2551 Remove secrets or move them to local-only config. \u2551"),console.log("\u2551 To allowlist: add a specific pattern to .nex/push-allowlist"),console.log("\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D"),console.log(""),process.exit(1)}require.main===Dc&&Sx();Dc.exports={SECRET_PATTERNS:_p,SENSITIVE_FILE_RULES:xp,scanDiffText:Sp,scanFileNames:vp,scanRepo:Ep,isSafeExampleFile:kp}});var Cp=Q((DA,Rp)=>{var{C:jA}=rt(),{SECRET_PATTERNS:Ex}=Tp(),Tx=[{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 Rx(t,e){let n=e.split(`
135
+ `),o=[],s=t?`.${t.split(".").pop()}`:"";for(let r=0;r<n.length;r++){let i=n[r],a=r+1;for(let c of Ex)c.regex.test(i)&&o.push({line:a,message:`Potential secret detected: ${c.category}`,severity:"error"});for(let c of Tx)c.ext&&!c.ext.includes(s)||c.regex.test(i)&&o.push({line:a,message:c.message||`Found ${c.name}`,severity:c.severity||"warn"})}return n.length>500&&o.push({line:0,message:`Large file detected (${n.length} lines). Consider refactoring.`,severity:"info"}),o}function Cx(){let t=process.memoryUsage();return{rss:Math.round(t.rss/1024/1024*100)/100,heapUsed:Math.round(t.heapUsed/1024/1024*100)/100}}Rp.exports={runDiagnostics:Rx,getMemoryUsage:Cx}});var cn=Q((qA,Bp)=>{var es=require("fs").promises,kt=require("path"),{exec:Ax}=require("util").promisify(require("child_process").exec),Pn=[],Bc=null,_i=!1,Fc=0,Ox=6e4;function Uc(t){return!(Pn.length===0||Bc!==t||Date.now()-Fc>Ox)}async function Pp(t){if(!_i&&!Uc(t)){_i=!0,Bc=t;try{try{let{stdout:o}=await Ax("rg --files",{cwd:t,timeout:5e3});Pn=o.split(`
136
+ `).filter(Boolean),Fc=Date.now(),_i=!1;return}catch{}let e=[],n=async(o,s)=>{let r;try{r=await es.readdir(o,{withFileTypes:!0})}catch{return}for(let i of r){if(i.name==="node_modules"||i.name===".git"||i.name.startsWith("."))continue;let a=s?`${s}/${i.name}`:i.name;i.isDirectory()?await n(kt.join(o,i.name),a):e.push(a)}};await n(t,""),Pn=e,Fc=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{_i=!1}}}function jo(){return Pn}function Nx(){return Bc}function Mx(t){return Pn.filter(e=>kt.basename(e)===t)}function Px(t){let e=t.toLowerCase();return Pn.filter(n=>n.toLowerCase().includes(e)).slice(0,20)}function Lp(t,e){let n=t.length,o=e.length;if(n===0)return o;if(o===0)return n;let s=Array.from({length:o+1},(r,i)=>i);for(let r=1;r<=n;r++){let i=r-1;s[0]=r;for(let a=1;a<=o;a++){let c=t[r-1]===e[a-1]?i:1+Math.min(s[a],s[a-1],i);i=s[a],s[a]=c}}return s[o]}function Ip(t,e){let n=t.toLowerCase(),o=e.toLowerCase();if(n===o)return 1e3;let s=n.split("/").filter(Boolean),r=o.split("/").filter(Boolean),i=0;for(let l=1;l<=Math.min(s.length,r.length)&&s[s.length-l]===r[r.length-l];l++)i=l;if(i>0&&i===r.length)return 500+i*100;let a=kt.basename(t).toLowerCase(),c=kt.basename(e).toLowerCase(),u=0;if(a===c)u+=80;else{let l=Math.max(a.length,c.length);if(l>0&&l<100){let f=1-Lp(a,c)/l;f>=.6&&(u+=Math.round(f*50))}}if((n.includes(o)||o.includes(n))&&(u+=20),r.length>1){let l=new Set(s),d=0;for(let f of r)l.has(f)&&d++;u+=d*10}return i>0&&(u+=i*30),u}function Lx(t,{limit:e=10,minScore:n=15}={}){if(!t||Pn.length===0)return[];let o=[];for(let s of Pn){let r=Ip(s,t);r>=n&&o.push({file:s,score:r})}return o.sort((s,r)=>r.score-s.score),o.slice(0,e)}var qc=null,Ap=0,Op=null,jp=12e4,xi=null,Np=0,Mp=null,Dp=new Set([".js",".ts",".jsx",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".rb"]);function qp(t,e){let n=[],o=t.split(`
137
+ `);for(let s=0;s<o.length;s++){let r=o[s],i=s+1;if([".js",".ts",".jsx",".tsx",".mjs",".cjs"].includes(e)){let a=r.match(/(?:export\s+)?(?:async\s+)?function\s+(\w+)/);a&&n.push({type:"function",name:a[1],line:i});let c=r.match(/(?:export\s+)?class\s+(\w+)/);c&&n.push({type:"class",name:c[1],line:i});let u=r.match(/(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?(?:\([^)]*\)|[\w$]+)\s*=>/);u&&n.push({type:"function",name:u[1],line:i});let l=r.match(/module\.exports\s*=\s*\{([^}]+)\}/);if(l){let f=l[1].split(",").map(p=>p.trim().split(":")[0].trim()).filter(Boolean);for(let p of f)/^\w+$/.test(p)&&n.push({type:"export",name:p,line:i})}let d=r.match(/(?:require\(['"]([^'"]+)['"]\)|from\s+['"]([^'"]+)['"])/);if(d){let f=d[1]||d[2];n.push({type:"import",name:f,line:i})}}if(e===".py"){let a=r.match(/^(?:async\s+)?def\s+(\w+)/);a&&n.push({type:"function",name:a[1],line:i});let c=r.match(/^class\s+(\w+)/);c&&n.push({type:"class",name:c[1],line:i});let u=r.match(/^(?:from\s+(\S+)\s+)?import\s+(\S+)/);u&&n.push({type:"import",name:u[1]||u[2],line:i})}if(e===".go"){let a=r.match(/^func\s+(?:\([^)]+\)\s+)?(\w+)/);a&&n.push({type:"function",name:a[1],line:i});let c=r.match(/^type\s+(\w+)\s+struct/);c&&n.push({type:"class",name:c[1],line:i})}}return n}async function ki(t){t=t||process.cwd();let e=kt.join(t,".nex","index","content-index.json"),n={};if(qc&&Op===t&&Date.now()-Ap<jp)return qc;try{let i=await es.readFile(e,"utf-8");n=JSON.parse(i)}catch{n={files:{}}}let o=jo();(!Uc(t)||o.length===0)&&(await Pp(t),o=jo());let s={files:{}},r=!1;for(let i of jo()){let a=kt.extname(i);if(!Dp.has(a))continue;let c=kt.join(t,i);try{let l=(await es.stat(c)).mtimeMs;if(n.files[i]&&n.files[i].mtime===l){s.files[i]=n.files[i];continue}let d=await es.readFile(c,"utf-8"),f=qp(d,a);s.files[i]={defs:f,mtime:l},r=!0}catch{}}if(r){let i=kt.join(t,".nex","index");await es.mkdir(i,{recursive:!0}),await es.writeFile(e,JSON.stringify(s),"utf-8")}return qc=s,Ap=Date.now(),Op=t,s}async function Ix(t,e,n){let o=await ki(n),s=[],r=t.toLowerCase();for(let[i,a]of Object.entries(o.files))for(let c of a.defs)e&&c.type!==e||c.name.toLowerCase().includes(r)&&s.push({file:i,type:c.type,name:c.name,line:c.line});return s.sort((i,a)=>{let c=i.name.toLowerCase()===r?0:1,u=a.name.toLowerCase()===r?0:1;if(c!==u)return c-u;let l=i.name.toLowerCase().startsWith(r)?0:1,d=a.name.toLowerCase().startsWith(r)?0:1;return l-d}),s.slice(0,50)}function jx(t,e,n){if(!e||!e.startsWith("."))return null;let o=kt.posix.dirname(t.replace(/\\/g,"/")),s=kt.posix.normalize(kt.posix.join(o==="."?"":o,e)),r=[];if(kt.posix.extname(s))r.push(s);else for(let a of Dp)r.push(`${s}${a}`),r.push(kt.posix.join(s,`index${a}`));for(let a of r)if(n.has(a))return a;return null}async function Wc(t){if(t=t||process.cwd(),xi&&Mp===t&&Date.now()-Np<jp)return xi;let e=await ki(t),n=jo(),o=new Set(n.map(i=>i.replace(/\\/g,"/"))),s={},r={};for(let i of Object.keys(e.files||{})){let a=i.replace(/\\/g,"/"),c=Array.isArray(e.files[i]?.defs)?e.files[i].defs:[],u=[],l=new Set;for(let d of c){if(d.type!=="import")continue;let f=jx(a,d.name,o);!f||f===a||l.has(f)||(l.add(f),u.push(f),r[f]||(r[f]=[]),r[f].push(a))}s[a]=u}for(let[i,a]of Object.entries(r))r[i]=[...new Set(a)].sort();return xi={importsByFile:s,importedByFile:r},Np=Date.now(),Mp=t,xi}async function Dx(t,e,n=6){if(!t)return[];let o=await Wc(e),s=String(t).replace(/\\/g,"/"),r=[...o.importsByFile[s]||[],...o.importedByFile[s]||[]];return[...new Set(r)].filter(i=>i!==s).slice(0,n)}async function qx(t,e=4){let n=await Wc(t),o=new Map;for(let[s,r]of Object.entries(n.importsByFile||{}))o.set(s,(o.get(s)||0)+r.length);for(let[s,r]of Object.entries(n.importedByFile||{}))o.set(s,(o.get(s)||0)+r.length);return[...o.entries()].filter(([,s])=>s>0).sort((s,r)=>r[1]-s[1]||s[0].localeCompare(r[0])).slice(0,e).map(([s,r])=>`${s} (${r} links)`)}function Fp(t){return String(t).replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Fx(t,e){let n=Fp(e);return[new RegExp(`\\bfunction\\s+${n}\\b`),new RegExp(`\\bclass\\s+${n}\\b`),new RegExp(`\\b(?:const|let|var)\\s+${n}\\b\\s*=`),new RegExp(`\\bdef\\s+${n}\\b`),new RegExp(`\\btype\\s+${n}\\b\\s+struct\\b`),new RegExp(`\\bmodule\\.exports\\b[^\\n]*\\b${n}\\b`),new RegExp(`\\bexport\\b[^\\n]*\\b${n}\\b`)].some(s=>s.test(t))}async function Bx(t,e,n={}){e=e||process.cwd();let{excludeFile:o=null,excludeLine:s=null,limit:r=6}=n;if(!t||typeof t!="string")return[];let i=await ki(e),a=Fp(t),c=new RegExp(`\\b${a}\\s*\\(`),u=new RegExp(`\\b${a}\\b`),l=[];for(let d of Object.keys(i.files||{})){let f=d.replace(/\\/g,"/");try{let p=kt.join(e,f),g=(await es.readFile(p,"utf-8")).split(`
138
+ `);for(let w=0;w<g.length;w++){let _=g[w],S=w+1;if(!u.test(_)||o&&f===o&&s===S||Fx(_,t))continue;let A=(f===o?0:4)+(c.test(_)?3:1);l.push({file:f,line:S,context:_.trim(),score:A})}}catch{}}return l.sort((d,f)=>f.score!==d.score?f.score-d.score:d.file.localeCompare(f.file)||d.line-f.line),l.slice(0,r)}Bp.exports={refreshIndex:Pp,getFileIndex:jo,getIndexedCwd:Nx,findFileInIndex:Mx,searchIndex:Px,isIndexValid:Uc,buildContentIndex:ki,searchContentIndex:Ix,extractDefinitions:qp,buildImportGraph:Wc,getRelatedFiles:Dx,summarizeModuleHubs:qx,findSymbolReferences:Bx,smartSearch:Lx,scorePathMatch:Ip,pathLevenshtein:Lp}});var Ks=Q((FA,zp)=>{var vi=require("fs"),Ri=require("path"),Ci=require("os"),{execFile:Ux}=require("child_process"),{promisify:Wx}=require("util"),Hc=Wx(Ux),Hx=Ri.join(Ci.homedir(),".nex","servers.json"),Si=Ri.join(Ci.tmpdir(),"nex-ssh-sockets");function Yx(){return Ri.join(process.cwd(),".nex","servers.json")}function Up(){let t=o=>{if(!vi.existsSync(o))return{};try{return JSON.parse(vi.readFileSync(o,"utf-8"))}catch{return{}}},e=t(Hx),n=t(Yx());return{...e,...n}}function Gx(t){let e=Up();if(e[t])return{...e[t],_name:t};if(/^[\w.-]+@[\w.-]+$/.test(t)||/[\w-]+\.[\w.-]+/.test(t)||t==="localhost"){let[s,r]=t.includes("@")?t.split("@"):[void 0,t];return{host:r,user:s}}let n=Object.keys(e),o=n.length?`Available profiles: ${n.join(", ")}`:"No profiles configured. Create .nex/servers.json (project) or ~/.nex/servers.json (global)";throw new Error(`Unknown server: "${t}". ${o}`)}function zx(){vi.existsSync(Si)||vi.mkdirSync(Si,{recursive:!0})}function Wp(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=yes","-o","ServerAliveInterval=30"];t.key&&e.push("-i",t.key.replace(/^~/,Ci.homedir())),t.port&&Number(t.port)!==22&&e.push("-p",String(t.port)),zx();let n=t.user?`${t.user}@${t.host}`:t.host,o=Ri.join(Si,n.replace(/[@.:]/g,"_"));return e.push("-o","ControlMaster=auto","-o",`ControlPath=${o}`,"-o","ControlPersist=120"),e.push(n),{args:e,target:n}}function Hp(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=yes","-r"];return t.key&&e.push("-i",t.key.replace(/^~/,Ci.homedir())),t.port&&Number(t.port)!==22&&e.push("-P",String(t.port)),e}async function Ei(t,e,{timeout:n=3e4,sudo:o=!1}={}){let{args:s}=Wp(t),r=o&&t.sudo?`sudo sh -c ${JSON.stringify(e)}`:e;try{let{stdout:i,stderr:a}=await Hc("ssh",[...s,r],{timeout:n,maxBuffer:4194304});return{stdout:i||"",stderr:a||"",exitCode:0}}catch(i){let a=typeof i.code=="number"?i.code:1,c=(i.stderr||i.message||"").toString();return{stdout:(i.stdout||"").toString(),stderr:c,exitCode:a,error:Ai(c,t)}}}async function Kx(t,e,n,{timeout:o=12e4}={}){let s=Hp(t),r=t.user?`${t.user}@${t.host}`:t.host;s.push(e,`${r}:${n}`);try{let{stdout:i,stderr:a}=await Hc("scp",s,{timeout:o,maxBuffer:1048576});return i||a||`Uploaded ${e} \u2192 ${r}:${n}`}catch(i){let a=(i.stderr||i.message||"").toString();throw new Error(Ai(a,t)||a)}}async function Xx(t,e,n,{timeout:o=12e4}={}){let s=Hp(t),r=t.user?`${t.user}@${t.host}`:t.host;s.push(`${r}:${e}`,n);try{let{stdout:i,stderr:a}=await Hc("scp",s,{timeout:o,maxBuffer:1048576});return i||a||`Downloaded ${r}:${e} \u2192 ${n}`}catch(i){let a=(i.stderr||i.message||"").toString();throw new Error(Ai(a,t)||a)}}function Ai(t,e){if(!t)return"";if(/connection refused/i.test(t)){let n=e.port||22;return`${t}
139
139
  HINT: Connection refused on ${e.host}:${n}. Check: server is running, SSH service is active (systemctl status sshd), firewall allows port ${n} (firewall-cmd --list-ports).`}if(/permission denied/i.test(t)){let n=e.key?`key: ${e.key}`:"SSH agent";return`${t}
140
140
  HINT: Auth failed using ${n} as user "${e.user||"root"}". Check: authorized_keys on server, correct username, key passphrase.`}return/no route to host|network unreachable|name or service not known/i.test(t)?`${t}
141
141
  HINT: Cannot reach ${e.host}. Check: network connection, correct hostname/IP, DNS resolution.`:/host key verification failed/i.test(t)?`${t}
142
142
  HINT: Host key changed for ${e.host}. To reset: ssh-keygen -R ${e.host}`:/timed out/i.test(t)?`${t}
143
143
  HINT: Connection timed out to ${e.host}. Check firewall rules and network connectivity.`:/too many authentication failures/i.test(t)?`${t}
144
- HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function Vx(t,e){let n=e.user?`${e.user}@${e.host}`:e.host,o=e.port&&Number(e.port)!==22?`:${e.port}`:"",s=e.os?` [${e.os}]`:"",r=e.key?` key:${e.key}`:"",i=e.sudo?" sudo:yes":"";return`${t}: ${n}${o}${s}${r}${i}`}var Ti=new Map,Jx=12e4;async function Hp(t,e,{force:n=!1}={}){let s=`${t.user?`${t.user}@${t.host}`:t.host}:${e}`,r=Ti.get(s);if(!n&&r&&Date.now()-r.time<Jx)return r.files;let i=`find ${e} -maxdepth 6 -type f -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/venv/*' -not -path '*/__pycache__/*' -not -path '*/dist/*' -not -name '*.pyc' 2>/dev/null | head -5000`,{stdout:a,exitCode:c}=await Ei(t,i,{timeout:15e3});if(c!==0||!a.trim())return[];let u=e.endsWith("/")?e:e+"/",l=a.split(`
145
- `).filter(Boolean).map(d=>d.startsWith(u)?d.slice(u.length):d);return Ti.set(s,{files:l,time:Date.now()}),l}async function Yp(t,e,n,{limit:o=5,minScore:s=15}={}){let r=await Hp(t,e);if(r.length===0)return[];let{scorePathMatch:i}=cn(),a=[];for(let c of r){let u=i(c,n);u>=s&&a.push({file:c,score:u})}return a.sort((c,u)=>u.score-c.score),a.slice(0,o)}async function Zx(t,e,n){if(!n)return{fixedPath:null,message:""};let o=n.replace(/\/+/g,"/");if(o.startsWith("~/")){let{stdout:r}=await Ei(t,"echo $HOME",{timeout:5e3}),i=r.trim();i&&(o=o.replace("~/",i+"/"))}if(o.startsWith("/")){let{exitCode:r}=await Ei(t,`test -f ${JSON.stringify(o)}`,{timeout:5e3});if(r===0)return{fixedPath:o,message:"(auto-fixed: normalized path)"}}let s=await Yp(t,e,n,{limit:5,minScore:15});if(s.length>0){let i=(e.endsWith("/")?e:e+"/")+s[0].file;if(s[0].score>=200||s.length===1&&s[0].score>=50)return{fixedPath:i,message:`(auto-fixed: remote smart match \u2192 ${s[0].file})`};if(s.length>=2&&s[0].score>=80&&s[0].score>=s[1].score*1.5)return{fixedPath:i,message:`(auto-fixed: remote best match \u2192 ${s[0].file})`};if(s.length<=5)return{fixedPath:null,message:`File not found on remote. Did you mean:
144
+ HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function Vx(t,e){let n=e.user?`${e.user}@${e.host}`:e.host,o=e.port&&Number(e.port)!==22?`:${e.port}`:"",s=e.os?` [${e.os}]`:"",r=e.key?` key:${e.key}`:"",i=e.sudo?" sudo:yes":"";return`${t}: ${n}${o}${s}${r}${i}`}var Ti=new Map,Jx=12e4;async function Yp(t,e,{force:n=!1}={}){let s=`${t.user?`${t.user}@${t.host}`:t.host}:${e}`,r=Ti.get(s);if(!n&&r&&Date.now()-r.time<Jx)return r.files;let i=`find ${e} -maxdepth 6 -type f -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/venv/*' -not -path '*/__pycache__/*' -not -path '*/dist/*' -not -name '*.pyc' 2>/dev/null | head -5000`,{stdout:a,exitCode:c}=await Ei(t,i,{timeout:15e3});if(c!==0||!a.trim())return[];let u=e.endsWith("/")?e:e+"/",l=a.split(`
145
+ `).filter(Boolean).map(d=>d.startsWith(u)?d.slice(u.length):d);return Ti.set(s,{files:l,time:Date.now()}),l}async function Gp(t,e,n,{limit:o=5,minScore:s=15}={}){let r=await Yp(t,e);if(r.length===0)return[];let{scorePathMatch:i}=cn(),a=[];for(let c of r){let u=i(c,n);u>=s&&a.push({file:c,score:u})}return a.sort((c,u)=>u.score-c.score),a.slice(0,o)}async function Zx(t,e,n){if(!n)return{fixedPath:null,message:""};let o=n.replace(/\/+/g,"/");if(o.startsWith("~/")){let{stdout:r}=await Ei(t,"echo $HOME",{timeout:5e3}),i=r.trim();i&&(o=o.replace("~/",i+"/"))}if(o.startsWith("/")){let{exitCode:r}=await Ei(t,`test -f ${JSON.stringify(o)}`,{timeout:5e3});if(r===0)return{fixedPath:o,message:"(auto-fixed: normalized path)"}}let s=await Gp(t,e,n,{limit:5,minScore:15});if(s.length>0){let i=(e.endsWith("/")?e:e+"/")+s[0].file;if(s[0].score>=200||s.length===1&&s[0].score>=50)return{fixedPath:i,message:`(auto-fixed: remote smart match \u2192 ${s[0].file})`};if(s.length>=2&&s[0].score>=80&&s[0].score>=s[1].score*1.5)return{fixedPath:i,message:`(auto-fixed: remote best match \u2192 ${s[0].file})`};if(s.length<=5)return{fixedPath:null,message:`File not found on remote. Did you mean:
146
146
  ${s.map(a=>` - ${a.file}`).join(`
147
- `)}`}}return{fixedPath:null,message:""}}function Qx(t){t?Ti.delete(t):Ti.clear()}Gp.exports={loadServerProfiles:Bp,resolveProfile:Gx,buildSSHArgs:Up,sshExec:Ei,scpUpload:Kx,scpDownload:Xx,enrichSSHError:Ai,formatProfile:Vx,SSH_SOCKET_DIR:Si,getRemoteIndex:Hp,remoteSmartSearch:Yp,remoteAutoFixPath:Zx,clearRemoteIndex:Qx}});var Xp=Q((FA,Kp)=>{var Do=require("fs"),Yc=require("path"),ek=Yc.join(".nex","deploy.json");function Gc(){return Yc.join(process.cwd(),ek)}function zp(){let t=Gc();if(!Do.existsSync(t))return{};try{return JSON.parse(Do.readFileSync(t,"utf-8"))}catch{return{}}}function tk(t){let e=zp();if(e[t])return{...e[t],_name:t};let n=Object.keys(e),o=n.length?`Available: ${n.join(", ")}`:"No deploy configs found. Create .nex/deploy.json or use explicit params.";throw new Error(`Unknown deploy config: "${t}". ${o}`)}function nk(t){let e=Yc.join(process.cwd(),".nex");Do.existsSync(e)||Do.mkdirSync(e,{recursive:!0}),Do.writeFileSync(Gc(),JSON.stringify(t,null,2)+`
148
- `,"utf-8")}Kp.exports={loadDeployConfigs:zp,resolveDeployConfig:tk,saveDeployConfigs:nk,getDeployConfigPath:Gc}});var Uo=Q((BA,Zp)=>{var{getActiveModel:sk,getActiveProviderName:ok}=ct(),qo={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},Fo={"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"},Bo={ollama:"full",openai:"full",anthropic:"full",gemini:"full",local:"essential"},ln={};function Jp(){try{let t=require("fs"),n=require("path").join(process.cwd(),".nex","config.json");t.existsSync(n)&&(ln=JSON.parse(t.readFileSync(n,"utf-8")).toolTiers||{})}catch{ln={}}}Jp();function zc(){let e=sk()?.id,n=ok();return e&&ln[e]?ln[e]:n&&ln[`${n}:*`]?ln[`${n}:*`]:e&&Fo[e]?Fo[e]:n&&Bo[n]?Bo[n]:"full"}var rk=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"]),Vp={anthropic:"strict",openai:"strict",gemini:"strict",ollama:"fuzzy",local:"fuzzy"};function ik(t,e){return t&&(rk.has(t)||t.startsWith("claude-"))?"strict":e&&Vp[e]?Vp[e]:"fuzzy"}function ak(t,e){return t&&ln[t]?ln[t]:e&&ln[`${e}:*`]?ln[`${e}:*`]:t&&Fo[t]?Fo[t]:e&&Bo[e]?Bo[e]:"full"}function ck(t,e){let n=e||zc();if(n==="full"||!qo[n])return t;let o=new Set(qo[n]);return t.filter(s=>o.has(s.function.name))}function lk(){let t=zc(),e=qo[t]?qo[t].length:"all";return{tier:t,toolCount:e}}Zp.exports={filterToolsForModel:ck,getActiveTier:zc,getModelTier:ak,getEditMode:ik,getTierInfo:lk,TIERS:qo,MODEL_TIERS:Fo,PROVIDER_DEFAULT_TIER:Bo,loadConfigOverrides:Jp}});var kn=Q((UA,th)=>{var Kc=null,xn=null,Wo=null,Qp=`Playwright is not installed. Install with:
147
+ `)}`}}return{fixedPath:null,message:""}}function Qx(t){t?Ti.delete(t):Ti.clear()}zp.exports={loadServerProfiles:Up,resolveProfile:Gx,buildSSHArgs:Wp,sshExec:Ei,scpUpload:Kx,scpDownload:Xx,enrichSSHError:Ai,formatProfile:Vx,SSH_SOCKET_DIR:Si,getRemoteIndex:Yp,remoteSmartSearch:Gp,remoteAutoFixPath:Zx,clearRemoteIndex:Qx}});var Vp=Q((BA,Xp)=>{var Do=require("fs"),Yc=require("path"),ek=Yc.join(".nex","deploy.json");function Gc(){return Yc.join(process.cwd(),ek)}function Kp(){let t=Gc();if(!Do.existsSync(t))return{};try{return JSON.parse(Do.readFileSync(t,"utf-8"))}catch{return{}}}function tk(t){let e=Kp();if(e[t])return{...e[t],_name:t};let n=Object.keys(e),o=n.length?`Available: ${n.join(", ")}`:"No deploy configs found. Create .nex/deploy.json or use explicit params.";throw new Error(`Unknown deploy config: "${t}". ${o}`)}function nk(t){let e=Yc.join(process.cwd(),".nex");Do.existsSync(e)||Do.mkdirSync(e,{recursive:!0}),Do.writeFileSync(Gc(),JSON.stringify(t,null,2)+`
148
+ `,"utf-8")}Xp.exports={loadDeployConfigs:Kp,resolveDeployConfig:tk,saveDeployConfigs:nk,getDeployConfigPath:Gc}});var Uo=Q((UA,Qp)=>{var{getActiveModel:sk,getActiveProviderName:ok}=ct(),qo={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},Fo={"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"},Bo={ollama:"full",openai:"full",anthropic:"full",gemini:"full",local:"essential"},ln={};function Zp(){try{let t=require("fs"),n=require("path").join(process.cwd(),".nex","config.json");t.existsSync(n)&&(ln=JSON.parse(t.readFileSync(n,"utf-8")).toolTiers||{})}catch{ln={}}}Zp();function zc(){let e=sk()?.id,n=ok();return e&&ln[e]?ln[e]:n&&ln[`${n}:*`]?ln[`${n}:*`]:e&&Fo[e]?Fo[e]:n&&Bo[n]?Bo[n]:"full"}var rk=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"]),Jp={anthropic:"strict",openai:"strict",gemini:"strict",ollama:"fuzzy",local:"fuzzy"};function ik(t,e){return t&&(rk.has(t)||t.startsWith("claude-"))?"strict":e&&Jp[e]?Jp[e]:"fuzzy"}function ak(t,e){return t&&ln[t]?ln[t]:e&&ln[`${e}:*`]?ln[`${e}:*`]:t&&Fo[t]?Fo[t]:e&&Bo[e]?Bo[e]:"full"}function ck(t,e){let n=e||zc();if(n==="full"||!qo[n])return t;let o=new Set(qo[n]);return t.filter(s=>o.has(s.function.name))}function lk(){let t=zc(),e=qo[t]?qo[t].length:"all";return{tier:t,toolCount:e}}Qp.exports={filterToolsForModel:ck,getActiveTier:zc,getModelTier:ak,getEditMode:ik,getTierInfo:lk,TIERS:qo,MODEL_TIERS:Fo,PROVIDER_DEFAULT_TIER:Bo,loadConfigOverrides:Zp}});var kn=Q((WA,nh)=>{var Kc=null,xn=null,Wo=null,eh=`Playwright is not installed. Install with:
149
149
  npm install playwright && npx playwright install chromium
150
- Then restart nex-code.`;function eh(){if(Wo!==null)return Wo;try{require("playwright"),Wo=!0}catch{Wo=!1}return Wo}async function Oi(){if(!eh())throw new Error(Qp);return Kc||(Kc=require("playwright")),(!xn||!xn.isConnected())&&(xn=await Kc.chromium.launch({headless:!0})),xn}async function uk(){if(xn){try{await xn.close()}catch(t){console.error("closeBrowser failed:",t.message)}xn=null}}process.on("exit",()=>{if(xn)try{xn.close()}catch(t){console.error("Error closing browser on exit:",t.message)}});async function dk(t,{timeout:e=3e4,waitFor:n="domcontentloaded"}={}){let s=await(await Oi()).newPage();try{await s.goto(t,{waitUntil:n,timeout:e});let r=await s.title(),i=await s.evaluate(()=>(document.querySelectorAll("script,style,nav,footer,header,aside,[role=navigation]").forEach(u=>u.remove()),document.body?.innerText||"")),a=await s.evaluate(()=>Array.from(document.querySelectorAll("a[href]")).slice(0,30).map(c=>({text:(c.innerText||c.textContent||"").trim().substring(0,80),href:c.href})).filter(c=>c.text&&c.href&&!c.href.startsWith("javascript:")));return{title:r,url:s.url(),text:i.substring(0,8e3)+(i.length>8e3?`
151
- ...(truncated)`:""),links:a.slice(0,20)}}finally{await s.close()}}async function fk(t,{width:e=1280,height:n=800,fullPage:o=!1,timeout:s=3e4}={}){let i=await(await Oi()).newPage();try{await i.setViewportSize({width:e,height:n}),await i.goto(t,{waitUntil:"networkidle",timeout:s});let a=await i.screenshot({type:"png",fullPage:o}),c=require("os"),u=require("path"),l=require("fs"),d=u.join(c.tmpdir(),`nex-screenshot-${Date.now()}.png`);return l.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 pk(t,{selector:e,text:n,timeout:o=3e4}={}){if(!e&&!n)throw new Error("selector or text is required");let r=await(await Oi()).newPage();try{await r.goto(t,{waitUntil:"domcontentloaded",timeout:o}),n?await r.getByText(n,{exact:!1}).first().click({timeout:1e4}):await r.locator(e).first().click({timeout:1e4}),await r.waitForLoadState("domcontentloaded");let i=await r.title();return`Clicked \u2014 now at: ${r.url()} (${i})`}finally{await r.close()}}async function hk(t,{selector:e,value:n,submit:o=!1,timeout:s=3e4}={}){if(!e||n===void 0)throw new Error("selector and value are required");let i=await(await Oi()).newPage();try{return await i.goto(t,{waitUntil:"domcontentloaded",timeout:s}),await i.fill(e,String(n)),o&&(await i.keyboard.press("Enter"),await i.waitForLoadState("domcontentloaded")),`Filled "${e}" with value. ${o?`Submitted \u2192 ${i.url()}`:"Not submitted."}`}finally{await i.close()}}th.exports={isPlaywrightAvailable:eh,browserNavigate:dk,browserScreenshot:fk,browserClick:pk,browserFill:hk,closeBrowser:uk,INSTALL_MSG:Qp}});var Xc=Q((WA,sh)=>{"use strict";var mk=require("util"),nh=require("stream"),Xt=sh.exports=function(){nh.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};mk.inherits(Xt,nh);Xt.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))};Xt.prototype.write=function(t,e){if(!this.writable)return this.emit("error",new Error("Stream not writable")),!1;let n;return Buffer.isBuffer(t)?n=t:n=Buffer.from(t,e||this._encoding),this._buffers.push(n),this._buffered+=n.length,this._process(),this._reads&&this._reads.length===0&&(this._paused=!0),this.writable&&!this._paused};Xt.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()))};Xt.prototype.destroySoon=Xt.prototype.end;Xt.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};Xt.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};Xt.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))};Xt.prototype._processRead=function(t){this._reads.shift();let e=0,n=0,o=Buffer.alloc(t.length);for(;e<t.length;){let s=this._buffers[n++],r=Math.min(s.length,t.length-e);s.copy(o,e,0,r),e+=r,r!==s.length&&(this._buffers[--n]=s.slice(r))}n>0&&this._buffers.splice(0,n),this._buffered-=t.length,t.func.call(this,o)};Xt.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 Jc=Q(Vc=>{"use strict";var Ln=[{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]}];Vc.getImagePasses=function(t,e){let n=[],o=t%8,s=e%8,r=(t-o)/8,i=(e-s)/8;for(let a=0;a<Ln.length;a++){let c=Ln[a],u=r*c.x.length,l=i*c.y.length;for(let d=0;d<c.x.length&&c.x[d]<o;d++)u++;for(let d=0;d<c.y.length&&c.y[d]<s;d++)l++;u>0&&l>0&&n.push({width:u,height:l,index:a})}return n};Vc.getInterlaceIterator=function(t){return function(e,n,o){let s=e%Ln[o].x.length,r=(e-s)/Ln[o].x.length*8+Ln[o].x[s],i=n%Ln[o].y.length,a=(n-i)/Ln[o].y.length*8+Ln[o].y[i];return r*4+a*t*4}}});var Zc=Q((YA,oh)=>{"use strict";oh.exports=function(e,n,o){let s=e+n-o,r=Math.abs(s-e),i=Math.abs(s-n),a=Math.abs(s-o);return r<=i&&r<=a?e:i<=a?n:o}});var Qc=Q((GA,ih)=>{"use strict";var gk=Jc(),yk=Zc();function rh(t,e,n){let o=t*e;return n!==8&&(o=Math.ceil(o/(8/n))),o}var Xs=ih.exports=function(t,e){let n=t.width,o=t.height,s=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=[],s){let a=gk.getImagePasses(n,o);for(let c=0;c<a.length;c++)this._images.push({byteWidth:rh(a[c].width,r,i),height:a[c].height,lineIndex:0})}else this._images.push({byteWidth:rh(n,r,i),height:o,lineIndex:0});i===8?this._xComparison=r:i===16?this._xComparison=r*2:this._xComparison=1};Xs.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};Xs.prototype._unFilterType1=function(t,e,n){let o=this._xComparison,s=o-1;for(let r=0;r<n;r++){let i=t[1+r],a=r>s?e[r-o]:0;e[r]=i+a}};Xs.prototype._unFilterType2=function(t,e,n){let o=this._lastLine;for(let s=0;s<n;s++){let r=t[1+s],i=o?o[s]:0;e[s]=r+i}};Xs.prototype._unFilterType3=function(t,e,n){let o=this._xComparison,s=o-1,r=this._lastLine;for(let i=0;i<n;i++){let a=t[1+i],c=r?r[i]:0,u=i>s?e[i-o]:0,l=Math.floor((u+c)/2);e[i]=a+l}};Xs.prototype._unFilterType4=function(t,e,n){let o=this._xComparison,s=o-1,r=this._lastLine;for(let i=0;i<n;i++){let a=t[1+i],c=r?r[i]:0,u=i>s?e[i-o]:0,l=i>s&&r?r[i-o]:0,d=yk(u,c,l);e[i]=a+d}};Xs.prototype._reverseFilterLine=function(t){let e=t[0],n,o=this._images[this._imageIndex],s=o.byteWidth;if(e===0)n=t.slice(1,s+1);else switch(n=Buffer.alloc(s),e){case 1:this._unFilterType1(t,n,s);break;case 2:this._unFilterType2(t,n,s);break;case 3:this._unFilterType3(t,n,s);break;case 4:this._unFilterType4(t,n,s);break;default:throw new Error("Unrecognised filter type - "+e)}this.write(n),o.lineIndex++,o.lineIndex>=o.height?(this._lastLine=null,this._imageIndex++,o=this._images[this._imageIndex]):this._lastLine=n,o?this.read(o.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}});var lh=Q((zA,ch)=>{"use strict";var wk=require("util"),ah=Xc(),bk=Qc(),$k=ch.exports=function(t){ah.call(this);let e=[],n=this;this._filter=new bk(t,{read:this.read.bind(this),write:function(o){e.push(o)},complete:function(){n.emit("complete",Buffer.concat(e))}}),this._filter.start()};wk.inherits($k,ah)});var Vs=Q((KA,uh)=>{"use strict";uh.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 nl=Q((XA,dh)=>{"use strict";var el=[];(function(){for(let t=0;t<256;t++){let e=t;for(let n=0;n<8;n++)e&1?e=3988292384^e>>>1:e=e>>>1;el[t]=e}})();var tl=dh.exports=function(){this._crc=-1};tl.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=el[(this._crc^t[e])&255]^this._crc>>>8;return!0};tl.prototype.crc32=function(){return this._crc^-1};tl.crc32=function(t){let e=-1;for(let n=0;n<t.length;n++)e=el[(e^t[n])&255]^e>>>8;return e^-1}});var sl=Q((VA,fh)=>{"use strict";var st=Vs(),_k=nl(),it=fh.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[st.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[st.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[st.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[st.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[st.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[st.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(){}};it.prototype.start=function(){this.read(st.PNG_SIGNATURE.length,this._parseSignature.bind(this))};it.prototype._parseSignature=function(t){let e=st.PNG_SIGNATURE;for(let n=0;n<e.length;n++)if(t[n]!==e[n]){this.error(new Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};it.prototype._parseChunkBegin=function(t){let e=t.readUInt32BE(0),n=t.readUInt32BE(4),o="";for(let r=4;r<8;r++)o+=String.fromCharCode(t[r]);let s=!!(t[4]&32);if(!this._hasIHDR&&n!==st.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new _k,this._crc.write(Buffer.from(o)),this._chunks[n])return this._chunks[n](e);if(!s){this.error(new Error("Unsupported critical chunk type "+o));return}this.read(e+4,this._skipChunk.bind(this))};it.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};it.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};it.prototype._parseChunkEnd=function(t){let e=t.readInt32BE(0),n=this._crc.crc32();if(this._options.checkCRC&&n!==e){this.error(new Error("Crc error - "+e+" - "+n));return}this._hasIEND||this.read(8,this._parseChunkBegin.bind(this))};it.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};it.prototype._parseIHDR=function(t){this._crc.write(t);let e=t.readUInt32BE(0),n=t.readUInt32BE(4),o=t[8],s=t[9],r=t[10],i=t[11],a=t[12];if(o!==8&&o!==4&&o!==2&&o!==1&&o!==16){this.error(new Error("Unsupported bit depth "+o));return}if(!(s in st.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=s;let c=st.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:n,depth:o,interlace:!!a,palette:!!(s&st.COLORTYPE_PALETTE),color:!!(s&st.COLORTYPE_COLOR),alpha:!!(s&st.COLORTYPE_ALPHA),bpp:c,colorType:s}),this._handleChunkEnd()};it.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};it.prototype._parsePLTE=function(t){this._crc.write(t);let e=Math.floor(t.length/3);for(let n=0;n<e;n++)this._palette.push([t[n*3],t[n*3+1],t[n*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};it.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};it.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===st.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===st.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===st.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};it.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};it.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/st.GAMMA_DIVISION),this._handleChunkEnd()};it.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};it.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===st.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw new Error("Expected palette not found");this.inflateData(e);let n=t-e.length;n>0?this._handleIDAT(n):this._handleChunkEnd()};it.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};it.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var ol=Q(hh=>{"use strict";var ph=Jc(),xk=[function(){},function(t,e,n,o){if(o===e.length)throw new Error("Ran out of data");let s=e[o];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=255},function(t,e,n,o){if(o+1>=e.length)throw new Error("Ran out of data");let s=e[o];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=e[o+1]},function(t,e,n,o){if(o+2>=e.length)throw new Error("Ran out of data");t[n]=e[o],t[n+1]=e[o+1],t[n+2]=e[o+2],t[n+3]=255},function(t,e,n,o){if(o+3>=e.length)throw new Error("Ran out of data");t[n]=e[o],t[n+1]=e[o+1],t[n+2]=e[o+2],t[n+3]=e[o+3]}],kk=[function(){},function(t,e,n,o){let s=e[0];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=o},function(t,e,n){let o=e[0];t[n]=o,t[n+1]=o,t[n+2]=o,t[n+3]=e[1]},function(t,e,n,o){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=o},function(t,e,n){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=e[3]}];function vk(t,e){let n=[],o=0;function s(){if(o===t.length)throw new Error("Ran out of data");let r=t[o];o++;let i,a,c,u,l,d,f,p;switch(e){default:throw new Error("unrecognised depth");case 16:f=t[o],o++,n.push((r<<8)+f);break;case 4:f=r&15,p=r>>4,n.push(p,f);break;case 2:l=r&3,d=r>>2&3,f=r>>4&3,p=r>>6&3,n.push(p,f,d,l);break;case 1:i=r&1,a=r>>1&1,c=r>>2&1,u=r>>3&1,l=r>>4&1,d=r>>5&1,f=r>>6&1,p=r>>7&1,n.push(p,f,d,l,u,c,a,i);break}}return{get:function(r){for(;n.length<r;)s();let i=n.slice(0,r);return n=n.slice(r),i},resetAfterLine:function(){n.length=0},end:function(){if(o!==t.length)throw new Error("extra data found")}}}function Sk(t,e,n,o,s,r){let i=t.width,a=t.height,c=t.index;for(let u=0;u<a;u++)for(let l=0;l<i;l++){let d=n(l,u,c);xk[o](e,s,d,r),r+=o}return r}function Ek(t,e,n,o,s,r){let i=t.width,a=t.height,c=t.index;for(let u=0;u<a;u++){for(let l=0;l<i;l++){let d=s.get(o),f=n(l,u,c);kk[o](e,d,f,r)}s.resetAfterLine()}}hh.dataToBitMap=function(t,e){let n=e.width,o=e.height,s=e.depth,r=e.bpp,i=e.interlace,a;s!==8&&(a=vk(t,s));let c;s<=8?c=Buffer.alloc(n*o*4):c=new Uint16Array(n*o*4);let u=Math.pow(2,s)-1,l=0,d,f;if(i)d=ph.getImagePasses(n,o),f=ph.getInterlaceIterator(n,o);else{let p=0;f=function(){let h=p;return p+=4,h},d=[{width:n,height:o}]}for(let p=0;p<d.length;p++)s===8?l=Sk(d[p],c,f,r,t,l):Ek(d[p],c,f,r,a,u);if(s===8){if(l!==t.length)throw new Error("extra data found")}else a.end();return c}});var rl=Q((ZA,mh)=>{"use strict";function Tk(t,e,n,o,s){let r=0;for(let i=0;i<o;i++)for(let a=0;a<n;a++){let c=s[t[r]];if(!c)throw new Error("index "+t[r]+" not in palette");for(let u=0;u<4;u++)e[r+u]=c[u];r+=4}}function Rk(t,e,n,o,s){let r=0;for(let i=0;i<o;i++)for(let a=0;a<n;a++){let c=!1;if(s.length===1?s[0]===t[r]&&(c=!0):s[0]===t[r]&&s[1]===t[r+1]&&s[2]===t[r+2]&&(c=!0),c)for(let u=0;u<4;u++)e[r+u]=0;r+=4}}function Ck(t,e,n,o,s){let r=255,i=Math.pow(2,s)-1,a=0;for(let c=0;c<o;c++)for(let u=0;u<n;u++){for(let l=0;l<4;l++)e[a+l]=Math.floor(t[a+l]*r/i+.5);a+=4}}mh.exports=function(t,e,n=!1){let o=e.depth,s=e.width,r=e.height,i=e.colorType,a=e.transColor,c=e.palette,u=t;return i===3?Tk(t,u,s,r,c):(a&&Rk(t,u,s,r,a),o!==8&&!n&&(o===16&&(u=Buffer.alloc(s*r*4)),Ck(t,u,s,r,o))),u}});var wh=Q((QA,yh)=>{"use strict";var Ak=require("util"),il=require("zlib"),gh=Xc(),Ok=lh(),Nk=sl(),Mk=ol(),Pk=rl(),un=yh.exports=function(t){gh.call(this),this._parser=new Nk(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()};Ak.inherits(un,gh);un.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};un.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=il.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 n=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,o=Math.max(n,il.Z_MIN_CHUNK);this._inflate=il.createInflate({chunkSize:o});let s=n,r=this.emit.bind(this,"error");this._inflate.on("error",function(a){s&&r(a)}),this._filter.on("complete",this._complete.bind(this));let i=this._filter.write.bind(this._filter);this._inflate.on("data",function(a){s&&(a.length>s&&(a=a.slice(0,s)),s-=a.length,i(a))}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};un.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new Ok(this._bitmapInfo)};un.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};un.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};un.prototype._simpleTransparency=function(){this._metaData.alpha=!0};un.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};un.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};un.prototype._complete=function(t){if(this.errord)return;let e;try{let n=Mk.dataToBitMap(t,this._bitmapInfo);e=Pk(n,this._bitmapInfo,this._options.skipRescale),n=null}catch(n){this._handleError(n);return}this.emit("parsed",e)}});var $h=Q((eO,bh)=>{"use strict";var Dt=Vs();bh.exports=function(t,e,n,o){let s=[Dt.COLORTYPE_COLOR_ALPHA,Dt.COLORTYPE_ALPHA].indexOf(o.colorType)!==-1;if(o.colorType===o.inputColorType){let h=(function(){let g=new ArrayBuffer(2);return new DataView(g).setInt16(0,256,!0),new Int16Array(g)[0]!==256})();if(o.bitDepth===8||o.bitDepth===16&&h)return t}let r=o.bitDepth!==16?t:new Uint16Array(t.buffer),i=255,a=Dt.COLORTYPE_TO_BPP_MAP[o.inputColorType];a===4&&!o.inputHasAlpha&&(a=3);let c=Dt.COLORTYPE_TO_BPP_MAP[o.colorType];o.bitDepth===16&&(i=65535,c*=2);let u=Buffer.alloc(e*n*c),l=0,d=0,f=o.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,w,_=i;switch(o.inputColorType){case Dt.COLORTYPE_COLOR_ALPHA:_=r[l+3],h=r[l],g=r[l+1],w=r[l+2];break;case Dt.COLORTYPE_COLOR:h=r[l],g=r[l+1],w=r[l+2];break;case Dt.COLORTYPE_ALPHA:_=r[l+1],h=r[l],g=h,w=h;break;case Dt.COLORTYPE_GRAYSCALE:h=r[l],g=h,w=h;break;default:throw new Error("input color type:"+o.inputColorType+" is not supported at present")}return o.inputHasAlpha&&(s||(_/=i,h=Math.min(Math.max(Math.round((1-_)*f.red+_*h),0),i),g=Math.min(Math.max(Math.round((1-_)*f.green+_*g),0),i),w=Math.min(Math.max(Math.round((1-_)*f.blue+_*w),0),i))),{red:h,green:g,blue:w,alpha:_}}for(let h=0;h<n;h++)for(let g=0;g<e;g++){let w=p(r,l);switch(o.colorType){case Dt.COLORTYPE_COLOR_ALPHA:case Dt.COLORTYPE_COLOR:o.bitDepth===8?(u[d]=w.red,u[d+1]=w.green,u[d+2]=w.blue,s&&(u[d+3]=w.alpha)):(u.writeUInt16BE(w.red,d),u.writeUInt16BE(w.green,d+2),u.writeUInt16BE(w.blue,d+4),s&&u.writeUInt16BE(w.alpha,d+6));break;case Dt.COLORTYPE_ALPHA:case Dt.COLORTYPE_GRAYSCALE:{let _=(w.red+w.green+w.blue)/3;o.bitDepth===8?(u[d]=_,s&&(u[d+1]=w.alpha)):(u.writeUInt16BE(_,d),s&&u.writeUInt16BE(w.alpha,d+2));break}default:throw new Error("unrecognised color Type "+o.colorType)}l+=a,d+=c}return u}});var kh=Q((tO,xh)=>{"use strict";var _h=Zc();function Lk(t,e,n,o,s){for(let r=0;r<n;r++)o[s+r]=t[e+r]}function Ik(t,e,n){let o=0,s=e+n;for(let r=e;r<s;r++)o+=Math.abs(t[r]);return o}function jk(t,e,n,o,s,r){for(let i=0;i<n;i++){let a=i>=r?t[e+i-r]:0,c=t[e+i]-a;o[s+i]=c}}function Dk(t,e,n,o){let s=0;for(let r=0;r<n;r++){let i=r>=o?t[e+r-o]:0,a=t[e+r]-i;s+=Math.abs(a)}return s}function qk(t,e,n,o,s){for(let r=0;r<n;r++){let i=e>0?t[e+r-n]:0,a=t[e+r]-i;o[s+r]=a}}function Fk(t,e,n){let o=0,s=e+n;for(let r=e;r<s;r++){let i=e>0?t[r-n]:0,a=t[r]-i;o+=Math.abs(a)}return o}function Bk(t,e,n,o,s,r){for(let i=0;i<n;i++){let a=i>=r?t[e+i-r]:0,c=e>0?t[e+i-n]:0,u=t[e+i]-(a+c>>1);o[s+i]=u}}function Uk(t,e,n,o){let s=0;for(let r=0;r<n;r++){let i=r>=o?t[e+r-o]:0,a=e>0?t[e+r-n]:0,c=t[e+r]-(i+a>>1);s+=Math.abs(c)}return s}function Wk(t,e,n,o,s,r){for(let i=0;i<n;i++){let a=i>=r?t[e+i-r]:0,c=e>0?t[e+i-n]:0,u=e>0&&i>=r?t[e+i-(n+r)]:0,l=t[e+i]-_h(a,c,u);o[s+i]=l}}function Hk(t,e,n,o){let s=0;for(let r=0;r<n;r++){let i=r>=o?t[e+r-o]:0,a=e>0?t[e+r-n]:0,c=e>0&&r>=o?t[e+r-(n+o)]:0,u=t[e+r]-_h(i,a,c);s+=Math.abs(u)}return s}var Yk={0:Lk,1:jk,2:qk,3:Bk,4:Wk},Gk={0:Ik,1:Dk,2:Fk,3:Uk,4:Hk};xh.exports=function(t,e,n,o,s){let r;if(!("filterType"in o)||o.filterType===-1)r=[0,1,2,3,4];else if(typeof o.filterType=="number")r=[o.filterType];else throw new Error("unrecognised filter types");o.bitDepth===16&&(s*=2);let i=e*s,a=0,c=0,u=Buffer.alloc((i+1)*n),l=r[0];for(let d=0;d<n;d++){if(r.length>1){let f=1/0;for(let p=0;p<r.length;p++){let h=Gk[r[p]](t,c,i,s);h<f&&(l=r[p],f=h)}}u[a]=l,a++,Yk[l](t,c,i,u,a,s),a+=i,c+=i}return u}});var al=Q((nO,vh)=>{"use strict";var pt=Vs(),zk=nl(),Kk=$h(),Xk=kh(),Vk=require("zlib"),In=vh.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||Vk.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:pt.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:pt.COLORTYPE_COLOR_ALPHA,[pt.COLORTYPE_GRAYSCALE,pt.COLORTYPE_COLOR,pt.COLORTYPE_COLOR_ALPHA,pt.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([pt.COLORTYPE_GRAYSCALE,pt.COLORTYPE_COLOR,pt.COLORTYPE_COLOR_ALPHA,pt.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")};In.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};In.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};In.prototype.filterData=function(t,e,n){let o=Kk(t,e,n,this._options),s=pt.COLORTYPE_TO_BPP_MAP[this._options.colorType];return Xk(o,e,n,this._options,s)};In.prototype._packChunk=function(t,e){let n=e?e.length:0,o=Buffer.alloc(n+12);return o.writeUInt32BE(n,0),o.writeUInt32BE(t,4),e&&e.copy(o,8),o.writeInt32BE(zk.crc32(o.slice(4,o.length-4)),o.length-4),o};In.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*pt.GAMMA_DIVISION),0),this._packChunk(pt.TYPE_gAMA,e)};In.prototype.packIHDR=function(t,e){let n=Buffer.alloc(13);return n.writeUInt32BE(t,0),n.writeUInt32BE(e,4),n[8]=this._options.bitDepth,n[9]=this._options.colorType,n[10]=0,n[11]=0,n[12]=0,this._packChunk(pt.TYPE_IHDR,n)};In.prototype.packIDAT=function(t){return this._packChunk(pt.TYPE_IDAT,t)};In.prototype.packIEND=function(){return this._packChunk(pt.TYPE_IEND,null)}});var Rh=Q((sO,Th)=>{"use strict";var Jk=require("util"),Sh=require("stream"),Zk=Vs(),Qk=al(),Eh=Th.exports=function(t){Sh.call(this);let e=t||{};this._packer=new Qk(e),this._deflate=this._packer.createDeflate(),this.readable=!0};Jk.inherits(Eh,Sh);Eh.prototype.pack=function(t,e,n,o){this.emit("data",Buffer.from(Zk.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,n)),o&&this.emit("data",this._packer.packGAMA(o));let s=this._packer.filterData(t,e,n);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(s)}});var Ph=Q((Ho,Mh)=>{"use strict";var Ch=require("assert").ok,Js=require("zlib"),ev=require("util"),Ah=require("buffer").kMaxLength;function ts(t){if(!(this instanceof ts))return new ts(t);t&&t.chunkSize<Js.Z_MIN_CHUNK&&(t.chunkSize=Js.Z_MIN_CHUNK),Js.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 tv(t){return new ts(t)}function Oh(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}ts.prototype._processChunk=function(t,e,n){if(typeof n=="function")return Js.Inflate._processChunk.call(this,t,e,n);let o=this,s=t&&t.length,r=this._chunkSize-this._offset,i=this._maxLength,a=0,c=[],u=0,l;this.on("error",function(h){l=h});function d(h,g){if(o._hadError)return;let w=r-g;if(Ch(w>=0,"have should not go down"),w>0){let _=o._buffer.slice(o._offset,o._offset+w);if(o._offset+=w,_.length>i&&(_=_.slice(0,i)),c.push(_),u+=_.length,i-=_.length,i===0)return!1}return(g===0||o._offset>=o._chunkSize)&&(r=o._chunkSize,o._offset=0,o._buffer=Buffer.allocUnsafe(o._chunkSize)),g===0?(a+=s-h,s=h,!0):!1}Ch(this._handle,"zlib binding closed");let f;do f=this._handle.writeSync(e,t,a,s,this._buffer,this._offset,r),f=f||this._writeState;while(!this._hadError&&d(f[0],f[1]));if(this._hadError)throw l;if(u>=Ah)throw Oh(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+Ah.toString(16)+" bytes");let p=Buffer.concat(c,u);return Oh(this),p};ev.inherits(ts,Js.Inflate);function nv(t,e){if(typeof e=="string"&&(e=Buffer.from(e)),!(e instanceof Buffer))throw new TypeError("Not a string or buffer");let n=t._finishFlushFlag;return n==null&&(n=Js.Z_FINISH),t._processChunk(e,n)}function Nh(t,e){return nv(new ts(e),t)}Mh.exports=Ho=Nh;Ho.Inflate=ts;Ho.createInflate=tv;Ho.inflateSync=Nh});var cl=Q((oO,Ih)=>{"use strict";var Lh=Ih.exports=function(t){this._buffer=t,this._reads=[]};Lh.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};Lh.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 Dh=Q(jh=>{"use strict";var sv=cl(),ov=Qc();jh.process=function(t,e){let n=[],o=new sv(t);return new ov(e,{read:o.read.bind(o),write:function(r){n.push(r)},complete:function(){}}).start(),o.process(),Buffer.concat(n)}});var Uh=Q((iO,Bh)=>{"use strict";var qh=!0,Fh=require("zlib"),rv=Ph();Fh.deflateSync||(qh=!1);var iv=cl(),av=Dh(),cv=sl(),lv=ol(),uv=rl();Bh.exports=function(t,e){if(!qh)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n;function o(E){n=E}let s;function r(E){s=E}function i(E){s.transColor=E}function a(E){s.palette=E}function c(){s.alpha=!0}let u;function l(E){u=E}let d=[];function f(E){d.push(E)}let p=new iv(t);if(new cv(e,{read:p.read.bind(p),error:o,metadata:r,gamma:l,palette:a,transColor:i,inflateData:f,simpleTransparency:c}).start(),p.process(),n)throw n;let g=Buffer.concat(d);d.length=0;let w;if(s.interlace)w=Fh.inflateSync(g);else{let v=((s.width*s.bpp*s.depth+7>>3)+1)*s.height;w=rv(g,{chunkSize:v,maxLength:v})}if(g=null,!w||!w.length)throw new Error("bad png - invalid inflate data response");let _=av.process(w,s);g=null;let S=lv.dataToBitMap(_,s);_=null;let A=uv(S,s,e.skipRescale);return s.data=A,s.gamma=u||0,s}});var Gh=Q((aO,Yh)=>{"use strict";var Wh=!0,Hh=require("zlib");Hh.deflateSync||(Wh=!1);var dv=Vs(),fv=al();Yh.exports=function(t,e){if(!Wh)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n=e||{},o=new fv(n),s=[];s.push(Buffer.from(dv.PNG_SIGNATURE)),s.push(o.packIHDR(t.width,t.height)),t.gamma&&s.push(o.packGAMA(t.gamma));let r=o.filterData(t.data,t.width,t.height),i=Hh.deflateSync(r,o.getDeflateOptions());if(r=null,!i||!i.length)throw new Error("bad png - invalid compressed data response");return s.push(o.packIDAT(i)),s.push(o.packIEND()),Buffer.concat(s)}});var zh=Q(ll=>{"use strict";var pv=Uh(),hv=Gh();ll.read=function(t,e){return pv(t,e||{})};ll.write=function(t,e){return hv(t,e)}});var Vh=Q(Xh=>{"use strict";var mv=require("util"),Kh=require("stream"),gv=wh(),yv=Rh(),wv=zh(),gt=Xh.PNG=function(t){Kh.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 gv(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 yv(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"))};mv.inherits(gt,Kh);gt.sync=wv;gt.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)};gt.prototype.parse=function(t,e){if(e){let n,o;n=function(s){this.removeListener("error",o),this.data=s,e(null,this)}.bind(this),o=function(s){this.removeListener("parsed",n),e(s,null)}.bind(this),this.once("parsed",n),this.once("error",o)}return this.end(t),this};gt.prototype.write=function(t){return this._parser.write(t),!0};gt.prototype.end=function(t){this._parser.end(t)};gt.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};gt.prototype._gamma=function(t){this.gamma=t};gt.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};gt.bitblt=function(t,e,n,o,s,r,i,a){if(n|=0,o|=0,s|=0,r|=0,i|=0,a|=0,n>t.width||o>t.height||n+s>t.width||o+r>t.height)throw new Error("bitblt reading outside image");if(i>e.width||a>e.height||i+s>e.width||a+r>e.height)throw new Error("bitblt writing outside image");for(let c=0;c<r;c++)t.data.copy(e.data,(a+c)*e.width+i<<2,(o+c)*t.width+n<<2,(o+c)*t.width+n+s<<2)};gt.prototype.bitblt=function(t,e,n,o,s,r,i){return gt.bitblt(this,t,e,n,o,s,r,i),this};gt.adjustGamma=function(t){if(t.gamma){for(let e=0;e<t.height;e++)for(let n=0;n<t.width;n++){let o=t.width*e+n<<2;for(let s=0;s<3;s++){let r=t.data[o+s]/255;r=Math.pow(r,1/2.2/t.gamma),t.data[o+s]=Math.round(r*255)}}t.gamma=0}};gt.prototype.adjustGamma=function(){gt.adjustGamma(this)}});var tm={};Fw(tm,{default:()=>Qh});function Qh(t,e,n,o,s,r={}){let{threshold:i=.1,alpha:a=.1,aaColor:c=[255,255,0],diffColor:u=[255,0,0],includeAA:l,diffColorAlt:d,diffMask:f}=r;if(!ul(t)||!ul(e)||n&&!ul(n))throw new Error("Image data: Uint8Array, Uint8ClampedArray or Buffer expected.");if(t.length!==e.length||n&&n.length!==t.length)throw new Error("Image sizes do not match.");if(t.length!==o*s*4)throw new Error("Image data size does not match width/height.");let p=o*s,h=new Uint32Array(t.buffer,t.byteOffset,p),g=new Uint32Array(e.buffer,e.byteOffset,p),w=!0;for(let le=0;le<p;le++)if(h[le]!==g[le]){w=!1;break}if(w){if(n&&!f)for(let le=0;le<p;le++)Zh(t,4*le,a,n);return 0}let _=35215*i*i,[S,A,E]=c,[v,N,ne]=u,[oe,ue,fe]=d||u,ie=0;for(let le=0;le<s;le++)for(let T=0;T<o;T++){let F=le*o+T,ee=F*4,be=h[F]===g[F]?0:em(t,e,ee,ee,!1);if(Math.abs(be)>_){let ve=Jh(t,T,le,o,s,h,g)||Jh(e,T,le,o,s,g,h);!l&&ve?n&&!f&&Mi(n,ee,S,A,E):(n&&(be<0?Mi(n,ee,oe,ue,fe):Mi(n,ee,v,N,ne)),ie++)}else n&&!f&&Zh(t,ee,a,n)}return ie}function ul(t){return ArrayBuffer.isView(t)&&t.BYTES_PER_ELEMENT===1}function Jh(t,e,n,o,s,r,i){let a=Math.max(e-1,0),c=Math.max(n-1,0),u=Math.min(e+1,o-1),l=Math.min(n+1,s-1),d=n*o+e,f=e===a||e===u||n===c||n===l?1:0,p=0,h=0,g=0,w=0,_=0,S=0;for(let A=a;A<=u;A++)for(let E=c;E<=l;E++){if(A===e&&E===n)continue;let v=em(t,t,d*4,(E*o+A)*4,!0);if(v===0){if(f++,f>2)return!1}else v<p?(p=v,g=A,w=E):v>h&&(h=v,_=A,S=E)}return p===0||h===0?!1:Ni(r,g,w,o,s)&&Ni(i,g,w,o,s)||Ni(r,_,S,o,s)&&Ni(i,_,S,o,s)}function Ni(t,e,n,o,s){let r=Math.max(e-1,0),i=Math.max(n-1,0),a=Math.min(e+1,o-1),c=Math.min(n+1,s-1),u=t[n*o+e],l=e===r||e===a||n===i||n===c?1:0;for(let d=r;d<=a;d++)for(let f=i;f<=c;f++)if(!(d===e&&f===n)&&(l+=+(u===t[f*o+d]),l>2))return!0;return!1}function em(t,e,n,o,s){let r=t[n],i=t[n+1],a=t[n+2],c=t[n+3],u=e[o],l=e[o+1],d=e[o+2],f=e[o+3],p=r-u,h=i-l,g=a-d,w=c-f;if(!p&&!h&&!g&&!w)return 0;if(c<255||f<255){let v=48+159*(n%2),N=48+159*((n/1.618033988749895|0)%2),ne=48+159*((n/2.618033988749895|0)%2);p=(r*c-u*f-v*w)/255,h=(i*c-l*f-N*w)/255,g=(a*c-d*f-ne*w)/255}let _=p*.29889531+h*.58662247+g*.11448223;if(s)return _;let S=p*.59597799-h*.2741761-g*.32180189,A=p*.21147017-h*.52261711+g*.31114694,E=.5053*_*_+.299*S*S+.1957*A*A;return _>0?-E:E}function Mi(t,e,n,o,s){t[e+0]=n,t[e+1]=o,t[e+2]=s,t[e+3]=255}function Zh(t,e,n,o){let s=255+(t[e]*.29889531+t[e+1]*.58662247+t[e+2]*.11448223-255)*n*t[e+3]/255;Mi(o,e,s,s,s)}var nm=qw(()=>{});var ns=Q((uO,am)=>{var vn=require("fs"),bv=require("path"),$v=require("os"),_v="nex-visual-";function om(t){return bv.join($v.tmpdir(),`${_v}${Date.now()}-${t}`)}var dl=null;function Pi(){return dl||(dl=Vh().PNG),dl}var fl=null;function xv(){if(!fl){let t=(nm(),Uw(tm));fl=t.default||t}return fl}function ml(t,e,{threshold:n=.1}={}){let o=Pi(),s=xv(),r=o.sync.read(vn.readFileSync(t)),i=o.sync.read(vn.readFileSync(e)),a=Math.max(r.width,i.width),c=Math.max(r.height,i.height),u=sm(r,a,c),l=sm(i,a,c),d=new o({width:a,height:c}),f=s(u,l,d.data,a,c,{threshold:n,includeAA:!1}),p=a*c,h=(f/p*100).toFixed(1),g=kv(d.data,a,c,3,3),w=om("diff.png");return vn.writeFileSync(w,o.sync.write(d),{mode:384}),{diffPath:w,diffPercent:parseFloat(h),totalPixels:p,changedPixels:f,regionSummary:g,beforePath:t,afterPath:e,width:a,height:c}}function sm(t,e,n){if(t.width===e&&t.height===n)return t.data;let o=Buffer.alloc(e*n*4,0);for(let s=0;s<t.height;s++){let r=s*t.width*4,i=s*e*4;t.data.copy(o,i,r,r+t.width*4)}return o}function kv(t,e,n,o,s){let r=[["top-left","top-center","top-right"],["middle-left","center","middle-right"],["bottom-left","bottom-center","bottom-right"]],i=Math.ceil(e/o),a=Math.ceil(n/s),c=[];for(let u=0;u<s;u++)for(let l=0;l<o;l++){let d=0,f=0,p=l*i,h=u*a,g=Math.min(p+i,e),w=Math.min(h+a,n);for(let _=h;_<w;_++)for(let S=p;S<g;S++){f++;let A=(_*e+S)*4;(t[A]>0||t[A+1]>0)&&d++}if(d>0){let _=(d/f*100).toFixed(1),S=r[u]&&r[u][l]?r[u][l]:`row${u}-col${l}`;c.push({name:S,changedPercent:parseFloat(_),changed:d,total:f})}}return c.sort((u,l)=>l.changedPercent-u.changedPercent),c}var rm=[{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 vv(t,{viewports:e=rm,height:n=800,fullPage:o=!1,timeout:s=3e4}={}){let{browserScreenshot:r}=kn(),i=[];for(let a of e){let c=await r(t,{width:a.width,height:n,fullPage:o,timeout:s});i.push({label:a.label,width:a.width,path:c.path,base64:c.base64,media_type:c.media_type})}return i}function im(t,e=[]){let n=Pi(),o=n.sync.read(vn.readFileSync(t));for(let i of e){let a=Sv(i.color||"#FF0000");i.type==="box"?(Ev(o,i.x||0,i.y||0,i.width||50,i.height||50,a,i.thickness||3),i.label&&hl(o,i.x||0,(i.y||0)-14,i.label,a)):i.type==="arrow"?(Tv(o,i.x||0,i.y||0,i.toX||i.x+50,i.toY||i.y,a,i.thickness||3),i.label&&hl(o,i.x||0,(i.y||0)-14,i.label,a)):i.type==="circle"&&(Rv(o,i.x||0,i.y||0,i.radius||20,a,i.thickness||3),i.label&&hl(o,(i.x||0)-(i.radius||20),(i.y||0)-(i.radius||20)-14,i.label,a))}let s=om("annotated.png");vn.writeFileSync(s,n.sync.write(o),{mode:384});let r=vn.readFileSync(s).toString("base64");return{path:s,base64:r,media_type:"image/png"}}function Sv(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 dn(t,e,n,o){if(e<0||n<0||e>=t.width||n>=t.height)return;let s=(n*t.width+e)*4;t.data[s]=o.r,t.data[s+1]=o.g,t.data[s+2]=o.b,t.data[s+3]=o.a}function Ev(t,e,n,o,s,r,i=3){for(let a=0;a<i;a++){for(let c=0;c<o;c++)dn(t,e+c,n+a,r),dn(t,e+c,n+s-1-a,r);for(let c=0;c<s;c++)dn(t,e+a,n+c,r),dn(t,e+o-1-a,n+c,r)}}function pl(t,e,n,o,s,r,i=3){let a=Math.abs(o-e),c=Math.abs(s-n),u=e<o?1:-1,l=n<s?1:-1,d=a-c,f=e,p=n;for(;;){let h=Math.floor(i/2);for(let w=-h;w<=h;w++)for(let _=-h;_<=h;_++)dn(t,f+w,p+_,r);if(f===o&&p===s)break;let g=2*d;g>-c&&(d-=c,f+=u),g<a&&(d+=a,p+=l)}}function Tv(t,e,n,o,s,r,i=3){pl(t,e,n,o,s,r,i);let a=Math.atan2(s-n,o-e),c=15,u=a+Math.PI*.8,l=a-Math.PI*.8;pl(t,o,s,Math.round(o+c*Math.cos(u)),Math.round(s+c*Math.sin(u)),r,i),pl(t,o,s,Math.round(o+c*Math.cos(l)),Math.round(s+c*Math.sin(l)),r,i)}function Rv(t,e,n,o,s,r=3){for(let i=0;i<r;i++){let a=o-i;for(let c=0;c<360;c+=.5){let u=c*Math.PI/180,l=Math.round(e+a*Math.cos(u)),d=Math.round(n+a*Math.sin(u));dn(t,l,d,s)}}}function hl(t,e,n,o,s){let i=o.length*6+4,a=12;for(let c=0;c<a;c++)for(let u=0;u<i;u++)dn(t,e+u,n+c,{r:0,g:0,b:0,a:200});for(let c=0;c<i;c++)dn(t,e+c,n+a-1,s),dn(t,e+c,n+a-2,s);for(let c=0;c<o.length;c++){let u=e+2+c*6;for(let l=2;l<9;l++)for(let d=0;d<4;d++)dn(t,u+d,n+l,s)}}async function*Cv(t,e,{maxIterations:n=20,hmrDelay:o=1500,width:s=1280,height:r=800,timeout:i=3e4}={}){let{browserScreenshot:a}=kn(),c=Av("chokidar"),u=await a(t,{width:s,height:r,timeout:i});if(yield{iteration:0,type:"baseline",path:u.path,base64:u.base64,media_type:u.media_type},!c){yield{iteration:-1,type:"error",message:"chokidar not installed \u2014 watch mode requires it. Install with: npm install chokidar"};return}let l=0,d=!1,f=c.watch(e,{ignoreInitial:!0,ignored:/(node_modules|\.git|dist)/});f.on("change",()=>{d=!0});try{for(;l<n;){await Nv(()=>d,3e5),d=!1,l++,await Ov(o);let p=await a(t,{width:s,height:r,timeout:i}),h=null;try{h=ml(u.path,p.path)}catch{}u=p,yield{iteration:l,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 Av(t){try{return require(t)}catch{return null}}function Ov(t){return new Promise(e=>setTimeout(e,t))}function Nv(t,e=6e4){return new Promise((n,o)=>{let s=setInterval(()=>{t()&&(clearInterval(s),clearTimeout(r),n())},200),r=setTimeout(()=>{clearInterval(s),o(new Error("Watch timeout \u2014 no file changes detected"))},e)})}function Mv(t,{sampleRate:e=4}={}){let o=Pi().sync.read(vn.readFileSync(t)),s=new Map;for(let u=0;u<o.height;u+=e)for(let l=0;l<o.width;l+=e){let d=(u*o.width+l)*4,f=o.data[d],p=o.data[d+1],h=o.data[d+2];if(o.data[d+3]<128)continue;let w=Math.round(f/8)*8,_=Math.round(p/8)*8,S=Math.round(h/8)*8,A=`${w},${_},${S}`;s.set(A,(s.get(A)||0)+1)}let r=[...s.entries()].sort((u,l)=>l[1]-u[1]).slice(0,20),i=r.reduce((u,l)=>u+l[1],0),a=r.map(([u,l])=>{let[d,f,p]=u.split(",").map(Number);return{hex:Pv(d,f,p),rgb:`rgb(${d}, ${f}, ${p})`,frequency:parseFloat((l/i*100).toFixed(1)),category:Lv(d,f,p)}}),c=Iv(o);return{colors:a,spacing:c,dimensions:{width:o.width,height:o.height},imagePath:t}}function Pv(t,e,n){return"#"+[t,e,n].map(o=>Math.min(255,o).toString(16).padStart(2,"0")).join("")}function Lv(t,e,n){let o=(t*299+e*587+n*114)/1e3;return o>240?"white/background":o<30?"black/text":o<80?"dark":t>200&&e<100&&n<100?"red/danger":t<100&&e>150&&n<100?"green/success":t<100&&e<100&&n>200?"blue/primary":t>200&&e>200&&n<100?"yellow/warning":t>200&&e>100&&n<50?"orange/accent":o>200?"light/subtle":"midtone"}function Iv(t){let e=[],n=!1,o=0,s=jv(t);for(let i=0;i<t.height;i++){let a=!0;for(let c=0;c<t.width;c+=4){let u=(i*t.width+c)*4;if(Math.abs(t.data[u]-s.r)>20||Math.abs(t.data[u+1]-s.g)>20||Math.abs(t.data[u+2]-s.b)>20){a=!1;break}}if(a&&n)n=!1,o=i;else if(!a&&!n&&(n=!0,o>0)){let c=i-o;c>=4&&c<=200&&e.push(c)}}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 jv(t){let e=[[0,0],[t.width-1,0],[0,t.height-1],[t.width-1,t.height-1]],n=0,o=0,s=0;for(let[r,i]of e){let a=(i*t.width+r)*4;n+=t.data[a],o+=t.data[a+1],s+=t.data[a+2]}return{r:Math.round(n/4),g:Math.round(o/4),b:Math.round(s/4)}}async function Dv(t,e,{width:n,height:o=800,fullPage:s=!1,threshold:r=.1,timeout:i=3e4}={}){let{browserScreenshot:a}=kn(),u=Pi().sync.read(vn.readFileSync(e)),l=n||u.width,d=o||u.height,f=await a(t,{width:l,height:d,fullPage:s,timeout:i}),p=ml(e,f.path,{threshold:r}),h=im(f.path,p.regionSummary.filter(g=>g.changedPercent>1).map((g,w)=>{let A=Math.ceil(p.width/3),E=Math.ceil(p.height/3),v=[["top-left","top-center","top-right"],["middle-left","center","middle-right"],["bottom-left","bottom-center","bottom-right"]],N=0,ne=0;for(let oe=0;oe<3;oe++)for(let ue=0;ue<3;ue++)v[oe][ue]===g.name&&(N=ue,ne=oe);return{type:"box",x:N*A+2,y:ne*E+2,width:A-4,height:E-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:vn.readFileSync(p.diffPath).toString("base64"),annotatedBase64:h.base64}}am.exports={pixelDiff:ml,responsiveSweep:vv,annotateImage:im,visualWatch:Cv,extractDesignTokens:Mv,designCompare:Dv,DEFAULT_VIEWPORTS:rm}});var gl=Q((dO,cm)=>{var{C:qe}=rt(),Go="",yt=[],Yo=0,ss=null;function qv(t){ss=t}function Fv(t,e){Go=t,yt=[],Yo=0;for(let o of e){Yo++;let s=`t${Yo}`;yt.push({id:s,description:o.description||o.title||o.name||o.task||`Task ${Yo}`,status:"pending",dependsOn:o.depends_on||[],result:null})}let n=yt.map(o=>({...o}));return ss&&ss("create",{name:t,tasks:n}),n}function Bv(t,e,n){let o=yt.find(s=>s.id===t);return o?(o.status=e,n!==void 0&&(o.result=n),ss&&ss("update",{id:t,status:e,result:n}),{...o}):null}function Uv(){return{name:Go,tasks:yt.map(t=>({...t}))}}function Wv(){Go="",yt=[],Yo=0,ss&&ss("clear",{})}function Hv(){return yt.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let n=yt.find(o=>o.id===e);return n&&n.status==="done"}))}function Yv(){if(yt.length===0)return`${qe.dim}No active tasks${qe.reset}`;let t=[];Go&&(t.push(` ${qe.bold}${qe.cyan}Tasks: ${Go}${qe.reset}`),t.push(` ${qe.dim}${"\u2500".repeat(40)}${qe.reset}`));for(let s of yt){let r,i;switch(s.status){case"done":r="\u2713",i=qe.green;break;case"in_progress":r="\u2192",i=qe.cyan;break;case"failed":r="\u2717",i=qe.red;break;default:r="\xB7",i=qe.dim}let a=s.dependsOn.length>0?` ${qe.dim}(after: ${s.dependsOn.join(", ")})${qe.reset}`:"",c=`[${s.status}]`,u=s.description.length>50?s.description.substring(0,47)+"...":s.description;if(t.push(` ${i}${r}${qe.reset} ${qe.bold}${s.id}${qe.reset} ${u.padEnd(40)} ${i}${c}${qe.reset}${a}`),s.result&&s.status==="done"){let l=s.result.length>60?s.result.substring(0,57)+"...":s.result;t.push(` ${qe.dim}\u2192 ${l}${qe.reset}`)}}let e=yt.filter(s=>s.status==="done").length,n=yt.filter(s=>s.status==="failed").length,o=yt.length;return t.push(` ${qe.dim}${"\u2500".repeat(40)}${qe.reset}`),t.push(` ${qe.dim}${e}/${o} done${n>0?`, ${n} failed`:""}${qe.reset}`),t.join(`
152
- `)}function Gv(){return yt.length>0&&yt.some(t=>t.status==="pending"||t.status==="in_progress")}cm.exports={createTasks:Fv,updateTask:Bv,getTaskList:Uv,clearTasks:Wv,getReadyTasks:Hv,renderTaskList:Yv,setOnChange:qv,hasActiveTasks:Gv}});var Li=Q((fO,um)=>{var zo={"devstral-2":{staleWarn:3e4,staleAbort:9e4,investigationCap:18,postEditCap:10,briefing:`You are devstral-2, a strong coding model optimized for agentic tasks.
150
+ Then restart nex-code.`;function th(){if(Wo!==null)return Wo;try{require("playwright"),Wo=!0}catch{Wo=!1}return Wo}async function Oi(){if(!th())throw new Error(eh);return Kc||(Kc=require("playwright")),(!xn||!xn.isConnected())&&(xn=await Kc.chromium.launch({headless:!0})),xn}async function uk(){if(xn){try{await xn.close()}catch(t){console.error("closeBrowser failed:",t.message)}xn=null}}process.on("exit",()=>{if(xn)try{xn.close()}catch(t){console.error("Error closing browser on exit:",t.message)}});async function dk(t,{timeout:e=3e4,waitFor:n="domcontentloaded"}={}){let s=await(await Oi()).newPage();try{await s.goto(t,{waitUntil:n,timeout:e});let r=await s.title(),i=await s.evaluate(()=>(document.querySelectorAll("script,style,nav,footer,header,aside,[role=navigation]").forEach(u=>u.remove()),document.body?.innerText||"")),a=await s.evaluate(()=>Array.from(document.querySelectorAll("a[href]")).slice(0,30).map(c=>({text:(c.innerText||c.textContent||"").trim().substring(0,80),href:c.href})).filter(c=>c.text&&c.href&&!c.href.startsWith("javascript:")));return{title:r,url:s.url(),text:i.substring(0,8e3)+(i.length>8e3?`
151
+ ...(truncated)`:""),links:a.slice(0,20)}}finally{await s.close()}}async function fk(t,{width:e=1280,height:n=800,fullPage:o=!1,timeout:s=3e4}={}){let i=await(await Oi()).newPage();try{await i.setViewportSize({width:e,height:n}),await i.goto(t,{waitUntil:"networkidle",timeout:s});let a=await i.screenshot({type:"png",fullPage:o}),c=require("os"),u=require("path"),l=require("fs"),d=u.join(c.tmpdir(),`nex-screenshot-${Date.now()}.png`);return l.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 pk(t,{selector:e,text:n,timeout:o=3e4}={}){if(!e&&!n)throw new Error("selector or text is required");let r=await(await Oi()).newPage();try{await r.goto(t,{waitUntil:"domcontentloaded",timeout:o}),n?await r.getByText(n,{exact:!1}).first().click({timeout:1e4}):await r.locator(e).first().click({timeout:1e4}),await r.waitForLoadState("domcontentloaded");let i=await r.title();return`Clicked \u2014 now at: ${r.url()} (${i})`}finally{await r.close()}}async function hk(t,{selector:e,value:n,submit:o=!1,timeout:s=3e4}={}){if(!e||n===void 0)throw new Error("selector and value are required");let i=await(await Oi()).newPage();try{return await i.goto(t,{waitUntil:"domcontentloaded",timeout:s}),await i.fill(e,String(n)),o&&(await i.keyboard.press("Enter"),await i.waitForLoadState("domcontentloaded")),`Filled "${e}" with value. ${o?`Submitted \u2192 ${i.url()}`:"Not submitted."}`}finally{await i.close()}}nh.exports={isPlaywrightAvailable:th,browserNavigate:dk,browserScreenshot:fk,browserClick:pk,browserFill:hk,closeBrowser:uk,INSTALL_MSG:eh}});var Xc=Q((HA,oh)=>{"use strict";var mk=require("util"),sh=require("stream"),Xt=oh.exports=function(){sh.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};mk.inherits(Xt,sh);Xt.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))};Xt.prototype.write=function(t,e){if(!this.writable)return this.emit("error",new Error("Stream not writable")),!1;let n;return Buffer.isBuffer(t)?n=t:n=Buffer.from(t,e||this._encoding),this._buffers.push(n),this._buffered+=n.length,this._process(),this._reads&&this._reads.length===0&&(this._paused=!0),this.writable&&!this._paused};Xt.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()))};Xt.prototype.destroySoon=Xt.prototype.end;Xt.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};Xt.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};Xt.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))};Xt.prototype._processRead=function(t){this._reads.shift();let e=0,n=0,o=Buffer.alloc(t.length);for(;e<t.length;){let s=this._buffers[n++],r=Math.min(s.length,t.length-e);s.copy(o,e,0,r),e+=r,r!==s.length&&(this._buffers[--n]=s.slice(r))}n>0&&this._buffers.splice(0,n),this._buffered-=t.length,t.func.call(this,o)};Xt.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 Jc=Q(Vc=>{"use strict";var Ln=[{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]}];Vc.getImagePasses=function(t,e){let n=[],o=t%8,s=e%8,r=(t-o)/8,i=(e-s)/8;for(let a=0;a<Ln.length;a++){let c=Ln[a],u=r*c.x.length,l=i*c.y.length;for(let d=0;d<c.x.length&&c.x[d]<o;d++)u++;for(let d=0;d<c.y.length&&c.y[d]<s;d++)l++;u>0&&l>0&&n.push({width:u,height:l,index:a})}return n};Vc.getInterlaceIterator=function(t){return function(e,n,o){let s=e%Ln[o].x.length,r=(e-s)/Ln[o].x.length*8+Ln[o].x[s],i=n%Ln[o].y.length,a=(n-i)/Ln[o].y.length*8+Ln[o].y[i];return r*4+a*t*4}}});var Zc=Q((GA,rh)=>{"use strict";rh.exports=function(e,n,o){let s=e+n-o,r=Math.abs(s-e),i=Math.abs(s-n),a=Math.abs(s-o);return r<=i&&r<=a?e:i<=a?n:o}});var Qc=Q((zA,ah)=>{"use strict";var gk=Jc(),yk=Zc();function ih(t,e,n){let o=t*e;return n!==8&&(o=Math.ceil(o/(8/n))),o}var Xs=ah.exports=function(t,e){let n=t.width,o=t.height,s=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=[],s){let a=gk.getImagePasses(n,o);for(let c=0;c<a.length;c++)this._images.push({byteWidth:ih(a[c].width,r,i),height:a[c].height,lineIndex:0})}else this._images.push({byteWidth:ih(n,r,i),height:o,lineIndex:0});i===8?this._xComparison=r:i===16?this._xComparison=r*2:this._xComparison=1};Xs.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};Xs.prototype._unFilterType1=function(t,e,n){let o=this._xComparison,s=o-1;for(let r=0;r<n;r++){let i=t[1+r],a=r>s?e[r-o]:0;e[r]=i+a}};Xs.prototype._unFilterType2=function(t,e,n){let o=this._lastLine;for(let s=0;s<n;s++){let r=t[1+s],i=o?o[s]:0;e[s]=r+i}};Xs.prototype._unFilterType3=function(t,e,n){let o=this._xComparison,s=o-1,r=this._lastLine;for(let i=0;i<n;i++){let a=t[1+i],c=r?r[i]:0,u=i>s?e[i-o]:0,l=Math.floor((u+c)/2);e[i]=a+l}};Xs.prototype._unFilterType4=function(t,e,n){let o=this._xComparison,s=o-1,r=this._lastLine;for(let i=0;i<n;i++){let a=t[1+i],c=r?r[i]:0,u=i>s?e[i-o]:0,l=i>s&&r?r[i-o]:0,d=yk(u,c,l);e[i]=a+d}};Xs.prototype._reverseFilterLine=function(t){let e=t[0],n,o=this._images[this._imageIndex],s=o.byteWidth;if(e===0)n=t.slice(1,s+1);else switch(n=Buffer.alloc(s),e){case 1:this._unFilterType1(t,n,s);break;case 2:this._unFilterType2(t,n,s);break;case 3:this._unFilterType3(t,n,s);break;case 4:this._unFilterType4(t,n,s);break;default:throw new Error("Unrecognised filter type - "+e)}this.write(n),o.lineIndex++,o.lineIndex>=o.height?(this._lastLine=null,this._imageIndex++,o=this._images[this._imageIndex]):this._lastLine=n,o?this.read(o.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}});var uh=Q((KA,lh)=>{"use strict";var wk=require("util"),ch=Xc(),bk=Qc(),$k=lh.exports=function(t){ch.call(this);let e=[],n=this;this._filter=new bk(t,{read:this.read.bind(this),write:function(o){e.push(o)},complete:function(){n.emit("complete",Buffer.concat(e))}}),this._filter.start()};wk.inherits($k,ch)});var Vs=Q((XA,dh)=>{"use strict";dh.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 nl=Q((VA,fh)=>{"use strict";var el=[];(function(){for(let t=0;t<256;t++){let e=t;for(let n=0;n<8;n++)e&1?e=3988292384^e>>>1:e=e>>>1;el[t]=e}})();var tl=fh.exports=function(){this._crc=-1};tl.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=el[(this._crc^t[e])&255]^this._crc>>>8;return!0};tl.prototype.crc32=function(){return this._crc^-1};tl.crc32=function(t){let e=-1;for(let n=0;n<t.length;n++)e=el[(e^t[n])&255]^e>>>8;return e^-1}});var sl=Q((JA,ph)=>{"use strict";var st=Vs(),_k=nl(),it=ph.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[st.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[st.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[st.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[st.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[st.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[st.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(){}};it.prototype.start=function(){this.read(st.PNG_SIGNATURE.length,this._parseSignature.bind(this))};it.prototype._parseSignature=function(t){let e=st.PNG_SIGNATURE;for(let n=0;n<e.length;n++)if(t[n]!==e[n]){this.error(new Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};it.prototype._parseChunkBegin=function(t){let e=t.readUInt32BE(0),n=t.readUInt32BE(4),o="";for(let r=4;r<8;r++)o+=String.fromCharCode(t[r]);let s=!!(t[4]&32);if(!this._hasIHDR&&n!==st.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new _k,this._crc.write(Buffer.from(o)),this._chunks[n])return this._chunks[n](e);if(!s){this.error(new Error("Unsupported critical chunk type "+o));return}this.read(e+4,this._skipChunk.bind(this))};it.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};it.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};it.prototype._parseChunkEnd=function(t){let e=t.readInt32BE(0),n=this._crc.crc32();if(this._options.checkCRC&&n!==e){this.error(new Error("Crc error - "+e+" - "+n));return}this._hasIEND||this.read(8,this._parseChunkBegin.bind(this))};it.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};it.prototype._parseIHDR=function(t){this._crc.write(t);let e=t.readUInt32BE(0),n=t.readUInt32BE(4),o=t[8],s=t[9],r=t[10],i=t[11],a=t[12];if(o!==8&&o!==4&&o!==2&&o!==1&&o!==16){this.error(new Error("Unsupported bit depth "+o));return}if(!(s in st.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=s;let c=st.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:n,depth:o,interlace:!!a,palette:!!(s&st.COLORTYPE_PALETTE),color:!!(s&st.COLORTYPE_COLOR),alpha:!!(s&st.COLORTYPE_ALPHA),bpp:c,colorType:s}),this._handleChunkEnd()};it.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};it.prototype._parsePLTE=function(t){this._crc.write(t);let e=Math.floor(t.length/3);for(let n=0;n<e;n++)this._palette.push([t[n*3],t[n*3+1],t[n*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};it.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};it.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===st.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===st.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===st.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};it.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};it.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/st.GAMMA_DIVISION),this._handleChunkEnd()};it.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};it.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===st.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw new Error("Expected palette not found");this.inflateData(e);let n=t-e.length;n>0?this._handleIDAT(n):this._handleChunkEnd()};it.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};it.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var ol=Q(mh=>{"use strict";var hh=Jc(),xk=[function(){},function(t,e,n,o){if(o===e.length)throw new Error("Ran out of data");let s=e[o];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=255},function(t,e,n,o){if(o+1>=e.length)throw new Error("Ran out of data");let s=e[o];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=e[o+1]},function(t,e,n,o){if(o+2>=e.length)throw new Error("Ran out of data");t[n]=e[o],t[n+1]=e[o+1],t[n+2]=e[o+2],t[n+3]=255},function(t,e,n,o){if(o+3>=e.length)throw new Error("Ran out of data");t[n]=e[o],t[n+1]=e[o+1],t[n+2]=e[o+2],t[n+3]=e[o+3]}],kk=[function(){},function(t,e,n,o){let s=e[0];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=o},function(t,e,n){let o=e[0];t[n]=o,t[n+1]=o,t[n+2]=o,t[n+3]=e[1]},function(t,e,n,o){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=o},function(t,e,n){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=e[3]}];function vk(t,e){let n=[],o=0;function s(){if(o===t.length)throw new Error("Ran out of data");let r=t[o];o++;let i,a,c,u,l,d,f,p;switch(e){default:throw new Error("unrecognised depth");case 16:f=t[o],o++,n.push((r<<8)+f);break;case 4:f=r&15,p=r>>4,n.push(p,f);break;case 2:l=r&3,d=r>>2&3,f=r>>4&3,p=r>>6&3,n.push(p,f,d,l);break;case 1:i=r&1,a=r>>1&1,c=r>>2&1,u=r>>3&1,l=r>>4&1,d=r>>5&1,f=r>>6&1,p=r>>7&1,n.push(p,f,d,l,u,c,a,i);break}}return{get:function(r){for(;n.length<r;)s();let i=n.slice(0,r);return n=n.slice(r),i},resetAfterLine:function(){n.length=0},end:function(){if(o!==t.length)throw new Error("extra data found")}}}function Sk(t,e,n,o,s,r){let i=t.width,a=t.height,c=t.index;for(let u=0;u<a;u++)for(let l=0;l<i;l++){let d=n(l,u,c);xk[o](e,s,d,r),r+=o}return r}function Ek(t,e,n,o,s,r){let i=t.width,a=t.height,c=t.index;for(let u=0;u<a;u++){for(let l=0;l<i;l++){let d=s.get(o),f=n(l,u,c);kk[o](e,d,f,r)}s.resetAfterLine()}}mh.dataToBitMap=function(t,e){let n=e.width,o=e.height,s=e.depth,r=e.bpp,i=e.interlace,a;s!==8&&(a=vk(t,s));let c;s<=8?c=Buffer.alloc(n*o*4):c=new Uint16Array(n*o*4);let u=Math.pow(2,s)-1,l=0,d,f;if(i)d=hh.getImagePasses(n,o),f=hh.getInterlaceIterator(n,o);else{let p=0;f=function(){let h=p;return p+=4,h},d=[{width:n,height:o}]}for(let p=0;p<d.length;p++)s===8?l=Sk(d[p],c,f,r,t,l):Ek(d[p],c,f,r,a,u);if(s===8){if(l!==t.length)throw new Error("extra data found")}else a.end();return c}});var rl=Q((QA,gh)=>{"use strict";function Tk(t,e,n,o,s){let r=0;for(let i=0;i<o;i++)for(let a=0;a<n;a++){let c=s[t[r]];if(!c)throw new Error("index "+t[r]+" not in palette");for(let u=0;u<4;u++)e[r+u]=c[u];r+=4}}function Rk(t,e,n,o,s){let r=0;for(let i=0;i<o;i++)for(let a=0;a<n;a++){let c=!1;if(s.length===1?s[0]===t[r]&&(c=!0):s[0]===t[r]&&s[1]===t[r+1]&&s[2]===t[r+2]&&(c=!0),c)for(let u=0;u<4;u++)e[r+u]=0;r+=4}}function Ck(t,e,n,o,s){let r=255,i=Math.pow(2,s)-1,a=0;for(let c=0;c<o;c++)for(let u=0;u<n;u++){for(let l=0;l<4;l++)e[a+l]=Math.floor(t[a+l]*r/i+.5);a+=4}}gh.exports=function(t,e,n=!1){let o=e.depth,s=e.width,r=e.height,i=e.colorType,a=e.transColor,c=e.palette,u=t;return i===3?Tk(t,u,s,r,c):(a&&Rk(t,u,s,r,a),o!==8&&!n&&(o===16&&(u=Buffer.alloc(s*r*4)),Ck(t,u,s,r,o))),u}});var bh=Q((eO,wh)=>{"use strict";var Ak=require("util"),il=require("zlib"),yh=Xc(),Ok=uh(),Nk=sl(),Mk=ol(),Pk=rl(),un=wh.exports=function(t){yh.call(this),this._parser=new Nk(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()};Ak.inherits(un,yh);un.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};un.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=il.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 n=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,o=Math.max(n,il.Z_MIN_CHUNK);this._inflate=il.createInflate({chunkSize:o});let s=n,r=this.emit.bind(this,"error");this._inflate.on("error",function(a){s&&r(a)}),this._filter.on("complete",this._complete.bind(this));let i=this._filter.write.bind(this._filter);this._inflate.on("data",function(a){s&&(a.length>s&&(a=a.slice(0,s)),s-=a.length,i(a))}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};un.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new Ok(this._bitmapInfo)};un.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};un.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};un.prototype._simpleTransparency=function(){this._metaData.alpha=!0};un.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};un.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};un.prototype._complete=function(t){if(this.errord)return;let e;try{let n=Mk.dataToBitMap(t,this._bitmapInfo);e=Pk(n,this._bitmapInfo,this._options.skipRescale),n=null}catch(n){this._handleError(n);return}this.emit("parsed",e)}});var _h=Q((tO,$h)=>{"use strict";var Dt=Vs();$h.exports=function(t,e,n,o){let s=[Dt.COLORTYPE_COLOR_ALPHA,Dt.COLORTYPE_ALPHA].indexOf(o.colorType)!==-1;if(o.colorType===o.inputColorType){let h=(function(){let g=new ArrayBuffer(2);return new DataView(g).setInt16(0,256,!0),new Int16Array(g)[0]!==256})();if(o.bitDepth===8||o.bitDepth===16&&h)return t}let r=o.bitDepth!==16?t:new Uint16Array(t.buffer),i=255,a=Dt.COLORTYPE_TO_BPP_MAP[o.inputColorType];a===4&&!o.inputHasAlpha&&(a=3);let c=Dt.COLORTYPE_TO_BPP_MAP[o.colorType];o.bitDepth===16&&(i=65535,c*=2);let u=Buffer.alloc(e*n*c),l=0,d=0,f=o.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,w,_=i;switch(o.inputColorType){case Dt.COLORTYPE_COLOR_ALPHA:_=r[l+3],h=r[l],g=r[l+1],w=r[l+2];break;case Dt.COLORTYPE_COLOR:h=r[l],g=r[l+1],w=r[l+2];break;case Dt.COLORTYPE_ALPHA:_=r[l+1],h=r[l],g=h,w=h;break;case Dt.COLORTYPE_GRAYSCALE:h=r[l],g=h,w=h;break;default:throw new Error("input color type:"+o.inputColorType+" is not supported at present")}return o.inputHasAlpha&&(s||(_/=i,h=Math.min(Math.max(Math.round((1-_)*f.red+_*h),0),i),g=Math.min(Math.max(Math.round((1-_)*f.green+_*g),0),i),w=Math.min(Math.max(Math.round((1-_)*f.blue+_*w),0),i))),{red:h,green:g,blue:w,alpha:_}}for(let h=0;h<n;h++)for(let g=0;g<e;g++){let w=p(r,l);switch(o.colorType){case Dt.COLORTYPE_COLOR_ALPHA:case Dt.COLORTYPE_COLOR:o.bitDepth===8?(u[d]=w.red,u[d+1]=w.green,u[d+2]=w.blue,s&&(u[d+3]=w.alpha)):(u.writeUInt16BE(w.red,d),u.writeUInt16BE(w.green,d+2),u.writeUInt16BE(w.blue,d+4),s&&u.writeUInt16BE(w.alpha,d+6));break;case Dt.COLORTYPE_ALPHA:case Dt.COLORTYPE_GRAYSCALE:{let _=(w.red+w.green+w.blue)/3;o.bitDepth===8?(u[d]=_,s&&(u[d+1]=w.alpha)):(u.writeUInt16BE(_,d),s&&u.writeUInt16BE(w.alpha,d+2));break}default:throw new Error("unrecognised color Type "+o.colorType)}l+=a,d+=c}return u}});var vh=Q((nO,kh)=>{"use strict";var xh=Zc();function Lk(t,e,n,o,s){for(let r=0;r<n;r++)o[s+r]=t[e+r]}function Ik(t,e,n){let o=0,s=e+n;for(let r=e;r<s;r++)o+=Math.abs(t[r]);return o}function jk(t,e,n,o,s,r){for(let i=0;i<n;i++){let a=i>=r?t[e+i-r]:0,c=t[e+i]-a;o[s+i]=c}}function Dk(t,e,n,o){let s=0;for(let r=0;r<n;r++){let i=r>=o?t[e+r-o]:0,a=t[e+r]-i;s+=Math.abs(a)}return s}function qk(t,e,n,o,s){for(let r=0;r<n;r++){let i=e>0?t[e+r-n]:0,a=t[e+r]-i;o[s+r]=a}}function Fk(t,e,n){let o=0,s=e+n;for(let r=e;r<s;r++){let i=e>0?t[r-n]:0,a=t[r]-i;o+=Math.abs(a)}return o}function Bk(t,e,n,o,s,r){for(let i=0;i<n;i++){let a=i>=r?t[e+i-r]:0,c=e>0?t[e+i-n]:0,u=t[e+i]-(a+c>>1);o[s+i]=u}}function Uk(t,e,n,o){let s=0;for(let r=0;r<n;r++){let i=r>=o?t[e+r-o]:0,a=e>0?t[e+r-n]:0,c=t[e+r]-(i+a>>1);s+=Math.abs(c)}return s}function Wk(t,e,n,o,s,r){for(let i=0;i<n;i++){let a=i>=r?t[e+i-r]:0,c=e>0?t[e+i-n]:0,u=e>0&&i>=r?t[e+i-(n+r)]:0,l=t[e+i]-xh(a,c,u);o[s+i]=l}}function Hk(t,e,n,o){let s=0;for(let r=0;r<n;r++){let i=r>=o?t[e+r-o]:0,a=e>0?t[e+r-n]:0,c=e>0&&r>=o?t[e+r-(n+o)]:0,u=t[e+r]-xh(i,a,c);s+=Math.abs(u)}return s}var Yk={0:Lk,1:jk,2:qk,3:Bk,4:Wk},Gk={0:Ik,1:Dk,2:Fk,3:Uk,4:Hk};kh.exports=function(t,e,n,o,s){let r;if(!("filterType"in o)||o.filterType===-1)r=[0,1,2,3,4];else if(typeof o.filterType=="number")r=[o.filterType];else throw new Error("unrecognised filter types");o.bitDepth===16&&(s*=2);let i=e*s,a=0,c=0,u=Buffer.alloc((i+1)*n),l=r[0];for(let d=0;d<n;d++){if(r.length>1){let f=1/0;for(let p=0;p<r.length;p++){let h=Gk[r[p]](t,c,i,s);h<f&&(l=r[p],f=h)}}u[a]=l,a++,Yk[l](t,c,i,u,a,s),a+=i,c+=i}return u}});var al=Q((sO,Sh)=>{"use strict";var pt=Vs(),zk=nl(),Kk=_h(),Xk=vh(),Vk=require("zlib"),In=Sh.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||Vk.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:pt.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:pt.COLORTYPE_COLOR_ALPHA,[pt.COLORTYPE_GRAYSCALE,pt.COLORTYPE_COLOR,pt.COLORTYPE_COLOR_ALPHA,pt.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([pt.COLORTYPE_GRAYSCALE,pt.COLORTYPE_COLOR,pt.COLORTYPE_COLOR_ALPHA,pt.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")};In.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};In.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};In.prototype.filterData=function(t,e,n){let o=Kk(t,e,n,this._options),s=pt.COLORTYPE_TO_BPP_MAP[this._options.colorType];return Xk(o,e,n,this._options,s)};In.prototype._packChunk=function(t,e){let n=e?e.length:0,o=Buffer.alloc(n+12);return o.writeUInt32BE(n,0),o.writeUInt32BE(t,4),e&&e.copy(o,8),o.writeInt32BE(zk.crc32(o.slice(4,o.length-4)),o.length-4),o};In.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*pt.GAMMA_DIVISION),0),this._packChunk(pt.TYPE_gAMA,e)};In.prototype.packIHDR=function(t,e){let n=Buffer.alloc(13);return n.writeUInt32BE(t,0),n.writeUInt32BE(e,4),n[8]=this._options.bitDepth,n[9]=this._options.colorType,n[10]=0,n[11]=0,n[12]=0,this._packChunk(pt.TYPE_IHDR,n)};In.prototype.packIDAT=function(t){return this._packChunk(pt.TYPE_IDAT,t)};In.prototype.packIEND=function(){return this._packChunk(pt.TYPE_IEND,null)}});var Ch=Q((oO,Rh)=>{"use strict";var Jk=require("util"),Eh=require("stream"),Zk=Vs(),Qk=al(),Th=Rh.exports=function(t){Eh.call(this);let e=t||{};this._packer=new Qk(e),this._deflate=this._packer.createDeflate(),this.readable=!0};Jk.inherits(Th,Eh);Th.prototype.pack=function(t,e,n,o){this.emit("data",Buffer.from(Zk.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,n)),o&&this.emit("data",this._packer.packGAMA(o));let s=this._packer.filterData(t,e,n);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(s)}});var Lh=Q((Ho,Ph)=>{"use strict";var Ah=require("assert").ok,Js=require("zlib"),ev=require("util"),Oh=require("buffer").kMaxLength;function ts(t){if(!(this instanceof ts))return new ts(t);t&&t.chunkSize<Js.Z_MIN_CHUNK&&(t.chunkSize=Js.Z_MIN_CHUNK),Js.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 tv(t){return new ts(t)}function Nh(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}ts.prototype._processChunk=function(t,e,n){if(typeof n=="function")return Js.Inflate._processChunk.call(this,t,e,n);let o=this,s=t&&t.length,r=this._chunkSize-this._offset,i=this._maxLength,a=0,c=[],u=0,l;this.on("error",function(h){l=h});function d(h,g){if(o._hadError)return;let w=r-g;if(Ah(w>=0,"have should not go down"),w>0){let _=o._buffer.slice(o._offset,o._offset+w);if(o._offset+=w,_.length>i&&(_=_.slice(0,i)),c.push(_),u+=_.length,i-=_.length,i===0)return!1}return(g===0||o._offset>=o._chunkSize)&&(r=o._chunkSize,o._offset=0,o._buffer=Buffer.allocUnsafe(o._chunkSize)),g===0?(a+=s-h,s=h,!0):!1}Ah(this._handle,"zlib binding closed");let f;do f=this._handle.writeSync(e,t,a,s,this._buffer,this._offset,r),f=f||this._writeState;while(!this._hadError&&d(f[0],f[1]));if(this._hadError)throw l;if(u>=Oh)throw Nh(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+Oh.toString(16)+" bytes");let p=Buffer.concat(c,u);return Nh(this),p};ev.inherits(ts,Js.Inflate);function nv(t,e){if(typeof e=="string"&&(e=Buffer.from(e)),!(e instanceof Buffer))throw new TypeError("Not a string or buffer");let n=t._finishFlushFlag;return n==null&&(n=Js.Z_FINISH),t._processChunk(e,n)}function Mh(t,e){return nv(new ts(e),t)}Ph.exports=Ho=Mh;Ho.Inflate=ts;Ho.createInflate=tv;Ho.inflateSync=Mh});var cl=Q((rO,jh)=>{"use strict";var Ih=jh.exports=function(t){this._buffer=t,this._reads=[]};Ih.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};Ih.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 qh=Q(Dh=>{"use strict";var sv=cl(),ov=Qc();Dh.process=function(t,e){let n=[],o=new sv(t);return new ov(e,{read:o.read.bind(o),write:function(r){n.push(r)},complete:function(){}}).start(),o.process(),Buffer.concat(n)}});var Wh=Q((aO,Uh)=>{"use strict";var Fh=!0,Bh=require("zlib"),rv=Lh();Bh.deflateSync||(Fh=!1);var iv=cl(),av=qh(),cv=sl(),lv=ol(),uv=rl();Uh.exports=function(t,e){if(!Fh)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n;function o(E){n=E}let s;function r(E){s=E}function i(E){s.transColor=E}function a(E){s.palette=E}function c(){s.alpha=!0}let u;function l(E){u=E}let d=[];function f(E){d.push(E)}let p=new iv(t);if(new cv(e,{read:p.read.bind(p),error:o,metadata:r,gamma:l,palette:a,transColor:i,inflateData:f,simpleTransparency:c}).start(),p.process(),n)throw n;let g=Buffer.concat(d);d.length=0;let w;if(s.interlace)w=Bh.inflateSync(g);else{let v=((s.width*s.bpp*s.depth+7>>3)+1)*s.height;w=rv(g,{chunkSize:v,maxLength:v})}if(g=null,!w||!w.length)throw new Error("bad png - invalid inflate data response");let _=av.process(w,s);g=null;let S=lv.dataToBitMap(_,s);_=null;let A=uv(S,s,e.skipRescale);return s.data=A,s.gamma=u||0,s}});var zh=Q((cO,Gh)=>{"use strict";var Hh=!0,Yh=require("zlib");Yh.deflateSync||(Hh=!1);var dv=Vs(),fv=al();Gh.exports=function(t,e){if(!Hh)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n=e||{},o=new fv(n),s=[];s.push(Buffer.from(dv.PNG_SIGNATURE)),s.push(o.packIHDR(t.width,t.height)),t.gamma&&s.push(o.packGAMA(t.gamma));let r=o.filterData(t.data,t.width,t.height),i=Yh.deflateSync(r,o.getDeflateOptions());if(r=null,!i||!i.length)throw new Error("bad png - invalid compressed data response");return s.push(o.packIDAT(i)),s.push(o.packIEND()),Buffer.concat(s)}});var Kh=Q(ll=>{"use strict";var pv=Wh(),hv=zh();ll.read=function(t,e){return pv(t,e||{})};ll.write=function(t,e){return hv(t,e)}});var Jh=Q(Vh=>{"use strict";var mv=require("util"),Xh=require("stream"),gv=bh(),yv=Ch(),wv=Kh(),gt=Vh.PNG=function(t){Xh.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 gv(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 yv(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"))};mv.inherits(gt,Xh);gt.sync=wv;gt.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)};gt.prototype.parse=function(t,e){if(e){let n,o;n=function(s){this.removeListener("error",o),this.data=s,e(null,this)}.bind(this),o=function(s){this.removeListener("parsed",n),e(s,null)}.bind(this),this.once("parsed",n),this.once("error",o)}return this.end(t),this};gt.prototype.write=function(t){return this._parser.write(t),!0};gt.prototype.end=function(t){this._parser.end(t)};gt.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};gt.prototype._gamma=function(t){this.gamma=t};gt.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};gt.bitblt=function(t,e,n,o,s,r,i,a){if(n|=0,o|=0,s|=0,r|=0,i|=0,a|=0,n>t.width||o>t.height||n+s>t.width||o+r>t.height)throw new Error("bitblt reading outside image");if(i>e.width||a>e.height||i+s>e.width||a+r>e.height)throw new Error("bitblt writing outside image");for(let c=0;c<r;c++)t.data.copy(e.data,(a+c)*e.width+i<<2,(o+c)*t.width+n<<2,(o+c)*t.width+n+s<<2)};gt.prototype.bitblt=function(t,e,n,o,s,r,i){return gt.bitblt(this,t,e,n,o,s,r,i),this};gt.adjustGamma=function(t){if(t.gamma){for(let e=0;e<t.height;e++)for(let n=0;n<t.width;n++){let o=t.width*e+n<<2;for(let s=0;s<3;s++){let r=t.data[o+s]/255;r=Math.pow(r,1/2.2/t.gamma),t.data[o+s]=Math.round(r*255)}}t.gamma=0}};gt.prototype.adjustGamma=function(){gt.adjustGamma(this)}});var nm={};Fw(nm,{default:()=>em});function em(t,e,n,o,s,r={}){let{threshold:i=.1,alpha:a=.1,aaColor:c=[255,255,0],diffColor:u=[255,0,0],includeAA:l,diffColorAlt:d,diffMask:f}=r;if(!ul(t)||!ul(e)||n&&!ul(n))throw new Error("Image data: Uint8Array, Uint8ClampedArray or Buffer expected.");if(t.length!==e.length||n&&n.length!==t.length)throw new Error("Image sizes do not match.");if(t.length!==o*s*4)throw new Error("Image data size does not match width/height.");let p=o*s,h=new Uint32Array(t.buffer,t.byteOffset,p),g=new Uint32Array(e.buffer,e.byteOffset,p),w=!0;for(let le=0;le<p;le++)if(h[le]!==g[le]){w=!1;break}if(w){if(n&&!f)for(let le=0;le<p;le++)Qh(t,4*le,a,n);return 0}let _=35215*i*i,[S,A,E]=c,[v,N,ne]=u,[oe,ue,fe]=d||u,ie=0;for(let le=0;le<s;le++)for(let T=0;T<o;T++){let F=le*o+T,ee=F*4,be=h[F]===g[F]?0:tm(t,e,ee,ee,!1);if(Math.abs(be)>_){let ve=Zh(t,T,le,o,s,h,g)||Zh(e,T,le,o,s,g,h);!l&&ve?n&&!f&&Mi(n,ee,S,A,E):(n&&(be<0?Mi(n,ee,oe,ue,fe):Mi(n,ee,v,N,ne)),ie++)}else n&&!f&&Qh(t,ee,a,n)}return ie}function ul(t){return ArrayBuffer.isView(t)&&t.BYTES_PER_ELEMENT===1}function Zh(t,e,n,o,s,r,i){let a=Math.max(e-1,0),c=Math.max(n-1,0),u=Math.min(e+1,o-1),l=Math.min(n+1,s-1),d=n*o+e,f=e===a||e===u||n===c||n===l?1:0,p=0,h=0,g=0,w=0,_=0,S=0;for(let A=a;A<=u;A++)for(let E=c;E<=l;E++){if(A===e&&E===n)continue;let v=tm(t,t,d*4,(E*o+A)*4,!0);if(v===0){if(f++,f>2)return!1}else v<p?(p=v,g=A,w=E):v>h&&(h=v,_=A,S=E)}return p===0||h===0?!1:Ni(r,g,w,o,s)&&Ni(i,g,w,o,s)||Ni(r,_,S,o,s)&&Ni(i,_,S,o,s)}function Ni(t,e,n,o,s){let r=Math.max(e-1,0),i=Math.max(n-1,0),a=Math.min(e+1,o-1),c=Math.min(n+1,s-1),u=t[n*o+e],l=e===r||e===a||n===i||n===c?1:0;for(let d=r;d<=a;d++)for(let f=i;f<=c;f++)if(!(d===e&&f===n)&&(l+=+(u===t[f*o+d]),l>2))return!0;return!1}function tm(t,e,n,o,s){let r=t[n],i=t[n+1],a=t[n+2],c=t[n+3],u=e[o],l=e[o+1],d=e[o+2],f=e[o+3],p=r-u,h=i-l,g=a-d,w=c-f;if(!p&&!h&&!g&&!w)return 0;if(c<255||f<255){let v=48+159*(n%2),N=48+159*((n/1.618033988749895|0)%2),ne=48+159*((n/2.618033988749895|0)%2);p=(r*c-u*f-v*w)/255,h=(i*c-l*f-N*w)/255,g=(a*c-d*f-ne*w)/255}let _=p*.29889531+h*.58662247+g*.11448223;if(s)return _;let S=p*.59597799-h*.2741761-g*.32180189,A=p*.21147017-h*.52261711+g*.31114694,E=.5053*_*_+.299*S*S+.1957*A*A;return _>0?-E:E}function Mi(t,e,n,o,s){t[e+0]=n,t[e+1]=o,t[e+2]=s,t[e+3]=255}function Qh(t,e,n,o){let s=255+(t[e]*.29889531+t[e+1]*.58662247+t[e+2]*.11448223-255)*n*t[e+3]/255;Mi(o,e,s,s,s)}var sm=qw(()=>{});var ns=Q((dO,cm)=>{var vn=require("fs"),bv=require("path"),$v=require("os"),_v="nex-visual-";function rm(t){return bv.join($v.tmpdir(),`${_v}${Date.now()}-${t}`)}var dl=null;function Pi(){return dl||(dl=Jh().PNG),dl}var fl=null;function xv(){if(!fl){let t=(sm(),Uw(nm));fl=t.default||t}return fl}function ml(t,e,{threshold:n=.1}={}){let o=Pi(),s=xv(),r=o.sync.read(vn.readFileSync(t)),i=o.sync.read(vn.readFileSync(e)),a=Math.max(r.width,i.width),c=Math.max(r.height,i.height),u=om(r,a,c),l=om(i,a,c),d=new o({width:a,height:c}),f=s(u,l,d.data,a,c,{threshold:n,includeAA:!1}),p=a*c,h=(f/p*100).toFixed(1),g=kv(d.data,a,c,3,3),w=rm("diff.png");return vn.writeFileSync(w,o.sync.write(d),{mode:384}),{diffPath:w,diffPercent:parseFloat(h),totalPixels:p,changedPixels:f,regionSummary:g,beforePath:t,afterPath:e,width:a,height:c}}function om(t,e,n){if(t.width===e&&t.height===n)return t.data;let o=Buffer.alloc(e*n*4,0);for(let s=0;s<t.height;s++){let r=s*t.width*4,i=s*e*4;t.data.copy(o,i,r,r+t.width*4)}return o}function kv(t,e,n,o,s){let r=[["top-left","top-center","top-right"],["middle-left","center","middle-right"],["bottom-left","bottom-center","bottom-right"]],i=Math.ceil(e/o),a=Math.ceil(n/s),c=[];for(let u=0;u<s;u++)for(let l=0;l<o;l++){let d=0,f=0,p=l*i,h=u*a,g=Math.min(p+i,e),w=Math.min(h+a,n);for(let _=h;_<w;_++)for(let S=p;S<g;S++){f++;let A=(_*e+S)*4;(t[A]>0||t[A+1]>0)&&d++}if(d>0){let _=(d/f*100).toFixed(1),S=r[u]&&r[u][l]?r[u][l]:`row${u}-col${l}`;c.push({name:S,changedPercent:parseFloat(_),changed:d,total:f})}}return c.sort((u,l)=>l.changedPercent-u.changedPercent),c}var im=[{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 vv(t,{viewports:e=im,height:n=800,fullPage:o=!1,timeout:s=3e4}={}){let{browserScreenshot:r}=kn(),i=[];for(let a of e){let c=await r(t,{width:a.width,height:n,fullPage:o,timeout:s});i.push({label:a.label,width:a.width,path:c.path,base64:c.base64,media_type:c.media_type})}return i}function am(t,e=[]){let n=Pi(),o=n.sync.read(vn.readFileSync(t));for(let i of e){let a=Sv(i.color||"#FF0000");i.type==="box"?(Ev(o,i.x||0,i.y||0,i.width||50,i.height||50,a,i.thickness||3),i.label&&hl(o,i.x||0,(i.y||0)-14,i.label,a)):i.type==="arrow"?(Tv(o,i.x||0,i.y||0,i.toX||i.x+50,i.toY||i.y,a,i.thickness||3),i.label&&hl(o,i.x||0,(i.y||0)-14,i.label,a)):i.type==="circle"&&(Rv(o,i.x||0,i.y||0,i.radius||20,a,i.thickness||3),i.label&&hl(o,(i.x||0)-(i.radius||20),(i.y||0)-(i.radius||20)-14,i.label,a))}let s=rm("annotated.png");vn.writeFileSync(s,n.sync.write(o),{mode:384});let r=vn.readFileSync(s).toString("base64");return{path:s,base64:r,media_type:"image/png"}}function Sv(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 dn(t,e,n,o){if(e<0||n<0||e>=t.width||n>=t.height)return;let s=(n*t.width+e)*4;t.data[s]=o.r,t.data[s+1]=o.g,t.data[s+2]=o.b,t.data[s+3]=o.a}function Ev(t,e,n,o,s,r,i=3){for(let a=0;a<i;a++){for(let c=0;c<o;c++)dn(t,e+c,n+a,r),dn(t,e+c,n+s-1-a,r);for(let c=0;c<s;c++)dn(t,e+a,n+c,r),dn(t,e+o-1-a,n+c,r)}}function pl(t,e,n,o,s,r,i=3){let a=Math.abs(o-e),c=Math.abs(s-n),u=e<o?1:-1,l=n<s?1:-1,d=a-c,f=e,p=n;for(;;){let h=Math.floor(i/2);for(let w=-h;w<=h;w++)for(let _=-h;_<=h;_++)dn(t,f+w,p+_,r);if(f===o&&p===s)break;let g=2*d;g>-c&&(d-=c,f+=u),g<a&&(d+=a,p+=l)}}function Tv(t,e,n,o,s,r,i=3){pl(t,e,n,o,s,r,i);let a=Math.atan2(s-n,o-e),c=15,u=a+Math.PI*.8,l=a-Math.PI*.8;pl(t,o,s,Math.round(o+c*Math.cos(u)),Math.round(s+c*Math.sin(u)),r,i),pl(t,o,s,Math.round(o+c*Math.cos(l)),Math.round(s+c*Math.sin(l)),r,i)}function Rv(t,e,n,o,s,r=3){for(let i=0;i<r;i++){let a=o-i;for(let c=0;c<360;c+=.5){let u=c*Math.PI/180,l=Math.round(e+a*Math.cos(u)),d=Math.round(n+a*Math.sin(u));dn(t,l,d,s)}}}function hl(t,e,n,o,s){let i=o.length*6+4,a=12;for(let c=0;c<a;c++)for(let u=0;u<i;u++)dn(t,e+u,n+c,{r:0,g:0,b:0,a:200});for(let c=0;c<i;c++)dn(t,e+c,n+a-1,s),dn(t,e+c,n+a-2,s);for(let c=0;c<o.length;c++){let u=e+2+c*6;for(let l=2;l<9;l++)for(let d=0;d<4;d++)dn(t,u+d,n+l,s)}}async function*Cv(t,e,{maxIterations:n=20,hmrDelay:o=1500,width:s=1280,height:r=800,timeout:i=3e4}={}){let{browserScreenshot:a}=kn(),c=Av("chokidar"),u=await a(t,{width:s,height:r,timeout:i});if(yield{iteration:0,type:"baseline",path:u.path,base64:u.base64,media_type:u.media_type},!c){yield{iteration:-1,type:"error",message:"chokidar not installed \u2014 watch mode requires it. Install with: npm install chokidar"};return}let l=0,d=!1,f=c.watch(e,{ignoreInitial:!0,ignored:/(node_modules|\.git|dist)/});f.on("change",()=>{d=!0});try{for(;l<n;){await Nv(()=>d,3e5),d=!1,l++,await Ov(o);let p=await a(t,{width:s,height:r,timeout:i}),h=null;try{h=ml(u.path,p.path)}catch{}u=p,yield{iteration:l,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 Av(t){try{return require(t)}catch{return null}}function Ov(t){return new Promise(e=>setTimeout(e,t))}function Nv(t,e=6e4){return new Promise((n,o)=>{let s=setInterval(()=>{t()&&(clearInterval(s),clearTimeout(r),n())},200),r=setTimeout(()=>{clearInterval(s),o(new Error("Watch timeout \u2014 no file changes detected"))},e)})}function Mv(t,{sampleRate:e=4}={}){let o=Pi().sync.read(vn.readFileSync(t)),s=new Map;for(let u=0;u<o.height;u+=e)for(let l=0;l<o.width;l+=e){let d=(u*o.width+l)*4,f=o.data[d],p=o.data[d+1],h=o.data[d+2];if(o.data[d+3]<128)continue;let w=Math.round(f/8)*8,_=Math.round(p/8)*8,S=Math.round(h/8)*8,A=`${w},${_},${S}`;s.set(A,(s.get(A)||0)+1)}let r=[...s.entries()].sort((u,l)=>l[1]-u[1]).slice(0,20),i=r.reduce((u,l)=>u+l[1],0),a=r.map(([u,l])=>{let[d,f,p]=u.split(",").map(Number);return{hex:Pv(d,f,p),rgb:`rgb(${d}, ${f}, ${p})`,frequency:parseFloat((l/i*100).toFixed(1)),category:Lv(d,f,p)}}),c=Iv(o);return{colors:a,spacing:c,dimensions:{width:o.width,height:o.height},imagePath:t}}function Pv(t,e,n){return"#"+[t,e,n].map(o=>Math.min(255,o).toString(16).padStart(2,"0")).join("")}function Lv(t,e,n){let o=(t*299+e*587+n*114)/1e3;return o>240?"white/background":o<30?"black/text":o<80?"dark":t>200&&e<100&&n<100?"red/danger":t<100&&e>150&&n<100?"green/success":t<100&&e<100&&n>200?"blue/primary":t>200&&e>200&&n<100?"yellow/warning":t>200&&e>100&&n<50?"orange/accent":o>200?"light/subtle":"midtone"}function Iv(t){let e=[],n=!1,o=0,s=jv(t);for(let i=0;i<t.height;i++){let a=!0;for(let c=0;c<t.width;c+=4){let u=(i*t.width+c)*4;if(Math.abs(t.data[u]-s.r)>20||Math.abs(t.data[u+1]-s.g)>20||Math.abs(t.data[u+2]-s.b)>20){a=!1;break}}if(a&&n)n=!1,o=i;else if(!a&&!n&&(n=!0,o>0)){let c=i-o;c>=4&&c<=200&&e.push(c)}}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 jv(t){let e=[[0,0],[t.width-1,0],[0,t.height-1],[t.width-1,t.height-1]],n=0,o=0,s=0;for(let[r,i]of e){let a=(i*t.width+r)*4;n+=t.data[a],o+=t.data[a+1],s+=t.data[a+2]}return{r:Math.round(n/4),g:Math.round(o/4),b:Math.round(s/4)}}async function Dv(t,e,{width:n,height:o=800,fullPage:s=!1,threshold:r=.1,timeout:i=3e4}={}){let{browserScreenshot:a}=kn(),u=Pi().sync.read(vn.readFileSync(e)),l=n||u.width,d=o||u.height,f=await a(t,{width:l,height:d,fullPage:s,timeout:i}),p=ml(e,f.path,{threshold:r}),h=am(f.path,p.regionSummary.filter(g=>g.changedPercent>1).map((g,w)=>{let A=Math.ceil(p.width/3),E=Math.ceil(p.height/3),v=[["top-left","top-center","top-right"],["middle-left","center","middle-right"],["bottom-left","bottom-center","bottom-right"]],N=0,ne=0;for(let oe=0;oe<3;oe++)for(let ue=0;ue<3;ue++)v[oe][ue]===g.name&&(N=ue,ne=oe);return{type:"box",x:N*A+2,y:ne*E+2,width:A-4,height:E-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:vn.readFileSync(p.diffPath).toString("base64"),annotatedBase64:h.base64}}cm.exports={pixelDiff:ml,responsiveSweep:vv,annotateImage:am,visualWatch:Cv,extractDesignTokens:Mv,designCompare:Dv,DEFAULT_VIEWPORTS:im}});var gl=Q((fO,lm)=>{var{C:qe}=rt(),Go="",yt=[],Yo=0,ss=null;function qv(t){ss=t}function Fv(t,e){Go=t,yt=[],Yo=0;for(let o of e){Yo++;let s=`t${Yo}`;yt.push({id:s,description:o.description||o.title||o.name||o.task||`Task ${Yo}`,status:"pending",dependsOn:o.depends_on||[],result:null})}let n=yt.map(o=>({...o}));return ss&&ss("create",{name:t,tasks:n}),n}function Bv(t,e,n){let o=yt.find(s=>s.id===t);return o?(o.status=e,n!==void 0&&(o.result=n),ss&&ss("update",{id:t,status:e,result:n}),{...o}):null}function Uv(){return{name:Go,tasks:yt.map(t=>({...t}))}}function Wv(){Go="",yt=[],Yo=0,ss&&ss("clear",{})}function Hv(){return yt.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let n=yt.find(o=>o.id===e);return n&&n.status==="done"}))}function Yv(){if(yt.length===0)return`${qe.dim}No active tasks${qe.reset}`;let t=[];Go&&(t.push(` ${qe.bold}${qe.cyan}Tasks: ${Go}${qe.reset}`),t.push(` ${qe.dim}${"\u2500".repeat(40)}${qe.reset}`));for(let s of yt){let r,i;switch(s.status){case"done":r="\u2713",i=qe.green;break;case"in_progress":r="\u2192",i=qe.cyan;break;case"failed":r="\u2717",i=qe.red;break;default:r="\xB7",i=qe.dim}let a=s.dependsOn.length>0?` ${qe.dim}(after: ${s.dependsOn.join(", ")})${qe.reset}`:"",c=`[${s.status}]`,u=s.description.length>50?s.description.substring(0,47)+"...":s.description;if(t.push(` ${i}${r}${qe.reset} ${qe.bold}${s.id}${qe.reset} ${u.padEnd(40)} ${i}${c}${qe.reset}${a}`),s.result&&s.status==="done"){let l=s.result.length>60?s.result.substring(0,57)+"...":s.result;t.push(` ${qe.dim}\u2192 ${l}${qe.reset}`)}}let e=yt.filter(s=>s.status==="done").length,n=yt.filter(s=>s.status==="failed").length,o=yt.length;return t.push(` ${qe.dim}${"\u2500".repeat(40)}${qe.reset}`),t.push(` ${qe.dim}${e}/${o} done${n>0?`, ${n} failed`:""}${qe.reset}`),t.join(`
152
+ `)}function Gv(){return yt.length>0&&yt.some(t=>t.status==="pending"||t.status==="in_progress")}lm.exports={createTasks:Fv,updateTask:Bv,getTaskList:Uv,clearTasks:Wv,getReadyTasks:Hv,renderTaskList:Yv,setOnChange:qv,hasActiveTasks:Gv}});var Li=Q((pO,dm)=>{var zo={"devstral-2":{staleWarn:3e4,staleAbort:9e4,investigationCap:18,postEditCap:10,briefing:`You are devstral-2, a strong coding model optimized for agentic tasks.
153
153
  Use tools confidently and without hesitation \u2014 tool use is the expected workflow.
154
154
  You excel at sysadmin, frontend, and multi-step coding tasks.
155
155
  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.
@@ -162,7 +162,7 @@ Focus on correctness over speed.`},"ministral-3":{staleWarn:2e4,staleAbort:6e4,i
162
162
  Prioritize decisive, targeted edits. Read only what you need, then fix.
163
163
  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.
164
164
  Trust your reasoning. Use tools thoroughly when the task demands it.
165
- You handle complex multi-step tasks well \u2014 don't cut corners prematurely.`}},lm={staleWarn:6e4,staleAbort:12e4,investigationCap:18,postEditCap:10};function zv(t){let e=(t||"").toLowerCase(),n=null,o=0;for(let r of Object.keys(zo))e.startsWith(r)&&r.length>o&&(n=r,o=r.length);let s=n?{...zo[n]}:{...lm};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&&(s[i]=a)}return s}function Kv(t){let e=(t||"").toLowerCase(),n=null,o=0;for(let s of Object.keys(zo))e.startsWith(s)&&s.length>o&&(n=s,o=s.length);return n&&zo[n].briefing||""}um.exports={getModelProfile:zv,getModelBriefing:Kv,PROFILES:zo,DEFAULTS:lm}});var wl=Q((pO,gm)=>{var{callChat:Xv}=ct(),{estimateTokens:yl}=fn(),dm=process.env.NEX_COMPACTION!=="false",fm=6,pm=2e3,hm=3,Vv=`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.
165
+ You handle complex multi-step tasks well \u2014 don't cut corners prematurely.`}},um={staleWarn:6e4,staleAbort:12e4,investigationCap:18,postEditCap:10};function zv(t){let e=(t||"").toLowerCase(),n=null,o=0;for(let r of Object.keys(zo))e.startsWith(r)&&r.length>o&&(n=r,o=r.length);let s=n?{...zo[n]}:{...um};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&&(s[i]=a)}return s}function Kv(t){let e=(t||"").toLowerCase(),n=null,o=0;for(let s of Object.keys(zo))e.startsWith(s)&&s.length>o&&(n=s,o=s.length);return n&&zo[n].briefing||""}dm.exports={getModelProfile:zv,getModelBriefing:Kv,PROFILES:zo,DEFAULTS:um}});var wl=Q((hO,ym)=>{var{callChat:Xv}=ct(),{estimateTokens:yl}=fn(),fm=process.env.NEX_COMPACTION!=="false",pm=6,hm=2e3,mm=3,Vv=`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.
166
166
  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.
167
167
 
168
168
  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:
@@ -194,30 +194,30 @@ Format your output as:
194
194
 
195
195
  <summary>
196
196
  [Sections 1-9 above]
197
- </summary>`,os=0;async function Jv(t){if(!dm||t.length<fm||os>=hm)return null;let e=[{role:"system",content:Vv},{role:"user",content:mm(t)}];try{let o=((await Xv(e,[],{temperature:0,maxTokens:pm})).content||"").trim();if(!o)return os++,null;let s=o.match(/<summary>([\s\S]*?)<\/summary>/);if(s?o=s[1].trim():o=o.replace(/<analysis>[\s\S]*?<\/analysis>/g,"").trim(),!o)return os++,null;let r=t.reduce((a,c)=>a+yl(c.content||"")+(c.tool_calls?yl(JSON.stringify(c.tool_calls)):0),0),i=yl(o);return i>=r*.8?(os++,null):(os=0,{message:{role:"system",content:`[Conversation Summary \u2014 ${t.length} messages compacted]
198
- ${o}`,_compacted:!0,_originalCount:t.length},tokensRemoved:r-i})}catch{return os++,null}}function Zv(){os=0}function mm(t){return t.map(e=>{let n=e.role==="tool"?"tool_result":e.role,o=(e.content||"").substring(0,500);if(e.tool_calls){let s=e.tool_calls.map(r=>r.function?.name).join(", ");return`[${n}] ${o}
197
+ </summary>`,os=0;async function Jv(t){if(!fm||t.length<pm||os>=mm)return null;let e=[{role:"system",content:Vv},{role:"user",content:gm(t)}];try{let o=((await Xv(e,[],{temperature:0,maxTokens:hm})).content||"").trim();if(!o)return os++,null;let s=o.match(/<summary>([\s\S]*?)<\/summary>/);if(s?o=s[1].trim():o=o.replace(/<analysis>[\s\S]*?<\/analysis>/g,"").trim(),!o)return os++,null;let r=t.reduce((a,c)=>a+yl(c.content||"")+(c.tool_calls?yl(JSON.stringify(c.tool_calls)):0),0),i=yl(o);return i>=r*.8?(os++,null):(os=0,{message:{role:"system",content:`[Conversation Summary \u2014 ${t.length} messages compacted]
198
+ ${o}`,_compacted:!0,_originalCount:t.length},tokensRemoved:r-i})}catch{return os++,null}}function Zv(){os=0}function gm(t){return t.map(e=>{let n=e.role==="tool"?"tool_result":e.role,o=(e.content||"").substring(0,500);if(e.tool_calls){let s=e.tool_calls.map(r=>r.function?.name).join(", ");return`[${n}] ${o}
199
199
  tools: ${s}`}return`[${n}] ${o}`}).join(`
200
200
 
201
- `)}gm.exports={compactMessages:Jv,formatMessagesForSummary:mm,resetCompactionFailures:Zv,COMPACTION_ENABLED:dm,COMPACTION_MIN_MESSAGES:fm,COMPACTION_SUMMARY_BUDGET:pm,MAX_CONSECUTIVE_FAILURES:hm}});var fn=Q((hO,Em)=>{var Qv=require("path");function wm(){return ct().getActiveModel()}var eS={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},tS={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},rs=new Map,ym=1e3,bl=new WeakMap,is=null;function nS(){if(is!==null)return is;try{let t=wm(),e=t?.provider||"ollama",n=(t?.id||"").toLowerCase();for(let[o,s]of Object.entries(tS))if(n.startsWith(o))return is=s,is;return is=eS[e]||4,is}catch{return 4}}function sS(){is=null}function as(t){if(!t)return 0;typeof t!="string"&&(t=JSON.stringify(t));let e=t.length<=120?t:`${t.length}:${t.substring(0,60)}:${t.substring(t.length>>1,(t.length>>1)+30)}:${t.substring(t.length-30)}`,n=rs.get(e);if(n!==void 0)return rs.delete(e),rs.set(e,n),n;let o=Math.ceil(t.length/nS());if(rs.size>=ym){let s=ym>>1,r=rs.keys();for(let i=0;i<s;i++)rs.delete(r.next().value)}return rs.set(e,o),o}function oS(t){if(bl.has(t))return bl.get(t);let e=JSON.stringify(t);return bl.set(t,e),e}function cs(t){let n=4;if(t.content&&(n+=as(t.content)),t.tool_calls)for(let o of t.tool_calls){n+=4,n+=as(o.function?.name||"");let s=o.function?.arguments;typeof s=="string"?n+=as(s):s&&(n+=as(JSON.stringify(s)))}return n}function Vt(t){let e=0;for(let n of t)e+=cs(n);return e}function rS(t,e){if(t&&t.length===e.length){let r=!1;for(let i=0;i<e.length;i++)if(t[i]!==e[i]){r=!0;break}if(!r)return 0}let n=t?t.length:0,o=e.length,s=0;for(let r=n;r<o;r++)s+=cs(e[r]);return s}var $l=new WeakMap;function Ii(t){if(!t||t.length===0)return 0;if($l.has(t))return $l.get(t);let e=as(JSON.stringify(t));return $l.set(t,e),e}function ji(){return wm()?.contextWindow||32768}var wt={msgCount:-1,lastMsgRef:null,toolCount:-1,result:null,messagesRef:null,messageTokens:0,systemTokens:0,conversationTokens:0,toolResultTokens:0};function iS(t,e){let n=t.length>0?t[t.length-1]:null,o=e?e.length:0;if(wt.result&&t.length===wt.msgCount&&n===wt.lastMsgRef&&o===wt.toolCount)return wt.result;let s,r,i,a;if(wt.messagesRef===t&&t.length>wt.msgCount&&wt.msgCount>=0){s=wt.messageTokens,r=wt.systemTokens,i=wt.conversationTokens,a=wt.toolResultTokens;for(let p=wt.msgCount;p<t.length;p++){let h=cs(t[p]);s+=h,t[p].role==="system"?r+=h:t[p].role==="tool"?a+=h:i+=h}}else{s=0,r=0,i=0,a=0;for(let p of t){let h=cs(p);s+=h,p.role==="system"?r+=h:p.role==="tool"?a+=h:i+=h}}let c=Ii(e),u=s+c,l=ji(),d=l>0?u/l*100:0,f={used:u,limit:l,percentage:Math.round(d*10)/10,breakdown:{system:r,conversation:i,toolResults:a,toolDefinitions:c},messageCount:t.length};return wt={msgCount:t.length,lastMsgRef:n,toolCount:o,result:f,messagesRef:t,messageTokens:s,systemTokens:r,conversationTokens:i,toolResultTokens:a},f}var Ko=parseFloat(process.env.NEX_COMPRESSION_THRESHOLD)||.75,bm=parseFloat(process.env.NEX_SAFETY_MARGIN)||.1,$m=parseInt(process.env.NEX_KEEP_RECENT,10)||10,_m={essential:.6,standard:.65,full:Math.min(Ko,.75)};function xm(){if(process.env.NEX_COMPRESSION_THRESHOLD)return Ko;try{let{getActiveTier:t}=Uo(),e=t();return _m[e]??Ko}catch{return Ko}}var aS=200,cS=1e3;function km(t,e){if(!t||t.length<=e)return t;let o=/^(ERROR|EXIT|BLOCKED|CANCELLED)/i.test(t)?e*3:e;if(t.length<=o)return t;let s=t.split(`
201
+ `)}ym.exports={compactMessages:Jv,formatMessagesForSummary:gm,resetCompactionFailures:Zv,COMPACTION_ENABLED:fm,COMPACTION_MIN_MESSAGES:pm,COMPACTION_SUMMARY_BUDGET:hm,MAX_CONSECUTIVE_FAILURES:mm}});var fn=Q((mO,Tm)=>{var Qv=require("path");function bm(){return ct().getActiveModel()}var eS={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},tS={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},rs=new Map,wm=1e3,bl=new WeakMap,is=null;function nS(){if(is!==null)return is;try{let t=bm(),e=t?.provider||"ollama",n=(t?.id||"").toLowerCase();for(let[o,s]of Object.entries(tS))if(n.startsWith(o))return is=s,is;return is=eS[e]||4,is}catch{return 4}}function sS(){is=null}function as(t){if(!t)return 0;typeof t!="string"&&(t=JSON.stringify(t));let e=t.length<=120?t:`${t.length}:${t.substring(0,60)}:${t.substring(t.length>>1,(t.length>>1)+30)}:${t.substring(t.length-30)}`,n=rs.get(e);if(n!==void 0)return rs.delete(e),rs.set(e,n),n;let o=Math.ceil(t.length/nS());if(rs.size>=wm){let s=wm>>1,r=rs.keys();for(let i=0;i<s;i++)rs.delete(r.next().value)}return rs.set(e,o),o}function oS(t){if(bl.has(t))return bl.get(t);let e=JSON.stringify(t);return bl.set(t,e),e}function cs(t){let n=4;if(t.content&&(n+=as(t.content)),t.tool_calls)for(let o of t.tool_calls){n+=4,n+=as(o.function?.name||"");let s=o.function?.arguments;typeof s=="string"?n+=as(s):s&&(n+=as(JSON.stringify(s)))}return n}function Vt(t){let e=0;for(let n of t)e+=cs(n);return e}function rS(t,e){if(t&&t.length===e.length){let r=!1;for(let i=0;i<e.length;i++)if(t[i]!==e[i]){r=!0;break}if(!r)return 0}let n=t?t.length:0,o=e.length,s=0;for(let r=n;r<o;r++)s+=cs(e[r]);return s}var $l=new WeakMap;function Ii(t){if(!t||t.length===0)return 0;if($l.has(t))return $l.get(t);let e=as(JSON.stringify(t));return $l.set(t,e),e}function ji(){return bm()?.contextWindow||32768}var wt={msgCount:-1,lastMsgRef:null,toolCount:-1,result:null,messagesRef:null,messageTokens:0,systemTokens:0,conversationTokens:0,toolResultTokens:0};function iS(t,e){let n=t.length>0?t[t.length-1]:null,o=e?e.length:0;if(wt.result&&t.length===wt.msgCount&&n===wt.lastMsgRef&&o===wt.toolCount)return wt.result;let s,r,i,a;if(wt.messagesRef===t&&t.length>wt.msgCount&&wt.msgCount>=0){s=wt.messageTokens,r=wt.systemTokens,i=wt.conversationTokens,a=wt.toolResultTokens;for(let p=wt.msgCount;p<t.length;p++){let h=cs(t[p]);s+=h,t[p].role==="system"?r+=h:t[p].role==="tool"?a+=h:i+=h}}else{s=0,r=0,i=0,a=0;for(let p of t){let h=cs(p);s+=h,p.role==="system"?r+=h:p.role==="tool"?a+=h:i+=h}}let c=Ii(e),u=s+c,l=ji(),d=l>0?u/l*100:0,f={used:u,limit:l,percentage:Math.round(d*10)/10,breakdown:{system:r,conversation:i,toolResults:a,toolDefinitions:c},messageCount:t.length};return wt={msgCount:t.length,lastMsgRef:n,toolCount:o,result:f,messagesRef:t,messageTokens:s,systemTokens:r,conversationTokens:i,toolResultTokens:a},f}var Ko=parseFloat(process.env.NEX_COMPRESSION_THRESHOLD)||.75,$m=parseFloat(process.env.NEX_SAFETY_MARGIN)||.1,_m=parseInt(process.env.NEX_KEEP_RECENT,10)||10,xm={essential:.6,standard:.65,full:Math.min(Ko,.75)};function km(){if(process.env.NEX_COMPRESSION_THRESHOLD)return Ko;try{let{getActiveTier:t}=Uo(),e=t();return xm[e]??Ko}catch{return Ko}}var aS=200,cS=1e3;function vm(t,e){if(!t||t.length<=e)return t;let o=/^(ERROR|EXIT|BLOCKED|CANCELLED)/i.test(t)?e*3:e;if(t.length<=o)return t;let s=t.split(`
202
202
  `);if(s.length<=10){let h=Math.floor(o*.6),g=Math.floor(o*.4),w=t.substring(0,h),_=t.substring(t.length-g);return w+`
203
203
  ...(${t.length} chars total)...
204
204
  `+_}let r=Math.floor(s.length*.4),i=Math.floor(s.length*.4),a=[],c=0,u=Math.floor(o*.4);for(let h=0;h<r&&c<u;h++)if(c+s[h].length+1>u&&s[h].trim().startsWith("```")){a.push(s[h]),c+=s[h].length+1;let g=h+1;for(;g<s.length&&c<u*1.5&&!s[g].trim().startsWith("```");)a.push(s[g]),c+=s[g].length+1,g++;g<s.length&&s[g].trim().startsWith("```")&&(a.push(s[g]),c+=s[g].length+1),h=g}else a.push(s[h]),c+=s[h].length+1;let l=[],d=0,f=Math.floor(o*.4);for(let h=s.length-1;h>=s.length-i&&d<f;h--)if(d+s[h].length+1>f&&s[h].trim().startsWith("```")){l.push(s[h]),d+=s[h].length+1;let g=h-1;for(;g>=0&&d<f*1.5&&!s[g].trim().startsWith("```");)l.push(s[g]),d+=s[g].length+1,g--;g>=0&&s[g].trim().startsWith("```")&&(l.push(s[g]),d+=s[g].length+1),h=g}else l.push(s[h]),d+=s[h].length+1;l.reverse();let p=s.length-a.length-l.length;return a.join(`
205
205
  `)+`
206
206
  ...(${p} lines omitted, ${s.length} total)...
207
207
  `+l.join(`
208
- `)}function Qs(t,e="light"){let n=e==="aggressive"?100:e==="medium"?200:cS,o=e==="aggressive"?50:e==="medium"?100:aS;if(t.role==="tool"){let s=typeof t.content=="string"?t.content:JSON.stringify(t.content);return s.length>o?{...t,content:km(s,o)}:t}if(t.role==="assistant"){let s={...t};return s.content&&s.content.length>n&&(s.content=s.content.substring(0,n)+`
209
- ...(truncated)`),s.tool_calls&&e==="aggressive"&&(s.tool_calls=s.tool_calls.map(r=>({...r,function:{name:r.function.name,arguments:typeof r.function.arguments=="string"?r.function.arguments.substring(0,50):r.function.arguments}}))),s}return t}function vm(t,e,n,o){let s=0;if(t.role==="system")return 100;if(t.role==="user")s+=35;else if(t.role==="tool"){let i=typeof t.content=="string"?t.content:JSON.stringify(t.content||"");/^(ERROR|BLOCKED|CANCELLED)/i.test(i)?s+=30:s+=15}else t.role==="assistant"&&(s+=t.tool_calls?20:10);let r=n>1?e/(n-1):1;if(s+=Math.round(r*30),o&&o.size>0){let i=typeof t.content=="string"?t.content:JSON.stringify(t.content||""),a=0;for(let c of o)(i.includes(c)||i.includes(Qv.basename(c)))&&a++;s+=Math.min(30,a*10)}return Math.min(100,s)}function Sm(t,e=10){let n=new Set,o=t.slice(-e),s=/(?:\/[\w.-]+)+\.\w+/g;for(let r of o){let a=(typeof r.content=="string"?r.content:JSON.stringify(r.content||"")).match(s);a&&a.forEach(c=>n.add(c))}return n}function lS(t,{filesModified:e=new Set,currentPhase:n=null}={}){let o=[];if(e.size>0){let r=[...e].map(i=>i.split("/").slice(-2).join("/")).join(", ");o.push(`Files already modified: ${r} \u2014 do NOT rewrite these, use edit_file for additions only.`)}n&&o.push(`Current phase: ${n}`);let s=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 s.length>0&&o.push(`Recent progress:
208
+ `)}function Qs(t,e="light"){let n=e==="aggressive"?100:e==="medium"?200:cS,o=e==="aggressive"?50:e==="medium"?100:aS;if(t.role==="tool"){let s=typeof t.content=="string"?t.content:JSON.stringify(t.content);return s.length>o?{...t,content:vm(s,o)}:t}if(t.role==="assistant"){let s={...t};return s.content&&s.content.length>n&&(s.content=s.content.substring(0,n)+`
209
+ ...(truncated)`),s.tool_calls&&e==="aggressive"&&(s.tool_calls=s.tool_calls.map(r=>({...r,function:{name:r.function.name,arguments:typeof r.function.arguments=="string"?r.function.arguments.substring(0,50):r.function.arguments}}))),s}return t}function Sm(t,e,n,o){let s=0;if(t.role==="system")return 100;if(t.role==="user")s+=35;else if(t.role==="tool"){let i=typeof t.content=="string"?t.content:JSON.stringify(t.content||"");/^(ERROR|BLOCKED|CANCELLED)/i.test(i)?s+=30:s+=15}else t.role==="assistant"&&(s+=t.tool_calls?20:10);let r=n>1?e/(n-1):1;if(s+=Math.round(r*30),o&&o.size>0){let i=typeof t.content=="string"?t.content:JSON.stringify(t.content||""),a=0;for(let c of o)(i.includes(c)||i.includes(Qv.basename(c)))&&a++;s+=Math.min(30,a*10)}return Math.min(100,s)}function Em(t,e=10){let n=new Set,o=t.slice(-e),s=/(?:\/[\w.-]+)+\.\w+/g;for(let r of o){let a=(typeof r.content=="string"?r.content:JSON.stringify(r.content||"")).match(s);a&&a.forEach(c=>n.add(c))}return n}function lS(t,{filesModified:e=new Set,currentPhase:n=null}={}){let o=[];if(e.size>0){let r=[...e].map(i=>i.split("/").slice(-2).join("/")).join(", ");o.push(`Files already modified: ${r} \u2014 do NOT rewrite these, use edit_file for additions only.`)}n&&o.push(`Current phase: ${n}`);let s=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 s.length>0&&o.push(`Recent progress:
210
210
  `+s.map(r=>`- ${r}`).join(`
211
211
  `)),o.length===0?null:{role:"system",content:`## Progress State (preserved through compression)
212
212
  ${o.join(`
213
- `)}`,_pinned:!0,_progressSnapshot:!0}}var Zs={msgCount:-1,lastMsgRef:null,result:null};function uS(){Zs={msgCount:-1,lastMsgRef:null,result:null},wt={msgCount:-1,lastMsgRef:null,toolCount:-1,result:null,messagesRef:null,messageTokens:0,systemTokens:0,conversationTokens:0,toolResultTokens:0}}async function dS(t,e,n={}){let o=t.length>0?t[t.length-1]:null;if(!n.force&&Zs.result&&t.length===Zs.msgCount&&o===Zs.lastMsgRef)return Zs.result;let s=n.threshold??xm(),r=n.safetyMargin??bm,i=n.keepRecent??$m,a=ji(),c=Ii(e),u=Math.floor(a*(s-r)),l=u-c,d=Vt(t);if(d+c<=u){let ie={messages:t,compressed:!1,compacted:!1,tokensRemoved:0};return Zs={msgCount:t.length,lastMsgRef:o,result:ie},ie}let p=d,h=null,g=0;t.length>0&&t[0].role==="system"&&(h=t[0],g=1);let w=Math.max(g,t.length-i),_=t.slice(g,w),S=t.slice(w),A=_.map(ie=>Qs(ie,"light")),E=jn(h,A,S),v=Vt(E);if(v+c<=u)return{messages:E,compressed:!0,compacted:!1,tokensRemoved:p-v};if(A=_.map(ie=>Qs(ie,"medium")),E=jn(h,A,S),v=Vt(E),v+c<=u)return{messages:E,compressed:!0,compacted:!1,tokensRemoved:p-v};if(A=_.map(ie=>Qs(ie,"aggressive")),E=jn(h,A,S),v=Vt(E),v+c<=u)return{messages:E,compressed:!0,compacted:!1,tokensRemoved:p-v};let N=process.env.NEX_SKIP_COMPACTOR==="1",ne=_.filter(ie=>ie._pinned),oe=_.filter(ie=>!ie._compacted&&!ie._pinned);if(!N&&oe.length>=6)try{let{compactMessages:ie}=wl(),le=await ie(oe);if(le){let T=_.filter(ve=>ve._compacted&&!ve._pinned),F=[...ne,...T,le.message],ee=jn(h,F,S),be=Vt(ee);if(be+c<=u)return{messages:ee,compressed:!0,compacted:!0,tokensRemoved:p-be};_=F}}catch(ie){process.env.NEX_DEBUG&&console.error("[context-engine] LLM compacting failed:",ie.message)}let ue=Sm([...A,...S]),fe=A.map((ie,le)=>({msg:ie,score:ie._pinned?1/0:vm(ie,le,A.length,ue),tokens:cs(ie)}));for(;fe.length>0&&v>l;){let ie=-1;for(let le=0;le<fe.length;le++)fe[le].score!==1/0&&(ie===-1||fe[le].score<fe[ie].score)&&(ie=le);if(ie===-1)break;v-=fe[ie].tokens,fe.splice(ie,1)}return A=fe.map(ie=>ie.msg),E=jn(h,A,S),v=Vt(E),{messages:E,compressed:!0,compacted:!1,tokensRemoved:p-v}}function jn(t,e,n){let o=[];return t&&o.push(t),o.push(...e,...n),o}function fS(t,e){if(!t)return"";if(as(t)<=e)return t;let o=e*4,s=t.split(`
213
+ `)}`,_pinned:!0,_progressSnapshot:!0}}var Zs={msgCount:-1,lastMsgRef:null,result:null};function uS(){Zs={msgCount:-1,lastMsgRef:null,result:null},wt={msgCount:-1,lastMsgRef:null,toolCount:-1,result:null,messagesRef:null,messageTokens:0,systemTokens:0,conversationTokens:0,toolResultTokens:0}}async function dS(t,e,n={}){let o=t.length>0?t[t.length-1]:null;if(!n.force&&Zs.result&&t.length===Zs.msgCount&&o===Zs.lastMsgRef)return Zs.result;let s=n.threshold??km(),r=n.safetyMargin??$m,i=n.keepRecent??_m,a=ji(),c=Ii(e),u=Math.floor(a*(s-r)),l=u-c,d=Vt(t);if(d+c<=u){let ie={messages:t,compressed:!1,compacted:!1,tokensRemoved:0};return Zs={msgCount:t.length,lastMsgRef:o,result:ie},ie}let p=d,h=null,g=0;t.length>0&&t[0].role==="system"&&(h=t[0],g=1);let w=Math.max(g,t.length-i),_=t.slice(g,w),S=t.slice(w),A=_.map(ie=>Qs(ie,"light")),E=jn(h,A,S),v=Vt(E);if(v+c<=u)return{messages:E,compressed:!0,compacted:!1,tokensRemoved:p-v};if(A=_.map(ie=>Qs(ie,"medium")),E=jn(h,A,S),v=Vt(E),v+c<=u)return{messages:E,compressed:!0,compacted:!1,tokensRemoved:p-v};if(A=_.map(ie=>Qs(ie,"aggressive")),E=jn(h,A,S),v=Vt(E),v+c<=u)return{messages:E,compressed:!0,compacted:!1,tokensRemoved:p-v};let N=process.env.NEX_SKIP_COMPACTOR==="1",ne=_.filter(ie=>ie._pinned),oe=_.filter(ie=>!ie._compacted&&!ie._pinned);if(!N&&oe.length>=6)try{let{compactMessages:ie}=wl(),le=await ie(oe);if(le){let T=_.filter(ve=>ve._compacted&&!ve._pinned),F=[...ne,...T,le.message],ee=jn(h,F,S),be=Vt(ee);if(be+c<=u)return{messages:ee,compressed:!0,compacted:!0,tokensRemoved:p-be};_=F}}catch(ie){process.env.NEX_DEBUG&&console.error("[context-engine] LLM compacting failed:",ie.message)}let ue=Em([...A,...S]),fe=A.map((ie,le)=>({msg:ie,score:ie._pinned?1/0:Sm(ie,le,A.length,ue),tokens:cs(ie)}));for(;fe.length>0&&v>l;){let ie=-1;for(let le=0;le<fe.length;le++)fe[le].score!==1/0&&(ie===-1||fe[le].score<fe[ie].score)&&(ie=le);if(ie===-1)break;v-=fe[ie].tokens,fe.splice(ie,1)}return A=fe.map(ie=>ie.msg),E=jn(h,A,S),v=Vt(E),{messages:E,compressed:!0,compacted:!1,tokensRemoved:p-v}}function jn(t,e,n){let o=[];return t&&o.push(t),o.push(...e,...n),o}function fS(t,e){if(!t)return"";if(as(t)<=e)return t;let o=e*4,s=t.split(`
214
214
  `),r=Math.floor(o*.6),i=Math.floor(o*.4),a="",c=0;for(let p of s){if(a.length+p.length+1>r)break;a+=(a?`
215
215
  `:"")+p,c++}let u="",l=0;for(let p=s.length-1;p>=c;p--){let h=s[p]+(u?`
216
216
  `:"")+u;if(h.length>i)break;u=h,l++}let f=`
217
217
 
218
218
  ... (${s.length-c-l} lines omitted, ${s.length} total) ...
219
219
 
220
- `;return a+f+u}var pS=6;function hS(t,e,n=!1){let o=ji(),s=Ii(e),r=Math.floor(o*(n?.35:.5))-s,i=Vt(t),a=Math.floor(i*(n?.5:.8));r>a&&(r=a);let c=null,u=0;t.length>0&&t[0].role==="system"&&(c=t[0],u=1);let l=n?2:pS,d=Math.max(u,t.length-l),f=t.slice(u,d),p=t.slice(d),h=f.map(v=>Qs(v,"aggressive"));n&&(p=p.map(v=>Qs(v,"aggressive")));let g=jn(c,h,p),w=Vt(g);for(;h.length>0&&w>r;){let v=h.shift();w-=cs(v)}n&&w>r&&(p=p.filter(N=>N.role==="user").slice(-1),g=jn(c,[],p),w=Vt(g)),g=jn(c,h,p);let _=t.filter(v=>v.role==="user"),S=v=>{let N=typeof v.content=="string"?v.content:"";return N.startsWith("[SYSTEM WARNING]")||N.startsWith("[SYSTEM:")||N.startsWith("BLOCKED:")},A=_.find(v=>!S(v)),E=[..._].reverse().find(v=>!S(v));if(A&&!g.find(v=>v===A)){let v=g.findIndex(ne=>ne.role==="system"),N=v>=0?v+1:0;g.splice(N,0,A)}return E&&E!==A&&!g.find(v=>v===E)&&g.push(E),{messages:g,tokensRemoved:i-Vt(g)}}Em.exports={estimateTokens:as,estimateMessageTokens:cs,estimateMessagesTokens:Vt,estimateDeltaTokens:rS,estimateToolsTokens:Ii,serializeMessage:oS,getContextWindow:ji,getUsage:iS,compressMessage:Qs,compressToolResult:km,scoreMessageRelevance:vm,extractActiveFiles:Sm,buildProgressSnapshot:lS,fitToContext:dS,forceCompress:hS,truncateFileContent:fS,invalidateTokenRatioCache:sS,invalidateFitToContextCache:uS,getEffectiveCompressionThreshold:xm,COMPRESSION_THRESHOLD:Ko,TIER_COMPRESSION_THRESHOLDS:_m,SAFETY_MARGIN:bm,KEEP_RECENT:$m}});var to=Q((mO,Tm)=>{var{fork:mS}=require("child_process"),gS=require("path"),yS=gS.join(__dirname,"background-worker.js"),ls=new Map,eo=new Map;function wS(){return`bg-${Date.now()}-${Math.random().toString(36).slice(2,6)}`}function bS(t){let e=wS(),n=mS(yS,[],{silent:!0,env:process.env,cwd:process.cwd()});return n.send({jobId:e,agentDef:t}),n.on("message",o=>{o.type==="result"?_l(e,t,o.payload):o.type==="error"&&_l(e,t,{task:t.task,status:"failed",result:`Background agent error: ${o.error}`,toolsUsed:[],tokensUsed:{input:0,output:0}})}),n.on("exit",(o,s)=>{if(ls.has(e)){let r=s?`killed (${s})`:`exit code ${o}`;_l(e,t,{task:t.task,status:"failed",result:`Background agent terminated unexpectedly: ${r}`,toolsUsed:[],tokensUsed:{input:0,output:0}})}}),ls.set(e,{process:n,agentDef:t,startedAt:Date.now()}),e}function _l(t,e,n){ls.delete(t),eo.set(t,{jobId:t,agentDef:e,result:n,finishedAt:Date.now()})}function $S(){if(eo.size===0)return[];let t=[...eo.values()];return eo.clear(),t}function _S(){return ls.size>0||eo.size>0}function xS(){let t=ls.size;return t===0?"":`${t} bg agent${t===1?"":"s"} running`}function kS(){for(let[t,e]of ls){try{e.process.kill("SIGTERM")}catch{}ls.delete(t)}eo.clear()}Tm.exports={createJob:bS,getCompletedJobs:$S,getPendingJobSummary:xS,hasPendingOrCompletedJobs:_S,cancelAllJobs:kS}});var Sl=Q((yO,Km)=>{var{callStream:vS,getActiveProviderName:qi,getActiveModelId:Rm,getConfiguredProviders:SS,getProvider:Cm,getActiveProvider:Am,parseModelSpec:Om}=ct(),{parseToolArgs:Nm}=Ao(),{filterToolsForModel:ES,getModelTier:Di}=Uo(),{getModelBriefing:TS}=Li(),{trackUsage:Mm,estimateTokens:Pm}=ii(),{MultiProgress:RS,C:gO}=rt();function Lm(t){return!t||typeof t!="string"?0:typeof Pm=="function"?Pm(t):Math.ceil(t.length/4)}var Dm=15,CS=parseInt(process.env.NEX_MAX_PARALLEL||"5",10),Im=parseInt(process.env.NEX_MAX_CHAT_RETRIES||"3",10),qm=8,AS=2,Fi=new Map,Fm=600*1e3;function OS(t,e){let n=Fi.get(t);return n&&n.agentId!==e&&Date.now()-n.timestamp<Fm?!1:(Fi.set(t,{agentId:e,timestamp:Date.now()}),!0)}function Xo(t){Fi.delete(t)}function xl(){Fi.clear()}function kl(t){let e=(t.message||"").toLowerCase(),n=t.code||"";return e.includes("429")||e.includes("rate limit")?"rate_limit":e.includes("401")||e.includes("403")||e.includes("unauthorized")||e.includes("forbidden")?"auth":e.includes("context")&&(e.includes("too long")||e.includes("overflow")||e.includes("maximum"))||e.includes("400")&&(e.includes("content")||e.includes("length"))?"context_overflow":e.includes("500")||e.includes("502")||e.includes("503")||e.includes("504")?"server":e.includes("timed out")||e.includes("timeout")?"timeout":n==="ECONNRESET"||n==="ECONNABORTED"||n==="ETIMEDOUT"||n==="ECONNREFUSED"||n==="ENOTFOUND"||e.includes("socket disconnected")||e.includes("tls")||e.includes("econnreset")||e.includes("fetch failed")||e.includes("etimedout")||e.includes("enotfound")?"network":"unknown"}function Bm(t){let e=kl(t);return e==="rate_limit"||e==="server"||e==="network"||e==="timeout"}async function Um(t,e,n){let o;for(let s=0;s<=Im;s++)try{return await vS(t,e,n)}catch(r){o=r;let i=kl(r);if(i==="auth")throw r.message=`Authentication failed \u2014 check your API key or permissions. (${r.message})`,r;if(i==="context_overflow")throw r.message=`Context window exceeded \u2014 reduce message history or use a model with a larger context. (${r.message})`,r;if(s<Im&&Bm(r)){let c=i==="rate_limit"?Math.min(2e3*Math.pow(2,s),15e3):Math.min(500*Math.pow(2,s),4e3);await new Promise(u=>setTimeout(u,c).unref());continue}throw r}throw o}var jm=new Set(["ask_user","task_list"]);function Wm(t){return t>=2?new Set([...jm,"spawn_agents"]):jm}var NS=new Set(["write_file","edit_file","patch_file"]),Hm={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 only. Do NOT make changes. Output findings first, ordered by severity, using this format: "Finding: <title> | Severity: <high|medium|low> | File: <path[:line]> | Why: <impact>". After findings, add one short "Residual risk:" line. If there are no findings, say "No material findings" and still mention the main residual risk/test gap.'},implement:{allowedTools:null,systemSuffix:""}},MS=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,PS=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function Ym(t){return PS.test(t)?"full":MS.test(t)?"essential":t.length>300?"full":"standard"}function Gm(t){let e=SS(),n=qi(),o=[...e].sort((s,r)=>(s.name===n?-1:1)-(r.name===n?-1:1));for(let s of o)for(let r of s.models)if(Di(r.id,s.name)===t)return{provider:s.name,model:r.id};return null}var LS={essential:process.env.NEX_FAST_MODEL||null,standard:process.env.NEX_STANDARD_MODEL||null,full:process.env.NEX_HEAVY_MODEL||null};function Bi(t){if(t.model){let{provider:s,model:r}=Om(t.model),i=s?Cm(s):Am(),a=s||qi();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let c=Di(r,a);return{provider:a,model:r,tier:c}}}let e=Ym(t.task),n=LS[e];if(n){let{provider:s,model:r}=Om(n),i=s?Cm(s):Am(),a=s||qi();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let c=Di(r,a);return{provider:a,model:r,tier:c}}}let o=Gm(e);if(o){let s=Di(o.model,o.provider);return{provider:o.provider,model:o.model,tier:s}}return{provider:null,model:null,tier:null}}async function zm(t,e={},n=0){let o=n===0?Dm:qm,s=Math.min(t.max_iterations||10,o),r=`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,i=[],a={input:0,output:0},c=new Set,u=new Map,l=t._systemPrompt||`You are a focused sub-agent. Complete this specific task efficiently.
220
+ `;return a+f+u}var pS=6;function hS(t,e,n=!1){let o=ji(),s=Ii(e),r=Math.floor(o*(n?.35:.5))-s,i=Vt(t),a=Math.floor(i*(n?.5:.8));r>a&&(r=a);let c=null,u=0;t.length>0&&t[0].role==="system"&&(c=t[0],u=1);let l=n?2:pS,d=Math.max(u,t.length-l),f=t.slice(u,d),p=t.slice(d),h=f.map(v=>Qs(v,"aggressive"));n&&(p=p.map(v=>Qs(v,"aggressive")));let g=jn(c,h,p),w=Vt(g);for(;h.length>0&&w>r;){let v=h.shift();w-=cs(v)}n&&w>r&&(p=p.filter(N=>N.role==="user").slice(-1),g=jn(c,[],p),w=Vt(g)),g=jn(c,h,p);let _=t.filter(v=>v.role==="user"),S=v=>{let N=typeof v.content=="string"?v.content:"";return N.startsWith("[SYSTEM WARNING]")||N.startsWith("[SYSTEM:")||N.startsWith("BLOCKED:")},A=_.find(v=>!S(v)),E=[..._].reverse().find(v=>!S(v));if(A&&!g.find(v=>v===A)){let v=g.findIndex(ne=>ne.role==="system"),N=v>=0?v+1:0;g.splice(N,0,A)}return E&&E!==A&&!g.find(v=>v===E)&&g.push(E),{messages:g,tokensRemoved:i-Vt(g)}}Tm.exports={estimateTokens:as,estimateMessageTokens:cs,estimateMessagesTokens:Vt,estimateDeltaTokens:rS,estimateToolsTokens:Ii,serializeMessage:oS,getContextWindow:ji,getUsage:iS,compressMessage:Qs,compressToolResult:vm,scoreMessageRelevance:Sm,extractActiveFiles:Em,buildProgressSnapshot:lS,fitToContext:dS,forceCompress:hS,truncateFileContent:fS,invalidateTokenRatioCache:sS,invalidateFitToContextCache:uS,getEffectiveCompressionThreshold:km,COMPRESSION_THRESHOLD:Ko,TIER_COMPRESSION_THRESHOLDS:xm,SAFETY_MARGIN:$m,KEEP_RECENT:_m}});var to=Q((gO,Rm)=>{var{fork:mS}=require("child_process"),gS=require("path"),yS=gS.join(__dirname,"background-worker.js"),ls=new Map,eo=new Map;function wS(){return`bg-${Date.now()}-${Math.random().toString(36).slice(2,6)}`}function bS(t){let e=wS(),n=mS(yS,[],{silent:!0,env:process.env,cwd:process.cwd()});return n.send({jobId:e,agentDef:t}),n.on("message",o=>{o.type==="result"?_l(e,t,o.payload):o.type==="error"&&_l(e,t,{task:t.task,status:"failed",result:`Background agent error: ${o.error}`,toolsUsed:[],tokensUsed:{input:0,output:0}})}),n.on("exit",(o,s)=>{if(ls.has(e)){let r=s?`killed (${s})`:`exit code ${o}`;_l(e,t,{task:t.task,status:"failed",result:`Background agent terminated unexpectedly: ${r}`,toolsUsed:[],tokensUsed:{input:0,output:0}})}}),ls.set(e,{process:n,agentDef:t,startedAt:Date.now()}),e}function _l(t,e,n){ls.delete(t),eo.set(t,{jobId:t,agentDef:e,result:n,finishedAt:Date.now()})}function $S(){if(eo.size===0)return[];let t=[...eo.values()];return eo.clear(),t}function _S(){return ls.size>0||eo.size>0}function xS(){let t=ls.size;return t===0?"":`${t} bg agent${t===1?"":"s"} running`}function kS(){for(let[t,e]of ls){try{e.process.kill("SIGTERM")}catch{}ls.delete(t)}eo.clear()}Rm.exports={createJob:bS,getCompletedJobs:$S,getPendingJobSummary:xS,hasPendingOrCompletedJobs:_S,cancelAllJobs:kS}});var Sl=Q((wO,Xm)=>{var{callStream:vS,getActiveProviderName:qi,getActiveModelId:Cm,getConfiguredProviders:SS,getProvider:Am,getActiveProvider:Om,parseModelSpec:Nm}=ct(),{parseToolArgs:Mm}=Ao(),{filterToolsForModel:ES,getModelTier:Di}=Uo(),{getModelBriefing:TS}=Li(),{trackUsage:Pm,estimateTokens:Lm}=ii(),{MultiProgress:RS,C:yO}=rt();function Im(t){return!t||typeof t!="string"?0:typeof Lm=="function"?Lm(t):Math.ceil(t.length/4)}var qm=15,CS=parseInt(process.env.NEX_MAX_PARALLEL||"5",10),jm=parseInt(process.env.NEX_MAX_CHAT_RETRIES||"3",10),Fm=8,AS=2,Fi=new Map,Bm=600*1e3;function OS(t,e){let n=Fi.get(t);return n&&n.agentId!==e&&Date.now()-n.timestamp<Bm?!1:(Fi.set(t,{agentId:e,timestamp:Date.now()}),!0)}function Xo(t){Fi.delete(t)}function xl(){Fi.clear()}function kl(t){let e=(t.message||"").toLowerCase(),n=t.code||"";return e.includes("429")||e.includes("rate limit")?"rate_limit":e.includes("401")||e.includes("403")||e.includes("unauthorized")||e.includes("forbidden")?"auth":e.includes("context")&&(e.includes("too long")||e.includes("overflow")||e.includes("maximum"))||e.includes("400")&&(e.includes("content")||e.includes("length"))?"context_overflow":e.includes("500")||e.includes("502")||e.includes("503")||e.includes("504")?"server":e.includes("timed out")||e.includes("timeout")?"timeout":n==="ECONNRESET"||n==="ECONNABORTED"||n==="ETIMEDOUT"||n==="ECONNREFUSED"||n==="ENOTFOUND"||e.includes("socket disconnected")||e.includes("tls")||e.includes("econnreset")||e.includes("fetch failed")||e.includes("etimedout")||e.includes("enotfound")?"network":"unknown"}function Um(t){let e=kl(t);return e==="rate_limit"||e==="server"||e==="network"||e==="timeout"}async function Wm(t,e,n){let o;for(let s=0;s<=jm;s++)try{return await vS(t,e,n)}catch(r){o=r;let i=kl(r);if(i==="auth")throw r.message=`Authentication failed \u2014 check your API key or permissions. (${r.message})`,r;if(i==="context_overflow")throw r.message=`Context window exceeded \u2014 reduce message history or use a model with a larger context. (${r.message})`,r;if(s<jm&&Um(r)){let c=i==="rate_limit"?Math.min(2e3*Math.pow(2,s),15e3):Math.min(500*Math.pow(2,s),4e3);await new Promise(u=>setTimeout(u,c).unref());continue}throw r}throw o}var Dm=new Set(["ask_user","task_list"]);function Hm(t){return t>=2?new Set([...Dm,"spawn_agents"]):Dm}var NS=new Set(["write_file","edit_file","patch_file"]),Ym={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 only. Do NOT make changes. Output findings first, ordered by severity, using this format: "Finding: <title> | Severity: <high|medium|low> | File: <path[:line]> | Why: <impact>". After findings, add one short "Residual risk:" line. If there are no findings, say "No material findings" and still mention the main residual risk/test gap.'},implement:{allowedTools:null,systemSuffix:""}},MS=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,PS=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function Gm(t){return PS.test(t)?"full":MS.test(t)?"essential":t.length>300?"full":"standard"}function zm(t){let e=SS(),n=qi(),o=[...e].sort((s,r)=>(s.name===n?-1:1)-(r.name===n?-1:1));for(let s of o)for(let r of s.models)if(Di(r.id,s.name)===t)return{provider:s.name,model:r.id};return null}var LS={essential:process.env.NEX_FAST_MODEL||null,standard:process.env.NEX_STANDARD_MODEL||null,full:process.env.NEX_HEAVY_MODEL||null};function Bi(t){if(t.model){let{provider:s,model:r}=Nm(t.model),i=s?Am(s):Om(),a=s||qi();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let c=Di(r,a);return{provider:a,model:r,tier:c}}}let e=Gm(t.task),n=LS[e];if(n){let{provider:s,model:r}=Nm(n),i=s?Am(s):Om(),a=s||qi();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let c=Di(r,a);return{provider:a,model:r,tier:c}}}let o=zm(e);if(o){let s=Di(o.model,o.provider);return{provider:o.provider,model:o.model,tier:s}}return{provider:null,model:null,tier:null}}async function Km(t,e={},n=0){let o=n===0?qm:Fm,s=Math.min(t.max_iterations||10,o),r=`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,i=[],a={input:0,output:0},c=new Set,u=new Map,l=t._systemPrompt||`You are a focused sub-agent. Complete this specific task efficiently.
221
221
 
222
222
  TASK: ${t.task}
223
223
  ${t.context?`
@@ -243,30 +243,30 @@ TOOL STRATEGY:
243
243
  ERROR RECOVERY:
244
244
  - If edit_file fails with "old_text not found": read the file again, compare, and retry with exact text.
245
245
  - If bash fails: read the error, fix the root cause, then retry.
246
- - After 2 failed attempts at the same operation, summarize the issue and stop.`,d=t.type&&Hm[t.type],f=d&&d.systemSuffix?`
246
+ - After 2 failed attempts at the same operation, summarize the issue and stop.`,d=t.type&&Ym[t.type],f=d&&d.systemSuffix?`
247
247
 
248
- ${d.systemSuffix}`:"",p=Bi(t),h=p.provider,g=p.model,w=p.tier,_=TS(g||Rm()),A=[{role:"system",content:(_?`## Model Briefing
248
+ ${d.systemSuffix}`:"",p=Bi(t),h=p.provider,g=p.model,w=p.tier,_=TS(g||Cm()),A=[{role:"system",content:(_?`## Model Briefing
249
249
  ${_}
250
250
 
251
251
  ---
252
252
 
253
- `:"")+l+f}];A.push({role:"user",content:t.task});let{TOOL_DEFINITIONS:E,executeTool:v}=zs(),N=Wm(n),ne=ES(E.filter(fe=>!N.has(fe.function.name)),w);if(d&&d.allowedTools&&(ne=ne.filter(fe=>d.allowedTools.has(fe.function.name))),g&&!t._skipLog){let fe=w?` (${w})`:"";process.stderr.write(` [sub-agent: ${h}:${g}${fe}]
254
- `)}let oe={};h&&(oe.provider=h),g&&(oe.model=g);let ue=new Set;try{for(let ie=0;ie<s;ie++){let le=await Um(A,ne,oe);if(!le||typeof le!="object")throw new Error("Empty or invalid response from provider");{let Me=h||qi(),Ee=g||Rm();if(le.usage){let x=le.usage.prompt_tokens||0,P=le.usage.completion_tokens||0;a.input+=x,a.output+=P,Mm(Me,Ee,x,P)}else{let x=le.content||"",P=A.map(X=>typeof X.content=="string"?X.content:Array.isArray(X.content)?X.content.map(C=>typeof C=="string"?C:C.text||"").join(""):"").join(" "),B=Lm(P),te=Lm(x);a.input+=B,a.output+=te,a._estimated=!0,Mm(Me,Ee,B,te)}}let T=le.content||"",F=le.tool_calls,ee={role:"assistant",content:T||""};if(F&&F.length>0&&(ee.tool_calls=F),A.push(ee),!F||F.length===0){for(let Me of c)Xo(Me);return{task:t.task,status:"done",result:T||"(no response)",toolsUsed:i,tokensUsed:a,modelSpec:h&&g?`${h}:${g}`:null}}let be=new Set,ve=F.map(Me=>{let Ee=Me.function.name,x=Nm(Me.function.arguments),P=Me.id||`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!x)return Promise.resolve({role:"tool",content:`ERROR: Malformed tool arguments for ${Ee}`,tool_call_id:P});if(["edit_file","patch_file"].includes(Ee)&&x.path){if(ue.has(x.path)||be.has(x.path))return Promise.resolve({role:"tool",content:`BLOCKED: "${x.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});be.add(x.path)}let B=null;if(NS.has(Ee)&&x.path){let X=require("path"),C=X.isAbsolute(x.path)?x.path:X.resolve(process.cwd(),x.path);if(t._readOnlyFiles&&t._readOnlyFiles.length>0){let he=X.relative(process.cwd(),C);if(t._readOnlyFiles.some(re=>he===re||he.startsWith(re+"/")||C===re||C.startsWith(re+"/")))return Promise.resolve({role:"tool",content:`ERROR: File '${x.path}' is owned by another agent and is READ ONLY. Write to your own scope files instead.`,tool_call_id:P})}if(c.has(C)||!OS(C,r))return Promise.resolve({role:"tool",content:`ERROR: File '${x.path}' is locked by another operation. Try a different approach or skip this file.`,tool_call_id:P});c.add(C),B=C}return i.push(Ee),e.onUpdate&&e.onUpdate({type:"tool_call",tool:Ee,agentId:r}),(Ee==="spawn_agents"?vl(x,n+1):v(Ee,x,{autoConfirm:!0,silent:!0})).then(X=>{B&&(Xo(B),c.delete(B));let C=String(X??"");return x&&x.path&&(["edit_file","patch_file","write_file"].includes(Ee)&&C.startsWith("Edited:")?ue.add(x.path):Ee==="read_file"&&!C.startsWith("ERROR")&&ue.delete(x.path)),{role:"tool",content:C.length>2e4?C.substring(0,2e4)+`
255
- ...(truncated)`:C,tool_call_id:P}}).catch(X=>(B&&(Xo(B),c.delete(B)),{role:"tool",content:`ERROR: ${X.message}`,tool_call_id:P}))}),Fe=await Promise.all(ve);if(A.push(...Fe),ie>=7&&A.length>12)try{let{compressMessage:Me}=fn(),Ee=A.length-6;for(let x=1;x<Ee;x++)A[x]._subAgentCompressed||(A[x]={...Me(A[x],"light"),_subAgentCompressed:!0})}catch{}for(let Me=0;Me<F.length;Me++){let Ee=F[Me];if(Ee.function.name==="bash_exec"){let x=Nm(Ee.function.arguments);if((Fe[Me]?.content||"").startsWith("ERROR")&&x&&x.command){let B=x.command.replace(/\s+/g," ").trim().slice(0,100);u.set(B,(u.get(B)||0)+1)}}}e.onUpdate&&e.onUpdate(`step ${ie+1}/${s}`)}for(let ie of c)Xo(ie);let fe=[...u.entries()].filter(([,ie])=>ie>=3).sort((ie,le)=>le[1]-ie[1]).slice(0,3).map(([ie,le])=>`"${ie}" (failed ${le}\xD7)`);return{task:t.task,status:"truncated",abortReason:"iteration_limit",repeatedFailures:fe,result:A[A.length-1]?.content||"(max iterations reached)",toolsUsed:i,tokensUsed:a,modelSpec:h&&g?`${h}:${g}`:null}}catch(fe){for(let ie of c)Xo(ie);return{task:t.task,status:"failed",result:`Error: ${fe.message}`,toolsUsed:i,tokensUsed:a,modelSpec:h&&g?`${h}:${g}`:null}}}async function vl(t,e=0){if(e>=2)return"ERROR: max agent nesting depth (2) reached \u2014 reviewer agents cannot spawn further agents.";let n=e===0?CS:AS,o=e===0?Dm:qm,s=(t.agents||[]).slice(0,n);if(s.length===0)return"ERROR: No agents specified";let r=e>0?" \u21B3 ":"",i=e>0?38:44,a=s.map(l=>Bi(l)),c=s.map((l,d)=>{let f=a[d],p=f.model?` [${f.model}]`:"",h=l.task.substring(0,i-p.length);return`${r}Agent ${d+1}${p}: ${h}${l.task.length>h.length?"...":""}`}),u=new RS(c);u.start();try{let l=s.map((g,w)=>{let _=a[w],S=Math.min(g.max_iterations||o,o),A=_.model?{...g,model:`${_.provider}:${_.model}`,_skipLog:!0,max_iterations:S}:{...g,_skipLog:!0,max_iterations:S};return zm(A,{onUpdate:()=>{}},e).then(E=>(u.update(w,E.status==="failed"?"error":"done"),E)).catch(E=>(u.update(w,"error"),{task:g.task,status:"failed",result:`Error: ${E.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}))}),d=await Promise.all(l);u.stop(),xl();let f=["Sub-agent results:",""],p=0,h=0;for(let g=0;g<d.length;g++){let w=d[g],_=w.status==="done"?"\u2713":w.status==="truncated"?"\u26A0":"\u2717",S=w.modelSpec?` [${w.modelSpec}]`:"";f.push(`${_} Agent ${g+1}${S}: ${w.task}`),f.push(` Status: ${w.status}`),f.push(` Tools used: ${w.toolsUsed.length>0?w.toolsUsed.join(", "):"none"}`),f.push(` Result: ${w.result}`),w.repeatedFailures&&w.repeatedFailures.length>0&&f.push(` Repeated failures: ${w.repeatedFailures.join("; ")}`),f.push(""),p+=w.tokensUsed.input,h+=w.tokensUsed.output}return f.push(`Total sub-agent tokens: ${p} input + ${h} output`),f.join(`
253
+ `:"")+l+f}];A.push({role:"user",content:t.task});let{TOOL_DEFINITIONS:E,executeTool:v}=zs(),N=Hm(n),ne=ES(E.filter(fe=>!N.has(fe.function.name)),w);if(d&&d.allowedTools&&(ne=ne.filter(fe=>d.allowedTools.has(fe.function.name))),g&&!t._skipLog){let fe=w?` (${w})`:"";process.stderr.write(` [sub-agent: ${h}:${g}${fe}]
254
+ `)}let oe={};h&&(oe.provider=h),g&&(oe.model=g);let ue=new Set;try{for(let ie=0;ie<s;ie++){let le=await Wm(A,ne,oe);if(!le||typeof le!="object")throw new Error("Empty or invalid response from provider");{let Me=h||qi(),Ee=g||Cm();if(le.usage){let x=le.usage.prompt_tokens||0,P=le.usage.completion_tokens||0;a.input+=x,a.output+=P,Pm(Me,Ee,x,P)}else{let x=le.content||"",P=A.map(X=>typeof X.content=="string"?X.content:Array.isArray(X.content)?X.content.map(C=>typeof C=="string"?C:C.text||"").join(""):"").join(" "),B=Im(P),te=Im(x);a.input+=B,a.output+=te,a._estimated=!0,Pm(Me,Ee,B,te)}}let T=le.content||"",F=le.tool_calls,ee={role:"assistant",content:T||""};if(F&&F.length>0&&(ee.tool_calls=F),A.push(ee),!F||F.length===0){for(let Me of c)Xo(Me);return{task:t.task,status:"done",result:T||"(no response)",toolsUsed:i,tokensUsed:a,modelSpec:h&&g?`${h}:${g}`:null}}let be=new Set,ve=F.map(Me=>{let Ee=Me.function.name,x=Mm(Me.function.arguments),P=Me.id||`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!x)return Promise.resolve({role:"tool",content:`ERROR: Malformed tool arguments for ${Ee}`,tool_call_id:P});if(["edit_file","patch_file"].includes(Ee)&&x.path){if(ue.has(x.path)||be.has(x.path))return Promise.resolve({role:"tool",content:`BLOCKED: "${x.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});be.add(x.path)}let B=null;if(NS.has(Ee)&&x.path){let X=require("path"),C=X.isAbsolute(x.path)?x.path:X.resolve(process.cwd(),x.path);if(t._readOnlyFiles&&t._readOnlyFiles.length>0){let he=X.relative(process.cwd(),C);if(t._readOnlyFiles.some(re=>he===re||he.startsWith(re+"/")||C===re||C.startsWith(re+"/")))return Promise.resolve({role:"tool",content:`ERROR: File '${x.path}' is owned by another agent and is READ ONLY. Write to your own scope files instead.`,tool_call_id:P})}if(c.has(C)||!OS(C,r))return Promise.resolve({role:"tool",content:`ERROR: File '${x.path}' is locked by another operation. Try a different approach or skip this file.`,tool_call_id:P});c.add(C),B=C}return i.push(Ee),e.onUpdate&&e.onUpdate({type:"tool_call",tool:Ee,agentId:r}),(Ee==="spawn_agents"?vl(x,n+1):v(Ee,x,{autoConfirm:!0,silent:!0})).then(X=>{B&&(Xo(B),c.delete(B));let C=String(X??"");return x&&x.path&&(["edit_file","patch_file","write_file"].includes(Ee)&&C.startsWith("Edited:")?ue.add(x.path):Ee==="read_file"&&!C.startsWith("ERROR")&&ue.delete(x.path)),{role:"tool",content:C.length>2e4?C.substring(0,2e4)+`
255
+ ...(truncated)`:C,tool_call_id:P}}).catch(X=>(B&&(Xo(B),c.delete(B)),{role:"tool",content:`ERROR: ${X.message}`,tool_call_id:P}))}),Fe=await Promise.all(ve);if(A.push(...Fe),ie>=7&&A.length>12)try{let{compressMessage:Me}=fn(),Ee=A.length-6;for(let x=1;x<Ee;x++)A[x]._subAgentCompressed||(A[x]={...Me(A[x],"light"),_subAgentCompressed:!0})}catch{}for(let Me=0;Me<F.length;Me++){let Ee=F[Me];if(Ee.function.name==="bash_exec"){let x=Mm(Ee.function.arguments);if((Fe[Me]?.content||"").startsWith("ERROR")&&x&&x.command){let B=x.command.replace(/\s+/g," ").trim().slice(0,100);u.set(B,(u.get(B)||0)+1)}}}e.onUpdate&&e.onUpdate(`step ${ie+1}/${s}`)}for(let ie of c)Xo(ie);let fe=[...u.entries()].filter(([,ie])=>ie>=3).sort((ie,le)=>le[1]-ie[1]).slice(0,3).map(([ie,le])=>`"${ie}" (failed ${le}\xD7)`);return{task:t.task,status:"truncated",abortReason:"iteration_limit",repeatedFailures:fe,result:A[A.length-1]?.content||"(max iterations reached)",toolsUsed:i,tokensUsed:a,modelSpec:h&&g?`${h}:${g}`:null}}catch(fe){for(let ie of c)Xo(ie);return{task:t.task,status:"failed",result:`Error: ${fe.message}`,toolsUsed:i,tokensUsed:a,modelSpec:h&&g?`${h}:${g}`:null}}}async function vl(t,e=0){if(e>=2)return"ERROR: max agent nesting depth (2) reached \u2014 reviewer agents cannot spawn further agents.";let n=e===0?CS:AS,o=e===0?qm:Fm,s=(t.agents||[]).slice(0,n);if(s.length===0)return"ERROR: No agents specified";let r=e>0?" \u21B3 ":"",i=e>0?38:44,a=s.map(l=>Bi(l)),c=s.map((l,d)=>{let f=a[d],p=f.model?` [${f.model}]`:"",h=l.task.substring(0,i-p.length);return`${r}Agent ${d+1}${p}: ${h}${l.task.length>h.length?"...":""}`}),u=new RS(c);u.start();try{let l=s.map((g,w)=>{let _=a[w],S=Math.min(g.max_iterations||o,o),A=_.model?{...g,model:`${_.provider}:${_.model}`,_skipLog:!0,max_iterations:S}:{...g,_skipLog:!0,max_iterations:S};return Km(A,{onUpdate:()=>{}},e).then(E=>(u.update(w,E.status==="failed"?"error":"done"),E)).catch(E=>(u.update(w,"error"),{task:g.task,status:"failed",result:`Error: ${E.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}))}),d=await Promise.all(l);u.stop(),xl();let f=["Sub-agent results:",""],p=0,h=0;for(let g=0;g<d.length;g++){let w=d[g],_=w.status==="done"?"\u2713":w.status==="truncated"?"\u26A0":"\u2717",S=w.modelSpec?` [${w.modelSpec}]`:"";f.push(`${_} Agent ${g+1}${S}: ${w.task}`),f.push(` Status: ${w.status}`),f.push(` Tools used: ${w.toolsUsed.length>0?w.toolsUsed.join(", "):"none"}`),f.push(` Result: ${w.result}`),w.repeatedFailures&&w.repeatedFailures.length>0&&f.push(` Repeated failures: ${w.repeatedFailures.join("; ")}`),f.push(""),p+=w.tokensUsed.input,h+=w.tokensUsed.output}return f.push(`Total sub-agent tokens: ${p} input + ${h} output`),f.join(`
256
256
  `)}catch(l){return u.stop(),xl(),`ERROR: Sub-agent execution failed: ${l.message}`}}async function IS(t){let{createJob:e}=to(),n=(t.agents||[]).filter(i=>i.background),o=(t.agents||[]).filter(i=>!i.background),s=n.map(i=>{let a=Bi(i),c=a.model?{...i,model:`${a.provider}:${a.model}`,_skipLog:!0}:{...i,_skipLog:!0};return e(c)}),r=[];if(s.length>0&&r.push(`Background agents started: [${s.join(", ")}]
257
257
  `+n.map((i,a)=>` ${s[a]}: ${i.task}`).join(`
258
258
  `)+`
259
259
  Results will be injected into the conversation when each agent completes.`),o.length>0){let i=await vl({agents:o});r.push(i)}return r.join(`
260
260
 
261
- `)||"No agents specified."}Km.exports={runSubAgent:zm,executeSpawnAgents:vl,executeSpawnAgentsBackground:IS,clearAllLocks:xl,classifyTask:Ym,pickModelForTier:Gm,resolveSubAgentModel:Bi,classifyError:kl,isRetryableError:Bm,callWithRetry:Um,getExcludedTools:Wm,LOCK_TIMEOUT_MS:Fm,SUB_AGENT_TYPES:Hm}});var Ml=Q((wO,cg)=>{var Je=require("fs"),Sn=require("path"),{atomicWrite:Xm,withFileLockSync:Vm}=Jn(),jS=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 so(){let t=Sn.join(process.cwd(),".nex","brain");return Je.existsSync(t)||Je.mkdirSync(t,{recursive:!0}),t}function Wi(){return Sn.join(so(),".brain-index.json")}function Rl(){return Sn.join(so(),".embeddings.json")}function Vo(){let t=Sn.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 n=Sn.join(t,e),o=Je.statSync(n);return{name:e.replace(/\.md$/,""),path:n,size:o.size,modified:new Date(o.mtimeMs)}}).sort((e,n)=>n.modified-e.modified)}catch{return[]}}function Jo(t){let e={},n=t,o=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(o){let s=o[1].split(`
262
- `);for(let r of s){let i=r.match(/^(\w+):\s*(.+)$/);if(!i)continue;let a=i[1].trim(),c=i[2].trim();c.startsWith("[")&&c.endsWith("]")?e[a]=c.slice(1,-1).split(",").map(u=>u.trim()).filter(Boolean):e[a]=c}n=o[2]}return{frontmatter:e,body:n}}function Jm(t){let e=Sn.join(so(),`${t}.md`);if(!Je.existsSync(e))return{name:t,content:"",body:"",frontmatter:{}};let n=Je.readFileSync(e,"utf-8"),{frontmatter:o,body:s}=Jo(n);return{name:t,content:n,body:s,frontmatter:o}}function DS(t,e){let n=Sn.join(so(),`${t}.md`);Xm(n,e),BS(t,e),qS()}function qS(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return;let t=Rl();Je.existsSync(t)&&setImmediate(async()=>{try{await og()}catch{}})}function FS(t){let e=Sn.join(so(),`${t}.md`);return Je.existsSync(e)?(Je.unlinkSync(e),US(t),!0):!1}function Ui(t){return t.toLowerCase().replace(/[^a-z0-9äöüß\s-]/g," ").split(/[\s-]+/).filter(e=>e.length>2&&!jS.has(e))}function Cl(t){let e={},{frontmatter:n,body:o}=Jo(t),s=Array.isArray(n.tags)?n.tags:[];for(let i of s){let a=i.toLowerCase().replace(/[^a-z0-9-]/g,"");a.length>1&&(e[a]=(e[a]||0)+5)}let r=(o||t).split(`
263
- `);for(let i of r)if(i.startsWith("#")){let a=i.replace(/^#+\s*/,"");for(let c of Ui(a))e[c]=(e[c]||0)+3}for(let i of Ui(o||t))e[i]=(e[i]||0)+1;return e}function Al(){let t=Wi();if(!Je.existsSync(t))return{documents:{}};try{return JSON.parse(Je.readFileSync(t,"utf-8"))}catch{return{documents:{}}}}function Ol(t){Xm(Wi(),JSON.stringify(t,null,2))}function BS(t,e){Vm(Wi(),()=>{let n=Al(),{frontmatter:o}=Jo(e),s=Array.isArray(o.tags)?o.tags:[];n.documents[t]={keywords:Cl(e),tags:s,modified:new Date().toISOString()},Ol(n)})}function US(t){Vm(Wi(),()=>{let e=Al();delete e.documents[t],Ol(e)})}function Tl(){let t=Vo(),e={documents:{}};for(let n of t){let o=Je.readFileSync(n.path,"utf-8"),{frontmatter:s}=Jo(o),r=Array.isArray(s.tags)?s.tags:[];e.documents[n.name]={keywords:Cl(o),tags:r,modified:n.modified.toISOString()}}return Ol(e),e}function Zm(){let t=Al(),e=Vo();for(let n of e){let o=t.documents[n.name];if(!o||new Date(o.modified)<n.modified)return Tl()}for(let n of Object.keys(t.documents))if(!e.some(o=>o.name===n))return Tl();return t}function Qm(t,e={}){let{topK:n=3,minScore:o=.1}=e,s=Ui(t);if(s.length===0)return[];let r=Zm(),i=[];for(let[a,c]of Object.entries(r.documents)){let u=0;for(let l of s){c.keywords[l]&&(u+=c.keywords[l]);for(let[d,f]of Object.entries(c.keywords))d!==l&&d.length>3&&l.length>3&&(d.includes(l)||l.includes(d))&&(u+=f*.3)}u>=o&&i.push({name:a,score:u})}return i.sort((a,c)=>c.score-a.score),i.slice(0,n)}var eg=process.env.NEX_EMBED_MODEL||"nomic-embed-text",El=400,WS=50;async function tg(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return!1;try{let t=process.env.OLLAMA_HOST||"http://localhost:11434",e=require("http"),n=require("https"),o=new URL(`${t}/api/tags`),s=o.protocol==="https:"?n:e;return((await new Promise((a,c)=>{let u=s.get(o.toString(),{timeout:2e3},l=>{let d="";l.on("data",f=>d+=f),l.on("end",()=>{try{a(JSON.parse(d))}catch{c(new Error("bad json"))}})});u.on("error",c),u.on("timeout",()=>{u.destroy(),c(new Error("timeout"))})})).models||[]).map(a=>a.name).some(a=>a.startsWith(eg.split(":")[0]))}catch{return!1}}async function Nl(t){let e=process.env.OLLAMA_HOST||"http://localhost:11434",n=require("http"),o=require("https"),s=new URL(`${e}/api/embeddings`),r=s.protocol==="https:"?o:n,i=JSON.stringify({model:eg,prompt:t});return new Promise((a,c)=>{let u=r.request(s,{method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(i)},timeout:3e4},l=>{let d="";l.on("data",f=>d+=f),l.on("end",()=>{try{a(JSON.parse(d).embedding||[])}catch(f){c(f)}})});u.on("error",c),u.on("timeout",()=>{u.destroy(),c(new Error("embedding timeout"))}),u.write(i),u.end()})}function ng(t,e){if(!t||!e||t.length!==e.length)return 0;let n=0,o=0,s=0;for(let i=0;i<t.length;i++)n+=t[i]*e[i],o+=t[i]*t[i],s+=e[i]*e[i];let r=Math.sqrt(o)*Math.sqrt(s);return r===0?0:n/r}function sg(t){let e=t.split(/\s+/),n=[],o=0;for(;o<e.length;){let s=e.slice(o,o+El).join(" ");if(n.push({text:s,offset:o}),o+El>=e.length)break;o+=El-WS}return n}async function og(){let t=Vo(),e={documents:{}},n=Rl();if(Je.existsSync(n))try{e=JSON.parse(Je.readFileSync(n,"utf-8"))}catch{}for(let o of t){let s=e.documents[o.name];if(s&&new Date(s.modified)>=o.modified)continue;let r=Je.readFileSync(o.path,"utf-8"),i=sg(r),a=[];for(let c of i){let u=await Nl(c.text);a.push({text:c.text,embedding:u,offset:c.offset})}e.documents[o.name]={chunks:a,modified:o.modified.toISOString()}}for(let o of Object.keys(e.documents))t.some(s=>s.name===o)||delete e.documents[o];return Je.writeFileSync(n,JSON.stringify(e),"utf-8"),e}async function rg(t,e={}){let{topK:n=3,minSimilarity:o=.3}=e,s=Rl();if(!Je.existsSync(s))return[];let r;try{r=JSON.parse(Je.readFileSync(s,"utf-8"))}catch{return[]}let i=await Nl(t),a=[];for(let[c,u]of Object.entries(r.documents||{})){let l=0,d="";for(let f of u.chunks||[]){let p=ng(i,f.embedding);p>l&&(l=p,d=f.text)}l>=o&&a.push({name:c,score:l,bestChunk:d})}return a.sort((c,u)=>u.score-c.score),a.slice(0,n)}function ig(t,e,n={}){let{k:o=60,topK:s=3}=n,r={};return t.forEach((i,a)=>{r[i.name]=(r[i.name]||0)+1/(o+a+1)}),e.forEach((i,a)=>{r[i.name]=(r[i.name]||0)+1/(o+a+1)}),Object.entries(r).map(([i,a])=>({name:i,score:a})).sort((i,a)=>a.score-i.score).slice(0,s)}async function ag(t,e={}){let{topK:n=3,minScore:o=.1}=e,s=Qm(t,{topK:n,minScore:o}),r=s;if(process.env.NEX_BRAIN_EMBEDDINGS!=="false")try{if(await tg()){let a=await rg(t,{topK:n});r=ig(s,a,{topK:n})}}catch{}return r.map(i=>{let a=Jm(i.name),c=(a.body||a.content||"").slice(0,300).replace(/\n+/g," ")+"...";return{name:i.name,score:i.score,content:a.content,excerpt:c}})}var no={queryKey:null,result:null,ts:0},HS=3e5;async function YS(t){if(!t||!t.trim())return"";let e=Sn.join(process.cwd(),".nex","brain");if(!Je.existsSync(e)||Vo().length===0)return"";let o=t.trim().toLowerCase().slice(0,200);if(no.result!==null&&no.queryKey===o&&Date.now()-no.ts<HS)return no.result;let s;try{s=await ag(t,{topK:3})}catch{return""}if(!s||s.length===0)return"";let r;try{r=fn().estimateTokens}catch{r=l=>Math.ceil(l.length/4)}let i=25e3,a=[],c=0;for(let l of s){let d=l.content||"",f=r(d);if(c+f>i){let h=i-c;if(h<100)break;let g=h/f;d=d.slice(0,Math.floor(d.length*g))+`
261
+ `)||"No agents specified."}Xm.exports={runSubAgent:Km,executeSpawnAgents:vl,executeSpawnAgentsBackground:IS,clearAllLocks:xl,classifyTask:Gm,pickModelForTier:zm,resolveSubAgentModel:Bi,classifyError:kl,isRetryableError:Um,callWithRetry:Wm,getExcludedTools:Hm,LOCK_TIMEOUT_MS:Bm,SUB_AGENT_TYPES:Ym}});var Ml=Q((bO,lg)=>{var Je=require("fs"),Sn=require("path"),{atomicWrite:Vm,withFileLockSync:Jm}=Jn(),jS=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 so(){let t=Sn.join(process.cwd(),".nex","brain");return Je.existsSync(t)||Je.mkdirSync(t,{recursive:!0}),t}function Wi(){return Sn.join(so(),".brain-index.json")}function Rl(){return Sn.join(so(),".embeddings.json")}function Vo(){let t=Sn.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 n=Sn.join(t,e),o=Je.statSync(n);return{name:e.replace(/\.md$/,""),path:n,size:o.size,modified:new Date(o.mtimeMs)}}).sort((e,n)=>n.modified-e.modified)}catch{return[]}}function Jo(t){let e={},n=t,o=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(o){let s=o[1].split(`
262
+ `);for(let r of s){let i=r.match(/^(\w+):\s*(.+)$/);if(!i)continue;let a=i[1].trim(),c=i[2].trim();c.startsWith("[")&&c.endsWith("]")?e[a]=c.slice(1,-1).split(",").map(u=>u.trim()).filter(Boolean):e[a]=c}n=o[2]}return{frontmatter:e,body:n}}function Zm(t){let e=Sn.join(so(),`${t}.md`);if(!Je.existsSync(e))return{name:t,content:"",body:"",frontmatter:{}};let n=Je.readFileSync(e,"utf-8"),{frontmatter:o,body:s}=Jo(n);return{name:t,content:n,body:s,frontmatter:o}}function DS(t,e){let n=Sn.join(so(),`${t}.md`);Vm(n,e),BS(t,e),qS()}function qS(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return;let t=Rl();Je.existsSync(t)&&setImmediate(async()=>{try{await rg()}catch{}})}function FS(t){let e=Sn.join(so(),`${t}.md`);return Je.existsSync(e)?(Je.unlinkSync(e),US(t),!0):!1}function Ui(t){return t.toLowerCase().replace(/[^a-z0-9äöüß\s-]/g," ").split(/[\s-]+/).filter(e=>e.length>2&&!jS.has(e))}function Cl(t){let e={},{frontmatter:n,body:o}=Jo(t),s=Array.isArray(n.tags)?n.tags:[];for(let i of s){let a=i.toLowerCase().replace(/[^a-z0-9-]/g,"");a.length>1&&(e[a]=(e[a]||0)+5)}let r=(o||t).split(`
263
+ `);for(let i of r)if(i.startsWith("#")){let a=i.replace(/^#+\s*/,"");for(let c of Ui(a))e[c]=(e[c]||0)+3}for(let i of Ui(o||t))e[i]=(e[i]||0)+1;return e}function Al(){let t=Wi();if(!Je.existsSync(t))return{documents:{}};try{return JSON.parse(Je.readFileSync(t,"utf-8"))}catch{return{documents:{}}}}function Ol(t){Vm(Wi(),JSON.stringify(t,null,2))}function BS(t,e){Jm(Wi(),()=>{let n=Al(),{frontmatter:o}=Jo(e),s=Array.isArray(o.tags)?o.tags:[];n.documents[t]={keywords:Cl(e),tags:s,modified:new Date().toISOString()},Ol(n)})}function US(t){Jm(Wi(),()=>{let e=Al();delete e.documents[t],Ol(e)})}function Tl(){let t=Vo(),e={documents:{}};for(let n of t){let o=Je.readFileSync(n.path,"utf-8"),{frontmatter:s}=Jo(o),r=Array.isArray(s.tags)?s.tags:[];e.documents[n.name]={keywords:Cl(o),tags:r,modified:n.modified.toISOString()}}return Ol(e),e}function Qm(){let t=Al(),e=Vo();for(let n of e){let o=t.documents[n.name];if(!o||new Date(o.modified)<n.modified)return Tl()}for(let n of Object.keys(t.documents))if(!e.some(o=>o.name===n))return Tl();return t}function eg(t,e={}){let{topK:n=3,minScore:o=.1}=e,s=Ui(t);if(s.length===0)return[];let r=Qm(),i=[];for(let[a,c]of Object.entries(r.documents)){let u=0;for(let l of s){c.keywords[l]&&(u+=c.keywords[l]);for(let[d,f]of Object.entries(c.keywords))d!==l&&d.length>3&&l.length>3&&(d.includes(l)||l.includes(d))&&(u+=f*.3)}u>=o&&i.push({name:a,score:u})}return i.sort((a,c)=>c.score-a.score),i.slice(0,n)}var tg=process.env.NEX_EMBED_MODEL||"nomic-embed-text",El=400,WS=50;async function ng(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return!1;try{let t=process.env.OLLAMA_HOST||"http://localhost:11434",e=require("http"),n=require("https"),o=new URL(`${t}/api/tags`),s=o.protocol==="https:"?n:e;return((await new Promise((a,c)=>{let u=s.get(o.toString(),{timeout:2e3},l=>{let d="";l.on("data",f=>d+=f),l.on("end",()=>{try{a(JSON.parse(d))}catch{c(new Error("bad json"))}})});u.on("error",c),u.on("timeout",()=>{u.destroy(),c(new Error("timeout"))})})).models||[]).map(a=>a.name).some(a=>a.startsWith(tg.split(":")[0]))}catch{return!1}}async function Nl(t){let e=process.env.OLLAMA_HOST||"http://localhost:11434",n=require("http"),o=require("https"),s=new URL(`${e}/api/embeddings`),r=s.protocol==="https:"?o:n,i=JSON.stringify({model:tg,prompt:t});return new Promise((a,c)=>{let u=r.request(s,{method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(i)},timeout:3e4},l=>{let d="";l.on("data",f=>d+=f),l.on("end",()=>{try{a(JSON.parse(d).embedding||[])}catch(f){c(f)}})});u.on("error",c),u.on("timeout",()=>{u.destroy(),c(new Error("embedding timeout"))}),u.write(i),u.end()})}function sg(t,e){if(!t||!e||t.length!==e.length)return 0;let n=0,o=0,s=0;for(let i=0;i<t.length;i++)n+=t[i]*e[i],o+=t[i]*t[i],s+=e[i]*e[i];let r=Math.sqrt(o)*Math.sqrt(s);return r===0?0:n/r}function og(t){let e=t.split(/\s+/),n=[],o=0;for(;o<e.length;){let s=e.slice(o,o+El).join(" ");if(n.push({text:s,offset:o}),o+El>=e.length)break;o+=El-WS}return n}async function rg(){let t=Vo(),e={documents:{}},n=Rl();if(Je.existsSync(n))try{e=JSON.parse(Je.readFileSync(n,"utf-8"))}catch{}for(let o of t){let s=e.documents[o.name];if(s&&new Date(s.modified)>=o.modified)continue;let r=Je.readFileSync(o.path,"utf-8"),i=og(r),a=[];for(let c of i){let u=await Nl(c.text);a.push({text:c.text,embedding:u,offset:c.offset})}e.documents[o.name]={chunks:a,modified:o.modified.toISOString()}}for(let o of Object.keys(e.documents))t.some(s=>s.name===o)||delete e.documents[o];return Je.writeFileSync(n,JSON.stringify(e),"utf-8"),e}async function ig(t,e={}){let{topK:n=3,minSimilarity:o=.3}=e,s=Rl();if(!Je.existsSync(s))return[];let r;try{r=JSON.parse(Je.readFileSync(s,"utf-8"))}catch{return[]}let i=await Nl(t),a=[];for(let[c,u]of Object.entries(r.documents||{})){let l=0,d="";for(let f of u.chunks||[]){let p=sg(i,f.embedding);p>l&&(l=p,d=f.text)}l>=o&&a.push({name:c,score:l,bestChunk:d})}return a.sort((c,u)=>u.score-c.score),a.slice(0,n)}function ag(t,e,n={}){let{k:o=60,topK:s=3}=n,r={};return t.forEach((i,a)=>{r[i.name]=(r[i.name]||0)+1/(o+a+1)}),e.forEach((i,a)=>{r[i.name]=(r[i.name]||0)+1/(o+a+1)}),Object.entries(r).map(([i,a])=>({name:i,score:a})).sort((i,a)=>a.score-i.score).slice(0,s)}async function cg(t,e={}){let{topK:n=3,minScore:o=.1}=e,s=eg(t,{topK:n,minScore:o}),r=s;if(process.env.NEX_BRAIN_EMBEDDINGS!=="false")try{if(await ng()){let a=await ig(t,{topK:n});r=ag(s,a,{topK:n})}}catch{}return r.map(i=>{let a=Zm(i.name),c=(a.body||a.content||"").slice(0,300).replace(/\n+/g," ")+"...";return{name:i.name,score:i.score,content:a.content,excerpt:c}})}var no={queryKey:null,result:null,ts:0},HS=3e5;async function YS(t){if(!t||!t.trim())return"";let e=Sn.join(process.cwd(),".nex","brain");if(!Je.existsSync(e)||Vo().length===0)return"";let o=t.trim().toLowerCase().slice(0,200);if(no.result!==null&&no.queryKey===o&&Date.now()-no.ts<HS)return no.result;let s;try{s=await cg(t,{topK:3})}catch{return""}if(!s||s.length===0)return"";let r;try{r=fn().estimateTokens}catch{r=l=>Math.ceil(l.length/4)}let i=25e3,a=[],c=0;for(let l of s){let d=l.content||"",f=r(d);if(c+f>i){let h=i-c;if(h<100)break;let g=h/f;d=d.slice(0,Math.floor(d.length*g))+`
264
264
  ...(truncated)`}let p=typeof l.score=="number"?l.score.toFixed(2):String(l.score);if(a.push(`--- ${l.name} (relevance: ${p}) ---
265
265
  ${d}`),c+=r(d),c>=i)break}if(a.length===0)return no={queryKey:o,result:"",ts:Date.now()},"";let u=`KNOWLEDGE BASE (auto-selected):
266
266
 
267
267
  ${a.join(`
268
268
 
269
- `)}`;return no={queryKey:o,result:u,ts:Date.now()},u}cg.exports={getBrainDir:so,listDocuments:Vo,readDocument:Jm,writeDocument:DS,removeDocument:FS,buildIndex:Tl,getIndex:Zm,query:ag,getBrainContext:YS,isEmbeddingAvailable:tg,generateEmbedding:Nl,buildEmbeddingIndex:og,semanticQuery:rg,cosineSimilarity:ng,_keywordQuery:Qm,_extractKeywords:Cl,_chunkText:sg,parseFrontmatter:Jo,tokenize:Ui,_fuseResults:ig}});var er=Q((bO,$g)=>{var Be=require("fs"),Ct=require("path"),GS=require("os"),{atomicWrite:Hi,withFileLockSync:lg}=Jn(),Zo=["user","feedback","project","reference"],zS=50;function us(){return Ct.join(process.cwd(),".nex","memory")}function oo(){return Ct.join(us(),"memory.json")}function ug(){return Ct.join(us(),"MEMORY.md")}function KS(){return Ct.join(process.cwd(),"NEX.md")}function dg(){return Ct.join(GS.homedir(),".nex","NEX.md")}function Yi(){let t=us();Be.existsSync(t)||Be.mkdirSync(t,{recursive:!0})}function fg(t){let e=Ct.join(us(),t);return Be.existsSync(e)||Be.mkdirSync(e,{recursive:!0}),e}function Qo(){let t=oo();if(!Be.existsSync(t))return{};try{return JSON.parse(Be.readFileSync(t,"utf-8"))}catch{return{}}}function pg(t){Yi(),Hi(oo(),JSON.stringify(t,null,2))}function hg(){let t=oo();if(!Be.existsSync(t))return;let e=Qo(),n=Object.keys(e);if(n.length===0){try{Be.renameSync(t,t+".bak")}catch{}return}for(let o of n){let s=e[o],r=s.value||String(s),i=o.replace(/[^a-z0-9_-]/gi,"-").toLowerCase().replace(/-+/g,"-").replace(/^-|-$/g,"");if(!i)continue;let a=fg("project"),c=Ct.join(a,`${i}.md`),u=r.split(`
269
+ `)}`;return no={queryKey:o,result:u,ts:Date.now()},u}lg.exports={getBrainDir:so,listDocuments:Vo,readDocument:Zm,writeDocument:DS,removeDocument:FS,buildIndex:Tl,getIndex:Qm,query:cg,getBrainContext:YS,isEmbeddingAvailable:ng,generateEmbedding:Nl,buildEmbeddingIndex:rg,semanticQuery:ig,cosineSimilarity:sg,_keywordQuery:eg,_extractKeywords:Cl,_chunkText:og,parseFrontmatter:Jo,tokenize:Ui,_fuseResults:ag}});var er=Q(($O,_g)=>{var Be=require("fs"),Ct=require("path"),GS=require("os"),{atomicWrite:Hi,withFileLockSync:ug}=Jn(),Zo=["user","feedback","project","reference"],zS=50;function us(){return Ct.join(process.cwd(),".nex","memory")}function oo(){return Ct.join(us(),"memory.json")}function dg(){return Ct.join(us(),"MEMORY.md")}function KS(){return Ct.join(process.cwd(),"NEX.md")}function fg(){return Ct.join(GS.homedir(),".nex","NEX.md")}function Yi(){let t=us();Be.existsSync(t)||Be.mkdirSync(t,{recursive:!0})}function pg(t){let e=Ct.join(us(),t);return Be.existsSync(e)||Be.mkdirSync(e,{recursive:!0}),e}function Qo(){let t=oo();if(!Be.existsSync(t))return{};try{return JSON.parse(Be.readFileSync(t,"utf-8"))}catch{return{}}}function hg(t){Yi(),Hi(oo(),JSON.stringify(t,null,2))}function mg(){let t=oo();if(!Be.existsSync(t))return;let e=Qo(),n=Object.keys(e);if(n.length===0){try{Be.renameSync(t,t+".bak")}catch{}return}for(let o of n){let s=e[o],r=s.value||String(s),i=o.replace(/[^a-z0-9_-]/gi,"-").toLowerCase().replace(/-+/g,"-").replace(/^-|-$/g,"");if(!i)continue;let a=pg("project"),c=Ct.join(a,`${i}.md`),u=r.split(`
270
270
  `)[0].slice(0,100),l=`---
271
271
  name: ${o}
272
272
  description: ${u}
@@ -274,7 +274,7 @@ type: project
274
274
  ---
275
275
 
276
276
  ${r}
277
- `;Hi(c,l)}Gi();try{Be.renameSync(t,t+".bak")}catch{}}function XS(t,e,n,o){if(!Zo.includes(t))return{ok:!1,path:"",error:`Invalid type: ${t}. Must be one of: ${Zo.join(", ")}`};if(!e||typeof e!="string")return{ok:!1,path:"",error:"name must be a non-empty string"};if(!n||typeof n!="string"||n.trim().length<5)return{ok:!1,path:"",error:"content must be at least 5 characters"};let s=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase().replace(/-+/g,"-").replace(/^-|-$/g,"");if(!s)return{ok:!1,path:"",error:"name produces empty slug after sanitization"};let r=fg(t),i=Ct.join(r,`${s}.md`);if(Be.existsSync(i))try{if(Pl(Be.readFileSync(i,"utf-8")).body.slice(0,200)===n.slice(0,200))return{ok:!0,path:i,updated:!1}}catch{}let a=o||n.split(`
277
+ `;Hi(c,l)}Gi();try{Be.renameSync(t,t+".bak")}catch{}}function XS(t,e,n,o){if(!Zo.includes(t))return{ok:!1,path:"",error:`Invalid type: ${t}. Must be one of: ${Zo.join(", ")}`};if(!e||typeof e!="string")return{ok:!1,path:"",error:"name must be a non-empty string"};if(!n||typeof n!="string"||n.trim().length<5)return{ok:!1,path:"",error:"content must be at least 5 characters"};let s=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase().replace(/-+/g,"-").replace(/^-|-$/g,"");if(!s)return{ok:!1,path:"",error:"name produces empty slug after sanitization"};let r=pg(t),i=Ct.join(r,`${s}.md`);if(Be.existsSync(i))try{if(Pl(Be.readFileSync(i,"utf-8")).body.slice(0,200)===n.slice(0,200))return{ok:!0,path:i,updated:!1}}catch{}let a=o||n.split(`
278
278
  `)[0].slice(0,100),c=`---
279
279
  name: ${e}
280
280
  description: ${a}
@@ -282,11 +282,11 @@ type: ${t}
282
282
  ---
283
283
 
284
284
  ${n}
285
- `;return Hi(i,c),Gi(),{ok:!0,path:i,updated:!0}}function VS(t,e){if(!Zo.includes(t))return!1;let n=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase(),o=Ct.join(us(),t,`${n}.md`);if(!Be.existsSync(o))return!1;try{return Be.unlinkSync(o),Gi(),!0}catch{return!1}}function Pl(t){let e=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(!e)return{name:"",description:"",type:"",body:t.trim()};let n=e[1],o=(e[2]||"").trim(),s=r=>{let i=n.match(new RegExp(`^${r}:\\s*(.+)$`,"m"));return i?i[1].trim():""};return{name:s("name"),description:s("description"),type:s("type"),body:o}}function mg(){let t=[],e=us();for(let n of Zo){let o=Ct.join(e,n);if(!Be.existsSync(o))continue;let s;try{s=Be.readdirSync(o).filter(r=>r.endsWith(".md"))}catch{continue}for(let r of s){let i=Ct.join(o,r);try{let a=Be.readFileSync(i,"utf-8"),c=Pl(a);t.push({type:n,name:c.name||Ct.basename(r,".md"),description:c.description,filePath:i})}catch{}}}return t}function Gi(){let t=mg(),e=["# Project Memory Index",""];for(let n of t){if(e.length>=zS+2)break;let o=`${n.type}/${Ct.basename(n.filePath)}`;e.push(`- [${n.name}](${o}) \u2014 ${n.description||"(no description)"}`)}Yi(),Hi(ug(),e.join(`
285
+ `;return Hi(i,c),Gi(),{ok:!0,path:i,updated:!0}}function VS(t,e){if(!Zo.includes(t))return!1;let n=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase(),o=Ct.join(us(),t,`${n}.md`);if(!Be.existsSync(o))return!1;try{return Be.unlinkSync(o),Gi(),!0}catch{return!1}}function Pl(t){let e=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(!e)return{name:"",description:"",type:"",body:t.trim()};let n=e[1],o=(e[2]||"").trim(),s=r=>{let i=n.match(new RegExp(`^${r}:\\s*(.+)$`,"m"));return i?i[1].trim():""};return{name:s("name"),description:s("description"),type:s("type"),body:o}}function gg(){let t=[],e=us();for(let n of Zo){let o=Ct.join(e,n);if(!Be.existsSync(o))continue;let s;try{s=Be.readdirSync(o).filter(r=>r.endsWith(".md"))}catch{continue}for(let r of s){let i=Ct.join(o,r);try{let a=Be.readFileSync(i,"utf-8"),c=Pl(a);t.push({type:n,name:c.name||Ct.basename(r,".md"),description:c.description,filePath:i})}catch{}}}return t}function Gi(){let t=gg(),e=["# Project Memory Index",""];for(let n of t){if(e.length>=zS+2)break;let o=`${n.type}/${Ct.basename(n.filePath)}`;e.push(`- [${n.name}](${o}) \u2014 ${n.description||"(no description)"}`)}Yi(),Hi(dg(),e.join(`
286
286
  `)+`
287
- `)}function gg(){let t=ug();if(!Be.existsSync(t))return"";try{return Be.readFileSync(t,"utf-8").trim()}catch{return""}}function JS(t,e){Yi(),lg(oo(),()=>{let n=Qo();n[t]={value:e,updatedAt:new Date().toISOString()},pg(n)})}function ZS(t){let e=Qo();return e[t]?e[t].value:null}function QS(t){return Yi(),lg(oo(),()=>{let e=Qo();return t in e?(delete e[t],pg(e),!0):!1})}function yg(){let t=Qo();return Object.entries(t).map(([e,n])=>({key:e,value:n.value,updatedAt:n.updatedAt}))}function wg(){let t=dg();if(!Be.existsSync(t))return"";try{return Be.readFileSync(t,"utf-8").trim()}catch{return""}}function bg(){let t=KS();if(!Be.existsSync(t))return"";try{return Be.readFileSync(t,"utf-8").trim()}catch{return""}}function eE(){hg();let t=[],e=wg();e&&t.push(`GLOBAL INSTRUCTIONS (~/.nex/NEX.md):
288
- ${e}`);let n=bg();n&&t.push(`PROJECT INSTRUCTIONS (NEX.md):
289
- ${n}`);let o="",s=gg();if(s)o=s;else{let d=yg();d.length>0&&(o=`PROJECT MEMORY:
287
+ `)}function yg(){let t=dg();if(!Be.existsSync(t))return"";try{return Be.readFileSync(t,"utf-8").trim()}catch{return""}}function JS(t,e){Yi(),ug(oo(),()=>{let n=Qo();n[t]={value:e,updatedAt:new Date().toISOString()},hg(n)})}function ZS(t){let e=Qo();return e[t]?e[t].value:null}function QS(t){return Yi(),ug(oo(),()=>{let e=Qo();return t in e?(delete e[t],hg(e),!0):!1})}function wg(){let t=Qo();return Object.entries(t).map(([e,n])=>({key:e,value:n.value,updatedAt:n.updatedAt}))}function bg(){let t=fg();if(!Be.existsSync(t))return"";try{return Be.readFileSync(t,"utf-8").trim()}catch{return""}}function $g(){let t=KS();if(!Be.existsSync(t))return"";try{return Be.readFileSync(t,"utf-8").trim()}catch{return""}}function eE(){mg();let t=[],e=bg();e&&t.push(`GLOBAL INSTRUCTIONS (~/.nex/NEX.md):
288
+ ${e}`);let n=$g();n&&t.push(`PROJECT INSTRUCTIONS (NEX.md):
289
+ ${n}`);let o="",s=yg();if(s)o=s;else{let d=wg();d.length>0&&(o=`PROJECT MEMORY:
290
290
  ${d.map(p=>` ${p.key}: ${p.value}`).join(`
291
291
  `)}`)}let r=t.join(`
292
292
 
@@ -295,9 +295,9 @@ ${d.map(p=>` ${p.key}: ${p.value}`).join(`
295
295
  `}o=f.trimEnd()+`
296
296
  [Memory index truncated \u2014 use delete_memory to prune old entries]`}else o.length>u&&(o="");let l=[...t];return o&&l.push(o),l.length>0&&l.push(i),l.join(`
297
297
 
298
- `)}$g.exports={saveMemory:XS,deleteMemory:VS,scanMemories:mg,rebuildIndex:Gi,loadMemoryIndex:gg,remember:JS,recall:ZS,forget:QS,listMemories:yg,loadGlobalInstructions:wg,loadProjectInstructions:bg,getMemoryContext:eE,_getMemoryDir:us,_getMemoryFile:oo,_getGlobalNexMdPath:dg,_parseMemoryFile:Pl,_migrateIfNeeded:hg,VALID_TYPES:Zo}});var Eg=Q(($O,Sg)=>{var tr=require("fs"),Ll=require("path"),Il=process.env.NEX_AUDIT!=="false",ds=null;function _g(){return ds||(ds=Ll.join(process.cwd(),".nex","audit"),tr.existsSync(ds)||tr.mkdirSync(ds,{recursive:!0}),ds)}function xg(){let t=new Date().toISOString().split("T")[0];return Ll.join(_g(),`${t}.jsonl`)}function tE(t){if(Il)try{let e={timestamp:new Date().toISOString(),tool:t.tool,args:kg(t.args),resultLength:typeof t.result=="string"?t.result.length:0,resultPreview:typeof t.result=="string"?t.result.substring(0,200):"",duration:t.duration||0,success:t.success!==!1,model:t.model||null,provider:t.provider||null},n=JSON.stringify(e)+`
299
- `;tr.appendFileSync(xg(),n,"utf-8")}catch{}}function kg(t){if(!t||typeof t!="object")return{};let e={};for(let[n,o]of Object.entries(t))/key|token|password|secret|credential/i.test(n)?e[n]="***":typeof o=="string"&&o.length>500?e[n]=o.substring(0,500)+`... (${o.length} chars)`:e[n]=o;return e}function vg(t={}){let e=_g(),n=t.days||1,o=[];for(let s=0;s<n;s++){let r=t.date||new Date(Date.now()-s*864e5).toISOString().split("T")[0],i=Ll.join(e,`${r}.jsonl`);if(!tr.existsSync(i))continue;let a=tr.readFileSync(i,"utf-8").split(`
300
- `).filter(c=>c.trim());for(let c of a)try{let u=JSON.parse(c);if(t.tool&&u.tool!==t.tool)continue;o.push(u)}catch{}if(t.date)break}return o}function nE(t=1){let e=vg({days:t});if(e.length===0)return{totalCalls:0,byTool:{},avgDuration:0,successRate:1};let n={},o=0,s=0;for(let r of e)n[r.tool]=(n[r.tool]||0)+1,o+=r.duration||0,r.success&&s++;return{totalCalls:e.length,byTool:n,avgDuration:Math.round(o/e.length),successRate:s/e.length}}function sE(t){Il=t}function oE(){return Il}function rE(){ds=null}Sg.exports={logToolExecution:tE,sanitizeArgs:kg,readAuditLog:vg,getAuditSummary:nE,setAuditEnabled:sE,isAuditEnabled:oE,getAuditLogPath:xg,_reset:rE}});var Yg=Q((xO,Hg)=>{var Ze=require("fs").promises,Zt=require("fs"),ae=require("path"),Ye=require("util").promisify(require("child_process").exec),fs=require("util").promisify(require("child_process").execFile),{spawnSync:iE}=require("child_process"),jl=require("axios"),{isForbidden:aE,isSSHForbidden:cE,isDangerous:lE,isCritical:Tg,isBashPathForbidden:uE,confirm:Jt}=No(),{showDiff:zi,showNewFile:dE,showEditDiff:_O,confirmFileChange:nr}=If(),{C:pe,Spinner:fE,getToolSpinnerText:pE}=rt(),{ToolProgress:Ki}=Yn(),{isGitRepo:Dl,getCurrentBranch:Rg,getStatus:hE,getDiff:mE}=di(),{recordChange:Xi}=zf(),{fuzzyFindText:Cg,findMostSimilar:ar}=yp(),{runDiagnostics:sr}=Rp(),{findFileInIndex:gE,getFileIndex:Ag,searchContentIndex:yE,scorePathMatch:Og,refreshIndex:wE,isIndexValid:bE}=cn(),{resolveProfile:qt,sshExec:bt,scpUpload:$E,scpDownload:Ng}=Ks(),{resolveDeployConfig:_E,loadDeployConfigs:xE}=Xp(),{getEditMode:Mg}=Uo(),kE=/^(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/,vE=/^ssh\s/,SE=/^ssh(?:\s+-\S+)*\s+\S+@?\S+\s+["']?[^-]/;async function At(t){return Ze.access(t).then(()=>!0).catch(()=>!1)}var Vi=null,Pg=0,EE=12e4;function TE(){let t=Date.now();if(Vi&&t-Pg<EE)return Vi;let e=ae.dirname(process.cwd());try{let n=Zt.readdirSync(e,{withFileTypes:!0}),o=ae.basename(process.cwd()),s=n.filter(r=>r.isDirectory()&&r.name!==o&&!r.name.startsWith(".")).map(r=>r.name).sort();return Vi=s.length>0?s:null,Pg=t,Vi}catch{return null}}function ql(t){if(t&&ae.resolve(t)!==process.cwd())return"";let e=TE();if(!e)return"";let n=ae.dirname(process.cwd());return`
298
+ `)}_g.exports={saveMemory:XS,deleteMemory:VS,scanMemories:gg,rebuildIndex:Gi,loadMemoryIndex:yg,remember:JS,recall:ZS,forget:QS,listMemories:wg,loadGlobalInstructions:bg,loadProjectInstructions:$g,getMemoryContext:eE,_getMemoryDir:us,_getMemoryFile:oo,_getGlobalNexMdPath:fg,_parseMemoryFile:Pl,_migrateIfNeeded:mg,VALID_TYPES:Zo}});var Tg=Q((_O,Eg)=>{var tr=require("fs"),Ll=require("path"),Il=process.env.NEX_AUDIT!=="false",ds=null;function xg(){return ds||(ds=Ll.join(process.cwd(),".nex","audit"),tr.existsSync(ds)||tr.mkdirSync(ds,{recursive:!0}),ds)}function kg(){let t=new Date().toISOString().split("T")[0];return Ll.join(xg(),`${t}.jsonl`)}function tE(t){if(Il)try{let e={timestamp:new Date().toISOString(),tool:t.tool,args:vg(t.args),resultLength:typeof t.result=="string"?t.result.length:0,resultPreview:typeof t.result=="string"?t.result.substring(0,200):"",duration:t.duration||0,success:t.success!==!1,model:t.model||null,provider:t.provider||null},n=JSON.stringify(e)+`
299
+ `;tr.appendFileSync(kg(),n,"utf-8")}catch{}}function vg(t){if(!t||typeof t!="object")return{};let e={};for(let[n,o]of Object.entries(t))/key|token|password|secret|credential/i.test(n)?e[n]="***":typeof o=="string"&&o.length>500?e[n]=o.substring(0,500)+`... (${o.length} chars)`:e[n]=o;return e}function Sg(t={}){let e=xg(),n=t.days||1,o=[];for(let s=0;s<n;s++){let r=t.date||new Date(Date.now()-s*864e5).toISOString().split("T")[0],i=Ll.join(e,`${r}.jsonl`);if(!tr.existsSync(i))continue;let a=tr.readFileSync(i,"utf-8").split(`
300
+ `).filter(c=>c.trim());for(let c of a)try{let u=JSON.parse(c);if(t.tool&&u.tool!==t.tool)continue;o.push(u)}catch{}if(t.date)break}return o}function nE(t=1){let e=Sg({days:t});if(e.length===0)return{totalCalls:0,byTool:{},avgDuration:0,successRate:1};let n={},o=0,s=0;for(let r of e)n[r.tool]=(n[r.tool]||0)+1,o+=r.duration||0,r.success&&s++;return{totalCalls:e.length,byTool:n,avgDuration:Math.round(o/e.length),successRate:s/e.length}}function sE(t){Il=t}function oE(){return Il}function rE(){ds=null}Eg.exports={logToolExecution:tE,sanitizeArgs:vg,readAuditLog:Sg,getAuditSummary:nE,setAuditEnabled:sE,isAuditEnabled:oE,getAuditLogPath:kg,_reset:rE}});var Gg=Q((kO,Yg)=>{var Ze=require("fs").promises,Zt=require("fs"),ae=require("path"),Ye=require("util").promisify(require("child_process").exec),fs=require("util").promisify(require("child_process").execFile),{spawnSync:iE}=require("child_process"),jl=require("axios"),{isForbidden:aE,isSSHForbidden:cE,isDangerous:lE,isCritical:Rg,isBashPathForbidden:uE,confirm:Jt}=No(),{showDiff:zi,showNewFile:dE,showEditDiff:xO,confirmFileChange:nr}=jf(),{C:pe,Spinner:fE,getToolSpinnerText:pE}=rt(),{ToolProgress:Ki}=Yn(),{isGitRepo:Dl,getCurrentBranch:Cg,getStatus:hE,getDiff:mE}=di(),{recordChange:Xi}=Kf(),{fuzzyFindText:Ag,findMostSimilar:ar}=wp(),{runDiagnostics:sr}=Cp(),{findFileInIndex:gE,getFileIndex:Og,searchContentIndex:yE,scorePathMatch:Ng,refreshIndex:wE,isIndexValid:bE}=cn(),{resolveProfile:qt,sshExec:bt,scpUpload:$E,scpDownload:Mg}=Ks(),{resolveDeployConfig:_E,loadDeployConfigs:xE}=Vp(),{getEditMode:Pg}=Uo(),kE=/^(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/,vE=/^ssh\s/,SE=/^ssh(?:\s+-\S+)*\s+\S+@?\S+\s+["']?[^-]/;async function At(t){return Ze.access(t).then(()=>!0).catch(()=>!1)}var Vi=null,Lg=0,EE=12e4;function TE(){let t=Date.now();if(Vi&&t-Lg<EE)return Vi;let e=ae.dirname(process.cwd());try{let n=Zt.readdirSync(e,{withFileTypes:!0}),o=ae.basename(process.cwd()),s=n.filter(r=>r.isDirectory()&&r.name!==o&&!r.name.startsWith(".")).map(r=>r.name).sort();return Vi=s.length>0?s:null,Lg=t,Vi}catch{return null}}function ql(t){if(t&&ae.resolve(t)!==process.cwd())return"";let e=TE();if(!e)return"";let n=ae.dirname(process.cwd());return`
301
301
  Hint: no matches in current project. Sibling directories in ${n}/:
302
302
  ${e.join(", ")}
303
303
  You can search there with: grep pattern --path ${n}/<dir>`}async function Ji(t){if(!t)return{fixedPath:null,message:""};let e=t.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),n=ut(e);if(n&&await At(n))return{fixedPath:n,message:`(auto-fixed path: ${t} \u2192 ${e})`};let o=[".js",".ts",".jsx",".tsx",".mjs",".cjs",".json"],s=ae.extname(t);if(!s)for(let i of o){let a=ut(t+i);if(a&&await At(a))return{fixedPath:a,message:`(auto-fixed: added ${i} extension)`}}if(s){let i=t.replace(/\.[^.]+$/,"");for(let a of o){if(a===s)continue;let c=ut(i+a);if(c&&await At(c))return{fixedPath:c,message:`(auto-fixed: ${s} \u2192 ${a})`}}}let r=ae.basename(t);if(r&&r.length>2)try{let i=gE(r).map(a=>ut(a));if(i.length===1)return{fixedPath:i[0],message:`(auto-fixed: found ${r} at ${ae.relative(process.cwd(),i[0])})`};if(i.length>1&&i.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
@@ -306,14 +306,14 @@ ${i.map(c=>ae.relative(process.cwd(),c)).map(c=>` - ${c}`).join(`
306
306
  ${c.map(l=>ae.relative(process.cwd(),l)).map(l=>` - ${l}`).join(`
307
307
  `)}`}}catch{}try{let{smartSearch:i}=cn(),a=i(t,{limit:5,minScore:15});if(a.length>0){let c=ut(a[0].file);if(a[0].score>=200||a.length===1&&a[0].score>=50)return{fixedPath:c,message:`(auto-fixed: smart matched ${t} \u2192 ${ae.relative(process.cwd(),c)})`};if(a.length>=2&&a[0].score>=80&&a[0].score>=a[1].score*1.5)return{fixedPath:c,message:`(auto-fixed: best match ${t} \u2192 ${ae.relative(process.cwd(),c)})`};if(a.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
308
308
  ${a.map(l=>ae.relative(process.cwd(),ut(l.file))).map(l=>` - ${l}`).join(`
309
- `)}`}}}catch{}return{fixedPath:null,message:""}}function RE(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 Dg(t){if(!t||typeof t!="string")return null;let e=t.trim();if(!e||/[()[\]{}|^$\\]/.test(e))return null;let n=e.replace(/\*\*/g," ").replace(/[*?]/g," ").replace(/[:=><!]+/g," ").replace(/\s+/g," ").trim();if(!n)return null;let o=n.split(/[\/\s,]+/).map(s=>s.trim()).filter(Boolean).filter(s=>s!=="."&&s!=="..").filter(s=>!/^\.[a-z0-9]+$/i.test(s)).filter(s=>s.length>=3);return o.length===0?null:(o.sort((s,r)=>r.length-s.length),o[0])}async function qg(t,e){let n=Dg(t);if(!n)return new Map;try{let o=await yE(n,void 0,e||process.cwd()),s=new Map;for(let r of o){let a=r.name.toLowerCase()===n.toLowerCase()?140:90;s.set(r.file,(s.get(r.file)||0)+a)}return s}catch{return new Map}}function Lg(t,e){if(!t)return"";let n=e||process.cwd(),o=ae.isAbsolute(t)?t:ae.resolve(n,t),s=ae.relative(n,o);return s&&!s.startsWith("..")&&!ae.isAbsolute(s)?s:ae.relative(process.cwd(),o)}function or(t,e){let n=(t||"").trim();return n?e==="files_with_matches"||e==="count"?n.split(`
309
+ `)}`}}}catch{}return{fixedPath:null,message:""}}function RE(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 qg(t){if(!t||typeof t!="string")return null;let e=t.trim();if(!e||/[()[\]{}|^$\\]/.test(e))return null;let n=e.replace(/\*\*/g," ").replace(/[*?]/g," ").replace(/[:=><!]+/g," ").replace(/\s+/g," ").trim();if(!n)return null;let o=n.split(/[\/\s,]+/).map(s=>s.trim()).filter(Boolean).filter(s=>s!=="."&&s!=="..").filter(s=>!/^\.[a-z0-9]+$/i.test(s)).filter(s=>s.length>=3);return o.length===0?null:(o.sort((s,r)=>r.length-s.length),o[0])}async function Fg(t,e){let n=qg(t);if(!n)return new Map;try{let o=await yE(n,void 0,e||process.cwd()),s=new Map;for(let r of o){let a=r.name.toLowerCase()===n.toLowerCase()?140:90;s.set(r.file,(s.get(r.file)||0)+a)}return s}catch{return new Map}}function Ig(t,e){if(!t)return"";let n=e||process.cwd(),o=ae.isAbsolute(t)?t:ae.resolve(n,t),s=ae.relative(n,o);return s&&!s.startsWith("..")&&!ae.isAbsolute(s)?s:ae.relative(process.cwd(),o)}function or(t,e){let n=(t||"").trim();return n?e==="files_with_matches"||e==="count"?n.split(`
310
310
  `).filter(o=>o.trim()):n.split(`
311
- `).filter(o=>o.trim()):[]}function Fg(t,{query:e,basePath:n,definitionScores:o=new Map,mtimeByPath:s=new Map}={}){let r=Dg(e);return[...t].sort((i,a)=>{let c=Lg(i,n),u=Lg(a,n),l=0,d=0;if(r&&(l+=Og(c,r),d+=Og(u,r)),l+=o.get(c)||0,d+=o.get(u)||0,l!==d)return d-l;let f=s.get(i)||0,p=s.get(a)||0;return f!==p?p-f:c.localeCompare(u)})}async function Fl(t,{query:e,basePath:n,outputMode:o}={}){if(!Array.isArray(t)||t.length<=1)return t;let s=new Map,r=[];for(let u of t){if(!u)continue;let l=u;(o==="count"||o!=="files_with_matches")&&(l=u.split(":")[0]),s.has(l)||(s.set(l,[]),r.push(l)),s.get(l).push(u)}let i=await qg(e,n),a=Fg(r,{query:e,basePath:n,definitionScores:i}),c=[];for(let u of a)c.push(...s.get(u)||[]);return c}function Bg(t,e){let n=[];if(/command not found|: not found|not recognized/i.test(t)){let o=e.match(/^(\S+)/),s=o?o[1]:"";/^(npx|npm|node|yarn|pnpm|bun)$/.test(s)?n.push("HINT: Node.js/npm may not be in PATH. Check your Node.js installation."):/^(python|python3|pip|pip3)$/.test(s)?n.push("HINT: Python may not be installed. Try: brew install python3 (macOS) or apt install python3 (Linux)"):n.push(`HINT: "${s}" is not installed. Try installing it with your package manager.`)}if(/Cannot find module|MODULE_NOT_FOUND/i.test(t)){let o=t.match(/Cannot find module '([^']+)'/),s=o?o[1]:"";s&&!s.startsWith(".")&&!s.startsWith("/")?n.push(`HINT: Missing npm package "${s}". Run: npm install ${s}`):n.push("HINT: Module not found. Check the import path or run npm install.")}if(/permission denied|EACCES/i.test(t)&&n.push("HINT: Permission denied. Check file permissions or try a different approach."),/EADDRINUSE|address already in use/i.test(t)){let o=t.match(/port (\d+)|:(\d+)/),s=o?o[1]||o[2]:"";n.push(`HINT: Port ${s||""} is already in use. Kill the process or use a different port.`)}if(/SyntaxError|Unexpected token/i.test(t)&&n.push("HINT: Syntax error in the code. Check the file at the line number shown above."),/TS\d{4}:/i.test(t)&&n.push("HINT: TypeScript compilation error. Fix the type issue at the indicated line."),/Test Suites:.*failed|Tests:.*failed/i.test(t)&&n.push("HINT: Test failures detected. Read the error output above to identify failing tests."),/fatal: not a git repository/i.test(t)&&n.push("HINT: Not inside a git repository. Run git init or cd to a git project."),/^curl\b/.test(e)){let o=t.match(/curl:\s*\((\d+)\)/),s=o?parseInt(o[1],10):null;s===6||/Could not resolve host/i.test(t)?n.push("HINT: Hostname could not be resolved. Check DNS or use an IP address directly."):s===7||/Failed to connect|Connection refused/i.test(t)?n.push("HINT: Service not running or port wrong. Check if the service is up and the port is correct."):s===22||/HTTP error/i.test(t)?n.push("HINT: HTTP 4xx/5xx response. The endpoint exists but returned an error status."):s===28||/timed out/i.test(t)?n.push("HINT: Request timed out. The host may be unreachable or the service is slow."):(s===35||/SSL.*error/i.test(t))&&n.push("HINT: SSL/TLS handshake failed. Try with --insecure to bypass, or check the certificate.")}if(/remote port forwarding failed/i.test(t)){let o=t.match(/port (\d+)/),s=o?o[1]:"";n.push(`HINT: SSH remote port forwarding failed for port ${s}. The port may already be bound on the server. Check with: ssh server "ss -tuln | grep ${s}" and kill any lingering process with that port.`)}return/bind.*Cannot assign requested address|Address already in use/i.test(t)&&n.push("HINT: Port is already in use. Find the process with: ss -tuln | grep <port> and kill it, then retry."),/Connection.*timed out|ssh.*timeout/i.test(t)&&/^ssh\b/.test(e)&&n.push("HINT: SSH connection timed out. Check if the host is reachable: ping <host> and verify the port with: nc -zv <host> 22"),/spawn \/bin\/sh ENOENT|spawn sh ENOENT/i.test(t)&&n.push("HINT: The working directory was deleted during this session \u2014 bash cannot execute commands in a non-existent cwd. Previous rm/delete commands succeeded. Use list_directory or glob to verify the state instead of retrying bash."),/cp.*\$f.*\$f\.bak.*sed.*-i\.bak|sed.*-i\.bak.*cp.*\$f.*\$f\.bak/i.test(e)&&n.push('HINT: Using both cp with .bak and sed -i.bak creates double backups (.bak.bak). Choose one method: either cp "$f" "$f.bak" OR sed -i.bak, not both.'),n.length===0?t:t+`
311
+ `).filter(o=>o.trim()):[]}function Bg(t,{query:e,basePath:n,definitionScores:o=new Map,mtimeByPath:s=new Map}={}){let r=qg(e);return[...t].sort((i,a)=>{let c=Ig(i,n),u=Ig(a,n),l=0,d=0;if(r&&(l+=Ng(c,r),d+=Ng(u,r)),l+=o.get(c)||0,d+=o.get(u)||0,l!==d)return d-l;let f=s.get(i)||0,p=s.get(a)||0;return f!==p?p-f:c.localeCompare(u)})}async function Fl(t,{query:e,basePath:n,outputMode:o}={}){if(!Array.isArray(t)||t.length<=1)return t;let s=new Map,r=[];for(let u of t){if(!u)continue;let l=u;(o==="count"||o!=="files_with_matches")&&(l=u.split(":")[0]),s.has(l)||(s.set(l,[]),r.push(l)),s.get(l).push(u)}let i=await Fg(e,n),a=Bg(r,{query:e,basePath:n,definitionScores:i}),c=[];for(let u of a)c.push(...s.get(u)||[]);return c}function Ug(t,e){let n=[];if(/command not found|: not found|not recognized/i.test(t)){let o=e.match(/^(\S+)/),s=o?o[1]:"";/^(npx|npm|node|yarn|pnpm|bun)$/.test(s)?n.push("HINT: Node.js/npm may not be in PATH. Check your Node.js installation."):/^(python|python3|pip|pip3)$/.test(s)?n.push("HINT: Python may not be installed. Try: brew install python3 (macOS) or apt install python3 (Linux)"):n.push(`HINT: "${s}" is not installed. Try installing it with your package manager.`)}if(/Cannot find module|MODULE_NOT_FOUND/i.test(t)){let o=t.match(/Cannot find module '([^']+)'/),s=o?o[1]:"";s&&!s.startsWith(".")&&!s.startsWith("/")?n.push(`HINT: Missing npm package "${s}". Run: npm install ${s}`):n.push("HINT: Module not found. Check the import path or run npm install.")}if(/permission denied|EACCES/i.test(t)&&n.push("HINT: Permission denied. Check file permissions or try a different approach."),/EADDRINUSE|address already in use/i.test(t)){let o=t.match(/port (\d+)|:(\d+)/),s=o?o[1]||o[2]:"";n.push(`HINT: Port ${s||""} is already in use. Kill the process or use a different port.`)}if(/SyntaxError|Unexpected token/i.test(t)&&n.push("HINT: Syntax error in the code. Check the file at the line number shown above."),/TS\d{4}:/i.test(t)&&n.push("HINT: TypeScript compilation error. Fix the type issue at the indicated line."),/Test Suites:.*failed|Tests:.*failed/i.test(t)&&n.push("HINT: Test failures detected. Read the error output above to identify failing tests."),/fatal: not a git repository/i.test(t)&&n.push("HINT: Not inside a git repository. Run git init or cd to a git project."),/^curl\b/.test(e)){let o=t.match(/curl:\s*\((\d+)\)/),s=o?parseInt(o[1],10):null;s===6||/Could not resolve host/i.test(t)?n.push("HINT: Hostname could not be resolved. Check DNS or use an IP address directly."):s===7||/Failed to connect|Connection refused/i.test(t)?n.push("HINT: Service not running or port wrong. Check if the service is up and the port is correct."):s===22||/HTTP error/i.test(t)?n.push("HINT: HTTP 4xx/5xx response. The endpoint exists but returned an error status."):s===28||/timed out/i.test(t)?n.push("HINT: Request timed out. The host may be unreachable or the service is slow."):(s===35||/SSL.*error/i.test(t))&&n.push("HINT: SSL/TLS handshake failed. Try with --insecure to bypass, or check the certificate.")}if(/remote port forwarding failed/i.test(t)){let o=t.match(/port (\d+)/),s=o?o[1]:"";n.push(`HINT: SSH remote port forwarding failed for port ${s}. The port may already be bound on the server. Check with: ssh server "ss -tuln | grep ${s}" and kill any lingering process with that port.`)}return/bind.*Cannot assign requested address|Address already in use/i.test(t)&&n.push("HINT: Port is already in use. Find the process with: ss -tuln | grep <port> and kill it, then retry."),/Connection.*timed out|ssh.*timeout/i.test(t)&&/^ssh\b/.test(e)&&n.push("HINT: SSH connection timed out. Check if the host is reachable: ping <host> and verify the port with: nc -zv <host> 22"),/spawn \/bin\/sh ENOENT|spawn sh ENOENT/i.test(t)&&n.push("HINT: The working directory was deleted during this session \u2014 bash cannot execute commands in a non-existent cwd. Previous rm/delete commands succeeded. Use list_directory or glob to verify the state instead of retrying bash."),/cp.*\$f.*\$f\.bak.*sed.*-i\.bak|sed.*-i\.bak.*cp.*\$f.*\$f\.bak/i.test(e)&&n.push('HINT: Using both cp with .bak and sed -i.bak creates double backups (.bak.bak). Choose one method: either cp "$f" "$f.bak" OR sed -i.bak, not both.'),n.length===0?t:t+`
312
312
 
313
313
  `+n.join(`
314
- `)}function Ug(t,e,n){let o=ar(t,e);if(!o)return null;let s=Math.max(2,Math.ceil(e.length*.03));return o.distance>s?null:{autoFixed:!0,matchText:o.text,content:t.split(o.text).join(n),distance:o.distance,line:o.line}}var Ig=!1,ps=null;function CE(){ps&&(ps(),ps=null)}var Hl=null;function AE(t){Hl=t}async function Bl(){if(!Ig){Ig=!0;try{let{stdout:t}=await Ye("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await Ye('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await Ye("git stash pop",{cwd:process.cwd(),timeout:1e4}),await Ye("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var OE=[/\.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 NE(){let t=process.cwd();try{return Zt.realpathSync(t)}catch{return ae.resolve(t)}}function ME(t,e){let n=ae.relative(e,t);return n===""||!n.startsWith("..")&&!ae.isAbsolute(n)}function PE(t){if(Zt.existsSync(t))return Zt.realpathSync(t);let e=ae.dirname(t);for(;e&&e!==ae.dirname(e);){if(Zt.existsSync(e)){let n=Zt.realpathSync(e),o=ae.relative(e,t);return ae.resolve(n,o)}e=ae.dirname(e)}return t}function ut(t){let e=ae.isAbsolute(t)?ae.resolve(t):ae.resolve(process.cwd(),t);for(let o of OE)if(o.test(e))return null;let n=PE(e);return ME(n,NE())?n:null}function Ae(t){return`'${String(t).replace(/'/g,"'\\''")}'`}function Wg(t){return typeof t=="string"&&/^[a-z_][a-z0-9_-]{0,31}\$?$/i.test(t)}function LE(t){return typeof t=="string"&&/^[a-zA-Z0-9@_.:-]+(?:\.service)?$/.test(t)}function IE(t){return typeof t=="string"&&/^[a-zA-Z0-9+_.:@/-]+$/.test(t)}function Ul(t){return typeof t=="string"&&/^\d{1,5}(?:\/(?:tcp|udp))?$/i.test(t)}function jE(t){return typeof t=="string"&&/^(?:SIG[A-Z0-9]+|[A-Z0-9]+|\d{1,2})$/.test(t)}function rr(t,e="user"){return Wg(t)?null:`ERROR: ${e} contains unsafe characters`}function Wl(t,e="service"){return LE(t)?null:`ERROR: ${e} contains unsafe characters`}var DE=[{type:"function",function:{name:"bash",description:`Execute a bash command in the project directory. Timeout: 90s (commands that exceed this are killed). Use for: running tests, installing packages, git commands, build tools, starting servers, compiling code. Example: use bash for "npm install" or "git status", but NOT for "cat config.json" (use read_file instead) or "grep -r 'error' src/" (use grep tool instead). AVOID using bash for: cat/head/tail (use read_file), sed/awk (use edit_file), find/ls (use glob or list_directory), grep/rg (use grep tool). Using dedicated tools is faster and produces better-formatted output. Always quote file paths containing spaces with double quotes. Check the exit code in output \u2014 non-zero means the command failed. For long-running commands (large builds, full test suites), warn the user if they may exceed 90s. Destructive or dangerous commands (rm -rf, git push, npm publish, sudo) require user confirmation.`,parameters:{type:"object",properties:{command:{type:"string",description:"The bash command to execute"}},required:["command"]}}},{type:"function",function:{name:"read_file",description:"Read a file's contents with line numbers. ALWAYS read a file before editing it to ensure exact content matching \u2014 edit_file requires the EXACT text including whitespace and newlines. Example: read_file path=src/app.js line_start=10 line_end=20. Auto-truncates at 350 lines for unbounded reads. For large files (>350 lines), use line_start/line_end to read specific sections. Concrete example: read_file(path='src/app.js', line_start=10, line_end=20) reads lines 10-20 of src/app.js. Prefer this over bash cat/head/tail \u2014 dedicated tools produce better-formatted output. Files are read with UTF-8 encoding. IMPORTANT: If you need more than 350 lines, specify line_start and line_end explicitly \u2014 omitting them will truncate the output.",parameters:{type:"object",properties:{path:{type:"string",description:"File path (relative or absolute)"},line_start:{type:"number",description:"Start line (1-based, optional)"},line_end:{type:"number",description:"End line (1-based, optional)"}},required:["path"]}}},{type:"function",function:{name:"write_file",description:"Create a new file or completely overwrite an existing file. Example: use write_file for creating a new config file like .env.example, but NOT for changing one line in an existing file (use edit_file instead). For targeted changes to existing files, prefer edit_file or patch_file instead \u2014 they only send the diff and are safer. Only use write_file when creating new files or when the entire content needs to be replaced.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},content:{type:"string",description:"Full file content"}},required:["path","content"]}}},{type:"function",function:{name:"edit_file",description:"Replace specific text in a file. ALWAYS call read_file first to get the exact content \u2014 edit_file requires the EXACT text including whitespace, indentation, and newlines. Example: edit_file(path='src/config.js', old_text='debug: false', new_text='debug: true'). IMPORTANT: old_text must match byte-for-byte \u2014 even a single space or newline difference will cause failure. If the edit fails with 'old_text not found', re-read that region with line_start/line_end then retry. For multiple replacements in one file, prefer patch_file (atomic). For new files, use write_file instead.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},old_text:{type:"string",description:"Exact text to find (must match file content precisely)"},new_text:{type:"string",description:"Replacement text"}},required:["path","old_text","new_text"]}}},{type:"function",function:{name:"list_directory",description:"List files and directories in a tree view. Use this to understand project structure. Example: use list_directory to see the overall layout of the src/ directory, but NOT for finding all .js files (use glob instead). For finding specific files by pattern, prefer glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory path"},max_depth:{type:"number",description:"Max depth (default: 2)"},pattern:{type:"string",description:"File filter glob (e.g. '*.js')"}},required:["path"]}}},{type:"function",function:{name:"search_files",description:"Search for a text pattern across files (regex). Returns matching lines with file paths. Example: use search_files for finding all occurrences of 'error' in .js files, but NOT for finding all .js files (use glob instead). For simple content search, grep is equivalent. For finding files by name, use glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory to search"},pattern:{type:"string",description:"Search pattern (regex)"},file_pattern:{type:"string",description:"File filter (e.g. '*.js')"}},required:["path","pattern"]}}},{type:"function",function:{name:"glob",description:"Find files matching a glob pattern by name or extension. Returns paths sorted by modification time. ALWAYS use this to locate files BEFORE reading them \u2014 never guess file paths. Example: glob(pattern='src/**/*.test.js') finds all test files in src directory. DO NOT use for content search (e.g. finding 'error' in files) \u2014 use grep tool instead. Examples: '**/*.test.js' (all test files), 'src/**/*.ts' (all TypeScript in src), 'package.json' (find config). Prefer this over bash find/ls. When you need file contents, glob first to get the exact path, then read_file to read it.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Glob pattern (e.g. '**/*.ts', 'src/**/*.test.js')"},path:{type:"string",description:"Base directory (default: project root)"}},required:["pattern"]}}},{type:"function",function:{name:"grep",description:"Search file CONTENTS with regex \u2014 use this when you need to find text inside files. Example: grep(pattern='callStream') finds files containing the text 'callStream'. Do NOT use glob for this \u2014 glob finds files by NAME pattern, grep searches file CONTENTS. Use output_mode='files_with_matches' for just file paths, output_mode='content' (default) for matching lines. Optionally use include to filter by file type (e.g. '*.js') but OMIT it when first searching \u2014 code may live in .html, .vue, .py or other unexpected file types. Supports context lines, offset pagination, and multiline patterns.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Regex pattern to search for"},path:{type:"string",description:"Directory or file to search (default: project root)"},include:{type:"string",description:"File filter glob (e.g. '*.js', '*.ts')"},ignore_case:{type:"boolean",description:"Case-insensitive search"},output_mode:{type:"string",enum:["content","files_with_matches","count"],description:"Output mode: content (matching lines), files_with_matches (file paths only), count (match counts). Default: content"},context:{type:"number",description:"Lines of context around each match (like grep -C)"},before_context:{type:"number",description:"Lines before each match (like grep -B)"},after_context:{type:"number",description:"Lines after each match (like grep -A)"},head_limit:{type:"number",description:"Limit output to first N results"},offset:{type:"number",description:"Skip first N results"},type:{type:"string",description:"File type filter (e.g. 'js', 'py', 'ts') \u2014 maps to --include='*.ext'"},multiline:{type:"boolean",description:"Enable multiline matching (grep -Pz)"},staged:{type:"boolean",description:"Search only staged content (git diff --cached). Default: false"}},required:["pattern"]}}},{type:"function",function:{name:"patch_file",description:"Apply multiple text replacements to a file atomically. All patches are validated before any are applied \u2014 if one fails, none are written. Example: when changing 3 different variables in the same function, use patch_file with an array of 3 { old_text, new_text } objects instead of 3 separate edit_file calls. This ensures either all changes are applied or none are, preventing partial edits. Like edit_file, all old_text values must match exactly.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},patches:{type:"array",description:"Array of { old_text, new_text } replacements to apply in order",items:{type:"object",properties:{old_text:{type:"string",description:"Text to find"},new_text:{type:"string",description:"Replacement text"}},required:["old_text","new_text"]}}},required:["path","patches"]}}},{type:"function",function:{name:"web_fetch",description:"Fetch content from a URL and return text. HTML tags are stripped. Use for reading documentation, API responses, or web pages. Will not work with authenticated/private URLs.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to fetch"},max_length:{type:"number",description:"Max response length in chars (default: 10000)"}},required:["url"]}}},{type:"function",function:{name:"web_search",description:"Search the web. Uses Perplexity (grounded, AI-summarized) if PERPLEXITY_API_KEY is set, otherwise DuckDuckGo. Returns titles, URLs, and summaries. Use to find documentation, solutions, or current information beyond your knowledge cutoff.",parameters:{type:"object",properties:{query:{type:"string",description:"Search query"},max_results:{type:"number",description:"Max results (default: 5)"}},required:["query"]}}},{type:"function",function:{name:"browser_open",description:"Open a URL in a headless browser and return the page title, text content, and links. More reliable than web_fetch for JavaScript-heavy pages. Requires playwright (npm install playwright && npx playwright install chromium).",parameters:{type:"object",properties:{url:{type:"string",description:"URL to open"},wait_for:{type:"string",enum:["domcontentloaded","networkidle","load"],description:"When to consider page loaded (default: domcontentloaded)"}},required:["url"]}}},{type:"function",function:{name:"browser_screenshot",description:"Take a screenshot of a URL in a headless browser. Returns the screenshot file path. The path can be pasted into the next message for visual analysis. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot"},full_page:{type:"boolean",description:"Capture full page (default: false \u2014 viewport only)"},width:{type:"number",description:"Viewport width in px (default: 1280)"},height:{type:"number",description:"Viewport height in px (default: 800)"}},required:["url"]}}},{type:"function",function:{name:"visual_review",description:"Screenshot a URL, analyze the visual result, and return structured feedback about layout, design, and usability issues. Use this to visually inspect web pages, check CSS changes, or verify UI fixes. Returns the screenshot path + analysis.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot and analyze"},focus:{type:"string",description:"What to focus on: layout, colors, typography, spacing, responsiveness, accessibility, or a custom description (e.g. 'check the navbar alignment')"},width:{type:"number",description:"Viewport width in px (default: 1280)"},height:{type:"number",description:"Viewport height in px (default: 800)"},full_page:{type:"boolean",description:"Capture full scrollable page (default: false)"},compare_with:{type:"string",description:"Path to a previous screenshot to compare against (optional). Enables before/after analysis."}},required:["url"]}}},{type:"function",function:{name:"clipboard_image",description:"Grab the current image from the system clipboard (macOS). Returns the screenshot path for visual analysis. Use when the user says 'clipboard', 'pasteboard', or wants to analyze a copied screenshot.",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"browser_click",description:"Click an element on a web page (by CSS selector or visible text). Returns the new URL after navigation. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of element to click (mutually exclusive with text)"},text:{type:"string",description:"Visible text of element to click (mutually exclusive with selector)"}},required:["url"]}}},{type:"function",function:{name:"browser_fill",description:"Fill a form field on a web page and optionally submit. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of the input field"},value:{type:"string",description:"Value to fill in"},submit:{type:"boolean",description:"Press Enter to submit after filling (default: false)"}},required:["url","selector","value"]}}},{type:"function",function:{name:"visual_diff",description:"Compare two screenshots pixel-by-pixel and compute a visual diff. Returns the percentage of changed pixels and which screen regions (top-left, center, bottom-right, etc.) were affected. Use after making CSS/HTML changes to quantify what changed. Example: take a before screenshot, make changes, take an after screenshot, then visual_diff both paths.",parameters:{type:"object",properties:{before:{type:"string",description:"Path to the 'before' screenshot (PNG)"},after:{type:"string",description:"Path to the 'after' screenshot (PNG)"},threshold:{type:"number",description:"Color distance threshold 0-1 (default: 0.1). Lower = more sensitive."}},required:["before","after"]}}},{type:"function",function:{name:"responsive_sweep",description:"Screenshot a URL at 5 viewport widths (320, 768, 1024, 1440, 1920) and return all screenshots for breakpoint analysis. Quickly identifies responsive layout issues across mobile, tablet, and desktop. Returns images for visual analysis.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot at each viewport"},viewports:{type:"array",items:{type:"object",properties:{width:{type:"number"},label:{type:"string"}}},description:"Custom viewport list (default: 320/768/1024/1440/1920)"},full_page:{type:"boolean",description:"Capture full scrollable page at each viewport (default: false)"}},required:["url"]}}},{type:"function",function:{name:"visual_annotate",description:"Draw annotations (red boxes, arrows, circles) directly on a screenshot to mark problem areas. Returns the annotated image. Use instead of describing locations verbally \u2014 visual markers are unambiguous.",parameters:{type:"object",properties:{image:{type:"string",description:"Path to the screenshot (PNG) to annotate"},annotations:{type:"array",items:{type:"object",properties:{type:{type:"string",description:"box, arrow, or circle"},x:{type:"number",description:"X position (px)"},y:{type:"number",description:"Y position (px)"},width:{type:"number",description:"Width for box (px)"},height:{type:"number",description:"Height for box (px)"},toX:{type:"number",description:"Arrow end X (px)"},toY:{type:"number",description:"Arrow end Y (px)"},radius:{type:"number",description:"Circle radius (px)"},label:{type:"string",description:"Text label for the annotation"},color:{type:"string",description:"Hex color (default: #FF0000)"}},required:["type","x","y"]},description:"List of annotations to draw"}},required:["image","annotations"]}}},{type:"function",function:{name:"visual_watch",description:"Hot-reload visual feedback loop: watches source files for changes, waits for HMR to settle, takes a new screenshot, diffs it against the previous one, and reports what changed. Runs up to N iterations (default: 10). Requires a running dev server (Vite, Next, etc.) and chokidar. Use for autonomous visual polish loops.",parameters:{type:"object",properties:{url:{type:"string",description:"Dev server URL to screenshot (e.g. http://localhost:5173)"},watch:{type:"array",items:{type:"string"},description:"File paths or directories to watch for changes (e.g. ['src/components', 'src/styles'])"},max_iterations:{type:"number",description:"Max number of change\u2192screenshot\u2192diff cycles (default: 10)"},hmr_delay:{type:"number",description:"Milliseconds to wait after file change for HMR to settle (default: 1500)"}},required:["url","watch"]}}},{type:"function",function:{name:"design_tokens",description:"Extract design tokens from a screenshot: dominant colors (with hex/rgb/frequency/category), detected vertical spacing values, and image dimensions. Use to audit visual consistency, compare against a design system, or reverse-engineer CSS variables from a rendered page.",parameters:{type:"object",properties:{image:{type:"string",description:"Path to screenshot (PNG) to analyze"},sample_rate:{type:"number",description:"Pixel sampling interval \u2014 lower = more accurate but slower (default: 4)"}},required:["image"]}}},{type:"function",function:{name:"design_compare",description:"Compare a live web page against a reference design (Figma export, mockup PNG). Screenshots the URL at the reference image's dimensions, computes pixel-level diff, and returns annotated images highlighting deviations. Use to verify implementation matches the design spec.",parameters:{type:"object",properties:{url:{type:"string",description:"Live URL to compare against the reference"},reference:{type:"string",description:"Path to reference design image (PNG)"},width:{type:"number",description:"Override viewport width (default: match reference image width)"},height:{type:"number",description:"Override viewport height (default: 800)"},threshold:{type:"number",description:"Color distance threshold 0-1 (default: 0.1)"}},required:["url","reference"]}}},{type:"function",function:{name:"ask_user",description:"Ask the user a clarifying question with 2-3 specific options. Use when the user's intent is ambiguous. Always provide concrete, actionable options. The user can select an option or type a custom answer.",parameters:{type:"object",properties:{question:{type:"string",description:"The clarifying question to ask"},options:{type:"array",items:{type:"string"},description:"2-3 specific, actionable answer options for the user to choose from",minItems:1,maxItems:3}},required:["question","options"]}}},{type:"function",function:{name:"git_status",description:"Get git status: current branch, changed files, staged/unstaged state. Use before git operations to understand the current state.",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"git_diff",description:"Get git diff for changed files. Shows additions and deletions.",parameters:{type:"object",properties:{staged:{type:"boolean",description:"Show only staged changes (default: false)"},file:{type:"string",description:"Diff specific file only (optional)"}},required:[]}}},{type:"function",function:{name:"git_log",description:"Show recent git commits (short format).",parameters:{type:"object",properties:{count:{type:"number",description:"Number of commits to show (default: 10)"},file:{type:"string",description:"Show commits for specific file (optional)"}},required:[]}}},{type:"function",function:{name:"task_list",description:"Create and manage a task list for complex multi-step tasks. Use for tasks with 3+ steps to track progress. Actions: create (new list with tasks), update (mark task in_progress/done/failed), get (view current list). Always update task status as you work.",parameters:{type:"object",properties:{action:{type:"string",enum:["create","update","get"],description:"Action to perform"},name:{type:"string",description:"Task list name (for create)"},tasks:{type:"array",description:"Array of tasks to create (for create)",items:{type:"object",properties:{description:{type:"string",description:"Task description"},depends_on:{type:"array",items:{type:"string"},description:"IDs of prerequisite tasks"}},required:["description"]}},task_id:{type:"string",description:"Task ID to update (for update)"},status:{type:"string",enum:["in_progress","done","failed"],description:"New status (for update)"},result:{type:"string",description:"Result summary (for update, optional)"}},required:["action"]}}},{type:"function",function:{name:"gh_run_list",description:"List recent GitHub Actions workflow runs for this repository. Shows run status, conclusion, branch, and timing. Use to check CI/CD status or find a run ID.",parameters:{type:"object",properties:{limit:{type:"number",description:"Number of runs to show (default: 10, max: 30)"},workflow:{type:"string",description:"Filter by workflow name or filename (optional)"},branch:{type:"string",description:"Filter by branch name (optional)"},status:{type:"string",enum:["completed","in_progress","queued","failure","success"],description:"Filter by status (optional)"}},required:[]}}},{type:"function",function:{name:"gh_run_view",description:"View details of a specific GitHub Actions workflow run: steps, logs, errors. Use gh_run_list first to get the run ID.",parameters:{type:"object",properties:{run_id:{type:"string",description:"The run ID (from gh_run_list)"},log:{type:"boolean",description:"Include full log output (default: false \u2014 shows step summary only)"}},required:["run_id"]}}},{type:"function",function:{name:"gh_workflow_trigger",description:"Trigger a GitHub Actions workflow dispatch event. Only works for workflows with workflow_dispatch trigger. Requires user confirmation.",parameters:{type:"object",properties:{workflow:{type:"string",description:"Workflow filename (e.g. ci.yml) or name"},branch:{type:"string",description:"Branch to run on (default: current branch)"},inputs:{type:"object",description:"Workflow input parameters as key-value pairs (optional)"}},required:["workflow"]}}},{type:"function",function:{name:"spawn_agents",description:"Run multiple independent sub-agents in parallel (max 5 at top level, max 2 when called from within a sub-agent). Each agent has its own conversation context. Use when 2+ tasks can run simultaneously \u2014 e.g. reading multiple files, analyzing separate modules, independent research. Do NOT use for tasks that depend on each other or modify the same file. Keep task descriptions specific and self-contained. SWARM PATTERN: Sub-agents can call spawn_agents once (max nesting depth 2) to enable Architect\u2192Coder\u2192Reviewer pipelines: a coder agent spawns 1-2 reviewer agents that validate and fix its own output before returning results to the parent.",parameters:{type:"object",properties:{agents:{type:"array",description:"Array of agent definitions to run in parallel (max 5)",items:{type:"object",properties:{task:{type:"string",description:"Task description for the agent"},context:{type:"string",description:"Additional context (optional)"},max_iterations:{type:"number",description:"Max iterations (default: 10, max: 15)"},model:{type:"string",description:'Override model for this agent (provider:model, e.g. "anthropic:claude-haiku"). Auto-selected if omitted.'},background:{type:"boolean",description:"Run this agent non-blocking in the background. The main session continues immediately; results are injected as [BACKGROUND AGENT COMPLETED] user messages when the agent finishes. Use for tasks that can run in parallel to your main work."}},required:["task"]}}},required:["agents"]}}},{type:"function",function:{name:"switch_model",description:"Switch the active AI model mid-conversation. Use when a different model is better for the next steps \u2014 e.g. switch to a fast model for simple lookups, or a more capable model for complex refactoring. The switch persists for all subsequent turns.",parameters:{type:"object",properties:{model:{type:"string",description:'Model spec: "provider:model" (e.g. "ollama:devstral-small-2:24b") or just model name'}},required:["model"]}}},{type:"function",function:{name:"k8s_pods",description:"List Kubernetes pods. Shows pod name, status, restarts, and age. Runs kubectl locally or via SSH on a remote server. Use namespace to filter, or omit for all namespaces.",parameters:{type:"object",properties:{namespace:{type:"string",description:"Namespace to list pods in (default: all namespaces)"},label:{type:"string",description:'Label selector filter (e.g. "app=nginx")'},context:{type:"string",description:"kubectl context to use (optional)"},server:{type:"string",description:"Remote server as user@host to run kubectl via SSH (optional, local kubectl if omitted)"}},required:[]}}},{type:"function",function:{name:"k8s_logs",description:'Fetch logs from a Kubernetes pod. Use tail to limit output, since for time-based filtering (e.g. "1h", "30m").',parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (required if pod has multiple containers)"},tail:{type:"number",description:"Number of recent lines to show (default: 100)"},since:{type:"string",description:'Show logs since duration (e.g. "1h", "30m", "5s")'},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod"]}}},{type:"function",function:{name:"k8s_exec",description:"Execute a command inside a running Kubernetes pod (kubectl exec). Requires user confirmation. Use for inspecting container state, reading configs, or debugging.",parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},command:{type:"string",description:'Command to run in the pod (e.g. "env", "ls /app", "cat /etc/config.yaml")'},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (optional)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod","command"]}}},{type:"function",function:{name:"k8s_apply",description:"Apply a Kubernetes manifest file (kubectl apply -f). Requires confirmation before applying to the cluster. Use dry_run=true to validate without applying.",parameters:{type:"object",properties:{file:{type:"string",description:"Path to manifest YAML file (relative or absolute)"},namespace:{type:"string",description:"Override namespace (optional)"},dry_run:{type:"boolean",description:"Validate only without applying (default: false)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["file"]}}},{type:"function",function:{name:"k8s_rollout",description:"Manage Kubernetes deployment rollouts: check status, restart (rolling update), view history, or undo (rollback). Restart and undo require confirmation.",parameters:{type:"object",properties:{action:{type:"string",enum:["status","restart","history","undo"],description:"Action: status (check rollout progress), restart (rolling restart), history (show revision history), undo (rollback to previous revision)"},deployment:{type:"string",description:"Deployment name"},namespace:{type:"string",description:"Namespace (default: default)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["action","deployment"]}}},{type:"function",function:{name:"brain_write",description:"Write or update a knowledge document in the project brain (.nex/brain/). Use this to persist important findings, architecture decisions, debugging insights, or conventions discovered during the session. The user can review changes via /brain review or git diff.",parameters:{type:"object",properties:{name:{type:"string",description:'Document name (without .md extension). Use kebab-case. Examples: "api-auth-flow", "db-schema-notes", "deployment-checklist"'},content:{type:"string",description:"Full Markdown content. Use headings (#), lists (-), and code blocks. Include optional YAML frontmatter with tags."},mode:{type:"string",enum:["create","update","append"],description:"create: new document (fails if exists). update: overwrite existing. append: add to end of existing document."}},required:["name","content","mode"]}}},{type:"function",function:{name:"ssh_exec",description:'Execute a command on a remote server via SSH. Server is a profile name from .nex/servers.json (e.g. "prod") or "user@host". Use for: checking status, reading logs, running deployments. Destructive commands (restart, delete, modify config) require confirmation. For service management prefer service_manage; for logs prefer service_logs.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name (from .nex/servers.json) or "user@host"'},command:{type:"string",description:"Shell command to run on the remote server"},sudo:{type:"boolean",description:"Run command with sudo (only if profile has sudo:true). Default: false"},timeout:{type:"number",description:"Timeout in seconds. Default: 30"}},required:["server","command"]}}},{type:"function",function:{name:"ssh_upload",description:"Upload a local file or directory to a remote server via SCP. Recursive for directories. Requires confirmation before upload.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},local_path:{type:"string",description:"Local path to upload (file or directory)"},remote_path:{type:"string",description:"Destination path on the remote server (absolute preferred)"}},required:["server","local_path","remote_path"]}}},{type:"function",function:{name:"ssh_download",description:"Download a file or directory from a remote server via SCP. Recursive for directories.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},remote_path:{type:"string",description:"Path on the remote server to download"},local_path:{type:"string",description:"Local destination path"}},required:["server","remote_path","local_path"]}}},{type:"function",function:{name:"remote_agent",description:'Delegate a coding task to nex-code running on a remote server. Use this when the task involves server-side projects (musikschule, stadtkapelle, cahill, schoensgibl) that live on almalinux9. Runs nex-code --auto on the server and streams output. Server is a profile name from .nex/servers.json or "user@host".',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name from .nex/servers.json (e.g. "almalinux9") or "user@host"'},task:{type:"string",description:"The full task description to run on the remote nex-code"},project_path:{type:"string",description:"Working directory on the remote server (e.g. /home/deploy/app). Defaults to home directory."},model:{type:"string",description:"Model to use on remote nex-code (e.g. qwen3-coder:480b). Defaults to server default."}},required:["server","task"]}}},{type:"function",function:{name:"service_manage",description:"Manage a systemd service on a remote (or local) server. Uses systemctl. Status is read-only; start/stop/restart/reload/enable/disable require confirmation. For AlmaLinux 9: runs via SSH with sudo if configured.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn", "postgresql")'},action:{type:"string",enum:["status","start","stop","restart","reload","enable","disable"],description:"systemctl action to perform"}},required:["service","action"]}}},{type:"function",function:{name:"service_logs",description:"Fetch systemd service logs via journalctl. Works on AlmaLinux 9 and any systemd Linux. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn")'},lines:{type:"number",description:"Number of recent log lines to fetch. Default: 50"},since:{type:"string",description:'Time filter, e.g. "1 hour ago", "today", "2024-01-01 12:00". Optional.'},follow:{type:"boolean",description:"Tail logs in real-time (follow mode). Default: false"}},required:["service"]}}},{type:"function",function:{name:"container_list",description:"List Docker containers on a server (or locally). Shows container ID, name, image, status, and ports. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},all:{type:"boolean",description:"Show all containers including stopped ones. Default: false (running only)."}},required:[]}}},{type:"function",function:{name:"container_logs",description:"Fetch logs from a Docker container on a server (or locally). Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},lines:{type:"number",description:"Number of recent log lines. Default: 50."},since:{type:"string",description:'Time filter, e.g. "1h", "30m", "2024-01-01T12:00:00". Optional.'}},required:["container"]}}},{type:"function",function:{name:"container_exec",description:"Execute a command inside a running Docker container. Destructive or state-changing commands require confirmation.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},command:{type:"string",description:'Command to run inside the container (e.g. "cat /etc/nginx/nginx.conf").'}},required:["container","command"]}}},{type:"function",function:{name:"container_manage",description:'Start, stop, restart, or remove a Docker container. All actions except "inspect" require confirmation.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},action:{type:"string",enum:["start","stop","restart","remove","inspect"],description:"Action to perform on the container."}},required:["container","action"]}}},{type:"function",function:{name:"frontend_recon",description:"MANDATORY first step before creating or significantly modifying any frontend file (HTML template, Vue/React component, CSS). Scans the project and returns: (1) design tokens \u2014 CSS variables, Tailwind theme colors/fonts, (2) main layout/index page structure, (3) a reference component of the same type, (4) detected JS/CSS framework stack. Call this BEFORE writing any markup or styles. Never skip it for frontend tasks.",parameters:{type:"object",properties:{type:{type:"string",description:'Type of frontend file you are about to create. Used to find a relevant reference component. Examples: "list", "form", "detail", "dashboard", "modal", "component". Optional but improves reference quality.'}},required:[]}}},{type:"function",function:{name:"deploy",description:'Deploy to a remote server. Supports two methods: "rsync" (sync local files) and "git" (git pull on remote). Can use a named config from .nex/deploy.json. Requires confirmation before executing.',parameters:{type:"object",properties:{config:{type:"string",description:'Named deploy config from .nex/deploy.json (e.g. "prod"). Overrides all other params if provided.'},method:{type:"string",enum:["rsync","git"],description:'Deploy method: "rsync" syncs local files (default), "git" runs git pull on the remote.'},server:{type:"string",description:'Profile name or "user@host". Required if no config.'},remote_path:{type:"string",description:"Remote project directory. Required for git method; destination path for rsync."},local_path:{type:"string",description:"Local directory or file to sync. Required for rsync method."},branch:{type:"string",description:"Branch to pull (git method only). Defaults to current remote branch."},deploy_script:{type:"string",description:'Shell command(s) to run on the remote after sync/pull (e.g. "npm ci && systemctl restart myapp"). Optional.'},health_check:{type:"string",description:"URL (HTTP GET) or shell command to verify the service is healthy after deploy. If it fails, the deploy is marked as failed. Optional."},exclude:{type:"array",items:{type:"string"},description:"Paths to exclude from rsync. Optional."},dry_run:{type:"boolean",description:"Show what would happen without executing. Default: false."}},required:[]}}},{type:"function",function:{name:"deployment_status",description:"Check deployment status across all configured servers. Reads .nex/deploy.json configs and checks service health on each server. Returns a status summary table.",parameters:{type:"object",properties:{config:{type:"string",description:"Specific deploy config name to check (optional \u2014 checks all if omitted)"}},required:[]}}},{type:"function",function:{name:"sysadmin",description:"Senior sysadmin operations on a remote (or local) Linux server. Covers: system audit, disk_usage, process_list, network_status, package management (dnf/apt), user management, firewall (firewalld/ufw/iptables), cron, SSL cert checks, log tailing, large file discovery, systemd service management, process kill, journalctl log querying. Read-only actions run without confirmation; state-changing actions require user approval.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},action:{type:"string",enum:["audit","disk_usage","process_list","network_status","package","user_manage","firewall","cron","ssl_check","log_tail","find_large","service","kill_process","journalctl"],description:"Sysadmin operation. audit=full health overview; disk_usage=df+du; process_list=top procs; network_status=open ports; package=dnf/apt (package_action: check|list|install|remove|update|upgrade); user_manage=users/keys; firewall=rules; cron=crontab; ssl_check=cert expiry+days; log_tail=tail any log; find_large=big files; service=systemd unit management; kill_process=kill by PID or name; journalctl=query system journal."},path:{type:"string",description:"File or directory path. For disk_usage (default /), log_tail (required), find_large (default /)."},lines:{type:"number",description:"Lines to tail for log_tail or journalctl. Default: 100."},limit:{type:"number",description:"Result count for process_list (default 20) or find_large (default 20)."},sort_by:{type:"string",enum:["cpu","mem"],description:"Sort order for process_list. Default: cpu."},min_size:{type:"string",description:'Minimum file size for find_large. Default: "100M". Examples: "50M", "1G".'},package_action:{type:"string",enum:["install","remove","update","list","upgrade"],description:"Package sub-action for action=package."},packages:{type:"array",items:{type:"string"},description:"Package name(s) for install/remove/update."},user_action:{type:"string",enum:["list","create","delete","add_ssh_key","info"],description:"User sub-action for action=user_manage."},user:{type:"string",description:"Linux username for user_manage or cron."},groups:{type:"array",items:{type:"string"},description:'Groups to assign on user create (e.g. ["sudo", "docker"]).'},ssh_key:{type:"string",description:"SSH public key string to add for user_action=add_ssh_key."},firewall_action:{type:"string",enum:["status","allow","deny","remove","reload"],description:"Firewall sub-action for action=firewall."},port:{type:"string",description:'Port/protocol for firewall rules, e.g. "80/tcp", "443", "8080/udp".'},cron_action:{type:"string",enum:["list","add","remove"],description:"Cron sub-action for action=cron."},schedule:{type:"string",description:'Cron schedule expression for cron add, e.g. "0 2 * * *".'},command:{type:"string",description:"Command for cron add, or substring to match for cron remove."},domain:{type:"string",description:`Domain for ssl_check (e.g. "example.com"). Auto-detects Let's Encrypt cert on server; falls back to live TLS probe.`},cert_path:{type:"string",description:'Explicit path to cert file on server for ssl_check (e.g. "/etc/letsencrypt/live/x/cert.pem").'},service_name:{type:"string",description:'Systemd unit name for action=service (e.g. "nginx", "my-api", "gunicorn"). .service suffix optional.'},service_action:{type:"string",enum:["status","start","stop","restart","reload","enable","disable","list_failed"],description:"Sub-action for action=service. list_failed shows all failed units."},pid:{type:"number",description:"Process ID to kill for action=kill_process."},process_name:{type:"string",description:"Process name to kill (uses pkill) for action=kill_process. Use with pid for safety."},signal:{type:"string",enum:["SIGTERM","SIGKILL","SIGHUP","SIGINT"],description:"Signal for kill_process. Default: SIGTERM."},unit:{type:"string",description:'Systemd unit to filter for journalctl (e.g. "nginx", "my-api"). Omit for system-wide.'},since:{type:"string",description:'Time filter for journalctl, e.g. "1 hour ago", "today", "2026-03-17 10:00". Default: last 200 lines.'},priority:{type:"string",enum:["emerg","alert","crit","err","warning","notice","info","debug"],description:"Minimum log priority for journalctl. Default: no filter."}},required:["action"]}}},{type:"function",function:{name:"save_memory",description:"Save a typed memory for cross-session persistence. Use this to remember user preferences, feedback, project context, or external references.",parameters:{type:"object",properties:{type:{type:"string",enum:["user","feedback","project","reference"],description:"Memory type: user (role/prefs), feedback (approach guidance), project (ongoing work), reference (external pointers)"},name:{type:"string",description:"Short slug identifier for this memory (e.g. 'testing-preference', 'deploy-workflow')"},content:{type:"string",description:"Markdown content of the memory"},description:{type:"string",description:"One-line description for the memory index (optional, defaults to first line of content)"}},required:["type","name","content"]}}},{type:"function",function:{name:"delete_memory",description:"Delete a typed memory entry. Use this to prune outdated or incorrect memories.",parameters:{type:"object",properties:{type:{type:"string",enum:["user","feedback","project","reference"],description:"Memory type to delete from"},name:{type:"string",description:"Slug identifier of the memory to delete"}},required:["type","name"]}}}];function ir(t,{server:e,context:n}={}){let o=e?e.replace(/[^a-zA-Z0-9@._-]/g,""):null,s=n?n.replace(/[^a-zA-Z0-9._/-]/g,""):null,r="kubectl";if(s&&(r+=` --context ${s}`),r+=` ${t}`,o){let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`ssh -o ConnectTimeout=10 -o BatchMode=yes ${o} "${i}"`}return r}async function jg(t,e,n={}){switch(t){case"bash":{let o=e.command,s=aE(o);if(s){let d=RE(o);return`BLOCKED: Command matches forbidden pattern: ${s}${d?`
314
+ `)}function Wg(t,e,n){let o=ar(t,e);if(!o)return null;let s=Math.max(2,Math.ceil(e.length*.03));return o.distance>s?null:{autoFixed:!0,matchText:o.text,content:t.split(o.text).join(n),distance:o.distance,line:o.line}}var jg=!1,ps=null;function CE(){ps&&(ps(),ps=null)}var Hl=null;function AE(t){Hl=t}async function Bl(){if(!jg){jg=!0;try{let{stdout:t}=await Ye("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await Ye('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await Ye("git stash pop",{cwd:process.cwd(),timeout:1e4}),await Ye("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var OE=[/\.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 NE(){let t=process.cwd();try{return Zt.realpathSync(t)}catch{return ae.resolve(t)}}function ME(t,e){let n=ae.relative(e,t);return n===""||!n.startsWith("..")&&!ae.isAbsolute(n)}function PE(t){if(Zt.existsSync(t))return Zt.realpathSync(t);let e=ae.dirname(t);for(;e&&e!==ae.dirname(e);){if(Zt.existsSync(e)){let n=Zt.realpathSync(e),o=ae.relative(e,t);return ae.resolve(n,o)}e=ae.dirname(e)}return t}function ut(t){let e=ae.isAbsolute(t)?ae.resolve(t):ae.resolve(process.cwd(),t);for(let o of OE)if(o.test(e))return null;let n=PE(e);return ME(n,NE())?n:null}function Ae(t){return`'${String(t).replace(/'/g,"'\\''")}'`}function Hg(t){return typeof t=="string"&&/^[a-z_][a-z0-9_-]{0,31}\$?$/i.test(t)}function LE(t){return typeof t=="string"&&/^[a-zA-Z0-9@_.:-]+(?:\.service)?$/.test(t)}function IE(t){return typeof t=="string"&&/^[a-zA-Z0-9+_.:@/-]+$/.test(t)}function Ul(t){return typeof t=="string"&&/^\d{1,5}(?:\/(?:tcp|udp))?$/i.test(t)}function jE(t){return typeof t=="string"&&/^(?:SIG[A-Z0-9]+|[A-Z0-9]+|\d{1,2})$/.test(t)}function rr(t,e="user"){return Hg(t)?null:`ERROR: ${e} contains unsafe characters`}function Wl(t,e="service"){return LE(t)?null:`ERROR: ${e} contains unsafe characters`}var DE=[{type:"function",function:{name:"bash",description:`Execute a bash command in the project directory. Timeout: 90s (commands that exceed this are killed). Use for: running tests, installing packages, git commands, build tools, starting servers, compiling code. Example: use bash for "npm install" or "git status", but NOT for "cat config.json" (use read_file instead) or "grep -r 'error' src/" (use grep tool instead). AVOID using bash for: cat/head/tail (use read_file), sed/awk (use edit_file), find/ls (use glob or list_directory), grep/rg (use grep tool). Using dedicated tools is faster and produces better-formatted output. Always quote file paths containing spaces with double quotes. Check the exit code in output \u2014 non-zero means the command failed. For long-running commands (large builds, full test suites), warn the user if they may exceed 90s. Destructive or dangerous commands (rm -rf, git push, npm publish, sudo) require user confirmation.`,parameters:{type:"object",properties:{command:{type:"string",description:"The bash command to execute"}},required:["command"]}}},{type:"function",function:{name:"read_file",description:"Read a file's contents with line numbers. ALWAYS read a file before editing it to ensure exact content matching \u2014 edit_file requires the EXACT text including whitespace and newlines. Example: read_file path=src/app.js line_start=10 line_end=20. Auto-truncates at 350 lines for unbounded reads. For large files (>350 lines), use line_start/line_end to read specific sections. Concrete example: read_file(path='src/app.js', line_start=10, line_end=20) reads lines 10-20 of src/app.js. Prefer this over bash cat/head/tail \u2014 dedicated tools produce better-formatted output. Files are read with UTF-8 encoding. IMPORTANT: If you need more than 350 lines, specify line_start and line_end explicitly \u2014 omitting them will truncate the output.",parameters:{type:"object",properties:{path:{type:"string",description:"File path (relative or absolute)"},line_start:{type:"number",description:"Start line (1-based, optional)"},line_end:{type:"number",description:"End line (1-based, optional)"}},required:["path"]}}},{type:"function",function:{name:"write_file",description:"Create a new file or completely overwrite an existing file. Example: use write_file for creating a new config file like .env.example, but NOT for changing one line in an existing file (use edit_file instead). For targeted changes to existing files, prefer edit_file or patch_file instead \u2014 they only send the diff and are safer. Only use write_file when creating new files or when the entire content needs to be replaced.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},content:{type:"string",description:"Full file content"}},required:["path","content"]}}},{type:"function",function:{name:"edit_file",description:"Replace specific text in a file. ALWAYS call read_file first to get the exact content \u2014 edit_file requires the EXACT text including whitespace, indentation, and newlines. Example: edit_file(path='src/config.js', old_text='debug: false', new_text='debug: true'). IMPORTANT: old_text must match byte-for-byte \u2014 even a single space or newline difference will cause failure. If the edit fails with 'old_text not found', re-read that region with line_start/line_end then retry. For multiple replacements in one file, prefer patch_file (atomic). For new files, use write_file instead.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},old_text:{type:"string",description:"Exact text to find (must match file content precisely)"},new_text:{type:"string",description:"Replacement text"}},required:["path","old_text","new_text"]}}},{type:"function",function:{name:"list_directory",description:"List files and directories in a tree view. Use this to understand project structure. Example: use list_directory to see the overall layout of the src/ directory, but NOT for finding all .js files (use glob instead). For finding specific files by pattern, prefer glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory path"},max_depth:{type:"number",description:"Max depth (default: 2)"},pattern:{type:"string",description:"File filter glob (e.g. '*.js')"}},required:["path"]}}},{type:"function",function:{name:"search_files",description:"Search for a text pattern across files (regex). Returns matching lines with file paths. Example: use search_files for finding all occurrences of 'error' in .js files, but NOT for finding all .js files (use glob instead). For simple content search, grep is equivalent. For finding files by name, use glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory to search"},pattern:{type:"string",description:"Search pattern (regex)"},file_pattern:{type:"string",description:"File filter (e.g. '*.js')"}},required:["path","pattern"]}}},{type:"function",function:{name:"glob",description:"Find files matching a glob pattern by name or extension. Returns paths sorted by modification time. ALWAYS use this to locate files BEFORE reading them \u2014 never guess file paths. Example: glob(pattern='src/**/*.test.js') finds all test files in src directory. DO NOT use for content search (e.g. finding 'error' in files) \u2014 use grep tool instead. Examples: '**/*.test.js' (all test files), 'src/**/*.ts' (all TypeScript in src), 'package.json' (find config). Prefer this over bash find/ls. When you need file contents, glob first to get the exact path, then read_file to read it.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Glob pattern (e.g. '**/*.ts', 'src/**/*.test.js')"},path:{type:"string",description:"Base directory (default: project root)"}},required:["pattern"]}}},{type:"function",function:{name:"grep",description:"Search file CONTENTS with regex \u2014 use this when you need to find text inside files. Example: grep(pattern='callStream') finds files containing the text 'callStream'. Do NOT use glob for this \u2014 glob finds files by NAME pattern, grep searches file CONTENTS. Use output_mode='files_with_matches' for just file paths, output_mode='content' (default) for matching lines. Optionally use include to filter by file type (e.g. '*.js') but OMIT it when first searching \u2014 code may live in .html, .vue, .py or other unexpected file types. Supports context lines, offset pagination, and multiline patterns.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Regex pattern to search for"},path:{type:"string",description:"Directory or file to search (default: project root)"},include:{type:"string",description:"File filter glob (e.g. '*.js', '*.ts')"},ignore_case:{type:"boolean",description:"Case-insensitive search"},output_mode:{type:"string",enum:["content","files_with_matches","count"],description:"Output mode: content (matching lines), files_with_matches (file paths only), count (match counts). Default: content"},context:{type:"number",description:"Lines of context around each match (like grep -C)"},before_context:{type:"number",description:"Lines before each match (like grep -B)"},after_context:{type:"number",description:"Lines after each match (like grep -A)"},head_limit:{type:"number",description:"Limit output to first N results"},offset:{type:"number",description:"Skip first N results"},type:{type:"string",description:"File type filter (e.g. 'js', 'py', 'ts') \u2014 maps to --include='*.ext'"},multiline:{type:"boolean",description:"Enable multiline matching (grep -Pz)"},staged:{type:"boolean",description:"Search only staged content (git diff --cached). Default: false"}},required:["pattern"]}}},{type:"function",function:{name:"patch_file",description:"Apply multiple text replacements to a file atomically. All patches are validated before any are applied \u2014 if one fails, none are written. Example: when changing 3 different variables in the same function, use patch_file with an array of 3 { old_text, new_text } objects instead of 3 separate edit_file calls. This ensures either all changes are applied or none are, preventing partial edits. Like edit_file, all old_text values must match exactly.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},patches:{type:"array",description:"Array of { old_text, new_text } replacements to apply in order",items:{type:"object",properties:{old_text:{type:"string",description:"Text to find"},new_text:{type:"string",description:"Replacement text"}},required:["old_text","new_text"]}}},required:["path","patches"]}}},{type:"function",function:{name:"web_fetch",description:"Fetch content from a URL and return text. HTML tags are stripped. Use for reading documentation, API responses, or web pages. Will not work with authenticated/private URLs.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to fetch"},max_length:{type:"number",description:"Max response length in chars (default: 10000)"}},required:["url"]}}},{type:"function",function:{name:"web_search",description:"Search the web. Uses Perplexity (grounded, AI-summarized) if PERPLEXITY_API_KEY is set, otherwise DuckDuckGo. Returns titles, URLs, and summaries. Use to find documentation, solutions, or current information beyond your knowledge cutoff.",parameters:{type:"object",properties:{query:{type:"string",description:"Search query"},max_results:{type:"number",description:"Max results (default: 5)"}},required:["query"]}}},{type:"function",function:{name:"browser_open",description:"Open a URL in a headless browser and return the page title, text content, and links. More reliable than web_fetch for JavaScript-heavy pages. Requires playwright (npm install playwright && npx playwright install chromium).",parameters:{type:"object",properties:{url:{type:"string",description:"URL to open"},wait_for:{type:"string",enum:["domcontentloaded","networkidle","load"],description:"When to consider page loaded (default: domcontentloaded)"}},required:["url"]}}},{type:"function",function:{name:"browser_screenshot",description:"Take a screenshot of a URL in a headless browser. Returns the screenshot file path. The path can be pasted into the next message for visual analysis. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot"},full_page:{type:"boolean",description:"Capture full page (default: false \u2014 viewport only)"},width:{type:"number",description:"Viewport width in px (default: 1280)"},height:{type:"number",description:"Viewport height in px (default: 800)"}},required:["url"]}}},{type:"function",function:{name:"visual_review",description:"Screenshot a URL, analyze the visual result, and return structured feedback about layout, design, and usability issues. Use this to visually inspect web pages, check CSS changes, or verify UI fixes. Returns the screenshot path + analysis.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot and analyze"},focus:{type:"string",description:"What to focus on: layout, colors, typography, spacing, responsiveness, accessibility, or a custom description (e.g. 'check the navbar alignment')"},width:{type:"number",description:"Viewport width in px (default: 1280)"},height:{type:"number",description:"Viewport height in px (default: 800)"},full_page:{type:"boolean",description:"Capture full scrollable page (default: false)"},compare_with:{type:"string",description:"Path to a previous screenshot to compare against (optional). Enables before/after analysis."}},required:["url"]}}},{type:"function",function:{name:"clipboard_image",description:"Grab the current image from the system clipboard (macOS). Returns the screenshot path for visual analysis. Use when the user says 'clipboard', 'pasteboard', or wants to analyze a copied screenshot.",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"browser_click",description:"Click an element on a web page (by CSS selector or visible text). Returns the new URL after navigation. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of element to click (mutually exclusive with text)"},text:{type:"string",description:"Visible text of element to click (mutually exclusive with selector)"}},required:["url"]}}},{type:"function",function:{name:"browser_fill",description:"Fill a form field on a web page and optionally submit. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of the input field"},value:{type:"string",description:"Value to fill in"},submit:{type:"boolean",description:"Press Enter to submit after filling (default: false)"}},required:["url","selector","value"]}}},{type:"function",function:{name:"visual_diff",description:"Compare two screenshots pixel-by-pixel and compute a visual diff. Returns the percentage of changed pixels and which screen regions (top-left, center, bottom-right, etc.) were affected. Use after making CSS/HTML changes to quantify what changed. Example: take a before screenshot, make changes, take an after screenshot, then visual_diff both paths.",parameters:{type:"object",properties:{before:{type:"string",description:"Path to the 'before' screenshot (PNG)"},after:{type:"string",description:"Path to the 'after' screenshot (PNG)"},threshold:{type:"number",description:"Color distance threshold 0-1 (default: 0.1). Lower = more sensitive."}},required:["before","after"]}}},{type:"function",function:{name:"responsive_sweep",description:"Screenshot a URL at 5 viewport widths (320, 768, 1024, 1440, 1920) and return all screenshots for breakpoint analysis. Quickly identifies responsive layout issues across mobile, tablet, and desktop. Returns images for visual analysis.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot at each viewport"},viewports:{type:"array",items:{type:"object",properties:{width:{type:"number"},label:{type:"string"}}},description:"Custom viewport list (default: 320/768/1024/1440/1920)"},full_page:{type:"boolean",description:"Capture full scrollable page at each viewport (default: false)"}},required:["url"]}}},{type:"function",function:{name:"visual_annotate",description:"Draw annotations (red boxes, arrows, circles) directly on a screenshot to mark problem areas. Returns the annotated image. Use instead of describing locations verbally \u2014 visual markers are unambiguous.",parameters:{type:"object",properties:{image:{type:"string",description:"Path to the screenshot (PNG) to annotate"},annotations:{type:"array",items:{type:"object",properties:{type:{type:"string",description:"box, arrow, or circle"},x:{type:"number",description:"X position (px)"},y:{type:"number",description:"Y position (px)"},width:{type:"number",description:"Width for box (px)"},height:{type:"number",description:"Height for box (px)"},toX:{type:"number",description:"Arrow end X (px)"},toY:{type:"number",description:"Arrow end Y (px)"},radius:{type:"number",description:"Circle radius (px)"},label:{type:"string",description:"Text label for the annotation"},color:{type:"string",description:"Hex color (default: #FF0000)"}},required:["type","x","y"]},description:"List of annotations to draw"}},required:["image","annotations"]}}},{type:"function",function:{name:"visual_watch",description:"Hot-reload visual feedback loop: watches source files for changes, waits for HMR to settle, takes a new screenshot, diffs it against the previous one, and reports what changed. Runs up to N iterations (default: 10). Requires a running dev server (Vite, Next, etc.) and chokidar. Use for autonomous visual polish loops.",parameters:{type:"object",properties:{url:{type:"string",description:"Dev server URL to screenshot (e.g. http://localhost:5173)"},watch:{type:"array",items:{type:"string"},description:"File paths or directories to watch for changes (e.g. ['src/components', 'src/styles'])"},max_iterations:{type:"number",description:"Max number of change\u2192screenshot\u2192diff cycles (default: 10)"},hmr_delay:{type:"number",description:"Milliseconds to wait after file change for HMR to settle (default: 1500)"}},required:["url","watch"]}}},{type:"function",function:{name:"design_tokens",description:"Extract design tokens from a screenshot: dominant colors (with hex/rgb/frequency/category), detected vertical spacing values, and image dimensions. Use to audit visual consistency, compare against a design system, or reverse-engineer CSS variables from a rendered page.",parameters:{type:"object",properties:{image:{type:"string",description:"Path to screenshot (PNG) to analyze"},sample_rate:{type:"number",description:"Pixel sampling interval \u2014 lower = more accurate but slower (default: 4)"}},required:["image"]}}},{type:"function",function:{name:"design_compare",description:"Compare a live web page against a reference design (Figma export, mockup PNG). Screenshots the URL at the reference image's dimensions, computes pixel-level diff, and returns annotated images highlighting deviations. Use to verify implementation matches the design spec.",parameters:{type:"object",properties:{url:{type:"string",description:"Live URL to compare against the reference"},reference:{type:"string",description:"Path to reference design image (PNG)"},width:{type:"number",description:"Override viewport width (default: match reference image width)"},height:{type:"number",description:"Override viewport height (default: 800)"},threshold:{type:"number",description:"Color distance threshold 0-1 (default: 0.1)"}},required:["url","reference"]}}},{type:"function",function:{name:"ask_user",description:"Ask the user a clarifying question with 2-3 specific options. Use when the user's intent is ambiguous. Always provide concrete, actionable options. The user can select an option or type a custom answer.",parameters:{type:"object",properties:{question:{type:"string",description:"The clarifying question to ask"},options:{type:"array",items:{type:"string"},description:"2-3 specific, actionable answer options for the user to choose from",minItems:1,maxItems:3}},required:["question","options"]}}},{type:"function",function:{name:"git_status",description:"Get git status: current branch, changed files, staged/unstaged state. Use before git operations to understand the current state.",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"git_diff",description:"Get git diff for changed files. Shows additions and deletions.",parameters:{type:"object",properties:{staged:{type:"boolean",description:"Show only staged changes (default: false)"},file:{type:"string",description:"Diff specific file only (optional)"}},required:[]}}},{type:"function",function:{name:"git_log",description:"Show recent git commits (short format).",parameters:{type:"object",properties:{count:{type:"number",description:"Number of commits to show (default: 10)"},file:{type:"string",description:"Show commits for specific file (optional)"}},required:[]}}},{type:"function",function:{name:"task_list",description:"Create and manage a task list for complex multi-step tasks. Use for tasks with 3+ steps to track progress. Actions: create (new list with tasks), update (mark task in_progress/done/failed), get (view current list). Always update task status as you work.",parameters:{type:"object",properties:{action:{type:"string",enum:["create","update","get"],description:"Action to perform"},name:{type:"string",description:"Task list name (for create)"},tasks:{type:"array",description:"Array of tasks to create (for create)",items:{type:"object",properties:{description:{type:"string",description:"Task description"},depends_on:{type:"array",items:{type:"string"},description:"IDs of prerequisite tasks"}},required:["description"]}},task_id:{type:"string",description:"Task ID to update (for update)"},status:{type:"string",enum:["in_progress","done","failed"],description:"New status (for update)"},result:{type:"string",description:"Result summary (for update, optional)"}},required:["action"]}}},{type:"function",function:{name:"gh_run_list",description:"List recent GitHub Actions workflow runs for this repository. Shows run status, conclusion, branch, and timing. Use to check CI/CD status or find a run ID.",parameters:{type:"object",properties:{limit:{type:"number",description:"Number of runs to show (default: 10, max: 30)"},workflow:{type:"string",description:"Filter by workflow name or filename (optional)"},branch:{type:"string",description:"Filter by branch name (optional)"},status:{type:"string",enum:["completed","in_progress","queued","failure","success"],description:"Filter by status (optional)"}},required:[]}}},{type:"function",function:{name:"gh_run_view",description:"View details of a specific GitHub Actions workflow run: steps, logs, errors. Use gh_run_list first to get the run ID.",parameters:{type:"object",properties:{run_id:{type:"string",description:"The run ID (from gh_run_list)"},log:{type:"boolean",description:"Include full log output (default: false \u2014 shows step summary only)"}},required:["run_id"]}}},{type:"function",function:{name:"gh_workflow_trigger",description:"Trigger a GitHub Actions workflow dispatch event. Only works for workflows with workflow_dispatch trigger. Requires user confirmation.",parameters:{type:"object",properties:{workflow:{type:"string",description:"Workflow filename (e.g. ci.yml) or name"},branch:{type:"string",description:"Branch to run on (default: current branch)"},inputs:{type:"object",description:"Workflow input parameters as key-value pairs (optional)"}},required:["workflow"]}}},{type:"function",function:{name:"spawn_agents",description:"Run multiple independent sub-agents in parallel (max 5 at top level, max 2 when called from within a sub-agent). Each agent has its own conversation context. Use when 2+ tasks can run simultaneously \u2014 e.g. reading multiple files, analyzing separate modules, independent research. Do NOT use for tasks that depend on each other or modify the same file. Keep task descriptions specific and self-contained. SWARM PATTERN: Sub-agents can call spawn_agents once (max nesting depth 2) to enable Architect\u2192Coder\u2192Reviewer pipelines: a coder agent spawns 1-2 reviewer agents that validate and fix its own output before returning results to the parent.",parameters:{type:"object",properties:{agents:{type:"array",description:"Array of agent definitions to run in parallel (max 5)",items:{type:"object",properties:{task:{type:"string",description:"Task description for the agent"},context:{type:"string",description:"Additional context (optional)"},max_iterations:{type:"number",description:"Max iterations (default: 10, max: 15)"},model:{type:"string",description:'Override model for this agent (provider:model, e.g. "anthropic:claude-haiku"). Auto-selected if omitted.'},background:{type:"boolean",description:"Run this agent non-blocking in the background. The main session continues immediately; results are injected as [BACKGROUND AGENT COMPLETED] user messages when the agent finishes. Use for tasks that can run in parallel to your main work."}},required:["task"]}}},required:["agents"]}}},{type:"function",function:{name:"switch_model",description:"Switch the active AI model mid-conversation. Use when a different model is better for the next steps \u2014 e.g. switch to a fast model for simple lookups, or a more capable model for complex refactoring. The switch persists for all subsequent turns.",parameters:{type:"object",properties:{model:{type:"string",description:'Model spec: "provider:model" (e.g. "ollama:devstral-small-2:24b") or just model name'}},required:["model"]}}},{type:"function",function:{name:"k8s_pods",description:"List Kubernetes pods. Shows pod name, status, restarts, and age. Runs kubectl locally or via SSH on a remote server. Use namespace to filter, or omit for all namespaces.",parameters:{type:"object",properties:{namespace:{type:"string",description:"Namespace to list pods in (default: all namespaces)"},label:{type:"string",description:'Label selector filter (e.g. "app=nginx")'},context:{type:"string",description:"kubectl context to use (optional)"},server:{type:"string",description:"Remote server as user@host to run kubectl via SSH (optional, local kubectl if omitted)"}},required:[]}}},{type:"function",function:{name:"k8s_logs",description:'Fetch logs from a Kubernetes pod. Use tail to limit output, since for time-based filtering (e.g. "1h", "30m").',parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (required if pod has multiple containers)"},tail:{type:"number",description:"Number of recent lines to show (default: 100)"},since:{type:"string",description:'Show logs since duration (e.g. "1h", "30m", "5s")'},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod"]}}},{type:"function",function:{name:"k8s_exec",description:"Execute a command inside a running Kubernetes pod (kubectl exec). Requires user confirmation. Use for inspecting container state, reading configs, or debugging.",parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},command:{type:"string",description:'Command to run in the pod (e.g. "env", "ls /app", "cat /etc/config.yaml")'},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (optional)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod","command"]}}},{type:"function",function:{name:"k8s_apply",description:"Apply a Kubernetes manifest file (kubectl apply -f). Requires confirmation before applying to the cluster. Use dry_run=true to validate without applying.",parameters:{type:"object",properties:{file:{type:"string",description:"Path to manifest YAML file (relative or absolute)"},namespace:{type:"string",description:"Override namespace (optional)"},dry_run:{type:"boolean",description:"Validate only without applying (default: false)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["file"]}}},{type:"function",function:{name:"k8s_rollout",description:"Manage Kubernetes deployment rollouts: check status, restart (rolling update), view history, or undo (rollback). Restart and undo require confirmation.",parameters:{type:"object",properties:{action:{type:"string",enum:["status","restart","history","undo"],description:"Action: status (check rollout progress), restart (rolling restart), history (show revision history), undo (rollback to previous revision)"},deployment:{type:"string",description:"Deployment name"},namespace:{type:"string",description:"Namespace (default: default)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["action","deployment"]}}},{type:"function",function:{name:"brain_write",description:"Write or update a knowledge document in the project brain (.nex/brain/). Use this to persist important findings, architecture decisions, debugging insights, or conventions discovered during the session. The user can review changes via /brain review or git diff.",parameters:{type:"object",properties:{name:{type:"string",description:'Document name (without .md extension). Use kebab-case. Examples: "api-auth-flow", "db-schema-notes", "deployment-checklist"'},content:{type:"string",description:"Full Markdown content. Use headings (#), lists (-), and code blocks. Include optional YAML frontmatter with tags."},mode:{type:"string",enum:["create","update","append"],description:"create: new document (fails if exists). update: overwrite existing. append: add to end of existing document."}},required:["name","content","mode"]}}},{type:"function",function:{name:"ssh_exec",description:'Execute a command on a remote server via SSH. Server is a profile name from .nex/servers.json (e.g. "prod") or "user@host". Use for: checking status, reading logs, running deployments. Destructive commands (restart, delete, modify config) require confirmation. For service management prefer service_manage; for logs prefer service_logs.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name (from .nex/servers.json) or "user@host"'},command:{type:"string",description:"Shell command to run on the remote server"},sudo:{type:"boolean",description:"Run command with sudo (only if profile has sudo:true). Default: false"},timeout:{type:"number",description:"Timeout in seconds. Default: 30"}},required:["server","command"]}}},{type:"function",function:{name:"ssh_upload",description:"Upload a local file or directory to a remote server via SCP. Recursive for directories. Requires confirmation before upload.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},local_path:{type:"string",description:"Local path to upload (file or directory)"},remote_path:{type:"string",description:"Destination path on the remote server (absolute preferred)"}},required:["server","local_path","remote_path"]}}},{type:"function",function:{name:"ssh_download",description:"Download a file or directory from a remote server via SCP. Recursive for directories.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},remote_path:{type:"string",description:"Path on the remote server to download"},local_path:{type:"string",description:"Local destination path"}},required:["server","remote_path","local_path"]}}},{type:"function",function:{name:"remote_agent",description:'Delegate a coding task to nex-code running on a remote server. Use this when the task involves server-side projects (musikschule, stadtkapelle, cahill, schoensgibl) that live on almalinux9. Runs nex-code --auto on the server and streams output. Server is a profile name from .nex/servers.json or "user@host".',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name from .nex/servers.json (e.g. "almalinux9") or "user@host"'},task:{type:"string",description:"The full task description to run on the remote nex-code"},project_path:{type:"string",description:"Working directory on the remote server (e.g. /home/deploy/app). Defaults to home directory."},model:{type:"string",description:"Model to use on remote nex-code (e.g. qwen3-coder:480b). Defaults to server default."}},required:["server","task"]}}},{type:"function",function:{name:"service_manage",description:"Manage a systemd service on a remote (or local) server. Uses systemctl. Status is read-only; start/stop/restart/reload/enable/disable require confirmation. For AlmaLinux 9: runs via SSH with sudo if configured.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn", "postgresql")'},action:{type:"string",enum:["status","start","stop","restart","reload","enable","disable"],description:"systemctl action to perform"}},required:["service","action"]}}},{type:"function",function:{name:"service_logs",description:"Fetch systemd service logs via journalctl. Works on AlmaLinux 9 and any systemd Linux. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn")'},lines:{type:"number",description:"Number of recent log lines to fetch. Default: 50"},since:{type:"string",description:'Time filter, e.g. "1 hour ago", "today", "2024-01-01 12:00". Optional.'},follow:{type:"boolean",description:"Tail logs in real-time (follow mode). Default: false"}},required:["service"]}}},{type:"function",function:{name:"container_list",description:"List Docker containers on a server (or locally). Shows container ID, name, image, status, and ports. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},all:{type:"boolean",description:"Show all containers including stopped ones. Default: false (running only)."}},required:[]}}},{type:"function",function:{name:"container_logs",description:"Fetch logs from a Docker container on a server (or locally). Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},lines:{type:"number",description:"Number of recent log lines. Default: 50."},since:{type:"string",description:'Time filter, e.g. "1h", "30m", "2024-01-01T12:00:00". Optional.'}},required:["container"]}}},{type:"function",function:{name:"container_exec",description:"Execute a command inside a running Docker container. Destructive or state-changing commands require confirmation.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},command:{type:"string",description:'Command to run inside the container (e.g. "cat /etc/nginx/nginx.conf").'}},required:["container","command"]}}},{type:"function",function:{name:"container_manage",description:'Start, stop, restart, or remove a Docker container. All actions except "inspect" require confirmation.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},action:{type:"string",enum:["start","stop","restart","remove","inspect"],description:"Action to perform on the container."}},required:["container","action"]}}},{type:"function",function:{name:"frontend_recon",description:"MANDATORY first step before creating or significantly modifying any frontend file (HTML template, Vue/React component, CSS). Scans the project and returns: (1) design tokens \u2014 CSS variables, Tailwind theme colors/fonts, (2) main layout/index page structure, (3) a reference component of the same type, (4) detected JS/CSS framework stack. Call this BEFORE writing any markup or styles. Never skip it for frontend tasks.",parameters:{type:"object",properties:{type:{type:"string",description:'Type of frontend file you are about to create. Used to find a relevant reference component. Examples: "list", "form", "detail", "dashboard", "modal", "component". Optional but improves reference quality.'}},required:[]}}},{type:"function",function:{name:"deploy",description:'Deploy to a remote server. Supports two methods: "rsync" (sync local files) and "git" (git pull on remote). Can use a named config from .nex/deploy.json. Requires confirmation before executing.',parameters:{type:"object",properties:{config:{type:"string",description:'Named deploy config from .nex/deploy.json (e.g. "prod"). Overrides all other params if provided.'},method:{type:"string",enum:["rsync","git"],description:'Deploy method: "rsync" syncs local files (default), "git" runs git pull on the remote.'},server:{type:"string",description:'Profile name or "user@host". Required if no config.'},remote_path:{type:"string",description:"Remote project directory. Required for git method; destination path for rsync."},local_path:{type:"string",description:"Local directory or file to sync. Required for rsync method."},branch:{type:"string",description:"Branch to pull (git method only). Defaults to current remote branch."},deploy_script:{type:"string",description:'Shell command(s) to run on the remote after sync/pull (e.g. "npm ci && systemctl restart myapp"). Optional.'},health_check:{type:"string",description:"URL (HTTP GET) or shell command to verify the service is healthy after deploy. If it fails, the deploy is marked as failed. Optional."},exclude:{type:"array",items:{type:"string"},description:"Paths to exclude from rsync. Optional."},dry_run:{type:"boolean",description:"Show what would happen without executing. Default: false."}},required:[]}}},{type:"function",function:{name:"deployment_status",description:"Check deployment status across all configured servers. Reads .nex/deploy.json configs and checks service health on each server. Returns a status summary table.",parameters:{type:"object",properties:{config:{type:"string",description:"Specific deploy config name to check (optional \u2014 checks all if omitted)"}},required:[]}}},{type:"function",function:{name:"sysadmin",description:"Senior sysadmin operations on a remote (or local) Linux server. Covers: system audit, disk_usage, process_list, network_status, package management (dnf/apt), user management, firewall (firewalld/ufw/iptables), cron, SSL cert checks, log tailing, large file discovery, systemd service management, process kill, journalctl log querying. Read-only actions run without confirmation; state-changing actions require user approval.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},action:{type:"string",enum:["audit","disk_usage","process_list","network_status","package","user_manage","firewall","cron","ssl_check","log_tail","find_large","service","kill_process","journalctl"],description:"Sysadmin operation. audit=full health overview; disk_usage=df+du; process_list=top procs; network_status=open ports; package=dnf/apt (package_action: check|list|install|remove|update|upgrade); user_manage=users/keys; firewall=rules; cron=crontab; ssl_check=cert expiry+days; log_tail=tail any log; find_large=big files; service=systemd unit management; kill_process=kill by PID or name; journalctl=query system journal."},path:{type:"string",description:"File or directory path. For disk_usage (default /), log_tail (required), find_large (default /)."},lines:{type:"number",description:"Lines to tail for log_tail or journalctl. Default: 100."},limit:{type:"number",description:"Result count for process_list (default 20) or find_large (default 20)."},sort_by:{type:"string",enum:["cpu","mem"],description:"Sort order for process_list. Default: cpu."},min_size:{type:"string",description:'Minimum file size for find_large. Default: "100M". Examples: "50M", "1G".'},package_action:{type:"string",enum:["install","remove","update","list","upgrade"],description:"Package sub-action for action=package."},packages:{type:"array",items:{type:"string"},description:"Package name(s) for install/remove/update."},user_action:{type:"string",enum:["list","create","delete","add_ssh_key","info"],description:"User sub-action for action=user_manage."},user:{type:"string",description:"Linux username for user_manage or cron."},groups:{type:"array",items:{type:"string"},description:'Groups to assign on user create (e.g. ["sudo", "docker"]).'},ssh_key:{type:"string",description:"SSH public key string to add for user_action=add_ssh_key."},firewall_action:{type:"string",enum:["status","allow","deny","remove","reload"],description:"Firewall sub-action for action=firewall."},port:{type:"string",description:'Port/protocol for firewall rules, e.g. "80/tcp", "443", "8080/udp".'},cron_action:{type:"string",enum:["list","add","remove"],description:"Cron sub-action for action=cron."},schedule:{type:"string",description:'Cron schedule expression for cron add, e.g. "0 2 * * *".'},command:{type:"string",description:"Command for cron add, or substring to match for cron remove."},domain:{type:"string",description:`Domain for ssl_check (e.g. "example.com"). Auto-detects Let's Encrypt cert on server; falls back to live TLS probe.`},cert_path:{type:"string",description:'Explicit path to cert file on server for ssl_check (e.g. "/etc/letsencrypt/live/x/cert.pem").'},service_name:{type:"string",description:'Systemd unit name for action=service (e.g. "nginx", "my-api", "gunicorn"). .service suffix optional.'},service_action:{type:"string",enum:["status","start","stop","restart","reload","enable","disable","list_failed"],description:"Sub-action for action=service. list_failed shows all failed units."},pid:{type:"number",description:"Process ID to kill for action=kill_process."},process_name:{type:"string",description:"Process name to kill (uses pkill) for action=kill_process. Use with pid for safety."},signal:{type:"string",enum:["SIGTERM","SIGKILL","SIGHUP","SIGINT"],description:"Signal for kill_process. Default: SIGTERM."},unit:{type:"string",description:'Systemd unit to filter for journalctl (e.g. "nginx", "my-api"). Omit for system-wide.'},since:{type:"string",description:'Time filter for journalctl, e.g. "1 hour ago", "today", "2026-03-17 10:00". Default: last 200 lines.'},priority:{type:"string",enum:["emerg","alert","crit","err","warning","notice","info","debug"],description:"Minimum log priority for journalctl. Default: no filter."}},required:["action"]}}},{type:"function",function:{name:"save_memory",description:"Save a typed memory for cross-session persistence. Use this to remember user preferences, feedback, project context, or external references.",parameters:{type:"object",properties:{type:{type:"string",enum:["user","feedback","project","reference"],description:"Memory type: user (role/prefs), feedback (approach guidance), project (ongoing work), reference (external pointers)"},name:{type:"string",description:"Short slug identifier for this memory (e.g. 'testing-preference', 'deploy-workflow')"},content:{type:"string",description:"Markdown content of the memory"},description:{type:"string",description:"One-line description for the memory index (optional, defaults to first line of content)"}},required:["type","name","content"]}}},{type:"function",function:{name:"delete_memory",description:"Delete a typed memory entry. Use this to prune outdated or incorrect memories.",parameters:{type:"object",properties:{type:{type:"string",enum:["user","feedback","project","reference"],description:"Memory type to delete from"},name:{type:"string",description:"Slug identifier of the memory to delete"}},required:["type","name"]}}}];function ir(t,{server:e,context:n}={}){let o=e?e.replace(/[^a-zA-Z0-9@._-]/g,""):null,s=n?n.replace(/[^a-zA-Z0-9._/-]/g,""):null,r="kubectl";if(s&&(r+=` --context ${s}`),r+=` ${t}`,o){let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`ssh -o ConnectTimeout=10 -o BatchMode=yes ${o} "${i}"`}return r}async function Dg(t,e,n={}){switch(t){case"bash":{let o=e.command,s=aE(o);if(s){let d=RE(o);return`BLOCKED: Command matches forbidden pattern: ${s}${d?`
315
315
  HINT: ${d}`:""}`}let r=uE(o);if(r)return`BLOCKED: Destructive operation on protected path: ${r}
316
- HINT: Protected files (.env, credentials, venv, .ssh, etc.) cannot be deleted or moved via bash. Override with NEX_UNPROTECT=1 if intentional.`;if(n.autoConfirm?Tg(o):lE(o)){let d=Tg(o)?"\u26D4":"\u26A0";if(!await Jt(` ${d} bash: \`${o}\``,{toolName:"bash"}))return"CANCELLED: User declined to execute this command."}let a;try{a=process.cwd(),Zt.accessSync(a)}catch{a=require("os").homedir(),n.silent||console.log(`${pe.yellow} \u26A0 Working directory no longer exists \u2014 running in ${a}${pe.reset}`)}let c=vE.test(o.trim())&&!SE.test(o.trim());if(kE.test(o.trim())||c){n.silent||console.log(`${pe.dim} \u25B6 interactive: ${o}${pe.reset}`);let d=iE("sh",["-c",o],{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:u}=Yn(),l=n.silent?null:new u("bash",`$ ${o.substring(0,72)}`);l&&l.start();try{let{stdout:d,stderr:f}=await Ye(o,{cwd:a,timeout:9e4,maxBuffer:5242880});return l&&l.stop(),d||f||"(no output)"}catch(d){l&&l.stop();let f=(d.stderr||d.stdout||d.message||"").toString().substring(0,5e3),p=Bg(f,o);return`EXIT ${d.code||1}
316
+ HINT: Protected files (.env, credentials, venv, .ssh, etc.) cannot be deleted or moved via bash. Override with NEX_UNPROTECT=1 if intentional.`;if(n.autoConfirm?Rg(o):lE(o)){let d=Rg(o)?"\u26D4":"\u26A0";if(!await Jt(` ${d} bash: \`${o}\``,{toolName:"bash"}))return"CANCELLED: User declined to execute this command."}let a;try{a=process.cwd(),Zt.accessSync(a)}catch{a=require("os").homedir(),n.silent||console.log(`${pe.yellow} \u26A0 Working directory no longer exists \u2014 running in ${a}${pe.reset}`)}let c=vE.test(o.trim())&&!SE.test(o.trim());if(kE.test(o.trim())||c){n.silent||console.log(`${pe.dim} \u25B6 interactive: ${o}${pe.reset}`);let d=iE("sh",["-c",o],{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:u}=Yn(),l=n.silent?null:new u("bash",`$ ${o.substring(0,72)}`);l&&l.start();try{let{stdout:d,stderr:f}=await Ye(o,{cwd:a,timeout:9e4,maxBuffer:5242880});return l&&l.stop(),d||f||"(no output)"}catch(d){l&&l.stop();let f=(d.stderr||d.stdout||d.message||"").toString().substring(0,5e3),p=Ug(f,o);return`EXIT ${d.code||1}
317
317
  ${p}`}}case"read_file":{let o=new Ki("read_file","Reading file...");o.start();try{let s=ut(e.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await At(s)){let ue=await Ji(e.path);if(ue.fixedPath)s=ue.fixedPath,console.log(`${pe.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ae.relative(process.cwd(),s)}${pe.reset}`),o.update({message:"Resolved path",detail:ae.relative(process.cwd(),s)});else return`ERROR: File not found: ${e.path}${ue.message?`
318
318
  `+ue.message:""}`}let i=ae.relative(process.cwd(),s);o.update({message:"Scanning",detail:i});let a=Buffer.alloc(8192),c=await Zt.promises.open(s,"r"),{bytesRead:u}=await c.read(a,0,8192,0);await c.close();for(let ue=0;ue<u;ue++)if(a[ue]===0)return`ERROR: ${s} is a binary file (not readable as text)`;let l=await Ze.readFile(s,"utf-8");if(!l&&(await Ze.stat(s)).size>0)return`WARNING: ${s} is empty or unreadable`;let d=l.split(`
319
319
  `),f=await Ze.stat(s),p=d.length,h=350,g=!e.line_start&&!e.line_end,w=g&&p>h,_=(e.line_start||1)-1,S=w?h:e.line_end||d.length,A=_+1,E=S;o.update({count:Math.max(0,S-_),total:p,detail:`${i} lines ${A}-${E}`,message:w?"Reading excerpt":"Reading"});let v=w?`showing lines 1-${h} of ${p}`:e.line_start||e.line_end?`lines ${_+1}-${S} of ${p}`:`${p} lines`,N=`File: ${i} (${v}, ${f.size} bytes)`,ne=d.slice(_,S).map((ue,fe)=>`${_+fe+1}: ${ue}`).join(`
@@ -325,9 +325,9 @@ ${p}`}}case"read_file":{let o=new Ki("read_file","Reading file...");o.start();tr
325
325
  ${ne}${oe}`}finally{o.stop()}}case"write_file":{let o=new Ki("write_file","Preparing write...");o.start();try{await Bl();let s=ut(e.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let r=await At(s),i=null,a=String(e.content||"").split(`
326
326
  `).length;if(o.update({count:a,detail:`${ae.relative(process.cwd(),s)} ${a} lines`,message:r?"Overwriting":"Creating"}),n.autoConfirm)r&&(i=await Ze.readFile(s,"utf-8"));else if(r){i=await Ze.readFile(s,"utf-8");let f=await sr(s,e.content);if(zi(s,i,e.content,{annotations:f}),!await nr("Overwrite"))return"CANCELLED: User declined to overwrite file."}else{let f=await sr(s,e.content);if(dE(s,e.content,{annotations:f}),!await nr("Create"))return"CANCELLED: User declined to create file."}let c=ae.dirname(s);await At(c)||await Ze.mkdir(c,{recursive:!0}),o.update({message:"Writing",detail:`${ae.relative(process.cwd(),s)} ${a} lines`}),await Ze.writeFile(s,e.content,"utf-8");let l=/[/\\]\.git[/\\]hooks[/\\]/.test(s)||s.endsWith(".sh")||e.content.startsWith("#!");l&&(o.update({message:"Chmod",detail:ae.relative(process.cwd(),s)}),await Ze.chmod(s,493)),Xi("write_file",s,i,e.content);let d=l?" [chmod +x applied]":"";return`Written: ${s} (${e.content.length} chars)${d}`}finally{o.stop()}}case"edit_file":{let o=new Ki("edit_file","Preparing edit...");o.start();try{await Bl();let s=ut(e.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await At(s)){let d=await Ji(e.path);if(d.fixedPath)s=d.fixedPath,console.log(`${pe.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ae.relative(process.cwd(),s)}${pe.reset}`);else return`ERROR: File not found: ${e.path}${d.message?`
327
327
  `+d.message:""}`}o.update({message:"Loading",detail:ae.relative(process.cwd(),s)});let i=await Ze.readFile(s,"utf-8"),a=e.old_text,c=!1,u=!1;if(!i.includes(e.old_text)){o.update({message:"Matching target",detail:`${ae.relative(process.cwd(),s)} ${String(e.old_text||"").trim().split(`
328
- `)[0].slice(0,40)}`});let{getActiveModelId:d,getActiveProviderName:f}=ct();if(Mg(d(),f())==="strict"){let g=ar(i,e.old_text);return g?`ERROR: old_text not found in ${s} (strict mode \u2014 exact match required)
328
+ `)[0].slice(0,40)}`});let{getActiveModelId:d,getActiveProviderName:f}=ct();if(Pg(d(),f())==="strict"){let g=ar(i,e.old_text);return g?`ERROR: old_text not found in ${s} (strict mode \u2014 exact match required)
329
329
  Most similar text (line ${g.line}, distance ${g.distance}):
330
- ${g.text}`:`ERROR: old_text not found in ${s} (strict mode \u2014 exact match required)`}let h=Cg(i,e.old_text);if(h)a=h,c=!0,o.update({message:"Matched target",detail:`${ae.relative(process.cwd(),s)} whitespace-normalized`}),console.log(`${pe.dim} \u2713 fuzzy whitespace match applied${pe.reset}`);else{let g=Ug(i,e.old_text,e.new_text);if(g){if(!n.autoConfirm){let E=await sr(s,g.content);if(zi(s,i,g.content,{annotations:E}),!await nr(`Apply (auto-fix, line ${g.line}, distance ${g.distance})`))return"CANCELLED: User declined to apply edit."}await Ze.writeFile(s,g.content,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(s)||s.endsWith(".sh")||g.content.startsWith("#!"))&&await Ze.chmod(s,493),Xi("edit_file",s,i,g.content);let A=g.matchText.length>80?g.matchText.substring(0,77)+"...":g.matchText;return console.log(`${pe.dim} \u2713 auto-fixed edit: line ${g.line}, distance ${g.distance}${pe.reset}`),`Edited: ${s} (auto-fixed, line ${g.line}, distance ${g.distance}, matched: "${A}")`}let w=ar(i,e.old_text);if(w){let A=i.split(`
330
+ ${g.text}`:`ERROR: old_text not found in ${s} (strict mode \u2014 exact match required)`}let h=Ag(i,e.old_text);if(h)a=h,c=!0,o.update({message:"Matched target",detail:`${ae.relative(process.cwd(),s)} whitespace-normalized`}),console.log(`${pe.dim} \u2713 fuzzy whitespace match applied${pe.reset}`);else{let g=Wg(i,e.old_text,e.new_text);if(g){if(!n.autoConfirm){let E=await sr(s,g.content);if(zi(s,i,g.content,{annotations:E}),!await nr(`Apply (auto-fix, line ${g.line}, distance ${g.distance})`))return"CANCELLED: User declined to apply edit."}await Ze.writeFile(s,g.content,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(s)||s.endsWith(".sh")||g.content.startsWith("#!"))&&await Ze.chmod(s,493),Xi("edit_file",s,i,g.content);let A=g.matchText.length>80?g.matchText.substring(0,77)+"...":g.matchText;return console.log(`${pe.dim} \u2713 auto-fixed edit: line ${g.line}, distance ${g.distance}${pe.reset}`),`Edited: ${s} (auto-fixed, line ${g.line}, distance ${g.distance}, matched: "${A}")`}let w=ar(i,e.old_text);if(w){let A=i.split(`
331
331
  `),E=Math.max(0,w.line-6),v=Math.min(A.length,w.line+10),N=A.slice(E,v).map((oe,ue)=>`${E+ue+1}: ${oe}`).join(`
332
332
  `),ne=`line_start=${Math.max(1,w.line-5)} line_end=${Math.min(A.length,w.line+15)}`;return`ERROR: old_text not found in ${s} (most similar at line ${w.line}, distance ${w.distance})
333
333
 
@@ -341,16 +341,16 @@ Recovery: use grep -n to locate the text, then re-read that section with line_st
341
341
  `)[0].slice(0,40)}`});let d=i.split(a).join(e.new_text),f=await sr(s,d);if(zi(s,i,d,{annotations:f}),!await nr(c?"Apply (fuzzy match)":"Apply"))return"CANCELLED: User declined to apply edit."}let l=i.split(a).join(e.new_text);return o.update({message:"Applying edit",detail:`${ae.relative(process.cwd(),s)} ${String(e.new_text||"").trim().split(`
342
342
  `)[0].slice(0,40)}`}),await Ze.writeFile(s,l,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(s)||s.endsWith(".sh")||l.startsWith("#!"))&&(o.update({message:"Chmod",detail:ae.relative(process.cwd(),s)}),await Ze.chmod(s,493)),Xi("edit_file",s,i,l),c?`Edited: ${s} (fuzzy match)`:`Edited: ${s}`}finally{o.stop()}}case"list_directory":{let o=ut(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await At(o)){let u=e.path.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),l=ut(u),d=await At(l);if(l&&d)o=l;else return`ERROR: Directory not found: ${e.path}`}let r=e.max_depth||2,i=null;if(e.pattern)try{let u=e.pattern.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");i=new RegExp(`^${u}$`)}catch{return`ERROR: Invalid pattern: ${e.pattern}`}let a=[],c=async(u,l,d)=>{if(l>r)return;let f;try{f=await Ze.readdir(u,{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 c(ae.join(u,p.name),l+1,d+" ")}};return await c(o,1,""),a.join(`
343
343
  `)||"(empty)"}case"search_files":{let o=ut(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let s=["-rn","-H"];e.file_pattern&&s.push(`--include=${e.file_pattern}`),s.push(e.pattern,o);try{let{stdout:r}=await fs("grep",s,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),i=or(r).slice(0,50);return(await Fl(i,{query:e.pattern,basePath:o})).join(`
344
- `)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let s=process.cwd(),r=e.path?ut(e.path):s,i=e.pattern,a=v=>{let N=v.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"(.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");return new RegExp(`^${N}$`)},c=a(i),u=i.split("/").pop(),l=a(u),{ToolProgress:d}=Yn(),f=new d("glob","Finding files...");f.start();let p=Ag();bE(r)||(await wE(r),p=Ag());let h=p.filter(v=>c.test(v)||l.test(ae.basename(v))).map(v=>ae.join(r,v));if(h.length===0)return f.stop(),"(no matches)"+ql(e.path);let g=await Promise.all(h.slice(0,210).map(async v=>{try{let N=await Ze.stat(v);return{path:v,mtime:N.mtimeMs}}catch{return{path:v,mtime:0}}})),w=new Map(g.map(v=>[v.path,v.mtime])),_=await qg(i,r),S=Fg(g.map(v=>v.path),{query:i,basePath:r,definitionScores:_,mtimeByPath:w}),A=h.length>200,E=S.slice(0,200).join(`
344
+ `)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let s=process.cwd(),r=e.path?ut(e.path):s,i=e.pattern,a=v=>{let N=v.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"(.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");return new RegExp(`^${N}$`)},c=a(i),u=i.split("/").pop(),l=a(u),{ToolProgress:d}=Yn(),f=new d("glob","Finding files...");f.start();let p=Og();bE(r)||(await wE(r),p=Og());let h=p.filter(v=>c.test(v)||l.test(ae.basename(v))).map(v=>ae.join(r,v));if(h.length===0)return f.stop(),"(no matches)"+ql(e.path);let g=await Promise.all(h.slice(0,210).map(async v=>{try{let N=await Ze.stat(v);return{path:v,mtime:N.mtimeMs}}catch{return{path:v,mtime:0}}})),w=new Map(g.map(v=>[v.path,v.mtime])),_=await Fg(i,r),S=Bg(g.map(v=>v.path),{query:i,basePath:r,definitionScores:_,mtimeByPath:w}),A=h.length>200,E=S.slice(0,200).join(`
345
345
  `);return f.update({count:h.length,detail:e.pattern}),f.stop(),A?`${E}
346
346
 
347
347
  \u26A0 Results truncated at 200. Use a more specific pattern.`:E}case"grep":{let o=e.path?ut(e.path):process.cwd();if(e.staged){let{getDiff:c}=di(),u=await c(!0);if(!u.trim())return"(no staged changes)";let l=new Set,d=u.split(`
348
348
  `);for(let w of d)if(w.startsWith("diff --git")){let _=w.match(/diff --git a\/(.+) b\/(.+)/);_&&l.add(_[2])}let f=["-rn","-E","-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}=Yn(),h=new p("grep","Searching staged content...");h.start();let g=[];for(let w of l)try{let _=ae.join(process.cwd(),w);if(await At(_)){let S=[...f];S.push(e.pattern,_);let{stdout:A}=await fs("grep",S,{cwd:process.cwd(),timeout:3e4,maxBuffer:2*1024*1024});if(e.output_mode==="files_with_matches"||e.output_mode==="count"){let E=or(A,e.output_mode);g=g.concat(E)}else g=g.concat(or(A))}}catch{}return g=await Fl(g,{query:e.pattern,basePath:process.cwd(),outputMode:e.output_mode}),h.update({count:g.length,detail:"in staged files"}),h.stop(),g.join(`
349
349
  `).trim()||"(no matches in staged files)"}let s=["-rn","-E","-H"];e.ignore_case&&s.push("-i"),e.include&&s.push(`--include=${e.include}`),e.type&&s.push(`--include=*.${e.type}`);let r=20;e.context?s.push("-C",String(Math.min(Number(e.context),r))):(e.before_context&&s.push("-B",String(Math.min(Number(e.before_context),r))),e.after_context&&s.push("-A",String(Math.min(Number(e.after_context),r)))),e.output_mode==="files_with_matches"?s.push("-l"):e.output_mode==="count"&&s.push("-c"),s.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage"),s.push(e.pattern,o);let{ToolProgress:i}=Yn(),a=new i("grep","Searching...");a.start();try{let{stdout:c}=await fs("grep",s,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),u;e.output_mode==="files_with_matches"||e.output_mode==="count"?u=or(c,e.output_mode):u=or(c);let l=e.offset||0,d=e.head_limit||(e.output_mode==="files_with_matches"?200:100);return u=await Fl(u,{query:e.pattern,basePath:o,outputMode:e.output_mode}),u=u.slice(l,l+d),a.update({count:u.length,detail:`in ${o}`}),a.stop(),u.join(`
350
350
  `).trim()||"(no matches)"+ql(e.path)}catch(c){if(a.stop(),c.code===2){let u=(c.stderr||c.message||"").toString().trim();return u.includes("No such file or directory")?`ERROR: Directory not found: ${o}`:u.includes("Invalid")||u.includes("Unmatched")||u.includes("unterminated")||u.includes("unclosed")||u.includes("parse error")||u.includes("brackets")||u.includes("not balanced")?`ERROR: Invalid regex pattern: ${e.pattern}`:`ERROR: grep failed: ${u.slice(0,200)||"exit code 2"}`}return"(no matches)"+ql(e.path)}}case"patch_file":{let o=new Ki("patch_file","Preparing patches...");o.start();try{await Bl();let s=ut(e.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await At(s)){let S=await Ji(e.path);if(S.fixedPath)s=S.fixedPath,console.log(`${pe.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ae.relative(process.cwd(),s)}${pe.reset}`);else return`ERROR: File not found: ${e.path}${S.message?`
351
- `+S.message:""}`}let i=e.patches;if(!Array.isArray(i)||i.length===0)return"ERROR: No patches provided";o.update({count:0,total:i.length,detail:`${ae.relative(process.cwd(),s)} ${i.length} patches`,message:"Validating patches"});let a=await Ze.readFile(s,"utf-8"),{getActiveModelId:c,getActiveProviderName:u}=ct(),l=Mg(c(),u()),d=[],f=!1,p=!1;for(let S=0;S<i.length;S++){o.update({count:S+1,total:i.length,detail:`${ae.relative(process.cwd(),s)} patch ${S+1}/${i.length}`,message:"Matching patches"});let{old_text:A,new_text:E}=i[S];if(a.includes(A))d.push({old_text:A,new_text:E});else if(l==="strict"){let v=ar(a,A);return v?`ERROR: Patch ${S+1} old_text not found in ${s} (strict mode \u2014 exact match required)
351
+ `+S.message:""}`}let i=e.patches;if(!Array.isArray(i)||i.length===0)return"ERROR: No patches provided";o.update({count:0,total:i.length,detail:`${ae.relative(process.cwd(),s)} ${i.length} patches`,message:"Validating patches"});let a=await Ze.readFile(s,"utf-8"),{getActiveModelId:c,getActiveProviderName:u}=ct(),l=Pg(c(),u()),d=[],f=!1,p=!1;for(let S=0;S<i.length;S++){o.update({count:S+1,total:i.length,detail:`${ae.relative(process.cwd(),s)} patch ${S+1}/${i.length}`,message:"Matching patches"});let{old_text:A,new_text:E}=i[S];if(a.includes(A))d.push({old_text:A,new_text:E});else if(l==="strict"){let v=ar(a,A);return v?`ERROR: Patch ${S+1} old_text not found in ${s} (strict mode \u2014 exact match required)
352
352
  Most similar text (line ${v.line}, distance ${v.distance}):
353
- ${v.text}`:`ERROR: Patch ${S+1} old_text not found in ${s} (strict mode \u2014 exact match required)`}else{let v=Cg(a,A);if(v)d.push({old_text:v,new_text:E}),f=!0;else{let N=ar(a,A);if(N){let ne=Math.max(3,Math.ceil(A.length*.05));if(N.distance<=ne)d.push({old_text:N.text,new_text:E}),p=!0;else return`ERROR: Patch ${S+1} old_text not found in ${s}
353
+ ${v.text}`:`ERROR: Patch ${S+1} old_text not found in ${s} (strict mode \u2014 exact match required)`}else{let v=Ag(a,A);if(v)d.push({old_text:v,new_text:E}),f=!0;else{let N=ar(a,A);if(N){let ne=Math.max(3,Math.ceil(A.length*.05));if(N.distance<=ne)d.push({old_text:N.text,new_text:E}),p=!0;else return`ERROR: Patch ${S+1} old_text not found in ${s}
354
354
  Most similar text (line ${N.line}, distance ${N.distance}):
355
355
  ${N.text}`}else return`ERROR: Patch ${S+1} old_text not found in ${s}`}}}let h=a;for(let{old_text:S,new_text:A}of d)h=h.split(S).join(A);if(!n.autoConfirm){o.update({message:"Previewing patch set",count:d.length,total:i.length,detail:`${ae.relative(process.cwd(),s)} ${d.length} matched`});let S=await sr(s,h);if(zi(s,a,h,{annotations:S}),!await nr(f?"Apply patches (fuzzy match)":"Apply patches"))return"CANCELLED: User declined to apply patches."}o.update({message:"Applying patches",count:d.length,total:i.length,detail:`${ae.relative(process.cwd(),s)} ${d.length} matched`}),await Ze.writeFile(s,h,"utf-8");let g=/[/\\]\.git[/\\]hooks[/\\]/.test(s)||s.endsWith(".sh")||h.startsWith("#!");g&&(o.update({message:"Chmod",detail:ae.relative(process.cwd(),s)}),await Ze.chmod(s,493)),Xi("patch_file",s,a,h);let w=p?" (auto-fixed)":f?" (fuzzy match)":"",_=g?" [chmod +x applied]":"";return`Patched: ${s} (${i.length} replacements)${w}${_}`}finally{o.stop()}}case"web_fetch":{let o=e.url,s=e.max_length||1e4;try{let i=new URL(o).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 jl.get(o,{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,s)||"(empty response)"}catch(r){return`ERROR: Failed to fetch ${o}: ${r.message}`}}case"web_search":{let o=e.max_results||5;if(process.env.PERPLEXITY_API_KEY)try{let s=await jl.post("https://api.perplexity.ai/chat/completions",{model:"sonar",messages:[{role:"user",content:e.query}],max_tokens:1024,search_recency_filter:"month",return_citations:!0},{timeout:2e4,headers:{Authorization:`Bearer ${process.env.PERPLEXITY_API_KEY}`,"Content-Type":"application/json"}}),r=s.data?.choices?.[0]?.message?.content||"",i=s.data?.citations||[],a=`[Perplexity grounded search]
356
356
 
@@ -453,7 +453,7 @@ ${r}
453
453
  ${s.map((c,u)=>` ${u+1}. ${c}`).join(`
454
454
  `)}
455
455
  `:"";console.log(`
456
- ${pe.cyan}${pe.bold} ? ${o}${pe.reset}${a}`),i.question(`${pe.cyan} > ${pe.reset}`,c=>{ps=null,i.close(),r(c.trim()||"(no response)")})})}case"git_status":{if(!await Dl())return"ERROR: Not a git repository";let o=await Rg()||"(detached)",s=await hE();if(s.length===0)return`Branch: ${o}
456
+ ${pe.cyan}${pe.bold} ? ${o}${pe.reset}${a}`),i.question(`${pe.cyan} > ${pe.reset}`,c=>{ps=null,i.close(),r(c.trim()||"(no response)")})})}case"git_status":{if(!await Dl())return"ERROR: Not a git repository";let o=await Cg()||"(detached)",s=await hE();if(s.length===0)return`Branch: ${o}
457
457
  Clean working tree (no changes)`;let r=[`Branch: ${o}`,`Changed files (${s.length}):`];for(let i of s){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(`
458
458
  `)}case"git_diff":{if(!await Dl())return"ERROR: Not a git repository";let o;if(e.file){let s=["diff"];e.staged&&s.push("--cached"),s.push("--",e.file);try{o=execFileSync("git",s,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()}catch{o=""}}else o=await mE(!!e.staged);return o||"(no diff)"}case"git_log":{if(!await Dl())return"ERROR: Not a git repository";let s=["log","--oneline",`-${Math.min(e.count||10,50)}`];e.file&&s.push("--",e.file);try{return execFileSync("git",s,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()||"(no commits)"}catch{return"(no commits)"}}case"task_list":{let{createTasks:o,updateTask:s,getTaskList:r,renderTaskList:i,hasActiveTasks:a}=gl(),{getActiveTaskProgress:c}=rt(),u=c();switch(e.action){case"create":{if(!e.name||!e.tasks)return"ERROR: task_list create requires name and tasks";let l=o(e.name,e.tasks);return u||console.log(`
459
459
  `+i()),`Created task list "${e.name}" with ${l.length} tasks:
@@ -465,7 +465,7 @@ Clean working tree (no changes)`;let r=[`Branch: ${o}`,`Changed files (${s.lengt
465
465
  `)[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 fs("gh",["run","view",String(e.run_id),"--log"],{cwd:process.cwd(),timeout:6e4,maxBuffer:5242880});return i.substring(0,8e3)+(i.length>8e3?`
466
466
  ...(truncated)`:"")}let{stdout:o}=await fs("gh",["run","view",String(e.run_id),"--json","status,conclusion,name,headBranch,createdAt,updatedAt,jobs"],{cwd:process.cwd(),timeout:3e4}),s=JSON.parse(o),r=[`Run: ${s.name} [${e.run_id}]`,`Branch: ${s.headBranch} Status: ${s.conclusion||s.status}`,`Started: ${s.createdAt} Finished: ${s.updatedAt||"\u2014"}`,"","Jobs:"];for(let i of s.jobs||[]){let a=i.conclusion==="success"?"\u2713":i.conclusion==="failure"?"\u2717":"\u25CB";r.push(` ${a} ${i.name} (${i.conclusion||i.status})`);for(let c of i.steps||[]){if(c.conclusion==="failure"||c.conclusion==="skipped")continue;let u=c.conclusion==="success"?" \u2713":c.conclusion==="failure"?" \u2717":" \u25CB";r.push(` ${u} ${c.name}`)}}return r.join(`
467
467
  `)}catch(o){return`ERROR: ${(o.stderr||o.message||"").toString().split(`
468
- `)[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:o}=No(),s=e.branch||await Rg()||"main";if(!/^[\w./-]+$/.test(s))return"ERROR: invalid branch name";let r=["workflow","run",e.workflow,"--ref",s];if(e.inputs)for(let[a,c]of Object.entries(e.inputs)){if(!/^[\w-]+$/.test(a))return`ERROR: invalid input key: ${a}`;r.push("-f",`${a}=${c}`)}if(console.log(`
468
+ `)[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:o}=No(),s=e.branch||await Cg()||"main";if(!/^[\w./-]+$/.test(s))return"ERROR: invalid branch name";let r=["workflow","run",e.workflow,"--ref",s];if(e.inputs)for(let[a,c]of Object.entries(e.inputs)){if(!/^[\w-]+$/.test(a))return`ERROR: invalid input key: ${a}`;r.push("-f",`${a}=${c}`)}if(console.log(`
469
469
  ${pe.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${s}${pe.reset}`),!await o(" Trigger?"))return"CANCELLED: User declined to trigger workflow.";try{return await fs("gh",r,{cwd:process.cwd(),timeout:3e4}),`Workflow "${e.workflow}" triggered on branch "${s}". Check status with gh_run_list.`}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
470
470
  `)[0]}`}}case"k8s_pods":{let o=e.namespace?`-n ${e.namespace}`:"-A",s=e.label?`-l ${e.label}`:"",r=ir(`get pods ${o} ${s} -o wide`.trim(),e);try{let{stdout:i,stderr:a}=await Ye(r,{timeout:3e4,maxBuffer:2097152});return(i||a||"(no pods)").trim()}catch(i){let a=(i.stderr||i.message||"").toString().split(`
471
471
  `)[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 o=e.namespace||"default",s=e.tail||100,r=`logs ${e.pod} -n ${o} --tail=${s}`;e.since&&(r+=` --since=${e.since}`),e.container&&(r+=` -c ${e.container}`);let i=ir(r,e);try{let{stdout:a,stderr:c}=await Ye(i,{timeout:6e4,maxBuffer:5242880}),u=(a||c||"(no logs)").trim();return u.substring(0,2e4)+(u.length>2e4?`
@@ -499,7 +499,7 @@ ${f||p||"(no output)"}`}let h=/\bgrep\b/.test(s),g=p;h&&(g=g.split(`
499
499
  `));let S=4,A=g.split(`
500
500
  `),E=[],v=0;for(;v<A.length;){let N=v+1;for(;N<A.length&&A[N]===A[v];)N++;let ne=N-v;if(E.push(A[v]),ne>S)E.push(`... (${ne-1} identical lines omitted)`);else for(let oe=1;oe<ne;oe++)E.push(A[v]);v=N}return E.join(`
501
501
  `)||"(command completed, no output)"}case"ssh_upload":{if(!e.server||!e.local_path||!e.remote_path)return"ERROR: server, local_path, and remote_path are required";let o;try{o=qt(e.server)}catch(i){return`ERROR: ${i.message}`}let s=o.user?`${o.user}@${o.host}`:o.host;if(console.log(`
502
- ${pe.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${s}:${e.remote_path}${pe.reset}`),!await Jt(" Upload to remote server?"))return"CANCELLED: User declined upload.";try{let i=await $E(o,e.local_path,e.remote_path);try{Ks().clearRemoteIndex()}catch{}return i}catch(i){return`ERROR: ${i.message}`}}case"ssh_download":{if(!e.server||!e.remote_path||!e.local_path)return"ERROR: server, remote_path, and local_path are required";let o;try{o=qt(e.server)}catch(s){return`ERROR: ${s.message}`}try{return await Ng(o,e.remote_path,e.local_path)}catch(s){if(/no such file|not found/i.test(s.message))try{let{remoteAutoFixPath:r}=Ks(),i=e.remote_path.split("/").slice(0,-1).join("/")||"/",a=await r(o,i,e.remote_path);if(a.fixedPath){console.log(`${pe.dim} \u2713 remote auto-fix: ${e.remote_path} \u2192 ${a.fixedPath}${pe.reset}`);let c=await Ng(o,a.fixedPath,e.local_path);return`${a.message}
502
+ ${pe.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${s}:${e.remote_path}${pe.reset}`),!await Jt(" Upload to remote server?"))return"CANCELLED: User declined upload.";try{let i=await $E(o,e.local_path,e.remote_path);try{Ks().clearRemoteIndex()}catch{}return i}catch(i){return`ERROR: ${i.message}`}}case"ssh_download":{if(!e.server||!e.remote_path||!e.local_path)return"ERROR: server, remote_path, and local_path are required";let o;try{o=qt(e.server)}catch(s){return`ERROR: ${s.message}`}try{return await Mg(o,e.remote_path,e.local_path)}catch(s){if(/no such file|not found/i.test(s.message))try{let{remoteAutoFixPath:r}=Ks(),i=e.remote_path.split("/").slice(0,-1).join("/")||"/",a=await r(o,i,e.remote_path);if(a.fixedPath){console.log(`${pe.dim} \u2713 remote auto-fix: ${e.remote_path} \u2192 ${a.fixedPath}${pe.reset}`);let c=await Mg(o,a.fixedPath,e.local_path);return`${a.message}
503
503
  ${c}`}if(a.message)return`ERROR: ${s.message}
504
504
 
505
505
  ${a.message}`}catch{}return`ERROR: ${s.message}`}}case"remote_agent":{let o=require("path").join(process.cwd(),".nex","servers.json"),s=null;try{s=JSON.parse(require("fs").readFileSync(o,"utf-8"))[e.server]||null}catch{}let r=s?`${s.user||"root"}@${s.host}`:e.server,i=s?.key?["-i",s.key]:[],a=(e.project_path||s?.home||"~").replace(/[^a-zA-Z0-9_/~.-]/g,""),c=(e.model||"").replace(/[^a-zA-Z0-9_:.-]/g,""),l=['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`,c?`nex-code --prompt-file "$TMPFILE" --auto --model "${c}" 2>&1`:'nex-code --prompt-file "$TMPFILE" --auto 2>&1',"EXIT_CODE=$?",'rm -f "$TMPFILE"',"exit $EXIT_CODE"].join(" && "),{spawnSync:d}=require("child_process"),f=d("ssh",[...i,"-o","StrictHostKeyChecking=yes","-o","ConnectTimeout=10",r,`bash -c '${l}'`],{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}.
@@ -594,7 +594,7 @@ ${d}`:d}case"network_status":{let c="ss -tlnp 2>/dev/null || netstat -tlnp 2>/de
594
594
  ${u}`:u}case"package":{if(!e.package_action)return"ERROR: package_action is required for action=package";let{out:c}=await r("which dnf 2>/dev/null && echo dnf || (which apt-get 2>/dev/null && echo apt) || echo unknown",1e4),u=c.includes("dnf")?"dnf":c.includes("apt")?"apt":null;if(!u)return"ERROR: No supported package manager found (dnf/apt)";let l=e.packages||[];if(!l.every(IE))return"ERROR: package names contain unsafe characters";let d=l.map(Ae).join(" "),f;switch(e.package_action){case"list":f=u==="dnf"?"dnf list installed 2>/dev/null | head -60":"dpkg -l | head -60";break;case"check":{let g=u==="dnf"?'dnf check-update 2>/dev/null; EC=$?; [ $EC -eq 100 ] && echo "EXIT_STATUS: updates_available" || ([ $EC -eq 0 ] && echo "EXIT_STATUS: up_to_date" || echo "EXIT_STATUS: error $EC")':"apt-get -s upgrade 2>/dev/null | tail -5",{out:w}=await r(g,6e4);return w||"(no output from package check)"}case"install":if(!d)return"ERROR: packages required for install";f=u==="dnf"?`dnf install -y ${d}`:`apt-get install -y ${d}`;break;case"remove":if(!d)return"ERROR: packages required for remove";f=u==="dnf"?`dnf remove -y ${d}`:`apt-get remove -y ${d}`;break;case"update":if(!d)return"ERROR: packages required for update (use upgrade for full system upgrade)";f=u==="dnf"?`dnf update -y ${d}`:`apt-get install -y --only-upgrade ${d}`;break;case"upgrade":f=u==="dnf"?"dnf upgrade -y":"DEBIAN_FRONTEND=noninteractive apt-get upgrade -y";break;default:return`ERROR: Unknown package_action: ${e.package_action}`}let{out:p,exitCode:h}=await r(f,12e4);return h!==0?`EXIT ${h}
595
595
  ${p}`:p||`${e.package_action} OK`}case"user_manage":{if(!e.user_action)return"ERROR: user_action is required for action=user_manage";switch(e.user_action){case"list":{let c=`awk -F: '$3 >= 1000 && $1 != "nobody" {print $1, "uid="$3, "gid="$4, "shell="$7}' /etc/passwd`,{out:u,exitCode:l}=await r(c,1e4);return l!==0?`EXIT ${l}
596
596
  ${u}`:u||"(no regular users)"}case"info":{if(!e.user)return"ERROR: user is required for user_action=info";let c=rr(e.user);if(c)return c;let u=Ae(e.user),l=`id ${u} && echo '--- Groups ---' && groups ${u} && echo '--- Last login ---' && lastlog -u ${u} 2>/dev/null`,{out:d,exitCode:f}=await r(l,1e4);return f!==0?`EXIT ${f}
597
- ${d}`:d}case"create":{if(!e.user)return"ERROR: user is required for user_action=create";let c=rr(e.user);if(c)return c;if(!(e.groups||[]).every(Wg))return"ERROR: groups contain unsafe characters";let u=(e.groups||[]).map(h=>`-G ${Ae(h)}`).join(" "),l=Ae(e.user),d=`useradd -m ${u} ${l} && echo "User ${e.user} created"`,{out:f,exitCode:p}=await r(d,15e3);return p!==0?`EXIT ${p}
597
+ ${d}`:d}case"create":{if(!e.user)return"ERROR: user is required for user_action=create";let c=rr(e.user);if(c)return c;if(!(e.groups||[]).every(Hg))return"ERROR: groups contain unsafe characters";let u=(e.groups||[]).map(h=>`-G ${Ae(h)}`).join(" "),l=Ae(e.user),d=`useradd -m ${u} ${l} && echo "User ${e.user} created"`,{out:f,exitCode:p}=await r(d,15e3);return p!==0?`EXIT ${p}
598
598
  ${f}`:f}case"delete":{if(!e.user)return"ERROR: user is required for user_action=delete";let c=rr(e.user);if(c)return c;let l=`userdel -r ${Ae(e.user)} && echo "User ${e.user} deleted"`,{out:d,exitCode:f}=await r(l,15e3);return f!==0?`EXIT ${f}
599
599
  ${d}`:d}case"add_ssh_key":{if(!e.user)return"ERROR: user is required for user_action=add_ssh_key";if(!e.ssh_key)return"ERROR: ssh_key is required for user_action=add_ssh_key";let c=rr(e.user);if(c)return c;let l=`${`/home/${e.user}`}/.ssh`,d=`${l}/authorized_keys`,f=Ae(e.user),p=`mkdir -p ${Ae(l)} && chmod 700 ${Ae(l)} && printf '%s
600
600
  ' ${Ae(e.ssh_key)} >> ${Ae(d)} && chmod 600 ${Ae(d)} && chown -R ${Ae(`${e.user}:${e.user}`)} ${Ae(l)} && echo "SSH key added for ${e.user}"`,{out:h,exitCode:g}=await r(p,15e3);return g!==0?`EXIT ${g}
@@ -631,7 +631,7 @@ ${l}`:l||"(empty log)"}case"find_large":{let c=e.path||"/",u=e.limit||20,l=e.min
631
631
  ${f}`:f||`(no files larger than ${l} in ${c})`}case"service":{if(!e.service_action)return"ERROR: service_action is required for action=service";if(e.service_action!=="list_failed"&&!e.service_name)return"ERROR: service_name is required (except for list_failed)";if(e.service_name){let p=Wl(e.service_name,"service_name");if(p)return p}let c=e.service_name?e.service_name.includes(".")?e.service_name:`${e.service_name}.service`:"",u;switch(e.service_action){case"status":u=`systemctl status ${c} --no-pager -l 2>&1 | head -40`;break;case"list_failed":u="systemctl list-units --state=failed --no-legend 2>/dev/null";break;case"start":u=`systemctl start ${c} && systemctl status ${c} --no-pager -l 2>&1 | head -20`;break;case"stop":u=`systemctl stop ${c} && echo "${c} stopped"`;break;case"restart":u=`systemctl restart ${c} && systemctl status ${c} --no-pager -l 2>&1 | head -20`;break;case"reload":u=`systemctl reload ${c} 2>&1 || systemctl reload-or-restart ${c} 2>&1`;break;case"enable":u=`systemctl enable ${c} && echo "${c} enabled"`;break;case"disable":u=`systemctl disable ${c} && echo "${c} disabled"`;break;default:return`ERROR: Unknown service_action: ${e.service_action}`}let{out:l,exitCode:d}=await r(u,3e4);return d===0||e.service_action==="status"&&d===3?l||`service ${e.service_action} OK`:`EXIT ${d}
632
632
  ${l}`}case"kill_process":{if(!e.pid&&!e.process_name)return"ERROR: pid or process_name is required for kill_process";let c=e.signal||"SIGTERM";if(!jE(c))return"ERROR: signal contains unsafe characters";let u;if(e.pid){if(!/^\d+$/.test(String(e.pid)))return"ERROR: pid must be numeric";u=`ps -p ${e.pid} -o pid,user,%cpu,%mem,etime,cmd 2>/dev/null && kill -${c} ${e.pid} && echo "Sent ${c} to PID ${e.pid}"`}else u=`pgrep -a ${Ae(e.process_name)} 2>/dev/null | head -5 && pkill -${c} ${Ae(e.process_name)} && echo "Sent ${c} to all '${e.process_name}' processes"`;let{out:l,exitCode:d}=await r(u,15e3);return d!==0?`EXIT ${d}
633
633
  ${l}`:l}case"journalctl":{let c=e.lines||100,u=["journalctl","--no-pager","-n",String(c)];e.unit&&u.push("-u",e.unit.includes(".")?e.unit:`${e.unit}.service`),e.priority&&u.push("-p",e.priority),e.since&&u.push(`--since="${e.since}"`),u.push('2>/dev/null || echo "(journalctl not available)"');let{out:l,exitCode:d}=await r(u.join(" "),2e4);return d!==0?`EXIT ${d}
634
- ${l}`:l||"(no log entries)"}default:return`ERROR: Unknown sysadmin action: ${e.action}`}}case"save_memory":{let{saveMemory:o}=er(),s=o(e.type,e.name,e.content,e.description);return s.ok?s.updated===!1?`Memory unchanged (duplicate): ${e.type}/${e.name}`:`Memory saved: ${e.type}/${e.name} \u2192 ${s.path}`:`ERROR: ${s.error}`}case"delete_memory":{let{deleteMemory:o}=er();return o(e.type,e.name)?`Memory deleted: ${e.type}/${e.name}`:`Memory not found: ${e.type}/${e.name}`}default:{let{executePluginTool:o}=gi(),s=await o(t,e,n);return s!==null?s:`ERROR: Unknown tool: ${t}`}}}async function qE(t,e,n={}){let{emit:o}=gi(),{logToolExecution:s}=Eg(),r=Date.now(),i=n.silent?null:pE(t,e);if(!i){let c=await jg(t,e,n);return s({tool:t,args:e,result:c,duration:Date.now()-r,success:!c.startsWith?.("ERROR")}),await o("onToolResult",{tool:t,args:e,result:c}),c}let a=new fE(i);a.start();try{let c=await jg(t,e,n);return a.stop(),s({tool:t,args:e,result:c,duration:Date.now()-r,success:!c.startsWith?.("ERROR")}),await o("onToolResult",{tool:t,args:e,result:c}),c}catch(c){throw a.stop(),s({tool:t,args:e,result:c.message,duration:Date.now()-r,success:!1}),c}}Hg.exports={TOOL_DEFINITIONS:DE,executeTool:qE,resolvePath:ut,autoFixPath:Ji,autoFixEdit:Ug,enrichBashError:Bg,cancelPendingAskUser:CE,setAskUserHandler:AE,fileExists:At}});var zs=Q((kO,Gg)=>{Gg.exports=Yg()});var zl=Q((SO,Kg)=>{var{loadServerProfiles:ro,resolveProfile:vO,sshExec:FE}=Ks(),BE=/\.(?:png|jpe?g|gif|webp|bmp|svg|ico|pdf|mp4|webm|mov)(?:[?#].*)?$/i,UE=/\b(bug|issue|problem|broken|failing|fails|error|wrong|regression|debug|investigate|why|slow|fix|delete|deleted|deleting|removed|reappears?|returns?|comes?\s+back|webui|production|prod|server|fehler|kaputt|lösche|loesch|gelösch|geloesch|zurück|zurueck|taucht?\s+wieder\s+auf)\b/i,WE=/https?:\/\/[^\s)]+/gi;function HE(t){if(typeof t!="string")return[];let e=new Set,n=[];for(let o of t.match(WE)||[]){let s=o.replace(/[.,;!?]+$/g,"");e.has(s)||(e.add(s),n.push(s))}return n}function YE(t,e){let n;try{n=new URL(t).hostname.toLowerCase()}catch{return null}let o=n.split(".");for(let[s,r]of Object.entries(e))if(o.includes(s.toLowerCase()))return{matchedName:s,matchedProfile:r,hostname:n};for(let[s,r]of Object.entries(e))if(String(r.host||"").toLowerCase()===n)return{matchedName:s,matchedProfile:r,hostname:n};return{matchedName:null,matchedProfile:null,hostname:n}}function zg(t,e=ro()){if(typeof t!="string"||!UE.test(t))return null;let n=HE(t).filter(o=>!BE.test(o));if(n.length===0)return null;for(let o of n){let s=YE(o,e);if(s)return{url:o,hostname:s.hostname,matchedName:s.matchedName,matchedProfile:s.matchedProfile,shouldPreferBrowser:!0,shouldPreferSsh:!!(s.matchedName&&s.matchedProfile)}}return null}var 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 GE(){let t=ro();if(Object.keys(t).length===0)return null;let n=["## Remote Servers (.nex/servers.json)"];n.push(""),n.push("Available server profiles (use with ssh_exec, ssh_upload, ssh_download, service_manage, service_logs, container_list, container_logs, container_exec, container_manage, deploy):");for(let[s,r]of Object.entries(t)){let i=r.user?`${r.user}@${r.host}`:r.host,a=r.port&&Number(r.port)!==22?`:${r.port}`:"",c=r.os?` \u2014 OS: ${r.os}`:"",u=r.sudo?", sudo available":"";n.push(`- **${s}**: ${i}${a}${c}${u}`)}let o=new Set;for(let s of Object.values(t))s.os&&Gl[s.os]&&o.add(s.os);if(o.size>0){n.push("");for(let s of o){let r={almalinux9:"AlmaLinux 9",almalinux8:"AlmaLinux 8",ubuntu:"Ubuntu",debian:"Debian",macos:"macOS"}[s]||s;n.push(`### ${r} Notes`);for(let i of Gl[s])n.push(`- ${i}`)}}return n.join(`
634
+ ${l}`:l||"(no log entries)"}default:return`ERROR: Unknown sysadmin action: ${e.action}`}}case"save_memory":{let{saveMemory:o}=er(),s=o(e.type,e.name,e.content,e.description);return s.ok?s.updated===!1?`Memory unchanged (duplicate): ${e.type}/${e.name}`:`Memory saved: ${e.type}/${e.name} \u2192 ${s.path}`:`ERROR: ${s.error}`}case"delete_memory":{let{deleteMemory:o}=er();return o(e.type,e.name)?`Memory deleted: ${e.type}/${e.name}`:`Memory not found: ${e.type}/${e.name}`}default:{let{executePluginTool:o}=gi(),s=await o(t,e,n);return s!==null?s:`ERROR: Unknown tool: ${t}`}}}async function qE(t,e,n={}){let{emit:o}=gi(),{logToolExecution:s}=Tg(),r=Date.now(),i=n.silent?null:pE(t,e);if(!i){let c=await Dg(t,e,n);return s({tool:t,args:e,result:c,duration:Date.now()-r,success:!c.startsWith?.("ERROR")}),await o("onToolResult",{tool:t,args:e,result:c}),c}let a=new fE(i);a.start();try{let c=await Dg(t,e,n);return a.stop(),s({tool:t,args:e,result:c,duration:Date.now()-r,success:!c.startsWith?.("ERROR")}),await o("onToolResult",{tool:t,args:e,result:c}),c}catch(c){throw a.stop(),s({tool:t,args:e,result:c.message,duration:Date.now()-r,success:!1}),c}}Yg.exports={TOOL_DEFINITIONS:DE,executeTool:qE,resolvePath:ut,autoFixPath:Ji,autoFixEdit:Wg,enrichBashError:Ug,cancelPendingAskUser:CE,setAskUserHandler:AE,fileExists:At}});var zs=Q((vO,zg)=>{zg.exports=Gg()});var zl=Q((EO,Xg)=>{var{loadServerProfiles:ro,resolveProfile:SO,sshExec:FE}=Ks(),BE=/\.(?:png|jpe?g|gif|webp|bmp|svg|ico|pdf|mp4|webm|mov)(?:[?#].*)?$/i,UE=/\b(bug|issue|problem|broken|failing|fails|error|wrong|regression|debug|investigate|why|slow|fix|delete|deleted|deleting|removed|reappears?|returns?|comes?\s+back|webui|production|prod|server|fehler|kaputt|lösche|loesch|gelösch|geloesch|zurück|zurueck|taucht?\s+wieder\s+auf)\b/i,WE=/https?:\/\/[^\s)]+/gi;function HE(t){if(typeof t!="string")return[];let e=new Set,n=[];for(let o of t.match(WE)||[]){let s=o.replace(/[.,;!?]+$/g,"");e.has(s)||(e.add(s),n.push(s))}return n}function YE(t,e){let n;try{n=new URL(t).hostname.toLowerCase()}catch{return null}let o=n.split(".");for(let[s,r]of Object.entries(e))if(o.includes(s.toLowerCase()))return{matchedName:s,matchedProfile:r,hostname:n};for(let[s,r]of Object.entries(e))if(String(r.host||"").toLowerCase()===n)return{matchedName:s,matchedProfile:r,hostname:n};return{matchedName:null,matchedProfile:null,hostname:n}}function Kg(t,e=ro()){if(typeof t!="string"||!UE.test(t))return null;let n=HE(t).filter(o=>!BE.test(o));if(n.length===0)return null;for(let o of n){let s=YE(o,e);if(s)return{url:o,hostname:s.hostname,matchedName:s.matchedName,matchedProfile:s.matchedProfile,shouldPreferBrowser:!0,shouldPreferSsh:!!(s.matchedName&&s.matchedProfile)}}return null}var 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 GE(){let t=ro();if(Object.keys(t).length===0)return null;let n=["## Remote Servers (.nex/servers.json)"];n.push(""),n.push("Available server profiles (use with ssh_exec, ssh_upload, ssh_download, service_manage, service_logs, container_list, container_logs, container_exec, container_manage, deploy):");for(let[s,r]of Object.entries(t)){let i=r.user?`${r.user}@${r.host}`:r.host,a=r.port&&Number(r.port)!==22?`:${r.port}`:"",c=r.os?` \u2014 OS: ${r.os}`:"",u=r.sudo?", sudo available":"";n.push(`- **${s}**: ${i}${a}${c}${u}`)}let o=new Set;for(let s of Object.values(t))s.os&&Gl[s.os]&&o.add(s.os);if(o.size>0){n.push("");for(let s of o){let r={almalinux9:"AlmaLinux 9",almalinux8:"AlmaLinux 8",ubuntu:"Ubuntu",debian:"Debian",macos:"macOS"}[s]||s;n.push(`### ${r} Notes`);for(let i of Gl[s])n.push(`- ${i}`)}}return n.join(`
635
635
  `)}function zE(t){let e=ro();return Object.values(e).some(n=>n.os&&n.os.startsWith(t))}function KE(){return Object.keys(ro())}function XE(){let t=require("fs"),n=require("path").join(process.cwd(),"NEX.md"),o="";try{o=t.readFileSync(n,"utf-8")}catch{}let s=ro(),r=Object.keys(s);if(r.length===0)return null;let i=["server","deploy","remote","ssh","service","systemctl","production","linux","almalinux","ubuntu","debian"],a=o.toLowerCase();if(!i.some(f=>a.includes(f)))return null;let u=r.map(f=>{let p=s[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(`
636
636
  `),l=r.map(f=>s[f].log_path).filter(Boolean),d=l.length>0?`
637
637
  - Server log paths: ${l.join(", ")}`:"";return`# Deployment Context (Auto-detected)
@@ -662,11 +662,11 @@ ${u}
662
662
  - 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.
663
663
  - 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.
664
664
  - 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.
665
- - 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 JE(t){let e=ro(),n=zg(t,e);if(!n?.matchedProfile||!n?.matchedName)return null;let{matchedProfile:o,matchedName:s}=n,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 FE(o,r,{timeout:4e3});if(!i||i.trim().length<5)return null;let a=o.user?`${o.user}@${o.host}`:o.host;return`[Server context for "${s}" (${a}) \u2014 probed at task start]
666
- `+i.trim()}catch{return null}}Kg.exports={getServerContext:GE,getDeploymentContextBlock:XE,hasServerOS:zE,getProfileNames:KE,probeUrlServer:JE,detectRuntimeDebugTarget:zg,OS_HINTS:Gl}});var Zg=Q((EO,Jg)=>{var $t=require("fs").promises,Qi=require("fs"),Ge=require("path"),Zi=require("util").promisify(require("child_process").exec),{C:io}=rt(),{getMergeConflicts:Vg}=di(),{getServerContext:ZE}=zl(),{refreshIndex:QE,getFileIndex:eT,buildContentIndex:tT,summarizeModuleHubs:nT}=cn(),sT=new Set(["node_modules",".git",".svn","dist","build","coverage",".nyc_output","__pycache__",".DS_Store",".next",".nuxt",".turbo",".cache","vendor","tmp","temp"]),oT=[{file:"tsconfig.json",label:"TypeScript"},{file:"jest.config.js",label:"Jest"},{file:"jest.config.cjs",label:"Jest"},{file:"jest.config.mjs",label:"Jest"},{file:"vitest.config.js",label:"Vitest"},{file:"vitest.config.ts",label:"Vitest"},{file:"vite.config.js",label:"Vite"},{file:"vite.config.ts",label:"Vite"},{file:"next.config.js",label:"Next.js"},{file:"next.config.mjs",label:"Next.js"},{file:"tailwind.config.js",label:"Tailwind"},{file:"tailwind.config.ts",label:"Tailwind"},{file:"docker-compose.yml",label:"Docker Compose"},{file:"docker-compose.yaml",label:"Docker Compose"},{file:".github/workflows",label:"GitHub Actions"}];function rT(t,e=6){let n=new Map;for(let o of t){let s=o.includes("/")?o.split("/")[0]:"(root)";!s||s.startsWith(".")||n.set(s,(n.get(s)||0)+1)}return[...n.entries()].sort((o,s)=>s[1]-o[1]||o[0].localeCompare(s[0])).slice(0,e).map(([o,s])=>`${o} (${s})`)}function iT(t){let e=new Set(t),n=new Set;for(let o of oT)(e.has(o.file)||[...e].some(s=>s.startsWith(`${o.file}/`)))&&n.add(o.label);return e.has("package.json")&&n.add("Node.js"),[...e].some(o=>/^tests?\//.test(o)||/\.test\./.test(o)||/\.spec\./.test(o))&&n.add("Tests"),[...e].some(o=>o.startsWith("vscode/"))&&n.add("VS Code Extension"),[...n]}function aT(t){let e=["package.json","cli/index.js","src/index.ts","src/index.js","index.ts","index.js","bin/nex-code.js","dist/nex-code.js","README.md"],n=[];for(let o of e)if(t.includes(o)&&n.push(o),n.length>=5)break;return n}function cT(t,e=6){let n=t.filter(r=>/^tests?\//.test(r)||/\.test\./.test(r)||/\.spec\./.test(r));if(n.length===0)return[];let o=t.filter(r=>!/^tests?\//.test(r)&&!/\.test\./.test(r)&&!/\.spec\./.test(r)&&/\.(js|jsx|ts|tsx|py|go|rs|java)$/.test(r)),s=[];for(let r of o){let i=Ge.basename(r).replace(/\.[^.]+$/,"");if(i.length<3)continue;let a=n.filter(c=>c.includes(i));if(a.length>0&&s.push(`${r} -> ${a.slice(0,2).join(", ")}`),s.length>=e)break}return s}function lT(t){return!t||!t.workspaces?[]:Array.isArray(t.workspaces)?t.workspaces:Array.isArray(t.workspaces.packages)?t.workspaces.packages:[]}async function uT(t){try{await QE(t);let e=eT();if(!e||e.length===0)return"";let n=iT(e),o=rT(e),s=aT(e),r=e.filter(d=>/^tests?\//.test(d)||/\.test\./.test(d)||/\.spec\./.test(d)).length,i=cT(e),a=[];try{let d=Ge.join(t,"package.json");if(Qi.existsSync(d)){let f=JSON.parse(Qi.readFileSync(d,"utf-8"));a=lT(f)}}catch{}let c="",u="";try{let d=await tT(t),f=Object.entries(d.files||{}).map(([p,h])=>({file:p,defs:Array.isArray(h.defs)?h.defs.length:0})).filter(p=>p.defs>0).sort((p,h)=>h.defs-p.defs||p.file.localeCompare(h.file)).slice(0,4).map(p=>`${p.file} (${p.defs} defs)`);f.length>0&&(c=`CODE HOTSPOTS: ${f.join(", ")}`)}catch{}try{let d=await nT(t,4);d.length>0&&(u=`MODULE HUBS: ${d.join(", ")}`)}catch{}let l=[`REPO MAP: ${e.length} indexed files${n.length?` | stack: ${n.join(", ")}`:""}`];return o.length>0&&l.push(`WORK AREAS: ${o.join(", ")}`),s.length>0&&l.push(`LIKELY ENTRY POINTS: ${s.join(", ")}`),a.length>0&&l.push(`WORKSPACES: ${a.join(", ")}`),r>0&&l.push(`TEST FOOTPRINT: ${r} test files detected`),i.length>0&&l.push(`TEST MAP: ${i.join(" | ")}`),c&&l.push(c),u&&l.push(u),l.push("RETRIEVAL RULE: Prefer the smallest verified path set first \u2014 identify likely files, then read only the exact symbols/sections you need before editing."),l.join(`
665
+ - 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 JE(t){let e=ro(),n=Kg(t,e);if(!n?.matchedProfile||!n?.matchedName)return null;let{matchedProfile:o,matchedName:s}=n,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 FE(o,r,{timeout:4e3});if(!i||i.trim().length<5)return null;let a=o.user?`${o.user}@${o.host}`:o.host;return`[Server context for "${s}" (${a}) \u2014 probed at task start]
666
+ `+i.trim()}catch{return null}}Xg.exports={getServerContext:GE,getDeploymentContextBlock:XE,hasServerOS:zE,getProfileNames:KE,probeUrlServer:JE,detectRuntimeDebugTarget:Kg,OS_HINTS:Gl}});var Qg=Q((TO,Zg)=>{var $t=require("fs").promises,Qi=require("fs"),Ge=require("path"),Zi=require("util").promisify(require("child_process").exec),{C:io}=rt(),{getMergeConflicts:Jg}=di(),{getServerContext:ZE}=zl(),{refreshIndex:QE,getFileIndex:eT,buildContentIndex:tT,summarizeModuleHubs:nT}=cn(),sT=new Set(["node_modules",".git",".svn","dist","build","coverage",".nyc_output","__pycache__",".DS_Store",".next",".nuxt",".turbo",".cache","vendor","tmp","temp"]),oT=[{file:"tsconfig.json",label:"TypeScript"},{file:"jest.config.js",label:"Jest"},{file:"jest.config.cjs",label:"Jest"},{file:"jest.config.mjs",label:"Jest"},{file:"vitest.config.js",label:"Vitest"},{file:"vitest.config.ts",label:"Vitest"},{file:"vite.config.js",label:"Vite"},{file:"vite.config.ts",label:"Vite"},{file:"next.config.js",label:"Next.js"},{file:"next.config.mjs",label:"Next.js"},{file:"tailwind.config.js",label:"Tailwind"},{file:"tailwind.config.ts",label:"Tailwind"},{file:"docker-compose.yml",label:"Docker Compose"},{file:"docker-compose.yaml",label:"Docker Compose"},{file:".github/workflows",label:"GitHub Actions"}];function rT(t,e=6){let n=new Map;for(let o of t){let s=o.includes("/")?o.split("/")[0]:"(root)";!s||s.startsWith(".")||n.set(s,(n.get(s)||0)+1)}return[...n.entries()].sort((o,s)=>s[1]-o[1]||o[0].localeCompare(s[0])).slice(0,e).map(([o,s])=>`${o} (${s})`)}function iT(t){let e=new Set(t),n=new Set;for(let o of oT)(e.has(o.file)||[...e].some(s=>s.startsWith(`${o.file}/`)))&&n.add(o.label);return e.has("package.json")&&n.add("Node.js"),[...e].some(o=>/^tests?\//.test(o)||/\.test\./.test(o)||/\.spec\./.test(o))&&n.add("Tests"),[...e].some(o=>o.startsWith("vscode/"))&&n.add("VS Code Extension"),[...n]}function aT(t){let e=["package.json","cli/index.js","src/index.ts","src/index.js","index.ts","index.js","bin/nex-code.js","dist/nex-code.js","README.md"],n=[];for(let o of e)if(t.includes(o)&&n.push(o),n.length>=5)break;return n}function cT(t,e=6){let n=t.filter(r=>/^tests?\//.test(r)||/\.test\./.test(r)||/\.spec\./.test(r));if(n.length===0)return[];let o=t.filter(r=>!/^tests?\//.test(r)&&!/\.test\./.test(r)&&!/\.spec\./.test(r)&&/\.(js|jsx|ts|tsx|py|go|rs|java)$/.test(r)),s=[];for(let r of o){let i=Ge.basename(r).replace(/\.[^.]+$/,"");if(i.length<3)continue;let a=n.filter(c=>c.includes(i));if(a.length>0&&s.push(`${r} -> ${a.slice(0,2).join(", ")}`),s.length>=e)break}return s}function lT(t){return!t||!t.workspaces?[]:Array.isArray(t.workspaces)?t.workspaces:Array.isArray(t.workspaces.packages)?t.workspaces.packages:[]}async function uT(t){try{await QE(t);let e=eT();if(!e||e.length===0)return"";let n=iT(e),o=rT(e),s=aT(e),r=e.filter(d=>/^tests?\//.test(d)||/\.test\./.test(d)||/\.spec\./.test(d)).length,i=cT(e),a=[];try{let d=Ge.join(t,"package.json");if(Qi.existsSync(d)){let f=JSON.parse(Qi.readFileSync(d,"utf-8"));a=lT(f)}}catch{}let c="",u="";try{let d=await tT(t),f=Object.entries(d.files||{}).map(([p,h])=>({file:p,defs:Array.isArray(h.defs)?h.defs.length:0})).filter(p=>p.defs>0).sort((p,h)=>h.defs-p.defs||p.file.localeCompare(h.file)).slice(0,4).map(p=>`${p.file} (${p.defs} defs)`);f.length>0&&(c=`CODE HOTSPOTS: ${f.join(", ")}`)}catch{}try{let d=await nT(t,4);d.length>0&&(u=`MODULE HUBS: ${d.join(", ")}`)}catch{}let l=[`REPO MAP: ${e.length} indexed files${n.length?` | stack: ${n.join(", ")}`:""}`];return o.length>0&&l.push(`WORK AREAS: ${o.join(", ")}`),s.length>0&&l.push(`LIKELY ENTRY POINTS: ${s.join(", ")}`),a.length>0&&l.push(`WORKSPACES: ${a.join(", ")}`),r>0&&l.push(`TEST FOOTPRINT: ${r} test files detected`),i.length>0&&l.push(`TEST MAP: ${i.join(" | ")}`),c&&l.push(c),u&&l.push(u),l.push("RETRIEVAL RULE: Prefer the smallest verified path set first \u2014 identify likely files, then read only the exact symbols/sections you need before editing."),l.join(`
667
667
  `)}catch{return""}}function dT(t){try{return Qi.readFileSync(t,"utf-8").split(`
668
668
  `).map(n=>n.trim()).filter(n=>n&&!n.startsWith("#")&&!n.startsWith("!")).map(n=>n.replace(/\/$/,""))}catch{return[]}}function fT(t,e){for(let n of e)if(n===t||n.includes("*")&&new RegExp("^"+n.replace(/\./g,"\\.").replace(/\*/g,".*")+"$").test(t))return!0;return!1}function pT(t,{maxDepth:e=3,maxFiles:n=200,giPatterns:o=[]}={}){let s=Ge.join(t,".gitignore"),r=[...o,...dT(s)],i=0,a=[Ge.basename(t)+"/"];function c(u,l,d){if(d>e||i>=n)return;let f;try{f=Qi.readdirSync(u,{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=>!(sT.has(h.name)||h.name.startsWith(".")&&h.name!==".env.example"||fT(h.name,r)));for(let h=0;h<p.length;h++){if(i>=n){a.push(`${l}\u2514\u2500\u2500 \u2026 (truncated)`);break}let g=p[h],w=h===p.length-1,_=w?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",S=l+(w?" ":"\u2502 "),A=g.isDirectory()?g.name+"/":g.name;a.push(`${l}${_}${A}`),i++,g.isDirectory()&&c(Ge.join(u,g.name),S,d+1)}}return c(t,"",1),a.join(`
669
- `)}var Kl=new Map,co=new Map,ea=null,Xg=3e4,ao={result:null,expiry:0,cwd:null};async function pn(t){try{return await t()}catch{return null}}async function hT(){if(!ea||Date.now()>ea)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 n=await $t.stat(e),o=co.get(e);if(!o||n.mtimeMs!==o)return!1}catch{if(co.has(e))return!1}try{let e=Ge.join(process.cwd(),".git","HEAD"),n=await $t.stat(e),o=co.get(e);if(!o||n.mtimeMs!==o)return!1}catch{}return!0}async function mT(){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 n=await $t.stat(e);co.set(e,n.mtimeMs)}catch{co.delete(e)}}async function gT(t){let e="fileContext",n=Kl.get(e),o=!1;if(n&&await hT()&&(o=!0),!o){let u=[],l=Ge.join(t,"package.json");if(await pn(()=>$t.access(l).then(()=>!0).catch(()=>!1)))try{let v=await $t.readFile(l,"utf-8"),N=JSON.parse(v),ne={name:N.name,version:N.version};N.scripts&&(ne.scripts=Object.keys(N.scripts).slice(0,15)),N.dependencies&&(ne.deps=Object.keys(N.dependencies).length),N.devDependencies&&(ne.devDeps=Object.keys(N.devDependencies).length),u.push(`PACKAGE: ${JSON.stringify(ne)}`)}catch{}let f=Ge.join(t,"README.md");if(await pn(()=>$t.access(f).then(()=>!0).catch(()=>!1))){let N=(await $t.readFile(f,"utf-8")).split(`
669
+ `)}var Kl=new Map,co=new Map,ea=null,Vg=3e4,ao={result:null,expiry:0,cwd:null};async function pn(t){try{return await t()}catch{return null}}async function hT(){if(!ea||Date.now()>ea)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 n=await $t.stat(e),o=co.get(e);if(!o||n.mtimeMs!==o)return!1}catch{if(co.has(e))return!1}try{let e=Ge.join(process.cwd(),".git","HEAD"),n=await $t.stat(e),o=co.get(e);if(!o||n.mtimeMs!==o)return!1}catch{}return!0}async function mT(){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 n=await $t.stat(e);co.set(e,n.mtimeMs)}catch{co.delete(e)}}async function gT(t){let e="fileContext",n=Kl.get(e),o=!1;if(n&&await hT()&&(o=!0),!o){let u=[],l=Ge.join(t,"package.json");if(await pn(()=>$t.access(l).then(()=>!0).catch(()=>!1)))try{let v=await $t.readFile(l,"utf-8"),N=JSON.parse(v),ne={name:N.name,version:N.version};N.scripts&&(ne.scripts=Object.keys(N.scripts).slice(0,15)),N.dependencies&&(ne.deps=Object.keys(N.dependencies).length),N.devDependencies&&(ne.devDeps=Object.keys(N.devDependencies).length),u.push(`PACKAGE: ${JSON.stringify(ne)}`)}catch{}let f=Ge.join(t,"README.md");if(await pn(()=>$t.access(f).then(()=>!0).catch(()=>!1))){let N=(await $t.readFile(f,"utf-8")).split(`
670
670
  `).slice(0,50);u.push(`README (first 50 lines):
671
671
  ${N.join(`
672
672
  `)}`)}let h=Ge.join(t,".gitignore");if(await pn(()=>$t.access(h).then(()=>!0).catch(()=>!1))){let v=await $t.readFile(h,"utf-8");u.push(`GITIGNORE:
@@ -674,24 +674,24 @@ ${v.trim()}`)}let w=Ge.join(t,"CLAUDE.md");if(await pn(()=>$t.access(w).then(()=
674
674
  ${v.trim()}`)}let S=Ge.join(t,".nex","CLAUDE.md");if(await pn(()=>$t.access(S).then(()=>!0).catch(()=>!1))){let v=await $t.readFile(S,"utf-8");v.trim()&&u.push(`PRIVATE PROJECT INSTRUCTIONS (.nex/CLAUDE.md):
675
675
  ${v.trim()}`)}let E=await uT(t);E&&u.push(E),n=u.join(`
676
676
 
677
- `),Kl.set(e,n),ea=Date.now()+Xg,await mT()}let s=[n],r,i,a,c;if(ao.result&&Date.now()<ao.expiry&&ao.cwd===t?{branch:r,status:i,log:a,conflicts:c}=ao.result:([r,i,a,c]=await Promise.all([pn(async()=>{let{stdout:u}=await Zi("git branch --show-current",{cwd:t,timeout:5e3});return u.trim()}),pn(async()=>{let{stdout:u}=await Zi("git status --short",{cwd:t,timeout:5e3});return u.trim()}),pn(async()=>{let{stdout:u}=await Zi("git log --oneline -5",{cwd:t,timeout:5e3});return u.trim()}),Vg()]),ao={result:{branch:r,status:i,log:a,conflicts:c},expiry:Date.now()+Xg,cwd:t}),r&&s.push(`GIT BRANCH: ${r}`),i&&s.push(`GIT STATUS:
677
+ `),Kl.set(e,n),ea=Date.now()+Vg,await mT()}let s=[n],r,i,a,c;if(ao.result&&Date.now()<ao.expiry&&ao.cwd===t?{branch:r,status:i,log:a,conflicts:c}=ao.result:([r,i,a,c]=await Promise.all([pn(async()=>{let{stdout:u}=await Zi("git branch --show-current",{cwd:t,timeout:5e3});return u.trim()}),pn(async()=>{let{stdout:u}=await Zi("git status --short",{cwd:t,timeout:5e3});return u.trim()}),pn(async()=>{let{stdout:u}=await Zi("git log --oneline -5",{cwd:t,timeout:5e3});return u.trim()}),Jg()]),ao={result:{branch:r,status:i,log:a,conflicts:c},expiry:Date.now()+Vg,cwd:t}),r&&s.push(`GIT BRANCH: ${r}`),i&&s.push(`GIT STATUS:
678
678
  ${i}`),a&&s.push(`RECENT COMMITS:
679
679
  ${a}`),c&&c.length>0){let u=c.map(l=>` ${l.file}`).join(`
680
680
  `);s.push(`MERGE CONFLICTS (resolve before editing these files):
681
681
  ${u}`)}try{let u=ZE();u&&s.push(u)}catch{}return s.join(`
682
682
 
683
- `)}async function yT(t){let e=Ge.join(t,"package.json"),n="";if(await pn(()=>$t.access(e).then(()=>!0).catch(()=>!1)))try{let i=await $t.readFile(e,"utf-8"),a=JSON.parse(i);n=`${a.name||"?"} v${a.version||"?"}`}catch{}let[s,r]=await Promise.all([pn(async()=>{let{stdout:i}=await Zi("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),Vg()]);if(r&&r.length>0){console.log(`${io.red} \u26A0 ${r.length} unresolved merge conflict(s):${io.reset}`);for(let i of r)console.log(`${io.red} ${i.file}${io.reset}`);console.log(`${io.yellow} \u2192 Resolve conflicts before starting tasks${io.reset}`)}console.log()}Jg.exports={gatherProjectContext:gT,printContext:yT,generateFileTree:pT,_clearContextCache:()=>{Kl.clear(),co.clear(),ea=null,ao={result:null,expiry:0,cwd:null}}}});var na=Q((TO,ty)=>{var Qt=require("fs"),ta=require("path"),{atomicWrite:wT}=Jn();function lr(){return ta.join(process.cwd(),".nex","sessions")}function Xl(){let t=lr();Qt.existsSync(t)||Qt.mkdirSync(t,{recursive:!0,mode:448})}function Vl(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return ta.join(lr(),`${e}.json`)}function Jl(t,e,n={}){Xl();let o=Vl(t),s={name:t,createdAt:n.createdAt||new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:e.length,model:n.model||null,provider:n.provider||null,messages:e};return wT(o,JSON.stringify(s,null,2)),{path:o,name:t}}function Qg(t){let e=Vl(t);if(!Qt.existsSync(e))return null;try{return JSON.parse(Qt.readFileSync(e,"utf-8"))}catch{return null}}function ey(){Xl();let t=lr(),e=Qt.readdirSync(t).filter(o=>o.endsWith(".json")),n=[];for(let o of e)try{let s=JSON.parse(Qt.readFileSync(ta.join(t,o),"utf-8"));n.push({name:s.name||o.replace(".json",""),createdAt:s.createdAt,updatedAt:s.updatedAt,messageCount:s.messageCount||0,model:s.model,provider:s.provider,score:s.score!=null?s.score:null,scoreGrade:s.scoreGrade||null})}catch{}return n.sort((o,s)=>(s.updatedAt||"").localeCompare(o.updatedAt||""))}function bT(t){let e=Vl(t);return Qt.existsSync(e)?(Qt.unlinkSync(e),!0):!1}function $T(){let t=ey();return t.length===0?null:Qg(t[0].name)}var hs=null,En=null,cr=null;function _T(t,e={}){t.length!==0&&(hs&&clearTimeout(hs),En=t,cr=e||{},hs=setTimeout(()=>{En&&En.length>0&&Jl("_autosave",En,cr),hs=null,En=null,cr=null},5e3))}function xT(){hs&&(clearTimeout(hs),hs=null),En&&En.length>0&&(Jl("_autosave",En,cr),En=null,cr=null)}function kT(){Xl();let t=lr(),e=Qt.readdirSync(t).filter(r=>r.endsWith(".json")),n=new Date,o=new Date(n.getTime()-720*60*60*1e3),s=0;for(let r of e){let i=ta.join(t,r);try{let a=Qt.statSync(i);new Date(a.mtime)<o&&(Qt.unlinkSync(i),s++)}catch{}}return s}ty.exports={saveSession:Jl,loadSession:Qg,listSessions:ey,deleteSession:bT,getLastSession:$T,autoSave:_T,flushAutoSave:xT,clearOldSessions:kT,_getSessionsDir:lr}});var sa=Q((RO,ly)=>{"use strict";var ur=require("fs"),ny=require("path");function sy(t){let e=[];return t.forEach((n,o)=>{n.role==="assistant"&&(Array.isArray(n.content)&&n.content.forEach(s=>{s&&s.type==="tool_use"&&e.push({name:s.name||"",input:s.input||{},index:o,id:s.id||null})}),Array.isArray(n.tool_calls)&&n.tool_calls.forEach(s=>{let r=s.function?.name||s.name||"",i={};try{i=typeof s.function?.arguments=="string"?JSON.parse(s.function.arguments):s.function?.arguments||s.input||{}}catch{}e.push({name:r,input:i,index:o,id:s.id||null})}))}),e}function vT(t){let e=new Set;return t.forEach(n=>{n.role==="tool"&&typeof n.content=="string"&&n.content.startsWith("BLOCKED:")&&n.tool_call_id&&e.add(n.tool_call_id),n.role==="user"&&Array.isArray(n.content)&&n.content.forEach(o=>{o&&o.type==="tool_result"&&o.tool_use_id&&typeof o.content=="string"&&o.content.startsWith("BLOCKED:")&&e.add(o.tool_use_id)})}),e}function oy(t){let e=[];return t.forEach((n,o)=>{if(n.role==="user"&&Array.isArray(n.content)&&n.content.forEach(s=>{if(s&&s.type==="tool_result"){let r=typeof s.content=="string"?s.content:Array.isArray(s.content)?s.content.map(i=>typeof i=="string"?i:i.text||"").join(""):JSON.stringify(s.content||"");e.push({content:r,index:o})}}),n.role==="tool"){let s=typeof n.content=="string"?n.content:JSON.stringify(n.content||"");e.push({content:s,index:o})}}),e}function ry(t){for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role==="assistant"){if(typeof n.content=="string")return n.content.trim();if(Array.isArray(n.content)){let o=n.content.filter(s=>s&&(s.type==="text"||typeof s=="string")).map(s=>typeof s=="string"?s:s.text||"").join("").trim();if(o)return o}}}return""}function iy(t,e){let n=[];for(let o=t.length-1;o>=0&&n.length<e;o--){let s=t[o];if(s.role!=="assistant")continue;let r="";typeof s.content=="string"?r=s.content.trim():Array.isArray(s.content)&&(r=s.content.filter(i=>i&&(i.type==="text"||typeof i=="string")).map(i=>typeof i=="string"?i:i.text||"").join("").trim()),r&&n.push(r)}return n}function ay(t){let e=new Map;for(let n of t){let o;try{o=JSON.stringify(n.input)}catch{o=String(n.input)}let s=`${n.name}|${o}`;e.set(s,(e.get(s)||0)+1)}return e}function cy(t){if(!Array.isArray(t)||t.length===0)return{score:0,issues:["Empty or invalid session \u2014 no messages to analyse"],summary:"No messages found"};let e=10,n=[],o=sy(t),s=oy(t),r=o.length,i=vT(t),a=o.filter(x=>!x.id||!i.has(x.id));t.some(x=>x.role==="user"&&typeof x.content=="string"&&x.content.startsWith("[SYSTEM WARNING]")&&(x.content.includes("edited")||x.content.includes("bash command")||x.content.includes("grep pattern")||x.content.includes("re-read")||x.content.includes("already in your context")))&&(e-=2,n.push("Loop-warning was fired during session (repeated file edits, bash commands, or re-reads)"));let u=o.find(x=>{let P=x.input?.command||x.input?.cmd||"";return/\bsed\s+-n\b/.test(P)});if(u){let x=(u.input?.command||u.input?.cmd||"").slice(0,80);s.some(B=>B.content.includes("BLOCKED: sed -n is forbidden")||B.content.includes("BLOCKED: sed -n"))?(e-=.25,n.push(`sed -n attempted but blocked by agent guard: ${x}`)):(e-=1.5,n.push(`sed -n anti-pattern used: ${x}`))}o.find(x=>{if(x.name!=="grep"&&x.name!=="bash"&&x.name!=="ssh_exec")return!1;let P=x.input?.command||x.input?.cmd||"",B=x.input?.pattern||"",te=`${P} ${B}`;return/(?:-[CAB]|--context|--after|--before)\s*[=\s]?([2-9][1-9]|\d{3,})/.test(te)||/grep.*-[CAB]\s*([2-9][1-9]|\d{3,})/.test(te)})&&(e-=1,n.push("grep used with >20 context lines (context flood risk)"));let d=t.some(x=>x.role==="assistant"),f=ry(t),h=iy(t,3).some(x=>x.length>100&&!/^[^.!]{0,40}\?$/.test(x));if(d&&!h&&(f.length<80||/^[^.!]{0,40}\?$/.test(f))){e-=2;let x=f.length>0?`"${f.slice(0,60)}..."`:"(no assistant text found)";n.push(`Session ends without diagnosis \u2014 last response too short or is only a question: ${x}`)}r>40?(e-=1.5,n.push(`Excessive tool calls: ${r} (>40 threshold)`)):r>25&&(e-=.5,n.push(`High tool call count: ${r} (>25 threshold)`)),t.some(x=>{let P=typeof x.content=="string"?x.content:Array.isArray(x.content)?x.content.map(B=>typeof B=="string"?B:B.text||"").join(""):"";return/\[auto-compressed|context compacted|force-compressed/.test(P)})&&(e-=.5,n.push("Auto-compress triggered (context flood indicator)"));let _=ay(a),S=0,A="";for(let[x,P]of _)P>S&&(S=P,A=x);if(S>=3){let[x]=A.split("|");e-=1,n.push(`Same tool call repeated ${S}\xD7 (tool: ${x})`)}let E=!1,v=t.findIndex(x=>x.role==="user"&&typeof x.content=="string"&&x.content.includes("[SYSTEM STOP]")&&x.content.includes('"valid":true'));v>=0&&o.filter(P=>P.index>v).length>0&&(E=!0),E&&(e-=1.5,n.push('Stop-trigger ignored: tool result contained "valid":true but session continued with more tool calls'));let N=o.filter(x=>x.name==="ssh_exec");if(N.length>=8){let x=0,P=1;for(let B=1;B<N.length;B++)N[B].index<=N[B-1].index+2?P++:(x=Math.max(x,P),P=1);x=Math.max(x,P),x>=8&&(e-=.5,n.push(`SSH reconnect storm: ${x} 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,n.push("Surrender: model asked user to manually provide server output instead of gathering it"));let ne=new Map;for(let x of a)if(x.name==="read_file"&&x.input?.path){let P=x.input.path;ne.has(P)||ne.set(P,{count:0,ranges:[]});let B=ne.get(P);if(B.count++,x.input.line_start!=null){let te=x.input.line_start||1,X=x.input.line_end||te+350;B.ranges.push([te,X])}}function oe(x,P,B){for(let[te,X]of B){let C=Math.max(x,te),he=Math.min(P,X);if(he>C){let Y=he-C,re=P-x||1;if(Y/re>=.7)return!0}}return!1}let ue=0,fe="";for(let[x,P]of ne){if(P.count<3)continue;if(P.ranges.length===P.count){let X=!1,C=[];for(let[he,Y]of P.ranges){if(C.length>0&&oe(he,Y,C)){X=!0;break}C.push([he,Y])}if(!X)continue}if(P.count-P.ranges.length<=2&&P.ranges.length>=1){let X=!1,C=[];for(let[he,Y]of P.ranges){if(C.length>0&&oe(he,Y,C)){X=!0;break}C.push([he,Y])}if(!X)continue}P.count>ue&&(ue=P.count,fe=x)}if(ue>=3){e-=1;let x=fe.split("/").slice(-2).join("/");n.push(`read_file loop: "${x}" read ${ue}\xD7 (file already in context)`)}let ie=0,le="";for(let[x,P]of ne){if(P.ranges.length<4)continue;let B=[],te=!1;for(let[X,C]of P.ranges){if(B.length>0&&oe(X,C,B)){te=!0;break}B.push([X,C])}!te&&P.ranges.length>ie&&(ie=P.ranges.length,le=x)}if(ie>=4){e-=.5;let x=le.split("/").slice(-2).join("/");n.push(`File-scroll pattern: "${x}" read in ${ie} sequential sections \u2014 use grep instead`)}let T=new Map;for(let x of a)if(x.name==="grep"&&x.input?.path&&x.input?.pattern){let P=x.input.path;T.has(P)||T.set(P,new Set),T.get(P).add(x.input.pattern)}let F=0,ee="";for(let[x,P]of T)x.split("/").pop().includes(".")&&P.size>F&&(F=P.size,ee=x);if(F>=3){e-=.75;let x=ee.split("/").slice(-2).join("/");n.push(`grep flood on single file: "${x}" searched ${F}\xD7 with different patterns (file already in context)`)}{let x=new Set,P=new Set,B=/^(test_|demo_|temp_|tmp_|scratch_)/;for(let X of o){if(X.name==="write_file"&&X.input?.path){let C=X.input.path.split("/").pop(),he=X.input.path.includes("/tests/");B.test(C)&&!he&&x.add(X.input.path)}if((X.name==="bash"||X.name==="ssh_exec")&&X.input?.command){let C=X.input.command.match(/\brm\s+(?:-\w+\s+)?(\S+)/g);if(C)for(let he of C){let Y=he.split(/\s+/),re=Y[Y.length-1];for(let Z of x)(Z.endsWith(re)||re.endsWith(Z.split("/").pop()))&&P.add(Z)}}}let te=P.size;if(te>=1){let X=Math.min(te*.25,.5);e-=X;let C=[...P].map(he=>he.split("/").pop()).join(", ");n.push(`Temp file write-then-delete: ${C} \u2014 write inline logic or use tests/ instead`)}}let be=s.filter(x=>x.content.startsWith("EXIT")).length;be>=10?(e-=1,n.push(`Bash exit-error storm: ${be} tool results started with EXIT (repeated failing commands)`)):be>=5&&(e-=.5,n.push(`Repeated bash errors: ${be} tool results with non-zero exit code`));for(let x of t){if(x.role!=="assistant")continue;let P="";if(typeof x.content=="string"?P=x.content:Array.isArray(x.content)&&(P=x.content.filter(re=>re&&(re.type==="text"||typeof re=="string")).map(re=>typeof re=="string"?re:re.text||"").join("")),P.length<=5e3)continue;let B=P.split(/(?<=\. )/).filter(re=>re.trim().length>0);if(B.length<6)continue;let te=new Map;for(let re=0;re<=B.length-3;re++){let Z=B.slice(re,re+3).join("").trim();Z.length>30&&te.set(Z,(te.get(Z)||0)+1)}let X=0,C="";for(let[re,Z]of te)Z>X&&(X=Z,C=re);if(X<3)continue;let Y=C.length*X/P.length;if(Y>=.4||X>=10){e-=1.5,n.push(`llm output loop: assistant message repeated content detected (${X}\xD7 same paragraph, ${Math.round(Y*100)}% repeated)`);break}}{let x=new Set(["read_file","list_directory","search_files","glob","grep"]),P=t.some(te=>Array.isArray(te.tool_calls)?te.tool_calls.some(X=>x.has(X.function?.name)):Array.isArray(te.content)?te.content.some(X=>X.type==="tool_use"&&x.has(X.name)):!1);t.some(te=>te.role==="assistant"&&typeof te.content=="string"&&(te.content.includes("## Steps")||te.content.includes("/plan approve")))&&!P&&(e-=2,n.push("plan written without reading any files \u2014 LLM invented data structures from training knowledge (hallucination risk)"))}let ve=s.filter(x=>x.content.startsWith("BLOCKED:")&&!x.content.includes("BLOCKED: sed -n")&&!x.content.includes("SSH paused")&&!x.content.includes("SSH temporarily paused"));if(ve.length>0){let x=Math.min(ve.length*.5,1.5);e-=x,n.push(`${ve.length} tool call${ve.length===1?"":"s"} blocked (agent attempted denied actions)`)}let Fe=t.filter(x=>{let P=typeof x.content=="string"?x.content:"";return/\[SYSTEM WARNING\] Context wiped \d+×/.test(P)}).length;if(Fe>0){let x=Math.min(Fe*1,2);e-=x,n.push(`Super-nuclear context wipe fired ${Fe}\xD7 (context collapse \u2014 task too large or read loops)`)}{let x=!1,P=!1,B=!1;for(let X of o){if(X.name!=="bash")continue;let C=(X.input?.command||X.input?.cmd||"").trim();!(/cat\s*>/.test(C)||/<</.test(C))&&/\bcat\s+\S/.test(C)&&(x=!0),/^\s*ls(\s|$)/.test(C)&&!/npm|yarn|pnpm|make|git\b/.test(C)&&(P=!0),/\bfind\s+\S/.test(C)&&!/git\b|npm\b|-exec\b/.test(C)&&(B=!0)}let te=[x,P,B].filter(Boolean).length;if(te>0){let X=Math.min(te*.25,.75);e-=X;let C=[];x&&C.push("cat (use read_file)"),P&&C.push("ls (use list_directory)"),B&&C.push("find (use glob)"),n.push(`bash used instead of dedicated tool: ${C.join(", ")}`)}}{let x=o.some(C=>(C.name==="write_file"||C.name==="Write")&&C.input?.path&&(C.input.path.endsWith("requirements.txt")||C.input.path.endsWith("Pipfile")||C.input.path.endsWith("pyproject.toml"))),P=o.some(C=>(C.name==="write_file"||C.name==="Write")&&C.input?.path&&C.input.path.endsWith("package.json")),B=o.filter(C=>(C.name==="bash"||C.name==="Bash")&&C.input?.command).map(C=>C.input.command),te=B.some(C=>/pip\s+install|python\s+-m\s+venv/.test(C)),X=B.some(C=>/npm\s+install/.test(C));x&&!te?(e-=1,n.push("wrote requirements.txt but never ran pip install \u2014 environment not bootstrapped")):P&&!X&&o.some(he=>(he.name==="write_file"||he.name==="Write")&&he.input?.path&&/(\/src\/|index\.js|App\.js|main\.js)/.test(he.input.path))&&(e-=.75,n.push("created new React/Node project but never ran npm install \u2014 project is not runnable"))}if(d){let x=t.find(C=>C.role==="assistant"),P="";x&&(typeof x.content=="string"?P=x.content:Array.isArray(x.content)&&(P=x.content.filter(C=>C&&(C.type==="text"||typeof C=="string")).map(C=>typeof C=="string"?C:C.text||"").join("")));let B=P.slice(0,400),te=/^[\d\s\+\-\*\/×÷\(\)\.]+\s*=\s*[\d\s\+\-\*\/×÷\(\)\.]+[.\n]/m,X=B.split(`
683
+ `)}async function yT(t){let e=Ge.join(t,"package.json"),n="";if(await pn(()=>$t.access(e).then(()=>!0).catch(()=>!1)))try{let i=await $t.readFile(e,"utf-8"),a=JSON.parse(i);n=`${a.name||"?"} v${a.version||"?"}`}catch{}let[s,r]=await Promise.all([pn(async()=>{let{stdout:i}=await Zi("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),Jg()]);if(r&&r.length>0){console.log(`${io.red} \u26A0 ${r.length} unresolved merge conflict(s):${io.reset}`);for(let i of r)console.log(`${io.red} ${i.file}${io.reset}`);console.log(`${io.yellow} \u2192 Resolve conflicts before starting tasks${io.reset}`)}console.log()}Zg.exports={gatherProjectContext:gT,printContext:yT,generateFileTree:pT,_clearContextCache:()=>{Kl.clear(),co.clear(),ea=null,ao={result:null,expiry:0,cwd:null}}}});var na=Q((RO,ny)=>{var Qt=require("fs"),ta=require("path"),{atomicWrite:wT}=Jn();function lr(){return ta.join(process.cwd(),".nex","sessions")}function Xl(){let t=lr();Qt.existsSync(t)||Qt.mkdirSync(t,{recursive:!0,mode:448})}function Vl(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return ta.join(lr(),`${e}.json`)}function Jl(t,e,n={}){Xl();let o=Vl(t),s={name:t,createdAt:n.createdAt||new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:e.length,model:n.model||null,provider:n.provider||null,messages:e};return wT(o,JSON.stringify(s,null,2)),{path:o,name:t}}function ey(t){let e=Vl(t);if(!Qt.existsSync(e))return null;try{return JSON.parse(Qt.readFileSync(e,"utf-8"))}catch{return null}}function ty(){Xl();let t=lr(),e=Qt.readdirSync(t).filter(o=>o.endsWith(".json")),n=[];for(let o of e)try{let s=JSON.parse(Qt.readFileSync(ta.join(t,o),"utf-8"));n.push({name:s.name||o.replace(".json",""),createdAt:s.createdAt,updatedAt:s.updatedAt,messageCount:s.messageCount||0,model:s.model,provider:s.provider,score:s.score!=null?s.score:null,scoreGrade:s.scoreGrade||null})}catch{}return n.sort((o,s)=>(s.updatedAt||"").localeCompare(o.updatedAt||""))}function bT(t){let e=Vl(t);return Qt.existsSync(e)?(Qt.unlinkSync(e),!0):!1}function $T(){let t=ty();return t.length===0?null:ey(t[0].name)}var hs=null,En=null,cr=null;function _T(t,e={}){t.length!==0&&(hs&&clearTimeout(hs),En=t,cr=e||{},hs=setTimeout(()=>{En&&En.length>0&&Jl("_autosave",En,cr),hs=null,En=null,cr=null},5e3))}function xT(){hs&&(clearTimeout(hs),hs=null),En&&En.length>0&&(Jl("_autosave",En,cr),En=null,cr=null)}function kT(){Xl();let t=lr(),e=Qt.readdirSync(t).filter(r=>r.endsWith(".json")),n=new Date,o=new Date(n.getTime()-720*60*60*1e3),s=0;for(let r of e){let i=ta.join(t,r);try{let a=Qt.statSync(i);new Date(a.mtime)<o&&(Qt.unlinkSync(i),s++)}catch{}}return s}ny.exports={saveSession:Jl,loadSession:ey,listSessions:ty,deleteSession:bT,getLastSession:$T,autoSave:_T,flushAutoSave:xT,clearOldSessions:kT,_getSessionsDir:lr}});var sa=Q((CO,uy)=>{"use strict";var ur=require("fs"),sy=require("path");function oy(t){let e=[];return t.forEach((n,o)=>{n.role==="assistant"&&(Array.isArray(n.content)&&n.content.forEach(s=>{s&&s.type==="tool_use"&&e.push({name:s.name||"",input:s.input||{},index:o,id:s.id||null})}),Array.isArray(n.tool_calls)&&n.tool_calls.forEach(s=>{let r=s.function?.name||s.name||"",i={};try{i=typeof s.function?.arguments=="string"?JSON.parse(s.function.arguments):s.function?.arguments||s.input||{}}catch{}e.push({name:r,input:i,index:o,id:s.id||null})}))}),e}function vT(t){let e=new Set;return t.forEach(n=>{n.role==="tool"&&typeof n.content=="string"&&n.content.startsWith("BLOCKED:")&&n.tool_call_id&&e.add(n.tool_call_id),n.role==="user"&&Array.isArray(n.content)&&n.content.forEach(o=>{o&&o.type==="tool_result"&&o.tool_use_id&&typeof o.content=="string"&&o.content.startsWith("BLOCKED:")&&e.add(o.tool_use_id)})}),e}function ry(t){let e=[];return t.forEach((n,o)=>{if(n.role==="user"&&Array.isArray(n.content)&&n.content.forEach(s=>{if(s&&s.type==="tool_result"){let r=typeof s.content=="string"?s.content:Array.isArray(s.content)?s.content.map(i=>typeof i=="string"?i:i.text||"").join(""):JSON.stringify(s.content||"");e.push({content:r,index:o})}}),n.role==="tool"){let s=typeof n.content=="string"?n.content:JSON.stringify(n.content||"");e.push({content:s,index:o})}}),e}function iy(t){for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role==="assistant"){if(typeof n.content=="string")return n.content.trim();if(Array.isArray(n.content)){let o=n.content.filter(s=>s&&(s.type==="text"||typeof s=="string")).map(s=>typeof s=="string"?s:s.text||"").join("").trim();if(o)return o}}}return""}function ay(t,e){let n=[];for(let o=t.length-1;o>=0&&n.length<e;o--){let s=t[o];if(s.role!=="assistant")continue;let r="";typeof s.content=="string"?r=s.content.trim():Array.isArray(s.content)&&(r=s.content.filter(i=>i&&(i.type==="text"||typeof i=="string")).map(i=>typeof i=="string"?i:i.text||"").join("").trim()),r&&n.push(r)}return n}function cy(t){let e=new Map;for(let n of t){let o;try{o=JSON.stringify(n.input)}catch{o=String(n.input)}let s=`${n.name}|${o}`;e.set(s,(e.get(s)||0)+1)}return e}function ly(t){if(!Array.isArray(t)||t.length===0)return{score:0,issues:["Empty or invalid session \u2014 no messages to analyse"],summary:"No messages found"};let e=10,n=[],o=oy(t),s=ry(t),r=o.length,i=vT(t),a=o.filter(x=>!x.id||!i.has(x.id));t.some(x=>x.role==="user"&&typeof x.content=="string"&&x.content.startsWith("[SYSTEM WARNING]")&&(x.content.includes("edited")||x.content.includes("bash command")||x.content.includes("grep pattern")||x.content.includes("re-read")||x.content.includes("already in your context")))&&(e-=2,n.push("Loop-warning was fired during session (repeated file edits, bash commands, or re-reads)"));let u=o.find(x=>{let P=x.input?.command||x.input?.cmd||"";return/\bsed\s+-n\b/.test(P)});if(u){let x=(u.input?.command||u.input?.cmd||"").slice(0,80);s.some(B=>B.content.includes("BLOCKED: sed -n is forbidden")||B.content.includes("BLOCKED: sed -n"))?(e-=.25,n.push(`sed -n attempted but blocked by agent guard: ${x}`)):(e-=1.5,n.push(`sed -n anti-pattern used: ${x}`))}o.find(x=>{if(x.name!=="grep"&&x.name!=="bash"&&x.name!=="ssh_exec")return!1;let P=x.input?.command||x.input?.cmd||"",B=x.input?.pattern||"",te=`${P} ${B}`;return/(?:-[CAB]|--context|--after|--before)\s*[=\s]?([2-9][1-9]|\d{3,})/.test(te)||/grep.*-[CAB]\s*([2-9][1-9]|\d{3,})/.test(te)})&&(e-=1,n.push("grep used with >20 context lines (context flood risk)"));let d=t.some(x=>x.role==="assistant"),f=iy(t),h=ay(t,3).some(x=>x.length>100&&!/^[^.!]{0,40}\?$/.test(x));if(d&&!h&&(f.length<80||/^[^.!]{0,40}\?$/.test(f))){e-=2;let x=f.length>0?`"${f.slice(0,60)}..."`:"(no assistant text found)";n.push(`Session ends without diagnosis \u2014 last response too short or is only a question: ${x}`)}r>40?(e-=1.5,n.push(`Excessive tool calls: ${r} (>40 threshold)`)):r>25&&(e-=.5,n.push(`High tool call count: ${r} (>25 threshold)`)),t.some(x=>{let P=typeof x.content=="string"?x.content:Array.isArray(x.content)?x.content.map(B=>typeof B=="string"?B:B.text||"").join(""):"";return/\[auto-compressed|context compacted|force-compressed/.test(P)})&&(e-=.5,n.push("Auto-compress triggered (context flood indicator)"));let _=cy(a),S=0,A="";for(let[x,P]of _)P>S&&(S=P,A=x);if(S>=3){let[x]=A.split("|");e-=1,n.push(`Same tool call repeated ${S}\xD7 (tool: ${x})`)}let E=!1,v=t.findIndex(x=>x.role==="user"&&typeof x.content=="string"&&x.content.includes("[SYSTEM STOP]")&&x.content.includes('"valid":true'));v>=0&&o.filter(P=>P.index>v).length>0&&(E=!0),E&&(e-=1.5,n.push('Stop-trigger ignored: tool result contained "valid":true but session continued with more tool calls'));let N=o.filter(x=>x.name==="ssh_exec");if(N.length>=8){let x=0,P=1;for(let B=1;B<N.length;B++)N[B].index<=N[B-1].index+2?P++:(x=Math.max(x,P),P=1);x=Math.max(x,P),x>=8&&(e-=.5,n.push(`SSH reconnect storm: ${x} 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,n.push("Surrender: model asked user to manually provide server output instead of gathering it"));let ne=new Map;for(let x of a)if(x.name==="read_file"&&x.input?.path){let P=x.input.path;ne.has(P)||ne.set(P,{count:0,ranges:[]});let B=ne.get(P);if(B.count++,x.input.line_start!=null){let te=x.input.line_start||1,X=x.input.line_end||te+350;B.ranges.push([te,X])}}function oe(x,P,B){for(let[te,X]of B){let C=Math.max(x,te),he=Math.min(P,X);if(he>C){let Y=he-C,re=P-x||1;if(Y/re>=.7)return!0}}return!1}let ue=0,fe="";for(let[x,P]of ne){if(P.count<3)continue;if(P.ranges.length===P.count){let X=!1,C=[];for(let[he,Y]of P.ranges){if(C.length>0&&oe(he,Y,C)){X=!0;break}C.push([he,Y])}if(!X)continue}if(P.count-P.ranges.length<=2&&P.ranges.length>=1){let X=!1,C=[];for(let[he,Y]of P.ranges){if(C.length>0&&oe(he,Y,C)){X=!0;break}C.push([he,Y])}if(!X)continue}P.count>ue&&(ue=P.count,fe=x)}if(ue>=3){e-=1;let x=fe.split("/").slice(-2).join("/");n.push(`read_file loop: "${x}" read ${ue}\xD7 (file already in context)`)}let ie=0,le="";for(let[x,P]of ne){if(P.ranges.length<4)continue;let B=[],te=!1;for(let[X,C]of P.ranges){if(B.length>0&&oe(X,C,B)){te=!0;break}B.push([X,C])}!te&&P.ranges.length>ie&&(ie=P.ranges.length,le=x)}if(ie>=4){e-=.5;let x=le.split("/").slice(-2).join("/");n.push(`File-scroll pattern: "${x}" read in ${ie} sequential sections \u2014 use grep instead`)}let T=new Map;for(let x of a)if(x.name==="grep"&&x.input?.path&&x.input?.pattern){let P=x.input.path;T.has(P)||T.set(P,new Set),T.get(P).add(x.input.pattern)}let F=0,ee="";for(let[x,P]of T)x.split("/").pop().includes(".")&&P.size>F&&(F=P.size,ee=x);if(F>=3){e-=.75;let x=ee.split("/").slice(-2).join("/");n.push(`grep flood on single file: "${x}" searched ${F}\xD7 with different patterns (file already in context)`)}{let x=new Set,P=new Set,B=/^(test_|demo_|temp_|tmp_|scratch_)/;for(let X of o){if(X.name==="write_file"&&X.input?.path){let C=X.input.path.split("/").pop(),he=X.input.path.includes("/tests/");B.test(C)&&!he&&x.add(X.input.path)}if((X.name==="bash"||X.name==="ssh_exec")&&X.input?.command){let C=X.input.command.match(/\brm\s+(?:-\w+\s+)?(\S+)/g);if(C)for(let he of C){let Y=he.split(/\s+/),re=Y[Y.length-1];for(let Z of x)(Z.endsWith(re)||re.endsWith(Z.split("/").pop()))&&P.add(Z)}}}let te=P.size;if(te>=1){let X=Math.min(te*.25,.5);e-=X;let C=[...P].map(he=>he.split("/").pop()).join(", ");n.push(`Temp file write-then-delete: ${C} \u2014 write inline logic or use tests/ instead`)}}let be=s.filter(x=>x.content.startsWith("EXIT")).length;be>=10?(e-=1,n.push(`Bash exit-error storm: ${be} tool results started with EXIT (repeated failing commands)`)):be>=5&&(e-=.5,n.push(`Repeated bash errors: ${be} tool results with non-zero exit code`));for(let x of t){if(x.role!=="assistant")continue;let P="";if(typeof x.content=="string"?P=x.content:Array.isArray(x.content)&&(P=x.content.filter(re=>re&&(re.type==="text"||typeof re=="string")).map(re=>typeof re=="string"?re:re.text||"").join("")),P.length<=5e3)continue;let B=P.split(/(?<=\. )/).filter(re=>re.trim().length>0);if(B.length<6)continue;let te=new Map;for(let re=0;re<=B.length-3;re++){let Z=B.slice(re,re+3).join("").trim();Z.length>30&&te.set(Z,(te.get(Z)||0)+1)}let X=0,C="";for(let[re,Z]of te)Z>X&&(X=Z,C=re);if(X<3)continue;let Y=C.length*X/P.length;if(Y>=.4||X>=10){e-=1.5,n.push(`llm output loop: assistant message repeated content detected (${X}\xD7 same paragraph, ${Math.round(Y*100)}% repeated)`);break}}{let x=new Set(["read_file","list_directory","search_files","glob","grep"]),P=t.some(te=>Array.isArray(te.tool_calls)?te.tool_calls.some(X=>x.has(X.function?.name)):Array.isArray(te.content)?te.content.some(X=>X.type==="tool_use"&&x.has(X.name)):!1);t.some(te=>te.role==="assistant"&&typeof te.content=="string"&&(te.content.includes("## Steps")||te.content.includes("/plan approve")))&&!P&&(e-=2,n.push("plan written without reading any files \u2014 LLM invented data structures from training knowledge (hallucination risk)"))}let ve=s.filter(x=>x.content.startsWith("BLOCKED:")&&!x.content.includes("BLOCKED: sed -n")&&!x.content.includes("SSH paused")&&!x.content.includes("SSH temporarily paused"));if(ve.length>0){let x=Math.min(ve.length*.5,1.5);e-=x,n.push(`${ve.length} tool call${ve.length===1?"":"s"} blocked (agent attempted denied actions)`)}let Fe=t.filter(x=>{let P=typeof x.content=="string"?x.content:"";return/\[SYSTEM WARNING\] Context wiped \d+×/.test(P)}).length;if(Fe>0){let x=Math.min(Fe*1,2);e-=x,n.push(`Super-nuclear context wipe fired ${Fe}\xD7 (context collapse \u2014 task too large or read loops)`)}{let x=!1,P=!1,B=!1;for(let X of o){if(X.name!=="bash")continue;let C=(X.input?.command||X.input?.cmd||"").trim();!(/cat\s*>/.test(C)||/<</.test(C))&&/\bcat\s+\S/.test(C)&&(x=!0),/^\s*ls(\s|$)/.test(C)&&!/npm|yarn|pnpm|make|git\b/.test(C)&&(P=!0),/\bfind\s+\S/.test(C)&&!/git\b|npm\b|-exec\b/.test(C)&&(B=!0)}let te=[x,P,B].filter(Boolean).length;if(te>0){let X=Math.min(te*.25,.75);e-=X;let C=[];x&&C.push("cat (use read_file)"),P&&C.push("ls (use list_directory)"),B&&C.push("find (use glob)"),n.push(`bash used instead of dedicated tool: ${C.join(", ")}`)}}{let x=o.some(C=>(C.name==="write_file"||C.name==="Write")&&C.input?.path&&(C.input.path.endsWith("requirements.txt")||C.input.path.endsWith("Pipfile")||C.input.path.endsWith("pyproject.toml"))),P=o.some(C=>(C.name==="write_file"||C.name==="Write")&&C.input?.path&&C.input.path.endsWith("package.json")),B=o.filter(C=>(C.name==="bash"||C.name==="Bash")&&C.input?.command).map(C=>C.input.command),te=B.some(C=>/pip\s+install|python\s+-m\s+venv/.test(C)),X=B.some(C=>/npm\s+install/.test(C));x&&!te?(e-=1,n.push("wrote requirements.txt but never ran pip install \u2014 environment not bootstrapped")):P&&!X&&o.some(he=>(he.name==="write_file"||he.name==="Write")&&he.input?.path&&/(\/src\/|index\.js|App\.js|main\.js)/.test(he.input.path))&&(e-=.75,n.push("created new React/Node project but never ran npm install \u2014 project is not runnable"))}if(d){let x=t.find(C=>C.role==="assistant"),P="";x&&(typeof x.content=="string"?P=x.content:Array.isArray(x.content)&&(P=x.content.filter(C=>C&&(C.type==="text"||typeof C=="string")).map(C=>typeof C=="string"?C:C.text||"").join("")));let B=P.slice(0,400),te=/^[\d\s\+\-\*\/×÷\(\)\.]+\s*=\s*[\d\s\+\-\*\/×÷\(\)\.]+[.\n]/m,X=B.split(`
684
684
  `).find(C=>{let he=C.trim();return he.length>0&&he.length<=30&&/^\d/.test(he)&&/=/.test(he)&&!/[a-zA-Z]/.test(he)});if(te.test(B)||X){e-=1.5;let C=(X||B.split(`
685
685
  `)[0]).trim().slice(0,40);n.push(`Thinking-chain leak: non-sequitur artifact at response start: "${C}"`)}}if(d&&r>0){let x=t.findIndex(B=>B.role==="assistant"),P=t.findIndex(B=>!!(Array.isArray(B.tool_calls)&&B.tool_calls.length>0||Array.isArray(B.content)&&B.content.some(te=>te&&te.type==="tool_use")));if(x!==-1&&P!==-1&&x<P){let B=t[x],te="";typeof B.content=="string"?te=B.content:Array.isArray(B.content)&&(te=B.content.filter(he=>he&&(he.type==="text"||typeof he=="string")).map(he=>typeof he=="string"?he:he.text||"").join(""));let X=/ssh\s+\S+@\S+\s+"[^"]*\/[^"]*\./.test(te),C=/\/(?:home|var|etc|usr|opt|root|srv|data)\/[a-zA-Z0-9_.\-\/]+\.[a-zA-Z]{2,5}/.test(te);(X||C)&&(e-=1,n.push("Answer-before-verify: model gave concrete file paths/SSH commands before making any tool calls (paths guessed, not verified)"))}}if(d){let x=f;if(x.length>100){let B=(x.match(/^```/gm)||[]).length%2!==0,te=/"\s*:\s*$/.test(x.trimEnd()),X=/[,\[{]\s*$/.test(x.trimEnd());(B||te||X)&&(e-=.75,n.push("Truncated response: last assistant message ends mid-code-block or mid-JSON (model hit token limit)"))}}{let x=[];t.forEach((B,te)=>{let X=[];Array.isArray(B.tool_calls)&&B.tool_calls.forEach(C=>{if((C.function?.name||C.name||"")==="read_file"){let Y={};try{Y=typeof C.function?.arguments=="string"?JSON.parse(C.function.arguments):C.function?.arguments||{}}catch{}(Y.path||"").endsWith(".json")&&X.push({id:C.id,path:Y.path})}}),Array.isArray(B.content)&&B.content.forEach(C=>{C&&C.type==="tool_use"&&C.name==="read_file"&&(C.input?.path||"").endsWith(".json")&&X.push({id:C.id,path:C.input.path})}),X.forEach(C=>x.push({...C,msgIdx:te}))});let P=0;for(let B of x){let te=null;for(let C of t){if(C.role==="tool"&&C.tool_call_id===B.id&&typeof C.content=="string"){te=C.content;break}if(C.role==="user"&&Array.isArray(C.content)){let he=C.content.find(Y=>Y&&Y.type==="tool_result"&&Y.tool_use_id===B.id);if(he){te=typeof he.content=="string"?he.content:"";break}}}if(!te)continue;te.split(`
686
- `).filter(C=>C.trim()).length<5&&/^\s*\[/.test(te)&&!/\]\s*$/.test(te.trimEnd())&&P++}P>=1&&(e-=.75,n.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 x=s.filter(P=>/argument errors?/i.test(P.content)||/missing required (argument|parameter)/i.test(P.content)||/invalid argument/i.test(P.content));x.length>=3?(e-=.75,n.push(`Repeated tool argument errors: ${x.length} tool calls returned argument errors \u2014 model couldn't correct its tool usage`)):x.length>=2&&(e-=.25,n.push(`Tool argument errors: ${x.length} tool calls returned argument errors`))}{let x=!1,P=0,B=0;for(let te of a){if((te.name==="bash"||te.name==="Bash")&&te.input?.command&&/git\s+commit\b/.test(te.input.command)){x&&(B=Math.max(B,P)),x=!0,P=0;continue}x&&(te.name==="bash"||te.name==="Bash")&&te.input?.command&&/git\s+(status|diff|log|show)\b/.test(te.input.command)&&P++}B=Math.max(B,P),B>=3&&(e-=.75,n.push(`Post-commit verification waste: ${B} git status/diff/log calls after commit`))}e=Math.max(0,Math.min(10,e)),e=Math.round(e*10)/10;let Me=e>=9?"A":e>=8?"B":e>=7?"C":e>=6?"D":"F",Ee=n.length===0?`Clean session \u2014 no quality issues detected (${r} tool calls)`:`${n.length} issue${n.length===1?"":"s"} found \u2014 ${r} tool calls`;return{score:e,grade:Me,issues:n,summary:Ee}}function ST(t){try{let{loadSession:e}=na(),n=e(t);return n?cy(n.messages||[]):null}catch{return null}}function ET(t,e=null){let{score:n,issues:o}=t,s=e?.dim||"",r=e?.reset||"",i=e?.yellow||"";if(n>=8||o.length===0)return"";let a=o.map(l=>l.replace(/:\s+\d+.*$/,"").replace(/\s*\(.*?\)/,"").replace(/\s*—.*$/,""));if(n>=6){let l=a.slice(0,3),d=a.length-l.length,f=l.join(" \xB7 ");return d>0&&(f+=` (+${d})`),`
686
+ `).filter(C=>C.trim()).length<5&&/^\s*\[/.test(te)&&!/\]\s*$/.test(te.trimEnd())&&P++}P>=1&&(e-=.75,n.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 x=s.filter(P=>/argument errors?/i.test(P.content)||/missing required (argument|parameter)/i.test(P.content)||/invalid argument/i.test(P.content));x.length>=3?(e-=.75,n.push(`Repeated tool argument errors: ${x.length} tool calls returned argument errors \u2014 model couldn't correct its tool usage`)):x.length>=2&&(e-=.25,n.push(`Tool argument errors: ${x.length} tool calls returned argument errors`))}{let x=!1,P=0,B=0;for(let te of a){if((te.name==="bash"||te.name==="Bash")&&te.input?.command&&/git\s+commit\b/.test(te.input.command)){x&&(B=Math.max(B,P)),x=!0,P=0;continue}x&&(te.name==="bash"||te.name==="Bash")&&te.input?.command&&/git\s+(status|diff|log|show)\b/.test(te.input.command)&&P++}B=Math.max(B,P),B>=3&&(e-=.75,n.push(`Post-commit verification waste: ${B} git status/diff/log calls after commit`))}e=Math.max(0,Math.min(10,e)),e=Math.round(e*10)/10;let Me=e>=9?"A":e>=8?"B":e>=7?"C":e>=6?"D":"F",Ee=n.length===0?`Clean session \u2014 no quality issues detected (${r} tool calls)`:`${n.length} issue${n.length===1?"":"s"} found \u2014 ${r} tool calls`;return{score:e,grade:Me,issues:n,summary:Ee}}function ST(t){try{let{loadSession:e}=na(),n=e(t);return n?ly(n.messages||[]):null}catch{return null}}function ET(t,e=null){let{score:n,issues:o}=t,s=e?.dim||"",r=e?.reset||"",i=e?.yellow||"";if(n>=8||o.length===0)return"";let a=o.map(l=>l.replace(/:\s+\d+.*$/,"").replace(/\s*\(.*?\)/,"").replace(/\s*—.*$/,""));if(n>=6){let l=a.slice(0,3),d=a.length-l.length,f=l.join(" \xB7 ");return d>0&&(f+=` (+${d})`),`
687
687
  ${s}${f}${r}`}let c="";for(let l of a.slice(0,4))c+=`
688
688
  ${i}\u26A0${r} ${s}${l}${r}`;let u=a.length-4;return u>0&&(c+=`
689
- ${s}(+${u} more)${r}`),c}function TT(t,e={}){try{let n=ny.join(process.cwd(),".nex");ur.existsSync(n)||ur.mkdirSync(n,{recursive:!0});let o=ny.join(n,"benchmark-history.json"),s=[];if(ur.existsSync(o))try{s=JSON.parse(ur.readFileSync(o,"utf-8"))}catch{s=[]}Array.isArray(s)||(s=[]);let r=t>=9?"A":t>=8?"B":t>=7?"C":t>=6?"D":"F",i={date:new Date().toISOString(),version:e.version||null,model:e.model||null,score:t,grade:r,sessionName:e.sessionName||null,issues:Array.isArray(e.issues)?e.issues:[]};s.push(i),s.length>100&&(s=s.slice(s.length-100)),ur.writeFileSync(o,JSON.stringify(s,null,2))}catch{}}ly.exports={scoreMessages:cy,scoreSession:ST,formatScore:ET,appendScoreHistory:TT,_extractToolCalls:sy,_extractToolResults:oy,_getLastAssistantText:ry,_getLastNAssistantTexts:iy,_countDuplicateToolCalls:ay}});var ms=Q((CO,hy)=>{"use strict";var RT=require("os"),Zl=require("path"),Dn=require("fs"),dr=Zl.join(RT.homedir(),".nex-code","model-routing.json"),oa={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}},uy=["agentic","frontend","sysadmin","data","coding"];function CT(t){if(!t||t.length<8)return null;for(let e of uy){let n=oa[e];if(!n.pattern||n.pattern.test(t))return n}return oa.coding}function fr(){try{if(Dn.existsSync(dr))return JSON.parse(Dn.readFileSync(dr,"utf-8"))}catch{}return{}}function dy(t){if(process.env.NEX_FORCE_MODEL)return process.env.NEX_FORCE_MODEL;let e=oa[t];return e?.envVar&&process.env[e.envVar]?process.env[e.envVar]:fr()[t]||null}var fy={explore:10,plan:10,implement:35,verify:8},Ql={explore:"devstral-small-2:24b",plan:"qwen3-coder:480b",implement:null,verify:"devstral-small-2:24b"};function py(){let t=fr();if(t.phases&&Object.keys(t.phases).length>0)return t.phases;try{let{getActiveProviderName:e}=ct();if(e()==="ollama")return Ql}catch{}return process.env.NEX_PHASE_ROUTING==="1"?Ql:null}function AT(t,e){if(process.env.NEX_FORCE_MODEL)return process.env.NEX_FORCE_MODEL;let n=py();return n?.[t]?n[t]:e?dy(e):null}function OT(t){return fr().phaseBudgets?.[t]||fy[t]||20}function NT(){return process.env.NEX_PHASE_ROUTING==="0"||process.env.NEX_FORCE_MODEL?!1:py()!==null}function MT(t){let e=Zl.dirname(dr);Dn.existsSync(e)||Dn.mkdirSync(e,{recursive:!0});let n=fr(),o={...n,...t};!t.phases&&n.phases&&(o.phases=n.phases),!t.phaseBudgets&&n.phaseBudgets&&(o.phaseBudgets=n.phaseBudgets),Dn.writeFileSync(dr,JSON.stringify(o,null,2));try{let s=Zl.join(e,".env"),r="";Dn.existsSync(s)&&(r=Dn.readFileSync(s,"utf-8"));let i=r.split(/\r?\n/),a=(c,u)=>{let l=i.findIndex(d=>d.startsWith(c+"="));l>=0?i[l]=`${c}=${u}`:i.push(`${c}=${u}`)};o.coding&&a("NEX_ROUTE_CODING",o.coding),o.frontend&&a("NEX_ROUTE_FRONTEND",o.frontend),o.sysadmin&&a("NEX_ROUTE_SYSADMIN",o.sysadmin),o.data&&a("NEX_ROUTE_DATA",o.data),o.agentic&&a("NEX_ROUTE_AGENTIC",o.agentic),o.phases&&(o.phases.plan&&a("NEX_PHASE_PLAN_MODEL",o.phases.plan),o.phases.implement&&a("NEX_PHASE_IMPLEMENT_MODEL",o.phases.implement),o.phases.verify&&a("NEX_PHASE_VERIFY_MODEL",o.phases.verify)),Dn.writeFileSync(s,i.filter(c=>c.trim()!=="").join(`
689
+ ${s}(+${u} more)${r}`),c}function TT(t,e={}){try{let n=sy.join(process.cwd(),".nex");ur.existsSync(n)||ur.mkdirSync(n,{recursive:!0});let o=sy.join(n,"benchmark-history.json"),s=[];if(ur.existsSync(o))try{s=JSON.parse(ur.readFileSync(o,"utf-8"))}catch{s=[]}Array.isArray(s)||(s=[]);let r=t>=9?"A":t>=8?"B":t>=7?"C":t>=6?"D":"F",i={date:new Date().toISOString(),version:e.version||null,model:e.model||null,score:t,grade:r,sessionName:e.sessionName||null,issues:Array.isArray(e.issues)?e.issues:[]};s.push(i),s.length>100&&(s=s.slice(s.length-100)),ur.writeFileSync(o,JSON.stringify(s,null,2))}catch{}}uy.exports={scoreMessages:ly,scoreSession:ST,formatScore:ET,appendScoreHistory:TT,_extractToolCalls:oy,_extractToolResults:ry,_getLastAssistantText:iy,_getLastNAssistantTexts:ay,_countDuplicateToolCalls:cy}});var ms=Q((AO,my)=>{"use strict";var RT=require("os"),Zl=require("path"),Dn=require("fs"),dr=Zl.join(RT.homedir(),".nex-code","model-routing.json"),oa={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}},dy=["agentic","frontend","sysadmin","data","coding"];function CT(t){if(!t||t.length<8)return null;for(let e of dy){let n=oa[e];if(!n.pattern||n.pattern.test(t))return n}return oa.coding}function fr(){try{if(Dn.existsSync(dr))return JSON.parse(Dn.readFileSync(dr,"utf-8"))}catch{}return{}}function fy(t){if(process.env.NEX_FORCE_MODEL)return process.env.NEX_FORCE_MODEL;let e=oa[t];return e?.envVar&&process.env[e.envVar]?process.env[e.envVar]:fr()[t]||null}var py={explore:10,plan:10,implement:35,verify:8},Ql={explore:"devstral-small-2:24b",plan:"qwen3-coder:480b",implement:null,verify:"devstral-small-2:24b"};function hy(){let t=fr();if(t.phases&&Object.keys(t.phases).length>0)return t.phases;try{let{getActiveProviderName:e}=ct();if(e()==="ollama")return Ql}catch{}return process.env.NEX_PHASE_ROUTING==="1"?Ql:null}function AT(t,e){if(process.env.NEX_FORCE_MODEL)return process.env.NEX_FORCE_MODEL;let n=hy();return n?.[t]?n[t]:e?fy(e):null}function OT(t){return fr().phaseBudgets?.[t]||py[t]||20}function NT(){return process.env.NEX_PHASE_ROUTING==="0"||process.env.NEX_FORCE_MODEL?!1:hy()!==null}function MT(t){let e=Zl.dirname(dr);Dn.existsSync(e)||Dn.mkdirSync(e,{recursive:!0});let n=fr(),o={...n,...t};!t.phases&&n.phases&&(o.phases=n.phases),!t.phaseBudgets&&n.phaseBudgets&&(o.phaseBudgets=n.phaseBudgets),Dn.writeFileSync(dr,JSON.stringify(o,null,2));try{let s=Zl.join(e,".env"),r="";Dn.existsSync(s)&&(r=Dn.readFileSync(s,"utf-8"));let i=r.split(/\r?\n/),a=(c,u)=>{let l=i.findIndex(d=>d.startsWith(c+"="));l>=0?i[l]=`${c}=${u}`:i.push(`${c}=${u}`)};o.coding&&a("NEX_ROUTE_CODING",o.coding),o.frontend&&a("NEX_ROUTE_FRONTEND",o.frontend),o.sysadmin&&a("NEX_ROUTE_SYSADMIN",o.sysadmin),o.data&&a("NEX_ROUTE_DATA",o.data),o.agentic&&a("NEX_ROUTE_AGENTIC",o.agentic),o.phases&&(o.phases.plan&&a("NEX_PHASE_PLAN_MODEL",o.phases.plan),o.phases.implement&&a("NEX_PHASE_IMPLEMENT_MODEL",o.phases.implement),o.phases.verify&&a("NEX_PHASE_VERIFY_MODEL",o.phases.verify)),Dn.writeFileSync(s,i.filter(c=>c.trim()!=="").join(`
690
690
  `)+`
691
- `)}catch{}}hy.exports={CATEGORIES:oa,DETECTION_ORDER:uy,detectCategory:CT,getModelForCategory:dy,getModelForPhase:AT,getPhaseBudget:OT,isPhaseRoutingEnabled:NT,DEFAULT_PHASE_BUDGETS:fy,BUILTIN_PHASE_DEFAULTS:Ql,saveRoutingConfig:MT,loadRoutingConfig:fr,ROUTING_CONFIG_PATH:dr}});var wy=Q((AO,yy)=>{"use strict";var gs=require("fs"),pr=require("path"),PT=require("os"),{detectCategory:LT}=ms(),lo=pr.join(PT.homedir(),".nex-code","examples"),eu=pr.join(__dirname,"..","examples");function my(t){try{let n=gs.readFileSync(t,"utf-8").replace(/<!--[\s\S]*?-->/g,"").trim(),o=n.match(/^user:\s*(.+)$/m);if(!o)return null;let s=o[1].trim(),r=n.indexOf(`
691
+ `)}catch{}}my.exports={CATEGORIES:oa,DETECTION_ORDER:dy,detectCategory:CT,getModelForCategory:fy,getModelForPhase:AT,getPhaseBudget:OT,isPhaseRoutingEnabled:NT,DEFAULT_PHASE_BUDGETS:py,BUILTIN_PHASE_DEFAULTS:Ql,saveRoutingConfig:MT,loadRoutingConfig:fr,ROUTING_CONFIG_PATH:dr}});var by=Q((OO,wy)=>{"use strict";var gs=require("fs"),pr=require("path"),PT=require("os"),{detectCategory:LT}=ms(),lo=pr.join(PT.homedir(),".nex-code","examples"),eu=pr.join(__dirname,"..","examples");function gy(t){try{let n=gs.readFileSync(t,"utf-8").replace(/<!--[\s\S]*?-->/g,"").trim(),o=n.match(/^user:\s*(.+)$/m);if(!o)return null;let s=o[1].trim(),r=n.indexOf(`
692
692
  A: |`);if(r===-1)return null;let i=n.slice(r+5),a=[],c=0;for(let l of i.split(`
693
693
  `))if(l.startsWith(" ")){for(;c>0;)a.push(""),c--;a.push(l.slice(2))}else if(l.trim()==="")a.length>0&&c++;else break;if(a.length===0)return null;let u=a.join(`
694
- `).trim();return{user:s,assistant:u}}catch{return null}}function gy(t){let e=`${t}.md`,n=pr.join(lo,e);if(gs.existsSync(n)){let s=my(n);if(s)return s}let o=pr.join(eu,e);return gs.existsSync(o)?my(o):null}function IT(t){if(process.env.NEX_FEW_SHOT==="0"||!t||t.length<8)return null;let e=LT(t);return!e||e.id==="coding"&&!/\b(fix|bug|crash|error|implement|add|create|change|update|refactor|rewrite|broken|fail|patch|migrate|port)\b/i.test(t)?null:gy(e.id)}function jT(){let t=new Set;for(let e of[lo,eu])try{for(let n of gs.readdirSync(e))n.endsWith(".md")&&t.add(n.replace(".md",""))}catch{}return[...t].sort()}function DT(t,e){gs.existsSync(lo)||gs.mkdirSync(lo,{recursive:!0});let n=`<!-- Auto-extracted from high-scoring session \u2014 edit as needed -->
694
+ `).trim();return{user:s,assistant:u}}catch{return null}}function yy(t){let e=`${t}.md`,n=pr.join(lo,e);if(gs.existsSync(n)){let s=gy(n);if(s)return s}let o=pr.join(eu,e);return gs.existsSync(o)?gy(o):null}function IT(t){if(process.env.NEX_FEW_SHOT==="0"||!t||t.length<8)return null;let e=LT(t);return!e||e.id==="coding"&&!/\b(fix|bug|crash|error|implement|add|create|change|update|refactor|rewrite|broken|fail|patch|migrate|port)\b/i.test(t)?null:yy(e.id)}function jT(){let t=new Set;for(let e of[lo,eu])try{for(let n of gs.readdirSync(e))n.endsWith(".md")&&t.add(n.replace(".md",""))}catch{}return[...t].sort()}function DT(t,e){gs.existsSync(lo)||gs.mkdirSync(lo,{recursive:!0});let n=`<!-- Auto-extracted from high-scoring session \u2014 edit as needed -->
695
695
 
696
696
  user: ${e.user}
697
697
 
@@ -699,14 +699,14 @@ A: |
699
699
  ${e.assistant.split(`
700
700
  `).map(o=>` ${o}`).join(`
701
701
  `)}
702
- `;gs.writeFileSync(pr.join(lo,`${t}.md`),n,"utf-8")}yy.exports={getFewShotForInput:IT,loadExampleForCategory:gy,listAvailableExamples:jT,savePrivateExample:DT,PRIVATE_EXAMPLES_DIR:lo,BUNDLED_EXAMPLES_DIR:eu}});var vy=Q((NO,ky)=>{var Ot=require("fs"),uo=require("path"),{C:OO}=rt(),{atomicWrite:qT,withFileLockSync:FT}=Jn(),ra={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"},fo={...ra};function by(){let t=uo.join(process.cwd(),".nex","config.json");if(Ot.existsSync(t))try{let e=JSON.parse(Ot.readFileSync(t,"utf-8"));e.permissions&&(fo={...ra,...e.permissions})}catch{}}function BT(){let t=uo.join(process.cwd(),".nex"),e=uo.join(t,"config.json");Ot.existsSync(t)||Ot.mkdirSync(t,{recursive:!0}),FT(e,()=>{let n={};if(Ot.existsSync(e))try{n=JSON.parse(Ot.readFileSync(e,"utf-8"))}catch{n={}}n.permissions=fo,qT(e,JSON.stringify(n,null,2))})}function $y(t){return fo[t]||"ask"}function UT(t,e){return["allow","ask","deny"].includes(e)?(fo[t]=e,!0):!1}function WT(t){return $y(t)}function HT(){return Object.entries(fo).map(([t,e])=>({tool:t,mode:e}))}function YT(){fo={...ra}}var hr={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 _y(){let t=uo.join(process.cwd(),".nex","config.json");try{return Ot.existsSync(t)&&JSON.parse(Ot.readFileSync(t,"utf-8")).teamPermissions||null}catch{return null}}function GT(t){let e=uo.join(process.cwd(),".nex"),n=uo.join(e,"config.json");Ot.existsSync(e)||Ot.mkdirSync(e,{recursive:!0});let o={};try{Ot.existsSync(n)&&(o=JSON.parse(Ot.readFileSync(n,"utf-8")))}catch{o={}}o.teamPermissions=t,Ot.writeFileSync(n,JSON.stringify(o,null,2),"utf-8")}function xy(){let t=_y();if(!t)return hr.admin;let e=t.role||"admin",n=hr[e]||hr.admin;return{...n,...t.overrides,blockedTools:[...n.blockedTools||[],...t.overrides?.blockedTools||[]]}}function zT(t){let e=xy();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 KT(){return Object.entries(hr).map(([t,e])=>({name:t,description:e.description,toolCount:e.allowedTools?`${e.allowedTools.length} allowed`:"all allowed",blockedCount:e.blockedTools.length}))}by();ky.exports={getPermission:$y,setPermission:UT,checkPermission:WT,listPermissions:HT,loadPermissions:by,savePermissions:BT,resetPermissions:YT,DEFAULT_PERMISSIONS:ra,PERMISSION_PRESETS:hr,loadPresetConfig:_y,savePresetConfig:GT,getEffectivePreset:xy,isToolAllowed:zT,listPresets:KT}});var ca=Q((PO,Cy)=>{var ws=require("fs"),ia=require("path"),MO=require("readline"),{C:Le}=rt(),Oe=null,nu=!1,su=null,Sy=new Set(["read_file","list_directory","search_files","glob","grep","web_search","web_fetch","git_status","git_diff","git_log","git_show"]);function aa(){return ia.join(process.cwd(),".nex","plans")}function Ey(){let t=aa();ws.existsSync(t)||ws.mkdirSync(t,{recursive:!0})}function XT(t,e=[]){return Oe={name:`plan-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,task:t,steps:e.map(n=>({description:n.description||n,files:n.files||[],status:"pending"})),status:"draft",createdAt:new Date().toISOString()},Oe}function VT(){return Oe}function JT(t){nu=t}function ZT(){return nu}function QT(){return!Oe||Oe.status!=="draft"?!1:(Oe.status="approved",Oe.updatedAt=new Date().toISOString(),!0)}function eR(){return!Oe||Oe.status!=="approved"?!1:(Oe.status="executing",!0)}function tu(t,e){return!Oe||t<0||t>=Oe.steps.length?!1:(Oe.steps[t].status=e,Oe.updatedAt=new Date().toISOString(),Oe.steps.every(n=>n.status==="done"||n.status==="skipped")&&(Oe.status="completed"),!0)}function tR(t){if(!t)return`${Le.dim}No active plan${Le.reset}`;let e={draft:`${Le.yellow}DRAFT${Le.reset}`,approved:`${Le.green}APPROVED${Le.reset}`,executing:`${Le.blue}EXECUTING${Le.reset}`,completed:`${Le.green}COMPLETED${Le.reset}`},n=[];n.push(`
702
+ `;gs.writeFileSync(pr.join(lo,`${t}.md`),n,"utf-8")}wy.exports={getFewShotForInput:IT,loadExampleForCategory:yy,listAvailableExamples:jT,savePrivateExample:DT,PRIVATE_EXAMPLES_DIR:lo,BUNDLED_EXAMPLES_DIR:eu}});var Sy=Q((MO,vy)=>{var Ot=require("fs"),uo=require("path"),{C:NO}=rt(),{atomicWrite:qT,withFileLockSync:FT}=Jn(),ra={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"},fo={...ra};function $y(){let t=uo.join(process.cwd(),".nex","config.json");if(Ot.existsSync(t))try{let e=JSON.parse(Ot.readFileSync(t,"utf-8"));e.permissions&&(fo={...ra,...e.permissions})}catch{}}function BT(){let t=uo.join(process.cwd(),".nex"),e=uo.join(t,"config.json");Ot.existsSync(t)||Ot.mkdirSync(t,{recursive:!0}),FT(e,()=>{let n={};if(Ot.existsSync(e))try{n=JSON.parse(Ot.readFileSync(e,"utf-8"))}catch{n={}}n.permissions=fo,qT(e,JSON.stringify(n,null,2))})}function _y(t){return fo[t]||"ask"}function UT(t,e){return["allow","ask","deny"].includes(e)?(fo[t]=e,!0):!1}function WT(t){return _y(t)}function HT(){return Object.entries(fo).map(([t,e])=>({tool:t,mode:e}))}function YT(){fo={...ra}}var hr={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 xy(){let t=uo.join(process.cwd(),".nex","config.json");try{return Ot.existsSync(t)&&JSON.parse(Ot.readFileSync(t,"utf-8")).teamPermissions||null}catch{return null}}function GT(t){let e=uo.join(process.cwd(),".nex"),n=uo.join(e,"config.json");Ot.existsSync(e)||Ot.mkdirSync(e,{recursive:!0});let o={};try{Ot.existsSync(n)&&(o=JSON.parse(Ot.readFileSync(n,"utf-8")))}catch{o={}}o.teamPermissions=t,Ot.writeFileSync(n,JSON.stringify(o,null,2),"utf-8")}function ky(){let t=xy();if(!t)return hr.admin;let e=t.role||"admin",n=hr[e]||hr.admin;return{...n,...t.overrides,blockedTools:[...n.blockedTools||[],...t.overrides?.blockedTools||[]]}}function zT(t){let e=ky();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 KT(){return Object.entries(hr).map(([t,e])=>({name:t,description:e.description,toolCount:e.allowedTools?`${e.allowedTools.length} allowed`:"all allowed",blockedCount:e.blockedTools.length}))}$y();vy.exports={getPermission:_y,setPermission:UT,checkPermission:WT,listPermissions:HT,loadPermissions:$y,savePermissions:BT,resetPermissions:YT,DEFAULT_PERMISSIONS:ra,PERMISSION_PRESETS:hr,loadPresetConfig:xy,savePresetConfig:GT,getEffectivePreset:ky,isToolAllowed:zT,listPresets:KT}});var ca=Q((LO,Ay)=>{var ws=require("fs"),ia=require("path"),PO=require("readline"),{C:Le}=rt(),Oe=null,nu=!1,su=null,Ey=new Set(["read_file","list_directory","search_files","glob","grep","web_search","web_fetch","git_status","git_diff","git_log","git_show"]);function aa(){return ia.join(process.cwd(),".nex","plans")}function Ty(){let t=aa();ws.existsSync(t)||ws.mkdirSync(t,{recursive:!0})}function XT(t,e=[]){return Oe={name:`plan-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,task:t,steps:e.map(n=>({description:n.description||n,files:n.files||[],status:"pending"})),status:"draft",createdAt:new Date().toISOString()},Oe}function VT(){return Oe}function JT(t){nu=t}function ZT(){return nu}function QT(){return!Oe||Oe.status!=="draft"?!1:(Oe.status="approved",Oe.updatedAt=new Date().toISOString(),!0)}function eR(){return!Oe||Oe.status!=="approved"?!1:(Oe.status="executing",!0)}function tu(t,e){return!Oe||t<0||t>=Oe.steps.length?!1:(Oe.steps[t].status=e,Oe.updatedAt=new Date().toISOString(),Oe.steps.every(n=>n.status==="done"||n.status==="skipped")&&(Oe.status="completed"),!0)}function tR(t){if(!t)return`${Le.dim}No active plan${Le.reset}`;let e={draft:`${Le.yellow}DRAFT${Le.reset}`,approved:`${Le.green}APPROVED${Le.reset}`,executing:`${Le.blue}EXECUTING${Le.reset}`,completed:`${Le.green}COMPLETED${Le.reset}`},n=[];n.push(`
703
703
  ${Le.bold}${Le.cyan}Plan: ${t.task}${Le.reset}`),n.push(`${Le.dim}Status: ${e[t.status]||t.status}${Le.reset}
704
704
  `);for(let o=0;o<t.steps.length;o++){let s=t.steps[o],r;switch(s.status){case"done":r=`${Le.green}\u2713${Le.reset}`;break;case"in_progress":r=`${Le.blue}\u2192${Le.reset}`;break;case"skipped":r=`${Le.dim}\u25CB${Le.reset}`;break;default:r=`${Le.dim} ${Le.reset}`}n.push(` ${r} ${Le.bold}Step ${o+1}:${Le.reset} ${s.description}`),s.files.length>0&&n.push(` ${Le.dim}Files: ${s.files.join(", ")}${Le.reset}`)}return n.push(""),n.join(`
705
- `)}function nR(t){if(t||(t=Oe),!t)return null;Ey();let e=ia.join(aa(),`${t.name}.json`);return ws.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function sR(t){let e=ia.join(aa(),`${t}.json`);if(!ws.existsSync(e))return null;try{let n=JSON.parse(ws.readFileSync(e,"utf-8"));return Oe=n,n}catch{return null}}function oR(){Ey();let t=aa(),e=ws.readdirSync(t).filter(o=>o.endsWith(".json")),n=[];for(let o of e)try{let s=JSON.parse(ws.readFileSync(ia.join(t,o),"utf-8"));n.push({name:s.name,task:s.task,status:s.status,steps:s.steps?s.steps.length:0,createdAt:s.createdAt})}catch{}return n.sort((o,s)=>(s.createdAt||"").localeCompare(o.createdAt||""))}function rR(t){if(!t)return[];let e=[],n=t.match(/##\s+Steps?\s*\n([\s\S]*?)(?:\n##|\s*$)/i),o=n?n[1]:t,s=/^\s*(\d+)[.)]\s+(.+)/gm,r;for(;(r=s.exec(o))!==null;){let a=r[2].trim().replace(/^\*\*What\*\*:\s*/i,"").replace(/^\*\*\d+\.\*\*\s*/,"").replace(/\*\*/g,"").trim();a.length>3&&e.push({description:a,files:[],status:"pending"})}if(e.length===0){let i=/\*\*Step\s+\d+[:.]\*\*\s*(.+)/gi;for(;(r=i.exec(t))!==null;){let a=r[1].replace(/\*\*/g,"").trim();a.length>3&&e.push({description:a,files:[],status:"pending"})}}if(e.length>0){let i=/\*\*(?:Where|Files?)\*\*:\s*(.+)/gi,a=[...t.matchAll(i)];for(let c=0;c<Math.min(e.length,a.length);c++){let u=a[c][1];e[c].files=u.split(/[,\s]+/).filter(l=>/[./]/.test(l)).slice(0,5)}}return e}function iR(t){su=t}function aR(){return su}function cR(){Oe=null,nu=!1,su=null,fR()}function lR(){return`
705
+ `)}function nR(t){if(t||(t=Oe),!t)return null;Ty();let e=ia.join(aa(),`${t.name}.json`);return ws.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function sR(t){let e=ia.join(aa(),`${t}.json`);if(!ws.existsSync(e))return null;try{let n=JSON.parse(ws.readFileSync(e,"utf-8"));return Oe=n,n}catch{return null}}function oR(){Ty();let t=aa(),e=ws.readdirSync(t).filter(o=>o.endsWith(".json")),n=[];for(let o of e)try{let s=JSON.parse(ws.readFileSync(ia.join(t,o),"utf-8"));n.push({name:s.name,task:s.task,status:s.status,steps:s.steps?s.steps.length:0,createdAt:s.createdAt})}catch{}return n.sort((o,s)=>(s.createdAt||"").localeCompare(o.createdAt||""))}function rR(t){if(!t)return[];let e=[],n=t.match(/##\s+Steps?\s*\n([\s\S]*?)(?:\n##|\s*$)/i),o=n?n[1]:t,s=/^\s*(\d+)[.)]\s+(.+)/gm,r;for(;(r=s.exec(o))!==null;){let a=r[2].trim().replace(/^\*\*What\*\*:\s*/i,"").replace(/^\*\*\d+\.\*\*\s*/,"").replace(/\*\*/g,"").trim();a.length>3&&e.push({description:a,files:[],status:"pending"})}if(e.length===0){let i=/\*\*Step\s+\d+[:.]\*\*\s*(.+)/gi;for(;(r=i.exec(t))!==null;){let a=r[1].replace(/\*\*/g,"").trim();a.length>3&&e.push({description:a,files:[],status:"pending"})}}if(e.length>0){let i=/\*\*(?:Where|Files?)\*\*:\s*(.+)/gi,a=[...t.matchAll(i)];for(let c=0;c<Math.min(e.length,a.length);c++){let u=a[c][1];e[c].files=u.split(/[,\s]+/).filter(l=>/[./]/.test(l)).slice(0,5)}}return e}function iR(t){su=t}function aR(){return su}function cR(){Oe=null,nu=!1,su=null,fR()}function lR(){return`
706
706
  PLAN MODE ACTIVE: You are in analysis-only mode. You MUST NOT execute any changes.
707
707
 
708
708
  # Allowed Tools (read-only)
709
- You may ONLY use these tools: ${[...Sy].join(", ")}
709
+ You may ONLY use these tools: ${[...Ey].join(", ")}
710
710
  Any other tool call will be blocked and returned with an error.
711
711
 
712
712
  # MANDATORY: Read Before You Plan
@@ -758,14 +758,14 @@ Bullet list of potential issues and mitigations.
758
758
  - Order steps by dependency (later steps may depend on earlier ones).
759
759
  - After presenting the plan, tell the user to type \`/plan approve\` to proceed.
760
760
  - Do NOT make any file changes \u2014 your role is analysis and planning only.
761
- - 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 ys=0;function uR(){!Oe||Oe.status!=="executing"||(ys>0&&tu(ys-1,"done"),ys<Oe.steps.length&&(tu(ys,"in_progress"),ys++))}function dR(){if(!Oe||Oe.status!=="executing"||Oe.steps.length===0)return null;let t=Math.min(ys,Oe.steps.length),e=Oe.steps.length,n=Math.max(0,t-1),o=Oe.steps[n]?.description||"";return{current:t,total:e,description:o}}function fR(){ys=0}var Ty=["interactive","semi-auto","autonomous"],Ry="interactive";function pR(t){return Ty.includes(t)?(Ry=t,!0):!1}function hR(){return Ry}Cy.exports={createPlan:XT,getActivePlan:VT,setPlanMode:JT,isPlanMode:ZT,approvePlan:QT,startExecution:eR,updateStep:tu,formatPlan:tR,savePlan:nR,loadPlan:sR,listPlans:oR,clearPlan:cR,getPlanModePrompt:lR,setPlanContent:iR,getPlanContent:aR,extractStepsFromText:rR,advancePlanStep:uR,getPlanStepInfo:dR,PLAN_MODE_ALLOWED_TOOLS:Sy,setAutonomyLevel:pR,getAutonomyLevel:hR,AUTONOMY_LEVELS:Ty}});var Fy=Q((LO,qy)=>{var{C:k}=rt();function Ay(){return Math.max(10,(process.stdout.columns||80)-2)}function mR(t){if(!t)return"";let e=t.split(`
762
- `),n=[],o=!1,s="";for(let r of e){let i=Ay();if(r.trim().startsWith("```")){if(o)n.push(`${k.dim}${"\u2500".repeat(40)}${k.reset}`),o=!1,s="";else{o=!0,s=r.trim().substring(3).trim();let a=s?` ${s} `:"";n.push(`${k.dim}${"\u2500".repeat(3)}${a}${"\u2500".repeat(Math.max(0,37-a.length))}${k.reset}`)}continue}if(o){n.push(` ${ru(r,s)}`);continue}if(r.startsWith("###### ")){n.push(`${k.bold}${k.cyan} ${Nt(r.substring(7))}${k.reset}`);continue}if(r.startsWith("##### ")){n.push(`${k.bold}${k.cyan} ${Nt(r.substring(6))}${k.reset}`);continue}if(r.startsWith("#### ")){n.push(`${k.bold}${k.cyan} ${Nt(r.substring(5))}${k.reset}`);continue}if(r.startsWith("### ")){n.push(`${k.bold}${k.cyan} ${Nt(r.substring(4))}${k.reset}`);continue}if(r.startsWith("## ")){n.push(`${k.bold}${k.cyan} ${Nt(r.substring(3))}${k.reset}`);continue}if(r.startsWith("# ")){n.push(`${k.bold}${k.cyan}${Nt(r.substring(2))}${k.reset}`);continue}if(/^\s*[-*]\s/.test(r)){let a=r.match(/^(\s*)/)[1],c=r.replace(/^\s*[-*]\s/,""),u=`${a}${k.cyan}\u2022${k.reset} ${bs(c)}`;n.push($s(u,i,a+" "));continue}if(/^\s*\d+\.\s/.test(r)){let a=r.match(/^(\s*)(\d+)\.\s(.*)/);if(a){let c=a[1],u=a[2],l=a[3],d=`${c}${k.cyan}${u}.${k.reset} ${bs(l)}`,f=c+" ".repeat(u.length+2);n.push($s(d,i,f));continue}}n.push($s(bs(r),i))}return n.join(`
763
- `)}function Nt(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function bs(t){return t?t.replace(/`([^`]+)`/g,`${k.cyan}$1${k.reset}`).replace(/\*\*([^*]+)\*\*/g,`${k.bold}$1${k.reset}`).replace(/\*([^*]+)\*/g,`${k.dim}$1${k.reset}`).replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${k.cyan}$1${k.reset} ${k.dim}($2)${k.reset}`):""}function ru(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?Oy(t):e==="bash"||e==="sh"||e==="shell"||e==="zsh"?Ny(t):e==="json"||e==="jsonc"?My(t):e==="python"||e==="py"?Py(t):e==="go"||e==="golang"?Ly(t):e==="rust"||e==="rs"?Iy(t):e==="css"||e==="scss"||e==="less"?jy(t):e==="html"||e==="xml"||e==="svg"||e==="htm"?Dy(t):t:""}function Oy(t){let e=/\b(const|let|var|function|return|if|else|for|while|class|import|export|from|require|async|await|new|this|throw|try|catch|switch|case|break|default|typeof|instanceof)\b/g,n=/(["'`])(?:(?=(\\?))\2.)*?\1/g,o=/(\/\/.*$)/,s=/\b(\d+\.?\d*)\b/g,r=t;return r=r.replace(s,`${k.yellow}$1${k.reset}`),r=r.replace(e,`${k.magenta}$1${k.reset}`),r=r.replace(n,`${k.green}$&${k.reset}`),r=r.replace(o,`${k.dim}$1${k.reset}`),r}function Ny(t){let e=/^(\s*)([\w-]+)/,n=/(--?\w[\w-]*)/g,o=/(["'])(?:(?=(\\?))\2.)*?\1/g,s=/(#.*$)/,r=t;return r=r.replace(n,`${k.cyan}$1${k.reset}`),r=r.replace(e,`$1${k.green}$2${k.reset}`),r=r.replace(o,`${k.yellow}$&${k.reset}`),r=r.replace(s,`${k.dim}$1${k.reset}`),r}function My(t){let e=/("[\w-]+")\s*:/g,n=/:\s*("(?:[^"\\]|\\.)*")/g,o=/:\s*(\d+\.?\d*)/g,s=/:\s*(true|false|null)/g,r=t;return r=r.replace(e,`${k.cyan}$1${k.reset}:`),r=r.replace(n,`: ${k.green}$1${k.reset}`),r=r.replace(o,`: ${k.yellow}$1${k.reset}`),r=r.replace(s,`: ${k.magenta}$1${k.reset}`),r}function Py(t){let e=/\b(def|class|if|elif|else|for|while|return|import|from|as|try|except|finally|raise|with|yield|lambda|pass|break|continue|and|or|not|in|is|None|True|False|self|async|await|nonlocal|global)\b/g,n=/("""[\s\S]*?"""|'''[\s\S]*?'''|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')/g,o=/(#.*$)/,s=/\b(\d+\.?\d*)\b/g,r=/^(\s*@\w+)/,i=t;return i=i.replace(s,`${k.yellow}$1${k.reset}`),i=i.replace(e,`${k.magenta}$1${k.reset}`),i=i.replace(r,`${k.cyan}$1${k.reset}`),i=i.replace(n,`${k.green}$&${k.reset}`),i=i.replace(o,`${k.dim}$1${k.reset}`),i}function Ly(t){let e=/\b(func|package|import|var|const|type|struct|interface|map|chan|go|defer|return|if|else|for|range|switch|case|default|break|continue|select|fallthrough|nil|true|false|make|new|len|cap|append|copy|delete|panic|recover)\b/g,n=/\b(string|int|int8|int16|int32|int64|uint|uint8|uint16|uint32|uint64|float32|float64|bool|byte|rune|error|any)\b/g,o=/(["'`])(?:(?=(\\?))\2.)*?\1/g,s=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,i=t;return i=i.replace(r,`${k.yellow}$1${k.reset}`),i=i.replace(n,`${k.cyan}$1${k.reset}`),i=i.replace(e,`${k.magenta}$1${k.reset}`),i=i.replace(o,`${k.green}$&${k.reset}`),i=i.replace(s,`${k.dim}$1${k.reset}`),i}function Iy(t){let e=/\b(fn|let|mut|const|struct|enum|impl|trait|pub|use|mod|crate|self|super|match|if|else|for|while|loop|return|break|continue|where|as|in|ref|move|async|await|unsafe|extern|type|static|dyn|macro_rules)\b/g,n=/\b(i8|i16|i32|i64|i128|u8|u16|u32|u64|u128|f32|f64|bool|char|str|String|Vec|Option|Result|Box|Rc|Arc|Self|Some|None|Ok|Err|true|false)\b/g,o=/(["'])(?:(?=(\\?))\2.)*?\1/g,s=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,i=/\b(\w+!)/g,a=t;return a=a.replace(r,`${k.yellow}$1${k.reset}`),a=a.replace(n,`${k.cyan}$1${k.reset}`),a=a.replace(e,`${k.magenta}$1${k.reset}`),a=a.replace(i,`${k.yellow}$1${k.reset}`),a=a.replace(o,`${k.green}$&${k.reset}`),a=a.replace(s,`${k.dim}$1${k.reset}`),a}function jy(t){let e=/^(\s*)([\w-]+)\s*:/,n=/:\s*([^;]+)/,o=/^(\s*[.#@][\w-]+)/,s=/\b(\d+\.?\d*(px|em|rem|%|vh|vw|s|ms|deg|fr)?)\b/g,r=/(\/\*.*?\*\/|\/\/.*$)/,i=/(#[0-9a-fA-F]{3,8})\b/g,a=t;return a=a.replace(i,`${k.yellow}$1${k.reset}`),a=a.replace(s,`${k.yellow}$1${k.reset}`),a=a.replace(e,`$1${k.cyan}$2${k.reset}:`),a=a.replace(o,`$1${k.magenta}$&${k.reset}`),a=a.replace(r,`${k.dim}$1${k.reset}`),a}function Dy(t){let e=/<\/?(\w[\w-]*)/g,n=/\s([\w-]+)=/g,o=/(["'])(?:(?=(\\?))\2.)*?\1/g,s=/(<!--.*?-->)/g,r=/(&\w+;)/g,i=t;return i=i.replace(s,`${k.dim}$1${k.reset}`),i=i.replace(o,`${k.green}$&${k.reset}`),i=i.replace(e,`<${k.magenta}$1${k.reset}`),i=i.replace(n,` ${k.cyan}$1${k.reset}=`),i=i.replace(r,`${k.yellow}$1${k.reset}`),i}function $s(t,e,n=""){if(!e||e<10)return t;let o="",s=0,r=-1,i=0,a=0,c=t.length;for(;i<c;){if(t[i]==="\x1B"){let u=i+1;if(u<c&&t[u]==="["){for(u++;u<c&&!/[a-zA-Z]/.test(t[u]);)u++;u<c&&u++}i=u;continue}if(t[i]===" "&&(r=i),s++,s>e&&r!==-1){o+=t.slice(a,r)+`
761
+ - 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 ys=0;function uR(){!Oe||Oe.status!=="executing"||(ys>0&&tu(ys-1,"done"),ys<Oe.steps.length&&(tu(ys,"in_progress"),ys++))}function dR(){if(!Oe||Oe.status!=="executing"||Oe.steps.length===0)return null;let t=Math.min(ys,Oe.steps.length),e=Oe.steps.length,n=Math.max(0,t-1),o=Oe.steps[n]?.description||"";return{current:t,total:e,description:o}}function fR(){ys=0}var Ry=["interactive","semi-auto","autonomous"],Cy="interactive";function pR(t){return Ry.includes(t)?(Cy=t,!0):!1}function hR(){return Cy}Ay.exports={createPlan:XT,getActivePlan:VT,setPlanMode:JT,isPlanMode:ZT,approvePlan:QT,startExecution:eR,updateStep:tu,formatPlan:tR,savePlan:nR,loadPlan:sR,listPlans:oR,clearPlan:cR,getPlanModePrompt:lR,setPlanContent:iR,getPlanContent:aR,extractStepsFromText:rR,advancePlanStep:uR,getPlanStepInfo:dR,PLAN_MODE_ALLOWED_TOOLS:Ey,setAutonomyLevel:pR,getAutonomyLevel:hR,AUTONOMY_LEVELS:Ry}});var By=Q((IO,Fy)=>{var{C:k}=rt();function Oy(){return Math.max(10,(process.stdout.columns||80)-2)}function mR(t){if(!t)return"";let e=t.split(`
762
+ `),n=[],o=!1,s="";for(let r of e){let i=Oy();if(r.trim().startsWith("```")){if(o)n.push(`${k.dim}${"\u2500".repeat(40)}${k.reset}`),o=!1,s="";else{o=!0,s=r.trim().substring(3).trim();let a=s?` ${s} `:"";n.push(`${k.dim}${"\u2500".repeat(3)}${a}${"\u2500".repeat(Math.max(0,37-a.length))}${k.reset}`)}continue}if(o){n.push(` ${ru(r,s)}`);continue}if(r.startsWith("###### ")){n.push(`${k.bold}${k.cyan} ${Nt(r.substring(7))}${k.reset}`);continue}if(r.startsWith("##### ")){n.push(`${k.bold}${k.cyan} ${Nt(r.substring(6))}${k.reset}`);continue}if(r.startsWith("#### ")){n.push(`${k.bold}${k.cyan} ${Nt(r.substring(5))}${k.reset}`);continue}if(r.startsWith("### ")){n.push(`${k.bold}${k.cyan} ${Nt(r.substring(4))}${k.reset}`);continue}if(r.startsWith("## ")){n.push(`${k.bold}${k.cyan} ${Nt(r.substring(3))}${k.reset}`);continue}if(r.startsWith("# ")){n.push(`${k.bold}${k.cyan}${Nt(r.substring(2))}${k.reset}`);continue}if(/^\s*[-*]\s/.test(r)){let a=r.match(/^(\s*)/)[1],c=r.replace(/^\s*[-*]\s/,""),u=`${a}${k.cyan}\u2022${k.reset} ${bs(c)}`;n.push($s(u,i,a+" "));continue}if(/^\s*\d+\.\s/.test(r)){let a=r.match(/^(\s*)(\d+)\.\s(.*)/);if(a){let c=a[1],u=a[2],l=a[3],d=`${c}${k.cyan}${u}.${k.reset} ${bs(l)}`,f=c+" ".repeat(u.length+2);n.push($s(d,i,f));continue}}n.push($s(bs(r),i))}return n.join(`
763
+ `)}function Nt(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function bs(t){return t?t.replace(/`([^`]+)`/g,`${k.cyan}$1${k.reset}`).replace(/\*\*([^*]+)\*\*/g,`${k.bold}$1${k.reset}`).replace(/\*([^*]+)\*/g,`${k.dim}$1${k.reset}`).replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${k.cyan}$1${k.reset} ${k.dim}($2)${k.reset}`):""}function ru(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?Ny(t):e==="bash"||e==="sh"||e==="shell"||e==="zsh"?My(t):e==="json"||e==="jsonc"?Py(t):e==="python"||e==="py"?Ly(t):e==="go"||e==="golang"?Iy(t):e==="rust"||e==="rs"?jy(t):e==="css"||e==="scss"||e==="less"?Dy(t):e==="html"||e==="xml"||e==="svg"||e==="htm"?qy(t):t:""}function Ny(t){let e=/\b(const|let|var|function|return|if|else|for|while|class|import|export|from|require|async|await|new|this|throw|try|catch|switch|case|break|default|typeof|instanceof)\b/g,n=/(["'`])(?:(?=(\\?))\2.)*?\1/g,o=/(\/\/.*$)/,s=/\b(\d+\.?\d*)\b/g,r=t;return r=r.replace(s,`${k.yellow}$1${k.reset}`),r=r.replace(e,`${k.magenta}$1${k.reset}`),r=r.replace(n,`${k.green}$&${k.reset}`),r=r.replace(o,`${k.dim}$1${k.reset}`),r}function My(t){let e=/^(\s*)([\w-]+)/,n=/(--?\w[\w-]*)/g,o=/(["'])(?:(?=(\\?))\2.)*?\1/g,s=/(#.*$)/,r=t;return r=r.replace(n,`${k.cyan}$1${k.reset}`),r=r.replace(e,`$1${k.green}$2${k.reset}`),r=r.replace(o,`${k.yellow}$&${k.reset}`),r=r.replace(s,`${k.dim}$1${k.reset}`),r}function Py(t){let e=/("[\w-]+")\s*:/g,n=/:\s*("(?:[^"\\]|\\.)*")/g,o=/:\s*(\d+\.?\d*)/g,s=/:\s*(true|false|null)/g,r=t;return r=r.replace(e,`${k.cyan}$1${k.reset}:`),r=r.replace(n,`: ${k.green}$1${k.reset}`),r=r.replace(o,`: ${k.yellow}$1${k.reset}`),r=r.replace(s,`: ${k.magenta}$1${k.reset}`),r}function Ly(t){let e=/\b(def|class|if|elif|else|for|while|return|import|from|as|try|except|finally|raise|with|yield|lambda|pass|break|continue|and|or|not|in|is|None|True|False|self|async|await|nonlocal|global)\b/g,n=/("""[\s\S]*?"""|'''[\s\S]*?'''|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')/g,o=/(#.*$)/,s=/\b(\d+\.?\d*)\b/g,r=/^(\s*@\w+)/,i=t;return i=i.replace(s,`${k.yellow}$1${k.reset}`),i=i.replace(e,`${k.magenta}$1${k.reset}`),i=i.replace(r,`${k.cyan}$1${k.reset}`),i=i.replace(n,`${k.green}$&${k.reset}`),i=i.replace(o,`${k.dim}$1${k.reset}`),i}function Iy(t){let e=/\b(func|package|import|var|const|type|struct|interface|map|chan|go|defer|return|if|else|for|range|switch|case|default|break|continue|select|fallthrough|nil|true|false|make|new|len|cap|append|copy|delete|panic|recover)\b/g,n=/\b(string|int|int8|int16|int32|int64|uint|uint8|uint16|uint32|uint64|float32|float64|bool|byte|rune|error|any)\b/g,o=/(["'`])(?:(?=(\\?))\2.)*?\1/g,s=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,i=t;return i=i.replace(r,`${k.yellow}$1${k.reset}`),i=i.replace(n,`${k.cyan}$1${k.reset}`),i=i.replace(e,`${k.magenta}$1${k.reset}`),i=i.replace(o,`${k.green}$&${k.reset}`),i=i.replace(s,`${k.dim}$1${k.reset}`),i}function jy(t){let e=/\b(fn|let|mut|const|struct|enum|impl|trait|pub|use|mod|crate|self|super|match|if|else|for|while|loop|return|break|continue|where|as|in|ref|move|async|await|unsafe|extern|type|static|dyn|macro_rules)\b/g,n=/\b(i8|i16|i32|i64|i128|u8|u16|u32|u64|u128|f32|f64|bool|char|str|String|Vec|Option|Result|Box|Rc|Arc|Self|Some|None|Ok|Err|true|false)\b/g,o=/(["'])(?:(?=(\\?))\2.)*?\1/g,s=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,i=/\b(\w+!)/g,a=t;return a=a.replace(r,`${k.yellow}$1${k.reset}`),a=a.replace(n,`${k.cyan}$1${k.reset}`),a=a.replace(e,`${k.magenta}$1${k.reset}`),a=a.replace(i,`${k.yellow}$1${k.reset}`),a=a.replace(o,`${k.green}$&${k.reset}`),a=a.replace(s,`${k.dim}$1${k.reset}`),a}function Dy(t){let e=/^(\s*)([\w-]+)\s*:/,n=/:\s*([^;]+)/,o=/^(\s*[.#@][\w-]+)/,s=/\b(\d+\.?\d*(px|em|rem|%|vh|vw|s|ms|deg|fr)?)\b/g,r=/(\/\*.*?\*\/|\/\/.*$)/,i=/(#[0-9a-fA-F]{3,8})\b/g,a=t;return a=a.replace(i,`${k.yellow}$1${k.reset}`),a=a.replace(s,`${k.yellow}$1${k.reset}`),a=a.replace(e,`$1${k.cyan}$2${k.reset}:`),a=a.replace(o,`$1${k.magenta}$&${k.reset}`),a=a.replace(r,`${k.dim}$1${k.reset}`),a}function qy(t){let e=/<\/?(\w[\w-]*)/g,n=/\s([\w-]+)=/g,o=/(["'])(?:(?=(\\?))\2.)*?\1/g,s=/(<!--.*?-->)/g,r=/(&\w+;)/g,i=t;return i=i.replace(s,`${k.dim}$1${k.reset}`),i=i.replace(o,`${k.green}$&${k.reset}`),i=i.replace(e,`<${k.magenta}$1${k.reset}`),i=i.replace(n,` ${k.cyan}$1${k.reset}=`),i=i.replace(r,`${k.yellow}$1${k.reset}`),i}function $s(t,e,n=""){if(!e||e<10)return t;let o="",s=0,r=-1,i=0,a=0,c=t.length;for(;i<c;){if(t[i]==="\x1B"){let u=i+1;if(u<c&&t[u]==="["){for(u++;u<c&&!/[a-zA-Z]/.test(t[u]);)u++;u<c&&u++}i=u;continue}if(t[i]===" "&&(r=i),s++,s>e&&r!==-1){o+=t.slice(a,r)+`
764
764
  `+n,a=r+1,i=a,s=n.length,r=-1;continue}s>e&&r===-1&&(o+=t.slice(a,i)+`
765
765
  `+n,a=i,s=n.length+1),i++}return o+=t.slice(a),o}function gR(t,e){if(!t||t.length===0)return"";let n=t.map((i,a)=>{let c=e.reduce((u,l)=>Math.max(u,(l[a]||"").length),0);return Math.max(i.length,c)}),o=n.map(i=>"\u2500".repeat(i+2)).join("\u253C"),s=t.map((i,a)=>` ${k.bold}${i.padEnd(n[a])}${k.reset} `).join("\u2502"),r=[];r.push(`${k.dim}\u250C${o.replace(/┼/g,"\u252C")}\u2510${k.reset}`),r.push(`${k.dim}\u2502${k.reset}${s}${k.dim}\u2502${k.reset}`),r.push(`${k.dim}\u251C${o}\u2524${k.reset}`);for(let i of e){let a=t.map((c,u)=>` ${(i[u]||"").padEnd(n[u])} `).join(`${k.dim}\u2502${k.reset}`);r.push(`${k.dim}\u2502${k.reset}${a}${k.dim}\u2502${k.reset}`)}return r.push(`${k.dim}\u2514${o.replace(/┼/g,"\u2534")}\u2518${k.reset}`),r.join(`
766
766
  `)}function yR(t,e,n,o=30){let s=n>0?Math.round(e/n*100):0,r=Math.round(s/100*o),i=o-r,a=s>=100?k.green:s>50?k.yellow:k.cyan;return` ${t} ${a}${"\u2588".repeat(r)}${k.dim}${"\u2591".repeat(i)}${k.reset} ${s}% (${e}/${n})`}var ou=class{constructor(){this.buffer="",this.inCodeBlock=!1,this.codeBlockLang="",this.lineCount=0,this._cursorTimer=null,this._cursorFrame=0,this._cursorActive=!1}_safeWrite(e){try{this.lineCount+=(e.match(/\n/g)||[]).length,process.stdout.write(e)}catch(n){if(n.code!=="EPIPE")throw n}}_cursorWrite(e){try{process.stderr.write(e)}catch(n){if(n.code!=="EPIPE")throw n}}startCursor(){process.stderr.isTTY&&(this._cursorActive=!0,this._cursorFrame=0,this._cursorWrite("\x1B[?25l"),this._renderCursor(),this._cursorTimer=setInterval(()=>this._renderCursor(),100))}_renderCursor(){let n=[0,1,2,3,4,3,2,1],o=n[this._cursorFrame%n.length],s="";for(let r=0;r<5;r++)s+=r===o?`${Kt().T.cyan}\u25CF${Kt().T.reset}`:" ";this._cursorWrite(`\x1B[2K\r${s}`),this._cursorFrame++}_clearCursorLine(){this._cursorActive&&this._cursorWrite("\x1B[2K\r")}stopCursor(){this._cursorTimer&&(clearInterval(this._cursorTimer),this._cursorTimer=null),this._cursorActive&&(this._cursorWrite("\x1B[2K\r\x1B[?25h"),this._cursorActive=!1)}push(e){if(!e)return;this._clearCursorLine(),this.buffer+=e;let n;for(;(n=this.buffer.indexOf(`
767
767
  `))!==-1;){let o=this.buffer.substring(0,n);this.buffer=this.buffer.substring(n+1),this._renderLine(o)}this._cursorActive&&(this._renderCursor(),this._cursorTimer&&clearInterval(this._cursorTimer),this._cursorTimer=setInterval(()=>this._renderCursor(),100))}flush(){this.stopCursor(),this.buffer&&(this._renderLine(this.buffer),this.buffer=""),this.inCodeBlock&&(this._safeWrite(`${k.dim}${"\u2500".repeat(40)}${k.reset}
768
- `),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){let n=Ay();if(e.trim().startsWith("```")){if(this.inCodeBlock)this._safeWrite(`${k.dim}${"\u2500".repeat(40)}${k.reset}
768
+ `),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){let n=Oy();if(e.trim().startsWith("```")){if(this.inCodeBlock)this._safeWrite(`${k.dim}${"\u2500".repeat(40)}${k.reset}
769
769
  `),this.inCodeBlock=!1,this.codeBlockLang="";else{this.inCodeBlock=!0,this.codeBlockLang=e.trim().substring(3).trim();let s=this.codeBlockLang?` ${this.codeBlockLang} `:"";this._safeWrite(`${k.dim}${"\u2500".repeat(3)}${s}${"\u2500".repeat(Math.max(0,37-s.length))}${k.reset}
770
770
  `)}return}if(this.inCodeBlock){this._safeWrite(` ${ru(e,this.codeBlockLang)}
771
771
  `);return}if(e.startsWith("###### ")){this._safeWrite(`${k.bold}${k.cyan} ${Nt(e.substring(7))}${k.reset}
@@ -777,7 +777,7 @@ Bullet list of potential issues and mitigations.
777
777
  `);return}if(/^\s*[-*]\s/.test(e)){let s=e.match(/^(\s*)/)[1],r=e.replace(/^\s*[-*]\s/,""),i=`${s}${k.cyan}\u2022${k.reset} ${bs(r)}`,a=$s(i,n,s+" ");this._safeWrite(`${a}
778
778
  `);return}if(/^\s*\d+\.\s/.test(e)){let s=e.match(/^(\s*)(\d+)\.\s(.*)/);if(s){let r=s[1],i=s[2],a=s[3],c=`${r}${k.cyan}${i}.${k.reset} ${bs(a)}`,u=r+" ".repeat(i.length+2),l=$s(c,n,u);this._safeWrite(`${l}
779
779
  `);return}}let o=$s(bs(e),n);this._safeWrite(`${o}
780
- `)}};qy.exports={renderMarkdown:mR,renderInline:bs,stripHeadingMarkers:Nt,highlightCode:ru,highlightJS:Oy,highlightBash:Ny,highlightJSON:My,highlightPython:Py,highlightGo:Ly,highlightRust:Iy,highlightCSS:jy,highlightHTML:Dy,renderTable:gR,renderProgress:yR,wrapAnsi:$s,StreamRenderer:ou}});var Yy=Q((IO,Hy)=>{var{execSync:wR}=require("child_process"),iu=require("path"),mr=require("fs"),au=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function By(){return iu.join(process.cwd(),".nex","hooks")}function bR(){return iu.join(process.cwd(),".nex","config.json")}function Uy(){let t=bR();if(!mr.existsSync(t))return{};try{return JSON.parse(mr.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function la(t){if(!au.includes(t))return[];let e=[],n=By(),o=iu.join(n,t);mr.existsSync(o)&&e.push(o);let s=Uy();if(s[t]){let r=Array.isArray(s[t])?s[t]:[s[t]];e.push(...r)}return e}function Wy(t,e={},n=3e4){try{return{success:!0,exitCode:0,output:wR(t,{cwd:process.cwd(),encoding:"utf-8",timeout:n,env:{...process.env,...e},stdio:["pipe","pipe","pipe"]}).trim()}}catch(o){let s=typeof o.status=="number"?o.status:1;return{success:!1,exitCode:s,blocked:s===2,output:o.stdout?o.stdout.trim():"",error:o.stderr?o.stderr.trim():o.message}}}function $R(t,e={}){let n=la(t);if(n.length===0)return{results:[],blocked:!1};let o={};for(let[r,i]of Object.entries(e))o[`NEX_${r.toUpperCase()}`]=String(i);let s=[];for(let r of n){let i=Wy(r,o);if(s.push({command:r,...i}),i.blocked&&t.startsWith("pre-")){let a=i.output||i.error||"hook blocked tool call";return{results:s,blocked:!0,blockReason:a}}if(!i.success&&t.startsWith("pre-"))break}return{results:s,blocked:!1}}function _R(t){return la(t).length>0}function xR(){let t=[];for(let e of au){let n=la(e);n.length>0&&t.push({event:e,commands:n})}return t}function kR(){let t=By();return mr.existsSync(t)||mr.mkdirSync(t,{recursive:!0}),t}Hy.exports={HOOK_EVENTS:au,loadHookConfig:Uy,getHooksForEvent:la,executeHook:Wy,runHooks:$R,hasHooks:_R,listHooks:xR,initHooksDir:kR}});var l0=Q((FO,c0)=>{"use strict";var{callWithRetry:Ky,runSubAgent:Gy,clearAllLocks:vR}=Sl(),{parseModelSpec:Xy,getActiveProviderName:jO,getActiveModelId:DO}=ct(),{detectCategory:SR,getModelForCategory:zy}=ms(),{MultiProgress:ER,C:ge}=rt(),{getModelBriefing:qO}=Li(),Vy=parseInt(process.env.NEX_MAX_PARALLEL||"4",10),ua=parseInt(process.env.NEX_MAX_SUBTASKS||"8",10),Jy="devstral-2:123b",Zy="kimi-k2.5",Qy=`You are a task decomposition engine. Given a complex user request, split it into independent, atomic sub-tasks.
780
+ `)}};Fy.exports={renderMarkdown:mR,renderInline:bs,stripHeadingMarkers:Nt,highlightCode:ru,highlightJS:Ny,highlightBash:My,highlightJSON:Py,highlightPython:Ly,highlightGo:Iy,highlightRust:jy,highlightCSS:Dy,highlightHTML:qy,renderTable:gR,renderProgress:yR,wrapAnsi:$s,StreamRenderer:ou}});var Gy=Q((jO,Yy)=>{var{execSync:wR}=require("child_process"),iu=require("path"),mr=require("fs"),au=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function Uy(){return iu.join(process.cwd(),".nex","hooks")}function bR(){return iu.join(process.cwd(),".nex","config.json")}function Wy(){let t=bR();if(!mr.existsSync(t))return{};try{return JSON.parse(mr.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function la(t){if(!au.includes(t))return[];let e=[],n=Uy(),o=iu.join(n,t);mr.existsSync(o)&&e.push(o);let s=Wy();if(s[t]){let r=Array.isArray(s[t])?s[t]:[s[t]];e.push(...r)}return e}function Hy(t,e={},n=3e4){try{return{success:!0,exitCode:0,output:wR(t,{cwd:process.cwd(),encoding:"utf-8",timeout:n,env:{...process.env,...e},stdio:["pipe","pipe","pipe"]}).trim()}}catch(o){let s=typeof o.status=="number"?o.status:1;return{success:!1,exitCode:s,blocked:s===2,output:o.stdout?o.stdout.trim():"",error:o.stderr?o.stderr.trim():o.message}}}function $R(t,e={}){let n=la(t);if(n.length===0)return{results:[],blocked:!1};let o={};for(let[r,i]of Object.entries(e))o[`NEX_${r.toUpperCase()}`]=String(i);let s=[];for(let r of n){let i=Hy(r,o);if(s.push({command:r,...i}),i.blocked&&t.startsWith("pre-")){let a=i.output||i.error||"hook blocked tool call";return{results:s,blocked:!0,blockReason:a}}if(!i.success&&t.startsWith("pre-"))break}return{results:s,blocked:!1}}function _R(t){return la(t).length>0}function xR(){let t=[];for(let e of au){let n=la(e);n.length>0&&t.push({event:e,commands:n})}return t}function kR(){let t=Uy();return mr.existsSync(t)||mr.mkdirSync(t,{recursive:!0}),t}Yy.exports={HOOK_EVENTS:au,loadHookConfig:Wy,getHooksForEvent:la,executeHook:Hy,runHooks:$R,hasHooks:_R,listHooks:xR,initHooksDir:kR}});var u0=Q((BO,l0)=>{"use strict";var{callWithRetry:Xy,runSubAgent:zy,clearAllLocks:vR}=Sl(),{parseModelSpec:Vy,getActiveProviderName:DO,getActiveModelId:qO}=ct(),{detectCategory:SR,getModelForCategory:Ky}=ms(),{MultiProgress:ER,C:ge}=rt(),{getModelBriefing:FO}=Li(),Jy=parseInt(process.env.NEX_MAX_PARALLEL||"4",10),ua=parseInt(process.env.NEX_MAX_SUBTASKS||"8",10),Zy="devstral-2:123b",Qy="kimi-k2.5",e0=`You are a task decomposition engine. Given a complex user request, split it into independent, atomic sub-tasks.
781
781
 
782
782
  RULES:
783
783
  - Output ONLY a JSON array, no markdown fences, no explanation.
@@ -792,7 +792,7 @@ RULES:
792
792
  - If the request is simple (single goal), return an array with exactly 1 item.
793
793
 
794
794
  USER REQUEST:
795
- {prompt}`,e0=`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.
795
+ {prompt}`,t0=`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.
796
796
 
797
797
  RULES:
798
798
  - Output ONLY a JSON object with these fields:
@@ -806,16 +806,16 @@ ORIGINAL REQUEST:
806
806
  {prompt}
807
807
 
808
808
  SUB-AGENT RESULTS:
809
- {results}`;async function t0(t,e=1,n=2e3){for(let o=0;o<=e;o++)try{return await t()}catch(s){if(o===e)throw s;await new Promise(r=>setTimeout(r,n))}}function n0(t){let e=0,n=[];return function(){return new Promise(s=>{let r=()=>{e<t?(e++,s(()=>{e--,n.length>0&&n.shift()()})):n.push(r)};r()})}}function TR(t){if(!t||typeof t!="string")return{isComplex:!1,estimatedGoals:0,reason:"empty"};let e=0,n=[],o=t.match(/(?:(?:^|\n)\s*|\s)(?:\d+[.)]\s|[(]\d+[)][\s,]|[(][a-z][)][\s,])/g);o&&o.length>=2&&(e=Math.max(e,o.length),n.push(`${o.length} numbered items`));let s=t.match(/(?:^|\n)\s*[-*]\s+\S/g);s&&s.length>=3&&(e=Math.max(e,s.length),n.push(`${s.length} bullet points`));let r=t.split(/;\s*/).filter(u=>u.trim().length>10);r.length>=3&&(e=Math.max(e,r.length),n.push(`${r.length} semicolon-separated goals`));let i=t.match(/\b(also|additionally|and\s+(?:fix|add|update|create|implement|remove|refactor))\b/gi);i&&i.length>=2&&(e=Math.max(e,i.length+1),n.push(`${i.length} transition keywords`));let a=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10);return{isComplex:e>=a,estimatedGoals:e,reason:n.length>0?n.join(", "):"single goal"}}function cu(t){if(!t||typeof t!="string")throw new Error("Empty response from orchestrator model");let e=t.trim();try{return JSON.parse(e)}catch{}let n=e.match(/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/);if(n)try{return JSON.parse(n[1].trim())}catch{}let o=e.search(/[[\{]/);if(o>=0){let s=e.slice(o);try{return JSON.parse(s)}catch{}}throw new Error(`Could not extract valid JSON from response:
810
- ${e.slice(0,200)}`)}async function s0(t,e,n={}){let o=n.maxSubTasks||ua,r=[{role:"system",content:Qy.replace("{maxSubTasks}",String(o)).replace("{prompt}",t)},{role:"user",content:t}],i={};if(e){let g=Xy(e);g.provider&&(i.provider=g.provider),g.model&&(i.model=g.model)}let c=(await Ky(r,[],i)).content||"",u=cu(c);if(!Array.isArray(u))throw new Error(`Decompose returned non-array: ${typeof u}`);let l=10,f=u.slice(0,o).map((g,w)=>({id:g.id||`t${w+1}`,task:String(g.task||""),scope:Array.isArray(g.scope)?g.scope:[],estimatedCalls:typeof g.estimatedCalls=="number"?Math.min(g.estimatedCalls,l):8,priority:typeof g.priority=="number"?g.priority:w+1})).filter(g=>g.task.length>0),p=f.reduce((g,w)=>g+w.estimatedCalls,0),h=ua*l;if(p>h){let{debugLog:g}=hc();g(`${Kt().T.yellow} \u26A0 Orchestrator: total estimated calls ${p} > ${h} \u2014 consider raising maxSubTasks${Kt().T.reset}`)}return f}async function o0(t,e,n){if(!t||t.length===0)return{summary:"No sub-tasks were executed.",conflicts:[],commitMessage:"",resourcesChanged:[]};let o=t.map((l,d)=>{let f=l.status==="done"?"SUCCESS":l.status==="truncated"?"PARTIAL":"FAILED";return`--- Agent ${d+1} [${f}] ---
809
+ {results}`;async function n0(t,e=1,n=2e3){for(let o=0;o<=e;o++)try{return await t()}catch(s){if(o===e)throw s;await new Promise(r=>setTimeout(r,n))}}function s0(t){let e=0,n=[];return function(){return new Promise(s=>{let r=()=>{e<t?(e++,s(()=>{e--,n.length>0&&n.shift()()})):n.push(r)};r()})}}function TR(t){if(!t||typeof t!="string")return{isComplex:!1,estimatedGoals:0,reason:"empty"};let e=0,n=[],o=t.match(/(?:(?:^|\n)\s*|\s)(?:\d+[.)]\s|[(]\d+[)][\s,]|[(][a-z][)][\s,])/g);o&&o.length>=2&&(e=Math.max(e,o.length),n.push(`${o.length} numbered items`));let s=t.match(/(?:^|\n)\s*[-*]\s+\S/g);s&&s.length>=3&&(e=Math.max(e,s.length),n.push(`${s.length} bullet points`));let r=t.split(/;\s*/).filter(u=>u.trim().length>10);r.length>=3&&(e=Math.max(e,r.length),n.push(`${r.length} semicolon-separated goals`));let i=t.match(/\b(also|additionally|and\s+(?:fix|add|update|create|implement|remove|refactor))\b/gi);i&&i.length>=2&&(e=Math.max(e,i.length+1),n.push(`${i.length} transition keywords`));let a=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10);return{isComplex:e>=a,estimatedGoals:e,reason:n.length>0?n.join(", "):"single goal"}}function cu(t){if(!t||typeof t!="string")throw new Error("Empty response from orchestrator model");let e=t.trim();try{return JSON.parse(e)}catch{}let n=e.match(/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/);if(n)try{return JSON.parse(n[1].trim())}catch{}let o=e.search(/[[\{]/);if(o>=0){let s=e.slice(o);try{return JSON.parse(s)}catch{}}throw new Error(`Could not extract valid JSON from response:
810
+ ${e.slice(0,200)}`)}async function o0(t,e,n={}){let o=n.maxSubTasks||ua,r=[{role:"system",content:e0.replace("{maxSubTasks}",String(o)).replace("{prompt}",t)},{role:"user",content:t}],i={};if(e){let g=Vy(e);g.provider&&(i.provider=g.provider),g.model&&(i.model=g.model)}let c=(await Xy(r,[],i)).content||"",u=cu(c);if(!Array.isArray(u))throw new Error(`Decompose returned non-array: ${typeof u}`);let l=10,f=u.slice(0,o).map((g,w)=>({id:g.id||`t${w+1}`,task:String(g.task||""),scope:Array.isArray(g.scope)?g.scope:[],estimatedCalls:typeof g.estimatedCalls=="number"?Math.min(g.estimatedCalls,l):8,priority:typeof g.priority=="number"?g.priority:w+1})).filter(g=>g.task.length>0),p=f.reduce((g,w)=>g+w.estimatedCalls,0),h=ua*l;if(p>h){let{debugLog:g}=hc();g(`${Kt().T.yellow} \u26A0 Orchestrator: total estimated calls ${p} > ${h} \u2014 consider raising maxSubTasks${Kt().T.reset}`)}return f}async function r0(t,e,n){if(!t||t.length===0)return{summary:"No sub-tasks were executed.",conflicts:[],commitMessage:"",resourcesChanged:[]};let o=t.map((l,d)=>{let f=l.status==="done"?"SUCCESS":l.status==="truncated"?"PARTIAL":"FAILED";return`--- Agent ${d+1} [${f}] ---
811
811
  Task: ${l.task}
812
812
  Result: ${l.result}
813
813
  Tools: ${(l.toolsUsed||[]).join(", ")||"none"}`}).join(`
814
814
 
815
- `),r=[{role:"system",content:e0.replace("{prompt}",e).replace("{results}",o)},{role:"user",content:"Synthesize the sub-agent results above."}],i={};if(n){let l=Xy(n);l.provider&&(i.provider=l.provider),l.model&&(i.model=l.model)}let c=(await Ky(r,[],i)).content||"",u=cu(c);return{summary:String(u.summary||""),conflicts:Array.isArray(u.conflicts)?u.conflicts:[],commitMessage:String(u.commitMessage||""),filesChanged:Array.isArray(u.filesChanged)?u.filesChanged:[]}}async function RR(t,e={}){let n=e.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL||Zy,o=e.workerModel||Jy,s=e.maxParallel||Vy,r=e.maxSubTasks||ua,i=e.onProgress||(()=>{}),a={input:0,output:0};console.log(`
815
+ `),r=[{role:"system",content:t0.replace("{prompt}",e).replace("{results}",o)},{role:"user",content:"Synthesize the sub-agent results above."}],i={};if(n){let l=Vy(n);l.provider&&(i.provider=l.provider),l.model&&(i.model=l.model)}let c=(await Xy(r,[],i)).content||"",u=cu(c);return{summary:String(u.summary||""),conflicts:Array.isArray(u.conflicts)?u.conflicts:[],commitMessage:String(u.commitMessage||""),filesChanged:Array.isArray(u.filesChanged)?u.filesChanged:[]}}async function RR(t,e={}){let n=e.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL||Qy,o=e.workerModel||Zy,s=e.maxParallel||Jy,r=e.maxSubTasks||ua,i=e.onProgress||(()=>{}),a={input:0,output:0};console.log(`
816
816
  ${ge.bold}Orchestrator${ge.reset} ${ge.dim}model: ${n} | workers: ${o} | max parallel: ${s}${ge.reset}
817
- `),i("decomposing"),console.log(`${ge.dim}Phase 1: Decomposing prompt into sub-tasks...${ge.reset}`);let c;try{c=await s0(t,n,{maxSubTasks:r})}catch(F){return console.log(`${ge.red}Decompose failed: ${F.message}${ge.reset}`),{results:[],synthesis:{summary:`Decompose failed: ${F.message}`,conflicts:[],commitMessage:"",resourcesChanged:[]},totalTokens:a}}if(c.length===0)return console.log(`${ge.yellow}No sub-tasks generated. Prompt may be too simple for orchestration.${ge.reset}`),{results:[],synthesis:{summary:"No sub-tasks generated.",conflicts:[],commitMessage:"",resourcesChanged:[]},totalTokens:a};console.log(`${ge.green}Decomposed into ${c.length} sub-tasks:${ge.reset}`);for(let F of c){console.log(` ${ge.dim}${F.id}:${ge.reset} ${F.task}`);let ee=F.scope.filter(Boolean);ee.length>0&&console.log(` ${ge.dim}scope: ${ee.join(", ")}${ge.reset}`)}console.log("");let u=new Map;for(let F=0;F<c.length;F++)for(let ee of c[F].scope)ee&&!u.has(ee)&&u.set(ee,F);i("executing"),console.log(`${ge.dim}Phase 2: Running ${c.length} sub-agents (max ${s} parallel)...${ge.reset}
818
- `);let l=Date.now(),d=n0(s),f={findings:[],_lock:!1},p=c.map(F=>{let ee=SR(F.task);return(ee?zy(ee.id):null)||o}),h=c.map((F,ee)=>{let be=`Agent ${ee+1} [${p[ee]}]: `,ve=Math.max(20,60-be.length),Fe=F.task.substring(0,ve)+(F.task.length>ve?"...":"");return be+Fe}),g=new ER(h);g.start();let w=`
817
+ `),i("decomposing"),console.log(`${ge.dim}Phase 1: Decomposing prompt into sub-tasks...${ge.reset}`);let c;try{c=await o0(t,n,{maxSubTasks:r})}catch(F){return console.log(`${ge.red}Decompose failed: ${F.message}${ge.reset}`),{results:[],synthesis:{summary:`Decompose failed: ${F.message}`,conflicts:[],commitMessage:"",resourcesChanged:[]},totalTokens:a}}if(c.length===0)return console.log(`${ge.yellow}No sub-tasks generated. Prompt may be too simple for orchestration.${ge.reset}`),{results:[],synthesis:{summary:"No sub-tasks generated.",conflicts:[],commitMessage:"",resourcesChanged:[]},totalTokens:a};console.log(`${ge.green}Decomposed into ${c.length} sub-tasks:${ge.reset}`);for(let F of c){console.log(` ${ge.dim}${F.id}:${ge.reset} ${F.task}`);let ee=F.scope.filter(Boolean);ee.length>0&&console.log(` ${ge.dim}scope: ${ee.join(", ")}${ge.reset}`)}console.log("");let u=new Map;for(let F=0;F<c.length;F++)for(let ee of c[F].scope)ee&&!u.has(ee)&&u.set(ee,F);i("executing"),console.log(`${ge.dim}Phase 2: Running ${c.length} sub-agents (max ${s} parallel)...${ge.reset}
818
+ `);let l=Date.now(),d=s0(s),f={findings:[],_lock:!1},p=c.map(F=>{let ee=SR(F.task);return(ee?Ky(ee.id):null)||o}),h=c.map((F,ee)=>{let be=`Agent ${ee+1} [${p[ee]}]: `,ve=Math.max(20,60-be.length),Fe=F.task.substring(0,ve)+(F.task.length>ve?"...":"");return be+Fe}),g=new ER(h);g.start();let w=`
819
819
  You are a focused coding agent executing ONE specific sub-task.
820
820
  Your scope is limited to the files listed in your task definition.
821
821
 
@@ -843,21 +843,21 @@ RULES:
843
843
  `,_=new Map;for(let F=0;F<c.length;F++){let ee=c[F].priority||1;_.has(ee)||_.set(ee,[]),_.get(ee).push({st:c[F],idx:F})}let S=[..._.keys()].sort((F,ee)=>F-ee),A=new Array(c.length);for(let F of S){let be=_.get(F).map(async({st:ve,idx:Fe})=>{let Me=await d();try{let Ee=await E(ve,Fe,{acquire:d,subTaskModels:p,labels:h,progress:g,sharedContext:f,_fileOwnership:u,workerModel:o,WORKER_SYSTEM_PROMPT:w});return A[Fe]=Ee,Ee}finally{Me()}});await Promise.all(be)}async function E(F,ee,be){try{let ve=f.findings.filter(Y=>Y.agentId!==F.id).map(Y=>`Agent ${Y.agentId} found: ${Y.summary}`).join(`
844
844
  `),Fe=[...u.entries()].filter(([,Y])=>Y===ee).map(([Y])=>Y),Me=[...u.entries()].filter(([,Y])=>Y!==ee).map(([Y])=>Y),Ee=[ve?`Prior agent findings:
845
845
  ${ve}
846
- `:"",F.scope.length>0?`Focus on files: ${F.scope.join(", ")}`:"",Fe.length>0?`You OWN these files (may read+write): ${Fe.join(", ")}`:"",Me.length>0?`READ ONLY (owned by other agents, do NOT write): ${Me.join(", ")}`:""].filter(Boolean),x=a0(F.task),P=p[ee],B=process.env.NEX_FALLBACK_MODEL||zy("agentic")||o,te=0,X=await t0(async()=>{let Y=te>0;Y&&(g.update(ee,"retry"),process.stderr.write(` ${ge.dim}[Agent ${ee+1}] retrying after error...${ge.reset}
847
- `)),te++;let re=Y&&P!==B?B:P;return Gy({task:F.task,type:x,context:Ee.length>0?Ee.join(`
848
- `):void 0,max_iterations:Math.min(F.estimatedCalls||10,15),model:re,_skipLog:!0,_systemPrompt:w,_readOnlyFiles:Me},{onUpdate:Z=>{if(Z&&Z.type==="tool_call"&&process.stderr.isTTY){let Se=`Agent ${ee+1} [${re}]`,Os=Z.tool||"...";g.labels[ee]=`${Se}: ${Os}`}}})},1,2e3),C="";if(i0(x,X,F,Fe)){let Y=[...new Set([...Fe,...Array.isArray(X.filesModified)?X.filesModified:[],...Array.isArray(F.scope)?F.scope:[]])].filter(Boolean);try{g.labels[ee]=`Agent ${ee+1} [${P}] review`,g.update(ee,"retry");let re=await Gy({task:`Review the completed changes for: ${F.task}`,type:"review",context:NR(F,X,Y),max_iterations:4,model:P,_skipLog:!0,_systemPrompt:w},{onUpdate:()=>{}},1);r0(re.result)?(C=`
846
+ `:"",F.scope.length>0?`Focus on files: ${F.scope.join(", ")}`:"",Fe.length>0?`You OWN these files (may read+write): ${Fe.join(", ")}`:"",Me.length>0?`READ ONLY (owned by other agents, do NOT write): ${Me.join(", ")}`:""].filter(Boolean),x=c0(F.task),P=p[ee],B=process.env.NEX_FALLBACK_MODEL||Ky("agentic")||o,te=0,X=await n0(async()=>{let Y=te>0;Y&&(g.update(ee,"retry"),process.stderr.write(` ${ge.dim}[Agent ${ee+1}] retrying after error...${ge.reset}
847
+ `)),te++;let re=Y&&P!==B?B:P;return zy({task:F.task,type:x,context:Ee.length>0?Ee.join(`
848
+ `):void 0,max_iterations:Math.min(F.estimatedCalls||10,15),model:re,_skipLog:!0,_systemPrompt:w,_readOnlyFiles:Me},{onUpdate:Z=>{if(Z&&Z.type==="tool_call"&&process.stderr.isTTY){let Se=`Agent ${ee+1} [${re}]`,Os=Z.tool||"...";g.labels[ee]=`${Se}: ${Os}`}}})},1,2e3),C="";if(a0(x,X,F,Fe)){let Y=[...new Set([...Fe,...Array.isArray(X.filesModified)?X.filesModified:[],...Array.isArray(F.scope)?F.scope:[]])].filter(Boolean);try{g.labels[ee]=`Agent ${ee+1} [${P}] review`,g.update(ee,"retry");let re=await zy({task:`Review the completed changes for: ${F.task}`,type:"review",context:NR(F,X,Y),max_iterations:4,model:P,_skipLog:!0,_systemPrompt:w},{onUpdate:()=>{}},1);i0(re.result)?(C=`
849
849
 
850
850
  Reviewer findings:
851
851
  ${re.result}`,f.findings.push({agentId:`${F.id}-review`,summary:String(re.result||"").slice(0,200),files:Y})):re.result&&(C=`
852
852
 
853
853
  Reviewer: ${re.result}`)}catch(re){C=`
854
854
 
855
- Reviewer note: review pass failed (${re.message})`}}let he=typeof X.result=="string"?`${X.result}${C}`.slice(0,200):`${String(X.result||"")}${C}`.slice(0,200);return f.findings.push({agentId:F.id,summary:he,files:Array.isArray(F.scope)?F.scope:[]}),g.labels[ee]=h[ee],g.update(ee,X.status==="failed"?"error":"done"),a.input+=X.tokensUsed?.input||0,a.output+=X.tokensUsed?.output||0,X.tokensUsed?._estimated&&(a._estimated=!0),{...X,result:`${String(X.result||"")}${C}`,_scope:F.scope,_idx:ee}}catch(ve){return g.labels[ee]=h[ee],g.update(ee,"error"),{task:F.task,status:"failed",result:`Error: ${ve.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}}}let v;try{v=A}finally{g.stop({silent:!0}),vR()}console.log("");let N=Math.round((Date.now()-l)/1e3),ne=N>=60?`${Math.floor(N/60)}m ${N%60}s`:`${N}s`;for(let F=0;F<v.length;F++){let ee=v[F],ve=ee.status==="done"||ee.status==="truncated"&&ee.result&&!ee.result.startsWith("Error")?`${ge.green}\u2713${ge.reset}`:`${ge.red}\u2717${ge.reset}`,Fe=ee._scope&&ee._scope.length>0?ee._scope.map(x=>x.replace(/^.*\//,"").replace(/\/$/,"")).filter(Boolean):[],Me=Fe.length>0?Fe.join(", "):ee.task.substring(0,35)+(ee.task.length>35?"...":""),Ee=F===v.length-1;console.log(` ${ve} Agent ${F+1} ${ge.dim}${Me}${ge.reset}${Ee?` ${ge.dim}${ne}${ge.reset}`:""}`)}console.log(""),i("synthesizing"),console.log(`${ge.dim}Phase 3: Synthesizing results...${ge.reset}`);let oe;try{oe=await o0(v,t,n)}catch(F){console.log(`${ge.yellow}Synthesize failed: ${F.message} \u2014 using raw results.${ge.reset}`),oe={summary:v.map(ee=>ee.result).join(`
855
+ Reviewer note: review pass failed (${re.message})`}}let he=typeof X.result=="string"?`${X.result}${C}`.slice(0,200):`${String(X.result||"")}${C}`.slice(0,200);return f.findings.push({agentId:F.id,summary:he,files:Array.isArray(F.scope)?F.scope:[]}),g.labels[ee]=h[ee],g.update(ee,X.status==="failed"?"error":"done"),a.input+=X.tokensUsed?.input||0,a.output+=X.tokensUsed?.output||0,X.tokensUsed?._estimated&&(a._estimated=!0),{...X,result:`${String(X.result||"")}${C}`,_scope:F.scope,_idx:ee}}catch(ve){return g.labels[ee]=h[ee],g.update(ee,"error"),{task:F.task,status:"failed",result:`Error: ${ve.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}}}let v;try{v=A}finally{g.stop({silent:!0}),vR()}console.log("");let N=Math.round((Date.now()-l)/1e3),ne=N>=60?`${Math.floor(N/60)}m ${N%60}s`:`${N}s`;for(let F=0;F<v.length;F++){let ee=v[F],ve=ee.status==="done"||ee.status==="truncated"&&ee.result&&!ee.result.startsWith("Error")?`${ge.green}\u2713${ge.reset}`:`${ge.red}\u2717${ge.reset}`,Fe=ee._scope&&ee._scope.length>0?ee._scope.map(x=>x.replace(/^.*\//,"").replace(/\/$/,"")).filter(Boolean):[],Me=Fe.length>0?Fe.join(", "):ee.task.substring(0,35)+(ee.task.length>35?"...":""),Ee=F===v.length-1;console.log(` ${ve} Agent ${F+1} ${ge.dim}${Me}${ge.reset}${Ee?` ${ge.dim}${ne}${ge.reset}`:""}`)}console.log(""),i("synthesizing"),console.log(`${ge.dim}Phase 3: Synthesizing results...${ge.reset}`);let oe;try{oe=await r0(v,t,n)}catch(F){console.log(`${ge.yellow}Synthesize failed: ${F.message} \u2014 using raw results.${ge.reset}`),oe={summary:v.map(ee=>ee.result).join(`
856
856
  `),conflicts:[],commitMessage:"",resourcesChanged:[]}}let ue=f.findings.flatMap(F=>F.files),fe=new Map;for(let F of ue)fe.set(F,(fe.get(F)||0)+1);let ie=[...fe.values()].some(F=>F>1),le=f.findings.length>1&&ie?` ${ge.dim}(agents shared context)${ge.reset}`:"";if(console.log(`
857
857
  ${ge.bold}Summary:${ge.reset} ${oe.summary}${le}`),oe.conflicts.length>0){console.log(`${ge.yellow}Conflicts:${ge.reset}`);for(let F of oe.conflicts)console.log(` - ${F}`)}oe.commitMessage&&console.log(`${ge.dim}Suggested commit: ${oe.commitMessage}${ge.reset}`);let T=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(`${ge.dim}Tokens: ${T}${ge.reset}
858
858
  `),{results:v,synthesis:oe,totalTokens:a}}var CR=/\b(research|analyze|investigate|check|verify|review|audit|read|find|search|discover|look|examine|inspect|scan|list)\b/i,AR=/\b(review|audit|verify|validate|inspect|critique)\b/i,OR=/\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 NR(t,e,n){let o=Array.isArray(n)&&n.length>0?`Files to review: ${n.join(", ")}`:"Files to review: inspect the files touched by the implementing agent";return["Review the finished implementation for correctness, regressions, and missing verification.",`Original task: ${t.task}`,o,`Implementation summary: ${String(e.result||"").slice(0,600)}`,'Report findings first. If no material issue exists, say "No material findings" and mention the main residual risk.'].join(`
859
- `)}function r0(t){return!t||typeof t!="string"?!1:!/no material findings/i.test(t)}function i0(t,e,n,o){if(t!=="implement"||!e||e.status==="failed")return!1;let s=Array.isArray(n?.scope)?n.scope.length:0,r=Array.isArray(e.filesModified)?e.filesModified.length:0,i=Array.isArray(o)?o.length:0;return s+r+i>0}function a0(t){if(!t)return"implement";let e=CR.test(t),n=AR.test(t);return OR.test(t)?"implement":n?"review":e?"explore":"implement"}c0.exports={runOrchestrated:RR,decompose:s0,synthesize:o0,detectComplexPrompt:TR,extractJSON:cu,createSemaphore:n0,DECOMPOSE_PROMPT:Qy,SYNTHESIZE_PROMPT:e0,DEFAULT_ORCHESTRATOR_MODEL:Zy,DEFAULT_WORKER_MODEL:Jy,DEFAULT_MAX_PARALLEL:Vy,DEFAULT_MAX_SUBTASKS:ua,withRetry:t0,_classifyWorkerType:a0,_hasMaterialReviewFindings:r0,_shouldRunFollowUpReview:i0}});var Yl=Q((GO,W0)=>{var{C:m,Spinner:ho,TaskProgress:MR,formatToolCall:PR,formatToolSummary:xu,formatSectionHeader:gr,formatMilestone:LR,setActiveTaskProgress:BO,getThinkingVerb:lu,setActiveModelForSpinner:u0}=rt(),{debugLog:L,warnLog:UO}=hc(),{MilestoneTracker:IR}=Ef(),{callStream:d0}=ct(),{parseToolArgs:jR}=Ao(),{executeTool:DR}=zs(),{gatherProjectContext:qR}=Zg(),{fitToContext:FR,forceCompress:hn,getUsage:en,estimateTokens:BR,buildProgressSnapshot:UR}=fn(),{autoSave:WR,flushAutoSave:HR}=na(),{scoreMessages:YR,formatScore:GR,appendScoreHistory:zR}=sa(),{detectCategory:KR,getModelForPhase:ku,getPhaseBudget:_s,isPhaseRoutingEnabled:XR}=ms();function Ne(t){WR(t),HR()}function da(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 VR(t){return!t||typeof t!="string"?!1:/\.(?:md|mdx|txt|rst|adoc)$/i.test(t)}function yr(t){try{if(!t.some(o=>o.role!=="assistant"?!1:!!(Array.isArray(o.content)&&o.content.some(s=>s&&s.type==="tool_use")||Array.isArray(o.tool_calls)&&o.tool_calls.length>0)))return;let n=YR(t);if(!n)return;console.log(GR(n,m));try{let{_getSessionsDir:o}=na(),s=require("fs"),r=require("path").join(o(),"_autosave.json");if(s.existsSync(r)){let i=JSON.parse(s.readFileSync(r,"utf-8"));i.score=n.score,i.scoreGrade=n.grade,i.scoreIssues=n.issues,s.writeFileSync(r,JSON.stringify(i,null,2))}}catch{}try{let{getActiveModel:o}=Ao(),s=Ur();zR(n.score,{version:s.version,model:o?o():null,sessionName:"_autosave",issues:n.issues})}catch{}}catch{}}var{getMemoryContext:JR}=er(),{getDeploymentContextBlock:ZR,probeUrlServer:QR,detectRuntimeDebugTarget:f0}=zl(),{getFewShotForInput:e1}=wy(),{checkPermission:t1,setPermission:n1,savePermissions:s1}=vy(),{confirm:E0,setAllowAlwaysHandler:o1,getAutoConfirm:Ts}=No(),{isPlanMode:Tr,getPlanModePrompt:r1,PLAN_MODE_ALLOWED_TOOLS:T0,setPlanContent:i1,extractStepsFromText:a1,createPlan:c1,getActivePlan:WO,startExecution:HO,advancePlanStep:l1,getPlanStepInfo:u1}=ca(),{StreamRenderer:d1}=Fy(),{runHooks:p0}=Yy(),{routeMCPCall:f1,getMCPToolDefinitions:p1}=Nc(),{getSkillInstructions:h1,getSkillToolDefinitions:m1,routeSkillCall:g1,matchSkillTriggers:y1}=Ac(),{trackUsage:h0,estimateTokens:m0}=ii();function g0(t){return!t||typeof t!="string"?0:typeof m0=="function"?m0(t):Math.ceil(t.length/4)}var{validateToolArgs:w1}=Lc(),{filterToolsForModel:y0,getModelTier:b1,PROVIDER_DEFAULT_TIER:YO}=Uo(),{getConfiguredProviders:$1,getActiveProviderName:mo,getActiveModelId:nn,setActiveModel:uu,MODEL_EQUIVALENTS:Ta}=ct(),{getModelProfile:_1,getModelBriefing:x1}=Li(),Ue=require("fs"),ze=require("path"),k1=(()=>{let t=parseInt(process.env.NEX_MILESTONE_STEPS??"5",10);return Number.isFinite(t)&&t>=0?t:5})();function v1(t){let e=LR(t.phaseName,t.stepCount,t.toolCounts,t.elapsed,t.filesRead,t.filesModified);process.stdout.write(`${e}
860
- `)}var w0=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi,b0=/(?:^|\s)(https?:\/\/[^\s]+\.(?:png|jpe?g|gif|webp)(?:\?[^\s]*)?)(?:\s|$)/gi,S1=/\b(?:clipboard|pasteboard|zwischenablage|screenshot aus clipboard)\b/i;function E1(t){let e=[],n;for(w0.lastIndex=0;(n=w0.exec(t))!==null;){let o=n[1].trim(),s=o.startsWith("~")?o.replace("~",process.env.HOME||""):ze.resolve(o);Ue.existsSync(s)&&e.push({raw:o,abs:s})}return e}function R0(t){let e=[],n;for(b0.lastIndex=0;(n=b0.exec(t))!==null;)e.push(n[1].trim());return e}async function C0(t){try{let n=await require("axios").get(t,{responseType:"arraybuffer",timeout:1e4,maxContentLength:10*1024*1024,headers:{"User-Agent":"nex-code/vision"}}),o=n.headers["content-type"]||"",s=o.startsWith("image/")?o.split(";")[0]:T1(t);return{data:Buffer.from(n.data).toString("base64"),media_type:s}}catch{return null}}function T1(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 A0(){if(process.platform!=="darwin")return null;let{spawnSync:t}=require("child_process"),e=ze.join(require("os").tmpdir(),`nex-clipboard-${Date.now()}.png`);if(t("pngpaste",[e],{timeout:3e3}).status===0&&Ue.existsSync(e)){let s=Ue.readFileSync(e);if(s.length>100)return{data:s.toString("base64"),media_type:"image/png",path:e};try{Ue.unlinkSync(e)}catch(r){console.error("Failed to unlink temp file:",r)}}let o=t("osascript",["-e",`try
859
+ `)}function i0(t){return!t||typeof t!="string"?!1:!/no material findings/i.test(t)}function a0(t,e,n,o){if(t!=="implement"||!e||e.status==="failed")return!1;let s=Array.isArray(n?.scope)?n.scope.length:0,r=Array.isArray(e.filesModified)?e.filesModified.length:0,i=Array.isArray(o)?o.length:0;return s+r+i>0}function c0(t){if(!t)return"implement";let e=CR.test(t),n=AR.test(t);return OR.test(t)?"implement":n?"review":e?"explore":"implement"}l0.exports={runOrchestrated:RR,decompose:o0,synthesize:r0,detectComplexPrompt:TR,extractJSON:cu,createSemaphore:s0,DECOMPOSE_PROMPT:e0,SYNTHESIZE_PROMPT:t0,DEFAULT_ORCHESTRATOR_MODEL:Qy,DEFAULT_WORKER_MODEL:Zy,DEFAULT_MAX_PARALLEL:Jy,DEFAULT_MAX_SUBTASKS:ua,withRetry:n0,_classifyWorkerType:c0,_hasMaterialReviewFindings:i0,_shouldRunFollowUpReview:a0}});var Yl=Q((zO,W0)=>{var{C:m,Spinner:ho,TaskProgress:MR,formatToolCall:PR,formatToolSummary:xu,formatSectionHeader:gr,formatMilestone:LR,setActiveTaskProgress:UO,getThinkingVerb:lu,setActiveModelForSpinner:d0}=rt(),{debugLog:L,warnLog:WO}=hc(),{MilestoneTracker:IR}=Tf(),{callStream:f0}=ct(),{parseToolArgs:jR}=Ao(),{executeTool:DR}=zs(),{gatherProjectContext:qR}=Qg(),{fitToContext:FR,forceCompress:hn,getUsage:en,estimateTokens:BR,buildProgressSnapshot:UR}=fn(),{autoSave:WR,flushAutoSave:HR}=na(),{scoreMessages:YR,formatScore:GR,appendScoreHistory:zR}=sa(),{detectCategory:KR,getModelForPhase:ku,getPhaseBudget:_s,isPhaseRoutingEnabled:XR}=ms();function Ne(t){WR(t),HR()}function da(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 VR(t){return!t||typeof t!="string"?!1:/\.(?:md|mdx|txt|rst|adoc)$/i.test(t)}function yr(t){try{if(!t.some(o=>o.role!=="assistant"?!1:!!(Array.isArray(o.content)&&o.content.some(s=>s&&s.type==="tool_use")||Array.isArray(o.tool_calls)&&o.tool_calls.length>0)))return;let n=YR(t);if(!n)return;console.log(GR(n,m));try{let{_getSessionsDir:o}=na(),s=require("fs"),r=require("path").join(o(),"_autosave.json");if(s.existsSync(r)){let i=JSON.parse(s.readFileSync(r,"utf-8"));i.score=n.score,i.scoreGrade=n.grade,i.scoreIssues=n.issues,s.writeFileSync(r,JSON.stringify(i,null,2))}}catch{}try{let{getActiveModel:o}=Ao(),s=Ur();zR(n.score,{version:s.version,model:o?o():null,sessionName:"_autosave",issues:n.issues})}catch{}}catch{}}var{getMemoryContext:JR}=er(),{getDeploymentContextBlock:ZR,probeUrlServer:QR,detectRuntimeDebugTarget:p0}=zl(),{getFewShotForInput:e1}=by(),{checkPermission:t1,setPermission:n1,savePermissions:s1}=Sy(),{confirm:T0,setAllowAlwaysHandler:o1,getAutoConfirm:Ts}=No(),{isPlanMode:Tr,getPlanModePrompt:r1,PLAN_MODE_ALLOWED_TOOLS:R0,setPlanContent:i1,extractStepsFromText:a1,createPlan:c1,getActivePlan:HO,startExecution:YO,advancePlanStep:l1,getPlanStepInfo:u1}=ca(),{StreamRenderer:d1}=By(),{runHooks:h0}=Gy(),{routeMCPCall:f1,getMCPToolDefinitions:p1}=Nc(),{getSkillInstructions:h1,getSkillToolDefinitions:m1,routeSkillCall:g1,matchSkillTriggers:y1}=Ac(),{trackUsage:m0,estimateTokens:g0}=ii();function y0(t){return!t||typeof t!="string"?0:typeof g0=="function"?g0(t):Math.ceil(t.length/4)}var{validateToolArgs:w1}=Lc(),{filterToolsForModel:w0,getModelTier:b1,PROVIDER_DEFAULT_TIER:GO}=Uo(),{getConfiguredProviders:$1,getActiveProviderName:mo,getActiveModelId:nn,setActiveModel:uu,MODEL_EQUIVALENTS:Ta}=ct(),{getModelProfile:_1,getModelBriefing:x1}=Li(),Ue=require("fs"),ze=require("path"),k1=(()=>{let t=parseInt(process.env.NEX_MILESTONE_STEPS??"5",10);return Number.isFinite(t)&&t>=0?t:5})();function v1(t){let e=LR(t.phaseName,t.stepCount,t.toolCounts,t.elapsed,t.filesRead,t.filesModified);process.stdout.write(`${e}
860
+ `)}var b0=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi,$0=/(?:^|\s)(https?:\/\/[^\s]+\.(?:png|jpe?g|gif|webp)(?:\?[^\s]*)?)(?:\s|$)/gi,S1=/\b(?:clipboard|pasteboard|zwischenablage|screenshot aus clipboard)\b/i;function E1(t){let e=[],n;for(b0.lastIndex=0;(n=b0.exec(t))!==null;){let o=n[1].trim(),s=o.startsWith("~")?o.replace("~",process.env.HOME||""):ze.resolve(o);Ue.existsSync(s)&&e.push({raw:o,abs:s})}return e}function C0(t){let e=[],n;for($0.lastIndex=0;(n=$0.exec(t))!==null;)e.push(n[1].trim());return e}async function A0(t){try{let n=await require("axios").get(t,{responseType:"arraybuffer",timeout:1e4,maxContentLength:10*1024*1024,headers:{"User-Agent":"nex-code/vision"}}),o=n.headers["content-type"]||"",s=o.startsWith("image/")?o.split(";")[0]:T1(t);return{data:Buffer.from(n.data).toString("base64"),media_type:s}}catch{return null}}function T1(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 O0(){if(process.platform!=="darwin")return null;let{spawnSync:t}=require("child_process"),e=ze.join(require("os").tmpdir(),`nex-clipboard-${Date.now()}.png`);if(t("pngpaste",[e],{timeout:3e3}).status===0&&Ue.existsSync(e)){let s=Ue.readFileSync(e);if(s.length>100)return{data:s.toString("base64"),media_type:"image/png",path:e};try{Ue.unlinkSync(e)}catch(r){console.error("Failed to unlink temp file:",r)}}let o=t("osascript",["-e",`try
861
861
  set imgData to the clipboard as \xABclass PNGf\xBB
862
862
  return "has_image"
863
863
  on error
@@ -868,47 +868,47 @@ end try`],{timeout:3e3});if(o.stdout&&o.stdout.toString().trim()==="has_image"){
868
868
  set fRef to open for access filePath with write permission
869
869
  write imgData to fRef
870
870
  close access fRef
871
- `;if(t("osascript",["-e",s],{timeout:5e3}).status===0&&Ue.existsSync(e)){let i=Ue.readFileSync(e);if(i.length>100)return{data:i.toString("base64"),media_type:"image/png",path:e}}}return null}function $0(t){let e=Ue.readFileSync(t),n=ze.extname(t).toLowerCase().replace(".",""),o=n==="jpg"||n==="jpeg"?"image/jpeg":n==="png"?"image/png":n==="gif"?"image/gif":n==="webp"?"image/webp":"image/png";return{data:e.toString("base64"),media_type:o}}function O0(t){let e=E1(t),n=R0(t),o=S1.test(t),s=n.length>0||o;if(e.length===0&&!s)return t;if(!s){let r=[{type:"text",text:t}];for(let i of e)try{let{data:a,media_type:c}=$0(i.abs);r.push({type:"image",media_type:c,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:c}=$0(i.abs);r.push({type:"image",media_type:c,data:a})}catch(a){L(`${m.yellow} \u26A0 Path resolution failed: ${a.message}${m.reset}`)}if(n.length>0){let i=await Promise.all(n.map(C0));for(let a of i)a&&r.push({type:"image",media_type:a.media_type,data:a.data})}if(o){let i=A0();i?(r.push({type:"image",media_type:i.media_type,data:i.data}),r[0].text+=`
871
+ `;if(t("osascript",["-e",s],{timeout:5e3}).status===0&&Ue.existsSync(e)){let i=Ue.readFileSync(e);if(i.length>100)return{data:i.toString("base64"),media_type:"image/png",path:e}}}return null}function _0(t){let e=Ue.readFileSync(t),n=ze.extname(t).toLowerCase().replace(".",""),o=n==="jpg"||n==="jpeg"?"image/jpeg":n==="png"?"image/png":n==="gif"?"image/gif":n==="webp"?"image/webp":"image/png";return{data:e.toString("base64"),media_type:o}}function N0(t){let e=E1(t),n=C0(t),o=S1.test(t),s=n.length>0||o;if(e.length===0&&!s)return t;if(!s){let r=[{type:"text",text:t}];for(let i of e)try{let{data:a,media_type:c}=_0(i.abs);r.push({type:"image",media_type:c,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:c}=_0(i.abs);r.push({type:"image",media_type:c,data:a})}catch(a){L(`${m.yellow} \u26A0 Path resolution failed: ${a.message}${m.reset}`)}if(n.length>0){let i=await Promise.all(n.map(A0));for(let a of i)a&&r.push({type:"image",media_type:a.media_type,data:a.data})}if(o){let i=O0();i?(r.push({type:"image",media_type:i.media_type,data:i.data}),r[0].text+=`
872
872
  [Clipboard image attached: ${i.path}]`):r[0].text+=`
873
- [No image found in clipboard]`}return r.length>1?r:t})()}var R1=[/\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 N0(t){return typeof t!="string"||!t?!1:R1.some(e=>e.test(t))}function C1(t){if(!t||t.length<200)return{text:t,truncated:!1,repeatCount:0};let n=t.split(/(?<=\. )/).filter(c=>c.trim().length>0);if(n.length<6)return{text:t,truncated:!1,repeatCount:0};let o=new Map;for(let c=0;c<=n.length-3;c++){let u=n.slice(c,c+3).join("").trim();u.length>30&&o.set(u,(o.get(u)||0)+1)}let s=0,r="";for(let[c,u]of o)u>s&&(s=u,r=c);if(s<3)return{text:t,truncated:!1,repeatCount:s};let i=`
873
+ [No image found in clipboard]`}return r.length>1?r:t})()}var R1=[/\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 M0(t){return typeof t!="string"||!t?!1:R1.some(e=>e.test(t))}function C1(t){if(!t||t.length<200)return{text:t,truncated:!1,repeatCount:0};let n=t.split(/(?<=\. )/).filter(c=>c.trim().length>0);if(n.length<6)return{text:t,truncated:!1,repeatCount:0};let o=new Map;for(let c=0;c<=n.length-3;c++){let u=n.slice(c,c+3).join("").trim();u.length>30&&o.set(u,(o.get(u)||0)+1)}let s=0,r="";for(let[c,u]of o)u>s&&(s=u,r=c);if(s<3)return{text:t,truncated:!1,repeatCount:s};let i=`
874
874
 
875
875
  [SYSTEM: Output repetition detected \u2014 response truncated (${s}\xD7 repeated paragraph)]`,a;if(t.length>8e3)a=t.slice(0,3e3)+i;else{let c=0,u=-1,l=0;for(;c<2;){let d=t.indexOf(r,l);if(d===-1)break;c++,u=d+r.length,l=d+1}a=u>0?t.slice(0,u)+i:t.slice(0,3e3)+i}return{text:a,truncated:!0,repeatCount:s}}function vu(t,e=5){if(!t||t.length<40)return{text:t,truncated:!1,repeatCount:0};let n=t.split(`
876
876
  `),o=new Map;for(let p of n){let h=p.trim();h.length>=20&&o.set(h,(o.get(h)||0)+1)}let s=0,r="";for(let[p,h]of o)h>s&&(s=h,r=p);let a=r.toLowerCase().includes("read_file")||r.toLowerCase().includes("reading")?2:e;if(s<=a)return{text:t,truncated:!1,repeatCount:s};let c=`
877
877
 
878
- \u26A0 [Response truncated: repeated paragraph detected (${s}\xD7)]`,u=0,l=-1,d=0;for(;u<e;){let p=t.indexOf(r,d);if(p===-1)break;u++,l=p+r.length,d=p+1}return{text:l>0?t.slice(0,l)+c:t.slice(0,2e3)+c,truncated:!0,repeatCount:s}}var du=null,fu=null,pu=null;function ht(){if(du===null){let{TOOL_DEFINITIONS:t}=zs();du=t}return fu===null&&(fu=m1()),pu===null&&(pu=p1()),[...du,...fu,...pu]}var Su=50;function A1(t){Number.isFinite(t)&&t>0&&(Su=t)}var ma=()=>null;function O1(t){ma=t}var _r=null,Eu=null,go=null,yo="",wo=0,Tu="",Ru=0,ga=new Map,N1=1e4,M1=6e3,P1=/\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 L1(t){return!t||typeof t!="string"?t:t.replace(P1,(e,n)=>`${n}=***REDACTED***`)}var I1=7e3,j1=4e3;function D1(t,e=null){let n=L1(t),o=BR(n),s=e==="read_file"?I1:N1,r=e==="read_file"?j1:M1;if(o>s)try{let{compressToolResult:i}=fn();return i(n,r)}catch{return n}return n}function M0(t){try{let{getActiveModel:e}=ct(),n=e(),o=n?`${n.provider}:${n.id}`:"default";if(ga.has(o))return ga.get(o);let s=y0(t);return ga.set(o,s),s}catch{return y0(t)}}function q1(){ga.clear()}function F1(t,e){let n=new Set(e);return(t||[]).some(o=>o.role!=="assistant"?!1:Array.isArray(o.tool_calls)?o.tool_calls.some(s=>n.has(s?.function?.name||s?.name)):Array.isArray(o.content)?o.content.some(s=>s?.type==="tool_use"&&n.has(s?.name)):!1)}var xr={hash:null,ts:0},B1=3e4;async function P0(){if(xr.hash&&Date.now()-xr.ts<B1)return xr.hash;try{let t=require("fs").promises,e=require("path"),n=[e.join(process.cwd(),"package.json"),e.join(process.cwd(),".git","HEAD"),e.join(process.cwd(),"README.md"),e.join(process.cwd(),"NEX.md")],s=(await Promise.allSettled(n.map(i=>t.stat(i).then(a=>`${i}:${a.mtimeMs}`)))).filter(i=>i.status==="fulfilled").map(i=>i.value);try{let{getMemoryContextHash:i}=er(),a=i();a&&s.push(`memory:${a}`)}catch{}try{let i=e.join(process.cwd(),".nex","brain");if(Ue.existsSync(i)){let a=await t.stat(i);s.push(`brain:${a.mtimeMs}`)}}catch{}let r=s.join("|");return xr={hash:r,ts:Date.now()},r}catch{return`fallback:${Date.now()}`}}function Cu(){_r=null,Eu=null,xr={hash:null,ts:0},go=null}var U1=new Set(["spawn_agents"]),hu=10,mu=10,fa=5,_0=6e4,gu=12e4,W1=process.env.NEX_STALE_AUTO_SWITCH!=="0";function H1(t){try{let e=require("fs"),n=require("path"),o=n.join(process.cwd(),".nex","plans");e.existsSync(o)||e.mkdirSync(o,{recursive:!0});let s=n.join(o,"current-plan.md");e.writeFileSync(s,t,"utf-8")}catch{}}o1(t=>{n1(t,"allow"),s1(),console.log(`${m.green} \u2713 ${t}: always allow${m.reset}`)});async function Y1(t){let e=t.function.name,n=jR(t.function.arguments),o=t.id||`cli-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!n){let d=ht().find(p=>p.function.name===e),f=d?JSON.stringify(d.function.parameters,null,2):"unknown";return L(`${m.yellow} \u26A0 ${e}: malformed arguments, sending schema hint${m.reset}`),{callId:o,fnName:e,args:null,canExecute:!1,errorResult:{role:"tool",content:`ERROR: Malformed tool arguments. Could not parse your arguments as JSON.
878
+ \u26A0 [Response truncated: repeated paragraph detected (${s}\xD7)]`,u=0,l=-1,d=0;for(;u<e;){let p=t.indexOf(r,d);if(p===-1)break;u++,l=p+r.length,d=p+1}return{text:l>0?t.slice(0,l)+c:t.slice(0,2e3)+c,truncated:!0,repeatCount:s}}var du=null,fu=null,pu=null;function ht(){if(du===null){let{TOOL_DEFINITIONS:t}=zs();du=t}return fu===null&&(fu=m1()),pu===null&&(pu=p1()),[...du,...fu,...pu]}var Su=50;function A1(t){Number.isFinite(t)&&t>0&&(Su=t)}var ma=()=>null;function O1(t){ma=t}var _r=null,Eu=null,go=null,yo="",wo=0,Tu="",Ru=0,ga=new Map,N1=1e4,M1=6e3,P1=/\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 L1(t){return!t||typeof t!="string"?t:t.replace(P1,(e,n)=>`${n}=***REDACTED***`)}var I1=7e3,j1=4e3;function D1(t,e=null){let n=L1(t),o=BR(n),s=e==="read_file"?I1:N1,r=e==="read_file"?j1:M1;if(o>s)try{let{compressToolResult:i}=fn();return i(n,r)}catch{return n}return n}function P0(t){try{let{getActiveModel:e}=ct(),n=e(),o=n?`${n.provider}:${n.id}`:"default";if(ga.has(o))return ga.get(o);let s=w0(t);return ga.set(o,s),s}catch{return w0(t)}}function q1(){ga.clear()}function F1(t,e){let n=new Set(e);return(t||[]).some(o=>o.role!=="assistant"?!1:Array.isArray(o.tool_calls)?o.tool_calls.some(s=>n.has(s?.function?.name||s?.name)):Array.isArray(o.content)?o.content.some(s=>s?.type==="tool_use"&&n.has(s?.name)):!1)}var xr={hash:null,ts:0},B1=3e4;async function L0(){if(xr.hash&&Date.now()-xr.ts<B1)return xr.hash;try{let t=require("fs").promises,e=require("path"),n=[e.join(process.cwd(),"package.json"),e.join(process.cwd(),".git","HEAD"),e.join(process.cwd(),"README.md"),e.join(process.cwd(),"NEX.md")],s=(await Promise.allSettled(n.map(i=>t.stat(i).then(a=>`${i}:${a.mtimeMs}`)))).filter(i=>i.status==="fulfilled").map(i=>i.value);try{let{getMemoryContextHash:i}=er(),a=i();a&&s.push(`memory:${a}`)}catch{}try{let i=e.join(process.cwd(),".nex","brain");if(Ue.existsSync(i)){let a=await t.stat(i);s.push(`brain:${a.mtimeMs}`)}}catch{}let r=s.join("|");return xr={hash:r,ts:Date.now()},r}catch{return`fallback:${Date.now()}`}}function Cu(){_r=null,Eu=null,xr={hash:null,ts:0},go=null}var U1=new Set(["spawn_agents"]),hu=10,mu=10,fa=5,x0=6e4,gu=12e4,W1=process.env.NEX_STALE_AUTO_SWITCH!=="0";function H1(t){try{let e=require("fs"),n=require("path"),o=n.join(process.cwd(),".nex","plans");e.existsSync(o)||e.mkdirSync(o,{recursive:!0});let s=n.join(o,"current-plan.md");e.writeFileSync(s,t,"utf-8")}catch{}}o1(t=>{n1(t,"allow"),s1(),console.log(`${m.green} \u2713 ${t}: always allow${m.reset}`)});async function Y1(t){let e=t.function.name,n=jR(t.function.arguments),o=t.id||`cli-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!n){let d=ht().find(p=>p.function.name===e),f=d?JSON.stringify(d.function.parameters,null,2):"unknown";return L(`${m.yellow} \u26A0 ${e}: malformed arguments, sending schema hint${m.reset}`),{callId:o,fnName:e,args:null,canExecute:!1,errorResult:{role:"tool",content:`ERROR: Malformed tool arguments. Could not parse your arguments as JSON.
879
879
  Raw input: ${typeof t.function.arguments=="string"?t.function.arguments.substring(0,200):"N/A"}
880
880
 
881
881
  Expected JSON schema for "${e}":
882
882
  ${f}
883
883
 
884
884
  Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:o}}}if(n&&typeof n.path=="string")try{let l=require("os"),d=ze.resolve(process.cwd(),n.path.replace(/^~/,l.homedir())),f=n.path;n.path=ze.relative(process.cwd(),d)||".",Object.defineProperty(n,"_originalPath",{value:f,enumerable:!1})}catch(l){console.error("path resolution failed:",l.message)}let s=w1(e,n);if(!s.valid){L(`${m.yellow} \u26A0 ${e}: ${s.error.split(`
885
- `)[0]}${m.reset}`);let l=(k0.get(e)||0)+1;k0.set(e,l);let d=l>=2?`${s.error}
885
+ `)[0]}${m.reset}`);let l=(v0.get(e)||0)+1;v0.set(e,l);let d=l>=2?`${s.error}
886
886
 
887
- [SYSTEM: This is argument error #${l} for "${e}". Study the "Expected parameters" schema above and correct your call \u2014 do not repeat the same mistake.]`:s.error;return{callId:o,fnName:e,args:n,canExecute:!1,errorResult:{role:"tool",content:d,tool_call_id:o}}}let r=s.corrected||n;if(s.corrected){let l=Object.keys(n),d=Object.keys(s.corrected),f=l.filter(p=>!d.includes(p));f.length&&console.log(`${m.dim} \u2713 ${e}: corrected args (${f.join(", ")})${m.reset}`)}if(Tr()&&!T0.has(e))return console.log(`${m.yellow} \u2717 ${e}: blocked in plan mode${m.reset}`),{callId:o,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`PLAN MODE: '${e}' is blocked. Only read-only tools are allowed. Present your plan as text output instead of making changes.`,tool_call_id:o}};let i=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"]),c=e==="spawn_agents"&&Array.isArray(r?.agents)&&r.agents.length>0&&r.agents.every(l=>l.background===!0);if(we&&Re==="plan"&&!i.has(e)&&!e.startsWith("skill_")&&!c)return Fn++,Er=e,L(`${m.yellow} \u2717 ${e}: blocked in plan phase (read-only, block #${Fn})${m.reset}`),{callId:o,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:o}};if(we&&Re==="verify"&&!a.has(e)&&!e.startsWith("skill_"))return L(`${m.yellow} \u2717 ${e}: blocked in verify phase (read + bash only)${m.reset}`),{callId:o,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:o}};let u=t1(e);if(u==="deny")return console.log(`${m.red} \u2717 ${e}: denied by permissions${m.reset}`),{callId:o,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`DENIED: Tool '${e}' is blocked by permissions`,tool_call_id:o}};if(u==="ask"){let l=` Allow ${e}?`;return e==="bash"&&r.command&&(l=` bash: \`${r.command.substring(0,80)}${r.command.length>80?"\u2026":""}\`?`),await E0(l,{toolName:e})?{callId:o,fnName:e,args:r,canExecute:!0,confirmedByUser:!0,errorResult:null}:{callId:o,fnName:e,args:r,canExecute:!1,confirmedByUser:!1,errorResult:{role:"tool",content:`CANCELLED: User declined ${e}`,tool_call_id:o}}}return{callId:o,fnName:e,args:r,canExecute:!0,confirmedByUser:!0,errorResult:null}}async function G1(t,e,n={}){let o=await g1(t,e);if(o!==null)return o;let s=await f1(t,e);return s!==null?s:DR(t,e,n)}function z1(t,e){switch(t){case"read_file":case"write_file":case"edit_file":case"patch_file":case"list_directory":return e._originalPath||e.path||"";case"bash":return(e.command||"").substring(0,60);case"grep":case"search_files":case"glob":return e.pattern||"";case"web_fetch":return(e.url||"").substring(0,50);case"web_search":return(e.query||"").substring(0,40);default:return""}}async function yu(t,e=!1){e||console.log(PR(t.fnName,t.args));let n=p0("pre-tool",{tool_name:t.fnName}),o=n.results;if(n.blocked){let w=`BLOCKED: pre-tool hook rejected ${t.fnName}: ${n.blockReason}`;e||console.log(`${m.yellow} [hook pre-tool] BLOCKED: ${n.blockReason}${m.reset}`);let _=xu(t.fnName,t.args,w,!0);return e||console.log(_),{msg:{role:"tool",content:w,tool_call_id:t.callId},summary:_}}if(!e&&o.length>0)for(let w of o)w.success?console.log(`${m.dim} [hook pre-tool] ${w.command} \u2192 ${w.output||"ok"}${m.reset}`):console.log(`${m.yellow} [hook pre-tool] ${w.command} \u2192 ERROR: ${w.error}${m.reset}`);wn?.onToolStart&&wn.onToolStart(t.fnName,t.args);let s=await G1(t.fnName,t.args,{silent:!0,autoConfirm:t.confirmedByUser===!0}),r=null,i;s&&typeof s=="object"&&s.text?(i=String(s.text),Array.isArray(s.images)&&s.images.length>0&&(r=s.images)):i=String(s??"");let a=i.length>5e4?i.substring(0,5e4)+`
887
+ [SYSTEM: This is argument error #${l} for "${e}". Study the "Expected parameters" schema above and correct your call \u2014 do not repeat the same mistake.]`:s.error;return{callId:o,fnName:e,args:n,canExecute:!1,errorResult:{role:"tool",content:d,tool_call_id:o}}}let r=s.corrected||n;if(s.corrected){let l=Object.keys(n),d=Object.keys(s.corrected),f=l.filter(p=>!d.includes(p));f.length&&console.log(`${m.dim} \u2713 ${e}: corrected args (${f.join(", ")})${m.reset}`)}if(Tr()&&!R0.has(e))return console.log(`${m.yellow} \u2717 ${e}: blocked in plan mode${m.reset}`),{callId:o,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`PLAN MODE: '${e}' is blocked. Only read-only tools are allowed. Present your plan as text output instead of making changes.`,tool_call_id:o}};let i=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"]),c=e==="spawn_agents"&&Array.isArray(r?.agents)&&r.agents.length>0&&r.agents.every(l=>l.background===!0);if(we&&Re==="plan"&&!i.has(e)&&!e.startsWith("skill_")&&!c)return Fn++,Er=e,L(`${m.yellow} \u2717 ${e}: blocked in plan phase (read-only, block #${Fn})${m.reset}`),{callId:o,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:o}};if(we&&Re==="verify"&&!a.has(e)&&!e.startsWith("skill_"))return L(`${m.yellow} \u2717 ${e}: blocked in verify phase (read + bash only)${m.reset}`),{callId:o,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:o}};let u=t1(e);if(u==="deny")return console.log(`${m.red} \u2717 ${e}: denied by permissions${m.reset}`),{callId:o,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`DENIED: Tool '${e}' is blocked by permissions`,tool_call_id:o}};if(u==="ask"){let l=` Allow ${e}?`;return e==="bash"&&r.command&&(l=` bash: \`${r.command.substring(0,80)}${r.command.length>80?"\u2026":""}\`?`),await T0(l,{toolName:e})?{callId:o,fnName:e,args:r,canExecute:!0,confirmedByUser:!0,errorResult:null}:{callId:o,fnName:e,args:r,canExecute:!1,confirmedByUser:!1,errorResult:{role:"tool",content:`CANCELLED: User declined ${e}`,tool_call_id:o}}}return{callId:o,fnName:e,args:r,canExecute:!0,confirmedByUser:!0,errorResult:null}}async function G1(t,e,n={}){let o=await g1(t,e);if(o!==null)return o;let s=await f1(t,e);return s!==null?s:DR(t,e,n)}function z1(t,e){switch(t){case"read_file":case"write_file":case"edit_file":case"patch_file":case"list_directory":return e._originalPath||e.path||"";case"bash":return(e.command||"").substring(0,60);case"grep":case"search_files":case"glob":return e.pattern||"";case"web_fetch":return(e.url||"").substring(0,50);case"web_search":return(e.query||"").substring(0,40);default:return""}}async function yu(t,e=!1){e||console.log(PR(t.fnName,t.args));let n=h0("pre-tool",{tool_name:t.fnName}),o=n.results;if(n.blocked){let w=`BLOCKED: pre-tool hook rejected ${t.fnName}: ${n.blockReason}`;e||console.log(`${m.yellow} [hook pre-tool] BLOCKED: ${n.blockReason}${m.reset}`);let _=xu(t.fnName,t.args,w,!0);return e||console.log(_),{msg:{role:"tool",content:w,tool_call_id:t.callId},summary:_}}if(!e&&o.length>0)for(let w of o)w.success?console.log(`${m.dim} [hook pre-tool] ${w.command} \u2192 ${w.output||"ok"}${m.reset}`):console.log(`${m.yellow} [hook pre-tool] ${w.command} \u2192 ERROR: ${w.error}${m.reset}`);wn?.onToolStart&&wn.onToolStart(t.fnName,t.args);let s=await G1(t.fnName,t.args,{silent:!0,autoConfirm:t.confirmedByUser===!0}),r=null,i;s&&typeof s=="object"&&s.text?(i=String(s.text),Array.isArray(s.images)&&s.images.length>0&&(r=s.images)):i=String(s??"");let a=i.length>5e4?i.substring(0,5e4)+`
888
888
  ...(truncated ${i.length-5e4} chars)`:i,c=a.split(`
889
- `)[0],u=c.startsWith("ERROR")||c.includes("CANCELLED")||c.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(a)&&/✗ Agent/.test(a),l=xu(t.fnName,t.args,a,u);e||console.log(l),wn?.onToolEnd&&wn.onToolEnd(t.fnName,l,!u);let f=p0("post-tool",{tool_name:t.fnName}).results;if(!e&&f.length>0)for(let w of f)w.success?console.log(`${m.dim} [hook post-tool] ${w.command} \u2192 ${w.output||"ok"}${m.reset}`):console.log(`${m.yellow} [hook post-tool] ${w.command} \u2192 ERROR: ${w.error}${m.reset}`);let h=D1(a,t.fnName);if(t.fnName==="bash"&&t.args?.command){let w=t.args.command.trim();!/cat\s*>|<</.test(w)&&/\bcat\s+\S/.test(w)?h+=`
889
+ `)[0],u=c.startsWith("ERROR")||c.includes("CANCELLED")||c.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(a)&&/✗ Agent/.test(a),l=xu(t.fnName,t.args,a,u);e||console.log(l),wn?.onToolEnd&&wn.onToolEnd(t.fnName,l,!u);let f=h0("post-tool",{tool_name:t.fnName}).results;if(!e&&f.length>0)for(let w of f)w.success?console.log(`${m.dim} [hook post-tool] ${w.command} \u2192 ${w.output||"ok"}${m.reset}`):console.log(`${m.yellow} [hook post-tool] ${w.command} \u2192 ERROR: ${w.error}${m.reset}`);let h=D1(a,t.fnName);if(t.fnName==="bash"&&t.args?.command){let w=t.args.command.trim();!/cat\s*>|<</.test(w)&&/\bcat\s+\S/.test(w)?h+=`
890
890
  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(w)&&!/npm|yarn|pnpm|make|git\b/.test(w)?h+=`
891
891
  HINT: use list_directory instead of bash ls \u2014 it is the preferred tool for listing directory contents.`:/\bfind\s+\S/.test(w)&&!/git\b|npm\b|-exec\b|-delete\b|-print0\b/.test(w)&&(h+=`
892
- 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(w=>({type:"image",media_type:w.media_type,data:w.base64}))]:h,tool_call_id:t.callId},summary:l}}var K1=[{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 wu(t){for(let{re:e,label:n}of K1){let o=t.match(e);if(o){let s=(o[1]||"").trim();return s?`${n}: ${s}`:n}}return null}async function X1(t,e=!1,n={}){let o=new Array(t.length),s=[],r=[],i=null;if(e&&!n.skipSpinner){let c=t.filter(u=>u.canExecute);if(c.length>0){let u;if(c.length===1){let l=c[0],d=z1(l.fnName,l.args);u=`\u23FA ${l.fnName}${d?`(${d})`:""}`}else{let l=c.map(d=>d.fnName).join(", ");u=`\u23FA ${c.length} tools: ${l.length>60?l.substring(0,57)+"\u2026":l}`}i=new ho(u),i.start()}}async function a(){if(r.length!==0){if(r.length===1){let c=r[0],{msg:u,summary:l}=await yu(t[c],e);o[c]=u,s.push(l)}else{let c=r.map(l=>yu(t[l],e)),u=await Promise.all(c);for(let l=0;l<r.length;l++)o[r[l]]=u[l].msg,s.push(u[l].summary)}r=[]}}for(let c=0;c<t.length;c++){let u=t[c];if(!u.canExecute){await a(),o[c]=u.errorResult,s.push(xu(u.fnName,u.args||{},u.errorResult.content,!0));continue}if(U1.has(u.fnName)){await a(),u.fnName==="spawn_agents"&&i&&(i.stop(),i=null);let{msg:l,summary:d}=await yu(u,e);o[c]=l,s.push(d)}else r.push(c)}if(await a(),i&&i.stop(),e&&s.length>0&&!n.skipSummaries)for(let c of s)console.log(c);return{results:o,summaries:s}}var M=[],x0=300,L0=900*1e3;function mn(t,e){let n=t.get(e);return n?Date.now()-n.ts>L0?(t.delete(e),0):n.count:0}function xs(t,e){let n=t.get(e),o=n&&Date.now()-n.ts<=L0?n.count+1:1;return t.set(e,{count:o,ts:Date.now()}),o}function bu(t,e,n){t.set(e,{count:n,ts:Date.now()})}var qu=new Map,I0=new Map,ya=new Map,Rr=new Set,j0=new Map,wa=new Map,Cr=new Set,yn=new Map,Tn=new Map,Ar=new Map,Ft=new Map,Rs=new Map,k0=new Map,Ra=new Map,Au=new Map,Bt=0,kr=0,ba=0,Ou="",$a=0,Mt=!1,pa=0,_a=0,vs=-1,Nu=!1,xa=0,ka=!1,Wt=0,Ht=!1,tn=0,Yt=0,dt=!1,vt="",vr=0,qn=0,va="",Ss=0,Es=0,Sa="",wr=0,Ut=!1,Mu=!1,Or=new Map,Nr=new Set,Sr=null,$u=!1,br=0,v0=!1,Re="plan",Ca=0,we=!1,Fn=0,Er=null,sn=null,Pu=null,Lu=null,bo=0,$o=0,_o=0,xo=!1,ko=0,Cs=null,As=[],ks=new Set;function V1(t){return t==="write_file"||t==="edit_file"||t==="patch_file"||t==="bash"}function S0(t){let e=String(t||"");if(!e)return!1;let n=/(?:^|\s)(?:\.{1,2}\/)?[\w./-]+\.(?:js|ts|tsx|jsx|py|md|json|yml|yaml|sh|css|html)\b/i.test(e),o=/\b(create|write|add|make|build|scaffold)\b[\s\S]{0,160}\b(refactor|rename|improve|update|change|edit)\b/i.test(e)||/\b(refactor|update|change|edit)\b[\s\S]{0,160}\b(create|write|add|make|build|scaffold)\b/i.test(e),s=/\b(create|write|add|make|build|refactor|update|change|edit)\b[\s\S]{0,160}\bfile\b/i.test(e);return n&&(o||s)}function Iu(t){return String(t||"").replace(/\\/g,"/").replace(/^\.\//,"").trim()}function J1(t){let n=String(t||"").match(/(?:^|\s)((?:\.{1,2}\/)?[\w./-]+\.(?:js|ts|tsx|jsx|py|md|json|yml|yaml|sh|css|html))\b/gi);return n?[...new Set(n.map(o=>Iu(o)))]:[]}function po(t,e){t===Ou?($a++,debug&&debug.DEBUG&&process.stdout.write(`\x1B[1A\x1B[2K${e} \u26A0 ${t} (\xD7${$a})${m.reset}
893
- `)):(Ou=t,$a=1,L(`${e} \u26A0 ${t}${m.reset}`))}var Ea=[];function Z1(t){Ea.push(t.trim())}function Q1(){return Ea.length===0?null:Ea.splice(0,Ea.length).join(`
894
- `)}function eC(t){let e=t._startedAt?Math.round((t.finishedAt-t._startedAt)/1e3):null,n=e!==null?`
892
+ 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(w=>({type:"image",media_type:w.media_type,data:w.base64}))]:h,tool_call_id:t.callId},summary:l}}var K1=[{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 wu(t){for(let{re:e,label:n}of K1){let o=t.match(e);if(o){let s=(o[1]||"").trim();return s?`${n}: ${s}`:n}}return null}async function X1(t,e=!1,n={}){let o=new Array(t.length),s=[],r=[],i=null;if(e&&!n.skipSpinner){let c=t.filter(u=>u.canExecute);if(c.length>0){let u;if(c.length===1){let l=c[0],d=z1(l.fnName,l.args);u=`\u23FA ${l.fnName}${d?`(${d})`:""}`}else{let l=c.map(d=>d.fnName).join(", ");u=`\u23FA ${c.length} tools: ${l.length>60?l.substring(0,57)+"\u2026":l}`}i=new ho(u),i.start()}}async function a(){if(r.length!==0){if(r.length===1){let c=r[0],{msg:u,summary:l}=await yu(t[c],e);o[c]=u,s.push(l)}else{let c=r.map(l=>yu(t[l],e)),u=await Promise.all(c);for(let l=0;l<r.length;l++)o[r[l]]=u[l].msg,s.push(u[l].summary)}r=[]}}for(let c=0;c<t.length;c++){let u=t[c];if(!u.canExecute){await a(),o[c]=u.errorResult,s.push(xu(u.fnName,u.args||{},u.errorResult.content,!0));continue}if(U1.has(u.fnName)){await a(),u.fnName==="spawn_agents"&&i&&(i.stop(),i=null);let{msg:l,summary:d}=await yu(u,e);o[c]=l,s.push(d)}else r.push(c)}if(await a(),i&&i.stop(),e&&s.length>0&&!n.skipSummaries)for(let c of s)console.log(c);return{results:o,summaries:s}}var M=[],k0=300,I0=900*1e3;function mn(t,e){let n=t.get(e);return n?Date.now()-n.ts>I0?(t.delete(e),0):n.count:0}function xs(t,e){let n=t.get(e),o=n&&Date.now()-n.ts<=I0?n.count+1:1;return t.set(e,{count:o,ts:Date.now()}),o}function bu(t,e,n){t.set(e,{count:n,ts:Date.now()})}var qu=new Map,j0=new Map,ya=new Map,Rr=new Set,D0=new Map,wa=new Map,Cr=new Set,yn=new Map,Tn=new Map,Ar=new Map,Ft=new Map,Rs=new Map,v0=new Map,Ra=new Map,Au=new Map,Bt=0,kr=0,ba=0,Ou="",$a=0,Mt=!1,pa=0,_a=0,vs=-1,Nu=!1,xa=0,ka=!1,Wt=0,Ht=!1,tn=0,Yt=0,dt=!1,vt="",vr=0,qn=0,va="",Ss=0,Es=0,Sa="",wr=0,Ut=!1,Mu=!1,Or=new Map,Nr=new Set,Sr=null,$u=!1,br=0,S0=!1,Re="plan",Ca=0,we=!1,Fn=0,Er=null,sn=null,Pu=null,Lu=null,bo=0,$o=0,_o=0,xo=!1,ko=0,Cs=null,As=[],ks=new Set;function V1(t){return t==="write_file"||t==="edit_file"||t==="patch_file"||t==="bash"}function E0(t){let e=String(t||"");if(!e)return!1;let n=/(?:^|\s)(?:\.{1,2}\/)?[\w./-]+\.(?:js|ts|tsx|jsx|py|md|json|yml|yaml|sh|css|html)\b/i.test(e),o=/\b(create|write|add|make|build|scaffold)\b[\s\S]{0,160}\b(refactor|rename|improve|update|change|edit)\b/i.test(e)||/\b(refactor|update|change|edit)\b[\s\S]{0,160}\b(create|write|add|make|build|scaffold)\b/i.test(e),s=/\b(create|write|add|make|build|refactor|update|change|edit)\b[\s\S]{0,160}\bfile\b/i.test(e);return n&&(o||s)}function J1(t){let e=String(t||"").trim();return e?/^(hi|hello|hey|yo)\b/i.test(e)||/\b(introduce yourself|who are you|what can you do|tell me about yourself)\b/i.test(e):!1}function Iu(t){return String(t||"").replace(/\\/g,"/").replace(/^\.\//,"").trim()}function Z1(t){let n=String(t||"").match(/(?:^|\s)((?:\.{1,2}\/)?[\w./-]+\.(?:js|ts|tsx|jsx|py|md|json|yml|yaml|sh|css|html))\b/gi);return n?[...new Set(n.map(o=>Iu(o)))]:[]}function po(t,e){t===Ou?($a++,debug&&debug.DEBUG&&process.stdout.write(`\x1B[1A\x1B[2K${e} \u26A0 ${t} (\xD7${$a})${m.reset}
893
+ `)):(Ou=t,$a=1,L(`${e} \u26A0 ${t}${m.reset}`))}var Ea=[];function Q1(t){Ea.push(t.trim())}function eC(){return Ea.length===0?null:Ea.splice(0,Ea.length).join(`
894
+ `)}function tC(t){let e=t._startedAt?Math.round((t.finishedAt-t._startedAt)/1e3):null,n=e!==null?`
895
895
  Duration: ${e}s`:"",o=typeof t.result.result=="string"?t.result.result.slice(0,4e3):JSON.stringify(t.result.result||"").slice(0,4e3),s=t.result.filesModified&&t.result.filesModified.length>0?`
896
896
  Files modified: ${t.result.filesModified.join(", ")}`:"";return`[BACKGROUND AGENT COMPLETED]
897
897
  Job: ${t.jobId}
898
898
  Task: "${t.agentDef.task}"`+n+`
899
899
  Status: ${t.result.status||"done"}`+s+`
900
- Result: ${o}`}function ha(t,e){let{getCompletedJobs:n}=to(),o=n();for(let s of o){let r={role:"user",content:eC(s)};t.push(r),e.push(r);let i=s.result?.status||"done",a=i==="failed"?m.red+" \u2717":m.cyan+" \u2713";process.stderr.write(`${a} Background agent ${i}: ${s.agentDef.task.slice(0,50)} \u2014 ${String(s.result?.result||"").slice(0,80)}${m.reset}
901
- `)}}function D0(t,e){let n=[],o=new Set([...e.keys(),...Rr,...Cr]);if(!o.size||!t)return n;for(let s of o){let r=s.split("/").pop();if(r&&(t.includes(r)||t.includes(s))){let a=t.split(`
902
- `).find(c=>c.includes(r)||c.includes(s));n.push({file:s,action:(a||"edit this file").trim().slice(0,200),done:!1})}}return n}function tC(t){if(!t||typeof t!="string")return[];let e=t.match(/[A-Za-z_][A-Za-z0-9_]{2,}/g)||[],n=new Set(["the","and","for","with","from","into","that","this","when","then","have","your","just","read","write","edit","file","files","test","tests","verify","phase","implement","summary","report","pass","fail","changes","change","address","original","task","user","request","code","module","function","class"]),o=new Set,s=[];for(let r of e){let i=r.toLowerCase();n.has(i)||o.has(i)||(o.add(i),s.push(r))}return s.sort((r,i)=>i.length-r.length),s.slice(0,6)}function nC(){return Ue.existsSync(ze.join(process.cwd(),"pnpm-lock.yaml"))?"pnpm":Ue.existsSync(ze.join(process.cwd(),"yarn.lock"))?"yarn":"npm"}function gn(t){let e=nC();return t==="test"?e==="yarn"?"yarn test":e==="pnpm"?"pnpm test":"npm test":e==="yarn"?`yarn ${t}`:e==="pnpm"?`pnpm run ${t}`:`npm run ${t}`}function sC(t,e,n){let o=[...t||[]].slice(0,6).join(", ")||"recently modified files",s=(e||[]).slice(0,3),r=(n||[]).slice(0,3),i=[`[SYSTEM] You already changed code in: ${o}.`,"Run one narrow verification step next before more exploration."];return s.length>0&&i.push(`Suggested verification commands: ${s.join(" | ")}`),r.length>0&&i.push(`Likely related tests: ${r.join(", ")}`),i.push("Do not continue broad read/search loops until the latest edit has been checked."),i.join(`
903
- `)}function oC(t){if(!t||!t.fnName||!["bash","ssh_exec"].includes(t.fnName))return!1;let e=String(t.args?.command||"").toLowerCase();return/\b(test|jest|vitest|pytest|mocha|rspec|phpunit|cargo test|go test|tsc|build|lint|eslint|check)\b/.test(e)}async function q0(t){let e=tC(t);if(e.length===0)return[];let{searchContentIndex:n}=cn(),o=[],s=new Set;for(let r of e)try{let i=await n(r,void 0,process.cwd());for(let a of i.slice(0,3)){let c=`${a.file}:${a.name}:${a.line}`;if(!s.has(c)&&(s.add(c),o.push(a),o.length>=5))return o}}catch{}return o}async function F0(t){let e=await q0(t);if(e.length===0)return"";let{getRelatedFiles:n,findSymbolReferences:o}=cn(),s=["Likely symbol targets:"];for(let r=0;r<e.length;r++){let i=e[r],a=Math.max(1,i.line-20),c=i.line+40;s.push(`${r+1}. ${i.name} (${i.type}) in ${i.file}:${i.line} -> read_file(path='${i.file}', line_start=${a}, line_end=${c})`);try{let u=await n(i.file,process.cwd(),3);u.length>0&&s.push(` Follow-up files: ${u.join(", ")} (read only if the primary symbol points into one of these modules)`)}catch{}try{let u=await o(i.name,process.cwd(),{excludeFile:i.file,excludeLine:i.line,limit:2});u.length>0&&s.push(` Likely callers/usages: ${u.map(l=>`${l.file}:${l.line}`).join(", ")} (read these next if behavior depends on where ${i.name} is invoked)`)}catch{}}return`${s.join(`
900
+ Result: ${o}`}function ha(t,e){let{getCompletedJobs:n}=to(),o=n();for(let s of o){let r={role:"user",content:tC(s)};t.push(r),e.push(r);let i=s.result?.status||"done",a=i==="failed"?m.red+" \u2717":m.cyan+" \u2713";process.stderr.write(`${a} Background agent ${i}: ${s.agentDef.task.slice(0,50)} \u2014 ${String(s.result?.result||"").slice(0,80)}${m.reset}
901
+ `)}}function q0(t,e){let n=[],o=new Set([...e.keys(),...Rr,...Cr]);if(!o.size||!t)return n;for(let s of o){let r=s.split("/").pop();if(r&&(t.includes(r)||t.includes(s))){let a=t.split(`
902
+ `).find(c=>c.includes(r)||c.includes(s));n.push({file:s,action:(a||"edit this file").trim().slice(0,200),done:!1})}}return n}function nC(t){if(!t||typeof t!="string")return[];let e=t.match(/[A-Za-z_][A-Za-z0-9_]{2,}/g)||[],n=new Set(["the","and","for","with","from","into","that","this","when","then","have","your","just","read","write","edit","file","files","test","tests","verify","phase","implement","summary","report","pass","fail","changes","change","address","original","task","user","request","code","module","function","class"]),o=new Set,s=[];for(let r of e){let i=r.toLowerCase();n.has(i)||o.has(i)||(o.add(i),s.push(r))}return s.sort((r,i)=>i.length-r.length),s.slice(0,6)}function sC(){return Ue.existsSync(ze.join(process.cwd(),"pnpm-lock.yaml"))?"pnpm":Ue.existsSync(ze.join(process.cwd(),"yarn.lock"))?"yarn":"npm"}function gn(t){let e=sC();return t==="test"?e==="yarn"?"yarn test":e==="pnpm"?"pnpm test":"npm test":e==="yarn"?`yarn ${t}`:e==="pnpm"?`pnpm run ${t}`:`npm run ${t}`}function oC(t,e,n){let o=[...t||[]].slice(0,6).join(", ")||"recently modified files",s=(e||[]).slice(0,3),r=(n||[]).slice(0,3),i=[`[SYSTEM] You already changed code in: ${o}.`,"Run one narrow verification step next before more exploration."];return s.length>0&&i.push(`Suggested verification commands: ${s.join(" | ")}`),r.length>0&&i.push(`Likely related tests: ${r.join(", ")}`),i.push("Do not continue broad read/search loops until the latest edit has been checked."),i.join(`
903
+ `)}function rC(t){if(!t||!t.fnName||!["bash","ssh_exec"].includes(t.fnName))return!1;let e=String(t.args?.command||"").toLowerCase();return/\b(test|jest|vitest|pytest|mocha|rspec|phpunit|cargo test|go test|tsc|build|lint|eslint|check)\b/.test(e)}async function F0(t){let e=nC(t);if(e.length===0)return[];let{searchContentIndex:n}=cn(),o=[],s=new Set;for(let r of e)try{let i=await n(r,void 0,process.cwd());for(let a of i.slice(0,3)){let c=`${a.file}:${a.name}:${a.line}`;if(!s.has(c)&&(s.add(c),o.push(a),o.length>=5))return o}}catch{}return o}async function B0(t){let e=await F0(t);if(e.length===0)return"";let{getRelatedFiles:n,findSymbolReferences:o}=cn(),s=["Likely symbol targets:"];for(let r=0;r<e.length;r++){let i=e[r],a=Math.max(1,i.line-20),c=i.line+40;s.push(`${r+1}. ${i.name} (${i.type}) in ${i.file}:${i.line} -> read_file(path='${i.file}', line_start=${a}, line_end=${c})`);try{let u=await n(i.file,process.cwd(),3);u.length>0&&s.push(` Follow-up files: ${u.join(", ")} (read only if the primary symbol points into one of these modules)`)}catch{}try{let u=await o(i.name,process.cwd(),{excludeFile:i.file,excludeLine:i.line,limit:2});u.length>0&&s.push(` Likely callers/usages: ${u.map(l=>`${l.file}:${l.line}`).join(", ")} (read these next if behavior depends on where ${i.name} is invoked)`)}catch{}}return`${s.join(`
904
904
  `)}
905
905
  Use these exact targeted reads before broader searching.
906
906
 
907
- `}async function Aa(t){let{getFileIndex:e}=cn(),{buildContentIndex:n,findSymbolReferences:o,getRelatedFiles:s}=cn(),i=e().filter(u=>/^tests?\//.test(u)||/\.test\./.test(u)||/\.spec\./.test(u));if(i.length===0)return[];let a=new Set,c=await n(process.cwd());for(let u of t||[]){let l=String(u),d=ze.basename(l).replace(/\.[^.]+$/,"");if(d.length<3)continue;for(let h of i)if(h.includes(d)&&a.add(h),a.size>=4)return[...a];try{let h=await s(l,process.cwd(),4);for(let g of h){let w=ze.basename(g).replace(/\.[^.]+$/,"");if(!(w.length<3)){for(let _ of i)if(_.includes(w)&&a.add(_),a.size>=4)return[...a]}}}catch{}let p=(Array.isArray(c.files?.[l]?.defs)?c.files[l].defs:[]).filter(h=>["function","class","export"].includes(h.type)).map(h=>h.name).filter((h,g,w)=>h&&w.indexOf(h)===g).slice(0,3);for(let h of p)try{let g=await o(h,process.cwd(),{excludeFile:l,limit:8});for(let w of g)if(i.includes(w.file)&&a.add(w.file),a.size>=4)return[...a]}catch{}}return[...a]}function rC(t,e={}){if(!Array.isArray(t)||t.length===0)return[];let n=t.slice(0,4).join(" "),o=[],s=String(e.test||"");return/vitest/.test(s)||Ue.existsSync(ze.join(process.cwd(),"vitest.config.ts"))||Ue.existsSync(ze.join(process.cwd(),"vitest.config.js"))?o.push(`npx vitest run ${n}`):(/jest/.test(s)||Ue.existsSync(ze.join(process.cwd(),"jest.config.js"))||Ue.existsSync(ze.join(process.cwd(),"jest.config.cjs"))||Ue.existsSync(ze.join(process.cwd(),"jest.config.mjs")))&&o.push(`npx jest --runInBand ${n}`),(Ue.existsSync(ze.join(process.cwd(),"pytest.ini"))||Ue.existsSync(ze.join(process.cwd(),"pyproject.toml")))&&t.some(r=>/\.py$/i.test(r))&&o.push(`pytest ${t.filter(r=>/\.py$/i.test(r)).slice(0,4).join(" ")}`),o}async function $r(t,e,n,o){if(!we)return null;let s=Re;Re=t,Ca=0,sn=ku(t,Cs),t==="verify"&&($o=0,_o=0,xo=!1,ko=0),Wt=0,Ht=!1,tn=0,Yt=0,Rs.clear(),Ra.clear(),qu.clear(),Ar.clear(),t==="implement"&&(As=D0(e||"",yn));let r=As.length>0?`
907
+ `}async function Aa(t){let{getFileIndex:e}=cn(),{buildContentIndex:n,findSymbolReferences:o,getRelatedFiles:s}=cn(),i=e().filter(u=>/^tests?\//.test(u)||/\.test\./.test(u)||/\.spec\./.test(u));if(i.length===0)return[];let a=new Set,c=await n(process.cwd());for(let u of t||[]){let l=String(u),d=ze.basename(l).replace(/\.[^.]+$/,"");if(d.length<3)continue;for(let h of i)if(h.includes(d)&&a.add(h),a.size>=4)return[...a];try{let h=await s(l,process.cwd(),4);for(let g of h){let w=ze.basename(g).replace(/\.[^.]+$/,"");if(!(w.length<3)){for(let _ of i)if(_.includes(w)&&a.add(_),a.size>=4)return[...a]}}}catch{}let p=(Array.isArray(c.files?.[l]?.defs)?c.files[l].defs:[]).filter(h=>["function","class","export"].includes(h.type)).map(h=>h.name).filter((h,g,w)=>h&&w.indexOf(h)===g).slice(0,3);for(let h of p)try{let g=await o(h,process.cwd(),{excludeFile:l,limit:8});for(let w of g)if(i.includes(w.file)&&a.add(w.file),a.size>=4)return[...a]}catch{}}return[...a]}function iC(t,e={}){if(!Array.isArray(t)||t.length===0)return[];let n=t.slice(0,4).join(" "),o=[],s=String(e.test||"");return/vitest/.test(s)||Ue.existsSync(ze.join(process.cwd(),"vitest.config.ts"))||Ue.existsSync(ze.join(process.cwd(),"vitest.config.js"))?o.push(`npx vitest run ${n}`):(/jest/.test(s)||Ue.existsSync(ze.join(process.cwd(),"jest.config.js"))||Ue.existsSync(ze.join(process.cwd(),"jest.config.cjs"))||Ue.existsSync(ze.join(process.cwd(),"jest.config.mjs")))&&o.push(`npx jest --runInBand ${n}`),(Ue.existsSync(ze.join(process.cwd(),"pytest.ini"))||Ue.existsSync(ze.join(process.cwd(),"pyproject.toml")))&&t.some(r=>/\.py$/i.test(r))&&o.push(`pytest ${t.filter(r=>/\.py$/i.test(r)).slice(0,4).join(" ")}`),o}async function $r(t,e,n,o){if(!we)return null;let s=Re;Re=t,Ca=0,sn=ku(t,Cs),t==="verify"&&($o=0,_o=0,xo=!1,ko=0),Wt=0,Ht=!1,tn=0,Yt=0,Rs.clear(),Ra.clear(),qu.clear(),Ar.clear(),t==="implement"&&(As=q0(e||"",yn));let r=As.length>0?`
908
908
 
909
909
  ACTION ITEMS (execute these in order, do NOT re-read these files):
910
910
  `+As.map((c,u)=>`${u+1}. ${c.file} \u2014 ${c.action}`).join(`
911
- `):"",i=await F0(t==="verify"?o:e||o||""),a;if(t==="implement")Pu=e?.slice(0,2e3)||"",a=`[PHASE: IMPLEMENTATION] Analysis complete. Based on the analysis:
911
+ `):"",i=await B0(t==="verify"?o:e||o||""),a;if(t==="implement")Pu=e?.slice(0,2e3)||"",a=`[PHASE: IMPLEMENTATION] Analysis complete. Based on the analysis:
912
912
  ${Pu}
913
913
 
914
914
  ${i}Now implement the fix/changes. Do not investigate further \u2014 edit files directly.`+r;else if(t==="verify"){Lu=e?.slice(0,500)||"";let c=n?[...n].join(", "):"none",u=await Fu(n),l=await Aa(n),d=u.length>0?`Suggested checks (run the narrowest ones that fit the change):
@@ -928,21 +928,24 @@ Prefer these before broader suites when a targeted run is possible.
928
928
  Report PASS (all good) or FAIL (list specific issues).
929
929
 
930
930
  Files modified: ${c}
931
- ${i}${d}${f}Summary: ${Lu}`}return L(`${m.cyan} \u21B3 Phase transition: ${s} \u2192 ${t} (model: ${sn||"default"})${m.reset}`),a?{role:"user",content:a}:null}async function Fu(t){let e=[],o=[...t||[]].map(c=>String(c).toLowerCase()),s={};try{let c=ze.join(process.cwd(),"package.json");if(Ue.existsSync(c)){s=JSON.parse(Ue.readFileSync(c,"utf-8")).scripts||{};let l=[["test",gn("test")],["lint",gn("lint")],["typecheck",gn("typecheck")],["check",gn("check")],["build",gn("build")]];for(let[d,f]of l)s[d]&&e.push(f)}}catch{}e.length===0&&(Ue.existsSync(ze.join(process.cwd(),"package.json"))&&e.push(gn("test")),(Ue.existsSync(ze.join(process.cwd(),"pytest.ini"))||Ue.existsSync(ze.join(process.cwd(),"pyproject.toml")))&&e.push("pytest"));let r=await Aa(t);e.unshift(...rC(r,s));let i=o.some(c=>/\.(ts|tsx)$/.test(c)),a=o.some(c=>/\.(js|jsx|ts|tsx)$/.test(c));return i&&!e.includes(gn("typecheck"))&&e.push(gn("typecheck")),a&&!e.includes(gn("lint"))&&e.push(gn("lint")),[...new Set(e)].slice(0,4)}function iC(t){let e=process.env.NEX_LANGUAGE;if(e&&e!=="auto")return e;if(U0())return"English";let n=String(t||"").trim();if(!n)return"English";if(/[äöüß]/i.test(n))return"German";let o=n.toLowerCase().match(/[a-zA-Zäöüß]+/g)||[],s=new Set(["a","an","and","are","can","do","does","explain","file","folder","for","how","in","is","it","list","of","please","show","the","this","what","where","why","with"]),r=new Set(["aber","analysiere","bitte","das","den","der","die","dies","diese","diesem","du","ein","eine","einer","englisch","erkl\xE4re","f\xFCr","hier","im","ist","mit","ordner","und","warum","was","wie","wieso","zeige"]),i=0,a=0;for(let c of o)s.has(c)&&i++,r.has(c)&&a++;return a>i?"German":(i>a,"English")}function aC(){let t=process.env.NEX_LANGUAGE,e=process.env.NEX_CODE_LANGUAGE,n=process.env.NEX_COMMIT_LANGUAGE,o=U0(),s=!t||t==="auto"?null:t,r=[`# Language Rules (CRITICAL \u2014 enforce strictly)
932
- `];s?r.push(`RESPONSE LANGUAGE: You MUST always respond in ${s}. 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. ${s} only.`):o?r.push("RESPONSE LANGUAGE: This project requires English. Always respond in English, even if the user writes in another language."):r.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."),r.push("CODE EXAMPLES: Always show actual, working code examples \u2014 never pseudocode or placeholder snippets."),r.push("COMPLETENESS RULES:"),r.push(" \u2022 ALWAYS show actual code when explaining implementations \u2014 never describe without showing"),Ts()?r.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."):r.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."),r.push(" \u2022 Include complete examples with full context (imports, function signatures, error handling)"),r.push(' \u2022 Show alternative approaches when relevant (e.g., "Alternative: use util.promisify instead")'),r.push(" \u2022 Include edge cases in explanations (empty input, null values, boundary conditions)"),r.push(" \u2022 Provide platform-specific guidance when commands differ by OS (Linux/macOS/Windows)"),r.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.'),r.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."),r.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."),r.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.'),r.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).'),r.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)."),r.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."),r.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."),r.push(" \u2022 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\u2011handling middleware \u2014 do not just send a raw 500 response."),r.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.'),r.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 i=e||"English";r.push(`CODE LANGUAGE: Write all code comments, docstrings, variable descriptions, and inline documentation in ${i}.`);let a=n||"English";return r.push(`COMMIT MESSAGES: Write all git commit messages in ${a}.`),s&&r.push(`
931
+ ${i}${d}${f}Summary: ${Lu}`}return L(`${m.cyan} \u21B3 Phase transition: ${s} \u2192 ${t} (model: ${sn||"default"})${m.reset}`),a?{role:"user",content:a}:null}async function Fu(t){let e=[],o=[...t||[]].map(c=>String(c).toLowerCase()),s={};try{let c=ze.join(process.cwd(),"package.json");if(Ue.existsSync(c)){s=JSON.parse(Ue.readFileSync(c,"utf-8")).scripts||{};let l=[["test",gn("test")],["lint",gn("lint")],["typecheck",gn("typecheck")],["check",gn("check")],["build",gn("build")]];for(let[d,f]of l)s[d]&&e.push(f)}}catch{}e.length===0&&(Ue.existsSync(ze.join(process.cwd(),"package.json"))&&e.push(gn("test")),(Ue.existsSync(ze.join(process.cwd(),"pytest.ini"))||Ue.existsSync(ze.join(process.cwd(),"pyproject.toml")))&&e.push("pytest"));let r=await Aa(t);e.unshift(...iC(r,s));let i=o.some(c=>/\.(ts|tsx)$/.test(c)),a=o.some(c=>/\.(js|jsx|ts|tsx)$/.test(c));return i&&!e.includes(gn("typecheck"))&&e.push(gn("typecheck")),a&&!e.includes(gn("lint"))&&e.push(gn("lint")),[...new Set(e)].slice(0,4)}function aC(t){let e=process.env.NEX_LANGUAGE;if(e&&e!=="auto")return e;if(Bu())return"English";let n=String(t||"").trim();if(!n)return"English";if(/[äöüß]/i.test(n))return"German";let o=n.toLowerCase().match(/[a-zA-Zäöüß]+/g)||[],s=new Set(["a","an","and","are","can","do","does","explain","file","folder","for","how","in","is","it","list","of","please","show","the","this","what","where","why","with"]),r=new Set(["aber","analysiere","bitte","das","den","der","die","dies","diese","diesem","du","ein","eine","einer","englisch","erkl\xE4re","f\xFCr","hier","im","ist","mit","ordner","und","warum","was","wie","wieso","zeige"]),i=0,a=0;for(let c of o)s.has(c)&&i++,r.has(c)&&a++;return a>i?"German":(i>a,"English")}function cC(){let t=process.env.NEX_LANGUAGE,e=process.env.NEX_CODE_LANGUAGE,n=process.env.NEX_COMMIT_LANGUAGE,o=Bu(),s=!t||t==="auto"?null:t,r=[`# Language Rules (CRITICAL \u2014 enforce strictly)
932
+ `];o?r.push("RESPONSE LANGUAGE: This project requires English. Always respond in English, even if the user writes in another language."):s?r.push(`RESPONSE LANGUAGE: You MUST always respond in ${s}. 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. ${s} only.`):r.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."),r.push("CODE EXAMPLES: Always show actual, working code examples \u2014 never pseudocode or placeholder snippets."),r.push("COMPLETENESS RULES:"),r.push(" \u2022 ALWAYS show actual code when explaining implementations \u2014 never describe without showing"),Ts()?r.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."):r.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."),r.push(" \u2022 Include complete examples with full context (imports, function signatures, error handling)"),r.push(' \u2022 Show alternative approaches when relevant (e.g., "Alternative: use util.promisify instead")'),r.push(" \u2022 Include edge cases in explanations (empty input, null values, boundary conditions)"),r.push(" \u2022 Provide platform-specific guidance when commands differ by OS (Linux/macOS/Windows)"),r.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.'),r.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."),r.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."),r.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.'),r.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).'),r.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)."),r.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."),r.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."),r.push(" \u2022 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\u2011handling middleware \u2014 do not just send a raw 500 response."),r.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.'),r.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 i=e||"English";r.push(`CODE LANGUAGE: Write all code comments, docstrings, variable descriptions, and inline documentation in ${i}.`);let a=n||"English";return r.push(`COMMIT MESSAGES: Write all git commit messages in ${a}.`),s&&r.push(`
933
933
  This is a hard requirement. Always respond in ${s}. 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 ${s}.`),r.join(`
934
934
  `)+`
935
935
 
936
- `}function cC(t){let e=iC(t);return`# Current Turn Language (CRITICAL \u2014 enforce strictly)
936
+ `}function lC(t){let e=aC(t);return Bu()?`# Current Turn Language (CRITICAL \u2014 enforce strictly)
937
+ This repository is English-only. You MUST answer this turn in English, even if the user's message is written in German or any other language. Treat non-English input as content to answer, not as a language-switch instruction. Do NOT switch to another language because of the user's wording, repository files, prior conversation, examples, or project instructions.
938
+
939
+ `:`# Current Turn Language (CRITICAL \u2014 enforce strictly)
937
940
  The current user message is in ${e}. You MUST answer this turn in ${e}. Do NOT switch to another language because of repository files, prior conversation, examples, or project instructions.
938
941
 
939
- `}function lC(){if(go!==null)return go;try{let e=$1().flatMap(s=>s.models.map(r=>({spec:`${s.name}:${r.id}`,tier:b1(r.id,s.name),name:r.name})));if(e.length<2)return go="","";let n={full:"complex tasks (refactor, implement, generate)",standard:"regular tasks (edit, fix, analyze)",essential:"simple tasks (read, search, list)"},o=`
942
+ `}function uC(){if(go!==null)return go;try{let e=$1().flatMap(s=>s.models.map(r=>({spec:`${s.name}:${r.id}`,tier:b1(r.id,s.name),name:r.name})));if(e.length<2)return go="","";let n={full:"complex tasks (refactor, implement, generate)",standard:"regular tasks (edit, fix, analyze)",essential:"simple tasks (read, search, list)"},o=`
940
943
  # Sub-Agent Model Routing
941
944
 
942
945
  `;o+='Sub-agents auto-select models by task complexity. Override with `model: "provider:model"` in agent definition.\n\n',o+=`| Model | Tier | Auto-assigned for |
943
946
  |---|---|---|
944
947
  `;for(let s of e)o+=`| ${s.spec} | ${s.tier} | ${n[s.tier]||s.tier} |
945
- `;return go=o,o}catch(t){return process.env.NEX_DEBUG&&console.error("[agent] model routing guide failed:",t.message),go="",""}}var ju="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->";function uC(t){let e=t.indexOf(ju);return e===-1?{dynamic:t,static:""}:{dynamic:t.slice(0,e).trimEnd(),static:t.slice(e+ju.length).trimStart()}}async function Du(){let t=await P0()+":"+nn();if(_r!==null&&t===Eu)return _r;let e=await qR(process.cwd()),n=JR(),o=h1(),s=Tr()?r1():"",r=aC(),i=ZR(),a=x1(nn());return _r=`${a?`## Model Briefing
948
+ `;return go=o,o}catch(t){return process.env.NEX_DEBUG&&console.error("[agent] model routing guide failed:",t.message),go="",""}}var ju="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->";function dC(t){let e=t.indexOf(ju);return e===-1?{dynamic:t,static:""}:{dynamic:t.slice(0,e).trimEnd(),static:t.slice(e+ju.length).trimStart()}}async function Du(){let t=await L0()+":"+nn();if(_r!==null&&t===Eu)return _r;let e=await qR(process.cwd()),n=JR(),o=h1(),s=Tr()?r1():"",r=cC(),i=ZR(),a=x1(nn());return _r=`${a?`## Model Briefing
946
949
  ${a}
947
950
 
948
951
  ---
@@ -1203,7 +1206,7 @@ You have a soft budget of ~30 tool calls per task. Sessions with >40 tool calls
1203
1206
  - Instead: use bash with inline node -e '...' for quick one-off checks.
1204
1207
  - If the test is worth keeping, write it to tests/ with a proper name.
1205
1208
  - Write-then-delete patterns waste 3 tool calls and leave orphans if the session is interrupted.
1206
- ${lC()}
1209
+ ${uC()}
1207
1210
 
1208
1211
  # Edit Protocol (Mandatory \u2014 Follow These Steps Exactly)
1209
1212
 
@@ -1395,20 +1398,20 @@ class ErrorBoundary extends React.Component {
1395
1398
  - Use migrations for schema changes, never manual ALTER TABLE
1396
1399
  - Add database-level constraints (unique, foreign key, check) not just app-level
1397
1400
 
1398
- `,Eu=t,_r}function B0(){qu.clear(),I0.clear(),ya.clear(),Rr.clear(),j0.clear(),wa.clear(),Cr.clear(),yn.clear(),Tn.clear(),Ar.clear(),Ft.clear(),Rs.clear(),Ra.clear(),Au.clear(),Bt=0,kr=0,ba=0,Mt=!1,_a=0,vs=-1,Nu=!1,xa=0,ka=!1,Wt=0,Ht=!1,tn=0,Yt=0,dt=!1,vt="",vr=0,va="",Ss=0,Sa="",Es=0,Ut=!1,Mu=!1,Re="plan",Ca=0,we=!1,sn=null,Pu=null,Lu=null,As=[],bo=0,$o=0,_o=0,xo=!1,ko=0,Fn=0,Cs=null,Or.clear(),Nr.clear(),Ou="",$a=0}function dC(){M=[],Sr=null,yo="",wo=0,Tu="",Ru=0,B0();try{let{resetCompactionFailures:t}=wl();t()}catch{}try{let{cancelAllJobs:t}=to();t()}catch{}}function fC(){M.length>x0&&M.splice(0,M.length-x0)}function U0(){try{let t=require("fs"),n=require("path").join(process.cwd(),"AGENTS.md");if(!t.existsSync(n))return!1;let o=t.readFileSync(n,"utf8");return/all.*english/i.test(o)&&/no german/i.test(o)}catch{return!1}}function _u(t,e,n,o=1500){return!t||!e?!1:t===e&&Date.now()-n<o}function pC(){return M.length}function hC(){return M}function mC(t){M=t}async function gC(){let{execFile:t}=require("child_process"),e=require("fs"),n=process.cwd(),o=(d,f)=>new Promise(p=>{t(d,f,{cwd:n,timeout:3e3},(h,g)=>{p(h?"":(g||"").trim())})}),[s]=await Promise.all([o("find",[".","-type","f","-not","-path","*/node_modules/*","-not","-path","*/.git/*","-not","-path","*/dist/*","-not","-path","*/.next/*","-not","-path","*/build/*","-not","-path","*/__pycache__/*","-not","-path","*/vendor/*"])]),r=new Set(["js","ts","jsx","tsx","py","go","rs","rb","java","cpp","c","cs"]),i=(s?s.split(`
1401
+ `,Eu=t,_r}function U0(){qu.clear(),j0.clear(),ya.clear(),Rr.clear(),D0.clear(),wa.clear(),Cr.clear(),yn.clear(),Tn.clear(),Ar.clear(),Ft.clear(),Rs.clear(),Ra.clear(),Au.clear(),Bt=0,kr=0,ba=0,Mt=!1,_a=0,vs=-1,Nu=!1,xa=0,ka=!1,Wt=0,Ht=!1,tn=0,Yt=0,dt=!1,vt="",vr=0,va="",Ss=0,Sa="",Es=0,Ut=!1,Mu=!1,Re="plan",Ca=0,we=!1,sn=null,Pu=null,Lu=null,As=[],bo=0,$o=0,_o=0,xo=!1,ko=0,Fn=0,Cs=null,Or.clear(),Nr.clear(),Ou="",$a=0}function fC(){M=[],Sr=null,yo="",wo=0,Tu="",Ru=0,U0();try{let{resetCompactionFailures:t}=wl();t()}catch{}try{let{cancelAllJobs:t}=to();t()}catch{}}function pC(){M.length>k0&&M.splice(0,M.length-k0)}function Bu(){try{let t=require("fs"),n=require("path").join(process.cwd(),"AGENTS.md");if(!t.existsSync(n))return!1;let o=t.readFileSync(n,"utf8");return/all.*english/i.test(o)&&/no german/i.test(o)}catch{return!1}}function _u(t,e,n,o=1500){return!t||!e?!1:t===e&&Date.now()-n<o}function hC(){return M.length}function mC(){return M}function gC(t){M=t}async function yC(){let{execFile:t}=require("child_process"),e=require("fs"),n=process.cwd(),o=(d,f)=>new Promise(p=>{t(d,f,{cwd:n,timeout:3e3},(h,g)=>{p(h?"":(g||"").trim())})}),[s]=await Promise.all([o("find",[".","-type","f","-not","-path","*/node_modules/*","-not","-path","*/.git/*","-not","-path","*/dist/*","-not","-path","*/.next/*","-not","-path","*/build/*","-not","-path","*/__pycache__/*","-not","-path","*/vendor/*"])]),r=new Set(["js","ts","jsx","tsx","py","go","rs","rb","java","cpp","c","cs"]),i=(s?s.split(`
1399
1402
  `):[]).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 u=` \u{1F4C1} ${Object.entries(a).sort((d,f)=>f[1]-d[1]).slice(0,4).map(([d,f])=>`${f} .${d}`).join(" \xB7 ")}`,l=ze.join(n,"package.json");if(e.existsSync(l))try{let d=JSON.parse(e.readFileSync(l,"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}`:"";u+=`
1400
- \u{1F4E6} ${p}${h}`}}catch{}return u}function yC(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 je(t,e,n,o,s,{suppressHint:r=!1}={}){if(t<1)return;let i=[...e.values()].reduce((u,l)=>u+l,0),a=`\u2500\u2500 ${t} ${t===1?"step":"steps"} \xB7 ${i} ${i===1?"tool":"tools"}`,c=0;if(s){let u=Date.now()-s;c=Math.round(u/1e3),a+=c>=60?` \xB7 ${Math.floor(c/60)}m ${c%60}s`:` \xB7 ${c}s`}if(n.size>0&&(a+=` \xB7 ${n.size} ${n.size===1?"file":"files"} modified`),a+=" \u2500\u2500",console.log(`
1401
- ${m.dim} ${a}${m.reset}`),c>=30&&process.stdout.isTTY){let u=n.size>0?`Done \u2014 ${n.size} ${n.size===1?"file":"files"} modified in ${c}s`:`Done \u2014 ${t} ${t===1?"step":"steps"} in ${c}s`;yC(u)}if(Nr.size>0&&Or.size>0)for(let u of Nr){let l=Or.get(u);l&&console.log(`${m.dim} \u2714 task #${u} auto-matched: ${l.slice(0,60)}${m.reset}`)}n.size>0?console.log(`${m.dim} \u{1F4A1} /diff \xB7 /commit \xB7 /undo${m.reset}`):!r&&o.size>=5&&n.size===0&&t>=3?console.log(`${m.dim} \u{1F4A1} Found issues? Say "fix 1" or "apply all fixes"${m.reset}`):o.size>0&&t>=2&&console.log(`${m.dim} \u{1F4A1} /save \xB7 /clear${m.reset}`)}async function wC(){if(!process.stdout.isTTY)return{action:"quit"};let t=mo(),e=nn(),n=Ta.fast?.[t],o=Ta.strong?.[t],s=n&&n!==e,r=o&&o!==e&&o!==n,i=[];i.push({key:"r",label:`Retry with current model ${m.dim}(${e})${m.reset}`}),s&&i.push({key:"f",label:`Switch to ${m.bold}${n}${m.reset} ${m.dim}\u2014 fast, low latency${m.reset}`,model:n}),r&&i.push({key:"s",label:`Switch to ${m.bold}${o}${m.reset} ${m.dim}\u2014 reliable tool-calling, medium speed${m.reset}`,model:o}),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 c=process.stdin,u=c.isRaw;c.setRawMode(!0),c.resume(),c.setEncoding("utf8");let l=!1,d=f=>{if(l)return;l=!0,c.removeListener("data",d),c.setRawMode(u||!1),c.pause();let p=f.toLowerCase().trim();if(process.stdout.write(`${p}
1402
- `),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})};c.on("data",d)})}function bC(t){let e=/https?:\/\/[^\s/]+(\/[^\s?#]+)/g,n=new Set,o;for(;(o=e.exec(t))!==null;){let s=o[1].replace(/\/$/,"");s.length>1&&s.split("/").filter(i=>i.length>2).forEach(i=>n.add(i))}return Array.from(n)}function $C(t){let e=[];return(t.includes("@click")||t.includes("x-data")||t.includes("v-if")||t.includes("v-model"))&&e.push("Snippet contains Vue/Alpine.js directives (e.g., @click, v-model). Do not restrict your search to just .js/.ts/.vue files; also search .html and .py (templates) if appropriate."),(t.includes("className=")||t.includes("useEffect"))&&e.push("Snippet appears to be React. Look in .jsx, .tsx, .js, .ts files."),e}var wn=null;async function _C(t,e=null,n={}){let o=_1(nn());_0=o.staleWarn,gu=o.staleAbort,wn=e;let s=t;if(Sr&&typeof t=="string"&&(s=`${Sr}
1403
+ \u{1F4E6} ${p}${h}`}}catch{}return u}function wC(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 je(t,e,n,o,s,{suppressHint:r=!1}={}){if(t<1)return;let i=[...e.values()].reduce((u,l)=>u+l,0),a=`\u2500\u2500 ${t} ${t===1?"step":"steps"} \xB7 ${i} ${i===1?"tool":"tools"}`,c=0;if(s){let u=Date.now()-s;c=Math.round(u/1e3),a+=c>=60?` \xB7 ${Math.floor(c/60)}m ${c%60}s`:` \xB7 ${c}s`}if(n.size>0&&(a+=` \xB7 ${n.size} ${n.size===1?"file":"files"} modified`),a+=" \u2500\u2500",console.log(`
1404
+ ${m.dim} ${a}${m.reset}`),c>=30&&process.stdout.isTTY){let u=n.size>0?`Done \u2014 ${n.size} ${n.size===1?"file":"files"} modified in ${c}s`:`Done \u2014 ${t} ${t===1?"step":"steps"} in ${c}s`;wC(u)}if(Nr.size>0&&Or.size>0)for(let u of Nr){let l=Or.get(u);l&&console.log(`${m.dim} \u2714 task #${u} auto-matched: ${l.slice(0,60)}${m.reset}`)}n.size>0?console.log(`${m.dim} \u{1F4A1} /diff \xB7 /commit \xB7 /undo${m.reset}`):!r&&o.size>=5&&n.size===0&&t>=3?console.log(`${m.dim} \u{1F4A1} Found issues? Say "fix 1" or "apply all fixes"${m.reset}`):o.size>0&&t>=2&&console.log(`${m.dim} \u{1F4A1} /save \xB7 /clear${m.reset}`)}async function bC(){if(!process.stdout.isTTY)return{action:"quit"};let t=mo(),e=nn(),n=Ta.fast?.[t],o=Ta.strong?.[t],s=n&&n!==e,r=o&&o!==e&&o!==n,i=[];i.push({key:"r",label:`Retry with current model ${m.dim}(${e})${m.reset}`}),s&&i.push({key:"f",label:`Switch to ${m.bold}${n}${m.reset} ${m.dim}\u2014 fast, low latency${m.reset}`,model:n}),r&&i.push({key:"s",label:`Switch to ${m.bold}${o}${m.reset} ${m.dim}\u2014 reliable tool-calling, medium speed${m.reset}`,model:o}),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 c=process.stdin,u=c.isRaw;c.setRawMode(!0),c.resume(),c.setEncoding("utf8");let l=!1,d=f=>{if(l)return;l=!0,c.removeListener("data",d),c.setRawMode(u||!1),c.pause();let p=f.toLowerCase().trim();if(process.stdout.write(`${p}
1405
+ `),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})};c.on("data",d)})}function $C(t){let e=/https?:\/\/[^\s/]+(\/[^\s?#]+)/g,n=new Set,o;for(;(o=e.exec(t))!==null;){let s=o[1].replace(/\/$/,"");s.length>1&&s.split("/").filter(i=>i.length>2).forEach(i=>n.add(i))}return Array.from(n)}function _C(t){let e=[];return(t.includes("@click")||t.includes("x-data")||t.includes("v-if")||t.includes("v-model"))&&e.push("Snippet contains Vue/Alpine.js directives (e.g., @click, v-model). Do not restrict your search to just .js/.ts/.vue files; also search .html and .py (templates) if appropriate."),(t.includes("className=")||t.includes("useEffect"))&&e.push("Snippet appears to be React. Look in .jsx, .tsx, .js, .ts files."),e}var wn=null;async function xC(t,e=null,n={}){let o=_1(nn());x0=o.staleWarn,gu=o.staleAbort,wn=e;let s=t;if(Sr&&typeof t=="string"&&(s=`${Sr}
1403
1406
 
1404
- ${t}`,Sr=null),typeof s=="string"){let xe=bC(s),ye=$C(s);(xe.length>0||ye.length>0)&&(s+=`
1407
+ ${t}`,Sr=null),typeof s=="string"){let xe=$C(s),ye=_C(s);(xe.length>0||ye.length>0)&&(s+=`
1405
1408
 
1406
1409
  [System Note for Assistant: To resolve this task faster, consider these hints:
1407
1410
  `,xe.length>0&&(s+=`- The user mentioned URLs containing the paths/folders: ${xe.join(", ")}. Prioritize searching these folder names using glob or grep first.
1408
1411
  `),ye.length>0&&ye.forEach(Ce=>{s+=`- ${Ce}
1409
- `}),s+="Always prefer parallel search execution if unsure.]")}typeof s=="string"&&N0(s)&&(s+=`
1412
+ `}),s+="Always prefer parallel search execution if unsure.]")}typeof s=="string"&&M0(s)&&(s+=`
1410
1413
 
1411
- [Note for assistant: the user appears frustrated \u2014 acknowledge their concern briefly and empathetically before proceeding]`);let r=typeof t=="string"?f0(t):null,i=O0(s);i&&typeof i.then=="function"&&(i=await i),M.push({role:"user",content:i}),fC();let a=n.autoOrchestrate!==!1&&process.env.NEX_AUTO_ORCHESTRATE!=="false",c=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10);try{let{detectComplexPrompt:xe,runOrchestrated:ye}=l0(),Ce=xe(typeof t=="string"?t:"");if(a&&Ce.isComplex&&Ce.estimatedGoals>=c){console.log(`${m.yellow}\u26A1 Auto-orchestrate: ${Ce.estimatedGoals} goals \u2192 parallel agents${m.reset}`);let Xe=await ye(t,{orchestratorModel:n.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL,workerModel:n.model});if(Xe&&Xe.synthesis){let at=Xe.synthesis.summary||"",An=Xe.synthesis.filesChanged?.length?`
1414
+ [Note for assistant: the user appears frustrated \u2014 acknowledge their concern briefly and empathetically before proceeding]`);let r=typeof t=="string"?p0(t):null,i=N0(s);i&&typeof i.then=="function"&&(i=await i),M.push({role:"user",content:i}),pC();let a=n.autoOrchestrate!==!1&&process.env.NEX_AUTO_ORCHESTRATE!=="false",c=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10);try{let{detectComplexPrompt:xe,runOrchestrated:ye}=u0(),Ce=xe(typeof t=="string"?t:"");if(a&&Ce.isComplex&&Ce.estimatedGoals>=c){console.log(`${m.yellow}\u26A1 Auto-orchestrate: ${Ce.estimatedGoals} goals \u2192 parallel agents${m.reset}`);let Xe=await ye(t,{orchestratorModel:n.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL,workerModel:n.model});if(Xe&&Xe.synthesis){let at=Xe.synthesis.summary||"",An=Xe.synthesis.filesChanged?.length?`
1412
1415
 
1413
1416
  Files changed: ${Xe.synthesis.filesChanged.join(", ")}`:"",ot=Xe.synthesis.conflicts?.length?`
1414
1417
 
@@ -1421,14 +1424,14 @@ ${ye.instructions}`).join(`
1421
1424
  `);p+=`
1422
1425
  `+xe+`
1423
1426
  `}p+=`
1424
- `+cC(t);let w=[{role:"system",content:p},...M];u0(nn());let _=new ho(lu());_.start();let S=M.length===1,A=S?gC().catch(()=>null):Promise.resolve(null),E=S?QR(typeof t=="string"?t:"").catch(()=>null):Promise.resolve(null),v=ht(),[{messages:N,compressed:ne,compacted:oe,tokensRemoved:ue},fe,ie]=await Promise.all([FR(w,v),A,E]),le=en(w,v);if(_.stop(),fe&&console.log(`${m.dim}${fe}${m.reset}`),oe)console.log(`${m.dim} [context compacted \u2014 summary (~${ue} tokens freed)]${m.reset}`);else if(ne){let xe=le.limit>0?Math.round(ue/le.limit*100):0;L(`${m.dim} [context compressed \u2014 ~${ue} tokens freed (${xe}%)]${m.reset}`)}le.percentage>85&&L(`${m.yellow} \u26A0 Context ${Math.round(le.percentage)}% used (${Math.round(100-le.percentage)}% remaining) \u2014 consider /clear or /save + start fresh${m.reset}`);let T=N;if(ie&&S&&(T=[T[0],{role:"user",content:`[Server probe at task start]
1427
+ `+lC(t);let w=[{role:"system",content:p},...M];d0(nn());let _=new ho(lu());_.start();let S=M.length===1,A=S?yC().catch(()=>null):Promise.resolve(null),E=S?QR(typeof t=="string"?t:"").catch(()=>null):Promise.resolve(null),v=ht(),[{messages:N,compressed:ne,compacted:oe,tokensRemoved:ue},fe,ie]=await Promise.all([FR(w,v),A,E]),le=en(w,v);if(_.stop(),fe&&console.log(`${m.dim}${fe}${m.reset}`),oe)console.log(`${m.dim} [context compacted \u2014 summary (~${ue} tokens freed)]${m.reset}`);else if(ne){let xe=le.limit>0?Math.round(ue/le.limit*100):0;L(`${m.dim} [context compressed \u2014 ~${ue} tokens freed (${xe}%)]${m.reset}`)}le.percentage>85&&L(`${m.yellow} \u26A0 Context ${Math.round(le.percentage)}% used (${Math.round(100-le.percentage)}% remaining) \u2014 consider /clear or /save + start fresh${m.reset}`);let T=N;if(ie&&S&&(T=[T[0],{role:"user",content:`[Server probe at task start]
1425
1428
  ${ie}`},{role:"assistant",content:"Understood \u2014 I have the server context. Proceeding with the task."},...T.slice(1)]),r&&S){let xe=r.shouldPreferSsh?`[Runtime URL detected]
1426
1429
  The user linked a live app URL (${r.url}) and described broken behavior. Treat this as a runtime/deployed-instance issue first. Reproduce it with browser_open or browser_screenshot on the URL before reading local files. Because this URL matches server profile "${r.matchedName}", prefer ssh_exec/service_logs on that server for investigation before local repo inspection.`:`[Runtime URL detected]
1427
1430
  The user linked a live app URL (${r.url}) and described broken behavior. Treat this as a runtime issue first. Reproduce it with browser_open or browser_screenshot before reading local files. Only inspect the local repo after you have confirmed the live behavior.`;T=[T[0],{role:"user",content:xe},{role:"assistant",content:"Understood \u2014 I will inspect the live app/runtime first."},...T.slice(1)]}if(S){let xe=e1(typeof t=="string"?t:"");xe&&(T=[T[0],{role:"user",content:`[EXAMPLE \u2014 illustrative only, not the real task]
1428
1431
  `+xe.user},{role:"assistant",content:xe.assistant+`
1429
- [END EXAMPLE \u2014 wait for the real user request below]`},...T.slice(1)])}if(en(T,ht()).percentage>=65){let{messages:ye,tokensRemoved:Ce}=hn(T,ht());Ce>0&&(T=ye,console.log(`${m.dim} [pre-flight compress \u2014 ${Ce} tokens freed, now ${Math.round(en(T,ht()).percentage)}% used]${m.reset}`))}let F=0,ee=0,be=0,ve=0,Fe=0,Me=9,Ee=0,x=new Set,P=(()=>{let xe=M.find(ye=>ye.role==="user");return typeof xe?.content=="string"?xe.content:""})(),B=typeof P=="string"?f0(P):null,te=J1(P),X=/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(P)||!!B?.shouldPreferSsh,C=!!B,he=0;if(!dt){let xe=M.filter(Ce=>Ce.role==="user"||Ce.role==="tool").map(Ce=>typeof Ce.content=="string"?Ce.content:"").join(`
1430
- `),ye=wu(xe);ye&&(dt=!0,vt=ye.slice(0,120),L(`${m.yellow} \u26A1 Root cause in briefing: ${vt} \u2014 fix phase active from start (read budget: 3)${m.reset}`))}if(!dt&&!Ut&&/\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(P)&&(Ut=!0,L(`${m.cyan} \u26A1 Creation task detected \u2014 tight investigation cap (4 pre-edit, 2 post-edit)${m.reset}`)),M.length<=1&&!n.skipPhaseRouting&&(we=XR(),we)){Cs=KR(P)?.id||"coding";let ye=S0(P);if(Re=ye?"implement":"plan",sn=ku(Re,Cs),Ca=0,bo=0,Fn=0,Er=null,ks.clear(),process.stdout.isTTY&&console.log(ye?`${m.dim} \u21B3 Phase routing: implement(${sn||"default"}) \u2192 verify ${m.yellow}[plan skipped: direct file task]${m.reset}`:`${m.dim} \u21B3 Phase routing: plan(${sn||"default"}) \u2192 implement \u2192 verify${m.reset}`),L(ye?`${m.cyan} \u26A1 Phase routing enabled \u2014 skipping plan phase for direct file task, starting in implement with ${sn||"default model"} (category: ${Cs})${m.reset}`:`${m.cyan} \u26A1 Phase routing enabled \u2014 plan phase with ${sn||"default model"} (category: ${Cs})${m.reset}`),ye&&te.length>0){let Xe={role:"user",content:`[SYSTEM] This is a direct file task targeting: ${te.slice(0,3).join(", ")}. Modify only the explicitly requested file(s) unless the user asks for more. Do NOT create extra helper or test files for verification. Prefer inline verification with bash or by reading the edited file.`};M.push(Xe),T.push(Xe)}}let Y=0,re=new Map,Z=new Set,Se=new Set,Os=new Set,Ns=0,Qu=0,Ia=0,Ms=0,Pe=Date.now(),aw=new IR(k1),cw=Ar,et=n.skillLoop?10:1,lw=3*et,uw=5*et,ed=qu,dw=5*et,fw=8*et,pw=I0,hw=(we?6:4)*et,mw=(we?10:7)*et,ja=ya,gw=(we?5:3)*et,Lr=(we?8:5)*et,yw=j0,ww=(we?4:3)*et,bw=(we?6:4)*et,$w=3*et,_w=4*et,Ps=yn,xw=(we?6:4)*et,kw=(we?10:8)*et,Ls=(we?12:10)*et,vw=25,Un=0,Sw=10*et,Ew=15*et,Wn=0,td=5*et,Hn=0,Tw=2*et,Rw=3,Da=0,Eo=10,Cw=16,nd=n.skillLoop?999:o.investigationCap,sd=async()=>{let{hasPendingOrCompletedJobs:xe,getPendingJobSummary:ye}=to();if(xe()){if(ye()){let Ce=Date.now()+45e3;for(process.stderr.write(`${m.cyan} \u23F3 Waiting for background agents to finish\u2026${m.reset}
1431
- `);ye()&&Date.now()<Ce;)await new Promise(Xe=>setTimeout(Xe,500).unref()),ha(M,T)}ha(M,T),M.length>0&&Ne(M)}},Cn=typeof t=="string"?t.trim():"",od=Cn.length>0&&/^\s*(analyze|analyse|analysiere|explain|erkläre|describe|beschreib|review|audit|summari[sz]e|zusammenfass|list|liste|understand|document|documentation|docs|what is|what does|wie funktioniert|wie geht|how does|show me|zeig|show the|show all|tell me about|erzähl)/i.test(Cn)&&!/\b(fix|bug|crash|error|implement|add|create|change|update|refactor|rewrite|broken|fail|patch|migrate|port|build|edit|write|delete|remove|install|setup|deploy|run)\b/i.test(Cn),Ir=Cn.length>0&&/\b(analyze|analyse|explain|describe|review|audit|summari[sz]e|understand|document|scan|count|inventory|map|list|identify)\b/i.test(Cn)&&/\b(create|write|generate|produce|output)\b/i.test(Cn)&&/\b([A-Z0-9_-]+\.md|markdown|report|summary|overview|architecture|audit|table|documentation|docs|inventory|catalog)\b/i.test(Cn)&&!/\b(fix|bug|crash|error|implement|add(?!\s+(?:to|into)\b)|change|update|refactor|rewrite|broken|fail|patch|migrate|port|build|delete|remove|install|setup|deploy|run)\b/i.test(Cn),Ke,Et=n.maxIterations||(we?_s(Re):Su);od&&(Et=Math.min(Et,4),L(`${m.dim} \u21B3 Analysis-only prompt detected \u2014 iter cap=${Et}${m.reset}`));let qa=0,rd=3,Fa=!1,jr=0,Ba=!1;e:for(;;){for(Fa=!1,Ke=0;Ke<Et&&!ma()?.aborted;Ke++){ha(M,T);{let b=ht(),y=en(T,b),G=Y===0?65:78;if(y.percentage>=G){if(Z.size>0||we&&Re!=="plan"){let K=UR(M,{filesModified:Z,currentPhase:we?Re:null});if(K){let j=T.findIndex(O=>O._progressSnapshot);j!==-1&&T.splice(j,1);let ce=T.findIndex(O=>O.role==="system");T.splice(ce+1,0,K)}}let{messages:U,tokensRemoved:z}=hn(T,b,Y===0);if(z>0&&(T=U,z>50&&console.log(`${m.dim} [auto-compressed \u2014 ~${z} tokens freed, now ${Math.round(en(T,b).percentage)}%]${m.reset}`),Ut&&Z.size>=3)){let K=[...Z].map(ce=>ce.split("/").pop()).slice(0,10).join(", "),j={role:"user",content:`[FRAMEWORK \u2014 context compressed] Task is IN PROGRESS. Already created ${Z.size} files: ${K}. DO NOT restart or re-investigate what was already done. Continue from where you left off.`};T.push(j)}}}if(Mt&&!dt&&vr<2){vr++;let b={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."};T.push(b),M.push(b),L(`${m.yellow} \u26A0 Pre-call SSH-blocked nudge #${vr} injected \u2014 model told to synthesize${m.reset}`)}Mt||(vr=0);let ye=!0;Y>0&&l1();let Ce=null;if(l&&l.isActive())l._paused&&l.resume();else if(!l){let b,y=u1();if(y&&y.total>1){let z=y.description.length>40?y.description.slice(0,37)+"\u2026":y.description;b=`Plan step ${y.current}/${y.total}: ${z}`}else b=Y>0?`${lu()} (step ${Y+1})`:lu();let{getPendingJobSummary:G}=to(),U=G();U&&(b+=` [${U}]`),Ce=new ho(b),Ce.start()}let Xe=!0,at="",An=!1,ot=new d1,Pt,Ua=Date.now(),Dr=!1,Wa=new AbortController,id=setInterval(()=>{let b=Date.now()-Ua;if(b>=gu)ot._clearCursorLine(),L(`${m.yellow} \u26A0 Stream stale for ${Math.round(b/1e3)}s \u2014 aborting and retrying${m.reset}`),Wa.abort();else if(b>=_0&&!Dr){Dr=!0,ot._clearCursorLine();let y=Ta.fast?.[mo()],G=be>0?` (retry ${be+1}/${fa})`:"",U=Math.round((gu-b)/1e3);L(`${m.yellow} \u26A0 No tokens received for ${Math.round(b/1e3)}s \u2014 waiting...${G}${m.reset}`),y&&y!==nn()?console.log(`${m.dim} \u{1F4A1} Will auto-switch to ${y} in ~${U}s if no tokens arrive${m.reset}`):console.log(`${m.dim} \u{1F4A1} Ctrl+C to abort \xB7 auto-abort in ~${U}s${m.reset}`)}},5e3),Lt="",bn=null;try{let b=M0(ht()),y=new Set(["read_file","list_directory","search_files","glob","grep","git_status","git_diff","git_log","git_show","ssh_exec"]),G=new Set(["read_file","list_directory","glob","grep","bash","git_status","git_diff","git_log","ssh_exec"]),U;Tr()?U=b.filter(j=>T0.has(j.function.name)):we&&Re==="plan"?U=b.filter(j=>y.has(j.function.name)):we&&Re==="verify"?U=b.filter(j=>G.has(j.function.name)):U=b;let z=ma(),K=new AbortController;z&&z.addEventListener("abort",()=>K.abort(),{once:!0}),Wa.signal.addEventListener("abort",()=>K.abort(),{once:!0}),Pt=await d0(T,U,{signal:K.signal,...sn?{model:sn}:{},onThinkingToken:()=>{Ua=Date.now(),Dr=!1,wn?.onThinkingToken&&wn.onThinkingToken()},onToken:j=>{if(Ua=Date.now(),Dr=!1,wn?.onToken){wn.onToken(j),at+=j;return}if(at+=j,!An&&at.length>400&&at.length%250<j.length+1){let ce=vu(at,3);ce.truncated&&(An=!0,ot._clearCursorLine?.(),L(`${m.yellow} \u26A0 LLM stream loop detected (${ce.repeatCount}\xD7 repeated) \u2014 suppressing display${m.reset}`))}An||(Lt+=j,process.stdout.isTTY?bn||(bn=setTimeout(()=>{Lt&&ot&&ot.push(Lt),Lt="",bn=null},50)):(ot.push(Lt),Lt=""),Xe&&(l&&!l._paused?l.pause():Ce&&Ce.stop(),ye||(ye=!0),ot.startCursor(),Xe=!1))}})}catch(b){if(clearInterval(id),bn&&(clearTimeout(bn),bn=null),Lt&&ot&&(ot.push(Lt),Lt=""),l&&!l._paused&&l.pause(),Ce&&Ce.stop(),ot.stopCursor(),Wa.signal.aborted&&!ma()?.aborted){if(be++,be>fa){if(ve<1){ve++,po("Stale retries exhausted \u2014 last-resort force-compress...",m.yellow);let ce=ht(),{messages:O,tokensRemoved:W}=hn(T,ce);T=O,W>50&&L(`${m.dim} [force-compressed \u2014 ~${W} tokens freed]${m.reset}`),be=0,Ke--;continue}l&&(l.stop(),l=null);let j=await wC();if(j.action==="quit"){u(null),je(Y,re,Z,Se,Pe),Ne(M);break}j.action==="switch"&&(uu(`${j.provider}:${j.model}`),console.log(`${m.green} \u2713 Switched to ${j.provider}:${j.model}${m.reset}`)),be=0,Ke--;continue}let z=be===1?3e3:5e3;if(be>=1&&Ee<1){Ee++,po(`Stale retry ${be}/${fa} \u2014 force-compressing before retry...`,m.yellow);let j=ht(),{messages:ce,tokensRemoved:O}=hn(T,j,!0);if(T=ce,O>0&&O>50&&L(`${m.dim} [force-compressed \u2014 ~${O} tokens freed]${m.reset}`),W1){let W=Ta.fast?.[mo()];W&&W!==nn()&&(uu(`${mo()}:${W}`),console.log(`${m.cyan} \u26A1 Auto-switched to ${W} to avoid further stale timeouts${m.reset}`),console.log(`${m.dim} (disable with NEX_STALE_AUTO_SWITCH=0)${m.reset}`))}}else L(`${m.yellow} \u26A0 Stale retry ${be}/${fa} \u2014 retrying in ${z/1e3}s...${m.reset}`);let K=new ho(`Waiting ${z/1e3}s before retry...`);K.start(),await new Promise(j=>setTimeout(j,z)),K.stop(),Ke--;continue}if(b.name==="AbortError"||b.name==="CanceledError"||b.message?.includes("canceled")||b.message?.includes("aborted")){l&&(l.stop(),l=null),u(null),je(Y,re,Z,Se,Pe),Ne(M);break}let y=b.message;if(b.code==="ECONNREFUSED"||b.message.includes("ECONNREFUSED"))y="Connection refused \u2014 please check your internet connection or API endpoint";else if(b.code==="ENOTFOUND"||b.message.includes("ENOTFOUND"))y="Network error \u2014 could not reach the API server. Please check your connection";else if(b.code==="ETIMEDOUT"||b.message.includes("timeout"))y="Request timed out \u2014 the API server took too long to respond. Please try again";else if(b.message.includes("401")||b.message.includes("Unauthorized"))y="Authentication failed \u2014 please check your API key in the .env file";else if(b.message.includes("403")||b.message.includes("Forbidden"))y="Access denied \u2014 your API key may not have permission for this model";else if(b.message.includes("404")){let z=nn?nn():"unknown",K=O=>O.includes(":")&&O.split(":")[0].match(/^[a-z]+$/)&&!O.split(":")[1].includes(":")?O.split(":").slice(1).join(":"):O;x.add(K(z));let ce=(()=>{let O=[];process.env.NEX_FALLBACK_MODEL&&O.push(process.env.NEX_FALLBACK_MODEL);try{let{getModelForCategory:W}=ms(),R=["agentic","coding","plan","verify","sysadmin","data","frontend"];for(let H of R){let de=W(H);de&&!O.includes(de)&&O.push(de)}}catch{}return O.filter(W=>!x.has(K(W)))})()[0];if(ce){console.log(`${m.yellow} \u26A0 Model ${z} unavailable (404) \u2014 switching to ${ce}${m.reset}`),uu(ce),u0(ce),Ke--;continue}y=`Model not found (404): ${z} \u2014 no fallback available. Set NEX_FALLBACK_MODEL or run /models to list available models`,console.log(`${m.red} \u2717 ${y}${m.reset}`),l&&(l.stop(),l=null),u(null),je(Y,re,Z,Se,Pe),Ne(M);break}else if(b.message.includes("400")){if(ve<3&&Fe<Me){ve++,Fe++;let z=Y===0&&ve===1,K=z||ve===3||Ee>0;if(z){ve=3;let W=b.message.replace(/^API Error(\s*\[HTTP \d+\])?:\s*/i,"").slice(0,150);po(`Bad request (400) \u2014 ${W||"system prompt too large"}, compressing...`,m.yellow)}else po(K?`Bad request (400) \u2014 nuclear compression (attempt ${ve}/3, dropping history)...`:`Bad request (400) \u2014 force-compressing and retrying... (attempt ${ve}/3)`,m.yellow);let j=ht(),{messages:ce,tokensRemoved:O}=hn(T,j,K);T=ce,O>50&&L(`${m.dim} [force-compressed \u2014 ~${O} tokens freed]${m.reset}`),Ke--;continue}{let z=T.find(R=>R.role==="system"),K=T.find(R=>R.role==="user"&&!String(R.content).startsWith("[SYSTEM")&&!String(R.content).startsWith("BLOCKED:")),j=[z,K].filter(Boolean),{getUsage:ce}=fn(),O=fn().estimateMessagesTokens(j),W=fn().estimateMessagesTokens(T);if(O<W){let R=[],H=M.filter(I=>I.role==="assistant"&&typeof I.content=="string"&&I.content.trim().length>30).slice(-5).map(I=>I.content.trim().slice(0,300).replace(/\n+/g," "));H.length>0&&R.push(`Key findings:
1432
+ [END EXAMPLE \u2014 wait for the real user request below]`},...T.slice(1)])}if(en(T,ht()).percentage>=65){let{messages:ye,tokensRemoved:Ce}=hn(T,ht());Ce>0&&(T=ye,console.log(`${m.dim} [pre-flight compress \u2014 ${Ce} tokens freed, now ${Math.round(en(T,ht()).percentage)}% used]${m.reset}`))}let F=0,ee=0,be=0,ve=0,Fe=0,Me=9,Ee=0,x=new Set,P=(()=>{let xe=M.find(ye=>ye.role==="user");return typeof xe?.content=="string"?xe.content:""})(),B=typeof P=="string"?p0(P):null,te=Z1(P),X=/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(P)||!!B?.shouldPreferSsh,C=!!B,he=0;if(!dt){let xe=M.filter(Ce=>Ce.role==="user"||Ce.role==="tool").map(Ce=>typeof Ce.content=="string"?Ce.content:"").join(`
1433
+ `),ye=wu(xe);ye&&(dt=!0,vt=ye.slice(0,120),L(`${m.yellow} \u26A1 Root cause in briefing: ${vt} \u2014 fix phase active from start (read budget: 3)${m.reset}`))}if(!dt&&!Ut&&/\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(P)&&(Ut=!0,L(`${m.cyan} \u26A1 Creation task detected \u2014 tight investigation cap (4 pre-edit, 2 post-edit)${m.reset}`)),M.length<=1&&!n.skipPhaseRouting&&!J1(P)&&(we=XR(),we)){Cs=KR(P)?.id||"coding";let ye=E0(P);if(Re=ye?"implement":"plan",sn=ku(Re,Cs),Ca=0,bo=0,Fn=0,Er=null,ks.clear(),process.stdout.isTTY&&console.log(ye?`${m.dim} \u21B3 Phase routing: implement(${sn||"default"}) \u2192 verify ${m.yellow}[plan skipped: direct file task]${m.reset}`:`${m.dim} \u21B3 Phase routing: plan(${sn||"default"}) \u2192 implement \u2192 verify${m.reset}`),L(ye?`${m.cyan} \u26A1 Phase routing enabled \u2014 skipping plan phase for direct file task, starting in implement with ${sn||"default model"} (category: ${Cs})${m.reset}`:`${m.cyan} \u26A1 Phase routing enabled \u2014 plan phase with ${sn||"default model"} (category: ${Cs})${m.reset}`),ye&&te.length>0){let Xe={role:"user",content:`[SYSTEM] This is a direct file task targeting: ${te.slice(0,3).join(", ")}. Modify only the explicitly requested file(s) unless the user asks for more. Do NOT create extra helper or test files for verification. Prefer inline verification with bash or by reading the edited file.`};M.push(Xe),T.push(Xe)}}let Y=0,re=new Map,Z=new Set,Se=new Set,Os=new Set,Ns=0,ed=0,Ia=0,Ms=0,Pe=Date.now(),aw=new IR(k1),cw=Ar,et=n.skillLoop?10:1,lw=3*et,uw=5*et,td=qu,dw=5*et,fw=8*et,pw=j0,hw=(we?6:4)*et,mw=(we?10:7)*et,ja=ya,gw=(we?5:3)*et,Lr=(we?8:5)*et,yw=D0,ww=(we?4:3)*et,bw=(we?6:4)*et,$w=3*et,_w=4*et,Ps=yn,xw=(we?6:4)*et,kw=(we?10:8)*et,Ls=(we?12:10)*et,vw=25,Un=0,Sw=10*et,Ew=15*et,Wn=0,nd=5*et,Hn=0,Tw=2*et,Rw=3,Da=0,Eo=10,Cw=16,sd=n.skillLoop?999:o.investigationCap,od=async()=>{let{hasPendingOrCompletedJobs:xe,getPendingJobSummary:ye}=to();if(xe()){if(ye()){let Ce=Date.now()+45e3;for(process.stderr.write(`${m.cyan} \u23F3 Waiting for background agents to finish\u2026${m.reset}
1434
+ `);ye()&&Date.now()<Ce;)await new Promise(Xe=>setTimeout(Xe,500).unref()),ha(M,T)}ha(M,T),M.length>0&&Ne(M)}},Cn=typeof t=="string"?t.trim():"",rd=Cn.length>0&&/^\s*(analyze|analyse|analysiere|explain|erkläre|describe|beschreib|review|audit|summari[sz]e|zusammenfass|list|liste|understand|document|documentation|docs|what is|what does|wie funktioniert|wie geht|how does|show me|zeig|show the|show all|tell me about|erzähl)/i.test(Cn)&&!/\b(fix|bug|crash|error|implement|add|create|change|update|refactor|rewrite|broken|fail|patch|migrate|port|build|edit|write|delete|remove|install|setup|deploy|run)\b/i.test(Cn),Ir=Cn.length>0&&/\b(analyze|analyse|explain|describe|review|audit|summari[sz]e|understand|document|scan|count|inventory|map|list|identify)\b/i.test(Cn)&&/\b(create|write|generate|produce|output)\b/i.test(Cn)&&/\b([A-Z0-9_-]+\.md|markdown|report|summary|overview|architecture|audit|table|documentation|docs|inventory|catalog)\b/i.test(Cn)&&!/\b(fix|bug|crash|error|implement|add(?!\s+(?:to|into)\b)|change|update|refactor|rewrite|broken|fail|patch|migrate|port|build|delete|remove|install|setup|deploy|run)\b/i.test(Cn),Ke,Et=n.maxIterations||(we?_s(Re):Su);rd&&(Et=Math.min(Et,4),L(`${m.dim} \u21B3 Analysis-only prompt detected \u2014 iter cap=${Et}${m.reset}`));let qa=0,id=3,Fa=!1,jr=0,Ba=!1;e:for(;;){for(Fa=!1,Ke=0;Ke<Et&&!ma()?.aborted;Ke++){ha(M,T);{let b=ht(),y=en(T,b),G=Y===0?65:78;if(y.percentage>=G){if(Z.size>0||we&&Re!=="plan"){let K=UR(M,{filesModified:Z,currentPhase:we?Re:null});if(K){let j=T.findIndex(O=>O._progressSnapshot);j!==-1&&T.splice(j,1);let ce=T.findIndex(O=>O.role==="system");T.splice(ce+1,0,K)}}let{messages:U,tokensRemoved:z}=hn(T,b,Y===0);if(z>0&&(T=U,z>50&&console.log(`${m.dim} [auto-compressed \u2014 ~${z} tokens freed, now ${Math.round(en(T,b).percentage)}%]${m.reset}`),Ut&&Z.size>=3)){let K=[...Z].map(ce=>ce.split("/").pop()).slice(0,10).join(", "),j={role:"user",content:`[FRAMEWORK \u2014 context compressed] Task is IN PROGRESS. Already created ${Z.size} files: ${K}. DO NOT restart or re-investigate what was already done. Continue from where you left off.`};T.push(j)}}}if(Mt&&!dt&&vr<2){vr++;let b={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."};T.push(b),M.push(b),L(`${m.yellow} \u26A0 Pre-call SSH-blocked nudge #${vr} injected \u2014 model told to synthesize${m.reset}`)}Mt||(vr=0);let ye=!0;Y>0&&l1();let Ce=null;if(l&&l.isActive())l._paused&&l.resume();else if(!l){let b,y=u1();if(y&&y.total>1){let z=y.description.length>40?y.description.slice(0,37)+"\u2026":y.description;b=`Plan step ${y.current}/${y.total}: ${z}`}else b=Y>0?`${lu()} (step ${Y+1})`:lu();let{getPendingJobSummary:G}=to(),U=G();U&&(b+=` [${U}]`),Ce=new ho(b),Ce.start()}let Xe=!0,at="",An=!1,ot=new d1,Pt,Ua=Date.now(),Dr=!1,Wa=new AbortController,ad=setInterval(()=>{let b=Date.now()-Ua;if(b>=gu)ot._clearCursorLine(),L(`${m.yellow} \u26A0 Stream stale for ${Math.round(b/1e3)}s \u2014 aborting and retrying${m.reset}`),Wa.abort();else if(b>=x0&&!Dr){Dr=!0,ot._clearCursorLine();let y=Ta.fast?.[mo()],G=be>0?` (retry ${be+1}/${fa})`:"",U=Math.round((gu-b)/1e3);L(`${m.yellow} \u26A0 No tokens received for ${Math.round(b/1e3)}s \u2014 waiting...${G}${m.reset}`),y&&y!==nn()?console.log(`${m.dim} \u{1F4A1} Will auto-switch to ${y} in ~${U}s if no tokens arrive${m.reset}`):console.log(`${m.dim} \u{1F4A1} Ctrl+C to abort \xB7 auto-abort in ~${U}s${m.reset}`)}},5e3),Lt="",bn=null;try{let b=P0(ht()),y=new Set(["read_file","list_directory","search_files","glob","grep","git_status","git_diff","git_log","git_show","ssh_exec"]),G=new Set(["read_file","list_directory","glob","grep","bash","git_status","git_diff","git_log","ssh_exec"]),U;Tr()?U=b.filter(j=>R0.has(j.function.name)):we&&Re==="plan"?U=b.filter(j=>y.has(j.function.name)):we&&Re==="verify"?U=b.filter(j=>G.has(j.function.name)):U=b;let z=ma(),K=new AbortController;z&&z.addEventListener("abort",()=>K.abort(),{once:!0}),Wa.signal.addEventListener("abort",()=>K.abort(),{once:!0}),Pt=await f0(T,U,{signal:K.signal,...sn?{model:sn}:{},onThinkingToken:()=>{Ua=Date.now(),Dr=!1,wn?.onThinkingToken&&wn.onThinkingToken()},onToken:j=>{if(Ua=Date.now(),Dr=!1,wn?.onToken){wn.onToken(j),at+=j;return}if(at+=j,!An&&at.length>400&&at.length%250<j.length+1){let ce=vu(at,3);ce.truncated&&(An=!0,ot._clearCursorLine?.(),L(`${m.yellow} \u26A0 LLM stream loop detected (${ce.repeatCount}\xD7 repeated) \u2014 suppressing display${m.reset}`))}An||(Lt+=j,process.stdout.isTTY?bn||(bn=setTimeout(()=>{Lt&&ot&&ot.push(Lt),Lt="",bn=null},50)):(ot.push(Lt),Lt=""),Xe&&(l&&!l._paused?l.pause():Ce&&Ce.stop(),ye||(ye=!0),ot.startCursor(),Xe=!1))}})}catch(b){if(clearInterval(ad),bn&&(clearTimeout(bn),bn=null),Lt&&ot&&(ot.push(Lt),Lt=""),l&&!l._paused&&l.pause(),Ce&&Ce.stop(),ot.stopCursor(),Wa.signal.aborted&&!ma()?.aborted){if(be++,be>fa){if(ve<1){ve++,po("Stale retries exhausted \u2014 last-resort force-compress...",m.yellow);let ce=ht(),{messages:O,tokensRemoved:W}=hn(T,ce);T=O,W>50&&L(`${m.dim} [force-compressed \u2014 ~${W} tokens freed]${m.reset}`),be=0,Ke--;continue}l&&(l.stop(),l=null);let j=await bC();if(j.action==="quit"){u(null),je(Y,re,Z,Se,Pe),Ne(M);break}j.action==="switch"&&(uu(`${j.provider}:${j.model}`),console.log(`${m.green} \u2713 Switched to ${j.provider}:${j.model}${m.reset}`)),be=0,Ke--;continue}let z=be===1?3e3:5e3;if(be>=1&&Ee<1){Ee++,po(`Stale retry ${be}/${fa} \u2014 force-compressing before retry...`,m.yellow);let j=ht(),{messages:ce,tokensRemoved:O}=hn(T,j,!0);if(T=ce,O>0&&O>50&&L(`${m.dim} [force-compressed \u2014 ~${O} tokens freed]${m.reset}`),W1){let W=Ta.fast?.[mo()];W&&W!==nn()&&(uu(`${mo()}:${W}`),console.log(`${m.cyan} \u26A1 Auto-switched to ${W} to avoid further stale timeouts${m.reset}`),console.log(`${m.dim} (disable with NEX_STALE_AUTO_SWITCH=0)${m.reset}`))}}else L(`${m.yellow} \u26A0 Stale retry ${be}/${fa} \u2014 retrying in ${z/1e3}s...${m.reset}`);let K=new ho(`Waiting ${z/1e3}s before retry...`);K.start(),await new Promise(j=>setTimeout(j,z)),K.stop(),Ke--;continue}if(b.name==="AbortError"||b.name==="CanceledError"||b.message?.includes("canceled")||b.message?.includes("aborted")){l&&(l.stop(),l=null),u(null),je(Y,re,Z,Se,Pe),Ne(M);break}let y=b.message;if(b.code==="ECONNREFUSED"||b.message.includes("ECONNREFUSED"))y="Connection refused \u2014 please check your internet connection or API endpoint";else if(b.code==="ENOTFOUND"||b.message.includes("ENOTFOUND"))y="Network error \u2014 could not reach the API server. Please check your connection";else if(b.code==="ETIMEDOUT"||b.message.includes("timeout"))y="Request timed out \u2014 the API server took too long to respond. Please try again";else if(b.message.includes("401")||b.message.includes("Unauthorized"))y="Authentication failed \u2014 please check your API key in the .env file";else if(b.message.includes("403")||b.message.includes("Forbidden"))y="Access denied \u2014 your API key may not have permission for this model";else if(b.message.includes("404")){let z=nn?nn():"unknown",K=O=>O.includes(":")&&O.split(":")[0].match(/^[a-z]+$/)&&!O.split(":")[1].includes(":")?O.split(":").slice(1).join(":"):O;x.add(K(z));let ce=(()=>{let O=[];process.env.NEX_FALLBACK_MODEL&&O.push(process.env.NEX_FALLBACK_MODEL);try{let{getModelForCategory:W}=ms(),R=["agentic","coding","plan","verify","sysadmin","data","frontend"];for(let H of R){let de=W(H);de&&!O.includes(de)&&O.push(de)}}catch{}return O.filter(W=>!x.has(K(W)))})()[0];if(ce){console.log(`${m.yellow} \u26A0 Model ${z} unavailable (404) \u2014 switching to ${ce}${m.reset}`),uu(ce),d0(ce),Ke--;continue}y=`Model not found (404): ${z} \u2014 no fallback available. Set NEX_FALLBACK_MODEL or run /models to list available models`,console.log(`${m.red} \u2717 ${y}${m.reset}`),l&&(l.stop(),l=null),u(null),je(Y,re,Z,Se,Pe),Ne(M);break}else if(b.message.includes("400")){if(ve<3&&Fe<Me){ve++,Fe++;let z=Y===0&&ve===1,K=z||ve===3||Ee>0;if(z){ve=3;let W=b.message.replace(/^API Error(\s*\[HTTP \d+\])?:\s*/i,"").slice(0,150);po(`Bad request (400) \u2014 ${W||"system prompt too large"}, compressing...`,m.yellow)}else po(K?`Bad request (400) \u2014 nuclear compression (attempt ${ve}/3, dropping history)...`:`Bad request (400) \u2014 force-compressing and retrying... (attempt ${ve}/3)`,m.yellow);let j=ht(),{messages:ce,tokensRemoved:O}=hn(T,j,K);T=ce,O>50&&L(`${m.dim} [force-compressed \u2014 ~${O} tokens freed]${m.reset}`),Ke--;continue}{let z=T.find(R=>R.role==="system"),K=T.find(R=>R.role==="user"&&!String(R.content).startsWith("[SYSTEM")&&!String(R.content).startsWith("BLOCKED:")),j=[z,K].filter(Boolean),{getUsage:ce}=fn(),O=fn().estimateMessagesTokens(j),W=fn().estimateMessagesTokens(T);if(O<W){let R=[],H=M.filter(I=>I.role==="assistant"&&typeof I.content=="string"&&I.content.trim().length>30).slice(-5).map(I=>I.content.trim().slice(0,300).replace(/\n+/g," "));H.length>0&&R.push(`Key findings:
1432
1435
  `+H.map(I=>`- ${I}`).join(`
1433
1436
  `));let de=M.filter(I=>I.role==="tool"&&typeof I.content=="string"&&!I.content.startsWith("BLOCKED:")&&I.content.trim().length>10).slice(-5).map(I=>I.content.trim().split(`
1434
1437
  `).slice(0,8).join(`
@@ -1442,7 +1445,7 @@ Continue implementing the fixes based on these findings.`};j.push(I)}if(kr>=3){l
1442
1445
  Files modified so far: ${[...Z].map(_e=>_e.split("/").slice(-1)[0]).join(", ")}`:"";L(`${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.${I?m.dim+I:""}${m.reset}`),l&&(l.stop(),l=null),u(null),je(Y,re,Z,Se,Pe,{suppressHint:!0}),Ne(M);break}T=j,kr++,vs=10+Math.min(se*3,7),Nu=!0,xa=Z.size,ka=!1,Bt=0,he=0;for(let[I,_e]of yn){let Te=_e?.count??_e??0;bu(yn,I,Te>=2?Te:1)}for(let[I]of Tn)mn(yn,I)<2&&Tn.delete(I);Ft.clear(),Rs.clear(),Ut&&Yt>0&&(Ht=!0,L(`${m.cyan} \u26A1 Post-wipe creation guard: cap pre-fired (${Yt} edits already made)${m.reset}`));for(let[I]of ya)bu(ya,I,Lr-1);if(po(`Super-nuclear compression \u2014 dropped all history, keeping original task only (${W-O} tokens freed)`,m.yellow),kr>=1){let I=[...yn.entries()].filter(([,Ve])=>Ve>=Ls).map(([Ve])=>Ve.split("/").slice(-1)[0]),_e=I.length>0?`
1443
1446
 
1444
1447
  Files already at read cap \u2014 use grep_search instead: ${I.join(", ")}`:"",We={role:"user",content:Mt&&!dt?"[SYSTEM] Context was compressed. SSH is currently unavailable \u2014 do not read more local files. Summarize what you found and ask the user for the server output you need.":`[SYSTEM] Context was compressed. Use the findings above to implement your fix. If you need to re-read a file, use line_start/line_end for the specific section.${_e}`};M.push(We),T.push(We)}ve=0,Ke--;continue}}y="Context too large to compress \u2014 use /clear to start fresh"}else b.message.includes("500")||b.message.includes("502")||b.message.includes("503")||b.message.includes("504")?y="API server error \u2014 the provider is experiencing issues. Please try again in a moment":(b.message.includes("fetch failed")||b.message.includes("fetch"))&&(y="Network request failed \u2014 please check your internet connection");if(console.log(`${m.red} \u2717 ${y}${m.reset}`),b.message.includes("429")){if(F++,F>hu){console.log(`${m.red} Rate limit: max retries (${hu}) exceeded. Try again later or use /budget to check your limits.${m.reset}`),l&&(l.stop(),l=null),u(null),je(Y,re,Z,Se,Pe),Ne(M);break e}let z=Math.min(1e4*Math.pow(2,F-1),12e4),K=new ho(`Rate limit \u2014 waiting ${Math.round(z/1e3)}s (retry ${F}/${hu})`);K.start(),await new Promise(j=>setTimeout(j,z)),K.stop();continue}let G=process.env.NEX_PHASE_ROUTING!=="0"&&(()=>{try{return ct().getActiveProviderName()==="ollama"}catch{return!1}})();if(b.message.includes("socket disconnected")||b.message.includes("TLS")||b.message.includes("ECONNRESET")||b.message.includes("ECONNABORTED")||b.message.includes("ETIMEDOUT")||G&&(b.message.includes("500")||b.message.includes("502")||b.message.includes("503")||b.message.includes("504")||b.message.includes("401")||b.message.includes("Unauthorized"))||b.code==="ECONNRESET"||b.code==="ECONNABORTED"){if(ee++,ee>mu){console.log(`${m.red} Network error: max retries (${mu}) exceeded. Check your connection and try again.
1445
- Use /undo to revert changes made during this session.${m.reset}`),l&&(l.stop(),l=null),u(null),je(Y,re,Z,Se,Pe),Ne(M);break e}let z=Math.min(2e3*Math.pow(2,ee-1),3e4),K=new ho(`API temporarily unavailable \u2014 retrying in ${Math.round(z/1e3)}s (${ee}/${mu}). Your changes are safe.`);K.start(),await new Promise(j=>setTimeout(j,z)),K.stop(),Ke--;continue}l&&(l.stop(),l=null),u(null),je(Y,re,Z,Se,Pe),Ne(M);break}if(clearInterval(id),F=0,ee=0,Xe&&(l&&!l._paused&&l.pause(),Ce&&Ce.stop()),bn&&(clearTimeout(bn),bn=null),Lt&&ot&&(ot.push(Lt),Lt=""),at&&ot.flush(),ee=0,be=0,Pt&&Pt.usage){let b=Pt.usage.prompt_tokens||0,y=Pt.usage.completion_tokens||0;h0(mo(),nn(),b,y),d+=b+y,l&&l.setStats({tokens:d})}else if(Pt&&!Pt.usage){let b=T.map(U=>typeof U.content=="string"?U.content:Array.isArray(U.content)?U.content.map(z=>typeof z=="string"?z:z.text||"").join(""):"").join(" "),y=g0(b),G=g0(Pt.content||at||"");h0(mo(),nn(),y,G),d+=y+G,l&&l.setStats({tokens:d})}let{content:ad,tool_calls:Is}=Pt,on=Is,Ha=!1;if(Array.isArray(Is)&&Is.length>0){let b=Is.filter(y=>y?.function?.name==="ask_user");b.length>0&&(on=[b[0]],Ha=Is.length!==1,Ha&&L(`${m.yellow} \u26A0 ask_user must run alone \u2014 deferring ${Is.length-1} other tool call(s) until the user replies${m.reset}`))}let qr=vu(ad||""),cd=qr.truncated?qr.text:ad;qr.truncated&&L(`${m.yellow} \u26A0 LLM output loop detected (${qr.repeatCount}\xD7 repeated paragraph) \u2014 response truncated${m.reset}`);let Fr=C1(cd||""),Tt=Fr.truncated?Fr.text:cd;Fr.truncated&&L(`${m.yellow} \u26A0 LLM output loop detected (${Fr.repeatCount}\xD7 repeated window) \u2014 response truncated${m.reset}`);let To={role:"assistant",content:Tt||""};if(on&&on.length>0&&(To.tool_calls=on),M.push(To),T.push(To),od&&!da(Tt||at||"")&&Z.size===0&&Ms===0){L(`${m.green} \u2713 Analysis-only early exit: ${(Tt||"").length} chars produced, no file changes${m.reset}`),To.tool_calls&&delete To.tool_calls,je(Y,re,Z,Se,Pe),Ne(M);break e}if(!dt&&Tt&&on&&on.length>0){let b=wu(Tt);if(b){dt=!0,vt=b.slice(0,120),Wt=0,Ht=!1,tn=0,L(`${m.yellow} \u26A1 Root cause in model analysis: ${vt} \u2014 fix phase (read budget: 3)${m.reset}`);let y={role:"user",content:`[SYSTEM] Root cause identified: ${vt}. Read only the file that needs fixing, then edit it. Do not read other files.`};M.push(y),T.push(y)}}if(!on||on.length===0){let b=(Tt||"").trim().length>0||at.trim().length>0,y=!1;if(Mt&&b&&(pa>=2?L(`${m.yellow} \u26A0 SSH permanently blocked after ${pa} storm warnings \u2014 no further SSH calls allowed${m.reset}`):(Mt=!1,Bt=Eo-4,y=!0)),y&&b){let K=(Tt||"").trim();if(K.endsWith("?")||/\b(Wo |Bitte |Kannst du|Soll ich)\b/.test(K.slice(-200))){let ce={role:"user",content:"[SYSTEM] Continue. Do not ask questions \u2014 implement the fix yourself using SSH. The server is at 94.130.37.43."};T.push(ce),M.push(ce);continue}}if(!b&&Y>0&&Ke<Su-1){let K={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."};T.push(K),M.push(K);continue}let G=/keine.*Tool|can.?t use.*tool|Tool.?Budget|nicht.*zugreifen|cannot.*access|no.*tool.*access|keine.*Werkzeug|da ich keine.*kann/i;if(b&&Ke<3&&G.test((Tt||"").slice(0,600)))if(Nu&&vs<=0||Mt){L(`${m.yellow} \u26A0 Tool avoidance (constrained context) \u2014 telling model to ask user${m.reset}`);let j={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."};T.push(j),M.push(j);continue}else{L(`${m.yellow} \u26A0 Tool avoidance detected \u2014 nudging model to use tools${m.reset}`);let j={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."};T.push(j),M.push(j);continue}if(n.skillLoop&&b&&Y>3&&jr<5){let K=(Tt||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(K.slice(-600))){jr=(jr||0)+1,L(`${m.yellow} \u26A0 Skill loop: model tried to stop \u2014 continuation nudge #${jr}${m.reset}`);let ce={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."};T.push(ce),M.push(ce);continue}}if(Ts()&&!n.skillLoop&&(Z.size>0||Ms>0)&&b&&!da(Tt||at||"")&&Y>=1&&(!we||Re==="implement")){L(`${m.green} \u2713 Headless early exit: ${Z.size} file(s) modified (+ ${Ms} bash writes), substantive text response received${m.reset}`),je(Y,re,Z,Se,Pe),Ne(M);break e}let z=V1(Er)?1:2;if(we&&Re==="plan"&&Fn>=z){L(`${m.cyan} \u21B3 Plan phase: ${Fn} consecutive blocks (last: ${Er||"unknown"}) \u2014 auto-advancing to implement${m.reset}`),Fn=0,Er=null;let K=await $r("implement","[auto-advance: task only requires direct action]");if(K){M.push(K),T.push(K),Ke=0,Et=_s("implement");continue}}if(we&&b){let K=(Tt||at||"").trim();if(Re==="plan"){let j=/\b(no match(es)?|not found|couldn'?t find|does not exist|no results|nothing found|no files|keine (Ergebnisse|Treffer|Übereinstimmung|Funde|passenden)|nicht gefunden|nichts gefunden)\b/i,ce=D0(K,yn).length===0,O=Rr.size>0,W=Cr.size>0,R=K.length>1500;if(Ts()&&ce&&!O&&!W&&!R&&j.test(K)){L(`${m.yellow} \u26A0 Plan phase: nothing actionable found \u2014 exiting gracefully${m.reset}`),process.stdout.isTTY&&process.stderr.write(`${m.yellow} \u26A0 Could not find the target in this project. The plan phase found no actionable items.${m.reset}
1448
+ Use /undo to revert changes made during this session.${m.reset}`),l&&(l.stop(),l=null),u(null),je(Y,re,Z,Se,Pe),Ne(M);break e}let z=Math.min(2e3*Math.pow(2,ee-1),3e4),K=new ho(`API temporarily unavailable \u2014 retrying in ${Math.round(z/1e3)}s (${ee}/${mu}). Your changes are safe.`);K.start(),await new Promise(j=>setTimeout(j,z)),K.stop(),Ke--;continue}l&&(l.stop(),l=null),u(null),je(Y,re,Z,Se,Pe),Ne(M);break}if(clearInterval(ad),F=0,ee=0,Xe&&(l&&!l._paused&&l.pause(),Ce&&Ce.stop()),bn&&(clearTimeout(bn),bn=null),Lt&&ot&&(ot.push(Lt),Lt=""),at&&ot.flush(),ee=0,be=0,Pt&&Pt.usage){let b=Pt.usage.prompt_tokens||0,y=Pt.usage.completion_tokens||0;m0(mo(),nn(),b,y),d+=b+y,l&&l.setStats({tokens:d})}else if(Pt&&!Pt.usage){let b=T.map(U=>typeof U.content=="string"?U.content:Array.isArray(U.content)?U.content.map(z=>typeof z=="string"?z:z.text||"").join(""):"").join(" "),y=y0(b),G=y0(Pt.content||at||"");m0(mo(),nn(),y,G),d+=y+G,l&&l.setStats({tokens:d})}let{content:cd,tool_calls:Is}=Pt,on=Is,Ha=!1;if(Array.isArray(Is)&&Is.length>0){let b=Is.filter(y=>y?.function?.name==="ask_user");b.length>0&&(on=[b[0]],Ha=Is.length!==1,Ha&&L(`${m.yellow} \u26A0 ask_user must run alone \u2014 deferring ${Is.length-1} other tool call(s) until the user replies${m.reset}`))}let qr=vu(cd||""),ld=qr.truncated?qr.text:cd;qr.truncated&&L(`${m.yellow} \u26A0 LLM output loop detected (${qr.repeatCount}\xD7 repeated paragraph) \u2014 response truncated${m.reset}`);let Fr=C1(ld||""),Tt=Fr.truncated?Fr.text:ld;Fr.truncated&&L(`${m.yellow} \u26A0 LLM output loop detected (${Fr.repeatCount}\xD7 repeated window) \u2014 response truncated${m.reset}`);let To={role:"assistant",content:Tt||""};if(on&&on.length>0&&(To.tool_calls=on),M.push(To),T.push(To),rd&&!da(Tt||at||"")&&Z.size===0&&Ms===0){L(`${m.green} \u2713 Analysis-only early exit: ${(Tt||"").length} chars produced, no file changes${m.reset}`),To.tool_calls&&delete To.tool_calls,je(Y,re,Z,Se,Pe),Ne(M);break e}if(!dt&&Tt&&on&&on.length>0){let b=wu(Tt);if(b){dt=!0,vt=b.slice(0,120),Wt=0,Ht=!1,tn=0,L(`${m.yellow} \u26A1 Root cause in model analysis: ${vt} \u2014 fix phase (read budget: 3)${m.reset}`);let y={role:"user",content:`[SYSTEM] Root cause identified: ${vt}. Read only the file that needs fixing, then edit it. Do not read other files.`};M.push(y),T.push(y)}}if(!on||on.length===0){let b=(Tt||"").trim().length>0||at.trim().length>0,y=!1;if(Mt&&b&&(pa>=2?L(`${m.yellow} \u26A0 SSH permanently blocked after ${pa} storm warnings \u2014 no further SSH calls allowed${m.reset}`):(Mt=!1,Bt=Eo-4,y=!0)),y&&b){let K=(Tt||"").trim();if(K.endsWith("?")||/\b(Wo |Bitte |Kannst du|Soll ich)\b/.test(K.slice(-200))){let ce={role:"user",content:"[SYSTEM] Continue. Do not ask questions \u2014 implement the fix yourself using SSH. The server is at 94.130.37.43."};T.push(ce),M.push(ce);continue}}if(!b&&Y>0&&Ke<Su-1){let K={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."};T.push(K),M.push(K);continue}let G=/keine.*Tool|can.?t use.*tool|Tool.?Budget|nicht.*zugreifen|cannot.*access|no.*tool.*access|keine.*Werkzeug|da ich keine.*kann/i;if(b&&Ke<3&&G.test((Tt||"").slice(0,600)))if(Nu&&vs<=0||Mt){L(`${m.yellow} \u26A0 Tool avoidance (constrained context) \u2014 telling model to ask user${m.reset}`);let j={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."};T.push(j),M.push(j);continue}else{L(`${m.yellow} \u26A0 Tool avoidance detected \u2014 nudging model to use tools${m.reset}`);let j={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."};T.push(j),M.push(j);continue}if(n.skillLoop&&b&&Y>3&&jr<5){let K=(Tt||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(K.slice(-600))){jr=(jr||0)+1,L(`${m.yellow} \u26A0 Skill loop: model tried to stop \u2014 continuation nudge #${jr}${m.reset}`);let ce={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."};T.push(ce),M.push(ce);continue}}if(Ts()&&!n.skillLoop&&(Z.size>0||Ms>0)&&b&&!da(Tt||at||"")&&Y>=1&&(!we||Re==="implement")){L(`${m.green} \u2713 Headless early exit: ${Z.size} file(s) modified (+ ${Ms} bash writes), substantive text response received${m.reset}`),je(Y,re,Z,Se,Pe),Ne(M);break e}let z=V1(Er)?1:2;if(we&&Re==="plan"&&Fn>=z){L(`${m.cyan} \u21B3 Plan phase: ${Fn} consecutive blocks (last: ${Er||"unknown"}) \u2014 auto-advancing to implement${m.reset}`),Fn=0,Er=null;let K=await $r("implement","[auto-advance: task only requires direct action]");if(K){M.push(K),T.push(K),Ke=0,Et=_s("implement");continue}}if(we&&b){let K=(Tt||at||"").trim();if(Re==="plan"){let j=/\b(no match(es)?|not found|couldn'?t find|does not exist|no results|nothing found|no files|keine (Ergebnisse|Treffer|Übereinstimmung|Funde|passenden)|nicht gefunden|nichts gefunden)\b/i,ce=q0(K,yn).length===0,O=Rr.size>0,W=Cr.size>0,R=K.length>1500;if(Ts()&&ce&&!O&&!W&&!R&&j.test(K)){L(`${m.yellow} \u26A0 Plan phase: nothing actionable found \u2014 exiting gracefully${m.reset}`),process.stdout.isTTY&&process.stderr.write(`${m.yellow} \u26A0 Could not find the target in this project. The plan phase found no actionable items.${m.reset}
1446
1449
  `),je(Y,re,Z,Se,Pe),Ne(M);break e}let H=await $r("implement",K);if(H){M.push(H),T.push(H),Ke=0,Et=_s("implement");continue}}else if(Re==="implement"&&(Z.size>0||Ms>0)){let j=M.find(W=>W.role==="user"),ce=typeof j?.content=="string"?j.content:"",O=await $r("verify",K,Z,ce);if(O){M.push(O),T.push(O),Ke=0,Et=Math.min(_s("verify")+Math.max(0,(Z.size-2)*2),20);continue}}else if(Re==="verify"){let j=/\bPASS\b/i.test(K.slice(0,500)),O=/\bFAIL\b|test.*fail|error|broken|missing|incorrect/i.test(K.slice(0,500)),W=$o>0||T.some(R=>R.role==="assistant"&&typeof R.content=="string"&&/\bPASS\b/i.test(R.content.slice(0,500)));if(Ts()&&!n.skillLoop&&W&&!O&&!da(K)){L(`${m.green} \u2713 Verification phase complete (headless substantive summary)${m.reset}`),je(Y,re,Z,Se,Pe),Ne(M),yr(M);break e}if(O&&bo<3){bo++;let R={role:"user",content:`[PHASE: RE-IMPLEMENTATION] Verification found issues:
1447
1450
  ${K.slice(0,400)}
1448
1451
 
@@ -1462,30 +1465,30 @@ ${m.cyan}${m.bold}Plan ready.${m.reset} ${m.green}[A]${m.reset}${m.dim}pprove${
1462
1465
  Implement the following plan step by step. All tools are now available.
1463
1466
 
1464
1467
  ${getPlanContent()||Pt.content}`;M.push({role:"user",content:I}),T.push({role:"user",content:I}),ce=!0}}else console.log(`
1465
- ${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(ce){l&&(l.stop(),l=null),Ke--;continue}}}if(l&&(l.stop(),l=null),u(null),je(Y,re,Z,Se,Pe),Ut&&Z.size>=3){let K=[...Z].map(R=>R.split("/").pop()).slice(0,8).join(", "),j=[...Z].some(R=>R.endsWith("package.json")),ce=[...Z].some(R=>R.endsWith("requirements.txt")),O=[...Z].some(R=>R.endsWith("package-lock.json")||R.endsWith("yarn.lock")||R.endsWith("pnpm-lock.yaml")),W=j&&!O?"npm install not yet run":ce?"pip install not yet run":null;Sr=`[Previous session created ${Z.size} files: ${K}`+(W?` \u2014 ${W}`:"")+". Use this context to answer follow-up questions without re-reading files.]"}if(Ut&&!Mu&&Y>0){let K=[...Z].some(se=>se.endsWith("package.json")),j=[...Z].some(se=>se.endsWith("requirements.txt")||se.endsWith("Pipfile")||se.endsWith("pyproject.toml")),ce=[...Z].some(se=>se.endsWith("package-lock.json")||se.endsWith("yarn.lock")||se.endsWith("pnpm-lock.yaml")),O=M.flatMap(se=>{let I=Array.isArray(se.tool_calls)?se.tool_calls:[],_e=Array.isArray(se.content)?se.content.filter(Te=>Te?.type==="tool_use"):[];return[...I,..._e]}).filter(se=>{let I=se.function?.name||se.name||"";return I==="bash"||I==="Bash"}).map(se=>{try{let I=se.function?.arguments??se.input??{};return(typeof I=="string"?JSON.parse(I):I)?.command||""}catch{return""}}),W=O.some(se=>/pip\s+install|python\s+-m\s+venv/.test(se)),R=O.some(se=>/npm\s+install/.test(se)),de=[...Z].some(se=>/\/App\.(js|ts|jsx|tsx)$/.test(se))&&!K&&!R;if(j&&!W||K&&!ce&&!R||de){Mu=!0;let se=[];j&&!W&&se.push("python -m venv venv && source venv/bin/activate && pip install -r requirements.txt"),de?se.push("create package.json for the React frontend (with react, react-dom, react-scripts dependencies), then run npm install"):K&&!ce&&!R&&se.push("npm install");let I=`[FRAMEWORK \u2014 post-creation check] You wrote dependency files but never ran the installer. Run now: ${se.join(" && ")}. Verify it succeeds, fix any errors, then write a closing summary.`;L(`${m.dim} [post-creation] bootstrapping environment (${se.join(", ")})${m.reset}`),M.push({role:"user",content:I}),T.push({role:"user",content:I});continue}}if(Y>0&&!n._isSummaryTurn&&da(Tt))try{L(`${m.dim} [post-turn] terse ending \u2014 requesting diagnosis/summary${m.reset}`);let K=Z.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.",j=[...T,{role:"user",content:K}],O=((await d0(j,[],{}))?.content||"").trim();O&&(console.log(`
1466
- ${O}`),M.push({role:"user",content:K},{role:"assistant",content:O}))}catch{}Ne(M),yr(M),await sd();return}Y++,Ca++,Y>=1&&(ye=!1);for(let b of on){let y=b.function.name;re.set(y,(re.get(y)||0)+1)}if(Y>=30&&!v0){v0=!0,L(`${m.yellow} \u26A0 Tool budget warning: ${Y} tool calls used \u2014 nudging model to wrap up${m.reset}`);let b={role:"user",content:"[SYSTEM] \u26A0 You have used "+Y+" 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."};M.push(b),T.push(b)}let ke=await Promise.all(on.map(b=>Y1(b)));if(Ba){let b=new Set(["read_file","grep","search_files","glob","list_directory","ssh_exec","find_files"]);for(let y of ke)!y.canExecute||!b.has(y.fnName)||(y.canExecute=!1,y.errorResult={role:"tool",content:"BLOCKED: You already have enough evidence to produce the requested summary/document. Write the deliverable now and stop reading more files.",tool_call_id:y.callId})}{let b=en(T,ht()),y=b.percentage,G=ke.some(j=>j.canExecute&&j.fnName==="read_file"&&!j.args?.line_end),U=ke.filter(j=>j.canExecute&&j.fnName==="read_file"&&j.args?.path&&mn(Ps,j.args.path)>=1&&!j.args?.line_start).map(j=>j.args.path.split("/").slice(-2).join("/")),z=U.length>0;if(y>=70&&G&&Da<70||y>=85&&Da<85||z){Da=y;let j=y>=85?"URGENT":"WARNING",ce;z?(j="WARNING",ce=`Full-file read of ${U.join(", ")} already done \u2014 use line_start/line_end for specific sections instead.`):G?ce=`Unbounded read at ${Math.round(y)}% context \u2014 use line_start/line_end to avoid overflow.`:ce="Use targeted reads (line_start/line_end) to save space.";let O={role:"user",content:`[SYSTEM ${j}] Context ${Math.round(y)}% used (${b.used}/${b.limit} tokens). ${ce}`};if(M.push(O),T.push(O),y>=85){let W=z?` (re-read of: ${U.join(", ")})`:"";L(`${m.yellow} \u26A0 Context ${Math.round(y)}% used \u2014 agent warned to use targeted reads${W}${m.reset}`)}}}let Ya=new Map;for(let b of ke){if(!b.canExecute||b.fnName!=="read_file")continue;let y=b.args?.path;if(!y)continue;let G=mn(Ps,y),U=Ya.get(y)||0,z=G+U,K=ks.has(y),j=b.args?.line_start!=null,ce=Ft.get(y)||0,O=ce>0,W=2;if(!K&&z>=Ls){let R=y.split("/").slice(-2).join("/"),H=(Rs.get(y)||0)+1;if(Rs.set(y,H),H===1)L(`${m.red} \u2716 Blocked: "${R}" read ${z}\xD7 \u2014 hard cap (${Ls}) reached${m.reset}`);else if(H===2){L(`${m.red} \u2716 Escalated block: "${R}" \u2014 model ignored BLOCKED, injecting system warning${m.reset}`);let de={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 (${Ls}\xD7). Do NOT attempt to read it again. Use grep_search to find specific content, or proceed with what you already know.`};M.push(de),T.push(de)}b.canExecute=!1,b.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 file already read ${z}\xD7 (hard cap: ${Ls}). You have seen enough of this file. Use grep to find specific content or proceed with what you know.`,tool_call_id:b.callId}}else if(!K&&z>=1&&j)if(O&&ce<=W){let R=y.split("/").slice(-2).join("/");console.log(`${m.cyan} \u21A9 Targeted re-read: "${R}" (line_start=${b.args.line_start}) \u2014 edit recovery #${ce}${m.reset}`),Ft.set(y,ce-1)}else if(O&&ce>W){let R=y.split("/").slice(-2).join("/");L(`${m.red} \u2716 Edit recovery blocked: "${R}" \u2014 ${W} recovery reads already used. Use grep to find the exact line numbers, then retry.${m.reset}`),b.canExecute=!1,b.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 edit recovery budget exhausted (${W} 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:b.callId}}else{let R=parseInt(b.args.line_start,10)||1,H=parseInt(b.args.line_end,10)||R+350,de=Tn.get(y)||[],$e=!1;for(let[se,I]of de){let _e=Math.max(R,se),Te=Math.min(H,I);if(Te>_e){let We=Te-_e,Ve=H-R||1,It=I-se||1,nt=We/It>=.7&&We/Ve<.7,Br=H-R<=vw;if(We>=Ve||!Br&&(We/Ve>=.7||We/It>=.7)){let za=y.split("/").slice(-2).join("/"),pd=`${y}:${R}-${H}`,Ds=(Ra.get(pd)||0)+1;if(Ra.set(pd,Ds),L(nt?`${m.red} \u2716 Blocked superread: "${za}" lines ${R}-${H} subsumes already-read ${se}-${I} \u2014 use line_start=${I+1} to skip known content (block #${Ds})${m.reset}`:`${m.red} \u2716 Blocked duplicate read: "${za}" lines ${R}-${H} (\u226570% overlap with lines ${se}-${I} already in context, block #${Ds})${m.reset}`),Ds>=2){L(`${m.red} \u2716 Escalated range-block: "${za}" lines ${R}-${H} \u2014 model ignored BLOCKED, injecting system warning${m.reset}`);let hd={role:"user",content:nt?`[SYSTEM] Read blocked ${Ds}\xD7 for read_file("${y}", lines ${R}-${H}). Lines ${se}-${I} were already read. Use line_start=${I+1} to read only new content, or use grep_search for specific lines.`:`[SYSTEM] Read blocked ${Ds}\xD7 for read_file("${y}", lines ${R}-${H}). Lines ${se}-${I} were already read and will NOT change. Use grep_search to find specific content instead.`};M.push(hd),T.push(hd)}b.canExecute=!1,b.errorResult={role:"tool",content:nt?`BLOCKED: read_file("${y}", lines ${R}-${H}) re-reads lines ${se}-${I} already in context. Use line_start=${I+1} to read only the new content beyond line ${I}.`:`BLOCKED: read_file("${y}", lines ${R}-${H}) is a duplicate \u2014 lines ${se}-${I} are already in your context (\u226570% overlap). Use grep to find specific content instead of re-reading.`,tool_call_id:b.callId},$e=!0;break}}}if(!$e){let se=de.length,I=2;if(se>=3){let Te=y.split("/").slice(-2).join("/");L(`${m.red} \u2716 Blocked file-scroll: "${Te}" \u2014 ${se} sections already read. Use grep to find specific content.${m.reset}`);let We=mn(ja,y)>=Lr;b.canExecute=!1,b.errorResult={role:"tool",content:We?`BLOCKED: read_file("${y}") denied \u2014 you have already read ${se} 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 ${se} 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:b.callId}}else se>=I&&(b._scrollWarn={sectionCount:se+1,path:y})}}else if(!K&&z>=1){let R=Ft.get(y)||0;if(R>0){let H=y.split("/").slice(-2).join("/");console.log(`${m.cyan} \u21A9 Full re-read: "${H}" \u2014 test-failure recovery (${R} remaining)${m.reset}`);let de=R-1;de<=0?Ft.delete(y):Ft.set(y,de)}else{let H=y.split("/").slice(-2).join("/"),de=(Rs.get(y)||0)+1;if(Rs.set(y,de),de===1)L(`${m.red} \u2716 Blocked unbounded re-read: "${H}" \u2014 already in context. Use line_start/line_end for specific sections.${m.reset}`);else if(de===2){L(`${m.red} \u2716 Escalated block: "${H}" \u2014 model ignored unbounded re-read block, injecting system warning${m.reset}`);let $e={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.`};M.push($e),T.push($e)}b.canExecute=!1,b.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 file already in context (read ${z}\xD7). Use line_start/line_end to read a specific section instead of the full file.`,tool_call_id:b.callId}}}b.canExecute&&Ya.set(y,(Ya.get(y)||0)+1)}if(qn>=3)for(let b of ke)b.canExecute&&(b.fnName!=="read_file"&&b.fnName!=="edit_file"||(L(`${m.red} \u2716 Blocked ${b.fnName} \u2014 ${qn} consecutive file-not-found errors, must search first${m.reset}`),b.canExecute=!1,b.errorResult={role:"tool",content:`BLOCKED: ${qn} 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:b.callId}));for(let b of ke){if(!b.canExecute||b.fnName!=="bash")continue;let y=(b.args?.command||"").trim();if(/^\s*ls(\s+-[a-zA-Z]+)*(\s+\S+)?\s*$/.test(y)&&!/npm|yarn|pnpm|make|git/.test(y)){L(`${m.red} \u2716 Blocked bash ls \u2014 use list_directory tool instead${m.reset}`),b.canExecute=!1,b.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:b.callId};continue}/\bfind\s+[\S.]/.test(y)&&!/git\s|npm\s|yarn\s|-exec\s+\S|-execdir/.test(y)&&(L(`${m.red} \u2716 Blocked bash find \u2014 use glob tool with a pattern instead${m.reset}`),b.canExecute=!1,b.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:b.callId})}for(let b of ke)b.canExecute&&(b.fnName!=="ssh_exec"&&b.fnName!=="bash"||/\bsed\s+-n\b/.test(b.args?.command||"")&&(L(`${m.red} \u2716 Blocked sed -n: use grep -n "pattern" <file> | head -30 instead${m.reset}`),b.canExecute=!1,b.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:b.callId}));for(let b of ke){if(!b.canExecute||b.fnName!=="write_file")continue;let y=b.args?.path,G=b.args?.content||"";if(y)try{let U=require("fs"),z=require("path").resolve(process.cwd(),y);if(U.existsSync(z)){let K=U.statSync(z).size,j=Buffer.byteLength(G,"utf8"),ce=K>0?j/K:1,O=Iu(P),W=Iu(y);if(S0(P)&&(O.includes(W)||O.includes(`./${W}`)))continue;if(ce<.6&&K>200){let H=y.split("/").slice(-2).join("/");console.log(`${m.red} \u2716 write_file shrink guard: "${H}" would shrink to ${Math.round(ce*100)}% of original \u2014 likely context loss${m.reset}`),b.canExecute=!1,b.errorResult={role:"tool",content:`BLOCKED: write_file("${y}") denied \u2014 new content is only ${Math.round(ce*100)}% of current file size (${K} \u2192 ${j} 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:b.callId}}}}catch{}}let ld=new Map;for(let b of ke){if(!b.canExecute||b.fnName!=="grep")continue;let y=b.args?.path;if(!y)continue;let G=ld.get(y)||0,U=mn(ja,y)+G,z=mn(Ps,y)>=1,K=z?Math.min(3,Lr):Lr;if(U>=K){let j=y.split("/").slice(-2).join("/");L(`${m.red} \u2716 Blocked grep: "${j}" grepped ${U}\xD7 with different patterns \u2014 flood threshold exceeded${m.reset}`);let ce=mn(Ps,y),O=ce>=Ls;if(O){let W={role:"user",content:`[SYSTEM] Both read_file and grep are now blocked for "${y}". You have already read ${ce} sections and tried ${U} 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.`};M.push(W),T.push(W),L(`${m.red} \u2716 Deadlock detected: "${j}" \u2014 both read and grep blocked, injecting deadlock-break${m.reset}`)}b.canExecute=!1,b.errorResult={role:"tool",content:O?`BLOCKED: grep("${y}") denied \u2014 ${U} 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.`:z?`BLOCKED: grep("${y}") denied \u2014 file was already read and ${U} grep patterns tried. The content is already in your context; use it instead of searching again.`:`BLOCKED: grep("${y}") denied \u2014 ${U} patterns already tried. Work with the grep results already in your context.`,tool_call_id:b.callId}}b.canExecute&&ld.set(y,G+1)}let Aw=5,ud=new Map;for(let b of ke){if(!b.canExecute||b.fnName!=="ssh_exec")continue;let G=(b.args?.command||"").replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),U=ud.get(G)||0,z=mn(ed,G)+U;z>=Aw&&(L(`${m.yellow} \u26A0 Blocked ssh_exec: same command run ${z}\xD7 \u2014 result already in context${m.reset}`),b.canExecute=!1,b.errorResult={role:"tool",content:`BLOCKED: ssh_exec denied \u2014 this command has already run ${z} 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:b.callId}),b.canExecute&&ud.set(G,U+1)}if(Mt){let b=ke.filter(U=>U.canExecute&&U.fnName==="ssh_exec"),y=ke.some(U=>U.canExecute&&U.fnName!=="ssh_exec"),G=X&&he<3;if(b.length>0&&!y&&G&&_a<1)Mt=!1,_a++,Bt=Math.max(0,Eo-2),L(`${m.dim} [dual-block deadlock: SSH storm relaxed \u2014 allowing 1 SSH call (relax ${_a}/1)]${m.reset}`);else for(let U of b)U.canExecute=!1,U.errorResult={role:"tool",content:dt?`BLOCKED: ssh_exec denied \u2014 SSH paused (${Eo}+ calls). Root cause is known (${vt}). 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 (${Eo}+ 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:U.callId}}let Ow=F1(M,["browser_open","browser_screenshot","ssh_exec","service_logs","remote_agent"]);if((X||C)&&!Ow&&he<3&&!Mt)for(let b of ke){if(!b.canExecute||!["bash","read_file","find_files","list_directory","search_files","glob","grep"].includes(b.fnName))continue;he++;{let U=ht(),{messages:z}=hn(T,U);T=z}let y=B?.matchedName?`${B.matchedName} (${B.matchedProfile?.host||"server"})`:B?.url,G=B?.shouldPreferSsh?`BLOCKED: ${b.fnName} denied \u2014 this looks like a live app/server issue. Inspect ${B?.url} with browser_open or use ssh_exec on ${y} first, then return to local code if needed.`:`BLOCKED: ${b.fnName} denied \u2014 this looks like a live app issue. Inspect ${B?.url} with browser_open first, then return to local code if needed.`;L(`${m.yellow} \u26A0 Runtime guard: blocking local ${b.fnName} \u2014 inspect the live app first${m.reset}`),b.canExecute=!1,b.errorResult={role:"tool",content:G,tool_call_id:b.callId};break}if(!we&&Ht&&Ut&&Yt>=1){let b=["read_file","grep","search_files","glob","list_directory","find_files"];for(let y of ke)y.canExecute&&b.includes(y.fnName)&&(L(`${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(vs>=0){let b=ke.filter(y=>y.canExecute).length;if(b>0&&(vs-=b,vs<0))if(!ka&&Z.size>xa){ka=!0,vs=5,L(`${m.green} \u2713 Post-wipe progress detected (${Z.size-xa} 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."};M.push(y),T.push(y)}else{L(`${m.red} \u2716 Post-wipe tool budget exhausted \u2014 blocking all tool calls${m.reset}`);for(let G of ke)G.canExecute&&(G.canExecute=!1,G.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:G.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."};M.push(y),T.push(y)}}let Nw=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 b of ke){if(!b.canExecute||Nw.has(b.fnName))continue;let y=JSON.stringify(b.args||{}),G=`${b.fnName}|${y}`,U=mn(Au,G);U>=2?(L(`${m.red} \u2716 Blocked duplicate: ${b.fnName}(${y.substring(0,80)}) \u2014 called ${U+1}\xD7 with identical args${m.reset}`),b.canExecute=!1,b.errorResult={role:"tool",content:`BLOCKED: ${b.fnName}() with these exact arguments has already been called ${U}\xD7 \u2014 the result is already in your context. Use the existing output instead of repeating the same call.`,tool_call_id:b.callId}):U===1&&L(`${m.yellow} \u26A0 Duplicate tool call: ${b.fnName}(${y.substring(0,80)}) \u2014 2nd call with identical args${m.reset}`),xs(Au,G)}{let b=new Set;for(let y of ke){if(!y.canExecute||!["edit_file","patch_file"].includes(y.fnName))continue;let G=y.args?.path;G&&(b.has(G)?(y.canExecute=!1,y.errorResult={role:"tool",content:`BLOCKED: "${G}" is already being edited in this batch. Finish one edit first, then re-read the changed section before the next one.`,tool_call_id:y.callId},L(`${m.yellow} \u26A0 Map-first gate: blocked duplicate same-batch edit of "${G.split("/").slice(-1)[0]}"${m.reset}`)):Os.has(G)&&!ks.has(G)?(y.canExecute=!1,y.errorResult={role:"tool",content:`BLOCKED: "${G}" 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},L(`${m.yellow} \u26A0 Map-first gate: blocked re-edit of "${G.split("/").slice(-1)[0]}" \u2014 re-read required${m.reset}`)):b.add(G))}}let Ro=l?{skipSpinner:!0,skipSummaries:!0}:{},Mw=ke.some(b=>b.fnName==="ask_user"),dd=!Ro.skipSummaries&&!ye,zt=null,js=null;if(dd&&!Mw){if(ye=!0,Ro.skipSpinner=!0,process.stdout.isTTY){global._nexFooter&&(js=Math.min(global._nexFooter._lastOutputRow+1,global._nexFooter._scrollEnd));let b=gr(ke,Y,!1,0),y=gr(ke,Y,!1);process.stdout.write(`${Y>1?`
1468
+ ${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(ce){l&&(l.stop(),l=null),Ke--;continue}}}if(l&&(l.stop(),l=null),u(null),je(Y,re,Z,Se,Pe),Ut&&Z.size>=3){let K=[...Z].map(R=>R.split("/").pop()).slice(0,8).join(", "),j=[...Z].some(R=>R.endsWith("package.json")),ce=[...Z].some(R=>R.endsWith("requirements.txt")),O=[...Z].some(R=>R.endsWith("package-lock.json")||R.endsWith("yarn.lock")||R.endsWith("pnpm-lock.yaml")),W=j&&!O?"npm install not yet run":ce?"pip install not yet run":null;Sr=`[Previous session created ${Z.size} files: ${K}`+(W?` \u2014 ${W}`:"")+". Use this context to answer follow-up questions without re-reading files.]"}if(Ut&&!Mu&&Y>0){let K=[...Z].some(se=>se.endsWith("package.json")),j=[...Z].some(se=>se.endsWith("requirements.txt")||se.endsWith("Pipfile")||se.endsWith("pyproject.toml")),ce=[...Z].some(se=>se.endsWith("package-lock.json")||se.endsWith("yarn.lock")||se.endsWith("pnpm-lock.yaml")),O=M.flatMap(se=>{let I=Array.isArray(se.tool_calls)?se.tool_calls:[],_e=Array.isArray(se.content)?se.content.filter(Te=>Te?.type==="tool_use"):[];return[...I,..._e]}).filter(se=>{let I=se.function?.name||se.name||"";return I==="bash"||I==="Bash"}).map(se=>{try{let I=se.function?.arguments??se.input??{};return(typeof I=="string"?JSON.parse(I):I)?.command||""}catch{return""}}),W=O.some(se=>/pip\s+install|python\s+-m\s+venv/.test(se)),R=O.some(se=>/npm\s+install/.test(se)),de=[...Z].some(se=>/\/App\.(js|ts|jsx|tsx)$/.test(se))&&!K&&!R;if(j&&!W||K&&!ce&&!R||de){Mu=!0;let se=[];j&&!W&&se.push("python -m venv venv && source venv/bin/activate && pip install -r requirements.txt"),de?se.push("create package.json for the React frontend (with react, react-dom, react-scripts dependencies), then run npm install"):K&&!ce&&!R&&se.push("npm install");let I=`[FRAMEWORK \u2014 post-creation check] You wrote dependency files but never ran the installer. Run now: ${se.join(" && ")}. Verify it succeeds, fix any errors, then write a closing summary.`;L(`${m.dim} [post-creation] bootstrapping environment (${se.join(", ")})${m.reset}`),M.push({role:"user",content:I}),T.push({role:"user",content:I});continue}}if(Y>0&&!n._isSummaryTurn&&da(Tt))try{L(`${m.dim} [post-turn] terse ending \u2014 requesting diagnosis/summary${m.reset}`);let K=Z.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.",j=[...T,{role:"user",content:K}],O=((await f0(j,[],{}))?.content||"").trim();O&&(console.log(`
1469
+ ${O}`),M.push({role:"user",content:K},{role:"assistant",content:O}))}catch{}Ne(M),yr(M),await od();return}Y++,Ca++,Y>=1&&(ye=!1);for(let b of on){let y=b.function.name;re.set(y,(re.get(y)||0)+1)}if(Y>=30&&!S0){S0=!0,L(`${m.yellow} \u26A0 Tool budget warning: ${Y} tool calls used \u2014 nudging model to wrap up${m.reset}`);let b={role:"user",content:"[SYSTEM] \u26A0 You have used "+Y+" 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."};M.push(b),T.push(b)}let ke=await Promise.all(on.map(b=>Y1(b)));if(Ba){let b=new Set(["read_file","grep","search_files","glob","list_directory","ssh_exec","find_files"]);for(let y of ke)!y.canExecute||!b.has(y.fnName)||(y.canExecute=!1,y.errorResult={role:"tool",content:"BLOCKED: You already have enough evidence to produce the requested summary/document. Write the deliverable now and stop reading more files.",tool_call_id:y.callId})}{let b=en(T,ht()),y=b.percentage,G=ke.some(j=>j.canExecute&&j.fnName==="read_file"&&!j.args?.line_end),U=ke.filter(j=>j.canExecute&&j.fnName==="read_file"&&j.args?.path&&mn(Ps,j.args.path)>=1&&!j.args?.line_start).map(j=>j.args.path.split("/").slice(-2).join("/")),z=U.length>0;if(y>=70&&G&&Da<70||y>=85&&Da<85||z){Da=y;let j=y>=85?"URGENT":"WARNING",ce;z?(j="WARNING",ce=`Full-file read of ${U.join(", ")} already done \u2014 use line_start/line_end for specific sections instead.`):G?ce=`Unbounded read at ${Math.round(y)}% context \u2014 use line_start/line_end to avoid overflow.`:ce="Use targeted reads (line_start/line_end) to save space.";let O={role:"user",content:`[SYSTEM ${j}] Context ${Math.round(y)}% used (${b.used}/${b.limit} tokens). ${ce}`};if(M.push(O),T.push(O),y>=85){let W=z?` (re-read of: ${U.join(", ")})`:"";L(`${m.yellow} \u26A0 Context ${Math.round(y)}% used \u2014 agent warned to use targeted reads${W}${m.reset}`)}}}let Ya=new Map;for(let b of ke){if(!b.canExecute||b.fnName!=="read_file")continue;let y=b.args?.path;if(!y)continue;let G=mn(Ps,y),U=Ya.get(y)||0,z=G+U,K=ks.has(y),j=b.args?.line_start!=null,ce=Ft.get(y)||0,O=ce>0,W=2;if(!K&&z>=Ls){let R=y.split("/").slice(-2).join("/"),H=(Rs.get(y)||0)+1;if(Rs.set(y,H),H===1)L(`${m.red} \u2716 Blocked: "${R}" read ${z}\xD7 \u2014 hard cap (${Ls}) reached${m.reset}`);else if(H===2){L(`${m.red} \u2716 Escalated block: "${R}" \u2014 model ignored BLOCKED, injecting system warning${m.reset}`);let de={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 (${Ls}\xD7). Do NOT attempt to read it again. Use grep_search to find specific content, or proceed with what you already know.`};M.push(de),T.push(de)}b.canExecute=!1,b.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 file already read ${z}\xD7 (hard cap: ${Ls}). You have seen enough of this file. Use grep to find specific content or proceed with what you know.`,tool_call_id:b.callId}}else if(!K&&z>=1&&j)if(O&&ce<=W){let R=y.split("/").slice(-2).join("/");console.log(`${m.cyan} \u21A9 Targeted re-read: "${R}" (line_start=${b.args.line_start}) \u2014 edit recovery #${ce}${m.reset}`),Ft.set(y,ce-1)}else if(O&&ce>W){let R=y.split("/").slice(-2).join("/");L(`${m.red} \u2716 Edit recovery blocked: "${R}" \u2014 ${W} recovery reads already used. Use grep to find the exact line numbers, then retry.${m.reset}`),b.canExecute=!1,b.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 edit recovery budget exhausted (${W} 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:b.callId}}else{let R=parseInt(b.args.line_start,10)||1,H=parseInt(b.args.line_end,10)||R+350,de=Tn.get(y)||[],$e=!1;for(let[se,I]of de){let _e=Math.max(R,se),Te=Math.min(H,I);if(Te>_e){let We=Te-_e,Ve=H-R||1,It=I-se||1,nt=We/It>=.7&&We/Ve<.7,Br=H-R<=vw;if(We>=Ve||!Br&&(We/Ve>=.7||We/It>=.7)){let za=y.split("/").slice(-2).join("/"),hd=`${y}:${R}-${H}`,Ds=(Ra.get(hd)||0)+1;if(Ra.set(hd,Ds),L(nt?`${m.red} \u2716 Blocked superread: "${za}" lines ${R}-${H} subsumes already-read ${se}-${I} \u2014 use line_start=${I+1} to skip known content (block #${Ds})${m.reset}`:`${m.red} \u2716 Blocked duplicate read: "${za}" lines ${R}-${H} (\u226570% overlap with lines ${se}-${I} already in context, block #${Ds})${m.reset}`),Ds>=2){L(`${m.red} \u2716 Escalated range-block: "${za}" lines ${R}-${H} \u2014 model ignored BLOCKED, injecting system warning${m.reset}`);let md={role:"user",content:nt?`[SYSTEM] Read blocked ${Ds}\xD7 for read_file("${y}", lines ${R}-${H}). Lines ${se}-${I} were already read. Use line_start=${I+1} to read only new content, or use grep_search for specific lines.`:`[SYSTEM] Read blocked ${Ds}\xD7 for read_file("${y}", lines ${R}-${H}). Lines ${se}-${I} were already read and will NOT change. Use grep_search to find specific content instead.`};M.push(md),T.push(md)}b.canExecute=!1,b.errorResult={role:"tool",content:nt?`BLOCKED: read_file("${y}", lines ${R}-${H}) re-reads lines ${se}-${I} already in context. Use line_start=${I+1} to read only the new content beyond line ${I}.`:`BLOCKED: read_file("${y}", lines ${R}-${H}) is a duplicate \u2014 lines ${se}-${I} are already in your context (\u226570% overlap). Use grep to find specific content instead of re-reading.`,tool_call_id:b.callId},$e=!0;break}}}if(!$e){let se=de.length,I=2;if(se>=3){let Te=y.split("/").slice(-2).join("/");L(`${m.red} \u2716 Blocked file-scroll: "${Te}" \u2014 ${se} sections already read. Use grep to find specific content.${m.reset}`);let We=mn(ja,y)>=Lr;b.canExecute=!1,b.errorResult={role:"tool",content:We?`BLOCKED: read_file("${y}") denied \u2014 you have already read ${se} 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 ${se} 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:b.callId}}else se>=I&&(b._scrollWarn={sectionCount:se+1,path:y})}}else if(!K&&z>=1){let R=Ft.get(y)||0;if(R>0){let H=y.split("/").slice(-2).join("/");console.log(`${m.cyan} \u21A9 Full re-read: "${H}" \u2014 test-failure recovery (${R} remaining)${m.reset}`);let de=R-1;de<=0?Ft.delete(y):Ft.set(y,de)}else{let H=y.split("/").slice(-2).join("/"),de=(Rs.get(y)||0)+1;if(Rs.set(y,de),de===1)L(`${m.red} \u2716 Blocked unbounded re-read: "${H}" \u2014 already in context. Use line_start/line_end for specific sections.${m.reset}`);else if(de===2){L(`${m.red} \u2716 Escalated block: "${H}" \u2014 model ignored unbounded re-read block, injecting system warning${m.reset}`);let $e={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.`};M.push($e),T.push($e)}b.canExecute=!1,b.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 file already in context (read ${z}\xD7). Use line_start/line_end to read a specific section instead of the full file.`,tool_call_id:b.callId}}}b.canExecute&&Ya.set(y,(Ya.get(y)||0)+1)}if(qn>=3)for(let b of ke)b.canExecute&&(b.fnName!=="read_file"&&b.fnName!=="edit_file"||(L(`${m.red} \u2716 Blocked ${b.fnName} \u2014 ${qn} consecutive file-not-found errors, must search first${m.reset}`),b.canExecute=!1,b.errorResult={role:"tool",content:`BLOCKED: ${qn} 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:b.callId}));for(let b of ke){if(!b.canExecute||b.fnName!=="bash")continue;let y=(b.args?.command||"").trim();if(/^\s*ls(\s+-[a-zA-Z]+)*(\s+\S+)?\s*$/.test(y)&&!/npm|yarn|pnpm|make|git/.test(y)){L(`${m.red} \u2716 Blocked bash ls \u2014 use list_directory tool instead${m.reset}`),b.canExecute=!1,b.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:b.callId};continue}/\bfind\s+[\S.]/.test(y)&&!/git\s|npm\s|yarn\s|-exec\s+\S|-execdir/.test(y)&&(L(`${m.red} \u2716 Blocked bash find \u2014 use glob tool with a pattern instead${m.reset}`),b.canExecute=!1,b.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:b.callId})}for(let b of ke)b.canExecute&&(b.fnName!=="ssh_exec"&&b.fnName!=="bash"||/\bsed\s+-n\b/.test(b.args?.command||"")&&(L(`${m.red} \u2716 Blocked sed -n: use grep -n "pattern" <file> | head -30 instead${m.reset}`),b.canExecute=!1,b.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:b.callId}));for(let b of ke){if(!b.canExecute||b.fnName!=="write_file")continue;let y=b.args?.path,G=b.args?.content||"";if(y)try{let U=require("fs"),z=require("path").resolve(process.cwd(),y);if(U.existsSync(z)){let K=U.statSync(z).size,j=Buffer.byteLength(G,"utf8"),ce=K>0?j/K:1,O=Iu(P),W=Iu(y);if(E0(P)&&(O.includes(W)||O.includes(`./${W}`)))continue;if(ce<.6&&K>200){let H=y.split("/").slice(-2).join("/");console.log(`${m.red} \u2716 write_file shrink guard: "${H}" would shrink to ${Math.round(ce*100)}% of original \u2014 likely context loss${m.reset}`),b.canExecute=!1,b.errorResult={role:"tool",content:`BLOCKED: write_file("${y}") denied \u2014 new content is only ${Math.round(ce*100)}% of current file size (${K} \u2192 ${j} 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:b.callId}}}}catch{}}let ud=new Map;for(let b of ke){if(!b.canExecute||b.fnName!=="grep")continue;let y=b.args?.path;if(!y)continue;let G=ud.get(y)||0,U=mn(ja,y)+G,z=mn(Ps,y)>=1,K=z?Math.min(3,Lr):Lr;if(U>=K){let j=y.split("/").slice(-2).join("/");L(`${m.red} \u2716 Blocked grep: "${j}" grepped ${U}\xD7 with different patterns \u2014 flood threshold exceeded${m.reset}`);let ce=mn(Ps,y),O=ce>=Ls;if(O){let W={role:"user",content:`[SYSTEM] Both read_file and grep are now blocked for "${y}". You have already read ${ce} sections and tried ${U} 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.`};M.push(W),T.push(W),L(`${m.red} \u2716 Deadlock detected: "${j}" \u2014 both read and grep blocked, injecting deadlock-break${m.reset}`)}b.canExecute=!1,b.errorResult={role:"tool",content:O?`BLOCKED: grep("${y}") denied \u2014 ${U} 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.`:z?`BLOCKED: grep("${y}") denied \u2014 file was already read and ${U} grep patterns tried. The content is already in your context; use it instead of searching again.`:`BLOCKED: grep("${y}") denied \u2014 ${U} patterns already tried. Work with the grep results already in your context.`,tool_call_id:b.callId}}b.canExecute&&ud.set(y,G+1)}let Aw=5,dd=new Map;for(let b of ke){if(!b.canExecute||b.fnName!=="ssh_exec")continue;let G=(b.args?.command||"").replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),U=dd.get(G)||0,z=mn(td,G)+U;z>=Aw&&(L(`${m.yellow} \u26A0 Blocked ssh_exec: same command run ${z}\xD7 \u2014 result already in context${m.reset}`),b.canExecute=!1,b.errorResult={role:"tool",content:`BLOCKED: ssh_exec denied \u2014 this command has already run ${z} 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:b.callId}),b.canExecute&&dd.set(G,U+1)}if(Mt){let b=ke.filter(U=>U.canExecute&&U.fnName==="ssh_exec"),y=ke.some(U=>U.canExecute&&U.fnName!=="ssh_exec"),G=X&&he<3;if(b.length>0&&!y&&G&&_a<1)Mt=!1,_a++,Bt=Math.max(0,Eo-2),L(`${m.dim} [dual-block deadlock: SSH storm relaxed \u2014 allowing 1 SSH call (relax ${_a}/1)]${m.reset}`);else for(let U of b)U.canExecute=!1,U.errorResult={role:"tool",content:dt?`BLOCKED: ssh_exec denied \u2014 SSH paused (${Eo}+ calls). Root cause is known (${vt}). 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 (${Eo}+ 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:U.callId}}let Ow=F1(M,["browser_open","browser_screenshot","ssh_exec","service_logs","remote_agent"]);if((X||C)&&!Ow&&he<3&&!Mt)for(let b of ke){if(!b.canExecute||!["bash","read_file","find_files","list_directory","search_files","glob","grep"].includes(b.fnName))continue;he++;{let U=ht(),{messages:z}=hn(T,U);T=z}let y=B?.matchedName?`${B.matchedName} (${B.matchedProfile?.host||"server"})`:B?.url,G=B?.shouldPreferSsh?`BLOCKED: ${b.fnName} denied \u2014 this looks like a live app/server issue. Inspect ${B?.url} with browser_open or use ssh_exec on ${y} first, then return to local code if needed.`:`BLOCKED: ${b.fnName} denied \u2014 this looks like a live app issue. Inspect ${B?.url} with browser_open first, then return to local code if needed.`;L(`${m.yellow} \u26A0 Runtime guard: blocking local ${b.fnName} \u2014 inspect the live app first${m.reset}`),b.canExecute=!1,b.errorResult={role:"tool",content:G,tool_call_id:b.callId};break}if(!we&&Ht&&Ut&&Yt>=1){let b=["read_file","grep","search_files","glob","list_directory","find_files"];for(let y of ke)y.canExecute&&b.includes(y.fnName)&&(L(`${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(vs>=0){let b=ke.filter(y=>y.canExecute).length;if(b>0&&(vs-=b,vs<0))if(!ka&&Z.size>xa){ka=!0,vs=5,L(`${m.green} \u2713 Post-wipe progress detected (${Z.size-xa} 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."};M.push(y),T.push(y)}else{L(`${m.red} \u2716 Post-wipe tool budget exhausted \u2014 blocking all tool calls${m.reset}`);for(let G of ke)G.canExecute&&(G.canExecute=!1,G.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:G.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."};M.push(y),T.push(y)}}let Nw=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 b of ke){if(!b.canExecute||Nw.has(b.fnName))continue;let y=JSON.stringify(b.args||{}),G=`${b.fnName}|${y}`,U=mn(Au,G);U>=2?(L(`${m.red} \u2716 Blocked duplicate: ${b.fnName}(${y.substring(0,80)}) \u2014 called ${U+1}\xD7 with identical args${m.reset}`),b.canExecute=!1,b.errorResult={role:"tool",content:`BLOCKED: ${b.fnName}() with these exact arguments has already been called ${U}\xD7 \u2014 the result is already in your context. Use the existing output instead of repeating the same call.`,tool_call_id:b.callId}):U===1&&L(`${m.yellow} \u26A0 Duplicate tool call: ${b.fnName}(${y.substring(0,80)}) \u2014 2nd call with identical args${m.reset}`),xs(Au,G)}{let b=new Set;for(let y of ke){if(!y.canExecute||!["edit_file","patch_file"].includes(y.fnName))continue;let G=y.args?.path;G&&(b.has(G)?(y.canExecute=!1,y.errorResult={role:"tool",content:`BLOCKED: "${G}" is already being edited in this batch. Finish one edit first, then re-read the changed section before the next one.`,tool_call_id:y.callId},L(`${m.yellow} \u26A0 Map-first gate: blocked duplicate same-batch edit of "${G.split("/").slice(-1)[0]}"${m.reset}`)):Os.has(G)&&!ks.has(G)?(y.canExecute=!1,y.errorResult={role:"tool",content:`BLOCKED: "${G}" 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},L(`${m.yellow} \u26A0 Map-first gate: blocked re-edit of "${G.split("/").slice(-1)[0]}" \u2014 re-read required${m.reset}`)):b.add(G))}}let Ro=l?{skipSpinner:!0,skipSummaries:!0}:{},Mw=ke.some(b=>b.fnName==="ask_user"),fd=!Ro.skipSummaries&&!ye,zt=null,js=null;if(fd&&!Mw){if(ye=!0,Ro.skipSpinner=!0,process.stdout.isTTY){global._nexFooter&&(js=Math.min(global._nexFooter._lastOutputRow+1,global._nexFooter._scrollEnd));let b=gr(ke,Y,!1,0),y=gr(ke,Y,!1);process.stdout.write(`${Y>1?`
1467
1470
  `:""}${b}`),yo=y,wo=Date.now(),zt={start:Date.now(),frame:0,timer:null}}else if(!wn){let b=gr(ke,Y,!1);_u(b,yo,wo)||(process.stdout.write(`${Y>1?`
1468
1471
  `:""}${b}
1469
- `),yo=b,wo=Date.now())}}else dd&&(ye=!0,Ro.skipSpinner=!0);l&&l._paused&&l.resume(),zt&&process.stdout.isTTY&&(zt.timer=setInterval(()=>{zt.frame++;let b=Math.round((Date.now()-zt.start)/1e3),y=b>=1?` ${m.dim}[${b}s]${m.reset}`:"",G=`${gr(ke,Y,!1,zt.frame)}${y}`;js!==null?process.stdout.write(`\x1B[${js};1H\x1B[2K${G}`):process.stdout.write(`\r\x1B[2K${G}`)},120));let{results:tt,summaries:Pw}=await X1(ke,!0,{...Ro,skipSummaries:!0});if(Ha){let b={role:"user",content:"[SYSTEM] ask_user is exclusive. Wait for the user's answer before making any other tool calls."};M.push(b),T.push(b)}if(zt){zt.timer&&(clearInterval(zt.timer),zt.timer=null);let b=gr(ke,Y,!1);_u(b,yo,wo)||(js!==null?process.stdout.write(`\x1B[${js};1H\x1B[2K${b}
1472
+ `),yo=b,wo=Date.now())}}else fd&&(ye=!0,Ro.skipSpinner=!0);l&&l._paused&&l.resume(),zt&&process.stdout.isTTY&&(zt.timer=setInterval(()=>{zt.frame++;let b=Math.round((Date.now()-zt.start)/1e3),y=b>=1?` ${m.dim}[${b}s]${m.reset}`:"",G=`${gr(ke,Y,!1,zt.frame)}${y}`;js!==null?process.stdout.write(`\x1B[${js};1H\x1B[2K${G}`):process.stdout.write(`\r\x1B[2K${G}`)},120));let{results:tt,summaries:Pw}=await X1(ke,!0,{...Ro,skipSummaries:!0});if(Ha){let b={role:"user",content:"[SYSTEM] ask_user is exclusive. Wait for the user's answer before making any other tool calls."};M.push(b),T.push(b)}if(zt){zt.timer&&(clearInterval(zt.timer),zt.timer=null);let b=gr(ke,Y,!1);_u(b,yo,wo)||(js!==null?process.stdout.write(`\x1B[${js};1H\x1B[2K${b}
1470
1473
  `):process.stdout.write(`\r\x1B[2K${b}
1471
- `),yo=b,wo=Date.now()),js=null,zt=null}if(!Ro.skipSummaries){let b=Pw.filter((U,z)=>!(ke[z]&&ke[z].fnName==="ask_user"));for(let U of b)_u(U,Tu,Ru)||(console.log(U),Tu=U,Ru=Date.now());let y=ke.filter(U=>U&&U.fnName!=="ask_user").map(U=>U.fnName),G=aw.record(0,y,Se,Z);G&&v1(G)}for(let b of ke){if(b.canExecute||!b.errorResult)continue;let y=typeof b.errorResult.content=="string"?b.errorResult.content:"";if((y.startsWith("BLOCKED:")||y.startsWith("PLAN MODE:")||y.startsWith("PLAN PHASE:"))&&(Wn++,Wn>=td)){L(`${m.red} \u2716 Loop abort: ${Wn} consecutive blocked calls (pre-execution) \u2014 model not heeding BLOCKED messages${m.reset}`),l&&(l.stop(),l=null),u(null),je(Y,re,Z,Se,Pe,{suppressHint:!0}),Ne(M);return}}let Ga=!1;for(let b=0;b<ke.length;b++){let y=ke[b];if(!y.canExecute)continue;let G=tt[b].content,U=G.split(`
1474
+ `),yo=b,wo=Date.now()),js=null,zt=null}if(!Ro.skipSummaries){let b=Pw.filter((U,z)=>!(ke[z]&&ke[z].fnName==="ask_user"));for(let U of b)_u(U,Tu,Ru)||(console.log(U),Tu=U,Ru=Date.now());let y=ke.filter(U=>U&&U.fnName!=="ask_user").map(U=>U.fnName),G=aw.record(0,y,Se,Z);G&&v1(G)}for(let b of ke){if(b.canExecute||!b.errorResult)continue;let y=typeof b.errorResult.content=="string"?b.errorResult.content:"";if((y.startsWith("BLOCKED:")||y.startsWith("PLAN MODE:")||y.startsWith("PLAN PHASE:"))&&(Wn++,Wn>=nd)){L(`${m.red} \u2716 Loop abort: ${Wn} consecutive blocked calls (pre-execution) \u2014 model not heeding BLOCKED messages${m.reset}`),l&&(l.stop(),l=null),u(null),je(Y,re,Z,Se,Pe,{suppressHint:!0}),Ne(M);return}}let Ga=!1;for(let b=0;b<ke.length;b++){let y=ke[b];if(!y.canExecute)continue;let G=tt[b].content,U=G.split(`
1472
1475
  `)[0],z=!U.startsWith("ERROR")&&!U.startsWith("CANCELLED")&&!U.startsWith("Command failed")&&!U.startsWith("EXIT");if(!z&&(y.fnName==="edit_file"||y.fnName==="patch_file")&&y.args?.path&&U.includes("old_text not found")){let O=Ft.get(y.args.path)||0;Ft.set(y.args.path,O+1)}if(!z&&y.fnName==="bash"&&Ar.size>0){let O=(y.args?.command||"").toLowerCase();if(/\b(test|jest|vitest|pytest|mocha|tsc|build|lint|eslint|check)\b/.test(O))for(let[R]of Ar)Ft.has(R)||(Ft.set(R,1),L(`${m.cyan} \u21A9 Test failure \u2014 queuing recovery re-read: "${R.split("/").pop()}"${m.reset}`))}if(!z&&(y.fnName==="read_file"||y.fnName==="edit_file")&&/file not found|does not exist|ENOENT/i.test(U)){if(qn++,qn>=2){L(`${m.yellow} \u26A0 File-not-found streak: ${qn} consecutive misses \u2014 forcing search${m.reset}`);let O={role:"user",content:`[SYSTEM] ${qn} 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.`};M.push(O),T.push(O)}}else z&&(y.fnName==="read_file"||y.fnName==="edit_file"||y.fnName==="search_files"||y.fnName==="glob_files")&&(qn=0);if(z&&y.fnName==="write_file"&&y.args?.path){let O=y.args.path.split("/").pop(),W=y.args.path.includes("/tests/")||y.args.path.includes("\\tests\\");if(/^(test_|demo_|temp_|tmp_|scratch_)/.test(O)&&!W){L(`${m.yellow} \u26A0 Temp file: "${O}" \u2014 delete with bash rm when done to keep the workspace clean${m.reset}`);let H={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.`};M.push(H),T.push(H)}}if(z&&["write_file","edit_file","patch_file"].includes(y.fnName)&&y.args&&y.args.path){Ft.delete(y.args.path),Z.add(y.args.path);for(let R of As)!R.done&&y.args.path.endsWith(R.file.split("/").pop())&&(R.done=!0,L(`${m.green} \u2713 TODO done: ${R.file}${m.reset}`));let O=xs(cw,y.args.path),W=y.args.path.split("/").slice(-2).join("/");if(O===lw){L(`${m.yellow} \u26A0 Loop warning: "${W}" edited ${O}\xD7 \u2014 possible edit loop${m.reset}`);let R={role:"user",content:`[SYSTEM WARNING] "${y.args.path}" edited ${O}\xD7. One more edit max, then move on.`};M.push(R),T.push(R)}else if(O>=uw){L(`${m.red} \u2716 Loop abort: "${W}" edited ${O}\xD7 \u2014 aborting to prevent runaway loop${m.reset}`),l&&(l.stop(),l=null),u(null),je(Y,re,Z,Se,Pe,{suppressHint:!0}),Ne(M);return}we&&Re==="verify"||(xo=!0,ko=0,Ga=!0)}if(z&&y.canExecute&&we&&(Fn=0),z&&y.canExecute&&!(we&&Re==="plan")){let O=["read_file","grep","search_files","glob","list_directory","ssh_exec","find_files"];if(["write_file","edit_file","patch_file"].includes(y.fnName)){Wt=0,Ht=!1,tn=0,Yt++;let I=y.args?.path||y.args?.file_path;I&&(y.fnName==="write_file"?(ks.add(I),yn.delete(I),Tn.delete(I),Os.delete(I)):(ks.delete(I),bu(yn,I,1),Tn.delete(I),Os.add(I)))}else if(O.includes(y.fnName)){if(Wt++,Ht&&tn++,we&&Re==="implement"&&y.fnName==="read_file"){let I=y.args?.path||y.args?.file_path||"";if(I&&ks.has(I)){let _e={role:"user",content:`[SYSTEM] You just created and re-read "${I}". Do NOT analyze further. Apply the requested refactor now with edit_file.`};M.push(_e),T.push(_e),L(`${m.yellow} \u26A0 Fresh-write nudge: ${I} \u2014 refactor directly after re-read${m.reset}`)}}if(we&&Re==="implement"&&y.fnName==="read_file"&&As.length>0){let I=y.args?.path||y.args?.file_path||"",_e=As.find(Te=>!Te.done&&I.endsWith(Te.file.split("/").pop()));if(_e){let Te={role:"user",content:`[TODO OBSERVER] You already analyzed "${_e.file}" in the plan phase. Action: ${_e.action}
1473
- Do NOT re-read \u2014 apply the edit directly with edit_file.`};M.push(Te),T.push(Te),L(`${m.yellow} \u26A0 TODO nudge: ${_e.file} \u2014 already analyzed, edit directly${m.reset}`)}}we&&Re==="implement"&&xo&&ko<1&&(ko++,Ga=!0)}we&&Re==="verify"&&$o++,z&&oC(y)&&(xo=!1,ko=0);let R=o.postEditCap,H=we&&Re==="implement"?Math.min(nd,10):nd,de=dt?8:Ir?Yt>0?4:6:Ut?Yt>0?6:10:Yt>0?R:H,$e=6,se=!we&&Ht&&(dt&&tn>=$e||Ut&&Yt>=3&&tn>=$e||tn>=$e);if(wr<2&&!Ht&&Wt>=3&&Z.size===0){let I=parseInt(process.env.NEX_TASK_TIMEOUT_MS,10)||0,_e=Date.now()-Pe,Te=wr===0?.4:.65;if(I>0&&_e>I*Te){wr++;let We=Math.round(_e/6e4),Ve=Math.round(_e/I*100);L(`${m.yellow} \u26A0 Time nudge #${wr}: ${We}m elapsed (${Ve}%), ${Wt} reads, 0 edits${m.reset}`);let It={role:"user",content:wr===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.`};M.push(It),T.push(It)}}if(se&&O.includes(y.fnName)){let I=dt?`root cause already identified (${vt})`:tn>=$e?`${Wt} consecutive reads without an edit`:`${Yt} file edit(s) already made`;L(`${m.red} \u2716 Blocked read-only tool: cap fired, ${I}${m.reset}`),y.canExecute=!1,y.errorResult={role:"tool",content:dt?`BLOCKED: root cause already identified (${vt}). Use edit_file to fix the issue \u2014 do not read more files.`:Ut?"BLOCKED: files already written \u2014 continue with write_file or edit_file to finish the remaining tasks. Do not read more files.":tn>=$e?`BLOCKED: You have read ${Wt} 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: ${Yt} 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(Wt>=de&&!Ht){if(Ht=!0,Ir&&(Ba=!0),L(`${m.yellow} \u26A0 Investigation cap: ${Wt} read-only calls without an edit \u2014 forcing implementation${m.reset}`),we&&Re==="plan"){let Te=[...T].reverse().find(It=>It.role==="assistant"),We=typeof Te?.content=="string"?Te.content:"",Ve=await $r("implement",We);Ve&&(M.push(Ve),T.push(Ve),Ke=0,Et=_s("implement"))}let I;dt?I=`[SYSTEM] Root cause was already identified (${vt}). Edit the file now \u2014 do not read more files.`:Ir?I="[SYSTEM] You have enough evidence to write the requested summary/document now. Use write_file or edit_file to produce the deliverable, and stop reading more files unless a required section is still unsupported.":Mt?I="[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.":I="[SYSTEM] You have read enough files. Now implement your fix using edit_file.";let _e={role:"user",content:I};M.push(_e),T.push(_e)}}if((y.fnName==="bash"||y.fnName==="ssh_exec")&&y.args&&y.args.command){let O=y.args.command.replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),W=xs(ed,O);if(W===dw){L(`${m.yellow} \u26A0 Loop warning: same bash command run ${W}\xD7 \u2014 possible debug loop${m.reset}`);let R={role:"user",content:`[SYSTEM WARNING] Same bash command ${W}\xD7. Debug loop detected \u2014 try a different approach.`};M.push(R),T.push(R)}else if(W>=fw){L(`${m.red} \u2716 Loop abort: same bash command run ${W}\xD7 \u2014 aborting runaway debug loop${m.reset}`),l&&(l.stop(),l=null),u(null),je(Y,re,Z,Se,Pe,{suppressHint:!0}),Ne(M);return}}if(y.fnName==="ssh_exec"){Bt++;{let R=(tt[b]?.content??"").split(`
1476
+ Do NOT re-read \u2014 apply the edit directly with edit_file.`};M.push(Te),T.push(Te),L(`${m.yellow} \u26A0 TODO nudge: ${_e.file} \u2014 already analyzed, edit directly${m.reset}`)}}we&&Re==="implement"&&xo&&ko<1&&(ko++,Ga=!0)}we&&Re==="verify"&&$o++,z&&rC(y)&&(xo=!1,ko=0);let R=o.postEditCap,H=we&&Re==="implement"?Math.min(sd,10):sd,de=dt?8:Ir?Yt>0?4:6:Ut?Yt>0?6:10:Yt>0?R:H,$e=6,se=!we&&Ht&&(dt&&tn>=$e||Ut&&Yt>=3&&tn>=$e||tn>=$e);if(wr<2&&!Ht&&Wt>=3&&Z.size===0){let I=parseInt(process.env.NEX_TASK_TIMEOUT_MS,10)||0,_e=Date.now()-Pe,Te=wr===0?.4:.65;if(I>0&&_e>I*Te){wr++;let We=Math.round(_e/6e4),Ve=Math.round(_e/I*100);L(`${m.yellow} \u26A0 Time nudge #${wr}: ${We}m elapsed (${Ve}%), ${Wt} reads, 0 edits${m.reset}`);let It={role:"user",content:wr===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.`};M.push(It),T.push(It)}}if(se&&O.includes(y.fnName)){let I=dt?`root cause already identified (${vt})`:tn>=$e?`${Wt} consecutive reads without an edit`:`${Yt} file edit(s) already made`;L(`${m.red} \u2716 Blocked read-only tool: cap fired, ${I}${m.reset}`),y.canExecute=!1,y.errorResult={role:"tool",content:dt?`BLOCKED: root cause already identified (${vt}). Use edit_file to fix the issue \u2014 do not read more files.`:Ut?"BLOCKED: files already written \u2014 continue with write_file or edit_file to finish the remaining tasks. Do not read more files.":tn>=$e?`BLOCKED: You have read ${Wt} 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: ${Yt} 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(Wt>=de&&!Ht){if(Ht=!0,Ir&&(Ba=!0),L(`${m.yellow} \u26A0 Investigation cap: ${Wt} read-only calls without an edit \u2014 forcing implementation${m.reset}`),we&&Re==="plan"){let Te=[...T].reverse().find(It=>It.role==="assistant"),We=typeof Te?.content=="string"?Te.content:"",Ve=await $r("implement",We);Ve&&(M.push(Ve),T.push(Ve),Ke=0,Et=_s("implement"))}let I;dt?I=`[SYSTEM] Root cause was already identified (${vt}). Edit the file now \u2014 do not read more files.`:Ir?I="[SYSTEM] You have enough evidence to write the requested summary/document now. Use write_file or edit_file to produce the deliverable, and stop reading more files unless a required section is still unsupported.":Mt?I="[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.":I="[SYSTEM] You have read enough files. Now implement your fix using edit_file.";let _e={role:"user",content:I};M.push(_e),T.push(_e)}}if((y.fnName==="bash"||y.fnName==="ssh_exec")&&y.args&&y.args.command){let O=y.args.command.replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),W=xs(td,O);if(W===dw){L(`${m.yellow} \u26A0 Loop warning: same bash command run ${W}\xD7 \u2014 possible debug loop${m.reset}`);let R={role:"user",content:`[SYSTEM WARNING] Same bash command ${W}\xD7. Debug loop detected \u2014 try a different approach.`};M.push(R),T.push(R)}else if(W>=fw){L(`${m.red} \u2716 Loop abort: same bash command run ${W}\xD7 \u2014 aborting runaway debug loop${m.reset}`),l&&(l.stop(),l=null),u(null),je(Y,re,Z,Se,Pe,{suppressHint:!0}),Ne(M);return}}if(y.fnName==="ssh_exec"){Bt++;{let R=(tt[b]?.content??"").split(`
1474
1477
  `).map(H=>H.trim()).find(H=>H.length>0&&!H.startsWith("**")&&(H.startsWith("EXIT")||/^[\w./-]+:\s/.test(H)||H.startsWith("bash:")||H.startsWith("sh:")))??"";if(R){if(R===va?Ss++:(va=R,Ss=1),Ss===3&&!Mt){L(`${m.yellow} \u26A0 SSH repeated-error: "${R.slice(0,60)}" returned ${Ss}\xD7 \u2014 nudging to change approach${m.reset}`);let H={role:"user",content:`[SYSTEM WARNING] The last ${Ss} SSH commands all failed with the same error: "${R}". 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).`};M.push(H),T.push(H)}}else va="",Ss=0}if(Bt>=Cw){L(`${m.red} \u2716 SSH storm abort: ${Bt} consecutive ssh_exec calls \u2014 aborting${m.reset}`),l&&(l.stop(),l=null),u(null),je(Y,re,Z,Se,Pe,{suppressHint:!0}),Ne(M);return}else if(Bt===Eo){{let R=ht(),{messages:H}=hn(T,R);T=H}Mt=!0,pa++,L(`${m.yellow} \u26A0 SSH storm warning (#${pa}): ${Bt} consecutive ssh_exec calls \u2014 blocking further SSH${m.reset}`);let W={role:"user",content:dt?`[SYSTEM WARNING] ${Bt} consecutive SSH calls. Root cause identified (${vt}). Read the file that needs fixing, then edit it.`:`[SYSTEM WARNING] ${Bt} 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.`};M.push(W),T.push(W)}}else y.canExecute&&(Bt=0);if(y.fnName==="bash"&&y.canExecute){let R=(tt[b]?.content??"").split(`
1475
1478
  `).map(H=>H.trim()).find(H=>H.length>0&&(H.startsWith("EXIT")||/^[\w./-]+:\s/.test(H)||H.startsWith("bash:")||H.startsWith("sh:")))??"";if(R){if(R===Sa?Es++:(Sa=R,Es=1),Es===3){L(`${m.yellow} \u26A0 Bash repeated-error: "${R.slice(0,60)}" returned ${Es}\xD7 \u2014 nudging to change approach${m.reset}`);let H={role:"user",content:`[SYSTEM WARNING] The last ${Es} bash commands all failed with the same error: "${R}". 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).`};M.push(H),T.push(H)}}else Sa="",Es=0}if(y.fnName==="bash"&&y.canExecute&&!$u&&y.args?.command){let O=tt[b]?.content??"";if(/git\s+commit\b/.test(y.args.command)&&!O.startsWith("EXIT")&&!O.startsWith("ERROR")&&(/\[\S+\s+[a-f0-9]+\]/.test(O)||O.includes("files changed")||O.includes("file changed")||O.includes("insertions(+)")||O.includes("create mode"))){$u=!0,br=0,L(`${m.green} \u2713 Git commit detected \u2014 post-commit verification cap active (max 2 git status/diff/log)${m.reset}`);let H={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."};M.push(H),T.push(H)}}if($u&&y.fnName==="bash"&&y.args?.command&&/git\s+(status|diff|log|show)\b/.test(y.args.command)&&(br++,br>2)){L(`${m.yellow} \u26A0 Post-commit git verification blocked (call ${br})${m.reset}`);let W={role:"user",content:"[SYSTEM] \u26A0 STOP: You already ran "+(br-1)+" git verification commands after committing. The commit is confirmed. Write your final summary NOW and do not make any more tool calls."};M.push(W),T.push(W)}if(z&&y.fnName==="grep"&&G&&!G.startsWith("(no matches)")){let O=G.split(`
1476
1479
  `);for(let W of O){let R=W.indexOf(":");if(R>0){let H=W.substring(0,R);H.startsWith("/")&&!H.includes(" ")&&Rr.add(H)}else W.startsWith("/")&&!W.includes(" ")&&Rr.add(W.trim())}}{let O=["grep","search_files","glob","glob_files"].includes(y.fnName);if(O&&z&&G&&(G.startsWith("(no matches)")||G.trim()===""||/^No matches found/.test(G.trim())||/^\(0 results\)/.test(G.trim()))){if(Ia++,Ia===3){L(`${m.yellow} \u26A0 3 consecutive empty local searches \u2014 injecting SSH pivot hint${m.reset}`);let R={role:"user",content:"[SYSTEM NOTE] 3 consecutive local searches returned no results. The target files may be on a remote server. If you have an SSH profile configured for this project's server, use ssh_exec to search there (e.g. ssh_exec with grep). Do not keep searching locally if the code does not exist on this machine."};M.push(R),T.push(R)}}else O&&z&&G&&G.trim().length>0&&(Ia=0)}if(z&&y.fnName==="grep"&&y.args&&y.args.pattern){let O=`${y.args.pattern}|${y.args.path||""}`,W=xs(pw,O);if(W===hw){L(`${m.yellow} \u26A0 Loop warning: grep pattern "${y.args.pattern.slice(0,40)}" run ${W}\xD7 \u2014 possible search loop${m.reset}`);let R={role:"user",content:`[SYSTEM WARNING] Same grep pattern ${W}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};M.push(R),T.push(R)}else if(W>=mw){L(`${m.red} \u2716 Loop abort: grep pattern run ${W}\xD7 \u2014 aborting runaway search loop${m.reset}`),l&&(l.stop(),l=null),u(null),je(Y,re,Z,Se,Pe,{suppressHint:!0}),Ne(M);return}if(y.args.path){let R=xs(ja,y.args.path),H=mn(Ps,y.args.path)>=1;if(R===(H?1:gw)){let $e=y.args.path.split("/").slice(-2).join("/");L(`${m.yellow} \u26A0 Loop warning: "${$e}" grepped ${R}\xD7 with different patterns \u2014 context flood risk${m.reset}`);let se={role:"user",content:H?`[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 ${R}\xD7 \u2014 use the search results already in context instead of searching again.`};M.push(se),T.push(se)}}}if(z&&(y.fnName==="glob"||y.fnName==="glob_files"||y.fnName==="search_files")&&y.args){if(G&&!G.startsWith("(no matches)")){let H=G.split(`
1477
- `);for(let de of H)(de.startsWith("/")&&!de.includes(" ")||!de.includes(":")&&!de.startsWith("["))&&Cr.add(de.trim())}let O=y.args.pattern||y.args.query||y.args.path||"",W=xs(yw,O);if(W===ww){L(`${m.yellow} \u26A0 Loop warning: glob pattern "${O.slice(0,40)}" run ${W}\xD7 \u2014 possible search loop${m.reset}`);let H={role:"user",content:`[SYSTEM WARNING] Same glob/search pattern ${W}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};M.push(H),T.push(H)}else if(W>=bw){L(`${m.red} \u2716 Loop abort: glob pattern run ${W}\xD7 \u2014 aborting runaway search loop${m.reset}`),l&&(l.stop(),l=null),u(null),je(Y,re,Z,Se,Pe,{suppressHint:!0}),Ne(M);return}let R=O.replace(/\*+/g," ").replace(/[{}()\[\],.\/\\]/g," ").split(/\s+/).filter(H=>H.length>=4&&!/^\.(js|ts|py|json|md|yaml|yml|txt|css|html|sh)$/.test(H));for(let H of R){let de=H.toLowerCase();wa.has(de)||wa.set(de,new Set);let $e=wa.get(de);if($e.add(O),$e.size===_w){L(`${m.red} \u2716 Glob core-term block: ${$e.size} different patterns all searching for "${de}" \u2014 search loop${m.reset}`);let se={role:"user",content:`[SYSTEM WARNING] You have searched for "${de}" using ${$e.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.`};M.push(se),T.push(se)}else if($e.size===$w){L(`${m.yellow} \u26A0 Glob core-term warning: ${$e.size} different patterns searching for "${de}"${m.reset}`);let se={role:"user",content:`[SYSTEM WARNING] ${$e.size} different glob patterns all target "${de}". If previous searches returned no results, the file probably does not exist \u2014 stop searching and proceed with available information.`};M.push(se),T.push(se)}}}let K=(y.args?.command||y.args?.cmd||y.args?.script||"").toLowerCase(),j=/\b(health|healthcheck|health-check|status|check|ping|validate|alive|ready)\b/.test(K)||/\/(health|status|ping|ready|alive)\b/.test(K);if(z&&(y.fnName==="bash"||y.fnName==="ssh_exec")&&j&&G.includes('"valid":true')){{let W=ht();if(en(T,W).percentage>=60){let{messages:H,tokensRemoved:de}=hn(T,W);de>0&&(T=H,console.log(`${m.dim} [pre-stop-compress \u2014 ~${de} tokens freed before STOP injection, now ${Math.round(en(T,W).percentage)}%]${m.reset}`))}}let O={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.'};M.push(O),T.push(O),console.log(`${m.cyan} \u2713 Health-check stop signal detected \u2014 injecting STOP instruction${m.reset}`)}if(z&&(y.fnName==="bash"||y.fnName==="ssh_exec")&&K&&/\bsed\s+-[ie]\b|\btee\b|\bcp\b|\bmv\b|\bpatch\b|\bdd\b|>\s*\S|\becho\b.*>|\bcat\b.*>|\bprintf\b.*>|\bpython[23]?\b.*open\b.*['"'w]|\bnpm\b.*run\b|\byarn\b.*run\b/.test(K)&&(Ms++,L(`${m.dim} [bash write detected: _bashModifiedFiles=${Ms}]${m.reset}`)),G.startsWith("BLOCKED:")){if(Wn++,Wn>=td){L(`${m.red} \u2716 Loop abort: ${Wn} consecutive blocked calls \u2014 model not heeding BLOCKED messages${m.reset}`),l&&(l.stop(),l=null),u(null),je(Y,re,Z,Se,Pe,{suppressHint:!0}),Ne(M);return}}else Wn=0;if(z)Un=0,Fa=!0;else if(Un++,Un===Sw){L(`${m.yellow} \u26A0 Loop warning: ${Un} consecutive tool errors \u2014 possible stuck loop${m.reset}`);let O={role:"user",content:`[SYSTEM WARNING] ${Un} consecutive errors. Stuck loop \u2014 try fundamentally different approach or declare done.`};M.push(O),T.push(O)}else if(Un>=Ew){L(`${m.red} \u2716 Loop abort: ${Un} consecutive errors \u2014 aborting stuck loop${m.reset}`),l&&(l.stop(),l=null),u(null),je(Y,re,Z,Se,Pe,{suppressHint:!0}),Ne(M);return}if(z&&y.fnName==="read_file"&&y.args&&y.args.path){Se.add(y.args.path),ks.delete(y.args.path),Os.delete(y.args.path);let O=xs(Ps,y.args.path);{let de=y.args.line_start!=null&&parseInt(y.args.line_start,10)||1,$e=y.args.line_start!=null?parseInt(y.args.line_end,10)||de+350:350;Tn.has(y.args.path)||Tn.set(y.args.path,[]),Tn.get(y.args.path).push([de,$e])}if(y._scrollWarn){let{sectionCount:de,path:$e}=y._scrollWarn,se={role:"user",content:`[SYSTEM WARNING] "${$e}" \u2014 you have now read ${de} 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.`};M.push(se),T.push(se),L(`${m.yellow} \u26A0 Scroll warning: "${$e.split("/").slice(-2).join("/")}" \u2014 ${de} sections read \u2014 use grep instead${m.reset}`)}let W=y.args.path.split("/").slice(-2).join("/"),R=!y.args?.line_start&&!y.args?.line_end,H=we&&Re==="plan";if(!H&&R&&O===xw){{let $e=ht();if(en(T,$e).percentage>=60){let{messages:I}=hn(T,$e);T=I}}L(`${m.yellow} \u26A0 Loop warning: "${W}" read unbounded ${O}\xD7 \u2014 use line_start/line_end${m.reset}`);let de={role:"user",content:`[SYSTEM WARNING] "${y.args.path}" read ${O}\xD7 without line ranges. Use line_start/line_end to read specific sections \u2014 do not re-read the full file.`};M.push(de),T.push(de)}else if(!H&&R&&O>=kw){L(`${m.red} \u2716 Loop abort: "${W}" read unbounded ${O}\xD7 \u2014 aborting runaway read loop${m.reset}`),l&&(l.stop(),l=null),u(null),je(Y,re,Z,Se,Pe,{suppressHint:!0}),Ne(M);return}}if(y.fnName==="spawn_agents"){let O=(G.match(/\bStatus: done\b/g)||[]).length;if((G.match(/\bStatus: truncated\b/g)||[]).length>0&&O===0){if(Hn++,Hn===Tw){L(`${m.yellow} \u26A0 Swarm warning: all sub-agents hit iteration limit ${Hn}\xD7 in a row${m.reset}`);let R={role:"user",content:`[SYSTEM WARNING] Sub-agents truncated ${Hn}\xD7 in a row. Stop spawning \u2014 try different approach or report findings.`};M.push(R),T.push(R)}else if(Hn>=Rw){console.log(`${m.red} \u2716 Swarm abort: all sub-agents hit iteration limit ${Hn}\xD7 \u2014 aborting stuck swarm${m.reset}`),l&&(l.stop(),l=null),u(null),je(Y,re,Z,Se,Pe,{suppressHint:!0}),Ne(M);return}}else O>0&&(Hn=0)}}if(Ga&&xo&&!(we&&Re==="verify")){let b=await Fu(Z),y=await Aa(Z),G={role:"user",content:sC(Z,b,y)};M.push(G),T.push(G),L(`${m.cyan} \u21B3 Post-edit verify prompt injected (${b.length} checks, ${y.length} tests)${m.reset}`)}{let y=tt.reduce((G,U)=>G+(typeof U.content=="string"?U.content.length:0),0);if(y>2e5){let G=tt.map((U,z)=>({i:z,len:typeof U.content=="string"?U.content.length:0})).sort((U,z)=>z.len-U.len);for(let{i:U,len:z}of G){if(y<=2e5)break;let K=y-2e5,j=Math.max(z-K,500);j<z&&typeof tt[U].content=="string"&&(tt[U]={...tt[U],content:tt[U].content.substring(0,j)+`
1478
- ...(truncated ${z-j} chars \u2014 per-message budget)`},y-=z-j)}}}for(let b of tt)M.push(b),T.push(b);let Lw=Ir&&ke.some((b,y)=>{if(!b||!["write_file","edit_file","patch_file"].includes(b.fnName))return!1;let G=b.args?.path||b.args?.file_path;return VR(G)&&typeof tt[y]?.content=="string"&&!tt[y].content.startsWith("ERROR")&&!tt[y].content.startsWith("BLOCKED:")});if(Ts()&&!n.skillLoop&&Ba&&Lw){L(`${m.green} \u2713 Synthesis deliverable exit: text deliverable written after evidence threshold reached${m.reset}`),je(Y,re,Z,Se,Pe),Ne(M);break e}if(ha(M,T),!dt)for(let b=0;b<tt.length;b++){if(!ke[b]||ke[b].fnName!=="ssh_exec")continue;let y=tt[b];if(!y||typeof y.content!="string")continue;let G=wu(y.content);if(G){dt=!0,vt=G.slice(0,120),Wt=0,Ht=!1,tn=0,L(`${m.yellow} \u26A1 Root cause detected: ${vt} \u2014 fix phase (read budget: 3)${m.reset}`);let U={role:"user",content:`[SYSTEM] Root cause identified: ${vt}. Read only the file that needs fixing, then edit it. Do not read other files.`};M.push(U),T.push(U);break}}for(let b=0;b<tt.length;b++){let y=ke[b];if(!y)continue;let G=typeof tt[b]?.content=="string"?tt[b].content:"";if(y.fnName==="create_task"){let U=G.match(/Task #(\d+) created/),z=typeof y.args?.subject=="string"?y.args.subject:"";U&&z&&Or.set(U[1],z)}else if((y.fnName==="write_file"||y.fnName==="edit_file")&&!G.startsWith("BLOCKED:")&&G.trim().length>0){let z=(typeof y.args?.path=="string"?y.args.path:typeof y.args?.file_path=="string"?y.args.file_path:"").split("/").pop().toLowerCase(),K=z.split(/[._\-/]/).filter(j=>j.length>2);for(let[j,ce]of Or){if(Nr.has(j))continue;let O=ce.toLowerCase().split(/\W+/).filter(R=>R.length>3);K.filter(R=>O.some(H=>H.includes(R)||R.includes(H))).length>=1&&(Nr.add(j),L(`${m.green} \u2714 Auto-matched task #${j} to ${z}: ${ce.slice(0,60)}${m.reset}`))}}}{let b=ht();if(en(T,b).percentage>=78){let{messages:G,tokensRemoved:U}=hn(T,b);U>0&&(T=G,console.log(`${m.dim} [auto-compressed \u2014 ~${U} tokens freed, now ${Math.round(en(T,b).percentage)}%]${m.reset}`))}}if(Ts()&&!n.skillLoop&&(ke.some(y=>y&&["write_file","edit_file","patch_file"].includes(y.fnName))?Ns=0:(Ns===0&&(Qu=Z.size),Ns++),Ns>=9&&Y>=4&&Z.size===Qu)){L(`${m.green} \u2713 Stagnation exit: ${Ns} read-only iterations, no new file changes${m.reset}`),process.stdout.isTTY&&process.stderr.write(`${m.yellow} \u26A0 Stagnation detected: ${Ns} iterations without edits \u2014 exiting. The model investigated but did not apply changes.${m.reset}
1479
- `),l&&(l.stop(),l=null),u(null),je(Y,re,Z,Se,Pe),Ne(M);break e}let fd=Q1();if(fd){let b={role:"user",content:`[User note mid-run]: ${fd}`};M.push(b),T.push(b),console.log(`${m.cyan} \u270E Context added${m.reset}`)}}if(Ke>=Et){if(l&&(l.stop(),l=null),u(null),je(Y,re,Z,Se,Pe),Ne(M),yr(M),we&&Re==="plan"){let Xe=[...M].reverse().find(ot=>ot.role==="assistant"),at=typeof Xe?.content=="string"?Xe.content:"",An=await $r("implement",at);if(An){M.push(An),T=[{role:"system",content:await Du()},...M],Et=_s("implement"),L(`${m.yellow} \u26A0 Plan budget exhausted \u2014 auto-transitioning to implement${m.reset}`);continue e}}else if(we&&Re==="verify"){L(`${m.yellow} \u26A0 Verify budget exhausted \u2014 completing session${m.reset}`);break e}let{getActiveProviderName:xe}=ct();if(xe()==="ollama"&&qa<rd){if(Z.size===0&&!Fa){console.log(`${m.yellow} \u26A0 Max iterations reached with no progress. Stopping.${m.reset}`);break e}qa++,Et=20,console.log(`${m.dim} \u2500\u2500 auto-extending (+20 turns, ext ${qa}/${rd}) \u2500\u2500${m.reset}`);continue e}if(console.log(`
1480
- ${m.yellow}\u26A0 Max iterations reached.${m.reset}`),await E0(" Continue for 20 more turns?")){Et=20;continue e}console.log(`${m.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${m.reset}`)}break e}await sd()}W0.exports={processInput:_C,clearConversation:dC,getConversationLength:pC,getConversationMessages:hC,setConversationMessages:mC,setAbortSignalGetter:O1,setMaxIterations:A1,invalidateSystemPromptCache:Cu,clearToolFilterCache:q1,getCachedFilteredTools:M0,buildSystemPrompt:Du,splitSystemPrompt:uC,SYSTEM_PROMPT_DYNAMIC_BOUNDARY:ju,getProjectContextHash:P0,_inferVerificationCommands:Fu,_inferRelevantTests:Aa,_inferSymbolTargets:q0,_buildSymbolHintBlock:F0,buildUserContent:O0,_detectImageURLs:R0,_downloadImageURL:C0,_grabClipboardImage:A0,detectFrustration:N0,detectAndTruncateLoop:vu,injectMidRunNote:Z1,resetSessionTracking:B0}});var ct=Q((zO,z0)=>{var{OllamaProvider:xC}=Vd(),{OpenAIProvider:kC}=ef(),{AnthropicProvider:vC}=of(),{GeminiProvider:SC}=lf(),{LocalProvider:EC}=ff(),{checkBudget:TC}=ii(),Wu={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"}},Bu=(process.env.OLLAMA_FALLBACK_CHAIN||"").split(",").map(t=>t.trim()).filter(Boolean),Y0={};for(let[t,e]of Object.entries(Wu))for(let n of Object.values(e))Y0[n]=t;function Uu(t,e){let n=Y0[t];return n&&Wu[n][e]||t}var ft={},St=null,Qe=null,Mr=[];function Gt(){if(Object.keys(ft).length>0)return;vo("ollama",new xC),vo("openai",new kC),vo("anthropic",new vC),vo("gemini",new SC),vo("local",new EC);let t=process.env.DEFAULT_PROVIDER||"ollama",e=process.env.DEFAULT_MODEL||null;ft[t]?(St=t,Qe=e||ft[t].defaultModel):(St="ollama",Qe="kimi-k2.5");let n=process.env.FALLBACK_CHAIN;n&&(Mr=n.split(",").map(o=>o.trim()).filter(Boolean))}function vo(t,e){ft[t]=e}function RC(t){return Gt(),ft[t]||null}function Hu(){return Gt(),ft[St]||null}function CC(){return Gt(),St}function AC(){return Gt(),Qe}function OC(){Gt();let t=Hu();if(!t)return{id:Qe,name:Qe,provider:St};let e=t.getModel(Qe);return e?{...e,provider:St}:{id:Qe,name:Qe,provider:St}}function Yu(t){if(!t)return{provider:null,model:null};let e=t.indexOf(":");if(e>0){let n=t.slice(0,e);if(ft[n]||["ollama","openai","anthropic","gemini","local"].includes(n))return{provider:n,model:t.slice(e+1)}}return{provider:null,model:t}}function NC(t){Gt();let{provider:e,model:n}=Yu(t);if(e){let s=ft[e];return s&&(s.getModel(n)||e==="local"||e==="ollama")?(St=e,Qe=n,Oa(),!0):!1}let o=Hu();if(o&&o.getModel(n))return Qe=n,Oa(),!0;for(let[s,r]of Object.entries(ft))if(r.getModel(n))return St=s,Qe=n,Oa(),!0;return!1}function Oa(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=Yl();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=fn();t()}catch{}}function MC(){Gt();let t=new Set;for(let e of Object.values(ft))for(let n of e.getModelNames())t.add(n);return Array.from(t)}function PC(){return Gt(),Object.entries(ft).map(([t,e])=>({provider:t,configured:e.isConfigured(),models:Object.values(e.getModels()).map(n=>({...n,active:t===St&&n.id===Qe}))}))}function LC(){Gt();let t=[];for(let[e,n]of Object.entries(ft)){let o=n.isConfigured();for(let s of Object.values(n.getModels()))t.push({spec:`${e}:${s.id}`,name:s.name,provider:e,configured:o})}return t}function IC(t){Mr=Array.isArray(t)?t:[]}function jC(){return[...Mr]}function H0(t){let e=t.message||"",n=t.code||"";return!!(e.includes("429")||e.includes("500")||e.includes("502")||e.includes("503")||e.includes("504")||n==="ECONNABORTED"||n==="ETIMEDOUT"||n==="ECONNREFUSED"||n==="ECONNRESET"||n==="EHOSTUNREACH"||n==="ENETUNREACH"||n==="EPIPE"||n==="ERR_SOCKET_CONNECTION_TIMEOUT"||e.includes("socket disconnected")||e.includes("TLS")||e.includes("ECONNRESET")||e.includes("ECONNABORTED")||e.includes("network")||e.includes("ETIMEDOUT"))}async function G0(t){let e=[St,...Mr.filter(r=>r!==St)],n,o=0,s=0;for(let r=0;r<e.length;r++){let i=e[r],a=ft[i];if(!a||!a.isConfigured())continue;s++;let c=TC(i);if(!c.allowed){o++,n=new Error(`Budget limit reached for ${i}: $${c.spent.toFixed(2)} / $${c.limit.toFixed(2)}`);continue}try{let u=r>0,l=u?Uu(Qe,i):Qe;return u&&l!==Qe&&process.stderr.write(` [fallback: ${i}:${l}]
1481
- `),await t(a,i,l)}catch(u){if(n=u,!H0(u)||r>=e.length-1)throw u;if(i==="ollama"&&Bu.length>0){let l=isFallback?Uu(Qe,i):Qe;for(let d of Bu)if(d!==l)try{return process.stderr.write(` [ollama fallback: ${d}]
1482
- `),await t(a,i,d)}catch(f){if(n=f,!H0(f))throw f}}continue}}throw o>0&&o===s?new Error("All providers are over budget. Use /budget to check limits or /budget <provider> off to remove a limit."):s===0?new Error("No configured provider available"):n||new Error("No configured provider available")}async function DC(t,e,n={}){Gt();let o=n.model,s=o?(()=>{let{model:i}=Yu(o);return i||o})():void 0,r=s!==o?{...n,model:s}:n;return G0((i,a,c)=>i.stream(t,e,{model:c,signal:r.signal,...r}))}async function qC(t,e,n={}){if(Gt(),n.provider){let o=ft[n.provider];if(!o||!o.isConfigured())throw new Error(`Provider '${n.provider}' is not available`);let s={model:n.model||Qe,...n};try{return await o.chat(t,e,s)}catch(r){if(typeof o.stream=="function")try{return await o.stream(t,e,{...s,onToken:()=>{}})}catch{}throw r}}return G0(async(o,s,r)=>{try{return await o.chat(t,e,{model:r,...n})}catch(i){if(typeof o.stream=="function")try{return await o.stream(t,e,{model:r,...n,onToken:()=>{}})}catch{}throw i}})}function FC(){Gt();let t=[];for(let[e,n]of Object.entries(ft))n.isConfigured()&&t.push({name:e,models:Object.values(n.getModels())});return t}function BC(){for(let t of Object.keys(ft))delete ft[t];St=null,Qe=null,Mr=[]}z0.exports={registerProvider:vo,getProvider:RC,getActiveProvider:Hu,getActiveProviderName:CC,getActiveModelId:AC,getActiveModel:OC,setActiveModel:NC,getModelNames:MC,parseModelSpec:Yu,listProviders:PC,listAllModels:LC,callStream:DC,callChat:qC,getConfiguredProviders:FC,setFallbackChain:IC,getFallbackChain:jC,resolveModelForProvider:Uu,MODEL_EQUIVALENTS:Wu,OLLAMA_FALLBACK_MODELS:Bu,_reset:BC}});var{C:D}=rt(),UC=ct(),{TOOL_DEFINITIONS:K0}=zs(),{saveRoutingConfig:WC}=ms();function Bn(t){let e=Array.isArray(t?.tasks)?t.tasks.flatMap(n=>typeof n=="string"?[n]:n&&typeof n=="object"?[n.title,n.task,n.description]:[]):[];return[t?.pattern,t?.query,t?.regex,t?.file_pattern,t?.include,t?.path,t?.command,t?.name,...e].filter(n=>typeof n=="string").join(" ")}function Rn(t){return typeof t=="string"?t.toLowerCase():""}function HC(t,e=[]){let n=Rn(t);return e.some(o=>n.includes(Rn(o)))}function Xu(t,e=[]){let n=Rn(t);return e.every(o=>n.includes(Rn(o)))}function J0(t=""){return/\b(test|jest|vitest|mocha|ava|pytest|cargo\s+test|go\s+test|rspec|phpunit|mix\s+test|npm\s+(run\s+)?test|pnpm\s+(run\s+)?test|yarn\s+test)\b/i.test(t)}function YC(t=""){return/\b(lint|eslint|prettier|ruff|flake8|rubocop|golangci-lint|tsc(?:\s|$)|npm\s+run\s+lint|pnpm\s+run\s+lint|yarn\s+lint)\b/i.test(t)}function GC(t=""){return/\b(build|compile|tsc(?:\s|$)|webpack|vite\s+build|next\s+build|npm\s+run\s+build|pnpm\s+run\s+build|yarn\s+build|cargo\s+build|go\s+build)\b/i.test(t)}function X0(t=""){return/\b(rg|grep|find|fd|ls|dir|sed|awk)\b/i.test(t)}function Ma(t,e=[]){return t?.action!=="create"||!Array.isArray(t.tasks)||t.tasks.length===0?!1:Xu(Bn(t),e)}function V0(t,{pathIncludes:e=[],table:n="users",action:o="select",conditionTerms:s=[]}={}){if(!Pr(t)||!Xu(t.path,e))return!1;let r=Rn(t.content);return!r.includes(o)||!r.includes(n)?!1:s.every(i=>HC(r,i))}function zC(t,e=[]){let n=Bn(t);return Xu(n,e)}function Gu(t,{pathIncludes:e=[],oldTexts:n=[],newTexts:o=[]}={}){if(typeof t?.path!="string"||!(e.length===0||e.some(d=>t.path.toLowerCase().includes(d.toLowerCase()))))return!1;let r=Array.isArray(t.patches)?t.patches.flatMap(d=>[d.old_text,d.new_text]).filter(d=>typeof d=="string"):[],i=typeof t.old_text=="string"?t.old_text:"",a=typeof t.new_text=="string"?t.new_text:"",c=[i,a,...r],u=n.length===0||n.some(d=>c.some(f=>f.includes(d))),l=o.length===0||o.some(d=>c.some(f=>f.includes(d)));return!u||!l?!1:i&&a?!0:Array.isArray(t.patches)&&t.patches.length>0}function Pr(t,{pathIncludes:e=[],contentIncludes:n=[]}={}){return typeof t?.path!="string"||typeof t?.content!="string"||!(e.length===0||e.some(s=>Rn(t.path).includes(Rn(s))))?!1:n.length===0||n.every(s=>Rn(t.content).includes(Rn(s)))}var Vu=[{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=>Pr(t,{pathIncludes:["nex-bench-test.txt"],contentIncludes:["benchmark run"]})},{id:"edit-file",category:"file-ops",prompt:'You already read src/config.js and confirmed it contains the exact text "debug: false". Replace that exact text with "debug: true".',expectedTool:["edit_file","patch_file"],validateArgs:t=>Gu(t,{pathIncludes:["config"],oldTexts:["debug: false"],newTexts:["debug: true"]})},{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.line_end=="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=>Pr(t,{pathIncludes:[".gitignore"],contentIncludes:["node_modules","dist"]})},{id:"edit-version-bump",category:"file-ops",prompt:'You already read package.json and confirmed it contains the exact snippet `"version": "1.0.0"`. Do not inspect the repo again. Update it directly to `"version": "1.1.0"`.',expectedTool:["edit_file","patch_file"],validateArgs:t=>Gu(t,{pathIncludes:["package.json"],oldTexts:["1.0.0",'"version": "1.0.0"','"version":"1.0.0"'],newTexts:["1.1.0",'"version": "1.1.0"','"version":"1.1.0"']})},{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","git_status"],validateArgs:t=>(typeof t.command=="string"&&t.command.includes("git"),!0)},{id:"git-status",category:"shell",prompt:"Show me the current git status of the repository.",expectedTool:["bash","git_status"],validateArgs:t=>(typeof t.command=="string"&&t.command.includes("git status"),!0)},{id:"npm-install",category:"shell",prompt:"Run npm install to install project dependencies.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("npm")},{id:"schema-strict",category:"schema",prompt:"Read the file README.md",expectedTool:"read_file",validateArgs:(t,e)=>{let n=e?.function?.parameters||{},o=n.required||[],s=Object.keys(n.properties||{});return o.every(r=>t[r]!==void 0)&&Object.keys(t).every(r=>s.includes(r))}},{id:"multi-step-version",category:"multi-step",prompt:"You need to determine the current project version. What tool do you call first to inspect the most likely source file?",expectedTool:["read_file","glob","list_directory","search_files"],validateArgs:t=>!!(typeof t.path=="string"&&/package\.json|package|version/i.test(t.path)||typeof t.pattern=="string"&&/package\.json|package|version/i.test(t.pattern)||/package\.json|package|version/i.test(Bn(t)))},{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:"There is no existing Button component and no need to inspect other files first. What tool call do you use first to create src/components/Button.jsx with a React functional Button component that accepts a label prop and renders a styled button element?",expectedTool:"write_file",validateArgs:t=>Pr(t,{pathIncludes:["button.","src/components"],contentIncludes:["Button","label","button"]})},{id:"frontend-edit-css",category:"frontend",prompt:"You already read src/styles.css and confirmed it contains the exact text `background-color: blue`. Change that exact value to `background-color: red`.",expectedTool:["edit_file","patch_file"],validateArgs:t=>Gu(t,{pathIncludes:[".css","styles"],oldTexts:["background-color: blue"],newTexts:["background-color: red"]})},{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","sysadmin"],validateArgs:t=>typeof t.command=="string"?t.command.includes("lsof")||t.command.includes("ss")||t.command.includes("netstat")||t.command.includes("3000"):t.action==="network_status"},{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","service_manage","sysadmin"],validateArgs:t=>typeof t.command=="string"?t.command.includes("systemctl")||t.command.includes("service")||t.command.includes("nginx"):t.action==="status"&&typeof t.service=="string"?t.service.includes("nginx"):t.action==="service"&&t.service_action==="status"&&typeof t.service_name=="string"&&t.service_name.includes("nginx")},{id:"sysadmin-error-log",category:"sysadmin",prompt:"Show the last 100 lines of the nginx error log.",expectedTool:["bash","service_logs","sysadmin"],validateArgs:t=>typeof t.command=="string"?t.command.includes("tail")||t.command.includes("journalctl")||t.command.includes("nginx"):typeof t.service=="string"?t.service.includes("nginx"):t.action==="journalctl"&&typeof t.unit=="string"&&t.unit.includes("nginx")||t.action==="log_tail"&&typeof t.path=="string"&&/nginx|error/i.test(t.path)},{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:"Do not inspect the repo first. Write a SQL query to find all users who have not logged in for more than 30 days and save it to queries/inactive-users.sql.",expectedTool:"write_file",validateArgs:t=>V0(t,{pathIncludes:["queries","inactive-users.sql"],conditionTerms:[["last_login","last seen","last_seen","last_sign_in","last_signin","logged_in_at","login_at","last_active_at","lastactivity"],["30 day","30-day","interval '30 day'","interval '30 days'","date_sub","datetime('now', '-30 days')","current_date - 30","now() - interval","dateadd(day, -30","add_months","interval '1 month'"]]})},{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:'There is no need to inspect the repo first. What tool call do you use first to create scripts/average_price.py with a Python script that reads data.csv and calculates the average of the "price" column?',expectedTool:"write_file",validateArgs:t=>Pr(t,{pathIncludes:["average_price.py","scripts"],contentIncludes:["data.csv","price"]})},{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","search_files","list_directory","bash"],validateArgs:t=>/schema|model|migration|prisma|dbml|typeorm|sequelize|orm|db|database|entity/i.test(Bn(t))},{id:"data-write-query",category:"data",prompt:"Do not inspect the repo first. 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=>V0(t,{pathIncludes:["queries","recent-users.sql"],conditionTerms:[["created_at","registered_at","registered_on","signup_date","signed_up_at","joined_at","createdon","created_on"],["30 day","30-day","interval '30 day'","interval '30 days'","date_sub","datetime('now', '-30 days')","current_date - 30","now() - interval","dateadd(day, -30","add_months","interval '1 month'"]]})},{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. Use a discovery or search tool as your next step, not read_file again. What tool do you use first?",expectedTool:["glob","bash","search_files","list_directory"],validateArgs:t=>{let e=Bn(t);return/src|helper|util|helpers|\.js|find/i.test(e)}},{id:"resilience-large-file-nav",category:"resilience",prompt:"The file src/api.js is 2800 lines. You need to locate the authenticateUser function. Use a search-oriented tool first instead of reading the whole file. What is the most efficient tool call?",expectedTool:["bash","grep","search_files","glob"],validateArgs:t=>typeof t.command=="string"&&X0(t.command)&&/authenticateuser|src\/api\.js/i.test(t.command)?!0:zC(t,["authenticateuser"])},{id:"resilience-broken-import",category:"resilience",prompt:"TypeScript reports: Cannot find module './config'. The file was recently renamed. Use a search or discovery tool first to find the new location. What tool do you use?",expectedTool:["glob","bash","search_files","grep","list_directory"],validateArgs:t=>{let e=Bn(t);return/config|rename|module|import|\.ts|\.js|find|src|path/i.test(e)}},{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. Use a search tool to list exported function names in src/ and identify the current name. What tool call do you use first?",expectedTool:["bash","grep","search_files"],validateArgs:t=>typeof t.command=="string"?X0(t.command)&&/src|export|function|module\.exports|exports\./i.test(t.command):/getUserById|export|function|module\.exports|exports\.|src|public|def /i.test(Bn(t))},{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","service_logs","sysadmin"],validateArgs:t=>typeof t.command=="string"?(t.command.includes("tail")||t.command.includes("log"))&&typeof t.server=="string":typeof t.service=="string"?t.service.includes("nginx"):typeof t.server=="string"&&(t.action==="journalctl"&&typeof t.unit=="string"&&t.unit.includes("nginx")||t.action==="log_tail"&&typeof t.path=="string"&&/nginx|error/i.test(t.path))},{id:"ssh-exec-service",category:"ssh",prompt:'Restart the nginx service on server "prod-1".',expectedTool:["ssh_exec","service_manage","sysadmin"],validateArgs:t=>typeof t.command=="string"?(t.command.includes("nginx")||t.command.includes("systemctl")||t.command.includes("restart"))&&typeof t.server=="string":t.action==="restart"&&typeof t.service=="string"&&t.service.includes("nginx")?!0:t.action==="service"&&t.service_action==="restart"&&typeof t.service_name=="string"&&t.service_name.includes("nginx")&&typeof t.server=="string"},{id:"ssh-exec-port",category:"ssh",prompt:'Check if port 8080 is listening on server "prod-1".',expectedTool:["ssh_exec","sysadmin"],validateArgs:t=>typeof t.command=="string"?(t.command.includes("8080")||t.command.includes("ss")||t.command.includes("netstat")||t.command.includes("lsof"))&&typeof t.server=="string":t.action==="network_status"&&typeof t.server=="string"},{id:"ssh-exec-processes",category:"ssh",prompt:'Show the top CPU-consuming processes on server "prod-1".',expectedTool:["ssh_exec","sysadmin"],validateArgs:t=>typeof t.command=="string"?(t.command.includes("top")||t.command.includes("ps")||t.command.includes("htop"))&&typeof t.server=="string":t.action==="process_list"&&typeof t.server=="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.count=="number"||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=>(Object.keys(t||{}).length===0||typeof t.command=="string"&&t.command.includes("status"),!0)},{id:"agentic-test-first",category:"agentic",prompt:"You need to run the full test suite first. Do not inspect files before that. If any tests fail after the run, identify the failing test file and read it to understand the issue. What is the first tool call?",expectedTool:["bash","task_list"],validateArgs:t=>typeof t.command=="string"?J0(t.command):Ma(t,["test"])},{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","task_list"],validateArgs:t=>{if(typeof t.command=="string")return t.command.includes("build")||t.command.includes("npm");let e=Bn(t);return t.action==="create"&&/build|dist/i.test(e)}},{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}],Z0=[{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","search_files"],validateArgs:t=>{let e=t.pattern||t.query||t.regex||"";return/cors/i.test(e)}},{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","bash"],validateArgs:t=>(typeof t.command=="string"&&t.command.includes("log"),!0)},{id:"phase-verify-test",category:"phase-verify",prompt:"You are explicitly in the verify phase. Do not inspect files first. The first verification step is to run tests for a fix in src/utils.js. What tool call do you use first?",expectedTool:["bash","task_list"],validateArgs:t=>typeof t.command=="string"?J0(t.command):Ma(t,["test"])},{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:"You are explicitly in the verify phase. Do not inspect files first. The first verification step is to run linting after changes in src/components/Header.tsx. What tool call do you use first?",expectedTool:["bash","task_list"],validateArgs:t=>typeof t.command=="string"?YC(t.command):Ma(t,["lint"])},{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","bash"],validateArgs:t=>(typeof t.command=="string"&&t.command.includes("log"),!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","search_files"],validateArgs:t=>{let e=t.pattern||t.query||t.regex||"";return/api.?key|env/i.test(e)}},{id:"phase-verify-build",category:"phase-verify",prompt:"You are in the verify phase. Do not inspect files first. The TypeScript source was modified, so run the build command to verify there are no compilation errors.",expectedTool:["bash","task_list"],validateArgs:t=>typeof t.command=="string"?GC(t.command):Ma(t,["build"])},{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)}],La=[...Vu,...Z0],zu=["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 KC(){try{let n=require("path").join(require("os").homedir(),".nex-code","benchmark-results.json");if(!require("fs").existsSync(n))return zu;let o=JSON.parse(require("fs").readFileSync(n,"utf-8"));return!Array.isArray(o)||o.length===0?zu:o.filter(s=>typeof s.score=="number"&&s.score>=60).sort((s,r)=>r.score-s.score).slice(0,12).map(s=>s.model)}catch{return zu}}var Ju=KC(),XC=["minimax-m2.7:cloud","qwen3-coder:480b","devstral-2:123b"],Q0=(()=>{let t=Ju.slice(0,3);return t.length>=3?t:XC})(),VC=14,Na={producedToolCall:.2,correctTool:.35,validArgs:.3,schemaCompliant:.15},JC="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 Ku(t,e){let n={taskId:t.id,category:t.category,model:e,producedToolCall:!1,correctTool:!1,validArgs:!1,schemaCompliant:!1,toolCalled:null,error:null,latencyMs:0},o=[{role:"system",content:JC},{role:"user",content:t.prompt}],s=Date.now();try{let r=await UC.callChat(o,K0,{provider:"ollama",model:e,temperature:0,timeout:9e4});n.latencyMs=Date.now()-s;let i=r.tool_calls||[];if(t.expectedTool===null){let a=i.length===0;n.producedToolCall=a,n.correctTool=a,n.validArgs=!0,n.schemaCompliant=!0}else if(i.length>0){n.producedToolCall=!0;let a=Array.isArray(t.expectedTool)?t.expectedTool:[t.expectedTool],c=-1,u=i[0].function?.name||"unknown",l=!1,d=!1,f=!1;for(let p of i){let h=p.function?.name||"unknown",g=p.function?.arguments||{},w=a.includes(h),_=!1,S=!1,A=0;if(w){let E=K0.find(v=>v.function?.name===h);if(_=!!t.validateArgs(g,E),E){let v=E.function?.parameters||{},N=v.required||[],ne=Object.keys(v.properties||{});S=N.every(oe=>g[oe]!==void 0)&&Object.keys(g).every(oe=>ne.includes(oe))}A=(w?2:0)+(_?1:0)+(S?.5:0)}A>c&&(c=A,u=h,l=w,d=_,f=S)}n.toolCalled=l?u:i[0].function?.name||"unknown",n.correctTool=l,n.validArgs=d,n.schemaCompliant=f}}catch(r){n.latencyMs=Date.now()-s,n.error=r.message.slice(0,120)}return n}function So(t){return t.error?0:((t.producedToolCall?Na.producedToolCall:0)+(t.correctTool?Na.correctTool:0)+(t.validArgs?Na.validArgs:0)+(t.schemaCompliant?Na.schemaCompliant:0))*100}var ew={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 Zu(t){return Object.entries(t).map(([e,n])=>{let o=n.map(So),s=o.reduce((a,c)=>a+c,0)/o.length,r=a=>Math.round(n.filter(a).length/n.length*100),i={};for(let a of["coding","frontend","sysadmin","data","agentic","plan","verify"]){let c=n.filter(l=>ew[l.category]===a);if(c.length===0)continue;let u=c.map(So).reduce((l,d)=>l+d,0)/c.length;i[a]=Math.round(u*10)/10}return{model:e,score:Math.round(s*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(n.reduce((a,c)=>a+c.latencyMs,0)/n.length),errorCount:n.filter(a=>a.error).length,categoryScores:i,results:n}}).sort((e,n)=>n.score-e.score)}function tw(t){return nw(t)}function nw(t){let e={};for(let r of["coding","frontend","sysadmin","data","agentic","plan","verify"]){let i=t.filter(f=>f.categoryScores[r]!==void 0&&f.score>=65).sort((f,p)=>p.categoryScores[r]-f.categoryScores[r]);if(i.length===0||(i[0]?.results||[]).filter(f=>ew[f.category]===r).length<4)continue;let u=i[0],d=i.filter(f=>u.categoryScores[r]-f.categoryScores[r]<=5).sort((f,p)=>f.avgLatency-p.avgLatency)[0];e[r]={model:d.model,score:d.categoryScores[r],avgLatency:d.avgLatency}}return e}function sw(t,e){let n=`nex-code Model Benchmark (${e} tasks \xB7 ollama cloud)`,o=[{label:"#",width:3},{label:"Model",width:26},{label:"Score",width:7},{label:"Tool\u2713",width:7},{label:"Name\u2713",width:7},{label:"Args\u2713",width:7},{label:"Schema\u2713",width:8},{label:"Latency",width:8},{label:"Err",width:4}],s=o.reduce((l,d)=>l+d.width+1,0)+1,r="\u2500".repeat(s);console.log(`
1480
+ `);for(let de of H)(de.startsWith("/")&&!de.includes(" ")||!de.includes(":")&&!de.startsWith("["))&&Cr.add(de.trim())}let O=y.args.pattern||y.args.query||y.args.path||"",W=xs(yw,O);if(W===ww){L(`${m.yellow} \u26A0 Loop warning: glob pattern "${O.slice(0,40)}" run ${W}\xD7 \u2014 possible search loop${m.reset}`);let H={role:"user",content:`[SYSTEM WARNING] Same glob/search pattern ${W}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};M.push(H),T.push(H)}else if(W>=bw){L(`${m.red} \u2716 Loop abort: glob pattern run ${W}\xD7 \u2014 aborting runaway search loop${m.reset}`),l&&(l.stop(),l=null),u(null),je(Y,re,Z,Se,Pe,{suppressHint:!0}),Ne(M);return}let R=O.replace(/\*+/g," ").replace(/[{}()\[\],.\/\\]/g," ").split(/\s+/).filter(H=>H.length>=4&&!/^\.(js|ts|py|json|md|yaml|yml|txt|css|html|sh)$/.test(H));for(let H of R){let de=H.toLowerCase();wa.has(de)||wa.set(de,new Set);let $e=wa.get(de);if($e.add(O),$e.size===_w){L(`${m.red} \u2716 Glob core-term block: ${$e.size} different patterns all searching for "${de}" \u2014 search loop${m.reset}`);let se={role:"user",content:`[SYSTEM WARNING] You have searched for "${de}" using ${$e.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.`};M.push(se),T.push(se)}else if($e.size===$w){L(`${m.yellow} \u26A0 Glob core-term warning: ${$e.size} different patterns searching for "${de}"${m.reset}`);let se={role:"user",content:`[SYSTEM WARNING] ${$e.size} different glob patterns all target "${de}". If previous searches returned no results, the file probably does not exist \u2014 stop searching and proceed with available information.`};M.push(se),T.push(se)}}}let K=(y.args?.command||y.args?.cmd||y.args?.script||"").toLowerCase(),j=/\b(health|healthcheck|health-check|status|check|ping|validate|alive|ready)\b/.test(K)||/\/(health|status|ping|ready|alive)\b/.test(K);if(z&&(y.fnName==="bash"||y.fnName==="ssh_exec")&&j&&G.includes('"valid":true')){{let W=ht();if(en(T,W).percentage>=60){let{messages:H,tokensRemoved:de}=hn(T,W);de>0&&(T=H,console.log(`${m.dim} [pre-stop-compress \u2014 ~${de} tokens freed before STOP injection, now ${Math.round(en(T,W).percentage)}%]${m.reset}`))}}let O={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.'};M.push(O),T.push(O),console.log(`${m.cyan} \u2713 Health-check stop signal detected \u2014 injecting STOP instruction${m.reset}`)}if(z&&(y.fnName==="bash"||y.fnName==="ssh_exec")&&K&&/\bsed\s+-[ie]\b|\btee\b|\bcp\b|\bmv\b|\bpatch\b|\bdd\b|>\s*\S|\becho\b.*>|\bcat\b.*>|\bprintf\b.*>|\bpython[23]?\b.*open\b.*['"'w]|\bnpm\b.*run\b|\byarn\b.*run\b/.test(K)&&(Ms++,L(`${m.dim} [bash write detected: _bashModifiedFiles=${Ms}]${m.reset}`)),G.startsWith("BLOCKED:")){if(Wn++,Wn>=nd){L(`${m.red} \u2716 Loop abort: ${Wn} consecutive blocked calls \u2014 model not heeding BLOCKED messages${m.reset}`),l&&(l.stop(),l=null),u(null),je(Y,re,Z,Se,Pe,{suppressHint:!0}),Ne(M);return}}else Wn=0;if(z)Un=0,Fa=!0;else if(Un++,Un===Sw){L(`${m.yellow} \u26A0 Loop warning: ${Un} consecutive tool errors \u2014 possible stuck loop${m.reset}`);let O={role:"user",content:`[SYSTEM WARNING] ${Un} consecutive errors. Stuck loop \u2014 try fundamentally different approach or declare done.`};M.push(O),T.push(O)}else if(Un>=Ew){L(`${m.red} \u2716 Loop abort: ${Un} consecutive errors \u2014 aborting stuck loop${m.reset}`),l&&(l.stop(),l=null),u(null),je(Y,re,Z,Se,Pe,{suppressHint:!0}),Ne(M);return}if(z&&y.fnName==="read_file"&&y.args&&y.args.path){Se.add(y.args.path),ks.delete(y.args.path),Os.delete(y.args.path);let O=xs(Ps,y.args.path);{let de=y.args.line_start!=null&&parseInt(y.args.line_start,10)||1,$e=y.args.line_start!=null?parseInt(y.args.line_end,10)||de+350:350;Tn.has(y.args.path)||Tn.set(y.args.path,[]),Tn.get(y.args.path).push([de,$e])}if(y._scrollWarn){let{sectionCount:de,path:$e}=y._scrollWarn,se={role:"user",content:`[SYSTEM WARNING] "${$e}" \u2014 you have now read ${de} 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.`};M.push(se),T.push(se),L(`${m.yellow} \u26A0 Scroll warning: "${$e.split("/").slice(-2).join("/")}" \u2014 ${de} sections read \u2014 use grep instead${m.reset}`)}let W=y.args.path.split("/").slice(-2).join("/"),R=!y.args?.line_start&&!y.args?.line_end,H=we&&Re==="plan";if(!H&&R&&O===xw){{let $e=ht();if(en(T,$e).percentage>=60){let{messages:I}=hn(T,$e);T=I}}L(`${m.yellow} \u26A0 Loop warning: "${W}" read unbounded ${O}\xD7 \u2014 use line_start/line_end${m.reset}`);let de={role:"user",content:`[SYSTEM WARNING] "${y.args.path}" read ${O}\xD7 without line ranges. Use line_start/line_end to read specific sections \u2014 do not re-read the full file.`};M.push(de),T.push(de)}else if(!H&&R&&O>=kw){L(`${m.red} \u2716 Loop abort: "${W}" read unbounded ${O}\xD7 \u2014 aborting runaway read loop${m.reset}`),l&&(l.stop(),l=null),u(null),je(Y,re,Z,Se,Pe,{suppressHint:!0}),Ne(M);return}}if(y.fnName==="spawn_agents"){let O=(G.match(/\bStatus: done\b/g)||[]).length;if((G.match(/\bStatus: truncated\b/g)||[]).length>0&&O===0){if(Hn++,Hn===Tw){L(`${m.yellow} \u26A0 Swarm warning: all sub-agents hit iteration limit ${Hn}\xD7 in a row${m.reset}`);let R={role:"user",content:`[SYSTEM WARNING] Sub-agents truncated ${Hn}\xD7 in a row. Stop spawning \u2014 try different approach or report findings.`};M.push(R),T.push(R)}else if(Hn>=Rw){console.log(`${m.red} \u2716 Swarm abort: all sub-agents hit iteration limit ${Hn}\xD7 \u2014 aborting stuck swarm${m.reset}`),l&&(l.stop(),l=null),u(null),je(Y,re,Z,Se,Pe,{suppressHint:!0}),Ne(M);return}}else O>0&&(Hn=0)}}if(Ga&&xo&&!(we&&Re==="verify")){let b=await Fu(Z),y=await Aa(Z),G={role:"user",content:oC(Z,b,y)};M.push(G),T.push(G),L(`${m.cyan} \u21B3 Post-edit verify prompt injected (${b.length} checks, ${y.length} tests)${m.reset}`)}{let y=tt.reduce((G,U)=>G+(typeof U.content=="string"?U.content.length:0),0);if(y>2e5){let G=tt.map((U,z)=>({i:z,len:typeof U.content=="string"?U.content.length:0})).sort((U,z)=>z.len-U.len);for(let{i:U,len:z}of G){if(y<=2e5)break;let K=y-2e5,j=Math.max(z-K,500);j<z&&typeof tt[U].content=="string"&&(tt[U]={...tt[U],content:tt[U].content.substring(0,j)+`
1481
+ ...(truncated ${z-j} chars \u2014 per-message budget)`},y-=z-j)}}}for(let b of tt)M.push(b),T.push(b);let Lw=Ir&&ke.some((b,y)=>{if(!b||!["write_file","edit_file","patch_file"].includes(b.fnName))return!1;let G=b.args?.path||b.args?.file_path;return VR(G)&&typeof tt[y]?.content=="string"&&!tt[y].content.startsWith("ERROR")&&!tt[y].content.startsWith("BLOCKED:")});if(Ts()&&!n.skillLoop&&Ba&&Lw){L(`${m.green} \u2713 Synthesis deliverable exit: text deliverable written after evidence threshold reached${m.reset}`),je(Y,re,Z,Se,Pe),Ne(M);break e}if(ha(M,T),!dt)for(let b=0;b<tt.length;b++){if(!ke[b]||ke[b].fnName!=="ssh_exec")continue;let y=tt[b];if(!y||typeof y.content!="string")continue;let G=wu(y.content);if(G){dt=!0,vt=G.slice(0,120),Wt=0,Ht=!1,tn=0,L(`${m.yellow} \u26A1 Root cause detected: ${vt} \u2014 fix phase (read budget: 3)${m.reset}`);let U={role:"user",content:`[SYSTEM] Root cause identified: ${vt}. Read only the file that needs fixing, then edit it. Do not read other files.`};M.push(U),T.push(U);break}}for(let b=0;b<tt.length;b++){let y=ke[b];if(!y)continue;let G=typeof tt[b]?.content=="string"?tt[b].content:"";if(y.fnName==="create_task"){let U=G.match(/Task #(\d+) created/),z=typeof y.args?.subject=="string"?y.args.subject:"";U&&z&&Or.set(U[1],z)}else if((y.fnName==="write_file"||y.fnName==="edit_file")&&!G.startsWith("BLOCKED:")&&G.trim().length>0){let z=(typeof y.args?.path=="string"?y.args.path:typeof y.args?.file_path=="string"?y.args.file_path:"").split("/").pop().toLowerCase(),K=z.split(/[._\-/]/).filter(j=>j.length>2);for(let[j,ce]of Or){if(Nr.has(j))continue;let O=ce.toLowerCase().split(/\W+/).filter(R=>R.length>3);K.filter(R=>O.some(H=>H.includes(R)||R.includes(H))).length>=1&&(Nr.add(j),L(`${m.green} \u2714 Auto-matched task #${j} to ${z}: ${ce.slice(0,60)}${m.reset}`))}}}{let b=ht();if(en(T,b).percentage>=78){let{messages:G,tokensRemoved:U}=hn(T,b);U>0&&(T=G,console.log(`${m.dim} [auto-compressed \u2014 ~${U} tokens freed, now ${Math.round(en(T,b).percentage)}%]${m.reset}`))}}if(Ts()&&!n.skillLoop&&(ke.some(y=>y&&["write_file","edit_file","patch_file"].includes(y.fnName))?Ns=0:(Ns===0&&(ed=Z.size),Ns++),Ns>=9&&Y>=4&&Z.size===ed)){L(`${m.green} \u2713 Stagnation exit: ${Ns} read-only iterations, no new file changes${m.reset}`),process.stdout.isTTY&&process.stderr.write(`${m.yellow} \u26A0 Stagnation detected: ${Ns} iterations without edits \u2014 exiting. The model investigated but did not apply changes.${m.reset}
1482
+ `),l&&(l.stop(),l=null),u(null),je(Y,re,Z,Se,Pe),Ne(M);break e}let pd=eC();if(pd){let b={role:"user",content:`[User note mid-run]: ${pd}`};M.push(b),T.push(b),console.log(`${m.cyan} \u270E Context added${m.reset}`)}}if(Ke>=Et){if(l&&(l.stop(),l=null),u(null),je(Y,re,Z,Se,Pe),Ne(M),yr(M),we&&Re==="plan"){let Xe=[...M].reverse().find(ot=>ot.role==="assistant"),at=typeof Xe?.content=="string"?Xe.content:"",An=await $r("implement",at);if(An){M.push(An),T=[{role:"system",content:await Du()},...M],Et=_s("implement"),L(`${m.yellow} \u26A0 Plan budget exhausted \u2014 auto-transitioning to implement${m.reset}`);continue e}}else if(we&&Re==="verify"){L(`${m.yellow} \u26A0 Verify budget exhausted \u2014 completing session${m.reset}`);break e}let{getActiveProviderName:xe}=ct();if(xe()==="ollama"&&qa<id){if(Z.size===0&&!Fa){console.log(`${m.yellow} \u26A0 Max iterations reached with no progress. Stopping.${m.reset}`);break e}qa++,Et=20,console.log(`${m.dim} \u2500\u2500 auto-extending (+20 turns, ext ${qa}/${id}) \u2500\u2500${m.reset}`);continue e}if(console.log(`
1483
+ ${m.yellow}\u26A0 Max iterations reached.${m.reset}`),await T0(" Continue for 20 more turns?")){Et=20;continue e}console.log(`${m.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${m.reset}`)}break e}await od()}W0.exports={processInput:xC,clearConversation:fC,getConversationLength:hC,getConversationMessages:mC,setConversationMessages:gC,setAbortSignalGetter:O1,setMaxIterations:A1,invalidateSystemPromptCache:Cu,clearToolFilterCache:q1,getCachedFilteredTools:P0,buildSystemPrompt:Du,splitSystemPrompt:dC,SYSTEM_PROMPT_DYNAMIC_BOUNDARY:ju,getProjectContextHash:L0,_inferVerificationCommands:Fu,_inferRelevantTests:Aa,_inferSymbolTargets:F0,_buildSymbolHintBlock:B0,buildUserContent:N0,_detectImageURLs:C0,_downloadImageURL:A0,_grabClipboardImage:O0,detectFrustration:M0,detectAndTruncateLoop:vu,injectMidRunNote:Q1,resetSessionTracking:U0}});var ct=Q((KO,z0)=>{var{OllamaProvider:kC}=Jd(),{OpenAIProvider:vC}=tf(),{AnthropicProvider:SC}=rf(),{GeminiProvider:EC}=uf(),{LocalProvider:TC}=pf(),{checkBudget:RC}=ii(),Hu={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"}},Uu=(process.env.OLLAMA_FALLBACK_CHAIN||"").split(",").map(t=>t.trim()).filter(Boolean),Y0={};for(let[t,e]of Object.entries(Hu))for(let n of Object.values(e))Y0[n]=t;function Wu(t,e){let n=Y0[t];return n&&Hu[n][e]||t}var ft={},St=null,Qe=null,Mr=[];function Gt(){if(Object.keys(ft).length>0)return;vo("ollama",new kC),vo("openai",new vC),vo("anthropic",new SC),vo("gemini",new EC),vo("local",new TC);let t=process.env.DEFAULT_PROVIDER||"ollama",e=process.env.DEFAULT_MODEL||null;ft[t]?(St=t,Qe=e||ft[t].defaultModel):(St="ollama",Qe="kimi-k2.5");let n=process.env.FALLBACK_CHAIN;n&&(Mr=n.split(",").map(o=>o.trim()).filter(Boolean))}function vo(t,e){ft[t]=e}function CC(t){return Gt(),ft[t]||null}function Yu(){return Gt(),ft[St]||null}function AC(){return Gt(),St}function OC(){return Gt(),Qe}function NC(){Gt();let t=Yu();if(!t)return{id:Qe,name:Qe,provider:St};let e=t.getModel(Qe);return e?{...e,provider:St}:{id:Qe,name:Qe,provider:St}}function Gu(t){if(!t)return{provider:null,model:null};let e=t.indexOf(":");if(e>0){let n=t.slice(0,e);if(ft[n]||["ollama","openai","anthropic","gemini","local"].includes(n))return{provider:n,model:t.slice(e+1)}}return{provider:null,model:t}}function MC(t){Gt();let{provider:e,model:n}=Gu(t);if(e){let s=ft[e];return s&&(s.getModel(n)||e==="local"||e==="ollama")?(St=e,Qe=n,Oa(),!0):!1}let o=Yu();if(o&&o.getModel(n))return Qe=n,Oa(),!0;for(let[s,r]of Object.entries(ft))if(r.getModel(n))return St=s,Qe=n,Oa(),!0;return!1}function Oa(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=Yl();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=fn();t()}catch{}}function PC(){Gt();let t=new Set;for(let e of Object.values(ft))for(let n of e.getModelNames())t.add(n);return Array.from(t)}function LC(){return Gt(),Object.entries(ft).map(([t,e])=>({provider:t,configured:e.isConfigured(),models:Object.values(e.getModels()).map(n=>({...n,active:t===St&&n.id===Qe}))}))}function IC(){Gt();let t=[];for(let[e,n]of Object.entries(ft)){let o=n.isConfigured();for(let s of Object.values(n.getModels()))t.push({spec:`${e}:${s.id}`,name:s.name,provider:e,configured:o})}return t}function jC(t){Mr=Array.isArray(t)?t:[]}function DC(){return[...Mr]}function H0(t){let e=t.message||"",n=t.code||"";return!!(e.includes("429")||e.includes("500")||e.includes("502")||e.includes("503")||e.includes("504")||n==="ECONNABORTED"||n==="ETIMEDOUT"||n==="ECONNREFUSED"||n==="ECONNRESET"||n==="EHOSTUNREACH"||n==="ENETUNREACH"||n==="EPIPE"||n==="ERR_SOCKET_CONNECTION_TIMEOUT"||e.includes("socket disconnected")||e.includes("TLS")||e.includes("ECONNRESET")||e.includes("ECONNABORTED")||e.includes("network")||e.includes("ETIMEDOUT"))}async function G0(t){let e=[St,...Mr.filter(r=>r!==St)],n,o=0,s=0;for(let r=0;r<e.length;r++){let i=e[r],a=ft[i];if(!a||!a.isConfigured())continue;s++;let c=RC(i);if(!c.allowed){o++,n=new Error(`Budget limit reached for ${i}: $${c.spent.toFixed(2)} / $${c.limit.toFixed(2)}`);continue}try{let u=r>0,l=u?Wu(Qe,i):Qe;return u&&l!==Qe&&process.stderr.write(` [fallback: ${i}:${l}]
1484
+ `),await t(a,i,l)}catch(u){if(n=u,!H0(u)||r>=e.length-1)throw u;if(i==="ollama"&&Uu.length>0){let l=isFallback?Wu(Qe,i):Qe;for(let d of Uu)if(d!==l)try{return process.stderr.write(` [ollama fallback: ${d}]
1485
+ `),await t(a,i,d)}catch(f){if(n=f,!H0(f))throw f}}continue}}throw o>0&&o===s?new Error("All providers are over budget. Use /budget to check limits or /budget <provider> off to remove a limit."):s===0?new Error("No configured provider available"):n||new Error("No configured provider available")}async function qC(t,e,n={}){Gt();let o=n.model,s=o?(()=>{let{model:i}=Gu(o);return i||o})():void 0,r=s!==o?{...n,model:s}:n;return G0((i,a,c)=>i.stream(t,e,{model:c,signal:r.signal,...r}))}async function FC(t,e,n={}){if(Gt(),n.provider){let o=ft[n.provider];if(!o||!o.isConfigured())throw new Error(`Provider '${n.provider}' is not available`);let s={model:n.model||Qe,...n};try{return await o.chat(t,e,s)}catch(r){if(typeof o.stream=="function")try{return await o.stream(t,e,{...s,onToken:()=>{}})}catch{}throw r}}return G0(async(o,s,r)=>{try{return await o.chat(t,e,{model:r,...n})}catch(i){if(typeof o.stream=="function")try{return await o.stream(t,e,{model:r,...n,onToken:()=>{}})}catch{}throw i}})}function BC(){Gt();let t=[];for(let[e,n]of Object.entries(ft))n.isConfigured()&&t.push({name:e,models:Object.values(n.getModels())});return t}function UC(){for(let t of Object.keys(ft))delete ft[t];St=null,Qe=null,Mr=[]}z0.exports={registerProvider:vo,getProvider:CC,getActiveProvider:Yu,getActiveProviderName:AC,getActiveModelId:OC,getActiveModel:NC,setActiveModel:MC,getModelNames:PC,parseModelSpec:Gu,listProviders:LC,listAllModels:IC,callStream:qC,callChat:FC,getConfiguredProviders:BC,setFallbackChain:jC,getFallbackChain:DC,resolveModelForProvider:Wu,MODEL_EQUIVALENTS:Hu,OLLAMA_FALLBACK_MODELS:Uu,_reset:UC}});var{C:D}=rt(),WC=ct(),{TOOL_DEFINITIONS:K0}=zs(),{saveRoutingConfig:HC}=ms();function Bn(t){let e=Array.isArray(t?.tasks)?t.tasks.flatMap(n=>typeof n=="string"?[n]:n&&typeof n=="object"?[n.title,n.task,n.description]:[]):[];return[t?.pattern,t?.query,t?.regex,t?.file_pattern,t?.include,t?.path,t?.command,t?.name,...e].filter(n=>typeof n=="string").join(" ")}function Rn(t){return typeof t=="string"?t.toLowerCase():""}function YC(t,e=[]){let n=Rn(t);return e.some(o=>n.includes(Rn(o)))}function Vu(t,e=[]){let n=Rn(t);return e.every(o=>n.includes(Rn(o)))}function J0(t=""){return/\b(test|jest|vitest|mocha|ava|pytest|cargo\s+test|go\s+test|rspec|phpunit|mix\s+test|npm\s+(run\s+)?test|pnpm\s+(run\s+)?test|yarn\s+test)\b/i.test(t)}function GC(t=""){return/\b(lint|eslint|prettier|ruff|flake8|rubocop|golangci-lint|tsc(?:\s|$)|npm\s+run\s+lint|pnpm\s+run\s+lint|yarn\s+lint)\b/i.test(t)}function zC(t=""){return/\b(build|compile|tsc(?:\s|$)|webpack|vite\s+build|next\s+build|npm\s+run\s+build|pnpm\s+run\s+build|yarn\s+build|cargo\s+build|go\s+build)\b/i.test(t)}function X0(t=""){return/\b(rg|grep|find|fd|ls|dir|sed|awk)\b/i.test(t)}function Ma(t,e=[]){return t?.action!=="create"||!Array.isArray(t.tasks)||t.tasks.length===0?!1:Vu(Bn(t),e)}function V0(t,{pathIncludes:e=[],table:n="users",action:o="select",conditionTerms:s=[]}={}){if(!Pr(t)||!Vu(t.path,e))return!1;let r=Rn(t.content);return!r.includes(o)||!r.includes(n)?!1:s.every(i=>YC(r,i))}function KC(t,e=[]){let n=Bn(t);return Vu(n,e)}function zu(t,{pathIncludes:e=[],oldTexts:n=[],newTexts:o=[]}={}){if(typeof t?.path!="string"||!(e.length===0||e.some(d=>t.path.toLowerCase().includes(d.toLowerCase()))))return!1;let r=Array.isArray(t.patches)?t.patches.flatMap(d=>[d.old_text,d.new_text]).filter(d=>typeof d=="string"):[],i=typeof t.old_text=="string"?t.old_text:"",a=typeof t.new_text=="string"?t.new_text:"",c=[i,a,...r],u=n.length===0||n.some(d=>c.some(f=>f.includes(d))),l=o.length===0||o.some(d=>c.some(f=>f.includes(d)));return!u||!l?!1:i&&a?!0:Array.isArray(t.patches)&&t.patches.length>0}function Pr(t,{pathIncludes:e=[],contentIncludes:n=[]}={}){return typeof t?.path!="string"||typeof t?.content!="string"||!(e.length===0||e.some(s=>Rn(t.path).includes(Rn(s))))?!1:n.length===0||n.every(s=>Rn(t.content).includes(Rn(s)))}var Ju=[{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=>Pr(t,{pathIncludes:["nex-bench-test.txt"],contentIncludes:["benchmark run"]})},{id:"edit-file",category:"file-ops",prompt:'You already read src/config.js and confirmed it contains the exact text "debug: false". Replace that exact text with "debug: true".',expectedTool:["edit_file","patch_file"],validateArgs:t=>zu(t,{pathIncludes:["config"],oldTexts:["debug: false"],newTexts:["debug: true"]})},{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.line_end=="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=>Pr(t,{pathIncludes:[".gitignore"],contentIncludes:["node_modules","dist"]})},{id:"edit-version-bump",category:"file-ops",prompt:'You already read package.json and confirmed it contains the exact snippet `"version": "1.0.0"`. Do not inspect the repo again. Update it directly to `"version": "1.1.0"`.',expectedTool:["edit_file","patch_file"],validateArgs:t=>zu(t,{pathIncludes:["package.json"],oldTexts:["1.0.0",'"version": "1.0.0"','"version":"1.0.0"'],newTexts:["1.1.0",'"version": "1.1.0"','"version":"1.1.0"']})},{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","git_status"],validateArgs:t=>(typeof t.command=="string"&&t.command.includes("git"),!0)},{id:"git-status",category:"shell",prompt:"Show me the current git status of the repository.",expectedTool:["bash","git_status"],validateArgs:t=>(typeof t.command=="string"&&t.command.includes("git status"),!0)},{id:"npm-install",category:"shell",prompt:"Run npm install to install project dependencies.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("npm")},{id:"schema-strict",category:"schema",prompt:"Read the file README.md",expectedTool:"read_file",validateArgs:(t,e)=>{let n=e?.function?.parameters||{},o=n.required||[],s=Object.keys(n.properties||{});return o.every(r=>t[r]!==void 0)&&Object.keys(t).every(r=>s.includes(r))}},{id:"multi-step-version",category:"multi-step",prompt:"You need to determine the current project version. What tool do you call first to inspect the most likely source file?",expectedTool:["read_file","glob","list_directory","search_files"],validateArgs:t=>!!(typeof t.path=="string"&&/package\.json|package|version/i.test(t.path)||typeof t.pattern=="string"&&/package\.json|package|version/i.test(t.pattern)||/package\.json|package|version/i.test(Bn(t)))},{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:"There is no existing Button component and no need to inspect other files first. What tool call do you use first to create src/components/Button.jsx with a React functional Button component that accepts a label prop and renders a styled button element?",expectedTool:"write_file",validateArgs:t=>Pr(t,{pathIncludes:["button.","src/components"],contentIncludes:["Button","label","button"]})},{id:"frontend-edit-css",category:"frontend",prompt:"You already read src/styles.css and confirmed it contains the exact text `background-color: blue`. Change that exact value to `background-color: red`.",expectedTool:["edit_file","patch_file"],validateArgs:t=>zu(t,{pathIncludes:[".css","styles"],oldTexts:["background-color: blue"],newTexts:["background-color: red"]})},{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","sysadmin"],validateArgs:t=>typeof t.command=="string"?t.command.includes("lsof")||t.command.includes("ss")||t.command.includes("netstat")||t.command.includes("3000"):t.action==="network_status"},{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","service_manage","sysadmin"],validateArgs:t=>typeof t.command=="string"?t.command.includes("systemctl")||t.command.includes("service")||t.command.includes("nginx"):t.action==="status"&&typeof t.service=="string"?t.service.includes("nginx"):t.action==="service"&&t.service_action==="status"&&typeof t.service_name=="string"&&t.service_name.includes("nginx")},{id:"sysadmin-error-log",category:"sysadmin",prompt:"Show the last 100 lines of the nginx error log.",expectedTool:["bash","service_logs","sysadmin"],validateArgs:t=>typeof t.command=="string"?t.command.includes("tail")||t.command.includes("journalctl")||t.command.includes("nginx"):typeof t.service=="string"?t.service.includes("nginx"):t.action==="journalctl"&&typeof t.unit=="string"&&t.unit.includes("nginx")||t.action==="log_tail"&&typeof t.path=="string"&&/nginx|error/i.test(t.path)},{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:"Do not inspect the repo first. Write a SQL query to find all users who have not logged in for more than 30 days and save it to queries/inactive-users.sql.",expectedTool:"write_file",validateArgs:t=>V0(t,{pathIncludes:["queries","inactive-users.sql"],conditionTerms:[["last_login","last seen","last_seen","last_sign_in","last_signin","logged_in_at","login_at","last_active_at","lastactivity"],["30 day","30-day","interval '30 day'","interval '30 days'","date_sub","datetime('now', '-30 days')","current_date - 30","now() - interval","dateadd(day, -30","add_months","interval '1 month'"]]})},{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:'There is no need to inspect the repo first. What tool call do you use first to create scripts/average_price.py with a Python script that reads data.csv and calculates the average of the "price" column?',expectedTool:"write_file",validateArgs:t=>Pr(t,{pathIncludes:["average_price.py","scripts"],contentIncludes:["data.csv","price"]})},{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","search_files","list_directory","bash"],validateArgs:t=>/schema|model|migration|prisma|dbml|typeorm|sequelize|orm|db|database|entity/i.test(Bn(t))},{id:"data-write-query",category:"data",prompt:"Do not inspect the repo first. 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=>V0(t,{pathIncludes:["queries","recent-users.sql"],conditionTerms:[["created_at","registered_at","registered_on","signup_date","signed_up_at","joined_at","createdon","created_on"],["30 day","30-day","interval '30 day'","interval '30 days'","date_sub","datetime('now', '-30 days')","current_date - 30","now() - interval","dateadd(day, -30","add_months","interval '1 month'"]]})},{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. Use a discovery or search tool as your next step, not read_file again. What tool do you use first?",expectedTool:["glob","bash","search_files","list_directory"],validateArgs:t=>{let e=Bn(t);return/src|helper|util|helpers|\.js|find/i.test(e)}},{id:"resilience-large-file-nav",category:"resilience",prompt:"The file src/api.js is 2800 lines. You need to locate the authenticateUser function. Use a search-oriented tool first instead of reading the whole file. What is the most efficient tool call?",expectedTool:["bash","grep","search_files","glob"],validateArgs:t=>typeof t.command=="string"&&X0(t.command)&&/authenticateuser|src\/api\.js/i.test(t.command)?!0:KC(t,["authenticateuser"])},{id:"resilience-broken-import",category:"resilience",prompt:"TypeScript reports: Cannot find module './config'. The file was recently renamed. Use a search or discovery tool first to find the new location. What tool do you use?",expectedTool:["glob","bash","search_files","grep","list_directory"],validateArgs:t=>{let e=Bn(t);return/config|rename|module|import|\.ts|\.js|find|src|path/i.test(e)}},{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. Use a search tool to list exported function names in src/ and identify the current name. What tool call do you use first?",expectedTool:["bash","grep","search_files"],validateArgs:t=>typeof t.command=="string"?X0(t.command)&&/src|export|function|module\.exports|exports\./i.test(t.command):/getUserById|export|function|module\.exports|exports\.|src|public|def /i.test(Bn(t))},{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","service_logs","sysadmin"],validateArgs:t=>typeof t.command=="string"?(t.command.includes("tail")||t.command.includes("log"))&&typeof t.server=="string":typeof t.service=="string"?t.service.includes("nginx"):typeof t.server=="string"&&(t.action==="journalctl"&&typeof t.unit=="string"&&t.unit.includes("nginx")||t.action==="log_tail"&&typeof t.path=="string"&&/nginx|error/i.test(t.path))},{id:"ssh-exec-service",category:"ssh",prompt:'Restart the nginx service on server "prod-1".',expectedTool:["ssh_exec","service_manage","sysadmin"],validateArgs:t=>typeof t.command=="string"?(t.command.includes("nginx")||t.command.includes("systemctl")||t.command.includes("restart"))&&typeof t.server=="string":t.action==="restart"&&typeof t.service=="string"&&t.service.includes("nginx")?!0:t.action==="service"&&t.service_action==="restart"&&typeof t.service_name=="string"&&t.service_name.includes("nginx")&&typeof t.server=="string"},{id:"ssh-exec-port",category:"ssh",prompt:'Check if port 8080 is listening on server "prod-1".',expectedTool:["ssh_exec","sysadmin"],validateArgs:t=>typeof t.command=="string"?(t.command.includes("8080")||t.command.includes("ss")||t.command.includes("netstat")||t.command.includes("lsof"))&&typeof t.server=="string":t.action==="network_status"&&typeof t.server=="string"},{id:"ssh-exec-processes",category:"ssh",prompt:'Show the top CPU-consuming processes on server "prod-1".',expectedTool:["ssh_exec","sysadmin"],validateArgs:t=>typeof t.command=="string"?(t.command.includes("top")||t.command.includes("ps")||t.command.includes("htop"))&&typeof t.server=="string":t.action==="process_list"&&typeof t.server=="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.count=="number"||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=>(Object.keys(t||{}).length===0||typeof t.command=="string"&&t.command.includes("status"),!0)},{id:"agentic-test-first",category:"agentic",prompt:"You need to run the full test suite first. Do not inspect files before that. If any tests fail after the run, identify the failing test file and read it to understand the issue. What is the first tool call?",expectedTool:["bash","task_list"],validateArgs:t=>typeof t.command=="string"?J0(t.command):Ma(t,["test"])},{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","task_list"],validateArgs:t=>{if(typeof t.command=="string")return t.command.includes("build")||t.command.includes("npm");let e=Bn(t);return t.action==="create"&&/build|dist/i.test(e)}},{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}],Z0=[{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","search_files"],validateArgs:t=>{let e=t.pattern||t.query||t.regex||"";return/cors/i.test(e)}},{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","bash"],validateArgs:t=>(typeof t.command=="string"&&t.command.includes("log"),!0)},{id:"phase-verify-test",category:"phase-verify",prompt:"You are explicitly in the verify phase. Do not inspect files first. The first verification step is to run tests for a fix in src/utils.js. What tool call do you use first?",expectedTool:["bash","task_list"],validateArgs:t=>typeof t.command=="string"?J0(t.command):Ma(t,["test"])},{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:"You are explicitly in the verify phase. Do not inspect files first. The first verification step is to run linting after changes in src/components/Header.tsx. What tool call do you use first?",expectedTool:["bash","task_list"],validateArgs:t=>typeof t.command=="string"?GC(t.command):Ma(t,["lint"])},{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","bash"],validateArgs:t=>(typeof t.command=="string"&&t.command.includes("log"),!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","search_files"],validateArgs:t=>{let e=t.pattern||t.query||t.regex||"";return/api.?key|env/i.test(e)}},{id:"phase-verify-build",category:"phase-verify",prompt:"You are in the verify phase. Do not inspect files first. The TypeScript source was modified, so run the build command to verify there are no compilation errors.",expectedTool:["bash","task_list"],validateArgs:t=>typeof t.command=="string"?zC(t.command):Ma(t,["build"])},{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)}],La=[...Ju,...Z0],Ku=["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 XC(){try{let n=require("path").join(require("os").homedir(),".nex-code","benchmark-results.json");if(!require("fs").existsSync(n))return Ku;let o=JSON.parse(require("fs").readFileSync(n,"utf-8"));return!Array.isArray(o)||o.length===0?Ku:o.filter(s=>typeof s.score=="number"&&s.score>=60).sort((s,r)=>r.score-s.score).slice(0,12).map(s=>s.model)}catch{return Ku}}var Zu=XC(),VC=["minimax-m2.7:cloud","qwen3-coder:480b","devstral-2:123b"],Q0=(()=>{let t=Zu.slice(0,3);return t.length>=3?t:VC})(),JC=14,Na={producedToolCall:.2,correctTool:.35,validArgs:.3,schemaCompliant:.15},ZC="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 Xu(t,e){let n={taskId:t.id,category:t.category,model:e,producedToolCall:!1,correctTool:!1,validArgs:!1,schemaCompliant:!1,toolCalled:null,error:null,latencyMs:0},o=[{role:"system",content:ZC},{role:"user",content:t.prompt}],s=Date.now();try{let r=await WC.callChat(o,K0,{provider:"ollama",model:e,temperature:0,timeout:9e4});n.latencyMs=Date.now()-s;let i=r.tool_calls||[];if(t.expectedTool===null){let a=i.length===0;n.producedToolCall=a,n.correctTool=a,n.validArgs=!0,n.schemaCompliant=!0}else if(i.length>0){n.producedToolCall=!0;let a=Array.isArray(t.expectedTool)?t.expectedTool:[t.expectedTool],c=-1,u=i[0].function?.name||"unknown",l=!1,d=!1,f=!1;for(let p of i){let h=p.function?.name||"unknown",g=p.function?.arguments||{},w=a.includes(h),_=!1,S=!1,A=0;if(w){let E=K0.find(v=>v.function?.name===h);if(_=!!t.validateArgs(g,E),E){let v=E.function?.parameters||{},N=v.required||[],ne=Object.keys(v.properties||{});S=N.every(oe=>g[oe]!==void 0)&&Object.keys(g).every(oe=>ne.includes(oe))}A=(w?2:0)+(_?1:0)+(S?.5:0)}A>c&&(c=A,u=h,l=w,d=_,f=S)}n.toolCalled=l?u:i[0].function?.name||"unknown",n.correctTool=l,n.validArgs=d,n.schemaCompliant=f}}catch(r){n.latencyMs=Date.now()-s,n.error=r.message.slice(0,120)}return n}function So(t){return t.error?0:((t.producedToolCall?Na.producedToolCall:0)+(t.correctTool?Na.correctTool:0)+(t.validArgs?Na.validArgs:0)+(t.schemaCompliant?Na.schemaCompliant:0))*100}var ew={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 Qu(t){return Object.entries(t).map(([e,n])=>{let o=n.map(So),s=o.reduce((a,c)=>a+c,0)/o.length,r=a=>Math.round(n.filter(a).length/n.length*100),i={};for(let a of["coding","frontend","sysadmin","data","agentic","plan","verify"]){let c=n.filter(l=>ew[l.category]===a);if(c.length===0)continue;let u=c.map(So).reduce((l,d)=>l+d,0)/c.length;i[a]=Math.round(u*10)/10}return{model:e,score:Math.round(s*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(n.reduce((a,c)=>a+c.latencyMs,0)/n.length),errorCount:n.filter(a=>a.error).length,categoryScores:i,results:n}}).sort((e,n)=>n.score-e.score)}function tw(t){return nw(t)}function nw(t){let e={};for(let r of["coding","frontend","sysadmin","data","agentic","plan","verify"]){let i=t.filter(f=>f.categoryScores[r]!==void 0&&f.score>=65).sort((f,p)=>p.categoryScores[r]-f.categoryScores[r]);if(i.length===0||(i[0]?.results||[]).filter(f=>ew[f.category]===r).length<4)continue;let u=i[0],d=i.filter(f=>u.categoryScores[r]-f.categoryScores[r]<=5).sort((f,p)=>f.avgLatency-p.avgLatency)[0];e[r]={model:d.model,score:d.categoryScores[r],avgLatency:d.avgLatency}}return e}function sw(t,e){let n=`nex-code Model Benchmark (${e} tasks \xB7 ollama cloud)`,o=[{label:"#",width:3},{label:"Model",width:26},{label:"Score",width:7},{label:"Tool\u2713",width:7},{label:"Name\u2713",width:7},{label:"Args\u2713",width:7},{label:"Schema\u2713",width:8},{label:"Latency",width:8},{label:"Err",width:4}],s=o.reduce((l,d)=>l+d.width+1,0)+1,r="\u2500".repeat(s);console.log(`
1483
1486
  ${D.bold}${n}${D.reset}`),console.log(r);let i=o.map(l=>l.label.padEnd(l.width)).join(" ");if(console.log(`${D.dim}${i}${D.reset}`),console.log(r),t.forEach((l,d)=>{let f=String(d+1).padEnd(o[0].width),p=l.model.slice(0,o[1].width).padEnd(o[1].width),h=String(l.score).padEnd(o[2].width),g=`${l.toolCallRate}%`.padEnd(o[3].width),w=`${l.correctRate}%`.padEnd(o[4].width),_=`${l.validArgsRate}%`.padEnd(o[5].width),S=`${l.schemaRate}%`.padEnd(o[6].width),A=`${(l.avgLatency/1e3).toFixed(1)}s`.padEnd(o[7].width),E=l.errorCount>0?`${D.red}${l.errorCount}${D.reset}`:`${D.dim}0${D.reset}`,v=l.score>=80?D.green:l.score>=60?D.yellow:D.red,N=d===0?`${D.yellow}${f}${D.reset}`:`${D.dim}${f}${D.reset}`;console.log(`${N} ${v}${p}${D.reset} ${D.bold}${v}${h}${D.reset} ${g} ${w} ${_} ${S} ${D.dim}${A}${D.reset} ${E}`)}),console.log(r),t.length>0){let l=t[0];if(console.log(`
1484
1487
  ${D.bold}${D.green}Winner: ${l.model}${D.reset} score ${l.score}/100`),t.length>1){let d=(l.score-t[1].score).toFixed(1);console.log(`${D.dim}+${d} pts over ${t[1].model}${D.reset}`)}}let a=t.filter(l=>l.results.some(d=>!d.error&&(!d.correctTool||!d.validArgs)));if(a.length>0){console.log(`${D.bold}Failing tasks:${D.reset}`);for(let l of a){let d=l.results.filter(h=>!h.error&&(!h.correctTool||!h.validArgs));if(d.length===0)continue;let f=l.model.slice(0,22),p=d.map(h=>{if(!h.correctTool){let g=h.toolCalled||"(none)";return`${D.dim}${h.taskId}${D.reset} ${D.red}\u2192${g}${D.reset}`}return`${D.dim}${h.taskId}${D.reset} ${D.yellow}bad-args${D.reset}`});console.log(` ${D.dim}${f.padEnd(22)}${D.reset} ${p.join(" ")}`)}console.log()}if(t.length>=3){let l={},d={};for(let h of t)for(let g of h.results)g.error||(d[g.taskId]=(d[g.taskId]||0)+1,(!g.correctTool||!g.validArgs)&&(l[g.taskId]=(l[g.taskId]||0)+1));let f=Math.ceil(t.length*.5),p=Object.entries(l).filter(([h,g])=>g>=f&&d[h]>=3).sort((h,g)=>g[1]-h[1]);if(p.length>0){console.log(`
1485
1488
  ${D.bold}Systemic failures${D.reset} ${D.dim}(>50% of models fail \u2014 may indicate benchmark design issues)${D.reset}`);for(let[h,g]of p){let w=d[h],_=Math.round(g/w*100),S=_>=80?D.red:D.yellow;console.log(` ${S}${_}%${D.reset} ${D.dim}fail${D.reset} ${h}`)}console.log()}}let c=["coding","frontend","sysadmin","data","agentic","plan","verify"];if(t.some(l=>Object.keys(l.categoryScores).length>1)){console.log(`
1486
- ${D.bold}Best model per task type:${D.reset}`);let l=nw(t);for(let d of c){let f=l[d];if(!f)continue;let p=f.score,h=p>=80?D.green:p>=60?D.yellow:D.red,g=t.filter(_=>_.categoryScores[d]!==void 0).sort((_,S)=>S.categoryScores[d]-_.categoryScores[d])[0],w=g&&g.model!==f.model?`${D.dim} raw leader: ${g.model} (${g.categoryScores[d]}/100)${D.reset}`:"";console.log(` ${D.dim}${d.padEnd(10)}${D.reset} ${h}${f.model}${D.reset} ${D.dim}${p}/100${D.reset}${w}`)}console.log(`${D.dim} Winners use the same conservative routing criteria as auto-update (overall-score floor plus latency tiebreak band).${D.reset}`)}console.log()}function ow(t){if(!(!t||t.length<2))try{let e=tw(t),{loadRoutingConfig:n}=ms(),o=n(),s={...o},r=[],i=new Set(["plan","verify"]);for(let[a,{model:c,score:u}]of Object.entries(e)){let l=i.has(a),d=l?o.phases&&o.phases[a]:o[a];d&&d!==c&&!t.find(p=>p.model===d)||(l?(s.phases||(s.phases={}),s.phases[a]!==c&&(s.phases[a]=c,r.push(`phase:${a}\u2192${c}`))):s[a]!==c&&(s[a]=c,r.push(`${a}\u2192${c}`)))}r.length>0&&(WC(s),console.log(`
1489
+ ${D.bold}Best model per task type:${D.reset}`);let l=nw(t);for(let d of c){let f=l[d];if(!f)continue;let p=f.score,h=p>=80?D.green:p>=60?D.yellow:D.red,g=t.filter(_=>_.categoryScores[d]!==void 0).sort((_,S)=>S.categoryScores[d]-_.categoryScores[d])[0],w=g&&g.model!==f.model?`${D.dim} raw leader: ${g.model} (${g.categoryScores[d]}/100)${D.reset}`:"";console.log(` ${D.dim}${d.padEnd(10)}${D.reset} ${h}${f.model}${D.reset} ${D.dim}${p}/100${D.reset}${w}`)}console.log(`${D.dim} Winners use the same conservative routing criteria as auto-update (overall-score floor plus latency tiebreak band).${D.reset}`)}console.log()}function ow(t){if(!(!t||t.length<2))try{let e=tw(t),{loadRoutingConfig:n}=ms(),o=n(),s={...o},r=[],i=new Set(["plan","verify"]);for(let[a,{model:c,score:u}]of Object.entries(e)){let l=i.has(a),d=l?o.phases&&o.phases[a]:o[a];d&&d!==c&&!t.find(p=>p.model===d)||(l?(s.phases||(s.phases={}),s.phases[a]!==c&&(s.phases[a]=c,r.push(`phase:${a}\u2192${c}`))):s[a]!==c&&(s[a]=c,r.push(`${a}\u2192${c}`)))}r.length>0&&(HC(s),console.log(`
1487
1490
  ${D.dim} Routing updated: ${r.join(", ")}${D.reset}`),console.log(`
1488
- ${D.green}\u{1F4A1} The best models have been saved to ~/.nex-code/.env and will be automatically used by nex-code from now on.${D.reset}`))}catch{}}async function ZC({models:t,quick:e=!1,onProgress:n,parallelModels:o=1}={}){let s=e?Vu.slice(0,VC):La,r=t?.length>0?t:e?Q0:Ju,i={};for(let c of r)i[c]=[];if(o<=1)for(let c of r)for(let u of s){n?.({model:c,task:u.id,done:!1});let l=await Ku(u,c);i[c].push(l),n?.({model:c,task:u.id,done:!0,score:So(l),error:l.error})}else{let c=Math.min(o,r.length),u=[...r],l=Array.from({length:c},async()=>{for(;u.length>0;){let d=u.shift();if(!d)break;for(let f of s){n?.({model:d,task:f.id,done:!1});let p=await Ku(f,d);i[d].push(p),n?.({model:d,task:f.id,done:!0,score:So(p),error:p.error})}}});await Promise.all(l)}let a=Zu(i);return sw(a,s.length),ow(a),a}async function QC({newModels:t,existingRanking:e=[],onProgress:n}={}){if(!t||t.length===0)return e;let o={};for(let i of t){o[i]=[];for(let a of La){n?.({model:i,task:a.id,done:!1});let c=await Ku(a,i);o[i].push(c),n?.({model:i,task:a.id,done:!0,score:So(c),error:c.error})}}let r=[...Zu(o)];for(let i of e)r.find(a=>a.model===i.model)||r.push(i);return r.sort((i,a)=>a.score-i.score),sw(r,La.length),ow(r),r}var Pa=[{id:"simple_question",name:"Simple Convergence",prompt:"What is 2+2?",maxTurns:3,successCriteria:["4"]}];function rw(t){let e=require("fs"),o=require("path").join(t||process.cwd(),".nex","benchmark-config.json");if(!e.existsSync(o))return console.log(`${D.yellow}No scenarios configured.${D.reset} Create ${D.dim}.nex/benchmark-config.json${D.reset} to define your benchmark scenarios.
1491
+ ${D.green}\u{1F4A1} The best models have been saved to ~/.nex-code/.env and will be automatically used by nex-code from now on.${D.reset}`))}catch{}}async function QC({models:t,quick:e=!1,onProgress:n,parallelModels:o=1}={}){let s=e?Ju.slice(0,JC):La,r=t?.length>0?t:e?Q0:Zu,i={};for(let c of r)i[c]=[];if(o<=1)for(let c of r)for(let u of s){n?.({model:c,task:u.id,done:!1});let l=await Xu(u,c);i[c].push(l),n?.({model:c,task:u.id,done:!0,score:So(l),error:l.error})}else{let c=Math.min(o,r.length),u=[...r],l=Array.from({length:c},async()=>{for(;u.length>0;){let d=u.shift();if(!d)break;for(let f of s){n?.({model:d,task:f.id,done:!1});let p=await Xu(f,d);i[d].push(p),n?.({model:d,task:f.id,done:!0,score:So(p),error:p.error})}}});await Promise.all(l)}let a=Qu(i);return sw(a,s.length),ow(a),a}async function eA({newModels:t,existingRanking:e=[],onProgress:n}={}){if(!t||t.length===0)return e;let o={};for(let i of t){o[i]=[];for(let a of La){n?.({model:i,task:a.id,done:!1});let c=await Xu(a,i);o[i].push(c),n?.({model:i,task:a.id,done:!0,score:So(c),error:c.error})}}let r=[...Qu(o)];for(let i of e)r.find(a=>a.model===i.model)||r.push(i);return r.sort((i,a)=>a.score-i.score),sw(r,La.length),ow(r),r}var Pa=[{id:"simple_question",name:"Simple Convergence",prompt:"What is 2+2?",maxTurns:3,successCriteria:["4"]}];function rw(t){let e=require("fs"),o=require("path").join(t||process.cwd(),".nex","benchmark-config.json");if(!e.existsSync(o))return console.log(`${D.yellow}No scenarios configured.${D.reset} Create ${D.dim}.nex/benchmark-config.json${D.reset} to define your benchmark scenarios.
1489
1492
  Example:
1490
1493
  {
1491
1494
  "scenarios": [
@@ -1500,12 +1503,12 @@ ${D.green}\u{1F4A1} The best models have been saved to ~/.nex-code/.env and will
1500
1503
  }
1501
1504
  `),Pa;try{let s=JSON.parse(e.readFileSync(o,"utf-8"));return!Array.isArray(s.scenarios)||s.scenarios.length===0?(console.log(`${D.yellow}benchmark-config.json has no scenarios \u2014 using defaults.${D.reset}
1502
1505
  `),Pa):s.scenarios}catch(s){return console.log(`${D.yellow}Failed to parse benchmark-config.json: ${s.message}${D.reset}
1503
- `),Pa}}function iw(t,e){let{scoreMessages:n,_extractToolCalls:o,_getLastAssistantText:s}=sa(),r=n(t),i=r.score,a=[],c=s(t).toLowerCase();e.successCriteria.every(f=>c.includes(f.toLowerCase()))&&(i=Math.min(10,i+1),a.push("+1.0 all success criteria met"));let l=o(t);l.length<e.maxTurns/2&&(i=Math.min(10,i+.5),a.push(`+0.5 efficient (${l.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 eA(t,e={}){let{spawn:n}=require("child_process"),o=require("fs"),s=require("path"),r=require("os"),i=s.join(r.tmpdir(),`nex-bench-${t.id}-${Date.now()}.txt`);o.writeFileSync(i,t.prompt,"utf-8");let a=s.resolve(__dirname,"..","bin","nex-code.js"),c=e.cwd||process.cwd(),u=[a,"--prompt-file",i,"--delete-prompt-file","--auto","--max-turns",String(t.maxTurns)];return e.model&&u.push("--model",e.model),new Promise(l=>{let d=n(process.execPath,u,{cwd:c,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{o.unlinkSync(i)}catch{}let w=s.join(c,".nex","sessions","_autosave.json"),_=[];if(o.existsSync(w))try{_=JSON.parse(o.readFileSync(w,"utf-8")).messages||[]}catch{}l({messages:_,exitCode:g||0,timedOut:p})}),d.stdout.resume(),d.stderr.resume()})}function tA(t,e,n){let o=t.length>0?Math.round(t.reduce((c,u)=>c+u.score,0)/t.length*10)/10:0,s=o>=9?"A":o>=8?"B":o>=7?"C":o>=6?"D":"F",r=57,i="\u2500".repeat(r);console.log(`
1506
+ `),Pa}}function iw(t,e){let{scoreMessages:n,_extractToolCalls:o,_getLastAssistantText:s}=sa(),r=n(t),i=r.score,a=[],c=s(t).toLowerCase();e.successCriteria.every(f=>c.includes(f.toLowerCase()))&&(i=Math.min(10,i+1),a.push("+1.0 all success criteria met"));let l=o(t);l.length<e.maxTurns/2&&(i=Math.min(10,i+.5),a.push(`+0.5 efficient (${l.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 tA(t,e={}){let{spawn:n}=require("child_process"),o=require("fs"),s=require("path"),r=require("os"),i=s.join(r.tmpdir(),`nex-bench-${t.id}-${Date.now()}.txt`);o.writeFileSync(i,t.prompt,"utf-8");let a=s.resolve(__dirname,"..","bin","nex-code.js"),c=e.cwd||process.cwd(),u=[a,"--prompt-file",i,"--delete-prompt-file","--auto","--max-turns",String(t.maxTurns)];return e.model&&u.push("--model",e.model),new Promise(l=>{let d=n(process.execPath,u,{cwd:c,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{o.unlinkSync(i)}catch{}let w=s.join(c,".nex","sessions","_autosave.json"),_=[];if(o.existsSync(w))try{_=JSON.parse(o.readFileSync(w,"utf-8")).messages||[]}catch{}l({messages:_,exitCode:g||0,timedOut:p})}),d.stdout.resume(),d.stderr.resume()})}function nA(t,e,n){let o=t.length>0?Math.round(t.reduce((c,u)=>c+u.score,0)/t.length*10)/10:0,s=o>=9?"A":o>=8?"B":o>=7?"C":o>=6?"D":"F",r=57,i="\u2500".repeat(r);console.log(`
1504
1507
  \u250C\u2500 Benchmark Results ${"\u2500".repeat(r-19)}\u2510`);for(let c of t){let u=c.id.padEnd(20),l=c.name.substring(0,26).padEnd(26),d=`${c.score}/10`.padStart(6),f=c.grade.padStart(2);console.log(`\u2502 ${u} ${l} ${d} ${f} \u2502`)}console.log(`\u2502 ${" ".repeat(r-2)} \u2502`);let a=`Overall: ${o}/10 (${s}) \xB7 v${e} \xB7 ${n}`;console.log(`\u2502 ${a.substring(0,r-4).padEnd(r-4)} \u2502`),console.log(`\u2514${"\u2500".repeat(r+1)}\u2518
1505
- `)}function nA(t=10){let e=require("fs"),o=require("path").join(process.cwd(),".nex","benchmark-history.json");if(!e.existsSync(o)){console.log(`${D.yellow}No score history yet. Run a session first.${D.reset}
1508
+ `)}function sA(t=10){let e=require("fs"),o=require("path").join(process.cwd(),".nex","benchmark-history.json");if(!e.existsSync(o)){console.log(`${D.yellow}No score history yet. Run a session first.${D.reset}
1506
1509
  `);return}let s=[];try{s=JSON.parse(e.readFileSync(o,"utf-8"))}catch{s=[]}if(!Array.isArray(s)||s.length===0){console.log(`${D.yellow}Score history is empty.${D.reset}
1507
1510
  `);return}let r=s.slice(-t);console.log(`
1508
- ${D.bold}Score History (last ${r.length} session${r.length===1?"":"s"}):${D.reset}`);for(let i of r){let a=(i.date||"").replace("T"," ").substring(0,16),c=(i.version||"?").padEnd(8),u=(i.model||"?").substring(0,12).padEnd(12),l=`${i.score}/10`.padStart(6),d=i.grade||"?",f=i.issues&&i.issues.length>0?`${D.yellow}\u26A0 ${i.issues.slice(0,2).map(h=>h.substring(0,30)).join(", ")}${D.reset}`:`${D.green}\u2713${D.reset}`,p=i.score>=8?D.green:i.score>=6?D.yellow:D.red;console.log(` ${D.dim}${a}${D.reset} ${D.dim}v${c}${D.reset} ${D.dim}${u}${D.reset} ${p}${l} ${d}${D.reset} ${f}`)}console.log()}async function sA({dryRun:t=!1,model:e,cwd:n,onProgress:o}={}){let s=Ur(),r=rw(n);if(t){console.log(`
1511
+ ${D.bold}Score History (last ${r.length} session${r.length===1?"":"s"}):${D.reset}`);for(let i of r){let a=(i.date||"").replace("T"," ").substring(0,16),c=(i.version||"?").padEnd(8),u=(i.model||"?").substring(0,12).padEnd(12),l=`${i.score}/10`.padStart(6),d=i.grade||"?",f=i.issues&&i.issues.length>0?`${D.yellow}\u26A0 ${i.issues.slice(0,2).map(h=>h.substring(0,30)).join(", ")}${D.reset}`:`${D.green}\u2713${D.reset}`,p=i.score>=8?D.green:i.score>=6?D.yellow:D.red;console.log(` ${D.dim}${a}${D.reset} ${D.dim}v${c}${D.reset} ${D.dim}${u}${D.reset} ${p}${l} ${d}${D.reset} ${f}`)}console.log()}async function oA({dryRun:t=!1,model:e,cwd:n,onProgress:o}={}){let s=Ur(),r=rw(n);if(t){console.log(`
1509
1512
  ${D.bold}Scenario Benchmark \u2014 Scenarios (dry-run):${D.reset}
1510
1513
  `);for(let c of r)console.log(` ${D.cyan}${c.id.padEnd(20)}${D.reset} ${D.dim}${c.name}${D.reset} maxTurns=${c.maxTurns}`),console.log(` ${D.dim}${c.prompt.substring(0,80)}${D.reset}`);return console.log(),[]}let i=(()=>{if(e)return typeof e=="object"?e.id||"unknown":e;try{let{getActiveModel:c}=Ao(),u=c?c():null;return u?typeof u=="object"?u.id||"unknown":u:"unknown"}catch{return"unknown"}})(),a=[];for(let c of r){o?.({id:c.id,name:c.name,done:!1}),console.log(`
1511
- ${D.dim}Running scenario: ${c.name}...${D.reset}`);let{messages:u,timedOut:l}=await eA(c,{model:i,cwd:n}),d;l||u.length===0?d={score:0,grade:"F",issues:[l?"Scenario timed out":"No messages produced"],summary:"No output",bonuses:[]}:d=iw(u,c);let f={id:c.id,name:c.name,score:d.score,grade:d.grade,issues:d.issues,bonuses:d.bonuses};a.push(f),o?.({id:c.id,name:c.name,done:!0,score:d.score,grade:d.grade});try{let{appendScoreHistory:p}=sa();p(d.score,{version:s.version,model:i,sessionName:`bench:${c.id}`,issues:d.issues})}catch{}}return tA(a,s.version,i),a}module.exports={runBenchmark:ZC,runDiscoverBenchmark:QC,buildSummary:Zu,buildCategoryWinners:tw,TASKS:Vu,PHASE_TASKS:Z0,ALL_TASKS:La,scoreResult:So,DEFAULT_MODELS:Ju,QUICK_MODELS:Q0,runScenarioBenchmark:sA,showScoreTrend:nA,loadScenarios:rw,DEFAULT_SCENARIOS:Pa,scoreScenario:iw};
1514
+ ${D.dim}Running scenario: ${c.name}...${D.reset}`);let{messages:u,timedOut:l}=await tA(c,{model:i,cwd:n}),d;l||u.length===0?d={score:0,grade:"F",issues:[l?"Scenario timed out":"No messages produced"],summary:"No output",bonuses:[]}:d=iw(u,c);let f={id:c.id,name:c.name,score:d.score,grade:d.grade,issues:d.issues,bonuses:d.bonuses};a.push(f),o?.({id:c.id,name:c.name,done:!0,score:d.score,grade:d.grade});try{let{appendScoreHistory:p}=sa();p(d.score,{version:s.version,model:i,sessionName:`bench:${c.id}`,issues:d.issues})}catch{}}return nA(a,s.version,i),a}module.exports={runBenchmark:QC,runDiscoverBenchmark:eA,buildSummary:Qu,buildCategoryWinners:tw,TASKS:Ju,PHASE_TASKS:Z0,ALL_TASKS:La,scoreResult:So,DEFAULT_MODELS:Zu,QUICK_MODELS:Q0,runScenarioBenchmark:oA,showScoreTrend:sA,loadScenarios:rw,DEFAULT_SCENARIOS:Pa,scoreScenario:iw};