nex-code 0.5.16 → 0.5.17

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,47 +1,47 @@
1
- "use strict";var Ka=Object.defineProperty;var jw=Object.getOwnPropertyDescriptor;var Dw=Object.getOwnPropertyNames;var qw=Object.prototype.hasOwnProperty;var Fw=(t,e)=>()=>(t&&(e=t(t=0)),e);var Q=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Bw=(t,e)=>{for(var n in e)Ka(t,n,{get:e[n],enumerable:!0})},Uw=(t,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Dw(e))!qw.call(t,s)&&s!==n&&Ka(t,s,{get:()=>e[s],enumerable:!(o=jw(e,s))||o.enumerable});return t};var Ww=t=>Uw(Ka({},"__esModule",{value:!0}),t);var Xt=Q((lA,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 Hw(){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 Yw(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 Gw(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 zw(){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=Yw(n);if(o!==null)return o;let s=Hw(),r=s!==null?s:!0;return Gw(n,r),r}var bd=zw(),$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)},Kw=bd?$d:_d;xd.exports={T:Kw,isDark:bd,DARK:$d,LIGHT:_d}});var Ur=Q((uA,Xw)=>{Xw.exports={name:"nex-code",version:"0.5.16",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((dA,Rd)=>{var{T:J}=Xt(),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}
1
+ "use strict";var Va=Object.defineProperty;var Fw=Object.getOwnPropertyDescriptor;var Bw=Object.getOwnPropertyNames;var Uw=Object.prototype.hasOwnProperty;var Ww=(t,e)=>()=>(t&&(e=t(t=0)),e);var Q=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Hw=(t,e)=>{for(var n in e)Va(t,n,{get:e[n],enumerable:!0})},Yw=(t,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Bw(e))!Uw.call(t,s)&&s!==n&&Va(t,s,{get:()=>e[s],enumerable:!(o=Fw(e,s))||o.enumerable});return t};var Gw=t=>Yw(Va({},"__esModule",{value:!0}),t);var Xt=Q((mA,Sd)=>{"use strict";var bd="\x1B[0m",$d="\x1B[1m",qs="\x1B[2m";function V(t,e,n){return`\x1B[38;2;${t};${e};${n}m`}function zw(){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 _d(){let t=require("os");return require("path").join(t.homedir(),".nex-code",".theme_cache.json")}function Kw(t){try{let n=require("fs").readFileSync(_d(),"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 Xw(t,e){try{let n=require("fs"),o=require("path"),s=_d(),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 Vw(){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=Kw(n);if(o!==null)return o;let s=zw(),r=s!==null?s:!0;return Xw(n,r),r}var xd=Vw(),kd={reset:bd,bold:$d,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)},vd={reset:bd,bold:$d,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)},Jw=xd?kd:vd;Sd.exports={T:Jw,isDark:xd,DARK:kd,LIGHT:vd}});var Ur=Q((gA,Zw)=>{Zw.exports={name:"nex-code",version:"0.5.17",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 --runInBand","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 Gn=Q((yA,Od)=>{var{T:J}=Xt(),Ja=5,Fs=(()=>{let t=[];for(let e=0;e<Ja;e++)t.push(e);for(let e=Ja-2;e>=1;e--)t.push(e);return t})(),Ed=["\u273D","\u2726","\u2727","\u2726"],Td=["\xB7 ","\xB7\xB7 ","\xB7\xB7\xB7"," \xB7\xB7"];function Rd(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 Cd(t,e,n){let o="";for(let s=0;s<Ja;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 Ad(t){return`${J.dim}${Td[t%Td.length]}${J.reset}`}var Za=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=Rd(this.text),o=Cd(e,n.glyph,n.color),s=Ad(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}},Qa=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=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}
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,ec=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=Ed[this.frame%Ed.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=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 Vw(t){On=t}function Jw(){return On}function Zw(){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:Vw,getActiveTaskProgress:Jw,cleanupTerminal:Zw}});var Yr=Q((fA,Md)=>{"use strict";var{T:Gn}=Xt(),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"])},Qw={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 Qw[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 eb(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 tb(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 nb(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 eb(t);if(e==="html"||e==="xml")return tb(t);if(e==="css")return nb(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 sb(t,e){let n=Od(e);if(!n)return t.split(`
13
+ `}process.stderr.write(i)}},tc=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=Rd(this.message),o=Cd(e,n.glyph,n.color),s=Ad(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 Qw(t){On=t}function eb(){return On}function tb(){On&&(On.stop(),On=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}Od.exports={C:J,Spinner:Za,MultiProgress:Qa,TaskProgress:ec,ToolProgress:tc,setActiveTaskProgress:Qw,getActiveTaskProgress:eb,cleanupTerminal:tb}});var Yr=Q((wA,Id)=>{"use strict";var{T:zn}=Xt(),me={kw:zn.syn_keyword,str:zn.syn_string,cmt:zn.syn_comment,num:zn.syn_number,type:zn.cyan,punct:zn.magenta,reset:zn.reset},Nd={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"])},nb={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 Pd(t){if(!t)return null;let e=t.split(".").pop().toLowerCase();return nb[e]||null}var Md=/\x1b\[[0-9;]*m/g;function $n(t,e,n){let o=t.split(Md),s=t.match(Md)||[],r="";for(let i=0;i<o.length;i++)r+=o[i].replace(e,n),i<s.length&&(r+=s[i]);return r}function sb(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 ob(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 rb(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 Ld(t,e,n){if(e==="json")return sb(t);if(e==="html"||e==="xml")return ob(t);if(e==="css")return rb(t);if(e==="md")return t;let o=Nd[e]||Nd.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 ib(t,e){let n=Pd(e);if(!n)return t.split(`
14
14
  `);let o=t.split(`
15
- `),s={inString:null,inBlockComment:!1};return o.map(r=>Nd(r,n,s))}function ob(t,e){return e?Nd(t,e,{inString:null,inBlockComment:!1}):t}Md.exports={detectLang:Od,highlightLine:ob,highlightLines:sb}});var Wd=Q((pA,Ud)=>{var{T:$}=Xt(),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 rb={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"},ib={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 ib[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 ab(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]||ab(t)}function cb(t){return String(t||"").split(`
16
- `).map(e=>{let n=e.match(/^(\d+):\s?(.*)$/s);return n?{lineNumber:n[1],content:n[2]||""}:null}).filter(Boolean)}function lb(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
- `)}function ub(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=>ub(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
- `)}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 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 db(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=rb[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 fb(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=db(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 pb(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
- ${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=Bd(e.path,e.patches,{indent:" ",maxPatches:2,maxLinesPerSide:1,maxContent:90});return i?`${r}
24
- ${i}`:r}return r}function hb(t,e=8){let n=t.split(`
15
+ `),s={inString:null,inBlockComment:!1};return o.map(r=>Ld(r,n,s))}function ab(t,e){return e?Ld(t,e,{inString:null,inBlockComment:!1}):t}Id.exports={detectLang:Pd,highlightLine:ab,highlightLines:ib}});var Gd=Q((bA,Yd)=>{var{T:$}=Xt(),Ie=$,jd=require("path"),Dd=["\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 cb={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},Ud={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"},lb={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 sc(t){return lb[t]||{label:"Run",accent:$.tool_default,icon:"\u2022"}}function qd(t){let e=sc(t);return`${e.accent}${Ie.bold}${e.icon} ${e.label.toUpperCase()}${$.reset}`}function ub(t){return t.replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase())}function Fd(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):Ud[t]||ub(t)}function db(t){return String(t||"").split(`
16
+ `).map(e=>{let n=e.match(/^(\d+):\s?(.*)$/s);return n?{lineNumber:n[1],content:n[2]||""}:null}).filter(Boolean)}function fb(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
+ `)}function pb(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 nc(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=>pb(a,o));return{shown:i,more:Math.max(0,r.length-i.length)}}function Wd(t,e={}){let{indent:n=" ",maxLines:o=2,maxContent:s=100}=e;if(!t)return"";let{shown:r,more:i}=nc(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
+ `)}function oc(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}=nc(e,{maxLines:r,maxContent:i}),{shown:p,more:h}=nc(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 Hd(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=oc(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 hb(t){let e=new Set,n=[];for(let o of t){let s=sc(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=cb[t]||$.tool_default;if(n==="blink")return`${o}\x1B[5m\u23FA\x1B[25m${$.reset}`;let s=typeof n=="number"?Dd[n%Dd.length]:n!==null?n:"\u23FA";return`${o}${s}${$.reset}`}function mb(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=Fd(u.fnName,{...l,path:l._originalPath||l.path});return`${Gr(u.fnName,n,o)} ${qd(u.fnName)} ${Ie.bold}${d}${Ie.reset}`}let r=s[0].fnName,i=hb(s)||`${s.length} tools`,a=s.slice(0,2).map(u=>Fd(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)} ${qd(r)} ${Ie.bold}${i}${Ie.reset}${c}`}function gb(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=Ud[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=Wd(e.command,{indent:" ",maxLines:2,maxContent:108});return i?`${r}
22
+ ${i}`:r}if(t==="edit_file"){let i=oc(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=Hd(e.path,e.patches,{indent:" ",maxPatches:2,maxLinesPerSide:1,maxContent:90});return i?`${r}
24
+ ${i}`:r}return r}function yb(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"],Dd=Math.floor(Math.random()*Kr.length),mb=null;function gb(t){mb=t}function yb(){let t=Kr[Dd%Kr.length];return Dd++,t}function wb(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 bb(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"],Bd=Math.floor(Math.random()*Kr.length),wb=null;function bb(t){wb=t}function $b(){let t=Kr[Bd%Kr.length];return Bd++,t}function _b(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 xb(t,e,n,o){let s=String(n||""),r=sc(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=cb(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=lb(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=db(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?jd.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=fb(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?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(`
31
+ `).length,d=e.path?jd.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}
35
35
  ${_}
36
36
  ${$.subtle}\u2026 +${l-w} lines${$.reset}`}break}case"edit_file":{let u=(e.old_text||"").split(`
37
37
  `),l=(e.new_text||"").split(`
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?`
38
+ `),d=u.length,f=l.length,p=e.path?zr(e.path):null,h=p?` ${$.muted}${p}${$.reset}`:"",g=oc(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=Bd(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=Hd(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=Fd(e.command,{indent:" ",maxLines:2,maxContent:108});h&&(a=`${h}
44
+ `)}let h=Wd(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}${_}
@@ -60,96 +60,96 @@ ${g.join(`
60
60
  `)[0].replace(/^\d+\.\s*/,"").trim():null,f=d?` ${$.muted}\u2014 ${d.substring(0,70)}${$.reset}`:"";a=`${l} result${l!==1?"s":""}${f}`;break}case"task_list":a="Done";break;case"spawn_agents":{if(s.includes("Background agents started")){let d=s.match(/\bbg-[\w-]+/g),f=d?d.length:0;a=`${f} bg agent${f!==1?"s":""} started`;break}let u=(s.match(/✓ Agent/g)||[]).length,l=(s.match(/✗ Agent/g)||[]).length;a=l>0?`${u} done, ${l} failed`:`${u} agent${u!==1?"s":""} done`;break}case"switch_model":{let u=s.match(/Switched to (.+)/);a=u?`\u2192 ${u[1]}`:"Done";break}case"ssh_exec":{let l=s.startsWith("EXIT ")||s.startsWith("Command failed"),d=s.split(`
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
- `).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 $b(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}Ud.exports={C:Ie,formatToolCall:pb,formatResult:hb,getToolSpinnerText:wb,formatToolSummary:bb,formatSectionHeader:fb,formatMilestone:$b,getThinkingVerb:yb,setActiveModelForSpinner:gb,THINKING_VERBS:Kr}});var rt=Q((hA,Yd)=>{var{T:rn}=Xt(),sc=rn,_b=require("path"),Hd=["01100110","01111110","01111110","01011010","01111110","00111100"];function xb(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 kb(t,e,n={}){let o=sc.bold,s=sc.reset,r=xb(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(`
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 kb(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}Yd.exports={C:Ie,formatToolCall:gb,formatResult:yb,getToolSpinnerText:_b,formatToolSummary:xb,formatSectionHeader:mb,formatMilestone:kb,getThinkingVerb:$b,setActiveModelForSpinner:bb,THINKING_VERBS:Kr}});var it=Q(($A,Kd)=>{var{T:an}=Xt(),rc=an,vb=require("path"),zd=["01100110","01111110","01111110","01011010","01111110","00111100"];function Sb(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 Eb(t,e,n={}){let o=rc.bold,s=rc.reset,r=Sb(zd,an.banner_logo),i=n.yolo?` ${o}${an.banner_yolo}\u26A1 YOLO${s}`:"",a=n.gemini?` ${o}${an.banner_gemini}\u2726 GEMINI${s}`:"",c=Ur().version,u=e?vb.basename(e):null,l=`${an.banner_model}[${t||"model"}]${s}`,d=`${an.banner_version}[${u||"workspace"}]${s}`,f=[` ${an.banner_name}${o}nex-code${s} ${an.banner_version}v${c}${s}`,` ${l} ${d}`,` ${an.banner_logo}${o}terminal workbench${s} ${an.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=zd[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:vb,MultiProgress:Sb,TaskProgress:Eb,ToolProgress:Tb,setActiveTaskProgress:Rb,getActiveTaskProgress:Cb,cleanupTerminal:Ab}=Yn(),{formatToolCall:Ob,formatResult:Nb,getToolSpinnerText:Mb,formatToolSummary:Pb,formatSectionHeader:Lb,formatMilestone:Ib,getThinkingVerb:jb,setActiveModelForSpinner:Db}=Wd();Yd.exports={C:sc,banner:kb,Spinner:vb,MultiProgress:Sb,TaskProgress:Eb,ToolProgress:Tb,setActiveTaskProgress:Rb,getActiveTaskProgress:Cb,cleanupTerminal:Ab,formatToolCall:Ob,formatResult:Nb,getToolSpinnerText:Mb,formatToolSummary:Pb,formatSectionHeader:Lb,formatMilestone:Ib,getThinkingVerb:jb,setActiveModelForSpinner:Db}});var Bs=Q((mA,Gd)=>{async function qb(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:qb}});var Hs=Q((gA,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)}},Fb=new Vr,Bb=new Zr,Ub=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:Fb,anthropicProtocol:Bb,ollamaProtocol:Ub}});var Jd=Q((yA,Vd)=>{var ti=require("axios"),Wb=require("http"),Hb=require("https"),{BaseProvider:Yb,readStreamErrorBody:Gb}=Bs(),{ollamaProtocol:zn}=Hs(),ni=new Wb.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),si=new Hb.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 Yb{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 Gb(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((wA,ef)=>{var Zd=require("axios"),{BaseProvider:zb,readStreamErrorBody:Kb}=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 zb{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 Kb(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((bA,of)=>{var nf=require("axios"),{BaseProvider:Xb,readStreamErrorBody:Vb}=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}},Jb="2023-06-01",cc=class extends Xb{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||Jb}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 Vb(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(($A,lf)=>{var af=require("axios"),{BaseProvider:Zb,readStreamErrorBody:Qb}=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 Zb{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 Qb(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((_A,ff)=>{var oi=require("axios"),{BaseProvider:e$,readStreamErrorBody:t$}=Bs(),{ollamaProtocol:Vn}=Hs(),df="http://localhost:11434",uc=class extends e${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 t$(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((xA,mf)=>{"use strict";var Ct=require("fs"),hf=require("path");function n$(t){if(!t||isNaN(t))return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function s$(t){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}catch{let e=Date.now()+t;for(;Date.now()<e;);}}function o$(t,e){let n=hf.dirname(t),o=hf.join(n,`.nex-tmp.${process.pid}.${Date.now()}`);try{Ct.existsSync(n)||Ct.mkdirSync(n,{recursive:!0,mode:448}),Ct.writeFileSync(o,e,{encoding:"utf-8",mode:384}),Ct.renameSync(o,t)}catch(s){try{Ct.unlinkSync(o)}catch{}throw s}}function r$(t,e,{timeout:n=5e3,retryMs:o=50}={}){let s=t+".lock",r=Date.now()+n;for(;;){let i=-1;try{i=Ct.openSync(s,"wx"),Ct.writeSync(i,Buffer.from(String(process.pid))),Ct.closeSync(i),i=-1;try{return e()}finally{try{Ct.unlinkSync(s)}catch{}}}catch(a){if(i!==-1)try{Ct.closeSync(i)}catch{}if(a.code!=="EEXIST")throw a;try{let c=Ct.readFileSync(s,"utf-8").trim(),u=parseInt(c,10);if(!n$(u)){try{Ct.unlinkSync(s)}catch{}continue}}catch(c){if(c.code&&c.code!=="ENOENT")throw c;continue}if(Date.now()>=r){try{Ct.unlinkSync(s)}catch{}return e()}s$(o)}}}mf.exports={atomicWrite:o$,withFileLockSync:r$}});var ii=Q((kA,kf)=>{var Ys=require("fs"),dc=require("path"),{T:gf}=Xt(),{atomicWrite:i$,withFileLockSync:a$}=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 c$(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 l$(){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 u$(t){return!t||typeof t!="string"?0:Math.ceil(t.length/4)}function d$(t,e,n,o){let s=fc(t,e),r=(n*s.input+o*s.output)/1e6;return r<=0?"":`[~$${r.toFixed(4)}]`}function f$(){ri=[]}function p$(t,e){Mn[t]=e}function h$(t){delete Mn[t]}function m$(){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 g$(){let t=dc.join(process.cwd(),".nex"),e=dc.join(t,"config.json");Ys.existsSync(t)||Ys.mkdirSync(t,{recursive:!0}),a$(e,()=>{let n={};if(Ys.existsSync(e))try{n=JSON.parse(Ys.readFileSync(e,"utf-8"))}catch{n={}}n.costLimits=Mn,i$(e,JSON.stringify(n,null,2))})}function y$(){Mn={}}xf();kf.exports={PRICING:yf,trackUsage:c$,getSessionCosts:bf,formatCosts:l$,formatCostHint:d$,resetCosts:f$,getPricing:fc,setCostLimit:p$,removeCostLimit:h$,getCostLimits:m$,getProviderSpend:$f,checkBudget:_f,loadCostLimits:xf,saveCostLimits:g$,resetCostLimits:y$,estimateTokens:u$}});var hc=Q((vA,vf)=>{function pc(){return process.env.NEX_DEBUG==="true"||process.argv.includes("--debug")}var w$=pc();function b$(...t){pc()&&console.log(...t)}function $$(...t){pc()&&console.warn(...t)}vf.exports={DEBUG:w$,debugLog:b$,warnLog:$$}});var Tf=Q((SA,Ef)=>{"use strict";var _$=new Set(["read_file","grep","glob","search_files","list_directory"]),x$=new Set(["write_file","edit_file","patch_file"]),k$=new Set(["bash"]),v$=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),x$.has(a)&&(o+=c),k$.has(a)&&(s+=c),v$.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((EA,Rf)=>{var Co=ct(),S$={"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 E$(){return Co.getActiveModel()}function T$(t){return Co.setActiveModel(t)}function R$(){return Co.getModelNames()}function C$(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 A$(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 O$(t,e){return Co.callChat(t,e)}Rf.exports={MODELS:S$,getActiveModel:E$,setActiveModel:T$,getModelNames:R$,callOllamaStream:A$,callOllama:O$,parseToolArgs:C$}});var No=Q((TA,Pf)=>{var N$=require("readline"),{C:an}=rt(),M$=/[\u200B\u200C\u200D\uFEFF\u2060\u00AD]/g,P$=/^=([\w-]+)/;function Oo(t){return typeof t!="string"?t:t.replace(M$,"").replace(P$,"$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 L$(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)/],I$=/\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 j$(t){$c=t}function D$(t){yc=t}function q$(){return $c}function F$(t){Zn=t}function B$(t){let e=Oo(t);for(let n of wc)if(n.test(e))return n;return null}function U$(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 W$(t){let e=Oo(t);for(let n of bc)if(n.test(e))return!0;return!1}function H$(t){if(process.env.NEX_UNPROTECT==="1")return null;let e=Oo(t);if(!I$.test(e))return null;for(let n of Af)if(n.test(e))return n;return null}function Y$(t,e={}){if($c)return Promise.resolve(!0);if(yc)return yc(t,e);if(!process.stdout.isTTY||!process.stdin.isTTY)return G$(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 G$(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=N$.createInterface({input:process.stdin,output:process.stdout});r.question(`${an.yellow}${t} ${n}${an.reset}`,i=>{r.close(),s(i)})}})}var ai=()=>{};function z$(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:B$,isSSHForbidden:L$,isDangerous:U$,isCritical:W$,isBashPathForbidden:H$,confirm:Y$,setAutoConfirm:j$,getAutoConfirm:q$,setConfirmHook:D$,setReadlineInterface:F$,setAllowAlwaysHandler:z$}});var jf=Q((CA,If)=>{var ci=require("path"),{C:q}=rt(),{T:_c,isDark:RA}=Xt(),{confirm:K$,getAutoConfirm:X$}=No(),Lf=2e3;function Mo(t,e){let n=t.split(`
67
+ `)}var{Spinner:Tb,MultiProgress:Rb,TaskProgress:Cb,ToolProgress:Ab,setActiveTaskProgress:Ob,getActiveTaskProgress:Nb,cleanupTerminal:Mb}=Gn(),{formatToolCall:Pb,formatResult:Lb,getToolSpinnerText:Ib,formatToolSummary:jb,formatSectionHeader:Db,formatMilestone:qb,getThinkingVerb:Fb,setActiveModelForSpinner:Bb}=Gd();Kd.exports={C:rc,banner:Eb,Spinner:Tb,MultiProgress:Rb,TaskProgress:Cb,ToolProgress:Ab,setActiveTaskProgress:Ob,getActiveTaskProgress:Nb,cleanupTerminal:Mb,formatToolCall:Pb,formatResult:Lb,getToolSpinnerText:Ib,formatToolSummary:jb,formatSectionHeader:Db,formatMilestone:qb,getThinkingVerb:Fb,setActiveModelForSpinner:Bb}});var Bs=Q((_A,Xd)=>{async function Ub(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 ic=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`)}};Xd.exports={BaseProvider:ic,readStreamErrorBody:Ub}});var Hs=Q((xA,Jd)=>{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}}})}}},ac="<!-- 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(ac);if(l!==-1){let d=u.slice(0,l).trimEnd(),f=u.slice(l+ac.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 Vd(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:Vd(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:Vd(o.function?.arguments??o.arguments)}}))}}createStreamParser(e,n={}){return new Qr(e,n)}},Wb=new Vr,Hb=new Zr,Yb=new ei;Jd.exports={ANTHROPIC_CACHE_BOUNDARY:ac,WireProtocol:Us,StreamParser:Ws,OpenAICompatibleProtocol:Vr,AnthropicProtocol:Zr,OllamaChatProtocol:ei,OpenAIStreamParser:Xr,AnthropicStreamParser:Jr,OllamaStreamParser:Qr,openaiProtocol:Wb,anthropicProtocol:Hb,ollamaProtocol:Yb}});var Qd=Q((kA,Zd)=>{var ti=require("axios"),Gb=require("http"),zb=require("https"),{BaseProvider:Kb,readStreamErrorBody:Xb}=Bs(),{ollamaProtocol:Kn}=Hs(),ni=new Gb.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),si=new zb.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),oi={"qwen3-coder:480b":{id:"qwen3-coder:480b",name:"Qwen3 Coder 480B",maxTokens:16384,contextWindow:131072,capability:"agentic",speed:"balanced",quality:98,recommendedFor:["coding","agentic","refactor"]},"qwen3-coder-next":{id:"qwen3-coder-next",name:"Qwen3 Coder Next",maxTokens:16384,contextWindow:262144,capability:"agentic",speed:"balanced",quality:97,recommendedFor:["coding","agentic","large-context"]},"devstral-2:123b":{id:"devstral-2:123b",name:"Devstral 2 123B",maxTokens:16384,contextWindow:131072,capability:"agentic",speed:"balanced",quality:94,recommendedFor:["coding","sysadmin","agentic"]},"devstral-small-2:24b":{id:"devstral-small-2:24b",name:"Devstral Small 2 24B",maxTokens:16384,contextWindow:131072,capability:"fast-coding",speed:"fast",quality:82,recommendedFor:["quick-fix","sysadmin","fallback"]},"minimax-m2.7:cloud":{id:"minimax-m2.7:cloud",name:"MiniMax M2.7 Cloud",maxTokens:16384,contextWindow:131072,capability:"general",speed:"balanced",quality:90,recommendedFor:["coding","reasoning"]},"kimi-k2.5":{id:"kimi-k2.5",name:"Kimi K2.5",maxTokens:16384,contextWindow:256e3,capability:"reasoning",speed:"balanced",quality:96,recommendedFor:["reasoning","large-context","review"]},"kimi-k2:1t":{id:"kimi-k2:1t",name:"Kimi K2 1T",maxTokens:16384,contextWindow:256e3,capability:"reasoning",speed:"deliberate",quality:99,recommendedFor:["reasoning","architecture","review"]},"kimi-k2-thinking":{id:"kimi-k2-thinking",name:"Kimi K2 Thinking",maxTokens:16384,contextWindow:256e3,capability:"reasoning",speed:"deliberate",quality:98,recommendedFor:["reasoning","debugging","review"]},"deepseek-v3.2":{id:"deepseek-v3.2",name:"DeepSeek V3.2",maxTokens:16384,contextWindow:131072,capability:"general",speed:"balanced",quality:94,recommendedFor:["coding","reasoning","fallback"]},"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,capability:"vision-language",speed:"balanced",quality:95,recommendedFor:["frontend","vision","large-context"]},"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,capability:"fast-coding",speed:"fast",quality:84,recommendedFor:["quick-fix","coding","fallback"]},"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,capability:"fast-coding",speed:"fast",quality:86,recommendedFor:["quick-fix","coding"]},"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,capability:"open-reasoning",speed:"balanced",quality:88,recommendedFor:["open-source","reasoning","coding"]},"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,capability:"fast-coding",speed:"fast",quality:78,recommendedFor:["quick-fix","fallback"]},"ministral-3:8b":{id:"ministral-3:8b",name:"Ministral 3 8B",maxTokens:8192,contextWindow:131072,capability:"fast",speed:"very-fast",quality:72,recommendedFor:["quick-fix","fallback"]},"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}},cc={coding:["qwen3-coder:480b","qwen3-coder-next","devstral-2:123b"],agentic:["qwen3-coder:480b","qwen3-coder-next","devstral-2:123b"],reasoning:["kimi-k2:1t","kimi-k2-thinking","kimi-k2.5"],"large-context":["qwen3-coder-next","qwen3.5:397b-cloud","kimi-k2.5"],frontend:["qwen3.5:397b-cloud","qwen3-coder-next","qwen3-coder:480b"],"quick-fix":["devstral-small-2:24b","qwen3-next:80b","ministral-3:14b"],fallback:["devstral-small-2:24b","deepseek-v3.2","qwen3.5:35b-a3b"],"open-source":["qwen3-coder:480b","devstral-2:123b","gpt-oss:120b"]};function Vb(t="coding",e=5){let n=cc[t]||cc.coding;return n.map(s=>oi[s]).filter(Boolean).concat(Object.values(oi).filter(s=>!n.includes(s.id)).filter(s=>(s.recommendedFor||[]).includes(t))).sort((s,r)=>(r.quality||0)-(s.quality||0)).slice(0,e)}var lc=class extends Kb{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||oi,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=Kn.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}${Kn.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 Kn.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=Kn.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}${Kn.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 Xb(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=Kn.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 Kn.normalizeResponse(e)}};Zd.exports={OllamaProvider:lc,OLLAMA_MODELS:oi,OLLAMA_USE_CASES:cc,getOllamaRecommendations:Vb}});var sf=Q((vA,nf)=>{var ef=require("axios"),{BaseProvider:Jb,readStreamErrorBody:Zb}=Bs(),{openaiProtocol:Xn}=Hs(),tf={"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}},uc=class extends Jb{constructor(e={}){super({name:"openai",baseUrl:e.baseUrl||"https://api.openai.com/v1",models:e.models||tf,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=Xn.buildRequestBody({model:s,messages:a,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!1}),u;try{u=await ef.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||16384,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 ef.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)}};nf.exports={OpenAIProvider:uc,OPENAI_MODELS:tf}});var cf=Q((SA,af)=>{var of=require("axios"),{BaseProvider:Qb,readStreamErrorBody:e$}=Bs(),{anthropicProtocol:Nn}=Hs(),rf={"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}},t$="2023-06-01",dc=class extends Qb{constructor(e={}){super({name:"anthropic",baseUrl:e.baseUrl||"https://api.anthropic.com/v1",models:e.models||rf,defaultModel:e.defaultModel||"claude-sonnet",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this.apiVersion=e.apiVersion||t$}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 of.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 of.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 e$(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)}};af.exports={AnthropicProvider:dc,ANTHROPIC_MODELS:rf}});var ff=Q((EA,df)=>{var lf=require("axios"),{BaseProvider:n$,readStreamErrorBody:s$}=Bs(),{openaiProtocol:Vn}=Hs(),uf={"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}},fc=class extends n${constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||uf,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=Vn.buildRequestBody({model:s,messages:a,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!1}),u;try{u=await lf.post(`${this.baseUrl}${Vn.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 Vn.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=Vn.buildRequestBody({model:s,messages:c,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!0}),l;try{l=await lf.post(`${this.baseUrl}${Vn.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 s$(f,g=>g?.error?.message||g?.error);throw new Error(`API Error${p}: ${h}`)}let d=Vn.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 Vn.normalizeResponse(e)}};df.exports={GeminiProvider:fc,GEMINI_MODELS:uf}});var mf=Q((TA,hf)=>{var ri=require("axios"),{BaseProvider:o$,readStreamErrorBody:r$}=Bs(),{ollamaProtocol:Jn}=Hs(),pf="http://localhost:11434",pc=class extends o${constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||pf,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 ri.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 ri.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=Jn.buildRequestBody({model:s,messages:this._formatMessages(e),tools:n,maxTokens:o.maxTokens||8192,temperature:o.temperature??this.temperature,stream:!1}),i;try{i=await ri.post(`${this.baseUrl}${Jn.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 Jn.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=Jn.buildRequestBody({model:s,messages:this._formatMessages(e),tools:n,maxTokens:o.maxTokens||8192,temperature:o.temperature??this.temperature,stream:!0}),a;try{a=await ri.post(`${this.baseUrl}${Jn.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 r$(u,f=>f?.error);throw new Error(`API Error${l}: ${d}`)}let c=Jn.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 Jn.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}};hf.exports={LocalProvider:pc,DEFAULT_LOCAL_URL:pf}});var Zn=Q((RA,yf)=>{"use strict";var Ct=require("fs"),gf=require("path");function i$(t){if(!t||isNaN(t))return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function a$(t){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}catch{let e=Date.now()+t;for(;Date.now()<e;);}}function c$(t,e){let n=gf.dirname(t),o=gf.join(n,`.nex-tmp.${process.pid}.${Date.now()}`);try{Ct.existsSync(n)||Ct.mkdirSync(n,{recursive:!0,mode:448}),Ct.writeFileSync(o,e,{encoding:"utf-8",mode:384}),Ct.renameSync(o,t)}catch(s){try{Ct.unlinkSync(o)}catch{}throw s}}function l$(t,e,{timeout:n=5e3,retryMs:o=50}={}){let s=t+".lock",r=Date.now()+n;for(;;){let i=-1;try{i=Ct.openSync(s,"wx"),Ct.writeSync(i,Buffer.from(String(process.pid))),Ct.closeSync(i),i=-1;try{return e()}finally{try{Ct.unlinkSync(s)}catch{}}}catch(a){if(i!==-1)try{Ct.closeSync(i)}catch{}if(a.code!=="EEXIST")throw a;try{let c=Ct.readFileSync(s,"utf-8").trim(),u=parseInt(c,10);if(!i$(u)){try{Ct.unlinkSync(s)}catch{}continue}}catch(c){if(c.code&&c.code!=="ENOENT")throw c;continue}if(Date.now()>=r){try{Ct.unlinkSync(s)}catch{}return e()}a$(o)}}}yf.exports={atomicWrite:c$,withFileLockSync:l$}});var ai=Q((CA,Sf)=>{var Ys=require("fs"),hc=require("path"),{T:wf}=Xt(),{atomicWrite:u$,withFileLockSync:d$}=Zn(),bf={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:{}},ii=[],Mn={};function f$(t,e,n,o,s=0){if(ii.push({provider:t,model:e,input:n,output:o,cacheRead:s}),Mn[t]!==void 0){let r=kf(t);r.allowed||process.stderr.write(`${wf.yellow}\u26A0 Budget limit reached for ${t}: $${r.spent.toFixed(2)} / $${r.limit.toFixed(2)}${wf.reset}
74
+ `)}}function mc(t,e){let n=bf[t];return n?n[e]||{input:0,output:0}:{input:0,output:0}}function $f(t){let e=mc(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function _f(){let t={};for(let i of ii){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:$f(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 p$(){let{totalCost:t,totalInput:e,totalOutput:n,breakdown:o}=_f();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 h$(t){return!t||typeof t!="string"?0:Math.ceil(t.length/4)}function m$(t,e,n,o){let s=mc(t,e),r=(n*s.input+o*s.output)/1e6;return r<=0?"":`[~$${r.toFixed(4)}]`}function g$(){ii=[]}function y$(t,e){Mn[t]=e}function w$(t){delete Mn[t]}function b$(){return{...Mn}}function xf(t){let e=0;for(let n of ii)n.provider===t&&(e+=$f(n));return e}function kf(t){let e=xf(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 vf(){let t=hc.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 $$(){let t=hc.join(process.cwd(),".nex"),e=hc.join(t,"config.json");Ys.existsSync(t)||Ys.mkdirSync(t,{recursive:!0}),d$(e,()=>{let n={};if(Ys.existsSync(e))try{n=JSON.parse(Ys.readFileSync(e,"utf-8"))}catch{n={}}n.costLimits=Mn,u$(e,JSON.stringify(n,null,2))})}function _$(){Mn={}}vf();Sf.exports={PRICING:bf,trackUsage:f$,getSessionCosts:_f,formatCosts:p$,formatCostHint:m$,resetCosts:g$,getPricing:mc,setCostLimit:y$,removeCostLimit:w$,getCostLimits:b$,getProviderSpend:xf,checkBudget:kf,loadCostLimits:vf,saveCostLimits:$$,resetCostLimits:_$,estimateTokens:h$}});var yc=Q((AA,Ef)=>{function gc(){return process.env.NEX_DEBUG==="true"||process.argv.includes("--debug")}var x$=gc();function k$(...t){gc()&&console.log(...t)}function v$(...t){gc()&&console.warn(...t)}Ef.exports={DEBUG:x$,debugLog:k$,warnLog:v$}});var Cf=Q((OA,Rf)=>{"use strict";var S$=new Set(["read_file","grep","glob","search_files","list_directory"]),E$=new Set(["write_file","edit_file","patch_file"]),T$=new Set(["bash"]),R$=new Set(["web_search","web_fetch","perplexity_search"]);function Tf(t,e){let n=0,o=0,s=0,r=0,i=0;for(let[a,c]of t)i+=c,S$.has(a)&&(n+=c),E$.has(a)&&(o+=c),T$.has(a)&&(s+=c),R$.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 wc=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:Tf(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}};Rf.exports={MilestoneTracker:wc,_phaseName:Tf}});var Ao=Q((NA,Af)=>{var Co=lt(),C$={"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 A$(){return Co.getActiveModel()}function O$(t){return Co.setActiveModel(t)}function N$(){return Co.getModelNames()}function M$(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 P$(t,e){let{C:n}=it(),{Spinner:o}=it(),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 L$(t,e){return Co.callChat(t,e)}Af.exports={MODELS:C$,getActiveModel:A$,setActiveModel:O$,getModelNames:N$,callOllamaStream:P$,callOllama:L$,parseToolArgs:M$}});var No=Q((MA,If)=>{var I$=require("readline"),{C:cn}=it(),j$=/[\u200B\u200C\u200D\uFEFF\u2060\u00AD]/g,D$=/^=([\w-]+)/;function Oo(t){return typeof t!="string"?t:t.replace(j$,"").replace(D$,"$1")}var _c=[/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/],Of=[..._c,/\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 q$(t){for(let e of Of)if(e.test(t))return e;return null}var Nf=[/\.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)/],F$=/\b(?:rm|rmdir|unlink|truncate|shred|mv|cp)\b/,bc=[/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 Mf(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)):bc.some(c=>c.test(r))}return/^\w+=\$?\(/.test(i)||/^\w+=["']/.test(i)||/^\w+=\S/.test(i)?!0:bc.some(a=>a.test(i))};return o.every(s)}var xc=[/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/],Pf=[/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/],Lf=[...xc,...Pf],kc=!1,Qn=null,$c=null;function B$(t){kc=t}function U$(t){$c=t}function W$(){return kc}function H$(t){Qn=t}function Y$(t){let e=Oo(t);for(let n of _c)if(n.test(e))return n;return null}function G$(t){let e=Oo(t);if(/ssh\s/.test(e)&&Mf(e))return!1;for(let n of Lf)if(n.test(e))return!0;return!1}function z$(t){let e=Oo(t);for(let n of xc)if(n.test(e))return!0;return!1}function K$(t){if(process.env.NEX_UNPROTECT==="1")return null;let e=Oo(t);if(!F$.test(e))return null;for(let n of Nf)if(n.test(e))return n;return null}function X$(t,e={}){if(kc)return Promise.resolve(!0);if($c)return $c(t,e);if(!process.stdout.isTTY||!process.stdin.isTTY)return V$(t,e);let n=e.toolName?["Yes","No","Always allow"]:["Yes","No"];return new Promise(o=>{let s=0;Qn&&Qn.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${cn.yellow}${t}${cn.reset}`;for(let p=0;p<n.length;p++){let h=p===s,g=h?`${cn.yellow}\u276F${cn.reset}`:" ",w=h?`${cn.yellow}${n[p]}${cn.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(),Qn&&Qn.resume(),o(d)},u=d=>{if(d===1){c(!1);return}d===2&&e.toolName&&ci(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){ci(e.toolName),c(!0);return}};a(),process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",l)})}function V$(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?(ci(e.toolName),o(!0)):o(i!=="n")};if(Qn)Qn.question(`${cn.yellow}${t} ${n}${cn.reset}`,s);else{let r=I$.createInterface({input:process.stdin,output:process.stdout});r.question(`${cn.yellow}${t} ${n}${cn.reset}`,i=>{r.close(),s(i)})}})}var ci=()=>{};function J$(t){ci=t}If.exports={sanitizeBashCommand:Oo,FORBIDDEN_PATTERNS:_c,SSH_FORBIDDEN_PATTERNS:Of,BASH_PROTECTED_PATHS:Nf,SSH_SAFE_PATTERNS:bc,isSSHReadOnly:Mf,DANGEROUS_BASH:Lf,CRITICAL_BASH:xc,NOTABLE_BASH:Pf,isForbidden:Y$,isSSHForbidden:q$,isDangerous:G$,isCritical:z$,isBashPathForbidden:K$,confirm:X$,setAutoConfirm:B$,getAutoConfirm:W$,setConfirmHook:U$,setReadlineInterface:H$,setAllowAlwaysHandler:J$}});var qf=Q((LA,Df)=>{var li=require("path"),{C:q}=it(),{T:vc,isDark:PA}=Xt(),{confirm:Z$,getAutoConfirm:Q$}=No(),jf=2e3;function Mo(t,e){let n=t.split(`
78
78
  `),o=e.split(`
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 V$(t,e,n,o=3){console.log(`
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 J$(t,e,n){console.log(`
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 Z$(t,e){console.log(`
79
+ `),s=[],r=n.length,i=o.length;if(r>jf||i>jf){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 e_(t,e,n,o=3){console.log(`
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 t_(t,e,n){console.log(`
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 n_(t,e){console.log(`
82
82
  ${q.bold}${q.cyan} New file: ${t}${q.reset}`);let n=e.split(`
83
- `),o=n.slice(0,20);for(let s of o)console.log(`${q.green} + ${s}${q.reset}`);n.length>20&&console.log(`${q.gray} ...+${n.length-20} more lines${q.reset}`),console.log()}async function Q$(t){return X$()?!0:K$(` ${t}?`)}function e_(t,e,n,o){let s=o||process.stdout.columns||80,r=Math.floor((s-3)/2);console.log(`
83
+ `),o=n.slice(0,20);for(let s of o)console.log(`${q.green} + ${s}${q.reset}`);n.length>20&&console.log(`${q.gray} ...+${n.length-20} more lines${q.reset}`),console.log()}async function s_(t){return Q$()?!0:Z$(` ${t}?`)}function o_(t,e,n,o){let s=o||process.stdout.columns||80,r=Math.floor((s-3)/2);console.log(`
84
84
  ${q.bold}${q.cyan} Side-by-side: ${t}${q.reset}`),console.log(` ${q.dim}${"\u2500".repeat(r)}\u252C${"\u2500".repeat(r)}${q.reset}`);let i=Mo(e,n),a=[],c=0;for(;c<i.length;)if(i[c].type==="same")a.push({left:i[c].line,right:i[c].line,type:"same"}),c++;else if(i[c].type==="remove"){let p=[];for(;c<i.length&&i[c].type==="remove";)p.push(i[c].line),c++;let h=[];for(;c<i.length&&i[c].type==="add";)h.push(i[c].line),c++;let g=Math.max(p.length,h.length);for(let w=0;w<g;w++)a.push({left:w<p.length?p[w]:"",right:w<h.length?h[w]:"",type:"changed"})}else i[c].type==="add"&&(a.push({left:"",right:i[c].line,type:"changed"}),c++);let u=a.map((p,h)=>p.type!=="same"?h:-1).filter(p=>p>=0);if(u.length===0){console.log(` ${q.gray}(no changes)${q.reset}`);return}let l=Math.max(0,u[0]-2),d=Math.min(a.length,u[u.length-1]+3),f=(p,h)=>{let g=p.replace(/\x1b\[[0-9;]*m/g,"");return g.length>=h?p.substring(0,h):p+" ".repeat(h-g.length)};l>0&&console.log(` ${q.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${q.reset}`);for(let p=l;p<d;p++){let h=a[p];if(h.type==="same")console.log(` ${q.gray}${f(h.left,r)}${q.reset}\u2502${q.gray}${f(h.right,r)}${q.reset}`);else{let g=h.left?`${q.red}${f(h.left,r)}${q.reset}`:`${f("",r)}`,w=h.right?`${q.green}${f(h.right,r)}${q.reset}`:`${f("",r)}`;console.log(` ${g}\u2502${w}`)}}d<a.length&&console.log(` ${q.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${q.reset}`),console.log(` ${q.dim}${"\u2500".repeat(r)}\u2534${"\u2500".repeat(r)}${q.reset}
85
- `)}function t_(t,e,n,o={}){let s=o.label||"Update",r=o.context||3,i=o.annotations||[],a=ci.isAbsolute(t)?ci.relative(process.cwd(),t):t,c=Mo(e,n),u=1,l=1;for(let N of c)N.type==="same"?(N.oldLine=u++,N.newLine=l++):N.type==="remove"?(N.oldLine=u++,N.newLine=null):(N.oldLine=null,N.newLine=l++);let d=0,f=0;for(let N of c)N.type==="add"?d++:N.type==="remove"&&f++;if(console.log(`
85
+ `)}function r_(t,e,n,o={}){let s=o.label||"Update",r=o.context||3,i=o.annotations||[],a=li.isAbsolute(t)?li.relative(process.cwd(),t):t,c=Mo(e,n),u=1,l=1;for(let N of c)N.type==="same"?(N.oldLine=u++,N.newLine=l++):N.type==="remove"?(N.oldLine=u++,N.newLine=null):(N.oldLine=null,N.newLine=l++);let d=0,f=0;for(let N of c)N.type==="add"?d++:N.type==="remove"&&f++;if(console.log(`
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
- `);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 n_(t,e,n={}){let o=ci.isAbsolute(t)?ci.relative(process.cwd(),t):t,s=e.split(`
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(vc.diff_rem_bg,q.red,`${A}${le} - ${fe.line}`)):fe.type==="add"?console.log(v(vc.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 i_(t,e,n={}){let o=li.isAbsolute(t)?li.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()}If.exports={diffLines:Mo,showEditDiff:V$,showWriteDiff:J$,showNewFilePreview:Z$,confirmFileChange:Q$,showSideBySideDiff:e_,showDiff:t_,showNewFile:n_}});var di=Q((AA,Ff)=>{var Df=require("util").promisify(require("child_process").exec),s_=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 s_("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function o_(){return await xc("git rev-parse --is-inside-work-tree")==="true"}async function r_(){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 i_(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 a_(t){return await li("add","-A"),await li("commit","-m",t)?await li("rev-parse","--short","HEAD"):null}async function c_(){let t=await qf();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(`${vc.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()}Df.exports={diffLines:Mo,showEditDiff:e_,showWriteDiff:t_,showNewFilePreview:n_,confirmFileChange:s_,showSideBySideDiff:o_,showDiff:r_,showNewFile:i_}});var fi=Q((IA,Uf)=>{var Ff=require("util").promisify(require("child_process").exec),a_=require("util").promisify(require("child_process").execFile),{C:He}=it();async function Sc(t){try{let{stdout:e}=await Ff(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function ui(...t){try{let{stdout:e}=await a_("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function c_(){return await Sc("git rev-parse --is-inside-work-tree")==="true"}async function l_(){return await Sc("git branch --show-current")}async function Ec(){try{let{stdout:t}=await Ff("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 di(t=!1){return await Sc(`git diff ${t?"--cached":""}`)||""}async function Tc(){return(await Ec()).map(e=>e.file)}async function Bf(){let t=await Tc();if(t.length===0)return null;let e=await di(),o=await di(!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 u_(t){let n=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await ui("checkout","-b",n)!==null?n:null}async function d_(t){return await ui("add","-A"),await ui("commit","-m",t)?await ui("rev-parse","--short","HEAD"):null}async function f_(){let t=await Bf();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}
95
95
  `),e.join(`
96
- `)}async function l_(){return(await kc()).filter(e=>e.status==="UU"||e.status==="AA"||e.status==="DD")}async function u_(){let t=await vc();if(t.length===0)return"";let e=[`CHANGED FILES (${t.length}):`];for(let o of t.slice(0,10))e.push(` ${o}`);let n=await ui();if(n){let o=n.length>5e3?n.substring(0,5e3)+`
96
+ `)}async function p_(){return(await Ec()).filter(e=>e.status==="UU"||e.status==="AA"||e.status==="DD")}async function h_(){let t=await Tc();if(t.length===0)return"";let e=[`CHANGED FILES (${t.length}):`];for(let o of t.slice(0,10))e.push(` ${o}`);let n=await di();if(n){let o=n.length>5e3?n.substring(0,5e3)+`
97
97
  ...(truncated)`:n;e.push(`
98
98
  DIFF:
99
99
  ${o}`)}return e.join(`
100
- `)}Ff.exports={isGitRepo:o_,getCurrentBranch:r_,getStatus:kc,getDiff:ui,getChangedFiles:vc,analyzeDiff:qf,createBranch:i_,commit:a_,formatDiffSummary:c_,getDiffContext:u_,getMergeConflicts:l_}});var Kf=Q((NA,zf)=>{var lt=require("fs").promises,OA=require("fs"),Dt=require("path"),d_=require("crypto"),{execSync:Sc,execFileSync:Wf}=require("child_process"),f_=100*1024,Hf=50,xt=[],Gs=[];function p_(t,e,n,o){for(xt.push({tool:t,filePath:e,oldContent:n,newContent:o,timestamp:Date.now()});xt.length>Hf;)xt.shift();Gs.length=0,Yf(xt[xt.length-1]).catch(()=>{})}async function h_(){if(xt.length===0)return null;let t=xt.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 m_(){if(Gs.length===0)return null;let t=Gs.pop();return await lt.writeFile(t.filePath,t.newContent,"utf-8"),xt.push(t),{tool:t.tool,filePath:t.filePath}}function g_(t=10){return xt.slice(-t).reverse().map(e=>({tool:e.tool,filePath:e.filePath,timestamp:e.timestamp}))}function y_(){return xt.length}function w_(){return Gs.length}function b_({diskToo:t=!0}={}){if(xt.length=0,Gs.length=0,t){let e=pi();lt.readdir(e).then(n=>{for(let o of n)o.endsWith(".json")&&lt.unlink(Dt.join(e,o)).catch(()=>{})}).catch(()=>{})}}function pi(){return Dt.join(process.cwd(),".nex","history")}async function Bf(t,e){if(t==null)return{inline:!0,content:t};if(Buffer.byteLength(t,"utf-8")<=f_)return{inline:!0,content:t};let n=d_.createHash("sha256").update(t,"utf-8").digest("hex"),o=Dt.join(e,"blobs");return await lt.mkdir(o,{recursive:!0}),await lt.writeFile(Dt.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=Dt.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(Dt.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=Dt.join(e,"blobs",t.hash);return lt.readFile(n,"utf-8")}async function $_(){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(Dt.join(t,s),"utf-8"),i=JSON.parse(r),a=await Uf(i.oldContent,t),c=await Uf(i.newContent,t);xt.push({tool:i.tool,filePath:i.filePath,timestamp:i.timestamp,oldContent:a,newContent:c}),o++}catch{}for(;xt.length>Hf;)xt.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(Dt.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(Dt.join(e,u))}catch{}let c=Dt.join(e,"blobs");try{let u=await lt.readdir(c);for(let l of u)if(!i.has(l))try{await lt.unlink(Dt.join(c,l))}catch{}}catch{}return r}var fi="nex-snapshot";function x_(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 k_(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:p_,undo:h_,redo:m_,getHistory:g_,getUndoCount:y_,getRedoCount:w_,clearHistory:b_,persistEntry:Yf,loadPersistedHistory:$_,pruneHistory:__,createSnapshot:x_,listSnapshots:Gf,restoreSnapshot:k_}});var Ac=Q((MA,ep)=>{var De=require("fs"),kt=require("path"),{atomicWrite:v_,withFileLockSync:S_}=Jn(),mt=[];function Po(){return kt.join(process.cwd(),".nex","skills")}function Xf(){return kt.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=kt.dirname(e);De.existsSync(n)||De.mkdirSync(n,{recursive:!0}),S_(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,v_(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=kt.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||kt.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
+ `)}Uf.exports={isGitRepo:c_,getCurrentBranch:l_,getStatus:Ec,getDiff:di,getChangedFiles:Tc,analyzeDiff:Bf,createBranch:u_,commit:d_,formatDiffSummary:f_,getDiffContext:h_,getMergeConflicts:p_}});var Vf=Q((DA,Xf)=>{var ut=require("fs").promises,jA=require("fs"),Ft=require("path"),m_=require("crypto"),{execSync:Rc,execFileSync:Yf}=require("child_process"),g_=100*1024,Gf=50,xt=[],Gs=[];function y_(t,e,n,o){for(xt.push({tool:t,filePath:e,oldContent:n,newContent:o,timestamp:Date.now()});xt.length>Gf;)xt.shift();Gs.length=0,zf(xt[xt.length-1]).catch(()=>{})}async function w_(){if(xt.length===0)return null;let t=xt.pop();if(t.oldContent===null)try{await ut.unlink(t.filePath)}catch{}else await ut.writeFile(t.filePath,t.oldContent,"utf-8");return Gs.push(t),{tool:t.tool,filePath:t.filePath,wasCreated:t.oldContent===null}}async function b_(){if(Gs.length===0)return null;let t=Gs.pop();return await ut.writeFile(t.filePath,t.newContent,"utf-8"),xt.push(t),{tool:t.tool,filePath:t.filePath}}function $_(t=10){return xt.slice(-t).reverse().map(e=>({tool:e.tool,filePath:e.filePath,timestamp:e.timestamp}))}function __(){return xt.length}function x_(){return Gs.length}function k_({diskToo:t=!0}={}){if(xt.length=0,Gs.length=0,t){let e=hi();ut.readdir(e).then(n=>{for(let o of n)o.endsWith(".json")&&ut.unlink(Ft.join(e,o)).catch(()=>{})}).catch(()=>{})}}function hi(){return Ft.join(process.cwd(),".nex","history")}async function Wf(t,e){if(t==null)return{inline:!0,content:t};if(Buffer.byteLength(t,"utf-8")<=g_)return{inline:!0,content:t};let n=m_.createHash("sha256").update(t,"utf-8").digest("hex"),o=Ft.join(e,"blobs");return await ut.mkdir(o,{recursive:!0}),await ut.writeFile(Ft.join(o,n),t,"utf-8"),{inline:!1,hash:n}}async function zf(t){let e=hi();await ut.mkdir(e,{recursive:!0});let n=Ft.basename(t.filePath).replace(/[^a-zA-Z0-9]/g,"-"),o=`${t.timestamp}-${n}.json`,s=await Wf(t.oldContent,e),r=await Wf(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 ut.writeFile(Ft.join(e,o),JSON.stringify(i),"utf-8")}async function Hf(t,e){if(!t)return null;if(t.inline)return t.content;let n=Ft.join(e,"blobs",t.hash);return ut.readFile(n,"utf-8")}async function v_(){let t=hi(),e;try{e=await ut.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 ut.readFile(Ft.join(t,s),"utf-8"),i=JSON.parse(r),a=await Hf(i.oldContent,t),c=await Hf(i.newContent,t);xt.push({tool:i.tool,filePath:i.filePath,timestamp:i.timestamp,oldContent:a,newContent:c}),o++}catch{}for(;xt.length>Gf;)xt.shift();return o}async function S_(t=7){let e=hi(),n;try{n=await ut.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 ut.readFile(Ft.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 ut.unlink(Ft.join(e,u))}catch{}let c=Ft.join(e,"blobs");try{let u=await ut.readdir(c);for(let l of u)if(!i.has(l))try{await ut.unlink(Ft.join(c,l))}catch{}}catch{}return r}var pi="nex-snapshot";function E_(t,e=process.cwd()){let n=t?`${pi}-${t.replace(/[^a-zA-Z0-9_-]/g,"-")}`:`${pi}-${Date.now()}`;try{return Rc("git status --porcelain",{cwd:e,timeout:1e4}).toString().trim()?(Yf("git",["stash","push","-u","-m",n],{cwd:e,timeout:15e3}),Rc("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 Kf(t=process.cwd()){try{let e=Rc("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(pi)?{index:parseInt(o[1],10),label:s,shortName:s.replace(`${pi}-`,""),date:n}:null}).filter(Boolean):[]}catch{return[]}}function T_(t,e=process.cwd()){try{let n=Kf(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?(Yf("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}}}Xf.exports={recordChange:y_,undo:w_,redo:b_,getHistory:$_,getUndoCount:__,getRedoCount:x_,clearHistory:k_,persistEntry:zf,loadPersistedHistory:v_,pruneHistory:S_,createSnapshot:E_,listSnapshots:Kf,restoreSnapshot:T_}});var Mc=Q((qA,np)=>{var De=require("fs"),kt=require("path"),{atomicWrite:R_,withFileLockSync:C_}=Zn(),mt=[];function Po(){return kt.join(process.cwd(),".nex","skills")}function Jf(){return kt.join(process.cwd(),".nex","config.json")}function Zf(){let t=Po();return De.existsSync(t)||De.mkdirSync(t,{recursive:!0}),t}function Oc(){let t=Jf();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 Qf(t){let e=Jf(),n=kt.dirname(e);De.existsSync(n)||De.mkdirSync(n,{recursive:!0}),C_(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,R_(e,JSON.stringify(o,null,2))})}function ep(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 tp(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 Cc(t){try{let e=De.readFileSync(t,"utf-8").trim();if(!e)return null;let n=kt.basename(t,".md"),{triggers:o,body:s}=tp(e);return{name:n,type:"prompt",filePath:t,instructions:s||e,triggers:o,commands:[],tools:[]}}catch{return null}}function Ac(t){try{let e=require(t),{valid:n,errors:o}=ep(e,t);return n?{name:e.name||kt.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
- `)}`),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=kt.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=kt.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=kt.join(o,r),a=kt.basename(r,kt.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 E_(){let t=[];for(let e of mt)!e.enabled||!e.instructions||t.push(`[Skill: ${e.name}]
104
+ `)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function Nc(){mt=[];let t=Oc(),e=Po(),n=[];if(De.existsSync(e))try{n=De.readdirSync(e)}catch{n=[]}for(let s of n){let r=kt.join(e,s),i;try{i=De.statSync(r)}catch{continue}if(!i.isFile())continue;let a=null;s.endsWith(".md")?a=Cc(r):s.endsWith(".js")&&(a=Ac(r)),a&&(a.enabled=!t.includes(a.name),mt.push(a))}let o=kt.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=kt.join(o,r),a=kt.basename(r,kt.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")?Cc(i):Ac(i);u&&(u._builtin=!0,u.enabled=!t.includes(u.name),mt.push(u))}}return mt}function A_(){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 T_(){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 R_(){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 C_(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 A_(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 O_(){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 N_(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 M_(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 P_(){return mt}async function L_(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||kt.basename(s,".git").replace(/^nex-skill-/,""),i=kt.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=kt.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 I_(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 j_(t){let e=kt.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 D_(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 O_(){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 N_(){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 M_(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 P_(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 L_(){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 I_(t){let e=mt.find(o=>o.name===t);if(!e)return!1;e.enabled=!0;let n=Oc().filter(o=>o!==t);return Qf(n),!0}function j_(t){let e=mt.find(o=>o.name===t);if(!e)return!1;e.enabled=!1;let n=Oc();return n.includes(t)||(n.push(t),Qf(n)),!0}function D_(){return mt}async function q_(t,e={}){let{execFileSync:n}=require("child_process"),o=Zf(),s=t;/^[\w-]+\/[\w.-]+$/.test(t)&&(s=`https://github.com/${t}.git`);let r=e.name||kt.basename(s,".git").replace(/^nex-skill-/,""),i=kt.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=kt.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 Nc(),{ok:!0,name:r}}async function F_(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 B_(t){let e=kt.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}),Nc(),{ok:!0}}catch(n){return{ok:!1,error:n.message}}}function U_(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}ep.exports={initSkillsDir:Vf,loadAllSkills:Cc,getSkillInstructions:E_,getSkillCommands:T_,getSkillToolDefinitions:R_,routeSkillCall:C_,handleSkillCommand:A_,listSkills:O_,enableSkill:N_,disableSkill:M_,getLoadedSkills:P_,installSkill:L_,searchSkills:I_,removeSkill:j_,matchSkillTriggers:D_,_getSkillsDir:Po,_validateScriptSkill:Zf,_loadMarkdownSkill:Ec,_loadScriptSkill:Tc,_parseFrontmatter:Qf}});var Nc=Q((PA,ip)=>{var{spawn:q_}=require("child_process"),F_=require("path"),tp=require("fs"),_n=new Map;function B_(){return F_.join(process.cwd(),".nex","config.json")}function Oc(){let t=B_();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})+`
110
+ `);n.push({name:o.name,instructions:r})}}return n}np.exports={initSkillsDir:Zf,loadAllSkills:Nc,getSkillInstructions:A_,getSkillCommands:O_,getSkillToolDefinitions:N_,routeSkillCall:M_,handleSkillCommand:P_,listSkills:L_,enableSkill:I_,disableSkill:j_,getLoadedSkills:D_,installSkill:q_,searchSkills:F_,removeSkill:B_,matchSkillTriggers:U_,_getSkillsDir:Po,_validateScriptSkill:ep,_loadMarkdownSkill:Cc,_loadScriptSkill:Ac,_parseFrontmatter:tp}});var Lc=Q((FA,cp)=>{var{spawn:W_}=require("child_process"),H_=require("path"),sp=require("fs"),_n=new Map;function Y_(){return H_.join(process.cwd(),".nex","config.json")}function Pc(){let t=Y_();if(!sp.existsSync(t))return{};try{return JSON.parse(sp.readFileSync(t,"utf-8")).mcpServers||{}}catch{return{}}}function mi(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 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=q_(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 U_(){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 W_(){return rp().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function H_(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 Y_(){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 G_(){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:U_,callTool:op,getAllTools:rp,getMCPToolDefinitions:W_,routeMCPCall:H_,listServers:Y_,connectAll:G_}});var gi=Q((LA,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 z_(){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 K_(){return Lo.map(t=>t.definition)}async function X_(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 V_(){return[...mi]}function J_(){let t={};for(let e of Io)t[e]=(Qn[e]||[]).length;return t}function Z_(){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:z_,getPluginToolDefinitions:K_,executePluginTool:X_,getLoadedPlugins:V_,getHookCounts:J_,clearPlugins:Z_,EVENTS:Io}});var Lc=Q((IA,hp)=>{var{getSkillToolDefinitions:Q_}=Ac(),{getMCPToolDefinitions:ex}=Nc(),{getPluginToolDefinitions:tx}=gi(),yi=new Map;function dp(){let{TOOL_DEFINITIONS:t}=zs();return[...t,...Q_(),...ex(),...tx()]}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 nx(){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 sx(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
- 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:
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 op(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=W_(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:{...o,...e.env||{}}}),r={name:t,proc:s,tools:[],config:e};try{await mi(s,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.2.0"}});let i=await mi(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 rp(t){let e=_n.get(t);if(!e)return!1;try{e.proc.kill()}catch{}return _n.delete(t),!0}function G_(){for(let[t]of _n)rp(t)}async function ip(t,e,n={}){let o=_n.get(t);if(!o)throw new Error(`MCP server not connected: ${t}`);let s=await mi(o.proc,"tools/call",{name:e,arguments:n});return s&&Array.isArray(s.content)?s.content.filter(r=>r.type==="text").map(r=>r.text).join(`
113
+ `):JSON.stringify(s)}function ap(){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 z_(){return ap().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function K_(t,e){if(!t.startsWith("mcp_"))return null;let n=t.substring(4).split("_");if(n.length<2)return null;let o=n[0],s=n.slice(1).join("_");return ip(o,s,e)}function X_(){let t=Pc();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 V_(){let t=Pc(),e=[];for(let[n,o]of Object.entries(t))try{let s=await op(n,o);e.push({name:n,tools:s.tools.length})}catch(s){e.push({name:n,tools:0,error:s.message})}return e}cp.exports={loadMCPConfig:Pc,sendRequest:mi,connectServer:op,disconnectServer:rp,disconnectAll:G_,callTool:ip,getAllTools:ap,getMCPToolDefinitions:z_,routeMCPCall:K_,listServers:X_,connectAll:V_}});var yi=Q((BA,fp)=>{var lp=require("fs"),Ic=require("path"),gi=[],Lo=[],es={},Io=["onToolResult","onModelResponse","onSessionStart","onSessionEnd","onFileChange","beforeToolExec","afterToolExec"];function up(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 dp(t,e){return Io.includes(t)?typeof e!="function"?{ok:!1,error:"Handler must be a function"}:(es[t]||(es[t]=[]),es[t].push(e),{ok:!0}):{ok:!1,error:`Unknown event "${t}". Available: ${Io.join(", ")}`}}async function jc(t,e){let n=es[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 J_(){let t=Ic.join(process.cwd(),".nex","plugins"),e=[];if(!lp.existsSync(t))return{loaded:0,errors:[]};let n=lp.readdirSync(t).filter(s=>s.endsWith(".js")),o={registerTool:up,registerHook:dp,EVENTS:Io};for(let s of n){let r=Ic.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}gi.push({name:i.name||Ic.basename(s,".js"),filePath:r})}catch(i){e.push(`${s}: ${i.message}`)}}return{loaded:gi.length,errors:e}}function Z_(){return Lo.map(t=>t.definition)}async function Q_(t,e,n={}){let o=Lo.find(a=>a.definition.function.name===t);if(!o)return null;let s=await jc("beforeToolExec",{name:t,args:e,options:n}),r=await o.handler(s.args||e,n);return(await jc("afterToolExec",{name:t,args:e,result:r})).result||r}function ex(){return[...gi]}function tx(){let t={};for(let e of Io)t[e]=(es[e]||[]).length;return t}function nx(){gi.length=0,Lo.length=0;for(let t of Object.keys(es))delete es[t]}fp.exports={registerTool:up,registerHook:dp,emit:jc,loadPlugins:J_,getPluginToolDefinitions:Z_,executePluginTool:Q_,getLoadedPlugins:ex,getHookCounts:tx,clearPlugins:nx,EVENTS:Io}});var Dc=Q((UA,gp)=>{var{getSkillToolDefinitions:sx}=Mc(),{getMCPToolDefinitions:ox}=Lc(),{getPluginToolDefinitions:rx}=yi(),wi=new Map;function pp(){let{TOOL_DEFINITIONS:t}=zs();return[...t,...sx(),...ox(),...rx()]}function hp(t){if(wi.has(t))return wi.get(t);let n=pp().find(s=>s.function.name===t);if(!n)return null;let o=n.function.parameters;return wi.set(t,o),o}function ix(){wi.clear()}function bi(t,e){if(!t||e.length===0)return null;let n=null,o=1/0;for(let s of e){let r=mp(t.toLowerCase(),s.toLowerCase());r<o&&(o=r,n=s)}return o<=Math.ceil(t.length/2)?n:null}function mp(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 ax(t,e){let n=hp(t);if(n===null){let d=pp().map(p=>p.function.name),f=bi(t,d);return{valid:!1,error:`Unknown tool "${t}".${f?` Did you mean "${f}"?`:""}
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=bi(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=bi(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 ox(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:sx,validateToolCallFormat:ox,closestMatch:wi,levenshtein:pp,getCachedSchema:fp,clearSchemaCache:nx}});var wp=Q((jA,yp)=>{var{levenshtein:bi}=Lc(),rx=200,ix=.3,ax=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 cx(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}}gp.exports={validateToolArgs:ax,validateToolCallFormat:cx,closestMatch:bi,levenshtein:mp,getCachedSchema:hp,clearSchemaCache:ix}});var $p=Q((WA,bp)=>{var{levenshtein:$i}=Dc(),lx=200,ux=.3,dx=2;function qc(t){return t.replace(/\r\n/g,`
119
119
  `).replace(/\r/g,`
120
- `).replace(/\t/g," ".repeat(ax)).split(`
120
+ `).replace(/\t/g," ".repeat(dx)).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(`
122
- `)}function cx(t,e){if(t.includes(e))return e;if(e.length<10)return null;let n=Ic(t),o=Ic(e);if(!n.includes(o))return null;let s=t.split(`
122
+ `)}function fx(t,e){if(t.includes(e))return e;if(e.length<10)return null;let n=qc(t),o=qc(e);if(!n.includes(o))return null;let s=t.split(`
123
123
  `),r=n.split(`
124
124
  `),i=o.split(`
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
- `)}if(i.length===1){for(let u=0;u<r.length;u++)if(r[u].indexOf(o)!==-1)return s[u]}return null}function lx(t,e){if(!t||!e)return null;let n=t.split(`
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 px(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?ux(n,e):fx(n,e,s)}function mp(t){return Math.max(1,Math.floor(t/rx))}function gp(t,e){return t<=Math.ceil(e*ix)}function ux(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=dx(t,n,s,o)||s,r=s.distance),gp(r,e.length)?s:null}function dx(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 fx(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=px(t,e,r,s,n,o)||r,i=r.distance),gp(i,e.length)?r:null}function px(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:cx,findMostSimilar:lx}});var Tp=Q((DA,Dc)=>{var bp=require("fs"),hx=require("path"),{execFileSync:mx}=require("child_process"),$p=["--",".",":!*.lock",":!*.min.js",":!*.min.css",":!package-lock.json",":!yarn.lock",":!dist/",":!tests/hooks-pre-push.test.js"],gx=/(^|\/)(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}],yx=/(^|\/)\.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 mx("git",t,{cwd:e,encoding:"utf8"})}function wx(t=process.cwd()){return $i(["rev-parse","--show-toplevel"],t).trim()}function bx(t){let e=hx.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 yx.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 $x(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 $x(t))if(!gx.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 xx(t,e){return $i(["diff",e,...$p],t)}function kx(t){return $i(["diff","--cached",...$p],t)}function Ep({repoRoot:t,mode:e,range:n}){let o=bx(t),s=e==="staged"?_x(t):[],r=vp(s,o),i=e==="range"?xx(t,n):kx(t),a=Sp(i,o);return[...r,...a]}function vx(t){return t.map(e=>` [${e.category}]
128
+ `).length;return n.length===0||s===0?null:s===1?hx(n,e):gx(n,e,s)}function yp(t){return Math.max(1,Math.floor(t/lx))}function wp(t,e){return t<=Math.ceil(e*ux)}function hx(t,e){let n=e.trim(),o=yp(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=$i(a.trim(),n);c<r&&(r=c,s={text:a,distance:c,line:i+1})}return s&&o>1&&(s=mx(t,n,s,o)||s,r=s.distance),wp(r,e.length)?s:null}function mx(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=$i(l.trim(),e);d<a&&(a=d,c={text:l,distance:d,line:u+1})}return c}function gx(t,e,n){let o=t.length-n+1;if(o<=0)return null;let s=yp(o),r=null,i=1/0;for(let a=0;a<o;a+=s){let c=t.slice(a,a+n).join(`
129
+ `),u=$i(c,e);u<i&&(i=u,r={text:c,distance:u,line:a+1})}return r&&s>1&&(r=yx(t,e,r,s,n,o)||r,i=r.distance),wp(i,e.length)?r:null}function yx(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=$i(f,e);p<u&&(u=p,l={text:f,distance:p,line:d+1})}return l}bp.exports={normalizeWhitespace:qc,fuzzyFindText:fx,findMostSimilar:px}});var Cp=Q((HA,Bc)=>{var _p=require("fs"),wx=require("path"),{execFileSync:bx}=require("child_process"),xp=["--",".",":!*.lock",":!*.min.js",":!*.min.css",":!package-lock.json",":!yarn.lock",":!dist/",":!tests/hooks-pre-push.test.js"],$x=/(^|\/)(tests\/.*\.test\.(js|ts|jsx|tsx)|__tests__\/.*\.(js|ts|jsx|tsx))$/i,kp=[{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}],_x=/(^|\/)\.env(?:\.[^/]+)?\.(example|sample|template)$/i,vp=[{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 bx("git",t,{cwd:e,encoding:"utf8"})}function xx(t=process.cwd()){return _i(["rev-parse","--show-toplevel"],t).trim()}function kx(t){let e=wx.join(t,".nex","push-allowlist");return _p.existsSync(e)?_p.readFileSync(e,"utf8").split(`
131
+ `).map(n=>n.trim()).filter(n=>n&&!n.startsWith("#")):[]}function Fc(t,e){return e.some(n=>t.includes(n))}function Sp(t){return _x.test(t)}function Ep(t,e){let n=[];for(let o of t)if(!Sp(o))for(let s of vp)s.regex.test(o)&&(Fc(o,e)||n.push({category:s.category,location:o,preview:o}));return n}function vx(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 Tp(t,e){let n=[];for(let o of vx(t))if(!$x.test(o.filePath||""))for(let s of kp)s.regex.test(o.text)&&(Fc(o.raw,e)||Fc(o.text,e)||n.push({category:s.category,location:`${o.lineNumber}:${o.raw}`,preview:o.raw}));return n}function Sx(t){return _i(["diff","--cached","--name-only","--diff-filter=ACMR","-z"],t).split("\0").filter(Boolean)}function Ex(t,e){return _i(["diff",e,...xp],t)}function Tx(t){return _i(["diff","--cached",...xp],t)}function Rp({repoRoot:t,mode:e,range:n}){let o=kx(t),s=e==="staged"?Sx(t):[],r=Ep(s,o),i=e==="range"?Ex(t,n):Tx(t),a=Tp(i,o);return[...r,...a]}function Rx(t){return t.map(e=>` [${e.category}]
133
133
  ${e.location}`).join(`
134
- `)}function Sx(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 Ex(){let t=Sx(process.argv.slice(2)),e=wx(),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(vx(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&&Ex();Dc.exports={SECRET_PATTERNS:_p,SENSITIVE_FILE_RULES:xp,scanDiffText:Sp,scanFileNames:vp,scanRepo:Ep,isSafeExampleFile:kp}});var Cp=Q((FA,Rp)=>{var{C:qA}=rt(),{SECRET_PATTERNS:Tx}=Tp(),Rx=[{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 Cx(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 Tx)c.regex.test(i)&&o.push({line:a,message:`Potential secret detected: ${c.category}`,severity:"error"});for(let c of Rx)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 Ax(){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:Cx,getMemoryUsage:Ax}});var cn=Q((BA,Bp)=>{var es=require("fs").promises,vt=require("path"),{exec:Ox}=require("util").promisify(require("child_process").exec),Pn=[],Bc=null,_i=!1,Fc=0,Nx=6e4;function Uc(t){return!(Pn.length===0||Bc!==t||Date.now()-Fc>Nx)}async function Pp(t){if(!_i&&!Uc(t)){_i=!0,Bc=t;try{try{let{stdout:o}=await Ox("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(vt.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 Mx(){return Bc}function Px(t){return Pn.filter(e=>vt.basename(e)===t)}function Lx(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=vt.basename(t).toLowerCase(),c=vt.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 Ix(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=vt.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=vt.extname(i);if(!Dp.has(a))continue;let c=vt.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=vt.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 jx(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 Dx(t,e,n){if(!e||!e.startsWith("."))return null;let o=vt.posix.dirname(t.replace(/\\/g,"/")),s=vt.posix.normalize(vt.posix.join(o==="."?"":o,e)),r=[];if(vt.posix.extname(s))r.push(s);else for(let a of Dp)r.push(`${s}${a}`),r.push(vt.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=Dx(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 qx(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 Fx(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 Bx(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 Ux(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=vt.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||Bx(_,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:Mx,findFileInIndex:Px,searchIndex:Lx,isIndexValid:Uc,buildContentIndex:ki,searchContentIndex:jx,extractDefinitions:qp,buildImportGraph:Wc,getRelatedFiles:qx,summarizeModuleHubs:Fx,findSymbolReferences:Ux,smartSearch:Ix,scorePathMatch:Ip,pathLevenshtein:Lp}});var Ks=Q((UA,zp)=>{var vi=require("fs"),Ri=require("path"),Ci=require("os"),{execFile:Wx}=require("child_process"),{promisify:Hx}=require("util"),Hc=Hx(Wx),Yx=Ri.join(Ci.homedir(),".nex","servers.json"),Si=Ri.join(Ci.tmpdir(),"nex-ssh-sockets");function Gx(){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(Yx),n=t(Gx());return{...e,...n}}function zx(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 Kx(){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)),Kx();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 Xx(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 Vx(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}
134
+ `)}function Cx(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 Ax(){let t=Cx(process.argv.slice(2)),e=xx(),n=Rp({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(Rx(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===Bc&&Ax();Bc.exports={SECRET_PATTERNS:kp,SENSITIVE_FILE_RULES:vp,scanDiffText:Tp,scanFileNames:Ep,scanRepo:Rp,isSafeExampleFile:Sp}});var Op=Q((GA,Ap)=>{var{C:YA}=it(),{SECRET_PATTERNS:Ox}=Cp(),Nx=[{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 Mx(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 Ox)c.regex.test(i)&&o.push({line:a,message:`Potential secret detected: ${c.category}`,severity:"error"});for(let c of Nx)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 Px(){let t=process.memoryUsage();return{rss:Math.round(t.rss/1024/1024*100)/100,heapUsed:Math.round(t.heapUsed/1024/1024*100)/100}}Ap.exports={runDiagnostics:Mx,getMemoryUsage:Px}});var ln=Q((zA,Wp)=>{var ts=require("fs").promises,vt=require("path"),{exec:Lx}=require("util").promisify(require("child_process").exec),Pn=[],Hc=null,xi=!1,Wc=0,Ix=6e4;function Yc(t){return!(Pn.length===0||Hc!==t||Date.now()-Wc>Ix)}async function Ip(t){if(!xi&&!Yc(t)){xi=!0,Hc=t;try{try{let{stdout:o}=await Lx("rg --files",{cwd:t,timeout:5e3});Pn=o.split(`
136
+ `).filter(Boolean),Wc=Date.now(),xi=!1;return}catch{}let e=[],n=async(o,s)=>{let r;try{r=await ts.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(vt.join(o,i.name),a):e.push(a)}};await n(t,""),Pn=e,Wc=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{xi=!1}}}function jo(){return Pn}function jx(){return Hc}function Dx(t){return Pn.filter(e=>vt.basename(e)===t)}function qx(t){let e=t.toLowerCase();return Pn.filter(n=>n.toLowerCase().includes(e)).slice(0,20)}function jp(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 Dp(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=vt.basename(t).toLowerCase(),c=vt.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-jp(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 Fx(t,{limit:e=10,minScore:n=15}={}){if(!t||Pn.length===0)return[];let o=[];for(let s of Pn){let r=Dp(s,t);r>=n&&o.push({file:s,score:r})}return o.sort((s,r)=>r.score-s.score),o.slice(0,e)}var Uc=null,Np=0,Mp=null,qp=12e4,ki=null,Pp=0,Lp=null,Fp=new Set([".js",".ts",".jsx",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".rb"]);function Bp(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 vi(t){t=t||process.cwd();let e=vt.join(t,".nex","index","content-index.json"),n={};if(Uc&&Mp===t&&Date.now()-Np<qp)return Uc;try{let i=await ts.readFile(e,"utf-8");n=JSON.parse(i)}catch{n={files:{}}}let o=jo();(!Yc(t)||o.length===0)&&(await Ip(t),o=jo());let s={files:{}},r=!1;for(let i of jo()){let a=vt.extname(i);if(!Fp.has(a))continue;let c=vt.join(t,i);try{let l=(await ts.stat(c)).mtimeMs;if(n.files[i]&&n.files[i].mtime===l){s.files[i]=n.files[i];continue}let d=await ts.readFile(c,"utf-8"),f=Bp(d,a);s.files[i]={defs:f,mtime:l},r=!0}catch{}}if(r){let i=vt.join(t,".nex","index");await ts.mkdir(i,{recursive:!0}),await ts.writeFile(e,JSON.stringify(s),"utf-8")}return Uc=s,Np=Date.now(),Mp=t,s}async function Bx(t,e,n){let o=await vi(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 Ux(t,e,n){if(!e||!e.startsWith("."))return null;let o=vt.posix.dirname(t.replace(/\\/g,"/")),s=vt.posix.normalize(vt.posix.join(o==="."?"":o,e)),r=[];if(vt.posix.extname(s))r.push(s);else for(let a of Fp)r.push(`${s}${a}`),r.push(vt.posix.join(s,`index${a}`));for(let a of r)if(n.has(a))return a;return null}async function Gc(t){if(t=t||process.cwd(),ki&&Lp===t&&Date.now()-Pp<qp)return ki;let e=await vi(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=Ux(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 ki={importsByFile:s,importedByFile:r},Pp=Date.now(),Lp=t,ki}async function Wx(t,e,n=6){if(!t)return[];let o=await Gc(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 Hx(t,e=4){let n=await Gc(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 Up(t){return String(t).replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Yx(t,e){let n=Up(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 Gx(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 vi(e),a=Up(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=vt.join(e,f),g=(await ts.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||Yx(_,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)}Wp.exports={refreshIndex:Ip,getFileIndex:jo,getIndexedCwd:jx,findFileInIndex:Dx,searchIndex:qx,isIndexValid:Yc,buildContentIndex:vi,searchContentIndex:Bx,extractDefinitions:Bp,buildImportGraph:Gc,getRelatedFiles:Wx,summarizeModuleHubs:Hx,findSymbolReferences:Gx,smartSearch:Fx,scorePathMatch:Dp,pathLevenshtein:jp}});var Ks=Q((KA,Xp)=>{var Si=require("fs"),Ci=require("path"),Ai=require("os"),{execFile:zx}=require("child_process"),{promisify:Kx}=require("util"),zc=Kx(zx),Xx=Ci.join(Ai.homedir(),".nex","servers.json"),Ei=Ci.join(Ai.tmpdir(),"nex-ssh-sockets");function Vx(){return Ci.join(process.cwd(),".nex","servers.json")}function Hp(){let t=o=>{if(!Si.existsSync(o))return{};try{return JSON.parse(Si.readFileSync(o,"utf-8"))}catch{return{}}},e=t(Xx),n=t(Vx());return{...e,...n}}function Jx(t){let e=Hp();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(){Si.existsSync(Ei)||Si.mkdirSync(Ei,{recursive:!0})}function Yp(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=yes","-o","ServerAliveInterval=30"];t.key&&e.push("-i",t.key.replace(/^~/,Ai.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=Ci.join(Ei,n.replace(/[@.:]/g,"_"));return e.push("-o","ControlMaster=auto","-o",`ControlPath=${o}`,"-o","ControlPersist=120"),e.push(n),{args:e,target:n}}function Gp(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=yes","-r"];return t.key&&e.push("-i",t.key.replace(/^~/,Ai.homedir())),t.port&&Number(t.port)!==22&&e.push("-P",String(t.port)),e}async function Ti(t,e,{timeout:n=3e4,sudo:o=!1}={}){let{args:s}=Yp(t),r=o&&t.sudo?`sudo sh -c ${JSON.stringify(e)}`:e;try{let{stdout:i,stderr:a}=await zc("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:Oi(c,t)}}}async function Qx(t,e,n,{timeout:o=12e4}={}){let s=Gp(t),r=t.user?`${t.user}@${t.host}`:t.host;s.push(e,`${r}:${n}`);try{let{stdout:i,stderr:a}=await zc("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(Oi(a,t)||a)}}async function ek(t,e,n,{timeout:o=12e4}={}){let s=Gp(t),r=t.user?`${t.user}@${t.host}`:t.host;s.push(`${r}:${e}`,n);try{let{stdout:i,stderr:a}=await zc("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(Oi(a,t)||a)}}function Oi(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 Jx(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,Zx=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<Zx)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 Qx(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:
144
+ HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function tk(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 Ri=new Map,nk=12e4;async function zp(t,e,{force:n=!1}={}){let s=`${t.user?`${t.user}@${t.host}`:t.host}:${e}`,r=Ri.get(s);if(!n&&r&&Date.now()-r.time<nk)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 Ti(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 Ri.set(s,{files:l,time:Date.now()}),l}async function Kp(t,e,n,{limit:o=5,minScore:s=15}={}){let r=await zp(t,e);if(r.length===0)return[];let{scorePathMatch:i}=ln(),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 sk(t,e,n){if(!n)return{fixedPath:null,message:""};let o=n.replace(/\/+/g,"/");if(o.startsWith("~/")){let{stdout:r}=await Ti(t,"echo $HOME",{timeout:5e3}),i=r.trim();i&&(o=o.replace("~/",i+"/"))}if(o.startsWith("/")){let{exitCode:r}=await Ti(t,`test -f ${JSON.stringify(o)}`,{timeout:5e3});if(r===0)return{fixedPath:o,message:"(auto-fixed: normalized path)"}}let s=await Kp(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 ek(t){t?Ti.delete(t):Ti.clear()}zp.exports={loadServerProfiles:Up,resolveProfile:zx,buildSSHArgs:Wp,sshExec:Ei,scpUpload:Xx,scpDownload:Vx,enrichSSHError:Ai,formatProfile:Jx,SSH_SOCKET_DIR:Si,getRemoteIndex:Yp,remoteSmartSearch:Gp,remoteAutoFixPath:Qx,clearRemoteIndex:ek}});var Vp=Q((WA,Xp)=>{var Do=require("fs"),Yc=require("path"),tk=Yc.join(".nex","deploy.json");function Gc(){return Yc.join(process.cwd(),tk)}function Kp(){let t=Gc();if(!Do.existsSync(t))return{};try{return JSON.parse(Do.readFileSync(t,"utf-8"))}catch{return{}}}function nk(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 sk(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:nk,saveDeployConfigs:sk,getDeployConfigPath:Gc}});var Uo=Q((HA,Qp)=>{var{getActiveModel:ok,getActiveProviderName:rk}=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=ok()?.id,n=rk();return e&&ln[e]?ln[e]:n&&ln[`${n}:*`]?ln[`${n}:*`]:e&&Fo[e]?Fo[e]:n&&Bo[n]?Bo[n]:"full"}var ik=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 ak(t,e){return t&&(ik.has(t)||t.startsWith("claude-"))?"strict":e&&Jp[e]?Jp[e]:"fuzzy"}function ck(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 lk(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 uk(){let t=zc(),e=qo[t]?qo[t].length:"all";return{tier:t,toolCount:e}}Qp.exports={filterToolsForModel:lk,getActiveTier:zc,getModelTier:ck,getEditMode:ak,getTierInfo:uk,TIERS:qo,MODEL_TIERS:Fo,PROVIDER_DEFAULT_TIER:Bo,loadConfigOverrides:Zp}});var kn=Q((YA,nh)=>{var Kc=null,xn=null,Wo=null,eh=`Playwright is not installed. Install with:
147
+ `)}`}}return{fixedPath:null,message:""}}function ok(t){t?Ri.delete(t):Ri.clear()}Xp.exports={loadServerProfiles:Hp,resolveProfile:Jx,buildSSHArgs:Yp,sshExec:Ti,scpUpload:Qx,scpDownload:ek,enrichSSHError:Oi,formatProfile:tk,SSH_SOCKET_DIR:Ei,getRemoteIndex:zp,remoteSmartSearch:Kp,remoteAutoFixPath:sk,clearRemoteIndex:ok}});var Zp=Q((XA,Jp)=>{var Do=require("fs"),Kc=require("path"),rk=Kc.join(".nex","deploy.json");function Xc(){return Kc.join(process.cwd(),rk)}function Vp(){let t=Xc();if(!Do.existsSync(t))return{};try{return JSON.parse(Do.readFileSync(t,"utf-8"))}catch{return{}}}function ik(t){let e=Vp();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 ak(t){let e=Kc.join(process.cwd(),".nex");Do.existsSync(e)||Do.mkdirSync(e,{recursive:!0}),Do.writeFileSync(Xc(),JSON.stringify(t,null,2)+`
148
+ `,"utf-8")}Jp.exports={loadDeployConfigs:Vp,resolveDeployConfig:ik,saveDeployConfigs:ak,getDeployConfigPath:Xc}});var Uo=Q((VA,th)=>{var{getActiveModel:ck,getActiveProviderName:lk}=lt(),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"},un={};function eh(){try{let t=require("fs"),n=require("path").join(process.cwd(),".nex","config.json");t.existsSync(n)&&(un=JSON.parse(t.readFileSync(n,"utf-8")).toolTiers||{})}catch{un={}}}eh();function Vc(){let e=ck()?.id,n=lk();return e&&un[e]?un[e]:n&&un[`${n}:*`]?un[`${n}:*`]:e&&Fo[e]?Fo[e]:n&&Bo[n]?Bo[n]:"full"}var uk=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"]),Qp={anthropic:"strict",openai:"strict",gemini:"strict",ollama:"fuzzy",local:"fuzzy"};function dk(t,e){return t&&(uk.has(t)||t.startsWith("claude-"))?"strict":e&&Qp[e]?Qp[e]:"fuzzy"}function fk(t,e){return t&&un[t]?un[t]:e&&un[`${e}:*`]?un[`${e}:*`]:t&&Fo[t]?Fo[t]:e&&Bo[e]?Bo[e]:"full"}function pk(t,e){let n=e||Vc();if(n==="full"||!qo[n])return t;let o=new Set(qo[n]);return t.filter(s=>o.has(s.function.name))}function hk(){let t=Vc(),e=qo[t]?qo[t].length:"all";return{tier:t,toolCount:e}}th.exports={filterToolsForModel:pk,getActiveTier:Vc,getModelTier:fk,getEditMode:dk,getTierInfo:hk,TIERS:qo,MODEL_TIERS:Fo,PROVIDER_DEFAULT_TIER:Bo,loadConfigOverrides:eh}});var kn=Q((JA,rh)=>{var Jc=null,xn=null,Wo=null,Zc=Symbol.for("nex-code.browserExitCleanup"),nh=`Playwright is not installed. Install with:
149
149
  npm install playwright && npx playwright install chromium
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 dk(){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 fk(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 pk(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 hk(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 mk(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:fk,browserScreenshot:pk,browserClick:hk,browserFill:mk,closeBrowser:dk,INSTALL_MSG:eh}});var Xc=Q((GA,oh)=>{"use strict";var gk=require("util"),sh=require("stream"),Vt=oh.exports=function(){sh.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};gk.inherits(Vt,sh);Vt.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))};Vt.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};Vt.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()))};Vt.prototype.destroySoon=Vt.prototype.end;Vt.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};Vt.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};Vt.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))};Vt.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)};Vt.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((KA,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((XA,ah)=>{"use strict";var yk=Jc(),wk=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=yk.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=wk(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((VA,lh)=>{"use strict";var bk=require("util"),ch=Xc(),$k=Qc(),_k=lh.exports=function(t){ch.call(this);let e=[],n=this;this._filter=new $k(t,{read:this.read.bind(this),write:function(o){e.push(o)},complete:function(){n.emit("complete",Buffer.concat(e))}}),this._filter.start()};bk.inherits(_k,ch)});var Vs=Q((JA,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((ZA,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((QA,ph)=>{"use strict";var st=Vs(),xk=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 xk,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(),kk=[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]}],vk=[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 Sk(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 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=n(l,u,c);kk[o](e,s,d,r),r+=o}return r}function Tk(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);vk[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=Sk(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=Ek(d[p],c,f,r,t,l):Tk(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((tO,gh)=>{"use strict";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=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 Ck(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 Ak(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?Rk(t,u,s,r,c):(a&&Ck(t,u,s,r,a),o!==8&&!n&&(o===16&&(u=Buffer.alloc(s*r*4)),Ak(t,u,s,r,o))),u}});var bh=Q((nO,wh)=>{"use strict";var Ok=require("util"),il=require("zlib"),yh=Xc(),Nk=uh(),Mk=sl(),Pk=ol(),Lk=rl(),un=wh.exports=function(t){yh.call(this),this._parser=new Mk(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()};Ok.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 Nk(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=Pk.dataToBitMap(t,this._bitmapInfo);e=Lk(n,this._bitmapInfo,this._options.skipRescale),n=null}catch(n){this._handleError(n);return}this.emit("parsed",e)}});var _h=Q((sO,$h)=>{"use strict";var qt=Vs();$h.exports=function(t,e,n,o){let s=[qt.COLORTYPE_COLOR_ALPHA,qt.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=qt.COLORTYPE_TO_BPP_MAP[o.inputColorType];a===4&&!o.inputHasAlpha&&(a=3);let c=qt.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 qt.COLORTYPE_COLOR_ALPHA:_=r[l+3],h=r[l],g=r[l+1],w=r[l+2];break;case qt.COLORTYPE_COLOR:h=r[l],g=r[l+1],w=r[l+2];break;case qt.COLORTYPE_ALPHA:_=r[l+1],h=r[l],g=h,w=h;break;case qt.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 qt.COLORTYPE_COLOR_ALPHA:case qt.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 qt.COLORTYPE_ALPHA:case qt.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((oO,kh)=>{"use strict";var xh=Zc();function Ik(t,e,n,o,s){for(let r=0;r<n;r++)o[s+r]=t[e+r]}function jk(t,e,n){let o=0,s=e+n;for(let r=e;r<s;r++)o+=Math.abs(t[r]);return o}function Dk(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 qk(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 Fk(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 Bk(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 Uk(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 Wk(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 Hk(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 Yk(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 Gk={0:Ik,1:Dk,2:Fk,3:Uk,4:Hk},zk={0:jk,1:qk,2:Bk,3:Wk,4:Yk};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=zk[r[p]](t,c,i,s);h<f&&(l=r[p],f=h)}}u[a]=l,a++,Gk[l](t,c,i,u,a,s),a+=i,c+=i}return u}});var al=Q((rO,Sh)=>{"use strict";var pt=Vs(),Kk=nl(),Xk=_h(),Vk=vh(),Jk=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||Jk.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=Xk(t,e,n,this._options),s=pt.COLORTYPE_TO_BPP_MAP[this._options.colorType];return Vk(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(Kk.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((iO,Rh)=>{"use strict";var Zk=require("util"),Eh=require("stream"),Qk=Vs(),ev=al(),Th=Rh.exports=function(t){Eh.call(this);let e=t||{};this._packer=new ev(e),this._deflate=this._packer.createDeflate(),this.readable=!0};Zk.inherits(Th,Eh);Th.prototype.pack=function(t,e,n,o){this.emit("data",Buffer.from(Qk.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"),tv=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 nv(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};tv.inherits(ts,Js.Inflate);function sv(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 sv(new ts(e),t)}Ph.exports=Ho=Mh;Ho.Inflate=ts;Ho.createInflate=nv;Ho.inflateSync=Mh});var cl=Q((aO,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 ov=cl(),rv=Qc();Dh.process=function(t,e){let n=[],o=new ov(t);return new rv(e,{read:o.read.bind(o),write:function(r){n.push(r)},complete:function(){}}).start(),o.process(),Buffer.concat(n)}});var Wh=Q((lO,Uh)=>{"use strict";var Fh=!0,Bh=require("zlib"),iv=Lh();Bh.deflateSync||(Fh=!1);var av=cl(),cv=qh(),lv=sl(),uv=ol(),dv=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 av(t);if(new lv(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=iv(g,{chunkSize:v,maxLength:v})}if(g=null,!w||!w.length)throw new Error("bad png - invalid inflate data response");let _=cv.process(w,s);g=null;let S=uv.dataToBitMap(_,s);_=null;let A=dv(S,s,e.skipRescale);return s.data=A,s.gamma=u||0,s}});var zh=Q((uO,Gh)=>{"use strict";var Hh=!0,Yh=require("zlib");Yh.deflateSync||(Hh=!1);var fv=Vs(),pv=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 pv(n),s=[];s.push(Buffer.from(fv.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 hv=Wh(),mv=zh();ll.read=function(t,e){return hv(t,e||{})};ll.write=function(t,e){return mv(t,e)}});var Jh=Q(Vh=>{"use strict";var gv=require("util"),Xh=require("stream"),yv=bh(),wv=Ch(),bv=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 yv(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 wv(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"))};gv.inherits(gt,Xh);gt.sync=bv;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={};Bw(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=Fw(()=>{});var ns=Q((pO,cm)=>{var vn=require("fs"),$v=require("path"),_v=require("os"),xv="nex-visual-";function rm(t){return $v.join(_v.tmpdir(),`${xv}${Date.now()}-${t}`)}var dl=null;function Pi(){return dl||(dl=Jh().PNG),dl}var fl=null;function kv(){if(!fl){let t=(sm(),Ww(nm));fl=t.default||t}return fl}function ml(t,e,{threshold:n=.1}={}){let o=Pi(),s=kv(),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=vv(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 vv(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 Sv(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=Ev(i.color||"#FF0000");i.type==="box"?(Tv(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"?(Rv(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"&&(Cv(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 Ev(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 Tv(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 Rv(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 Cv(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*Av(t,e,{maxIterations:n=20,hmrDelay:o=1500,width:s=1280,height:r=800,timeout:i=3e4}={}){let{browserScreenshot:a}=kn(),c=Ov("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 Mv(()=>d,3e5),d=!1,l++,await Nv(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 Ov(t){try{return require(t)}catch{return null}}function Nv(t){return new Promise(e=>setTimeout(e,t))}function Mv(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 Pv(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:Lv(d,f,p),rgb:`rgb(${d}, ${f}, ${p})`,frequency:parseFloat((l/i*100).toFixed(1)),category:Iv(d,f,p)}}),c=jv(o);return{colors:a,spacing:c,dimensions:{width:o.width,height:o.height},imagePath:t}}function Lv(t,e,n){return"#"+[t,e,n].map(o=>Math.min(255,o).toString(16).padStart(2,"0")).join("")}function Iv(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 jv(t){let e=[],n=!1,o=0,s=Dv(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 Dv(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 qv(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:Sv,annotateImage:am,visualWatch:Av,extractDesignTokens:Pv,designCompare:qv,DEFAULT_VIEWPORTS:im}});var gl=Q((hO,lm)=>{var{C:qe}=rt(),Go="",yt=[],Yo=0,ss=null;function Fv(t){ss=t}function Bv(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 Uv(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 Wv(){return{name:Go,tasks:yt.map(t=>({...t}))}}function Hv(){Go="",yt=[],Yo=0,ss&&ss("clear",{})}function Yv(){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 Gv(){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 zv(){return yt.length>0&&yt.some(t=>t.status==="pending"||t.status==="in_progress")}lm.exports={createTasks:Bv,updateTask:Uv,getTaskList:Wv,clearTasks:Hv,getReadyTasks:Yv,renderTaskList:Gv,setOnChange:Fv,hasActiveTasks:zv}});var Li=Q((mO,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.
150
+ Then restart nex-code.`;function sh(){if(Wo!==null)return Wo;try{require("playwright"),Wo=!0}catch{Wo=!1}return Wo}async function Ni(){if(!sh())throw new Error(nh);return Jc||(Jc=require("playwright")),(!xn||!xn.isConnected())&&(xn=await Jc.chromium.launch({headless:!0})),xn}async function mk(){if(xn){try{await xn.close()}catch(t){console.error("closeBrowser failed:",t.message)}xn=null}}globalThis[Zc]&&process.off("exit",globalThis[Zc]);var oh=()=>{if(xn)try{xn.close()}catch(t){console.error("Error closing browser on exit:",t.message)}};globalThis[Zc]=oh;process.on("exit",oh);async function gk(t,{timeout:e=3e4,waitFor:n="domcontentloaded"}={}){let s=await(await Ni()).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 yk(t,{width:e=1280,height:n=800,fullPage:o=!1,timeout:s=3e4}={}){let i=await(await Ni()).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 wk(t,{selector:e,text:n,timeout:o=3e4}={}){if(!e&&!n)throw new Error("selector or text is required");let r=await(await Ni()).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 bk(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 Ni()).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()}}rh.exports={isPlaywrightAvailable:sh,browserNavigate:gk,browserScreenshot:yk,browserClick:wk,browserFill:bk,closeBrowser:mk,INSTALL_MSG:nh}});var Qc=Q((ZA,ah)=>{"use strict";var $k=require("util"),ih=require("stream"),Vt=ah.exports=function(){ih.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};$k.inherits(Vt,ih);Vt.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))};Vt.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};Vt.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()))};Vt.prototype.destroySoon=Vt.prototype.end;Vt.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};Vt.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};Vt.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))};Vt.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)};Vt.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 tl=Q(el=>{"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]}];el.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};el.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 nl=Q((eO,ch)=>{"use strict";ch.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 sl=Q((tO,uh)=>{"use strict";var _k=tl(),xk=nl();function lh(t,e,n){let o=t*e;return n!==8&&(o=Math.ceil(o/(8/n))),o}var Xs=uh.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=_k.getImagePasses(n,o);for(let c=0;c<a.length;c++)this._images.push({byteWidth:lh(a[c].width,r,i),height:a[c].height,lineIndex:0})}else this._images.push({byteWidth:lh(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=xk(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 ph=Q((nO,fh)=>{"use strict";var kk=require("util"),dh=Qc(),vk=sl(),Sk=fh.exports=function(t){dh.call(this);let e=[],n=this;this._filter=new vk(t,{read:this.read.bind(this),write:function(o){e.push(o)},complete:function(){n.emit("complete",Buffer.concat(e))}}),this._filter.start()};kk.inherits(Sk,dh)});var Vs=Q((sO,hh)=>{"use strict";hh.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 il=Q((oO,mh)=>{"use strict";var ol=[];(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;ol[t]=e}})();var rl=mh.exports=function(){this._crc=-1};rl.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=ol[(this._crc^t[e])&255]^this._crc>>>8;return!0};rl.prototype.crc32=function(){return this._crc^-1};rl.crc32=function(t){let e=-1;for(let n=0;n<t.length;n++)e=ol[(e^t[n])&255]^e>>>8;return e^-1}});var al=Q((rO,gh)=>{"use strict";var st=Vs(),Ek=il(),at=gh.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(){}};at.prototype.start=function(){this.read(st.PNG_SIGNATURE.length,this._parseSignature.bind(this))};at.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))};at.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 Ek,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))};at.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};at.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};at.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))};at.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};at.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()};at.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};at.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()};at.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};at.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()};at.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};at.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/st.GAMMA_DIVISION),this._handleChunkEnd()};at.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};at.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()};at.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};at.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var cl=Q(wh=>{"use strict";var yh=tl(),Tk=[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]}],Rk=[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 Ck(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 Ak(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);Tk[o](e,s,d,r),r+=o}return r}function Ok(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);Rk[o](e,d,f,r)}s.resetAfterLine()}}wh.dataToBitMap=function(t,e){let n=e.width,o=e.height,s=e.depth,r=e.bpp,i=e.interlace,a;s!==8&&(a=Ck(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=yh.getImagePasses(n,o),f=yh.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=Ak(d[p],c,f,r,t,l):Ok(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 ll=Q((aO,bh)=>{"use strict";function Nk(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 Mk(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 Pk(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}}bh.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?Nk(t,u,s,r,c):(a&&Mk(t,u,s,r,a),o!==8&&!n&&(o===16&&(u=Buffer.alloc(s*r*4)),Pk(t,u,s,r,o))),u}});var xh=Q((cO,_h)=>{"use strict";var Lk=require("util"),ul=require("zlib"),$h=Qc(),Ik=ph(),jk=al(),Dk=cl(),qk=ll(),dn=_h.exports=function(t){$h.call(this),this._parser=new jk(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()};Lk.inherits(dn,$h);dn.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};dn.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=ul.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,ul.Z_MIN_CHUNK);this._inflate=ul.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)};dn.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new Ik(this._bitmapInfo)};dn.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};dn.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};dn.prototype._simpleTransparency=function(){this._metaData.alpha=!0};dn.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};dn.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};dn.prototype._complete=function(t){if(this.errord)return;let e;try{let n=Dk.dataToBitMap(t,this._bitmapInfo);e=qk(n,this._bitmapInfo,this._options.skipRescale),n=null}catch(n){this._handleError(n);return}this.emit("parsed",e)}});var vh=Q((lO,kh)=>{"use strict";var Bt=Vs();kh.exports=function(t,e,n,o){let s=[Bt.COLORTYPE_COLOR_ALPHA,Bt.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=Bt.COLORTYPE_TO_BPP_MAP[o.inputColorType];a===4&&!o.inputHasAlpha&&(a=3);let c=Bt.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 Bt.COLORTYPE_COLOR_ALPHA:_=r[l+3],h=r[l],g=r[l+1],w=r[l+2];break;case Bt.COLORTYPE_COLOR:h=r[l],g=r[l+1],w=r[l+2];break;case Bt.COLORTYPE_ALPHA:_=r[l+1],h=r[l],g=h,w=h;break;case Bt.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 Bt.COLORTYPE_COLOR_ALPHA:case Bt.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 Bt.COLORTYPE_ALPHA:case Bt.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 Th=Q((uO,Eh)=>{"use strict";var Sh=nl();function Fk(t,e,n,o,s){for(let r=0;r<n;r++)o[s+r]=t[e+r]}function Bk(t,e,n){let o=0,s=e+n;for(let r=e;r<s;r++)o+=Math.abs(t[r]);return o}function Uk(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 Wk(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 Hk(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 Yk(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 Gk(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 zk(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 Kk(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]-Sh(a,c,u);o[s+i]=l}}function Xk(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]-Sh(i,a,c);s+=Math.abs(u)}return s}var Vk={0:Fk,1:Uk,2:Hk,3:Gk,4:Kk},Jk={0:Bk,1:Wk,2:Yk,3:zk,4:Xk};Eh.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=Jk[r[p]](t,c,i,s);h<f&&(l=r[p],f=h)}}u[a]=l,a++,Vk[l](t,c,i,u,a,s),a+=i,c+=i}return u}});var dl=Q((dO,Rh)=>{"use strict";var pt=Vs(),Zk=il(),Qk=vh(),ev=Th(),tv=require("zlib"),In=Rh.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||tv.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=Qk(t,e,n,this._options),s=pt.COLORTYPE_TO_BPP_MAP[this._options.colorType];return ev(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 Nh=Q((fO,Oh)=>{"use strict";var nv=require("util"),Ch=require("stream"),sv=Vs(),ov=dl(),Ah=Oh.exports=function(t){Ch.call(this);let e=t||{};this._packer=new ov(e),this._deflate=this._packer.createDeflate(),this.readable=!0};nv.inherits(Ah,Ch);Ah.prototype.pack=function(t,e,n,o){this.emit("data",Buffer.from(sv.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 Dh=Q((Ho,jh)=>{"use strict";var Mh=require("assert").ok,Js=require("zlib"),rv=require("util"),Ph=require("buffer").kMaxLength;function ns(t){if(!(this instanceof ns))return new ns(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 iv(t){return new ns(t)}function Lh(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}ns.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(Mh(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}Mh(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>=Ph)throw Lh(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+Ph.toString(16)+" bytes");let p=Buffer.concat(c,u);return Lh(this),p};rv.inherits(ns,Js.Inflate);function av(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 Ih(t,e){return av(new ns(e),t)}jh.exports=Ho=Ih;Ho.Inflate=ns;Ho.createInflate=iv;Ho.inflateSync=Ih});var fl=Q((pO,Fh)=>{"use strict";var qh=Fh.exports=function(t){this._buffer=t,this._reads=[]};qh.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};qh.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 Uh=Q(Bh=>{"use strict";var cv=fl(),lv=sl();Bh.process=function(t,e){let n=[],o=new cv(t);return new lv(e,{read:o.read.bind(o),write:function(r){n.push(r)},complete:function(){}}).start(),o.process(),Buffer.concat(n)}});var Gh=Q((mO,Yh)=>{"use strict";var Wh=!0,Hh=require("zlib"),uv=Dh();Hh.deflateSync||(Wh=!1);var dv=fl(),fv=Uh(),pv=al(),hv=cl(),mv=ll();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;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 dv(t);if(new pv(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=Hh.inflateSync(g);else{let v=((s.width*s.bpp*s.depth+7>>3)+1)*s.height;w=uv(g,{chunkSize:v,maxLength:v})}if(g=null,!w||!w.length)throw new Error("bad png - invalid inflate data response");let _=fv.process(w,s);g=null;let S=hv.dataToBitMap(_,s);_=null;let A=mv(S,s,e.skipRescale);return s.data=A,s.gamma=u||0,s}});var Vh=Q((gO,Xh)=>{"use strict";var zh=!0,Kh=require("zlib");Kh.deflateSync||(zh=!1);var gv=Vs(),yv=dl();Xh.exports=function(t,e){if(!zh)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 yv(n),s=[];s.push(Buffer.from(gv.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=Kh.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 Jh=Q(pl=>{"use strict";var wv=Gh(),bv=Vh();pl.read=function(t,e){return wv(t,e||{})};pl.write=function(t,e){return bv(t,e)}});var em=Q(Qh=>{"use strict";var $v=require("util"),Zh=require("stream"),_v=xh(),xv=Nh(),kv=Jh(),gt=Qh.PNG=function(t){Zh.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 _v(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 xv(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"))};$v.inherits(gt,Zh);gt.sync=kv;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 rm={};Hw(rm,{default:()=>sm});function sm(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(!hl(t)||!hl(e)||n&&!hl(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++)nm(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:om(t,e,ee,ee,!1);if(Math.abs(be)>_){let ve=tm(t,T,le,o,s,h,g)||tm(e,T,le,o,s,g,h);!l&&ve?n&&!f&&Pi(n,ee,S,A,E):(n&&(be<0?Pi(n,ee,oe,ue,fe):Pi(n,ee,v,N,ne)),ie++)}else n&&!f&&nm(t,ee,a,n)}return ie}function hl(t){return ArrayBuffer.isView(t)&&t.BYTES_PER_ELEMENT===1}function tm(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=om(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:Mi(r,g,w,o,s)&&Mi(i,g,w,o,s)||Mi(r,_,S,o,s)&&Mi(i,_,S,o,s)}function Mi(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 om(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 Pi(t,e,n,o,s){t[e+0]=n,t[e+1]=o,t[e+2]=s,t[e+3]=255}function nm(t,e,n,o){let s=255+(t[e]*.29889531+t[e+1]*.58662247+t[e+2]*.11448223-255)*n*t[e+3]/255;Pi(o,e,s,s,s)}var im=Ww(()=>{});var ss=Q((bO,dm)=>{var vn=require("fs"),vv=require("path"),Sv=require("os"),Ev="nex-visual-";function cm(t){return vv.join(Sv.tmpdir(),`${Ev}${Date.now()}-${t}`)}var ml=null;function Li(){return ml||(ml=em().PNG),ml}var gl=null;function Tv(){if(!gl){let t=(im(),Gw(rm));gl=t.default||t}return gl}function bl(t,e,{threshold:n=.1}={}){let o=Li(),s=Tv(),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=am(r,a,c),l=am(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=Rv(d.data,a,c,3,3),w=cm("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 am(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 Rv(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 lm=[{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 Cv(t,{viewports:e=lm,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 um(t,e=[]){let n=Li(),o=n.sync.read(vn.readFileSync(t));for(let i of e){let a=Av(i.color||"#FF0000");i.type==="box"?(Ov(o,i.x||0,i.y||0,i.width||50,i.height||50,a,i.thickness||3),i.label&&wl(o,i.x||0,(i.y||0)-14,i.label,a)):i.type==="arrow"?(Nv(o,i.x||0,i.y||0,i.toX||i.x+50,i.toY||i.y,a,i.thickness||3),i.label&&wl(o,i.x||0,(i.y||0)-14,i.label,a)):i.type==="circle"&&(Mv(o,i.x||0,i.y||0,i.radius||20,a,i.thickness||3),i.label&&wl(o,(i.x||0)-(i.radius||20),(i.y||0)-(i.radius||20)-14,i.label,a))}let s=cm("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 Av(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 fn(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 Ov(t,e,n,o,s,r,i=3){for(let a=0;a<i;a++){for(let c=0;c<o;c++)fn(t,e+c,n+a,r),fn(t,e+c,n+s-1-a,r);for(let c=0;c<s;c++)fn(t,e+a,n+c,r),fn(t,e+o-1-a,n+c,r)}}function yl(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;_++)fn(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 Nv(t,e,n,o,s,r,i=3){yl(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;yl(t,o,s,Math.round(o+c*Math.cos(u)),Math.round(s+c*Math.sin(u)),r,i),yl(t,o,s,Math.round(o+c*Math.cos(l)),Math.round(s+c*Math.sin(l)),r,i)}function Mv(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));fn(t,l,d,s)}}}function wl(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++)fn(t,e+u,n+c,{r:0,g:0,b:0,a:200});for(let c=0;c<i;c++)fn(t,e+c,n+a-1,s),fn(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++)fn(t,u+d,n+l,s)}}async function*Pv(t,e,{maxIterations:n=20,hmrDelay:o=1500,width:s=1280,height:r=800,timeout:i=3e4}={}){let{browserScreenshot:a}=kn(),c=Lv("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 jv(()=>d,3e5),d=!1,l++,await Iv(o);let p=await a(t,{width:s,height:r,timeout:i}),h=null;try{h=bl(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 Lv(t){try{return require(t)}catch{return null}}function Iv(t){return new Promise(e=>setTimeout(e,t))}function jv(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 Dv(t,{sampleRate:e=4}={}){let o=Li().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:qv(d,f,p),rgb:`rgb(${d}, ${f}, ${p})`,frequency:parseFloat((l/i*100).toFixed(1)),category:Fv(d,f,p)}}),c=Bv(o);return{colors:a,spacing:c,dimensions:{width:o.width,height:o.height},imagePath:t}}function qv(t,e,n){return"#"+[t,e,n].map(o=>Math.min(255,o).toString(16).padStart(2,"0")).join("")}function Fv(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 Bv(t){let e=[],n=!1,o=0,s=Uv(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 Uv(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 Wv(t,e,{width:n,height:o=800,fullPage:s=!1,threshold:r=.1,timeout:i=3e4}={}){let{browserScreenshot:a}=kn(),u=Li().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=bl(e,f.path,{threshold:r}),h=um(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}}dm.exports={pixelDiff:bl,responsiveSweep:Cv,annotateImage:um,visualWatch:Pv,extractDesignTokens:Dv,designCompare:Wv,DEFAULT_VIEWPORTS:lm}});var $l=Q(($O,fm)=>{var{C:qe}=it(),Go="",yt=[],Yo=0,os=null;function Hv(t){os=t}function Yv(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 os&&os("create",{name:t,tasks:n}),n}function Gv(t,e,n){let o=yt.find(s=>s.id===t);return o?(o.status=e,n!==void 0&&(o.result=n),os&&os("update",{id:t,status:e,result:n}),{...o}):null}function zv(){return{name:Go,tasks:yt.map(t=>({...t}))}}function Kv(){Go="",yt=[],Yo=0,os&&os("clear",{})}function Xv(){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 Vv(){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 Jv(){return yt.length>0&&yt.some(t=>t.status==="pending"||t.status==="in_progress")}fm.exports={createTasks:Yv,updateTask:Gv,getTaskList:zv,clearTasks:Kv,getReadyTasks:Xv,renderTaskList:Vv,setOnChange:Hv,hasActiveTasks:Jv}});var Ii=Q((_O,hm)=>{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.`}},um={staleWarn:6e4,staleAbort:12e4,investigationCap:18,postEditCap:10};function Kv(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 Xv(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:Kv,getModelBriefing:Xv,PROFILES:zo,DEFAULTS:um}});var wl=Q((gO,ym)=>{var{callChat:Vv}=ct(),{estimateTokens:yl}=fn(),fm=process.env.NEX_COMPACTION!=="false",pm=6,hm=2e3,mm=3,Jv=`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.`}},pm={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]}:{...pm};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 Qv(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||""}hm.exports={getModelProfile:Zv,getModelBriefing:Qv,PROFILES:zo,DEFAULTS:pm}});var xl=Q((xO,$m)=>{var{callChat:eS}=lt(),{estimateTokens:_l}=pn(),mm=process.env.NEX_COMPACTION!=="false",gm=6,ym=2e3,wm=3,tS=`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 Zv(t){if(!fm||t.length<pm||os>=mm)return null;let e=[{role:"system",content:Jv},{role:"user",content:gm(t)}];try{let o=((await Vv(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 Qv(){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}
197
+ </summary>`,rs=0;async function nS(t){if(!mm||t.length<gm||rs>=wm)return null;let e=[{role:"system",content:tS},{role:"user",content:bm(t)}];try{let o=((await eS(e,[],{temperature:0,maxTokens:ym})).content||"").trim();if(!o)return rs++,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 rs++,null;let r=t.reduce((a,c)=>a+_l(c.content||"")+(c.tool_calls?_l(JSON.stringify(c.tool_calls)):0),0),i=_l(o);return i>=r*.8?(rs++,null):(rs=0,{message:{role:"system",content:`[Conversation Summary \u2014 ${t.length} messages compacted]
198
+ ${o}`,_compacted:!0,_originalCount:t.length},tokensRemoved:r-i})}catch{return rs++,null}}function sS(){rs=0}function bm(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
- `)}ym.exports={compactMessages:Zv,formatMessagesForSummary:gm,resetCompactionFailures:Qv,COMPACTION_ENABLED:fm,COMPACTION_MIN_MESSAGES:pm,COMPACTION_SUMMARY_BUDGET:hm,MAX_CONSECUTIVE_FAILURES:mm}});var fn=Q((yO,Tm)=>{var eS=require("path");function bm(){return ct().getActiveModel()}var tS={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},nS={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 sS(){if(is!==null)return is;try{let t=bm(),e=t?.provider||"ollama",n=(t?.id||"").toLowerCase();for(let[o,s]of Object.entries(nS))if(n.startsWith(o))return is=s,is;return is=tS[e]||4,is}catch{return 4}}function oS(){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/sS());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 rS(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 Jt(t){let e=0;for(let n of t)e+=cs(n);return e}function iS(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 aS(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 cS=200,lS=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(`
201
+ `)}$m.exports={compactMessages:nS,formatMessagesForSummary:bm,resetCompactionFailures:sS,COMPACTION_ENABLED:mm,COMPACTION_MIN_MESSAGES:gm,COMPACTION_SUMMARY_BUDGET:ym,MAX_CONSECUTIVE_FAILURES:wm}});var pn=Q((kO,Am)=>{var oS=require("path");function xm(){return lt().getActiveModel()}var rS={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},iS={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},is=new Map,_m=1e3,kl=new WeakMap,as=null;function aS(){if(as!==null)return as;try{let t=xm(),e=t?.provider||"ollama",n=(t?.id||"").toLowerCase();for(let[o,s]of Object.entries(iS))if(n.startsWith(o))return as=s,as;return as=rS[e]||4,as}catch{return 4}}function cS(){as=null}function cs(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=is.get(e);if(n!==void 0)return is.delete(e),is.set(e,n),n;let o=Math.ceil(t.length/aS());if(is.size>=_m){let s=_m>>1,r=is.keys();for(let i=0;i<s;i++)is.delete(r.next().value)}return is.set(e,o),o}function lS(t){if(kl.has(t))return kl.get(t);let e=JSON.stringify(t);return kl.set(t,e),e}function ls(t){let n=4;if(t.content&&(n+=cs(t.content)),t.tool_calls)for(let o of t.tool_calls){n+=4,n+=cs(o.function?.name||"");let s=o.function?.arguments;typeof s=="string"?n+=cs(s):s&&(n+=cs(JSON.stringify(s)))}return n}function Jt(t){let e=0;for(let n of t)e+=ls(n);return e}function uS(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+=ls(e[r]);return s}var vl=new WeakMap;function ji(t){if(!t||t.length===0)return 0;if(vl.has(t))return vl.get(t);let e=cs(JSON.stringify(t));return vl.set(t,e),e}function Di(){return xm()?.contextWindow||32768}var wt={msgCount:-1,lastMsgRef:null,toolCount:-1,result:null,messagesRef:null,messageTokens:0,systemTokens:0,conversationTokens:0,toolResultTokens:0};function dS(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=ls(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=ls(p);s+=h,p.role==="system"?r+=h:p.role==="tool"?a+=h:i+=h}}let c=ji(e),u=s+c,l=Di(),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,km=parseFloat(process.env.NEX_SAFETY_MARGIN)||.1,vm=parseInt(process.env.NEX_KEEP_RECENT,10)||10,Sm={essential:.6,standard:.65,full:Math.min(Ko,.75)};function Em(){if(process.env.NEX_COMPRESSION_THRESHOLD)return Ko;try{let{getActiveTier:t}=Uo(),e=t();return Sm[e]??Ko}catch{return Ko}}var fS=200,pS=1e3;function Tm(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:lS,o=e==="aggressive"?50:e==="medium"?100:cS;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(eS.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 uS(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:pS,o=e==="aggressive"?50:e==="medium"?100:fS;if(t.role==="tool"){let s=typeof t.content=="string"?t.content:JSON.stringify(t.content);return s.length>o?{...t,content:Tm(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 Rm(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(oS.basename(c)))&&a++;s+=Math.min(30,a*10)}return Math.min(100,s)}function Cm(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 hS(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 dS(){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 fS(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=Jt(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=Jt(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=Jt(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=Jt(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=Jt(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=Jt(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 pS(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 mS(){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 gS(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??Em(),r=n.safetyMargin??km,i=n.keepRecent??vm,a=Di(),c=ji(e),u=Math.floor(a*(s-r)),l=u-c,d=Jt(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=Jt(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=Jt(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=Jt(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}=xl(),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=Jt(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=Cm([...A,...S]),fe=A.map((ie,le)=>({msg:ie,score:ie._pinned?1/0:Rm(ie,le,A.length,ue),tokens:ls(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=Jt(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 yS(t,e){if(!t)return"";if(cs(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 hS=6;function mS(t,e,n=!1){let o=ji(),s=Ii(e),r=Math.floor(o*(n?.35:.5))-s,i=Jt(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:hS,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=Jt(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=Jt(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-Jt(g)}}Tm.exports={estimateTokens:as,estimateMessageTokens:cs,estimateMessagesTokens:Jt,estimateDeltaTokens:iS,estimateToolsTokens:Ii,serializeMessage:rS,getContextWindow:ji,getUsage:aS,compressMessage:Qs,compressToolResult:vm,scoreMessageRelevance:Sm,extractActiveFiles:Em,buildProgressSnapshot:uS,fitToContext:fS,forceCompress:mS,truncateFileContent:pS,invalidateTokenRatioCache:oS,invalidateFitToContextCache:dS,getEffectiveCompressionThreshold:km,COMPRESSION_THRESHOLD:Ko,TIER_COMPRESSION_THRESHOLDS:xm,SAFETY_MARGIN:$m,KEEP_RECENT:_m}});var to=Q((wO,Rm)=>{var{fork:gS}=require("child_process"),yS=require("path"),wS=yS.join(__dirname,"background-worker.js"),ls=new Map,eo=new Map;function bS(){return`bg-${Date.now()}-${Math.random().toString(36).slice(2,6)}`}function $S(t){let e=bS(),n=gS(wS,[],{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 xS(){return ls.size>0||eo.size>0}function kS(){let t=ls.size;return t===0?"":`${t} bg agent${t===1?"":"s"} running`}function vS(){for(let[t,e]of ls){try{e.process.kill("SIGTERM")}catch{}ls.delete(t)}eo.clear()}Rm.exports={createJob:$S,getCompletedJobs:_S,getPendingJobSummary:kS,hasPendingOrCompletedJobs:xS,cancelAllJobs:vS}});var Sl=Q(($O,Xm)=>{var{callStream:SS,getActiveProviderName:qi,getActiveModelId:Cm,getConfiguredProviders:ES,getProvider:Am,getActiveProvider:Om,parseModelSpec:Nm}=ct(),{parseToolArgs:Mm}=Ao(),{filterToolsForModel:TS,getModelTier:Di}=Uo(),{getModelBriefing:RS}=Li(),{trackUsage:Pm,estimateTokens:Lm}=ii(),{MultiProgress:CS,C:bO}=rt();function Im(t){return!t||typeof t!="string"?0:typeof Lm=="function"?Lm(t):Math.ceil(t.length/4)}var qm=15,AS=parseInt(process.env.NEX_MAX_PARALLEL||"5",10),jm=parseInt(process.env.NEX_MAX_CHAT_RETRIES||"3",10),Fm=8,OS=2,Fi=new Map,Bm=600*1e3;function NS(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 SS(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 MS=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:""}},PS=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,LS=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function Gm(t){return LS.test(t)?"full":PS.test(t)?"essential":t.length>300?"full":"standard"}function zm(t){let e=ES(),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 IS={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=IS[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.
220
+ `;return a+f+u}var wS=6;function bS(t,e,n=!1){let o=Di(),s=ji(e),r=Math.floor(o*(n?.35:.5))-s,i=Jt(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:wS,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=Jt(g);for(;h.length>0&&w>r;){let v=h.shift();w-=ls(v)}n&&w>r&&(p=p.filter(N=>N.role==="user").slice(-1),g=jn(c,[],p),w=Jt(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-Jt(g)}}Am.exports={estimateTokens:cs,estimateMessageTokens:ls,estimateMessagesTokens:Jt,estimateDeltaTokens:uS,estimateToolsTokens:ji,serializeMessage:lS,getContextWindow:Di,getUsage:dS,compressMessage:Qs,compressToolResult:Tm,scoreMessageRelevance:Rm,extractActiveFiles:Cm,buildProgressSnapshot:hS,fitToContext:gS,forceCompress:bS,truncateFileContent:yS,invalidateTokenRatioCache:cS,invalidateFitToContextCache:mS,getEffectiveCompressionThreshold:Em,COMPRESSION_THRESHOLD:Ko,TIER_COMPRESSION_THRESHOLDS:Sm,SAFETY_MARGIN:km,KEEP_RECENT:vm}});var to=Q((vO,Om)=>{var{fork:$S}=require("child_process"),_S=require("path"),xS=_S.join(__dirname,"background-worker.js"),us=new Map,eo=new Map;function kS(){return`bg-${Date.now()}-${Math.random().toString(36).slice(2,6)}`}function vS(t){let e=kS(),n=$S(xS,[],{silent:!0,env:process.env,cwd:process.cwd()});return n.send({jobId:e,agentDef:t}),n.on("message",o=>{o.type==="result"?Sl(e,t,o.payload):o.type==="error"&&Sl(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(us.has(e)){let r=s?`killed (${s})`:`exit code ${o}`;Sl(e,t,{task:t.task,status:"failed",result:`Background agent terminated unexpectedly: ${r}`,toolsUsed:[],tokensUsed:{input:0,output:0}})}}),us.set(e,{process:n,agentDef:t,startedAt:Date.now()}),e}function Sl(t,e,n){us.delete(t),eo.set(t,{jobId:t,agentDef:e,result:n,finishedAt:Date.now()})}function SS(){if(eo.size===0)return[];let t=[...eo.values()];return eo.clear(),t}function ES(){return us.size>0||eo.size>0}function TS(){let t=us.size;return t===0?"":`${t} bg agent${t===1?"":"s"} running`}function RS(){for(let[t,e]of us){try{e.process.kill("SIGTERM")}catch{}us.delete(t)}eo.clear()}Om.exports={createJob:vS,getCompletedJobs:SS,getPendingJobSummary:TS,hasPendingOrCompletedJobs:ES,cancelAllJobs:RS}});var Cl=Q((EO,Zm)=>{var{callStream:CS,getActiveProviderName:Fi,getActiveModelId:Nm,getConfiguredProviders:AS,getProvider:Mm,getActiveProvider:Pm,parseModelSpec:Lm}=lt(),{parseToolArgs:Im}=Ao(),{filterToolsForModel:OS,getModelTier:qi}=Uo(),{getModelBriefing:NS}=Ii(),{trackUsage:jm,estimateTokens:Dm}=ai(),{MultiProgress:MS,C:SO}=it();function qm(t){return!t||typeof t!="string"?0:typeof Dm=="function"?Dm(t):Math.ceil(t.length/4)}var Um=15,PS=parseInt(process.env.NEX_MAX_PARALLEL||"5",10),Fm=parseInt(process.env.NEX_MAX_CHAT_RETRIES||"3",10),Wm=8,LS=2,Bi=new Map,Hm=600*1e3;function IS(t,e){let n=Bi.get(t);return n&&n.agentId!==e&&Date.now()-n.timestamp<Hm?!1:(Bi.set(t,{agentId:e,timestamp:Date.now()}),!0)}function Xo(t){Bi.delete(t)}function El(){Bi.clear()}function Tl(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 Ym(t){let e=Tl(t);return e==="rate_limit"||e==="server"||e==="network"||e==="timeout"}async function Gm(t,e,n){let o;for(let s=0;s<=Fm;s++)try{return await CS(t,e,n)}catch(r){o=r;let i=Tl(r);if(i==="auth")throw r.message=`Authentication failed \u2014 check your API key or permissions. (${r.message})`,r;if(i==="context_overflow")throw r.message=`Context window exceeded \u2014 reduce message history or use a model with a larger context. (${r.message})`,r;if(s<Fm&&Ym(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 Bm=new Set(["ask_user","task_list"]);function zm(t){return t>=2?new Set([...Bm,"spawn_agents"]):Bm}var jS=new Set(["write_file","edit_file","patch_file"]),Km={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:""}},DS=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,qS=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function Xm(t){return qS.test(t)?"full":DS.test(t)?"essential":t.length>300?"full":"standard"}function Vm(t){let e=AS(),n=Fi(),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(qi(r.id,s.name)===t)return{provider:s.name,model:r.id};return null}var FS={essential:process.env.NEX_FAST_MODEL||null,standard:process.env.NEX_STANDARD_MODEL||null,full:process.env.NEX_HEAVY_MODEL||null};function Ui(t){if(t.model){let{provider:s,model:r}=Lm(t.model),i=s?Mm(s):Pm(),a=s||Fi();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let c=qi(r,a);return{provider:a,model:r,tier:c}}}let e=Xm(t.task),n=FS[e];if(n){let{provider:s,model:r}=Lm(n),i=s?Mm(s):Pm(),a=s||Fi();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let c=qi(r,a);return{provider:a,model:r,tier:c}}}let o=Vm(e);if(o){let s=qi(o.model,o.provider);return{provider:o.provider,model:o.model,tier:s}}return{provider:null,model:null,tier:null}}async function Jm(t,e={},n=0){let o=n===0?Um:Wm,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&&Ym[t.type],f=d&&d.systemSuffix?`
246
+ - After 2 failed attempts at the same operation, summarize the issue and stop.`,d=t.type&&Km[t.type],f=d&&d.systemSuffix?`
247
247
 
248
- ${d.systemSuffix}`:"",p=Bi(t),h=p.provider,g=p.model,w=p.tier,_=RS(g||Cm()),A=[{role:"system",content:(_?`## Model Briefing
248
+ ${d.systemSuffix}`:"",p=Ui(t),h=p.provider,g=p.model,w=p.tier,_=NS(g||Nm()),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=Hm(n),ne=TS(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(MS.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)||!NS(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?AS:OS,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 CS(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
- `)}catch(l){return u.stop(),xl(),`ERROR: Sub-agent execution failed: ${l.message}`}}async function jS(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(", ")}]
253
+ `:"")+l+f}];A.push({role:"user",content:t.task});let{TOOL_DEFINITIONS:E,executeTool:v}=zs(),N=zm(n),ne=OS(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 Gm(A,ne,oe);if(!le||typeof le!="object")throw new Error("Empty or invalid response from provider");{let Me=h||Fi(),Ee=g||Nm();if(le.usage){let x=le.usage.prompt_tokens||0,P=le.usage.completion_tokens||0;a.input+=x,a.output+=P,jm(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=qm(P),te=qm(x);a.input+=B,a.output+=te,a._estimated=!0,jm(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=Im(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(jS.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)||!IS(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"?Rl(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}=pn(),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=Im(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 Rl(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?PS:LS,o=e===0?Um:Wm,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=>Ui(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 MS(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 Jm(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(),El();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
+ `)}catch(l){return u.stop(),El(),`ERROR: Sub-agent execution failed: ${l.message}`}}async function BS(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=Ui(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
- 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(`
259
+ Results will be injected into the conversation when each agent completes.`),o.length>0){let i=await Rl({agents:o});r.push(i)}return r.join(`
260
260
 
261
- `)||"No agents specified."}Xm.exports={runSubAgent:Km,executeSpawnAgents:vl,executeSpawnAgentsBackground:jS,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((_O,lg)=>{var Je=require("fs"),Sn=require("path"),{atomicWrite:Vm,withFileLockSync:Jm}=Jn(),DS=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 qS(t,e){let n=Sn.join(so(),`${t}.md`);Vm(n,e),US(t,e),FS()}function FS(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return;let t=Rl();Je.existsSync(t)&&setImmediate(async()=>{try{await rg()}catch{}})}function BS(t){let e=Sn.join(so(),`${t}.md`);return Je.existsSync(e)?(Je.unlinkSync(e),WS(t),!0):!1}function Ui(t){return t.toLowerCase().replace(/[^a-z0-9äöüß\s-]/g," ").split(/[\s-]+/).filter(e=>e.length>2&&!DS.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 US(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 WS(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,HS=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-HS}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},YS=3e5;async function GS(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<YS)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))+`
261
+ `)||"No agents specified."}Zm.exports={runSubAgent:Jm,executeSpawnAgents:Rl,executeSpawnAgentsBackground:BS,clearAllLocks:El,classifyTask:Xm,pickModelForTier:Vm,resolveSubAgentModel:Ui,classifyError:Tl,isRetryableError:Ym,callWithRetry:Gm,getExcludedTools:zm,LOCK_TIMEOUT_MS:Hm,SUB_AGENT_TYPES:Km}});var jl=Q((TO,fg)=>{var Je=require("fs"),Sn=require("path"),{atomicWrite:Qm,withFileLockSync:eg}=Zn(),US=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 Hi(){return Sn.join(so(),".brain-index.json")}function Nl(){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 tg(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 WS(t,e){let n=Sn.join(so(),`${t}.md`);Qm(n,e),GS(t,e),HS()}function HS(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return;let t=Nl();Je.existsSync(t)&&setImmediate(async()=>{try{await cg()}catch{}})}function YS(t){let e=Sn.join(so(),`${t}.md`);return Je.existsSync(e)?(Je.unlinkSync(e),zS(t),!0):!1}function Wi(t){return t.toLowerCase().replace(/[^a-z0-9äöüß\s-]/g," ").split(/[\s-]+/).filter(e=>e.length>2&&!US.has(e))}function Ml(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 Wi(a))e[c]=(e[c]||0)+3}for(let i of Wi(o||t))e[i]=(e[i]||0)+1;return e}function Pl(){let t=Hi();if(!Je.existsSync(t))return{documents:{}};try{return JSON.parse(Je.readFileSync(t,"utf-8"))}catch{return{documents:{}}}}function Ll(t){Qm(Hi(),JSON.stringify(t,null,2))}function GS(t,e){eg(Hi(),()=>{let n=Pl(),{frontmatter:o}=Jo(e),s=Array.isArray(o.tags)?o.tags:[];n.documents[t]={keywords:Ml(e),tags:s,modified:new Date().toISOString()},Ll(n)})}function zS(t){eg(Hi(),()=>{let e=Pl();delete e.documents[t],Ll(e)})}function Ol(){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:Ml(o),tags:r,modified:n.modified.toISOString()}}return Ll(e),e}function ng(){let t=Pl(),e=Vo();for(let n of e){let o=t.documents[n.name];if(!o||new Date(o.modified)<n.modified)return Ol()}for(let n of Object.keys(t.documents))if(!e.some(o=>o.name===n))return Ol();return t}function sg(t,e={}){let{topK:n=3,minScore:o=.1}=e,s=Wi(t);if(s.length===0)return[];let r=ng(),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 og=process.env.NEX_EMBED_MODEL||"nomic-embed-text",Al=400,KS=50;async function rg(){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(og.split(":")[0]))}catch{return!1}}async function Il(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:og,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 ig(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 ag(t){let e=t.split(/\s+/),n=[],o=0;for(;o<e.length;){let s=e.slice(o,o+Al).join(" ");if(n.push({text:s,offset:o}),o+Al>=e.length)break;o+=Al-KS}return n}async function cg(){let t=Vo(),e={documents:{}},n=Nl();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=ag(r),a=[];for(let c of i){let u=await Il(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 lg(t,e={}){let{topK:n=3,minSimilarity:o=.3}=e,s=Nl();if(!Je.existsSync(s))return[];let r;try{r=JSON.parse(Je.readFileSync(s,"utf-8"))}catch{return[]}let i=await Il(t),a=[];for(let[c,u]of Object.entries(r.documents||{})){let l=0,d="";for(let f of u.chunks||[]){let p=ig(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 ug(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 dg(t,e={}){let{topK:n=3,minScore:o=.1}=e,s=sg(t,{topK:n,minScore:o}),r=s;if(process.env.NEX_BRAIN_EMBEDDINGS!=="false")try{if(await rg()){let a=await lg(t,{topK:n});r=ug(s,a,{topK:n})}}catch{}return r.map(i=>{let a=tg(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},XS=3e5;async function VS(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<XS)return no.result;let s;try{s=await dg(t,{topK:3})}catch{return""}if(!s||s.length===0)return"";let r;try{r=pn().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}lg.exports={getBrainDir:so,listDocuments:Vo,readDocument:Zm,writeDocument:qS,removeDocument:BS,buildIndex:Tl,getIndex:Qm,query:cg,getBrainContext:GS,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((xO,_g)=>{var Be=require("fs"),At=require("path"),zS=require("os"),{atomicWrite:Hi,withFileLockSync:ug}=Jn(),Zo=["user","feedback","project","reference"],KS=50;function us(){return At.join(process.cwd(),".nex","memory")}function oo(){return At.join(us(),"memory.json")}function dg(){return At.join(us(),"MEMORY.md")}function XS(){return At.join(process.cwd(),"NEX.md")}function fg(){return At.join(zS.homedir(),".nex","NEX.md")}function Yi(){let t=us();Be.existsSync(t)||Be.mkdirSync(t,{recursive:!0})}function pg(t){let e=At.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=At.join(a,`${i}.md`),u=r.split(`
269
+ `)}`;return no={queryKey:o,result:u,ts:Date.now()},u}fg.exports={getBrainDir:so,listDocuments:Vo,readDocument:tg,writeDocument:WS,removeDocument:YS,buildIndex:Ol,getIndex:ng,query:dg,getBrainContext:VS,isEmbeddingAvailable:rg,generateEmbedding:Il,buildEmbeddingIndex:cg,semanticQuery:lg,cosineSimilarity:ig,_keywordQuery:sg,_extractKeywords:Ml,_chunkText:ag,parseFrontmatter:Jo,tokenize:Wi,_fuseResults:ug}});var er=Q((RO,vg)=>{var Be=require("fs"),At=require("path"),JS=require("os"),{atomicWrite:Yi,withFileLockSync:pg}=Zn(),Zo=["user","feedback","project","reference"],ZS=50;function ds(){return At.join(process.cwd(),".nex","memory")}function oo(){return At.join(ds(),"memory.json")}function hg(){return At.join(ds(),"MEMORY.md")}function QS(){return At.join(process.cwd(),"NEX.md")}function mg(){return At.join(JS.homedir(),".nex","NEX.md")}function Gi(){let t=ds();Be.existsSync(t)||Be.mkdirSync(t,{recursive:!0})}function gg(t){let e=At.join(ds(),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 yg(t){Gi(),Yi(oo(),JSON.stringify(t,null,2))}function wg(){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=gg("project"),c=At.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 VS(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=At.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
+ `;Yi(c,l)}zi();try{Be.renameSync(t,t+".bak")}catch{}}function eE(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=gg(t),i=At.join(r,`${s}.md`);if(Be.existsSync(i))try{if(Dl(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 JS(t,e){if(!Zo.includes(t))return!1;let n=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase(),o=At.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=At.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=At.join(o,r);try{let a=Be.readFileSync(i,"utf-8"),c=Pl(a);t.push({type:n,name:c.name||At.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>=KS+2)break;let o=`${n.type}/${At.basename(n.filePath)}`;e.push(`- [${n.name}](${o}) \u2014 ${n.description||"(no description)"}`)}Yi(),Hi(dg(),e.join(`
285
+ `;return Yi(i,c),zi(),{ok:!0,path:i,updated:!0}}function tE(t,e){if(!Zo.includes(t))return!1;let n=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase(),o=At.join(ds(),t,`${n}.md`);if(!Be.existsSync(o))return!1;try{return Be.unlinkSync(o),zi(),!0}catch{return!1}}function Dl(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 bg(){let t=[],e=ds();for(let n of Zo){let o=At.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=At.join(o,r);try{let a=Be.readFileSync(i,"utf-8"),c=Dl(a);t.push({type:n,name:c.name||At.basename(r,".md"),description:c.description,filePath:i})}catch{}}}return t}function zi(){let t=bg(),e=["# Project Memory Index",""];for(let n of t){if(e.length>=ZS+2)break;let o=`${n.type}/${At.basename(n.filePath)}`;e.push(`- [${n.name}](${o}) \u2014 ${n.description||"(no description)"}`)}Gi(),Yi(hg(),e.join(`
286
286
  `)+`
287
- `)}function yg(){let t=dg();if(!Be.existsSync(t))return"";try{return Be.readFileSync(t,"utf-8").trim()}catch{return""}}function ZS(t,e){Yi(),ug(oo(),()=>{let n=Qo();n[t]={value:e,updatedAt:new Date().toISOString()},hg(n)})}function QS(t){let e=Qo();return e[t]?e[t].value:null}function eE(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=XS();if(!Be.existsSync(t))return"";try{return Be.readFileSync(t,"utf-8").trim()}catch{return""}}function tE(){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:
287
+ `)}function $g(){let t=hg();if(!Be.existsSync(t))return"";try{return Be.readFileSync(t,"utf-8").trim()}catch{return""}}function nE(t,e){Gi(),pg(oo(),()=>{let n=Qo();n[t]={value:e,updatedAt:new Date().toISOString()},yg(n)})}function sE(t){let e=Qo();return e[t]?e[t].value:null}function oE(t){return Gi(),pg(oo(),()=>{let e=Qo();return t in e?(delete e[t],yg(e),!0):!1})}function _g(){let t=Qo();return Object.entries(t).map(([e,n])=>({key:e,value:n.value,updatedAt:n.updatedAt}))}function xg(){let t=mg();if(!Be.existsSync(t))return"";try{return Be.readFileSync(t,"utf-8").trim()}catch{return""}}function kg(){let t=QS();if(!Be.existsSync(t))return"";try{return Be.readFileSync(t,"utf-8").trim()}catch{return""}}function rE(){wg();let t=[],e=xg();e&&t.push(`GLOBAL INSTRUCTIONS (~/.nex/NEX.md):
288
+ ${e}`);let n=kg();n&&t.push(`PROJECT INSTRUCTIONS (NEX.md):
289
+ ${n}`);let o="",s=$g();if(s)o=s;else{let d=_g();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,26 +295,26 @@ ${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:VS,deleteMemory:JS,scanMemories:gg,rebuildIndex:Gi,loadMemoryIndex:yg,remember:ZS,recall:QS,forget:eE,listMemories:wg,loadGlobalInstructions:bg,loadProjectInstructions:$g,getMemoryContext:tE,_getMemoryDir:us,_getMemoryFile:oo,_getGlobalNexMdPath:fg,_parseMemoryFile:Pl,_migrateIfNeeded:mg,VALID_TYPES:Zo}});var Tg=Q((kO,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 nE(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 sE(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 oE(t){Il=t}function rE(){return Il}function iE(){ds=null}Eg.exports={logToolExecution:nE,sanitizeArgs:vg,readAuditLog:Sg,getAuditSummary:sE,setAuditEnabled:oE,isAuditEnabled:rE,getAuditLogPath:kg,_reset:iE}});var Gg=Q((SO,Yg)=>{var Ze=require("fs").promises,Qt=require("fs"),ae=require("path"),Ye=require("util").promisify(require("child_process").exec),fs=require("util").promisify(require("child_process").execFile),{spawnSync:aE}=require("child_process"),jl=require("axios"),{isForbidden:cE,isSSHForbidden:lE,isDangerous:uE,isCritical:Rg,isBashPathForbidden:dE,confirm:Zt}=No(),{showDiff:zi,showNewFile:fE,showEditDiff:vO,confirmFileChange:nr}=jf(),{C:pe,Spinner:pE,getToolSpinnerText:hE}=rt(),{ToolProgress:Ki}=Yn(),{isGitRepo:Dl,getCurrentBranch:Cg,getStatus:mE,getDiff:gE}=di(),{recordChange:Xi}=Kf(),{fuzzyFindText:Ag,findMostSimilar:ar}=wp(),{runDiagnostics:sr}=Cp(),{findFileInIndex:yE,getFileIndex:Og,searchContentIndex:wE,scorePathMatch:Ng,refreshIndex:bE,isIndexValid:$E}=cn(),{resolveProfile:Ft,sshExec:bt,scpUpload:_E,scpDownload:Mg}=Ks(),{resolveDeployConfig:xE,loadDeployConfigs:kE}=Vp(),{getEditMode:Pg}=Uo(),vE=/^(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/,SE=/^ssh\s/,EE=/^ssh(?:\s+-\S+)*\s+\S+@?\S+\s+["']?[^-]/;async function Ot(t){return Ze.access(t).then(()=>!0).catch(()=>!1)}var Vi=null,Lg=0,TE=12e4;function RE(){let t=Date.now();if(Vi&&t-Lg<TE)return Vi;let e=ae.dirname(process.cwd());try{let n=Qt.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=RE();if(!e)return"";let n=ae.dirname(process.cwd());return`
298
+ `)}vg.exports={saveMemory:eE,deleteMemory:tE,scanMemories:bg,rebuildIndex:zi,loadMemoryIndex:$g,remember:nE,recall:sE,forget:oE,listMemories:_g,loadGlobalInstructions:xg,loadProjectInstructions:kg,getMemoryContext:rE,_getMemoryDir:ds,_getMemoryFile:oo,_getGlobalNexMdPath:mg,_parseMemoryFile:Dl,_migrateIfNeeded:wg,VALID_TYPES:Zo}});var Ag=Q((CO,Cg)=>{var tr=require("fs"),ql=require("path"),Fl=process.env.NEX_AUDIT!=="false",fs=null;function Sg(){return fs||(fs=ql.join(process.cwd(),".nex","audit"),tr.existsSync(fs)||tr.mkdirSync(fs,{recursive:!0}),fs)}function Eg(){let t=new Date().toISOString().split("T")[0];return ql.join(Sg(),`${t}.jsonl`)}function iE(t){if(Fl)try{let e={timestamp:new Date().toISOString(),tool:t.tool,args:Tg(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(Eg(),n,"utf-8")}catch{}}function Tg(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 Rg(t={}){let e=Sg(),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=ql.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 aE(t=1){let e=Rg({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 cE(t){Fl=t}function lE(){return Fl}function uE(){fs=null}Cg.exports={logToolExecution:iE,sanitizeArgs:Tg,readAuditLog:Rg,getAuditSummary:aE,setAuditEnabled:cE,isAuditEnabled:lE,getAuditLogPath:Eg,_reset:uE}});var Xg=Q((OO,Kg)=>{var Ze=require("fs").promises,Qt=require("fs"),ae=require("path"),Ye=require("util").promisify(require("child_process").exec),ps=require("util").promisify(require("child_process").execFile),{spawnSync:dE}=require("child_process"),Bl=require("axios"),{isForbidden:fE,isSSHForbidden:pE,isDangerous:hE,isCritical:Og,isBashPathForbidden:mE,confirm:Zt}=No(),{showDiff:Ki,showNewFile:gE,showEditDiff:AO,confirmFileChange:nr}=qf(),{C:pe,Spinner:yE,getToolSpinnerText:wE}=it(),{ToolProgress:Xi}=Gn(),{isGitRepo:Ul,getCurrentBranch:Ng,getStatus:bE,getDiff:$E}=fi(),{recordChange:Vi}=Vf(),{fuzzyFindText:Mg,findMostSimilar:ar}=$p(),{runDiagnostics:sr}=Op(),{findFileInIndex:_E,getFileIndex:Pg,searchContentIndex:xE,scorePathMatch:Lg,refreshIndex:kE,isIndexValid:vE}=ln(),{resolveProfile:Ut,sshExec:bt,scpUpload:SE,scpDownload:Ig}=Ks(),{resolveDeployConfig:EE,loadDeployConfigs:TE}=Zp(),{getEditMode:jg}=Uo(),RE=/^(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/,CE=/^ssh\s/,AE=/^ssh(?:\s+-\S+)*\s+\S+@?\S+\s+["']?[^-]/;async function Ot(t){return Ze.access(t).then(()=>!0).catch(()=>!1)}var Ji=null,Dg=0,OE=12e4;function NE(){let t=Date.now();if(Ji&&t-Dg<OE)return Ji;let e=ae.dirname(process.cwd());try{let n=Qt.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 Ji=s.length>0?s:null,Dg=t,Ji}catch{return null}}function Wl(t){if(t&&ae.resolve(t)!==process.cwd())return"";let e=NE();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
- 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 Ot(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 Ot(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 Ot(c))return{fixedPath:c,message:`(auto-fixed: ${s} \u2192 ${a})`}}}let r=ae.basename(t);if(r&&r.length>2)try{let i=yE(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:
303
+ You can search there with: grep pattern --path ${n}/<dir>`}async function Zi(t){if(!t)return{fixedPath:null,message:""};let e=t.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),n=dt(e);if(n&&await Ot(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=dt(t+i);if(a&&await Ot(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=dt(i+a);if(c&&await Ot(c))return{fixedPath:c,message:`(auto-fixed: ${s} \u2192 ${a})`}}}let r=ae.basename(t);if(r&&r.length>2)try{let i=_E(r).map(a=>dt(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:
304
304
  ${i.map(c=>ae.relative(process.cwd(),c)).map(c=>` - ${c}`).join(`
305
- `)}`}}catch{}if(r&&r.length>2)try{let i=r.toLowerCase(),{getFileIndex:a}=cn(),c=a().filter(u=>ae.basename(u).toLowerCase()===i).map(u=>ut(u));if(c.length===1)return{fixedPath:c[0],message:`(auto-fixed: case-insensitive match \u2192 ${ae.relative(process.cwd(),c[0])})`};if(c.length>1&&c.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
305
+ `)}`}}catch{}if(r&&r.length>2)try{let i=r.toLowerCase(),{getFileIndex:a}=ln(),c=a().filter(u=>ae.basename(u).toLowerCase()===i).map(u=>dt(u));if(c.length===1)return{fixedPath:c[0],message:`(auto-fixed: case-insensitive match \u2192 ${ae.relative(process.cwd(),c[0])})`};if(c.length>1&&c.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
306
306
  ${c.map(l=>ae.relative(process.cwd(),l)).map(l=>` - ${l}`).join(`
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
- ${a.map(l=>ae.relative(process.cwd(),ut(l.file))).map(l=>` - ${l}`).join(`
309
- `)}`}}}catch{}return{fixedPath:null,message:""}}function CE(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 wE(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(`
307
+ `)}`}}catch{}try{let{smartSearch:i}=ln(),a=i(t,{limit:5,minScore:15});if(a.length>0){let c=dt(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
+ ${a.map(l=>ae.relative(process.cwd(),dt(l.file))).map(l=>` - ${l}`).join(`
309
+ `)}`}}}catch{}return{fixedPath:null,message:""}}function ME(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 Ug(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 Wg(t,e){let n=Ug(t);if(!n)return new Map;try{let o=await xE(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 qg(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 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+`
311
+ `).filter(o=>o.trim()):[]}function Hg(t,{query:e,basePath:n,definitionScores:o=new Map,mtimeByPath:s=new Map}={}){let r=Ug(e);return[...t].sort((i,a)=>{let c=qg(i,n),u=qg(a,n),l=0,d=0;if(r&&(l+=Lg(c,r),d+=Lg(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 Hl(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 Wg(e,n),a=Hg(r,{query:e,basePath:n,definitionScores:i}),c=[];for(let u of a)c.push(...s.get(u)||[]);return c}function Yg(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 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 AE(){ps&&(ps(),ps=null)}var Hl=null;function OE(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 NE=[/\.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 ME(){let t=process.cwd();try{return Qt.realpathSync(t)}catch{return ae.resolve(t)}}function PE(t,e){let n=ae.relative(e,t);return n===""||!n.startsWith("..")&&!ae.isAbsolute(n)}function LE(t){if(Qt.existsSync(t))return Qt.realpathSync(t);let e=ae.dirname(t);for(;e&&e!==ae.dirname(e);){if(Qt.existsSync(e)){let n=Qt.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 NE)if(o.test(e))return null;let n=LE(e);return PE(n,ME())?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 IE(t){return typeof t=="string"&&/^[a-zA-Z0-9@_.:-]+(?:\.service)?$/.test(t)}function jE(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 DE(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 IE(t)?null:`ERROR: ${e} contains unsafe characters`}var qE=[{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=cE(o);if(s){let d=CE(o);return`BLOCKED: Command matches forbidden pattern: ${s}${d?`
315
- HINT: ${d}`:""}`}let r=dE(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?Rg(o):uE(o)){let d=Rg(o)?"\u26D4":"\u26A0";if(!await Zt(` ${d} bash: \`${o}\``,{toolName:"bash"}))return"CANCELLED: User declined to execute this command."}let a;try{a=process.cwd(),Qt.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=SE.test(o.trim())&&!EE.test(o.trim());if(vE.test(o.trim())||c){n.silent||console.log(`${pe.dim} \u25B6 interactive: ${o}${pe.reset}`);let d=aE("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
- ${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 Ot(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?`
314
+ `)}function Gg(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 Fg=!1,hs=null;function PE(){hs&&(hs(),hs=null)}var Kl=null;function LE(t){Kl=t}async function Yl(){if(!Fg){Fg=!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 IE=[/\.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 jE(){let t=process.cwd();try{return Qt.realpathSync(t)}catch{return ae.resolve(t)}}function DE(t,e){let n=ae.relative(e,t);return n===""||!n.startsWith("..")&&!ae.isAbsolute(n)}function qE(t){if(Qt.existsSync(t))return Qt.realpathSync(t);let e=ae.dirname(t);for(;e&&e!==ae.dirname(e);){if(Qt.existsSync(e)){let n=Qt.realpathSync(e),o=ae.relative(e,t);return ae.resolve(n,o)}e=ae.dirname(e)}return t}function dt(t){let e=ae.isAbsolute(t)?ae.resolve(t):ae.resolve(process.cwd(),t);for(let o of IE)if(o.test(e))return null;let n=qE(e);return DE(n,jE())?n:null}function Ae(t){return`'${String(t).replace(/'/g,"'\\''")}'`}function zg(t){return typeof t=="string"&&/^[a-z_][a-z0-9_-]{0,31}\$?$/i.test(t)}function FE(t){return typeof t=="string"&&/^[a-zA-Z0-9@_.:-]+(?:\.service)?$/.test(t)}function BE(t){return typeof t=="string"&&/^[a-zA-Z0-9+_.:@/-]+$/.test(t)}function Gl(t){return typeof t=="string"&&/^\d{1,5}(?:\/(?:tcp|udp))?$/i.test(t)}function UE(t){return typeof t=="string"&&/^(?:SIG[A-Z0-9]+|[A-Z0-9]+|\d{1,2})$/.test(t)}function rr(t,e="user"){return zg(t)?null:`ERROR: ${e} contains unsafe characters`}function zl(t,e="service"){return FE(t)?null:`ERROR: ${e} contains unsafe characters`}var WE=[{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 Bg(t,e,n={}){switch(t){case"bash":{let o=e.command,s=fE(o);if(s){let d=ME(o);return`BLOCKED: Command matches forbidden pattern: ${s}${d?`
315
+ HINT: ${d}`:""}`}let r=mE(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?Og(o):hE(o)){let d=Og(o)?"\u26D4":"\u26A0";if(!await Zt(` ${d} bash: \`${o}\``,{toolName:"bash"}))return"CANCELLED: User declined to execute this command."}let a;try{a=process.cwd(),Qt.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=CE.test(o.trim())&&!AE.test(o.trim());if(RE.test(o.trim())||c){n.silent||console.log(`${pe.dim} \u25B6 interactive: ${o}${pe.reset}`);let d=dE("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}=Gn(),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=Yg(f,o);return`EXIT ${d.code||1}
317
+ ${p}`}}case"read_file":{let o=new Xi("read_file","Reading file...");o.start();try{let s=dt(e.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await Ot(s)){let ue=await Zi(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 Qt.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(`
320
320
  `),oe=w?`
@@ -322,12 +322,12 @@ ${p}`}}case"read_file":{let o=new Ki("read_file","Reading file...");o.start();tr
322
322
  [\u{1F6A8} FILE TRUNCATED: You are only seeing lines 1-${h} of ${p} total lines. The rest of the file is HIDDEN. You MUST use line_start and line_end to read further down (e.g. line_start=${h+1}), or use grep_search to find specific keywords.]`:!g&&p>S?`
323
323
 
324
324
  [\u{1F6A8} FILE CONTINUES: This is only lines ${_+1} to ${S} of ${p} total. The rest is HIDDEN. Use line_start=${S+1} to read the next section, or grep_search for keywords.]`:"";return`${N}
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 Ot(s),i=null,a=String(e.content||"").split(`
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(fE(s,e.content,{annotations:f}),!await nr("Create"))return"CANCELLED: User declined to create file."}let c=ae.dirname(s);await Ot(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 Ot(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?`
325
+ ${ne}${oe}`}finally{o.stop()}}case"write_file":{let o=new Xi("write_file","Preparing write...");o.start();try{await Yl();let s=dt(e.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let r=await Ot(s),i=null,a=String(e.content||"").split(`
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(Ki(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(gE(s,e.content,{annotations:f}),!await nr("Create"))return"CANCELLED: User declined to create file."}let c=ae.dirname(s);await Ot(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)),Vi("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 Xi("edit_file","Preparing edit...");o.start();try{await Yl();let s=dt(e.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await Ot(s)){let d=await Zi(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(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)
328
+ `)[0].slice(0,40)}`});let{getActiveModelId:d,getActiveProviderName:f}=lt();if(jg(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=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(`
330
+ ${g.text}`:`ERROR: old_text not found in ${s} (strict mode \u2014 exact match required)`}let h=Mg(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=Gg(i,e.old_text,e.new_text);if(g){if(!n.autoConfirm){let E=await sr(s,g.content);if(Ki(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),Vi("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
 
@@ -338,27 +338,27 @@ Fix: update old_text to match the exact lines above, then retry. If you need mor
338
338
  `)[0].slice(0,60),S=_?`
339
339
  Recovery: grep -n "${_.replace(/"/g,'\\"')}" <file> to find the line, then re-read that section with line_start/line_end.`:`
340
340
  Recovery: use grep -n to locate the text, then re-read that section with line_start/line_end.`;return`ERROR: old_text not found in ${s}${S}`}}if(!n.autoConfirm){o.update({message:"Previewing edit",detail:`${ae.relative(process.cwd(),s)} ${String(e.new_text||"").trim().split(`
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
- `)[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 Ot(o)){let u=e.path.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),l=ut(u),d=await Ot(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
- `)||"(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=Og();$E(r)||(await bE(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(`
341
+ `)[0].slice(0,40)}`});let d=i.split(a).join(e.new_text),f=await sr(s,d);if(Ki(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
+ `)[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)),Vi("edit_file",s,i,l),c?`Edited: ${s} (fuzzy match)`:`Edited: ${s}`}finally{o.stop()}}case"list_directory":{let o=dt(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await Ot(o)){let u=e.path.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),l=dt(u),d=await Ot(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
+ `)||"(empty)"}case"search_files":{let o=dt(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 ps("grep",s,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),i=or(r).slice(0,50);return(await Hl(i,{query:e.pattern,basePath:o})).join(`
344
+ `)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let s=process.cwd(),r=e.path?dt(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}=Gn(),f=new d("glob","Finding files...");f.start();let p=Pg();vE(r)||(await kE(r),p=Pg());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)"+Wl(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 Wg(i,r),S=Hg(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
- \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
- `);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 Ot(_)){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
- `).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
- `).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 Ot(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=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)
347
+ \u26A0 Results truncated at 200. Use a more specific pattern.`:E}case"grep":{let o=e.path?dt(e.path):process.cwd();if(e.staged){let{getDiff:c}=fi(),u=await c(!0);if(!u.trim())return"(no staged changes)";let l=new Set,d=u.split(`
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}=Gn(),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 Ot(_)){let S=[...f];S.push(e.pattern,_);let{stdout:A}=await ps("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 Hl(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
+ `).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}=Gn(),a=new i("grep","Searching...");a.start();try{let{stdout:c}=await ps("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 Hl(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
+ `).trim()||"(no matches)"+Wl(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)"+Wl(e.path)}}case"patch_file":{let o=new Xi("patch_file","Preparing patches...");o.start();try{await Yl();let s=dt(e.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await Ot(s)){let S=await Zi(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}=lt(),l=jg(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=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}
353
+ ${v.text}`:`ERROR: Patch ${S+1} old_text not found in ${s} (strict mode \u2014 exact match required)`}else{let v=Mg(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
- ${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]
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(Ki(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)),Vi("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 Bl.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 Bl.post("https://api.perplexity.ai/chat/completions",{model:"sonar",messages:[{role:"user",content:e.query}],max_tokens:1024,search_recency_filter:"month",return_citations:!0},{timeout:2e4,headers:{Authorization:`Bearer ${process.env.PERPLEXITY_API_KEY}`,"Content-Type":"application/json"}}),r=s.data?.choices?.[0]?.message?.content||"",i=s.data?.citations||[],a=`[Perplexity grounded search]
356
356
 
357
357
  ${r}`;return i.length>0&&(a+=`
358
358
 
359
359
  Sources:
360
360
  `+i.slice(0,o).map((c,u)=>`${u+1}. ${c}`).join(`
361
- `)),a}catch(s){console.error(`${pe.dim} Perplexity search failed (${s.message}), falling back to DuckDuckGo${pe.reset}`)}try{let r=(await jl.get("https://html.duckduckgo.com/html/",{params:{q:e.query},timeout:1e4,responseType:"text",headers:{"User-Agent":"nex-code/0.2.0"}})).data,i=[],a=/<a[^>]*class="result__a"[^>]*href="([^"]*)"[^>]*>([\s\S]*?)<\/a>/gi,c;for(;(c=a.exec(r))!==null&&i.length<o;){let u=c[1].replace(/.*uddg=/,"").split("&")[0],l=c[2].replace(/<[^>]+>/g,"").trim();try{i.push({title:l,url:decodeURIComponent(u)})}catch{i.push({title:l,url:u})}}return i.length===0?"(no results)":i.map((u,l)=>`${l+1}. ${u.title}
361
+ `)),a}catch(s){console.error(`${pe.dim} Perplexity search failed (${s.message}), falling back to DuckDuckGo${pe.reset}`)}try{let r=(await Bl.get("https://html.duckduckgo.com/html/",{params:{q:e.query},timeout:1e4,responseType:"text",headers:{"User-Agent":"nex-code/0.2.0"}})).data,i=[],a=/<a[^>]*class="result__a"[^>]*href="([^"]*)"[^>]*>([\s\S]*?)<\/a>/gi,c;for(;(c=a.exec(r))!==null&&i.length<o;){let u=c[1].replace(/.*uddg=/,"").split("&")[0],l=c[2].replace(/<[^>]+>/g,"").trim();try{i.push({title:l,url:decodeURIComponent(u)})}catch{i.push({title:l,url:u})}}return i.length===0?"(no results)":i.map((u,l)=>`${l+1}. ${u.title}
362
362
  ${u.url}`).join(`
363
363
 
364
364
  `)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:o}=kn();try{let s=await o(e.url,{waitFor:e.wait_for}),r=s.links.length>0?`
@@ -389,10 +389,10 @@ Analyze the screenshot above and provide structured feedback:
389
389
  4. Responsiveness concerns at this viewport
390
390
  5. Specific issues related to: ${r}`;return e.compare_with&&Qt.existsSync(e.compare_with)&&(i+=`
391
391
 
392
- COMPARISON: Previous screenshot at ${e.compare_with} \u2014 describe what changed.`),{text:i,images:[{path:s.path,base64:s.base64,media_type:"image/png"}],compare_with:e.compare_with||null}}catch(s){return`ERROR: ${s.message}`}}case"clipboard_image":try{let{_grabClipboardImage:o}=Yl(),s=o();return s?{text:`Clipboard image captured: ${s.path}
392
+ COMPARISON: Previous screenshot at ${e.compare_with} \u2014 describe what changed.`),{text:i,images:[{path:s.path,base64:s.base64,media_type:"image/png"}],compare_with:e.compare_with||null}}catch(s){return`ERROR: ${s.message}`}}case"clipboard_image":try{let{_grabClipboardImage:o}=Xl(),s=o();return s?{text:`Clipboard image captured: ${s.path}
393
393
  Size: ${Math.round(Buffer.from(s.data,"base64").length/1024)} KB
394
394
 
395
- [Clipboard image is attached for visual analysis]`,images:[{path:s.path,base64:s.data,media_type:s.media_type}]}:"No image found in clipboard. Copy a screenshot first (Cmd+Shift+4 on macOS), then try again."}catch(o){return`ERROR: ${o.message}`}case"browser_click":{let{browserClick:o}=kn();try{return await o(e.url,{selector:e.selector,text:e.text})}catch(s){return`ERROR: ${s.message}`}}case"browser_fill":{let{browserFill:o}=kn();try{return await o(e.url,{selector:e.selector,value:e.value,submit:e.submit})}catch(s){return`ERROR: ${s.message}`}}case"visual_diff":try{let{pixelDiff:o}=ns(),s=o(e.before,e.after,{threshold:e.threshold}),r=s.regionSummary.slice(0,5),i=r.length?r.map(a=>` ${a.name}: ${a.changedPercent}% changed`).join(`
395
+ [Clipboard image is attached for visual analysis]`,images:[{path:s.path,base64:s.data,media_type:s.media_type}]}:"No image found in clipboard. Copy a screenshot first (Cmd+Shift+4 on macOS), then try again."}catch(o){return`ERROR: ${o.message}`}case"browser_click":{let{browserClick:o}=kn();try{return await o(e.url,{selector:e.selector,text:e.text})}catch(s){return`ERROR: ${s.message}`}}case"browser_fill":{let{browserFill:o}=kn();try{return await o(e.url,{selector:e.selector,value:e.value,submit:e.submit})}catch(s){return`ERROR: ${s.message}`}}case"visual_diff":try{let{pixelDiff:o}=ss(),s=o(e.before,e.after,{threshold:e.threshold}),r=s.regionSummary.slice(0,5),i=r.length?r.map(a=>` ${a.name}: ${a.changedPercent}% changed`).join(`
396
396
  `):" No significant regional changes";return{text:`VISUAL DIFF \u2014 ${s.diffPercent}% of pixels changed
397
397
  Changed: ${s.changedPixels.toLocaleString()} / ${s.totalPixels.toLocaleString()} pixels
398
398
  Canvas: ${s.width}\xD7${s.height}
@@ -401,7 +401,7 @@ Diff image: ${s.diffPath}
401
401
  Regional breakdown:
402
402
  ${i}
403
403
 
404
- [Diff image attached \u2014 red/magenta pixels indicate changes]`,images:[{path:s.diffPath,base64:Qt.readFileSync(s.diffPath).toString("base64"),media_type:"image/png"}]}}catch(o){return`ERROR: ${o.message}`}case"responsive_sweep":try{let{responsiveSweep:o}=ns(),s=await o(e.url,{viewports:e.viewports,fullPage:e.full_page}),r=s.map(i=>` ${i.label} (${i.width}px): ${i.path}`).join(`
404
+ [Diff image attached \u2014 red/magenta pixels indicate changes]`,images:[{path:s.diffPath,base64:Qt.readFileSync(s.diffPath).toString("base64"),media_type:"image/png"}]}}catch(o){return`ERROR: ${o.message}`}case"responsive_sweep":try{let{responsiveSweep:o}=ss(),s=await o(e.url,{viewports:e.viewports,fullPage:e.full_page}),r=s.map(i=>` ${i.label} (${i.width}px): ${i.path}`).join(`
405
405
  `);return{text:`RESPONSIVE SWEEP \u2014 ${s.length} viewports captured
406
406
  URL: ${e.url}
407
407
 
@@ -415,15 +415,15 @@ Analyze these screenshots for:
415
415
  2. Typography scaling (text too small on mobile, too large on desktop)
416
416
  3. Navigation pattern changes across viewports
417
417
  4. Image/media sizing and aspect ratio issues
418
- 5. Touch target sizes on mobile viewports`,images:s.map(i=>({path:i.path,base64:i.base64,media_type:i.media_type}))}}catch(o){return`ERROR: ${o.message}`}case"visual_annotate":try{let{annotateImage:o}=ns(),s=o(e.image,e.annotations),r=e.annotations.length,i=[...new Set(e.annotations.map(a=>a.type))].join(", ");return{text:`ANNOTATED IMAGE \u2014 ${r} annotation(s) added (${i})
418
+ 5. Touch target sizes on mobile viewports`,images:s.map(i=>({path:i.path,base64:i.base64,media_type:i.media_type}))}}catch(o){return`ERROR: ${o.message}`}case"visual_annotate":try{let{annotateImage:o}=ss(),s=o(e.image,e.annotations),r=e.annotations.length,i=[...new Set(e.annotations.map(a=>a.type))].join(", ");return{text:`ANNOTATED IMAGE \u2014 ${r} annotation(s) added (${i})
419
419
  Source: ${e.image}
420
420
  Output: ${s.path}
421
421
 
422
- [Annotated image attached with visual markers]`,images:[{path:s.path,base64:s.base64,media_type:s.media_type}]}}catch(o){return`ERROR: ${o.message}`}case"visual_watch":try{let{visualWatch:o}=ns(),s=o(e.url,e.watch,{maxIterations:e.max_iterations||10,hmrDelay:e.hmr_delay||1500}),r=await s.next();if(r.value?.type==="error")return`ERROR: ${r.value.message}`;let i=[];i.push(`VISUAL WATCH \u2014 monitoring ${e.watch.length} path(s)`,`URL: ${e.url}`,`Baseline screenshot: ${r.value?.path}`,"","Watching for file changes... (will capture up to "+(e.max_iterations||10)+" iterations)");let a=await s.next();if(!a.done&&a.value){let c=a.value;i.push("",`--- Iteration ${c.iteration} ---`,`Screenshot: ${c.path}`),c.diff&&i.push(`Diff: ${c.diff.diffPercent}% changed (${c.diff.changedPixels} pixels)`,`Regions: ${c.diff.regions.map(l=>`${l.name}:${l.changedPercent}%`).join(", ")}`);let u=[{path:c.path,base64:c.base64,media_type:c.media_type}];return c.diff?.diffPath&&u.push({path:c.diff.diffPath,base64:Qt.readFileSync(c.diff.diffPath).toString("base64"),media_type:"image/png"}),{text:i.join(`
422
+ [Annotated image attached with visual markers]`,images:[{path:s.path,base64:s.base64,media_type:s.media_type}]}}catch(o){return`ERROR: ${o.message}`}case"visual_watch":try{let{visualWatch:o}=ss(),s=o(e.url,e.watch,{maxIterations:e.max_iterations||10,hmrDelay:e.hmr_delay||1500}),r=await s.next();if(r.value?.type==="error")return`ERROR: ${r.value.message}`;let i=[];i.push(`VISUAL WATCH \u2014 monitoring ${e.watch.length} path(s)`,`URL: ${e.url}`,`Baseline screenshot: ${r.value?.path}`,"","Watching for file changes... (will capture up to "+(e.max_iterations||10)+" iterations)");let a=await s.next();if(!a.done&&a.value){let c=a.value;i.push("",`--- Iteration ${c.iteration} ---`,`Screenshot: ${c.path}`),c.diff&&i.push(`Diff: ${c.diff.diffPercent}% changed (${c.diff.changedPixels} pixels)`,`Regions: ${c.diff.regions.map(l=>`${l.name}:${l.changedPercent}%`).join(", ")}`);let u=[{path:c.path,base64:c.base64,media_type:c.media_type}];return c.diff?.diffPath&&u.push({path:c.diff.diffPath,base64:Qt.readFileSync(c.diff.diffPath).toString("base64"),media_type:"image/png"}),{text:i.join(`
423
423
  `),images:u}}return{text:i.join(`
424
424
  `)+`
425
425
 
426
- No changes detected within timeout.`,images:r.value?.base64?[{path:r.value.path,base64:r.value.base64,media_type:"image/png"}]:[]}}catch(o){return`ERROR: ${o.message}`}case"design_tokens":try{let{extractDesignTokens:o}=ns(),s=o(e.image,{sampleRate:e.sample_rate}),r=s.colors.slice(0,12).map(a=>` ${a.hex} ${a.rgb.padEnd(20)} ${a.frequency.toString().padStart(5)}% ${a.category}`).join(`
426
+ No changes detected within timeout.`,images:r.value?.base64?[{path:r.value.path,base64:r.value.base64,media_type:"image/png"}]:[]}}catch(o){return`ERROR: ${o.message}`}case"design_tokens":try{let{extractDesignTokens:o}=ss(),s=o(e.image,{sampleRate:e.sample_rate}),r=s.colors.slice(0,12).map(a=>` ${a.hex} ${a.rgb.padEnd(20)} ${a.frequency.toString().padStart(5)}% ${a.category}`).join(`
427
427
  `),i=s.spacing.length?s.spacing.map(a=>` ${a.px}px (${a.occurrences} occurrences)`).join(`
428
428
  `):" No clear spacing pattern detected";return`DESIGN TOKENS \u2014 extracted from ${s.dimensions.width}\xD7${s.dimensions.height} image
429
429
  Source: ${s.imagePath}
@@ -437,7 +437,7 @@ ${i}
437
437
  Use these values to:
438
438
  - Compare against CSS variables / design system tokens
439
439
  - Identify inconsistent colors or spacing
440
- - Generate a color palette from the rendered output`}catch(o){return`ERROR: ${o.message}`}case"design_compare":try{let{designCompare:o}=ns(),s=await o(e.url,e.reference,{width:e.width,height:e.height,threshold:e.threshold}),r=s.regions.filter(i=>i.changedPercent>.5).slice(0,6).map(i=>` ${i.name}: ${i.changedPercent}% deviation`).join(`
440
+ - Generate a color palette from the rendered output`}catch(o){return`ERROR: ${o.message}`}case"design_compare":try{let{designCompare:o}=ss(),s=await o(e.url,e.reference,{width:e.width,height:e.height,threshold:e.threshold}),r=s.regions.filter(i=>i.changedPercent>.5).slice(0,6).map(i=>` ${i.name}: ${i.changedPercent}% deviation`).join(`
441
441
  `)||" All regions match within tolerance";return{text:`DESIGN COMPARISON \u2014 ${s.diffPercent}% deviation from reference
442
442
  Reference: ${s.referencePath}
443
443
  Live: ${s.livePath}
@@ -449,24 +449,24 @@ Pixel deviation: ${s.changedPixels.toLocaleString()} / ${s.totalPixels.toLocaleS
449
449
  Regional breakdown:
450
450
  ${r}
451
451
 
452
- [Three images attached: live screenshot, pixel diff, annotated deviation map]`,images:[{path:s.livePath,base64:s.liveBase64,media_type:"image/png"},{path:s.diffPath,base64:s.diffBase64,media_type:"image/png"},{path:s.annotatedPath,base64:s.annotatedBase64,media_type:"image/png"}]}}catch(o){return`ERROR: ${o.message}`}case"ask_user":{let{question:o,options:s=[]}=e;return Hl?new Promise(r=>{ps=()=>r("CANCELLED"),Hl(o,s).then(i=>{ps=null,r(i||"User did not answer")})}):new Promise(r=>{let i=require("readline").createInterface({input:process.stdin,output:process.stdout});ps=()=>{i.close(),r("CANCELLED")};let a=s.length>0?`
452
+ [Three images attached: live screenshot, pixel diff, annotated deviation map]`,images:[{path:s.livePath,base64:s.liveBase64,media_type:"image/png"},{path:s.diffPath,base64:s.diffBase64,media_type:"image/png"},{path:s.annotatedPath,base64:s.annotatedBase64,media_type:"image/png"}]}}catch(o){return`ERROR: ${o.message}`}case"ask_user":{let{question:o,options:s=[]}=e;return Kl?new Promise(r=>{hs=()=>r("CANCELLED"),Kl(o,s).then(i=>{hs=null,r(i||"User did not answer")})}):new Promise(r=>{let i=require("readline").createInterface({input:process.stdin,output:process.stdout});hs=()=>{i.close(),r("CANCELLED")};let a=s.length>0?`
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 Cg()||"(detached)",s=await mE();if(s.length===0)return`Branch: ${o}
456
+ ${pe.cyan}${pe.bold} ? ${o}${pe.reset}${a}`),i.question(`${pe.cyan} > ${pe.reset}`,c=>{hs=null,i.close(),r(c.trim()||"(no response)")})})}case"git_status":{if(!await Ul())return"ERROR: Not a git repository";let o=await Ng()||"(detached)",s=await bE();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
- `)}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 gE(!!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(`
458
+ `)}case"git_diff":{if(!await Ul())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 $E(!!e.staged);return o||"(no diff)"}case"git_log":{if(!await Ul())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}=$l(),{getActiveTaskProgress:c}=it(),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:
460
460
  `+l.map(d=>` ${d.id}: ${d.description}`).join(`
461
461
  `)}case"update":return!e.task_id||!e.status?"ERROR: task_list update requires task_id and status":s(e.task_id,e.status,e.result)?(u||console.log(`
462
462
  `+i()),`Updated ${e.task_id}: ${e.status}${e.result?" \u2014 "+e.result:""}`):`ERROR: Task not found: ${e.task_id}`;case"get":{let l=r();return l.tasks.length===0?"No active tasks":(u||console.log(`
463
- `+i()),JSON.stringify(l,null,2))}default:return`ERROR: Unknown task_list action: ${e.action}. Use: create, update, get`}}case"spawn_agents":{let{executeSpawnAgents:o,executeSpawnAgentsBackground:s}=Sl();return e.agents?.some(r=>r.background)?s(e):o(e)}case"switch_model":{let{setActiveModel:o,getActiveProviderName:s,getActiveModelId:r}=ct();return o(e.model)?`Switched to ${s()}:${r()}`:`ERROR: Unknown model: ${e.model}. Use /providers to see available models.`}case"gh_run_list":{let o=Math.min(e.limit||10,30),s=["run","list","--limit",String(o),"--json","databaseId,status,conclusion,name,headBranch,createdAt,updatedAt,event"];e.workflow&&s.push("--workflow",e.workflow),e.branch&&s.push("--branch",e.branch),e.status&&s.push("--status",e.status);try{let{stdout:r}=await fs("gh",s,{cwd:process.cwd(),timeout:3e4}),i=JSON.parse(r||"[]");return i.length===0?"No workflow runs found.":i.map(c=>{let u=c.conclusion||c.status||"unknown",l=u==="success"?"\u2713":u==="failure"?"\u2717":u==="in_progress"?"\u283F":"\u25CB",d=c.updatedAt?new Date(c.updatedAt).toISOString().slice(0,16).replace("T"," "):"";return`${l} [${c.databaseId}] ${c.name} \xB7 ${c.headBranch} \xB7 ${u} \xB7 ${d}`}).join(`
463
+ `+i()),JSON.stringify(l,null,2))}default:return`ERROR: Unknown task_list action: ${e.action}. Use: create, update, get`}}case"spawn_agents":{let{executeSpawnAgents:o,executeSpawnAgentsBackground:s}=Cl();return e.agents?.some(r=>r.background)?s(e):o(e)}case"switch_model":{let{setActiveModel:o,getActiveProviderName:s,getActiveModelId:r}=lt();return o(e.model)?`Switched to ${s()}:${r()}`:`ERROR: Unknown model: ${e.model}. Use /providers to see available models.`}case"gh_run_list":{let o=Math.min(e.limit||10,30),s=["run","list","--limit",String(o),"--json","databaseId,status,conclusion,name,headBranch,createdAt,updatedAt,event"];e.workflow&&s.push("--workflow",e.workflow),e.branch&&s.push("--branch",e.branch),e.status&&s.push("--status",e.status);try{let{stdout:r}=await ps("gh",s,{cwd:process.cwd(),timeout:3e4}),i=JSON.parse(r||"[]");return i.length===0?"No workflow runs found.":i.map(c=>{let u=c.conclusion||c.status||"unknown",l=u==="success"?"\u2713":u==="failure"?"\u2717":u==="in_progress"?"\u283F":"\u25CB",d=c.updatedAt?new Date(c.updatedAt).toISOString().slice(0,16).replace("T"," "):"";return`${l} [${c.databaseId}] ${c.name} \xB7 ${c.headBranch} \xB7 ${u} \xB7 ${d}`}).join(`
464
464
  `)}catch(r){let i=(r.stderr||r.message||"").toString();return i.includes("not found")||i.includes("not logged")?"ERROR: gh CLI not found or not authenticated. Run: gh auth login":`ERROR: ${i.split(`
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
- ...(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(`
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 ps("gh",["run","view",String(e.run_id),"--log"],{cwd:process.cwd(),timeout:6e4,maxBuffer:5242880});return i.substring(0,8e3)+(i.length>8e3?`
466
+ ...(truncated)`:"")}let{stdout:o}=await ps("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 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
- ${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(`
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 Ng()||"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
+ ${pe.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${s}${pe.reset}`),!await o(" Trigger?"))return"CANCELLED: User declined to trigger workflow.";try{return await ps("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?`
472
472
  ...(truncated)`:"")}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
@@ -476,9 +476,9 @@ ${pe.yellow} \u26A0 kubectl exec into pod: ${e.pod} (ns: ${o})${pe.reset}`),con
476
476
  ${pe.yellow} \u26A0 kubectl apply: ${i}${e.namespace?` (ns: ${e.namespace})`:""}${pe.reset}`),!await Zt(" Apply to cluster?"))return"CANCELLED: User declined."}let s=`apply -f ${e.file}`;e.namespace&&(s+=` -n ${e.namespace}`),o&&(s+=" --dry-run=client");let r=ir(s,e);try{let{stdout:i,stderr:a}=await Ye(r,{timeout:12e4,maxBuffer:2097152});return(i||a||"(no output)").trim()}catch(i){return`ERROR: ${(i.stderr||i.message||"").toString().split(`
477
477
  `)[0]}`}}case"k8s_rollout":{if(!e.action)return"ERROR: action is required";if(!e.deployment)return"ERROR: deployment is required";let o=e.namespace||"default";if(e.action==="restart"||e.action==="undo"){let a=e.action==="restart"?"Rolling restart":"Rollback (undo)";if(console.log(`
478
478
  ${pe.yellow} \u26A0 ${a}: deployment/${e.deployment} (ns: ${o})${pe.reset}`),!await Zt(` ${a}?`))return"CANCELLED: User declined."}let r=`rollout ${e.action} deployment/${e.deployment} -n ${o}`,i=ir(r,e);try{let{stdout:a,stderr:c}=await Ye(i,{timeout:12e4,maxBuffer:2097152});return(a||c||"(no output)").trim()}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
479
- `)[0]}`}}case"brain_write":{if(!e.name)return"ERROR: name is required";if(!e.content)return"ERROR: content is required";if(!e.mode)return"ERROR: mode is required (create, update, append)";let{writeDocument:o,readDocument:s}=Ml(),{name:r,content:i,mode:a}=e;if(a==="create"&&s(r).content)return`ERROR: Document "${r}" already exists. Use mode "update" to overwrite.`;if(a==="append"){let c=s(r),u=c.content?c.content+`
479
+ `)[0]}`}}case"brain_write":{if(!e.name)return"ERROR: name is required";if(!e.content)return"ERROR: content is required";if(!e.mode)return"ERROR: mode is required (create, update, append)";let{writeDocument:o,readDocument:s}=jl(),{name:r,content:i,mode:a}=e;if(a==="create"&&s(r).content)return`ERROR: Document "${r}" already exists. Use mode "update" to overwrite.`;if(a==="append"){let c=s(r),u=c.content?c.content+`
480
480
 
481
- `+i:i;return o(r,u),`Appended to brain document: ${r}.md`}return o(r,i),`${a==="create"?"Created":"Updated"} brain document: ${r}.md`}case"ssh_exec":{if(!e.server)return"ERROR: server is required";if(!e.command)return"ERROR: command is required";let o;try{o=Ft(e.server)}catch(N){return`ERROR: ${N.message}`}let s=e.command,r=!!e.sudo,i=(e.timeout||30)*1e3,a=lE(s);if(a)return/\bsed\s+-n\s+['"]?\d+,\d+p/.test(s)?`BLOCKED: sed -n line-range is blocked (floods context). To read specific lines from a remote file use:
481
+ `+i:i;return o(r,u),`Appended to brain document: ${r}.md`}return o(r,i),`${a==="create"?"Created":"Updated"} brain document: ${r}.md`}case"ssh_exec":{if(!e.server)return"ERROR: server is required";if(!e.command)return"ERROR: command is required";let o;try{o=Ut(e.server)}catch(N){return`ERROR: ${N.message}`}let s=e.command,r=!!e.sudo,i=(e.timeout||30)*1e3,a=pE(s);if(a)return/\bsed\s+-n\s+['"]?\d+,\d+p/.test(s)?`BLOCKED: sed -n line-range is blocked (floods context). To read specific lines from a remote file use:
482
482
  grep -n "pattern" /path/to/file -A 50
483
483
  or to read the whole file:
484
484
  cat /path/to/file
@@ -498,33 +498,33 @@ ${f||p||"(no output)"}`}let h=/\bgrep\b/.test(s),g=p;h&&(g=g.split(`
498
498
  `+_.slice(-w).join(`
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
- `)||"(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=Ft(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 Zt(" 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=Ft(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}
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=Ut(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 Zt(" Upload to remote server?"))return"CANCELLED: User declined upload.";try{let i=await SE(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=Ut(e.server)}catch(s){return`ERROR: ${s.message}`}try{return await Ig(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 Ig(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}.
506
- ${p.slice(-2e3)}`:p.slice(-5e3)||"Remote nex-code completed (no output)"}case"service_manage":{if(!e.service)return"ERROR: service is required";if(!e.action)return"ERROR: action is required";let o=Wl(e.service);if(o)return o;let s=["status","start","stop","restart","reload","enable","disable"];if(!s.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${s.join(", ")}`;let r=!e.server||e.server==="local"||e.server==="localhost",i=e.action==="status",a=null;if(!r)try{a=Ft(e.server)}catch(l){return`ERROR: ${l.message}`}if(!i){let l=r?"local machine":a.user?`${a.user}@${a.host}`:a.host;if(console.log(`
506
+ ${p.slice(-2e3)}`:p.slice(-5e3)||"Remote nex-code completed (no output)"}case"service_manage":{if(!e.service)return"ERROR: service is required";if(!e.action)return"ERROR: action is required";let o=zl(e.service);if(o)return o;let s=["status","start","stop","restart","reload","enable","disable"];if(!s.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${s.join(", ")}`;let r=!e.server||e.server==="local"||e.server==="localhost",i=e.action==="status",a=null;if(!r)try{a=Ut(e.server)}catch(l){return`ERROR: ${l.message}`}if(!i){let l=r?"local machine":a.user?`${a.user}@${a.host}`:a.host;if(console.log(`
507
507
  ${pe.yellow} \u26A0 Service: systemctl ${e.action} ${e.service} on ${l}${pe.reset}`),!await Zt(" Execute?"))return"CANCELLED: User declined service action."}let c=e.service.includes(".")?e.service:`${e.service}.service`,u=`systemctl ${e.action} ${Ae(c)}`;if(r){let d=e.action!=="status"?`sudo ${u}`:u;try{let{stdout:f,stderr:p}=await Ye(d,{timeout:15e3});return(f||p||`systemctl ${e.action} ${e.service}: OK`).trim()}catch(f){let p=(f.stderr||f.message||"").toString().trim();return/not found|loaded.*not-found/i.test(p)?`ERROR: Service "${e.service}" not found. Check: systemctl list-units --type=service`:`EXIT ${f.code||1}
508
508
  ${p}`}}else{let{stdout:l,stderr:d,exitCode:f,error:p}=await bt(a,u,{timeout:15e3,sudo:!0}),h=[l,d].filter(Boolean).join(`
509
509
  `).trim();return f!==0?/not found|loaded.*not-found/i.test(h)?`ERROR: Service "${e.service}" not found on ${a.host}. Check: ssh_exec to run "systemctl list-units --type=service"`:`EXIT ${f}
510
- ${p||h||"(no output)"}`:h||`systemctl ${e.action} ${e.service}: OK`}}case"service_logs":{if(!e.service)return"ERROR: service is required";let o=Wl(e.service);if(o)return o;let s=!e.server||e.server==="local"||e.server==="localhost",r=e.lines||50,i=e.service.includes(".")?e.service:`${e.service}.service`,a=e.since?`--since ${Ae(e.since)}`:"",c=e.follow?"-f":"",u=`journalctl -u ${Ae(i)} -n ${r} ${a} ${c} --no-pager`.trim().replace(/\s+/g," ");if(s)try{let{stdout:w,stderr:_}=await Ye(u,{timeout:15e3});return(w||_||"(no log output)").trim()}catch(w){return`EXIT ${w.code||1}
511
- ${(w.stderr||w.message||"").toString().trim()}`}let l;try{l=Ft(e.server)}catch(w){return`ERROR: ${w.message}`}let{stdout:d,stderr:f,exitCode:p,error:h}=await bt(l,u,{timeout:2e4}),g=[d,f].filter(Boolean).join(`
510
+ ${p||h||"(no output)"}`:h||`systemctl ${e.action} ${e.service}: OK`}}case"service_logs":{if(!e.service)return"ERROR: service is required";let o=zl(e.service);if(o)return o;let s=!e.server||e.server==="local"||e.server==="localhost",r=e.lines||50,i=e.service.includes(".")?e.service:`${e.service}.service`,a=e.since?`--since ${Ae(e.since)}`:"",c=e.follow?"-f":"",u=`journalctl -u ${Ae(i)} -n ${r} ${a} ${c} --no-pager`.trim().replace(/\s+/g," ");if(s)try{let{stdout:w,stderr:_}=await Ye(u,{timeout:15e3});return(w||_||"(no log output)").trim()}catch(w){return`EXIT ${w.code||1}
511
+ ${(w.stderr||w.message||"").toString().trim()}`}let l;try{l=Ut(e.server)}catch(w){return`ERROR: ${w.message}`}let{stdout:d,stderr:f,exitCode:p,error:h}=await bt(l,u,{timeout:2e4}),g=[d,f].filter(Boolean).join(`
512
512
  `).trim();return p!==0?`EXIT ${p}
513
513
  ${h||g||"(no output)"}`:g||"(no log output)"}case"container_list":{let o=!e.server||e.server==="local"||e.server==="localhost",r=`docker ps ${e.all?"-a":""} --format "table {{.ID}}\\t{{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}"`.trim().replace(/\s+/g," ");if(o)try{let{stdout:f,stderr:p}=await Ye(r,{timeout:1e4});return(f||p||"(no containers)").trim()}catch(f){return`EXIT ${f.code||1}
514
- ${(f.stderr||f.message||"").toString().trim()}`}let i;try{i=Ft(e.server)}catch(f){return`ERROR: ${f.message}`}let{stdout:a,stderr:c,exitCode:u,error:l}=await bt(i,r,{timeout:15e3}),d=[a,c].filter(Boolean).join(`
514
+ ${(f.stderr||f.message||"").toString().trim()}`}let i;try{i=Ut(e.server)}catch(f){return`ERROR: ${f.message}`}let{stdout:a,stderr:c,exitCode:u,error:l}=await bt(i,r,{timeout:15e3}),d=[a,c].filter(Boolean).join(`
515
515
  `).trim();return u!==0?`EXIT ${u}
516
516
  ${l||d}`:d||"(no containers)"}case"container_logs":{if(!e.container)return"ERROR: container is required";let o=!e.server||e.server==="local"||e.server==="localhost",s=e.lines||50,r=e.since?`--since "${e.since}"`:"",i=`docker logs --tail ${s} ${r} ${e.container} 2>&1`.trim().replace(/\s+/g," ");if(o)try{let{stdout:p,stderr:h}=await Ye(i,{timeout:15e3});return(p||h||"(no log output)").trim()}catch(p){return`EXIT ${p.code||1}
517
- ${(p.stderr||p.message||"").toString().trim()}`}let a;try{a=Ft(e.server)}catch(p){return`ERROR: ${p.message}`}let{stdout:c,stderr:u,exitCode:l,error:d}=await bt(a,i,{timeout:2e4}),f=[c,u].filter(Boolean).join(`
517
+ ${(p.stderr||p.message||"").toString().trim()}`}let a;try{a=Ut(e.server)}catch(p){return`ERROR: ${p.message}`}let{stdout:c,stderr:u,exitCode:l,error:d}=await bt(a,i,{timeout:2e4}),f=[c,u].filter(Boolean).join(`
518
518
  `).trim();return l!==0?`EXIT ${l}
519
519
  ${d||f}`:f||"(no log output)"}case"container_exec":{if(!e.container)return"ERROR: container is required";if(!e.command)return"ERROR: command is required";let o=!e.server||e.server==="local"||e.server==="localhost",s=/^(cat|ls|echo|env|printenv|df|du|ps|id|whoami|uname|hostname|date|pwd|which|find\s|head\s|tail\s|grep\s|curl\s+-[A-Za-z]*G|curl\s+https?:\/\/[^\s]+$)/;if(!n.autoConfirm&&!s.test(e.command.trim())){let h=o?"local":e.server;if(console.log(`
520
520
  ${pe.yellow} \u26A0 docker exec in ${e.container} on ${h}: ${e.command}${pe.reset}`),!await Zt(" Execute?"))return"CANCELLED: User declined."}let i=(e.container||"").replace(/[^a-zA-Z0-9._\/-]/g,"");if(!i)return"ERROR: Invalid container name";let a=`docker exec ${i} sh -c ${JSON.stringify(e.command)}`;if(o)try{let{stdout:h,stderr:g}=await Ye(a,{timeout:3e4});return(h||g||"(no output)").trim()}catch(h){return`EXIT ${h.code||1}
521
- ${(h.stderr||h.message||"").toString().trim()}`}let c;try{c=Ft(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:u,stderr:l,exitCode:d,error:f}=await bt(c,a,{timeout:35e3}),p=[u,l].filter(Boolean).join(`
521
+ ${(h.stderr||h.message||"").toString().trim()}`}let c;try{c=Ut(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:u,stderr:l,exitCode:d,error:f}=await bt(c,a,{timeout:35e3}),p=[u,l].filter(Boolean).join(`
522
522
  `).trim();return d!==0?`EXIT ${d}
523
523
  ${f||p}`:p||"(no output)"}case"container_manage":{if(!e.container)return"ERROR: container is required";if(!e.action)return"ERROR: action is required";let o=["start","stop","restart","remove","inspect"];if(!o.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${o.join(", ")}`;let s=!e.server||e.server==="local"||e.server==="localhost";if(!(e.action==="inspect")&&!n.autoConfirm){let h=s?"local":e.server;if(console.log(`
524
524
  ${pe.yellow} \u26A0 docker ${e.action} ${e.container} on ${h}${pe.reset}`),!await Zt(" Execute?"))return"CANCELLED: User declined."}let i=e.action==="remove"?"rm":e.action,a=e.action==="inspect"?`docker inspect ${e.container}`:`docker ${i} ${e.container}`;if(s)try{let{stdout:h,stderr:g}=await Ye(a,{timeout:3e4});return(h||g||`docker ${e.action} ${e.container}: OK`).trim()}catch(h){return`EXIT ${h.code||1}
525
- ${(h.stderr||h.message||"").toString().trim()}`}let c;try{c=Ft(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:u,stderr:l,exitCode:d,error:f}=await bt(c,a,{timeout:35e3}),p=[u,l].filter(Boolean).join(`
525
+ ${(h.stderr||h.message||"").toString().trim()}`}let c;try{c=Ut(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:u,stderr:l,exitCode:d,error:f}=await bt(c,a,{timeout:35e3}),p=[u,l].filter(Boolean).join(`
526
526
  `).trim();return d!==0?`EXIT ${d}
527
- ${f||p}`:p||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...xE(e.config),...e},delete e.config,delete e._name}catch(l){return`ERROR: ${l.message}`}if(!e.server)return'ERROR: server is required (or use config: "<name>")';if(!e.remote_path)return"ERROR: remote_path is required";let o=e.method||"rsync";if(o==="rsync"&&!e.local_path)return"ERROR: local_path is required for rsync method";let s;try{s=Ft(e.server)}catch(l){return`ERROR: ${l.message}`}let r=s.user?`${s.user}@${s.host}`:s.host;if(!e.dry_run&&!n.autoConfirm){if(o==="git"){let d=e.branch?` (branch: ${e.branch})`:"";console.log(`
527
+ ${f||p}`:p||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...EE(e.config),...e},delete e.config,delete e._name}catch(l){return`ERROR: ${l.message}`}if(!e.server)return'ERROR: server is required (or use config: "<name>")';if(!e.remote_path)return"ERROR: remote_path is required";let o=e.method||"rsync";if(o==="rsync"&&!e.local_path)return"ERROR: local_path is required for rsync method";let s;try{s=Ut(e.server)}catch(l){return`ERROR: ${l.message}`}let r=s.user?`${s.user}@${s.host}`:s.host;if(!e.dry_run&&!n.autoConfirm){if(o==="git"){let d=e.branch?` (branch: ${e.branch})`:"";console.log(`
528
528
  ${pe.yellow} \u26A0 Deploy [git pull]: ${r}:${e.remote_path}${d}${pe.reset}`)}else{let d=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`;console.log(`
529
529
  ${pe.yellow} \u26A0 Deploy [rsync]: ${d} \u2192 ${r}:${e.remote_path}${pe.reset}`)}if(e.deploy_script&&console.log(`${pe.yellow} Then run: ${e.deploy_script}${pe.reset}`),e.health_check&&console.log(`${pe.yellow} Health check: ${e.health_check}${pe.reset}`),!await Zt(" Proceed with deployment?"))return"CANCELLED: User declined."}let i="";if(o==="git"){let l=(e.branch||"").replace(/[^a-zA-Z0-9._\/-]/g,"");if(e.branch&&l!==e.branch)return`ERROR: Invalid branch name: ${e.branch}`;let d=(e.remote_path||"").replace(/'/g,"'\\''"),f=l?`cd '${d}' && git fetch origin && git checkout '${l}' && git pull origin '${l}'`:`cd '${d}' && git pull`;if(e.dry_run)return`DRY RUN [git]: would run on ${r}:
530
530
  ${f}${e.deploy_script?`
@@ -550,7 +550,7 @@ Health check FAILED: ${l} \u2192 ${f.message}`,(o==="git"?"git pull OK":"rsync O
550
550
  Health check FAILED (exit ${h}): ${g}`,(o==="git"?"git pull OK":"rsync OK")+i+a+c;c=`
551
551
 
552
552
  Health check: \u2713 ${g||"(exit 0)"}`}}let u=o==="git"?`${r}:${e.remote_path}`:`${e.local_path} \u2192 ${r}:${e.remote_path}`;return`Deployed [${o}] ${u}
553
- ${i}${a}${c}`.trim()}case"deployment_status":{let o=kE(),s=e.config?[e.config]:Object.keys(o);if(s.length===0)return"No deploy configs found. Create .nex/deploy.json to configure deployments.";let r=[];for(let i of s){let a=o[i];if(!a){r.push(`${i}: NOT FOUND`);continue}try{let c=Ft(a.server||i),l=(await bt(c,"echo OK",{timeout:1e4})).stdout.trim()==="OK",d="unknown";if(l&&a.deploy_script){let p=a.deploy_script.match(/systemctl\s+\w+\s+(\S+)/);if(p)try{d=(await bt(c,`systemctl is-active ${p[1]}`,{timeout:1e4})).stdout.trim()}catch{d="inactive"}}let f="N/A";if(a.health_check){let p=a.health_check.trim();if(/^https?:\/\//.test(p))try{let h=require("node-fetch"),g=await Promise.race([h(p),new Promise((w,_)=>setTimeout(()=>_(new Error("timeout")),1e4))]);f=g.ok?"healthy":`HTTP ${g.status}`}catch(h){f=`unhealthy: ${h.message.substring(0,50)}`}else try{f=(await bt(c,p,{timeout:1e4})).exitCode===0?"healthy":"unhealthy"}catch{f="unhealthy"}}r.push(`${i}: server=${l?"reachable":"unreachable"} service=${d} health=${f}`)}catch(c){r.push(`${i}: ERROR \u2014 ${c.message}`)}}return`Deployment Status:
553
+ ${i}${a}${c}`.trim()}case"deployment_status":{let o=TE(),s=e.config?[e.config]:Object.keys(o);if(s.length===0)return"No deploy configs found. Create .nex/deploy.json to configure deployments.";let r=[];for(let i of s){let a=o[i];if(!a){r.push(`${i}: NOT FOUND`);continue}try{let c=Ut(a.server||i),l=(await bt(c,"echo OK",{timeout:1e4})).stdout.trim()==="OK",d="unknown";if(l&&a.deploy_script){let p=a.deploy_script.match(/systemctl\s+\w+\s+(\S+)/);if(p)try{d=(await bt(c,`systemctl is-active ${p[1]}`,{timeout:1e4})).stdout.trim()}catch{d="inactive"}}let f="N/A";if(a.health_check){let p=a.health_check.trim();if(/^https?:\/\//.test(p))try{let h=require("node-fetch"),g=await Promise.race([h(p),new Promise((w,_)=>setTimeout(()=>_(new Error("timeout")),1e4))]);f=g.ok?"healthy":`HTTP ${g.status}`}catch(h){f=`unhealthy: ${h.message.substring(0,50)}`}else try{f=(await bt(c,p,{timeout:1e4})).exitCode===0?"healthy":"unhealthy"}catch{f="unhealthy"}}r.push(`${i}: server=${l?"reachable":"unreachable"} service=${d} health=${f}`)}catch(c){r.push(`${i}: ERROR \u2014 ${c.message}`)}}return`Deployment Status:
554
554
  ${r.join(`
555
555
  `)}`}case"frontend_recon":{let o=process.cwd(),s=(e.type||"").toLowerCase(),r=[],i=async(E,v=120)=>{try{let N=ae.isAbsolute(E)?E:ae.join(o,E),oe=(await Ze.readFile(N,"utf8")).split(`
556
556
  `),ue=oe.slice(0,v).join(`
@@ -585,20 +585,20 @@ ${v}
585
585
  \u26A0 Use ONLY the frameworks listed above. Do NOT mix (e.g. no fetch() when HTMX is used for the same action).`)):r.push("(framework not detected \u2014 check package.json or script tags manually)"),r.push(`
586
586
  ---
587
587
  \u2705 Design recon complete. Now build consistently with the patterns above.`),r.join(`
588
- `)}case"sysadmin":{if(!e.action)return"ERROR: action is required";let o=!e.server||e.server==="local"||e.server==="localhost",s;if(!o)try{s=Ft(e.server)}catch(c){return`ERROR: ${c.message}`}let r=async(c,u=3e4)=>{if(o)try{let{stdout:l,stderr:d}=await Ye(c,{timeout:u});return{out:(l||d||"").trim(),exitCode:0}}catch(l){return{out:(l.stderr||l.message||"").toString().trim(),exitCode:l.code||1}}else{let{stdout:l,stderr:d,exitCode:f,error:p}=await bt(s,c,{timeout:u}),h=[l,d].filter(Boolean).join(`
588
+ `)}case"sysadmin":{if(!e.action)return"ERROR: action is required";let o=!e.server||e.server==="local"||e.server==="localhost",s;if(!o)try{s=Ut(e.server)}catch(c){return`ERROR: ${c.message}`}let r=async(c,u=3e4)=>{if(o)try{let{stdout:l,stderr:d}=await Ye(c,{timeout:u});return{out:(l||d||"").trim(),exitCode:0}}catch(l){return{out:(l.stderr||l.message||"").toString().trim(),exitCode:l.code||1}}else{let{stdout:l,stderr:d,exitCode:f,error:p}=await bt(s,c,{timeout:u}),h=[l,d].filter(Boolean).join(`
589
589
  `).trim();return{out:p&&f!==0&&!l.trim()?(p+`
590
590
  `+h).trim():h,exitCode:f}}};if(!(["audit","disk_usage","process_list","network_status","ssl_check","log_tail","find_large","journalctl"].includes(e.action)||e.action==="package"&&e.package_action==="list"||e.action==="user_manage"&&["list","info"].includes(e.user_action)||e.action==="firewall"&&e.firewall_action==="status"||e.action==="cron"&&e.cron_action==="list"||e.action==="service"&&["status","list_failed"].includes(e.service_action))&&!n.autoConfirm){let c=o?"local":e.server;if(!await Zt(`sysadmin [${e.action}] on ${c} \u2014 proceed?`))return"Cancelled."}switch(e.action){case"audit":{let c=["echo '=== OS / KERNEL ==='","cat /etc/os-release 2>/dev/null | grep -E '^(NAME|VERSION)=' || uname -a","echo '=== UPTIME / LOAD ==='","uptime","echo '=== MEMORY / SWAP ==='","free -h","echo '=== DISK ==='","df -h --output=target,size,used,avail,pcent 2>/dev/null || df -h","echo '=== TOP 10 PROCESSES (CPU) ==='","ps aux --sort=-%cpu | head -11","echo '=== FAILED SYSTEMD UNITS ==='","systemctl list-units --state=failed --no-legend 2>/dev/null || echo '(systemctl not available)'","echo '=== RECENT ERRORS (journalctl) ==='","journalctl -p err --no-pager -n 15 2>/dev/null || echo '(journalctl not available)'","echo '=== LISTENING PORTS ==='","ss -tlnp 2>/dev/null || netstat -tlnp 2>/dev/null || echo '(ss/netstat not available)'"].join(" && "),{out:u,exitCode:l}=await r(c,45e3);return u||`EXIT ${l}
591
591
  (no output)`}case"disk_usage":{let c=e.path||"/",u=Ae(c),l=`df -h ${u}; echo '--- Top subdirs ---'; du -d1 -x -h ${u} 2>/dev/null | sort -rh | head -20`,{out:d,exitCode:f}=await r(l,3e4);return f!==0?`EXIT ${f}
592
592
  ${d}`:d}case"process_list":{let c=e.sort_by==="mem"?"4":"3",u=(e.limit||20)+1,l=`ps aux --sort=-${e.sort_by==="mem"?"%mem":"%cpu"} 2>/dev/null | head -${u} || ps aux | awk 'NR==1{print; next} {print | "sort -k${c} -rn"}' | head -${u}`,{out:d,exitCode:f}=await r(l,15e3);return f!==0?`EXIT ${f}
593
593
  ${d}`:d}case"network_status":{let c="ss -tlnp 2>/dev/null || netstat -tlnp 2>/dev/null; echo '--- Active connections ---'; ss -tnp 2>/dev/null | head -30",{out:u,exitCode:l}=await r(c,15e3);return l!==0?`EXIT ${l}
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(jE))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}
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(BE))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(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}
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(zg))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}
601
- ${h}`:h}default:return`ERROR: Unknown user_action: ${e.user_action}`}}case"firewall":{if(!e.firewall_action)return"ERROR: firewall_action is required for action=firewall";let{out:c}=await r("which firewall-cmd 2>/dev/null && echo firewalld || (which ufw 2>/dev/null && echo ufw) || echo iptables",1e4),u=c.includes("firewalld")?"firewalld":c.includes("ufw")?"ufw":"iptables",l;switch(e.firewall_action){case"status":l=u==="firewalld"?"firewall-cmd --state && firewall-cmd --list-all":u==="ufw"?"ufw status verbose":"iptables -L -n --line-numbers | head -60";break;case"allow":if(!e.port)return'ERROR: port is required for firewall allow (e.g. "80/tcp")';if(!Ul(e.port))return"ERROR: port contains unsafe characters";l=u==="firewalld"?`firewall-cmd --permanent --add-port=${e.port} && firewall-cmd --reload`:u==="ufw"?`ufw allow ${Ae(e.port)}`:`iptables -A INPUT -p ${e.port.includes("/")?e.port.split("/")[1]:"tcp"} --dport ${e.port.split("/")[0]} -j ACCEPT`;break;case"deny":if(!e.port)return"ERROR: port is required for firewall deny";if(!Ul(e.port))return"ERROR: port contains unsafe characters";l=u==="firewalld"?`firewall-cmd --permanent --remove-port=${e.port} && firewall-cmd --reload`:u==="ufw"?`ufw deny ${Ae(e.port)}`:`iptables -A INPUT -p ${e.port.includes("/")?e.port.split("/")[1]:"tcp"} --dport ${e.port.split("/")[0]} -j DROP`;break;case"remove":if(!e.port)return"ERROR: port is required for firewall remove";if(!Ul(e.port))return"ERROR: port contains unsafe characters";l=u==="firewalld"?`firewall-cmd --permanent --remove-port=${e.port} && firewall-cmd --reload`:u==="ufw"?`ufw delete allow ${Ae(e.port)}`:`iptables -D INPUT -p ${e.port.includes("/")?e.port.split("/")[1]:"tcp"} --dport ${e.port.split("/")[0]} -j ACCEPT 2>/dev/null || true`;break;case"reload":l=u==="firewalld"?"firewall-cmd --reload":u==="ufw"?"ufw reload":'iptables-restore < /etc/iptables/rules.v4 2>/dev/null || echo "iptables: manual reload not available"';break;default:return`ERROR: Unknown firewall_action: ${e.firewall_action}`}let{out:d,exitCode:f}=await r(l,3e4);return f!==0?`EXIT ${f}
601
+ ${h}`:h}default:return`ERROR: Unknown user_action: ${e.user_action}`}}case"firewall":{if(!e.firewall_action)return"ERROR: firewall_action is required for action=firewall";let{out:c}=await r("which firewall-cmd 2>/dev/null && echo firewalld || (which ufw 2>/dev/null && echo ufw) || echo iptables",1e4),u=c.includes("firewalld")?"firewalld":c.includes("ufw")?"ufw":"iptables",l;switch(e.firewall_action){case"status":l=u==="firewalld"?"firewall-cmd --state && firewall-cmd --list-all":u==="ufw"?"ufw status verbose":"iptables -L -n --line-numbers | head -60";break;case"allow":if(!e.port)return'ERROR: port is required for firewall allow (e.g. "80/tcp")';if(!Gl(e.port))return"ERROR: port contains unsafe characters";l=u==="firewalld"?`firewall-cmd --permanent --add-port=${e.port} && firewall-cmd --reload`:u==="ufw"?`ufw allow ${Ae(e.port)}`:`iptables -A INPUT -p ${e.port.includes("/")?e.port.split("/")[1]:"tcp"} --dport ${e.port.split("/")[0]} -j ACCEPT`;break;case"deny":if(!e.port)return"ERROR: port is required for firewall deny";if(!Gl(e.port))return"ERROR: port contains unsafe characters";l=u==="firewalld"?`firewall-cmd --permanent --remove-port=${e.port} && firewall-cmd --reload`:u==="ufw"?`ufw deny ${Ae(e.port)}`:`iptables -A INPUT -p ${e.port.includes("/")?e.port.split("/")[1]:"tcp"} --dport ${e.port.split("/")[0]} -j DROP`;break;case"remove":if(!e.port)return"ERROR: port is required for firewall remove";if(!Gl(e.port))return"ERROR: port contains unsafe characters";l=u==="firewalld"?`firewall-cmd --permanent --remove-port=${e.port} && firewall-cmd --reload`:u==="ufw"?`ufw delete allow ${Ae(e.port)}`:`iptables -D INPUT -p ${e.port.includes("/")?e.port.split("/")[1]:"tcp"} --dport ${e.port.split("/")[0]} -j ACCEPT 2>/dev/null || true`;break;case"reload":l=u==="firewalld"?"firewall-cmd --reload":u==="ufw"?"ufw reload":'iptables-restore < /etc/iptables/rules.v4 2>/dev/null || echo "iptables: manual reload not available"';break;default:return`ERROR: Unknown firewall_action: ${e.firewall_action}`}let{out:d,exitCode:f}=await r(l,3e4);return f!==0?`EXIT ${f}
602
602
  ${d}`:d||`firewall ${e.firewall_action} OK`}case"cron":{if(!e.cron_action)return"ERROR: cron_action is required for action=cron";if(e.user){let u=rr(e.user);if(u)return u}let c=e.user?`-u ${Ae(e.user)}`:"";switch(e.cron_action){case"list":{let u=`crontab ${c} -l 2>/dev/null || echo '(no crontab for ${e.user||"current user"})'`,{out:l}=await r(u,1e4);return l||"(empty crontab)"}case"add":{if(!e.schedule)return"ERROR: schedule is required for cron add";if(!e.command)return"ERROR: command is required for cron add";let u=`${e.schedule} ${e.command}`,l=`(crontab ${c} -l 2>/dev/null; printf '%s
603
603
  ' ${Ae(u)}) | crontab ${c} - && echo "Cron entry added: ${u}"`,{out:d,exitCode:f}=await r(l,15e3);return f!==0?`EXIT ${f}
604
604
  ${d}`:d}case"remove":{if(!e.command)return"ERROR: command (substring to match) is required for cron remove";let u=e.command.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),l=`crontab ${c} -l 2>/dev/null | grep -v "${u}" | crontab ${c} - && echo "Matching cron entries removed"`,{out:d,exitCode:f}=await r(l,15e3);return f!==0?`EXIT ${f}
@@ -628,11 +628,11 @@ fi
628
628
  `.trim();let{out:u,exitCode:l}=await r(c,25e3),d=/notAfter=|Days until expiry:/i.test(u);return l!==0&&!d?`EXIT ${l}
629
629
  ${u}`:u||"(no cert info returned)"}case"log_tail":{if(!e.path)return"ERROR: path is required for log_tail";let u=`tail -n ${e.lines||100} ${Ae(e.path)} 2>&1`,{out:l,exitCode:d}=await r(u,15e3);return d!==0?`EXIT ${d}
630
630
  ${l}`:l||"(empty log)"}case"find_large":{let c=e.path||"/",u=e.limit||20,l=e.min_size||"100M",d=`find ${Ae(c)} -xdev -type f -size +${Ae(l)} 2>/dev/null | xargs du -sh 2>/dev/null | sort -rh | head -${u}`,{out:f,exitCode:p}=await r(d,6e4);return p!==0?`EXIT ${p}
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
- ${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(!DE(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}
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=zl(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
+ ${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(!UE(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 FE(t,e,n={}){let{emit:o}=gi(),{logToolExecution:s}=Tg(),r=Date.now(),i=n.silent?null:hE(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 pE(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:qE,executeTool:FE,resolvePath:ut,autoFixPath:Ji,autoFixEdit:Wg,enrichBashError:Ug,cancelPendingAskUser:AE,setAskUserHandler:OE,fileExists:Ot}});var zs=Q((EO,zg)=>{zg.exports=Gg()});var zl=Q((RO,Xg)=>{var{loadServerProfiles:ro,resolveProfile:TO,sshExec:BE}=Ks(),UE=/\.(?:png|jpe?g|gif|webp|bmp|svg|ico|pdf|mp4|webm|mov)(?:[?#].*)?$/i,WE=/\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,HE=/https?:\/\/[^\s)]+/gi;function YE(t){if(typeof t!="string")return[];let e=new Set,n=[];for(let o of t.match(HE)||[]){let s=o.replace(/[.,;!?]+$/g,"");e.has(s)||(e.add(s),n.push(s))}return n}function GE(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"||!WE.test(t))return null;let n=YE(t).filter(o=>!UE.test(o));if(n.length===0)return null;for(let o of n){let s=GE(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 zE(){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
- `)}function KE(t){let e=ro();return Object.values(e).some(n=>n.os&&n.os.startsWith(t))}function XE(){return Object.keys(ro())}function VE(){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(`
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}=yi(),s=await o(t,e,n);return s!==null?s:`ERROR: Unknown tool: ${t}`}}}async function HE(t,e,n={}){let{emit:o}=yi(),{logToolExecution:s}=Ag(),r=Date.now(),i=n.silent?null:wE(t,e);if(!i){let c=await Bg(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 yE(i);a.start();try{let c=await Bg(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}}Kg.exports={TOOL_DEFINITIONS:WE,executeTool:HE,resolvePath:dt,autoFixPath:Zi,autoFixEdit:Gg,enrichBashError:Yg,cancelPendingAskUser:PE,setAskUserHandler:LE,fileExists:Ot}});var zs=Q((NO,Vg)=>{Vg.exports=Xg()});var Jl=Q((PO,Zg)=>{var{loadServerProfiles:ro,resolveProfile:MO,sshExec:YE}=Ks(),GE=/\.(?:png|jpe?g|gif|webp|bmp|svg|ico|pdf|mp4|webm|mov)(?:[?#].*)?$/i,zE=/\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,KE=/https?:\/\/[^\s)]+/gi;function XE(t){if(typeof t!="string")return[];let e=new Set,n=[];for(let o of t.match(KE)||[]){let s=o.replace(/[.,;!?]+$/g,"");e.has(s)||(e.add(s),n.push(s))}return n}function VE(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 Jg(t,e=ro()){if(typeof t!="string"||!zE.test(t))return null;let n=XE(t).filter(o=>!GE.test(o));if(n.length===0)return null;for(let o of n){let s=VE(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 Vl={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 JE(){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&&Vl[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 Vl[s])n.push(`- ${i}`)}}return n.join(`
635
+ `)}function ZE(t){let e=ro();return Object.values(e).some(n=>n.os&&n.os.startsWith(t))}function QE(){return Object.keys(ro())}function eT(){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)
638
638
 
@@ -651,7 +651,7 @@ ${u}
651
651
  - \u274C Do NOT \`read_file\` on paths like \`logs/\` \u2014 these files do not exist locally
652
652
  - \u274C Do NOT \`list_directory\` on server paths \u2014 the local project is the source, not the running instance
653
653
 
654
- **When in doubt:** If a path contains \`logs/\`, \`/var/log/\`, or \`/home/<user>/\` \u2014 it is on the server. SSH there.${JE(s)}`}function JE(t){return Object.values(t).some(n=>n.host==="94.130.37.43")?`
654
+ **When in doubt:** If a path contains \`logs/\`, \`/var/log/\`, or \`/home/<user>/\` \u2014 it is on the server. SSH there.${tT(s)}`}function tT(t){return Object.values(t).some(n=>n.host==="94.130.37.43")?`
655
655
 
656
656
  ## Server Debugging Rules
657
657
 
@@ -662,36 +662,36 @@ ${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 ZE(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 BE(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:zE,getDeploymentContextBlock:VE,hasServerOS:KE,getProfileNames:XE,probeUrlServer:ZE,detectRuntimeDebugTarget:Kg,OS_HINTS:Gl}});var Qg=Q((CO,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:QE}=zl(),{refreshIndex:eT,getFileIndex:tT,buildContentIndex:nT,summarizeModuleHubs:sT}=cn(),oT=new Set(["node_modules",".git",".svn","dist","build","coverage",".nyc_output","__pycache__",".DS_Store",".next",".nuxt",".turbo",".cache","vendor","tmp","temp"]),rT=[{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 iT(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 aT(t){let e=new Set(t),n=new Set;for(let o of rT)(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 cT(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 lT(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 uT(t){return!t||!t.workspaces?[]:Array.isArray(t.workspaces)?t.workspaces:Array.isArray(t.workspaces.packages)?t.workspaces.packages:[]}async function dT(t){try{await eT(t);let e=tT();if(!e||e.length===0)return"";let n=aT(e),o=iT(e),s=cT(e),r=e.filter(d=>/^tests?\//.test(d)||/\.test\./.test(d)||/\.spec\./.test(d)).length,i=lT(e),a=[];try{let d=Ge.join(t,"package.json");if(Qi.existsSync(d)){let f=JSON.parse(Qi.readFileSync(d,"utf-8"));a=uT(f)}}catch{}let c="",u="";try{let d=await nT(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 sT(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
- `)}catch{return""}}function fT(t){try{return Qi.readFileSync(t,"utf-8").split(`
668
- `).map(n=>n.trim()).filter(n=>n&&!n.startsWith("#")&&!n.startsWith("!")).map(n=>n.replace(/\/$/,""))}catch{return[]}}function pT(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 hT(t,{maxDepth:e=3,maxFiles:n=200,giPatterns:o=[]}={}){let s=Ge.join(t,".gitignore"),r=[...o,...fT(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=>!(oT.has(h.name)||h.name.startsWith(".")&&h.name!==".env.example"||pT(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,Vg=3e4,ao={result:null,expiry:0,cwd:null};async function pn(t){try{return await t()}catch{return null}}async function mT(){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 gT(){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 yT(t){let e="fileContext",n=Kl.get(e),o=!1;if(n&&await mT()&&(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(`
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 nT(t){let e=ro(),n=Jg(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 YE(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}}Zg.exports={getServerContext:JE,getDeploymentContextBlock:eT,hasServerOS:ZE,getProfileNames:QE,probeUrlServer:nT,detectRuntimeDebugTarget:Jg,OS_HINTS:Vl}});var ny=Q((LO,ty)=>{var $t=require("fs").promises,ea=require("fs"),Ge=require("path"),Qi=require("util").promisify(require("child_process").exec),{C:io}=it(),{getMergeConflicts:ey}=fi(),{getServerContext:sT}=Jl(),{refreshIndex:oT,getFileIndex:rT,buildContentIndex:iT,summarizeModuleHubs:aT}=ln(),cT=new Set(["node_modules",".git",".svn","dist","build","coverage",".nyc_output","__pycache__",".DS_Store",".next",".nuxt",".turbo",".cache","vendor","tmp","temp"]),lT=[{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 uT(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 dT(t){let e=new Set(t),n=new Set;for(let o of lT)(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 fT(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 pT(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 hT(t){return!t||!t.workspaces?[]:Array.isArray(t.workspaces)?t.workspaces:Array.isArray(t.workspaces.packages)?t.workspaces.packages:[]}async function mT(t){try{await oT(t);let e=rT();if(!e||e.length===0)return"";let n=dT(e),o=uT(e),s=fT(e),r=e.filter(d=>/^tests?\//.test(d)||/\.test\./.test(d)||/\.spec\./.test(d)).length,i=pT(e),a=[];try{let d=Ge.join(t,"package.json");if(ea.existsSync(d)){let f=JSON.parse(ea.readFileSync(d,"utf-8"));a=hT(f)}}catch{}let c="",u="";try{let d=await iT(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 aT(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
+ `)}catch{return""}}function gT(t){try{return ea.readFileSync(t,"utf-8").split(`
668
+ `).map(n=>n.trim()).filter(n=>n&&!n.startsWith("#")&&!n.startsWith("!")).map(n=>n.replace(/\/$/,""))}catch{return[]}}function yT(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 wT(t,{maxDepth:e=3,maxFiles:n=200,giPatterns:o=[]}={}){let s=Ge.join(t,".gitignore"),r=[...o,...gT(s)],i=0,a=[Ge.basename(t)+"/"];function c(u,l,d){if(d>e||i>=n)return;let f;try{f=ea.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=>!(cT.has(h.name)||h.name.startsWith(".")&&h.name!==".env.example"||yT(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 Zl=new Map,co=new Map,ta=null,Qg=3e4,ao={result:null,expiry:0,cwd:null};async function hn(t){try{return await t()}catch{return null}}async function bT(){if(!ta||Date.now()>ta)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 $T(){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 _T(t){let e="fileContext",n=Zl.get(e),o=!1;if(n&&await bT()&&(o=!0),!o){let u=[],l=Ge.join(t,"package.json");if(await hn(()=>$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 hn(()=>$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
- `)}`)}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:
673
- ${v.trim()}`)}let w=Ge.join(t,"CLAUDE.md");if(await pn(()=>$t.access(w).then(()=>!0).catch(()=>!1))){let v=await $t.readFile(w,"utf-8");v.trim()&&u.push(`PROJECT INSTRUCTIONS (CLAUDE.md):
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
- ${v.trim()}`)}let E=await dT(t);E&&u.push(E),n=u.join(`
672
+ `)}`)}let h=Ge.join(t,".gitignore");if(await hn(()=>$t.access(h).then(()=>!0).catch(()=>!1))){let v=await $t.readFile(h,"utf-8");u.push(`GITIGNORE:
673
+ ${v.trim()}`)}let w=Ge.join(t,"CLAUDE.md");if(await hn(()=>$t.access(w).then(()=>!0).catch(()=>!1))){let v=await $t.readFile(w,"utf-8");v.trim()&&u.push(`PROJECT INSTRUCTIONS (CLAUDE.md):
674
+ ${v.trim()}`)}let S=Ge.join(t,".nex","CLAUDE.md");if(await hn(()=>$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
+ ${v.trim()}`)}let E=await mT(t);E&&u.push(E),n=u.join(`
676
676
 
677
- `),Kl.set(e,n),ea=Date.now()+Vg,await gT()}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:
677
+ `),Zl.set(e,n),ta=Date.now()+Qg,await $T()}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([hn(async()=>{let{stdout:u}=await Qi("git branch --show-current",{cwd:t,timeout:5e3});return u.trim()}),hn(async()=>{let{stdout:u}=await Qi("git status --short",{cwd:t,timeout:5e3});return u.trim()}),hn(async()=>{let{stdout:u}=await Qi("git log --oneline -5",{cwd:t,timeout:5e3});return u.trim()}),ey()]),ao={result:{branch:r,status:i,log:a,conflicts:c},expiry:Date.now()+Qg,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
- ${u}`)}try{let u=QE();u&&s.push(u)}catch{}return s.join(`
681
+ ${u}`)}try{let u=sT();u&&s.push(u)}catch{}return s.join(`
682
682
 
683
- `)}async function wT(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:yT,printContext:wT,generateFileTree:hT,_clearContextCache:()=>{Kl.clear(),co.clear(),ea=null,ao={result:null,expiry:0,cwd:null}}}});var na=Q((AO,ny)=>{var en=require("fs"),ta=require("path"),{atomicWrite:bT}=Jn();function lr(){return ta.join(process.cwd(),".nex","sessions")}function Xl(){let t=lr();en.existsSync(t)||en.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 bT(o,JSON.stringify(s,null,2)),{path:o,name:t}}function ey(t){let e=Vl(t);if(!en.existsSync(e))return null;try{return JSON.parse(en.readFileSync(e,"utf-8"))}catch{return null}}function ty(){Xl();let t=lr(),e=en.readdirSync(t).filter(o=>o.endsWith(".json")),n=[];for(let o of e)try{let s=JSON.parse(en.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 $T(t){let e=Vl(t);return en.existsSync(e)?(en.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 xT(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 kT(){hs&&(clearTimeout(hs),hs=null),En&&En.length>0&&(Jl("_autosave",En,cr),En=null,cr=null)}function vT(){Xl();let t=lr(),e=en.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=en.statSync(i);new Date(a.mtime)<o&&(en.unlinkSync(i),s++)}catch{}}return s}ny.exports={saveSession:Jl,loadSession:ey,listSessions:ty,deleteSession:$T,getLastSession:_T,autoSave:xT,flushAutoSave:kT,clearOldSessions:vT,_getSessionsDir:lr}});var sa=Q((OO,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 ST(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=ST(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(`
683
+ `)}async function xT(t){let e=Ge.join(t,"package.json"),n="";if(await hn(()=>$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([hn(async()=>{let{stdout:i}=await Qi("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),ey()]);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()}ty.exports={gatherProjectContext:_T,printContext:xT,generateFileTree:wT,_clearContextCache:()=>{Zl.clear(),co.clear(),ta=null,ao={result:null,expiry:0,cwd:null}}}});var sa=Q((IO,ry)=>{var en=require("fs"),na=require("path"),{atomicWrite:kT}=Zn();function lr(){return na.join(process.cwd(),".nex","sessions")}function Ql(){let t=lr();en.existsSync(t)||en.mkdirSync(t,{recursive:!0,mode:448})}function eu(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return na.join(lr(),`${e}.json`)}function tu(t,e,n={}){Ql();let o=eu(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 kT(o,JSON.stringify(s,null,2)),{path:o,name:t}}function sy(t){let e=eu(t);if(!en.existsSync(e))return null;try{return JSON.parse(en.readFileSync(e,"utf-8"))}catch{return null}}function oy(){Ql();let t=lr(),e=en.readdirSync(t).filter(o=>o.endsWith(".json")),n=[];for(let o of e)try{let s=JSON.parse(en.readFileSync(na.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 vT(t){let e=eu(t);return en.existsSync(e)?(en.unlinkSync(e),!0):!1}function ST(){let t=oy();return t.length===0?null:sy(t[0].name)}var Dn=null,En=null,cr=null;function ET(t,e={}){t.length!==0&&(Dn&&clearTimeout(Dn),En=t,cr=e||{},Dn=setTimeout(()=>{En&&En.length>0&&tu("_autosave",En,cr),Dn=null,En=null,cr=null},5e3),Dn.unref?.())}function TT(){Dn&&(clearTimeout(Dn),Dn=null),En&&En.length>0&&(tu("_autosave",En,cr),En=null,cr=null)}function RT(){Ql();let t=lr(),e=en.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=na.join(t,r);try{let a=en.statSync(i);new Date(a.mtime)<o&&(en.unlinkSync(i),s++)}catch{}}return s}ry.exports={saveSession:tu,loadSession:sy,listSessions:oy,deleteSession:vT,getLastSession:ST,autoSave:ET,flushAutoSave:TT,clearOldSessions:RT,_getSessionsDir:lr}});var oa=Q((jO,py)=>{"use strict";var ur=require("fs"),iy=require("path");function ay(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 CT(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 cy(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 ly(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 uy(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 dy(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 fy(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=ay(t),s=cy(t),r=o.length,i=CT(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=ly(t),h=uy(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 _=dy(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 ET(t){try{let{loadSession:e}=na(),n=e(t);return n?ly(n.messages||[]):null}catch{return null}}function TT(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 AT(t){try{let{loadSession:e}=sa(),n=e(t);return n?fy(n.messages||[]):null}catch{return null}}function OT(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 RT(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:ET,formatScore:TT,appendScoreHistory:RT,_extractToolCalls:oy,_extractToolResults:ry,_getLastAssistantText:iy,_getLastNAssistantTexts:ay,_countDuplicateToolCalls:cy}});var ms=Q((NO,my)=>{"use strict";var CT=require("os"),Zl=require("path"),Dn=require("fs"),dr=Zl.join(CT.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 AT(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 OT(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 NT(t){return fr().phaseBudgets?.[t]||py[t]||20}function MT(){return process.env.NEX_PHASE_ROUTING==="0"||process.env.NEX_FORCE_MODEL?!1:hy()!==null}function PT(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 NT(t,e={}){try{let n=iy.join(process.cwd(),".nex");ur.existsSync(n)||ur.mkdirSync(n,{recursive:!0});let o=iy.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{}}py.exports={scoreMessages:fy,scoreSession:AT,formatScore:OT,appendScoreHistory:NT,_extractToolCalls:ay,_extractToolResults:cy,_getLastAssistantText:ly,_getLastNAssistantTexts:uy,_countDuplicateToolCalls:dy}});var ms=Q((DO,wy)=>{"use strict";var MT=require("os"),nu=require("path"),qn=require("fs"),dr=nu.join(MT.homedir(),".nex-code","model-routing.json"),ra={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}},hy=["agentic","frontend","sysadmin","data","coding"];function PT(t){if(!t||t.length<8)return null;for(let e of hy){let n=ra[e];if(!n.pattern||n.pattern.test(t))return n}return ra.coding}function fr(){try{if(qn.existsSync(dr))return JSON.parse(qn.readFileSync(dr,"utf-8"))}catch{}return{}}function my(t){if(process.env.NEX_FORCE_MODEL)return process.env.NEX_FORCE_MODEL;let e=ra[t];return e?.envVar&&process.env[e.envVar]?process.env[e.envVar]:fr()[t]||null}var gy={explore:10,plan:10,implement:35,verify:8},su={explore:"devstral-small-2:24b",plan:"qwen3-coder:480b",implement:null,verify:"devstral-small-2:24b"};function yy(){let t=fr();if(t.phases&&Object.keys(t.phases).length>0)return t.phases;try{let{getActiveProviderName:e}=lt();if(e()==="ollama")return su}catch{}return process.env.NEX_PHASE_ROUTING==="1"?su:null}function LT(t,e){if(process.env.NEX_FORCE_MODEL)return process.env.NEX_FORCE_MODEL;let n=yy();return n?.[t]?n[t]:e?my(e):null}function IT(t){return fr().phaseBudgets?.[t]||gy[t]||20}function jT(){return process.env.NEX_PHASE_ROUTING==="0"||process.env.NEX_FORCE_MODEL?!1:yy()!==null}function DT(t){let e=nu.dirname(dr);qn.existsSync(e)||qn.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),qn.writeFileSync(dr,JSON.stringify(o,null,2));try{let s=nu.join(e,".env"),r="";qn.existsSync(s)&&(r=qn.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)),qn.writeFileSync(s,i.filter(c=>c.trim()!=="").join(`
690
690
  `)+`
691
- `)}catch{}}my.exports={CATEGORIES:oa,DETECTION_ORDER:dy,detectCategory:AT,getModelForCategory:fy,getModelForPhase:OT,getPhaseBudget:NT,isPhaseRoutingEnabled:MT,DEFAULT_PHASE_BUDGETS:py,BUILTIN_PHASE_DEFAULTS:Ql,saveRoutingConfig:PT,loadRoutingConfig:fr,ROUTING_CONFIG_PATH:dr}});var by=Q((MO,wy)=>{"use strict";var gs=require("fs"),pr=require("path"),LT=require("os"),{detectCategory:IT}=ms(),lo=pr.join(LT.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(`
691
+ `)}catch{}}wy.exports={CATEGORIES:ra,DETECTION_ORDER:hy,detectCategory:PT,getModelForCategory:my,getModelForPhase:LT,getPhaseBudget:IT,isPhaseRoutingEnabled:jT,DEFAULT_PHASE_BUDGETS:gy,BUILTIN_PHASE_DEFAULTS:su,saveRoutingConfig:DT,loadRoutingConfig:fr,ROUTING_CONFIG_PATH:dr}});var xy=Q((qO,_y)=>{"use strict";var gs=require("fs"),pr=require("path"),qT=require("os"),{detectCategory:FT}=ms(),lo=pr.join(qT.homedir(),".nex-code","examples"),ou=pr.join(__dirname,"..","examples");function by(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 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 jT(t){if(process.env.NEX_FEW_SHOT==="0"||!t||t.length<8)return null;let e=IT(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 DT(){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 qT(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 $y(t){let e=`${t}.md`,n=pr.join(lo,e);if(gs.existsSync(n)){let s=by(n);if(s)return s}let o=pr.join(ou,e);return gs.existsSync(o)?by(o):null}function BT(t){if(process.env.NEX_FEW_SHOT==="0"||!t||t.length<8)return null;let e=FT(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:$y(e.id)}function UT(){let t=new Set;for(let e of[lo,ou])try{for(let n of gs.readdirSync(e))n.endsWith(".md")&&t.add(n.replace(".md",""))}catch{}return[...t].sort()}function WT(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")}wy.exports={getFewShotForInput:jT,loadExampleForCategory:yy,listAvailableExamples:DT,savePrivateExample:qT,PRIVATE_EXAMPLES_DIR:lo,BUNDLED_EXAMPLES_DIR:eu}});var Sy=Q((LO,vy)=>{var Nt=require("fs"),uo=require("path"),{C:PO}=rt(),{atomicWrite:FT,withFileLockSync:BT}=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(Nt.existsSync(t))try{let e=JSON.parse(Nt.readFileSync(t,"utf-8"));e.permissions&&(fo={...ra,...e.permissions})}catch{}}function UT(){let t=uo.join(process.cwd(),".nex"),e=uo.join(t,"config.json");Nt.existsSync(t)||Nt.mkdirSync(t,{recursive:!0}),BT(e,()=>{let n={};if(Nt.existsSync(e))try{n=JSON.parse(Nt.readFileSync(e,"utf-8"))}catch{n={}}n.permissions=fo,FT(e,JSON.stringify(n,null,2))})}function _y(t){return fo[t]||"ask"}function WT(t,e){return["allow","ask","deny"].includes(e)?(fo[t]=e,!0):!1}function HT(t){return _y(t)}function YT(){return Object.entries(fo).map(([t,e])=>({tool:t,mode:e}))}function GT(){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 Nt.existsSync(t)&&JSON.parse(Nt.readFileSync(t,"utf-8")).teamPermissions||null}catch{return null}}function zT(t){let e=uo.join(process.cwd(),".nex"),n=uo.join(e,"config.json");Nt.existsSync(e)||Nt.mkdirSync(e,{recursive:!0});let o={};try{Nt.existsSync(n)&&(o=JSON.parse(Nt.readFileSync(n,"utf-8")))}catch{o={}}o.teamPermissions=t,Nt.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 KT(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 XT(){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:WT,checkPermission:HT,listPermissions:YT,loadPermissions:$y,savePermissions:UT,resetPermissions:GT,DEFAULT_PERMISSIONS:ra,PERMISSION_PRESETS:hr,loadPresetConfig:xy,savePresetConfig:zT,getEffectivePreset:ky,isToolAllowed:KT,listPresets:XT}});var ca=Q((jO,Ay)=>{var ws=require("fs"),ia=require("path"),IO=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 VT(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 JT(){return Oe}function ZT(t){nu=t}function QT(){return nu}function eR(){return!Oe||Oe.status!=="draft"?!1:(Oe.status="approved",Oe.updatedAt=new Date().toISOString(),!0)}function tR(){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 nR(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")}_y.exports={getFewShotForInput:BT,loadExampleForCategory:$y,listAvailableExamples:UT,savePrivateExample:WT,PRIVATE_EXAMPLES_DIR:lo,BUNDLED_EXAMPLES_DIR:ou}});var Ry=Q((BO,Ty)=>{var Nt=require("fs"),uo=require("path"),{C:FO}=it(),{atomicWrite:HT,withFileLockSync:YT}=Zn(),ia={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={...ia};function ky(){let t=uo.join(process.cwd(),".nex","config.json");if(Nt.existsSync(t))try{let e=JSON.parse(Nt.readFileSync(t,"utf-8"));e.permissions&&(fo={...ia,...e.permissions})}catch{}}function GT(){let t=uo.join(process.cwd(),".nex"),e=uo.join(t,"config.json");Nt.existsSync(t)||Nt.mkdirSync(t,{recursive:!0}),YT(e,()=>{let n={};if(Nt.existsSync(e))try{n=JSON.parse(Nt.readFileSync(e,"utf-8"))}catch{n={}}n.permissions=fo,HT(e,JSON.stringify(n,null,2))})}function vy(t){return fo[t]||"ask"}function zT(t,e){return["allow","ask","deny"].includes(e)?(fo[t]=e,!0):!1}function KT(t){return vy(t)}function XT(){return Object.entries(fo).map(([t,e])=>({tool:t,mode:e}))}function VT(){fo={...ia}}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 Sy(){let t=uo.join(process.cwd(),".nex","config.json");try{return Nt.existsSync(t)&&JSON.parse(Nt.readFileSync(t,"utf-8")).teamPermissions||null}catch{return null}}function JT(t){let e=uo.join(process.cwd(),".nex"),n=uo.join(e,"config.json");Nt.existsSync(e)||Nt.mkdirSync(e,{recursive:!0});let o={};try{Nt.existsSync(n)&&(o=JSON.parse(Nt.readFileSync(n,"utf-8")))}catch{o={}}o.teamPermissions=t,Nt.writeFileSync(n,JSON.stringify(o,null,2),"utf-8")}function Ey(){let t=Sy();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=Ey();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 QT(){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}))}ky();Ty.exports={getPermission:vy,setPermission:zT,checkPermission:KT,listPermissions:XT,loadPermissions:ky,savePermissions:GT,resetPermissions:VT,DEFAULT_PERMISSIONS:ia,PERMISSION_PRESETS:hr,loadPresetConfig:Sy,savePresetConfig:JT,getEffectivePreset:Ey,isToolAllowed:ZT,listPresets:QT}});var la=Q((WO,My)=>{var ws=require("fs"),aa=require("path"),UO=require("readline"),{C:Le}=it(),Oe=null,iu=!1,au=null,Cy=new Set(["read_file","list_directory","search_files","glob","grep","web_search","web_fetch","git_status","git_diff","git_log","git_show"]);function ca(){return aa.join(process.cwd(),".nex","plans")}function Ay(){let t=ca();ws.existsSync(t)||ws.mkdirSync(t,{recursive:!0})}function eR(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 tR(){return Oe}function nR(t){iu=t}function sR(){return iu}function oR(){return!Oe||Oe.status!=="draft"?!1:(Oe.status="approved",Oe.updatedAt=new Date().toISOString(),!0)}function rR(){return!Oe||Oe.status!=="approved"?!1:(Oe.status="executing",!0)}function ru(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 iR(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 sR(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 oR(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 rR(){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 iR(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 aR(t){su=t}function cR(){return su}function lR(){Oe=null,nu=!1,su=null,pR()}function uR(){return`
705
+ `)}function aR(t){if(t||(t=Oe),!t)return null;Ay();let e=aa.join(ca(),`${t.name}.json`);return ws.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function cR(t){let e=aa.join(ca(),`${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 lR(){Ay();let t=ca(),e=ws.readdirSync(t).filter(o=>o.endsWith(".json")),n=[];for(let o of e)try{let s=JSON.parse(ws.readFileSync(aa.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 uR(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 dR(t){au=t}function fR(){return au}function pR(){Oe=null,iu=!1,au=null,yR()}function hR(){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: ${[...Ey].join(", ")}
709
+ You may ONLY use these tools: ${[...Cy].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,16 +758,16 @@ 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 dR(){!Oe||Oe.status!=="executing"||(ys>0&&tu(ys-1,"done"),ys<Oe.steps.length&&(tu(ys,"in_progress"),ys++))}function fR(){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 pR(){ys=0}var Ry=["interactive","semi-auto","autonomous"],Cy="interactive";function hR(t){return Ry.includes(t)?(Cy=t,!0):!1}function mR(){return Cy}Ay.exports={createPlan:VT,getActivePlan:JT,setPlanMode:ZT,isPlanMode:QT,approvePlan:eR,startExecution:tR,updateStep:tu,formatPlan:nR,savePlan:sR,loadPlan:oR,listPlans:rR,clearPlan:lR,getPlanModePrompt:uR,setPlanContent:aR,getPlanContent:cR,extractStepsFromText:iR,advancePlanStep:dR,getPlanStepInfo:fR,PLAN_MODE_ALLOWED_TOOLS:Ey,setAutonomyLevel:hR,getAutonomyLevel:mR,AUTONOMY_LEVELS:Ry}});var By=Q((DO,Fy)=>{var{C:k}=rt();function Oy(){return Math.max(10,(process.stdout.columns||80)-2)}function gR(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} ${Mt(r.substring(7))}${k.reset}`);continue}if(r.startsWith("##### ")){n.push(`${k.bold}${k.cyan} ${Mt(r.substring(6))}${k.reset}`);continue}if(r.startsWith("#### ")){n.push(`${k.bold}${k.cyan} ${Mt(r.substring(5))}${k.reset}`);continue}if(r.startsWith("### ")){n.push(`${k.bold}${k.cyan} ${Mt(r.substring(4))}${k.reset}`);continue}if(r.startsWith("## ")){n.push(`${k.bold}${k.cyan} ${Mt(r.substring(3))}${k.reset}`);continue}if(r.startsWith("# ")){n.push(`${k.bold}${k.cyan}${Mt(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 Mt(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)+`
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 mR(){!Oe||Oe.status!=="executing"||(ys>0&&ru(ys-1,"done"),ys<Oe.steps.length&&(ru(ys,"in_progress"),ys++))}function gR(){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 yR(){ys=0}var Oy=["interactive","semi-auto","autonomous"],Ny="interactive";function wR(t){return Oy.includes(t)?(Ny=t,!0):!1}function bR(){return Ny}My.exports={createPlan:eR,getActivePlan:tR,setPlanMode:nR,isPlanMode:sR,approvePlan:oR,startExecution:rR,updateStep:ru,formatPlan:iR,savePlan:aR,loadPlan:cR,listPlans:lR,clearPlan:pR,getPlanModePrompt:hR,setPlanContent:dR,getPlanContent:fR,extractStepsFromText:uR,advancePlanStep:mR,getPlanStepInfo:gR,PLAN_MODE_ALLOWED_TOOLS:Cy,setAutonomyLevel:wR,getAutonomyLevel:bR,AUTONOMY_LEVELS:Oy}});var Hy=Q((HO,Wy)=>{var{C:k}=it();function Py(){return Math.max(10,(process.stdout.columns||80)-2)}function $R(t){if(!t)return"";let e=t.split(`
762
+ `),n=[],o=!1,s="";for(let r of e){let i=Py();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(` ${lu(r,s)}`);continue}if(r.startsWith("###### ")){n.push(`${k.bold}${k.cyan} ${Mt(r.substring(7))}${k.reset}`);continue}if(r.startsWith("##### ")){n.push(`${k.bold}${k.cyan} ${Mt(r.substring(6))}${k.reset}`);continue}if(r.startsWith("#### ")){n.push(`${k.bold}${k.cyan} ${Mt(r.substring(5))}${k.reset}`);continue}if(r.startsWith("### ")){n.push(`${k.bold}${k.cyan} ${Mt(r.substring(4))}${k.reset}`);continue}if(r.startsWith("## ")){n.push(`${k.bold}${k.cyan} ${Mt(r.substring(3))}${k.reset}`);continue}if(r.startsWith("# ")){n.push(`${k.bold}${k.cyan}${Mt(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 Mt(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 lu(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?Ly(t):e==="bash"||e==="sh"||e==="shell"||e==="zsh"?Iy(t):e==="json"||e==="jsonc"?jy(t):e==="python"||e==="py"?Dy(t):e==="go"||e==="golang"?qy(t):e==="rust"||e==="rs"?Fy(t):e==="css"||e==="scss"||e==="less"?By(t):e==="html"||e==="xml"||e==="svg"||e==="htm"?Uy(t):t:""}function Ly(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 Iy(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 jy(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 Dy(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 qy(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 Fy(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 By(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 Uy(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
- `+n,a=i,s=n.length+1),i++}return o+=t.slice(a),o}function yR(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
- `)}function wR(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?`${Xt().T.cyan}\u25CF${Xt().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(`
765
+ `+n,a=i,s=n.length+1),i++}return o+=t.slice(a),o}function _R(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
+ `)}function xR(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 cu=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?`${Xt().T.cyan}\u25CF${Xt().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=Oy();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=Py();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
- `)}return}if(this.inCodeBlock){this._safeWrite(` ${ru(e,this.codeBlockLang)}
770
+ `)}return}if(this.inCodeBlock){this._safeWrite(` ${lu(e,this.codeBlockLang)}
771
771
  `);return}if(e.startsWith("###### ")){this._safeWrite(`${k.bold}${k.cyan} ${Mt(e.substring(7))}${k.reset}
772
772
  `);return}if(e.startsWith("##### ")){this._safeWrite(`${k.bold}${k.cyan} ${Mt(e.substring(6))}${k.reset}
773
773
  `);return}if(e.startsWith("#### ")){this._safeWrite(`${k.bold}${k.cyan} ${Mt(e.substring(5))}${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
- `)}};Fy.exports={renderMarkdown:gR,renderInline:bs,stripHeadingMarkers:Mt,highlightCode:ru,highlightJS:Ny,highlightBash:My,highlightJSON:Py,highlightPython:Ly,highlightGo:Iy,highlightRust:jy,highlightCSS:Dy,highlightHTML:qy,renderTable:yR,renderProgress:wR,wrapAnsi:$s,StreamRenderer:ou}});var Gy=Q((qO,Yy)=>{var{execSync:bR}=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 $R(){return iu.join(process.cwd(),".nex","config.json")}function Wy(){let t=$R();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:bR(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 xR(t){return la(t).length>0}function kR(){let t=[];for(let e of au){let n=la(e);n.length>0&&t.push({event:e,commands:n})}return t}function vR(){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:xR,listHooks:kR,initHooksDir:vR}});var d0=Q((WO,u0)=>{"use strict";var{callWithRetry:Xy,runSubAgent:zy,clearAllLocks:SR}=Sl(),{parseModelSpec:Vy,getActiveProviderName:FO,getActiveModelId:BO}=ct(),{detectCategory:ER,getModelForCategory:Ky}=ms(),{MultiProgress:TR,C:ge}=rt(),{getModelBriefing:UO}=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.
780
+ `)}};Wy.exports={renderMarkdown:$R,renderInline:bs,stripHeadingMarkers:Mt,highlightCode:lu,highlightJS:Ly,highlightBash:Iy,highlightJSON:jy,highlightPython:Dy,highlightGo:qy,highlightRust:Fy,highlightCSS:By,highlightHTML:Uy,renderTable:_R,renderProgress:xR,wrapAnsi:$s,StreamRenderer:cu}});var Xy=Q((YO,Ky)=>{var{execSync:kR}=require("child_process"),uu=require("path"),mr=require("fs"),du=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function Yy(){return uu.join(process.cwd(),".nex","hooks")}function vR(){return uu.join(process.cwd(),".nex","config.json")}function Gy(){let t=vR();if(!mr.existsSync(t))return{};try{return JSON.parse(mr.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function ua(t){if(!du.includes(t))return[];let e=[],n=Yy(),o=uu.join(n,t);mr.existsSync(o)&&e.push(o);let s=Gy();if(s[t]){let r=Array.isArray(s[t])?s[t]:[s[t]];e.push(...r)}return e}function zy(t,e={},n=3e4){try{return{success:!0,exitCode:0,output:kR(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 SR(t,e={}){let n=ua(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=zy(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 ER(t){return ua(t).length>0}function TR(){let t=[];for(let e of du){let n=ua(e);n.length>0&&t.push({event:e,commands:n})}return t}function RR(){let t=Yy();return mr.existsSync(t)||mr.mkdirSync(t,{recursive:!0}),t}Ky.exports={HOOK_EVENTS:du,loadHookConfig:Gy,getHooksForEvent:ua,executeHook:zy,runHooks:SR,hasHooks:ER,listHooks:TR,initHooksDir:RR}});var h0=Q((XO,p0)=>{"use strict";var{callWithRetry:Zy,runSubAgent:Vy,clearAllLocks:CR}=Cl(),{parseModelSpec:Qy,getActiveProviderName:GO,getActiveModelId:zO}=lt(),{detectCategory:AR,getModelForCategory:Jy}=ms(),{MultiProgress:OR,C:ge}=it(),{getModelBriefing:KO}=Ii(),e0=parseInt(process.env.NEX_MAX_PARALLEL||"4",10),da=parseInt(process.env.NEX_MAX_SUBTASKS||"8",10),t0="devstral-2:123b",n0="kimi-k2.5",s0=`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}`,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.
795
+ {prompt}`,o0=`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:
@@ -808,16 +808,16 @@ ORIGINAL REQUEST:
808
808
  {prompt}
809
809
 
810
810
  SUB-AGENT RESULTS:
811
- {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 RR(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:
812
- ${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(`${Xt().T.yellow} \u26A0 Orchestrator: total estimated calls ${p} > ${h} \u2014 consider raising maxSubTasks${Xt().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((f,p)=>{let h=f.status==="done"?"SUCCESS":f.status==="truncated"?"PARTIAL":"FAILED";return`--- Agent ${p+1} [${h}] ---
811
+ {results}`;async function r0(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 i0(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 NR(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 fu(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:
812
+ ${e.slice(0,200)}`)}async function a0(t,e,n={}){let o=n.maxSubTasks||da,r=[{role:"system",content:s0.replace("{maxSubTasks}",String(o)).replace("{prompt}",t)},{role:"user",content:t}],i={};if(e){let g=Qy(e);g.provider&&(i.provider=g.provider),g.model&&(i.model=g.model)}let c=(await Zy(r,[],i)).content||"",u=fu(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=da*l;if(p>h){let{debugLog:g}=yc();g(`${Xt().T.yellow} \u26A0 Orchestrator: total estimated calls ${p} > ${h} \u2014 consider raising maxSubTasks${Xt().T.reset}`)}return f}async function c0(t,e,n){if(!t||t.length===0)return{summary:"No sub-tasks were executed.",conflicts:[],commitMessage:"",resourcesChanged:[]};let o=t.map((f,p)=>{let h=f.status==="done"?"SUCCESS":f.status==="truncated"?"PARTIAL":"FAILED";return`--- Agent ${p+1} [${h}] ---
813
813
  Task: ${f.task}
814
814
  Result: ${f.result}
815
815
  Tools: ${(f.toolsUsed||[]).join(", ")||"none"}`}).join(`
816
816
 
817
- `),r=[{role:"system",content:t0.replace("{prompt}",e).replace("{results}",o)},{role:"user",content:"Synthesize the sub-agent results above."}],i={};if(n){let f=Vy(n);f.provider&&(i.provider=f.provider),f.model&&(i.model=f.model)}let c=(await Xy(r,[],i)).content||"",u=cu(c),l={summary:String(u.summary||""),conflicts:Array.isArray(u.conflicts)?u.conflicts:[],commitMessage:String(u.commitMessage||""),filesChanged:Array.isArray(u.filesChanged)?u.filesChanged:[]},d=i0(l,t);return d&&(l.commitMessage="",l.commitSuppressedReason=d),l}function i0(t,e){let n=/\b(fail(?:ed|ure|s)?|did not pass|tests? (?:are )?failing|red|broken)\b/i,o=/\b(reported|claimed|said)\b.*\b(pass|fail)/i;for(let s of t.conflicts)if(typeof s=="string"){if(n.test(s))return"conflict mentions failure";if(o.test(s)&&/pass/i.test(s)&&/fail/i.test(s))return"agents disagree on pass/fail"}for(let s of e){if(s.status==="error"||s.status==="failed")return`agent reported ${s.status}`;let r=String(s.result||"");if(/\b(test(?:s)? fail|verification fail|build (?:error|fail))/i.test(r))return"agent result describes test/build failure"}return null}async function CR(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(`
817
+ `),r=[{role:"system",content:o0.replace("{prompt}",e).replace("{results}",o)},{role:"user",content:"Synthesize the sub-agent results above."}],i={};if(n){let f=Qy(n);f.provider&&(i.provider=f.provider),f.model&&(i.model=f.model)}let c=(await Zy(r,[],i)).content||"",u=fu(c),l={summary:String(u.summary||""),conflicts:Array.isArray(u.conflicts)?u.conflicts:[],commitMessage:String(u.commitMessage||""),filesChanged:Array.isArray(u.filesChanged)?u.filesChanged:[]},d=l0(l,t);return d&&(l.commitMessage="",l.commitSuppressedReason=d),l}function l0(t,e){let n=/\b(fail(?:ed|ure|s)?|did not pass|tests? (?:are )?failing|red|broken)\b/i,o=/\b(reported|claimed|said)\b.*\b(pass|fail)/i;for(let s of t.conflicts)if(typeof s=="string"){if(n.test(s))return"conflict mentions failure";if(o.test(s)&&/pass/i.test(s)&&/fail/i.test(s))return"agents disagree on pass/fail"}for(let s of e){if(s.status==="error"||s.status==="failed")return`agent reported ${s.status}`;let r=String(s.result||"");if(/\b(test(?:s)? fail|verification fail|build (?:error|fail))/i.test(r))return"agent result describes test/build failure"}return null}async function MR(t,e={}){let n=e.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL||n0,o=e.workerModel||t0,s=e.maxParallel||e0,r=e.maxSubTasks||da,i=e.onProgress||(()=>{}),a={input:0,output:0};console.log(`
818
818
  ${ge.bold}Orchestrator${ge.reset} ${ge.dim}model: ${n} | workers: ${o} | max parallel: ${s}${ge.reset}
819
- `),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}
820
- `);let l=Date.now(),d=s0(s),f={findings:[],_lock:!1},p=c.map(F=>{let ee=ER(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 TR(h);g.start();let w=`
819
+ `),i("decomposing"),console.log(`${ge.dim}Phase 1: Decomposing prompt into sub-tasks...${ge.reset}`);let c;try{c=await a0(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}
820
+ `);let l=Date.now(),d=i0(s),f={findings:[],_lock:!1},p=c.map(F=>{let ee=AR(F.task);return(ee?Jy(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 OR(h);g.start();let w=`
821
821
  You are a focused coding agent executing ONE specific sub-task.
822
822
  Your scope is limited to the files listed in your task definition.
823
823
 
@@ -845,21 +845,21 @@ RULES:
845
845
  `,_=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(`
846
846
  `),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:
847
847
  ${ve}
848
- `:"",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=l0(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}
849
- `)),te++;let re=Y&&P!==B?B:P;return zy({task:F.task,type:x,context:Ee.length>0?Ee.join(`
850
- `):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(c0(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:MR(F,X,Y),max_iterations:4,model:P,_skipLog:!0,_systemPrompt:w},{onUpdate:()=>{}},1);a0(re.result)?(C=`
848
+ `:"",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=f0(F.task),P=p[ee],B=process.env.NEX_FALLBACK_MODEL||Jy("agentic")||o,te=0,X=await r0(async()=>{let Y=te>0;Y&&(g.update(ee,"retry"),process.stderr.write(` ${ge.dim}[Agent ${ee+1}] retrying after error...${ge.reset}
849
+ `)),te++;let re=Y&&P!==B?B:P;return Vy({task:F.task,type:x,context:Ee.length>0?Ee.join(`
850
+ `):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(d0(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 Vy({task:`Review the completed changes for: ${F.task}`,type:"review",context:jR(F,X,Y),max_iterations:4,model:P,_skipLog:!0,_systemPrompt:w},{onUpdate:()=>{}},1);u0(re.result)?(C=`
851
851
 
852
852
  Reviewer findings:
853
853
  ${re.result}`,f.findings.push({agentId:`${F.id}-review`,summary:String(re.result||"").slice(0,200),files:Y})):re.result&&(C=`
854
854
 
855
855
  Reviewer: ${re.result}`)}catch(re){C=`
856
856
 
857
- 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}),SR()}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(`
857
+ 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}),CR()}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 c0(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(`
858
858
  `),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(`
859
859
  ${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}`):oe.commitSuppressedReason&&console.log(`${ge.yellow}No commit suggested:${ge.reset} ${oe.commitSuppressedReason}`);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}
860
- `),{results:v,synthesis:oe,totalTokens:a}}var AR=/\b(research|analyze|investigate|check|verify|review|audit|read|find|search|discover|look|examine|inspect|scan|list)\b/i,OR=/\b(review|audit|verify|validate|inspect|critique)\b/i,NR=/\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 MR(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(`
861
- `)}function a0(t){return!t||typeof t!="string"?!1:!/no material findings/i.test(t)}function c0(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 l0(t){if(!t)return"implement";let e=AR.test(t),n=OR.test(t);return NR.test(t)?"implement":n?"review":e?"explore":"implement"}u0.exports={runOrchestrated:CR,decompose:o0,synthesize:r0,shouldSuppressCommit:i0,detectComplexPrompt:RR,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:l0,_hasMaterialReviewFindings:a0,_shouldRunFollowUpReview:c0}});var Yl=Q((XO,H0)=>{var{C:m,Spinner:ho,TaskProgress:PR,formatToolCall:LR,formatToolSummary:xu,formatSectionHeader:gr,formatMilestone:IR,setActiveTaskProgress:HO,getThinkingVerb:lu,setActiveModelForSpinner:f0}=rt(),{debugLog:L,warnLog:YO}=hc(),{MilestoneTracker:jR}=Tf(),{callStream:p0}=ct(),{parseToolArgs:DR}=Ao(),{executeTool:qR}=zs(),{gatherProjectContext:FR}=Qg(),{fitToContext:BR,forceCompress:hn,getUsage:tn,estimateTokens:UR,buildProgressSnapshot:WR}=fn(),{autoSave:HR,flushAutoSave:YR}=na(),{scoreMessages:GR,formatScore:zR,appendScoreHistory:KR}=sa(),{detectCategory:XR,getModelForPhase:ku,getPhaseBudget:_s,isPhaseRoutingEnabled:VR}=ms();function Ne(t){HR(t),YR()}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 JR(t){if(!t||typeof t!="string")return!1;let e=t.trim();if(!e)return!1;let n=e.slice(-300);return n.includes("?")?/(?:would you like|do you want|should i|shall i|can you clarify|could you clarify|what would you like me to|which (?:one|option|area|approach)|how would you like me to)\b/i.test(n):!1}function ZR(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=GR(t);if(!n)return;console.log(zR(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();KR(n.score,{version:s.version,model:o?o():null,sessionName:"_autosave",issues:n.issues})}catch{}}catch{}}var{getMemoryContext:QR}=er(),{getDeploymentContextBlock:e1,probeUrlServer:t1,detectRuntimeDebugTarget:h0}=zl(),{getFewShotForInput:n1}=by(),{checkPermission:s1,setPermission:o1,savePermissions:r1}=Sy(),{confirm:R0,setAllowAlwaysHandler:i1,getAutoConfirm:Ts}=No(),{isPlanMode:Tr,getPlanModePrompt:a1,PLAN_MODE_ALLOWED_TOOLS:C0,setPlanContent:c1,extractStepsFromText:l1,createPlan:u1,getActivePlan:GO,startExecution:zO,advancePlanStep:d1,getPlanStepInfo:f1}=ca(),{StreamRenderer:p1}=By(),{runHooks:m0}=Gy(),{routeMCPCall:h1,getMCPToolDefinitions:m1}=Nc(),{getSkillInstructions:g1,getSkillToolDefinitions:y1,routeSkillCall:w1,matchSkillTriggers:b1}=Ac(),{trackUsage:g0,estimateTokens:y0}=ii();function w0(t){return!t||typeof t!="string"?0:typeof y0=="function"?y0(t):Math.ceil(t.length/4)}var{validateToolArgs:$1}=Lc(),{filterToolsForModel:b0,getModelTier:_1,PROVIDER_DEFAULT_TIER:KO}=Uo(),{getConfiguredProviders:x1,getActiveProviderName:mo,getActiveModelId:sn,setActiveModel:uu,MODEL_EQUIVALENTS:Ta}=ct(),{getModelProfile:k1,getModelBriefing:v1}=Li(),Ue=require("fs"),ze=require("path"),S1=(()=>{let t=parseInt(process.env.NEX_MILESTONE_STEPS??"5",10);return Number.isFinite(t)&&t>=0?t:5})();function E1(t){let e=IR(t.phaseName,t.stepCount,t.toolCounts,t.elapsed,t.filesRead,t.filesModified);process.stdout.write(`${e}
862
- `)}var $0=/(?:^|\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,T1=/\b(?:clipboard|pasteboard|zwischenablage|screenshot aus clipboard)\b/i;function R1(t){let e=[],n;for($0.lastIndex=0;(n=$0.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 A0(t){let e=[],n;for(_0.lastIndex=0;(n=_0.exec(t))!==null;)e.push(n[1].trim());return e}async function O0(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]:C1(t);return{data:Buffer.from(n.data).toString("base64"),media_type:s}}catch{return null}}function C1(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 N0(){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
860
+ `),{results:v,synthesis:oe,totalTokens:a}}var PR=/\b(research|analyze|investigate|check|verify|review|audit|read|find|search|discover|look|examine|inspect|scan|list)\b/i,LR=/\b(review|audit|verify|validate|inspect|critique)\b/i,IR=/\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 jR(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(`
861
+ `)}function u0(t){return!t||typeof t!="string"?!1:!/no material findings/i.test(t)}function d0(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 f0(t){if(!t)return"implement";let e=PR.test(t),n=LR.test(t);return IR.test(t)?"implement":n?"review":e?"explore":"implement"}p0.exports={runOrchestrated:MR,decompose:a0,synthesize:c0,shouldSuppressCommit:l0,detectComplexPrompt:NR,extractJSON:fu,createSemaphore:i0,DECOMPOSE_PROMPT:s0,SYNTHESIZE_PROMPT:o0,DEFAULT_ORCHESTRATOR_MODEL:n0,DEFAULT_WORKER_MODEL:t0,DEFAULT_MAX_PARALLEL:e0,DEFAULT_MAX_SUBTASKS:da,withRetry:r0,_classifyWorkerType:f0,_hasMaterialReviewFindings:u0,_shouldRunFollowUpReview:d0}});var Xl=Q((tN,z0)=>{var{C:m,Spinner:ho,TaskProgress:DR,formatToolCall:qR,formatToolSummary:Eu,formatSectionHeader:gr,formatMilestone:FR,setActiveTaskProgress:VO,getThinkingVerb:pu,setActiveModelForSpinner:m0}=it(),{debugLog:L,warnLog:JO}=yc(),{MilestoneTracker:BR}=Cf(),{callStream:g0}=lt(),{parseToolArgs:UR}=Ao(),{executeTool:WR}=zs(),{gatherProjectContext:HR}=ny(),{fitToContext:YR,forceCompress:mn,getUsage:tn,estimateTokens:GR,buildProgressSnapshot:zR}=pn(),{autoSave:KR,flushAutoSave:XR}=sa(),{scoreMessages:VR,formatScore:JR,appendScoreHistory:ZR}=oa(),{detectCategory:QR,getModelForPhase:Tu,getPhaseBudget:_s,isPhaseRoutingEnabled:e1}=ms();function Ne(t){KR(t),XR()}function fa(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 t1(t){if(!t||typeof t!="string")return!1;let e=t.trim();if(!e)return!1;let n=e.slice(-300);return n.includes("?")?/(?:would you like|do you want|should i|shall i|can you clarify|could you clarify|what would you like me to|which (?:one|option|area|approach)|how would you like me to)\b/i.test(n):!1}function n1(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=VR(t);if(!n)return;console.log(JR(n,m));try{let{_getSessionsDir:o}=sa(),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:s1}=er(),{getDeploymentContextBlock:o1,probeUrlServer:r1,detectRuntimeDebugTarget:y0}=Jl(),{getFewShotForInput:i1}=xy(),{checkPermission:a1,setPermission:c1,savePermissions:l1}=Ry(),{confirm:O0,setAllowAlwaysHandler:u1,getAutoConfirm:Ts}=No(),{isPlanMode:Tr,getPlanModePrompt:d1,PLAN_MODE_ALLOWED_TOOLS:N0,setPlanContent:f1,extractStepsFromText:p1,createPlan:h1,getActivePlan:ZO,startExecution:QO,advancePlanStep:m1,getPlanStepInfo:g1}=la(),{StreamRenderer:y1}=Hy(),{runHooks:w0}=Xy(),{routeMCPCall:w1,getMCPToolDefinitions:b1}=Lc(),{getSkillInstructions:$1,getSkillToolDefinitions:_1,routeSkillCall:x1,matchSkillTriggers:k1}=Mc(),{trackUsage:b0,estimateTokens:$0}=ai();function _0(t){return!t||typeof t!="string"?0:typeof $0=="function"?$0(t):Math.ceil(t.length/4)}var{validateToolArgs:v1}=Dc(),{filterToolsForModel:x0,getModelTier:S1,PROVIDER_DEFAULT_TIER:eN}=Uo(),{getConfiguredProviders:E1,getActiveProviderName:mo,getActiveModelId:sn,setActiveModel:hu,MODEL_EQUIVALENTS:Ra}=lt(),{getModelProfile:T1,getModelBriefing:R1}=Ii(),Ue=require("fs"),ze=require("path"),C1=(()=>{let t=parseInt(process.env.NEX_MILESTONE_STEPS??"5",10);return Number.isFinite(t)&&t>=0?t:5})();function A1(t){let e=FR(t.phaseName,t.stepCount,t.toolCounts,t.elapsed,t.filesRead,t.filesModified);process.stdout.write(`${e}
862
+ `)}var k0=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi,v0=/(?:^|\s)(https?:\/\/[^\s]+\.(?:png|jpe?g|gif|webp)(?:\?[^\s]*)?)(?:\s|$)/gi,O1=/\b(?:clipboard|pasteboard|zwischenablage|screenshot aus clipboard)\b/i;function N1(t){let e=[],n;for(k0.lastIndex=0;(n=k0.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 M0(t){let e=[],n;for(v0.lastIndex=0;(n=v0.exec(t))!==null;)e.push(n[1].trim());return e}async function P0(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]:M1(t);return{data:Buffer.from(n.data).toString("base64"),media_type:s}}catch{return null}}function M1(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 L0(){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
863
863
  set imgData to the clipboard as \xABclass PNGf\xBB
864
864
  return "has_image"
865
865
  on error
@@ -870,50 +870,50 @@ end try`],{timeout:3e3});if(o.stdout&&o.stdout.toString().trim()==="has_image"){
870
870
  set fRef to open for access filePath with write permission
871
871
  write imgData to fRef
872
872
  close access fRef
873
- `;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 x0(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 M0(t){let e=R1(t),n=A0(t),o=T1.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}=x0(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}=x0(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(O0));for(let a of i)a&&r.push({type:"image",media_type:a.media_type,data:a.data})}if(o){let i=N0();i?(r.push({type:"image",media_type:i.media_type,data:i.data}),r[0].text+=`
873
+ `;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 S0(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 I0(t){let e=N1(t),n=M0(t),o=O1.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}=S0(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}=S0(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(P0));for(let a of i)a&&r.push({type:"image",media_type:a.media_type,data:a.data})}if(o){let i=L0();i?(r.push({type:"image",media_type:i.media_type,data:i.data}),r[0].text+=`
874
874
  [Clipboard image attached: ${i.path}]`):r[0].text+=`
875
- [No image found in clipboard]`}return r.length>1?r:t})()}var A1=[/\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 P0(t){return typeof t!="string"||!t?!1:A1.some(e=>e.test(t))}function O1(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=`
875
+ [No image found in clipboard]`}return r.length>1?r:t})()}var P1=[/\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 j0(t){return typeof t!="string"||!t?!1:P1.some(e=>e.test(t))}function L1(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=`
876
876
 
877
- [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(`
877
+ [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 Ru(t,e=5){if(!t||t.length<40)return{text:t,truncated:!1,repeatCount:0};let n=t.split(`
878
878
  `),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=`
879
879
 
880
- \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=y1()),pu===null&&(pu=m1()),[...du,...fu,...pu]}var Su=50;function N1(t){Number.isFinite(t)&&t>0&&(Su=t)}var ma=()=>null;function M1(t){ma=t}var _r=null,Eu=null,go=null,yo="",wo=0,Tu="",Ru=0,ga=new Map,P1=1e4,L1=6e3,I1=/\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 j1(t){return!t||typeof t!="string"?t:t.replace(I1,(e,n)=>`${n}=***REDACTED***`)}var D1=7e3,q1=4e3;function F1(t,e=null){let n=j1(t),o=UR(n),s=e==="read_file"?D1:P1,r=e==="read_file"?q1:L1;if(o>s)try{let{compressToolResult:i}=fn();return i(n,r)}catch{return n}return n}function L0(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=b0(t);return ga.set(o,s),s}catch{return b0(t)}}function B1(){ga.clear()}function U1(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},W1=3e4;async function I0(){if(xr.hash&&Date.now()-xr.ts<W1)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 H1=new Set(["spawn_agents"]),hu=10,mu=10,fa=5,k0=6e4,gu=12e4,Y1=process.env.NEX_STALE_AUTO_SWITCH!=="0";function G1(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{}}i1(t=>{o1(t,"allow"),r1(),console.log(`${m.green} \u2713 ${t}: always allow${m.reset}`)});async function z1(t){let e=t.function.name,n=DR(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.
880
+ \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 mu=null,gu=null,yu=null;function ht(){if(mu===null){let{TOOL_DEFINITIONS:t}=zs();mu=t}return gu===null&&(gu=_1()),yu===null&&(yu=b1()),[...mu,...gu,...yu]}var Cu=50;function I1(t){Number.isFinite(t)&&t>0&&(Cu=t)}var ga=()=>null;function j1(t){ga=t}var _r=null,Au=null,go=null,yo="",wo=0,Ou="",Nu=0,ya=new Map,D1=1e4,q1=6e3,F1=/\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 B1(t){return!t||typeof t!="string"?t:t.replace(F1,(e,n)=>`${n}=***REDACTED***`)}var U1=7e3,W1=4e3;function H1(t,e=null){let n=B1(t),o=GR(n),s=e==="read_file"?U1:D1,r=e==="read_file"?W1:q1;if(o>s)try{let{compressToolResult:i}=pn();return i(n,r)}catch{return n}return n}function D0(t){try{let{getActiveModel:e}=lt(),n=e(),o=n?`${n.provider}:${n.id}`:"default";if(ya.has(o))return ya.get(o);let s=x0(t);return ya.set(o,s),s}catch{return x0(t)}}function Y1(){ya.clear()}function G1(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},z1=3e4;async function q0(){if(xr.hash&&Date.now()-xr.ts<z1)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 Mu(){_r=null,Au=null,xr={hash:null,ts:0},go=null}var K1=new Set(["spawn_agents"]),wu=10,bu=10,pa=5,E0=6e4,$u=12e4,X1=process.env.NEX_STALE_AUTO_SWITCH!=="0";function V1(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{}}u1(t=>{c1(t,"allow"),l1(),console.log(`${m.green} \u2713 ${t}: always allow${m.reset}`)});async function J1(t){let e=t.function.name,n=UR(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.
881
881
  Raw input: ${typeof t.function.arguments=="string"?t.function.arguments.substring(0,200):"N/A"}
882
882
 
883
883
  Expected JSON schema for "${e}":
884
884
  ${f}
885
885
 
886
- 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=$1(e,n);if(!s.valid){L(`${m.yellow} \u26A0 ${e}: ${s.error.split(`
887
- `)[0]}${m.reset}`);let l=(S0.get(e)||0)+1;S0.set(e,l);let d=l>=2?`${s.error}
886
+ 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=v1(e,n);if(!s.valid){L(`${m.yellow} \u26A0 ${e}: ${s.error.split(`
887
+ `)[0]}${m.reset}`);let l=(R0.get(e)||0)+1;R0.set(e,l);let d=l>=2?`${s.error}
888
888
 
889
- [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()&&!C0.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=s1(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 R0(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 K1(t,e,n={}){let o=await w1(t,e);if(o!==null)return o;let s=await h1(t,e);return s!==null?s:qR(t,e,n)}function X1(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(LR(t.fnName,t.args));let n=m0("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 K1(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)+`
889
+ [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()&&!N0.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 Bn++,Er=e,L(`${m.yellow} \u2717 ${e}: blocked in plan phase (read-only, block #${Bn})${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=a1(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 O0(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 Z1(t,e,n={}){let o=await x1(t,e);if(o!==null)return o;let s=await w1(t,e);return s!==null?s:WR(t,e,n)}function Q1(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 _u(t,e=!1){e||console.log(qR(t.fnName,t.args));let n=w0("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 _=Eu(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}`);bn?.onToolStart&&bn.onToolStart(t.fnName,t.args);let s=await Z1(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)+`
890
890
  ...(truncated ${i.length-5e4} chars)`:i,c=a.split(`
891
- `)[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=m0("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=F1(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+=`
891
+ `)[0],u=c.startsWith("ERROR")||c.includes("CANCELLED")||c.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(a)&&/✗ Agent/.test(a),l=Eu(t.fnName,t.args,a,u);e||console.log(l),bn?.onToolEnd&&bn.onToolEnd(t.fnName,l,!u);let f=w0("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=H1(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+=`
892
892
  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+=`
893
893
  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+=`
894
- 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 V1=[{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 V1){let o=t.match(e);if(o){let s=(o[1]||"").trim();return s?`${n}: ${s}`:n}}return null}async function J1(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=X1(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(H1.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=[],v0=300,j0=900*1e3;function mn(t,e){let n=t.get(e);return n?Date.now()-n.ts>j0?(t.delete(e),0):n.count:0}function xs(t,e){let n=t.get(e),o=n&&Date.now()-n.ts<=j0?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,D0=new Map,ya=new Map,Rr=new Set,q0=new Map,wa=new Map,Cr=new Set,yn=new Map,Tn=new Map,Ar=new Map,Bt=new Map,Rs=new Map,S0=new Map,Ra=new Map,Au=new Map,Ut=0,kr=0,ba=0,Ou="",$a=0,Pt=!1,pa=0,_a=0,vs=-1,Nu=!1,xa=0,ka=!1,Ht=0,Yt=!1,nn=0,Gt=0,dt=!1,St="",vr=0,qn=0,va="",Ss=0,Es=0,Sa="",wr=0,Wt=!1,Mu=!1,Or=new Map,Nr=new Set,Sr=null,$u=!1,br=0,E0=!1,Re="plan",Ca=0,we=!1,Fn=0,Er=null,on=null,Pu=null,Lu=null,bo=0,$o=0,_o=0,xo=!1,ko=0,Cs=null,As=[],ks=new Set;function Z1(t){return t==="write_file"||t==="edit_file"||t==="patch_file"||t==="bash"}function T0(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 Q1(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 eC(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}
895
- `)):(Ou=t,$a=1,L(`${e} \u26A0 ${t}${m.reset}`))}var Ea=[];function tC(t){Ea.push(t.trim())}function nC(){return Ea.length===0?null:Ea.splice(0,Ea.length).join(`
896
- `)}function sC(t){let e=t._startedAt?Math.round((t.finishedAt-t._startedAt)/1e3):null,n=e!==null?`
894
+ 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 eC=[{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 xu(t){for(let{re:e,label:n}of eC){let o=t.match(e);if(o){let s=(o[1]||"").trim();return s?`${n}: ${s}`:n}}return null}async function tC(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=Q1(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 _u(t[c],e);o[c]=u,s.push(l)}else{let c=r.map(l=>_u(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(Eu(u.fnName,u.args||{},u.errorResult.content,!0));continue}if(K1.has(u.fnName)){await a(),u.fnName==="spawn_agents"&&i&&(i.stop(),i=null);let{msg:l,summary:d}=await _u(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=[],T0=300,F0=900*1e3;function gn(t,e){let n=t.get(e);return n?Date.now()-n.ts>F0?(t.delete(e),0):n.count:0}function xs(t,e){let n=t.get(e),o=n&&Date.now()-n.ts<=F0?n.count+1:1;return t.set(e,{count:o,ts:Date.now()}),o}function ku(t,e,n){t.set(e,{count:n,ts:Date.now()})}var Wu=new Map,B0=new Map,wa=new Map,Rr=new Set,U0=new Map,ba=new Map,Cr=new Set,wn=new Map,Tn=new Map,Ar=new Map,Wt=new Map,Rs=new Map,R0=new Map,Ca=new Map,Pu=new Map,Ht=0,kr=0,$a=0,Lu="",_a=0,Pt=!1,ha=0,xa=0,vs=-1,Iu=!1,ka=0,va=!1,Gt=0,zt=!1,nn=0,Kt=0,ft=!1,St="",vr=0,Fn=0,Sa="",Ss=0,Es=0,Ea="",wr=0,Yt=!1,ju=!1,Or=new Map,Nr=new Set,Sr=null,vu=!1,br=0,C0=!1,Re="plan",Aa=0,we=!1,Bn=0,Er=null,on=null,Du=null,qu=null,bo=0,$o=0,_o=0,xo=!1,ko=0,Cs=null,As=[],ks=new Set;function nC(t){return t==="write_file"||t==="edit_file"||t==="patch_file"||t==="bash"}function A0(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 sC(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 Fu(t){return String(t||"").replace(/\\/g,"/").replace(/^\.\//,"").trim()}function oC(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=>Fu(o)))]:[]}function po(t,e){t===Lu?(_a++,debug&&debug.DEBUG&&process.stdout.write(`\x1B[1A\x1B[2K${e} \u26A0 ${t} (\xD7${_a})${m.reset}
895
+ `)):(Lu=t,_a=1,L(`${e} \u26A0 ${t}${m.reset}`))}var Ta=[];function rC(t){Ta.push(t.trim())}function iC(){return Ta.length===0?null:Ta.splice(0,Ta.length).join(`
896
+ `)}function aC(t){let e=t._startedAt?Math.round((t.finishedAt-t._startedAt)/1e3):null,n=e!==null?`
897
897
  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?`
898
898
  Files modified: ${t.result.filesModified.join(", ")}`:"";return`[BACKGROUND AGENT COMPLETED]
899
899
  Job: ${t.jobId}
900
900
  Task: "${t.agentDef.task}"`+n+`
901
901
  Status: ${t.result.status||"done"}`+s+`
902
- Result: ${o}`}function ha(t,e){let{getCompletedJobs:n}=to(),o=n();for(let s of o){let r={role:"user",content:sC(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}
903
- `)}}function F0(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(`
904
- `).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 oC(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 rC(){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=rC();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 iC(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(`
905
- `)}function aC(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 B0(t){let e=oC(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 U0(t){let e=await B0(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(`
902
+ Result: ${o}`}function ma(t,e){let{getCompletedJobs:n}=to(),o=n();for(let s of o){let r={role:"user",content:aC(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}
903
+ `)}}function W0(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(`
904
+ `).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 cC(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 lC(){return Ue.existsSync(ze.join(process.cwd(),"pnpm-lock.yaml"))?"pnpm":Ue.existsSync(ze.join(process.cwd(),"yarn.lock"))?"yarn":"npm"}function yn(t){let e=lC();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 uC(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(`
905
+ `)}function dC(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 H0(t){let e=cC(t);if(e.length===0)return[];let{searchContentIndex:n}=ln(),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 Y0(t){let e=await H0(t);if(e.length===0)return"";let{getRelatedFiles:n,findSymbolReferences:o}=ln(),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(`
906
906
  `)}
907
907
  Use these exact targeted reads before broader searching.
908
908
 
909
- `}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 cC(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,on=ku(t,Cs),t==="verify"&&($o=0,_o=0,xo=!1,ko=0),Ht=0,Yt=!1,nn=0,Gt=0,Rs.clear(),Ra.clear(),qu.clear(),Ar.clear(),t==="implement"&&(As=F0(e||"",yn));let r=As.length>0?`
909
+ `}async function Oa(t){let{getFileIndex:e}=ln(),{buildContentIndex:n,findSymbolReferences:o,getRelatedFiles:s}=ln(),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 fC(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,Aa=0,on=Tu(t,Cs),t==="verify"&&($o=0,_o=0,xo=!1,ko=0),Gt=0,zt=!1,nn=0,Kt=0,Rs.clear(),Ca.clear(),Wu.clear(),Ar.clear(),t==="implement"&&(As=W0(e||"",wn));let r=As.length>0?`
910
910
 
911
911
  ACTION ITEMS (execute these in order, do NOT re-read these files):
912
912
  `+As.map((c,u)=>`${u+1}. ${c.file} \u2014 ${c.action}`).join(`
913
- `):"",i=await U0(t==="verify"?o:e||o||""),a;if(t==="implement")Pu=e?.slice(0,2e3)||"",a=`[PHASE: IMPLEMENTATION] Analysis complete. Based on the analysis:
914
- ${Pu}
913
+ `):"",i=await Y0(t==="verify"?o:e||o||""),a;if(t==="implement")Du=e?.slice(0,2e3)||"",a=`[PHASE: IMPLEMENTATION] Analysis complete. Based on the analysis:
914
+ ${Du}
915
915
 
916
- ${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):
916
+ ${i}Now implement the fix/changes. Do not investigate further \u2014 edit files directly.`+r;else if(t==="verify"){qu=e?.slice(0,500)||"";let c=n?[...n].join(", "):"none",u=await Hu(n),l=await Oa(n),d=u.length>0?`Suggested checks (run the narrowest ones that fit the change):
917
917
  ${u.map((p,h)=>`${h+1}. ${p}`).join(`
918
918
  `)}
919
919
 
@@ -930,24 +930,24 @@ Prefer these before broader suites when a targeted run is possible.
930
930
  Report PASS (all good) or FAIL (list specific issues).
931
931
 
932
932
  Files modified: ${c}
933
- ${i}${d}${f}Summary: ${Lu}`}return L(`${m.cyan} \u21B3 Phase transition: ${s} \u2192 ${t} (model: ${on||"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(...cC(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 lC(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 uC(){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)
933
+ ${i}${d}${f}Summary: ${qu}`}return L(`${m.cyan} \u21B3 Phase transition: ${s} \u2192 ${t} (model: ${on||"default"})${m.reset}`),a?{role:"user",content:a}:null}async function Hu(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",yn("test")],["lint",yn("lint")],["typecheck",yn("typecheck")],["check",yn("check")],["build",yn("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(yn("test")),(Ue.existsSync(ze.join(process.cwd(),"pytest.ini"))||Ue.existsSync(ze.join(process.cwd(),"pyproject.toml")))&&e.push("pytest"));let r=await Oa(t);e.unshift(...fC(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(yn("typecheck"))&&e.push(yn("typecheck")),a&&!e.includes(yn("lint"))&&e.push(yn("lint")),[...new Set(e)].slice(0,4)}function pC(t){let e=process.env.NEX_LANGUAGE;if(e&&e!=="auto")return e;if(Yu())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 hC(){let t=process.env.NEX_LANGUAGE,e=process.env.NEX_CODE_LANGUAGE,n=process.env.NEX_COMMIT_LANGUAGE,o=Yu(),s=!t||t==="auto"?null:t,r=[`# Language Rules (CRITICAL \u2014 enforce strictly)
934
934
  `];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(`
935
935
  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(`
936
936
  `)+`
937
937
 
938
- `}function dC(t){let e=lC(t);return Bu()?`# Current Turn Language (CRITICAL \u2014 enforce strictly)
938
+ `}function mC(t){let e=pC(t);return Yu()?`# Current Turn Language (CRITICAL \u2014 enforce strictly)
939
939
  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.
940
940
 
941
941
  `:`# Current Turn Language (CRITICAL \u2014 enforce strictly)
942
942
  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.
943
943
 
944
- `}function fC(){if(go!==null)return go;try{let e=x1().flatMap(s=>s.models.map(r=>({spec:`${s.name}:${r.id}`,tier:_1(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=`
944
+ `}function gC(){if(go!==null)return go;try{let e=E1().flatMap(s=>s.models.map(r=>({spec:`${s.name}:${r.id}`,tier:S1(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=`
945
945
  # Sub-Agent Model Routing
946
946
 
947
947
  `;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 |
948
948
  |---|---|---|
949
949
  `;for(let s of e)o+=`| ${s.spec} | ${s.tier} | ${n[s.tier]||s.tier} |
950
- `;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 pC(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 I0()+":"+sn();if(_r!==null&&t===Eu)return _r;let e=await FR(process.cwd()),n=QR(),o=g1(),s=Tr()?a1():"",r=uC(),i=e1(),a=v1(sn());return _r=`${a?`## Model Briefing
950
+ `;return go=o,o}catch(t){return process.env.NEX_DEBUG&&console.error("[agent] model routing guide failed:",t.message),go="",""}}var Bu="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->";function yC(t){let e=t.indexOf(Bu);return e===-1?{dynamic:t,static:""}:{dynamic:t.slice(0,e).trimEnd(),static:t.slice(e+Bu.length).trimStart()}}async function Uu(){let t=await q0()+":"+sn();if(_r!==null&&t===Au)return _r;let e=await HR(process.cwd()),n=s1(),o=$1(),s=Tr()?d1():"",r=hC(),i=o1(),a=R1(sn());return _r=`${a?`## Model Briefing
951
951
  ${a}
952
952
 
953
953
  ---
@@ -1208,7 +1208,7 @@ You have a soft budget of ~30 tool calls per task. Sessions with >40 tool calls
1208
1208
  - Instead: use bash with inline node -e '...' for quick one-off checks.
1209
1209
  - If the test is worth keeping, write it to tests/ with a proper name.
1210
1210
  - Write-then-delete patterns waste 3 tool calls and leave orphans if the session is interrupted.
1211
- ${fC()}
1211
+ ${gC()}
1212
1212
 
1213
1213
  # Edit Protocol (Mandatory \u2014 Follow These Steps Exactly)
1214
1214
 
@@ -1400,97 +1400,97 @@ class ErrorBoundary extends React.Component {
1400
1400
  - Use migrations for schema changes, never manual ALTER TABLE
1401
1401
  - Add database-level constraints (unique, foreign key, check) not just app-level
1402
1402
 
1403
- `,Eu=t,_r}function W0(){qu.clear(),D0.clear(),ya.clear(),Rr.clear(),q0.clear(),wa.clear(),Cr.clear(),yn.clear(),Tn.clear(),Ar.clear(),Bt.clear(),Rs.clear(),Ra.clear(),Au.clear(),Ut=0,kr=0,ba=0,Pt=!1,_a=0,vs=-1,Nu=!1,xa=0,ka=!1,Ht=0,Yt=!1,nn=0,Gt=0,dt=!1,St="",vr=0,va="",Ss=0,Sa="",Es=0,Wt=!1,Mu=!1,Re="plan",Ca=0,we=!1,on=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 hC(){M=[],Sr=null,yo="",wo=0,Tu="",Ru=0,W0();try{let{resetCompactionFailures:t}=wl();t()}catch{}try{let{cancelAllJobs:t}=to();t()}catch{}}function mC(){M.length>v0&&M.splice(0,M.length-v0)}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 gC(){return M.length}function yC(){return M}function wC(t){M=t}async function bC(){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(`
1403
+ `,Au=t,_r}function G0(){Wu.clear(),B0.clear(),wa.clear(),Rr.clear(),U0.clear(),ba.clear(),Cr.clear(),wn.clear(),Tn.clear(),Ar.clear(),Wt.clear(),Rs.clear(),Ca.clear(),Pu.clear(),Ht=0,kr=0,$a=0,Pt=!1,xa=0,vs=-1,Iu=!1,ka=0,va=!1,Gt=0,zt=!1,nn=0,Kt=0,ft=!1,St="",vr=0,Sa="",Ss=0,Ea="",Es=0,Yt=!1,ju=!1,Re="plan",Aa=0,we=!1,on=null,Du=null,qu=null,As=[],bo=0,$o=0,_o=0,xo=!1,ko=0,Bn=0,Cs=null,Or.clear(),Nr.clear(),Lu="",_a=0}function wC(){M=[],Sr=null,yo="",wo=0,Ou="",Nu=0,G0();try{let{resetCompactionFailures:t}=xl();t()}catch{}try{let{cancelAllJobs:t}=to();t()}catch{}}function bC(){M.length>T0&&M.splice(0,M.length-T0)}function Yu(){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 Su(t,e,n,o=1500){return!t||!e?!1:t===e&&Date.now()-n<o}function $C(){return M.length}function _C(){return M}function xC(t){M=t}async function kC(){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(`
1404
1404
  `):[]).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+=`
1405
- \u{1F4E6} ${p}${h}`}}catch{}return u}function $C(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(`
1406
- ${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`;$C(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 _C(){if(!process.stdout.isTTY)return{action:"quit"};let t=mo(),e=sn(),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}
1407
- `),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 xC(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 kC(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 vC(t,e=null,n={}){let o=k1(sn());k0=o.staleWarn,gu=o.staleAbort,wn=e;let s=t;if(Sr&&typeof t=="string"&&(s=`${Sr}
1405
+ \u{1F4E6} ${p}${h}`}}catch{}return u}function vC(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(`
1406
+ ${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`;vC(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 SC(){if(!process.stdout.isTTY)return{action:"quit"};let t=mo(),e=sn(),n=Ra.fast?.[t],o=Ra.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}
1407
+ `),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 EC(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 TC(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 bn=null;async function RC(t,e=null,n={}){let o=T1(sn());E0=o.staleWarn,$u=o.staleAbort,bn=e;let s=t;if(Sr&&typeof t=="string"&&(s=`${Sr}
1408
1408
 
1409
- ${t}`,Sr=null),typeof s=="string"){let xe=xC(s),ye=kC(s);(xe.length>0||ye.length>0)&&(s+=`
1409
+ ${t}`,Sr=null),typeof s=="string"){let xe=EC(s),ye=TC(s);(xe.length>0||ye.length>0)&&(s+=`
1410
1410
 
1411
1411
  [System Note for Assistant: To resolve this task faster, consider these hints:
1412
1412
  `,xe.length>0&&(s+=`- The user mentioned URLs containing the paths/folders: ${xe.join(", ")}. Prioritize searching these folder names using glob or grep first.
1413
1413
  `),ye.length>0&&ye.forEach(Ce=>{s+=`- ${Ce}
1414
- `}),s+="Always prefer parallel search execution if unsure.]")}typeof s=="string"&&P0(s)&&(s+=`
1414
+ `}),s+="Always prefer parallel search execution if unsure.]")}typeof s=="string"&&j0(s)&&(s+=`
1415
1415
 
1416
- [Note for assistant: the user appears frustrated \u2014 acknowledge their concern briefly and empathetically before proceeding]`);let r=typeof t=="string"?h0(t):null,i=M0(s);i&&typeof i.then=="function"&&(i=await i),M.push({role:"user",content:i}),mC();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}=d0(),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?`
1416
+ [Note for assistant: the user appears frustrated \u2014 acknowledge their concern briefly and empathetically before proceeding]`);let r=typeof t=="string"?y0(t):null,i=I0(s);i&&typeof i.then=="function"&&(i=await i),M.push({role:"user",content:i}),bC();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}=h0(),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 ct=Xe.synthesis.summary||"",An=Xe.synthesis.filesChanged?.length?`
1417
1417
 
1418
- Files changed: ${Xe.synthesis.filesChanged.join(", ")}`:"",ot=Xe.synthesis.conflicts?.length?`
1418
+ Files changed: ${Xe.synthesis.filesChanged.join(", ")}`:"",rt=Xe.synthesis.conflicts?.length?`
1419
1419
 
1420
1420
  Conflicts:
1421
- ${Xe.synthesis.conflicts.map(Lt=>`- ${Lt}`).join(`
1422
- `)}`:"";M.push({role:"assistant",content:at+An+ot}),Ne(M),yr(M)}return Xe}Ce.isComplex&&process.stdout.isTTY&&console.log(`${m.dim}Hint: ~${Ce.estimatedGoals} goals detected. Disable with NEX_AUTO_ORCHESTRATE=false${m.reset}`)}catch{}let{setOnChange:u}=gl(),l=null,d=0;u((xe,ye)=>{xe==="create"?(l&&l.stop(),l=new PR(ye.name,ye.tasks),l.setStats({tokens:d}),l.start()):xe==="update"&&l?l.updateTask(ye.id,ye.status):xe==="clear"&&l&&(l.stop(),l=null)});let f=await Du(),p=f;try{let{getBrainContext:xe}=Ml(),ye=await xe(t);ye&&(p=f+`
1421
+ ${Xe.synthesis.conflicts.map(It=>`- ${It}`).join(`
1422
+ `)}`:"";M.push({role:"assistant",content:ct+An+rt}),Ne(M),yr(M)}return Xe}Ce.isComplex&&process.stdout.isTTY&&console.log(`${m.dim}Hint: ~${Ce.estimatedGoals} goals detected. Disable with NEX_AUTO_ORCHESTRATE=false${m.reset}`)}catch{}let{setOnChange:u}=$l(),l=null,d=0;u((xe,ye)=>{xe==="create"?(l&&l.stop(),l=new DR(ye.name,ye.tasks),l.setStats({tokens:d}),l.start()):xe==="update"&&l?l.updateTask(ye.id,ye.status):xe==="clear"&&l&&(l.stop(),l=null)});let f=await Uu(),p=f;try{let{getBrainContext:xe}=jl(),ye=await xe(t);ye&&(p=f+`
1423
1423
  `+ye+`
1424
- `)}catch(xe){process.env.NEX_DEBUG&&console.error("[agent] brain context failed:",xe.message)}let g=b1(typeof t=="string"?t:"");if(g.length>0){let xe=g.map(ye=>`[Triggered: ${ye.name}]
1424
+ `)}catch(xe){process.env.NEX_DEBUG&&console.error("[agent] brain context failed:",xe.message)}let g=k1(typeof t=="string"?t:"");if(g.length>0){let xe=g.map(ye=>`[Triggered: ${ye.name}]
1425
1425
  ${ye.instructions}`).join(`
1426
1426
  `);p+=`
1427
1427
  `+xe+`
1428
1428
  `}p+=`
1429
- `+dC(t);let w=[{role:"system",content:p},...M];f0(sn());let _=new ho(lu());_.start();let S=M.length===1,A=S?bC().catch(()=>null):Promise.resolve(null),E=S?t1(typeof t=="string"?t:"").catch(()=>null):Promise.resolve(null),v=ht(),[{messages:N,compressed:ne,compacted:oe,tokensRemoved:ue},fe,ie]=await Promise.all([BR(w,v),A,E]),le=tn(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]
1429
+ `+mC(t);let w=[{role:"system",content:p},...M];m0(sn());let _=new ho(pu());_.start();let S=M.length===1,A=S?kC().catch(()=>null):Promise.resolve(null),E=S?r1(typeof t=="string"?t:"").catch(()=>null):Promise.resolve(null),v=ht(),[{messages:N,compressed:ne,compacted:oe,tokensRemoved:ue},fe,ie]=await Promise.all([YR(w,v),A,E]),le=tn(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]
1430
1430
  ${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]
1431
1431
  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]
1432
- 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=n1(typeof t=="string"?t:"");xe&&(T=[T[0],{role:"user",content:`[EXAMPLE \u2014 illustrative only, not the real task]
1432
+ 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=i1(typeof t=="string"?t:"");xe&&(T=[T[0],{role:"user",content:`[EXAMPLE \u2014 illustrative only, not the real task]
1433
1433
  `+xe.user},{role:"assistant",content:xe.assistant+`
1434
- [END EXAMPLE \u2014 wait for the real user request below]`},...T.slice(1)])}if(tn(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(tn(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"?h0(P):null,te=eC(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(`
1435
- `),ye=wu(xe);ye&&(dt=!0,St=ye.slice(0,120),L(`${m.yellow} \u26A1 Root cause in briefing: ${St} \u2014 fix phase active from start (read budget: 3)${m.reset}`))}if(!dt&&!Wt&&/\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)&&(Wt=!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&&!Q1(P)&&(we=VR(),we)){Cs=XR(P)?.id||"coding";let ye=T0(P);if(Re=ye?"implement":"plan",on=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(${on||"default"}) \u2192 verify ${m.yellow}[plan skipped: direct file task]${m.reset}`:`${m.dim} \u21B3 Phase routing: plan(${on||"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 ${on||"default model"} (category: ${Cs})${m.reset}`:`${m.cyan} \u26A1 Phase routing enabled \u2014 plan phase with ${on||"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(),cw=new jR(S1),lw=Ar,et=n.skillLoop?10:1,uw=3*et,dw=5*et,td=qu,fw=5*et,pw=8*et,hw=D0,mw=(we?6:4)*et,gw=(we?10:7)*et,ja=ya,yw=(we?5:3)*et,Lr=(we?8:5)*et,ww=q0,bw=(we?4:3)*et,$w=(we?6:4)*et,_w=3*et,xw=4*et,Ps=yn,kw=(we?6:4)*et,vw=(we?10:8)*et,Ls=(we?12:10)*et,Sw=25,Un=0,Ew=10*et,Tw=15*et,Wn=0,nd=5*et,Hn=0,Rw=2*et,Cw=3,Da=0,Eo=10,Aw=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}
1436
- `);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,Tt=n.maxIterations||(we?_s(Re):Su);rd&&(Tt=Math.min(Tt,4),L(`${m.dim} \u21B3 Analysis-only prompt detected \u2014 iter cap=${Tt}${m.reset}`));let qa=0,id=3,Fa=!1,jr=0,Ba=!1;e:for(;;){for(Fa=!1,Ke=0;Ke<Tt&&!ma()?.aborted;Ke++){ha(M,T);{let b=ht(),y=tn(T,b),G=Y===0?65:78;if(y.percentage>=G){if(Z.size>0||we&&Re!=="plan"){let K=WR(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(tn(T,b).percentage)}%]${m.reset}`),Wt&&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(Pt&&!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}`)}Pt||(vr=0);let ye=!0;Y>0&&d1();let Ce=null;if(l&&l.isActive())l._paused&&l.resume();else if(!l){let b,y=f1();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 p1,Lt,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>=k0&&!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!==sn()?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),It="",bn=null;try{let b=L0(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=>C0.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}),Lt=await p0(T,U,{signal:K.signal,...on?{model:on}:{},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||(It+=j,process.stdout.isTTY?bn||(bn=setTimeout(()=>{It&&ot&&ot.push(It),It="",bn=null},50)):(ot.push(It),It=""),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),It&&ot&&(ot.push(It),It=""),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 _C();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}`),Y1){let W=Ta.fast?.[mo()];W&&W!==sn()&&(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=sn?sn():"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),f0(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:
1434
+ [END EXAMPLE \u2014 wait for the real user request below]`},...T.slice(1)])}if(tn(T,ht()).percentage>=65){let{messages:ye,tokensRemoved:Ce}=mn(T,ht());Ce>0&&(T=ye,console.log(`${m.dim} [pre-flight compress \u2014 ${Ce} tokens freed, now ${Math.round(tn(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"?y0(P):null,te=oC(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(!ft){let xe=M.filter(Ce=>Ce.role==="user"||Ce.role==="tool").map(Ce=>typeof Ce.content=="string"?Ce.content:"").join(`
1435
+ `),ye=xu(xe);ye&&(ft=!0,St=ye.slice(0,120),L(`${m.yellow} \u26A1 Root cause in briefing: ${St} \u2014 fix phase active from start (read budget: 3)${m.reset}`))}if(!ft&&!Yt&&/\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)&&(Yt=!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&&!sC(P)&&(we=e1(),we)){Cs=QR(P)?.id||"coding";let ye=A0(P);if(Re=ye?"implement":"plan",on=Tu(Re,Cs),Aa=0,bo=0,Bn=0,Er=null,ks.clear(),process.stdout.isTTY&&console.log(ye?`${m.dim} \u21B3 Phase routing: implement(${on||"default"}) \u2192 verify ${m.yellow}[plan skipped: direct file task]${m.reset}`:`${m.dim} \u21B3 Phase routing: plan(${on||"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 ${on||"default model"} (category: ${Cs})${m.reset}`:`${m.cyan} \u26A1 Phase routing enabled \u2014 plan phase with ${on||"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,od=0,ja=0,Ms=0,Pe=Date.now(),dw=new BR(C1),fw=Ar,et=n.skillLoop?10:1,pw=3*et,hw=5*et,rd=Wu,mw=5*et,gw=8*et,yw=B0,ww=(we?6:4)*et,bw=(we?10:7)*et,Da=wa,$w=(we?5:3)*et,Lr=(we?8:5)*et,_w=U0,xw=(we?4:3)*et,kw=(we?6:4)*et,vw=3*et,Sw=4*et,Ps=wn,Ew=(we?6:4)*et,Tw=(we?10:8)*et,Ls=(we?12:10)*et,Rw=25,Wn=0,Cw=10*et,Aw=15*et,Hn=0,id=5*et,Yn=0,Ow=2*et,Nw=3,qa=0,Eo=10,Mw=16,ad=n.skillLoop?999:o.investigationCap,cd=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}
1436
+ `);ye()&&Date.now()<Ce;)await new Promise(Xe=>setTimeout(Xe,500).unref()),ma(M,T)}ma(M,T),M.length>0&&Ne(M)}},Cn=typeof t=="string"?t.trim():"",ld=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,Tt=n.maxIterations||(we?_s(Re):Cu);ld&&(Tt=Math.min(Tt,4),L(`${m.dim} \u21B3 Analysis-only prompt detected \u2014 iter cap=${Tt}${m.reset}`));let Fa=0,ud=3,Ba=!1,jr=0,Ua=!1;e:for(;;){for(Ba=!1,Ke=0;Ke<Tt&&!ga()?.aborted;Ke++){ma(M,T);{let b=ht(),y=tn(T,b),G=Y===0?65:78;if(y.percentage>=G){if(Z.size>0||we&&Re!=="plan"){let K=zR(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}=mn(T,b,Y===0);if(z>0&&(T=U,z>50&&console.log(`${m.dim} [auto-compressed \u2014 ~${z} tokens freed, now ${Math.round(tn(T,b).percentage)}%]${m.reset}`),Yt&&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(Pt&&!ft&&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}`)}Pt||(vr=0);let ye=!0;Y>0&&m1();let Ce=null;if(l&&l.isActive())l._paused&&l.resume();else if(!l){let b,y=g1();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?`${pu()} (step ${Y+1})`:pu();let{getPendingJobSummary:G}=to(),U=G();U&&(b+=` [${U}]`),Ce=new ho(b),Ce.start()}let Xe=!0,ct="",An=!1,rt=new y1,It,Wa=Date.now(),Dr=!1,Ha=new AbortController,Ya=setInterval(()=>{let b=Date.now()-Wa;if(b>=$u)rt._clearCursorLine(),L(`${m.yellow} \u26A0 Stream stale for ${Math.round(b/1e3)}s \u2014 aborting and retrying${m.reset}`),Ha.abort();else if(b>=E0&&!Dr){Dr=!0,rt._clearCursorLine();let y=Ra.fast?.[mo()],G=be>0?` (retry ${be+1}/${pa})`:"",U=Math.round(($u-b)/1e3);L(`${m.yellow} \u26A0 No tokens received for ${Math.round(b/1e3)}s \u2014 waiting...${G}${m.reset}`),y&&y!==sn()?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);Ya.unref?.();let jt="",rn=null;try{let b=D0(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=>N0.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=ga(),K=new AbortController;z&&z.addEventListener("abort",()=>K.abort(),{once:!0}),Ha.signal.addEventListener("abort",()=>K.abort(),{once:!0}),It=await g0(T,U,{signal:K.signal,...on?{model:on}:{},onThinkingToken:()=>{Wa=Date.now(),Dr=!1,bn?.onThinkingToken&&bn.onThinkingToken()},onToken:j=>{if(Wa=Date.now(),Dr=!1,bn?.onToken){bn.onToken(j),ct+=j;return}if(ct+=j,!An&&ct.length>400&&ct.length%250<j.length+1){let ce=Ru(ct,3);ce.truncated&&(An=!0,rt._clearCursorLine?.(),L(`${m.yellow} \u26A0 LLM stream loop detected (${ce.repeatCount}\xD7 repeated) \u2014 suppressing display${m.reset}`))}An||(jt+=j,process.stdout.isTTY?rn||(rn=setTimeout(()=>{jt&&rt&&rt.push(jt),jt="",rn=null},50),rn.unref?.()):(rt.push(jt),jt=""),Xe&&(l&&!l._paused?l.pause():Ce&&Ce.stop(),ye||(ye=!0),rt.startCursor(),Xe=!1))}})}catch(b){if(clearInterval(Ya),rn&&(clearTimeout(rn),rn=null),jt&&rt&&(rt.push(jt),jt=""),l&&!l._paused&&l.pause(),Ce&&Ce.stop(),rt.stopCursor(),Ha.signal.aborted&&!ga()?.aborted){if(be++,be>pa){if(ve<1){ve++,po("Stale retries exhausted \u2014 last-resort force-compress...",m.yellow);let ce=ht(),{messages:O,tokensRemoved:W}=mn(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 SC();if(j.action==="quit"){u(null),je(Y,re,Z,Se,Pe),Ne(M);break}j.action==="switch"&&(hu(`${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}/${pa} \u2014 force-compressing before retry...`,m.yellow);let j=ht(),{messages:ce,tokensRemoved:O}=mn(T,j,!0);if(T=ce,O>0&&O>50&&L(`${m.dim} [force-compressed \u2014 ~${O} tokens freed]${m.reset}`),X1){let W=Ra.fast?.[mo()];W&&W!==sn()&&(hu(`${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}/${pa} \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=sn?sn():"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}`),hu(ce),m0(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}=mn(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}=pn(),O=pn().estimateMessagesTokens(j),W=pn().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:
1437
1437
  `+H.map(I=>`- ${I}`).join(`
1438
1438
  `));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(`
1439
1439
  `).slice(0,8).join(`
1440
1440
  `).slice(0,500));if(de.length>0&&R.push(`Tool results summary:
1441
1441
  `+de.map(I=>`- ${I}`).join(`
1442
- `)),Z.size>0){let I=[...Z].map(_e=>_e.split("/").slice(-2).join("/")).join(", ");R.unshift(`Already modified: ${I} \u2014 use edit_file to add missing pieces only, DO NOT use write_file on these files.`)}if(Se.size>0){let I=[...Se].map(_e=>_e.split("/").slice(-2).join("/")).join(", ");R.push(`Files already investigated: ${I}`)}let $e=require("os").tmpdir()+"/nex-session-checkpoint.json";try{require("fs").writeFileSync($e,JSON.stringify({filesWritten:[...Z].map(I=>I.split("/").slice(-2).join("/")),filesRead:[...Se].map(I=>I.split("/").slice(-2).join("/")),isCreationTask:Wt,wipeNumber:kr+1,timestamp:Date.now()},null,2)),R.push(`Session checkpoint: ${$e} \u2014 read it for exact file list`)}catch{}let se=0;{let _e=((typeof K?.content=="string"?K.content:Array.isArray(K?.content)?K.content.filter(nt=>nt.type==="text").map(nt=>nt.text).join(" "):"").match(/(?:^|\s)([\w./\-]+\.(?:js|ts|jsx|tsx|py|json|yml|yaml|sh|css|scss|html|md|go|rs|java|rb|php))/gm)||[]).map(nt=>nt.trim()).filter(Boolean),Te=[...Z],We=_e.filter(nt=>!Te.some(Br=>Br.endsWith(nt)||nt.endsWith(Br.split("/").pop())));se=We.length;let Ve=[...M].reverse().find(nt=>nt.role==="tool"&&typeof nt.content=="string"&&!nt.content.startsWith("BLOCKED:")&&nt.content.length>5),jt={completed:Te.map(nt=>nt.split("/").slice(-2).join("/")),pending:We.length>0?We:Te.length===0?["(task files not yet identified)"]:[],lastEdit:Ve?Ve.content.trim().slice(0,120):null};(jt.completed.length>0||jt.pending.length>0)&&R.unshift(`Work manifest:
1443
- ${JSON.stringify(jt,null,2)}`)}if(R.length>0){let I={role:"user",content:`[SYSTEM: Findings from investigation before context wipe]
1442
+ `)),Z.size>0){let I=[...Z].map(_e=>_e.split("/").slice(-2).join("/")).join(", ");R.unshift(`Already modified: ${I} \u2014 use edit_file to add missing pieces only, DO NOT use write_file on these files.`)}if(Se.size>0){let I=[...Se].map(_e=>_e.split("/").slice(-2).join("/")).join(", ");R.push(`Files already investigated: ${I}`)}let $e=require("os").tmpdir()+"/nex-session-checkpoint.json";try{require("fs").writeFileSync($e,JSON.stringify({filesWritten:[...Z].map(I=>I.split("/").slice(-2).join("/")),filesRead:[...Se].map(I=>I.split("/").slice(-2).join("/")),isCreationTask:Yt,wipeNumber:kr+1,timestamp:Date.now()},null,2)),R.push(`Session checkpoint: ${$e} \u2014 read it for exact file list`)}catch{}let se=0;{let _e=((typeof K?.content=="string"?K.content:Array.isArray(K?.content)?K.content.filter(nt=>nt.type==="text").map(nt=>nt.text).join(" "):"").match(/(?:^|\s)([\w./\-]+\.(?:js|ts|jsx|tsx|py|json|yml|yaml|sh|css|scss|html|md|go|rs|java|rb|php))/gm)||[]).map(nt=>nt.trim()).filter(Boolean),Te=[...Z],We=_e.filter(nt=>!Te.some(Br=>Br.endsWith(nt)||nt.endsWith(Br.split("/").pop())));se=We.length;let Ve=[...M].reverse().find(nt=>nt.role==="tool"&&typeof nt.content=="string"&&!nt.content.startsWith("BLOCKED:")&&nt.content.length>5),qt={completed:Te.map(nt=>nt.split("/").slice(-2).join("/")),pending:We.length>0?We:Te.length===0?["(task files not yet identified)"]:[],lastEdit:Ve?Ve.content.trim().slice(0,120):null};(qt.completed.length>0||qt.pending.length>0)&&R.unshift(`Work manifest:
1443
+ ${JSON.stringify(qt,null,2)}`)}if(R.length>0){let I={role:"user",content:`[SYSTEM: Findings from investigation before context wipe]
1444
1444
  ${R.join(`
1445
1445
  `)}
1446
1446
  Continue implementing the fixes based on these findings.`};j.push(I)}if(kr>=3){let I=Z.size>0?`
1447
- 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,Ut=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);Bt.clear(),Rs.clear(),Wt&&Gt>0&&(Yt=!0,L(`${m.cyan} \u26A1 Post-wipe creation guard: cap pre-fired (${Gt} 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?`
1447
+ 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),Iu=!0,ka=Z.size,va=!1,Ht=0,he=0;for(let[I,_e]of wn){let Te=_e?.count??_e??0;ku(wn,I,Te>=2?Te:1)}for(let[I]of Tn)gn(wn,I)<2&&Tn.delete(I);Wt.clear(),Rs.clear(),Yt&&Kt>0&&(zt=!0,L(`${m.cyan} \u26A1 Post-wipe creation guard: cap pre-fired (${Kt} edits already made)${m.reset}`));for(let[I]of wa)ku(wa,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=[...wn.entries()].filter(([,Ve])=>Ve>=Ls).map(([Ve])=>Ve.split("/").slice(-1)[0]),_e=I.length>0?`
1448
1448
 
1449
- Files already at read cap \u2014 use grep_search instead: ${I.join(", ")}`:"",We={role:"user",content:Pt&&!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.
1450
- 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),It&&ot&&(ot.push(It),It=""),at&&ot.flush(),ee=0,be=0,Lt&&Lt.usage){let b=Lt.usage.prompt_tokens||0,y=Lt.usage.completion_tokens||0;g0(mo(),sn(),b,y),d+=b+y,l&&l.setStats({tokens:d})}else if(Lt&&!Lt.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=w0(b),G=w0(Lt.content||at||"");g0(mo(),sn(),y,G),d+=y+G,l&&l.setStats({tokens:d})}let{content:cd,tool_calls:Is}=Lt,Rt=Is,Ha=!1;if(Array.isArray(Is)&&Is.length>0){let b=Is.filter(y=>y?.function?.name==="ask_user");b.length>0&&(Rt=[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=O1(ld||""),_t=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}`),Array.isArray(Rt)&&Rt.length>0&&JR(_t||"")&&(L(`${m.yellow} \u26A0 Assistant asked the user a direct question in text \u2014 dropping tool calls and waiting for user input${m.reset}`),Rt=[]);let To={role:"assistant",content:_t||""};if(Rt&&Rt.length>0&&(To.tool_calls=Rt),M.push(To),T.push(To),rd&&!da(_t||at||"")&&Z.size===0&&Ms===0){L(`${m.green} \u2713 Analysis-only early exit: ${(_t||"").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&&_t&&Rt&&Rt.length>0){let b=wu(_t);if(b){dt=!0,St=b.slice(0,120),Ht=0,Yt=!1,nn=0,L(`${m.yellow} \u26A1 Root cause in model analysis: ${St} \u2014 fix phase (read budget: 3)${m.reset}`);let y={role:"user",content:`[SYSTEM] Root cause identified: ${St}. Read only the file that needs fixing, then edit it. Do not read other files.`};M.push(y),T.push(y)}}if(!Rt||Rt.length===0){let b=(_t||"").trim().length>0||at.trim().length>0,y=!1;if(Pt&&b&&(pa>=2?L(`${m.yellow} \u26A0 SSH permanently blocked after ${pa} storm warnings \u2014 no further SSH calls allowed${m.reset}`):(Pt=!1,Ut=Eo-4,y=!0)),y&&b){let K=(_t||"").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((_t||"").slice(0,600)))if(Nu&&vs<=0||Pt){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=(_t||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(_t||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=Z1(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,Tt=_s("implement");continue}}if(we&&b){let K=(_t||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=F0(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}
1451
- `),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,Tt=_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,Tt=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:
1449
+ Files already at read cap \u2014 use grep_search instead: ${I.join(", ")}`:"",We={role:"user",content:Pt&&!ft?"[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>wu){console.log(`${m.red} Rate limit: max retries (${wu}) 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}/${wu})`);K.start(),await new Promise(j=>setTimeout(j,z)),K.stop();continue}let G=process.env.NEX_PHASE_ROUTING!=="0"&&(()=>{try{return lt().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>bu){console.log(`${m.red} Network error: max retries (${bu}) exceeded. Check your connection and try again.
1450
+ 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}/${bu}). 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(Ya),F=0,ee=0,Xe&&(l&&!l._paused&&l.pause(),Ce&&Ce.stop()),rn&&(clearTimeout(rn),rn=null),jt&&rt&&(rt.push(jt),jt=""),ct&&rt.flush(),ee=0,be=0,It&&It.usage){let b=It.usage.prompt_tokens||0,y=It.usage.completion_tokens||0;b0(mo(),sn(),b,y),d+=b+y,l&&l.setStats({tokens:d})}else if(It&&!It.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=_0(b),G=_0(It.content||ct||"");b0(mo(),sn(),y,G),d+=y+G,l&&l.setStats({tokens:d})}let{content:dd,tool_calls:Is}=It,Rt=Is,Ga=!1;if(Array.isArray(Is)&&Is.length>0){let b=Is.filter(y=>y?.function?.name==="ask_user");b.length>0&&(Rt=[b[0]],Ga=Is.length!==1,Ga&&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=Ru(dd||""),fd=qr.truncated?qr.text:dd;qr.truncated&&L(`${m.yellow} \u26A0 LLM output loop detected (${qr.repeatCount}\xD7 repeated paragraph) \u2014 response truncated${m.reset}`);let Fr=L1(fd||""),_t=Fr.truncated?Fr.text:fd;Fr.truncated&&L(`${m.yellow} \u26A0 LLM output loop detected (${Fr.repeatCount}\xD7 repeated window) \u2014 response truncated${m.reset}`),Array.isArray(Rt)&&Rt.length>0&&t1(_t||"")&&(L(`${m.yellow} \u26A0 Assistant asked the user a direct question in text \u2014 dropping tool calls and waiting for user input${m.reset}`),Rt=[]);let To={role:"assistant",content:_t||""};if(Rt&&Rt.length>0&&(To.tool_calls=Rt),M.push(To),T.push(To),ld&&!fa(_t||ct||"")&&Z.size===0&&Ms===0){L(`${m.green} \u2713 Analysis-only early exit: ${(_t||"").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(!ft&&_t&&Rt&&Rt.length>0){let b=xu(_t);if(b){ft=!0,St=b.slice(0,120),Gt=0,zt=!1,nn=0,L(`${m.yellow} \u26A1 Root cause in model analysis: ${St} \u2014 fix phase (read budget: 3)${m.reset}`);let y={role:"user",content:`[SYSTEM] Root cause identified: ${St}. Read only the file that needs fixing, then edit it. Do not read other files.`};M.push(y),T.push(y)}}if(!Rt||Rt.length===0){let b=(_t||"").trim().length>0||ct.trim().length>0,y=!1;if(Pt&&b&&(ha>=2?L(`${m.yellow} \u26A0 SSH permanently blocked after ${ha} storm warnings \u2014 no further SSH calls allowed${m.reset}`):(Pt=!1,Ht=Eo-4,y=!0)),y&&b){let K=(_t||"").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<Cu-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((_t||"").slice(0,600)))if(Iu&&vs<=0||Pt){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=(_t||ct||"").toLowerCase();if(/\b(i.ll stop|stop the|stopped|done with|complet|summar|conclud|no more|finish|end of|that.s all|final|wrapped up|no further|mindful of|reached.*limit|tool call limit|at this point|recommend keep)/.test(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&&!fa(_t||ct||"")&&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=nC(Er)?1:2;if(we&&Re==="plan"&&Bn>=z){L(`${m.cyan} \u21B3 Plan phase: ${Bn} consecutive blocks (last: ${Er||"unknown"}) \u2014 auto-advancing to implement${m.reset}`),Bn=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,Tt=_s("implement");continue}}if(we&&b){let K=(_t||ct||"").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=W0(K,wn).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}
1451
+ `),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,Tt=_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,Tt=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&&!fa(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:
1452
1452
  ${K.slice(0,400)}
1453
1453
 
1454
- Fix the identified issues. This is attempt ${bo}/3.`};Re="implement",on=ku("implement",Cs),M.push(R),T.push(R),Ke=0,Tt=_s("implement"),L(`${m.yellow} \u21B3 Verify \u2192 implement loop-back #${bo} (issues found)${m.reset}`);continue}if(!O&&(!j||$o===0)){if(_o<2){_o++;let R=[];$o===0&&R.push("run at least one verification tool"),j||R.push("end your report with PASS or FAIL");let H={role:"user",content:`[SYSTEM] Verification is incomplete: ${R.join(" and ")}. Do not stop yet. Re-read the modified files and/or run tests or linters, then respond with PASS or FAIL.`};M.push(H),T.push(H),L(`${m.yellow} \u26A0 Verify phase incomplete \u2014 nudging for evidence (${_o}/2)${m.reset}`);continue}L(`${m.yellow} \u26A0 Verify phase completion accepted without full markers after ${_o} nudges${m.reset}`)}if(L(`${m.green} \u2713 Verification phase complete${O?" (loop-back exhausted)":" (PASS)"}${m.reset}`),!O){je(Y,re,Z,Se,Pe),Ne(M),yr(M);break e}}}if(Tr()&&b&&Y===0)if(ba++,ba>2)L(`${m.yellow} \u26A0 Plan accepted despite no file reads (rejection loop cap reached)${m.reset}`);else{let K={role:"user",content:`[SYSTEM] You wrote a plan without reading any files. This plan may be based on incorrect assumptions (wrong database type, wrong file structure, etc.).
1454
+ Fix the identified issues. This is attempt ${bo}/3.`};Re="implement",on=Tu("implement",Cs),M.push(R),T.push(R),Ke=0,Tt=_s("implement"),L(`${m.yellow} \u21B3 Verify \u2192 implement loop-back #${bo} (issues found)${m.reset}`);continue}if(!O&&(!j||$o===0)){if(_o<2){_o++;let R=[];$o===0&&R.push("run at least one verification tool"),j||R.push("end your report with PASS or FAIL");let H={role:"user",content:`[SYSTEM] Verification is incomplete: ${R.join(" and ")}. Do not stop yet. Re-read the modified files and/or run tests or linters, then respond with PASS or FAIL.`};M.push(H),T.push(H),L(`${m.yellow} \u26A0 Verify phase incomplete \u2014 nudging for evidence (${_o}/2)${m.reset}`);continue}L(`${m.yellow} \u26A0 Verify phase completion accepted without full markers after ${_o} nudges${m.reset}`)}if(L(`${m.green} \u2713 Verification phase complete${O?" (loop-back exhausted)":" (PASS)"}${m.reset}`),!O){je(Y,re,Z,Se,Pe),Ne(M),yr(M);break e}}}if(Tr()&&b&&Y===0)if($a++,$a>2)L(`${m.yellow} \u26A0 Plan accepted despite no file reads (rejection loop cap reached)${m.reset}`);else{let K={role:"user",content:`[SYSTEM] You wrote a plan without reading any files. This plan may be based on incorrect assumptions (wrong database type, wrong file structure, etc.).
1455
1455
 
1456
- MANDATORY: Use read_file, glob, or grep to investigate the actual codebase first. Read at least the relevant module file and route file before writing the plan.`};M.push(K),T.push(K),L(`${m.yellow} \u26A0 Plan rejected (${ba}/2): no files read \u2014 forcing investigation${m.reset}`);continue}if(Tr()&&b){let K=(_t||at||"").trim();c1(K),G1(K);let j=l1(K);if(j.length>0){let ce=M.find(de=>de.role==="user"),O=typeof ce?.content=="string"?ce.content.slice(0,120):"Task";u1(O,j);let W=j.length===1?"step":"steps",R=!1;if(process.stdout.isTTY&&process.stdin.isTTY&&!process.env.JEST_WORKER_ID){let{approvePlan:de,startExecution:$e,setPlanMode:se}=ca();process.stdout.write(`
1456
+ MANDATORY: Use read_file, glob, or grep to investigate the actual codebase first. Read at least the relevant module file and route file before writing the plan.`};M.push(K),T.push(K),L(`${m.yellow} \u26A0 Plan rejected (${$a}/2): no files read \u2014 forcing investigation${m.reset}`);continue}if(Tr()&&b){let K=(_t||ct||"").trim();f1(K),V1(K);let j=p1(K);if(j.length>0){let ce=M.find(de=>de.role==="user"),O=typeof ce?.content=="string"?ce.content.slice(0,120):"Task";h1(O,j);let W=j.length===1?"step":"steps",R=!1;if(process.stdout.isTTY&&process.stdin.isTTY&&!process.env.JEST_WORKER_ID){let{approvePlan:de,startExecution:$e,setPlanMode:se}=la();process.stdout.write(`
1457
1457
  ${m.cyan}${m.bold}Plan ready${m.reset} ${m.dim}(${j.length} ${W})${m.reset} ${m.green}[A]${m.reset}${m.dim}pprove${m.reset} ${m.yellow}[E]${m.reset}${m.dim}dit${m.reset} ${m.red}[R]${m.reset}${m.dim}eject${m.reset} ${m.dim}[\u21B5 = approve]:${m.reset} `);let I=process.stdin.isRaw,_e=await new Promise(Te=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",We=>{try{process.stdin.setRawMode(I||!1)}catch{}let Ve=We.toString().toLowerCase()[0]||"\r";Te(Ve)})});if(process.stdout.write(`
1458
- `),_e==="r")console.log(`${m.red}Plan rejected.${m.reset} Ask follow-up questions to refine.`);else if(_e==="e")console.log(`${m.yellow}Type /plan edit to open in editor, or give feedback.${m.reset}`);else if(de()){$e(),se(!1),Cu(),console.log(`${m.green}${m.bold}Approved!${m.reset} Executing ${j.length} ${W}...`);let Te=`[PLAN APPROVED \u2014 EXECUTE NOW]
1458
+ `),_e==="r")console.log(`${m.red}Plan rejected.${m.reset} Ask follow-up questions to refine.`);else if(_e==="e")console.log(`${m.yellow}Type /plan edit to open in editor, or give feedback.${m.reset}`);else if(de()){$e(),se(!1),Mu(),console.log(`${m.green}${m.bold}Approved!${m.reset} Executing ${j.length} ${W}...`);let Te=`[PLAN APPROVED \u2014 EXECUTE NOW]
1459
1459
 
1460
1460
  Implement the following plan step by step. All tools are now available.
1461
1461
 
1462
1462
  ${K}`;M.push({role:"user",content:Te}),T.push({role:"user",content:Te}),R=!0}}else console.log(`
1463
- ${m.cyan}${m.bold}Plan ready${m.reset} ${m.dim}(${j.length} ${W} extracted).${m.reset} Type ${m.cyan}/plan approve${m.reset}${m.dim} to execute, or ${m.reset}${m.cyan}/plan edit${m.reset}${m.dim} to review.${m.reset}`);if(R){l&&(l.stop(),l=null),Ke--;continue}}else{let ce=!1;if(process.stdout.isTTY&&process.stdin.isTTY&&!process.env.JEST_WORKER_ID){let{approvePlan:W,startExecution:R,setPlanMode:H}=ca();process.stdout.write(`
1463
+ ${m.cyan}${m.bold}Plan ready${m.reset} ${m.dim}(${j.length} ${W} extracted).${m.reset} Type ${m.cyan}/plan approve${m.reset}${m.dim} to execute, or ${m.reset}${m.cyan}/plan edit${m.reset}${m.dim} to review.${m.reset}`);if(R){l&&(l.stop(),l=null),Ke--;continue}}else{let ce=!1;if(process.stdout.isTTY&&process.stdin.isTTY&&!process.env.JEST_WORKER_ID){let{approvePlan:W,startExecution:R,setPlanMode:H}=la();process.stdout.write(`
1464
1464
  ${m.cyan}${m.bold}Plan ready.${m.reset} ${m.green}[A]${m.reset}${m.dim}pprove${m.reset} ${m.red}[R]${m.reset}${m.dim}eject${m.reset} ${m.dim}[\u21B5 = approve]:${m.reset} `);let de=process.stdin.isRaw,$e=await new Promise(se=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",I=>{try{process.stdin.setRawMode(de||!1)}catch{}se(I.toString().toLowerCase()[0]||"\r")})});if(process.stdout.write(`
1465
- `),$e==="r")console.log(`${m.red}Plan rejected.${m.reset} Ask follow-up questions to refine.`);else if(W()){R(),H(!1),Cu(),console.log(`${m.green}${m.bold}Approved!${m.reset} Executing...`);let I=`[PLAN APPROVED \u2014 EXECUTE NOW]
1465
+ `),$e==="r")console.log(`${m.red}Plan rejected.${m.reset} Ask follow-up questions to refine.`);else if(W()){R(),H(!1),Mu(),console.log(`${m.green}${m.bold}Approved!${m.reset} Executing...`);let I=`[PLAN APPROVED \u2014 EXECUTE NOW]
1466
1466
 
1467
1467
  Implement the following plan step by step. All tools are now available.
1468
1468
 
1469
- ${getPlanContent()||Lt.content}`;M.push({role:"user",content:I}),T.push({role:"user",content:I}),ce=!0}}else console.log(`
1470
- ${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),Wt&&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(Wt&&!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(_t))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 p0(j,[],{}))?.content||"").trim();O&&(console.log(`
1471
- ${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 Rt){let y=b.function.name;re.set(y,(re.get(y)||0)+1)}if(Y>=30&&!E0){E0=!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(Rt.map(b=>z1(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=tn(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=Bt.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}`),Bt.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,jt=I-se||1,nt=We/jt>=.7&&We/Ve<.7,Br=H-R<=Sw;if(We>=Ve||!Br&&(We/Ve>=.7||We/jt>=.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=Bt.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?Bt.delete(y):Bt.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(T0(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 Ow=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>=Ow&&(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(Pt){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)Pt=!1,_a++,Ut=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 (${St}). 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 Nw=U1(M,["browser_open","browser_screenshot","ssh_exec","service_logs","remote_agent"]);if((X||C)&&!Nw&&he<3&&!Pt)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&&Yt&&Wt&&Gt>=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 Mw=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||Mw.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}:{},Pw=ke.some(b=>b.fnName==="ask_user"),fd=!Ro.skipSummaries&&!ye,Kt=null,js=null;if(fd&&!Pw){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?`
1472
- `:""}${b}`),yo=y,wo=Date.now(),Kt={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?`
1469
+ ${getPlanContent()||It.content}`;M.push({role:"user",content:I}),T.push({role:"user",content:I}),ce=!0}}else console.log(`
1470
+ ${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),Yt&&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(Yt&&!ju&&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){ju=!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&&fa(_t))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 g0(j,[],{}))?.content||"").trim();O&&(console.log(`
1471
+ ${O}`),M.push({role:"user",content:K},{role:"assistant",content:O}))}catch{}Ne(M),yr(M),await cd();return}Y++,Aa++,Y>=1&&(ye=!1);for(let b of Rt){let y=b.function.name;re.set(y,(re.get(y)||0)+1)}if(Y>=30&&!C0){C0=!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(Rt.map(b=>J1(b)));if(Ua){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=tn(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&&gn(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&&qa<70||y>=85&&qa<85||z){qa=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 za=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=gn(Ps,y),U=za.get(y)||0,z=G+U,K=ks.has(y),j=b.args?.line_start!=null,ce=Wt.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}`),Wt.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,qt=I-se||1,nt=We/qt>=.7&&We/Ve<.7,Br=H-R<=Rw;if(We>=Ve||!Br&&(We/Ve>=.7||We/qt>=.7)){let Xa=y.split("/").slice(-2).join("/"),yd=`${y}:${R}-${H}`,Ds=(Ca.get(yd)||0)+1;if(Ca.set(yd,Ds),L(nt?`${m.red} \u2716 Blocked superread: "${Xa}" 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: "${Xa}" 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: "${Xa}" lines ${R}-${H} \u2014 model ignored BLOCKED, injecting system warning${m.reset}`);let wd={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(wd),T.push(wd)}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=gn(Da,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=Wt.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?Wt.delete(y):Wt.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&&za.set(y,(za.get(y)||0)+1)}if(Fn>=3)for(let b of ke)b.canExecute&&(b.fnName!=="read_file"&&b.fnName!=="edit_file"||(L(`${m.red} \u2716 Blocked ${b.fnName} \u2014 ${Fn} consecutive file-not-found errors, must search first${m.reset}`),b.canExecute=!1,b.errorResult={role:"tool",content:`BLOCKED: ${Fn} 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=Fu(P),W=Fu(y);if(A0(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 pd=new Map;for(let b of ke){if(!b.canExecute||b.fnName!=="grep")continue;let y=b.args?.path;if(!y)continue;let G=pd.get(y)||0,U=gn(Da,y)+G,z=gn(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=gn(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&&pd.set(y,G+1)}let Pw=5,hd=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=hd.get(G)||0,z=gn(rd,G)+U;z>=Pw&&(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&&hd.set(G,U+1)}if(Pt){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&&xa<1)Pt=!1,xa++,Ht=Math.max(0,Eo-2),L(`${m.dim} [dual-block deadlock: SSH storm relaxed \u2014 allowing 1 SSH call (relax ${xa}/1)]${m.reset}`);else for(let U of b)U.canExecute=!1,U.errorResult={role:"tool",content:ft?`BLOCKED: ssh_exec denied \u2014 SSH paused (${Eo}+ calls). Root cause is known (${St}). 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 Lw=G1(M,["browser_open","browser_screenshot","ssh_exec","service_logs","remote_agent"]);if((X||C)&&!Lw&&he<3&&!Pt)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}=mn(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&&zt&&Yt&&Kt>=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(!va&&Z.size>ka){va=!0,vs=5,L(`${m.green} \u2713 Post-wipe progress detected (${Z.size-ka} 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 Iw=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||Iw.has(b.fnName))continue;let y=JSON.stringify(b.args||{}),G=`${b.fnName}|${y}`,U=gn(Pu,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(Pu,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}:{},jw=ke.some(b=>b.fnName==="ask_user"),md=!Ro.skipSummaries&&!ye,Dt=null,js=null;if(md&&!jw){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?`
1472
+ `:""}${b}`),yo=y,wo=Date.now(),Dt={start:Date.now(),frame:0,timer:null}}else if(!bn){let b=gr(ke,Y,!1);Su(b,yo,wo)||(process.stdout.write(`${Y>1?`
1473
1473
  `:""}${b}
1474
- `),yo=b,wo=Date.now())}}else fd&&(ye=!0,Ro.skipSpinner=!0);l&&l._paused&&l.resume(),Kt&&process.stdout.isTTY&&(Kt.timer=setInterval(()=>{Kt.frame++;let b=Math.round((Date.now()-Kt.start)/1e3),y=b>=1?` ${m.dim}[${b}s]${m.reset}`:"",G=`${gr(ke,Y,!1,Kt.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:Lw}=await J1(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(Kt){Kt.timer&&(clearInterval(Kt.timer),Kt.timer=null);let b=gr(ke,Y,!1);_u(b,yo,wo)||(js!==null?process.stdout.write(`\x1B[${js};1H\x1B[2K${b}
1474
+ `),yo=b,wo=Date.now())}}else md&&(ye=!0,Ro.skipSpinner=!0);l&&l._paused&&l.resume(),Dt&&process.stdout.isTTY&&(Dt.timer=setInterval(()=>{Dt.frame++;let b=Math.round((Date.now()-Dt.start)/1e3),y=b>=1?` ${m.dim}[${b}s]${m.reset}`:"",G=`${gr(ke,Y,!1,Dt.frame)}${y}`;js!==null?process.stdout.write(`\x1B[${js};1H\x1B[2K${G}`):process.stdout.write(`\r\x1B[2K${G}`)},120),Dt.timer.unref?.());let{results:tt,summaries:Dw}=await tC(ke,!0,{...Ro,skipSummaries:!0});if(Ga){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(Dt){Dt.timer&&(clearInterval(Dt.timer),Dt.timer=null);let b=gr(ke,Y,!1);Su(b,yo,wo)||(js!==null?process.stdout.write(`\x1B[${js};1H\x1B[2K${b}
1475
1475
  `):process.stdout.write(`\r\x1B[2K${b}
1476
- `),yo=b,wo=Date.now()),js=null,Kt=null}if(!Ro.skipSummaries){let b=Lw.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=cw.record(0,y,Se,Z);G&&E1(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(`
1477
- `)[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=Bt.get(y.args.path)||0;Bt.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)Bt.has(R)||(Bt.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){Bt.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(lw,y.args.path),W=y.args.path.split("/").slice(-2).join("/");if(O===uw){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>=dw){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)){Ht=0,Yt=!1,nn=0,Gt++;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(Ht++,Yt&&nn++,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}
1478
- 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&&aC(y)&&(xo=!1,ko=0);let R=o.postEditCap,H=we&&Re==="implement"?Math.min(sd,10):sd,de=dt?8:Ir?Gt>0?4:6:Wt?Gt>0?6:10:Gt>0?R:H,$e=6,se=!we&&Yt&&(dt&&nn>=$e||Wt&&Gt>=3&&nn>=$e||nn>=$e);if(wr<2&&!Yt&&Ht>=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}%), ${Ht} reads, 0 edits${m.reset}`);let jt={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(jt),T.push(jt)}}if(se&&O.includes(y.fnName)){let I=dt?`root cause already identified (${St})`:nn>=$e?`${Ht} consecutive reads without an edit`:`${Gt} 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 (${St}). Use edit_file to fix the issue \u2014 do not read more files.`:Wt?"BLOCKED: files already written \u2014 continue with write_file or edit_file to finish the remaining tasks. Do not read more files.":nn>=$e?`BLOCKED: You have read ${Ht} 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: ${Gt} 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(Ht>=de&&!Yt){if(Yt=!0,Ir&&(Ba=!0),L(`${m.yellow} \u26A0 Investigation cap: ${Ht} read-only calls without an edit \u2014 forcing implementation${m.reset}`),we&&Re==="plan"){let Te=[...T].reverse().find(jt=>jt.role==="assistant"),We=typeof Te?.content=="string"?Te.content:"",Ve=await $r("implement",We);Ve&&(M.push(Ve),T.push(Ve),Ke=0,Tt=_s("implement"))}let I;dt?I=`[SYSTEM] Root cause was already identified (${St}). 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.":Pt?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===fw){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>=pw){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"){Ut++;{let R=(tt[b]?.content??"").split(`
1479
- `).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&&!Pt){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(Ut>=Aw){L(`${m.red} \u2716 SSH storm abort: ${Ut} 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(Ut===Eo){{let R=ht(),{messages:H}=hn(T,R);T=H}Pt=!0,pa++,L(`${m.yellow} \u26A0 SSH storm warning (#${pa}): ${Ut} consecutive ssh_exec calls \u2014 blocking further SSH${m.reset}`);let W={role:"user",content:dt?`[SYSTEM WARNING] ${Ut} consecutive SSH calls. Root cause identified (${St}). Read the file that needs fixing, then edit it.`:`[SYSTEM WARNING] ${Ut} 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&&(Ut=0);if(y.fnName==="bash"&&y.canExecute){let R=(tt[b]?.content??"").split(`
1480
- `).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(`
1481
- `);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(hw,O);if(W===mw){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>=gw){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:yw)){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(`
1482
- `);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(ww,O);if(W===bw){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>=$w){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===xw){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(tn(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(tn(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===Ew){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>=Tw){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===kw){{let $e=ht();if(tn(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>=vw){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===Rw){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>=Cw){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:iC(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)+`
1483
- ...(truncated ${z-j} chars \u2014 per-message budget)`},y-=z-j)}}}for(let b of tt)M.push(b),T.push(b);let Iw=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 ZR(G)&&typeof tt[y]?.content=="string"&&!tt[y].content.startsWith("ERROR")&&!tt[y].content.startsWith("BLOCKED:")});if(Ts()&&!n.skillLoop&&Ba&&Iw){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,St=G.slice(0,120),Ht=0,Yt=!1,nn=0,L(`${m.yellow} \u26A1 Root cause detected: ${St} \u2014 fix phase (read budget: 3)${m.reset}`);let U={role:"user",content:`[SYSTEM] Root cause identified: ${St}. 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(tn(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(tn(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}
1484
- `),l&&(l.stop(),l=null),u(null),je(Y,re,Z,Se,Pe),Ne(M);break e}let pd=nC();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>=Tt){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],Tt=_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++,Tt=20,console.log(`${m.dim} \u2500\u2500 auto-extending (+20 turns, ext ${qa}/${id}) \u2500\u2500${m.reset}`);continue e}if(console.log(`
1485
- ${m.yellow}\u26A0 Max iterations reached.${m.reset}`),await R0(" Continue for 20 more turns?")){Tt=20;continue e}console.log(`${m.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${m.reset}`)}break e}await od()}H0.exports={processInput:vC,clearConversation:hC,getConversationLength:gC,getConversationMessages:yC,setConversationMessages:wC,setAbortSignalGetter:M1,setMaxIterations:N1,invalidateSystemPromptCache:Cu,clearToolFilterCache:B1,getCachedFilteredTools:L0,buildSystemPrompt:Du,splitSystemPrompt:pC,SYSTEM_PROMPT_DYNAMIC_BOUNDARY:ju,getProjectContextHash:I0,_inferVerificationCommands:Fu,_inferRelevantTests:Aa,_inferSymbolTargets:B0,_buildSymbolHintBlock:U0,buildUserContent:M0,_detectImageURLs:A0,_downloadImageURL:O0,_grabClipboardImage:N0,detectFrustration:P0,detectAndTruncateLoop:vu,injectMidRunNote:tC,resetSessionTracking:W0}});var ct=Q((VO,K0)=>{var{OllamaProvider:SC}=Jd(),{OpenAIProvider:EC}=tf(),{AnthropicProvider:TC}=rf(),{GeminiProvider:RC}=uf(),{LocalProvider:CC}=pf(),{checkBudget:AC}=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),G0={};for(let[t,e]of Object.entries(Hu))for(let n of Object.values(e))G0[n]=t;function Wu(t,e){let n=G0[t];return n&&Hu[n][e]||t}var ft={},Et=null,Qe=null,Mr=[];function zt(){if(Object.keys(ft).length>0)return;vo("ollama",new SC),vo("openai",new EC),vo("anthropic",new TC),vo("gemini",new RC),vo("local",new CC);let t=process.env.DEFAULT_PROVIDER||"ollama",e=process.env.DEFAULT_MODEL||null;ft[t]?(Et=t,Qe=e||ft[t].defaultModel):(Et="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 OC(t){return zt(),ft[t]||null}function Yu(){return zt(),ft[Et]||null}function NC(){return zt(),Et}function MC(){return zt(),Qe}function PC(){zt();let t=Yu();if(!t)return{id:Qe,name:Qe,provider:Et};let e=t.getModel(Qe);return e?{...e,provider:Et}:{id:Qe,name:Qe,provider:Et}}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 LC(t){zt();let{provider:e,model:n}=Gu(t);if(e){let s=ft[e];return s&&(s.getModel(n)||e==="local"||e==="ollama")?(Et=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 Et=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 IC(){zt();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 jC(){return zt(),Object.entries(ft).map(([t,e])=>({provider:t,configured:e.isConfigured(),models:Object.values(e.getModels()).map(n=>({...n,active:t===Et&&n.id===Qe}))}))}function DC(){zt();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 qC(t){Mr=Array.isArray(t)?t:[]}function FC(){return[...Mr]}function Y0(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 z0(t){let e=[Et,...Mr.filter(r=>r!==Et)],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=AC(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}]
1486
- `),await t(a,i,l)}catch(u){if(n=u,!Y0(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}]
1487
- `),await t(a,i,d)}catch(f){if(n=f,!Y0(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 BC(t,e,n={}){zt();let o=n.model,s=o?(()=>{let{model:i}=Gu(o);return i||o})():void 0,r=s!==o?{...n,model:s}:n;return z0((i,a,c)=>i.stream(t,e,{model:c,signal:r.signal,...r}))}async function UC(t,e,n={}){if(zt(),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 z0(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 WC(){zt();let t=[];for(let[e,n]of Object.entries(ft))n.isConfigured()&&t.push({name:e,models:Object.values(n.getModels())});return t}function HC(){for(let t of Object.keys(ft))delete ft[t];Et=null,Qe=null,Mr=[]}K0.exports={registerProvider:vo,getProvider:OC,getActiveProvider:Yu,getActiveProviderName:NC,getActiveModelId:MC,getActiveModel:PC,setActiveModel:LC,getModelNames:IC,parseModelSpec:Gu,listProviders:jC,listAllModels:DC,callStream:BC,callChat:UC,getConfiguredProviders:WC,setFallbackChain:qC,getFallbackChain:FC,resolveModelForProvider:Wu,MODEL_EQUIVALENTS:Hu,OLLAMA_FALLBACK_MODELS:Uu,_reset:HC}});var{C:D}=rt(),YC=ct(),{TOOL_DEFINITIONS:X0}=zs(),{saveRoutingConfig:GC}=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 zC(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 Z0(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 KC(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 XC(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 V0(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 J0(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=>zC(r,i))}function VC(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=>J0(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=>J0(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"&&V0(t.command)&&/authenticateuser|src\/api\.js/i.test(t.command)?!0:VC(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"?V0(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"?Z0(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}],Q0=[{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"?Z0(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"?KC(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"?XC(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,...Q0],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 JC(){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=JC(),ZC=["minimax-m2.7:cloud","qwen3-coder:480b","devstral-2:123b"],ew=(()=>{let t=Zu.slice(0,3);return t.length>=3?t:ZC})(),QC=14,Na={producedToolCall:.2,correctTool:.35,validArgs:.3,schemaCompliant:.15},eA="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:eA},{role:"user",content:t.prompt}],s=Date.now();try{let r=await YC.callChat(o,X0,{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=X0.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 tw={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=>tw[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 nw(t){return sw(t)}function sw(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=>tw[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 ow(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(`
1476
+ `),yo=b,wo=Date.now()),js=null,Dt=null}if(!Ro.skipSummaries){let b=Dw.filter((U,z)=>!(ke[z]&&ke[z].fnName==="ask_user"));for(let U of b)Su(U,Ou,Nu)||(console.log(U),Ou=U,Nu=Date.now());let y=ke.filter(U=>U&&U.fnName!=="ask_user").map(U=>U.fnName),G=dw.record(0,y,Se,Z);G&&A1(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:"))&&(Hn++,Hn>=id)){L(`${m.red} \u2716 Loop abort: ${Hn} 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 Ka=!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(`
1477
+ `)[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=Wt.get(y.args.path)||0;Wt.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)Wt.has(R)||(Wt.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(Fn++,Fn>=2){L(`${m.yellow} \u26A0 File-not-found streak: ${Fn} consecutive misses \u2014 forcing search${m.reset}`);let O={role:"user",content:`[SYSTEM] ${Fn} 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")&&(Fn=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){Wt.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(fw,y.args.path),W=y.args.path.split("/").slice(-2).join("/");if(O===pw){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>=hw){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,Ka=!0)}if(z&&y.canExecute&&we&&(Bn=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)){Gt=0,zt=!1,nn=0,Kt++;let I=y.args?.path||y.args?.file_path;I&&(y.fnName==="write_file"?(ks.add(I),wn.delete(I),Tn.delete(I),Os.delete(I)):(ks.delete(I),ku(wn,I,1),Tn.delete(I),Os.add(I)))}else if(O.includes(y.fnName)){if(Gt++,zt&&nn++,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}
1478
+ 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++,Ka=!0)}we&&Re==="verify"&&$o++,z&&dC(y)&&(xo=!1,ko=0);let R=o.postEditCap,H=we&&Re==="implement"?Math.min(ad,10):ad,de=ft?8:Ir?Kt>0?4:6:Yt?Kt>0?6:10:Kt>0?R:H,$e=6,se=!we&&zt&&(ft&&nn>=$e||Yt&&Kt>=3&&nn>=$e||nn>=$e);if(wr<2&&!zt&&Gt>=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}%), ${Gt} reads, 0 edits${m.reset}`);let qt={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(qt),T.push(qt)}}if(se&&O.includes(y.fnName)){let I=ft?`root cause already identified (${St})`:nn>=$e?`${Gt} consecutive reads without an edit`:`${Kt} 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:ft?`BLOCKED: root cause already identified (${St}). Use edit_file to fix the issue \u2014 do not read more files.`:Yt?"BLOCKED: files already written \u2014 continue with write_file or edit_file to finish the remaining tasks. Do not read more files.":nn>=$e?`BLOCKED: You have read ${Gt} files without making any edits. Stop investigating and either implement a fix with edit_file/write_file, or write your diagnosis as text output. Do not read more files.`:`BLOCKED: ${Kt} file edit(s) already made and post-edit investigation cap reached. The fix is in place. Do not read more files \u2014 proceed with the task.`,tool_call_id:y.callId}}else if(Gt>=de&&!zt){if(zt=!0,Ir&&(Ua=!0),L(`${m.yellow} \u26A0 Investigation cap: ${Gt} read-only calls without an edit \u2014 forcing implementation${m.reset}`),we&&Re==="plan"){let Te=[...T].reverse().find(qt=>qt.role==="assistant"),We=typeof Te?.content=="string"?Te.content:"",Ve=await $r("implement",We);Ve&&(M.push(Ve),T.push(Ve),Ke=0,Tt=_s("implement"))}let I;ft?I=`[SYSTEM] Root cause was already identified (${St}). 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.":Pt?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(rd,O);if(W===mw){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>=gw){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"){Ht++;{let R=(tt[b]?.content??"").split(`
1479
+ `).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===Sa?Ss++:(Sa=R,Ss=1),Ss===3&&!Pt){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 Sa="",Ss=0}if(Ht>=Mw){L(`${m.red} \u2716 SSH storm abort: ${Ht} 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(Ht===Eo){{let R=ht(),{messages:H}=mn(T,R);T=H}Pt=!0,ha++,L(`${m.yellow} \u26A0 SSH storm warning (#${ha}): ${Ht} consecutive ssh_exec calls \u2014 blocking further SSH${m.reset}`);let W={role:"user",content:ft?`[SYSTEM WARNING] ${Ht} consecutive SSH calls. Root cause identified (${St}). Read the file that needs fixing, then edit it.`:`[SYSTEM WARNING] ${Ht} 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&&(Ht=0);if(y.fnName==="bash"&&y.canExecute){let R=(tt[b]?.content??"").split(`
1480
+ `).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===Ea?Es++:(Ea=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 Ea="",Es=0}if(y.fnName==="bash"&&y.canExecute&&!vu&&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"))){vu=!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(vu&&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(`
1481
+ `);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(ja++,ja===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&&(ja=0)}if(z&&y.fnName==="grep"&&y.args&&y.args.pattern){let O=`${y.args.pattern}|${y.args.path||""}`,W=xs(yw,O);if(W===ww){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>=bw){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(Da,y.args.path),H=gn(Ps,y.args.path)>=1;if(R===(H?1:$w)){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(`
1482
+ `);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(_w,O);if(W===xw){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>=kw){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();ba.has(de)||ba.set(de,new Set);let $e=ba.get(de);if($e.add(O),$e.size===Sw){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===vw){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(tn(T,W).percentage>=60){let{messages:H,tokensRemoved:de}=mn(T,W);de>0&&(T=H,console.log(`${m.dim} [pre-stop-compress \u2014 ~${de} tokens freed before STOP injection, now ${Math.round(tn(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(Hn++,Hn>=id){L(`${m.red} \u2716 Loop abort: ${Hn} 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 Hn=0;if(z)Wn=0,Ba=!0;else if(Wn++,Wn===Cw){L(`${m.yellow} \u26A0 Loop warning: ${Wn} consecutive tool errors \u2014 possible stuck loop${m.reset}`);let O={role:"user",content:`[SYSTEM WARNING] ${Wn} consecutive errors. Stuck loop \u2014 try fundamentally different approach or declare done.`};M.push(O),T.push(O)}else if(Wn>=Aw){L(`${m.red} \u2716 Loop abort: ${Wn} 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===Ew){{let $e=ht();if(tn(T,$e).percentage>=60){let{messages:I}=mn(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>=Tw){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(Yn++,Yn===Ow){L(`${m.yellow} \u26A0 Swarm warning: all sub-agents hit iteration limit ${Yn}\xD7 in a row${m.reset}`);let R={role:"user",content:`[SYSTEM WARNING] Sub-agents truncated ${Yn}\xD7 in a row. Stop spawning \u2014 try different approach or report findings.`};M.push(R),T.push(R)}else if(Yn>=Nw){console.log(`${m.red} \u2716 Swarm abort: all sub-agents hit iteration limit ${Yn}\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&&(Yn=0)}}if(Ka&&xo&&!(we&&Re==="verify")){let b=await Hu(Z),y=await Oa(Z),G={role:"user",content:uC(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)+`
1483
+ ...(truncated ${z-j} chars \u2014 per-message budget)`},y-=z-j)}}}for(let b of tt)M.push(b),T.push(b);let qw=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 n1(G)&&typeof tt[y]?.content=="string"&&!tt[y].content.startsWith("ERROR")&&!tt[y].content.startsWith("BLOCKED:")});if(Ts()&&!n.skillLoop&&Ua&&qw){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(ma(M,T),!ft)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=xu(y.content);if(G){ft=!0,St=G.slice(0,120),Gt=0,zt=!1,nn=0,L(`${m.yellow} \u26A1 Root cause detected: ${St} \u2014 fix phase (read budget: 3)${m.reset}`);let U={role:"user",content:`[SYSTEM] Root cause identified: ${St}. 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(tn(T,b).percentage>=78){let{messages:G,tokensRemoved:U}=mn(T,b);U>0&&(T=G,console.log(`${m.dim} [auto-compressed \u2014 ~${U} tokens freed, now ${Math.round(tn(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&&(od=Z.size),Ns++),Ns>=9&&Y>=4&&Z.size===od)){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}
1484
+ `),l&&(l.stop(),l=null),u(null),je(Y,re,Z,Se,Pe),Ne(M);break e}let gd=iC();if(gd){let b={role:"user",content:`[User note mid-run]: ${gd}`};M.push(b),T.push(b),console.log(`${m.cyan} \u270E Context added${m.reset}`)}}if(Ke>=Tt){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(rt=>rt.role==="assistant"),ct=typeof Xe?.content=="string"?Xe.content:"",An=await $r("implement",ct);if(An){M.push(An),T=[{role:"system",content:await Uu()},...M],Tt=_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}=lt();if(xe()==="ollama"&&Fa<ud){if(Z.size===0&&!Ba){console.log(`${m.yellow} \u26A0 Max iterations reached with no progress. Stopping.${m.reset}`);break e}Fa++,Tt=20,console.log(`${m.dim} \u2500\u2500 auto-extending (+20 turns, ext ${Fa}/${ud}) \u2500\u2500${m.reset}`);continue e}if(console.log(`
1485
+ ${m.yellow}\u26A0 Max iterations reached.${m.reset}`),await O0(" Continue for 20 more turns?")){Tt=20;continue e}console.log(`${m.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${m.reset}`)}break e}await cd()}z0.exports={processInput:RC,clearConversation:wC,getConversationLength:$C,getConversationMessages:_C,setConversationMessages:xC,setAbortSignalGetter:j1,setMaxIterations:I1,invalidateSystemPromptCache:Mu,clearToolFilterCache:Y1,getCachedFilteredTools:D0,buildSystemPrompt:Uu,splitSystemPrompt:yC,SYSTEM_PROMPT_DYNAMIC_BOUNDARY:Bu,getProjectContextHash:q0,_inferVerificationCommands:Hu,_inferRelevantTests:Oa,_inferSymbolTargets:H0,_buildSymbolHintBlock:Y0,buildUserContent:I0,_detectImageURLs:M0,_downloadImageURL:P0,_grabClipboardImage:L0,detectFrustration:j0,detectAndTruncateLoop:Ru,injectMidRunNote:rC,resetSessionTracking:G0}});var lt=Q((nN,J0)=>{var{OllamaProvider:CC,getOllamaRecommendations:AC}=Qd(),{OpenAIProvider:OC}=sf(),{AnthropicProvider:NC}=cf(),{GeminiProvider:MC}=ff(),{LocalProvider:PC}=mf(),{checkBudget:LC}=ai(),Ku={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"}},Gu=(process.env.OLLAMA_FALLBACK_CHAIN||"").split(",").map(t=>t.trim()).filter(Boolean),X0={};for(let[t,e]of Object.entries(Ku))for(let n of Object.values(e))X0[n]=t;function zu(t,e){let n=X0[t];return n&&Ku[n][e]||t}var ot={},Et=null,Qe=null,Mr=[];function Lt(){if(Object.keys(ot).length>0)return;vo("ollama",new CC),vo("openai",new OC),vo("anthropic",new NC),vo("gemini",new MC),vo("local",new PC);let t=process.env.DEFAULT_PROVIDER||"ollama",e=process.env.DEFAULT_MODEL||null;ot[t]?(Et=t,Qe=e||ot[t].defaultModel):(Et="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){ot[t]=e}function IC(t){return Lt(),ot[t]||null}function Xu(){return Lt(),ot[Et]||null}function jC(){return Lt(),Et}function DC(){return Lt(),Qe}function qC(){Lt();let t=Xu();if(!t)return{id:Qe,name:Qe,provider:Et};let e=t.getModel(Qe);return e?{...e,provider:Et}:{id:Qe,name:Qe,provider:Et}}function Vu(t){if(!t)return{provider:null,model:null};let e=t.indexOf(":");if(e>0){let n=t.slice(0,e);if(ot[n]||["ollama","openai","anthropic","gemini","local"].includes(n))return{provider:n,model:t.slice(e+1)}}return{provider:null,model:t}}function FC(t){Lt();let{provider:e,model:n}=Vu(t);if(e){let s=ot[e];return s&&(s.getModel(n)||e==="local"||e==="ollama")?(Et=e,Qe=n,Na(),!0):!1}let o=Xu();if(o&&o.getModel(n))return Qe=n,Na(),!0;for(let[s,r]of Object.entries(ot))if(r.getModel(n))return Et=s,Qe=n,Na(),!0;return!1}function Na(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=Xl();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=pn();t()}catch{}}function BC(){Lt();let t=new Set;for(let e of Object.values(ot))for(let n of e.getModelNames())t.add(n);return Array.from(t)}function UC(){return Lt(),Object.entries(ot).map(([t,e])=>({provider:t,configured:e.isConfigured(),models:Object.values(e.getModels()).map(n=>({...n,active:t===Et&&n.id===Qe}))}))}function WC(){Lt();let t=[];for(let[e,n]of Object.entries(ot)){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,maxTokens:s.maxTokens,contextWindow:s.contextWindow,capability:s.capability,speed:s.speed,quality:s.quality,recommendedFor:s.recommendedFor||[]})}return t}function HC(t="coding",e={}){Lt();let n=e.limit||5,o=e.configuredOnly!==!1,s=[],r=ot.ollama;if(r&&(!o||r.isConfigured()))for(let i of AC(t,n))s.push({...i,spec:`ollama:${i.id}`,provider:"ollama",configured:r.isConfigured()});if(s.length>=n)return s.slice(0,n);for(let[i,a]of Object.entries(ot)){if(i==="ollama"||o&&!a.isConfigured())continue;let c=a.getModel(a.defaultModel);if(c&&(s.push({...c,spec:`${i}:${c.id}`,provider:i,configured:a.isConfigured()}),s.length>=n))break}return s}function YC(t){Mr=Array.isArray(t)?t:[]}function GC(){return[...Mr]}function K0(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 V0(t){let e=[Et,...Mr.filter(r=>r!==Et)],n,o=0,s=0;for(let r=0;r<e.length;r++){let i=e[r],a=ot[i];if(!a||!a.isConfigured())continue;s++;let c=LC(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?zu(Qe,i):Qe;return u&&l!==Qe&&process.stderr.write(` [fallback: ${i}:${l}]
1486
+ `),await t(a,i,l)}catch(u){if(n=u,!K0(u)||r>=e.length-1)throw u;if(i==="ollama"&&Gu.length>0){let l=isFallback?zu(Qe,i):Qe;for(let d of Gu)if(d!==l)try{return process.stderr.write(` [ollama fallback: ${d}]
1487
+ `),await t(a,i,d)}catch(f){if(n=f,!K0(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 zC(t,e,n={}){Lt();let o=n.model,s=o?(()=>{let{model:i}=Vu(o);return i||o})():void 0,r=s!==o?{...n,model:s}:n;return V0((i,a,c)=>i.stream(t,e,{model:c,signal:r.signal,...r}))}async function KC(t,e,n={}){if(Lt(),n.provider){let o=ot[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 V0(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 XC(){Lt();let t=[];for(let[e,n]of Object.entries(ot))n.isConfigured()&&t.push({name:e,models:Object.values(n.getModels())});return t}function VC(){for(let t of Object.keys(ot))delete ot[t];Et=null,Qe=null,Mr=[]}J0.exports={registerProvider:vo,getProvider:IC,getActiveProvider:Xu,getActiveProviderName:jC,getActiveModelId:DC,getActiveModel:qC,setActiveModel:FC,getModelNames:BC,parseModelSpec:Vu,listProviders:UC,listAllModels:WC,recommendModels:HC,callStream:zC,callChat:KC,getConfiguredProviders:XC,setFallbackChain:YC,getFallbackChain:GC,resolveModelForProvider:zu,MODEL_EQUIVALENTS:Ku,OLLAMA_FALLBACK_MODELS:Gu,_reset:VC}});var{C:D}=it(),JC=lt(),{TOOL_DEFINITIONS:Z0}=zs(),{saveRoutingConfig:ZC}=ms();function Un(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 QC(t,e=[]){let n=Rn(t);return e.some(o=>n.includes(Rn(o)))}function ed(t,e=[]){let n=Rn(t);return e.every(o=>n.includes(Rn(o)))}function tw(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 eA(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 tA(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 Q0(t=""){return/\b(rg|grep|find|fd|ls|dir|sed|awk)\b/i.test(t)}function Pa(t,e=[]){return t?.action!=="create"||!Array.isArray(t.tasks)||t.tasks.length===0?!1:ed(Un(t),e)}function ew(t,{pathIncludes:e=[],table:n="users",action:o="select",conditionTerms:s=[]}={}){if(!Pr(t)||!ed(t.path,e))return!1;let r=Rn(t.content);return!r.includes(o)||!r.includes(n)?!1:s.every(i=>QC(r,i))}function nA(t,e=[]){let n=Un(t);return ed(n,e)}function Ju(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 td=[{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=>Ju(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=>Ju(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(Un(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=>Ju(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=>ew(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(Un(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=>ew(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=Un(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"&&Q0(t.command)&&/authenticateuser|src\/api\.js/i.test(t.command)?!0:nA(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=Un(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"?Q0(t.command)&&/src|export|function|module\.exports|exports\./i.test(t.command):/getUserById|export|function|module\.exports|exports\.|src|public|def /i.test(Un(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"?tw(t.command):Pa(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=Un(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}],nw=[{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"?tw(t.command):Pa(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"?eA(t.command):Pa(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"?tA(t.command):Pa(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)}],Ia=[...td,...nw],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 sA(){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 nd=sA(),oA=["minimax-m2.7:cloud","qwen3-coder:480b","devstral-2:123b"],sw=(()=>{let t=nd.slice(0,3);return t.length>=3?t:oA})(),rA=14,Ma={producedToolCall:.2,correctTool:.35,validArgs:.3,schemaCompliant:.15},iA="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 Qu(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:iA},{role:"user",content:t.prompt}],s=Date.now();try{let r=await JC.callChat(o,Z0,{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=Z0.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?Ma.producedToolCall:0)+(t.correctTool?Ma.correctTool:0)+(t.validArgs?Ma.validArgs:0)+(t.schemaCompliant?Ma.schemaCompliant:0))*100}var ow={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 sd(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=>ow[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 rw(t){return iw(t)}function iw(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=>ow[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 aw(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(`
1488
1488
  ${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(`
1489
1489
  ${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(`
1490
1490
  ${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(`
1491
- ${D.bold}Best model per task type:${D.reset}`);let l=sw(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 rw(t){if(!(!t||t.length<2))try{let e=nw(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&&(GC(s),console.log(`
1491
+ ${D.bold}Best model per task type:${D.reset}`);let l=iw(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 cw(t){if(!(!t||t.length<2))try{let e=rw(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&&(ZC(s),console.log(`
1492
1492
  ${D.dim} Routing updated: ${r.join(", ")}${D.reset}`),console.log(`
1493
- ${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 tA({models:t,quick:e=!1,onProgress:n,parallelModels:o=1}={}){let s=e?Ju.slice(0,QC):La,r=t?.length>0?t:e?ew: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 ow(a,s.length),rw(a),a}async function nA({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),ow(r,La.length),rw(r),r}var Pa=[{id:"simple_question",name:"Simple Convergence",prompt:"What is 2+2?",maxTurns:3,successCriteria:["4"]}];function iw(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.
1493
+ ${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 aA({models:t,quick:e=!1,onProgress:n,parallelModels:o=1}={}){let s=e?td.slice(0,rA):Ia,r=t?.length>0?t:e?sw:nd,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 Qu(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 Qu(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=sd(i);return aw(a,s.length),cw(a),a}async function cA({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 Ia){n?.({model:i,task:a.id,done:!1});let c=await Qu(a,i);o[i].push(c),n?.({model:i,task:a.id,done:!0,score:So(c),error:c.error})}}let r=[...sd(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),aw(r,Ia.length),cw(r),r}var La=[{id:"simple_question",name:"Simple Convergence",prompt:"What is 2+2?",maxTurns:3,successCriteria:["4"]}];function lw(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.
1494
1494
  Example:
1495
1495
  {
1496
1496
  "scenarios": [
@@ -1503,14 +1503,14 @@ ${D.green}\u{1F4A1} The best models have been saved to ~/.nex-code/.env and will
1503
1503
  }
1504
1504
  ]
1505
1505
  }
1506
- `),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}
1507
- `),Pa):s.scenarios}catch(s){return console.log(`${D.yellow}Failed to parse benchmark-config.json: ${s.message}${D.reset}
1508
- `),Pa}}function aw(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 sA(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 oA(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
+ `),La;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}
1507
+ `),La):s.scenarios}catch(s){return console.log(`${D.yellow}Failed to parse benchmark-config.json: ${s.message}${D.reset}
1508
+ `),La}}function uw(t,e){let{scoreMessages:n,_extractToolCalls:o,_getLastAssistantText:s}=oa(),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 lA(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 uA(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(`
1509
1509
  \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
1510
- `)}function rA(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}
1510
+ `)}function dA(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}
1511
1511
  `);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}
1512
1512
  `);return}let r=s.slice(-t);console.log(`
1513
- ${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 iA({dryRun:t=!1,model:e,cwd:n,onProgress:o}={}){let s=Ur(),r=iw(n);if(t){console.log(`
1513
+ ${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 fA({dryRun:t=!1,model:e,cwd:n,onProgress:o}={}){let s=Ur(),r=lw(n);if(t){console.log(`
1514
1514
  ${D.bold}Scenario Benchmark \u2014 Scenarios (dry-run):${D.reset}
1515
1515
  `);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(`
1516
- ${D.dim}Running scenario: ${c.name}...${D.reset}`);let{messages:u,timedOut:l}=await sA(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=aw(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 oA(a,s.version,i),a}module.exports={runBenchmark:tA,runDiscoverBenchmark:nA,buildSummary:Qu,buildCategoryWinners:nw,TASKS:Ju,PHASE_TASKS:Q0,ALL_TASKS:La,scoreResult:So,DEFAULT_MODELS:Zu,QUICK_MODELS:ew,runScenarioBenchmark:iA,showScoreTrend:rA,loadScenarios:iw,DEFAULT_SCENARIOS:Pa,scoreScenario:aw};
1516
+ ${D.dim}Running scenario: ${c.name}...${D.reset}`);let{messages:u,timedOut:l}=await lA(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=uw(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}=oa();p(d.score,{version:s.version,model:i,sessionName:`bench:${c.id}`,issues:d.issues})}catch{}}return uA(a,s.version,i),a}module.exports={runBenchmark:aA,runDiscoverBenchmark:cA,buildSummary:sd,buildCategoryWinners:rw,TASKS:td,PHASE_TASKS:nw,ALL_TASKS:Ia,scoreResult:So,DEFAULT_MODELS:nd,QUICK_MODELS:sw,runScenarioBenchmark:fA,showScoreTrend:dA,loadScenarios:lw,DEFAULT_SCENARIOS:La,scoreScenario:uw};