nex-code 0.5.26 → 0.5.27

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,61 +1,61 @@
1
- "use strict";var mc=Object.defineProperty;var B_=Object.getOwnPropertyDescriptor;var U_=Object.getOwnPropertyNames;var W_=Object.prototype.hasOwnProperty;var H_=(t,e)=>()=>(t&&(e=t(t=0)),e);var ne=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),G_=(t,e)=>{for(var n in e)mc(t,n,{get:e[n],enumerable:!0})},Y_=(t,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of U_(e))!W_.call(t,o)&&o!==n&&mc(t,o,{get:()=>e[o],enumerable:!(s=B_(e,o))||s.enumerable});return t};var z_=t=>Y_(mc({},"__esModule",{value:!0}),t);var kn=ne((eM,tp)=>{"use strict";var Vf="\x1B[0m",Xf="\x1B[1m",Ao="\x1B[2m";function J(t,e,n){return`\x1B[38;2;${t};${e};${n}m`}function K_(){if(!process.stdout.isTTY)return null;try{let{execFileSync:t}=require("child_process"),e=["import sys,os,tty,termios,select","f=open('/dev/tty','r+b',buffering=0)","fd=f.fileno()","s=termios.tcgetattr(fd)","try:"," tty.setraw(fd)"," f.write(bytes([0x1b,0x5d,0x31,0x31,0x3b,0x3f,0x1b,0x5c]))"," r=select.select([fd],[],[],0.1)[0]"," d=b''"," if r:"," while True:"," r2=select.select([fd],[],[],0.05)[0]"," if not r2:break"," c=os.read(fd,1)"," d+=c"," if d[-1:]==bytes([0x07]) or d[-2:]==bytes([0x1b,0x5c]):break"," sys.stdout.buffer.write(d)","finally:"," termios.tcsetattr(fd,termios.TCSADRAIN,s)"," f.close()"].join(`
2
- `),o=t("python3",["-c",e],{encoding:"buffer",timeout:400,stdio:["ignore","pipe","ignore"]}).toString("utf8").match(/rgb:([0-9a-fA-F]+)\/([0-9a-fA-F]+)\/([0-9a-fA-F]+)/);if(o){let r=parseInt(o[1].slice(0,2),16),i=parseInt(o[2].slice(0,2),16),a=parseInt(o[3].slice(0,2),16);return .299*r+.587*i+.114*a<128}}catch{}return null}function Jf(){let t=require("os");return require("path").join(t.homedir(),".nex-code",".theme_cache.json")}function V_(t){try{let n=require("fs").readFileSync(Jf(),"utf8"),s=JSON.parse(n);if(s&&typeof s[t]=="boolean")return s[t]}catch(e){console.error("readThemeCache failed:",e.message)}return null}function X_(t,e){try{let n=require("fs"),s=require("path"),o=Jf(),r=s.dirname(o),i={};try{i=JSON.parse(n.readFileSync(o,"utf8"))}catch(l){console.error("theme cache failed:",l.message)}i[t]=e;let a=Object.keys(i);a.length>50&&a.slice(0,a.length-50).forEach(l=>delete i[l]),n.existsSync(r)||n.mkdirSync(r,{recursive:!0}),n.writeFileSync(o,JSON.stringify(i),"utf8")}catch{}}function J_(){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",s=V_(n);if(s!==null)return s;let o=K_(),r=o!==null?o:!0;return X_(n,r),r}var Zf=J_(),Qf={reset:Vf,bold:Xf,dim:Ao,primary:J(80,190,255),secondary:J(60,170,190),success:J(80,210,120),warning:J(245,175,50),error:J(230,80,80),muted:Ao,subtle:J(130,130,145),tool_read:J(80,190,255),tool_write:J(245,165,55),tool_exec:J(185,100,235),tool_search:J(70,185,190),tool_git:J(90,210,100),tool_web:J(100,215,250),tool_sysadmin:J(225,150,75),tool_default:J(100,205,115),syn_keyword:J(185,100,235),syn_string:J(90,210,120),syn_number:J(245,175,50),syn_comment:Ao,syn_key:J(80,190,255),diff_add:J(80,210,120),diff_rem:J(230,80,80),banner_logo:J(80,200,255),banner_name:J(80,200,255),banner_version:Ao,banner_model:Ao,banner_yolo:J(245,175,50),banner_gemini:J(138,180,248),footer_sep:Ao,footer_model:J(80,175,235),footer_branch:J(80,210,100),footer_project:J(130,130,145),footer_divider:J(80,80,95),footer_mode:J(210,150,50),white:J(210,210,220),red:J(220,85,85),green:J(80,200,110),yellow:J(230,185,60),blue:J(70,140,230),magenta:J(200,120,190),cyan:J(90,200,215),gray:J(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:J(110,215,230),brightMagenta:J(220,140,210),brightBlue:J(100,160,240)},ep={reset:Vf,bold:Xf,dim:J(110,110,120),primary:J(0,110,190),secondary:J(0,125,148),success:J(0,148,62),warning:J(168,92,0),error:J(188,32,32),muted:J(110,110,120),subtle:J(155,155,165),tool_read:J(0,110,190),tool_write:J(168,92,0),tool_exec:J(128,42,188),tool_search:J(0,122,148),tool_git:J(0,138,62),tool_web:J(0,112,178),tool_sysadmin:J(168,82,0),tool_default:J(0,138,62),syn_keyword:J(128,42,188),syn_string:J(0,138,62),syn_number:J(168,92,0),syn_comment:J(135,135,148),syn_key:J(0,110,190),diff_add:J(0,148,62),diff_rem:J(188,32,32),banner_logo:J(0,122,205),banner_name:J(0,122,205),banner_version:J(100,100,118),banner_model:J(100,100,118),banner_yolo:J(168,62,0),banner_gemini:J(26,115,232),footer_sep:J(168,168,178),footer_model:J(0,102,175),footer_branch:J(0,138,62),footer_project:J(135,135,148),footer_divider:J(168,168,178),footer_mode:J(148,88,0),white:J(40,40,52),red:J(188,32,32),green:J(0,148,62),yellow:J(168,92,0),blue:J(0,110,190),magenta:J(128,42,188),cyan:J(0,125,148),gray:J(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:J(0,158,182),brightMagenta:J(158,52,208),brightBlue:J(0,112,208)},Z_=Zf?Qf:ep;tp.exports={T:Z_,isDark:Zf,DARK:Qf,LIGHT:ep}});var Yi=ne((tM,Q_)=>{Q_.exports={name:"nex-code",version:"0.5.26",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 Ls=ne((nM,ap)=>{var{T:Q}=kn(),gc=5,Oo=(()=>{let t=[];for(let e=0;e<gc;e++)t.push(e);for(let e=gc-2;e>=1;e--)t.push(e);return t})(),np=["\u273D","\u2726","\u2727","\u2726"],sp=["\xB7 ","\xB7\xB7 ","\xB7\xB7\xB7"," \xB7\xB7"];function op(t=""){let e=String(t).toLowerCase();return e.includes("search")||e.includes("read")||e.includes("list")||e.includes("inspect")?{glyph:"\u25CC",color:Q.cyan,accent:"scan"}:e.includes("write")||e.includes("edit")||e.includes("patch")||e.includes("build")?{glyph:"\u2726",color:Q.yellow,accent:"shape"}:e.includes("test")||e.includes("diff")||e.includes("check")||e.includes("verify")?{glyph:"\u25A3",color:Q.green,accent:"verify"}:e.includes("wait")||e.includes("github")||e.includes("fetch")||e.includes("browser")?{glyph:"\u25CD",color:Q.blue,accent:"wait"}:{glyph:"\u25CF",color:Q.cyan,accent:"think"}}function rp(t,e,n){let s="";for(let o=0;o<gc;o++)o===t?s+=`${n}${e}${Q.reset}`:o===t-1||o===t+1?s+=`${Q.dim}\xB7${Q.reset}`:s+=`${Q.dim}\xB7${Q.reset}`;return s}function ip(t){return`${Q.dim}${sp[t%sp.length]}${Q.reset}`}var yc=class{constructor(e="Thinking..."){this.text=e,this.frame=0,this.interval=null,this.startTime=null}_render(){if(this._stopped)return;let e=Oo[this.frame%Oo.length],n=op(this.text),s=rp(e,n.glyph,n.color),o=ip(this.frame),r="";if(this.startTime){let i=Math.floor((Date.now()-this.startTime)/1e3);if(i>=60){let a=Math.floor(i/60),l=i%60;r=` ${Q.dim}${a}m ${String(l).padStart(2,"0")}s${Q.reset}`}else i>=1&&(r=` ${Q.dim}${i}s${Q.reset}`)}process.stderr.write(`\x1B[2K\r${n.color}${n.accent.toUpperCase()}${Q.reset}${o} ${s} ${Q.dim}${this.text}${Q.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}},bc=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),s=e%60;return n>0?`${n}m ${String(s).padStart(2,"0")}s`:`${s}s`}_render(){if(this._stopped)return;let e=Oo[this.frame%Oo.length],n=`${Q.cyan}\u25CC${Q.reset}`,s=this._formatElapsed(),o=s?` ${Q.dim}${s}${Q.reset}`:"",r=process.stderr.columns||80,i="";for(let a=0;a<this.labels.length;a++){let l,c;switch(this.statuses[a]){case"done":l=`${Q.green}\u2713${Q.reset}`,c=Q.dim;break;case"error":l=`${Q.red}\u2717${Q.reset}`,c=Q.dim;break;case"retry":l=`${Q.yellow}\u21BB${Q.reset}`,c=Q.yellow;break;default:l=a===e?n:`${Q.dim}\xB7${Q.reset}`,c=""}let u=a===this.labels.length-1?o:"",d=r-4-(u?s.length+1:0),f=this.labels[a].length>d?this.labels[a].substring(0,Math.max(10,d-3))+"...":this.labels[a];i+=`\x1B[2K ${l} ${c}${f}${Q.reset}${u}
1
+ "use strict";var mc=Object.defineProperty;var B_=Object.getOwnPropertyDescriptor;var U_=Object.getOwnPropertyNames;var W_=Object.prototype.hasOwnProperty;var H_=(t,e)=>()=>(t&&(e=t(t=0)),e);var ne=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),G_=(t,e)=>{for(var n in e)mc(t,n,{get:e[n],enumerable:!0})},Y_=(t,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of U_(e))!W_.call(t,s)&&s!==n&&mc(t,s,{get:()=>e[s],enumerable:!(o=B_(e,s))||o.enumerable});return t};var z_=t=>Y_(mc({},"__esModule",{value:!0}),t);var kn=ne((eM,tp)=>{"use strict";var Vf="\x1B[0m",Xf="\x1B[1m",Ao="\x1B[2m";function J(t,e,n){return`\x1B[38;2;${t};${e};${n}m`}function K_(){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 Jf(){let t=require("os");return require("path").join(t.homedir(),".nex-code",".theme_cache.json")}function V_(t){try{let n=require("fs").readFileSync(Jf(),"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 X_(t,e){try{let n=require("fs"),o=require("path"),s=Jf(),r=o.dirname(s),i={};try{i=JSON.parse(n.readFileSync(s,"utf8"))}catch(l){console.error("theme cache failed:",l.message)}i[t]=e;let a=Object.keys(i);a.length>50&&a.slice(0,a.length-50).forEach(l=>delete i[l]),n.existsSync(r)||n.mkdirSync(r,{recursive:!0}),n.writeFileSync(s,JSON.stringify(i),"utf8")}catch{}}function J_(){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=V_(n);if(o!==null)return o;let s=K_(),r=s!==null?s:!0;return X_(n,r),r}var Zf=J_(),Qf={reset:Vf,bold:Xf,dim:Ao,primary:J(80,190,255),secondary:J(60,170,190),success:J(80,210,120),warning:J(245,175,50),error:J(230,80,80),muted:Ao,subtle:J(130,130,145),tool_read:J(80,190,255),tool_write:J(245,165,55),tool_exec:J(185,100,235),tool_search:J(70,185,190),tool_git:J(90,210,100),tool_web:J(100,215,250),tool_sysadmin:J(225,150,75),tool_default:J(100,205,115),syn_keyword:J(185,100,235),syn_string:J(90,210,120),syn_number:J(245,175,50),syn_comment:Ao,syn_key:J(80,190,255),diff_add:J(80,210,120),diff_rem:J(230,80,80),banner_logo:J(80,200,255),banner_name:J(80,200,255),banner_version:Ao,banner_model:Ao,banner_yolo:J(245,175,50),banner_gemini:J(138,180,248),footer_sep:Ao,footer_model:J(80,175,235),footer_branch:J(80,210,100),footer_project:J(130,130,145),footer_divider:J(80,80,95),footer_mode:J(210,150,50),white:J(210,210,220),red:J(220,85,85),green:J(80,200,110),yellow:J(230,185,60),blue:J(70,140,230),magenta:J(200,120,190),cyan:J(90,200,215),gray:J(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:J(110,215,230),brightMagenta:J(220,140,210),brightBlue:J(100,160,240)},ep={reset:Vf,bold:Xf,dim:J(110,110,120),primary:J(0,110,190),secondary:J(0,125,148),success:J(0,148,62),warning:J(168,92,0),error:J(188,32,32),muted:J(110,110,120),subtle:J(155,155,165),tool_read:J(0,110,190),tool_write:J(168,92,0),tool_exec:J(128,42,188),tool_search:J(0,122,148),tool_git:J(0,138,62),tool_web:J(0,112,178),tool_sysadmin:J(168,82,0),tool_default:J(0,138,62),syn_keyword:J(128,42,188),syn_string:J(0,138,62),syn_number:J(168,92,0),syn_comment:J(135,135,148),syn_key:J(0,110,190),diff_add:J(0,148,62),diff_rem:J(188,32,32),banner_logo:J(0,122,205),banner_name:J(0,122,205),banner_version:J(100,100,118),banner_model:J(100,100,118),banner_yolo:J(168,62,0),banner_gemini:J(26,115,232),footer_sep:J(168,168,178),footer_model:J(0,102,175),footer_branch:J(0,138,62),footer_project:J(135,135,148),footer_divider:J(168,168,178),footer_mode:J(148,88,0),white:J(40,40,52),red:J(188,32,32),green:J(0,148,62),yellow:J(168,92,0),blue:J(0,110,190),magenta:J(128,42,188),cyan:J(0,125,148),gray:J(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:J(0,158,182),brightMagenta:J(158,52,208),brightBlue:J(0,112,208)},Z_=Zf?Qf:ep;tp.exports={T:Z_,isDark:Zf,DARK:Qf,LIGHT:ep}});var Yi=ne((tM,Q_)=>{Q_.exports={name:"nex-code",version:"0.5.27",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 Ls=ne((nM,ap)=>{var{T:Q}=kn(),gc=5,Oo=(()=>{let t=[];for(let e=0;e<gc;e++)t.push(e);for(let e=gc-2;e>=1;e--)t.push(e);return t})(),np=["\u273D","\u2726","\u2727","\u2726"],sp=["\xB7 ","\xB7\xB7 ","\xB7\xB7\xB7"," \xB7\xB7"];function op(t=""){let e=String(t).toLowerCase();return e.includes("search")||e.includes("read")||e.includes("list")||e.includes("inspect")?{glyph:"\u25CC",color:Q.cyan,accent:"scan"}:e.includes("write")||e.includes("edit")||e.includes("patch")||e.includes("build")?{glyph:"\u2726",color:Q.yellow,accent:"shape"}:e.includes("test")||e.includes("diff")||e.includes("check")||e.includes("verify")?{glyph:"\u25A3",color:Q.green,accent:"verify"}:e.includes("wait")||e.includes("github")||e.includes("fetch")||e.includes("browser")?{glyph:"\u25CD",color:Q.blue,accent:"wait"}:{glyph:"\u25CF",color:Q.cyan,accent:"think"}}function rp(t,e,n){let o="";for(let s=0;s<gc;s++)s===t?o+=`${n}${e}${Q.reset}`:s===t-1||s===t+1?o+=`${Q.dim}\xB7${Q.reset}`:o+=`${Q.dim}\xB7${Q.reset}`;return o}function ip(t){return`${Q.dim}${sp[t%sp.length]}${Q.reset}`}var yc=class{constructor(e="Thinking..."){this.text=e,this.frame=0,this.interval=null,this.startTime=null}_render(){if(this._stopped)return;let e=Oo[this.frame%Oo.length],n=op(this.text),o=rp(e,n.glyph,n.color),s=ip(this.frame),r="";if(this.startTime){let i=Math.floor((Date.now()-this.startTime)/1e3);if(i>=60){let a=Math.floor(i/60),l=i%60;r=` ${Q.dim}${a}m ${String(l).padStart(2,"0")}s${Q.reset}`}else i>=1&&(r=` ${Q.dim}${i}s${Q.reset}`)}process.stderr.write(`\x1B[2K\r${n.color}${n.accent.toUpperCase()}${Q.reset}${s} ${o} ${Q.dim}${this.text}${Q.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}},bc=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=Oo[this.frame%Oo.length],n=`${Q.cyan}\u25CC${Q.reset}`,o=this._formatElapsed(),s=o?` ${Q.dim}${o}${Q.reset}`:"",r=process.stderr.columns||80,i="";for(let a=0;a<this.labels.length;a++){let l,c;switch(this.statuses[a]){case"done":l=`${Q.green}\u2713${Q.reset}`,c=Q.dim;break;case"error":l=`${Q.red}\u2717${Q.reset}`,c=Q.dim;break;case"retry":l=`${Q.yellow}\u21BB${Q.reset}`,c=Q.yellow;break;default:l=a===e?n:`${Q.dim}\xB7${Q.reset}`,c=""}let u=a===this.labels.length-1?s:"",d=r-4-(u?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 ${l} ${c}${f}${Q.reset}${u}
3
3
  `}this.lineCount>0&&(i+=`\x1B[${this.lineCount}A`),process.stderr.write(i),this.frame++}start(){this._stopped=!1,this.startTime=Date.now();let e="\x1B[?25l";for(let n=0;n<this.lineCount;n++)e+=`
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 s=0;s<this.lineCount;s++)n+=`\x1B[2K
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?` ${Q.dim}${e}${Q.reset}`:"",s=process.stderr.columns||80,o="";for(let r=0;r<this.labels.length;r++){let i;switch(this.statuses[r]){case"done":i=`${Q.green}\u2713${Q.reset}`;break;case"error":i=`${Q.red}\u2717${Q.reset}`;break;case"retry":i=`${Q.yellow}\u21BB${Q.reset}`;break;default:i=`${Q.yellow}\u25CB${Q.reset}`}let a=r===this.labels.length-1?n:"",l=s-4-(a?e.length+1:0),c=this.labels[r].length>l?this.labels[r].substring(0,Math.max(10,l-3))+"...":this.labels[r];o+=`\x1B[2K ${i} ${Q.dim}${c}${Q.reset}${a}
6
- `}process.stderr.write(o)}},zi={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},Ki={done:Q.green,in_progress:Q.cyan,pending:Q.dim,failed:Q.red},ps=null,wc=class{constructor(e,n){this.name=e,this.tasks=n.map(s=>({id:s.id,description:s.description,status:s.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),s=e%60;return n>0?`${n}m ${String(s).padStart(2,"0")}s`:`${s}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=np[this.frame%np.length],n=this._formatElapsed(),s=this._formatTokens(),o=[n,s?`\u2193 ${s} tokens`:""].filter(Boolean).join(" \xB7 "),r=o?` ${Q.dim}(${o})${Q.reset}`:"",i=`\x1B[2K${Q.cyan}${Q.bold}${e}${Q.reset} ${Q.bold}${this.name}${Q.reset}${Q.dim}\u2026${Q.reset}${r}
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
+ `;this.lineCount>0&&(n+=`\x1B[${this.lineCount}A`),process.stderr.write(n)}process.stderr.write("\x1B[?25h")}_renderFinal(){let e=this._formatElapsed(),n=e?` ${Q.dim}${e}${Q.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=`${Q.green}\u2713${Q.reset}`;break;case"error":i=`${Q.red}\u2717${Q.reset}`;break;case"retry":i=`${Q.yellow}\u21BB${Q.reset}`;break;default:i=`${Q.yellow}\u25CB${Q.reset}`}let a=r===this.labels.length-1?n:"",l=o-4-(a?e.length+1:0),c=this.labels[r].length>l?this.labels[r].substring(0,Math.max(10,l-3))+"...":this.labels[r];s+=`\x1B[2K ${i} ${Q.dim}${c}${Q.reset}${a}
6
+ `}process.stderr.write(s)}},zi={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},Ki={done:Q.green,in_progress:Q.cyan,pending:Q.dim,failed:Q.red},ps=null,wc=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=np[this.frame%np.length],n=this._formatElapsed(),o=this._formatTokens(),s=[n,o?`\u2193 ${o} tokens`:""].filter(Boolean).join(" \xB7 "),r=s?` ${Q.dim}(${s})${Q.reset}`:"",i=`\x1B[2K${Q.cyan}${Q.bold}${e}${Q.reset} ${Q.bold}${this.name}${Q.reset}${Q.dim}\u2026${Q.reset}${r}
7
7
  `;for(let a=0;a<this.tasks.length;a++){let l=this.tasks[a],c=a===0?"\u23BF":"\u2502",u=zi[l.status]||zi.pending,d=Ki[l.status]||Ki.pending,f=l.description.length>55?l.description.substring(0,52)+"...":l.description;i+=`\x1B[2K ${Q.dim}${c}${Q.reset} ${d}${u}${Q.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),ps=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,ps===this&&(ps=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
- `;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120)}updateTask(e,n){let s=this.tasks.find(o=>o.id===e);s&&(s.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,s=this.tasks.filter(a=>a.status==="failed").length,o=this.tasks.length,r=s>0?`${n}/${o} done, ${s} failed`:`${n}/${o} done`,i=`\x1B[2K${Q.green}${Q.bold}\u2714${Q.reset} ${Q.bold}${this.name}${Q.reset} ${Q.dim}(${e} \xB7 ${r})${Q.reset}
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${Q.green}${Q.bold}\u2714${Q.reset} ${Q.bold}${this.name}${Q.reset} ${Q.dim}(${e} \xB7 ${r})${Q.reset}
12
12
  `;for(let a=0;a<this.tasks.length;a++){let l=this.tasks[a],c=a===0?"\u23BF":"\u2502",u=zi[l.status]||zi.pending,d=Ki[l.status]||Ki.pending,f=l.description.length>55?l.description.substring(0,52)+"...":l.description;i+=`\x1B[2K ${Q.dim}${c}${Q.reset} ${d}${u}${Q.reset} ${Q.dim}${f}${Q.reset}
13
- `}process.stderr.write(i)}},_c=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=Oo[this.frame%Oo.length],n=op(this.message),s=rp(e,n.glyph,n.color),o=ip(this.frame),r=this.message;this.count>0&&(r+=` ${Q.cyan}${this.count}${Q.reset}`,this.total&&(r+=`/${this.total}`)),this.detail&&(r+=` ${Q.dim}${this.detail}${Q.reset}`);let i="";if(this.startTime){let a=Math.floor((Date.now()-this.startTime)/1e3);a>=1&&(i=` ${Q.dim}${a}s${Q.reset}`)}process.stderr.write(`\x1B[2K\r${n.color}${n.accent.toUpperCase()}${Q.reset}${o} ${s} ${Q.dim}${r}${Q.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 e$(t){ps=t}function t$(){return ps}function n$(){ps&&(ps.stop(),ps=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}ap.exports={C:Q,Spinner:yc,MultiProgress:bc,TaskProgress:wc,ToolProgress:_c,setActiveTaskProgress:e$,getActiveTaskProgress:t$,cleanupTerminal:n$}});var Vi=ne((sM,fp)=>{"use strict";var{T:Is}=kn(),be={kw:Is.syn_keyword,str:Is.syn_string,cmt:Is.syn_comment,num:Is.syn_number,type:Is.cyan,punct:Is.magenta,reset:Is.reset},lp={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"])},s$={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 up(t){if(!t)return null;let e=t.split(".").pop().toLowerCase();return s$[e]||null}var cp=/\x1b\[[0-9;]*m/g;function Xn(t,e,n){let s=t.split(cp),o=t.match(cp)||[],r="";for(let i=0;i<s.length;i++)r+=s[i].replace(e,n),i<o.length&&(r+=o[i]);return r}function o$(t){let e=t;return e=e.replace(/"([^"\\]|\\.)*"\s*:/g,n=>be.type+n+be.reset),e=Xn(e,/"([^"\\]|\\.)*"/g,n=>be.str+n+be.reset),e=Xn(e,/\b-?(\d+(\.\d+)?([eE][+-]?\d+)?)\b/g,n=>be.num+n+be.reset),e=Xn(e,/\b(true|false|null)\b/g,n=>be.kw+n+be.reset),e}function r$(t){if(/<!--/.test(t))return t.replace(/<!--[\s\S]*?(?:-->|$)/g,n=>be.cmt+n+be.reset);let e=t;return e=e.replace(/(<\/?)([a-zA-Z][a-zA-Z0-9.-]*)/g,(n,s,o)=>s+be.type+o+be.reset),e=Xn(e,/\s([a-zA-Z][a-zA-Z0-9-]*)=/g,(n,s)=>" "+be.kw+s+be.reset+"="),e=Xn(e,/"([^"]*)"/g,n=>be.str+n+be.reset),e}function i$(t){let e=t;return e=e.replace(/\/\*[\s\S]*?(?:\*\/|$)/g,n=>be.cmt+n+be.reset),e=Xn(e,/#[0-9a-fA-F]{3,8}\b/g,n=>be.num+n+be.reset),e=Xn(e,/\b(-?\d+(?:\.\d+)?)(px|em|rem|vh|vw|vmin|vmax|%|s|ms|deg|fr)\b/g,(n,s,o)=>be.num+s+be.reset+o),e=Xn(e,/([a-z][a-z-]*)(\s*:)/g,(n,s,o)=>be.type+s+be.reset+o),e=Xn(e,/"[^"]*"|'[^']*'/g,n=>be.str+n+be.reset),e}function dp(t,e,n){if(e==="json")return o$(t);if(e==="html"||e==="xml")return r$(t);if(e==="css")return i$(t);if(e==="md")return t;let s=lp[e]||lp.js,o="",r=0;if(n.inBlockComment){let i=t.indexOf("*/");if(i===-1)return be.cmt+t+be.reset;if(o+=be.cmt+t.slice(0,i+2)+be.reset,n.inBlockComment=!1,r=i+2,r>=t.length)return o}if(n.inString==="`"){let i=t.indexOf("`");if(i===-1)return be.str+t+be.reset;if(o+=be.str+t.slice(0,i+1)+be.reset,n.inString=null,r=i+1,r>=t.length)return o}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 o+=be.cmt+t.slice(r)+be.reset,n.inBlockComment=!0,o;o+=be.cmt+t.slice(r,a+2)+be.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 o+=be.cmt+t.slice(r)+be.reset,o;if(!n.inString&&(i==='"'||i==="'"||i==="`")){n.inString=i,o+=be.str+i,r++;continue}if(n.inString){if(i==="\\"&&r+1<t.length){o+=i+t[r+1],r+=2;continue}if(i===n.inString){o+=i+be.reset,n.inString=null,r++;continue}o+=i,r++;continue}if(/[0-9]/.test(i)&&(r===0||!/[a-zA-Z0-9_$]/.test(t[r-1]))){let a="";for(;r<t.length&&/[0-9a-fA-F_.xXoObBeE+-]/.test(t[r])&&!(a.length>0&&/[eE]/.test(t[r-1])&&/[^+-]/.test(i));)a+=t[r++];o+=be.num+a+be.reset;continue}if(i==="@"&&(e==="js"||e==="java"||e==="py")){let a="@";for(r++;r<t.length&&/[a-zA-Z0-9_$.]/.test(t[r]);)a+=t[r++];o+=be.punct+a+be.reset;continue}if(/[a-zA-Z_$]/.test(i)){let a="";for(;r<t.length&&/[a-zA-Z0-9_$]/.test(t[r]);)a+=t[r++];s.has(a)?o+=be.kw+a+be.reset:/^[A-Z][A-Za-z0-9]*$/.test(a)&&e!=="sh"?o+=be.type+a+be.reset:o+=a;continue}o+=i,r++}return n.inString&&n.inString!=="`"&&(o+=be.reset,n.inString=null),o}function a$(t,e){let n=up(e);if(!n)return t.split(`
14
- `);let s=t.split(`
15
- `),o={inString:null,inBlockComment:!1};return s.map(r=>dp(r,n,o))}function l$(t,e){return e?dp(t,e,{inString:null,inBlockComment:!1}):t}fp.exports={detectLang:up,highlightLine:l$,highlightLines:a$}});var vc=ne((oM,$p)=>{var{C:v}=xt(),js=null;function ht(){if(js!==null)return js;let t=(process.env.LANG||process.env.LC_ALL||process.env.LC_CTYPE||"").toLowerCase();if(t.includes("utf-8")||t.includes("utf8"))js=!0;else try{process.stdout.isTTY&&process.stdout.columns>0?js=!0:js=process.env.TERM?!/^(vt100|vt220|ansi|xterm)$/.test(process.env.TERM):!0}catch{js=!1}return js}var Ze={tl:()=>ht()?"\u250C":"+",tr:()=>ht()?"\u2510":"+",bl:()=>ht()?"\u2514":"+",br:()=>ht()?"\u2518":"+",h:()=>ht()?"\u2500":"-",v:()=>ht()?"\u2502":"|",bq:()=>ht()?"\u258E":"|",dot:()=>ht()?"\u25CF":"*",error:()=>ht()?"\u2716":"x",diamond:()=>ht()?"\u25C6":"#",doutline:()=>ht()?"\u25C7":"o",dcircle:()=>ht()?"\u25CE":"@",circle:()=>ht()?"\u25CB":"o",bullet:()=>ht()?"\u2022":"-"};function $c(){return Math.max(10,(process.stdout.columns||80)-2)}function c$(t){if(!t)return"";let e=t.split(`
16
- `),n=[],s=!1,o="";for(let r of e){let i=$c();if(r.trim().startsWith("```")){if(s){let a=Ze.h().repeat(Math.min(i-1,50));n.push(`${v.dim}${Ze.bl()}${a}${v.reset}`),s=!1,o=""}else{s=!0,o=r.trim().substring(3).trim();let a=o?` ${o} `:" code ",l=Ze.h().repeat(Math.max(0,Math.min(i-a.length-2,50)));n.push(`${v.dim}${Ze.tl()}${a}${l}${v.reset}`)}continue}if(s){n.push(`${v.dim}${Ze.v()}${v.reset} ${xc(r,o)}`);continue}if(r.startsWith("###### ")){n.push(`${v.dim}${v.cyan} ${Jt(r.substring(7))}${v.reset}`);continue}if(r.startsWith("##### ")){n.push(`${v.dim}${v.cyan} ${Jt(r.substring(6))}${v.reset}`);continue}if(r.startsWith("#### ")){n.push(`${v.dim}${v.bold} ${Jt(r.substring(5))}${v.reset}`);continue}if(r.startsWith("### ")){n.push(`${v.bold}${v.cyan} ${Jt(r.substring(4))}${v.reset}`);continue}if(r.startsWith("## ")){n.push(`${v.bold}${v.primary} ${Jt(r.substring(3))}${v.reset}`);continue}if(r.startsWith("# ")){let a=Jt(r.substring(2)),l=Ze.h().repeat(Math.min(a.length+2,i-2));n.push(`
13
+ `}process.stderr.write(i)}},_c=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=Oo[this.frame%Oo.length],n=op(this.message),o=rp(e,n.glyph,n.color),s=ip(this.frame),r=this.message;this.count>0&&(r+=` ${Q.cyan}${this.count}${Q.reset}`,this.total&&(r+=`/${this.total}`)),this.detail&&(r+=` ${Q.dim}${this.detail}${Q.reset}`);let i="";if(this.startTime){let a=Math.floor((Date.now()-this.startTime)/1e3);a>=1&&(i=` ${Q.dim}${a}s${Q.reset}`)}process.stderr.write(`\x1B[2K\r${n.color}${n.accent.toUpperCase()}${Q.reset}${s} ${o} ${Q.dim}${r}${Q.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 e$(t){ps=t}function t$(){return ps}function n$(){ps&&(ps.stop(),ps=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}ap.exports={C:Q,Spinner:yc,MultiProgress:bc,TaskProgress:wc,ToolProgress:_c,setActiveTaskProgress:e$,getActiveTaskProgress:t$,cleanupTerminal:n$}});var Vi=ne((sM,fp)=>{"use strict";var{T:Is}=kn(),be={kw:Is.syn_keyword,str:Is.syn_string,cmt:Is.syn_comment,num:Is.syn_number,type:Is.cyan,punct:Is.magenta,reset:Is.reset},lp={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"])},s$={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 up(t){if(!t)return null;let e=t.split(".").pop().toLowerCase();return s$[e]||null}var cp=/\x1b\[[0-9;]*m/g;function Xn(t,e,n){let o=t.split(cp),s=t.match(cp)||[],r="";for(let i=0;i<o.length;i++)r+=o[i].replace(e,n),i<s.length&&(r+=s[i]);return r}function o$(t){let e=t;return e=e.replace(/"([^"\\]|\\.)*"\s*:/g,n=>be.type+n+be.reset),e=Xn(e,/"([^"\\]|\\.)*"/g,n=>be.str+n+be.reset),e=Xn(e,/\b-?(\d+(\.\d+)?([eE][+-]?\d+)?)\b/g,n=>be.num+n+be.reset),e=Xn(e,/\b(true|false|null)\b/g,n=>be.kw+n+be.reset),e}function r$(t){if(/<!--/.test(t))return t.replace(/<!--[\s\S]*?(?:-->|$)/g,n=>be.cmt+n+be.reset);let e=t;return e=e.replace(/(<\/?)([a-zA-Z][a-zA-Z0-9.-]*)/g,(n,o,s)=>o+be.type+s+be.reset),e=Xn(e,/\s([a-zA-Z][a-zA-Z0-9-]*)=/g,(n,o)=>" "+be.kw+o+be.reset+"="),e=Xn(e,/"([^"]*)"/g,n=>be.str+n+be.reset),e}function i$(t){let e=t;return e=e.replace(/\/\*[\s\S]*?(?:\*\/|$)/g,n=>be.cmt+n+be.reset),e=Xn(e,/#[0-9a-fA-F]{3,8}\b/g,n=>be.num+n+be.reset),e=Xn(e,/\b(-?\d+(?:\.\d+)?)(px|em|rem|vh|vw|vmin|vmax|%|s|ms|deg|fr)\b/g,(n,o,s)=>be.num+o+be.reset+s),e=Xn(e,/([a-z][a-z-]*)(\s*:)/g,(n,o,s)=>be.type+o+be.reset+s),e=Xn(e,/"[^"]*"|'[^']*'/g,n=>be.str+n+be.reset),e}function dp(t,e,n){if(e==="json")return o$(t);if(e==="html"||e==="xml")return r$(t);if(e==="css")return i$(t);if(e==="md")return t;let o=lp[e]||lp.js,s="",r=0;if(n.inBlockComment){let i=t.indexOf("*/");if(i===-1)return be.cmt+t+be.reset;if(s+=be.cmt+t.slice(0,i+2)+be.reset,n.inBlockComment=!1,r=i+2,r>=t.length)return s}if(n.inString==="`"){let i=t.indexOf("`");if(i===-1)return be.str+t+be.reset;if(s+=be.str+t.slice(0,i+1)+be.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+=be.cmt+t.slice(r)+be.reset,n.inBlockComment=!0,s;s+=be.cmt+t.slice(r,a+2)+be.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+=be.cmt+t.slice(r)+be.reset,s;if(!n.inString&&(i==='"'||i==="'"||i==="`")){n.inString=i,s+=be.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+be.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+=be.num+a+be.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+=be.punct+a+be.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+=be.kw+a+be.reset:/^[A-Z][A-Za-z0-9]*$/.test(a)&&e!=="sh"?s+=be.type+a+be.reset:s+=a;continue}s+=i,r++}return n.inString&&n.inString!=="`"&&(s+=be.reset,n.inString=null),s}function a$(t,e){let n=up(e);if(!n)return t.split(`
14
+ `);let o=t.split(`
15
+ `),s={inString:null,inBlockComment:!1};return o.map(r=>dp(r,n,s))}function l$(t,e){return e?dp(t,e,{inString:null,inBlockComment:!1}):t}fp.exports={detectLang:up,highlightLine:l$,highlightLines:a$}});var vc=ne((oM,$p)=>{var{C:v}=xt(),js=null;function ht(){if(js!==null)return js;let t=(process.env.LANG||process.env.LC_ALL||process.env.LC_CTYPE||"").toLowerCase();if(t.includes("utf-8")||t.includes("utf8"))js=!0;else try{process.stdout.isTTY&&process.stdout.columns>0?js=!0:js=process.env.TERM?!/^(vt100|vt220|ansi|xterm)$/.test(process.env.TERM):!0}catch{js=!1}return js}var Ze={tl:()=>ht()?"\u250C":"+",tr:()=>ht()?"\u2510":"+",bl:()=>ht()?"\u2514":"+",br:()=>ht()?"\u2518":"+",h:()=>ht()?"\u2500":"-",v:()=>ht()?"\u2502":"|",bq:()=>ht()?"\u258E":"|",dot:()=>ht()?"\u25CF":"*",error:()=>ht()?"\u2716":"x",diamond:()=>ht()?"\u25C6":"#",doutline:()=>ht()?"\u25C7":"o",dcircle:()=>ht()?"\u25CE":"@",circle:()=>ht()?"\u25CB":"o",bullet:()=>ht()?"\u2022":"-"};function $c(){return Math.max(10,(process.stdout.columns||80)-2)}function c$(t){if(!t)return"";let e=t.split(`
16
+ `),n=[],o=!1,s="";for(let r of e){let i=$c();if(r.trim().startsWith("```")){if(o){let a=Ze.h().repeat(Math.min(i-1,50));n.push(`${v.dim}${Ze.bl()}${a}${v.reset}`),o=!1,s=""}else{o=!0,s=r.trim().substring(3).trim();let a=s?` ${s} `:" code ",l=Ze.h().repeat(Math.max(0,Math.min(i-a.length-2,50)));n.push(`${v.dim}${Ze.tl()}${a}${l}${v.reset}`)}continue}if(o){n.push(`${v.dim}${Ze.v()}${v.reset} ${xc(r,s)}`);continue}if(r.startsWith("###### ")){n.push(`${v.dim}${v.cyan} ${Jt(r.substring(7))}${v.reset}`);continue}if(r.startsWith("##### ")){n.push(`${v.dim}${v.cyan} ${Jt(r.substring(6))}${v.reset}`);continue}if(r.startsWith("#### ")){n.push(`${v.dim}${v.bold} ${Jt(r.substring(5))}${v.reset}`);continue}if(r.startsWith("### ")){n.push(`${v.bold}${v.cyan} ${Jt(r.substring(4))}${v.reset}`);continue}if(r.startsWith("## ")){n.push(`${v.bold}${v.primary} ${Jt(r.substring(3))}${v.reset}`);continue}if(r.startsWith("# ")){let a=Jt(r.substring(2)),l=Ze.h().repeat(Math.min(a.length+2,i-2));n.push(`
17
17
  ${v.bold}${v.primary} ${a}${v.reset}
18
18
  ${v.dim} ${l}${v.reset}`);continue}if(/^(\s*)(-{3,}|\*{3,}|_{3,})\s*$/.test(r)){n.push(`${v.dim}${Ze.h().repeat(Math.min(i,50))}${v.reset}`);continue}if(/^\s*>\s?/.test(r)){let a=r.match(/^(\s*)/)[1],l=r.replace(/^\s*>\s?/,""),c=`${a}${v.dim}${Ze.bq()}${v.reset} ${v.dim}${Jn(l)}${v.reset}`;n.push(Zn(c,i,a+" "));continue}if(/^\s*[-*]\s/.test(r)){let a=r.match(/^(\s*)/)[1],l=r.replace(/^\s*[-*]\s/,""),c=`${a}${v.cyan}${Ze.bullet()}${v.reset} ${Jn(l)}`;n.push(Zn(c,i,a+" "));continue}if(/^\s*\d+\.\s/.test(r)){let a=r.match(/^(\s*)(\d+)\.\s(.*)/);if(a){let l=a[1],c=a[2],u=a[3],d=`${l}${v.cyan}${c}.${v.reset} ${Jn(u)}`,f=l+" ".repeat(c.length+2);n.push(Zn(d,i,f));continue}}n.push(Zn(Jn(r),i))}return n.join(`
19
- `)}function Jt(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function Jn(t){return t?t.replace(/`([^`]+)`/g,`${v.cyan}$1${v.reset}`).replace(/\*\*([^*]+)\*\*/g,`${v.bold}$1${v.reset}`).replace(/\*([^*]+)\*/g,`${v.dim}$1${v.reset}`).replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${v.cyan}$1${v.reset} ${v.dim}($2)${v.reset}`):""}function xc(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?pp(t):e==="bash"||e==="sh"||e==="shell"||e==="zsh"?hp(t):e==="json"||e==="jsonc"?mp(t):e==="python"||e==="py"?gp(t):e==="go"||e==="golang"?yp(t):e==="rust"||e==="rs"?bp(t):e==="css"||e==="scss"||e==="less"?wp(t):e==="html"||e==="xml"||e==="svg"||e==="htm"?_p(t):t:""}function pp(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,s=/(\/\/.*$)/,o=/\b(\d+\.?\d*)\b/g,r=t;return r=r.replace(o,`${v.yellow}$1${v.reset}`),r=r.replace(e,`${v.magenta}$1${v.reset}`),r=r.replace(n,`${v.green}$&${v.reset}`),r=r.replace(s,`${v.dim}$1${v.reset}`),r}function hp(t){let e=/^(\s*)([\w-]+)/,n=/(--?\w[\w-]*)/g,s=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(#.*$)/,r=t;return r=r.replace(n,`${v.cyan}$1${v.reset}`),r=r.replace(e,`$1${v.green}$2${v.reset}`),r=r.replace(s,`${v.yellow}$&${v.reset}`),r=r.replace(o,`${v.dim}$1${v.reset}`),r}function mp(t){let e=/("[\w-]+")\s*:/g,n=/:\s*("(?:[^"\\]|\\.)*")/g,s=/:\s*(\d+\.?\d*)/g,o=/:\s*(true|false|null)/g,r=t;return r=r.replace(e,`${v.cyan}$1${v.reset}:`),r=r.replace(n,`: ${v.green}$1${v.reset}`),r=r.replace(s,`: ${v.yellow}$1${v.reset}`),r=r.replace(o,`: ${v.magenta}$1${v.reset}`),r}function gp(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,s=/(#.*$)/,o=/\b(\d+\.?\d*)\b/g,r=/^(\s*@\w+)/,i=t;return i=i.replace(o,`${v.yellow}$1${v.reset}`),i=i.replace(e,`${v.magenta}$1${v.reset}`),i=i.replace(r,`${v.cyan}$1${v.reset}`),i=i.replace(n,`${v.green}$&${v.reset}`),i=i.replace(s,`${v.dim}$1${v.reset}`),i}function yp(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,s=/(["'`])(?:(?=(\\?))\2.)*?\1/g,o=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,i=t;return i=i.replace(r,`${v.yellow}$1${v.reset}`),i=i.replace(n,`${v.cyan}$1${v.reset}`),i=i.replace(e,`${v.magenta}$1${v.reset}`),i=i.replace(s,`${v.green}$&${v.reset}`),i=i.replace(o,`${v.dim}$1${v.reset}`),i}function bp(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,s=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,i=/\b(\w+!)/g,a=t;return a=a.replace(r,`${v.yellow}$1${v.reset}`),a=a.replace(n,`${v.cyan}$1${v.reset}`),a=a.replace(e,`${v.magenta}$1${v.reset}`),a=a.replace(i,`${v.yellow}$1${v.reset}`),a=a.replace(s,`${v.green}$&${v.reset}`),a=a.replace(o,`${v.dim}$1${v.reset}`),a}function wp(t){let e=/^(\s*)([\w-]+)\s*:/,n=/:\s*([^;]+)/,s=/^(\s*[.#@][\w-]+)/,o=/\b(\d+\.?\d*(px|em|rem|%|vh|vw|s|ms|deg|fr)?)\b/g,r=/(\/\*.*?\*\/|\/\/.*$)/,i=/(#[0-9a-fA-F]{3,8})\b/g,a=t;return a=a.replace(i,`${v.yellow}$1${v.reset}`),a=a.replace(o,`${v.yellow}$1${v.reset}`),a=a.replace(e,`$1${v.cyan}$2${v.reset}:`),a=a.replace(s,`$1${v.magenta}$&${v.reset}`),a=a.replace(r,`${v.dim}$1${v.reset}`),a}function _p(t){let e=/<\/?(\w[\w-]*)/g,n=/\s([\w-]+)=/g,s=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(<!--.*?-->)/g,r=/(&\w+;)/g,i=t;return i=i.replace(o,`${v.dim}$1${v.reset}`),i=i.replace(s,`${v.green}$&${v.reset}`),i=i.replace(e,`<${v.magenta}$1${v.reset}`),i=i.replace(n,` ${v.cyan}$1${v.reset}=`),i=i.replace(r,`${v.yellow}$1${v.reset}`),i}function Zn(t,e,n=""){if(!e||e<10)return t;let s="",o=0,r=-1,i=0,a=0,l=t.length;for(;i<l;){if(t[i]==="\x1B"){let c=i+1;if(c<l&&t[c]==="["){for(c++;c<l&&!/[a-zA-Z]/.test(t[c]);)c++;c<l&&c++}i=c;continue}if(t[i]===" "&&(r=i),o++,o>e&&r!==-1){s+=t.slice(a,r)+`
20
- `+n,a=r+1,i=a,o=n.length,r=-1;continue}o>e&&r===-1&&(s+=t.slice(a,i)+`
21
- `+n,a=i,o=n.length+1),i++}return s+=t.slice(a),s}function u$(t,e){if(!t||t.length===0)return"";let n=t.map((d,f)=>{let p=e.reduce((h,g)=>Math.max(h,(g[f]||"").length),0);return Math.max(d.length,p)}),s=Ze.v(),o=Ze.h(),r=ht()?"\u253C":"+",i=ht()?"\u252C":"+",a=ht()?"\u2534":"+",l=n.map(d=>o.repeat(d+2)).join(r),c=t.map((d,f)=>` ${v.bold}${d.padEnd(n[f])}${v.reset} `).join(s),u=[];u.push(`${v.dim}${Ze.tl()}${l.replace(/\+/g,i)}${Ze.tr()}${v.reset}`),u.push(`${v.dim}${s}${v.reset}${c}${v.dim}${s}${v.reset}`),u.push(`${v.dim}${ht()?"\u251C":"+"}${l}${ht()?"\u2524":"+"}${v.reset}`);for(let d of e){let f=t.map((p,h)=>` ${(d[h]||"").padEnd(n[h])} `).join(`${v.dim}${s}${v.reset}`);u.push(`${v.dim}${s}${v.reset}${f}${v.dim}${s}${v.reset}`)}return u.push(`${v.dim}${Ze.bl()}${l.replace(/\+/g,a)}${Ze.br()}${v.reset}`),u.join(`
22
- `)}function d$(t,e,n,s=30){let o=n>0?Math.round(e/n*100):0,r=Math.round(o/100*s),i=s-r,a=o>=100?v.green:o>50?v.yellow:v.cyan;return` ${t} ${a}${"\u2588".repeat(r)}${v.dim}${"\u2591".repeat(i)}${v.reset} ${o}% (${e}/${n})`}var kc=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],s=n[this._cursorFrame%n.length],o="";for(let r=0;r<5;r++)o+=r===s?`${kn().T.cyan}\u25CF${kn().T.reset}`:" ";this._cursorWrite(`\x1B[2K\r${o}`),this._cursorFrame++}_clearCursorLine(){this._cursorActive&&this._cursorWrite("\x1B[2K\r")}stopCursor(){this._cursorTimer&&(clearInterval(this._cursorTimer),this._cursorTimer=null),this._cursorActive&&(this._cursorWrite("\x1B[2K\r\x1B[?25h"),this._cursorActive=!1)}push(e){if(!e)return;this._clearCursorLine(),this.buffer+=e;let n;for(;(n=this.buffer.indexOf(`
23
- `))!==-1;){let s=this.buffer.substring(0,n);this.buffer=this.buffer.substring(n+1),this._renderLine(s)}this._cursorActive&&(this._renderCursor(),this._cursorTimer&&clearInterval(this._cursorTimer),this._cursorTimer=setInterval(()=>this._renderCursor(),100))}flush(){if(this.stopCursor(),this.buffer&&(this._renderLine(this.buffer),this.buffer=""),this.inCodeBlock){let e=$c();this._safeWrite(`${v.dim}${Ze.bl()}${Ze.h().repeat(Math.min(e-1,50))}${v.reset}
24
- `),this.inCodeBlock=!1,this.codeBlockLang=""}}_renderLine(e){let n=$c();if(e.trim().startsWith("```")){if(this.inCodeBlock){let o=Ze.h().repeat(Math.min(n-1,50));this._safeWrite(`${v.dim}${Ze.bl()}${o}${v.reset}
25
- `),this.inCodeBlock=!1,this.codeBlockLang=""}else{this.inCodeBlock=!0,this.codeBlockLang=e.trim().substring(3).trim();let o=this.codeBlockLang?` ${this.codeBlockLang} `:" code ",r=Ze.h().repeat(Math.max(0,Math.min(n-o.length-2,50)));this._safeWrite(`${v.dim}${Ze.tl()}${o}${r}${v.reset}
19
+ `)}function Jt(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function Jn(t){return t?t.replace(/`([^`]+)`/g,`${v.cyan}$1${v.reset}`).replace(/\*\*([^*]+)\*\*/g,`${v.bold}$1${v.reset}`).replace(/\*([^*]+)\*/g,`${v.dim}$1${v.reset}`).replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${v.cyan}$1${v.reset} ${v.dim}($2)${v.reset}`):""}function xc(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?pp(t):e==="bash"||e==="sh"||e==="shell"||e==="zsh"?hp(t):e==="json"||e==="jsonc"?mp(t):e==="python"||e==="py"?gp(t):e==="go"||e==="golang"?yp(t):e==="rust"||e==="rs"?bp(t):e==="css"||e==="scss"||e==="less"?wp(t):e==="html"||e==="xml"||e==="svg"||e==="htm"?_p(t):t:""}function pp(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,`${v.yellow}$1${v.reset}`),r=r.replace(e,`${v.magenta}$1${v.reset}`),r=r.replace(n,`${v.green}$&${v.reset}`),r=r.replace(o,`${v.dim}$1${v.reset}`),r}function hp(t){let e=/^(\s*)([\w-]+)/,n=/(--?\w[\w-]*)/g,o=/(["'])(?:(?=(\\?))\2.)*?\1/g,s=/(#.*$)/,r=t;return r=r.replace(n,`${v.cyan}$1${v.reset}`),r=r.replace(e,`$1${v.green}$2${v.reset}`),r=r.replace(o,`${v.yellow}$&${v.reset}`),r=r.replace(s,`${v.dim}$1${v.reset}`),r}function mp(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,`${v.cyan}$1${v.reset}:`),r=r.replace(n,`: ${v.green}$1${v.reset}`),r=r.replace(o,`: ${v.yellow}$1${v.reset}`),r=r.replace(s,`: ${v.magenta}$1${v.reset}`),r}function gp(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,`${v.yellow}$1${v.reset}`),i=i.replace(e,`${v.magenta}$1${v.reset}`),i=i.replace(r,`${v.cyan}$1${v.reset}`),i=i.replace(n,`${v.green}$&${v.reset}`),i=i.replace(o,`${v.dim}$1${v.reset}`),i}function yp(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,`${v.yellow}$1${v.reset}`),i=i.replace(n,`${v.cyan}$1${v.reset}`),i=i.replace(e,`${v.magenta}$1${v.reset}`),i=i.replace(o,`${v.green}$&${v.reset}`),i=i.replace(s,`${v.dim}$1${v.reset}`),i}function bp(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,`${v.yellow}$1${v.reset}`),a=a.replace(n,`${v.cyan}$1${v.reset}`),a=a.replace(e,`${v.magenta}$1${v.reset}`),a=a.replace(i,`${v.yellow}$1${v.reset}`),a=a.replace(o,`${v.green}$&${v.reset}`),a=a.replace(s,`${v.dim}$1${v.reset}`),a}function wp(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,`${v.yellow}$1${v.reset}`),a=a.replace(s,`${v.yellow}$1${v.reset}`),a=a.replace(e,`$1${v.cyan}$2${v.reset}:`),a=a.replace(o,`$1${v.magenta}$&${v.reset}`),a=a.replace(r,`${v.dim}$1${v.reset}`),a}function _p(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,`${v.dim}$1${v.reset}`),i=i.replace(o,`${v.green}$&${v.reset}`),i=i.replace(e,`<${v.magenta}$1${v.reset}`),i=i.replace(n,` ${v.cyan}$1${v.reset}=`),i=i.replace(r,`${v.yellow}$1${v.reset}`),i}function Zn(t,e,n=""){if(!e||e<10)return t;let o="",s=0,r=-1,i=0,a=0,l=t.length;for(;i<l;){if(t[i]==="\x1B"){let c=i+1;if(c<l&&t[c]==="["){for(c++;c<l&&!/[a-zA-Z]/.test(t[c]);)c++;c<l&&c++}i=c;continue}if(t[i]===" "&&(r=i),s++,s>e&&r!==-1){o+=t.slice(a,r)+`
20
+ `+n,a=r+1,i=a,s=n.length,r=-1;continue}s>e&&r===-1&&(o+=t.slice(a,i)+`
21
+ `+n,a=i,s=n.length+1),i++}return o+=t.slice(a),o}function u$(t,e){if(!t||t.length===0)return"";let n=t.map((d,f)=>{let p=e.reduce((h,g)=>Math.max(h,(g[f]||"").length),0);return Math.max(d.length,p)}),o=Ze.v(),s=Ze.h(),r=ht()?"\u253C":"+",i=ht()?"\u252C":"+",a=ht()?"\u2534":"+",l=n.map(d=>s.repeat(d+2)).join(r),c=t.map((d,f)=>` ${v.bold}${d.padEnd(n[f])}${v.reset} `).join(o),u=[];u.push(`${v.dim}${Ze.tl()}${l.replace(/\+/g,i)}${Ze.tr()}${v.reset}`),u.push(`${v.dim}${o}${v.reset}${c}${v.dim}${o}${v.reset}`),u.push(`${v.dim}${ht()?"\u251C":"+"}${l}${ht()?"\u2524":"+"}${v.reset}`);for(let d of e){let f=t.map((p,h)=>` ${(d[h]||"").padEnd(n[h])} `).join(`${v.dim}${o}${v.reset}`);u.push(`${v.dim}${o}${v.reset}${f}${v.dim}${o}${v.reset}`)}return u.push(`${v.dim}${Ze.bl()}${l.replace(/\+/g,a)}${Ze.br()}${v.reset}`),u.join(`
22
+ `)}function d$(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?v.green:s>50?v.yellow:v.cyan;return` ${t} ${a}${"\u2588".repeat(r)}${v.dim}${"\u2591".repeat(i)}${v.reset} ${s}% (${e}/${n})`}var kc=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?`${kn().T.cyan}\u25CF${kn().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(`
23
+ `))!==-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(){if(this.stopCursor(),this.buffer&&(this._renderLine(this.buffer),this.buffer=""),this.inCodeBlock){let e=$c();this._safeWrite(`${v.dim}${Ze.bl()}${Ze.h().repeat(Math.min(e-1,50))}${v.reset}
24
+ `),this.inCodeBlock=!1,this.codeBlockLang=""}}_renderLine(e){let n=$c();if(e.trim().startsWith("```")){if(this.inCodeBlock){let s=Ze.h().repeat(Math.min(n-1,50));this._safeWrite(`${v.dim}${Ze.bl()}${s}${v.reset}
25
+ `),this.inCodeBlock=!1,this.codeBlockLang=""}else{this.inCodeBlock=!0,this.codeBlockLang=e.trim().substring(3).trim();let s=this.codeBlockLang?` ${this.codeBlockLang} `:" code ",r=Ze.h().repeat(Math.max(0,Math.min(n-s.length-2,50)));this._safeWrite(`${v.dim}${Ze.tl()}${s}${r}${v.reset}
26
26
  `)}return}if(this.inCodeBlock){this._safeWrite(`${v.dim}${Ze.v()}${v.reset} ${xc(e,this.codeBlockLang)}
27
27
  `);return}if(e.startsWith("###### ")){this._safeWrite(`${v.dim}${v.cyan} ${Jt(e.substring(7))}${v.reset}
28
28
  `);return}if(e.startsWith("##### ")){this._safeWrite(`${v.dim}${v.cyan} ${Jt(e.substring(6))}${v.reset}
29
29
  `);return}if(e.startsWith("#### ")){this._safeWrite(`${v.dim}${v.bold} ${Jt(e.substring(5))}${v.reset}
30
30
  `);return}if(e.startsWith("### ")){this._safeWrite(`${v.bold}${v.cyan} ${Jt(e.substring(4))}${v.reset}
31
31
  `);return}if(e.startsWith("## ")){this._safeWrite(`${v.bold}${v.primary} ${Jt(e.substring(3))}${v.reset}
32
- `);return}if(e.startsWith("# ")){let o=Jt(e.substring(2)),r=Ze.h().repeat(Math.min(o.length+2,n-2));this._safeWrite(`
33
- ${v.bold}${v.primary} ${o}${v.reset}
32
+ `);return}if(e.startsWith("# ")){let s=Jt(e.substring(2)),r=Ze.h().repeat(Math.min(s.length+2,n-2));this._safeWrite(`
33
+ ${v.bold}${v.primary} ${s}${v.reset}
34
34
  ${v.dim} ${r}${v.reset}
35
35
  `);return}if(/^(\s*)(-{3,}|\*{3,}|_{3,})\s*$/.test(e)){this._safeWrite(`${v.dim}${Ze.h().repeat(Math.min(n,50))}${v.reset}
36
- `);return}if(/^\s*>\s?/.test(e)){let o=e.match(/^(\s*)/)[1],r=e.replace(/^\s*>\s?/,""),i=`${o}${v.dim}${Ze.bq()}${v.reset} ${v.dim}${Jn(r)}${v.reset}`,a=Zn(i,n,o+" ");this._safeWrite(`${a}
37
- `);return}if(/^\s*[-*]\s/.test(e)){let o=e.match(/^(\s*)/)[1],r=e.replace(/^\s*[-*]\s/,""),i=`${o}${v.cyan}\u2022${v.reset} ${Jn(r)}`,a=Zn(i,n,o+" ");this._safeWrite(`${a}
38
- `);return}if(/^\s*\d+\.\s/.test(e)){let o=e.match(/^(\s*)(\d+)\.\s(.*)/);if(o){let r=o[1],i=o[2],a=o[3],l=`${r}${v.cyan}${i}.${v.reset} ${Jn(a)}`,c=r+" ".repeat(i.length+2),u=Zn(l,n,c);this._safeWrite(`${u}
39
- `);return}}let s=Zn(Jn(e),n);this._safeWrite(`${s}
40
- `)}};function f$(t,e={}){let{maxDepth:n=4,maxFiles:s=60,highlight:o=new Set,dim:r=new Set,icons:i=!0}=e,a=require("fs"),l=require("path"),c=new Set([".git","node_modules",".next","__pycache__",".venv","venv",".cache","dist",".nex","coverage",".DS_Store","target"]);function u(C,M){if(!i)return"";if(M)return"\u{1F4C1} ";let K=l.extname(C).toLowerCase(),z={".js":"\u{1F4DC} ",".ts":"\u{1F537} ",".jsx":"\u269B ",".tsx":"\u{1F536} ",".py":"\u{1F40D} ",".rs":"\u{1F980} ",".go":"\u{1F535} ",".css":"\u{1F3A8} ",".scss":"\u{1F3A8} ",".html":"\u{1F310} ",".md":"\u{1F4DD} ",".json":"\u{1F4CB} ",".toml":"\u2699 ",".yml":"\u2699 ",".yaml":"\u2699 ",".sh":"\u26A1 ",".env":"\u{1F512} ",".svg":"\u{1F5BC} ",".test.js":"\u{1F9EA} ",".test.ts":"\u{1F9EA} ",".spec.js":"\u{1F9EA} "};return z[K]||z[C]||"\u{1F4C4} "}function d(C,M){if(M)return v.cyan;let K=l.extname(C).toLowerCase();return/\.(js|ts|jsx|tsx)$/.test(K)?v.yellow:/\.(py|rs|go|java|rb)$/.test(K)?v.green:/\.(css|scss|less)$/.test(K)?v.magenta:/\.(html|xml|svg)$/.test(K)?v.primary:/\.(md|txt|rst)$/.test(K)?v.white:/\.(json|toml|yml|yaml)$/.test(K)?v.subtle:/\.(sh|bash|zsh)$/.test(K)?v.success:v.reset}let f=[],p=0,h=ht(),g=h?"\u251C\u2500\u2500 ":"|-- ",w=h?"\u2514\u2500\u2500 ":"`-- ",k=h?"\u2502 ":"| ",T=" ",$=l.relative(process.cwd(),t)||".";f.push(`${v.bold}${v.cyan}${$}${v.reset}`);function R(C,M,K){if(M>n||p>=s)return;let z;try{z=a.readdirSync(C,{withFileTypes:!0})}catch{f.push(`${K}${g}${v.dim}(unreadable)${v.reset}`);return}z.sort((Z,oe)=>Z.isDirectory()!==oe.isDirectory()?Z.isDirectory()?-1:1:Z.name.localeCompare(oe.name)),z=z.filter(Z=>!c.has(Z.name)&&!Z.name.startsWith("."));let X=20,ae=z.length-X;ae>0&&(z=z.slice(0,X));for(let Z=0;Z<z.length;Z++){if(p>=s){f.push(`${K}${g}${v.dim}\u2026 +${ae} more${v.reset}`);return}let oe=z[Z],Ke=Z===z.length-1&&ae<=0,Ee=Ke?w:g,G=K+(Ke?T:k),re=l.join(C,oe.name),et=l.relative(process.cwd(),re),Ve=v.reset;o.has(et)?Ve=v.yellow:r.has(et)?Ve=v.dim:Ve=d(oe.name,oe.isDirectory());let Ae=u(oe.name,oe.isDirectory()),Oe=oe.isDirectory()?`${v.bold}${oe.name}/${v.reset}`:oe.name;f.push(`${K}${Ee}${Ve}${Ae}${Oe}${v.reset}`),p++,oe.isDirectory()&&R(re,M+1,G)}ae>0&&f.push(`${K}${g}${v.dim}\u2026 +${ae} more${v.reset}`)}return R(t,1,""),f.join(`
41
- `)}$p.exports={hasUnicode:ht,G:Ze,renderTree:f$,renderMarkdown:c$,renderInline:Jn,stripHeadingMarkers:Jt,highlightCode:xc,highlightJS:pp,highlightBash:hp,highlightJSON:mp,highlightPython:gp,highlightGo:yp,highlightRust:bp,highlightCSS:wp,highlightHTML:_p,renderTable:u$,renderProgress:d$,wrapAnsi:Zn,StreamRenderer:kc}});var Pp=ne((rM,Op)=>{var{T:S}=kn(),Po=null;function Xi(){if(Po!==null)return Po;let t=(process.env.LANG||process.env.LC_ALL||process.env.LC_CTYPE||"").toLowerCase();return t.includes("utf-8")||t.includes("utf8")||process.stdout.isTTY&&process.stdout.columns>0?Po=!0:Po=process.env.TERM?!/^(vt100|vt220|ansi|xterm)$/.test(process.env.TERM):!0,Po}var Fe=S,kp=require("path"),xp=Xi()?["\u25C6","\u25C7","\u25CE","\u25C7"]:["#","o","@","o"];function Zi(t){if(!t)return"";let e=t.replace(/^\.\//,"").split("/");return e.length>1?e.slice(-2).join("/"):e[0]}var p$={read_file:S.tool_read,list_directory:S.tool_read,write_file:S.tool_write,edit_file:S.tool_write,patch_file:S.tool_write,bash:S.tool_exec,grep:S.tool_search,search_files:S.tool_search,glob:S.tool_search,git_commit:S.tool_git,git_push:S.tool_git,git_pull:S.tool_git,git_status:S.tool_git,git_diff:S.tool_git,git_log:S.tool_git,git_branch:S.tool_git,git_stash:S.tool_git,web_fetch:S.tool_web,web_search:S.tool_web,sysadmin:S.tool_sysadmin,ssh_exec:S.tool_sysadmin,ssh_upload:S.tool_sysadmin,ssh_download:S.tool_sysadmin,deploy:S.tool_sysadmin},Tp={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"},h$={read_file:{label:"Inspect",accent:S.tool_read,icon:"\u25CC"},list_directory:{label:"Inspect",accent:S.tool_read,icon:"\u25CC"},grep:{label:"Inspect",accent:S.tool_search,icon:"\u25CC"},search_files:{label:"Inspect",accent:S.tool_search,icon:"\u25CC"},glob:{label:"Inspect",accent:S.tool_search,icon:"\u25CC"},web_fetch:{label:"Explore",accent:S.tool_web,icon:"\u25CC"},web_search:{label:"Explore",accent:S.tool_web,icon:"\u25CC"},browser_open:{label:"Explore",accent:S.tool_web,icon:"\u25CC"},browser_screenshot:{label:"Capture",accent:S.tool_web,icon:"\u25CC"},browser_click:{label:"Interact",accent:S.tool_web,icon:"\u25CC"},browser_fill:{label:"Interact",accent:S.tool_web,icon:"\u25CC"},write_file:{label:"Shape",accent:S.tool_write,icon:"\u2726"},edit_file:{label:"Shape",accent:S.tool_write,icon:"\u2726"},patch_file:{label:"Shape",accent:S.tool_write,icon:"\u2726"},bash:{label:"Execute",accent:S.tool_exec,icon:"\u25A3"},sysadmin:{label:"Operate",accent:S.tool_sysadmin,icon:"\u25A3"},ssh_exec:{label:"Operate",accent:S.tool_sysadmin,icon:"\u25A3"},ssh_upload:{label:"Ship",accent:S.tool_sysadmin,icon:"\u25A3"},ssh_download:{label:"Collect",accent:S.tool_sysadmin,icon:"\u25A3"},deploy:{label:"Ship",accent:S.tool_sysadmin,icon:"\u25A3"},git_status:{label:"Verify",accent:S.tool_git,icon:"\u2713"},git_diff:{label:"Verify",accent:S.tool_git,icon:"\u2713"},git_log:{label:"Verify",accent:S.tool_git,icon:"\u2713"},git_commit:{label:"Commit",accent:S.tool_git,icon:"\u2713"},git_push:{label:"Ship",accent:S.tool_git,icon:"\u2713"},git_pull:{label:"Sync",accent:S.tool_git,icon:"\u2713"},git_branch:{label:"Sync",accent:S.tool_git,icon:"\u2713"},git_stash:{label:"Sync",accent:S.tool_git,icon:"\u2713"}};function Rp(t){return String(t||"").replace(/\x1B(?:\][^\x07]*(?:\x07|\x1B\\)|[PX^_][\s\S]*?\x1B\\)/g,"").replace(/[\x1B\x9B][[\]()#;?]*(?:\d{1,4}(?:;\d{0,4})*)?[0-9A-ORZcf-nq-uy=><]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,"")}function m$(t){let e=t.trim();if(!e)return!1;let n=e.replace(/^[│┃┆┊>↩✓✗⚠◆●◉◎⏺◌✦▣•\-\s]+/,"").trim();return!!(/^(INSPECT|SHAPE|EXECUTE|EXPLORE|VERIFY|OPERATE|SHIP|SYNC|COMMIT|RUN|CAPTURE|INTERACT)\b/i.test(n)||/^Step\s+\d+\b/i.test(n)||/^(Read|Write|Edit|Patch|Bash|Grep|Search|Glob|WebFetch|WebSearch|TaskList|Agent|AskUser)\b.*\s→\s/i.test(n)||/^(Reading|Writing|Editing|Patching|Running|Searching|Listing|Fetching|Delegating|Switching)\b/i.test(n)||/^\[(?:context|auto|pre-flight|pre-stop|debug|system)\b/i.test(n)||/\b(?:auto-abort|Ctrl\+C to abort|Headless early exit|Phase transition|tool budget|model metadata|orchestration log)\b/i.test(n)||/^(?:Thinking|Analyzing|Planning|Implementing|Verifying|Working)(?:[.\s]|$)/i.test(n)||/^(?:Model|Provider|Tokens|Cost|Usage):\s/i.test(n))}function g$(t){let e=Rp(t),n=[],s=!1;for(let o of e.split(/\r?\n/)){if(/^\s*```/.test(o)){s=!s,n.push(o.replace(/[ \t]+$/g,""));continue}!s&&m$(o)||n.push(o.replace(/[ \t]+$/g,""))}return n.join(`
36
+ `);return}if(/^\s*>\s?/.test(e)){let s=e.match(/^(\s*)/)[1],r=e.replace(/^\s*>\s?/,""),i=`${s}${v.dim}${Ze.bq()}${v.reset} ${v.dim}${Jn(r)}${v.reset}`,a=Zn(i,n,s+" ");this._safeWrite(`${a}
37
+ `);return}if(/^\s*[-*]\s/.test(e)){let s=e.match(/^(\s*)/)[1],r=e.replace(/^\s*[-*]\s/,""),i=`${s}${v.cyan}\u2022${v.reset} ${Jn(r)}`,a=Zn(i,n,s+" ");this._safeWrite(`${a}
38
+ `);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],l=`${r}${v.cyan}${i}.${v.reset} ${Jn(a)}`,c=r+" ".repeat(i.length+2),u=Zn(l,n,c);this._safeWrite(`${u}
39
+ `);return}}let o=Zn(Jn(e),n);this._safeWrite(`${o}
40
+ `)}};function f$(t,e={}){let{maxDepth:n=4,maxFiles:o=60,highlight:s=new Set,dim:r=new Set,icons:i=!0}=e,a=require("fs"),l=require("path"),c=new Set([".git","node_modules",".next","__pycache__",".venv","venv",".cache","dist",".nex","coverage",".DS_Store","target"]);function u(C,M){if(!i)return"";if(M)return"\u{1F4C1} ";let K=l.extname(C).toLowerCase(),z={".js":"\u{1F4DC} ",".ts":"\u{1F537} ",".jsx":"\u269B ",".tsx":"\u{1F536} ",".py":"\u{1F40D} ",".rs":"\u{1F980} ",".go":"\u{1F535} ",".css":"\u{1F3A8} ",".scss":"\u{1F3A8} ",".html":"\u{1F310} ",".md":"\u{1F4DD} ",".json":"\u{1F4CB} ",".toml":"\u2699 ",".yml":"\u2699 ",".yaml":"\u2699 ",".sh":"\u26A1 ",".env":"\u{1F512} ",".svg":"\u{1F5BC} ",".test.js":"\u{1F9EA} ",".test.ts":"\u{1F9EA} ",".spec.js":"\u{1F9EA} "};return z[K]||z[C]||"\u{1F4C4} "}function d(C,M){if(M)return v.cyan;let K=l.extname(C).toLowerCase();return/\.(js|ts|jsx|tsx)$/.test(K)?v.yellow:/\.(py|rs|go|java|rb)$/.test(K)?v.green:/\.(css|scss|less)$/.test(K)?v.magenta:/\.(html|xml|svg)$/.test(K)?v.primary:/\.(md|txt|rst)$/.test(K)?v.white:/\.(json|toml|yml|yaml)$/.test(K)?v.subtle:/\.(sh|bash|zsh)$/.test(K)?v.success:v.reset}let f=[],p=0,h=ht(),g=h?"\u251C\u2500\u2500 ":"|-- ",w=h?"\u2514\u2500\u2500 ":"`-- ",k=h?"\u2502 ":"| ",T=" ",$=l.relative(process.cwd(),t)||".";f.push(`${v.bold}${v.cyan}${$}${v.reset}`);function R(C,M,K){if(M>n||p>=o)return;let z;try{z=a.readdirSync(C,{withFileTypes:!0})}catch{f.push(`${K}${g}${v.dim}(unreadable)${v.reset}`);return}z.sort((Z,oe)=>Z.isDirectory()!==oe.isDirectory()?Z.isDirectory()?-1:1:Z.name.localeCompare(oe.name)),z=z.filter(Z=>!c.has(Z.name)&&!Z.name.startsWith("."));let X=20,ae=z.length-X;ae>0&&(z=z.slice(0,X));for(let Z=0;Z<z.length;Z++){if(p>=o){f.push(`${K}${g}${v.dim}\u2026 +${ae} more${v.reset}`);return}let oe=z[Z],Ke=Z===z.length-1&&ae<=0,Ee=Ke?w:g,G=K+(Ke?T:k),re=l.join(C,oe.name),et=l.relative(process.cwd(),re),Ve=v.reset;s.has(et)?Ve=v.yellow:r.has(et)?Ve=v.dim:Ve=d(oe.name,oe.isDirectory());let Ae=u(oe.name,oe.isDirectory()),Oe=oe.isDirectory()?`${v.bold}${oe.name}/${v.reset}`:oe.name;f.push(`${K}${Ee}${Ve}${Ae}${Oe}${v.reset}`),p++,oe.isDirectory()&&R(re,M+1,G)}ae>0&&f.push(`${K}${g}${v.dim}\u2026 +${ae} more${v.reset}`)}return R(t,1,""),f.join(`
41
+ `)}$p.exports={hasUnicode:ht,G:Ze,renderTree:f$,renderMarkdown:c$,renderInline:Jn,stripHeadingMarkers:Jt,highlightCode:xc,highlightJS:pp,highlightBash:hp,highlightJSON:mp,highlightPython:gp,highlightGo:yp,highlightRust:bp,highlightCSS:wp,highlightHTML:_p,renderTable:u$,renderProgress:d$,wrapAnsi:Zn,StreamRenderer:kc}});var Pp=ne((rM,Op)=>{var{T:S}=kn(),Po=null;function Xi(){if(Po!==null)return Po;let t=(process.env.LANG||process.env.LC_ALL||process.env.LC_CTYPE||"").toLowerCase();return t.includes("utf-8")||t.includes("utf8")||process.stdout.isTTY&&process.stdout.columns>0?Po=!0:Po=process.env.TERM?!/^(vt100|vt220|ansi|xterm)$/.test(process.env.TERM):!0,Po}var Fe=S,kp=require("path"),xp=Xi()?["\u25C6","\u25C7","\u25CE","\u25C7"]:["#","o","@","o"];function Zi(t){if(!t)return"";let e=t.replace(/^\.\//,"").split("/");return e.length>1?e.slice(-2).join("/"):e[0]}var p$={read_file:S.tool_read,list_directory:S.tool_read,write_file:S.tool_write,edit_file:S.tool_write,patch_file:S.tool_write,bash:S.tool_exec,grep:S.tool_search,search_files:S.tool_search,glob:S.tool_search,git_commit:S.tool_git,git_push:S.tool_git,git_pull:S.tool_git,git_status:S.tool_git,git_diff:S.tool_git,git_log:S.tool_git,git_branch:S.tool_git,git_stash:S.tool_git,web_fetch:S.tool_web,web_search:S.tool_web,sysadmin:S.tool_sysadmin,ssh_exec:S.tool_sysadmin,ssh_upload:S.tool_sysadmin,ssh_download:S.tool_sysadmin,deploy:S.tool_sysadmin},Tp={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"},h$={read_file:{label:"Inspect",accent:S.tool_read,icon:"\u25CC"},list_directory:{label:"Inspect",accent:S.tool_read,icon:"\u25CC"},grep:{label:"Inspect",accent:S.tool_search,icon:"\u25CC"},search_files:{label:"Inspect",accent:S.tool_search,icon:"\u25CC"},glob:{label:"Inspect",accent:S.tool_search,icon:"\u25CC"},web_fetch:{label:"Explore",accent:S.tool_web,icon:"\u25CC"},web_search:{label:"Explore",accent:S.tool_web,icon:"\u25CC"},browser_open:{label:"Explore",accent:S.tool_web,icon:"\u25CC"},browser_screenshot:{label:"Capture",accent:S.tool_web,icon:"\u25CC"},browser_click:{label:"Interact",accent:S.tool_web,icon:"\u25CC"},browser_fill:{label:"Interact",accent:S.tool_web,icon:"\u25CC"},write_file:{label:"Shape",accent:S.tool_write,icon:"\u2726"},edit_file:{label:"Shape",accent:S.tool_write,icon:"\u2726"},patch_file:{label:"Shape",accent:S.tool_write,icon:"\u2726"},bash:{label:"Execute",accent:S.tool_exec,icon:"\u25A3"},sysadmin:{label:"Operate",accent:S.tool_sysadmin,icon:"\u25A3"},ssh_exec:{label:"Operate",accent:S.tool_sysadmin,icon:"\u25A3"},ssh_upload:{label:"Ship",accent:S.tool_sysadmin,icon:"\u25A3"},ssh_download:{label:"Collect",accent:S.tool_sysadmin,icon:"\u25A3"},deploy:{label:"Ship",accent:S.tool_sysadmin,icon:"\u25A3"},git_status:{label:"Verify",accent:S.tool_git,icon:"\u2713"},git_diff:{label:"Verify",accent:S.tool_git,icon:"\u2713"},git_log:{label:"Verify",accent:S.tool_git,icon:"\u2713"},git_commit:{label:"Commit",accent:S.tool_git,icon:"\u2713"},git_push:{label:"Ship",accent:S.tool_git,icon:"\u2713"},git_pull:{label:"Sync",accent:S.tool_git,icon:"\u2713"},git_branch:{label:"Sync",accent:S.tool_git,icon:"\u2713"},git_stash:{label:"Sync",accent:S.tool_git,icon:"\u2713"}};function Rp(t){return String(t||"").replace(/\x1B(?:\][^\x07]*(?:\x07|\x1B\\)|[PX^_][\s\S]*?\x1B\\)/g,"").replace(/[\x1B\x9B][[\]()#;?]*(?:\d{1,4}(?:;\d{0,4})*)?[0-9A-ORZcf-nq-uy=><]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,"")}function m$(t){let e=t.trim();if(!e)return!1;let n=e.replace(/^[│┃┆┊>↩✓✗⚠◆●◉◎⏺◌✦▣•\-\s]+/,"").trim();return!!(/^(INSPECT|SHAPE|EXECUTE|EXPLORE|VERIFY|OPERATE|SHIP|SYNC|COMMIT|RUN|CAPTURE|INTERACT)\b/i.test(n)||/^Step\s+\d+\b/i.test(n)||/^(Read|Write|Edit|Patch|Bash|Grep|Search|Glob|WebFetch|WebSearch|TaskList|Agent|AskUser)\b.*\s→\s/i.test(n)||/^(Reading|Writing|Editing|Patching|Running|Searching|Listing|Fetching|Delegating|Switching)\b/i.test(n)||/^\[(?:context|auto|pre-flight|pre-stop|debug|system)\b/i.test(n)||/\b(?:auto-abort|Ctrl\+C to abort|Headless early exit|Phase transition|tool budget|model metadata|orchestration log)\b/i.test(n)||/^(?:Thinking|Analyzing|Planning|Implementing|Verifying|Working)(?:[.\s]|$)/i.test(n)||/^(?:Model|Provider|Tokens|Cost|Usage):\s/i.test(n))}function g$(t){let e=Rp(t),n=[],o=!1;for(let s of e.split(/\r?\n/)){if(/^\s*```/.test(s)){o=!o,n.push(s.replace(/[ \t]+$/g,""));continue}!o&&m$(s)||n.push(s.replace(/[ \t]+$/g,""))}return n.join(`
42
42
  `).replace(/\n{3,}/g,`
43
43
 
44
44
  `).trim()}function Ec(t){return h$[t]||{label:"Run",accent:S.tool_default,icon:"\u2022"}}function vp(t){let e=Ec(t);return`${e.accent}${Fe.bold}${e.icon} ${e.label.toUpperCase()}${S.reset}`}function y$(t){return t.replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase())}function Sp(t,e={}){return e.path?Zi(e.path):e.file?Zi(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):Tp[t]||y$(t)}function b$(t){return String(t||"").split(`
45
- `).map(e=>{let n=e.match(/^(\d+):\s?(.*)$/s);return n?{lineNumber:n[1],content:n[2]||""}:null}).filter(Boolean)}function w$(t,e,n={}){let{maxLines:s=4,indent:o=" ",maxContent:r=110,includeOverflow:i=!0}=n;if(!Array.isArray(e)||e.length===0)return"";let{highlightLine:a,detectLang:l}=Vi(),c=l(t||null),u=e.slice(0,s),d=u.map(({lineNumber:f,content:p})=>{let h=p.length>r?p.substring(0,r-1)+"\u2026":p;return`${o}${S.subtle}${f}:${S.reset} ${a(h,c)}${S.reset}`});return i&&e.length>u.length&&d.push(`${o}${S.subtle}\u2026 +${e.length-u.length} more line${e.length-u.length!==1?"s":""}${S.reset}`),d.join(`
46
- `)}function _$(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 Sc(t,e={}){let{maxLines:n=3,maxContent:s=96}=e,r=String(t||"").split(`
47
- `).filter((a,l,c)=>a.trim()||c.length===1||l===0),i=r.slice(0,n).map(a=>_$(a,s));return{shown:i,more:Math.max(0,r.length-i.length)}}function Cp(t,e={}){let{indent:n=" ",maxLines:s=2,maxContent:o=100}=e;if(!t)return"";let{shown:r,more:i}=Sc(t,{maxLines:s,maxContent:o});if(r.length===0)return"";let a=r.map((l,c)=>`${n}${S.subtle}${c===0?"$":">"}${S.reset} ${S.muted}${l}${S.reset}`);return i>0&&a.push(`${n}${S.subtle}\u2026 +${i} more command line${i!==1?"s":""}${S.reset}`),a.join(`
48
- `)}function Tc(t,e,n,s={}){let{indent:o=" ",maxLines:r=3,maxContent:i=96,includeLabels:a=!0}=s,{highlightLine:l,detectLang:c}=Vi(),u=c(t||null),{shown:d,more:f}=Sc(e,{maxLines:r,maxContent:i}),{shown:p,more:h}=Sc(n,{maxLines:r,maxContent:i}),g=[];return d.length>0&&a&&g.push(`${o}${S.subtle}before${S.reset}`),d.forEach(w=>{g.push(`${o}${S.diff_rem}- ${S.reset}${l(w,u)}${S.reset}`)}),f>0&&g.push(`${o}${S.subtle}\u2026 ${f} more removed line${f!==1?"s":""}${S.reset}`),p.length>0&&a&&g.push(`${o}${S.subtle}after${S.reset}`),p.forEach(w=>{g.push(`${o}${S.diff_add}+ ${S.reset}${l(w,u)}${S.reset}`)}),h>0&&g.push(`${o}${S.subtle}\u2026 ${h} more added line${h!==1?"s":""}${S.reset}`),g.join(`
49
- `)}function Ap(t,e,n={}){let{indent:s=" ",maxPatches:o=2,maxLinesPerSide:r=2,maxContent:i=92}=n;if(!Array.isArray(e)||e.length===0)return"";let a=[];return e.slice(0,o).forEach((l,c)=>{a.push(`${s}${S.subtle}patch ${c+1}${S.reset}`);let u=Tc(t,l.old_text,l.new_text,{indent:s+" ",maxLines:r,maxContent:i,includeLabels:!1});u&&a.push(u)}),e.length>o&&a.push(`${s}${S.subtle}\u2026 +${e.length-o} more patches${S.reset}`),a.join(`
50
- `)}function $$(t){let e=new Set,n=[];for(let s of t){let o=Ec(s.fnName).label;e.has(o)||(e.add(o),n.push(o))}return n.length===0?"":n.length<=3?n.join(`${Fe.dim} \u2192 ${Fe.reset}`):`${n.slice(0,3).join(`${Fe.dim} \u2192 ${Fe.reset}`)}${Fe.dim} \u2192 +${n.length-3}${Fe.reset}`}function Ji(t,e=!1,n=null){if(e)return`${S.error}${Xi()?"\u2716":"x"}${S.reset}`;let s=p$[t]||S.tool_default;if(n==="blink")return`${s}\x1B[5m${Xi()?"\u25CF":"*"}\x1B[25m${S.reset}`;let o=typeof n=="number"?xp[n%xp.length]:n!==null?n:Xi()?"\u25CF":"*";return`${s}${o}${S.reset}`}function k$(t,e,n=!1,s=null){let o=(t||[]).filter(c=>c&&c.canExecute!==!1);if(o.length===0)return`${Ji("",n,s)} Step ${e}`;if(o.length===1){let c=o[0],u=c.args||{},d=Sp(c.fnName,{...u,path:u._originalPath||u.path});return`${Ji(c.fnName,n,s)} ${vp(c.fnName)} ${Fe.bold}${d}${Fe.reset}`}let r=o[0].fnName,i=$$(o)||`${o.length} tools`,a=o.slice(0,2).map(c=>Sp(c.fnName,c.args||{})).filter(Boolean).join(`${Fe.dim} \xB7 ${Fe.reset}`),l=a?` ${S.subtle}\xB7${S.reset} ${Fe.dim}${a}${Fe.reset}`:"";return`${Ji(r,n,s)} ${vp(r)} ${Fe.bold}${i}${Fe.reset}${l}`}function x$(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,52);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 s=Tp[t]||t.replace(/_/g," "),o=n?` ${Fe.dim}${n}${Fe.reset}`:"",r=`${Ji(t)} ${Fe.bold}${s}${Fe.reset}${o}`;if(t==="bash"||t==="ssh_exec"){let i=Cp(e.command,{indent:" ",maxLines:2,maxContent:108});return i?`${r}
45
+ `).map(e=>{let n=e.match(/^(\d+):\s?(.*)$/s);return n?{lineNumber:n[1],content:n[2]||""}:null}).filter(Boolean)}function w$(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:l}=Vi(),c=l(t||null),u=e.slice(0,o),d=u.map(({lineNumber:f,content:p})=>{let h=p.length>r?p.substring(0,r-1)+"\u2026":p;return`${s}${S.subtle}${f}:${S.reset} ${a(h,c)}${S.reset}`});return i&&e.length>u.length&&d.push(`${s}${S.subtle}\u2026 +${e.length-u.length} more line${e.length-u.length!==1?"s":""}${S.reset}`),d.join(`
46
+ `)}function _$(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 Sc(t,e={}){let{maxLines:n=3,maxContent:o=96}=e,r=String(t||"").split(`
47
+ `).filter((a,l,c)=>a.trim()||c.length===1||l===0),i=r.slice(0,n).map(a=>_$(a,o));return{shown:i,more:Math.max(0,r.length-i.length)}}function Cp(t,e={}){let{indent:n=" ",maxLines:o=2,maxContent:s=100}=e;if(!t)return"";let{shown:r,more:i}=Sc(t,{maxLines:o,maxContent:s});if(r.length===0)return"";let a=r.map((l,c)=>`${n}${S.subtle}${c===0?"$":">"}${S.reset} ${S.muted}${l}${S.reset}`);return i>0&&a.push(`${n}${S.subtle}\u2026 +${i} more command line${i!==1?"s":""}${S.reset}`),a.join(`
48
+ `)}function Tc(t,e,n,o={}){let{indent:s=" ",maxLines:r=3,maxContent:i=96,includeLabels:a=!0}=o,{highlightLine:l,detectLang:c}=Vi(),u=c(t||null),{shown:d,more:f}=Sc(e,{maxLines:r,maxContent:i}),{shown:p,more:h}=Sc(n,{maxLines:r,maxContent:i}),g=[];return d.length>0&&a&&g.push(`${s}${S.subtle}before${S.reset}`),d.forEach(w=>{g.push(`${s}${S.diff_rem}- ${S.reset}${l(w,u)}${S.reset}`)}),f>0&&g.push(`${s}${S.subtle}\u2026 ${f} more removed line${f!==1?"s":""}${S.reset}`),p.length>0&&a&&g.push(`${s}${S.subtle}after${S.reset}`),p.forEach(w=>{g.push(`${s}${S.diff_add}+ ${S.reset}${l(w,u)}${S.reset}`)}),h>0&&g.push(`${s}${S.subtle}\u2026 ${h} more added line${h!==1?"s":""}${S.reset}`),g.join(`
49
+ `)}function Ap(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((l,c)=>{a.push(`${o}${S.subtle}patch ${c+1}${S.reset}`);let u=Tc(t,l.old_text,l.new_text,{indent:o+" ",maxLines:r,maxContent:i,includeLabels:!1});u&&a.push(u)}),e.length>s&&a.push(`${o}${S.subtle}\u2026 +${e.length-s} more patches${S.reset}`),a.join(`
50
+ `)}function $$(t){let e=new Set,n=[];for(let o of t){let s=Ec(o.fnName).label;e.has(s)||(e.add(s),n.push(s))}return n.length===0?"":n.length<=3?n.join(`${Fe.dim} \u2192 ${Fe.reset}`):`${n.slice(0,3).join(`${Fe.dim} \u2192 ${Fe.reset}`)}${Fe.dim} \u2192 +${n.length-3}${Fe.reset}`}function Ji(t,e=!1,n=null){if(e)return`${S.error}${Xi()?"\u2716":"x"}${S.reset}`;let o=p$[t]||S.tool_default;if(n==="blink")return`${o}\x1B[5m${Xi()?"\u25CF":"*"}\x1B[25m${S.reset}`;let s=typeof n=="number"?xp[n%xp.length]:n!==null?n:Xi()?"\u25CF":"*";return`${o}${s}${S.reset}`}function k$(t,e,n=!1,o=null){let s=(t||[]).filter(c=>c&&c.canExecute!==!1);if(s.length===0)return`${Ji("",n,o)} Step ${e}`;if(s.length===1){let c=s[0],u=c.args||{},d=Sp(c.fnName,{...u,path:u._originalPath||u.path});return`${Ji(c.fnName,n,o)} ${vp(c.fnName)} ${Fe.bold}${d}${Fe.reset}`}let r=s[0].fnName,i=$$(s)||`${s.length} tools`,a=s.slice(0,2).map(c=>Sp(c.fnName,c.args||{})).filter(Boolean).join(`${Fe.dim} \xB7 ${Fe.reset}`),l=a?` ${S.subtle}\xB7${S.reset} ${Fe.dim}${a}${Fe.reset}`:"";return`${Ji(r,n,o)} ${vp(r)} ${Fe.bold}${i}${Fe.reset}${l}`}function x$(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,52);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=Tp[t]||t.replace(/_/g," "),s=n?` ${Fe.dim}${n}${Fe.reset}`:"",r=`${Ji(t)} ${Fe.bold}${o}${Fe.reset}${s}`;if(t==="bash"||t==="ssh_exec"){let i=Cp(e.command,{indent:" ",maxLines:2,maxContent:108});return i?`${r}
51
51
  ${i}`:r}if(t==="edit_file"){let i=Tc(e.path,e.old_text,e.new_text,{indent:" ",maxLines:2,maxContent:92});return i?`${r}
52
52
  ${i}`:r}if(t==="patch_file"){let i=Ap(e.path,e.patches,{indent:" ",maxPatches:2,maxLinesPerSide:1,maxContent:90});return i?`${r}
53
53
  ${i}`:r}return r}function v$(t,e=8){let n=t.split(`
54
- `),s=n.slice(0,e),o=n.length-e,r=s.map(i=>`${S.subtle} \u23BF${S.reset} ${i}`).join(`
55
- `);return o>0&&(r+=`
56
- ${S.subtle} \u2026 +${o} lines${S.reset}`),r}var Qi=["Sampling","Decoding","Attending","Inferring","Generating","Routing","Embedding","Reasoning","Tokenizing","Predicting"],Ep=Math.floor(Math.random()*Qi.length),S$=null;function E$(t){S$=t}function T$(){let t=Qi[Ep%Qi.length];return Ep++,t}function R$(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 C$(t,e,n,s){let o=String(n||""),r=Ec(t),i=` ${S.subtle}\u2502${S.reset} ${r.accent}${Fe.bold}${r.label}${S.reset} ${S.subtle}\xB7${S.reset} `;if(s){let c=o.split(`
57
- `)[0];if(c.startsWith("BLOCKED:")){let p=c.replace(/^BLOCKED:\s*/,"").replace(/\s*—.*$/,"").replace(/\s*\(hard cap:.*?\)/,"").trim().substring(0,70);return`${i}${S.muted}blocked: ${p}${S.reset}`}let u=c.replace(/^ERROR:\s*/i,"").substring(0,80),d=o.match(/\nHINT: (.+)/),f=d?`
58
- ${S.muted}${d[1].substring(0,100)}${S.reset}`:"";return`${i}${S.error}${u}${S.reset}${f}`}let a;switch(t){case"read_file":{let c=b$(o),u=c.length,d=c[c.length-1],f=d?parseInt(d.lineNumber||"0"):0,p=e.line_start||e.line_end,h=e.path?kp.basename(e.path):null,g=h?` ${S.muted}from ${h}${S.reset}`:"";p&&f>u?a=`Read lines ${e.line_start||1}\u2013${f}${g}`:a=`Read ${u} line${u!==1?"s":""}${g}`;let w=w$(e.path,c,{maxLines:4,maxContent:120});w&&(a+=`
54
+ `),o=n.slice(0,e),s=n.length-e,r=o.map(i=>`${S.subtle} \u23BF${S.reset} ${i}`).join(`
55
+ `);return s>0&&(r+=`
56
+ ${S.subtle} \u2026 +${s} lines${S.reset}`),r}var Qi=["Sampling","Decoding","Attending","Inferring","Generating","Routing","Embedding","Reasoning","Tokenizing","Predicting"],Ep=Math.floor(Math.random()*Qi.length),S$=null;function E$(t){S$=t}function T$(){let t=Qi[Ep%Qi.length];return Ep++,t}function R$(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 C$(t,e,n,o){let s=String(n||""),r=Ec(t),i=` ${S.subtle}\u2502${S.reset} ${r.accent}${Fe.bold}${r.label}${S.reset} ${S.subtle}\xB7${S.reset} `;if(o){let c=s.split(`
57
+ `)[0];if(c.startsWith("BLOCKED:")){let p=c.replace(/^BLOCKED:\s*/,"").replace(/\s*—.*$/,"").replace(/\s*\(hard cap:.*?\)/,"").trim().substring(0,70);return`${i}${S.muted}blocked: ${p}${S.reset}`}let u=c.replace(/^ERROR:\s*/i,"").substring(0,80),d=s.match(/\nHINT: (.+)/),f=d?`
58
+ ${S.muted}${d[1].substring(0,100)}${S.reset}`:"";return`${i}${S.error}${u}${S.reset}${f}`}let a;switch(t){case"read_file":{let c=b$(s),u=c.length,d=c[c.length-1],f=d?parseInt(d.lineNumber||"0"):0,p=e.line_start||e.line_end,h=e.path?kp.basename(e.path):null,g=h?` ${S.muted}from ${h}${S.reset}`:"";p&&f>u?a=`Read lines ${e.line_start||1}\u2013${f}${g}`:a=`Read ${u} line${u!==1?"s":""}${g}`;let w=w$(e.path,c,{maxLines:4,maxContent:120});w&&(a+=`
59
59
  ${w}`);break}case"write_file":{let u=(e.content||"").split(`
60
60
  `).length,d=e.path?kp.basename(e.path):null,f=d?`Wrote ${d} \xB7 ${u} line${u!==1?"s":""}`:`Wrote ${u} line${u!==1?"s":""}`,{highlightLines:p}=Vi(),h=p(e.content||"",e.path||null),g=40,w=8;if(u<=g){let k=h.map(T=>` ${T}`).join(`
61
61
  `);a=`${f}
@@ -68,42 +68,42 @@ ${k}
68
68
  `+g:"");break}case"patch_file":{let c=e.patches||[],u=c.reduce((g,w)=>g+(w.old_text||"").split(`
69
69
  `).length,0),d=c.reduce((g,w)=>g+(w.new_text||"").split(`
70
70
  `).length,0),f=e.path?Zi(e.path):null,p=f?` ${S.muted}${f}${S.reset}`:"";a=`${c.length} patch${c.length!==1?"es":""} ${S.diff_rem}\u2212${u}${S.reset} ${S.diff_add}+${d}${S.reset}${p}`;let h=Ap(e.path,c,{indent:" ",maxPatches:3,maxLinesPerSide:2,maxContent:92});h&&(a+=`
71
- ${h}`);break}case"bash":{let u=o.match(/^EXIT (\d+)/),d=o.split(`
72
- `).filter(g=>g&&!g.startsWith("EXIT ")&&!g.startsWith("HINT:")&&g.trim()),f=u?u[1]==="0"?`${S.success}\u2713${S.reset}`:`${S.error}\u2717 Exit ${u[1]}${S.reset}`:`${S.success}\u2713${S.reset}`,p=o.match(/\nHINT: (.+)/);if(p)a=`${f} ${S.muted}\u2014 ${p[1].substring(0,100)}${S.reset}`;else if(d.length===0)a=f;else{let g=u&&u[1]!=="0",w=g?d.slice(-3):d.slice(0,3),k=d.length-3,T=w.map(($,R)=>R===0?`${f} ${S.muted}${$.substring(0,120)}${S.reset}`:` ${S.muted}${$.substring(0,120)}${S.reset}`);if(k>0){let $=g?` ${S.subtle}${k} lines above\u2026${S.reset}`:` ${S.subtle}\u2026 +${k} lines${S.reset}`;g?T.unshift($):T.push($)}a=T.join(`
71
+ ${h}`);break}case"bash":{let u=s.match(/^EXIT (\d+)/),d=s.split(`
72
+ `).filter(g=>g&&!g.startsWith("EXIT ")&&!g.startsWith("HINT:")&&g.trim()),f=u?u[1]==="0"?`${S.success}\u2713${S.reset}`:`${S.error}\u2717 Exit ${u[1]}${S.reset}`:`${S.success}\u2713${S.reset}`,p=s.match(/\nHINT: (.+)/);if(p)a=`${f} ${S.muted}\u2014 ${p[1].substring(0,100)}${S.reset}`;else if(d.length===0)a=f;else{let g=u&&u[1]!=="0",w=g?d.slice(-3):d.slice(0,3),k=d.length-3,T=w.map(($,R)=>R===0?`${f} ${S.muted}${$.substring(0,120)}${S.reset}`:` ${S.muted}${$.substring(0,120)}${S.reset}`);if(k>0){let $=g?` ${S.subtle}${k} lines above\u2026${S.reset}`:` ${S.subtle}\u2026 +${k} lines${S.reset}`;g?T.unshift($):T.push($)}a=T.join(`
73
73
  `)}let h=Cp(e.command,{indent:" ",maxLines:2,maxContent:108});h&&(a=`${h}
74
- ${a}`);break}case"grep":case"search_files":{if(o.includes("(no matches)")||o==="no matches")a=`No matches${e.pattern?` ${S.muted}"${String(e.pattern).substring(0,40)}"${S.reset}`:""}`;else{let w=function(R){let C=R.indexOf(":");if(C===-1)return`${S.muted}${R.substring(0,90)}${S.reset}`;let M=R.substring(0,C),K=R.substring(C+1),z=K.match(/^(\d+)[:-](.*)/s),X=z?`:${z[1]}`:"",ae=(z?z[2]:K).trim(),Z=`${S.subtle}${c.basename(M)}${X}${S.reset}`,oe=`${S.muted}${ae.substring(0,80)}${ae.length>80?"\u2026":""}${S.reset}`;return`${Z} ${oe}`};var l=w;let c=require("path"),u=o.split(`
74
+ ${a}`);break}case"grep":case"search_files":{if(s.includes("(no matches)")||s==="no matches")a=`No matches${e.pattern?` ${S.muted}"${String(e.pattern).substring(0,40)}"${S.reset}`:""}`;else{let w=function(R){let C=R.indexOf(":");if(C===-1)return`${S.muted}${R.substring(0,90)}${S.reset}`;let M=R.substring(0,C),K=R.substring(C+1),z=K.match(/^(\d+)[:-](.*)/s),X=z?`:${z[1]}`:"",ae=(z?z[2]:K).trim(),Z=`${S.subtle}${c.basename(M)}${X}${S.reset}`,oe=`${S.muted}${ae.substring(0,80)}${ae.length>80?"\u2026":""}${S.reset}`;return`${Z} ${oe}`};var l=w;let c=require("path"),u=s.split(`
75
75
  `).filter(Boolean),d=u.length,p=new Set(u.map(R=>R.split(":")[0]).filter(Boolean)).size,h=e.pattern?` ${S.muted}"${String(e.pattern).substring(0,40)}"${S.reset}`:"",g=p>1?`${d} match${d!==1?"es":""} in ${p} files${h}`:`${d} match${d!==1?"es":""}${h}`,k=e.path?`
76
76
  ${S.subtle}path:${S.reset} ${S.muted}${String(e.path).substring(0,70)}${S.reset}`:"",T=u.slice(0,5).map((R,C)=>C===0?`${g}${k}
77
77
  ${w(R)}`:` ${w(R)}`),$=u.length-5;$>0&&T.push(` ${S.subtle}\u2026 +${$} more matches${S.reset}`),a=T.join(`
78
- `)}break}case"glob":{let c=e.pattern?` ${S.muted}${String(e.pattern).substring(0,50)}${S.reset}`:"";if(o==="(no matches)")a=`No files found${c}`;else{let u=require("path"),d=o.split(`
78
+ `)}break}case"glob":{let c=e.pattern?` ${S.muted}${String(e.pattern).substring(0,50)}${S.reset}`:"";if(s==="(no matches)")a=`No files found${c}`;else{let u=require("path"),d=s.split(`
79
79
  `).filter(Boolean),f=d.length,p=d.slice(0,8),h=f-p.length,g=p.map(k=>` ${S.muted}${k}${S.reset}`);h>0&&g.push(` ${S.subtle}\u2026 +${h} more files${S.reset}`);let w=e.path?`
80
80
  ${S.subtle}path:${S.reset} ${S.muted}${String(e.path).substring(0,70)}${S.reset}`:"";a=`${f} file${f!==1?"s":""}${c}${w}`+(g.length>0?`
81
81
  ${g.join(`
82
- `)}`:"")}break}case"list_directory":{if(o==="(empty)")a="0 entries";else{let c=o.split(`
83
- `).filter(Boolean),u=c.length,d=c.slice(0,6).join(", "),f=u-6;a=f>0?`${u} entries \u2014 ${S.muted}${d}, +${f} more${S.reset}`:`${u} entr${u!==1?"ies":"y"} \u2014 ${S.muted}${d}${S.reset}`}break}case"git_status":{let c=o.match(/Branch:\s*(\S+)/),u=o.split(`
84
- `).filter(d=>/^\s*[MADRCU?!]/.test(d)).length;a=c?`${c[1]} \xB7 ${u} change${u!==1?"s":""}`:"Done";break}case"git_diff":{let c=(o.match(/^\+[^+]/gm)||[]).length,u=(o.match(/^-[^-]/gm)||[]).length;a=c||u?`+${c} \u2212${u} lines`:"No diff";break}case"git_log":{let c=o.split(`
85
- `).filter(p=>/^commit\s+[0-9a-f]{7}/.test(p)),u=c.length,d=c[0]?c[0].replace(/^commit\s+/,"").substring(0,7):null,f=(()=>{let p=o.indexOf(c[0]||"\0");return p===-1?null:o.substring(p).split(`
86
- `).find((g,w)=>w>0&&g.trim()&&!g.startsWith("Author:")&&!g.startsWith("Date:")&&!g.startsWith("Merge:"))})();if(u===0)a="Log retrieved";else if(d&&f){let p=u>1?` ${S.muted}+${u-1} more${S.reset}`:"";a=`${d} ${S.muted}${f.trim().substring(0,60)}${S.reset}${p}`}else a=`${u} commit${u!==1?"s":""}`;break}case"git_commit":{let c=o.match(/\[[\w./\-]+ ([0-9a-f]{7,})\]/),u=o.match(/\[[\w./\-]+ [0-9a-f]+\]\s+(.+)/);a=c?`${c[1]}${u?` \u2014 ${u[1].substring(0,55)}`:""}`:"Committed";break}case"git_push":{let c=o.match(/(?:->|→)\s*(\S+)/);a=c?`\u2192 ${c[1]}`:"Pushed";break}case"git_pull":{if(/Already up.to.date/i.test(o))a="Already up to date";else{let c=(o.match(/^\+/gm)||[]).length;a=c>0?`Pulled \xB7 +${c} lines`:"Pulled"}break}case"web_fetch":{let c=o.match(/<title[^>]*>([^<]{1,80})<\/title>/i),u=o.match(/^#\s+(.{1,80})/m),d=e.url||"",f="";try{f=new URL(d).hostname}catch{f=d.substring(0,60)}let p=c?c[1].trim():u?u[1].trim():null;a=p?`${f} \u2014 ${S.muted}${p.substring(0,70)}${S.reset}`:`Fetched ${f}`;break}case"web_search":{let c=o.split(`
82
+ `)}`:"")}break}case"list_directory":{if(s==="(empty)")a="0 entries";else{let c=s.split(`
83
+ `).filter(Boolean),u=c.length,d=c.slice(0,6).join(", "),f=u-6;a=f>0?`${u} entries \u2014 ${S.muted}${d}, +${f} more${S.reset}`:`${u} entr${u!==1?"ies":"y"} \u2014 ${S.muted}${d}${S.reset}`}break}case"git_status":{let c=s.match(/Branch:\s*(\S+)/),u=s.split(`
84
+ `).filter(d=>/^\s*[MADRCU?!]/.test(d)).length;a=c?`${c[1]} \xB7 ${u} change${u!==1?"s":""}`:"Done";break}case"git_diff":{let c=(s.match(/^\+[^+]/gm)||[]).length,u=(s.match(/^-[^-]/gm)||[]).length;a=c||u?`+${c} \u2212${u} lines`:"No diff";break}case"git_log":{let c=s.split(`
85
+ `).filter(p=>/^commit\s+[0-9a-f]{7}/.test(p)),u=c.length,d=c[0]?c[0].replace(/^commit\s+/,"").substring(0,7):null,f=(()=>{let p=s.indexOf(c[0]||"\0");return p===-1?null:s.substring(p).split(`
86
+ `).find((g,w)=>w>0&&g.trim()&&!g.startsWith("Author:")&&!g.startsWith("Date:")&&!g.startsWith("Merge:"))})();if(u===0)a="Log retrieved";else if(d&&f){let p=u>1?` ${S.muted}+${u-1} more${S.reset}`:"";a=`${d} ${S.muted}${f.trim().substring(0,60)}${S.reset}${p}`}else a=`${u} commit${u!==1?"s":""}`;break}case"git_commit":{let c=s.match(/\[[\w./\-]+ ([0-9a-f]{7,})\]/),u=s.match(/\[[\w./\-]+ [0-9a-f]+\]\s+(.+)/);a=c?`${c[1]}${u?` \u2014 ${u[1].substring(0,55)}`:""}`:"Committed";break}case"git_push":{let c=s.match(/(?:->|→)\s*(\S+)/);a=c?`\u2192 ${c[1]}`:"Pushed";break}case"git_pull":{if(/Already up.to.date/i.test(s))a="Already up to date";else{let c=(s.match(/^\+/gm)||[]).length;a=c>0?`Pulled \xB7 +${c} lines`:"Pulled"}break}case"web_fetch":{let c=s.match(/<title[^>]*>([^<]{1,80})<\/title>/i),u=s.match(/^#\s+(.{1,80})/m),d=e.url||"",f="";try{f=new URL(d).hostname}catch{f=d.substring(0,60)}let p=c?c[1].trim():u?u[1].trim():null;a=p?`${f} \u2014 ${S.muted}${p.substring(0,70)}${S.reset}`:`Fetched ${f}`;break}case"web_search":{let c=s.split(`
87
87
 
88
88
  `).filter(Boolean),u=c.length,d=c[0]?c[0].split(`
89
- `)[0].replace(/^\d+\.\s*/,"").trim():null,f=d?` ${S.muted}\u2014 ${d.substring(0,70)}${S.reset}`:"";a=`${u} result${u!==1?"s":""}${f}`;break}case"task_list":a="Done";break;case"spawn_agents":{if(o.includes("Background agents started")){let d=o.match(/\bbg-[\w-]+/g),f=d?d.length:0;a=`${f} bg agent${f!==1?"s":""} started`;break}let c=(o.match(/✓ Agent/g)||[]).length,u=(o.match(/✗ Agent/g)||[]).length;a=u>0?`${c} done, ${u} failed`:`${c} agent${c!==1?"s":""} done`;break}case"switch_model":{let c=o.match(/Switched to (.+)/);a=c?`\u2192 ${c[1]}`:"Done";break}case"ssh_exec":{let u=o.startsWith("EXIT ")||o.startsWith("Command failed"),d=o.split(`
89
+ `)[0].replace(/^\d+\.\s*/,"").trim():null,f=d?` ${S.muted}\u2014 ${d.substring(0,70)}${S.reset}`:"";a=`${u} result${u!==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 c=(s.match(/✓ Agent/g)||[]).length,u=(s.match(/✗ Agent/g)||[]).length;a=u>0?`${c} done, ${u} failed`:`${c} agent${c!==1?"s":""} done`;break}case"switch_model":{let c=s.match(/Switched to (.+)/);a=c?`\u2192 ${c[1]}`:"Done";break}case"ssh_exec":{let u=s.startsWith("EXIT ")||s.startsWith("Command failed"),d=s.split(`
90
90
  `).filter(p=>p.trim()&&!p.startsWith("EXIT ")),f=u?`${S.error}\u2717${S.reset}`:`${S.success}\u2713${S.reset}`;if(d.length===0)a=f;else{if(d.length>2&&d.every(k=>/^\[/.test(k.trim()))){a=`${f} ${d.length} log lines`;break}let h=u?d.slice(-3):d.slice(0,3),g=d.length-3,w=h.map((k,T)=>T===0?`${f} ${S.muted}${k.substring(0,120)}${S.reset}`:` ${S.muted}${k.substring(0,120)}${S.reset}`);if(g>0){let k=u?` ${S.subtle}${g} lines above\u2026${S.reset}`:` ${S.subtle}\u2026 +${g} lines${S.reset}`;u?w.unshift(k):w.push(k)}a=w.join(`
91
- `)}break}default:{let c=o.split(`
92
- `).filter(u=>u.trim()&&!u.startsWith("EXIT ")&&!u.startsWith("HINT:"));if(c.length>0){let u=c[0].trim().substring(0,90),d=c.length>1?` ${S.subtle}\u2026 +${c.length-1} lines${S.reset}`:"";a=`${S.muted}${u}${S.reset}${d}`}else a=`${r.label} complete`}}return`${i}${a}${S.reset}`}function A$(t,e,n,s,o,r){let i=Math.round(s/1e3),a=i>=60?`${Math.floor(i/60)}m ${i%60}s`:`${i}s`,l=`
93
- ${S.success}\u25C6${Fe.reset} ${Fe.bold}${t}${Fe.reset}`;l+=` ${S.subtle}\u2501\u2501${S.reset} ${Fe.dim}${a}`,r.size>0&&(l+=` \xB7 ${S.warning}${r.size} file${r.size!==1?"s":""} modified${Fe.reset}`),o.size>0&&(l+=` \xB7 ${S.subtle}${o.size} scanned${Fe.reset}`),l+=Fe.reset;let c=8,u=[...r].slice(0,c),d=[...o].filter(f=>!r.has(f)).slice(0,Math.max(0,c-u.length));if(u.length>0||d.length>0){let f=require("path"),p=(()=>{try{return vc().hasUnicode()}catch{return!0}})(),h=p?"\u251C\u2500 ":"|-- ",g=p?"\u2514\u2500 ":"`-- ",w=p?"\u2502 ":"| ",k=" ",T=[],$=0;for(let M of u){let K=f.relative(process.cwd(),M)||M,z=$===0&&d.length===0&&u.length===1?k:$===u.length-1&&d.length===0?g:h;T.push(`${S.subtle} ${z}${S.reset}${S.warning}${K}${S.reset}`),$++}for(let M=0;M<d.length;M++){let K=d[M],z=f.relative(process.cwd(),K)||K,X=M===d.length-1?g:h;T.push(`${S.subtle} ${X}${S.reset}${S.subtle}${z}${Fe.reset}`)}let R=r.size,C=o.size;if(R>c||u.length+d.length<R+C){let M=R-u.length+(C-d.length-(o.size-d.length));T.push(`${S.subtle} ${g}${S.reset}${Fe.dim}\u2026 +${Math.max(0,R+C-u.length-d.length)} more${Fe.reset}`)}T.length>0&&(l+=`
91
+ `)}break}default:{let c=s.split(`
92
+ `).filter(u=>u.trim()&&!u.startsWith("EXIT ")&&!u.startsWith("HINT:"));if(c.length>0){let u=c[0].trim().substring(0,90),d=c.length>1?` ${S.subtle}\u2026 +${c.length-1} lines${S.reset}`:"";a=`${S.muted}${u}${S.reset}${d}`}else a=`${r.label} complete`}}return`${i}${a}${S.reset}`}function A$(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`,l=`
93
+ ${S.success}\u25C6${Fe.reset} ${Fe.bold}${t}${Fe.reset}`;l+=` ${S.subtle}\u2501\u2501${S.reset} ${Fe.dim}${a}`,r.size>0&&(l+=` \xB7 ${S.warning}${r.size} file${r.size!==1?"s":""} modified${Fe.reset}`),s.size>0&&(l+=` \xB7 ${S.subtle}${s.size} scanned${Fe.reset}`),l+=Fe.reset;let c=8,u=[...r].slice(0,c),d=[...s].filter(f=>!r.has(f)).slice(0,Math.max(0,c-u.length));if(u.length>0||d.length>0){let f=require("path"),p=(()=>{try{return vc().hasUnicode()}catch{return!0}})(),h=p?"\u251C\u2500 ":"|-- ",g=p?"\u2514\u2500 ":"`-- ",w=p?"\u2502 ":"| ",k=" ",T=[],$=0;for(let M of u){let K=f.relative(process.cwd(),M)||M,z=$===0&&d.length===0&&u.length===1?k:$===u.length-1&&d.length===0?g:h;T.push(`${S.subtle} ${z}${S.reset}${S.warning}${K}${S.reset}`),$++}for(let M=0;M<d.length;M++){let K=d[M],z=f.relative(process.cwd(),K)||K,X=M===d.length-1?g:h;T.push(`${S.subtle} ${X}${S.reset}${S.subtle}${z}${Fe.reset}`)}let R=r.size,C=s.size;if(R>c||u.length+d.length<R+C){let M=R-u.length+(C-d.length-(s.size-d.length));T.push(`${S.subtle} ${g}${S.reset}${Fe.dim}\u2026 +${Math.max(0,R+C-u.length-d.length)} more${Fe.reset}`)}T.length>0&&(l+=`
94
94
  `+T.join(`
95
- `))}return l}Op.exports={C:Fe,formatToolCall:x$,formatResult:v$,getToolSpinnerText:R$,formatToolSummary:C$,formatSectionHeader:k$,formatMilestone:A$,stripAnsiControlSequences:Rp,sanitizeFinalAnswer:g$,getThinkingVerb:T$,setActiveModelForSpinner:E$,THINKING_VERBS:Qi}});var xt=ne((iM,Np)=>{var{T:Nn}=kn(),ea=Nn,O$=require("path"),Mp=["01100110","01111110","01111110","01011010","01111110","00111100"];function P$(t,e){let n=[];for(let s=0;s<t.length;s+=2){let o="";for(let r=0;r<t[0].length;r++){let i=t[s][r]==="1",a=s+1<t.length&&t[s+1][r]==="1";i&&a?o+=`${e}\u2588\x1B[0m`:i&&!a?o+=`${e}\u2580\x1B[0m`:!i&&a?o+=`${e}\u2584\x1B[0m`:o+=" "}n.push(o)}return n}function M$(t,e,n={}){let s=ea.bold,o=ea.reset,r=P$(Mp,Nn.banner_logo),i=n.yolo?` ${s}${Nn.banner_yolo}\u26A1 YOLO${o}`:"",a=n.gemini?` ${s}${Nn.banner_gemini}\u2726 GEMINI${o}`:"",l=Yi().version,c=e?O$.basename(e):null,u=`${Nn.muted}[${t||"model"}]${o}`,d=`${Nn.muted}[${c||"workspace"}]${o}`,f=[` ${Nn.banner_name}${s}nex-code${o} ${Nn.banner_version}v${l}${o}`,` ${u} ${d}`,` ${Nn.banner_logo}${s}terminal workbench${o} ${Nn.muted}\xB7 /help${o}${a}${i}`,` ${ea.dim}${"\u2014".repeat(50)}${o}`],p=Math.max(r.length,f.length),h=Math.floor((p-r.length)/2),g=Math.floor((p-f.length)/2),w=Mp[0].length,k=[];for(let T=0;T<p;T++){let $=r[T-h]??" ".repeat(w),R=f[T-g]??"";k.push($+R)}console.log(`
95
+ `))}return l}Op.exports={C:Fe,formatToolCall:x$,formatResult:v$,getToolSpinnerText:R$,formatToolSummary:C$,formatSectionHeader:k$,formatMilestone:A$,stripAnsiControlSequences:Rp,sanitizeFinalAnswer:g$,getThinkingVerb:T$,setActiveModelForSpinner:E$,THINKING_VERBS:Qi}});var xt=ne((iM,Np)=>{var{T:Nn}=kn(),ea=Nn,O$=require("path"),Mp=["01100110","01111110","01111110","01011010","01111110","00111100"];function P$(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 M$(t,e,n={}){let o=ea.bold,s=ea.reset,r=P$(Mp,Nn.banner_logo),i=n.yolo?` ${o}${Nn.banner_yolo}\u26A1 YOLO${s}`:"",a=n.gemini?` ${o}${Nn.banner_gemini}\u2726 GEMINI${s}`:"",l=Yi().version,c=e?O$.basename(e):null,u=`${Nn.muted}[${t||"model"}]${s}`,d=`${Nn.muted}[${c||"workspace"}]${s}`,f=[` ${Nn.banner_name}${o}nex-code${s} ${Nn.banner_version}v${l}${s}`,` ${u} ${d}`,` ${Nn.banner_logo}${o}terminal workbench${s} ${Nn.muted}\xB7 /help${s}${a}${i}`,` ${ea.dim}${"\u2014".repeat(50)}${s}`],p=Math.max(r.length,f.length),h=Math.floor((p-r.length)/2),g=Math.floor((p-f.length)/2),w=Mp[0].length,k=[];for(let T=0;T<p;T++){let $=r[T-h]??" ".repeat(w),R=f[T-g]??"";k.push($+R)}console.log(`
96
96
  `+k.join(`
97
- `))}var{Spinner:N$,MultiProgress:L$,TaskProgress:I$,ToolProgress:j$,setActiveTaskProgress:D$,getActiveTaskProgress:q$,cleanupTerminal:F$}=Ls(),{formatToolCall:B$,formatResult:U$,getToolSpinnerText:W$,formatToolSummary:H$,formatSectionHeader:G$,formatMilestone:Y$,getThinkingVerb:z$,setActiveModelForSpinner:K$}=Pp();Np.exports={C:ea,banner:M$,Spinner:N$,MultiProgress:L$,TaskProgress:I$,ToolProgress:j$,setActiveTaskProgress:D$,getActiveTaskProgress:q$,cleanupTerminal:F$,formatToolCall:B$,formatResult:U$,getToolSpinnerText:W$,formatToolSummary:H$,formatSectionHeader:G$,formatMilestone:Y$,getThinkingVerb:z$,setActiveModelForSpinner:K$}});var Ds=ne((aM,Lp)=>{async function V$(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 s=await new Promise((r,i)=>{let a=[];n.on("data",l=>a.push(l)),n.on("end",()=>r(Buffer.concat(a).toString("utf8"))),n.on("error",i)}),o=JSON.parse(s);return e(o)||s||t.message}catch{return t.message}}var Rc=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,s={}){throw new Error(`${this.name}: chat() not implemented`)}async stream(e,n,s={}){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`)}};Lp.exports={BaseProvider:Rc,readStreamErrorBody:V$}});var Lo=ne((lM,jp)=>{var Mo=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")}},No=class{constructor(e,n={}){this.onToken=e,this.callbacks=n,this.content="",this.buffer=""}feed(e){this.buffer+=e;let n=this.buffer.split(`
98
- `);this.buffer=n.pop()||"";for(let s of n){let o=this.parseLine(s);if(o?.done)return o}return{done:!1}}flush(){return this.buffer.trim()&&(this.parseLine(this.buffer),this.buffer=""),this.getResult()}parseLine(e){throw new Error("parseLine() not implemented")}getResult(){throw new Error("getResult() not implemented")}},ta=class extends No{constructor(e,n={}){super(e,n),this.toolCallsMap={}}parseLine(e){let n=e.trim();if(!n||!n.startsWith("data: "))return{done:!1};let s=n.slice(6);if(s==="[DONE]")return{done:!0,result:this.getResult()};let o;try{o=JSON.parse(s)}catch{return{done:!1}}let r=o.choices?.[0]?.delta;if(!r)return{done:!1};if(r.content&&(this.onToken(r.content),this.content+=r.content),r.tool_calls)for(let i of r.tool_calls){let a;i.index!==void 0&&i.index!==null?a=i.index:i.id?a=`id:${i.id}`:a=0,this.toolCallsMap[a]||(this.toolCallsMap[a]={id:i.id||"",name:"",arguments:""}),i.id&&(this.toolCallsMap[a].id=i.id),i.function?.name&&(this.toolCallsMap[a].name+=i.function.name),i.function?.arguments&&(this.toolCallsMap[a].arguments+=i.function.arguments)}return{done:!1}}getResult(){return{content:this.content,tool_calls:Object.values(this.toolCallsMap).filter(e=>e.name).map(e=>({id:e.id||`call-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,function:{name:e.name,arguments:e.arguments}}))}}},na=class extends Mo{getEndpoint(){return"/chat/completions"}buildRequestBody({model:e,messages:n,tools:s,maxTokens:o,temperature:r,stream:i}){let a={model:e,messages:n,max_tokens:o,temperature:r};return i&&(a.stream=!0),s&&s.length>0&&(a.tools=s),a}normalizeResponse(e){let n=e.choices?.[0]?.message||{},s=(n.tool_calls||[]).map(o=>({id:o.id,function:{name:o.function.name,arguments:o.function.arguments}}));return{content:n.content||"",tool_calls:s}}createStreamParser(e,n={}){return new ta(e,n)}},sa=class extends No{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 s=n.slice(6),o;try{o=JSON.parse(s)}catch{return{done:!1}}switch(o.type){case"content_block_start":{let r=o.content_block;r?.type==="tool_use"&&(this.currentToolIndex=this.toolUses.length,this.toolUses.push({id:r.id,name:r.name,inputJson:""}));break}case"content_block_delta":{let r=o.delta;r?.type==="text_delta"&&r.text&&(this.onToken(r.text),this.content+=r.text),r?.type==="input_json_delta"&&r.partial_json!==void 0&&this.currentToolIndex>=0&&(this.toolUses[this.currentToolIndex].inputJson+=r.partial_json);break}case"content_block_stop":this.currentToolIndex=-1;break;case"message_stop":return{done:!0,result:this.getResult()}}return{done:!1}}getResult(){return{content:this.content,tool_calls:this.toolUses.filter(e=>e.name).map(e=>{let 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}}})}}},Cc="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->",oa=class extends Mo{getEndpoint(){return"/messages"}buildRequestBody({model:e,messages:n,tools:s,maxTokens:o,temperature:r,stream:i,extra:a}){let l={model:e,messages:n,max_tokens:o,temperature:r};if(i&&(l.stream=!0),a?.system){let c=a.system,u=c.indexOf(Cc);if(u!==-1){let d=c.slice(0,u).trimEnd(),f=c.slice(u+Cc.length).trimStart();l.system=[{type:"text",text:d},{type:"text",text:f,cache_control:{type:"ephemeral"}}]}else l.system=c}return s&&s.length>0&&(l.tools=s),l}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="",s=[];for(let o of e.content||[])o.type==="text"?n+=o.text:o.type==="tool_use"&&s.push({id:o.id,function:{name:o.name,arguments:o.input}});return{content:n,tool_calls:s}}createStreamParser(e,n={}){return new sa(e,n)}};function Ip(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 ra=class extends No{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:Ip(e.function?.arguments??e.arguments)}}))}}},ia=class extends Mo{getEndpoint(){return"/api/chat"}buildRequestBody({model:e,messages:n,tools:s,maxTokens:o,temperature:r,stream:i,extra:a}){let l={model:e,messages:n,stream:i,options:{temperature:r,num_predict:o,repeat_penalty:a?.repeat_penalty??1.05}};return s&&s.length>0&&(l.tools=s),l}normalizeResponse(e){let n=e.message||{};return{content:n.content||"",tool_calls:(n.tool_calls||[]).map((s,o)=>({id:s.id||`ollama-${Date.now()}-${o}`,function:{name:s.function?.name||s.name||"unknown",arguments:Ip(s.function?.arguments??s.arguments)}}))}}createStreamParser(e,n={}){return new ra(e,n)}},X$=new na,J$=new oa,Z$=new ia;jp.exports={ANTHROPIC_CACHE_BOUNDARY:Cc,WireProtocol:Mo,StreamParser:No,OpenAICompatibleProtocol:na,AnthropicProtocol:oa,OllamaChatProtocol:ia,OpenAIStreamParser:ta,AnthropicStreamParser:sa,OllamaStreamParser:ra,openaiProtocol:X$,anthropicProtocol:J$,ollamaProtocol:Z$}});var qp=ne((cM,Dp)=>{var aa=require("axios"),Q$=require("http"),ek=require("https"),{BaseProvider:tk,readStreamErrorBody:nk}=Ds(),{ollamaProtocol:qs}=Lo(),la=new Q$.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),ca=new ek.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),ua={"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-v4-pro:cloud":{id:"deepseek-v4-pro:cloud",name:"DeepSeek V4 Pro",maxTokens:16384,contextWindow:1048576,capability:"general",speed:"balanced",quality:96,recommendedFor:["coding","reasoning","review"]},"deepseek-v4-flash:cloud":{id:"deepseek-v4-flash:cloud",name:"DeepSeek V4 Flash",maxTokens:16384,contextWindow:1048576,capability:"general",speed:"fast",quality:90,recommendedFor:["coding","quick-fix","fallback"]},"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}},Ac={coding:["qwen3-coder:480b","qwen3-coder-next","devstral-2:123b","deepseek-v4-pro:cloud"],agentic:["qwen3-coder:480b","qwen3-coder-next","devstral-2:123b","deepseek-v4-pro:cloud"],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","deepseek-v4-flash:cloud"],fallback:["devstral-small-2:24b","deepseek-v4-flash:cloud","deepseek-v3.2","qwen3.5:35b-a3b"],"open-source":["qwen3-coder:480b","devstral-2:123b","gpt-oss:120b"]};function sk(t="coding",e=5){let n=Ac[t]||Ac.coding;return n.map(o=>ua[o]).filter(Boolean).concat(Object.values(ua).filter(o=>!n.includes(o.id)).filter(o=>(o.recommendedFor||[]).includes(t))).sort((o,r)=>(r.quality||0)-(o.quality||0)).slice(0,e)}var Oc=class extends tk{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||ua,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){aa.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:la,httpsAgent:ca}).then(e=>{let n=e.data?.models||[];for(let s of n){let o=(s.name||s.model||"").replace(/:latest$/,"");!o||this.models[o]||(this.models[o]={id:o,name:s.name||o,maxTokens:16384,contextWindow:131072})}}).catch(()=>{});return}try{let n=(await aa.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:la,httpsAgent:ca})).data?.models||[];for(let s of n){let o=(s.name||s.model||"").replace(/:latest$/,"");!o||this.models[o]||(this.models[o]={id:o,name:s.name||o,maxTokens:16384,contextWindow:131072})}}catch{}}}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OLLAMA_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OLLAMA_API_KEY not set");return{Authorization:`Bearer ${e}`}}_formatMessages(e){return e.map(n=>{if(Array.isArray(n.content)){let s=[],o=[];for(let i of n.content)i.type==="text"?s.push(i.text??""):i.type==="image"&&i.data&&o.push(i.data);let r={role:n.role,content:s.join(`
99
- `)};return o.length>0&&(r.images=o),n.tool_call_id&&(r.tool_call_id=n.tool_call_id),r}return n})}async chat(e,n,s={}){await this.discoverModels();let o=s.model||this.defaultModel,r=this.getModel(o),i=s.maxTokens||r?.maxTokens||16384,a=qs.buildRequestBody({model:o,messages:this._formatMessages(e),tools:n,maxTokens:i,temperature:s.temperature??this.temperature,stream:!1,extra:{repeat_penalty:s.repeat_penalty}}),l;try{l=await aa.post(`${this.baseUrl}${qs.getEndpoint()}`,a,{timeout:s.timeout||this.timeout,headers:this._getHeaders(),httpAgent:la,httpsAgent:ca})}catch(c){if(c.name==="CanceledError"||c.name==="AbortError"||c.code==="ERR_CANCELED")throw c;let u=c.response?.status?` [HTTP ${c.response.status}]`:"",d=c.response?.data?.error||c.message;throw new Error(`API Error${u}: ${d}`)}return qs.normalizeResponse(l.data)}async stream(e,n,s={}){await this.discoverModels();let o=s.model||this.defaultModel,r=this.getModel(o),i=s.maxTokens||r?.maxTokens||16384,a=s.onToken||(()=>{}),l=s.onThinkingToken||(()=>{}),c=qs.buildRequestBody({model:o,messages:this._formatMessages(e),tools:n,maxTokens:i,temperature:s.temperature??this.temperature,stream:!0,extra:{repeat_penalty:s.repeat_penalty}}),u;try{u=await aa.post(`${this.baseUrl}${qs.getEndpoint()}`,c,{timeout:s.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:s.signal,httpAgent:la,httpsAgent:ca})}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 nk(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=qs.createStreamParser(a,{onThinkingToken:l});return new Promise((f,p)=>{s.signal&&s.signal.addEventListener("abort",()=>{u.data.destroy(),p(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",h=>{let{done:g,result:w}=d.feed(h.toString());g&&f(w)}),u.data.on("error",h=>{if(s.signal?.aborted)return;let g=new Error(`Stream error: ${h.message}`);g.code=h.code||h.name,p(g)}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return qs.normalizeResponse(e)}};Dp.exports={OllamaProvider:Oc,OLLAMA_MODELS:ua,OLLAMA_USE_CASES:Ac,getOllamaRecommendations:sk}});var Mc=ne((uM,Up)=>{var Fp=require("axios"),{BaseProvider:ok,readStreamErrorBody:rk}=Ds(),{openaiProtocol:Fs}=Lo(),Bp={"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}},Pc=class extends ok{constructor(e={}){super({name:"openai",baseUrl:e.baseUrl||"https://api.openai.com/v1",models:e.models||Bp,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 s of e){if(this._messageFormatCache.has(s)){n.push(this._messageFormatCache.get(s));continue}let o=this._getMessageCacheKey(s);if(this._messageStringCache.has(o)){let i=this._messageStringCache.get(o);this._messageFormatCache.set(s,i),n.push(i);continue}let r=this._formatSingleMessage(s);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(o,r),this._messageFormatCache.set(s,r),n.push(r)}return{messages:n}}_getMessageCacheKey(e){let n=e.role||"",s=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${n}:${s.length}:${o}`}_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(o=>o.type==="text").map(o=>o.text).join(`
100
- `)||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 s of e.content)if(s.type==="text")n.push({type:"text",text:s.text??""});else if(s.type==="image"&&s.data){let o=s.data.startsWith("data:")?s.data:`data:${s.media_type||"image/png"};base64,${s.data}`;n.push({type:"image_url",image_url:{url:o,detail:"auto"}})}return{role:"user",content:n}}return{role:e.role,content:e.content}}prepareRequestBody(e,n={}){return e}async chat(e,n,s={}){let o=s.model||this.defaultModel,r=this.getModel(o),i=s.maxTokens||r?.maxTokens||16384,{messages:a}=this.formatMessages(e),l=this.prepareRequestBody(Fs.buildRequestBody({model:o,messages:a,tools:n,maxTokens:i,temperature:s.temperature??this.temperature,stream:!1}),s),c;try{c=await Fp.post(`${this.baseUrl}${Fs.getEndpoint()}`,l,{timeout:s.timeout||this.timeout,headers:this._getHeaders()})}catch(u){if(u.name==="CanceledError"||u.name==="AbortError"||u.code==="ERR_CANCELED")throw u;let d=u.response?.status?` [HTTP ${u.response.status}]`:"",f=u.response?.data?.error?.message||u.response?.data?.error||u.message;throw new Error(`API Error${d}: ${f}`)}return Fs.normalizeResponse(c.data)}async stream(e,n,s={}){let o=s.model||this.defaultModel,r=this.getModel(o),i=s.maxTokens||r?.maxTokens||16384,a=s.onToken||(()=>{}),{messages:l}=this.formatMessages(e),c=this.prepareRequestBody(Fs.buildRequestBody({model:o,messages:l,tools:n,maxTokens:i,temperature:s.temperature??this.temperature,stream:!0}),s),u;try{u=await Fp.post(`${this.baseUrl}${Fs.getEndpoint()}`,c,{timeout:s.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:s.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 rk(f,g=>g?.error?.message||g?.error);throw new Error(`API Error${p}: ${h}`)}let d=Fs.createStreamParser(a);return new Promise((f,p)=>{s.signal&&s.signal.addEventListener("abort",()=>{u.data.destroy(),p(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",h=>{let{done:g,result:w}=d.feed(h.toString());g&&f(w)}),u.data.on("error",h=>{s.signal?.aborted||p(new Error(`Stream error: ${h.message}`))}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return Fs.normalizeResponse(e)}};Up.exports={OpenAIProvider:Pc,OPENAI_MODELS:Bp}});var Gp=ne((dM,Hp)=>{var{OpenAIProvider:ik}=Mc(),Wp={"deepseek-v4-flash":{id:"deepseek-v4-flash",name:"DeepSeek V4 Flash",maxTokens:16384,contextWindow:1048576,capability:"fast-coding",speed:"fast",quality:90,recommendedFor:["coding","quick-fix","fallback"]},"deepseek-v4-pro":{id:"deepseek-v4-pro",name:"DeepSeek V4 Pro",maxTokens:16384,contextWindow:1048576,capability:"agentic",speed:"balanced",quality:96,recommendedFor:["coding","agentic","reasoning","review"]}},Nc=class extends ik{constructor(e={}){super({name:"deepseek",baseUrl:e.baseUrl||process.env.DEEPSEEK_BASE_URL||"https://api.deepseek.com",models:e.models||Wp,defaultModel:e.defaultModel||"deepseek-v4-flash",...e})}getApiKey(){return process.env.DEEPSEEK_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("DEEPSEEK_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}prepareRequestBody(e,n={}){let s=n.thinking||process.env.DEEPSEEK_THINKING;return{...e,thinking:s!==void 0?{type:s}:{type:"disabled"}}}};Hp.exports={DeepSeekProvider:Nc,DEEPSEEK_MODELS:Wp}});var Vp=ne((fM,Kp)=>{var Yp=require("axios"),{BaseProvider:ak,readStreamErrorBody:lk}=Ds(),{anthropicProtocol:hs}=Lo(),zp={"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}},ck="2023-06-01",Lc=class extends ak{constructor(e={}){super({name:"anthropic",baseUrl:e.baseUrl||"https://api.anthropic.com/v1",models:e.models||zp,defaultModel:e.defaultModel||"claude-sonnet",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this.apiVersion=e.apiVersion||ck}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="",s=[];for(let o of e){if(o.role==="system"){n+=(n?`
97
+ `))}var{Spinner:N$,MultiProgress:L$,TaskProgress:I$,ToolProgress:j$,setActiveTaskProgress:D$,getActiveTaskProgress:q$,cleanupTerminal:F$}=Ls(),{formatToolCall:B$,formatResult:U$,getToolSpinnerText:W$,formatToolSummary:H$,formatSectionHeader:G$,formatMilestone:Y$,getThinkingVerb:z$,setActiveModelForSpinner:K$}=Pp();Np.exports={C:ea,banner:M$,Spinner:N$,MultiProgress:L$,TaskProgress:I$,ToolProgress:j$,setActiveTaskProgress:D$,getActiveTaskProgress:q$,cleanupTerminal:F$,formatToolCall:B$,formatResult:U$,getToolSpinnerText:W$,formatToolSummary:H$,formatSectionHeader:G$,formatMilestone:Y$,getThinkingVerb:z$,setActiveModelForSpinner:K$}});var Ds=ne((aM,Lp)=>{async function V$(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",l=>a.push(l)),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 Rc=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`)}};Lp.exports={BaseProvider:Rc,readStreamErrorBody:V$}});var Lo=ne((lM,jp)=>{var Mo=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")}},No=class{constructor(e,n={}){this.onToken=e,this.callbacks=n,this.content="",this.buffer=""}feed(e){this.buffer+=e;let n=this.buffer.split(`
98
+ `);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")}},ta=class extends No{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}}))}}},na=class extends Mo{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 ta(e,n)}},sa=class extends No{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}}})}}},Cc="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->",oa=class extends Mo{getEndpoint(){return"/messages"}buildRequestBody({model:e,messages:n,tools:o,maxTokens:s,temperature:r,stream:i,extra:a}){let l={model:e,messages:n,max_tokens:s,temperature:r};if(i&&(l.stream=!0),a?.system){let c=a.system,u=c.indexOf(Cc);if(u!==-1){let d=c.slice(0,u).trimEnd(),f=c.slice(u+Cc.length).trimStart();l.system=[{type:"text",text:d},{type:"text",text:f,cache_control:{type:"ephemeral"}}]}else l.system=c}return o&&o.length>0&&(l.tools=o),l}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 sa(e,n)}};function Ip(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 ra=class extends No{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:Ip(e.function?.arguments??e.arguments)}}))}}},ia=class extends Mo{getEndpoint(){return"/api/chat"}buildRequestBody({model:e,messages:n,tools:o,maxTokens:s,temperature:r,stream:i,extra:a}){let l={model:e,messages:n,stream:i,options:{temperature:r,num_predict:s,repeat_penalty:a?.repeat_penalty??1.05}};return o&&o.length>0&&(l.tools=o),l}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:Ip(o.function?.arguments??o.arguments)}}))}}createStreamParser(e,n={}){return new ra(e,n)}},X$=new na,J$=new oa,Z$=new ia;jp.exports={ANTHROPIC_CACHE_BOUNDARY:Cc,WireProtocol:Mo,StreamParser:No,OpenAICompatibleProtocol:na,AnthropicProtocol:oa,OllamaChatProtocol:ia,OpenAIStreamParser:ta,AnthropicStreamParser:sa,OllamaStreamParser:ra,openaiProtocol:X$,anthropicProtocol:J$,ollamaProtocol:Z$}});var qp=ne((cM,Dp)=>{var aa=require("axios"),Q$=require("http"),ek=require("https"),{BaseProvider:tk,readStreamErrorBody:nk}=Ds(),{ollamaProtocol:qs}=Lo(),la=new Q$.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),ca=new ek.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),ua={"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-v4-pro:cloud":{id:"deepseek-v4-pro:cloud",name:"DeepSeek V4 Pro",maxTokens:16384,contextWindow:1048576,capability:"general",speed:"balanced",quality:96,recommendedFor:["coding","reasoning","review"]},"deepseek-v4-flash:cloud":{id:"deepseek-v4-flash:cloud",name:"DeepSeek V4 Flash",maxTokens:16384,contextWindow:1048576,capability:"general",speed:"fast",quality:90,recommendedFor:["coding","quick-fix","fallback"]},"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}},Ac={coding:["qwen3-coder:480b","qwen3-coder-next","devstral-2:123b","deepseek-v4-pro:cloud"],agentic:["qwen3-coder:480b","qwen3-coder-next","devstral-2:123b","deepseek-v4-pro:cloud"],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","deepseek-v4-flash:cloud"],fallback:["devstral-small-2:24b","deepseek-v4-flash:cloud","deepseek-v3.2","qwen3.5:35b-a3b"],"open-source":["qwen3-coder:480b","devstral-2:123b","gpt-oss:120b"]};function sk(t="coding",e=5){let n=Ac[t]||Ac.coding;return n.map(s=>ua[s]).filter(Boolean).concat(Object.values(ua).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 Oc=class extends tk{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||ua,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){aa.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:la,httpsAgent:ca}).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 aa.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:la,httpsAgent:ca})).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(`
99
+ `)};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=qs.buildRequestBody({model:s,messages:this._formatMessages(e),tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!1,extra:{repeat_penalty:o.repeat_penalty}}),l;try{l=await aa.post(`${this.baseUrl}${qs.getEndpoint()}`,a,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),httpAgent:la,httpsAgent:ca})}catch(c){if(c.name==="CanceledError"||c.name==="AbortError"||c.code==="ERR_CANCELED")throw c;let u=c.response?.status?` [HTTP ${c.response.status}]`:"",d=c.response?.data?.error||c.message;throw new Error(`API Error${u}: ${d}`)}return qs.normalizeResponse(l.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||(()=>{}),l=o.onThinkingToken||(()=>{}),c=qs.buildRequestBody({model:s,messages:this._formatMessages(e),tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!0,extra:{repeat_penalty:o.repeat_penalty}}),u;try{u=await aa.post(`${this.baseUrl}${qs.getEndpoint()}`,c,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal,httpAgent:la,httpsAgent:ca})}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 nk(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=qs.createStreamParser(a,{onThinkingToken:l});return new Promise((f,p)=>{o.signal&&o.signal.addEventListener("abort",()=>{u.data.destroy(),p(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",h=>{let{done:g,result:w}=d.feed(h.toString());g&&f(w)}),u.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)}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return qs.normalizeResponse(e)}};Dp.exports={OllamaProvider:Oc,OLLAMA_MODELS:ua,OLLAMA_USE_CASES:Ac,getOllamaRecommendations:sk}});var Mc=ne((uM,Up)=>{var Fp=require("axios"),{BaseProvider:ok,readStreamErrorBody:rk}=Ds(),{openaiProtocol:Fs}=Lo(),Bp={"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}},Pc=class extends ok{constructor(e={}){super({name:"openai",baseUrl:e.baseUrl||"https://api.openai.com/v1",models:e.models||Bp,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(`
100
+ `)||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}}prepareRequestBody(e,n={}){return e}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),l=this.prepareRequestBody(Fs.buildRequestBody({model:s,messages:a,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!1}),o),c;try{c=await Fp.post(`${this.baseUrl}${Fs.getEndpoint()}`,l,{timeout:o.timeout||this.timeout,headers:this._getHeaders()})}catch(u){if(u.name==="CanceledError"||u.name==="AbortError"||u.code==="ERR_CANCELED")throw u;let d=u.response?.status?` [HTTP ${u.response.status}]`:"",f=u.response?.data?.error?.message||u.response?.data?.error||u.message;throw new Error(`API Error${d}: ${f}`)}return Fs.normalizeResponse(c.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:l}=this.formatMessages(e),c=this.prepareRequestBody(Fs.buildRequestBody({model:s,messages:l,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!0}),o),u;try{u=await Fp.post(`${this.baseUrl}${Fs.getEndpoint()}`,c,{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 rk(f,g=>g?.error?.message||g?.error);throw new Error(`API Error${p}: ${h}`)}let d=Fs.createStreamParser(a);return new Promise((f,p)=>{o.signal&&o.signal.addEventListener("abort",()=>{u.data.destroy(),p(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",h=>{let{done:g,result:w}=d.feed(h.toString());g&&f(w)}),u.data.on("error",h=>{o.signal?.aborted||p(new Error(`Stream error: ${h.message}`))}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return Fs.normalizeResponse(e)}};Up.exports={OpenAIProvider:Pc,OPENAI_MODELS:Bp}});var Gp=ne((dM,Hp)=>{var{OpenAIProvider:ik}=Mc(),Wp={"deepseek-v4-flash":{id:"deepseek-v4-flash",name:"DeepSeek V4 Flash",maxTokens:16384,contextWindow:1048576,capability:"fast-coding",speed:"fast",quality:90,recommendedFor:["coding","quick-fix","fallback"]},"deepseek-v4-pro":{id:"deepseek-v4-pro",name:"DeepSeek V4 Pro",maxTokens:16384,contextWindow:1048576,capability:"agentic",speed:"balanced",quality:96,recommendedFor:["coding","agentic","reasoning","review"]}},Nc=class extends ik{constructor(e={}){super({name:"deepseek",baseUrl:e.baseUrl||process.env.DEEPSEEK_BASE_URL||"https://api.deepseek.com",models:e.models||Wp,defaultModel:e.defaultModel||"deepseek-v4-flash",...e})}getApiKey(){return process.env.DEEPSEEK_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("DEEPSEEK_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}prepareRequestBody(e,n={}){let o=n.thinking||process.env.DEEPSEEK_THINKING;return{...e,thinking:o!==void 0?{type:o}:{type:"disabled"}}}};Hp.exports={DeepSeekProvider:Nc,DEEPSEEK_MODELS:Wp}});var Vp=ne((fM,Kp)=>{var Yp=require("axios"),{BaseProvider:ak,readStreamErrorBody:lk}=Ds(),{anthropicProtocol:hs}=Lo(),zp={"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}},ck="2023-06-01",Lc=class extends ak{constructor(e={}){super({name:"anthropic",baseUrl:e.baseUrl||"https://api.anthropic.com/v1",models:e.models||zp,defaultModel:e.defaultModel||"claude-sonnet",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this.apiVersion=e.apiVersion||ck}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?`
101
101
 
102
- `:"")+o.content;continue}if(o.role!=="system"&&o.role!=="tool"&&this._messageFormatCache.has(o)){s.push(this._messageFormatCache.get(o));continue}let r=this._formatSingleMessage(o,s);if(r){if(o.role!=="system"&&o.role!=="tool"&&this._messageStringCache.size<this._maxCacheSize){let i=this._getMessageCacheKey(o);this._messageStringCache.set(i,r),this._messageFormatCache.set(o,r)}s.push(r)}}for(let o=s.length-1;o>0;o--)s[o].role==="user"&&s[o-1].role==="user"&&s.splice(o,0,{role:"assistant",content:[{type:"text",text:"[continuing]"}]});return{messages:s,system:n}}_getMessageCacheKey(e){let n=e.role||"",s=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${n}:${s.length}:${o}`}_formatSingleMessage(e,n=[]){if(e.role==="assistant"){let s=[];if(e.content&&s.push({type:"text",text:e.content}),e.tool_calls)for(let o of e.tool_calls)s.push({type:"tool_use",id:o.id||`toolu-${Date.now()}`,name:o.function.name,input:typeof o.function.arguments=="string"?JSON.parse(o.function.arguments||"{}"):o.function.arguments||{}});return{role:"assistant",content:s.length>0?s:[{type:"text",text:""}]}}if(e.role==="tool"){let s=n[n.length-1],o;if(Array.isArray(e.content)){let i=[];for(let a of e.content)a.type==="text"?i.push({type:"text",text:a.text??""}):a.type==="image"&&a.data&&i.push({type:"image",source:{type:"base64",media_type:a.media_type||"image/png",data:a.data}});o=i}else o=typeof e.content=="string"?e.content:JSON.stringify(e.content);let r={type:"tool_result",tool_use_id:e.tool_call_id,content:o};return s&&s.role==="user"&&Array.isArray(s.content)&&s.content[0]?.type==="tool_result"?(s.content.push(r),null):{role:"user",content:[r]}}if(Array.isArray(e.content)){let s=[];for(let o of e.content)o.type==="text"?s.push({type:"text",text:o.text??""}):o.type==="image"&&o.data&&s.push({type:"image",source:{type:"base64",media_type:o.media_type||"image/png",data:o.data}});return{role:"user",content:s}}return{role:"user",content:e.content}}formatTools(e){return hs.formatTools(e)}_resolveModelId(e){return this.getModel(e)?.id||e}async chat(e,n,s={}){let o=s.model||this.defaultModel,r=this._resolveModelId(o),i=this.getModel(o),a=s.maxTokens||i?.maxTokens||8192,{messages:l,system:c}=this.formatMessages(e),u=this.formatTools(n),d=hs.buildRequestBody({model:r,messages:l,tools:u,maxTokens:a,temperature:s.temperature??this.temperature,stream:!1,extra:{system:c}}),f;try{f=await Yp.post(`${this.baseUrl}${hs.getEndpoint()}`,d,{timeout:s.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 hs.normalizeResponse(f.data)}async stream(e,n,s={}){let o=s.model||this.defaultModel,r=this._resolveModelId(o),i=this.getModel(o),a=s.maxTokens||i?.maxTokens||8192,l=s.onToken||(()=>{}),{messages:c,system:u}=this.formatMessages(e),d=this.formatTools(n),f=hs.buildRequestBody({model:r,messages:c,tools:d,maxTokens:a,temperature:s.temperature??this.temperature,stream:!0,extra:{system:u}}),p;try{p=await Yp.post(`${this.baseUrl}${hs.getEndpoint()}`,f,{timeout:s.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:s.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}]`:"",k=await lk(g,T=>T?.error?.message||T?.error);throw new Error(`API Error${w}: ${k}`)}let h=hs.createStreamParser(l);return new Promise((g,w)=>{s.signal&&s.signal.addEventListener("abort",()=>{p.data.destroy(),w(new DOMException("The operation was aborted","AbortError"))},{once:!0}),p.data.on("data",k=>{let{done:T,result:$}=h.feed(k.toString());T&&g($)}),p.data.on("error",k=>{s.signal?.aborted||w(new Error(`Stream error: ${k.message}`))}),p.data.on("end",()=>{g(h.flush())})})}normalizeResponse(e){return hs.normalizeResponse(e)}};Kp.exports={AnthropicProvider:Lc,ANTHROPIC_MODELS:zp}});var Qp=ne((pM,Zp)=>{var Xp=require("axios"),{BaseProvider:uk,readStreamErrorBody:dk}=Ds(),{openaiProtocol:Bs}=Lo(),Jp={"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}},Ic=class extends uk{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||Jp,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 s of e){if(this._messageFormatCache.has(s)){n.push(this._messageFormatCache.get(s));continue}let o=this._getMessageCacheKey(s);if(this._messageStringCache.has(o)){let i=this._messageStringCache.get(o);this._messageFormatCache.set(s,i),n.push(i);continue}let r=this._formatSingleMessage(s);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(o,r),this._messageFormatCache.set(s,r),n.push(r)}return{messages:n}}_getMessageCacheKey(e){let n=e.role||"",s=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${n}:${s.length}:${o}`}_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 s of e.content)if(s.type==="text")n.push({type:"text",text:s.text??""});else if(s.type==="image"&&s.data){let o=s.data.startsWith("data:")?s.data:`data:${s.media_type||"image/png"};base64,${s.data}`;n.push({type:"image_url",image_url:{url:o,detail:"auto"}})}return{role:"user",content:n}}return{role:e.role,content:e.content}}async chat(e,n,s={}){let o=s.model||this.defaultModel,r=this.getModel(o),i=s.maxTokens||r?.maxTokens||8192,{messages:a}=this.formatMessages(e),l=Bs.buildRequestBody({model:o,messages:a,tools:n,maxTokens:i,temperature:s.temperature??this.temperature,stream:!1}),c;try{c=await Xp.post(`${this.baseUrl}${Bs.getEndpoint()}`,l,{timeout:s.timeout||this.timeout,headers:this._getHeaders()})}catch(u){if(u.name==="CanceledError"||u.name==="AbortError"||u.code==="ERR_CANCELED")throw u;let d=u.response?.status?` [HTTP ${u.response.status}]`:"",f=u.response?.data?.error?.message||u.response?.data?.error||u.message;throw new Error(`API Error${d}: ${f}`)}return Bs.normalizeResponse(c.data)}async stream(e,n,s={}){let o=s.model||this.defaultModel,r=this.getModel(o),i=s.maxTokens||r?.maxTokens||8192,a=s.onToken||(()=>{}),{messages:l}=this.formatMessages(e),c=Bs.buildRequestBody({model:o,messages:l,tools:n,maxTokens:i,temperature:s.temperature??this.temperature,stream:!0}),u;try{u=await Xp.post(`${this.baseUrl}${Bs.getEndpoint()}`,c,{timeout:s.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:s.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 dk(f,g=>g?.error?.message||g?.error);throw new Error(`API Error${p}: ${h}`)}let d=Bs.createStreamParser(a);return new Promise((f,p)=>{s.signal&&s.signal.addEventListener("abort",()=>{u.data.destroy(),p(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",h=>{let{done:g,result:w}=d.feed(h.toString());g&&f(w)}),u.data.on("error",h=>{s.signal?.aborted||p(new Error(`Stream error: ${h.message}`))}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return Bs.normalizeResponse(e)}};Zp.exports={GeminiProvider:Ic,GEMINI_MODELS:Jp}});var nh=ne((hM,th)=>{var da=require("axios"),{BaseProvider:fk,readStreamErrorBody:pk}=Ds(),{ollamaProtocol:Us}=Lo(),eh="http://localhost:11434",jc=class extends fk{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||eh,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 da.get(`${this.baseUrl}/api/tags`,{timeout:5e3})).data?.models||[];this.models={};for(let s of n){let o=s.name||s.model;if(!o)continue;let r=o.replace(/:latest$/,""),i=32768;try{let a=await da.post(`${this.baseUrl}/api/show`,{name:o},{timeout:5e3}),l=a.data?.model_info||a.data?.details||{};i=l["general.context_length"]||l["llama.context_length"]||this._parseContextFromModelfile(a.data?.modelfile)||32768}catch{}this.models[r]={id:r,name:s.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 s=[],o=[];for(let i of n.content)i.type==="text"?s.push(i.text??""):i.type==="image"&&i.data&&o.push(i.data);let r={role:"user",content:s.join(`
103
- `)};return o.length>0&&(r.images=o),r}return n})}async chat(e,n,s={}){this._modelsLoaded||await this.loadModels();let o=s.model||this.defaultModel;if(!o)throw new Error("No local model available. Is Ollama running?");let r=Us.buildRequestBody({model:o,messages:this._formatMessages(e),tools:n,maxTokens:s.maxTokens||8192,temperature:s.temperature??this.temperature,stream:!1}),i;try{i=await da.post(`${this.baseUrl}${Us.getEndpoint()}`,r,{timeout:s.timeout||this.timeout})}catch(a){if(a.name==="CanceledError"||a.name==="AbortError"||a.code==="ERR_CANCELED")throw a;let l=a.response?.status?` [HTTP ${a.response.status}]`:"",c=a.response?.data?.error||a.message;throw new Error(`API Error${l}: ${c}`)}return Us.normalizeResponse(i.data)}async stream(e,n,s={}){this._modelsLoaded||await this.loadModels();let o=s.model||this.defaultModel;if(!o)throw new Error("No local model available. Is Ollama running?");let r=s.onToken||(()=>{}),i=Us.buildRequestBody({model:o,messages:this._formatMessages(e),tools:n,maxTokens:s.maxTokens||8192,temperature:s.temperature??this.temperature,stream:!0}),a;try{a=await da.post(`${this.baseUrl}${Us.getEndpoint()}`,i,{timeout:s.timeout||this.timeout,responseType:"stream",signal:s.signal})}catch(c){if(c.name==="CanceledError"||c.name==="AbortError"||c.code==="ERR_CANCELED")throw c;let u=c.response?.status?` [HTTP ${c.response.status}]`:"",d=await pk(c,f=>f?.error);throw new Error(`API Error${u}: ${d}`)}let l=Us.createStreamParser(r);return new Promise((c,u)=>{s.signal&&s.signal.addEventListener("abort",()=>{a.data.destroy(),u(new DOMException("The operation was aborted","AbortError"))},{once:!0}),a.data.on("data",d=>{let{done:f,result:p}=l.feed(d.toString());f&&c(p)}),a.data.on("error",d=>{s.signal?.aborted||u(new Error(`Stream error: ${d.message}`))}),a.data.on("end",()=>{c(l.flush())})})}normalizeResponse(e){return Us.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}};th.exports={LocalProvider:jc,DEFAULT_LOCAL_URL:eh}});var Ws=ne((mM,oh)=>{"use strict";var Zt=require("fs"),sh=require("path");function hk(t){if(!t||isNaN(t))return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function mk(t){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}catch{let e=Date.now()+t;for(;Date.now()<e;);}}function gk(t,e){let n=sh.dirname(t),s=sh.join(n,`.nex-tmp.${process.pid}.${Date.now()}`);try{Zt.existsSync(n)||Zt.mkdirSync(n,{recursive:!0,mode:448}),Zt.writeFileSync(s,e,{encoding:"utf-8",mode:384}),Zt.renameSync(s,t)}catch(o){try{Zt.unlinkSync(s)}catch{}throw o}}function yk(t,e,{timeout:n=5e3,retryMs:s=50}={}){let o=t+".lock",r=Date.now()+n;for(;;){let i=-1;try{i=Zt.openSync(o,"wx"),Zt.writeSync(i,Buffer.from(String(process.pid))),Zt.closeSync(i),i=-1;try{return e()}finally{try{Zt.unlinkSync(o)}catch{}}}catch(a){if(i!==-1)try{Zt.closeSync(i)}catch{}if(a.code!=="EEXIST")throw a;try{let l=Zt.readFileSync(o,"utf-8").trim(),c=parseInt(l,10);if(!hk(c)){try{Zt.unlinkSync(o)}catch{}continue}}catch(l){if(l.code&&l.code!=="ENOENT")throw l;continue}if(Date.now()>=r){try{Zt.unlinkSync(o)}catch{}return e()}mk(s)}}}oh.exports={atomicWrite:gk,withFileLockSync:yk}});var ma=ne((gM,dh)=>{var Io=require("fs"),Dc=require("path"),{T:fa}=kn(),{atomicWrite:bk,withFileLockSync:wk}=Ws(),rh={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}},deepseek:{"deepseek-v4-flash":{input:.14,output:.28},"deepseek-v4-pro":{input:.435,output:.87}},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-v4-pro:cloud":{input:0,output:0},"deepseek-v4-flash:cloud":{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:{}},_k=new Set(["ollama","local"]),$k=new Set(["openai","deepseek","anthropic","gemini"]),ha=[],ms={},pa=new Set;function _r(t){let e=String(t||"").toLowerCase();return _k.has(e)?{provider:e,tier:"affordable",paid:!1,label:e==="local"?"local open model":"open-model path",detail:e==="local"?"runs through a local Ollama server with no per-token API charge":"recommended affordable path for open coding models"}:$k.has(e)?{provider:e,tier:"premium",paid:!0,label:"premium paid provider",detail:"may incur per-token API charges; use /budget to cap spend"}:{provider:e,tier:"unknown",paid:null,label:"cost unknown",detail:"pricing is not known to nex-code"}}function kk(t){return _r(t).tier==="affordable"}function xk(t){return _r(t).tier==="premium"}function vk(t){let e=_r(t);return`${e.label} \u2014 ${e.detail}`}function Sk(t,e,n,s,o=0){if(ha.push({provider:t,model:e,input:n,output:s,cacheRead:o}),ms[t]!==void 0){let r=ch(t);if(!r.allowed)process.stderr.write(`${fa.yellow}\u26A0 Budget limit reached for ${t}: $${r.spent.toFixed(2)} / $${r.limit.toFixed(2)}${fa.reset}
102
+ `:"")+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 hs.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:l,system:c}=this.formatMessages(e),u=this.formatTools(n),d=hs.buildRequestBody({model:r,messages:l,tools:u,maxTokens:a,temperature:o.temperature??this.temperature,stream:!1,extra:{system:c}}),f;try{f=await Yp.post(`${this.baseUrl}${hs.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 hs.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,l=o.onToken||(()=>{}),{messages:c,system:u}=this.formatMessages(e),d=this.formatTools(n),f=hs.buildRequestBody({model:r,messages:c,tools:d,maxTokens:a,temperature:o.temperature??this.temperature,stream:!0,extra:{system:u}}),p;try{p=await Yp.post(`${this.baseUrl}${hs.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}]`:"",k=await lk(g,T=>T?.error?.message||T?.error);throw new Error(`API Error${w}: ${k}`)}let h=hs.createStreamParser(l);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",k=>{let{done:T,result:$}=h.feed(k.toString());T&&g($)}),p.data.on("error",k=>{o.signal?.aborted||w(new Error(`Stream error: ${k.message}`))}),p.data.on("end",()=>{g(h.flush())})})}normalizeResponse(e){return hs.normalizeResponse(e)}};Kp.exports={AnthropicProvider:Lc,ANTHROPIC_MODELS:zp}});var Qp=ne((pM,Zp)=>{var Xp=require("axios"),{BaseProvider:uk,readStreamErrorBody:dk}=Ds(),{openaiProtocol:Bs}=Lo(),Jp={"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}},Ic=class extends uk{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||Jp,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),l=Bs.buildRequestBody({model:s,messages:a,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!1}),c;try{c=await Xp.post(`${this.baseUrl}${Bs.getEndpoint()}`,l,{timeout:o.timeout||this.timeout,headers:this._getHeaders()})}catch(u){if(u.name==="CanceledError"||u.name==="AbortError"||u.code==="ERR_CANCELED")throw u;let d=u.response?.status?` [HTTP ${u.response.status}]`:"",f=u.response?.data?.error?.message||u.response?.data?.error||u.message;throw new Error(`API Error${d}: ${f}`)}return Bs.normalizeResponse(c.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:l}=this.formatMessages(e),c=Bs.buildRequestBody({model:s,messages:l,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!0}),u;try{u=await Xp.post(`${this.baseUrl}${Bs.getEndpoint()}`,c,{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 dk(f,g=>g?.error?.message||g?.error);throw new Error(`API Error${p}: ${h}`)}let d=Bs.createStreamParser(a);return new Promise((f,p)=>{o.signal&&o.signal.addEventListener("abort",()=>{u.data.destroy(),p(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",h=>{let{done:g,result:w}=d.feed(h.toString());g&&f(w)}),u.data.on("error",h=>{o.signal?.aborted||p(new Error(`Stream error: ${h.message}`))}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return Bs.normalizeResponse(e)}};Zp.exports={GeminiProvider:Ic,GEMINI_MODELS:Jp}});var nh=ne((hM,th)=>{var da=require("axios"),{BaseProvider:fk,readStreamErrorBody:pk}=Ds(),{ollamaProtocol:Us}=Lo(),eh="http://localhost:11434",jc=class extends fk{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||eh,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 da.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 da.post(`${this.baseUrl}/api/show`,{name:s},{timeout:5e3}),l=a.data?.model_info||a.data?.details||{};i=l["general.context_length"]||l["llama.context_length"]||this._parseContextFromModelfile(a.data?.modelfile)||32768}catch{}this.models[r]={id:r,name: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(`
103
+ `)};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=Us.buildRequestBody({model:s,messages:this._formatMessages(e),tools:n,maxTokens:o.maxTokens||8192,temperature:o.temperature??this.temperature,stream:!1}),i;try{i=await da.post(`${this.baseUrl}${Us.getEndpoint()}`,r,{timeout:o.timeout||this.timeout})}catch(a){if(a.name==="CanceledError"||a.name==="AbortError"||a.code==="ERR_CANCELED")throw a;let l=a.response?.status?` [HTTP ${a.response.status}]`:"",c=a.response?.data?.error||a.message;throw new Error(`API Error${l}: ${c}`)}return Us.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=Us.buildRequestBody({model:s,messages:this._formatMessages(e),tools:n,maxTokens:o.maxTokens||8192,temperature:o.temperature??this.temperature,stream:!0}),a;try{a=await da.post(`${this.baseUrl}${Us.getEndpoint()}`,i,{timeout:o.timeout||this.timeout,responseType:"stream",signal:o.signal})}catch(c){if(c.name==="CanceledError"||c.name==="AbortError"||c.code==="ERR_CANCELED")throw c;let u=c.response?.status?` [HTTP ${c.response.status}]`:"",d=await pk(c,f=>f?.error);throw new Error(`API Error${u}: ${d}`)}let l=Us.createStreamParser(r);return new Promise((c,u)=>{o.signal&&o.signal.addEventListener("abort",()=>{a.data.destroy(),u(new DOMException("The operation was aborted","AbortError"))},{once:!0}),a.data.on("data",d=>{let{done:f,result:p}=l.feed(d.toString());f&&c(p)}),a.data.on("error",d=>{o.signal?.aborted||u(new Error(`Stream error: ${d.message}`))}),a.data.on("end",()=>{c(l.flush())})})}normalizeResponse(e){return Us.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}};th.exports={LocalProvider:jc,DEFAULT_LOCAL_URL:eh}});var Ws=ne((mM,oh)=>{"use strict";var Zt=require("fs"),sh=require("path");function hk(t){if(!t||isNaN(t))return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function mk(t){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}catch{let e=Date.now()+t;for(;Date.now()<e;);}}function gk(t,e){let n=sh.dirname(t),o=sh.join(n,`.nex-tmp.${process.pid}.${Date.now()}`);try{Zt.existsSync(n)||Zt.mkdirSync(n,{recursive:!0,mode:448}),Zt.writeFileSync(o,e,{encoding:"utf-8",mode:384}),Zt.renameSync(o,t)}catch(s){try{Zt.unlinkSync(o)}catch{}throw s}}function yk(t,e,{timeout:n=5e3,retryMs:o=50}={}){let s=t+".lock",r=Date.now()+n;for(;;){let i=-1;try{i=Zt.openSync(s,"wx"),Zt.writeSync(i,Buffer.from(String(process.pid))),Zt.closeSync(i),i=-1;try{return e()}finally{try{Zt.unlinkSync(s)}catch{}}}catch(a){if(i!==-1)try{Zt.closeSync(i)}catch{}if(a.code!=="EEXIST")throw a;try{let l=Zt.readFileSync(s,"utf-8").trim(),c=parseInt(l,10);if(!hk(c)){try{Zt.unlinkSync(s)}catch{}continue}}catch(l){if(l.code&&l.code!=="ENOENT")throw l;continue}if(Date.now()>=r){try{Zt.unlinkSync(s)}catch{}return e()}mk(o)}}}oh.exports={atomicWrite:gk,withFileLockSync:yk}});var ma=ne((gM,dh)=>{var Io=require("fs"),Dc=require("path"),{T:fa}=kn(),{atomicWrite:bk,withFileLockSync:wk}=Ws(),rh={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}},deepseek:{"deepseek-v4-flash":{input:.14,output:.28},"deepseek-v4-pro":{input:.435,output:.87}},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-v4-pro:cloud":{input:0,output:0},"deepseek-v4-flash:cloud":{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:{}},_k=new Set(["ollama","local"]),$k=new Set(["openai","deepseek","anthropic","gemini"]),ha=[],ms={},pa=new Set;function _r(t){let e=String(t||"").toLowerCase();return _k.has(e)?{provider:e,tier:"affordable",paid:!1,label:e==="local"?"local open model":"open-model path",detail:e==="local"?"runs through a local Ollama server with no per-token API charge":"recommended affordable path for open coding models"}:$k.has(e)?{provider:e,tier:"premium",paid:!0,label:"premium paid provider",detail:"may incur per-token API charges; use /budget to cap spend"}:{provider:e,tier:"unknown",paid:null,label:"cost unknown",detail:"pricing is not known to nex-code"}}function kk(t){return _r(t).tier==="affordable"}function xk(t){return _r(t).tier==="premium"}function vk(t){let e=_r(t);return`${e.label} \u2014 ${e.detail}`}function Sk(t,e,n,o,s=0){if(ha.push({provider:t,model:e,input:n,output:o,cacheRead:s}),ms[t]!==void 0){let r=ch(t);if(!r.allowed)process.stderr.write(`${fa.yellow}\u26A0 Budget limit reached for ${t}: $${r.spent.toFixed(2)} / $${r.limit.toFixed(2)}${fa.reset}
104
104
  `);else if(r.limit>0&&r.spent>=r.limit*.8){let i=`${t}:${r.limit}:80`;pa.has(i)||(pa.add(i),process.stderr.write(`${fa.yellow}Budget warning for ${t}: $${r.spent.toFixed(2)} / $${r.limit.toFixed(2)} used. Use /budget ${t} <amount> to raise the cap or /model ollama:<model> for the affordable path.${fa.reset}
105
- `))}}}function qc(t,e){let n=rh[t];return n?n[e]||{input:0,output:0}:{input:0,output:0}}function ih(t){let e=qc(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function ah(){let t={};for(let i of ha){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:ih(i)})),n=e.reduce((i,a)=>i+a.cost,0),s=e.reduce((i,a)=>i+a.input,0),o=e.reduce((i,a)=>i+a.output,0),r=e.reduce((i,a)=>i+(a.cacheRead||0),0);return{totalCost:n,totalInput:s,totalOutput:o,totalCacheRead:r,breakdown:e}}function Ek(){let{totalCost:t,totalInput:e,totalOutput:n,breakdown:s}=ah();if(s.length===0)return"No token usage recorded this session.";let o=[];o.push("Session Token Usage:"),o.push("");for(let r of s){let i=r.cost>0?`$${r.cost.toFixed(4)}`:"free",a=_r(r.provider);o.push(` ${r.provider}:${r.model}`),o.push(` Path: ${a.label}`),o.push(` Input: ${r.input.toLocaleString()} tokens`),o.push(` Output: ${r.output.toLocaleString()} tokens`),o.push(` Cost: ${i}`)}return o.push(""),o.push(` Total: ${e.toLocaleString()} in + ${n.toLocaleString()} out = $${t.toFixed(4)}`),o.join(`
106
- `)}function Tk(t){return!t||typeof t!="string"?0:Math.ceil(t.length/4)}function Rk(t,e,n,s){let o=qc(t,e),r=(n*o.input+s*o.output)/1e6;return r<=0?"":`[~$${r.toFixed(4)}]`}function Ck(){ha=[],pa=new Set}function Ak(t,e){ms[t]=e}function Ok(t){delete ms[t]}function Pk(){return{...ms}}function lh(t){let e=0;for(let n of ha)n.provider===t&&(e+=ih(n));return e}function ch(t){let e=lh(t),n=ms[t];if(n===void 0)return{allowed:!0,spent:e,limit:null,remaining:null};let s=Math.max(0,n-e);return{allowed:e<n,spent:e,limit:n,remaining:s}}function uh(){let t=Dc.join(process.cwd(),".nex","config.json");if(Io.existsSync(t))try{let e=JSON.parse(Io.readFileSync(t,"utf-8"));e.costLimits&&typeof e.costLimits=="object"&&(ms={...e.costLimits})}catch{}}function Mk(){let t=Dc.join(process.cwd(),".nex"),e=Dc.join(t,"config.json");Io.existsSync(t)||Io.mkdirSync(t,{recursive:!0}),wk(e,()=>{let n={};if(Io.existsSync(e))try{n=JSON.parse(Io.readFileSync(e,"utf-8"))}catch{n={}}n.costLimits=ms,bk(e,JSON.stringify(n,null,2))})}function Nk(){ms={},pa=new Set}uh();dh.exports={PRICING:rh,trackUsage:Sk,getSessionCosts:ah,formatCosts:Ek,formatCostHint:Rk,resetCosts:Ck,getPricing:qc,setCostLimit:Ak,removeCostLimit:Ok,getCostLimits:Pk,getProviderSpend:lh,checkBudget:ch,getProviderCostMode:_r,formatProviderCostMode:vk,isAffordableProvider:kk,isPremiumProvider:xk,loadCostLimits:uh,saveCostLimits:Mk,resetCostLimits:Nk,estimateTokens:Tk}});var Bc=ne((yM,mh)=>{var{BaseProvider:Lk}=Ds();function Se(t,e,n){return{id:n||`mock-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,function:{name:t,arguments:typeof e=="string"?e:JSON.stringify(e||{})}}}function Pe(t,e){return Array.isArray(t)&&t.some(n=>n?.role==="tool"&&n?.tool_call_id===e)}function Ik(t){let e=Array.isArray(t)?[...t].reverse().find(n=>n?.role==="user"):null;return e?hh(e):""}function hh(t){return t?typeof t.content=="string"?t.content:Array.isArray(t.content)?t.content.map(e=>e?.type==="text"?e.text:"").filter(Boolean).join(`
105
+ `))}}}function qc(t,e){let n=rh[t];return n?n[e]||{input:0,output:0}:{input:0,output:0}}function ih(t){let e=qc(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function ah(){let t={};for(let i of ha){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:ih(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 Ek(){let{totalCost:t,totalInput:e,totalOutput:n,breakdown:o}=ah();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",a=_r(r.provider);s.push(` ${r.provider}:${r.model}`),s.push(` Path: ${a.label}`),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(`
106
+ `)}function Tk(t){return!t||typeof t!="string"?0:Math.ceil(t.length/4)}function Rk(t,e,n,o){let s=qc(t,e),r=(n*s.input+o*s.output)/1e6;return r<=0?"":`[~$${r.toFixed(4)}]`}function Ck(){ha=[],pa=new Set}function Ak(t,e){ms[t]=e}function Ok(t){delete ms[t]}function Pk(){return{...ms}}function lh(t){let e=0;for(let n of ha)n.provider===t&&(e+=ih(n));return e}function ch(t){let e=lh(t),n=ms[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 uh(){let t=Dc.join(process.cwd(),".nex","config.json");if(Io.existsSync(t))try{let e=JSON.parse(Io.readFileSync(t,"utf-8"));e.costLimits&&typeof e.costLimits=="object"&&(ms={...e.costLimits})}catch{}}function Mk(){let t=Dc.join(process.cwd(),".nex"),e=Dc.join(t,"config.json");Io.existsSync(t)||Io.mkdirSync(t,{recursive:!0}),wk(e,()=>{let n={};if(Io.existsSync(e))try{n=JSON.parse(Io.readFileSync(e,"utf-8"))}catch{n={}}n.costLimits=ms,bk(e,JSON.stringify(n,null,2))})}function Nk(){ms={},pa=new Set}uh();dh.exports={PRICING:rh,trackUsage:Sk,getSessionCosts:ah,formatCosts:Ek,formatCostHint:Rk,resetCosts:Ck,getPricing:qc,setCostLimit:Ak,removeCostLimit:Ok,getCostLimits:Pk,getProviderSpend:lh,checkBudget:ch,getProviderCostMode:_r,formatProviderCostMode:vk,isAffordableProvider:kk,isPremiumProvider:xk,loadCostLimits:uh,saveCostLimits:Mk,resetCostLimits:Nk,estimateTokens:Tk}});var Bc=ne((yM,mh)=>{var{BaseProvider:Lk}=Ds();function Se(t,e,n){return{id:n||`mock-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,function:{name:t,arguments:typeof e=="string"?e:JSON.stringify(e||{})}}}function Pe(t,e){return Array.isArray(t)&&t.some(n=>n?.role==="tool"&&n?.tool_call_id===e)}function Ik(t){let e=Array.isArray(t)?[...t].reverse().find(n=>n?.role==="user"):null;return e?hh(e):""}function hh(t){return t?typeof t.content=="string"?t.content:Array.isArray(t.content)?t.content.map(e=>e?.type==="text"?e.text:"").filter(Boolean).join(`
107
107
  `):String(t.content||""):""}function fh(t){return Array.isArray(t)?t.filter(e=>e?.role==="user").map(e=>hh(e)).filter(Boolean).join(`
108
108
 
109
109
  `):""}var ga=null;function jk(){return ga||(ga={scenario:null,lastStep:0},ga)}var Dk=`// Scenario A fixture: refactor callback-based flow to async/await.
@@ -196,102 +196,102 @@ run()
196
196
  process.exitCode = 1;
197
197
  });
198
198
  `;function Wk(){return["# Scenario F fixture: subtle nginx typo in a sandboxed mock root.","events { worker_connections 128; }","http {"," upstream app_backend {"," server 127.0.0.1:3000;"," }"," server {"," listen 8081;"," location /api {"," proxy_pass http://app_backend;"," }"," }","}",""].join(`
199
- `)}function Hk(t){let e=String(t||"");return/malformed tool call/i.test(e)?"malformed":/Scenario I|bounded backlog same-file locate/i.test(e)?"i":/Scenario G|merge conflicts/i.test(e)?"g":/Scenario H|bounded backlog missing prompt example/i.test(e)?"h":/Scenario F|dummy systemctl|sandboxed nginx config typo/i.test(e)?"f":/Scenario E|legacy callback processor|nested callback/i.test(e)?"e":/mocked server environment|nginx/i.test(e)?"c":/discount|node\s+src\/main\.js/i.test(e)?"b":/async\s*\/\s*await|Refactor\s+app\.js/i.test(e)?"a":/tool budget|budget stop/i.test(e)?"d":null}function ph(t){let e=fh(t),n=Hk(e||Ik(t)),s=jk();!s.scenario&&n&&(s.scenario=n);let o=s.scenario||n;if(process.env.NEX_MOCK_MALFORMED_TOOL_CALL==="1"||o==="malformed"){let r=Pe(t,"m1")?1:0;return s.lastStep=Math.max(s.lastStep,r),s.lastStep<1?(s.lastStep=1,{content:"Simulating a malformed tool call to test CLI error handling.",tool_calls:[Se("read_file","}{","m1")]}):{content:"Final report: the CLI handled a malformed tool call without hanging. The tool arguments were not valid JSON, so execution was blocked and the session concluded safely.",tool_calls:[]}}if(o==="a"){let r=Pe(t,"a3")?3:Pe(t,"a2")?2:Pe(t,"a1")?1:0;return s.lastStep=Math.max(s.lastStep,r),s.lastStep<1?(s.lastStep=1,{content:"Inspecting current implementation.",tool_calls:[Se("read_file",{path:"app.js"},"a1")]}):s.lastStep<2?(s.lastStep=2,{content:"Applying async/await refactor.",tool_calls:[Se("write_file",{path:"app.js",content:Dk},"a2")]}):s.lastStep<3?(s.lastStep=3,{content:"Verifying behavior.",tool_calls:[Se("bash",{command:"node app.js"},"a3")]}):{content:"Refactored the callback-based flow to Promises + async/await and verified the script still runs successfully.",tool_calls:[]}}if(o==="b"){let r=Pe(t,"b4")?4:Pe(t,"b3")?3:Pe(t,"b2")?2:Pe(t,"b1")?1:0;return s.lastStep=Math.max(s.lastStep,r),s.lastStep<1?(s.lastStep=1,{content:"Reading the failing entry point.",tool_calls:[Se("read_file",{path:"src/main.js"},"b1")]}):s.lastStep<2?(s.lastStep=2,{content:"Locating the bug in discount calculation.",tool_calls:[Se("read_file",{path:"src/discount.js"},"b2")]}):s.lastStep<3?(s.lastStep=3,{content:"Fixing discount logic.",tool_calls:[Se("write_file",{path:"src/discount.js",content:qk},"b3")]}):s.lastStep<4?(s.lastStep=4,{content:"Verifying the fix.",tool_calls:[Se("bash",{command:"node src/main.js"},"b4")]}):{content:"Fixed the percent discount bug (10 now correctly means 10%) and verified the script runs without throwing.",tool_calls:[]}}if(o==="c"){let r=Pe(t,"c5")?5:Pe(t,"c4")?4:Pe(t,"c3")||Pe(t,"c2")?3:Pe(t,"c1")?1:0;return s.lastStep=Math.max(s.lastStep,r),s.lastStep<1?(s.lastStep=1,{content:"Inspecting nginx configuration.",tool_calls:[Se("read_file",{path:"sandbox-local/etc/nginx/nginx.conf"},"c1")]}):s.lastStep<3?(s.lastStep=3,{content:"Fixing nginx config syntax error and adding dry-run restart helper.",tool_calls:[Se("write_file",{path:"sandbox-local/etc/nginx/nginx.conf",content:Fk()},"c2"),Se("write_file",{path:"restart-nginx-dry-run.sh",content:Bk()},"c3")]}):s.lastStep<4?(s.lastStep=4,{content:"Making the restart helper executable.",tool_calls:[Se("bash",{command:"chmod +x restart-nginx-dry-run.sh"},"c4")]}):s.lastStep<5?(s.lastStep=5,{content:"Verifying dry-run restart in the sandbox.",tool_calls:[Se("bash",{command:"./restart-nginx-dry-run.sh"},"c5")]}):{content:"Fixed the nginx syntax error (missing semicolon) and added a sandbox-only dry-run restart script that validates the config then performs a fake systemctl restart.",tool_calls:[]}}if(o==="d"){let r=Pe(t,"d1")?1:0;return s.lastStep=Math.max(s.lastStep,r),s.lastStep<1?(s.lastStep=1,{content:"Investigating.",tool_calls:[Se("list_directory",{path:".",max_depth:2},"d1"),Se("glob",{pattern:"**/*.js"},"d2"),Se("grep",{pattern:"fakeApiGet",path:"."},"d3"),Se("read_file",{path:"README.md"},"d4"),Se("read_file",{path:"app.js"},"d5"),Se("search_files",{path:".",pattern:"getUserAndPosts"},"d6")]}):{content:"Final summary: tool budget enforcement worked; no further tool calls were executed.",tool_calls:[]}}if(o==="e"){let r=Pe(t,"e3")?3:Pe(t,"e2")?2:Pe(t,"e1")?1:0;return s.lastStep=Math.max(s.lastStep,r),s.lastStep<1?(s.lastStep=1,{content:"Reading the legacy callback processor.",tool_calls:[Se("read_file",{path:"processor.js"},"e1")]}):s.lastStep<2?(s.lastStep=2,{content:"Refactoring nested callbacks to async helpers without adding dependencies.",tool_calls:[Se("write_file",{path:"processor.js",content:Uk},"e2")]}):s.lastStep<3?(s.lastStep=3,{content:"Verifying the refactored processor.",tool_calls:[Se("bash",{command:"node processor.js"},"e3")]}):{content:"Refactored the nested callback processor to async/await without adding dependencies and verified the output.",tool_calls:[]}}if(o==="f"){let r=Pe(t,"f3")?3:Pe(t,"f2")?2:Pe(t,"f1")?1:0;return s.lastStep=Math.max(s.lastStep,r),s.lastStep<1?(s.lastStep=1,{content:"Reading the sandboxed nginx config.",tool_calls:[Se("read_file",{path:"mock-root/etc/nginx/nginx.conf"},"f1")]}):s.lastStep<2?(s.lastStep=2,{content:"Fixing the upstream name typo.",tool_calls:[Se("write_file",{path:"mock-root/etc/nginx/nginx.conf",content:Wk()},"f2")]}):s.lastStep<3?(s.lastStep=3,{content:"Checking the dummy service command stays sandboxed.",tool_calls:[Se("bash",{command:'PATH="$PWD/bin:$PATH" systemctl reload nginx'},"f3")]}):{content:"Fixed the sandboxed nginx upstream typo and verified only the dummy systemctl executable was invoked.",tool_calls:[]}}if(o==="g"){let r=Pe(t,"g5")?5:Pe(t,"g4")?4:Pe(t,"g3")||Pe(t,"g2")?3:Pe(t,"g1")?1:0;return s.lastStep=Math.max(s.lastStep,r),s.lastStep<1?(s.lastStep=1,{content:"Inspecting simulated conflict markers.",tool_calls:[Se("grep",{pattern:"<<<<<<<|=======|>>>>>>>",path:"."},"g1")]}):s.lastStep<3?(s.lastStep=3,{content:"Reading conflicted files.",tool_calls:[Se("read_file",{path:"service.js"},"g2"),Se("read_file",{path:"README.md"},"g3")]}):s.lastStep<5?(s.lastStep=5,{content:"Resolving conflicts by preserving configurable behavior.",tool_calls:[Se("write_file",{path:"service.js",content:`function port() { return Number(process.env.PORT || 3000); }
199
+ `)}function Hk(t){let e=String(t||"");return/malformed tool call/i.test(e)?"malformed":/Scenario I|bounded backlog same-file locate/i.test(e)?"i":/Scenario G|merge conflicts/i.test(e)?"g":/Scenario H|bounded backlog missing prompt example/i.test(e)?"h":/Scenario F|dummy systemctl|sandboxed nginx config typo/i.test(e)?"f":/Scenario E|legacy callback processor|nested callback/i.test(e)?"e":/mocked server environment|nginx/i.test(e)?"c":/discount|node\s+src\/main\.js/i.test(e)?"b":/async\s*\/\s*await|Refactor\s+app\.js/i.test(e)?"a":/tool budget|budget stop/i.test(e)?"d":null}function ph(t){let e=fh(t),n=Hk(e||Ik(t)),o=jk();!o.scenario&&n&&(o.scenario=n);let s=o.scenario||n;if(process.env.NEX_MOCK_MALFORMED_TOOL_CALL==="1"||s==="malformed"){let r=Pe(t,"m1")?1:0;return o.lastStep=Math.max(o.lastStep,r),o.lastStep<1?(o.lastStep=1,{content:"Simulating a malformed tool call to test CLI error handling.",tool_calls:[Se("read_file","}{","m1")]}):{content:"Final report: the CLI handled a malformed tool call without hanging. The tool arguments were not valid JSON, so execution was blocked and the session concluded safely.",tool_calls:[]}}if(s==="a"){let r=Pe(t,"a3")?3:Pe(t,"a2")?2:Pe(t,"a1")?1:0;return o.lastStep=Math.max(o.lastStep,r),o.lastStep<1?(o.lastStep=1,{content:"Inspecting current implementation.",tool_calls:[Se("read_file",{path:"app.js"},"a1")]}):o.lastStep<2?(o.lastStep=2,{content:"Applying async/await refactor.",tool_calls:[Se("write_file",{path:"app.js",content:Dk},"a2")]}):o.lastStep<3?(o.lastStep=3,{content:"Verifying behavior.",tool_calls:[Se("bash",{command:"node app.js"},"a3")]}):{content:"Refactored the callback-based flow to Promises + async/await and verified the script still runs successfully.",tool_calls:[]}}if(s==="b"){let r=Pe(t,"b4")?4:Pe(t,"b3")?3:Pe(t,"b2")?2:Pe(t,"b1")?1:0;return o.lastStep=Math.max(o.lastStep,r),o.lastStep<1?(o.lastStep=1,{content:"Reading the failing entry point.",tool_calls:[Se("read_file",{path:"src/main.js"},"b1")]}):o.lastStep<2?(o.lastStep=2,{content:"Locating the bug in discount calculation.",tool_calls:[Se("read_file",{path:"src/discount.js"},"b2")]}):o.lastStep<3?(o.lastStep=3,{content:"Fixing discount logic.",tool_calls:[Se("write_file",{path:"src/discount.js",content:qk},"b3")]}):o.lastStep<4?(o.lastStep=4,{content:"Verifying the fix.",tool_calls:[Se("bash",{command:"node src/main.js"},"b4")]}):{content:"Fixed the percent discount bug (10 now correctly means 10%) and verified the script runs without throwing.",tool_calls:[]}}if(s==="c"){let r=Pe(t,"c5")?5:Pe(t,"c4")?4:Pe(t,"c3")||Pe(t,"c2")?3:Pe(t,"c1")?1:0;return o.lastStep=Math.max(o.lastStep,r),o.lastStep<1?(o.lastStep=1,{content:"Inspecting nginx configuration.",tool_calls:[Se("read_file",{path:"sandbox-local/etc/nginx/nginx.conf"},"c1")]}):o.lastStep<3?(o.lastStep=3,{content:"Fixing nginx config syntax error and adding dry-run restart helper.",tool_calls:[Se("write_file",{path:"sandbox-local/etc/nginx/nginx.conf",content:Fk()},"c2"),Se("write_file",{path:"restart-nginx-dry-run.sh",content:Bk()},"c3")]}):o.lastStep<4?(o.lastStep=4,{content:"Making the restart helper executable.",tool_calls:[Se("bash",{command:"chmod +x restart-nginx-dry-run.sh"},"c4")]}):o.lastStep<5?(o.lastStep=5,{content:"Verifying dry-run restart in the sandbox.",tool_calls:[Se("bash",{command:"./restart-nginx-dry-run.sh"},"c5")]}):{content:"Fixed the nginx syntax error (missing semicolon) and added a sandbox-only dry-run restart script that validates the config then performs a fake systemctl restart.",tool_calls:[]}}if(s==="d"){let r=Pe(t,"d1")?1:0;return o.lastStep=Math.max(o.lastStep,r),o.lastStep<1?(o.lastStep=1,{content:"Investigating.",tool_calls:[Se("list_directory",{path:".",max_depth:2},"d1"),Se("glob",{pattern:"**/*.js"},"d2"),Se("grep",{pattern:"fakeApiGet",path:"."},"d3"),Se("read_file",{path:"README.md"},"d4"),Se("read_file",{path:"app.js"},"d5"),Se("search_files",{path:".",pattern:"getUserAndPosts"},"d6")]}):{content:"Final summary: tool budget enforcement worked; no further tool calls were executed.",tool_calls:[]}}if(s==="e"){let r=Pe(t,"e3")?3:Pe(t,"e2")?2:Pe(t,"e1")?1:0;return o.lastStep=Math.max(o.lastStep,r),o.lastStep<1?(o.lastStep=1,{content:"Reading the legacy callback processor.",tool_calls:[Se("read_file",{path:"processor.js"},"e1")]}):o.lastStep<2?(o.lastStep=2,{content:"Refactoring nested callbacks to async helpers without adding dependencies.",tool_calls:[Se("write_file",{path:"processor.js",content:Uk},"e2")]}):o.lastStep<3?(o.lastStep=3,{content:"Verifying the refactored processor.",tool_calls:[Se("bash",{command:"node processor.js"},"e3")]}):{content:"Refactored the nested callback processor to async/await without adding dependencies and verified the output.",tool_calls:[]}}if(s==="f"){let r=Pe(t,"f3")?3:Pe(t,"f2")?2:Pe(t,"f1")?1:0;return o.lastStep=Math.max(o.lastStep,r),o.lastStep<1?(o.lastStep=1,{content:"Reading the sandboxed nginx config.",tool_calls:[Se("read_file",{path:"mock-root/etc/nginx/nginx.conf"},"f1")]}):o.lastStep<2?(o.lastStep=2,{content:"Fixing the upstream name typo.",tool_calls:[Se("write_file",{path:"mock-root/etc/nginx/nginx.conf",content:Wk()},"f2")]}):o.lastStep<3?(o.lastStep=3,{content:"Checking the dummy service command stays sandboxed.",tool_calls:[Se("bash",{command:'PATH="$PWD/bin:$PATH" systemctl reload nginx'},"f3")]}):{content:"Fixed the sandboxed nginx upstream typo and verified only the dummy systemctl executable was invoked.",tool_calls:[]}}if(s==="g"){let r=Pe(t,"g5")?5:Pe(t,"g4")?4:Pe(t,"g3")||Pe(t,"g2")?3:Pe(t,"g1")?1:0;return o.lastStep=Math.max(o.lastStep,r),o.lastStep<1?(o.lastStep=1,{content:"Inspecting simulated conflict markers.",tool_calls:[Se("grep",{pattern:"<<<<<<<|=======|>>>>>>>",path:"."},"g1")]}):o.lastStep<3?(o.lastStep=3,{content:"Reading conflicted files.",tool_calls:[Se("read_file",{path:"service.js"},"g2"),Se("read_file",{path:"README.md"},"g3")]}):o.lastStep<5?(o.lastStep=5,{content:"Resolving conflicts by preserving configurable behavior.",tool_calls:[Se("write_file",{path:"service.js",content:`function port() { return Number(process.env.PORT || 3000); }
200
200
 
201
201
  module.exports = { port };
202
202
  `},"g4"),Se("write_file",{path:"README.md",content:`Run the service with PORT=3001 node service.js.
203
- `},"g5")]}):{content:"Resolved the simulated multi-file git conflict while preserving the configurable port behavior.",tool_calls:[]}}if(o==="h"){let r=fh(t),i=/previous plan named implementation files that do not exist/i.test(r),a=Pe(t,"h5")?5:Pe(t,"h4")?4:Pe(t,"h3")?3:Pe(t,"h2")?2:0;return s.lastStep=Math.max(s.lastStep,a),!i&&s.lastStep<1?{content:`Selected improvement: add an accessible label to the notation toolbar
203
+ `},"g5")]}):{content:"Resolved the simulated multi-file git conflict while preserving the configurable port behavior.",tool_calls:[]}}if(s==="h"){let r=fh(t),i=/previous plan named implementation files that do not exist/i.test(r),a=Pe(t,"h5")?5:Pe(t,"h4")?4:Pe(t,"h3")?3:Pe(t,"h2")?2:0;return o.lastStep=Math.max(o.lastStep,a),!i&&o.lastStep<1?{content:`Selected improvement: add an accessible label to the notation toolbar
204
204
  Selection rationale: current UI evidence shows active editing controls need clearer labels
205
205
  Files: components/NotationToolbar.tsx
206
206
  Implementation outline: update one existing button label
207
207
  Verification plan: npm test && npm run build
208
- Browser/UI applicability: not required for this deterministic harness scenario`,tool_calls:[]}:i&&s.lastStep<1?(s.lastStep=1,{content:`Selected improvement: add an accessible label to the command center insert action
208
+ Browser/UI applicability: not required for this deterministic harness scenario`,tool_calls:[]}:i&&o.lastStep<1?(o.lastStep=1,{content:`Selected improvement: add an accessible label to the command center insert action
209
209
  Selection rationale: components/CommandCenter.tsx is existing UI evidence and the active editing action needs clearer assistive text
210
210
  Files: components/CommandCenter.tsx
211
211
  Implementation outline: read the current button line, then add one aria-label without changing behavior
212
212
  Verification plan: npm test && npm run build
213
- Browser/UI applicability: not required for this deterministic harness scenario`,tool_calls:[]}):s.lastStep<2?(s.lastStep=2,{content:"Reading the corrected implementation file.",tool_calls:[Se("read_file",{path:"components/CommandCenter.tsx",line_start:1,line_end:80},"h2")]}):s.lastStep<3?(s.lastStep=3,{content:"Applying the scoped accessibility label.",tool_calls:[Se("edit_file",{path:"components/CommandCenter.tsx",old_text:'<button className="command-action">Insert note</button>',new_text:'<button className="command-action" aria-label="Insert note">Insert note</button>'},"h3")]}):s.lastStep<4?(s.lastStep=4,{content:"Verifying the scoped UI change.",tool_calls:[Se("bash",{command:"npm test && npm run build"},"h4")]}):s.lastStep<5?(s.lastStep=5,{content:"Staging, committing, pushing, and checking final status.",tool_calls:[Se("bash",{command:'git status --short --branch && git add components/CommandCenter.tsx && git commit -m "fix: clarify command center action label" && git push origin main && git status --short --branch'},"h5")]}):{content:"Corrected the missing prompt example path, implemented the command center accessibility label, verified with npm test and npm run build, committed the scoped change, pushed main to origin, and confirmed the worktree is clean.",tool_calls:[]}}if(o==="i"){let r=Pe(t,"i8")?8:Pe(t,"i7")?7:Pe(t,"i6")?6:Pe(t,"i5")?5:Pe(t,"i4")?4:Pe(t,"i3")?3:Pe(t,"i2")?2:0;return s.lastStep=Math.max(s.lastStep,r),s.lastStep<1?(s.lastStep=1,{content:`Selected improvement: add an accessible label to the command center apply action
213
+ Browser/UI applicability: not required for this deterministic harness scenario`,tool_calls:[]}):o.lastStep<2?(o.lastStep=2,{content:"Reading the corrected implementation file.",tool_calls:[Se("read_file",{path:"components/CommandCenter.tsx",line_start:1,line_end:80},"h2")]}):o.lastStep<3?(o.lastStep=3,{content:"Applying the scoped accessibility label.",tool_calls:[Se("edit_file",{path:"components/CommandCenter.tsx",old_text:'<button className="command-action">Insert note</button>',new_text:'<button className="command-action" aria-label="Insert note">Insert note</button>'},"h3")]}):o.lastStep<4?(o.lastStep=4,{content:"Verifying the scoped UI change.",tool_calls:[Se("bash",{command:"npm test && npm run build"},"h4")]}):o.lastStep<5?(o.lastStep=5,{content:"Staging, committing, pushing, and checking final status.",tool_calls:[Se("bash",{command:'git status --short --branch && git add components/CommandCenter.tsx && git commit -m "fix: clarify command center action label" && git push origin main && git status --short --branch'},"h5")]}):{content:"Corrected the missing prompt example path, implemented the command center accessibility label, verified with npm test and npm run build, committed the scoped change, pushed main to origin, and confirmed the worktree is clean.",tool_calls:[]}}if(s==="i"){let r=Pe(t,"i8")?8:Pe(t,"i7")?7:Pe(t,"i6")?6:Pe(t,"i5")?5:Pe(t,"i4")?4:Pe(t,"i3")?3:Pe(t,"i2")?2:0;return o.lastStep=Math.max(o.lastStep,r),o.lastStep<1?(o.lastStep=1,{content:`Selected improvement: add an accessible label to the command center apply action
214
214
  Selection rationale: components/CommandCenter.tsx is an existing active editing UI and the Apply action needs clearer assistive text
215
215
  Files: components/CommandCenter.tsx
216
216
  Implementation outline: read the planned implementation file, locate the Apply button if the first range misses it, then add one aria-label without changing behavior
217
217
  Verification plan: npm test && npm run build
218
- Browser/UI applicability: not required for this deterministic harness scenario`,tool_calls:[]}):s.lastStep<2?(s.lastStep=2,{content:"Reading the accepted implementation file.",tool_calls:[Se("read_file",{path:"components/CommandCenter.tsx",line_start:90,line_end:150},"i2")]}):s.lastStep<3?(s.lastStep=3,{content:"Checking labels inside the same planned file.",tool_calls:[Se("grep",{path:"components/CommandCenter.tsx",pattern:"Apply"},"i3")]}):s.lastStep<4?(s.lastStep=4,{content:"Trying the more specific Apply label in the same file.",tool_calls:[Se("grep",{path:"components/CommandCenter.tsx",pattern:"Apply changes"},"i4")]}):s.lastStep<5?(s.lastStep=5,{content:"Locating the Apply action class inside the same planned file.",tool_calls:[Se("grep",{path:"components/CommandCenter.tsx",pattern:"apply-action"},"i5")]}):s.lastStep<6?(s.lastStep=6,{content:"Reading the located Apply button range.",tool_calls:[Se("read_file",{path:"components/CommandCenter.tsx",line_start:200,line_end:230},"i6")]}):s.lastStep<7?(s.lastStep=7,{content:"Applying the scoped accessibility label.",tool_calls:[Se("edit_file",{path:"components/CommandCenter.tsx",old_text:'<button className="apply-action">Apply</button>',new_text:'<button className="apply-action" aria-label="Apply changes">Apply</button>'},"i7")]}):s.lastStep<8?(s.lastStep=8,{content:"Verifying, committing, pushing, and checking final status.",tool_calls:[Se("bash",{command:'npm test && npm run build && git status --short --branch && git add components/CommandCenter.tsx && git commit -m "fix: clarify command center apply label" && git push origin main && git status --short --branch'},"i8")]}):{content:"Located the Apply button with a same-file search after the initial range missed it, implemented the command center accessibility label, verified with npm test and npm run build, committed the scoped change, pushed main to origin, and confirmed the worktree is clean.",tool_calls:[]}}return{content:"No mock scenario matched this prompt. Set a Scenario A\u2013I prompt (or enable malformed mode) to run deterministic E2E flows.",tool_calls:[]}}var Fc=class extends Lk{constructor(e={}){super({name:"mock",baseUrl:"mock://",models:{"mock-model":{id:"mock-model",name:"Mock Model",maxTokens:4096,contextWindow:8192}},defaultModel:"mock-model",...e})}isConfigured(){return process.env.NEX_MOCK_PROVIDER==="1"}async chat(e,n,s={}){return process.env.NEX_MOCK_NULL_RESPONSE==="1"?null:ph(e)}async stream(e,n,s={}){if(process.env.NEX_MOCK_NULL_RESPONSE==="1")return null;let o=typeof s.onToken=="function"?s.onToken:()=>{},r=ph(e),i=String(r.content||""),a=Math.min(i.length,Math.max(1,Math.floor(i.length/2)));return i&&(o(i.slice(0,a)),o(i.slice(a))),r}normalizeResponse(e){return e}};mh.exports={MockProvider:Fc}});var Wc=ne((bM,gh)=>{function Uc(){return process.env.NEX_DEBUG==="true"||process.argv.includes("--debug")}var Gk=Uc();function Yk(...t){Uc()&&console.log(...t)}function zk(...t){Uc()&&console.warn(...t)}gh.exports={DEBUG:Gk,debugLog:Yk,warnLog:zk}});var wh=ne((wM,bh)=>{"use strict";var Kk=new Set(["read_file","grep","glob","search_files","list_directory"]),Vk=new Set(["write_file","edit_file","patch_file"]),Xk=new Set(["bash"]),Jk=new Set(["web_search","web_fetch","perplexity_search"]);function yh(t,e){let n=0,s=0,o=0,r=0,i=0;for(let[a,l]of t)i+=l,Kk.has(a)&&(n+=l),Vk.has(a)&&(s+=l),Xk.has(a)&&(o+=l),Jk.has(a)&&(r+=l);return i===0?`Phase ${e}`:r/i>.5?"Research":n/i>.5?"Exploration":s/i>.3?"Implementation":o/i>.3&&s/i<.15?"Verification":`Phase ${e}`}var Hc=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,s,o){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:yh(this._phaseCounts,this._phaseNum),stepCount:this._stepsThisPhase,toolCounts:new Map(this._phaseCounts),elapsed:Date.now()-this._phaseStart,filesRead:new Set(s),filesModified:new Set(o)};return this._stepsThisPhase=0,this._phaseCounts=new Map,this._phaseStart=Date.now(),r}};bh.exports={MilestoneTracker:Hc,_phaseName:yh}});var kr=ne((_M,_h)=>{var $r=vt(),Zk={"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 Qk(){return $r.getActiveModel()}function ex(t){return $r.setActiveModel(t)}function tx(){return $r.getModelNames()}function nx(t){if(!t)return null;if(typeof t=="object")return t;try{return JSON.parse(t)}catch{}try{let s=t.replace(/,\s*([}\]])/g,"$1").replace(/'/g,'"');return JSON.parse(s)}catch{}let e=t.match(/\{[\s\S]*\}/);if(e)try{return JSON.parse(e[0])}catch{}try{let s=t.replace(/(\{|,)\s*([a-zA-Z_]\w*)\s*:/g,'$1"$2":');return JSON.parse(s)}catch{}let n=t.match(/```(?:json)?\s*([\s\S]*?)```/);if(n)try{return JSON.parse(n[1].trim())}catch{}return null}async function sx(t,e){let{C:n}=xt(),{Spinner:s}=xt(),o=new s("Thinking...");o.start();let r=!0,i="";try{let a=await $r.callStream(t,e,{onToken:l=>{r&&(o.stop(),process.stdout.write(`${n.blue}`),r=!1),process.stdout.write(l),i+=l}});return r?o.stop():process.stdout.write(`${n.reset}
219
- `),a}catch(a){throw o.stop(),a}}async function ox(t,e){return $r.callChat(t,e)}_h.exports={MODELS:Zk,getActiveModel:Qk,setActiveModel:ex,getModelNames:tx,callOllamaStream:sx,callOllama:ox,parseToolArgs:nx}});var vr=ne(($M,Eh)=>{var rx=require("readline"),{C:Ln}=xt(),ix=/[\u200B\u200C\u200D\uFEFF\u2060\u00AD]/g,ax=/^=([\w-]+)/;function xr(t){return typeof t!="string"?t:t.replace(ix,"").replace(ax,"$1")}var zc=[/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/],$h=[...zc,/\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 lx(t){for(let e of $h)if(e.test(t))return e;return null}var kh=[/\.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)/],cx=/\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 xh(t){let e=t.match(/ssh\s+[^"]*"([^"]+)"/)?.[1]||t.match(/ssh\s+[^']*'([^']+)'/)?.[1];if(!e)return!1;let s=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(s.length===0)return!1;let o=r=>{let i=r.replace(/^sudo\s+(?:-[ugCD]\s+\S+\s+|-[A-Za-z]+\s+)*/,"");if(/^\s*(?:echo|printf)\s/.test(i))return!0;if(/^\s*for\s/.test(r)||/^\s*while\s/.test(r)){let a=r.match(/\bdo\s+([\s\S]*?)\s*(?:done|$)/)?.[1];return a?a.split(/\s*;\s*/).map(c=>c.trim()).filter(Boolean).every(c=>o(c)):Gc.some(l=>l.test(r))}return/^\w+=\$?\(/.test(i)||/^\w+=["']/.test(i)||/^\w+=\S/.test(i)?!0:Gc.some(a=>a.test(i))};return s.every(o)}var Kc=[/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/],vh=[/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/],Sh=[...Kc,...vh],Vc=!1,Qn=null,Yc=null;function ux(t){Vc=t}function dx(t){Yc=t}function fx(){return Vc}function px(t){Qn=t}function hx(t){let e=xr(t);for(let n of zc)if(n.test(e))return n;return null}function mx(t){let e=xr(t);if(/ssh\s/.test(e)&&xh(e))return!1;for(let n of Sh)if(n.test(e))return!0;return!1}function gx(t){let e=xr(t);for(let n of Kc)if(n.test(e))return!0;return!1}function yx(t){if(process.env.NEX_UNPROTECT==="1")return null;let e=xr(t);if(!cx.test(e))return null;for(let n of kh)if(n.test(e))return n;return null}function bx(t,e={}){if(Vc)return Promise.resolve(!0);if(Yc)return Yc(t,e);if(!process.stdout.isTTY||!process.stdin.isTTY||process.env.NODE_ENV==="test"||process.env.JEST_WORKER_ID||typeof process.stdin.setRawMode!="function")return wx(t,e);let n=e.toolName?["Yes","No","Always allow"]:["Yes","No"];return new Promise(s=>{let o=0;Qn&&typeof Qn.pause=="function"&&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${Ln.yellow}${t}${Ln.reset}`;for(let p=0;p<n.length;p++){let h=p===o,g=h?`${Ln.yellow}\u276F${Ln.reset}`:" ",w=h?`${Ln.yellow}${n[p]}${Ln.reset}`:n[p];f+=`\x1B[${d+1+p};1H\x1B[2K ${g} ${w}`}r(f)},l=d=>{typeof process.stdin.setRawMode=="function"&&process.stdin.setRawMode(!1),process.stdin.pause(),process.stdin.removeListener("data",u);let f=global._nexRawWrite||(g=>process.stdout.write(g)),p=i(),h="";for(let g=0;g<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&&typeof Qn.resume=="function"&&Qn.resume(),s(d)},c=d=>{if(d===1){l(!1);return}d===2&&e.toolName&&ya(e.toolName),l(!0)},u=d=>{if(d[0]===3){l(!1);return}let f=d.toString();if(f==="\r"||f===`
220
- `){c(o);return}if(f==="\x1B[A"){o=(o-1+n.length)%n.length,a();return}if(f==="\x1B[B"){o=(o+1)%n.length,a();return}let p=f.toLowerCase().trim();if(p==="y"){l(!0);return}if(p==="n"){l(!1);return}if(p==="a"&&e.toolName){ya(e.toolName),l(!0);return}};a(),process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",u)})}function wx(t,e){let n=e.toolName?"[Y/n/a] ":"[Y/n] ";return new Promise(s=>{let o=r=>{let i=r.trim().toLowerCase();i==="a"&&e.toolName?(ya(e.toolName),s(!0)):s(i!=="n")};if(Qn)Qn.question(`${Ln.yellow}${t} ${n}${Ln.reset}`,o);else{let r=rx.createInterface({input:process.stdin,output:process.stdout});r.question(`${Ln.yellow}${t} ${n}${Ln.reset}`,i=>{r.close(),o(i)})}})}var ya=()=>{};function _x(t){ya=t}Eh.exports={sanitizeBashCommand:xr,FORBIDDEN_PATTERNS:zc,SSH_FORBIDDEN_PATTERNS:$h,BASH_PROTECTED_PATHS:kh,SSH_SAFE_PATTERNS:Gc,isSSHReadOnly:xh,DANGEROUS_BASH:Sh,CRITICAL_BASH:Kc,NOTABLE_BASH:vh,isForbidden:hx,isSSHForbidden:lx,isDangerous:mx,isCritical:gx,isBashPathForbidden:yx,confirm:bx,setAutoConfirm:ux,getAutoConfirm:fx,setConfirmHook:dx,setReadlineInterface:px,setAllowAlwaysHandler:_x}});var Ch=ne((xM,Rh)=>{var ba=require("path"),{C:W}=xt(),{T:Xc,isDark:kM}=kn(),{confirm:$x,getAutoConfirm:kx}=vr(),Th=2e3;function Sr(t,e){let n=t.split(`
221
- `),s=e.split(`
222
- `),o=[],r=n.length,i=s.length;if(r>Th||i>Th){for(let d of n)o.push({type:"remove",line:d});for(let d of s)o.push({type:"add",line:d});return o}let a=Array.from({length:r+1},()=>new Array(i+1).fill(0));for(let d=1;d<=r;d++)for(let f=1;f<=i;f++)n[d-1]===s[f-1]?a[d][f]=a[d-1][f-1]+1:a[d][f]=Math.max(a[d-1][f],a[d][f-1]);let l=r,c=i,u=[];for(;l>0||c>0;)l>0&&c>0&&n[l-1]===s[c-1]?(u.unshift({type:"same",line:n[l-1]}),l--,c--):c>0&&(l===0||a[l][c-1]>=a[l-1][c])?(u.unshift({type:"add",line:s[c-1]}),c--):(u.unshift({type:"remove",line:n[l-1]}),l--);return u}function xx(t,e,n,s=3){console.log(`
223
- ${W.bold}${W.cyan} Diff: ${t}${W.reset}`);let o=Sr(e,n),r=[];if(o.forEach((l,c)=>{l.type!=="same"&&r.push(c)}),r.length===0){console.log(`${W.gray} (no changes)${W.reset}`);return}let i=Math.max(0,r[0]-s),a=Math.min(o.length,r[r.length-1]+s+1);i>0&&console.log(`${W.gray} ...${W.reset}`);for(let l=i;l<a;l++){let c=o[l];switch(c.type){case"remove":console.log(`${W.red} - ${c.line}${W.reset}`);break;case"add":console.log(`${W.green} + ${c.line}${W.reset}`);break;default:console.log(`${W.gray} ${c.line}${W.reset}`)}}a<o.length&&console.log(`${W.gray} ...${W.reset}`),console.log()}function vx(t,e,n){console.log(`
224
- ${W.bold}${W.cyan} File exists \u2014 showing changes: ${t}${W.reset}`);let s=Sr(e,n),o=0;for(let i of s)i.type!=="same"&&o++;if(o===0){console.log(`${W.gray} (identical content)${W.reset}`);return}let r=0;for(let i of s){if(r>=30){console.log(`${W.gray} ...(${o-r} more changes)${W.reset}`);break}switch(i.type){case"remove":console.log(`${W.red} - ${i.line}${W.reset}`),r++;break;case"add":console.log(`${W.green} + ${i.line}${W.reset}`),r++;break;default:r>0&&console.log(`${W.gray} ${i.line}${W.reset}`)}}console.log()}function Sx(t,e){console.log(`
218
+ Browser/UI applicability: not required for this deterministic harness scenario`,tool_calls:[]}):o.lastStep<2?(o.lastStep=2,{content:"Reading the accepted implementation file.",tool_calls:[Se("read_file",{path:"components/CommandCenter.tsx",line_start:90,line_end:150},"i2")]}):o.lastStep<3?(o.lastStep=3,{content:"Checking labels inside the same planned file.",tool_calls:[Se("grep",{path:"components/CommandCenter.tsx",pattern:"Apply"},"i3")]}):o.lastStep<4?(o.lastStep=4,{content:"Trying the more specific Apply label in the same file.",tool_calls:[Se("grep",{path:"components/CommandCenter.tsx",pattern:"Apply changes"},"i4")]}):o.lastStep<5?(o.lastStep=5,{content:"Locating the Apply action class inside the same planned file.",tool_calls:[Se("grep",{path:"components/CommandCenter.tsx",pattern:"apply-action"},"i5")]}):o.lastStep<6?(o.lastStep=6,{content:"Reading the located Apply button range.",tool_calls:[Se("read_file",{path:"components/CommandCenter.tsx",line_start:200,line_end:230},"i6")]}):o.lastStep<7?(o.lastStep=7,{content:"Applying the scoped accessibility label.",tool_calls:[Se("edit_file",{path:"components/CommandCenter.tsx",old_text:'<button className="apply-action">Apply</button>',new_text:'<button className="apply-action" aria-label="Apply changes">Apply</button>'},"i7")]}):o.lastStep<8?(o.lastStep=8,{content:"Verifying, committing, pushing, and checking final status.",tool_calls:[Se("bash",{command:'npm test && npm run build && git status --short --branch && git add components/CommandCenter.tsx && git commit -m "fix: clarify command center apply label" && git push origin main && git status --short --branch'},"i8")]}):{content:"Located the Apply button with a same-file search after the initial range missed it, implemented the command center accessibility label, verified with npm test and npm run build, committed the scoped change, pushed main to origin, and confirmed the worktree is clean.",tool_calls:[]}}return{content:"No mock scenario matched this prompt. Set a Scenario A\u2013I prompt (or enable malformed mode) to run deterministic E2E flows.",tool_calls:[]}}var Fc=class extends Lk{constructor(e={}){super({name:"mock",baseUrl:"mock://",models:{"mock-model":{id:"mock-model",name:"Mock Model",maxTokens:4096,contextWindow:8192}},defaultModel:"mock-model",...e})}isConfigured(){return process.env.NEX_MOCK_PROVIDER==="1"}async chat(e,n,o={}){return process.env.NEX_MOCK_NULL_RESPONSE==="1"?null:ph(e)}async stream(e,n,o={}){if(process.env.NEX_MOCK_NULL_RESPONSE==="1")return null;let s=typeof o.onToken=="function"?o.onToken:()=>{},r=ph(e),i=String(r.content||""),a=Math.min(i.length,Math.max(1,Math.floor(i.length/2)));return i&&(s(i.slice(0,a)),s(i.slice(a))),r}normalizeResponse(e){return e}};mh.exports={MockProvider:Fc}});var Wc=ne((bM,gh)=>{function Uc(){return process.env.NEX_DEBUG==="true"||process.argv.includes("--debug")}var Gk=Uc();function Yk(...t){Uc()&&console.log(...t)}function zk(...t){Uc()&&console.warn(...t)}gh.exports={DEBUG:Gk,debugLog:Yk,warnLog:zk}});var wh=ne((wM,bh)=>{"use strict";var Kk=new Set(["read_file","grep","glob","search_files","list_directory"]),Vk=new Set(["write_file","edit_file","patch_file"]),Xk=new Set(["bash"]),Jk=new Set(["web_search","web_fetch","perplexity_search"]);function yh(t,e){let n=0,o=0,s=0,r=0,i=0;for(let[a,l]of t)i+=l,Kk.has(a)&&(n+=l),Vk.has(a)&&(o+=l),Xk.has(a)&&(s+=l),Jk.has(a)&&(r+=l);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 Hc=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:yh(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}};bh.exports={MilestoneTracker:Hc,_phaseName:yh}});var kr=ne((_M,_h)=>{var $r=vt(),Zk={"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 Qk(){return $r.getActiveModel()}function ex(t){return $r.setActiveModel(t)}function tx(){return $r.getModelNames()}function nx(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 sx(t,e){let{C:n}=xt(),{Spinner:o}=xt(),s=new o("Thinking...");s.start();let r=!0,i="";try{let a=await $r.callStream(t,e,{onToken:l=>{r&&(s.stop(),process.stdout.write(`${n.blue}`),r=!1),process.stdout.write(l),i+=l}});return r?s.stop():process.stdout.write(`${n.reset}
219
+ `),a}catch(a){throw s.stop(),a}}async function ox(t,e){return $r.callChat(t,e)}_h.exports={MODELS:Zk,getActiveModel:Qk,setActiveModel:ex,getModelNames:tx,callOllamaStream:sx,callOllama:ox,parseToolArgs:nx}});var vr=ne(($M,Eh)=>{var rx=require("readline"),{C:Ln}=xt(),ix=/[\u200B\u200C\u200D\uFEFF\u2060\u00AD]/g,ax=/^=([\w-]+)/;function xr(t){return typeof t!="string"?t:t.replace(ix,"").replace(ax,"$1")}var zc=[/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/],$h=[...zc,/\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 lx(t){for(let e of $h)if(e.test(t))return e;return null}var kh=[/\.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)/],cx=/\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 xh(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(c=>c.trim()).filter(Boolean).every(c=>s(c)):Gc.some(l=>l.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 Kc=[/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/],vh=[/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/],Sh=[...Kc,...vh],Vc=!1,Qn=null,Yc=null;function ux(t){Vc=t}function dx(t){Yc=t}function fx(){return Vc}function px(t){Qn=t}function hx(t){let e=xr(t);for(let n of zc)if(n.test(e))return n;return null}function mx(t){let e=xr(t);if(/ssh\s/.test(e)&&xh(e))return!1;for(let n of Sh)if(n.test(e))return!0;return!1}function gx(t){let e=xr(t);for(let n of Kc)if(n.test(e))return!0;return!1}function yx(t){if(process.env.NEX_UNPROTECT==="1")return null;let e=xr(t);if(!cx.test(e))return null;for(let n of kh)if(n.test(e))return n;return null}function bx(t,e={}){if(Vc)return Promise.resolve(!0);if(Yc)return Yc(t,e);if(!process.stdout.isTTY||!process.stdin.isTTY||process.env.NODE_ENV==="test"||process.env.JEST_WORKER_ID||typeof process.stdin.setRawMode!="function")return wx(t,e);let n=e.toolName?["Yes","No","Always allow"]:["Yes","No"];return new Promise(o=>{let s=0;Qn&&typeof Qn.pause=="function"&&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${Ln.yellow}${t}${Ln.reset}`;for(let p=0;p<n.length;p++){let h=p===s,g=h?`${Ln.yellow}\u276F${Ln.reset}`:" ",w=h?`${Ln.yellow}${n[p]}${Ln.reset}`:n[p];f+=`\x1B[${d+1+p};1H\x1B[2K ${g} ${w}`}r(f)},l=d=>{typeof process.stdin.setRawMode=="function"&&process.stdin.setRawMode(!1),process.stdin.pause(),process.stdin.removeListener("data",u);let f=global._nexRawWrite||(g=>process.stdout.write(g)),p=i(),h="";for(let g=0;g<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&&typeof Qn.resume=="function"&&Qn.resume(),o(d)},c=d=>{if(d===1){l(!1);return}d===2&&e.toolName&&ya(e.toolName),l(!0)},u=d=>{if(d[0]===3){l(!1);return}let f=d.toString();if(f==="\r"||f===`
220
+ `){c(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"){l(!0);return}if(p==="n"){l(!1);return}if(p==="a"&&e.toolName){ya(e.toolName),l(!0);return}};a(),process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",u)})}function wx(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?(ya(e.toolName),o(!0)):o(i!=="n")};if(Qn)Qn.question(`${Ln.yellow}${t} ${n}${Ln.reset}`,s);else{let r=rx.createInterface({input:process.stdin,output:process.stdout});r.question(`${Ln.yellow}${t} ${n}${Ln.reset}`,i=>{r.close(),s(i)})}})}var ya=()=>{};function _x(t){ya=t}Eh.exports={sanitizeBashCommand:xr,FORBIDDEN_PATTERNS:zc,SSH_FORBIDDEN_PATTERNS:$h,BASH_PROTECTED_PATHS:kh,SSH_SAFE_PATTERNS:Gc,isSSHReadOnly:xh,DANGEROUS_BASH:Sh,CRITICAL_BASH:Kc,NOTABLE_BASH:vh,isForbidden:hx,isSSHForbidden:lx,isDangerous:mx,isCritical:gx,isBashPathForbidden:yx,confirm:bx,setAutoConfirm:ux,getAutoConfirm:fx,setConfirmHook:dx,setReadlineInterface:px,setAllowAlwaysHandler:_x}});var Ch=ne((xM,Rh)=>{var ba=require("path"),{C:W}=xt(),{T:Xc,isDark:kM}=kn(),{confirm:$x,getAutoConfirm:kx}=vr(),Th=2e3;function Sr(t,e){let n=t.split(`
221
+ `),o=e.split(`
222
+ `),s=[],r=n.length,i=o.length;if(r>Th||i>Th){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 l=r,c=i,u=[];for(;l>0||c>0;)l>0&&c>0&&n[l-1]===o[c-1]?(u.unshift({type:"same",line:n[l-1]}),l--,c--):c>0&&(l===0||a[l][c-1]>=a[l-1][c])?(u.unshift({type:"add",line:o[c-1]}),c--):(u.unshift({type:"remove",line:n[l-1]}),l--);return u}function xx(t,e,n,o=3){console.log(`
223
+ ${W.bold}${W.cyan} Diff: ${t}${W.reset}`);let s=Sr(e,n),r=[];if(s.forEach((l,c)=>{l.type!=="same"&&r.push(c)}),r.length===0){console.log(`${W.gray} (no changes)${W.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(`${W.gray} ...${W.reset}`);for(let l=i;l<a;l++){let c=s[l];switch(c.type){case"remove":console.log(`${W.red} - ${c.line}${W.reset}`);break;case"add":console.log(`${W.green} + ${c.line}${W.reset}`);break;default:console.log(`${W.gray} ${c.line}${W.reset}`)}}a<s.length&&console.log(`${W.gray} ...${W.reset}`),console.log()}function vx(t,e,n){console.log(`
224
+ ${W.bold}${W.cyan} File exists \u2014 showing changes: ${t}${W.reset}`);let o=Sr(e,n),s=0;for(let i of o)i.type!=="same"&&s++;if(s===0){console.log(`${W.gray} (identical content)${W.reset}`);return}let r=0;for(let i of o){if(r>=30){console.log(`${W.gray} ...(${s-r} more changes)${W.reset}`);break}switch(i.type){case"remove":console.log(`${W.red} - ${i.line}${W.reset}`),r++;break;case"add":console.log(`${W.green} + ${i.line}${W.reset}`),r++;break;default:r>0&&console.log(`${W.gray} ${i.line}${W.reset}`)}}console.log()}function Sx(t,e){console.log(`
225
225
  ${W.bold}${W.cyan} New file: ${t}${W.reset}`);let n=e.split(`
226
- `),s=n.slice(0,20);for(let o of s)console.log(`${W.green} + ${o}${W.reset}`);n.length>20&&console.log(`${W.gray} ...+${n.length-20} more lines${W.reset}`),console.log()}async function Ex(t){return kx()?!0:$x(` ${t}?`)}function Tx(t,e,n,s){let o=s||process.stdout.columns||80,r=Math.floor((o-3)/2);console.log(`
226
+ `),o=n.slice(0,20);for(let s of o)console.log(`${W.green} + ${s}${W.reset}`);n.length>20&&console.log(`${W.gray} ...+${n.length-20} more lines${W.reset}`),console.log()}async function Ex(t){return kx()?!0:$x(` ${t}?`)}function Tx(t,e,n,o){let s=o||process.stdout.columns||80,r=Math.floor((s-3)/2);console.log(`
227
227
  ${W.bold}${W.cyan} Side-by-side: ${t}${W.reset}`),console.log(` ${W.dim}${"\u2500".repeat(r)}\u252C${"\u2500".repeat(r)}${W.reset}`);let i=Sr(e,n),a=[],l=0;for(;l<i.length;)if(i[l].type==="same")a.push({left:i[l].line,right:i[l].line,type:"same"}),l++;else if(i[l].type==="remove"){let p=[];for(;l<i.length&&i[l].type==="remove";)p.push(i[l].line),l++;let h=[];for(;l<i.length&&i[l].type==="add";)h.push(i[l].line),l++;let g=Math.max(p.length,h.length);for(let w=0;w<g;w++)a.push({left:w<p.length?p[w]:"",right:w<h.length?h[w]:"",type:"changed"})}else i[l].type==="add"&&(a.push({left:"",right:i[l].line,type:"changed"}),l++);let c=a.map((p,h)=>p.type!=="same"?h:-1).filter(p=>p>=0);if(c.length===0){console.log(` ${W.gray}(no changes)${W.reset}`);return}let u=Math.max(0,c[0]-2),d=Math.min(a.length,c[c.length-1]+3),f=(p,h)=>{let g=p.replace(/\x1b\[[0-9;]*m/g,"");return g.length>=h?p.substring(0,h):p+" ".repeat(h-g.length)};u>0&&console.log(` ${W.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${W.reset}`);for(let p=u;p<d;p++){let h=a[p];if(h.type==="same")console.log(` ${W.gray}${f(h.left,r)}${W.reset}\u2502${W.gray}${f(h.right,r)}${W.reset}`);else{let g=h.left?`${W.red}${f(h.left,r)}${W.reset}`:`${f("",r)}`,w=h.right?`${W.green}${f(h.right,r)}${W.reset}`:`${f("",r)}`;console.log(` ${g}\u2502${w}`)}}d<a.length&&console.log(` ${W.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${W.reset}`),console.log(` ${W.dim}${"\u2500".repeat(r)}\u2534${"\u2500".repeat(r)}${W.reset}
228
- `)}function Rx(t,e,n,s={}){let o=s.label||"Update",r=s.context||3,i=s.annotations||[],a=ba.isAbsolute(t)?ba.relative(process.cwd(),t):t,l=Sr(e,n),c=1,u=1;for(let M of l)M.type==="same"?(M.oldLine=c++,M.newLine=u++):M.type==="remove"?(M.oldLine=c++,M.newLine=null):(M.oldLine=null,M.newLine=u++);let d=0,f=0;for(let M of l)M.type==="add"?d++:M.type==="remove"&&f++;if(console.log(`
229
- ${W.green}\u23FA${W.reset} ${W.bold}${o}(${a})${W.reset}`),d===0&&f===0){console.log(` ${W.dim}\u23BF (no changes)${W.reset}
230
- `);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 M=i.filter(ae=>ae.severity==="error").length,K=i.filter(ae=>ae.severity==="warn").length,z=i.filter(ae=>ae.severity==="info").length,X=[];M>0&&X.push(`${W.red}${M} error${M!==1?"s":""}${W.dim}`),K>0&&X.push(`${W.yellow}${K} warning${K!==1?"s":""}${W.dim}`),z>0&&X.push(`${W.cyan}${z} info${z!==1?"s":""}${W.dim}`),p.push(`found ${X.join(", ")}`)}console.log(` ${W.dim}\u23BF ${p.join(", ")}${W.reset}`);let g=[];l.forEach((M,K)=>{M.type!=="same"&&g.push(K)});let w=[],k=null,T=null;for(let M of g){let K=Math.max(0,M-r),z=Math.min(l.length-1,M+r);k===null?(k=K,T=z):(K<=T+1||(w.push([k,T]),k=K),T=z)}k!==null&&w.push([k,T]);let $=" ",R=process.stdout.columns||120;function C(M,K,z){let X=z.replace(/\x1b\[[0-9;]*m/g,""),ae=z+" ".repeat(Math.max(0,R-X.length));return`${M}${K}${ae}${W.reset}`}for(let M=0;M<w.length;M++){M>0&&console.log(`${$}${W.dim}\xB7\xB7\xB7${W.reset}`);let[K,z]=w[M];for(let X=K;X<=z;X++){let ae=l[X],Z=ae.newLine!=null?ae.newLine:ae.oldLine,oe=String(Z).padStart(4),Ke=ae.type!=="remove"?i.filter(Ee=>Ee.line===ae.newLine):[];ae.type==="remove"?console.log(C(Xc.diff_rem_bg,W.red,`${$}${oe} - ${ae.line}`)):ae.type==="add"?console.log(C(Xc.diff_add_bg,W.green,`${$}${oe} + ${ae.line}`)):console.log(`${$}${W.dim}${oe} ${W.reset}${ae.line}`);for(let Ee of Ke){let G=W.cyan,re="\u2139";Ee.severity==="error"?(G=W.red,re="\u2716"):Ee.severity==="warn"&&(G=W.yellow,re="\u26A0"),console.log(`${$} ${G}${re} ${Ee.message}${W.reset}`)}}}console.log()}function Cx(t,e,n={}){let s=ba.isAbsolute(t)?ba.relative(process.cwd(),t):t,o=e.split(`
228
+ `)}function Rx(t,e,n,o={}){let s=o.label||"Update",r=o.context||3,i=o.annotations||[],a=ba.isAbsolute(t)?ba.relative(process.cwd(),t):t,l=Sr(e,n),c=1,u=1;for(let M of l)M.type==="same"?(M.oldLine=c++,M.newLine=u++):M.type==="remove"?(M.oldLine=c++,M.newLine=null):(M.oldLine=null,M.newLine=u++);let d=0,f=0;for(let M of l)M.type==="add"?d++:M.type==="remove"&&f++;if(console.log(`
229
+ ${W.green}\u23FA${W.reset} ${W.bold}${s}(${a})${W.reset}`),d===0&&f===0){console.log(` ${W.dim}\u23BF (no changes)${W.reset}
230
+ `);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 M=i.filter(ae=>ae.severity==="error").length,K=i.filter(ae=>ae.severity==="warn").length,z=i.filter(ae=>ae.severity==="info").length,X=[];M>0&&X.push(`${W.red}${M} error${M!==1?"s":""}${W.dim}`),K>0&&X.push(`${W.yellow}${K} warning${K!==1?"s":""}${W.dim}`),z>0&&X.push(`${W.cyan}${z} info${z!==1?"s":""}${W.dim}`),p.push(`found ${X.join(", ")}`)}console.log(` ${W.dim}\u23BF ${p.join(", ")}${W.reset}`);let g=[];l.forEach((M,K)=>{M.type!=="same"&&g.push(K)});let w=[],k=null,T=null;for(let M of g){let K=Math.max(0,M-r),z=Math.min(l.length-1,M+r);k===null?(k=K,T=z):(K<=T+1||(w.push([k,T]),k=K),T=z)}k!==null&&w.push([k,T]);let $=" ",R=process.stdout.columns||120;function C(M,K,z){let X=z.replace(/\x1b\[[0-9;]*m/g,""),ae=z+" ".repeat(Math.max(0,R-X.length));return`${M}${K}${ae}${W.reset}`}for(let M=0;M<w.length;M++){M>0&&console.log(`${$}${W.dim}\xB7\xB7\xB7${W.reset}`);let[K,z]=w[M];for(let X=K;X<=z;X++){let ae=l[X],Z=ae.newLine!=null?ae.newLine:ae.oldLine,oe=String(Z).padStart(4),Ke=ae.type!=="remove"?i.filter(Ee=>Ee.line===ae.newLine):[];ae.type==="remove"?console.log(C(Xc.diff_rem_bg,W.red,`${$}${oe} - ${ae.line}`)):ae.type==="add"?console.log(C(Xc.diff_add_bg,W.green,`${$}${oe} + ${ae.line}`)):console.log(`${$}${W.dim}${oe} ${W.reset}${ae.line}`);for(let Ee of Ke){let G=W.cyan,re="\u2139";Ee.severity==="error"?(G=W.red,re="\u2716"):Ee.severity==="warn"&&(G=W.yellow,re="\u26A0"),console.log(`${$} ${G}${re} ${Ee.message}${W.reset}`)}}}console.log()}function Cx(t,e,n={}){let o=ba.isAbsolute(t)?ba.relative(process.cwd(),t):t,s=e.split(`
231
231
  `),r=n.annotations||[];console.log(`
232
- ${W.green}\u23FA${W.reset} ${W.bold}Create(${s})${W.reset}`);let i=[`${o.length} line${o.length!==1?"s":""}`];if(r.length>0){let d=r.filter(g=>g.severity==="error").length,f=r.filter(g=>g.severity==="warn").length,p=r.filter(g=>g.severity==="info").length,h=[];d>0&&h.push(`${W.red}${d} error${d!==1?"s":""}${W.dim}`),f>0&&h.push(`${W.yellow}${f} warning${f!==1?"s":""}${W.dim}`),p>0&&h.push(`${W.cyan}${p} info${p!==1?"s":""}${W.dim}`),i.push(`found ${h.join(", ")}`)}console.log(` ${W.dim}\u23BF ${i.join(", ")}${W.reset}`);let l=" ",c=process.stdout.columns||120,u=Math.min(o.length,20);for(let d=0;d<u;d++){let f=String(d+1).padStart(4),p=d+1,h=r.filter(T=>T.line===p),g=`${l}${f} + ${o[d]}`,w=g.replace(/\x1b\[[0-9;]*m/g,""),k=g+" ".repeat(Math.max(0,c-w.length));console.log(`${Xc.diff_add_bg}${W.green}${k}${W.reset}`);for(let T of h){let $=W.cyan,R="\u2139";T.severity==="error"?($=W.red,R="\u2716"):T.severity==="warn"&&($=W.yellow,R="\u26A0"),console.log(`${l} ${$}${R} ${T.message}${W.reset}`)}}o.length>20&&console.log(`${l}${W.dim} ...+${o.length-20} more lines${W.reset}`),console.log()}Rh.exports={diffLines:Sr,showEditDiff:xx,showWriteDiff:vx,showNewFilePreview:Sx,confirmFileChange:Ex,showSideBySideDiff:Tx,showDiff:Rx,showNewFile:Cx}});var $a=ne((vM,Ph)=>{var Ah=require("util").promisify(require("child_process").exec),Ax=require("util").promisify(require("child_process").execFile),{C:mt}=xt();async function Jc(t){try{let{stdout:e}=await Ah(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function wa(...t){try{let{stdout:e}=await Ax("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function Ox(){return await Jc("git rev-parse --is-inside-work-tree")==="true"}async function Px(){return await Jc("git branch --show-current")}async function Zc(){try{let{stdout:t}=await Ah("git status --porcelain",{cwd:process.cwd(),timeout:3e4});return!t||!t.trim()?[]:t.split(`
233
- `).filter(Boolean).map(e=>{let n=e.substring(0,2).trim(),s=e.substring(3);return{status:n,file:s}})}catch{return[]}}async function _a(t=!1){return await Jc(`git diff ${t?"--cached":""}`)||""}async function Qc(){return(await Zc()).map(e=>e.file)}async function Oh(){let t=await Qc();if(t.length===0)return null;let e=await _a(),s=await _a(!0)||e,o=0,r=0;if(s){let u=s.split(`
234
- `);for(let d of u)d.startsWith("+")&&!d.startsWith("+++")&&o++,d.startsWith("-")&&!d.startsWith("---")&&r++}else o=t.length;let i="chore",a=t.join(" ").toLowerCase();a.includes("test")?i="test":a.includes("readme")||a.includes("doc")?i="docs":o>r*2?i="feat":r>o?i="refactor":i="fix";let l=t.slice(0,3).map(u=>u.split("/").pop());return{summary:`${i}: update ${l.join(", ")}${t.length>3?` (+${t.length-3} more)`:""}`,type:i,files:t,stats:{additions:o,deletions:r}}}async function Mx(t){let n=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await wa("checkout","-b",n)!==null?n:null}async function Nx(t){return await wa("add","-A"),await wa("commit","-m",t)?await wa("rev-parse","--short","HEAD"):null}async function Lx(){let t=await Oh();if(!t)return`${mt.dim}No changes${mt.reset}`;let e=[];e.push(`
232
+ ${W.green}\u23FA${W.reset} ${W.bold}Create(${o})${W.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(`${W.red}${d} error${d!==1?"s":""}${W.dim}`),f>0&&h.push(`${W.yellow}${f} warning${f!==1?"s":""}${W.dim}`),p>0&&h.push(`${W.cyan}${p} info${p!==1?"s":""}${W.dim}`),i.push(`found ${h.join(", ")}`)}console.log(` ${W.dim}\u23BF ${i.join(", ")}${W.reset}`);let l=" ",c=process.stdout.columns||120,u=Math.min(s.length,20);for(let d=0;d<u;d++){let f=String(d+1).padStart(4),p=d+1,h=r.filter(T=>T.line===p),g=`${l}${f} + ${s[d]}`,w=g.replace(/\x1b\[[0-9;]*m/g,""),k=g+" ".repeat(Math.max(0,c-w.length));console.log(`${Xc.diff_add_bg}${W.green}${k}${W.reset}`);for(let T of h){let $=W.cyan,R="\u2139";T.severity==="error"?($=W.red,R="\u2716"):T.severity==="warn"&&($=W.yellow,R="\u26A0"),console.log(`${l} ${$}${R} ${T.message}${W.reset}`)}}s.length>20&&console.log(`${l}${W.dim} ...+${s.length-20} more lines${W.reset}`),console.log()}Rh.exports={diffLines:Sr,showEditDiff:xx,showWriteDiff:vx,showNewFilePreview:Sx,confirmFileChange:Ex,showSideBySideDiff:Tx,showDiff:Rx,showNewFile:Cx}});var $a=ne((vM,Ph)=>{var Ah=require("util").promisify(require("child_process").exec),Ax=require("util").promisify(require("child_process").execFile),{C:mt}=xt();async function Jc(t){try{let{stdout:e}=await Ah(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function wa(...t){try{let{stdout:e}=await Ax("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function Ox(){return await Jc("git rev-parse --is-inside-work-tree")==="true"}async function Px(){return await Jc("git branch --show-current")}async function Zc(){try{let{stdout:t}=await Ah("git status --porcelain",{cwd:process.cwd(),timeout:3e4});return!t||!t.trim()?[]:t.split(`
233
+ `).filter(Boolean).map(e=>{let n=e.substring(0,2).trim(),o=e.substring(3);return{status:n,file:o}})}catch{return[]}}async function _a(t=!1){return await Jc(`git diff ${t?"--cached":""}`)||""}async function Qc(){return(await Zc()).map(e=>e.file)}async function Oh(){let t=await Qc();if(t.length===0)return null;let e=await _a(),o=await _a(!0)||e,s=0,r=0;if(o){let u=o.split(`
234
+ `);for(let d of u)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 l=t.slice(0,3).map(u=>u.split("/").pop());return{summary:`${i}: update ${l.join(", ")}${t.length>3?` (+${t.length-3} more)`:""}`,type:i,files:t,stats:{additions:s,deletions:r}}}async function Mx(t){let n=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await wa("checkout","-b",n)!==null?n:null}async function Nx(t){return await wa("add","-A"),await wa("commit","-m",t)?await wa("rev-parse","--short","HEAD"):null}async function Lx(){let t=await Oh();if(!t)return`${mt.dim}No changes${mt.reset}`;let e=[];e.push(`
235
235
  ${mt.bold}${mt.cyan}Git Diff Summary:${mt.reset}`),e.push(` ${mt.green}+${t.stats.additions}${mt.reset} ${mt.red}-${t.stats.deletions}${mt.reset} in ${t.files.length} file(s)`),e.push(`
236
236
  ${mt.bold}${mt.cyan}Files:${mt.reset}`);for(let n of t.files.slice(0,20))e.push(` ${mt.dim}${n}${mt.reset}`);return t.files.length>20&&e.push(` ${mt.dim}...+${t.files.length-20} more${mt.reset}`),e.push(`
237
237
  ${mt.bold}${mt.cyan}Suggested message:${mt.reset}`),e.push(` ${mt.cyan}${t.summary}${mt.reset}
238
238
  `),e.join(`
239
- `)}async function Ix(){return(await Zc()).filter(e=>e.status==="UU"||e.status==="AA"||e.status==="DD")}async function jx(){let t=await Qc();if(t.length===0)return"";let e=[`CHANGED FILES (${t.length}):`];for(let s of t.slice(0,10))e.push(` ${s}`);let n=await _a();if(n){let s=n.length>5e3?n.substring(0,5e3)+`
239
+ `)}async function Ix(){return(await Zc()).filter(e=>e.status==="UU"||e.status==="AA"||e.status==="DD")}async function jx(){let t=await Qc();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 _a();if(n){let o=n.length>5e3?n.substring(0,5e3)+`
240
240
  ...(truncated)`:n;e.push(`
241
241
  DIFF:
242
- ${s}`)}return e.join(`
243
- `)}Ph.exports={isGitRepo:Ox,getCurrentBranch:Px,getStatus:Zc,getDiff:_a,getChangedFiles:Qc,analyzeDiff:Oh,createBranch:Mx,commit:Nx,formatDiffSummary:Lx,getDiffContext:jx,getMergeConflicts:Ix}});var Fh=ne((EM,qh)=>{var Ct=require("fs").promises,SM=require("fs"),un=require("path"),Dx=require("crypto"),{execSync:eu,execFileSync:Lh}=require("child_process"),qx=100*1024,Ih=50,Wt=[],jo=[];function Fx(t,e,n,s){for(Wt.push({tool:t,filePath:e,oldContent:n,newContent:s,timestamp:Date.now()});Wt.length>Ih;)Wt.shift();jo.length=0,jh(Wt[Wt.length-1]).catch(()=>{})}async function Bx(){if(Wt.length===0)return null;let t=Wt.pop();if(t.oldContent===null)try{await Ct.unlink(t.filePath)}catch{}else await Ct.writeFile(t.filePath,t.oldContent,"utf-8");return jo.push(t),{tool:t.tool,filePath:t.filePath,wasCreated:t.oldContent===null}}async function Ux(){if(jo.length===0)return null;let t=jo.pop();return await Ct.writeFile(t.filePath,t.newContent,"utf-8"),Wt.push(t),{tool:t.tool,filePath:t.filePath}}function Wx(t=10){return Wt.slice(-t).reverse().map(e=>({tool:e.tool,filePath:e.filePath,timestamp:e.timestamp}))}function Hx(){return Wt.length}function Gx(){return jo.length}function Yx({diskToo:t=!0}={}){if(Wt.length=0,jo.length=0,t){let e=xa();Ct.readdir(e).then(n=>{for(let s of n)s.endsWith(".json")&&Ct.unlink(un.join(e,s)).catch(()=>{})}).catch(()=>{})}}function xa(){return un.join(process.cwd(),".nex","history")}async function Mh(t,e){if(t==null)return{inline:!0,content:t};if(Buffer.byteLength(t,"utf-8")<=qx)return{inline:!0,content:t};let n=Dx.createHash("sha256").update(t,"utf-8").digest("hex"),s=un.join(e,"blobs");return await Ct.mkdir(s,{recursive:!0}),await Ct.writeFile(un.join(s,n),t,"utf-8"),{inline:!1,hash:n}}async function jh(t){let e=xa();await Ct.mkdir(e,{recursive:!0});let n=un.basename(t.filePath).replace(/[^a-zA-Z0-9]/g,"-"),s=`${t.timestamp}-${n}.json`,o=await Mh(t.oldContent,e),r=await Mh(t.newContent,e),i={tool:t.tool,filePath:t.filePath,timestamp:t.timestamp,oldContent:o.inline?{inline:!0,content:o.content}:{inline:!1,hash:o.hash},newContent:r.inline?{inline:!0,content:r.content}:{inline:!1,hash:r.hash}};await Ct.writeFile(un.join(e,s),JSON.stringify(i),"utf-8")}async function Nh(t,e){if(!t)return null;if(t.inline)return t.content;let n=un.join(e,"blobs",t.hash);return Ct.readFile(n,"utf-8")}async function zx(){let t=xa(),e;try{e=await Ct.readdir(t)}catch{return 0}let n=e.filter(o=>o.endsWith(".json")).sort(),s=0;for(let o of n)try{let r=await Ct.readFile(un.join(t,o),"utf-8"),i=JSON.parse(r),a=await Nh(i.oldContent,t),l=await Nh(i.newContent,t);Wt.push({tool:i.tool,filePath:i.filePath,timestamp:i.timestamp,oldContent:a,newContent:l}),s++}catch{}for(;Wt.length>Ih;)Wt.shift();return s}async function Kx(t=7){let e=xa(),n;try{n=await Ct.readdir(e)}catch{return 0}let s=Date.now()-t*24*60*60*1e3,o=n.filter(c=>c.endsWith(".json")),r=0,i=new Set,a=[];for(let c of o)try{let u=await Ct.readFile(un.join(e,c),"utf-8"),d=JSON.parse(u);d.timestamp<s?(a.push(c),r++):(d.oldContent&&!d.oldContent.inline&&d.oldContent.hash&&i.add(d.oldContent.hash),d.newContent&&!d.newContent.inline&&d.newContent.hash&&i.add(d.newContent.hash))}catch{}for(let c of a)try{await Ct.unlink(un.join(e,c))}catch{}let l=un.join(e,"blobs");try{let c=await Ct.readdir(l);for(let u of c)if(!i.has(u))try{await Ct.unlink(un.join(l,u))}catch{}}catch{}return r}var ka="nex-snapshot";function Vx(t,e=process.cwd()){let n=t?`${ka}-${t.replace(/[^a-zA-Z0-9_-]/g,"-")}`:`${ka}-${Date.now()}`;try{return eu("git status --porcelain",{cwd:e,timeout:1e4}).toString().trim()?(Lh("git",["stash","push","-u","-m",n],{cwd:e,timeout:15e3}),eu("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(s){return{name:n,label:n,ok:!1,error:s.message}}}function Dh(t=process.cwd()){try{let e=eu("git stash list",{cwd:t,timeout:1e4}).toString().trim();return e?e.split(`
244
- `).map(n=>{let s=n.match(/^stash@\{(\d+)\}:\s+(?:WIP on [^:]+:\s+\S+\s+|On \S+:\s+)(.*)/);if(!s)return null;let o=s[2].trim();return o.startsWith(ka)?{index:parseInt(s[1],10),label:o,shortName:o.replace(`${ka}-`,""),date:n}:null}).filter(Boolean):[]}catch{return[]}}function Xx(t,e=process.cwd()){try{let n=Dh(e);if(n.length===0)return{ok:!1,error:"No snapshots found"};let s;return t===void 0||t==="last"?s=n[0]:typeof t=="number"?s=n.find(o=>o.index===t):s=n.find(o=>o.label===t||o.shortName===t||o.shortName.includes(String(t))),s?(Lh("git",["stash","apply",`stash@{${s.index}}`],{cwd:e,timeout:15e3}),{ok:!0,label:s.label}):{ok:!1,error:`Snapshot not found: ${t}`}}catch(n){return{ok:!1,error:n.message}}}qh.exports={recordChange:Fx,undo:Bx,redo:Ux,getHistory:Wx,getUndoCount:Hx,getRedoCount:Gx,clearHistory:Yx,persistEntry:jh,loadPersistedHistory:zx,pruneHistory:Kx,createSnapshot:Vx,listSnapshots:Dh,restoreSnapshot:Xx}});var ru=ne((TM,Yh)=>{var it=require("fs"),Ht=require("path"),{atomicWrite:Jx,withFileLockSync:Zx}=Ws(),jt=[];function Er(){return Ht.join(process.cwd(),".nex","skills")}function Bh(){return Ht.join(process.cwd(),".nex","config.json")}function Uh(){let t=Er();return it.existsSync(t)||it.mkdirSync(t,{recursive:!0}),t}function su(){let t=Bh();if(!it.existsSync(t))return[];try{let e=JSON.parse(it.readFileSync(t,"utf-8"));return e.skills&&Array.isArray(e.skills.disabled)?e.skills.disabled:[]}catch{return[]}}function Wh(t){let e=Bh(),n=Ht.dirname(e);it.existsSync(n)||it.mkdirSync(n,{recursive:!0}),Zx(e,()=>{let s={};if(it.existsSync(e))try{s=JSON.parse(it.readFileSync(e,"utf-8"))}catch{s={}}s.skills||(s.skills={}),s.skills.disabled=t,Jx(e,JSON.stringify(s,null,2))})}function Hh(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 s=0;s<t.commands.length;s++){let o=t.commands[s];(!o.cmd||typeof o.cmd!="string")&&n.push(`commands[${s}].cmd must be a non-empty string`),o.handler!==void 0&&typeof o.handler!="function"&&n.push(`commands[${s}].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 s=0;s<t.tools.length;s++){let o=t.tools[s];(!o.function||!o.function.name||typeof o.function.name!="string")&&n.push(`tools[${s}].function.name must be a non-empty string`),o.execute!==void 0&&typeof o.execute!="function"&&n.push(`tools[${s}].execute must be a function`)}return{valid:n.length===0,errors:n}}function Gh(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],s=e[2].trim(),o=[],r=!1;for(let i of n.split(`
245
- `)){let a=i.trim();if(/^trigger:\s*$/i.test(a)){r=!0;continue}r&&a.startsWith("- ")?o.push(a.slice(2).trim().replace(/^["']|["']$/g,"")):r&&a&&!a.startsWith("#")&&(r=!1)}return{triggers:o,body:s}}function tu(t){try{let e=it.readFileSync(t,"utf-8").trim();if(!e)return null;let n=Ht.basename(t,".md"),{triggers:s,body:o}=Gh(e);return{name:n,type:"prompt",filePath:t,instructions:o||e,triggers:s,commands:[],tools:[]}}catch{return null}}function nu(t){try{let e=require(t),{valid:n,errors:s}=Hh(e,t);return n?{name:e.name||Ht.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}
246
- ${s.join(`
247
- `)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function ou(){jt=[];let t=su(),e=Er(),n=[];if(it.existsSync(e))try{n=it.readdirSync(e)}catch{n=[]}for(let o of n){let r=Ht.join(e,o),i;try{i=it.statSync(r)}catch{continue}if(!i.isFile())continue;let a=null;o.endsWith(".md")?a=tu(r):o.endsWith(".js")&&(a=nu(r)),a&&(a.enabled=!t.includes(a.name),jt.push(a))}let s=Ht.join(__dirname,"skills");if(!process.env.NEX_SKIP_BUILTIN_SKILLS&&it.existsSync(s)){let o;try{o=it.readdirSync(s).filter(r=>r.endsWith(".md")||r.endsWith(".js"))}catch{o=[]}for(let r of o){let i=Ht.join(s,r),a=Ht.basename(r,Ht.extname(r));if(jt.some(u=>u.name===a))continue;let l;try{l=it.statSync(i)}catch{continue}if(!l.isFile())continue;let c=r.endsWith(".md")?tu(i):nu(i);c&&(c._builtin=!0,c.enabled=!t.includes(c.name),jt.push(c))}}return jt}function Qx(){let t=[];for(let e of jt)!e.enabled||!e.instructions||t.push(`[Skill: ${e.name}]
242
+ ${o}`)}return e.join(`
243
+ `)}Ph.exports={isGitRepo:Ox,getCurrentBranch:Px,getStatus:Zc,getDiff:_a,getChangedFiles:Qc,analyzeDiff:Oh,createBranch:Mx,commit:Nx,formatDiffSummary:Lx,getDiffContext:jx,getMergeConflicts:Ix}});var Fh=ne((EM,qh)=>{var Ct=require("fs").promises,SM=require("fs"),un=require("path"),Dx=require("crypto"),{execSync:eu,execFileSync:Lh}=require("child_process"),qx=100*1024,Ih=50,Wt=[],jo=[];function Fx(t,e,n,o){for(Wt.push({tool:t,filePath:e,oldContent:n,newContent:o,timestamp:Date.now()});Wt.length>Ih;)Wt.shift();jo.length=0,jh(Wt[Wt.length-1]).catch(()=>{})}async function Bx(){if(Wt.length===0)return null;let t=Wt.pop();if(t.oldContent===null)try{await Ct.unlink(t.filePath)}catch{}else await Ct.writeFile(t.filePath,t.oldContent,"utf-8");return jo.push(t),{tool:t.tool,filePath:t.filePath,wasCreated:t.oldContent===null}}async function Ux(){if(jo.length===0)return null;let t=jo.pop();return await Ct.writeFile(t.filePath,t.newContent,"utf-8"),Wt.push(t),{tool:t.tool,filePath:t.filePath}}function Wx(t=10){return Wt.slice(-t).reverse().map(e=>({tool:e.tool,filePath:e.filePath,timestamp:e.timestamp}))}function Hx(){return Wt.length}function Gx(){return jo.length}function Yx({diskToo:t=!0}={}){if(Wt.length=0,jo.length=0,t){let e=xa();Ct.readdir(e).then(n=>{for(let o of n)o.endsWith(".json")&&Ct.unlink(un.join(e,o)).catch(()=>{})}).catch(()=>{})}}function xa(){return un.join(process.cwd(),".nex","history")}async function Mh(t,e){if(t==null)return{inline:!0,content:t};if(Buffer.byteLength(t,"utf-8")<=qx)return{inline:!0,content:t};let n=Dx.createHash("sha256").update(t,"utf-8").digest("hex"),o=un.join(e,"blobs");return await Ct.mkdir(o,{recursive:!0}),await Ct.writeFile(un.join(o,n),t,"utf-8"),{inline:!1,hash:n}}async function jh(t){let e=xa();await Ct.mkdir(e,{recursive:!0});let n=un.basename(t.filePath).replace(/[^a-zA-Z0-9]/g,"-"),o=`${t.timestamp}-${n}.json`,s=await Mh(t.oldContent,e),r=await Mh(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 Ct.writeFile(un.join(e,o),JSON.stringify(i),"utf-8")}async function Nh(t,e){if(!t)return null;if(t.inline)return t.content;let n=un.join(e,"blobs",t.hash);return Ct.readFile(n,"utf-8")}async function zx(){let t=xa(),e;try{e=await Ct.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 Ct.readFile(un.join(t,s),"utf-8"),i=JSON.parse(r),a=await Nh(i.oldContent,t),l=await Nh(i.newContent,t);Wt.push({tool:i.tool,filePath:i.filePath,timestamp:i.timestamp,oldContent:a,newContent:l}),o++}catch{}for(;Wt.length>Ih;)Wt.shift();return o}async function Kx(t=7){let e=xa(),n;try{n=await Ct.readdir(e)}catch{return 0}let o=Date.now()-t*24*60*60*1e3,s=n.filter(c=>c.endsWith(".json")),r=0,i=new Set,a=[];for(let c of s)try{let u=await Ct.readFile(un.join(e,c),"utf-8"),d=JSON.parse(u);d.timestamp<o?(a.push(c),r++):(d.oldContent&&!d.oldContent.inline&&d.oldContent.hash&&i.add(d.oldContent.hash),d.newContent&&!d.newContent.inline&&d.newContent.hash&&i.add(d.newContent.hash))}catch{}for(let c of a)try{await Ct.unlink(un.join(e,c))}catch{}let l=un.join(e,"blobs");try{let c=await Ct.readdir(l);for(let u of c)if(!i.has(u))try{await Ct.unlink(un.join(l,u))}catch{}}catch{}return r}var ka="nex-snapshot";function Vx(t,e=process.cwd()){let n=t?`${ka}-${t.replace(/[^a-zA-Z0-9_-]/g,"-")}`:`${ka}-${Date.now()}`;try{return eu("git status --porcelain",{cwd:e,timeout:1e4}).toString().trim()?(Lh("git",["stash","push","-u","-m",n],{cwd:e,timeout:15e3}),eu("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 Dh(t=process.cwd()){try{let e=eu("git stash list",{cwd:t,timeout:1e4}).toString().trim();return e?e.split(`
244
+ `).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(ka)?{index:parseInt(o[1],10),label:s,shortName:s.replace(`${ka}-`,""),date:n}:null}).filter(Boolean):[]}catch{return[]}}function Xx(t,e=process.cwd()){try{let n=Dh(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?(Lh("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}}}qh.exports={recordChange:Fx,undo:Bx,redo:Ux,getHistory:Wx,getUndoCount:Hx,getRedoCount:Gx,clearHistory:Yx,persistEntry:jh,loadPersistedHistory:zx,pruneHistory:Kx,createSnapshot:Vx,listSnapshots:Dh,restoreSnapshot:Xx}});var ru=ne((TM,Yh)=>{var it=require("fs"),Ht=require("path"),{atomicWrite:Jx,withFileLockSync:Zx}=Ws(),jt=[];function Er(){return Ht.join(process.cwd(),".nex","skills")}function Bh(){return Ht.join(process.cwd(),".nex","config.json")}function Uh(){let t=Er();return it.existsSync(t)||it.mkdirSync(t,{recursive:!0}),t}function su(){let t=Bh();if(!it.existsSync(t))return[];try{let e=JSON.parse(it.readFileSync(t,"utf-8"));return e.skills&&Array.isArray(e.skills.disabled)?e.skills.disabled:[]}catch{return[]}}function Wh(t){let e=Bh(),n=Ht.dirname(e);it.existsSync(n)||it.mkdirSync(n,{recursive:!0}),Zx(e,()=>{let o={};if(it.existsSync(e))try{o=JSON.parse(it.readFileSync(e,"utf-8"))}catch{o={}}o.skills||(o.skills={}),o.skills.disabled=t,Jx(e,JSON.stringify(o,null,2))})}function Hh(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 Gh(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(`
245
+ `)){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 tu(t){try{let e=it.readFileSync(t,"utf-8").trim();if(!e)return null;let n=Ht.basename(t,".md"),{triggers:o,body:s}=Gh(e);return{name:n,type:"prompt",filePath:t,instructions:s||e,triggers:o,commands:[],tools:[]}}catch{return null}}function nu(t){try{let e=require(t),{valid:n,errors:o}=Hh(e,t);return n?{name:e.name||Ht.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}
246
+ ${o.join(`
247
+ `)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function ou(){jt=[];let t=su(),e=Er(),n=[];if(it.existsSync(e))try{n=it.readdirSync(e)}catch{n=[]}for(let s of n){let r=Ht.join(e,s),i;try{i=it.statSync(r)}catch{continue}if(!i.isFile())continue;let a=null;s.endsWith(".md")?a=tu(r):s.endsWith(".js")&&(a=nu(r)),a&&(a.enabled=!t.includes(a.name),jt.push(a))}let o=Ht.join(__dirname,"skills");if(!process.env.NEX_SKIP_BUILTIN_SKILLS&&it.existsSync(o)){let s;try{s=it.readdirSync(o).filter(r=>r.endsWith(".md")||r.endsWith(".js"))}catch{s=[]}for(let r of s){let i=Ht.join(o,r),a=Ht.basename(r,Ht.extname(r));if(jt.some(u=>u.name===a))continue;let l;try{l=it.statSync(i)}catch{continue}if(!l.isFile())continue;let c=r.endsWith(".md")?tu(i):nu(i);c&&(c._builtin=!0,c.enabled=!t.includes(c.name),jt.push(c))}}return jt}function Qx(){let t=[];for(let e of jt)!e.enabled||!e.instructions||t.push(`[Skill: ${e.name}]
248
248
  ${e.instructions}`);return t.length===0?"":`SKILL INSTRUCTIONS:
249
249
  ${t.join(`
250
250
 
251
- `)}`}function ev(){let t=[];for(let e of jt)if(e.enabled)for(let n of e.commands)t.push({cmd:n.cmd,desc:n.desc||`[skill: ${e.name}]`});return t}function tv(){let t=[];for(let e of jt)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 nv(t,e){if(!t.startsWith("skill_"))return null;let n=t.substring(6);for(let s of jt)if(s.enabled){for(let o of s.tools)if(o.function.name===n&&o.execute)try{let r=await o.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 sv(t){let[e,...n]=t.split(/\s+/),s=n.join(" ").trim();for(let o of jt)if(o.enabled){for(let r of o.commands)if(r.cmd===e&&r.handler){try{let i=r.handler(s);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 ov(){return jt.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 rv(t){let e=jt.find(s=>s.name===t);if(!e)return!1;e.enabled=!0;let n=su().filter(s=>s!==t);return Wh(n),!0}function iv(t){let e=jt.find(s=>s.name===t);if(!e)return!1;e.enabled=!1;let n=su();return n.includes(t)||(n.push(t),Wh(n)),!0}function av(){return jt}async function lv(t,e={}){let{execFileSync:n}=require("child_process"),s=Uh(),o=t;/^[\w-]+\/[\w.-]+$/.test(t)&&(o=`https://github.com/${t}.git`);let r=e.name||Ht.basename(o,".git").replace(/^nex-skill-/,""),i=Ht.join(s,r);if(it.existsSync(i))return{ok:!1,name:r,error:`Skill "${r}" is already installed at ${i}. Remove it first to reinstall.`};try{if(!/^https?:\/\/[a-zA-Z0-9._\-/:.@]+$/.test(o))throw new Error(`Invalid git URL: ${o}`);n("git",["clone","--depth","1",o,i],{timeout:3e4,stdio:"pipe"})}catch(u){return{ok:!1,name:r,error:`Git clone failed: ${u.stderr?.toString().trim()||u.message}`}}let a=Ht.join(i,"skill.json"),l=it.existsSync(a),c=it.readdirSync(i).some(u=>(u.endsWith(".md")||u.endsWith(".js"))&&!u.startsWith("."));if(!l&&!c){try{it.rmSync(i,{recursive:!0,force:!0})}catch(u){console.error("skills.js line 562 failed:",u.message)}return{ok:!1,name:r,error:"No skill.json manifest or .md/.js skill file found in repository"}}if(l)try{let u=JSON.parse(it.readFileSync(a,"utf-8"));u.name||(u.name=r)}catch{try{it.rmSync(i,{recursive:!0,force:!0})}catch{}return{ok:!1,name:r,error:"Invalid skill.json \u2014 not valid JSON"}}return ou(),{ok:!0,name:r}}async function cv(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(o=>({name:o.name.replace(/^nex-skill-/,""),description:o.description||"(no description)",url:o.clone_url,stars:o.stargazers_count,owner:o.owner.login}))}catch(n){return[{name:"error",description:`Search failed: ${n.message}`,url:"",stars:0,owner:""}]}}function uv(t){let e=Ht.join(Er(),t);if(!it.existsSync(e))return{ok:!1,error:`Skill "${t}" not found in ${Er()}`};try{return it.rmSync(e,{recursive:!0,force:!0}),ou(),{ok:!0}}catch(n){return{ok:!1,error:n.message}}}function dv(t){if(!t)return[];let e=t.toLowerCase(),n=[];for(let s of jt){if(!s.enabled||!s.triggers||s.triggers.length===0)continue;if(s.triggers.some(r=>e.includes(r.toLowerCase()))){let r=(s.instructions||"").split(`
251
+ `)}`}function ev(){let t=[];for(let e of jt)if(e.enabled)for(let n of e.commands)t.push({cmd:n.cmd,desc:n.desc||`[skill: ${e.name}]`});return t}function tv(){let t=[];for(let e of jt)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 nv(t,e){if(!t.startsWith("skill_"))return null;let n=t.substring(6);for(let o of jt)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 sv(t){let[e,...n]=t.split(/\s+/),o=n.join(" ").trim();for(let s of jt)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 ov(){return jt.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 rv(t){let e=jt.find(o=>o.name===t);if(!e)return!1;e.enabled=!0;let n=su().filter(o=>o!==t);return Wh(n),!0}function iv(t){let e=jt.find(o=>o.name===t);if(!e)return!1;e.enabled=!1;let n=su();return n.includes(t)||(n.push(t),Wh(n)),!0}function av(){return jt}async function lv(t,e={}){let{execFileSync:n}=require("child_process"),o=Uh(),s=t;/^[\w-]+\/[\w.-]+$/.test(t)&&(s=`https://github.com/${t}.git`);let r=e.name||Ht.basename(s,".git").replace(/^nex-skill-/,""),i=Ht.join(o,r);if(it.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(u){return{ok:!1,name:r,error:`Git clone failed: ${u.stderr?.toString().trim()||u.message}`}}let a=Ht.join(i,"skill.json"),l=it.existsSync(a),c=it.readdirSync(i).some(u=>(u.endsWith(".md")||u.endsWith(".js"))&&!u.startsWith("."));if(!l&&!c){try{it.rmSync(i,{recursive:!0,force:!0})}catch(u){console.error("skills.js line 562 failed:",u.message)}return{ok:!1,name:r,error:"No skill.json manifest or .md/.js skill file found in repository"}}if(l)try{let u=JSON.parse(it.readFileSync(a,"utf-8"));u.name||(u.name=r)}catch{try{it.rmSync(i,{recursive:!0,force:!0})}catch{}return{ok:!1,name:r,error:"Invalid skill.json \u2014 not valid JSON"}}return ou(),{ok:!0,name:r}}async function cv(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 uv(t){let e=Ht.join(Er(),t);if(!it.existsSync(e))return{ok:!1,error:`Skill "${t}" not found in ${Er()}`};try{return it.rmSync(e,{recursive:!0,force:!0}),ou(),{ok:!0}}catch(n){return{ok:!1,error:n.message}}}function dv(t){if(!t)return[];let e=t.toLowerCase(),n=[];for(let o of jt){if(!o.enabled||!o.triggers||o.triggers.length===0)continue;if(o.triggers.some(r=>e.includes(r.toLowerCase()))){let r=(o.instructions||"").split(`
252
252
  `).slice(0,3).join(`
253
- `);n.push({name:s.name,instructions:r})}}return n}Yh.exports={initSkillsDir:Uh,loadAllSkills:ou,getSkillInstructions:Qx,getSkillCommands:ev,getSkillToolDefinitions:tv,routeSkillCall:nv,handleSkillCommand:sv,listSkills:ov,enableSkill:rv,disableSkill:iv,getLoadedSkills:av,installSkill:lv,searchSkills:cv,removeSkill:uv,matchSkillTriggers:dv,_getSkillsDir:Er,_validateScriptSkill:Hh,_loadMarkdownSkill:tu,_loadScriptSkill:nu,_parseFrontmatter:Gh}});var au=ne((RM,Zh)=>{var{spawn:fv}=require("child_process"),pv=require("path"),zh=require("fs"),es=new Map;function hv(){return pv.join(process.cwd(),".nex","config.json")}function iu(){let t=hv();if(!zh.existsSync(t))return{};try{return JSON.parse(zh.readFileSync(t,"utf-8")).mcpServers||{}}catch{return{}}}function va(t,e,n={},s=1e4){return new Promise((o,r)=>{let i=`${Date.now()}-${Math.random().toString(36).slice(2,6)}`,a=JSON.stringify({jsonrpc:"2.0",id:i,method:e,params:n})+`
254
- `,l="",c=setTimeout(()=>{d(),r(new Error(`MCP request timeout: ${e}`))},s);function u(f){l+=f.toString();let p=l.split(`
255
- `);for(let h of p)if(h.trim())try{let g=JSON.parse(h);if(g.id===i){d(),g.error?r(new Error(`MCP error: ${g.error.message||JSON.stringify(g.error)}`)):o(g.result);return}}catch{}l=p[p.length-1]||""}function d(){clearTimeout(c),t.stdout.removeListener("data",u)}t.stdout.on("data",u);try{t.stdin.write(a)}catch(f){d(),r(new Error(`MCP write failed: ${f.message}`))}})}async function Kh(t,e){if(es.has(t))return es.get(t);let n=["PATH","HOME","USER","SHELL","LANG","TERM","NODE_ENV"],s={};for(let i of n)process.env[i]&&(s[i]=process.env[i]);let o=fv(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:{...s,...e.env||{}}}),r={name:t,proc:o,tools:[],config:e};try{await va(o,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.2.0"}});let i=await va(o,"tools/list",{});return r.tools=i&&i.tools||[],es.set(t,r),r}catch(i){throw o.kill(),new Error(`Failed to connect MCP server '${t}': ${i.message}`)}}function Vh(t){let e=es.get(t);if(!e)return!1;try{e.proc.kill()}catch{}return es.delete(t),!0}function mv(){for(let[t]of es)Vh(t)}async function Xh(t,e,n={}){let s=es.get(t);if(!s)throw new Error(`MCP server not connected: ${t}`);let o=await va(s.proc,"tools/call",{name:e,arguments:n});return o&&Array.isArray(o.content)?o.content.filter(r=>r.type==="text").map(r=>r.text).join(`
256
- `):JSON.stringify(o)}function Jh(){let t=[];for(let[e,n]of es)for(let s of n.tools)t.push({server:e,name:s.name,description:s.description||"",inputSchema:s.inputSchema||{type:"object",properties:{}}});return t}function gv(){return Jh().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function yv(t,e){if(!t.startsWith("mcp_"))return null;let n=t.substring(4).split("_");if(n.length<2)return null;let s=n[0],o=n.slice(1).join("_");return Xh(s,o,e)}function bv(){let t=iu();return Object.entries(t).map(([e,n])=>{let s=es.get(e);return{name:e,command:n.command,connected:!!s,toolCount:s?s.tools.length:0}})}async function wv(){let t=iu(),e=[];for(let[n,s]of Object.entries(t))try{let o=await Kh(n,s);e.push({name:n,tools:o.tools.length})}catch(o){e.push({name:n,tools:0,error:o.message})}return e}Zh.exports={loadMCPConfig:iu,sendRequest:va,connectServer:Kh,disconnectServer:Vh,disconnectAll:mv,callTool:Xh,getAllTools:Jh,getMCPToolDefinitions:gv,routeMCPCall:yv,listServers:bv,connectAll:wv}});var Ea=ne((CM,nm)=>{var Qh=require("fs"),lu=require("path"),Sa=[],Tr=[],Hs={},Rr=["onToolResult","onModelResponse","onSessionStart","onSessionEnd","onFileChange","beforeToolExec","afterToolExec"];function em(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 Tr.some(s=>s.definition.function.name===n)?{ok:!1,error:`Tool "${n}" is already registered`}:(Tr.push({definition:{type:"function",...t},handler:e}),{ok:!0})}function tm(t,e){return Rr.includes(t)?typeof e!="function"?{ok:!1,error:"Handler must be a function"}:(Hs[t]||(Hs[t]=[]),Hs[t].push(e),{ok:!0}):{ok:!1,error:`Unknown event "${t}". Available: ${Rr.join(", ")}`}}async function cu(t,e){let n=Hs[t]||[],s=e;for(let o of n)try{let r=await o(s);r!==void 0&&(s=r)}catch(r){process.env.NEX_DEBUG&&console.error(`[plugin] Hook error on ${t}: ${r.message}`)}return s}function _v(){let t=lu.join(process.cwd(),".nex","plugins"),e=[];if(!Qh.existsSync(t))return{loaded:0,errors:[]};let n=Qh.readdirSync(t).filter(o=>o.endsWith(".js")),s={registerTool:em,registerHook:tm,EVENTS:Rr};for(let o of n){let r=lu.join(t,o);try{let i=require(r);if(typeof i=="function")i(s);else if(typeof i.setup=="function")i.setup(s);else{e.push(`${o}: Plugin must export a function or { setup: function }`);continue}Sa.push({name:i.name||lu.basename(o,".js"),filePath:r})}catch(i){e.push(`${o}: ${i.message}`)}}return{loaded:Sa.length,errors:e}}function $v(){return Tr.map(t=>t.definition)}async function kv(t,e,n={}){let s=Tr.find(a=>a.definition.function.name===t);if(!s)return null;let o=await cu("beforeToolExec",{name:t,args:e,options:n}),r=await s.handler(o.args||e,n);return(await cu("afterToolExec",{name:t,args:e,result:r})).result||r}function xv(){return[...Sa]}function vv(){let t={};for(let e of Rr)t[e]=(Hs[e]||[]).length;return t}function Sv(){Sa.length=0,Tr.length=0;for(let t of Object.keys(Hs))delete Hs[t]}nm.exports={registerTool:em,registerHook:tm,emit:cu,loadPlugins:_v,getPluginToolDefinitions:$v,executePluginTool:kv,getLoadedPlugins:xv,getHookCounts:vv,clearPlugins:Sv,EVENTS:Rr}});var uu=ne((AM,im)=>{var{getSkillToolDefinitions:Ev}=ru(),{getMCPToolDefinitions:Tv}=au(),{getPluginToolDefinitions:Rv}=Ea(),Ta=new Map;function sm(){let{TOOL_DEFINITIONS:t}=Do();return[...t,...Ev(),...Tv(),...Rv()]}function om(t){if(Ta.has(t))return Ta.get(t);let n=sm().find(o=>o.function.name===t);if(!n)return null;let s=n.function.parameters;return Ta.set(t,s),s}function Cv(){Ta.clear()}function Ra(t,e){if(!t||e.length===0)return null;let n=null,s=1/0;for(let o of e){let r=rm(t.toLowerCase(),o.toLowerCase());r<s&&(s=r,n=o)}return s<=Math.ceil(t.length/2)?n:null}function rm(t,e){let n=t.length,s=e.length,o=Array.from({length:n+1},()=>Array(s+1).fill(0));for(let r=0;r<=n;r++)o[r][0]=r;for(let r=0;r<=s;r++)o[0][r]=r;for(let r=1;r<=n;r++)for(let i=1;i<=s;i++)o[r][i]=t[r-1]===e[i-1]?o[r-1][i-1]:1+Math.min(o[r-1][i],o[r][i-1],o[r-1][i-1]);return o[n][s]}function Av(t,e){let n=om(t);if(n===null){let d=sm().map(p=>p.function.name),f=Ra(t,d);return{valid:!1,error:`Unknown tool "${t}".${f?` Did you mean "${f}"?`:""}
257
- Available tools: ${d.join(", ")}`}}if(!n||!n.properties)return{valid:!0};let s=n.required||[],o=Object.keys(n.properties),r=Object.keys(e),i=[],a={...e},l=!1;for(let u of s)if(!(u in e)||e[u]===void 0||e[u]===null){let d=Ra(u,r);d&&!o.includes(d)?(a[u]=e[d],delete a[d],l=!0):i.push(`Missing required parameter "${u}" (${n.properties[u]?.description||n.properties[u]?.type||"unknown"})`)}new Set(["grep","grep_search","search_files"]).has(t)&&(("-n"in a||"n"in a)&&!o.includes("-n")&&(delete a["-n"],delete a.n,l=!0),("-i"in a||"--ignore-case"in a)&&"ignore_case"in(n.properties||{})&&(a.ignore_case=!0,delete a["-i"],delete a["--ignore-case"],l=!0),("-r"in a||"--recursive"in a)&&(delete a["-r"],delete a["--recursive"],l=!0)),t==="read_file"&&("offset"in a&&!("line_start"in a)&&(a.line_start=a.offset,delete a.offset,l=!0),"start_line"in a&&!("line_start"in a)&&(a.line_start=a.start_line,delete a.start_line,l=!0),"end_line"in a&&!("line_end"in a)&&(a.line_end=a.end_line,delete a.end_line,l=!0));for(let u of Object.keys(a))if(!o.includes(u)){let d=Ra(u,o);if(d&&!(d in a))a[d]=a[u],delete a[u],l=!0;else if(!l){let f=d?` Did you mean "${d}"?`:"";i.push(`Unknown parameter "${u}".${f}`)}}for(let u of Object.keys(a)){if(!n.properties[u])continue;let d=n.properties[u].type,f=typeof a[u];d==="string"&&f==="number"?(a[u]=String(a[u]),l=!0):d==="number"&&f==="string"&&!isNaN(a[u])?(a[u]=Number(a[u]),l=!0):d==="boolean"&&f==="string"&&(a[u]=a[u]==="true",l=!0)}return i.length>0&&!l?{valid:!1,error:`Tool "${t}" argument errors:
253
+ `);n.push({name:o.name,instructions:r})}}return n}Yh.exports={initSkillsDir:Uh,loadAllSkills:ou,getSkillInstructions:Qx,getSkillCommands:ev,getSkillToolDefinitions:tv,routeSkillCall:nv,handleSkillCommand:sv,listSkills:ov,enableSkill:rv,disableSkill:iv,getLoadedSkills:av,installSkill:lv,searchSkills:cv,removeSkill:uv,matchSkillTriggers:dv,_getSkillsDir:Er,_validateScriptSkill:Hh,_loadMarkdownSkill:tu,_loadScriptSkill:nu,_parseFrontmatter:Gh}});var au=ne((RM,Zh)=>{var{spawn:fv}=require("child_process"),pv=require("path"),zh=require("fs"),es=new Map;function hv(){return pv.join(process.cwd(),".nex","config.json")}function iu(){let t=hv();if(!zh.existsSync(t))return{};try{return JSON.parse(zh.readFileSync(t,"utf-8")).mcpServers||{}}catch{return{}}}function va(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})+`
254
+ `,l="",c=setTimeout(()=>{d(),r(new Error(`MCP request timeout: ${e}`))},o);function u(f){l+=f.toString();let p=l.split(`
255
+ `);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{}l=p[p.length-1]||""}function d(){clearTimeout(c),t.stdout.removeListener("data",u)}t.stdout.on("data",u);try{t.stdin.write(a)}catch(f){d(),r(new Error(`MCP write failed: ${f.message}`))}})}async function Kh(t,e){if(es.has(t))return es.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=fv(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:{...o,...e.env||{}}}),r={name:t,proc:s,tools:[],config:e};try{await va(s,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.2.0"}});let i=await va(s,"tools/list",{});return r.tools=i&&i.tools||[],es.set(t,r),r}catch(i){throw s.kill(),new Error(`Failed to connect MCP server '${t}': ${i.message}`)}}function Vh(t){let e=es.get(t);if(!e)return!1;try{e.proc.kill()}catch{}return es.delete(t),!0}function mv(){for(let[t]of es)Vh(t)}async function Xh(t,e,n={}){let o=es.get(t);if(!o)throw new Error(`MCP server not connected: ${t}`);let s=await va(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(`
256
+ `):JSON.stringify(s)}function Jh(){let t=[];for(let[e,n]of es)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 gv(){return Jh().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function yv(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 Xh(o,s,e)}function bv(){let t=iu();return Object.entries(t).map(([e,n])=>{let o=es.get(e);return{name:e,command:n.command,connected:!!o,toolCount:o?o.tools.length:0}})}async function wv(){let t=iu(),e=[];for(let[n,o]of Object.entries(t))try{let s=await Kh(n,o);e.push({name:n,tools:s.tools.length})}catch(s){e.push({name:n,tools:0,error:s.message})}return e}Zh.exports={loadMCPConfig:iu,sendRequest:va,connectServer:Kh,disconnectServer:Vh,disconnectAll:mv,callTool:Xh,getAllTools:Jh,getMCPToolDefinitions:gv,routeMCPCall:yv,listServers:bv,connectAll:wv}});var Ea=ne((CM,nm)=>{var Qh=require("fs"),lu=require("path"),Sa=[],Tr=[],Hs={},Rr=["onToolResult","onModelResponse","onSessionStart","onSessionEnd","onFileChange","beforeToolExec","afterToolExec"];function em(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 Tr.some(o=>o.definition.function.name===n)?{ok:!1,error:`Tool "${n}" is already registered`}:(Tr.push({definition:{type:"function",...t},handler:e}),{ok:!0})}function tm(t,e){return Rr.includes(t)?typeof e!="function"?{ok:!1,error:"Handler must be a function"}:(Hs[t]||(Hs[t]=[]),Hs[t].push(e),{ok:!0}):{ok:!1,error:`Unknown event "${t}". Available: ${Rr.join(", ")}`}}async function cu(t,e){let n=Hs[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 _v(){let t=lu.join(process.cwd(),".nex","plugins"),e=[];if(!Qh.existsSync(t))return{loaded:0,errors:[]};let n=Qh.readdirSync(t).filter(s=>s.endsWith(".js")),o={registerTool:em,registerHook:tm,EVENTS:Rr};for(let s of n){let r=lu.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}Sa.push({name:i.name||lu.basename(s,".js"),filePath:r})}catch(i){e.push(`${s}: ${i.message}`)}}return{loaded:Sa.length,errors:e}}function $v(){return Tr.map(t=>t.definition)}async function kv(t,e,n={}){let o=Tr.find(a=>a.definition.function.name===t);if(!o)return null;let s=await cu("beforeToolExec",{name:t,args:e,options:n}),r=await o.handler(s.args||e,n);return(await cu("afterToolExec",{name:t,args:e,result:r})).result||r}function xv(){return[...Sa]}function vv(){let t={};for(let e of Rr)t[e]=(Hs[e]||[]).length;return t}function Sv(){Sa.length=0,Tr.length=0;for(let t of Object.keys(Hs))delete Hs[t]}nm.exports={registerTool:em,registerHook:tm,emit:cu,loadPlugins:_v,getPluginToolDefinitions:$v,executePluginTool:kv,getLoadedPlugins:xv,getHookCounts:vv,clearPlugins:Sv,EVENTS:Rr}});var uu=ne((AM,im)=>{var{getSkillToolDefinitions:Ev}=ru(),{getMCPToolDefinitions:Tv}=au(),{getPluginToolDefinitions:Rv}=Ea(),Ta=new Map;function sm(){let{TOOL_DEFINITIONS:t}=Do();return[...t,...Ev(),...Tv(),...Rv()]}function om(t){if(Ta.has(t))return Ta.get(t);let n=sm().find(s=>s.function.name===t);if(!n)return null;let o=n.function.parameters;return Ta.set(t,o),o}function Cv(){Ta.clear()}function Ra(t,e){if(!t||e.length===0)return null;let n=null,o=1/0;for(let s of e){let r=rm(t.toLowerCase(),s.toLowerCase());r<o&&(o=r,n=s)}return o<=Math.ceil(t.length/2)?n:null}function rm(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 Av(t,e){let n=om(t);if(n===null){let d=sm().map(p=>p.function.name),f=Ra(t,d);return{valid:!1,error:`Unknown tool "${t}".${f?` Did you mean "${f}"?`:""}
257
+ 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},l=!1;for(let u of o)if(!(u in e)||e[u]===void 0||e[u]===null){let d=Ra(u,r);d&&!s.includes(d)?(a[u]=e[d],delete a[d],l=!0):i.push(`Missing required parameter "${u}" (${n.properties[u]?.description||n.properties[u]?.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,l=!0),("-i"in a||"--ignore-case"in a)&&"ignore_case"in(n.properties||{})&&(a.ignore_case=!0,delete a["-i"],delete a["--ignore-case"],l=!0),("-r"in a||"--recursive"in a)&&(delete a["-r"],delete a["--recursive"],l=!0)),t==="read_file"&&("offset"in a&&!("line_start"in a)&&(a.line_start=a.offset,delete a.offset,l=!0),"start_line"in a&&!("line_start"in a)&&(a.line_start=a.start_line,delete a.start_line,l=!0),"end_line"in a&&!("line_end"in a)&&(a.line_end=a.end_line,delete a.end_line,l=!0));for(let u of Object.keys(a))if(!s.includes(u)){let d=Ra(u,s);if(d&&!(d in a))a[d]=a[u],delete a[u],l=!0;else if(!l){let f=d?` Did you mean "${d}"?`:"";i.push(`Unknown parameter "${u}".${f}`)}}for(let u of Object.keys(a)){if(!n.properties[u])continue;let d=n.properties[u].type,f=typeof a[u];d==="string"&&f==="number"?(a[u]=String(a[u]),l=!0):d==="number"&&f==="string"&&!isNaN(a[u])?(a[u]=Number(a[u]),l=!0):d==="boolean"&&f==="string"&&(a[u]=a[u]==="true",l=!0)}return i.length>0&&!l?{valid:!1,error:`Tool "${t}" argument errors:
258
258
  `+i.map(u=>` - ${u}`).join(`
259
259
  `)+`
260
260
 
261
- Expected parameters: ${JSON.stringify(n.properties,null,2)}`}:{valid:!0,corrected:l?a:null}}function Ov(t,e){let n=[],s={...t};if(!s.function&&!s.name)return n.push('Tool call missing both "function" and "name" fields'),{valid:!1,normalized:s,errors:n};if(!s.function&&s.name&&(s.function={name:s.name,arguments:s.arguments||s.args||{}},delete s.name,delete s.args),s.function&&s.function.args!==void 0&&s.function.arguments===void 0&&(s.function.arguments=s.function.args,delete s.function.args),s.function&&(s.function.arguments===void 0||s.function.arguments===null)&&(s.function.arguments={}),s.function&&typeof s.function.arguments=="string"){let o=s.function.arguments;if(o.trim()==="")s.function.arguments={};else try{s.function.arguments=JSON.parse(o)}catch(r){return n.push(`Invalid JSON in arguments${e?` (${e})`:""}: ${r.message}`),{valid:!1,normalized:s,errors:n}}}return s.function&&typeof s.function.arguments!="object"?(n.push(`Arguments must be an object, got ${typeof s.function.arguments}`),{valid:!1,normalized:s,errors:n}):!s.function.name||typeof s.function.name!="string"?(n.push("Tool call function name must be a non-empty string"),{valid:!1,normalized:s,errors:n}):{valid:n.length===0,normalized:s,errors:n}}im.exports={validateToolArgs:Av,validateToolCallFormat:Ov,closestMatch:Ra,levenshtein:rm,getCachedSchema:om,clearSchemaCache:Cv}});var um=ne((OM,cm)=>{var{levenshtein:Ca}=uu(),Pv=200,Mv=.3,Nv=2;function du(t){return t.replace(/\r\n/g,`
261
+ Expected parameters: ${JSON.stringify(n.properties,null,2)}`}:{valid:!0,corrected:l?a:null}}function Ov(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}}im.exports={validateToolArgs:Av,validateToolCallFormat:Ov,closestMatch:Ra,levenshtein:rm,getCachedSchema:om,clearSchemaCache:Cv}});var um=ne((OM,cm)=>{var{levenshtein:Ca}=uu(),Pv=200,Mv=.3,Nv=2;function du(t){return t.replace(/\r\n/g,`
262
262
  `).replace(/\r/g,`
263
263
  `).replace(/\t/g," ".repeat(Nv)).split(`
264
- `).map(e=>{let n=e.replace(/\s+$/,""),s=n.match(/^(\s*)(.*)/);if(!s)return n;let[,o,r]=s;return o+r.replace(/ {2,}/g," ")}).join(`
265
- `)}function Lv(t,e){if(t.includes(e))return e;if(e.length<10)return null;let n=du(t),s=du(e);if(!n.includes(s))return null;let o=t.split(`
264
+ `).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(`
265
+ `)}function Lv(t,e){if(t.includes(e))return e;if(e.length<10)return null;let n=du(t),o=du(e);if(!n.includes(o))return null;let s=t.split(`
266
266
  `),r=n.split(`
267
- `),i=s.split(`
268
- `),a=i[0],l=i[i.length-1];for(let c=0;c<=r.length-i.length;c++){let u=!0;for(let d=0;d<i.length;d++)if(r[c+d]!==i[d]){u=!1;break}if(u)return o.slice(c,c+i.length).join(`
269
- `)}if(i.length===1){for(let c=0;c<r.length;c++)if(r[c].indexOf(s)!==-1)return o[c]}return null}function Iv(t,e){if(!t||!e)return null;let n=t.split(`
270
- `),o=e.split(`
271
- `).length;return n.length===0||o===0?null:o===1?jv(n,e):qv(n,e,o)}function am(t){return Math.max(1,Math.floor(t/Pv))}function lm(t,e){return t<=Math.ceil(e*Mv)}function jv(t,e){let n=e.trim(),s=am(t.length),o=null,r=1/0;for(let i=0;i<t.length;i+=s){let a=t[i];if(!a.trim())continue;let l=Ca(a.trim(),n);l<r&&(r=l,o={text:a,distance:l,line:i+1})}return o&&s>1&&(o=Dv(t,n,o,s)||o,r=o.distance),lm(r,e.length)?o:null}function Dv(t,e,n,s){let o=n.line-1,r=Math.max(0,o-s),i=Math.min(t.length-1,o+s),a=n.distance,l=null;for(let c=r;c<=i;c++){let u=t[c];if(!u.trim())continue;let d=Ca(u.trim(),e);d<a&&(a=d,l={text:u,distance:d,line:c+1})}return l}function qv(t,e,n){let s=t.length-n+1;if(s<=0)return null;let o=am(s),r=null,i=1/0;for(let a=0;a<s;a+=o){let l=t.slice(a,a+n).join(`
272
- `),c=Ca(l,e);c<i&&(i=c,r={text:l,distance:c,line:a+1})}return r&&o>1&&(r=Fv(t,e,r,o,n,s)||r,i=r.distance),lm(i,e.length)?r:null}function Fv(t,e,n,s,o,r){let i=n.line-1,a=Math.max(0,i-s),l=Math.min(r-1,i+s),c=n.distance,u=null;for(let d=a;d<=l;d++){let f=t.slice(d,d+o).join(`
267
+ `),i=o.split(`
268
+ `),a=i[0],l=i[i.length-1];for(let c=0;c<=r.length-i.length;c++){let u=!0;for(let d=0;d<i.length;d++)if(r[c+d]!==i[d]){u=!1;break}if(u)return s.slice(c,c+i.length).join(`
269
+ `)}if(i.length===1){for(let c=0;c<r.length;c++)if(r[c].indexOf(o)!==-1)return s[c]}return null}function Iv(t,e){if(!t||!e)return null;let n=t.split(`
270
+ `),s=e.split(`
271
+ `).length;return n.length===0||s===0?null:s===1?jv(n,e):qv(n,e,s)}function am(t){return Math.max(1,Math.floor(t/Pv))}function lm(t,e){return t<=Math.ceil(e*Mv)}function jv(t,e){let n=e.trim(),o=am(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 l=Ca(a.trim(),n);l<r&&(r=l,s={text:a,distance:l,line:i+1})}return s&&o>1&&(s=Dv(t,n,s,o)||s,r=s.distance),lm(r,e.length)?s:null}function Dv(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,l=null;for(let c=r;c<=i;c++){let u=t[c];if(!u.trim())continue;let d=Ca(u.trim(),e);d<a&&(a=d,l={text:u,distance:d,line:c+1})}return l}function qv(t,e,n){let o=t.length-n+1;if(o<=0)return null;let s=am(o),r=null,i=1/0;for(let a=0;a<o;a+=s){let l=t.slice(a,a+n).join(`
272
+ `),c=Ca(l,e);c<i&&(i=c,r={text:l,distance:c,line:a+1})}return r&&s>1&&(r=Fv(t,e,r,s,n,o)||r,i=r.distance),lm(i,e.length)?r:null}function Fv(t,e,n,o,s,r){let i=n.line-1,a=Math.max(0,i-o),l=Math.min(r-1,i+o),c=n.distance,u=null;for(let d=a;d<=l;d++){let f=t.slice(d,d+s).join(`
273
273
  `),p=Ca(f,e);p<c&&(c=p,u={text:f,distance:p,line:d+1})}return u}cm.exports={normalizeWhitespace:du,fuzzyFindText:Lv,findMostSimilar:Iv}});var wm=ne((PM,pu)=>{var dm=require("fs"),Bv=require("path"),{execFileSync:Uv}=require("child_process"),fm=["--",".",":!*.lock",":!*.min.js",":!*.min.css",":!package-lock.json",":!yarn.lock",":!dist/",":!tests/hooks-pre-push.test.js"],Wv=/(^|\/)(tests\/.*\.test\.(js|ts|jsx|tsx)|__tests__\/.*\.(js|ts|jsx|tsx))$/i,pm=[{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}],Hv=/(^|\/)\.env(?:\.[^/]+)?\.(example|sample|template)$/i,hm=[{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 Aa(t,e=process.cwd()){return Uv("git",t,{cwd:e,encoding:"utf8"})}function Gv(t=process.cwd()){return Aa(["rev-parse","--show-toplevel"],t).trim()}function Yv(t){let e=Bv.join(t,".nex","push-allowlist");return dm.existsSync(e)?dm.readFileSync(e,"utf8").split(`
274
- `).map(n=>n.trim()).filter(n=>n&&!n.startsWith("#")):[]}function fu(t,e){return e.some(n=>t.includes(n))}function mm(t){return Hv.test(t)}function gm(t,e){let n=[];for(let s of t)if(!mm(s))for(let o of hm)o.regex.test(s)&&(fu(s,e)||n.push({category:o.category,location:s,preview:s}));return n}function zv(t){let e=t.split(`
275
- `),n=[],s="";for(let o=0;o<e.length;o++){let r=e[o];if(r.startsWith("+++ b/")){s=r.slice(6);continue}!r.startsWith("+")||r.startsWith("+++")||n.push({filePath:s,lineNumber:o+1,text:r.slice(1),raw:r})}return n}function ym(t,e){let n=[];for(let s of zv(t))if(!Wv.test(s.filePath||""))for(let o of pm)o.regex.test(s.text)&&(fu(s.raw,e)||fu(s.text,e)||n.push({category:o.category,location:`${s.lineNumber}:${s.raw}`,preview:s.raw}));return n}function Kv(t){return Aa(["diff","--cached","--name-only","--diff-filter=ACMR","-z"],t).split("\0").filter(Boolean)}function Vv(t,e){return Aa(["diff",e,...fm],t)}function Xv(t){return Aa(["diff","--cached",...fm],t)}function bm({repoRoot:t,mode:e,range:n}){let s=Yv(t),o=e==="staged"?Kv(t):[],r=gm(o,s),i=e==="range"?Vv(t,n):Xv(t),a=ym(i,s);return[...r,...a]}function Jv(t){return t.map(e=>` [${e.category}]
274
+ `).map(n=>n.trim()).filter(n=>n&&!n.startsWith("#")):[]}function fu(t,e){return e.some(n=>t.includes(n))}function mm(t){return Hv.test(t)}function gm(t,e){let n=[];for(let o of t)if(!mm(o))for(let s of hm)s.regex.test(o)&&(fu(o,e)||n.push({category:s.category,location:o,preview:o}));return n}function zv(t){let e=t.split(`
275
+ `),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 ym(t,e){let n=[];for(let o of zv(t))if(!Wv.test(o.filePath||""))for(let s of pm)s.regex.test(o.text)&&(fu(o.raw,e)||fu(o.text,e)||n.push({category:s.category,location:`${o.lineNumber}:${o.raw}`,preview:o.raw}));return n}function Kv(t){return Aa(["diff","--cached","--name-only","--diff-filter=ACMR","-z"],t).split("\0").filter(Boolean)}function Vv(t,e){return Aa(["diff",e,...fm],t)}function Xv(t){return Aa(["diff","--cached",...fm],t)}function bm({repoRoot:t,mode:e,range:n}){let o=Yv(t),s=e==="staged"?Kv(t):[],r=gm(s,o),i=e==="range"?Vv(t,n):Xv(t),a=ym(i,o);return[...r,...a]}function Jv(t){return t.map(e=>` [${e.category}]
276
276
  ${e.location}`).join(`
277
- `)}function Zv(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 Qv(){let t=Zv(process.argv.slice(2)),e=Gv(),n=bm({repoRoot:e,mode:t.mode,range:t.range});if(n.length===0)return;let s=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 ${s}:`),console.log(Jv(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===pu&&Qv();pu.exports={SECRET_PATTERNS:pm,SENSITIVE_FILE_RULES:hm,scanDiffText:ym,scanFileNames:gm,scanRepo:bm,isSafeExampleFile:mm}});var $m=ne((NM,_m)=>{var{C:MM}=xt(),{SECRET_PATTERNS:eS}=wm(),tS=[{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 nS(t,e){let n=e.split(`
278
- `),s=[],o=t?`.${t.split(".").pop()}`:"";for(let r=0;r<n.length;r++){let i=n[r],a=r+1;for(let l of eS)l.regex.test(i)&&s.push({line:a,message:`Potential secret detected: ${l.category}`,severity:"error"});for(let l of tS)l.ext&&!l.ext.includes(o)||l.regex.test(i)&&s.push({line:a,message:l.message||`Found ${l.name}`,severity:l.severity||"warn"})}return n.length>500&&s.push({line:0,message:`Large file detected (${n.length} lines). Consider refactoring.`,severity:"info"}),s}function sS(){let t=process.memoryUsage();return{rss:Math.round(t.rss/1024/1024*100)/100,heapUsed:Math.round(t.heapUsed/1024/1024*100)/100}}_m.exports={runDiagnostics:nS,getMemoryUsage:sS}});var In=ne((LM,Mm)=>{var Gs=require("fs").promises,Gt=require("path"),{exec:oS}=require("util").promisify(require("child_process").exec),gs=[],gu=null,Oa=!1,mu=0,rS=6e4;function yu(t){return!(gs.length===0||gu!==t||Date.now()-mu>rS)}async function Em(t){if(!Oa&&!yu(t)){Oa=!0,gu=t;try{try{let{stdout:s}=await oS("rg --files",{cwd:t,timeout:5e3});gs=s.split(`
279
- `).filter(Boolean),mu=Date.now(),Oa=!1;return}catch{}let e=[],n=async(s,o)=>{let r;try{r=await Gs.readdir(s,{withFileTypes:!0})}catch{return}for(let i of r){if(i.name==="node_modules"||i.name===".git"||i.name.startsWith("."))continue;let a=o?`${o}/${i.name}`:i.name;i.isDirectory()?await n(Gt.join(s,i.name),a):e.push(a)}};await n(t,""),gs=e,mu=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{Oa=!1}}}function Cr(){return gs}function iS(){return gu}function aS(t){return gs.filter(e=>Gt.basename(e)===t)}function lS(t){let e=t.toLowerCase();return gs.filter(n=>n.toLowerCase().includes(e)).slice(0,20)}function Tm(t,e){let n=t.length,s=e.length;if(n===0)return s;if(s===0)return n;let o=Array.from({length:s+1},(r,i)=>i);for(let r=1;r<=n;r++){let i=r-1;o[0]=r;for(let a=1;a<=s;a++){let l=t[r-1]===e[a-1]?i:1+Math.min(o[a],o[a-1],i);i=o[a],o[a]=l}}return o[s]}function Rm(t,e){let n=t.toLowerCase(),s=e.toLowerCase();if(n===s)return 1e3;let o=n.split("/").filter(Boolean),r=s.split("/").filter(Boolean),i=0;for(let u=1;u<=Math.min(o.length,r.length)&&o[o.length-u]===r[r.length-u];u++)i=u;if(i>0&&i===r.length)return 500+i*100;let a=Gt.basename(t).toLowerCase(),l=Gt.basename(e).toLowerCase(),c=0;if(a===l)c+=80;else{let u=Math.max(a.length,l.length);if(u>0&&u<100){let f=1-Tm(a,l)/u;f>=.6&&(c+=Math.round(f*50))}}if((n.includes(s)||s.includes(n))&&(c+=20),r.length>1){let u=new Set(o),d=0;for(let f of r)u.has(f)&&d++;c+=d*10}return i>0&&(c+=i*30),c}function cS(t,{limit:e=10,minScore:n=15}={}){if(!t||gs.length===0)return[];let s=[];for(let o of gs){let r=Rm(o,t);r>=n&&s.push({file:o,score:r})}return s.sort((o,r)=>r.score-o.score),s.slice(0,e)}var hu=null,km=0,xm=null,Cm=12e4,Pa=null,vm=0,Sm=null,Am=new Set([".js",".ts",".jsx",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".rb"]);function Om(t,e){let n=[],s=t.split(`
280
- `);for(let o=0;o<s.length;o++){let r=s[o],i=o+1;if([".js",".ts",".jsx",".tsx",".mjs",".cjs"].includes(e)){let a=r.match(/(?:export\s+)?(?:async\s+)?function\s+(\w+)/);a&&n.push({type:"function",name:a[1],line:i});let l=r.match(/(?:export\s+)?class\s+(\w+)/);l&&n.push({type:"class",name:l[1],line:i});let c=r.match(/(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?(?:\([^)]*\)|[\w$]+)\s*=>/);c&&n.push({type:"function",name:c[1],line:i});let u=r.match(/module\.exports\s*=\s*\{([^}]+)\}/);if(u){let f=u[1].split(",").map(p=>p.trim().split(":")[0].trim()).filter(Boolean);for(let p of f)/^\w+$/.test(p)&&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 l=r.match(/^class\s+(\w+)/);l&&n.push({type:"class",name:l[1],line:i});let c=r.match(/^(?:from\s+(\S+)\s+)?import\s+(\S+)/);c&&n.push({type:"import",name:c[1]||c[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 l=r.match(/^type\s+(\w+)\s+struct/);l&&n.push({type:"class",name:l[1],line:i})}}return n}async function Ma(t){t=t||process.cwd();let e=Gt.join(t,".nex","index","content-index.json"),n={};if(hu&&xm===t&&Date.now()-km<Cm)return hu;try{let i=await Gs.readFile(e,"utf-8");n=JSON.parse(i)}catch{n={files:{}}}let s=Cr();(!yu(t)||s.length===0)&&(await Em(t),s=Cr());let o={files:{}},r=!1;for(let i of Cr()){let a=Gt.extname(i);if(!Am.has(a))continue;let l=Gt.join(t,i);try{let u=(await Gs.stat(l)).mtimeMs;if(n.files[i]&&n.files[i].mtime===u){o.files[i]=n.files[i];continue}let d=await Gs.readFile(l,"utf-8"),f=Om(d,a);o.files[i]={defs:f,mtime:u},r=!0}catch{}}if(r){let i=Gt.join(t,".nex","index");await Gs.mkdir(i,{recursive:!0}),await Gs.writeFile(e,JSON.stringify(o),"utf-8")}return hu=o,km=Date.now(),xm=t,o}async function uS(t,e,n){let s=await Ma(n),o=[],r=t.toLowerCase();for(let[i,a]of Object.entries(s.files))for(let l of a.defs)e&&l.type!==e||l.name.toLowerCase().includes(r)&&o.push({file:i,type:l.type,name:l.name,line:l.line});return o.sort((i,a)=>{let l=i.name.toLowerCase()===r?0:1,c=a.name.toLowerCase()===r?0:1;if(l!==c)return l-c;let u=i.name.toLowerCase().startsWith(r)?0:1,d=a.name.toLowerCase().startsWith(r)?0:1;return u-d}),o.slice(0,50)}function dS(t,e,n){if(!e||!e.startsWith("."))return null;let s=Gt.posix.dirname(t.replace(/\\/g,"/")),o=Gt.posix.normalize(Gt.posix.join(s==="."?"":s,e)),r=[];if(Gt.posix.extname(o))r.push(o);else for(let a of Am)r.push(`${o}${a}`),r.push(Gt.posix.join(o,`index${a}`));for(let a of r)if(n.has(a))return a;return null}async function bu(t){if(t=t||process.cwd(),Pa&&Sm===t&&Date.now()-vm<Cm)return Pa;let e=await Ma(t),n=Cr(),s=new Set(n.map(i=>i.replace(/\\/g,"/"))),o={},r={};for(let i of Object.keys(e.files||{})){let a=i.replace(/\\/g,"/"),l=Array.isArray(e.files[i]?.defs)?e.files[i].defs:[],c=[],u=new Set;for(let d of l){if(d.type!=="import")continue;let f=dS(a,d.name,s);!f||f===a||u.has(f)||(u.add(f),c.push(f),r[f]||(r[f]=[]),r[f].push(a))}o[a]=c}for(let[i,a]of Object.entries(r))r[i]=[...new Set(a)].sort();return Pa={importsByFile:o,importedByFile:r},vm=Date.now(),Sm=t,Pa}async function fS(t,e,n=6){if(!t)return[];let s=await bu(e),o=String(t).replace(/\\/g,"/"),r=[...s.importsByFile[o]||[],...s.importedByFile[o]||[]];return[...new Set(r)].filter(i=>i!==o).slice(0,n)}async function pS(t,e=4){let n=await bu(t),s=new Map;for(let[o,r]of Object.entries(n.importsByFile||{}))s.set(o,(s.get(o)||0)+r.length);for(let[o,r]of Object.entries(n.importedByFile||{}))s.set(o,(s.get(o)||0)+r.length);return[...s.entries()].filter(([,o])=>o>0).sort((o,r)=>r[1]-o[1]||o[0].localeCompare(r[0])).slice(0,e).map(([o,r])=>`${o} (${r} links)`)}function Pm(t){return String(t).replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function hS(t,e){let n=Pm(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(o=>o.test(t))}async function mS(t,e,n={}){e=e||process.cwd();let{excludeFile:s=null,excludeLine:o=null,limit:r=6}=n;if(!t||typeof t!="string")return[];let i=await Ma(e),a=Pm(t),l=new RegExp(`\\b${a}\\s*\\(`),c=new RegExp(`\\b${a}\\b`),u=[];for(let d of Object.keys(i.files||{})){let f=d.replace(/\\/g,"/");try{let p=Gt.join(e,f),g=(await Gs.readFile(p,"utf-8")).split(`
281
- `);for(let w=0;w<g.length;w++){let k=g[w],T=w+1;if(!c.test(k)||s&&f===s&&o===T||hS(k,t))continue;let $=(f===s?0:4)+(l.test(k)?3:1);u.push({file:f,line:T,context:k.trim(),score:$})}}catch{}}return u.sort((d,f)=>f.score!==d.score?f.score-d.score:d.file.localeCompare(f.file)||d.line-f.line),u.slice(0,r)}Mm.exports={refreshIndex:Em,getFileIndex:Cr,getIndexedCwd:iS,findFileInIndex:aS,searchIndex:lS,isIndexValid:yu,buildContentIndex:Ma,searchContentIndex:uS,extractDefinitions:Om,buildImportGraph:bu,getRelatedFiles:fS,summarizeModuleHubs:pS,findSymbolReferences:mS,smartSearch:cS,scorePathMatch:Rm,pathLevenshtein:Tm}});var qo=ne((IM,qm)=>{var Na=require("fs"),Da=require("path"),qa=require("os"),{execFile:gS}=require("child_process"),{promisify:yS}=require("util"),wu=yS(gS),bS=Da.join(qa.homedir(),".nex","servers.json"),La=Da.join(qa.tmpdir(),"nex-ssh-sockets");function wS(){return Da.join(process.cwd(),".nex","servers.json")}function Nm(){let t=s=>{if(!Na.existsSync(s))return{};try{return JSON.parse(Na.readFileSync(s,"utf-8"))}catch{return{}}},e=t(bS),n=t(wS());return{...e,...n}}function _S(t){let e=Nm();if(e[t])return{...e[t],_name:t};if(/^[\w.-]+@[\w.-]+$/.test(t)||/[\w-]+\.[\w.-]+/.test(t)||t==="localhost"){let[o,r]=t.includes("@")?t.split("@"):[void 0,t];return{host:r,user:o}}let n=Object.keys(e),s=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}". ${s}`)}function $S(){Na.existsSync(La)||Na.mkdirSync(La,{recursive:!0})}function Lm(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=yes","-o","ServerAliveInterval=30"];t.key&&e.push("-i",t.key.replace(/^~/,qa.homedir())),t.port&&Number(t.port)!==22&&e.push("-p",String(t.port)),$S();let n=t.user?`${t.user}@${t.host}`:t.host,s=Da.join(La,n.replace(/[@.:]/g,"_"));return e.push("-o","ControlMaster=auto","-o",`ControlPath=${s}`,"-o","ControlPersist=120"),e.push(n),{args:e,target:n}}function Im(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=yes","-r"];return t.key&&e.push("-i",t.key.replace(/^~/,qa.homedir())),t.port&&Number(t.port)!==22&&e.push("-P",String(t.port)),e}async function Ia(t,e,{timeout:n=3e4,sudo:s=!1}={}){let{args:o}=Lm(t),r=s&&t.sudo?`sudo sh -c ${JSON.stringify(e)}`:e;try{let{stdout:i,stderr:a}=await wu("ssh",[...o,r],{timeout:n,maxBuffer:4194304});return{stdout:i||"",stderr:a||"",exitCode:0}}catch(i){let a=typeof i.code=="number"?i.code:1,l=(i.stderr||i.message||"").toString();return{stdout:(i.stdout||"").toString(),stderr:l,exitCode:a,error:Fa(l,t)}}}async function kS(t,e,n,{timeout:s=12e4}={}){let o=Im(t),r=t.user?`${t.user}@${t.host}`:t.host;o.push(e,`${r}:${n}`);try{let{stdout:i,stderr:a}=await wu("scp",o,{timeout:s,maxBuffer:1048576});return i||a||`Uploaded ${e} \u2192 ${r}:${n}`}catch(i){let a=(i.stderr||i.message||"").toString();throw new Error(Fa(a,t)||a)}}async function xS(t,e,n,{timeout:s=12e4}={}){let o=Im(t),r=t.user?`${t.user}@${t.host}`:t.host;o.push(`${r}:${e}`,n);try{let{stdout:i,stderr:a}=await wu("scp",o,{timeout:s,maxBuffer:1048576});return i||a||`Downloaded ${r}:${e} \u2192 ${n}`}catch(i){let a=(i.stderr||i.message||"").toString();throw new Error(Fa(a,t)||a)}}function Fa(t,e){if(!t)return"";if(/connection refused/i.test(t)){let n=e.port||22;return`${t}
277
+ `)}function Zv(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 Qv(){let t=Zv(process.argv.slice(2)),e=Gv(),n=bm({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(Jv(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===pu&&Qv();pu.exports={SECRET_PATTERNS:pm,SENSITIVE_FILE_RULES:hm,scanDiffText:ym,scanFileNames:gm,scanRepo:bm,isSafeExampleFile:mm}});var $m=ne((NM,_m)=>{var{C:MM}=xt(),{SECRET_PATTERNS:eS}=wm(),tS=[{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 nS(t,e){let n=e.split(`
278
+ `),o=[],s=t?`.${t.split(".").pop()}`:"";for(let r=0;r<n.length;r++){let i=n[r],a=r+1;for(let l of eS)l.regex.test(i)&&o.push({line:a,message:`Potential secret detected: ${l.category}`,severity:"error"});for(let l of tS)l.ext&&!l.ext.includes(s)||l.regex.test(i)&&o.push({line:a,message:l.message||`Found ${l.name}`,severity:l.severity||"warn"})}return n.length>500&&o.push({line:0,message:`Large file detected (${n.length} lines). Consider refactoring.`,severity:"info"}),o}function sS(){let t=process.memoryUsage();return{rss:Math.round(t.rss/1024/1024*100)/100,heapUsed:Math.round(t.heapUsed/1024/1024*100)/100}}_m.exports={runDiagnostics:nS,getMemoryUsage:sS}});var In=ne((LM,Mm)=>{var Gs=require("fs").promises,Gt=require("path"),{exec:oS}=require("util").promisify(require("child_process").exec),gs=[],gu=null,Oa=!1,mu=0,rS=6e4;function yu(t){return!(gs.length===0||gu!==t||Date.now()-mu>rS)}async function Em(t){if(!Oa&&!yu(t)){Oa=!0,gu=t;try{try{let{stdout:o}=await oS("rg --files",{cwd:t,timeout:5e3});gs=o.split(`
279
+ `).filter(Boolean),mu=Date.now(),Oa=!1;return}catch{}let e=[],n=async(o,s)=>{let r;try{r=await Gs.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(Gt.join(o,i.name),a):e.push(a)}};await n(t,""),gs=e,mu=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{Oa=!1}}}function Cr(){return gs}function iS(){return gu}function aS(t){return gs.filter(e=>Gt.basename(e)===t)}function lS(t){let e=t.toLowerCase();return gs.filter(n=>n.toLowerCase().includes(e)).slice(0,20)}function Tm(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 l=t[r-1]===e[a-1]?i:1+Math.min(s[a],s[a-1],i);i=s[a],s[a]=l}}return s[o]}function Rm(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 u=1;u<=Math.min(s.length,r.length)&&s[s.length-u]===r[r.length-u];u++)i=u;if(i>0&&i===r.length)return 500+i*100;let a=Gt.basename(t).toLowerCase(),l=Gt.basename(e).toLowerCase(),c=0;if(a===l)c+=80;else{let u=Math.max(a.length,l.length);if(u>0&&u<100){let f=1-Tm(a,l)/u;f>=.6&&(c+=Math.round(f*50))}}if((n.includes(o)||o.includes(n))&&(c+=20),r.length>1){let u=new Set(s),d=0;for(let f of r)u.has(f)&&d++;c+=d*10}return i>0&&(c+=i*30),c}function cS(t,{limit:e=10,minScore:n=15}={}){if(!t||gs.length===0)return[];let o=[];for(let s of gs){let r=Rm(s,t);r>=n&&o.push({file:s,score:r})}return o.sort((s,r)=>r.score-s.score),o.slice(0,e)}var hu=null,km=0,xm=null,Cm=12e4,Pa=null,vm=0,Sm=null,Am=new Set([".js",".ts",".jsx",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".rb"]);function Om(t,e){let n=[],o=t.split(`
280
+ `);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 l=r.match(/(?:export\s+)?class\s+(\w+)/);l&&n.push({type:"class",name:l[1],line:i});let c=r.match(/(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?(?:\([^)]*\)|[\w$]+)\s*=>/);c&&n.push({type:"function",name:c[1],line:i});let u=r.match(/module\.exports\s*=\s*\{([^}]+)\}/);if(u){let f=u[1].split(",").map(p=>p.trim().split(":")[0].trim()).filter(Boolean);for(let p of f)/^\w+$/.test(p)&&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 l=r.match(/^class\s+(\w+)/);l&&n.push({type:"class",name:l[1],line:i});let c=r.match(/^(?:from\s+(\S+)\s+)?import\s+(\S+)/);c&&n.push({type:"import",name:c[1]||c[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 l=r.match(/^type\s+(\w+)\s+struct/);l&&n.push({type:"class",name:l[1],line:i})}}return n}async function Ma(t){t=t||process.cwd();let e=Gt.join(t,".nex","index","content-index.json"),n={};if(hu&&xm===t&&Date.now()-km<Cm)return hu;try{let i=await Gs.readFile(e,"utf-8");n=JSON.parse(i)}catch{n={files:{}}}let o=Cr();(!yu(t)||o.length===0)&&(await Em(t),o=Cr());let s={files:{}},r=!1;for(let i of Cr()){let a=Gt.extname(i);if(!Am.has(a))continue;let l=Gt.join(t,i);try{let u=(await Gs.stat(l)).mtimeMs;if(n.files[i]&&n.files[i].mtime===u){s.files[i]=n.files[i];continue}let d=await Gs.readFile(l,"utf-8"),f=Om(d,a);s.files[i]={defs:f,mtime:u},r=!0}catch{}}if(r){let i=Gt.join(t,".nex","index");await Gs.mkdir(i,{recursive:!0}),await Gs.writeFile(e,JSON.stringify(s),"utf-8")}return hu=s,km=Date.now(),xm=t,s}async function uS(t,e,n){let o=await Ma(n),s=[],r=t.toLowerCase();for(let[i,a]of Object.entries(o.files))for(let l of a.defs)e&&l.type!==e||l.name.toLowerCase().includes(r)&&s.push({file:i,type:l.type,name:l.name,line:l.line});return s.sort((i,a)=>{let l=i.name.toLowerCase()===r?0:1,c=a.name.toLowerCase()===r?0:1;if(l!==c)return l-c;let u=i.name.toLowerCase().startsWith(r)?0:1,d=a.name.toLowerCase().startsWith(r)?0:1;return u-d}),s.slice(0,50)}function dS(t,e,n){if(!e||!e.startsWith("."))return null;let o=Gt.posix.dirname(t.replace(/\\/g,"/")),s=Gt.posix.normalize(Gt.posix.join(o==="."?"":o,e)),r=[];if(Gt.posix.extname(s))r.push(s);else for(let a of Am)r.push(`${s}${a}`),r.push(Gt.posix.join(s,`index${a}`));for(let a of r)if(n.has(a))return a;return null}async function bu(t){if(t=t||process.cwd(),Pa&&Sm===t&&Date.now()-vm<Cm)return Pa;let e=await Ma(t),n=Cr(),o=new Set(n.map(i=>i.replace(/\\/g,"/"))),s={},r={};for(let i of Object.keys(e.files||{})){let a=i.replace(/\\/g,"/"),l=Array.isArray(e.files[i]?.defs)?e.files[i].defs:[],c=[],u=new Set;for(let d of l){if(d.type!=="import")continue;let f=dS(a,d.name,o);!f||f===a||u.has(f)||(u.add(f),c.push(f),r[f]||(r[f]=[]),r[f].push(a))}s[a]=c}for(let[i,a]of Object.entries(r))r[i]=[...new Set(a)].sort();return Pa={importsByFile:s,importedByFile:r},vm=Date.now(),Sm=t,Pa}async function fS(t,e,n=6){if(!t)return[];let o=await bu(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 pS(t,e=4){let n=await bu(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 Pm(t){return String(t).replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function hS(t,e){let n=Pm(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 mS(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 Ma(e),a=Pm(t),l=new RegExp(`\\b${a}\\s*\\(`),c=new RegExp(`\\b${a}\\b`),u=[];for(let d of Object.keys(i.files||{})){let f=d.replace(/\\/g,"/");try{let p=Gt.join(e,f),g=(await Gs.readFile(p,"utf-8")).split(`
281
+ `);for(let w=0;w<g.length;w++){let k=g[w],T=w+1;if(!c.test(k)||o&&f===o&&s===T||hS(k,t))continue;let $=(f===o?0:4)+(l.test(k)?3:1);u.push({file:f,line:T,context:k.trim(),score:$})}}catch{}}return u.sort((d,f)=>f.score!==d.score?f.score-d.score:d.file.localeCompare(f.file)||d.line-f.line),u.slice(0,r)}Mm.exports={refreshIndex:Em,getFileIndex:Cr,getIndexedCwd:iS,findFileInIndex:aS,searchIndex:lS,isIndexValid:yu,buildContentIndex:Ma,searchContentIndex:uS,extractDefinitions:Om,buildImportGraph:bu,getRelatedFiles:fS,summarizeModuleHubs:pS,findSymbolReferences:mS,smartSearch:cS,scorePathMatch:Rm,pathLevenshtein:Tm}});var qo=ne((IM,qm)=>{var Na=require("fs"),Da=require("path"),qa=require("os"),{execFile:gS}=require("child_process"),{promisify:yS}=require("util"),wu=yS(gS),bS=Da.join(qa.homedir(),".nex","servers.json"),La=Da.join(qa.tmpdir(),"nex-ssh-sockets");function wS(){return Da.join(process.cwd(),".nex","servers.json")}function Nm(){let t=o=>{if(!Na.existsSync(o))return{};try{return JSON.parse(Na.readFileSync(o,"utf-8"))}catch{return{}}},e=t(bS),n=t(wS());return{...e,...n}}function _S(t){let e=Nm();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 $S(){Na.existsSync(La)||Na.mkdirSync(La,{recursive:!0})}function Lm(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=yes","-o","ServerAliveInterval=30"];t.key&&e.push("-i",t.key.replace(/^~/,qa.homedir())),t.port&&Number(t.port)!==22&&e.push("-p",String(t.port)),$S();let n=t.user?`${t.user}@${t.host}`:t.host,o=Da.join(La,n.replace(/[@.:]/g,"_"));return e.push("-o","ControlMaster=auto","-o",`ControlPath=${o}`,"-o","ControlPersist=120"),e.push(n),{args:e,target:n}}function Im(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=yes","-r"];return t.key&&e.push("-i",t.key.replace(/^~/,qa.homedir())),t.port&&Number(t.port)!==22&&e.push("-P",String(t.port)),e}async function Ia(t,e,{timeout:n=3e4,sudo:o=!1}={}){let{args:s}=Lm(t),r=o&&t.sudo?`sudo sh -c ${JSON.stringify(e)}`:e;try{let{stdout:i,stderr:a}=await wu("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,l=(i.stderr||i.message||"").toString();return{stdout:(i.stdout||"").toString(),stderr:l,exitCode:a,error:Fa(l,t)}}}async function kS(t,e,n,{timeout:o=12e4}={}){let s=Im(t),r=t.user?`${t.user}@${t.host}`:t.host;s.push(e,`${r}:${n}`);try{let{stdout:i,stderr:a}=await wu("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(Fa(a,t)||a)}}async function xS(t,e,n,{timeout:o=12e4}={}){let s=Im(t),r=t.user?`${t.user}@${t.host}`:t.host;s.push(`${r}:${e}`,n);try{let{stdout:i,stderr:a}=await wu("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(Fa(a,t)||a)}}function Fa(t,e){if(!t)return"";if(/connection refused/i.test(t)){let n=e.port||22;return`${t}
282
282
  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}
283
283
  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}
284
284
  HINT: Cannot reach ${e.host}. Check: network connection, correct hostname/IP, DNS resolution.`:/host key verification failed/i.test(t)?`${t}
285
285
  HINT: Host key changed for ${e.host}. To reset: ssh-keygen -R ${e.host}`:/timed out/i.test(t)?`${t}
286
286
  HINT: Connection timed out to ${e.host}. Check firewall rules and network connectivity.`:/too many authentication failures/i.test(t)?`${t}
287
- HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function vS(t,e){let n=e.user?`${e.user}@${e.host}`:e.host,s=e.port&&Number(e.port)!==22?`:${e.port}`:"",o=e.os?` [${e.os}]`:"",r=e.key?` key:${e.key}`:"",i=e.sudo?" sudo:yes":"";return`${t}: ${n}${s}${o}${r}${i}`}var ja=new Map,SS=12e4;async function jm(t,e,{force:n=!1}={}){let o=`${t.user?`${t.user}@${t.host}`:t.host}:${e}`,r=ja.get(o);if(!n&&r&&Date.now()-r.time<SS)return r.files;let i=`find ${e} -maxdepth 6 -type f -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/venv/*' -not -path '*/__pycache__/*' -not -path '*/dist/*' -not -name '*.pyc' 2>/dev/null | head -5000`,{stdout:a,exitCode:l}=await Ia(t,i,{timeout:15e3});if(l!==0||!a.trim())return[];let c=e.endsWith("/")?e:e+"/",u=a.split(`
288
- `).filter(Boolean).map(d=>d.startsWith(c)?d.slice(c.length):d);return ja.set(o,{files:u,time:Date.now()}),u}async function Dm(t,e,n,{limit:s=5,minScore:o=15}={}){let r=await jm(t,e);if(r.length===0)return[];let{scorePathMatch:i}=In(),a=[];for(let l of r){let c=i(l,n);c>=o&&a.push({file:l,score:c})}return a.sort((l,c)=>c.score-l.score),a.slice(0,s)}async function ES(t,e,n){if(!n)return{fixedPath:null,message:""};let s=n.replace(/\/+/g,"/");if(s.startsWith("~/")){let{stdout:r}=await Ia(t,"echo $HOME",{timeout:5e3}),i=r.trim();i&&(s=s.replace("~/",i+"/"))}if(s.startsWith("/")){let{exitCode:r}=await Ia(t,`test -f ${JSON.stringify(s)}`,{timeout:5e3});if(r===0)return{fixedPath:s,message:"(auto-fixed: normalized path)"}}let o=await Dm(t,e,n,{limit:5,minScore:15});if(o.length>0){let i=(e.endsWith("/")?e:e+"/")+o[0].file;if(o[0].score>=200||o.length===1&&o[0].score>=50)return{fixedPath:i,message:`(auto-fixed: remote smart match \u2192 ${o[0].file})`};if(o.length>=2&&o[0].score>=80&&o[0].score>=o[1].score*1.5)return{fixedPath:i,message:`(auto-fixed: remote best match \u2192 ${o[0].file})`};if(o.length<=5)return{fixedPath:null,message:`File not found on remote. Did you mean:
289
- ${o.map(a=>` - ${a.file}`).join(`
290
- `)}`}}return{fixedPath:null,message:""}}function TS(t){t?ja.delete(t):ja.clear()}qm.exports={loadServerProfiles:Nm,resolveProfile:_S,buildSSHArgs:Lm,sshExec:Ia,scpUpload:kS,scpDownload:xS,enrichSSHError:Fa,formatProfile:vS,SSH_SOCKET_DIR:La,getRemoteIndex:jm,remoteSmartSearch:Dm,remoteAutoFixPath:ES,clearRemoteIndex:TS}});var Um=ne((jM,Bm)=>{var Ar=require("fs"),_u=require("path"),RS=_u.join(".nex","deploy.json");function $u(){return _u.join(process.cwd(),RS)}function Fm(){let t=$u();if(!Ar.existsSync(t))return{};try{return JSON.parse(Ar.readFileSync(t,"utf-8"))}catch{return{}}}function CS(t){let e=Fm();if(e[t])return{...e[t],_name:t};let n=Object.keys(e),s=n.length?`Available: ${n.join(", ")}`:"No deploy configs found. Create .nex/deploy.json or use explicit params.";throw new Error(`Unknown deploy config: "${t}". ${s}`)}function AS(t){let e=_u.join(process.cwd(),".nex");Ar.existsSync(e)||Ar.mkdirSync(e,{recursive:!0}),Ar.writeFileSync($u(),JSON.stringify(t,null,2)+`
291
- `,"utf-8")}Bm.exports={loadDeployConfigs:Fm,resolveDeployConfig:CS,saveDeployConfigs:AS,getDeployConfigPath:$u}});var Nr=ne((DM,Gm)=>{var{getActiveModel:OS,getActiveProviderName:PS}=vt(),Or={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},Pr={"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"},Mr={ollama:"full",openai:"full",anthropic:"full",gemini:"full",local:"essential"},jn={};function Hm(){try{let t=require("fs"),n=require("path").join(process.cwd(),".nex","config.json");t.existsSync(n)&&(jn=JSON.parse(t.readFileSync(n,"utf-8")).toolTiers||{})}catch{jn={}}}Hm();function ku(){let e=OS()?.id,n=PS();return e&&jn[e]?jn[e]:n&&jn[`${n}:*`]?jn[`${n}:*`]:e&&Pr[e]?Pr[e]:n&&Mr[n]?Mr[n]:"full"}var MS=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"]),Wm={anthropic:"strict",openai:"strict",gemini:"strict",ollama:"fuzzy",local:"fuzzy"};function NS(t,e){return t&&(MS.has(t)||t.startsWith("claude-"))?"strict":e&&Wm[e]?Wm[e]:"fuzzy"}function LS(t,e){return t&&jn[t]?jn[t]:e&&jn[`${e}:*`]?jn[`${e}:*`]:t&&Pr[t]?Pr[t]:e&&Mr[e]?Mr[e]:"full"}function IS(t,e){let n=e||ku();if(n==="full"||!Or[n])return t;let s=new Set(Or[n]);return t.filter(o=>s.has(o.function.name))}function jS(){let t=ku(),e=Or[t]?Or[t].length:"all";return{tier:t,toolCount:e}}Gm.exports={filterToolsForModel:IS,getActiveTier:ku,getModelTier:LS,getEditMode:NS,getTierInfo:jS,TIERS:Or,MODEL_TIERS:Pr,PROVIDER_DEFAULT_TIER:Mr,loadConfigOverrides:Hm}});var ns=ne((qM,Vm)=>{var xu=null,ts=null,Lr=null,vu=Symbol.for("nex-code.browserExitCleanup"),Ym=`Playwright is not installed. Install with:
287
+ HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function vS(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 ja=new Map,SS=12e4;async function jm(t,e,{force:n=!1}={}){let s=`${t.user?`${t.user}@${t.host}`:t.host}:${e}`,r=ja.get(s);if(!n&&r&&Date.now()-r.time<SS)return r.files;let i=`find ${e} -maxdepth 6 -type f -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/venv/*' -not -path '*/__pycache__/*' -not -path '*/dist/*' -not -name '*.pyc' 2>/dev/null | head -5000`,{stdout:a,exitCode:l}=await Ia(t,i,{timeout:15e3});if(l!==0||!a.trim())return[];let c=e.endsWith("/")?e:e+"/",u=a.split(`
288
+ `).filter(Boolean).map(d=>d.startsWith(c)?d.slice(c.length):d);return ja.set(s,{files:u,time:Date.now()}),u}async function Dm(t,e,n,{limit:o=5,minScore:s=15}={}){let r=await jm(t,e);if(r.length===0)return[];let{scorePathMatch:i}=In(),a=[];for(let l of r){let c=i(l,n);c>=s&&a.push({file:l,score:c})}return a.sort((l,c)=>c.score-l.score),a.slice(0,o)}async function ES(t,e,n){if(!n)return{fixedPath:null,message:""};let o=n.replace(/\/+/g,"/");if(o.startsWith("~/")){let{stdout:r}=await Ia(t,"echo $HOME",{timeout:5e3}),i=r.trim();i&&(o=o.replace("~/",i+"/"))}if(o.startsWith("/")){let{exitCode:r}=await Ia(t,`test -f ${JSON.stringify(o)}`,{timeout:5e3});if(r===0)return{fixedPath:o,message:"(auto-fixed: normalized path)"}}let s=await Dm(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:
289
+ ${s.map(a=>` - ${a.file}`).join(`
290
+ `)}`}}return{fixedPath:null,message:""}}function TS(t){t?ja.delete(t):ja.clear()}qm.exports={loadServerProfiles:Nm,resolveProfile:_S,buildSSHArgs:Lm,sshExec:Ia,scpUpload:kS,scpDownload:xS,enrichSSHError:Fa,formatProfile:vS,SSH_SOCKET_DIR:La,getRemoteIndex:jm,remoteSmartSearch:Dm,remoteAutoFixPath:ES,clearRemoteIndex:TS}});var Um=ne((jM,Bm)=>{var Ar=require("fs"),_u=require("path"),RS=_u.join(".nex","deploy.json");function $u(){return _u.join(process.cwd(),RS)}function Fm(){let t=$u();if(!Ar.existsSync(t))return{};try{return JSON.parse(Ar.readFileSync(t,"utf-8"))}catch{return{}}}function CS(t){let e=Fm();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 AS(t){let e=_u.join(process.cwd(),".nex");Ar.existsSync(e)||Ar.mkdirSync(e,{recursive:!0}),Ar.writeFileSync($u(),JSON.stringify(t,null,2)+`
291
+ `,"utf-8")}Bm.exports={loadDeployConfigs:Fm,resolveDeployConfig:CS,saveDeployConfigs:AS,getDeployConfigPath:$u}});var Nr=ne((DM,Gm)=>{var{getActiveModel:OS,getActiveProviderName:PS}=vt(),Or={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},Pr={"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"},Mr={ollama:"full",openai:"full",anthropic:"full",gemini:"full",local:"essential"},jn={};function Hm(){try{let t=require("fs"),n=require("path").join(process.cwd(),".nex","config.json");t.existsSync(n)&&(jn=JSON.parse(t.readFileSync(n,"utf-8")).toolTiers||{})}catch{jn={}}}Hm();function ku(){let e=OS()?.id,n=PS();return e&&jn[e]?jn[e]:n&&jn[`${n}:*`]?jn[`${n}:*`]:e&&Pr[e]?Pr[e]:n&&Mr[n]?Mr[n]:"full"}var MS=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"]),Wm={anthropic:"strict",openai:"strict",gemini:"strict",ollama:"fuzzy",local:"fuzzy"};function NS(t,e){return t&&(MS.has(t)||t.startsWith("claude-"))?"strict":e&&Wm[e]?Wm[e]:"fuzzy"}function LS(t,e){return t&&jn[t]?jn[t]:e&&jn[`${e}:*`]?jn[`${e}:*`]:t&&Pr[t]?Pr[t]:e&&Mr[e]?Mr[e]:"full"}function IS(t,e){let n=e||ku();if(n==="full"||!Or[n])return t;let o=new Set(Or[n]);return t.filter(s=>o.has(s.function.name))}function jS(){let t=ku(),e=Or[t]?Or[t].length:"all";return{tier:t,toolCount:e}}Gm.exports={filterToolsForModel:IS,getActiveTier:ku,getModelTier:LS,getEditMode:NS,getTierInfo:jS,TIERS:Or,MODEL_TIERS:Pr,PROVIDER_DEFAULT_TIER:Mr,loadConfigOverrides:Hm}});var ns=ne((qM,Vm)=>{var xu=null,ts=null,Lr=null,vu=Symbol.for("nex-code.browserExitCleanup"),Ym=`Playwright is not installed. Install with:
292
292
  npm install playwright && npx playwright install chromium
293
- Then restart nex-code.`;function zm(){if(Lr!==null)return Lr;try{require("playwright"),Lr=!0}catch{Lr=!1}return Lr}async function Ba(){if(!zm())throw new Error(Ym);return xu||(xu=require("playwright")),(!ts||!ts.isConnected())&&(ts=await xu.chromium.launch({headless:!0})),ts}async function DS(){if(ts){try{await ts.close()}catch(t){console.error("closeBrowser failed:",t.message)}ts=null}}globalThis[vu]&&process.off("exit",globalThis[vu]);var Km=()=>{if(ts)try{ts.close()}catch(t){console.error("Error closing browser on exit:",t.message)}};globalThis[vu]=Km;process.on("exit",Km);async function qS(t,{timeout:e=3e4,waitFor:n="domcontentloaded"}={}){let o=await(await Ba()).newPage();try{await o.goto(t,{waitUntil:n,timeout:e});let r=await o.title(),i=await o.evaluate(()=>(document.querySelectorAll("script,style,nav,footer,header,aside,[role=navigation]").forEach(c=>c.remove()),document.body?.innerText||"")),a=await o.evaluate(()=>Array.from(document.querySelectorAll("a[href]")).slice(0,30).map(l=>({text:(l.innerText||l.textContent||"").trim().substring(0,80),href:l.href})).filter(l=>l.text&&l.href&&!l.href.startsWith("javascript:")));return{title:r,url:o.url(),text:i.substring(0,8e3)+(i.length>8e3?`
294
- ...(truncated)`:""),links:a.slice(0,20)}}finally{await o.close()}}async function FS(t,{width:e=1280,height:n=800,fullPage:s=!1,timeout:o=3e4}={}){let i=await(await Ba()).newPage();try{await i.setViewportSize({width:e,height:n}),await i.goto(t,{waitUntil:"networkidle",timeout:o});let a=await i.screenshot({type:"png",fullPage:s}),l=require("os"),c=require("path"),u=require("fs"),d=c.join(l.tmpdir(),`nex-screenshot-${Date.now()}.png`);return u.writeFileSync(d,a,{mode:384}),{path:d,base64:a.toString("base64"),media_type:"image/png",title:await i.title(),url:i.url()}}finally{await i.close()}}async function BS(t,{selector:e,text:n,timeout:s=3e4}={}){if(!e&&!n)throw new Error("selector or text is required");let r=await(await Ba()).newPage();try{await r.goto(t,{waitUntil:"domcontentloaded",timeout:s}),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 US(t,{selector:e,value:n,submit:s=!1,timeout:o=3e4}={}){if(!e||n===void 0)throw new Error("selector and value are required");let i=await(await Ba()).newPage();try{return await i.goto(t,{waitUntil:"domcontentloaded",timeout:o}),await i.fill(e,String(n)),s&&(await i.keyboard.press("Enter"),await i.waitForLoadState("domcontentloaded")),`Filled "${e}" with value. ${s?`Submitted \u2192 ${i.url()}`:"Not submitted."}`}finally{await i.close()}}Vm.exports={isPlaywrightAvailable:zm,browserNavigate:qS,browserScreenshot:FS,browserClick:BS,browserFill:US,closeBrowser:DS,INSTALL_MSG:Ym}});var Su=ne((FM,Jm)=>{"use strict";var WS=require("util"),Xm=require("stream"),xn=Jm.exports=function(){Xm.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};WS.inherits(xn,Xm);xn.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))};xn.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};xn.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()))};xn.prototype.destroySoon=xn.prototype.end;xn.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};xn.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};xn.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))};xn.prototype._processRead=function(t){this._reads.shift();let e=0,n=0,s=Buffer.alloc(t.length);for(;e<t.length;){let o=this._buffers[n++],r=Math.min(o.length,t.length-e);o.copy(s,e,0,r),e+=r,r!==o.length&&(this._buffers[--n]=o.slice(r))}n>0&&this._buffers.splice(0,n),this._buffered-=t.length,t.func.call(this,s)};xn.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 Tu=ne(Eu=>{"use strict";var ys=[{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]}];Eu.getImagePasses=function(t,e){let n=[],s=t%8,o=e%8,r=(t-s)/8,i=(e-o)/8;for(let a=0;a<ys.length;a++){let l=ys[a],c=r*l.x.length,u=i*l.y.length;for(let d=0;d<l.x.length&&l.x[d]<s;d++)c++;for(let d=0;d<l.y.length&&l.y[d]<o;d++)u++;c>0&&u>0&&n.push({width:c,height:u,index:a})}return n};Eu.getInterlaceIterator=function(t){return function(e,n,s){let o=e%ys[s].x.length,r=(e-o)/ys[s].x.length*8+ys[s].x[o],i=n%ys[s].y.length,a=(n-i)/ys[s].y.length*8+ys[s].y[i];return r*4+a*t*4}}});var Ru=ne((UM,Zm)=>{"use strict";Zm.exports=function(e,n,s){let o=e+n-s,r=Math.abs(o-e),i=Math.abs(o-n),a=Math.abs(o-s);return r<=i&&r<=a?e:i<=a?n:s}});var Cu=ne((WM,eg)=>{"use strict";var HS=Tu(),GS=Ru();function Qm(t,e,n){let s=t*e;return n!==8&&(s=Math.ceil(s/(8/n))),s}var Fo=eg.exports=function(t,e){let n=t.width,s=t.height,o=t.interlace,r=t.bpp,i=t.depth;if(this.read=e.read,this.write=e.write,this.complete=e.complete,this._imageIndex=0,this._images=[],o){let a=HS.getImagePasses(n,s);for(let l=0;l<a.length;l++)this._images.push({byteWidth:Qm(a[l].width,r,i),height:a[l].height,lineIndex:0})}else this._images.push({byteWidth:Qm(n,r,i),height:s,lineIndex:0});i===8?this._xComparison=r:i===16?this._xComparison=r*2:this._xComparison=1};Fo.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};Fo.prototype._unFilterType1=function(t,e,n){let s=this._xComparison,o=s-1;for(let r=0;r<n;r++){let i=t[1+r],a=r>o?e[r-s]:0;e[r]=i+a}};Fo.prototype._unFilterType2=function(t,e,n){let s=this._lastLine;for(let o=0;o<n;o++){let r=t[1+o],i=s?s[o]:0;e[o]=r+i}};Fo.prototype._unFilterType3=function(t,e,n){let s=this._xComparison,o=s-1,r=this._lastLine;for(let i=0;i<n;i++){let a=t[1+i],l=r?r[i]:0,c=i>o?e[i-s]:0,u=Math.floor((c+l)/2);e[i]=a+u}};Fo.prototype._unFilterType4=function(t,e,n){let s=this._xComparison,o=s-1,r=this._lastLine;for(let i=0;i<n;i++){let a=t[1+i],l=r?r[i]:0,c=i>o?e[i-s]:0,u=i>o&&r?r[i-s]:0,d=GS(c,l,u);e[i]=a+d}};Fo.prototype._reverseFilterLine=function(t){let e=t[0],n,s=this._images[this._imageIndex],o=s.byteWidth;if(e===0)n=t.slice(1,o+1);else switch(n=Buffer.alloc(o),e){case 1:this._unFilterType1(t,n,o);break;case 2:this._unFilterType2(t,n,o);break;case 3:this._unFilterType3(t,n,o);break;case 4:this._unFilterType4(t,n,o);break;default:throw new Error("Unrecognised filter type - "+e)}this.write(n),s.lineIndex++,s.lineIndex>=s.height?(this._lastLine=null,this._imageIndex++,s=this._images[this._imageIndex]):this._lastLine=n,s?this.read(s.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}});var sg=ne((HM,ng)=>{"use strict";var YS=require("util"),tg=Su(),zS=Cu(),KS=ng.exports=function(t){tg.call(this);let e=[],n=this;this._filter=new zS(t,{read:this.read.bind(this),write:function(s){e.push(s)},complete:function(){n.emit("complete",Buffer.concat(e))}}),this._filter.start()};YS.inherits(KS,tg)});var Bo=ne((GM,og)=>{"use strict";og.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 Pu=ne((YM,rg)=>{"use strict";var Au=[];(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;Au[t]=e}})();var Ou=rg.exports=function(){this._crc=-1};Ou.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=Au[(this._crc^t[e])&255]^this._crc>>>8;return!0};Ou.prototype.crc32=function(){return this._crc^-1};Ou.crc32=function(t){let e=-1;for(let n=0;n<t.length;n++)e=Au[(e^t[n])&255]^e>>>8;return e^-1}});var Mu=ne((zM,ig)=>{"use strict";var $t=Bo(),VS=Pu(),St=ig.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[$t.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[$t.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[$t.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[$t.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[$t.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[$t.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(){}};St.prototype.start=function(){this.read($t.PNG_SIGNATURE.length,this._parseSignature.bind(this))};St.prototype._parseSignature=function(t){let e=$t.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))};St.prototype._parseChunkBegin=function(t){let e=t.readUInt32BE(0),n=t.readUInt32BE(4),s="";for(let r=4;r<8;r++)s+=String.fromCharCode(t[r]);let o=!!(t[4]&32);if(!this._hasIHDR&&n!==$t.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new VS,this._crc.write(Buffer.from(s)),this._chunks[n])return this._chunks[n](e);if(!o){this.error(new Error("Unsupported critical chunk type "+s));return}this.read(e+4,this._skipChunk.bind(this))};St.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};St.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};St.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))};St.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};St.prototype._parseIHDR=function(t){this._crc.write(t);let e=t.readUInt32BE(0),n=t.readUInt32BE(4),s=t[8],o=t[9],r=t[10],i=t[11],a=t[12];if(s!==8&&s!==4&&s!==2&&s!==1&&s!==16){this.error(new Error("Unsupported bit depth "+s));return}if(!(o in $t.COLORTYPE_TO_BPP_MAP)){this.error(new Error("Unsupported color type"));return}if(r!==0){this.error(new Error("Unsupported compression method"));return}if(i!==0){this.error(new Error("Unsupported filter method"));return}if(a!==0&&a!==1){this.error(new Error("Unsupported interlace method"));return}this._colorType=o;let l=$t.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:n,depth:s,interlace:!!a,palette:!!(o&$t.COLORTYPE_PALETTE),color:!!(o&$t.COLORTYPE_COLOR),alpha:!!(o&$t.COLORTYPE_ALPHA),bpp:l,colorType:o}),this._handleChunkEnd()};St.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};St.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()};St.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};St.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===$t.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===$t.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===$t.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};St.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};St.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/$t.GAMMA_DIVISION),this._handleChunkEnd()};St.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};St.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===$t.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()};St.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};St.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var Nu=ne(lg=>{"use strict";var ag=Tu(),XS=[function(){},function(t,e,n,s){if(s===e.length)throw new Error("Ran out of data");let o=e[s];t[n]=o,t[n+1]=o,t[n+2]=o,t[n+3]=255},function(t,e,n,s){if(s+1>=e.length)throw new Error("Ran out of data");let o=e[s];t[n]=o,t[n+1]=o,t[n+2]=o,t[n+3]=e[s+1]},function(t,e,n,s){if(s+2>=e.length)throw new Error("Ran out of data");t[n]=e[s],t[n+1]=e[s+1],t[n+2]=e[s+2],t[n+3]=255},function(t,e,n,s){if(s+3>=e.length)throw new Error("Ran out of data");t[n]=e[s],t[n+1]=e[s+1],t[n+2]=e[s+2],t[n+3]=e[s+3]}],JS=[function(){},function(t,e,n,s){let o=e[0];t[n]=o,t[n+1]=o,t[n+2]=o,t[n+3]=s},function(t,e,n){let s=e[0];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=e[1]},function(t,e,n,s){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=s},function(t,e,n){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=e[3]}];function ZS(t,e){let n=[],s=0;function o(){if(s===t.length)throw new Error("Ran out of data");let r=t[s];s++;let i,a,l,c,u,d,f,p;switch(e){default:throw new Error("unrecognised depth");case 16:f=t[s],s++,n.push((r<<8)+f);break;case 4:f=r&15,p=r>>4,n.push(p,f);break;case 2:u=r&3,d=r>>2&3,f=r>>4&3,p=r>>6&3,n.push(p,f,d,u);break;case 1:i=r&1,a=r>>1&1,l=r>>2&1,c=r>>3&1,u=r>>4&1,d=r>>5&1,f=r>>6&1,p=r>>7&1,n.push(p,f,d,u,c,l,a,i);break}}return{get:function(r){for(;n.length<r;)o();let i=n.slice(0,r);return n=n.slice(r),i},resetAfterLine:function(){n.length=0},end:function(){if(s!==t.length)throw new Error("extra data found")}}}function QS(t,e,n,s,o,r){let i=t.width,a=t.height,l=t.index;for(let c=0;c<a;c++)for(let u=0;u<i;u++){let d=n(u,c,l);XS[s](e,o,d,r),r+=s}return r}function eE(t,e,n,s,o,r){let i=t.width,a=t.height,l=t.index;for(let c=0;c<a;c++){for(let u=0;u<i;u++){let d=o.get(s),f=n(u,c,l);JS[s](e,d,f,r)}o.resetAfterLine()}}lg.dataToBitMap=function(t,e){let n=e.width,s=e.height,o=e.depth,r=e.bpp,i=e.interlace,a;o!==8&&(a=ZS(t,o));let l;o<=8?l=Buffer.alloc(n*s*4):l=new Uint16Array(n*s*4);let c=Math.pow(2,o)-1,u=0,d,f;if(i)d=ag.getImagePasses(n,s),f=ag.getInterlaceIterator(n,s);else{let p=0;f=function(){let h=p;return p+=4,h},d=[{width:n,height:s}]}for(let p=0;p<d.length;p++)o===8?u=QS(d[p],l,f,r,t,u):eE(d[p],l,f,r,a,c);if(o===8){if(u!==t.length)throw new Error("extra data found")}else a.end();return l}});var Lu=ne((VM,cg)=>{"use strict";function tE(t,e,n,s,o){let r=0;for(let i=0;i<s;i++)for(let a=0;a<n;a++){let l=o[t[r]];if(!l)throw new Error("index "+t[r]+" not in palette");for(let c=0;c<4;c++)e[r+c]=l[c];r+=4}}function nE(t,e,n,s,o){let r=0;for(let i=0;i<s;i++)for(let a=0;a<n;a++){let l=!1;if(o.length===1?o[0]===t[r]&&(l=!0):o[0]===t[r]&&o[1]===t[r+1]&&o[2]===t[r+2]&&(l=!0),l)for(let c=0;c<4;c++)e[r+c]=0;r+=4}}function sE(t,e,n,s,o){let r=255,i=Math.pow(2,o)-1,a=0;for(let l=0;l<s;l++)for(let c=0;c<n;c++){for(let u=0;u<4;u++)e[a+u]=Math.floor(t[a+u]*r/i+.5);a+=4}}cg.exports=function(t,e,n=!1){let s=e.depth,o=e.width,r=e.height,i=e.colorType,a=e.transColor,l=e.palette,c=t;return i===3?tE(t,c,o,r,l):(a&&nE(t,c,o,r,a),s!==8&&!n&&(s===16&&(c=Buffer.alloc(o*r*4)),sE(t,c,o,r,s))),c}});var fg=ne((XM,dg)=>{"use strict";var oE=require("util"),Iu=require("zlib"),ug=Su(),rE=sg(),iE=Mu(),aE=Nu(),lE=Lu(),Dn=dg.exports=function(t){ug.call(this),this._parser=new iE(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()};oE.inherits(Dn,ug);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=Iu.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,s=Math.max(n,Iu.Z_MIN_CHUNK);this._inflate=Iu.createInflate({chunkSize:s});let o=n,r=this.emit.bind(this,"error");this._inflate.on("error",function(a){o&&r(a)}),this._filter.on("complete",this._complete.bind(this));let i=this._filter.write.bind(this._filter);this._inflate.on("data",function(a){o&&(a.length>o&&(a=a.slice(0,o)),o-=a.length,i(a))}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};Dn.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new rE(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=aE.dataToBitMap(t,this._bitmapInfo);e=lE(n,this._bitmapInfo,this._options.skipRescale),n=null}catch(n){this._handleError(n);return}this.emit("parsed",e)}});var hg=ne((JM,pg)=>{"use strict";var dn=Bo();pg.exports=function(t,e,n,s){let o=[dn.COLORTYPE_COLOR_ALPHA,dn.COLORTYPE_ALPHA].indexOf(s.colorType)!==-1;if(s.colorType===s.inputColorType){let h=(function(){let g=new ArrayBuffer(2);return new DataView(g).setInt16(0,256,!0),new Int16Array(g)[0]!==256})();if(s.bitDepth===8||s.bitDepth===16&&h)return t}let r=s.bitDepth!==16?t:new Uint16Array(t.buffer),i=255,a=dn.COLORTYPE_TO_BPP_MAP[s.inputColorType];a===4&&!s.inputHasAlpha&&(a=3);let l=dn.COLORTYPE_TO_BPP_MAP[s.colorType];s.bitDepth===16&&(i=65535,l*=2);let c=Buffer.alloc(e*n*l),u=0,d=0,f=s.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,k=i;switch(s.inputColorType){case dn.COLORTYPE_COLOR_ALPHA:k=r[u+3],h=r[u],g=r[u+1],w=r[u+2];break;case dn.COLORTYPE_COLOR:h=r[u],g=r[u+1],w=r[u+2];break;case dn.COLORTYPE_ALPHA:k=r[u+1],h=r[u],g=h,w=h;break;case dn.COLORTYPE_GRAYSCALE:h=r[u],g=h,w=h;break;default:throw new Error("input color type:"+s.inputColorType+" is not supported at present")}return s.inputHasAlpha&&(o||(k/=i,h=Math.min(Math.max(Math.round((1-k)*f.red+k*h),0),i),g=Math.min(Math.max(Math.round((1-k)*f.green+k*g),0),i),w=Math.min(Math.max(Math.round((1-k)*f.blue+k*w),0),i))),{red:h,green:g,blue:w,alpha:k}}for(let h=0;h<n;h++)for(let g=0;g<e;g++){let w=p(r,u);switch(s.colorType){case dn.COLORTYPE_COLOR_ALPHA:case dn.COLORTYPE_COLOR:s.bitDepth===8?(c[d]=w.red,c[d+1]=w.green,c[d+2]=w.blue,o&&(c[d+3]=w.alpha)):(c.writeUInt16BE(w.red,d),c.writeUInt16BE(w.green,d+2),c.writeUInt16BE(w.blue,d+4),o&&c.writeUInt16BE(w.alpha,d+6));break;case dn.COLORTYPE_ALPHA:case dn.COLORTYPE_GRAYSCALE:{let k=(w.red+w.green+w.blue)/3;s.bitDepth===8?(c[d]=k,o&&(c[d+1]=w.alpha)):(c.writeUInt16BE(k,d),o&&c.writeUInt16BE(w.alpha,d+2));break}default:throw new Error("unrecognised color Type "+s.colorType)}u+=a,d+=l}return c}});var yg=ne((ZM,gg)=>{"use strict";var mg=Ru();function cE(t,e,n,s,o){for(let r=0;r<n;r++)s[o+r]=t[e+r]}function uE(t,e,n){let s=0,o=e+n;for(let r=e;r<o;r++)s+=Math.abs(t[r]);return s}function dE(t,e,n,s,o,r){for(let i=0;i<n;i++){let a=i>=r?t[e+i-r]:0,l=t[e+i]-a;s[o+i]=l}}function fE(t,e,n,s){let o=0;for(let r=0;r<n;r++){let i=r>=s?t[e+r-s]:0,a=t[e+r]-i;o+=Math.abs(a)}return o}function pE(t,e,n,s,o){for(let r=0;r<n;r++){let i=e>0?t[e+r-n]:0,a=t[e+r]-i;s[o+r]=a}}function hE(t,e,n){let s=0,o=e+n;for(let r=e;r<o;r++){let i=e>0?t[r-n]:0,a=t[r]-i;s+=Math.abs(a)}return s}function mE(t,e,n,s,o,r){for(let i=0;i<n;i++){let a=i>=r?t[e+i-r]:0,l=e>0?t[e+i-n]:0,c=t[e+i]-(a+l>>1);s[o+i]=c}}function gE(t,e,n,s){let o=0;for(let r=0;r<n;r++){let i=r>=s?t[e+r-s]:0,a=e>0?t[e+r-n]:0,l=t[e+r]-(i+a>>1);o+=Math.abs(l)}return o}function yE(t,e,n,s,o,r){for(let i=0;i<n;i++){let a=i>=r?t[e+i-r]:0,l=e>0?t[e+i-n]:0,c=e>0&&i>=r?t[e+i-(n+r)]:0,u=t[e+i]-mg(a,l,c);s[o+i]=u}}function bE(t,e,n,s){let o=0;for(let r=0;r<n;r++){let i=r>=s?t[e+r-s]:0,a=e>0?t[e+r-n]:0,l=e>0&&r>=s?t[e+r-(n+s)]:0,c=t[e+r]-mg(i,a,l);o+=Math.abs(c)}return o}var wE={0:cE,1:dE,2:pE,3:mE,4:yE},_E={0:uE,1:fE,2:hE,3:gE,4:bE};gg.exports=function(t,e,n,s,o){let r;if(!("filterType"in s)||s.filterType===-1)r=[0,1,2,3,4];else if(typeof s.filterType=="number")r=[s.filterType];else throw new Error("unrecognised filter types");s.bitDepth===16&&(o*=2);let i=e*o,a=0,l=0,c=Buffer.alloc((i+1)*n),u=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=_E[r[p]](t,l,i,o);h<f&&(u=r[p],f=h)}}c[a]=u,a++,wE[u](t,l,i,c,a,o),a+=i,l+=i}return c}});var ju=ne((QM,bg)=>{"use strict";var Nt=Bo(),$E=Pu(),kE=hg(),xE=yg(),vE=require("zlib"),bs=bg.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||vE.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:Nt.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:Nt.COLORTYPE_COLOR_ALPHA,[Nt.COLORTYPE_GRAYSCALE,Nt.COLORTYPE_COLOR,Nt.COLORTYPE_COLOR_ALPHA,Nt.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([Nt.COLORTYPE_GRAYSCALE,Nt.COLORTYPE_COLOR,Nt.COLORTYPE_COLOR_ALPHA,Nt.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")};bs.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};bs.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};bs.prototype.filterData=function(t,e,n){let s=kE(t,e,n,this._options),o=Nt.COLORTYPE_TO_BPP_MAP[this._options.colorType];return xE(s,e,n,this._options,o)};bs.prototype._packChunk=function(t,e){let n=e?e.length:0,s=Buffer.alloc(n+12);return s.writeUInt32BE(n,0),s.writeUInt32BE(t,4),e&&e.copy(s,8),s.writeInt32BE($E.crc32(s.slice(4,s.length-4)),s.length-4),s};bs.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*Nt.GAMMA_DIVISION),0),this._packChunk(Nt.TYPE_gAMA,e)};bs.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(Nt.TYPE_IHDR,n)};bs.prototype.packIDAT=function(t){return this._packChunk(Nt.TYPE_IDAT,t)};bs.prototype.packIEND=function(){return this._packChunk(Nt.TYPE_IEND,null)}});var kg=ne((eN,$g)=>{"use strict";var SE=require("util"),wg=require("stream"),EE=Bo(),TE=ju(),_g=$g.exports=function(t){wg.call(this);let e=t||{};this._packer=new TE(e),this._deflate=this._packer.createDeflate(),this.readable=!0};SE.inherits(_g,wg);_g.prototype.pack=function(t,e,n,s){this.emit("data",Buffer.from(EE.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,n)),s&&this.emit("data",this._packer.packGAMA(s));let o=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(o)}});var Rg=ne((Ir,Tg)=>{"use strict";var xg=require("assert").ok,Uo=require("zlib"),RE=require("util"),vg=require("buffer").kMaxLength;function Ys(t){if(!(this instanceof Ys))return new Ys(t);t&&t.chunkSize<Uo.Z_MIN_CHUNK&&(t.chunkSize=Uo.Z_MIN_CHUNK),Uo.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 CE(t){return new Ys(t)}function Sg(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}Ys.prototype._processChunk=function(t,e,n){if(typeof n=="function")return Uo.Inflate._processChunk.call(this,t,e,n);let s=this,o=t&&t.length,r=this._chunkSize-this._offset,i=this._maxLength,a=0,l=[],c=0,u;this.on("error",function(h){u=h});function d(h,g){if(s._hadError)return;let w=r-g;if(xg(w>=0,"have should not go down"),w>0){let k=s._buffer.slice(s._offset,s._offset+w);if(s._offset+=w,k.length>i&&(k=k.slice(0,i)),l.push(k),c+=k.length,i-=k.length,i===0)return!1}return(g===0||s._offset>=s._chunkSize)&&(r=s._chunkSize,s._offset=0,s._buffer=Buffer.allocUnsafe(s._chunkSize)),g===0?(a+=o-h,o=h,!0):!1}xg(this._handle,"zlib binding closed");let f;do f=this._handle.writeSync(e,t,a,o,this._buffer,this._offset,r),f=f||this._writeState;while(!this._hadError&&d(f[0],f[1]));if(this._hadError)throw u;if(c>=vg)throw Sg(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+vg.toString(16)+" bytes");let p=Buffer.concat(l,c);return Sg(this),p};RE.inherits(Ys,Uo.Inflate);function AE(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=Uo.Z_FINISH),t._processChunk(e,n)}function Eg(t,e){return AE(new Ys(e),t)}Tg.exports=Ir=Eg;Ir.Inflate=Ys;Ir.createInflate=CE;Ir.inflateSync=Eg});var Du=ne((tN,Ag)=>{"use strict";var Cg=Ag.exports=function(t){this._buffer=t,this._reads=[]};Cg.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};Cg.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 Pg=ne(Og=>{"use strict";var OE=Du(),PE=Cu();Og.process=function(t,e){let n=[],s=new OE(t);return new PE(e,{read:s.read.bind(s),write:function(r){n.push(r)},complete:function(){}}).start(),s.process(),Buffer.concat(n)}});var Ig=ne((sN,Lg)=>{"use strict";var Mg=!0,Ng=require("zlib"),ME=Rg();Ng.deflateSync||(Mg=!1);var NE=Du(),LE=Pg(),IE=Mu(),jE=Nu(),DE=Lu();Lg.exports=function(t,e){if(!Mg)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 s(R){n=R}let o;function r(R){o=R}function i(R){o.transColor=R}function a(R){o.palette=R}function l(){o.alpha=!0}let c;function u(R){c=R}let d=[];function f(R){d.push(R)}let p=new NE(t);if(new IE(e,{read:p.read.bind(p),error:s,metadata:r,gamma:u,palette:a,transColor:i,inflateData:f,simpleTransparency:l}).start(),p.process(),n)throw n;let g=Buffer.concat(d);d.length=0;let w;if(o.interlace)w=Ng.inflateSync(g);else{let C=((o.width*o.bpp*o.depth+7>>3)+1)*o.height;w=ME(g,{chunkSize:C,maxLength:C})}if(g=null,!w||!w.length)throw new Error("bad png - invalid inflate data response");let k=LE.process(w,o);g=null;let T=jE.dataToBitMap(k,o);k=null;let $=DE(T,o,e.skipRescale);return o.data=$,o.gamma=c||0,o}});var Fg=ne((oN,qg)=>{"use strict";var jg=!0,Dg=require("zlib");Dg.deflateSync||(jg=!1);var qE=Bo(),FE=ju();qg.exports=function(t,e){if(!jg)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||{},s=new FE(n),o=[];o.push(Buffer.from(qE.PNG_SIGNATURE)),o.push(s.packIHDR(t.width,t.height)),t.gamma&&o.push(s.packGAMA(t.gamma));let r=s.filterData(t.data,t.width,t.height),i=Dg.deflateSync(r,s.getDeflateOptions());if(r=null,!i||!i.length)throw new Error("bad png - invalid compressed data response");return o.push(s.packIDAT(i)),o.push(s.packIEND()),Buffer.concat(o)}});var Bg=ne(qu=>{"use strict";var BE=Ig(),UE=Fg();qu.read=function(t,e){return BE(t,e||{})};qu.write=function(t,e){return UE(t,e)}});var Hg=ne(Wg=>{"use strict";var WE=require("util"),Ug=require("stream"),HE=fg(),GE=kg(),YE=Bg(),Dt=Wg.PNG=function(t){Ug.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 HE(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 GE(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"))};WE.inherits(Dt,Ug);Dt.sync=YE;Dt.prototype.pack=function(){return!this.data||!this.data.length?(this.emit("error","No data provided"),this):(process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this)),this)};Dt.prototype.parse=function(t,e){if(e){let n,s;n=function(o){this.removeListener("error",s),this.data=o,e(null,this)}.bind(this),s=function(o){this.removeListener("parsed",n),e(o,null)}.bind(this),this.once("parsed",n),this.once("error",s)}return this.end(t),this};Dt.prototype.write=function(t){return this._parser.write(t),!0};Dt.prototype.end=function(t){this._parser.end(t)};Dt.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};Dt.prototype._gamma=function(t){this.gamma=t};Dt.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};Dt.bitblt=function(t,e,n,s,o,r,i,a){if(n|=0,s|=0,o|=0,r|=0,i|=0,a|=0,n>t.width||s>t.height||n+o>t.width||s+r>t.height)throw new Error("bitblt reading outside image");if(i>e.width||a>e.height||i+o>e.width||a+r>e.height)throw new Error("bitblt writing outside image");for(let l=0;l<r;l++)t.data.copy(e.data,(a+l)*e.width+i<<2,(s+l)*t.width+n<<2,(s+l)*t.width+n+o<<2)};Dt.prototype.bitblt=function(t,e,n,s,o,r,i){return Dt.bitblt(this,t,e,n,s,o,r,i),this};Dt.adjustGamma=function(t){if(t.gamma){for(let e=0;e<t.height;e++)for(let n=0;n<t.width;n++){let s=t.width*e+n<<2;for(let o=0;o<3;o++){let r=t.data[s+o]/255;r=Math.pow(r,1/2.2/t.gamma),t.data[s+o]=Math.round(r*255)}}t.gamma=0}};Dt.prototype.adjustGamma=function(){Dt.adjustGamma(this)}});var Vg={};G_(Vg,{default:()=>zg});function zg(t,e,n,s,o,r={}){let{threshold:i=.1,alpha:a=.1,aaColor:l=[255,255,0],diffColor:c=[255,0,0],includeAA:u,diffColorAlt:d,diffMask:f}=r;if(!Fu(t)||!Fu(e)||n&&!Fu(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!==s*o*4)throw new Error("Image data size does not match width/height.");let p=s*o,h=new Uint32Array(t.buffer,t.byteOffset,p),g=new Uint32Array(e.buffer,e.byteOffset,p),w=!0;for(let oe=0;oe<p;oe++)if(h[oe]!==g[oe]){w=!1;break}if(w){if(n&&!f)for(let oe=0;oe<p;oe++)Yg(t,4*oe,a,n);return 0}let k=35215*i*i,[T,$,R]=l,[C,M,K]=c,[z,X,ae]=d||c,Z=0;for(let oe=0;oe<o;oe++)for(let Ke=0;Ke<s;Ke++){let Ee=oe*s+Ke,G=Ee*4,re=h[Ee]===g[Ee]?0:Kg(t,e,G,G,!1);if(Math.abs(re)>k){let et=Gg(t,Ke,oe,s,o,h,g)||Gg(e,Ke,oe,s,o,g,h);!u&&et?n&&!f&&Wa(n,G,T,$,R):(n&&(re<0?Wa(n,G,z,X,ae):Wa(n,G,C,M,K)),Z++)}else n&&!f&&Yg(t,G,a,n)}return Z}function Fu(t){return ArrayBuffer.isView(t)&&t.BYTES_PER_ELEMENT===1}function Gg(t,e,n,s,o,r,i){let a=Math.max(e-1,0),l=Math.max(n-1,0),c=Math.min(e+1,s-1),u=Math.min(n+1,o-1),d=n*s+e,f=e===a||e===c||n===l||n===u?1:0,p=0,h=0,g=0,w=0,k=0,T=0;for(let $=a;$<=c;$++)for(let R=l;R<=u;R++){if($===e&&R===n)continue;let C=Kg(t,t,d*4,(R*s+$)*4,!0);if(C===0){if(f++,f>2)return!1}else C<p?(p=C,g=$,w=R):C>h&&(h=C,k=$,T=R)}return p===0||h===0?!1:Ua(r,g,w,s,o)&&Ua(i,g,w,s,o)||Ua(r,k,T,s,o)&&Ua(i,k,T,s,o)}function Ua(t,e,n,s,o){let r=Math.max(e-1,0),i=Math.max(n-1,0),a=Math.min(e+1,s-1),l=Math.min(n+1,o-1),c=t[n*s+e],u=e===r||e===a||n===i||n===l?1:0;for(let d=r;d<=a;d++)for(let f=i;f<=l;f++)if(!(d===e&&f===n)&&(u+=+(c===t[f*s+d]),u>2))return!0;return!1}function Kg(t,e,n,s,o){let r=t[n],i=t[n+1],a=t[n+2],l=t[n+3],c=e[s],u=e[s+1],d=e[s+2],f=e[s+3],p=r-c,h=i-u,g=a-d,w=l-f;if(!p&&!h&&!g&&!w)return 0;if(l<255||f<255){let C=48+159*(n%2),M=48+159*((n/1.618033988749895|0)%2),K=48+159*((n/2.618033988749895|0)%2);p=(r*l-c*f-C*w)/255,h=(i*l-u*f-M*w)/255,g=(a*l-d*f-K*w)/255}let k=p*.29889531+h*.58662247+g*.11448223;if(o)return k;let T=p*.59597799-h*.2741761-g*.32180189,$=p*.21147017-h*.52261711+g*.31114694,R=.5053*k*k+.299*T*T+.1957*$*$;return k>0?-R:R}function Wa(t,e,n,s,o){t[e+0]=n,t[e+1]=s,t[e+2]=o,t[e+3]=255}function Yg(t,e,n,s){let o=255+(t[e]*.29889531+t[e+1]*.58662247+t[e+2]*.11448223-255)*n*t[e+3]/255;Wa(s,e,o,o,o)}var Xg=H_(()=>{});var zs=ne((aN,ty)=>{var ss=require("fs"),zE=require("path"),KE=require("os"),VE="nex-visual-";function Zg(t){return zE.join(KE.tmpdir(),`${VE}${Date.now()}-${t}`)}var Bu=null;function Ha(){return Bu||(Bu=Hg().PNG),Bu}var Uu=null;function XE(){if(!Uu){let t=(Xg(),z_(Vg));Uu=t.default||t}return Uu}function Gu(t,e,{threshold:n=.1}={}){let s=Ha(),o=XE(),r=s.sync.read(ss.readFileSync(t)),i=s.sync.read(ss.readFileSync(e)),a=Math.max(r.width,i.width),l=Math.max(r.height,i.height),c=Jg(r,a,l),u=Jg(i,a,l),d=new s({width:a,height:l}),f=o(c,u,d.data,a,l,{threshold:n,includeAA:!1}),p=a*l,h=(f/p*100).toFixed(1),g=JE(d.data,a,l,3,3),w=Zg("diff.png");return ss.writeFileSync(w,s.sync.write(d),{mode:384}),{diffPath:w,diffPercent:parseFloat(h),totalPixels:p,changedPixels:f,regionSummary:g,beforePath:t,afterPath:e,width:a,height:l}}function Jg(t,e,n){if(t.width===e&&t.height===n)return t.data;let s=Buffer.alloc(e*n*4,0);for(let o=0;o<t.height;o++){let r=o*t.width*4,i=o*e*4;t.data.copy(s,i,r,r+t.width*4)}return s}function JE(t,e,n,s,o){let r=[["top-left","top-center","top-right"],["middle-left","center","middle-right"],["bottom-left","bottom-center","bottom-right"]],i=Math.ceil(e/s),a=Math.ceil(n/o),l=[];for(let c=0;c<o;c++)for(let u=0;u<s;u++){let d=0,f=0,p=u*i,h=c*a,g=Math.min(p+i,e),w=Math.min(h+a,n);for(let k=h;k<w;k++)for(let T=p;T<g;T++){f++;let $=(k*e+T)*4;(t[$]>0||t[$+1]>0)&&d++}if(d>0){let k=(d/f*100).toFixed(1),T=r[c]&&r[c][u]?r[c][u]:`row${c}-col${u}`;l.push({name:T,changedPercent:parseFloat(k),changed:d,total:f})}}return l.sort((c,u)=>u.changedPercent-c.changedPercent),l}var Qg=[{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 ZE(t,{viewports:e=Qg,height:n=800,fullPage:s=!1,timeout:o=3e4}={}){let{browserScreenshot:r}=ns(),i=[];for(let a of e){let l=await r(t,{width:a.width,height:n,fullPage:s,timeout:o});i.push({label:a.label,width:a.width,path:l.path,base64:l.base64,media_type:l.media_type})}return i}function ey(t,e=[]){let n=Ha(),s=n.sync.read(ss.readFileSync(t));for(let i of e){let a=QE(i.color||"#FF0000");i.type==="box"?(eT(s,i.x||0,i.y||0,i.width||50,i.height||50,a,i.thickness||3),i.label&&Hu(s,i.x||0,(i.y||0)-14,i.label,a)):i.type==="arrow"?(tT(s,i.x||0,i.y||0,i.toX||i.x+50,i.toY||i.y,a,i.thickness||3),i.label&&Hu(s,i.x||0,(i.y||0)-14,i.label,a)):i.type==="circle"&&(nT(s,i.x||0,i.y||0,i.radius||20,a,i.thickness||3),i.label&&Hu(s,(i.x||0)-(i.radius||20),(i.y||0)-(i.radius||20)-14,i.label,a))}let o=Zg("annotated.png");ss.writeFileSync(o,n.sync.write(s),{mode:384});let r=ss.readFileSync(o).toString("base64");return{path:o,base64:r,media_type:"image/png"}}function QE(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 qn(t,e,n,s){if(e<0||n<0||e>=t.width||n>=t.height)return;let o=(n*t.width+e)*4;t.data[o]=s.r,t.data[o+1]=s.g,t.data[o+2]=s.b,t.data[o+3]=s.a}function eT(t,e,n,s,o,r,i=3){for(let a=0;a<i;a++){for(let l=0;l<s;l++)qn(t,e+l,n+a,r),qn(t,e+l,n+o-1-a,r);for(let l=0;l<o;l++)qn(t,e+a,n+l,r),qn(t,e+s-1-a,n+l,r)}}function Wu(t,e,n,s,o,r,i=3){let a=Math.abs(s-e),l=Math.abs(o-n),c=e<s?1:-1,u=n<o?1:-1,d=a-l,f=e,p=n;for(;;){let h=Math.floor(i/2);for(let w=-h;w<=h;w++)for(let k=-h;k<=h;k++)qn(t,f+w,p+k,r);if(f===s&&p===o)break;let g=2*d;g>-l&&(d-=l,f+=c),g<a&&(d+=a,p+=u)}}function tT(t,e,n,s,o,r,i=3){Wu(t,e,n,s,o,r,i);let a=Math.atan2(o-n,s-e),l=15,c=a+Math.PI*.8,u=a-Math.PI*.8;Wu(t,s,o,Math.round(s+l*Math.cos(c)),Math.round(o+l*Math.sin(c)),r,i),Wu(t,s,o,Math.round(s+l*Math.cos(u)),Math.round(o+l*Math.sin(u)),r,i)}function nT(t,e,n,s,o,r=3){for(let i=0;i<r;i++){let a=s-i;for(let l=0;l<360;l+=.5){let c=l*Math.PI/180,u=Math.round(e+a*Math.cos(c)),d=Math.round(n+a*Math.sin(c));qn(t,u,d,o)}}}function Hu(t,e,n,s,o){let i=s.length*6+4,a=12;for(let l=0;l<a;l++)for(let c=0;c<i;c++)qn(t,e+c,n+l,{r:0,g:0,b:0,a:200});for(let l=0;l<i;l++)qn(t,e+l,n+a-1,o),qn(t,e+l,n+a-2,o);for(let l=0;l<s.length;l++){let c=e+2+l*6;for(let u=2;u<9;u++)for(let d=0;d<4;d++)qn(t,c+d,n+u,o)}}async function*sT(t,e,{maxIterations:n=20,hmrDelay:s=1500,width:o=1280,height:r=800,timeout:i=3e4}={}){let{browserScreenshot:a}=ns(),l=oT("chokidar"),c=await a(t,{width:o,height:r,timeout:i});if(yield{iteration:0,type:"baseline",path:c.path,base64:c.base64,media_type:c.media_type},!l){yield{iteration:-1,type:"error",message:"chokidar not installed \u2014 watch mode requires it. Install with: npm install chokidar"};return}let u=0,d=!1,f=l.watch(e,{ignoreInitial:!0,ignored:/(node_modules|\.git|dist)/});f.on("change",()=>{d=!0});try{for(;u<n;){await iT(()=>d,3e5),d=!1,u++,await rT(s);let p=await a(t,{width:o,height:r,timeout:i}),h=null;try{h=Gu(c.path,p.path)}catch{}c=p,yield{iteration:u,type:"change",path:p.path,base64:p.base64,media_type:p.media_type,diff:h?{diffPath:h.diffPath,diffPercent:h.diffPercent,changedPixels:h.changedPixels,regions:h.regionSummary}:null}}}finally{await f.close()}}function oT(t){try{return require(t)}catch{return null}}function rT(t){return new Promise(e=>setTimeout(e,t))}function iT(t,e=6e4){return new Promise((n,s)=>{let o=setInterval(()=>{t()&&(clearInterval(o),clearTimeout(r),n())},200),r=setTimeout(()=>{clearInterval(o),s(new Error("Watch timeout \u2014 no file changes detected"))},e)})}function aT(t,{sampleRate:e=4}={}){let s=Ha().sync.read(ss.readFileSync(t)),o=new Map;for(let c=0;c<s.height;c+=e)for(let u=0;u<s.width;u+=e){let d=(c*s.width+u)*4,f=s.data[d],p=s.data[d+1],h=s.data[d+2];if(s.data[d+3]<128)continue;let w=Math.round(f/8)*8,k=Math.round(p/8)*8,T=Math.round(h/8)*8,$=`${w},${k},${T}`;o.set($,(o.get($)||0)+1)}let r=[...o.entries()].sort((c,u)=>u[1]-c[1]).slice(0,20),i=r.reduce((c,u)=>c+u[1],0),a=r.map(([c,u])=>{let[d,f,p]=c.split(",").map(Number);return{hex:lT(d,f,p),rgb:`rgb(${d}, ${f}, ${p})`,frequency:parseFloat((u/i*100).toFixed(1)),category:cT(d,f,p)}}),l=uT(s);return{colors:a,spacing:l,dimensions:{width:s.width,height:s.height},imagePath:t}}function lT(t,e,n){return"#"+[t,e,n].map(s=>Math.min(255,s).toString(16).padStart(2,"0")).join("")}function cT(t,e,n){let s=(t*299+e*587+n*114)/1e3;return s>240?"white/background":s<30?"black/text":s<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":s>200?"light/subtle":"midtone"}function uT(t){let e=[],n=!1,s=0,o=dT(t);for(let i=0;i<t.height;i++){let a=!0;for(let l=0;l<t.width;l+=4){let c=(i*t.width+l)*4;if(Math.abs(t.data[c]-o.r)>20||Math.abs(t.data[c+1]-o.g)>20||Math.abs(t.data[c+2]-o.b)>20){a=!1;break}}if(a&&n)n=!1,s=i;else if(!a&&!n&&(n=!0,s>0)){let l=i-s;l>=4&&l<=200&&e.push(l)}}let r=new Map;for(let i of e){let a=Math.round(i/4)*4;r.set(a,(r.get(a)||0)+1)}return[...r.entries()].sort((i,a)=>a[1]-i[1]).slice(0,8).map(([i,a])=>({px:i,occurrences:a}))}function dT(t){let e=[[0,0],[t.width-1,0],[0,t.height-1],[t.width-1,t.height-1]],n=0,s=0,o=0;for(let[r,i]of e){let a=(i*t.width+r)*4;n+=t.data[a],s+=t.data[a+1],o+=t.data[a+2]}return{r:Math.round(n/4),g:Math.round(s/4),b:Math.round(o/4)}}async function fT(t,e,{width:n,height:s=800,fullPage:o=!1,threshold:r=.1,timeout:i=3e4}={}){let{browserScreenshot:a}=ns(),c=Ha().sync.read(ss.readFileSync(e)),u=n||c.width,d=s||c.height,f=await a(t,{width:u,height:d,fullPage:o,timeout:i}),p=Gu(e,f.path,{threshold:r}),h=ey(f.path,p.regionSummary.filter(g=>g.changedPercent>1).map((g,w)=>{let $=Math.ceil(p.width/3),R=Math.ceil(p.height/3),C=[["top-left","top-center","top-right"],["middle-left","center","middle-right"],["bottom-left","bottom-center","bottom-right"]],M=0,K=0;for(let z=0;z<3;z++)for(let X=0;X<3;X++)C[z][X]===g.name&&(M=X,K=z);return{type:"box",x:M*$+2,y:K*R+2,width:$-4,height:R-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:ss.readFileSync(p.diffPath).toString("base64"),annotatedBase64:h.base64}}ty.exports={pixelDiff:Gu,responsiveSweep:ZE,annotateImage:ey,visualWatch:sT,extractDesignTokens:aT,designCompare:fT,DEFAULT_VIEWPORTS:Qg}});var Yu=ne((lN,ny)=>{var{C:at}=xt(),Dr="",qt=[],jr=0,Ks=null;function pT(t){Ks=t}function hT(t,e){Dr=t,qt=[],jr=0;for(let s of e){jr++;let o=`t${jr}`;qt.push({id:o,description:s.description||s.title||s.name||s.task||`Task ${jr}`,status:"pending",dependsOn:s.depends_on||[],result:null})}let n=qt.map(s=>({...s}));return Ks&&Ks("create",{name:t,tasks:n}),n}function mT(t,e,n){let s=qt.find(o=>o.id===t);return s?(s.status=e,n!==void 0&&(s.result=n),Ks&&Ks("update",{id:t,status:e,result:n}),{...s}):null}function gT(){return{name:Dr,tasks:qt.map(t=>({...t}))}}function yT(){Dr="",qt=[],jr=0,Ks&&Ks("clear",{})}function bT(){return qt.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let n=qt.find(s=>s.id===e);return n&&n.status==="done"}))}function wT(){if(qt.length===0)return`${at.dim}No active tasks${at.reset}`;let t=[];Dr&&(t.push(` ${at.bold}${at.cyan}Tasks: ${Dr}${at.reset}`),t.push(` ${at.dim}${"\u2500".repeat(40)}${at.reset}`));for(let o of qt){let r,i;switch(o.status){case"done":r="\u2713",i=at.green;break;case"in_progress":r="\u2192",i=at.cyan;break;case"failed":r="\u2717",i=at.red;break;default:r="\xB7",i=at.dim}let a=o.dependsOn.length>0?` ${at.dim}(after: ${o.dependsOn.join(", ")})${at.reset}`:"",l=`[${o.status}]`,c=o.description.length>50?o.description.substring(0,47)+"...":o.description;if(t.push(` ${i}${r}${at.reset} ${at.bold}${o.id}${at.reset} ${c.padEnd(40)} ${i}${l}${at.reset}${a}`),o.result&&o.status==="done"){let u=o.result.length>60?o.result.substring(0,57)+"...":o.result;t.push(` ${at.dim}\u2192 ${u}${at.reset}`)}}let e=qt.filter(o=>o.status==="done").length,n=qt.filter(o=>o.status==="failed").length,s=qt.length;return t.push(` ${at.dim}${"\u2500".repeat(40)}${at.reset}`),t.push(` ${at.dim}${e}/${s} done${n>0?`, ${n} failed`:""}${at.reset}`),t.join(`
293
+ Then restart nex-code.`;function zm(){if(Lr!==null)return Lr;try{require("playwright"),Lr=!0}catch{Lr=!1}return Lr}async function Ba(){if(!zm())throw new Error(Ym);return xu||(xu=require("playwright")),(!ts||!ts.isConnected())&&(ts=await xu.chromium.launch({headless:!0})),ts}async function DS(){if(ts){try{await ts.close()}catch(t){console.error("closeBrowser failed:",t.message)}ts=null}}globalThis[vu]&&process.off("exit",globalThis[vu]);var Km=()=>{if(ts)try{ts.close()}catch(t){console.error("Error closing browser on exit:",t.message)}};globalThis[vu]=Km;process.on("exit",Km);async function qS(t,{timeout:e=3e4,waitFor:n="domcontentloaded"}={}){let s=await(await Ba()).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(c=>c.remove()),document.body?.innerText||"")),a=await s.evaluate(()=>Array.from(document.querySelectorAll("a[href]")).slice(0,30).map(l=>({text:(l.innerText||l.textContent||"").trim().substring(0,80),href:l.href})).filter(l=>l.text&&l.href&&!l.href.startsWith("javascript:")));return{title:r,url:s.url(),text:i.substring(0,8e3)+(i.length>8e3?`
294
+ ...(truncated)`:""),links:a.slice(0,20)}}finally{await s.close()}}async function FS(t,{width:e=1280,height:n=800,fullPage:o=!1,timeout:s=3e4}={}){let i=await(await Ba()).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}),l=require("os"),c=require("path"),u=require("fs"),d=c.join(l.tmpdir(),`nex-screenshot-${Date.now()}.png`);return u.writeFileSync(d,a,{mode:384}),{path:d,base64:a.toString("base64"),media_type:"image/png",title:await i.title(),url:i.url()}}finally{await i.close()}}async function BS(t,{selector:e,text:n,timeout:o=3e4}={}){if(!e&&!n)throw new Error("selector or text is required");let r=await(await Ba()).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 US(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 Ba()).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()}}Vm.exports={isPlaywrightAvailable:zm,browserNavigate:qS,browserScreenshot:FS,browserClick:BS,browserFill:US,closeBrowser:DS,INSTALL_MSG:Ym}});var Su=ne((FM,Jm)=>{"use strict";var WS=require("util"),Xm=require("stream"),xn=Jm.exports=function(){Xm.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};WS.inherits(xn,Xm);xn.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))};xn.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};xn.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()))};xn.prototype.destroySoon=xn.prototype.end;xn.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};xn.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};xn.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))};xn.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)};xn.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 Tu=ne(Eu=>{"use strict";var ys=[{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]}];Eu.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<ys.length;a++){let l=ys[a],c=r*l.x.length,u=i*l.y.length;for(let d=0;d<l.x.length&&l.x[d]<o;d++)c++;for(let d=0;d<l.y.length&&l.y[d]<s;d++)u++;c>0&&u>0&&n.push({width:c,height:u,index:a})}return n};Eu.getInterlaceIterator=function(t){return function(e,n,o){let s=e%ys[o].x.length,r=(e-s)/ys[o].x.length*8+ys[o].x[s],i=n%ys[o].y.length,a=(n-i)/ys[o].y.length*8+ys[o].y[i];return r*4+a*t*4}}});var Ru=ne((UM,Zm)=>{"use strict";Zm.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 Cu=ne((WM,eg)=>{"use strict";var HS=Tu(),GS=Ru();function Qm(t,e,n){let o=t*e;return n!==8&&(o=Math.ceil(o/(8/n))),o}var Fo=eg.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=HS.getImagePasses(n,o);for(let l=0;l<a.length;l++)this._images.push({byteWidth:Qm(a[l].width,r,i),height:a[l].height,lineIndex:0})}else this._images.push({byteWidth:Qm(n,r,i),height:o,lineIndex:0});i===8?this._xComparison=r:i===16?this._xComparison=r*2:this._xComparison=1};Fo.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};Fo.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}};Fo.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}};Fo.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],l=r?r[i]:0,c=i>s?e[i-o]:0,u=Math.floor((c+l)/2);e[i]=a+u}};Fo.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],l=r?r[i]:0,c=i>s?e[i-o]:0,u=i>s&&r?r[i-o]:0,d=GS(c,l,u);e[i]=a+d}};Fo.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 sg=ne((HM,ng)=>{"use strict";var YS=require("util"),tg=Su(),zS=Cu(),KS=ng.exports=function(t){tg.call(this);let e=[],n=this;this._filter=new zS(t,{read:this.read.bind(this),write:function(o){e.push(o)},complete:function(){n.emit("complete",Buffer.concat(e))}}),this._filter.start()};YS.inherits(KS,tg)});var Bo=ne((GM,og)=>{"use strict";og.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 Pu=ne((YM,rg)=>{"use strict";var Au=[];(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;Au[t]=e}})();var Ou=rg.exports=function(){this._crc=-1};Ou.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=Au[(this._crc^t[e])&255]^this._crc>>>8;return!0};Ou.prototype.crc32=function(){return this._crc^-1};Ou.crc32=function(t){let e=-1;for(let n=0;n<t.length;n++)e=Au[(e^t[n])&255]^e>>>8;return e^-1}});var Mu=ne((zM,ig)=>{"use strict";var $t=Bo(),VS=Pu(),St=ig.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[$t.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[$t.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[$t.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[$t.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[$t.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[$t.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(){}};St.prototype.start=function(){this.read($t.PNG_SIGNATURE.length,this._parseSignature.bind(this))};St.prototype._parseSignature=function(t){let e=$t.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))};St.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!==$t.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new VS,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))};St.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};St.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};St.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))};St.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};St.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 $t.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 l=$t.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:n,depth:o,interlace:!!a,palette:!!(s&$t.COLORTYPE_PALETTE),color:!!(s&$t.COLORTYPE_COLOR),alpha:!!(s&$t.COLORTYPE_ALPHA),bpp:l,colorType:s}),this._handleChunkEnd()};St.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};St.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()};St.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};St.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===$t.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===$t.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===$t.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};St.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};St.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/$t.GAMMA_DIVISION),this._handleChunkEnd()};St.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};St.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===$t.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()};St.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};St.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var Nu=ne(lg=>{"use strict";var ag=Tu(),XS=[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]}],JS=[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 ZS(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,l,c,u,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:u=r&3,d=r>>2&3,f=r>>4&3,p=r>>6&3,n.push(p,f,d,u);break;case 1:i=r&1,a=r>>1&1,l=r>>2&1,c=r>>3&1,u=r>>4&1,d=r>>5&1,f=r>>6&1,p=r>>7&1,n.push(p,f,d,u,c,l,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 QS(t,e,n,o,s,r){let i=t.width,a=t.height,l=t.index;for(let c=0;c<a;c++)for(let u=0;u<i;u++){let d=n(u,c,l);XS[o](e,s,d,r),r+=o}return r}function eE(t,e,n,o,s,r){let i=t.width,a=t.height,l=t.index;for(let c=0;c<a;c++){for(let u=0;u<i;u++){let d=s.get(o),f=n(u,c,l);JS[o](e,d,f,r)}s.resetAfterLine()}}lg.dataToBitMap=function(t,e){let n=e.width,o=e.height,s=e.depth,r=e.bpp,i=e.interlace,a;s!==8&&(a=ZS(t,s));let l;s<=8?l=Buffer.alloc(n*o*4):l=new Uint16Array(n*o*4);let c=Math.pow(2,s)-1,u=0,d,f;if(i)d=ag.getImagePasses(n,o),f=ag.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?u=QS(d[p],l,f,r,t,u):eE(d[p],l,f,r,a,c);if(s===8){if(u!==t.length)throw new Error("extra data found")}else a.end();return l}});var Lu=ne((VM,cg)=>{"use strict";function tE(t,e,n,o,s){let r=0;for(let i=0;i<o;i++)for(let a=0;a<n;a++){let l=s[t[r]];if(!l)throw new Error("index "+t[r]+" not in palette");for(let c=0;c<4;c++)e[r+c]=l[c];r+=4}}function nE(t,e,n,o,s){let r=0;for(let i=0;i<o;i++)for(let a=0;a<n;a++){let l=!1;if(s.length===1?s[0]===t[r]&&(l=!0):s[0]===t[r]&&s[1]===t[r+1]&&s[2]===t[r+2]&&(l=!0),l)for(let c=0;c<4;c++)e[r+c]=0;r+=4}}function sE(t,e,n,o,s){let r=255,i=Math.pow(2,s)-1,a=0;for(let l=0;l<o;l++)for(let c=0;c<n;c++){for(let u=0;u<4;u++)e[a+u]=Math.floor(t[a+u]*r/i+.5);a+=4}}cg.exports=function(t,e,n=!1){let o=e.depth,s=e.width,r=e.height,i=e.colorType,a=e.transColor,l=e.palette,c=t;return i===3?tE(t,c,s,r,l):(a&&nE(t,c,s,r,a),o!==8&&!n&&(o===16&&(c=Buffer.alloc(s*r*4)),sE(t,c,s,r,o))),c}});var fg=ne((XM,dg)=>{"use strict";var oE=require("util"),Iu=require("zlib"),ug=Su(),rE=sg(),iE=Mu(),aE=Nu(),lE=Lu(),Dn=dg.exports=function(t){ug.call(this),this._parser=new iE(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()};oE.inherits(Dn,ug);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=Iu.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,Iu.Z_MIN_CHUNK);this._inflate=Iu.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 rE(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=aE.dataToBitMap(t,this._bitmapInfo);e=lE(n,this._bitmapInfo,this._options.skipRescale),n=null}catch(n){this._handleError(n);return}this.emit("parsed",e)}});var hg=ne((JM,pg)=>{"use strict";var dn=Bo();pg.exports=function(t,e,n,o){let s=[dn.COLORTYPE_COLOR_ALPHA,dn.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=dn.COLORTYPE_TO_BPP_MAP[o.inputColorType];a===4&&!o.inputHasAlpha&&(a=3);let l=dn.COLORTYPE_TO_BPP_MAP[o.colorType];o.bitDepth===16&&(i=65535,l*=2);let c=Buffer.alloc(e*n*l),u=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,k=i;switch(o.inputColorType){case dn.COLORTYPE_COLOR_ALPHA:k=r[u+3],h=r[u],g=r[u+1],w=r[u+2];break;case dn.COLORTYPE_COLOR:h=r[u],g=r[u+1],w=r[u+2];break;case dn.COLORTYPE_ALPHA:k=r[u+1],h=r[u],g=h,w=h;break;case dn.COLORTYPE_GRAYSCALE:h=r[u],g=h,w=h;break;default:throw new Error("input color type:"+o.inputColorType+" is not supported at present")}return o.inputHasAlpha&&(s||(k/=i,h=Math.min(Math.max(Math.round((1-k)*f.red+k*h),0),i),g=Math.min(Math.max(Math.round((1-k)*f.green+k*g),0),i),w=Math.min(Math.max(Math.round((1-k)*f.blue+k*w),0),i))),{red:h,green:g,blue:w,alpha:k}}for(let h=0;h<n;h++)for(let g=0;g<e;g++){let w=p(r,u);switch(o.colorType){case dn.COLORTYPE_COLOR_ALPHA:case dn.COLORTYPE_COLOR:o.bitDepth===8?(c[d]=w.red,c[d+1]=w.green,c[d+2]=w.blue,s&&(c[d+3]=w.alpha)):(c.writeUInt16BE(w.red,d),c.writeUInt16BE(w.green,d+2),c.writeUInt16BE(w.blue,d+4),s&&c.writeUInt16BE(w.alpha,d+6));break;case dn.COLORTYPE_ALPHA:case dn.COLORTYPE_GRAYSCALE:{let k=(w.red+w.green+w.blue)/3;o.bitDepth===8?(c[d]=k,s&&(c[d+1]=w.alpha)):(c.writeUInt16BE(k,d),s&&c.writeUInt16BE(w.alpha,d+2));break}default:throw new Error("unrecognised color Type "+o.colorType)}u+=a,d+=l}return c}});var yg=ne((ZM,gg)=>{"use strict";var mg=Ru();function cE(t,e,n,o,s){for(let r=0;r<n;r++)o[s+r]=t[e+r]}function uE(t,e,n){let o=0,s=e+n;for(let r=e;r<s;r++)o+=Math.abs(t[r]);return o}function dE(t,e,n,o,s,r){for(let i=0;i<n;i++){let a=i>=r?t[e+i-r]:0,l=t[e+i]-a;o[s+i]=l}}function fE(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 pE(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 hE(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 mE(t,e,n,o,s,r){for(let i=0;i<n;i++){let a=i>=r?t[e+i-r]:0,l=e>0?t[e+i-n]:0,c=t[e+i]-(a+l>>1);o[s+i]=c}}function gE(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,l=t[e+r]-(i+a>>1);s+=Math.abs(l)}return s}function yE(t,e,n,o,s,r){for(let i=0;i<n;i++){let a=i>=r?t[e+i-r]:0,l=e>0?t[e+i-n]:0,c=e>0&&i>=r?t[e+i-(n+r)]:0,u=t[e+i]-mg(a,l,c);o[s+i]=u}}function bE(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,l=e>0&&r>=o?t[e+r-(n+o)]:0,c=t[e+r]-mg(i,a,l);s+=Math.abs(c)}return s}var wE={0:cE,1:dE,2:pE,3:mE,4:yE},_E={0:uE,1:fE,2:hE,3:gE,4:bE};gg.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,l=0,c=Buffer.alloc((i+1)*n),u=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=_E[r[p]](t,l,i,s);h<f&&(u=r[p],f=h)}}c[a]=u,a++,wE[u](t,l,i,c,a,s),a+=i,l+=i}return c}});var ju=ne((QM,bg)=>{"use strict";var Nt=Bo(),$E=Pu(),kE=hg(),xE=yg(),vE=require("zlib"),bs=bg.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||vE.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:Nt.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:Nt.COLORTYPE_COLOR_ALPHA,[Nt.COLORTYPE_GRAYSCALE,Nt.COLORTYPE_COLOR,Nt.COLORTYPE_COLOR_ALPHA,Nt.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([Nt.COLORTYPE_GRAYSCALE,Nt.COLORTYPE_COLOR,Nt.COLORTYPE_COLOR_ALPHA,Nt.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")};bs.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};bs.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};bs.prototype.filterData=function(t,e,n){let o=kE(t,e,n,this._options),s=Nt.COLORTYPE_TO_BPP_MAP[this._options.colorType];return xE(o,e,n,this._options,s)};bs.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($E.crc32(o.slice(4,o.length-4)),o.length-4),o};bs.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*Nt.GAMMA_DIVISION),0),this._packChunk(Nt.TYPE_gAMA,e)};bs.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(Nt.TYPE_IHDR,n)};bs.prototype.packIDAT=function(t){return this._packChunk(Nt.TYPE_IDAT,t)};bs.prototype.packIEND=function(){return this._packChunk(Nt.TYPE_IEND,null)}});var kg=ne((eN,$g)=>{"use strict";var SE=require("util"),wg=require("stream"),EE=Bo(),TE=ju(),_g=$g.exports=function(t){wg.call(this);let e=t||{};this._packer=new TE(e),this._deflate=this._packer.createDeflate(),this.readable=!0};SE.inherits(_g,wg);_g.prototype.pack=function(t,e,n,o){this.emit("data",Buffer.from(EE.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 Rg=ne((Ir,Tg)=>{"use strict";var xg=require("assert").ok,Uo=require("zlib"),RE=require("util"),vg=require("buffer").kMaxLength;function Ys(t){if(!(this instanceof Ys))return new Ys(t);t&&t.chunkSize<Uo.Z_MIN_CHUNK&&(t.chunkSize=Uo.Z_MIN_CHUNK),Uo.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 CE(t){return new Ys(t)}function Sg(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}Ys.prototype._processChunk=function(t,e,n){if(typeof n=="function")return Uo.Inflate._processChunk.call(this,t,e,n);let o=this,s=t&&t.length,r=this._chunkSize-this._offset,i=this._maxLength,a=0,l=[],c=0,u;this.on("error",function(h){u=h});function d(h,g){if(o._hadError)return;let w=r-g;if(xg(w>=0,"have should not go down"),w>0){let k=o._buffer.slice(o._offset,o._offset+w);if(o._offset+=w,k.length>i&&(k=k.slice(0,i)),l.push(k),c+=k.length,i-=k.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}xg(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 u;if(c>=vg)throw Sg(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+vg.toString(16)+" bytes");let p=Buffer.concat(l,c);return Sg(this),p};RE.inherits(Ys,Uo.Inflate);function AE(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=Uo.Z_FINISH),t._processChunk(e,n)}function Eg(t,e){return AE(new Ys(e),t)}Tg.exports=Ir=Eg;Ir.Inflate=Ys;Ir.createInflate=CE;Ir.inflateSync=Eg});var Du=ne((tN,Ag)=>{"use strict";var Cg=Ag.exports=function(t){this._buffer=t,this._reads=[]};Cg.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};Cg.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 Pg=ne(Og=>{"use strict";var OE=Du(),PE=Cu();Og.process=function(t,e){let n=[],o=new OE(t);return new PE(e,{read:o.read.bind(o),write:function(r){n.push(r)},complete:function(){}}).start(),o.process(),Buffer.concat(n)}});var Ig=ne((sN,Lg)=>{"use strict";var Mg=!0,Ng=require("zlib"),ME=Rg();Ng.deflateSync||(Mg=!1);var NE=Du(),LE=Pg(),IE=Mu(),jE=Nu(),DE=Lu();Lg.exports=function(t,e){if(!Mg)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(R){n=R}let s;function r(R){s=R}function i(R){s.transColor=R}function a(R){s.palette=R}function l(){s.alpha=!0}let c;function u(R){c=R}let d=[];function f(R){d.push(R)}let p=new NE(t);if(new IE(e,{read:p.read.bind(p),error:o,metadata:r,gamma:u,palette:a,transColor:i,inflateData:f,simpleTransparency:l}).start(),p.process(),n)throw n;let g=Buffer.concat(d);d.length=0;let w;if(s.interlace)w=Ng.inflateSync(g);else{let C=((s.width*s.bpp*s.depth+7>>3)+1)*s.height;w=ME(g,{chunkSize:C,maxLength:C})}if(g=null,!w||!w.length)throw new Error("bad png - invalid inflate data response");let k=LE.process(w,s);g=null;let T=jE.dataToBitMap(k,s);k=null;let $=DE(T,s,e.skipRescale);return s.data=$,s.gamma=c||0,s}});var Fg=ne((oN,qg)=>{"use strict";var jg=!0,Dg=require("zlib");Dg.deflateSync||(jg=!1);var qE=Bo(),FE=ju();qg.exports=function(t,e){if(!jg)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 FE(n),s=[];s.push(Buffer.from(qE.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=Dg.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 Bg=ne(qu=>{"use strict";var BE=Ig(),UE=Fg();qu.read=function(t,e){return BE(t,e||{})};qu.write=function(t,e){return UE(t,e)}});var Hg=ne(Wg=>{"use strict";var WE=require("util"),Ug=require("stream"),HE=fg(),GE=kg(),YE=Bg(),Dt=Wg.PNG=function(t){Ug.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 HE(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 GE(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"))};WE.inherits(Dt,Ug);Dt.sync=YE;Dt.prototype.pack=function(){return!this.data||!this.data.length?(this.emit("error","No data provided"),this):(process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this)),this)};Dt.prototype.parse=function(t,e){if(e){let 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};Dt.prototype.write=function(t){return this._parser.write(t),!0};Dt.prototype.end=function(t){this._parser.end(t)};Dt.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};Dt.prototype._gamma=function(t){this.gamma=t};Dt.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};Dt.bitblt=function(t,e,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 l=0;l<r;l++)t.data.copy(e.data,(a+l)*e.width+i<<2,(o+l)*t.width+n<<2,(o+l)*t.width+n+s<<2)};Dt.prototype.bitblt=function(t,e,n,o,s,r,i){return Dt.bitblt(this,t,e,n,o,s,r,i),this};Dt.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}};Dt.prototype.adjustGamma=function(){Dt.adjustGamma(this)}});var Vg={};G_(Vg,{default:()=>zg});function zg(t,e,n,o,s,r={}){let{threshold:i=.1,alpha:a=.1,aaColor:l=[255,255,0],diffColor:c=[255,0,0],includeAA:u,diffColorAlt:d,diffMask:f}=r;if(!Fu(t)||!Fu(e)||n&&!Fu(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 oe=0;oe<p;oe++)if(h[oe]!==g[oe]){w=!1;break}if(w){if(n&&!f)for(let oe=0;oe<p;oe++)Yg(t,4*oe,a,n);return 0}let k=35215*i*i,[T,$,R]=l,[C,M,K]=c,[z,X,ae]=d||c,Z=0;for(let oe=0;oe<s;oe++)for(let Ke=0;Ke<o;Ke++){let Ee=oe*o+Ke,G=Ee*4,re=h[Ee]===g[Ee]?0:Kg(t,e,G,G,!1);if(Math.abs(re)>k){let et=Gg(t,Ke,oe,o,s,h,g)||Gg(e,Ke,oe,o,s,g,h);!u&&et?n&&!f&&Wa(n,G,T,$,R):(n&&(re<0?Wa(n,G,z,X,ae):Wa(n,G,C,M,K)),Z++)}else n&&!f&&Yg(t,G,a,n)}return Z}function Fu(t){return ArrayBuffer.isView(t)&&t.BYTES_PER_ELEMENT===1}function Gg(t,e,n,o,s,r,i){let a=Math.max(e-1,0),l=Math.max(n-1,0),c=Math.min(e+1,o-1),u=Math.min(n+1,s-1),d=n*o+e,f=e===a||e===c||n===l||n===u?1:0,p=0,h=0,g=0,w=0,k=0,T=0;for(let $=a;$<=c;$++)for(let R=l;R<=u;R++){if($===e&&R===n)continue;let C=Kg(t,t,d*4,(R*o+$)*4,!0);if(C===0){if(f++,f>2)return!1}else C<p?(p=C,g=$,w=R):C>h&&(h=C,k=$,T=R)}return p===0||h===0?!1:Ua(r,g,w,o,s)&&Ua(i,g,w,o,s)||Ua(r,k,T,o,s)&&Ua(i,k,T,o,s)}function Ua(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),l=Math.min(n+1,s-1),c=t[n*o+e],u=e===r||e===a||n===i||n===l?1:0;for(let d=r;d<=a;d++)for(let f=i;f<=l;f++)if(!(d===e&&f===n)&&(u+=+(c===t[f*o+d]),u>2))return!0;return!1}function Kg(t,e,n,o,s){let r=t[n],i=t[n+1],a=t[n+2],l=t[n+3],c=e[o],u=e[o+1],d=e[o+2],f=e[o+3],p=r-c,h=i-u,g=a-d,w=l-f;if(!p&&!h&&!g&&!w)return 0;if(l<255||f<255){let C=48+159*(n%2),M=48+159*((n/1.618033988749895|0)%2),K=48+159*((n/2.618033988749895|0)%2);p=(r*l-c*f-C*w)/255,h=(i*l-u*f-M*w)/255,g=(a*l-d*f-K*w)/255}let k=p*.29889531+h*.58662247+g*.11448223;if(s)return k;let T=p*.59597799-h*.2741761-g*.32180189,$=p*.21147017-h*.52261711+g*.31114694,R=.5053*k*k+.299*T*T+.1957*$*$;return k>0?-R:R}function Wa(t,e,n,o,s){t[e+0]=n,t[e+1]=o,t[e+2]=s,t[e+3]=255}function Yg(t,e,n,o){let s=255+(t[e]*.29889531+t[e+1]*.58662247+t[e+2]*.11448223-255)*n*t[e+3]/255;Wa(o,e,s,s,s)}var Xg=H_(()=>{});var zs=ne((aN,ty)=>{var ss=require("fs"),zE=require("path"),KE=require("os"),VE="nex-visual-";function Zg(t){return zE.join(KE.tmpdir(),`${VE}${Date.now()}-${t}`)}var Bu=null;function Ha(){return Bu||(Bu=Hg().PNG),Bu}var Uu=null;function XE(){if(!Uu){let t=(Xg(),z_(Vg));Uu=t.default||t}return Uu}function Gu(t,e,{threshold:n=.1}={}){let o=Ha(),s=XE(),r=o.sync.read(ss.readFileSync(t)),i=o.sync.read(ss.readFileSync(e)),a=Math.max(r.width,i.width),l=Math.max(r.height,i.height),c=Jg(r,a,l),u=Jg(i,a,l),d=new o({width:a,height:l}),f=s(c,u,d.data,a,l,{threshold:n,includeAA:!1}),p=a*l,h=(f/p*100).toFixed(1),g=JE(d.data,a,l,3,3),w=Zg("diff.png");return ss.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:l}}function Jg(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 JE(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),l=[];for(let c=0;c<s;c++)for(let u=0;u<o;u++){let d=0,f=0,p=u*i,h=c*a,g=Math.min(p+i,e),w=Math.min(h+a,n);for(let k=h;k<w;k++)for(let T=p;T<g;T++){f++;let $=(k*e+T)*4;(t[$]>0||t[$+1]>0)&&d++}if(d>0){let k=(d/f*100).toFixed(1),T=r[c]&&r[c][u]?r[c][u]:`row${c}-col${u}`;l.push({name:T,changedPercent:parseFloat(k),changed:d,total:f})}}return l.sort((c,u)=>u.changedPercent-c.changedPercent),l}var Qg=[{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 ZE(t,{viewports:e=Qg,height:n=800,fullPage:o=!1,timeout:s=3e4}={}){let{browserScreenshot:r}=ns(),i=[];for(let a of e){let l=await r(t,{width:a.width,height:n,fullPage:o,timeout:s});i.push({label:a.label,width:a.width,path:l.path,base64:l.base64,media_type:l.media_type})}return i}function ey(t,e=[]){let n=Ha(),o=n.sync.read(ss.readFileSync(t));for(let i of e){let a=QE(i.color||"#FF0000");i.type==="box"?(eT(o,i.x||0,i.y||0,i.width||50,i.height||50,a,i.thickness||3),i.label&&Hu(o,i.x||0,(i.y||0)-14,i.label,a)):i.type==="arrow"?(tT(o,i.x||0,i.y||0,i.toX||i.x+50,i.toY||i.y,a,i.thickness||3),i.label&&Hu(o,i.x||0,(i.y||0)-14,i.label,a)):i.type==="circle"&&(nT(o,i.x||0,i.y||0,i.radius||20,a,i.thickness||3),i.label&&Hu(o,(i.x||0)-(i.radius||20),(i.y||0)-(i.radius||20)-14,i.label,a))}let s=Zg("annotated.png");ss.writeFileSync(s,n.sync.write(o),{mode:384});let r=ss.readFileSync(s).toString("base64");return{path:s,base64:r,media_type:"image/png"}}function QE(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 qn(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 eT(t,e,n,o,s,r,i=3){for(let a=0;a<i;a++){for(let l=0;l<o;l++)qn(t,e+l,n+a,r),qn(t,e+l,n+s-1-a,r);for(let l=0;l<s;l++)qn(t,e+a,n+l,r),qn(t,e+o-1-a,n+l,r)}}function Wu(t,e,n,o,s,r,i=3){let a=Math.abs(o-e),l=Math.abs(s-n),c=e<o?1:-1,u=n<s?1:-1,d=a-l,f=e,p=n;for(;;){let h=Math.floor(i/2);for(let w=-h;w<=h;w++)for(let k=-h;k<=h;k++)qn(t,f+w,p+k,r);if(f===o&&p===s)break;let g=2*d;g>-l&&(d-=l,f+=c),g<a&&(d+=a,p+=u)}}function tT(t,e,n,o,s,r,i=3){Wu(t,e,n,o,s,r,i);let a=Math.atan2(s-n,o-e),l=15,c=a+Math.PI*.8,u=a-Math.PI*.8;Wu(t,o,s,Math.round(o+l*Math.cos(c)),Math.round(s+l*Math.sin(c)),r,i),Wu(t,o,s,Math.round(o+l*Math.cos(u)),Math.round(s+l*Math.sin(u)),r,i)}function nT(t,e,n,o,s,r=3){for(let i=0;i<r;i++){let a=o-i;for(let l=0;l<360;l+=.5){let c=l*Math.PI/180,u=Math.round(e+a*Math.cos(c)),d=Math.round(n+a*Math.sin(c));qn(t,u,d,s)}}}function Hu(t,e,n,o,s){let i=o.length*6+4,a=12;for(let l=0;l<a;l++)for(let c=0;c<i;c++)qn(t,e+c,n+l,{r:0,g:0,b:0,a:200});for(let l=0;l<i;l++)qn(t,e+l,n+a-1,s),qn(t,e+l,n+a-2,s);for(let l=0;l<o.length;l++){let c=e+2+l*6;for(let u=2;u<9;u++)for(let d=0;d<4;d++)qn(t,c+d,n+u,s)}}async function*sT(t,e,{maxIterations:n=20,hmrDelay:o=1500,width:s=1280,height:r=800,timeout:i=3e4}={}){let{browserScreenshot:a}=ns(),l=oT("chokidar"),c=await a(t,{width:s,height:r,timeout:i});if(yield{iteration:0,type:"baseline",path:c.path,base64:c.base64,media_type:c.media_type},!l){yield{iteration:-1,type:"error",message:"chokidar not installed \u2014 watch mode requires it. Install with: npm install chokidar"};return}let u=0,d=!1,f=l.watch(e,{ignoreInitial:!0,ignored:/(node_modules|\.git|dist)/});f.on("change",()=>{d=!0});try{for(;u<n;){await iT(()=>d,3e5),d=!1,u++,await rT(o);let p=await a(t,{width:s,height:r,timeout:i}),h=null;try{h=Gu(c.path,p.path)}catch{}c=p,yield{iteration:u,type:"change",path:p.path,base64:p.base64,media_type:p.media_type,diff:h?{diffPath:h.diffPath,diffPercent:h.diffPercent,changedPixels:h.changedPixels,regions:h.regionSummary}:null}}}finally{await f.close()}}function oT(t){try{return require(t)}catch{return null}}function rT(t){return new Promise(e=>setTimeout(e,t))}function iT(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 aT(t,{sampleRate:e=4}={}){let o=Ha().sync.read(ss.readFileSync(t)),s=new Map;for(let c=0;c<o.height;c+=e)for(let u=0;u<o.width;u+=e){let d=(c*o.width+u)*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,k=Math.round(p/8)*8,T=Math.round(h/8)*8,$=`${w},${k},${T}`;s.set($,(s.get($)||0)+1)}let r=[...s.entries()].sort((c,u)=>u[1]-c[1]).slice(0,20),i=r.reduce((c,u)=>c+u[1],0),a=r.map(([c,u])=>{let[d,f,p]=c.split(",").map(Number);return{hex:lT(d,f,p),rgb:`rgb(${d}, ${f}, ${p})`,frequency:parseFloat((u/i*100).toFixed(1)),category:cT(d,f,p)}}),l=uT(o);return{colors:a,spacing:l,dimensions:{width:o.width,height:o.height},imagePath:t}}function lT(t,e,n){return"#"+[t,e,n].map(o=>Math.min(255,o).toString(16).padStart(2,"0")).join("")}function cT(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 uT(t){let e=[],n=!1,o=0,s=dT(t);for(let i=0;i<t.height;i++){let a=!0;for(let l=0;l<t.width;l+=4){let c=(i*t.width+l)*4;if(Math.abs(t.data[c]-s.r)>20||Math.abs(t.data[c+1]-s.g)>20||Math.abs(t.data[c+2]-s.b)>20){a=!1;break}}if(a&&n)n=!1,o=i;else if(!a&&!n&&(n=!0,o>0)){let l=i-o;l>=4&&l<=200&&e.push(l)}}let r=new Map;for(let i of e){let a=Math.round(i/4)*4;r.set(a,(r.get(a)||0)+1)}return[...r.entries()].sort((i,a)=>a[1]-i[1]).slice(0,8).map(([i,a])=>({px:i,occurrences:a}))}function dT(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 fT(t,e,{width:n,height:o=800,fullPage:s=!1,threshold:r=.1,timeout:i=3e4}={}){let{browserScreenshot:a}=ns(),c=Ha().sync.read(ss.readFileSync(e)),u=n||c.width,d=o||c.height,f=await a(t,{width:u,height:d,fullPage:s,timeout:i}),p=Gu(e,f.path,{threshold:r}),h=ey(f.path,p.regionSummary.filter(g=>g.changedPercent>1).map((g,w)=>{let $=Math.ceil(p.width/3),R=Math.ceil(p.height/3),C=[["top-left","top-center","top-right"],["middle-left","center","middle-right"],["bottom-left","bottom-center","bottom-right"]],M=0,K=0;for(let z=0;z<3;z++)for(let X=0;X<3;X++)C[z][X]===g.name&&(M=X,K=z);return{type:"box",x:M*$+2,y:K*R+2,width:$-4,height:R-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:ss.readFileSync(p.diffPath).toString("base64"),annotatedBase64:h.base64}}ty.exports={pixelDiff:Gu,responsiveSweep:ZE,annotateImage:ey,visualWatch:sT,extractDesignTokens:aT,designCompare:fT,DEFAULT_VIEWPORTS:Qg}});var Yu=ne((lN,ny)=>{var{C:at}=xt(),Dr="",qt=[],jr=0,Ks=null;function pT(t){Ks=t}function hT(t,e){Dr=t,qt=[],jr=0;for(let o of e){jr++;let s=`t${jr}`;qt.push({id:s,description:o.description||o.title||o.name||o.task||`Task ${jr}`,status:"pending",dependsOn:o.depends_on||[],result:null})}let n=qt.map(o=>({...o}));return Ks&&Ks("create",{name:t,tasks:n}),n}function mT(t,e,n){let o=qt.find(s=>s.id===t);return o?(o.status=e,n!==void 0&&(o.result=n),Ks&&Ks("update",{id:t,status:e,result:n}),{...o}):null}function gT(){return{name:Dr,tasks:qt.map(t=>({...t}))}}function yT(){Dr="",qt=[],jr=0,Ks&&Ks("clear",{})}function bT(){return qt.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let n=qt.find(o=>o.id===e);return n&&n.status==="done"}))}function wT(){if(qt.length===0)return`${at.dim}No active tasks${at.reset}`;let t=[];Dr&&(t.push(` ${at.bold}${at.cyan}Tasks: ${Dr}${at.reset}`),t.push(` ${at.dim}${"\u2500".repeat(40)}${at.reset}`));for(let s of qt){let r,i;switch(s.status){case"done":r="\u2713",i=at.green;break;case"in_progress":r="\u2192",i=at.cyan;break;case"failed":r="\u2717",i=at.red;break;default:r="\xB7",i=at.dim}let a=s.dependsOn.length>0?` ${at.dim}(after: ${s.dependsOn.join(", ")})${at.reset}`:"",l=`[${s.status}]`,c=s.description.length>50?s.description.substring(0,47)+"...":s.description;if(t.push(` ${i}${r}${at.reset} ${at.bold}${s.id}${at.reset} ${c.padEnd(40)} ${i}${l}${at.reset}${a}`),s.result&&s.status==="done"){let u=s.result.length>60?s.result.substring(0,57)+"...":s.result;t.push(` ${at.dim}\u2192 ${u}${at.reset}`)}}let e=qt.filter(s=>s.status==="done").length,n=qt.filter(s=>s.status==="failed").length,o=qt.length;return t.push(` ${at.dim}${"\u2500".repeat(40)}${at.reset}`),t.push(` ${at.dim}${e}/${o} done${n>0?`, ${n} failed`:""}${at.reset}`),t.join(`
295
295
  `)}function _T(){return qt.length>0&&qt.some(t=>t.status==="pending"||t.status==="in_progress")}ny.exports={createTasks:hT,updateTask:mT,getTaskList:gT,clearTasks:yT,getReadyTasks:bT,renderTaskList:wT,setOnChange:pT,hasActiveTasks:_T}});var Ga=ne((cN,oy)=>{var qr={"devstral-2":{staleWarn:6e4,staleAbort:18e4,investigationCap:18,postEditCap:10,briefing:`You are devstral-2, a strong coding model optimized for agentic tasks.
296
296
  Use tools confidently and without hesitation \u2014 tool use is the expected workflow.
297
297
  You excel at sysadmin, frontend, and multi-step coding tasks.
@@ -305,7 +305,7 @@ Focus on correctness over speed.`},"ministral-3":{staleWarn:4e4,staleAbort:12e4,
305
305
  Prioritize decisive, targeted edits. Read only what you need, then fix.
306
306
  Stay on-scope \u2014 your strength is focused, efficient coding tasks.`},"qwen3-vl":{staleWarn:12e4,staleAbort:3e5,investigationCap:15,postEditCap:12,briefing:`You are qwen3-vl, the highest-ranked model for data, frontend, and agentic tasks.
307
307
  Trust your reasoning. Use tools thoroughly when the task demands it.
308
- You handle complex multi-step tasks well \u2014 don't cut corners prematurely.`}},sy={staleWarn:12e4,staleAbort:24e4,investigationCap:18,postEditCap:10};function $T(t){let e=(t||"").toLowerCase(),n=null,s=0;for(let r of Object.keys(qr))e.startsWith(r)&&r.length>s&&(n=r,s=r.length);let o=n?{...qr[n]}:{...sy};for(let[r,i]of[["NEX_STALE_WARN_MS","staleWarn"],["NEX_STALE_ABORT_MS","staleAbort"]])if(process.env[r]){let a=parseInt(process.env[r],10);Number.isInteger(a)&&a>=1e3&&a<=3e5&&(o[i]=a)}return o}function kT(t){let e=(t||"").toLowerCase(),n=null,s=0;for(let o of Object.keys(qr))e.startsWith(o)&&o.length>s&&(n=o,s=o.length);return n&&qr[n].briefing||""}oy.exports={getModelProfile:$T,getModelBriefing:kT,PROFILES:qr,DEFAULTS:sy}});var Ku=ne((uN,uy)=>{var{callChat:xT}=vt(),{estimateTokens:zu}=Fn(),ry=process.env.NEX_COMPACTION!=="false",iy=6,ay=2e3,ly=3,vT=`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.
308
+ You handle complex multi-step tasks well \u2014 don't cut corners prematurely.`}},sy={staleWarn:12e4,staleAbort:24e4,investigationCap:18,postEditCap:10};function $T(t){let e=(t||"").toLowerCase(),n=null,o=0;for(let r of Object.keys(qr))e.startsWith(r)&&r.length>o&&(n=r,o=r.length);let s=n?{...qr[n]}:{...sy};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 kT(t){let e=(t||"").toLowerCase(),n=null,o=0;for(let s of Object.keys(qr))e.startsWith(s)&&s.length>o&&(n=s,o=s.length);return n&&qr[n].briefing||""}oy.exports={getModelProfile:$T,getModelBriefing:kT,PROFILES:qr,DEFAULTS:sy}});var Ku=ne((uN,uy)=>{var{callChat:xT}=vt(),{estimateTokens:zu}=Fn(),ry=process.env.NEX_COMPACTION!=="false",iy=6,ay=2e3,ly=3,vT=`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.
309
309
  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.
310
310
 
311
311
  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:
@@ -337,30 +337,30 @@ Format your output as:
337
337
 
338
338
  <summary>
339
339
  [Sections 1-9 above]
340
- </summary>`,Vs=0;async function ST(t){if(!ry||t.length<iy||Vs>=ly)return null;let e=[{role:"system",content:vT},{role:"user",content:cy(t)}];try{let s=((await xT(e,[],{temperature:0,maxTokens:ay})).content||"").trim();if(!s)return Vs++,null;let o=s.match(/<summary>([\s\S]*?)<\/summary>/);if(o?s=o[1].trim():s=s.replace(/<analysis>[\s\S]*?<\/analysis>/g,"").trim(),!s)return Vs++,null;let r=t.reduce((a,l)=>a+zu(l.content||"")+(l.tool_calls?zu(JSON.stringify(l.tool_calls)):0),0),i=zu(s);return i>=r*.8?(Vs++,null):(Vs=0,{message:{role:"system",content:`[Conversation Summary \u2014 ${t.length} messages compacted]
341
- ${s}`,_compacted:!0,_originalCount:t.length},tokensRemoved:r-i})}catch{return Vs++,null}}function ET(){Vs=0}function cy(t){return t.map(e=>{let n=e.role==="tool"?"tool_result":e.role,s=(e.content||"").substring(0,500);if(e.tool_calls){let o=e.tool_calls.map(r=>r.function?.name).join(", ");return`[${n}] ${s}
342
- tools: ${o}`}return`[${n}] ${s}`}).join(`
340
+ </summary>`,Vs=0;async function ST(t){if(!ry||t.length<iy||Vs>=ly)return null;let e=[{role:"system",content:vT},{role:"user",content:cy(t)}];try{let o=((await xT(e,[],{temperature:0,maxTokens:ay})).content||"").trim();if(!o)return Vs++,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 Vs++,null;let r=t.reduce((a,l)=>a+zu(l.content||"")+(l.tool_calls?zu(JSON.stringify(l.tool_calls)):0),0),i=zu(o);return i>=r*.8?(Vs++,null):(Vs=0,{message:{role:"system",content:`[Conversation Summary \u2014 ${t.length} messages compacted]
341
+ ${o}`,_compacted:!0,_originalCount:t.length},tokensRemoved:r-i})}catch{return Vs++,null}}function ET(){Vs=0}function cy(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}
342
+ tools: ${s}`}return`[${n}] ${o}`}).join(`
343
343
 
344
- `)}uy.exports={compactMessages:ST,formatMessagesForSummary:cy,resetCompactionFailures:ET,COMPACTION_ENABLED:ry,COMPACTION_MIN_MESSAGES:iy,COMPACTION_SUMMARY_BUDGET:ay,MAX_CONSECUTIVE_FAILURES:ly}});var Fn=ne((dN,_y)=>{var TT=require("path");function fy(){return vt().getActiveModel()}var RT={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},CT={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},Xs=new Map,dy=1e3,Vu=new WeakMap,Js=null;function AT(){if(Js!==null)return Js;try{let t=fy(),e=t?.provider||"ollama",n=(t?.id||"").toLowerCase();for(let[s,o]of Object.entries(CT))if(n.startsWith(s))return Js=o,Js;return Js=RT[e]||4,Js}catch{return 4}}function OT(){Js=null}function Zs(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=Xs.get(e);if(n!==void 0)return Xs.delete(e),Xs.set(e,n),n;let s=Math.ceil(t.length/AT());if(Xs.size>=dy){let o=dy>>1,r=Xs.keys();for(let i=0;i<o;i++)Xs.delete(r.next().value)}return Xs.set(e,s),s}function PT(t){if(Vu.has(t))return Vu.get(t);let e=JSON.stringify(t);return Vu.set(t,e),e}function ws(t){let n=4;if(t.content&&(n+=Zs(t.content)),t.tool_calls)for(let s of t.tool_calls){n+=4,n+=Zs(s.function?.name||"");let o=s.function?.arguments;typeof o=="string"?n+=Zs(o):o&&(n+=Zs(JSON.stringify(o)))}return n}function fn(t){let e=0;for(let n of t)e+=ws(n);return e}function MT(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,s=e.length,o=0;for(let r=n;r<s;r++)o+=ws(e[r]);return o}var Xu=new WeakMap;function Ya(t){if(!t||t.length===0)return 0;if(Xu.has(t))return Xu.get(t);let e=Zs(JSON.stringify(t));return Xu.set(t,e),e}function za(){return fy()?.contextWindow||32768}var Ft={msgCount:-1,lastMsgRef:null,toolCount:-1,result:null,messagesRef:null,messageTokens:0,systemTokens:0,conversationTokens:0,toolResultTokens:0};function NT(t,e){let n=t.length>0?t[t.length-1]:null,s=e?e.length:0;if(Ft.result&&t.length===Ft.msgCount&&n===Ft.lastMsgRef&&s===Ft.toolCount)return Ft.result;let o,r,i,a;if(Ft.messagesRef===t&&t.length>Ft.msgCount&&Ft.msgCount>=0){o=Ft.messageTokens,r=Ft.systemTokens,i=Ft.conversationTokens,a=Ft.toolResultTokens;for(let p=Ft.msgCount;p<t.length;p++){let h=ws(t[p]);o+=h,t[p].role==="system"?r+=h:t[p].role==="tool"?a+=h:i+=h}}else{o=0,r=0,i=0,a=0;for(let p of t){let h=ws(p);o+=h,p.role==="system"?r+=h:p.role==="tool"?a+=h:i+=h}}let l=Ya(e),c=o+l,u=za(),d=u>0?c/u*100:0,f={used:c,limit:u,percentage:Math.round(d*10)/10,breakdown:{system:r,conversation:i,toolResults:a,toolDefinitions:l},messageCount:t.length};return Ft={msgCount:t.length,lastMsgRef:n,toolCount:s,result:f,messagesRef:t,messageTokens:o,systemTokens:r,conversationTokens:i,toolResultTokens:a},f}var Fr=parseFloat(process.env.NEX_COMPRESSION_THRESHOLD)||.75,py=parseFloat(process.env.NEX_SAFETY_MARGIN)||.1,hy=parseInt(process.env.NEX_KEEP_RECENT,10)||10,my={essential:.6,standard:.65,full:Math.min(Fr,.75)};function gy(){if(process.env.NEX_COMPRESSION_THRESHOLD)return Fr;try{let{getActiveTier:t}=Nr(),e=t();return my[e]??Fr}catch{return Fr}}var LT=200,IT=1e3;function yy(t,e){if(!t||t.length<=e)return t;let s=/^(ERROR|EXIT|BLOCKED|CANCELLED)/i.test(t)?e*3:e;if(t.length<=s)return t;let o=t.split(`
345
- `);if(o.length<=10){let h=Math.floor(s*.6),g=Math.floor(s*.4),w=t.substring(0,h),k=t.substring(t.length-g);return w+`
344
+ `)}uy.exports={compactMessages:ST,formatMessagesForSummary:cy,resetCompactionFailures:ET,COMPACTION_ENABLED:ry,COMPACTION_MIN_MESSAGES:iy,COMPACTION_SUMMARY_BUDGET:ay,MAX_CONSECUTIVE_FAILURES:ly}});var Fn=ne((dN,_y)=>{var TT=require("path");function fy(){return vt().getActiveModel()}var RT={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},CT={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},Xs=new Map,dy=1e3,Vu=new WeakMap,Js=null;function AT(){if(Js!==null)return Js;try{let t=fy(),e=t?.provider||"ollama",n=(t?.id||"").toLowerCase();for(let[o,s]of Object.entries(CT))if(n.startsWith(o))return Js=s,Js;return Js=RT[e]||4,Js}catch{return 4}}function OT(){Js=null}function Zs(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=Xs.get(e);if(n!==void 0)return Xs.delete(e),Xs.set(e,n),n;let o=Math.ceil(t.length/AT());if(Xs.size>=dy){let s=dy>>1,r=Xs.keys();for(let i=0;i<s;i++)Xs.delete(r.next().value)}return Xs.set(e,o),o}function PT(t){if(Vu.has(t))return Vu.get(t);let e=JSON.stringify(t);return Vu.set(t,e),e}function ws(t){let n=4;if(t.content&&(n+=Zs(t.content)),t.tool_calls)for(let o of t.tool_calls){n+=4,n+=Zs(o.function?.name||"");let s=o.function?.arguments;typeof s=="string"?n+=Zs(s):s&&(n+=Zs(JSON.stringify(s)))}return n}function fn(t){let e=0;for(let n of t)e+=ws(n);return e}function MT(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+=ws(e[r]);return s}var Xu=new WeakMap;function Ya(t){if(!t||t.length===0)return 0;if(Xu.has(t))return Xu.get(t);let e=Zs(JSON.stringify(t));return Xu.set(t,e),e}function za(){return fy()?.contextWindow||32768}var Ft={msgCount:-1,lastMsgRef:null,toolCount:-1,result:null,messagesRef:null,messageTokens:0,systemTokens:0,conversationTokens:0,toolResultTokens:0};function NT(t,e){let n=t.length>0?t[t.length-1]:null,o=e?e.length:0;if(Ft.result&&t.length===Ft.msgCount&&n===Ft.lastMsgRef&&o===Ft.toolCount)return Ft.result;let s,r,i,a;if(Ft.messagesRef===t&&t.length>Ft.msgCount&&Ft.msgCount>=0){s=Ft.messageTokens,r=Ft.systemTokens,i=Ft.conversationTokens,a=Ft.toolResultTokens;for(let p=Ft.msgCount;p<t.length;p++){let h=ws(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=ws(p);s+=h,p.role==="system"?r+=h:p.role==="tool"?a+=h:i+=h}}let l=Ya(e),c=s+l,u=za(),d=u>0?c/u*100:0,f={used:c,limit:u,percentage:Math.round(d*10)/10,breakdown:{system:r,conversation:i,toolResults:a,toolDefinitions:l},messageCount:t.length};return Ft={msgCount:t.length,lastMsgRef:n,toolCount:o,result:f,messagesRef:t,messageTokens:s,systemTokens:r,conversationTokens:i,toolResultTokens:a},f}var Fr=parseFloat(process.env.NEX_COMPRESSION_THRESHOLD)||.75,py=parseFloat(process.env.NEX_SAFETY_MARGIN)||.1,hy=parseInt(process.env.NEX_KEEP_RECENT,10)||10,my={essential:.6,standard:.65,full:Math.min(Fr,.75)};function gy(){if(process.env.NEX_COMPRESSION_THRESHOLD)return Fr;try{let{getActiveTier:t}=Nr(),e=t();return my[e]??Fr}catch{return Fr}}var LT=200,IT=1e3;function yy(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(`
345
+ `);if(s.length<=10){let h=Math.floor(o*.6),g=Math.floor(o*.4),w=t.substring(0,h),k=t.substring(t.length-g);return w+`
346
346
  ...(${t.length} chars total)...
347
- `+k}let r=Math.floor(o.length*.4),i=Math.floor(o.length*.4),a=[],l=0,c=Math.floor(s*.4);for(let h=0;h<r&&l<c;h++)if(l+o[h].length+1>c&&o[h].trim().startsWith("```")){a.push(o[h]),l+=o[h].length+1;let g=h+1;for(;g<o.length&&l<c*1.5&&!o[g].trim().startsWith("```");)a.push(o[g]),l+=o[g].length+1,g++;g<o.length&&o[g].trim().startsWith("```")&&(a.push(o[g]),l+=o[g].length+1),h=g}else a.push(o[h]),l+=o[h].length+1;let u=[],d=0,f=Math.floor(s*.4);for(let h=o.length-1;h>=o.length-i&&d<f;h--)if(d+o[h].length+1>f&&o[h].trim().startsWith("```")){u.push(o[h]),d+=o[h].length+1;let g=h-1;for(;g>=0&&d<f*1.5&&!o[g].trim().startsWith("```");)u.push(o[g]),d+=o[g].length+1,g--;g>=0&&o[g].trim().startsWith("```")&&(u.push(o[g]),d+=o[g].length+1),h=g}else u.push(o[h]),d+=o[h].length+1;u.reverse();let p=o.length-a.length-u.length;return a.join(`
347
+ `+k}let r=Math.floor(s.length*.4),i=Math.floor(s.length*.4),a=[],l=0,c=Math.floor(o*.4);for(let h=0;h<r&&l<c;h++)if(l+s[h].length+1>c&&s[h].trim().startsWith("```")){a.push(s[h]),l+=s[h].length+1;let g=h+1;for(;g<s.length&&l<c*1.5&&!s[g].trim().startsWith("```");)a.push(s[g]),l+=s[g].length+1,g++;g<s.length&&s[g].trim().startsWith("```")&&(a.push(s[g]),l+=s[g].length+1),h=g}else a.push(s[h]),l+=s[h].length+1;let u=[],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("```")){u.push(s[h]),d+=s[h].length+1;let g=h-1;for(;g>=0&&d<f*1.5&&!s[g].trim().startsWith("```");)u.push(s[g]),d+=s[g].length+1,g--;g>=0&&s[g].trim().startsWith("```")&&(u.push(s[g]),d+=s[g].length+1),h=g}else u.push(s[h]),d+=s[h].length+1;u.reverse();let p=s.length-a.length-u.length;return a.join(`
348
348
  `)+`
349
- ...(${p} lines omitted, ${o.length} total)...
349
+ ...(${p} lines omitted, ${s.length} total)...
350
350
  `+u.join(`
351
- `)}function Ho(t,e="light"){let n=e==="aggressive"?100:e==="medium"?200:IT,s=e==="aggressive"?50:e==="medium"?100:LT;if(t.role==="tool"){let o=typeof t.content=="string"?t.content:JSON.stringify(t.content);return o.length>s?{...t,content:yy(o,s)}:t}if(t.role==="assistant"){let o={...t};return o.content&&o.content.length>n&&(o.content=o.content.substring(0,n)+`
352
- ...(truncated)`),o.tool_calls&&e==="aggressive"&&(o.tool_calls=o.tool_calls.map(r=>({...r,function:{name:r.function.name,arguments:typeof r.function.arguments=="string"?r.function.arguments.substring(0,50):r.function.arguments}}))),o}return t}function by(t,e,n,s){let o=0;if(t.role==="system")return 100;if(t.role==="user")o+=35;else if(t.role==="tool"){let i=typeof t.content=="string"?t.content:JSON.stringify(t.content||"");/^(ERROR|BLOCKED|CANCELLED)/i.test(i)?o+=30:o+=15}else t.role==="assistant"&&(o+=t.tool_calls?20:10);let r=n>1?e/(n-1):1;if(o+=Math.round(r*30),s&&s.size>0){let i=typeof t.content=="string"?t.content:JSON.stringify(t.content||""),a=0;for(let l of s)(i.includes(l)||i.includes(TT.basename(l)))&&a++;o+=Math.min(30,a*10)}return Math.min(100,o)}function wy(t,e=10){let n=new Set,s=t.slice(-e),o=/(?:\/[\w.-]+)+\.\w+/g;for(let r of s){let a=(typeof r.content=="string"?r.content:JSON.stringify(r.content||"")).match(o);a&&a.forEach(l=>n.add(l))}return n}function jT(t,{filesModified:e=new Set,currentPhase:n=null}={}){let s=[];if(e.size>0){let r=[...e].map(i=>i.split("/").slice(-2).join("/")).join(", ");s.push(`Files already modified: ${r} \u2014 do NOT rewrite these, use edit_file for additions only.`)}n&&s.push(`Current phase: ${n}`);let o=t.filter(r=>r.role==="assistant"&&typeof r.content=="string"&&r.content.trim().length>30).slice(-3).map(r=>r.content.trim().slice(0,200).replace(/\n+/g," "));return o.length>0&&s.push(`Recent progress:
353
- `+o.map(r=>`- ${r}`).join(`
354
- `)),s.length===0?null:{role:"system",content:`## Progress State (preserved through compression)
355
- ${s.join(`
356
- `)}`,_pinned:!0,_progressSnapshot:!0}}var Wo={msgCount:-1,lastMsgRef:null,result:null};function DT(){Wo={msgCount:-1,lastMsgRef:null,result:null},Ft={msgCount:-1,lastMsgRef:null,toolCount:-1,result:null,messagesRef:null,messageTokens:0,systemTokens:0,conversationTokens:0,toolResultTokens:0}}async function qT(t,e,n={}){let s=t.length>0?t[t.length-1]:null;if(!n.force&&Wo.result&&t.length===Wo.msgCount&&s===Wo.lastMsgRef)return Wo.result;let o=n.threshold??gy(),r=n.safetyMargin??py,i=n.keepRecent??hy,a=za(),l=Ya(e),c=Math.floor(a*(o-r)),u=c-l,d=fn(t);if(d+l<=c){let Z={messages:t,compressed:!1,compacted:!1,tokensRemoved:0};return Wo={msgCount:t.length,lastMsgRef:s,result:Z},Z}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),k=t.slice(g,w),T=t.slice(w),$=k.map(Z=>Ho(Z,"light")),R=os(h,$,T),C=fn(R);if(C+l<=c)return{messages:R,compressed:!0,compacted:!1,tokensRemoved:p-C};if($=k.map(Z=>Ho(Z,"medium")),R=os(h,$,T),C=fn(R),C+l<=c)return{messages:R,compressed:!0,compacted:!1,tokensRemoved:p-C};if($=k.map(Z=>Ho(Z,"aggressive")),R=os(h,$,T),C=fn(R),C+l<=c)return{messages:R,compressed:!0,compacted:!1,tokensRemoved:p-C};let M=process.env.NEX_SKIP_COMPACTOR==="1",K=k.filter(Z=>Z._pinned),z=k.filter(Z=>!Z._compacted&&!Z._pinned);if(!M&&z.length>=6)try{let{compactMessages:Z}=Ku(),oe=await Z(z);if(oe){let Ke=k.filter(et=>et._compacted&&!et._pinned),Ee=[...K,...Ke,oe.message],G=os(h,Ee,T),re=fn(G);if(re+l<=c)return{messages:G,compressed:!0,compacted:!0,tokensRemoved:p-re};k=Ee}}catch(Z){process.env.NEX_DEBUG&&console.error("[context-engine] LLM compacting failed:",Z.message)}let X=wy([...$,...T]),ae=$.map((Z,oe)=>({msg:Z,score:Z._pinned?1/0:by(Z,oe,$.length,X),tokens:ws(Z)}));for(;ae.length>0&&C>u;){let Z=-1;for(let oe=0;oe<ae.length;oe++)ae[oe].score!==1/0&&(Z===-1||ae[oe].score<ae[Z].score)&&(Z=oe);if(Z===-1)break;C-=ae[Z].tokens,ae.splice(Z,1)}return $=ae.map(Z=>Z.msg),R=os(h,$,T),C=fn(R),{messages:R,compressed:!0,compacted:!1,tokensRemoved:p-C}}function os(t,e,n){let s=[];return t&&s.push(t),s.push(...e,...n),s}function FT(t,e){if(!t)return"";if(Zs(t)<=e)return t;let s=e*4,o=t.split(`
357
- `),r=Math.floor(s*.6),i=Math.floor(s*.4),a="",l=0;for(let p of o){if(a.length+p.length+1>r)break;a+=(a?`
358
- `:"")+p,l++}let c="",u=0;for(let p=o.length-1;p>=l;p--){let h=o[p]+(c?`
351
+ `)}function Ho(t,e="light"){let n=e==="aggressive"?100:e==="medium"?200:IT,o=e==="aggressive"?50:e==="medium"?100:LT;if(t.role==="tool"){let s=typeof t.content=="string"?t.content:JSON.stringify(t.content);return s.length>o?{...t,content:yy(s,o)}:t}if(t.role==="assistant"){let s={...t};return s.content&&s.content.length>n&&(s.content=s.content.substring(0,n)+`
352
+ ...(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 by(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 l of o)(i.includes(l)||i.includes(TT.basename(l)))&&a++;s+=Math.min(30,a*10)}return Math.min(100,s)}function wy(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(l=>n.add(l))}return n}function jT(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:
353
+ `+s.map(r=>`- ${r}`).join(`
354
+ `)),o.length===0?null:{role:"system",content:`## Progress State (preserved through compression)
355
+ ${o.join(`
356
+ `)}`,_pinned:!0,_progressSnapshot:!0}}var Wo={msgCount:-1,lastMsgRef:null,result:null};function DT(){Wo={msgCount:-1,lastMsgRef:null,result:null},Ft={msgCount:-1,lastMsgRef:null,toolCount:-1,result:null,messagesRef:null,messageTokens:0,systemTokens:0,conversationTokens:0,toolResultTokens:0}}async function qT(t,e,n={}){let o=t.length>0?t[t.length-1]:null;if(!n.force&&Wo.result&&t.length===Wo.msgCount&&o===Wo.lastMsgRef)return Wo.result;let s=n.threshold??gy(),r=n.safetyMargin??py,i=n.keepRecent??hy,a=za(),l=Ya(e),c=Math.floor(a*(s-r)),u=c-l,d=fn(t);if(d+l<=c){let Z={messages:t,compressed:!1,compacted:!1,tokensRemoved:0};return Wo={msgCount:t.length,lastMsgRef:o,result:Z},Z}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),k=t.slice(g,w),T=t.slice(w),$=k.map(Z=>Ho(Z,"light")),R=os(h,$,T),C=fn(R);if(C+l<=c)return{messages:R,compressed:!0,compacted:!1,tokensRemoved:p-C};if($=k.map(Z=>Ho(Z,"medium")),R=os(h,$,T),C=fn(R),C+l<=c)return{messages:R,compressed:!0,compacted:!1,tokensRemoved:p-C};if($=k.map(Z=>Ho(Z,"aggressive")),R=os(h,$,T),C=fn(R),C+l<=c)return{messages:R,compressed:!0,compacted:!1,tokensRemoved:p-C};let M=process.env.NEX_SKIP_COMPACTOR==="1",K=k.filter(Z=>Z._pinned),z=k.filter(Z=>!Z._compacted&&!Z._pinned);if(!M&&z.length>=6)try{let{compactMessages:Z}=Ku(),oe=await Z(z);if(oe){let Ke=k.filter(et=>et._compacted&&!et._pinned),Ee=[...K,...Ke,oe.message],G=os(h,Ee,T),re=fn(G);if(re+l<=c)return{messages:G,compressed:!0,compacted:!0,tokensRemoved:p-re};k=Ee}}catch(Z){process.env.NEX_DEBUG&&console.error("[context-engine] LLM compacting failed:",Z.message)}let X=wy([...$,...T]),ae=$.map((Z,oe)=>({msg:Z,score:Z._pinned?1/0:by(Z,oe,$.length,X),tokens:ws(Z)}));for(;ae.length>0&&C>u;){let Z=-1;for(let oe=0;oe<ae.length;oe++)ae[oe].score!==1/0&&(Z===-1||ae[oe].score<ae[Z].score)&&(Z=oe);if(Z===-1)break;C-=ae[Z].tokens,ae.splice(Z,1)}return $=ae.map(Z=>Z.msg),R=os(h,$,T),C=fn(R),{messages:R,compressed:!0,compacted:!1,tokensRemoved:p-C}}function os(t,e,n){let o=[];return t&&o.push(t),o.push(...e,...n),o}function FT(t,e){if(!t)return"";if(Zs(t)<=e)return t;let o=e*4,s=t.split(`
357
+ `),r=Math.floor(o*.6),i=Math.floor(o*.4),a="",l=0;for(let p of s){if(a.length+p.length+1>r)break;a+=(a?`
358
+ `:"")+p,l++}let c="",u=0;for(let p=s.length-1;p>=l;p--){let h=s[p]+(c?`
359
359
  `:"")+c;if(h.length>i)break;c=h,u++}let f=`
360
360
 
361
- ... (${o.length-l-u} lines omitted, ${o.length} total) ...
361
+ ... (${s.length-l-u} lines omitted, ${s.length} total) ...
362
362
 
363
- `;return a+f+c}var BT=6;function UT(t,e,n=!1){let s=za(),o=Ya(e),r=Math.floor(s*(n?.35:.5))-o,i=fn(t),a=Math.floor(i*(n?.5:.8));r>a&&(r=a);let l=null,c=0;t.length>0&&t[0].role==="system"&&(l=t[0],c=1);let u=n?2:BT,d=Math.max(c,t.length-u),f=t.slice(c,d),p=t.slice(d),h=f;n&&(p=p.map(C=>Ho(C,"aggressive")));let g=os(l,h,p),w=fn(g);for(;h.length>0&&w>r;){let C=h.shift();w-=ws(C)}if(!n&&w>r&&h.length>0)for(h=h.map(C=>Ho(C,"aggressive")),g=os(l,h,p),w=fn(g);h.length>0&&w>r;){let C=h.shift();w-=ws(C)}n&&w>r&&(p=p.filter(M=>M.role==="user").slice(-1),g=os(l,[],p),w=fn(g)),g=os(l,h,p);let k=t.filter(C=>C.role==="user"),T=C=>{let M=typeof C.content=="string"?C.content:"";return M.startsWith("[SYSTEM WARNING]")||M.startsWith("[SYSTEM:")||M.startsWith("BLOCKED:")},$=k.find(C=>!T(C)),R=[...k].reverse().find(C=>!T(C));if($&&!g.find(C=>C===$)){let C=g.findIndex(K=>K.role==="system"),M=C>=0?C+1:0;g.splice(M,0,$)}return R&&R!==$&&!g.find(C=>C===R)&&g.push(R),{messages:g,tokensRemoved:i-fn(g)}}_y.exports={estimateTokens:Zs,estimateMessageTokens:ws,estimateMessagesTokens:fn,estimateDeltaTokens:MT,estimateToolsTokens:Ya,serializeMessage:PT,getContextWindow:za,getUsage:NT,compressMessage:Ho,compressToolResult:yy,scoreMessageRelevance:by,extractActiveFiles:wy,buildProgressSnapshot:jT,fitToContext:qT,forceCompress:UT,truncateFileContent:FT,invalidateTokenRatioCache:OT,invalidateFitToContextCache:DT,getEffectiveCompressionThreshold:gy,COMPRESSION_THRESHOLD:Fr,TIER_COMPRESSION_THRESHOLDS:my,SAFETY_MARGIN:py,KEEP_RECENT:hy}});var Yo=ne((fN,$y)=>{var{fork:WT}=require("child_process"),HT=require("path"),GT=HT.join(__dirname,"background-worker.js"),Qs=new Map,Go=new Map;function YT(){return`bg-${Date.now()}-${Math.random().toString(36).slice(2,6)}`}function zT(t){let e=YT(),n=WT(GT,[],{silent:!0,env:process.env,cwd:process.cwd()});return n.send({jobId:e,agentDef:t}),n.on("message",s=>{s.type==="result"?Ju(e,t,s.payload):s.type==="error"&&Ju(e,t,{task:t.task,status:"failed",result:`Background agent error: ${s.error}`,toolsUsed:[],tokensUsed:{input:0,output:0}})}),n.on("exit",(s,o)=>{if(Qs.has(e)){let r=o?`killed (${o})`:`exit code ${s}`;Ju(e,t,{task:t.task,status:"failed",result:`Background agent terminated unexpectedly: ${r}`,toolsUsed:[],tokensUsed:{input:0,output:0}})}}),Qs.set(e,{process:n,agentDef:t,startedAt:Date.now()}),e}function Ju(t,e,n){Qs.delete(t),Go.set(t,{jobId:t,agentDef:e,result:n,finishedAt:Date.now()})}function KT(){if(Go.size===0)return[];let t=[...Go.values()];return Go.clear(),t}function VT(){return Qs.size>0||Go.size>0}function XT(){let t=Qs.size;return t===0?"":`${t} bg agent${t===1?"":"s"} running`}function JT(){for(let[t,e]of Qs){try{e.process.kill("SIGTERM")}catch{}Qs.delete(t)}Go.clear()}$y.exports={createJob:zT,getCompletedJobs:KT,getPendingJobSummary:XT,hasPendingOrCompletedJobs:VT,cancelAllJobs:JT}});var td=ne((hN,Uy)=>{var{callStream:ZT,getActiveProviderName:Va,getActiveModelId:ky,getConfiguredProviders:QT,getProvider:xy,getActiveProvider:vy,parseModelSpec:Sy}=vt(),{parseToolArgs:Ey}=kr(),{filterToolsForModel:eR,getModelTier:Ka}=Nr(),{getModelBriefing:tR}=Ga(),{trackUsage:Ty,estimateTokens:Ry}=ma(),{MultiProgress:nR,C:pN}=xt();function Cy(t){return!t||typeof t!="string"?0:typeof Ry=="function"?Ry(t):Math.ceil(t.length/4)}var Py=15,sR=parseInt(process.env.NEX_MAX_PARALLEL||"10",10),Ay=parseInt(process.env.NEX_MAX_CHAT_RETRIES||"3",10),My=8,oR=2,Xa=new Map,Ny=600*1e3;function rR(t,e){let n=Xa.get(t);return n&&n.agentId!==e&&Date.now()-n.timestamp<Ny?!1:(Xa.set(t,{agentId:e,timestamp:Date.now()}),!0)}function Br(t){Xa.delete(t)}function Zu(){Xa.clear()}function Qu(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 Ly(t){let e=Qu(t);return e==="rate_limit"||e==="server"||e==="network"||e==="timeout"}async function Iy(t,e,n){let s;for(let o=0;o<=Ay;o++)try{return await ZT(t,e,n)}catch(r){s=r;let i=Qu(r);if(i==="auth")throw r.message=`Authentication failed \u2014 check your API key or permissions. (${r.message})`,r;if(i==="context_overflow")throw r.message=`Context window exceeded \u2014 reduce message history or use a model with a larger context. (${r.message})`,r;if(o<Ay&&Ly(r)){let l=i==="rate_limit"?Math.min(2e3*Math.pow(2,o),15e3):Math.min(500*Math.pow(2,o),4e3);await new Promise(c=>setTimeout(c,l).unref());continue}throw r}throw s}var Oy=new Set(["ask_user","task_list"]);function jy(t){return t>=2?new Set([...Oy,"spawn_agents"]):Oy}var iR=new Set(["write_file","edit_file","patch_file"]),Dy={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:""}},aR=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,lR=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function qy(t){return lR.test(t)?"full":aR.test(t)?"essential":t.length>300?"full":"standard"}function Fy(t){let e=QT(),n=Va(),s=[...e].sort((o,r)=>(o.name===n?-1:1)-(r.name===n?-1:1));for(let o of s)for(let r of o.models)if(Ka(r.id,o.name)===t)return{provider:o.name,model:r.id};return null}var cR={essential:process.env.NEX_FAST_MODEL||null,standard:process.env.NEX_STANDARD_MODEL||null,full:process.env.NEX_HEAVY_MODEL||null};function Ja(t){if(t.model){let{provider:o,model:r}=Sy(t.model),i=o?xy(o):vy(),a=o||Va();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let l=Ka(r,a);return{provider:a,model:r,tier:l}}}let e=qy(t.task),n=cR[e];if(n){let{provider:o,model:r}=Sy(n),i=o?xy(o):vy(),a=o||Va();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let l=Ka(r,a);return{provider:a,model:r,tier:l}}}let s=Fy(e);if(s){let o=Ka(s.model,s.provider);return{provider:s.provider,model:s.model,tier:o}}return{provider:null,model:null,tier:null}}async function By(t,e={},n=0){let s=n===0?Py:My,o=Math.min(t.max_iterations||10,s),r=`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,i=[],a={input:0,output:0},l=new Set,c=new Map,u=t._systemPrompt||`You are a focused sub-agent. Complete this specific task efficiently.
363
+ `;return a+f+c}var BT=6;function UT(t,e,n=!1){let o=za(),s=Ya(e),r=Math.floor(o*(n?.35:.5))-s,i=fn(t),a=Math.floor(i*(n?.5:.8));r>a&&(r=a);let l=null,c=0;t.length>0&&t[0].role==="system"&&(l=t[0],c=1);let u=n?2:BT,d=Math.max(c,t.length-u),f=t.slice(c,d),p=t.slice(d),h=f;n&&(p=p.map(C=>Ho(C,"aggressive")));let g=os(l,h,p),w=fn(g);for(;h.length>0&&w>r;){let C=h.shift();w-=ws(C)}if(!n&&w>r&&h.length>0)for(h=h.map(C=>Ho(C,"aggressive")),g=os(l,h,p),w=fn(g);h.length>0&&w>r;){let C=h.shift();w-=ws(C)}n&&w>r&&(p=p.filter(M=>M.role==="user").slice(-1),g=os(l,[],p),w=fn(g)),g=os(l,h,p);let k=t.filter(C=>C.role==="user"),T=C=>{let M=typeof C.content=="string"?C.content:"";return M.startsWith("[SYSTEM WARNING]")||M.startsWith("[SYSTEM:")||M.startsWith("BLOCKED:")},$=k.find(C=>!T(C)),R=[...k].reverse().find(C=>!T(C));if($&&!g.find(C=>C===$)){let C=g.findIndex(K=>K.role==="system"),M=C>=0?C+1:0;g.splice(M,0,$)}return R&&R!==$&&!g.find(C=>C===R)&&g.push(R),{messages:g,tokensRemoved:i-fn(g)}}_y.exports={estimateTokens:Zs,estimateMessageTokens:ws,estimateMessagesTokens:fn,estimateDeltaTokens:MT,estimateToolsTokens:Ya,serializeMessage:PT,getContextWindow:za,getUsage:NT,compressMessage:Ho,compressToolResult:yy,scoreMessageRelevance:by,extractActiveFiles:wy,buildProgressSnapshot:jT,fitToContext:qT,forceCompress:UT,truncateFileContent:FT,invalidateTokenRatioCache:OT,invalidateFitToContextCache:DT,getEffectiveCompressionThreshold:gy,COMPRESSION_THRESHOLD:Fr,TIER_COMPRESSION_THRESHOLDS:my,SAFETY_MARGIN:py,KEEP_RECENT:hy}});var Yo=ne((fN,$y)=>{var{fork:WT}=require("child_process"),HT=require("path"),GT=HT.join(__dirname,"background-worker.js"),Qs=new Map,Go=new Map;function YT(){return`bg-${Date.now()}-${Math.random().toString(36).slice(2,6)}`}function zT(t){let e=YT(),n=WT(GT,[],{silent:!0,env:process.env,cwd:process.cwd()});return n.send({jobId:e,agentDef:t}),n.on("message",o=>{o.type==="result"?Ju(e,t,o.payload):o.type==="error"&&Ju(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(Qs.has(e)){let r=s?`killed (${s})`:`exit code ${o}`;Ju(e,t,{task:t.task,status:"failed",result:`Background agent terminated unexpectedly: ${r}`,toolsUsed:[],tokensUsed:{input:0,output:0}})}}),Qs.set(e,{process:n,agentDef:t,startedAt:Date.now()}),e}function Ju(t,e,n){Qs.delete(t),Go.set(t,{jobId:t,agentDef:e,result:n,finishedAt:Date.now()})}function KT(){if(Go.size===0)return[];let t=[...Go.values()];return Go.clear(),t}function VT(){return Qs.size>0||Go.size>0}function XT(){let t=Qs.size;return t===0?"":`${t} bg agent${t===1?"":"s"} running`}function JT(){for(let[t,e]of Qs){try{e.process.kill("SIGTERM")}catch{}Qs.delete(t)}Go.clear()}$y.exports={createJob:zT,getCompletedJobs:KT,getPendingJobSummary:XT,hasPendingOrCompletedJobs:VT,cancelAllJobs:JT}});var td=ne((hN,Uy)=>{var{callStream:ZT,getActiveProviderName:Va,getActiveModelId:ky,getConfiguredProviders:QT,getProvider:xy,getActiveProvider:vy,parseModelSpec:Sy}=vt(),{parseToolArgs:Ey}=kr(),{filterToolsForModel:eR,getModelTier:Ka}=Nr(),{getModelBriefing:tR}=Ga(),{trackUsage:Ty,estimateTokens:Ry}=ma(),{MultiProgress:nR,C:pN}=xt();function Cy(t){return!t||typeof t!="string"?0:typeof Ry=="function"?Ry(t):Math.ceil(t.length/4)}var Py=15,sR=parseInt(process.env.NEX_MAX_PARALLEL||"10",10),Ay=parseInt(process.env.NEX_MAX_CHAT_RETRIES||"3",10),My=8,oR=2,Xa=new Map,Ny=600*1e3;function rR(t,e){let n=Xa.get(t);return n&&n.agentId!==e&&Date.now()-n.timestamp<Ny?!1:(Xa.set(t,{agentId:e,timestamp:Date.now()}),!0)}function Br(t){Xa.delete(t)}function Zu(){Xa.clear()}function Qu(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 Ly(t){let e=Qu(t);return e==="rate_limit"||e==="server"||e==="network"||e==="timeout"}async function Iy(t,e,n){let o;for(let s=0;s<=Ay;s++)try{return await ZT(t,e,n)}catch(r){o=r;let i=Qu(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<Ay&&Ly(r)){let l=i==="rate_limit"?Math.min(2e3*Math.pow(2,s),15e3):Math.min(500*Math.pow(2,s),4e3);await new Promise(c=>setTimeout(c,l).unref());continue}throw r}throw o}var Oy=new Set(["ask_user","task_list"]);function jy(t){return t>=2?new Set([...Oy,"spawn_agents"]):Oy}var iR=new Set(["write_file","edit_file","patch_file"]),Dy={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:""}},aR=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,lR=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function qy(t){return lR.test(t)?"full":aR.test(t)?"essential":t.length>300?"full":"standard"}function Fy(t){let e=QT(),n=Va(),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(Ka(r.id,s.name)===t)return{provider:s.name,model:r.id};return null}var cR={essential:process.env.NEX_FAST_MODEL||null,standard:process.env.NEX_STANDARD_MODEL||null,full:process.env.NEX_HEAVY_MODEL||null};function Ja(t){if(t.model){let{provider:s,model:r}=Sy(t.model),i=s?xy(s):vy(),a=s||Va();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let l=Ka(r,a);return{provider:a,model:r,tier:l}}}let e=qy(t.task),n=cR[e];if(n){let{provider:s,model:r}=Sy(n),i=s?xy(s):vy(),a=s||Va();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let l=Ka(r,a);return{provider:a,model:r,tier:l}}}let o=Fy(e);if(o){let s=Ka(o.model,o.provider);return{provider:o.provider,model:o.model,tier:s}}return{provider:null,model:null,tier:null}}async function By(t,e={},n=0){let o=n===0?Py:My,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},l=new Set,c=new Map,u=t._systemPrompt||`You are a focused sub-agent. Complete this specific task efficiently.
364
364
 
365
365
  TASK: ${t.task}
366
366
  ${t.context?`
@@ -394,30 +394,30 @@ ${k}
394
394
  ---
395
395
 
396
396
  `:"")+u+f}];$.push({role:"user",content:t.task});let{TOOL_DEFINITIONS:R,executeTool:C}=Do(),M=jy(n),K=eR(R.filter(ae=>!M.has(ae.function.name)),w);if(d&&d.allowedTools&&(K=K.filter(ae=>d.allowedTools.has(ae.function.name))),g&&!t._skipLog){let ae=w?` (${w})`:"";process.stderr.write(` [sub-agent: ${h}:${g}${ae}]
397
- `)}let z={};h&&(z.provider=h),g&&(z.model=g);let X=new Set;try{for(let Z=0;Z<o;Z++){let oe=await Iy($,K,z);if(!oe||typeof oe!="object")throw new Error("Empty or invalid response from provider");{let Ae=h||Va(),Oe=g||ky();if(oe.usage){let E=oe.usage.prompt_tokens||0,_=oe.usage.completion_tokens||0;a.input+=E,a.output+=_,Ty(Ae,Oe,E,_)}else{let E=oe.content||"",_=$.map(ee=>typeof ee.content=="string"?ee.content:Array.isArray(ee.content)?ee.content.map(P=>typeof P=="string"?P:P.text||"").join(""):"").join(" "),H=Cy(_),se=Cy(E);a.input+=H,a.output+=se,a._estimated=!0,Ty(Ae,Oe,H,se)}}let Ke=oe.content||"",Ee=oe.tool_calls,G={role:"assistant",content:Ke||""};if(Ee&&Ee.length>0&&(G.tool_calls=Ee),$.push(G),!Ee||Ee.length===0){for(let Ae of l)Br(Ae);return{task:t.task,status:"done",result:Ke||"(no response)",toolsUsed:i,tokensUsed:a,modelSpec:h&&g?`${h}:${g}`:null}}let re=new Set,et=Ee.map(Ae=>{let Oe=Ae.function.name,E=Ey(Ae.function.arguments),_=Ae.id||`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!E)return Promise.resolve({role:"tool",content:`ERROR: Malformed tool arguments for ${Oe}`,tool_call_id:_});if(["edit_file","patch_file"].includes(Oe)&&E.path){if(X.has(E.path)||re.has(E.path))return Promise.resolve({role:"tool",content:`BLOCKED: "${E.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:_});re.add(E.path)}let H=null;if(iR.has(Oe)&&E.path){let ee=require("path"),P=ee.isAbsolute(E.path)?E.path:ee.resolve(process.cwd(),E.path);if(t._readOnlyFiles&&t._readOnlyFiles.length>0){let he=ee.relative(process.cwd(),P);if(t._readOnlyFiles.some($e=>he===$e||he.startsWith($e+"/")||P===$e||P.startsWith($e+"/")))return Promise.resolve({role:"tool",content:`ERROR: File '${E.path}' is owned by another agent and is READ ONLY. Write to your own scope files instead.`,tool_call_id:_})}if(l.has(P)||!rR(P,r))return Promise.resolve({role:"tool",content:`ERROR: File '${E.path}' is locked by another operation. Try a different approach or skip this file.`,tool_call_id:_});l.add(P),H=P}return i.push(Oe),e.onUpdate&&e.onUpdate({type:"tool_call",tool:Oe,agentId:r}),(Oe==="spawn_agents"?ed(E,n+1):C(Oe,E,{autoConfirm:!0,silent:!0})).then(ee=>{H&&(Br(H),l.delete(H));let P=String(ee??"");return E&&E.path&&(["edit_file","patch_file","write_file"].includes(Oe)&&P.startsWith("Edited:")?X.add(E.path):Oe==="read_file"&&!P.startsWith("ERROR")&&X.delete(E.path)),{role:"tool",content:P.length>2e4?P.substring(0,2e4)+`
398
- ...(truncated)`:P,tool_call_id:_}}).catch(ee=>(H&&(Br(H),l.delete(H)),{role:"tool",content:`ERROR: ${ee.message}`,tool_call_id:_}))}),Ve=await Promise.all(et);if($.push(...Ve),Z>=7&&$.length>12)try{let{compressMessage:Ae}=Fn(),Oe=$.length-6;for(let E=1;E<Oe;E++)$[E]._subAgentCompressed||($[E]={...Ae($[E],"light"),_subAgentCompressed:!0})}catch{}for(let Ae=0;Ae<Ee.length;Ae++){let Oe=Ee[Ae];if(Oe.function.name==="bash_exec"){let E=Ey(Oe.function.arguments);if((Ve[Ae]?.content||"").startsWith("ERROR")&&E&&E.command){let H=E.command.replace(/\s+/g," ").trim().slice(0,100);c.set(H,(c.get(H)||0)+1)}}}e.onUpdate&&e.onUpdate(`step ${Z+1}/${o}`)}for(let Z of l)Br(Z);let ae=[...c.entries()].filter(([,Z])=>Z>=3).sort((Z,oe)=>oe[1]-Z[1]).slice(0,3).map(([Z,oe])=>`"${Z}" (failed ${oe}\xD7)`);return{task:t.task,status:"truncated",abortReason:"iteration_limit",repeatedFailures:ae,result:$[$.length-1]?.content||"(max iterations reached)",toolsUsed:i,tokensUsed:a,modelSpec:h&&g?`${h}:${g}`:null}}catch(ae){for(let Z of l)Br(Z);return{task:t.task,status:"failed",result:`Error: ${ae.message}`,toolsUsed:i,tokensUsed:a,modelSpec:h&&g?`${h}:${g}`:null}}}async function ed(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?sR:oR,s=e===0?Py:My,o=(t.agents||[]).slice(0,n);if(o.length===0)return"ERROR: No agents specified";let r=e>0?" \u21B3 ":"",i=e>0?38:44,a=o.map(u=>Ja(u)),l=o.map((u,d)=>{let f=a[d],p=f.model?` [${f.model}]`:"",h=u.task.substring(0,i-p.length);return`${r}Agent ${d+1}${p}: ${h}${u.task.length>h.length?"...":""}`}),c=new nR(l);c.start();try{let u=o.map((g,w)=>{let k=a[w],T=Math.min(g.max_iterations||s,s),$=k.model?{...g,model:`${k.provider}:${k.model}`,_skipLog:!0,max_iterations:T}:{...g,_skipLog:!0,max_iterations:T};return By($,{onUpdate:()=>{}},e).then(R=>(c.update(w,R.status==="failed"?"error":"done"),R)).catch(R=>(c.update(w,"error"),{task:g.task,status:"failed",result:`Error: ${R.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}))}),d=await Promise.all(u);c.stop(),Zu();let f=["Sub-agent results:",""],p=0,h=0;for(let g=0;g<d.length;g++){let w=d[g],k=w.status==="done"?"\u2713":w.status==="truncated"?"\u26A0":"\u2717",T=w.modelSpec?` [${w.modelSpec}]`:"";f.push(`${k} Agent ${g+1}${T}: ${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(`
399
- `)}catch(u){return c.stop(),Zu(),`ERROR: Sub-agent execution failed: ${u.message}`}}async function uR(t){let{createJob:e}=Yo(),n=(t.agents||[]).filter(i=>i.background),s=(t.agents||[]).filter(i=>!i.background),o=n.map(i=>{let a=Ja(i),l=a.model?{...i,model:`${a.provider}:${a.model}`,_skipLog:!0}:{...i,_skipLog:!0};return e(l)}),r=[];if(o.length>0&&r.push(`Background agents started: [${o.join(", ")}]
400
- `+n.map((i,a)=>` ${o[a]}: ${i.task}`).join(`
397
+ `)}let z={};h&&(z.provider=h),g&&(z.model=g);let X=new Set;try{for(let Z=0;Z<s;Z++){let oe=await Iy($,K,z);if(!oe||typeof oe!="object")throw new Error("Empty or invalid response from provider");{let Ae=h||Va(),Oe=g||ky();if(oe.usage){let E=oe.usage.prompt_tokens||0,_=oe.usage.completion_tokens||0;a.input+=E,a.output+=_,Ty(Ae,Oe,E,_)}else{let E=oe.content||"",_=$.map(ee=>typeof ee.content=="string"?ee.content:Array.isArray(ee.content)?ee.content.map(P=>typeof P=="string"?P:P.text||"").join(""):"").join(" "),H=Cy(_),se=Cy(E);a.input+=H,a.output+=se,a._estimated=!0,Ty(Ae,Oe,H,se)}}let Ke=oe.content||"",Ee=oe.tool_calls,G={role:"assistant",content:Ke||""};if(Ee&&Ee.length>0&&(G.tool_calls=Ee),$.push(G),!Ee||Ee.length===0){for(let Ae of l)Br(Ae);return{task:t.task,status:"done",result:Ke||"(no response)",toolsUsed:i,tokensUsed:a,modelSpec:h&&g?`${h}:${g}`:null}}let re=new Set,et=Ee.map(Ae=>{let Oe=Ae.function.name,E=Ey(Ae.function.arguments),_=Ae.id||`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!E)return Promise.resolve({role:"tool",content:`ERROR: Malformed tool arguments for ${Oe}`,tool_call_id:_});if(["edit_file","patch_file"].includes(Oe)&&E.path){if(X.has(E.path)||re.has(E.path))return Promise.resolve({role:"tool",content:`BLOCKED: "${E.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:_});re.add(E.path)}let H=null;if(iR.has(Oe)&&E.path){let ee=require("path"),P=ee.isAbsolute(E.path)?E.path:ee.resolve(process.cwd(),E.path);if(t._readOnlyFiles&&t._readOnlyFiles.length>0){let he=ee.relative(process.cwd(),P);if(t._readOnlyFiles.some($e=>he===$e||he.startsWith($e+"/")||P===$e||P.startsWith($e+"/")))return Promise.resolve({role:"tool",content:`ERROR: File '${E.path}' is owned by another agent and is READ ONLY. Write to your own scope files instead.`,tool_call_id:_})}if(l.has(P)||!rR(P,r))return Promise.resolve({role:"tool",content:`ERROR: File '${E.path}' is locked by another operation. Try a different approach or skip this file.`,tool_call_id:_});l.add(P),H=P}return i.push(Oe),e.onUpdate&&e.onUpdate({type:"tool_call",tool:Oe,agentId:r}),(Oe==="spawn_agents"?ed(E,n+1):C(Oe,E,{autoConfirm:!0,silent:!0})).then(ee=>{H&&(Br(H),l.delete(H));let P=String(ee??"");return E&&E.path&&(["edit_file","patch_file","write_file"].includes(Oe)&&P.startsWith("Edited:")?X.add(E.path):Oe==="read_file"&&!P.startsWith("ERROR")&&X.delete(E.path)),{role:"tool",content:P.length>2e4?P.substring(0,2e4)+`
398
+ ...(truncated)`:P,tool_call_id:_}}).catch(ee=>(H&&(Br(H),l.delete(H)),{role:"tool",content:`ERROR: ${ee.message}`,tool_call_id:_}))}),Ve=await Promise.all(et);if($.push(...Ve),Z>=7&&$.length>12)try{let{compressMessage:Ae}=Fn(),Oe=$.length-6;for(let E=1;E<Oe;E++)$[E]._subAgentCompressed||($[E]={...Ae($[E],"light"),_subAgentCompressed:!0})}catch{}for(let Ae=0;Ae<Ee.length;Ae++){let Oe=Ee[Ae];if(Oe.function.name==="bash_exec"){let E=Ey(Oe.function.arguments);if((Ve[Ae]?.content||"").startsWith("ERROR")&&E&&E.command){let H=E.command.replace(/\s+/g," ").trim().slice(0,100);c.set(H,(c.get(H)||0)+1)}}}e.onUpdate&&e.onUpdate(`step ${Z+1}/${s}`)}for(let Z of l)Br(Z);let ae=[...c.entries()].filter(([,Z])=>Z>=3).sort((Z,oe)=>oe[1]-Z[1]).slice(0,3).map(([Z,oe])=>`"${Z}" (failed ${oe}\xD7)`);return{task:t.task,status:"truncated",abortReason:"iteration_limit",repeatedFailures:ae,result:$[$.length-1]?.content||"(max iterations reached)",toolsUsed:i,tokensUsed:a,modelSpec:h&&g?`${h}:${g}`:null}}catch(ae){for(let Z of l)Br(Z);return{task:t.task,status:"failed",result:`Error: ${ae.message}`,toolsUsed:i,tokensUsed:a,modelSpec:h&&g?`${h}:${g}`:null}}}async function ed(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?sR:oR,o=e===0?Py:My,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(u=>Ja(u)),l=s.map((u,d)=>{let f=a[d],p=f.model?` [${f.model}]`:"",h=u.task.substring(0,i-p.length);return`${r}Agent ${d+1}${p}: ${h}${u.task.length>h.length?"...":""}`}),c=new nR(l);c.start();try{let u=s.map((g,w)=>{let k=a[w],T=Math.min(g.max_iterations||o,o),$=k.model?{...g,model:`${k.provider}:${k.model}`,_skipLog:!0,max_iterations:T}:{...g,_skipLog:!0,max_iterations:T};return By($,{onUpdate:()=>{}},e).then(R=>(c.update(w,R.status==="failed"?"error":"done"),R)).catch(R=>(c.update(w,"error"),{task:g.task,status:"failed",result:`Error: ${R.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}))}),d=await Promise.all(u);c.stop(),Zu();let f=["Sub-agent results:",""],p=0,h=0;for(let g=0;g<d.length;g++){let w=d[g],k=w.status==="done"?"\u2713":w.status==="truncated"?"\u26A0":"\u2717",T=w.modelSpec?` [${w.modelSpec}]`:"";f.push(`${k} Agent ${g+1}${T}: ${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(`
399
+ `)}catch(u){return c.stop(),Zu(),`ERROR: Sub-agent execution failed: ${u.message}`}}async function uR(t){let{createJob:e}=Yo(),n=(t.agents||[]).filter(i=>i.background),o=(t.agents||[]).filter(i=>!i.background),s=n.map(i=>{let a=Ja(i),l=a.model?{...i,model:`${a.provider}:${a.model}`,_skipLog:!0}:{...i,_skipLog:!0};return e(l)}),r=[];if(s.length>0&&r.push(`Background agents started: [${s.join(", ")}]
400
+ `+n.map((i,a)=>` ${s[a]}: ${i.task}`).join(`
401
401
  `)+`
402
- Results will be injected into the conversation when each agent completes.`),s.length>0){let i=await ed({agents:s});r.push(i)}return r.join(`
402
+ Results will be injected into the conversation when each agent completes.`),o.length>0){let i=await ed({agents:o});r.push(i)}return r.join(`
403
403
 
404
- `)||"No agents specified."}Uy.exports={runSubAgent:By,executeSpawnAgents:ed,executeSpawnAgentsBackground:uR,clearAllLocks:Zu,classifyTask:qy,pickModelForTier:Fy,resolveSubAgentModel:Ja,classifyError:Qu,isRetryableError:Ly,callWithRetry:Iy,getExcludedTools:jy,LOCK_TIMEOUT_MS:Ny,SUB_AGENT_TYPES:Dy}});var cd=ne((mN,nb)=>{var yt=require("fs"),rs=require("path"),{atomicWrite:Wy,withFileLockSync:Hy}=Ws(),dR=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 Ko(){let t=rs.join(process.cwd(),".nex","brain");return yt.existsSync(t)||yt.mkdirSync(t,{recursive:!0}),t}function Qa(){return rs.join(Ko(),".brain-index.json")}function od(){return rs.join(Ko(),".embeddings.json")}function Ur(){let t=rs.join(process.cwd(),".nex","brain");if(!yt.existsSync(t))return[];try{return yt.readdirSync(t).filter(e=>e.endsWith(".md")&&!e.startsWith(".")).map(e=>{let n=rs.join(t,e),s=yt.statSync(n);return{name:e.replace(/\.md$/,""),path:n,size:s.size,modified:new Date(s.mtimeMs)}}).sort((e,n)=>n.modified-e.modified)}catch{return[]}}function Wr(t){let e={},n=t,s=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(s){let o=s[1].split(`
405
- `);for(let r of o){let i=r.match(/^(\w+):\s*(.+)$/);if(!i)continue;let a=i[1].trim(),l=i[2].trim();l.startsWith("[")&&l.endsWith("]")?e[a]=l.slice(1,-1).split(",").map(c=>c.trim()).filter(Boolean):e[a]=l}n=s[2]}return{frontmatter:e,body:n}}function Gy(t){let e=rs.join(Ko(),`${t}.md`);if(!yt.existsSync(e))return{name:t,content:"",body:"",frontmatter:{}};let n=yt.readFileSync(e,"utf-8"),{frontmatter:s,body:o}=Wr(n);return{name:t,content:n,body:o,frontmatter:s}}function fR(t,e){let n=rs.join(Ko(),`${t}.md`);Wy(n,e),mR(t,e),pR()}function pR(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return;let t=od();yt.existsSync(t)&&setImmediate(async()=>{try{await Zy()}catch{}})}function hR(t){let e=rs.join(Ko(),`${t}.md`);return yt.existsSync(e)?(yt.unlinkSync(e),gR(t),!0):!1}function Za(t){return t.toLowerCase().replace(/[^a-z0-9äöüß\s-]/g," ").split(/[\s-]+/).filter(e=>e.length>2&&!dR.has(e))}function rd(t){let e={},{frontmatter:n,body:s}=Wr(t),o=Array.isArray(n.tags)?n.tags:[];for(let i of o){let a=i.toLowerCase().replace(/[^a-z0-9-]/g,"");a.length>1&&(e[a]=(e[a]||0)+5)}let r=(s||t).split(`
406
- `);for(let i of r)if(i.startsWith("#")){let a=i.replace(/^#+\s*/,"");for(let l of Za(a))e[l]=(e[l]||0)+3}for(let i of Za(s||t))e[i]=(e[i]||0)+1;return e}function id(){let t=Qa();if(!yt.existsSync(t))return{documents:{}};try{return JSON.parse(yt.readFileSync(t,"utf-8"))}catch{return{documents:{}}}}function ad(t){Wy(Qa(),JSON.stringify(t,null,2))}function mR(t,e){Hy(Qa(),()=>{let n=id(),{frontmatter:s}=Wr(e),o=Array.isArray(s.tags)?s.tags:[];n.documents[t]={keywords:rd(e),tags:o,modified:new Date().toISOString()},ad(n)})}function gR(t){Hy(Qa(),()=>{let e=id();delete e.documents[t],ad(e)})}function sd(){let t=Ur(),e={documents:{}};for(let n of t){let s=yt.readFileSync(n.path,"utf-8"),{frontmatter:o}=Wr(s),r=Array.isArray(o.tags)?o.tags:[];e.documents[n.name]={keywords:rd(s),tags:r,modified:n.modified.toISOString()}}return ad(e),e}function Yy(){let t=id(),e=Ur();for(let n of e){let s=t.documents[n.name];if(!s||new Date(s.modified)<n.modified)return sd()}for(let n of Object.keys(t.documents))if(!e.some(s=>s.name===n))return sd();return t}function zy(t,e={}){let{topK:n=3,minScore:s=.1}=e,o=Za(t);if(o.length===0)return[];let r=Yy(),i=[];for(let[a,l]of Object.entries(r.documents)){let c=0;for(let u of o){l.keywords[u]&&(c+=l.keywords[u]);for(let[d,f]of Object.entries(l.keywords))d!==u&&d.length>3&&u.length>3&&(d.includes(u)||u.includes(d))&&(c+=f*.3)}c>=s&&i.push({name:a,score:c})}return i.sort((a,l)=>l.score-a.score),i.slice(0,n)}var Ky=process.env.NEX_EMBED_MODEL||"nomic-embed-text",nd=400,yR=50;async function Vy(){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"),s=new URL(`${t}/api/tags`),o=s.protocol==="https:"?n:e;return((await new Promise((a,l)=>{let c=o.get(s.toString(),{timeout:2e3},u=>{let d="";u.on("data",f=>d+=f),u.on("end",()=>{try{a(JSON.parse(d))}catch{l(new Error("bad json"))}})});c.on("error",l),c.on("timeout",()=>{c.destroy(),l(new Error("timeout"))})})).models||[]).map(a=>a.name).some(a=>a.startsWith(Ky.split(":")[0]))}catch{return!1}}async function ld(t){let e=process.env.OLLAMA_HOST||"http://localhost:11434",n=require("http"),s=require("https"),o=new URL(`${e}/api/embeddings`),r=o.protocol==="https:"?s:n,i=JSON.stringify({model:Ky,prompt:t});return new Promise((a,l)=>{let c=r.request(o,{method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(i)},timeout:3e4},u=>{let d="";u.on("data",f=>d+=f),u.on("end",()=>{try{a(JSON.parse(d).embedding||[])}catch(f){l(f)}})});c.on("error",l),c.on("timeout",()=>{c.destroy(),l(new Error("embedding timeout"))}),c.write(i),c.end()})}function Xy(t,e){if(!t||!e||t.length!==e.length)return 0;let n=0,s=0,o=0;for(let i=0;i<t.length;i++)n+=t[i]*e[i],s+=t[i]*t[i],o+=e[i]*e[i];let r=Math.sqrt(s)*Math.sqrt(o);return r===0?0:n/r}function Jy(t){let e=t.split(/\s+/),n=[],s=0;for(;s<e.length;){let o=e.slice(s,s+nd).join(" ");if(n.push({text:o,offset:s}),s+nd>=e.length)break;s+=nd-yR}return n}async function Zy(){let t=Ur(),e={documents:{}},n=od();if(yt.existsSync(n))try{e=JSON.parse(yt.readFileSync(n,"utf-8"))}catch{}for(let s of t){let o=e.documents[s.name];if(o&&new Date(o.modified)>=s.modified)continue;let r=yt.readFileSync(s.path,"utf-8"),i=Jy(r),a=[];for(let l of i){let c=await ld(l.text);a.push({text:l.text,embedding:c,offset:l.offset})}e.documents[s.name]={chunks:a,modified:s.modified.toISOString()}}for(let s of Object.keys(e.documents))t.some(o=>o.name===s)||delete e.documents[s];return yt.writeFileSync(n,JSON.stringify(e),"utf-8"),e}async function Qy(t,e={}){let{topK:n=3,minSimilarity:s=.3}=e,o=od();if(!yt.existsSync(o))return[];let r;try{r=JSON.parse(yt.readFileSync(o,"utf-8"))}catch{return[]}let i=await ld(t),a=[];for(let[l,c]of Object.entries(r.documents||{})){let u=0,d="";for(let f of c.chunks||[]){let p=Xy(i,f.embedding);p>u&&(u=p,d=f.text)}u>=s&&a.push({name:l,score:u,bestChunk:d})}return a.sort((l,c)=>c.score-l.score),a.slice(0,n)}function eb(t,e,n={}){let{k:s=60,topK:o=3}=n,r={};return t.forEach((i,a)=>{r[i.name]=(r[i.name]||0)+1/(s+a+1)}),e.forEach((i,a)=>{r[i.name]=(r[i.name]||0)+1/(s+a+1)}),Object.entries(r).map(([i,a])=>({name:i,score:a})).sort((i,a)=>a.score-i.score).slice(0,o)}async function tb(t,e={}){let{topK:n=3,minScore:s=.1}=e,o=zy(t,{topK:n,minScore:s}),r=o;if(process.env.NEX_BRAIN_EMBEDDINGS!=="false")try{if(await Vy()){let a=await Qy(t,{topK:n});r=eb(o,a,{topK:n})}}catch{}return r.map(i=>{let a=Gy(i.name),l=(a.body||a.content||"").slice(0,300).replace(/\n+/g," ")+"...";return{name:i.name,score:i.score,content:a.content,excerpt:l}})}var zo={queryKey:null,result:null,ts:0},bR=3e5;async function wR(t){if(!t||!t.trim())return"";let e=rs.join(process.cwd(),".nex","brain");if(!yt.existsSync(e)||Ur().length===0)return"";let s=t.trim().toLowerCase().slice(0,200);if(zo.result!==null&&zo.queryKey===s&&Date.now()-zo.ts<bR)return zo.result;let o;try{o=await tb(t,{topK:3})}catch{return""}if(!o||o.length===0)return"";let r;try{r=Fn().estimateTokens}catch{r=u=>Math.ceil(u.length/4)}let i=25e3,a=[],l=0;for(let u of o){let d=u.content||"",f=r(d);if(l+f>i){let h=i-l;if(h<100)break;let g=h/f;d=d.slice(0,Math.floor(d.length*g))+`
404
+ `)||"No agents specified."}Uy.exports={runSubAgent:By,executeSpawnAgents:ed,executeSpawnAgentsBackground:uR,clearAllLocks:Zu,classifyTask:qy,pickModelForTier:Fy,resolveSubAgentModel:Ja,classifyError:Qu,isRetryableError:Ly,callWithRetry:Iy,getExcludedTools:jy,LOCK_TIMEOUT_MS:Ny,SUB_AGENT_TYPES:Dy}});var cd=ne((mN,nb)=>{var yt=require("fs"),rs=require("path"),{atomicWrite:Wy,withFileLockSync:Hy}=Ws(),dR=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 Ko(){let t=rs.join(process.cwd(),".nex","brain");return yt.existsSync(t)||yt.mkdirSync(t,{recursive:!0}),t}function Qa(){return rs.join(Ko(),".brain-index.json")}function od(){return rs.join(Ko(),".embeddings.json")}function Ur(){let t=rs.join(process.cwd(),".nex","brain");if(!yt.existsSync(t))return[];try{return yt.readdirSync(t).filter(e=>e.endsWith(".md")&&!e.startsWith(".")).map(e=>{let n=rs.join(t,e),o=yt.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 Wr(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(`
405
+ `);for(let r of s){let i=r.match(/^(\w+):\s*(.+)$/);if(!i)continue;let a=i[1].trim(),l=i[2].trim();l.startsWith("[")&&l.endsWith("]")?e[a]=l.slice(1,-1).split(",").map(c=>c.trim()).filter(Boolean):e[a]=l}n=o[2]}return{frontmatter:e,body:n}}function Gy(t){let e=rs.join(Ko(),`${t}.md`);if(!yt.existsSync(e))return{name:t,content:"",body:"",frontmatter:{}};let n=yt.readFileSync(e,"utf-8"),{frontmatter:o,body:s}=Wr(n);return{name:t,content:n,body:s,frontmatter:o}}function fR(t,e){let n=rs.join(Ko(),`${t}.md`);Wy(n,e),mR(t,e),pR()}function pR(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return;let t=od();yt.existsSync(t)&&setImmediate(async()=>{try{await Zy()}catch{}})}function hR(t){let e=rs.join(Ko(),`${t}.md`);return yt.existsSync(e)?(yt.unlinkSync(e),gR(t),!0):!1}function Za(t){return t.toLowerCase().replace(/[^a-z0-9äöüß\s-]/g," ").split(/[\s-]+/).filter(e=>e.length>2&&!dR.has(e))}function rd(t){let e={},{frontmatter:n,body:o}=Wr(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(`
406
+ `);for(let i of r)if(i.startsWith("#")){let a=i.replace(/^#+\s*/,"");for(let l of Za(a))e[l]=(e[l]||0)+3}for(let i of Za(o||t))e[i]=(e[i]||0)+1;return e}function id(){let t=Qa();if(!yt.existsSync(t))return{documents:{}};try{return JSON.parse(yt.readFileSync(t,"utf-8"))}catch{return{documents:{}}}}function ad(t){Wy(Qa(),JSON.stringify(t,null,2))}function mR(t,e){Hy(Qa(),()=>{let n=id(),{frontmatter:o}=Wr(e),s=Array.isArray(o.tags)?o.tags:[];n.documents[t]={keywords:rd(e),tags:s,modified:new Date().toISOString()},ad(n)})}function gR(t){Hy(Qa(),()=>{let e=id();delete e.documents[t],ad(e)})}function sd(){let t=Ur(),e={documents:{}};for(let n of t){let o=yt.readFileSync(n.path,"utf-8"),{frontmatter:s}=Wr(o),r=Array.isArray(s.tags)?s.tags:[];e.documents[n.name]={keywords:rd(o),tags:r,modified:n.modified.toISOString()}}return ad(e),e}function Yy(){let t=id(),e=Ur();for(let n of e){let o=t.documents[n.name];if(!o||new Date(o.modified)<n.modified)return sd()}for(let n of Object.keys(t.documents))if(!e.some(o=>o.name===n))return sd();return t}function zy(t,e={}){let{topK:n=3,minScore:o=.1}=e,s=Za(t);if(s.length===0)return[];let r=Yy(),i=[];for(let[a,l]of Object.entries(r.documents)){let c=0;for(let u of s){l.keywords[u]&&(c+=l.keywords[u]);for(let[d,f]of Object.entries(l.keywords))d!==u&&d.length>3&&u.length>3&&(d.includes(u)||u.includes(d))&&(c+=f*.3)}c>=o&&i.push({name:a,score:c})}return i.sort((a,l)=>l.score-a.score),i.slice(0,n)}var Ky=process.env.NEX_EMBED_MODEL||"nomic-embed-text",nd=400,yR=50;async function Vy(){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,l)=>{let c=s.get(o.toString(),{timeout:2e3},u=>{let d="";u.on("data",f=>d+=f),u.on("end",()=>{try{a(JSON.parse(d))}catch{l(new Error("bad json"))}})});c.on("error",l),c.on("timeout",()=>{c.destroy(),l(new Error("timeout"))})})).models||[]).map(a=>a.name).some(a=>a.startsWith(Ky.split(":")[0]))}catch{return!1}}async function ld(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:Ky,prompt:t});return new Promise((a,l)=>{let c=r.request(s,{method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(i)},timeout:3e4},u=>{let d="";u.on("data",f=>d+=f),u.on("end",()=>{try{a(JSON.parse(d).embedding||[])}catch(f){l(f)}})});c.on("error",l),c.on("timeout",()=>{c.destroy(),l(new Error("embedding timeout"))}),c.write(i),c.end()})}function Xy(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 Jy(t){let e=t.split(/\s+/),n=[],o=0;for(;o<e.length;){let s=e.slice(o,o+nd).join(" ");if(n.push({text:s,offset:o}),o+nd>=e.length)break;o+=nd-yR}return n}async function Zy(){let t=Ur(),e={documents:{}},n=od();if(yt.existsSync(n))try{e=JSON.parse(yt.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=yt.readFileSync(o.path,"utf-8"),i=Jy(r),a=[];for(let l of i){let c=await ld(l.text);a.push({text:l.text,embedding:c,offset:l.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 yt.writeFileSync(n,JSON.stringify(e),"utf-8"),e}async function Qy(t,e={}){let{topK:n=3,minSimilarity:o=.3}=e,s=od();if(!yt.existsSync(s))return[];let r;try{r=JSON.parse(yt.readFileSync(s,"utf-8"))}catch{return[]}let i=await ld(t),a=[];for(let[l,c]of Object.entries(r.documents||{})){let u=0,d="";for(let f of c.chunks||[]){let p=Xy(i,f.embedding);p>u&&(u=p,d=f.text)}u>=o&&a.push({name:l,score:u,bestChunk:d})}return a.sort((l,c)=>c.score-l.score),a.slice(0,n)}function eb(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 tb(t,e={}){let{topK:n=3,minScore:o=.1}=e,s=zy(t,{topK:n,minScore:o}),r=s;if(process.env.NEX_BRAIN_EMBEDDINGS!=="false")try{if(await Vy()){let a=await Qy(t,{topK:n});r=eb(s,a,{topK:n})}}catch{}return r.map(i=>{let a=Gy(i.name),l=(a.body||a.content||"").slice(0,300).replace(/\n+/g," ")+"...";return{name:i.name,score:i.score,content:a.content,excerpt:l}})}var zo={queryKey:null,result:null,ts:0},bR=3e5;async function wR(t){if(!t||!t.trim())return"";let e=rs.join(process.cwd(),".nex","brain");if(!yt.existsSync(e)||Ur().length===0)return"";let o=t.trim().toLowerCase().slice(0,200);if(zo.result!==null&&zo.queryKey===o&&Date.now()-zo.ts<bR)return zo.result;let s;try{s=await tb(t,{topK:3})}catch{return""}if(!s||s.length===0)return"";let r;try{r=Fn().estimateTokens}catch{r=u=>Math.ceil(u.length/4)}let i=25e3,a=[],l=0;for(let u of s){let d=u.content||"",f=r(d);if(l+f>i){let h=i-l;if(h<100)break;let g=h/f;d=d.slice(0,Math.floor(d.length*g))+`
407
407
  ...(truncated)`}let p=typeof u.score=="number"?u.score.toFixed(2):String(u.score);if(a.push(`--- ${u.name} (relevance: ${p}) ---
408
- ${d}`),l+=r(d),l>=i)break}if(a.length===0)return zo={queryKey:s,result:"",ts:Date.now()},"";let c=`KNOWLEDGE BASE (auto-selected):
408
+ ${d}`),l+=r(d),l>=i)break}if(a.length===0)return zo={queryKey:o,result:"",ts:Date.now()},"";let c=`KNOWLEDGE BASE (auto-selected):
409
409
 
410
410
  ${a.join(`
411
411
 
412
- `)}`;return zo={queryKey:s,result:c,ts:Date.now()},c}nb.exports={getBrainDir:Ko,listDocuments:Ur,readDocument:Gy,writeDocument:fR,removeDocument:hR,buildIndex:sd,getIndex:Yy,query:tb,getBrainContext:wR,isEmbeddingAvailable:Vy,generateEmbedding:ld,buildEmbeddingIndex:Zy,semanticQuery:Qy,cosineSimilarity:Xy,_keywordQuery:zy,_extractKeywords:rd,_chunkText:Jy,parseFrontmatter:Wr,tokenize:Za,_fuseResults:eb}});var Gr=ne((gN,yb)=>{var lt=require("fs"),Yt=require("path"),_R=require("os"),{atomicWrite:el,withFileLockSync:sb}=Ws(),eo=["user","feedback","project","reference"],$R=50;function to(){return Yt.join(process.cwd(),".nex","memory")}function Vo(){return Yt.join(to(),"memory.json")}function ob(){return Yt.join(to(),"MEMORY.md")}function kR(){return Yt.join(process.cwd(),"NEX.md")}function rb(){return Yt.join(_R.homedir(),".nex","NEX.md")}function tl(){let t=to();lt.existsSync(t)||lt.mkdirSync(t,{recursive:!0})}function ib(t){let e=Yt.join(to(),t);return lt.existsSync(e)||lt.mkdirSync(e,{recursive:!0}),e}function Hr(){let t=Vo();if(!lt.existsSync(t))return{};try{return JSON.parse(lt.readFileSync(t,"utf-8"))}catch{return{}}}function ab(t){tl(),el(Vo(),JSON.stringify(t,null,2))}function lb(){let t=Vo();if(!lt.existsSync(t))return;let e=Hr(),n=Object.keys(e);if(n.length===0){try{lt.renameSync(t,t+".bak")}catch{}return}for(let s of n){let o=e[s],r=o.value||String(o),i=s.replace(/[^a-z0-9_-]/gi,"-").toLowerCase().replace(/-+/g,"-").replace(/^-|-$/g,"");if(!i)continue;let a=ib("project"),l=Yt.join(a,`${i}.md`),c=r.split(`
412
+ `)}`;return zo={queryKey:o,result:c,ts:Date.now()},c}nb.exports={getBrainDir:Ko,listDocuments:Ur,readDocument:Gy,writeDocument:fR,removeDocument:hR,buildIndex:sd,getIndex:Yy,query:tb,getBrainContext:wR,isEmbeddingAvailable:Vy,generateEmbedding:ld,buildEmbeddingIndex:Zy,semanticQuery:Qy,cosineSimilarity:Xy,_keywordQuery:zy,_extractKeywords:rd,_chunkText:Jy,parseFrontmatter:Wr,tokenize:Za,_fuseResults:eb}});var Gr=ne((gN,yb)=>{var lt=require("fs"),Yt=require("path"),_R=require("os"),{atomicWrite:el,withFileLockSync:sb}=Ws(),eo=["user","feedback","project","reference"],$R=50;function to(){return Yt.join(process.cwd(),".nex","memory")}function Vo(){return Yt.join(to(),"memory.json")}function ob(){return Yt.join(to(),"MEMORY.md")}function kR(){return Yt.join(process.cwd(),"NEX.md")}function rb(){return Yt.join(_R.homedir(),".nex","NEX.md")}function tl(){let t=to();lt.existsSync(t)||lt.mkdirSync(t,{recursive:!0})}function ib(t){let e=Yt.join(to(),t);return lt.existsSync(e)||lt.mkdirSync(e,{recursive:!0}),e}function Hr(){let t=Vo();if(!lt.existsSync(t))return{};try{return JSON.parse(lt.readFileSync(t,"utf-8"))}catch{return{}}}function ab(t){tl(),el(Vo(),JSON.stringify(t,null,2))}function lb(){let t=Vo();if(!lt.existsSync(t))return;let e=Hr(),n=Object.keys(e);if(n.length===0){try{lt.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=ib("project"),l=Yt.join(a,`${i}.md`),c=r.split(`
413
413
  `)[0].slice(0,100),u=`---
414
- name: ${s}
414
+ name: ${o}
415
415
  description: ${c}
416
416
  type: project
417
417
  ---
418
418
 
419
419
  ${r}
420
- `;el(l,u)}nl();try{lt.renameSync(t,t+".bak")}catch{}}function xR(t,e,n,s){if(!eo.includes(t))return{ok:!1,path:"",error:`Invalid type: ${t}. Must be one of: ${eo.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 o=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase().replace(/-+/g,"-").replace(/^-|-$/g,"");if(!o)return{ok:!1,path:"",error:"name produces empty slug after sanitization"};let r=ib(t),i=Yt.join(r,`${o}.md`);if(lt.existsSync(i))try{if(dd(lt.readFileSync(i,"utf-8")).body.slice(0,200)===n.slice(0,200))return{ok:!0,path:i,updated:!1}}catch{}let a=s||n.split(`
420
+ `;el(l,u)}nl();try{lt.renameSync(t,t+".bak")}catch{}}function xR(t,e,n,o){if(!eo.includes(t))return{ok:!1,path:"",error:`Invalid type: ${t}. Must be one of: ${eo.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=ib(t),i=Yt.join(r,`${s}.md`);if(lt.existsSync(i))try{if(dd(lt.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(`
421
421
  `)[0].slice(0,100),l=`---
422
422
  name: ${e}
423
423
  description: ${a}
@@ -425,55 +425,55 @@ type: ${t}
425
425
  ---
426
426
 
427
427
  ${n}
428
- `;return el(i,l),nl(),{ok:!0,path:i,updated:!0}}function vR(t,e){if(!eo.includes(t))return!1;let n=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase(),s=Yt.join(to(),t,`${n}.md`);if(!lt.existsSync(s))return!1;try{return lt.unlinkSync(s),nl(),!0}catch{return!1}}function dd(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],s=(e[2]||"").trim(),o=r=>{let i=n.match(new RegExp(`^${r}:\\s*(.+)$`,"m"));return i?i[1].trim():""};return{name:o("name"),description:o("description"),type:o("type"),body:s}}function cb({includeBody:t=!1}={}){let e=[],n=to();for(let s of eo){let o=Yt.join(n,s);if(!lt.existsSync(o))continue;let r;try{r=lt.readdirSync(o).filter(i=>i.endsWith(".md"))}catch{continue}for(let i of r){let a=Yt.join(o,i);try{let l=lt.readFileSync(a,"utf-8"),c=dd(l),u=null;try{u=lt.statSync(a)}catch{u=null}let d={type:s,name:c.name||Yt.basename(i,".md"),description:c.description,filePath:a,updatedAt:u?u.mtimeMs:0};t&&(d.body=c.body),e.push(d)}catch{}}}return e}function ub(){return cb()}function db(t){return String(t||"").replace(/\s+/g," ").trim()}function SR(t,e){let n=db(t);return n.length<=e?n:n.slice(0,Math.max(0,e-15)).trimEnd()+" [truncated]"}function ud(t,e,n){return t.join(`
428
+ `;return el(i,l),nl(),{ok:!0,path:i,updated:!0}}function vR(t,e){if(!eo.includes(t))return!1;let n=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase(),o=Yt.join(to(),t,`${n}.md`);if(!lt.existsSync(o))return!1;try{return lt.unlinkSync(o),nl(),!0}catch{return!1}}function dd(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 cb({includeBody:t=!1}={}){let e=[],n=to();for(let o of eo){let s=Yt.join(n,o);if(!lt.existsSync(s))continue;let r;try{r=lt.readdirSync(s).filter(i=>i.endsWith(".md"))}catch{continue}for(let i of r){let a=Yt.join(s,i);try{let l=lt.readFileSync(a,"utf-8"),c=dd(l),u=null;try{u=lt.statSync(a)}catch{u=null}let d={type:o,name:c.name||Yt.basename(i,".md"),description:c.description,filePath:a,updatedAt:u?u.mtimeMs:0};t&&(d.body=c.body),e.push(d)}catch{}}}return e}function ub(){return cb()}function db(t){return String(t||"").replace(/\s+/g," ").trim()}function SR(t,e){let n=db(t);return n.length<=e?n:n.slice(0,Math.max(0,e-15)).trimEnd()+" [truncated]"}function ud(t,e,n){return t.join(`
429
429
  `).length+e.length+1>n?!1:(t.push(e),!0)}function fb(t){if(t<=200)return"";let e=pb(),n=cb({includeBody:!0});if(!e&&n.length===0){let r=hb();if(r.length===0)return"";let i=["PROJECT MEMORY:"];for(let a of r)if(!ud(i,` ${a.key}: ${a.value}`,t)){i.push("[Memory truncated - use delete_memory to prune old entries]");break}return i.join(`
430
- `)}let s=[];if(e){let r=Math.max(350,Math.floor(t*.45)),i=e.split(`
431
- `);for(let a of i)if(!ud(s,a,r)){s.push("[Memory index truncated - use delete_memory to prune old entries]");break}}let o=n.filter(r=>db(r.body).length>0).sort((r,i)=>{let a=eo.indexOf(r.type)-eo.indexOf(i.type);return a!==0?a:(i.updatedAt||0)-(r.updatedAt||0)});if(o.length>0&&s.join(`
432
- `).length<t-220){s.length>0&&s.push(""),s.push("ACTIVE MEMORY EXCERPTS:");for(let r of o){let i=t-s.join(`
433
- `).length-1;if(i<180)break;let a=Math.min(520,Math.max(120,i-90)),l=`${r.type}/${Yt.basename(r.filePath)}`,c=r.description?` - ${r.description}`:"",u=SR(r.body,a),d=`- ${r.name} (${l})${c}: ${u}`;if(!ud(s,d,t))break}}return s.length===0?"":s.join(`
434
- `)}function nl(){let t=ub(),e=["# Project Memory Index",""];for(let n of t){if(e.length>=$R+2)break;let s=`${n.type}/${Yt.basename(n.filePath)}`;e.push(`- [${n.name}](${s}) \u2014 ${n.description||"(no description)"}`)}tl(),el(ob(),e.join(`
430
+ `)}let o=[];if(e){let r=Math.max(350,Math.floor(t*.45)),i=e.split(`
431
+ `);for(let a of i)if(!ud(o,a,r)){o.push("[Memory index truncated - use delete_memory to prune old entries]");break}}let s=n.filter(r=>db(r.body).length>0).sort((r,i)=>{let a=eo.indexOf(r.type)-eo.indexOf(i.type);return a!==0?a:(i.updatedAt||0)-(r.updatedAt||0)});if(s.length>0&&o.join(`
432
+ `).length<t-220){o.length>0&&o.push(""),o.push("ACTIVE MEMORY EXCERPTS:");for(let r of s){let i=t-o.join(`
433
+ `).length-1;if(i<180)break;let a=Math.min(520,Math.max(120,i-90)),l=`${r.type}/${Yt.basename(r.filePath)}`,c=r.description?` - ${r.description}`:"",u=SR(r.body,a),d=`- ${r.name} (${l})${c}: ${u}`;if(!ud(o,d,t))break}}return o.length===0?"":o.join(`
434
+ `)}function nl(){let t=ub(),e=["# Project Memory Index",""];for(let n of t){if(e.length>=$R+2)break;let o=`${n.type}/${Yt.basename(n.filePath)}`;e.push(`- [${n.name}](${o}) \u2014 ${n.description||"(no description)"}`)}tl(),el(ob(),e.join(`
435
435
  `)+`
436
436
  `)}function pb(){let t=ob();if(!lt.existsSync(t))return"";try{return lt.readFileSync(t,"utf-8").trim()}catch{return""}}function ER(t,e){tl(),sb(Vo(),()=>{let n=Hr();n[t]={value:e,updatedAt:new Date().toISOString()},ab(n)})}function TR(t){let e=Hr();return e[t]?e[t].value:null}function RR(t){return tl(),sb(Vo(),()=>{let e=Hr();return t in e?(delete e[t],ab(e),!0):!1})}function hb(){let t=Hr();return Object.entries(t).map(([e,n])=>({key:e,value:n.value,updatedAt:n.updatedAt}))}function mb(){let t=rb();if(!lt.existsSync(t))return"";try{return lt.readFileSync(t,"utf-8").trim()}catch{return""}}function gb(){let t=kR();if(!lt.existsSync(t))return"";try{return lt.readFileSync(t,"utf-8").trim()}catch{return""}}function CR(){lb();let t=[],e=mb();e&&t.push(`GLOBAL INSTRUCTIONS (~/.nex/NEX.md):
437
437
  ${e}`);let n=gb();n&&t.push(`PROJECT INSTRUCTIONS (NEX.md):
438
- ${n}`);let s=t.join(`
438
+ ${n}`);let o=t.join(`
439
439
 
440
- `),o="You can save insights with save_memory(type, name, content) and remove them with delete_memory(type, name).",a=Math.max(1500,16e3-s.length-o.length-10),l=fb(a),c=[...t];return l&&c.push(l),c.length>0&&c.push(o),c.join(`
440
+ `),s="You can save insights with save_memory(type, name, content) and remove them with delete_memory(type, name).",a=Math.max(1500,16e3-o.length-s.length-10),l=fb(a),c=[...t];return l&&c.push(l),c.length>0&&c.push(s),c.join(`
441
441
 
442
442
  `)}yb.exports={saveMemory:xR,deleteMemory:vR,scanMemories:ub,rebuildIndex:nl,loadMemoryIndex:pb,remember:ER,recall:TR,forget:RR,listMemories:hb,loadGlobalInstructions:mb,loadProjectInstructions:gb,getMemoryContext:CR,_getMemoryDir:to,_getMemoryFile:Vo,_getGlobalNexMdPath:rb,_parseMemoryFile:dd,_buildMemoryPromptSection:fb,_migrateIfNeeded:lb,VALID_TYPES:eo}});var xb=ne((yN,kb)=>{var Yr=require("fs"),fd=require("path"),pd=process.env.NEX_AUDIT!=="false",no=null;function bb(){return no||(no=fd.join(process.cwd(),".nex","audit"),Yr.existsSync(no)||Yr.mkdirSync(no,{recursive:!0}),no)}function wb(){let t=new Date().toISOString().split("T")[0];return fd.join(bb(),`${t}.jsonl`)}function AR(t){if(pd)try{let e={timestamp:new Date().toISOString(),tool:t.tool,args:_b(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)+`
443
- `;Yr.appendFileSync(wb(),n,"utf-8")}catch{}}function _b(t){if(!t||typeof t!="object")return{};let e={};for(let[n,s]of Object.entries(t))/key|token|password|secret|credential/i.test(n)?e[n]="***":typeof s=="string"&&s.length>500?e[n]=s.substring(0,500)+`... (${s.length} chars)`:e[n]=s;return e}function $b(t={}){let e=bb(),n=t.days||1,s=[];for(let o=0;o<n;o++){let r=t.date||new Date(Date.now()-o*864e5).toISOString().split("T")[0],i=fd.join(e,`${r}.jsonl`);if(!Yr.existsSync(i))continue;let a=Yr.readFileSync(i,"utf-8").split(`
444
- `).filter(l=>l.trim());for(let l of a)try{let c=JSON.parse(l);if(t.tool&&c.tool!==t.tool)continue;s.push(c)}catch{}if(t.date)break}return s}function OR(t=1){let e=$b({days:t});if(e.length===0)return{totalCalls:0,byTool:{},avgDuration:0,successRate:1};let n={},s=0,o=0;for(let r of e)n[r.tool]=(n[r.tool]||0)+1,s+=r.duration||0,r.success&&o++;return{totalCalls:e.length,byTool:n,avgDuration:Math.round(s/e.length),successRate:o/e.length}}function PR(t){pd=t}function MR(){return pd}function NR(){no=null}kb.exports={logToolExecution:AR,sanitizeArgs:_b,readAuditLog:$b,getAuditSummary:OR,setAuditEnabled:PR,isAuditEnabled:MR,getAuditLogPath:wb,_reset:NR}});var Wb=ne((wN,Ub)=>{var bt=require("fs").promises,Sn=require("fs"),le=require("path"),gt=require("util").promisify(require("child_process").exec),so=require("util").promisify(require("child_process").execFile),{spawnSync:LR}=require("child_process"),hd=require("axios"),{isForbidden:IR,isSSHForbidden:jR,isDangerous:DR,isCritical:vb,isBashPathForbidden:qR,confirm:vn}=vr(),{showDiff:sl,showNewFile:FR,showEditDiff:bN,confirmFileChange:zr}=Ch(),{C:ye,Spinner:BR,getToolSpinnerText:UR}=xt(),{ToolProgress:ol}=Ls(),{isGitRepo:md,getCurrentBranch:Sb,getStatus:WR,getDiff:HR}=$a(),{recordChange:rl}=Fh(),{fuzzyFindText:Eb,findMostSimilar:Zr}=um(),{runDiagnostics:Kr}=$m(),{findFileInIndex:GR,getFileIndex:Tb,searchContentIndex:YR,scorePathMatch:Rb,refreshIndex:zR,isIndexValid:KR}=In(),{resolveProfile:pn,sshExec:Bt,scpUpload:VR,scpDownload:Cb}=qo(),{resolveDeployConfig:XR,loadDeployConfigs:JR}=Um(),{getEditMode:Ab}=Nr(),ZR=/^(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/,QR=/^ssh\s/,e1=/^ssh(?:\s+-\S+)*\s+\S+@?\S+\s+["']?[^-]/,t1=new Set(["assert","buffer","child_process","cluster","crypto","dns","events","fs","http","https","module","net","os","path","perf_hooks","process","querystring","readline","stream","timers","tls","tty","url","util","vm","zlib"]);function Lb(t){let n=String(t||"").match(/\b(?:npm\s+(?:install|i|add)|yarn\s+add|pnpm\s+(?:add|install))\s+([^;&|]+)/i);return n&&n[1].split(/\s+/).map(o=>o.trim()).filter(o=>o&&!o.startsWith("-")&&!o.includes("=")&&o!=="."&&o!=="./").map(o=>o.replace(/^node:/,"").replace(/@[^/]+$/,"")).find(o=>t1.has(o))||null}async function Qt(t){return bt.access(t).then(()=>!0).catch(()=>!1)}var il=null,Ob=0,n1=12e4;function s1(){let t=Date.now();if(il&&t-Ob<n1)return il;let e=le.dirname(process.cwd());try{let n=Sn.readdirSync(e,{withFileTypes:!0}),s=le.basename(process.cwd()),o=n.filter(r=>r.isDirectory()&&r.name!==s&&!r.name.startsWith(".")).map(r=>r.name).sort();return il=o.length>0?o:null,Ob=t,il}catch{return null}}function gd(t){if(t&&le.resolve(t)!==process.cwd())return"";let e=s1();if(!e)return"";let n=le.dirname(process.cwd());return`
443
+ `;Yr.appendFileSync(wb(),n,"utf-8")}catch{}}function _b(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 $b(t={}){let e=bb(),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=fd.join(e,`${r}.jsonl`);if(!Yr.existsSync(i))continue;let a=Yr.readFileSync(i,"utf-8").split(`
444
+ `).filter(l=>l.trim());for(let l of a)try{let c=JSON.parse(l);if(t.tool&&c.tool!==t.tool)continue;o.push(c)}catch{}if(t.date)break}return o}function OR(t=1){let e=$b({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 PR(t){pd=t}function MR(){return pd}function NR(){no=null}kb.exports={logToolExecution:AR,sanitizeArgs:_b,readAuditLog:$b,getAuditSummary:OR,setAuditEnabled:PR,isAuditEnabled:MR,getAuditLogPath:wb,_reset:NR}});var Wb=ne((wN,Ub)=>{var bt=require("fs").promises,Sn=require("fs"),le=require("path"),gt=require("util").promisify(require("child_process").exec),so=require("util").promisify(require("child_process").execFile),{spawnSync:LR}=require("child_process"),hd=require("axios"),{isForbidden:IR,isSSHForbidden:jR,isDangerous:DR,isCritical:vb,isBashPathForbidden:qR,confirm:vn}=vr(),{showDiff:sl,showNewFile:FR,showEditDiff:bN,confirmFileChange:zr}=Ch(),{C:ye,Spinner:BR,getToolSpinnerText:UR}=xt(),{ToolProgress:ol}=Ls(),{isGitRepo:md,getCurrentBranch:Sb,getStatus:WR,getDiff:HR}=$a(),{recordChange:rl}=Fh(),{fuzzyFindText:Eb,findMostSimilar:Zr}=um(),{runDiagnostics:Kr}=$m(),{findFileInIndex:GR,getFileIndex:Tb,searchContentIndex:YR,scorePathMatch:Rb,refreshIndex:zR,isIndexValid:KR}=In(),{resolveProfile:pn,sshExec:Bt,scpUpload:VR,scpDownload:Cb}=qo(),{resolveDeployConfig:XR,loadDeployConfigs:JR}=Um(),{getEditMode:Ab}=Nr(),ZR=/^(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/,QR=/^ssh\s/,e1=/^ssh(?:\s+-\S+)*\s+\S+@?\S+\s+["']?[^-]/,t1=new Set(["assert","buffer","child_process","cluster","crypto","dns","events","fs","http","https","module","net","os","path","perf_hooks","process","querystring","readline","stream","timers","tls","tty","url","util","vm","zlib"]);function Lb(t){let n=String(t||"").match(/\b(?:npm\s+(?:install|i|add)|yarn\s+add|pnpm\s+(?:add|install))\s+([^;&|]+)/i);return n&&n[1].split(/\s+/).map(s=>s.trim()).filter(s=>s&&!s.startsWith("-")&&!s.includes("=")&&s!=="."&&s!=="./").map(s=>s.replace(/^node:/,"").replace(/@[^/]+$/,"")).find(s=>t1.has(s))||null}async function Qt(t){return bt.access(t).then(()=>!0).catch(()=>!1)}var il=null,Ob=0,n1=12e4;function s1(){let t=Date.now();if(il&&t-Ob<n1)return il;let e=le.dirname(process.cwd());try{let n=Sn.readdirSync(e,{withFileTypes:!0}),o=le.basename(process.cwd()),s=n.filter(r=>r.isDirectory()&&r.name!==o&&!r.name.startsWith(".")).map(r=>r.name).sort();return il=s.length>0?s:null,Ob=t,il}catch{return null}}function gd(t){if(t&&le.resolve(t)!==process.cwd())return"";let e=s1();if(!e)return"";let n=le.dirname(process.cwd());return`
445
445
  Hint: no matches in current project. Sibling directories in ${n}/:
446
446
  ${e.join(", ")}
447
- You can search there with: grep pattern --path ${n}/<dir>`}async function al(t){if(!t)return{fixedPath:null,message:""};let e=t.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),n=At(e);if(n&&await Qt(n))return{fixedPath:n,message:`(auto-fixed path: ${t} \u2192 ${e})`};let s=[".js",".ts",".jsx",".tsx",".mjs",".cjs",".json"],o=le.extname(t);if(!o)for(let i of s){let a=At(t+i);if(a&&await Qt(a))return{fixedPath:a,message:`(auto-fixed: added ${i} extension)`}}if(o){let i=t.replace(/\.[^.]+$/,"");for(let a of s){if(a===o)continue;let l=At(i+a);if(l&&await Qt(l))return{fixedPath:l,message:`(auto-fixed: ${o} \u2192 ${a})`}}}let r=le.basename(t);if(r&&r.length>2)try{let i=GR(r).map(a=>At(a));if(i.length===1)return{fixedPath:i[0],message:`(auto-fixed: found ${r} at ${le.relative(process.cwd(),i[0])})`};if(i.length>1&&i.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
447
+ You can search there with: grep pattern --path ${n}/<dir>`}async function al(t){if(!t)return{fixedPath:null,message:""};let e=t.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),n=At(e);if(n&&await Qt(n))return{fixedPath:n,message:`(auto-fixed path: ${t} \u2192 ${e})`};let o=[".js",".ts",".jsx",".tsx",".mjs",".cjs",".json"],s=le.extname(t);if(!s)for(let i of o){let a=At(t+i);if(a&&await Qt(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 l=At(i+a);if(l&&await Qt(l))return{fixedPath:l,message:`(auto-fixed: ${s} \u2192 ${a})`}}}let r=le.basename(t);if(r&&r.length>2)try{let i=GR(r).map(a=>At(a));if(i.length===1)return{fixedPath:i[0],message:`(auto-fixed: found ${r} at ${le.relative(process.cwd(),i[0])})`};if(i.length>1&&i.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
448
448
  ${i.map(l=>le.relative(process.cwd(),l)).map(l=>` - ${l}`).join(`
449
449
  `)}`}}catch{}if(r&&r.length>2)try{let i=r.toLowerCase(),{getFileIndex:a}=In(),l=a().filter(c=>le.basename(c).toLowerCase()===i).map(c=>At(c));if(l.length===1)return{fixedPath:l[0],message:`(auto-fixed: case-insensitive match \u2192 ${le.relative(process.cwd(),l[0])})`};if(l.length>1&&l.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
450
450
  ${l.map(u=>le.relative(process.cwd(),u)).map(u=>` - ${u}`).join(`
451
451
  `)}`}}catch{}try{let{smartSearch:i}=In(),a=i(t,{limit:5,minScore:15});if(a.length>0){let l=At(a[0].file);if(a[0].score>=200||a.length===1&&a[0].score>=50)return{fixedPath:l,message:`(auto-fixed: smart matched ${t} \u2192 ${le.relative(process.cwd(),l)})`};if(a.length>=2&&a[0].score>=80&&a[0].score>=a[1].score*1.5)return{fixedPath:l,message:`(auto-fixed: best match ${t} \u2192 ${le.relative(process.cwd(),l)})`};if(a.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
452
452
  ${a.map(u=>le.relative(process.cwd(),At(u.file))).map(u=>` - ${u}`).join(`
453
- `)}`}}}catch{}return{fixedPath:null,message:""}}function o1(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 Ib(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 s=n.split(/[\/\s,]+/).map(o=>o.trim()).filter(Boolean).filter(o=>o!=="."&&o!=="..").filter(o=>!/^\.[a-z0-9]+$/i.test(o)).filter(o=>o.length>=3);return s.length===0?null:(s.sort((o,r)=>r.length-o.length),s[0])}async function jb(t,e){let n=Ib(t);if(!n)return new Map;try{let s=await YR(n,void 0,e||process.cwd()),o=new Map;for(let r of s){let a=r.name.toLowerCase()===n.toLowerCase()?140:90;o.set(r.file,(o.get(r.file)||0)+a)}return o}catch{return new Map}}function Pb(t,e){if(!t)return"";let n=e||process.cwd(),s=le.isAbsolute(t)?t:le.resolve(n,t),o=le.relative(n,s);return o&&!o.startsWith("..")&&!le.isAbsolute(o)?o:le.relative(process.cwd(),s)}function Vr(t,e){let n=(t||"").trim();return n?e==="files_with_matches"||e==="count"?n.split(`
454
- `).filter(s=>s.trim()):n.split(`
455
- `).filter(s=>s.trim()):[]}function Db(t,{query:e,basePath:n,definitionScores:s=new Map,mtimeByPath:o=new Map}={}){let r=Ib(e);return[...t].sort((i,a)=>{let l=Pb(i,n),c=Pb(a,n),u=0,d=0;if(r&&(u+=Rb(l,r),d+=Rb(c,r)),u+=s.get(l)||0,d+=s.get(c)||0,u!==d)return d-u;let f=o.get(i)||0,p=o.get(a)||0;return f!==p?p-f:l.localeCompare(c)})}async function yd(t,{query:e,basePath:n,outputMode:s}={}){if(!Array.isArray(t)||t.length<=1)return t;let o=new Map,r=[];for(let c of t){if(!c)continue;let u=c;(s==="count"||s!=="files_with_matches")&&(u=c.split(":")[0]),o.has(u)||(o.set(u,[]),r.push(u)),o.get(u).push(c)}let i=await jb(e,n),a=Db(r,{query:e,basePath:n,definitionScores:i}),l=[];for(let c of a)l.push(...o.get(c)||[]);return l}function qb(t,e){let n=[];if(/command not found|: not found|not recognized/i.test(t)){let s=e.match(/^(\S+)/),o=s?s[1]:"";/^(npx|npm|node|yarn|pnpm|bun)$/.test(o)?n.push("HINT: Node.js/npm may not be in PATH. Check your Node.js installation."):/^(python|python3|pip|pip3)$/.test(o)?n.push("HINT: Python may not be installed. Try: brew install python3 (macOS) or apt install python3 (Linux)"):n.push(`HINT: "${o}" is not installed. Try installing it with your package manager.`)}if(/Cannot find module|MODULE_NOT_FOUND/i.test(t)){let s=t.match(/Cannot find module '([^']+)'/),o=s?s[1]:"";o&&!o.startsWith(".")&&!o.startsWith("/")?n.push(`HINT: Missing npm package "${o}". Run: npm install ${o}`):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 s=t.match(/port (\d+)|:(\d+)/),o=s?s[1]||s[2]:"";n.push(`HINT: Port ${o||""} 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 s=t.match(/curl:\s*\((\d+)\)/),o=s?parseInt(s[1],10):null;o===6||/Could not resolve host/i.test(t)?n.push("HINT: Hostname could not be resolved. Check DNS or use an IP address directly."):o===7||/Failed to connect|Connection refused/i.test(t)?n.push("HINT: Service not running or port wrong. Check if the service is up and the port is correct."):o===22||/HTTP error/i.test(t)?n.push("HINT: HTTP 4xx/5xx response. The endpoint exists but returned an error status."):o===28||/timed out/i.test(t)?n.push("HINT: Request timed out. The host may be unreachable or the service is slow."):(o===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 s=t.match(/port (\d+)/),o=s?s[1]:"";n.push(`HINT: SSH remote port forwarding failed for port ${o}. The port may already be bound on the server. Check with: ssh server "ss -tuln | grep ${o}" and kill any lingering process with that port.`)}return/bind.*Cannot assign requested address|Address already in use/i.test(t)&&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+`
453
+ `)}`}}}catch{}return{fixedPath:null,message:""}}function o1(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 Ib(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 jb(t,e){let n=Ib(t);if(!n)return new Map;try{let o=await YR(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 Pb(t,e){if(!t)return"";let n=e||process.cwd(),o=le.isAbsolute(t)?t:le.resolve(n,t),s=le.relative(n,o);return s&&!s.startsWith("..")&&!le.isAbsolute(s)?s:le.relative(process.cwd(),o)}function Vr(t,e){let n=(t||"").trim();return n?e==="files_with_matches"||e==="count"?n.split(`
454
+ `).filter(o=>o.trim()):n.split(`
455
+ `).filter(o=>o.trim()):[]}function Db(t,{query:e,basePath:n,definitionScores:o=new Map,mtimeByPath:s=new Map}={}){let r=Ib(e);return[...t].sort((i,a)=>{let l=Pb(i,n),c=Pb(a,n),u=0,d=0;if(r&&(u+=Rb(l,r),d+=Rb(c,r)),u+=o.get(l)||0,d+=o.get(c)||0,u!==d)return d-u;let f=s.get(i)||0,p=s.get(a)||0;return f!==p?p-f:l.localeCompare(c)})}async function yd(t,{query:e,basePath:n,outputMode:o}={}){if(!Array.isArray(t)||t.length<=1)return t;let s=new Map,r=[];for(let c of t){if(!c)continue;let u=c;(o==="count"||o!=="files_with_matches")&&(u=c.split(":")[0]),s.has(u)||(s.set(u,[]),r.push(u)),s.get(u).push(c)}let i=await jb(e,n),a=Db(r,{query:e,basePath:n,definitionScores:i}),l=[];for(let c of a)l.push(...s.get(c)||[]);return l}function qb(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+`
456
456
 
457
457
  `+n.join(`
458
- `)}function Fb(t,e,n){let s=Zr(t,e);if(!s)return null;let o=Math.max(2,Math.ceil(e.length*.03));return s.distance>o?null:{autoFixed:!0,matchText:s.text,content:t.split(s.text).join(n),distance:s.distance,line:s.line}}var Mb=!1,oo=null;function r1(){oo&&(oo(),oo=null)}var $d=null;function i1(t){$d=t}async function bd(){if(!Mb){Mb=!0;try{let{stdout:t}=await gt("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await gt('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await gt("git stash pop",{cwd:process.cwd(),timeout:1e4}),await gt("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var a1=[/\.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 l1(){let t=process.cwd();try{return Sn.realpathSync(t)}catch{return le.resolve(t)}}function c1(t,e){let n=le.relative(e,t);return n===""||!n.startsWith("..")&&!le.isAbsolute(n)}function u1(t){if(Sn.existsSync(t))return Sn.realpathSync(t);let e=le.dirname(t);for(;e&&e!==le.dirname(e);){if(Sn.existsSync(e)){let n=Sn.realpathSync(e),s=le.relative(e,t);return le.resolve(n,s)}e=le.dirname(e)}return t}function At(t){let e=le.isAbsolute(t)?le.resolve(t):le.resolve(process.cwd(),t);for(let s of a1)if(s.test(e))return null;let n=u1(e);return c1(n,l1())?n:null}function He(t){return`'${String(t).replace(/'/g,"'\\''")}'`}function Bb(t){return typeof t=="string"&&/^[a-z_][a-z0-9_-]{0,31}\$?$/i.test(t)}function d1(t){return typeof t=="string"&&/^[a-zA-Z0-9@_.:-]+(?:\.service)?$/.test(t)}function f1(t){return typeof t=="string"&&/^[a-zA-Z0-9+_.:@/-]+$/.test(t)}function wd(t){return typeof t=="string"&&/^\d{1,5}(?:\/(?:tcp|udp))?$/i.test(t)}function p1(t){return typeof t=="string"&&/^(?:SIG[A-Z0-9]+|[A-Z0-9]+|\d{1,2})$/.test(t)}function Xr(t,e="user"){return Bb(t)?null:`ERROR: ${e} contains unsafe characters`}function _d(t,e="service"){return d1(t)?null:`ERROR: ${e} contains unsafe characters`}var h1=[{type:"function",function:{name:"bash",description:"Run shell commands in the project directory. Timeout: 90s. Use for tests, installs, git, builds, servers, and compilers. Do not use for reading/searching files: use read_file, grep, glob, or list_directory instead. Quote paths with spaces. Check exit code; non-zero means failure. Dangerous commands require confirmation.",parameters:{type:"object",properties:{command:{type:"string",description:"The bash command to execute"}},required:["command"]}}},{type:"function",function:{name:"read_file",description:"Read UTF-8 file contents with line numbers. Read before editing so edit_file can match exact text. Use line_start/line_end for targeted or large-file reads; unbounded reads truncate at 350 lines. Prefer this over bash cat/head/tail.",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 by name/path glob, sorted by modification time. Use before reading when paths are unknown. Do not search file contents with this; use grep. Prefer this over bash find/ls.",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 Jr(t,{server:e,context:n}={}){let s=e?e.replace(/[^a-zA-Z0-9@._-]/g,""):null,o=n?n.replace(/[^a-zA-Z0-9._/-]/g,""):null,r="kubectl";if(o&&(r+=` --context ${o}`),r+=` ${t}`,s){let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`ssh -o ConnectTimeout=10 -o BatchMode=yes ${s} "${i}"`}return r}async function Nb(t,e,n={}){switch(t){case"bash":{let s=e.command,o=Lb(s);if(o)return`BLOCKED: ${o} is a Node.js built-in module and must not be installed. Import it directly instead.`;let r=IR(s);if(r){let f=o1(s);return`BLOCKED: Command matches forbidden pattern: ${r}${f?`
459
- HINT: ${f}`:""}`}let i=qR(s);if(i)return`BLOCKED: Destructive operation on protected path: ${i}
460
- 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?vb(s):DR(s)){let f=vb(s)?"\u26D4":"\u26A0";if(!await vn(` ${f} bash: \`${s}\``,{toolName:"bash"}))return"CANCELLED: User declined to execute this command."}let l;try{l=process.cwd(),Sn.accessSync(l)}catch{l=require("os").homedir(),n.silent||console.log(`${ye.yellow} \u26A0 Working directory no longer exists \u2014 running in ${l}${ye.reset}`)}let c=QR.test(s.trim())&&!e1.test(s.trim());if(ZR.test(s.trim())||c){n.silent||console.log(`${ye.dim} \u25B6 interactive: ${s}${ye.reset}`);let f=LR("sh",["-c",s],{stdio:"inherit",cwd:l});return f.error?`ERROR: ${f.error.message}`:f.status===0?"(interactive command completed successfully)":`(interactive command exited with code ${f.status})`}let{ToolProgress:u}=Ls(),d=n.silent?null:new u("bash",`$ ${s.substring(0,72)}`);d&&d.start();try{let{stdout:f,stderr:p}=await gt(s,{cwd:l,timeout:9e4,maxBuffer:5242880});return d&&d.stop(),f||p||"(no output)"}catch(f){d&&d.stop();let p=(f.stderr||f.stdout||f.message||"").toString().substring(0,5e3),h=qb(p,s);return`EXIT ${f.code||1}
461
- ${h}`}}case"read_file":{let s=new ol("read_file","Reading file...");s.start();try{let o=At(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await Qt(o)){let X=await al(e.path);if(X.fixedPath)o=X.fixedPath,console.log(`${ye.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${le.relative(process.cwd(),o)}${ye.reset}`),s.update({message:"Resolved path",detail:le.relative(process.cwd(),o)});else return`ERROR: File not found: ${e.path}${X.message?`
462
- `+X.message:""}`}let i=le.relative(process.cwd(),o);s.update({message:"Scanning",detail:i});let a=Buffer.alloc(8192),l=await Sn.promises.open(o,"r"),{bytesRead:c}=await l.read(a,0,8192,0);await l.close();for(let X=0;X<c;X++)if(a[X]===0)return`ERROR: ${o} is a binary file (not readable as text)`;let u=await bt.readFile(o,"utf-8");if(!u&&(await bt.stat(o)).size>0)return`WARNING: ${o} is empty or unreadable`;let d=u.split(`
463
- `),f=await bt.stat(o),p=d.length,h=350,g=!e.line_start&&!e.line_end,w=g&&p>h,k=(e.line_start||1)-1,T=w?h:e.line_end||d.length,$=k+1,R=T;s.update({count:Math.max(0,T-k),total:p,detail:`${i} lines ${$}-${R}`,message:w?"Reading excerpt":"Reading"});let C=w?`showing lines 1-${h} of ${p}`:e.line_start||e.line_end?`lines ${k+1}-${T} of ${p}`:`${p} lines`,M=`File: ${i} (${C}, ${f.size} bytes)`,K=d.slice(k,T).map((X,ae)=>`${k+ae+1}: ${X}`).join(`
458
+ `)}function Fb(t,e,n){let o=Zr(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 Mb=!1,oo=null;function r1(){oo&&(oo(),oo=null)}var $d=null;function i1(t){$d=t}async function bd(){if(!Mb){Mb=!0;try{let{stdout:t}=await gt("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await gt('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await gt("git stash pop",{cwd:process.cwd(),timeout:1e4}),await gt("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var a1=[/\.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 l1(){let t=process.cwd();try{return Sn.realpathSync(t)}catch{return le.resolve(t)}}function c1(t,e){let n=le.relative(e,t);return n===""||!n.startsWith("..")&&!le.isAbsolute(n)}function u1(t){if(Sn.existsSync(t))return Sn.realpathSync(t);let e=le.dirname(t);for(;e&&e!==le.dirname(e);){if(Sn.existsSync(e)){let n=Sn.realpathSync(e),o=le.relative(e,t);return le.resolve(n,o)}e=le.dirname(e)}return t}function At(t){let e=le.isAbsolute(t)?le.resolve(t):le.resolve(process.cwd(),t);for(let o of a1)if(o.test(e))return null;let n=u1(e);return c1(n,l1())?n:null}function He(t){return`'${String(t).replace(/'/g,"'\\''")}'`}function Bb(t){return typeof t=="string"&&/^[a-z_][a-z0-9_-]{0,31}\$?$/i.test(t)}function d1(t){return typeof t=="string"&&/^[a-zA-Z0-9@_.:-]+(?:\.service)?$/.test(t)}function f1(t){return typeof t=="string"&&/^[a-zA-Z0-9+_.:@/-]+$/.test(t)}function wd(t){return typeof t=="string"&&/^\d{1,5}(?:\/(?:tcp|udp))?$/i.test(t)}function p1(t){return typeof t=="string"&&/^(?:SIG[A-Z0-9]+|[A-Z0-9]+|\d{1,2})$/.test(t)}function Xr(t,e="user"){return Bb(t)?null:`ERROR: ${e} contains unsafe characters`}function _d(t,e="service"){return d1(t)?null:`ERROR: ${e} contains unsafe characters`}var h1=[{type:"function",function:{name:"bash",description:"Run shell commands in the project directory. Timeout: 90s. Use for tests, installs, git, builds, servers, and compilers. Do not use for reading/searching files: use read_file, grep, glob, or list_directory instead. Quote paths with spaces. Check exit code; non-zero means failure. Dangerous commands require confirmation.",parameters:{type:"object",properties:{command:{type:"string",description:"The bash command to execute"}},required:["command"]}}},{type:"function",function:{name:"read_file",description:"Read UTF-8 file contents with line numbers. Read before editing so edit_file can match exact text. Use line_start/line_end for targeted or large-file reads; unbounded reads truncate at 350 lines. Prefer this over bash cat/head/tail.",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 by name/path glob, sorted by modification time. Use before reading when paths are unknown. Do not search file contents with this; use grep. Prefer this over bash find/ls.",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 Jr(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 Nb(t,e,n={}){switch(t){case"bash":{let o=e.command,s=Lb(o);if(s)return`BLOCKED: ${s} is a Node.js built-in module and must not be installed. Import it directly instead.`;let r=IR(o);if(r){let f=o1(o);return`BLOCKED: Command matches forbidden pattern: ${r}${f?`
459
+ HINT: ${f}`:""}`}let i=qR(o);if(i)return`BLOCKED: Destructive operation on protected path: ${i}
460
+ 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?vb(o):DR(o)){let f=vb(o)?"\u26D4":"\u26A0";if(!await vn(` ${f} bash: \`${o}\``,{toolName:"bash"}))return"CANCELLED: User declined to execute this command."}let l;try{l=process.cwd(),Sn.accessSync(l)}catch{l=require("os").homedir(),n.silent||console.log(`${ye.yellow} \u26A0 Working directory no longer exists \u2014 running in ${l}${ye.reset}`)}let c=QR.test(o.trim())&&!e1.test(o.trim());if(ZR.test(o.trim())||c){n.silent||console.log(`${ye.dim} \u25B6 interactive: ${o}${ye.reset}`);let f=LR("sh",["-c",o],{stdio:"inherit",cwd:l});return f.error?`ERROR: ${f.error.message}`:f.status===0?"(interactive command completed successfully)":`(interactive command exited with code ${f.status})`}let{ToolProgress:u}=Ls(),d=n.silent?null:new u("bash",`$ ${o.substring(0,72)}`);d&&d.start();try{let{stdout:f,stderr:p}=await gt(o,{cwd:l,timeout:9e4,maxBuffer:5242880});return d&&d.stop(),f||p||"(no output)"}catch(f){d&&d.stop();let p=(f.stderr||f.stdout||f.message||"").toString().substring(0,5e3),h=qb(p,o);return`EXIT ${f.code||1}
461
+ ${h}`}}case"read_file":{let o=new ol("read_file","Reading file...");o.start();try{let s=At(e.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await Qt(s)){let X=await al(e.path);if(X.fixedPath)s=X.fixedPath,console.log(`${ye.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${le.relative(process.cwd(),s)}${ye.reset}`),o.update({message:"Resolved path",detail:le.relative(process.cwd(),s)});else return`ERROR: File not found: ${e.path}${X.message?`
462
+ `+X.message:""}`}let i=le.relative(process.cwd(),s);o.update({message:"Scanning",detail:i});let a=Buffer.alloc(8192),l=await Sn.promises.open(s,"r"),{bytesRead:c}=await l.read(a,0,8192,0);await l.close();for(let X=0;X<c;X++)if(a[X]===0)return`ERROR: ${s} is a binary file (not readable as text)`;let u=await bt.readFile(s,"utf-8");if(!u&&(await bt.stat(s)).size>0)return`WARNING: ${s} is empty or unreadable`;let d=u.split(`
463
+ `),f=await bt.stat(s),p=d.length,h=350,g=!e.line_start&&!e.line_end,w=g&&p>h,k=(e.line_start||1)-1,T=w?h:e.line_end||d.length,$=k+1,R=T;o.update({count:Math.max(0,T-k),total:p,detail:`${i} lines ${$}-${R}`,message:w?"Reading excerpt":"Reading"});let C=w?`showing lines 1-${h} of ${p}`:e.line_start||e.line_end?`lines ${k+1}-${T} of ${p}`:`${p} lines`,M=`File: ${i} (${C}, ${f.size} bytes)`,K=d.slice(k,T).map((X,ae)=>`${k+ae+1}: ${X}`).join(`
464
464
  `),z=w?`
465
465
 
466
466
  [\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>T?`
467
467
 
468
468
  [\u{1F6A8} FILE CONTINUES: This is only lines ${k+1} to ${T} of ${p} total. The rest is HIDDEN. Use line_start=${T+1} to read the next section, or grep_search for keywords.]`:"";return`${M}
469
- ${K}${z}`}finally{s.stop()}}case"write_file":{let s=new ol("write_file","Preparing write...");s.start();try{await bd();let o=At(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let r=await Qt(o),i=null,a=String(e.content||"").split(`
470
- `).length;if(s.update({count:a,detail:`${le.relative(process.cwd(),o)} ${a} lines`,message:r?"Overwriting":"Creating"}),n.autoConfirm)r&&(i=await bt.readFile(o,"utf-8"));else if(r){i=await bt.readFile(o,"utf-8");let f=await Kr(o,e.content);if(sl(o,i,e.content,{annotations:f}),!await zr("Overwrite"))return"CANCELLED: User declined to overwrite file."}else{let f=await Kr(o,e.content);if(FR(o,e.content,{annotations:f}),!await zr("Create"))return"CANCELLED: User declined to create file."}let l=le.dirname(o);await Qt(l)||await bt.mkdir(l,{recursive:!0}),s.update({message:"Writing",detail:`${le.relative(process.cwd(),o)} ${a} lines`}),await bt.writeFile(o,e.content,"utf-8");let u=/[/\\]\.git[/\\]hooks[/\\]/.test(o)||o.endsWith(".sh")||e.content.startsWith("#!");u&&(s.update({message:"Chmod",detail:le.relative(process.cwd(),o)}),await bt.chmod(o,493)),rl("write_file",o,i,e.content);let d=u?" [chmod +x applied]":"";return`Written: ${o} (${e.content.length} chars)${d}`}finally{s.stop()}}case"edit_file":{let s=new ol("edit_file","Preparing edit...");s.start();try{await bd();let o=At(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await Qt(o)){let d=await al(e.path);if(d.fixedPath)o=d.fixedPath,console.log(`${ye.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${le.relative(process.cwd(),o)}${ye.reset}`);else return`ERROR: File not found: ${e.path}${d.message?`
471
- `+d.message:""}`}s.update({message:"Loading",detail:le.relative(process.cwd(),o)});let i=await bt.readFile(o,"utf-8"),a=e.old_text,l=!1,c=!1;if(!i.includes(e.old_text)){s.update({message:"Matching target",detail:`${le.relative(process.cwd(),o)} ${String(e.old_text||"").trim().split(`
472
- `)[0].slice(0,40)}`});let{getActiveModelId:d,getActiveProviderName:f}=vt();if(Ab(d(),f())==="strict"){let g=Zr(i,e.old_text);return g?`ERROR: old_text not found in ${o} (strict mode \u2014 exact match required)
469
+ ${K}${z}`}finally{o.stop()}}case"write_file":{let o=new ol("write_file","Preparing write...");o.start();try{await bd();let s=At(e.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let r=await Qt(s),i=null,a=String(e.content||"").split(`
470
+ `).length;if(o.update({count:a,detail:`${le.relative(process.cwd(),s)} ${a} lines`,message:r?"Overwriting":"Creating"}),n.autoConfirm)r&&(i=await bt.readFile(s,"utf-8"));else if(r){i=await bt.readFile(s,"utf-8");let f=await Kr(s,e.content);if(sl(s,i,e.content,{annotations:f}),!await zr("Overwrite"))return"CANCELLED: User declined to overwrite file."}else{let f=await Kr(s,e.content);if(FR(s,e.content,{annotations:f}),!await zr("Create"))return"CANCELLED: User declined to create file."}let l=le.dirname(s);await Qt(l)||await bt.mkdir(l,{recursive:!0}),o.update({message:"Writing",detail:`${le.relative(process.cwd(),s)} ${a} lines`}),await bt.writeFile(s,e.content,"utf-8");let u=/[/\\]\.git[/\\]hooks[/\\]/.test(s)||s.endsWith(".sh")||e.content.startsWith("#!");u&&(o.update({message:"Chmod",detail:le.relative(process.cwd(),s)}),await bt.chmod(s,493)),rl("write_file",s,i,e.content);let d=u?" [chmod +x applied]":"";return`Written: ${s} (${e.content.length} chars)${d}`}finally{o.stop()}}case"edit_file":{let o=new ol("edit_file","Preparing edit...");o.start();try{await bd();let s=At(e.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await Qt(s)){let d=await al(e.path);if(d.fixedPath)s=d.fixedPath,console.log(`${ye.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${le.relative(process.cwd(),s)}${ye.reset}`);else return`ERROR: File not found: ${e.path}${d.message?`
471
+ `+d.message:""}`}o.update({message:"Loading",detail:le.relative(process.cwd(),s)});let i=await bt.readFile(s,"utf-8"),a=e.old_text,l=!1,c=!1;if(!i.includes(e.old_text)){o.update({message:"Matching target",detail:`${le.relative(process.cwd(),s)} ${String(e.old_text||"").trim().split(`
472
+ `)[0].slice(0,40)}`});let{getActiveModelId:d,getActiveProviderName:f}=vt();if(Ab(d(),f())==="strict"){let g=Zr(i,e.old_text);return g?`ERROR: old_text not found in ${s} (strict mode \u2014 exact match required)
473
473
  Most similar text (line ${g.line}, distance ${g.distance}):
474
- ${g.text}`:`ERROR: old_text not found in ${o} (strict mode \u2014 exact match required)`}let h=Eb(i,e.old_text);if(h)a=h,l=!0,s.update({message:"Matched target",detail:`${le.relative(process.cwd(),o)} whitespace-normalized`}),console.log(`${ye.dim} \u2713 fuzzy whitespace match applied${ye.reset}`);else{let g=Fb(i,e.old_text,e.new_text);if(g){if(!n.autoConfirm){let R=await Kr(o,g.content);if(sl(o,i,g.content,{annotations:R}),!await zr(`Apply (auto-fix, line ${g.line}, distance ${g.distance})`))return"CANCELLED: User declined to apply edit."}await bt.writeFile(o,g.content,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(o)||o.endsWith(".sh")||g.content.startsWith("#!"))&&await bt.chmod(o,493),rl("edit_file",o,i,g.content);let $=g.matchText.length>80?g.matchText.substring(0,77)+"...":g.matchText;return console.log(`${ye.dim} \u2713 auto-fixed edit: line ${g.line}, distance ${g.distance}${ye.reset}`),`Edited: ${o} (auto-fixed, line ${g.line}, distance ${g.distance}, matched: "${$}")`}let w=Zr(i,e.old_text);if(w){let $=i.split(`
474
+ ${g.text}`:`ERROR: old_text not found in ${s} (strict mode \u2014 exact match required)`}let h=Eb(i,e.old_text);if(h)a=h,l=!0,o.update({message:"Matched target",detail:`${le.relative(process.cwd(),s)} whitespace-normalized`}),console.log(`${ye.dim} \u2713 fuzzy whitespace match applied${ye.reset}`);else{let g=Fb(i,e.old_text,e.new_text);if(g){if(!n.autoConfirm){let R=await Kr(s,g.content);if(sl(s,i,g.content,{annotations:R}),!await zr(`Apply (auto-fix, line ${g.line}, distance ${g.distance})`))return"CANCELLED: User declined to apply edit."}await bt.writeFile(s,g.content,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(s)||s.endsWith(".sh")||g.content.startsWith("#!"))&&await bt.chmod(s,493),rl("edit_file",s,i,g.content);let $=g.matchText.length>80?g.matchText.substring(0,77)+"...":g.matchText;return console.log(`${ye.dim} \u2713 auto-fixed edit: line ${g.line}, distance ${g.distance}${ye.reset}`),`Edited: ${s} (auto-fixed, line ${g.line}, distance ${g.distance}, matched: "${$}")`}let w=Zr(i,e.old_text);if(w){let $=i.split(`
475
475
  `),R=Math.max(0,w.line-6),C=Math.min($.length,w.line+10),M=$.slice(R,C).map((z,X)=>`${R+X+1}: ${z}`).join(`
476
- `),K=`line_start=${Math.max(1,w.line-5)} line_end=${Math.min($.length,w.line+15)}`;return`ERROR: old_text not found in ${o} (most similar at line ${w.line}, distance ${w.distance})
476
+ `),K=`line_start=${Math.max(1,w.line-5)} line_end=${Math.min($.length,w.line+15)}`;return`ERROR: old_text not found in ${s} (most similar at line ${w.line}, distance ${w.distance})
477
477
 
478
478
  Actual file content around line ${w.line} \u2014 use this to correct old_text:
479
479
  ${M}
@@ -481,45 +481,45 @@ ${M}
481
481
  Fix: update old_text to match the exact lines above, then retry. If you need more context: read_file with ${K}`}let k=(e.old_text||"").trim().split(`
482
482
  `)[0].slice(0,60),T=k?`
483
483
  Recovery: grep -n "${k.replace(/"/g,'\\"')}" <file> to find the line, then re-read that section with line_start/line_end.`:`
484
- 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 ${o}${T}`}}if(!n.autoConfirm){s.update({message:"Previewing edit",detail:`${le.relative(process.cwd(),o)} ${String(e.new_text||"").trim().split(`
485
- `)[0].slice(0,40)}`});let d=i.split(a).join(e.new_text),f=await Kr(o,d);if(sl(o,i,d,{annotations:f}),!await zr(l?"Apply (fuzzy match)":"Apply"))return"CANCELLED: User declined to apply edit."}let u=i.split(a).join(e.new_text);return s.update({message:"Applying edit",detail:`${le.relative(process.cwd(),o)} ${String(e.new_text||"").trim().split(`
486
- `)[0].slice(0,40)}`}),await bt.writeFile(o,u,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(o)||o.endsWith(".sh")||u.startsWith("#!"))&&(s.update({message:"Chmod",detail:le.relative(process.cwd(),o)}),await bt.chmod(o,493)),rl("edit_file",o,i,u),l?`Edited: ${o} (fuzzy match)`:`Edited: ${o}`}finally{s.stop()}}case"list_directory":{let s=At(e.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await Qt(s)){let c=e.path.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),u=At(c),d=await Qt(u);if(u&&d)s=u;else return`ERROR: Directory not found: ${e.path}`}let r=e.max_depth||2,i=null;if(e.pattern)try{let c=e.pattern.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");i=new RegExp(`^${c}$`)}catch{return`ERROR: Invalid pattern: ${e.pattern}`}let a=[],l=async(c,u,d)=>{if(u>r)return;let f;try{f=await bt.readdir(c,{withFileTypes:!0})}catch{return}f=f.filter(p=>!p.name.startsWith(".")&&p.name!=="node_modules");for(let p of f){if(i&&!p.isDirectory()&&!i.test(p.name))continue;let h=p.isDirectory()?"/":"";a.push(`${d}${p.name}${h}`),p.isDirectory()&&await l(le.join(c,p.name),u+1,d+" ")}};return await l(s,1,""),a.join(`
487
- `)||"(empty)"}case"search_files":{let s=At(e.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let o=["-rn","-H"];e.file_pattern&&o.push(`--include=${e.file_pattern}`),o.push(e.pattern,s);try{let{stdout:r}=await so("grep",o,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),i=Vr(r).slice(0,50);return(await yd(i,{query:e.pattern,basePath:s})).join(`
488
- `)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let o=process.cwd(),r=e.path?At(e.path):o,i=e.pattern,a=C=>{let M=C.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"(.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");return new RegExp(`^${M}$`)},l=a(i),c=i.split("/").pop(),u=a(c),{ToolProgress:d}=Ls(),f=new d("glob","Finding files...");f.start();let p=Tb();KR(r)||(await zR(r),p=Tb());let h=p.filter(C=>l.test(C)||u.test(le.basename(C))).map(C=>le.join(r,C));if(h.length===0)return f.stop(),"(no matches)"+gd(e.path);let g=await Promise.all(h.slice(0,210).map(async C=>{try{let M=await bt.stat(C);return{path:C,mtime:M.mtimeMs}}catch{return{path:C,mtime:0}}})),w=new Map(g.map(C=>[C.path,C.mtime])),k=await jb(i,r),T=Db(g.map(C=>C.path),{query:i,basePath:r,definitionScores:k,mtimeByPath:w}),$=h.length>200,R=T.slice(0,200).join(`
484
+ 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}${T}`}}if(!n.autoConfirm){o.update({message:"Previewing edit",detail:`${le.relative(process.cwd(),s)} ${String(e.new_text||"").trim().split(`
485
+ `)[0].slice(0,40)}`});let d=i.split(a).join(e.new_text),f=await Kr(s,d);if(sl(s,i,d,{annotations:f}),!await zr(l?"Apply (fuzzy match)":"Apply"))return"CANCELLED: User declined to apply edit."}let u=i.split(a).join(e.new_text);return o.update({message:"Applying edit",detail:`${le.relative(process.cwd(),s)} ${String(e.new_text||"").trim().split(`
486
+ `)[0].slice(0,40)}`}),await bt.writeFile(s,u,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(s)||s.endsWith(".sh")||u.startsWith("#!"))&&(o.update({message:"Chmod",detail:le.relative(process.cwd(),s)}),await bt.chmod(s,493)),rl("edit_file",s,i,u),l?`Edited: ${s} (fuzzy match)`:`Edited: ${s}`}finally{o.stop()}}case"list_directory":{let o=At(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await Qt(o)){let c=e.path.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),u=At(c),d=await Qt(u);if(u&&d)o=u;else return`ERROR: Directory not found: ${e.path}`}let r=e.max_depth||2,i=null;if(e.pattern)try{let c=e.pattern.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");i=new RegExp(`^${c}$`)}catch{return`ERROR: Invalid pattern: ${e.pattern}`}let a=[],l=async(c,u,d)=>{if(u>r)return;let f;try{f=await bt.readdir(c,{withFileTypes:!0})}catch{return}f=f.filter(p=>!p.name.startsWith(".")&&p.name!=="node_modules");for(let p of f){if(i&&!p.isDirectory()&&!i.test(p.name))continue;let h=p.isDirectory()?"/":"";a.push(`${d}${p.name}${h}`),p.isDirectory()&&await l(le.join(c,p.name),u+1,d+" ")}};return await l(o,1,""),a.join(`
487
+ `)||"(empty)"}case"search_files":{let o=At(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 so("grep",s,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),i=Vr(r).slice(0,50);return(await yd(i,{query:e.pattern,basePath:o})).join(`
488
+ `)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let s=process.cwd(),r=e.path?At(e.path):s,i=e.pattern,a=C=>{let M=C.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"(.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");return new RegExp(`^${M}$`)},l=a(i),c=i.split("/").pop(),u=a(c),{ToolProgress:d}=Ls(),f=new d("glob","Finding files...");f.start();let p=Tb();KR(r)||(await zR(r),p=Tb());let h=p.filter(C=>l.test(C)||u.test(le.basename(C))).map(C=>le.join(r,C));if(h.length===0)return f.stop(),"(no matches)"+gd(e.path);let g=await Promise.all(h.slice(0,210).map(async C=>{try{let M=await bt.stat(C);return{path:C,mtime:M.mtimeMs}}catch{return{path:C,mtime:0}}})),w=new Map(g.map(C=>[C.path,C.mtime])),k=await jb(i,r),T=Db(g.map(C=>C.path),{query:i,basePath:r,definitionScores:k,mtimeByPath:w}),$=h.length>200,R=T.slice(0,200).join(`
489
489
  `);return f.update({count:h.length,detail:e.pattern}),f.stop(),$?`${R}
490
490
 
491
- \u26A0 Results truncated at 200. Use a more specific pattern.`:R}case"grep":{let s=e.path?At(e.path):process.cwd();if(e.staged){let{getDiff:l}=$a(),c=await l(!0);if(!c.trim())return"(no staged changes)";let u=new Set,d=c.split(`
491
+ \u26A0 Results truncated at 200. Use a more specific pattern.`:R}case"grep":{let o=e.path?At(e.path):process.cwd();if(e.staged){let{getDiff:l}=$a(),c=await l(!0);if(!c.trim())return"(no staged changes)";let u=new Set,d=c.split(`
492
492
  `);for(let w of d)if(w.startsWith("diff --git")){let k=w.match(/diff --git a\/(.+) b\/(.+)/);k&&u.add(k[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}=Ls(),h=new p("grep","Searching staged content...");h.start();let g=[];for(let w of u)try{let k=le.join(process.cwd(),w);if(await Qt(k)){let T=[...f];T.push(e.pattern,k);let{stdout:$}=await so("grep",T,{cwd:process.cwd(),timeout:3e4,maxBuffer:2*1024*1024});if(e.output_mode==="files_with_matches"||e.output_mode==="count"){let R=Vr($,e.output_mode);g=g.concat(R)}else g=g.concat(Vr($))}}catch{}return g=await yd(g,{query:e.pattern,basePath:process.cwd(),outputMode:e.output_mode}),h.update({count:g.length,detail:"in staged files"}),h.stop(),g.join(`
493
- `).trim()||"(no matches in staged files)"}let o=["-rn","-E","-H"];e.ignore_case&&o.push("-i"),e.include&&o.push(`--include=${e.include}`),e.type&&o.push(`--include=*.${e.type}`);let r=20;e.context?o.push("-C",String(Math.min(Number(e.context),r))):(e.before_context&&o.push("-B",String(Math.min(Number(e.before_context),r))),e.after_context&&o.push("-A",String(Math.min(Number(e.after_context),r)))),e.output_mode==="files_with_matches"?o.push("-l"):e.output_mode==="count"&&o.push("-c"),o.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage"),o.push(e.pattern,s);let{ToolProgress:i}=Ls(),a=new i("grep","Searching...");a.start();try{let{stdout:l}=await so("grep",o,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),c;e.output_mode==="files_with_matches"||e.output_mode==="count"?c=Vr(l,e.output_mode):c=Vr(l);let u=e.offset||0,d=e.head_limit||(e.output_mode==="files_with_matches"?200:100);return c=await yd(c,{query:e.pattern,basePath:s,outputMode:e.output_mode}),c=c.slice(u,u+d),a.update({count:c.length,detail:`in ${s}`}),a.stop(),c.join(`
494
- `).trim()||"(no matches)"+gd(e.path)}catch(l){if(a.stop(),l.code===2){let c=(l.stderr||l.message||"").toString().trim();return c.includes("No such file or directory")?`ERROR: Directory not found: ${s}`:c.includes("Invalid")||c.includes("Unmatched")||c.includes("unterminated")||c.includes("unclosed")||c.includes("parse error")||c.includes("brackets")||c.includes("not balanced")?`ERROR: Invalid regex pattern: ${e.pattern}`:`ERROR: grep failed: ${c.slice(0,200)||"exit code 2"}`}return"(no matches)"+gd(e.path)}}case"patch_file":{let s=new ol("patch_file","Preparing patches...");s.start();try{await bd();let o=At(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await Qt(o)){let T=await al(e.path);if(T.fixedPath)o=T.fixedPath,console.log(`${ye.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${le.relative(process.cwd(),o)}${ye.reset}`);else return`ERROR: File not found: ${e.path}${T.message?`
495
- `+T.message:""}`}let i=e.patches;if(!Array.isArray(i)||i.length===0)return"ERROR: No patches provided";s.update({count:0,total:i.length,detail:`${le.relative(process.cwd(),o)} ${i.length} patches`,message:"Validating patches"});let a=await bt.readFile(o,"utf-8"),{getActiveModelId:l,getActiveProviderName:c}=vt(),u=Ab(l(),c()),d=[],f=!1,p=!1;for(let T=0;T<i.length;T++){s.update({count:T+1,total:i.length,detail:`${le.relative(process.cwd(),o)} patch ${T+1}/${i.length}`,message:"Matching patches"});let{old_text:$,new_text:R}=i[T];if(a.includes($))d.push({old_text:$,new_text:R});else if(u==="strict"){let C=Zr(a,$);return C?`ERROR: Patch ${T+1} old_text not found in ${o} (strict mode \u2014 exact match required)
493
+ `).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}=Ls(),a=new i("grep","Searching...");a.start();try{let{stdout:l}=await so("grep",s,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),c;e.output_mode==="files_with_matches"||e.output_mode==="count"?c=Vr(l,e.output_mode):c=Vr(l);let u=e.offset||0,d=e.head_limit||(e.output_mode==="files_with_matches"?200:100);return c=await yd(c,{query:e.pattern,basePath:o,outputMode:e.output_mode}),c=c.slice(u,u+d),a.update({count:c.length,detail:`in ${o}`}),a.stop(),c.join(`
494
+ `).trim()||"(no matches)"+gd(e.path)}catch(l){if(a.stop(),l.code===2){let c=(l.stderr||l.message||"").toString().trim();return c.includes("No such file or directory")?`ERROR: Directory not found: ${o}`:c.includes("Invalid")||c.includes("Unmatched")||c.includes("unterminated")||c.includes("unclosed")||c.includes("parse error")||c.includes("brackets")||c.includes("not balanced")?`ERROR: Invalid regex pattern: ${e.pattern}`:`ERROR: grep failed: ${c.slice(0,200)||"exit code 2"}`}return"(no matches)"+gd(e.path)}}case"patch_file":{let o=new ol("patch_file","Preparing patches...");o.start();try{await bd();let s=At(e.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await Qt(s)){let T=await al(e.path);if(T.fixedPath)s=T.fixedPath,console.log(`${ye.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${le.relative(process.cwd(),s)}${ye.reset}`);else return`ERROR: File not found: ${e.path}${T.message?`
495
+ `+T.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:`${le.relative(process.cwd(),s)} ${i.length} patches`,message:"Validating patches"});let a=await bt.readFile(s,"utf-8"),{getActiveModelId:l,getActiveProviderName:c}=vt(),u=Ab(l(),c()),d=[],f=!1,p=!1;for(let T=0;T<i.length;T++){o.update({count:T+1,total:i.length,detail:`${le.relative(process.cwd(),s)} patch ${T+1}/${i.length}`,message:"Matching patches"});let{old_text:$,new_text:R}=i[T];if(a.includes($))d.push({old_text:$,new_text:R});else if(u==="strict"){let C=Zr(a,$);return C?`ERROR: Patch ${T+1} old_text not found in ${s} (strict mode \u2014 exact match required)
496
496
  Most similar text (line ${C.line}, distance ${C.distance}):
497
- ${C.text}`:`ERROR: Patch ${T+1} old_text not found in ${o} (strict mode \u2014 exact match required)`}else{let C=Eb(a,$);if(C)d.push({old_text:C,new_text:R}),f=!0;else{let M=Zr(a,$);if(M){let K=Math.max(3,Math.ceil($.length*.05));if(M.distance<=K)d.push({old_text:M.text,new_text:R}),p=!0;else return`ERROR: Patch ${T+1} old_text not found in ${o}
497
+ ${C.text}`:`ERROR: Patch ${T+1} old_text not found in ${s} (strict mode \u2014 exact match required)`}else{let C=Eb(a,$);if(C)d.push({old_text:C,new_text:R}),f=!0;else{let M=Zr(a,$);if(M){let K=Math.max(3,Math.ceil($.length*.05));if(M.distance<=K)d.push({old_text:M.text,new_text:R}),p=!0;else return`ERROR: Patch ${T+1} old_text not found in ${s}
498
498
  Most similar text (line ${M.line}, distance ${M.distance}):
499
- ${M.text}`}else return`ERROR: Patch ${T+1} old_text not found in ${o}`}}}let h=a;for(let{old_text:T,new_text:$}of d)h=h.split(T).join($);if(!n.autoConfirm){s.update({message:"Previewing patch set",count:d.length,total:i.length,detail:`${le.relative(process.cwd(),o)} ${d.length} matched`});let T=await Kr(o,h);if(sl(o,a,h,{annotations:T}),!await zr(f?"Apply patches (fuzzy match)":"Apply patches"))return"CANCELLED: User declined to apply patches."}s.update({message:"Applying patches",count:d.length,total:i.length,detail:`${le.relative(process.cwd(),o)} ${d.length} matched`}),await bt.writeFile(o,h,"utf-8");let g=/[/\\]\.git[/\\]hooks[/\\]/.test(o)||o.endsWith(".sh")||h.startsWith("#!");g&&(s.update({message:"Chmod",detail:le.relative(process.cwd(),o)}),await bt.chmod(o,493)),rl("patch_file",o,a,h);let w=p?" (auto-fixed)":f?" (fuzzy match)":"",k=g?" [chmod +x applied]":"";return`Patched: ${o} (${i.length} replacements)${w}${k}`}finally{s.stop()}}case"web_fetch":{let s=e.url,o=e.max_length||1e4;try{let i=new URL(s).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 hd.get(s,{timeout:15e3,maxContentLength:1048576,responseType:"text",headers:{"User-Agent":"nex-code/0.2.0"}});return(typeof a.data=="string"?a.data:JSON.stringify(a.data)).replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim().substring(0,o)||"(empty response)"}catch(r){return`ERROR: Failed to fetch ${s}: ${r.message}`}}case"web_search":{let s=e.max_results||5;if(process.env.PERPLEXITY_API_KEY)try{let o=await hd.post("https://api.perplexity.ai/chat/completions",{model:"sonar",messages:[{role:"user",content:e.query}],max_tokens:1024,search_recency_filter:"month",return_citations:!0},{timeout:2e4,headers:{Authorization:`Bearer ${process.env.PERPLEXITY_API_KEY}`,"Content-Type":"application/json"}}),r=o.data?.choices?.[0]?.message?.content||"",i=o.data?.citations||[],a=`[Perplexity grounded search]
499
+ ${M.text}`}else return`ERROR: Patch ${T+1} old_text not found in ${s}`}}}let h=a;for(let{old_text:T,new_text:$}of d)h=h.split(T).join($);if(!n.autoConfirm){o.update({message:"Previewing patch set",count:d.length,total:i.length,detail:`${le.relative(process.cwd(),s)} ${d.length} matched`});let T=await Kr(s,h);if(sl(s,a,h,{annotations:T}),!await zr(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:`${le.relative(process.cwd(),s)} ${d.length} matched`}),await bt.writeFile(s,h,"utf-8");let g=/[/\\]\.git[/\\]hooks[/\\]/.test(s)||s.endsWith(".sh")||h.startsWith("#!");g&&(o.update({message:"Chmod",detail:le.relative(process.cwd(),s)}),await bt.chmod(s,493)),rl("patch_file",s,a,h);let w=p?" (auto-fixed)":f?" (fuzzy match)":"",k=g?" [chmod +x applied]":"";return`Patched: ${s} (${i.length} replacements)${w}${k}`}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 hd.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 hd.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]
500
500
 
501
501
  ${r}`;return i.length>0&&(a+=`
502
502
 
503
503
  Sources:
504
- `+i.slice(0,s).map((l,c)=>`${c+1}. ${l}`).join(`
505
- `)),a}catch(o){console.error(`${ye.dim} Perplexity search failed (${o.message}), falling back to DuckDuckGo${ye.reset}`)}try{let r=(await hd.get("https://html.duckduckgo.com/html/",{params:{q:e.query},timeout:1e4,responseType:"text",headers:{"User-Agent":"nex-code/0.2.0"}})).data,i=[],a=/<a[^>]*class="result__a"[^>]*href="([^"]*)"[^>]*>([\s\S]*?)<\/a>/gi,l;for(;(l=a.exec(r))!==null&&i.length<s;){let c=l[1].replace(/.*uddg=/,"").split("&")[0],u=l[2].replace(/<[^>]+>/g,"").trim();try{i.push({title:u,url:decodeURIComponent(c)})}catch{i.push({title:u,url:c})}}return i.length===0?"(no results)":i.map((c,u)=>`${u+1}. ${c.title}
504
+ `+i.slice(0,o).map((l,c)=>`${c+1}. ${l}`).join(`
505
+ `)),a}catch(s){console.error(`${ye.dim} Perplexity search failed (${s.message}), falling back to DuckDuckGo${ye.reset}`)}try{let r=(await hd.get("https://html.duckduckgo.com/html/",{params:{q:e.query},timeout:1e4,responseType:"text",headers:{"User-Agent":"nex-code/0.2.0"}})).data,i=[],a=/<a[^>]*class="result__a"[^>]*href="([^"]*)"[^>]*>([\s\S]*?)<\/a>/gi,l;for(;(l=a.exec(r))!==null&&i.length<o;){let c=l[1].replace(/.*uddg=/,"").split("&")[0],u=l[2].replace(/<[^>]+>/g,"").trim();try{i.push({title:u,url:decodeURIComponent(c)})}catch{i.push({title:u,url:c})}}return i.length===0?"(no results)":i.map((c,u)=>`${u+1}. ${c.title}
506
506
  ${c.url}`).join(`
507
507
 
508
- `)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:s}=ns();try{let o=await s(e.url,{waitFor:e.wait_for}),r=o.links.length>0?`
508
+ `)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:o}=ns();try{let s=await o(e.url,{waitFor:e.wait_for}),r=s.links.length>0?`
509
509
 
510
510
  Links:
511
- `+o.links.map(i=>` ${i.text} \u2192 ${i.href}`).join(`
512
- `):"";return`Title: ${o.title}
513
- URL: ${o.url}
514
-
515
- ${o.text}${r}`}catch(o){return`ERROR: ${o.message}`}}case"browser_screenshot":{let{browserScreenshot:s}=ns();try{let o=await s(e.url,{width:e.width,height:e.height,fullPage:e.full_page});return`Screenshot saved: ${o.path}
516
- Title: ${o.title}
517
- URL: ${o.url}
518
-
519
- To analyze visually, paste the path into your next message: ${o.path}`}catch(o){return`ERROR: ${o.message}`}}case"visual_review":{let{browserScreenshot:s}=ns();try{let o=await s(e.url,{width:e.width||1280,height:e.height||800,fullPage:e.full_page||!1}),r=e.focus||"general layout, spacing, typography, colors, and usability",i=`VISUAL REVIEW \u2014 Screenshot captured
520
- URL: ${o.url}
521
- Title: ${o.title}
522
- Screenshot: ${o.path}
511
+ `+s.links.map(i=>` ${i.text} \u2192 ${i.href}`).join(`
512
+ `):"";return`Title: ${s.title}
513
+ URL: ${s.url}
514
+
515
+ ${s.text}${r}`}catch(s){return`ERROR: ${s.message}`}}case"browser_screenshot":{let{browserScreenshot:o}=ns();try{let s=await o(e.url,{width:e.width,height:e.height,fullPage:e.full_page});return`Screenshot saved: ${s.path}
516
+ Title: ${s.title}
517
+ URL: ${s.url}
518
+
519
+ To analyze visually, paste the path into your next message: ${s.path}`}catch(s){return`ERROR: ${s.message}`}}case"visual_review":{let{browserScreenshot:o}=ns();try{let s=await o(e.url,{width:e.width||1280,height:e.height||800,fullPage:e.full_page||!1}),r=e.focus||"general layout, spacing, typography, colors, and usability",i=`VISUAL REVIEW \u2014 Screenshot captured
520
+ URL: ${s.url}
521
+ Title: ${s.title}
522
+ Screenshot: ${s.path}
523
523
  Viewport: ${e.width||1280}\xD7${e.height||800}${e.full_page?" (full page)":""}
524
524
 
525
525
  Focus area: ${r}
@@ -533,44 +533,44 @@ Analyze the screenshot above and provide structured feedback:
533
533
  4. Responsiveness concerns at this viewport
534
534
  5. Specific issues related to: ${r}`;return e.compare_with&&Sn.existsSync(e.compare_with)&&(i+=`
535
535
 
536
- COMPARISON: Previous screenshot at ${e.compare_with} \u2014 describe what changed.`),{text:i,images:[{path:o.path,base64:o.base64,media_type:"image/png"}],compare_with:e.compare_with||null}}catch(o){return`ERROR: ${o.message}`}}case"clipboard_image":try{let{_grabClipboardImage:s}=kd(),o=s();return o?{text:`Clipboard image captured: ${o.path}
537
- Size: ${Math.round(Buffer.from(o.data,"base64").length/1024)} KB
536
+ 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}=kd(),s=o();return s?{text:`Clipboard image captured: ${s.path}
537
+ Size: ${Math.round(Buffer.from(s.data,"base64").length/1024)} KB
538
538
 
539
- [Clipboard image is attached for visual analysis]`,images:[{path:o.path,base64:o.data,media_type:o.media_type}]}:"No image found in clipboard. Copy a screenshot first (Cmd+Shift+4 on macOS), then try again."}catch(s){return`ERROR: ${s.message}`}case"browser_click":{let{browserClick:s}=ns();try{return await s(e.url,{selector:e.selector,text:e.text})}catch(o){return`ERROR: ${o.message}`}}case"browser_fill":{let{browserFill:s}=ns();try{return await s(e.url,{selector:e.selector,value:e.value,submit:e.submit})}catch(o){return`ERROR: ${o.message}`}}case"visual_diff":try{let{pixelDiff:s}=zs(),o=s(e.before,e.after,{threshold:e.threshold}),r=o.regionSummary.slice(0,5),i=r.length?r.map(a=>` ${a.name}: ${a.changedPercent}% changed`).join(`
540
- `):" No significant regional changes";return{text:`VISUAL DIFF \u2014 ${o.diffPercent}% of pixels changed
541
- Changed: ${o.changedPixels.toLocaleString()} / ${o.totalPixels.toLocaleString()} pixels
542
- Canvas: ${o.width}\xD7${o.height}
543
- Diff image: ${o.diffPath}
539
+ [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}=ns();try{return await o(e.url,{selector:e.selector,text:e.text})}catch(s){return`ERROR: ${s.message}`}}case"browser_fill":{let{browserFill:o}=ns();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}=zs(),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(`
540
+ `):" No significant regional changes";return{text:`VISUAL DIFF \u2014 ${s.diffPercent}% of pixels changed
541
+ Changed: ${s.changedPixels.toLocaleString()} / ${s.totalPixels.toLocaleString()} pixels
542
+ Canvas: ${s.width}\xD7${s.height}
543
+ Diff image: ${s.diffPath}
544
544
 
545
545
  Regional breakdown:
546
546
  ${i}
547
547
 
548
- [Diff image attached \u2014 red/magenta pixels indicate changes]`,images:[{path:o.diffPath,base64:Sn.readFileSync(o.diffPath).toString("base64"),media_type:"image/png"}]}}catch(s){return`ERROR: ${s.message}`}case"responsive_sweep":try{let{responsiveSweep:s}=zs(),o=await s(e.url,{viewports:e.viewports,fullPage:e.full_page}),r=o.map(i=>` ${i.label} (${i.width}px): ${i.path}`).join(`
549
- `);return{text:`RESPONSIVE SWEEP \u2014 ${o.length} viewports captured
548
+ [Diff image attached \u2014 red/magenta pixels indicate changes]`,images:[{path:s.diffPath,base64:Sn.readFileSync(s.diffPath).toString("base64"),media_type:"image/png"}]}}catch(o){return`ERROR: ${o.message}`}case"responsive_sweep":try{let{responsiveSweep:o}=zs(),s=await o(e.url,{viewports:e.viewports,fullPage:e.full_page}),r=s.map(i=>` ${i.label} (${i.width}px): ${i.path}`).join(`
549
+ `);return{text:`RESPONSIVE SWEEP \u2014 ${s.length} viewports captured
550
550
  URL: ${e.url}
551
551
 
552
552
  Screenshots:
553
553
  ${r}
554
554
 
555
- [All ${o.length} screenshots attached for breakpoint analysis]
555
+ [All ${s.length} screenshots attached for breakpoint analysis]
556
556
 
557
557
  Analyze these screenshots for:
558
558
  1. Layout breakpoint issues (overflow, collapse, stacking)
559
559
  2. Typography scaling (text too small on mobile, too large on desktop)
560
560
  3. Navigation pattern changes across viewports
561
561
  4. Image/media sizing and aspect ratio issues
562
- 5. Touch target sizes on mobile viewports`,images:o.map(i=>({path:i.path,base64:i.base64,media_type:i.media_type}))}}catch(s){return`ERROR: ${s.message}`}case"visual_annotate":try{let{annotateImage:s}=zs(),o=s(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})
562
+ 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}=zs(),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})
563
563
  Source: ${e.image}
564
- Output: ${o.path}
564
+ Output: ${s.path}
565
565
 
566
- [Annotated image attached with visual markers]`,images:[{path:o.path,base64:o.base64,media_type:o.media_type}]}}catch(s){return`ERROR: ${s.message}`}case"visual_watch":try{let{visualWatch:s}=zs(),o=s(e.url,e.watch,{maxIterations:e.max_iterations||10,hmrDelay:e.hmr_delay||1500}),r=await o.next();if(r.value?.type==="error")return`ERROR: ${r.value.message}`;let i=[];i.push(`VISUAL WATCH \u2014 monitoring ${e.watch.length} path(s)`,`URL: ${e.url}`,`Baseline screenshot: ${r.value?.path}`,"","Watching for file changes... (will capture up to "+(e.max_iterations||10)+" iterations)");let a=await o.next();if(!a.done&&a.value){let l=a.value;i.push("",`--- Iteration ${l.iteration} ---`,`Screenshot: ${l.path}`),l.diff&&i.push(`Diff: ${l.diff.diffPercent}% changed (${l.diff.changedPixels} pixels)`,`Regions: ${l.diff.regions.map(u=>`${u.name}:${u.changedPercent}%`).join(", ")}`);let c=[{path:l.path,base64:l.base64,media_type:l.media_type}];return l.diff?.diffPath&&c.push({path:l.diff.diffPath,base64:Sn.readFileSync(l.diff.diffPath).toString("base64"),media_type:"image/png"}),{text:i.join(`
566
+ [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}=zs(),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 l=a.value;i.push("",`--- Iteration ${l.iteration} ---`,`Screenshot: ${l.path}`),l.diff&&i.push(`Diff: ${l.diff.diffPercent}% changed (${l.diff.changedPixels} pixels)`,`Regions: ${l.diff.regions.map(u=>`${u.name}:${u.changedPercent}%`).join(", ")}`);let c=[{path:l.path,base64:l.base64,media_type:l.media_type}];return l.diff?.diffPath&&c.push({path:l.diff.diffPath,base64:Sn.readFileSync(l.diff.diffPath).toString("base64"),media_type:"image/png"}),{text:i.join(`
567
567
  `),images:c}}return{text:i.join(`
568
568
  `)+`
569
569
 
570
- No changes detected within timeout.`,images:r.value?.base64?[{path:r.value.path,base64:r.value.base64,media_type:"image/png"}]:[]}}catch(s){return`ERROR: ${s.message}`}case"design_tokens":try{let{extractDesignTokens:s}=zs(),o=s(e.image,{sampleRate:e.sample_rate}),r=o.colors.slice(0,12).map(a=>` ${a.hex} ${a.rgb.padEnd(20)} ${a.frequency.toString().padStart(5)}% ${a.category}`).join(`
571
- `),i=o.spacing.length?o.spacing.map(a=>` ${a.px}px (${a.occurrences} occurrences)`).join(`
572
- `):" No clear spacing pattern detected";return`DESIGN TOKENS \u2014 extracted from ${o.dimensions.width}\xD7${o.dimensions.height} image
573
- Source: ${o.imagePath}
570
+ 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}=zs(),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(`
571
+ `),i=s.spacing.length?s.spacing.map(a=>` ${a.px}px (${a.occurrences} occurrences)`).join(`
572
+ `):" No clear spacing pattern detected";return`DESIGN TOKENS \u2014 extracted from ${s.dimensions.width}\xD7${s.dimensions.height} image
573
+ Source: ${s.imagePath}
574
574
 
575
575
  Dominant Colors:
576
576
  ${r}
@@ -581,102 +581,102 @@ ${i}
581
581
  Use these values to:
582
582
  - Compare against CSS variables / design system tokens
583
583
  - Identify inconsistent colors or spacing
584
- - Generate a color palette from the rendered output`}catch(s){return`ERROR: ${s.message}`}case"design_compare":try{let{designCompare:s}=zs(),o=await s(e.url,e.reference,{width:e.width,height:e.height,threshold:e.threshold}),r=o.regions.filter(i=>i.changedPercent>.5).slice(0,6).map(i=>` ${i.name}: ${i.changedPercent}% deviation`).join(`
585
- `)||" All regions match within tolerance";return{text:`DESIGN COMPARISON \u2014 ${o.diffPercent}% deviation from reference
586
- Reference: ${o.referencePath}
587
- Live: ${o.livePath}
588
- Diff: ${o.diffPath}
589
- Annotated: ${o.annotatedPath}
584
+ - Generate a color palette from the rendered output`}catch(o){return`ERROR: ${o.message}`}case"design_compare":try{let{designCompare:o}=zs(),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(`
585
+ `)||" All regions match within tolerance";return{text:`DESIGN COMPARISON \u2014 ${s.diffPercent}% deviation from reference
586
+ Reference: ${s.referencePath}
587
+ Live: ${s.livePath}
588
+ Diff: ${s.diffPath}
589
+ Annotated: ${s.annotatedPath}
590
590
 
591
- Pixel deviation: ${o.changedPixels.toLocaleString()} / ${o.totalPixels.toLocaleString()}
591
+ Pixel deviation: ${s.changedPixels.toLocaleString()} / ${s.totalPixels.toLocaleString()}
592
592
 
593
593
  Regional breakdown:
594
594
  ${r}
595
595
 
596
- [Three images attached: live screenshot, pixel diff, annotated deviation map]`,images:[{path:o.livePath,base64:o.liveBase64,media_type:"image/png"},{path:o.diffPath,base64:o.diffBase64,media_type:"image/png"},{path:o.annotatedPath,base64:o.annotatedBase64,media_type:"image/png"}]}}catch(s){return`ERROR: ${s.message}`}case"ask_user":{let{question:s,options:o=[]}=e;return $d?new Promise(r=>{oo=()=>r("CANCELLED"),$d(s,o).then(i=>{oo=null,r(i||"User did not answer")})}):new Promise(r=>{let i=require("readline").createInterface({input:process.stdin,output:process.stdout});oo=()=>{i.close(),r("CANCELLED")};let a=o.length>0?`
597
- ${o.map((l,c)=>` ${c+1}. ${l}`).join(`
596
+ [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 $d?new Promise(r=>{oo=()=>r("CANCELLED"),$d(o,s).then(i=>{oo=null,r(i||"User did not answer")})}):new Promise(r=>{let i=require("readline").createInterface({input:process.stdin,output:process.stdout});oo=()=>{i.close(),r("CANCELLED")};let a=s.length>0?`
597
+ ${s.map((l,c)=>` ${c+1}. ${l}`).join(`
598
598
  `)}
599
599
  `:"";console.log(`
600
- ${ye.cyan}${ye.bold} ? ${s}${ye.reset}${a}`),i.question(`${ye.cyan} > ${ye.reset}`,l=>{oo=null,i.close(),r(l.trim()||"(no response)")})})}case"git_status":{if(!await md())return"ERROR: Not a git repository";let s=await Sb()||"(detached)",o=await WR();if(o.length===0)return`Branch: ${s}
601
- Clean working tree (no changes)`;let r=[`Branch: ${s}`,`Changed files (${o.length}):`];for(let i of o){let a=i.status==="M"?"modified":i.status==="A"?"added":i.status==="D"?"deleted":i.status==="??"?"untracked":i.status;r.push(` ${a}: ${i.file}`)}return r.join(`
602
- `)}case"git_diff":{if(!await md())return"ERROR: Not a git repository";let s;if(e.file){let o=["diff"];e.staged&&o.push("--cached"),o.push("--",e.file);try{s=execFileSync("git",o,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()}catch{s=""}}else s=await HR(!!e.staged);return s||"(no diff)"}case"git_log":{if(!await md())return"ERROR: Not a git repository";let o=["log","--oneline",`-${Math.min(e.count||10,50)}`];e.file&&o.push("--",e.file);try{return execFileSync("git",o,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()||"(no commits)"}catch{return"(no commits)"}}case"task_list":{let{createTasks:s,updateTask:o,getTaskList:r,renderTaskList:i,hasActiveTasks:a}=Yu(),{getActiveTaskProgress:l}=xt(),c=l();switch(e.action){case"create":{if(!e.name||!e.tasks)return"ERROR: task_list create requires name and tasks";let u=s(e.name,e.tasks);return c||console.log(`
600
+ ${ye.cyan}${ye.bold} ? ${o}${ye.reset}${a}`),i.question(`${ye.cyan} > ${ye.reset}`,l=>{oo=null,i.close(),r(l.trim()||"(no response)")})})}case"git_status":{if(!await md())return"ERROR: Not a git repository";let o=await Sb()||"(detached)",s=await WR();if(s.length===0)return`Branch: ${o}
601
+ 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(`
602
+ `)}case"git_diff":{if(!await md())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 HR(!!e.staged);return o||"(no diff)"}case"git_log":{if(!await md())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}=Yu(),{getActiveTaskProgress:l}=xt(),c=l();switch(e.action){case"create":{if(!e.name||!e.tasks)return"ERROR: task_list create requires name and tasks";let u=o(e.name,e.tasks);return c||console.log(`
603
603
  `+i()),`Created task list "${e.name}" with ${u.length} tasks:
604
604
  `+u.map(d=>` ${d.id}: ${d.description}`).join(`
605
- `)}case"update":return!e.task_id||!e.status?"ERROR: task_list update requires task_id and status":o(e.task_id,e.status,e.result)?(c||console.log(`
605
+ `)}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)?(c||console.log(`
606
606
  `+i()),`Updated ${e.task_id}: ${e.status}${e.result?" \u2014 "+e.result:""}`):`ERROR: Task not found: ${e.task_id}`;case"get":{let u=r();return u.tasks.length===0?"No active tasks":(c||console.log(`
607
- `+i()),JSON.stringify(u,null,2))}default:return`ERROR: Unknown task_list action: ${e.action}. Use: create, update, get`}}case"spawn_agents":{let{executeSpawnAgents:s,executeSpawnAgentsBackground:o}=td();return e.agents?.some(r=>r.background)?o(e):s(e)}case"switch_model":{let{setActiveModel:s,getActiveProviderName:o,getActiveModelId:r}=vt();return s(e.model)?`Switched to ${o()}:${r()}`:`ERROR: Unknown model: ${e.model}. Use /providers to see available models.`}case"gh_run_list":{let s=Math.min(e.limit||10,30),o=["run","list","--limit",String(s),"--json","databaseId,status,conclusion,name,headBranch,createdAt,updatedAt,event"];e.workflow&&o.push("--workflow",e.workflow),e.branch&&o.push("--branch",e.branch),e.status&&o.push("--status",e.status);try{let{stdout:r}=await so("gh",o,{cwd:process.cwd(),timeout:3e4}),i=JSON.parse(r||"[]");return i.length===0?"No workflow runs found.":i.map(l=>{let c=l.conclusion||l.status||"unknown",u=c==="success"?"\u2713":c==="failure"?"\u2717":c==="in_progress"?"\u283F":"\u25CB",d=l.updatedAt?new Date(l.updatedAt).toISOString().slice(0,16).replace("T"," "):"";return`${u} [${l.databaseId}] ${l.name} \xB7 ${l.headBranch} \xB7 ${c} \xB7 ${d}`}).join(`
607
+ `+i()),JSON.stringify(u,null,2))}default:return`ERROR: Unknown task_list action: ${e.action}. Use: create, update, get`}}case"spawn_agents":{let{executeSpawnAgents:o,executeSpawnAgentsBackground:s}=td();return e.agents?.some(r=>r.background)?s(e):o(e)}case"switch_model":{let{setActiveModel:o,getActiveProviderName:s,getActiveModelId:r}=vt();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 so("gh",s,{cwd:process.cwd(),timeout:3e4}),i=JSON.parse(r||"[]");return i.length===0?"No workflow runs found.":i.map(l=>{let c=l.conclusion||l.status||"unknown",u=c==="success"?"\u2713":c==="failure"?"\u2717":c==="in_progress"?"\u283F":"\u25CB",d=l.updatedAt?new Date(l.updatedAt).toISOString().slice(0,16).replace("T"," "):"";return`${u} [${l.databaseId}] ${l.name} \xB7 ${l.headBranch} \xB7 ${c} \xB7 ${d}`}).join(`
608
608
  `)}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(`
609
609
  `)[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 so("gh",["run","view",String(e.run_id),"--log"],{cwd:process.cwd(),timeout:6e4,maxBuffer:5242880});return i.substring(0,8e3)+(i.length>8e3?`
610
- ...(truncated)`:"")}let{stdout:s}=await so("gh",["run","view",String(e.run_id),"--json","status,conclusion,name,headBranch,createdAt,updatedAt,jobs"],{cwd:process.cwd(),timeout:3e4}),o=JSON.parse(s),r=[`Run: ${o.name} [${e.run_id}]`,`Branch: ${o.headBranch} Status: ${o.conclusion||o.status}`,`Started: ${o.createdAt} Finished: ${o.updatedAt||"\u2014"}`,"","Jobs:"];for(let i of o.jobs||[]){let a=i.conclusion==="success"?"\u2713":i.conclusion==="failure"?"\u2717":"\u25CB";r.push(` ${a} ${i.name} (${i.conclusion||i.status})`);for(let l of i.steps||[]){if(l.conclusion==="failure"||l.conclusion==="skipped")continue;let c=l.conclusion==="success"?" \u2713":l.conclusion==="failure"?" \u2717":" \u25CB";r.push(` ${c} ${l.name}`)}}return r.join(`
611
- `)}catch(s){return`ERROR: ${(s.stderr||s.message||"").toString().split(`
612
- `)[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:s}=vr(),o=e.branch||await Sb()||"main";if(!/^[\w./-]+$/.test(o))return"ERROR: invalid branch name";let r=["workflow","run",e.workflow,"--ref",o];if(e.inputs)for(let[a,l]of Object.entries(e.inputs)){if(!/^[\w-]+$/.test(a))return`ERROR: invalid input key: ${a}`;r.push("-f",`${a}=${l}`)}if(console.log(`
613
- ${ye.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${o}${ye.reset}`),!await s(" Trigger?"))return"CANCELLED: User declined to trigger workflow.";try{return await so("gh",r,{cwd:process.cwd(),timeout:3e4}),`Workflow "${e.workflow}" triggered on branch "${o}". Check status with gh_run_list.`}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
614
- `)[0]}`}}case"k8s_pods":{let s=e.namespace?`-n ${e.namespace}`:"-A",o=e.label?`-l ${e.label}`:"",r=Jr(`get pods ${s} ${o} -o wide`.trim(),e);try{let{stdout:i,stderr:a}=await gt(r,{timeout:3e4,maxBuffer:2097152});return(i||a||"(no pods)").trim()}catch(i){let a=(i.stderr||i.message||"").toString().split(`
615
- `)[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 s=e.namespace||"default",o=e.tail||100,r=`logs ${e.pod} -n ${s} --tail=${o}`;e.since&&(r+=` --since=${e.since}`),e.container&&(r+=` -c ${e.container}`);let i=Jr(r,e);try{let{stdout:a,stderr:l}=await gt(i,{timeout:6e4,maxBuffer:5242880}),c=(a||l||"(no logs)").trim();return c.substring(0,2e4)+(c.length>2e4?`
610
+ ...(truncated)`:"")}let{stdout:o}=await so("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 l of i.steps||[]){if(l.conclusion==="failure"||l.conclusion==="skipped")continue;let c=l.conclusion==="success"?" \u2713":l.conclusion==="failure"?" \u2717":" \u25CB";r.push(` ${c} ${l.name}`)}}return r.join(`
611
+ `)}catch(o){return`ERROR: ${(o.stderr||o.message||"").toString().split(`
612
+ `)[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}=vr(),s=e.branch||await Sb()||"main";if(!/^[\w./-]+$/.test(s))return"ERROR: invalid branch name";let r=["workflow","run",e.workflow,"--ref",s];if(e.inputs)for(let[a,l]of Object.entries(e.inputs)){if(!/^[\w-]+$/.test(a))return`ERROR: invalid input key: ${a}`;r.push("-f",`${a}=${l}`)}if(console.log(`
613
+ ${ye.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${s}${ye.reset}`),!await o(" Trigger?"))return"CANCELLED: User declined to trigger workflow.";try{return await so("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(`
614
+ `)[0]}`}}case"k8s_pods":{let o=e.namespace?`-n ${e.namespace}`:"-A",s=e.label?`-l ${e.label}`:"",r=Jr(`get pods ${o} ${s} -o wide`.trim(),e);try{let{stdout:i,stderr:a}=await gt(r,{timeout:3e4,maxBuffer:2097152});return(i||a||"(no pods)").trim()}catch(i){let a=(i.stderr||i.message||"").toString().split(`
615
+ `)[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=Jr(r,e);try{let{stdout:a,stderr:l}=await gt(i,{timeout:6e4,maxBuffer:5242880}),c=(a||l||"(no logs)").trim();return c.substring(0,2e4)+(c.length>2e4?`
616
616
  ...(truncated)`:"")}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
617
- `)[0]}`}}case"k8s_exec":{if(!e.pod)return"ERROR: pod is required";if(!e.command)return"ERROR: command is required";let s=e.namespace||"default";if(console.log(`
618
- ${ye.yellow} \u26A0 kubectl exec into pod: ${e.pod} (ns: ${s})${ye.reset}`),console.log(`${ye.dim} Command: ${e.command}${ye.reset}`),!await vn(" Execute in pod?"))return"CANCELLED: User declined.";let r=`exec ${e.pod} -n ${s}`;e.container&&(r+=` -c ${e.container}`),r+=` -- sh -c ${JSON.stringify(e.command)}`;let i=Jr(r,e);try{let{stdout:a,stderr:l}=await gt(i,{timeout:6e4,maxBuffer:2097152});return(a||l||"(no output)").trim()}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
619
- `)[0]}`}}case"k8s_apply":{if(!e.file)return"ERROR: file is required";let s=!!e.dry_run;if(!s){let i=e.file;if(console.log(`
620
- ${ye.yellow} \u26A0 kubectl apply: ${i}${e.namespace?` (ns: ${e.namespace})`:""}${ye.reset}`),!await vn(" Apply to cluster?"))return"CANCELLED: User declined."}let o=`apply -f ${e.file}`;e.namespace&&(o+=` -n ${e.namespace}`),s&&(o+=" --dry-run=client");let r=Jr(o,e);try{let{stdout:i,stderr:a}=await gt(r,{timeout:12e4,maxBuffer:2097152});return(i||a||"(no output)").trim()}catch(i){return`ERROR: ${(i.stderr||i.message||"").toString().split(`
621
- `)[0]}`}}case"k8s_rollout":{if(!e.action)return"ERROR: action is required";if(!e.deployment)return"ERROR: deployment is required";let s=e.namespace||"default";if(e.action==="restart"||e.action==="undo"){let a=e.action==="restart"?"Rolling restart":"Rollback (undo)";if(console.log(`
622
- ${ye.yellow} \u26A0 ${a}: deployment/${e.deployment} (ns: ${s})${ye.reset}`),!await vn(` ${a}?`))return"CANCELLED: User declined."}let r=`rollout ${e.action} deployment/${e.deployment} -n ${s}`,i=Jr(r,e);try{let{stdout:a,stderr:l}=await gt(i,{timeout:12e4,maxBuffer:2097152});return(a||l||"(no output)").trim()}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
623
- `)[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:s,readDocument:o}=cd(),{name:r,content:i,mode:a}=e;if(a==="create"&&o(r).content)return`ERROR: Document "${r}" already exists. Use mode "update" to overwrite.`;if(a==="append"){let l=o(r),c=l.content?l.content+`
624
-
625
- `+i:i;return s(r,c),`Appended to brain document: ${r}.md`}return s(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 s;try{s=pn(e.server)}catch(M){return`ERROR: ${M.message}`}let o=e.command,r=!!e.sudo,i=(e.timeout||30)*1e3,a=jR(o);if(a)return/\bsed\s+-n\s+['"]?\d+,\d+p/.test(o)?`BLOCKED: sed -n line-range is blocked (floods context). To read specific lines from a remote file use:
617
+ `)[0]}`}}case"k8s_exec":{if(!e.pod)return"ERROR: pod is required";if(!e.command)return"ERROR: command is required";let o=e.namespace||"default";if(console.log(`
618
+ ${ye.yellow} \u26A0 kubectl exec into pod: ${e.pod} (ns: ${o})${ye.reset}`),console.log(`${ye.dim} Command: ${e.command}${ye.reset}`),!await vn(" Execute in pod?"))return"CANCELLED: User declined.";let r=`exec ${e.pod} -n ${o}`;e.container&&(r+=` -c ${e.container}`),r+=` -- sh -c ${JSON.stringify(e.command)}`;let i=Jr(r,e);try{let{stdout:a,stderr:l}=await gt(i,{timeout:6e4,maxBuffer:2097152});return(a||l||"(no output)").trim()}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
619
+ `)[0]}`}}case"k8s_apply":{if(!e.file)return"ERROR: file is required";let o=!!e.dry_run;if(!o){let i=e.file;if(console.log(`
620
+ ${ye.yellow} \u26A0 kubectl apply: ${i}${e.namespace?` (ns: ${e.namespace})`:""}${ye.reset}`),!await vn(" 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=Jr(s,e);try{let{stdout:i,stderr:a}=await gt(r,{timeout:12e4,maxBuffer:2097152});return(i||a||"(no output)").trim()}catch(i){return`ERROR: ${(i.stderr||i.message||"").toString().split(`
621
+ `)[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(`
622
+ ${ye.yellow} \u26A0 ${a}: deployment/${e.deployment} (ns: ${o})${ye.reset}`),!await vn(` ${a}?`))return"CANCELLED: User declined."}let r=`rollout ${e.action} deployment/${e.deployment} -n ${o}`,i=Jr(r,e);try{let{stdout:a,stderr:l}=await gt(i,{timeout:12e4,maxBuffer:2097152});return(a||l||"(no output)").trim()}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
623
+ `)[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}=cd(),{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 l=s(r),c=l.content?l.content+`
624
+
625
+ `+i:i;return o(r,c),`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=pn(e.server)}catch(M){return`ERROR: ${M.message}`}let s=e.command,r=!!e.sudo,i=(e.timeout||30)*1e3,a=jR(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:
626
626
  grep -n "pattern" /path/to/file -A 50
627
627
  or to read the whole file:
628
628
  cat /path/to/file
629
629
  NEVER use sed -n again \u2014 it will always be blocked.`:`BLOCKED: Remote command matches SSH secret-exposure pattern: ${a}
630
- HINT: Do not read .env, credentials, or private key files via ssh_exec \u2014 secrets would appear in tool output. Reference variable names or file paths instead.`;if(o=o.replace(/(-[BAC])\s*(\d+)/g,(M,K,z)=>{let X=Math.min(Number(z),20);return`${K} ${X}`}),o=o.replace(/(--(?:before|after|context)=)(\d+)/g,(M,K,z)=>K+Math.min(Number(z),20)),/\b(rm|rmdir|mv|cp|chmod|chown|dd|mkfs|systemctl\s+(start|stop|restart|reload|enable|disable)|dnf\s+(install|remove|update|upgrade)|yum\s+(install|remove)|apt(-get)?\s+(install|remove|purge)|pip\s+install|pip3\s+install|firewall-cmd\s+--permanent|semanage|setsebool|passwd|userdel|useradd|nginx\s+-s\s+(reload|stop)|service\s+\w+\s+(start|stop|restart))\b/.test(o)){let M=s.user?`${s.user}@${s.host}`:s.host;if(console.log(`
631
- ${ye.yellow} \u26A0 Remote command on ${M}: ${o}${ye.reset}`),!await vn(" Execute on remote server?"))return"CANCELLED: User declined to execute remote command."}let{stdout:c,stderr:u,exitCode:d,error:f}=await Bt(s,o,{timeout:i,sudo:r}),p=[c,u].filter(Boolean).join(`
632
- `).trim();if(d!==0){if(/no such file or directory/i.test(p)){let K=p.match(/['"]?([/\w._-]+\.\w+)['"]?:\s*No such file/i),z=o.match(/(?:cat|head|tail|less|grep\s+\S+\s+|ls\s+|stat\s+|wc\s+|file\s+)['"]?([/\w._-]+)['"]?/),X=K&&K[1]||z&&z[1];if(X)try{let{remoteAutoFixPath:ae}=qo(),Z=X.startsWith("/")?X.split("/").slice(0,-1).join("/").replace(/\/[^/]+$/,"")||"/":"/home/"+(s.user||"root"),oe=await ae(s,Z,X);if(oe.fixedPath){let Ke=o.replace(X,oe.fixedPath);console.log(`${ye.dim} \u2713 remote auto-fix: ${X} \u2192 ${oe.fixedPath}${ye.reset}`);let Ee=await Bt(s,Ke,{timeout:i,sudo:r}),G=[Ee.stdout,Ee.stderr].filter(Boolean).join(`
630
+ HINT: Do not read .env, credentials, or private key files via ssh_exec \u2014 secrets would appear in tool output. Reference variable names or file paths instead.`;if(s=s.replace(/(-[BAC])\s*(\d+)/g,(M,K,z)=>{let X=Math.min(Number(z),20);return`${K} ${X}`}),s=s.replace(/(--(?:before|after|context)=)(\d+)/g,(M,K,z)=>K+Math.min(Number(z),20)),/\b(rm|rmdir|mv|cp|chmod|chown|dd|mkfs|systemctl\s+(start|stop|restart|reload|enable|disable)|dnf\s+(install|remove|update|upgrade)|yum\s+(install|remove)|apt(-get)?\s+(install|remove|purge)|pip\s+install|pip3\s+install|firewall-cmd\s+--permanent|semanage|setsebool|passwd|userdel|useradd|nginx\s+-s\s+(reload|stop)|service\s+\w+\s+(start|stop|restart))\b/.test(s)){let M=o.user?`${o.user}@${o.host}`:o.host;if(console.log(`
631
+ ${ye.yellow} \u26A0 Remote command on ${M}: ${s}${ye.reset}`),!await vn(" Execute on remote server?"))return"CANCELLED: User declined to execute remote command."}let{stdout:c,stderr:u,exitCode:d,error:f}=await Bt(o,s,{timeout:i,sudo:r}),p=[c,u].filter(Boolean).join(`
632
+ `).trim();if(d!==0){if(/no such file or directory/i.test(p)){let K=p.match(/['"]?([/\w._-]+\.\w+)['"]?:\s*No such file/i),z=s.match(/(?:cat|head|tail|less|grep\s+\S+\s+|ls\s+|stat\s+|wc\s+|file\s+)['"]?([/\w._-]+)['"]?/),X=K&&K[1]||z&&z[1];if(X)try{let{remoteAutoFixPath:ae}=qo(),Z=X.startsWith("/")?X.split("/").slice(0,-1).join("/").replace(/\/[^/]+$/,"")||"/":"/home/"+(o.user||"root"),oe=await ae(o,Z,X);if(oe.fixedPath){let Ke=s.replace(X,oe.fixedPath);console.log(`${ye.dim} \u2713 remote auto-fix: ${X} \u2192 ${oe.fixedPath}${ye.reset}`);let Ee=await Bt(o,Ke,{timeout:i,sudo:r}),G=[Ee.stdout,Ee.stderr].filter(Boolean).join(`
633
633
  `).trim();if(Ee.exitCode===0)return`${oe.message}
634
634
  ${G}`||"(command completed, no output)"}else if(oe.message)return`EXIT ${d}
635
635
  ${f||p}
636
636
 
637
637
  ${oe.message}`}catch{}}return`EXIT ${d}
638
- ${f||p||"(no output)"}`}let h=/\bgrep\b/.test(o),g=p;h&&(g=g.split(`
638
+ ${f||p||"(no output)"}`}let h=/\bgrep\b/.test(s),g=p;h&&(g=g.split(`
639
639
  `).filter(M=>M!=="--").join(`
640
640
  `));let w=h?60:100,k=g.split(`
641
641
  `);k.length>w&&(g=`(${k.length-w} earlier lines omitted \u2014 showing last ${w})
642
642
  `+k.slice(-w).join(`
643
643
  `));let T=4,$=g.split(`
644
644
  `),R=[],C=0;for(;C<$.length;){let M=C+1;for(;M<$.length&&$[M]===$[C];)M++;let K=M-C;if(R.push($[C]),K>T)R.push(`... (${K-1} identical lines omitted)`);else for(let z=1;z<K;z++)R.push($[C]);C=M}return R.join(`
645
- `)||"(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 s;try{s=pn(e.server)}catch(i){return`ERROR: ${i.message}`}let o=s.user?`${s.user}@${s.host}`:s.host;if(console.log(`
646
- ${ye.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${o}:${e.remote_path}${ye.reset}`),!await vn(" Upload to remote server?"))return"CANCELLED: User declined upload.";try{let i=await VR(s,e.local_path,e.remote_path);try{qo().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 s;try{s=pn(e.server)}catch(o){return`ERROR: ${o.message}`}try{return await Cb(s,e.remote_path,e.local_path)}catch(o){if(/no such file|not found/i.test(o.message))try{let{remoteAutoFixPath:r}=qo(),i=e.remote_path.split("/").slice(0,-1).join("/")||"/",a=await r(s,i,e.remote_path);if(a.fixedPath){console.log(`${ye.dim} \u2713 remote auto-fix: ${e.remote_path} \u2192 ${a.fixedPath}${ye.reset}`);let l=await Cb(s,a.fixedPath,e.local_path);return`${a.message}
647
- ${l}`}if(a.message)return`ERROR: ${o.message}
645
+ `)||"(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=pn(e.server)}catch(i){return`ERROR: ${i.message}`}let s=o.user?`${o.user}@${o.host}`:o.host;if(console.log(`
646
+ ${ye.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${s}:${e.remote_path}${ye.reset}`),!await vn(" Upload to remote server?"))return"CANCELLED: User declined upload.";try{let i=await VR(o,e.local_path,e.remote_path);try{qo().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=pn(e.server)}catch(s){return`ERROR: ${s.message}`}try{return await Cb(o,e.remote_path,e.local_path)}catch(s){if(/no such file|not found/i.test(s.message))try{let{remoteAutoFixPath:r}=qo(),i=e.remote_path.split("/").slice(0,-1).join("/")||"/",a=await r(o,i,e.remote_path);if(a.fixedPath){console.log(`${ye.dim} \u2713 remote auto-fix: ${e.remote_path} \u2192 ${a.fixedPath}${ye.reset}`);let l=await Cb(o,a.fixedPath,e.local_path);return`${a.message}
647
+ ${l}`}if(a.message)return`ERROR: ${s.message}
648
648
 
649
- ${a.message}`}catch{}return`ERROR: ${o.message}`}}case"remote_agent":{let s=require("path").join(process.cwd(),".nex","servers.json"),o=null;try{o=JSON.parse(require("fs").readFileSync(s,"utf-8"))[e.server]||null}catch{}let r=o?`${o.user||"root"}@${o.host}`:e.server,i=o?.key?["-i",o.key]:[],a=(e.project_path||o?.home||"~").replace(/[^a-zA-Z0-9_/~.-]/g,""),l=(e.model||"").replace(/[^a-zA-Z0-9_:.-]/g,""),u=['TMPFILE=$(mktemp /tmp/nexcode-XXXXXX.txt) && chmod 600 "$TMPFILE"',`echo "${Buffer.from(e.task).toString("base64")}" | base64 -d > "$TMPFILE"`,`cd "${a}" 2>/dev/null || true`,l?`nex-code --prompt-file "$TMPFILE" --auto --model "${l}" 2>&1`:'nex-code --prompt-file "$TMPFILE" --auto 2>&1',"EXIT_CODE=$?",'rm -f "$TMPFILE"',"exit $EXIT_CODE"].join(" && "),{spawnSync:d}=require("child_process"),f=d("ssh",[...i,"-o","StrictHostKeyChecking=yes","-o","ConnectTimeout=10",r,`bash -c '${u}'`],{encoding:"utf-8",maxBuffer:10*1024*1024,timeout:3e5});if(f.error)return`ERROR: SSH connection failed: ${f.error.message}`;let p=(f.stdout||"")+(f.stderr||"");return f.status!==0?`Remote nex-code exited with code ${f.status}.
650
- ${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 s=_d(e.service);if(s)return s;let o=["status","start","stop","restart","reload","enable","disable"];if(!o.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${o.join(", ")}`;let r=!e.server||e.server==="local"||e.server==="localhost",i=e.action==="status",a=null;if(!r)try{a=pn(e.server)}catch(u){return`ERROR: ${u.message}`}if(!i){let u=r?"local machine":a.user?`${a.user}@${a.host}`:a.host;if(console.log(`
649
+ ${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,""),l=(e.model||"").replace(/[^a-zA-Z0-9_:.-]/g,""),u=['TMPFILE=$(mktemp /tmp/nexcode-XXXXXX.txt) && chmod 600 "$TMPFILE"',`echo "${Buffer.from(e.task).toString("base64")}" | base64 -d > "$TMPFILE"`,`cd "${a}" 2>/dev/null || true`,l?`nex-code --prompt-file "$TMPFILE" --auto --model "${l}" 2>&1`:'nex-code --prompt-file "$TMPFILE" --auto 2>&1',"EXIT_CODE=$?",'rm -f "$TMPFILE"',"exit $EXIT_CODE"].join(" && "),{spawnSync:d}=require("child_process"),f=d("ssh",[...i,"-o","StrictHostKeyChecking=yes","-o","ConnectTimeout=10",r,`bash -c '${u}'`],{encoding:"utf-8",maxBuffer:10*1024*1024,timeout:3e5});if(f.error)return`ERROR: SSH connection failed: ${f.error.message}`;let p=(f.stdout||"")+(f.stderr||"");return f.status!==0?`Remote nex-code exited with code ${f.status}.
650
+ ${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=_d(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=pn(e.server)}catch(u){return`ERROR: ${u.message}`}if(!i){let u=r?"local machine":a.user?`${a.user}@${a.host}`:a.host;if(console.log(`
651
651
  ${ye.yellow} \u26A0 Service: systemctl ${e.action} ${e.service} on ${u}${ye.reset}`),!await vn(" Execute?"))return"CANCELLED: User declined service action."}let l=e.service.includes(".")?e.service:`${e.service}.service`,c=`systemctl ${e.action} ${He(l)}`;if(r){let d=e.action!=="status"?`sudo ${c}`:c;try{let{stdout:f,stderr:p}=await gt(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}
652
652
  ${p}`}}else{let{stdout:u,stderr:d,exitCode:f,error:p}=await Bt(a,c,{timeout:15e3,sudo:!0}),h=[u,d].filter(Boolean).join(`
653
653
  `).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}
654
- ${p||h||"(no output)"}`:h||`systemctl ${e.action} ${e.service}: OK`}}case"service_logs":{if(!e.service)return"ERROR: service is required";let s=_d(e.service);if(s)return s;let o=!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 ${He(e.since)}`:"",l=e.follow?"-f":"",c=`journalctl -u ${He(i)} -n ${r} ${a} ${l} --no-pager`.trim().replace(/\s+/g," ");if(o)try{let{stdout:w,stderr:k}=await gt(c,{timeout:15e3});return(w||k||"(no log output)").trim()}catch(w){return`EXIT ${w.code||1}
654
+ ${p||h||"(no output)"}`:h||`systemctl ${e.action} ${e.service}: OK`}}case"service_logs":{if(!e.service)return"ERROR: service is required";let o=_d(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 ${He(e.since)}`:"",l=e.follow?"-f":"",c=`journalctl -u ${He(i)} -n ${r} ${a} ${l} --no-pager`.trim().replace(/\s+/g," ");if(s)try{let{stdout:w,stderr:k}=await gt(c,{timeout:15e3});return(w||k||"(no log output)").trim()}catch(w){return`EXIT ${w.code||1}
655
655
  ${(w.stderr||w.message||"").toString().trim()}`}let u;try{u=pn(e.server)}catch(w){return`ERROR: ${w.message}`}let{stdout:d,stderr:f,exitCode:p,error:h}=await Bt(u,c,{timeout:2e4}),g=[d,f].filter(Boolean).join(`
656
656
  `).trim();return p!==0?`EXIT ${p}
657
- ${h||g||"(no output)"}`:g||"(no log output)"}case"container_list":{let s=!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(s)try{let{stdout:f,stderr:p}=await gt(r,{timeout:1e4});return(f||p||"(no containers)").trim()}catch(f){return`EXIT ${f.code||1}
657
+ ${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 gt(r,{timeout:1e4});return(f||p||"(no containers)").trim()}catch(f){return`EXIT ${f.code||1}
658
658
  ${(f.stderr||f.message||"").toString().trim()}`}let i;try{i=pn(e.server)}catch(f){return`ERROR: ${f.message}`}let{stdout:a,stderr:l,exitCode:c,error:u}=await Bt(i,r,{timeout:15e3}),d=[a,l].filter(Boolean).join(`
659
659
  `).trim();return c!==0?`EXIT ${c}
660
- ${u||d}`:d||"(no containers)"}case"container_logs":{if(!e.container)return"ERROR: container is required";let s=!e.server||e.server==="local"||e.server==="localhost",o=e.lines||50,r=e.since?`--since "${e.since}"`:"",i=`docker logs --tail ${o} ${r} ${e.container} 2>&1`.trim().replace(/\s+/g," ");if(s)try{let{stdout:p,stderr:h}=await gt(i,{timeout:15e3});return(p||h||"(no log output)").trim()}catch(p){return`EXIT ${p.code||1}
660
+ ${u||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 gt(i,{timeout:15e3});return(p||h||"(no log output)").trim()}catch(p){return`EXIT ${p.code||1}
661
661
  ${(p.stderr||p.message||"").toString().trim()}`}let a;try{a=pn(e.server)}catch(p){return`ERROR: ${p.message}`}let{stdout:l,stderr:c,exitCode:u,error:d}=await Bt(a,i,{timeout:2e4}),f=[l,c].filter(Boolean).join(`
662
662
  `).trim();return u!==0?`EXIT ${u}
663
- ${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 s=!e.server||e.server==="local"||e.server==="localhost",o=/^(cat|ls|echo|env|printenv|df|du|ps|id|whoami|uname|hostname|date|pwd|which|find\s|head\s|tail\s|grep\s|curl\s+-[A-Za-z]*G|curl\s+https?:\/\/[^\s]+$)/;if(!n.autoConfirm&&!o.test(e.command.trim())){let h=s?"local":e.server;if(console.log(`
664
- ${ye.yellow} \u26A0 docker exec in ${e.container} on ${h}: ${e.command}${ye.reset}`),!await vn(" 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(s)try{let{stdout:h,stderr:g}=await gt(a,{timeout:3e4});return(h||g||"(no output)").trim()}catch(h){return`EXIT ${h.code||1}
663
+ ${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(`
664
+ ${ye.yellow} \u26A0 docker exec in ${e.container} on ${h}: ${e.command}${ye.reset}`),!await vn(" 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 gt(a,{timeout:3e4});return(h||g||"(no output)").trim()}catch(h){return`EXIT ${h.code||1}
665
665
  ${(h.stderr||h.message||"").toString().trim()}`}let l;try{l=pn(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:c,stderr:u,exitCode:d,error:f}=await Bt(l,a,{timeout:35e3}),p=[c,u].filter(Boolean).join(`
666
666
  `).trim();return d!==0?`EXIT ${d}
667
- ${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 s=["start","stop","restart","remove","inspect"];if(!s.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${s.join(", ")}`;let o=!e.server||e.server==="local"||e.server==="localhost";if(!(e.action==="inspect")&&!n.autoConfirm){let h=o?"local":e.server;if(console.log(`
668
- ${ye.yellow} \u26A0 docker ${e.action} ${e.container} on ${h}${ye.reset}`),!await vn(" Execute?"))return"CANCELLED: User declined."}let i=e.action==="remove"?"rm":e.action,a=e.action==="inspect"?`docker inspect ${e.container}`:`docker ${i} ${e.container}`;if(o)try{let{stdout:h,stderr:g}=await gt(a,{timeout:3e4});return(h||g||`docker ${e.action} ${e.container}: OK`).trim()}catch(h){return`EXIT ${h.code||1}
667
+ ${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(`
668
+ ${ye.yellow} \u26A0 docker ${e.action} ${e.container} on ${h}${ye.reset}`),!await vn(" 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 gt(a,{timeout:3e4});return(h||g||`docker ${e.action} ${e.container}: OK`).trim()}catch(h){return`EXIT ${h.code||1}
669
669
  ${(h.stderr||h.message||"").toString().trim()}`}let l;try{l=pn(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:c,stderr:u,exitCode:d,error:f}=await Bt(l,a,{timeout:35e3}),p=[c,u].filter(Boolean).join(`
670
670
  `).trim();return d!==0?`EXIT ${d}
671
- ${f||p}`:p||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...XR(e.config),...e},delete e.config,delete e._name}catch(u){return`ERROR: ${u.message}`}if(!e.server)return'ERROR: server is required (or use config: "<name>")';if(!e.remote_path)return"ERROR: remote_path is required";let s=e.method||"rsync";if(s==="rsync"&&!e.local_path)return"ERROR: local_path is required for rsync method";let o;try{o=pn(e.server)}catch(u){return`ERROR: ${u.message}`}let r=o.user?`${o.user}@${o.host}`:o.host;if(!e.dry_run&&!n.autoConfirm){if(s==="git"){let d=e.branch?` (branch: ${e.branch})`:"";console.log(`
671
+ ${f||p}`:p||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...XR(e.config),...e},delete e.config,delete e._name}catch(u){return`ERROR: ${u.message}`}if(!e.server)return'ERROR: server is required (or use config: "<name>")';if(!e.remote_path)return"ERROR: remote_path is required";let o=e.method||"rsync";if(o==="rsync"&&!e.local_path)return"ERROR: local_path is required for rsync method";let s;try{s=pn(e.server)}catch(u){return`ERROR: ${u.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(`
672
672
  ${ye.yellow} \u26A0 Deploy [git pull]: ${r}:${e.remote_path}${d}${ye.reset}`)}else{let d=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`;console.log(`
673
- ${ye.yellow} \u26A0 Deploy [rsync]: ${d} \u2192 ${r}:${e.remote_path}${ye.reset}`)}if(e.deploy_script&&console.log(`${ye.yellow} Then run: ${e.deploy_script}${ye.reset}`),e.health_check&&console.log(`${ye.yellow} Health check: ${e.health_check}${ye.reset}`),!await vn(" Proceed with deployment?"))return"CANCELLED: User declined."}let i="";if(s==="git"){let u=(e.branch||"").replace(/[^a-zA-Z0-9._\/-]/g,"");if(e.branch&&u!==e.branch)return`ERROR: Invalid branch name: ${e.branch}`;let d=(e.remote_path||"").replace(/'/g,"'\\''"),f=u?`cd '${d}' && git fetch origin && git checkout '${u}' && git pull origin '${u}'`:`cd '${d}' && git pull`;if(e.dry_run)return`DRY RUN [git]: would run on ${r}:
673
+ ${ye.yellow} \u26A0 Deploy [rsync]: ${d} \u2192 ${r}:${e.remote_path}${ye.reset}`)}if(e.deploy_script&&console.log(`${ye.yellow} Then run: ${e.deploy_script}${ye.reset}`),e.health_check&&console.log(`${ye.yellow} Health check: ${e.health_check}${ye.reset}`),!await vn(" Proceed with deployment?"))return"CANCELLED: User declined."}let i="";if(o==="git"){let u=(e.branch||"").replace(/[^a-zA-Z0-9._\/-]/g,"");if(e.branch&&u!==e.branch)return`ERROR: Invalid branch name: ${e.branch}`;let d=(e.remote_path||"").replace(/'/g,"'\\''"),f=u?`cd '${d}' && git fetch origin && git checkout '${u}' && git pull origin '${u}'`:`cd '${d}' && git pull`;if(e.dry_run)return`DRY RUN [git]: would run on ${r}:
674
674
  ${f}${e.deploy_script?`
675
- ${e.deploy_script}`:""}`;let{stdout:p,stderr:h,exitCode:g,error:w}=await Bt(o,f,{timeout:12e4});if(i=[p,h].filter(Boolean).join(`
675
+ ${e.deploy_script}`:""}`;let{stdout:p,stderr:h,exitCode:g,error:w}=await Bt(s,f,{timeout:12e4});if(i=[p,h].filter(Boolean).join(`
676
676
  `).trim(),g!==0)return`ERROR (git pull, exit ${g}):
677
- ${w||i}`}else{let u=o.key?`-e "ssh -i ${o.key.replace(/^~/,require("os").homedir())}${o.port&&Number(o.port)!==22?` -p ${o.port}`:""}"`:o.port&&Number(o.port)!==22?`-e "ssh -p ${o.port}"`:"",d=(e.exclude||[]).map(g=>`--exclude="${g}"`).join(" "),f=e.dry_run?"--dry-run":"",p=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`,h=`rsync -avz --delete ${f} ${d} ${u} ${p} ${r}:${e.remote_path}`.trim().replace(/\s+/g," ");try{let{stdout:g,stderr:w}=await gt(h,{timeout:12e4});i=(g||w||"").trim()}catch(g){return`ERROR (rsync): ${(g.stderr||g.message||"").toString().trim()}`}if(e.dry_run)return`DRY RUN [rsync]:
678
- ${i||"(nothing to sync)"}`}let a="";if(e.deploy_script){let{stdout:u,stderr:d,exitCode:f,error:p}=await Bt(o,e.deploy_script,{timeout:12e4}),h=[u,d].filter(Boolean).join(`
679
- `).trim();if(f!==0)return`${s==="git"?"git pull":"rsync"} OK
677
+ ${w||i}`}else{let u=s.key?`-e "ssh -i ${s.key.replace(/^~/,require("os").homedir())}${s.port&&Number(s.port)!==22?` -p ${s.port}`:""}"`:s.port&&Number(s.port)!==22?`-e "ssh -p ${s.port}"`:"",d=(e.exclude||[]).map(g=>`--exclude="${g}"`).join(" "),f=e.dry_run?"--dry-run":"",p=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`,h=`rsync -avz --delete ${f} ${d} ${u} ${p} ${r}:${e.remote_path}`.trim().replace(/\s+/g," ");try{let{stdout:g,stderr:w}=await gt(h,{timeout:12e4});i=(g||w||"").trim()}catch(g){return`ERROR (rsync): ${(g.stderr||g.message||"").toString().trim()}`}if(e.dry_run)return`DRY RUN [rsync]:
678
+ ${i||"(nothing to sync)"}`}let a="";if(e.deploy_script){let{stdout:u,stderr:d,exitCode:f,error:p}=await Bt(s,e.deploy_script,{timeout:12e4}),h=[u,d].filter(Boolean).join(`
679
+ `).trim();if(f!==0)return`${o==="git"?"git pull":"rsync"} OK
680
680
 
681
681
  ERROR (deploy_script, exit ${f}):
682
682
  ${p||h}`;a=`
@@ -686,52 +686,52 @@ ${h||"(no output)"}`}let l="";if(e.health_check){let u=e.health_check.trim();if(
686
686
 
687
687
  Health check: \u2713 ${u} \u2192 ${p.status}`;else return l=`
688
688
 
689
- Health check FAILED: ${u} \u2192 HTTP ${p.status}`,(s==="git"?"git pull OK":"rsync OK")+i+a+l}catch(f){return l=`
689
+ Health check FAILED: ${u} \u2192 HTTP ${p.status}`,(o==="git"?"git pull OK":"rsync OK")+i+a+l}catch(f){return l=`
690
690
 
691
- Health check FAILED: ${u} \u2192 ${f.message}`,(s==="git"?"git pull OK":"rsync OK")+i+a+l}else{let{stdout:f,stderr:p,exitCode:h}=await Bt(o,u,{timeout:15e3}),g=[f,p].filter(Boolean).join(`
691
+ Health check FAILED: ${u} \u2192 ${f.message}`,(o==="git"?"git pull OK":"rsync OK")+i+a+l}else{let{stdout:f,stderr:p,exitCode:h}=await Bt(s,u,{timeout:15e3}),g=[f,p].filter(Boolean).join(`
692
692
  `).trim();if(h!==0)return l=`
693
693
 
694
- Health check FAILED (exit ${h}): ${g}`,(s==="git"?"git pull OK":"rsync OK")+i+a+l;l=`
694
+ Health check FAILED (exit ${h}): ${g}`,(o==="git"?"git pull OK":"rsync OK")+i+a+l;l=`
695
695
 
696
- Health check: \u2713 ${g||"(exit 0)"}`}}let c=s==="git"?`${r}:${e.remote_path}`:`${e.local_path} \u2192 ${r}:${e.remote_path}`;return`Deployed [${s}] ${c}
697
- ${i}${a}${l}`.trim()}case"deployment_status":{let s=JR(),o=e.config?[e.config]:Object.keys(s);if(o.length===0)return"No deploy configs found. Create .nex/deploy.json to configure deployments.";let r=[];for(let i of o){let a=s[i];if(!a){r.push(`${i}: NOT FOUND`);continue}try{let l=pn(a.server||i),u=(await Bt(l,"echo OK",{timeout:1e4})).stdout.trim()==="OK",d="unknown";if(u&&a.deploy_script){let p=a.deploy_script.match(/systemctl\s+\w+\s+(\S+)/);if(p)try{d=(await Bt(l,`systemctl is-active ${p[1]}`,{timeout:1e4})).stdout.trim()}catch{d="inactive"}}let f="N/A";if(a.health_check){let p=a.health_check.trim();if(/^https?:\/\//.test(p))try{let h=require("node-fetch"),g=await Promise.race([h(p),new Promise((w,k)=>setTimeout(()=>k(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(l,p,{timeout:1e4})).exitCode===0?"healthy":"unhealthy"}catch{f="unhealthy"}}r.push(`${i}: server=${u?"reachable":"unreachable"} service=${d} health=${f}`)}catch(l){r.push(`${i}: ERROR \u2014 ${l.message}`)}}return`Deployment Status:
696
+ Health check: \u2713 ${g||"(exit 0)"}`}}let c=o==="git"?`${r}:${e.remote_path}`:`${e.local_path} \u2192 ${r}:${e.remote_path}`;return`Deployed [${o}] ${c}
697
+ ${i}${a}${l}`.trim()}case"deployment_status":{let o=JR(),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 l=pn(a.server||i),u=(await Bt(l,"echo OK",{timeout:1e4})).stdout.trim()==="OK",d="unknown";if(u&&a.deploy_script){let p=a.deploy_script.match(/systemctl\s+\w+\s+(\S+)/);if(p)try{d=(await Bt(l,`systemctl is-active ${p[1]}`,{timeout:1e4})).stdout.trim()}catch{d="inactive"}}let f="N/A";if(a.health_check){let p=a.health_check.trim();if(/^https?:\/\//.test(p))try{let h=require("node-fetch"),g=await Promise.race([h(p),new Promise((w,k)=>setTimeout(()=>k(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(l,p,{timeout:1e4})).exitCode===0?"healthy":"unhealthy"}catch{f="unhealthy"}}r.push(`${i}: server=${u?"reachable":"unreachable"} service=${d} health=${f}`)}catch(l){r.push(`${i}: ERROR \u2014 ${l.message}`)}}return`Deployment Status:
698
698
  ${r.join(`
699
- `)}`}case"frontend_recon":{let s=process.cwd(),o=(e.type||"").toLowerCase(),r=[],i=async(R,C=120)=>{try{let M=le.isAbsolute(R)?R:le.join(s,R),z=(await bt.readFile(M,"utf8")).split(`
699
+ `)}`}case"frontend_recon":{let o=process.cwd(),s=(e.type||"").toLowerCase(),r=[],i=async(R,C=120)=>{try{let M=le.isAbsolute(R)?R:le.join(o,R),z=(await bt.readFile(M,"utf8")).split(`
700
700
  `),X=z.slice(0,C).join(`
701
701
  `);return z.length>C?X+`
702
- ... (${z.length-C} more lines \u2014 use read_file for full content)`:X}catch{return null}},l=["node_modules",".git","dist","build","vendor",".next","__pycache__","venv",".venv"].map(R=>`-not -path "*/${R}/*"`).join(" "),c=async R=>{try{let{stdout:C}=await gt(`find "${s}" -type f -name "${R}" ${l} 2>/dev/null | head -10`,{timeout:8e3});return C.trim().split(`
703
- `).filter(Boolean)}catch{return[]}},u=async(R,C)=>{try{let{stdout:M}=await gt(`grep -rl "${R}" "${s}" --include="${C}" --exclude-dir=node_modules --exclude-dir=.git --exclude-dir=dist --exclude-dir=build 2>/dev/null | head -5`,{timeout:8e3});return M.trim().split(`
702
+ ... (${z.length-C} more lines \u2014 use read_file for full content)`:X}catch{return null}},l=["node_modules",".git","dist","build","vendor",".next","__pycache__","venv",".venv"].map(R=>`-not -path "*/${R}/*"`).join(" "),c=async R=>{try{let{stdout:C}=await gt(`find "${o}" -type f -name "${R}" ${l} 2>/dev/null | head -10`,{timeout:8e3});return C.trim().split(`
703
+ `).filter(Boolean)}catch{return[]}},u=async(R,C)=>{try{let{stdout:M}=await gt(`grep -rl "${R}" "${o}" --include="${C}" --exclude-dir=node_modules --exclude-dir=.git --exclude-dir=dist --exclude-dir=build 2>/dev/null | head -5`,{timeout:8e3});return M.trim().split(`
704
704
  `).filter(Boolean)}catch{return[]}};r.push(`## STEP 1: Design Tokens
705
- `);let d=[...await c("tailwind.config.js"),...await c("tailwind.config.ts"),...await c("tailwind.config.mjs")];if(d.length>0){let R=await i(d[0],80);R&&r.push(`### Tailwind config (${le.relative(s,d[0])})
705
+ `);let d=[...await c("tailwind.config.js"),...await c("tailwind.config.ts"),...await c("tailwind.config.mjs")];if(d.length>0){let R=await i(d[0],80);R&&r.push(`### Tailwind config (${le.relative(o,d[0])})
706
706
  \`\`\`js
707
707
  ${R}
708
- \`\`\``)}else r.push("(no tailwind.config found)");let f=["variables.css","_variables.scss","tokens.css","base.css","global.css","main.css","index.css","app.css","style.css","styles.css"],p=!1;for(let R of f){let C=await c(R);for(let M of C){let K=await i(M,100);if(K&&K.includes(":root")){r.push(`### CSS Variables (${le.relative(s,M)})
708
+ \`\`\``)}else r.push("(no tailwind.config found)");let f=["variables.css","_variables.scss","tokens.css","base.css","global.css","main.css","index.css","app.css","style.css","styles.css"],p=!1;for(let R of f){let C=await c(R);for(let M of C){let K=await i(M,100);if(K&&K.includes(":root")){r.push(`### CSS Variables (${le.relative(o,M)})
709
709
  \`\`\`css
710
710
  ${K}
711
- \`\`\``),p=!0;break}}if(p)break}if(!p){let R=await u(":root","*.css");if(R.length>0){let C=await i(R[0],100);C&&r.push(`### CSS Variables (${le.relative(s,R[0])})
711
+ \`\`\``),p=!0;break}}if(p)break}if(!p){let R=await u(":root","*.css");if(R.length>0){let C=await i(R[0],100);C&&r.push(`### CSS Variables (${le.relative(o,R[0])})
712
712
  \`\`\`css
713
713
  ${C}
714
714
  \`\`\``),p=!0}}p||r.push("(no CSS custom properties / :root found)"),r.push(`
715
715
  ## STEP 2: Main Layout / Index Page
716
- `);let h=["base.html","_base.html","layout.html","base.jinja","App.vue","App.jsx","App.tsx","_app.jsx","_app.tsx","_app.js","layout.vue","index.html"],g=!1;for(let R of h){let C=await c(R);if(C.length>0){let M=await i(C[0],150);if(M){r.push(`### Main layout: ${le.relative(s,C[0])}
716
+ `);let h=["base.html","_base.html","layout.html","base.jinja","App.vue","App.jsx","App.tsx","_app.jsx","_app.tsx","_app.js","layout.vue","index.html"],g=!1;for(let R of h){let C=await c(R);if(C.length>0){let M=await i(C[0],150);if(M){r.push(`### Main layout: ${le.relative(o,C[0])}
717
717
  \`\`\`html
718
718
  ${M}
719
719
  \`\`\``),g=!0;break}}}g||r.push("(no main layout/index file found \u2014 try read_file on your root template manually)"),r.push(`
720
720
  ## STEP 3: Reference Component (same type)
721
- `);let w=[];if(o){for(let R of["*.html","*.vue","*.jsx","*.tsx"])if(w=await u(o,R),w.length>0)break}if(w.length===0)try{let{stdout:R}=await gt(`find "${s}" -type f \\( -name "*.html" -o -name "*.vue" -o -name "*.jsx" -o -name "*.tsx" \\) -not -path "*/node_modules/*" -not -path "*/.git/*" -not -path "*/dist/*" -not -path "*/build/*" -not -name "base.html" -not -name "_base.html" -not -name "layout.html" -not -name "App.vue" -not -name "App.jsx" 2>/dev/null | head -20`,{timeout:8e3});w=R.trim().split(`
722
- `).filter(Boolean)}catch{w=[]}if(w.length>0){let R=w[0],C=await i(R,150);C?r.push(`### Reference: ${le.relative(s,R)}
721
+ `);let w=[];if(s){for(let R of["*.html","*.vue","*.jsx","*.tsx"])if(w=await u(s,R),w.length>0)break}if(w.length===0)try{let{stdout:R}=await gt(`find "${o}" -type f \\( -name "*.html" -o -name "*.vue" -o -name "*.jsx" -o -name "*.tsx" \\) -not -path "*/node_modules/*" -not -path "*/.git/*" -not -path "*/dist/*" -not -path "*/build/*" -not -name "base.html" -not -name "_base.html" -not -name "layout.html" -not -name "App.vue" -not -name "App.jsx" 2>/dev/null | head -20`,{timeout:8e3});w=R.trim().split(`
722
+ `).filter(Boolean)}catch{w=[]}if(w.length>0){let R=w[0],C=await i(R,150);C?r.push(`### Reference: ${le.relative(o,R)}
723
723
  \`\`\`html
724
724
  ${C}
725
725
  \`\`\``):r.push("(reference file found but could not be read)")}else r.push("(no reference component found \u2014 check manually with glob or list_directory)");r.push(`
726
726
  ## STEP 4: Framework Stack
727
- `);let k=[],T=await i(le.join(s,"package.json"),999);if(T){if((T.includes('"react"')||T.includes("'react'"))&&k.push("React"),T.includes('"vue"')||T.includes("'vue'")){let C=T.match(/"vue":\s*"[\^~]?(\d+)/);k.push(C?`Vue.js v${C[1]}`:"Vue.js")}let R=T.match(/"alpinejs":\s*"[\^~]?(\d+)/);R&&k.push(`Alpine.js v${R[1]} (\u26A0 v2 vs v3 API differs!)`),(T.includes('"htmx')||T.includes("'htmx"))&&k.push("HTMX"),T.includes('"tailwindcss"')&&k.push("Tailwind CSS"),T.includes('"bootstrap"')&&k.push("Bootstrap")}if((await Qt(le.join(s,"manage.py"))||(await i(le.join(s,"requirements.txt"),50)||"").includes("Django"))&&k.push("Django (server-rendered templates)"),!k.some(R=>R.includes("Alpine"))){let R=await u("alpinejs","*.html");if(R.length>0){let M=(await i(R[0],30)||"").match(/alpinejs[@/]v?(\d)/);k.push(M?`Alpine.js v${M[1]} (via CDN \u2014 \u26A0 v2 vs v3 API differs!)`:"Alpine.js (via CDN \u2014 check version!)")}}return k.some(R=>R.includes("HTMX"))||(await u("htmx","*.html")).length>0&&k.push("HTMX (via CDN)"),k.length>0?(r.push(k.map(R=>`- ${R}`).join(`
727
+ `);let k=[],T=await i(le.join(o,"package.json"),999);if(T){if((T.includes('"react"')||T.includes("'react'"))&&k.push("React"),T.includes('"vue"')||T.includes("'vue'")){let C=T.match(/"vue":\s*"[\^~]?(\d+)/);k.push(C?`Vue.js v${C[1]}`:"Vue.js")}let R=T.match(/"alpinejs":\s*"[\^~]?(\d+)/);R&&k.push(`Alpine.js v${R[1]} (\u26A0 v2 vs v3 API differs!)`),(T.includes('"htmx')||T.includes("'htmx"))&&k.push("HTMX"),T.includes('"tailwindcss"')&&k.push("Tailwind CSS"),T.includes('"bootstrap"')&&k.push("Bootstrap")}if((await Qt(le.join(o,"manage.py"))||(await i(le.join(o,"requirements.txt"),50)||"").includes("Django"))&&k.push("Django (server-rendered templates)"),!k.some(R=>R.includes("Alpine"))){let R=await u("alpinejs","*.html");if(R.length>0){let M=(await i(R[0],30)||"").match(/alpinejs[@/]v?(\d)/);k.push(M?`Alpine.js v${M[1]} (via CDN \u2014 \u26A0 v2 vs v3 API differs!)`:"Alpine.js (via CDN \u2014 check version!)")}}return k.some(R=>R.includes("HTMX"))||(await u("htmx","*.html")).length>0&&k.push("HTMX (via CDN)"),k.length>0?(r.push(k.map(R=>`- ${R}`).join(`
728
728
  `)),r.push(`
729
729
  \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(`
730
730
  ---
731
731
  \u2705 Design recon complete. Now build consistently with the patterns above.`),r.join(`
732
- `)}case"sysadmin":{if(!e.action)return"ERROR: action is required";let s=!e.server||e.server==="local"||e.server==="localhost",o;if(!s)try{o=pn(e.server)}catch(l){return`ERROR: ${l.message}`}let r=async(l,c=3e4)=>{if(s)try{let{stdout:u,stderr:d}=await gt(l,{timeout:c});return{out:(u||d||"").trim(),exitCode:0}}catch(u){return{out:(u.stderr||u.message||"").toString().trim(),exitCode:u.code||1}}else{let{stdout:u,stderr:d,exitCode:f,error:p}=await Bt(o,l,{timeout:c}),h=[u,d].filter(Boolean).join(`
732
+ `)}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=pn(e.server)}catch(l){return`ERROR: ${l.message}`}let r=async(l,c=3e4)=>{if(o)try{let{stdout:u,stderr:d}=await gt(l,{timeout:c});return{out:(u||d||"").trim(),exitCode:0}}catch(u){return{out:(u.stderr||u.message||"").toString().trim(),exitCode:u.code||1}}else{let{stdout:u,stderr:d,exitCode:f,error:p}=await Bt(s,l,{timeout:c}),h=[u,d].filter(Boolean).join(`
733
733
  `).trim();return{out:p&&f!==0&&!u.trim()?(p+`
734
- `+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 l=s?"local":e.server;if(!await vn(`sysadmin [${e.action}] on ${l} \u2014 proceed?`))return"Cancelled."}switch(e.action){case"audit":{let l=["echo '=== OS / KERNEL ==='","cat /etc/os-release 2>/dev/null | grep -E '^(NAME|VERSION)=' || uname -a","echo '=== UPTIME / LOAD ==='","uptime","echo '=== MEMORY / SWAP ==='","free -h","echo '=== DISK ==='","df -h --output=target,size,used,avail,pcent 2>/dev/null || df -h","echo '=== TOP 10 PROCESSES (CPU) ==='","ps aux --sort=-%cpu | head -11","echo '=== FAILED SYSTEMD UNITS ==='","systemctl list-units --state=failed --no-legend 2>/dev/null || echo '(systemctl not available)'","echo '=== RECENT ERRORS (journalctl) ==='","journalctl -p err --no-pager -n 15 2>/dev/null || echo '(journalctl not available)'","echo '=== LISTENING PORTS ==='","ss -tlnp 2>/dev/null || netstat -tlnp 2>/dev/null || echo '(ss/netstat not available)'"].join(" && "),{out:c,exitCode:u}=await r(l,45e3);return c||`EXIT ${u}
734
+ `+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 l=o?"local":e.server;if(!await vn(`sysadmin [${e.action}] on ${l} \u2014 proceed?`))return"Cancelled."}switch(e.action){case"audit":{let l=["echo '=== OS / KERNEL ==='","cat /etc/os-release 2>/dev/null | grep -E '^(NAME|VERSION)=' || uname -a","echo '=== UPTIME / LOAD ==='","uptime","echo '=== MEMORY / SWAP ==='","free -h","echo '=== DISK ==='","df -h --output=target,size,used,avail,pcent 2>/dev/null || df -h","echo '=== TOP 10 PROCESSES (CPU) ==='","ps aux --sort=-%cpu | head -11","echo '=== FAILED SYSTEMD UNITS ==='","systemctl list-units --state=failed --no-legend 2>/dev/null || echo '(systemctl not available)'","echo '=== RECENT ERRORS (journalctl) ==='","journalctl -p err --no-pager -n 15 2>/dev/null || echo '(journalctl not available)'","echo '=== LISTENING PORTS ==='","ss -tlnp 2>/dev/null || netstat -tlnp 2>/dev/null || echo '(ss/netstat not available)'"].join(" && "),{out:c,exitCode:u}=await r(l,45e3);return c||`EXIT ${u}
735
735
  (no output)`}case"disk_usage":{let l=e.path||"/",c=He(l),u=`df -h ${c}; echo '--- Top subdirs ---'; du -d1 -x -h ${c} 2>/dev/null | sort -rh | head -20`,{out:d,exitCode:f}=await r(u,3e4);return f!==0?`EXIT ${f}
736
736
  ${d}`:d}case"process_list":{let l=e.sort_by==="mem"?"4":"3",c=(e.limit||20)+1,u=`ps aux --sort=-${e.sort_by==="mem"?"%mem":"%cpu"} 2>/dev/null | head -${c} || ps aux | awk 'NR==1{print; next} {print | "sort -k${l} -rn"}' | head -${c}`,{out:d,exitCode:f}=await r(u,15e3);return f!==0?`EXIT ${f}
737
737
  ${d}`:d}case"network_status":{let l="ss -tlnp 2>/dev/null || netstat -tlnp 2>/dev/null; echo '--- Active connections ---'; ss -tnp 2>/dev/null | head -30",{out:c,exitCode:u}=await r(l,15e3);return u!==0?`EXIT ${u}
@@ -775,9 +775,9 @@ ${u}`:u||"(empty log)"}case"find_large":{let l=e.path||"/",c=e.limit||20,u=e.min
775
775
  ${f}`:f||`(no files larger than ${u} in ${l})`}case"service":{if(!e.service_action)return"ERROR: service_action is required for action=service";if(e.service_action!=="list_failed"&&!e.service_name)return"ERROR: service_name is required (except for list_failed)";if(e.service_name){let p=_d(e.service_name,"service_name");if(p)return p}let l=e.service_name?e.service_name.includes(".")?e.service_name:`${e.service_name}.service`:"",c;switch(e.service_action){case"status":c=`systemctl status ${l} --no-pager -l 2>&1 | head -40`;break;case"list_failed":c="systemctl list-units --state=failed --no-legend 2>/dev/null";break;case"start":c=`systemctl start ${l} && systemctl status ${l} --no-pager -l 2>&1 | head -20`;break;case"stop":c=`systemctl stop ${l} && echo "${l} stopped"`;break;case"restart":c=`systemctl restart ${l} && systemctl status ${l} --no-pager -l 2>&1 | head -20`;break;case"reload":c=`systemctl reload ${l} 2>&1 || systemctl reload-or-restart ${l} 2>&1`;break;case"enable":c=`systemctl enable ${l} && echo "${l} enabled"`;break;case"disable":c=`systemctl disable ${l} && echo "${l} disabled"`;break;default:return`ERROR: Unknown service_action: ${e.service_action}`}let{out:u,exitCode:d}=await r(c,3e4);return d===0||e.service_action==="status"&&d===3?u||`service ${e.service_action} OK`:`EXIT ${d}
776
776
  ${u}`}case"kill_process":{if(!e.pid&&!e.process_name)return"ERROR: pid or process_name is required for kill_process";let l=e.signal||"SIGTERM";if(!p1(l))return"ERROR: signal contains unsafe characters";let c;if(e.pid){if(!/^\d+$/.test(String(e.pid)))return"ERROR: pid must be numeric";c=`ps -p ${e.pid} -o pid,user,%cpu,%mem,etime,cmd 2>/dev/null && kill -${l} ${e.pid} && echo "Sent ${l} to PID ${e.pid}"`}else c=`pgrep -a ${He(e.process_name)} 2>/dev/null | head -5 && pkill -${l} ${He(e.process_name)} && echo "Sent ${l} to all '${e.process_name}' processes"`;let{out:u,exitCode:d}=await r(c,15e3);return d!==0?`EXIT ${d}
777
777
  ${u}`:u}case"journalctl":{let l=e.lines||100,c=["journalctl","--no-pager","-n",String(l)];e.unit&&c.push("-u",e.unit.includes(".")?e.unit:`${e.unit}.service`),e.priority&&c.push("-p",e.priority),e.since&&c.push(`--since="${e.since}"`),c.push('2>/dev/null || echo "(journalctl not available)"');let{out:u,exitCode:d}=await r(c.join(" "),2e4);return d!==0?`EXIT ${d}
778
- ${u}`:u||"(no log entries)"}default:return`ERROR: Unknown sysadmin action: ${e.action}`}}case"save_memory":{let{saveMemory:s}=Gr(),o=s(e.type,e.name,e.content,e.description);return o.ok?o.updated===!1?`Memory unchanged (duplicate): ${e.type}/${e.name}`:`Memory saved: ${e.type}/${e.name} \u2192 ${o.path}`:`ERROR: ${o.error}`}case"delete_memory":{let{deleteMemory:s}=Gr();return s(e.type,e.name)?`Memory deleted: ${e.type}/${e.name}`:`Memory not found: ${e.type}/${e.name}`}default:{let{executePluginTool:s}=Ea(),o=await s(t,e,n);return o!==null?o:`ERROR: Unknown tool: ${t}`}}}async function m1(t,e,n={}){let{emit:s}=Ea(),{logToolExecution:o}=xb(),r=Date.now(),i=n.silent?null:UR(t,e);if(!i){let l=await Nb(t,e,n);return o({tool:t,args:e,result:l,duration:Date.now()-r,success:!l.startsWith?.("ERROR")}),await s("onToolResult",{tool:t,args:e,result:l}),l}let a=new BR(i);a.start();try{let l=await Nb(t,e,n);return a.stop(),o({tool:t,args:e,result:l,duration:Date.now()-r,success:!l.startsWith?.("ERROR")}),await s("onToolResult",{tool:t,args:e,result:l}),l}catch(l){throw a.stop(),o({tool:t,args:e,result:l.message,duration:Date.now()-r,success:!1}),l}}Ub.exports={TOOL_DEFINITIONS:h1,executeTool:m1,resolvePath:At,autoFixPath:al,autoFixEdit:Fb,enrichBashError:qb,getNodeBuiltinInstallAttempt:Lb,cancelPendingAskUser:r1,setAskUserHandler:i1,fileExists:Qt}});var Do=ne((_N,Hb)=>{Hb.exports=Wb()});var vd=ne((kN,Yb)=>{var{loadServerProfiles:Xo,resolveProfile:$N,sshExec:g1}=qo(),y1=/\.(?:png|jpe?g|gif|webp|bmp|svg|ico|pdf|mp4|webm|mov)(?:[?#].*)?$/i,b1=/\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,w1=/https?:\/\/[^\s)]+/gi;function _1(t){if(typeof t!="string")return[];let e=new Set,n=[];for(let s of t.match(w1)||[]){let o=s.replace(/[.,;!?]+$/g,"");e.has(o)||(e.add(o),n.push(o))}return n}function $1(t,e){let n;try{n=new URL(t).hostname.toLowerCase()}catch{return null}let s=n.split(".");for(let[o,r]of Object.entries(e))if(s.includes(o.toLowerCase()))return{matchedName:o,matchedProfile:r,hostname:n};for(let[o,r]of Object.entries(e))if(String(r.host||"").toLowerCase()===n)return{matchedName:o,matchedProfile:r,hostname:n};return{matchedName:null,matchedProfile:null,hostname:n}}function Gb(t,e=Xo()){if(typeof t!="string"||!b1.test(t))return null;let n=_1(t).filter(s=>!y1.test(s));if(n.length===0)return null;for(let s of n){let o=$1(s,e);if(o)return{url:s,hostname:o.hostname,matchedName:o.matchedName,matchedProfile:o.matchedProfile,shouldPreferBrowser:!0,shouldPreferSsh:!!(o.matchedName&&o.matchedProfile)}}return null}var xd={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 k1(){let t=Xo();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[o,r]of Object.entries(t)){let i=r.user?`${r.user}@${r.host}`:r.host,a=r.port&&Number(r.port)!==22?`:${r.port}`:"",l=r.os?` \u2014 OS: ${r.os}`:"",c=r.sudo?", sudo available":"";n.push(`- **${o}**: ${i}${a}${l}${c}`)}let s=new Set;for(let o of Object.values(t))o.os&&xd[o.os]&&s.add(o.os);if(s.size>0){n.push("");for(let o of s){let r={almalinux9:"AlmaLinux 9",almalinux8:"AlmaLinux 8",ubuntu:"Ubuntu",debian:"Debian",macos:"macOS"}[o]||o;n.push(`### ${r} Notes`);for(let i of xd[o])n.push(`- ${i}`)}}return n.join(`
779
- `)}function x1(t){let e=Xo();return Object.values(e).some(n=>n.os&&n.os.startsWith(t))}function v1(){return Object.keys(Xo())}function S1(){let t=require("fs"),n=require("path").join(process.cwd(),"NEX.md"),s="";try{s=t.readFileSync(n,"utf-8")}catch{}let o=Xo(),r=Object.keys(o);if(r.length===0)return null;let i=["server","deploy","remote","ssh","service","systemctl","production","linux","almalinux","ubuntu","debian"],a=s.toLowerCase();if(!i.some(f=>a.includes(f)))return null;let c=r.map(f=>{let p=o[f],h=p.user?`${p.user}@${p.host}`:p.host,g=p.port&&Number(p.port)!==22?`:${p.port}`:"";return` - **${f}**: ${h}${g}${p.os?` (${p.os})`:""}`}).join(`
780
- `),u=r.map(f=>o[f].log_path).filter(Boolean),d=u.length>0?`
778
+ ${u}`:u||"(no log entries)"}default:return`ERROR: Unknown sysadmin action: ${e.action}`}}case"save_memory":{let{saveMemory:o}=Gr(),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}=Gr();return o(e.type,e.name)?`Memory deleted: ${e.type}/${e.name}`:`Memory not found: ${e.type}/${e.name}`}default:{let{executePluginTool:o}=Ea(),s=await o(t,e,n);return s!==null?s:`ERROR: Unknown tool: ${t}`}}}async function m1(t,e,n={}){let{emit:o}=Ea(),{logToolExecution:s}=xb(),r=Date.now(),i=n.silent?null:UR(t,e);if(!i){let l=await Nb(t,e,n);return s({tool:t,args:e,result:l,duration:Date.now()-r,success:!l.startsWith?.("ERROR")}),await o("onToolResult",{tool:t,args:e,result:l}),l}let a=new BR(i);a.start();try{let l=await Nb(t,e,n);return a.stop(),s({tool:t,args:e,result:l,duration:Date.now()-r,success:!l.startsWith?.("ERROR")}),await o("onToolResult",{tool:t,args:e,result:l}),l}catch(l){throw a.stop(),s({tool:t,args:e,result:l.message,duration:Date.now()-r,success:!1}),l}}Ub.exports={TOOL_DEFINITIONS:h1,executeTool:m1,resolvePath:At,autoFixPath:al,autoFixEdit:Fb,enrichBashError:qb,getNodeBuiltinInstallAttempt:Lb,cancelPendingAskUser:r1,setAskUserHandler:i1,fileExists:Qt}});var Do=ne((_N,Hb)=>{Hb.exports=Wb()});var vd=ne((kN,Yb)=>{var{loadServerProfiles:Xo,resolveProfile:$N,sshExec:g1}=qo(),y1=/\.(?:png|jpe?g|gif|webp|bmp|svg|ico|pdf|mp4|webm|mov)(?:[?#].*)?$/i,b1=/\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,w1=/https?:\/\/[^\s)]+/gi;function _1(t){if(typeof t!="string")return[];let e=new Set,n=[];for(let o of t.match(w1)||[]){let s=o.replace(/[.,;!?]+$/g,"");e.has(s)||(e.add(s),n.push(s))}return n}function $1(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 Gb(t,e=Xo()){if(typeof t!="string"||!b1.test(t))return null;let n=_1(t).filter(o=>!y1.test(o));if(n.length===0)return null;for(let o of n){let s=$1(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 xd={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 k1(){let t=Xo();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}`:"",l=r.os?` \u2014 OS: ${r.os}`:"",c=r.sudo?", sudo available":"";n.push(`- **${s}**: ${i}${a}${l}${c}`)}let o=new Set;for(let s of Object.values(t))s.os&&xd[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 xd[s])n.push(`- ${i}`)}}return n.join(`
779
+ `)}function x1(t){let e=Xo();return Object.values(e).some(n=>n.os&&n.os.startsWith(t))}function v1(){return Object.keys(Xo())}function S1(){let t=require("fs"),n=require("path").join(process.cwd(),"NEX.md"),o="";try{o=t.readFileSync(n,"utf-8")}catch{}let s=Xo(),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 c=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(`
780
+ `),u=r.map(f=>s[f].log_path).filter(Boolean),d=u.length>0?`
781
781
  - Server log paths: ${u.join(", ")}`:"";return`# Deployment Context (Auto-detected)
782
782
 
783
783
  This project is deployed on a **remote server**. The application runs as a service there \u2014 NOT locally.
@@ -795,7 +795,7 @@ ${c}
795
795
  - \u274C Do NOT \`read_file\` on paths like \`logs/\` \u2014 these files do not exist locally
796
796
  - \u274C Do NOT \`list_directory\` on server paths \u2014 the local project is the source, not the running instance
797
797
 
798
- **When in doubt:** If a path contains \`logs/\`, \`/var/log/\`, or \`/home/<user>/\` \u2014 it is on the server. SSH there.${E1(o)}`}function E1(t){return Object.values(t).some(n=>n.host==="94.130.37.43")?`
798
+ **When in doubt:** If a path contains \`logs/\`, \`/var/log/\`, or \`/home/<user>/\` \u2014 it is on the server. SSH there.${E1(s)}`}function E1(t){return Object.values(t).some(n=>n.host==="94.130.37.43")?`
799
799
 
800
800
  ## Server Debugging Rules
801
801
 
@@ -806,11 +806,11 @@ ${c}
806
806
  - 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.
807
807
  - 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.
808
808
  - 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.
809
- - 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 T1(t){let e=Xo(),n=Gb(t,e);if(!n?.matchedProfile||!n?.matchedName)return null;let{matchedProfile:s,matchedName:o}=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 g1(s,r,{timeout:4e3});if(!i||i.trim().length<5)return null;let a=s.user?`${s.user}@${s.host}`:s.host;return`[Server context for "${o}" (${a}) \u2014 probed at task start]
810
- `+i.trim()}catch{return null}}Yb.exports={getServerContext:k1,getDeploymentContextBlock:S1,hasServerOS:x1,getProfileNames:v1,probeUrlServer:T1,detectRuntimeDebugTarget:Gb,OS_HINTS:xd}});var Xb=ne((xN,Vb)=>{var Ot=require("fs").promises,ll=require("fs"),st=require("path"),Qr=require("util").promisify(require("child_process").exec),{C:Jo}=xt(),{getMergeConflicts:Kb}=$a(),{getServerContext:R1}=vd(),{refreshIndex:C1,getFileIndex:A1,buildContentIndex:O1,summarizeModuleHubs:P1}=In(),M1=new Set(["node_modules",".git",".svn","dist","build","coverage",".nyc_output","__pycache__",".DS_Store",".next",".nuxt",".turbo",".cache","vendor","tmp","temp"]),N1=[{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 L1(t,e=6){let n=new Map;for(let s of t){let o=s.includes("/")?s.split("/")[0]:"(root)";!o||o.startsWith(".")||n.set(o,(n.get(o)||0)+1)}return[...n.entries()].sort((s,o)=>o[1]-s[1]||s[0].localeCompare(o[0])).slice(0,e).map(([s,o])=>`${s} (${o})`)}function I1(t){let e=new Set(t),n=new Set;for(let s of N1)(e.has(s.file)||[...e].some(o=>o.startsWith(`${s.file}/`)))&&n.add(s.label);return e.has("package.json")&&n.add("Node.js"),[...e].some(s=>/^tests?\//.test(s)||/\.test\./.test(s)||/\.spec\./.test(s))&&n.add("Tests"),[...e].some(s=>s.startsWith("vscode/"))&&n.add("VS Code Extension"),[...n]}function j1(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 s of e)if(t.includes(s)&&n.push(s),n.length>=5)break;return n}function D1(t,e=6){let n=t.filter(r=>/^tests?\//.test(r)||/\.test\./.test(r)||/\.spec\./.test(r));if(n.length===0)return[];let s=t.filter(r=>!/^tests?\//.test(r)&&!/\.test\./.test(r)&&!/\.spec\./.test(r)&&/\.(js|jsx|ts|tsx|py|go|rs|java)$/.test(r)),o=[];for(let r of s){let i=st.basename(r).replace(/\.[^.]+$/,"");if(i.length<3)continue;let a=n.filter(l=>l.includes(i));if(a.length>0&&o.push(`${r} -> ${a.slice(0,2).join(", ")}`),o.length>=e)break}return o}function q1(t){return!t||!t.workspaces?[]:Array.isArray(t.workspaces)?t.workspaces:Array.isArray(t.workspaces.packages)?t.workspaces.packages:[]}async function F1(t){try{await C1(t);let e=A1();if(!e||e.length===0)return"";let n=I1(e),s=L1(e),o=j1(e),r=e.filter(d=>/^tests?\//.test(d)||/\.test\./.test(d)||/\.spec\./.test(d)).length,i=D1(e),a=[];try{let d=st.join(t,"package.json");if(ll.existsSync(d)){let f=JSON.parse(ll.readFileSync(d,"utf-8"));a=q1(f)}}catch{}let l="",c="";try{let d=await O1(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&&(l=`CODE HOTSPOTS: ${f.join(", ")}`)}catch{}try{let d=await P1(t,4);d.length>0&&(c=`MODULE HUBS: ${d.join(", ")}`)}catch{}let u=[`REPO MAP: ${e.length} indexed files${n.length?` | stack: ${n.join(", ")}`:""}`];return s.length>0&&u.push(`WORK AREAS: ${s.join(", ")}`),o.length>0&&u.push(`LIKELY ENTRY POINTS: ${o.join(", ")}`),a.length>0&&u.push(`WORKSPACES: ${a.join(", ")}`),r>0&&u.push(`TEST FOOTPRINT: ${r} test files detected`),i.length>0&&u.push(`TEST MAP: ${i.join(" | ")}`),l&&u.push(l),c&&u.push(c),u.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."),u.join(`
809
+ - 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 T1(t){let e=Xo(),n=Gb(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 g1(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]
810
+ `+i.trim()}catch{return null}}Yb.exports={getServerContext:k1,getDeploymentContextBlock:S1,hasServerOS:x1,getProfileNames:v1,probeUrlServer:T1,detectRuntimeDebugTarget:Gb,OS_HINTS:xd}});var Xb=ne((xN,Vb)=>{var Ot=require("fs").promises,ll=require("fs"),st=require("path"),Qr=require("util").promisify(require("child_process").exec),{C:Jo}=xt(),{getMergeConflicts:Kb}=$a(),{getServerContext:R1}=vd(),{refreshIndex:C1,getFileIndex:A1,buildContentIndex:O1,summarizeModuleHubs:P1}=In(),M1=new Set(["node_modules",".git",".svn","dist","build","coverage",".nyc_output","__pycache__",".DS_Store",".next",".nuxt",".turbo",".cache","vendor","tmp","temp"]),N1=[{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 L1(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 I1(t){let e=new Set(t),n=new Set;for(let o of N1)(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 j1(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 D1(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=st.basename(r).replace(/\.[^.]+$/,"");if(i.length<3)continue;let a=n.filter(l=>l.includes(i));if(a.length>0&&s.push(`${r} -> ${a.slice(0,2).join(", ")}`),s.length>=e)break}return s}function q1(t){return!t||!t.workspaces?[]:Array.isArray(t.workspaces)?t.workspaces:Array.isArray(t.workspaces.packages)?t.workspaces.packages:[]}async function F1(t){try{await C1(t);let e=A1();if(!e||e.length===0)return"";let n=I1(e),o=L1(e),s=j1(e),r=e.filter(d=>/^tests?\//.test(d)||/\.test\./.test(d)||/\.spec\./.test(d)).length,i=D1(e),a=[];try{let d=st.join(t,"package.json");if(ll.existsSync(d)){let f=JSON.parse(ll.readFileSync(d,"utf-8"));a=q1(f)}}catch{}let l="",c="";try{let d=await O1(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&&(l=`CODE HOTSPOTS: ${f.join(", ")}`)}catch{}try{let d=await P1(t,4);d.length>0&&(c=`MODULE HUBS: ${d.join(", ")}`)}catch{}let u=[`REPO MAP: ${e.length} indexed files${n.length?` | stack: ${n.join(", ")}`:""}`];return o.length>0&&u.push(`WORK AREAS: ${o.join(", ")}`),s.length>0&&u.push(`LIKELY ENTRY POINTS: ${s.join(", ")}`),a.length>0&&u.push(`WORKSPACES: ${a.join(", ")}`),r>0&&u.push(`TEST FOOTPRINT: ${r} test files detected`),i.length>0&&u.push(`TEST MAP: ${i.join(" | ")}`),l&&u.push(l),c&&u.push(c),u.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."),u.join(`
811
811
  `)}catch{return""}}function B1(t){try{return ll.readFileSync(t,"utf-8").split(`
812
- `).map(n=>n.trim()).filter(n=>n&&!n.startsWith("#")&&!n.startsWith("!")).map(n=>n.replace(/\/$/,""))}catch{return[]}}function U1(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 W1(t,{maxDepth:e=3,maxFiles:n=200,giPatterns:s=[]}={}){let o=st.join(t,".gitignore"),r=[...s,...B1(o)],i=0,a=[st.basename(t)+"/"];function l(c,u,d){if(d>e||i>=n)return;let f;try{f=ll.readdirSync(c,{withFileTypes:!0})}catch{return}f.sort((h,g)=>h.isDirectory()!==g.isDirectory()?h.isDirectory()?-1:1:h.name.localeCompare(g.name));let p=f.filter(h=>!(M1.has(h.name)||h.name.startsWith(".")&&h.name!==".env.example"||U1(h.name,r)));for(let h=0;h<p.length;h++){if(i>=n){a.push(`${u}\u2514\u2500\u2500 \u2026 (truncated)`);break}let g=p[h],w=h===p.length-1,k=w?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",T=u+(w?" ":"\u2502 "),$=g.isDirectory()?g.name+"/":g.name;a.push(`${u}${k}${$}`),i++,g.isDirectory()&&l(st.join(c,g.name),T,d+1)}}return l(t,"",1),a.join(`
813
- `)}var Sd=new Map,Qo=new Map,cl=null,zb=3e4,Zo={result:null,expiry:0,cwd:null};async function hn(t){try{return await t()}catch{return null}}async function H1(){if(!cl||Date.now()>cl)return!1;let t=[st.join(process.cwd(),"package.json"),st.join(process.cwd(),"README.md"),st.join(process.cwd(),"AGENTS.md"),st.join(process.cwd(),".gitignore")];for(let e of t)try{let n=await Ot.stat(e),s=Qo.get(e);if(!s||n.mtimeMs!==s)return!1}catch{if(Qo.has(e))return!1}try{let e=st.join(process.cwd(),".git","HEAD"),n=await Ot.stat(e),s=Qo.get(e);if(!s||n.mtimeMs!==s)return!1}catch{}return!0}async function G1(){let t=[st.join(process.cwd(),"package.json"),st.join(process.cwd(),"README.md"),st.join(process.cwd(),"AGENTS.md"),st.join(process.cwd(),".gitignore"),st.join(process.cwd(),".git","HEAD"),st.join(process.cwd(),"CLAUDE.md"),st.join(process.cwd(),".nex","CLAUDE.md")];for(let e of t)try{let n=await Ot.stat(e);Qo.set(e,n.mtimeMs)}catch{Qo.delete(e)}}async function Y1(t){let e="fileContext",n=Sd.get(e),s=!1;if(n&&await H1()&&(s=!0),!s){let u=[],d=st.join(t,"package.json");if(await hn(()=>Ot.access(d).then(()=>!0).catch(()=>!1)))try{let z=await Ot.readFile(d,"utf-8"),X=JSON.parse(z),ae={name:X.name,version:X.version};if(X.scripts&&(ae.scripts=Object.keys(X.scripts).slice(0,15)),X.dependencies&&(ae.deps=Object.keys(X.dependencies).length),X.devDependencies&&(ae.devDeps=Object.keys(X.devDependencies).length),u.push(`PACKAGE: ${JSON.stringify(ae)}`),X.scripts){let Z=["test","build","lint","typecheck","check","benchmark:gate","benchmark"].filter(oe=>X.scripts[oe]).map(oe=>`${oe}=${X.scripts[oe]}`).slice(0,8);Z.length>0&&u.push(`PACKAGE SCRIPTS:
812
+ `).map(n=>n.trim()).filter(n=>n&&!n.startsWith("#")&&!n.startsWith("!")).map(n=>n.replace(/\/$/,""))}catch{return[]}}function U1(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 W1(t,{maxDepth:e=3,maxFiles:n=200,giPatterns:o=[]}={}){let s=st.join(t,".gitignore"),r=[...o,...B1(s)],i=0,a=[st.basename(t)+"/"];function l(c,u,d){if(d>e||i>=n)return;let f;try{f=ll.readdirSync(c,{withFileTypes:!0})}catch{return}f.sort((h,g)=>h.isDirectory()!==g.isDirectory()?h.isDirectory()?-1:1:h.name.localeCompare(g.name));let p=f.filter(h=>!(M1.has(h.name)||h.name.startsWith(".")&&h.name!==".env.example"||U1(h.name,r)));for(let h=0;h<p.length;h++){if(i>=n){a.push(`${u}\u2514\u2500\u2500 \u2026 (truncated)`);break}let g=p[h],w=h===p.length-1,k=w?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",T=u+(w?" ":"\u2502 "),$=g.isDirectory()?g.name+"/":g.name;a.push(`${u}${k}${$}`),i++,g.isDirectory()&&l(st.join(c,g.name),T,d+1)}}return l(t,"",1),a.join(`
813
+ `)}var Sd=new Map,Qo=new Map,cl=null,zb=3e4,Zo={result:null,expiry:0,cwd:null};async function hn(t){try{return await t()}catch{return null}}async function H1(){if(!cl||Date.now()>cl)return!1;let t=[st.join(process.cwd(),"package.json"),st.join(process.cwd(),"README.md"),st.join(process.cwd(),"AGENTS.md"),st.join(process.cwd(),".gitignore")];for(let e of t)try{let n=await Ot.stat(e),o=Qo.get(e);if(!o||n.mtimeMs!==o)return!1}catch{if(Qo.has(e))return!1}try{let e=st.join(process.cwd(),".git","HEAD"),n=await Ot.stat(e),o=Qo.get(e);if(!o||n.mtimeMs!==o)return!1}catch{}return!0}async function G1(){let t=[st.join(process.cwd(),"package.json"),st.join(process.cwd(),"README.md"),st.join(process.cwd(),"AGENTS.md"),st.join(process.cwd(),".gitignore"),st.join(process.cwd(),".git","HEAD"),st.join(process.cwd(),"CLAUDE.md"),st.join(process.cwd(),".nex","CLAUDE.md")];for(let e of t)try{let n=await Ot.stat(e);Qo.set(e,n.mtimeMs)}catch{Qo.delete(e)}}async function Y1(t){let e="fileContext",n=Sd.get(e),o=!1;if(n&&await H1()&&(o=!0),!o){let u=[],d=st.join(t,"package.json");if(await hn(()=>Ot.access(d).then(()=>!0).catch(()=>!1)))try{let z=await Ot.readFile(d,"utf-8"),X=JSON.parse(z),ae={name:X.name,version:X.version};if(X.scripts&&(ae.scripts=Object.keys(X.scripts).slice(0,15)),X.dependencies&&(ae.deps=Object.keys(X.dependencies).length),X.devDependencies&&(ae.devDeps=Object.keys(X.devDependencies).length),u.push(`PACKAGE: ${JSON.stringify(ae)}`),X.scripts){let Z=["test","build","lint","typecheck","check","benchmark:gate","benchmark"].filter(oe=>X.scripts[oe]).map(oe=>`${oe}=${X.scripts[oe]}`).slice(0,8);Z.length>0&&u.push(`PACKAGE SCRIPTS:
814
814
  ${Z.join(`
815
815
  `)}`)}}catch{}let p=st.join(t,"README.md");if(await hn(()=>Ot.access(p).then(()=>!0).catch(()=>!1))){let X=(await Ot.readFile(p,"utf-8")).split(`
816
816
  `).slice(0,50);u.push(`README (first 50 lines):
@@ -821,36 +821,36 @@ ${z.trim()}`)}let $=st.join(t,"CLAUDE.md");if(await hn(()=>Ot.access($).then(()=
821
821
  ${z.trim()}`)}let C=st.join(t,".nex","CLAUDE.md");if(await hn(()=>Ot.access(C).then(()=>!0).catch(()=>!1))){let z=await Ot.readFile(C,"utf-8");z.trim()&&u.push(`PRIVATE PROJECT INSTRUCTIONS (.nex/CLAUDE.md):
822
822
  ${z.trim()}`)}let K=await F1(t);K&&u.push(K),n=u.join(`
823
823
 
824
- `),Sd.set(e,n),cl=Date.now()+zb,await G1()}let o=[n],r,i,a,l,c;if(Zo.result&&Date.now()<Zo.expiry&&Zo.cwd===t?{branch:r,status:i,log:a,diffStat:l,conflicts:c}=Zo.result:([r,i,a,l,c]=await Promise.all([hn(async()=>{let{stdout:u}=await Qr("git branch --show-current",{cwd:t,timeout:5e3});return u.trim()}),hn(async()=>{let{stdout:u}=await Qr("git status --short",{cwd:t,timeout:5e3});return u.trim()}),hn(async()=>{let{stdout:u}=await Qr("git log --oneline -5",{cwd:t,timeout:5e3});return u.trim()}),hn(async()=>{let{stdout:u}=await Qr("git diff --stat -- .",{cwd:t,timeout:5e3,maxBuffer:2e4});return u.trim()}),Kb()]),Zo={result:{branch:r,status:i,log:a,diffStat:l,conflicts:c},expiry:Date.now()+zb,cwd:t}),r&&o.push(`GIT BRANCH: ${r}`),i&&o.push(`GIT STATUS:
825
- ${i}`),l&&o.push(`GIT DIFF STAT:
826
- ${l}`),a&&o.push(`RECENT COMMITS:
824
+ `),Sd.set(e,n),cl=Date.now()+zb,await G1()}let s=[n],r,i,a,l,c;if(Zo.result&&Date.now()<Zo.expiry&&Zo.cwd===t?{branch:r,status:i,log:a,diffStat:l,conflicts:c}=Zo.result:([r,i,a,l,c]=await Promise.all([hn(async()=>{let{stdout:u}=await Qr("git branch --show-current",{cwd:t,timeout:5e3});return u.trim()}),hn(async()=>{let{stdout:u}=await Qr("git status --short",{cwd:t,timeout:5e3});return u.trim()}),hn(async()=>{let{stdout:u}=await Qr("git log --oneline -5",{cwd:t,timeout:5e3});return u.trim()}),hn(async()=>{let{stdout:u}=await Qr("git diff --stat -- .",{cwd:t,timeout:5e3,maxBuffer:2e4});return u.trim()}),Kb()]),Zo={result:{branch:r,status:i,log:a,diffStat:l,conflicts:c},expiry:Date.now()+zb,cwd:t}),r&&s.push(`GIT BRANCH: ${r}`),i&&s.push(`GIT STATUS:
825
+ ${i}`),l&&s.push(`GIT DIFF STAT:
826
+ ${l}`),a&&s.push(`RECENT COMMITS:
827
827
  ${a}`),c&&c.length>0){let u=c.map(d=>` ${d.file}`).join(`
828
- `);o.push(`MERGE CONFLICTS (resolve before editing these files):
829
- ${u}`)}try{let u=R1();u&&o.push(u)}catch{}return o.join(`
828
+ `);s.push(`MERGE CONFLICTS (resolve before editing these files):
829
+ ${u}`)}try{let u=R1();u&&s.push(u)}catch{}return s.join(`
830
830
 
831
- `)}async function z1(t){let e=st.join(t,"package.json"),n="";if(await hn(()=>Ot.access(e).then(()=>!0).catch(()=>!1)))try{let i=await Ot.readFile(e,"utf-8"),a=JSON.parse(i);n=`${a.name||"?"} v${a.version||"?"}`}catch{}let[o,r]=await Promise.all([hn(async()=>{let{stdout:i}=await Qr("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),Kb()]);if(r&&r.length>0){console.log(`${Jo.red} \u26A0 ${r.length} unresolved merge conflict(s):${Jo.reset}`);for(let i of r)console.log(`${Jo.red} ${i.file}${Jo.reset}`);console.log(`${Jo.yellow} \u2192 Resolve conflicts before starting tasks${Jo.reset}`)}console.log()}Vb.exports={gatherProjectContext:Y1,printContext:z1,generateFileTree:W1,_clearContextCache:()=>{Sd.clear(),Qo.clear(),cl=null,Zo={result:null,expiry:0,cwd:null}}}});var dl=ne((vN,Qb)=>{var En=require("fs"),ul=require("path"),{atomicWrite:K1}=Ws();function ti(){return ul.join(process.cwd(),".nex","sessions")}function Ed(){let t=ti();En.existsSync(t)||En.mkdirSync(t,{recursive:!0,mode:448})}function Td(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return ul.join(ti(),`${e}.json`)}function Rd(t,e,n={}){Ed();let s=Td(t),o={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 K1(s,JSON.stringify(o,null,2)),{path:s,name:t}}function Jb(t){let e=Td(t);if(!En.existsSync(e))return null;try{return JSON.parse(En.readFileSync(e,"utf-8"))}catch{return null}}function Zb(){Ed();let t=ti(),e=En.readdirSync(t).filter(s=>s.endsWith(".json")),n=[];for(let s of e)try{let o=JSON.parse(En.readFileSync(ul.join(t,s),"utf-8"));n.push({name:o.name||s.replace(".json",""),createdAt:o.createdAt,updatedAt:o.updatedAt,messageCount:o.messageCount||0,model:o.model,provider:o.provider,score:o.score!=null?o.score:null,scoreGrade:o.scoreGrade||null})}catch{}return n.sort((s,o)=>(o.updatedAt||"").localeCompare(s.updatedAt||""))}function V1(t){let e=Td(t);return En.existsSync(e)?(En.unlinkSync(e),!0):!1}function X1(){let t=Zb();return t.length===0?null:Jb(t[0].name)}var _s=null,is=null,ei=null;function J1(t,e={}){t.length!==0&&(_s&&clearTimeout(_s),is=t,ei=e||{},_s=setTimeout(()=>{is&&is.length>0&&Rd("_autosave",is,ei),_s=null,is=null,ei=null},5e3),_s.unref?.())}function Z1(){_s&&(clearTimeout(_s),_s=null),is&&is.length>0&&(Rd("_autosave",is,ei),is=null,ei=null)}function Q1(){Ed();let t=ti(),e=En.readdirSync(t).filter(r=>r.endsWith(".json")),n=new Date,s=new Date(n.getTime()-720*60*60*1e3),o=0;for(let r of e){let i=ul.join(t,r);try{let a=En.statSync(i);new Date(a.mtime)<s&&(En.unlinkSync(i),o++)}catch{}}return o}Qb.exports={saveSession:Rd,loadSession:Jb,listSessions:Zb,deleteSession:V1,getLastSession:X1,autoSave:J1,flushAutoSave:Z1,clearOldSessions:Q1,_getSessionsDir:ti}});var fl=ne((SN,aw)=>{"use strict";var ni=require("fs"),ew=require("path");function tw(t){let e=[];return t.forEach((n,s)=>{n.role==="assistant"&&(Array.isArray(n.content)&&n.content.forEach(o=>{o&&o.type==="tool_use"&&e.push({name:o.name||"",input:o.input||{},index:s,id:o.id||null})}),Array.isArray(n.tool_calls)&&n.tool_calls.forEach(o=>{let r=o.function?.name||o.name||"",i={};try{i=typeof o.function?.arguments=="string"?JSON.parse(o.function.arguments):o.function?.arguments||o.input||{}}catch{}e.push({name:r,input:i,index:s,id:o.id||null})}))}),e}function eC(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(s=>{s&&s.type==="tool_result"&&s.tool_use_id&&typeof s.content=="string"&&s.content.startsWith("BLOCKED:")&&e.add(s.tool_use_id)})}),e}function nw(t){let e=[];return t.forEach((n,s)=>{if(n.role==="user"&&Array.isArray(n.content)&&n.content.forEach(o=>{if(o&&o.type==="tool_result"){let r=typeof o.content=="string"?o.content:Array.isArray(o.content)?o.content.map(i=>typeof i=="string"?i:i.text||"").join(""):JSON.stringify(o.content||"");e.push({content:r,index:s})}}),n.role==="tool"){let o=typeof n.content=="string"?n.content:JSON.stringify(n.content||"");e.push({content:o,index:s})}}),e}function sw(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 s=n.content.filter(o=>o&&(o.type==="text"||typeof o=="string")).map(o=>typeof o=="string"?o:o.text||"").join("").trim();if(s)return s}}}return""}function ow(t,e){let n=[];for(let s=t.length-1;s>=0&&n.length<e;s--){let o=t[s];if(o.role!=="assistant")continue;let r="";typeof o.content=="string"?r=o.content.trim():Array.isArray(o.content)&&(r=o.content.filter(i=>i&&(i.type==="text"||typeof i=="string")).map(i=>typeof i=="string"?i:i.text||"").join("").trim()),r&&n.push(r)}return n}function rw(t){let e=new Map;for(let n of t){let s;try{s=JSON.stringify(n.input)}catch{s=String(n.input)}let o=`${n.name}|${s}`;e.set(o,(e.get(o)||0)+1)}return e}function iw(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=[],s=tw(t),o=nw(t),r=s.length,i=eC(t),a=s.filter(E=>!E.id||!i.has(E.id));t.some(E=>E.role==="user"&&typeof E.content=="string"&&E.content.startsWith("[SYSTEM WARNING]")&&(E.content.includes("edited")||E.content.includes("bash command")||E.content.includes("grep pattern")||E.content.includes("re-read")||E.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 c=s.find(E=>{let _=E.input?.command||E.input?.cmd||"";return/\bsed\s+-n\b/.test(_)});if(c){let E=(c.input?.command||c.input?.cmd||"").slice(0,80);o.some(H=>H.content.includes("BLOCKED: sed -n is forbidden")||H.content.includes("BLOCKED: sed -n"))?(e-=.25,n.push(`sed -n attempted but blocked by agent guard: ${E}`)):(e-=1.5,n.push(`sed -n anti-pattern used: ${E}`))}s.find(E=>{if(E.name!=="grep"&&E.name!=="bash"&&E.name!=="ssh_exec")return!1;let _=E.input?.command||E.input?.cmd||"",H=E.input?.pattern||"",se=`${_} ${H}`;return/(?:-[CAB]|--context|--after|--before)\s*[=\s]?([2-9][1-9]|\d{3,})/.test(se)||/grep.*-[CAB]\s*([2-9][1-9]|\d{3,})/.test(se)})&&(e-=1,n.push("grep used with >20 context lines (context flood risk)"));let d=t.some(E=>E.role==="assistant"),f=sw(t),h=ow(t,3).some(E=>E.length>100&&!/^[^.!]{0,40}\?$/.test(E));if(d&&!h&&(f.length<80||/^[^.!]{0,40}\?$/.test(f))){e-=2;let E=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: ${E}`)}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(E=>{let _=typeof E.content=="string"?E.content:Array.isArray(E.content)?E.content.map(H=>typeof H=="string"?H:H.text||"").join(""):"";return/\[auto-compressed|context compacted|force-compressed/.test(_)})&&(e-=.5,n.push("Auto-compress triggered (context flood indicator)"));let k=rw(a),T=0,$="";for(let[E,_]of k)_>T&&(T=_,$=E);if(T>=3){let[E]=$.split("|");e-=1,n.push(`Same tool call repeated ${T}\xD7 (tool: ${E})`)}let R=!1,C=t.findIndex(E=>E.role==="user"&&typeof E.content=="string"&&E.content.includes("[SYSTEM STOP]")&&E.content.includes('"valid":true'));C>=0&&s.filter(_=>_.index>C).length>0&&(R=!0),R&&(e-=1.5,n.push('Stop-trigger ignored: tool result contained "valid":true but session continued with more tool calls'));let M=s.filter(E=>E.name==="ssh_exec");if(M.length>=8){let E=0,_=1;for(let H=1;H<M.length;H++)M[H].index<=M[H-1].index+2?_++:(E=Math.max(E,_),_=1);E=Math.max(E,_),E>=8&&(e-=.5,n.push(`SSH reconnect storm: ${E} consecutive SSH calls`))}d&&M.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 K=new Map;for(let E of a)if(E.name==="read_file"&&E.input?.path){let _=E.input.path;K.has(_)||K.set(_,{count:0,ranges:[]});let H=K.get(_);if(H.count++,E.input.line_start!=null){let se=E.input.line_start||1,ee=E.input.line_end||se+350;H.ranges.push([se,ee])}}function z(E,_,H){for(let[se,ee]of H){let P=Math.max(E,se),he=Math.min(_,ee);if(he>P){let Xe=he-P,$e=_-E||1;if(Xe/$e>=.7)return!0}}return!1}let X=0,ae="";for(let[E,_]of K){if(_.count<3)continue;if(_.ranges.length===_.count){let ee=!1,P=[];for(let[he,Xe]of _.ranges){if(P.length>0&&z(he,Xe,P)){ee=!0;break}P.push([he,Xe])}if(!ee)continue}if(_.count-_.ranges.length<=2&&_.ranges.length>=1){let ee=!1,P=[];for(let[he,Xe]of _.ranges){if(P.length>0&&z(he,Xe,P)){ee=!0;break}P.push([he,Xe])}if(!ee)continue}_.count>X&&(X=_.count,ae=E)}if(X>=3){e-=1;let E=ae.split("/").slice(-2).join("/");n.push(`read_file loop: "${E}" read ${X}\xD7 (file already in context)`)}let Z=0,oe="";for(let[E,_]of K){if(_.ranges.length<4)continue;let H=[],se=!1;for(let[ee,P]of _.ranges){if(H.length>0&&z(ee,P,H)){se=!0;break}H.push([ee,P])}!se&&_.ranges.length>Z&&(Z=_.ranges.length,oe=E)}if(Z>=4){e-=.5;let E=oe.split("/").slice(-2).join("/");n.push(`File-scroll pattern: "${E}" read in ${Z} sequential sections \u2014 use grep instead`)}let Ke=new Map;for(let E of a)if(E.name==="grep"&&E.input?.path&&E.input?.pattern){let _=E.input.path;Ke.has(_)||Ke.set(_,new Set),Ke.get(_).add(E.input.pattern)}let Ee=0,G="";for(let[E,_]of Ke)E.split("/").pop().includes(".")&&_.size>Ee&&(Ee=_.size,G=E);if(Ee>=3){e-=.75;let E=G.split("/").slice(-2).join("/");n.push(`grep flood on single file: "${E}" searched ${Ee}\xD7 with different patterns (file already in context)`)}{let E=new Set,_=new Set,H=/^(test_|demo_|temp_|tmp_|scratch_)/;for(let ee of s){if(ee.name==="write_file"&&ee.input?.path){let P=ee.input.path.split("/").pop(),he=ee.input.path.includes("/tests/");H.test(P)&&!he&&E.add(ee.input.path)}if((ee.name==="bash"||ee.name==="ssh_exec")&&ee.input?.command){let P=ee.input.command.match(/\brm\s+(?:-\w+\s+)?(\S+)/g);if(P)for(let he of P){let Xe=he.split(/\s+/),$e=Xe[Xe.length-1];for(let tt of E)(tt.endsWith($e)||$e.endsWith(tt.split("/").pop()))&&_.add(tt)}}}let se=_.size;if(se>=1){let ee=Math.min(se*.25,.5);e-=ee;let P=[..._].map(he=>he.split("/").pop()).join(", ");n.push(`Temp file write-then-delete: ${P} \u2014 write inline logic or use tests/ instead`)}}let re=o.filter(E=>E.content.startsWith("EXIT")).length;re>=10?(e-=1,n.push(`Bash exit-error storm: ${re} tool results started with EXIT (repeated failing commands)`)):re>=5&&(e-=.5,n.push(`Repeated bash errors: ${re} tool results with non-zero exit code`));for(let E of t){if(E.role!=="assistant")continue;let _="";if(typeof E.content=="string"?_=E.content:Array.isArray(E.content)&&(_=E.content.filter($e=>$e&&($e.type==="text"||typeof $e=="string")).map($e=>typeof $e=="string"?$e:$e.text||"").join("")),_.length<=5e3)continue;let H=_.split(/(?<=\. )/).filter($e=>$e.trim().length>0);if(H.length<6)continue;let se=new Map;for(let $e=0;$e<=H.length-3;$e++){let tt=H.slice($e,$e+3).join("").trim();tt.length>30&&se.set(tt,(se.get(tt)||0)+1)}let ee=0,P="";for(let[$e,tt]of se)tt>ee&&(ee=tt,P=$e);if(ee<3)continue;let Xe=P.length*ee/_.length;if(Xe>=.4||ee>=10){e-=1.5,n.push(`llm output loop: assistant message repeated content detected (${ee}\xD7 same paragraph, ${Math.round(Xe*100)}% repeated)`);break}}{let E=new Set(["read_file","list_directory","search_files","glob","grep"]),_=t.some(se=>Array.isArray(se.tool_calls)?se.tool_calls.some(ee=>E.has(ee.function?.name)):Array.isArray(se.content)?se.content.some(ee=>ee.type==="tool_use"&&E.has(ee.name)):!1);t.some(se=>se.role==="assistant"&&typeof se.content=="string"&&(se.content.includes("## Steps")||se.content.includes("/plan approve")))&&!_&&(e-=2,n.push("plan written without reading any files \u2014 LLM invented data structures from training knowledge (hallucination risk)"))}let et=o.filter(E=>E.content.startsWith("BLOCKED:")&&!E.content.includes("BLOCKED: sed -n")&&!E.content.includes("SSH paused")&&!E.content.includes("SSH temporarily paused"));if(et.length>0){let E=Math.min(et.length*.5,1.5);e-=E,n.push(`${et.length} tool call${et.length===1?"":"s"} blocked (agent attempted denied actions)`)}let Ve=t.filter(E=>{let _=typeof E.content=="string"?E.content:"";return/\[SYSTEM WARNING\] Context wiped \d+×/.test(_)}).length;if(Ve>0){let E=Math.min(Ve*1,2);e-=E,n.push(`Super-nuclear context wipe fired ${Ve}\xD7 (context collapse \u2014 task too large or read loops)`)}{let E=!1,_=!1,H=!1;for(let ee of s){if(ee.name!=="bash")continue;let P=(ee.input?.command||ee.input?.cmd||"").trim();!(/cat\s*>/.test(P)||/<</.test(P))&&/\bcat\s+\S/.test(P)&&(E=!0),/^\s*ls(\s|$)/.test(P)&&!/npm|yarn|pnpm|make|git\b/.test(P)&&(_=!0),/\bfind\s+\S/.test(P)&&!/git\b|npm\b|-exec\b/.test(P)&&(H=!0)}let se=[E,_,H].filter(Boolean).length;if(se>0){let ee=Math.min(se*.25,.75);e-=ee;let P=[];E&&P.push("cat (use read_file)"),_&&P.push("ls (use list_directory)"),H&&P.push("find (use glob)"),n.push(`bash used instead of dedicated tool: ${P.join(", ")}`)}}{let E=s.some(P=>(P.name==="write_file"||P.name==="Write")&&P.input?.path&&(P.input.path.endsWith("requirements.txt")||P.input.path.endsWith("Pipfile")||P.input.path.endsWith("pyproject.toml"))),_=s.some(P=>(P.name==="write_file"||P.name==="Write")&&P.input?.path&&P.input.path.endsWith("package.json")),H=s.filter(P=>(P.name==="bash"||P.name==="Bash")&&P.input?.command).map(P=>P.input.command),se=H.some(P=>/pip\s+install|python\s+-m\s+venv/.test(P)),ee=H.some(P=>/npm\s+install/.test(P));E&&!se?(e-=1,n.push("wrote requirements.txt but never ran pip install \u2014 environment not bootstrapped")):_&&!ee&&s.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 E=t.find(P=>P.role==="assistant"),_="";E&&(typeof E.content=="string"?_=E.content:Array.isArray(E.content)&&(_=E.content.filter(P=>P&&(P.type==="text"||typeof P=="string")).map(P=>typeof P=="string"?P:P.text||"").join("")));let H=_.slice(0,400),se=/^[\d\s\+\-\*\/×÷\(\)\.]+\s*=\s*[\d\s\+\-\*\/×÷\(\)\.]+[.\n]/m,ee=H.split(`
831
+ `)}async function z1(t){let e=st.join(t,"package.json"),n="";if(await hn(()=>Ot.access(e).then(()=>!0).catch(()=>!1)))try{let i=await Ot.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 Qr("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),Kb()]);if(r&&r.length>0){console.log(`${Jo.red} \u26A0 ${r.length} unresolved merge conflict(s):${Jo.reset}`);for(let i of r)console.log(`${Jo.red} ${i.file}${Jo.reset}`);console.log(`${Jo.yellow} \u2192 Resolve conflicts before starting tasks${Jo.reset}`)}console.log()}Vb.exports={gatherProjectContext:Y1,printContext:z1,generateFileTree:W1,_clearContextCache:()=>{Sd.clear(),Qo.clear(),cl=null,Zo={result:null,expiry:0,cwd:null}}}});var dl=ne((vN,Qb)=>{var En=require("fs"),ul=require("path"),{atomicWrite:K1}=Ws();function ti(){return ul.join(process.cwd(),".nex","sessions")}function Ed(){let t=ti();En.existsSync(t)||En.mkdirSync(t,{recursive:!0,mode:448})}function Td(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return ul.join(ti(),`${e}.json`)}function Rd(t,e,n={}){Ed();let o=Td(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 K1(o,JSON.stringify(s,null,2)),{path:o,name:t}}function Jb(t){let e=Td(t);if(!En.existsSync(e))return null;try{return JSON.parse(En.readFileSync(e,"utf-8"))}catch{return null}}function Zb(){Ed();let t=ti(),e=En.readdirSync(t).filter(o=>o.endsWith(".json")),n=[];for(let o of e)try{let s=JSON.parse(En.readFileSync(ul.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 V1(t){let e=Td(t);return En.existsSync(e)?(En.unlinkSync(e),!0):!1}function X1(){let t=Zb();return t.length===0?null:Jb(t[0].name)}var _s=null,is=null,ei=null;function J1(t,e={}){t.length!==0&&(_s&&clearTimeout(_s),is=t,ei=e||{},_s=setTimeout(()=>{is&&is.length>0&&Rd("_autosave",is,ei),_s=null,is=null,ei=null},5e3),_s.unref?.())}function Z1(){_s&&(clearTimeout(_s),_s=null),is&&is.length>0&&(Rd("_autosave",is,ei),is=null,ei=null)}function Q1(){Ed();let t=ti(),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=ul.join(t,r);try{let a=En.statSync(i);new Date(a.mtime)<o&&(En.unlinkSync(i),s++)}catch{}}return s}Qb.exports={saveSession:Rd,loadSession:Jb,listSessions:Zb,deleteSession:V1,getLastSession:X1,autoSave:J1,flushAutoSave:Z1,clearOldSessions:Q1,_getSessionsDir:ti}});var fl=ne((SN,aw)=>{"use strict";var ni=require("fs"),ew=require("path");function tw(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 eC(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 nw(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 sw(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 ow(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 rw(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 iw(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=tw(t),s=nw(t),r=o.length,i=eC(t),a=o.filter(E=>!E.id||!i.has(E.id));t.some(E=>E.role==="user"&&typeof E.content=="string"&&E.content.startsWith("[SYSTEM WARNING]")&&(E.content.includes("edited")||E.content.includes("bash command")||E.content.includes("grep pattern")||E.content.includes("re-read")||E.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 c=o.find(E=>{let _=E.input?.command||E.input?.cmd||"";return/\bsed\s+-n\b/.test(_)});if(c){let E=(c.input?.command||c.input?.cmd||"").slice(0,80);s.some(H=>H.content.includes("BLOCKED: sed -n is forbidden")||H.content.includes("BLOCKED: sed -n"))?(e-=.25,n.push(`sed -n attempted but blocked by agent guard: ${E}`)):(e-=1.5,n.push(`sed -n anti-pattern used: ${E}`))}o.find(E=>{if(E.name!=="grep"&&E.name!=="bash"&&E.name!=="ssh_exec")return!1;let _=E.input?.command||E.input?.cmd||"",H=E.input?.pattern||"",se=`${_} ${H}`;return/(?:-[CAB]|--context|--after|--before)\s*[=\s]?([2-9][1-9]|\d{3,})/.test(se)||/grep.*-[CAB]\s*([2-9][1-9]|\d{3,})/.test(se)})&&(e-=1,n.push("grep used with >20 context lines (context flood risk)"));let d=t.some(E=>E.role==="assistant"),f=sw(t),h=ow(t,3).some(E=>E.length>100&&!/^[^.!]{0,40}\?$/.test(E));if(d&&!h&&(f.length<80||/^[^.!]{0,40}\?$/.test(f))){e-=2;let E=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: ${E}`)}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(E=>{let _=typeof E.content=="string"?E.content:Array.isArray(E.content)?E.content.map(H=>typeof H=="string"?H:H.text||"").join(""):"";return/\[auto-compressed|context compacted|force-compressed/.test(_)})&&(e-=.5,n.push("Auto-compress triggered (context flood indicator)"));let k=rw(a),T=0,$="";for(let[E,_]of k)_>T&&(T=_,$=E);if(T>=3){let[E]=$.split("|");e-=1,n.push(`Same tool call repeated ${T}\xD7 (tool: ${E})`)}let R=!1,C=t.findIndex(E=>E.role==="user"&&typeof E.content=="string"&&E.content.includes("[SYSTEM STOP]")&&E.content.includes('"valid":true'));C>=0&&o.filter(_=>_.index>C).length>0&&(R=!0),R&&(e-=1.5,n.push('Stop-trigger ignored: tool result contained "valid":true but session continued with more tool calls'));let M=o.filter(E=>E.name==="ssh_exec");if(M.length>=8){let E=0,_=1;for(let H=1;H<M.length;H++)M[H].index<=M[H-1].index+2?_++:(E=Math.max(E,_),_=1);E=Math.max(E,_),E>=8&&(e-=.5,n.push(`SSH reconnect storm: ${E} consecutive SSH calls`))}d&&M.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 K=new Map;for(let E of a)if(E.name==="read_file"&&E.input?.path){let _=E.input.path;K.has(_)||K.set(_,{count:0,ranges:[]});let H=K.get(_);if(H.count++,E.input.line_start!=null){let se=E.input.line_start||1,ee=E.input.line_end||se+350;H.ranges.push([se,ee])}}function z(E,_,H){for(let[se,ee]of H){let P=Math.max(E,se),he=Math.min(_,ee);if(he>P){let Xe=he-P,$e=_-E||1;if(Xe/$e>=.7)return!0}}return!1}let X=0,ae="";for(let[E,_]of K){if(_.count<3)continue;if(_.ranges.length===_.count){let ee=!1,P=[];for(let[he,Xe]of _.ranges){if(P.length>0&&z(he,Xe,P)){ee=!0;break}P.push([he,Xe])}if(!ee)continue}if(_.count-_.ranges.length<=2&&_.ranges.length>=1){let ee=!1,P=[];for(let[he,Xe]of _.ranges){if(P.length>0&&z(he,Xe,P)){ee=!0;break}P.push([he,Xe])}if(!ee)continue}_.count>X&&(X=_.count,ae=E)}if(X>=3){e-=1;let E=ae.split("/").slice(-2).join("/");n.push(`read_file loop: "${E}" read ${X}\xD7 (file already in context)`)}let Z=0,oe="";for(let[E,_]of K){if(_.ranges.length<4)continue;let H=[],se=!1;for(let[ee,P]of _.ranges){if(H.length>0&&z(ee,P,H)){se=!0;break}H.push([ee,P])}!se&&_.ranges.length>Z&&(Z=_.ranges.length,oe=E)}if(Z>=4){e-=.5;let E=oe.split("/").slice(-2).join("/");n.push(`File-scroll pattern: "${E}" read in ${Z} sequential sections \u2014 use grep instead`)}let Ke=new Map;for(let E of a)if(E.name==="grep"&&E.input?.path&&E.input?.pattern){let _=E.input.path;Ke.has(_)||Ke.set(_,new Set),Ke.get(_).add(E.input.pattern)}let Ee=0,G="";for(let[E,_]of Ke)E.split("/").pop().includes(".")&&_.size>Ee&&(Ee=_.size,G=E);if(Ee>=3){e-=.75;let E=G.split("/").slice(-2).join("/");n.push(`grep flood on single file: "${E}" searched ${Ee}\xD7 with different patterns (file already in context)`)}{let E=new Set,_=new Set,H=/^(test_|demo_|temp_|tmp_|scratch_)/;for(let ee of o){if(ee.name==="write_file"&&ee.input?.path){let P=ee.input.path.split("/").pop(),he=ee.input.path.includes("/tests/");H.test(P)&&!he&&E.add(ee.input.path)}if((ee.name==="bash"||ee.name==="ssh_exec")&&ee.input?.command){let P=ee.input.command.match(/\brm\s+(?:-\w+\s+)?(\S+)/g);if(P)for(let he of P){let Xe=he.split(/\s+/),$e=Xe[Xe.length-1];for(let tt of E)(tt.endsWith($e)||$e.endsWith(tt.split("/").pop()))&&_.add(tt)}}}let se=_.size;if(se>=1){let ee=Math.min(se*.25,.5);e-=ee;let P=[..._].map(he=>he.split("/").pop()).join(", ");n.push(`Temp file write-then-delete: ${P} \u2014 write inline logic or use tests/ instead`)}}let re=s.filter(E=>E.content.startsWith("EXIT")).length;re>=10?(e-=1,n.push(`Bash exit-error storm: ${re} tool results started with EXIT (repeated failing commands)`)):re>=5&&(e-=.5,n.push(`Repeated bash errors: ${re} tool results with non-zero exit code`));for(let E of t){if(E.role!=="assistant")continue;let _="";if(typeof E.content=="string"?_=E.content:Array.isArray(E.content)&&(_=E.content.filter($e=>$e&&($e.type==="text"||typeof $e=="string")).map($e=>typeof $e=="string"?$e:$e.text||"").join("")),_.length<=5e3)continue;let H=_.split(/(?<=\. )/).filter($e=>$e.trim().length>0);if(H.length<6)continue;let se=new Map;for(let $e=0;$e<=H.length-3;$e++){let tt=H.slice($e,$e+3).join("").trim();tt.length>30&&se.set(tt,(se.get(tt)||0)+1)}let ee=0,P="";for(let[$e,tt]of se)tt>ee&&(ee=tt,P=$e);if(ee<3)continue;let Xe=P.length*ee/_.length;if(Xe>=.4||ee>=10){e-=1.5,n.push(`llm output loop: assistant message repeated content detected (${ee}\xD7 same paragraph, ${Math.round(Xe*100)}% repeated)`);break}}{let E=new Set(["read_file","list_directory","search_files","glob","grep"]),_=t.some(se=>Array.isArray(se.tool_calls)?se.tool_calls.some(ee=>E.has(ee.function?.name)):Array.isArray(se.content)?se.content.some(ee=>ee.type==="tool_use"&&E.has(ee.name)):!1);t.some(se=>se.role==="assistant"&&typeof se.content=="string"&&(se.content.includes("## Steps")||se.content.includes("/plan approve")))&&!_&&(e-=2,n.push("plan written without reading any files \u2014 LLM invented data structures from training knowledge (hallucination risk)"))}let et=s.filter(E=>E.content.startsWith("BLOCKED:")&&!E.content.includes("BLOCKED: sed -n")&&!E.content.includes("SSH paused")&&!E.content.includes("SSH temporarily paused"));if(et.length>0){let E=Math.min(et.length*.5,1.5);e-=E,n.push(`${et.length} tool call${et.length===1?"":"s"} blocked (agent attempted denied actions)`)}let Ve=t.filter(E=>{let _=typeof E.content=="string"?E.content:"";return/\[SYSTEM WARNING\] Context wiped \d+×/.test(_)}).length;if(Ve>0){let E=Math.min(Ve*1,2);e-=E,n.push(`Super-nuclear context wipe fired ${Ve}\xD7 (context collapse \u2014 task too large or read loops)`)}{let E=!1,_=!1,H=!1;for(let ee of o){if(ee.name!=="bash")continue;let P=(ee.input?.command||ee.input?.cmd||"").trim();!(/cat\s*>/.test(P)||/<</.test(P))&&/\bcat\s+\S/.test(P)&&(E=!0),/^\s*ls(\s|$)/.test(P)&&!/npm|yarn|pnpm|make|git\b/.test(P)&&(_=!0),/\bfind\s+\S/.test(P)&&!/git\b|npm\b|-exec\b/.test(P)&&(H=!0)}let se=[E,_,H].filter(Boolean).length;if(se>0){let ee=Math.min(se*.25,.75);e-=ee;let P=[];E&&P.push("cat (use read_file)"),_&&P.push("ls (use list_directory)"),H&&P.push("find (use glob)"),n.push(`bash used instead of dedicated tool: ${P.join(", ")}`)}}{let E=o.some(P=>(P.name==="write_file"||P.name==="Write")&&P.input?.path&&(P.input.path.endsWith("requirements.txt")||P.input.path.endsWith("Pipfile")||P.input.path.endsWith("pyproject.toml"))),_=o.some(P=>(P.name==="write_file"||P.name==="Write")&&P.input?.path&&P.input.path.endsWith("package.json")),H=o.filter(P=>(P.name==="bash"||P.name==="Bash")&&P.input?.command).map(P=>P.input.command),se=H.some(P=>/pip\s+install|python\s+-m\s+venv/.test(P)),ee=H.some(P=>/npm\s+install/.test(P));E&&!se?(e-=1,n.push("wrote requirements.txt but never ran pip install \u2014 environment not bootstrapped")):_&&!ee&&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 E=t.find(P=>P.role==="assistant"),_="";E&&(typeof E.content=="string"?_=E.content:Array.isArray(E.content)&&(_=E.content.filter(P=>P&&(P.type==="text"||typeof P=="string")).map(P=>typeof P=="string"?P:P.text||"").join("")));let H=_.slice(0,400),se=/^[\d\s\+\-\*\/×÷\(\)\.]+\s*=\s*[\d\s\+\-\*\/×÷\(\)\.]+[.\n]/m,ee=H.split(`
832
832
  `).find(P=>{let he=P.trim();return he.length>0&&he.length<=30&&/^\d/.test(he)&&/=/.test(he)&&!/[a-zA-Z]/.test(he)});if(se.test(H)||ee){e-=1.5;let P=(ee||H.split(`
833
833
  `)[0]).trim().slice(0,40);n.push(`Thinking-chain leak: non-sequitur artifact at response start: "${P}"`)}}if(d&&r>0){let E=t.findIndex(H=>H.role==="assistant"),_=t.findIndex(H=>!!(Array.isArray(H.tool_calls)&&H.tool_calls.length>0||Array.isArray(H.content)&&H.content.some(se=>se&&se.type==="tool_use")));if(E!==-1&&_!==-1&&E<_){let H=t[E],se="";typeof H.content=="string"?se=H.content:Array.isArray(H.content)&&(se=H.content.filter(he=>he&&(he.type==="text"||typeof he=="string")).map(he=>typeof he=="string"?he:he.text||"").join(""));let ee=/ssh\s+\S+@\S+\s+"[^"]*\/[^"]*\./.test(se),P=/\/(?:home|var|etc|usr|opt|root|srv|data)\/[a-zA-Z0-9_.\-\/]+\.[a-zA-Z]{2,5}/.test(se);(ee||P)&&(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 E=f;if(E.length>100){let H=(E.match(/^```/gm)||[]).length%2!==0,se=/"\s*:\s*$/.test(E.trimEnd()),ee=/[,\[{]\s*$/.test(E.trimEnd());(H||se||ee)&&(e-=.75,n.push("Truncated response: last assistant message ends mid-code-block or mid-JSON (model hit token limit)"))}}{let E=[];t.forEach((H,se)=>{let ee=[];Array.isArray(H.tool_calls)&&H.tool_calls.forEach(P=>{if((P.function?.name||P.name||"")==="read_file"){let Xe={};try{Xe=typeof P.function?.arguments=="string"?JSON.parse(P.function.arguments):P.function?.arguments||{}}catch{}(Xe.path||"").endsWith(".json")&&ee.push({id:P.id,path:Xe.path})}}),Array.isArray(H.content)&&H.content.forEach(P=>{P&&P.type==="tool_use"&&P.name==="read_file"&&(P.input?.path||"").endsWith(".json")&&ee.push({id:P.id,path:P.input.path})}),ee.forEach(P=>E.push({...P,msgIdx:se}))});let _=0;for(let H of E){let se=null;for(let P of t){if(P.role==="tool"&&P.tool_call_id===H.id&&typeof P.content=="string"){se=P.content;break}if(P.role==="user"&&Array.isArray(P.content)){let he=P.content.find(Xe=>Xe&&Xe.type==="tool_result"&&Xe.tool_use_id===H.id);if(he){se=typeof he.content=="string"?he.content:"";break}}}if(!se)continue;se.split(`
834
- `).filter(P=>P.trim()).length<5&&/^\s*\[/.test(se)&&!/\]\s*$/.test(se.trimEnd())&&_++}_>=1&&(e-=.75,n.push(`Shallow JSON read: ${_} .json file${_>1?"s":""} read with < 5 lines \u2014 array was incomplete, model drew conclusions from truncated data`))}{let E=o.filter(_=>/argument errors?/i.test(_.content)||/missing required (argument|parameter)/i.test(_.content)||/invalid argument/i.test(_.content));E.length>=3?(e-=.75,n.push(`Repeated tool argument errors: ${E.length} tool calls returned argument errors \u2014 model couldn't correct its tool usage`)):E.length>=2&&(e-=.25,n.push(`Tool argument errors: ${E.length} tool calls returned argument errors`))}{let E=!1,_=0,H=0;for(let se of a){if((se.name==="bash"||se.name==="Bash")&&se.input?.command&&/git\s+commit\b/.test(se.input.command)){E&&(H=Math.max(H,_)),E=!0,_=0;continue}E&&(se.name==="bash"||se.name==="Bash")&&se.input?.command&&/git\s+(status|diff|log|show)\b/.test(se.input.command)&&_++}H=Math.max(H,_),H>=3&&(e-=.75,n.push(`Post-commit verification waste: ${H} git status/diff/log calls after commit`))}e=Math.max(0,Math.min(10,e)),e=Math.round(e*10)/10;let Ae=e>=9?"A":e>=8?"B":e>=7?"C":e>=6?"D":"F",Oe=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:Ae,issues:n,summary:Oe}}function tC(t){try{let{loadSession:e}=dl(),n=e(t);return n?iw(n.messages||[]):null}catch{return null}}function nC(t,e=null){let{score:n,issues:s}=t,o=e?.dim||"",r=e?.reset||"",i=e?.yellow||"";if(n>=8||s.length===0)return"";let a=s.map(u=>u.replace(/:\s+\d+.*$/,"").replace(/\s*\(.*?\)/,"").replace(/\s*—.*$/,""));if(n>=6){let u=a.slice(0,3),d=a.length-u.length,f=u.join(" \xB7 ");return d>0&&(f+=` (+${d})`),`
835
- ${o}${f}${r}`}let l="";for(let u of a.slice(0,4))l+=`
836
- ${i}\u26A0${r} ${o}${u}${r}`;let c=a.length-4;return c>0&&(l+=`
837
- ${o}(+${c} more)${r}`),l}function sC(t,e={}){try{let n=ew.join(process.cwd(),".nex");ni.existsSync(n)||ni.mkdirSync(n,{recursive:!0});let s=ew.join(n,"benchmark-history.json"),o=[];if(ni.existsSync(s))try{o=JSON.parse(ni.readFileSync(s,"utf-8"))}catch{o=[]}Array.isArray(o)||(o=[]);let r=t>=9?"A":t>=8?"B":t>=7?"C":t>=6?"D":"F",i={date:new Date().toISOString(),version:e.version||null,model:e.model||null,score:t,grade:r,sessionName:e.sessionName||null,issues:Array.isArray(e.issues)?e.issues:[]};o.push(i),o.length>100&&(o=o.slice(o.length-100)),ni.writeFileSync(s,JSON.stringify(o,null,2))}catch{}}aw.exports={scoreMessages:iw,scoreSession:tC,formatScore:nC,appendScoreHistory:sC,_extractToolCalls:tw,_extractToolResults:nw,_getLastAssistantText:sw,_getLastNAssistantTexts:ow,_countDuplicateToolCalls:rw}});var ro=ne((EN,fw)=>{"use strict";var oC=require("os"),Cd=require("path"),$s=require("fs"),si=Cd.join(oC.homedir(),".nex-code","model-routing.json"),pl={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}},lw=["agentic","frontend","sysadmin","data","coding"];function rC(t){if(!t||t.length<8)return null;for(let e of lw){let n=pl[e];if(!n.pattern||n.pattern.test(t))return n}return pl.coding}function oi(){try{if($s.existsSync(si))return JSON.parse($s.readFileSync(si,"utf-8"))}catch{}return{}}function cw(t){if(process.env.NEX_FORCE_MODEL)return process.env.NEX_FORCE_MODEL;let e=pl[t];return e?.envVar&&process.env[e.envVar]?process.env[e.envVar]:oi()[t]||null}var uw={explore:10,plan:10,implement:35,verify:8},Ad={explore:"devstral-small-2:24b",plan:"qwen3-coder:480b",implement:null,verify:"devstral-small-2:24b"};function dw(){let t=oi();if(t.phases&&Object.keys(t.phases).length>0)return t.phases;try{let{getActiveProviderName:e}=vt();if(e()==="ollama")return Ad}catch{}return process.env.NEX_PHASE_ROUTING==="1"?Ad:null}function iC(t,e){if(process.env.NEX_FORCE_MODEL)return process.env.NEX_FORCE_MODEL;let n=dw();return n?.[t]?n[t]:e?cw(e):null}function aC(t){return oi().phaseBudgets?.[t]||uw[t]||20}function lC(){return process.env.NEX_PHASE_ROUTING==="0"||process.env.NEX_FORCE_MODEL?!1:dw()!==null}function cC(t){let e=Cd.dirname(si);$s.existsSync(e)||$s.mkdirSync(e,{recursive:!0});let n=oi(),s={...n,...t};!t.phases&&n.phases&&(s.phases=n.phases),!t.phaseBudgets&&n.phaseBudgets&&(s.phaseBudgets=n.phaseBudgets),$s.writeFileSync(si,JSON.stringify(s,null,2));try{let o=Cd.join(e,".env"),r="";$s.existsSync(o)&&(r=$s.readFileSync(o,"utf-8"));let i=r.split(/\r?\n/),a=(l,c)=>{let u=i.findIndex(d=>d.startsWith(l+"="));u>=0?i[u]=`${l}=${c}`:i.push(`${l}=${c}`)};s.coding&&a("NEX_ROUTE_CODING",s.coding),s.frontend&&a("NEX_ROUTE_FRONTEND",s.frontend),s.sysadmin&&a("NEX_ROUTE_SYSADMIN",s.sysadmin),s.data&&a("NEX_ROUTE_DATA",s.data),s.agentic&&a("NEX_ROUTE_AGENTIC",s.agentic),s.phases&&(s.phases.plan&&a("NEX_PHASE_PLAN_MODEL",s.phases.plan),s.phases.implement&&a("NEX_PHASE_IMPLEMENT_MODEL",s.phases.implement),s.phases.verify&&a("NEX_PHASE_VERIFY_MODEL",s.phases.verify)),$s.writeFileSync(o,i.filter(l=>l.trim()!=="").join(`
834
+ `).filter(P=>P.trim()).length<5&&/^\s*\[/.test(se)&&!/\]\s*$/.test(se.trimEnd())&&_++}_>=1&&(e-=.75,n.push(`Shallow JSON read: ${_} .json file${_>1?"s":""} read with < 5 lines \u2014 array was incomplete, model drew conclusions from truncated data`))}{let E=s.filter(_=>/argument errors?/i.test(_.content)||/missing required (argument|parameter)/i.test(_.content)||/invalid argument/i.test(_.content));E.length>=3?(e-=.75,n.push(`Repeated tool argument errors: ${E.length} tool calls returned argument errors \u2014 model couldn't correct its tool usage`)):E.length>=2&&(e-=.25,n.push(`Tool argument errors: ${E.length} tool calls returned argument errors`))}{let E=!1,_=0,H=0;for(let se of a){if((se.name==="bash"||se.name==="Bash")&&se.input?.command&&/git\s+commit\b/.test(se.input.command)){E&&(H=Math.max(H,_)),E=!0,_=0;continue}E&&(se.name==="bash"||se.name==="Bash")&&se.input?.command&&/git\s+(status|diff|log|show)\b/.test(se.input.command)&&_++}H=Math.max(H,_),H>=3&&(e-=.75,n.push(`Post-commit verification waste: ${H} git status/diff/log calls after commit`))}e=Math.max(0,Math.min(10,e)),e=Math.round(e*10)/10;let Ae=e>=9?"A":e>=8?"B":e>=7?"C":e>=6?"D":"F",Oe=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:Ae,issues:n,summary:Oe}}function tC(t){try{let{loadSession:e}=dl(),n=e(t);return n?iw(n.messages||[]):null}catch{return null}}function nC(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(u=>u.replace(/:\s+\d+.*$/,"").replace(/\s*\(.*?\)/,"").replace(/\s*—.*$/,""));if(n>=6){let u=a.slice(0,3),d=a.length-u.length,f=u.join(" \xB7 ");return d>0&&(f+=` (+${d})`),`
835
+ ${s}${f}${r}`}let l="";for(let u of a.slice(0,4))l+=`
836
+ ${i}\u26A0${r} ${s}${u}${r}`;let c=a.length-4;return c>0&&(l+=`
837
+ ${s}(+${c} more)${r}`),l}function sC(t,e={}){try{let n=ew.join(process.cwd(),".nex");ni.existsSync(n)||ni.mkdirSync(n,{recursive:!0});let o=ew.join(n,"benchmark-history.json"),s=[];if(ni.existsSync(o))try{s=JSON.parse(ni.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)),ni.writeFileSync(o,JSON.stringify(s,null,2))}catch{}}aw.exports={scoreMessages:iw,scoreSession:tC,formatScore:nC,appendScoreHistory:sC,_extractToolCalls:tw,_extractToolResults:nw,_getLastAssistantText:sw,_getLastNAssistantTexts:ow,_countDuplicateToolCalls:rw}});var ro=ne((EN,fw)=>{"use strict";var oC=require("os"),Cd=require("path"),$s=require("fs"),si=Cd.join(oC.homedir(),".nex-code","model-routing.json"),pl={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}},lw=["agentic","frontend","sysadmin","data","coding"];function rC(t){if(!t||t.length<8)return null;for(let e of lw){let n=pl[e];if(!n.pattern||n.pattern.test(t))return n}return pl.coding}function oi(){try{if($s.existsSync(si))return JSON.parse($s.readFileSync(si,"utf-8"))}catch{}return{}}function cw(t){if(process.env.NEX_FORCE_MODEL)return process.env.NEX_FORCE_MODEL;let e=pl[t];return e?.envVar&&process.env[e.envVar]?process.env[e.envVar]:oi()[t]||null}var uw={explore:10,plan:10,implement:35,verify:8},Ad={explore:"devstral-small-2:24b",plan:"qwen3-coder:480b",implement:null,verify:"devstral-small-2:24b"};function dw(){let t=oi();if(t.phases&&Object.keys(t.phases).length>0)return t.phases;try{let{getActiveProviderName:e}=vt();if(e()==="ollama")return Ad}catch{}return process.env.NEX_PHASE_ROUTING==="1"?Ad:null}function iC(t,e){if(process.env.NEX_FORCE_MODEL)return process.env.NEX_FORCE_MODEL;let n=dw();return n?.[t]?n[t]:e?cw(e):null}function aC(t){return oi().phaseBudgets?.[t]||uw[t]||20}function lC(){return process.env.NEX_PHASE_ROUTING==="0"||process.env.NEX_FORCE_MODEL?!1:dw()!==null}function cC(t){let e=Cd.dirname(si);$s.existsSync(e)||$s.mkdirSync(e,{recursive:!0});let n=oi(),o={...n,...t};!t.phases&&n.phases&&(o.phases=n.phases),!t.phaseBudgets&&n.phaseBudgets&&(o.phaseBudgets=n.phaseBudgets),$s.writeFileSync(si,JSON.stringify(o,null,2));try{let s=Cd.join(e,".env"),r="";$s.existsSync(s)&&(r=$s.readFileSync(s,"utf-8"));let i=r.split(/\r?\n/),a=(l,c)=>{let u=i.findIndex(d=>d.startsWith(l+"="));u>=0?i[u]=`${l}=${c}`:i.push(`${l}=${c}`)};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)),$s.writeFileSync(s,i.filter(l=>l.trim()!=="").join(`
838
838
  `)+`
839
- `)}catch{}}fw.exports={CATEGORIES:pl,DETECTION_ORDER:lw,detectCategory:rC,getModelForCategory:cw,getModelForPhase:iC,getPhaseBudget:aC,isPhaseRoutingEnabled:lC,DEFAULT_PHASE_BUDGETS:uw,BUILTIN_PHASE_DEFAULTS:Ad,saveRoutingConfig:cC,loadRoutingConfig:oi,ROUTING_CONFIG_PATH:si}});var gw=ne((TN,mw)=>{"use strict";var io=require("fs"),ri=require("path"),uC=require("os"),{detectCategory:dC}=ro(),er=ri.join(uC.homedir(),".nex-code","examples"),Od=ri.join(__dirname,"..","examples");function pw(t){try{let n=io.readFileSync(t,"utf-8").replace(/<!--[\s\S]*?-->/g,"").trim(),s=n.match(/^user:\s*(.+)$/m);if(!s)return null;let o=s[1].trim(),r=n.indexOf(`
839
+ `)}catch{}}fw.exports={CATEGORIES:pl,DETECTION_ORDER:lw,detectCategory:rC,getModelForCategory:cw,getModelForPhase:iC,getPhaseBudget:aC,isPhaseRoutingEnabled:lC,DEFAULT_PHASE_BUDGETS:uw,BUILTIN_PHASE_DEFAULTS:Ad,saveRoutingConfig:cC,loadRoutingConfig:oi,ROUTING_CONFIG_PATH:si}});var gw=ne((TN,mw)=>{"use strict";var io=require("fs"),ri=require("path"),uC=require("os"),{detectCategory:dC}=ro(),er=ri.join(uC.homedir(),".nex-code","examples"),Od=ri.join(__dirname,"..","examples");function pw(t){try{let n=io.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(`
840
840
  A: |`);if(r===-1)return null;let i=n.slice(r+5),a=[],l=0;for(let u of i.split(`
841
841
  `))if(u.startsWith(" ")){for(;l>0;)a.push(""),l--;a.push(u.slice(2))}else if(u.trim()==="")a.length>0&&l++;else break;if(a.length===0)return null;let c=a.join(`
842
- `).trim();return{user:o,assistant:c}}catch{return null}}function hw(t){let e=`${t}.md`,n=ri.join(er,e);if(io.existsSync(n)){let o=pw(n);if(o)return o}let s=ri.join(Od,e);return io.existsSync(s)?pw(s):null}function fC(t){if(process.env.NEX_FEW_SHOT==="0"||!t||t.length<8)return null;let e=dC(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:hw(e.id)}function pC(){let t=new Set;for(let e of[er,Od])try{for(let n of io.readdirSync(e))n.endsWith(".md")&&t.add(n.replace(".md",""))}catch{}return[...t].sort()}function hC(t,e){io.existsSync(er)||io.mkdirSync(er,{recursive:!0});let n=`<!-- Auto-extracted from high-scoring session \u2014 edit as needed -->
842
+ `).trim();return{user:s,assistant:c}}catch{return null}}function hw(t){let e=`${t}.md`,n=ri.join(er,e);if(io.existsSync(n)){let s=pw(n);if(s)return s}let o=ri.join(Od,e);return io.existsSync(o)?pw(o):null}function fC(t){if(process.env.NEX_FEW_SHOT==="0"||!t||t.length<8)return null;let e=dC(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:hw(e.id)}function pC(){let t=new Set;for(let e of[er,Od])try{for(let n of io.readdirSync(e))n.endsWith(".md")&&t.add(n.replace(".md",""))}catch{}return[...t].sort()}function hC(t,e){io.existsSync(er)||io.mkdirSync(er,{recursive:!0});let n=`<!-- Auto-extracted from high-scoring session \u2014 edit as needed -->
843
843
 
844
844
  user: ${e.user}
845
845
 
846
846
  A: |
847
847
  ${e.assistant.split(`
848
- `).map(s=>` ${s}`).join(`
848
+ `).map(o=>` ${o}`).join(`
849
849
  `)}
850
- `;io.writeFileSync(ri.join(er,`${t}.md`),n,"utf-8")}mw.exports={getFewShotForInput:fC,loadExampleForCategory:hw,listAvailableExamples:pC,savePrivateExample:hC,PRIVATE_EXAMPLES_DIR:er,BUNDLED_EXAMPLES_DIR:Od}});var kw=ne((CN,$w)=>{var en=require("fs"),tr=require("path"),{C:RN}=xt(),{atomicWrite:mC,withFileLockSync:gC}=Ws(),hl={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"},nr={...hl};function yw(){let t=tr.join(process.cwd(),".nex","config.json");if(en.existsSync(t))try{let e=JSON.parse(en.readFileSync(t,"utf-8"));e.permissions&&(nr={...hl,...e.permissions})}catch{}}function yC(){let t=tr.join(process.cwd(),".nex"),e=tr.join(t,"config.json");en.existsSync(t)||en.mkdirSync(t,{recursive:!0}),gC(e,()=>{let n={};if(en.existsSync(e))try{n=JSON.parse(en.readFileSync(e,"utf-8"))}catch{n={}}n.permissions=nr,mC(e,JSON.stringify(n,null,2))})}function bw(t){return nr[t]||"ask"}function bC(t,e){return["allow","ask","deny"].includes(e)?(nr[t]=e,!0):!1}function wC(t){return bw(t)}function _C(){return Object.entries(nr).map(([t,e])=>({tool:t,mode:e}))}function $C(){nr={...hl}}var ii={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 ww(){let t=tr.join(process.cwd(),".nex","config.json");try{return en.existsSync(t)&&JSON.parse(en.readFileSync(t,"utf-8")).teamPermissions||null}catch{return null}}function kC(t){let e=tr.join(process.cwd(),".nex"),n=tr.join(e,"config.json");en.existsSync(e)||en.mkdirSync(e,{recursive:!0});let s={};try{en.existsSync(n)&&(s=JSON.parse(en.readFileSync(n,"utf-8")))}catch{s={}}s.teamPermissions=t,en.writeFileSync(n,JSON.stringify(s,null,2),"utf-8")}function _w(){let t=ww();if(!t)return ii.admin;let e=t.role||"admin",n=ii[e]||ii.admin;return{...n,...t.overrides,blockedTools:[...n.blockedTools||[],...t.overrides?.blockedTools||[]]}}function xC(t){let e=_w();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 vC(){return Object.entries(ii).map(([t,e])=>({name:t,description:e.description,toolCount:e.allowedTools?`${e.allowedTools.length} allowed`:"all allowed",blockedCount:e.blockedTools.length}))}yw();$w.exports={getPermission:bw,setPermission:bC,checkPermission:wC,listPermissions:_C,loadPermissions:yw,savePermissions:yC,resetPermissions:$C,DEFAULT_PERMISSIONS:hl,PERMISSION_PRESETS:ii,loadPresetConfig:ww,savePresetConfig:kC,getEffectivePreset:_w,isToolAllowed:xC,listPresets:vC}});var yl=ne((ON,Tw)=>{var lo=require("fs"),ml=require("path"),AN=require("readline"),{C:ze}=xt(),Ge=null,Md=!1,Nd=null,xw=new Set(["read_file","list_directory","search_files","glob","grep","web_search","web_fetch","git_status","git_diff","git_log","git_show"]);function gl(){return ml.join(process.cwd(),".nex","plans")}function vw(){let t=gl();lo.existsSync(t)||lo.mkdirSync(t,{recursive:!0})}function SC(t,e=[]){return Ge={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()},Ge}function EC(){return Ge}function TC(t){Md=t}function RC(){return Md}function CC(){return!Ge||Ge.status!=="draft"?!1:(Ge.status="approved",Ge.updatedAt=new Date().toISOString(),!0)}function AC(){return!Ge||Ge.status!=="approved"?!1:(Ge.status="executing",!0)}function Pd(t,e){return!Ge||t<0||t>=Ge.steps.length?!1:(Ge.steps[t].status=e,Ge.updatedAt=new Date().toISOString(),Ge.steps.every(n=>n.status==="done"||n.status==="skipped")&&(Ge.status="completed"),!0)}function OC(t){if(!t)return`${ze.dim}No active plan${ze.reset}`;let e={draft:`${ze.yellow}DRAFT${ze.reset}`,approved:`${ze.green}APPROVED${ze.reset}`,executing:`${ze.blue}EXECUTING${ze.reset}`,completed:`${ze.green}COMPLETED${ze.reset}`},n=[];n.push(`
850
+ `;io.writeFileSync(ri.join(er,`${t}.md`),n,"utf-8")}mw.exports={getFewShotForInput:fC,loadExampleForCategory:hw,listAvailableExamples:pC,savePrivateExample:hC,PRIVATE_EXAMPLES_DIR:er,BUNDLED_EXAMPLES_DIR:Od}});var kw=ne((CN,$w)=>{var en=require("fs"),tr=require("path"),{C:RN}=xt(),{atomicWrite:mC,withFileLockSync:gC}=Ws(),hl={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"},nr={...hl};function yw(){let t=tr.join(process.cwd(),".nex","config.json");if(en.existsSync(t))try{let e=JSON.parse(en.readFileSync(t,"utf-8"));e.permissions&&(nr={...hl,...e.permissions})}catch{}}function yC(){let t=tr.join(process.cwd(),".nex"),e=tr.join(t,"config.json");en.existsSync(t)||en.mkdirSync(t,{recursive:!0}),gC(e,()=>{let n={};if(en.existsSync(e))try{n=JSON.parse(en.readFileSync(e,"utf-8"))}catch{n={}}n.permissions=nr,mC(e,JSON.stringify(n,null,2))})}function bw(t){return nr[t]||"ask"}function bC(t,e){return["allow","ask","deny"].includes(e)?(nr[t]=e,!0):!1}function wC(t){return bw(t)}function _C(){return Object.entries(nr).map(([t,e])=>({tool:t,mode:e}))}function $C(){nr={...hl}}var ii={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 ww(){let t=tr.join(process.cwd(),".nex","config.json");try{return en.existsSync(t)&&JSON.parse(en.readFileSync(t,"utf-8")).teamPermissions||null}catch{return null}}function kC(t){let e=tr.join(process.cwd(),".nex"),n=tr.join(e,"config.json");en.existsSync(e)||en.mkdirSync(e,{recursive:!0});let o={};try{en.existsSync(n)&&(o=JSON.parse(en.readFileSync(n,"utf-8")))}catch{o={}}o.teamPermissions=t,en.writeFileSync(n,JSON.stringify(o,null,2),"utf-8")}function _w(){let t=ww();if(!t)return ii.admin;let e=t.role||"admin",n=ii[e]||ii.admin;return{...n,...t.overrides,blockedTools:[...n.blockedTools||[],...t.overrides?.blockedTools||[]]}}function xC(t){let e=_w();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 vC(){return Object.entries(ii).map(([t,e])=>({name:t,description:e.description,toolCount:e.allowedTools?`${e.allowedTools.length} allowed`:"all allowed",blockedCount:e.blockedTools.length}))}yw();$w.exports={getPermission:bw,setPermission:bC,checkPermission:wC,listPermissions:_C,loadPermissions:yw,savePermissions:yC,resetPermissions:$C,DEFAULT_PERMISSIONS:hl,PERMISSION_PRESETS:ii,loadPresetConfig:ww,savePresetConfig:kC,getEffectivePreset:_w,isToolAllowed:xC,listPresets:vC}});var yl=ne((ON,Tw)=>{var lo=require("fs"),ml=require("path"),AN=require("readline"),{C:ze}=xt(),Ge=null,Md=!1,Nd=null,xw=new Set(["read_file","list_directory","search_files","glob","grep","web_search","web_fetch","git_status","git_diff","git_log","git_show"]);function gl(){return ml.join(process.cwd(),".nex","plans")}function vw(){let t=gl();lo.existsSync(t)||lo.mkdirSync(t,{recursive:!0})}function SC(t,e=[]){return Ge={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()},Ge}function EC(){return Ge}function TC(t){Md=t}function RC(){return Md}function CC(){return!Ge||Ge.status!=="draft"?!1:(Ge.status="approved",Ge.updatedAt=new Date().toISOString(),!0)}function AC(){return!Ge||Ge.status!=="approved"?!1:(Ge.status="executing",!0)}function Pd(t,e){return!Ge||t<0||t>=Ge.steps.length?!1:(Ge.steps[t].status=e,Ge.updatedAt=new Date().toISOString(),Ge.steps.every(n=>n.status==="done"||n.status==="skipped")&&(Ge.status="completed"),!0)}function OC(t){if(!t)return`${ze.dim}No active plan${ze.reset}`;let e={draft:`${ze.yellow}DRAFT${ze.reset}`,approved:`${ze.green}APPROVED${ze.reset}`,executing:`${ze.blue}EXECUTING${ze.reset}`,completed:`${ze.green}COMPLETED${ze.reset}`},n=[];n.push(`
851
851
  ${ze.bold}${ze.cyan}Plan: ${t.task}${ze.reset}`),n.push(`${ze.dim}Status: ${e[t.status]||t.status}${ze.reset}
852
- `);for(let s=0;s<t.steps.length;s++){let o=t.steps[s],r;switch(o.status){case"done":r=`${ze.green}\u2713${ze.reset}`;break;case"in_progress":r=`${ze.blue}\u2192${ze.reset}`;break;case"skipped":r=`${ze.dim}\u25CB${ze.reset}`;break;default:r=`${ze.dim} ${ze.reset}`}n.push(` ${r} ${ze.bold}Step ${s+1}:${ze.reset} ${o.description}`),o.files.length>0&&n.push(` ${ze.dim}Files: ${o.files.join(", ")}${ze.reset}`)}return n.push(""),n.join(`
853
- `)}function PC(t){if(t||(t=Ge),!t)return null;vw();let e=ml.join(gl(),`${t.name}.json`);return lo.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function MC(t){let e=ml.join(gl(),`${t}.json`);if(!lo.existsSync(e))return null;try{let n=JSON.parse(lo.readFileSync(e,"utf-8"));return Ge=n,n}catch{return null}}function NC(){vw();let t=gl(),e=lo.readdirSync(t).filter(s=>s.endsWith(".json")),n=[];for(let s of e)try{let o=JSON.parse(lo.readFileSync(ml.join(t,s),"utf-8"));n.push({name:o.name,task:o.task,status:o.status,steps:o.steps?o.steps.length:0,createdAt:o.createdAt})}catch{}return n.sort((s,o)=>(o.createdAt||"").localeCompare(s.createdAt||""))}function LC(t){if(!t)return[];let e=[],n=t.match(/##\s+Steps?\s*\n([\s\S]*?)(?:\n##|\s*$)/i),s=n?n[1]:t,o=/^\s*(\d+)[.)]\s+(.+)/gm,r;for(;(r=o.exec(s))!==null;){let a=r[2].trim().replace(/^\*\*What\*\*:\s*/i,"").replace(/^\*\*\d+\.\*\*\s*/,"").replace(/\*\*/g,"").trim();a.length>3&&e.push({description:a,files:[],status:"pending"})}if(e.length===0){let i=/\*\*Step\s+\d+[:.]\*\*\s*(.+)/gi;for(;(r=i.exec(t))!==null;){let a=r[1].replace(/\*\*/g,"").trim();a.length>3&&e.push({description:a,files:[],status:"pending"})}}if(e.length>0){let i=/\*\*(?:Where|Files?)\*\*:\s*(.+)/gi,a=[...t.matchAll(i)];for(let l=0;l<Math.min(e.length,a.length);l++){let c=a[l][1];e[l].files=c.split(/[,\s]+/).filter(u=>/[./]/.test(u)).slice(0,5)}}return e}function IC(t){Nd=t}function jC(){return Nd}function DC(){Ge=null,Md=!1,Nd=null,UC()}function qC(){return`
852
+ `);for(let o=0;o<t.steps.length;o++){let s=t.steps[o],r;switch(s.status){case"done":r=`${ze.green}\u2713${ze.reset}`;break;case"in_progress":r=`${ze.blue}\u2192${ze.reset}`;break;case"skipped":r=`${ze.dim}\u25CB${ze.reset}`;break;default:r=`${ze.dim} ${ze.reset}`}n.push(` ${r} ${ze.bold}Step ${o+1}:${ze.reset} ${s.description}`),s.files.length>0&&n.push(` ${ze.dim}Files: ${s.files.join(", ")}${ze.reset}`)}return n.push(""),n.join(`
853
+ `)}function PC(t){if(t||(t=Ge),!t)return null;vw();let e=ml.join(gl(),`${t.name}.json`);return lo.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function MC(t){let e=ml.join(gl(),`${t}.json`);if(!lo.existsSync(e))return null;try{let n=JSON.parse(lo.readFileSync(e,"utf-8"));return Ge=n,n}catch{return null}}function NC(){vw();let t=gl(),e=lo.readdirSync(t).filter(o=>o.endsWith(".json")),n=[];for(let o of e)try{let s=JSON.parse(lo.readFileSync(ml.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 LC(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 l=0;l<Math.min(e.length,a.length);l++){let c=a[l][1];e[l].files=c.split(/[,\s]+/).filter(u=>/[./]/.test(u)).slice(0,5)}}return e}function IC(t){Nd=t}function jC(){return Nd}function DC(){Ge=null,Md=!1,Nd=null,UC()}function qC(){return`
854
854
  PLAN MODE ACTIVE: You are in analysis-only mode. You MUST NOT execute any changes.
855
855
 
856
856
  # Allowed Tools (read-only)
@@ -906,7 +906,7 @@ Bullet list of potential issues and mitigations.
906
906
  - Order steps by dependency (later steps may depend on earlier ones).
907
907
  - After presenting the plan, tell the user to type \`/plan approve\` to proceed.
908
908
  - Do NOT make any file changes \u2014 your role is analysis and planning only.
909
- - 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 ao=0;function FC(){!Ge||Ge.status!=="executing"||(ao>0&&Pd(ao-1,"done"),ao<Ge.steps.length&&(Pd(ao,"in_progress"),ao++))}function BC(){if(!Ge||Ge.status!=="executing"||Ge.steps.length===0)return null;let t=Math.min(ao,Ge.steps.length),e=Ge.steps.length,n=Math.max(0,t-1),s=Ge.steps[n]?.description||"";return{current:t,total:e,description:s}}function UC(){ao=0}var Sw=["interactive","semi-auto","autonomous"],Ew="interactive";function WC(t){return Sw.includes(t)?(Ew=t,!0):!1}function HC(){return Ew}Tw.exports={createPlan:SC,getActivePlan:EC,setPlanMode:TC,isPlanMode:RC,approvePlan:CC,startExecution:AC,updateStep:Pd,formatPlan:OC,savePlan:PC,loadPlan:MC,listPlans:NC,clearPlan:DC,getPlanModePrompt:qC,setPlanContent:IC,getPlanContent:jC,extractStepsFromText:LC,advancePlanStep:FC,getPlanStepInfo:BC,PLAN_MODE_ALLOWED_TOOLS:xw,setAutonomyLevel:WC,getAutonomyLevel:HC,AUTONOMY_LEVELS:Sw}});var Pw=ne((PN,Ow)=>{var{execSync:GC}=require("child_process"),Ld=require("path"),ai=require("fs"),Id=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function Rw(){return Ld.join(process.cwd(),".nex","hooks")}function YC(){return Ld.join(process.cwd(),".nex","config.json")}function Cw(){let t=YC();if(!ai.existsSync(t))return{};try{return JSON.parse(ai.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function bl(t){if(!Id.includes(t))return[];let e=[],n=Rw(),s=Ld.join(n,t);ai.existsSync(s)&&e.push(s);let o=Cw();if(o[t]){let r=Array.isArray(o[t])?o[t]:[o[t]];e.push(...r)}return e}function Aw(t,e={},n=3e4){try{return{success:!0,exitCode:0,output:GC(t,{cwd:process.cwd(),encoding:"utf-8",timeout:n,env:{...process.env,...e},stdio:["pipe","pipe","pipe"]}).trim()}}catch(s){let o=typeof s.status=="number"?s.status:1;return{success:!1,exitCode:o,blocked:o===2,output:s.stdout?s.stdout.trim():"",error:s.stderr?s.stderr.trim():s.message}}}function zC(t,e={}){let n=bl(t);if(n.length===0)return{results:[],blocked:!1};let s={};for(let[r,i]of Object.entries(e))s[`NEX_${r.toUpperCase()}`]=String(i);let o=[];for(let r of n){let i=Aw(r,s);if(o.push({command:r,...i}),i.blocked&&t.startsWith("pre-")){let a=i.output||i.error||"hook blocked tool call";return{results:o,blocked:!0,blockReason:a}}if(!i.success&&t.startsWith("pre-"))break}return{results:o,blocked:!1}}function KC(t){return bl(t).length>0}function VC(){let t=[];for(let e of Id){let n=bl(e);n.length>0&&t.push({event:e,commands:n})}return t}function XC(){let t=Rw();return ai.existsSync(t)||ai.mkdirSync(t,{recursive:!0}),t}Ow.exports={HOOK_EVENTS:Id,loadHookConfig:Cw,getHooksForEvent:bl,executeHook:Aw,runHooks:zC,hasHooks:KC,listHooks:VC,initHooksDir:XC}});var e0=ne((IN,Qw)=>{"use strict";var{callWithRetry:Lw,runSubAgent:Mw,clearAllLocks:JC}=td(),{parseModelSpec:Iw,getActiveProviderName:MN,getActiveModelId:NN}=vt(),{detectCategory:ZC,getModelForCategory:Nw}=ro(),{MultiProgress:QC,C:ve}=xt(),{getModelBriefing:LN}=Ga(),jw=parseInt(process.env.NEX_MAX_PARALLEL||"8",10),wl=parseInt(process.env.NEX_MAX_SUBTASKS||"8",10),Dw="devstral-2:123b",qw="kimi-k2.5",Fw=`You are a task decomposition engine. Given a complex user request, split it into independent, atomic sub-tasks.
909
+ - 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 ao=0;function FC(){!Ge||Ge.status!=="executing"||(ao>0&&Pd(ao-1,"done"),ao<Ge.steps.length&&(Pd(ao,"in_progress"),ao++))}function BC(){if(!Ge||Ge.status!=="executing"||Ge.steps.length===0)return null;let t=Math.min(ao,Ge.steps.length),e=Ge.steps.length,n=Math.max(0,t-1),o=Ge.steps[n]?.description||"";return{current:t,total:e,description:o}}function UC(){ao=0}var Sw=["interactive","semi-auto","autonomous"],Ew="interactive";function WC(t){return Sw.includes(t)?(Ew=t,!0):!1}function HC(){return Ew}Tw.exports={createPlan:SC,getActivePlan:EC,setPlanMode:TC,isPlanMode:RC,approvePlan:CC,startExecution:AC,updateStep:Pd,formatPlan:OC,savePlan:PC,loadPlan:MC,listPlans:NC,clearPlan:DC,getPlanModePrompt:qC,setPlanContent:IC,getPlanContent:jC,extractStepsFromText:LC,advancePlanStep:FC,getPlanStepInfo:BC,PLAN_MODE_ALLOWED_TOOLS:xw,setAutonomyLevel:WC,getAutonomyLevel:HC,AUTONOMY_LEVELS:Sw}});var Pw=ne((PN,Ow)=>{var{execSync:GC}=require("child_process"),Ld=require("path"),ai=require("fs"),Id=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function Rw(){return Ld.join(process.cwd(),".nex","hooks")}function YC(){return Ld.join(process.cwd(),".nex","config.json")}function Cw(){let t=YC();if(!ai.existsSync(t))return{};try{return JSON.parse(ai.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function bl(t){if(!Id.includes(t))return[];let e=[],n=Rw(),o=Ld.join(n,t);ai.existsSync(o)&&e.push(o);let s=Cw();if(s[t]){let r=Array.isArray(s[t])?s[t]:[s[t]];e.push(...r)}return e}function Aw(t,e={},n=3e4){try{return{success:!0,exitCode:0,output:GC(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 zC(t,e={}){let n=bl(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=Aw(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 KC(t){return bl(t).length>0}function VC(){let t=[];for(let e of Id){let n=bl(e);n.length>0&&t.push({event:e,commands:n})}return t}function XC(){let t=Rw();return ai.existsSync(t)||ai.mkdirSync(t,{recursive:!0}),t}Ow.exports={HOOK_EVENTS:Id,loadHookConfig:Cw,getHooksForEvent:bl,executeHook:Aw,runHooks:zC,hasHooks:KC,listHooks:VC,initHooksDir:XC}});var e0=ne((IN,Qw)=>{"use strict";var{callWithRetry:Lw,runSubAgent:Mw,clearAllLocks:JC}=td(),{parseModelSpec:Iw,getActiveProviderName:MN,getActiveModelId:NN}=vt(),{detectCategory:ZC,getModelForCategory:Nw}=ro(),{MultiProgress:QC,C:ve}=xt(),{getModelBriefing:LN}=Ga(),jw=parseInt(process.env.NEX_MAX_PARALLEL||"8",10),wl=parseInt(process.env.NEX_MAX_SUBTASKS||"8",10),Dw="devstral-2:123b",qw="kimi-k2.5",Fw=`You are a task decomposition engine. Given a complex user request, split it into independent, atomic sub-tasks.
910
910
 
911
911
  RULES:
912
912
  - Output ONLY a JSON array, no markdown fences, no explanation.
@@ -937,23 +937,23 @@ ORIGINAL REQUEST:
937
937
  {prompt}
938
938
 
939
939
  SUB-AGENT RESULTS:
940
- {results}`;async function Uw(t,e=1,n=2e3){for(let s=0;s<=e;s++)try{return await t()}catch(o){if(s===e)throw o;await new Promise(r=>setTimeout(r,n))}}function Ww(t){let e=0,n=[];return function(){return new Promise(o=>{let r=()=>{e<t?(e++,o(()=>{e--,n.length>0&&n.shift()()})):n.push(r)};r()})}}function eA(t){if(!t||typeof t!="string")return{isComplex:!1,estimatedGoals:0,reason:"empty"};let e=0,n=[],s=t.match(/(?:(?:^|\n)\s*|\s)(?:\d+[.)]\s|[(]\d+[)][\s,]|[(][a-z][)][\s,])/g);s&&s.length>=2&&(e=Math.max(e,s.length),n.push(`${s.length} numbered items`));let o=t.match(/(?:^|\n)\s*[-*]\s+\S/g);o&&o.length>=3&&(e=Math.max(e,o.length),n.push(`${o.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=Hw(t);if(a.isCriticalPath)return{isComplex:!1,estimatedGoals:e,reason:`critical path workflow: ${a.reason}`};let l=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10);return{isComplex:e>=l,estimatedGoals:e,reason:n.length>0?n.join(", "):"single goal"}}function Hw(t){if(!t||typeof t!="string")return{isCriticalPath:!1,reason:""};let e=t.toLowerCase(),n=/\b(at the start|before|after|in order|mandatory|must|only when|do not proceed|don't proceed|then)\b/i.test(e),s=/\b(if|when)\b[\s\S]{0,100}\b(stop|abort|do not|don't|without editing|without committing|without pushing)\b/i.test(e),o=[/\bgit status\b/i,/\bcurrent branch\b/i,/\bworktree\b/i,/\bdirty\b/i,/\bunrelated changes?\b/i,/\bclean working tree\b/i,/\bpull\/rebase\b/i,/\brebase\b/i,/\bcommit\b/i,/\bpush\b/i,/\bmerge-to-main\b/i].filter(i=>i.test(e)).length,r=/\b(verification passes|tests? pass|build passes|stage only|never stage|never push|do not commit|do not push)\b/i.test(e);return(n||s)&&o>=2?{isCriticalPath:!0,reason:"ordered git safety gates"}:s&&r?{isCriticalPath:!0,reason:"explicit stop condition"}:{isCriticalPath:!1,reason:""}}function jd(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 s=e.search(/[[\{]/);if(s>=0){let o=e.slice(s);try{return JSON.parse(o)}catch{}}throw new Error(`Could not extract valid JSON from response:
941
- ${e.slice(0,200)}`)}function tA(){let t=require("fs"),e=require("path"),n=[];try{let s=process.cwd(),o=t.readdirSync(s,{withFileTypes:!0}),r=o.filter(l=>l.isDirectory()).map(l=>l.name),i=o.filter(l=>l.isFile()).map(l=>l.name);n.push(`Project root: ${s}`),n.push(`Top-level dirs: ${r.join(", ")||"(none)"}`),n.push(`Top-level files: ${i.join(", ")||"(none)"}`);let a=e.join(s,"package.json");if(t.existsSync(a)){let l=JSON.parse(t.readFileSync(a,"utf-8")),c=Object.keys(l.scripts||{}).slice(0,6);c.length&&n.push(`Scripts: ${c.join(", ")}`);let u=Object.keys(l.dependencies||{}).slice(0,8);u.length&&n.push(`Dependencies: ${u.join(", ")}`)}i.some(l=>/\.tsx?$/.test(l))?n.push("Language: TypeScript"):i.some(l=>/\.jsx?$/.test(l))&&n.push("Language: JavaScript"),i.some(l=>/\.py$/.test(l))&&n.push("Language: Python"),(r.includes("tests")||r.includes("test"))&&n.push("Test directory: found")}catch{}return n.length>1?`
940
+ {results}`;async function Uw(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 Ww(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 eA(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=Hw(t);if(a.isCriticalPath)return{isComplex:!1,estimatedGoals:e,reason:`critical path workflow: ${a.reason}`};let l=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10);return{isComplex:e>=l,estimatedGoals:e,reason:n.length>0?n.join(", "):"single goal"}}function Hw(t){if(!t||typeof t!="string")return{isCriticalPath:!1,reason:""};let e=t.toLowerCase(),n=/\b(at the start|before|after|in order|mandatory|must|only when|do not proceed|don't proceed|then)\b/i.test(e),o=/\b(if|when)\b[\s\S]{0,100}\b(stop|abort|do not|don't|without editing|without committing|without pushing)\b/i.test(e),s=[/\bgit status\b/i,/\bcurrent branch\b/i,/\bworktree\b/i,/\bdirty\b/i,/\bunrelated changes?\b/i,/\bclean working tree\b/i,/\bpull\/rebase\b/i,/\brebase\b/i,/\bcommit\b/i,/\bpush\b/i,/\bmerge-to-main\b/i].filter(i=>i.test(e)).length,r=/\b(verification passes|tests? pass|build passes|stage only|never stage|never push|do not commit|do not push)\b/i.test(e);return(n||o)&&s>=2?{isCriticalPath:!0,reason:"ordered git safety gates"}:o&&r?{isCriticalPath:!0,reason:"explicit stop condition"}:{isCriticalPath:!1,reason:""}}function jd(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:
941
+ ${e.slice(0,200)}`)}function tA(){let t=require("fs"),e=require("path"),n=[];try{let o=process.cwd(),s=t.readdirSync(o,{withFileTypes:!0}),r=s.filter(l=>l.isDirectory()).map(l=>l.name),i=s.filter(l=>l.isFile()).map(l=>l.name);n.push(`Project root: ${o}`),n.push(`Top-level dirs: ${r.join(", ")||"(none)"}`),n.push(`Top-level files: ${i.join(", ")||"(none)"}`);let a=e.join(o,"package.json");if(t.existsSync(a)){let l=JSON.parse(t.readFileSync(a,"utf-8")),c=Object.keys(l.scripts||{}).slice(0,6);c.length&&n.push(`Scripts: ${c.join(", ")}`);let u=Object.keys(l.dependencies||{}).slice(0,8);u.length&&n.push(`Dependencies: ${u.join(", ")}`)}i.some(l=>/\.tsx?$/.test(l))?n.push("Language: TypeScript"):i.some(l=>/\.jsx?$/.test(l))&&n.push("Language: JavaScript"),i.some(l=>/\.py$/.test(l))&&n.push("Language: Python"),(r.includes("tests")||r.includes("test"))&&n.push("Test directory: found")}catch{}return n.length>1?`
942
942
  ## Project Structure Preview
943
943
  ${n.join(`
944
944
  `)}
945
- `:""}async function Gw(t,e,n={}){let s=n.maxSubTasks||wl,o=tA(),r=o?`${t}
945
+ `:""}async function Gw(t,e,n={}){let o=n.maxSubTasks||wl,s=tA(),r=s?`${t}
946
946
 
947
- ${o}
948
- Use the project structure above to scope sub-tasks to real files and directories. Do not invent paths or files that do not exist.`:t,a=[{role:"system",content:Fw.replace("{maxSubTasks}",String(s)).replace("{prompt}",r)},{role:"user",content:t}],l={};if(e){let k=Iw(e);k.provider&&(l.provider=k.provider),k.model&&(l.model=k.model)}let u=(await Lw(a,[],l)).content||"",d=jd(u);if(!Array.isArray(d))throw new Error(`Decompose returned non-array: ${typeof d}`);let f=10,h=d.slice(0,s).map((k,T)=>({id:k.id||`t${T+1}`,task:String(k.task||""),scope:Array.isArray(k.scope)?k.scope:[],estimatedCalls:typeof k.estimatedCalls=="number"?Math.min(k.estimatedCalls,f):8,priority:typeof k.priority=="number"?k.priority:T+1})).filter(k=>k.task.length>0),g=h.reduce((k,T)=>k+T.estimatedCalls,0),w=wl*f;if(g>w){let{debugLog:k}=Wc();k(`${kn().T.yellow} \u26A0 Orchestrator: total estimated calls ${g} > ${w} \u2014 consider raising maxSubTasks${kn().T.reset}`)}return h}async function Yw(t,e,n){if(!t||t.length===0)return{summary:"No sub-tasks were executed.",conflicts:[],commitMessage:"",resourcesChanged:[]};let s=t.map((f,p)=>{let h=f.status==="done"?"SUCCESS":f.status==="truncated"?"PARTIAL":"FAILED";return`--- Agent ${p+1} [${h}] ---
947
+ ${s}
948
+ Use the project structure above to scope sub-tasks to real files and directories. Do not invent paths or files that do not exist.`:t,a=[{role:"system",content:Fw.replace("{maxSubTasks}",String(o)).replace("{prompt}",r)},{role:"user",content:t}],l={};if(e){let k=Iw(e);k.provider&&(l.provider=k.provider),k.model&&(l.model=k.model)}let u=(await Lw(a,[],l)).content||"",d=jd(u);if(!Array.isArray(d))throw new Error(`Decompose returned non-array: ${typeof d}`);let f=10,h=d.slice(0,o).map((k,T)=>({id:k.id||`t${T+1}`,task:String(k.task||""),scope:Array.isArray(k.scope)?k.scope:[],estimatedCalls:typeof k.estimatedCalls=="number"?Math.min(k.estimatedCalls,f):8,priority:typeof k.priority=="number"?k.priority:T+1})).filter(k=>k.task.length>0),g=h.reduce((k,T)=>k+T.estimatedCalls,0),w=wl*f;if(g>w){let{debugLog:k}=Wc();k(`${kn().T.yellow} \u26A0 Orchestrator: total estimated calls ${g} > ${w} \u2014 consider raising maxSubTasks${kn().T.reset}`)}return h}async function Yw(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}] ---
949
949
  Task: ${f.task}
950
950
  Result: ${f.result}
951
951
  Tools: ${(f.toolsUsed||[]).join(", ")||"none"}`}).join(`
952
952
 
953
- `),r=[{role:"system",content:Bw.replace("{prompt}",e).replace("{results}",s)},{role:"user",content:"Synthesize the sub-agent results above."}],i={};if(n){let f=Iw(n);f.provider&&(i.provider=f.provider),f.model&&(i.model=f.model)}let l=(await Lw(r,[],i)).content||"",c=jd(l),u={summary:String(c.summary||""),conflicts:Array.isArray(c.conflicts)?c.conflicts:[],commitMessage:String(c.commitMessage||""),filesChanged:Array.isArray(c.filesChanged)?c.filesChanged:[]},d=zw(u,t);return d&&(u.commitMessage="",u.commitSuppressedReason=d),u}function zw(t,e){let n=/\b(fail(?:ed|ure|s)?|did not pass|tests? (?:are )?failing|red|broken)\b/i,s=/\b(reported|claimed|said)\b.*\b(pass|fail)/i;for(let o of t.conflicts)if(typeof o=="string"){if(n.test(o))return"conflict mentions failure";if(s.test(o)&&/pass/i.test(o)&&/fail/i.test(o))return"agents disagree on pass/fail"}for(let o of e){if(o.status==="error"||o.status==="failed"||o.status==="skipped")return`agent reported ${o.status}`;let r=String(o.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 nA(t,e={}){let n=e.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL||qw,s=e.workerModel||Dw,o=e.maxParallel||jw,r=e.maxSubTasks||wl,i=e.onProgress||(()=>{}),a={input:0,output:0};console.log(`
954
- ${ve.bold}Orchestrator${ve.reset} ${ve.dim}model: ${n} | workers: ${s} | max parallel: ${o}${ve.reset}
955
- `),i("decomposing"),console.log(`${ve.dim}Phase 1: Decomposing prompt into sub-tasks...${ve.reset}`);let l;try{l=await Gw(t,n,{maxSubTasks:r})}catch(G){return console.log(`${ve.red}Decompose failed: ${G.message}${ve.reset}`),{results:[],synthesis:{summary:`Decompose failed: ${G.message}`,conflicts:[],commitMessage:"",resourcesChanged:[]},totalTokens:a}}if(l.length===0)return console.log(`${ve.yellow}No sub-tasks generated. Prompt may be too simple for orchestration.${ve.reset}`),{results:[],synthesis:{summary:"No sub-tasks generated.",conflicts:[],commitMessage:"",resourcesChanged:[]},totalTokens:a};console.log(`${ve.green}Decomposed into ${l.length} sub-tasks:${ve.reset}`);for(let G of l){console.log(` ${ve.dim}${G.id}:${ve.reset} ${G.task}`);let re=G.scope.filter(Boolean);re.length>0&&console.log(` ${ve.dim}scope: ${re.join(", ")}${ve.reset}`)}console.log("");let c=new Map;for(let G=0;G<l.length;G++)for(let re of l[G].scope)re&&!c.has(re)&&c.set(re,G);i("executing"),console.log(`${ve.dim}Phase 2: Running ${l.length} sub-agents (max ${o} parallel)...${ve.reset}
956
- `);let u=Date.now(),d=Ww(o),f={findings:[],_lock:!1},p=l.map(G=>{let re=ZC(G.task);return(re?Nw(re.id):null)||s}),h=l.map((G,re)=>{let et=`Agent ${re+1} [${p[re]}]: `,Ve=Math.max(20,60-et.length),Ae=G.task.substring(0,Ve)+(G.task.length>Ve?"...":"");return et+Ae}),g=new QC(h);g.start();let w=`
953
+ `),r=[{role:"system",content:Bw.replace("{prompt}",e).replace("{results}",o)},{role:"user",content:"Synthesize the sub-agent results above."}],i={};if(n){let f=Iw(n);f.provider&&(i.provider=f.provider),f.model&&(i.model=f.model)}let l=(await Lw(r,[],i)).content||"",c=jd(l),u={summary:String(c.summary||""),conflicts:Array.isArray(c.conflicts)?c.conflicts:[],commitMessage:String(c.commitMessage||""),filesChanged:Array.isArray(c.filesChanged)?c.filesChanged:[]},d=zw(u,t);return d&&(u.commitMessage="",u.commitSuppressedReason=d),u}function zw(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"||s.status==="skipped")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 nA(t,e={}){let n=e.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL||qw,o=e.workerModel||Dw,s=e.maxParallel||jw,r=e.maxSubTasks||wl,i=e.onProgress||(()=>{}),a={input:0,output:0};console.log(`
954
+ ${ve.bold}Orchestrator${ve.reset} ${ve.dim}model: ${n} | workers: ${o} | max parallel: ${s}${ve.reset}
955
+ `),i("decomposing"),console.log(`${ve.dim}Phase 1: Decomposing prompt into sub-tasks...${ve.reset}`);let l;try{l=await Gw(t,n,{maxSubTasks:r})}catch(G){return console.log(`${ve.red}Decompose failed: ${G.message}${ve.reset}`),{results:[],synthesis:{summary:`Decompose failed: ${G.message}`,conflicts:[],commitMessage:"",resourcesChanged:[]},totalTokens:a}}if(l.length===0)return console.log(`${ve.yellow}No sub-tasks generated. Prompt may be too simple for orchestration.${ve.reset}`),{results:[],synthesis:{summary:"No sub-tasks generated.",conflicts:[],commitMessage:"",resourcesChanged:[]},totalTokens:a};console.log(`${ve.green}Decomposed into ${l.length} sub-tasks:${ve.reset}`);for(let G of l){console.log(` ${ve.dim}${G.id}:${ve.reset} ${G.task}`);let re=G.scope.filter(Boolean);re.length>0&&console.log(` ${ve.dim}scope: ${re.join(", ")}${ve.reset}`)}console.log("");let c=new Map;for(let G=0;G<l.length;G++)for(let re of l[G].scope)re&&!c.has(re)&&c.set(re,G);i("executing"),console.log(`${ve.dim}Phase 2: Running ${l.length} sub-agents (max ${s} parallel)...${ve.reset}
956
+ `);let u=Date.now(),d=Ww(s),f={findings:[],_lock:!1},p=l.map(G=>{let re=ZC(G.task);return(re?Nw(re.id):null)||o}),h=l.map((G,re)=>{let et=`Agent ${re+1} [${p[re]}]: `,Ve=Math.max(20,60-et.length),Ae=G.task.substring(0,Ve)+(G.task.length>Ve?"...":"");return et+Ae}),g=new QC(h);g.start();let w=`
957
957
  You are a focused coding agent executing ONE specific sub-task.
958
958
  Your scope is limited to the files listed in your task definition.
959
959
 
@@ -977,10 +977,10 @@ RULES:
977
977
  - Start with symbol-aware reads inside your scope: locate the target function/class/module, then read the exact section instead of scanning broadly.
978
978
  - Before finishing, run the smallest relevant verification for your scope and report any residual risk explicitly.
979
979
  - If your sub-task is review/audit/verify/preflight-oriented, do not edit files. Output findings or the blocker first with severity, file/resource, and impact. If nothing is wrong, say so explicitly and mention remaining risk.
980
- `,k=new Map;for(let G=0;G<l.length;G++){let re=l[G].priority||1;k.has(re)||k.set(re,[]),k.get(re).push({st:l[G],idx:G})}let T=[...k.keys()].sort((G,re)=>G-re),$=new Array(l.length),R=null;for(let G of T){let et=k.get(G).map(async({st:Oe,idx:E})=>{let _=await d();try{let H=await C(Oe,E,{acquire:d,subTaskModels:p,labels:h,progress:g,sharedContext:f,_fileOwnership:c,workerModel:s,WORKER_SYSTEM_PROMPT:w});return $[E]=H,H}finally{_()}}),Ae=(await Promise.all(et)).find(Oe=>Xw(l[Oe?._idx],Oe,G,T));if(Ae){R={task:l[Ae._idx]?.task||Ae.task||"unknown task",result:Ae.result||""};break}}if(R)for(let G=0;G<$.length;G++)$[G]||($[G]={task:l[G].task,status:"skipped",result:`Skipped because prerequisite failed: ${R.task}`,toolsUsed:[],tokensUsed:{input:0,output:0},_scope:l[G].scope,_idx:G});async function C(G,re,et){try{let Ve=f.findings.filter($e=>$e.agentId!==G.id).map($e=>`Agent ${$e.agentId} found: ${$e.summary}`).join(`
980
+ `,k=new Map;for(let G=0;G<l.length;G++){let re=l[G].priority||1;k.has(re)||k.set(re,[]),k.get(re).push({st:l[G],idx:G})}let T=[...k.keys()].sort((G,re)=>G-re),$=new Array(l.length),R=null;for(let G of T){let et=k.get(G).map(async({st:Oe,idx:E})=>{let _=await d();try{let H=await C(Oe,E,{acquire:d,subTaskModels:p,labels:h,progress:g,sharedContext:f,_fileOwnership:c,workerModel:o,WORKER_SYSTEM_PROMPT:w});return $[E]=H,H}finally{_()}}),Ae=(await Promise.all(et)).find(Oe=>Xw(l[Oe?._idx],Oe,G,T));if(Ae){R={task:l[Ae._idx]?.task||Ae.task||"unknown task",result:Ae.result||""};break}}if(R)for(let G=0;G<$.length;G++)$[G]||($[G]={task:l[G].task,status:"skipped",result:`Skipped because prerequisite failed: ${R.task}`,toolsUsed:[],tokensUsed:{input:0,output:0},_scope:l[G].scope,_idx:G});async function C(G,re,et){try{let Ve=f.findings.filter($e=>$e.agentId!==G.id).map($e=>`Agent ${$e.agentId} found: ${$e.summary}`).join(`
981
981
  `),Ae=[...c.entries()].filter(([,$e])=>$e===re).map(([$e])=>$e),Oe=[...c.entries()].filter(([,$e])=>$e!==re).map(([$e])=>$e),E=Zw(G.task),_=[`Worker mode: ${E}`,Ve?`Prior agent findings:
982
982
  ${Ve}
983
- `:"",G.scope.length>0?`Focus on files: ${G.scope.join(", ")}`:"",Ae.length>0?`You OWN these files (may read+write): ${Ae.join(", ")}`:"",Oe.length>0?`READ ONLY (owned by other agents, do NOT write): ${Oe.join(", ")}`:""].filter(Boolean),H=p[re],se=process.env.NEX_FALLBACK_MODEL||Nw("agentic")||s,ee=0,P=await Uw(async()=>{let $e=ee>0;$e&&(g.update(re,"retry"),process.stderr.write(` ${ve.dim}[Agent ${re+1}] retrying after error...${ve.reset}
983
+ `:"",G.scope.length>0?`Focus on files: ${G.scope.join(", ")}`:"",Ae.length>0?`You OWN these files (may read+write): ${Ae.join(", ")}`:"",Oe.length>0?`READ ONLY (owned by other agents, do NOT write): ${Oe.join(", ")}`:""].filter(Boolean),H=p[re],se=process.env.NEX_FALLBACK_MODEL||Nw("agentic")||o,ee=0,P=await Uw(async()=>{let $e=ee>0;$e&&(g.update(re,"retry"),process.stderr.write(` ${ve.dim}[Agent ${re+1}] retrying after error...${ve.reset}
984
984
  `)),ee++;let tt=$e&&H!==se?se:H;return Mw({task:G.task,type:E,context:_.length>0?_.join(`
985
985
  `):void 0,max_iterations:Math.min(G.estimatedCalls||10,15),model:tt,_skipLog:!0,_systemPrompt:w,_readOnlyFiles:Oe},{onUpdate:rn=>{if(rn&&rn.type==="tool_call"&&process.stderr.isTTY){let $n=`Agent ${re+1} [${tt}]`,Nf=rn.tool||"...";g.labels[re]=`${$n}: ${Nf}`}}})},1,2e3),he="";if(Vw(E,P,G,Ae)){let $e=[...new Set([...Ae,...Array.isArray(P.filesModified)?P.filesModified:[],...Array.isArray(G.scope)?G.scope:[]])].filter(Boolean);try{g.labels[re]=`Agent ${re+1} [${H}] review`,g.update(re,"retry");let tt=await Mw({task:`Review the completed changes for: ${G.task}`,type:"review",context:iA(G,P,$e),max_iterations:4,model:H,_skipLog:!0,_systemPrompt:w},{onUpdate:()=>{}},1);Kw(tt.result)?(he=`
986
986
 
@@ -992,70 +992,70 @@ Reviewer: ${tt.result}`)}catch(tt){he=`
992
992
  Reviewer note: review pass failed (${tt.message})`}}let Xe=typeof P.result=="string"?`${P.result}${he}`.slice(0,200):`${String(P.result||"")}${he}`.slice(0,200);return f.findings.push({agentId:G.id,summary:Xe,files:Array.isArray(G.scope)?G.scope:[]}),g.labels[re]=h[re],g.update(re,P.status==="failed"?"error":"done"),a.input+=P.tokensUsed?.input||0,a.output+=P.tokensUsed?.output||0,P.tokensUsed?._estimated&&(a._estimated=!0),{...P,result:`${String(P.result||"")}${he}`,_scope:G.scope,_idx:re}}catch(Ve){return g.labels[re]=h[re],g.update(re,"error"),{task:G.task,status:"failed",result:`Error: ${Ve.message}`,toolsUsed:[],tokensUsed:{input:0,output:0},_scope:G.scope,_idx:re}}}let M;try{M=$}finally{g.stop({silent:!0}),JC()}console.log("");let K=Math.round((Date.now()-u)/1e3),z=K>=60?`${Math.floor(K/60)}m ${K%60}s`:`${K}s`;for(let G=0;G<M.length;G++){let re=M[G],Ve=re.status==="done"||re.status==="truncated"&&re.result&&!re.result.startsWith("Error")?`${ve.green}\u2713${ve.reset}`:`${ve.red}\u2717${ve.reset}`,Ae=re._scope&&re._scope.length>0?re._scope.map(_=>_.replace(/^.*\//,"").replace(/\/$/,"")).filter(Boolean):[],Oe=Ae.length>0?Ae.join(", "):re.task.substring(0,35)+(re.task.length>35?"...":""),E=G===M.length-1;console.log(` ${Ve} Agent ${G+1} ${ve.dim}${Oe}${ve.reset}${E?` ${ve.dim}${z}${ve.reset}`:""}`)}console.log(""),i("synthesizing"),console.log(`${ve.dim}Phase 3: Synthesizing results...${ve.reset}`);let X;if(R)X={summary:`Stopped before continuing because prerequisite sub-task failed: ${R.task}. ${R.result}`,conflicts:[],commitMessage:"",commitSuppressedReason:"prerequisite sub-task failed",filesChanged:[],resourcesChanged:[]};else try{X=await Yw(M,t,n)}catch(G){console.log(`${ve.yellow}Synthesize failed: ${G.message} \u2014 using raw results.${ve.reset}`),X={summary:M.map(re=>re.result).join(`
993
993
  `),conflicts:[],commitMessage:"",resourcesChanged:[]}}let ae=f.findings.flatMap(G=>G.files),Z=new Map;for(let G of ae)Z.set(G,(Z.get(G)||0)+1);let oe=[...Z.values()].some(G=>G>1),Ke=f.findings.length>1&&oe?` ${ve.dim}(agents shared context)${ve.reset}`:"";if(console.log(`
994
994
  ${ve.bold}Summary:${ve.reset} ${X.summary}${Ke}`),X.conflicts.length>0){console.log(`${ve.yellow}Conflicts:${ve.reset}`);for(let G of X.conflicts)console.log(` - ${G}`)}X.commitMessage?console.log(`${ve.dim}Suggested commit: ${X.commitMessage}${ve.reset}`):X.commitSuppressedReason&&console.log(`${ve.yellow}No commit suggested:${ve.reset} ${X.commitSuppressedReason}`);let Ee=a.input===0&&a.output===0?"n/a (provider does not report token counts)":a._estimated?`~${a.input} input / ~${a.output} output (est.)`:`${a.input} input + ${a.output} output`;return console.log(`${ve.dim}Tokens: ${Ee}${ve.reset}
995
- `),{results:M,synthesis:X,totalTokens:a}}var sA=/\b(research|analyze|investigate|check|verify|review|audit|read|find|search|discover|look|examine|inspect|scan|list)\b/i,oA=/\b(review|audit|verify|validate|inspect|critique)\b/i,rA=/\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 iA(t,e,n){let s=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}`,s,`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(`
996
- `)}function Kw(t){return!t||typeof t!="string"?!1:!/no material findings/i.test(t)}function Vw(t,e,n,s){if(t!=="implement"||!e||e.status==="failed")return!1;let o=Array.isArray(n?.scope)?n.scope.length:0,r=Array.isArray(e.filesModified)?e.filesModified.length:0,i=Array.isArray(s)?s.length:0;return o+r+i>0}function Xw(t,e,n,s){return aA(e)?Jw(t)?!0:s.some(r=>r>n)&&n===s[0]:!1}function aA(t){return t&&(t.status==="failed"||t.status==="error"||t.status==="skipped")}function Jw(t){let e=typeof t=="string"?t:`${t?.task||""} ${(t?.scope||[]).join(" ")}`;return/\b(preflight|git status|current branch|worktree|dirty|unrelated changes?|clean working tree|pull\/rebase|rebase|before changing|before editing|stop without|abort|blocker|verification gate|release gate)\b/i.test(e)}function Zw(t){if(!t)return"implement";let e=sA.test(t),n=oA.test(t);return rA.test(t)?"implement":n?"review":e?"explore":"implement"}Qw.exports={runOrchestrated:nA,decompose:Gw,synthesize:Yw,shouldSuppressCommit:zw,detectComplexPrompt:eA,detectCriticalPathPrompt:Hw,extractJSON:jd,createSemaphore:Ww,DECOMPOSE_PROMPT:Fw,SYNTHESIZE_PROMPT:Bw,DEFAULT_ORCHESTRATOR_MODEL:qw,DEFAULT_WORKER_MODEL:Dw,DEFAULT_MAX_PARALLEL:jw,DEFAULT_MAX_SUBTASKS:wl,withRetry:Uw,_classifyWorkerType:Zw,_hasMaterialReviewFindings:Kw,_shouldRunFollowUpReview:Vw,_shouldAbortAfterWave:Xw,_isBlockingTask:Jw}});var kd=ne((UN,G0)=>{var{C:m,Spinner:ir,TaskProgress:lA,formatToolCall:cA,formatToolSummary:vi,formatSectionHeader:li,formatMilestone:uA,setActiveTaskProgress:jN,getThinkingVerb:Dd,setActiveModelForSpinner:t0}=xt(),{debugLog:N,warnLog:DN}=Wc(),{MilestoneTracker:dA}=wh(),{callStream:_l}=vt(),{parseToolArgs:fA}=kr(),{executeTool:yf}=Do(),{gatherProjectContext:pA}=Xb(),{fitToContext:hA,forceCompress:Bn,getUsage:Tn,estimateTokens:mA,buildProgressSnapshot:gA}=Fn(),{autoSave:yA,flushAutoSave:bA}=dl(),{scoreMessages:wA,formatScore:_A,appendScoreHistory:$A}=fl(),{detectCategory:kA,getModelForPhase:Jd,getPhaseBudget:ks,isPhaseRoutingEnabled:xA}=ro();function we(t){yA(t),bA()}function $l(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 Zd(t){if(!t||typeof t!="string")return!1;let e=t.slice(-1200);return/\b(done|complete|completed|fixed|implemented|ready|verified|verification complete|tests? pass(?:ed)?|build pass(?:ed)?|all checks pass(?:ed)?|all good)\b/i.test(e)}function Qd(t){return!t||typeof t!="string"?!1:/\b(not verified|verification (?:was )?not run|tests? (?:were )?not run|build (?:was )?not run|unchecked|unverified)\b/i.test(t)}function vA(t){return!t||typeof t!="string"?!1:/^\s*(?:final\s+)?(?:summary|report|answer|result)\s*:/i.test(t)}function SA(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 EA(t){return!t||typeof t!="string"?!1:/\.(?:md|mdx|txt|rst|adoc)$/i.test(t)}function Qe(t){try{if(!t.some(s=>s.role!=="assistant"?!1:!!(Array.isArray(s.content)&&s.content.some(o=>o&&o.type==="tool_use")||Array.isArray(s.tool_calls)&&s.tool_calls.length>0)))return;let n=wA(t);if(!n)return;console.log(_A(n,m));try{let{_getSessionsDir:s}=dl(),o=require("fs"),r=require("path").join(s(),"_autosave.json");if(o.existsSync(r)){let i=JSON.parse(o.readFileSync(r,"utf-8"));i.score=n.score,i.scoreGrade=n.grade,i.scoreIssues=n.issues,o.writeFileSync(r,JSON.stringify(i,null,2))}}catch{}try{let{getActiveModel:s}=kr(),o=Yi();$A(n.score,{version:o.version,model:s?s():null,sessionName:"_autosave",issues:n.issues})}catch{}}catch{}}var{getMemoryContext:TA}=Gr(),{getDeploymentContextBlock:RA,probeUrlServer:CA,detectRuntimeDebugTarget:n0}=vd(),{getFewShotForInput:AA}=gw(),{checkPermission:OA,setPermission:PA,savePermissions:MA}=kw(),{confirm:k0,setAllowAlwaysHandler:NA,getAutoConfirm:_n}=vr(),{isPlanMode:go,getPlanModePrompt:LA,PLAN_MODE_ALLOWED_TOOLS:x0,setPlanContent:IA,extractStepsFromText:jA,createPlan:DA,getActivePlan:qN,startExecution:FN,advancePlanStep:qA,getPlanStepInfo:FA}=yl(),{StreamRenderer:BA}=vc(),{runHooks:s0}=Pw(),{routeMCPCall:UA,getMCPToolDefinitions:WA}=au(),{getSkillInstructions:HA,getSkillToolDefinitions:GA,routeSkillCall:YA,matchSkillTriggers:zA}=ru(),{trackUsage:o0,estimateTokens:r0,getSessionCosts:i0,getProviderCostMode:a0}=ma();function l0(t){return!t||typeof t!="string"?0:typeof r0=="function"?r0(t):Math.ceil(t.length/4)}var{validateToolArgs:KA}=uu(),{filterToolsForModel:c0,getModelTier:VA,PROVIDER_DEFAULT_TIER:BN}=Nr(),{getConfiguredProviders:XA,getActiveProviderName:Yn,getActiveModelId:Cn,setActiveModel:qd,MODEL_EQUIVALENTS:Hl}=vt(),{getModelProfile:JA,getModelBriefing:ZA}=Ga(),Ue=require("fs"),Ye=require("path"),QA=(()=>{let t=parseInt(process.env.NEX_MILESTONE_STEPS??"5",10);return Number.isFinite(t)&&t>=0?t:5})();function eO(t){let e=uA(t.phaseName,t.stepCount,t.toolCounts,t.elapsed,t.filesRead,t.filesModified);process.stdout.write(`${e}
997
- `),global._nexFooter&&global._nexFooter.setFileInfo({modified:t.filesModified?.size||0,scanned:t.filesRead?.size||0})}var u0=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi,d0=/(?:^|\s)(https?:\/\/[^\s]+\.(?:png|jpe?g|gif|webp)(?:\?[^\s]*)?)(?:\s|$)/gi,tO=/\b(?:clipboard|pasteboard|clipboard screenshot)\b/i;function nO(t){let e=[],n;for(u0.lastIndex=0;(n=u0.exec(t))!==null;){let s=n[1].trim(),o=s.startsWith("~")?s.replace("~",process.env.HOME||""):Ye.resolve(s);Ue.existsSync(o)&&e.push({raw:s,abs:o})}return e}function v0(t){let e=[],n;for(d0.lastIndex=0;(n=d0.exec(t))!==null;)e.push(n[1].trim());return e}async function S0(t){try{let n=await require("axios").get(t,{responseType:"arraybuffer",timeout:1e4,maxContentLength:10*1024*1024,headers:{"User-Agent":"nex-code/vision"}}),s=n.headers["content-type"]||"",o=s.startsWith("image/")?s.split(";")[0]:sO(t);return{data:Buffer.from(n.data).toString("base64"),media_type:o}}catch{return null}}function sO(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 E0(){if(process.platform!=="darwin")return null;let{spawnSync:t}=require("child_process"),e=Ye.join(require("os").tmpdir(),`nex-clipboard-${Date.now()}.png`);if(t("pngpaste",[e],{timeout:3e3}).status===0&&Ue.existsSync(e)){let o=Ue.readFileSync(e);if(o.length>100)return{data:o.toString("base64"),media_type:"image/png",path:e};try{Ue.unlinkSync(e)}catch(r){console.error("Failed to unlink temp file:",r)}}let s=t("osascript",["-e",`try
995
+ `),{results:M,synthesis:X,totalTokens:a}}var sA=/\b(research|analyze|investigate|check|verify|review|audit|read|find|search|discover|look|examine|inspect|scan|list)\b/i,oA=/\b(review|audit|verify|validate|inspect|critique)\b/i,rA=/\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 iA(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(`
996
+ `)}function Kw(t){return!t||typeof t!="string"?!1:!/no material findings/i.test(t)}function Vw(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 Xw(t,e,n,o){return aA(e)?Jw(t)?!0:o.some(r=>r>n)&&n===o[0]:!1}function aA(t){return t&&(t.status==="failed"||t.status==="error"||t.status==="skipped")}function Jw(t){let e=typeof t=="string"?t:`${t?.task||""} ${(t?.scope||[]).join(" ")}`;return/\b(preflight|git status|current branch|worktree|dirty|unrelated changes?|clean working tree|pull\/rebase|rebase|before changing|before editing|stop without|abort|blocker|verification gate|release gate)\b/i.test(e)}function Zw(t){if(!t)return"implement";let e=sA.test(t),n=oA.test(t);return rA.test(t)?"implement":n?"review":e?"explore":"implement"}Qw.exports={runOrchestrated:nA,decompose:Gw,synthesize:Yw,shouldSuppressCommit:zw,detectComplexPrompt:eA,detectCriticalPathPrompt:Hw,extractJSON:jd,createSemaphore:Ww,DECOMPOSE_PROMPT:Fw,SYNTHESIZE_PROMPT:Bw,DEFAULT_ORCHESTRATOR_MODEL:qw,DEFAULT_WORKER_MODEL:Dw,DEFAULT_MAX_PARALLEL:jw,DEFAULT_MAX_SUBTASKS:wl,withRetry:Uw,_classifyWorkerType:Zw,_hasMaterialReviewFindings:Kw,_shouldRunFollowUpReview:Vw,_shouldAbortAfterWave:Xw,_isBlockingTask:Jw}});var kd=ne((UN,G0)=>{var{C:m,Spinner:ir,TaskProgress:lA,formatToolCall:cA,formatToolSummary:vi,formatSectionHeader:li,formatMilestone:uA,setActiveTaskProgress:jN,getThinkingVerb:Dd,setActiveModelForSpinner:t0}=xt(),{debugLog:N,warnLog:DN}=Wc(),{MilestoneTracker:dA}=wh(),{callStream:_l}=vt(),{parseToolArgs:fA}=kr(),{executeTool:yf}=Do(),{gatherProjectContext:pA}=Xb(),{fitToContext:hA,forceCompress:Bn,getUsage:Tn,estimateTokens:mA,buildProgressSnapshot:gA}=Fn(),{autoSave:yA,flushAutoSave:bA}=dl(),{scoreMessages:wA,formatScore:_A,appendScoreHistory:$A}=fl(),{detectCategory:kA,getModelForPhase:Jd,getPhaseBudget:ks,isPhaseRoutingEnabled:xA}=ro();function we(t){yA(t),bA()}function $l(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 Zd(t){if(!t||typeof t!="string")return!1;let e=t.slice(-1200);return/\b(done|complete|completed|fixed|implemented|ready|verified|verification complete|tests? pass(?:ed)?|build pass(?:ed)?|all checks pass(?:ed)?|all good)\b/i.test(e)}function Qd(t){return!t||typeof t!="string"?!1:/\b(not verified|verification (?:was )?not run|tests? (?:were )?not run|build (?:was )?not run|unchecked|unverified)\b/i.test(t)}function vA(t){return!t||typeof t!="string"?!1:/^\s*(?:final\s+)?(?:summary|report|answer|result)\s*:/i.test(t)}function SA(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 EA(t){return!t||typeof t!="string"?!1:/\.(?:md|mdx|txt|rst|adoc)$/i.test(t)}function Qe(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=wA(t);if(!n)return;console.log(_A(n,m));try{let{_getSessionsDir:o}=dl(),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}=kr(),s=Yi();$A(n.score,{version:s.version,model:o?o():null,sessionName:"_autosave",issues:n.issues})}catch{}}catch{}}var{getMemoryContext:TA}=Gr(),{getDeploymentContextBlock:RA,probeUrlServer:CA,detectRuntimeDebugTarget:n0}=vd(),{getFewShotForInput:AA}=gw(),{checkPermission:OA,setPermission:PA,savePermissions:MA}=kw(),{confirm:k0,setAllowAlwaysHandler:NA,getAutoConfirm:_n}=vr(),{isPlanMode:go,getPlanModePrompt:LA,PLAN_MODE_ALLOWED_TOOLS:x0,setPlanContent:IA,extractStepsFromText:jA,createPlan:DA,getActivePlan:qN,startExecution:FN,advancePlanStep:qA,getPlanStepInfo:FA}=yl(),{StreamRenderer:BA}=vc(),{runHooks:s0}=Pw(),{routeMCPCall:UA,getMCPToolDefinitions:WA}=au(),{getSkillInstructions:HA,getSkillToolDefinitions:GA,routeSkillCall:YA,matchSkillTriggers:zA}=ru(),{trackUsage:o0,estimateTokens:r0,getSessionCosts:i0,getProviderCostMode:a0}=ma();function l0(t){return!t||typeof t!="string"?0:typeof r0=="function"?r0(t):Math.ceil(t.length/4)}var{validateToolArgs:KA}=uu(),{filterToolsForModel:c0,getModelTier:VA,PROVIDER_DEFAULT_TIER:BN}=Nr(),{getConfiguredProviders:XA,getActiveProviderName:Yn,getActiveModelId:Cn,setActiveModel:qd,MODEL_EQUIVALENTS:Hl}=vt(),{getModelProfile:JA,getModelBriefing:ZA}=Ga(),Ue=require("fs"),Ye=require("path"),QA=(()=>{let t=parseInt(process.env.NEX_MILESTONE_STEPS??"5",10);return Number.isFinite(t)&&t>=0?t:5})();function eO(t){let e=uA(t.phaseName,t.stepCount,t.toolCounts,t.elapsed,t.filesRead,t.filesModified);process.stdout.write(`${e}
997
+ `),global._nexFooter&&global._nexFooter.setFileInfo({modified:t.filesModified?.size||0,scanned:t.filesRead?.size||0})}var u0=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi,d0=/(?:^|\s)(https?:\/\/[^\s]+\.(?:png|jpe?g|gif|webp)(?:\?[^\s]*)?)(?:\s|$)/gi,tO=/\b(?:clipboard|pasteboard|clipboard screenshot)\b/i;function nO(t){let e=[],n;for(u0.lastIndex=0;(n=u0.exec(t))!==null;){let o=n[1].trim(),s=o.startsWith("~")?o.replace("~",process.env.HOME||""):Ye.resolve(o);Ue.existsSync(s)&&e.push({raw:o,abs:s})}return e}function v0(t){let e=[],n;for(d0.lastIndex=0;(n=d0.exec(t))!==null;)e.push(n[1].trim());return e}async function S0(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]:sO(t);return{data:Buffer.from(n.data).toString("base64"),media_type:s}}catch{return null}}function sO(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 E0(){if(process.platform!=="darwin")return null;let{spawnSync:t}=require("child_process"),e=Ye.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
998
998
  set imgData to the clipboard as \xABclass PNGf\xBB
999
999
  return "has_image"
1000
1000
  on error
1001
1001
  return "no_image"
1002
- end try`],{timeout:3e3});if(s.stdout&&s.stdout.toString().trim()==="has_image"){let o=`
1002
+ end try`],{timeout:3e3});if(o.stdout&&o.stdout.toString().trim()==="has_image"){let s=`
1003
1003
  set imgData to the clipboard as \xABclass PNGf\xBB
1004
1004
  set filePath to POSIX file "${e}"
1005
1005
  set fRef to open for access filePath with write permission
1006
1006
  write imgData to fRef
1007
1007
  close access fRef
1008
- `;if(t("osascript",["-e",o],{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 f0(t){let e=Ue.readFileSync(t),n=Ye.extname(t).toLowerCase().replace(".",""),s=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:s}}function T0(t){let e=nO(t),n=v0(t),s=tO.test(t),o=n.length>0||s;if(e.length===0&&!o)return t;if(!o){let r=[{type:"text",text:t}];for(let i of e)try{let{data:a,media_type:l}=f0(i.abs);r.push({type:"image",media_type:l,data:a})}catch{}return r.length>1?r:t}return(async()=>{let r=[{type:"text",text:t}];for(let i of e)try{let{data:a,media_type:l}=f0(i.abs);r.push({type:"image",media_type:l,data:a})}catch(a){N(`${m.yellow} \u26A0 Path resolution failed: ${a.message}${m.reset}`)}if(n.length>0){let i=await Promise.all(n.map(S0));for(let a of i)a&&r.push({type:"image",media_type:a.media_type,data:a.data})}if(s){let i=E0();i?(r.push({type:"image",media_type:i.media_type,data:i.data}),r[0].text+=`
1008
+ `;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 f0(t){let e=Ue.readFileSync(t),n=Ye.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 T0(t){let e=nO(t),n=v0(t),o=tO.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:l}=f0(i.abs);r.push({type:"image",media_type:l,data:a})}catch{}return r.length>1?r:t}return(async()=>{let r=[{type:"text",text:t}];for(let i of e)try{let{data:a,media_type:l}=f0(i.abs);r.push({type:"image",media_type:l,data:a})}catch(a){N(`${m.yellow} \u26A0 Path resolution failed: ${a.message}${m.reset}`)}if(n.length>0){let i=await Promise.all(n.map(S0));for(let a of i)a&&r.push({type:"image",media_type:a.media_type,data:a.data})}if(o){let i=E0();i?(r.push({type:"image",media_type:i.media_type,data:i.data}),r[0].text+=`
1009
1009
  [Clipboard image attached: ${i.path}]`):r[0].text+=`
1010
- [No image found in clipboard]`}return r.length>1?r:t})()}var oO=[/\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 R0(t){return typeof t!="string"||!t?!1:oO.some(e=>e.test(t))}function rO(t){if(!t||t.length<200)return{text:t,truncated:!1,repeatCount:0};let n=t.split(/(?<=\. )/).filter(l=>l.trim().length>0);if(n.length<6)return{text:t,truncated:!1,repeatCount:0};let s=new Map;for(let l=0;l<=n.length-3;l++){let c=n.slice(l,l+3).join("").trim();c.length>30&&s.set(c,(s.get(c)||0)+1)}let o=0,r="";for(let[l,c]of s)c>o&&(o=c,r=l);if(o<3)return{text:t,truncated:!1,repeatCount:o};let i=`
1010
+ [No image found in clipboard]`}return r.length>1?r:t})()}var oO=[/\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 R0(t){return typeof t!="string"||!t?!1:oO.some(e=>e.test(t))}function rO(t){if(!t||t.length<200)return{text:t,truncated:!1,repeatCount:0};let n=t.split(/(?<=\. )/).filter(l=>l.trim().length>0);if(n.length<6)return{text:t,truncated:!1,repeatCount:0};let o=new Map;for(let l=0;l<=n.length-3;l++){let c=n.slice(l,l+3).join("").trim();c.length>30&&o.set(c,(o.get(c)||0)+1)}let s=0,r="";for(let[l,c]of o)c>s&&(s=c,r=l);if(s<3)return{text:t,truncated:!1,repeatCount:s};let i=`
1011
1011
 
1012
- [SYSTEM: Output repetition detected \u2014 response truncated (${o}\xD7 repeated paragraph)]`,a;if(t.length>8e3)a=t.slice(0,3e3)+i;else{let l=0,c=-1,u=0;for(;l<2;){let d=t.indexOf(r,u);if(d===-1)break;l++,c=d+r.length,u=d+1}a=c>0?t.slice(0,c)+i:t.slice(0,3e3)+i}return{text:a,truncated:!0,repeatCount:o}}function ef(t,e=5){if(!t||t.length<40)return{text:t,truncated:!1,repeatCount:0};let n=t.split(`
1013
- `),s=new Map;for(let p of n){let h=p.trim();h.length>=20&&s.set(h,(s.get(h)||0)+1)}let o=0,r="";for(let[p,h]of s)h>o&&(o=h,r=p);let a=r.toLowerCase().includes("read_file")||r.toLowerCase().includes("reading")?2:e;if(o<=a)return{text:t,truncated:!1,repeatCount:o};let l=`
1012
+ [SYSTEM: Output repetition detected \u2014 response truncated (${s}\xD7 repeated paragraph)]`,a;if(t.length>8e3)a=t.slice(0,3e3)+i;else{let l=0,c=-1,u=0;for(;l<2;){let d=t.indexOf(r,u);if(d===-1)break;l++,c=d+r.length,u=d+1}a=c>0?t.slice(0,c)+i:t.slice(0,3e3)+i}return{text:a,truncated:!0,repeatCount:s}}function ef(t,e=5){if(!t||t.length<40)return{text:t,truncated:!1,repeatCount:0};let n=t.split(`
1013
+ `),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 l=`
1014
1014
 
1015
- \u26A0 [Response truncated: repeated paragraph detected (${o}\xD7)]`,c=0,u=-1,d=0;for(;c<e;){let p=t.indexOf(r,d);if(p===-1)break;c++,u=p+r.length,d=p+1}return{text:u>0?t.slice(0,u)+l:t.slice(0,2e3)+l,truncated:!0,repeatCount:o}}var Fd=null,Bd=null,Ud=null;function Kt(){if(Fd===null){let{TOOL_DEFINITIONS:t}=Do();Fd=t}return Bd===null&&(Bd=GA()),Ud===null&&(Ud=WA()),[...Fd,...Bd,...Ud]}var Rl=50;function iO(t){Number.isFinite(t)&&t>0&&(Rl=t)}function Wd(t=Yn()){if(process.env.NEX_DISABLE_TOOL_BUDGET==="1")return 1/0;let e=process.env.NEX_MAX_TOOL_CALLS;if(e){let n=parseInt(e,10);if(Number.isFinite(n)&&n>0)return n}return t==="local"?5:30}function p0(t,e){return`[SYSTEM STOP] Tool-call budget reached (${t}/${e}). You MUST stop calling tools now. Provide your final answer based only on the information already in the conversation. If the task cannot be completed from the gathered evidence, state the blocker plainly and do not invent facts.`}var Cl=()=>null;function aO(t){Cl=t}var di=null,tf=null,ar=null,lr="",cr=0,nf="",sf=0,Al=new Map,lO=1e4,cO=6e3,uO=/\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 dO(t){return!t||typeof t!="string"?t:t.replace(uO,(e,n)=>`${n}=***REDACTED***`)}var fO=7e3,pO=4e3;function hO(t,e=null){let n=dO(t),s=mA(n),o=e==="read_file"?fO:lO,r=e==="read_file"?pO:cO;if(s>o)try{let{compressToolResult:i}=Fn();return i(n,r)}catch{return n}return n}function C0(t){try{let{getActiveModel:e}=vt(),n=e(),s=n?`${n.provider}:${n.id}`:"default";if(Al.has(s))return Al.get(s);let o=c0(t);return Al.set(s,o),o}catch{return c0(t)}}function mO(){Al.clear()}function gO(t,e){let n=new Set(e);return(t||[]).some(s=>s.role!=="assistant"?!1:Array.isArray(s.tool_calls)?s.tool_calls.some(o=>n.has(o?.function?.name||o?.name)):Array.isArray(s.content)?s.content.some(o=>o?.type==="tool_use"&&n.has(o?.name)):!1)}var fi={hash:null,ts:0},yO=3e4;async function A0(){if(fi.hash&&Date.now()-fi.ts<yO)return fi.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")],o=(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}=Gr(),a=i();a&&o.push(`memory:${a}`)}catch{}try{let i=e.join(process.cwd(),".nex","brain");if(Ue.existsSync(i)){let a=await t.stat(i);o.push(`brain:${a.mtimeMs}`)}}catch{}let r=o.join("|");return fi={hash:r,ts:Date.now()},r}catch{return`fallback:${Date.now()}`}}function Ol(){di=null,tf=null,fi={hash:null,ts:0},ar=null}var bO=new Set(["spawn_agents"]),Hd=10,Gd=10,kl=5,h0=6e4,Yd=12e4,wO=process.env.NEX_STALE_AUTO_SWITCH!=="0";function _O(t){try{let e=require("fs"),n=require("path"),s=n.join(process.cwd(),".nex","plans");e.existsSync(s)||e.mkdirSync(s,{recursive:!0});let o=n.join(s,"current-plan.md");e.writeFileSync(o,t,"utf-8")}catch{}}NA(t=>{PA(t,"allow"),MA(),console.log(`${m.green} \u2713 ${t}: always allow${m.reset}`)});async function $O(t){let e=t.function.name,n=e;if(typeof e=="string"&&e.includes(".")){let d=e.split(".").pop(),f={exec:"bash",find:"search_files",search:"search_files",grep_search:"grep",list:"list_directory",print_tree:"list_directory",read:"read_file",tree:"list_directory"};Kt().some(h=>h.function.name===d)?n=d:f[d]&&(n=f[d])}let s=fA(t.function.arguments),o=t.id||`cli-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!s){let f=Kt().find(h=>h.function.name===n),p=f?JSON.stringify(f.function.parameters,null,2):"unknown";return N(`${m.yellow} \u26A0 ${n}: malformed arguments, sending schema hint${m.reset}`),{callId:o,fnName:n,args:null,canExecute:!1,errorResult:{role:"tool",content:`ERROR: Malformed tool arguments. Could not parse your arguments as JSON.
1015
+ \u26A0 [Response truncated: repeated paragraph detected (${s}\xD7)]`,c=0,u=-1,d=0;for(;c<e;){let p=t.indexOf(r,d);if(p===-1)break;c++,u=p+r.length,d=p+1}return{text:u>0?t.slice(0,u)+l:t.slice(0,2e3)+l,truncated:!0,repeatCount:s}}var Fd=null,Bd=null,Ud=null;function Kt(){if(Fd===null){let{TOOL_DEFINITIONS:t}=Do();Fd=t}return Bd===null&&(Bd=GA()),Ud===null&&(Ud=WA()),[...Fd,...Bd,...Ud]}var Rl=50;function iO(t){Number.isFinite(t)&&t>0&&(Rl=t)}function Wd(t=Yn()){if(process.env.NEX_DISABLE_TOOL_BUDGET==="1")return 1/0;let e=process.env.NEX_MAX_TOOL_CALLS;if(e){let n=parseInt(e,10);if(Number.isFinite(n)&&n>0)return n}return t==="local"?5:30}function p0(t,e){return`[SYSTEM STOP] Tool-call budget reached (${t}/${e}). You MUST stop calling tools now. Provide your final answer based only on the information already in the conversation. If the task cannot be completed from the gathered evidence, state the blocker plainly and do not invent facts.`}var Cl=()=>null;function aO(t){Cl=t}var di=null,tf=null,ar=null,lr="",cr=0,nf="",sf=0,Al=new Map,lO=1e4,cO=6e3,uO=/\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 dO(t){return!t||typeof t!="string"?t:t.replace(uO,(e,n)=>`${n}=***REDACTED***`)}var fO=7e3,pO=4e3;function hO(t,e=null){let n=dO(t),o=mA(n),s=e==="read_file"?fO:lO,r=e==="read_file"?pO:cO;if(o>s)try{let{compressToolResult:i}=Fn();return i(n,r)}catch{return n}return n}function C0(t){try{let{getActiveModel:e}=vt(),n=e(),o=n?`${n.provider}:${n.id}`:"default";if(Al.has(o))return Al.get(o);let s=c0(t);return Al.set(o,s),s}catch{return c0(t)}}function mO(){Al.clear()}function gO(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 fi={hash:null,ts:0},yO=3e4;async function A0(){if(fi.hash&&Date.now()-fi.ts<yO)return fi.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}=Gr(),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 fi={hash:r,ts:Date.now()},r}catch{return`fallback:${Date.now()}`}}function Ol(){di=null,tf=null,fi={hash:null,ts:0},ar=null}var bO=new Set(["spawn_agents"]),Hd=10,Gd=10,kl=5,h0=6e4,Yd=12e4,wO=process.env.NEX_STALE_AUTO_SWITCH!=="0";function _O(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{}}NA(t=>{PA(t,"allow"),MA(),console.log(`${m.green} \u2713 ${t}: always allow${m.reset}`)});async function $O(t){let e=t.function.name,n=e;if(typeof e=="string"&&e.includes(".")){let f=e.split(".").pop(),p={exec:"bash",find:"search_files",search:"search_files",grep_search:"grep",list:"list_directory",print_tree:"list_directory",read:"read_file",tree:"list_directory"};Kt().some(g=>g.function.name===f)?n=f:p[f]&&(n=p[f])}let o=fA(t.function.arguments),s=t.id||`cli-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!o){let p=Kt().find(g=>g.function.name===n),h=p?JSON.stringify(p.function.parameters,null,2):"unknown";return N(`${m.yellow} \u26A0 ${n}: malformed arguments, sending schema hint${m.reset}`),{callId:s,fnName:n,args:null,canExecute:!1,errorResult:{role:"tool",content:`ERROR: Malformed tool arguments. Could not parse your arguments as JSON.
1016
1016
  Raw input: ${typeof t.function.arguments=="string"?t.function.arguments.substring(0,200):"N/A"}
1017
1017
 
1018
1018
  Expected JSON schema for "${n}":
1019
- ${p}
1019
+ ${h}
1020
1020
 
1021
- Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:o}}}if(s&&typeof s.path=="string")try{let d=require("os"),f=Ye.resolve(process.cwd(),s.path.replace(/^~/,d.homedir())),p=s.path;s.path=Ye.relative(process.cwd(),f)||".",Object.defineProperty(s,"_originalPath",{value:p,enumerable:!1})}catch(d){console.error("path resolution failed:",d.message)}s&&(n==="search_files"||n==="grep")&&typeof s.pattern!="string"&&(typeof s.query=="string"?s.pattern=s.query:typeof s.search=="string"&&(s.pattern=s.search));let r=KA(n,s);if(!r.valid){N(`${m.yellow} \u26A0 ${n}: ${r.error.split(`
1022
- `)[0]}${m.reset}`);let d=(g0.get(n)||0)+1;g0.set(n,d);let f=d>=2?`${r.error}
1021
+ Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:s}}}if(o&&typeof o.path=="string")try{let f=require("os"),p=Ye.resolve(process.cwd(),o.path.replace(/^~/,f.homedir())),h=o.path;o.path=Ye.relative(process.cwd(),p)||".",Object.defineProperty(o,"_originalPath",{value:h,enumerable:!1})}catch(f){console.error("path resolution failed:",f.message)}o&&(n==="search_files"||n==="grep")&&typeof o.pattern!="string"&&(typeof o.query=="string"?o.pattern=o.query:typeof o.search=="string"&&(o.pattern=o.search));let r=KA(n,o);if(!r.valid){N(`${m.yellow} \u26A0 ${n}: ${r.error.split(`
1022
+ `)[0]}${m.reset}`);let f=(g0.get(n)||0)+1;g0.set(n,f);let p=f>=2?`${r.error}
1023
1023
 
1024
- [SYSTEM: This is argument error #${d} for "${n}". Study the "Expected parameters" schema above and correct your call \u2014 do not repeat the same mistake.]`:r.error;return{callId:o,fnName:n,args:s,canExecute:!1,errorResult:{role:"tool",content:f,tool_call_id:o}}}let i=r.corrected||s;if(r.corrected){let d=Object.keys(s),f=Object.keys(r.corrected),p=d.filter(h=>!f.includes(h));p.length&&console.log(`${m.dim} \u2713 ${n}: corrected args (${p.join(", ")})${m.reset}`)}if(go()&&!x0.has(n))return console.log(`${m.yellow} \u2717 ${n}: blocked in plan mode${m.reset}`),{callId:o,fnName:n,args:i,canExecute:!1,errorResult:{role:"tool",content:`PLAN MODE: '${n}' is blocked. Only read-only tools are allowed. Present your plan as text output instead of making changes.`,tool_call_id:o}};let a=new Set(["read_file","list_directory","search_files","glob","grep","git_status","git_diff","git_log","git_show","ssh_exec"]),l=new Set(["read_file","list_directory","glob","grep","bash","git_status","git_diff","git_log","ssh_exec"]),c=n==="spawn_agents"&&Array.isArray(i?.agents)&&i.agents.length>0&&i.agents.every(d=>d.background===!0);if(de&&ke==="plan"&&!a.has(n)&&!n.startsWith("skill_")&&!c)return Ts++,fr=n,N(`${m.yellow} \u2717 ${n}: blocked in plan phase (read-only, block #${Ts})${m.reset}`),{callId:o,fnName:n,args:i,canExecute:!1,errorResult:{role:"tool",content:`PLAN PHASE: '${n}' 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(de&&ke==="verify"&&!l.has(n)&&!n.startsWith("skill_"))return N(`${m.yellow} \u2717 ${n}: blocked in verify phase (read + bash only)${m.reset}`),{callId:o,fnName:n,args:i,canExecute:!1,errorResult:{role:"tool",content:`VERIFY PHASE: '${n}' is blocked. Use read_file and bash (for tests/linters) to verify changes. Report PASS or FAIL.`,tool_call_id:o}};let u=OA(n);if(u==="deny")return console.log(`${m.red} \u2717 ${n}: denied by permissions${m.reset}`),{callId:o,fnName:n,args:i,canExecute:!1,errorResult:{role:"tool",content:`DENIED: Tool '${n}' is blocked by permissions`,tool_call_id:o}};if(u==="ask"){let d=` Allow ${n}?`;return n==="bash"&&i.command&&(d=` bash: \`${i.command.substring(0,80)}${i.command.length>80?"\u2026":""}\`?`),await k0(d,{toolName:n})?{callId:o,fnName:n,args:i,canExecute:!0,confirmedByUser:!0,errorResult:null}:{callId:o,fnName:n,args:i,canExecute:!1,confirmedByUser:!1,errorResult:{role:"tool",content:`CANCELLED: User declined ${n}`,tool_call_id:o}}}return{callId:o,fnName:n,args:i,canExecute:!0,confirmedByUser:!0,errorResult:null}}async function kO(t,e,n={}){let s=await YA(t,e);if(s!==null)return s;let o=await UA(t,e);return o!==null?o:yf(t,e,n)}function xO(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 zd(t,e=!1){e||console.log(cA(t.fnName,t.args));let n=s0("pre-tool",{tool_name:t.fnName}),s=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 k=vi(t.fnName,t.args,w,!0);return e||console.log(k),{msg:{role:"tool",content:w,tool_call_id:t.callId},summary:k}}if(!e&&s.length>0)for(let w of s)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}`);ft?.onToolStart&&ft.onToolStart(t.fnName,t.args);let o=await kO(t.fnName,t.args,{silent:!0,autoConfirm:t.confirmedByUser===!0}),r=null,i;o&&typeof o=="object"&&o.text?(i=String(o.text),Array.isArray(o.images)&&o.images.length>0&&(r=o.images)):i=String(o??"");let a=i.length>5e4?i.substring(0,5e4)+`
1024
+ [SYSTEM: This is argument error #${f} for "${n}". Study the "Expected parameters" schema above and correct your call \u2014 do not repeat the same mistake.]`:r.error;return{callId:s,fnName:n,args:o,canExecute:!1,errorResult:{role:"tool",content:p,tool_call_id:s}}}let i=r.corrected||o;if(r.corrected){let f=Object.keys(o),p=Object.keys(r.corrected),h=f.filter(g=>!p.includes(g));h.length&&console.log(`${m.dim} \u2713 ${n}: corrected args (${h.join(", ")})${m.reset}`)}if(go()&&!x0.has(n))return console.log(`${m.yellow} \u2717 ${n}: blocked in plan mode${m.reset}`),{callId:s,fnName:n,args:i,canExecute:!1,errorResult:{role:"tool",content:`PLAN MODE: '${n}' is blocked. Only read-only tools are allowed. Present your plan as text output instead of making changes.`,tool_call_id:s}};let a=new Set(["read_file","list_directory","search_files","glob","grep","git_status","git_diff","git_log","git_show","ssh_exec"]),l=new Set(["read_file","list_directory","glob","grep","bash","git_status","git_diff","git_log","ssh_exec"]),c=n==="spawn_agents"&&Array.isArray(i?.agents)&&i.agents.length>0&&i.agents.every(f=>f.background===!0);if(de&&ke==="plan"&&!a.has(n)&&!n.startsWith("skill_")&&!c)return Ts++,fr=n,N(`${m.yellow} \u2717 ${n}: blocked in plan phase (read-only, block #${Ts})${m.reset}`),{callId:s,fnName:n,args:i,canExecute:!1,errorResult:{role:"tool",content:`PLAN PHASE: '${n}' is blocked. Analyze the codebase using read-only tools, then present your findings as text. Edits happen in the next phase.`,tool_call_id:s}};if(de&&ke==="verify"&&!l.has(n)&&!n.startsWith("skill_"))return N(`${m.yellow} \u2717 ${n}: blocked in verify phase (read + bash only)${m.reset}`),{callId:s,fnName:n,args:i,canExecute:!1,errorResult:{role:"tool",content:`VERIFY PHASE: '${n}' is blocked. Use read_file and bash (for tests/linters) to verify changes. Report PASS or FAIL.`,tool_call_id:s}};if(new Set(["write_file","edit_file","patch_file"]).has(n)&&process.env.NEX_SCOPE){let f=i.path||i.file_path||"";if(f){let p=process.env.NEX_SCOPE.split(",").map(w=>w.trim()),h=f.replace(/\\/g,"/");if(!p.some(w=>new RegExp("^"+w.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"___DOUBLESTAR___").replace(/\*/g,"[^/]*").replace(/___DOUBLESTAR___/g,".*")+"$").test(h)||h.endsWith(w)||h===w))return N(`${m.yellow} \u2717 ${n}: ${f} outside scope (--scope ${process.env.NEX_SCOPE})${m.reset}`),{callId:s,fnName:n,args:i,canExecute:!1,errorResult:{role:"tool",content:`SCOPE BLOCKED: '${f}' is outside the allowed scope. Only these files may be edited: ${process.env.NEX_SCOPE}. Use read_file to inspect other files, but do not edit them.`,tool_call_id:s}}}}let d=OA(n);if(d==="deny")return console.log(`${m.red} \u2717 ${n}: denied by permissions${m.reset}`),{callId:s,fnName:n,args:i,canExecute:!1,errorResult:{role:"tool",content:`DENIED: Tool '${n}' is blocked by permissions`,tool_call_id:s}};if(d==="ask"){let f=` Allow ${n}?`;return n==="bash"&&i.command&&(f=` bash: \`${i.command.substring(0,80)}${i.command.length>80?"\u2026":""}\`?`),await k0(f,{toolName:n})?{callId:s,fnName:n,args:i,canExecute:!0,confirmedByUser:!0,errorResult:null}:{callId:s,fnName:n,args:i,canExecute:!1,confirmedByUser:!1,errorResult:{role:"tool",content:`CANCELLED: User declined ${n}`,tool_call_id:s}}}return{callId:s,fnName:n,args:i,canExecute:!0,confirmedByUser:!0,errorResult:null}}async function kO(t,e,n={}){let o=await YA(t,e);if(o!==null)return o;let s=await UA(t,e);return s!==null?s:yf(t,e,n)}function xO(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 zd(t,e=!1){e||console.log(cA(t.fnName,t.args));let n=s0("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 k=vi(t.fnName,t.args,w,!0);return e||console.log(k),{msg:{role:"tool",content:w,tool_call_id:t.callId},summary:k}}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}`);ft?.onToolStart&&ft.onToolStart(t.fnName,t.args);let s=await kO(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)+`
1025
1025
  ...(truncated ${i.length-5e4} chars)`:i,l=a.split(`
1026
1026
  `)[0],c=l.startsWith("ERROR")||l.includes("CANCELLED")||l.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(a)&&/✗ Agent/.test(a),u=vi(t.fnName,t.args,a,c);e||console.log(u),ft?.onToolEnd&&ft.onToolEnd(t.fnName,u,!c);let f=s0("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=hO(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+=`
1027
1027
  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+=`
1028
1028
  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+=`
1029
- 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:u}}var vO=[{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 Kd(t){for(let{re:e,label:n}of vO){let s=t.match(e);if(s){let o=(s[1]||"").trim();return o?`${n}: ${o}`:n}}return null}async function SO(t,e=!1,n={}){let s=new Array(t.length),o=[],r=[],i=null;if(e&&!n.skipSpinner){let l=t.filter(c=>c.canExecute);if(l.length>0){let c;if(l.length===1){let u=l[0],d=xO(u.fnName,u.args);c=`\u23FA ${u.fnName}${d?`(${d})`:""}`}else{let u=l.map(d=>d.fnName).join(", ");c=`\u23FA ${l.length} tools: ${u.length>60?u.substring(0,57)+"\u2026":u}`}i=new ir(c),i.start()}}async function a(){if(r.length!==0){if(r.length===1){let l=r[0],{msg:c,summary:u}=await zd(t[l],e);s[l]=c,o.push(u)}else{let l=r.map(u=>zd(t[u],e)),c=await Promise.all(l);for(let u=0;u<r.length;u++)s[r[u]]=c[u].msg,o.push(c[u].summary)}r=[]}}for(let l=0;l<t.length;l++){let c=t[l];if(!c.canExecute){await a(),s[l]=c.errorResult,o.push(vi(c.fnName,c.args||{},c.errorResult.content,!0));continue}if(bO.has(c.fnName)){await a(),c.fnName==="spawn_agents"&&i&&(i.stop(),i=null);let{msg:u,summary:d}=await zd(c,e);s[l]=u,o.push(d)}else r.push(l)}if(await a(),i&&i.stop(),e&&o.length>0&&!n.skipSummaries)for(let l of o)console.log(l);return{results:s,summaries:o}}var x=[],m0=300,O0=900*1e3;function Un(t,e){let n=t.get(e);return n?Date.now()-n.ts>O0?(t.delete(e),0):n.count:0}function co(t,e){let n=t.get(e),s=n&&Date.now()-n.ts<=O0?n.count+1:1;return t.set(e,{count:s,ts:Date.now()}),s}function Vd(t,e,n){t.set(e,{count:n,ts:Date.now()})}var bf=new Map,P0=new Map,Pl=new Map,bi=new Set,M0=new Map,Ml=new Map,wi=new Set,zn=new Map,as=new Map,_i=new Map,Et=new Map,yo=new Map,g0=new Map,Gl=new Map,of=new Map,mn=0,pi=0,Nl=0,rf="",Ll=0,tn=!1,xl=0,Il=0,fo=-1,af=!1,jl=0,Dl=!1,yn=0,bn=!1,Rn=0,wn=0,Pt=!1,zt="",hi=0,xs=0,ql="",po=0,ho=0,Fl="",ci=0,gn=!1,lf=!1,Si=new Map,Ei=new Set,mi=null,sr=!1,ui=0,y0=!1,Ie=null,nn=!1,wf=null,cf=!1,uf=!1,Bl=!1,Ss="",mo="",gi="",ke="plan",Yl=0,de=!1,Ts=0,fr=null,An=null,Ti=null,df=null,ur=0,pr=0,hr=0,Es=0,vl=0,Sl=0,Kn=!1,Vn=0,bo=null,ls=[],vs=new Set,Be=!1,Vt=0,Ri=0,Ut=new Set,wo=new Set,Tt=!1,Jl="",Ul=!1,Hn=0,sn=0,$i=0,zl=0,Kl=0,mr=new Set,ki=new Map,Vl=8,dr=10,b0=3,EO=3,TO=4,RO=new Set(["read_file","grep","search_files","glob","list_directory","find_files"]),w0=null;function CO(t){return t==="write_file"||t==="edit_file"||t==="patch_file"||t==="bash"}function ff(t){let e=String(t||"");if(!e||Ai(e)||xi(e).length!==1)return!1;let s=/\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),o=/\b(create|write|add|make|build|refactor|update|change|edit)\b[\s\S]{0,160}\bfile\b/i.test(e);return s||o}function Ai(t){let e=String(t||"");return e?Zl(e)?!0:/\bAutomation(?:\s+ID)?\b|\bLast run:\b/i.test(e)||/\b(work from main|at the start|current branch|git status|worktree|dirty|unrelated changes?|pull\/rebase|before changing|before editing)\b/i.test(e)||/\b(if|when)\b[\s\S]{0,120}\b(stop|abort|do not|don't|without editing|without committing|without pushing)\b/i.test(e)||/\b(backlog|primary backlog|pick (?:at most )?one|at most one|choose (?:one|a task)|priority order|verification is mandatory|stage only|commit and push|push main|push devel)\b/i.test(e):!1}function N0(t){let e=String(t||"");return!e||!Ai(e)?!1:/\b(primary backlog|backlog|pick at most one|at most one|priority order|choose (?:one|a task)|one tightly scoped improvement)\b/i.test(e)}function Gn({blocked:t=!1}={}){return[t?"[SYSTEM BLOCKED] Bounded backlog planning has enough evidence. Do not read or search more files.":"[SYSTEM] Bounded backlog automation plan template.","Before deciding, inspect the concrete backlog/reference paths named by the user prompt. Prefer read_file on those paths over generic searches for words like `backlog`, `TODO`, or `FIXME`.","Ground the selected improvement in those files and the current project. Do not invent generic React bugs, placeholder files, or example components that were not found in the evidence.","For UI work, choose only controls, labels, handlers, or component names that were actually visible in the evidence already read. Do not infer a button exists from the product domain; if the exact target is delegated to a child component, name that existing child component/file as the target instead.","Write the plan now using exactly these label lines. Do not use markdown headings for these labels.","Selected improvement: name one scoped task, or write `no safe task found`.","Selection rationale: why this task is the safest/highest-value choice from the backlog evidence.","Files: list the files you will change and any read-only reference files.","Implementation outline: concrete edit steps, kept to this one task.","Verification plan: exact focused commands or reads that will prove the change.","Browser/UI applicability: say required, not required, or blocked, with the reason.",`After ${Vl}-${dr} read/search tools, you must choose one scoped task or stop cleanly with \`no safe task found\`; do not keep exploring.`].join(`
1030
- `)}function Lt(t){return String(t||"").replace(/^\.\/+/,"").replace(/\/+$/,"")}function AO(t){let e=String(t||"");if(!e)return null;let n=[/\b(?:work|operate|run)\s+(?:only\s+)?(?:in|inside|within|from)\s+[`"']?(\/[^\s`"',;:)]+)/i,/\bworking\s+directory\s*:\s*[`"']?(\/[^\s`"',;:)]+)/i,/\bcwd\s*:\s*[`"']?(\/[^\s`"',;:)]+)/i];for(let s of n){let o=e.match(s);if(!o)continue;let r=String(o[1]||"").replace(/[.]+$/,"");if(r)try{let i=Ye.resolve(r);if(Ue.existsSync(i)&&Ue.statSync(i).isDirectory())return Ue.realpathSync(i)}catch{}}return null}function OO(t,e={}){if(!Be||Ut.size===0)return!0;let n=[];if(e.path&&n.push(e.path),e.pattern&&/[/.]/.test(String(e.pattern))&&n.push(e.pattern),e.include&&/[/.]/.test(String(e.include))&&n.push(e.include),e.file_pattern&&/[/.]/.test(String(e.file_pattern))&&n.push(e.file_pattern),n.length===0)return!1;let s=n.map(Lt);for(let o of Ut){let r=Lt(o);if(r&&s.some(i=>i===r||i.endsWith(`/${r}`)||r.endsWith(`/${i}`)))return!0}return t==="grep"||t==="search_files"?s.some(o=>[...Ut].some(r=>o.includes(Lt(r)))):!1}function PO(t,e={}){if(t!=="grep"&&t!=="search_files"&&t!=="glob"&&t!=="list_directory"&&t!=="find_files")return!1;let n=Lt(e.path||e.cwd||"");if(n&&Ut.has(n))return!1;let s=String(e.pattern||e.glob||e.query||e.search||""),o=String(e.include||e.file_pattern||""),r=`${n} ${s} ${o}`;return![...Ut].some(i=>{let a=Lt(i);return a&&r.includes(a)})}function L0(t){if(!Be)return!1;let e=String(t||"");if(!e.trim())return!1;let n=String(Jl||"");if(/\b(stale data|list component|ListComponent)\b/i.test(e)&&!/\b(stale data|list component|ListComponent)\b/i.test(n))return!0;let o=new Set,r=/[`'"]?((?:[A-Za-z0-9_.@-]+\/)+[A-Za-z0-9_.@-]+\.(?:tsx|jsx|mjs|cjs|mdx|json|scss|html|yaml|yml|css|ts|js|md))[`'"]?/g,i;for(;i=r.exec(e);)o.add(Lt(i[1]));let a=0,l=0;for(let c of o){if(Ut.has(c))continue;a++;let u=Ye.resolve(process.cwd(),c);Ue.existsSync(u)&&l++}return!1}function I0(t){let e=new Set,n=/[`'"]?((?:[A-Za-z0-9_.@-]+\/)+[A-Za-z0-9_.@-]+\.(?:tsx|jsx|mjs|cjs|mdx|json|scss|html|yaml|yml|css|ts|js|md))[`'"]?/g,s;for(;s=n.exec(String(t||""));)e.add(Lt(s[1]));return[...e]}function MO(t){if(!Be||wo.size===0)return!1;let e=I0(t).filter(s=>s&&!/\.(md|mdx|txt|rst|adoc)$/i.test(s));return e.length===0?!1:e.filter(s=>Ue.existsSync(Ye.resolve(process.cwd(),s))).length===0}function El(t,e){let n=String(e||"").replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?:^|\\n)\\s*(?:[-*]\\s*)?(?:\\*\\*)?${n}\\s*:(?:\\*\\*)?`,"i").test(String(t||""))}function yi(t){let e=String(t||"");return!e.trim()||L0(e)||j0(e)?!1:/\bno safe task found\b/i.test(e)?!0:El(e,"Selected improvement")&&El(e,"Selection rationale")&&El(e,"Files")&&El(e,"Verification plan")}function j0(t){let e=String(t||"");return e.trim()?/(?:^|\n)\s*#{1,6}\s*selected improvement\b/i.test(e)&&/(?:^|\n)\s*#{1,6}\s*selection rationale\b/i.test(e)&&/(?:^|\n)\s*#{1,6}\s*files\b/i.test(e)&&/(?:^|\n)\s*#{1,6}\s*verification plan\b/i.test(e):!1}function NO(t){let e=String(t||"");return e.trim()?/\b(need|must|will|should|let'?s|attempt|going)\b.{0,80}\b(call|issue|use|run|read)\b.{0,80}\b(read_file|tool call|tool_calls?|JSON calls?)\b/i.test(e)||/\b(need|must|will|should|let'?s|attempt|going)\b.{0,80}\b(run|check|use)\b.{0,80}\b(git status|bash|grep|glob|search)\b/i.test(e)||/\{\s*["']tool["']\s*:\s*["'](?:read_file|grep|search_files|glob)["']/i.test(e):!1}function uo(t,e){return Be&&Tt&&(sn>0||Et.size>0)&&t.size===0&&e===0}function D0(t){let e=String(t||"");if(!/\bno safe task found\b/i.test(e)||/\bexample only\b|\bnot applicable\b/i.test(e)||!(/\b(because|reason|blocked|blocker|cannot|can't|unable|failed|unavailable|permission denied|missing|not found|no readable|dirty worktree|wrong branch|merge conflict|precheck blocked|preflight failed|ambiguous|unrelated|manual user work|no safe worthwhile improvement)\b/i.test(e)&&e.trim().length>60))return!1;let s=Ut.size===0||Ri>0;return Vt>=Vl?s:/\b(blocked|blocker|cannot|can't|unable|failed|unavailable|permission denied|missing|not found|no readable|dirty worktree|wrong branch|merge conflict|precheck blocked|preflight failed)\b/i.test(e)&&/\b(because|reason|preflight|worktree|branch|git|permission|missing|unavailable|inspect|read|search)\b/i.test(e)}function pf(t){let e=String(t||"");if(!e.trim()||/\bexample only\b/i.test(e))return!1;let n=/\bpreflight\s*:/i.test(e),s=/\bpreflight output\s*:/i.test(e),o=/\bbranch\s*:/i.test(e),r=/\b(chosen task|selected improvement)\s*:/i.test(e)||/\bno safe task found\b/i.test(e),i=/\bfiles changed\s*:/i.test(e),a=/\bverification\s*:/i.test(e),l=/\bcommit\s*:/i.test(e),c=/\bpush\s*:/i.test(e),u=/\bfinal git status\s*:/i.test(e);return!(n&&s&&o&&r&&i&&a&&l&&c&&u)||Ie?.ran&&(/\bpreflight\s*:\s*(?:not performed|not run|not applicable|unknown)\b/i.test(e)||/\bpreflight output\s*:\s*(?:not performed|not run|not applicable|unknown|\(missing preflight output\))\b/i.test(e)||/\bbranch\s*:\s*(?:not applicable|unknown)\b/i.test(e))?!1:/\bno safe task found\b/i.test(e)?D0(e):!0}function Zl(t){let e=String(t||"");if(!e)return null;let n=[/\bwork\s+(?:from|on)\s+(?:the\s+)?(?:branch\s+)?[`'"]?([A-Za-z0-9._/-]+)[`'"]?\s+only\b/i,/\bwork\s+(?:from|on)\s+(?:the\s+)?[`'"]?([A-Za-z0-9._/-]+)[`'"]?\s+branch\s+only\b/i];for(let s of n){let o=e.match(s);if(!o)continue;let r=String(o[1]||"").trim();if(r)return r}return null}function LO(t){let e=String(t||"").trim();if(!e)return{branch:null,dirty:null,changedFiles:[]};if(/^fatal:/i.test(e))return{branch:null,dirty:null,changedFiles:[]};let n=e.split(`
1031
- `).map(l=>l.replace(/\r$/,"")),s=n.find(l=>l.startsWith("## "))||n[0]||"",o=s.startsWith("## ")?s.slice(3).trim():s.trim(),r=o?o.split("...")[0].trim().split(/\s+/)[0]:null,i=n.filter(l=>!l.startsWith("## ")&&l.trim()!==""),a=[];for(let l of i){let c=l.match(/^[ MADRCU?!]{1,2}\s+(.*)$/);if(!c)continue;let u=(c[1]||"").trim();if(!u)continue;let d=u.includes(" -> ")?u.split(" -> ").pop():u;d&&a.push(d)}return{branch:r||null,dirty:a.length>0,changedFiles:a}}function IO(t){let e=String(t||"");return!e||!Ai(e)?!1:Zl(e)?!0:/\b(git status|current branch|worktree|dirty|pull\/rebase|rebase|commit|push)\b/i.test(e)}function jO(t,e=2500){let n=String(t??"");return n.trim()?n.length<=e?n:n.slice(0,e)+`
1032
- ...(truncated ${n.length-e} chars)`:"(no output)"}async function DO(t,e,n){if(Ie?.ran)return Ie;let s=wf||Zl(t),o="git status --short --branch",r="preflight-git-status";Ie={required:!0,ran:!0,ok:!1,command:o,requiredBranch:s,branch:null,dirty:null,changedFiles:[],raw:""};let i="",a=!1;try{let w={role:"assistant",content:"",tool_calls:[{id:r,type:"function",function:{name:"bash",arguments:JSON.stringify({command:o})}}]};n.push(w),e.push(w),ft?.onToolStart&&(ft.onToolStart("bash",{command:o}),a=!0),i=await yf("bash",{command:o},{silent:!0,autoConfirm:!0})}catch(w){i=`ERROR: failed to run preflight: ${w?.message||String(w)}`}let l=String(i??"");if(a&&ft?.onToolEnd){let w=l.length>5e4?l.substring(0,5e4)+`
1029
+ 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:u}}var vO=[{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 Kd(t){for(let{re:e,label:n}of vO){let o=t.match(e);if(o){let s=(o[1]||"").trim();return s?`${n}: ${s}`:n}}return null}async function SO(t,e=!1,n={}){let o=new Array(t.length),s=[],r=[],i=null;if(e&&!n.skipSpinner){let l=t.filter(c=>c.canExecute);if(l.length>0){let c;if(l.length===1){let u=l[0],d=xO(u.fnName,u.args);c=`\u23FA ${u.fnName}${d?`(${d})`:""}`}else{let u=l.map(d=>d.fnName).join(", ");c=`\u23FA ${l.length} tools: ${u.length>60?u.substring(0,57)+"\u2026":u}`}i=new ir(c),i.start()}}async function a(){if(r.length!==0){if(r.length===1){let l=r[0],{msg:c,summary:u}=await zd(t[l],e);o[l]=c,s.push(u)}else{let l=r.map(u=>zd(t[u],e)),c=await Promise.all(l);for(let u=0;u<r.length;u++)o[r[u]]=c[u].msg,s.push(c[u].summary)}r=[]}}for(let l=0;l<t.length;l++){let c=t[l];if(!c.canExecute){await a(),o[l]=c.errorResult,s.push(vi(c.fnName,c.args||{},c.errorResult.content,!0));continue}if(bO.has(c.fnName)){await a(),c.fnName==="spawn_agents"&&i&&(i.stop(),i=null);let{msg:u,summary:d}=await zd(c,e);o[l]=u,s.push(d)}else r.push(l)}if(await a(),i&&i.stop(),e&&s.length>0&&!n.skipSummaries)for(let l of s)console.log(l);return{results:o,summaries:s}}var x=[],m0=300,O0=900*1e3;function Un(t,e){let n=t.get(e);return n?Date.now()-n.ts>O0?(t.delete(e),0):n.count:0}function co(t,e){let n=t.get(e),o=n&&Date.now()-n.ts<=O0?n.count+1:1;return t.set(e,{count:o,ts:Date.now()}),o}function Vd(t,e,n){t.set(e,{count:n,ts:Date.now()})}var bf=new Map,P0=new Map,Pl=new Map,bi=new Set,M0=new Map,Ml=new Map,wi=new Set,zn=new Map,as=new Map,_i=new Map,Et=new Map,yo=new Map,g0=new Map,Gl=new Map,of=new Map,mn=0,pi=0,Nl=0,rf="",Ll=0,tn=!1,xl=0,Il=0,fo=-1,af=!1,jl=0,Dl=!1,yn=0,bn=!1,Rn=0,wn=0,Pt=!1,zt="",hi=0,xs=0,ql="",po=0,ho=0,Fl="",ci=0,gn=!1,lf=!1,Si=new Map,Ei=new Set,mi=null,sr=!1,ui=0,y0=!1,Ie=null,nn=!1,wf=null,cf=!1,uf=!1,Bl=!1,Ss="",mo="",gi="",ke="plan",Yl=0,de=!1,Ts=0,fr=null,An=null,Ti=null,df=null,ur=0,pr=0,hr=0,Es=0,vl=0,Sl=0,Kn=!1,Vn=0,bo=null,ls=[],vs=new Set,Be=!1,Vt=0,Ri=0,Ut=new Set,wo=new Set,Tt=!1,Jl="",Ul=!1,Hn=0,sn=0,$i=0,zl=0,Kl=0,mr=new Set,ki=new Map,Vl=8,dr=10,b0=3,EO=3,TO=4,RO=new Set(["read_file","grep","search_files","glob","list_directory","find_files"]),w0=null;function CO(t){return t==="write_file"||t==="edit_file"||t==="patch_file"||t==="bash"}function ff(t){let e=String(t||"");if(!e||Ai(e)||xi(e).length!==1)return!1;let 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 o||s}function Ai(t){let e=String(t||"");return e?Zl(e)?!0:/\bAutomation(?:\s+ID)?\b|\bLast run:\b/i.test(e)||/\b(work from main|at the start|current branch|git status|worktree|dirty|unrelated changes?|pull\/rebase|before changing|before editing)\b/i.test(e)||/\b(if|when)\b[\s\S]{0,120}\b(stop|abort|do not|don't|without editing|without committing|without pushing)\b/i.test(e)||/\b(backlog|primary backlog|pick (?:at most )?one|at most one|choose (?:one|a task)|priority order|verification is mandatory|stage only|commit and push|push main|push devel)\b/i.test(e):!1}function N0(t){let e=String(t||"");return!e||!Ai(e)?!1:/\b(primary backlog|backlog|pick at most one|at most one|priority order|choose (?:one|a task)|one tightly scoped improvement)\b/i.test(e)}function Gn({blocked:t=!1}={}){return[t?"[SYSTEM BLOCKED] Bounded backlog planning has enough evidence. Do not read or search more files.":"[SYSTEM] Bounded backlog automation plan template.","Before deciding, inspect the concrete backlog/reference paths named by the user prompt. Prefer read_file on those paths over generic searches for words like `backlog`, `TODO`, or `FIXME`.","Ground the selected improvement in those files and the current project. Do not invent generic React bugs, placeholder files, or example components that were not found in the evidence.","For UI work, choose only controls, labels, handlers, or component names that were actually visible in the evidence already read. Do not infer a button exists from the product domain; if the exact target is delegated to a child component, name that existing child component/file as the target instead.","Write the plan now using exactly these label lines. Do not use markdown headings for these labels.","Selected improvement: name one scoped task, or write `no safe task found`.","Selection rationale: why this task is the safest/highest-value choice from the backlog evidence.","Files: list the files you will change and any read-only reference files.","Implementation outline: concrete edit steps, kept to this one task.","Verification plan: exact focused commands or reads that will prove the change.","Browser/UI applicability: say required, not required, or blocked, with the reason.",`After ${Vl}-${dr} read/search tools, you must choose one scoped task or stop cleanly with \`no safe task found\`; do not keep exploring.`].join(`
1030
+ `)}function Lt(t){return String(t||"").replace(/^\.\/+/,"").replace(/\/+$/,"")}function AO(t){let e=String(t||"");if(!e)return null;let n=[/\b(?:work|operate|run)\s+(?:only\s+)?(?:in|inside|within|from)\s+[`"']?(\/[^\s`"',;:)]+)/i,/\bworking\s+directory\s*:\s*[`"']?(\/[^\s`"',;:)]+)/i,/\bcwd\s*:\s*[`"']?(\/[^\s`"',;:)]+)/i];for(let o of n){let s=e.match(o);if(!s)continue;let r=String(s[1]||"").replace(/[.]+$/,"");if(r)try{let i=Ye.resolve(r);if(Ue.existsSync(i)&&Ue.statSync(i).isDirectory())return Ue.realpathSync(i)}catch{}}return null}function OO(t,e={}){if(!Be||Ut.size===0)return!0;let n=[];if(e.path&&n.push(e.path),e.pattern&&/[/.]/.test(String(e.pattern))&&n.push(e.pattern),e.include&&/[/.]/.test(String(e.include))&&n.push(e.include),e.file_pattern&&/[/.]/.test(String(e.file_pattern))&&n.push(e.file_pattern),n.length===0)return!1;let o=n.map(Lt);for(let s of Ut){let r=Lt(s);if(r&&o.some(i=>i===r||i.endsWith(`/${r}`)||r.endsWith(`/${i}`)))return!0}return t==="grep"||t==="search_files"?o.some(s=>[...Ut].some(r=>s.includes(Lt(r)))):!1}function PO(t,e={}){if(t!=="grep"&&t!=="search_files"&&t!=="glob"&&t!=="list_directory"&&t!=="find_files")return!1;let n=Lt(e.path||e.cwd||"");if(n&&Ut.has(n))return!1;let o=String(e.pattern||e.glob||e.query||e.search||""),s=String(e.include||e.file_pattern||""),r=`${n} ${o} ${s}`;return![...Ut].some(i=>{let a=Lt(i);return a&&r.includes(a)})}function L0(t){if(!Be)return!1;let e=String(t||"");if(!e.trim())return!1;let n=String(Jl||"");if(/\b(stale data|list component|ListComponent)\b/i.test(e)&&!/\b(stale data|list component|ListComponent)\b/i.test(n))return!0;let s=new Set,r=/[`'"]?((?:[A-Za-z0-9_.@-]+\/)+[A-Za-z0-9_.@-]+\.(?:tsx|jsx|mjs|cjs|mdx|json|scss|html|yaml|yml|css|ts|js|md))[`'"]?/g,i;for(;i=r.exec(e);)s.add(Lt(i[1]));let a=0,l=0;for(let c of s){if(Ut.has(c))continue;a++;let u=Ye.resolve(process.cwd(),c);Ue.existsSync(u)&&l++}return!1}function I0(t){let e=new Set,n=/[`'"]?((?:[A-Za-z0-9_.@-]+\/)+[A-Za-z0-9_.@-]+\.(?:tsx|jsx|mjs|cjs|mdx|json|scss|html|yaml|yml|css|ts|js|md))[`'"]?/g,o;for(;o=n.exec(String(t||""));)e.add(Lt(o[1]));return[...e]}function MO(t){if(!Be||wo.size===0)return!1;let e=I0(t).filter(o=>o&&!/\.(md|mdx|txt|rst|adoc)$/i.test(o));return e.length===0?!1:e.filter(o=>Ue.existsSync(Ye.resolve(process.cwd(),o))).length===0}function El(t,e){let n=String(e||"").replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?:^|\\n)\\s*(?:[-*]\\s*)?(?:\\*\\*)?${n}\\s*:(?:\\*\\*)?`,"i").test(String(t||""))}function yi(t){let e=String(t||"");return!e.trim()||L0(e)||j0(e)?!1:/\bno safe task found\b/i.test(e)?!0:El(e,"Selected improvement")&&El(e,"Selection rationale")&&El(e,"Files")&&El(e,"Verification plan")}function j0(t){let e=String(t||"");return e.trim()?/(?:^|\n)\s*#{1,6}\s*selected improvement\b/i.test(e)&&/(?:^|\n)\s*#{1,6}\s*selection rationale\b/i.test(e)&&/(?:^|\n)\s*#{1,6}\s*files\b/i.test(e)&&/(?:^|\n)\s*#{1,6}\s*verification plan\b/i.test(e):!1}function NO(t){let e=String(t||"");return e.trim()?/\b(need|must|will|should|let'?s|attempt|going)\b.{0,80}\b(call|issue|use|run|read)\b.{0,80}\b(read_file|tool call|tool_calls?|JSON calls?)\b/i.test(e)||/\b(need|must|will|should|let'?s|attempt|going)\b.{0,80}\b(run|check|use)\b.{0,80}\b(git status|bash|grep|glob|search)\b/i.test(e)||/\{\s*["']tool["']\s*:\s*["'](?:read_file|grep|search_files|glob)["']/i.test(e):!1}function uo(t,e){return Be&&Tt&&(sn>0||Et.size>0)&&t.size===0&&e===0}function D0(t){let e=String(t||"");if(!/\bno safe task found\b/i.test(e)||/\bexample only\b|\bnot applicable\b/i.test(e)||!(/\b(because|reason|blocked|blocker|cannot|can't|unable|failed|unavailable|permission denied|missing|not found|no readable|dirty worktree|wrong branch|merge conflict|precheck blocked|preflight failed|ambiguous|unrelated|manual user work|no safe worthwhile improvement)\b/i.test(e)&&e.trim().length>60))return!1;let o=Ut.size===0||Ri>0;return Vt>=Vl?o:/\b(blocked|blocker|cannot|can't|unable|failed|unavailable|permission denied|missing|not found|no readable|dirty worktree|wrong branch|merge conflict|precheck blocked|preflight failed)\b/i.test(e)&&/\b(because|reason|preflight|worktree|branch|git|permission|missing|unavailable|inspect|read|search)\b/i.test(e)}function pf(t){let e=String(t||"");if(!e.trim()||/\bexample only\b/i.test(e))return!1;let n=/\bpreflight\s*:/i.test(e),o=/\bpreflight output\s*:/i.test(e),s=/\bbranch\s*:/i.test(e),r=/\b(chosen task|selected improvement)\s*:/i.test(e)||/\bno safe task found\b/i.test(e),i=/\bfiles changed\s*:/i.test(e),a=/\bverification\s*:/i.test(e),l=/\bcommit\s*:/i.test(e),c=/\bpush\s*:/i.test(e),u=/\bfinal git status\s*:/i.test(e);return!(n&&o&&s&&r&&i&&a&&l&&c&&u)||Ie?.ran&&(/\bpreflight\s*:\s*(?:not performed|not run|not applicable|unknown)\b/i.test(e)||/\bpreflight output\s*:\s*(?:not performed|not run|not applicable|unknown|\(missing preflight output\))\b/i.test(e)||/\bbranch\s*:\s*(?:not applicable|unknown)\b/i.test(e))?!1:/\bno safe task found\b/i.test(e)?D0(e):!0}function Zl(t){let e=String(t||"");if(!e)return null;let n=[/\bwork\s+(?:from|on)\s+(?:the\s+)?(?:branch\s+)?[`'"]?([A-Za-z0-9._/-]+)[`'"]?\s+only\b/i,/\bwork\s+(?:from|on)\s+(?:the\s+)?[`'"]?([A-Za-z0-9._/-]+)[`'"]?\s+branch\s+only\b/i];for(let o of n){let s=e.match(o);if(!s)continue;let r=String(s[1]||"").trim();if(r)return r}return null}function LO(t){let e=String(t||"").trim();if(!e)return{branch:null,dirty:null,changedFiles:[]};if(/^fatal:/i.test(e))return{branch:null,dirty:null,changedFiles:[]};let n=e.split(`
1031
+ `).map(l=>l.replace(/\r$/,"")),o=n.find(l=>l.startsWith("## "))||n[0]||"",s=o.startsWith("## ")?o.slice(3).trim():o.trim(),r=s?s.split("...")[0].trim().split(/\s+/)[0]:null,i=n.filter(l=>!l.startsWith("## ")&&l.trim()!==""),a=[];for(let l of i){let c=l.match(/^[ MADRCU?!]{1,2}\s+(.*)$/);if(!c)continue;let u=(c[1]||"").trim();if(!u)continue;let d=u.includes(" -> ")?u.split(" -> ").pop():u;d&&a.push(d)}return{branch:r||null,dirty:a.length>0,changedFiles:a}}function IO(t){let e=String(t||"");return!e||!Ai(e)?!1:Zl(e)?!0:/\b(git status|current branch|worktree|dirty|pull\/rebase|rebase|commit|push)\b/i.test(e)}function jO(t,e=2500){let n=String(t??"");return n.trim()?n.length<=e?n:n.slice(0,e)+`
1032
+ ...(truncated ${n.length-e} chars)`:"(no output)"}async function DO(t,e,n){if(Ie?.ran)return Ie;let o=wf||Zl(t),s="git status --short --branch",r="preflight-git-status";Ie={required:!0,ran:!0,ok:!1,command:s,requiredBranch:o,branch:null,dirty:null,changedFiles:[],raw:""};let i="",a=!1;try{let w={role:"assistant",content:"",tool_calls:[{id:r,type:"function",function:{name:"bash",arguments:JSON.stringify({command:s})}}]};n.push(w),e.push(w),ft?.onToolStart&&(ft.onToolStart("bash",{command:s}),a=!0),i=await yf("bash",{command:s},{silent:!0,autoConfirm:!0})}catch(w){i=`ERROR: failed to run preflight: ${w?.message||String(w)}`}let l=String(i??"");if(a&&ft?.onToolEnd){let w=l.length>5e4?l.substring(0,5e4)+`
1033
1033
  ...(truncated ${l.length-5e4} chars)`:l,k=w.split(`
1034
- `)[0]||"",T=k.startsWith("ERROR")||k.includes("CANCELLED")||k.includes("BLOCKED");try{ft.onToolEnd("bash",vi("bash",{command:o},w,T),!T)}catch{}}let c=l.trim(),u=/^\s*##\s+\S+/.test(c),d=LO(l);Ie.branch=d.branch,Ie.dirty=d.dirty,Ie.changedFiles=d.changedFiles,Ie.raw=l;let f={role:"tool",tool_call_id:r,content:l||"(no output)"};n.push(f),e.push(f);let p=jO(l),h=`[PRECHECK] Preflight ran: \`${o}\`.`+(s?` Required branch: ${s}.`:"")+`
1034
+ `)[0]||"",T=k.startsWith("ERROR")||k.includes("CANCELLED")||k.includes("BLOCKED");try{ft.onToolEnd("bash",vi("bash",{command:s},w,T),!T)}catch{}}let c=l.trim(),u=/^\s*##\s+\S+/.test(c),d=LO(l);Ie.branch=d.branch,Ie.dirty=d.dirty,Ie.changedFiles=d.changedFiles,Ie.raw=l;let f={role:"tool",tool_call_id:r,content:l||"(no output)"};n.push(f),e.push(f);let p=jO(l),h=`[PRECHECK] Preflight ran: \`${s}\`.`+(o?` Required branch: ${o}.`:"")+`
1035
1035
 
1036
1036
  ${p}`,g={role:"assistant",content:h};if(n.push(g),e.push(g),!kf)try{ft?.onToken?ft.onToken(h+`
1037
- `):console.log(h)}catch{}return!l||/^ERROR:/i.test(l)||/^fatal:/i.test(l)||!u||d.dirty||s&&(!d.branch||d.branch!==s)?(Ie.ok=!1,Ie):(Ie.ok=!0,Ie)}async function qO(t,e){if(Tt||!Be||Ut.size===0)return;let n=[...Ut].filter(u=>/\.(md|mdx|txt|rst|adoc|tsx?|jsx?)$/i.test(u)).slice(0,4);if(n.length===0)return;Tt=!0;let s="[BACKLOG PREFLIGHT] Reading prompt-named backlog/reference files before planning.",o={role:"assistant",content:s};if(e.push(o),t.push(o),!kf)try{ft?.onToken?ft.onToken(s+`
1038
- `):console.log(s)}catch{}let r=new Map;async function i(u,d,f,{named:p=!1}={}){let h={role:"assistant",content:"",tool_calls:[{id:f,type:"function",function:{name:u,arguments:JSON.stringify(d)}}]};e.push(h),t.push(h);let g="";try{ft?.onToolStart&&ft.onToolStart(u,d),g=await yf(u,d,{silent:!0,autoConfirm:!0})}catch(T){g=`ERROR: failed to read backlog evidence ${d.path||u}: ${T?.message||String(T)}`}let w=String(g||"");if(ft?.onToolEnd){let T=w.split(`
1039
- `)[0]||"",$=/^ERROR:/i.test(T)||T.includes("CANCELLED")||T.includes("BLOCKED");try{ft.onToolEnd(u,vi(u,d,w.slice(0,5e4),$),!$)}catch{}}let k={role:"tool",tool_call_id:f,content:w||"(no output)"};return e.push(k),t.push(k),u==="read_file"&&d.path&&r.set(Lt(d.path),w),Vt++,p&&Ri++,w}for(let u=0;u<n.length;u++){let d=n[u];await i("read_file",{path:d,line_start:1,line_end:140},`bounded-backlog-evidence-${u}`,{named:!0})}if(/\b(current UI|UI\/components|components?|toolbar|palette|inspector|command center|menus?)\b/i.test(Jl)){let u=["components","src","app"].filter(p=>Ue.existsSync(Ye.resolve(process.cwd(),p)));for(let p=0;p<Math.min(u.length,2);p++)await i("list_directory",{path:u[p],max_depth:2},`bounded-backlog-ui-tree-${p}`);let d=["components/NotationToolbar.tsx","components/CommandCenter.tsx","components/EditPalette.tsx","components/Inspector.tsx"].filter(p=>Ue.existsSync(Ye.resolve(process.cwd(),p)));for(let p=0;p<Math.min(d.length,2);p++)wo.add(d[p]),await i("read_file",{path:d[p],line_start:1,line_end:180},`bounded-backlog-ui-evidence-${p}`);let f=[];for(let[p,h]of r.entries()){if(!p.startsWith("components/"))continue;let g=/from\s+['"](?:@\/components\/|\.\/)([A-Za-z][A-Za-z0-9_-]*)['"]/g,w;for(;w=g.exec(h);){let k=`components/${w[1]}.tsx`;Ue.existsSync(Ye.resolve(process.cwd(),k))&&!r.has(k)&&!f.includes(k)&&f.push(k)}}for(let p=0;p<Math.min(f.length,2);p++){let h=f[p];wo.add(h),await i("read_file",{path:h,line_start:1,line_end:180},`bounded-backlog-ui-child-evidence-${p}`)}}let c={role:"user",content:"[BACKLOG PREFLIGHT] The prompt-named backlog/reference files and any requested UI/component evidence above have already been read. Your next response must be the bounded plan labels exactly as requested (`Selected improvement:`, `Selection rationale:`, `Files:`, `Implementation outline:`, `Verification plan:`, `Browser/UI applicability:`). Choose only controls, handlers, labels, and files that are visible in that evidence; do not invent toolbar buttons or src/components paths. Do not request or describe more read_file calls."};e.push(c),t.push(c)}function FO(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 hf(t){return String(t||"").replace(/\\/g,"/").replace(/^\.\//,"").trim()}function xi(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(s=>hf(s)))]:[]}function or(t,e){t===rf?(Ll++,debug&&debug.DEBUG&&process.stdout.write(`\x1B[1A\x1B[2K${e} \u26A0 ${t} (\xD7${Ll})${m.reset}
1037
+ `):console.log(h)}catch{}return!l||/^ERROR:/i.test(l)||/^fatal:/i.test(l)||!u||d.dirty||o&&(!d.branch||d.branch!==o)?(Ie.ok=!1,Ie):(Ie.ok=!0,Ie)}async function qO(t,e){if(Tt||!Be||Ut.size===0)return;let n=[...Ut].filter(u=>/\.(md|mdx|txt|rst|adoc|tsx?|jsx?)$/i.test(u)).slice(0,4);if(n.length===0)return;Tt=!0;let o="[BACKLOG PREFLIGHT] Reading prompt-named backlog/reference files before planning.",s={role:"assistant",content:o};if(e.push(s),t.push(s),!kf)try{ft?.onToken?ft.onToken(o+`
1038
+ `):console.log(o)}catch{}let r=new Map;async function i(u,d,f,{named:p=!1}={}){let h={role:"assistant",content:"",tool_calls:[{id:f,type:"function",function:{name:u,arguments:JSON.stringify(d)}}]};e.push(h),t.push(h);let g="";try{ft?.onToolStart&&ft.onToolStart(u,d),g=await yf(u,d,{silent:!0,autoConfirm:!0})}catch(T){g=`ERROR: failed to read backlog evidence ${d.path||u}: ${T?.message||String(T)}`}let w=String(g||"");if(ft?.onToolEnd){let T=w.split(`
1039
+ `)[0]||"",$=/^ERROR:/i.test(T)||T.includes("CANCELLED")||T.includes("BLOCKED");try{ft.onToolEnd(u,vi(u,d,w.slice(0,5e4),$),!$)}catch{}}let k={role:"tool",tool_call_id:f,content:w||"(no output)"};return e.push(k),t.push(k),u==="read_file"&&d.path&&r.set(Lt(d.path),w),Vt++,p&&Ri++,w}for(let u=0;u<n.length;u++){let d=n[u];await i("read_file",{path:d,line_start:1,line_end:140},`bounded-backlog-evidence-${u}`,{named:!0})}if(/\b(current UI|UI\/components|components?|toolbar|palette|inspector|command center|menus?)\b/i.test(Jl)){let u=["components","src","app"].filter(p=>Ue.existsSync(Ye.resolve(process.cwd(),p)));for(let p=0;p<Math.min(u.length,2);p++)await i("list_directory",{path:u[p],max_depth:2},`bounded-backlog-ui-tree-${p}`);let d=["components/NotationToolbar.tsx","components/CommandCenter.tsx","components/EditPalette.tsx","components/Inspector.tsx"].filter(p=>Ue.existsSync(Ye.resolve(process.cwd(),p)));for(let p=0;p<Math.min(d.length,2);p++)wo.add(d[p]),await i("read_file",{path:d[p],line_start:1,line_end:180},`bounded-backlog-ui-evidence-${p}`);let f=[];for(let[p,h]of r.entries()){if(!p.startsWith("components/"))continue;let g=/from\s+['"](?:@\/components\/|\.\/)([A-Za-z][A-Za-z0-9_-]*)['"]/g,w;for(;w=g.exec(h);){let k=`components/${w[1]}.tsx`;Ue.existsSync(Ye.resolve(process.cwd(),k))&&!r.has(k)&&!f.includes(k)&&f.push(k)}}for(let p=0;p<Math.min(f.length,2);p++){let h=f[p];wo.add(h),await i("read_file",{path:h,line_start:1,line_end:180},`bounded-backlog-ui-child-evidence-${p}`)}}let c={role:"user",content:"[BACKLOG PREFLIGHT] The prompt-named backlog/reference files and any requested UI/component evidence above have already been read. Your next response must be the bounded plan labels exactly as requested (`Selected improvement:`, `Selection rationale:`, `Files:`, `Implementation outline:`, `Verification plan:`, `Browser/UI applicability:`). Choose only controls, handlers, labels, and files that are visible in that evidence; do not invent toolbar buttons or src/components paths. Do not request or describe more read_file calls."};e.push(c),t.push(c)}function FO(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 hf(t){return String(t||"").replace(/\\/g,"/").replace(/^\.\//,"").trim()}function xi(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=>hf(o)))]:[]}function or(t,e){t===rf?(Ll++,debug&&debug.DEBUG&&process.stdout.write(`\x1B[1A\x1B[2K${e} \u26A0 ${t} (\xD7${Ll})${m.reset}
1040
1040
  `)):(rf=t,Ll=1,N(`${e} \u26A0 ${t}${m.reset}`))}var Wl=[];function BO(t){Wl.push(t.trim())}function UO(){return Wl.length===0?null:Wl.splice(0,Wl.length).join(`
1041
1041
  `)}function WO(t){let e=t._startedAt?Math.round((t.finishedAt-t._startedAt)/1e3):null,n=e!==null?`
1042
- Duration: ${e}s`:"",s=typeof t.result.result=="string"?t.result.result.slice(0,4e3):JSON.stringify(t.result.result||"").slice(0,4e3),o=t.result.filesModified&&t.result.filesModified.length>0?`
1042
+ 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?`
1043
1043
  Files modified: ${t.result.filesModified.join(", ")}`:"";return`[BACKGROUND AGENT COMPLETED]
1044
1044
  Job: ${t.jobId}
1045
1045
  Task: "${t.agentDef.task}"`+n+`
1046
- Status: ${t.result.status||"done"}`+o+`
1047
- Result: ${s}`}function Tl(t,e){let{getCompletedJobs:n}=Yo(),s=n();for(let o of s){let r={role:"user",content:WO(o)};t.push(r),e.push(r);let i=o.result?.status||"done",a=i==="failed"?m.red+" \u2717":m.cyan+" \u2713";process.stderr.write(`${a} Background agent ${i}: ${o.agentDef.task.slice(0,50)} \u2014 ${String(o.result?.result||"").slice(0,80)}${m.reset}
1048
- `)}}function q0(t,e){let n=[],s=new Set([...e.keys(),...bi,...wi]);if(!s.size||!t)return n;for(let o of s){let r=o.split("/").pop();if(r&&(t.includes(r)||t.includes(o))){let a=t.split(`
1049
- `).find(l=>l.includes(r)||l.includes(o));n.push({file:o,action:(a||"edit this file").trim().slice(0,200),done:!1})}}return n}function HO(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"]),s=new Set,o=[];for(let r of e){let i=r.toLowerCase();n.has(i)||s.has(i)||(s.add(i),o.push(r))}return o.sort((r,i)=>i.length-r.length),o.slice(0,6)}function GO(){return Ue.existsSync(Ye.join(process.cwd(),"pnpm-lock.yaml"))?"pnpm":Ue.existsSync(Ye.join(process.cwd(),"yarn.lock"))?"yarn":"npm"}function Wn(t){let e=GO();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 _0(t,e,n){let s=[...t||[]].slice(0,6).join(", ")||"recently modified files",o=(e||[]).slice(0,3),r=(n||[]).slice(0,3),i=[`[SYSTEM] You already changed code in: ${s}.`,"Verification is mandatory before further exploration \u2014 do not read other files. STEP 1: read_file the modified file(s) to confirm the edit was applied correctly. Do not trust memory \u2014 verify the actual file content on disk. STEP 2: run the narrowest relevant verification command (lint, test, typecheck)."];return o.length>0&&i.push(`Suggested verification commands: ${o.join(" | ")}`),r.length>0&&i.push(`Likely related tests: ${r.join(", ")}`),i.push('If verification passes: report "Verification passed" and you may continue. If verification fails: fix the issue before any other work.'),i.join(`
1050
- `)}function $0(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)||/\bnode\s+["']?[\w./ -]+\.(?:c?js|mjs)\b/.test(e)}async function F0(t){let e=HO(t);if(e.length===0)return[];let{searchContentIndex:n}=In(),s=[],o=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 l=`${a.file}:${a.name}:${a.line}`;if(!o.has(l)&&(o.add(l),s.push(a),s.length>=5))return s}}catch{}return s}async function B0(t){let e=await F0(t);if(e.length===0)return"";let{getRelatedFiles:n,findSymbolReferences:s}=In(),o=["Likely symbol targets:"];for(let r=0;r<e.length;r++){let i=e[r],a=Math.max(1,i.line-20),l=i.line+40;o.push(`${r+1}. ${i.name} (${i.type}) in ${i.file}:${i.line} -> read_file(path='${i.file}', line_start=${a}, line_end=${l})`);try{let c=await n(i.file,process.cwd(),3);c.length>0&&o.push(` Follow-up files: ${c.join(", ")} (read only if the primary symbol points into one of these modules)`)}catch{}try{let c=await s(i.name,process.cwd(),{excludeFile:i.file,excludeLine:i.line,limit:2});c.length>0&&o.push(` Likely callers/usages: ${c.map(u=>`${u.file}:${u.line}`).join(", ")} (read these next if behavior depends on where ${i.name} is invoked)`)}catch{}}return`${o.join(`
1046
+ Status: ${t.result.status||"done"}`+s+`
1047
+ Result: ${o}`}function Tl(t,e){let{getCompletedJobs:n}=Yo(),o=n();for(let s of o){let r={role:"user",content:WO(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}
1048
+ `)}}function q0(t,e){let n=[],o=new Set([...e.keys(),...bi,...wi]);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(`
1049
+ `).find(l=>l.includes(r)||l.includes(s));n.push({file:s,action:(a||"edit this file").trim().slice(0,200),done:!1})}}return n}function HO(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 GO(){return Ue.existsSync(Ye.join(process.cwd(),"pnpm-lock.yaml"))?"pnpm":Ue.existsSync(Ye.join(process.cwd(),"yarn.lock"))?"yarn":"npm"}function Wn(t){let e=GO();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 _0(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}.`,"Verification is mandatory before further exploration \u2014 do not read other files. STEP 1: read_file the modified file(s) to confirm the edit was applied correctly. Do not trust memory \u2014 verify the actual file content on disk. STEP 2: run the narrowest relevant verification command (lint, test, typecheck)."];return s.length>0&&i.push(`Suggested verification commands: ${s.join(" | ")}`),r.length>0&&i.push(`Likely related tests: ${r.join(", ")}`),i.push('If verification passes: report "Verification passed" and you may continue. If verification fails: fix the issue before any other work.'),i.join(`
1050
+ `)}function $0(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)||/\bnode\s+["']?[\w./ -]+\.(?:c?js|mjs)\b/.test(e)}async function F0(t){let e=HO(t);if(e.length===0)return[];let{searchContentIndex:n}=In(),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 l=`${a.file}:${a.name}:${a.line}`;if(!s.has(l)&&(s.add(l),o.push(a),o.length>=5))return o}}catch{}return o}async function B0(t){let e=await F0(t);if(e.length===0)return"";let{getRelatedFiles:n,findSymbolReferences:o}=In(),s=["Likely symbol targets:"];for(let r=0;r<e.length;r++){let i=e[r],a=Math.max(1,i.line-20),l=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=${l})`);try{let c=await n(i.file,process.cwd(),3);c.length>0&&s.push(` Follow-up files: ${c.join(", ")} (read only if the primary symbol points into one of these modules)`)}catch{}try{let c=await o(i.name,process.cwd(),{excludeFile:i.file,excludeLine:i.line,limit:2});c.length>0&&s.push(` Likely callers/usages: ${c.map(u=>`${u.file}:${u.line}`).join(", ")} (read these next if behavior depends on where ${i.name} is invoked)`)}catch{}}return`${s.join(`
1051
1051
  `)}
1052
1052
  Use these exact targeted reads before broader searching.
1053
1053
 
1054
- `}async function Ci(t){let{getFileIndex:e}=In(),{buildContentIndex:n,findSymbolReferences:s,getRelatedFiles:o}=In(),i=e().filter(c=>/^tests?\//.test(c)||/\.test\./.test(c)||/\.spec\./.test(c));if(i.length===0)return[];let a=new Set,l=await n(process.cwd());for(let c of t||[]){let u=String(c),d=Ye.basename(u).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 o(u,process.cwd(),4);for(let g of h){let w=Ye.basename(g).replace(/\.[^.]+$/,"");if(!(w.length<3)){for(let k of i)if(k.includes(w)&&a.add(k),a.size>=4)return[...a]}}}catch{}let p=(Array.isArray(l.files?.[u]?.defs)?l.files[u].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 s(h,process.cwd(),{excludeFile:u,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 YO(t,e={}){if(!Array.isArray(t)||t.length===0)return[];let n=t.slice(0,4).join(" "),s=[],o=String(e.test||"");return/vitest/.test(o)||Ue.existsSync(Ye.join(process.cwd(),"vitest.config.ts"))||Ue.existsSync(Ye.join(process.cwd(),"vitest.config.js"))?s.push(`npx vitest run ${n}`):(/jest/.test(o)||Ue.existsSync(Ye.join(process.cwd(),"jest.config.js"))||Ue.existsSync(Ye.join(process.cwd(),"jest.config.cjs"))||Ue.existsSync(Ye.join(process.cwd(),"jest.config.mjs")))&&s.push(`npx jest --runInBand ${n}`),(Ue.existsSync(Ye.join(process.cwd(),"pytest.ini"))||Ue.existsSync(Ye.join(process.cwd(),"pyproject.toml")))&&t.some(r=>/\.py$/i.test(r))&&s.push(`pytest ${t.filter(r=>/\.py$/i.test(r)).slice(0,4).join(" ")}`),s}async function rr(t,e,n,s){if(!de)return null;let o=ke;ke=t,Yl=0,An=Jd(t,bo),t==="implement"&&(Es=0,Be&&(sn=0,$i=0,zl=0,Kl=0,mr.clear(),ki.clear())),t==="verify"&&(pr=0,hr=0,Kn=!1,Vn=0),yn=0,bn=!1,Rn=0,wn=0,yo.clear(),Gl.clear(),bf.clear(),_i.clear(),t==="implement"&&(ls=q0(e||"",zn));let r=ls.length>0?`
1054
+ `}async function Ci(t){let{getFileIndex:e}=In(),{buildContentIndex:n,findSymbolReferences:o,getRelatedFiles:s}=In(),i=e().filter(c=>/^tests?\//.test(c)||/\.test\./.test(c)||/\.spec\./.test(c));if(i.length===0)return[];let a=new Set,l=await n(process.cwd());for(let c of t||[]){let u=String(c),d=Ye.basename(u).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(u,process.cwd(),4);for(let g of h){let w=Ye.basename(g).replace(/\.[^.]+$/,"");if(!(w.length<3)){for(let k of i)if(k.includes(w)&&a.add(k),a.size>=4)return[...a]}}}catch{}let p=(Array.isArray(l.files?.[u]?.defs)?l.files[u].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:u,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 YO(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(Ye.join(process.cwd(),"vitest.config.ts"))||Ue.existsSync(Ye.join(process.cwd(),"vitest.config.js"))?o.push(`npx vitest run ${n}`):(/jest/.test(s)||Ue.existsSync(Ye.join(process.cwd(),"jest.config.js"))||Ue.existsSync(Ye.join(process.cwd(),"jest.config.cjs"))||Ue.existsSync(Ye.join(process.cwd(),"jest.config.mjs")))&&o.push(`npx jest --runInBand ${n}`),(Ue.existsSync(Ye.join(process.cwd(),"pytest.ini"))||Ue.existsSync(Ye.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 rr(t,e,n,o){if(!de)return null;let s=ke;ke=t,Yl=0,An=Jd(t,bo),t==="implement"&&(Es=0,Be&&(sn=0,$i=0,zl=0,Kl=0,mr.clear(),ki.clear())),t==="verify"&&(pr=0,hr=0,Kn=!1,Vn=0),yn=0,bn=!1,Rn=0,wn=0,yo.clear(),Gl.clear(),bf.clear(),_i.clear(),t==="implement"&&(ls=q0(e||"",zn));let r=ls.length>0?`
1055
1055
 
1056
1056
  ACTION ITEMS (execute these in order; use one targeted read if code context is needed):
1057
1057
  `+ls.map((l,c)=>`${c+1}. ${l.file} \u2014 ${l.action}`).join(`
1058
- `):"",i=await B0(t==="verify"?s:e||s||""),a;if(t==="implement"){Ti=e?.slice(0,2e3)||"";let l=Be&&wo.size>0?` Known existing UI files from the preflight evidence: ${[...wo].slice(0,4).join(", ")}. If a planned path does not exist, use the closest known existing UI file instead of searching invented src/components paths.`:"",c=Be?`
1058
+ `):"",i=await B0(t==="verify"?o:e||o||""),a;if(t==="implement"){Ti=e?.slice(0,2e3)||"";let l=Be&&wo.size>0?` Known existing UI files from the preflight evidence: ${[...wo].slice(0,4).join(", ")}. If a planned path does not exist, use the closest known existing UI file instead of searching invented src/components paths.`:"",c=Be?`
1059
1059
 
1060
1060
  Bounded backlog implementation guard: preflight and backlog review are already complete. Do not run git status, git log, or re-read the backlog/docs before making progress. Start by reading the concrete implementation file(s) named in the accepted plan with targeted line ranges, then edit one scoped change.`+l:"";a=`[PHASE: IMPLEMENTATION] Analysis complete. Based on the analysis:
1061
1061
  ${Ti}
@@ -1073,11 +1073,11 @@ Prefer these before broader suites when a targeted run is possible.
1073
1073
  1. Read only the modified sections/files and confirm the final code matches intent
1074
1074
  2. Run the smallest relevant verification command(s)
1075
1075
  3. If one check fails, explain the failure precisely and loop back with a focused fix
1076
- 4. Does the implementation address: "${(s||"").slice(0,200)}"?
1076
+ 4. Does the implementation address: "${(o||"").slice(0,200)}"?
1077
1077
  Report PASS (all good) or FAIL (list specific issues).
1078
1078
 
1079
1079
  Files modified: ${l}
1080
- ${i}${d}${f}Summary: ${df}`}return N(`${m.cyan} \u21B3 Phase transition: ${o} \u2192 ${t} (model: ${An||"default"})${m.reset}`),a?{role:"user",content:a}:null}async function Xl(t){let e=[],s=[...t||[]].map(l=>String(l).toLowerCase()),o={};try{let l=Ye.join(process.cwd(),"package.json");if(Ue.existsSync(l)){o=JSON.parse(Ue.readFileSync(l,"utf-8")).scripts||{};let u=[["test",Wn("test")],["lint",Wn("lint")],["typecheck",Wn("typecheck")],["check",Wn("check")],["build",Wn("build")]];for(let[d,f]of u)o[d]&&e.push(f)}}catch{}e.length===0&&(Ue.existsSync(Ye.join(process.cwd(),"package.json"))&&e.push(Wn("test")),(Ue.existsSync(Ye.join(process.cwd(),"pytest.ini"))||Ue.existsSync(Ye.join(process.cwd(),"pyproject.toml")))&&e.push("pytest"));let r=await Ci(t);e.unshift(...YO(r,o));let i=s.some(l=>/\.(ts|tsx)$/.test(l)),a=s.some(l=>/\.(js|jsx|ts|tsx)$/.test(l));return i&&!e.includes(Wn("typecheck"))&&e.push(Wn("typecheck")),a&&!e.includes(Wn("lint"))&&e.push(Wn("lint")),[...new Set(e)].slice(0,4)}function _f(t){let e=process.env.NEX_LANGUAGE;if(e&&e!=="auto")return e;if($f())return"English";let n=String(t||"").trim();if(!n)return"English";let o=n.replace(/```[\s\S]*?```/g," ").replace(/`[^`]*`/g," ").toLowerCase().match(/[a-zäöüß]+/gi)||[],r=new Set(["the","and","or","for","with","without","write","create","explain","refactor","query","function","makefile","dockerfile","healthcheck","preserve","return","input","output","using","should","must","please"]),i=new Set(["der","die","das","und","oder","ist","sind","nicht","bitte","erstelle","schreibe","erkl\xE4re","funktion","abfrage","datei","zur\xFCck","mit","ohne","danke"]),a=0,l=0;for(let c of o)r.has(c)&&a++,i.has(c)&&l++;return l>=3&&l>a*1.4?"German":"English"}function zO(t){let n=String(t||"").replace(/```[\s\S]*?```/g," ").replace(/`[^`]*`/g," ").toLowerCase().match(/[a-zäöüß]+/gi)||[];if(n.length===0)return"English";let s=new Set(["the","and","or","for","with","without","write","create","explain","refactor","query","function","makefile","dockerfile","healthcheck","preserve","return","input","output","using","should","must","please","this","that","it","is","are","as","in"]),o=new Set(["der","die","das","und","oder","ist","sind","nicht","bitte","ich","habe","wir","du","sie","es","diese","dieser","dass","wird","wurde","um","mit","ohne","danke"]),r=0,i=0;for(let a of n)s.has(a)&&r++,o.has(a)&&i++;return i>=3&&i>r*1.4?"German":"English"}function KO(t,e){if(typeof e!="string"||typeof t!="string")return!1;let n=t.toLowerCase(),s=e.toLowerCase(),o=/\b(bash|shell|sh)\b/.test(n)||/\b(one-?liner|pre-commit)\b/.test(n),r=/\b(dockerfile|makefile|cron|crontab|sql)\b/.test(n);if(!o&&!r&&(/```bash\b/.test(s)||/```sh\b/.test(s)))return!0;let i=e.replace(/```[\s\S]*?```/g," ").replace(/`[^`]*`/g," ").toLowerCase();return[/\b(let me|i(?:'|’)ll|i will)\s+(check|search|look)\b/,/\bfirst,\s*let me\b/,/\bsince i (?:do not|don’t|don't) see\b/,/\b(let me|i(?:'|’)ll|i will)\s+(?:run|execute)\b/,/\bsearch(?:ing)?\s+for\b/,/\bcheck if there(?: is| are)\b/].some(a=>a.test(i))}function U0(t){let e=String(t||"").trim();if(!e||e.length>2500)return!1;let n=e.toLowerCase();return/\b(?:repo|repository|project|codebase|existing|current workspace|this workspace)\b/.test(n)||/\b(?:create|write|save)\s+(?:a\s+)?file\b/.test(n)||/\b(?:read|search|inspect|look through|find in|run|install)\b/.test(n)?!1:[/\b(?:reply|respond|answer)\b.*\bexactly\b/i,/\b(?:sql\s+query|select\s+.+\s+from)\b/i,/\b(?:cron(?:\s+expression)?|crontab)\b/i,/\bregex\b.*\b(?:explain|refactor|rewrite|readable)\b/i,/\b(?:small|simple|minimal)?\s*makefile\b/i,/\b(?:small|simple|minimal)?\s*dockerfile\b/i,/\b(?:docker\s+healthcheck|healthcheck)\b/i,/\brefactor\b.*\bcallbacks?\b.*\basync\s*\/\s*await\b/i,/\bcallbacks?\b.*\basync\s*\/\s*await\b/i,/\btypescript\b.*\binterface\b/i,/\b(?:debug|fix)\b.*\bbash\b.*\bscript\b/i,/\bpre-commit\s+hook\b/i,/\bbash\s+one-?liner\b/i,/\bdataclass\b/i,/\bexpress\b.*\broute\b/i,/\beventemitter\b/i,/\b(?:javascript|js|python)\s+function\b/i,/\bfunction\s+\w+\s*\(/i].some(s=>s.test(e))}function VO(t){if(typeof t!="string")return null;let e=t.toLowerCase();return/\bsieve of eratosthenes\b/i.test(t)&&/\bprimes?\b/i.test(t)&&/\bup to n\b/i.test(t)?["```python","from __future__ import annotations","","from typing import List","","","def sieve_of_eratosthenes(n: int) -> List[int]:",' """Return all prime numbers <= n using the Sieve of Eratosthenes.',""," Args:"," n: Upper bound (inclusive).",""," Returns:"," A list of all primes p such that 2 <= p <= n, in ascending order.",' """'," if n < 2:"," return []",""," is_prime = [True] * (n + 1)"," is_prime[0] = False"," is_prime[1] = False",""," p = 2"," while p * p <= n:"," if is_prime[p]:"," for multiple in range(p * p, n + 1, p):"," is_prime[multiple] = False"," p += 1",""," return [i for i in range(2, n + 1) if is_prime[i]]","```"].join(`
1080
+ ${i}${d}${f}Summary: ${df}`}return N(`${m.cyan} \u21B3 Phase transition: ${s} \u2192 ${t} (model: ${An||"default"})${m.reset}`),a?{role:"user",content:a}:null}async function Xl(t){let e=[],o=[...t||[]].map(l=>String(l).toLowerCase()),s={};try{let l=Ye.join(process.cwd(),"package.json");if(Ue.existsSync(l)){s=JSON.parse(Ue.readFileSync(l,"utf-8")).scripts||{};let u=[["test",Wn("test")],["lint",Wn("lint")],["typecheck",Wn("typecheck")],["check",Wn("check")],["build",Wn("build")]];for(let[d,f]of u)s[d]&&e.push(f)}}catch{}e.length===0&&(Ue.existsSync(Ye.join(process.cwd(),"package.json"))&&e.push(Wn("test")),(Ue.existsSync(Ye.join(process.cwd(),"pytest.ini"))||Ue.existsSync(Ye.join(process.cwd(),"pyproject.toml")))&&e.push("pytest"));let r=await Ci(t);e.unshift(...YO(r,s));let i=o.some(l=>/\.(ts|tsx)$/.test(l)),a=o.some(l=>/\.(js|jsx|ts|tsx)$/.test(l));return i&&!e.includes(Wn("typecheck"))&&e.push(Wn("typecheck")),a&&!e.includes(Wn("lint"))&&e.push(Wn("lint")),[...new Set(e)].slice(0,4)}function _f(t){let e=process.env.NEX_LANGUAGE;if(e&&e!=="auto")return e;if($f())return"English";let n=String(t||"").trim();if(!n)return"English";let s=n.replace(/```[\s\S]*?```/g," ").replace(/`[^`]*`/g," ").toLowerCase().match(/[a-zäöüß]+/gi)||[],r=new Set(["the","and","or","for","with","without","write","create","explain","refactor","query","function","makefile","dockerfile","healthcheck","preserve","return","input","output","using","should","must","please"]),i=new Set(["der","die","das","und","oder","ist","sind","nicht","bitte","erstelle","schreibe","erkl\xE4re","funktion","abfrage","datei","zur\xFCck","mit","ohne","danke"]),a=0,l=0;for(let c of s)r.has(c)&&a++,i.has(c)&&l++;return l>=3&&l>a*1.4?"German":"English"}function zO(t){let n=String(t||"").replace(/```[\s\S]*?```/g," ").replace(/`[^`]*`/g," ").toLowerCase().match(/[a-zäöüß]+/gi)||[];if(n.length===0)return"English";let o=new Set(["the","and","or","for","with","without","write","create","explain","refactor","query","function","makefile","dockerfile","healthcheck","preserve","return","input","output","using","should","must","please","this","that","it","is","are","as","in"]),s=new Set(["der","die","das","und","oder","ist","sind","nicht","bitte","ich","habe","wir","du","sie","es","diese","dieser","dass","wird","wurde","um","mit","ohne","danke"]),r=0,i=0;for(let a of n)o.has(a)&&r++,s.has(a)&&i++;return i>=3&&i>r*1.4?"German":"English"}function KO(t,e){if(typeof e!="string"||typeof t!="string")return!1;let n=t.toLowerCase(),o=e.toLowerCase(),s=/\b(bash|shell|sh)\b/.test(n)||/\b(one-?liner|pre-commit)\b/.test(n),r=/\b(dockerfile|makefile|cron|crontab|sql)\b/.test(n);if(!s&&!r&&(/```bash\b/.test(o)||/```sh\b/.test(o)))return!0;let i=e.replace(/```[\s\S]*?```/g," ").replace(/`[^`]*`/g," ").toLowerCase();return[/\b(let me|i(?:'|’)ll|i will)\s+(check|search|look)\b/,/\bfirst,\s*let me\b/,/\bsince i (?:do not|don’t|don't) see\b/,/\b(let me|i(?:'|’)ll|i will)\s+(?:run|execute)\b/,/\bsearch(?:ing)?\s+for\b/,/\bcheck if there(?: is| are)\b/].some(a=>a.test(i))}function U0(t){let e=String(t||"").trim();if(!e||e.length>2500)return!1;let n=e.toLowerCase();return/\b(?:repo|repository|project|codebase|existing|current workspace|this workspace)\b/.test(n)||/\b(?:create|write|save)\s+(?:a\s+)?file\b/.test(n)||/\b(?:read|search|inspect|look through|find in|run|install)\b/.test(n)?!1:[/\b(?:reply|respond|answer)\b.*\bexactly\b/i,/\b(?:sql\s+query|select\s+.+\s+from)\b/i,/\b(?:cron(?:\s+expression)?|crontab)\b/i,/\bregex\b.*\b(?:explain|refactor|rewrite|readable)\b/i,/\b(?:small|simple|minimal)?\s*makefile\b/i,/\b(?:small|simple|minimal)?\s*dockerfile\b/i,/\b(?:docker\s+healthcheck|healthcheck)\b/i,/\brefactor\b.*\bcallbacks?\b.*\basync\s*\/\s*await\b/i,/\bcallbacks?\b.*\basync\s*\/\s*await\b/i,/\btypescript\b.*\binterface\b/i,/\b(?:debug|fix)\b.*\bbash\b.*\bscript\b/i,/\bpre-commit\s+hook\b/i,/\bbash\s+one-?liner\b/i,/\bdataclass\b/i,/\bexpress\b.*\broute\b/i,/\beventemitter\b/i,/\b(?:javascript|js|python)\s+function\b/i,/\bfunction\s+\w+\s*\(/i].some(o=>o.test(e))}function VO(t){if(typeof t!="string")return null;let e=t.toLowerCase();return/\bsieve of eratosthenes\b/i.test(t)&&/\bprimes?\b/i.test(t)&&/\bup to n\b/i.test(t)?["```python","from __future__ import annotations","","from typing import List","","","def sieve_of_eratosthenes(n: int) -> List[int]:",' """Return all prime numbers <= n using the Sieve of Eratosthenes.',""," Args:"," n: Upper bound (inclusive).",""," Returns:"," A list of all primes p such that 2 <= p <= n, in ascending order.",' """'," if n < 2:"," return []",""," is_prime = [True] * (n + 1)"," is_prime[0] = False"," is_prime[1] = False",""," p = 2"," while p * p <= n:"," if is_prime[p]:"," for multiple in range(p * p, n + 1, p):"," is_prime[multiple] = False"," p += 1",""," return [i for i in range(2, n + 1) if is_prime[i]]","```"].join(`
1081
1081
  `):/for\s+f\s+in\s+\$\(\s*ls\s+\*\.txt\s*\)\s*;\s*do/i.test(t)&&/\bfilenames?\s+with\s+spaces\b/i.test(t)?["The problem is word splitting: `$(ls *.txt)` produces whitespace-separated output, so filenames with spaces get split into multiple loop items.","","Use a glob directly (no `ls`, no command substitution) and quote the variable:","","```bash","for f in *.txt; do",' echo "$f"',"done","```","","Why this works:","- `*.txt` is expanded by the shell into one word per matching filename (spaces are preserved as part of the word).",'- Quoting `"$f"` prevents a filename like `My File.txt` from being split again when echoed/used.'].join(`
1082
1082
  `):/\bexplain\b.*\bregex\b/i.test(t)&&/25\[0-5\]/.test(t)&&/2\[0-4\]/.test(t)&&/\[01\]\?/.test(t)&&/\)\\\.\)\{3\}/.test(t)?["This regex validates an IPv4 address in dotted-decimal form (e.g. `192.168.0.1`).","","What it does:","- It matches **four** numeric octets separated by literal dots (`.`).","- Each octet must be in the range **0\u2013255**:"," - `25[0-5]` \u2192 250\u2013255"," - `2[0-4][0-9]` \u2192 200\u2013249"," - `[01]?[0-9][0-9]?` \u2192 0\u2013199 (allows 1\u20133 digits, including leading zeros like `001`)","- `^` and `$` anchor the match to the entire string (no extra characters).","","A more readable rewrite (same logic), using a reusable `octet` subpattern:","","```js","const octet = '(?:25[0-5]|2[0-4]\\\\d|[01]?\\\\d\\\\d?)';","const ipv4Regex = new RegExp(`^(?:${octet}\\\\.){3}${octet}$`);","```"].join(`
1083
1083
  `):/\brefactor\b.*\bcallbacks?\b.*\basync\s*\/\s*await\b/i.test(t)&&/fs\.readFile\(\s*["']a\.txt["']/.test(t)&&/fs\.writeFile\(\s*["']b\.txt["']/.test(t)?["```js","const { readFile, writeFile } = require('fs/promises');","","(async () => {"," const data = await readFile('a.txt');"," await writeFile('b.txt', data);"," console.log('done');",""," // If you need a specific encoding, use: await readFile('a.txt', 'utf8')","})().catch((err) => {"," // Closest to `if (err) throw err;` from the callback version."," console.error(err);"," process.exitCode = 1;","});","```","","This keeps the same control flow, but uses `fs/promises` so the operations can be awaited instead of nested callbacks."].join(`
@@ -1092,9 +1092,9 @@ ${i}${d}${f}Summary: ${df}`}return N(`${m.cyan} \u21B3 Phase transition: ${o} \
1092
1092
  `):/\bcron expressions?\b/i.test(t)&&/every\s+weekday/i.test(t)&&/first\s+day\s+of\s+each\s+month/i.test(t)&&/every\s+15\s+minutes/i.test(t)?["(1) Every weekday at 9:30 AM:","```cron","30 9 * * 1-5","```","Runs at minute 30, hour 9, Monday\u2013Friday.","","(2) First day of each month at midnight:","```cron","0 0 1 * *","```","Runs at 00:00 on day 1 of every month.","","(3) Every 15 minutes between 8\u201318h on weekdays:","```cron","*/15 8-18 * * 1-5","```","Runs every 15 minutes during hours 08 through 18 (inclusive), Monday\u2013Friday."].join(`
1093
1093
  `):/\bflatten(deep)?\b/i.test(t)&&/\biterative\b/i.test(t)&&/\brecursive\b/i.test(t)?["Recursive version:","```js","function flattenDeep(arr) {"," const result = [];"," for (const item of arr) {"," if (Array.isArray(item)) result.push(...flattenDeep(item));"," else result.push(item);"," }"," return result;","}","```","","Iterative version (preserves left-to-right order, does not mutate input):","```js","function flattenDeepIterative(arr) {"," const result = [];"," const stack = [{ array: arr, index: 0 }];",""," while (stack.length > 0) {"," const frame = stack[stack.length - 1];"," if (frame.index >= frame.array.length) {"," stack.pop();"," continue;"," }"," const value = frame.array[frame.index++];"," if (Array.isArray(value)) {"," stack.push({ array: value, index: 0 });"," } else {"," result.push(value);"," }"," }",""," return result;","}","```"].join(`
1094
1094
  `):/\bpre-commit\s+hook\b/.test(e)&&/console\.log/.test(t)&&/\.js\b/.test(e)?["```bash","#!/usr/bin/env bash","","# Block commits that contain console.log() in staged .js files.","","# Only inspect staged content (the commit snapshot), not the working tree.","# NOTE: Do NOT use `set -e` in hooks: grep returns 1 on no match.","","# If no staged JS files, allow the commit.",'if ! git diff --cached --name-only --diff-filter=ACMR -- "*.js" | grep -q .; then'," exit 0","fi","","# Scan staged file contents so existing console.log() also blocks the commit.","while IFS= read -r -d '' file; do",' if git show ":$file" | grep -Eq "(^|[^[:alnum:]_])console\\\\.log[[:space:]]*\\\\("; then',' echo "ERROR: console.log() found in staged JavaScript file: $file"',' echo "Remove it (use proper logging) before committing."'," exit 1"," fi",'done < <(git diff --cached --name-only -z --diff-filter=ACMR -- "*.js")',"","exit 0","```","","Why: `console.log()` is usually temporary debug output. Blocking it at commit time keeps debug noise out of the codebase and prevents accidental logs in production.","","Install: save this as `.git/hooks/pre-commit` and run `chmod +x .git/hooks/pre-commit`."].join(`
1095
- `):null}function XO(){let t=process.env.NEX_LANGUAGE,e=process.env.NEX_CODE_LANGUAGE,n=process.env.NEX_COMMIT_LANGUAGE,s=$f(),o=!t||t==="auto"?null:t,r=[`# Language Rules (CRITICAL \u2014 enforce strictly)
1096
- `];s?r.push("RESPONSE LANGUAGE: This project requires English. Always respond in English, even if the user writes in another language."):o?r.push(`RESPONSE LANGUAGE: You MUST always respond in ${o}. 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. ${o} 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"),_n()?r.push(" \u2022 FILE CREATION TASKS (Makefile, Dockerfile, config files, documentation): create or edit files only when the user explicitly asks for files or the existing workflow clearly requires files. For self-contained snippet requests, answer in text only."):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 Iterative deep flatten must preserve left-to-right order and must not mutate the caller's input. Initialize the stack with a shallow copy such as input.slice(), pop values, push child array contents onto the stack in their existing order, collect scalar values with push(), then reverse the result once at the end."),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. In Alpine or minimal images, do not assume wget or curl exists unless the Dockerfile installs it; either install the tool explicitly or use a dependency-free command such as "node -e" when Node is present.'),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}.`),o&&r.push(`
1097
- This is a hard requirement. Always respond in ${o}. 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 ${o}.`),r.join(`
1095
+ `):null}function XO(){let t=process.env.NEX_LANGUAGE,e=process.env.NEX_CODE_LANGUAGE,n=process.env.NEX_COMMIT_LANGUAGE,o=$f(),s=!t||t==="auto"?null:t,r=[`# Language Rules (CRITICAL \u2014 enforce strictly)
1096
+ `];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"),_n()?r.push(" \u2022 FILE CREATION TASKS (Makefile, Dockerfile, config files, documentation): create or edit files only when the user explicitly asks for files or the existing workflow clearly requires files. For self-contained snippet requests, answer in text only."):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 Iterative deep flatten must preserve left-to-right order and must not mutate the caller's input. Initialize the stack with a shallow copy such as input.slice(), pop values, push child array contents onto the stack in their existing order, collect scalar values with push(), then reverse the result once at the end."),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. In Alpine or minimal images, do not assume wget or curl exists unless the Dockerfile installs it; either install the tool explicitly or use a dependency-free command such as "node -e" when Node is present.'),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(`
1097
+ 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(`
1098
1098
  `)+`
1099
1099
 
1100
1100
  `}function JO(t){let e=_f(t);return $f()?`# Current Turn Language (CRITICAL \u2014 enforce strictly)
@@ -1103,13 +1103,13 @@ This repository is English-only. You MUST answer this turn in English, even if t
1103
1103
  `:`# Current Turn Language (CRITICAL \u2014 enforce strictly)
1104
1104
  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.
1105
1105
 
1106
- `}function ZO(){if(ar!==null)return ar;try{let e=XA().flatMap(o=>o.models.map(r=>({spec:`${o.name}:${r.id}`,tier:VA(r.id,o.name),name:r.name})));if(e.length<2)return ar="","";let n={full:"complex tasks (refactor, implement, generate)",standard:"regular tasks (edit, fix, analyze)",essential:"simple tasks (read, search, list)"},s=`
1106
+ `}function ZO(){if(ar!==null)return ar;try{let e=XA().flatMap(s=>s.models.map(r=>({spec:`${s.name}:${r.id}`,tier:VA(r.id,s.name),name:r.name})));if(e.length<2)return ar="","";let n={full:"complex tasks (refactor, implement, generate)",standard:"regular tasks (edit, fix, analyze)",essential:"simple tasks (read, search, list)"},o=`
1107
1107
  # Sub-Agent Model Routing
1108
1108
 
1109
- `;s+='Sub-agents auto-select models by task complexity. Override with `model: "provider:model"` in agent definition.\n\n',s+=`| Model | Tier | Auto-assigned for |
1109
+ `;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 |
1110
1110
  |---|---|---|
1111
- `;for(let o of e)s+=`| ${o.spec} | ${o.tier} | ${n[o.tier]||o.tier} |
1112
- `;return ar=s,s}catch(t){return process.env.NEX_DEBUG&&console.error("[agent] model routing guide failed:",t.message),ar="",""}}var mf="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->";function QO(t){let e=t.indexOf(mf);return e===-1?{dynamic:t,static:""}:{dynamic:t.slice(0,e).trimEnd(),static:t.slice(e+mf.length).trimStart()}}async function gf(){let t=await A0()+":"+Cn();if(di!==null&&t===tf)return di;let e=await pA(process.cwd()),n=TA(),s=HA(),o=go()?LA():"",r=XO(),i=RA(),a=ZA(Cn());return di=`${a?`## Model Briefing
1111
+ `;for(let s of e)o+=`| ${s.spec} | ${s.tier} | ${n[s.tier]||s.tier} |
1112
+ `;return ar=o,o}catch(t){return process.env.NEX_DEBUG&&console.error("[agent] model routing guide failed:",t.message),ar="",""}}var mf="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->";function QO(t){let e=t.indexOf(mf);return e===-1?{dynamic:t,static:""}:{dynamic:t.slice(0,e).trimEnd(),static:t.slice(e+mf.length).trimStart()}}async function gf(){let t=await A0()+":"+Cn();if(di!==null&&t===tf)return di;let e=await pA(process.cwd()),n=TA(),o=HA(),s=go()?LA():"",r=XO(),i=RA(),a=ZA(Cn());return di=`${a?`## Model Briefing
1113
1113
  ${a}
1114
1114
 
1115
1115
  ---
@@ -1122,10 +1122,10 @@ PROJECT CONTEXT:
1122
1122
  ${e}
1123
1123
  ${n?`
1124
1124
  ${n}
1125
- `:""}${s?`
1126
- ${s}
1127
1125
  `:""}${o?`
1128
1126
  ${o}
1127
+ `:""}${s?`
1128
+ ${s}
1129
1129
  `:""}
1130
1130
  ${r?`${r}
1131
1131
  `:""}${i?`${i}
@@ -1568,20 +1568,20 @@ class ErrorBoundary extends React.Component {
1568
1568
  - Use migrations for schema changes, never manual ALTER TABLE
1569
1569
  - Add database-level constraints (unique, foreign key, check) not just app-level
1570
1570
 
1571
- `,tf=t,di}function W0(){bf.clear(),P0.clear(),Pl.clear(),bi.clear(),M0.clear(),Ml.clear(),wi.clear(),zn.clear(),as.clear(),_i.clear(),Et.clear(),yo.clear(),Gl.clear(),of.clear(),mn=0,pi=0,Nl=0,tn=!1,Il=0,fo=-1,af=!1,jl=0,Dl=!1,yn=0,bn=!1,Rn=0,wn=0,Pt=!1,zt="",hi=0,ql="",po=0,Fl="",ho=0,gn=!1,lf=!1,ke="plan",Yl=0,de=!1,An=null,Ti=null,df=null,ls=[],ur=0,pr=0,hr=0,Es=0,Kn=!1,Vn=0,Ts=0,fr=null,bo=null,Be=!1,Vt=0,Ri=0,Ut.clear(),Tt=!1,Jl="",Ul=!1,Hn=0,sn=0,$i=0,zl=0,Kl=0,mr.clear(),ki.clear(),Si.clear(),Ei.clear(),Ie=null,nn=!1,wf=null,cf=!1,uf=!1,Bl=!1,Ss="",mo="",gi="",rf="",Ll=0}function eP(){x=[],mi=null,lr="",cr=0,nf="",sf=0,W0();try{let{resetCompactionFailures:t}=Ku();t()}catch{}try{let{cancelAllJobs:t}=Yo();t()}catch{}}function tP(){x.length>m0&&x.splice(0,x.length-m0)}function $f(){try{let t=require("fs"),n=require("path").join(process.cwd(),"AGENTS.md");if(!t.existsSync(n))return!1;let s=t.readFileSync(n,"utf8");return/all.*english/i.test(s)&&/no german/i.test(s)}catch{return!1}}function Xd(t,e,n,s=1500){return!t||!e?!1:t===e&&Date.now()-n<s}function nP(){return x.length}function sP(){return x}function oP(t){x=t}async function rP(){let{execFile:t}=require("child_process"),e=require("fs"),n=process.cwd(),s=(d,f)=>new Promise(p=>{t(d,f,{cwd:n,timeout:3e3},(h,g)=>{p(h?"":(g||"").trim())})}),[o]=await Promise.all([s("find",[".","-type","f","-not","-path","*/node_modules/*","-not","-path","*/.git/*","-not","-path","*/dist/*","-not","-path","*/.next/*","-not","-path","*/build/*","-not","-path","*/__pycache__/*","-not","-path","*/vendor/*"])]),r=new Set(["js","ts","jsx","tsx","py","go","rs","rb","java","cpp","c","cs"]),i=(o?o.split(`
1571
+ `,tf=t,di}function W0(){bf.clear(),P0.clear(),Pl.clear(),bi.clear(),M0.clear(),Ml.clear(),wi.clear(),zn.clear(),as.clear(),_i.clear(),Et.clear(),yo.clear(),Gl.clear(),of.clear(),mn=0,pi=0,Nl=0,tn=!1,Il=0,fo=-1,af=!1,jl=0,Dl=!1,yn=0,bn=!1,Rn=0,wn=0,Pt=!1,zt="",hi=0,ql="",po=0,Fl="",ho=0,gn=!1,lf=!1,ke="plan",Yl=0,de=!1,An=null,Ti=null,df=null,ls=[],ur=0,pr=0,hr=0,Es=0,Kn=!1,Vn=0,Ts=0,fr=null,bo=null,Be=!1,Vt=0,Ri=0,Ut.clear(),Tt=!1,Jl="",Ul=!1,Hn=0,sn=0,$i=0,zl=0,Kl=0,mr.clear(),ki.clear(),Si.clear(),Ei.clear(),Ie=null,nn=!1,wf=null,cf=!1,uf=!1,Bl=!1,Ss="",mo="",gi="",rf="",Ll=0}function eP(){x=[],mi=null,lr="",cr=0,nf="",sf=0,W0();try{let{resetCompactionFailures:t}=Ku();t()}catch{}try{let{cancelAllJobs:t}=Yo();t()}catch{}}function tP(){x.length>m0&&x.splice(0,x.length-m0)}function $f(){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 Xd(t,e,n,o=1500){return!t||!e?!1:t===e&&Date.now()-n<o}function nP(){return x.length}function sP(){return x}function oP(t){x=t}async function rP(){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(`
1572
1572
  `):[]).filter(d=>{let f=d.split(".").pop();return r.has(f)});if(i.length<3)return null;let a={};for(let d of i){let f=d.split(".").pop();a[f]=(a[f]||0)+1}let c=` \u{1F4C1} ${Object.entries(a).sort((d,f)=>f[1]-d[1]).slice(0,4).map(([d,f])=>`${f} .${d}`).join(" \xB7 ")}`,u=Ye.join(n,"package.json");if(e.existsSync(u))try{let d=JSON.parse(e.readFileSync(u,"utf-8")),f=Object.keys({...d.dependencies||{},...d.devDependencies||{}});if(f.length>0){let p=f.slice(0,5).join(" \xB7 "),h=f.length>5?` +${f.length-5}`:"";c+=`
1573
- \u{1F4E6} ${p}${h}`}}catch{}return c}function iP(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 De(t,e,n,s,o,{suppressHint:r=!1}={}){if(t<1)return;let i=[...e.values()].reduce((c,u)=>c+u,0),a=`\u2500\u2500 ${t} ${t===1?"step":"steps"} \xB7 ${i} ${i===1?"tool":"tools"}`,l=0;if(o){let c=Date.now()-o;l=Math.round(c/1e3),a+=l>=60?` \xB7 ${Math.floor(l/60)}m ${l%60}s`:` \xB7 ${l}s`}n.size>0&&(a+=` \xB7 ${n.size} ${n.size===1?"file":"files"} modified`),a+=" \u2500\u2500",console.log(`
1574
- ${m.dim} ${a}${m.reset}`);try{let{getActiveProviderName:c,getActiveModelId:u}=vt(),d=c(),f=u(),p=typeof a0=="function"?a0(d).label:"cost unknown",h=typeof i0=="function"?i0():null;if(d&&f&&h){let g=h.totalCost>0?`$${h.totalCost.toFixed(4)}`:"free";console.log(`${m.dim} model ${d}:${f} \xB7 ${p} \xB7 ${h.totalInput.toLocaleString()} in / ${h.totalOutput.toLocaleString()} out \xB7 ${g}${m.reset}`)}}catch{}if(l>=30&&process.stdout.isTTY){let c=n.size>0?`Done \u2014 ${n.size} ${n.size===1?"file":"files"} modified in ${l}s`:`Done \u2014 ${t} ${t===1?"step":"steps"} in ${l}s`;iP(c)}if(Ei.size>0&&Si.size>0)for(let c of Ei){let u=Si.get(c);u&&console.log(`${m.dim} \u2714 task #${c} auto-matched: ${u.slice(0,60)}${m.reset}`)}n.size>0?console.log(`${m.dim} \u{1F4A1} /diff \xB7 /commit \xB7 /undo${m.reset}`):!r&&s.size>=5&&n.size===0&&t>=3?console.log(`${m.dim} \u{1F4A1} Found issues? Say "fix 1" or "apply all fixes"${m.reset}`):s.size>0&&t>=2&&console.log(`${m.dim} \u{1F4A1} /save \xB7 /clear${m.reset}`)}async function aP(){if(!process.stdout.isTTY)return{action:"quit"};let t=Yn(),e=Cn(),n=Hl.fast?.[t],s=Hl.strong?.[t],o=n&&n!==e,r=s&&s!==e&&s!==n,i=[];i.push({key:"r",label:`Retry with current model ${m.dim}(${e})${m.reset}`}),o&&i.push({key:"f",label:`Switch to ${m.bold}${n}${m.reset} ${m.dim}\u2014 fast, low latency${m.reset}`,model:n}),r&&i.push({key:"s",label:`Switch to ${m.bold}${s}${m.reset} ${m.dim}\u2014 reliable tool-calling, medium speed${m.reset}`,model:s}),i.push({key:"q",label:`${m.dim}Quit${m.reset}`}),console.log(),console.log(`${m.yellow} Stream stale \u2014 all retries exhausted.${m.reset} What would you like to do?`);for(let a of i)console.log(` ${m.cyan}[${a.key}]${m.reset} ${a.label}`);return process.stdout.write(` ${m.yellow}> ${m.reset}`),new Promise(a=>{let l=process.stdin,c=l.isRaw;l.setRawMode(!0),l.resume(),l.setEncoding("utf8");let u=!1,d=f=>{if(u)return;u=!0,l.removeListener("data",d),l.setRawMode(c||!1),l.pause();let p=f.toLowerCase().trim();if(process.stdout.write(`${p}
1575
- `),f==="")return a({action:"quit"});let h=i.find(g=>g.key===p);!h||h.key==="q"||!h.model&&h.key!=="r"?a({action:"quit"}):h.key==="r"?a({action:"retry"}):a({action:"switch",model:h.model,provider:t})};l.on("data",d)})}function lP(t){let e=/https?:\/\/[^\s/]+(\/[^\s?#]+)/g,n=new Set,s;for(;(s=e.exec(t))!==null;){let o=s[1].replace(/\/$/,"");o.length>1&&o.split("/").filter(i=>i.length>2).forEach(i=>n.add(i))}return Array.from(n)}function cP(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 ft=null,kf=!1;async function uP(t,e=null,n={}){let s=JA(Cn());h0=s.staleWarn,Yd=s.staleAbort,ft=e,kf=!!n.silent;let o=t;mi&&typeof t=="string"&&(o=`${mi}
1573
+ \u{1F4E6} ${p}${h}`}}catch{}return c}function iP(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 De(t,e,n,o,s,{suppressHint:r=!1}={}){if(t<1)return;let i=[...e.values()].reduce((c,u)=>c+u,0),a=`\u2500\u2500 ${t} ${t===1?"step":"steps"} \xB7 ${i} ${i===1?"tool":"tools"}`,l=0;if(s){let c=Date.now()-s;l=Math.round(c/1e3),a+=l>=60?` \xB7 ${Math.floor(l/60)}m ${l%60}s`:` \xB7 ${l}s`}n.size>0&&(a+=` \xB7 ${n.size} ${n.size===1?"file":"files"} modified`),a+=" \u2500\u2500",console.log(`
1574
+ ${m.dim} ${a}${m.reset}`);try{let{getActiveProviderName:c,getActiveModelId:u}=vt(),d=c(),f=u(),p=typeof a0=="function"?a0(d).label:"cost unknown",h=typeof i0=="function"?i0():null;if(d&&f&&h){let g=h.totalCost>0?`$${h.totalCost.toFixed(4)}`:"free";console.log(`${m.dim} model ${d}:${f} \xB7 ${p} \xB7 ${h.totalInput.toLocaleString()} in / ${h.totalOutput.toLocaleString()} out \xB7 ${g}${m.reset}`)}}catch{}if(l>=30&&process.stdout.isTTY){let c=n.size>0?`Done \u2014 ${n.size} ${n.size===1?"file":"files"} modified in ${l}s`:`Done \u2014 ${t} ${t===1?"step":"steps"} in ${l}s`;iP(c)}if(Ei.size>0&&Si.size>0)for(let c of Ei){let u=Si.get(c);u&&console.log(`${m.dim} \u2714 task #${c} auto-matched: ${u.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 aP(){if(!process.stdout.isTTY)return{action:"quit"};let t=Yn(),e=Cn(),n=Hl.fast?.[t],o=Hl.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 l=process.stdin,c=l.isRaw;l.setRawMode(!0),l.resume(),l.setEncoding("utf8");let u=!1,d=f=>{if(u)return;u=!0,l.removeListener("data",d),l.setRawMode(c||!1),l.pause();let p=f.toLowerCase().trim();if(process.stdout.write(`${p}
1575
+ `),f==="")return a({action:"quit"});let h=i.find(g=>g.key===p);!h||h.key==="q"||!h.model&&h.key!=="r"?a({action:"quit"}):h.key==="r"?a({action:"retry"}):a({action:"switch",model:h.model,provider:t})};l.on("data",d)})}function lP(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 cP(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 ft=null,kf=!1;async function uP(t,e=null,n={}){let o=JA(Cn());h0=o.staleWarn,Yd=o.staleAbort,ft=e,kf=!!n.silent;let s=t;mi&&typeof t=="string"&&(s=`${mi}
1576
1576
 
1577
- ${t}`,mi=null);let r=typeof o=="string"?AO(o):null;if(r){let ce=null;try{ce=Ue.realpathSync(process.cwd())}catch{ce=Ye.resolve(process.cwd())}ce!==r&&(process.chdir(r),Ol())}if(typeof o=="string"){let ce=lP(o),_e=cP(o);(ce.length>0||_e.length>0)&&(o+=`
1577
+ ${t}`,mi=null);let r=typeof s=="string"?AO(s):null;if(r){let ce=null;try{ce=Ue.realpathSync(process.cwd())}catch{ce=Ye.resolve(process.cwd())}ce!==r&&(process.chdir(r),Ol())}if(typeof s=="string"){let ce=lP(s),_e=cP(s);(ce.length>0||_e.length>0)&&(s+=`
1578
1578
 
1579
1579
  [System Note for Assistant: To resolve this task faster, consider these hints:
1580
- `,ce.length>0&&(o+=`- The user mentioned URLs containing the paths/folders: ${ce.join(", ")}. Prioritize searching these folder names using glob or grep first.
1581
- `),_e.length>0&&_e.forEach(Le=>{o+=`- ${Le}
1582
- `}),o+="Always prefer parallel search execution if unsure.]")}typeof o=="string"&&R0(o)&&(o+=`
1580
+ `,ce.length>0&&(s+=`- The user mentioned URLs containing the paths/folders: ${ce.join(", ")}. Prioritize searching these folder names using glob or grep first.
1581
+ `),_e.length>0&&_e.forEach(Le=>{s+=`- ${Le}
1582
+ `}),s+="Always prefer parallel search execution if unsure.]")}typeof s=="string"&&R0(s)&&(s+=`
1583
1583
 
1584
- [Note for assistant: the user appears frustrated \u2014 acknowledge their concern briefly and empathetically before proceeding]`);let i=typeof t=="string"?n0(t):null,a=typeof t=="string"&&U0(t),l=typeof t=="string"?_f(t):"English",c=T0(o);if(c&&typeof c.then=="function"&&(c=await c),x.push({role:"user",content:c}),tP(),a){let ce=VO(t);if(ce){let _e={role:"assistant",content:ce};return x.push(_e),we(x),Qe(x),console.log(ce),{success:!0,deterministic:!0,content:ce}}}let u=go(),d=n.autoOrchestrate!==!1&&process.env.NEX_AUTO_ORCHESTRATE!=="false"&&!u,f=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10),p=typeof c=="string"?c:typeof t=="string"?t:"";if(Ai(p)&&(uf=!0),IO(p)){nn=!0;let ce=Zl(p);ce&&(wf=ce)}let w=nn,k=uf;try{let{detectComplexPrompt:ce,runOrchestrated:_e}=e0(),Le=ce(typeof t=="string"?t:"");if(!d&&u&&Le.isComplex&&console.log(`${m.dim}Plan mode active: auto-orchestrate disabled until /plan approve${m.reset}`),!k&&H0(d,Le,f,u)){console.log(`${m.yellow}\u26A1 Auto-orchestrate: ${Le.estimatedGoals} goals \u2192 parallel agents${m.reset}`);let Re=await _e(t,{orchestratorModel:n.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL,workerModel:n.model});if(Re&&Re.synthesis){let xe=Re.synthesis.summary||"",an=Re.synthesis.filesChanged?.length?`
1584
+ [Note for assistant: the user appears frustrated \u2014 acknowledge their concern briefly and empathetically before proceeding]`);let i=typeof t=="string"?n0(t):null,a=typeof t=="string"&&U0(t),l=typeof t=="string"?_f(t):"English",c=T0(s);if(c&&typeof c.then=="function"&&(c=await c),x.push({role:"user",content:c}),tP(),a){let ce=VO(t);if(ce){let _e={role:"assistant",content:ce};return x.push(_e),we(x),Qe(x),console.log(ce),{success:!0,deterministic:!0,content:ce}}}let u=go(),d=n.autoOrchestrate!==!1&&process.env.NEX_AUTO_ORCHESTRATE!=="false"&&!u,f=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10),p=typeof c=="string"?c:typeof t=="string"?t:"";if(Ai(p)&&(uf=!0),IO(p)){nn=!0;let ce=Zl(p);ce&&(wf=ce)}let w=nn,k=uf;try{let{detectComplexPrompt:ce,runOrchestrated:_e}=e0(),Le=ce(typeof t=="string"?t:"");if(!d&&u&&Le.isComplex&&console.log(`${m.dim}Plan mode active: auto-orchestrate disabled until /plan approve${m.reset}`),!k&&H0(d,Le,f,u)){console.log(`${m.yellow}\u26A1 Auto-orchestrate: ${Le.estimatedGoals} goals \u2192 parallel agents${m.reset}`);let Re=await _e(t,{orchestratorModel:n.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL,workerModel:n.model});if(Re&&Re.synthesis){let xe=Re.synthesis.summary||"",an=Re.synthesis.filesChanged?.length?`
1585
1585
 
1586
1586
  Files changed: ${Re.synthesis.filesChanged.join(", ")}`:"",Je=Re.synthesis.conflicts?.length?`
1587
1587
 
@@ -1605,7 +1605,7 @@ The user linked a live app URL (${i.url}) and described broken behavior. Treat t
1605
1605
  [END EXAMPLE \u2014 wait for the real user request below]`},..._.slice(1)])}if(Tn(_,Ee).percentage>=65){let{messages:_e,tokensRemoved:Le}=Bn(_,Ee);Le>0&&(_=_e,console.log(`${m.dim} [pre-flight compress \u2014 ${Le} tokens freed, now ${Math.round(Tn(_,Ee).percentage)}% used]${m.reset}`))}let H=0,se=0,ee=0,P=0,he=0,Xe=9,$e=0,tt=new Set,rn=(()=>{let ce=x.find(_e=>_e.role==="user");return typeof ce?.content=="string"?ce.content:""})(),$n=typeof rn=="string"?n0(rn):null,Nf=xi(rn),Lf=/set_reminder|google.?auth|cron:|api\.log|swarm.{0,30}(agent|crash|fail)|agent.{0,30}(crashed|crash|fail)|server.{0,30}(error|crash|problem)|on.server/i.test(rn)||!!$n?.shouldPreferSsh,u_=!!$n,Mi=0;if(!Pt){let ce=x.filter(Le=>Le.role==="user"||Le.role==="tool").map(Le=>typeof Le.content=="string"?Le.content:"").join(`
1606
1606
  `),_e=Kd(ce);_e&&(Pt=!0,zt=_e.slice(0,120),N(`${m.yellow} \u26A1 Root cause in briefing: ${zt} \u2014 fix phase active from start (read budget: 3)${m.reset}`))}!Pt&&!gn&&/\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(rn)&&(gn=!0,N(`${m.cyan} \u26A1 Creation task detected \u2014 tight investigation cap (4 pre-edit, 2 post-edit)${m.reset}`));let Cs=p||rn;if(!n.skipPhaseRouting&&!FO(Cs)&&(x.length<=1||k&&!de)&&(de=k?!0:xA(),de)){bo=kA(Cs)?.id||"coding";let _e=ff(Cs);if(ke=_e?"implement":"plan",An=Jd(ke,bo),Yl=0,ur=0,Ts=0,fr=null,Be=ke==="plan"&&N0(Cs),Vt=0,Ri=0,Ut.clear(),wo.clear(),Tt=!1,Jl=Be?Cs:"",Be)for(let Re of xi(Cs))Ut.add(Lt(Re));Ul=!1,Hn=0,vs.clear(),process.stdout.isTTY&&console.log(_e?`${m.dim} \u21B3 Phase routing: implement(${An||"default"}) \u2192 verify ${m.yellow}[plan skipped: direct file task]${m.reset}`:`${m.dim} \u21B3 Phase routing: plan(${An||"default"}) \u2192 implement \u2192 verify${m.reset}`),N(_e?`${m.cyan} \u26A1 Phase routing enabled \u2014 skipping plan phase for direct file task, starting in implement with ${An||"default model"} (category: ${bo})${m.reset}`:`${m.cyan} \u26A1 Phase routing enabled \u2014 plan phase with ${An||"default model"} (category: ${bo})${m.reset}`);let Le=xi(Cs);if(_e&&Le.length>0){let xe={role:"user",content:`[SYSTEM] This is a direct file task targeting: ${Le.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.`};x.push(xe),_.push(xe)}if(Be){let Re={role:"user",content:Gn()};x.push(Re),_.push(Re)}}if(nn){Ie=null;let ce=await DO(p,_,x);if(!ce.ok){let _e=ce.requiredBranch,Le=ce.branch?`Current branch: ${ce.branch}. `:"",Re=_e?`Required branch: ${_e}. `:"",xe=ce.dirty===!0?`Worktree is dirty (${ce.changedFiles.length} changed file${ce.changedFiles.length===1?"":"s"}). `:"",Je="[PRECHECK BLOCKED] This prompt contains explicit git/worktree safety gates. I ran `git status --short --branch` as preflight and will not proceed until it's safe.\n\n"+`${!ce.raw||/^ERROR:/i.test(ce.raw)||/^fatal:/i.test(ce.raw)?"Git preflight failed (no usable status output). ":""}${Le}${Re}${xe}`.trim()+`
1607
1607
 
1608
- Next step: make the worktree clean and be on the required branch, then re-run the automation.`,dt={role:"assistant",content:Je};x.push(dt),we(x),Qe(x),console.log(Je);return}if(!cf){let _e={role:"user",content:"[SYSTEM] This is a gated automation workflow. In your final summary, use these exact labels (one per line): Preflight:, Preflight output:, Branch:, Chosen task: (or Selected improvement: / no safe task found), Files changed:, Verification:, Commit:, Push:, Final git status:, Remaining risk:. If any field is unknown or not run, write that explicitly. Do not claim safety, verification, commit, push, or git status checks without evidence from tool output."};x.push(_e),_.push(_e),cf=!0}}await qO(_,x);let fe=0,On=0,Me=new Map,B=new Set,Te=new Set,$o=[],ko=[],yr=new Set,ds=0,If=0,oc=0,qe=0,Ne=Date.now(),d_=new dA(QA),rc=()=>$o.length>0||ko.length>0,f_=_i,wt=n.skillLoop?10:1,p_=3*wt,h_=5*wt,jf=bf,m_=5*wt,g_=8*wt,y_=P0,b_=(de?6:4)*wt,w_=(de?10:7)*wt,ic=Pl,__=(de?5:3)*wt,Ni=(de?8:5)*wt,$_=M0,k_=(de?4:3)*wt,x_=(de?6:4)*wt,v_=3*wt,S_=4*wt,xo=zn,E_=(de?6:4)*wt,T_=(de?10:8)*wt,vo=(de?12:10)*wt,R_=25,As=0,C_=10*wt,A_=15*wt,Os=0,Li=5*wt,So=()=>Be&&de&&ke==="implement"&&B.size===0&&qe===0&&Et.size===0&&sn>0,Ps=0,O_=2*wt,P_=3,Ii=!1,ac=0,ji=!1,Df=0,lc=0,br=10,M_=16,qf=n.skillLoop?999:s.investigationCap,Di=async()=>{let{hasPendingOrCompletedJobs:ce,getPendingJobSummary:_e}=Yo();if(ce()){if(_e()){let Le=Date.now()+45e3;for(process.stderr.write(`${m.cyan} \u23F3 Waiting for background agents to finish\u2026${m.reset}
1608
+ Next step: make the worktree clean and be on the required branch, then re-run the automation.`,dt={role:"assistant",content:Je};x.push(dt),we(x),Qe(x),console.log(Je);return}if(!cf){let _e={role:"user",content:"[SYSTEM] This is a gated automation workflow. In your final summary, use these exact labels (one per line): Preflight:, Preflight output:, Branch:, Chosen task: (or Selected improvement: / no safe task found), Files changed:, Verification:, Commit:, Push:, Final git status:, Remaining risk:. If any field is unknown or not run, write that explicitly. Do not claim safety, verification, commit, push, or git status checks without evidence from tool output."};x.push(_e),_.push(_e),cf=!0}}await qO(_,x);let fe=0,On=0,Me=new Map,B=new Set,Te=new Set,$o=[],ko=[],yr=new Set,ds=0,If=0,oc=0,qe=0,Ne=Date.now(),d_=new dA(QA),rc=()=>$o.length>0||ko.length>0,f_=_i,wt=n.skillLoop?10:1,p_=3*wt,h_=5*wt,jf=bf,m_=5*wt,g_=8*wt,y_=P0,b_=(de?6:4)*wt,w_=(de?10:7)*wt,ic=Pl,__=(de?5:3)*wt,Ni=(de?8:5)*wt,$_=M0,k_=(de?4:3)*wt,x_=(de?6:4)*wt,v_=3*wt,S_=4*wt,xo=zn,E_=(de?6:4)*wt,T_=(de?10:8)*wt,vo=(de?12:10)*wt,R_=25,As=0,C_=10*wt,A_=15*wt,Os=0,Li=5*wt,So=()=>Be&&de&&ke==="implement"&&B.size===0&&qe===0&&Et.size===0&&sn>0,Ps=0,O_=2*wt,P_=3,Ii=!1,ac=0,ji=!1,Df=0,lc=0,br=10,M_=16,qf=n.skillLoop?999:o.investigationCap,Di=async()=>{let{hasPendingOrCompletedJobs:ce,getPendingJobSummary:_e}=Yo();if(ce()){if(_e()){let Le=Date.now()+45e3;for(process.stderr.write(`${m.cyan} \u23F3 Waiting for background agents to finish\u2026${m.reset}
1609
1609
  `);_e()&&Date.now()<Le;)await new Promise(Re=>setTimeout(Re,500).unref()),Tl(x,_)}Tl(x,_),x.length>0&&we(x)}},fs=typeof t=="string"?t.trim():"",Ff=fs.length>0&&/^\s*(analyze|analyse|explain|describe|review|audit|summari[sz]e|list|understand|document|documentation|docs|what is|what does|how does|show me|show the|show all|tell me about)/i.test(fs)&&!/\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(fs),qi=fs.length>0&&/\b(analyze|analyse|explain|describe|review|audit|summari[sz]e|understand|document|scan|count|inventory|map|list|identify)\b/i.test(fs)&&/\b(create|write|generate|produce|output)\b/i.test(fs)&&/\b([A-Z0-9_-]+\.md|markdown|report|summary|overview|architecture|audit|table|documentation|docs|inventory|catalog)\b/i.test(fs)&&!/\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(fs),ut,It=n.maxIterations||(de?ks(ke):Rl);Ff&&(It=Math.min(It,4),N(`${m.dim} \u21B3 Analysis-only prompt detected \u2014 iter cap=${It}${m.reset}`));let cc=0,Bf=3,Fi=!1,Bi=0,uc=!1;e:for(;;){for(Fi=!1,ut=0;ut<It&&!Cl()?.aborted;ut++){Tl(x,_);{let b=Kt(),y=Tn(_,b),D=fe===0?65:78;if(y.percentage>=D){if(B.size>0||de&&ke!=="plan"){let ue=gA(x,{filesModified:B,currentPhase:de?ke:null});if(ue){let te=_.findIndex(A=>A._progressSnapshot);te!==-1&&_.splice(te,1);let F=_.findIndex(A=>A.role==="system");_.splice(F+1,0,ue)}}let{messages:L,tokensRemoved:V}=Bn(_,b,fe===0);if(V>0&&(_=L,V>50&&console.log(`${m.dim} [auto-compressed \u2014 ~${V} tokens freed, now ${Math.round(Tn(_,b).percentage)}%]${m.reset}`),gn&&B.size>=3)){let ue=[...B].map(F=>F.split("/").pop()).slice(0,10).join(", "),te={role:"user",content:`[FRAMEWORK \u2014 context compressed] Task is IN PROGRESS. Already created ${B.size} files: ${ue}. DO NOT restart or re-investigate what was already done. Continue from where you left off.`};_.push(te)}}}if(tn&&!Pt&&hi<2){hi++;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."};_.push(b),x.push(b),N(`${m.yellow} \u26A0 Pre-call SSH-blocked nudge #${hi} injected \u2014 model told to synthesize${m.reset}`)}tn||(hi=0);let _e=!0;fe>0&&qA();let Le=null;if($&&$.isActive())$._paused&&$.resume();else if(!$){let b,y=FA();if(y&&y.total>1){let V=y.description.length>40?y.description.slice(0,37)+"\u2026":y.description;b=`Plan step ${y.current}/${y.total}: ${V}`}else b=fe>0?`${Dd()} (step ${fe+1})`:Dd();let{getPendingJobSummary:D}=Yo(),L=D();L&&(b+=` [${L}]`),Le=new ir(b),Le.start()}let Re=!0,xe="",an=!1,Je=new BA,dt,Ms=Date.now(),Ui=!1,dc=new AbortController,fc=setInterval(()=>{let b=Date.now()-Ms;if(b>=Yd)Je._clearCursorLine(),N(`${m.yellow} \u26A0 Stream stale for ${Math.round(b/1e3)}s \u2014 aborting and retrying${m.reset}`),dc.abort();else if(b>=h0&&!Ui){Ui=!0,Je._clearCursorLine();let y=Hl.fast?.[Yn()],D=ee>0?` (retry ${ee+1}/${kl})`:"",L=Math.round((Yd-b)/1e3);N(`${m.yellow} \u26A0 No tokens received for ${Math.round(b/1e3)}s \u2014 waiting...${D}${m.reset}`),y&&y!==Cn()?console.log(`${m.dim} \u{1F4A1} Will auto-switch to ${y} in ~${L}s if no tokens arrive${m.reset}`):console.log(`${m.dim} \u{1F4A1} Ctrl+C to abort \xB7 auto-abort in ~${L}s${m.reset}`)}},5e3);fc.unref?.();let ln="",Pn=null;try{let b=a?[]:C0(Kt()),y=new Set(["read_file","list_directory","search_files","glob","grep","git_status","git_diff","git_log","git_show","ssh_exec"]),D=new Set(["read_file","list_directory","glob","grep","bash","git_status","git_diff","git_log","ssh_exec"]),L;Ii?L=[]:go()?L=b.filter(te=>x0.has(te.function.name)):de&&ke==="plan"?(L=b.filter(te=>y.has(te.function.name)),Be&&(Tt||Vt>=dr)&&(L=[])):de&&ke==="verify"?L=b.filter(te=>D.has(te.function.name)):L=b;let V=Cl(),ue=new AbortController;if(V&&V.addEventListener("abort",()=>ue.abort(),{once:!0}),dc.signal.addEventListener("abort",()=>ue.abort(),{once:!0}),dt=await _l(_,L,{signal:ue.signal,...An?{model:An}:{},onThinkingToken:()=>{Ms=Date.now(),Ui=!1,ft?.onThinkingToken&&ft.onThinkingToken()},onToken:te=>{if(Ms=Date.now(),Ui=!1,ft?.onToken){ft.onToken(te),xe+=te;return}if(xe+=te,!an&&xe.length>400&&xe.length%250<te.length+1){let F=ef(xe,3);F.truncated&&(an=!0,Je._clearCursorLine?.(),N(`${m.yellow} \u26A0 LLM stream loop detected (${F.repeatCount}\xD7 repeated) \u2014 suppressing display${m.reset}`))}an||(ln+=te,process.stdout.isTTY?Pn||(Pn=setTimeout(()=>{ln&&Je&&Je.push(ln),ln="",Pn=null},50),Pn.unref?.()):(Je.push(ln),ln=""),Re&&($&&!$._paused?$.pause():Le&&Le.stop(),_e||(_e=!0),Je.startCursor(),Re=!1))}}),!dt||typeof dt!="object")throw new Error("Provider returned an empty response (no content/tool_calls)")}catch(b){if(clearInterval(fc),Pn&&(clearTimeout(Pn),Pn=null),ln&&Je&&(Je.push(ln),ln=""),$&&!$._paused&&$.pause(),Le&&Le.stop(),Je.stopCursor(),dc.signal.aborted&&!Cl()?.aborted){if(ee++,ee>kl){if(P<1){P++,or("Stale retries exhausted \u2014 last-resort force-compress...",m.yellow);let A=Kt(),{messages:I,tokensRemoved:O}=Bn(_,A);_=I,O>50&&N(`${m.dim} [force-compressed \u2014 ~${O} tokens freed]${m.reset}`),ee=0,ut--;continue}$&&($.stop(),$=null);let F=await aP();if(F.action==="quit"){T(null),De(fe,Me,B,Te,Ne),we(x);break}F.action==="switch"&&(qd(`${F.provider}:${F.model}`),console.log(`${m.green} \u2713 Switched to ${F.provider}:${F.model}${m.reset}`)),ee=0,ut--;continue}let ue=ee===1?3e3:5e3;if(ee>=1&&$e<1){$e++,or(`Stale retry ${ee}/${kl} \u2014 force-compressing before retry...`,m.yellow);let F=Kt(),{messages:A,tokensRemoved:I}=Bn(_,F,!0);if(_=A,I>0&&I>50&&N(`${m.dim} [force-compressed \u2014 ~${I} tokens freed]${m.reset}`),wO){let O=Hl.fast?.[Yn()];O&&O!==Cn()&&(qd(`${Yn()}:${O}`),console.log(`${m.cyan} \u26A1 Auto-switched to ${O} to avoid further stale timeouts${m.reset}`),console.log(`${m.dim} (disable with NEX_STALE_AUTO_SWITCH=0)${m.reset}`))}}else N(`${m.yellow} \u26A0 Stale retry ${ee}/${kl} \u2014 retrying in ${ue/1e3}s...${m.reset}`);let te=new ir(`Waiting ${ue/1e3}s before retry...`);te.start(),await new Promise(F=>setTimeout(F,ue)),te.stop(),ut--;continue}if(b.name==="AbortError"||b.name==="CanceledError"||b.message?.includes("canceled")||b.message?.includes("aborted")){$&&($.stop(),$=null),T(null),De(fe,Me,B,Te,Ne),we(x);break}let y=b.message.includes("Provider returned an empty response"),D=b.message;if(b.code==="ECONNREFUSED"||b.message.includes("ECONNREFUSED"))D="Connection refused \u2014 please check your internet connection or API endpoint";else if(b.code==="ENOTFOUND"||b.message.includes("ENOTFOUND"))D="Network error \u2014 could not reach the API server. Please check your connection";else if(b.code==="ETIMEDOUT"||b.message.includes("timeout"))D="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"))D="Authentication failed \u2014 please check your API key in the .env file";else if(b.message.includes("403")||b.message.includes("Forbidden"))D="Access denied \u2014 your API key may not have permission for this model";else if(b.message.includes("404")){let ue=Cn?Cn():"unknown",te=I=>I.includes(":")&&I.split(":")[0].match(/^[a-z]+$/)&&!I.split(":")[1].includes(":")?I.split(":").slice(1).join(":"):I;tt.add(te(ue));let A=(()=>{let I=[];process.env.NEX_FALLBACK_MODEL&&I.push(process.env.NEX_FALLBACK_MODEL);try{let{getModelForCategory:O}=ro(),j=["agentic","coding","plan","verify","sysadmin","data","frontend"];for(let Y of j){let me=O(Y);me&&!I.includes(me)&&I.push(me)}}catch{}return I.filter(O=>!tt.has(te(O)))})()[0];if(A){console.log(`${m.yellow} \u26A0 Model ${ue} unavailable (404) \u2014 switching to ${A}${m.reset}`),qd(A),t0(A),ut--;continue}D=`Model not found (404): ${ue} \u2014 no fallback available. Set NEX_FALLBACK_MODEL or run /models to list available models`,console.log(`${m.red} \u2717 ${D}${m.reset}`),$&&($.stop(),$=null),T(null),De(fe,Me,B,Te,Ne),we(x);break}else if(b.message.includes("400")){if(P<3&&he<Xe){P++,he++;let ue=fe===0&&P===1,te=ue||P===3||$e>0;if(ue){P=3;let O=b.message.replace(/^API Error(\s*\[HTTP \d+\])?:\s*/i,"").slice(0,150);or(`Bad request (400) \u2014 ${O||"system prompt too large"}, compressing...`,m.yellow)}else or(te?`Bad request (400) \u2014 nuclear compression (attempt ${P}/3, dropping history)...`:`Bad request (400) \u2014 force-compressing and retrying... (attempt ${P}/3)`,m.yellow);let F=Kt(),{messages:A,tokensRemoved:I}=Bn(_,F,te);_=A,I>50&&N(`${m.dim} [force-compressed \u2014 ~${I} tokens freed]${m.reset}`),ut--;continue}{let ue=_.find(j=>j.role==="system"),te=_.find(j=>j.role==="user"&&!String(j.content).startsWith("[SYSTEM")&&!String(j.content).startsWith("BLOCKED:")),F=[ue,te].filter(Boolean),{getUsage:A}=Fn(),I=Fn().estimateMessagesTokens(F),O=Fn().estimateMessagesTokens(_);if(I<O){let j=[],Y=x.filter(q=>q.role==="assistant"&&typeof q.content=="string"&&q.content.trim().length>30).slice(-5).map(q=>q.content.trim().slice(0,300).replace(/\n+/g," "));Y.length>0&&j.push(`Key findings:
1610
1610
  `+Y.map(q=>`- ${q}`).join(`
1611
1611
  `));let me=x.filter(q=>q.role==="tool"&&typeof q.content=="string"&&!q.content.startsWith("BLOCKED:")&&q.content.trim().length>10).slice(-5).map(q=>q.content.trim().split(`
@@ -1694,7 +1694,7 @@ ${je}`),x.push({role:"user",content:ie},{role:"assistant",content:je}))}catch{}w
1694
1694
  The planned implementation file was already in context, but the model kept calling blocked read/search/git tools instead of editing. Stopping without commit or push so the workflow does not falsely report success.`,V={role:"assistant",content:L};x.push(V),_.push(V),console.log(`
1695
1695
  ${L}`),we(x),Qe(x)}$&&($.stop(),$=null),T(null),De(fe,Me,B,Te,Ne,{suppressHint:!0}),we(x);return}}}let Gi=!1;for(let b=0;b<Ce.length;b++){let y=Ce[b];if(!y.canExecute)continue;let D=_t[b].content,L=D.split(`
1696
1696
  `)[0],V=!L.startsWith("ERROR")&&!L.startsWith("CANCELLED")&&!L.startsWith("Command failed")&&!L.startsWith("EXIT")&&!/old_text not found/i.test(L);if(y.fnName==="git_status"&&V&&(gi="git_status",mo=D),y.fnName==="bash"&&y.canExecute&&typeof y.args?.command=="string"){let A=y.args.command;/git\s+status\s+--short\s+--branch\b/.test(A)&&(gi="bash:git status --short --branch",mo=D),/git\s+push\b/.test(A)&&(Ss=D,V&&!Ss.startsWith("EXIT")&&(/\bEverything up[- ]to[- ]date\b/i.test(Ss)||/\bTo\s+\S+/i.test(Ss)||/\bWriting objects\b/i.test(Ss))&&(Bl=!0))}if(!V&&(y.fnName==="edit_file"||y.fnName==="patch_file")&&y.args?.path&&L.includes("old_text not found")){let A=Et.get(y.args.path)||0;Et.set(y.args.path,A+1)}if(!V&&y.fnName==="bash"&&_i.size>0){let A=(y.args?.command||"").toLowerCase();if(/\b(test|jest|vitest|pytest|mocha|tsc|build|lint|eslint|check)\b/.test(A))for(let[O]of _i)Et.has(O)||(Et.set(O,1),N(`${m.cyan} \u21A9 Test failure \u2014 queuing recovery re-read: "${O.split("/").pop()}"${m.reset}`))}if(!V&&(y.fnName==="read_file"||y.fnName==="edit_file")&&/file not found|does not exist|ENOENT/i.test(L)){if(xs++,xs>=2){N(`${m.yellow} \u26A0 File-not-found streak: ${xs} consecutive misses \u2014 forcing search${m.reset}`);let A={role:"user",content:`[SYSTEM] ${xs} 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.`};x.push(A),_.push(A)}}else V&&(y.fnName==="read_file"||y.fnName==="edit_file"||y.fnName==="search_files"||y.fnName==="glob_files")&&(xs=0);if(V&&y.fnName==="write_file"&&y.args?.path){let A=y.args.path.split("/").pop(),I=y.args.path.includes("/tests/")||y.args.path.includes("\\tests\\");if(/^(test_|demo_|temp_|tmp_|scratch_)/.test(A)&&!I){N(`${m.yellow} \u26A0 Temp file: "${A}" \u2014 delete with bash rm when done to keep the workspace clean${m.reset}`);let j={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.`};x.push(j),_.push(j)}}if(V&&["write_file","edit_file","patch_file"].includes(y.fnName)&&y.args&&y.args.path){Et.delete(y.args.path),B.add(y.args.path);for(let O of ls)!O.done&&y.args.path.endsWith(O.file.split("/").pop())&&(O.done=!0,N(`${m.green} \u2713 TODO done: ${O.file}${m.reset}`));let A=co(f_,y.args.path),I=y.args.path.split("/").slice(-2).join("/");if(A===p_){N(`${m.yellow} \u26A0 Loop warning: "${I}" edited ${A}\xD7 \u2014 possible edit loop${m.reset}`);let O={role:"user",content:`[SYSTEM WARNING] "${y.args.path}" edited ${A}\xD7. One more edit max, then move on.`};x.push(O),_.push(O)}else if(A>=h_){N(`${m.red} \u2716 Loop abort: "${I}" edited ${A}\xD7 \u2014 aborting to prevent runaway loop${m.reset}`),$&&($.stop(),$=null),T(null),De(fe,Me,B,Te,Ne,{suppressHint:!0}),we(x);return}de&&ke==="verify"||(Kn=!0,Vn=0,Gi=!0)}if(V&&y.canExecute&&de&&(Ts=0),V&&y.canExecute&&Be&&de&&ke==="plan"&&RO.has(y.fnName)&&(Vt++,OO(y.fnName,y.args)&&Ri++,Vt>=Vl&&!Ul)){Ul=!0;let A={role:"user",content:Gn()};x.push(A),_.push(A),N(`${m.yellow} \u26A0 Bounded backlog plan: ${Vt} read/search tools used \u2014 requiring a decision${m.reset}`)}if(V&&y.canExecute&&!(de&&ke==="plan")){let A=["read_file","grep","search_files","glob","list_directory","ssh_exec","find_files"];if(["write_file","edit_file","patch_file"].includes(y.fnName)){yn=0,bn=!1,Rn=0,wn++;let ie=y.args?.path||y.args?.file_path;ie&&(y.fnName==="write_file"?(vs.add(ie),zn.delete(ie),as.delete(ie),yr.delete(ie)):(vs.delete(ie),Vd(zn,ie,1),as.delete(ie),yr.add(ie)))}else if(A.includes(y.fnName)){if(yn++,bn&&Rn++,de&&ke==="implement"&&y.fnName==="read_file"){let ie=y.args?.path||y.args?.file_path||"";if(ie&&vs.has(ie)){let q={role:"user",content:`[SYSTEM] You just created and re-read "${ie}". Do NOT analyze further. Apply the requested refactor now with edit_file.`};x.push(q),_.push(q),N(`${m.yellow} \u26A0 Fresh-write nudge: ${ie} \u2014 refactor directly after re-read${m.reset}`)}}if(de&&ke==="implement"&&y.fnName==="read_file"&&ls.length>0){let ie=y.args?.path||y.args?.file_path||"",q=ls.find(pe=>!pe.done&&ie.endsWith(pe.file.split("/").pop()));if(q){let pe={role:"user",content:`[TODO OBSERVER] You already analyzed "${q.file}" in the plan phase. Action: ${q.action}
1697
- Do NOT re-read \u2014 apply the edit directly with edit_file.`};x.push(pe),_.push(pe),N(`${m.yellow} \u26A0 TODO nudge: ${q.file} \u2014 already analyzed, edit directly${m.reset}`)}}de&&ke==="implement"&&Kn&&Vn<1&&(Vn++,Gi=!0)}if(de&&ke==="verify"&&pr++,V&&$0(y)){let ie=String(y.args?.command||"").trim();if(ie&&$o.push(ie.slice(0,160)),Kn=!1,Vn=0,nn&&(B.size>0||qe>0)&&!sr){let q={role:"user",content:"[SYSTEM] \u2713 Verification command succeeded after your edit. The dirty worktree now contains your own intended changes, not a preflight blocker. Do not restart planning or re-read the changed file. Stage only the files you changed, commit with a terse English message, push if the prompt requires it, then run one final `git status --short --branch`."};x.push(q),_.push(q)}}let O=s.postEditCap,j=de&&ke==="implement"?Math.min(qf,10):qf,Y=Pt?8:qi?wn>0?4:6:gn?wn>0?6:10:wn>0?O:j,me=6,ge=!de&&bn&&(Pt&&Rn>=me||gn&&wn>=3&&Rn>=me||Rn>=me);if(ci<2&&!bn&&yn>=3&&B.size===0){let ie=parseInt(process.env.NEX_TASK_TIMEOUT_MS,10)||0,q=Date.now()-Ne,pe=ci===0?.4:.65;if(ie>0&&q>ie*pe){ci++;let je=Math.round(q/6e4),We=Math.round(q/ie*100);N(`${m.yellow} \u26A0 Time nudge #${ci}: ${je}m elapsed (${We}%), ${yn} reads, 0 edits${m.reset}`);let rt={role:"user",content:ci===1?`[SYSTEM] ${We}% of available time used and no files edited yet. Start implementing now using edit_file or write_file \u2014 you have enough context.`:`[SYSTEM] ${We}% 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.`};x.push(rt),_.push(rt)}}if(ge&&A.includes(y.fnName)){let ie=Pt?`root cause already identified (${zt})`:Rn>=me?`${yn} consecutive reads without an edit`:`${wn} file edit(s) already made`;N(`${m.red} \u2716 Blocked read-only tool: cap fired, ${ie}${m.reset}`),y.canExecute=!1,y.errorResult={role:"tool",content:Pt?`BLOCKED: root cause already identified (${zt}). Use edit_file to fix the issue \u2014 do not read more files.`:gn?"BLOCKED: files already written \u2014 continue with write_file or edit_file to finish the remaining tasks. Do not read more files.":Rn>=me?`BLOCKED: You have read ${yn} 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: ${wn} 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(yn>=Y&&!bn){if(bn=!0,qi&&(uc=!0),N(`${m.yellow} \u26A0 Investigation cap: ${yn} read-only calls without an edit \u2014 forcing implementation${m.reset}`),de&&ke==="plan"){let pe=[..._].reverse().find(rt=>rt.role==="assistant"),je=typeof pe?.content=="string"?pe.content:"",We=await rr("implement",je);We&&(x.push(We),_.push(We),ut=0,It=ks("implement"))}let ie;Pt?ie=`[SYSTEM] Root cause was already identified (${zt}). Edit the file now \u2014 do not read more files.`:qi?ie="[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.":tn?ie="[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.":ie="[SYSTEM] You have read enough files. Now implement your fix using edit_file.";let q={role:"user",content:ie};x.push(q),_.push(q)}}if((y.fnName==="bash"||y.fnName==="ssh_exec")&&y.args&&y.args.command){let A=y.args.command.replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),I=co(jf,A);if(I===m_){N(`${m.yellow} \u26A0 Loop warning: same bash command run ${I}\xD7 \u2014 possible debug loop${m.reset}`);let O={role:"user",content:`[SYSTEM WARNING] Same bash command ${I}\xD7. Debug loop detected \u2014 try a different approach.`};x.push(O),_.push(O)}else if(I>=g_){N(`${m.red} \u2716 Loop abort: same bash command run ${I}\xD7 \u2014 aborting runaway debug loop${m.reset}`),$&&($.stop(),$=null),T(null),De(fe,Me,B,Te,Ne,{suppressHint:!0}),we(x);return}}if(y.fnName==="ssh_exec"){mn++;{let O=(_t[b]?.content??"").split(`
1697
+ Do NOT re-read \u2014 apply the edit directly with edit_file.`};x.push(pe),_.push(pe),N(`${m.yellow} \u26A0 TODO nudge: ${q.file} \u2014 already analyzed, edit directly${m.reset}`)}}de&&ke==="implement"&&Kn&&Vn<1&&(Vn++,Gi=!0)}if(de&&ke==="verify"&&pr++,V&&$0(y)){let ie=String(y.args?.command||"").trim();if(ie&&$o.push(ie.slice(0,160)),Kn=!1,Vn=0,nn&&(B.size>0||qe>0)&&!sr){let q={role:"user",content:"[SYSTEM] \u2713 Verification command succeeded after your edit. The dirty worktree now contains your own intended changes, not a preflight blocker. Do not restart planning or re-read the changed file. Stage only the files you changed, commit with a terse English message, push if the prompt requires it, then run one final `git status --short --branch`."};x.push(q),_.push(q)}}let O=o.postEditCap,j=de&&ke==="implement"?Math.min(qf,10):qf,Y=Pt?8:qi?wn>0?4:6:gn?wn>0?6:10:wn>0?O:j,me=6,ge=!de&&bn&&(Pt&&Rn>=me||gn&&wn>=3&&Rn>=me||Rn>=me);if(ci<2&&!bn&&yn>=3&&B.size===0){let ie=parseInt(process.env.NEX_TASK_TIMEOUT_MS,10)||0,q=Date.now()-Ne,pe=ci===0?.4:.65;if(ie>0&&q>ie*pe){ci++;let je=Math.round(q/6e4),We=Math.round(q/ie*100);N(`${m.yellow} \u26A0 Time nudge #${ci}: ${je}m elapsed (${We}%), ${yn} reads, 0 edits${m.reset}`);let rt={role:"user",content:ci===1?`[SYSTEM] ${We}% of available time used and no files edited yet. Start implementing now using edit_file or write_file \u2014 you have enough context.`:`[SYSTEM] ${We}% 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.`};x.push(rt),_.push(rt)}}if(ge&&A.includes(y.fnName)){let ie=Pt?`root cause already identified (${zt})`:Rn>=me?`${yn} consecutive reads without an edit`:`${wn} file edit(s) already made`;N(`${m.red} \u2716 Blocked read-only tool: cap fired, ${ie}${m.reset}`),y.canExecute=!1,y.errorResult={role:"tool",content:Pt?`BLOCKED: root cause already identified (${zt}). Use edit_file to fix the issue \u2014 do not read more files.`:gn?"BLOCKED: files already written \u2014 continue with write_file or edit_file to finish the remaining tasks. Do not read more files.":Rn>=me?`BLOCKED: You have read ${yn} 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: ${wn} 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(yn>=Y&&!bn){if(bn=!0,qi&&(uc=!0),N(`${m.yellow} \u26A0 Investigation cap: ${yn} read-only calls without an edit \u2014 forcing implementation${m.reset}`),de&&ke==="plan"){let pe=[..._].reverse().find(rt=>rt.role==="assistant"),je=typeof pe?.content=="string"?pe.content:"",We=await rr("implement",je);We&&(x.push(We),_.push(We),ut=0,It=ks("implement"))}let ie;Pt?ie=`[SYSTEM] Root cause was already identified (${zt}). Edit the file now \u2014 do not read more files.`:qi?ie="[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.":tn?ie="[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.":ie="[SYSTEM] You have read enough files. Now implement your fix using edit_file.";let q={role:"user",content:ie};x.push(q),_.push(q)}}if((y.fnName==="bash"||y.fnName==="ssh_exec")&&y.args&&y.args.command){let A=y.args.command.replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),I=co(jf,A);if(I===m_){N(`${m.yellow} \u26A0 Loop warning: same bash command run ${I}\xD7 \u2014 possible debug loop${m.reset}`);let O={role:"user",content:`[SYSTEM WARNING] Same bash command ${I}\xD7. Debug loop detected \u2014 try a different approach.`};x.push(O),_.push(O)}else if(I>=g_){N(`${m.red} \u2716 Loop abort: same bash command run ${I}\xD7 \u2014 aborting runaway debug loop${m.reset}`),$&&($.stop(),$=null),T(null),De(fe,Me,B,Te,Ne,{suppressHint:!0}),we(x);return}}if(y.fnName==="ssh_exec"){mn++;{let O=(_t[b]?.content??"").split(`
1698
1698
  `).map(j=>j.trim()).find(j=>j.length>0&&!j.startsWith("**")&&(j.startsWith("EXIT")||/^[\w./-]+:\s/.test(j)||j.startsWith("bash:")||j.startsWith("sh:")))??"";if(O){if(O===ql?po++:(ql=O,po=1),po===3&&!tn){N(`${m.yellow} \u26A0 SSH repeated-error: "${O.slice(0,60)}" returned ${po}\xD7 \u2014 nudging to change approach${m.reset}`);let j={role:"user",content:`[SYSTEM WARNING] The last ${po} SSH commands all failed with the same error: "${O}". 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).`};x.push(j),_.push(j)}}else ql="",po=0}if(mn>=M_){N(`${m.red} \u2716 SSH storm abort: ${mn} consecutive ssh_exec calls \u2014 aborting${m.reset}`),$&&($.stop(),$=null),T(null),De(fe,Me,B,Te,Ne,{suppressHint:!0}),we(x);return}else if(mn===br){{let O=Kt(),{messages:j}=Bn(_,O);_=j}tn=!0,xl++,N(`${m.yellow} \u26A0 SSH storm warning (#${xl}): ${mn} consecutive ssh_exec calls \u2014 blocking further SSH${m.reset}`);let I={role:"user",content:Pt?`[SYSTEM WARNING] ${mn} consecutive SSH calls. Root cause identified (${zt}). Read the file that needs fixing, then edit it.`:`[SYSTEM WARNING] ${mn} 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.`};x.push(I),_.push(I)}}else y.canExecute&&(mn=0);if(y.fnName==="bash"&&y.canExecute){let O=(_t[b]?.content??"").split(`
1699
1699
  `).map(j=>j.trim()).find(j=>j.length>0&&(j.startsWith("EXIT")||/^[\w./-]+:\s/.test(j)||j.startsWith("bash:")||j.startsWith("sh:")))??"";if(O){if(O===Fl?ho++:(Fl=O,ho=1),ho===3){N(`${m.yellow} \u26A0 Bash repeated-error: "${O.slice(0,60)}" returned ${ho}\xD7 \u2014 nudging to change approach${m.reset}`);let j={role:"user",content:`[SYSTEM WARNING] The last ${ho} bash commands all failed with the same error: "${O}". 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).`};x.push(j),_.push(j)}}else Fl="",ho=0}if(y.fnName==="bash"&&y.canExecute&&!sr&&y.args?.command){let A=_t[b]?.content??"";if(/git\s+commit\b/.test(y.args.command)&&!A.startsWith("EXIT")&&!A.startsWith("ERROR")&&(/\[\S+\s+[a-f0-9]+\]/.test(A)||A.includes("files changed")||A.includes("file changed")||A.includes("insertions(+)")||A.includes("create mode"))){sr=!0,ui=0;let j=nn?4:2;N(`${m.green} \u2713 Git commit detected \u2014 post-commit verification cap active (max ${j} git status/diff/log)${m.reset}`);let Y=nn?{role:"user",content:"[SYSTEM] \u2713 Git commit succeeded. This is a gated automation workflow: ensure you still capture final-state evidence. Next: push (if required by the prompt), then run `git status --short --branch` once and include its output in the final automation report. Avoid extra git diff/log unless needed to explain a blocker."}:{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."};x.push(Y),_.push(Y)}}if(sr&&y.fnName==="bash"&&y.args?.command&&/git\s+(status|diff|log|show)\b/.test(y.args.command)&&(ui++,ui>(nn?4:2))){N(`${m.yellow} \u26A0 Post-commit git verification blocked (call ${ui})${m.reset}`);let O={role:"user",content:"[SYSTEM] \u26A0 STOP: You already ran "+(ui-1)+" git verification commands after committing. "+(nn?"In gated automation workflows, keep tool use minimal: you already have enough evidence for the final report. Write the final automation report now and stop.":"The commit is confirmed. Write your final summary NOW and do not make any more tool calls.")};x.push(O),_.push(O)}if(V&&y.fnName==="grep"&&D&&!D.startsWith("(no matches)")){let A=Lt(y.args?.path||"");Be&&de&&ke==="implement"&&A&&ki.set(A,(ki.get(A)||0)+1);let I=D.split(`
1700
1700
  `);for(let O of I){let j=O.indexOf(":");if(j>0){let Y=O.substring(0,j);Y.startsWith("/")&&!Y.includes(" ")&&bi.add(Y)}else O.startsWith("/")&&!O.includes(" ")&&bi.add(O.trim())}}{let A=["grep","search_files","glob","glob_files"].includes(y.fnName);if(A&&V&&D&&(D.startsWith("(no matches)")||D.trim()===""||/^No matches found/.test(D.trim())||/^\(0 results\)/.test(D.trim()))){if(oc++,oc===3){N(`${m.yellow} \u26A0 3 consecutive empty local searches \u2014 injecting SSH pivot hint${m.reset}`);let O={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."};x.push(O),_.push(O)}}else A&&V&&D&&D.trim().length>0&&(oc=0)}if(V&&y.fnName==="grep"&&y.args&&y.args.pattern){let A=`${y.args.pattern}|${y.args.path||""}`,I=co(y_,A);if(I===b_){N(`${m.yellow} \u26A0 Loop warning: grep pattern "${y.args.pattern.slice(0,40)}" run ${I}\xD7 \u2014 possible search loop${m.reset}`);let O={role:"user",content:`[SYSTEM WARNING] Same grep pattern ${I}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};x.push(O),_.push(O)}else if(I>=w_){N(`${m.red} \u2716 Loop abort: grep pattern run ${I}\xD7 \u2014 aborting runaway search loop${m.reset}`),$&&($.stop(),$=null),T(null),De(fe,Me,B,Te,Ne,{suppressHint:!0}),we(x);return}if(y.args.path){let O=co(ic,y.args.path),j=Un(xo,y.args.path)>=1;if(O===(j?1:__)){let me=y.args.path.split("/").slice(-2).join("/");N(`${m.yellow} \u26A0 Loop warning: "${me}" grepped ${O}\xD7 with different patterns \u2014 context flood risk${m.reset}`);let ge={role:"user",content:j?`[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 ${O}\xD7 \u2014 use the search results already in context instead of searching again.`};x.push(ge),_.push(ge)}}}if(V&&(y.fnName==="glob"||y.fnName==="glob_files"||y.fnName==="search_files")&&y.args){if(D&&!D.startsWith("(no matches)")){let j=D.split(`
@@ -1725,17 +1725,17 @@ ${Re}`),we(x),Qe(x);break e}if(_e==="ollama"&&cc<Bf){if(B.size===0&&!Fi){console
1725
1725
  ${m.yellow}\u26A0 Max iterations reached.${m.reset}`),await k0(" Continue for 20 more turns?")){It=20;continue e}console.log(`${m.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${m.reset}`)}break e}if(Be&&Tt&&B.size===0&&qe===0){let ce=[...x].reverse().find(Re=>Re.role==="assistant"),_e=typeof ce?.content=="string"?ce.content:"";if(!/\b(no safe task found|implementation stalled before edits)\b/i.test(_e)){let Re=`Implementation stalled before edits.
1726
1726
 
1727
1727
  The bounded backlog workflow ended after reading/searching but before changing files. Stopping without commit or push so the workflow does not falsely report success.`,xe={role:"assistant",content:Re};x.push(xe),_.push(xe),console.log(`
1728
- ${Re}`),De(fe,Me,B,Te,Ne),we(x),Qe(x)}}await Di()}function H0(t,e,n,s=!1){return!s&&t&&e&&e.isComplex&&e.estimatedGoals>=n}G0.exports={processInput:uP,clearConversation:eP,getConversationLength:nP,getConversationMessages:sP,setConversationMessages:oP,setAbortSignalGetter:aO,setMaxIterations:iO,invalidateSystemPromptCache:Ol,clearToolFilterCache:mO,getCachedFilteredTools:C0,buildSystemPrompt:gf,splitSystemPrompt:QO,SYSTEM_PROMPT_DYNAMIC_BOUNDARY:mf,getProjectContextHash:A0,_inferVerificationCommands:Xl,_inferRelevantTests:Ci,_inferSymbolTargets:F0,_buildSymbolHintBlock:B0,_detectResponseLanguage:_f,_isSimpleDirectAnswerPrompt:U0,_claimsVerificationOrCompletion:Zd,_statesVerificationGap:Qd,_shouldAutoOrchestrate:H0,_shouldSkipPlanPhaseForDirectCreation:ff,_hasAutomationOrPreflightGate:Ai,_extractDirectTaskPaths:xi,_isBoundedBacklogPlanningPrompt:N0,_buildBoundedBacklogPlanInstruction:Gn,_looksLikeBoundedBacklogDecision:yi,_looksLikeGatedAutomationFinalSummary:pf,buildUserContent:T0,_detectImageURLs:v0,_downloadImageURL:S0,_grabClipboardImage:E0,detectFrustration:R0,detectAndTruncateLoop:ef,injectMidRunNote:BO,resetSessionTracking:W0}});var vt=ne((WN,X0)=>{var{OllamaProvider:dP,getOllamaRecommendations:fP}=qp(),{OpenAIProvider:pP}=Mc(),{DeepSeekProvider:hP}=Gp(),{AnthropicProvider:mP}=Vp(),{GeminiProvider:gP}=Qp(),{LocalProvider:yP}=nh(),{checkBudget:bP,formatProviderCostMode:wP,getProviderCostMode:_P}=ma(),vf={top:{ollama:"kimi-k2:1t",openai:"gpt-4.1",deepseek:"deepseek-v4-pro",anthropic:"claude-sonnet-4-5",gemini:"gemini-2.5-pro"},strong:{ollama:"qwen3-coder:480b",openai:"gpt-4o",deepseek:"deepseek-v4-pro",anthropic:"claude-sonnet",gemini:"gemini-2.5-flash"},fast:{ollama:"devstral-small-2:24b",openai:"gpt-4.1-mini",deepseek:"deepseek-v4-flash",anthropic:"claude-haiku",gemini:"gemini-2.0-flash"}},xf=(process.env.OLLAMA_FALLBACK_CHAIN||"").split(",").map(t=>t.trim()).filter(Boolean),z0={};for(let[t,e]of Object.entries(vf))for(let n of Object.values(e))z0[n]=t;function K0(t,e){let n=z0[t];return n&&vf[n][e]||t}function Ql(){return["No configured provider available.","Lowest-cost path: run /setup and choose Ollama Cloud, or set OLLAMA_API_KEY plus DEFAULT_PROVIDER=ollama.","Local free path: start Ollama locally, pull a coding model, then use /model local:<model>.","Paid fallback: set DEEPSEEK_API_KEY, OPENAI_API_KEY, ANTHROPIC_API_KEY, or GEMINI_API_KEY and use /fallback only when you want paid backup."].join(`
1729
- `)}var ct={},Mt=null,kt=null,_o=[];function on(){let t=process.env.NEX_MOCK_PROVIDER==="1";if(Object.keys(ct).length>0){if(t&&!ct.mock){let{MockProvider:o}=Bc();cs("mock",new o)}t&&ct.mock&&Mt!=="mock"&&(Mt="mock",kt=ct.mock.defaultModel||"mock-model",_o=[],Oi());return}if(cs("ollama",new dP),cs("openai",new pP),cs("deepseek",new hP),cs("anthropic",new mP),cs("gemini",new gP),cs("local",new yP),t){let{MockProvider:o}=Bc();cs("mock",new o)}let e=process.env.DEFAULT_PROVIDER||"ollama",n=process.env.DEFAULT_MODEL||null;t?(Mt="mock",kt=ct.mock?.defaultModel||"mock-model",_o=[]):ct[e]?(Mt=e,kt=n||ct[e].defaultModel):(Mt="ollama",kt="kimi-k2.5");let s=process.env.FALLBACK_CHAIN;s&&(_o=s.split(",").map(o=>o.trim()).filter(Boolean))}function cs(t,e){ct[t]=e}function $P(t){return on(),ct[t]||null}function Sf(){return on(),ct[Mt]||null}function kP(){return on(),Mt}function xP(){return on(),kt}function vP(){on();let t=Sf();if(!t)return{id:kt,name:kt,provider:Mt};let e=t.getModel(kt);return e?{...e,provider:Mt}:{id:kt,name:kt,provider:Mt}}function Ef(t){if(!t)return{provider:null,model:null};let e=t.indexOf(":");if(e>0){let n=t.slice(0,e);if(ct[n]||["ollama","openai","deepseek","anthropic","gemini","local","mock"].includes(n))return{provider:n,model:t.slice(e+1)}}return{provider:null,model:t}}function SP(t){on();let{provider:e,model:n}=Ef(t);if(e){let o=ct[e];return o&&(o.getModel(n)||e==="local"||e==="ollama")?(Mt=e,kt=n,Oi(),!0):!1}let s=Sf();if(s&&s.getModel(n))return kt=n,Oi(),!0;for(let[o,r]of Object.entries(ct))if(r.getModel(n))return Mt=o,kt=n,Oi(),!0;return!1}function Oi(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=kd();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=Fn();t()}catch{}}function EP(){on();let t=new Set;for(let e of Object.values(ct))for(let n of e.getModelNames())t.add(n);return Array.from(t)}function TP(){return on(),Object.entries(ct).map(([t,e])=>({provider:t,configured:e.isConfigured(),models:Object.values(e.getModels()).map(n=>({...n,active:t===Mt&&n.id===kt}))}))}function RP(){on();let t=[];for(let[e,n]of Object.entries(ct)){let s=n.isConfigured();for(let o of Object.values(n.getModels()))t.push({spec:`${e}:${o.id}`,name:o.name,provider:e,configured:s,maxTokens:o.maxTokens,contextWindow:o.contextWindow,capability:o.capability,speed:o.speed,quality:o.quality,recommendedFor:o.recommendedFor||[]})}return t}function CP(t="coding",e={}){on();let n=e.limit||5,s=e.configuredOnly!==!1,o=[],r=ct.ollama;if(r&&(!s||r.isConfigured()))for(let i of fP(t,n))o.push({...i,spec:`ollama:${i.id}`,provider:"ollama",configured:r.isConfigured()});if(o.length>=n)return o.slice(0,n);for(let[i,a]of Object.entries(ct)){if(i==="ollama"||s&&!a.isConfigured())continue;let l=a.getModel(a.defaultModel);if(l&&(o.push({...l,spec:`${i}:${l.id}`,provider:i,configured:a.isConfigured()}),o.length>=n))break}return o}function AP(t){_o=Array.isArray(t)?t:[]}function OP(){return[..._o]}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 V0(t){let e=[Mt,..._o.filter(r=>r!==Mt)],n,s=0,o=0;for(let r=0;r<e.length;r++){let i=e[r],a=ct[i];if(!a||!a.isConfigured())continue;o++;let l=bP(i);if(!l.allowed){s++,n=new Error(`Budget limit reached for ${i}: $${l.spent.toFixed(2)} / $${l.limit.toFixed(2)}`);continue}let c=r>0,u=c?K0(kt,i):kt;try{if(c){let d=_P(i).label;process.stderr.write(` [fallback: ${i}:${u} \xB7 ${d}]
1728
+ ${Re}`),De(fe,Me,B,Te,Ne),we(x),Qe(x)}}await Di()}function H0(t,e,n,o=!1){return!o&&t&&e&&e.isComplex&&e.estimatedGoals>=n}G0.exports={processInput:uP,clearConversation:eP,getConversationLength:nP,getConversationMessages:sP,setConversationMessages:oP,setAbortSignalGetter:aO,setMaxIterations:iO,invalidateSystemPromptCache:Ol,clearToolFilterCache:mO,getCachedFilteredTools:C0,buildSystemPrompt:gf,splitSystemPrompt:QO,SYSTEM_PROMPT_DYNAMIC_BOUNDARY:mf,getProjectContextHash:A0,_inferVerificationCommands:Xl,_inferRelevantTests:Ci,_inferSymbolTargets:F0,_buildSymbolHintBlock:B0,_detectResponseLanguage:_f,_isSimpleDirectAnswerPrompt:U0,_claimsVerificationOrCompletion:Zd,_statesVerificationGap:Qd,_shouldAutoOrchestrate:H0,_shouldSkipPlanPhaseForDirectCreation:ff,_hasAutomationOrPreflightGate:Ai,_extractDirectTaskPaths:xi,_isBoundedBacklogPlanningPrompt:N0,_buildBoundedBacklogPlanInstruction:Gn,_looksLikeBoundedBacklogDecision:yi,_looksLikeGatedAutomationFinalSummary:pf,buildUserContent:T0,_detectImageURLs:v0,_downloadImageURL:S0,_grabClipboardImage:E0,detectFrustration:R0,detectAndTruncateLoop:ef,injectMidRunNote:BO,resetSessionTracking:W0}});var vt=ne((WN,X0)=>{var{OllamaProvider:dP,getOllamaRecommendations:fP}=qp(),{OpenAIProvider:pP}=Mc(),{DeepSeekProvider:hP}=Gp(),{AnthropicProvider:mP}=Vp(),{GeminiProvider:gP}=Qp(),{LocalProvider:yP}=nh(),{checkBudget:bP,formatProviderCostMode:wP,getProviderCostMode:_P}=ma(),vf={top:{ollama:"kimi-k2:1t",openai:"gpt-4.1",deepseek:"deepseek-v4-pro",anthropic:"claude-sonnet-4-5",gemini:"gemini-2.5-pro"},strong:{ollama:"qwen3-coder:480b",openai:"gpt-4o",deepseek:"deepseek-v4-pro",anthropic:"claude-sonnet",gemini:"gemini-2.5-flash"},fast:{ollama:"devstral-small-2:24b",openai:"gpt-4.1-mini",deepseek:"deepseek-v4-flash",anthropic:"claude-haiku",gemini:"gemini-2.0-flash"}},xf=(process.env.OLLAMA_FALLBACK_CHAIN||"").split(",").map(t=>t.trim()).filter(Boolean),z0={};for(let[t,e]of Object.entries(vf))for(let n of Object.values(e))z0[n]=t;function K0(t,e){let n=z0[t];return n&&vf[n][e]||t}function Ql(){return["No configured provider available.","Lowest-cost path: run /setup and choose Ollama Cloud, or set OLLAMA_API_KEY plus DEFAULT_PROVIDER=ollama.","Local free path: start Ollama locally, pull a coding model, then use /model local:<model>.","Paid fallback: set DEEPSEEK_API_KEY, OPENAI_API_KEY, ANTHROPIC_API_KEY, or GEMINI_API_KEY and use /fallback only when you want paid backup."].join(`
1729
+ `)}var ct={},Mt=null,kt=null,_o=[];function on(){let t=process.env.NEX_MOCK_PROVIDER==="1";if(Object.keys(ct).length>0){if(t&&!ct.mock){let{MockProvider:s}=Bc();cs("mock",new s)}t&&ct.mock&&Mt!=="mock"&&(Mt="mock",kt=ct.mock.defaultModel||"mock-model",_o=[],Oi());return}if(cs("ollama",new dP),cs("openai",new pP),cs("deepseek",new hP),cs("anthropic",new mP),cs("gemini",new gP),cs("local",new yP),t){let{MockProvider:s}=Bc();cs("mock",new s)}let e=process.env.DEFAULT_PROVIDER||"ollama",n=process.env.DEFAULT_MODEL||null;t?(Mt="mock",kt=ct.mock?.defaultModel||"mock-model",_o=[]):ct[e]?(Mt=e,kt=n||ct[e].defaultModel):(Mt="ollama",kt="kimi-k2.5");let o=process.env.FALLBACK_CHAIN;o&&(_o=o.split(",").map(s=>s.trim()).filter(Boolean))}function cs(t,e){ct[t]=e}function $P(t){return on(),ct[t]||null}function Sf(){return on(),ct[Mt]||null}function kP(){return on(),Mt}function xP(){return on(),kt}function vP(){on();let t=Sf();if(!t)return{id:kt,name:kt,provider:Mt};let e=t.getModel(kt);return e?{...e,provider:Mt}:{id:kt,name:kt,provider:Mt}}function Ef(t){if(!t)return{provider:null,model:null};let e=t.indexOf(":");if(e>0){let n=t.slice(0,e);if(ct[n]||["ollama","openai","deepseek","anthropic","gemini","local","mock"].includes(n))return{provider:n,model:t.slice(e+1)}}return{provider:null,model:t}}function SP(t){on();let{provider:e,model:n}=Ef(t);if(e){let s=ct[e];return s&&(s.getModel(n)||e==="local"||e==="ollama")?(Mt=e,kt=n,Oi(),!0):!1}let o=Sf();if(o&&o.getModel(n))return kt=n,Oi(),!0;for(let[s,r]of Object.entries(ct))if(r.getModel(n))return Mt=s,kt=n,Oi(),!0;return!1}function Oi(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=kd();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=Fn();t()}catch{}}function EP(){on();let t=new Set;for(let e of Object.values(ct))for(let n of e.getModelNames())t.add(n);return Array.from(t)}function TP(){return on(),Object.entries(ct).map(([t,e])=>({provider:t,configured:e.isConfigured(),models:Object.values(e.getModels()).map(n=>({...n,active:t===Mt&&n.id===kt}))}))}function RP(){on();let t=[];for(let[e,n]of Object.entries(ct)){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 CP(t="coding",e={}){on();let n=e.limit||5,o=e.configuredOnly!==!1,s=[],r=ct.ollama;if(r&&(!o||r.isConfigured()))for(let i of fP(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(ct)){if(i==="ollama"||o&&!a.isConfigured())continue;let l=a.getModel(a.defaultModel);if(l&&(s.push({...l,spec:`${i}:${l.id}`,provider:i,configured:a.isConfigured()}),s.length>=n))break}return s}function AP(t){_o=Array.isArray(t)?t:[]}function OP(){return[..._o]}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 V0(t){let e=[Mt,..._o.filter(r=>r!==Mt)],n,o=0,s=0;for(let r=0;r<e.length;r++){let i=e[r],a=ct[i];if(!a||!a.isConfigured())continue;s++;let l=bP(i);if(!l.allowed){o++,n=new Error(`Budget limit reached for ${i}: $${l.spent.toFixed(2)} / $${l.limit.toFixed(2)}`);continue}let c=r>0,u=c?K0(kt,i):kt;try{if(c){let d=_P(i).label;process.stderr.write(` [fallback: ${i}:${u} \xB7 ${d}]
1730
1730
  `)}return await t(a,i,u)}catch(d){if(n=d,!Y0(d)||r>=e.length-1)throw d;if(i==="ollama"&&xf.length>0){let f=u;for(let p of xf)if(p!==f)try{return process.stderr.write(` [ollama fallback: ${p}]
1731
- `),await t(a,i,p)}catch(h){if(n=h,!Y0(h))throw h}}continue}}throw s>0&&s===o?new Error("All providers are over budget. Use /budget to check limits or /budget <provider> off to remove a limit."):o===0?new Error(Ql()):n||new Error(Ql())}async function PP(t,e,n={}){on();let s=n.model,o=s?(()=>{let{model:i}=Ef(s);return i||s})():void 0,r=o!==s?{...n,model:o}:n;return V0((i,a,l)=>i.stream(t,e,{model:l,signal:r.signal,...r}))}async function MP(t,e,n={}){if(on(),n.provider){let s=ct[n.provider];if(!s||!s.isConfigured()){let r=wP(n.provider);throw new Error(`Provider '${n.provider}' is not available (${r}).
1732
- `+Ql())}let o={model:n.model||kt,...n};try{return await s.chat(t,e,o)}catch(r){if(typeof s.stream=="function")try{return await s.stream(t,e,{...o,onToken:()=>{}})}catch{}throw r}}return V0(async(s,o,r)=>{try{return await s.chat(t,e,{model:r,...n})}catch(i){if(typeof s.stream=="function")try{return await s.stream(t,e,{model:r,...n,onToken:()=>{}})}catch{}throw i}})}function NP(){on();let t=[];for(let[e,n]of Object.entries(ct))n.isConfigured()&&t.push({name:e,models:Object.values(n.getModels())});return t}function LP(){for(let t of Object.keys(ct))delete ct[t];Mt=null,kt=null,_o=[]}X0.exports={registerProvider:cs,getProvider:$P,getActiveProvider:Sf,getActiveProviderName:kP,getActiveModelId:xP,getActiveModel:vP,setActiveModel:SP,getModelNames:EP,parseModelSpec:Ef,listProviders:TP,listAllModels:RP,recommendModels:CP,callStream:PP,callChat:MP,getConfiguredProviders:NP,setFallbackChain:AP,getFallbackChain:OP,resolveModelForProvider:K0,buildNoConfiguredProviderError:Ql,MODEL_EQUIVALENTS:vf,OLLAMA_FALLBACK_MODELS:xf,_reset:LP}});var{C:U}=xt(),IP=vt(),{TOOL_DEFINITIONS:J0}=Do(),{saveRoutingConfig:jP}=ro();function Rs(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 us(t){return typeof t=="string"?t.toLowerCase():""}function DP(t,e=[]){let n=us(t);return e.some(s=>n.includes(us(s)))}function Af(t,e=[]){let n=us(t);return e.every(s=>n.includes(us(s)))}function e_(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 qP(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 FP(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 Z0(t=""){return/\b(rg|grep|find|fd|ls|dir|sed|awk)\b/i.test(t)}function tc(t,e=[]){return t?.action!=="create"||!Array.isArray(t.tasks)||t.tasks.length===0?!1:Af(Rs(t),e)}function Q0(t,{pathIncludes:e=[],table:n="users",action:s="select",conditionTerms:o=[]}={}){if(!Pi(t)||!Af(t.path,e))return!1;let r=us(t.content);return!r.includes(s)||!r.includes(n)?!1:o.every(i=>DP(r,i))}function BP(t,e=[]){let n=Rs(t);return Af(n,e)}function Tf(t,{pathIncludes:e=[],oldTexts:n=[],newTexts:s=[]}={}){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:"",l=[i,a,...r],c=n.length===0||n.some(d=>l.some(f=>f.includes(d))),u=s.length===0||s.some(d=>l.some(f=>f.includes(d)));return!c||!u?!1:i&&a?!0:Array.isArray(t.patches)&&t.patches.length>0}function Pi(t,{pathIncludes:e=[],contentIncludes:n=[]}={}){return typeof t?.path!="string"||typeof t?.content!="string"||!(e.length===0||e.some(o=>us(t.path).includes(us(o))))?!1:n.length===0||n.every(o=>us(t.content).includes(us(o)))}var Of=[{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=>Pi(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=>Tf(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=>Pi(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=>Tf(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||{},s=n.required||[],o=Object.keys(n.properties||{});return s.every(r=>t[r]!==void 0)&&Object.keys(t).every(r=>o.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(Rs(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=>Pi(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=>Tf(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=>Q0(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=>Pi(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(Rs(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=>Q0(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=Rs(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"&&Z0(t.command)&&/authenticateuser|src\/api\.js/i.test(t.command)?!0:BP(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=Rs(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"?Z0(t.command)&&/src|export|function|module\.exports|exports\./i.test(t.command):/getUserById|export|function|module\.exports|exports\.|src|public|def /i.test(Rs(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"?e_(t.command):tc(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=Rs(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}],t_=[{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"?e_(t.command):tc(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"?qP(t.command):tc(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"?FP(t.command):tc(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)}],sc=[...Of,...t_],Rf=["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 UP(){try{let n=require("path").join(require("os").homedir(),".nex-code","benchmark-results.json");if(!require("fs").existsSync(n))return Rf;let s=JSON.parse(require("fs").readFileSync(n,"utf-8"));return!Array.isArray(s)||s.length===0?Rf:s.filter(o=>typeof o.score=="number"&&o.score>=60).sort((o,r)=>r.score-o.score).slice(0,12).map(o=>o.model)}catch{return Rf}}var Pf=UP(),WP=["minimax-m2.7:cloud","qwen3-coder:480b","devstral-2:123b"],n_=(()=>{let t=Pf.slice(0,3);return t.length>=3?t:WP})(),HP=14,ec={producedToolCall:.2,correctTool:.35,validArgs:.3,schemaCompliant:.15},GP="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 Cf(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},s=[{role:"system",content:GP},{role:"user",content:t.prompt}],o=Date.now();try{let r=await IP.callChat(s,J0,{provider:"ollama",model:e,temperature:0,timeout:9e4});n.latencyMs=Date.now()-o;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],l=-1,c=i[0].function?.name||"unknown",u=!1,d=!1,f=!1;for(let p of i){let h=p.function?.name||"unknown",g=p.function?.arguments||{},w=a.includes(h),k=!1,T=!1,$=0;if(w){let R=J0.find(C=>C.function?.name===h);if(k=!!t.validateArgs(g,R),R){let C=R.function?.parameters||{},M=C.required||[],K=Object.keys(C.properties||{});T=M.every(z=>g[z]!==void 0)&&Object.keys(g).every(z=>K.includes(z))}$=(w?2:0)+(k?1:0)+(T?.5:0)}$>l&&(l=$,c=h,u=w,d=k,f=T)}n.toolCalled=u?c:i[0].function?.name||"unknown",n.correctTool=u,n.validArgs=d,n.schemaCompliant=f}}catch(r){n.latencyMs=Date.now()-o,n.error=r.message.slice(0,120)}return n}function gr(t){return t.error?0:((t.producedToolCall?ec.producedToolCall:0)+(t.correctTool?ec.correctTool:0)+(t.validArgs?ec.validArgs:0)+(t.schemaCompliant?ec.schemaCompliant:0))*100}var s_={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 Mf(t){return Object.entries(t).map(([e,n])=>{let s=n.map(gr),o=s.reduce((a,l)=>a+l,0)/s.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 l=n.filter(u=>s_[u.category]===a);if(l.length===0)continue;let c=l.map(gr).reduce((u,d)=>u+d,0)/l.length;i[a]=Math.round(c*10)/10}return{model:e,score:Math.round(o*10)/10,toolCallRate:r(a=>!a.error&&(a.producedToolCall||a.category==="reasoning")),correctRate:r(a=>a.correctTool),validArgsRate:r(a=>a.validArgs),schemaRate:r(a=>a.schemaCompliant),avgLatency:Math.round(n.reduce((a,l)=>a+l.latencyMs,0)/n.length),errorCount:n.filter(a=>a.error).length,categoryScores:i,results:n}}).sort((e,n)=>n.score-e.score)}function o_(t){return r_(t)}function r_(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=>s_[f.category]===r).length<4)continue;let c=i[0],d=i.filter(f=>c.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 i_(t,e){let n=`nex-code Model Benchmark (${e} tasks \xB7 ollama cloud)`,s=[{label:"#",width:3},{label:"Model",width:26},{label:"Score",width:7},{label:"Tool\u2713",width:7},{label:"Name\u2713",width:7},{label:"Args\u2713",width:7},{label:"Schema\u2713",width:8},{label:"Latency",width:8},{label:"Err",width:4}],o=s.reduce((u,d)=>u+d.width+1,0)+1,r="\u2500".repeat(o);console.log(`
1733
- ${U.bold}${n}${U.reset}`),console.log(r);let i=s.map(u=>u.label.padEnd(u.width)).join(" ");if(console.log(`${U.dim}${i}${U.reset}`),console.log(r),t.forEach((u,d)=>{let f=String(d+1).padEnd(s[0].width),p=u.model.slice(0,s[1].width).padEnd(s[1].width),h=String(u.score).padEnd(s[2].width),g=`${u.toolCallRate}%`.padEnd(s[3].width),w=`${u.correctRate}%`.padEnd(s[4].width),k=`${u.validArgsRate}%`.padEnd(s[5].width),T=`${u.schemaRate}%`.padEnd(s[6].width),$=`${(u.avgLatency/1e3).toFixed(1)}s`.padEnd(s[7].width),R=u.errorCount>0?`${U.red}${u.errorCount}${U.reset}`:`${U.dim}0${U.reset}`,C=u.score>=80?U.green:u.score>=60?U.yellow:U.red,M=d===0?`${U.yellow}${f}${U.reset}`:`${U.dim}${f}${U.reset}`;console.log(`${M} ${C}${p}${U.reset} ${U.bold}${C}${h}${U.reset} ${g} ${w} ${k} ${T} ${U.dim}${$}${U.reset} ${R}`)}),console.log(r),t.length>0){let u=t[0];if(console.log(`
1731
+ `),await t(a,i,p)}catch(h){if(n=h,!Y0(h))throw h}}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(Ql()):n||new Error(Ql())}async function PP(t,e,n={}){on();let o=n.model,s=o?(()=>{let{model:i}=Ef(o);return i||o})():void 0,r=s!==o?{...n,model:s}:n;return V0((i,a,l)=>i.stream(t,e,{model:l,signal:r.signal,...r}))}async function MP(t,e,n={}){if(on(),n.provider){let o=ct[n.provider];if(!o||!o.isConfigured()){let r=wP(n.provider);throw new Error(`Provider '${n.provider}' is not available (${r}).
1732
+ `+Ql())}let s={model:n.model||kt,...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 NP(){on();let t=[];for(let[e,n]of Object.entries(ct))n.isConfigured()&&t.push({name:e,models:Object.values(n.getModels())});return t}function LP(){for(let t of Object.keys(ct))delete ct[t];Mt=null,kt=null,_o=[]}X0.exports={registerProvider:cs,getProvider:$P,getActiveProvider:Sf,getActiveProviderName:kP,getActiveModelId:xP,getActiveModel:vP,setActiveModel:SP,getModelNames:EP,parseModelSpec:Ef,listProviders:TP,listAllModels:RP,recommendModels:CP,callStream:PP,callChat:MP,getConfiguredProviders:NP,setFallbackChain:AP,getFallbackChain:OP,resolveModelForProvider:K0,buildNoConfiguredProviderError:Ql,MODEL_EQUIVALENTS:vf,OLLAMA_FALLBACK_MODELS:xf,_reset:LP}});var{C:U}=xt(),IP=vt(),{TOOL_DEFINITIONS:J0}=Do(),{saveRoutingConfig:jP}=ro();function Rs(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 us(t){return typeof t=="string"?t.toLowerCase():""}function DP(t,e=[]){let n=us(t);return e.some(o=>n.includes(us(o)))}function Af(t,e=[]){let n=us(t);return e.every(o=>n.includes(us(o)))}function e_(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 qP(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 FP(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 Z0(t=""){return/\b(rg|grep|find|fd|ls|dir|sed|awk)\b/i.test(t)}function tc(t,e=[]){return t?.action!=="create"||!Array.isArray(t.tasks)||t.tasks.length===0?!1:Af(Rs(t),e)}function Q0(t,{pathIncludes:e=[],table:n="users",action:o="select",conditionTerms:s=[]}={}){if(!Pi(t)||!Af(t.path,e))return!1;let r=us(t.content);return!r.includes(o)||!r.includes(n)?!1:s.every(i=>DP(r,i))}function BP(t,e=[]){let n=Rs(t);return Af(n,e)}function Tf(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:"",l=[i,a,...r],c=n.length===0||n.some(d=>l.some(f=>f.includes(d))),u=o.length===0||o.some(d=>l.some(f=>f.includes(d)));return!c||!u?!1:i&&a?!0:Array.isArray(t.patches)&&t.patches.length>0}function Pi(t,{pathIncludes:e=[],contentIncludes:n=[]}={}){return typeof t?.path!="string"||typeof t?.content!="string"||!(e.length===0||e.some(s=>us(t.path).includes(us(s))))?!1:n.length===0||n.every(s=>us(t.content).includes(us(s)))}var Of=[{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=>Pi(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=>Tf(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=>Pi(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=>Tf(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(Rs(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=>Pi(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=>Tf(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=>Q0(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=>Pi(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(Rs(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=>Q0(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=Rs(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"&&Z0(t.command)&&/authenticateuser|src\/api\.js/i.test(t.command)?!0:BP(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=Rs(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"?Z0(t.command)&&/src|export|function|module\.exports|exports\./i.test(t.command):/getUserById|export|function|module\.exports|exports\.|src|public|def /i.test(Rs(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"?e_(t.command):tc(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=Rs(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}],t_=[{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"?e_(t.command):tc(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"?qP(t.command):tc(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"?FP(t.command):tc(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)}],sc=[...Of,...t_],Rf=["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 UP(){try{let n=require("path").join(require("os").homedir(),".nex-code","benchmark-results.json");if(!require("fs").existsSync(n))return Rf;let o=JSON.parse(require("fs").readFileSync(n,"utf-8"));return!Array.isArray(o)||o.length===0?Rf: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 Rf}}var Pf=UP(),WP=["minimax-m2.7:cloud","qwen3-coder:480b","devstral-2:123b"],n_=(()=>{let t=Pf.slice(0,3);return t.length>=3?t:WP})(),HP=14,ec={producedToolCall:.2,correctTool:.35,validArgs:.3,schemaCompliant:.15},GP="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 Cf(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:GP},{role:"user",content:t.prompt}],s=Date.now();try{let r=await IP.callChat(o,J0,{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],l=-1,c=i[0].function?.name||"unknown",u=!1,d=!1,f=!1;for(let p of i){let h=p.function?.name||"unknown",g=p.function?.arguments||{},w=a.includes(h),k=!1,T=!1,$=0;if(w){let R=J0.find(C=>C.function?.name===h);if(k=!!t.validateArgs(g,R),R){let C=R.function?.parameters||{},M=C.required||[],K=Object.keys(C.properties||{});T=M.every(z=>g[z]!==void 0)&&Object.keys(g).every(z=>K.includes(z))}$=(w?2:0)+(k?1:0)+(T?.5:0)}$>l&&(l=$,c=h,u=w,d=k,f=T)}n.toolCalled=u?c:i[0].function?.name||"unknown",n.correctTool=u,n.validArgs=d,n.schemaCompliant=f}}catch(r){n.latencyMs=Date.now()-s,n.error=r.message.slice(0,120)}return n}function gr(t){return t.error?0:((t.producedToolCall?ec.producedToolCall:0)+(t.correctTool?ec.correctTool:0)+(t.validArgs?ec.validArgs:0)+(t.schemaCompliant?ec.schemaCompliant:0))*100}var s_={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 Mf(t){return Object.entries(t).map(([e,n])=>{let o=n.map(gr),s=o.reduce((a,l)=>a+l,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 l=n.filter(u=>s_[u.category]===a);if(l.length===0)continue;let c=l.map(gr).reduce((u,d)=>u+d,0)/l.length;i[a]=Math.round(c*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,l)=>a+l.latencyMs,0)/n.length),errorCount:n.filter(a=>a.error).length,categoryScores:i,results:n}}).sort((e,n)=>n.score-e.score)}function o_(t){return r_(t)}function r_(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=>s_[f.category]===r).length<4)continue;let c=i[0],d=i.filter(f=>c.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 i_(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((u,d)=>u+d.width+1,0)+1,r="\u2500".repeat(s);console.log(`
1733
+ ${U.bold}${n}${U.reset}`),console.log(r);let i=o.map(u=>u.label.padEnd(u.width)).join(" ");if(console.log(`${U.dim}${i}${U.reset}`),console.log(r),t.forEach((u,d)=>{let f=String(d+1).padEnd(o[0].width),p=u.model.slice(0,o[1].width).padEnd(o[1].width),h=String(u.score).padEnd(o[2].width),g=`${u.toolCallRate}%`.padEnd(o[3].width),w=`${u.correctRate}%`.padEnd(o[4].width),k=`${u.validArgsRate}%`.padEnd(o[5].width),T=`${u.schemaRate}%`.padEnd(o[6].width),$=`${(u.avgLatency/1e3).toFixed(1)}s`.padEnd(o[7].width),R=u.errorCount>0?`${U.red}${u.errorCount}${U.reset}`:`${U.dim}0${U.reset}`,C=u.score>=80?U.green:u.score>=60?U.yellow:U.red,M=d===0?`${U.yellow}${f}${U.reset}`:`${U.dim}${f}${U.reset}`;console.log(`${M} ${C}${p}${U.reset} ${U.bold}${C}${h}${U.reset} ${g} ${w} ${k} ${T} ${U.dim}${$}${U.reset} ${R}`)}),console.log(r),t.length>0){let u=t[0];if(console.log(`
1734
1734
  ${U.bold}${U.green}Winner: ${u.model}${U.reset} score ${u.score}/100`),t.length>1){let d=(u.score-t[1].score).toFixed(1);console.log(`${U.dim}+${d} pts over ${t[1].model}${U.reset}`)}}let a=t.filter(u=>u.results.some(d=>!d.error&&(!d.correctTool||!d.validArgs)));if(a.length>0){console.log(`${U.bold}Failing tasks:${U.reset}`);for(let u of a){let d=u.results.filter(h=>!h.error&&(!h.correctTool||!h.validArgs));if(d.length===0)continue;let f=u.model.slice(0,22),p=d.map(h=>{if(!h.correctTool){let g=h.toolCalled||"(none)";return`${U.dim}${h.taskId}${U.reset} ${U.red}\u2192${g}${U.reset}`}return`${U.dim}${h.taskId}${U.reset} ${U.yellow}bad-args${U.reset}`});console.log(` ${U.dim}${f.padEnd(22)}${U.reset} ${p.join(" ")}`)}console.log()}if(t.length>=3){let u={},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)&&(u[g.taskId]=(u[g.taskId]||0)+1));let f=Math.ceil(t.length*.5),p=Object.entries(u).filter(([h,g])=>g>=f&&d[h]>=3).sort((h,g)=>g[1]-h[1]);if(p.length>0){console.log(`
1735
1735
  ${U.bold}Systemic failures${U.reset} ${U.dim}(>50% of models fail \u2014 may indicate benchmark design issues)${U.reset}`);for(let[h,g]of p){let w=d[h],k=Math.round(g/w*100),T=k>=80?U.red:U.yellow;console.log(` ${T}${k}%${U.reset} ${U.dim}fail${U.reset} ${h}`)}console.log()}}let l=["coding","frontend","sysadmin","data","agentic","plan","verify"];if(t.some(u=>Object.keys(u.categoryScores).length>1)){console.log(`
1736
- ${U.bold}Best model per task type:${U.reset}`);let u=r_(t);for(let d of l){let f=u[d];if(!f)continue;let p=f.score,h=p>=80?U.green:p>=60?U.yellow:U.red,g=t.filter(k=>k.categoryScores[d]!==void 0).sort((k,T)=>T.categoryScores[d]-k.categoryScores[d])[0],w=g&&g.model!==f.model?`${U.dim} raw leader: ${g.model} (${g.categoryScores[d]}/100)${U.reset}`:"";console.log(` ${U.dim}${d.padEnd(10)}${U.reset} ${h}${f.model}${U.reset} ${U.dim}${p}/100${U.reset}${w}`)}console.log(`${U.dim} Winners use the same conservative routing criteria as auto-update (overall-score floor plus latency tiebreak band).${U.reset}`)}console.log()}function a_(t){if(!(!t||t.length<2))try{let e=o_(t),{loadRoutingConfig:n}=ro(),s=n(),o={...s},r=[],i=new Set(["plan","verify"]);for(let[a,{model:l,score:c}]of Object.entries(e)){let u=i.has(a),d=u?s.phases&&s.phases[a]:s[a];d&&d!==l&&!t.find(p=>p.model===d)||(u?(o.phases||(o.phases={}),o.phases[a]!==l&&(o.phases[a]=l,r.push(`phase:${a}\u2192${l}`))):o[a]!==l&&(o[a]=l,r.push(`${a}\u2192${l}`)))}r.length>0&&(jP(o),console.log(`
1736
+ ${U.bold}Best model per task type:${U.reset}`);let u=r_(t);for(let d of l){let f=u[d];if(!f)continue;let p=f.score,h=p>=80?U.green:p>=60?U.yellow:U.red,g=t.filter(k=>k.categoryScores[d]!==void 0).sort((k,T)=>T.categoryScores[d]-k.categoryScores[d])[0],w=g&&g.model!==f.model?`${U.dim} raw leader: ${g.model} (${g.categoryScores[d]}/100)${U.reset}`:"";console.log(` ${U.dim}${d.padEnd(10)}${U.reset} ${h}${f.model}${U.reset} ${U.dim}${p}/100${U.reset}${w}`)}console.log(`${U.dim} Winners use the same conservative routing criteria as auto-update (overall-score floor plus latency tiebreak band).${U.reset}`)}console.log()}function a_(t){if(!(!t||t.length<2))try{let e=o_(t),{loadRoutingConfig:n}=ro(),o=n(),s={...o},r=[],i=new Set(["plan","verify"]);for(let[a,{model:l,score:c}]of Object.entries(e)){let u=i.has(a),d=u?o.phases&&o.phases[a]:o[a];d&&d!==l&&!t.find(p=>p.model===d)||(u?(s.phases||(s.phases={}),s.phases[a]!==l&&(s.phases[a]=l,r.push(`phase:${a}\u2192${l}`))):s[a]!==l&&(s[a]=l,r.push(`${a}\u2192${l}`)))}r.length>0&&(jP(s),console.log(`
1737
1737
  ${U.dim} Routing updated: ${r.join(", ")}${U.reset}`),console.log(`
1738
- ${U.green}\u{1F4A1} The best models have been saved to ~/.nex-code/.env and will be automatically used by nex-code from now on.${U.reset}`))}catch{}}async function YP({models:t,quick:e=!1,onProgress:n,parallelModels:s=1}={}){let o=e?Of.slice(0,HP):sc,r=t?.length>0?t:e?n_:Pf,i={};for(let l of r)i[l]=[];if(s<=1)for(let l of r)for(let c of o){n?.({model:l,task:c.id,done:!1});let u=await Cf(c,l);i[l].push(u),n?.({model:l,task:c.id,done:!0,score:gr(u),error:u.error})}else{let l=Math.min(s,r.length),c=[...r],u=Array.from({length:l},async()=>{for(;c.length>0;){let d=c.shift();if(!d)break;for(let f of o){n?.({model:d,task:f.id,done:!1});let p=await Cf(f,d);i[d].push(p),n?.({model:d,task:f.id,done:!0,score:gr(p),error:p.error})}}});await Promise.all(u)}let a=Mf(i);return i_(a,o.length),a_(a),a}async function zP({newModels:t,existingRanking:e=[],onProgress:n}={}){if(!t||t.length===0)return e;let s={};for(let i of t){s[i]=[];for(let a of sc){n?.({model:i,task:a.id,done:!1});let l=await Cf(a,i);s[i].push(l),n?.({model:i,task:a.id,done:!0,score:gr(l),error:l.error})}}let r=[...Mf(s)];for(let i of e)r.find(a=>a.model===i.model)||r.push(i);return r.sort((i,a)=>a.score-i.score),i_(r,sc.length),a_(r),r}var nc=[{id:"simple_question",name:"Simple Convergence",prompt:"What is 2+2?",maxTurns:3,successCriteria:["4"]}];function l_(t){let e=require("fs"),s=require("path").join(t||process.cwd(),".nex","benchmark-config.json");if(!e.existsSync(s))return console.log(`${U.yellow}No scenarios configured.${U.reset} Create ${U.dim}.nex/benchmark-config.json${U.reset} to define your benchmark scenarios.
1738
+ ${U.green}\u{1F4A1} The best models have been saved to ~/.nex-code/.env and will be automatically used by nex-code from now on.${U.reset}`))}catch{}}async function YP({models:t,quick:e=!1,onProgress:n,parallelModels:o=1}={}){let s=e?Of.slice(0,HP):sc,r=t?.length>0?t:e?n_:Pf,i={};for(let l of r)i[l]=[];if(o<=1)for(let l of r)for(let c of s){n?.({model:l,task:c.id,done:!1});let u=await Cf(c,l);i[l].push(u),n?.({model:l,task:c.id,done:!0,score:gr(u),error:u.error})}else{let l=Math.min(o,r.length),c=[...r],u=Array.from({length:l},async()=>{for(;c.length>0;){let d=c.shift();if(!d)break;for(let f of s){n?.({model:d,task:f.id,done:!1});let p=await Cf(f,d);i[d].push(p),n?.({model:d,task:f.id,done:!0,score:gr(p),error:p.error})}}});await Promise.all(u)}let a=Mf(i);return i_(a,s.length),a_(a),a}async function zP({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 sc){n?.({model:i,task:a.id,done:!1});let l=await Cf(a,i);o[i].push(l),n?.({model:i,task:a.id,done:!0,score:gr(l),error:l.error})}}let r=[...Mf(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),i_(r,sc.length),a_(r),r}var nc=[{id:"simple_question",name:"Simple Convergence",prompt:"What is 2+2?",maxTurns:3,successCriteria:["4"]}];function l_(t){let e=require("fs"),o=require("path").join(t||process.cwd(),".nex","benchmark-config.json");if(!e.existsSync(o))return console.log(`${U.yellow}No scenarios configured.${U.reset} Create ${U.dim}.nex/benchmark-config.json${U.reset} to define your benchmark scenarios.
1739
1739
  Example:
1740
1740
  {
1741
1741
  "scenarios": [
@@ -1748,14 +1748,14 @@ ${U.green}\u{1F4A1} The best models have been saved to ~/.nex-code/.env and will
1748
1748
  }
1749
1749
  ]
1750
1750
  }
1751
- `),nc;try{let o=JSON.parse(e.readFileSync(s,"utf-8"));return!Array.isArray(o.scenarios)||o.scenarios.length===0?(console.log(`${U.yellow}benchmark-config.json has no scenarios \u2014 using defaults.${U.reset}
1752
- `),nc):o.scenarios}catch(o){return console.log(`${U.yellow}Failed to parse benchmark-config.json: ${o.message}${U.reset}
1753
- `),nc}}function c_(t,e){let{scoreMessages:n,_extractToolCalls:s,_getLastAssistantText:o}=fl(),r=n(t),i=r.score,a=[],l=o(t).toLowerCase();e.successCriteria.every(f=>l.includes(f.toLowerCase()))&&(i=Math.min(10,i+1),a.push("+1.0 all success criteria met"));let u=s(t);u.length<e.maxTurns/2&&(i=Math.min(10,i+.5),a.push(`+0.5 efficient (${u.length} tool calls < ${e.maxTurns/2})`)),i=Math.round(i*10)/10;let d=i>=9?"A":i>=8?"B":i>=7?"C":i>=6?"D":"F";return{score:i,grade:d,issues:r.issues,summary:r.summary,bonuses:a}}async function KP(t,e={}){let{spawn:n}=require("child_process"),s=require("fs"),o=require("path"),r=require("os"),i=o.join(r.tmpdir(),`nex-bench-${t.id}-${Date.now()}.txt`);s.writeFileSync(i,t.prompt,"utf-8");let a=o.resolve(__dirname,"..","bin","nex-code.js"),l=e.cwd||process.cwd(),c=[a,"--prompt-file",i,"--delete-prompt-file","--auto","--max-turns",String(t.maxTurns)];return e.model&&c.push("--model",e.model),new Promise(u=>{let d=n(process.execPath,c,{cwd:l,stdio:["ignore","pipe","pipe"],env:{...process.env}}),f=t.maxTurns*60*1e3,p=!1,h=setTimeout(()=>{p=!0;try{d.kill("SIGTERM")}catch{}},f);d.on("close",g=>{clearTimeout(h);try{s.unlinkSync(i)}catch{}let w=o.join(l,".nex","sessions","_autosave.json"),k=[];if(s.existsSync(w))try{k=JSON.parse(s.readFileSync(w,"utf-8")).messages||[]}catch{}u({messages:k,exitCode:g||0,timedOut:p})}),d.stdout.resume(),d.stderr.resume()})}function VP(t,e,n){let s=t.length>0?Math.round(t.reduce((l,c)=>l+c.score,0)/t.length*10)/10:0,o=s>=9?"A":s>=8?"B":s>=7?"C":s>=6?"D":"F",r=57,i="\u2500".repeat(r);console.log(`
1754
- \u250C\u2500 Benchmark Results ${"\u2500".repeat(r-19)}\u2510`);for(let l of t){let c=l.id.padEnd(20),u=l.name.substring(0,26).padEnd(26),d=`${l.score}/10`.padStart(6),f=l.grade.padStart(2);console.log(`\u2502 ${c} ${u} ${d} ${f} \u2502`)}console.log(`\u2502 ${" ".repeat(r-2)} \u2502`);let a=`Overall: ${s}/10 (${o}) \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
1755
- `)}function XP(t=10){let e=require("fs"),s=require("path").join(process.cwd(),".nex","benchmark-history.json");if(!e.existsSync(s)){console.log(`${U.yellow}No score history yet. Run a session first.${U.reset}
1756
- `);return}let o=[];try{o=JSON.parse(e.readFileSync(s,"utf-8"))}catch{o=[]}if(!Array.isArray(o)||o.length===0){console.log(`${U.yellow}Score history is empty.${U.reset}
1757
- `);return}let r=o.slice(-t);console.log(`
1758
- ${U.bold}Score History (last ${r.length} session${r.length===1?"":"s"}):${U.reset}`);for(let i of r){let a=(i.date||"").replace("T"," ").substring(0,16),l=(i.version||"?").padEnd(8),c=(i.model||"?").substring(0,12).padEnd(12),u=`${i.score}/10`.padStart(6),d=i.grade||"?",f=i.issues&&i.issues.length>0?`${U.yellow}\u26A0 ${i.issues.slice(0,2).map(h=>h.substring(0,30)).join(", ")}${U.reset}`:`${U.green}\u2713${U.reset}`,p=i.score>=8?U.green:i.score>=6?U.yellow:U.red;console.log(` ${U.dim}${a}${U.reset} ${U.dim}v${l}${U.reset} ${U.dim}${c}${U.reset} ${p}${u} ${d}${U.reset} ${f}`)}console.log()}async function JP({dryRun:t=!1,model:e,cwd:n,onProgress:s}={}){let o=Yi(),r=l_(n);if(t){console.log(`
1751
+ `),nc;try{let s=JSON.parse(e.readFileSync(o,"utf-8"));return!Array.isArray(s.scenarios)||s.scenarios.length===0?(console.log(`${U.yellow}benchmark-config.json has no scenarios \u2014 using defaults.${U.reset}
1752
+ `),nc):s.scenarios}catch(s){return console.log(`${U.yellow}Failed to parse benchmark-config.json: ${s.message}${U.reset}
1753
+ `),nc}}function c_(t,e){let{scoreMessages:n,_extractToolCalls:o,_getLastAssistantText:s}=fl(),r=n(t),i=r.score,a=[],l=s(t).toLowerCase();e.successCriteria.every(f=>l.includes(f.toLowerCase()))&&(i=Math.min(10,i+1),a.push("+1.0 all success criteria met"));let u=o(t);u.length<e.maxTurns/2&&(i=Math.min(10,i+.5),a.push(`+0.5 efficient (${u.length} tool calls < ${e.maxTurns/2})`)),i=Math.round(i*10)/10;let d=i>=9?"A":i>=8?"B":i>=7?"C":i>=6?"D":"F";return{score:i,grade:d,issues:r.issues,summary:r.summary,bonuses:a}}async function KP(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"),l=e.cwd||process.cwd(),c=[a,"--prompt-file",i,"--delete-prompt-file","--auto","--max-turns",String(t.maxTurns)];return e.model&&c.push("--model",e.model),new Promise(u=>{let d=n(process.execPath,c,{cwd:l,stdio:["ignore","pipe","pipe"],env:{...process.env}}),f=t.maxTurns*60*1e3,p=!1,h=setTimeout(()=>{p=!0;try{d.kill("SIGTERM")}catch{}},f);d.on("close",g=>{clearTimeout(h);try{o.unlinkSync(i)}catch{}let w=s.join(l,".nex","sessions","_autosave.json"),k=[];if(o.existsSync(w))try{k=JSON.parse(o.readFileSync(w,"utf-8")).messages||[]}catch{}u({messages:k,exitCode:g||0,timedOut:p})}),d.stdout.resume(),d.stderr.resume()})}function VP(t,e,n){let o=t.length>0?Math.round(t.reduce((l,c)=>l+c.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(`
1754
+ \u250C\u2500 Benchmark Results ${"\u2500".repeat(r-19)}\u2510`);for(let l of t){let c=l.id.padEnd(20),u=l.name.substring(0,26).padEnd(26),d=`${l.score}/10`.padStart(6),f=l.grade.padStart(2);console.log(`\u2502 ${c} ${u} ${d} ${f} \u2502`)}console.log(`\u2502 ${" ".repeat(r-2)} \u2502`);let a=`Overall: ${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
1755
+ `)}function XP(t=10){let e=require("fs"),o=require("path").join(process.cwd(),".nex","benchmark-history.json");if(!e.existsSync(o)){console.log(`${U.yellow}No score history yet. Run a session first.${U.reset}
1756
+ `);return}let s=[];try{s=JSON.parse(e.readFileSync(o,"utf-8"))}catch{s=[]}if(!Array.isArray(s)||s.length===0){console.log(`${U.yellow}Score history is empty.${U.reset}
1757
+ `);return}let r=s.slice(-t);console.log(`
1758
+ ${U.bold}Score History (last ${r.length} session${r.length===1?"":"s"}):${U.reset}`);for(let i of r){let a=(i.date||"").replace("T"," ").substring(0,16),l=(i.version||"?").padEnd(8),c=(i.model||"?").substring(0,12).padEnd(12),u=`${i.score}/10`.padStart(6),d=i.grade||"?",f=i.issues&&i.issues.length>0?`${U.yellow}\u26A0 ${i.issues.slice(0,2).map(h=>h.substring(0,30)).join(", ")}${U.reset}`:`${U.green}\u2713${U.reset}`,p=i.score>=8?U.green:i.score>=6?U.yellow:U.red;console.log(` ${U.dim}${a}${U.reset} ${U.dim}v${l}${U.reset} ${U.dim}${c}${U.reset} ${p}${u} ${d}${U.reset} ${f}`)}console.log()}async function JP({dryRun:t=!1,model:e,cwd:n,onProgress:o}={}){let s=Yi(),r=l_(n);if(t){console.log(`
1759
1759
  ${U.bold}Scenario Benchmark \u2014 Scenarios (dry-run):${U.reset}
1760
- `);for(let l of r)console.log(` ${U.cyan}${l.id.padEnd(20)}${U.reset} ${U.dim}${l.name}${U.reset} maxTurns=${l.maxTurns}`),console.log(` ${U.dim}${l.prompt.substring(0,80)}${U.reset}`);return console.log(),[]}let i=(()=>{if(e)return typeof e=="object"?e.id||"unknown":e;try{let{getActiveModel:l}=kr(),c=l?l():null;return c?typeof c=="object"?c.id||"unknown":c:"unknown"}catch{return"unknown"}})(),a=[];for(let l of r){s?.({id:l.id,name:l.name,done:!1}),console.log(`
1761
- ${U.dim}Running scenario: ${l.name}...${U.reset}`);let{messages:c,timedOut:u}=await KP(l,{model:i,cwd:n}),d;u||c.length===0?d={score:0,grade:"F",issues:[u?"Scenario timed out":"No messages produced"],summary:"No output",bonuses:[]}:d=c_(c,l);let f={id:l.id,name:l.name,score:d.score,grade:d.grade,issues:d.issues,bonuses:d.bonuses};a.push(f),s?.({id:l.id,name:l.name,done:!0,score:d.score,grade:d.grade});try{let{appendScoreHistory:p}=fl();p(d.score,{version:o.version,model:i,sessionName:`bench:${l.id}`,issues:d.issues})}catch{}}return VP(a,o.version,i),a}module.exports={runBenchmark:YP,runDiscoverBenchmark:zP,buildSummary:Mf,buildCategoryWinners:o_,TASKS:Of,PHASE_TASKS:t_,ALL_TASKS:sc,scoreResult:gr,DEFAULT_MODELS:Pf,QUICK_MODELS:n_,runScenarioBenchmark:JP,showScoreTrend:XP,loadScenarios:l_,DEFAULT_SCENARIOS:nc,scoreScenario:c_};
1760
+ `);for(let l of r)console.log(` ${U.cyan}${l.id.padEnd(20)}${U.reset} ${U.dim}${l.name}${U.reset} maxTurns=${l.maxTurns}`),console.log(` ${U.dim}${l.prompt.substring(0,80)}${U.reset}`);return console.log(),[]}let i=(()=>{if(e)return typeof e=="object"?e.id||"unknown":e;try{let{getActiveModel:l}=kr(),c=l?l():null;return c?typeof c=="object"?c.id||"unknown":c:"unknown"}catch{return"unknown"}})(),a=[];for(let l of r){o?.({id:l.id,name:l.name,done:!1}),console.log(`
1761
+ ${U.dim}Running scenario: ${l.name}...${U.reset}`);let{messages:c,timedOut:u}=await KP(l,{model:i,cwd:n}),d;u||c.length===0?d={score:0,grade:"F",issues:[u?"Scenario timed out":"No messages produced"],summary:"No output",bonuses:[]}:d=c_(c,l);let f={id:l.id,name:l.name,score:d.score,grade:d.grade,issues:d.issues,bonuses:d.bonuses};a.push(f),o?.({id:l.id,name:l.name,done:!0,score:d.score,grade:d.grade});try{let{appendScoreHistory:p}=fl();p(d.score,{version:s.version,model:i,sessionName:`bench:${l.id}`,issues:d.issues})}catch{}}return VP(a,s.version,i),a}module.exports={runBenchmark:YP,runDiscoverBenchmark:zP,buildSummary:Mf,buildCategoryWinners:o_,TASKS:Of,PHASE_TASKS:t_,ALL_TASKS:sc,scoreResult:gr,DEFAULT_MODELS:Pf,QUICK_MODELS:n_,runScenarioBenchmark:JP,showScoreTrend:XP,loadScenarios:l_,DEFAULT_SCENARIOS:nc,scoreScenario:c_};