nex-code 0.4.37 → 0.4.39

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,132 +1,132 @@
1
- "use strict";var se=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var ks=se((rk,Jc)=>{"use strict";var Gc="\x1B[0m",Yc="\x1B[1m",Wn="\x1B[2m";function Y(t,e,s){return`\x1B[38;2;${t};${e};${s}m`}function Zh(){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 Kc(){let t=require("os");return require("path").join(t.homedir(),".nex-code",".theme_cache.json")}function Qh(t){try{let s=require("fs").readFileSync(Kc(),"utf8"),n=JSON.parse(s);if(n&&typeof n[t]=="boolean")return n[t]}catch{}return null}function em(t,e){try{let s=require("fs"),n=require("path"),o=Kc(),r=n.dirname(o),i={};try{i=JSON.parse(s.readFileSync(o,"utf8"))}catch{}i[t]=e;let a=Object.keys(i);a.length>50&&a.slice(0,a.length-50).forEach(c=>delete i[c]),s.existsSync(r)||s.mkdirSync(r,{recursive:!0}),s.writeFileSync(o,JSON.stringify(i),"utf8")}catch{}}function tm(){let t=(process.env.NEX_THEME||"").toLowerCase();if(t==="light")return!1;if(t==="dark")return!0;let e=process.env.COLORFGBG;if(e){let i=e.split(";"),a=parseInt(i[i.length-1],10);if(!isNaN(a))return a<8}let s=process.env.TERM_SESSION_ID||"default",n=Qh(s);if(n!==null)return n;let o=Zh(),r=o!==null?o:!0;return em(s,r),r}var zc=tm(),Xc={reset:Gc,bold:Yc,dim:Wn,primary:Y(80,190,255),secondary:Y(60,170,190),success:Y(80,210,120),warning:Y(245,175,50),error:Y(230,80,80),muted:Wn,subtle:Y(130,130,145),tool_read:Y(80,190,255),tool_write:Y(245,165,55),tool_exec:Y(185,100,235),tool_search:Y(70,185,190),tool_git:Y(90,210,100),tool_web:Y(100,215,250),tool_sysadmin:Y(225,150,75),tool_default:Y(100,205,115),syn_keyword:Y(185,100,235),syn_string:Y(90,210,120),syn_number:Y(245,175,50),syn_comment:Wn,syn_key:Y(80,190,255),diff_add:Y(80,210,120),diff_rem:Y(230,80,80),banner_logo:Y(80,200,255),banner_name:Y(80,200,255),banner_version:Wn,banner_model:Wn,banner_yolo:Y(245,175,50),footer_sep:Wn,footer_model:Y(80,175,235),footer_branch:Y(80,210,100),footer_project:Y(130,130,145),footer_divider:Y(80,80,95),footer_mode:Y(210,150,50),white:"\x1B[37m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",gray:"\x1B[90m",bgRed:"\x1B[41m",bgGreen:"\x1B[42m",diff_add_bg:"\x1B[48;2;10;46;20m",diff_rem_bg:"\x1B[48;2;58;16;16m",brightCyan:"\x1B[96m",brightMagenta:"\x1B[95m",brightBlue:"\x1B[94m"},Vc={reset:Gc,bold:Yc,dim:Y(110,110,120),primary:Y(0,110,190),secondary:Y(0,125,148),success:Y(0,148,62),warning:Y(168,92,0),error:Y(188,32,32),muted:Y(110,110,120),subtle:Y(155,155,165),tool_read:Y(0,110,190),tool_write:Y(168,92,0),tool_exec:Y(128,42,188),tool_search:Y(0,122,148),tool_git:Y(0,138,62),tool_web:Y(0,112,178),tool_sysadmin:Y(168,82,0),tool_default:Y(0,138,62),syn_keyword:Y(128,42,188),syn_string:Y(0,138,62),syn_number:Y(168,92,0),syn_comment:Y(135,135,148),syn_key:Y(0,110,190),diff_add:Y(0,148,62),diff_rem:Y(188,32,32),banner_logo:Y(0,122,205),banner_name:Y(0,122,205),banner_version:Y(100,100,118),banner_model:Y(100,100,118),banner_yolo:Y(168,62,0),footer_sep:Y(168,168,178),footer_model:Y(0,102,175),footer_branch:Y(0,138,62),footer_project:Y(135,135,148),footer_divider:Y(168,168,178),footer_mode:Y(148,88,0),white:Y(40,40,52),red:Y(188,32,32),green:Y(0,148,62),yellow:Y(168,92,0),blue:Y(0,110,190),magenta:Y(128,42,188),cyan:Y(0,125,148),gray:Y(132,132,142),bgRed:"\x1B[41m",bgGreen:"\x1B[42m",diff_add_bg:"\x1B[48;2;215;245;220m",diff_rem_bg:"\x1B[48;2;255;215;215m",brightCyan:Y(0,158,182),brightMagenta:Y(158,52,208),brightBlue:Y(0,112,208)},nm=zc?Xc:Vc;Jc.exports={T:nm,isDark:zc,DARK:Xc,LIGHT:Vc}});var No=se((ik,sm)=>{sm.exports={name:"nex-code",version:"0.4.37",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:"esbuild bin/nex-code.js --bundle --platform=node --target=node18 --outfile=dist/nex-code.js --minify --external:axios --external:dotenv --external:playwright && esbuild cli/benchmark.js --bundle --platform=node --target=node18 --outfile=dist/benchmark.js --minify --external:axios --external:dotenv --external:playwright && rm -rf dist/skills && cp -r cli/skills dist/skills",dev:"esbuild bin/nex-code.js --bundle --platform=node --target=node18 --outfile=dist/nex-code.js --external:axios --external:dotenv --external:playwright --watch",test:"jest --forceExit","test:orchestrator":"jest tests/orchestrator.test.js --forceExit",coverage:"jest --coverage --forceExit","test:watch":"jest --watch",typecheck:"tsc --noEmit",format:"prettier --write .","install-hooks":"ln -sf ../../hooks/pre-push .git/hooks/pre-push && chmod +x .git/hooks/pre-push && ln -sf ../../hooks/post-merge .git/hooks/post-merge && chmod +x .git/hooks/post-merge && echo 'Hooks installed (pre-push, post-merge).'",prepublishOnly:"npm run build && npm test","merge-to-main":"bash scripts/merge-to-main.sh",improve:"node scripts/improve.js","extract-examples":"node scripts/extract-examples.js","benchmark:realworld":"node scripts/benchmark-realworld.js",release:"npm version patch && git push --follow-tags && npm publish"},keywords:["ai","cli","coding","agent","ollama","ollama-cloud","openai","anthropic","claude","gemini","llm","gpt","agentic","terminal","coding-assistant","claude-code-alternative","gemini-cli-alternative","open-source","free","qwen3","devstral","kimi-k2","deepseek","local-llm","mcp","model-context-protocol","multi-provider"],repository:{type:"git",url:"https://github.com/hybridpicker/nex-code.git"},bugs:{url:"https://github.com/hybridpicker/nex-code/issues"},homepage:"https://github.com/hybridpicker/nex-code#readme",license:"MIT",dependencies:{axios:"^1.7.0",dotenv:"^16.4.0"},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 Hn=se((ak,Qc)=>{var{T:Z}=ks(),Po=5,Un=(()=>{let t=[];for(let e=0;e<Po;e++)t.push(e);for(let e=Po-2;e>=1;e--)t.push(e);return t})(),Zc=["\u273D","\u2726","\u2727","\u2726"],gi=class{constructor(e="Thinking..."){this.text=e,this.frame=0,this.interval=null,this.startTime=null}_render(){if(this._stopped)return;let e=Un[this.frame%Un.length],s="";for(let o=0;o<Po;o++)s+=o===e?`${Z.cyan}\u25CF${Z.reset}`:" ";let n="";if(this.startTime){let o=Math.floor((Date.now()-this.startTime)/1e3);if(o>=60){let r=Math.floor(o/60),i=o%60;n=` ${Z.dim}${r}m ${String(i).padStart(2,"0")}s${Z.reset}`}else o>=1&&(n=` ${Z.dim}${o}s${Z.reset}`)}process.stderr.write(`\x1B[2K\r${s} ${Z.dim}${this.text}${Z.reset}${n}`),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),process.stderr.isTTY&&(process.stderr.write("\x1B[?25l"),this._render(),this.interval=setInterval(()=>this._render(),100))}update(e){this.text=e}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),process.stderr.isTTY&&process.stderr.write("\x1B[2K\r\x1B[?25h"),this.startTime=null}},yi=class{constructor(e){this.labels=e,this.statuses=e.map(()=>"running"),this.frame=0,this.interval=null,this.startTime=null,this.lineCount=e.length}_formatElapsed(){if(!this.startTime)return"";let e=Math.floor((Date.now()-this.startTime)/1e3);if(e<1)return"";let s=Math.floor(e/60),n=e%60;return s>0?`${s}m ${String(n).padStart(2,"0")}s`:`${n}s`}_render(){if(this._stopped)return;let e=Un[this.frame%Un.length],s=`${Z.cyan}\u25CF${Z.reset}`,n=this._formatElapsed(),o=n?` ${Z.dim}${n}${Z.reset}`:"",r=process.stderr.columns||80,i="";for(let a=0;a<this.labels.length;a++){let c,l;switch(this.statuses[a]){case"done":c=`${Z.green}\u2713${Z.reset}`,l=Z.dim;break;case"error":c=`${Z.red}\u2717${Z.reset}`,l=Z.dim;break;case"retry":c=`${Z.yellow}\u21BB${Z.reset}`,l=Z.yellow;break;default:c=a===e?s:" ",l=""}let u=a===this.labels.length-1?o:"",d=r-4-(u?n.length+1:0),f=this.labels[a].length>d?this.labels[a].substring(0,Math.max(10,d-3))+"...":this.labels[a];i+=`\x1B[2K ${c} ${l}${f}${Z.reset}${u}
1
+ "use strict";var re=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Es=re((Ek,ul)=>{"use strict";var ol="\x1B[0m",rl="\x1B[1m",Gn="\x1B[2m";function z(t,e,s){return`\x1B[38;2;${t};${e};${s}m`}function cm(){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 il(){let t=require("os");return require("path").join(t.homedir(),".nex-code",".theme_cache.json")}function lm(t){try{let s=require("fs").readFileSync(il(),"utf8"),n=JSON.parse(s);if(n&&typeof n[t]=="boolean")return n[t]}catch{}return null}function um(t,e){try{let s=require("fs"),n=require("path"),o=il(),r=n.dirname(o),i={};try{i=JSON.parse(s.readFileSync(o,"utf8"))}catch{}i[t]=e;let a=Object.keys(i);a.length>50&&a.slice(0,a.length-50).forEach(c=>delete i[c]),s.existsSync(r)||s.mkdirSync(r,{recursive:!0}),s.writeFileSync(o,JSON.stringify(i),"utf8")}catch{}}function dm(){let t=(process.env.NEX_THEME||"").toLowerCase();if(t==="light")return!1;if(t==="dark")return!0;let e=process.env.COLORFGBG;if(e){let i=e.split(";"),a=parseInt(i[i.length-1],10);if(!isNaN(a))return a<8}let s=process.env.TERM_SESSION_ID||"default",n=lm(s);if(n!==null)return n;let o=cm(),r=o!==null?o:!0;return um(s,r),r}var al=dm(),cl={reset:ol,bold:rl,dim:Gn,primary:z(80,190,255),secondary:z(60,170,190),success:z(80,210,120),warning:z(245,175,50),error:z(230,80,80),muted:Gn,subtle:z(130,130,145),tool_read:z(80,190,255),tool_write:z(245,165,55),tool_exec:z(185,100,235),tool_search:z(70,185,190),tool_git:z(90,210,100),tool_web:z(100,215,250),tool_sysadmin:z(225,150,75),tool_default:z(100,205,115),syn_keyword:z(185,100,235),syn_string:z(90,210,120),syn_number:z(245,175,50),syn_comment:Gn,syn_key:z(80,190,255),diff_add:z(80,210,120),diff_rem:z(230,80,80),banner_logo:z(80,200,255),banner_name:z(80,200,255),banner_version:Gn,banner_model:Gn,banner_yolo:z(245,175,50),footer_sep:Gn,footer_model:z(80,175,235),footer_branch:z(80,210,100),footer_project:z(130,130,145),footer_divider:z(80,80,95),footer_mode:z(210,150,50),white:"\x1B[37m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",gray:"\x1B[90m",bgRed:"\x1B[41m",bgGreen:"\x1B[42m",diff_add_bg:"\x1B[48;2;10;46;20m",diff_rem_bg:"\x1B[48;2;58;16;16m",brightCyan:"\x1B[96m",brightMagenta:"\x1B[95m",brightBlue:"\x1B[94m"},ll={reset:ol,bold:rl,dim:z(110,110,120),primary:z(0,110,190),secondary:z(0,125,148),success:z(0,148,62),warning:z(168,92,0),error:z(188,32,32),muted:z(110,110,120),subtle:z(155,155,165),tool_read:z(0,110,190),tool_write:z(168,92,0),tool_exec:z(128,42,188),tool_search:z(0,122,148),tool_git:z(0,138,62),tool_web:z(0,112,178),tool_sysadmin:z(168,82,0),tool_default:z(0,138,62),syn_keyword:z(128,42,188),syn_string:z(0,138,62),syn_number:z(168,92,0),syn_comment:z(135,135,148),syn_key:z(0,110,190),diff_add:z(0,148,62),diff_rem:z(188,32,32),banner_logo:z(0,122,205),banner_name:z(0,122,205),banner_version:z(100,100,118),banner_model:z(100,100,118),banner_yolo:z(168,62,0),footer_sep:z(168,168,178),footer_model:z(0,102,175),footer_branch:z(0,138,62),footer_project:z(135,135,148),footer_divider:z(168,168,178),footer_mode:z(148,88,0),white:z(40,40,52),red:z(188,32,32),green:z(0,148,62),yellow:z(168,92,0),blue:z(0,110,190),magenta:z(128,42,188),cyan:z(0,125,148),gray:z(132,132,142),bgRed:"\x1B[41m",bgGreen:"\x1B[42m",diff_add_bg:"\x1B[48;2;215;245;220m",diff_rem_bg:"\x1B[48;2;255;215;215m",brightCyan:z(0,158,182),brightMagenta:z(158,52,208),brightBlue:z(0,112,208)},fm=al?cl:ll;ul.exports={T:fm,isDark:al,DARK:cl,LIGHT:ll}});var Lo=re((Tk,pm)=>{pm.exports={name:"nex-code",version:"0.4.39",description:"Run 400B+ open coding models on your codebase without the hardware bill. Ollama Cloud first \u2014 OpenAI, Anthropic, and Gemini when you need them.",bin:{"nex-code":"./dist/nex-code.js"},files:["dist/","examples/","README.md","LICENSE"],engines:{node:">=18.0.0"},scripts:{start:"node dist/nex-code.js",build:"node scripts/build.js",dev:"node scripts/build.js --dev",test:"jest --forceExit","test:orchestrator":"jest tests/orchestrator.test.js --forceExit",coverage:"jest --coverage --forceExit","test:watch":"jest --watch",typecheck:"tsc --noEmit",format:"prettier --write .","install-hooks":"ln -sf ../../hooks/pre-push .git/hooks/pre-push && chmod +x .git/hooks/pre-push && ln -sf ../../hooks/post-merge .git/hooks/post-merge && chmod +x .git/hooks/post-merge && echo 'Hooks installed (pre-push, post-merge).'",prepublishOnly:"npm run build && npm test","merge-to-main":"bash scripts/merge-to-main.sh",improve:"node scripts/improve.js","extract-examples":"node scripts/extract-examples.js","benchmark:realworld":"node scripts/benchmark-realworld.js",release:"npm version patch && git push --follow-tags && npm publish"},keywords:["ai","cli","coding","agent","ollama","ollama-cloud","openai","anthropic","gemini","llm","gpt","agentic","terminal","coding-assistant","open-source","free","qwen3","devstral","kimi-k2","deepseek","local-llm","mcp","model-context-protocol","multi-provider"],repository:{type:"git",url:"https://github.com/hybridpicker/nex-code.git"},bugs:{url:"https://github.com/hybridpicker/nex-code/issues"},homepage:"https://github.com/hybridpicker/nex-code#readme",license:"MIT",dependencies:{axios:"^1.7.0",dotenv:"^16.4.0"},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 zn=re((Rk,fl)=>{var{T:te}=Es(),jo=5,Kn=(()=>{let t=[];for(let e=0;e<jo;e++)t.push(e);for(let e=jo-2;e>=1;e--)t.push(e);return t})(),dl=["\u273D","\u2726","\u2727","\u2726"],ki=class{constructor(e="Thinking..."){this.text=e,this.frame=0,this.interval=null,this.startTime=null}_render(){if(this._stopped)return;let e=Kn[this.frame%Kn.length],s="";for(let o=0;o<jo;o++)s+=o===e?`${te.cyan}\u25CF${te.reset}`:" ";let n="";if(this.startTime){let o=Math.floor((Date.now()-this.startTime)/1e3);if(o>=60){let r=Math.floor(o/60),i=o%60;n=` ${te.dim}${r}m ${String(i).padStart(2,"0")}s${te.reset}`}else o>=1&&(n=` ${te.dim}${o}s${te.reset}`)}process.stderr.write(`\x1B[2K\r${s} ${te.dim}${this.text}${te.reset}${n}`),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),process.stderr.isTTY&&(process.stderr.write("\x1B[?25l"),this._render(),this.interval=setInterval(()=>this._render(),100))}update(e){this.text=e}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),process.stderr.isTTY&&process.stderr.write("\x1B[2K\r\x1B[?25h"),this.startTime=null}},vi=class{constructor(e){this.labels=e,this.statuses=e.map(()=>"running"),this.frame=0,this.interval=null,this.startTime=null,this.lineCount=e.length}_formatElapsed(){if(!this.startTime)return"";let e=Math.floor((Date.now()-this.startTime)/1e3);if(e<1)return"";let s=Math.floor(e/60),n=e%60;return s>0?`${s}m ${String(n).padStart(2,"0")}s`:`${n}s`}_render(){if(this._stopped)return;let e=Kn[this.frame%Kn.length],s=`${te.cyan}\u25CF${te.reset}`,n=this._formatElapsed(),o=n?` ${te.dim}${n}${te.reset}`:"",r=process.stderr.columns||80,i="";for(let a=0;a<this.labels.length;a++){let c,l;switch(this.statuses[a]){case"done":c=`${te.green}\u2713${te.reset}`,l=te.dim;break;case"error":c=`${te.red}\u2717${te.reset}`,l=te.dim;break;case"retry":c=`${te.yellow}\u21BB${te.reset}`,l=te.yellow;break;default:c=a===e?s:" ",l=""}let u=a===this.labels.length-1?o:"",d=r-4-(u?n.length+1:0),f=this.labels[a].length>d?this.labels[a].substring(0,Math.max(10,d-3))+"...":this.labels[a];i+=`\x1B[2K ${c} ${l}${f}${te.reset}${u}
3
3
  `}this.lineCount>0&&(i+=`\x1B[${this.lineCount}A`),process.stderr.write(i),this.frame++}start(){this._stopped=!1,this.startTime=Date.now();let e="\x1B[?25l";for(let s=0;s<this.lineCount;s++)e+=`
4
4
  `;this.lineCount>0&&(e+=`\x1B[${this.lineCount}A`),process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),100)}update(e,s){e>=0&&e<this.statuses.length&&(this.statuses[e]=s)}stop(e={}){if(this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),!e.silent)this._renderFinal();else{let s="";for(let n=0;n<this.lineCount;n++)s+=`\x1B[2K
5
- `;this.lineCount>0&&(s+=`\x1B[${this.lineCount}A`),process.stderr.write(s)}process.stderr.write("\x1B[?25h")}_renderFinal(){let e=this._formatElapsed(),s=e?` ${Z.dim}${e}${Z.reset}`:"",n=process.stderr.columns||80,o="";for(let r=0;r<this.labels.length;r++){let i;switch(this.statuses[r]){case"done":i=`${Z.green}\u2713${Z.reset}`;break;case"error":i=`${Z.red}\u2717${Z.reset}`;break;case"retry":i=`${Z.yellow}\u21BB${Z.reset}`;break;default:i=`${Z.yellow}\u25CB${Z.reset}`}let a=r===this.labels.length-1?s:"",c=n-4-(a?e.length+1:0),l=this.labels[r].length>c?this.labels[r].substring(0,Math.max(10,c-3))+"...":this.labels[r];o+=`\x1B[2K ${i} ${Z.dim}${l}${Z.reset}${a}
6
- `}process.stderr.write(o)}},Mo={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},Lo={done:Z.green,in_progress:Z.cyan,pending:Z.dim,failed:Z.red},Xt=null,$i=class{constructor(e,s){this.name=e,this.tasks=s.map(n=>({id:n.id,description:n.description,status:n.status||"pending"})),this.frame=0,this.interval=null,this.startTime=null,this.tokens=0,this.lineCount=1+this.tasks.length,this._paused=!1}_formatElapsed(){if(!this.startTime)return"";let e=Math.floor((Date.now()-this.startTime)/1e3);if(e<1)return"";let s=Math.floor(e/60),n=e%60;return s>0?`${s}m ${String(n).padStart(2,"0")}s`:`${n}s`}_formatTokens(){return this.tokens<=0?"":this.tokens>=1e3?`${(this.tokens/1e3).toFixed(1)}k`:String(this.tokens)}_render(){if(this._stopped)return;let e=Zc[this.frame%Zc.length],s=this._formatElapsed(),n=this._formatTokens(),o=[s,n?`\u2193 ${n} tokens`:""].filter(Boolean).join(" \xB7 "),r=o?` ${Z.dim}(${o})${Z.reset}`:"",i=`\x1B[2K${Z.cyan}${e}${Z.reset} ${this.name}\u2026${r}
7
- `;for(let a=0;a<this.tasks.length;a++){let c=this.tasks[a],l=a===0?"\u23BF":" ",u=Mo[c.status]||Mo.pending,d=Lo[c.status]||Lo.pending,f=c.description.length>55?c.description.substring(0,52)+"...":c.description;i+=`\x1B[2K ${Z.dim}${l}${Z.reset} ${d}${u}${Z.reset} ${f}
5
+ `;this.lineCount>0&&(s+=`\x1B[${this.lineCount}A`),process.stderr.write(s)}process.stderr.write("\x1B[?25h")}_renderFinal(){let e=this._formatElapsed(),s=e?` ${te.dim}${e}${te.reset}`:"",n=process.stderr.columns||80,o="";for(let r=0;r<this.labels.length;r++){let i;switch(this.statuses[r]){case"done":i=`${te.green}\u2713${te.reset}`;break;case"error":i=`${te.red}\u2717${te.reset}`;break;case"retry":i=`${te.yellow}\u21BB${te.reset}`;break;default:i=`${te.yellow}\u25CB${te.reset}`}let a=r===this.labels.length-1?s:"",c=n-4-(a?e.length+1:0),l=this.labels[r].length>c?this.labels[r].substring(0,Math.max(10,c-3))+"...":this.labels[r];o+=`\x1B[2K ${i} ${te.dim}${l}${te.reset}${a}
6
+ `}process.stderr.write(o)}},Po={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},Io={done:te.green,in_progress:te.cyan,pending:te.dim,failed:te.red},Jt=null,Si=class{constructor(e,s){this.name=e,this.tasks=s.map(n=>({id:n.id,description:n.description,status:n.status||"pending"})),this.frame=0,this.interval=null,this.startTime=null,this.tokens=0,this.lineCount=1+this.tasks.length,this._paused=!1}_formatElapsed(){if(!this.startTime)return"";let e=Math.floor((Date.now()-this.startTime)/1e3);if(e<1)return"";let s=Math.floor(e/60),n=e%60;return s>0?`${s}m ${String(n).padStart(2,"0")}s`:`${n}s`}_formatTokens(){return this.tokens<=0?"":this.tokens>=1e3?`${(this.tokens/1e3).toFixed(1)}k`:String(this.tokens)}_render(){if(this._stopped)return;let e=dl[this.frame%dl.length],s=this._formatElapsed(),n=this._formatTokens(),o=[s,n?`\u2193 ${n} tokens`:""].filter(Boolean).join(" \xB7 "),r=o?` ${te.dim}(${o})${te.reset}`:"",i=`\x1B[2K${te.cyan}${e}${te.reset} ${this.name}\u2026${r}
7
+ `;for(let a=0;a<this.tasks.length;a++){let c=this.tasks[a],l=a===0?"\u23BF":" ",u=Po[c.status]||Po.pending,d=Io[c.status]||Io.pending,f=c.description.length>55?c.description.substring(0,52)+"...":c.description;i+=`\x1B[2K ${te.dim}${l}${te.reset} ${d}${u}${te.reset} ${f}
8
8
  `}i+=`\x1B[${this.lineCount}A`,process.stderr.write(i),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),this._paused=!1;let e="\x1B[?25l";for(let s=0;s<this.lineCount;s++)e+=`
9
- `;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120),Xt=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,Xt===this&&(Xt=null)}pause(){if(this._paused)return;this.interval&&(clearInterval(this.interval),this.interval=null);let e="";for(let s=0;s<this.lineCount;s++)e+=`\x1B[2K
9
+ `;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120),Jt=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,Jt===this&&(Jt=null)}pause(){if(this._paused)return;this.interval&&(clearInterval(this.interval),this.interval=null);let e="";for(let s=0;s<this.lineCount;s++)e+=`\x1B[2K
10
10
  `;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._paused=!0}resume(){if(!this._paused)return;this._paused=!1;let e="\x1B[?25l";for(let s=0;s<this.lineCount;s++)e+=`
11
- `;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120)}updateTask(e,s){let n=this.tasks.find(o=>o.id===e);n&&(n.status=s)}setStats({tokens:e}){e!==void 0&&(this.tokens=e)}isActive(){return this.interval!==null||this._paused}_renderFinal(){let e=this._formatElapsed(),s=this.tasks.filter(a=>a.status==="done").length,n=this.tasks.filter(a=>a.status==="failed").length,o=this.tasks.length,r=n>0?`${s}/${o} done, ${n} failed`:`${s}/${o} done`,i=`\x1B[2K${Z.green}\u2714${Z.reset} ${this.name} ${Z.dim}(${e} \xB7 ${r})${Z.reset}
12
- `;for(let a=0;a<this.tasks.length;a++){let c=this.tasks[a],l=a===0?"\u23BF":" ",u=Mo[c.status]||Mo.pending,d=Lo[c.status]||Lo.pending,f=c.description.length>55?c.description.substring(0,52)+"...":c.description;i+=`\x1B[2K ${Z.dim}${l}${Z.reset} ${d}${u}${Z.reset} ${Z.dim}${f}${Z.reset}
13
- `}process.stderr.write(i)}},wi=class{constructor(e,s){this.toolName=e,this.message=s||`Running ${e}...`,this.count=0,this.total=null,this.detail="",this.frame=0,this.interval=null,this.startTime=null,this._stopped=!1}_render(){if(this._stopped||!process.stderr.isTTY)return;let e=Un[this.frame%Un.length],s="";for(let r=0;r<Po;r++)s+=r===e?`${Z.cyan}\u25CF${Z.reset}`:" ";let n=this.message;this.count>0&&(n+=` ${Z.cyan}${this.count}${Z.reset}`,this.total&&(n+=`/${this.total}`),this.detail&&(n+=` ${Z.dim}${this.detail}${Z.reset}`));let o="";if(this.startTime){let r=Math.floor((Date.now()-this.startTime)/1e3);r>=1&&(o=` ${Z.dim}${r}s${Z.reset}`)}process.stderr.write(`\x1B[2K\r${s} ${Z.dim}${n}${Z.reset}${o}`),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),process.stderr.isTTY&&(process.stderr.write("\x1B[?25l"),this._render(),this.interval=setInterval(()=>this._render(),100))}update(e){e.count!==void 0&&(this.count=e.count),e.total!==void 0&&(this.total=e.total),e.detail!==void 0&&(this.detail=e.detail),e.message!==void 0&&(this.message=e.message)}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),process.stderr.isTTY&&process.stderr.write("\x1B[2K\r\x1B[?25h")}};function om(t){Xt=t}function rm(){return Xt}function im(){Xt&&(Xt.stop(),Xt=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}Qc.exports={C:Z,Spinner:gi,MultiProgress:yi,TaskProgress:$i,ToolProgress:wi,setActiveTaskProgress:om,getActiveTaskProgress:rm,cleanupTerminal:im}});var bi=se((ck,sl)=>{"use strict";var ie={kw:"\x1B[34m",str:"\x1B[32m",cmt:"\x1B[90m",num:"\x1B[33m",type:"\x1B[36m",punct:"\x1B[35m",reset:"\x1B[0m"},el={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"])},am={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 tl(t){if(!t)return null;let e=t.split(".").pop().toLowerCase();return am[e]||null}function cm(t){return t.replace(/"([^"\\]|\\.)*"\s*:/g,e=>ie.type+e+ie.reset).replace(/"([^"\\]|\\.)*"/g,e=>ie.str+e+ie.reset).replace(/\b-?(\d+(\.\d+)?([eE][+-]?\d+)?)\b/g,e=>ie.num+e+ie.reset).replace(/\b(true|false|null)\b/g,e=>ie.kw+e+ie.reset)}function lm(t){return/<!--/.test(t)?t.replace(/<!--[\s\S]*?(?:-->|$)/g,e=>ie.cmt+e+ie.reset):t.replace(/(<\/?)([a-zA-Z][a-zA-Z0-9.-]*)/g,(e,s,n)=>s+ie.type+n+ie.reset).replace(/\s([a-zA-Z][a-zA-Z0-9-]*)=/g,(e,s)=>" "+ie.kw+s+ie.reset+"=").replace(/"([^"]*)"/g,e=>ie.str+e+ie.reset)}function um(t){return t.replace(/\/\*[\s\S]*?(?:\*\/|$)/g,e=>ie.cmt+e+ie.reset).replace(/#[0-9a-fA-F]{3,8}\b/g,e=>ie.num+e+ie.reset).replace(/\b(-?\d+(?:\.\d+)?)(px|em|rem|vh|vw|vmin|vmax|%|s|ms|deg|fr)\b/g,(e,s,n)=>ie.num+s+ie.reset+n).replace(/([a-z][a-z-]*)(\s*:)/g,(e,s,n)=>ie.type+s+ie.reset+n).replace(/"[^"]*"|'[^']*'/g,e=>ie.str+e+ie.reset)}function nl(t,e,s){if(e==="json")return cm(t);if(e==="html"||e==="xml")return lm(t);if(e==="css")return um(t);if(e==="md")return t;let n=el[e]||el.js,o="",r=0;if(s.inBlockComment){let i=t.indexOf("*/");if(i===-1)return ie.cmt+t+ie.reset;if(o+=ie.cmt+t.slice(0,i+2)+ie.reset,s.inBlockComment=!1,r=i+2,r>=t.length)return o}if(s.inString==="`"){let i=t.indexOf("`");if(i===-1)return ie.str+t+ie.reset;if(o+=ie.str+t.slice(0,i+1)+ie.reset,s.inString=null,r=i+1,r>=t.length)return o}for(;r<t.length;){let i=t[r];if(!s.inString&&i==="/"&&t[r+1]==="*"){let a=t.indexOf("*/",r+2);if(a===-1)return o+=ie.cmt+t.slice(r)+ie.reset,s.inBlockComment=!0,o;o+=ie.cmt+t.slice(r,a+2)+ie.reset,r=a+2;continue}if(!s.inString&&((e==="js"||e==="go"||e==="rs"||e==="java")&&i==="/"&&t[r+1]==="/"||(e==="py"||e==="sh")&&i==="#"))return o+=ie.cmt+t.slice(r)+ie.reset,o;if(!s.inString&&(i==='"'||i==="'"||i==="`")){s.inString=i,o+=ie.str+i,r++;continue}if(s.inString){if(i==="\\"&&r+1<t.length){o+=i+t[r+1],r+=2;continue}if(i===s.inString){o+=i+ie.reset,s.inString=null,r++;continue}o+=i,r++;continue}if(/[0-9]/.test(i)&&(r===0||!/[a-zA-Z0-9_$]/.test(t[r-1]))){let a="";for(;r<t.length&&/[0-9a-fA-F_.xXoObBeE+-]/.test(t[r])&&!(a.length>0&&/[eE]/.test(t[r-1])&&/[^+-]/.test(i));)a+=t[r++];o+=ie.num+a+ie.reset;continue}if(i==="@"&&(e==="js"||e==="java"||e==="py")){let a="@";for(r++;r<t.length&&/[a-zA-Z0-9_$.]/.test(t[r]);)a+=t[r++];o+=ie.punct+a+ie.reset;continue}if(/[a-zA-Z_$]/.test(i)){let a="";for(;r<t.length&&/[a-zA-Z0-9_$]/.test(t[r]);)a+=t[r++];n.has(a)?o+=ie.kw+a+ie.reset:/^[A-Z][A-Za-z0-9]*$/.test(a)&&e!=="sh"?o+=ie.type+a+ie.reset:o+=a;continue}o+=i,r++}return s.inString&&s.inString!=="`"&&(o+=ie.reset,s.inString=null),o}function dm(t,e){let s=tl(e);if(!s)return t.split(`
11
+ `;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120)}updateTask(e,s){let n=this.tasks.find(o=>o.id===e);n&&(n.status=s)}setStats({tokens:e}){e!==void 0&&(this.tokens=e)}isActive(){return this.interval!==null||this._paused}_renderFinal(){let e=this._formatElapsed(),s=this.tasks.filter(a=>a.status==="done").length,n=this.tasks.filter(a=>a.status==="failed").length,o=this.tasks.length,r=n>0?`${s}/${o} done, ${n} failed`:`${s}/${o} done`,i=`\x1B[2K${te.green}\u2714${te.reset} ${this.name} ${te.dim}(${e} \xB7 ${r})${te.reset}
12
+ `;for(let a=0;a<this.tasks.length;a++){let c=this.tasks[a],l=a===0?"\u23BF":" ",u=Po[c.status]||Po.pending,d=Io[c.status]||Io.pending,f=c.description.length>55?c.description.substring(0,52)+"...":c.description;i+=`\x1B[2K ${te.dim}${l}${te.reset} ${d}${u}${te.reset} ${te.dim}${f}${te.reset}
13
+ `}process.stderr.write(i)}},Ei=class{constructor(e,s){this.toolName=e,this.message=s||`Running ${e}...`,this.count=0,this.total=null,this.detail="",this.frame=0,this.interval=null,this.startTime=null,this._stopped=!1}_render(){if(this._stopped||!process.stderr.isTTY)return;let e=Kn[this.frame%Kn.length],s="";for(let r=0;r<jo;r++)s+=r===e?`${te.cyan}\u25CF${te.reset}`:" ";let n=this.message;this.count>0&&(n+=` ${te.cyan}${this.count}${te.reset}`,this.total&&(n+=`/${this.total}`),this.detail&&(n+=` ${te.dim}${this.detail}${te.reset}`));let o="";if(this.startTime){let r=Math.floor((Date.now()-this.startTime)/1e3);r>=1&&(o=` ${te.dim}${r}s${te.reset}`)}process.stderr.write(`\x1B[2K\r${s} ${te.dim}${n}${te.reset}${o}`),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),process.stderr.isTTY&&(process.stderr.write("\x1B[?25l"),this._render(),this.interval=setInterval(()=>this._render(),100))}update(e){e.count!==void 0&&(this.count=e.count),e.total!==void 0&&(this.total=e.total),e.detail!==void 0&&(this.detail=e.detail),e.message!==void 0&&(this.message=e.message)}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),process.stderr.isTTY&&process.stderr.write("\x1B[2K\r\x1B[?25h")}};function hm(t){Jt=t}function mm(){return Jt}function gm(){Jt&&(Jt.stop(),Jt=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}fl.exports={C:te,Spinner:ki,MultiProgress:vi,TaskProgress:Si,ToolProgress:Ei,setActiveTaskProgress:hm,getActiveTaskProgress:mm,cleanupTerminal:gm}});var Ti=re((Ck,gl)=>{"use strict";var ae={kw:"\x1B[34m",str:"\x1B[32m",cmt:"\x1B[90m",num:"\x1B[33m",type:"\x1B[36m",punct:"\x1B[35m",reset:"\x1B[0m"},pl={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"])},ym={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 hl(t){if(!t)return null;let e=t.split(".").pop().toLowerCase();return ym[e]||null}function $m(t){return t.replace(/"([^"\\]|\\.)*"\s*:/g,e=>ae.type+e+ae.reset).replace(/"([^"\\]|\\.)*"/g,e=>ae.str+e+ae.reset).replace(/\b-?(\d+(\.\d+)?([eE][+-]?\d+)?)\b/g,e=>ae.num+e+ae.reset).replace(/\b(true|false|null)\b/g,e=>ae.kw+e+ae.reset)}function wm(t){return/<!--/.test(t)?t.replace(/<!--[\s\S]*?(?:-->|$)/g,e=>ae.cmt+e+ae.reset):t.replace(/(<\/?)([a-zA-Z][a-zA-Z0-9.-]*)/g,(e,s,n)=>s+ae.type+n+ae.reset).replace(/\s([a-zA-Z][a-zA-Z0-9-]*)=/g,(e,s)=>" "+ae.kw+s+ae.reset+"=").replace(/"([^"]*)"/g,e=>ae.str+e+ae.reset)}function bm(t){return t.replace(/\/\*[\s\S]*?(?:\*\/|$)/g,e=>ae.cmt+e+ae.reset).replace(/#[0-9a-fA-F]{3,8}\b/g,e=>ae.num+e+ae.reset).replace(/\b(-?\d+(?:\.\d+)?)(px|em|rem|vh|vw|vmin|vmax|%|s|ms|deg|fr)\b/g,(e,s,n)=>ae.num+s+ae.reset+n).replace(/([a-z][a-z-]*)(\s*:)/g,(e,s,n)=>ae.type+s+ae.reset+n).replace(/"[^"]*"|'[^']*'/g,e=>ae.str+e+ae.reset)}function ml(t,e,s){if(e==="json")return $m(t);if(e==="html"||e==="xml")return wm(t);if(e==="css")return bm(t);if(e==="md")return t;let n=pl[e]||pl.js,o="",r=0;if(s.inBlockComment){let i=t.indexOf("*/");if(i===-1)return ae.cmt+t+ae.reset;if(o+=ae.cmt+t.slice(0,i+2)+ae.reset,s.inBlockComment=!1,r=i+2,r>=t.length)return o}if(s.inString==="`"){let i=t.indexOf("`");if(i===-1)return ae.str+t+ae.reset;if(o+=ae.str+t.slice(0,i+1)+ae.reset,s.inString=null,r=i+1,r>=t.length)return o}for(;r<t.length;){let i=t[r];if(!s.inString&&i==="/"&&t[r+1]==="*"){let a=t.indexOf("*/",r+2);if(a===-1)return o+=ae.cmt+t.slice(r)+ae.reset,s.inBlockComment=!0,o;o+=ae.cmt+t.slice(r,a+2)+ae.reset,r=a+2;continue}if(!s.inString&&((e==="js"||e==="go"||e==="rs"||e==="java")&&i==="/"&&t[r+1]==="/"||(e==="py"||e==="sh")&&i==="#"))return o+=ae.cmt+t.slice(r)+ae.reset,o;if(!s.inString&&(i==='"'||i==="'"||i==="`")){s.inString=i,o+=ae.str+i,r++;continue}if(s.inString){if(i==="\\"&&r+1<t.length){o+=i+t[r+1],r+=2;continue}if(i===s.inString){o+=i+ae.reset,s.inString=null,r++;continue}o+=i,r++;continue}if(/[0-9]/.test(i)&&(r===0||!/[a-zA-Z0-9_$]/.test(t[r-1]))){let a="";for(;r<t.length&&/[0-9a-fA-F_.xXoObBeE+-]/.test(t[r])&&!(a.length>0&&/[eE]/.test(t[r-1])&&/[^+-]/.test(i));)a+=t[r++];o+=ae.num+a+ae.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+=ae.punct+a+ae.reset;continue}if(/[a-zA-Z_$]/.test(i)){let a="";for(;r<t.length&&/[a-zA-Z0-9_$]/.test(t[r]);)a+=t[r++];n.has(a)?o+=ae.kw+a+ae.reset:/^[A-Z][A-Za-z0-9]*$/.test(a)&&e!=="sh"?o+=ae.type+a+ae.reset:o+=a;continue}o+=i,r++}return s.inString&&s.inString!=="`"&&(o+=ae.reset,s.inString=null),o}function _m(t,e){let s=hl(e);if(!s)return t.split(`
14
14
  `);let n=t.split(`
15
- `),o={inString:null,inBlockComment:!1};return n.map(r=>nl(r,s,o))}function fm(t,e){return e?nl(t,e,{inString:null,inBlockComment:!1}):t}sl.exports={detectLang:tl,highlightLine:fm,highlightLines:dm}});var rl=se((lk,ol)=>{var{T:E}=ks(),Je=E,pm={read_file:E.tool_read,list_directory:E.tool_read,write_file:E.tool_write,edit_file:E.tool_write,patch_file:E.tool_write,bash:E.tool_exec,grep:E.tool_search,search_files:E.tool_search,glob:E.tool_search,git_commit:E.tool_git,git_push:E.tool_git,git_pull:E.tool_git,git_status:E.tool_git,git_diff:E.tool_git,git_log:E.tool_git,git_branch:E.tool_git,git_stash:E.tool_git,web_fetch:E.tool_web,web_search:E.tool_web,sysadmin:E.tool_sysadmin,ssh_exec:E.tool_sysadmin,ssh_upload:E.tool_sysadmin,ssh_download:E.tool_sysadmin,deploy:E.tool_sysadmin},_i={read_file:"Read",write_file:"Write",edit_file:"Edit",patch_file:"Edit",list_directory:"List",bash:"Bash",grep:"Grep",search_files:"Search",glob:"Glob",web_fetch:"WebFetch",web_search:"WebSearch",git_status:"Bash",git_diff:"Bash",git_log:"Bash",git_commit:"Bash",git_push:"Bash",git_pull:"Bash",git_branch:"Bash",git_stash:"Bash",task_list:"TaskList",spawn_agents:"Agent",ask_user:"AskUser",switch_model:"SwitchModel",gh_run_list:"Bash",gh_run_view:"Bash",gh_workflow_trigger:"Bash",browser_open:"Browser",browser_screenshot:"Browser",browser_click:"Browser",browser_fill:"Browser",ssh_exec:"Bash",ssh_upload:"Upload",ssh_download:"Download",service_manage:"Bash",service_logs:"Bash",container_list:"Bash",container_logs:"Bash",container_exec:"Bash",brain_write:"Write",deploy:"Bash",frontend_recon:"Search"};function Io(t,e=!1,s=null){if(e)return`${E.error}\u23FA${E.reset}`;let n=pm[t]||E.tool_default;return s==="blink"?`${n}\x1B[5m\u23FA\x1B[25m${E.reset}`:`${n}${s!==null?s:"\u23FA"}${E.reset}`}function hm(t,e,s=!1,n=null){let o=(t||[]).filter(c=>c&&c.canExecute!==!1);if(o.length===0)return`${Io("",s,n)} Step ${e}`;if(o.length===1){let c=o[0],l=c.args||{},u=_i[c.fnName]||c.fnName.replace(/_/g," "),d="";l.path?d=l.path:l.command?d=String(l.command).substring(0,80):l.query?d=String(l.query).substring(0,60):l.pattern?d=String(l.pattern).substring(0,60):l.url&&(d=String(l.url).substring(0,60));let f=d?`(${Je.dim}${d}${Je.reset})`:"";return`${Io(c.fnName,s,n)} ${Je.bold}${u}${Je.reset}${f}`}let r=o[0].fnName,i=[...new Set(o.map(c=>_i[c.fnName]||c.fnName.replace(/_/g," ")))],a=i.length<=3?i.join(", "):`${o.length} tools`;return`${Io(r,s,n)} ${Je.bold}${a}${Je.reset}`}function mm(t,e){let s;switch(t){case"write_file":case"edit_file":case"patch_file":case"read_file":case"list_directory":s=e.path||"";break;case"bash":case"ssh_exec":s=(e.command||"").substring(0,80);break;case"grep":case"search_files":s=e.pattern?`"${e.pattern}"${e.path?` in ${e.path}`:""}`:"";break;case"glob":s=e.pattern||"";break;case"web_fetch":s=(e.url||"").substring(0,60);break;case"web_search":s=(e.query||"").substring(0,50);break;default:s=JSON.stringify(e).substring(0,80)}let n=_i[t]||t.replace(/_/g," "),o=s?`(${Je.dim}${s}${Je.reset})`:"";return`${Io(t)} ${Je.bold}${n}${Je.reset}${o}`}function gm(t,e=8){let s=t.split(`
15
+ `),o={inString:null,inBlockComment:!1};return n.map(r=>ml(r,s,o))}function xm(t,e){return e?ml(t,e,{inString:null,inBlockComment:!1}):t}gl.exports={detectLang:hl,highlightLine:xm,highlightLines:_m}});var wl=re((Ak,$l)=>{var{T:E}=Es(),Ze=E,km={read_file:E.tool_read,list_directory:E.tool_read,write_file:E.tool_write,edit_file:E.tool_write,patch_file:E.tool_write,bash:E.tool_exec,grep:E.tool_search,search_files:E.tool_search,glob:E.tool_search,git_commit:E.tool_git,git_push:E.tool_git,git_pull:E.tool_git,git_status:E.tool_git,git_diff:E.tool_git,git_log:E.tool_git,git_branch:E.tool_git,git_stash:E.tool_git,web_fetch:E.tool_web,web_search:E.tool_web,sysadmin:E.tool_sysadmin,ssh_exec:E.tool_sysadmin,ssh_upload:E.tool_sysadmin,ssh_download:E.tool_sysadmin,deploy:E.tool_sysadmin},Ri={read_file:"Read",write_file:"Write",edit_file:"Edit",patch_file:"Edit",list_directory:"List",bash:"Bash",grep:"Grep",search_files:"Search",glob:"Glob",web_fetch:"WebFetch",web_search:"WebSearch",git_status:"Bash",git_diff:"Bash",git_log:"Bash",git_commit:"Bash",git_push:"Bash",git_pull:"Bash",git_branch:"Bash",git_stash:"Bash",task_list:"TaskList",spawn_agents:"Agent",ask_user:"AskUser",switch_model:"SwitchModel",gh_run_list:"Bash",gh_run_view:"Bash",gh_workflow_trigger:"Bash",browser_open:"Browser",browser_screenshot:"Browser",browser_click:"Browser",browser_fill:"Browser",ssh_exec:"Bash",ssh_upload:"Upload",ssh_download:"Download",service_manage:"Bash",service_logs:"Bash",container_list:"Bash",container_logs:"Bash",container_exec:"Bash",brain_write:"Write",deploy:"Bash",frontend_recon:"Search"};function Do(t,e=!1,s=null){if(e)return`${E.error}\u23FA${E.reset}`;let n=km[t]||E.tool_default;return s==="blink"?`${n}\x1B[5m\u23FA\x1B[25m${E.reset}`:`${n}${s!==null?s:"\u23FA"}${E.reset}`}function vm(t,e,s=!1,n=null){let o=(t||[]).filter(c=>c&&c.canExecute!==!1);if(o.length===0)return`${Do("",s,n)} Step ${e}`;if(o.length===1){let c=o[0],l=c.args||{},u=Ri[c.fnName]||c.fnName.replace(/_/g," "),d="";l.path?d=l.path:l.command?d=String(l.command).substring(0,80):l.query?d=String(l.query).substring(0,60):l.pattern?d=String(l.pattern).substring(0,60):l.url&&(d=String(l.url).substring(0,60));let f=d?`(${Ze.dim}${d}${Ze.reset})`:"";return`${Do(c.fnName,s,n)} ${Ze.bold}${u}${Ze.reset}${f}`}let r=o[0].fnName,i=[...new Set(o.map(c=>Ri[c.fnName]||c.fnName.replace(/_/g," ")))],a=i.length<=3?i.join(", "):`${o.length} tools`;return`${Do(r,s,n)} ${Ze.bold}${a}${Ze.reset}`}function Sm(t,e){let s;switch(t){case"write_file":case"edit_file":case"patch_file":case"read_file":case"list_directory":s=e.path||"";break;case"bash":case"ssh_exec":s=(e.command||"").substring(0,80);break;case"grep":case"search_files":s=e.pattern?`"${e.pattern}"${e.path?` in ${e.path}`:""}`:"";break;case"glob":s=e.pattern||"";break;case"web_fetch":s=(e.url||"").substring(0,60);break;case"web_search":s=(e.query||"").substring(0,50);break;default:s=JSON.stringify(e).substring(0,80)}let n=Ri[t]||t.replace(/_/g," "),o=s?`(${Ze.dim}${s}${Ze.reset})`:"";return`${Do(t)} ${Ze.bold}${n}${Ze.reset}${o}`}function Em(t,e=8){let s=t.split(`
16
16
  `),n=s.slice(0,e),o=s.length-e,r=`${E.muted} \u23BF ${E.reset}`,i=" ",a=n.map((c,l)=>`${l===0?r:i}${E.success}${c}${E.reset}`).join(`
17
17
  `);return o>0&&(a+=`
18
- ${E.subtle} \u2026 +${o} lines${E.reset}`),a}function ym(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`Glob: ${e.pattern||"..."}`;case"grep":return`Grep: ${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"Git status...";case"git_diff":return`Git diff${e.file?`: ${e.file}`:""}...`;case"git_log":return`Git log${e.file?`: ${e.file}`:""}...`;case"gh_run_list":return`GitHub Actions: listing runs${e.workflow?` (${e.workflow})`:""}...`;case"gh_run_view":return`GitHub Actions: run ${e.run_id}...`;case"gh_workflow_trigger":return`GitHub Actions: trigger ${e.workflow}...`;case"browser_open":return`Browser: opening ${(e.url||"").substring(0,60)}...`;case"browser_screenshot":return`Browser: screenshot ${(e.url||"").substring(0,60)}...`;case"browser_click":return`Browser: clicking ${e.text||e.selector||"element"}...`;case"browser_fill":return`Browser: filling ${e.selector||"field"}...`;case"sysadmin":{let s=e.server&&e.server!=="local"?` [${e.server}]`:"";switch(e.action){case"audit":return`Sysadmin${s}: full audit...`;case"disk_usage":return`Sysadmin${s}: disk usage ${e.path||"/"}...`;case"process_list":return`Sysadmin${s}: top processes (${e.sort_by||"cpu"})...`;case"network_status":return`Sysadmin${s}: network status...`;case"ssl_check":return`Sysadmin${s}: SSL check ${e.domain||e.cert_path||""}...`;case"log_tail":return`Sysadmin${s}: tail ${e.path||"log"}...`;case"find_large":return`Sysadmin${s}: find large files in ${e.path||"/"}...`;case"service":return`Sysadmin${s}: service ${e.service_action||""} ${e.service_name||""}...`;case"kill_process":return`Sysadmin${s}: kill PID ${e.pid||e.process_name||"?"}...`;case"journalctl":return`Sysadmin${s}: journal ${e.unit?`[${e.unit}]`:""}${e.since?` since ${e.since}`:""}...`;case"package":return`Sysadmin${s}: package ${e.package_action||""} ${(e.packages||[]).join(" ")}...`;case"firewall":return`Sysadmin${s}: firewall ${e.firewall_action||""}...`;case"user_manage":return`Sysadmin${s}: user ${e.user_action||""} ${e.user||""}...`;case"cron":return`Sysadmin${s}: cron ${e.cron_action||""}...`;default:return`Sysadmin${s}: ${e.action}...`}}default:return`Running: ${t}`}}function $m(t,e,s,n){let o=String(s||"");if(n){let a=o.split(`
18
+ ${E.subtle} \u2026 +${o} lines${E.reset}`),a}var qo=["Sampling","Decoding","Attending","Inferring","Generating","Routing","Embedding","Reasoning","Tokenizing","Predicting"],yl=Math.floor(Math.random()*qo.length),Ci=null;function Tm(t){Ci=t}function Rm(){let t=qo[yl%qo.length];yl++;let e=Ci?` \xB7 ${Ci}`:"";return`${t}${e}`}function Cm(t,e){switch(t){case"bash":case"ask_user":case"write_file":case"edit_file":case"patch_file":case"task_list":case"spawn_agents":return null;case"read_file":return`Reading ${e.path||"file"}`;case"list_directory":return`Listing ${e.path||"."}`;case"search_files":return`Searching ${e.pattern||"..."}`;case"glob":return`Searching ${e.pattern||"..."}`;case"grep":return`Searching ${e.pattern||"..."}`;case"web_fetch":return`Fetching ${(e.url||"").substring(0,60)}`;case"web_search":return`Searching web: ${(e.query||"").substring(0,50)}`;case"git_status":return"Checking git status";case"git_diff":return`Diffing${e.file?` ${e.file}`:""}`;case"git_log":return`Reading git log${e.file?` (${e.file})`:""}`;case"gh_run_list":return`GitHub Actions: listing runs${e.workflow?` (${e.workflow})`:""}...`;case"gh_run_view":return`GitHub Actions: run ${e.run_id}...`;case"gh_workflow_trigger":return`GitHub Actions: trigger ${e.workflow}...`;case"browser_open":return`Browser: opening ${(e.url||"").substring(0,60)}...`;case"browser_screenshot":return`Browser: screenshot ${(e.url||"").substring(0,60)}...`;case"browser_click":return`Browser: clicking ${e.text||e.selector||"element"}...`;case"browser_fill":return`Browser: filling ${e.selector||"field"}...`;case"sysadmin":{let s=e.server&&e.server!=="local"?` [${e.server}]`:"";switch(e.action){case"audit":return`Sysadmin${s}: full audit...`;case"disk_usage":return`Sysadmin${s}: disk usage ${e.path||"/"}...`;case"process_list":return`Sysadmin${s}: top processes (${e.sort_by||"cpu"})...`;case"network_status":return`Sysadmin${s}: network status...`;case"ssl_check":return`Sysadmin${s}: SSL check ${e.domain||e.cert_path||""}...`;case"log_tail":return`Sysadmin${s}: tail ${e.path||"log"}...`;case"find_large":return`Sysadmin${s}: find large files in ${e.path||"/"}...`;case"service":return`Sysadmin${s}: service ${e.service_action||""} ${e.service_name||""}...`;case"kill_process":return`Sysadmin${s}: kill PID ${e.pid||e.process_name||"?"}...`;case"journalctl":return`Sysadmin${s}: journal ${e.unit?`[${e.unit}]`:""}${e.since?` since ${e.since}`:""}...`;case"package":return`Sysadmin${s}: package ${e.package_action||""} ${(e.packages||[]).join(" ")}...`;case"firewall":return`Sysadmin${s}: firewall ${e.firewall_action||""}...`;case"user_manage":return`Sysadmin${s}: user ${e.user_action||""} ${e.user||""}...`;case"cron":return`Sysadmin${s}: cron ${e.cron_action||""}...`;default:return`Sysadmin${s}: ${e.action}...`}}default:return`Running: ${t}`}}function Am(t,e,s,n){let o=String(s||"");if(n){let a=o.split(`
19
19
  `)[0];if(a.startsWith("BLOCKED:")){let d=a.replace(/^BLOCKED:\s*/,"").replace(/\s*—.*$/,"").replace(/\s*\(hard cap:.*?\)/,"").trim().substring(0,70);return` ${E.muted}\u23BF blocked: ${d}${E.reset}`}let c=a.replace(/^ERROR:\s*/i,"").substring(0,80),l=o.match(/\nHINT: (.+)/),u=l?`
20
20
  ${E.muted}${l[1].substring(0,100)}${E.reset}`:"";return` ${E.error}\u23BF ${c}${E.reset}${u}`}let r;switch(t){case"read_file":{let c=o.split(`
21
- `).filter(Boolean).filter(g=>!/^File:\s/.test(g)&&!/^\[LARGE FILE:/.test(g)),l=c.length,u=c[c.length-1],d=u?parseInt(u.match(/^(\d+):/)?.[1]||"0"):0,f=e.line_start||e.line_end,h=e.path?require("path").basename(e.path):null,m=h?` ${E.muted}from ${h}${E.reset}`:"";f&&d>l?r=`Read lines ${e.line_start||1}\u2013${d}${m}`:r=`Read ${l} line${l!==1?"s":""}${m}`;break}case"write_file":{let c=(e.content||"").split(`
22
- `).length,l=e.path?require("path").basename(e.path):null,u=l?`Wrote ${l} \xB7 ${c} line${c!==1?"s":""}`:`Wrote ${c} line${c!==1?"s":""}`,{highlightLines:d}=bi(),f=d(e.content||"",e.path||null),h=40,m=8;if(c<=h){let g=f.map(b=>` ${b}`).join(`
21
+ `).filter(Boolean).filter(m=>!/^File:\s/.test(m)&&!/^\[LARGE FILE:/.test(m)),l=c.length,u=c[c.length-1],d=u?parseInt(u.match(/^(\d+):/)?.[1]||"0"):0,f=e.line_start||e.line_end,h=e.path?require("path").basename(e.path):null,g=h?` ${E.muted}from ${h}${E.reset}`:"";f&&d>l?r=`Read lines ${e.line_start||1}\u2013${d}${g}`:r=`Read ${l} line${l!==1?"s":""}${g}`;break}case"write_file":{let c=(e.content||"").split(`
22
+ `).length,l=e.path?require("path").basename(e.path):null,u=l?`Wrote ${l} \xB7 ${c} line${c!==1?"s":""}`:`Wrote ${c} line${c!==1?"s":""}`,{highlightLines:d}=Ti(),f=d(e.content||"",e.path||null),h=40,g=8;if(c<=h){let m=f.map(b=>` ${b}`).join(`
23
23
  `);r=`${u}
24
- ${g}`}else{let g=f.slice(0,m).map(b=>` ${b}`).join(`
24
+ ${m}`}else{let m=f.slice(0,g).map(b=>` ${b}`).join(`
25
25
  `);r=`${u}
26
- ${g}
27
- ${E.subtle}\u2026 +${c-m} lines${E.reset}`}break}case"edit_file":{let a=(e.old_text||"").split(`
26
+ ${m}
27
+ ${E.subtle}\u2026 +${c-g} lines${E.reset}`}break}case"edit_file":{let a=(e.old_text||"").split(`
28
28
  `),c=(e.new_text||"").split(`
29
- `),l=a.length,u=c.length,d=e.path?require("path").basename(e.path):null,f=d?` ${E.muted}${d}${E.reset}`:"",h=a.find(U=>U.trim()),m=c.find(U=>U.trim()),{highlightLine:g,detectLang:b}=bi(),v=b(e.path||null),O=[];h&&O.push(` ${E.diff_rem}- ${E.reset}${g(h.trimEnd().substring(0,72),v)}${E.reset}`),m&&O.push(` ${E.diff_add}+ ${E.reset}${g(m.trimEnd().substring(0,72),v)}${E.reset}`),r=`${E.diff_rem}\u2212${l}${E.reset} ${E.diff_add}+${u}${E.reset}${f}`+(O.length>0?`
30
- `+O.join(`
29
+ `),l=a.length,u=c.length,d=e.path?require("path").basename(e.path):null,f=d?` ${E.muted}${d}${E.reset}`:"",h=a.find(G=>G.trim()),g=c.find(G=>G.trim()),{highlightLine:m,detectLang:b}=Ti(),x=b(e.path||null),j=[];h&&j.push(` ${E.diff_rem}- ${E.reset}${m(h.trimEnd().substring(0,72),x)}${E.reset}`),g&&j.push(` ${E.diff_add}+ ${E.reset}${m(g.trimEnd().substring(0,72),x)}${E.reset}`),r=`${E.diff_rem}\u2212${l}${E.reset} ${E.diff_add}+${u}${E.reset}${f}`+(j.length>0?`
30
+ `+j.join(`
31
31
  `):"");break}case"patch_file":{let a=e.patches||[],c=a.reduce((u,d)=>u+(d.old_text||"").split(`
32
32
  `).length,0),l=a.reduce((u,d)=>u+(d.new_text||"").split(`
33
33
  `).length,0);r=`${E.reset}${a.length} patch${a.length!==1?"es":""} ${E.diff_rem}\u2212${c}${E.reset} ${E.diff_add}+${l}${E.reset}`;break}case"bash":{let c=o.match(/^EXIT (\d+)/),l=o.split(`
34
- `).filter(f=>f&&!f.startsWith("EXIT ")&&!f.startsWith("HINT:")&&f.trim()),u=c?c[1]==="0"?`${E.success}\u2713${E.reset}`:`${E.error}\u2717 Exit ${c[1]}${E.reset}`:`${E.success}\u2713${E.reset}`,d=o.match(/\nHINT: (.+)/);if(d)r=`${u} ${E.muted}\u2014 ${d[1].substring(0,100)}${E.reset}`;else if(l.length===0)r=u;else{let f=c&&c[1]!=="0",h=f?l.slice(-3):l.slice(0,3),m=l.length-3,g=h.map((b,v)=>v===0?`${u} ${E.muted}${b.substring(0,120)}${E.reset}`:` ${E.muted}${b.substring(0,120)}${E.reset}`);if(m>0){let b=f?` ${E.subtle}${m} lines above\u2026${E.reset}`:` ${E.subtle}\u2026 +${m} lines${E.reset}`;f?g.unshift(b):g.push(b)}r=g.join(`
35
- `)}break}case"grep":case"search_files":{if(o.includes("(no matches)")||o==="no matches")r=`No matches${e.pattern?` ${E.muted}"${String(e.pattern).substring(0,40)}"${E.reset}`:""}`;else{let m=function(v){let O=v.indexOf(":");if(O===-1)return`${E.muted}${v.substring(0,90)}${E.reset}`;let U=v.substring(0,O),L=v.substring(O+1),R=L.match(/^(\d+)[:-](.*)/s),C=R?`:${R[1]}`:"",K=(R?R[2]:L).trim(),Q=`${E.subtle}${a.basename(U)}${C}${E.reset}`,re=`${E.muted}${K.substring(0,80)}${K.length>80?"\u2026":""}${E.reset}`;return`${Q} ${re}`};var i=m;let a=require("path"),c=o.split(`
36
- `).filter(Boolean),l=c.length,d=new Set(c.map(v=>v.split(":")[0]).filter(Boolean)).size,f=e.pattern?` ${E.muted}"${String(e.pattern).substring(0,40)}"${E.reset}`:"",h=d>1?`${l} match${l!==1?"es":""} in ${d} files${f}`:`${l} match${l!==1?"es":""}${f}`,g=c.slice(0,3).map((v,O)=>O===0?`${h}
37
- ${m(v)}`:` ${m(v)}`),b=c.length-3;b>0&&g.push(` ${E.subtle}\u2026 +${b} lines${E.reset}`),r=g.join(`
34
+ `).filter(f=>f&&!f.startsWith("EXIT ")&&!f.startsWith("HINT:")&&f.trim()),u=c?c[1]==="0"?`${E.success}\u2713${E.reset}`:`${E.error}\u2717 Exit ${c[1]}${E.reset}`:`${E.success}\u2713${E.reset}`,d=o.match(/\nHINT: (.+)/);if(d)r=`${u} ${E.muted}\u2014 ${d[1].substring(0,100)}${E.reset}`;else if(l.length===0)r=u;else{let f=c&&c[1]!=="0",h=f?l.slice(-3):l.slice(0,3),g=l.length-3,m=h.map((b,x)=>x===0?`${u} ${E.muted}${b.substring(0,120)}${E.reset}`:` ${E.muted}${b.substring(0,120)}${E.reset}`);if(g>0){let b=f?` ${E.subtle}${g} lines above\u2026${E.reset}`:` ${E.subtle}\u2026 +${g} lines${E.reset}`;f?m.unshift(b):m.push(b)}r=m.join(`
35
+ `)}break}case"grep":case"search_files":{if(o.includes("(no matches)")||o==="no matches")r=`No matches${e.pattern?` ${E.muted}"${String(e.pattern).substring(0,40)}"${E.reset}`:""}`;else{let g=function(x){let j=x.indexOf(":");if(j===-1)return`${E.muted}${x.substring(0,90)}${E.reset}`;let G=x.substring(0,j),L=x.substring(j+1),P=L.match(/^(\d+)[:-](.*)/s),C=P?`:${P[1]}`:"",Z=(P?P[2]:L).trim(),Y=`${E.subtle}${a.basename(G)}${C}${E.reset}`,ue=`${E.muted}${Z.substring(0,80)}${Z.length>80?"\u2026":""}${E.reset}`;return`${Y} ${ue}`};var i=g;let a=require("path"),c=o.split(`
36
+ `).filter(Boolean),l=c.length,d=new Set(c.map(x=>x.split(":")[0]).filter(Boolean)).size,f=e.pattern?` ${E.muted}"${String(e.pattern).substring(0,40)}"${E.reset}`:"",h=d>1?`${l} match${l!==1?"es":""} in ${d} files${f}`:`${l} match${l!==1?"es":""}${f}`,m=c.slice(0,3).map((x,j)=>j===0?`${h}
37
+ ${g(x)}`:` ${g(x)}`),b=c.length-3;b>0&&m.push(` ${E.subtle}\u2026 +${b} lines${E.reset}`),r=m.join(`
38
38
  `)}break}case"glob":{let a=e.pattern?` ${E.muted}${String(e.pattern).substring(0,50)}${E.reset}`:"";if(o==="(no matches)")r=`No files found${a}`;else{let c=require("path"),l=o.split(`
39
- `).filter(Boolean),u=l.length,d=l.slice(0,5).map(m=>c.basename(m)),f=u-d.length,h=d.join(", ")+(f>0?`, +${f} more`:"");r=`${u} file${u!==1?"s":""}${a} \u2014 ${E.muted}${h}${E.reset}`}break}case"list_directory":{if(o==="(empty)")r="0 entries";else{let a=o.split(`
39
+ `).filter(Boolean),u=l.length,d=l.slice(0,5).map(g=>c.basename(g)),f=u-d.length,h=d.join(", ")+(f>0?`, +${f} more`:"");r=`${u} file${u!==1?"s":""}${a} \u2014 ${E.muted}${h}${E.reset}`}break}case"list_directory":{if(o==="(empty)")r="0 entries";else{let a=o.split(`
40
40
  `).filter(Boolean),c=a.length,l=a.slice(0,6).join(", "),u=c-6;r=u>0?`${c} entries \u2014 ${E.muted}${l}, +${u} more${E.reset}`:`${c} entr${c!==1?"ies":"y"} \u2014 ${E.muted}${l}${E.reset}`}break}case"git_status":{let a=o.match(/Branch:\s*(\S+)/),c=o.split(`
41
41
  `).filter(l=>/^\s*[MADRCU?!]/.test(l)).length;r=a?`${a[1]} \xB7 ${c} change${c!==1?"s":""}`:"Done";break}case"git_diff":{let a=(o.match(/^\+[^+]/gm)||[]).length,c=(o.match(/^-[^-]/gm)||[]).length;r=a||c?`+${a} \u2212${c} lines`:"No diff";break}case"git_log":{let a=o.split(`
42
42
  `).filter(d=>/^commit\s+[0-9a-f]{7}/.test(d)),c=a.length,l=a[0]?a[0].replace(/^commit\s+/,"").substring(0,7):null,u=(()=>{let d=o.indexOf(a[0]||"\0");return d===-1?null:o.substring(d).split(`
43
- `).find((h,m)=>m>0&&h.trim()&&!h.startsWith("Author:")&&!h.startsWith("Date:")&&!h.startsWith("Merge:"))})();if(c===0)r="Log retrieved";else if(l&&u){let d=c>1?` ${E.muted}+${c-1} more${E.reset}`:"";r=`${l} ${E.muted}${u.trim().substring(0,60)}${E.reset}${d}`}else r=`${c} commit${c!==1?"s":""}`;break}case"git_commit":{let a=o.match(/\[[\w./\-]+ ([0-9a-f]{7,})\]/),c=o.match(/\[[\w./\-]+ [0-9a-f]+\]\s+(.+)/);r=a?`${a[1]}${c?` \u2014 ${c[1].substring(0,55)}`:""}`:"Committed";break}case"git_push":{let a=o.match(/(?:->|→)\s*(\S+)/);r=a?`\u2192 ${a[1]}`:"Pushed";break}case"git_pull":{if(/Already up.to.date/i.test(o))r="Already up to date";else{let a=(o.match(/^\+/gm)||[]).length;r=a>0?`Pulled \xB7 +${a} lines`:"Pulled"}break}case"web_fetch":{let a=o.match(/<title[^>]*>([^<]{1,80})<\/title>/i),c=o.match(/^#\s+(.{1,80})/m),l=e.url||"",u="";try{u=new URL(l).hostname}catch{u=l.substring(0,60)}let d=a?a[1].trim():c?c[1].trim():null;r=d?`${u} \u2014 ${E.muted}${d.substring(0,70)}${E.reset}`:`Fetched ${u}`;break}case"web_search":{let a=o.split(`
43
+ `).find((h,g)=>g>0&&h.trim()&&!h.startsWith("Author:")&&!h.startsWith("Date:")&&!h.startsWith("Merge:"))})();if(c===0)r="Log retrieved";else if(l&&u){let d=c>1?` ${E.muted}+${c-1} more${E.reset}`:"";r=`${l} ${E.muted}${u.trim().substring(0,60)}${E.reset}${d}`}else r=`${c} commit${c!==1?"s":""}`;break}case"git_commit":{let a=o.match(/\[[\w./\-]+ ([0-9a-f]{7,})\]/),c=o.match(/\[[\w./\-]+ [0-9a-f]+\]\s+(.+)/);r=a?`${a[1]}${c?` \u2014 ${c[1].substring(0,55)}`:""}`:"Committed";break}case"git_push":{let a=o.match(/(?:->|→)\s*(\S+)/);r=a?`\u2192 ${a[1]}`:"Pushed";break}case"git_pull":{if(/Already up.to.date/i.test(o))r="Already up to date";else{let a=(o.match(/^\+/gm)||[]).length;r=a>0?`Pulled \xB7 +${a} lines`:"Pulled"}break}case"web_fetch":{let a=o.match(/<title[^>]*>([^<]{1,80})<\/title>/i),c=o.match(/^#\s+(.{1,80})/m),l=e.url||"",u="";try{u=new URL(l).hostname}catch{u=l.substring(0,60)}let d=a?a[1].trim():c?c[1].trim():null;r=d?`${u} \u2014 ${E.muted}${d.substring(0,70)}${E.reset}`:`Fetched ${u}`;break}case"web_search":{let a=o.split(`
44
44
 
45
45
  `).filter(Boolean),c=a.length,l=a[0]?a[0].split(`
46
46
  `)[0].replace(/^\d+\.\s*/,"").trim():null,u=l?` ${E.muted}\u2014 ${l.substring(0,70)}${E.reset}`:"";r=`${c} result${c!==1?"s":""}${u}`;break}case"task_list":r="Done";break;case"spawn_agents":{let a=(o.match(/✓ Agent/g)||[]).length,c=(o.match(/✗ Agent/g)||[]).length;r=c>0?`${a} done, ${c} failed`:`${a} agent${a!==1?"s":""} done`;break}case"switch_model":{let a=o.match(/Switched to (.+)/);r=a?`\u2192 ${a[1]}`:"Done";break}case"ssh_exec":{let c=o.startsWith("EXIT ")||o.startsWith("Command failed"),l=o.split(`
47
- `).filter(d=>d.trim()&&!d.startsWith("EXIT ")),u=c?`${E.error}\u2717${E.reset}`:`${E.success}\u2713${E.reset}`;if(l.length===0)r=u;else{if(l.length>2&&l.every(g=>/^\[/.test(g.trim()))){r=`${u} ${l.length} log lines`;break}let f=c?l.slice(-3):l.slice(0,3),h=l.length-3,m=f.map((g,b)=>b===0?`${u} ${E.muted}${g.substring(0,120)}${E.reset}`:` ${E.muted}${g.substring(0,120)}${E.reset}`);if(h>0){let g=c?` ${E.subtle}${h} lines above\u2026${E.reset}`:` ${E.subtle}\u2026 +${h} lines${E.reset}`;c?m.unshift(g):m.push(g)}r=m.join(`
47
+ `).filter(d=>d.trim()&&!d.startsWith("EXIT ")),u=c?`${E.error}\u2717${E.reset}`:`${E.success}\u2713${E.reset}`;if(l.length===0)r=u;else{if(l.length>2&&l.every(m=>/^\[/.test(m.trim()))){r=`${u} ${l.length} log lines`;break}let f=c?l.slice(-3):l.slice(0,3),h=l.length-3,g=f.map((m,b)=>b===0?`${u} ${E.muted}${m.substring(0,120)}${E.reset}`:` ${E.muted}${m.substring(0,120)}${E.reset}`);if(h>0){let m=c?` ${E.subtle}${h} lines above\u2026${E.reset}`:` ${E.subtle}\u2026 +${h} lines${E.reset}`;c?g.unshift(m):g.push(m)}r=g.join(`
48
48
  `)}break}default:{let a=o.split(`
49
- `).filter(c=>c.trim()&&!c.startsWith("EXIT ")&&!c.startsWith("HINT:"));if(a.length>0){let c=a[0].trim().substring(0,90),l=a.length>1?` ${E.subtle}\u2026 +${a.length-1} lines${E.reset}`:"";r=`${E.muted}${c}${E.reset}${l}`}else r="Done"}}return` ${E.muted}\u23BF ${r}${E.reset}`}function wm(t,e,s,n,o,r){let i=Math.round(n/1e3),a=i>=60?`${Math.floor(i/60)}m ${i%60}s`:`${i}s`,c=`
50
- ${E.success}\u25C6${Je.reset} ${Je.bold}${t}${Je.reset}`;return c+=`${Je.dim} \xB7 ${a}`,r.size>0&&(c+=` \xB7 ${r.size} file${r.size!==1?"s":""} modified`),c+=Je.reset,c}ol.exports={C:Je,formatToolCall:mm,formatResult:gm,getToolSpinnerText:ym,formatToolSummary:$m,formatSectionHeader:hm,formatMilestone:wm}});var Ue=se((uk,al)=>{var{T:an}=ks(),xi=an,il=["01100110","01111110","01111110","01011010","01111110","00111100"];function bm(t,e){let s=[];for(let n=0;n<t.length;n+=2){let o="";for(let r=0;r<t[0].length;r++){let i=t[n][r]==="1",a=n+1<t.length&&t[n+1][r]==="1";i&&a?o+=`${e}\u2588\x1B[0m`:i&&!a?o+=`${e}\u2580\x1B[0m`:!i&&a?o+=`${e}\u2584\x1B[0m`:o+=" "}s.push(o)}return s}function _m(t,e,s={}){let n=xi.bold,o=xi.reset,r=bm(il,an.banner_logo),i=s.yolo?` ${n}${an.banner_yolo}\u26A1 YOLO${o}`:"",a=No().version,c=[` ${an.banner_name}${n}nex-code${o} ${an.banner_version}v${a}${o}`,` ${an.banner_model}${t}${o} ${an.muted}\xB7 /help${o}${i}`,""],l=Math.max(r.length,c.length),u=Math.floor((l-r.length)/2),d=Math.floor((l-c.length)/2),f=il[0].length,h=[];for(let m=0;m<l;m++){let g=r[m-u]??" ".repeat(f),b=c[m-d]??"";h.push(g+b)}console.log(`
49
+ `).filter(c=>c.trim()&&!c.startsWith("EXIT ")&&!c.startsWith("HINT:"));if(a.length>0){let c=a[0].trim().substring(0,90),l=a.length>1?` ${E.subtle}\u2026 +${a.length-1} lines${E.reset}`:"";r=`${E.muted}${c}${E.reset}${l}`}else r="Done"}}return` ${E.muted}\u23BF ${r}${E.reset}`}function Om(t,e,s,n,o,r){let i=Math.round(n/1e3),a=i>=60?`${Math.floor(i/60)}m ${i%60}s`:`${i}s`,c=`
50
+ ${E.success}\u25C6${Ze.reset} ${Ze.bold}${t}${Ze.reset}`;return c+=`${Ze.dim} \xB7 ${a}`,r.size>0&&(c+=` \xB7 ${r.size} file${r.size!==1?"s":""} modified`),c+=Ze.reset,c}$l.exports={C:Ze,formatToolCall:Sm,formatResult:Em,getToolSpinnerText:Cm,formatToolSummary:Am,formatSectionHeader:vm,formatMilestone:Om,getThinkingVerb:Rm,setActiveModelForSpinner:Tm,THINKING_VERBS:qo}});var He=re((Ok,_l)=>{var{T:un}=Es(),Ai=un,bl=["01100110","01111110","01111110","01011010","01111110","00111100"];function Nm(t,e){let s=[];for(let n=0;n<t.length;n+=2){let o="";for(let r=0;r<t[0].length;r++){let i=t[n][r]==="1",a=n+1<t.length&&t[n+1][r]==="1";i&&a?o+=`${e}\u2588\x1B[0m`:i&&!a?o+=`${e}\u2580\x1B[0m`:!i&&a?o+=`${e}\u2584\x1B[0m`:o+=" "}s.push(o)}return s}function Mm(t,e,s={}){let n=Ai.bold,o=Ai.reset,r=Nm(bl,un.banner_logo),i=s.yolo?` ${n}${un.banner_yolo}\u26A1 YOLO${o}`:"",a=Lo().version,c=[` ${un.banner_name}${n}nex-code${o} ${un.banner_version}v${a}${o}`,` ${un.banner_model}${t}${o} ${un.muted}\xB7 /help${o}${i}`,""],l=Math.max(r.length,c.length),u=Math.floor((l-r.length)/2),d=Math.floor((l-c.length)/2),f=bl[0].length,h=[];for(let g=0;g<l;g++){let m=r[g-u]??" ".repeat(f),b=c[g-d]??"";h.push(m+b)}console.log(`
51
51
  `+h.join(`
52
52
  `)+`
53
- `)}var{Spinner:xm,MultiProgress:km,TaskProgress:vm,ToolProgress:Sm,setActiveTaskProgress:Em,getActiveTaskProgress:Tm,cleanupTerminal:Rm}=Hn(),{formatToolCall:Cm,formatResult:Am,getToolSpinnerText:Om,formatToolSummary:Nm,formatSectionHeader:Mm,formatMilestone:Lm}=rl();al.exports={C:xi,banner:_m,Spinner:xm,MultiProgress:km,TaskProgress:vm,ToolProgress:Sm,setActiveTaskProgress:Em,getActiveTaskProgress:Tm,cleanupTerminal:Rm,formatToolCall:Cm,formatResult:Am,getToolSpinnerText:Om,formatToolSummary:Nm,formatSectionHeader:Mm,formatMilestone:Lm}});var Gn=se((dk,cl)=>{async function Pm(t,e){if(!t.response?.data)return t.message;let s=t.response.data;if(typeof s=="object"&&s!==null&&typeof s.pipe!="function")return e(s)||t.message;try{let n=await new Promise((r,i)=>{let a=[];s.on("data",c=>a.push(c)),s.on("end",()=>r(Buffer.concat(a).toString("utf8"))),s.on("error",i)}),o=JSON.parse(n);return e(o)||n||t.message}catch{return t.message}}var ki=class t{constructor(e={}){if(new.target===t)throw new Error("BaseProvider is abstract \u2014 use a concrete provider");this.name=e.name||"unknown",this.baseUrl=e.baseUrl||"",this.models=e.models||{},this.defaultModel=e.defaultModel||null}isConfigured(){throw new Error(`${this.name}: isConfigured() not implemented`)}getApiKey(){return null}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}getModel(e){return this.models[e]||null}async chat(e,s,n={}){throw new Error(`${this.name}: chat() not implemented`)}async stream(e,s,n={}){throw new Error(`${this.name}: stream() not implemented`)}formatMessages(e){return{messages:e}}formatTools(e){return e}normalizeResponse(e){throw new Error(`${this.name}: normalizeResponse() not implemented`)}};cl.exports={BaseProvider:ki,readStreamErrorBody:Pm}});var zn=se((fk,ll)=>{var Yn=class{buildRequestBody(e){throw new Error("buildRequestBody() not implemented")}getEndpoint(){throw new Error("getEndpoint() not implemented")}formatTools(e){return e}normalizeResponse(e){throw new Error("normalizeResponse() not implemented")}createStreamParser(e,s={}){throw new Error("createStreamParser() not implemented")}},Kn=class{constructor(e,s={}){this.onToken=e,this.callbacks=s,this.content="",this.buffer=""}feed(e){this.buffer+=e;let s=this.buffer.split(`
54
- `);this.buffer=s.pop()||"";for(let n of s){let o=this.parseLine(n);if(o?.done)return o}return{done:!1}}flush(){return this.buffer.trim()&&(this.parseLine(this.buffer),this.buffer=""),this.getResult()}parseLine(e){throw new Error("parseLine() not implemented")}getResult(){throw new Error("getResult() not implemented")}},jo=class extends Kn{constructor(e,s={}){super(e,s),this.toolCallsMap={}}parseLine(e){let s=e.trim();if(!s||!s.startsWith("data: "))return{done:!1};let n=s.slice(6);if(n==="[DONE]")return{done:!0,result:this.getResult()};let o;try{o=JSON.parse(n)}catch{return{done:!1}}let r=o.choices?.[0]?.delta;if(!r)return{done:!1};if(r.content&&(this.onToken(r.content),this.content+=r.content),r.tool_calls)for(let i of r.tool_calls){let a=i.index??0;this.toolCallsMap[a]||(this.toolCallsMap[a]={id:i.id||"",name:"",arguments:""}),i.id&&(this.toolCallsMap[a].id=i.id),i.function?.name&&(this.toolCallsMap[a].name+=i.function.name),i.function?.arguments&&(this.toolCallsMap[a].arguments+=i.function.arguments)}return{done:!1}}getResult(){return{content:this.content,tool_calls:Object.values(this.toolCallsMap).filter(e=>e.name).map(e=>({id:e.id||`call-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,function:{name:e.name,arguments:e.arguments}}))}}},Do=class extends Yn{getEndpoint(){return"/chat/completions"}buildRequestBody({model:e,messages:s,tools:n,maxTokens:o,temperature:r,stream:i}){let a={model:e,messages:s,max_tokens:o,temperature:r};return i&&(a.stream=!0),n&&n.length>0&&(a.tools=n),a}normalizeResponse(e){let s=e.choices?.[0]?.message||{},n=(s.tool_calls||[]).map(o=>({id:o.id,function:{name:o.function.name,arguments:o.function.arguments}}));return{content:s.content||"",tool_calls:n}}createStreamParser(e,s={}){return new jo(e,s)}},qo=class extends Kn{constructor(e,s={}){super(e,s),this.toolUses=[],this.currentToolIndex=-1}parseLine(e){let s=e.trim();if(!s.startsWith("data: "))return{done:!1};let n=s.slice(6),o;try{o=JSON.parse(n)}catch{return{done:!1}}switch(o.type){case"content_block_start":{let r=o.content_block;r?.type==="tool_use"&&(this.currentToolIndex=this.toolUses.length,this.toolUses.push({id:r.id,name:r.name,inputJson:""}));break}case"content_block_delta":{let r=o.delta;r?.type==="text_delta"&&r.text&&(this.onToken(r.text),this.content+=r.text),r?.type==="input_json_delta"&&r.partial_json!==void 0&&this.currentToolIndex>=0&&(this.toolUses[this.currentToolIndex].inputJson+=r.partial_json);break}case"content_block_stop":this.currentToolIndex=-1;break;case"message_stop":return{done:!0,result:this.getResult()}}return{done:!1}}getResult(){return{content:this.content,tool_calls:this.toolUses.filter(e=>e.name).map(e=>{let s={};if(e.inputJson)try{s=JSON.parse(e.inputJson)}catch{s=e.inputJson}return{id:e.id||`anthropic-${Date.now()}`,function:{name:e.name,arguments:s}}})}}},Fo=class extends Yn{getEndpoint(){return"/messages"}buildRequestBody({model:e,messages:s,tools:n,maxTokens:o,temperature:r,stream:i,extra:a}){let c={model:e,messages:s,max_tokens:o,temperature:r};return i&&(c.stream=!0),a?.system&&(c.system=a.system),n&&n.length>0&&(c.tools=n),c}formatTools(e){return!e||e.length===0?[]:e.map(s=>({name:s.function.name,description:s.function.description||"",input_schema:s.function.parameters||{type:"object",properties:{}}}))}normalizeResponse(e){let s="",n=[];for(let o of e.content||[])o.type==="text"?s+=o.text:o.type==="tool_use"&&n.push({id:o.id,function:{name:o.name,arguments:o.input}});return{content:s,tool_calls:n}}createStreamParser(e,s={}){return new qo(e,s)}},Bo=class extends Kn{constructor(e,s={}){super(e,s),this.toolCalls=[],this.onThinkingToken=s.onThinkingToken||(()=>{})}parseLine(e){if(!e.trim())return{done:!1};let s;try{s=JSON.parse(e)}catch{return{done:!1}}return s.message?.thinking&&this.onThinkingToken(s.message.thinking),s.message?.content&&(this.onToken(s.message.content),this.content+=s.message.content),s.message?.tool_calls&&(this.toolCalls=this.toolCalls.concat(s.message.tool_calls)),s.done?{done:!0,result:this.getResult()}:{done:!1}}getResult(){return{content:this.content,tool_calls:this.toolCalls.map((e,s)=>({id:e.id||`ollama-${Date.now()}-${s}`,function:{name:e.function?.name||e.name||"unknown",arguments:e.function?.arguments||e.arguments||{}}}))}}},Wo=class extends Yn{getEndpoint(){return"/api/chat"}buildRequestBody({model:e,messages:s,tools:n,maxTokens:o,temperature:r,stream:i,extra:a}){let c={model:e,messages:s,stream:i,options:{temperature:r,num_predict:o,repeat_penalty:a?.repeat_penalty??1.05}};return n&&n.length>0&&(c.tools=n),c}normalizeResponse(e){let s=e.message||{};return{content:s.content||"",tool_calls:(s.tool_calls||[]).map((n,o)=>({id:n.id||`ollama-${Date.now()}-${o}`,function:{name:n.function?.name||n.name||"unknown",arguments:n.function?.arguments||n.arguments||{}}}))}}createStreamParser(e,s={}){return new Bo(e,s)}},Im=new Do,jm=new Fo,Dm=new Wo;ll.exports={WireProtocol:Yn,StreamParser:Kn,OpenAICompatibleProtocol:Do,AnthropicProtocol:Fo,OllamaChatProtocol:Wo,OpenAIStreamParser:jo,AnthropicStreamParser:qo,OllamaStreamParser:Bo,openaiProtocol:Im,anthropicProtocol:jm,ollamaProtocol:Dm}});var fl=se((pk,dl)=>{var Uo=require("axios"),qm=require("http"),Fm=require("https"),{BaseProvider:Bm,readStreamErrorBody:Wm}=Gn(),{ollamaProtocol:cn}=zn(),Ho=new qm.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Go=new Fm.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),ul={"qwen3-coder:480b":{id:"qwen3-coder:480b",name:"Qwen3 Coder 480B",maxTokens:16384,contextWindow:131072},"qwen3-coder-next":{id:"qwen3-coder-next",name:"Qwen3 Coder Next",maxTokens:16384,contextWindow:262144},"devstral-2:123b":{id:"devstral-2:123b",name:"Devstral 2 123B",maxTokens:16384,contextWindow:131072},"devstral-small-2:24b":{id:"devstral-small-2:24b",name:"Devstral Small 2 24B",maxTokens:16384,contextWindow:131072},"minimax-m2.7:cloud":{id:"minimax-m2.7:cloud",name:"MiniMax M2.7 Cloud",maxTokens:16384,contextWindow:131072},"kimi-k2.5":{id:"kimi-k2.5",name:"Kimi K2.5",maxTokens:16384,contextWindow:256e3},"kimi-k2:1t":{id:"kimi-k2:1t",name:"Kimi K2 1T",maxTokens:16384,contextWindow:256e3},"kimi-k2-thinking":{id:"kimi-k2-thinking",name:"Kimi K2 Thinking",maxTokens:16384,contextWindow:256e3},"deepseek-v3.2":{id:"deepseek-v3.2",name:"DeepSeek V3.2",maxTokens:16384,contextWindow:131072},"deepseek-v3.1:671b":{id:"deepseek-v3.1:671b",name:"DeepSeek V3.1 671B",maxTokens:16384,contextWindow:131072},"cogito-2.1:671b":{id:"cogito-2.1:671b",name:"Cogito 2.1 671B",maxTokens:16384,contextWindow:131072},"qwen3.5:397b-cloud":{id:"qwen3.5:397b-cloud",name:"Qwen3.5 397B Cloud",maxTokens:16384,contextWindow:262144},"qwen3.5:397b":{id:"qwen3.5:397b",name:"Qwen3.5 397B",maxTokens:16384,contextWindow:262144},"qwen3.5:122b-a10b":{id:"qwen3.5:122b-a10b",name:"Qwen3.5 122B-A10B",maxTokens:16384,contextWindow:262144},"qwen3.5:35b-a3b":{id:"qwen3.5:35b-a3b",name:"Qwen3.5 35B-A3B",maxTokens:16384,contextWindow:262144},"qwen3.5:27b":{id:"qwen3.5:27b",name:"Qwen3.5 27B",maxTokens:16384,contextWindow:262144},"qwen3-next:80b":{id:"qwen3-next:80b",name:"Qwen3 Next 80B",maxTokens:16384,contextWindow:131072},"mistral-large-3:675b":{id:"mistral-large-3:675b",name:"Mistral Large 3 675B",maxTokens:16384,contextWindow:131072},"gpt-oss:120b":{id:"gpt-oss:120b",name:"GPT-OSS 120B",maxTokens:16384,contextWindow:131072},"minimax-m2.5":{id:"minimax-m2.5",name:"MiniMax M2.5",maxTokens:16384,contextWindow:131072},"glm-5:cloud":{id:"glm-5:cloud",name:"GLM 5 Cloud",maxTokens:16384,contextWindow:2e5},"glm-5":{id:"glm-5",name:"GLM 5",maxTokens:16384,contextWindow:2e5},"glm-4.6":{id:"glm-4.6",name:"GLM 4.6",maxTokens:16384,contextWindow:2e5},"glm-4.7":{id:"glm-4.7",name:"GLM 4.7",maxTokens:16384,contextWindow:128e3},"nemotron-3-super:cloud":{id:"nemotron-3-super:cloud",name:"Nemotron 3 Super Cloud",maxTokens:16384,contextWindow:262144},"qwen3.5:9b":{id:"qwen3.5:9b",name:"Qwen3.5 9B",maxTokens:8192,contextWindow:262144},"qwen3.5:4b":{id:"qwen3.5:4b",name:"Qwen3.5 4B",maxTokens:8192,contextWindow:262144},"qwen3.5:2b":{id:"qwen3.5:2b",name:"Qwen3.5 2B",maxTokens:8192,contextWindow:262144},"qwen3.5:0.8b":{id:"qwen3.5:0.8b",name:"Qwen3.5 0.8B",maxTokens:8192,contextWindow:262144},"gemma3:27b":{id:"gemma3:27b",name:"Gemma 3 27B",maxTokens:8192,contextWindow:131072},"gemma3:12b":{id:"gemma3:12b",name:"Gemma 3 12B",maxTokens:8192,contextWindow:131072},"gemma3:4b":{id:"gemma3:4b",name:"Gemma 3 4B",maxTokens:8192,contextWindow:131072},"ministral-3:14b":{id:"ministral-3:14b",name:"Ministral 3 14B",maxTokens:8192,contextWindow:131072},"ministral-3:8b":{id:"ministral-3:8b",name:"Ministral 3 8B",maxTokens:8192,contextWindow:131072},"gemini-3-flash-preview":{id:"gemini-3-flash-preview",name:"Gemini 3 Flash Preview",maxTokens:16384,contextWindow:131072}},vi=class extends Bm{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||ul,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){Uo.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Ho,httpsAgent:Go}).then(e=>{let s=e.data?.models||[];for(let n of s){let o=(n.name||n.model||"").replace(/:latest$/,"");!o||this.models[o]||(this.models[o]={id:o,name:n.name||o,maxTokens:16384,contextWindow:131072})}}).catch(()=>{});return}try{let s=(await Uo.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Ho,httpsAgent:Go})).data?.models||[];for(let n of s){let o=(n.name||n.model||"").replace(/:latest$/,"");!o||this.models[o]||(this.models[o]={id:o,name:n.name||o,maxTokens:16384,contextWindow:131072})}}catch{}}}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OLLAMA_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OLLAMA_API_KEY not set");return{Authorization:`Bearer ${e}`}}_formatMessages(e){return e.map(s=>{if(s.role==="user"&&Array.isArray(s.content)){let n=[],o=[];for(let i of s.content)i.type==="text"?n.push(i.text??""):i.type==="image"&&i.data&&o.push(i.data);let r={role:"user",content:n.join(`
55
- `)};return o.length>0&&(r.images=o),r}return s})}async chat(e,s,n={}){await this.discoverModels();let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||16384,a=cn.buildRequestBody({model:o,messages:this._formatMessages(e),tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!1,extra:{repeat_penalty:n.repeat_penalty}}),c;try{c=await Uo.post(`${this.baseUrl}${cn.getEndpoint()}`,a,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),httpAgent:Ho,httpsAgent:Go})}catch(l){if(l.name==="CanceledError"||l.name==="AbortError"||l.code==="ERR_CANCELED")throw l;let u=l.response?.status?` [HTTP ${l.response.status}]`:"",d=l.response?.data?.error||l.message;throw new Error(`API Error${u}: ${d}`)}return cn.normalizeResponse(c.data)}async stream(e,s,n={}){await this.discoverModels();let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||16384,a=n.onToken||(()=>{}),c=n.onThinkingToken||(()=>{}),l=cn.buildRequestBody({model:o,messages:this._formatMessages(e),tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!0,extra:{repeat_penalty:n.repeat_penalty}}),u;try{u=await Uo.post(`${this.baseUrl}${cn.getEndpoint()}`,l,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal,httpAgent:Ho,httpsAgent:Go})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let h=f.response?.status?` [HTTP ${f.response.status}]`:"",m=await Wm(f,g=>g?.error);throw new Error(`API Error${h}: ${m}`)}let d=cn.createStreamParser(a,{onThinkingToken:c});return new Promise((f,h)=>{n.signal&&n.signal.addEventListener("abort",()=>{u.data.destroy(),h(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",m=>{let{done:g,result:b}=d.feed(m.toString());g&&f(b)}),u.data.on("error",m=>{n.signal?.aborted||h(new Error(`Stream error: ${m.message}`))}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return cn.normalizeResponse(e)}};dl.exports={OllamaProvider:vi,OLLAMA_MODELS:ul}});var gl=se((hk,ml)=>{var pl=require("axios"),{BaseProvider:Um,readStreamErrorBody:Hm}=Gn(),{openaiProtocol:ln}=zn(),hl={"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}},Si=class extends Um{constructor(e={}){super({name:"openai",baseUrl:e.baseUrl||"https://api.openai.com/v1",models:e.models||hl,defaultModel:e.defaultModel||"gpt-4o",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OPENAI_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OPENAI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let s=[];for(let n of e){if(this._messageFormatCache.has(n)){s.push(this._messageFormatCache.get(n));continue}let o=this._getMessageCacheKey(n);if(this._messageStringCache.has(o)){let i=this._messageStringCache.get(o);this._messageFormatCache.set(n,i),s.push(i);continue}let r=this._formatSingleMessage(n);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(o,r),this._messageFormatCache.set(n,r),s.push(r)}return{messages:s}}_getMessageCacheKey(e){let s=e.role||"",n=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${s}:${n.length}:${o}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||null,tool_calls:e.tool_calls.map(s=>({id:s.id||`call-${Date.now()}`,type:"function",function:{name:s.function.name,arguments:typeof s.function.arguments=="string"?s.function.arguments:JSON.stringify(s.function.arguments)}}))};if(e.role==="tool")return{role:"tool",content:typeof e.content=="string"?e.content:JSON.stringify(e.content),tool_call_id:e.tool_call_id};if(e.role==="user"&&Array.isArray(e.content)){let s=[];for(let n of e.content)if(n.type==="text")s.push({type:"text",text:n.text??""});else if(n.type==="image"&&n.data){let o=n.data.startsWith("data:")?n.data:`data:${n.media_type||"image/png"};base64,${n.data}`;s.push({type:"image_url",image_url:{url:o,detail:"auto"}})}return{role:"user",content:s}}return{role:e.role,content:e.content}}async chat(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||16384,{messages:a}=this.formatMessages(e),c=ln.buildRequestBody({model:o,messages:a,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!1}),l;try{l=await pl.post(`${this.baseUrl}${ln.getEndpoint()}`,c,{timeout:n.timeout||this.timeout,headers:this._getHeaders()})}catch(u){if(u.name==="CanceledError"||u.name==="AbortError"||u.code==="ERR_CANCELED")throw u;let d=u.response?.status?` [HTTP ${u.response.status}]`:"",f=u.response?.data?.error?.message||u.response?.data?.error||u.message;throw new Error(`API Error${d}: ${f}`)}return ln.normalizeResponse(l.data)}async stream(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||16384,a=n.onToken||(()=>{}),{messages:c}=this.formatMessages(e),l=ln.buildRequestBody({model:o,messages:c,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!0}),u;try{u=await pl.post(`${this.baseUrl}${ln.getEndpoint()}`,l,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let h=f.response?.status?` [HTTP ${f.response.status}]`:"",m=await Hm(f,g=>g?.error?.message||g?.error);throw new Error(`API Error${h}: ${m}`)}let d=ln.createStreamParser(a);return new Promise((f,h)=>{n.signal&&n.signal.addEventListener("abort",()=>{u.data.destroy(),h(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",m=>{let{done:g,result:b}=d.feed(m.toString());g&&f(b)}),u.data.on("error",m=>{n.signal?.aborted||h(new Error(`Stream error: ${m.message}`))}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return ln.normalizeResponse(e)}};ml.exports={OpenAIProvider:Si,OPENAI_MODELS:hl}});var bl=se((mk,wl)=>{var yl=require("axios"),{BaseProvider:Gm,readStreamErrorBody:Ym}=Gn(),{anthropicProtocol:Vt}=zn(),$l={"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}},Km="2023-06-01",Ei=class extends Gm{constructor(e={}){super({name:"anthropic",baseUrl:e.baseUrl||"https://api.anthropic.com/v1",models:e.models||$l,defaultModel:e.defaultModel||"claude-sonnet",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this.apiVersion=e.apiVersion||Km}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.ANTHROPIC_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("ANTHROPIC_API_KEY not set");return{"x-api-key":e,"anthropic-version":this.apiVersion,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let s="",n=[];for(let o of e){if(o.role==="system"){s+=(s?`
56
-
57
- `:"")+o.content;continue}if(o.role!=="system"&&o.role!=="tool"&&this._messageFormatCache.has(o)){n.push(this._messageFormatCache.get(o));continue}let r=this._formatSingleMessage(o,n);if(r){if(o.role!=="system"&&o.role!=="tool"&&this._messageStringCache.size<this._maxCacheSize){let i=this._getMessageCacheKey(o);this._messageStringCache.set(i,r),this._messageFormatCache.set(o,r)}n.push(r)}}for(let o=n.length-1;o>0;o--)n[o].role==="user"&&n[o-1].role==="user"&&n.splice(o,0,{role:"assistant",content:[{type:"text",text:"[continuing]"}]});return{messages:n,system:s}}_getMessageCacheKey(e){let s=e.role||"",n=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${s}:${n.length}:${o}`}_formatSingleMessage(e,s=[]){if(e.role==="assistant"){let n=[];if(e.content&&n.push({type:"text",text:e.content}),e.tool_calls)for(let o of e.tool_calls)n.push({type:"tool_use",id:o.id||`toolu-${Date.now()}`,name:o.function.name,input:typeof o.function.arguments=="string"?JSON.parse(o.function.arguments||"{}"):o.function.arguments||{}});return{role:"assistant",content:n.length>0?n:[{type:"text",text:""}]}}if(e.role==="tool"){let n=s[s.length-1],o={type:"tool_result",tool_use_id:e.tool_call_id,content:typeof e.content=="string"?e.content:JSON.stringify(e.content)};return n&&n.role==="user"&&Array.isArray(n.content)&&n.content[0]?.type==="tool_result"?(n.content.push(o),null):{role:"user",content:[o]}}if(Array.isArray(e.content)){let n=[];for(let o of e.content)o.type==="text"?n.push({type:"text",text:o.text??""}):o.type==="image"&&o.data&&n.push({type:"image",source:{type:"base64",media_type:o.media_type||"image/png",data:o.data}});return{role:"user",content:n}}return{role:"user",content:e.content}}formatTools(e){return Vt.formatTools(e)}_resolveModelId(e){return this.getModel(e)?.id||e}async chat(e,s,n={}){let o=n.model||this.defaultModel,r=this._resolveModelId(o),i=this.getModel(o),a=n.maxTokens||i?.maxTokens||8192,{messages:c,system:l}=this.formatMessages(e),u=this.formatTools(s),d=Vt.buildRequestBody({model:r,messages:c,tools:u,maxTokens:a,temperature:n.temperature??this.temperature,stream:!1,extra:{system:l}}),f;try{f=await yl.post(`${this.baseUrl}${Vt.getEndpoint()}`,d,{timeout:n.timeout||this.timeout,headers:this._getHeaders()})}catch(h){if(h.name==="CanceledError"||h.name==="AbortError"||h.code==="ERR_CANCELED")throw h;let m=h.response?.status?` [HTTP ${h.response.status}]`:"",g=h.response?.data?.error?.message||h.response?.data?.error||h.message;throw new Error(`API Error${m}: ${g}`)}return Vt.normalizeResponse(f.data)}async stream(e,s,n={}){let o=n.model||this.defaultModel,r=this._resolveModelId(o),i=this.getModel(o),a=n.maxTokens||i?.maxTokens||8192,c=n.onToken||(()=>{}),{messages:l,system:u}=this.formatMessages(e),d=this.formatTools(s),f=Vt.buildRequestBody({model:r,messages:l,tools:d,maxTokens:a,temperature:n.temperature??this.temperature,stream:!0,extra:{system:u}}),h;try{h=await yl.post(`${this.baseUrl}${Vt.getEndpoint()}`,f,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(g){if(g.name==="CanceledError"||g.name==="AbortError"||g.code==="ERR_CANCELED")throw g;let b=g.response?.status?` [HTTP ${g.response.status}]`:"",v=await Ym(g,O=>O?.error?.message||O?.error);throw new Error(`API Error${b}: ${v}`)}let m=Vt.createStreamParser(c);return new Promise((g,b)=>{n.signal&&n.signal.addEventListener("abort",()=>{h.data.destroy(),b(new DOMException("The operation was aborted","AbortError"))},{once:!0}),h.data.on("data",v=>{let{done:O,result:U}=m.feed(v.toString());O&&g(U)}),h.data.on("error",v=>{n.signal?.aborted||b(new Error(`Stream error: ${v.message}`))}),h.data.on("end",()=>{g(m.flush())})})}normalizeResponse(e){return Vt.normalizeResponse(e)}};wl.exports={AnthropicProvider:Ei,ANTHROPIC_MODELS:$l}});var vl=se((gk,kl)=>{var _l=require("axios"),{BaseProvider:zm,readStreamErrorBody:Xm}=Gn(),{openaiProtocol:un}=zn(),xl={"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}},Ti=class extends zm{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||xl,defaultModel:e.defaultModel||"gemini-2.5-flash",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("GEMINI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let s=[];for(let n of e){if(this._messageFormatCache.has(n)){s.push(this._messageFormatCache.get(n));continue}let o=this._getMessageCacheKey(n);if(this._messageStringCache.has(o)){let i=this._messageStringCache.get(o);this._messageFormatCache.set(n,i),s.push(i);continue}let r=this._formatSingleMessage(n);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(o,r),this._messageFormatCache.set(n,r),s.push(r)}return{messages:s}}_getMessageCacheKey(e){let s=e.role||"",n=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${s}:${n.length}:${o}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||"",tool_calls:e.tool_calls.map(s=>({id:s.id||`call-${Date.now()}`,type:"function",function:{name:s.function.name,arguments:typeof s.function.arguments=="string"?s.function.arguments:JSON.stringify(s.function.arguments)}}))};if(e.role==="tool")return{role:"tool",content:typeof e.content=="string"?e.content:JSON.stringify(e.content),tool_call_id:e.tool_call_id};if(e.role==="user"&&Array.isArray(e.content)){let s=[];for(let n of e.content)if(n.type==="text")s.push({type:"text",text:n.text??""});else if(n.type==="image"&&n.data){let o=n.data.startsWith("data:")?n.data:`data:${n.media_type||"image/png"};base64,${n.data}`;s.push({type:"image_url",image_url:{url:o,detail:"auto"}})}return{role:"user",content:s}}return{role:e.role,content:e.content}}async chat(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||8192,{messages:a}=this.formatMessages(e),c=un.buildRequestBody({model:o,messages:a,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!1}),l;try{l=await _l.post(`${this.baseUrl}${un.getEndpoint()}`,c,{timeout:n.timeout||this.timeout,headers:this._getHeaders()})}catch(u){if(u.name==="CanceledError"||u.name==="AbortError"||u.code==="ERR_CANCELED")throw u;let d=u.response?.status?` [HTTP ${u.response.status}]`:"",f=u.response?.data?.error?.message||u.response?.data?.error||u.message;throw new Error(`API Error${d}: ${f}`)}return un.normalizeResponse(l.data)}async stream(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||8192,a=n.onToken||(()=>{}),{messages:c}=this.formatMessages(e),l=un.buildRequestBody({model:o,messages:c,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!0}),u;try{u=await _l.post(`${this.baseUrl}${un.getEndpoint()}`,l,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let h=f.response?.status?` [HTTP ${f.response.status}]`:"",m=await Xm(f,g=>g?.error?.message||g?.error);throw new Error(`API Error${h}: ${m}`)}let d=un.createStreamParser(a);return new Promise((f,h)=>{n.signal&&n.signal.addEventListener("abort",()=>{u.data.destroy(),h(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",m=>{let{done:g,result:b}=d.feed(m.toString());g&&f(b)}),u.data.on("error",m=>{n.signal?.aborted||h(new Error(`Stream error: ${m.message}`))}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return un.normalizeResponse(e)}};kl.exports={GeminiProvider:Ti,GEMINI_MODELS:xl}});var Tl=se((yk,El)=>{var Yo=require("axios"),{BaseProvider:Vm,readStreamErrorBody:Jm}=Gn(),{ollamaProtocol:dn}=zn(),Sl="http://localhost:11434",Ri=class extends Vm{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||Sl,models:e.models||{},defaultModel:e.defaultModel||null,...e}),this.timeout=e.timeout||3e5,this.temperature=e.temperature??.2,this._modelsLoaded=!1}isConfigured(){return!0}async loadModels(){if(this._modelsLoaded)return this.models;try{let s=(await Yo.get(`${this.baseUrl}/api/tags`,{timeout:5e3})).data?.models||[];this.models={};for(let n of s){let o=n.name||n.model;if(!o)continue;let r=o.replace(/:latest$/,""),i=32768;try{let a=await Yo.post(`${this.baseUrl}/api/show`,{name:o},{timeout:5e3}),c=a.data?.model_info||a.data?.details||{};i=c["general.context_length"]||c["llama.context_length"]||this._parseContextFromModelfile(a.data?.modelfile)||32768}catch{}this.models[r]={id:r,name:n.name,maxTokens:Math.min(8192,Math.floor(i*.1)),contextWindow:i}}!this.defaultModel&&Object.keys(this.models).length>0&&(this.defaultModel=Object.keys(this.models)[0]),this._modelsLoaded=!0}catch{this.models={},this._modelsLoaded=!1}return this.models}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}_formatMessages(e){return e.map(s=>{if(s.role==="user"&&Array.isArray(s.content)){let n=[],o=[];for(let i of s.content)i.type==="text"?n.push(i.text??""):i.type==="image"&&i.data&&o.push(i.data);let r={role:"user",content:n.join(`
58
- `)};return o.length>0&&(r.images=o),r}return s})}async chat(e,s,n={}){this._modelsLoaded||await this.loadModels();let o=n.model||this.defaultModel;if(!o)throw new Error("No local model available. Is Ollama running?");let r=dn.buildRequestBody({model:o,messages:this._formatMessages(e),tools:s,maxTokens:n.maxTokens||8192,temperature:n.temperature??this.temperature,stream:!1}),i;try{i=await Yo.post(`${this.baseUrl}${dn.getEndpoint()}`,r,{timeout:n.timeout||this.timeout})}catch(a){if(a.name==="CanceledError"||a.name==="AbortError"||a.code==="ERR_CANCELED")throw a;let c=a.response?.status?` [HTTP ${a.response.status}]`:"",l=a.response?.data?.error||a.message;throw new Error(`API Error${c}: ${l}`)}return dn.normalizeResponse(i.data)}async stream(e,s,n={}){this._modelsLoaded||await this.loadModels();let o=n.model||this.defaultModel;if(!o)throw new Error("No local model available. Is Ollama running?");let r=n.onToken||(()=>{}),i=dn.buildRequestBody({model:o,messages:this._formatMessages(e),tools:s,maxTokens:n.maxTokens||8192,temperature:n.temperature??this.temperature,stream:!0}),a;try{a=await Yo.post(`${this.baseUrl}${dn.getEndpoint()}`,i,{timeout:n.timeout||this.timeout,responseType:"stream",signal:n.signal})}catch(l){if(l.name==="CanceledError"||l.name==="AbortError"||l.code==="ERR_CANCELED")throw l;let u=l.response?.status?` [HTTP ${l.response.status}]`:"",d=await Jm(l,f=>f?.error);throw new Error(`API Error${u}: ${d}`)}let c=dn.createStreamParser(r);return new Promise((l,u)=>{n.signal&&n.signal.addEventListener("abort",()=>{a.data.destroy(),u(new DOMException("The operation was aborted","AbortError"))},{once:!0}),a.data.on("data",d=>{let{done:f,result:h}=c.feed(d.toString());f&&l(h)}),a.data.on("error",d=>{n.signal?.aborted||u(new Error(`Stream error: ${d.message}`))}),a.data.on("end",()=>{l(c.flush())})})}normalizeResponse(e){return dn.normalizeResponse(e)}_parseContextFromModelfile(e){if(!e)return null;let s=e.match(/PARAMETER\s+num_ctx\s+(\d+)/i);return s?parseInt(s[1],10):null}};El.exports={LocalProvider:Ri,DEFAULT_LOCAL_URL:Sl}});var fn=se(($k,Cl)=>{"use strict";var ut=require("fs"),Rl=require("path");function Zm(t){if(!t||isNaN(t))return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function Qm(t){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}catch{let e=Date.now()+t;for(;Date.now()<e;);}}function eg(t,e){let s=Rl.dirname(t),n=Rl.join(s,`.nex-tmp.${process.pid}.${Date.now()}`);try{ut.existsSync(s)||ut.mkdirSync(s,{recursive:!0}),ut.writeFileSync(n,e,"utf-8"),ut.renameSync(n,t)}catch(o){try{ut.unlinkSync(n)}catch{}throw o}}function tg(t,e,{timeout:s=5e3,retryMs:n=50}={}){let o=t+".lock",r=Date.now()+s;for(;;){let i=-1;try{i=ut.openSync(o,"wx"),ut.writeSync(i,Buffer.from(String(process.pid))),ut.closeSync(i),i=-1;try{return e()}finally{try{ut.unlinkSync(o)}catch{}}}catch(a){if(i!==-1)try{ut.closeSync(i)}catch{}if(a.code!=="EEXIST")throw a;try{let c=ut.readFileSync(o,"utf-8").trim(),l=parseInt(c,10);if(!Zm(l)){try{ut.unlinkSync(o)}catch{}continue}}catch(c){if(c.code&&c.code!=="ENOENT")throw c;continue}if(Date.now()>=r){try{ut.unlinkSync(o)}catch{}return e()}Qm(n)}}}Cl.exports={atomicWrite:eg,withFileLockSync:tg}});var zo=se((wk,Il)=>{var Xn=require("fs"),Ci=require("path"),{atomicWrite:ng,withFileLockSync:sg}=fn(),Al={openai:{"gpt-4o":{input:2.5,output:10},"gpt-4o-mini":{input:.15,output:.6},"gpt-4.1":{input:2,output:8},"gpt-4.1-mini":{input:.4,output:1.6},"gpt-4.1-nano":{input:.1,output:.4},o1:{input:15,output:60},o3:{input:10,output:40},"o3-mini":{input:1.1,output:4.4},"o4-mini":{input:1.1,output:4.4}},anthropic:{"claude-sonnet":{input:3,output:15},"claude-opus":{input:5,output:25},"claude-haiku":{input:.8,output:4},"claude-sonnet-4-5":{input:3,output:15},"claude-sonnet-4":{input:3,output:15}},gemini:{"gemini-2.5-pro":{input:1.25,output:10},"gemini-2.5-flash":{input:.15,output:.6},"gemini-2.0-flash":{input:.1,output:.4},"gemini-2.0-flash-lite":{input:.075,output:.3}},ollama:{"qwen3-coder:480b":{input:0,output:0},"qwen3-coder-next":{input:0,output:0},"devstral-2:123b":{input:0,output:0},"devstral-small-2:24b":{input:0,output:0},"kimi-k2.5":{input:0,output:0},"kimi-k2:1t":{input:0,output:0},"deepseek-v3.2":{input:0,output:0},"minimax-m2.5":{input:0,output:0},"glm-5":{input:0,output:0},"glm-4.7":{input:0,output:0},"gpt-oss:120b":{input:0,output:0}},local:{}},Ko=[],Jt={};function og(t,e,s,n){if(Ko.push({provider:t,model:e,input:s,output:n}),Jt[t]!==void 0){let o=Ll(t);o.allowed||process.stderr.write(`\x1B[33m\u26A0 Budget limit reached for ${t}: $${o.spent.toFixed(2)} / $${o.limit.toFixed(2)}\x1B[0m
59
- `)}}function Ai(t,e){let s=Al[t];return s?s[e]||{input:0,output:0}:{input:0,output:0}}function Ol(t){let e=Ai(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function Nl(){let t={};for(let r of Ko){let i=`${r.provider}:${r.model}`;t[i]||(t[i]={provider:r.provider,model:r.model,input:0,output:0}),t[i].input+=r.input,t[i].output+=r.output}let e=Object.values(t).map(r=>({...r,cost:Ol(r)})),s=e.reduce((r,i)=>r+i.cost,0),n=e.reduce((r,i)=>r+i.input,0),o=e.reduce((r,i)=>r+i.output,0);return{totalCost:s,totalInput:n,totalOutput:o,breakdown:e}}function rg(){let{totalCost:t,totalInput:e,totalOutput:s,breakdown:n}=Nl();if(n.length===0)return"No token usage recorded this session.";let o=[];o.push("Session Token Usage:"),o.push("");for(let r of n){let i=r.cost>0?`$${r.cost.toFixed(4)}`:"free";o.push(` ${r.provider}:${r.model}`),o.push(` Input: ${r.input.toLocaleString()} tokens`),o.push(` Output: ${r.output.toLocaleString()} tokens`),o.push(` Cost: ${i}`)}return o.push(""),o.push(` Total: ${e.toLocaleString()} in + ${s.toLocaleString()} out = $${t.toFixed(4)}`),o.join(`
60
- `)}function ig(t){return!t||typeof t!="string"?0:Math.ceil(t.length/4)}function ag(t,e,s,n){let o=Ai(t,e),r=(s*o.input+n*o.output)/1e6;return r<=0?"":`[~$${r.toFixed(4)}]`}function cg(){Ko=[]}function lg(t,e){Jt[t]=e}function ug(t){delete Jt[t]}function dg(){return{...Jt}}function Ml(t){let e=0;for(let s of Ko)s.provider===t&&(e+=Ol(s));return e}function Ll(t){let e=Ml(t),s=Jt[t];if(s===void 0)return{allowed:!0,spent:e,limit:null,remaining:null};let n=Math.max(0,s-e);return{allowed:e<s,spent:e,limit:s,remaining:n}}function Pl(){let t=Ci.join(process.cwd(),".nex","config.json");if(Xn.existsSync(t))try{let e=JSON.parse(Xn.readFileSync(t,"utf-8"));e.costLimits&&typeof e.costLimits=="object"&&(Jt={...e.costLimits})}catch{}}function fg(){let t=Ci.join(process.cwd(),".nex"),e=Ci.join(t,"config.json");Xn.existsSync(t)||Xn.mkdirSync(t,{recursive:!0}),sg(e,()=>{let s={};if(Xn.existsSync(e))try{s=JSON.parse(Xn.readFileSync(e,"utf-8"))}catch{s={}}s.costLimits=Jt,ng(e,JSON.stringify(s,null,2))})}function pg(){Jt={}}Pl();Il.exports={PRICING:Al,trackUsage:og,getSessionCosts:Nl,formatCosts:rg,formatCostHint:ag,resetCosts:cg,getPricing:Ai,setCostLimit:lg,removeCostLimit:ug,getCostLimits:dg,getProviderSpend:Ml,checkBudget:Ll,loadCostLimits:Pl,saveCostLimits:fg,resetCostLimits:pg,estimateTokens:ig}});var Xo=se((bk,jl)=>{function Oi(){return process.env.NEX_DEBUG==="true"||process.argv.includes("--debug")}var hg=Oi();function mg(...t){Oi()&&console.log(...t)}function gg(...t){Oi()&&console.warn(...t)}jl.exports={DEBUG:hg,debugLog:mg,warnLog:gg}});var Fl=se((_k,ql)=>{"use strict";var yg=new Set(["read_file","grep","glob","search_files","list_directory"]),$g=new Set(["write_file","edit_file","patch_file"]),wg=new Set(["bash"]),bg=new Set(["web_search","web_fetch","perplexity_search"]);function Dl(t,e){let s=0,n=0,o=0,r=0,i=0;for(let[a,c]of t)i+=c,yg.has(a)&&(s+=c),$g.has(a)&&(n+=c),wg.has(a)&&(o+=c),bg.has(a)&&(r+=c);return i===0?`Phase ${e}`:r/i>.5?"Research":s/i>.5?"Exploration":n/i>.3?"Implementation":o/i>.3&&n/i<.15?"Verification":`Phase ${e}`}var Ni=class{constructor(e){this._N=e,this._disabled=e<=0,this._phaseNum=0,this._stepsThisPhase=0,this._phaseCounts=new Map,this._phaseStart=Date.now()}record(e,s,n,o){if(this._disabled)return null;this._stepsThisPhase++;for(let i of s)this._phaseCounts.set(i,(this._phaseCounts.get(i)||0)+1);if(this._stepsThisPhase<this._N)return null;this._phaseNum++;let r={phaseNum:this._phaseNum,phaseName:Dl(this._phaseCounts,this._phaseNum),stepCount:this._stepsThisPhase,toolCounts:new Map(this._phaseCounts),elapsed:Date.now()-this._phaseStart,filesRead:new Set(n),filesModified:new Set(o)};return this._stepsThisPhase=0,this._phaseCounts=new Map,this._phaseStart=Date.now(),r}};ql.exports={MilestoneTracker:Ni,_phaseName:Dl}});var Ss=se((xk,Bl)=>{var vs=He(),_g={"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 xg(){return vs.getActiveModel()}function kg(t){return vs.setActiveModel(t)}function vg(){return vs.getModelNames()}function Sg(t){if(!t)return null;if(typeof t=="object")return t;try{return JSON.parse(t)}catch{}try{let n=t.replace(/,\s*([}\]])/g,"$1").replace(/'/g,'"');return JSON.parse(n)}catch{}let e=t.match(/\{[\s\S]*\}/);if(e)try{return JSON.parse(e[0])}catch{}try{let n=t.replace(/(\{|,)\s*([a-zA-Z_]\w*)\s*:/g,'$1"$2":');return JSON.parse(n)}catch{}let s=t.match(/```(?:json)?\s*([\s\S]*?)```/);if(s)try{return JSON.parse(s[1].trim())}catch{}return null}async function Eg(t,e){let{C:s}=Ue(),{Spinner:n}=Ue(),o=new n("Thinking...");o.start();let r=!0,i="";try{let a=await vs.callStream(t,e,{onToken:c=>{r&&(o.stop(),process.stdout.write(`${s.blue}`),r=!1),process.stdout.write(c),i+=c}});return r?o.stop():process.stdout.write(`${s.reset}
61
- `),a}catch(a){throw o.stop(),a}}async function Tg(t,e){return vs.callChat(t,e)}Bl.exports={MODELS:_g,getActiveModel:xg,setActiveModel:kg,getModelNames:vg,callOllamaStream:Eg,callOllama:Tg,parseToolArgs:Sg}});var Es=se((kk,Kl)=>{var Rg=require("readline"),{C:Mt}=Ue(),Pi=[/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/],Wl=[...Pi,/\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 Cg(t){for(let e of Wl)if(e.test(t))return e;return null}var Ul=[/\.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)/],Ag=/\b(?:rm|rmdir|unlink|truncate|shred|mv|cp)\b/,Mi=[/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 Hl(t){let e=t.match(/ssh\s+[^"]*"([^"]+)"/)?.[1]||t.match(/ssh\s+[^']*'([^']+)'/)?.[1];if(!e)return!1;let n=e.replace(/\bfor\s[\s\S]*?\bdone\b/g,r=>r.replace(/;/g,"\0")).replace(/\bwhile\s[\s\S]*?\bdone\b/g,r=>r.replace(/;/g,"\0")).split(/\s*(?:&&|;)\s*/).map(r=>r.replace(/\x00/g,";").trim()).filter(Boolean);if(n.length===0)return!1;let o=r=>{let i=r.replace(/^sudo\s+(?:-[ugCD]\s+\S+\s+|-[A-Za-z]+\s+)*/,"");if(/^\s*(?:echo|printf)\s/.test(i))return!0;if(/^\s*for\s/.test(r)||/^\s*while\s/.test(r)){let a=r.match(/\bdo\s+([\s\S]*?)\s*(?:done|$)/)?.[1];return a?a.split(/\s*;\s*/).map(l=>l.trim()).filter(Boolean).every(l=>o(l)):Mi.some(c=>c.test(r))}return/^\w+=\$?\(/.test(i)||/^\w+=["']/.test(i)||/^\w+=\S/.test(i)?!0:Mi.some(a=>a.test(i))};return n.every(o)}var Ii=[/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)/],Gl=[/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/],Yl=[...Ii,...Gl],ji=!1,pn=null,Li=null;function Og(t){ji=t}function Ng(t){Li=t}function Mg(){return ji}function Lg(t){pn=t}function Pg(t){for(let e of Pi)if(e.test(t))return e;return null}function Ig(t){if(/ssh\s/.test(t)&&Hl(t))return!1;for(let e of Yl)if(e.test(t))return!0;return!1}function jg(t){for(let e of Ii)if(e.test(t))return!0;return!1}function Dg(t){if(process.env.NEX_UNPROTECT==="1"||!Ag.test(t))return null;for(let e of Ul)if(e.test(t))return e;return null}function qg(t,e={}){if(ji)return Promise.resolve(!0);if(Li)return Li(t,e);if(!process.stdout.isTTY||!process.stdin.isTTY)return Fg(t,e);let s=e.toolName?["Yes","No","Always allow"]:["Yes","No"];return new Promise(n=>{let o=0;pn&&pn.pause();let r=global._nexRawWrite||(d=>process.stdout.write(d)),i=()=>{let d=process.stdout.rows||24;return Math.max(1,d-s.length-2)},a=()=>{let d=i(),f=`\x1B[${d};1H\x1B[2K${Mt.yellow}${t}${Mt.reset}`;for(let h=0;h<s.length;h++){let m=h===o,g=m?`${Mt.yellow}\u276F${Mt.reset}`:" ",b=m?`${Mt.yellow}${s[h]}${Mt.reset}`:s[h];f+=`\x1B[${d+1+h};1H\x1B[2K ${g} ${b}`}r(f)},c=d=>{process.stdin.setRawMode(!1),process.stdin.pause(),process.stdin.removeListener("data",u);let f=global._nexRawWrite||(g=>process.stdout.write(g)),h=i(),m="";for(let g=0;g<s.length+1;g++)m+=`\x1B[${h+g};1H\x1B[2K`;f(m),global._nexFooter&&global._nexFooter.drawFooter(),pn&&pn.resume(),n(d)},l=d=>{if(d===1){c(!1);return}d===2&&e.toolName&&Vo(e.toolName),c(!0)},u=d=>{if(d[0]===3){c(!1);return}let f=d.toString();if(f==="\r"||f===`
62
- `){l(o);return}if(f==="\x1B[A"){o=(o-1+s.length)%s.length,a();return}if(f==="\x1B[B"){o=(o+1)%s.length,a();return}let h=f.toLowerCase().trim();if(h==="y"){c(!0);return}if(h==="n"){c(!1);return}if(h==="a"&&e.toolName){Vo(e.toolName),c(!0);return}};a(),process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",u)})}function Fg(t,e){let s=e.toolName?"[Y/n/a] ":"[Y/n] ";return new Promise(n=>{let o=r=>{let i=r.trim().toLowerCase();i==="a"&&e.toolName?(Vo(e.toolName),n(!0)):n(i!=="n")};if(pn)pn.question(`${Mt.yellow}${t} ${s}${Mt.reset}`,o);else{let r=Rg.createInterface({input:process.stdin,output:process.stdout});r.question(`${Mt.yellow}${t} ${s}${Mt.reset}`,i=>{r.close(),o(i)})}})}var Vo=()=>{};function Bg(t){Vo=t}Kl.exports={FORBIDDEN_PATTERNS:Pi,SSH_FORBIDDEN_PATTERNS:Wl,BASH_PROTECTED_PATHS:Ul,SSH_SAFE_PATTERNS:Mi,isSSHReadOnly:Hl,DANGEROUS_BASH:Yl,CRITICAL_BASH:Ii,NOTABLE_BASH:Gl,isForbidden:Pg,isSSHForbidden:Cg,isDangerous:Ig,isCritical:jg,isBashPathForbidden:Dg,confirm:qg,setAutoConfirm:Og,getAutoConfirm:Mg,setConfirmHook:Ng,setReadlineInterface:Lg,setAllowAlwaysHandler:Bg}});var Vl=se((Sk,Xl)=>{var Jo=require("path"),{C:M}=Ue(),{T:Di,isDark:vk}=ks(),{confirm:Wg,getAutoConfirm:Ug}=Es(),zl=2e3;function Ts(t,e){let s=t.split(`
53
+ `)}var{Spinner:Lm,MultiProgress:Pm,TaskProgress:Im,ToolProgress:jm,setActiveTaskProgress:Dm,getActiveTaskProgress:qm,cleanupTerminal:Fm}=zn(),{formatToolCall:Bm,formatResult:Wm,getToolSpinnerText:Um,formatToolSummary:Hm,formatSectionHeader:Ym,formatMilestone:Gm,getThinkingVerb:Km,setActiveModelForSpinner:zm}=wl();_l.exports={C:Ai,banner:Mm,Spinner:Lm,MultiProgress:Pm,TaskProgress:Im,ToolProgress:jm,setActiveTaskProgress:Dm,getActiveTaskProgress:qm,cleanupTerminal:Fm,formatToolCall:Bm,formatResult:Wm,getToolSpinnerText:Um,formatToolSummary:Hm,formatSectionHeader:Ym,formatMilestone:Gm,getThinkingVerb:Km,setActiveModelForSpinner:zm}});var Xn=re((Nk,xl)=>{async function Xm(t,e){if(!t.response?.data)return t.message;let s=t.response.data;if(typeof s=="object"&&s!==null&&typeof s.pipe!="function")return e(s)||t.message;try{let n=await new Promise((r,i)=>{let a=[];s.on("data",c=>a.push(c)),s.on("end",()=>r(Buffer.concat(a).toString("utf8"))),s.on("error",i)}),o=JSON.parse(n);return e(o)||n||t.message}catch{return t.message}}var Oi=class t{constructor(e={}){if(new.target===t)throw new Error("BaseProvider is abstract \u2014 use a concrete provider");this.name=e.name||"unknown",this.baseUrl=e.baseUrl||"",this.models=e.models||{},this.defaultModel=e.defaultModel||null}isConfigured(){throw new Error(`${this.name}: isConfigured() not implemented`)}getApiKey(){return null}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}getModel(e){return this.models[e]||null}async chat(e,s,n={}){throw new Error(`${this.name}: chat() not implemented`)}async stream(e,s,n={}){throw new Error(`${this.name}: stream() not implemented`)}formatMessages(e){return{messages:e}}formatTools(e){return e}normalizeResponse(e){throw new Error(`${this.name}: normalizeResponse() not implemented`)}};xl.exports={BaseProvider:Oi,readStreamErrorBody:Xm}});var Zn=re((Mk,kl)=>{var Vn=class{buildRequestBody(e){throw new Error("buildRequestBody() not implemented")}getEndpoint(){throw new Error("getEndpoint() not implemented")}formatTools(e){return e}normalizeResponse(e){throw new Error("normalizeResponse() not implemented")}createStreamParser(e,s={}){throw new Error("createStreamParser() not implemented")}},Jn=class{constructor(e,s={}){this.onToken=e,this.callbacks=s,this.content="",this.buffer=""}feed(e){this.buffer+=e;let s=this.buffer.split(`
54
+ `);this.buffer=s.pop()||"";for(let n of s){let o=this.parseLine(n);if(o?.done)return o}return{done:!1}}flush(){return this.buffer.trim()&&(this.parseLine(this.buffer),this.buffer=""),this.getResult()}parseLine(e){throw new Error("parseLine() not implemented")}getResult(){throw new Error("getResult() not implemented")}},Fo=class extends Jn{constructor(e,s={}){super(e,s),this.toolCallsMap={}}parseLine(e){let s=e.trim();if(!s||!s.startsWith("data: "))return{done:!1};let n=s.slice(6);if(n==="[DONE]")return{done:!0,result:this.getResult()};let o;try{o=JSON.parse(n)}catch{return{done:!1}}let r=o.choices?.[0]?.delta;if(!r)return{done:!1};if(r.content&&(this.onToken(r.content),this.content+=r.content),r.tool_calls)for(let i of r.tool_calls){let a=i.index??0;this.toolCallsMap[a]||(this.toolCallsMap[a]={id:i.id||"",name:"",arguments:""}),i.id&&(this.toolCallsMap[a].id=i.id),i.function?.name&&(this.toolCallsMap[a].name+=i.function.name),i.function?.arguments&&(this.toolCallsMap[a].arguments+=i.function.arguments)}return{done:!1}}getResult(){return{content:this.content,tool_calls:Object.values(this.toolCallsMap).filter(e=>e.name).map(e=>({id:e.id||`call-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,function:{name:e.name,arguments:e.arguments}}))}}},Bo=class extends Vn{getEndpoint(){return"/chat/completions"}buildRequestBody({model:e,messages:s,tools:n,maxTokens:o,temperature:r,stream:i}){let a={model:e,messages:s,max_tokens:o,temperature:r};return i&&(a.stream=!0),n&&n.length>0&&(a.tools=n),a}normalizeResponse(e){let s=e.choices?.[0]?.message||{},n=(s.tool_calls||[]).map(o=>({id:o.id,function:{name:o.function.name,arguments:o.function.arguments}}));return{content:s.content||"",tool_calls:n}}createStreamParser(e,s={}){return new Fo(e,s)}},Wo=class extends Jn{constructor(e,s={}){super(e,s),this.toolUses=[],this.currentToolIndex=-1}parseLine(e){let s=e.trim();if(!s.startsWith("data: "))return{done:!1};let n=s.slice(6),o;try{o=JSON.parse(n)}catch{return{done:!1}}switch(o.type){case"content_block_start":{let r=o.content_block;r?.type==="tool_use"&&(this.currentToolIndex=this.toolUses.length,this.toolUses.push({id:r.id,name:r.name,inputJson:""}));break}case"content_block_delta":{let r=o.delta;r?.type==="text_delta"&&r.text&&(this.onToken(r.text),this.content+=r.text),r?.type==="input_json_delta"&&r.partial_json!==void 0&&this.currentToolIndex>=0&&(this.toolUses[this.currentToolIndex].inputJson+=r.partial_json);break}case"content_block_stop":this.currentToolIndex=-1;break;case"message_stop":return{done:!0,result:this.getResult()}}return{done:!1}}getResult(){return{content:this.content,tool_calls:this.toolUses.filter(e=>e.name).map(e=>{let s={};if(e.inputJson)try{s=JSON.parse(e.inputJson)}catch{s=e.inputJson}return{id:e.id||`anthropic-${Date.now()}`,function:{name:e.name,arguments:s}}})}}},Uo=class extends Vn{getEndpoint(){return"/messages"}buildRequestBody({model:e,messages:s,tools:n,maxTokens:o,temperature:r,stream:i,extra:a}){let c={model:e,messages:s,max_tokens:o,temperature:r};return i&&(c.stream=!0),a?.system&&(c.system=a.system),n&&n.length>0&&(c.tools=n),c}formatTools(e){return!e||e.length===0?[]:e.map(s=>({name:s.function.name,description:s.function.description||"",input_schema:s.function.parameters||{type:"object",properties:{}}}))}normalizeResponse(e){let s="",n=[];for(let o of e.content||[])o.type==="text"?s+=o.text:o.type==="tool_use"&&n.push({id:o.id,function:{name:o.name,arguments:o.input}});return{content:s,tool_calls:n}}createStreamParser(e,s={}){return new Wo(e,s)}},Ho=class extends Jn{constructor(e,s={}){super(e,s),this.toolCalls=[],this.onThinkingToken=s.onThinkingToken||(()=>{})}parseLine(e){if(!e.trim())return{done:!1};let s;try{s=JSON.parse(e)}catch{return{done:!1}}return s.message?.thinking&&this.onThinkingToken(s.message.thinking),s.message?.content&&(this.onToken(s.message.content),this.content+=s.message.content),s.message?.tool_calls&&(this.toolCalls=this.toolCalls.concat(s.message.tool_calls)),s.done?{done:!0,result:this.getResult()}:{done:!1}}getResult(){return{content:this.content,tool_calls:this.toolCalls.map((e,s)=>({id:e.id||`ollama-${Date.now()}-${s}`,function:{name:e.function?.name||e.name||"unknown",arguments:e.function?.arguments||e.arguments||{}}}))}}},Yo=class extends Vn{getEndpoint(){return"/api/chat"}buildRequestBody({model:e,messages:s,tools:n,maxTokens:o,temperature:r,stream:i,extra:a}){let c={model:e,messages:s,stream:i,options:{temperature:r,num_predict:o,repeat_penalty:a?.repeat_penalty??1.05}};return n&&n.length>0&&(c.tools=n),c}normalizeResponse(e){let s=e.message||{};return{content:s.content||"",tool_calls:(s.tool_calls||[]).map((n,o)=>({id:n.id||`ollama-${Date.now()}-${o}`,function:{name:n.function?.name||n.name||"unknown",arguments:n.function?.arguments||n.arguments||{}}}))}}createStreamParser(e,s={}){return new Ho(e,s)}},Vm=new Bo,Jm=new Uo,Zm=new Yo;kl.exports={WireProtocol:Vn,StreamParser:Jn,OpenAICompatibleProtocol:Bo,AnthropicProtocol:Uo,OllamaChatProtocol:Yo,OpenAIStreamParser:Fo,AnthropicStreamParser:Wo,OllamaStreamParser:Ho,openaiProtocol:Vm,anthropicProtocol:Jm,ollamaProtocol:Zm}});var El=re((Lk,Sl)=>{var Go=require("axios"),Qm=require("http"),eg=require("https"),{BaseProvider:tg,readStreamErrorBody:ng}=Xn(),{ollamaProtocol:dn}=Zn(),Ko=new Qm.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),zo=new eg.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),vl={"qwen3-coder:480b":{id:"qwen3-coder:480b",name:"Qwen3 Coder 480B",maxTokens:16384,contextWindow:131072},"qwen3-coder-next":{id:"qwen3-coder-next",name:"Qwen3 Coder Next",maxTokens:16384,contextWindow:262144},"devstral-2:123b":{id:"devstral-2:123b",name:"Devstral 2 123B",maxTokens:16384,contextWindow:131072},"devstral-small-2:24b":{id:"devstral-small-2:24b",name:"Devstral Small 2 24B",maxTokens:16384,contextWindow:131072},"minimax-m2.7:cloud":{id:"minimax-m2.7:cloud",name:"MiniMax M2.7 Cloud",maxTokens:16384,contextWindow:131072},"kimi-k2.5":{id:"kimi-k2.5",name:"Kimi K2.5",maxTokens:16384,contextWindow:256e3},"kimi-k2:1t":{id:"kimi-k2:1t",name:"Kimi K2 1T",maxTokens:16384,contextWindow:256e3},"kimi-k2-thinking":{id:"kimi-k2-thinking",name:"Kimi K2 Thinking",maxTokens:16384,contextWindow:256e3},"deepseek-v3.2":{id:"deepseek-v3.2",name:"DeepSeek V3.2",maxTokens:16384,contextWindow:131072},"deepseek-v3.1:671b":{id:"deepseek-v3.1:671b",name:"DeepSeek V3.1 671B",maxTokens:16384,contextWindow:131072},"cogito-2.1:671b":{id:"cogito-2.1:671b",name:"Cogito 2.1 671B",maxTokens:16384,contextWindow:131072},"qwen3.5:397b-cloud":{id:"qwen3.5:397b-cloud",name:"Qwen3.5 397B Cloud",maxTokens:16384,contextWindow:262144},"qwen3.5:397b":{id:"qwen3.5:397b",name:"Qwen3.5 397B",maxTokens:16384,contextWindow:262144},"qwen3.5:122b-a10b":{id:"qwen3.5:122b-a10b",name:"Qwen3.5 122B-A10B",maxTokens:16384,contextWindow:262144},"qwen3.5:35b-a3b":{id:"qwen3.5:35b-a3b",name:"Qwen3.5 35B-A3B",maxTokens:16384,contextWindow:262144},"qwen3.5:27b":{id:"qwen3.5:27b",name:"Qwen3.5 27B",maxTokens:16384,contextWindow:262144},"qwen3-next:80b":{id:"qwen3-next:80b",name:"Qwen3 Next 80B",maxTokens:16384,contextWindow:131072},"mistral-large-3:675b":{id:"mistral-large-3:675b",name:"Mistral Large 3 675B",maxTokens:16384,contextWindow:131072},"gpt-oss:120b":{id:"gpt-oss:120b",name:"GPT-OSS 120B",maxTokens:16384,contextWindow:131072},"minimax-m2.5":{id:"minimax-m2.5",name:"MiniMax M2.5",maxTokens:16384,contextWindow:131072},"glm-5:cloud":{id:"glm-5:cloud",name:"GLM 5 Cloud",maxTokens:16384,contextWindow:2e5},"glm-5":{id:"glm-5",name:"GLM 5",maxTokens:16384,contextWindow:2e5},"glm-4.6":{id:"glm-4.6",name:"GLM 4.6",maxTokens:16384,contextWindow:2e5},"glm-4.7":{id:"glm-4.7",name:"GLM 4.7",maxTokens:16384,contextWindow:128e3},"nemotron-3-super:cloud":{id:"nemotron-3-super:cloud",name:"Nemotron 3 Super Cloud",maxTokens:16384,contextWindow:262144},"qwen3.5:9b":{id:"qwen3.5:9b",name:"Qwen3.5 9B",maxTokens:8192,contextWindow:262144},"qwen3.5:4b":{id:"qwen3.5:4b",name:"Qwen3.5 4B",maxTokens:8192,contextWindow:262144},"qwen3.5:2b":{id:"qwen3.5:2b",name:"Qwen3.5 2B",maxTokens:8192,contextWindow:262144},"qwen3.5:0.8b":{id:"qwen3.5:0.8b",name:"Qwen3.5 0.8B",maxTokens:8192,contextWindow:262144},"gemma3:27b":{id:"gemma3:27b",name:"Gemma 3 27B",maxTokens:8192,contextWindow:131072},"gemma3:12b":{id:"gemma3:12b",name:"Gemma 3 12B",maxTokens:8192,contextWindow:131072},"gemma3:4b":{id:"gemma3:4b",name:"Gemma 3 4B",maxTokens:8192,contextWindow:131072},"ministral-3:14b":{id:"ministral-3:14b",name:"Ministral 3 14B",maxTokens:8192,contextWindow:131072},"ministral-3:8b":{id:"ministral-3:8b",name:"Ministral 3 8B",maxTokens:8192,contextWindow:131072},"gemini-3-flash-preview":{id:"gemini-3-flash-preview",name:"Gemini 3 Flash Preview",maxTokens:16384,contextWindow:131072}},Ni=class extends tg{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||vl,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){Go.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Ko,httpsAgent:zo}).then(e=>{let s=e.data?.models||[];for(let n of s){let o=(n.name||n.model||"").replace(/:latest$/,"");!o||this.models[o]||(this.models[o]={id:o,name:n.name||o,maxTokens:16384,contextWindow:131072})}}).catch(()=>{});return}try{let s=(await Go.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Ko,httpsAgent:zo})).data?.models||[];for(let n of s){let o=(n.name||n.model||"").replace(/:latest$/,"");!o||this.models[o]||(this.models[o]={id:o,name:n.name||o,maxTokens:16384,contextWindow:131072})}}catch{}}}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OLLAMA_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OLLAMA_API_KEY not set");return{Authorization:`Bearer ${e}`}}_formatMessages(e){return e.map(s=>{if(s.role==="user"&&Array.isArray(s.content)){let n=[],o=[];for(let i of s.content)i.type==="text"?n.push(i.text??""):i.type==="image"&&i.data&&o.push(i.data);let r={role:"user",content:n.join(`
55
+ `)};return o.length>0&&(r.images=o),r}return s})}async chat(e,s,n={}){await this.discoverModels();let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||16384,a=dn.buildRequestBody({model:o,messages:this._formatMessages(e),tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!1,extra:{repeat_penalty:n.repeat_penalty}}),c;try{c=await Go.post(`${this.baseUrl}${dn.getEndpoint()}`,a,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),httpAgent:Ko,httpsAgent:zo})}catch(l){if(l.name==="CanceledError"||l.name==="AbortError"||l.code==="ERR_CANCELED")throw l;let u=l.response?.status?` [HTTP ${l.response.status}]`:"",d=l.response?.data?.error||l.message;throw new Error(`API Error${u}: ${d}`)}return dn.normalizeResponse(c.data)}async stream(e,s,n={}){await this.discoverModels();let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||16384,a=n.onToken||(()=>{}),c=n.onThinkingToken||(()=>{}),l=dn.buildRequestBody({model:o,messages:this._formatMessages(e),tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!0,extra:{repeat_penalty:n.repeat_penalty}}),u;try{u=await Go.post(`${this.baseUrl}${dn.getEndpoint()}`,l,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal,httpAgent:Ko,httpsAgent:zo})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let h=f.response?.status?` [HTTP ${f.response.status}]`:"",g=await ng(f,m=>m?.error);throw new Error(`API Error${h}: ${g}`)}let d=dn.createStreamParser(a,{onThinkingToken:c});return new Promise((f,h)=>{n.signal&&n.signal.addEventListener("abort",()=>{u.data.destroy(),h(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",g=>{let{done:m,result:b}=d.feed(g.toString());m&&f(b)}),u.data.on("error",g=>{n.signal?.aborted||h(new Error(`Stream error: ${g.message}`))}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return dn.normalizeResponse(e)}};Sl.exports={OllamaProvider:Ni,OLLAMA_MODELS:vl}});var Al=re((Pk,Cl)=>{var Tl=require("axios"),{BaseProvider:sg,readStreamErrorBody:og}=Xn(),{openaiProtocol:fn}=Zn(),Rl={"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}},Mi=class extends sg{constructor(e={}){super({name:"openai",baseUrl:e.baseUrl||"https://api.openai.com/v1",models:e.models||Rl,defaultModel:e.defaultModel||"gpt-4o",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OPENAI_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OPENAI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let s=[];for(let n of e){if(this._messageFormatCache.has(n)){s.push(this._messageFormatCache.get(n));continue}let o=this._getMessageCacheKey(n);if(this._messageStringCache.has(o)){let i=this._messageStringCache.get(o);this._messageFormatCache.set(n,i),s.push(i);continue}let r=this._formatSingleMessage(n);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(o,r),this._messageFormatCache.set(n,r),s.push(r)}return{messages:s}}_getMessageCacheKey(e){let s=e.role||"",n=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${s}:${n.length}:${o}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||null,tool_calls:e.tool_calls.map(s=>({id:s.id||`call-${Date.now()}`,type:"function",function:{name:s.function.name,arguments:typeof s.function.arguments=="string"?s.function.arguments:JSON.stringify(s.function.arguments)}}))};if(e.role==="tool")return{role:"tool",content:typeof e.content=="string"?e.content:JSON.stringify(e.content),tool_call_id:e.tool_call_id};if(e.role==="user"&&Array.isArray(e.content)){let s=[];for(let n of e.content)if(n.type==="text")s.push({type:"text",text:n.text??""});else if(n.type==="image"&&n.data){let o=n.data.startsWith("data:")?n.data:`data:${n.media_type||"image/png"};base64,${n.data}`;s.push({type:"image_url",image_url:{url:o,detail:"auto"}})}return{role:"user",content:s}}return{role:e.role,content:e.content}}async chat(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||16384,{messages:a}=this.formatMessages(e),c=fn.buildRequestBody({model:o,messages:a,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!1}),l;try{l=await Tl.post(`${this.baseUrl}${fn.getEndpoint()}`,c,{timeout:n.timeout||this.timeout,headers:this._getHeaders()})}catch(u){if(u.name==="CanceledError"||u.name==="AbortError"||u.code==="ERR_CANCELED")throw u;let d=u.response?.status?` [HTTP ${u.response.status}]`:"",f=u.response?.data?.error?.message||u.response?.data?.error||u.message;throw new Error(`API Error${d}: ${f}`)}return fn.normalizeResponse(l.data)}async stream(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||16384,a=n.onToken||(()=>{}),{messages:c}=this.formatMessages(e),l=fn.buildRequestBody({model:o,messages:c,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!0}),u;try{u=await Tl.post(`${this.baseUrl}${fn.getEndpoint()}`,l,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let h=f.response?.status?` [HTTP ${f.response.status}]`:"",g=await og(f,m=>m?.error?.message||m?.error);throw new Error(`API Error${h}: ${g}`)}let d=fn.createStreamParser(a);return new Promise((f,h)=>{n.signal&&n.signal.addEventListener("abort",()=>{u.data.destroy(),h(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",g=>{let{done:m,result:b}=d.feed(g.toString());m&&f(b)}),u.data.on("error",g=>{n.signal?.aborted||h(new Error(`Stream error: ${g.message}`))}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return fn.normalizeResponse(e)}};Cl.exports={OpenAIProvider:Mi,OPENAI_MODELS:Rl}});var Ll=re((Ik,Ml)=>{var Ol=require("axios"),{BaseProvider:rg,readStreamErrorBody:ig}=Xn(),{anthropicProtocol:Zt}=Zn(),Nl={"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}},ag="2023-06-01",Li=class extends rg{constructor(e={}){super({name:"anthropic",baseUrl:e.baseUrl||"https://api.anthropic.com/v1",models:e.models||Nl,defaultModel:e.defaultModel||"claude-sonnet",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this.apiVersion=e.apiVersion||ag}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.ANTHROPIC_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("ANTHROPIC_API_KEY not set");return{"x-api-key":e,"anthropic-version":this.apiVersion,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let s="",n=[];for(let o of e){if(o.role==="system"){s+=(s?`
56
+
57
+ `:"")+o.content;continue}if(o.role!=="system"&&o.role!=="tool"&&this._messageFormatCache.has(o)){n.push(this._messageFormatCache.get(o));continue}let r=this._formatSingleMessage(o,n);if(r){if(o.role!=="system"&&o.role!=="tool"&&this._messageStringCache.size<this._maxCacheSize){let i=this._getMessageCacheKey(o);this._messageStringCache.set(i,r),this._messageFormatCache.set(o,r)}n.push(r)}}for(let o=n.length-1;o>0;o--)n[o].role==="user"&&n[o-1].role==="user"&&n.splice(o,0,{role:"assistant",content:[{type:"text",text:"[continuing]"}]});return{messages:n,system:s}}_getMessageCacheKey(e){let s=e.role||"",n=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${s}:${n.length}:${o}`}_formatSingleMessage(e,s=[]){if(e.role==="assistant"){let n=[];if(e.content&&n.push({type:"text",text:e.content}),e.tool_calls)for(let o of e.tool_calls)n.push({type:"tool_use",id:o.id||`toolu-${Date.now()}`,name:o.function.name,input:typeof o.function.arguments=="string"?JSON.parse(o.function.arguments||"{}"):o.function.arguments||{}});return{role:"assistant",content:n.length>0?n:[{type:"text",text:""}]}}if(e.role==="tool"){let n=s[s.length-1],o={type:"tool_result",tool_use_id:e.tool_call_id,content:typeof e.content=="string"?e.content:JSON.stringify(e.content)};return n&&n.role==="user"&&Array.isArray(n.content)&&n.content[0]?.type==="tool_result"?(n.content.push(o),null):{role:"user",content:[o]}}if(Array.isArray(e.content)){let n=[];for(let o of e.content)o.type==="text"?n.push({type:"text",text:o.text??""}):o.type==="image"&&o.data&&n.push({type:"image",source:{type:"base64",media_type:o.media_type||"image/png",data:o.data}});return{role:"user",content:n}}return{role:"user",content:e.content}}formatTools(e){return Zt.formatTools(e)}_resolveModelId(e){return this.getModel(e)?.id||e}async chat(e,s,n={}){let o=n.model||this.defaultModel,r=this._resolveModelId(o),i=this.getModel(o),a=n.maxTokens||i?.maxTokens||8192,{messages:c,system:l}=this.formatMessages(e),u=this.formatTools(s),d=Zt.buildRequestBody({model:r,messages:c,tools:u,maxTokens:a,temperature:n.temperature??this.temperature,stream:!1,extra:{system:l}}),f;try{f=await Ol.post(`${this.baseUrl}${Zt.getEndpoint()}`,d,{timeout:n.timeout||this.timeout,headers:this._getHeaders()})}catch(h){if(h.name==="CanceledError"||h.name==="AbortError"||h.code==="ERR_CANCELED")throw h;let g=h.response?.status?` [HTTP ${h.response.status}]`:"",m=h.response?.data?.error?.message||h.response?.data?.error||h.message;throw new Error(`API Error${g}: ${m}`)}return Zt.normalizeResponse(f.data)}async stream(e,s,n={}){let o=n.model||this.defaultModel,r=this._resolveModelId(o),i=this.getModel(o),a=n.maxTokens||i?.maxTokens||8192,c=n.onToken||(()=>{}),{messages:l,system:u}=this.formatMessages(e),d=this.formatTools(s),f=Zt.buildRequestBody({model:r,messages:l,tools:d,maxTokens:a,temperature:n.temperature??this.temperature,stream:!0,extra:{system:u}}),h;try{h=await Ol.post(`${this.baseUrl}${Zt.getEndpoint()}`,f,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(m){if(m.name==="CanceledError"||m.name==="AbortError"||m.code==="ERR_CANCELED")throw m;let b=m.response?.status?` [HTTP ${m.response.status}]`:"",x=await ig(m,j=>j?.error?.message||j?.error);throw new Error(`API Error${b}: ${x}`)}let g=Zt.createStreamParser(c);return new Promise((m,b)=>{n.signal&&n.signal.addEventListener("abort",()=>{h.data.destroy(),b(new DOMException("The operation was aborted","AbortError"))},{once:!0}),h.data.on("data",x=>{let{done:j,result:G}=g.feed(x.toString());j&&m(G)}),h.data.on("error",x=>{n.signal?.aborted||b(new Error(`Stream error: ${x.message}`))}),h.data.on("end",()=>{m(g.flush())})})}normalizeResponse(e){return Zt.normalizeResponse(e)}};Ml.exports={AnthropicProvider:Li,ANTHROPIC_MODELS:Nl}});var Dl=re((jk,jl)=>{var Pl=require("axios"),{BaseProvider:cg,readStreamErrorBody:lg}=Xn(),{openaiProtocol:pn}=Zn(),Il={"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}},Pi=class extends cg{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||Il,defaultModel:e.defaultModel||"gemini-2.5-flash",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("GEMINI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let s=[];for(let n of e){if(this._messageFormatCache.has(n)){s.push(this._messageFormatCache.get(n));continue}let o=this._getMessageCacheKey(n);if(this._messageStringCache.has(o)){let i=this._messageStringCache.get(o);this._messageFormatCache.set(n,i),s.push(i);continue}let r=this._formatSingleMessage(n);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(o,r),this._messageFormatCache.set(n,r),s.push(r)}return{messages:s}}_getMessageCacheKey(e){let s=e.role||"",n=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${s}:${n.length}:${o}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||"",tool_calls:e.tool_calls.map(s=>({id:s.id||`call-${Date.now()}`,type:"function",function:{name:s.function.name,arguments:typeof s.function.arguments=="string"?s.function.arguments:JSON.stringify(s.function.arguments)}}))};if(e.role==="tool")return{role:"tool",content:typeof e.content=="string"?e.content:JSON.stringify(e.content),tool_call_id:e.tool_call_id};if(e.role==="user"&&Array.isArray(e.content)){let s=[];for(let n of e.content)if(n.type==="text")s.push({type:"text",text:n.text??""});else if(n.type==="image"&&n.data){let o=n.data.startsWith("data:")?n.data:`data:${n.media_type||"image/png"};base64,${n.data}`;s.push({type:"image_url",image_url:{url:o,detail:"auto"}})}return{role:"user",content:s}}return{role:e.role,content:e.content}}async chat(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||8192,{messages:a}=this.formatMessages(e),c=pn.buildRequestBody({model:o,messages:a,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!1}),l;try{l=await Pl.post(`${this.baseUrl}${pn.getEndpoint()}`,c,{timeout:n.timeout||this.timeout,headers:this._getHeaders()})}catch(u){if(u.name==="CanceledError"||u.name==="AbortError"||u.code==="ERR_CANCELED")throw u;let d=u.response?.status?` [HTTP ${u.response.status}]`:"",f=u.response?.data?.error?.message||u.response?.data?.error||u.message;throw new Error(`API Error${d}: ${f}`)}return pn.normalizeResponse(l.data)}async stream(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||8192,a=n.onToken||(()=>{}),{messages:c}=this.formatMessages(e),l=pn.buildRequestBody({model:o,messages:c,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!0}),u;try{u=await Pl.post(`${this.baseUrl}${pn.getEndpoint()}`,l,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let h=f.response?.status?` [HTTP ${f.response.status}]`:"",g=await lg(f,m=>m?.error?.message||m?.error);throw new Error(`API Error${h}: ${g}`)}let d=pn.createStreamParser(a);return new Promise((f,h)=>{n.signal&&n.signal.addEventListener("abort",()=>{u.data.destroy(),h(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",g=>{let{done:m,result:b}=d.feed(g.toString());m&&f(b)}),u.data.on("error",g=>{n.signal?.aborted||h(new Error(`Stream error: ${g.message}`))}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return pn.normalizeResponse(e)}};jl.exports={GeminiProvider:Pi,GEMINI_MODELS:Il}});var Bl=re((Dk,Fl)=>{var Xo=require("axios"),{BaseProvider:ug,readStreamErrorBody:dg}=Xn(),{ollamaProtocol:hn}=Zn(),ql="http://localhost:11434",Ii=class extends ug{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||ql,models:e.models||{},defaultModel:e.defaultModel||null,...e}),this.timeout=e.timeout||3e5,this.temperature=e.temperature??.2,this._modelsLoaded=!1}isConfigured(){return!0}async loadModels(){if(this._modelsLoaded)return this.models;try{let s=(await Xo.get(`${this.baseUrl}/api/tags`,{timeout:5e3})).data?.models||[];this.models={};for(let n of s){let o=n.name||n.model;if(!o)continue;let r=o.replace(/:latest$/,""),i=32768;try{let a=await Xo.post(`${this.baseUrl}/api/show`,{name:o},{timeout:5e3}),c=a.data?.model_info||a.data?.details||{};i=c["general.context_length"]||c["llama.context_length"]||this._parseContextFromModelfile(a.data?.modelfile)||32768}catch{}this.models[r]={id:r,name:n.name,maxTokens:Math.min(8192,Math.floor(i*.1)),contextWindow:i}}!this.defaultModel&&Object.keys(this.models).length>0&&(this.defaultModel=Object.keys(this.models)[0]),this._modelsLoaded=!0}catch{this.models={},this._modelsLoaded=!1}return this.models}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}_formatMessages(e){return e.map(s=>{if(s.role==="user"&&Array.isArray(s.content)){let n=[],o=[];for(let i of s.content)i.type==="text"?n.push(i.text??""):i.type==="image"&&i.data&&o.push(i.data);let r={role:"user",content:n.join(`
58
+ `)};return o.length>0&&(r.images=o),r}return s})}async chat(e,s,n={}){this._modelsLoaded||await this.loadModels();let o=n.model||this.defaultModel;if(!o)throw new Error("No local model available. Is Ollama running?");let r=hn.buildRequestBody({model:o,messages:this._formatMessages(e),tools:s,maxTokens:n.maxTokens||8192,temperature:n.temperature??this.temperature,stream:!1}),i;try{i=await Xo.post(`${this.baseUrl}${hn.getEndpoint()}`,r,{timeout:n.timeout||this.timeout})}catch(a){if(a.name==="CanceledError"||a.name==="AbortError"||a.code==="ERR_CANCELED")throw a;let c=a.response?.status?` [HTTP ${a.response.status}]`:"",l=a.response?.data?.error||a.message;throw new Error(`API Error${c}: ${l}`)}return hn.normalizeResponse(i.data)}async stream(e,s,n={}){this._modelsLoaded||await this.loadModels();let o=n.model||this.defaultModel;if(!o)throw new Error("No local model available. Is Ollama running?");let r=n.onToken||(()=>{}),i=hn.buildRequestBody({model:o,messages:this._formatMessages(e),tools:s,maxTokens:n.maxTokens||8192,temperature:n.temperature??this.temperature,stream:!0}),a;try{a=await Xo.post(`${this.baseUrl}${hn.getEndpoint()}`,i,{timeout:n.timeout||this.timeout,responseType:"stream",signal:n.signal})}catch(l){if(l.name==="CanceledError"||l.name==="AbortError"||l.code==="ERR_CANCELED")throw l;let u=l.response?.status?` [HTTP ${l.response.status}]`:"",d=await dg(l,f=>f?.error);throw new Error(`API Error${u}: ${d}`)}let c=hn.createStreamParser(r);return new Promise((l,u)=>{n.signal&&n.signal.addEventListener("abort",()=>{a.data.destroy(),u(new DOMException("The operation was aborted","AbortError"))},{once:!0}),a.data.on("data",d=>{let{done:f,result:h}=c.feed(d.toString());f&&l(h)}),a.data.on("error",d=>{n.signal?.aborted||u(new Error(`Stream error: ${d.message}`))}),a.data.on("end",()=>{l(c.flush())})})}normalizeResponse(e){return hn.normalizeResponse(e)}_parseContextFromModelfile(e){if(!e)return null;let s=e.match(/PARAMETER\s+num_ctx\s+(\d+)/i);return s?parseInt(s[1],10):null}};Fl.exports={LocalProvider:Ii,DEFAULT_LOCAL_URL:ql}});var mn=re((qk,Ul)=>{"use strict";var dt=require("fs"),Wl=require("path");function fg(t){if(!t||isNaN(t))return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function pg(t){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}catch{let e=Date.now()+t;for(;Date.now()<e;);}}function hg(t,e){let s=Wl.dirname(t),n=Wl.join(s,`.nex-tmp.${process.pid}.${Date.now()}`);try{dt.existsSync(s)||dt.mkdirSync(s,{recursive:!0}),dt.writeFileSync(n,e,"utf-8"),dt.renameSync(n,t)}catch(o){try{dt.unlinkSync(n)}catch{}throw o}}function mg(t,e,{timeout:s=5e3,retryMs:n=50}={}){let o=t+".lock",r=Date.now()+s;for(;;){let i=-1;try{i=dt.openSync(o,"wx"),dt.writeSync(i,Buffer.from(String(process.pid))),dt.closeSync(i),i=-1;try{return e()}finally{try{dt.unlinkSync(o)}catch{}}}catch(a){if(i!==-1)try{dt.closeSync(i)}catch{}if(a.code!=="EEXIST")throw a;try{let c=dt.readFileSync(o,"utf-8").trim(),l=parseInt(c,10);if(!fg(l)){try{dt.unlinkSync(o)}catch{}continue}}catch(c){if(c.code&&c.code!=="ENOENT")throw c;continue}if(Date.now()>=r){try{dt.unlinkSync(o)}catch{}return e()}pg(n)}}}Ul.exports={atomicWrite:hg,withFileLockSync:mg}});var Jo=re((Fk,Vl)=>{var Qn=require("fs"),ji=require("path"),{atomicWrite:gg,withFileLockSync:yg}=mn(),Hl={openai:{"gpt-4o":{input:2.5,output:10},"gpt-4o-mini":{input:.15,output:.6},"gpt-4.1":{input:2,output:8},"gpt-4.1-mini":{input:.4,output:1.6},"gpt-4.1-nano":{input:.1,output:.4},o1:{input:15,output:60},o3:{input:10,output:40},"o3-mini":{input:1.1,output:4.4},"o4-mini":{input:1.1,output:4.4}},anthropic:{"claude-sonnet":{input:3,output:15},"claude-opus":{input:5,output:25},"claude-haiku":{input:.8,output:4},"claude-sonnet-4-5":{input:3,output:15},"claude-sonnet-4":{input:3,output:15}},gemini:{"gemini-2.5-pro":{input:1.25,output:10},"gemini-2.5-flash":{input:.15,output:.6},"gemini-2.0-flash":{input:.1,output:.4},"gemini-2.0-flash-lite":{input:.075,output:.3}},ollama:{"qwen3-coder:480b":{input:0,output:0},"qwen3-coder-next":{input:0,output:0},"devstral-2:123b":{input:0,output:0},"devstral-small-2:24b":{input:0,output:0},"kimi-k2.5":{input:0,output:0},"kimi-k2:1t":{input:0,output:0},"deepseek-v3.2":{input:0,output:0},"minimax-m2.5":{input:0,output:0},"glm-5":{input:0,output:0},"glm-4.7":{input:0,output:0},"gpt-oss:120b":{input:0,output:0}},local:{}},Vo=[],Qt={};function $g(t,e,s,n){if(Vo.push({provider:t,model:e,input:s,output:n}),Qt[t]!==void 0){let o=zl(t);o.allowed||process.stderr.write(`\x1B[33m\u26A0 Budget limit reached for ${t}: $${o.spent.toFixed(2)} / $${o.limit.toFixed(2)}\x1B[0m
59
+ `)}}function Di(t,e){let s=Hl[t];return s?s[e]||{input:0,output:0}:{input:0,output:0}}function Yl(t){let e=Di(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function Gl(){let t={};for(let r of Vo){let i=`${r.provider}:${r.model}`;t[i]||(t[i]={provider:r.provider,model:r.model,input:0,output:0}),t[i].input+=r.input,t[i].output+=r.output}let e=Object.values(t).map(r=>({...r,cost:Yl(r)})),s=e.reduce((r,i)=>r+i.cost,0),n=e.reduce((r,i)=>r+i.input,0),o=e.reduce((r,i)=>r+i.output,0);return{totalCost:s,totalInput:n,totalOutput:o,breakdown:e}}function wg(){let{totalCost:t,totalInput:e,totalOutput:s,breakdown:n}=Gl();if(n.length===0)return"No token usage recorded this session.";let o=[];o.push("Session Token Usage:"),o.push("");for(let r of n){let i=r.cost>0?`$${r.cost.toFixed(4)}`:"free";o.push(` ${r.provider}:${r.model}`),o.push(` Input: ${r.input.toLocaleString()} tokens`),o.push(` Output: ${r.output.toLocaleString()} tokens`),o.push(` Cost: ${i}`)}return o.push(""),o.push(` Total: ${e.toLocaleString()} in + ${s.toLocaleString()} out = $${t.toFixed(4)}`),o.join(`
60
+ `)}function bg(t){return!t||typeof t!="string"?0:Math.ceil(t.length/4)}function _g(t,e,s,n){let o=Di(t,e),r=(s*o.input+n*o.output)/1e6;return r<=0?"":`[~$${r.toFixed(4)}]`}function xg(){Vo=[]}function kg(t,e){Qt[t]=e}function vg(t){delete Qt[t]}function Sg(){return{...Qt}}function Kl(t){let e=0;for(let s of Vo)s.provider===t&&(e+=Yl(s));return e}function zl(t){let e=Kl(t),s=Qt[t];if(s===void 0)return{allowed:!0,spent:e,limit:null,remaining:null};let n=Math.max(0,s-e);return{allowed:e<s,spent:e,limit:s,remaining:n}}function Xl(){let t=ji.join(process.cwd(),".nex","config.json");if(Qn.existsSync(t))try{let e=JSON.parse(Qn.readFileSync(t,"utf-8"));e.costLimits&&typeof e.costLimits=="object"&&(Qt={...e.costLimits})}catch{}}function Eg(){let t=ji.join(process.cwd(),".nex"),e=ji.join(t,"config.json");Qn.existsSync(t)||Qn.mkdirSync(t,{recursive:!0}),yg(e,()=>{let s={};if(Qn.existsSync(e))try{s=JSON.parse(Qn.readFileSync(e,"utf-8"))}catch{s={}}s.costLimits=Qt,gg(e,JSON.stringify(s,null,2))})}function Tg(){Qt={}}Xl();Vl.exports={PRICING:Hl,trackUsage:$g,getSessionCosts:Gl,formatCosts:wg,formatCostHint:_g,resetCosts:xg,getPricing:Di,setCostLimit:kg,removeCostLimit:vg,getCostLimits:Sg,getProviderSpend:Kl,checkBudget:zl,loadCostLimits:Xl,saveCostLimits:Eg,resetCostLimits:Tg,estimateTokens:bg}});var Zo=re((Bk,Jl)=>{function qi(){return process.env.NEX_DEBUG==="true"||process.argv.includes("--debug")}var Rg=qi();function Cg(...t){qi()&&console.log(...t)}function Ag(...t){qi()&&console.warn(...t)}Jl.exports={DEBUG:Rg,debugLog:Cg,warnLog:Ag}});var eu=re((Wk,Ql)=>{"use strict";var Og=new Set(["read_file","grep","glob","search_files","list_directory"]),Ng=new Set(["write_file","edit_file","patch_file"]),Mg=new Set(["bash"]),Lg=new Set(["web_search","web_fetch","perplexity_search"]);function Zl(t,e){let s=0,n=0,o=0,r=0,i=0;for(let[a,c]of t)i+=c,Og.has(a)&&(s+=c),Ng.has(a)&&(n+=c),Mg.has(a)&&(o+=c),Lg.has(a)&&(r+=c);return i===0?`Phase ${e}`:r/i>.5?"Research":s/i>.5?"Exploration":n/i>.3?"Implementation":o/i>.3&&n/i<.15?"Verification":`Phase ${e}`}var Fi=class{constructor(e){this._N=e,this._disabled=e<=0,this._phaseNum=0,this._stepsThisPhase=0,this._phaseCounts=new Map,this._phaseStart=Date.now()}record(e,s,n,o){if(this._disabled)return null;this._stepsThisPhase++;for(let i of s)this._phaseCounts.set(i,(this._phaseCounts.get(i)||0)+1);if(this._stepsThisPhase<this._N)return null;this._phaseNum++;let r={phaseNum:this._phaseNum,phaseName:Zl(this._phaseCounts,this._phaseNum),stepCount:this._stepsThisPhase,toolCounts:new Map(this._phaseCounts),elapsed:Date.now()-this._phaseStart,filesRead:new Set(n),filesModified:new Set(o)};return this._stepsThisPhase=0,this._phaseCounts=new Map,this._phaseStart=Date.now(),r}};Ql.exports={MilestoneTracker:Fi,_phaseName:Zl}});var Rs=re((Uk,tu)=>{var Ts=Ge(),Pg={"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 Ig(){return Ts.getActiveModel()}function jg(t){return Ts.setActiveModel(t)}function Dg(){return Ts.getModelNames()}function qg(t){if(!t)return null;if(typeof t=="object")return t;try{return JSON.parse(t)}catch{}try{let n=t.replace(/,\s*([}\]])/g,"$1").replace(/'/g,'"');return JSON.parse(n)}catch{}let e=t.match(/\{[\s\S]*\}/);if(e)try{return JSON.parse(e[0])}catch{}try{let n=t.replace(/(\{|,)\s*([a-zA-Z_]\w*)\s*:/g,'$1"$2":');return JSON.parse(n)}catch{}let s=t.match(/```(?:json)?\s*([\s\S]*?)```/);if(s)try{return JSON.parse(s[1].trim())}catch{}return null}async function Fg(t,e){let{C:s}=He(),{Spinner:n}=He(),o=new n("Thinking...");o.start();let r=!0,i="";try{let a=await Ts.callStream(t,e,{onToken:c=>{r&&(o.stop(),process.stdout.write(`${s.blue}`),r=!1),process.stdout.write(c),i+=c}});return r?o.stop():process.stdout.write(`${s.reset}
61
+ `),a}catch(a){throw o.stop(),a}}async function Bg(t,e){return Ts.callChat(t,e)}tu.exports={MODELS:Pg,getActiveModel:Ig,setActiveModel:jg,getModelNames:Dg,callOllamaStream:Fg,callOllama:Bg,parseToolArgs:qg}});var Cs=re((Hk,au)=>{var Wg=require("readline"),{C:Lt}=He(),Ui=[/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/],nu=[...Ui,/\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 Ug(t){for(let e of nu)if(e.test(t))return e;return null}var su=[/\.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)/],Hg=/\b(?:rm|rmdir|unlink|truncate|shred|mv|cp)\b/,Bi=[/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 ou(t){let e=t.match(/ssh\s+[^"]*"([^"]+)"/)?.[1]||t.match(/ssh\s+[^']*'([^']+)'/)?.[1];if(!e)return!1;let n=e.replace(/\bfor\s[\s\S]*?\bdone\b/g,r=>r.replace(/;/g,"\0")).replace(/\bwhile\s[\s\S]*?\bdone\b/g,r=>r.replace(/;/g,"\0")).split(/\s*(?:&&|;)\s*/).map(r=>r.replace(/\x00/g,";").trim()).filter(Boolean);if(n.length===0)return!1;let o=r=>{let i=r.replace(/^sudo\s+(?:-[ugCD]\s+\S+\s+|-[A-Za-z]+\s+)*/,"");if(/^\s*(?:echo|printf)\s/.test(i))return!0;if(/^\s*for\s/.test(r)||/^\s*while\s/.test(r)){let a=r.match(/\bdo\s+([\s\S]*?)\s*(?:done|$)/)?.[1];return a?a.split(/\s*;\s*/).map(l=>l.trim()).filter(Boolean).every(l=>o(l)):Bi.some(c=>c.test(r))}return/^\w+=\$?\(/.test(i)||/^\w+=["']/.test(i)||/^\w+=\S/.test(i)?!0:Bi.some(a=>a.test(i))};return n.every(o)}var Hi=[/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)/],ru=[/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/],iu=[...Hi,...ru],Yi=!1,gn=null,Wi=null;function Yg(t){Yi=t}function Gg(t){Wi=t}function Kg(){return Yi}function zg(t){gn=t}function Xg(t){for(let e of Ui)if(e.test(t))return e;return null}function Vg(t){if(/ssh\s/.test(t)&&ou(t))return!1;for(let e of iu)if(e.test(t))return!0;return!1}function Jg(t){for(let e of Hi)if(e.test(t))return!0;return!1}function Zg(t){if(process.env.NEX_UNPROTECT==="1"||!Hg.test(t))return null;for(let e of su)if(e.test(t))return e;return null}function Qg(t,e={}){if(Yi)return Promise.resolve(!0);if(Wi)return Wi(t,e);if(!process.stdout.isTTY||!process.stdin.isTTY)return ey(t,e);let s=e.toolName?["Yes","No","Always allow"]:["Yes","No"];return new Promise(n=>{let o=0;gn&&gn.pause();let r=global._nexRawWrite||(d=>process.stdout.write(d)),i=()=>{let d=process.stdout.rows||24;return Math.max(1,d-s.length-2)},a=()=>{let d=i();global._nexRawWrite&&d>1&&global._nexRawWrite(`\x1B[1;${d-1}r`);let f=`\x1B[${d};1H\x1B[2K${Lt.yellow}${t}${Lt.reset}`;for(let h=0;h<s.length;h++){let g=h===o,m=g?`${Lt.yellow}\u276F${Lt.reset}`:" ",b=g?`${Lt.yellow}${s[h]}${Lt.reset}`:s[h];f+=`\x1B[${d+1+h};1H\x1B[2K ${m} ${b}`}r(f)},c=d=>{process.stdin.setRawMode(!1),process.stdin.pause(),process.stdin.removeListener("data",u);let f=global._nexRawWrite||(m=>process.stdout.write(m)),h=i(),g="";for(let m=0;m<s.length+1;m++)g+=`\x1B[${h+m};1H\x1B[2K`;f(g),global._nexRawWrite&&global._nexFooter&&global._nexRawWrite(`\x1B[1;${global._nexFooter._scrollEnd}r`),global._nexFooter&&global._nexFooter.drawFooter(),gn&&gn.resume(),n(d)},l=d=>{if(d===1){c(!1);return}d===2&&e.toolName&&Qo(e.toolName),c(!0)},u=d=>{if(d[0]===3){c(!1);return}let f=d.toString();if(f==="\r"||f===`
62
+ `){l(o);return}if(f==="\x1B[A"){o=(o-1+s.length)%s.length,a();return}if(f==="\x1B[B"){o=(o+1)%s.length,a();return}let h=f.toLowerCase().trim();if(h==="y"){c(!0);return}if(h==="n"){c(!1);return}if(h==="a"&&e.toolName){Qo(e.toolName),c(!0);return}};a(),process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",u)})}function ey(t,e){let s=e.toolName?"[Y/n/a] ":"[Y/n] ";return new Promise(n=>{let o=r=>{let i=r.trim().toLowerCase();i==="a"&&e.toolName?(Qo(e.toolName),n(!0)):n(i!=="n")};if(gn)gn.question(`${Lt.yellow}${t} ${s}${Lt.reset}`,o);else{let r=Wg.createInterface({input:process.stdin,output:process.stdout});r.question(`${Lt.yellow}${t} ${s}${Lt.reset}`,i=>{r.close(),o(i)})}})}var Qo=()=>{};function ty(t){Qo=t}au.exports={FORBIDDEN_PATTERNS:Ui,SSH_FORBIDDEN_PATTERNS:nu,BASH_PROTECTED_PATHS:su,SSH_SAFE_PATTERNS:Bi,isSSHReadOnly:ou,DANGEROUS_BASH:iu,CRITICAL_BASH:Hi,NOTABLE_BASH:ru,isForbidden:Xg,isSSHForbidden:Ug,isDangerous:Vg,isCritical:Jg,isBashPathForbidden:Zg,confirm:Qg,setAutoConfirm:Yg,getAutoConfirm:Kg,setConfirmHook:Gg,setReadlineInterface:zg,setAllowAlwaysHandler:ty}});var uu=re((Gk,lu)=>{var er=require("path"),{C:M}=He(),{T:Gi,isDark:Yk}=Es(),{confirm:ny,getAutoConfirm:sy}=Cs(),cu=2e3;function As(t,e){let s=t.split(`
63
63
  `),n=e.split(`
64
- `),o=[],r=s.length,i=n.length;if(r>zl||i>zl){for(let d of s)o.push({type:"remove",line:d});for(let d of n)o.push({type:"add",line:d});return o}let a=Array.from({length:r+1},()=>new Array(i+1).fill(0));for(let d=1;d<=r;d++)for(let f=1;f<=i;f++)s[d-1]===n[f-1]?a[d][f]=a[d-1][f-1]+1:a[d][f]=Math.max(a[d-1][f],a[d][f-1]);let c=r,l=i,u=[];for(;c>0||l>0;)c>0&&l>0&&s[c-1]===n[l-1]?(u.unshift({type:"same",line:s[c-1]}),c--,l--):l>0&&(c===0||a[c][l-1]>=a[c-1][l])?(u.unshift({type:"add",line:n[l-1]}),l--):(u.unshift({type:"remove",line:s[c-1]}),c--);return u}function Hg(t,e,s,n=3){console.log(`
65
- ${M.bold}${M.cyan} Diff: ${t}${M.reset}`);let o=Ts(e,s),r=[];if(o.forEach((c,l)=>{c.type!=="same"&&r.push(l)}),r.length===0){console.log(`${M.gray} (no changes)${M.reset}`);return}let i=Math.max(0,r[0]-n),a=Math.min(o.length,r[r.length-1]+n+1);i>0&&console.log(`${M.gray} ...${M.reset}`);for(let c=i;c<a;c++){let l=o[c];switch(l.type){case"remove":console.log(`${M.red} - ${l.line}${M.reset}`);break;case"add":console.log(`${M.green} + ${l.line}${M.reset}`);break;default:console.log(`${M.gray} ${l.line}${M.reset}`)}}a<o.length&&console.log(`${M.gray} ...${M.reset}`),console.log()}function Gg(t,e,s){console.log(`
66
- ${M.bold}${M.cyan} File exists \u2014 showing changes: ${t}${M.reset}`);let n=Ts(e,s),o=0;for(let i of n)i.type!=="same"&&o++;if(o===0){console.log(`${M.gray} (identical content)${M.reset}`);return}let r=0;for(let i of n){if(r>=30){console.log(`${M.gray} ...(${o-r} more changes)${M.reset}`);break}switch(i.type){case"remove":console.log(`${M.red} - ${i.line}${M.reset}`),r++;break;case"add":console.log(`${M.green} + ${i.line}${M.reset}`),r++;break;default:r>0&&console.log(`${M.gray} ${i.line}${M.reset}`)}}console.log()}function Yg(t,e){console.log(`
64
+ `),o=[],r=s.length,i=n.length;if(r>cu||i>cu){for(let d of s)o.push({type:"remove",line:d});for(let d of n)o.push({type:"add",line:d});return o}let a=Array.from({length:r+1},()=>new Array(i+1).fill(0));for(let d=1;d<=r;d++)for(let f=1;f<=i;f++)s[d-1]===n[f-1]?a[d][f]=a[d-1][f-1]+1:a[d][f]=Math.max(a[d-1][f],a[d][f-1]);let c=r,l=i,u=[];for(;c>0||l>0;)c>0&&l>0&&s[c-1]===n[l-1]?(u.unshift({type:"same",line:s[c-1]}),c--,l--):l>0&&(c===0||a[c][l-1]>=a[c-1][l])?(u.unshift({type:"add",line:n[l-1]}),l--):(u.unshift({type:"remove",line:s[c-1]}),c--);return u}function oy(t,e,s,n=3){console.log(`
65
+ ${M.bold}${M.cyan} Diff: ${t}${M.reset}`);let o=As(e,s),r=[];if(o.forEach((c,l)=>{c.type!=="same"&&r.push(l)}),r.length===0){console.log(`${M.gray} (no changes)${M.reset}`);return}let i=Math.max(0,r[0]-n),a=Math.min(o.length,r[r.length-1]+n+1);i>0&&console.log(`${M.gray} ...${M.reset}`);for(let c=i;c<a;c++){let l=o[c];switch(l.type){case"remove":console.log(`${M.red} - ${l.line}${M.reset}`);break;case"add":console.log(`${M.green} + ${l.line}${M.reset}`);break;default:console.log(`${M.gray} ${l.line}${M.reset}`)}}a<o.length&&console.log(`${M.gray} ...${M.reset}`),console.log()}function ry(t,e,s){console.log(`
66
+ ${M.bold}${M.cyan} File exists \u2014 showing changes: ${t}${M.reset}`);let n=As(e,s),o=0;for(let i of n)i.type!=="same"&&o++;if(o===0){console.log(`${M.gray} (identical content)${M.reset}`);return}let r=0;for(let i of n){if(r>=30){console.log(`${M.gray} ...(${o-r} more changes)${M.reset}`);break}switch(i.type){case"remove":console.log(`${M.red} - ${i.line}${M.reset}`),r++;break;case"add":console.log(`${M.green} + ${i.line}${M.reset}`),r++;break;default:r>0&&console.log(`${M.gray} ${i.line}${M.reset}`)}}console.log()}function iy(t,e){console.log(`
67
67
  ${M.bold}${M.cyan} New file: ${t}${M.reset}`);let s=e.split(`
68
- `),n=s.slice(0,20);for(let o of n)console.log(`${M.green} + ${o}${M.reset}`);s.length>20&&console.log(`${M.gray} ...+${s.length-20} more lines${M.reset}`),console.log()}async function Kg(t){return Ug()?!0:Wg(` ${t}?`)}function zg(t,e,s,n){let o=n||process.stdout.columns||80,r=Math.floor((o-3)/2);console.log(`
69
- ${M.bold}${M.cyan} Side-by-side: ${t}${M.reset}`),console.log(` ${M.dim}${"\u2500".repeat(r)}\u252C${"\u2500".repeat(r)}${M.reset}`);let i=Ts(e,s),a=[],c=0;for(;c<i.length;)if(i[c].type==="same")a.push({left:i[c].line,right:i[c].line,type:"same"}),c++;else if(i[c].type==="remove"){let h=[];for(;c<i.length&&i[c].type==="remove";)h.push(i[c].line),c++;let m=[];for(;c<i.length&&i[c].type==="add";)m.push(i[c].line),c++;let g=Math.max(h.length,m.length);for(let b=0;b<g;b++)a.push({left:b<h.length?h[b]:"",right:b<m.length?m[b]:"",type:"changed"})}else i[c].type==="add"&&(a.push({left:"",right:i[c].line,type:"changed"}),c++);let l=a.map((h,m)=>h.type!=="same"?m:-1).filter(h=>h>=0);if(l.length===0){console.log(` ${M.gray}(no changes)${M.reset}`);return}let u=Math.max(0,l[0]-2),d=Math.min(a.length,l[l.length-1]+3),f=(h,m)=>{let g=h.replace(/\x1b\[[0-9;]*m/g,"");return g.length>=m?h.substring(0,m):h+" ".repeat(m-g.length)};u>0&&console.log(` ${M.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${M.reset}`);for(let h=u;h<d;h++){let m=a[h];if(m.type==="same")console.log(` ${M.gray}${f(m.left,r)}${M.reset}\u2502${M.gray}${f(m.right,r)}${M.reset}`);else{let g=m.left?`${M.red}${f(m.left,r)}${M.reset}`:`${f("",r)}`,b=m.right?`${M.green}${f(m.right,r)}${M.reset}`:`${f("",r)}`;console.log(` ${g}\u2502${b}`)}}d<a.length&&console.log(` ${M.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${M.reset}`),console.log(` ${M.dim}${"\u2500".repeat(r)}\u2534${"\u2500".repeat(r)}${M.reset}
70
- `)}function Xg(t,e,s,n={}){let o=n.label||"Update",r=n.context||3,i=n.annotations||[],a=Jo.isAbsolute(t)?Jo.relative(process.cwd(),t):t,c=Ts(e,s),l=1,u=1;for(let C of c)C.type==="same"?(C.oldLine=l++,C.newLine=u++):C.type==="remove"?(C.oldLine=l++,C.newLine=null):(C.oldLine=null,C.newLine=u++);let d=0,f=0;for(let C of c)C.type==="add"?d++:C.type==="remove"&&f++;if(console.log(`
68
+ `),n=s.slice(0,20);for(let o of n)console.log(`${M.green} + ${o}${M.reset}`);s.length>20&&console.log(`${M.gray} ...+${s.length-20} more lines${M.reset}`),console.log()}async function ay(t){return sy()?!0:ny(` ${t}?`)}function cy(t,e,s,n){let o=n||process.stdout.columns||80,r=Math.floor((o-3)/2);console.log(`
69
+ ${M.bold}${M.cyan} Side-by-side: ${t}${M.reset}`),console.log(` ${M.dim}${"\u2500".repeat(r)}\u252C${"\u2500".repeat(r)}${M.reset}`);let i=As(e,s),a=[],c=0;for(;c<i.length;)if(i[c].type==="same")a.push({left:i[c].line,right:i[c].line,type:"same"}),c++;else if(i[c].type==="remove"){let h=[];for(;c<i.length&&i[c].type==="remove";)h.push(i[c].line),c++;let g=[];for(;c<i.length&&i[c].type==="add";)g.push(i[c].line),c++;let m=Math.max(h.length,g.length);for(let b=0;b<m;b++)a.push({left:b<h.length?h[b]:"",right:b<g.length?g[b]:"",type:"changed"})}else i[c].type==="add"&&(a.push({left:"",right:i[c].line,type:"changed"}),c++);let l=a.map((h,g)=>h.type!=="same"?g:-1).filter(h=>h>=0);if(l.length===0){console.log(` ${M.gray}(no changes)${M.reset}`);return}let u=Math.max(0,l[0]-2),d=Math.min(a.length,l[l.length-1]+3),f=(h,g)=>{let m=h.replace(/\x1b\[[0-9;]*m/g,"");return m.length>=g?h.substring(0,g):h+" ".repeat(g-m.length)};u>0&&console.log(` ${M.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${M.reset}`);for(let h=u;h<d;h++){let g=a[h];if(g.type==="same")console.log(` ${M.gray}${f(g.left,r)}${M.reset}\u2502${M.gray}${f(g.right,r)}${M.reset}`);else{let m=g.left?`${M.red}${f(g.left,r)}${M.reset}`:`${f("",r)}`,b=g.right?`${M.green}${f(g.right,r)}${M.reset}`:`${f("",r)}`;console.log(` ${m}\u2502${b}`)}}d<a.length&&console.log(` ${M.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${M.reset}`),console.log(` ${M.dim}${"\u2500".repeat(r)}\u2534${"\u2500".repeat(r)}${M.reset}
70
+ `)}function ly(t,e,s,n={}){let o=n.label||"Update",r=n.context||3,i=n.annotations||[],a=er.isAbsolute(t)?er.relative(process.cwd(),t):t,c=As(e,s),l=1,u=1;for(let C of c)C.type==="same"?(C.oldLine=l++,C.newLine=u++):C.type==="remove"?(C.oldLine=l++,C.newLine=null):(C.oldLine=null,C.newLine=u++);let d=0,f=0;for(let C of c)C.type==="add"?d++:C.type==="remove"&&f++;if(console.log(`
71
71
  ${M.green}\u23FA${M.reset} ${M.bold}${o}(${a})${M.reset}`),d===0&&f===0){console.log(` ${M.dim}\u23BF (no changes)${M.reset}
72
- `);return}let h=[];if(d>0&&h.push(`Added ${d} line${d!==1?"s":""}`),f>0&&h.push(`removed ${f} line${f!==1?"s":""}`),i.length>0){let C=i.filter(V=>V.severity==="error").length,K=i.filter(V=>V.severity==="warn").length,Q=i.filter(V=>V.severity==="info").length,re=[];C>0&&re.push(`${M.red}${C} error${C!==1?"s":""}${M.dim}`),K>0&&re.push(`${M.yellow}${K} warning${K!==1?"s":""}${M.dim}`),Q>0&&re.push(`${M.cyan}${Q} info${Q!==1?"s":""}${M.dim}`),h.push(`found ${re.join(", ")}`)}console.log(` ${M.dim}\u23BF ${h.join(", ")}${M.reset}`);let g=[];c.forEach((C,K)=>{C.type!=="same"&&g.push(K)});let b=[],v=null,O=null;for(let C of g){let K=Math.max(0,C-r),Q=Math.min(c.length-1,C+r);v===null?(v=K,O=Q):(K<=O+1||(b.push([v,O]),v=K),O=Q)}v!==null&&b.push([v,O]);let U=" ",L=process.stdout.columns||120;function R(C,K,Q){let re=Q.replace(/\x1b\[[0-9;]*m/g,""),V=Q+" ".repeat(Math.max(0,L-re.length));return`${C}${K}${V}${M.reset}`}for(let C=0;C<b.length;C++){C>0&&console.log(`${U}${M.dim}\xB7\xB7\xB7${M.reset}`);let[K,Q]=b[C];for(let re=K;re<=Q;re++){let V=c[re],H=V.newLine!=null?V.newLine:V.oldLine,_=String(H).padStart(4),he=V.type!=="remove"?i.filter(de=>de.line===V.newLine):[];V.type==="remove"?console.log(R(Di.diff_rem_bg,M.red,`${U}${_} - ${V.line}`)):V.type==="add"?console.log(R(Di.diff_add_bg,M.green,`${U}${_} + ${V.line}`)):console.log(`${U}${M.dim}${_} ${M.reset}${V.line}`);for(let de of he){let me=M.cyan,ge="\u2139";de.severity==="error"?(me=M.red,ge="\u2716"):de.severity==="warn"&&(me=M.yellow,ge="\u26A0"),console.log(`${U} ${me}${ge} ${de.message}${M.reset}`)}}}console.log()}function Vg(t,e,s={}){let n=Jo.isAbsolute(t)?Jo.relative(process.cwd(),t):t,o=e.split(`
72
+ `);return}let h=[];if(d>0&&h.push(`Added ${d} line${d!==1?"s":""}`),f>0&&h.push(`removed ${f} line${f!==1?"s":""}`),i.length>0){let C=i.filter(ie=>ie.severity==="error").length,Z=i.filter(ie=>ie.severity==="warn").length,Y=i.filter(ie=>ie.severity==="info").length,ue=[];C>0&&ue.push(`${M.red}${C} error${C!==1?"s":""}${M.dim}`),Z>0&&ue.push(`${M.yellow}${Z} warning${Z!==1?"s":""}${M.dim}`),Y>0&&ue.push(`${M.cyan}${Y} info${Y!==1?"s":""}${M.dim}`),h.push(`found ${ue.join(", ")}`)}console.log(` ${M.dim}\u23BF ${h.join(", ")}${M.reset}`);let m=[];c.forEach((C,Z)=>{C.type!=="same"&&m.push(Z)});let b=[],x=null,j=null;for(let C of m){let Z=Math.max(0,C-r),Y=Math.min(c.length-1,C+r);x===null?(x=Z,j=Y):(Z<=j+1||(b.push([x,j]),x=Z),j=Y)}x!==null&&b.push([x,j]);let G=" ",L=process.stdout.columns||120;function P(C,Z,Y){let ue=Y.replace(/\x1b\[[0-9;]*m/g,""),ie=Y+" ".repeat(Math.max(0,L-ue.length));return`${C}${Z}${ie}${M.reset}`}for(let C=0;C<b.length;C++){C>0&&console.log(`${G}${M.dim}\xB7\xB7\xB7${M.reset}`);let[Z,Y]=b[C];for(let ue=Z;ue<=Y;ue++){let ie=c[ue],se=ie.newLine!=null?ie.newLine:ie.oldLine,T=String(se).padStart(4),Te=ie.type!=="remove"?i.filter(K=>K.line===ie.newLine):[];ie.type==="remove"?console.log(P(Gi.diff_rem_bg,M.red,`${G}${T} - ${ie.line}`)):ie.type==="add"?console.log(P(Gi.diff_add_bg,M.green,`${G}${T} + ${ie.line}`)):console.log(`${G}${M.dim}${T} ${M.reset}${ie.line}`);for(let K of Te){let X=M.cyan,me="\u2139";K.severity==="error"?(X=M.red,me="\u2716"):K.severity==="warn"&&(X=M.yellow,me="\u26A0"),console.log(`${G} ${X}${me} ${K.message}${M.reset}`)}}}console.log()}function uy(t,e,s={}){let n=er.isAbsolute(t)?er.relative(process.cwd(),t):t,o=e.split(`
73
73
  `),r=s.annotations||[];console.log(`
74
- ${M.green}\u23FA${M.reset} ${M.bold}Create(${n})${M.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,h=r.filter(g=>g.severity==="info").length,m=[];d>0&&m.push(`${M.red}${d} error${d!==1?"s":""}${M.dim}`),f>0&&m.push(`${M.yellow}${f} warning${f!==1?"s":""}${M.dim}`),h>0&&m.push(`${M.cyan}${h} info${h!==1?"s":""}${M.dim}`),i.push(`found ${m.join(", ")}`)}console.log(` ${M.dim}\u23BF ${i.join(", ")}${M.reset}`);let c=" ",l=process.stdout.columns||120,u=Math.min(o.length,20);for(let d=0;d<u;d++){let f=String(d+1).padStart(4),h=d+1,m=r.filter(O=>O.line===h),g=`${c}${f} + ${o[d]}`,b=g.replace(/\x1b\[[0-9;]*m/g,""),v=g+" ".repeat(Math.max(0,l-b.length));console.log(`${Di.diff_add_bg}${M.green}${v}${M.reset}`);for(let O of m){let U=M.cyan,L="\u2139";O.severity==="error"?(U=M.red,L="\u2716"):O.severity==="warn"&&(U=M.yellow,L="\u26A0"),console.log(`${c} ${U}${L} ${O.message}${M.reset}`)}}o.length>20&&console.log(`${c}${M.dim} ...+${o.length-20} more lines${M.reset}`),console.log()}Xl.exports={diffLines:Ts,showEditDiff:Hg,showWriteDiff:Gg,showNewFilePreview:Yg,confirmFileChange:Kg,showSideBySideDiff:zg,showClaudeDiff:Xg,showClaudeNewFile:Vg}});var er=se((Ek,Ql)=>{var Jl=require("util").promisify(require("child_process").exec),Jg=require("util").promisify(require("child_process").execFile),{C:Le}=Ue();async function qi(t){try{let{stdout:e}=await Jl(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function Zo(...t){try{let{stdout:e}=await Jg("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function Zg(){return await qi("git rev-parse --is-inside-work-tree")==="true"}async function Qg(){return await qi("git branch --show-current")}async function Fi(){try{let{stdout:t}=await Jl("git status --porcelain",{cwd:process.cwd(),timeout:3e4});return!t||!t.trim()?[]:t.split(`
75
- `).filter(Boolean).map(e=>{let s=e.substring(0,2).trim(),n=e.substring(3);return{status:s,file:n}})}catch{return[]}}async function Qo(t=!1){return await qi(`git diff ${t?"--cached":""}`)||""}async function Bi(){return(await Fi()).map(e=>e.file)}async function Zl(){let t=await Bi();if(t.length===0)return null;let e=await Qo(),n=await Qo(!0)||e,o=0,r=0;if(n){let u=n.split(`
76
- `);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 c=t.slice(0,3).map(u=>u.split("/").pop());return{summary:`${i}: update ${c.join(", ")}${t.length>3?` (+${t.length-3} more)`:""}`,type:i,files:t,stats:{additions:o,deletions:r}}}async function ey(t){let s=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await Zo("checkout","-b",s)!==null?s:null}async function ty(t){return await Zo("add","-A"),await Zo("commit","-m",t)?await Zo("rev-parse","--short","HEAD"):null}async function ny(){let t=await Zl();if(!t)return`${Le.dim}No changes${Le.reset}`;let e=[];e.push(`
77
- ${Le.bold}${Le.cyan}Git Diff Summary:${Le.reset}`),e.push(` ${Le.green}+${t.stats.additions}${Le.reset} ${Le.red}-${t.stats.deletions}${Le.reset} in ${t.files.length} file(s)`),e.push(`
78
- ${Le.bold}${Le.cyan}Files:${Le.reset}`);for(let s of t.files.slice(0,20))e.push(` ${Le.dim}${s}${Le.reset}`);return t.files.length>20&&e.push(` ${Le.dim}...+${t.files.length-20} more${Le.reset}`),e.push(`
79
- ${Le.bold}${Le.cyan}Suggested message:${Le.reset}`),e.push(` ${Le.cyan}${t.summary}${Le.reset}
74
+ ${M.green}\u23FA${M.reset} ${M.bold}Create(${n})${M.reset}`);let i=[`${o.length} line${o.length!==1?"s":""}`];if(r.length>0){let d=r.filter(m=>m.severity==="error").length,f=r.filter(m=>m.severity==="warn").length,h=r.filter(m=>m.severity==="info").length,g=[];d>0&&g.push(`${M.red}${d} error${d!==1?"s":""}${M.dim}`),f>0&&g.push(`${M.yellow}${f} warning${f!==1?"s":""}${M.dim}`),h>0&&g.push(`${M.cyan}${h} info${h!==1?"s":""}${M.dim}`),i.push(`found ${g.join(", ")}`)}console.log(` ${M.dim}\u23BF ${i.join(", ")}${M.reset}`);let c=" ",l=process.stdout.columns||120,u=Math.min(o.length,20);for(let d=0;d<u;d++){let f=String(d+1).padStart(4),h=d+1,g=r.filter(j=>j.line===h),m=`${c}${f} + ${o[d]}`,b=m.replace(/\x1b\[[0-9;]*m/g,""),x=m+" ".repeat(Math.max(0,l-b.length));console.log(`${Gi.diff_add_bg}${M.green}${x}${M.reset}`);for(let j of g){let G=M.cyan,L="\u2139";j.severity==="error"?(G=M.red,L="\u2716"):j.severity==="warn"&&(G=M.yellow,L="\u26A0"),console.log(`${c} ${G}${L} ${j.message}${M.reset}`)}}o.length>20&&console.log(`${c}${M.dim} ...+${o.length-20} more lines${M.reset}`),console.log()}lu.exports={diffLines:As,showEditDiff:oy,showWriteDiff:ry,showNewFilePreview:iy,confirmFileChange:ay,showSideBySideDiff:cy,showDiff:ly,showNewFile:uy}});var sr=re((Kk,pu)=>{var du=require("util").promisify(require("child_process").exec),dy=require("util").promisify(require("child_process").execFile),{C:Ie}=He();async function Ki(t){try{let{stdout:e}=await du(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function tr(...t){try{let{stdout:e}=await dy("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function fy(){return await Ki("git rev-parse --is-inside-work-tree")==="true"}async function py(){return await Ki("git branch --show-current")}async function zi(){try{let{stdout:t}=await du("git status --porcelain",{cwd:process.cwd(),timeout:3e4});return!t||!t.trim()?[]:t.split(`
75
+ `).filter(Boolean).map(e=>{let s=e.substring(0,2).trim(),n=e.substring(3);return{status:s,file:n}})}catch{return[]}}async function nr(t=!1){return await Ki(`git diff ${t?"--cached":""}`)||""}async function Xi(){return(await zi()).map(e=>e.file)}async function fu(){let t=await Xi();if(t.length===0)return null;let e=await nr(),n=await nr(!0)||e,o=0,r=0;if(n){let u=n.split(`
76
+ `);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 c=t.slice(0,3).map(u=>u.split("/").pop());return{summary:`${i}: update ${c.join(", ")}${t.length>3?` (+${t.length-3} more)`:""}`,type:i,files:t,stats:{additions:o,deletions:r}}}async function hy(t){let s=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await tr("checkout","-b",s)!==null?s:null}async function my(t){return await tr("add","-A"),await tr("commit","-m",t)?await tr("rev-parse","--short","HEAD"):null}async function gy(){let t=await fu();if(!t)return`${Ie.dim}No changes${Ie.reset}`;let e=[];e.push(`
77
+ ${Ie.bold}${Ie.cyan}Git Diff Summary:${Ie.reset}`),e.push(` ${Ie.green}+${t.stats.additions}${Ie.reset} ${Ie.red}-${t.stats.deletions}${Ie.reset} in ${t.files.length} file(s)`),e.push(`
78
+ ${Ie.bold}${Ie.cyan}Files:${Ie.reset}`);for(let s of t.files.slice(0,20))e.push(` ${Ie.dim}${s}${Ie.reset}`);return t.files.length>20&&e.push(` ${Ie.dim}...+${t.files.length-20} more${Ie.reset}`),e.push(`
79
+ ${Ie.bold}${Ie.cyan}Suggested message:${Ie.reset}`),e.push(` ${Ie.cyan}${t.summary}${Ie.reset}
80
80
  `),e.join(`
81
- `)}async function sy(){return(await Fi()).filter(e=>e.status==="UU"||e.status==="AA"||e.status==="DD")}async function oy(){let t=await Bi();if(t.length===0)return"";let e=[`CHANGED FILES (${t.length}):`];for(let n of t.slice(0,10))e.push(` ${n}`);let s=await Qo();if(s){let n=s.length>5e3?s.substring(0,5e3)+`
81
+ `)}async function yy(){return(await zi()).filter(e=>e.status==="UU"||e.status==="AA"||e.status==="DD")}async function $y(){let t=await Xi();if(t.length===0)return"";let e=[`CHANGED FILES (${t.length}):`];for(let n of t.slice(0,10))e.push(` ${n}`);let s=await nr();if(s){let n=s.length>5e3?s.substring(0,5e3)+`
82
82
  ...(truncated)`:s;e.push(`
83
83
  DIFF:
84
84
  ${n}`)}return e.join(`
85
- `)}Ql.exports={isGitRepo:Zg,getCurrentBranch:Qg,getStatus:Fi,getDiff:Qo,getChangedFiles:Bi,analyzeDiff:Zl,createBranch:ey,commit:ty,formatDiffSummary:ny,getDiffContext:oy,getMergeConflicts:sy}});var iu=se((Rk,ru)=>{var Ge=require("fs").promises,Tk=require("fs"),gt=require("path"),ry=require("crypto"),{execSync:Rs}=require("child_process"),iy=100*1024,nu=50,nt=[],Vn=[];function ay(t,e,s,n){for(nt.push({tool:t,filePath:e,oldContent:s,newContent:n,timestamp:Date.now()});nt.length>nu;)nt.shift();Vn.length=0,su(nt[nt.length-1]).catch(()=>{})}async function cy(){if(nt.length===0)return null;let t=nt.pop();if(t.oldContent===null)try{await Ge.unlink(t.filePath)}catch{}else await Ge.writeFile(t.filePath,t.oldContent,"utf-8");return Vn.push(t),{tool:t.tool,filePath:t.filePath,wasCreated:t.oldContent===null}}async function ly(){if(Vn.length===0)return null;let t=Vn.pop();return await Ge.writeFile(t.filePath,t.newContent,"utf-8"),nt.push(t),{tool:t.tool,filePath:t.filePath}}function uy(t=10){return nt.slice(-t).reverse().map(e=>({tool:e.tool,filePath:e.filePath,timestamp:e.timestamp}))}function dy(){return nt.length}function fy(){return Vn.length}function py({diskToo:t=!0}={}){if(nt.length=0,Vn.length=0,t){let e=nr();Ge.readdir(e).then(s=>{for(let n of s)n.endsWith(".json")&&Ge.unlink(gt.join(e,n)).catch(()=>{})}).catch(()=>{})}}function nr(){return gt.join(process.cwd(),".nex","history")}async function eu(t,e){if(t==null)return{inline:!0,content:t};if(Buffer.byteLength(t,"utf-8")<=iy)return{inline:!0,content:t};let s=ry.createHash("sha256").update(t,"utf-8").digest("hex"),n=gt.join(e,"blobs");return await Ge.mkdir(n,{recursive:!0}),await Ge.writeFile(gt.join(n,s),t,"utf-8"),{inline:!1,hash:s}}async function su(t){let e=nr();await Ge.mkdir(e,{recursive:!0});let s=gt.basename(t.filePath).replace(/[^a-zA-Z0-9]/g,"-"),n=`${t.timestamp}-${s}.json`,o=await eu(t.oldContent,e),r=await eu(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 Ge.writeFile(gt.join(e,n),JSON.stringify(i),"utf-8")}async function tu(t,e){if(!t)return null;if(t.inline)return t.content;let s=gt.join(e,"blobs",t.hash);return Ge.readFile(s,"utf-8")}async function hy(){let t=nr(),e;try{e=await Ge.readdir(t)}catch{return 0}let s=e.filter(o=>o.endsWith(".json")).sort(),n=0;for(let o of s)try{let r=await Ge.readFile(gt.join(t,o),"utf-8"),i=JSON.parse(r),a=await tu(i.oldContent,t),c=await tu(i.newContent,t);nt.push({tool:i.tool,filePath:i.filePath,timestamp:i.timestamp,oldContent:a,newContent:c}),n++}catch{}for(;nt.length>nu;)nt.shift();return n}async function my(t=7){let e=nr(),s;try{s=await Ge.readdir(e)}catch{return 0}let n=Date.now()-t*24*60*60*1e3,o=s.filter(l=>l.endsWith(".json")),r=0,i=new Set,a=[];for(let l of o)try{let u=await Ge.readFile(gt.join(e,l),"utf-8"),d=JSON.parse(u);d.timestamp<n?(a.push(l),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 l of a)try{await Ge.unlink(gt.join(e,l))}catch{}let c=gt.join(e,"blobs");try{let l=await Ge.readdir(c);for(let u of l)if(!i.has(u))try{await Ge.unlink(gt.join(c,u))}catch{}}catch{}return r}var tr="nex-snapshot";function gy(t,e=process.cwd()){let s=t?`${tr}-${t.replace(/[^a-zA-Z0-9_-]/g,"-")}`:`${tr}-${Date.now()}`;try{return Rs("git status --porcelain",{cwd:e,timeout:1e4}).toString().trim()?(Rs(`git stash push -u -m "${s}"`,{cwd:e,timeout:15e3}),Rs("git stash pop",{cwd:e,timeout:1e4}),{name:s,label:s,ok:!0}):{name:s,label:s,ok:!1,error:"No changes to snapshot (working tree clean)"}}catch(n){return{name:s,label:s,ok:!1,error:n.message}}}function ou(t=process.cwd()){try{let e=Rs("git stash list",{cwd:t,timeout:1e4}).toString().trim();return e?e.split(`
86
- `).map(s=>{let n=s.match(/^stash@\{(\d+)\}:\s+(?:WIP on [^:]+:\s+\S+\s+|On \S+:\s+)(.*)/);if(!n)return null;let o=n[2].trim();return o.startsWith(tr)?{index:parseInt(n[1],10),label:o,shortName:o.replace(`${tr}-`,""),date:s}:null}).filter(Boolean):[]}catch{return[]}}function yy(t,e=process.cwd()){try{let s=ou(e);if(s.length===0)return{ok:!1,error:"No snapshots found"};let n;return t===void 0||t==="last"?n=s[0]:typeof t=="number"?n=s.find(o=>o.index===t):n=s.find(o=>o.label===t||o.shortName===t||o.shortName.includes(String(t))),n?(Rs(`git stash apply stash@{${n.index}}`,{cwd:e,timeout:15e3}),{ok:!0,label:n.label}):{ok:!1,error:`Snapshot not found: ${t}`}}catch(s){return{ok:!1,error:s.message}}}ru.exports={recordChange:ay,undo:cy,redo:ly,getHistory:uy,getUndoCount:dy,getRedoCount:fy,clearHistory:py,persistEntry:su,loadPersistedHistory:hy,pruneHistory:my,createSnapshot:gy,listSnapshots:ou,restoreSnapshot:yy}});var Yi=se((Ck,fu)=>{var Ae=require("fs"),st=require("path"),{atomicWrite:$y,withFileLockSync:wy}=fn(),Qe=[];function Cs(){return st.join(process.cwd(),".nex","skills")}function au(){return st.join(process.cwd(),".nex","config.json")}function cu(){let t=Cs();return Ae.existsSync(t)||Ae.mkdirSync(t,{recursive:!0}),t}function Hi(){let t=au();if(!Ae.existsSync(t))return[];try{let e=JSON.parse(Ae.readFileSync(t,"utf-8"));return e.skills&&Array.isArray(e.skills.disabled)?e.skills.disabled:[]}catch{return[]}}function lu(t){let e=au(),s=st.dirname(e);Ae.existsSync(s)||Ae.mkdirSync(s,{recursive:!0}),wy(e,()=>{let n={};if(Ae.existsSync(e))try{n=JSON.parse(Ae.readFileSync(e,"utf-8"))}catch{n={}}n.skills||(n.skills={}),n.skills.disabled=t,$y(e,JSON.stringify(n,null,2))})}function uu(t,e){let s=[];if(typeof t!="object"||t===null)return{valid:!1,errors:["Module must export an object"]};if(t.name!==void 0&&typeof t.name!="string"&&s.push("name must be a string"),t.description!==void 0&&typeof t.description!="string"&&s.push("description must be a string"),t.instructions!==void 0&&typeof t.instructions!="string"&&s.push("instructions must be a string"),t.commands!==void 0)if(!Array.isArray(t.commands))s.push("commands must be an array");else for(let n=0;n<t.commands.length;n++){let o=t.commands[n];(!o.cmd||typeof o.cmd!="string")&&s.push(`commands[${n}].cmd must be a non-empty string`),o.handler!==void 0&&typeof o.handler!="function"&&s.push(`commands[${n}].handler must be a function`)}if(t.tools!==void 0)if(!Array.isArray(t.tools))s.push("tools must be an array");else for(let n=0;n<t.tools.length;n++){let o=t.tools[n];(!o.function||!o.function.name||typeof o.function.name!="string")&&s.push(`tools[${n}].function.name must be a non-empty string`),o.execute!==void 0&&typeof o.execute!="function"&&s.push(`tools[${n}].execute must be a function`)}return{valid:s.length===0,errors:s}}function du(t){let e=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(!e)return{triggers:[],body:t};let s=e[1],n=e[2].trim(),o=[],r=!1;for(let i of s.split(`
87
- `)){let a=i.trim();if(/^trigger:\s*$/i.test(a)){r=!0;continue}r&&a.startsWith("- ")?o.push(a.slice(2).trim().replace(/^["']|["']$/g,"")):r&&a&&!a.startsWith("#")&&(r=!1)}return{triggers:o,body:n}}function Wi(t){try{let e=Ae.readFileSync(t,"utf-8").trim();if(!e)return null;let s=st.basename(t,".md"),{triggers:n,body:o}=du(e);return{name:s,type:"prompt",filePath:t,instructions:o||e,triggers:n,commands:[],tools:[]}}catch{return null}}function Ui(t){try{let e=require(t),{valid:s,errors:n}=uu(e,t);return s?{name:e.name||st.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}
85
+ `)}pu.exports={isGitRepo:fy,getCurrentBranch:py,getStatus:zi,getDiff:nr,getChangedFiles:Xi,analyzeDiff:fu,createBranch:hy,commit:my,formatDiffSummary:gy,getDiffContext:$y,getMergeConflicts:yy}});var bu=re((Xk,wu)=>{var Ke=require("fs").promises,zk=require("fs"),$t=require("path"),wy=require("crypto"),{execSync:Os}=require("child_process"),by=100*1024,gu=50,st=[],es=[];function _y(t,e,s,n){for(st.push({tool:t,filePath:e,oldContent:s,newContent:n,timestamp:Date.now()});st.length>gu;)st.shift();es.length=0,yu(st[st.length-1]).catch(()=>{})}async function xy(){if(st.length===0)return null;let t=st.pop();if(t.oldContent===null)try{await Ke.unlink(t.filePath)}catch{}else await Ke.writeFile(t.filePath,t.oldContent,"utf-8");return es.push(t),{tool:t.tool,filePath:t.filePath,wasCreated:t.oldContent===null}}async function ky(){if(es.length===0)return null;let t=es.pop();return await Ke.writeFile(t.filePath,t.newContent,"utf-8"),st.push(t),{tool:t.tool,filePath:t.filePath}}function vy(t=10){return st.slice(-t).reverse().map(e=>({tool:e.tool,filePath:e.filePath,timestamp:e.timestamp}))}function Sy(){return st.length}function Ey(){return es.length}function Ty({diskToo:t=!0}={}){if(st.length=0,es.length=0,t){let e=rr();Ke.readdir(e).then(s=>{for(let n of s)n.endsWith(".json")&&Ke.unlink($t.join(e,n)).catch(()=>{})}).catch(()=>{})}}function rr(){return $t.join(process.cwd(),".nex","history")}async function hu(t,e){if(t==null)return{inline:!0,content:t};if(Buffer.byteLength(t,"utf-8")<=by)return{inline:!0,content:t};let s=wy.createHash("sha256").update(t,"utf-8").digest("hex"),n=$t.join(e,"blobs");return await Ke.mkdir(n,{recursive:!0}),await Ke.writeFile($t.join(n,s),t,"utf-8"),{inline:!1,hash:s}}async function yu(t){let e=rr();await Ke.mkdir(e,{recursive:!0});let s=$t.basename(t.filePath).replace(/[^a-zA-Z0-9]/g,"-"),n=`${t.timestamp}-${s}.json`,o=await hu(t.oldContent,e),r=await hu(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 Ke.writeFile($t.join(e,n),JSON.stringify(i),"utf-8")}async function mu(t,e){if(!t)return null;if(t.inline)return t.content;let s=$t.join(e,"blobs",t.hash);return Ke.readFile(s,"utf-8")}async function Ry(){let t=rr(),e;try{e=await Ke.readdir(t)}catch{return 0}let s=e.filter(o=>o.endsWith(".json")).sort(),n=0;for(let o of s)try{let r=await Ke.readFile($t.join(t,o),"utf-8"),i=JSON.parse(r),a=await mu(i.oldContent,t),c=await mu(i.newContent,t);st.push({tool:i.tool,filePath:i.filePath,timestamp:i.timestamp,oldContent:a,newContent:c}),n++}catch{}for(;st.length>gu;)st.shift();return n}async function Cy(t=7){let e=rr(),s;try{s=await Ke.readdir(e)}catch{return 0}let n=Date.now()-t*24*60*60*1e3,o=s.filter(l=>l.endsWith(".json")),r=0,i=new Set,a=[];for(let l of o)try{let u=await Ke.readFile($t.join(e,l),"utf-8"),d=JSON.parse(u);d.timestamp<n?(a.push(l),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 l of a)try{await Ke.unlink($t.join(e,l))}catch{}let c=$t.join(e,"blobs");try{let l=await Ke.readdir(c);for(let u of l)if(!i.has(u))try{await Ke.unlink($t.join(c,u))}catch{}}catch{}return r}var or="nex-snapshot";function Ay(t,e=process.cwd()){let s=t?`${or}-${t.replace(/[^a-zA-Z0-9_-]/g,"-")}`:`${or}-${Date.now()}`;try{return Os("git status --porcelain",{cwd:e,timeout:1e4}).toString().trim()?(Os(`git stash push -u -m "${s}"`,{cwd:e,timeout:15e3}),Os("git stash pop",{cwd:e,timeout:1e4}),{name:s,label:s,ok:!0}):{name:s,label:s,ok:!1,error:"No changes to snapshot (working tree clean)"}}catch(n){return{name:s,label:s,ok:!1,error:n.message}}}function $u(t=process.cwd()){try{let e=Os("git stash list",{cwd:t,timeout:1e4}).toString().trim();return e?e.split(`
86
+ `).map(s=>{let n=s.match(/^stash@\{(\d+)\}:\s+(?:WIP on [^:]+:\s+\S+\s+|On \S+:\s+)(.*)/);if(!n)return null;let o=n[2].trim();return o.startsWith(or)?{index:parseInt(n[1],10),label:o,shortName:o.replace(`${or}-`,""),date:s}:null}).filter(Boolean):[]}catch{return[]}}function Oy(t,e=process.cwd()){try{let s=$u(e);if(s.length===0)return{ok:!1,error:"No snapshots found"};let n;return t===void 0||t==="last"?n=s[0]:typeof t=="number"?n=s.find(o=>o.index===t):n=s.find(o=>o.label===t||o.shortName===t||o.shortName.includes(String(t))),n?(Os(`git stash apply stash@{${n.index}}`,{cwd:e,timeout:15e3}),{ok:!0,label:n.label}):{ok:!1,error:`Snapshot not found: ${t}`}}catch(s){return{ok:!1,error:s.message}}}wu.exports={recordChange:_y,undo:xy,redo:ky,getHistory:vy,getUndoCount:Sy,getRedoCount:Ey,clearHistory:Ty,persistEntry:yu,loadPersistedHistory:Ry,pruneHistory:Cy,createSnapshot:Ay,listSnapshots:$u,restoreSnapshot:Oy}});var ea=re((Vk,Eu)=>{var Oe=require("fs"),ot=require("path"),{atomicWrite:Ny,withFileLockSync:My}=mn(),et=[];function Ns(){return ot.join(process.cwd(),".nex","skills")}function _u(){return ot.join(process.cwd(),".nex","config.json")}function xu(){let t=Ns();return Oe.existsSync(t)||Oe.mkdirSync(t,{recursive:!0}),t}function Zi(){let t=_u();if(!Oe.existsSync(t))return[];try{let e=JSON.parse(Oe.readFileSync(t,"utf-8"));return e.skills&&Array.isArray(e.skills.disabled)?e.skills.disabled:[]}catch{return[]}}function ku(t){let e=_u(),s=ot.dirname(e);Oe.existsSync(s)||Oe.mkdirSync(s,{recursive:!0}),My(e,()=>{let n={};if(Oe.existsSync(e))try{n=JSON.parse(Oe.readFileSync(e,"utf-8"))}catch{n={}}n.skills||(n.skills={}),n.skills.disabled=t,Ny(e,JSON.stringify(n,null,2))})}function vu(t,e){let s=[];if(typeof t!="object"||t===null)return{valid:!1,errors:["Module must export an object"]};if(t.name!==void 0&&typeof t.name!="string"&&s.push("name must be a string"),t.description!==void 0&&typeof t.description!="string"&&s.push("description must be a string"),t.instructions!==void 0&&typeof t.instructions!="string"&&s.push("instructions must be a string"),t.commands!==void 0)if(!Array.isArray(t.commands))s.push("commands must be an array");else for(let n=0;n<t.commands.length;n++){let o=t.commands[n];(!o.cmd||typeof o.cmd!="string")&&s.push(`commands[${n}].cmd must be a non-empty string`),o.handler!==void 0&&typeof o.handler!="function"&&s.push(`commands[${n}].handler must be a function`)}if(t.tools!==void 0)if(!Array.isArray(t.tools))s.push("tools must be an array");else for(let n=0;n<t.tools.length;n++){let o=t.tools[n];(!o.function||!o.function.name||typeof o.function.name!="string")&&s.push(`tools[${n}].function.name must be a non-empty string`),o.execute!==void 0&&typeof o.execute!="function"&&s.push(`tools[${n}].execute must be a function`)}return{valid:s.length===0,errors:s}}function Su(t){let e=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(!e)return{triggers:[],body:t};let s=e[1],n=e[2].trim(),o=[],r=!1;for(let i of s.split(`
87
+ `)){let a=i.trim();if(/^trigger:\s*$/i.test(a)){r=!0;continue}r&&a.startsWith("- ")?o.push(a.slice(2).trim().replace(/^["']|["']$/g,"")):r&&a&&!a.startsWith("#")&&(r=!1)}return{triggers:o,body:n}}function Vi(t){try{let e=Oe.readFileSync(t,"utf-8").trim();if(!e)return null;let s=ot.basename(t,".md"),{triggers:n,body:o}=Su(e);return{name:s,type:"prompt",filePath:t,instructions:o||e,triggers:n,commands:[],tools:[]}}catch{return null}}function Ji(t){try{let e=require(t),{valid:s,errors:n}=vu(e,t);return s?{name:e.name||ot.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}
88
88
  ${n.join(`
89
- `)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function Gi(){Qe=[];let t=Hi(),e=Cs(),s=[];if(Ae.existsSync(e))try{s=Ae.readdirSync(e)}catch{s=[]}for(let o of s){let r=st.join(e,o),i;try{i=Ae.statSync(r)}catch{continue}if(!i.isFile())continue;let a=null;o.endsWith(".md")?a=Wi(r):o.endsWith(".js")&&(a=Ui(r)),a&&(a.enabled=!t.includes(a.name),Qe.push(a))}let n=st.join(__dirname,"skills");if(!process.env.NEX_SKIP_BUILTIN_SKILLS&&Ae.existsSync(n)){let o;try{o=Ae.readdirSync(n).filter(r=>r.endsWith(".md")||r.endsWith(".js"))}catch{o=[]}for(let r of o){let i=st.join(n,r),a=st.basename(r,st.extname(r));if(Qe.some(u=>u.name===a))continue;let c;try{c=Ae.statSync(i)}catch{continue}if(!c.isFile())continue;let l=r.endsWith(".md")?Wi(i):Ui(i);l&&(l._builtin=!0,l.enabled=!t.includes(l.name),Qe.push(l))}}return Qe}function by(){let t=[];for(let e of Qe)!e.enabled||!e.instructions||t.push(`[Skill: ${e.name}]
89
+ `)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function Qi(){et=[];let t=Zi(),e=Ns(),s=[];if(Oe.existsSync(e))try{s=Oe.readdirSync(e)}catch{s=[]}for(let o of s){let r=ot.join(e,o),i;try{i=Oe.statSync(r)}catch{continue}if(!i.isFile())continue;let a=null;o.endsWith(".md")?a=Vi(r):o.endsWith(".js")&&(a=Ji(r)),a&&(a.enabled=!t.includes(a.name),et.push(a))}let n=ot.join(__dirname,"skills");if(!process.env.NEX_SKIP_BUILTIN_SKILLS&&Oe.existsSync(n)){let o;try{o=Oe.readdirSync(n).filter(r=>r.endsWith(".md")||r.endsWith(".js"))}catch{o=[]}for(let r of o){let i=ot.join(n,r),a=ot.basename(r,ot.extname(r));if(et.some(u=>u.name===a))continue;let c;try{c=Oe.statSync(i)}catch{continue}if(!c.isFile())continue;let l=r.endsWith(".md")?Vi(i):Ji(i);l&&(l._builtin=!0,l.enabled=!t.includes(l.name),et.push(l))}}return et}function Ly(){let t=[];for(let e of et)!e.enabled||!e.instructions||t.push(`[Skill: ${e.name}]
90
90
  ${e.instructions}`);return t.length===0?"":`SKILL INSTRUCTIONS:
91
91
  ${t.join(`
92
92
 
93
- `)}`}function _y(){let t=[];for(let e of Qe)if(e.enabled)for(let s of e.commands)t.push({cmd:s.cmd,desc:s.desc||`[skill: ${e.name}]`});return t}function xy(){let t=[];for(let e of Qe)if(e.enabled)for(let s of e.tools)t.push({type:"function",function:{name:`skill_${s.function.name}`,description:`[Skill:${e.name}] ${s.function.description}`,parameters:s.function.parameters}});return t}async function ky(t,e){if(!t.startsWith("skill_"))return null;let s=t.substring(6);for(let n of Qe)if(n.enabled){for(let o of n.tools)if(o.function.name===s&&o.execute)try{let r=await o.execute(e);return typeof r=="string"?r:JSON.stringify(r)}catch(r){return`ERROR: Skill tool '${s}' failed: ${r.message}`}}return`ERROR: Skill tool '${s}' not found`}function vy(t){let[e,...s]=t.split(/\s+/),n=s.join(" ").trim();for(let o of Qe)if(o.enabled){for(let r of o.commands)if(r.cmd===e&&r.handler){try{let i=r.handler(n);if(typeof i=="string"&&i.length>0)return{handled:!0,agentPrompt:i}}catch(i){console.error(`Skill command error (${e}): ${i.message}`)}return{handled:!0}}}return!1}function Sy(){return Qe.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 Ey(t){let e=Qe.find(n=>n.name===t);if(!e)return!1;e.enabled=!0;let s=Hi().filter(n=>n!==t);return lu(s),!0}function Ty(t){let e=Qe.find(n=>n.name===t);if(!e)return!1;e.enabled=!1;let s=Hi();return s.includes(t)||(s.push(t),lu(s)),!0}function Ry(){return Qe}async function Cy(t,e={}){let{execSync:s}=require("child_process"),n=cu(),o=t;/^[\w-]+\/[\w.-]+$/.test(t)&&(o=`https://github.com/${t}.git`);let r=e.name||st.basename(o,".git").replace(/^nex-skill-/,""),i=st.join(n,r);if(Ae.existsSync(i))return{ok:!1,name:r,error:`Skill "${r}" is already installed at ${i}. Remove it first to reinstall.`};try{if(!/^https?:\/\/[a-zA-Z0-9._\-/:@#?=&%+~]+$/.test(o))throw new Error(`Invalid git URL: ${o}`);let u=i.replace(/'/g,"'\\''");s(`git clone --depth 1 '${o}' '${u}'`,{timeout:3e4,stdio:"pipe"})}catch(u){return{ok:!1,name:r,error:`Git clone failed: ${u.stderr?.toString().trim()||u.message}`}}let a=st.join(i,"skill.json"),c=Ae.existsSync(a),l=Ae.readdirSync(i).some(u=>(u.endsWith(".md")||u.endsWith(".js"))&&!u.startsWith("."));if(!c&&!l){try{Ae.rmSync(i,{recursive:!0,force:!0})}catch{}return{ok:!1,name:r,error:"No skill.json manifest or .md/.js skill file found in repository"}}if(c)try{let u=JSON.parse(Ae.readFileSync(a,"utf-8"));u.name||(u.name=r)}catch{try{Ae.rmSync(i,{recursive:!0,force:!0})}catch{}return{ok:!1,name:r,error:"Invalid skill.json \u2014 not valid JSON"}}return Gi(),{ok:!0,name:r}}async function Ay(t){let e=require("axios");try{let s=encodeURIComponent(`nex-skill ${t} OR nex-code-skill ${t}`);return((await e.get(`https://api.github.com/search/repositories?q=${s}&sort=stars&per_page=10`,{timeout:1e4,headers:{Accept:"application/vnd.github.v3+json"}})).data.items||[]).map(o=>({name:o.name.replace(/^nex-skill-/,""),description:o.description||"(no description)",url:o.clone_url,stars:o.stargazers_count,owner:o.owner.login}))}catch(s){return[{name:"error",description:`Search failed: ${s.message}`,url:"",stars:0,owner:""}]}}function Oy(t){let e=st.join(Cs(),t);if(!Ae.existsSync(e))return{ok:!1,error:`Skill "${t}" not found in ${Cs()}`};try{return Ae.rmSync(e,{recursive:!0,force:!0}),Gi(),{ok:!0}}catch(s){return{ok:!1,error:s.message}}}function Ny(t){if(!t)return[];let e=t.toLowerCase(),s=[];for(let n of Qe){if(!n.enabled||!n.triggers||n.triggers.length===0)continue;if(n.triggers.some(r=>e.includes(r.toLowerCase()))){let r=(n.instructions||"").split(`
93
+ `)}`}function Py(){let t=[];for(let e of et)if(e.enabled)for(let s of e.commands)t.push({cmd:s.cmd,desc:s.desc||`[skill: ${e.name}]`});return t}function Iy(){let t=[];for(let e of et)if(e.enabled)for(let s of e.tools)t.push({type:"function",function:{name:`skill_${s.function.name}`,description:`[Skill:${e.name}] ${s.function.description}`,parameters:s.function.parameters}});return t}async function jy(t,e){if(!t.startsWith("skill_"))return null;let s=t.substring(6);for(let n of et)if(n.enabled){for(let o of n.tools)if(o.function.name===s&&o.execute)try{let r=await o.execute(e);return typeof r=="string"?r:JSON.stringify(r)}catch(r){return`ERROR: Skill tool '${s}' failed: ${r.message}`}}return`ERROR: Skill tool '${s}' not found`}function Dy(t){let[e,...s]=t.split(/\s+/),n=s.join(" ").trim();for(let o of et)if(o.enabled){for(let r of o.commands)if(r.cmd===e&&r.handler){try{let i=r.handler(n);if(typeof i=="string"&&i.length>0)return{handled:!0,agentPrompt:i}}catch(i){console.error(`Skill command error (${e}): ${i.message}`)}return{handled:!0}}}return!1}function qy(){return et.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 Fy(t){let e=et.find(n=>n.name===t);if(!e)return!1;e.enabled=!0;let s=Zi().filter(n=>n!==t);return ku(s),!0}function By(t){let e=et.find(n=>n.name===t);if(!e)return!1;e.enabled=!1;let s=Zi();return s.includes(t)||(s.push(t),ku(s)),!0}function Wy(){return et}async function Uy(t,e={}){let{execSync:s}=require("child_process"),n=xu(),o=t;/^[\w-]+\/[\w.-]+$/.test(t)&&(o=`https://github.com/${t}.git`);let r=e.name||ot.basename(o,".git").replace(/^nex-skill-/,""),i=ot.join(n,r);if(Oe.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}`);let u=i.replace(/'/g,"'\\''");s(`git clone --depth 1 '${o}' '${u}'`,{timeout:3e4,stdio:"pipe"})}catch(u){return{ok:!1,name:r,error:`Git clone failed: ${u.stderr?.toString().trim()||u.message}`}}let a=ot.join(i,"skill.json"),c=Oe.existsSync(a),l=Oe.readdirSync(i).some(u=>(u.endsWith(".md")||u.endsWith(".js"))&&!u.startsWith("."));if(!c&&!l){try{Oe.rmSync(i,{recursive:!0,force:!0})}catch{}return{ok:!1,name:r,error:"No skill.json manifest or .md/.js skill file found in repository"}}if(c)try{let u=JSON.parse(Oe.readFileSync(a,"utf-8"));u.name||(u.name=r)}catch{try{Oe.rmSync(i,{recursive:!0,force:!0})}catch{}return{ok:!1,name:r,error:"Invalid skill.json \u2014 not valid JSON"}}return Qi(),{ok:!0,name:r}}async function Hy(t){let e=require("axios");try{let s=encodeURIComponent(`nex-skill ${t} OR nex-code-skill ${t}`);return((await e.get(`https://api.github.com/search/repositories?q=${s}&sort=stars&per_page=10`,{timeout:1e4,headers:{Accept:"application/vnd.github.v3+json"}})).data.items||[]).map(o=>({name:o.name.replace(/^nex-skill-/,""),description:o.description||"(no description)",url:o.clone_url,stars:o.stargazers_count,owner:o.owner.login}))}catch(s){return[{name:"error",description:`Search failed: ${s.message}`,url:"",stars:0,owner:""}]}}function Yy(t){let e=ot.join(Ns(),t);if(!Oe.existsSync(e))return{ok:!1,error:`Skill "${t}" not found in ${Ns()}`};try{return Oe.rmSync(e,{recursive:!0,force:!0}),Qi(),{ok:!0}}catch(s){return{ok:!1,error:s.message}}}function Gy(t){if(!t)return[];let e=t.toLowerCase(),s=[];for(let n of et){if(!n.enabled||!n.triggers||n.triggers.length===0)continue;if(n.triggers.some(r=>e.includes(r.toLowerCase()))){let r=(n.instructions||"").split(`
94
94
  `).slice(0,3).join(`
95
- `);s.push({name:n.name,instructions:r})}}return s}fu.exports={initSkillsDir:cu,loadAllSkills:Gi,getSkillInstructions:by,getSkillCommands:_y,getSkillToolDefinitions:xy,routeSkillCall:ky,handleSkillCommand:vy,listSkills:Sy,enableSkill:Ey,disableSkill:Ty,getLoadedSkills:Ry,installSkill:Cy,searchSkills:Ay,removeSkill:Oy,matchSkillTriggers:Ny,_getSkillsDir:Cs,_validateScriptSkill:uu,_loadMarkdownSkill:Wi,_loadScriptSkill:Ui,_parseFrontmatter:du}});var zi=se((Ak,$u)=>{var{spawn:My}=require("child_process"),Ly=require("path"),pu=require("fs"),Ut=new Map;function Py(){return Ly.join(process.cwd(),".nex","config.json")}function Ki(){let t=Py();if(!pu.existsSync(t))return{};try{return JSON.parse(pu.readFileSync(t,"utf-8")).mcpServers||{}}catch{return{}}}function sr(t,e,s={},n=1e4){return new Promise((o,r)=>{let i=`${Date.now()}-${Math.random().toString(36).slice(2,6)}`,a=JSON.stringify({jsonrpc:"2.0",id:i,method:e,params:s})+`
95
+ `);s.push({name:n.name,instructions:r})}}return s}Eu.exports={initSkillsDir:xu,loadAllSkills:Qi,getSkillInstructions:Ly,getSkillCommands:Py,getSkillToolDefinitions:Iy,routeSkillCall:jy,handleSkillCommand:Dy,listSkills:qy,enableSkill:Fy,disableSkill:By,getLoadedSkills:Wy,installSkill:Uy,searchSkills:Hy,removeSkill:Yy,matchSkillTriggers:Gy,_getSkillsDir:Ns,_validateScriptSkill:vu,_loadMarkdownSkill:Vi,_loadScriptSkill:Ji,_parseFrontmatter:Su}});var na=re((Jk,Nu)=>{var{spawn:Ky}=require("child_process"),zy=require("path"),Tu=require("fs"),Ht=new Map;function Xy(){return zy.join(process.cwd(),".nex","config.json")}function ta(){let t=Xy();if(!Tu.existsSync(t))return{};try{return JSON.parse(Tu.readFileSync(t,"utf-8")).mcpServers||{}}catch{return{}}}function ir(t,e,s={},n=1e4){return new Promise((o,r)=>{let i=`${Date.now()}-${Math.random().toString(36).slice(2,6)}`,a=JSON.stringify({jsonrpc:"2.0",id:i,method:e,params:s})+`
96
96
  `,c="",l=setTimeout(()=>{d(),r(new Error(`MCP request timeout: ${e}`))},n);function u(f){c+=f.toString();let h=c.split(`
97
- `);for(let m of h)if(m.trim())try{let g=JSON.parse(m);if(g.id===i){d(),g.error?r(new Error(`MCP error: ${g.error.message||JSON.stringify(g.error)}`)):o(g.result);return}}catch{}c=h[h.length-1]||""}function d(){clearTimeout(l),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 hu(t,e){if(Ut.has(t))return Ut.get(t);let s=["PATH","HOME","USER","SHELL","LANG","TERM","NODE_ENV"],n={};for(let i of s)process.env[i]&&(n[i]=process.env[i]);let o=My(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:{...n,...e.env||{}}}),r={name:t,proc:o,tools:[],config:e};try{await sr(o,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.2.0"}});let i=await sr(o,"tools/list",{});return r.tools=i&&i.tools||[],Ut.set(t,r),r}catch(i){throw o.kill(),new Error(`Failed to connect MCP server '${t}': ${i.message}`)}}function mu(t){let e=Ut.get(t);if(!e)return!1;try{e.proc.kill()}catch{}return Ut.delete(t),!0}function Iy(){for(let[t]of Ut)mu(t)}async function gu(t,e,s={}){let n=Ut.get(t);if(!n)throw new Error(`MCP server not connected: ${t}`);let o=await sr(n.proc,"tools/call",{name:e,arguments:s});return o&&Array.isArray(o.content)?o.content.filter(r=>r.type==="text").map(r=>r.text).join(`
98
- `):JSON.stringify(o)}function yu(){let t=[];for(let[e,s]of Ut)for(let n of s.tools)t.push({server:e,name:n.name,description:n.description||"",inputSchema:n.inputSchema||{type:"object",properties:{}}});return t}function jy(){return yu().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function Dy(t,e){if(!t.startsWith("mcp_"))return null;let s=t.substring(4).split("_");if(s.length<2)return null;let n=s[0],o=s.slice(1).join("_");return gu(n,o,e)}function qy(){let t=Ki();return Object.entries(t).map(([e,s])=>{let n=Ut.get(e);return{name:e,command:s.command,connected:!!n,toolCount:n?n.tools.length:0}})}async function Fy(){let t=Ki(),e=[];for(let[s,n]of Object.entries(t))try{let o=await hu(s,n);e.push({name:s,tools:o.tools.length})}catch(o){e.push({name:s,tools:0,error:o.message})}return e}$u.exports={loadMCPConfig:Ki,sendRequest:sr,connectServer:hu,disconnectServer:mu,disconnectAll:Iy,callTool:gu,getAllTools:yu,getMCPToolDefinitions:jy,routeMCPCall:Dy,listServers:qy,connectAll:Fy}});var rr=se((Ok,xu)=>{var wu=require("fs"),Xi=require("path"),or=[],As=[],hn={},Os=["onToolResult","onModelResponse","onSessionStart","onSessionEnd","onFileChange","beforeToolExec","afterToolExec"];function bu(t,e){if(!t||!t.function||!t.function.name)return{ok:!1,error:"Tool definition must have function.name"};if(typeof e!="function")return{ok:!1,error:"Handler must be a function"};let s=t.function.name;return As.some(n=>n.definition.function.name===s)?{ok:!1,error:`Tool "${s}" is already registered`}:(As.push({definition:{type:"function",...t},handler:e}),{ok:!0})}function _u(t,e){return Os.includes(t)?typeof e!="function"?{ok:!1,error:"Handler must be a function"}:(hn[t]||(hn[t]=[]),hn[t].push(e),{ok:!0}):{ok:!1,error:`Unknown event "${t}". Available: ${Os.join(", ")}`}}async function Vi(t,e){let s=hn[t]||[],n=e;for(let o of s)try{let r=await o(n);r!==void 0&&(n=r)}catch(r){process.env.NEX_DEBUG&&console.error(`[plugin] Hook error on ${t}: ${r.message}`)}return n}function By(){let t=Xi.join(process.cwd(),".nex","plugins"),e=[];if(!wu.existsSync(t))return{loaded:0,errors:[]};let s=wu.readdirSync(t).filter(o=>o.endsWith(".js")),n={registerTool:bu,registerHook:_u,EVENTS:Os};for(let o of s){let r=Xi.join(t,o);try{let i=require(r);if(typeof i=="function")i(n);else if(typeof i.setup=="function")i.setup(n);else{e.push(`${o}: Plugin must export a function or { setup: function }`);continue}or.push({name:i.name||Xi.basename(o,".js"),filePath:r})}catch(i){e.push(`${o}: ${i.message}`)}}return{loaded:or.length,errors:e}}function Wy(){return As.map(t=>t.definition)}async function Uy(t,e,s={}){let n=As.find(a=>a.definition.function.name===t);if(!n)return null;let o=await Vi("beforeToolExec",{name:t,args:e,options:s}),r=await n.handler(o.args||e,s);return(await Vi("afterToolExec",{name:t,args:e,result:r})).result||r}function Hy(){return[...or]}function Gy(){let t={};for(let e of Os)t[e]=(hn[e]||[]).length;return t}function Yy(){or.length=0,As.length=0;for(let t of Object.keys(hn))delete hn[t]}xu.exports={registerTool:bu,registerHook:_u,emit:Vi,loadPlugins:By,getPluginToolDefinitions:Wy,executePluginTool:Uy,getLoadedPlugins:Hy,getHookCounts:Gy,clearPlugins:Yy,EVENTS:Os}});var Ji=se((Nk,Eu)=>{var{getSkillToolDefinitions:Ky}=Yi(),{getMCPToolDefinitions:zy}=zi(),{getPluginToolDefinitions:Xy}=rr(),ir=new Map;function ku(){let{TOOL_DEFINITIONS:t}=Jn();return[...t,...Ky(),...zy(),...Xy()]}function vu(t){if(ir.has(t))return ir.get(t);let s=ku().find(o=>o.function.name===t);if(!s)return null;let n=s.function.parameters;return ir.set(t,n),n}function Vy(){ir.clear()}function ar(t,e){if(!t||e.length===0)return null;let s=null,n=1/0;for(let o of e){let r=Su(t.toLowerCase(),o.toLowerCase());r<n&&(n=r,s=o)}return n<=Math.ceil(t.length/2)?s:null}function Su(t,e){let s=t.length,n=e.length,o=Array.from({length:s+1},()=>Array(n+1).fill(0));for(let r=0;r<=s;r++)o[r][0]=r;for(let r=0;r<=n;r++)o[0][r]=r;for(let r=1;r<=s;r++)for(let i=1;i<=n;i++)o[r][i]=t[r-1]===e[i-1]?o[r-1][i-1]:1+Math.min(o[r-1][i],o[r][i-1],o[r-1][i-1]);return o[s][n]}function Jy(t,e){let s=vu(t);if(s===null){let d=ku().map(h=>h.function.name),f=ar(t,d);return{valid:!1,error:`Unknown tool "${t}".${f?` Did you mean "${f}"?`:""}
99
- Available tools: ${d.join(", ")}`}}if(!s||!s.properties)return{valid:!0};let n=s.required||[],o=Object.keys(s.properties),r=Object.keys(e),i=[],a={...e},c=!1;for(let u of n)if(!(u in e)||e[u]===void 0||e[u]===null){let d=ar(u,r);d&&!o.includes(d)?(a[u]=e[d],delete a[d],c=!0):i.push(`Missing required parameter "${u}" (${s.properties[u]?.description||s.properties[u]?.type||"unknown"})`)}new Set(["grep","grep_search","search_files"]).has(t)&&(("-n"in a||"n"in a)&&!o.includes("-n")&&(delete a["-n"],delete a.n,c=!0),("-i"in a||"--ignore-case"in a)&&"ignore_case"in(s.properties||{})&&(a.ignore_case=!0,delete a["-i"],delete a["--ignore-case"],c=!0),("-r"in a||"--recursive"in a)&&(delete a["-r"],delete a["--recursive"],c=!0)),t==="read_file"&&("offset"in a&&!("line_start"in a)&&(a.line_start=a.offset,delete a.offset,c=!0),"start_line"in a&&!("line_start"in a)&&(a.line_start=a.start_line,delete a.start_line,c=!0),"end_line"in a&&!("line_end"in a)&&(a.line_end=a.end_line,delete a.end_line,c=!0));for(let u of Object.keys(a))if(!o.includes(u)){let d=ar(u,o);if(d&&!(d in a))a[d]=a[u],delete a[u],c=!0;else if(!c){let f=d?` Did you mean "${d}"?`:"";i.push(`Unknown parameter "${u}".${f}`)}}for(let u of Object.keys(a)){if(!s.properties[u])continue;let d=s.properties[u].type,f=typeof a[u];d==="string"&&f==="number"?(a[u]=String(a[u]),c=!0):d==="number"&&f==="string"&&!isNaN(a[u])?(a[u]=Number(a[u]),c=!0):d==="boolean"&&f==="string"&&(a[u]=a[u]==="true",c=!0)}return i.length>0&&!c?{valid:!1,error:`Tool "${t}" argument errors:
97
+ `);for(let g of h)if(g.trim())try{let m=JSON.parse(g);if(m.id===i){d(),m.error?r(new Error(`MCP error: ${m.error.message||JSON.stringify(m.error)}`)):o(m.result);return}}catch{}c=h[h.length-1]||""}function d(){clearTimeout(l),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 Ru(t,e){if(Ht.has(t))return Ht.get(t);let s=["PATH","HOME","USER","SHELL","LANG","TERM","NODE_ENV"],n={};for(let i of s)process.env[i]&&(n[i]=process.env[i]);let o=Ky(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:{...n,...e.env||{}}}),r={name:t,proc:o,tools:[],config:e};try{await ir(o,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.2.0"}});let i=await ir(o,"tools/list",{});return r.tools=i&&i.tools||[],Ht.set(t,r),r}catch(i){throw o.kill(),new Error(`Failed to connect MCP server '${t}': ${i.message}`)}}function Cu(t){let e=Ht.get(t);if(!e)return!1;try{e.proc.kill()}catch{}return Ht.delete(t),!0}function Vy(){for(let[t]of Ht)Cu(t)}async function Au(t,e,s={}){let n=Ht.get(t);if(!n)throw new Error(`MCP server not connected: ${t}`);let o=await ir(n.proc,"tools/call",{name:e,arguments:s});return o&&Array.isArray(o.content)?o.content.filter(r=>r.type==="text").map(r=>r.text).join(`
98
+ `):JSON.stringify(o)}function Ou(){let t=[];for(let[e,s]of Ht)for(let n of s.tools)t.push({server:e,name:n.name,description:n.description||"",inputSchema:n.inputSchema||{type:"object",properties:{}}});return t}function Jy(){return Ou().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function Zy(t,e){if(!t.startsWith("mcp_"))return null;let s=t.substring(4).split("_");if(s.length<2)return null;let n=s[0],o=s.slice(1).join("_");return Au(n,o,e)}function Qy(){let t=ta();return Object.entries(t).map(([e,s])=>{let n=Ht.get(e);return{name:e,command:s.command,connected:!!n,toolCount:n?n.tools.length:0}})}async function e$(){let t=ta(),e=[];for(let[s,n]of Object.entries(t))try{let o=await Ru(s,n);e.push({name:s,tools:o.tools.length})}catch(o){e.push({name:s,tools:0,error:o.message})}return e}Nu.exports={loadMCPConfig:ta,sendRequest:ir,connectServer:Ru,disconnectServer:Cu,disconnectAll:Vy,callTool:Au,getAllTools:Ou,getMCPToolDefinitions:Jy,routeMCPCall:Zy,listServers:Qy,connectAll:e$}});var cr=re((Zk,Iu)=>{var Mu=require("fs"),sa=require("path"),ar=[],Ms=[],yn={},Ls=["onToolResult","onModelResponse","onSessionStart","onSessionEnd","onFileChange","beforeToolExec","afterToolExec"];function Lu(t,e){if(!t||!t.function||!t.function.name)return{ok:!1,error:"Tool definition must have function.name"};if(typeof e!="function")return{ok:!1,error:"Handler must be a function"};let s=t.function.name;return Ms.some(n=>n.definition.function.name===s)?{ok:!1,error:`Tool "${s}" is already registered`}:(Ms.push({definition:{type:"function",...t},handler:e}),{ok:!0})}function Pu(t,e){return Ls.includes(t)?typeof e!="function"?{ok:!1,error:"Handler must be a function"}:(yn[t]||(yn[t]=[]),yn[t].push(e),{ok:!0}):{ok:!1,error:`Unknown event "${t}". Available: ${Ls.join(", ")}`}}async function oa(t,e){let s=yn[t]||[],n=e;for(let o of s)try{let r=await o(n);r!==void 0&&(n=r)}catch(r){process.env.NEX_DEBUG&&console.error(`[plugin] Hook error on ${t}: ${r.message}`)}return n}function t$(){let t=sa.join(process.cwd(),".nex","plugins"),e=[];if(!Mu.existsSync(t))return{loaded:0,errors:[]};let s=Mu.readdirSync(t).filter(o=>o.endsWith(".js")),n={registerTool:Lu,registerHook:Pu,EVENTS:Ls};for(let o of s){let r=sa.join(t,o);try{let i=require(r);if(typeof i=="function")i(n);else if(typeof i.setup=="function")i.setup(n);else{e.push(`${o}: Plugin must export a function or { setup: function }`);continue}ar.push({name:i.name||sa.basename(o,".js"),filePath:r})}catch(i){e.push(`${o}: ${i.message}`)}}return{loaded:ar.length,errors:e}}function n$(){return Ms.map(t=>t.definition)}async function s$(t,e,s={}){let n=Ms.find(a=>a.definition.function.name===t);if(!n)return null;let o=await oa("beforeToolExec",{name:t,args:e,options:s}),r=await n.handler(o.args||e,s);return(await oa("afterToolExec",{name:t,args:e,result:r})).result||r}function o$(){return[...ar]}function r$(){let t={};for(let e of Ls)t[e]=(yn[e]||[]).length;return t}function i$(){ar.length=0,Ms.length=0;for(let t of Object.keys(yn))delete yn[t]}Iu.exports={registerTool:Lu,registerHook:Pu,emit:oa,loadPlugins:t$,getPluginToolDefinitions:n$,executePluginTool:s$,getLoadedPlugins:o$,getHookCounts:r$,clearPlugins:i$,EVENTS:Ls}});var ra=re((Qk,Fu)=>{var{getSkillToolDefinitions:a$}=ea(),{getMCPToolDefinitions:c$}=na(),{getPluginToolDefinitions:l$}=cr(),lr=new Map;function ju(){let{TOOL_DEFINITIONS:t}=ts();return[...t,...a$(),...c$(),...l$()]}function Du(t){if(lr.has(t))return lr.get(t);let s=ju().find(o=>o.function.name===t);if(!s)return null;let n=s.function.parameters;return lr.set(t,n),n}function u$(){lr.clear()}function ur(t,e){if(!t||e.length===0)return null;let s=null,n=1/0;for(let o of e){let r=qu(t.toLowerCase(),o.toLowerCase());r<n&&(n=r,s=o)}return n<=Math.ceil(t.length/2)?s:null}function qu(t,e){let s=t.length,n=e.length,o=Array.from({length:s+1},()=>Array(n+1).fill(0));for(let r=0;r<=s;r++)o[r][0]=r;for(let r=0;r<=n;r++)o[0][r]=r;for(let r=1;r<=s;r++)for(let i=1;i<=n;i++)o[r][i]=t[r-1]===e[i-1]?o[r-1][i-1]:1+Math.min(o[r-1][i],o[r][i-1],o[r-1][i-1]);return o[s][n]}function d$(t,e){let s=Du(t);if(s===null){let d=ju().map(h=>h.function.name),f=ur(t,d);return{valid:!1,error:`Unknown tool "${t}".${f?` Did you mean "${f}"?`:""}
99
+ Available tools: ${d.join(", ")}`}}if(!s||!s.properties)return{valid:!0};let n=s.required||[],o=Object.keys(s.properties),r=Object.keys(e),i=[],a={...e},c=!1;for(let u of n)if(!(u in e)||e[u]===void 0||e[u]===null){let d=ur(u,r);d&&!o.includes(d)?(a[u]=e[d],delete a[d],c=!0):i.push(`Missing required parameter "${u}" (${s.properties[u]?.description||s.properties[u]?.type||"unknown"})`)}new Set(["grep","grep_search","search_files"]).has(t)&&(("-n"in a||"n"in a)&&!o.includes("-n")&&(delete a["-n"],delete a.n,c=!0),("-i"in a||"--ignore-case"in a)&&"ignore_case"in(s.properties||{})&&(a.ignore_case=!0,delete a["-i"],delete a["--ignore-case"],c=!0),("-r"in a||"--recursive"in a)&&(delete a["-r"],delete a["--recursive"],c=!0)),t==="read_file"&&("offset"in a&&!("line_start"in a)&&(a.line_start=a.offset,delete a.offset,c=!0),"start_line"in a&&!("line_start"in a)&&(a.line_start=a.start_line,delete a.start_line,c=!0),"end_line"in a&&!("line_end"in a)&&(a.line_end=a.end_line,delete a.end_line,c=!0));for(let u of Object.keys(a))if(!o.includes(u)){let d=ur(u,o);if(d&&!(d in a))a[d]=a[u],delete a[u],c=!0;else if(!c){let f=d?` Did you mean "${d}"?`:"";i.push(`Unknown parameter "${u}".${f}`)}}for(let u of Object.keys(a)){if(!s.properties[u])continue;let d=s.properties[u].type,f=typeof a[u];d==="string"&&f==="number"?(a[u]=String(a[u]),c=!0):d==="number"&&f==="string"&&!isNaN(a[u])?(a[u]=Number(a[u]),c=!0):d==="boolean"&&f==="string"&&(a[u]=a[u]==="true",c=!0)}return i.length>0&&!c?{valid:!1,error:`Tool "${t}" argument errors:
100
100
  `+i.map(u=>` - ${u}`).join(`
101
101
  `)+`
102
102
 
103
- Expected parameters: ${JSON.stringify(s.properties,null,2)}`}:{valid:!0,corrected:c?a:null}}function Zy(t,e){let s=[],n={...t};if(!n.function&&!n.name)return s.push('Tool call missing both "function" and "name" fields'),{valid:!1,normalized:n,errors:s};if(!n.function&&n.name&&(n.function={name:n.name,arguments:n.arguments||n.args||{}},delete n.name,delete n.args),n.function&&n.function.args!==void 0&&n.function.arguments===void 0&&(n.function.arguments=n.function.args,delete n.function.args),n.function&&(n.function.arguments===void 0||n.function.arguments===null)&&(n.function.arguments={}),n.function&&typeof n.function.arguments=="string"){let o=n.function.arguments;if(o.trim()==="")n.function.arguments={};else try{n.function.arguments=JSON.parse(o)}catch(r){return s.push(`Invalid JSON in arguments${e?` (${e})`:""}: ${r.message}`),{valid:!1,normalized:n,errors:s}}}return n.function&&typeof n.function.arguments!="object"?(s.push(`Arguments must be an object, got ${typeof n.function.arguments}`),{valid:!1,normalized:n,errors:s}):!n.function.name||typeof n.function.name!="string"?(s.push("Tool call function name must be a non-empty string"),{valid:!1,normalized:n,errors:s}):{valid:s.length===0,normalized:n,errors:s}}Eu.exports={validateToolArgs:Jy,validateToolCallFormat:Zy,closestMatch:ar,levenshtein:Su,getCachedSchema:vu,clearSchemaCache:Vy}});var Au=se((Mk,Cu)=>{var{levenshtein:cr}=Ji(),Qy=200,e$=.3,t$=2;function Zi(t){return t.replace(/\r\n/g,`
103
+ Expected parameters: ${JSON.stringify(s.properties,null,2)}`}:{valid:!0,corrected:c?a:null}}function f$(t,e){let s=[],n={...t};if(!n.function&&!n.name)return s.push('Tool call missing both "function" and "name" fields'),{valid:!1,normalized:n,errors:s};if(!n.function&&n.name&&(n.function={name:n.name,arguments:n.arguments||n.args||{}},delete n.name,delete n.args),n.function&&n.function.args!==void 0&&n.function.arguments===void 0&&(n.function.arguments=n.function.args,delete n.function.args),n.function&&(n.function.arguments===void 0||n.function.arguments===null)&&(n.function.arguments={}),n.function&&typeof n.function.arguments=="string"){let o=n.function.arguments;if(o.trim()==="")n.function.arguments={};else try{n.function.arguments=JSON.parse(o)}catch(r){return s.push(`Invalid JSON in arguments${e?` (${e})`:""}: ${r.message}`),{valid:!1,normalized:n,errors:s}}}return n.function&&typeof n.function.arguments!="object"?(s.push(`Arguments must be an object, got ${typeof n.function.arguments}`),{valid:!1,normalized:n,errors:s}):!n.function.name||typeof n.function.name!="string"?(s.push("Tool call function name must be a non-empty string"),{valid:!1,normalized:n,errors:s}):{valid:s.length===0,normalized:n,errors:s}}Fu.exports={validateToolArgs:d$,validateToolCallFormat:f$,closestMatch:ur,levenshtein:qu,getCachedSchema:Du,clearSchemaCache:u$}});var Hu=re((ev,Uu)=>{var{levenshtein:dr}=ra(),p$=200,h$=.3,m$=2;function ia(t){return t.replace(/\r\n/g,`
104
104
  `).replace(/\r/g,`
105
- `).replace(/\t/g," ".repeat(t$)).split(`
105
+ `).replace(/\t/g," ".repeat(m$)).split(`
106
106
  `).map(e=>{let s=e.replace(/\s+$/,""),n=s.match(/^(\s*)(.*)/);if(!n)return s;let[,o,r]=n;return o+r.replace(/ {2,}/g," ")}).join(`
107
- `)}function n$(t,e){if(t.includes(e))return e;if(e.length<10)return null;let s=Zi(t),n=Zi(e);if(!s.includes(n))return null;let o=t.split(`
107
+ `)}function g$(t,e){if(t.includes(e))return e;if(e.length<10)return null;let s=ia(t),n=ia(e);if(!s.includes(n))return null;let o=t.split(`
108
108
  `),r=s.split(`
109
109
  `),i=n.split(`
110
110
  `),a=i[0],c=i[i.length-1];for(let l=0;l<=r.length-i.length;l++){let u=!0;for(let d=0;d<i.length;d++)if(r[l+d]!==i[d]){u=!1;break}if(u)return o.slice(l,l+i.length).join(`
111
- `)}if(i.length===1){for(let l=0;l<r.length;l++)if(r[l].indexOf(n)!==-1)return o[l]}return null}function s$(t,e){if(!t||!e)return null;let s=t.split(`
111
+ `)}if(i.length===1){for(let l=0;l<r.length;l++)if(r[l].indexOf(n)!==-1)return o[l]}return null}function y$(t,e){if(!t||!e)return null;let s=t.split(`
112
112
  `),o=e.split(`
113
- `).length;return s.length===0||o===0?null:o===1?o$(s,e):i$(s,e,o)}function Tu(t){return Math.max(1,Math.floor(t/Qy))}function Ru(t,e){return t<=Math.ceil(e*e$)}function o$(t,e){let s=e.trim(),n=Tu(t.length),o=null,r=1/0;for(let i=0;i<t.length;i+=n){let a=t[i];if(!a.trim())continue;let c=cr(a.trim(),s);c<r&&(r=c,o={text:a,distance:c,line:i+1})}return o&&n>1&&(o=r$(t,s,o,n)||o,r=o.distance),Ru(r,e.length)?o:null}function r$(t,e,s,n){let o=s.line-1,r=Math.max(0,o-n),i=Math.min(t.length-1,o+n),a=s.distance,c=null;for(let l=r;l<=i;l++){let u=t[l];if(!u.trim())continue;let d=cr(u.trim(),e);d<a&&(a=d,c={text:u,distance:d,line:l+1})}return c}function i$(t,e,s){let n=t.length-s+1;if(n<=0)return null;let o=Tu(n),r=null,i=1/0;for(let a=0;a<n;a+=o){let c=t.slice(a,a+s).join(`
114
- `),l=cr(c,e);l<i&&(i=l,r={text:c,distance:l,line:a+1})}return r&&o>1&&(r=a$(t,e,r,o,s,n)||r,i=r.distance),Ru(i,e.length)?r:null}function a$(t,e,s,n,o,r){let i=s.line-1,a=Math.max(0,i-n),c=Math.min(r-1,i+n),l=s.distance,u=null;for(let d=a;d<=c;d++){let f=t.slice(d,d+o).join(`
115
- `),h=cr(f,e);h<l&&(l=h,u={text:f,distance:h,line:d+1})}return u}Cu.exports={normalizeWhitespace:Zi,fuzzyFindText:n$,findMostSimilar:s$}});var Nu=se((Pk,Ou)=>{var{C:Lk}=Ue(),c$=[{name:"OpenAI API Key",regex:/sk-[a-zA-Z0-9]{20,}/i},{name:"Anthropic API Key",regex:/sk-ant-api03-[a-zA-Z0-9-]{90,}/i},{name:"Google Gemini API Key",regex:/AIzaSy[a-zA-Z0-9_-]{30,45}/i},{name:"Slack Token",regex:/xox[bpors]-[a-zA-Z0-9-]+/i},{name:"AWS Access Key",regex:/AKIA[A-Z0-9]{16}/i},{name:"GitHub Token",regex:/ghp_[a-zA-Z0-9]{36}/i},{name:"Private Key",regex:/BEGIN (RSA|EC|DSA|OPENSSH|PGP) PRIVATE KEY/i},{name:"Database URL",regex:/\b(postgres|mongodb|mysql|redis):\/\/[^"'\s]+/i},{name:"Hardcoded Secret",regex:/(password|secret|token|api_key|apikey|api_secret|access_token|auth_token|credentials)\s*[:=]\s*['"'][^'"']{8,}/i}],l$=[{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 u$(t,e){let s=e.split(`
116
- `),n=[],o=t?`.${t.split(".").pop()}`:"";for(let r=0;r<s.length;r++){let i=s[r],a=r+1;for(let c of c$)c.regex.test(i)&&n.push({line:a,message:`Potential secret detected: ${c.name}`,severity:"error"});for(let c of l$)c.ext&&!c.ext.includes(o)||c.regex.test(i)&&n.push({line:a,message:c.message||`Found ${c.name}`,severity:c.severity||"warn"})}return s.length>500&&n.push({line:0,message:`Large file detected (${s.length} lines). Consider refactoring.`,severity:"info"}),n}function d$(){let t=process.memoryUsage();return{rss:Math.round(t.rss/1024/1024*100)/100,heapUsed:Math.round(t.heapUsed/1024/1024*100)/100}}Ou.exports={runDiagnostics:u$,getMemoryUsage:d$}});var sa=se((Ik,Du)=>{var Zn=require("fs").promises,Qn=require("path"),{exec:f$}=require("util").promisify(require("child_process").exec),es=[],na=null,lr=!1,ea=0,p$=6e4;function Lu(t){return!(es.length===0||na!==t||Date.now()-ea>p$)}async function Pu(t){if(!lr&&!Lu(t)){lr=!0,na=t;try{try{let{stdout:n}=await f$("rg --files",{cwd:t,timeout:5e3});es=n.split(`
117
- `).filter(Boolean),ea=Date.now(),lr=!1;return}catch{}let e=[],s=async(n,o)=>{let r;try{r=await Zn.readdir(n,{withFileTypes:!0})}catch{return}for(let i of r){if(i.name==="node_modules"||i.name===".git"||i.name.startsWith("."))continue;let a=o?`${o}/${i.name}`:i.name;i.isDirectory()?await s(Qn.join(n,i.name),a):e.push(a)}};await s(t,""),es=e,ea=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{lr=!1}}}function ta(){return es}function h$(){return na}function m$(t){return es.filter(e=>Qn.basename(e)===t)}function g$(t){let e=t.toLowerCase();return es.filter(s=>s.toLowerCase().includes(e)).slice(0,20)}var Qi=null,Mu=0,y$=12e4,$$=new Set([".js",".ts",".jsx",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".rb"]);function Iu(t,e){let s=[],n=t.split(`
118
- `);for(let o=0;o<n.length;o++){let r=n[o],i=o+1;if([".js",".ts",".jsx",".tsx",".mjs",".cjs"].includes(e)){let a=r.match(/(?:export\s+)?(?:async\s+)?function\s+(\w+)/);a&&s.push({type:"function",name:a[1],line:i});let c=r.match(/(?:export\s+)?class\s+(\w+)/);c&&s.push({type:"class",name:c[1],line:i});let l=r.match(/(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?(?:\([^)]*\)|[\w$]+)\s*=>/);l&&s.push({type:"function",name:l[1],line:i});let u=r.match(/module\.exports\s*=\s*\{([^}]+)\}/);if(u){let f=u[1].split(",").map(h=>h.trim().split(":")[0].trim()).filter(Boolean);for(let h of f)/^\w+$/.test(h)&&s.push({type:"export",name:h,line:i})}let d=r.match(/(?:require\(['"]([^'"]+)['"]\)|from\s+['"]([^'"]+)['"])/);if(d){let f=d[1]||d[2];s.push({type:"import",name:f,line:i})}}if(e===".py"){let a=r.match(/^(?:async\s+)?def\s+(\w+)/);a&&s.push({type:"function",name:a[1],line:i});let c=r.match(/^class\s+(\w+)/);c&&s.push({type:"class",name:c[1],line:i});let l=r.match(/^(?:from\s+(\S+)\s+)?import\s+(\S+)/);l&&s.push({type:"import",name:l[1]||l[2],line:i})}if(e===".go"){let a=r.match(/^func\s+(?:\([^)]+\)\s+)?(\w+)/);a&&s.push({type:"function",name:a[1],line:i});let c=r.match(/^type\s+(\w+)\s+struct/);c&&s.push({type:"class",name:c[1],line:i})}}return s}async function ju(t){t=t||process.cwd();let e=Qn.join(t,".nex","index","content-index.json"),s={};if(Qi&&Date.now()-Mu<y$)return Qi;try{let i=await Zn.readFile(e,"utf-8");s=JSON.parse(i)}catch{s={files:{}}}ta().length===0&&await Pu(t);let o={files:{}},r=!1;for(let i of ta()){let a=Qn.extname(i);if(!$$.has(a))continue;let c=Qn.join(t,i);try{let u=(await Zn.stat(c)).mtimeMs;if(s.files[i]&&s.files[i].mtime===u){o.files[i]=s.files[i];continue}let d=await Zn.readFile(c,"utf-8"),f=Iu(d,a);o.files[i]={defs:f,mtime:u},r=!0}catch{}}if(r){let i=Qn.join(t,".nex","index");await Zn.mkdir(i,{recursive:!0}),await Zn.writeFile(e,JSON.stringify(o),"utf-8")}return Qi=o,Mu=Date.now(),o}async function w$(t,e){let s=await ju(),n=[],o=t.toLowerCase();for(let[r,i]of Object.entries(s.files))for(let a of i.defs)e&&a.type!==e||a.name.toLowerCase().includes(o)&&n.push({file:r,type:a.type,name:a.name,line:a.line});return n.sort((r,i)=>{let a=r.name.toLowerCase()===o?0:1,c=i.name.toLowerCase()===o?0:1;if(a!==c)return a-c;let l=r.name.toLowerCase().startsWith(o)?0:1,u=i.name.toLowerCase().startsWith(o)?0:1;return l-u}),n.slice(0,50)}Du.exports={refreshIndex:Pu,getFileIndex:ta,getIndexedCwd:h$,findFileInIndex:m$,searchIndex:g$,isIndexValid:Lu,buildContentIndex:ju,searchContentIndex:w$,extractDefinitions:Iu}});var ra=se((jk,Wu)=>{var ur=require("fs"),fr=require("path"),pr=require("os"),{execFile:b$}=require("child_process"),{promisify:_$}=require("util"),oa=_$(b$),x$=fr.join(pr.homedir(),".nex","servers.json"),dr=fr.join(pr.tmpdir(),"nex-ssh-sockets");function k$(){return fr.join(process.cwd(),".nex","servers.json")}function qu(){let t=n=>{if(!ur.existsSync(n))return{};try{return JSON.parse(ur.readFileSync(n,"utf-8"))}catch{return{}}},e=t(x$),s=t(k$());return{...e,...s}}function v$(t){let e=qu();if(e[t])return{...e[t],_name:t};if(/^[\w.-]+@[\w.-]+$/.test(t)||/[\w-]+\.[\w.-]+/.test(t)||t==="localhost"){let[o,r]=t.includes("@")?t.split("@"):[void 0,t];return{host:r,user:o}}let s=Object.keys(e),n=s.length?`Available profiles: ${s.join(", ")}`:"No profiles configured. Create .nex/servers.json (project) or ~/.nex/servers.json (global)";throw new Error(`Unknown server: "${t}". ${n}`)}function S$(){ur.existsSync(dr)||ur.mkdirSync(dr,{recursive:!0})}function Fu(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-o","ServerAliveInterval=30"];t.key&&e.push("-i",t.key.replace(/^~/,pr.homedir())),t.port&&Number(t.port)!==22&&e.push("-p",String(t.port)),S$();let s=t.user?`${t.user}@${t.host}`:t.host,n=fr.join(dr,s.replace(/[@.:]/g,"_"));return e.push("-o","ControlMaster=auto","-o",`ControlPath=${n}`,"-o","ControlPersist=120"),e.push(s),{args:e,target:s}}function Bu(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-r"];return t.key&&e.push("-i",t.key.replace(/^~/,pr.homedir())),t.port&&Number(t.port)!==22&&e.push("-P",String(t.port)),e}async function E$(t,e,{timeout:s=3e4,sudo:n=!1}={}){let{args:o}=Fu(t),r=n&&t.sudo?`sudo sh -c ${JSON.stringify(e)}`:e;try{let{stdout:i,stderr:a}=await oa("ssh",[...o,r],{timeout:s,maxBuffer:4194304});return{stdout:i||"",stderr:a||"",exitCode:0}}catch(i){let a=typeof i.code=="number"?i.code:1,c=(i.stderr||i.message||"").toString();return{stdout:(i.stdout||"").toString(),stderr:c,exitCode:a,error:hr(c,t)}}}async function T$(t,e,s,{timeout:n=12e4}={}){let o=Bu(t),r=t.user?`${t.user}@${t.host}`:t.host;o.push(e,`${r}:${s}`);try{let{stdout:i,stderr:a}=await oa("scp",o,{timeout:n,maxBuffer:1048576});return i||a||`Uploaded ${e} \u2192 ${r}:${s}`}catch(i){let a=(i.stderr||i.message||"").toString();throw new Error(hr(a,t)||a)}}async function R$(t,e,s,{timeout:n=12e4}={}){let o=Bu(t),r=t.user?`${t.user}@${t.host}`:t.host;o.push(`${r}:${e}`,s);try{let{stdout:i,stderr:a}=await oa("scp",o,{timeout:n,maxBuffer:1048576});return i||a||`Downloaded ${r}:${e} \u2192 ${s}`}catch(i){let a=(i.stderr||i.message||"").toString();throw new Error(hr(a,t)||a)}}function hr(t,e){if(!t)return"";if(/connection refused/i.test(t)){let s=e.port||22;return`${t}
113
+ `).length;return s.length===0||o===0?null:o===1?$$(s,e):b$(s,e,o)}function Bu(t){return Math.max(1,Math.floor(t/p$))}function Wu(t,e){return t<=Math.ceil(e*h$)}function $$(t,e){let s=e.trim(),n=Bu(t.length),o=null,r=1/0;for(let i=0;i<t.length;i+=n){let a=t[i];if(!a.trim())continue;let c=dr(a.trim(),s);c<r&&(r=c,o={text:a,distance:c,line:i+1})}return o&&n>1&&(o=w$(t,s,o,n)||o,r=o.distance),Wu(r,e.length)?o:null}function w$(t,e,s,n){let o=s.line-1,r=Math.max(0,o-n),i=Math.min(t.length-1,o+n),a=s.distance,c=null;for(let l=r;l<=i;l++){let u=t[l];if(!u.trim())continue;let d=dr(u.trim(),e);d<a&&(a=d,c={text:u,distance:d,line:l+1})}return c}function b$(t,e,s){let n=t.length-s+1;if(n<=0)return null;let o=Bu(n),r=null,i=1/0;for(let a=0;a<n;a+=o){let c=t.slice(a,a+s).join(`
114
+ `),l=dr(c,e);l<i&&(i=l,r={text:c,distance:l,line:a+1})}return r&&o>1&&(r=_$(t,e,r,o,s,n)||r,i=r.distance),Wu(i,e.length)?r:null}function _$(t,e,s,n,o,r){let i=s.line-1,a=Math.max(0,i-n),c=Math.min(r-1,i+n),l=s.distance,u=null;for(let d=a;d<=c;d++){let f=t.slice(d,d+o).join(`
115
+ `),h=dr(f,e);h<l&&(l=h,u={text:f,distance:h,line:d+1})}return u}Uu.exports={normalizeWhitespace:ia,fuzzyFindText:g$,findMostSimilar:y$}});var Gu=re((nv,Yu)=>{var{C:tv}=He(),x$=[{name:"OpenAI API Key",regex:/sk-[a-zA-Z0-9]{20,}/i},{name:"Anthropic API Key",regex:/sk-ant-api03-[a-zA-Z0-9-]{90,}/i},{name:"Google Gemini API Key",regex:/AIzaSy[a-zA-Z0-9_-]{30,45}/i},{name:"Slack Token",regex:/xox[bpors]-[a-zA-Z0-9-]+/i},{name:"AWS Access Key",regex:/AKIA[A-Z0-9]{16}/i},{name:"GitHub Token",regex:/ghp_[a-zA-Z0-9]{36}/i},{name:"Private Key",regex:/BEGIN (RSA|EC|DSA|OPENSSH|PGP) PRIVATE KEY/i},{name:"Database URL",regex:/\b(postgres|mongodb|mysql|redis):\/\/[^"'\s]+/i},{name:"Hardcoded Secret",regex:/(password|secret|token|api_key|apikey|api_secret|access_token|auth_token|credentials)\s*[:=]\s*['"'][^'"']{8,}/i}],k$=[{name:"TODO",regex:/\bTODO\b/i,severity:"warn"},{name:"FIXME",regex:/\bFIXME\b/i,severity:"warn"},{name:"Debugger",regex:/\bdebugger\b/,severity:"error",ext:[".js",".ts",".jsx",".tsx"]},{name:"eval()",regex:/\beval\s*\(/,severity:"warn",ext:[".js",".ts",".jsx",".tsx"]},{name:"Console Log",regex:/\bconsole\.log\(/,severity:"info",ext:[".js",".ts",".jsx",".tsx"]},{name:"ANSI Code",regex:/\\x1b\[[0-9;]*m/,severity:"warn",message:"Avoid hardcoded ANSI codes; use cli/ui.js instead."}];function v$(t,e){let s=e.split(`
116
+ `),n=[],o=t?`.${t.split(".").pop()}`:"";for(let r=0;r<s.length;r++){let i=s[r],a=r+1;for(let c of x$)c.regex.test(i)&&n.push({line:a,message:`Potential secret detected: ${c.name}`,severity:"error"});for(let c of k$)c.ext&&!c.ext.includes(o)||c.regex.test(i)&&n.push({line:a,message:c.message||`Found ${c.name}`,severity:c.severity||"warn"})}return s.length>500&&n.push({line:0,message:`Large file detected (${s.length} lines). Consider refactoring.`,severity:"info"}),n}function S$(){let t=process.memoryUsage();return{rss:Math.round(t.rss/1024/1024*100)/100,heapUsed:Math.round(t.heapUsed/1024/1024*100)/100}}Yu.exports={runDiagnostics:v$,getMemoryUsage:S$}});var da=re((sv,Zu)=>{var ns=require("fs").promises,ss=require("path"),{exec:E$}=require("util").promisify(require("child_process").exec),os=[],ua=null,fr=!1,ca=0,T$=6e4;function zu(t){return!(os.length===0||ua!==t||Date.now()-ca>T$)}async function Xu(t){if(!fr&&!zu(t)){fr=!0,ua=t;try{try{let{stdout:n}=await E$("rg --files",{cwd:t,timeout:5e3});os=n.split(`
117
+ `).filter(Boolean),ca=Date.now(),fr=!1;return}catch{}let e=[],s=async(n,o)=>{let r;try{r=await ns.readdir(n,{withFileTypes:!0})}catch{return}for(let i of r){if(i.name==="node_modules"||i.name===".git"||i.name.startsWith("."))continue;let a=o?`${o}/${i.name}`:i.name;i.isDirectory()?await s(ss.join(n,i.name),a):e.push(a)}};await s(t,""),os=e,ca=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{fr=!1}}}function la(){return os}function R$(){return ua}function C$(t){return os.filter(e=>ss.basename(e)===t)}function A$(t){let e=t.toLowerCase();return os.filter(s=>s.toLowerCase().includes(e)).slice(0,20)}var aa=null,Ku=0,O$=12e4,N$=new Set([".js",".ts",".jsx",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".rb"]);function Vu(t,e){let s=[],n=t.split(`
118
+ `);for(let o=0;o<n.length;o++){let r=n[o],i=o+1;if([".js",".ts",".jsx",".tsx",".mjs",".cjs"].includes(e)){let a=r.match(/(?:export\s+)?(?:async\s+)?function\s+(\w+)/);a&&s.push({type:"function",name:a[1],line:i});let c=r.match(/(?:export\s+)?class\s+(\w+)/);c&&s.push({type:"class",name:c[1],line:i});let l=r.match(/(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?(?:\([^)]*\)|[\w$]+)\s*=>/);l&&s.push({type:"function",name:l[1],line:i});let u=r.match(/module\.exports\s*=\s*\{([^}]+)\}/);if(u){let f=u[1].split(",").map(h=>h.trim().split(":")[0].trim()).filter(Boolean);for(let h of f)/^\w+$/.test(h)&&s.push({type:"export",name:h,line:i})}let d=r.match(/(?:require\(['"]([^'"]+)['"]\)|from\s+['"]([^'"]+)['"])/);if(d){let f=d[1]||d[2];s.push({type:"import",name:f,line:i})}}if(e===".py"){let a=r.match(/^(?:async\s+)?def\s+(\w+)/);a&&s.push({type:"function",name:a[1],line:i});let c=r.match(/^class\s+(\w+)/);c&&s.push({type:"class",name:c[1],line:i});let l=r.match(/^(?:from\s+(\S+)\s+)?import\s+(\S+)/);l&&s.push({type:"import",name:l[1]||l[2],line:i})}if(e===".go"){let a=r.match(/^func\s+(?:\([^)]+\)\s+)?(\w+)/);a&&s.push({type:"function",name:a[1],line:i});let c=r.match(/^type\s+(\w+)\s+struct/);c&&s.push({type:"class",name:c[1],line:i})}}return s}async function Ju(t){t=t||process.cwd();let e=ss.join(t,".nex","index","content-index.json"),s={};if(aa&&Date.now()-Ku<O$)return aa;try{let i=await ns.readFile(e,"utf-8");s=JSON.parse(i)}catch{s={files:{}}}la().length===0&&await Xu(t);let o={files:{}},r=!1;for(let i of la()){let a=ss.extname(i);if(!N$.has(a))continue;let c=ss.join(t,i);try{let u=(await ns.stat(c)).mtimeMs;if(s.files[i]&&s.files[i].mtime===u){o.files[i]=s.files[i];continue}let d=await ns.readFile(c,"utf-8"),f=Vu(d,a);o.files[i]={defs:f,mtime:u},r=!0}catch{}}if(r){let i=ss.join(t,".nex","index");await ns.mkdir(i,{recursive:!0}),await ns.writeFile(e,JSON.stringify(o),"utf-8")}return aa=o,Ku=Date.now(),o}async function M$(t,e){let s=await Ju(),n=[],o=t.toLowerCase();for(let[r,i]of Object.entries(s.files))for(let a of i.defs)e&&a.type!==e||a.name.toLowerCase().includes(o)&&n.push({file:r,type:a.type,name:a.name,line:a.line});return n.sort((r,i)=>{let a=r.name.toLowerCase()===o?0:1,c=i.name.toLowerCase()===o?0:1;if(a!==c)return a-c;let l=r.name.toLowerCase().startsWith(o)?0:1,u=i.name.toLowerCase().startsWith(o)?0:1;return l-u}),n.slice(0,50)}Zu.exports={refreshIndex:Xu,getFileIndex:la,getIndexedCwd:R$,findFileInIndex:C$,searchIndex:A$,isIndexValid:zu,buildContentIndex:Ju,searchContentIndex:M$,extractDefinitions:Vu}});var pa=re((ov,nd)=>{var pr=require("fs"),mr=require("path"),gr=require("os"),{execFile:L$}=require("child_process"),{promisify:P$}=require("util"),fa=P$(L$),I$=mr.join(gr.homedir(),".nex","servers.json"),hr=mr.join(gr.tmpdir(),"nex-ssh-sockets");function j$(){return mr.join(process.cwd(),".nex","servers.json")}function Qu(){let t=n=>{if(!pr.existsSync(n))return{};try{return JSON.parse(pr.readFileSync(n,"utf-8"))}catch{return{}}},e=t(I$),s=t(j$());return{...e,...s}}function D$(t){let e=Qu();if(e[t])return{...e[t],_name:t};if(/^[\w.-]+@[\w.-]+$/.test(t)||/[\w-]+\.[\w.-]+/.test(t)||t==="localhost"){let[o,r]=t.includes("@")?t.split("@"):[void 0,t];return{host:r,user:o}}let s=Object.keys(e),n=s.length?`Available profiles: ${s.join(", ")}`:"No profiles configured. Create .nex/servers.json (project) or ~/.nex/servers.json (global)";throw new Error(`Unknown server: "${t}". ${n}`)}function q$(){pr.existsSync(hr)||pr.mkdirSync(hr,{recursive:!0})}function ed(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-o","ServerAliveInterval=30"];t.key&&e.push("-i",t.key.replace(/^~/,gr.homedir())),t.port&&Number(t.port)!==22&&e.push("-p",String(t.port)),q$();let s=t.user?`${t.user}@${t.host}`:t.host,n=mr.join(hr,s.replace(/[@.:]/g,"_"));return e.push("-o","ControlMaster=auto","-o",`ControlPath=${n}`,"-o","ControlPersist=120"),e.push(s),{args:e,target:s}}function td(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-r"];return t.key&&e.push("-i",t.key.replace(/^~/,gr.homedir())),t.port&&Number(t.port)!==22&&e.push("-P",String(t.port)),e}async function F$(t,e,{timeout:s=3e4,sudo:n=!1}={}){let{args:o}=ed(t),r=n&&t.sudo?`sudo sh -c ${JSON.stringify(e)}`:e;try{let{stdout:i,stderr:a}=await fa("ssh",[...o,r],{timeout:s,maxBuffer:4194304});return{stdout:i||"",stderr:a||"",exitCode:0}}catch(i){let a=typeof i.code=="number"?i.code:1,c=(i.stderr||i.message||"").toString();return{stdout:(i.stdout||"").toString(),stderr:c,exitCode:a,error:yr(c,t)}}}async function B$(t,e,s,{timeout:n=12e4}={}){let o=td(t),r=t.user?`${t.user}@${t.host}`:t.host;o.push(e,`${r}:${s}`);try{let{stdout:i,stderr:a}=await fa("scp",o,{timeout:n,maxBuffer:1048576});return i||a||`Uploaded ${e} \u2192 ${r}:${s}`}catch(i){let a=(i.stderr||i.message||"").toString();throw new Error(yr(a,t)||a)}}async function W$(t,e,s,{timeout:n=12e4}={}){let o=td(t),r=t.user?`${t.user}@${t.host}`:t.host;o.push(`${r}:${e}`,s);try{let{stdout:i,stderr:a}=await fa("scp",o,{timeout:n,maxBuffer:1048576});return i||a||`Downloaded ${r}:${e} \u2192 ${s}`}catch(i){let a=(i.stderr||i.message||"").toString();throw new Error(yr(a,t)||a)}}function yr(t,e){if(!t)return"";if(/connection refused/i.test(t)){let s=e.port||22;return`${t}
119
119
  HINT: Connection refused on ${e.host}:${s}. Check: server is running, SSH service is active (systemctl status sshd), firewall allows port ${s} (firewall-cmd --list-ports).`}if(/permission denied/i.test(t)){let s=e.key?`key: ${e.key}`:"SSH agent";return`${t}
120
120
  HINT: Auth failed using ${s} as user "${e.user||"root"}". Check: authorized_keys on server, correct username, key passphrase.`}return/no route to host|network unreachable|name or service not known/i.test(t)?`${t}
121
121
  HINT: Cannot reach ${e.host}. Check: network connection, correct hostname/IP, DNS resolution.`:/host key verification failed/i.test(t)?`${t}
122
122
  HINT: Host key changed for ${e.host}. To reset: ssh-keygen -R ${e.host}`:/timed out/i.test(t)?`${t}
123
123
  HINT: Connection timed out to ${e.host}. Check firewall rules and network connectivity.`:/too many authentication failures/i.test(t)?`${t}
124
- HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function C$(t,e){let s=e.user?`${e.user}@${e.host}`:e.host,n=e.port&&Number(e.port)!==22?`:${e.port}`:"",o=e.os?` [${e.os}]`:"",r=e.key?` key:${e.key}`:"",i=e.sudo?" sudo:yes":"";return`${t}: ${s}${n}${o}${r}${i}`}Wu.exports={loadServerProfiles:qu,resolveProfile:v$,buildSSHArgs:Fu,sshExec:E$,scpUpload:T$,scpDownload:R$,enrichSSHError:hr,formatProfile:C$,SSH_SOCKET_DIR:dr}});var Gu=se((Dk,Hu)=>{var Ns=require("fs"),ia=require("path"),A$=ia.join(".nex","deploy.json");function aa(){return ia.join(process.cwd(),A$)}function Uu(){let t=aa();if(!Ns.existsSync(t))return{};try{return JSON.parse(Ns.readFileSync(t,"utf-8"))}catch{return{}}}function O$(t){let e=Uu();if(e[t])return{...e[t],_name:t};let s=Object.keys(e),n=s.length?`Available: ${s.join(", ")}`:"No deploy configs found. Create .nex/deploy.json or use explicit params.";throw new Error(`Unknown deploy config: "${t}". ${n}`)}function N$(t){let e=ia.join(process.cwd(),".nex");Ns.existsSync(e)||Ns.mkdirSync(e,{recursive:!0}),Ns.writeFileSync(aa(),JSON.stringify(t,null,2)+`
125
- `,"utf-8")}Hu.exports={loadDeployConfigs:Uu,resolveDeployConfig:O$,saveDeployConfigs:N$,getDeployConfigPath:aa}});var Is=se((qk,zu)=>{var{getActiveModel:M$,getActiveProviderName:L$}=He(),Ms={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},Ls={"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"},Ps={ollama:"full",openai:"full",anthropic:"full",gemini:"full",local:"essential"},Lt={};function Ku(){try{let t=require("fs"),s=require("path").join(process.cwd(),".nex","config.json");t.existsSync(s)&&(Lt=JSON.parse(t.readFileSync(s,"utf-8")).toolTiers||{})}catch{Lt={}}}Ku();function ca(){let e=M$()?.id,s=L$();return e&&Lt[e]?Lt[e]:s&&Lt[`${s}:*`]?Lt[`${s}:*`]:e&&Ls[e]?Ls[e]:s&&Ps[s]?Ps[s]:"full"}var P$=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"]),Yu={anthropic:"strict",openai:"strict",gemini:"strict",ollama:"fuzzy",local:"fuzzy"};function I$(t,e){return t&&(P$.has(t)||t.startsWith("claude-"))?"strict":e&&Yu[e]?Yu[e]:"fuzzy"}function j$(t,e){return t&&Lt[t]?Lt[t]:e&&Lt[`${e}:*`]?Lt[`${e}:*`]:t&&Ls[t]?Ls[t]:e&&Ps[e]?Ps[e]:"full"}function D$(t,e){let s=e||ca();if(s==="full"||!Ms[s])return t;let n=new Set(Ms[s]);return t.filter(o=>n.has(o.function.name))}function q$(){let t=ca(),e=Ms[t]?Ms[t].length:"all";return{tier:t,toolCount:e}}zu.exports={filterToolsForModel:D$,getActiveTier:ca,getModelTier:j$,getEditMode:I$,getTierInfo:q$,TIERS:Ms,MODEL_TIERS:Ls,PROVIDER_DEFAULT_TIER:Ps,loadConfigOverrides:Ku}});var Ds=se((Fk,Ju)=>{var la=null,Ht=null,js=null,Xu=`Playwright is not installed. Install with:
124
+ HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function U$(t,e){let s=e.user?`${e.user}@${e.host}`:e.host,n=e.port&&Number(e.port)!==22?`:${e.port}`:"",o=e.os?` [${e.os}]`:"",r=e.key?` key:${e.key}`:"",i=e.sudo?" sudo:yes":"";return`${t}: ${s}${n}${o}${r}${i}`}nd.exports={loadServerProfiles:Qu,resolveProfile:D$,buildSSHArgs:ed,sshExec:F$,scpUpload:B$,scpDownload:W$,enrichSSHError:yr,formatProfile:U$,SSH_SOCKET_DIR:hr}});var rd=re((rv,od)=>{var Ps=require("fs"),ha=require("path"),H$=ha.join(".nex","deploy.json");function ma(){return ha.join(process.cwd(),H$)}function sd(){let t=ma();if(!Ps.existsSync(t))return{};try{return JSON.parse(Ps.readFileSync(t,"utf-8"))}catch{return{}}}function Y$(t){let e=sd();if(e[t])return{...e[t],_name:t};let s=Object.keys(e),n=s.length?`Available: ${s.join(", ")}`:"No deploy configs found. Create .nex/deploy.json or use explicit params.";throw new Error(`Unknown deploy config: "${t}". ${n}`)}function G$(t){let e=ha.join(process.cwd(),".nex");Ps.existsSync(e)||Ps.mkdirSync(e,{recursive:!0}),Ps.writeFileSync(ma(),JSON.stringify(t,null,2)+`
125
+ `,"utf-8")}od.exports={loadDeployConfigs:sd,resolveDeployConfig:Y$,saveDeployConfigs:G$,getDeployConfigPath:ma}});var qs=re((iv,cd)=>{var{getActiveModel:K$,getActiveProviderName:z$}=Ge(),Is={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},js={"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"},Ds={ollama:"full",openai:"full",anthropic:"full",gemini:"full",local:"essential"},Pt={};function ad(){try{let t=require("fs"),s=require("path").join(process.cwd(),".nex","config.json");t.existsSync(s)&&(Pt=JSON.parse(t.readFileSync(s,"utf-8")).toolTiers||{})}catch{Pt={}}}ad();function ga(){let e=K$()?.id,s=z$();return e&&Pt[e]?Pt[e]:s&&Pt[`${s}:*`]?Pt[`${s}:*`]:e&&js[e]?js[e]:s&&Ds[s]?Ds[s]:"full"}var X$=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"]),id={anthropic:"strict",openai:"strict",gemini:"strict",ollama:"fuzzy",local:"fuzzy"};function V$(t,e){return t&&(X$.has(t)||t.startsWith("claude-"))?"strict":e&&id[e]?id[e]:"fuzzy"}function J$(t,e){return t&&Pt[t]?Pt[t]:e&&Pt[`${e}:*`]?Pt[`${e}:*`]:t&&js[t]?js[t]:e&&Ds[e]?Ds[e]:"full"}function Z$(t,e){let s=e||ga();if(s==="full"||!Is[s])return t;let n=new Set(Is[s]);return t.filter(o=>n.has(o.function.name))}function Q$(){let t=ga(),e=Is[t]?Is[t].length:"all";return{tier:t,toolCount:e}}cd.exports={filterToolsForModel:Z$,getActiveTier:ga,getModelTier:J$,getEditMode:V$,getTierInfo:Q$,TIERS:Is,MODEL_TIERS:js,PROVIDER_DEFAULT_TIER:Ds,loadConfigOverrides:ad}});var Bs=re((av,dd)=>{var ya=null,Yt=null,Fs=null,ld=`Playwright is not installed. Install with:
126
126
  npm install playwright && npx playwright install chromium
127
- Then restart nex-code.`;function Vu(){if(js!==null)return js;try{require("playwright"),js=!0}catch{js=!1}return js}async function mr(){if(!Vu())throw new Error(Xu);return la||(la=require("playwright")),(!Ht||!Ht.isConnected())&&(Ht=await la.chromium.launch({headless:!0})),Ht}async function F$(){if(Ht){try{await Ht.close()}catch{}Ht=null}}process.on("exit",()=>{if(Ht)try{Ht.close()}catch{}});async function B$(t,{timeout:e=3e4,waitFor:s="domcontentloaded"}={}){let o=await(await mr()).newPage();try{await o.goto(t,{waitUntil:s,timeout:e});let r=await o.title(),i=await o.evaluate(()=>(document.querySelectorAll("script,style,nav,footer,header,aside,[role=navigation]").forEach(l=>l.remove()),document.body?.innerText||"")),a=await o.evaluate(()=>Array.from(document.querySelectorAll("a[href]")).slice(0,30).map(c=>({text:(c.innerText||c.textContent||"").trim().substring(0,80),href:c.href})).filter(c=>c.text&&c.href&&!c.href.startsWith("javascript:")));return{title:r,url:o.url(),text:i.substring(0,8e3)+(i.length>8e3?`
128
- ...(truncated)`:""),links:a.slice(0,20)}}finally{await o.close()}}async function W$(t,{width:e=1280,height:s=800,fullPage:n=!1,timeout:o=3e4}={}){let i=await(await mr()).newPage();try{await i.setViewportSize({width:e,height:s}),await i.goto(t,{waitUntil:"networkidle",timeout:o});let a=await i.screenshot({type:"png",fullPage:n}),c=require("os"),l=require("path"),u=require("fs"),d=l.join(c.tmpdir(),`nex-screenshot-${Date.now()}.png`);return u.writeFileSync(d,a),{path:d,base64:a.toString("base64"),media_type:"image/png",title:await i.title(),url:i.url()}}finally{await i.close()}}async function U$(t,{selector:e,text:s,timeout:n=3e4}={}){if(!e&&!s)throw new Error("selector or text is required");let r=await(await mr()).newPage();try{await r.goto(t,{waitUntil:"domcontentloaded",timeout:n}),s?await r.getByText(s,{exact:!1}).first().click({timeout:1e4}):await r.locator(e).first().click({timeout:1e4}),await r.waitForLoadState("domcontentloaded");let i=await r.title();return`Clicked \u2014 now at: ${r.url()} (${i})`}finally{await r.close()}}async function H$(t,{selector:e,value:s,submit:n=!1,timeout:o=3e4}={}){if(!e||s===void 0)throw new Error("selector and value are required");let i=await(await mr()).newPage();try{return await i.goto(t,{waitUntil:"domcontentloaded",timeout:o}),await i.fill(e,String(s)),n&&(await i.keyboard.press("Enter"),await i.waitForLoadState("domcontentloaded")),`Filled "${e}" with value. ${n?`Submitted \u2192 ${i.url()}`:"Not submitted."}`}finally{await i.close()}}Ju.exports={isPlaywrightAvailable:Vu,browserNavigate:B$,browserScreenshot:W$,browserClick:U$,browserFill:H$,closeBrowser:F$,INSTALL_MSG:Xu}});var ua=se((Bk,Zu)=>{var{C:Oe}=Ue(),Fs="",et=[],qs=0,mn=null;function G$(t){mn=t}function Y$(t,e){Fs=t,et=[],qs=0;for(let n of e){qs++;let o=`t${qs}`;et.push({id:o,description:n.description||n.title||n.name||n.task||`Task ${qs}`,status:"pending",dependsOn:n.depends_on||[],result:null})}let s=et.map(n=>({...n}));return mn&&mn("create",{name:t,tasks:s}),s}function K$(t,e,s){let n=et.find(o=>o.id===t);return n?(n.status=e,s!==void 0&&(n.result=s),mn&&mn("update",{id:t,status:e,result:s}),{...n}):null}function z$(){return{name:Fs,tasks:et.map(t=>({...t}))}}function X$(){Fs="",et=[],qs=0,mn&&mn("clear",{})}function V$(){return et.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let s=et.find(n=>n.id===e);return s&&s.status==="done"}))}function J$(){if(et.length===0)return`${Oe.dim}No active tasks${Oe.reset}`;let t=[];Fs&&(t.push(` ${Oe.bold}${Oe.cyan}Tasks: ${Fs}${Oe.reset}`),t.push(` ${Oe.dim}${"\u2500".repeat(40)}${Oe.reset}`));for(let o of et){let r,i;switch(o.status){case"done":r="\u2713",i=Oe.green;break;case"in_progress":r="\u2192",i=Oe.cyan;break;case"failed":r="\u2717",i=Oe.red;break;default:r="\xB7",i=Oe.dim}let a=o.dependsOn.length>0?` ${Oe.dim}(after: ${o.dependsOn.join(", ")})${Oe.reset}`:"",c=`[${o.status}]`,l=o.description.length>50?o.description.substring(0,47)+"...":o.description;if(t.push(` ${i}${r}${Oe.reset} ${Oe.bold}${o.id}${Oe.reset} ${l.padEnd(40)} ${i}${c}${Oe.reset}${a}`),o.result&&o.status==="done"){let u=o.result.length>60?o.result.substring(0,57)+"...":o.result;t.push(` ${Oe.dim}\u2192 ${u}${Oe.reset}`)}}let e=et.filter(o=>o.status==="done").length,s=et.filter(o=>o.status==="failed").length,n=et.length;return t.push(` ${Oe.dim}${"\u2500".repeat(40)}${Oe.reset}`),t.push(` ${Oe.dim}${e}/${n} done${s>0?`, ${s} failed`:""}${Oe.reset}`),t.join(`
129
- `)}function Z$(){return et.length>0&&et.some(t=>t.status==="pending"||t.status==="in_progress")}Zu.exports={createTasks:Y$,updateTask:K$,getTaskList:z$,clearTasks:X$,getReadyTasks:V$,renderTaskList:J$,setOnChange:G$,hasActiveTasks:Z$}});var gr=se((Wk,ed)=>{var Bs={"devstral-2":{staleWarn:3e4,staleAbort:9e4,investigationCap:12,postEditCap:10,briefing:`You are devstral-2, a strong coding model optimized for agentic tasks.
127
+ Then restart nex-code.`;function ud(){if(Fs!==null)return Fs;try{require("playwright"),Fs=!0}catch{Fs=!1}return Fs}async function $r(){if(!ud())throw new Error(ld);return ya||(ya=require("playwright")),(!Yt||!Yt.isConnected())&&(Yt=await ya.chromium.launch({headless:!0})),Yt}async function ew(){if(Yt){try{await Yt.close()}catch{}Yt=null}}process.on("exit",()=>{if(Yt)try{Yt.close()}catch{}});async function tw(t,{timeout:e=3e4,waitFor:s="domcontentloaded"}={}){let o=await(await $r()).newPage();try{await o.goto(t,{waitUntil:s,timeout:e});let r=await o.title(),i=await o.evaluate(()=>(document.querySelectorAll("script,style,nav,footer,header,aside,[role=navigation]").forEach(l=>l.remove()),document.body?.innerText||"")),a=await o.evaluate(()=>Array.from(document.querySelectorAll("a[href]")).slice(0,30).map(c=>({text:(c.innerText||c.textContent||"").trim().substring(0,80),href:c.href})).filter(c=>c.text&&c.href&&!c.href.startsWith("javascript:")));return{title:r,url:o.url(),text:i.substring(0,8e3)+(i.length>8e3?`
128
+ ...(truncated)`:""),links:a.slice(0,20)}}finally{await o.close()}}async function nw(t,{width:e=1280,height:s=800,fullPage:n=!1,timeout:o=3e4}={}){let i=await(await $r()).newPage();try{await i.setViewportSize({width:e,height:s}),await i.goto(t,{waitUntil:"networkidle",timeout:o});let a=await i.screenshot({type:"png",fullPage:n}),c=require("os"),l=require("path"),u=require("fs"),d=l.join(c.tmpdir(),`nex-screenshot-${Date.now()}.png`);return u.writeFileSync(d,a),{path:d,base64:a.toString("base64"),media_type:"image/png",title:await i.title(),url:i.url()}}finally{await i.close()}}async function sw(t,{selector:e,text:s,timeout:n=3e4}={}){if(!e&&!s)throw new Error("selector or text is required");let r=await(await $r()).newPage();try{await r.goto(t,{waitUntil:"domcontentloaded",timeout:n}),s?await r.getByText(s,{exact:!1}).first().click({timeout:1e4}):await r.locator(e).first().click({timeout:1e4}),await r.waitForLoadState("domcontentloaded");let i=await r.title();return`Clicked \u2014 now at: ${r.url()} (${i})`}finally{await r.close()}}async function ow(t,{selector:e,value:s,submit:n=!1,timeout:o=3e4}={}){if(!e||s===void 0)throw new Error("selector and value are required");let i=await(await $r()).newPage();try{return await i.goto(t,{waitUntil:"domcontentloaded",timeout:o}),await i.fill(e,String(s)),n&&(await i.keyboard.press("Enter"),await i.waitForLoadState("domcontentloaded")),`Filled "${e}" with value. ${n?`Submitted \u2192 ${i.url()}`:"Not submitted."}`}finally{await i.close()}}dd.exports={isPlaywrightAvailable:ud,browserNavigate:tw,browserScreenshot:nw,browserClick:sw,browserFill:ow,closeBrowser:ew,INSTALL_MSG:ld}});var $a=re((cv,fd)=>{var{C:Ne}=He(),Us="",tt=[],Ws=0,$n=null;function rw(t){$n=t}function iw(t,e){Us=t,tt=[],Ws=0;for(let n of e){Ws++;let o=`t${Ws}`;tt.push({id:o,description:n.description||n.title||n.name||n.task||`Task ${Ws}`,status:"pending",dependsOn:n.depends_on||[],result:null})}let s=tt.map(n=>({...n}));return $n&&$n("create",{name:t,tasks:s}),s}function aw(t,e,s){let n=tt.find(o=>o.id===t);return n?(n.status=e,s!==void 0&&(n.result=s),$n&&$n("update",{id:t,status:e,result:s}),{...n}):null}function cw(){return{name:Us,tasks:tt.map(t=>({...t}))}}function lw(){Us="",tt=[],Ws=0,$n&&$n("clear",{})}function uw(){return tt.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let s=tt.find(n=>n.id===e);return s&&s.status==="done"}))}function dw(){if(tt.length===0)return`${Ne.dim}No active tasks${Ne.reset}`;let t=[];Us&&(t.push(` ${Ne.bold}${Ne.cyan}Tasks: ${Us}${Ne.reset}`),t.push(` ${Ne.dim}${"\u2500".repeat(40)}${Ne.reset}`));for(let o of tt){let r,i;switch(o.status){case"done":r="\u2713",i=Ne.green;break;case"in_progress":r="\u2192",i=Ne.cyan;break;case"failed":r="\u2717",i=Ne.red;break;default:r="\xB7",i=Ne.dim}let a=o.dependsOn.length>0?` ${Ne.dim}(after: ${o.dependsOn.join(", ")})${Ne.reset}`:"",c=`[${o.status}]`,l=o.description.length>50?o.description.substring(0,47)+"...":o.description;if(t.push(` ${i}${r}${Ne.reset} ${Ne.bold}${o.id}${Ne.reset} ${l.padEnd(40)} ${i}${c}${Ne.reset}${a}`),o.result&&o.status==="done"){let u=o.result.length>60?o.result.substring(0,57)+"...":o.result;t.push(` ${Ne.dim}\u2192 ${u}${Ne.reset}`)}}let e=tt.filter(o=>o.status==="done").length,s=tt.filter(o=>o.status==="failed").length,n=tt.length;return t.push(` ${Ne.dim}${"\u2500".repeat(40)}${Ne.reset}`),t.push(` ${Ne.dim}${e}/${n} done${s>0?`, ${s} failed`:""}${Ne.reset}`),t.join(`
129
+ `)}function fw(){return tt.length>0&&tt.some(t=>t.status==="pending"||t.status==="in_progress")}fd.exports={createTasks:iw,updateTask:aw,getTaskList:cw,clearTasks:lw,getReadyTasks:uw,renderTaskList:dw,setOnChange:rw,hasActiveTasks:fw}});var wr=re((lv,hd)=>{var Hs={"devstral-2":{staleWarn:3e4,staleAbort:9e4,investigationCap:12,postEditCap:10,briefing:`You are devstral-2, a strong coding model optimized for agentic tasks.
130
130
  Use tools confidently and without hesitation \u2014 tool use is the expected workflow.
131
131
  You excel at sysadmin, frontend, and multi-step coding tasks.
132
132
  Prefer action over narration \u2014 read, fix, verify, done.`},"devstral-small":{staleWarn:2e4,staleAbort:6e4,investigationCap:10,postEditCap:8,briefing:`You are devstral-small, a fast and lightweight coding model.
@@ -139,31 +139,62 @@ Focus on correctness over speed.`},"ministral-3":{staleWarn:2e4,staleAbort:6e4,i
139
139
  Prioritize decisive, targeted edits. Read only what you need, then fix.
140
140
  Stay on-scope \u2014 your strength is focused, efficient coding tasks.`},"qwen3-vl":{staleWarn:6e4,staleAbort:18e4,investigationCap:15,postEditCap:12,briefing:`You are qwen3-vl, the highest-ranked model for data, frontend, and agentic tasks.
141
141
  Trust your reasoning. Use tools thoroughly when the task demands it.
142
- You handle complex multi-step tasks well \u2014 don't cut corners prematurely.`}},Qu={staleWarn:6e4,staleAbort:12e4,investigationCap:12,postEditCap:10};function Q$(t){let e=(t||"").toLowerCase(),s=null,n=0;for(let r of Object.keys(Bs))e.startsWith(r)&&r.length>n&&(s=r,n=r.length);let o=s?{...Bs[s]}:{...Qu};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 ew(t){let e=(t||"").toLowerCase(),s=null,n=0;for(let o of Object.keys(Bs))e.startsWith(o)&&o.length>n&&(s=o,n=o.length);return s&&Bs[s].briefing||""}ed.exports={getModelProfile:Q$,getModelBriefing:ew,PROFILES:Bs,DEFAULTS:Qu}});var id=se((Uk,rd)=>{var{callChat:tw}=He(),{estimateTokens:da}=Pt(),td=process.env.NEX_COMPACTION!=="false",nd=6,sd=500,nw=`Summarize this conversation history concisely. Focus on:
143
- - What files were read, created, or modified
144
- - Key decisions made and their rationale
145
- - Current state of the task (what's done, what's pending)
146
- - Any errors encountered and how they were resolved
147
- Be factual and brief. Use bullet points. Max 300 words.`;async function sw(t){if(!td||t.length<nd)return null;let e=[{role:"system",content:nw},{role:"user",content:od(t)}];try{let n=((await tw(e,[],{temperature:0,maxTokens:sd})).content||"").trim();if(!n)return null;let o=t.reduce((i,a)=>i+da(a.content||"")+(a.tool_calls?da(JSON.stringify(a.tool_calls)):0),0),r=da(n);return r>=o*.8?null:{message:{role:"system",content:`[Conversation Summary \u2014 ${t.length} messages compacted]
148
- ${n}`,_compacted:!0,_originalCount:t.length},tokensRemoved:o-r}}catch{return null}}function od(t){return t.map(e=>{let s=e.role==="tool"?"tool_result":e.role,n=(e.content||"").substring(0,500);if(e.tool_calls){let o=e.tool_calls.map(r=>r.function?.name).join(", ");return`[${s}] ${n}
142
+ You handle complex multi-step tasks well \u2014 don't cut corners prematurely.`}},pd={staleWarn:6e4,staleAbort:12e4,investigationCap:12,postEditCap:10};function pw(t){let e=(t||"").toLowerCase(),s=null,n=0;for(let r of Object.keys(Hs))e.startsWith(r)&&r.length>n&&(s=r,n=r.length);let o=s?{...Hs[s]}:{...pd};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 hw(t){let e=(t||"").toLowerCase(),s=null,n=0;for(let o of Object.keys(Hs))e.startsWith(o)&&o.length>n&&(s=o,n=o.length);return s&&Hs[s].briefing||""}hd.exports={getModelProfile:pw,getModelBriefing:hw,PROFILES:Hs,DEFAULTS:pd}});var ba=re((uv,bd)=>{var{callChat:mw}=Ge(),{estimateTokens:wa}=It(),md=process.env.NEX_COMPACTION!=="false",gd=6,yd=2e3,$d=3,gw=`Your task is to create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions.
143
+ 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.
144
+
145
+ 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:
146
+ 1. Chronologically analyze each message. For each section thoroughly identify:
147
+ - The user's explicit requests and intents
148
+ - Your approach to addressing the user's requests
149
+ - Key decisions, technical concepts and code patterns
150
+ - Specific details like file names, code snippets, function signatures, file edits
151
+ - Errors that you ran into and how you fixed them
152
+ - Specific user feedback and direction changes
153
+ 2. Double-check for technical accuracy and completeness.
154
+
155
+ Your summary MUST include these sections:
156
+
157
+ 1. Primary Request and Intent: Capture all of the user's explicit requests and intents in detail
158
+ 2. Key Technical Concepts: List all important technical concepts, technologies, and frameworks discussed
159
+ 3. Files and Code Sections: Enumerate specific files examined, modified, or created \u2014 include full code snippets where applicable and why each is important
160
+ 4. Errors and Fixes: List all errors encountered and how they were resolved; note any user feedback that changed your approach
161
+ 5. Problem Solving: Document problems solved and any ongoing troubleshooting
162
+ 6. All User Messages: List ALL user messages that are not tool results \u2014 critical for understanding feedback and changing intent
163
+ 7. Pending Tasks: Outline any pending tasks explicitly requested
164
+ 8. Current Work: Describe precisely what was being worked on immediately before this summary, including file names and code snippets
165
+ 9. Optional Next Step: The next step directly in line with the user's most recent explicit request. Include direct quotes from the conversation showing exactly what task you were working on.
166
+
167
+ Format your output as:
168
+ <analysis>
169
+ [Your thought process]
170
+ </analysis>
171
+
172
+ <summary>
173
+ [Sections 1-9 above]
174
+ </summary>`,wn=0;async function yw(t){if(!md||t.length<gd||wn>=$d)return null;let e=[{role:"system",content:gw},{role:"user",content:wd(t)}];try{let n=((await mw(e,[],{temperature:0,maxTokens:yd})).content||"").trim();if(!n)return wn++,null;let o=n.match(/<summary>([\s\S]*?)<\/summary>/);if(o?n=o[1].trim():n=n.replace(/<analysis>[\s\S]*?<\/analysis>/g,"").trim(),!n)return wn++,null;let r=t.reduce((a,c)=>a+wa(c.content||"")+(c.tool_calls?wa(JSON.stringify(c.tool_calls)):0),0),i=wa(n);return i>=r*.8?(wn++,null):(wn=0,{message:{role:"system",content:`[Conversation Summary \u2014 ${t.length} messages compacted]
175
+ ${n}`,_compacted:!0,_originalCount:t.length},tokensRemoved:r-i})}catch{return wn++,null}}function $w(){wn=0}function wd(t){return t.map(e=>{let s=e.role==="tool"?"tool_result":e.role,n=(e.content||"").substring(0,500);if(e.tool_calls){let o=e.tool_calls.map(r=>r.function?.name).join(", ");return`[${s}] ${n}
149
176
  tools: ${o}`}return`[${s}] ${n}`}).join(`
150
177
 
151
- `)}rd.exports={compactMessages:sw,formatMessagesForSummary:od,COMPACTION_ENABLED:td,COMPACTION_MIN_MESSAGES:nd,COMPACTION_SUMMARY_BUDGET:sd}});var Pt=se((Hk,gd)=>{var ow=require("path");function cd(){return He().getActiveModel()}var rw={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},iw={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},gn=new Map,ad=1e3,fa=new WeakMap,yn=null;function aw(){if(yn!==null)return yn;try{let t=cd(),e=t?.provider||"ollama",s=(t?.id||"").toLowerCase();for(let[n,o]of Object.entries(iw))if(s.startsWith(n))return yn=o,yn;return yn=rw[e]||4,yn}catch{return 4}}function cw(){yn=null}function $n(t){if(!t)return 0;typeof t!="string"&&(t=JSON.stringify(t));let e=t.length<=120?t:`${t.length}:${t.substring(0,60)}:${t.substring(t.length>>1,(t.length>>1)+30)}:${t.substring(t.length-30)}`,s=gn.get(e);if(s!==void 0)return gn.delete(e),gn.set(e,s),s;let n=Math.ceil(t.length/aw());if(gn.size>=ad){let o=ad>>1,r=gn.keys();for(let i=0;i<o;i++)gn.delete(r.next().value)}return gn.set(e,n),n}function lw(t){if(fa.has(t))return fa.get(t);let e=JSON.stringify(t);return fa.set(t,e),e}function ss(t){let s=4;if(t.content&&(s+=$n(t.content)),t.tool_calls)for(let n of t.tool_calls){s+=4,s+=$n(n.function?.name||"");let o=n.function?.arguments;typeof o=="string"?s+=$n(o):o&&(s+=$n(JSON.stringify(o)))}return s}function yt(t){let e=0;for(let s of t)e+=ss(s);return e}function uw(t,e){if(t&&t.length===e.length){let r=!1;for(let i=0;i<e.length;i++)if(t[i]!==e[i]){r=!0;break}if(!r)return 0}let s=t?t.length:0,n=e.length,o=0;for(let r=s;r<n;r++)o+=ss(e[r]);return o}function yr(t){return!t||t.length===0?0:$n(JSON.stringify(t))}function $r(){return cd()?.contextWindow||32768}function dw(t,e){let s=yt(t),n=yr(e),o=s+n,r=$r(),i=r>0?o/r*100:0,a=0,c=0,l=0;for(let u of t){let d=ss(u);u.role==="system"?a+=d:u.role==="tool"?l+=d:c+=d}return{used:o,limit:r,percentage:Math.round(i*10)/10,breakdown:{system:a,conversation:c,toolResults:l,toolDefinitions:n},messageCount:t.length}}var Ws=parseFloat(process.env.NEX_COMPRESSION_THRESHOLD)||.75,ld=parseFloat(process.env.NEX_SAFETY_MARGIN)||.1,ud=parseInt(process.env.NEX_KEEP_RECENT,10)||10,dd={essential:.6,standard:.7,full:Ws};function fd(){if(process.env.NEX_COMPRESSION_THRESHOLD)return Ws;try{let{getActiveTier:t}=Is(),e=t();return dd[e]??Ws}catch{return Ws}}var fw=200,pw=1e3;function pd(t,e){if(!t||t.length<=e)return t;let n=/^(ERROR|EXIT|BLOCKED|CANCELLED)/i.test(t)?e*3:e;if(t.length<=n)return t;let o=t.split(`
152
- `);if(o.length<=10){let m=Math.floor(n*.6),g=Math.floor(n*.4),b=t.substring(0,m),v=t.substring(t.length-g);return b+`
178
+ `)}bd.exports={compactMessages:yw,formatMessagesForSummary:wd,resetCompactionFailures:$w,COMPACTION_ENABLED:md,COMPACTION_MIN_MESSAGES:gd,COMPACTION_SUMMARY_BUDGET:yd,MAX_CONSECUTIVE_FAILURES:$d}});var It=re((dv,Ad)=>{var ww=require("path");function xd(){return Ge().getActiveModel()}var bw={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},_w={devstral:3.8,mistral:3.8,ministral:3.8,codestral:3.8,qwen:3.5,deepseek:3.6,kimi:3.7,gemma:4,llama:3.8,cogito:3.6,phi:4},bn=new Map,_d=1e3,_a=new WeakMap,_n=null;function xw(){if(_n!==null)return _n;try{let t=xd(),e=t?.provider||"ollama",s=(t?.id||"").toLowerCase();for(let[n,o]of Object.entries(_w))if(s.startsWith(n))return _n=o,_n;return _n=bw[e]||4,_n}catch{return 4}}function kw(){_n=null}function xn(t){if(!t)return 0;typeof t!="string"&&(t=JSON.stringify(t));let e=t.length<=120?t:`${t.length}:${t.substring(0,60)}:${t.substring(t.length>>1,(t.length>>1)+30)}:${t.substring(t.length-30)}`,s=bn.get(e);if(s!==void 0)return bn.delete(e),bn.set(e,s),s;let n=Math.ceil(t.length/xw());if(bn.size>=_d){let o=_d>>1,r=bn.keys();for(let i=0;i<o;i++)bn.delete(r.next().value)}return bn.set(e,n),n}function vw(t){if(_a.has(t))return _a.get(t);let e=JSON.stringify(t);return _a.set(t,e),e}function as(t){let s=4;if(t.content&&(s+=xn(t.content)),t.tool_calls)for(let n of t.tool_calls){s+=4,s+=xn(n.function?.name||"");let o=n.function?.arguments;typeof o=="string"?s+=xn(o):o&&(s+=xn(JSON.stringify(o)))}return s}function wt(t){let e=0;for(let s of t)e+=as(s);return e}function Sw(t,e){if(t&&t.length===e.length){let r=!1;for(let i=0;i<e.length;i++)if(t[i]!==e[i]){r=!0;break}if(!r)return 0}let s=t?t.length:0,n=e.length,o=0;for(let r=s;r<n;r++)o+=as(e[r]);return o}function br(t){return!t||t.length===0?0:xn(JSON.stringify(t))}function _r(){return xd()?.contextWindow||32768}function Ew(t,e){let s=wt(t),n=br(e),o=s+n,r=_r(),i=r>0?o/r*100:0,a=0,c=0,l=0;for(let u of t){let d=as(u);u.role==="system"?a+=d:u.role==="tool"?l+=d:c+=d}return{used:o,limit:r,percentage:Math.round(i*10)/10,breakdown:{system:a,conversation:c,toolResults:l,toolDefinitions:n},messageCount:t.length}}var Ys=parseFloat(process.env.NEX_COMPRESSION_THRESHOLD)||.75,kd=parseFloat(process.env.NEX_SAFETY_MARGIN)||.1,vd=parseInt(process.env.NEX_KEEP_RECENT,10)||10,Sd={essential:.6,standard:.65,full:Math.min(Ys,.68)};function Ed(){if(process.env.NEX_COMPRESSION_THRESHOLD)return Ys;try{let{getActiveTier:t}=qs(),e=t();return Sd[e]??Ys}catch{return Ys}}var Tw=200,Rw=1e3;function Td(t,e){if(!t||t.length<=e)return t;let n=/^(ERROR|EXIT|BLOCKED|CANCELLED)/i.test(t)?e*3:e;if(t.length<=n)return t;let o=t.split(`
179
+ `);if(o.length<=10){let g=Math.floor(n*.6),m=Math.floor(n*.4),b=t.substring(0,g),x=t.substring(t.length-m);return b+`
153
180
  ...(${t.length} chars total)...
154
- `+v}let r=Math.floor(o.length*.4),i=Math.floor(o.length*.4),a=[],c=0,l=Math.floor(n*.4);for(let m=0;m<r&&c<l;m++)if(c+o[m].length+1>l&&o[m].trim().startsWith("```")){a.push(o[m]),c+=o[m].length+1;let g=m+1;for(;g<o.length&&c<l*1.5&&!o[g].trim().startsWith("```");)a.push(o[g]),c+=o[g].length+1,g++;g<o.length&&o[g].trim().startsWith("```")&&(a.push(o[g]),c+=o[g].length+1),m=g}else a.push(o[m]),c+=o[m].length+1;let u=[],d=0,f=Math.floor(n*.4);for(let m=o.length-1;m>=o.length-i&&d<f;m--)if(d+o[m].length+1>f&&o[m].trim().startsWith("```")){u.push(o[m]),d+=o[m].length+1;let g=m-1;for(;g>=0&&d<f*1.5&&!o[g].trim().startsWith("```");)u.push(o[g]),d+=o[g].length+1,g--;g>=0&&o[g].trim().startsWith("```")&&(u.push(o[g]),d+=o[g].length+1),m=g}else u.push(o[m]),d+=o[m].length+1;u.reverse();let h=o.length-a.length-u.length;return a.join(`
181
+ `+x}let r=Math.floor(o.length*.4),i=Math.floor(o.length*.4),a=[],c=0,l=Math.floor(n*.4);for(let g=0;g<r&&c<l;g++)if(c+o[g].length+1>l&&o[g].trim().startsWith("```")){a.push(o[g]),c+=o[g].length+1;let m=g+1;for(;m<o.length&&c<l*1.5&&!o[m].trim().startsWith("```");)a.push(o[m]),c+=o[m].length+1,m++;m<o.length&&o[m].trim().startsWith("```")&&(a.push(o[m]),c+=o[m].length+1),g=m}else a.push(o[g]),c+=o[g].length+1;let u=[],d=0,f=Math.floor(n*.4);for(let g=o.length-1;g>=o.length-i&&d<f;g--)if(d+o[g].length+1>f&&o[g].trim().startsWith("```")){u.push(o[g]),d+=o[g].length+1;let m=g-1;for(;m>=0&&d<f*1.5&&!o[m].trim().startsWith("```");)u.push(o[m]),d+=o[m].length+1,m--;m>=0&&o[m].trim().startsWith("```")&&(u.push(o[m]),d+=o[m].length+1),g=m}else u.push(o[g]),d+=o[g].length+1;u.reverse();let h=o.length-a.length-u.length;return a.join(`
155
182
  `)+`
156
183
  ...(${h} lines omitted, ${o.length} total)...
157
184
  `+u.join(`
158
- `)}function ns(t,e="light"){let s=e==="aggressive"?100:e==="medium"?200:pw,n=e==="aggressive"?50:e==="medium"?100:fw;if(t.role==="tool"){let o=typeof t.content=="string"?t.content:JSON.stringify(t.content);return o.length>n?{...t,content:pd(o,n)}:t}if(t.role==="assistant"){let o={...t};return o.content&&o.content.length>s&&(o.content=o.content.substring(0,s)+`
159
- ...(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 hd(t,e,s,n){let o=0;if(t.role==="system")return 100;if(t.role==="user")o+=35;else if(t.role==="tool"){let i=typeof t.content=="string"?t.content:JSON.stringify(t.content||"");/^(ERROR|BLOCKED|CANCELLED)/i.test(i)?o+=30:o+=15}else t.role==="assistant"&&(o+=t.tool_calls?20:10);let r=s>1?e/(s-1):1;if(o+=Math.round(r*30),n&&n.size>0){let i=typeof t.content=="string"?t.content:JSON.stringify(t.content||""),a=0;for(let c of n)(i.includes(c)||i.includes(ow.basename(c)))&&a++;o+=Math.min(30,a*10)}return Math.min(100,o)}function md(t,e=10){let s=new Set,n=t.slice(-e),o=/(?:\/[\w.-]+)+\.\w+/g;for(let r of n){let a=(typeof r.content=="string"?r.content:JSON.stringify(r.content||"")).match(o);a&&a.forEach(c=>s.add(c))}return s}var ts={msgCount:-1,lastMsgRef:null,result:null};function hw(){ts={msgCount:-1,lastMsgRef:null,result:null}}async function mw(t,e,s={}){let n=t.length>0?t[t.length-1]:null;if(!s.force&&ts.result&&t.length===ts.msgCount&&n===ts.lastMsgRef)return ts.result;let o=s.threshold??fd(),r=s.safetyMargin??ld,i=s.keepRecent??ud,a=$r(),c=yr(e),l=Math.floor(a*(o-r)),u=l-c,d=yt(t),f=d+c;if(f<=l){let V={messages:t,compressed:!1,compacted:!1,tokensRemoved:0};return ts={msgCount:t.length,lastMsgRef:n,result:V},V}let h=d,m=null,g=0;t.length>0&&t[0].role==="system"&&(m=t[0],g=1);let b=Math.max(g,t.length-i),v=t.slice(g,b),O=t.slice(b),U=v.filter(V=>!V._compacted);if(U.length>=6)try{let{compactMessages:V}=id(),H=await V(U);if(H){let he=[...v.filter(ge=>ge._compacted),H.message],de=Zt(m,he,O),me=yt(de);if(me+c<=l)return{messages:de,compressed:!0,compacted:!0,tokensRemoved:h-me};v=he}}catch(V){process.env.NEX_DEBUG&&console.error("[context-engine] LLM compacting failed:",V.message)}let L=(f-l)/l,R=v.map(V=>ns(V,"light")),C=Zt(m,R,O),K=yt(C);if(K+c<=l)return{messages:C,compressed:!0,compacted:!1,tokensRemoved:h-K};if(R=v.map(V=>ns(V,"medium")),C=Zt(m,R,O),K=yt(C),K+c<=l)return{messages:C,compressed:!0,compacted:!1,tokensRemoved:h-K};if(R=v.map(V=>ns(V,"aggressive")),C=Zt(m,R,O),K=yt(C),K+c<=l)return{messages:C,compressed:!0,compacted:!1,tokensRemoved:h-K};let Q=md([...R,...O]),re=R.map((V,H)=>({msg:V,score:hd(V,H,R.length,Q),tokens:ss(V)}));for(;re.length>0&&K>u;){let V=0;for(let H=1;H<re.length;H++)re[H].score<re[V].score&&(V=H);K-=re[V].tokens,re.splice(V,1)}return R=re.map(V=>V.msg),C=Zt(m,R,O),K=yt(C),{messages:C,compressed:!0,compacted:!1,tokensRemoved:h-K}}function Zt(t,e,s){let n=[];return t&&n.push(t),n.push(...e,...s),n}function gw(t,e){if(!t)return"";if($n(t)<=e)return t;let n=e*4,o=t.split(`
185
+ `)}function is(t,e="light"){let s=e==="aggressive"?100:e==="medium"?200:Rw,n=e==="aggressive"?50:e==="medium"?100:Tw;if(t.role==="tool"){let o=typeof t.content=="string"?t.content:JSON.stringify(t.content);return o.length>n?{...t,content:Td(o,n)}:t}if(t.role==="assistant"){let o={...t};return o.content&&o.content.length>s&&(o.content=o.content.substring(0,s)+`
186
+ ...(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 Rd(t,e,s,n){let o=0;if(t.role==="system")return 100;if(t.role==="user")o+=35;else if(t.role==="tool"){let i=typeof t.content=="string"?t.content:JSON.stringify(t.content||"");/^(ERROR|BLOCKED|CANCELLED)/i.test(i)?o+=30:o+=15}else t.role==="assistant"&&(o+=t.tool_calls?20:10);let r=s>1?e/(s-1):1;if(o+=Math.round(r*30),n&&n.size>0){let i=typeof t.content=="string"?t.content:JSON.stringify(t.content||""),a=0;for(let c of n)(i.includes(c)||i.includes(ww.basename(c)))&&a++;o+=Math.min(30,a*10)}return Math.min(100,o)}function Cd(t,e=10){let s=new Set,n=t.slice(-e),o=/(?:\/[\w.-]+)+\.\w+/g;for(let r of n){let a=(typeof r.content=="string"?r.content:JSON.stringify(r.content||"")).match(o);a&&a.forEach(c=>s.add(c))}return s}function Cw(t,{filesModified:e=new Set,currentPhase:s=null}={}){let n=[];if(e.size>0){let r=[...e].map(i=>i.split("/").slice(-2).join("/")).join(", ");n.push(`Files already modified: ${r} \u2014 do NOT rewrite these, use edit_file for additions only.`)}s&&n.push(`Current phase: ${s}`);let o=t.filter(r=>r.role==="assistant"&&typeof r.content=="string"&&r.content.trim().length>30).slice(-3).map(r=>r.content.trim().slice(0,200).replace(/\n+/g," "));return o.length>0&&n.push(`Recent progress:
187
+ `+o.map(r=>`- ${r}`).join(`
188
+ `)),n.length===0?null:{role:"system",content:`## Progress State (preserved through compression)
189
+ ${n.join(`
190
+ `)}`,_pinned:!0,_progressSnapshot:!0}}var rs={msgCount:-1,lastMsgRef:null,result:null};function Aw(){rs={msgCount:-1,lastMsgRef:null,result:null}}async function Ow(t,e,s={}){let n=t.length>0?t[t.length-1]:null;if(!s.force&&rs.result&&t.length===rs.msgCount&&n===rs.lastMsgRef)return rs.result;let o=s.threshold??Ed(),r=s.safetyMargin??kd,i=s.keepRecent??vd,a=_r(),c=br(e),l=Math.floor(a*(o-r)),u=l-c,d=wt(t),f=d+c;if(f<=l){let se={messages:t,compressed:!1,compacted:!1,tokensRemoved:0};return rs={msgCount:t.length,lastMsgRef:n,result:se},se}let h=d,g=null,m=0;t.length>0&&t[0].role==="system"&&(g=t[0],m=1);let b=Math.max(m,t.length-i),x=t.slice(m,b),j=t.slice(b),G=x.filter(se=>se._pinned),L=x.filter(se=>!se._compacted&&!se._pinned);if(L.length>=6)try{let{compactMessages:se}=ba(),T=await se(L);if(T){let Te=x.filter(fe=>fe._compacted&&!fe._pinned),K=[...G,...Te,T.message],X=en(g,K,j),me=wt(X);if(me+c<=l)return{messages:X,compressed:!0,compacted:!0,tokensRemoved:h-me};x=K}}catch(se){process.env.NEX_DEBUG&&console.error("[context-engine] LLM compacting failed:",se.message)}let P=(f-l)/l,C=x.map(se=>is(se,"light")),Z=en(g,C,j),Y=wt(Z);if(Y+c<=l)return{messages:Z,compressed:!0,compacted:!1,tokensRemoved:h-Y};if(C=x.map(se=>is(se,"medium")),Z=en(g,C,j),Y=wt(Z),Y+c<=l)return{messages:Z,compressed:!0,compacted:!1,tokensRemoved:h-Y};if(C=x.map(se=>is(se,"aggressive")),Z=en(g,C,j),Y=wt(Z),Y+c<=l)return{messages:Z,compressed:!0,compacted:!1,tokensRemoved:h-Y};let ue=Cd([...C,...j]),ie=C.map((se,T)=>({msg:se,score:se._pinned?1/0:Rd(se,T,C.length,ue),tokens:as(se)}));for(;ie.length>0&&Y>u;){let se=-1;for(let T=0;T<ie.length;T++)ie[T].score!==1/0&&(se===-1||ie[T].score<ie[se].score)&&(se=T);if(se===-1)break;Y-=ie[se].tokens,ie.splice(se,1)}return C=ie.map(se=>se.msg),Z=en(g,C,j),Y=wt(Z),{messages:Z,compressed:!0,compacted:!1,tokensRemoved:h-Y}}function en(t,e,s){let n=[];return t&&n.push(t),n.push(...e,...s),n}function Nw(t,e){if(!t)return"";if(xn(t)<=e)return t;let n=e*4,o=t.split(`
160
191
  `),r=Math.floor(n*.6),i=Math.floor(n*.4),a="",c=0;for(let h of o){if(a.length+h.length+1>r)break;a+=(a?`
161
- `:"")+h,c++}let l="",u=0;for(let h=o.length-1;h>=c;h--){let m=o[h]+(l?`
162
- `:"")+l;if(m.length>i)break;l=m,u++}let f=`
192
+ `:"")+h,c++}let l="",u=0;for(let h=o.length-1;h>=c;h--){let g=o[h]+(l?`
193
+ `:"")+l;if(g.length>i)break;l=g,u++}let f=`
163
194
 
164
195
  ... (${o.length-c-u} lines omitted, ${o.length} total) ...
165
196
 
166
- `;return a+f+l}var yw=6;function $w(t,e,s=!1){let n=$r(),o=yr(e),r=Math.floor(n*(s?.35:.5))-o,i=yt(t),a=Math.floor(i*(s?.5:.8));r>a&&(r=a);let c=null,l=0;t.length>0&&t[0].role==="system"&&(c=t[0],l=1);let u=s?2:yw,d=Math.max(l,t.length-u),f=t.slice(l,d),h=t.slice(d),m=f.map(R=>ns(R,"aggressive"));s&&(h=h.map(R=>ns(R,"aggressive")));let g=Zt(c,m,h),b=yt(g);for(;m.length>0&&b>r;){let R=m.shift();b-=ss(R)}s&&b>r&&(h=h.filter(C=>C.role==="user").slice(-1),g=Zt(c,[],h),b=yt(g)),g=Zt(c,m,h);let v=t.filter(R=>R.role==="user"),O=R=>{let C=typeof R.content=="string"?R.content:"";return C.startsWith("[SYSTEM WARNING]")||C.startsWith("[SYSTEM:")||C.startsWith("BLOCKED:")},U=v.find(R=>!O(R)),L=[...v].reverse().find(R=>!O(R));if(U&&!g.find(R=>R===U)){let R=g.findIndex(K=>K.role==="system"),C=R>=0?R+1:0;g.splice(C,0,U)}return L&&L!==U&&!g.find(R=>R===L)&&g.push(L),{messages:g,tokensRemoved:i-yt(g)}}gd.exports={estimateTokens:$n,estimateMessageTokens:ss,estimateMessagesTokens:yt,estimateDeltaTokens:uw,estimateToolsTokens:yr,serializeMessage:lw,getContextWindow:$r,getUsage:dw,compressMessage:ns,compressToolResult:pd,scoreMessageRelevance:hd,extractActiveFiles:md,fitToContext:mw,forceCompress:$w,truncateFileContent:gw,invalidateTokenRatioCache:cw,invalidateFitToContextCache:hw,getEffectiveCompressionThreshold:fd,COMPRESSION_THRESHOLD:Ws,TIER_COMPRESSION_THRESHOLDS:dd,SAFETY_MARGIN:ld,KEEP_RECENT:ud}});var ga=se((Yk,Dd)=>{var{callStream:ww,getActiveProviderName:br,getActiveModelId:yd,getConfiguredProviders:bw,getProvider:$d,getActiveProvider:wd,parseModelSpec:bd}=He(),{parseToolArgs:_d}=Ss(),{filterToolsForModel:_w,getModelTier:wr}=Is(),{getModelBriefing:xw}=gr(),{trackUsage:xd,estimateTokens:kd}=zo(),{MultiProgress:kw,C:Gk}=Ue();function vd(t){return!t||typeof t!="string"?0:typeof kd=="function"?kd(t):Math.ceil(t.length/4)}var Td=15,vw=5,Sd=3,Rd=8,Sw=2,_r=new Map,Cd=600*1e3;function Ew(t,e){let s=_r.get(t);return s&&s.agentId!==e&&Date.now()-s.timestamp<Cd?!1:(_r.set(t,{agentId:e,timestamp:Date.now()}),!0)}function Us(t){_r.delete(t)}function pa(){_r.clear()}function ha(t){let e=(t.message||"").toLowerCase(),s=t.code||"";return e.includes("429")||e.includes("rate limit")?"rate_limit":e.includes("401")||e.includes("403")||e.includes("unauthorized")||e.includes("forbidden")?"auth":e.includes("context")&&(e.includes("too long")||e.includes("overflow")||e.includes("maximum"))||e.includes("400")&&(e.includes("content")||e.includes("length"))?"context_overflow":e.includes("500")||e.includes("502")||e.includes("503")||e.includes("504")?"server":e.includes("timed out")||e.includes("timeout")?"timeout":s==="ECONNRESET"||s==="ECONNABORTED"||s==="ETIMEDOUT"||s==="ECONNREFUSED"||s==="ENOTFOUND"||e.includes("socket disconnected")||e.includes("tls")||e.includes("econnreset")||e.includes("fetch failed")||e.includes("etimedout")||e.includes("enotfound")?"network":"unknown"}function Ad(t){let e=ha(t);return e==="rate_limit"||e==="server"||e==="network"||e==="timeout"}async function Od(t,e,s){let n;for(let o=0;o<=Sd;o++)try{return await ww(t,e,s)}catch(r){n=r;let i=ha(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<Sd&&Ad(r)){let c=i==="rate_limit"?Math.min(2e3*Math.pow(2,o),15e3):Math.min(500*Math.pow(2,o),4e3);await new Promise(l=>setTimeout(l,c).unref());continue}throw r}throw n}var Ed=new Set(["ask_user","task_list"]);function Nd(t){return t>=2?new Set([...Ed,"spawn_agents"]):Ed}var Tw=new Set(["write_file","edit_file","patch_file"]),Md={explore:{allowedTools:new Set(["bash","read_file","list_directory","glob","grep","search_files","web_fetch","web_search"]),systemSuffix:"You are an exploration agent. Read and search code only. Do NOT modify any files."},review:{allowedTools:new Set(["read_file","list_directory","glob","grep","search_files"]),systemSuffix:"You are a code review agent. Read code and report findings. Do NOT make changes."},implement:{allowedTools:null,systemSuffix:""}},Rw=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,Cw=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function Ld(t){return Cw.test(t)?"full":Rw.test(t)?"essential":t.length>300?"full":"standard"}function Pd(t){let e=bw(),s=br(),n=[...e].sort((o,r)=>(o.name===s?-1:1)-(r.name===s?-1:1));for(let o of n)for(let r of o.models)if(wr(r.id,o.name)===t)return{provider:o.name,model:r.id};return null}var Aw={essential:process.env.NEX_FAST_MODEL||null,standard:process.env.NEX_STANDARD_MODEL||null,full:process.env.NEX_HEAVY_MODEL||null};function ma(t){if(t.model){let{provider:o,model:r}=bd(t.model),i=o?$d(o):wd(),a=o||br();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let c=wr(r,a);return{provider:a,model:r,tier:c}}}let e=Ld(t.task),s=Aw[e];if(s){let{provider:o,model:r}=bd(s),i=o?$d(o):wd(),a=o||br();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let c=wr(r,a);return{provider:a,model:r,tier:c}}}let n=Pd(e);if(n){let o=wr(n.model,n.provider);return{provider:n.provider,model:n.model,tier:o}}return{provider:null,model:null,tier:null}}async function Id(t,e={},s=0){let n=s===0?Td:Rd,o=Math.min(t.max_iterations||10,n),r=`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,i=[],a={input:0,output:0},c=new Set,l=new Map,u=t._systemPrompt||`You are a focused sub-agent. Complete this specific task efficiently.
197
+ `;return a+f+l}var Mw=6;function Lw(t,e,s=!1){let n=_r(),o=br(e),r=Math.floor(n*(s?.35:.5))-o,i=wt(t),a=Math.floor(i*(s?.5:.8));r>a&&(r=a);let c=null,l=0;t.length>0&&t[0].role==="system"&&(c=t[0],l=1);let u=s?2:Mw,d=Math.max(l,t.length-u),f=t.slice(l,d),h=t.slice(d),g=f.map(P=>is(P,"aggressive"));s&&(h=h.map(P=>is(P,"aggressive")));let m=en(c,g,h),b=wt(m);for(;g.length>0&&b>r;){let P=g.shift();b-=as(P)}s&&b>r&&(h=h.filter(C=>C.role==="user").slice(-1),m=en(c,[],h),b=wt(m)),m=en(c,g,h);let x=t.filter(P=>P.role==="user"),j=P=>{let C=typeof P.content=="string"?P.content:"";return C.startsWith("[SYSTEM WARNING]")||C.startsWith("[SYSTEM:")||C.startsWith("BLOCKED:")},G=x.find(P=>!j(P)),L=[...x].reverse().find(P=>!j(P));if(G&&!m.find(P=>P===G)){let P=m.findIndex(Z=>Z.role==="system"),C=P>=0?P+1:0;m.splice(C,0,G)}return L&&L!==G&&!m.find(P=>P===L)&&m.push(L),{messages:m,tokensRemoved:i-wt(m)}}Ad.exports={estimateTokens:xn,estimateMessageTokens:as,estimateMessagesTokens:wt,estimateDeltaTokens:Sw,estimateToolsTokens:br,serializeMessage:vw,getContextWindow:_r,getUsage:Ew,compressMessage:is,compressToolResult:Td,scoreMessageRelevance:Rd,extractActiveFiles:Cd,buildProgressSnapshot:Cw,fitToContext:Ow,forceCompress:Lw,truncateFileContent:Nw,invalidateTokenRatioCache:kw,invalidateFitToContextCache:Aw,getEffectiveCompressionThreshold:Ed,COMPRESSION_THRESHOLD:Ys,TIER_COMPRESSION_THRESHOLDS:Sd,SAFETY_MARGIN:kd,KEEP_RECENT:vd}});var Sa=re((pv,Zd)=>{var{callStream:Pw,getActiveProviderName:kr,getActiveModelId:Od,getConfiguredProviders:Iw,getProvider:Nd,getActiveProvider:Md,parseModelSpec:Ld}=Ge(),{parseToolArgs:Pd}=Rs(),{filterToolsForModel:jw,getModelTier:xr}=qs(),{getModelBriefing:Dw}=wr(),{trackUsage:Id,estimateTokens:jd}=Jo(),{MultiProgress:qw,C:fv}=He();function Dd(t){return!t||typeof t!="string"?0:typeof jd=="function"?jd(t):Math.ceil(t.length/4)}var Bd=15,Fw=5,qd=3,Wd=8,Bw=2,vr=new Map,Ud=600*1e3;function Ww(t,e){let s=vr.get(t);return s&&s.agentId!==e&&Date.now()-s.timestamp<Ud?!1:(vr.set(t,{agentId:e,timestamp:Date.now()}),!0)}function Gs(t){vr.delete(t)}function xa(){vr.clear()}function ka(t){let e=(t.message||"").toLowerCase(),s=t.code||"";return e.includes("429")||e.includes("rate limit")?"rate_limit":e.includes("401")||e.includes("403")||e.includes("unauthorized")||e.includes("forbidden")?"auth":e.includes("context")&&(e.includes("too long")||e.includes("overflow")||e.includes("maximum"))||e.includes("400")&&(e.includes("content")||e.includes("length"))?"context_overflow":e.includes("500")||e.includes("502")||e.includes("503")||e.includes("504")?"server":e.includes("timed out")||e.includes("timeout")?"timeout":s==="ECONNRESET"||s==="ECONNABORTED"||s==="ETIMEDOUT"||s==="ECONNREFUSED"||s==="ENOTFOUND"||e.includes("socket disconnected")||e.includes("tls")||e.includes("econnreset")||e.includes("fetch failed")||e.includes("etimedout")||e.includes("enotfound")?"network":"unknown"}function Hd(t){let e=ka(t);return e==="rate_limit"||e==="server"||e==="network"||e==="timeout"}async function Yd(t,e,s){let n;for(let o=0;o<=qd;o++)try{return await Pw(t,e,s)}catch(r){n=r;let i=ka(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<qd&&Hd(r)){let c=i==="rate_limit"?Math.min(2e3*Math.pow(2,o),15e3):Math.min(500*Math.pow(2,o),4e3);await new Promise(l=>setTimeout(l,c).unref());continue}throw r}throw n}var Fd=new Set(["ask_user","task_list"]);function Gd(t){return t>=2?new Set([...Fd,"spawn_agents"]):Fd}var Uw=new Set(["write_file","edit_file","patch_file"]),Kd={explore:{allowedTools:new Set(["bash","read_file","list_directory","glob","grep","search_files","web_fetch","web_search"]),systemSuffix:"You are an exploration agent. Read and search code only. Do NOT modify any files."},review:{allowedTools:new Set(["read_file","list_directory","glob","grep","search_files"]),systemSuffix:"You are a code review agent. Read code and report findings. Do NOT make changes."},implement:{allowedTools:null,systemSuffix:""}},Hw=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,Yw=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function zd(t){return Yw.test(t)?"full":Hw.test(t)?"essential":t.length>300?"full":"standard"}function Xd(t){let e=Iw(),s=kr(),n=[...e].sort((o,r)=>(o.name===s?-1:1)-(r.name===s?-1:1));for(let o of n)for(let r of o.models)if(xr(r.id,o.name)===t)return{provider:o.name,model:r.id};return null}var Gw={essential:process.env.NEX_FAST_MODEL||null,standard:process.env.NEX_STANDARD_MODEL||null,full:process.env.NEX_HEAVY_MODEL||null};function va(t){if(t.model){let{provider:o,model:r}=Ld(t.model),i=o?Nd(o):Md(),a=o||kr();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let c=xr(r,a);return{provider:a,model:r,tier:c}}}let e=zd(t.task),s=Gw[e];if(s){let{provider:o,model:r}=Ld(s),i=o?Nd(o):Md(),a=o||kr();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let c=xr(r,a);return{provider:a,model:r,tier:c}}}let n=Xd(e);if(n){let o=xr(n.model,n.provider);return{provider:n.provider,model:n.model,tier:o}}return{provider:null,model:null,tier:null}}async function Vd(t,e={},s=0){let n=s===0?Bd:Wd,o=Math.min(t.max_iterations||10,n),r=`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,i=[],a={input:0,output:0},c=new Set,l=new Map,u=t._systemPrompt||`You are a focused sub-agent. Complete this specific task efficiently.
167
198
 
168
199
  TASK: ${t.task}
169
200
  ${t.context?`
@@ -185,25 +216,25 @@ TOOL STRATEGY:
185
216
  ERROR RECOVERY:
186
217
  - If edit_file fails with "old_text not found": read the file again, compare, and retry with exact text.
187
218
  - If bash fails: read the error, fix the root cause, then retry.
188
- - After 2 failed attempts at the same operation, summarize the issue and stop.`,d=t.type&&Md[t.type],f=d&&d.systemSuffix?`
219
+ - After 2 failed attempts at the same operation, summarize the issue and stop.`,d=t.type&&Kd[t.type],f=d&&d.systemSuffix?`
189
220
 
190
- ${d.systemSuffix}`:"",h=ma(t),m=h.provider,g=h.model,b=h.tier,v=xw(g||yd()),U=[{role:"system",content:(v?`## Model Briefing
191
- ${v}
221
+ ${d.systemSuffix}`:"",h=va(t),g=h.provider,m=h.model,b=h.tier,x=Dw(m||Od()),G=[{role:"system",content:(x?`## Model Briefing
222
+ ${x}
192
223
 
193
224
  ---
194
225
 
195
- `:"")+u+f}];U.push({role:"user",content:t.task});let{TOOL_DEFINITIONS:L,executeTool:R}=Jn(),C=Nd(s),K=_w(L.filter(re=>!C.has(re.function.name)),b);if(d&&d.allowedTools&&(K=K.filter(re=>d.allowedTools.has(re.function.name))),g&&!t._skipLog){let re=b?` (${b})`:"";process.stderr.write(` [sub-agent: ${m}:${g}${re}]
196
- `)}let Q={};m&&(Q.provider=m),g&&(Q.model=g);try{for(let V=0;V<o;V++){let H=await Od(U,K,Q);if(!H||typeof H!="object")throw new Error("Empty or invalid response from provider");{let we=m||br(),Se=g||yd();if(H.usage){let fe=H.usage.prompt_tokens||0,Pe=H.usage.completion_tokens||0;a.input+=fe,a.output+=Pe,xd(we,Se,fe,Pe)}else{let fe=H.content||"",Pe=U.map(k=>typeof k.content=="string"?k.content:Array.isArray(k.content)?k.content.map(N=>typeof N=="string"?N:N.text||"").join(""):"").join(" "),w=vd(Pe),P=vd(fe);a.input+=w,a.output+=P,a._estimated=!0,xd(we,Se,w,P)}}let _=H.content||"",he=H.tool_calls,de={role:"assistant",content:_||""};if(he&&he.length>0&&(de.tool_calls=he),U.push(de),!he||he.length===0){for(let we of c)Us(we);return{task:t.task,status:"done",result:_||"(no response)",toolsUsed:i,tokensUsed:a,modelSpec:m&&g?`${m}:${g}`:null}}let me=he.map(we=>{let Se=we.function.name,fe=_d(we.function.arguments),Pe=we.id||`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!fe)return Promise.resolve({role:"tool",content:`ERROR: Malformed tool arguments for ${Se}`,tool_call_id:Pe});let w=null;if(Tw.has(Se)&&fe.path){let k=require("path"),N=k.isAbsolute(fe.path)?fe.path:k.resolve(process.cwd(),fe.path);if(t._readOnlyFiles&&t._readOnlyFiles.length>0){let T=k.relative(process.cwd(),N);if(t._readOnlyFiles.some(J=>T===J||T.startsWith(J+"/")||N===J||N.startsWith(J+"/")))return Promise.resolve({role:"tool",content:`ERROR: File '${fe.path}' is owned by another agent and is READ ONLY. Write to your own scope files instead.`,tool_call_id:Pe})}if(c.has(N)||!Ew(N,r))return Promise.resolve({role:"tool",content:`ERROR: File '${fe.path}' is locked by another operation. Try a different approach or skip this file.`,tool_call_id:Pe});c.add(N),w=N}return i.push(Se),e.onUpdate&&e.onUpdate({type:"tool_call",tool:Se,agentId:r}),(Se==="spawn_agents"?jd(fe,s+1):R(Se,fe,{autoConfirm:!0,silent:!0})).then(k=>{w&&(Us(w),c.delete(w));let N=String(k??"");return{role:"tool",content:N.length>2e4?N.substring(0,2e4)+`
197
- ...(truncated)`:N,tool_call_id:Pe}}).catch(k=>(w&&(Us(w),c.delete(w)),{role:"tool",content:`ERROR: ${k.message}`,tool_call_id:Pe}))}),ge=await Promise.all(me);if(U.push(...ge),V>=7&&U.length>12)try{let{compressMessage:we}=Pt(),Se=U.length-6;for(let fe=1;fe<Se;fe++)U[fe]._subAgentCompressed||(U[fe]={...we(U[fe],"light"),_subAgentCompressed:!0})}catch{}for(let we=0;we<he.length;we++){let Se=he[we];if(Se.function.name==="bash_exec"){let fe=_d(Se.function.arguments);if((ge[we]?.content||"").startsWith("ERROR")&&fe&&fe.command){let w=fe.command.replace(/\s+/g," ").trim().slice(0,100);l.set(w,(l.get(w)||0)+1)}}}e.onUpdate&&e.onUpdate(`step ${V+1}/${o}`)}for(let V of c)Us(V);let re=[...l.entries()].filter(([,V])=>V>=3).sort((V,H)=>H[1]-V[1]).slice(0,3).map(([V,H])=>`"${V}" (failed ${H}\xD7)`);return{task:t.task,status:"truncated",abortReason:"iteration_limit",repeatedFailures:re,result:U[U.length-1]?.content||"(max iterations reached)",toolsUsed:i,tokensUsed:a,modelSpec:m&&g?`${m}:${g}`:null}}catch(re){for(let V of c)Us(V);return{task:t.task,status:"failed",result:`Error: ${re.message}`,toolsUsed:i,tokensUsed:a,modelSpec:m&&g?`${m}:${g}`:null}}}async function jd(t,e=0){if(e>=2)return"ERROR: max agent nesting depth (2) reached \u2014 reviewer agents cannot spawn further agents.";let s=e===0?vw:Sw,n=e===0?Td:Rd,o=(t.agents||[]).slice(0,s);if(o.length===0)return"ERROR: No agents specified";let r=e>0?" \u21B3 ":"",i=e>0?38:44,a=o.map(u=>ma(u)),c=o.map((u,d)=>{let f=a[d],h=f.model?` [${f.model}]`:"",m=u.task.substring(0,i-h.length);return`${r}Agent ${d+1}${h}: ${m}${u.task.length>m.length?"...":""}`}),l=new kw(c);l.start();try{let u=o.map((g,b)=>{let v=a[b],O=Math.min(g.max_iterations||n,n),U=v.model?{...g,model:`${v.provider}:${v.model}`,_skipLog:!0,max_iterations:O}:{...g,_skipLog:!0,max_iterations:O};return Id(U,{onUpdate:()=>{}},e).then(L=>(l.update(b,L.status==="failed"?"error":"done"),L)).catch(L=>(l.update(b,"error"),{task:g.task,status:"failed",result:`Error: ${L.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}))}),d=await Promise.all(u);l.stop(),pa();let f=["Sub-agent results:",""],h=0,m=0;for(let g=0;g<d.length;g++){let b=d[g],v=b.status==="done"?"\u2713":b.status==="truncated"?"\u26A0":"\u2717",O=b.modelSpec?` [${b.modelSpec}]`:"";f.push(`${v} Agent ${g+1}${O}: ${b.task}`),f.push(` Status: ${b.status}`),f.push(` Tools used: ${b.toolsUsed.length>0?b.toolsUsed.join(", "):"none"}`),f.push(` Result: ${b.result}`),b.repeatedFailures&&b.repeatedFailures.length>0&&f.push(` Repeated failures: ${b.repeatedFailures.join("; ")}`),f.push(""),h+=b.tokensUsed.input,m+=b.tokensUsed.output}return f.push(`Total sub-agent tokens: ${h} input + ${m} output`),f.join(`
198
- `)}catch(u){return l.stop(),pa(),`ERROR: Sub-agent execution failed: ${u.message}`}}Dd.exports={runSubAgent:Id,executeSpawnAgents:jd,clearAllLocks:pa,classifyTask:Ld,pickModelForTier:Pd,resolveSubAgentModel:ma,classifyError:ha,isRetryableError:Ad,callWithRetry:Od,getExcludedTools:Nd,LOCK_TIMEOUT_MS:Cd,SUB_AGENT_TYPES:Md}});var va=se((Kk,Zd)=>{var Ie=require("fs"),Gt=require("path"),{atomicWrite:qd,withFileLockSync:Fd}=fn(),Ow=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 rs(){let t=Gt.join(process.cwd(),".nex","brain");return Ie.existsSync(t)||Ie.mkdirSync(t,{recursive:!0}),t}function kr(){return Gt.join(rs(),".brain-index.json")}function wa(){return Gt.join(rs(),".embeddings.json")}function Hs(){let t=Gt.join(process.cwd(),".nex","brain");if(!Ie.existsSync(t))return[];try{return Ie.readdirSync(t).filter(e=>e.endsWith(".md")&&!e.startsWith(".")).map(e=>{let s=Gt.join(t,e),n=Ie.statSync(s);return{name:e.replace(/\.md$/,""),path:s,size:n.size,modified:new Date(n.mtimeMs)}}).sort((e,s)=>s.modified-e.modified)}catch{return[]}}function Gs(t){let e={},s=t,n=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(n){let o=n[1].split(`
199
- `);for(let r of o){let i=r.match(/^(\w+):\s*(.+)$/);if(!i)continue;let a=i[1].trim(),c=i[2].trim();c.startsWith("[")&&c.endsWith("]")?e[a]=c.slice(1,-1).split(",").map(l=>l.trim()).filter(Boolean):e[a]=c}s=n[2]}return{frontmatter:e,body:s}}function Bd(t){let e=Gt.join(rs(),`${t}.md`);if(!Ie.existsSync(e))return{name:t,content:"",body:"",frontmatter:{}};let s=Ie.readFileSync(e,"utf-8"),{frontmatter:n,body:o}=Gs(s);return{name:t,content:s,body:o,frontmatter:n}}function Nw(t,e){let s=Gt.join(rs(),`${t}.md`);qd(s,e),Pw(t,e),Mw()}function Mw(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return;let t=wa();Ie.existsSync(t)&&setImmediate(async()=>{try{await zd()}catch{}})}function Lw(t){let e=Gt.join(rs(),`${t}.md`);return Ie.existsSync(e)?(Ie.unlinkSync(e),Iw(t),!0):!1}function xr(t){return t.toLowerCase().replace(/[^a-z0-9äöüß\s-]/g," ").split(/[\s-]+/).filter(e=>e.length>2&&!Ow.has(e))}function ba(t){let e={},{frontmatter:s,body:n}=Gs(t),o=Array.isArray(s.tags)?s.tags:[];for(let i of o){let a=i.toLowerCase().replace(/[^a-z0-9-]/g,"");a.length>1&&(e[a]=(e[a]||0)+5)}let r=(n||t).split(`
200
- `);for(let i of r)if(i.startsWith("#")){let a=i.replace(/^#+\s*/,"");for(let c of xr(a))e[c]=(e[c]||0)+3}for(let i of xr(n||t))e[i]=(e[i]||0)+1;return e}function _a(){let t=kr();if(!Ie.existsSync(t))return{documents:{}};try{return JSON.parse(Ie.readFileSync(t,"utf-8"))}catch{return{documents:{}}}}function xa(t){qd(kr(),JSON.stringify(t,null,2))}function Pw(t,e){Fd(kr(),()=>{let s=_a(),{frontmatter:n}=Gs(e),o=Array.isArray(n.tags)?n.tags:[];s.documents[t]={keywords:ba(e),tags:o,modified:new Date().toISOString()},xa(s)})}function Iw(t){Fd(kr(),()=>{let e=_a();delete e.documents[t],xa(e)})}function $a(){let t=Hs(),e={documents:{}};for(let s of t){let n=Ie.readFileSync(s.path,"utf-8"),{frontmatter:o}=Gs(n),r=Array.isArray(o.tags)?o.tags:[];e.documents[s.name]={keywords:ba(n),tags:r,modified:s.modified.toISOString()}}return xa(e),e}function Wd(){let t=_a(),e=Hs();for(let s of e){let n=t.documents[s.name];if(!n||new Date(n.modified)<s.modified)return $a()}for(let s of Object.keys(t.documents))if(!e.some(n=>n.name===s))return $a();return t}function Ud(t,e={}){let{topK:s=3,minScore:n=.1}=e,o=xr(t);if(o.length===0)return[];let r=Wd(),i=[];for(let[a,c]of Object.entries(r.documents)){let l=0;for(let u of o){c.keywords[u]&&(l+=c.keywords[u]);for(let[d,f]of Object.entries(c.keywords))d!==u&&d.length>3&&u.length>3&&(d.includes(u)||u.includes(d))&&(l+=f*.3)}l>=n&&i.push({name:a,score:l})}return i.sort((a,c)=>c.score-a.score),i.slice(0,s)}var Hd=process.env.NEX_EMBED_MODEL||"nomic-embed-text",ya=400,jw=50;async function Gd(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return!1;try{let t=process.env.OLLAMA_HOST||"http://localhost:11434",e=require("http"),s=require("https"),n=new URL(`${t}/api/tags`),o=n.protocol==="https:"?s:e;return((await new Promise((a,c)=>{let l=o.get(n.toString(),{timeout:2e3},u=>{let d="";u.on("data",f=>d+=f),u.on("end",()=>{try{a(JSON.parse(d))}catch{c(new Error("bad json"))}})});l.on("error",c),l.on("timeout",()=>{l.destroy(),c(new Error("timeout"))})})).models||[]).map(a=>a.name).some(a=>a.startsWith(Hd.split(":")[0]))}catch{return!1}}async function ka(t){let e=process.env.OLLAMA_HOST||"http://localhost:11434",s=require("http"),n=require("https"),o=new URL(`${e}/api/embeddings`),r=o.protocol==="https:"?n:s,i=JSON.stringify({model:Hd,prompt:t});return new Promise((a,c)=>{let l=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){c(f)}})});l.on("error",c),l.on("timeout",()=>{l.destroy(),c(new Error("embedding timeout"))}),l.write(i),l.end()})}function Yd(t,e){if(!t||!e||t.length!==e.length)return 0;let s=0,n=0,o=0;for(let i=0;i<t.length;i++)s+=t[i]*e[i],n+=t[i]*t[i],o+=e[i]*e[i];let r=Math.sqrt(n)*Math.sqrt(o);return r===0?0:s/r}function Kd(t){let e=t.split(/\s+/),s=[],n=0;for(;n<e.length;){let o=e.slice(n,n+ya).join(" ");if(s.push({text:o,offset:n}),n+ya>=e.length)break;n+=ya-jw}return s}async function zd(){let t=Hs(),e={documents:{}},s=wa();if(Ie.existsSync(s))try{e=JSON.parse(Ie.readFileSync(s,"utf-8"))}catch{}for(let n of t){let o=e.documents[n.name];if(o&&new Date(o.modified)>=n.modified)continue;let r=Ie.readFileSync(n.path,"utf-8"),i=Kd(r),a=[];for(let c of i){let l=await ka(c.text);a.push({text:c.text,embedding:l,offset:c.offset})}e.documents[n.name]={chunks:a,modified:n.modified.toISOString()}}for(let n of Object.keys(e.documents))t.some(o=>o.name===n)||delete e.documents[n];return Ie.writeFileSync(s,JSON.stringify(e),"utf-8"),e}async function Xd(t,e={}){let{topK:s=3,minSimilarity:n=.3}=e,o=wa();if(!Ie.existsSync(o))return[];let r;try{r=JSON.parse(Ie.readFileSync(o,"utf-8"))}catch{return[]}let i=await ka(t),a=[];for(let[c,l]of Object.entries(r.documents||{})){let u=0,d="";for(let f of l.chunks||[]){let h=Yd(i,f.embedding);h>u&&(u=h,d=f.text)}u>=n&&a.push({name:c,score:u,bestChunk:d})}return a.sort((c,l)=>l.score-c.score),a.slice(0,s)}function Vd(t,e,s={}){let{k:n=60,topK:o=3}=s,r={};return t.forEach((i,a)=>{r[i.name]=(r[i.name]||0)+1/(n+a+1)}),e.forEach((i,a)=>{r[i.name]=(r[i.name]||0)+1/(n+a+1)}),Object.entries(r).map(([i,a])=>({name:i,score:a})).sort((i,a)=>a.score-i.score).slice(0,o)}async function Jd(t,e={}){let{topK:s=3,minScore:n=.1}=e,o=Ud(t,{topK:s,minScore:n}),r=o;if(process.env.NEX_BRAIN_EMBEDDINGS!=="false")try{if(await Gd()){let a=await Xd(t,{topK:s});r=Vd(o,a,{topK:s})}}catch{}return r.map(i=>{let a=Bd(i.name),c=(a.body||a.content||"").slice(0,300).replace(/\n+/g," ")+"...";return{name:i.name,score:i.score,content:a.content,excerpt:c}})}var os={queryKey:null,result:null,ts:0},Dw=3e5;async function qw(t){if(!t||!t.trim())return"";let e=Gt.join(process.cwd(),".nex","brain");if(!Ie.existsSync(e)||Hs().length===0)return"";let n=t.trim().toLowerCase().slice(0,200);if(os.result!==null&&os.queryKey===n&&Date.now()-os.ts<Dw)return os.result;let o;try{o=await Jd(t,{topK:3})}catch{return""}if(!o||o.length===0)return"";let r;try{r=Pt().estimateTokens}catch{r=u=>Math.ceil(u.length/4)}let i=25e3,a=[],c=0;for(let u of o){let d=u.content||"",f=r(d);if(c+f>i){let m=i-c;if(m<100)break;let g=m/f;d=d.slice(0,Math.floor(d.length*g))+`
226
+ `:"")+u+f}];G.push({role:"user",content:t.task});let{TOOL_DEFINITIONS:L,executeTool:P}=ts(),C=Gd(s),Z=jw(L.filter(ue=>!C.has(ue.function.name)),b);if(d&&d.allowedTools&&(Z=Z.filter(ue=>d.allowedTools.has(ue.function.name))),m&&!t._skipLog){let ue=b?` (${b})`:"";process.stderr.write(` [sub-agent: ${g}:${m}${ue}]
227
+ `)}let Y={};g&&(Y.provider=g),m&&(Y.model=m);try{for(let ie=0;ie<o;ie++){let se=await Yd(G,Z,Y);if(!se||typeof se!="object")throw new Error("Empty or invalid response from provider");{let fe=g||kr(),$e=m||Od();if(se.usage){let pe=se.usage.prompt_tokens||0,Re=se.usage.completion_tokens||0;a.input+=pe,a.output+=Re,Id(fe,$e,pe,Re)}else{let pe=se.content||"",Re=G.map(v=>typeof v.content=="string"?v.content:Array.isArray(v.content)?v.content.map(O=>typeof O=="string"?O:O.text||"").join(""):"").join(" "),w=Dd(Re),I=Dd(pe);a.input+=w,a.output+=I,a._estimated=!0,Id(fe,$e,w,I)}}let T=se.content||"",Te=se.tool_calls,K={role:"assistant",content:T||""};if(Te&&Te.length>0&&(K.tool_calls=Te),G.push(K),!Te||Te.length===0){for(let fe of c)Gs(fe);return{task:t.task,status:"done",result:T||"(no response)",toolsUsed:i,tokensUsed:a,modelSpec:g&&m?`${g}:${m}`:null}}let X=Te.map(fe=>{let $e=fe.function.name,pe=Pd(fe.function.arguments),Re=fe.id||`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!pe)return Promise.resolve({role:"tool",content:`ERROR: Malformed tool arguments for ${$e}`,tool_call_id:Re});let w=null;if(Uw.has($e)&&pe.path){let v=require("path"),O=v.isAbsolute(pe.path)?pe.path:v.resolve(process.cwd(),pe.path);if(t._readOnlyFiles&&t._readOnlyFiles.length>0){let R=v.relative(process.cwd(),O);if(t._readOnlyFiles.some(H=>R===H||R.startsWith(H+"/")||O===H||O.startsWith(H+"/")))return Promise.resolve({role:"tool",content:`ERROR: File '${pe.path}' is owned by another agent and is READ ONLY. Write to your own scope files instead.`,tool_call_id:Re})}if(c.has(O)||!Ww(O,r))return Promise.resolve({role:"tool",content:`ERROR: File '${pe.path}' is locked by another operation. Try a different approach or skip this file.`,tool_call_id:Re});c.add(O),w=O}return i.push($e),e.onUpdate&&e.onUpdate({type:"tool_call",tool:$e,agentId:r}),($e==="spawn_agents"?Jd(pe,s+1):P($e,pe,{autoConfirm:!0,silent:!0})).then(v=>{w&&(Gs(w),c.delete(w));let O=String(v??"");return{role:"tool",content:O.length>2e4?O.substring(0,2e4)+`
228
+ ...(truncated)`:O,tool_call_id:Re}}).catch(v=>(w&&(Gs(w),c.delete(w)),{role:"tool",content:`ERROR: ${v.message}`,tool_call_id:Re}))}),me=await Promise.all(X);if(G.push(...me),ie>=7&&G.length>12)try{let{compressMessage:fe}=It(),$e=G.length-6;for(let pe=1;pe<$e;pe++)G[pe]._subAgentCompressed||(G[pe]={...fe(G[pe],"light"),_subAgentCompressed:!0})}catch{}for(let fe=0;fe<Te.length;fe++){let $e=Te[fe];if($e.function.name==="bash_exec"){let pe=Pd($e.function.arguments);if((me[fe]?.content||"").startsWith("ERROR")&&pe&&pe.command){let w=pe.command.replace(/\s+/g," ").trim().slice(0,100);l.set(w,(l.get(w)||0)+1)}}}e.onUpdate&&e.onUpdate(`step ${ie+1}/${o}`)}for(let ie of c)Gs(ie);let ue=[...l.entries()].filter(([,ie])=>ie>=3).sort((ie,se)=>se[1]-ie[1]).slice(0,3).map(([ie,se])=>`"${ie}" (failed ${se}\xD7)`);return{task:t.task,status:"truncated",abortReason:"iteration_limit",repeatedFailures:ue,result:G[G.length-1]?.content||"(max iterations reached)",toolsUsed:i,tokensUsed:a,modelSpec:g&&m?`${g}:${m}`:null}}catch(ue){for(let ie of c)Gs(ie);return{task:t.task,status:"failed",result:`Error: ${ue.message}`,toolsUsed:i,tokensUsed:a,modelSpec:g&&m?`${g}:${m}`:null}}}async function Jd(t,e=0){if(e>=2)return"ERROR: max agent nesting depth (2) reached \u2014 reviewer agents cannot spawn further agents.";let s=e===0?Fw:Bw,n=e===0?Bd:Wd,o=(t.agents||[]).slice(0,s);if(o.length===0)return"ERROR: No agents specified";let r=e>0?" \u21B3 ":"",i=e>0?38:44,a=o.map(u=>va(u)),c=o.map((u,d)=>{let f=a[d],h=f.model?` [${f.model}]`:"",g=u.task.substring(0,i-h.length);return`${r}Agent ${d+1}${h}: ${g}${u.task.length>g.length?"...":""}`}),l=new qw(c);l.start();try{let u=o.map((m,b)=>{let x=a[b],j=Math.min(m.max_iterations||n,n),G=x.model?{...m,model:`${x.provider}:${x.model}`,_skipLog:!0,max_iterations:j}:{...m,_skipLog:!0,max_iterations:j};return Vd(G,{onUpdate:()=>{}},e).then(L=>(l.update(b,L.status==="failed"?"error":"done"),L)).catch(L=>(l.update(b,"error"),{task:m.task,status:"failed",result:`Error: ${L.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}))}),d=await Promise.all(u);l.stop(),xa();let f=["Sub-agent results:",""],h=0,g=0;for(let m=0;m<d.length;m++){let b=d[m],x=b.status==="done"?"\u2713":b.status==="truncated"?"\u26A0":"\u2717",j=b.modelSpec?` [${b.modelSpec}]`:"";f.push(`${x} Agent ${m+1}${j}: ${b.task}`),f.push(` Status: ${b.status}`),f.push(` Tools used: ${b.toolsUsed.length>0?b.toolsUsed.join(", "):"none"}`),f.push(` Result: ${b.result}`),b.repeatedFailures&&b.repeatedFailures.length>0&&f.push(` Repeated failures: ${b.repeatedFailures.join("; ")}`),f.push(""),h+=b.tokensUsed.input,g+=b.tokensUsed.output}return f.push(`Total sub-agent tokens: ${h} input + ${g} output`),f.join(`
229
+ `)}catch(u){return l.stop(),xa(),`ERROR: Sub-agent execution failed: ${u.message}`}}Zd.exports={runSubAgent:Vd,executeSpawnAgents:Jd,clearAllLocks:xa,classifyTask:zd,pickModelForTier:Xd,resolveSubAgentModel:va,classifyError:ka,isRetryableError:Hd,callWithRetry:Yd,getExcludedTools:Gd,LOCK_TIMEOUT_MS:Ud,SUB_AGENT_TYPES:Kd}});var Ma=re((hv,pf)=>{var je=require("fs"),Gt=require("path"),{atomicWrite:Qd,withFileLockSync:ef}=mn(),Kw=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 ls(){let t=Gt.join(process.cwd(),".nex","brain");return je.existsSync(t)||je.mkdirSync(t,{recursive:!0}),t}function Er(){return Gt.join(ls(),".brain-index.json")}function Ra(){return Gt.join(ls(),".embeddings.json")}function Ks(){let t=Gt.join(process.cwd(),".nex","brain");if(!je.existsSync(t))return[];try{return je.readdirSync(t).filter(e=>e.endsWith(".md")&&!e.startsWith(".")).map(e=>{let s=Gt.join(t,e),n=je.statSync(s);return{name:e.replace(/\.md$/,""),path:s,size:n.size,modified:new Date(n.mtimeMs)}}).sort((e,s)=>s.modified-e.modified)}catch{return[]}}function zs(t){let e={},s=t,n=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(n){let o=n[1].split(`
230
+ `);for(let r of o){let i=r.match(/^(\w+):\s*(.+)$/);if(!i)continue;let a=i[1].trim(),c=i[2].trim();c.startsWith("[")&&c.endsWith("]")?e[a]=c.slice(1,-1).split(",").map(l=>l.trim()).filter(Boolean):e[a]=c}s=n[2]}return{frontmatter:e,body:s}}function tf(t){let e=Gt.join(ls(),`${t}.md`);if(!je.existsSync(e))return{name:t,content:"",body:"",frontmatter:{}};let s=je.readFileSync(e,"utf-8"),{frontmatter:n,body:o}=zs(s);return{name:t,content:s,body:o,frontmatter:n}}function zw(t,e){let s=Gt.join(ls(),`${t}.md`);Qd(s,e),Jw(t,e),Xw()}function Xw(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return;let t=Ra();je.existsSync(t)&&setImmediate(async()=>{try{await lf()}catch{}})}function Vw(t){let e=Gt.join(ls(),`${t}.md`);return je.existsSync(e)?(je.unlinkSync(e),Zw(t),!0):!1}function Sr(t){return t.toLowerCase().replace(/[^a-z0-9äöüß\s-]/g," ").split(/[\s-]+/).filter(e=>e.length>2&&!Kw.has(e))}function Ca(t){let e={},{frontmatter:s,body:n}=zs(t),o=Array.isArray(s.tags)?s.tags:[];for(let i of o){let a=i.toLowerCase().replace(/[^a-z0-9-]/g,"");a.length>1&&(e[a]=(e[a]||0)+5)}let r=(n||t).split(`
231
+ `);for(let i of r)if(i.startsWith("#")){let a=i.replace(/^#+\s*/,"");for(let c of Sr(a))e[c]=(e[c]||0)+3}for(let i of Sr(n||t))e[i]=(e[i]||0)+1;return e}function Aa(){let t=Er();if(!je.existsSync(t))return{documents:{}};try{return JSON.parse(je.readFileSync(t,"utf-8"))}catch{return{documents:{}}}}function Oa(t){Qd(Er(),JSON.stringify(t,null,2))}function Jw(t,e){ef(Er(),()=>{let s=Aa(),{frontmatter:n}=zs(e),o=Array.isArray(n.tags)?n.tags:[];s.documents[t]={keywords:Ca(e),tags:o,modified:new Date().toISOString()},Oa(s)})}function Zw(t){ef(Er(),()=>{let e=Aa();delete e.documents[t],Oa(e)})}function Ta(){let t=Ks(),e={documents:{}};for(let s of t){let n=je.readFileSync(s.path,"utf-8"),{frontmatter:o}=zs(n),r=Array.isArray(o.tags)?o.tags:[];e.documents[s.name]={keywords:Ca(n),tags:r,modified:s.modified.toISOString()}}return Oa(e),e}function nf(){let t=Aa(),e=Ks();for(let s of e){let n=t.documents[s.name];if(!n||new Date(n.modified)<s.modified)return Ta()}for(let s of Object.keys(t.documents))if(!e.some(n=>n.name===s))return Ta();return t}function sf(t,e={}){let{topK:s=3,minScore:n=.1}=e,o=Sr(t);if(o.length===0)return[];let r=nf(),i=[];for(let[a,c]of Object.entries(r.documents)){let l=0;for(let u of o){c.keywords[u]&&(l+=c.keywords[u]);for(let[d,f]of Object.entries(c.keywords))d!==u&&d.length>3&&u.length>3&&(d.includes(u)||u.includes(d))&&(l+=f*.3)}l>=n&&i.push({name:a,score:l})}return i.sort((a,c)=>c.score-a.score),i.slice(0,s)}var of=process.env.NEX_EMBED_MODEL||"nomic-embed-text",Ea=400,Qw=50;async function rf(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return!1;try{let t=process.env.OLLAMA_HOST||"http://localhost:11434",e=require("http"),s=require("https"),n=new URL(`${t}/api/tags`),o=n.protocol==="https:"?s:e;return((await new Promise((a,c)=>{let l=o.get(n.toString(),{timeout:2e3},u=>{let d="";u.on("data",f=>d+=f),u.on("end",()=>{try{a(JSON.parse(d))}catch{c(new Error("bad json"))}})});l.on("error",c),l.on("timeout",()=>{l.destroy(),c(new Error("timeout"))})})).models||[]).map(a=>a.name).some(a=>a.startsWith(of.split(":")[0]))}catch{return!1}}async function Na(t){let e=process.env.OLLAMA_HOST||"http://localhost:11434",s=require("http"),n=require("https"),o=new URL(`${e}/api/embeddings`),r=o.protocol==="https:"?n:s,i=JSON.stringify({model:of,prompt:t});return new Promise((a,c)=>{let l=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){c(f)}})});l.on("error",c),l.on("timeout",()=>{l.destroy(),c(new Error("embedding timeout"))}),l.write(i),l.end()})}function af(t,e){if(!t||!e||t.length!==e.length)return 0;let s=0,n=0,o=0;for(let i=0;i<t.length;i++)s+=t[i]*e[i],n+=t[i]*t[i],o+=e[i]*e[i];let r=Math.sqrt(n)*Math.sqrt(o);return r===0?0:s/r}function cf(t){let e=t.split(/\s+/),s=[],n=0;for(;n<e.length;){let o=e.slice(n,n+Ea).join(" ");if(s.push({text:o,offset:n}),n+Ea>=e.length)break;n+=Ea-Qw}return s}async function lf(){let t=Ks(),e={documents:{}},s=Ra();if(je.existsSync(s))try{e=JSON.parse(je.readFileSync(s,"utf-8"))}catch{}for(let n of t){let o=e.documents[n.name];if(o&&new Date(o.modified)>=n.modified)continue;let r=je.readFileSync(n.path,"utf-8"),i=cf(r),a=[];for(let c of i){let l=await Na(c.text);a.push({text:c.text,embedding:l,offset:c.offset})}e.documents[n.name]={chunks:a,modified:n.modified.toISOString()}}for(let n of Object.keys(e.documents))t.some(o=>o.name===n)||delete e.documents[n];return je.writeFileSync(s,JSON.stringify(e),"utf-8"),e}async function uf(t,e={}){let{topK:s=3,minSimilarity:n=.3}=e,o=Ra();if(!je.existsSync(o))return[];let r;try{r=JSON.parse(je.readFileSync(o,"utf-8"))}catch{return[]}let i=await Na(t),a=[];for(let[c,l]of Object.entries(r.documents||{})){let u=0,d="";for(let f of l.chunks||[]){let h=af(i,f.embedding);h>u&&(u=h,d=f.text)}u>=n&&a.push({name:c,score:u,bestChunk:d})}return a.sort((c,l)=>l.score-c.score),a.slice(0,s)}function df(t,e,s={}){let{k:n=60,topK:o=3}=s,r={};return t.forEach((i,a)=>{r[i.name]=(r[i.name]||0)+1/(n+a+1)}),e.forEach((i,a)=>{r[i.name]=(r[i.name]||0)+1/(n+a+1)}),Object.entries(r).map(([i,a])=>({name:i,score:a})).sort((i,a)=>a.score-i.score).slice(0,o)}async function ff(t,e={}){let{topK:s=3,minScore:n=.1}=e,o=sf(t,{topK:s,minScore:n}),r=o;if(process.env.NEX_BRAIN_EMBEDDINGS!=="false")try{if(await rf()){let a=await uf(t,{topK:s});r=df(o,a,{topK:s})}}catch{}return r.map(i=>{let a=tf(i.name),c=(a.body||a.content||"").slice(0,300).replace(/\n+/g," ")+"...";return{name:i.name,score:i.score,content:a.content,excerpt:c}})}var cs={queryKey:null,result:null,ts:0},e0=3e5;async function t0(t){if(!t||!t.trim())return"";let e=Gt.join(process.cwd(),".nex","brain");if(!je.existsSync(e)||Ks().length===0)return"";let n=t.trim().toLowerCase().slice(0,200);if(cs.result!==null&&cs.queryKey===n&&Date.now()-cs.ts<e0)return cs.result;let o;try{o=await ff(t,{topK:3})}catch{return""}if(!o||o.length===0)return"";let r;try{r=It().estimateTokens}catch{r=u=>Math.ceil(u.length/4)}let i=25e3,a=[],c=0;for(let u of o){let d=u.content||"",f=r(d);if(c+f>i){let g=i-c;if(g<100)break;let m=g/f;d=d.slice(0,Math.floor(d.length*m))+`
201
232
  ...(truncated)`}let h=typeof u.score=="number"?u.score.toFixed(2):String(u.score);if(a.push(`--- ${u.name} (relevance: ${h}) ---
202
- ${d}`),c+=r(d),c>=i)break}if(a.length===0)return os={queryKey:n,result:"",ts:Date.now()},"";let l=`KNOWLEDGE BASE (auto-selected):
233
+ ${d}`),c+=r(d),c>=i)break}if(a.length===0)return cs={queryKey:n,result:"",ts:Date.now()},"";let l=`KNOWLEDGE BASE (auto-selected):
203
234
 
204
235
  ${a.join(`
205
236
 
206
- `)}`;return os={queryKey:n,result:l,ts:Date.now()},l}Zd.exports={getBrainDir:rs,listDocuments:Hs,readDocument:Bd,writeDocument:Nw,removeDocument:Lw,buildIndex:$a,getIndex:Wd,query:Jd,getBrainContext:qw,isEmbeddingAvailable:Gd,generateEmbedding:ka,buildEmbeddingIndex:zd,semanticQuery:Xd,cosineSimilarity:Yd,_keywordQuery:Ud,_extractKeywords:ba,_chunkText:Kd,parseFrontmatter:Gs,tokenize:xr,_fuseResults:Vd}});var zs=se((zk,df)=>{var Me=require("fs"),dt=require("path"),Fw=require("os"),{atomicWrite:vr,withFileLockSync:Qd}=fn(),Ys=["user","feedback","project","reference"],Bw=50;function wn(){return dt.join(process.cwd(),".nex","memory")}function is(){return dt.join(wn(),"memory.json")}function ef(){return dt.join(wn(),"MEMORY.md")}function Ww(){return dt.join(process.cwd(),"NEX.md")}function tf(){return dt.join(Fw.homedir(),".nex","NEX.md")}function Sr(){let t=wn();Me.existsSync(t)||Me.mkdirSync(t,{recursive:!0})}function nf(t){let e=dt.join(wn(),t);return Me.existsSync(e)||Me.mkdirSync(e,{recursive:!0}),e}function Ks(){let t=is();if(!Me.existsSync(t))return{};try{return JSON.parse(Me.readFileSync(t,"utf-8"))}catch{return{}}}function sf(t){Sr(),vr(is(),JSON.stringify(t,null,2))}function of(){let t=is();if(!Me.existsSync(t))return;let e=Ks(),s=Object.keys(e);if(s.length===0){try{Me.renameSync(t,t+".bak")}catch{}return}for(let n of s){let o=e[n],r=o.value||String(o),i=n.replace(/[^a-z0-9_-]/gi,"-").toLowerCase().replace(/-+/g,"-").replace(/^-|-$/g,"");if(!i)continue;let a=nf("project"),c=dt.join(a,`${i}.md`),l=r.split(`
237
+ `)}`;return cs={queryKey:n,result:l,ts:Date.now()},l}pf.exports={getBrainDir:ls,listDocuments:Ks,readDocument:tf,writeDocument:zw,removeDocument:Vw,buildIndex:Ta,getIndex:nf,query:ff,getBrainContext:t0,isEmbeddingAvailable:rf,generateEmbedding:Na,buildEmbeddingIndex:lf,semanticQuery:uf,cosineSimilarity:af,_keywordQuery:sf,_extractKeywords:Ca,_chunkText:cf,parseFrontmatter:zs,tokenize:Sr,_fuseResults:df}});var Js=re((mv,Sf)=>{var Le=require("fs"),ft=require("path"),n0=require("os"),{atomicWrite:Tr,withFileLockSync:hf}=mn(),Xs=["user","feedback","project","reference"],s0=50;function kn(){return ft.join(process.cwd(),".nex","memory")}function us(){return ft.join(kn(),"memory.json")}function mf(){return ft.join(kn(),"MEMORY.md")}function o0(){return ft.join(process.cwd(),"NEX.md")}function gf(){return ft.join(n0.homedir(),".nex","NEX.md")}function Rr(){let t=kn();Le.existsSync(t)||Le.mkdirSync(t,{recursive:!0})}function yf(t){let e=ft.join(kn(),t);return Le.existsSync(e)||Le.mkdirSync(e,{recursive:!0}),e}function Vs(){let t=us();if(!Le.existsSync(t))return{};try{return JSON.parse(Le.readFileSync(t,"utf-8"))}catch{return{}}}function $f(t){Rr(),Tr(us(),JSON.stringify(t,null,2))}function wf(){let t=us();if(!Le.existsSync(t))return;let e=Vs(),s=Object.keys(e);if(s.length===0){try{Le.renameSync(t,t+".bak")}catch{}return}for(let n of s){let o=e[n],r=o.value||String(o),i=n.replace(/[^a-z0-9_-]/gi,"-").toLowerCase().replace(/-+/g,"-").replace(/^-|-$/g,"");if(!i)continue;let a=yf("project"),c=ft.join(a,`${i}.md`),l=r.split(`
207
238
  `)[0].slice(0,100),u=`---
208
239
  name: ${n}
209
240
  description: ${l}
@@ -211,7 +242,7 @@ type: project
211
242
  ---
212
243
 
213
244
  ${r}
214
- `;vr(c,u)}Er();try{Me.renameSync(t,t+".bak")}catch{}}function Uw(t,e,s,n){if(!Ys.includes(t))return{ok:!1,path:"",error:`Invalid type: ${t}. Must be one of: ${Ys.join(", ")}`};if(!e||typeof e!="string")return{ok:!1,path:"",error:"name must be a non-empty string"};if(!s||typeof s!="string"||s.trim().length<5)return{ok:!1,path:"",error:"content must be at least 5 characters"};let o=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase().replace(/-+/g,"-").replace(/^-|-$/g,"");if(!o)return{ok:!1,path:"",error:"name produces empty slug after sanitization"};let r=nf(t),i=dt.join(r,`${o}.md`);if(Me.existsSync(i))try{if(Sa(Me.readFileSync(i,"utf-8")).body.slice(0,200)===s.slice(0,200))return{ok:!0,path:i,updated:!1}}catch{}let a=n||s.split(`
245
+ `;Tr(c,u)}Cr();try{Le.renameSync(t,t+".bak")}catch{}}function r0(t,e,s,n){if(!Xs.includes(t))return{ok:!1,path:"",error:`Invalid type: ${t}. Must be one of: ${Xs.join(", ")}`};if(!e||typeof e!="string")return{ok:!1,path:"",error:"name must be a non-empty string"};if(!s||typeof s!="string"||s.trim().length<5)return{ok:!1,path:"",error:"content must be at least 5 characters"};let o=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase().replace(/-+/g,"-").replace(/^-|-$/g,"");if(!o)return{ok:!1,path:"",error:"name produces empty slug after sanitization"};let r=yf(t),i=ft.join(r,`${o}.md`);if(Le.existsSync(i))try{if(La(Le.readFileSync(i,"utf-8")).body.slice(0,200)===s.slice(0,200))return{ok:!0,path:i,updated:!1}}catch{}let a=n||s.split(`
215
246
  `)[0].slice(0,100),c=`---
216
247
  name: ${e}
217
248
  description: ${a}
@@ -219,11 +250,11 @@ type: ${t}
219
250
  ---
220
251
 
221
252
  ${s}
222
- `;return vr(i,c),Er(),{ok:!0,path:i,updated:!0}}function Hw(t,e){if(!Ys.includes(t))return!1;let s=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase(),n=dt.join(wn(),t,`${s}.md`);if(!Me.existsSync(n))return!1;try{return Me.unlinkSync(n),Er(),!0}catch{return!1}}function Sa(t){let e=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(!e)return{name:"",description:"",type:"",body:t.trim()};let s=e[1],n=(e[2]||"").trim(),o=r=>{let i=s.match(new RegExp(`^${r}:\\s*(.+)$`,"m"));return i?i[1].trim():""};return{name:o("name"),description:o("description"),type:o("type"),body:n}}function rf(){let t=[],e=wn();for(let s of Ys){let n=dt.join(e,s);if(!Me.existsSync(n))continue;let o;try{o=Me.readdirSync(n).filter(r=>r.endsWith(".md"))}catch{continue}for(let r of o){let i=dt.join(n,r);try{let a=Me.readFileSync(i,"utf-8"),c=Sa(a);t.push({type:s,name:c.name||dt.basename(r,".md"),description:c.description,filePath:i})}catch{}}}return t}function Er(){let t=rf(),e=["# Project Memory Index",""];for(let s of t){if(e.length>=Bw+2)break;let n=`${s.type}/${dt.basename(s.filePath)}`;e.push(`- [${s.name}](${n}) \u2014 ${s.description||"(no description)"}`)}Sr(),vr(ef(),e.join(`
253
+ `;return Tr(i,c),Cr(),{ok:!0,path:i,updated:!0}}function i0(t,e){if(!Xs.includes(t))return!1;let s=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase(),n=ft.join(kn(),t,`${s}.md`);if(!Le.existsSync(n))return!1;try{return Le.unlinkSync(n),Cr(),!0}catch{return!1}}function La(t){let e=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(!e)return{name:"",description:"",type:"",body:t.trim()};let s=e[1],n=(e[2]||"").trim(),o=r=>{let i=s.match(new RegExp(`^${r}:\\s*(.+)$`,"m"));return i?i[1].trim():""};return{name:o("name"),description:o("description"),type:o("type"),body:n}}function bf(){let t=[],e=kn();for(let s of Xs){let n=ft.join(e,s);if(!Le.existsSync(n))continue;let o;try{o=Le.readdirSync(n).filter(r=>r.endsWith(".md"))}catch{continue}for(let r of o){let i=ft.join(n,r);try{let a=Le.readFileSync(i,"utf-8"),c=La(a);t.push({type:s,name:c.name||ft.basename(r,".md"),description:c.description,filePath:i})}catch{}}}return t}function Cr(){let t=bf(),e=["# Project Memory Index",""];for(let s of t){if(e.length>=s0+2)break;let n=`${s.type}/${ft.basename(s.filePath)}`;e.push(`- [${s.name}](${n}) \u2014 ${s.description||"(no description)"}`)}Rr(),Tr(mf(),e.join(`
223
254
  `)+`
224
- `)}function af(){let t=ef();if(!Me.existsSync(t))return"";try{return Me.readFileSync(t,"utf-8").trim()}catch{return""}}function Gw(t,e){Sr(),Qd(is(),()=>{let s=Ks();s[t]={value:e,updatedAt:new Date().toISOString()},sf(s)})}function Yw(t){let e=Ks();return e[t]?e[t].value:null}function Kw(t){return Sr(),Qd(is(),()=>{let e=Ks();return t in e?(delete e[t],sf(e),!0):!1})}function cf(){let t=Ks();return Object.entries(t).map(([e,s])=>({key:e,value:s.value,updatedAt:s.updatedAt}))}function lf(){let t=tf();if(!Me.existsSync(t))return"";try{return Me.readFileSync(t,"utf-8").trim()}catch{return""}}function uf(){let t=Ww();if(!Me.existsSync(t))return"";try{return Me.readFileSync(t,"utf-8").trim()}catch{return""}}function zw(){of();let t=[],e=lf();e&&t.push(`GLOBAL INSTRUCTIONS (~/.nex/NEX.md):
225
- ${e}`);let s=uf();s&&t.push(`PROJECT INSTRUCTIONS (NEX.md):
226
- ${s}`);let n="",o=af();if(o)n=o;else{let d=cf();d.length>0&&(n=`PROJECT MEMORY:
255
+ `)}function _f(){let t=mf();if(!Le.existsSync(t))return"";try{return Le.readFileSync(t,"utf-8").trim()}catch{return""}}function a0(t,e){Rr(),hf(us(),()=>{let s=Vs();s[t]={value:e,updatedAt:new Date().toISOString()},$f(s)})}function c0(t){let e=Vs();return e[t]?e[t].value:null}function l0(t){return Rr(),hf(us(),()=>{let e=Vs();return t in e?(delete e[t],$f(e),!0):!1})}function xf(){let t=Vs();return Object.entries(t).map(([e,s])=>({key:e,value:s.value,updatedAt:s.updatedAt}))}function kf(){let t=gf();if(!Le.existsSync(t))return"";try{return Le.readFileSync(t,"utf-8").trim()}catch{return""}}function vf(){let t=o0();if(!Le.existsSync(t))return"";try{return Le.readFileSync(t,"utf-8").trim()}catch{return""}}function u0(){wf();let t=[],e=kf();e&&t.push(`GLOBAL INSTRUCTIONS (~/.nex/NEX.md):
256
+ ${e}`);let s=vf();s&&t.push(`PROJECT INSTRUCTIONS (NEX.md):
257
+ ${s}`);let n="",o=_f();if(o)n=o;else{let d=xf();d.length>0&&(n=`PROJECT MEMORY:
227
258
  ${d.map(h=>` ${h.key}: ${h.value}`).join(`
228
259
  `)}`)}let r=t.join(`
229
260
 
@@ -232,209 +263,209 @@ ${d.map(h=>` ${h.key}: ${h.value}`).join(`
232
263
  `}n=f.trimEnd()+`
233
264
  [Memory index truncated \u2014 use delete_memory to prune old entries]`}else n.length>l&&(n="");let u=[...t];return n&&u.push(n),u.length>0&&u.push(i),u.join(`
234
265
 
235
- `)}df.exports={saveMemory:Uw,deleteMemory:Hw,scanMemories:rf,rebuildIndex:Er,loadMemoryIndex:af,remember:Gw,recall:Yw,forget:Kw,listMemories:cf,loadGlobalInstructions:lf,loadProjectInstructions:uf,getMemoryContext:zw,_getMemoryDir:wn,_getMemoryFile:is,_getGlobalNexMdPath:tf,_parseMemoryFile:Sa,_migrateIfNeeded:of,VALID_TYPES:Ys}});var yf=se((Xk,gf)=>{var Xs=require("fs"),Ea=require("path"),Ta=process.env.NEX_AUDIT!=="false",bn=null;function ff(){return bn||(bn=Ea.join(process.cwd(),".nex","audit"),Xs.existsSync(bn)||Xs.mkdirSync(bn,{recursive:!0}),bn)}function pf(){let t=new Date().toISOString().split("T")[0];return Ea.join(ff(),`${t}.jsonl`)}function Xw(t){if(Ta)try{let e={timestamp:new Date().toISOString(),tool:t.tool,args:hf(t.args),resultLength:typeof t.result=="string"?t.result.length:0,resultPreview:typeof t.result=="string"?t.result.substring(0,200):"",duration:t.duration||0,success:t.success!==!1,model:t.model||null,provider:t.provider||null},s=JSON.stringify(e)+`
236
- `;Xs.appendFileSync(pf(),s,"utf-8")}catch{}}function hf(t){if(!t||typeof t!="object")return{};let e={};for(let[s,n]of Object.entries(t))/key|token|password|secret|credential/i.test(s)?e[s]="***":typeof n=="string"&&n.length>500?e[s]=n.substring(0,500)+`... (${n.length} chars)`:e[s]=n;return e}function mf(t={}){let e=ff(),s=t.days||1,n=[];for(let o=0;o<s;o++){let r=t.date||new Date(Date.now()-o*864e5).toISOString().split("T")[0],i=Ea.join(e,`${r}.jsonl`);if(!Xs.existsSync(i))continue;let a=Xs.readFileSync(i,"utf-8").split(`
237
- `).filter(c=>c.trim());for(let c of a)try{let l=JSON.parse(c);if(t.tool&&l.tool!==t.tool)continue;n.push(l)}catch{}if(t.date)break}return n}function Vw(t=1){let e=mf({days:t});if(e.length===0)return{totalCalls:0,byTool:{},avgDuration:0,successRate:1};let s={},n=0,o=0;for(let r of e)s[r.tool]=(s[r.tool]||0)+1,n+=r.duration||0,r.success&&o++;return{totalCalls:e.length,byTool:s,avgDuration:Math.round(n/e.length),successRate:o/e.length}}function Jw(t){Ta=t}function Zw(){return Ta}function Qw(){bn=null}gf.exports={logToolExecution:Xw,sanitizeArgs:hf,readAuditLog:mf,getAuditSummary:Vw,setAuditEnabled:Jw,isAuditEnabled:Zw,getAuditLogPath:pf,_reset:Qw}});var Rf=se((Zk,Tf)=>{var je=require("fs").promises,$f=require("fs"),ve=require("path"),Ee=require("util").promisify(require("child_process").exec),Ra=require("util").promisify(require("child_process").execFile),{spawnSync:e0}=require("child_process"),Ca=require("axios"),{isForbidden:t0,isSSHForbidden:n0,isDangerous:s0,isCritical:wf,isBashPathForbidden:o0,confirm:kt}=Es(),{showClaudeDiff:Tr,showClaudeNewFile:r0,showEditDiff:Vk,confirmFileChange:Vs}=Vl(),{C:ae,Spinner:i0,getToolSpinnerText:a0}=Ue(),{isGitRepo:Aa,getCurrentBranch:bf,getStatus:c0,getDiff:l0}=er(),{recordChange:Rr}=iu(),{fuzzyFindText:_f,findMostSimilar:Qs}=Au(),{runDiagnostics:Js}=Nu(),{findFileInIndex:u0,getFileIndex:Jk}=sa(),{resolveProfile:$t,sshExec:ot,scpUpload:d0,scpDownload:f0}=ra(),{resolveDeployConfig:p0,loadDeployConfigs:h0}=Gu(),{getEditMode:xf}=Is(),m0=/^(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/,g0=/^ssh\s/,y0=/^ssh(?:\s+-\S+)*\s+\S+@?\S+\s+["']?[^-]/;async function ft(t){return je.access(t).then(()=>!0).catch(()=>!1)}async function Cr(t){if(!t)return{fixedPath:null,message:""};let e=t.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),s=rt(e);if(s&&await ft(s))return{fixedPath:s,message:`(auto-fixed path: ${t} \u2192 ${e})`};let n=[".js",".ts",".jsx",".tsx",".mjs",".cjs",".json"],o=ve.extname(t);if(!o)for(let i of n){let a=rt(t+i);if(a&&await ft(a))return{fixedPath:a,message:`(auto-fixed: added ${i} extension)`}}if(o){let i=t.replace(/\.[^.]+$/,"");for(let a of n){if(a===o)continue;let c=rt(i+a);if(c&&await ft(c))return{fixedPath:c,message:`(auto-fixed: ${o} \u2192 ${a})`}}}let r=ve.basename(t);if(r&&r.length>2)try{let i=u0(r).map(a=>rt(a));if(i.length===1)return{fixedPath:i[0],message:`(auto-fixed: found ${r} at ${ve.relative(process.cwd(),i[0])})`};if(i.length>1&&i.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
238
- ${i.map(c=>ve.relative(process.cwd(),c)).map(c=>` - ${c}`).join(`
239
- `)}`}}catch{}return{fixedPath:null,message:""}}function $0(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 Sf(t,e){let s=[];if(/command not found|: not found|not recognized/i.test(t)){let n=e.match(/^(\S+)/),o=n?n[1]:"";/^(npx|npm|node|yarn|pnpm|bun)$/.test(o)?s.push("HINT: Node.js/npm may not be in PATH. Check your Node.js installation."):/^(python|python3|pip|pip3)$/.test(o)?s.push("HINT: Python may not be installed. Try: brew install python3 (macOS) or apt install python3 (Linux)"):s.push(`HINT: "${o}" is not installed. Try installing it with your package manager.`)}if(/Cannot find module|MODULE_NOT_FOUND/i.test(t)){let n=t.match(/Cannot find module '([^']+)'/),o=n?n[1]:"";o&&!o.startsWith(".")&&!o.startsWith("/")?s.push(`HINT: Missing npm package "${o}". Run: npm install ${o}`):s.push("HINT: Module not found. Check the import path or run npm install.")}if(/permission denied|EACCES/i.test(t)&&s.push("HINT: Permission denied. Check file permissions or try a different approach."),/EADDRINUSE|address already in use/i.test(t)){let n=t.match(/port (\d+)|:(\d+)/),o=n?n[1]||n[2]:"";s.push(`HINT: Port ${o||""} is already in use. Kill the process or use a different port.`)}if(/SyntaxError|Unexpected token/i.test(t)&&s.push("HINT: Syntax error in the code. Check the file at the line number shown above."),/TS\d{4}:/i.test(t)&&s.push("HINT: TypeScript compilation error. Fix the type issue at the indicated line."),/Test Suites:.*failed|Tests:.*failed/i.test(t)&&s.push("HINT: Test failures detected. Read the error output above to identify failing tests."),/fatal: not a git repository/i.test(t)&&s.push("HINT: Not inside a git repository. Run git init or cd to a git project."),/^curl\b/.test(e)){let n=t.match(/curl:\s*\((\d+)\)/),o=n?parseInt(n[1],10):null;o===6||/Could not resolve host/i.test(t)?s.push("HINT: Hostname could not be resolved. Check DNS or use an IP address directly."):o===7||/Failed to connect|Connection refused/i.test(t)?s.push("HINT: Service not running or port wrong. Check if the service is up and the port is correct."):o===22||/HTTP error/i.test(t)?s.push("HINT: HTTP 4xx/5xx response. The endpoint exists but returned an error status."):o===28||/timed out/i.test(t)?s.push("HINT: Request timed out. The host may be unreachable or the service is slow."):(o===35||/SSL.*error/i.test(t))&&s.push("HINT: SSL/TLS handshake failed. Try with --insecure to bypass, or check the certificate.")}if(/remote port forwarding failed/i.test(t)){let n=t.match(/port (\d+)/),o=n?n[1]:"";s.push(`HINT: SSH remote port forwarding failed for port ${o}. The port may already be bound on the server. Check with: ssh server "ss -tuln | grep ${o}" and kill any lingering process with that port.`)}return/bind.*Cannot assign requested address|Address already in use/i.test(t)&&s.push("HINT: Port is already in use. Find the process with: ss -tuln | grep <port> and kill it, then retry."),/Connection.*timed out|ssh.*timeout/i.test(t)&&/^ssh\b/.test(e)&&s.push("HINT: SSH connection timed out. Check if the host is reachable: ping <host> and verify the port with: nc -zv <host> 22"),/spawn \/bin\/sh ENOENT|spawn sh ENOENT/i.test(t)&&s.push("HINT: The working directory was deleted during this session \u2014 bash cannot execute commands in a non-existent cwd. Previous rm/delete commands succeeded. Use list_directory or glob to verify the state instead of retrying bash."),/cp.*\$f.*\$f\.bak.*sed.*-i\.bak|sed.*-i\.bak.*cp.*\$f.*\$f\.bak/i.test(e)&&s.push('HINT: Using both cp with .bak and sed -i.bak creates double backups (.bak.bak). Choose one method: either cp "$f" "$f.bak" OR sed -i.bak, not both.'),s.length===0?t:t+`
266
+ `)}Sf.exports={saveMemory:r0,deleteMemory:i0,scanMemories:bf,rebuildIndex:Cr,loadMemoryIndex:_f,remember:a0,recall:c0,forget:l0,listMemories:xf,loadGlobalInstructions:kf,loadProjectInstructions:vf,getMemoryContext:u0,_getMemoryDir:kn,_getMemoryFile:us,_getGlobalNexMdPath:gf,_parseMemoryFile:La,_migrateIfNeeded:wf,VALID_TYPES:Xs}});var Of=re((gv,Af)=>{var Zs=require("fs"),Pa=require("path"),Ia=process.env.NEX_AUDIT!=="false",vn=null;function Ef(){return vn||(vn=Pa.join(process.cwd(),".nex","audit"),Zs.existsSync(vn)||Zs.mkdirSync(vn,{recursive:!0}),vn)}function Tf(){let t=new Date().toISOString().split("T")[0];return Pa.join(Ef(),`${t}.jsonl`)}function d0(t){if(Ia)try{let e={timestamp:new Date().toISOString(),tool:t.tool,args:Rf(t.args),resultLength:typeof t.result=="string"?t.result.length:0,resultPreview:typeof t.result=="string"?t.result.substring(0,200):"",duration:t.duration||0,success:t.success!==!1,model:t.model||null,provider:t.provider||null},s=JSON.stringify(e)+`
267
+ `;Zs.appendFileSync(Tf(),s,"utf-8")}catch{}}function Rf(t){if(!t||typeof t!="object")return{};let e={};for(let[s,n]of Object.entries(t))/key|token|password|secret|credential/i.test(s)?e[s]="***":typeof n=="string"&&n.length>500?e[s]=n.substring(0,500)+`... (${n.length} chars)`:e[s]=n;return e}function Cf(t={}){let e=Ef(),s=t.days||1,n=[];for(let o=0;o<s;o++){let r=t.date||new Date(Date.now()-o*864e5).toISOString().split("T")[0],i=Pa.join(e,`${r}.jsonl`);if(!Zs.existsSync(i))continue;let a=Zs.readFileSync(i,"utf-8").split(`
268
+ `).filter(c=>c.trim());for(let c of a)try{let l=JSON.parse(c);if(t.tool&&l.tool!==t.tool)continue;n.push(l)}catch{}if(t.date)break}return n}function f0(t=1){let e=Cf({days:t});if(e.length===0)return{totalCalls:0,byTool:{},avgDuration:0,successRate:1};let s={},n=0,o=0;for(let r of e)s[r.tool]=(s[r.tool]||0)+1,n+=r.duration||0,r.success&&o++;return{totalCalls:e.length,byTool:s,avgDuration:Math.round(n/e.length),successRate:o/e.length}}function p0(t){Ia=t}function h0(){return Ia}function m0(){vn=null}Af.exports={logToolExecution:d0,sanitizeArgs:Rf,readAuditLog:Cf,getAuditSummary:f0,setAuditEnabled:p0,isAuditEnabled:h0,getAuditLogPath:Tf,_reset:m0}});var Wf=re((wv,Bf)=>{var De=require("fs").promises,Nf=require("fs"),Ee=require("path"),Ce=require("util").promisify(require("child_process").exec),ja=require("util").promisify(require("child_process").execFile),{spawnSync:g0}=require("child_process"),Da=require("axios"),{isForbidden:y0,isSSHForbidden:$0,isDangerous:w0,isCritical:Mf,isBashPathForbidden:b0,confirm:vt}=Cs(),{showDiff:Ar,showNewFile:_0,showEditDiff:yv,confirmFileChange:Qs}=uu(),{C:ce,Spinner:x0,getToolSpinnerText:k0}=He(),{isGitRepo:qa,getCurrentBranch:Lf,getStatus:v0,getDiff:S0}=sr(),{recordChange:Or}=bu(),{fuzzyFindText:Pf,findMostSimilar:no}=Hu(),{runDiagnostics:eo}=Gu(),{findFileInIndex:E0,getFileIndex:$v}=da(),{resolveProfile:bt,sshExec:rt,scpUpload:T0,scpDownload:R0}=pa(),{resolveDeployConfig:C0,loadDeployConfigs:A0}=rd(),{getEditMode:If}=qs(),O0=/^(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/,N0=/^ssh\s/,M0=/^ssh(?:\s+-\S+)*\s+\S+@?\S+\s+["']?[^-]/;async function pt(t){return De.access(t).then(()=>!0).catch(()=>!1)}async function Nr(t){if(!t)return{fixedPath:null,message:""};let e=t.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),s=it(e);if(s&&await pt(s))return{fixedPath:s,message:`(auto-fixed path: ${t} \u2192 ${e})`};let n=[".js",".ts",".jsx",".tsx",".mjs",".cjs",".json"],o=Ee.extname(t);if(!o)for(let i of n){let a=it(t+i);if(a&&await pt(a))return{fixedPath:a,message:`(auto-fixed: added ${i} extension)`}}if(o){let i=t.replace(/\.[^.]+$/,"");for(let a of n){if(a===o)continue;let c=it(i+a);if(c&&await pt(c))return{fixedPath:c,message:`(auto-fixed: ${o} \u2192 ${a})`}}}let r=Ee.basename(t);if(r&&r.length>2)try{let i=E0(r).map(a=>it(a));if(i.length===1)return{fixedPath:i[0],message:`(auto-fixed: found ${r} at ${Ee.relative(process.cwd(),i[0])})`};if(i.length>1&&i.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
269
+ ${i.map(c=>Ee.relative(process.cwd(),c)).map(c=>` - ${c}`).join(`
270
+ `)}`}}catch{}return{fixedPath:null,message:""}}function L0(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 qf(t,e){let s=[];if(/command not found|: not found|not recognized/i.test(t)){let n=e.match(/^(\S+)/),o=n?n[1]:"";/^(npx|npm|node|yarn|pnpm|bun)$/.test(o)?s.push("HINT: Node.js/npm may not be in PATH. Check your Node.js installation."):/^(python|python3|pip|pip3)$/.test(o)?s.push("HINT: Python may not be installed. Try: brew install python3 (macOS) or apt install python3 (Linux)"):s.push(`HINT: "${o}" is not installed. Try installing it with your package manager.`)}if(/Cannot find module|MODULE_NOT_FOUND/i.test(t)){let n=t.match(/Cannot find module '([^']+)'/),o=n?n[1]:"";o&&!o.startsWith(".")&&!o.startsWith("/")?s.push(`HINT: Missing npm package "${o}". Run: npm install ${o}`):s.push("HINT: Module not found. Check the import path or run npm install.")}if(/permission denied|EACCES/i.test(t)&&s.push("HINT: Permission denied. Check file permissions or try a different approach."),/EADDRINUSE|address already in use/i.test(t)){let n=t.match(/port (\d+)|:(\d+)/),o=n?n[1]||n[2]:"";s.push(`HINT: Port ${o||""} is already in use. Kill the process or use a different port.`)}if(/SyntaxError|Unexpected token/i.test(t)&&s.push("HINT: Syntax error in the code. Check the file at the line number shown above."),/TS\d{4}:/i.test(t)&&s.push("HINT: TypeScript compilation error. Fix the type issue at the indicated line."),/Test Suites:.*failed|Tests:.*failed/i.test(t)&&s.push("HINT: Test failures detected. Read the error output above to identify failing tests."),/fatal: not a git repository/i.test(t)&&s.push("HINT: Not inside a git repository. Run git init or cd to a git project."),/^curl\b/.test(e)){let n=t.match(/curl:\s*\((\d+)\)/),o=n?parseInt(n[1],10):null;o===6||/Could not resolve host/i.test(t)?s.push("HINT: Hostname could not be resolved. Check DNS or use an IP address directly."):o===7||/Failed to connect|Connection refused/i.test(t)?s.push("HINT: Service not running or port wrong. Check if the service is up and the port is correct."):o===22||/HTTP error/i.test(t)?s.push("HINT: HTTP 4xx/5xx response. The endpoint exists but returned an error status."):o===28||/timed out/i.test(t)?s.push("HINT: Request timed out. The host may be unreachable or the service is slow."):(o===35||/SSL.*error/i.test(t))&&s.push("HINT: SSL/TLS handshake failed. Try with --insecure to bypass, or check the certificate.")}if(/remote port forwarding failed/i.test(t)){let n=t.match(/port (\d+)/),o=n?n[1]:"";s.push(`HINT: SSH remote port forwarding failed for port ${o}. The port may already be bound on the server. Check with: ssh server "ss -tuln | grep ${o}" and kill any lingering process with that port.`)}return/bind.*Cannot assign requested address|Address already in use/i.test(t)&&s.push("HINT: Port is already in use. Find the process with: ss -tuln | grep <port> and kill it, then retry."),/Connection.*timed out|ssh.*timeout/i.test(t)&&/^ssh\b/.test(e)&&s.push("HINT: SSH connection timed out. Check if the host is reachable: ping <host> and verify the port with: nc -zv <host> 22"),/spawn \/bin\/sh ENOENT|spawn sh ENOENT/i.test(t)&&s.push("HINT: The working directory was deleted during this session \u2014 bash cannot execute commands in a non-existent cwd. Previous rm/delete commands succeeded. Use list_directory or glob to verify the state instead of retrying bash."),/cp.*\$f.*\$f\.bak.*sed.*-i\.bak|sed.*-i\.bak.*cp.*\$f.*\$f\.bak/i.test(e)&&s.push('HINT: Using both cp with .bak and sed -i.bak creates double backups (.bak.bak). Choose one method: either cp "$f" "$f.bak" OR sed -i.bak, not both.'),s.length===0?t:t+`
240
271
 
241
272
  `+s.join(`
242
- `)}function Ef(t,e,s){let n=Qs(t,e);if(!n)return null;let o=Math.max(2,Math.ceil(e.length*.03));return n.distance>o?null:{autoFixed:!0,matchText:n.text,content:t.split(n.text).join(s),distance:n.distance,line:n.line}}var kf=!1,_n=null;function w0(){_n&&(_n(),_n=null)}var Na=null;function b0(t){Na=t}async function Oa(){if(!kf){kf=!0;try{let{stdout:t}=await Ee("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await Ee('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await Ee("git stash pop",{cwd:process.cwd(),timeout:1e4}),await Ee("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var _0=[/\.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 rt(t){let e=ve.isAbsolute(t)?ve.resolve(t):ve.resolve(process.cwd(),t);for(let s of _0)if(s.test(e))return null;return e}var x0=[{type:"function",function:{name:"bash",description:"Execute a bash command in the project directory. Timeout: 90s (commands that exceed this are killed). Use for: running tests, installing packages, git commands, build tools, starting servers, compiling code. AVOID using bash for: cat/head/tail (use read_file), sed/awk (use edit_file), find/ls (use glob or list_directory), grep/rg (use grep tool). Using dedicated tools is faster and produces better-formatted output. Always quote file paths containing spaces with double quotes. Check the exit code in output \u2014 non-zero means the command failed. For long-running commands (large builds, full test suites), warn the user if they may exceed 90s. Destructive or dangerous commands (rm -rf, git push, npm publish, sudo) require user confirmation.",parameters:{type:"object",properties:{command:{type:"string",description:"The bash command to execute"}},required:["command"]}}},{type:"function",function:{name:"read_file",description:"Read a file's contents with line numbers. You MUST use this tool at least once on a file BEFORE calling edit_file or patch_file on it \u2014 this ensures you have the exact current content and edits will match. Auto-truncates at 350 lines for unbounded reads. For large files (>350 lines), use line_start/line_end to read specific sections. Prefer this over bash cat/head/tail \u2014 dedicated tools produce better-formatted output. Files are read with UTF-8 encoding.",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. 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. IMPORTANT: old_text must match the file content EXACTLY \u2014 including all whitespace, indentation (tabs vs spaces), and newlines. You MUST call read_file on the target file first to see the exact content \u2014 never guess or recall from memory. COMMON FAILURE: old_text doesn't match because you guessed the content instead of reading the file first. If the edit fails with 'old_text not found', use the line number from the error message to re-read that specific region with line_start/line_end, then retry with the exact text. For multiple changes to the same file, prefer patch_file (single atomic operation).",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. 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. For simple content search, grep is equivalent. For finding files by name, use glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory to search"},pattern:{type:"string",description:"Search pattern (regex)"},file_pattern:{type:"string",description:"File filter (e.g. '*.js')"}},required:["path","pattern"]}}},{type:"function",function:{name:"glob",description:"Find files matching a glob pattern. Fast file search by name/extension. Returns paths sorted by modification time. Use this to FIND files before reading them \u2014 never guess file paths, always glob first. Examples: '**/*.test.js' (all test files), 'src/**/*.ts' (all TypeScript in src), 'package.json' (find config). Prefer this over bash find/ls. When you need file contents, glob first to find the path, then read_file to read it.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Glob pattern (e.g. '**/*.ts', 'src/**/*.test.js')"},path:{type:"string",description:"Base directory (default: project root)"}},required:["pattern"]}}},{type:"function",function:{name:"grep",description:"Search file contents with regex. Returns matching lines with file paths and line numbers. Prefer this over bash grep/rg \u2014 this tool returns structured, formatted output. Use output_mode='files_with_matches' when you only need file paths (faster, less output). Use output_mode='content' (default) for matching lines with context. Use head_limit to cap results and avoid overwhelming output on broad searches. Use include to filter by file type (e.g. '*.js'). Supports context lines (context, before_context, after_context), offset for pagination, type filter, and multiline for cross-line 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. Prefer this over multiple edit_file calls when making several changes to the same file. 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:"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:"ask_user",description:"Ask the user a clarifying question with 2-3 specific options. Use when the user's intent is ambiguous. Always provide concrete, actionable options. The user can select an option or type a custom answer.",parameters:{type:"object",properties:{question:{type:"string",description:"The clarifying question to ask"},options:{type:"array",items:{type:"string"},description:"2-3 specific, actionable answer options for the user to choose from",minItems:1,maxItems:3}},required:["question","options"]}}},{type:"function",function:{name:"git_status",description:"Get git status: current branch, changed files, staged/unstaged state. Use before git operations to understand the current state.",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"git_diff",description:"Get git diff for changed files. Shows additions and deletions.",parameters:{type:"object",properties:{staged:{type:"boolean",description:"Show only staged changes (default: false)"},file:{type:"string",description:"Diff specific file only (optional)"}},required:[]}}},{type:"function",function:{name:"git_log",description:"Show recent git commits (short format).",parameters:{type:"object",properties:{count:{type:"number",description:"Number of commits to show (default: 10)"},file:{type:"string",description:"Show commits for specific file (optional)"}},required:[]}}},{type:"function",function:{name:"task_list",description:"Create and manage a task list for complex multi-step tasks. Use for tasks with 3+ steps to track progress. Actions: create (new list with tasks), update (mark task in_progress/done/failed), get (view current list). Always update task status as you work.",parameters:{type:"object",properties:{action:{type:"string",enum:["create","update","get"],description:"Action to perform"},name:{type:"string",description:"Task list name (for create)"},tasks:{type:"array",description:"Array of tasks to create (for create)",items:{type:"object",properties:{description:{type:"string",description:"Task description"},depends_on:{type:"array",items:{type:"string"},description:"IDs of prerequisite tasks"}},required:["description"]}},task_id:{type:"string",description:"Task ID to update (for update)"},status:{type:"string",enum:["in_progress","done","failed"],description:"New status (for update)"},result:{type:"string",description:"Result summary (for update, optional)"}},required:["action"]}}},{type:"function",function:{name:"gh_run_list",description:"List recent GitHub Actions workflow runs for this repository. Shows run status, conclusion, branch, and timing. Use to check CI/CD status or find a run ID.",parameters:{type:"object",properties:{limit:{type:"number",description:"Number of runs to show (default: 10, max: 30)"},workflow:{type:"string",description:"Filter by workflow name or filename (optional)"},branch:{type:"string",description:"Filter by branch name (optional)"},status:{type:"string",enum:["completed","in_progress","queued","failure","success"],description:"Filter by status (optional)"}},required:[]}}},{type:"function",function:{name:"gh_run_view",description:"View details of a specific GitHub Actions workflow run: steps, logs, errors. Use gh_run_list first to get the run ID.",parameters:{type:"object",properties:{run_id:{type:"string",description:"The run ID (from gh_run_list)"},log:{type:"boolean",description:"Include full log output (default: false \u2014 shows step summary only)"}},required:["run_id"]}}},{type:"function",function:{name:"gh_workflow_trigger",description:"Trigger a GitHub Actions workflow dispatch event. Only works for workflows with workflow_dispatch trigger. Requires user confirmation.",parameters:{type:"object",properties:{workflow:{type:"string",description:"Workflow filename (e.g. ci.yml) or name"},branch:{type:"string",description:"Branch to run on (default: current branch)"},inputs:{type:"object",description:"Workflow input parameters as key-value pairs (optional)"}},required:["workflow"]}}},{type:"function",function:{name:"spawn_agents",description:"Run multiple independent sub-agents in parallel (max 5 at top level, max 2 when called from within a sub-agent). Each agent has its own conversation context. Use when 2+ tasks can run simultaneously \u2014 e.g. reading multiple files, analyzing separate modules, independent research. Do NOT use for tasks that depend on each other or modify the same file. Keep task descriptions specific and self-contained. SWARM PATTERN: Sub-agents can call spawn_agents once (max nesting depth 2) to enable Architect\u2192Coder\u2192Reviewer pipelines: a coder agent spawns 1-2 reviewer agents that validate and fix its own output before returning results to the parent.",parameters:{type:"object",properties:{agents:{type:"array",description:"Array of agent definitions to run in parallel (max 5)",items:{type:"object",properties:{task:{type:"string",description:"Task description for the agent"},context:{type:"string",description:"Additional context (optional)"},max_iterations:{type:"number",description:"Max iterations (default: 10, max: 15)"},model:{type:"string",description:'Override model for this agent (provider:model, e.g. "anthropic:claude-haiku"). Auto-selected if omitted.'}},required:["task"]}}},required:["agents"]}}},{type:"function",function:{name:"switch_model",description:"Switch the active AI model mid-conversation. Use when a different model is better for the next steps \u2014 e.g. switch to a fast model for simple lookups, or a more capable model for complex refactoring. The switch persists for all subsequent turns.",parameters:{type:"object",properties:{model:{type:"string",description:'Model spec: "provider:model" (e.g. "ollama:devstral-small-2:24b") or just model name'}},required:["model"]}}},{type:"function",function:{name:"k8s_pods",description:"List Kubernetes pods. Shows pod name, status, restarts, and age. Runs kubectl locally or via SSH on a remote server. Use namespace to filter, or omit for all namespaces.",parameters:{type:"object",properties:{namespace:{type:"string",description:"Namespace to list pods in (default: all namespaces)"},label:{type:"string",description:'Label selector filter (e.g. "app=nginx")'},context:{type:"string",description:"kubectl context to use (optional)"},server:{type:"string",description:"Remote server as user@host to run kubectl via SSH (optional, local kubectl if omitted)"}},required:[]}}},{type:"function",function:{name:"k8s_logs",description:'Fetch logs from a Kubernetes pod. Use tail to limit output, since for time-based filtering (e.g. "1h", "30m").',parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (required if pod has multiple containers)"},tail:{type:"number",description:"Number of recent lines to show (default: 100)"},since:{type:"string",description:'Show logs since duration (e.g. "1h", "30m", "5s")'},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod"]}}},{type:"function",function:{name:"k8s_exec",description:"Execute a command inside a running Kubernetes pod (kubectl exec). Requires user confirmation. Use for inspecting container state, reading configs, or debugging.",parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},command:{type:"string",description:'Command to run in the pod (e.g. "env", "ls /app", "cat /etc/config.yaml")'},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (optional)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod","command"]}}},{type:"function",function:{name:"k8s_apply",description:"Apply a Kubernetes manifest file (kubectl apply -f). Requires confirmation before applying to the cluster. Use dry_run=true to validate without applying.",parameters:{type:"object",properties:{file:{type:"string",description:"Path to manifest YAML file (relative or absolute)"},namespace:{type:"string",description:"Override namespace (optional)"},dry_run:{type:"boolean",description:"Validate only without applying (default: false)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["file"]}}},{type:"function",function:{name:"k8s_rollout",description:"Manage Kubernetes deployment rollouts: check status, restart (rolling update), view history, or undo (rollback). Restart and undo require confirmation.",parameters:{type:"object",properties:{action:{type:"string",enum:["status","restart","history","undo"],description:"Action: status (check rollout progress), restart (rolling restart), history (show revision history), undo (rollback to previous revision)"},deployment:{type:"string",description:"Deployment name"},namespace:{type:"string",description:"Namespace (default: default)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["action","deployment"]}}},{type:"function",function:{name:"brain_write",description:"Write or update a knowledge document in the project brain (.nex/brain/). Use this to persist important findings, architecture decisions, debugging insights, or conventions discovered during the session. The user can review changes via /brain review or git diff.",parameters:{type:"object",properties:{name:{type:"string",description:'Document name (without .md extension). Use kebab-case. Examples: "api-auth-flow", "db-schema-notes", "deployment-checklist"'},content:{type:"string",description:"Full Markdown content. Use headings (#), lists (-), and code blocks. Include optional YAML frontmatter with tags."},mode:{type:"string",enum:["create","update","append"],description:"create: new document (fails if exists). update: overwrite existing. append: add to end of existing document."}},required:["name","content","mode"]}}},{type:"function",function:{name:"ssh_exec",description:'Execute a command on a remote server via SSH. Server is a profile name from .nex/servers.json (e.g. "prod") or "user@host". Use for: checking status, reading logs, running deployments. Destructive commands (restart, delete, modify config) require confirmation. For service management prefer service_manage; for logs prefer service_logs.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name (from .nex/servers.json) or "user@host"'},command:{type:"string",description:"Shell command to run on the remote server"},sudo:{type:"boolean",description:"Run command with sudo (only if profile has sudo:true). Default: false"},timeout:{type:"number",description:"Timeout in seconds. Default: 30"}},required:["server","command"]}}},{type:"function",function:{name:"ssh_upload",description:"Upload a local file or directory to a remote server via SCP. Recursive for directories. Requires confirmation before upload.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},local_path:{type:"string",description:"Local path to upload (file or directory)"},remote_path:{type:"string",description:"Destination path on the remote server (absolute preferred)"}},required:["server","local_path","remote_path"]}}},{type:"function",function:{name:"ssh_download",description:"Download a file or directory from a remote server via SCP. Recursive for directories.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},remote_path:{type:"string",description:"Path on the remote server to download"},local_path:{type:"string",description:"Local destination path"}},required:["server","remote_path","local_path"]}}},{type:"function",function:{name:"remote_agent",description:'Delegate a coding task to nex-code running on a remote server. Use this when the task involves server-side projects (musikschule, stadtkapelle, cahill, schoensgibl, jarvis) that live on almalinux9/jarvis. 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/jarvis/jarvis-agent). 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", "jarvis-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", "jarvis-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 Zs(t,{server:e,context:s}={}){let n=e?e.replace(/[^a-zA-Z0-9@._-]/g,""):null,o=s?s.replace(/[^a-zA-Z0-9._/-]/g,""):null,r="kubectl";if(o&&(r+=` --context ${o}`),r+=` ${t}`,n){let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`ssh -o ConnectTimeout=10 -o BatchMode=yes ${n} "${i}"`}return r}async function vf(t,e,s={}){switch(t){case"bash":{let n=e.command,o=t0(n);if(o){let d=$0(n);return`BLOCKED: Command matches forbidden pattern: ${o}${d?`
243
- HINT: ${d}`:""}`}let r=o0(n);if(r)return`BLOCKED: Destructive operation on protected path: ${r}
244
- HINT: Protected files (.env, credentials, venv, .ssh, etc.) cannot be deleted or moved via bash. Override with NEX_UNPROTECT=1 if intentional.`;if(s.autoConfirm?wf(n):s0(n)){let d=wf(n)?"\u26D4":"\u26A0";if(!await kt(` ${d} bash: \`${n}\``,{toolName:"bash"}))return"CANCELLED: User declined to execute this command."}let a;try{a=process.cwd(),$f.accessSync(a)}catch{a=require("os").homedir(),s.silent||console.log(`${ae.yellow} \u26A0 Working directory no longer exists \u2014 running in ${a}${ae.reset}`)}let c=g0.test(n.trim())&&!y0.test(n.trim());if(m0.test(n.trim())||c){s.silent||console.log(`${ae.dim} \u25B6 interactive: ${n}${ae.reset}`);let d=e0("sh",["-c",n],{stdio:"inherit",cwd:a});return d.error?`ERROR: ${d.error.message}`:d.status===0?"(interactive command completed successfully)":`(interactive command exited with code ${d.status})`}let{ToolProgress:l}=Hn(),u=s.silent?null:new l("bash",n.substring(0,40));u&&u.start();try{let{stdout:d,stderr:f}=await Ee(n,{cwd:a,timeout:9e4,maxBuffer:5242880});return u&&u.stop(),d||f||"(no output)"}catch(d){u&&u.stop();let f=(d.stderr||d.stdout||d.message||"").toString().substring(0,5e3),h=Sf(f,n);return`EXIT ${d.code||1}
245
- ${h}`}}case"read_file":{let n=rt(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await ft(n)){let C=await Cr(e.path);if(C.fixedPath)n=C.fixedPath,console.log(`${ae.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ve.relative(process.cwd(),n)}${ae.reset}`);else return`ERROR: File not found: ${e.path}${C.message?`
246
- `+C.message:""}`}let r=Buffer.alloc(8192),i=await $f.promises.open(n,"r"),{bytesRead:a}=await i.read(r,0,8192,0);await i.close();for(let C=0;C<a;C++)if(r[C]===0)return`ERROR: ${n} is a binary file (not readable as text)`;let c=await je.readFile(n,"utf-8");if(!c&&(await je.stat(n)).size>0)return`WARNING: ${n} is empty or unreadable`;let l=c.split(`
247
- `),u=await je.stat(n),d=l.length,f=350,h=!e.line_start&&!e.line_end,m=h&&d>f,g=(e.line_start||1)-1,b=m?f:e.line_end||l.length,v=ve.relative(process.cwd(),n),O=m?`showing lines 1-${f} of ${d}`:e.line_start||e.line_end?`lines ${g+1}-${b} of ${d}`:`${d} lines`,U=`File: ${v} (${O}, ${u.size} bytes)`,L=l.slice(g,b).map((C,K)=>`${g+K+1}: ${C}`).join(`
248
- `),R=m?`
273
+ `)}function Ff(t,e,s){let n=no(t,e);if(!n)return null;let o=Math.max(2,Math.ceil(e.length*.03));return n.distance>o?null:{autoFixed:!0,matchText:n.text,content:t.split(n.text).join(s),distance:n.distance,line:n.line}}var jf=!1,Sn=null;function P0(){Sn&&(Sn(),Sn=null)}var Ba=null;function I0(t){Ba=t}async function Fa(){if(!jf){jf=!0;try{let{stdout:t}=await Ce("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await Ce('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await Ce("git stash pop",{cwd:process.cwd(),timeout:1e4}),await Ce("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var j0=[/\.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 it(t){let e=Ee.isAbsolute(t)?Ee.resolve(t):Ee.resolve(process.cwd(),t);for(let s of j0)if(s.test(e))return null;return e}var D0=[{type:"function",function:{name:"bash",description:`Execute a bash command in the project directory. Timeout: 90s (commands that exceed this are killed). Use for: running tests, installing packages, git commands, build tools, starting servers, compiling code. Example: use bash for "npm install" or "git status", but NOT for "cat config.json" (use read_file instead) or "grep -r 'error' src/" (use grep tool instead). AVOID using bash for: cat/head/tail (use read_file), sed/awk (use edit_file), find/ls (use glob or list_directory), grep/rg (use grep tool). Using dedicated tools is faster and produces better-formatted output. Always quote file paths containing spaces with double quotes. Check the exit code in output \u2014 non-zero means the command failed. For long-running commands (large builds, full test suites), warn the user if they may exceed 90s. Destructive or dangerous commands (rm -rf, git push, npm publish, sudo) require user confirmation.`,parameters:{type:"object",properties:{command:{type:"string",description:"The bash command to execute"}},required:["command"]}}},{type:"function",function:{name:"read_file",description:"Read a file's contents with line numbers. ALWAYS read a file before editing it to ensure exact content matching \u2014 edit_file requires the EXACT text including whitespace and newlines. Example: read_file path=src/app.js line_start=10 line_end=20. Auto-truncates at 350 lines for unbounded reads. For large files (>350 lines), use line_start/line_end to read specific sections. Concrete example: read_file(path='src/app.js', line_start=10, line_end=20) reads lines 10-20 of src/app.js. Prefer this over bash cat/head/tail \u2014 dedicated tools produce better-formatted output. Files are read with UTF-8 encoding. IMPORTANT: If you need more than 350 lines, specify line_start and line_end explicitly \u2014 omitting them will truncate the output.",parameters:{type:"object",properties:{path:{type:"string",description:"File path (relative or absolute)"},line_start:{type:"number",description:"Start line (1-based, optional)"},line_end:{type:"number",description:"End line (1-based, optional)"}},required:["path"]}}},{type:"function",function:{name:"write_file",description:"Create a new file or completely overwrite an existing file. Example: use write_file for creating a new config file like .env.example, but NOT for changing one line in an existing file (use edit_file instead). For targeted changes to existing files, prefer edit_file or patch_file instead \u2014 they only send the diff and are safer. Only use write_file when creating new files or when the entire content needs to be replaced.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},content:{type:"string",description:"Full file content"}},required:["path","content"]}}},{type:"function",function:{name:"edit_file",description:"Replace specific text in a file. ALWAYS call read_file first to get the exact content \u2014 edit_file requires the EXACT text including whitespace, indentation, and newlines. Example: edit_file(path='src/config.js', old_text='debug: false', new_text='debug: true'). IMPORTANT: old_text must match byte-for-byte \u2014 even a single space or newline difference will cause failure. If the edit fails with 'old_text not found', re-read that region with line_start/line_end then retry. For multiple replacements in one file, prefer patch_file (atomic). For new files, use write_file instead.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},old_text:{type:"string",description:"Exact text to find (must match file content precisely)"},new_text:{type:"string",description:"Replacement text"}},required:["path","old_text","new_text"]}}},{type:"function",function:{name:"list_directory",description:"List files and directories in a tree view. Use this to understand project structure. Example: use list_directory to see the overall layout of the src/ directory, but NOT for finding all .js files (use glob instead). For finding specific files by pattern, prefer glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory path"},max_depth:{type:"number",description:"Max depth (default: 2)"},pattern:{type:"string",description:"File filter glob (e.g. '*.js')"}},required:["path"]}}},{type:"function",function:{name:"search_files",description:"Search for a text pattern across files (regex). Returns matching lines with file paths. Example: use search_files for finding all occurrences of 'error' in .js files, but NOT for finding all .js files (use glob instead). For simple content search, grep is equivalent. For finding files by name, use glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory to search"},pattern:{type:"string",description:"Search pattern (regex)"},file_pattern:{type:"string",description:"File filter (e.g. '*.js')"}},required:["path","pattern"]}}},{type:"function",function:{name:"glob",description:"Find files matching a glob pattern by name or extension. Returns paths sorted by modification time. ALWAYS use this to locate files BEFORE reading them \u2014 never guess file paths. Example: glob(pattern='src/**/*.test.js') finds all test files in src directory. DO NOT use for content search (e.g. finding 'error' in files) \u2014 use grep tool instead. Examples: '**/*.test.js' (all test files), 'src/**/*.ts' (all TypeScript in src), 'package.json' (find config). Prefer this over bash find/ls. When you need file contents, glob first to get the exact path, then read_file to read it.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Glob pattern (e.g. '**/*.ts', 'src/**/*.test.js')"},path:{type:"string",description:"Base directory (default: project root)"}},required:["pattern"]}}},{type:"function",function:{name:"grep",description:"Search file CONTENTS with regex \u2014 use this when you need to find text inside files. Example: grep(pattern='callStream') finds files containing the text 'callStream'. Do NOT use glob for this \u2014 glob finds files by NAME pattern, grep searches file CONTENTS. Use output_mode='files_with_matches' for just file paths, output_mode='content' (default) for matching lines. Use include to filter by file type (e.g. '*.js'). Supports context lines, offset pagination, and multiline patterns.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Regex pattern to search for"},path:{type:"string",description:"Directory or file to search (default: project root)"},include:{type:"string",description:"File filter glob (e.g. '*.js', '*.ts')"},ignore_case:{type:"boolean",description:"Case-insensitive search"},output_mode:{type:"string",enum:["content","files_with_matches","count"],description:"Output mode: content (matching lines), files_with_matches (file paths only), count (match counts). Default: content"},context:{type:"number",description:"Lines of context around each match (like grep -C)"},before_context:{type:"number",description:"Lines before each match (like grep -B)"},after_context:{type:"number",description:"Lines after each match (like grep -A)"},head_limit:{type:"number",description:"Limit output to first N results"},offset:{type:"number",description:"Skip first N results"},type:{type:"string",description:"File type filter (e.g. 'js', 'py', 'ts') \u2014 maps to --include='*.ext'"},multiline:{type:"boolean",description:"Enable multiline matching (grep -Pz)"},staged:{type:"boolean",description:"Search only staged content (git diff --cached). Default: false"}},required:["pattern"]}}},{type:"function",function:{name:"patch_file",description:"Apply multiple text replacements to a file atomically. All patches are validated before any are applied \u2014 if one fails, none are written. Example: when changing 3 different variables in the same function, use patch_file with an array of 3 { old_text, new_text } objects instead of 3 separate edit_file calls. This ensures either all changes are applied or none are, preventing partial edits. Like edit_file, all old_text values must match exactly.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},patches:{type:"array",description:"Array of { old_text, new_text } replacements to apply in order",items:{type:"object",properties:{old_text:{type:"string",description:"Text to find"},new_text:{type:"string",description:"Replacement text"}},required:["old_text","new_text"]}}},required:["path","patches"]}}},{type:"function",function:{name:"web_fetch",description:"Fetch content from a URL and return text. HTML tags are stripped. Use for reading documentation, API responses, or web pages. Will not work with authenticated/private URLs.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to fetch"},max_length:{type:"number",description:"Max response length in chars (default: 10000)"}},required:["url"]}}},{type:"function",function:{name:"web_search",description:"Search the web. Uses Perplexity (grounded, AI-summarized) if PERPLEXITY_API_KEY is set, otherwise DuckDuckGo. Returns titles, URLs, and summaries. Use to find documentation, solutions, or current information beyond your knowledge cutoff.",parameters:{type:"object",properties:{query:{type:"string",description:"Search query"},max_results:{type:"number",description:"Max results (default: 5)"}},required:["query"]}}},{type:"function",function:{name:"browser_open",description:"Open a URL in a headless browser and return the page title, text content, and links. More reliable than web_fetch for JavaScript-heavy pages. Requires playwright (npm install playwright && npx playwright install chromium).",parameters:{type:"object",properties:{url:{type:"string",description:"URL to open"},wait_for:{type:"string",enum:["domcontentloaded","networkidle","load"],description:"When to consider page loaded (default: domcontentloaded)"}},required:["url"]}}},{type:"function",function:{name:"browser_screenshot",description:"Take a screenshot of a URL in a headless browser. Returns the screenshot file path. The path can be pasted into the next message for visual analysis. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot"},full_page:{type:"boolean",description:"Capture full page (default: false \u2014 viewport only)"},width:{type:"number",description:"Viewport width in px (default: 1280)"},height:{type:"number",description:"Viewport height in px (default: 800)"}},required:["url"]}}},{type:"function",function:{name:"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:"ask_user",description:"Ask the user a clarifying question with 2-3 specific options. Use when the user's intent is ambiguous. Always provide concrete, actionable options. The user can select an option or type a custom answer.",parameters:{type:"object",properties:{question:{type:"string",description:"The clarifying question to ask"},options:{type:"array",items:{type:"string"},description:"2-3 specific, actionable answer options for the user to choose from",minItems:1,maxItems:3}},required:["question","options"]}}},{type:"function",function:{name:"git_status",description:"Get git status: current branch, changed files, staged/unstaged state. Use before git operations to understand the current state.",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"git_diff",description:"Get git diff for changed files. Shows additions and deletions.",parameters:{type:"object",properties:{staged:{type:"boolean",description:"Show only staged changes (default: false)"},file:{type:"string",description:"Diff specific file only (optional)"}},required:[]}}},{type:"function",function:{name:"git_log",description:"Show recent git commits (short format).",parameters:{type:"object",properties:{count:{type:"number",description:"Number of commits to show (default: 10)"},file:{type:"string",description:"Show commits for specific file (optional)"}},required:[]}}},{type:"function",function:{name:"task_list",description:"Create and manage a task list for complex multi-step tasks. Use for tasks with 3+ steps to track progress. Actions: create (new list with tasks), update (mark task in_progress/done/failed), get (view current list). Always update task status as you work.",parameters:{type:"object",properties:{action:{type:"string",enum:["create","update","get"],description:"Action to perform"},name:{type:"string",description:"Task list name (for create)"},tasks:{type:"array",description:"Array of tasks to create (for create)",items:{type:"object",properties:{description:{type:"string",description:"Task description"},depends_on:{type:"array",items:{type:"string"},description:"IDs of prerequisite tasks"}},required:["description"]}},task_id:{type:"string",description:"Task ID to update (for update)"},status:{type:"string",enum:["in_progress","done","failed"],description:"New status (for update)"},result:{type:"string",description:"Result summary (for update, optional)"}},required:["action"]}}},{type:"function",function:{name:"gh_run_list",description:"List recent GitHub Actions workflow runs for this repository. Shows run status, conclusion, branch, and timing. Use to check CI/CD status or find a run ID.",parameters:{type:"object",properties:{limit:{type:"number",description:"Number of runs to show (default: 10, max: 30)"},workflow:{type:"string",description:"Filter by workflow name or filename (optional)"},branch:{type:"string",description:"Filter by branch name (optional)"},status:{type:"string",enum:["completed","in_progress","queued","failure","success"],description:"Filter by status (optional)"}},required:[]}}},{type:"function",function:{name:"gh_run_view",description:"View details of a specific GitHub Actions workflow run: steps, logs, errors. Use gh_run_list first to get the run ID.",parameters:{type:"object",properties:{run_id:{type:"string",description:"The run ID (from gh_run_list)"},log:{type:"boolean",description:"Include full log output (default: false \u2014 shows step summary only)"}},required:["run_id"]}}},{type:"function",function:{name:"gh_workflow_trigger",description:"Trigger a GitHub Actions workflow dispatch event. Only works for workflows with workflow_dispatch trigger. Requires user confirmation.",parameters:{type:"object",properties:{workflow:{type:"string",description:"Workflow filename (e.g. ci.yml) or name"},branch:{type:"string",description:"Branch to run on (default: current branch)"},inputs:{type:"object",description:"Workflow input parameters as key-value pairs (optional)"}},required:["workflow"]}}},{type:"function",function:{name:"spawn_agents",description:"Run multiple independent sub-agents in parallel (max 5 at top level, max 2 when called from within a sub-agent). Each agent has its own conversation context. Use when 2+ tasks can run simultaneously \u2014 e.g. reading multiple files, analyzing separate modules, independent research. Do NOT use for tasks that depend on each other or modify the same file. Keep task descriptions specific and self-contained. SWARM PATTERN: Sub-agents can call spawn_agents once (max nesting depth 2) to enable Architect\u2192Coder\u2192Reviewer pipelines: a coder agent spawns 1-2 reviewer agents that validate and fix its own output before returning results to the parent.",parameters:{type:"object",properties:{agents:{type:"array",description:"Array of agent definitions to run in parallel (max 5)",items:{type:"object",properties:{task:{type:"string",description:"Task description for the agent"},context:{type:"string",description:"Additional context (optional)"},max_iterations:{type:"number",description:"Max iterations (default: 10, max: 15)"},model:{type:"string",description:'Override model for this agent (provider:model, e.g. "anthropic:claude-haiku"). Auto-selected if omitted.'}},required:["task"]}}},required:["agents"]}}},{type:"function",function:{name:"switch_model",description:"Switch the active AI model mid-conversation. Use when a different model is better for the next steps \u2014 e.g. switch to a fast model for simple lookups, or a more capable model for complex refactoring. The switch persists for all subsequent turns.",parameters:{type:"object",properties:{model:{type:"string",description:'Model spec: "provider:model" (e.g. "ollama:devstral-small-2:24b") or just model name'}},required:["model"]}}},{type:"function",function:{name:"k8s_pods",description:"List Kubernetes pods. Shows pod name, status, restarts, and age. Runs kubectl locally or via SSH on a remote server. Use namespace to filter, or omit for all namespaces.",parameters:{type:"object",properties:{namespace:{type:"string",description:"Namespace to list pods in (default: all namespaces)"},label:{type:"string",description:'Label selector filter (e.g. "app=nginx")'},context:{type:"string",description:"kubectl context to use (optional)"},server:{type:"string",description:"Remote server as user@host to run kubectl via SSH (optional, local kubectl if omitted)"}},required:[]}}},{type:"function",function:{name:"k8s_logs",description:'Fetch logs from a Kubernetes pod. Use tail to limit output, since for time-based filtering (e.g. "1h", "30m").',parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (required if pod has multiple containers)"},tail:{type:"number",description:"Number of recent lines to show (default: 100)"},since:{type:"string",description:'Show logs since duration (e.g. "1h", "30m", "5s")'},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod"]}}},{type:"function",function:{name:"k8s_exec",description:"Execute a command inside a running Kubernetes pod (kubectl exec). Requires user confirmation. Use for inspecting container state, reading configs, or debugging.",parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},command:{type:"string",description:'Command to run in the pod (e.g. "env", "ls /app", "cat /etc/config.yaml")'},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (optional)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod","command"]}}},{type:"function",function:{name:"k8s_apply",description:"Apply a Kubernetes manifest file (kubectl apply -f). Requires confirmation before applying to the cluster. Use dry_run=true to validate without applying.",parameters:{type:"object",properties:{file:{type:"string",description:"Path to manifest YAML file (relative or absolute)"},namespace:{type:"string",description:"Override namespace (optional)"},dry_run:{type:"boolean",description:"Validate only without applying (default: false)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["file"]}}},{type:"function",function:{name:"k8s_rollout",description:"Manage Kubernetes deployment rollouts: check status, restart (rolling update), view history, or undo (rollback). Restart and undo require confirmation.",parameters:{type:"object",properties:{action:{type:"string",enum:["status","restart","history","undo"],description:"Action: status (check rollout progress), restart (rolling restart), history (show revision history), undo (rollback to previous revision)"},deployment:{type:"string",description:"Deployment name"},namespace:{type:"string",description:"Namespace (default: default)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["action","deployment"]}}},{type:"function",function:{name:"brain_write",description:"Write or update a knowledge document in the project brain (.nex/brain/). Use this to persist important findings, architecture decisions, debugging insights, or conventions discovered during the session. The user can review changes via /brain review or git diff.",parameters:{type:"object",properties:{name:{type:"string",description:'Document name (without .md extension). Use kebab-case. Examples: "api-auth-flow", "db-schema-notes", "deployment-checklist"'},content:{type:"string",description:"Full Markdown content. Use headings (#), lists (-), and code blocks. Include optional YAML frontmatter with tags."},mode:{type:"string",enum:["create","update","append"],description:"create: new document (fails if exists). update: overwrite existing. append: add to end of existing document."}},required:["name","content","mode"]}}},{type:"function",function:{name:"ssh_exec",description:'Execute a command on a remote server via SSH. Server is a profile name from .nex/servers.json (e.g. "prod") or "user@host". Use for: checking status, reading logs, running deployments. Destructive commands (restart, delete, modify config) require confirmation. For service management prefer service_manage; for logs prefer service_logs.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name (from .nex/servers.json) or "user@host"'},command:{type:"string",description:"Shell command to run on the remote server"},sudo:{type:"boolean",description:"Run command with sudo (only if profile has sudo:true). Default: false"},timeout:{type:"number",description:"Timeout in seconds. Default: 30"}},required:["server","command"]}}},{type:"function",function:{name:"ssh_upload",description:"Upload a local file or directory to a remote server via SCP. Recursive for directories. Requires confirmation before upload.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},local_path:{type:"string",description:"Local path to upload (file or directory)"},remote_path:{type:"string",description:"Destination path on the remote server (absolute preferred)"}},required:["server","local_path","remote_path"]}}},{type:"function",function:{name:"ssh_download",description:"Download a file or directory from a remote server via SCP. Recursive for directories.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},remote_path:{type:"string",description:"Path on the remote server to download"},local_path:{type:"string",description:"Local destination path"}},required:["server","remote_path","local_path"]}}},{type:"function",function:{name:"remote_agent",description:'Delegate a coding task to nex-code running on a remote server. Use this when the task involves server-side projects (musikschule, stadtkapelle, cahill, schoensgibl) that live on almalinux9. Runs nex-code --auto on the server and streams output. Server is a profile name from .nex/servers.json or "user@host".',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name from .nex/servers.json (e.g. "almalinux9") or "user@host"'},task:{type:"string",description:"The full task description to run on the remote nex-code"},project_path:{type:"string",description:"Working directory on the remote server (e.g. /home/deploy/app). Defaults to home directory."},model:{type:"string",description:"Model to use on remote nex-code (e.g. qwen3-coder:480b). Defaults to server default."}},required:["server","task"]}}},{type:"function",function:{name:"service_manage",description:"Manage a systemd service on a remote (or local) server. Uses systemctl. Status is read-only; start/stop/restart/reload/enable/disable require confirmation. For AlmaLinux 9: runs via SSH with sudo if configured.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn", "postgresql")'},action:{type:"string",enum:["status","start","stop","restart","reload","enable","disable"],description:"systemctl action to perform"}},required:["service","action"]}}},{type:"function",function:{name:"service_logs",description:"Fetch systemd service logs via journalctl. Works on AlmaLinux 9 and any systemd Linux. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn")'},lines:{type:"number",description:"Number of recent log lines to fetch. Default: 50"},since:{type:"string",description:'Time filter, e.g. "1 hour ago", "today", "2024-01-01 12:00". Optional.'},follow:{type:"boolean",description:"Tail logs in real-time (follow mode). Default: false"}},required:["service"]}}},{type:"function",function:{name:"container_list",description:"List Docker containers on a server (or locally). Shows container ID, name, image, status, and ports. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},all:{type:"boolean",description:"Show all containers including stopped ones. Default: false (running only)."}},required:[]}}},{type:"function",function:{name:"container_logs",description:"Fetch logs from a Docker container on a server (or locally). Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},lines:{type:"number",description:"Number of recent log lines. Default: 50."},since:{type:"string",description:'Time filter, e.g. "1h", "30m", "2024-01-01T12:00:00". Optional.'}},required:["container"]}}},{type:"function",function:{name:"container_exec",description:"Execute a command inside a running Docker container. Destructive or state-changing commands require confirmation.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},command:{type:"string",description:'Command to run inside the container (e.g. "cat /etc/nginx/nginx.conf").'}},required:["container","command"]}}},{type:"function",function:{name:"container_manage",description:'Start, stop, restart, or remove a Docker container. All actions except "inspect" require confirmation.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},action:{type:"string",enum:["start","stop","restart","remove","inspect"],description:"Action to perform on the container."}},required:["container","action"]}}},{type:"function",function:{name:"frontend_recon",description:"MANDATORY first step before creating or significantly modifying any frontend file (HTML template, Vue/React component, CSS). Scans the project and returns: (1) design tokens \u2014 CSS variables, Tailwind theme colors/fonts, (2) main layout/index page structure, (3) a reference component of the same type, (4) detected JS/CSS framework stack. Call this BEFORE writing any markup or styles. Never skip it for frontend tasks.",parameters:{type:"object",properties:{type:{type:"string",description:'Type of frontend file you are about to create. Used to find a relevant reference component. Examples: "list", "form", "detail", "dashboard", "modal", "component". Optional but improves reference quality.'}},required:[]}}},{type:"function",function:{name:"deploy",description:'Deploy to a remote server. Supports two methods: "rsync" (sync local files) and "git" (git pull on remote). Can use a named config from .nex/deploy.json. Requires confirmation before executing.',parameters:{type:"object",properties:{config:{type:"string",description:'Named deploy config from .nex/deploy.json (e.g. "prod"). Overrides all other params if provided.'},method:{type:"string",enum:["rsync","git"],description:'Deploy method: "rsync" syncs local files (default), "git" runs git pull on the remote.'},server:{type:"string",description:'Profile name or "user@host". Required if no config.'},remote_path:{type:"string",description:"Remote project directory. Required for git method; destination path for rsync."},local_path:{type:"string",description:"Local directory or file to sync. Required for rsync method."},branch:{type:"string",description:"Branch to pull (git method only). Defaults to current remote branch."},deploy_script:{type:"string",description:'Shell command(s) to run on the remote after sync/pull (e.g. "npm ci && systemctl restart myapp"). Optional.'},health_check:{type:"string",description:"URL (HTTP GET) or shell command to verify the service is healthy after deploy. If it fails, the deploy is marked as failed. Optional."},exclude:{type:"array",items:{type:"string"},description:"Paths to exclude from rsync. Optional."},dry_run:{type:"boolean",description:"Show what would happen without executing. Default: false."}},required:[]}}},{type:"function",function:{name:"deployment_status",description:"Check deployment status across all configured servers. Reads .nex/deploy.json configs and checks service health on each server. Returns a status summary table.",parameters:{type:"object",properties:{config:{type:"string",description:"Specific deploy config name to check (optional \u2014 checks all if omitted)"}},required:[]}}},{type:"function",function:{name:"sysadmin",description:"Senior sysadmin operations on a remote (or local) Linux server. Covers: system audit, disk_usage, process_list, network_status, package management (dnf/apt), user management, firewall (firewalld/ufw/iptables), cron, SSL cert checks, log tailing, large file discovery, systemd service management, process kill, journalctl log querying. Read-only actions run without confirmation; state-changing actions require user approval.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},action:{type:"string",enum:["audit","disk_usage","process_list","network_status","package","user_manage","firewall","cron","ssl_check","log_tail","find_large","service","kill_process","journalctl"],description:"Sysadmin operation. audit=full health overview; disk_usage=df+du; process_list=top procs; network_status=open ports; package=dnf/apt (package_action: check|list|install|remove|update|upgrade); user_manage=users/keys; firewall=rules; cron=crontab; ssl_check=cert expiry+days; log_tail=tail any log; find_large=big files; service=systemd unit management; kill_process=kill by PID or name; journalctl=query system journal."},path:{type:"string",description:"File or directory path. For disk_usage (default /), log_tail (required), find_large (default /)."},lines:{type:"number",description:"Lines to tail for log_tail or journalctl. Default: 100."},limit:{type:"number",description:"Result count for process_list (default 20) or find_large (default 20)."},sort_by:{type:"string",enum:["cpu","mem"],description:"Sort order for process_list. Default: cpu."},min_size:{type:"string",description:'Minimum file size for find_large. Default: "100M". Examples: "50M", "1G".'},package_action:{type:"string",enum:["install","remove","update","list","upgrade"],description:"Package sub-action for action=package."},packages:{type:"array",items:{type:"string"},description:"Package name(s) for install/remove/update."},user_action:{type:"string",enum:["list","create","delete","add_ssh_key","info"],description:"User sub-action for action=user_manage."},user:{type:"string",description:"Linux username for user_manage or cron."},groups:{type:"array",items:{type:"string"},description:'Groups to assign on user create (e.g. ["sudo", "docker"]).'},ssh_key:{type:"string",description:"SSH public key string to add for user_action=add_ssh_key."},firewall_action:{type:"string",enum:["status","allow","deny","remove","reload"],description:"Firewall sub-action for action=firewall."},port:{type:"string",description:'Port/protocol for firewall rules, e.g. "80/tcp", "443", "8080/udp".'},cron_action:{type:"string",enum:["list","add","remove"],description:"Cron sub-action for action=cron."},schedule:{type:"string",description:'Cron schedule expression for cron add, e.g. "0 2 * * *".'},command:{type:"string",description:"Command for cron add, or substring to match for cron remove."},domain:{type:"string",description:`Domain for ssl_check (e.g. "example.com"). Auto-detects Let's Encrypt cert on server; falls back to live TLS probe.`},cert_path:{type:"string",description:'Explicit path to cert file on server for ssl_check (e.g. "/etc/letsencrypt/live/x/cert.pem").'},service_name:{type:"string",description:'Systemd unit name for action=service (e.g. "nginx", "my-api", "gunicorn"). .service suffix optional.'},service_action:{type:"string",enum:["status","start","stop","restart","reload","enable","disable","list_failed"],description:"Sub-action for action=service. list_failed shows all failed units."},pid:{type:"number",description:"Process ID to kill for action=kill_process."},process_name:{type:"string",description:"Process name to kill (uses pkill) for action=kill_process. Use with pid for safety."},signal:{type:"string",enum:["SIGTERM","SIGKILL","SIGHUP","SIGINT"],description:"Signal for kill_process. Default: SIGTERM."},unit:{type:"string",description:'Systemd unit to filter for journalctl (e.g. "nginx", "my-api"). Omit for system-wide.'},since:{type:"string",description:'Time filter for journalctl, e.g. "1 hour ago", "today", "2026-03-17 10:00". Default: last 200 lines.'},priority:{type:"string",enum:["emerg","alert","crit","err","warning","notice","info","debug"],description:"Minimum log priority for journalctl. Default: no filter."}},required:["action"]}}},{type:"function",function:{name:"save_memory",description:"Save a typed memory for cross-session persistence. Use this to remember user preferences, feedback, project context, or external references.",parameters:{type:"object",properties:{type:{type:"string",enum:["user","feedback","project","reference"],description:"Memory type: user (role/prefs), feedback (approach guidance), project (ongoing work), reference (external pointers)"},name:{type:"string",description:"Short slug identifier for this memory (e.g. 'testing-preference', 'deploy-workflow')"},content:{type:"string",description:"Markdown content of the memory"},description:{type:"string",description:"One-line description for the memory index (optional, defaults to first line of content)"}},required:["type","name","content"]}}},{type:"function",function:{name:"delete_memory",description:"Delete a typed memory entry. Use this to prune outdated or incorrect memories.",parameters:{type:"object",properties:{type:{type:"string",enum:["user","feedback","project","reference"],description:"Memory type to delete from"},name:{type:"string",description:"Slug identifier of the memory to delete"}},required:["type","name"]}}}];function to(t,{server:e,context:s}={}){let n=e?e.replace(/[^a-zA-Z0-9@._-]/g,""):null,o=s?s.replace(/[^a-zA-Z0-9._/-]/g,""):null,r="kubectl";if(o&&(r+=` --context ${o}`),r+=` ${t}`,n){let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`ssh -o ConnectTimeout=10 -o BatchMode=yes ${n} "${i}"`}return r}async function Df(t,e,s={}){switch(t){case"bash":{let n=e.command,o=y0(n);if(o){let d=L0(n);return`BLOCKED: Command matches forbidden pattern: ${o}${d?`
274
+ HINT: ${d}`:""}`}let r=b0(n);if(r)return`BLOCKED: Destructive operation on protected path: ${r}
275
+ HINT: Protected files (.env, credentials, venv, .ssh, etc.) cannot be deleted or moved via bash. Override with NEX_UNPROTECT=1 if intentional.`;if(s.autoConfirm?Mf(n):w0(n)){let d=Mf(n)?"\u26D4":"\u26A0";if(!await vt(` ${d} bash: \`${n}\``,{toolName:"bash"}))return"CANCELLED: User declined to execute this command."}let a;try{a=process.cwd(),Nf.accessSync(a)}catch{a=require("os").homedir(),s.silent||console.log(`${ce.yellow} \u26A0 Working directory no longer exists \u2014 running in ${a}${ce.reset}`)}let c=N0.test(n.trim())&&!M0.test(n.trim());if(O0.test(n.trim())||c){s.silent||console.log(`${ce.dim} \u25B6 interactive: ${n}${ce.reset}`);let d=g0("sh",["-c",n],{stdio:"inherit",cwd:a});return d.error?`ERROR: ${d.error.message}`:d.status===0?"(interactive command completed successfully)":`(interactive command exited with code ${d.status})`}let{ToolProgress:l}=zn(),u=s.silent?null:new l("bash",n.substring(0,40));u&&u.start();try{let{stdout:d,stderr:f}=await Ce(n,{cwd:a,timeout:9e4,maxBuffer:5242880});return u&&u.stop(),d||f||"(no output)"}catch(d){u&&u.stop();let f=(d.stderr||d.stdout||d.message||"").toString().substring(0,5e3),h=qf(f,n);return`EXIT ${d.code||1}
276
+ ${h}`}}case"read_file":{let n=it(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await pt(n)){let C=await Nr(e.path);if(C.fixedPath)n=C.fixedPath,console.log(`${ce.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${Ee.relative(process.cwd(),n)}${ce.reset}`);else return`ERROR: File not found: ${e.path}${C.message?`
277
+ `+C.message:""}`}let r=Buffer.alloc(8192),i=await Nf.promises.open(n,"r"),{bytesRead:a}=await i.read(r,0,8192,0);await i.close();for(let C=0;C<a;C++)if(r[C]===0)return`ERROR: ${n} is a binary file (not readable as text)`;let c=await De.readFile(n,"utf-8");if(!c&&(await De.stat(n)).size>0)return`WARNING: ${n} is empty or unreadable`;let l=c.split(`
278
+ `),u=await De.stat(n),d=l.length,f=350,h=!e.line_start&&!e.line_end,g=h&&d>f,m=(e.line_start||1)-1,b=g?f:e.line_end||l.length,x=Ee.relative(process.cwd(),n),j=g?`showing lines 1-${f} of ${d}`:e.line_start||e.line_end?`lines ${m+1}-${b} of ${d}`:`${d} lines`,G=`File: ${x} (${j}, ${u.size} bytes)`,L=l.slice(m,b).map((C,Z)=>`${m+Z+1}: ${C}`).join(`
279
+ `),P=g?`
249
280
 
250
281
  [File truncated: showing lines 1-${f} of ${d} total. Use line_start/line_end to read other sections, e.g. line_start=${f+1} line_end=${Math.min(f*2,d)}]`:!h&&d>f?`
251
- [Large file (${d} lines total) \u2014 use line_start/line_end for other sections]`:"";return`${U}
252
- ${L}${R}`}case"write_file":{await Oa();let n=rt(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let o=await ft(n),r=null;if(s.autoConfirm)o&&(r=await je.readFile(n,"utf-8"));else if(o){r=await je.readFile(n,"utf-8");let u=await Js(n,e.content);if(Tr(n,r,e.content,{annotations:u}),!await Vs("Overwrite"))return"CANCELLED: User declined to overwrite file."}else{let u=await Js(n,e.content);if(r0(n,e.content,{annotations:u}),!await Vs("Create"))return"CANCELLED: User declined to create file."}let i=ve.dirname(n);await ft(i)||await je.mkdir(i,{recursive:!0}),await je.writeFile(n,e.content,"utf-8");let c=/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||e.content.startsWith("#!");c&&await je.chmod(n,493),Rr("write_file",n,r,e.content);let l=c?" [chmod +x applied]":"";return`Written: ${n} (${e.content.length} chars)${l}`}case"edit_file":{await Oa();let n=rt(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await ft(n)){let u=await Cr(e.path);if(u.fixedPath)n=u.fixedPath,console.log(`${ae.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ve.relative(process.cwd(),n)}${ae.reset}`);else return`ERROR: File not found: ${e.path}${u.message?`
253
- `+u.message:""}`}let r=await je.readFile(n,"utf-8"),i=e.old_text,a=!1,c=!1;if(!r.includes(e.old_text)){let{getActiveModelId:u,getActiveProviderName:d}=He();if(xf(u(),d())==="strict"){let m=Qs(r,e.old_text);return m?`ERROR: old_text not found in ${n} (strict mode \u2014 exact match required)
254
- Most similar text (line ${m.line}, distance ${m.distance}):
255
- ${m.text}`:`ERROR: old_text not found in ${n} (strict mode \u2014 exact match required)`}let h=_f(r,e.old_text);if(h)i=h,a=!0,console.log(`${ae.dim} \u2713 fuzzy whitespace match applied${ae.reset}`);else{let m=Ef(r,e.old_text,e.new_text);if(m){if(!s.autoConfirm){let U=await Js(n,m.content);if(Tr(n,r,m.content,{annotations:U}),!await Vs(`Apply (auto-fix, line ${m.line}, distance ${m.distance})`))return"CANCELLED: User declined to apply edit."}await je.writeFile(n,m.content,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||m.content.startsWith("#!"))&&await je.chmod(n,493),Rr("edit_file",n,r,m.content);let O=m.matchText.length>80?m.matchText.substring(0,77)+"...":m.matchText;return console.log(`${ae.dim} \u2713 auto-fixed edit: line ${m.line}, distance ${m.distance}${ae.reset}`),`Edited: ${n} (auto-fixed, line ${m.line}, distance ${m.distance}, matched: "${O}")`}let g=Qs(r,e.old_text);if(g){let O=r.split(`
256
- `),U=Math.max(0,g.line-6),L=Math.min(O.length,g.line+10),R=O.slice(U,L).map((K,Q)=>`${U+Q+1}: ${K}`).join(`
257
- `),C=`line_start=${Math.max(1,g.line-5)} line_end=${Math.min(O.length,g.line+15)}`;return`ERROR: old_text not found in ${n} (most similar at line ${g.line}, distance ${g.distance})
282
+ [Large file (${d} lines total) \u2014 use line_start/line_end for other sections]`:"";return`${G}
283
+ ${L}${P}`}case"write_file":{await Fa();let n=it(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let o=await pt(n),r=null;if(s.autoConfirm)o&&(r=await De.readFile(n,"utf-8"));else if(o){r=await De.readFile(n,"utf-8");let u=await eo(n,e.content);if(Ar(n,r,e.content,{annotations:u}),!await Qs("Overwrite"))return"CANCELLED: User declined to overwrite file."}else{let u=await eo(n,e.content);if(_0(n,e.content,{annotations:u}),!await Qs("Create"))return"CANCELLED: User declined to create file."}let i=Ee.dirname(n);await pt(i)||await De.mkdir(i,{recursive:!0}),await De.writeFile(n,e.content,"utf-8");let c=/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||e.content.startsWith("#!");c&&await De.chmod(n,493),Or("write_file",n,r,e.content);let l=c?" [chmod +x applied]":"";return`Written: ${n} (${e.content.length} chars)${l}`}case"edit_file":{await Fa();let n=it(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await pt(n)){let u=await Nr(e.path);if(u.fixedPath)n=u.fixedPath,console.log(`${ce.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${Ee.relative(process.cwd(),n)}${ce.reset}`);else return`ERROR: File not found: ${e.path}${u.message?`
284
+ `+u.message:""}`}let r=await De.readFile(n,"utf-8"),i=e.old_text,a=!1,c=!1;if(!r.includes(e.old_text)){let{getActiveModelId:u,getActiveProviderName:d}=Ge();if(If(u(),d())==="strict"){let g=no(r,e.old_text);return g?`ERROR: old_text not found in ${n} (strict mode \u2014 exact match required)
285
+ Most similar text (line ${g.line}, distance ${g.distance}):
286
+ ${g.text}`:`ERROR: old_text not found in ${n} (strict mode \u2014 exact match required)`}let h=Pf(r,e.old_text);if(h)i=h,a=!0,console.log(`${ce.dim} \u2713 fuzzy whitespace match applied${ce.reset}`);else{let g=Ff(r,e.old_text,e.new_text);if(g){if(!s.autoConfirm){let G=await eo(n,g.content);if(Ar(n,r,g.content,{annotations:G}),!await Qs(`Apply (auto-fix, line ${g.line}, distance ${g.distance})`))return"CANCELLED: User declined to apply edit."}await De.writeFile(n,g.content,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||g.content.startsWith("#!"))&&await De.chmod(n,493),Or("edit_file",n,r,g.content);let j=g.matchText.length>80?g.matchText.substring(0,77)+"...":g.matchText;return console.log(`${ce.dim} \u2713 auto-fixed edit: line ${g.line}, distance ${g.distance}${ce.reset}`),`Edited: ${n} (auto-fixed, line ${g.line}, distance ${g.distance}, matched: "${j}")`}let m=no(r,e.old_text);if(m){let j=r.split(`
287
+ `),G=Math.max(0,m.line-6),L=Math.min(j.length,m.line+10),P=j.slice(G,L).map((Z,Y)=>`${G+Y+1}: ${Z}`).join(`
288
+ `),C=`line_start=${Math.max(1,m.line-5)} line_end=${Math.min(j.length,m.line+15)}`;return`ERROR: old_text not found in ${n} (most similar at line ${m.line}, distance ${m.distance})
258
289
 
259
- Actual file content around line ${g.line} \u2014 use this to correct old_text:
260
- ${R}
290
+ Actual file content around line ${m.line} \u2014 use this to correct old_text:
291
+ ${P}
261
292
 
262
293
  Fix: update old_text to match the exact lines above, then retry. If you need more context: read_file with ${C}`}let b=(e.old_text||"").trim().split(`
263
- `)[0].slice(0,60),v=b?`
294
+ `)[0].slice(0,60),x=b?`
264
295
  Recovery: grep -n "${b.replace(/"/g,'\\"')}" <file> to find the line, then re-read that section with line_start/line_end.`:`
265
- Recovery: use grep -n to locate the text, then re-read that section with line_start/line_end.`;return`ERROR: old_text not found in ${n}${v}`}}if(!s.autoConfirm){let u=r.split(i).join(e.new_text),d=await Js(n,u);if(Tr(n,r,u,{annotations:d}),!await Vs(a?"Apply (fuzzy match)":"Apply"))return"CANCELLED: User declined to apply edit."}let l=r.split(i).join(e.new_text);return await je.writeFile(n,l,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||l.startsWith("#!"))&&await je.chmod(n,493),Rr("edit_file",n,r,l),a?`Edited: ${n} (fuzzy match)`:`Edited: ${n}`}case"list_directory":{let n=rt(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await ft(n)){let l=e.path.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),u=rt(l),d=await ft(u);if(u&&d)n=u;else return`ERROR: Directory not found: ${e.path}`}let r=e.max_depth||2,i=null;if(e.pattern)try{let l=e.pattern.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");i=new RegExp(`^${l}$`)}catch{return`ERROR: Invalid pattern: ${e.pattern}`}let a=[],c=async(l,u,d)=>{if(u>r)return;let f;try{f=await je.readdir(l,{withFileTypes:!0})}catch{return}f=f.filter(h=>!h.name.startsWith(".")&&h.name!=="node_modules");for(let h of f){if(i&&!h.isDirectory()&&!i.test(h.name))continue;let m=h.isDirectory()?"/":"";a.push(`${d}${h.name}${m}`),h.isDirectory()&&await c(ve.join(l,h.name),u+1,d+" ")}};return await c(n,1,""),a.join(`
266
- `)||"(empty)"}case"search_files":{let n=rt(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let o=["-rn","--null","-H"];e.file_pattern&&o.push(`--include=${e.file_pattern}`),o.push(e.pattern,n);try{let{stdout:r}=await Ra("grep",o,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),i=r.split("\0"),a=[];for(let c=0;c<i.length;c+=2){let l=i[c],u=i[c+1];if(l&&u){let d=u.split(`
296
+ Recovery: use grep -n to locate the text, then re-read that section with line_start/line_end.`;return`ERROR: old_text not found in ${n}${x}`}}if(!s.autoConfirm){let u=r.split(i).join(e.new_text),d=await eo(n,u);if(Ar(n,r,u,{annotations:d}),!await Qs(a?"Apply (fuzzy match)":"Apply"))return"CANCELLED: User declined to apply edit."}let l=r.split(i).join(e.new_text);return await De.writeFile(n,l,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||l.startsWith("#!"))&&await De.chmod(n,493),Or("edit_file",n,r,l),a?`Edited: ${n} (fuzzy match)`:`Edited: ${n}`}case"list_directory":{let n=it(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await pt(n)){let l=e.path.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),u=it(l),d=await pt(u);if(u&&d)n=u;else return`ERROR: Directory not found: ${e.path}`}let r=e.max_depth||2,i=null;if(e.pattern)try{let l=e.pattern.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");i=new RegExp(`^${l}$`)}catch{return`ERROR: Invalid pattern: ${e.pattern}`}let a=[],c=async(l,u,d)=>{if(u>r)return;let f;try{f=await De.readdir(l,{withFileTypes:!0})}catch{return}f=f.filter(h=>!h.name.startsWith(".")&&h.name!=="node_modules");for(let h of f){if(i&&!h.isDirectory()&&!i.test(h.name))continue;let g=h.isDirectory()?"/":"";a.push(`${d}${h.name}${g}`),h.isDirectory()&&await c(Ee.join(l,h.name),u+1,d+" ")}};return await c(n,1,""),a.join(`
297
+ `)||"(empty)"}case"search_files":{let n=it(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let o=["-rn","--null","-H"];e.file_pattern&&o.push(`--include=${e.file_pattern}`),o.push(e.pattern,n);try{let{stdout:r}=await ja("grep",o,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),i=r.split("\0"),a=[];for(let c=0;c<i.length;c+=2){let l=i[c],u=i[c+1];if(l&&u){let d=u.split(`
267
298
  `).filter(f=>f.trim());for(let f of d)if(a.push(`${l}:${f}`),a.length>=50)break}if(a.length>=50)break}return a.join(`
268
- `)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let o=process.cwd(),r=e.path?rt(e.path):o,i=e.pattern,a=Q=>{let re=Q.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"(.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");return new RegExp(`^${re}$`)},c=a(i),l=i.split("/").pop(),u=a(l),{ToolProgress:d}=Hn(),f=new d("glob","Finding files...");f.start();let{getFileIndex:h,getIndexedCwd:m,refreshIndex:g,isIndexValid:b}=sa(),v=h(),O=m();b(r)||(await g(r),v=h());let U=v.filter(Q=>c.test(Q)||u.test(ve.basename(Q))).map(Q=>ve.join(r,Q));if(U.length===0)return f.stop(),"(no matches)";let L=await Promise.all(U.slice(0,210).map(async Q=>{try{let re=await je.stat(Q);return{path:Q,mtime:re.mtimeMs}}catch{return{path:Q,mtime:0}}}));L.sort((Q,re)=>re.mtime-Q.mtime);let R=L.map(Q=>Q.path),C=U.length>200,K=R.slice(0,200).join(`
269
- `);return f.update({count:U.length,detail:e.pattern}),f.stop(),C?`${K}
270
-
271
- \u26A0 Results truncated at 200. Use a more specific pattern.`:K}case"grep":{let n=e.path?rt(e.path):process.cwd();if(e.staged){let{getDiff:c}=er(),l=await c(!0);if(!l.trim())return"(no staged changes)";let u=new Set,d=l.split(`
272
- `);for(let b of d)if(b.startsWith("diff --git")){let v=b.match(/diff --git a\/(.+) b\/(.+)/);v&&u.add(v[2])}let f=["-rn","-E","--null","-H","--exclude=*.md","--exclude=*.txt","--exclude=*.json","--exclude=*.yaml","--exclude=*.yml"];e.ignore_case&&f.push("-i"),e.include&&f.push(`--include=${e.include}`),e.type&&f.push(`--include=*.${e.type}`),e.context?f.push("-C",String(e.context)):(e.before_context&&f.push("-B",String(e.before_context)),e.after_context&&f.push("-A",String(e.after_context))),e.output_mode==="files_with_matches"?f.push("-l"):e.output_mode==="count"&&f.push("-c"),f.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage");let{ToolProgress:h}=Hn(),m=new h("grep","Searching staged content...");m.start();let g=[];for(let b of u)try{let v=ve.join(process.cwd(),b);if(await ft(v)){let O=[...f];O.push(e.pattern,v);let{stdout:U}=await Ra("grep",O,{cwd:process.cwd(),timeout:3e4,maxBuffer:2*1024*1024});if(e.output_mode==="files_with_matches"||e.output_mode==="count"){let L=U.trim().split(`
273
- `).filter(R=>R.trim());g=g.concat(L)}else{let L=U.split("\0");for(let R=0;R<L.length;R+=2){let C=L[R+1];if(C){let K=C.split(`
274
- `).filter(Q=>Q.trim());for(let Q of K)g.push(`${b}:${Q}`)}}}}}catch{}return m.update({count:g.length,detail:"in staged files"}),m.stop(),g.join(`
275
- `).trim()||"(no matches in staged files)"}let o=["-rn","-E","--null","-H"];e.ignore_case&&o.push("-i"),e.include&&o.push(`--include=${e.include}`),e.type&&o.push(`--include=*.${e.type}`);let r=20;e.context?o.push("-C",String(Math.min(Number(e.context),r))):(e.before_context&&o.push("-B",String(Math.min(Number(e.before_context),r))),e.after_context&&o.push("-A",String(Math.min(Number(e.after_context),r)))),e.output_mode==="files_with_matches"?o.push("-l"):e.output_mode==="count"&&o.push("-c"),o.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage"),o.push(e.pattern,n);let{ToolProgress:i}=Hn(),a=new i("grep","Searching...");a.start();try{let{stdout:c}=await Ra("grep",o,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),l;if(e.output_mode==="files_with_matches"||e.output_mode==="count")l=c.trim().split(`
276
- `).filter(f=>f.trim());else{let f=c.split("\0");l=[];for(let h=0;h<f.length;h+=2){let m=f[h],g=f[h+1];if(m&&g){let b=g.split(`
277
- `).filter(v=>v.trim());for(let v of b)l.push(`${m}:${v}`)}}}let u=e.offset||0,d=e.head_limit||(e.output_mode==="files_with_matches"?200:100);return l=l.slice(u,u+d),a.update({count:l.length,detail:`in ${n}`}),a.stop(),l.join(`
278
- `).trim()||"(no matches)"}catch(c){return a.stop(),c.code===2?`ERROR: Invalid regex pattern: ${e.pattern}`:"(no matches)"}}case"patch_file":{await Oa();let n=rt(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await ft(n)){let v=await Cr(e.path);if(v.fixedPath)n=v.fixedPath,console.log(`${ae.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ve.relative(process.cwd(),n)}${ae.reset}`);else return`ERROR: File not found: ${e.path}${v.message?`
279
- `+v.message:""}`}let r=e.patches;if(!Array.isArray(r)||r.length===0)return"ERROR: No patches provided";let i=await je.readFile(n,"utf-8"),{getActiveModelId:a,getActiveProviderName:c}=He(),l=xf(a(),c()),u=[],d=!1,f=!1;for(let v=0;v<r.length;v++){let{old_text:O,new_text:U}=r[v];if(i.includes(O))u.push({old_text:O,new_text:U});else if(l==="strict"){let L=Qs(i,O);return L?`ERROR: Patch ${v+1} old_text not found in ${n} (strict mode \u2014 exact match required)
299
+ `)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let o=process.cwd(),r=e.path?it(e.path):o,i=e.pattern,a=Y=>{let ue=Y.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"(.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");return new RegExp(`^${ue}$`)},c=a(i),l=i.split("/").pop(),u=a(l),{ToolProgress:d}=zn(),f=new d("glob","Finding files...");f.start();let{getFileIndex:h,getIndexedCwd:g,refreshIndex:m,isIndexValid:b}=da(),x=h(),j=g();b(r)||(await m(r),x=h());let G=x.filter(Y=>c.test(Y)||u.test(Ee.basename(Y))).map(Y=>Ee.join(r,Y));if(G.length===0)return f.stop(),"(no matches)";let L=await Promise.all(G.slice(0,210).map(async Y=>{try{let ue=await De.stat(Y);return{path:Y,mtime:ue.mtimeMs}}catch{return{path:Y,mtime:0}}}));L.sort((Y,ue)=>ue.mtime-Y.mtime);let P=L.map(Y=>Y.path),C=G.length>200,Z=P.slice(0,200).join(`
300
+ `);return f.update({count:G.length,detail:e.pattern}),f.stop(),C?`${Z}
301
+
302
+ \u26A0 Results truncated at 200. Use a more specific pattern.`:Z}case"grep":{let n=e.path?it(e.path):process.cwd();if(e.staged){let{getDiff:c}=sr(),l=await c(!0);if(!l.trim())return"(no staged changes)";let u=new Set,d=l.split(`
303
+ `);for(let b of d)if(b.startsWith("diff --git")){let x=b.match(/diff --git a\/(.+) b\/(.+)/);x&&u.add(x[2])}let f=["-rn","-E","--null","-H","--exclude=*.md","--exclude=*.txt","--exclude=*.json","--exclude=*.yaml","--exclude=*.yml"];e.ignore_case&&f.push("-i"),e.include&&f.push(`--include=${e.include}`),e.type&&f.push(`--include=*.${e.type}`),e.context?f.push("-C",String(e.context)):(e.before_context&&f.push("-B",String(e.before_context)),e.after_context&&f.push("-A",String(e.after_context))),e.output_mode==="files_with_matches"?f.push("-l"):e.output_mode==="count"&&f.push("-c"),f.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage");let{ToolProgress:h}=zn(),g=new h("grep","Searching staged content...");g.start();let m=[];for(let b of u)try{let x=Ee.join(process.cwd(),b);if(await pt(x)){let j=[...f];j.push(e.pattern,x);let{stdout:G}=await ja("grep",j,{cwd:process.cwd(),timeout:3e4,maxBuffer:2*1024*1024});if(e.output_mode==="files_with_matches"||e.output_mode==="count"){let L=G.trim().split(`
304
+ `).filter(P=>P.trim());m=m.concat(L)}else{let L=G.split("\0");for(let P=0;P<L.length;P+=2){let C=L[P+1];if(C){let Z=C.split(`
305
+ `).filter(Y=>Y.trim());for(let Y of Z)m.push(`${b}:${Y}`)}}}}}catch{}return g.update({count:m.length,detail:"in staged files"}),g.stop(),m.join(`
306
+ `).trim()||"(no matches in staged files)"}let o=["-rn","-E","--null","-H"];e.ignore_case&&o.push("-i"),e.include&&o.push(`--include=${e.include}`),e.type&&o.push(`--include=*.${e.type}`);let r=20;e.context?o.push("-C",String(Math.min(Number(e.context),r))):(e.before_context&&o.push("-B",String(Math.min(Number(e.before_context),r))),e.after_context&&o.push("-A",String(Math.min(Number(e.after_context),r)))),e.output_mode==="files_with_matches"?o.push("-l"):e.output_mode==="count"&&o.push("-c"),o.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage"),o.push(e.pattern,n);let{ToolProgress:i}=zn(),a=new i("grep","Searching...");a.start();try{let{stdout:c}=await ja("grep",o,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),l;if(e.output_mode==="files_with_matches"||e.output_mode==="count")l=c.trim().split(`
307
+ `).filter(f=>f.trim());else{let f=c.split("\0");l=[];for(let h=0;h<f.length;h+=2){let g=f[h],m=f[h+1];if(g&&m){let b=m.split(`
308
+ `).filter(x=>x.trim());for(let x of b)l.push(`${g}:${x}`)}}}let u=e.offset||0,d=e.head_limit||(e.output_mode==="files_with_matches"?200:100);return l=l.slice(u,u+d),a.update({count:l.length,detail:`in ${n}`}),a.stop(),l.join(`
309
+ `).trim()||"(no matches)"}catch(c){return a.stop(),c.code===2?`ERROR: Invalid regex pattern: ${e.pattern}`:"(no matches)"}}case"patch_file":{await Fa();let n=it(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await pt(n)){let x=await Nr(e.path);if(x.fixedPath)n=x.fixedPath,console.log(`${ce.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${Ee.relative(process.cwd(),n)}${ce.reset}`);else return`ERROR: File not found: ${e.path}${x.message?`
310
+ `+x.message:""}`}let r=e.patches;if(!Array.isArray(r)||r.length===0)return"ERROR: No patches provided";let i=await De.readFile(n,"utf-8"),{getActiveModelId:a,getActiveProviderName:c}=Ge(),l=If(a(),c()),u=[],d=!1,f=!1;for(let x=0;x<r.length;x++){let{old_text:j,new_text:G}=r[x];if(i.includes(j))u.push({old_text:j,new_text:G});else if(l==="strict"){let L=no(i,j);return L?`ERROR: Patch ${x+1} old_text not found in ${n} (strict mode \u2014 exact match required)
280
311
  Most similar text (line ${L.line}, distance ${L.distance}):
281
- ${L.text}`:`ERROR: Patch ${v+1} old_text not found in ${n} (strict mode \u2014 exact match required)`}else{let L=_f(i,O);if(L)u.push({old_text:L,new_text:U}),d=!0;else{let R=Qs(i,O);if(R){let C=Math.max(3,Math.ceil(O.length*.05));if(R.distance<=C)u.push({old_text:R.text,new_text:U}),f=!0;else return`ERROR: Patch ${v+1} old_text not found in ${n}
282
- Most similar text (line ${R.line}, distance ${R.distance}):
283
- ${R.text}`}else return`ERROR: Patch ${v+1} old_text not found in ${n}`}}}let h=i;for(let{old_text:v,new_text:O}of u)h=h.split(v).join(O);if(!s.autoConfirm){let v=await Js(n,h);if(Tr(n,i,h,{annotations:v}),!await Vs(d?"Apply patches (fuzzy match)":"Apply patches"))return"CANCELLED: User declined to apply patches."}await je.writeFile(n,h,"utf-8");let m=/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||h.startsWith("#!");m&&await je.chmod(n,493),Rr("patch_file",n,i,h);let g=f?" (auto-fixed)":d?" (fuzzy match)":"",b=m?" [chmod +x applied]":"";return`Patched: ${n} (${r.length} replacements)${g}${b}`}case"web_fetch":{let n=e.url,o=e.max_length||1e4;try{let r=await Ca.get(n,{timeout:15e3,maxContentLength:1048576,responseType:"text",headers:{"User-Agent":"nex-code/0.2.0"}});return(typeof r.data=="string"?r.data:JSON.stringify(r.data)).replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim().substring(0,o)||"(empty response)"}catch(r){return`ERROR: Failed to fetch ${n}: ${r.message}`}}case"web_search":{let n=e.max_results||5;if(process.env.PERPLEXITY_API_KEY)try{let o=await Ca.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]
312
+ ${L.text}`:`ERROR: Patch ${x+1} old_text not found in ${n} (strict mode \u2014 exact match required)`}else{let L=Pf(i,j);if(L)u.push({old_text:L,new_text:G}),d=!0;else{let P=no(i,j);if(P){let C=Math.max(3,Math.ceil(j.length*.05));if(P.distance<=C)u.push({old_text:P.text,new_text:G}),f=!0;else return`ERROR: Patch ${x+1} old_text not found in ${n}
313
+ Most similar text (line ${P.line}, distance ${P.distance}):
314
+ ${P.text}`}else return`ERROR: Patch ${x+1} old_text not found in ${n}`}}}let h=i;for(let{old_text:x,new_text:j}of u)h=h.split(x).join(j);if(!s.autoConfirm){let x=await eo(n,h);if(Ar(n,i,h,{annotations:x}),!await Qs(d?"Apply patches (fuzzy match)":"Apply patches"))return"CANCELLED: User declined to apply patches."}await De.writeFile(n,h,"utf-8");let g=/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||h.startsWith("#!");g&&await De.chmod(n,493),Or("patch_file",n,i,h);let m=f?" (auto-fixed)":d?" (fuzzy match)":"",b=g?" [chmod +x applied]":"";return`Patched: ${n} (${r.length} replacements)${m}${b}`}case"web_fetch":{let n=e.url,o=e.max_length||1e4;try{let r=await Da.get(n,{timeout:15e3,maxContentLength:1048576,responseType:"text",headers:{"User-Agent":"nex-code/0.2.0"}});return(typeof r.data=="string"?r.data:JSON.stringify(r.data)).replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim().substring(0,o)||"(empty response)"}catch(r){return`ERROR: Failed to fetch ${n}: ${r.message}`}}case"web_search":{let n=e.max_results||5;if(process.env.PERPLEXITY_API_KEY)try{let o=await Da.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]
284
315
 
285
316
  ${r}`;return i.length>0&&(a+=`
286
317
 
287
318
  Sources:
288
319
  `+i.slice(0,n).map((c,l)=>`${l+1}. ${c}`).join(`
289
- `)),a}catch(o){console.error(`${ae.dim} Perplexity search failed (${o.message}), falling back to DuckDuckGo${ae.reset}`)}try{let r=(await Ca.get("https://html.duckduckgo.com/html/",{params:{q:e.query},timeout:1e4,responseType:"text",headers:{"User-Agent":"nex-code/0.2.0"}})).data,i=[],a=/<a[^>]*class="result__a"[^>]*href="([^"]*)"[^>]*>([\s\S]*?)<\/a>/gi,c;for(;(c=a.exec(r))!==null&&i.length<n;){let l=c[1].replace(/.*uddg=/,"").split("&")[0],u=c[2].replace(/<[^>]+>/g,"").trim();try{i.push({title:u,url:decodeURIComponent(l)})}catch{i.push({title:u,url:l})}}return i.length===0?"(no results)":i.map((l,u)=>`${u+1}. ${l.title}
320
+ `)),a}catch(o){console.error(`${ce.dim} Perplexity search failed (${o.message}), falling back to DuckDuckGo${ce.reset}`)}try{let r=(await Da.get("https://html.duckduckgo.com/html/",{params:{q:e.query},timeout:1e4,responseType:"text",headers:{"User-Agent":"nex-code/0.2.0"}})).data,i=[],a=/<a[^>]*class="result__a"[^>]*href="([^"]*)"[^>]*>([\s\S]*?)<\/a>/gi,c;for(;(c=a.exec(r))!==null&&i.length<n;){let l=c[1].replace(/.*uddg=/,"").split("&")[0],u=c[2].replace(/<[^>]+>/g,"").trim();try{i.push({title:u,url:decodeURIComponent(l)})}catch{i.push({title:u,url:l})}}return i.length===0?"(no results)":i.map((l,u)=>`${u+1}. ${l.title}
290
321
  ${l.url}`).join(`
291
322
 
292
- `)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:n}=Ds();try{let o=await n(e.url,{waitFor:e.wait_for}),r=o.links.length>0?`
323
+ `)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:n}=Bs();try{let o=await n(e.url,{waitFor:e.wait_for}),r=o.links.length>0?`
293
324
 
294
325
  Links:
295
326
  `+o.links.map(i=>` ${i.text} \u2192 ${i.href}`).join(`
296
327
  `):"";return`Title: ${o.title}
297
328
  URL: ${o.url}
298
329
 
299
- ${o.text}${r}`}catch(o){return`ERROR: ${o.message}`}}case"browser_screenshot":{let{browserScreenshot:n}=Ds();try{let o=await n(e.url,{width:e.width,height:e.height,fullPage:e.full_page});return`Screenshot saved: ${o.path}
330
+ ${o.text}${r}`}catch(o){return`ERROR: ${o.message}`}}case"browser_screenshot":{let{browserScreenshot:n}=Bs();try{let o=await n(e.url,{width:e.width,height:e.height,fullPage:e.full_page});return`Screenshot saved: ${o.path}
300
331
  Title: ${o.title}
301
332
  URL: ${o.url}
302
333
 
303
- To analyze visually, paste the path into your next message: ${o.path}`}catch(o){return`ERROR: ${o.message}`}}case"browser_click":{let{browserClick:n}=Ds();try{return await n(e.url,{selector:e.selector,text:e.text})}catch(o){return`ERROR: ${o.message}`}}case"browser_fill":{let{browserFill:n}=Ds();try{return await n(e.url,{selector:e.selector,value:e.value,submit:e.submit})}catch(o){return`ERROR: ${o.message}`}}case"ask_user":{let{question:n,options:o=[]}=e;return Na?new Promise(r=>{_n=()=>r("CANCELLED"),Na(n,o).then(i=>{_n=null,r(i||"User did not answer")})}):new Promise(r=>{let i=require("readline").createInterface({input:process.stdin,output:process.stdout});_n=()=>{i.close(),r("CANCELLED")};let a=o.length>0?`
334
+ To analyze visually, paste the path into your next message: ${o.path}`}catch(o){return`ERROR: ${o.message}`}}case"browser_click":{let{browserClick:n}=Bs();try{return await n(e.url,{selector:e.selector,text:e.text})}catch(o){return`ERROR: ${o.message}`}}case"browser_fill":{let{browserFill:n}=Bs();try{return await n(e.url,{selector:e.selector,value:e.value,submit:e.submit})}catch(o){return`ERROR: ${o.message}`}}case"ask_user":{let{question:n,options:o=[]}=e;return Ba?new Promise(r=>{Sn=()=>r("CANCELLED"),Ba(n,o).then(i=>{Sn=null,r(i||"User did not answer")})}):new Promise(r=>{let i=require("readline").createInterface({input:process.stdin,output:process.stdout});Sn=()=>{i.close(),r("CANCELLED")};let a=o.length>0?`
304
335
  ${o.map((c,l)=>` ${l+1}. ${c}`).join(`
305
336
  `)}
306
337
  `:"";console.log(`
307
- ${ae.cyan}${ae.bold} ? ${n}${ae.reset}${a}`),i.question(`${ae.cyan} > ${ae.reset}`,c=>{_n=null,i.close(),r(c.trim()||"(no response)")})})}case"git_status":{if(!await Aa())return"ERROR: Not a git repository";let n=await bf()||"(detached)",o=await c0();if(o.length===0)return`Branch: ${n}
338
+ ${ce.cyan}${ce.bold} ? ${n}${ce.reset}${a}`),i.question(`${ce.cyan} > ${ce.reset}`,c=>{Sn=null,i.close(),r(c.trim()||"(no response)")})})}case"git_status":{if(!await qa())return"ERROR: Not a git repository";let n=await Lf()||"(detached)",o=await v0();if(o.length===0)return`Branch: ${n}
308
339
  Clean working tree (no changes)`;let r=[`Branch: ${n}`,`Changed files (${o.length}):`];for(let i of o){let a=i.status==="M"?"modified":i.status==="A"?"added":i.status==="D"?"deleted":i.status==="??"?"untracked":i.status;r.push(` ${a}: ${i.file}`)}return r.join(`
309
- `)}case"git_diff":{if(!await Aa())return"ERROR: Not a git repository";let n;if(e.file){let o=["diff"];e.staged&&o.push("--cached"),o.push("--",e.file);try{n=execFileSync("git",o,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()}catch{n=""}}else n=await l0(!!e.staged);return n||"(no diff)"}case"git_log":{if(!await Aa())return"ERROR: Not a git repository";let o=["log","--oneline",`-${Math.min(e.count||10,50)}`];e.file&&o.push("--",e.file);try{return execFileSync("git",o,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()||"(no commits)"}catch{return"(no commits)"}}case"task_list":{let{createTasks:n,updateTask:o,getTaskList:r,renderTaskList:i,hasActiveTasks:a}=ua(),{getActiveTaskProgress:c}=Ue(),l=c();switch(e.action){case"create":{if(!e.name||!e.tasks)return"ERROR: task_list create requires name and tasks";let u=n(e.name,e.tasks);return l||console.log(`
340
+ `)}case"git_diff":{if(!await qa())return"ERROR: Not a git repository";let n;if(e.file){let o=["diff"];e.staged&&o.push("--cached"),o.push("--",e.file);try{n=execFileSync("git",o,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()}catch{n=""}}else n=await S0(!!e.staged);return n||"(no diff)"}case"git_log":{if(!await qa())return"ERROR: Not a git repository";let o=["log","--oneline",`-${Math.min(e.count||10,50)}`];e.file&&o.push("--",e.file);try{return execFileSync("git",o,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()||"(no commits)"}catch{return"(no commits)"}}case"task_list":{let{createTasks:n,updateTask:o,getTaskList:r,renderTaskList:i,hasActiveTasks:a}=$a(),{getActiveTaskProgress:c}=He(),l=c();switch(e.action){case"create":{if(!e.name||!e.tasks)return"ERROR: task_list create requires name and tasks";let u=n(e.name,e.tasks);return l||console.log(`
310
341
  `+i()),`Created task list "${e.name}" with ${u.length} tasks:
311
342
  `+u.map(d=>` ${d.id}: ${d.description}`).join(`
312
343
  `)}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)?(l||console.log(`
313
344
  `+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":(l||console.log(`
314
- `+i()),JSON.stringify(u,null,2))}default:return`ERROR: Unknown task_list action: ${e.action}. Use: create, update, get`}}case"spawn_agents":{let{executeSpawnAgents:n}=ga();return n(e)}case"switch_model":{let{setActiveModel:n,getActiveProviderName:o,getActiveModelId:r}=He();return n(e.model)?`Switched to ${o()}:${r()}`:`ERROR: Unknown model: ${e.model}. Use /providers to see available models.`}case"gh_run_list":{let n=Math.min(e.limit||10,30),o=["run","list","--limit",String(n),"--json","databaseId,status,conclusion,name,headBranch,createdAt,updatedAt,event"];e.workflow&&o.push("--workflow",e.workflow),e.branch&&o.push("--branch",e.branch),e.status&&o.push("--status",e.status);try{let{stdout:r}=await Ee(`gh ${o.join(" ")}`,{cwd:process.cwd(),timeout:3e4}),i=JSON.parse(r||"[]");return i.length===0?"No workflow runs found.":i.map(c=>{let l=c.conclusion||c.status||"unknown",u=l==="success"?"\u2713":l==="failure"?"\u2717":l==="in_progress"?"\u283F":"\u25CB",d=c.updatedAt?new Date(c.updatedAt).toISOString().slice(0,16).replace("T"," "):"";return`${u} [${c.databaseId}] ${c.name} \xB7 ${c.headBranch} \xB7 ${l} \xB7 ${d}`}).join(`
345
+ `+i()),JSON.stringify(u,null,2))}default:return`ERROR: Unknown task_list action: ${e.action}. Use: create, update, get`}}case"spawn_agents":{let{executeSpawnAgents:n}=Sa();return n(e)}case"switch_model":{let{setActiveModel:n,getActiveProviderName:o,getActiveModelId:r}=Ge();return n(e.model)?`Switched to ${o()}:${r()}`:`ERROR: Unknown model: ${e.model}. Use /providers to see available models.`}case"gh_run_list":{let n=Math.min(e.limit||10,30),o=["run","list","--limit",String(n),"--json","databaseId,status,conclusion,name,headBranch,createdAt,updatedAt,event"];e.workflow&&o.push("--workflow",e.workflow),e.branch&&o.push("--branch",e.branch),e.status&&o.push("--status",e.status);try{let{stdout:r}=await Ce(`gh ${o.join(" ")}`,{cwd:process.cwd(),timeout:3e4}),i=JSON.parse(r||"[]");return i.length===0?"No workflow runs found.":i.map(c=>{let l=c.conclusion||c.status||"unknown",u=l==="success"?"\u2713":l==="failure"?"\u2717":l==="in_progress"?"\u283F":"\u25CB",d=c.updatedAt?new Date(c.updatedAt).toISOString().slice(0,16).replace("T"," "):"";return`${u} [${c.databaseId}] ${c.name} \xB7 ${c.headBranch} \xB7 ${l} \xB7 ${d}`}).join(`
315
346
  `)}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(`
316
- `)[0]}`}}case"gh_run_view":{if(!e.run_id)return"ERROR: run_id is required";try{if(e.log){let{stdout:i}=await Ee(`gh run view ${e.run_id} --log`,{cwd:process.cwd(),timeout:6e4,maxBuffer:5242880});return i.substring(0,8e3)+(i.length>8e3?`
317
- ...(truncated)`:"")}let{stdout:n}=await Ee(`gh run view ${e.run_id} --json status,conclusion,name,headBranch,createdAt,updatedAt,jobs`,{cwd:process.cwd(),timeout:3e4}),o=JSON.parse(n),r=[`Run: ${o.name} [${e.run_id}]`,`Branch: ${o.headBranch} Status: ${o.conclusion||o.status}`,`Started: ${o.createdAt} Finished: ${o.updatedAt||"\u2014"}`,"","Jobs:"];for(let i of o.jobs||[]){let a=i.conclusion==="success"?"\u2713":i.conclusion==="failure"?"\u2717":"\u25CB";r.push(` ${a} ${i.name} (${i.conclusion||i.status})`);for(let c of i.steps||[]){if(c.conclusion==="failure"||c.conclusion==="skipped")continue;let l=c.conclusion==="success"?" \u2713":c.conclusion==="failure"?" \u2717":" \u25CB";r.push(` ${l} ${c.name}`)}}return r.join(`
347
+ `)[0]}`}}case"gh_run_view":{if(!e.run_id)return"ERROR: run_id is required";try{if(e.log){let{stdout:i}=await Ce(`gh run view ${e.run_id} --log`,{cwd:process.cwd(),timeout:6e4,maxBuffer:5242880});return i.substring(0,8e3)+(i.length>8e3?`
348
+ ...(truncated)`:"")}let{stdout:n}=await Ce(`gh run view ${e.run_id} --json status,conclusion,name,headBranch,createdAt,updatedAt,jobs`,{cwd:process.cwd(),timeout:3e4}),o=JSON.parse(n),r=[`Run: ${o.name} [${e.run_id}]`,`Branch: ${o.headBranch} Status: ${o.conclusion||o.status}`,`Started: ${o.createdAt} Finished: ${o.updatedAt||"\u2014"}`,"","Jobs:"];for(let i of o.jobs||[]){let a=i.conclusion==="success"?"\u2713":i.conclusion==="failure"?"\u2717":"\u25CB";r.push(` ${a} ${i.name} (${i.conclusion||i.status})`);for(let c of i.steps||[]){if(c.conclusion==="failure"||c.conclusion==="skipped")continue;let l=c.conclusion==="success"?" \u2713":c.conclusion==="failure"?" \u2717":" \u25CB";r.push(` ${l} ${c.name}`)}}return r.join(`
318
349
  `)}catch(n){return`ERROR: ${(n.stderr||n.message||"").toString().split(`
319
- `)[0]}`}}case"gh_workflow_trigger":{if(!e.workflow)return"ERROR: workflow is required";let{confirm:n}=Es(),o=e.branch||await bf()||"main",r=e.inputs?Object.entries(e.inputs).map(([c,l])=>`-f ${c}=${l}`).join(" "):"",i=`gh workflow run ${e.workflow} --ref ${o} ${r}`.trim();if(console.log(`
320
- ${ae.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${o}${ae.reset}`),!await n(" Trigger?"))return"CANCELLED: User declined to trigger workflow.";try{return await Ee(i,{cwd:process.cwd(),timeout:3e4}),`Workflow "${e.workflow}" triggered on branch "${o}". Check status with gh_run_list.`}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
321
- `)[0]}`}}case"k8s_pods":{let n=e.namespace?`-n ${e.namespace}`:"-A",o=e.label?`-l ${e.label}`:"",r=Zs(`get pods ${n} ${o} -o wide`.trim(),e);try{let{stdout:i,stderr:a}=await Ee(r,{timeout:3e4,maxBuffer:2097152});return(i||a||"(no pods)").trim()}catch(i){let a=(i.stderr||i.message||"").toString().split(`
322
- `)[0];return a.includes("command not found")?"ERROR: kubectl not found. Install kubectl or provide a server with kubectl.":`ERROR: ${a}`}}case"k8s_logs":{if(!e.pod)return"ERROR: pod is required";let n=e.namespace||"default",o=e.tail||100,r=`logs ${e.pod} -n ${n} --tail=${o}`;e.since&&(r+=` --since=${e.since}`),e.container&&(r+=` -c ${e.container}`);let i=Zs(r,e);try{let{stdout:a,stderr:c}=await Ee(i,{timeout:6e4,maxBuffer:5242880}),l=(a||c||"(no logs)").trim();return l.substring(0,2e4)+(l.length>2e4?`
350
+ `)[0]}`}}case"gh_workflow_trigger":{if(!e.workflow)return"ERROR: workflow is required";let{confirm:n}=Cs(),o=e.branch||await Lf()||"main",r=e.inputs?Object.entries(e.inputs).map(([c,l])=>`-f ${c}=${l}`).join(" "):"",i=`gh workflow run ${e.workflow} --ref ${o} ${r}`.trim();if(console.log(`
351
+ ${ce.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${o}${ce.reset}`),!await n(" Trigger?"))return"CANCELLED: User declined to trigger workflow.";try{return await Ce(i,{cwd:process.cwd(),timeout:3e4}),`Workflow "${e.workflow}" triggered on branch "${o}". Check status with gh_run_list.`}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
352
+ `)[0]}`}}case"k8s_pods":{let n=e.namespace?`-n ${e.namespace}`:"-A",o=e.label?`-l ${e.label}`:"",r=to(`get pods ${n} ${o} -o wide`.trim(),e);try{let{stdout:i,stderr:a}=await Ce(r,{timeout:3e4,maxBuffer:2097152});return(i||a||"(no pods)").trim()}catch(i){let a=(i.stderr||i.message||"").toString().split(`
353
+ `)[0];return a.includes("command not found")?"ERROR: kubectl not found. Install kubectl or provide a server with kubectl.":`ERROR: ${a}`}}case"k8s_logs":{if(!e.pod)return"ERROR: pod is required";let n=e.namespace||"default",o=e.tail||100,r=`logs ${e.pod} -n ${n} --tail=${o}`;e.since&&(r+=` --since=${e.since}`),e.container&&(r+=` -c ${e.container}`);let i=to(r,e);try{let{stdout:a,stderr:c}=await Ce(i,{timeout:6e4,maxBuffer:5242880}),l=(a||c||"(no logs)").trim();return l.substring(0,2e4)+(l.length>2e4?`
323
354
  ...(truncated)`:"")}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
324
355
  `)[0]}`}}case"k8s_exec":{if(!e.pod)return"ERROR: pod is required";if(!e.command)return"ERROR: command is required";let n=e.namespace||"default";if(console.log(`
325
- ${ae.yellow} \u26A0 kubectl exec into pod: ${e.pod} (ns: ${n})${ae.reset}`),console.log(`${ae.dim} Command: ${e.command}${ae.reset}`),!await kt(" Execute in pod?"))return"CANCELLED: User declined.";let r=`exec ${e.pod} -n ${n}`;e.container&&(r+=` -c ${e.container}`),r+=` -- sh -c ${JSON.stringify(e.command)}`;let i=Zs(r,e);try{let{stdout:a,stderr:c}=await Ee(i,{timeout:6e4,maxBuffer:2097152});return(a||c||"(no output)").trim()}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
356
+ ${ce.yellow} \u26A0 kubectl exec into pod: ${e.pod} (ns: ${n})${ce.reset}`),console.log(`${ce.dim} Command: ${e.command}${ce.reset}`),!await vt(" Execute in pod?"))return"CANCELLED: User declined.";let r=`exec ${e.pod} -n ${n}`;e.container&&(r+=` -c ${e.container}`),r+=` -- sh -c ${JSON.stringify(e.command)}`;let i=to(r,e);try{let{stdout:a,stderr:c}=await Ce(i,{timeout:6e4,maxBuffer:2097152});return(a||c||"(no output)").trim()}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
326
357
  `)[0]}`}}case"k8s_apply":{if(!e.file)return"ERROR: file is required";let n=!!e.dry_run;if(!n){let i=e.file;if(console.log(`
327
- ${ae.yellow} \u26A0 kubectl apply: ${i}${e.namespace?` (ns: ${e.namespace})`:""}${ae.reset}`),!await kt(" Apply to cluster?"))return"CANCELLED: User declined."}let o=`apply -f ${e.file}`;e.namespace&&(o+=` -n ${e.namespace}`),n&&(o+=" --dry-run=client");let r=Zs(o,e);try{let{stdout:i,stderr:a}=await Ee(r,{timeout:12e4,maxBuffer:2097152});return(i||a||"(no output)").trim()}catch(i){return`ERROR: ${(i.stderr||i.message||"").toString().split(`
358
+ ${ce.yellow} \u26A0 kubectl apply: ${i}${e.namespace?` (ns: ${e.namespace})`:""}${ce.reset}`),!await vt(" Apply to cluster?"))return"CANCELLED: User declined."}let o=`apply -f ${e.file}`;e.namespace&&(o+=` -n ${e.namespace}`),n&&(o+=" --dry-run=client");let r=to(o,e);try{let{stdout:i,stderr:a}=await Ce(r,{timeout:12e4,maxBuffer:2097152});return(i||a||"(no output)").trim()}catch(i){return`ERROR: ${(i.stderr||i.message||"").toString().split(`
328
359
  `)[0]}`}}case"k8s_rollout":{if(!e.action)return"ERROR: action is required";if(!e.deployment)return"ERROR: deployment is required";let n=e.namespace||"default";if(e.action==="restart"||e.action==="undo"){let a=e.action==="restart"?"Rolling restart":"Rollback (undo)";if(console.log(`
329
- ${ae.yellow} \u26A0 ${a}: deployment/${e.deployment} (ns: ${n})${ae.reset}`),!await kt(` ${a}?`))return"CANCELLED: User declined."}let r=`rollout ${e.action} deployment/${e.deployment} -n ${n}`,i=Zs(r,e);try{let{stdout:a,stderr:c}=await Ee(i,{timeout:12e4,maxBuffer:2097152});return(a||c||"(no output)").trim()}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
330
- `)[0]}`}}case"brain_write":{if(!e.name)return"ERROR: name is required";if(!e.content)return"ERROR: content is required";if(!e.mode)return"ERROR: mode is required (create, update, append)";let{writeDocument:n,readDocument:o}=va(),{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 c=o(r),l=c.content?c.content+`
360
+ ${ce.yellow} \u26A0 ${a}: deployment/${e.deployment} (ns: ${n})${ce.reset}`),!await vt(` ${a}?`))return"CANCELLED: User declined."}let r=`rollout ${e.action} deployment/${e.deployment} -n ${n}`,i=to(r,e);try{let{stdout:a,stderr:c}=await Ce(i,{timeout:12e4,maxBuffer:2097152});return(a||c||"(no output)").trim()}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
361
+ `)[0]}`}}case"brain_write":{if(!e.name)return"ERROR: name is required";if(!e.content)return"ERROR: content is required";if(!e.mode)return"ERROR: mode is required (create, update, append)";let{writeDocument:n,readDocument:o}=Ma(),{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 c=o(r),l=c.content?c.content+`
331
362
 
332
- `+i:i;return n(r,l),`Appended to brain document: ${r}.md`}return n(r,i),`${a==="create"?"Created":"Updated"} brain document: ${r}.md`}case"ssh_exec":{if(!e.server)return"ERROR: server is required";if(!e.command)return"ERROR: command is required";let n;try{n=$t(e.server)}catch(C){return`ERROR: ${C.message}`}let o=e.command,r=!!e.sudo,i=(e.timeout||30)*1e3,a=n0(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:
363
+ `+i:i;return n(r,l),`Appended to brain document: ${r}.md`}return n(r,i),`${a==="create"?"Created":"Updated"} brain document: ${r}.md`}case"ssh_exec":{if(!e.server)return"ERROR: server is required";if(!e.command)return"ERROR: command is required";let n;try{n=bt(e.server)}catch(C){return`ERROR: ${C.message}`}let o=e.command,r=!!e.sudo,i=(e.timeout||30)*1e3,a=$0(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:
333
364
  grep -n "pattern" /path/to/file -A 50
334
365
  or to read the whole file:
335
366
  cat /path/to/file
336
367
  NEVER use sed -n again \u2014 it will always be blocked.`:`BLOCKED: Remote command matches SSH secret-exposure pattern: ${a}
337
- 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,(C,K,Q)=>{let re=Math.min(Number(Q),20);return`${K} ${re}`}),o=o.replace(/(--(?:before|after|context)=)(\d+)/g,(C,K,Q)=>K+Math.min(Number(Q),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 C=n.user?`${n.user}@${n.host}`:n.host;if(console.log(`
338
- ${ae.yellow} \u26A0 Remote command on ${C}: ${o}${ae.reset}`),!await kt(" Execute on remote server?"))return"CANCELLED: User declined to execute remote command."}let{stdout:l,stderr:u,exitCode:d,error:f}=await ot(n,o,{timeout:i,sudo:r}),h=[l,u].filter(Boolean).join(`
368
+ 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,(C,Z,Y)=>{let ue=Math.min(Number(Y),20);return`${Z} ${ue}`}),o=o.replace(/(--(?:before|after|context)=)(\d+)/g,(C,Z,Y)=>Z+Math.min(Number(Y),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 C=n.user?`${n.user}@${n.host}`:n.host;if(console.log(`
369
+ ${ce.yellow} \u26A0 Remote command on ${C}: ${o}${ce.reset}`),!await vt(" Execute on remote server?"))return"CANCELLED: User declined to execute remote command."}let{stdout:l,stderr:u,exitCode:d,error:f}=await rt(n,o,{timeout:i,sudo:r}),h=[l,u].filter(Boolean).join(`
339
370
  `).trim();if(d!==0)return`EXIT ${d}
340
- ${f||h||"(no output)"}`;let m=/\bgrep\b/.test(o),g=h;m&&(g=g.split(`
371
+ ${f||h||"(no output)"}`;let g=/\bgrep\b/.test(o),m=h;g&&(m=m.split(`
341
372
  `).filter(C=>C!=="--").join(`
342
- `));let b=m?60:100,v=g.split(`
343
- `);v.length>b&&(g=`(${v.length-b} earlier lines omitted \u2014 showing last ${b})
344
- `+v.slice(-b).join(`
345
- `));let O=4,U=g.split(`
346
- `),L=[],R=0;for(;R<U.length;){let C=R+1;for(;C<U.length&&U[C]===U[R];)C++;let K=C-R;if(L.push(U[R]),K>O)L.push(`... (${K-1} identical lines omitted)`);else for(let Q=1;Q<K;Q++)L.push(U[R]);R=C}return L.join(`
347
- `)||"(command completed, no output)"}case"ssh_upload":{if(!e.server||!e.local_path||!e.remote_path)return"ERROR: server, local_path, and remote_path are required";let n;try{n=$t(e.server)}catch(i){return`ERROR: ${i.message}`}let o=n.user?`${n.user}@${n.host}`:n.host;if(console.log(`
348
- ${ae.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${o}:${e.remote_path}${ae.reset}`),!await kt(" Upload to remote server?"))return"CANCELLED: User declined upload.";try{return await d0(n,e.local_path,e.remote_path)}catch(i){return`ERROR: ${i.message}`}}case"ssh_download":{if(!e.server||!e.remote_path||!e.local_path)return"ERROR: server, remote_path, and local_path are required";let n;try{n=$t(e.server)}catch(o){return`ERROR: ${o.message}`}try{return await f0(n,e.remote_path,e.local_path)}catch(o){return`ERROR: ${o.message}`}}case"remote_agent":{let n=require("path").join(process.cwd(),".nex","servers.json"),o=null;try{o=JSON.parse(require("fs").readFileSync(n,"utf-8"))[e.server]||null}catch{}let r=o?`${o.user||"root"}@${o.host}`:e.server,i=o?.key?["-i",o.key]:[],a=e.project_path||o?.home||"~",c=e.model||"",u=["TMPFILE=$(mktemp /tmp/nexcode-XXXXXX.txt)",`echo "${Buffer.from(e.task).toString("base64")}" | base64 -d > "$TMPFILE"`,`cd "${a}" 2>/dev/null || true`,c?`nex-code --prompt-file "$TMPFILE" --auto --model "${c}" 2>&1`:'nex-code --prompt-file "$TMPFILE" --auto 2>&1',"EXIT_CODE=$?",'rm -f "$TMPFILE"',"exit $EXIT_CODE"].join(" && "),{spawnSync:d}=require("child_process"),f=d("ssh",[...i,"-o","StrictHostKeyChecking=no","-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 h=(f.stdout||"")+(f.stderr||"");return f.status!==0?`Remote nex-code exited with code ${f.status}.
349
- ${h.slice(-2e3)}`:h.slice(-5e3)||"Remote nex-code completed (no output)"}case"service_manage":{if(!e.service)return"ERROR: service is required";if(!e.action)return"ERROR: action is required";let n=["status","start","stop","restart","reload","enable","disable"];if(!n.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${n.join(", ")}`;let o=!e.server||e.server==="local"||e.server==="localhost",r=e.action==="status",i=null;if(!o)try{i=$t(e.server)}catch(c){return`ERROR: ${c.message}`}if(!r){let c=o?"local machine":i.user?`${i.user}@${i.host}`:i.host;if(console.log(`
350
- ${ae.yellow} \u26A0 Service: systemctl ${e.action} ${e.service} on ${c}${ae.reset}`),!await kt(" Execute?"))return"CANCELLED: User declined service action."}let a=`systemctl ${e.action} ${e.service}`;if(o){let l=e.action!=="status"?`sudo ${a}`:a;try{let{stdout:u,stderr:d}=await Ee(l,{timeout:15e3});return(u||d||`systemctl ${e.action} ${e.service}: OK`).trim()}catch(u){let d=(u.stderr||u.message||"").toString().trim();return/not found|loaded.*not-found/i.test(d)?`ERROR: Service "${e.service}" not found. Check: systemctl list-units --type=service`:`EXIT ${u.code||1}
351
- ${d}`}}else{let{stdout:c,stderr:l,exitCode:u,error:d}=await ot(i,a,{timeout:15e3,sudo:!0}),f=[c,l].filter(Boolean).join(`
373
+ `));let b=g?60:100,x=m.split(`
374
+ `);x.length>b&&(m=`(${x.length-b} earlier lines omitted \u2014 showing last ${b})
375
+ `+x.slice(-b).join(`
376
+ `));let j=4,G=m.split(`
377
+ `),L=[],P=0;for(;P<G.length;){let C=P+1;for(;C<G.length&&G[C]===G[P];)C++;let Z=C-P;if(L.push(G[P]),Z>j)L.push(`... (${Z-1} identical lines omitted)`);else for(let Y=1;Y<Z;Y++)L.push(G[P]);P=C}return L.join(`
378
+ `)||"(command completed, no output)"}case"ssh_upload":{if(!e.server||!e.local_path||!e.remote_path)return"ERROR: server, local_path, and remote_path are required";let n;try{n=bt(e.server)}catch(i){return`ERROR: ${i.message}`}let o=n.user?`${n.user}@${n.host}`:n.host;if(console.log(`
379
+ ${ce.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${o}:${e.remote_path}${ce.reset}`),!await vt(" Upload to remote server?"))return"CANCELLED: User declined upload.";try{return await T0(n,e.local_path,e.remote_path)}catch(i){return`ERROR: ${i.message}`}}case"ssh_download":{if(!e.server||!e.remote_path||!e.local_path)return"ERROR: server, remote_path, and local_path are required";let n;try{n=bt(e.server)}catch(o){return`ERROR: ${o.message}`}try{return await R0(n,e.remote_path,e.local_path)}catch(o){return`ERROR: ${o.message}`}}case"remote_agent":{let n=require("path").join(process.cwd(),".nex","servers.json"),o=null;try{o=JSON.parse(require("fs").readFileSync(n,"utf-8"))[e.server]||null}catch{}let r=o?`${o.user||"root"}@${o.host}`:e.server,i=o?.key?["-i",o.key]:[],a=e.project_path||o?.home||"~",c=e.model||"",u=["TMPFILE=$(mktemp /tmp/nexcode-XXXXXX.txt)",`echo "${Buffer.from(e.task).toString("base64")}" | base64 -d > "$TMPFILE"`,`cd "${a}" 2>/dev/null || true`,c?`nex-code --prompt-file "$TMPFILE" --auto --model "${c}" 2>&1`:'nex-code --prompt-file "$TMPFILE" --auto 2>&1',"EXIT_CODE=$?",'rm -f "$TMPFILE"',"exit $EXIT_CODE"].join(" && "),{spawnSync:d}=require("child_process"),f=d("ssh",[...i,"-o","StrictHostKeyChecking=no","-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 h=(f.stdout||"")+(f.stderr||"");return f.status!==0?`Remote nex-code exited with code ${f.status}.
380
+ ${h.slice(-2e3)}`:h.slice(-5e3)||"Remote nex-code completed (no output)"}case"service_manage":{if(!e.service)return"ERROR: service is required";if(!e.action)return"ERROR: action is required";let n=["status","start","stop","restart","reload","enable","disable"];if(!n.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${n.join(", ")}`;let o=!e.server||e.server==="local"||e.server==="localhost",r=e.action==="status",i=null;if(!o)try{i=bt(e.server)}catch(c){return`ERROR: ${c.message}`}if(!r){let c=o?"local machine":i.user?`${i.user}@${i.host}`:i.host;if(console.log(`
381
+ ${ce.yellow} \u26A0 Service: systemctl ${e.action} ${e.service} on ${c}${ce.reset}`),!await vt(" Execute?"))return"CANCELLED: User declined service action."}let a=`systemctl ${e.action} ${e.service}`;if(o){let l=e.action!=="status"?`sudo ${a}`:a;try{let{stdout:u,stderr:d}=await Ce(l,{timeout:15e3});return(u||d||`systemctl ${e.action} ${e.service}: OK`).trim()}catch(u){let d=(u.stderr||u.message||"").toString().trim();return/not found|loaded.*not-found/i.test(d)?`ERROR: Service "${e.service}" not found. Check: systemctl list-units --type=service`:`EXIT ${u.code||1}
382
+ ${d}`}}else{let{stdout:c,stderr:l,exitCode:u,error:d}=await rt(i,a,{timeout:15e3,sudo:!0}),f=[c,l].filter(Boolean).join(`
352
383
  `).trim();return u!==0?/not found|loaded.*not-found/i.test(f)?`ERROR: Service "${e.service}" not found on ${i.host}. Check: ssh_exec to run "systemctl list-units --type=service"`:`EXIT ${u}
353
- ${d||f||"(no output)"}`:f||`systemctl ${e.action} ${e.service}: OK`}}case"service_logs":{if(!e.service)return"ERROR: service is required";let n=!e.server||e.server==="local"||e.server==="localhost",o=e.lines||50,r=e.since?`--since "${e.since}"`:"",i=e.follow?"-f":"",a=`journalctl -u ${e.service} -n ${o} ${r} ${i} --no-pager`.trim().replace(/\s+/g," ");if(n)try{let{stdout:m,stderr:g}=await Ee(a,{timeout:15e3});return(m||g||"(no log output)").trim()}catch(m){return`EXIT ${m.code||1}
354
- ${(m.stderr||m.message||"").toString().trim()}`}let c;try{c=$t(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:l,stderr:u,exitCode:d,error:f}=await ot(c,a,{timeout:2e4}),h=[l,u].filter(Boolean).join(`
384
+ ${d||f||"(no output)"}`:f||`systemctl ${e.action} ${e.service}: OK`}}case"service_logs":{if(!e.service)return"ERROR: service is required";let n=!e.server||e.server==="local"||e.server==="localhost",o=e.lines||50,r=e.since?`--since "${e.since}"`:"",i=e.follow?"-f":"",a=`journalctl -u ${e.service} -n ${o} ${r} ${i} --no-pager`.trim().replace(/\s+/g," ");if(n)try{let{stdout:g,stderr:m}=await Ce(a,{timeout:15e3});return(g||m||"(no log output)").trim()}catch(g){return`EXIT ${g.code||1}
385
+ ${(g.stderr||g.message||"").toString().trim()}`}let c;try{c=bt(e.server)}catch(g){return`ERROR: ${g.message}`}let{stdout:l,stderr:u,exitCode:d,error:f}=await rt(c,a,{timeout:2e4}),h=[l,u].filter(Boolean).join(`
355
386
  `).trim();return d!==0?`EXIT ${d}
356
- ${f||h||"(no output)"}`:h||"(no log output)"}case"container_list":{let n=!e.server||e.server==="local"||e.server==="localhost",r=`docker ps ${e.all?"-a":""} --format "table {{.ID}}\\t{{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}"`.trim().replace(/\s+/g," ");if(n)try{let{stdout:f,stderr:h}=await Ee(r,{timeout:1e4});return(f||h||"(no containers)").trim()}catch(f){return`EXIT ${f.code||1}
357
- ${(f.stderr||f.message||"").toString().trim()}`}let i;try{i=$t(e.server)}catch(f){return`ERROR: ${f.message}`}let{stdout:a,stderr:c,exitCode:l,error:u}=await ot(i,r,{timeout:15e3}),d=[a,c].filter(Boolean).join(`
387
+ ${f||h||"(no output)"}`:h||"(no log output)"}case"container_list":{let n=!e.server||e.server==="local"||e.server==="localhost",r=`docker ps ${e.all?"-a":""} --format "table {{.ID}}\\t{{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}"`.trim().replace(/\s+/g," ");if(n)try{let{stdout:f,stderr:h}=await Ce(r,{timeout:1e4});return(f||h||"(no containers)").trim()}catch(f){return`EXIT ${f.code||1}
388
+ ${(f.stderr||f.message||"").toString().trim()}`}let i;try{i=bt(e.server)}catch(f){return`ERROR: ${f.message}`}let{stdout:a,stderr:c,exitCode:l,error:u}=await rt(i,r,{timeout:15e3}),d=[a,c].filter(Boolean).join(`
358
389
  `).trim();return l!==0?`EXIT ${l}
359
- ${u||d}`:d||"(no containers)"}case"container_logs":{if(!e.container)return"ERROR: container is required";let n=!e.server||e.server==="local"||e.server==="localhost",o=e.lines||50,r=e.since?`--since "${e.since}"`:"",i=`docker logs --tail ${o} ${r} ${e.container} 2>&1`.trim().replace(/\s+/g," ");if(n)try{let{stdout:h,stderr:m}=await Ee(i,{timeout:15e3});return(h||m||"(no log output)").trim()}catch(h){return`EXIT ${h.code||1}
360
- ${(h.stderr||h.message||"").toString().trim()}`}let a;try{a=$t(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:c,stderr:l,exitCode:u,error:d}=await ot(a,i,{timeout:2e4}),f=[c,l].filter(Boolean).join(`
390
+ ${u||d}`:d||"(no containers)"}case"container_logs":{if(!e.container)return"ERROR: container is required";let n=!e.server||e.server==="local"||e.server==="localhost",o=e.lines||50,r=e.since?`--since "${e.since}"`:"",i=`docker logs --tail ${o} ${r} ${e.container} 2>&1`.trim().replace(/\s+/g," ");if(n)try{let{stdout:h,stderr:g}=await Ce(i,{timeout:15e3});return(h||g||"(no log output)").trim()}catch(h){return`EXIT ${h.code||1}
391
+ ${(h.stderr||h.message||"").toString().trim()}`}let a;try{a=bt(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:c,stderr:l,exitCode:u,error:d}=await rt(a,i,{timeout:2e4}),f=[c,l].filter(Boolean).join(`
361
392
  `).trim();return u!==0?`EXIT ${u}
362
- ${d||f}`:f||"(no log output)"}case"container_exec":{if(!e.container)return"ERROR: container is required";if(!e.command)return"ERROR: command is required";let n=!e.server||e.server==="local"||e.server==="localhost",o=/^(cat|ls|echo|env|printenv|df|du|ps|id|whoami|uname|hostname|date|pwd|which|find\s|head\s|tail\s|grep\s|curl\s+-[A-Za-z]*G|curl\s+https?:\/\/[^\s]+$)/;if(!s.autoConfirm&&!o.test(e.command.trim())){let m=n?"local":e.server;if(console.log(`
363
- ${ae.yellow} \u26A0 docker exec in ${e.container} on ${m}: ${e.command}${ae.reset}`),!await kt(" Execute?"))return"CANCELLED: User declined."}let i=(e.container||"").replace(/[^a-zA-Z0-9._\/-]/g,"");if(!i)return"ERROR: Invalid container name";let a=`docker exec ${i} sh -c ${JSON.stringify(e.command)}`;if(n)try{let{stdout:m,stderr:g}=await Ee(a,{timeout:3e4});return(m||g||"(no output)").trim()}catch(m){return`EXIT ${m.code||1}
364
- ${(m.stderr||m.message||"").toString().trim()}`}let c;try{c=$t(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:l,stderr:u,exitCode:d,error:f}=await ot(c,a,{timeout:35e3}),h=[l,u].filter(Boolean).join(`
393
+ ${d||f}`:f||"(no log output)"}case"container_exec":{if(!e.container)return"ERROR: container is required";if(!e.command)return"ERROR: command is required";let n=!e.server||e.server==="local"||e.server==="localhost",o=/^(cat|ls|echo|env|printenv|df|du|ps|id|whoami|uname|hostname|date|pwd|which|find\s|head\s|tail\s|grep\s|curl\s+-[A-Za-z]*G|curl\s+https?:\/\/[^\s]+$)/;if(!s.autoConfirm&&!o.test(e.command.trim())){let g=n?"local":e.server;if(console.log(`
394
+ ${ce.yellow} \u26A0 docker exec in ${e.container} on ${g}: ${e.command}${ce.reset}`),!await vt(" Execute?"))return"CANCELLED: User declined."}let i=(e.container||"").replace(/[^a-zA-Z0-9._\/-]/g,"");if(!i)return"ERROR: Invalid container name";let a=`docker exec ${i} sh -c ${JSON.stringify(e.command)}`;if(n)try{let{stdout:g,stderr:m}=await Ce(a,{timeout:3e4});return(g||m||"(no output)").trim()}catch(g){return`EXIT ${g.code||1}
395
+ ${(g.stderr||g.message||"").toString().trim()}`}let c;try{c=bt(e.server)}catch(g){return`ERROR: ${g.message}`}let{stdout:l,stderr:u,exitCode:d,error:f}=await rt(c,a,{timeout:35e3}),h=[l,u].filter(Boolean).join(`
365
396
  `).trim();return d!==0?`EXIT ${d}
366
- ${f||h}`:h||"(no output)"}case"container_manage":{if(!e.container)return"ERROR: container is required";if(!e.action)return"ERROR: action is required";let n=["start","stop","restart","remove","inspect"];if(!n.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${n.join(", ")}`;let o=!e.server||e.server==="local"||e.server==="localhost";if(!(e.action==="inspect")&&!s.autoConfirm){let m=o?"local":e.server;if(console.log(`
367
- ${ae.yellow} \u26A0 docker ${e.action} ${e.container} on ${m}${ae.reset}`),!await kt(" Execute?"))return"CANCELLED: User declined."}let i=e.action==="remove"?"rm":e.action,a=e.action==="inspect"?`docker inspect ${e.container}`:`docker ${i} ${e.container}`;if(o)try{let{stdout:m,stderr:g}=await Ee(a,{timeout:3e4});return(m||g||`docker ${e.action} ${e.container}: OK`).trim()}catch(m){return`EXIT ${m.code||1}
368
- ${(m.stderr||m.message||"").toString().trim()}`}let c;try{c=$t(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:l,stderr:u,exitCode:d,error:f}=await ot(c,a,{timeout:35e3}),h=[l,u].filter(Boolean).join(`
397
+ ${f||h}`:h||"(no output)"}case"container_manage":{if(!e.container)return"ERROR: container is required";if(!e.action)return"ERROR: action is required";let n=["start","stop","restart","remove","inspect"];if(!n.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${n.join(", ")}`;let o=!e.server||e.server==="local"||e.server==="localhost";if(!(e.action==="inspect")&&!s.autoConfirm){let g=o?"local":e.server;if(console.log(`
398
+ ${ce.yellow} \u26A0 docker ${e.action} ${e.container} on ${g}${ce.reset}`),!await vt(" 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:g,stderr:m}=await Ce(a,{timeout:3e4});return(g||m||`docker ${e.action} ${e.container}: OK`).trim()}catch(g){return`EXIT ${g.code||1}
399
+ ${(g.stderr||g.message||"").toString().trim()}`}let c;try{c=bt(e.server)}catch(g){return`ERROR: ${g.message}`}let{stdout:l,stderr:u,exitCode:d,error:f}=await rt(c,a,{timeout:35e3}),h=[l,u].filter(Boolean).join(`
369
400
  `).trim();return d!==0?`EXIT ${d}
370
- ${f||h}`:h||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...p0(e.config),...e},delete e.config,delete e._name}catch(u){return`ERROR: ${u.message}`}if(!e.server)return'ERROR: server is required (or use config: "<name>")';if(!e.remote_path)return"ERROR: remote_path is required";let n=e.method||"rsync";if(n==="rsync"&&!e.local_path)return"ERROR: local_path is required for rsync method";let o;try{o=$t(e.server)}catch(u){return`ERROR: ${u.message}`}let r=o.user?`${o.user}@${o.host}`:o.host;if(!e.dry_run&&!s.autoConfirm){if(n==="git"){let d=e.branch?` (branch: ${e.branch})`:"";console.log(`
371
- ${ae.yellow} \u26A0 Deploy [git pull]: ${r}:${e.remote_path}${d}${ae.reset}`)}else{let d=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`;console.log(`
372
- ${ae.yellow} \u26A0 Deploy [rsync]: ${d} \u2192 ${r}:${e.remote_path}${ae.reset}`)}if(e.deploy_script&&console.log(`${ae.yellow} Then run: ${e.deploy_script}${ae.reset}`),e.health_check&&console.log(`${ae.yellow} Health check: ${e.health_check}${ae.reset}`),!await kt(" Proceed with deployment?"))return"CANCELLED: User declined."}let i="";if(n==="git"){let u=(e.branch||"").replace(/[^a-zA-Z0-9._\/-]/g,"");if(e.branch&&u!==e.branch)return`ERROR: Invalid branch name: ${e.branch}`;let d=(e.remote_path||"").replace(/'/g,"'\\''"),f=u?`cd '${d}' && git fetch origin && git checkout '${u}' && git pull origin '${u}'`:`cd '${d}' && git pull`;if(e.dry_run)return`DRY RUN [git]: would run on ${r}:
401
+ ${f||h}`:h||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...C0(e.config),...e},delete e.config,delete e._name}catch(u){return`ERROR: ${u.message}`}if(!e.server)return'ERROR: server is required (or use config: "<name>")';if(!e.remote_path)return"ERROR: remote_path is required";let n=e.method||"rsync";if(n==="rsync"&&!e.local_path)return"ERROR: local_path is required for rsync method";let o;try{o=bt(e.server)}catch(u){return`ERROR: ${u.message}`}let r=o.user?`${o.user}@${o.host}`:o.host;if(!e.dry_run&&!s.autoConfirm){if(n==="git"){let d=e.branch?` (branch: ${e.branch})`:"";console.log(`
402
+ ${ce.yellow} \u26A0 Deploy [git pull]: ${r}:${e.remote_path}${d}${ce.reset}`)}else{let d=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`;console.log(`
403
+ ${ce.yellow} \u26A0 Deploy [rsync]: ${d} \u2192 ${r}:${e.remote_path}${ce.reset}`)}if(e.deploy_script&&console.log(`${ce.yellow} Then run: ${e.deploy_script}${ce.reset}`),e.health_check&&console.log(`${ce.yellow} Health check: ${e.health_check}${ce.reset}`),!await vt(" Proceed with deployment?"))return"CANCELLED: User declined."}let i="";if(n==="git"){let u=(e.branch||"").replace(/[^a-zA-Z0-9._\/-]/g,"");if(e.branch&&u!==e.branch)return`ERROR: Invalid branch name: ${e.branch}`;let d=(e.remote_path||"").replace(/'/g,"'\\''"),f=u?`cd '${d}' && git fetch origin && git checkout '${u}' && git pull origin '${u}'`:`cd '${d}' && git pull`;if(e.dry_run)return`DRY RUN [git]: would run on ${r}:
373
404
  ${f}${e.deploy_script?`
374
- ${e.deploy_script}`:""}`;let{stdout:h,stderr:m,exitCode:g,error:b}=await ot(o,f,{timeout:12e4});if(i=[h,m].filter(Boolean).join(`
375
- `).trim(),g!==0)return`ERROR (git pull, exit ${g}):
376
- ${b||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":"",h=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`,m=`rsync -avz --delete ${f} ${d} ${u} ${h} ${r}:${e.remote_path}`.trim().replace(/\s+/g," ");try{let{stdout:g,stderr:b}=await Ee(m,{timeout:12e4});i=(g||b||"").trim()}catch(g){return`ERROR (rsync): ${(g.stderr||g.message||"").toString().trim()}`}if(e.dry_run)return`DRY RUN [rsync]:
377
- ${i||"(nothing to sync)"}`}let a="";if(e.deploy_script){let{stdout:u,stderr:d,exitCode:f,error:h}=await ot(o,e.deploy_script,{timeout:12e4}),m=[u,d].filter(Boolean).join(`
405
+ ${e.deploy_script}`:""}`;let{stdout:h,stderr:g,exitCode:m,error:b}=await rt(o,f,{timeout:12e4});if(i=[h,g].filter(Boolean).join(`
406
+ `).trim(),m!==0)return`ERROR (git pull, exit ${m}):
407
+ ${b||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(m=>`--exclude="${m}"`).join(" "),f=e.dry_run?"--dry-run":"",h=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`,g=`rsync -avz --delete ${f} ${d} ${u} ${h} ${r}:${e.remote_path}`.trim().replace(/\s+/g," ");try{let{stdout:m,stderr:b}=await Ce(g,{timeout:12e4});i=(m||b||"").trim()}catch(m){return`ERROR (rsync): ${(m.stderr||m.message||"").toString().trim()}`}if(e.dry_run)return`DRY RUN [rsync]:
408
+ ${i||"(nothing to sync)"}`}let a="";if(e.deploy_script){let{stdout:u,stderr:d,exitCode:f,error:h}=await rt(o,e.deploy_script,{timeout:12e4}),g=[u,d].filter(Boolean).join(`
378
409
  `).trim();if(f!==0)return`${n==="git"?"git pull":"rsync"} OK
379
410
 
380
411
  ERROR (deploy_script, exit ${f}):
381
- ${h||m}`;a=`
412
+ ${h||g}`;a=`
382
413
 
383
414
  Deploy script output:
384
- ${m||"(no output)"}`}let c="";if(e.health_check){let u=e.health_check.trim();if(/^https?:\/\//.test(u))try{let f=require("node-fetch"),h=await Promise.race([f(u),new Promise((m,g)=>setTimeout(()=>g(new Error("timeout")),15e3))]);if(h.ok)c=`
415
+ ${g||"(no output)"}`}let c="";if(e.health_check){let u=e.health_check.trim();if(/^https?:\/\//.test(u))try{let f=require("node-fetch"),h=await Promise.race([f(u),new Promise((g,m)=>setTimeout(()=>m(new Error("timeout")),15e3))]);if(h.ok)c=`
385
416
 
386
417
  Health check: \u2713 ${u} \u2192 ${h.status}`;else return c=`
387
418
 
388
419
  Health check FAILED: ${u} \u2192 HTTP ${h.status}`,(n==="git"?"git pull OK":"rsync OK")+i+a+c}catch(f){return c=`
389
420
 
390
- Health check FAILED: ${u} \u2192 ${f.message}`,(n==="git"?"git pull OK":"rsync OK")+i+a+c}else{let{stdout:f,stderr:h,exitCode:m}=await ot(o,u,{timeout:15e3}),g=[f,h].filter(Boolean).join(`
391
- `).trim();if(m!==0)return c=`
421
+ Health check FAILED: ${u} \u2192 ${f.message}`,(n==="git"?"git pull OK":"rsync OK")+i+a+c}else{let{stdout:f,stderr:h,exitCode:g}=await rt(o,u,{timeout:15e3}),m=[f,h].filter(Boolean).join(`
422
+ `).trim();if(g!==0)return c=`
392
423
 
393
- Health check FAILED (exit ${m}): ${g}`,(n==="git"?"git pull OK":"rsync OK")+i+a+c;c=`
424
+ Health check FAILED (exit ${g}): ${m}`,(n==="git"?"git pull OK":"rsync OK")+i+a+c;c=`
394
425
 
395
- Health check: \u2713 ${g||"(exit 0)"}`}}let l=n==="git"?`${r}:${e.remote_path}`:`${e.local_path} \u2192 ${r}:${e.remote_path}`;return`Deployed [${n}] ${l}
396
- ${i}${a}${c}`.trim()}case"deployment_status":{let n=h0(),o=e.config?[e.config]:Object.keys(n);if(o.length===0)return"No deploy configs found. Create .nex/deploy.json to configure deployments.";let r=[];for(let i of o){let a=n[i];if(!a){r.push(`${i}: NOT FOUND`);continue}try{let c=$t(a.server||i),u=(await ot(c,"echo OK",{timeout:1e4})).stdout.trim()==="OK",d="unknown";if(u&&a.deploy_script){let h=a.deploy_script.match(/systemctl\s+\w+\s+(\S+)/);if(h)try{d=(await ot(c,`systemctl is-active ${h[1]}`,{timeout:1e4})).stdout.trim()}catch{d="inactive"}}let f="N/A";if(a.health_check){let h=a.health_check.trim();if(/^https?:\/\//.test(h))try{let m=require("node-fetch"),g=await Promise.race([m(h),new Promise((b,v)=>setTimeout(()=>v(new Error("timeout")),1e4))]);f=g.ok?"healthy":`HTTP ${g.status}`}catch(m){f=`unhealthy: ${m.message.substring(0,50)}`}else try{f=(await ot(c,h,{timeout:1e4})).exitCode===0?"healthy":"unhealthy"}catch{f="unhealthy"}}r.push(`${i}: server=${u?"reachable":"unreachable"} service=${d} health=${f}`)}catch(c){r.push(`${i}: ERROR \u2014 ${c.message}`)}}return`Deployment Status:
426
+ Health check: \u2713 ${m||"(exit 0)"}`}}let l=n==="git"?`${r}:${e.remote_path}`:`${e.local_path} \u2192 ${r}:${e.remote_path}`;return`Deployed [${n}] ${l}
427
+ ${i}${a}${c}`.trim()}case"deployment_status":{let n=A0(),o=e.config?[e.config]:Object.keys(n);if(o.length===0)return"No deploy configs found. Create .nex/deploy.json to configure deployments.";let r=[];for(let i of o){let a=n[i];if(!a){r.push(`${i}: NOT FOUND`);continue}try{let c=bt(a.server||i),u=(await rt(c,"echo OK",{timeout:1e4})).stdout.trim()==="OK",d="unknown";if(u&&a.deploy_script){let h=a.deploy_script.match(/systemctl\s+\w+\s+(\S+)/);if(h)try{d=(await rt(c,`systemctl is-active ${h[1]}`,{timeout:1e4})).stdout.trim()}catch{d="inactive"}}let f="N/A";if(a.health_check){let h=a.health_check.trim();if(/^https?:\/\//.test(h))try{let g=require("node-fetch"),m=await Promise.race([g(h),new Promise((b,x)=>setTimeout(()=>x(new Error("timeout")),1e4))]);f=m.ok?"healthy":`HTTP ${m.status}`}catch(g){f=`unhealthy: ${g.message.substring(0,50)}`}else try{f=(await rt(c,h,{timeout:1e4})).exitCode===0?"healthy":"unhealthy"}catch{f="unhealthy"}}r.push(`${i}: server=${u?"reachable":"unreachable"} service=${d} health=${f}`)}catch(c){r.push(`${i}: ERROR \u2014 ${c.message}`)}}return`Deployment Status:
397
428
  ${r.join(`
398
- `)}`}case"frontend_recon":{let n=process.cwd(),o=(e.type||"").toLowerCase(),r=[],i=async(L,R=120)=>{try{let C=ve.isAbsolute(L)?L:ve.join(n,L),Q=(await je.readFile(C,"utf8")).split(`
399
- `),re=Q.slice(0,R).join(`
400
- `);return Q.length>R?re+`
401
- ... (${Q.length-R} more lines \u2014 use read_file for full content)`:re}catch{return null}},c=["node_modules",".git","dist","build","vendor",".next","__pycache__","venv",".venv"].map(L=>`-not -path "*/${L}/*"`).join(" "),l=async L=>{try{let{stdout:R}=await Ee(`find "${n}" -type f -name "${L}" ${c} 2>/dev/null | head -10`,{timeout:8e3});return R.trim().split(`
402
- `).filter(Boolean)}catch{return[]}},u=async(L,R)=>{try{let{stdout:C}=await Ee(`grep -rl "${L}" "${n}" --include="${R}" --exclude-dir=node_modules --exclude-dir=.git --exclude-dir=dist --exclude-dir=build 2>/dev/null | head -5`,{timeout:8e3});return C.trim().split(`
429
+ `)}`}case"frontend_recon":{let n=process.cwd(),o=(e.type||"").toLowerCase(),r=[],i=async(L,P=120)=>{try{let C=Ee.isAbsolute(L)?L:Ee.join(n,L),Y=(await De.readFile(C,"utf8")).split(`
430
+ `),ue=Y.slice(0,P).join(`
431
+ `);return Y.length>P?ue+`
432
+ ... (${Y.length-P} more lines \u2014 use read_file for full content)`:ue}catch{return null}},c=["node_modules",".git","dist","build","vendor",".next","__pycache__","venv",".venv"].map(L=>`-not -path "*/${L}/*"`).join(" "),l=async L=>{try{let{stdout:P}=await Ce(`find "${n}" -type f -name "${L}" ${c} 2>/dev/null | head -10`,{timeout:8e3});return P.trim().split(`
433
+ `).filter(Boolean)}catch{return[]}},u=async(L,P)=>{try{let{stdout:C}=await Ce(`grep -rl "${L}" "${n}" --include="${P}" --exclude-dir=node_modules --exclude-dir=.git --exclude-dir=dist --exclude-dir=build 2>/dev/null | head -5`,{timeout:8e3});return C.trim().split(`
403
434
  `).filter(Boolean)}catch{return[]}};r.push(`## STEP 1: Design Tokens
404
- `);let d=[...await l("tailwind.config.js"),...await l("tailwind.config.ts"),...await l("tailwind.config.mjs")];if(d.length>0){let L=await i(d[0],80);L&&r.push(`### Tailwind config (${ve.relative(n,d[0])})
435
+ `);let d=[...await l("tailwind.config.js"),...await l("tailwind.config.ts"),...await l("tailwind.config.mjs")];if(d.length>0){let L=await i(d[0],80);L&&r.push(`### Tailwind config (${Ee.relative(n,d[0])})
405
436
  \`\`\`js
406
437
  ${L}
407
- \`\`\``)}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"],h=!1;for(let L of f){let R=await l(L);for(let C of R){let K=await i(C,100);if(K&&K.includes(":root")){r.push(`### CSS Variables (${ve.relative(n,C)})
438
+ \`\`\``)}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"],h=!1;for(let L of f){let P=await l(L);for(let C of P){let Z=await i(C,100);if(Z&&Z.includes(":root")){r.push(`### CSS Variables (${Ee.relative(n,C)})
408
439
  \`\`\`css
409
- ${K}
410
- \`\`\``),h=!0;break}}if(h)break}if(!h){let L=await u(":root","*.css");if(L.length>0){let R=await i(L[0],100);R&&r.push(`### CSS Variables (${ve.relative(n,L[0])})
440
+ ${Z}
441
+ \`\`\``),h=!0;break}}if(h)break}if(!h){let L=await u(":root","*.css");if(L.length>0){let P=await i(L[0],100);P&&r.push(`### CSS Variables (${Ee.relative(n,L[0])})
411
442
  \`\`\`css
412
- ${R}
443
+ ${P}
413
444
  \`\`\``),h=!0}}h||r.push("(no CSS custom properties / :root found)"),r.push(`
414
445
  ## STEP 2: Main Layout / Index Page
415
- `);let m=["base.html","_base.html","layout.html","base.jinja","App.vue","App.jsx","App.tsx","_app.jsx","_app.tsx","_app.js","layout.vue","index.html"],g=!1;for(let L of m){let R=await l(L);if(R.length>0){let C=await i(R[0],150);if(C){r.push(`### Main layout: ${ve.relative(n,R[0])}
446
+ `);let g=["base.html","_base.html","layout.html","base.jinja","App.vue","App.jsx","App.tsx","_app.jsx","_app.tsx","_app.js","layout.vue","index.html"],m=!1;for(let L of g){let P=await l(L);if(P.length>0){let C=await i(P[0],150);if(C){r.push(`### Main layout: ${Ee.relative(n,P[0])}
416
447
  \`\`\`html
417
448
  ${C}
418
- \`\`\``),g=!0;break}}}g||r.push("(no main layout/index file found \u2014 try read_file on your root template manually)"),r.push(`
449
+ \`\`\``),m=!0;break}}}m||r.push("(no main layout/index file found \u2014 try read_file on your root template manually)"),r.push(`
419
450
  ## STEP 3: Reference Component (same type)
420
- `);let b=[];if(o){for(let L of["*.html","*.vue","*.jsx","*.tsx"])if(b=await u(o,L),b.length>0)break}if(b.length===0)try{let{stdout:L}=await Ee(`find "${n}" -type f \\( -name "*.html" -o -name "*.vue" -o -name "*.jsx" -o -name "*.tsx" \\) -not -path "*/node_modules/*" -not -path "*/.git/*" -not -path "*/dist/*" -not -path "*/build/*" -not -name "base.html" -not -name "_base.html" -not -name "layout.html" -not -name "App.vue" -not -name "App.jsx" 2>/dev/null | head -20`,{timeout:8e3});b=L.trim().split(`
421
- `).filter(Boolean)}catch{b=[]}if(b.length>0){let L=b[0],R=await i(L,150);R?r.push(`### Reference: ${ve.relative(n,L)}
451
+ `);let b=[];if(o){for(let L of["*.html","*.vue","*.jsx","*.tsx"])if(b=await u(o,L),b.length>0)break}if(b.length===0)try{let{stdout:L}=await Ce(`find "${n}" -type f \\( -name "*.html" -o -name "*.vue" -o -name "*.jsx" -o -name "*.tsx" \\) -not -path "*/node_modules/*" -not -path "*/.git/*" -not -path "*/dist/*" -not -path "*/build/*" -not -name "base.html" -not -name "_base.html" -not -name "layout.html" -not -name "App.vue" -not -name "App.jsx" 2>/dev/null | head -20`,{timeout:8e3});b=L.trim().split(`
452
+ `).filter(Boolean)}catch{b=[]}if(b.length>0){let L=b[0],P=await i(L,150);P?r.push(`### Reference: ${Ee.relative(n,L)}
422
453
  \`\`\`html
423
- ${R}
454
+ ${P}
424
455
  \`\`\``):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(`
425
456
  ## STEP 4: Framework Stack
426
- `);let v=[],O=await i(ve.join(n,"package.json"),999);if(O){if((O.includes('"react"')||O.includes("'react'"))&&v.push("React"),O.includes('"vue"')||O.includes("'vue'")){let R=O.match(/"vue":\s*"[\^~]?(\d+)/);v.push(R?`Vue.js v${R[1]}`:"Vue.js")}let L=O.match(/"alpinejs":\s*"[\^~]?(\d+)/);L&&v.push(`Alpine.js v${L[1]} (\u26A0 v2 vs v3 API differs!)`),(O.includes('"htmx')||O.includes("'htmx"))&&v.push("HTMX"),O.includes('"tailwindcss"')&&v.push("Tailwind CSS"),O.includes('"bootstrap"')&&v.push("Bootstrap")}if((await ft(ve.join(n,"manage.py"))||(await i(ve.join(n,"requirements.txt"),50)||"").includes("Django"))&&v.push("Django (server-rendered templates)"),!v.some(L=>L.includes("Alpine"))){let L=await u("alpinejs","*.html");if(L.length>0){let C=(await i(L[0],30)||"").match(/alpinejs[@/]v?(\d)/);v.push(C?`Alpine.js v${C[1]} (via CDN \u2014 \u26A0 v2 vs v3 API differs!)`:"Alpine.js (via CDN \u2014 check version!)")}}return v.some(L=>L.includes("HTMX"))||(await u("htmx","*.html")).length>0&&v.push("HTMX (via CDN)"),v.length>0?(r.push(v.map(L=>`- ${L}`).join(`
457
+ `);let x=[],j=await i(Ee.join(n,"package.json"),999);if(j){if((j.includes('"react"')||j.includes("'react'"))&&x.push("React"),j.includes('"vue"')||j.includes("'vue'")){let P=j.match(/"vue":\s*"[\^~]?(\d+)/);x.push(P?`Vue.js v${P[1]}`:"Vue.js")}let L=j.match(/"alpinejs":\s*"[\^~]?(\d+)/);L&&x.push(`Alpine.js v${L[1]} (\u26A0 v2 vs v3 API differs!)`),(j.includes('"htmx')||j.includes("'htmx"))&&x.push("HTMX"),j.includes('"tailwindcss"')&&x.push("Tailwind CSS"),j.includes('"bootstrap"')&&x.push("Bootstrap")}if((await pt(Ee.join(n,"manage.py"))||(await i(Ee.join(n,"requirements.txt"),50)||"").includes("Django"))&&x.push("Django (server-rendered templates)"),!x.some(L=>L.includes("Alpine"))){let L=await u("alpinejs","*.html");if(L.length>0){let C=(await i(L[0],30)||"").match(/alpinejs[@/]v?(\d)/);x.push(C?`Alpine.js v${C[1]} (via CDN \u2014 \u26A0 v2 vs v3 API differs!)`:"Alpine.js (via CDN \u2014 check version!)")}}return x.some(L=>L.includes("HTMX"))||(await u("htmx","*.html")).length>0&&x.push("HTMX (via CDN)"),x.length>0?(r.push(x.map(L=>`- ${L}`).join(`
427
458
  `)),r.push(`
428
459
  \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(`
429
460
  ---
430
461
  \u2705 Design recon complete. Now build consistently with the patterns above.`),r.join(`
431
- `)}case"sysadmin":{if(!e.action)return"ERROR: action is required";let n=!e.server||e.server==="local"||e.server==="localhost",o;if(!n)try{o=$t(e.server)}catch(c){return`ERROR: ${c.message}`}let r=async(c,l=3e4)=>{if(n)try{let{stdout:u,stderr:d}=await Ee(c,{timeout:l});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:h}=await ot(o,c,{timeout:l}),m=[u,d].filter(Boolean).join(`
462
+ `)}case"sysadmin":{if(!e.action)return"ERROR: action is required";let n=!e.server||e.server==="local"||e.server==="localhost",o;if(!n)try{o=bt(e.server)}catch(c){return`ERROR: ${c.message}`}let r=async(c,l=3e4)=>{if(n)try{let{stdout:u,stderr:d}=await Ce(c,{timeout:l});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:h}=await rt(o,c,{timeout:l}),g=[u,d].filter(Boolean).join(`
432
463
  `).trim();return{out:h&&f!==0&&!u.trim()?(h+`
433
- `+m).trim():m,exitCode:f}}};if(!(["audit","disk_usage","process_list","network_status","ssl_check","log_tail","find_large","journalctl"].includes(e.action)||e.action==="package"&&e.package_action==="list"||e.action==="user_manage"&&["list","info"].includes(e.user_action)||e.action==="firewall"&&e.firewall_action==="status"||e.action==="cron"&&e.cron_action==="list"||e.action==="service"&&["status","list_failed"].includes(e.service_action))&&!s.autoConfirm){let c=n?"local":e.server;if(!await kt(`sysadmin [${e.action}] on ${c} \u2014 proceed?`))return"Cancelled."}switch(e.action){case"audit":{let c=["echo '=== OS / KERNEL ==='","cat /etc/os-release 2>/dev/null | grep -E '^(NAME|VERSION)=' || uname -a","echo '=== UPTIME / LOAD ==='","uptime","echo '=== MEMORY / SWAP ==='","free -h","echo '=== DISK ==='","df -h --output=target,size,used,avail,pcent 2>/dev/null || df -h","echo '=== TOP 10 PROCESSES (CPU) ==='","ps aux --sort=-%cpu | head -11","echo '=== FAILED SYSTEMD UNITS ==='","systemctl list-units --state=failed --no-legend 2>/dev/null || echo '(systemctl not available)'","echo '=== RECENT ERRORS (journalctl) ==='","journalctl -p err --no-pager -n 15 2>/dev/null || echo '(journalctl not available)'","echo '=== LISTENING PORTS ==='","ss -tlnp 2>/dev/null || netstat -tlnp 2>/dev/null || echo '(ss/netstat not available)'"].join(" && "),{out:l,exitCode:u}=await r(c,45e3);return l||`EXIT ${u}
464
+ `+g).trim():g,exitCode:f}}};if(!(["audit","disk_usage","process_list","network_status","ssl_check","log_tail","find_large","journalctl"].includes(e.action)||e.action==="package"&&e.package_action==="list"||e.action==="user_manage"&&["list","info"].includes(e.user_action)||e.action==="firewall"&&e.firewall_action==="status"||e.action==="cron"&&e.cron_action==="list"||e.action==="service"&&["status","list_failed"].includes(e.service_action))&&!s.autoConfirm){let c=n?"local":e.server;if(!await vt(`sysadmin [${e.action}] on ${c} \u2014 proceed?`))return"Cancelled."}switch(e.action){case"audit":{let c=["echo '=== OS / KERNEL ==='","cat /etc/os-release 2>/dev/null | grep -E '^(NAME|VERSION)=' || uname -a","echo '=== UPTIME / LOAD ==='","uptime","echo '=== MEMORY / SWAP ==='","free -h","echo '=== DISK ==='","df -h --output=target,size,used,avail,pcent 2>/dev/null || df -h","echo '=== TOP 10 PROCESSES (CPU) ==='","ps aux --sort=-%cpu | head -11","echo '=== FAILED SYSTEMD UNITS ==='","systemctl list-units --state=failed --no-legend 2>/dev/null || echo '(systemctl not available)'","echo '=== RECENT ERRORS (journalctl) ==='","journalctl -p err --no-pager -n 15 2>/dev/null || echo '(journalctl not available)'","echo '=== LISTENING PORTS ==='","ss -tlnp 2>/dev/null || netstat -tlnp 2>/dev/null || echo '(ss/netstat not available)'"].join(" && "),{out:l,exitCode:u}=await r(c,45e3);return l||`EXIT ${u}
434
465
  (no output)`}case"disk_usage":{let c=e.path||"/",l=`df -h ${c}; echo '--- Top subdirs ---'; du -d1 -x -h ${c} 2>/dev/null | sort -rh | head -20`,{out:u,exitCode:d}=await r(l,3e4);return d!==0?`EXIT ${d}
435
466
  ${u}`:u}case"process_list":{let c=e.sort_by==="mem"?"4":"3",l=(e.limit||20)+1,u=`ps aux --sort=-${e.sort_by==="mem"?"%mem":"%cpu"} 2>/dev/null | head -${l} || ps aux | awk 'NR==1{print; next} {print | "sort -k${c} -rn"}' | head -${l}`,{out:d,exitCode:f}=await r(u,15e3);return f!==0?`EXIT ${f}
436
467
  ${d}`:d}case"network_status":{let c="ss -tlnp 2>/dev/null || netstat -tlnp 2>/dev/null; echo '--- Active connections ---'; ss -tnp 2>/dev/null | head -30",{out:l,exitCode:u}=await r(c,15e3);return u!==0?`EXIT ${u}
437
- ${l}`:l}case"package":{if(!e.package_action)return"ERROR: package_action is required for action=package";let{out:c}=await r("which dnf 2>/dev/null && echo dnf || (which apt-get 2>/dev/null && echo apt) || echo unknown",1e4),l=c.includes("dnf")?"dnf":c.includes("apt")?"apt":null;if(!l)return"ERROR: No supported package manager found (dnf/apt)";let u=(e.packages||[]).join(" "),d;switch(e.package_action){case"list":d=l==="dnf"?"dnf list installed 2>/dev/null | head -60":"dpkg -l | head -60";break;case"check":{let m=l==="dnf"?'dnf check-update 2>/dev/null; EC=$?; [ $EC -eq 100 ] && echo "EXIT_STATUS: updates_available" || ([ $EC -eq 0 ] && echo "EXIT_STATUS: up_to_date" || echo "EXIT_STATUS: error $EC")':"apt-get -s upgrade 2>/dev/null | tail -5",{out:g}=await r(m,6e4);return g||"(no output from package check)"}case"install":if(!u)return"ERROR: packages required for install";d=l==="dnf"?`dnf install -y ${u}`:`apt-get install -y ${u}`;break;case"remove":if(!u)return"ERROR: packages required for remove";d=l==="dnf"?`dnf remove -y ${u}`:`apt-get remove -y ${u}`;break;case"update":if(!u)return"ERROR: packages required for update (use upgrade for full system upgrade)";d=l==="dnf"?`dnf update -y ${u}`:`apt-get install -y --only-upgrade ${u}`;break;case"upgrade":d=l==="dnf"?"dnf upgrade -y":"DEBIAN_FRONTEND=noninteractive apt-get upgrade -y";break;default:return`ERROR: Unknown package_action: ${e.package_action}`}let{out:f,exitCode:h}=await r(d,12e4);return h!==0?`EXIT ${h}
468
+ ${l}`:l}case"package":{if(!e.package_action)return"ERROR: package_action is required for action=package";let{out:c}=await r("which dnf 2>/dev/null && echo dnf || (which apt-get 2>/dev/null && echo apt) || echo unknown",1e4),l=c.includes("dnf")?"dnf":c.includes("apt")?"apt":null;if(!l)return"ERROR: No supported package manager found (dnf/apt)";let u=(e.packages||[]).join(" "),d;switch(e.package_action){case"list":d=l==="dnf"?"dnf list installed 2>/dev/null | head -60":"dpkg -l | head -60";break;case"check":{let g=l==="dnf"?'dnf check-update 2>/dev/null; EC=$?; [ $EC -eq 100 ] && echo "EXIT_STATUS: updates_available" || ([ $EC -eq 0 ] && echo "EXIT_STATUS: up_to_date" || echo "EXIT_STATUS: error $EC")':"apt-get -s upgrade 2>/dev/null | tail -5",{out:m}=await r(g,6e4);return m||"(no output from package check)"}case"install":if(!u)return"ERROR: packages required for install";d=l==="dnf"?`dnf install -y ${u}`:`apt-get install -y ${u}`;break;case"remove":if(!u)return"ERROR: packages required for remove";d=l==="dnf"?`dnf remove -y ${u}`:`apt-get remove -y ${u}`;break;case"update":if(!u)return"ERROR: packages required for update (use upgrade for full system upgrade)";d=l==="dnf"?`dnf update -y ${u}`:`apt-get install -y --only-upgrade ${u}`;break;case"upgrade":d=l==="dnf"?"dnf upgrade -y":"DEBIAN_FRONTEND=noninteractive apt-get upgrade -y";break;default:return`ERROR: Unknown package_action: ${e.package_action}`}let{out:f,exitCode:h}=await r(d,12e4);return h!==0?`EXIT ${h}
438
469
  ${f}`:f||`${e.package_action} OK`}case"user_manage":{if(!e.user_action)return"ERROR: user_action is required for action=user_manage";switch(e.user_action){case"list":{let c=`awk -F: '$3 >= 1000 && $1 != "nobody" {print $1, "uid="$3, "gid="$4, "shell="$7}' /etc/passwd`,{out:l,exitCode:u}=await r(c,1e4);return u!==0?`EXIT ${u}
439
470
  ${l}`:l||"(no regular users)"}case"info":{if(!e.user)return"ERROR: user is required for user_action=info";let c=`id ${e.user} && echo '--- Groups ---' && groups ${e.user} && echo '--- Last login ---' && lastlog -u ${e.user} 2>/dev/null`,{out:l,exitCode:u}=await r(c,1e4);return u!==0?`EXIT ${u}
440
471
  ${l}`:l}case"create":{if(!e.user)return"ERROR: user is required for user_action=create";let l=`useradd -m ${(e.groups||[]).map(f=>`-G ${f}`).join(" ")} ${e.user} && echo "User ${e.user} created"`,{out:u,exitCode:d}=await r(l,15e3);return d!==0?`EXIT ${d}
@@ -472,8 +503,8 @@ ${u}`:u||"(empty log)"}case"find_large":{let c=e.path||"/",l=e.limit||20,u=e.min
472
503
  ${f}`:f||`(no files larger than ${u} in ${c})`}case"service":{if(!e.service_action)return"ERROR: service_action is required for action=service";if(e.service_action!=="list_failed"&&!e.service_name)return"ERROR: service_name is required (except for list_failed)";let c=e.service_name?e.service_name.includes(".")?e.service_name:`${e.service_name}.service`:"",l;switch(e.service_action){case"status":l=`systemctl status ${c} --no-pager -l 2>&1 | head -40`;break;case"list_failed":l="systemctl list-units --state=failed --no-legend 2>/dev/null";break;case"start":l=`systemctl start ${c} && systemctl status ${c} --no-pager -l 2>&1 | head -20`;break;case"stop":l=`systemctl stop ${c} && echo "${c} stopped"`;break;case"restart":l=`systemctl restart ${c} && systemctl status ${c} --no-pager -l 2>&1 | head -20`;break;case"reload":l=`systemctl reload ${c} 2>&1 || systemctl reload-or-restart ${c} 2>&1`;break;case"enable":l=`systemctl enable ${c} && echo "${c} enabled"`;break;case"disable":l=`systemctl disable ${c} && echo "${c} disabled"`;break;default:return`ERROR: Unknown service_action: ${e.service_action}`}let{out:u,exitCode:d}=await r(l,3e4);return d===0||e.service_action==="status"&&d===3?u||`service ${e.service_action} OK`:`EXIT ${d}
473
504
  ${u}`}case"kill_process":{if(!e.pid&&!e.process_name)return"ERROR: pid or process_name is required for kill_process";let c=e.signal||"SIGTERM",l;e.pid?l=`ps -p ${e.pid} -o pid,user,%cpu,%mem,etime,cmd 2>/dev/null && kill -${c} ${e.pid} && echo "Sent ${c} to PID ${e.pid}"`:l=`pgrep -a "${e.process_name}" 2>/dev/null | head -5 && pkill -${c} "${e.process_name}" && echo "Sent ${c} to all '${e.process_name}' processes"`;let{out:u,exitCode:d}=await r(l,15e3);return d!==0?`EXIT ${d}
474
505
  ${u}`:u}case"journalctl":{let c=e.lines||100,l=["journalctl","--no-pager","-n",String(c)];e.unit&&l.push("-u",e.unit.includes(".")?e.unit:`${e.unit}.service`),e.priority&&l.push("-p",e.priority),e.since&&l.push(`--since="${e.since}"`),l.push('2>/dev/null || echo "(journalctl not available)"');let{out:u,exitCode:d}=await r(l.join(" "),2e4);return d!==0?`EXIT ${d}
475
- ${u}`:u||"(no log entries)"}default:return`ERROR: Unknown sysadmin action: ${e.action}`}}case"save_memory":{let{saveMemory:n}=zs(),o=n(e.type,e.name,e.content,e.description);return o.ok?o.updated===!1?`Memory unchanged (duplicate): ${e.type}/${e.name}`:`Memory saved: ${e.type}/${e.name} \u2192 ${o.path}`:`ERROR: ${o.error}`}case"delete_memory":{let{deleteMemory:n}=zs();return n(e.type,e.name)?`Memory deleted: ${e.type}/${e.name}`:`Memory not found: ${e.type}/${e.name}`}default:{let{executePluginTool:n}=rr(),o=await n(t,e,s);return o!==null?o:`ERROR: Unknown tool: ${t}`}}}async function k0(t,e,s={}){let{emit:n}=rr(),{logToolExecution:o}=yf(),r=Date.now(),i=s.silent?null:a0(t,e);if(!i){let c=await vf(t,e,s);return o({tool:t,args:e,result:c,duration:Date.now()-r,success:!c.startsWith?.("ERROR")}),await n("onToolResult",{tool:t,args:e,result:c}),c}let a=new i0(i);a.start();try{let c=await vf(t,e,s);return a.stop(),o({tool:t,args:e,result:c,duration:Date.now()-r,success:!c.startsWith?.("ERROR")}),await n("onToolResult",{tool:t,args:e,result:c}),c}catch(c){throw a.stop(),o({tool:t,args:e,result:c.message,duration:Date.now()-r,success:!1}),c}}Tf.exports={TOOL_DEFINITIONS:x0,executeTool:k0,resolvePath:rt,autoFixPath:Cr,autoFixEdit:Ef,enrichBashError:Sf,cancelPendingAskUser:w0,setAskUserHandler:b0,fileExists:ft}});var Jn=se((Qk,Cf)=>{Cf.exports=Rf()});var La=se((tv,Af)=>{var{loadServerProfiles:eo,resolveProfile:ev,sshExec:v0}=ra(),Ma={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 S0(){let t=eo();if(Object.keys(t).length===0)return null;let s=["## Remote Servers (.nex/servers.json)"];s.push(""),s.push("Available server profiles (use with ssh_exec, ssh_upload, ssh_download, service_manage, service_logs, container_list, container_logs, container_exec, container_manage, deploy):");for(let[o,r]of Object.entries(t)){let i=r.user?`${r.user}@${r.host}`:r.host,a=r.port&&Number(r.port)!==22?`:${r.port}`:"",c=r.os?` \u2014 OS: ${r.os}`:"",l=r.sudo?", sudo available":"";s.push(`- **${o}**: ${i}${a}${c}${l}`)}let n=new Set;for(let o of Object.values(t))o.os&&Ma[o.os]&&n.add(o.os);if(n.size>0){s.push("");for(let o of n){let r={almalinux9:"AlmaLinux 9",almalinux8:"AlmaLinux 8",ubuntu:"Ubuntu",debian:"Debian",macos:"macOS"}[o]||o;s.push(`### ${r} Notes`);for(let i of Ma[o])s.push(`- ${i}`)}}return s.join(`
476
- `)}function E0(t){let e=eo();return Object.values(e).some(s=>s.os&&s.os.startsWith(t))}function T0(){return Object.keys(eo())}function R0(){let t=require("fs"),s=require("path").join(process.cwd(),"NEX.md"),n="";try{n=t.readFileSync(s,"utf-8")}catch{}let o=eo(),r=Object.keys(o);if(r.length===0)return null;let i=["server","deploy","remote","ssh","service","systemctl","production","linux","almalinux","ubuntu","debian"],a=n.toLowerCase();if(!i.some(f=>a.includes(f)))return null;let l=r.map(f=>{let h=o[f],m=h.user?`${h.user}@${h.host}`:h.host,g=h.port&&Number(h.port)!==22?`:${h.port}`:"";return` - **${f}**: ${m}${g}${h.os?` (${h.os})`:""}`}).join(`
506
+ ${u}`:u||"(no log entries)"}default:return`ERROR: Unknown sysadmin action: ${e.action}`}}case"save_memory":{let{saveMemory:n}=Js(),o=n(e.type,e.name,e.content,e.description);return o.ok?o.updated===!1?`Memory unchanged (duplicate): ${e.type}/${e.name}`:`Memory saved: ${e.type}/${e.name} \u2192 ${o.path}`:`ERROR: ${o.error}`}case"delete_memory":{let{deleteMemory:n}=Js();return n(e.type,e.name)?`Memory deleted: ${e.type}/${e.name}`:`Memory not found: ${e.type}/${e.name}`}default:{let{executePluginTool:n}=cr(),o=await n(t,e,s);return o!==null?o:`ERROR: Unknown tool: ${t}`}}}async function q0(t,e,s={}){let{emit:n}=cr(),{logToolExecution:o}=Of(),r=Date.now(),i=s.silent?null:k0(t,e);if(!i){let c=await Df(t,e,s);return o({tool:t,args:e,result:c,duration:Date.now()-r,success:!c.startsWith?.("ERROR")}),await n("onToolResult",{tool:t,args:e,result:c}),c}let a=new x0(i);a.start();try{let c=await Df(t,e,s);return a.stop(),o({tool:t,args:e,result:c,duration:Date.now()-r,success:!c.startsWith?.("ERROR")}),await n("onToolResult",{tool:t,args:e,result:c}),c}catch(c){throw a.stop(),o({tool:t,args:e,result:c.message,duration:Date.now()-r,success:!1}),c}}Bf.exports={TOOL_DEFINITIONS:D0,executeTool:q0,resolvePath:it,autoFixPath:Nr,autoFixEdit:Ff,enrichBashError:qf,cancelPendingAskUser:P0,setAskUserHandler:I0,fileExists:pt}});var ts=re((bv,Uf)=>{Uf.exports=Wf()});var Ua=re((xv,Hf)=>{var{loadServerProfiles:so,resolveProfile:_v,sshExec:F0}=pa(),Wa={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 B0(){let t=so();if(Object.keys(t).length===0)return null;let s=["## Remote Servers (.nex/servers.json)"];s.push(""),s.push("Available server profiles (use with ssh_exec, ssh_upload, ssh_download, service_manage, service_logs, container_list, container_logs, container_exec, container_manage, deploy):");for(let[o,r]of Object.entries(t)){let i=r.user?`${r.user}@${r.host}`:r.host,a=r.port&&Number(r.port)!==22?`:${r.port}`:"",c=r.os?` \u2014 OS: ${r.os}`:"",l=r.sudo?", sudo available":"";s.push(`- **${o}**: ${i}${a}${c}${l}`)}let n=new Set;for(let o of Object.values(t))o.os&&Wa[o.os]&&n.add(o.os);if(n.size>0){s.push("");for(let o of n){let r={almalinux9:"AlmaLinux 9",almalinux8:"AlmaLinux 8",ubuntu:"Ubuntu",debian:"Debian",macos:"macOS"}[o]||o;s.push(`### ${r} Notes`);for(let i of Wa[o])s.push(`- ${i}`)}}return s.join(`
507
+ `)}function W0(t){let e=so();return Object.values(e).some(s=>s.os&&s.os.startsWith(t))}function U0(){return Object.keys(so())}function H0(){let t=require("fs"),s=require("path").join(process.cwd(),"NEX.md"),n="";try{n=t.readFileSync(s,"utf-8")}catch{}let o=so(),r=Object.keys(o);if(r.length===0)return null;let i=["server","deploy","remote","ssh","service","systemctl","production","linux","almalinux","ubuntu","debian"],a=n.toLowerCase();if(!i.some(f=>a.includes(f)))return null;let l=r.map(f=>{let h=o[f],g=h.user?`${h.user}@${h.host}`:h.host,m=h.port&&Number(h.port)!==22?`:${h.port}`:"";return` - **${f}**: ${g}${m}${h.os?` (${h.os})`:""}`}).join(`
477
508
  `),u=r.map(f=>o[f].log_path).filter(Boolean),d=u.length>0?`
478
509
  - Server log paths: ${u.join(", ")}`:"";return`# Deployment Context (Auto-detected)
479
510
 
@@ -491,42 +522,44 @@ ${l}
491
522
  - \u274C Do NOT \`read_file\` on paths like \`logs/\` \u2014 these files do not exist locally
492
523
  - \u274C Do NOT \`list_directory\` on server paths \u2014 the local project is the source, not the running instance
493
524
 
494
- **When in doubt:** If a path contains \`logs/\`, \`/var/log/\`, or \`/home/<user>/\` \u2014 it is on the server. SSH there.${C0(o)}`}function C0(t){return Object.values(t).some(s=>s.host==="94.130.37.43")?`
525
+ **When in doubt:** If a path contains \`logs/\`, \`/var/log/\`, or \`/home/<user>/\` \u2014 it is on the server. SSH there.${Y0(o)}`}function Y0(t){return Object.values(t).some(s=>s.host==="94.130.37.43")?`
495
526
 
496
- ## Jarvis Debugging Rules
527
+ ## Server Debugging Rules
497
528
 
498
- - Jarvis errors (set_reminder, cron, Google Auth, SmartThings) come from the DEPLOYED server at 94.130.37.43
499
- - ALWAYS use ssh_exec to investigate: ssh_exec on 94.130.37.43, check /home/jarvis/jarvis-agent/logs/
500
- - NEVER run local bash/find/sqlite3 commands when debugging Jarvis issues
501
- - Local jarvis-agent/ is just source code \u2014 the running system is on the server
502
- - CRITICAL: When the user pastes a Jarvis error message ("jarvisFehler:", "jarvisEinige Fehler", 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.
503
- - LOG FILES: Always check the CURRENT log first: /home/jarvis/jarvis-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.
529
+ - Server errors (set_reminder, cron, Google Auth, SmartThings) come from the DEPLOYED server at 94.130.37.43
530
+ - ALWAYS use ssh_exec to investigate: ssh_exec on 94.130.37.43, check /home/deploy/server-agent/logs/
531
+ - NEVER run local bash/find/sqlite3 commands when debugging server issues
532
+ - Local server-agent/ is just source code \u2014 the running system is on the server
533
+ - 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.
534
+ - 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.
504
535
  - 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.
505
- - 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 A0(t){if(typeof t!="string")return null;let e=[...t.matchAll(/https?:\/\/([a-zA-Z0-9._-]+)/g)];if(e.length===0)return null;let s=eo();if(Object.keys(s).length===0)return null;let n=null,o=null;for(let[,i]of e){let a=i.toLowerCase().split(".");for(let[c,l]of Object.entries(s))if(a.includes(c.toLowerCase())){n=l,o=c;break}if(n)break;for(let[c,l]of Object.entries(s))if(l.host===i){n=l,o=c;break}if(n)break}if(!n||!o)return null;let r=["ss -tlnp 2>/dev/null | awk 'NR>1{print $4}' | grep -oE ':[0-9]+$' | sort -u | head -8","echo '---services---'","ps aux 2>/dev/null | grep -E '(node |python3 |gunicorn|uvicorn|ruby |java )' | grep -v grep | awk '{print $11, $12, $13}' | head -6","echo '---data---'","find /home -maxdepth 5 -name 'data' -type d 2>/dev/null | head -6"].join("; ");try{let{stdout:i}=await v0(n,r,{timeout:4e3});if(!i||i.trim().length<5)return null;let a=n.user?`${n.user}@${n.host}`:n.host;return`[Server context for "${o}" (${a}) \u2014 probed at task start]
506
- `+i.trim()}catch{return null}}Af.exports={getServerContext:S0,getDeploymentContextBlock:R0,hasServerOS:E0,getProfileNames:T0,probeUrlServer:A0,OS_HINTS:Ma}});var Lf=se((nv,Mf)=>{var vt=require("fs").promises,Of=require("fs"),tt=require("path"),Ar=require("util").promisify(require("child_process").exec),{C:as}=Ue(),{getMergeConflicts:Nf}=er(),{getServerContext:O0}=La(),N0=new Set(["node_modules",".git",".svn","dist","build","coverage",".nyc_output","__pycache__",".DS_Store",".next",".nuxt",".turbo",".cache","vendor","tmp","temp"]);function M0(t){try{return Of.readFileSync(t,"utf-8").split(`
507
- `).map(s=>s.trim()).filter(s=>s&&!s.startsWith("#")&&!s.startsWith("!")).map(s=>s.replace(/\/$/,""))}catch{return[]}}function L0(t,e){for(let s of e)if(s===t||s.includes("*")&&new RegExp("^"+s.replace(/\./g,"\\.").replace(/\*/g,".*")+"$").test(t))return!0;return!1}function P0(t,{maxDepth:e=3,maxFiles:s=200,giPatterns:n=[]}={}){let o=tt.join(t,".gitignore"),r=[...n,...M0(o)],i=0,a=[tt.basename(t)+"/"];function c(l,u,d){if(d>e||i>=s)return;let f;try{f=Of.readdirSync(l,{withFileTypes:!0})}catch{return}f.sort((m,g)=>m.isDirectory()!==g.isDirectory()?m.isDirectory()?-1:1:m.name.localeCompare(g.name));let h=f.filter(m=>!(N0.has(m.name)||m.name.startsWith(".")&&m.name!==".env.example"||L0(m.name,r)));for(let m=0;m<h.length;m++){if(i>=s){a.push(`${u}\u2514\u2500\u2500 \u2026 (truncated)`);break}let g=h[m],b=m===h.length-1,v=b?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",O=u+(b?" ":"\u2502 "),U=g.isDirectory()?g.name+"/":g.name;a.push(`${u}${v}${U}`),i++,g.isDirectory()&&c(tt.join(l,g.name),O,d+1)}}return c(t,"",1),a.join(`
508
- `)}var Pa=new Map,cs=new Map,Or=null,I0=3e4;async function Qt(t){try{return await t()}catch{return null}}async function j0(){if(!Or||Date.now()>Or)return!1;let t=[tt.join(process.cwd(),"package.json"),tt.join(process.cwd(),"README.md"),tt.join(process.cwd(),".gitignore")];for(let e of t)try{let s=await vt.stat(e),n=cs.get(e);if(!n||s.mtimeMs!==n)return!1}catch{if(cs.has(e))return!1}try{let e=tt.join(process.cwd(),".git","HEAD"),s=await vt.stat(e),n=cs.get(e);if(!n||s.mtimeMs!==n)return!1}catch{}return!0}async function D0(){let t=[tt.join(process.cwd(),"package.json"),tt.join(process.cwd(),"README.md"),tt.join(process.cwd(),".gitignore"),tt.join(process.cwd(),".git","HEAD")];for(let e of t)try{let s=await vt.stat(e);cs.set(e,s.mtimeMs)}catch{cs.delete(e)}}async function q0(t){let e="fileContext",s=Pa.get(e),n=!1;if(s&&await j0()&&(n=!0),!n){let l=[],u=tt.join(t,"package.json");if(await Qt(()=>vt.access(u).then(()=>!0).catch(()=>!1)))try{let b=await vt.readFile(u,"utf-8"),v=JSON.parse(b),O={name:v.name,version:v.version};v.scripts&&(O.scripts=Object.keys(v.scripts).slice(0,15)),v.dependencies&&(O.deps=Object.keys(v.dependencies).length),v.devDependencies&&(O.devDeps=Object.keys(v.devDependencies).length),l.push(`PACKAGE: ${JSON.stringify(O)}`)}catch{}let f=tt.join(t,"README.md");if(await Qt(()=>vt.access(f).then(()=>!0).catch(()=>!1))){let v=(await vt.readFile(f,"utf-8")).split(`
536
+ - 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 G0(t){if(typeof t!="string")return null;let e=[...t.matchAll(/https?:\/\/([a-zA-Z0-9._-]+)/g)];if(e.length===0)return null;let s=so();if(Object.keys(s).length===0)return null;let n=null,o=null;for(let[,i]of e){let a=i.toLowerCase().split(".");for(let[c,l]of Object.entries(s))if(a.includes(c.toLowerCase())){n=l,o=c;break}if(n)break;for(let[c,l]of Object.entries(s))if(l.host===i){n=l,o=c;break}if(n)break}if(!n||!o)return null;let r=["ss -tlnp 2>/dev/null | awk 'NR>1{print $4}' | grep -oE ':[0-9]+$' | sort -u | head -8","echo '---services---'","ps aux 2>/dev/null | grep -E '(node |python3 |gunicorn|uvicorn|ruby |java )' | grep -v grep | awk '{print $11, $12, $13}' | head -6","echo '---data---'","find /home -maxdepth 5 -name 'data' -type d 2>/dev/null | head -6"].join("; ");try{let{stdout:i}=await F0(n,r,{timeout:4e3});if(!i||i.trim().length<5)return null;let a=n.user?`${n.user}@${n.host}`:n.host;return`[Server context for "${o}" (${a}) \u2014 probed at task start]
537
+ `+i.trim()}catch{return null}}Hf.exports={getServerContext:B0,getDeploymentContextBlock:H0,hasServerOS:W0,getProfileNames:U0,probeUrlServer:G0,OS_HINTS:Wa}});var zf=re((kv,Kf)=>{var St=require("fs").promises,Yf=require("fs"),nt=require("path"),Mr=require("util").promisify(require("child_process").exec),{C:ds}=He(),{getMergeConflicts:Gf}=sr(),{getServerContext:K0}=Ua(),z0=new Set(["node_modules",".git",".svn","dist","build","coverage",".nyc_output","__pycache__",".DS_Store",".next",".nuxt",".turbo",".cache","vendor","tmp","temp"]);function X0(t){try{return Yf.readFileSync(t,"utf-8").split(`
538
+ `).map(s=>s.trim()).filter(s=>s&&!s.startsWith("#")&&!s.startsWith("!")).map(s=>s.replace(/\/$/,""))}catch{return[]}}function V0(t,e){for(let s of e)if(s===t||s.includes("*")&&new RegExp("^"+s.replace(/\./g,"\\.").replace(/\*/g,".*")+"$").test(t))return!0;return!1}function J0(t,{maxDepth:e=3,maxFiles:s=200,giPatterns:n=[]}={}){let o=nt.join(t,".gitignore"),r=[...n,...X0(o)],i=0,a=[nt.basename(t)+"/"];function c(l,u,d){if(d>e||i>=s)return;let f;try{f=Yf.readdirSync(l,{withFileTypes:!0})}catch{return}f.sort((g,m)=>g.isDirectory()!==m.isDirectory()?g.isDirectory()?-1:1:g.name.localeCompare(m.name));let h=f.filter(g=>!(z0.has(g.name)||g.name.startsWith(".")&&g.name!==".env.example"||V0(g.name,r)));for(let g=0;g<h.length;g++){if(i>=s){a.push(`${u}\u2514\u2500\u2500 \u2026 (truncated)`);break}let m=h[g],b=g===h.length-1,x=b?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",j=u+(b?" ":"\u2502 "),G=m.isDirectory()?m.name+"/":m.name;a.push(`${u}${x}${G}`),i++,m.isDirectory()&&c(nt.join(l,m.name),j,d+1)}}return c(t,"",1),a.join(`
539
+ `)}var Ha=new Map,fs=new Map,Lr=null,Z0=3e4;async function tn(t){try{return await t()}catch{return null}}async function Q0(){if(!Lr||Date.now()>Lr)return!1;let t=[nt.join(process.cwd(),"package.json"),nt.join(process.cwd(),"README.md"),nt.join(process.cwd(),".gitignore")];for(let e of t)try{let s=await St.stat(e),n=fs.get(e);if(!n||s.mtimeMs!==n)return!1}catch{if(fs.has(e))return!1}try{let e=nt.join(process.cwd(),".git","HEAD"),s=await St.stat(e),n=fs.get(e);if(!n||s.mtimeMs!==n)return!1}catch{}return!0}async function eb(){let t=[nt.join(process.cwd(),"package.json"),nt.join(process.cwd(),"README.md"),nt.join(process.cwd(),".gitignore"),nt.join(process.cwd(),".git","HEAD")];for(let e of t)try{let s=await St.stat(e);fs.set(e,s.mtimeMs)}catch{fs.delete(e)}}async function tb(t){let e="fileContext",s=Ha.get(e),n=!1;if(s&&await Q0()&&(n=!0),!n){let l=[],u=nt.join(t,"package.json");if(await tn(()=>St.access(u).then(()=>!0).catch(()=>!1)))try{let b=await St.readFile(u,"utf-8"),x=JSON.parse(b),j={name:x.name,version:x.version};x.scripts&&(j.scripts=Object.keys(x.scripts).slice(0,15)),x.dependencies&&(j.deps=Object.keys(x.dependencies).length),x.devDependencies&&(j.devDeps=Object.keys(x.devDependencies).length),l.push(`PACKAGE: ${JSON.stringify(j)}`)}catch{}let f=nt.join(t,"README.md");if(await tn(()=>St.access(f).then(()=>!0).catch(()=>!1))){let x=(await St.readFile(f,"utf-8")).split(`
509
540
  `).slice(0,50);l.push(`README (first 50 lines):
510
- ${v.join(`
511
- `)}`)}let m=tt.join(t,".gitignore");if(await Qt(()=>vt.access(m).then(()=>!0).catch(()=>!1))){let b=await vt.readFile(m,"utf-8");l.push(`GITIGNORE:
541
+ ${x.join(`
542
+ `)}`)}let g=nt.join(t,".gitignore");if(await tn(()=>St.access(g).then(()=>!0).catch(()=>!1))){let b=await St.readFile(g,"utf-8");l.push(`GITIGNORE:
512
543
  ${b.trim()}`)}s=l.join(`
513
544
 
514
- `),Pa.set(e,s),Or=Date.now()+I0,await D0()}let o=[s],[r,i,a,c]=await Promise.all([Qt(async()=>{let{stdout:l}=await Ar("git branch --show-current",{cwd:t,timeout:5e3});return l.trim()}),Qt(async()=>{let{stdout:l}=await Ar("git status --short",{cwd:t,timeout:5e3});return l.trim()}),Qt(async()=>{let{stdout:l}=await Ar("git log --oneline -5",{cwd:t,timeout:5e3});return l.trim()}),Nf()]);if(r&&o.push(`GIT BRANCH: ${r}`),i&&o.push(`GIT STATUS:
545
+ `),Ha.set(e,s),Lr=Date.now()+Z0,await eb()}let o=[s],[r,i,a,c]=await Promise.all([tn(async()=>{let{stdout:l}=await Mr("git branch --show-current",{cwd:t,timeout:5e3});return l.trim()}),tn(async()=>{let{stdout:l}=await Mr("git status --short",{cwd:t,timeout:5e3});return l.trim()}),tn(async()=>{let{stdout:l}=await Mr("git log --oneline -5",{cwd:t,timeout:5e3});return l.trim()}),Gf()]);if(r&&o.push(`GIT BRANCH: ${r}`),i&&o.push(`GIT STATUS:
515
546
  ${i}`),a&&o.push(`RECENT COMMITS:
516
547
  ${a}`),c&&c.length>0){let l=c.map(u=>` ${u.file}`).join(`
517
548
  `);o.push(`MERGE CONFLICTS (resolve before editing these files):
518
- ${l}`)}try{let l=O0();l&&o.push(l)}catch{}return o.join(`
549
+ ${l}`)}try{let l=K0();l&&o.push(l)}catch{}return o.join(`
519
550
 
520
- `)}async function F0(t){let e=tt.join(t,"package.json"),s="";if(await Qt(()=>vt.access(e).then(()=>!0).catch(()=>!1)))try{let i=await vt.readFile(e,"utf-8"),a=JSON.parse(i);s=`${a.name||"?"} v${a.version||"?"}`}catch{}let[o,r]=await Promise.all([Qt(async()=>{let{stdout:i}=await Ar("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),Nf()]);if(r&&r.length>0){console.log(`${as.red} \u26A0 ${r.length} unresolved merge conflict(s):${as.reset}`);for(let i of r)console.log(`${as.red} ${i.file}${as.reset}`);console.log(`${as.yellow} \u2192 Resolve conflicts before starting tasks${as.reset}`)}console.log()}Mf.exports={gatherProjectContext:q0,printContext:F0,generateFileTree:P0,_clearContextCache:()=>{Pa.clear(),cs.clear(),Or=null}}});var Mr=se((sv,jf)=>{var St=require("fs"),Nr=require("path"),{atomicWrite:B0}=fn();function no(){return Nr.join(process.cwd(),".nex","sessions")}function Ia(){let t=no();St.existsSync(t)||St.mkdirSync(t,{recursive:!0})}function ja(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return Nr.join(no(),`${e}.json`)}function Da(t,e,s={}){Ia();let n=ja(t),o={name:t,createdAt:s.createdAt||new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:e.length,model:s.model||null,provider:s.provider||null,messages:e};return B0(n,JSON.stringify(o,null,2)),{path:n,name:t}}function Pf(t){let e=ja(t);if(!St.existsSync(e))return null;try{return JSON.parse(St.readFileSync(e,"utf-8"))}catch{return null}}function If(){Ia();let t=no(),e=St.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(St.readFileSync(Nr.join(t,n),"utf-8"));s.push({name:o.name||n.replace(".json",""),createdAt:o.createdAt,updatedAt:o.updatedAt,messageCount:o.messageCount||0,model:o.model,provider:o.provider,score:o.score!=null?o.score:null,scoreGrade:o.scoreGrade||null})}catch{}return s.sort((n,o)=>(o.updatedAt||"").localeCompare(n.updatedAt||""))}function W0(t){let e=ja(t);return St.existsSync(e)?(St.unlinkSync(e),!0):!1}function U0(){let t=If();return t.length===0?null:Pf(t[0].name)}var xn=null,Yt=null,to=null;function H0(t,e={}){t.length!==0&&(xn&&clearTimeout(xn),Yt=t,to=e||{},xn=setTimeout(()=>{Yt&&Yt.length>0&&Da("_autosave",Yt,to),xn=null,Yt=null,to=null},5e3))}function G0(){xn&&(clearTimeout(xn),xn=null),Yt&&Yt.length>0&&(Da("_autosave",Yt,to),Yt=null,to=null)}function Y0(){Ia();let t=no(),e=St.readdirSync(t).filter(r=>r.endsWith(".json")),s=new Date,n=new Date(s.getTime()-720*60*60*1e3),o=0;for(let r of e){let i=Nr.join(t,r);try{let a=St.statSync(i);new Date(a.mtime)<n&&(St.unlinkSync(i),o++)}catch{}}return o}jf.exports={saveSession:Da,loadSession:Pf,listSessions:If,deleteSession:W0,getLastSession:U0,autoSave:H0,flushAutoSave:G0,clearOldSessions:Y0,_getSessionsDir:no}});var Lr=se((ov,Gf)=>{"use strict";var so=require("fs"),Df=require("path");function qf(t){let e=[];return t.forEach((s,n)=>{s.role==="assistant"&&(Array.isArray(s.content)&&s.content.forEach(o=>{o&&o.type==="tool_use"&&e.push({name:o.name||"",input:o.input||{},index:n,id:o.id||null})}),Array.isArray(s.tool_calls)&&s.tool_calls.forEach(o=>{let r=o.function?.name||o.name||"",i={};try{i=typeof o.function?.arguments=="string"?JSON.parse(o.function.arguments):o.function?.arguments||o.input||{}}catch{}e.push({name:r,input:i,index:n,id:o.id||null})}))}),e}function K0(t){let e=new Set;return t.forEach(s=>{s.role==="tool"&&typeof s.content=="string"&&s.content.startsWith("BLOCKED:")&&s.tool_call_id&&e.add(s.tool_call_id),s.role==="user"&&Array.isArray(s.content)&&s.content.forEach(n=>{n&&n.type==="tool_result"&&n.tool_use_id&&typeof n.content=="string"&&n.content.startsWith("BLOCKED:")&&e.add(n.tool_use_id)})}),e}function Ff(t){let e=[];return t.forEach((s,n)=>{if(s.role==="user"&&Array.isArray(s.content)&&s.content.forEach(o=>{if(o&&o.type==="tool_result"){let r=typeof o.content=="string"?o.content:Array.isArray(o.content)?o.content.map(i=>typeof i=="string"?i:i.text||"").join(""):JSON.stringify(o.content||"");e.push({content:r,index:n})}}),s.role==="tool"){let o=typeof s.content=="string"?s.content:JSON.stringify(s.content||"");e.push({content:o,index:n})}}),e}function Bf(t){for(let e=t.length-1;e>=0;e--){let s=t[e];if(s.role==="assistant"){if(typeof s.content=="string")return s.content.trim();if(Array.isArray(s.content)){let n=s.content.filter(o=>o&&(o.type==="text"||typeof o=="string")).map(o=>typeof o=="string"?o:o.text||"").join("").trim();if(n)return n}}}return""}function Wf(t,e){let s=[];for(let n=t.length-1;n>=0&&s.length<e;n--){let o=t[n];if(o.role!=="assistant")continue;let r="";typeof o.content=="string"?r=o.content.trim():Array.isArray(o.content)&&(r=o.content.filter(i=>i&&(i.type==="text"||typeof i=="string")).map(i=>typeof i=="string"?i:i.text||"").join("").trim()),r&&s.push(r)}return s}function Uf(t){let e=new Map;for(let s of t){let n;try{n=JSON.stringify(s.input)}catch{n=String(s.input)}let o=`${s.name}|${n}`;e.set(o,(e.get(o)||0)+1)}return e}function Hf(t){if(!Array.isArray(t)||t.length===0)return{score:0,issues:["Empty or invalid session \u2014 no messages to analyse"],summary:"No messages found"};let e=10,s=[],n=qf(t),o=Ff(t),r=n.length,i=K0(t),a=n.filter(w=>!w.id||!i.has(w.id));t.some(w=>w.role==="user"&&typeof w.content=="string"&&w.content.startsWith("[SYSTEM WARNING]")&&(w.content.includes("edited")||w.content.includes("bash command")||w.content.includes("grep pattern")||w.content.includes("re-read")||w.content.includes("already in your context")))&&(e-=2,s.push("Loop-warning was fired during session (repeated file edits, bash commands, or re-reads)"));let l=n.find(w=>{let P=w.input?.command||w.input?.cmd||"";return/\bsed\s+-n\b/.test(P)});if(l){let w=(l.input?.command||l.input?.cmd||"").slice(0,80);o.some(k=>k.content.includes("BLOCKED: sed -n is forbidden")||k.content.includes("BLOCKED: sed -n"))?(e-=.25,s.push(`sed -n attempted but blocked by agent guard: ${w}`)):(e-=1.5,s.push(`sed -n anti-pattern used: ${w}`))}n.find(w=>{if(w.name!=="grep"&&w.name!=="bash"&&w.name!=="ssh_exec")return!1;let P=w.input?.command||w.input?.cmd||"",k=w.input?.pattern||"",N=`${P} ${k}`;return/(?:-[CAB]|--context|--after|--before)\s*[=\s]?([2-9][1-9]|\d{3,})/.test(N)||/grep.*-[CAB]\s*([2-9][1-9]|\d{3,})/.test(N)})&&(e-=1,s.push("grep used with >20 context lines (context flood risk)"));let d=t.some(w=>w.role==="assistant"),f=Bf(t),m=Wf(t,3).some(w=>w.length>100&&!/^[^.!]{0,40}\?$/.test(w));if(d&&!m&&(f.length<80||/^[^.!]{0,40}\?$/.test(f))){e-=2;let w=f.length>0?`"${f.slice(0,60)}..."`:"(no assistant text found)";s.push(`Session ends without diagnosis \u2014 last response too short or is only a question: ${w}`)}r>40?(e-=1.5,s.push(`Excessive tool calls: ${r} (>40 threshold)`)):r>25&&(e-=.5,s.push(`High tool call count: ${r} (>25 threshold)`)),t.some(w=>{let P=typeof w.content=="string"?w.content:Array.isArray(w.content)?w.content.map(k=>typeof k=="string"?k:k.text||"").join(""):"";return/\[auto-compressed|context compacted|force-compressed/.test(P)})&&(e-=.5,s.push("Auto-compress triggered (context flood indicator)"));let v=Uf(a),O=0,U="";for(let[w,P]of v)P>O&&(O=P,U=w);if(O>=3){let[w]=U.split("|");e-=1,s.push(`Same tool call repeated ${O}\xD7 (tool: ${w})`)}let L=!1,R=t.findIndex(w=>w.role==="user"&&typeof w.content=="string"&&w.content.includes("[SYSTEM STOP]")&&w.content.includes('"valid":true'));R>=0&&n.filter(P=>P.index>R).length>0&&(L=!0),L&&(e-=1.5,s.push('Stop-trigger ignored: tool result contained "valid":true but session continued with more tool calls'));let C=n.filter(w=>w.name==="ssh_exec");if(C.length>=8){let w=0,P=1;for(let k=1;k<C.length;k++)C[k].index<=C[k-1].index+2?P++:(w=Math.max(w,P),P=1);w=Math.max(w,P),w>=8&&(e-=.5,s.push(`SSH reconnect storm: ${w} consecutive SSH calls`))}d&&C.length>0&&/\b(Könntest du|könntest du|Bitte (bereitstellen|kopier)|kannst du mir .* bereitstellen|could you (provide|share|paste)|please (provide|share|run .* and paste)|I (cannot|can't) access the server|nicht (auf den Server )?zugreifen|SSH .* (nicht verfügbar|unavailable|temporarily unavailable))\b/i.test(f)&&(e-=2,s.push("Surrender: model asked user to manually provide server output instead of gathering it"));let K=new Map;for(let w of a)if(w.name==="read_file"&&w.input?.path){let P=w.input.path;K.has(P)||K.set(P,{count:0,ranges:[]});let k=K.get(P);if(k.count++,w.input.line_start!=null){let N=w.input.line_start||1,T=w.input.line_end||N+350;k.ranges.push([N,T])}}function Q(w,P,k){for(let[N,T]of k){let S=Math.max(w,N),J=Math.min(P,T);if(J>S){let Re=J-S,Ce=P-w||1;if(Re/Ce>=.7)return!0}}return!1}let re=0,V="";for(let[w,P]of K){if(P.count<3)continue;if(P.ranges.length===P.count){let T=!1,S=[];for(let[J,Re]of P.ranges){if(S.length>0&&Q(J,Re,S)){T=!0;break}S.push([J,Re])}if(!T)continue}if(P.count-P.ranges.length<=2&&P.ranges.length>=1){let T=!1,S=[];for(let[J,Re]of P.ranges){if(S.length>0&&Q(J,Re,S)){T=!0;break}S.push([J,Re])}if(!T)continue}P.count>re&&(re=P.count,V=w)}if(re>=3){e-=1;let w=V.split("/").slice(-2).join("/");s.push(`read_file loop: "${w}" read ${re}\xD7 (file already in context)`)}let H=0,_="";for(let[w,P]of K){if(P.ranges.length<4)continue;let k=[],N=!1;for(let[T,S]of P.ranges){if(k.length>0&&Q(T,S,k)){N=!0;break}k.push([T,S])}!N&&P.ranges.length>H&&(H=P.ranges.length,_=w)}if(H>=4){e-=.5;let w=_.split("/").slice(-2).join("/");s.push(`File-scroll pattern: "${w}" read in ${H} sequential sections \u2014 use grep instead`)}let he=new Map;for(let w of a)if(w.name==="grep"&&w.input?.path&&w.input?.pattern){let P=w.input.path;he.has(P)||he.set(P,new Set),he.get(P).add(w.input.pattern)}let de=0,me="";for(let[w,P]of he)w.split("/").pop().includes(".")&&P.size>de&&(de=P.size,me=w);if(de>=3){e-=.75;let w=me.split("/").slice(-2).join("/");s.push(`grep flood on single file: "${w}" searched ${de}\xD7 with different patterns (file already in context)`)}{let w=new Set,P=new Set,k=/^(test_|demo_|temp_|tmp_|scratch_)/;for(let T of n){if(T.name==="write_file"&&T.input?.path){let S=T.input.path.split("/").pop(),J=T.input.path.includes("/tests/");k.test(S)&&!J&&w.add(T.input.path)}if((T.name==="bash"||T.name==="ssh_exec")&&T.input?.command){let S=T.input.command.match(/\brm\s+(?:-\w+\s+)?(\S+)/g);if(S)for(let J of S){let Re=J.split(/\s+/),Ce=Re[Re.length-1];for(let ye of w)(ye.endsWith(Ce)||Ce.endsWith(ye.split("/").pop()))&&P.add(ye)}}}let N=P.size;if(N>=1){let T=Math.min(N*.25,.5);e-=T;let S=[...P].map(J=>J.split("/").pop()).join(", ");s.push(`Temp file write-then-delete: ${S} \u2014 write inline logic or use tests/ instead`)}}let ge=o.filter(w=>w.content.startsWith("EXIT")).length;ge>=10?(e-=1,s.push(`Bash exit-error storm: ${ge} tool results started with EXIT (repeated failing commands)`)):ge>=5&&(e-=.5,s.push(`Repeated bash errors: ${ge} tool results with non-zero exit code`));for(let w of t){if(w.role!=="assistant")continue;let P="";if(typeof w.content=="string"?P=w.content:Array.isArray(w.content)&&(P=w.content.filter(Ce=>Ce&&(Ce.type==="text"||typeof Ce=="string")).map(Ce=>typeof Ce=="string"?Ce:Ce.text||"").join("")),P.length<=5e3)continue;let k=P.split(/(?<=\. )/).filter(Ce=>Ce.trim().length>0);if(k.length<6)continue;let N=new Map;for(let Ce=0;Ce<=k.length-3;Ce++){let ye=k.slice(Ce,Ce+3).join("").trim();ye.length>30&&N.set(ye,(N.get(ye)||0)+1)}let T=0,S="";for(let[Ce,ye]of N)ye>T&&(T=ye,S=Ce);if(T<3)continue;let Re=S.length*T/P.length;if(Re>=.4||T>=10){e-=1.5,s.push(`llm output loop: assistant message repeated content detected (${T}\xD7 same paragraph, ${Math.round(Re*100)}% repeated)`);break}}{let w=new Set(["read_file","list_directory","search_files","glob","grep"]),P=t.some(N=>Array.isArray(N.tool_calls)?N.tool_calls.some(T=>w.has(T.function?.name)):Array.isArray(N.content)?N.content.some(T=>T.type==="tool_use"&&w.has(T.name)):!1);t.some(N=>N.role==="assistant"&&typeof N.content=="string"&&(N.content.includes("## Steps")||N.content.includes("/plan approve")))&&!P&&(e-=2,s.push("plan written without reading any files \u2014 LLM invented data structures from training knowledge (hallucination risk)"))}let we=o.filter(w=>w.content.startsWith("BLOCKED:")&&!w.content.includes("BLOCKED: sed -n")&&!w.content.includes("SSH paused")&&!w.content.includes("SSH temporarily paused"));if(we.length>0){let w=Math.min(we.length*.5,1.5);e-=w,s.push(`${we.length} tool call${we.length===1?"":"s"} blocked (agent attempted denied actions)`)}let Se=t.filter(w=>{let P=typeof w.content=="string"?w.content:"";return/\[SYSTEM WARNING\] Context wiped \d+×/.test(P)}).length;if(Se>0){let w=Math.min(Se*1,2);e-=w,s.push(`Super-nuclear context wipe fired ${Se}\xD7 (context collapse \u2014 task too large or read loops)`)}{let w=!1,P=!1,k=!1;for(let T of n){if(T.name!=="bash")continue;let S=(T.input?.command||T.input?.cmd||"").trim();!(/cat\s*>/.test(S)||/<</.test(S))&&/\bcat\s+\S/.test(S)&&(w=!0),/^\s*ls(\s|$)/.test(S)&&!/npm|yarn|pnpm|make|git\b/.test(S)&&(P=!0),/\bfind\s+\S/.test(S)&&!/git\b|npm\b|-exec\b/.test(S)&&(k=!0)}let N=[w,P,k].filter(Boolean).length;if(N>0){let T=Math.min(N*.25,.75);e-=T;let S=[];w&&S.push("cat (use read_file)"),P&&S.push("ls (use list_directory)"),k&&S.push("find (use glob)"),s.push(`bash used instead of dedicated tool: ${S.join(", ")}`)}}{let w=n.some(S=>(S.name==="write_file"||S.name==="Write")&&S.input?.path&&(S.input.path.endsWith("requirements.txt")||S.input.path.endsWith("Pipfile")||S.input.path.endsWith("pyproject.toml"))),P=n.some(S=>(S.name==="write_file"||S.name==="Write")&&S.input?.path&&S.input.path.endsWith("package.json")),k=n.filter(S=>(S.name==="bash"||S.name==="Bash")&&S.input?.command).map(S=>S.input.command),N=k.some(S=>/pip\s+install|python\s+-m\s+venv/.test(S)),T=k.some(S=>/npm\s+install/.test(S));w&&!N?(e-=1,s.push("wrote requirements.txt but never ran pip install \u2014 environment not bootstrapped")):P&&!T&&n.some(J=>(J.name==="write_file"||J.name==="Write")&&J.input?.path&&/(\/src\/|index\.js|App\.js|main\.js)/.test(J.input.path))&&(e-=.75,s.push("created new React/Node project but never ran npm install \u2014 project is not runnable"))}if(d){let w=t.find(S=>S.role==="assistant"),P="";w&&(typeof w.content=="string"?P=w.content:Array.isArray(w.content)&&(P=w.content.filter(S=>S&&(S.type==="text"||typeof S=="string")).map(S=>typeof S=="string"?S:S.text||"").join("")));let k=P.slice(0,400),N=/^[\d\s\+\-\*\/×÷\(\)\.]+\s*=\s*[\d\s\+\-\*\/×÷\(\)\.]+[.\n]/m,T=k.split(`
521
- `).find(S=>{let J=S.trim();return J.length>0&&J.length<=30&&/^\d/.test(J)&&/=/.test(J)&&!/[a-zA-Z]/.test(J)});if(N.test(k)||T){e-=1.5;let S=(T||k.split(`
522
- `)[0]).trim().slice(0,40);s.push(`Thinking-chain leak: non-sequitur artifact at response start: "${S}"`)}}if(d&&r>0){let w=t.findIndex(k=>k.role==="assistant"),P=t.findIndex(k=>!!(Array.isArray(k.tool_calls)&&k.tool_calls.length>0||Array.isArray(k.content)&&k.content.some(N=>N&&N.type==="tool_use")));if(w!==-1&&P!==-1&&w<P){let k=t[w],N="";typeof k.content=="string"?N=k.content:Array.isArray(k.content)&&(N=k.content.filter(J=>J&&(J.type==="text"||typeof J=="string")).map(J=>typeof J=="string"?J:J.text||"").join(""));let T=/ssh\s+\S+@\S+\s+"[^"]*\/[^"]*\./.test(N),S=/\/(?:home|var|etc|usr|opt|root|srv|data)\/[a-zA-Z0-9_.\-\/]+\.[a-zA-Z]{2,5}/.test(N);(T||S)&&(e-=1,s.push("Answer-before-verify: model gave concrete file paths/SSH commands before making any tool calls (paths guessed, not verified)"))}}if(d){let w=f;if(w.length>100){let k=(w.match(/^```/gm)||[]).length%2!==0,N=/"\s*:\s*$/.test(w.trimEnd()),T=/[,\[{]\s*$/.test(w.trimEnd());(k||N||T)&&(e-=.75,s.push("Truncated response: last assistant message ends mid-code-block or mid-JSON (model hit token limit)"))}}{let w=[];t.forEach((k,N)=>{let T=[];Array.isArray(k.tool_calls)&&k.tool_calls.forEach(S=>{if((S.function?.name||S.name||"")==="read_file"){let Re={};try{Re=typeof S.function?.arguments=="string"?JSON.parse(S.function.arguments):S.function?.arguments||{}}catch{}(Re.path||"").endsWith(".json")&&T.push({id:S.id,path:Re.path})}}),Array.isArray(k.content)&&k.content.forEach(S=>{S&&S.type==="tool_use"&&S.name==="read_file"&&(S.input?.path||"").endsWith(".json")&&T.push({id:S.id,path:S.input.path})}),T.forEach(S=>w.push({...S,msgIdx:N}))});let P=0;for(let k of w){let N=null;for(let S of t){if(S.role==="tool"&&S.tool_call_id===k.id&&typeof S.content=="string"){N=S.content;break}if(S.role==="user"&&Array.isArray(S.content)){let J=S.content.find(Re=>Re&&Re.type==="tool_result"&&Re.tool_use_id===k.id);if(J){N=typeof J.content=="string"?J.content:"";break}}}if(!N)continue;N.split(`
523
- `).filter(S=>S.trim()).length<5&&/^\s*\[/.test(N)&&!/\]\s*$/.test(N.trimEnd())&&P++}P>=1&&(e-=.75,s.push(`Shallow JSON read: ${P} .json file${P>1?"s":""} read with < 5 lines \u2014 array was incomplete, model drew conclusions from truncated data`))}{let w=o.filter(P=>/argument errors?/i.test(P.content)||/missing required (argument|parameter)/i.test(P.content)||/invalid argument/i.test(P.content));w.length>=3?(e-=.75,s.push(`Repeated tool argument errors: ${w.length} tool calls returned argument errors \u2014 model couldn't correct its tool usage`)):w.length>=2&&(e-=.25,s.push(`Tool argument errors: ${w.length} tool calls returned argument errors`))}{let w=!1,P=0,k=0;for(let N of a){if((N.name==="bash"||N.name==="Bash")&&N.input?.command&&/git\s+commit\b/.test(N.input.command)){w&&(k=Math.max(k,P)),w=!0,P=0;continue}w&&(N.name==="bash"||N.name==="Bash")&&N.input?.command&&/git\s+(status|diff|log|show)\b/.test(N.input.command)&&P++}k=Math.max(k,P),k>=3&&(e-=.75,s.push(`Post-commit verification waste: ${k} git status/diff/log calls after commit`))}e=Math.max(0,Math.min(10,e)),e=Math.round(e*10)/10;let fe=e>=9?"A":e>=8?"B":e>=7?"C":e>=6?"D":"F",Pe=s.length===0?`Clean session \u2014 no quality issues detected (${r} tool calls)`:`${s.length} issue${s.length===1?"":"s"} found \u2014 ${r} tool calls`;return{score:e,grade:fe,issues:s,summary:Pe}}function z0(t){try{let{loadSession:e}=Mr(),s=e(t);return s?Hf(s.messages||[]):null}catch{return null}}function X0(t,e=null){let{score:s,issues:n}=t,o=e?.dim||"",r=e?.reset||"",i=e?.yellow||"";if(s>=8||n.length===0)return"";let a=n.map(u=>u.replace(/:\s+\d+.*$/,"").replace(/\s*\(.*?\)/,"").replace(/\s*—.*$/,""));if(s>=6){let u=a.slice(0,3),d=a.length-u.length,f=u.join(" \xB7 ");return d>0&&(f+=` (+${d})`),`
551
+ `)}async function nb(t){let e=nt.join(t,"package.json"),s="";if(await tn(()=>St.access(e).then(()=>!0).catch(()=>!1)))try{let i=await St.readFile(e,"utf-8"),a=JSON.parse(i);s=`${a.name||"?"} v${a.version||"?"}`}catch{}let[o,r]=await Promise.all([tn(async()=>{let{stdout:i}=await Mr("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),Gf()]);if(r&&r.length>0){console.log(`${ds.red} \u26A0 ${r.length} unresolved merge conflict(s):${ds.reset}`);for(let i of r)console.log(`${ds.red} ${i.file}${ds.reset}`);console.log(`${ds.yellow} \u2192 Resolve conflicts before starting tasks${ds.reset}`)}console.log()}Kf.exports={gatherProjectContext:tb,printContext:nb,generateFileTree:J0,_clearContextCache:()=>{Ha.clear(),fs.clear(),Lr=null}}});var Ir=re((vv,Jf)=>{var Et=require("fs"),Pr=require("path"),{atomicWrite:sb}=mn();function ro(){return Pr.join(process.cwd(),".nex","sessions")}function Ya(){let t=ro();Et.existsSync(t)||Et.mkdirSync(t,{recursive:!0})}function Ga(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return Pr.join(ro(),`${e}.json`)}function Ka(t,e,s={}){Ya();let n=Ga(t),o={name:t,createdAt:s.createdAt||new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:e.length,model:s.model||null,provider:s.provider||null,messages:e};return sb(n,JSON.stringify(o,null,2)),{path:n,name:t}}function Xf(t){let e=Ga(t);if(!Et.existsSync(e))return null;try{return JSON.parse(Et.readFileSync(e,"utf-8"))}catch{return null}}function Vf(){Ya();let t=ro(),e=Et.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(Et.readFileSync(Pr.join(t,n),"utf-8"));s.push({name:o.name||n.replace(".json",""),createdAt:o.createdAt,updatedAt:o.updatedAt,messageCount:o.messageCount||0,model:o.model,provider:o.provider,score:o.score!=null?o.score:null,scoreGrade:o.scoreGrade||null})}catch{}return s.sort((n,o)=>(o.updatedAt||"").localeCompare(n.updatedAt||""))}function ob(t){let e=Ga(t);return Et.existsSync(e)?(Et.unlinkSync(e),!0):!1}function rb(){let t=Vf();return t.length===0?null:Xf(t[0].name)}var En=null,Kt=null,oo=null;function ib(t,e={}){t.length!==0&&(En&&clearTimeout(En),Kt=t,oo=e||{},En=setTimeout(()=>{Kt&&Kt.length>0&&Ka("_autosave",Kt,oo),En=null,Kt=null,oo=null},5e3))}function ab(){En&&(clearTimeout(En),En=null),Kt&&Kt.length>0&&(Ka("_autosave",Kt,oo),Kt=null,oo=null)}function cb(){Ya();let t=ro(),e=Et.readdirSync(t).filter(r=>r.endsWith(".json")),s=new Date,n=new Date(s.getTime()-720*60*60*1e3),o=0;for(let r of e){let i=Pr.join(t,r);try{let a=Et.statSync(i);new Date(a.mtime)<n&&(Et.unlinkSync(i),o++)}catch{}}return o}Jf.exports={saveSession:Ka,loadSession:Xf,listSessions:Vf,deleteSession:ob,getLastSession:rb,autoSave:ib,flushAutoSave:ab,clearOldSessions:cb,_getSessionsDir:ro}});var jr=re((Sv,rp)=>{"use strict";var io=require("fs"),Zf=require("path");function Qf(t){let e=[];return t.forEach((s,n)=>{s.role==="assistant"&&(Array.isArray(s.content)&&s.content.forEach(o=>{o&&o.type==="tool_use"&&e.push({name:o.name||"",input:o.input||{},index:n,id:o.id||null})}),Array.isArray(s.tool_calls)&&s.tool_calls.forEach(o=>{let r=o.function?.name||o.name||"",i={};try{i=typeof o.function?.arguments=="string"?JSON.parse(o.function.arguments):o.function?.arguments||o.input||{}}catch{}e.push({name:r,input:i,index:n,id:o.id||null})}))}),e}function lb(t){let e=new Set;return t.forEach(s=>{s.role==="tool"&&typeof s.content=="string"&&s.content.startsWith("BLOCKED:")&&s.tool_call_id&&e.add(s.tool_call_id),s.role==="user"&&Array.isArray(s.content)&&s.content.forEach(n=>{n&&n.type==="tool_result"&&n.tool_use_id&&typeof n.content=="string"&&n.content.startsWith("BLOCKED:")&&e.add(n.tool_use_id)})}),e}function ep(t){let e=[];return t.forEach((s,n)=>{if(s.role==="user"&&Array.isArray(s.content)&&s.content.forEach(o=>{if(o&&o.type==="tool_result"){let r=typeof o.content=="string"?o.content:Array.isArray(o.content)?o.content.map(i=>typeof i=="string"?i:i.text||"").join(""):JSON.stringify(o.content||"");e.push({content:r,index:n})}}),s.role==="tool"){let o=typeof s.content=="string"?s.content:JSON.stringify(s.content||"");e.push({content:o,index:n})}}),e}function tp(t){for(let e=t.length-1;e>=0;e--){let s=t[e];if(s.role==="assistant"){if(typeof s.content=="string")return s.content.trim();if(Array.isArray(s.content)){let n=s.content.filter(o=>o&&(o.type==="text"||typeof o=="string")).map(o=>typeof o=="string"?o:o.text||"").join("").trim();if(n)return n}}}return""}function np(t,e){let s=[];for(let n=t.length-1;n>=0&&s.length<e;n--){let o=t[n];if(o.role!=="assistant")continue;let r="";typeof o.content=="string"?r=o.content.trim():Array.isArray(o.content)&&(r=o.content.filter(i=>i&&(i.type==="text"||typeof i=="string")).map(i=>typeof i=="string"?i:i.text||"").join("").trim()),r&&s.push(r)}return s}function sp(t){let e=new Map;for(let s of t){let n;try{n=JSON.stringify(s.input)}catch{n=String(s.input)}let o=`${s.name}|${n}`;e.set(o,(e.get(o)||0)+1)}return e}function op(t){if(!Array.isArray(t)||t.length===0)return{score:0,issues:["Empty or invalid session \u2014 no messages to analyse"],summary:"No messages found"};let e=10,s=[],n=Qf(t),o=ep(t),r=n.length,i=lb(t),a=n.filter(w=>!w.id||!i.has(w.id));t.some(w=>w.role==="user"&&typeof w.content=="string"&&w.content.startsWith("[SYSTEM WARNING]")&&(w.content.includes("edited")||w.content.includes("bash command")||w.content.includes("grep pattern")||w.content.includes("re-read")||w.content.includes("already in your context")))&&(e-=2,s.push("Loop-warning was fired during session (repeated file edits, bash commands, or re-reads)"));let l=n.find(w=>{let I=w.input?.command||w.input?.cmd||"";return/\bsed\s+-n\b/.test(I)});if(l){let w=(l.input?.command||l.input?.cmd||"").slice(0,80);o.some(v=>v.content.includes("BLOCKED: sed -n is forbidden")||v.content.includes("BLOCKED: sed -n"))?(e-=.25,s.push(`sed -n attempted but blocked by agent guard: ${w}`)):(e-=1.5,s.push(`sed -n anti-pattern used: ${w}`))}n.find(w=>{if(w.name!=="grep"&&w.name!=="bash"&&w.name!=="ssh_exec")return!1;let I=w.input?.command||w.input?.cmd||"",v=w.input?.pattern||"",O=`${I} ${v}`;return/(?:-[CAB]|--context|--after|--before)\s*[=\s]?([2-9][1-9]|\d{3,})/.test(O)||/grep.*-[CAB]\s*([2-9][1-9]|\d{3,})/.test(O)})&&(e-=1,s.push("grep used with >20 context lines (context flood risk)"));let d=t.some(w=>w.role==="assistant"),f=tp(t),g=np(t,3).some(w=>w.length>100&&!/^[^.!]{0,40}\?$/.test(w));if(d&&!g&&(f.length<80||/^[^.!]{0,40}\?$/.test(f))){e-=2;let w=f.length>0?`"${f.slice(0,60)}..."`:"(no assistant text found)";s.push(`Session ends without diagnosis \u2014 last response too short or is only a question: ${w}`)}r>40?(e-=1.5,s.push(`Excessive tool calls: ${r} (>40 threshold)`)):r>25&&(e-=.5,s.push(`High tool call count: ${r} (>25 threshold)`)),t.some(w=>{let I=typeof w.content=="string"?w.content:Array.isArray(w.content)?w.content.map(v=>typeof v=="string"?v:v.text||"").join(""):"";return/\[auto-compressed|context compacted|force-compressed/.test(I)})&&(e-=.5,s.push("Auto-compress triggered (context flood indicator)"));let x=sp(a),j=0,G="";for(let[w,I]of x)I>j&&(j=I,G=w);if(j>=3){let[w]=G.split("|");e-=1,s.push(`Same tool call repeated ${j}\xD7 (tool: ${w})`)}let L=!1,P=t.findIndex(w=>w.role==="user"&&typeof w.content=="string"&&w.content.includes("[SYSTEM STOP]")&&w.content.includes('"valid":true'));P>=0&&n.filter(I=>I.index>P).length>0&&(L=!0),L&&(e-=1.5,s.push('Stop-trigger ignored: tool result contained "valid":true but session continued with more tool calls'));let C=n.filter(w=>w.name==="ssh_exec");if(C.length>=8){let w=0,I=1;for(let v=1;v<C.length;v++)C[v].index<=C[v-1].index+2?I++:(w=Math.max(w,I),I=1);w=Math.max(w,I),w>=8&&(e-=.5,s.push(`SSH reconnect storm: ${w} consecutive SSH calls`))}d&&C.length>0&&/\b(Könntest du|könntest du|Bitte (bereitstellen|kopier)|kannst du mir .* bereitstellen|could you (provide|share|paste)|please (provide|share|run .* and paste)|I (cannot|can't) access the server|nicht (auf den Server )?zugreifen|SSH .* (nicht verfügbar|unavailable|temporarily unavailable))\b/i.test(f)&&(e-=2,s.push("Surrender: model asked user to manually provide server output instead of gathering it"));let Z=new Map;for(let w of a)if(w.name==="read_file"&&w.input?.path){let I=w.input.path;Z.has(I)||Z.set(I,{count:0,ranges:[]});let v=Z.get(I);if(v.count++,w.input.line_start!=null){let O=w.input.line_start||1,R=w.input.line_end||O+350;v.ranges.push([O,R])}}function Y(w,I,v){for(let[O,R]of v){let k=Math.max(w,O),H=Math.min(I,R);if(H>k){let Se=H-k,xe=I-w||1;if(Se/xe>=.7)return!0}}return!1}let ue=0,ie="";for(let[w,I]of Z){if(I.count<3)continue;if(I.ranges.length===I.count){let R=!1,k=[];for(let[H,Se]of I.ranges){if(k.length>0&&Y(H,Se,k)){R=!0;break}k.push([H,Se])}if(!R)continue}if(I.count-I.ranges.length<=2&&I.ranges.length>=1){let R=!1,k=[];for(let[H,Se]of I.ranges){if(k.length>0&&Y(H,Se,k)){R=!0;break}k.push([H,Se])}if(!R)continue}I.count>ue&&(ue=I.count,ie=w)}if(ue>=3){e-=1;let w=ie.split("/").slice(-2).join("/");s.push(`read_file loop: "${w}" read ${ue}\xD7 (file already in context)`)}let se=0,T="";for(let[w,I]of Z){if(I.ranges.length<4)continue;let v=[],O=!1;for(let[R,k]of I.ranges){if(v.length>0&&Y(R,k,v)){O=!0;break}v.push([R,k])}!O&&I.ranges.length>se&&(se=I.ranges.length,T=w)}if(se>=4){e-=.5;let w=T.split("/").slice(-2).join("/");s.push(`File-scroll pattern: "${w}" read in ${se} sequential sections \u2014 use grep instead`)}let Te=new Map;for(let w of a)if(w.name==="grep"&&w.input?.path&&w.input?.pattern){let I=w.input.path;Te.has(I)||Te.set(I,new Set),Te.get(I).add(w.input.pattern)}let K=0,X="";for(let[w,I]of Te)w.split("/").pop().includes(".")&&I.size>K&&(K=I.size,X=w);if(K>=3){e-=.75;let w=X.split("/").slice(-2).join("/");s.push(`grep flood on single file: "${w}" searched ${K}\xD7 with different patterns (file already in context)`)}{let w=new Set,I=new Set,v=/^(test_|demo_|temp_|tmp_|scratch_)/;for(let R of n){if(R.name==="write_file"&&R.input?.path){let k=R.input.path.split("/").pop(),H=R.input.path.includes("/tests/");v.test(k)&&!H&&w.add(R.input.path)}if((R.name==="bash"||R.name==="ssh_exec")&&R.input?.command){let k=R.input.command.match(/\brm\s+(?:-\w+\s+)?(\S+)/g);if(k)for(let H of k){let Se=H.split(/\s+/),xe=Se[Se.length-1];for(let ge of w)(ge.endsWith(xe)||xe.endsWith(ge.split("/").pop()))&&I.add(ge)}}}let O=I.size;if(O>=1){let R=Math.min(O*.25,.5);e-=R;let k=[...I].map(H=>H.split("/").pop()).join(", ");s.push(`Temp file write-then-delete: ${k} \u2014 write inline logic or use tests/ instead`)}}let me=o.filter(w=>w.content.startsWith("EXIT")).length;me>=10?(e-=1,s.push(`Bash exit-error storm: ${me} tool results started with EXIT (repeated failing commands)`)):me>=5&&(e-=.5,s.push(`Repeated bash errors: ${me} tool results with non-zero exit code`));for(let w of t){if(w.role!=="assistant")continue;let I="";if(typeof w.content=="string"?I=w.content:Array.isArray(w.content)&&(I=w.content.filter(xe=>xe&&(xe.type==="text"||typeof xe=="string")).map(xe=>typeof xe=="string"?xe:xe.text||"").join("")),I.length<=5e3)continue;let v=I.split(/(?<=\. )/).filter(xe=>xe.trim().length>0);if(v.length<6)continue;let O=new Map;for(let xe=0;xe<=v.length-3;xe++){let ge=v.slice(xe,xe+3).join("").trim();ge.length>30&&O.set(ge,(O.get(ge)||0)+1)}let R=0,k="";for(let[xe,ge]of O)ge>R&&(R=ge,k=xe);if(R<3)continue;let Se=k.length*R/I.length;if(Se>=.4||R>=10){e-=1.5,s.push(`llm output loop: assistant message repeated content detected (${R}\xD7 same paragraph, ${Math.round(Se*100)}% repeated)`);break}}{let w=new Set(["read_file","list_directory","search_files","glob","grep"]),I=t.some(O=>Array.isArray(O.tool_calls)?O.tool_calls.some(R=>w.has(R.function?.name)):Array.isArray(O.content)?O.content.some(R=>R.type==="tool_use"&&w.has(R.name)):!1);t.some(O=>O.role==="assistant"&&typeof O.content=="string"&&(O.content.includes("## Steps")||O.content.includes("/plan approve")))&&!I&&(e-=2,s.push("plan written without reading any files \u2014 LLM invented data structures from training knowledge (hallucination risk)"))}let fe=o.filter(w=>w.content.startsWith("BLOCKED:")&&!w.content.includes("BLOCKED: sed -n")&&!w.content.includes("SSH paused")&&!w.content.includes("SSH temporarily paused"));if(fe.length>0){let w=Math.min(fe.length*.5,1.5);e-=w,s.push(`${fe.length} tool call${fe.length===1?"":"s"} blocked (agent attempted denied actions)`)}let $e=t.filter(w=>{let I=typeof w.content=="string"?w.content:"";return/\[SYSTEM WARNING\] Context wiped \d+×/.test(I)}).length;if($e>0){let w=Math.min($e*1,2);e-=w,s.push(`Super-nuclear context wipe fired ${$e}\xD7 (context collapse \u2014 task too large or read loops)`)}{let w=!1,I=!1,v=!1;for(let R of n){if(R.name!=="bash")continue;let k=(R.input?.command||R.input?.cmd||"").trim();!(/cat\s*>/.test(k)||/<</.test(k))&&/\bcat\s+\S/.test(k)&&(w=!0),/^\s*ls(\s|$)/.test(k)&&!/npm|yarn|pnpm|make|git\b/.test(k)&&(I=!0),/\bfind\s+\S/.test(k)&&!/git\b|npm\b|-exec\b/.test(k)&&(v=!0)}let O=[w,I,v].filter(Boolean).length;if(O>0){let R=Math.min(O*.25,.75);e-=R;let k=[];w&&k.push("cat (use read_file)"),I&&k.push("ls (use list_directory)"),v&&k.push("find (use glob)"),s.push(`bash used instead of dedicated tool: ${k.join(", ")}`)}}{let w=n.some(k=>(k.name==="write_file"||k.name==="Write")&&k.input?.path&&(k.input.path.endsWith("requirements.txt")||k.input.path.endsWith("Pipfile")||k.input.path.endsWith("pyproject.toml"))),I=n.some(k=>(k.name==="write_file"||k.name==="Write")&&k.input?.path&&k.input.path.endsWith("package.json")),v=n.filter(k=>(k.name==="bash"||k.name==="Bash")&&k.input?.command).map(k=>k.input.command),O=v.some(k=>/pip\s+install|python\s+-m\s+venv/.test(k)),R=v.some(k=>/npm\s+install/.test(k));w&&!O?(e-=1,s.push("wrote requirements.txt but never ran pip install \u2014 environment not bootstrapped")):I&&!R&&n.some(H=>(H.name==="write_file"||H.name==="Write")&&H.input?.path&&/(\/src\/|index\.js|App\.js|main\.js)/.test(H.input.path))&&(e-=.75,s.push("created new React/Node project but never ran npm install \u2014 project is not runnable"))}if(d){let w=t.find(k=>k.role==="assistant"),I="";w&&(typeof w.content=="string"?I=w.content:Array.isArray(w.content)&&(I=w.content.filter(k=>k&&(k.type==="text"||typeof k=="string")).map(k=>typeof k=="string"?k:k.text||"").join("")));let v=I.slice(0,400),O=/^[\d\s\+\-\*\/×÷\(\)\.]+\s*=\s*[\d\s\+\-\*\/×÷\(\)\.]+[.\n]/m,R=v.split(`
552
+ `).find(k=>{let H=k.trim();return H.length>0&&H.length<=30&&/^\d/.test(H)&&/=/.test(H)&&!/[a-zA-Z]/.test(H)});if(O.test(v)||R){e-=1.5;let k=(R||v.split(`
553
+ `)[0]).trim().slice(0,40);s.push(`Thinking-chain leak: non-sequitur artifact at response start: "${k}"`)}}if(d&&r>0){let w=t.findIndex(v=>v.role==="assistant"),I=t.findIndex(v=>!!(Array.isArray(v.tool_calls)&&v.tool_calls.length>0||Array.isArray(v.content)&&v.content.some(O=>O&&O.type==="tool_use")));if(w!==-1&&I!==-1&&w<I){let v=t[w],O="";typeof v.content=="string"?O=v.content:Array.isArray(v.content)&&(O=v.content.filter(H=>H&&(H.type==="text"||typeof H=="string")).map(H=>typeof H=="string"?H:H.text||"").join(""));let R=/ssh\s+\S+@\S+\s+"[^"]*\/[^"]*\./.test(O),k=/\/(?:home|var|etc|usr|opt|root|srv|data)\/[a-zA-Z0-9_.\-\/]+\.[a-zA-Z]{2,5}/.test(O);(R||k)&&(e-=1,s.push("Answer-before-verify: model gave concrete file paths/SSH commands before making any tool calls (paths guessed, not verified)"))}}if(d){let w=f;if(w.length>100){let v=(w.match(/^```/gm)||[]).length%2!==0,O=/"\s*:\s*$/.test(w.trimEnd()),R=/[,\[{]\s*$/.test(w.trimEnd());(v||O||R)&&(e-=.75,s.push("Truncated response: last assistant message ends mid-code-block or mid-JSON (model hit token limit)"))}}{let w=[];t.forEach((v,O)=>{let R=[];Array.isArray(v.tool_calls)&&v.tool_calls.forEach(k=>{if((k.function?.name||k.name||"")==="read_file"){let Se={};try{Se=typeof k.function?.arguments=="string"?JSON.parse(k.function.arguments):k.function?.arguments||{}}catch{}(Se.path||"").endsWith(".json")&&R.push({id:k.id,path:Se.path})}}),Array.isArray(v.content)&&v.content.forEach(k=>{k&&k.type==="tool_use"&&k.name==="read_file"&&(k.input?.path||"").endsWith(".json")&&R.push({id:k.id,path:k.input.path})}),R.forEach(k=>w.push({...k,msgIdx:O}))});let I=0;for(let v of w){let O=null;for(let k of t){if(k.role==="tool"&&k.tool_call_id===v.id&&typeof k.content=="string"){O=k.content;break}if(k.role==="user"&&Array.isArray(k.content)){let H=k.content.find(Se=>Se&&Se.type==="tool_result"&&Se.tool_use_id===v.id);if(H){O=typeof H.content=="string"?H.content:"";break}}}if(!O)continue;O.split(`
554
+ `).filter(k=>k.trim()).length<5&&/^\s*\[/.test(O)&&!/\]\s*$/.test(O.trimEnd())&&I++}I>=1&&(e-=.75,s.push(`Shallow JSON read: ${I} .json file${I>1?"s":""} read with < 5 lines \u2014 array was incomplete, model drew conclusions from truncated data`))}{let w=o.filter(I=>/argument errors?/i.test(I.content)||/missing required (argument|parameter)/i.test(I.content)||/invalid argument/i.test(I.content));w.length>=3?(e-=.75,s.push(`Repeated tool argument errors: ${w.length} tool calls returned argument errors \u2014 model couldn't correct its tool usage`)):w.length>=2&&(e-=.25,s.push(`Tool argument errors: ${w.length} tool calls returned argument errors`))}{let w=!1,I=0,v=0;for(let O of a){if((O.name==="bash"||O.name==="Bash")&&O.input?.command&&/git\s+commit\b/.test(O.input.command)){w&&(v=Math.max(v,I)),w=!0,I=0;continue}w&&(O.name==="bash"||O.name==="Bash")&&O.input?.command&&/git\s+(status|diff|log|show)\b/.test(O.input.command)&&I++}v=Math.max(v,I),v>=3&&(e-=.75,s.push(`Post-commit verification waste: ${v} git status/diff/log calls after commit`))}e=Math.max(0,Math.min(10,e)),e=Math.round(e*10)/10;let pe=e>=9?"A":e>=8?"B":e>=7?"C":e>=6?"D":"F",Re=s.length===0?`Clean session \u2014 no quality issues detected (${r} tool calls)`:`${s.length} issue${s.length===1?"":"s"} found \u2014 ${r} tool calls`;return{score:e,grade:pe,issues:s,summary:Re}}function ub(t){try{let{loadSession:e}=Ir(),s=e(t);return s?op(s.messages||[]):null}catch{return null}}function db(t,e=null){let{score:s,issues:n}=t,o=e?.dim||"",r=e?.reset||"",i=e?.yellow||"";if(s>=8||n.length===0)return"";let a=n.map(u=>u.replace(/:\s+\d+.*$/,"").replace(/\s*\(.*?\)/,"").replace(/\s*—.*$/,""));if(s>=6){let u=a.slice(0,3),d=a.length-u.length,f=u.join(" \xB7 ");return d>0&&(f+=` (+${d})`),`
524
555
  ${o}${f}${r}`}let c="";for(let u of a.slice(0,4))c+=`
525
556
  ${i}\u26A0${r} ${o}${u}${r}`;let l=a.length-4;return l>0&&(c+=`
526
- ${o}(+${l} more)${r}`),c}function V0(t,e={}){try{let s=Df.join(process.cwd(),".nex");so.existsSync(s)||so.mkdirSync(s,{recursive:!0});let n=Df.join(s,"benchmark-history.json"),o=[];if(so.existsSync(n))try{o=JSON.parse(so.readFileSync(n,"utf-8"))}catch{o=[]}Array.isArray(o)||(o=[]);let r=t>=9?"A":t>=8?"B":t>=7?"C":t>=6?"D":"F",i={date:new Date().toISOString(),version:e.version||null,model:e.model||null,score:t,grade:r,sessionName:e.sessionName||null,issues:Array.isArray(e.issues)?e.issues:[]};o.push(i),o.length>100&&(o=o.slice(o.length-100)),so.writeFileSync(n,JSON.stringify(o,null,2))}catch{}}Gf.exports={scoreMessages:Hf,scoreSession:z0,formatScore:X0,appendScoreHistory:V0,_extractToolCalls:qf,_extractToolResults:Ff,_getLastAssistantText:Bf,_getLastNAssistantTexts:Wf,_countDuplicateToolCalls:Uf}});var ls=se((rv,Jf)=>{"use strict";var J0=require("os"),Yf=require("path"),oo=require("fs"),ro=Yf.join(J0.homedir(),".nex-code","model-routing.json"),Pr={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}},Kf=["agentic","frontend","sysadmin","data","coding"];function Z0(t){if(!t||t.length<8)return null;for(let e of Kf){let s=Pr[e];if(!s.pattern||s.pattern.test(t))return s}return Pr.coding}function io(){try{if(oo.existsSync(ro))return JSON.parse(oo.readFileSync(ro,"utf-8"))}catch{}return{}}function zf(t){let e=Pr[t];return e?.envVar&&process.env[e.envVar]?process.env[e.envVar]:io()[t]||null}var Xf={plan:10,implement:35,verify:8},qa={plan:"qwen3-coder:480b",implement:null,verify:"devstral-small-2:24b"};function Vf(){let t=io();if(t.phases&&Object.keys(t.phases).length>0)return t.phases;try{let{getActiveProviderName:e}=He();if(e()==="ollama")return qa}catch{}return process.env.NEX_PHASE_ROUTING==="1"?qa:null}function Q0(t,e){let s=Vf();return s?.[t]?s[t]:e?zf(e):null}function eb(t){return io().phaseBudgets?.[t]||Xf[t]||20}function tb(){return process.env.NEX_PHASE_ROUTING==="0"?!1:Vf()!==null}function nb(t){let e=Yf.dirname(ro);oo.existsSync(e)||oo.mkdirSync(e,{recursive:!0});let s=io(),n={...s,...t};!t.phases&&s.phases&&(n.phases=s.phases),!t.phaseBudgets&&s.phaseBudgets&&(n.phaseBudgets=s.phaseBudgets),oo.writeFileSync(ro,JSON.stringify(n,null,2))}Jf.exports={CATEGORIES:Pr,DETECTION_ORDER:Kf,detectCategory:Z0,getModelForCategory:zf,getModelForPhase:Q0,getPhaseBudget:eb,isPhaseRoutingEnabled:tb,DEFAULT_PHASE_BUDGETS:Xf,BUILTIN_PHASE_DEFAULTS:qa,saveRoutingConfig:nb,loadRoutingConfig:io,ROUTING_CONFIG_PATH:ro}});var tp=se((iv,ep)=>{"use strict";var kn=require("fs"),ao=require("path"),sb=require("os"),{detectCategory:ob}=ls(),us=ao.join(sb.homedir(),".nex-code","examples"),Fa=ao.join(__dirname,"..","examples");function Zf(t){try{let s=kn.readFileSync(t,"utf-8").replace(/<!--[\s\S]*?-->/g,"").trim(),n=s.match(/^user:\s*(.+)$/m);if(!n)return null;let o=n[1].trim(),r=s.indexOf(`
557
+ ${o}(+${l} more)${r}`),c}function fb(t,e={}){try{let s=Zf.join(process.cwd(),".nex");io.existsSync(s)||io.mkdirSync(s,{recursive:!0});let n=Zf.join(s,"benchmark-history.json"),o=[];if(io.existsSync(n))try{o=JSON.parse(io.readFileSync(n,"utf-8"))}catch{o=[]}Array.isArray(o)||(o=[]);let r=t>=9?"A":t>=8?"B":t>=7?"C":t>=6?"D":"F",i={date:new Date().toISOString(),version:e.version||null,model:e.model||null,score:t,grade:r,sessionName:e.sessionName||null,issues:Array.isArray(e.issues)?e.issues:[]};o.push(i),o.length>100&&(o=o.slice(o.length-100)),io.writeFileSync(n,JSON.stringify(o,null,2))}catch{}}rp.exports={scoreMessages:op,scoreSession:ub,formatScore:db,appendScoreHistory:fb,_extractToolCalls:Qf,_extractToolResults:ep,_getLastAssistantText:tp,_getLastNAssistantTexts:np,_countDuplicateToolCalls:sp}});var ps=re((Ev,up)=>{"use strict";var pb=require("os"),za=require("path"),nn=require("fs"),ao=za.join(pb.homedir(),".nex-code","model-routing.json"),Dr={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}},ip=["agentic","frontend","sysadmin","data","coding"];function hb(t){if(!t||t.length<8)return null;for(let e of ip){let s=Dr[e];if(!s.pattern||s.pattern.test(t))return s}return Dr.coding}function co(){try{if(nn.existsSync(ao))return JSON.parse(nn.readFileSync(ao,"utf-8"))}catch{}return{}}function ap(t){let e=Dr[t];return e?.envVar&&process.env[e.envVar]?process.env[e.envVar]:co()[t]||null}var cp={plan:10,implement:35,verify:8},Xa={plan:"qwen3-coder:480b",implement:null,verify:"devstral-small-2:24b"};function lp(){let t=co();if(t.phases&&Object.keys(t.phases).length>0)return t.phases;try{let{getActiveProviderName:e}=Ge();if(e()==="ollama")return Xa}catch{}return process.env.NEX_PHASE_ROUTING==="1"?Xa:null}function mb(t,e){let s=lp();return s?.[t]?s[t]:e?ap(e):null}function gb(t){return co().phaseBudgets?.[t]||cp[t]||20}function yb(){return process.env.NEX_PHASE_ROUTING==="0"?!1:lp()!==null}function $b(t){let e=za.dirname(ao);nn.existsSync(e)||nn.mkdirSync(e,{recursive:!0});let s=co(),n={...s,...t};!t.phases&&s.phases&&(n.phases=s.phases),!t.phaseBudgets&&s.phaseBudgets&&(n.phaseBudgets=s.phaseBudgets),nn.writeFileSync(ao,JSON.stringify(n,null,2));try{let o=za.join(e,".env"),r="";nn.existsSync(o)&&(r=nn.readFileSync(o,"utf-8"));let i=r.split(/\r?\n/),a=(c,l)=>{let u=i.findIndex(d=>d.startsWith(c+"="));u>=0?i[u]=`${c}=${l}`:i.push(`${c}=${l}`)};n.coding&&a("NEX_ROUTE_CODING",n.coding),n.frontend&&a("NEX_ROUTE_FRONTEND",n.frontend),n.sysadmin&&a("NEX_ROUTE_SYSADMIN",n.sysadmin),n.data&&a("NEX_ROUTE_DATA",n.data),n.agentic&&a("NEX_ROUTE_AGENTIC",n.agentic),n.phases&&(n.phases.plan&&a("NEX_PHASE_PLAN_MODEL",n.phases.plan),n.phases.implement&&a("NEX_PHASE_IMPLEMENT_MODEL",n.phases.implement),n.phases.verify&&a("NEX_PHASE_VERIFY_MODEL",n.phases.verify)),nn.writeFileSync(o,i.filter(c=>c.trim()!=="").join(`
558
+ `)+`
559
+ `)}catch{}}up.exports={CATEGORIES:Dr,DETECTION_ORDER:ip,detectCategory:hb,getModelForCategory:ap,getModelForPhase:mb,getPhaseBudget:gb,isPhaseRoutingEnabled:yb,DEFAULT_PHASE_BUDGETS:cp,BUILTIN_PHASE_DEFAULTS:Xa,saveRoutingConfig:$b,loadRoutingConfig:co,ROUTING_CONFIG_PATH:ao}});var hp=re((Tv,pp)=>{"use strict";var Tn=require("fs"),lo=require("path"),wb=require("os"),{detectCategory:bb}=ps(),hs=lo.join(wb.homedir(),".nex-code","examples"),Va=lo.join(__dirname,"..","examples");function dp(t){try{let s=Tn.readFileSync(t,"utf-8").replace(/<!--[\s\S]*?-->/g,"").trim(),n=s.match(/^user:\s*(.+)$/m);if(!n)return null;let o=n[1].trim(),r=s.indexOf(`
527
560
  A: |`);if(r===-1)return null;let i=s.slice(r+5),a=[],c=0;for(let u of i.split(`
528
561
  `))if(u.startsWith(" ")){for(;c>0;)a.push(""),c--;a.push(u.slice(2))}else if(u.trim()==="")a.length>0&&c++;else break;if(a.length===0)return null;let l=a.join(`
529
- `).trim();return{user:o,assistant:l}}catch{return null}}function Qf(t){let e=`${t}.md`,s=ao.join(us,e);if(kn.existsSync(s)){let o=Zf(s);if(o)return o}let n=ao.join(Fa,e);return kn.existsSync(n)?Zf(n):null}function rb(t){if(process.env.NEX_FEW_SHOT==="0"||!t||t.length<8)return null;let e=ob(t);return e?Qf(e.id):null}function ib(){let t=new Set;for(let e of[us,Fa])try{for(let s of kn.readdirSync(e))s.endsWith(".md")&&t.add(s.replace(".md",""))}catch{}return[...t].sort()}function ab(t,e){kn.existsSync(us)||kn.mkdirSync(us,{recursive:!0});let s=`<!-- Auto-extracted from high-scoring session \u2014 edit as needed -->
562
+ `).trim();return{user:o,assistant:l}}catch{return null}}function fp(t){let e=`${t}.md`,s=lo.join(hs,e);if(Tn.existsSync(s)){let o=dp(s);if(o)return o}let n=lo.join(Va,e);return Tn.existsSync(n)?dp(n):null}function _b(t){if(process.env.NEX_FEW_SHOT==="0"||!t||t.length<8)return null;let e=bb(t);return e?fp(e.id):null}function xb(){let t=new Set;for(let e of[hs,Va])try{for(let s of Tn.readdirSync(e))s.endsWith(".md")&&t.add(s.replace(".md",""))}catch{}return[...t].sort()}function kb(t,e){Tn.existsSync(hs)||Tn.mkdirSync(hs,{recursive:!0});let s=`<!-- Auto-extracted from high-scoring session \u2014 edit as needed -->
530
563
 
531
564
  user: ${e.user}
532
565
 
@@ -534,14 +567,14 @@ A: |
534
567
  ${e.assistant.split(`
535
568
  `).map(n=>` ${n}`).join(`
536
569
  `)}
537
- `;kn.writeFileSync(ao.join(us,`${t}.md`),s,"utf-8")}ep.exports={getFewShotForInput:rb,loadExampleForCategory:Qf,listAvailableExamples:ib,savePrivateExample:ab,PRIVATE_EXAMPLES_DIR:us,BUNDLED_EXAMPLES_DIR:Fa}});var ap=se((cv,ip)=>{var pt=require("fs"),ds=require("path"),{C:av}=Ue(),{atomicWrite:cb,withFileLockSync:lb}=fn(),Ir={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"},fs={...Ir};function np(){let t=ds.join(process.cwd(),".nex","config.json");if(pt.existsSync(t))try{let e=JSON.parse(pt.readFileSync(t,"utf-8"));e.permissions&&(fs={...Ir,...e.permissions})}catch{}}function ub(){let t=ds.join(process.cwd(),".nex"),e=ds.join(t,"config.json");pt.existsSync(t)||pt.mkdirSync(t,{recursive:!0}),lb(e,()=>{let s={};if(pt.existsSync(e))try{s=JSON.parse(pt.readFileSync(e,"utf-8"))}catch{s={}}s.permissions=fs,cb(e,JSON.stringify(s,null,2))})}function sp(t){return fs[t]||"ask"}function db(t,e){return["allow","ask","deny"].includes(e)?(fs[t]=e,!0):!1}function fb(t){return sp(t)}function pb(){return Object.entries(fs).map(([t,e])=>({tool:t,mode:e}))}function hb(){fs={...Ir}}var co={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 op(){let t=ds.join(process.cwd(),".nex","config.json");try{return pt.existsSync(t)&&JSON.parse(pt.readFileSync(t,"utf-8")).teamPermissions||null}catch{return null}}function mb(t){let e=ds.join(process.cwd(),".nex"),s=ds.join(e,"config.json");pt.existsSync(e)||pt.mkdirSync(e,{recursive:!0});let n={};try{pt.existsSync(s)&&(n=JSON.parse(pt.readFileSync(s,"utf-8")))}catch{n={}}n.teamPermissions=t,pt.writeFileSync(s,JSON.stringify(n,null,2),"utf-8")}function rp(){let t=op();if(!t)return co.admin;let e=t.role||"admin",s=co[e]||co.admin;return{...s,...t.overrides,blockedTools:[...s.blockedTools||[],...t.overrides?.blockedTools||[]]}}function gb(t){let e=rp();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 yb(){return Object.entries(co).map(([t,e])=>({name:t,description:e.description,toolCount:e.allowedTools?`${e.allowedTools.length} allowed`:"all allowed",blockedCount:e.blockedTools.length}))}np();ip.exports={getPermission:sp,setPermission:db,checkPermission:fb,listPermissions:pb,loadPermissions:np,savePermissions:ub,resetPermissions:hb,DEFAULT_PERMISSIONS:Ir,PERMISSION_PRESETS:co,loadPresetConfig:op,savePresetConfig:mb,getEffectivePreset:rp,isToolAllowed:gb,listPresets:yb}});var qr=se((uv,fp)=>{var Sn=require("fs"),jr=require("path"),lv=require("readline"),{C:ke}=Ue(),_e=null,Wa=!1,Ua=null,cp=new Set(["read_file","list_directory","search_files","glob","grep","web_search","web_fetch","git_status","git_diff","git_log","git_show"]);function Dr(){return jr.join(process.cwd(),".nex","plans")}function lp(){let t=Dr();Sn.existsSync(t)||Sn.mkdirSync(t,{recursive:!0})}function $b(t,e=[]){return _e={name:`plan-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,task:t,steps:e.map(s=>({description:s.description||s,files:s.files||[],status:"pending"})),status:"draft",createdAt:new Date().toISOString()},_e}function wb(){return _e}function bb(t){Wa=t}function _b(){return Wa}function xb(){return!_e||_e.status!=="draft"?!1:(_e.status="approved",_e.updatedAt=new Date().toISOString(),!0)}function kb(){return!_e||_e.status!=="approved"?!1:(_e.status="executing",!0)}function Ba(t,e){return!_e||t<0||t>=_e.steps.length?!1:(_e.steps[t].status=e,_e.updatedAt=new Date().toISOString(),_e.steps.every(s=>s.status==="done"||s.status==="skipped")&&(_e.status="completed"),!0)}function vb(t){if(!t)return`${ke.dim}No active plan${ke.reset}`;let e={draft:`${ke.yellow}DRAFT${ke.reset}`,approved:`${ke.green}APPROVED${ke.reset}`,executing:`${ke.blue}EXECUTING${ke.reset}`,completed:`${ke.green}COMPLETED${ke.reset}`},s=[];s.push(`
538
- ${ke.bold}${ke.cyan}Plan: ${t.task}${ke.reset}`),s.push(`${ke.dim}Status: ${e[t.status]||t.status}${ke.reset}
539
- `);for(let n=0;n<t.steps.length;n++){let o=t.steps[n],r;switch(o.status){case"done":r=`${ke.green}\u2713${ke.reset}`;break;case"in_progress":r=`${ke.blue}\u2192${ke.reset}`;break;case"skipped":r=`${ke.dim}\u25CB${ke.reset}`;break;default:r=`${ke.dim} ${ke.reset}`}s.push(` ${r} ${ke.bold}Step ${n+1}:${ke.reset} ${o.description}`),o.files.length>0&&s.push(` ${ke.dim}Files: ${o.files.join(", ")}${ke.reset}`)}return s.push(""),s.join(`
540
- `)}function Sb(t){if(t||(t=_e),!t)return null;lp();let e=jr.join(Dr(),`${t.name}.json`);return Sn.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function Eb(t){let e=jr.join(Dr(),`${t}.json`);if(!Sn.existsSync(e))return null;try{let s=JSON.parse(Sn.readFileSync(e,"utf-8"));return _e=s,s}catch{return null}}function Tb(){lp();let t=Dr(),e=Sn.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(Sn.readFileSync(jr.join(t,n),"utf-8"));s.push({name:o.name,task:o.task,status:o.status,steps:o.steps?o.steps.length:0,createdAt:o.createdAt})}catch{}return s.sort((n,o)=>(o.createdAt||"").localeCompare(n.createdAt||""))}function Rb(t){if(!t)return[];let e=[],s=t.match(/##\s+Steps?\s*\n([\s\S]*?)(?:\n##|\s*$)/i),n=s?s[1]:t,o=/^\s*(\d+)[.)]\s+(.+)/gm,r;for(;(r=o.exec(n))!==null;){let a=r[2].trim().replace(/^\*\*What\*\*:\s*/i,"").replace(/^\*\*\d+\.\*\*\s*/,"").replace(/\*\*/g,"").trim();a.length>3&&e.push({description:a,files:[],status:"pending"})}if(e.length===0){let i=/\*\*Step\s+\d+[:.]\*\*\s*(.+)/gi;for(;(r=i.exec(t))!==null;){let a=r[1].replace(/\*\*/g,"").trim();a.length>3&&e.push({description:a,files:[],status:"pending"})}}if(e.length>0){let i=/\*\*(?:Where|Files?)\*\*:\s*(.+)/gi,a=[...t.matchAll(i)];for(let c=0;c<Math.min(e.length,a.length);c++){let l=a[c][1];e[c].files=l.split(/[,\s]+/).filter(u=>/[./]/.test(u)).slice(0,5)}}return e}function Cb(t){Ua=t}function Ab(){return Ua}function Ob(){_e=null,Wa=!1,Ua=null,Pb()}function Nb(){return`
570
+ `;Tn.writeFileSync(lo.join(hs,`${t}.md`),s,"utf-8")}pp.exports={getFewShotForInput:_b,loadExampleForCategory:fp,listAvailableExamples:xb,savePrivateExample:kb,PRIVATE_EXAMPLES_DIR:hs,BUNDLED_EXAMPLES_DIR:Va}});var bp=re((Cv,wp)=>{var ht=require("fs"),ms=require("path"),{C:Rv}=He(),{atomicWrite:vb,withFileLockSync:Sb}=mn(),qr={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"},gs={...qr};function mp(){let t=ms.join(process.cwd(),".nex","config.json");if(ht.existsSync(t))try{let e=JSON.parse(ht.readFileSync(t,"utf-8"));e.permissions&&(gs={...qr,...e.permissions})}catch{}}function Eb(){let t=ms.join(process.cwd(),".nex"),e=ms.join(t,"config.json");ht.existsSync(t)||ht.mkdirSync(t,{recursive:!0}),Sb(e,()=>{let s={};if(ht.existsSync(e))try{s=JSON.parse(ht.readFileSync(e,"utf-8"))}catch{s={}}s.permissions=gs,vb(e,JSON.stringify(s,null,2))})}function gp(t){return gs[t]||"ask"}function Tb(t,e){return["allow","ask","deny"].includes(e)?(gs[t]=e,!0):!1}function Rb(t){return gp(t)}function Cb(){return Object.entries(gs).map(([t,e])=>({tool:t,mode:e}))}function Ab(){gs={...qr}}var uo={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 yp(){let t=ms.join(process.cwd(),".nex","config.json");try{return ht.existsSync(t)&&JSON.parse(ht.readFileSync(t,"utf-8")).teamPermissions||null}catch{return null}}function Ob(t){let e=ms.join(process.cwd(),".nex"),s=ms.join(e,"config.json");ht.existsSync(e)||ht.mkdirSync(e,{recursive:!0});let n={};try{ht.existsSync(s)&&(n=JSON.parse(ht.readFileSync(s,"utf-8")))}catch{n={}}n.teamPermissions=t,ht.writeFileSync(s,JSON.stringify(n,null,2),"utf-8")}function $p(){let t=yp();if(!t)return uo.admin;let e=t.role||"admin",s=uo[e]||uo.admin;return{...s,...t.overrides,blockedTools:[...s.blockedTools||[],...t.overrides?.blockedTools||[]]}}function Nb(t){let e=$p();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 Mb(){return Object.entries(uo).map(([t,e])=>({name:t,description:e.description,toolCount:e.allowedTools?`${e.allowedTools.length} allowed`:"all allowed",blockedCount:e.blockedTools.length}))}mp();wp.exports={getPermission:gp,setPermission:Tb,checkPermission:Rb,listPermissions:Cb,loadPermissions:mp,savePermissions:Eb,resetPermissions:Ab,DEFAULT_PERMISSIONS:qr,PERMISSION_PRESETS:uo,loadPresetConfig:yp,savePresetConfig:Ob,getEffectivePreset:$p,isToolAllowed:Nb,listPresets:Mb}});var Wr=re((Ov,Sp)=>{var Cn=require("fs"),Fr=require("path"),Av=require("readline"),{C:ve}=He(),_e=null,Za=!1,Qa=null,_p=new Set(["read_file","list_directory","search_files","glob","grep","web_search","web_fetch","git_status","git_diff","git_log","git_show"]);function Br(){return Fr.join(process.cwd(),".nex","plans")}function xp(){let t=Br();Cn.existsSync(t)||Cn.mkdirSync(t,{recursive:!0})}function Lb(t,e=[]){return _e={name:`plan-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,task:t,steps:e.map(s=>({description:s.description||s,files:s.files||[],status:"pending"})),status:"draft",createdAt:new Date().toISOString()},_e}function Pb(){return _e}function Ib(t){Za=t}function jb(){return Za}function Db(){return!_e||_e.status!=="draft"?!1:(_e.status="approved",_e.updatedAt=new Date().toISOString(),!0)}function qb(){return!_e||_e.status!=="approved"?!1:(_e.status="executing",!0)}function Ja(t,e){return!_e||t<0||t>=_e.steps.length?!1:(_e.steps[t].status=e,_e.updatedAt=new Date().toISOString(),_e.steps.every(s=>s.status==="done"||s.status==="skipped")&&(_e.status="completed"),!0)}function Fb(t){if(!t)return`${ve.dim}No active plan${ve.reset}`;let e={draft:`${ve.yellow}DRAFT${ve.reset}`,approved:`${ve.green}APPROVED${ve.reset}`,executing:`${ve.blue}EXECUTING${ve.reset}`,completed:`${ve.green}COMPLETED${ve.reset}`},s=[];s.push(`
571
+ ${ve.bold}${ve.cyan}Plan: ${t.task}${ve.reset}`),s.push(`${ve.dim}Status: ${e[t.status]||t.status}${ve.reset}
572
+ `);for(let n=0;n<t.steps.length;n++){let o=t.steps[n],r;switch(o.status){case"done":r=`${ve.green}\u2713${ve.reset}`;break;case"in_progress":r=`${ve.blue}\u2192${ve.reset}`;break;case"skipped":r=`${ve.dim}\u25CB${ve.reset}`;break;default:r=`${ve.dim} ${ve.reset}`}s.push(` ${r} ${ve.bold}Step ${n+1}:${ve.reset} ${o.description}`),o.files.length>0&&s.push(` ${ve.dim}Files: ${o.files.join(", ")}${ve.reset}`)}return s.push(""),s.join(`
573
+ `)}function Bb(t){if(t||(t=_e),!t)return null;xp();let e=Fr.join(Br(),`${t.name}.json`);return Cn.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function Wb(t){let e=Fr.join(Br(),`${t}.json`);if(!Cn.existsSync(e))return null;try{let s=JSON.parse(Cn.readFileSync(e,"utf-8"));return _e=s,s}catch{return null}}function Ub(){xp();let t=Br(),e=Cn.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(Cn.readFileSync(Fr.join(t,n),"utf-8"));s.push({name:o.name,task:o.task,status:o.status,steps:o.steps?o.steps.length:0,createdAt:o.createdAt})}catch{}return s.sort((n,o)=>(o.createdAt||"").localeCompare(n.createdAt||""))}function Hb(t){if(!t)return[];let e=[],s=t.match(/##\s+Steps?\s*\n([\s\S]*?)(?:\n##|\s*$)/i),n=s?s[1]:t,o=/^\s*(\d+)[.)]\s+(.+)/gm,r;for(;(r=o.exec(n))!==null;){let a=r[2].trim().replace(/^\*\*What\*\*:\s*/i,"").replace(/^\*\*\d+\.\*\*\s*/,"").replace(/\*\*/g,"").trim();a.length>3&&e.push({description:a,files:[],status:"pending"})}if(e.length===0){let i=/\*\*Step\s+\d+[:.]\*\*\s*(.+)/gi;for(;(r=i.exec(t))!==null;){let a=r[1].replace(/\*\*/g,"").trim();a.length>3&&e.push({description:a,files:[],status:"pending"})}}if(e.length>0){let i=/\*\*(?:Where|Files?)\*\*:\s*(.+)/gi,a=[...t.matchAll(i)];for(let c=0;c<Math.min(e.length,a.length);c++){let l=a[c][1];e[c].files=l.split(/[,\s]+/).filter(u=>/[./]/.test(u)).slice(0,5)}}return e}function Yb(t){Qa=t}function Gb(){return Qa}function Kb(){_e=null,Za=!1,Qa=null,Jb()}function zb(){return`
541
574
  PLAN MODE ACTIVE: You are in analysis-only mode. You MUST NOT execute any changes.
542
575
 
543
576
  # Allowed Tools (read-only)
544
- You may ONLY use these tools: ${[...cp].join(", ")}
577
+ You may ONLY use these tools: ${[..._p].join(", ")}
545
578
  Any other tool call will be blocked and returned with an error.
546
579
 
547
580
  # MANDATORY: Read Before You Plan
@@ -585,23 +618,23 @@ Bullet list of potential issues and mitigations.
585
618
  - Order steps by dependency (later steps may depend on earlier ones).
586
619
  - After presenting the plan, tell the user to type \`/plan approve\` to proceed.
587
620
  - Do NOT make any file changes \u2014 your role is analysis and planning only.
588
- - 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 vn=0;function Mb(){!_e||_e.status!=="executing"||(vn>0&&Ba(vn-1,"done"),vn<_e.steps.length&&(Ba(vn,"in_progress"),vn++))}function Lb(){if(!_e||_e.status!=="executing"||_e.steps.length===0)return null;let t=Math.min(vn,_e.steps.length),e=_e.steps.length,s=Math.max(0,t-1),n=_e.steps[s]?.description||"";return{current:t,total:e,description:n}}function Pb(){vn=0}var up=["interactive","semi-auto","autonomous"],dp="interactive";function Ib(t){return up.includes(t)?(dp=t,!0):!1}function jb(){return dp}fp.exports={createPlan:$b,getActivePlan:wb,setPlanMode:bb,isPlanMode:_b,approvePlan:xb,startExecution:kb,updateStep:Ba,formatPlan:vb,savePlan:Sb,loadPlan:Eb,listPlans:Tb,clearPlan:Ob,getPlanModePrompt:Nb,setPlanContent:Cb,getPlanContent:Ab,extractStepsFromText:Rb,advancePlanStep:Mb,getPlanStepInfo:Lb,PLAN_MODE_ALLOWED_TOOLS:cp,setAutonomyLevel:Ib,getAutonomyLevel:jb,AUTONOMY_LEVELS:up}});var kp=se((dv,xp)=>{var{C:x}=Ue();function pp(){return Math.max(10,(process.stdout.columns||80)-2)}function Db(t){if(!t)return"";let e=t.split(`
589
- `),s=[],n=!1,o="";for(let r of e){let i=pp();if(r.trim().startsWith("```")){if(n)s.push(`${x.dim}${"\u2500".repeat(40)}${x.reset}`),n=!1,o="";else{n=!0,o=r.trim().substring(3).trim();let a=o?` ${o} `:"";s.push(`${x.dim}${"\u2500".repeat(3)}${a}${"\u2500".repeat(Math.max(0,37-a.length))}${x.reset}`)}continue}if(n){s.push(` ${Ga(r,o)}`);continue}if(r.startsWith("### ")){s.push(`${x.bold}${x.cyan} ${En(r.substring(4))}${x.reset}`);continue}if(r.startsWith("## ")){s.push(`${x.bold}${x.cyan} ${En(r.substring(3))}${x.reset}`);continue}if(r.startsWith("# ")){s.push(`${x.bold}${x.cyan}${En(r.substring(2))}${x.reset}`);continue}if(/^\s*[-*]\s/.test(r)){let a=r.match(/^(\s*)/)[1],c=r.replace(/^\s*[-*]\s/,""),l=`${a}${x.cyan}\u2022${x.reset} ${Tn(c)}`;s.push(Rn(l,i,a+" "));continue}if(/^\s*\d+\.\s/.test(r)){let a=r.match(/^(\s*)(\d+)\.\s(.*)/);if(a){let c=a[1],l=a[2],u=a[3],d=`${c}${x.cyan}${l}.${x.reset} ${Tn(u)}`,f=c+" ".repeat(l.length+2);s.push(Rn(d,i,f));continue}}s.push(Rn(Tn(r),i))}return s.join(`
590
- `)}function En(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function Tn(t){return t?t.replace(/`([^`]+)`/g,`${x.cyan}$1${x.reset}`).replace(/\*\*([^*]+)\*\*/g,`${x.bold}$1${x.reset}`).replace(/\*([^*]+)\*/g,`${x.dim}$1${x.reset}`).replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${x.cyan}$1${x.reset} ${x.dim}($2)${x.reset}`):""}function Ga(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?hp(t):e==="bash"||e==="sh"||e==="shell"||e==="zsh"?mp(t):e==="json"||e==="jsonc"?gp(t):e==="python"||e==="py"?yp(t):e==="go"||e==="golang"?$p(t):e==="rust"||e==="rs"?wp(t):e==="css"||e==="scss"||e==="less"?bp(t):e==="html"||e==="xml"||e==="svg"||e==="htm"?_p(t):t:""}function hp(t){let e=/\b(const|let|var|function|return|if|else|for|while|class|import|export|from|require|async|await|new|this|throw|try|catch|switch|case|break|default|typeof|instanceof)\b/g,s=/(["'`])(?:(?=(\\?))\2.)*?\1/g,n=/(\/\/.*$)/,o=/\b(\d+\.?\d*)\b/g,r=t;return r=r.replace(o,`${x.yellow}$1${x.reset}`),r=r.replace(e,`${x.magenta}$1${x.reset}`),r=r.replace(s,`${x.green}$&${x.reset}`),r=r.replace(n,`${x.dim}$1${x.reset}`),r}function mp(t){let e=/^(\s*)([\w-]+)/,s=/(--?\w[\w-]*)/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(#.*$)/,r=t;return r=r.replace(s,`${x.cyan}$1${x.reset}`),r=r.replace(e,`$1${x.green}$2${x.reset}`),r=r.replace(n,`${x.yellow}$&${x.reset}`),r=r.replace(o,`${x.dim}$1${x.reset}`),r}function gp(t){let e=/("[\w-]+")\s*:/g,s=/:\s*("(?:[^"\\]|\\.)*")/g,n=/:\s*(\d+\.?\d*)/g,o=/:\s*(true|false|null)/g,r=t;return r=r.replace(e,`${x.cyan}$1${x.reset}:`),r=r.replace(s,`: ${x.green}$1${x.reset}`),r=r.replace(n,`: ${x.yellow}$1${x.reset}`),r=r.replace(o,`: ${x.magenta}$1${x.reset}`),r}function yp(t){let e=/\b(def|class|if|elif|else|for|while|return|import|from|as|try|except|finally|raise|with|yield|lambda|pass|break|continue|and|or|not|in|is|None|True|False|self|async|await|nonlocal|global)\b/g,s=/("""[\s\S]*?"""|'''[\s\S]*?'''|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')/g,n=/(#.*$)/,o=/\b(\d+\.?\d*)\b/g,r=/^(\s*@\w+)/,i=t;return i=i.replace(o,`${x.yellow}$1${x.reset}`),i=i.replace(e,`${x.magenta}$1${x.reset}`),i=i.replace(r,`${x.cyan}$1${x.reset}`),i=i.replace(s,`${x.green}$&${x.reset}`),i=i.replace(n,`${x.dim}$1${x.reset}`),i}function $p(t){let e=/\b(func|package|import|var|const|type|struct|interface|map|chan|go|defer|return|if|else|for|range|switch|case|default|break|continue|select|fallthrough|nil|true|false|make|new|len|cap|append|copy|delete|panic|recover)\b/g,s=/\b(string|int|int8|int16|int32|int64|uint|uint8|uint16|uint32|uint64|float32|float64|bool|byte|rune|error|any)\b/g,n=/(["'`])(?:(?=(\\?))\2.)*?\1/g,o=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,i=t;return i=i.replace(r,`${x.yellow}$1${x.reset}`),i=i.replace(s,`${x.cyan}$1${x.reset}`),i=i.replace(e,`${x.magenta}$1${x.reset}`),i=i.replace(n,`${x.green}$&${x.reset}`),i=i.replace(o,`${x.dim}$1${x.reset}`),i}function wp(t){let e=/\b(fn|let|mut|const|struct|enum|impl|trait|pub|use|mod|crate|self|super|match|if|else|for|while|loop|return|break|continue|where|as|in|ref|move|async|await|unsafe|extern|type|static|dyn|macro_rules)\b/g,s=/\b(i8|i16|i32|i64|i128|u8|u16|u32|u64|u128|f32|f64|bool|char|str|String|Vec|Option|Result|Box|Rc|Arc|Self|Some|None|Ok|Err|true|false)\b/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,i=/\b(\w+!)/g,a=t;return a=a.replace(r,`${x.yellow}$1${x.reset}`),a=a.replace(s,`${x.cyan}$1${x.reset}`),a=a.replace(e,`${x.magenta}$1${x.reset}`),a=a.replace(i,`${x.yellow}$1${x.reset}`),a=a.replace(n,`${x.green}$&${x.reset}`),a=a.replace(o,`${x.dim}$1${x.reset}`),a}function bp(t){let e=/^(\s*)([\w-]+)\s*:/,s=/:\s*([^;]+)/,n=/^(\s*[.#@][\w-]+)/,o=/\b(\d+\.?\d*(px|em|rem|%|vh|vw|s|ms|deg|fr)?)\b/g,r=/(\/\*.*?\*\/|\/\/.*$)/,i=/(#[0-9a-fA-F]{3,8})\b/g,a=t;return a=a.replace(i,`${x.yellow}$1${x.reset}`),a=a.replace(o,`${x.yellow}$1${x.reset}`),a=a.replace(e,`$1${x.cyan}$2${x.reset}:`),a=a.replace(n,`$1${x.magenta}$&${x.reset}`),a=a.replace(r,`${x.dim}$1${x.reset}`),a}function _p(t){let e=/<\/?(\w[\w-]*)/g,s=/\s([\w-]+)=/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(<!--.*?-->)/g,r=/(&\w+;)/g,i=t;return i=i.replace(o,`${x.dim}$1${x.reset}`),i=i.replace(n,`${x.green}$&${x.reset}`),i=i.replace(e,`<${x.magenta}$1${x.reset}`),i=i.replace(s,` ${x.cyan}$1${x.reset}=`),i=i.replace(r,`${x.yellow}$1${x.reset}`),i}function Rn(t,e,s=""){if(!e||e<10)return t;let n="",o=0,r=-1,i=0,a=0,c=t.length;for(;i<c;){if(t[i]==="\x1B"){let l=i+1;if(l<c&&t[l]==="["){for(l++;l<c&&!/[a-zA-Z]/.test(t[l]);)l++;l<c&&l++}i=l;continue}if(t[i]===" "&&(r=i),o++,o>e&&r!==-1){n+=t.slice(a,r)+`
621
+ - 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 Rn=0;function Xb(){!_e||_e.status!=="executing"||(Rn>0&&Ja(Rn-1,"done"),Rn<_e.steps.length&&(Ja(Rn,"in_progress"),Rn++))}function Vb(){if(!_e||_e.status!=="executing"||_e.steps.length===0)return null;let t=Math.min(Rn,_e.steps.length),e=_e.steps.length,s=Math.max(0,t-1),n=_e.steps[s]?.description||"";return{current:t,total:e,description:n}}function Jb(){Rn=0}var kp=["interactive","semi-auto","autonomous"],vp="interactive";function Zb(t){return kp.includes(t)?(vp=t,!0):!1}function Qb(){return vp}Sp.exports={createPlan:Lb,getActivePlan:Pb,setPlanMode:Ib,isPlanMode:jb,approvePlan:Db,startExecution:qb,updateStep:Ja,formatPlan:Fb,savePlan:Bb,loadPlan:Wb,listPlans:Ub,clearPlan:Kb,getPlanModePrompt:zb,setPlanContent:Yb,getPlanContent:Gb,extractStepsFromText:Hb,advancePlanStep:Xb,getPlanStepInfo:Vb,PLAN_MODE_ALLOWED_TOOLS:_p,setAutonomyLevel:Zb,getAutonomyLevel:Qb,AUTONOMY_LEVELS:kp}});var Ip=re((Nv,Pp)=>{var{C:_}=He();function Ep(){return Math.max(10,(process.stdout.columns||80)-2)}function e_(t){if(!t)return"";let e=t.split(`
622
+ `),s=[],n=!1,o="";for(let r of e){let i=Ep();if(r.trim().startsWith("```")){if(n)s.push(`${_.dim}${"\u2500".repeat(40)}${_.reset}`),n=!1,o="";else{n=!0,o=r.trim().substring(3).trim();let a=o?` ${o} `:"";s.push(`${_.dim}${"\u2500".repeat(3)}${a}${"\u2500".repeat(Math.max(0,37-a.length))}${_.reset}`)}continue}if(n){s.push(` ${tc(r,o)}`);continue}if(r.startsWith("### ")){s.push(`${_.bold}${_.cyan} ${An(r.substring(4))}${_.reset}`);continue}if(r.startsWith("## ")){s.push(`${_.bold}${_.cyan} ${An(r.substring(3))}${_.reset}`);continue}if(r.startsWith("# ")){s.push(`${_.bold}${_.cyan}${An(r.substring(2))}${_.reset}`);continue}if(/^\s*[-*]\s/.test(r)){let a=r.match(/^(\s*)/)[1],c=r.replace(/^\s*[-*]\s/,""),l=`${a}${_.cyan}\u2022${_.reset} ${On(c)}`;s.push(Nn(l,i,a+" "));continue}if(/^\s*\d+\.\s/.test(r)){let a=r.match(/^(\s*)(\d+)\.\s(.*)/);if(a){let c=a[1],l=a[2],u=a[3],d=`${c}${_.cyan}${l}.${_.reset} ${On(u)}`,f=c+" ".repeat(l.length+2);s.push(Nn(d,i,f));continue}}s.push(Nn(On(r),i))}return s.join(`
623
+ `)}function An(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function On(t){return t?t.replace(/`([^`]+)`/g,`${_.cyan}$1${_.reset}`).replace(/\*\*([^*]+)\*\*/g,`${_.bold}$1${_.reset}`).replace(/\*([^*]+)\*/g,`${_.dim}$1${_.reset}`).replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${_.cyan}$1${_.reset} ${_.dim}($2)${_.reset}`):""}function tc(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?Tp(t):e==="bash"||e==="sh"||e==="shell"||e==="zsh"?Rp(t):e==="json"||e==="jsonc"?Cp(t):e==="python"||e==="py"?Ap(t):e==="go"||e==="golang"?Op(t):e==="rust"||e==="rs"?Np(t):e==="css"||e==="scss"||e==="less"?Mp(t):e==="html"||e==="xml"||e==="svg"||e==="htm"?Lp(t):t:""}function Tp(t){let e=/\b(const|let|var|function|return|if|else|for|while|class|import|export|from|require|async|await|new|this|throw|try|catch|switch|case|break|default|typeof|instanceof)\b/g,s=/(["'`])(?:(?=(\\?))\2.)*?\1/g,n=/(\/\/.*$)/,o=/\b(\d+\.?\d*)\b/g,r=t;return r=r.replace(o,`${_.yellow}$1${_.reset}`),r=r.replace(e,`${_.magenta}$1${_.reset}`),r=r.replace(s,`${_.green}$&${_.reset}`),r=r.replace(n,`${_.dim}$1${_.reset}`),r}function Rp(t){let e=/^(\s*)([\w-]+)/,s=/(--?\w[\w-]*)/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(#.*$)/,r=t;return r=r.replace(s,`${_.cyan}$1${_.reset}`),r=r.replace(e,`$1${_.green}$2${_.reset}`),r=r.replace(n,`${_.yellow}$&${_.reset}`),r=r.replace(o,`${_.dim}$1${_.reset}`),r}function Cp(t){let e=/("[\w-]+")\s*:/g,s=/:\s*("(?:[^"\\]|\\.)*")/g,n=/:\s*(\d+\.?\d*)/g,o=/:\s*(true|false|null)/g,r=t;return r=r.replace(e,`${_.cyan}$1${_.reset}:`),r=r.replace(s,`: ${_.green}$1${_.reset}`),r=r.replace(n,`: ${_.yellow}$1${_.reset}`),r=r.replace(o,`: ${_.magenta}$1${_.reset}`),r}function Ap(t){let e=/\b(def|class|if|elif|else|for|while|return|import|from|as|try|except|finally|raise|with|yield|lambda|pass|break|continue|and|or|not|in|is|None|True|False|self|async|await|nonlocal|global)\b/g,s=/("""[\s\S]*?"""|'''[\s\S]*?'''|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')/g,n=/(#.*$)/,o=/\b(\d+\.?\d*)\b/g,r=/^(\s*@\w+)/,i=t;return i=i.replace(o,`${_.yellow}$1${_.reset}`),i=i.replace(e,`${_.magenta}$1${_.reset}`),i=i.replace(r,`${_.cyan}$1${_.reset}`),i=i.replace(s,`${_.green}$&${_.reset}`),i=i.replace(n,`${_.dim}$1${_.reset}`),i}function Op(t){let e=/\b(func|package|import|var|const|type|struct|interface|map|chan|go|defer|return|if|else|for|range|switch|case|default|break|continue|select|fallthrough|nil|true|false|make|new|len|cap|append|copy|delete|panic|recover)\b/g,s=/\b(string|int|int8|int16|int32|int64|uint|uint8|uint16|uint32|uint64|float32|float64|bool|byte|rune|error|any)\b/g,n=/(["'`])(?:(?=(\\?))\2.)*?\1/g,o=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,i=t;return i=i.replace(r,`${_.yellow}$1${_.reset}`),i=i.replace(s,`${_.cyan}$1${_.reset}`),i=i.replace(e,`${_.magenta}$1${_.reset}`),i=i.replace(n,`${_.green}$&${_.reset}`),i=i.replace(o,`${_.dim}$1${_.reset}`),i}function Np(t){let e=/\b(fn|let|mut|const|struct|enum|impl|trait|pub|use|mod|crate|self|super|match|if|else|for|while|loop|return|break|continue|where|as|in|ref|move|async|await|unsafe|extern|type|static|dyn|macro_rules)\b/g,s=/\b(i8|i16|i32|i64|i128|u8|u16|u32|u64|u128|f32|f64|bool|char|str|String|Vec|Option|Result|Box|Rc|Arc|Self|Some|None|Ok|Err|true|false)\b/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,i=/\b(\w+!)/g,a=t;return a=a.replace(r,`${_.yellow}$1${_.reset}`),a=a.replace(s,`${_.cyan}$1${_.reset}`),a=a.replace(e,`${_.magenta}$1${_.reset}`),a=a.replace(i,`${_.yellow}$1${_.reset}`),a=a.replace(n,`${_.green}$&${_.reset}`),a=a.replace(o,`${_.dim}$1${_.reset}`),a}function Mp(t){let e=/^(\s*)([\w-]+)\s*:/,s=/:\s*([^;]+)/,n=/^(\s*[.#@][\w-]+)/,o=/\b(\d+\.?\d*(px|em|rem|%|vh|vw|s|ms|deg|fr)?)\b/g,r=/(\/\*.*?\*\/|\/\/.*$)/,i=/(#[0-9a-fA-F]{3,8})\b/g,a=t;return a=a.replace(i,`${_.yellow}$1${_.reset}`),a=a.replace(o,`${_.yellow}$1${_.reset}`),a=a.replace(e,`$1${_.cyan}$2${_.reset}:`),a=a.replace(n,`$1${_.magenta}$&${_.reset}`),a=a.replace(r,`${_.dim}$1${_.reset}`),a}function Lp(t){let e=/<\/?(\w[\w-]*)/g,s=/\s([\w-]+)=/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(<!--.*?-->)/g,r=/(&\w+;)/g,i=t;return i=i.replace(o,`${_.dim}$1${_.reset}`),i=i.replace(n,`${_.green}$&${_.reset}`),i=i.replace(e,`<${_.magenta}$1${_.reset}`),i=i.replace(s,` ${_.cyan}$1${_.reset}=`),i=i.replace(r,`${_.yellow}$1${_.reset}`),i}function Nn(t,e,s=""){if(!e||e<10)return t;let n="",o=0,r=-1,i=0,a=0,c=t.length;for(;i<c;){if(t[i]==="\x1B"){let l=i+1;if(l<c&&t[l]==="["){for(l++;l<c&&!/[a-zA-Z]/.test(t[l]);)l++;l<c&&l++}i=l;continue}if(t[i]===" "&&(r=i),o++,o>e&&r!==-1){n+=t.slice(a,r)+`
591
624
  `+s,a=r+1,i=a,o=s.length,r=-1;continue}o>e&&r===-1&&(n+=t.slice(a,i)+`
592
- `+s,a=i,o=s.length+1),i++}return n+=t.slice(a),n}function qb(t,e){if(!t||t.length===0)return"";let s=t.map((i,a)=>{let c=e.reduce((l,u)=>Math.max(l,(u[a]||"").length),0);return Math.max(i.length,c)}),n=s.map(i=>"\u2500".repeat(i+2)).join("\u253C"),o=t.map((i,a)=>` ${x.bold}${i.padEnd(s[a])}${x.reset} `).join("\u2502"),r=[];r.push(`${x.dim}\u250C${n.replace(/┼/g,"\u252C")}\u2510${x.reset}`),r.push(`${x.dim}\u2502${x.reset}${o}${x.dim}\u2502${x.reset}`),r.push(`${x.dim}\u251C${n}\u2524${x.reset}`);for(let i of e){let a=t.map((c,l)=>` ${(i[l]||"").padEnd(s[l])} `).join(`${x.dim}\u2502${x.reset}`);r.push(`${x.dim}\u2502${x.reset}${a}${x.dim}\u2502${x.reset}`)}return r.push(`${x.dim}\u2514${n.replace(/┼/g,"\u2534")}\u2518${x.reset}`),r.join(`
593
- `)}function Fb(t,e,s,n=30){let o=s>0?Math.round(e/s*100):0,r=Math.round(o/100*n),i=n-r,a=o>=100?x.green:o>50?x.yellow:x.cyan;return` ${t} ${a}${"\u2588".repeat(r)}${x.dim}${"\u2591".repeat(i)}${x.reset} ${o}% (${e}/${s})`}var Ha=class{constructor(){this.buffer="",this.inCodeBlock=!1,this.codeBlockLang="",this.lineCount=0,this._cursorTimer=null,this._cursorFrame=0,this._cursorActive=!1}_safeWrite(e){try{this.lineCount+=(e.match(/\n/g)||[]).length,process.stdout.write(e)}catch(s){if(s.code!=="EPIPE")throw s}}_cursorWrite(e){try{process.stderr.write(e)}catch(s){if(s.code!=="EPIPE")throw s}}startCursor(){process.stderr.isTTY&&(this._cursorActive=!0,this._cursorFrame=0,this._cursorWrite("\x1B[?25l"),this._renderCursor(),this._cursorTimer=setInterval(()=>this._renderCursor(),100))}_renderCursor(){let s=[0,1,2,3,4,3,2,1],n=s[this._cursorFrame%s.length],o="";for(let r=0;r<5;r++)o+=r===n?"\x1B[36m\u25CF\x1B[0m":" ";this._cursorWrite(`\x1B[2K\r${o}`),this._cursorFrame++}_clearCursorLine(){this._cursorActive&&this._cursorWrite("\x1B[2K\r")}stopCursor(){this._cursorTimer&&(clearInterval(this._cursorTimer),this._cursorTimer=null),this._cursorActive&&(this._cursorWrite("\x1B[2K\r\x1B[?25h"),this._cursorActive=!1)}push(e){if(!e)return;this._clearCursorLine(),this.buffer+=e;let s;for(;(s=this.buffer.indexOf(`
594
- `))!==-1;){let n=this.buffer.substring(0,s);this.buffer=this.buffer.substring(s+1),this._renderLine(n)}this._cursorActive&&(this._renderCursor(),this._cursorTimer&&clearInterval(this._cursorTimer),this._cursorTimer=setInterval(()=>this._renderCursor(),100))}flush(){this.stopCursor(),this.buffer&&(this._renderLine(this.buffer),this.buffer=""),this.inCodeBlock&&(this._safeWrite(`${x.dim}${"\u2500".repeat(40)}${x.reset}
595
- `),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){let s=pp();if(e.trim().startsWith("```")){if(this.inCodeBlock)this._safeWrite(`${x.dim}${"\u2500".repeat(40)}${x.reset}
596
- `),this.inCodeBlock=!1,this.codeBlockLang="";else{this.inCodeBlock=!0,this.codeBlockLang=e.trim().substring(3).trim();let o=this.codeBlockLang?` ${this.codeBlockLang} `:"";this._safeWrite(`${x.dim}${"\u2500".repeat(3)}${o}${"\u2500".repeat(Math.max(0,37-o.length))}${x.reset}
597
- `)}return}if(this.inCodeBlock){this._safeWrite(` ${Ga(e,this.codeBlockLang)}
598
- `);return}if(e.startsWith("### ")){this._safeWrite(`${x.bold}${x.cyan} ${En(e.substring(4))}${x.reset}
599
- `);return}if(e.startsWith("## ")){this._safeWrite(`${x.bold}${x.cyan} ${En(e.substring(3))}${x.reset}
600
- `);return}if(e.startsWith("# ")){this._safeWrite(`${x.bold}${x.cyan}${En(e.substring(2))}${x.reset}
601
- `);return}if(/^\s*[-*]\s/.test(e)){let o=e.match(/^(\s*)/)[1],r=e.replace(/^\s*[-*]\s/,""),i=`${o}${x.cyan}\u2022${x.reset} ${Tn(r)}`,a=Rn(i,s,o+" ");this._safeWrite(`${a}
602
- `);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],c=`${r}${x.cyan}${i}.${x.reset} ${Tn(a)}`,l=r+" ".repeat(i.length+2),u=Rn(c,s,l);this._safeWrite(`${u}
603
- `);return}}let n=Rn(Tn(e),s);this._safeWrite(`${n}
604
- `)}};xp.exports={renderMarkdown:Db,renderInline:Tn,stripHeadingMarkers:En,highlightCode:Ga,highlightJS:hp,highlightBash:mp,highlightJSON:gp,highlightPython:yp,highlightGo:$p,highlightRust:wp,highlightCSS:bp,highlightHTML:_p,renderTable:qb,renderProgress:Fb,wrapAnsi:Rn,StreamRenderer:Ha}});var Rp=se((fv,Tp)=>{var{execSync:Bb}=require("child_process"),Ya=require("path"),lo=require("fs"),Ka=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function vp(){return Ya.join(process.cwd(),".nex","hooks")}function Wb(){return Ya.join(process.cwd(),".nex","config.json")}function Sp(){let t=Wb();if(!lo.existsSync(t))return{};try{return JSON.parse(lo.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function Fr(t){if(!Ka.includes(t))return[];let e=[],s=vp(),n=Ya.join(s,t);lo.existsSync(n)&&e.push(n);let o=Sp();if(o[t]){let r=Array.isArray(o[t])?o[t]:[o[t]];e.push(...r)}return e}function Ep(t,e={},s=3e4){try{return{success:!0,output:Bb(t,{cwd:process.cwd(),encoding:"utf-8",timeout:s,env:{...process.env,...e},stdio:["pipe","pipe","pipe"]}).trim()}}catch(n){return{success:!1,error:n.stderr?n.stderr.trim():n.message}}}function Ub(t,e={}){let s=Fr(t);if(s.length===0)return[];let n={};for(let[r,i]of Object.entries(e))n[`NEX_${r.toUpperCase()}`]=String(i);let o=[];for(let r of s){let i=Ep(r,n);if(o.push({command:r,...i}),!i.success&&t.startsWith("pre-"))break}return o}function Hb(t){return Fr(t).length>0}function Gb(){let t=[];for(let e of Ka){let s=Fr(e);s.length>0&&t.push({event:e,commands:s})}return t}function Yb(){let t=vp();return lo.existsSync(t)||lo.mkdirSync(t,{recursive:!0}),t}Tp.exports={HOOK_EVENTS:Ka,loadHookConfig:Sp,getHooksForEvent:Fr,executeHook:Ep,runHooks:Ub,hasHooks:Hb,listHooks:Gb,initHooksDir:Yb}});var Wp=se((gv,Bp)=>{"use strict";var{callWithRetry:Ap,runSubAgent:Kb,clearAllLocks:zb}=ga(),{parseModelSpec:Op,getActiveProviderName:pv,getActiveModelId:hv}=He(),{detectCategory:Xb,getModelForCategory:Cp}=ls(),{MultiProgress:Vb,C:ce}=Ue(),{getModelBriefing:mv}=gr(),Np=parseInt(process.env.NEX_MAX_PARALLEL||"4",10),Br=parseInt(process.env.NEX_MAX_SUBTASKS||"8",10),Mp="devstral-2:123b",Lp="kimi-k2.5",Pp=`You are a task decomposition engine. Given a complex user request, split it into independent, atomic sub-tasks.
625
+ `+s,a=i,o=s.length+1),i++}return n+=t.slice(a),n}function t_(t,e){if(!t||t.length===0)return"";let s=t.map((i,a)=>{let c=e.reduce((l,u)=>Math.max(l,(u[a]||"").length),0);return Math.max(i.length,c)}),n=s.map(i=>"\u2500".repeat(i+2)).join("\u253C"),o=t.map((i,a)=>` ${_.bold}${i.padEnd(s[a])}${_.reset} `).join("\u2502"),r=[];r.push(`${_.dim}\u250C${n.replace(/┼/g,"\u252C")}\u2510${_.reset}`),r.push(`${_.dim}\u2502${_.reset}${o}${_.dim}\u2502${_.reset}`),r.push(`${_.dim}\u251C${n}\u2524${_.reset}`);for(let i of e){let a=t.map((c,l)=>` ${(i[l]||"").padEnd(s[l])} `).join(`${_.dim}\u2502${_.reset}`);r.push(`${_.dim}\u2502${_.reset}${a}${_.dim}\u2502${_.reset}`)}return r.push(`${_.dim}\u2514${n.replace(/┼/g,"\u2534")}\u2518${_.reset}`),r.join(`
626
+ `)}function n_(t,e,s,n=30){let o=s>0?Math.round(e/s*100):0,r=Math.round(o/100*n),i=n-r,a=o>=100?_.green:o>50?_.yellow:_.cyan;return` ${t} ${a}${"\u2588".repeat(r)}${_.dim}${"\u2591".repeat(i)}${_.reset} ${o}% (${e}/${s})`}var ec=class{constructor(){this.buffer="",this.inCodeBlock=!1,this.codeBlockLang="",this.lineCount=0,this._cursorTimer=null,this._cursorFrame=0,this._cursorActive=!1}_safeWrite(e){try{this.lineCount+=(e.match(/\n/g)||[]).length,process.stdout.write(e)}catch(s){if(s.code!=="EPIPE")throw s}}_cursorWrite(e){try{process.stderr.write(e)}catch(s){if(s.code!=="EPIPE")throw s}}startCursor(){process.stderr.isTTY&&(this._cursorActive=!0,this._cursorFrame=0,this._cursorWrite("\x1B[?25l"),this._renderCursor(),this._cursorTimer=setInterval(()=>this._renderCursor(),100))}_renderCursor(){let s=[0,1,2,3,4,3,2,1],n=s[this._cursorFrame%s.length],o="";for(let r=0;r<5;r++)o+=r===n?"\x1B[36m\u25CF\x1B[0m":" ";this._cursorWrite(`\x1B[2K\r${o}`),this._cursorFrame++}_clearCursorLine(){this._cursorActive&&this._cursorWrite("\x1B[2K\r")}stopCursor(){this._cursorTimer&&(clearInterval(this._cursorTimer),this._cursorTimer=null),this._cursorActive&&(this._cursorWrite("\x1B[2K\r\x1B[?25h"),this._cursorActive=!1)}push(e){if(!e)return;this._clearCursorLine(),this.buffer+=e;let s;for(;(s=this.buffer.indexOf(`
627
+ `))!==-1;){let n=this.buffer.substring(0,s);this.buffer=this.buffer.substring(s+1),this._renderLine(n)}this._cursorActive&&(this._renderCursor(),this._cursorTimer&&clearInterval(this._cursorTimer),this._cursorTimer=setInterval(()=>this._renderCursor(),100))}flush(){this.stopCursor(),this.buffer&&(this._renderLine(this.buffer),this.buffer=""),this.inCodeBlock&&(this._safeWrite(`${_.dim}${"\u2500".repeat(40)}${_.reset}
628
+ `),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){let s=Ep();if(e.trim().startsWith("```")){if(this.inCodeBlock)this._safeWrite(`${_.dim}${"\u2500".repeat(40)}${_.reset}
629
+ `),this.inCodeBlock=!1,this.codeBlockLang="";else{this.inCodeBlock=!0,this.codeBlockLang=e.trim().substring(3).trim();let o=this.codeBlockLang?` ${this.codeBlockLang} `:"";this._safeWrite(`${_.dim}${"\u2500".repeat(3)}${o}${"\u2500".repeat(Math.max(0,37-o.length))}${_.reset}
630
+ `)}return}if(this.inCodeBlock){this._safeWrite(` ${tc(e,this.codeBlockLang)}
631
+ `);return}if(e.startsWith("### ")){this._safeWrite(`${_.bold}${_.cyan} ${An(e.substring(4))}${_.reset}
632
+ `);return}if(e.startsWith("## ")){this._safeWrite(`${_.bold}${_.cyan} ${An(e.substring(3))}${_.reset}
633
+ `);return}if(e.startsWith("# ")){this._safeWrite(`${_.bold}${_.cyan}${An(e.substring(2))}${_.reset}
634
+ `);return}if(/^\s*[-*]\s/.test(e)){let o=e.match(/^(\s*)/)[1],r=e.replace(/^\s*[-*]\s/,""),i=`${o}${_.cyan}\u2022${_.reset} ${On(r)}`,a=Nn(i,s,o+" ");this._safeWrite(`${a}
635
+ `);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],c=`${r}${_.cyan}${i}.${_.reset} ${On(a)}`,l=r+" ".repeat(i.length+2),u=Nn(c,s,l);this._safeWrite(`${u}
636
+ `);return}}let n=Nn(On(e),s);this._safeWrite(`${n}
637
+ `)}};Pp.exports={renderMarkdown:e_,renderInline:On,stripHeadingMarkers:An,highlightCode:tc,highlightJS:Tp,highlightBash:Rp,highlightJSON:Cp,highlightPython:Ap,highlightGo:Op,highlightRust:Np,highlightCSS:Mp,highlightHTML:Lp,renderTable:t_,renderProgress:n_,wrapAnsi:Nn,StreamRenderer:ec}});var Bp=re((Mv,Fp)=>{var{execSync:s_}=require("child_process"),nc=require("path"),fo=require("fs"),sc=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function jp(){return nc.join(process.cwd(),".nex","hooks")}function o_(){return nc.join(process.cwd(),".nex","config.json")}function Dp(){let t=o_();if(!fo.existsSync(t))return{};try{return JSON.parse(fo.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function Ur(t){if(!sc.includes(t))return[];let e=[],s=jp(),n=nc.join(s,t);fo.existsSync(n)&&e.push(n);let o=Dp();if(o[t]){let r=Array.isArray(o[t])?o[t]:[o[t]];e.push(...r)}return e}function qp(t,e={},s=3e4){try{return{success:!0,exitCode:0,output:s_(t,{cwd:process.cwd(),encoding:"utf-8",timeout:s,env:{...process.env,...e},stdio:["pipe","pipe","pipe"]}).trim()}}catch(n){let o=typeof n.status=="number"?n.status:1;return{success:!1,exitCode:o,blocked:o===2,output:n.stdout?n.stdout.trim():"",error:n.stderr?n.stderr.trim():n.message}}}function r_(t,e={}){let s=Ur(t);if(s.length===0)return{results:[],blocked:!1};let n={};for(let[r,i]of Object.entries(e))n[`NEX_${r.toUpperCase()}`]=String(i);let o=[];for(let r of s){let i=qp(r,n);if(o.push({command:r,...i}),i.blocked&&t.startsWith("pre-")){let a=i.output||i.error||"hook blocked tool call";return{results:o,blocked:!0,blockReason:a}}if(!i.success&&t.startsWith("pre-"))break}return{results:o,blocked:!1}}function i_(t){return Ur(t).length>0}function a_(){let t=[];for(let e of sc){let s=Ur(e);s.length>0&&t.push({event:e,commands:s})}return t}function c_(){let t=jp();return fo.existsSync(t)||fo.mkdirSync(t,{recursive:!0}),t}Fp.exports={HOOK_EVENTS:sc,loadHookConfig:Dp,getHooksForEvent:Ur,executeHook:qp,runHooks:r_,hasHooks:i_,listHooks:a_,initHooksDir:c_}});var nh=re((jv,th)=>{"use strict";var{callWithRetry:Up,runSubAgent:l_,clearAllLocks:u_}=Sa(),{parseModelSpec:Hp,getActiveProviderName:Lv,getActiveModelId:Pv}=Ge(),{detectCategory:d_,getModelForCategory:Wp}=ps(),{MultiProgress:f_,C:de}=He(),{getModelBriefing:Iv}=wr(),Yp=parseInt(process.env.NEX_MAX_PARALLEL||"4",10),Hr=parseInt(process.env.NEX_MAX_SUBTASKS||"8",10),Gp="devstral-2:123b",Kp="kimi-k2.5",zp=`You are a task decomposition engine. Given a complex user request, split it into independent, atomic sub-tasks.
605
638
 
606
639
  RULES:
607
640
  - Output ONLY a JSON array, no markdown fences, no explanation.
@@ -616,7 +649,7 @@ RULES:
616
649
  - If the request is simple (single goal), return an array with exactly 1 item.
617
650
 
618
651
  USER REQUEST:
619
- {prompt}`,Ip=`You are a result synthesis engine. Given the results of multiple sub-agents that worked on parts of a larger task, produce a unified summary.
652
+ {prompt}`,Xp=`You are a result synthesis engine. Given the results of multiple sub-agents that worked on parts of a larger task, produce a unified summary.
620
653
 
621
654
  RULES:
622
655
  - Output ONLY a JSON object with these fields:
@@ -630,16 +663,16 @@ ORIGINAL REQUEST:
630
663
  {prompt}
631
664
 
632
665
  SUB-AGENT RESULTS:
633
- {results}`;async function jp(t,e=1,s=2e3){for(let n=0;n<=e;n++)try{return await t()}catch(o){if(n===e)throw o;await new Promise(r=>setTimeout(r,s))}}function Dp(t){let e=0,s=[];return function(){return new Promise(o=>{let r=()=>{e<t?(e++,o(()=>{e--,s.length>0&&s.shift()()})):s.push(r)};r()})}}function Jb(t){if(!t||typeof t!="string")return{isComplex:!1,estimatedGoals:0,reason:"empty"};let e=0,s=[],n=t.match(/(?:(?:^|\n)\s*|\s)(?:\d+[.)]\s|[(]\d+[)][\s,]|[(][a-z][)][\s,])/g);n&&n.length>=2&&(e=Math.max(e,n.length),s.push(`${n.length} numbered items`));let o=t.match(/(?:^|\n)\s*[-*]\s+\S/g);o&&o.length>=3&&(e=Math.max(e,o.length),s.push(`${o.length} bullet points`));let r=t.split(/;\s*/).filter(l=>l.trim().length>10);r.length>=3&&(e=Math.max(e,r.length),s.push(`${r.length} semicolon-separated goals`));let i=t.match(/\b(also|additionally|and\s+(?:fix|add|update|create|implement|remove|refactor))\b/gi);i&&i.length>=2&&(e=Math.max(e,i.length+1),s.push(`${i.length} transition keywords`));let a=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10);return{isComplex:e>=a,estimatedGoals:e,reason:s.length>0?s.join(", "):"single goal"}}function za(t){if(!t||typeof t!="string")throw new Error("Empty response from orchestrator model");let e=t.trim();try{return JSON.parse(e)}catch{}let s=e.match(/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/);if(s)try{return JSON.parse(s[1].trim())}catch{}let n=e.search(/[[\{]/);if(n>=0){let o=e.slice(n);try{return JSON.parse(o)}catch{}}throw new Error(`Could not extract valid JSON from response:
634
- ${e.slice(0,200)}`)}async function qp(t,e,s={}){let n=s.maxSubTasks||Br,r=[{role:"system",content:Pp.replace("{maxSubTasks}",String(n)).replace("{prompt}",t)},{role:"user",content:t}],i={};if(e){let g=Op(e);g.provider&&(i.provider=g.provider),g.model&&(i.model=g.model)}let c=(await Ap(r,[],i)).content||"",l=za(c);if(!Array.isArray(l))throw new Error(`Decompose returned non-array: ${typeof l}`);let u=10,f=l.slice(0,n).map((g,b)=>({id:g.id||`t${b+1}`,task:String(g.task||""),scope:Array.isArray(g.scope)?g.scope:[],estimatedCalls:typeof g.estimatedCalls=="number"?Math.min(g.estimatedCalls,u):8,priority:typeof g.priority=="number"?g.priority:b+1})).filter(g=>g.task.length>0),h=f.reduce((g,b)=>g+b.estimatedCalls,0),m=Br*u;if(h>m){let{debugLog:g}=Xo();g(`\x1B[33m \u26A0 Orchestrator: total estimated calls ${h} > ${m} \u2014 consider raising maxSubTasks\x1B[0m`)}return f}async function Fp(t,e,s){if(!t||t.length===0)return{summary:"No sub-tasks were executed.",conflicts:[],commitMessage:"",resourcesChanged:[]};let n=t.map((u,d)=>{let f=u.status==="done"?"SUCCESS":u.status==="truncated"?"PARTIAL":"FAILED";return`--- Agent ${d+1} [${f}] ---
666
+ {results}`;async function Vp(t,e=1,s=2e3){for(let n=0;n<=e;n++)try{return await t()}catch(o){if(n===e)throw o;await new Promise(r=>setTimeout(r,s))}}function Jp(t){let e=0,s=[];return function(){return new Promise(o=>{let r=()=>{e<t?(e++,o(()=>{e--,s.length>0&&s.shift()()})):s.push(r)};r()})}}function p_(t){if(!t||typeof t!="string")return{isComplex:!1,estimatedGoals:0,reason:"empty"};let e=0,s=[],n=t.match(/(?:(?:^|\n)\s*|\s)(?:\d+[.)]\s|[(]\d+[)][\s,]|[(][a-z][)][\s,])/g);n&&n.length>=2&&(e=Math.max(e,n.length),s.push(`${n.length} numbered items`));let o=t.match(/(?:^|\n)\s*[-*]\s+\S/g);o&&o.length>=3&&(e=Math.max(e,o.length),s.push(`${o.length} bullet points`));let r=t.split(/;\s*/).filter(l=>l.trim().length>10);r.length>=3&&(e=Math.max(e,r.length),s.push(`${r.length} semicolon-separated goals`));let i=t.match(/\b(also|additionally|and\s+(?:fix|add|update|create|implement|remove|refactor))\b/gi);i&&i.length>=2&&(e=Math.max(e,i.length+1),s.push(`${i.length} transition keywords`));let a=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10);return{isComplex:e>=a,estimatedGoals:e,reason:s.length>0?s.join(", "):"single goal"}}function oc(t){if(!t||typeof t!="string")throw new Error("Empty response from orchestrator model");let e=t.trim();try{return JSON.parse(e)}catch{}let s=e.match(/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/);if(s)try{return JSON.parse(s[1].trim())}catch{}let n=e.search(/[[\{]/);if(n>=0){let o=e.slice(n);try{return JSON.parse(o)}catch{}}throw new Error(`Could not extract valid JSON from response:
667
+ ${e.slice(0,200)}`)}async function Zp(t,e,s={}){let n=s.maxSubTasks||Hr,r=[{role:"system",content:zp.replace("{maxSubTasks}",String(n)).replace("{prompt}",t)},{role:"user",content:t}],i={};if(e){let m=Hp(e);m.provider&&(i.provider=m.provider),m.model&&(i.model=m.model)}let c=(await Up(r,[],i)).content||"",l=oc(c);if(!Array.isArray(l))throw new Error(`Decompose returned non-array: ${typeof l}`);let u=10,f=l.slice(0,n).map((m,b)=>({id:m.id||`t${b+1}`,task:String(m.task||""),scope:Array.isArray(m.scope)?m.scope:[],estimatedCalls:typeof m.estimatedCalls=="number"?Math.min(m.estimatedCalls,u):8,priority:typeof m.priority=="number"?m.priority:b+1})).filter(m=>m.task.length>0),h=f.reduce((m,b)=>m+b.estimatedCalls,0),g=Hr*u;if(h>g){let{debugLog:m}=Zo();m(`\x1B[33m \u26A0 Orchestrator: total estimated calls ${h} > ${g} \u2014 consider raising maxSubTasks\x1B[0m`)}return f}async function Qp(t,e,s){if(!t||t.length===0)return{summary:"No sub-tasks were executed.",conflicts:[],commitMessage:"",resourcesChanged:[]};let n=t.map((u,d)=>{let f=u.status==="done"?"SUCCESS":u.status==="truncated"?"PARTIAL":"FAILED";return`--- Agent ${d+1} [${f}] ---
635
668
  Task: ${u.task}
636
669
  Result: ${u.result}
637
670
  Tools: ${(u.toolsUsed||[]).join(", ")||"none"}`}).join(`
638
671
 
639
- `),r=[{role:"system",content:Ip.replace("{prompt}",e).replace("{results}",n)},{role:"user",content:"Synthesize the sub-agent results above."}],i={};if(s){let u=Op(s);u.provider&&(i.provider=u.provider),u.model&&(i.model=u.model)}let c=(await Ap(r,[],i)).content||"",l=za(c);return{summary:String(l.summary||""),conflicts:Array.isArray(l.conflicts)?l.conflicts:[],commitMessage:String(l.commitMessage||""),filesChanged:Array.isArray(l.filesChanged)?l.filesChanged:[]}}async function Zb(t,e={}){let s=e.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL||Lp,n=e.workerModel||Mp,o=e.maxParallel||Np,r=e.maxSubTasks||Br,i=e.onProgress||(()=>{}),a={input:0,output:0};console.log(`
640
- ${ce.bold}Orchestrator${ce.reset} ${ce.dim}model: ${s} | workers: ${n} | max parallel: ${o}${ce.reset}
641
- `),i("decomposing"),console.log(`${ce.dim}Phase 1: Decomposing prompt into sub-tasks...${ce.reset}`);let c;try{c=await qp(t,s,{maxSubTasks:r})}catch(H){return console.log(`${ce.red}Decompose failed: ${H.message}${ce.reset}`),{results:[],synthesis:{summary:`Decompose failed: ${H.message}`,conflicts:[],commitMessage:"",resourcesChanged:[]},totalTokens:a}}if(c.length===0)return console.log(`${ce.yellow}No sub-tasks generated. Prompt may be too simple for orchestration.${ce.reset}`),{results:[],synthesis:{summary:"No sub-tasks generated.",conflicts:[],commitMessage:"",resourcesChanged:[]},totalTokens:a};console.log(`${ce.green}Decomposed into ${c.length} sub-tasks:${ce.reset}`);for(let H of c){console.log(` ${ce.dim}${H.id}:${ce.reset} ${H.task}`);let _=H.scope.filter(Boolean);_.length>0&&console.log(` ${ce.dim}scope: ${_.join(", ")}${ce.reset}`)}console.log("");let l=new Map;for(let H=0;H<c.length;H++)for(let _ of c[H].scope)_&&!l.has(_)&&l.set(_,H);i("executing"),console.log(`${ce.dim}Phase 2: Running ${c.length} sub-agents (max ${o} parallel)...${ce.reset}
642
- `);let u=Date.now(),d=Dp(o),f={findings:[],_lock:!1},h=c.map(H=>{let _=Xb(H.task);return(_?Cp(_.id):null)||n}),m=c.map((H,_)=>{let he=`Agent ${_+1} [${h[_]}]: `,de=Math.max(20,60-he.length),me=H.task.substring(0,de)+(H.task.length>de?"...":"");return he+me}),g=new Vb(m);g.start();let b=`
672
+ `),r=[{role:"system",content:Xp.replace("{prompt}",e).replace("{results}",n)},{role:"user",content:"Synthesize the sub-agent results above."}],i={};if(s){let u=Hp(s);u.provider&&(i.provider=u.provider),u.model&&(i.model=u.model)}let c=(await Up(r,[],i)).content||"",l=oc(c);return{summary:String(l.summary||""),conflicts:Array.isArray(l.conflicts)?l.conflicts:[],commitMessage:String(l.commitMessage||""),filesChanged:Array.isArray(l.filesChanged)?l.filesChanged:[]}}async function h_(t,e={}){let s=e.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL||Kp,n=e.workerModel||Gp,o=e.maxParallel||Yp,r=e.maxSubTasks||Hr,i=e.onProgress||(()=>{}),a={input:0,output:0};console.log(`
673
+ ${de.bold}Orchestrator${de.reset} ${de.dim}model: ${s} | workers: ${n} | max parallel: ${o}${de.reset}
674
+ `),i("decomposing"),console.log(`${de.dim}Phase 1: Decomposing prompt into sub-tasks...${de.reset}`);let c;try{c=await Zp(t,s,{maxSubTasks:r})}catch(K){return console.log(`${de.red}Decompose failed: ${K.message}${de.reset}`),{results:[],synthesis:{summary:`Decompose failed: ${K.message}`,conflicts:[],commitMessage:"",resourcesChanged:[]},totalTokens:a}}if(c.length===0)return console.log(`${de.yellow}No sub-tasks generated. Prompt may be too simple for orchestration.${de.reset}`),{results:[],synthesis:{summary:"No sub-tasks generated.",conflicts:[],commitMessage:"",resourcesChanged:[]},totalTokens:a};console.log(`${de.green}Decomposed into ${c.length} sub-tasks:${de.reset}`);for(let K of c){console.log(` ${de.dim}${K.id}:${de.reset} ${K.task}`);let X=K.scope.filter(Boolean);X.length>0&&console.log(` ${de.dim}scope: ${X.join(", ")}${de.reset}`)}console.log("");let l=new Map;for(let K=0;K<c.length;K++)for(let X of c[K].scope)X&&!l.has(X)&&l.set(X,K);i("executing"),console.log(`${de.dim}Phase 2: Running ${c.length} sub-agents (max ${o} parallel)...${de.reset}
675
+ `);let u=Date.now(),d=Jp(o),f={findings:[],_lock:!1},h=c.map(K=>{let X=d_(K.task);return(X?Wp(X.id):null)||n}),g=c.map((K,X)=>{let me=`Agent ${X+1} [${h[X]}]: `,fe=Math.max(20,60-me.length),$e=K.task.substring(0,fe)+(K.task.length>fe?"...":"");return me+$e}),m=new f_(g);m.start();let b=`
643
676
  You are a focused coding agent executing ONE specific sub-task.
644
677
  Your scope is limited to the files listed in your task definition.
645
678
 
@@ -660,40 +693,40 @@ RULES:
660
693
  - If your task says "add X to README" \u2014 add it, don't check if it exists first.
661
694
  - Max 10 tool calls. If you need more, you are doing too much \u2014 narrow your scope.
662
695
  - When done: stop calling tools and write a one-line summary of what you changed.
663
- `,v=c.map(async(H,_)=>{let he=await d();try{let de=f.findings.filter(k=>k.agentId!==H.id).map(k=>`Agent ${k.agentId} found: ${k.summary}`).join(`
664
- `),me=[...l.entries()].filter(([,k])=>k===_).map(([k])=>k),ge=[...l.entries()].filter(([,k])=>k!==_).map(([k])=>k),we=[de?`Prior agent findings:
665
- ${de}
666
- `:"",H.scope.length>0?`Focus on files: ${H.scope.join(", ")}`:"",me.length>0?`You OWN these files (may read+write): ${me.join(", ")}`:"",ge.length>0?`READ ONLY (owned by other agents, do NOT write): ${ge.join(", ")}`:""].filter(Boolean),Se=h[_],fe=process.env.NEX_FALLBACK_MODEL||Cp("agentic")||n,Pe=0,w=await jp(async()=>{let k=Pe>0;k&&(g.update(_,"retry"),process.stderr.write(` ${ce.dim}[Agent ${_+1}] retrying after error...${ce.reset}
667
- `)),Pe++;let N=k&&Se!==fe?fe:Se;return Kb({task:H.task,context:we.length>0?we.join(`
668
- `):void 0,max_iterations:Math.min(H.estimatedCalls||10,15),model:N,_skipLog:!0,_systemPrompt:b,_readOnlyFiles:ge},{onUpdate:T=>{if(T&&T.type==="tool_call"&&process.stderr.isTTY){let S=`Agent ${_+1} [${N}]`,J=T.tool||"...";g.labels[_]=`${S}: ${J}`}}})},1,2e3),P=typeof w.result=="string"?w.result.slice(0,200):String(w.result||"").slice(0,200);return f.findings.push({agentId:H.id,summary:P,files:Array.isArray(H.scope)?H.scope:[]}),g.labels[_]=m[_],g.update(_,w.status==="failed"?"error":"done"),a.input+=w.tokensUsed?.input||0,a.output+=w.tokensUsed?.output||0,w.tokensUsed?._estimated&&(a._estimated=!0),{...w,_scope:H.scope,_idx:_}}catch(de){return g.labels[_]=m[_],g.update(_,"error"),{task:H.task,status:"failed",result:`Error: ${de.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}}finally{he()}}),O;try{O=await Promise.all(v)}finally{g.stop({silent:!0}),zb()}console.log("");let U=Math.round((Date.now()-u)/1e3),L=U>=60?`${Math.floor(U/60)}m ${U%60}s`:`${U}s`;for(let H=0;H<O.length;H++){let _=O[H],de=_.status==="done"||_.status==="truncated"&&_.result&&!_.result.startsWith("Error")?`${ce.green}\u2713${ce.reset}`:`${ce.red}\u2717${ce.reset}`,me=_._scope&&_._scope.length>0?_._scope.map(Se=>Se.replace(/^.*\//,"").replace(/\/$/,"")).filter(Boolean):[],ge=me.length>0?me.join(", "):_.task.substring(0,35)+(_.task.length>35?"...":""),we=H===O.length-1;console.log(` ${de} Agent ${H+1} ${ce.dim}${ge}${ce.reset}${we?` ${ce.dim}${L}${ce.reset}`:""}`)}console.log(""),i("synthesizing"),console.log(`${ce.dim}Phase 3: Synthesizing results...${ce.reset}`);let R;try{R=await Fp(O,t,s)}catch(H){console.log(`${ce.yellow}Synthesize failed: ${H.message} \u2014 using raw results.${ce.reset}`),R={summary:O.map(_=>_.result).join(`
669
- `),conflicts:[],commitMessage:"",resourcesChanged:[]}}let C=f.findings.flatMap(H=>H.files),K=new Map;for(let H of C)K.set(H,(K.get(H)||0)+1);let Q=[...K.values()].some(H=>H>1),re=f.findings.length>1&&Q?` ${ce.dim}(agents shared context)${ce.reset}`:"";if(console.log(`
670
- ${ce.bold}Summary:${ce.reset} ${R.summary}${re}`),R.conflicts.length>0){console.log(`${ce.yellow}Conflicts:${ce.reset}`);for(let H of R.conflicts)console.log(` - ${H}`)}R.commitMessage&&console.log(`${ce.dim}Suggested commit: ${R.commitMessage}${ce.reset}`);let V=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(`${ce.dim}Tokens: ${V}${ce.reset}
671
- `),{results:O,synthesis:R,totalTokens:a}}Bp.exports={runOrchestrated:Zb,decompose:qp,synthesize:Fp,detectComplexPrompt:Jb,extractJSON:za,createSemaphore:Dp,DECOMPOSE_PROMPT:Pp,SYNTHESIZE_PROMPT:Ip,DEFAULT_ORCHESTRATOR_MODEL:Lp,DEFAULT_WORKER_MODEL:Mp,DEFAULT_MAX_PARALLEL:Np,DEFAULT_MAX_SUBTASKS:Br,withRetry:jp}});var fh=se((xv,dh)=>{var{C:p,Spinner:hs,TaskProgress:Qb,formatToolCall:e_,formatToolSummary:sh,formatSectionHeader:Wr,formatMilestone:t_,setActiveTaskProgress:yv}=Ue(),{debugLog:D,warnLog:$v}=Xo(),{MilestoneTracker:n_}=Fl(),{callStream:Up}=He(),{parseToolArgs:s_}=Ss(),{executeTool:o_}=Jn(),{gatherProjectContext:r_}=Lf(),{fitToContext:i_,forceCompress:It,getUsage:Et,estimateTokens:a_}=Pt(),{autoSave:c_,flushAutoSave:l_}=Mr(),{scoreMessages:u_,formatScore:d_,appendScoreHistory:f_}=Lr(),{detectCategory:p_,getModelForPhase:oc,getPhaseBudget:Cn,isPhaseRoutingEnabled:h_}=ls();function Be(t){c_(t),l_()}function m_(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 Hp(t){try{if(!t.some(n=>n.role!=="assistant"?!1:!!(Array.isArray(n.content)&&n.content.some(o=>o&&o.type==="tool_use")||Array.isArray(n.tool_calls)&&n.tool_calls.length>0)))return;let s=u_(t);if(!s)return;console.log(d_(s,p));try{let{_getSessionsDir:n}=Mr(),o=require("fs"),r=require("path").join(n(),"_autosave.json");if(o.existsSync(r)){let i=JSON.parse(o.readFileSync(r,"utf-8"));i.score=s.score,i.scoreGrade=s.grade,i.scoreIssues=s.issues,o.writeFileSync(r,JSON.stringify(i,null,2))}}catch{}try{let{getActiveModel:n}=Ss(),o=No();f_(s.score,{version:o.version,model:n?n():null,sessionName:"_autosave",issues:s.issues})}catch{}}catch{}}var{getMemoryContext:g_}=zs(),{getDeploymentContextBlock:y_,probeUrlServer:$_}=La(),{getFewShotForInput:w_}=tp(),{checkPermission:b_,setPermission:__,savePermissions:x_}=ap(),{confirm:oh,setAllowAlwaysHandler:k_,getAutoConfirm:v_}=Es(),{isPlanMode:wo,getPlanModePrompt:S_,PLAN_MODE_ALLOWED_TOOLS:rh,setPlanContent:E_,extractStepsFromText:T_,createPlan:R_,getActivePlan:wv,startExecution:bv,advancePlanStep:C_,getPlanStepInfo:A_}=qr(),{StreamRenderer:O_}=kp(),{runHooks:Gp}=Rp(),{routeMCPCall:N_,getMCPToolDefinitions:M_}=zi(),{getSkillInstructions:L_,getSkillToolDefinitions:P_,routeSkillCall:I_,matchSkillTriggers:j_}=Yi(),{trackUsage:Yp,estimateTokens:Kp}=zo();function zp(t){return!t||typeof t!="string"?0:typeof Kp=="function"?Kp(t):Math.ceil(t.length/4)}var{validateToolArgs:D_}=Ji(),{filterToolsForModel:Xp,getModelTier:q_,PROVIDER_DEFAULT_TIER:_v}=Is(),{getConfiguredProviders:F_,getActiveProviderName:ms,getActiveModelId:Dt,setActiveModel:Vp,MODEL_EQUIVALENTS:ti}=He(),{getModelProfile:B_,getModelBriefing:W_}=gr(),mc=require("fs"),gc=require("path"),U_=(()=>{let t=parseInt(process.env.NEX_MILESTONE_STEPS??"5",10);return Number.isFinite(t)&&t>=0?t:5})();function H_(t){let e=t_(t.phaseName,t.stepCount,t.toolCounts,t.elapsed,t.filesRead,t.filesModified);process.stdout.write(`${e}
672
- `)}var Jp=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi;function G_(t){let e=[],s;for(Jp.lastIndex=0;(s=Jp.exec(t))!==null;){let n=s[1].trim(),o=n.startsWith("~")?n.replace("~",process.env.HOME||""):gc.resolve(n);mc.existsSync(o)&&e.push({raw:n,abs:o})}return e}function Y_(t){let e=mc.readFileSync(t),s=gc.extname(t).toLowerCase().replace(".",""),n=s==="jpg"||s==="jpeg"?"image/jpeg":s==="png"?"image/png":s==="gif"?"image/gif":s==="webp"?"image/webp":"image/png";return{data:e.toString("base64"),media_type:n}}function ih(t){let e=G_(t);if(e.length===0)return t;let s=[{type:"text",text:t}];for(let n of e)try{let{data:o,media_type:r}=Y_(n.abs);s.push({type:"image",media_type:r,data:o})}catch{}return s.length>1?s:t}function K_(t){if(!t||t.length<200)return{text:t,truncated:!1,repeatCount:0};let s=t.split(/(?<=\. )/).filter(c=>c.trim().length>0);if(s.length<6)return{text:t,truncated:!1,repeatCount:0};let n=new Map;for(let c=0;c<=s.length-3;c++){let l=s.slice(c,c+3).join("").trim();l.length>30&&n.set(l,(n.get(l)||0)+1)}let o=0,r="";for(let[c,l]of n)l>o&&(o=l,r=c);if(o<3)return{text:t,truncated:!1,repeatCount:o};let i=`
673
-
674
- [SYSTEM: Output repetition detected \u2014 response truncated (${o}\xD7 repeated paragraph)]`,a;if(t.length>8e3)a=t.slice(0,3e3)+i;else{let c=0,l=-1,u=0;for(;c<2;){let d=t.indexOf(r,u);if(d===-1)break;c++,l=d+r.length,u=d+1}a=l>0?t.slice(0,l)+i:t.slice(0,3e3)+i}return{text:a,truncated:!0,repeatCount:o}}function rc(t,e=5){if(!t||t.length<40)return{text:t,truncated:!1,repeatCount:0};let s=t.split(`
696
+ `,x=new Map;for(let K=0;K<c.length;K++){let X=c[K].priority||1;x.has(X)||x.set(X,[]),x.get(X).push({st:c[K],idx:K})}let j=[...x.keys()].sort((K,X)=>K-X),G=new Array(c.length);for(let K of j){let me=x.get(K).map(async({st:fe,idx:$e})=>{let pe=await d();try{let Re=await L(fe,$e,{acquire:d,subTaskModels:h,labels:g,progress:m,sharedContext:f,_fileOwnership:l,workerModel:n,WORKER_SYSTEM_PROMPT:b});return G[$e]=Re,Re}finally{pe()}});await Promise.all(me)}async function L(K,X,me){try{let fe=f.findings.filter(H=>H.agentId!==K.id).map(H=>`Agent ${H.agentId} found: ${H.summary}`).join(`
697
+ `),$e=[...l.entries()].filter(([,H])=>H===X).map(([H])=>H),pe=[...l.entries()].filter(([,H])=>H!==X).map(([H])=>H),Re=[fe?`Prior agent findings:
698
+ ${fe}
699
+ `:"",K.scope.length>0?`Focus on files: ${K.scope.join(", ")}`:"",$e.length>0?`You OWN these files (may read+write): ${$e.join(", ")}`:"",pe.length>0?`READ ONLY (owned by other agents, do NOT write): ${pe.join(", ")}`:""].filter(Boolean),w=eh(K.task),I=h[X],v=process.env.NEX_FALLBACK_MODEL||Wp("agentic")||n,O=0,R=await Vp(async()=>{let H=O>0;H&&(m.update(X,"retry"),process.stderr.write(` ${de.dim}[Agent ${X+1}] retrying after error...${de.reset}
700
+ `)),O++;let Se=H&&I!==v?v:I;return l_({task:K.task,type:w,context:Re.length>0?Re.join(`
701
+ `):void 0,max_iterations:Math.min(K.estimatedCalls||10,15),model:Se,_skipLog:!0,_systemPrompt:b,_readOnlyFiles:pe},{onUpdate:xe=>{if(xe&&xe.type==="tool_call"&&process.stderr.isTTY){let ge=`Agent ${X+1} [${Se}]`,fi=xe.tool||"...";m.labels[X]=`${ge}: ${fi}`}}})},1,2e3),k=typeof R.result=="string"?R.result.slice(0,200):String(R.result||"").slice(0,200);return f.findings.push({agentId:K.id,summary:k,files:Array.isArray(K.scope)?K.scope:[]}),m.labels[X]=g[X],m.update(X,R.status==="failed"?"error":"done"),a.input+=R.tokensUsed?.input||0,a.output+=R.tokensUsed?.output||0,R.tokensUsed?._estimated&&(a._estimated=!0),{...R,_scope:K.scope,_idx:X}}catch(fe){return m.labels[X]=g[X],m.update(X,"error"),{task:K.task,status:"failed",result:`Error: ${fe.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}}}let P;try{P=G}finally{m.stop({silent:!0}),u_()}console.log("");let C=Math.round((Date.now()-u)/1e3),Z=C>=60?`${Math.floor(C/60)}m ${C%60}s`:`${C}s`;for(let K=0;K<P.length;K++){let X=P[K],fe=X.status==="done"||X.status==="truncated"&&X.result&&!X.result.startsWith("Error")?`${de.green}\u2713${de.reset}`:`${de.red}\u2717${de.reset}`,$e=X._scope&&X._scope.length>0?X._scope.map(w=>w.replace(/^.*\//,"").replace(/\/$/,"")).filter(Boolean):[],pe=$e.length>0?$e.join(", "):X.task.substring(0,35)+(X.task.length>35?"...":""),Re=K===P.length-1;console.log(` ${fe} Agent ${K+1} ${de.dim}${pe}${de.reset}${Re?` ${de.dim}${Z}${de.reset}`:""}`)}console.log(""),i("synthesizing"),console.log(`${de.dim}Phase 3: Synthesizing results...${de.reset}`);let Y;try{Y=await Qp(P,t,s)}catch(K){console.log(`${de.yellow}Synthesize failed: ${K.message} \u2014 using raw results.${de.reset}`),Y={summary:P.map(X=>X.result).join(`
702
+ `),conflicts:[],commitMessage:"",resourcesChanged:[]}}let ue=f.findings.flatMap(K=>K.files),ie=new Map;for(let K of ue)ie.set(K,(ie.get(K)||0)+1);let se=[...ie.values()].some(K=>K>1),T=f.findings.length>1&&se?` ${de.dim}(agents shared context)${de.reset}`:"";if(console.log(`
703
+ ${de.bold}Summary:${de.reset} ${Y.summary}${T}`),Y.conflicts.length>0){console.log(`${de.yellow}Conflicts:${de.reset}`);for(let K of Y.conflicts)console.log(` - ${K}`)}Y.commitMessage&&console.log(`${de.dim}Suggested commit: ${Y.commitMessage}${de.reset}`);let Te=a.input===0&&a.output===0?"n/a (provider does not report token counts)":a._estimated?`~${a.input} input / ~${a.output} output (est.)`:`${a.input} input + ${a.output} output`;return console.log(`${de.dim}Tokens: ${Te}${de.reset}
704
+ `),{results:P,synthesis:Y,totalTokens:a}}var m_=/\b(research|analyze|investigate|check|verify|review|audit|read|find|search|discover|look|examine|inspect|scan|list)\b/i,g_=/\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 eh(t){if(!t)return"implement";let e=m_.test(t);return g_.test(t)?"implement":e?"explore":"implement"}th.exports={runOrchestrated:h_,decompose:Zp,synthesize:Qp,detectComplexPrompt:p_,extractJSON:oc,createSemaphore:Jp,DECOMPOSE_PROMPT:zp,SYNTHESIZE_PROMPT:Xp,DEFAULT_ORCHESTRATOR_MODEL:Kp,DEFAULT_WORKER_MODEL:Gp,DEFAULT_MAX_PARALLEL:Yp,DEFAULT_MAX_SUBTASKS:Hr,withRetry:Vp,_classifyWorkerType:eh}});var kh=re((Uv,xh)=>{var{C:p,Spinner:$s,TaskProgress:y_,formatToolCall:$_,formatToolSummary:yc,formatSectionHeader:Yr,formatMilestone:w_,setActiveTaskProgress:Dv,getThinkingVerb:rc,setActiveModelForSpinner:b_}=He(),{debugLog:F,warnLog:qv}=Zo(),{MilestoneTracker:__}=eu(),{callStream:sh}=Ge(),{parseToolArgs:x_}=Rs(),{executeTool:k_}=ts(),{gatherProjectContext:v_}=zf(),{fitToContext:S_,forceCompress:jt,getUsage:Tt,estimateTokens:E_,buildProgressSnapshot:T_}=It(),{autoSave:R_,flushAutoSave:C_}=Ir(),{scoreMessages:A_,formatScore:O_,appendScoreHistory:N_}=jr(),{detectCategory:M_,getModelForPhase:$c,getPhaseBudget:Mn,isPhaseRoutingEnabled:L_}=ps();function qe(t){R_(t),C_()}function P_(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 ic(t){try{if(!t.some(n=>n.role!=="assistant"?!1:!!(Array.isArray(n.content)&&n.content.some(o=>o&&o.type==="tool_use")||Array.isArray(n.tool_calls)&&n.tool_calls.length>0)))return;let s=A_(t);if(!s)return;console.log(O_(s,p));try{let{_getSessionsDir:n}=Ir(),o=require("fs"),r=require("path").join(n(),"_autosave.json");if(o.existsSync(r)){let i=JSON.parse(o.readFileSync(r,"utf-8"));i.score=s.score,i.scoreGrade=s.grade,i.scoreIssues=s.issues,o.writeFileSync(r,JSON.stringify(i,null,2))}}catch{}try{let{getActiveModel:n}=Rs(),o=Lo();N_(s.score,{version:o.version,model:n?n():null,sessionName:"_autosave",issues:s.issues})}catch{}}catch{}}var{getMemoryContext:I_}=Js(),{getDeploymentContextBlock:j_,probeUrlServer:D_}=Ua(),{getFewShotForInput:q_}=hp(),{checkPermission:F_,setPermission:B_,savePermissions:W_}=bp(),{confirm:mh,setAllowAlwaysHandler:U_,getAutoConfirm:H_}=Cs(),{isPlanMode:_o,getPlanModePrompt:Y_,PLAN_MODE_ALLOWED_TOOLS:gh,setPlanContent:G_,extractStepsFromText:K_,createPlan:z_,getActivePlan:Fv,startExecution:Bv,advancePlanStep:X_,getPlanStepInfo:V_}=Wr(),{StreamRenderer:J_}=Ip(),{runHooks:oh}=Bp(),{routeMCPCall:Z_,getMCPToolDefinitions:Q_}=na(),{getSkillInstructions:ex,getSkillToolDefinitions:tx,routeSkillCall:nx,matchSkillTriggers:sx}=ea(),{trackUsage:rh,estimateTokens:ih}=Jo();function ah(t){return!t||typeof t!="string"?0:typeof ih=="function"?ih(t):Math.ceil(t.length/4)}var{validateToolArgs:ox}=ra(),{filterToolsForModel:ch,getModelTier:rx,PROVIDER_DEFAULT_TIER:Wv}=qs(),{getConfiguredProviders:ix,getActiveProviderName:ws,getActiveModelId:At,setActiveModel:lh,MODEL_EQUIVALENTS:oi}=Ge(),{getModelProfile:ax,getModelBriefing:cx}=wr(),Ac=require("fs"),Oc=require("path"),lx=(()=>{let t=parseInt(process.env.NEX_MILESTONE_STEPS??"5",10);return Number.isFinite(t)&&t>=0?t:5})();function ux(t){let e=w_(t.phaseName,t.stepCount,t.toolCounts,t.elapsed,t.filesRead,t.filesModified);process.stdout.write(`${e}
705
+ `)}var uh=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi;function dx(t){let e=[],s;for(uh.lastIndex=0;(s=uh.exec(t))!==null;){let n=s[1].trim(),o=n.startsWith("~")?n.replace("~",process.env.HOME||""):Oc.resolve(n);Ac.existsSync(o)&&e.push({raw:n,abs:o})}return e}function fx(t){let e=Ac.readFileSync(t),s=Oc.extname(t).toLowerCase().replace(".",""),n=s==="jpg"||s==="jpeg"?"image/jpeg":s==="png"?"image/png":s==="gif"?"image/gif":s==="webp"?"image/webp":"image/png";return{data:e.toString("base64"),media_type:n}}function yh(t){let e=dx(t);if(e.length===0)return t;let s=[{type:"text",text:t}];for(let n of e)try{let{data:o,media_type:r}=fx(n.abs);s.push({type:"image",media_type:r,data:o})}catch{}return s.length>1?s:t}function px(t){if(!t||t.length<200)return{text:t,truncated:!1,repeatCount:0};let s=t.split(/(?<=\. )/).filter(c=>c.trim().length>0);if(s.length<6)return{text:t,truncated:!1,repeatCount:0};let n=new Map;for(let c=0;c<=s.length-3;c++){let l=s.slice(c,c+3).join("").trim();l.length>30&&n.set(l,(n.get(l)||0)+1)}let o=0,r="";for(let[c,l]of n)l>o&&(o=l,r=c);if(o<3)return{text:t,truncated:!1,repeatCount:o};let i=`
706
+
707
+ [SYSTEM: Output repetition detected \u2014 response truncated (${o}\xD7 repeated paragraph)]`,a;if(t.length>8e3)a=t.slice(0,3e3)+i;else{let c=0,l=-1,u=0;for(;c<2;){let d=t.indexOf(r,u);if(d===-1)break;c++,l=d+r.length,u=d+1}a=l>0?t.slice(0,l)+i:t.slice(0,3e3)+i}return{text:a,truncated:!0,repeatCount:o}}function wc(t,e=5){if(!t||t.length<40)return{text:t,truncated:!1,repeatCount:0};let s=t.split(`
675
708
  `),n=new Map;for(let d of s){let f=d.trim();f.length>=20&&n.set(f,(n.get(f)||0)+1)}let o=0,r="";for(let[d,f]of n)f>o&&(o=f,r=d);if(o<=e)return{text:t,truncated:!1,repeatCount:o};let i=`
676
709
 
677
- \u26A0 [Response truncated: repeated paragraph detected (${o}\xD7)]`,a=0,c=-1,l=0;for(;a<e;){let d=t.indexOf(r,l);if(d===-1)break;a++,c=d+r.length,l=d+1}return{text:c>0?t.slice(0,c)+i:t.slice(0,2e3)+i,truncated:!0,repeatCount:o}}var Xa=null,Va=null,Ja=null;function Ze(){if(Xa===null){let{TOOL_DEFINITIONS:t}=Jn();Xa=t}return Va===null&&(Va=P_()),Ja===null&&(Ja=M_()),[...Xa,...Va,...Ja]}var ic=50;function z_(t){Number.isFinite(t)&&t>0&&(ic=t)}var Gr=()=>null;function X_(t){Gr=t}var po=null,ac=null,gs=null,Yr=new Map,V_=1e4,J_=6e3,Z_=/\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 Q_(t){return!t||typeof t!="string"?t:t.replace(Z_,(e,s)=>`${s}=***REDACTED***`)}var ex=7e3,tx=4e3;function nx(t,e=null){let s=Q_(t),n=a_(s),o=e==="read_file"?ex:V_,r=e==="read_file"?tx:J_;if(n>o)try{let{compressToolResult:i}=Pt();return i(s,r)}catch{return s}return s}function ah(t){try{let{getActiveModel:e}=He(),s=e(),n=s?`${s.provider}:${s.id}`:"default";if(Yr.has(n))return Yr.get(n);let o=Xp(t);return Yr.set(n,o),o}catch{return Xp(t)}}function sx(){Yr.clear()}var ho={hash:null,ts:0},ox=3e4;async function ch(){if(ho.hash&&Date.now()-ho.ts<ox)return ho.hash;try{let t=require("fs").promises,e=require("path"),s=[e.join(process.cwd(),"package.json"),e.join(process.cwd(),".git","HEAD"),e.join(process.cwd(),"README.md"),e.join(process.cwd(),"NEX.md")],o=(await Promise.allSettled(s.map(i=>t.stat(i).then(a=>`${i}:${a.mtimeMs}`)))).filter(i=>i.status==="fulfilled").map(i=>i.value);try{let{getMemoryContextHash:i}=zs(),a=i();a&&o.push(`memory:${a}`)}catch{}try{let i=e.join(process.cwd(),".nex","brain");if(mc.existsSync(i)){let a=await t.stat(i);o.push(`brain:${a.mtimeMs}`)}}catch{}let r=o.join("|");return ho={hash:r,ts:Date.now()},r}catch{return`fallback:${Date.now()}`}}function cc(){po=null,ac=null,ho={hash:null,ts:0},gs=null}var rx=new Set(["spawn_agents"]),Za=5,Qa=3,Ur=2,Zp=6e4,ec=12e4,ix=process.env.NEX_STALE_AUTO_SWITCH!=="0";function ax(t){try{let e=require("fs"),s=require("path"),n=s.join(process.cwd(),".nex","plans");e.existsSync(n)||e.mkdirSync(n,{recursive:!0});let o=s.join(n,"current-plan.md");e.writeFileSync(o,t,"utf-8")}catch{}}k_(t=>{__(t,"allow"),x_(),console.log(`${p.green} \u2713 ${t}: always allow${p.reset}`)});async function cx(t){let e=t.function.name,s=s_(t.function.arguments),n=t.id||`cli-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!s){let u=Ze().find(f=>f.function.name===e),d=u?JSON.stringify(u.function.parameters,null,2):"unknown";return D(`${p.yellow} \u26A0 ${e}: malformed arguments, sending schema hint${p.reset}`),{callId:n,fnName:e,args:null,canExecute:!1,errorResult:{role:"tool",content:`ERROR: Malformed tool arguments. Could not parse your arguments as JSON.
710
+ \u26A0 [Response truncated: repeated paragraph detected (${o}\xD7)]`,a=0,c=-1,l=0;for(;a<e;){let d=t.indexOf(r,l);if(d===-1)break;a++,c=d+r.length,l=d+1}return{text:c>0?t.slice(0,c)+i:t.slice(0,2e3)+i,truncated:!0,repeatCount:o}}var ac=null,cc=null,lc=null;function Qe(){if(ac===null){let{TOOL_DEFINITIONS:t}=ts();ac=t}return cc===null&&(cc=tx()),lc===null&&(lc=Q_()),[...ac,...cc,...lc]}var bc=50;function hx(t){Number.isFinite(t)&&t>0&&(bc=t)}var zr=()=>null;function mx(t){zr=t}var mo=null,_c=null,bs=null,Xr=new Map,gx=1e4,yx=6e3,$x=/\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 wx(t){return!t||typeof t!="string"?t:t.replace($x,(e,s)=>`${s}=***REDACTED***`)}var bx=7e3,_x=4e3;function xx(t,e=null){let s=wx(t),n=E_(s),o=e==="read_file"?bx:gx,r=e==="read_file"?_x:yx;if(n>o)try{let{compressToolResult:i}=It();return i(s,r)}catch{return s}return s}function $h(t){try{let{getActiveModel:e}=Ge(),s=e(),n=s?`${s.provider}:${s.id}`:"default";if(Xr.has(n))return Xr.get(n);let o=ch(t);return Xr.set(n,o),o}catch{return ch(t)}}function kx(){Xr.clear()}var go={hash:null,ts:0},vx=3e4;async function wh(){if(go.hash&&Date.now()-go.ts<vx)return go.hash;try{let t=require("fs").promises,e=require("path"),s=[e.join(process.cwd(),"package.json"),e.join(process.cwd(),".git","HEAD"),e.join(process.cwd(),"README.md"),e.join(process.cwd(),"NEX.md")],o=(await Promise.allSettled(s.map(i=>t.stat(i).then(a=>`${i}:${a.mtimeMs}`)))).filter(i=>i.status==="fulfilled").map(i=>i.value);try{let{getMemoryContextHash:i}=Js(),a=i();a&&o.push(`memory:${a}`)}catch{}try{let i=e.join(process.cwd(),".nex","brain");if(Ac.existsSync(i)){let a=await t.stat(i);o.push(`brain:${a.mtimeMs}`)}}catch{}let r=o.join("|");return go={hash:r,ts:Date.now()},r}catch{return`fallback:${Date.now()}`}}function xc(){mo=null,_c=null,go={hash:null,ts:0},bs=null}var Sx=new Set(["spawn_agents"]),uc=5,dc=3,Gr=2,dh=6e4,fc=12e4,Ex=process.env.NEX_STALE_AUTO_SWITCH!=="0";function Tx(t){try{let e=require("fs"),s=require("path"),n=s.join(process.cwd(),".nex","plans");e.existsSync(n)||e.mkdirSync(n,{recursive:!0});let o=s.join(n,"current-plan.md");e.writeFileSync(o,t,"utf-8")}catch{}}U_(t=>{B_(t,"allow"),W_(),console.log(`${p.green} \u2713 ${t}: always allow${p.reset}`)});async function Rx(t){let e=t.function.name,s=x_(t.function.arguments),n=t.id||`cli-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!s){let u=Qe().find(f=>f.function.name===e),d=u?JSON.stringify(u.function.parameters,null,2):"unknown";return F(`${p.yellow} \u26A0 ${e}: malformed arguments, sending schema hint${p.reset}`),{callId:n,fnName:e,args:null,canExecute:!1,errorResult:{role:"tool",content:`ERROR: Malformed tool arguments. Could not parse your arguments as JSON.
678
711
  Raw input: ${typeof t.function.arguments=="string"?t.function.arguments.substring(0,200):"N/A"}
679
712
 
680
713
  Expected JSON schema for "${e}":
681
714
  ${d}
682
715
 
683
- Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:n}}}let o=D_(e,s);if(!o.valid){D(`${p.yellow} \u26A0 ${e}: ${o.error.split(`
684
- `)[0]}${p.reset}`);let l=(th.get(e)||0)+1;th.set(e,l);let u=l>=2?`${o.error}
716
+ Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:n}}}let o=ox(e,s);if(!o.valid){F(`${p.yellow} \u26A0 ${e}: ${o.error.split(`
717
+ `)[0]}${p.reset}`);let l=(ph.get(e)||0)+1;ph.set(e,l);let u=l>=2?`${o.error}
685
718
 
686
- [SYSTEM: This is argument error #${l} for "${e}". Study the "Expected parameters" schema above and correct your call \u2014 do not repeat the same mistake.]`:o.error;return{callId:n,fnName:e,args:s,canExecute:!1,errorResult:{role:"tool",content:u,tool_call_id:n}}}let r=o.corrected||s;if(o.corrected){let l=Object.keys(s),u=Object.keys(o.corrected),d=l.filter(f=>!u.includes(f));d.length&&console.log(`${p.dim} \u2713 ${e}: corrected args (${d.join(", ")})${p.reset}`)}if(wo()&&!rh.has(e))return console.log(`${p.yellow} \u2717 ${e}: blocked in plan mode${p.reset}`),{callId:n,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`PLAN MODE: '${e}' is blocked. Only read-only tools are allowed. Present your plan as text output instead of making changes.`,tool_call_id:n}};let i=new Set(["read_file","list_directory","search_files","glob","grep","git_status","git_diff","git_log","git_show","ssh_exec"]),a=new Set(["read_file","list_directory","glob","grep","bash","git_status","git_diff","git_log","ssh_exec"]);if($e&&De==="plan"&&!i.has(e))return nn++,D(`${p.yellow} \u2717 ${e}: blocked in plan phase (read-only, block #${nn})${p.reset}`),{callId:n,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`PLAN PHASE: '${e}' is blocked. Analyze the codebase using read-only tools, then present your findings as text. Edits happen in the next phase.`,tool_call_id:n}};if($e&&De==="verify"&&!a.has(e))return D(`${p.yellow} \u2717 ${e}: blocked in verify phase (read + bash only)${p.reset}`),{callId:n,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`VERIFY PHASE: '${e}' is blocked. Use read_file and bash (for tests/linters) to verify changes. Report PASS or FAIL.`,tool_call_id:n}};let c=b_(e);if(c==="deny")return console.log(`${p.red} \u2717 ${e}: denied by permissions${p.reset}`),{callId:n,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`DENIED: Tool '${e}' is blocked by permissions`,tool_call_id:n}};if(c==="ask"){let l=` Allow ${e}?`;return e==="bash"&&r.command&&(l=` bash: \`${r.command.substring(0,80)}${r.command.length>80?"\u2026":""}\`?`),await oh(l,{toolName:e})?{callId:n,fnName:e,args:r,canExecute:!0,confirmedByUser:!0,errorResult:null}:{callId:n,fnName:e,args:r,canExecute:!1,confirmedByUser:!1,errorResult:{role:"tool",content:`CANCELLED: User declined ${e}`,tool_call_id:n}}}return{callId:n,fnName:e,args:r,canExecute:!0,confirmedByUser:!0,errorResult:null}}async function lx(t,e,s={}){let n=await I_(t,e);if(n!==null)return n;let o=await N_(t,e);return o!==null?o:o_(t,e,s)}function ux(t,e){switch(t){case"read_file":case"write_file":case"edit_file":case"patch_file":case"list_directory":return e.path||"";case"bash":return(e.command||"").substring(0,60);case"grep":case"search_files":case"glob":return e.pattern||"";case"web_fetch":return(e.url||"").substring(0,50);case"web_search":return(e.query||"").substring(0,40);default:return""}}async function tc(t,e=!1){e||console.log(e_(t.fnName,t.args));let s=Gp("pre-tool",{tool_name:t.fnName});if(!e&&s.length>0)for(let h of s)h.success?console.log(`${p.dim} [hook pre-tool] ${h.command} \u2192 ${h.output||"ok"}${p.reset}`):console.log(`${p.yellow} [hook pre-tool] ${h.command} \u2192 ERROR: ${h.error}${p.reset}`);qt?.onToolStart&&qt.onToolStart(t.fnName,t.args);let n=await lx(t.fnName,t.args,{silent:!0,autoConfirm:t.confirmedByUser===!0}),o=String(n??""),r=o.length>5e4?o.substring(0,5e4)+`
687
- ...(truncated ${o.length-5e4} chars)`:o,i=r.split(`
688
- `)[0],a=i.startsWith("ERROR")||i.includes("CANCELLED")||i.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(r)&&/✗ Agent/.test(r),c=sh(t.fnName,t.args,r,a);e||console.log(c),qt?.onToolEnd&&qt.onToolEnd(t.fnName,c,!a);let l=Gp("post-tool",{tool_name:t.fnName});if(!e&&l.length>0)for(let h of l)h.success?console.log(`${p.dim} [hook post-tool] ${h.command} \u2192 ${h.output||"ok"}${p.reset}`):console.log(`${p.yellow} [hook post-tool] ${h.command} \u2192 ERROR: ${h.error}${p.reset}`);let d=nx(r,t.fnName);if(t.fnName==="bash"&&t.args?.command){let h=t.args.command.trim();!/cat\s*>|<</.test(h)&&/\bcat\s+\S/.test(h)?d+=`
689
- 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(h)&&!/npm|yarn|pnpm|make|git\b/.test(h)?d+=`
690
- HINT: use list_directory instead of bash ls \u2014 it is the preferred tool for listing directory contents.`:/\bfind\s+\S/.test(h)&&!/git\b|npm\b|-exec\b|-delete\b|-print0\b/.test(h)&&(d+=`
691
- 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:d,tool_call_id:t.callId},summary:c}}var dx=[{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 nc(t){for(let{re:e,label:s}of dx){let n=t.match(e);if(n){let o=(n[1]||"").trim();return o?`${s}: ${o}`:s}}return null}async function fx(t,e=!1,s={}){let n=new Array(t.length),o=[],r=[],i=null;if(e&&!s.skipSpinner){let c=t.filter(l=>l.canExecute);if(c.length>0){let l;if(c.length===1){let u=c[0],d=ux(u.fnName,u.args);l=`\u23FA ${u.fnName}${d?`(${d})`:""}`}else{let u=c.map(d=>d.fnName).join(", ");l=`\u23FA ${c.length} tools: ${u.length>60?u.substring(0,57)+"\u2026":u}`}i=new hs(l),i.start()}}async function a(){if(r.length!==0){if(r.length===1){let c=r[0],{msg:l,summary:u}=await tc(t[c],e);n[c]=l,o.push(u)}else{let c=r.map(u=>tc(t[u],e)),l=await Promise.all(c);for(let u=0;u<r.length;u++)n[r[u]]=l[u].msg,o.push(l[u].summary)}r=[]}}for(let c=0;c<t.length;c++){let l=t[c];if(!l.canExecute){await a(),n[c]=l.errorResult,o.push(sh(l.fnName,l.args||{},l.errorResult.content,!0));continue}if(rx.has(l.fnName)){await a(),l.fnName==="spawn_agents"&&i&&(i.stop(),i=null);let{msg:u,summary:d}=await tc(l,e);n[c]=u,o.push(d)}else r.push(c)}if(await a(),i&&i.stop(),e&&o.length>0&&!s.skipSummaries)for(let c of o)console.log(c);return{results:n,summaries:o}}var q=[],Qp=300,lh=900*1e3;function An(t,e){let s=t.get(e);return s?Date.now()-s.ts>lh?(t.delete(e),0):s.count:0}function On(t,e){let s=t.get(e),n=s&&Date.now()-s.ts<=lh?s.count+1:1;return t.set(e,{count:n,ts:Date.now()}),n}function eh(t,e,s){t.set(e,{count:s,ts:Date.now()})}var yc=new Map,$c=new Map,bo=new Map,wc=new Map,_o=new Map,In=new Map,tn=new Map,bc=new Map,Nn=new Map,jn=new Map,th=new Map,ni=new Map,si=new Map,wt=0,mo=0,Kr=0,lc="",zr=0,ht=!1,Hr=0,Xr=0,Mn=-1,uc=!1,Vr=0,Jr=!1,jt=0,Tt=!1,Kt=0,Rt=0,Ye=!1,it="",go=0,en=0,Zr="",Ln=0,Pn=0,Qr="",bt=!1,dc=!1,xo=new Map,ko=new Set,yo=null,sc=!1,uo=0,nh=!1,De="plan",oi=0,$e=!1,nn=0,zt=null,fc=null,pc=null,$o=0,ys=null;function ps(t,e){t===lc?(zr++,Xo().DEBUG&&process.stdout.write(`\x1B[1A\x1B[2K${e} \u26A0 ${t} (\xD7${zr})${p.reset}
692
- `)):(lc=t,zr=1,D(`${e} \u26A0 ${t}${p.reset}`))}var ei=[];function px(t){ei.push(t.trim())}function hx(){return ei.length===0?null:ei.splice(0,ei.length).join(`
693
- `)}function fo(t,e,s,n){if(!$e)return null;let o=De;De=t,oi=0,zt=oc(t,ys),jt=0,Tt=!1,Kt=0,Rt=0,In.clear(),tn.clear(),jn.clear(),ni.clear(),si.clear(),$c.clear(),bo.clear(),wc.clear(),_o.clear(),yc.clear(),bc.clear();let r;if(t==="implement")fc=e?.slice(0,800)||"",r=`[PHASE: IMPLEMENTATION] Analysis complete. Based on the analysis:
694
- ${fc}
719
+ [SYSTEM: This is argument error #${l} for "${e}". Study the "Expected parameters" schema above and correct your call \u2014 do not repeat the same mistake.]`:o.error;return{callId:n,fnName:e,args:s,canExecute:!1,errorResult:{role:"tool",content:u,tool_call_id:n}}}let r=o.corrected||s;if(o.corrected){let l=Object.keys(s),u=Object.keys(o.corrected),d=l.filter(f=>!u.includes(f));d.length&&console.log(`${p.dim} \u2713 ${e}: corrected args (${d.join(", ")})${p.reset}`)}if(_o()&&!gh.has(e))return console.log(`${p.yellow} \u2717 ${e}: blocked in plan mode${p.reset}`),{callId:n,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`PLAN MODE: '${e}' is blocked. Only read-only tools are allowed. Present your plan as text output instead of making changes.`,tool_call_id:n}};let i=new Set(["read_file","list_directory","search_files","glob","grep","git_status","git_diff","git_log","git_show","ssh_exec"]),a=new Set(["read_file","list_directory","glob","grep","bash","git_status","git_diff","git_log","ssh_exec"]);if(we&&Pe==="plan"&&!i.has(e)&&!e.startsWith("skill_"))return rn++,F(`${p.yellow} \u2717 ${e}: blocked in plan phase (read-only, block #${rn})${p.reset}`),{callId:n,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`PLAN PHASE: '${e}' is blocked. Analyze the codebase using read-only tools, then present your findings as text. Edits happen in the next phase.`,tool_call_id:n}};if(we&&Pe==="verify"&&!a.has(e)&&!e.startsWith("skill_"))return F(`${p.yellow} \u2717 ${e}: blocked in verify phase (read + bash only)${p.reset}`),{callId:n,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`VERIFY PHASE: '${e}' is blocked. Use read_file and bash (for tests/linters) to verify changes. Report PASS or FAIL.`,tool_call_id:n}};let c=F_(e);if(c==="deny")return console.log(`${p.red} \u2717 ${e}: denied by permissions${p.reset}`),{callId:n,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`DENIED: Tool '${e}' is blocked by permissions`,tool_call_id:n}};if(c==="ask"){let l=` Allow ${e}?`;return e==="bash"&&r.command&&(l=` bash: \`${r.command.substring(0,80)}${r.command.length>80?"\u2026":""}\`?`),await mh(l,{toolName:e})?{callId:n,fnName:e,args:r,canExecute:!0,confirmedByUser:!0,errorResult:null}:{callId:n,fnName:e,args:r,canExecute:!1,confirmedByUser:!1,errorResult:{role:"tool",content:`CANCELLED: User declined ${e}`,tool_call_id:n}}}return{callId:n,fnName:e,args:r,canExecute:!0,confirmedByUser:!0,errorResult:null}}async function Cx(t,e,s={}){let n=await nx(t,e);if(n!==null)return n;let o=await Z_(t,e);return o!==null?o:k_(t,e,s)}function Ax(t,e){switch(t){case"read_file":case"write_file":case"edit_file":case"patch_file":case"list_directory":return e.path||"";case"bash":return(e.command||"").substring(0,60);case"grep":case"search_files":case"glob":return e.pattern||"";case"web_fetch":return(e.url||"").substring(0,50);case"web_search":return(e.query||"").substring(0,40);default:return""}}async function pc(t,e=!1){e||console.log($_(t.fnName,t.args));let s=oh("pre-tool",{tool_name:t.fnName}),n=s.results;if(s.blocked){let m=`BLOCKED: pre-tool hook rejected ${t.fnName}: ${s.blockReason}`;e||console.log(`${p.yellow} [hook pre-tool] BLOCKED: ${s.blockReason}${p.reset}`);let b=yc(t.fnName,t.args,m,!0);return e||console.log(b),{msg:{role:"tool",content:m,tool_call_id:t.callId},summary:b}}if(!e&&n.length>0)for(let m of n)m.success?console.log(`${p.dim} [hook pre-tool] ${m.command} \u2192 ${m.output||"ok"}${p.reset}`):console.log(`${p.yellow} [hook pre-tool] ${m.command} \u2192 ERROR: ${m.error}${p.reset}`);Ft?.onToolStart&&Ft.onToolStart(t.fnName,t.args);let o=await Cx(t.fnName,t.args,{silent:!0,autoConfirm:t.confirmedByUser===!0}),r=String(o??""),i=r.length>5e4?r.substring(0,5e4)+`
720
+ ...(truncated ${r.length-5e4} chars)`:r,a=i.split(`
721
+ `)[0],c=a.startsWith("ERROR")||a.includes("CANCELLED")||a.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(i)&&/✗ Agent/.test(i),l=yc(t.fnName,t.args,i,c);e||console.log(l),Ft?.onToolEnd&&Ft.onToolEnd(t.fnName,l,!c);let d=oh("post-tool",{tool_name:t.fnName}).results;if(!e&&d.length>0)for(let m of d)m.success?console.log(`${p.dim} [hook post-tool] ${m.command} \u2192 ${m.output||"ok"}${p.reset}`):console.log(`${p.yellow} [hook post-tool] ${m.command} \u2192 ERROR: ${m.error}${p.reset}`);let h=xx(i,t.fnName);if(t.fnName==="bash"&&t.args?.command){let m=t.args.command.trim();!/cat\s*>|<</.test(m)&&/\bcat\s+\S/.test(m)?h+=`
722
+ 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(m)&&!/npm|yarn|pnpm|make|git\b/.test(m)?h+=`
723
+ HINT: use list_directory instead of bash ls \u2014 it is the preferred tool for listing directory contents.`:/\bfind\s+\S/.test(m)&&!/git\b|npm\b|-exec\b|-delete\b|-print0\b/.test(m)&&(h+=`
724
+ 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:h,tool_call_id:t.callId},summary:l}}var Ox=[{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 hc(t){for(let{re:e,label:s}of Ox){let n=t.match(e);if(n){let o=(n[1]||"").trim();return o?`${s}: ${o}`:s}}return null}async function Nx(t,e=!1,s={}){let n=new Array(t.length),o=[],r=[],i=null;if(e&&!s.skipSpinner){let c=t.filter(l=>l.canExecute);if(c.length>0){let l;if(c.length===1){let u=c[0],d=Ax(u.fnName,u.args);l=`\u23FA ${u.fnName}${d?`(${d})`:""}`}else{let u=c.map(d=>d.fnName).join(", ");l=`\u23FA ${c.length} tools: ${u.length>60?u.substring(0,57)+"\u2026":u}`}i=new $s(l),i.start()}}async function a(){if(r.length!==0){if(r.length===1){let c=r[0],{msg:l,summary:u}=await pc(t[c],e);n[c]=l,o.push(u)}else{let c=r.map(u=>pc(t[u],e)),l=await Promise.all(c);for(let u=0;u<r.length;u++)n[r[u]]=l[u].msg,o.push(l[u].summary)}r=[]}}for(let c=0;c<t.length;c++){let l=t[c];if(!l.canExecute){await a(),n[c]=l.errorResult,o.push(yc(l.fnName,l.args||{},l.errorResult.content,!0));continue}if(Sx.has(l.fnName)){await a(),l.fnName==="spawn_agents"&&i&&(i.stop(),i=null);let{msg:u,summary:d}=await pc(l,e);n[c]=u,o.push(d)}else r.push(c)}if(await a(),i&&i.stop(),e&&o.length>0&&!s.skipSummaries)for(let c of o)console.log(c);return{results:n,summaries:o}}var q=[],fh=300,bh=900*1e3;function Dt(t,e){let s=t.get(e);return s?Date.now()-s.ts>bh?(t.delete(e),0):s.count:0}function Ln(t,e){let s=t.get(e),n=s&&Date.now()-s.ts<=bh?s.count+1:1;return t.set(e,{count:n,ts:Date.now()}),n}function mc(t,e,s){t.set(e,{count:s,ts:Date.now()})}var Nc=new Map,Mc=new Map,xo=new Map,Lc=new Map,ko=new Map,on=new Map,zt=new Map,Pc=new Map,Pn=new Map,qn=new Map,ph=new Map,ri=new Map,ii=new Map,_t=0,yo=0,Vr=0,kc="",Jr=0,mt=!1,Kr=0,Zr=0,In=-1,vc=!1,Qr=0,ei=!1,qt=0,Rt=!1,Xt=0,Ct=0,ze=!1,at="",$o=0,sn=0,ti="",jn=0,Dn=0,ni="",xt=!1,Sc=!1,vo=new Map,So=new Set,wo=null,gc=!1,po=0,hh=!1,Pe="plan",ai=0,we=!1,rn=0,Vt=null,Ec=null,Tc=null,bo=0,_s=null;function ys(t,e){t===kc?(Jr++,Zo().DEBUG&&process.stdout.write(`\x1B[1A\x1B[2K${e} \u26A0 ${t} (\xD7${Jr})${p.reset}
725
+ `)):(kc=t,Jr=1,F(`${e} \u26A0 ${t}${p.reset}`))}var si=[];function Mx(t){si.push(t.trim())}function Lx(){return si.length===0?null:si.splice(0,si.length).join(`
726
+ `)}function ho(t,e,s,n){if(!we)return null;let o=Pe;Pe=t,ai=0,Vt=$c(t,_s),qt=0,Rt=!1,Xt=0,Ct=0,on.clear(),zt.clear(),qn.clear(),ri.clear(),ii.clear(),Mc.clear(),xo.clear(),Lc.clear(),ko.clear(),Nc.clear(),Pc.clear();let r;if(t==="implement")Ec=e?.slice(0,800)||"",r=`[PHASE: IMPLEMENTATION] Analysis complete. Based on the analysis:
727
+ ${Ec}
695
728
 
696
- Now implement the fix/changes. Do not investigate further \u2014 edit files directly.`;else if(t==="verify"){pc=e?.slice(0,500)||"";let i=s?[...s].join(", "):"none";r=`[PHASE: VERIFICATION] Implementation complete. Verify the changes:
729
+ Now implement the fix/changes. Do not investigate further \u2014 edit files directly.`;else if(t==="verify"){Tc=e?.slice(0,500)||"";let i=s?[...s].join(", "):"none";r=`[PHASE: VERIFICATION] Implementation complete. Verify the changes:
697
730
  1. Read each modified file and confirm changes are correct
698
731
  2. If test command exists (npm test / pytest): run it
699
732
  3. If linter exists: run it
@@ -701,18 +734,18 @@ Now implement the fix/changes. Do not investigate further \u2014 edit files dire
701
734
  Report PASS (all good) or FAIL (list specific issues).
702
735
 
703
736
  Files modified: ${i}
704
- Summary: ${pc}`}return D(`${p.cyan} \u21B3 Phase transition: ${o} \u2192 ${t} (model: ${zt||"default"})${p.reset}`),r?{role:"user",content:r}:null}function mx(){let t=process.env.NEX_LANGUAGE,e=process.env.NEX_CODE_LANGUAGE,s=process.env.NEX_COMMIT_LANGUAGE,n=!t||t==="auto"?null:t,o=[`# Language Rules (CRITICAL \u2014 enforce strictly)
737
+ Summary: ${Tc}`}return F(`${p.cyan} \u21B3 Phase transition: ${o} \u2192 ${t} (model: ${Vt||"default"})${p.reset}`),r?{role:"user",content:r}:null}function Px(){let t=process.env.NEX_LANGUAGE,e=process.env.NEX_CODE_LANGUAGE,s=process.env.NEX_COMMIT_LANGUAGE,n=!t||t==="auto"?null:t,o=[`# Language Rules (CRITICAL \u2014 enforce strictly)
705
738
  `];n?o.push(`RESPONSE LANGUAGE: You MUST always respond in ${n}. This overrides any language defaults from your training. Never output Chinese, Japanese, or any other language in your responses \u2014 even when summarizing or thinking. ${n} only.`):o.push("RESPONSE LANGUAGE: Always respond in the same language as the user's message. If the user writes in German, respond in German; if in English, respond in English; etc."),o.push("CODE EXAMPLES: Always show actual, working code examples \u2014 never pseudocode or placeholder snippets."),o.push("COMPLETENESS RULES:"),o.push(" \u2022 ALWAYS show actual code when explaining implementations \u2014 never describe without showing"),o.push(" \u2022 FILE CREATION TASKS (Makefile, Dockerfile, config files): paste the COMPLETE file content in a fenced code block in your TEXT RESPONSE \u2014 writing a file with a tool does NOT make it visible. The fenced code block MUST appear in your response, not just via write_file."),o.push(" \u2022 Include complete examples with full context (imports, function signatures, error handling)"),o.push(' \u2022 Show alternative approaches when relevant (e.g., "Alternative: use util.promisify instead")'),o.push(" \u2022 Include edge cases in explanations (empty input, null values, boundary conditions)"),o.push(" \u2022 Provide platform-specific guidance when commands differ by OS (Linux/macOS/Windows)"),o.push(' \u2022 For Makefiles, paste the COMPLETE Makefile code DIRECTLY in your text response \u2014 every target, recipe, dependency, and .PHONY line. Writing the Makefile with a tool does NOT count as showing it. The Makefile MUST appear verbatim in your chat text as a code block, even if you also wrote it to a file. Never describe structure without showing the actual code. CRITICAL: use EXACTLY the command specified \u2014 if the task says "runs jest", write "jest" in the recipe, NEVER "npm test". npm test is NOT jest. Recipes need real TAB indentation. ONE .PHONY line listing ALL phony targets.'),o.push(" \u2022 For dataclasses, paste the COMPLETE dataclass code DIRECTLY in your text response \u2014 @dataclass decorator, all fields with types and defaults, full __post_init__ validation. Writing the file with a tool does NOT count as showing the code. The code MUST appear verbatim in your chat text, even if you also wrote it to a file."),o.push(" \u2022 For cron expressions, re-read the exact time boundaries in the task before writing. If asked for 8-18h, the range is 8,9,...,18 \u2014 write exactly what was asked, not an approximation."),o.push(' \u2022 When a task explicitly specifies a tool (e.g., "use tsc"), NEVER mention alternatives (e.g., "swc build") \u2014 use exactly what was requested.'),o.push(' \u2022 In Makefile prerequisites, NEVER use shell glob patterns like src/**/*.ts \u2014 make does not expand these natively. Keep prerequisite lists explicit or omit them. When a Makefile target says "runs jest", call jest directly in the recipe (not npm test).'),o.push(" \u2022 For bash in-place text replacements with backups: use ONLY ONE backup method \u2014 either sed -i.bak (let sed create the backup) OR cp file file.bak followed by sed -i (no extension). Never use both cp and sed -i.bak together \u2014 that produces redundant double backups (file.bak and file.bak.bak)."),o.push(" \u2022 For iterative array-flattening (flattenDeep): use push() and reverse() at the end \u2014 NEVER unshift(). unshift is O(n) per call making the whole function O(n^2). The iterative version MUST use a loop (while/for) and an explicit stack array \u2014 zero recursive calls. If a function calls itself, it is recursive regardless of its name. Never label a recursive function as iterative."),o.push(" \u2022 FORBIDDEN: when refactoring callbacks to async/await, NEVER write try { ... } catch(e) { throw e } \u2014 this is an explicit anti-pattern. WRONG: async function f() { try { const d = await readFile(..); await writeFile(.., d); } catch(e) { throw e; } } \u2014 RIGHT: async function f() { const d = await readFile(..); await writeFile(.., d); } \u2014 omit the try-catch entirely, let rejections propagate."),o.push(' \u2022 Docker HEALTHCHECK: always include --start-period=30s (or appropriate startup time) so the container has time to initialise before failures are counted. Also note that curl may not be available in minimal Node.js images \u2014 offer wget or "node -e" as alternatives.'),o.push(' \u2022 When fixing a bash word-splitting bug like "for f in $(ls *.txt)": replace the entire $(ls *.txt) with a bare glob directly \u2014 "for f in *.txt". The fix is eliminating the ls command and $() subshell entirely. Emphasise this in the explanation: the glob in the for loop prevents word splitting because the shell expands the glob into separate words before the loop \u2014 there is no subshell output to split. CRITICAL: NEVER suggest "ls -N" or any ls variant as a fix \u2014 ls -N outputs filenames one per line, but word splitting still occurs on each line when used in a subshell expansion. The only correct fix is the bare glob pattern.');let r=e||"English";o.push(`CODE LANGUAGE: Write all code comments, docstrings, variable descriptions, and inline documentation in ${r}.`);let i=s||"English";return o.push(`COMMIT MESSAGES: Write all git commit messages in ${i}.`),n&&o.push(`
706
739
  This is a hard requirement. Always respond in ${n}. Do NOT switch to any other language \u2014 even if the user writes to you in German, French, or any other language, your reply MUST be in ${n}.`),o.join(`
707
740
  `)+`
708
741
 
709
- `}function gx(){if(gs!==null)return gs;try{let e=F_().flatMap(o=>o.models.map(r=>({spec:`${o.name}:${r.id}`,tier:q_(r.id,o.name),name:r.name})));if(e.length<2)return gs="","";let s={full:"complex tasks (refactor, implement, generate)",standard:"regular tasks (edit, fix, analyze)",essential:"simple tasks (read, search, list)"},n=`
742
+ `}function Ix(){if(bs!==null)return bs;try{let e=ix().flatMap(o=>o.models.map(r=>({spec:`${o.name}:${r.id}`,tier:rx(r.id,o.name),name:r.name})));if(e.length<2)return bs="","";let s={full:"complex tasks (refactor, implement, generate)",standard:"regular tasks (edit, fix, analyze)",essential:"simple tasks (read, search, list)"},n=`
710
743
  # Sub-Agent Model Routing
711
744
 
712
745
  `;n+='Sub-agents auto-select models by task complexity. Override with `model: "provider:model"` in agent definition.\n\n',n+=`| Model | Tier | Auto-assigned for |
713
746
  |---|---|---|
714
747
  `;for(let o of e)n+=`| ${o.spec} | ${o.tier} | ${s[o.tier]||o.tier} |
715
- `;return gs=n,n}catch(t){return process.env.NEX_DEBUG&&console.error("[agent] model routing guide failed:",t.message),gs="",""}}async function hc(){let t=await ch()+":"+Dt();if(po!==null&&t===ac)return po;let e=await r_(process.cwd()),s=g_(),n=L_(),o=wo()?S_():"",r=mx(),i=y_(),a=W_(Dt());return po=`${a?`## Model Briefing
748
+ `;return bs=n,n}catch(t){return process.env.NEX_DEBUG&&console.error("[agent] model routing guide failed:",t.message),bs="",""}}var Rc="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->";function jx(t){let e=t.indexOf(Rc);return e===-1?{dynamic:t,static:""}:{dynamic:t.slice(0,e).trimEnd(),static:t.slice(e+Rc.length).trimStart()}}async function Cc(){let t=await wh()+":"+At();if(mo!==null&&t===_c)return mo;let e=await v_(process.cwd()),s=I_(),n=ex(),o=_o()?Y_():"",r=Px(),i=j_(),a=cx(At());return mo=`${a?`## Model Briefing
716
749
  ${a}
717
750
 
718
751
  ---
@@ -733,18 +766,19 @@ ${o}
733
766
  ${r?`${r}
734
767
  `:""}${i?`${i}
735
768
 
736
- `:""}${v_()?`# YOLO Mode \u2014 Auto-Execute
769
+ `:""}${H_()?`# YOLO Mode \u2014 Auto-Execute
737
770
 
738
771
  You are in YOLO mode (autoConfirm=true). All tool calls are pre-approved.
739
772
  - NEVER ask for confirmation \u2014 just execute tasks directly
740
773
  - NEVER end responses with questions like "Soll ich...?", "M\xF6chtest du...?", "Shall I...?"
741
774
  - When you have enough information, implement the fix immediately \u2014 do not propose or ask
742
775
  - If something is ambiguous, make a reasonable assumption and state it, then proceed
743
- - OVERRIDE "simple questions": If the user pastes any server error or Jarvis message, SSH investigate FIRST \u2014 NEVER answer from training knowledge alone
776
+ - OVERRIDE "simple questions": If the user pastes any server error message, SSH investigate FIRST \u2014 NEVER answer from training knowledge alone
744
777
  - **Inline code tasks**: If the prompt contains a code snippet and asks you to modify/add to/improve it, answer DIRECTLY with the improved code \u2014 do NOT search for files. The snippet is self-contained
745
778
  - After identifying root cause via SSH: IMMEDIATELY fix it (edit file + restart service). Do NOT write "Empfohlene L\xF6sungen" or ask "M\xF6chten Sie...?" \u2014 just execute the fix now.
746
779
 
747
780
  `:""}
781
+ <!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->
748
782
 
749
783
  # Plan Mode
750
784
 
@@ -958,7 +992,7 @@ You have a soft budget of ~30 tool calls per task. Sessions with >40 tool calls
958
992
  - Instead: use bash with inline node -e '...' for quick one-off checks.
959
993
  - If the test is worth keeping, write it to tests/ with a proper name.
960
994
  - Write-then-delete patterns waste 3 tool calls and leave orphans if the session is interrupted.
961
- ${gx()}
995
+ ${Ix()}
962
996
 
963
997
  # Edit Protocol (Mandatory \u2014 Follow These Steps Exactly)
964
998
 
@@ -1149,67 +1183,70 @@ class ErrorBoundary extends React.Component {
1149
1183
  - Use migrations for schema changes, never manual ALTER TABLE
1150
1184
  - Add database-level constraints (unique, foreign key, check) not just app-level
1151
1185
 
1152
- `,ac=t,po}function uh(){yc.clear(),$c.clear(),bo.clear(),wc.clear(),_o.clear(),In.clear(),tn.clear(),bc.clear(),Nn.clear(),jn.clear(),ni.clear(),si.clear(),wt=0,mo=0,Kr=0,ht=!1,Xr=0,Mn=-1,uc=!1,Vr=0,Jr=!1,jt=0,Tt=!1,Kt=0,Rt=0,Ye=!1,it="",go=0,Zr="",Ln=0,Qr="",Pn=0,bt=!1,dc=!1,De="plan",oi=0,$e=!1,zt=null,fc=null,pc=null,$o=0,nn=0,ys=null,xo.clear(),ko.clear(),lc="",zr=0}function yx(){q=[],yo=null,uh()}function $x(){q.length>Qp&&q.splice(0,q.length-Qp)}function wx(){return q.length}function bx(){return q}function _x(t){q=t}async function xx(){let{execFile:t}=require("child_process"),e=require("fs"),s=process.cwd(),n=(d,f)=>new Promise(h=>{t(d,f,{cwd:s,timeout:3e3},(m,g)=>{h(m?"":(g||"").trim())})}),[o]=await Promise.all([n("find",[".","-type","f","-not","-path","*/node_modules/*","-not","-path","*/.git/*","-not","-path","*/dist/*","-not","-path","*/.next/*","-not","-path","*/build/*","-not","-path","*/__pycache__/*","-not","-path","*/vendor/*"])]),r=new Set(["js","ts","jsx","tsx","py","go","rs","rb","java","cpp","c","cs"]),i=(o?o.split(`
1153
- `):[]).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 l=` \u{1F4C1} ${Object.entries(a).sort((d,f)=>f[1]-d[1]).slice(0,4).map(([d,f])=>`${f} .${d}`).join(" \xB7 ")}`,u=gc.join(s,"package.json");if(e.existsSync(u))try{let d=JSON.parse(e.readFileSync(u,"utf-8")),f=Object.keys({...d.dependencies||{},...d.devDependencies||{}});if(f.length>0){let h=f.slice(0,5).join(" \xB7 "),m=f.length>5?` +${f.length-5}`:"";l+=`
1154
- \u{1F4E6} ${h}${m}`}}catch{}return l}function kx(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 We(t,e,s,n,o,{suppressHint:r=!1}={}){if(t<1)return;let i=[...e.values()].reduce((l,u)=>l+u,0),a=`\u2500\u2500 ${t} ${t===1?"step":"steps"} \xB7 ${i} ${i===1?"tool":"tools"}`,c=0;if(o){let l=Date.now()-o;c=Math.round(l/1e3),a+=c>=60?` \xB7 ${Math.floor(c/60)}m ${c%60}s`:` \xB7 ${c}s`}if(s.size>0&&(a+=` \xB7 ${s.size} ${s.size===1?"file":"files"} modified`),a+=" \u2500\u2500",console.log(`
1155
- ${p.dim} ${a}${p.reset}`),c>=30&&process.stdout.isTTY){let l=s.size>0?`Done \u2014 ${s.size} ${s.size===1?"file":"files"} modified in ${c}s`:`Done \u2014 ${t} ${t===1?"step":"steps"} in ${c}s`;kx(l)}if(ko.size>0&&xo.size>0)for(let l of ko){let u=xo.get(l);u&&console.log(`${p.dim} \u2714 task #${l} auto-matched: ${u.slice(0,60)}${p.reset}`)}s.size>0?console.log(`${p.dim} \u{1F4A1} /diff \xB7 /commit \xB7 /undo${p.reset}`):!r&&n.size>=5&&s.size===0&&t>=3?console.log(`${p.dim} \u{1F4A1} Found issues? Say "fix 1" or "apply all fixes"${p.reset}`):n.size>0&&t>=2&&console.log(`${p.dim} \u{1F4A1} /save \xB7 /clear${p.reset}`)}async function vx(){if(!process.stdout.isTTY)return{action:"quit"};let t=ms(),e=Dt(),s=ti.fast?.[t],n=ti.strong?.[t],o=s&&s!==e,r=n&&n!==e&&n!==s,i=[];i.push({key:"r",label:`Retry with current model ${p.dim}(${e})${p.reset}`}),o&&i.push({key:"f",label:`Switch to ${p.bold}${s}${p.reset} ${p.dim}\u2014 fast, low latency${p.reset}`,model:s}),r&&i.push({key:"s",label:`Switch to ${p.bold}${n}${p.reset} ${p.dim}\u2014 reliable tool-calling, medium speed${p.reset}`,model:n}),i.push({key:"q",label:`${p.dim}Quit${p.reset}`}),console.log(),console.log(`${p.yellow} Stream stale \u2014 all retries exhausted.${p.reset} What would you like to do?`);for(let a of i)console.log(` ${p.cyan}[${a.key}]${p.reset} ${a.label}`);return process.stdout.write(` ${p.yellow}> ${p.reset}`),new Promise(a=>{let c=process.stdin,l=c.isRaw;c.setRawMode(!0),c.resume(),c.setEncoding("utf8");let u=!1,d=f=>{if(u)return;u=!0,c.removeListener("data",d),c.setRawMode(l||!1),c.pause();let h=f.toLowerCase().trim();if(process.stdout.write(`${h}
1156
- `),f==="")return a({action:"quit"});let m=i.find(g=>g.key===h);!m||m.key==="q"||!m.model&&m.key!=="r"?a({action:"quit"}):m.key==="r"?a({action:"retry"}):a({action:"switch",model:m.model,provider:t})};c.on("data",d)})}var qt=null;async function Sx(t,e=null,s={}){let n=B_(Dt());Zp=n.staleWarn,ec=n.staleAbort,qt=e;let o=t;yo&&typeof t=="string"&&(o=`${yo}
1186
+ `,_c=t,mo}function _h(){Nc.clear(),Mc.clear(),xo.clear(),Lc.clear(),ko.clear(),on.clear(),zt.clear(),Pc.clear(),Pn.clear(),qn.clear(),ri.clear(),ii.clear(),_t=0,yo=0,Vr=0,mt=!1,Zr=0,In=-1,vc=!1,Qr=0,ei=!1,qt=0,Rt=!1,Xt=0,Ct=0,ze=!1,at="",$o=0,ti="",jn=0,ni="",Dn=0,xt=!1,Sc=!1,Pe="plan",ai=0,we=!1,Vt=null,Ec=null,Tc=null,bo=0,rn=0,_s=null,vo.clear(),So.clear(),kc="",Jr=0}function Dx(){q=[],wo=null,_h();try{let{resetCompactionFailures:t}=ba();t()}catch{}}function qx(){q.length>fh&&q.splice(0,q.length-fh)}function Fx(){return q.length}function Bx(){return q}function Wx(t){q=t}async function Ux(){let{execFile:t}=require("child_process"),e=require("fs"),s=process.cwd(),n=(d,f)=>new Promise(h=>{t(d,f,{cwd:s,timeout:3e3},(g,m)=>{h(g?"":(m||"").trim())})}),[o]=await Promise.all([n("find",[".","-type","f","-not","-path","*/node_modules/*","-not","-path","*/.git/*","-not","-path","*/dist/*","-not","-path","*/.next/*","-not","-path","*/build/*","-not","-path","*/__pycache__/*","-not","-path","*/vendor/*"])]),r=new Set(["js","ts","jsx","tsx","py","go","rs","rb","java","cpp","c","cs"]),i=(o?o.split(`
1187
+ `):[]).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 l=` \u{1F4C1} ${Object.entries(a).sort((d,f)=>f[1]-d[1]).slice(0,4).map(([d,f])=>`${f} .${d}`).join(" \xB7 ")}`,u=Oc.join(s,"package.json");if(e.existsSync(u))try{let d=JSON.parse(e.readFileSync(u,"utf-8")),f=Object.keys({...d.dependencies||{},...d.devDependencies||{}});if(f.length>0){let h=f.slice(0,5).join(" \xB7 "),g=f.length>5?` +${f.length-5}`:"";l+=`
1188
+ \u{1F4E6} ${h}${g}`}}catch{}return l}function Hx(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 Fe(t,e,s,n,o,{suppressHint:r=!1}={}){if(t<1)return;let i=[...e.values()].reduce((l,u)=>l+u,0),a=`\u2500\u2500 ${t} ${t===1?"step":"steps"} \xB7 ${i} ${i===1?"tool":"tools"}`,c=0;if(o){let l=Date.now()-o;c=Math.round(l/1e3),a+=c>=60?` \xB7 ${Math.floor(c/60)}m ${c%60}s`:` \xB7 ${c}s`}if(s.size>0&&(a+=` \xB7 ${s.size} ${s.size===1?"file":"files"} modified`),a+=" \u2500\u2500",console.log(`
1189
+ ${p.dim} ${a}${p.reset}`),c>=30&&process.stdout.isTTY){let l=s.size>0?`Done \u2014 ${s.size} ${s.size===1?"file":"files"} modified in ${c}s`:`Done \u2014 ${t} ${t===1?"step":"steps"} in ${c}s`;Hx(l)}if(So.size>0&&vo.size>0)for(let l of So){let u=vo.get(l);u&&console.log(`${p.dim} \u2714 task #${l} auto-matched: ${u.slice(0,60)}${p.reset}`)}s.size>0?console.log(`${p.dim} \u{1F4A1} /diff \xB7 /commit \xB7 /undo${p.reset}`):!r&&n.size>=5&&s.size===0&&t>=3?console.log(`${p.dim} \u{1F4A1} Found issues? Say "fix 1" or "apply all fixes"${p.reset}`):n.size>0&&t>=2&&console.log(`${p.dim} \u{1F4A1} /save \xB7 /clear${p.reset}`)}async function Yx(){if(!process.stdout.isTTY)return{action:"quit"};let t=ws(),e=At(),s=oi.fast?.[t],n=oi.strong?.[t],o=s&&s!==e,r=n&&n!==e&&n!==s,i=[];i.push({key:"r",label:`Retry with current model ${p.dim}(${e})${p.reset}`}),o&&i.push({key:"f",label:`Switch to ${p.bold}${s}${p.reset} ${p.dim}\u2014 fast, low latency${p.reset}`,model:s}),r&&i.push({key:"s",label:`Switch to ${p.bold}${n}${p.reset} ${p.dim}\u2014 reliable tool-calling, medium speed${p.reset}`,model:n}),i.push({key:"q",label:`${p.dim}Quit${p.reset}`}),console.log(),console.log(`${p.yellow} Stream stale \u2014 all retries exhausted.${p.reset} What would you like to do?`);for(let a of i)console.log(` ${p.cyan}[${a.key}]${p.reset} ${a.label}`);return process.stdout.write(` ${p.yellow}> ${p.reset}`),new Promise(a=>{let c=process.stdin,l=c.isRaw;c.setRawMode(!0),c.resume(),c.setEncoding("utf8");let u=!1,d=f=>{if(u)return;u=!0,c.removeListener("data",d),c.setRawMode(l||!1),c.pause();let h=f.toLowerCase().trim();if(process.stdout.write(`${h}
1190
+ `),f==="")return a({action:"quit"});let g=i.find(m=>m.key===h);!g||g.key==="q"||!g.model&&g.key!=="r"?a({action:"quit"}):g.key==="r"?a({action:"retry"}):a({action:"switch",model:g.model,provider:t})};c.on("data",d)})}var Ft=null;async function Gx(t,e=null,s={}){let n=ax(At());dh=n.staleWarn,fc=n.staleAbort,Ft=e;let o=t;wo&&typeof t=="string"&&(o=`${wo}
1157
1191
 
1158
- ${t}`,yo=null);let r=ih(o);q.push({role:"user",content:r}),$x();let i=s.autoOrchestrate!==!1&&process.env.NEX_AUTO_ORCHESTRATE!=="false",a=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10);try{let{detectComplexPrompt:be,runOrchestrated:xe}=Wp(),Te=be(typeof t=="string"?t:"");if(i&&Te.isComplex&&Te.estimatedGoals>=a)return console.log(`${p.yellow}\u26A1 Auto-orchestrate: ${Te.estimatedGoals} goals \u2192 parallel agents${p.reset}`),await xe(t,{orchestratorModel:s.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL,workerModel:s.model});Te.isComplex&&process.stdout.isTTY&&console.log(`${p.dim}Hint: ~${Te.estimatedGoals} goals detected. Disable with NEX_AUTO_ORCHESTRATE=false${p.reset}`)}catch{}let{setOnChange:c}=ua(),l=null,u=0;c((be,xe)=>{be==="create"?(l&&l.stop(),l=new Qb(xe.name,xe.tasks),l.setStats({tokens:u}),l.start()):be==="update"&&l?l.updateTask(xe.id,xe.status):be==="clear"&&l&&(l.stop(),l=null)});let d=await hc(),f=d;try{let{getBrainContext:be}=va(),xe=await be(t);xe&&(f=d+`
1159
- `+xe+`
1160
- `)}catch(be){process.env.NEX_DEBUG&&console.error("[agent] brain context failed:",be.message)}let m=j_(typeof t=="string"?t:"");if(m.length>0){let be=m.map(xe=>`[Triggered: ${xe.name}]
1161
- ${xe.instructions}`).join(`
1192
+ ${t}`,wo=null);let r=yh(o);q.push({role:"user",content:r}),qx();let i=s.autoOrchestrate!==!1&&process.env.NEX_AUTO_ORCHESTRATE!=="false",a=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10);try{let{detectComplexPrompt:be,runOrchestrated:ke}=nh(),Ae=be(typeof t=="string"?t:"");if(i&&Ae.isComplex&&Ae.estimatedGoals>=a)return console.log(`${p.yellow}\u26A1 Auto-orchestrate: ${Ae.estimatedGoals} goals \u2192 parallel agents${p.reset}`),await ke(t,{orchestratorModel:s.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL,workerModel:s.model});Ae.isComplex&&process.stdout.isTTY&&console.log(`${p.dim}Hint: ~${Ae.estimatedGoals} goals detected. Disable with NEX_AUTO_ORCHESTRATE=false${p.reset}`)}catch{}let{setOnChange:c}=$a(),l=null,u=0;c((be,ke)=>{be==="create"?(l&&l.stop(),l=new y_(ke.name,ke.tasks),l.setStats({tokens:u}),l.start()):be==="update"&&l?l.updateTask(ke.id,ke.status):be==="clear"&&l&&(l.stop(),l=null)});let d=await Cc(),f=d;try{let{getBrainContext:be}=Ma(),ke=await be(t);ke&&(f=d+`
1193
+ `+ke+`
1194
+ `)}catch(be){process.env.NEX_DEBUG&&console.error("[agent] brain context failed:",be.message)}let g=sx(typeof t=="string"?t:"");if(g.length>0){let be=g.map(ke=>`[Triggered: ${ke.name}]
1195
+ ${ke.instructions}`).join(`
1162
1196
  `);f+=`
1163
1197
  `+be+`
1164
- `}let g=[{role:"system",content:f},...q],b=new hs("Thinking...");b.start();let v=q.length===1,O=v?xx().catch(()=>null):Promise.resolve(null),U=v?$_(typeof t=="string"?t:"").catch(()=>null):Promise.resolve(null),L=Ze(),[{messages:R,compressed:C,compacted:K,tokensRemoved:Q},re,V]=await Promise.all([i_(g,L),O,U]),H=Et(g,L);if(b.stop(),re&&console.log(`${p.dim}${re}${p.reset}`),K)console.log(`${p.dim} [context compacted \u2014 summary (~${Q} tokens freed)]${p.reset}`);else if(C){let be=H.limit>0?Math.round(Q/H.limit*100):0;D(`${p.dim} [context compressed \u2014 ~${Q} tokens freed (${be}%)]${p.reset}`)}H.percentage>85&&D(`${p.yellow} \u26A0 Context ${Math.round(H.percentage)}% used (${Math.round(100-H.percentage)}% remaining) \u2014 consider /clear or /save + start fresh${p.reset}`);let _=R;if(V&&v&&(_=[_[0],{role:"user",content:`[Server probe at task start]
1165
- ${V}`},{role:"assistant",content:"Understood \u2014 I have the server context. Proceeding with the task."},..._.slice(1)]),v){let be=w_(typeof t=="string"?t:"");be&&(_=[_[0],{role:"user",content:be.user},{role:"assistant",content:be.assistant},..._.slice(1)])}if(Et(_,Ze()).percentage>=65){let{messages:xe,tokensRemoved:Te}=It(_,Ze());Te>0&&(_=xe,console.log(`${p.dim} [pre-flight compress \u2014 ${Te} tokens freed, now ${Math.round(Et(_,Ze()).percentage)}% used]${p.reset}`))}let he=0,de=0,me=0,ge=0,we=0,Se=9,fe=0,Pe=(()=>{let be=q.find(xe=>xe.role==="user");return typeof be?.content=="string"?be.content:""})(),w=/set_reminder|google.?auth|cron:|api\.log|jarvis.{0,30}(fehler|error|fail|broken|crash|nicht.{0,10}(funktioniert|läuft)|debug)|(?:fehler|error|crash|broken|gecrasht|abgestürzt).{0,30}jarvis|swarm.{0,30}(agent|crash|gecrasht|abgestürzt|fail)|agent.{0,30}(gecrasht|abgestürzt|crashed|fail)|server.{0,30}(passiert|fehler|crash|problem)|am.server/i.test(Pe),P=0;if(!Ye){let be=q.filter(Te=>Te.role==="user"||Te.role==="tool").map(Te=>typeof Te.content=="string"?Te.content:"").join(`
1166
- `),xe=nc(be);xe&&(Ye=!0,it=xe.slice(0,120),D(`${p.yellow} \u26A1 Root cause in briefing: ${it} \u2014 fix phase active from start (read budget: 3)${p.reset}`))}!Ye&&!bt&&/\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(Pe)&&(bt=!0,D(`${p.cyan} \u26A1 Creation task detected \u2014 tight investigation cap (4 pre-edit, 2 post-edit)${p.reset}`)),q.length<=1&&!s.skipPhaseRouting&&($e=h_(),$e&&(ys=p_(Pe)?.id||"coding",De="plan",zt=oc("plan",ys),oi=0,$o=0,nn=0,process.stdout.isTTY&&console.log(`${p.dim} \u21B3 Phase routing: plan(${zt||"default"}) \u2192 implement \u2192 verify${p.reset}`),D(`${p.cyan} \u26A1 Phase routing enabled \u2014 plan phase with ${zt||"default model"} (category: ${ys})${p.reset}`)));let k=0,N=new Map,T=new Set,S=new Set,J=Date.now(),Re=new n_(U_),Ce=bc,ye=s.skillLoop?10:1,Th=3*ye,Rh=5*ye,Ac=yc,Ch=5*ye,Ah=8*ye,Oh=$c,Nh=($e?6:4)*ye,Mh=($e?10:7)*ye,Oc=bo,Lh=($e?5:3)*ye,Nc=($e?8:5)*ye,Ph=wc,Ih=($e?4:3)*ye,jh=($e?6:4)*ye,Dh=3*ye,qh=4*ye,So=In,Fh=($e?3:2)*ye,Bh=($e?5:3)*ye,bs=($e?6:4)*ye,Wh=25,sn=0,Uh=6*ye,Hh=10*ye,on=0,Mc=5*ye,rn=0,Gh=2*ye,Yh=3,li=0,_s=10,Kh=16,Lc=s.skillLoop?999:n.investigationCap,Fe,Ct=s.maxIterations||($e?Cn(De):ic),ui=0,Pc=3,di=!1,Eo=0;e:for(;;){for(di=!1,Fe=0;Fe<Ct&&!Gr()?.aborted;Fe++){{let $=Ze(),y=Et(_,$),ee=k===0?65:78;if(y.percentage>=ee){let{messages:A,tokensRemoved:I}=It(_,$,k===0);if(I>0&&(_=A,I>50&&console.log(`${p.dim} [auto-compressed \u2014 ~${I} tokens freed, now ${Math.round(Et(_,$).percentage)}%]${p.reset}`),bt&&T.size>=3)){let te=[...T].map(le=>le.split("/").pop()).slice(0,10).join(", "),F={role:"user",content:`[FRAMEWORK \u2014 context compressed] Task is IN PROGRESS. Already created ${T.size} files: ${te}. DO NOT restart or re-investigate what was already done. Continue from where you left off.`};_.push(F)}}}if(ht&&!Ye&&go<2){go++;let $={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($),q.push($),D(`${p.yellow} \u26A0 Pre-call SSH-blocked nudge #${go} injected \u2014 model told to synthesize${p.reset}`)}ht||(go=0);let xe=!0;k>0&&C_();let Te=null;if(l&&l.isActive())l._paused&&l.resume();else if(!l){let $,y=A_();if(y&&y.total>1){let ee=y.description.length>40?y.description.slice(0,37)+"\u2026":y.description;$=`Plan step ${y.current}/${y.total}: ${ee}`}else $=k>0?`Thinking... (step ${k+1})`:"Thinking...";Te=new hs($),Te.start()}let Dn=!0,ct="",qn=!1,ze=new O_,At,fi=Date.now(),To=!1,pi=new AbortController,Ic=setInterval(()=>{let $=Date.now()-fi;if($>=ec)ze._clearCursorLine(),D(`${p.yellow} \u26A0 Stream stale for ${Math.round($/1e3)}s \u2014 aborting and retrying${p.reset}`),pi.abort();else if($>=Zp&&!To){To=!0,ze._clearCursorLine();let y=ti.fast?.[ms()],ee=me>0?` (retry ${me+1}/${Ur})`:"",A=Math.round((ec-$)/1e3);D(`${p.yellow} \u26A0 No tokens received for ${Math.round($/1e3)}s \u2014 waiting...${ee}${p.reset}`),y&&y!==Dt()?console.log(`${p.dim} \u{1F4A1} Will auto-switch to ${y} in ~${A}s if no tokens arrive${p.reset}`):console.log(`${p.dim} \u{1F4A1} Ctrl+C to abort \xB7 auto-abort in ~${A}s${p.reset}`)}},5e3),mt="",Ft=null;try{let $=ah(Ze()),y=new Set(["read_file","list_directory","search_files","glob","grep","git_status","git_diff","git_log","git_show","ssh_exec"]),ee=new Set(["read_file","list_directory","glob","grep","bash","git_status","git_diff","git_log","ssh_exec"]),A;wo()?A=$.filter(F=>rh.has(F.function.name)):$e&&De==="plan"?A=$.filter(F=>y.has(F.function.name)):$e&&De==="verify"?A=$.filter(F=>ee.has(F.function.name)):A=$;let I=Gr(),te=new AbortController;I&&I.addEventListener("abort",()=>te.abort(),{once:!0}),pi.signal.addEventListener("abort",()=>te.abort(),{once:!0}),At=await Up(_,A,{signal:te.signal,...zt?{model:zt}:{},onThinkingToken:()=>{fi=Date.now(),To=!1,qt?.onThinkingToken&&qt.onThinkingToken()},onToken:F=>{if(fi=Date.now(),To=!1,qt?.onToken){qt.onToken(F),ct+=F;return}if(ct+=F,!qn&&ct.length>400&&ct.length%250<F.length+1){let le=rc(ct,3);le.truncated&&(qn=!0,ze._clearCursorLine?.(),D(`${p.yellow} \u26A0 LLM stream loop detected (${le.repeatCount}\xD7 repeated) \u2014 suppressing display${p.reset}`))}qn||(mt+=F,process.stdout.isTTY?Ft||(Ft=setTimeout(()=>{mt&&ze&&ze.push(mt),mt="",Ft=null},50)):(ze.push(mt),mt=""),Dn&&(l&&!l._paused?l.pause():Te&&Te.stop(),xe||(xe=!0),ze.startCursor(),Dn=!1))}})}catch($){if(clearInterval(Ic),Ft&&(clearTimeout(Ft),Ft=null),mt&&ze&&(ze.push(mt),mt=""),l&&!l._paused&&l.pause(),Te&&Te.stop(),ze.stopCursor(),pi.signal.aborted&&!Gr()?.aborted){if(me++,me>Ur){if(ge<1){ge++,ps("Stale retries exhausted \u2014 last-resort force-compress...",p.yellow);let le=Ze(),{messages:j,tokensRemoved:B}=It(_,le);_=j,B>50&&D(`${p.dim} [force-compressed \u2014 ~${B} tokens freed]${p.reset}`),me=0,Fe--;continue}l&&(l.stop(),l=null);let F=await vx();if(F.action==="quit"){c(null),We(k,N,T,S,J),Be(q);break}F.action==="switch"&&(Vp(`${F.provider}:${F.model}`),console.log(`${p.green} \u2713 Switched to ${F.provider}:${F.model}${p.reset}`)),me=0,Fe--;continue}let I=me===1?3e3:5e3;if(me>=1&&fe<1){fe++,ps(`Stale retry ${me}/${Ur} \u2014 force-compressing before retry...`,p.yellow);let F=Ze(),{messages:le,tokensRemoved:j}=It(_,F,!0);if(_=le,j>0&&j>50&&D(`${p.dim} [force-compressed \u2014 ~${j} tokens freed]${p.reset}`),ix){let B=ti.fast?.[ms()];B&&B!==Dt()&&(Vp(`${ms()}:${B}`),console.log(`${p.cyan} \u26A1 Auto-switched to ${B} to avoid further stale timeouts${p.reset}`),console.log(`${p.dim} (disable with NEX_STALE_AUTO_SWITCH=0)${p.reset}`))}}else D(`${p.yellow} \u26A0 Stale retry ${me}/${Ur} \u2014 retrying in ${I/1e3}s...${p.reset}`);let te=new hs(`Waiting ${I/1e3}s before retry...`);te.start(),await new Promise(F=>setTimeout(F,I)),te.stop(),Fe--;continue}if($.name==="AbortError"||$.name==="CanceledError"||$.message?.includes("canceled")||$.message?.includes("aborted")){l&&(l.stop(),l=null),c(null),We(k,N,T,S,J),Be(q);break}let y=$.message;if($.code==="ECONNREFUSED"||$.message.includes("ECONNREFUSED"))y="Connection refused \u2014 please check your internet connection or API endpoint";else if($.code==="ENOTFOUND"||$.message.includes("ENOTFOUND"))y="Network error \u2014 could not reach the API server. Please check your connection";else if($.code==="ETIMEDOUT"||$.message.includes("timeout"))y="Request timed out \u2014 the API server took too long to respond. Please try again";else if($.message.includes("401")||$.message.includes("Unauthorized"))y="Authentication failed \u2014 please check your API key in the .env file";else if($.message.includes("403")||$.message.includes("Forbidden"))y="Access denied \u2014 your API key may not have permission for this model";else if($.message.includes("404")){y=`Model not found (404): ${Dt?Dt():"unknown"} \u2014 check your .env MODEL setting or run /models to list available models`,console.log(`${p.red} \u2717 ${y}${p.reset}`),l&&(l.stop(),l=null),c(null),We(k,N,T,S,J),Be(q);break}else if($.message.includes("400")){if(ge<3&&we<Se){ge++,we++;let I=k===0&&ge===1,te=I||ge===3||fe>0;if(I){ge=3;let B=$.message.replace(/^API Error(\s*\[HTTP \d+\])?:\s*/i,"").slice(0,150);ps(`Bad request (400) \u2014 ${B||"system prompt too large"}, compressing...`,p.yellow)}else ps(te?`Bad request (400) \u2014 nuclear compression (attempt ${ge}/3, dropping history)...`:`Bad request (400) \u2014 force-compressing and retrying... (attempt ${ge}/3)`,p.yellow);let F=Ze(),{messages:le,tokensRemoved:j}=It(_,F,te);_=le,j>50&&D(`${p.dim} [force-compressed \u2014 ~${j} tokens freed]${p.reset}`),Fe--;continue}{let I=_.find(W=>W.role==="system"),te=_.find(W=>W.role==="user"&&!String(W.content).startsWith("[SYSTEM")&&!String(W.content).startsWith("BLOCKED:")),F=[I,te].filter(Boolean),{getUsage:le}=Pt(),j=Pt().estimateMessagesTokens(F),B=Pt().estimateMessagesTokens(_);if(j<B){let W=[],z=q.filter(ne=>ne.role==="assistant"&&typeof ne.content=="string"&&ne.content.trim().length>30).slice(-5).map(ne=>ne.content.trim().slice(0,300).replace(/\n+/g," "));z.length>0&&W.push(`Key findings:
1167
- `+z.map(ne=>`- ${ne}`).join(`
1168
- `));let X=q.filter(ne=>ne.role==="tool"&&typeof ne.content=="string"&&!ne.content.startsWith("BLOCKED:")&&ne.content.trim().length>10).slice(-5).map(ne=>ne.content.trim().split(`
1198
+ `}let m=[{role:"system",content:f},...q];b_(At());let b=new $s(rc());b.start();let x=q.length===1,j=x?Ux().catch(()=>null):Promise.resolve(null),G=x?D_(typeof t=="string"?t:"").catch(()=>null):Promise.resolve(null),L=Qe(),[{messages:P,compressed:C,compacted:Z,tokensRemoved:Y},ue,ie]=await Promise.all([S_(m,L),j,G]),se=Tt(m,L);if(b.stop(),ue&&console.log(`${p.dim}${ue}${p.reset}`),Z)console.log(`${p.dim} [context compacted \u2014 summary (~${Y} tokens freed)]${p.reset}`);else if(C){let be=se.limit>0?Math.round(Y/se.limit*100):0;F(`${p.dim} [context compressed \u2014 ~${Y} tokens freed (${be}%)]${p.reset}`)}se.percentage>85&&F(`${p.yellow} \u26A0 Context ${Math.round(se.percentage)}% used (${Math.round(100-se.percentage)}% remaining) \u2014 consider /clear or /save + start fresh${p.reset}`);let T=P;if(ie&&x&&(T=[T[0],{role:"user",content:`[Server probe at task start]
1199
+ ${ie}`},{role:"assistant",content:"Understood \u2014 I have the server context. Proceeding with the task."},...T.slice(1)]),x){let be=q_(typeof t=="string"?t:"");be&&(T=[T[0],{role:"user",content:be.user},{role:"assistant",content:be.assistant},...T.slice(1)])}if(Tt(T,Qe()).percentage>=65){let{messages:ke,tokensRemoved:Ae}=jt(T,Qe());Ae>0&&(T=ke,console.log(`${p.dim} [pre-flight compress \u2014 ${Ae} tokens freed, now ${Math.round(Tt(T,Qe()).percentage)}% used]${p.reset}`))}let Te=0,K=0,X=0,me=0,fe=0,$e=9,pe=0,Re=(()=>{let be=q.find(ke=>ke.role==="user");return typeof be?.content=="string"?be.content:""})(),w=/set_reminder|google.?auth|cron:|api\.log|swarm.{0,30}(agent|crash|gecrasht|abgestürzt|fail)|agent.{0,30}(gecrasht|abgestürzt|crashed|fail)|server.{0,30}(passiert|fehler|crash|problem)|am.server/i.test(Re),I=0;if(!ze){let be=q.filter(Ae=>Ae.role==="user"||Ae.role==="tool").map(Ae=>typeof Ae.content=="string"?Ae.content:"").join(`
1200
+ `),ke=hc(be);ke&&(ze=!0,at=ke.slice(0,120),F(`${p.yellow} \u26A1 Root cause in briefing: ${at} \u2014 fix phase active from start (read budget: 3)${p.reset}`))}!ze&&!xt&&/\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(Re)&&(xt=!0,F(`${p.cyan} \u26A1 Creation task detected \u2014 tight investigation cap (4 pre-edit, 2 post-edit)${p.reset}`)),q.length<=1&&!s.skipPhaseRouting&&(we=L_(),we&&(_s=M_(Re)?.id||"coding",Pe="plan",Vt=$c("plan",_s),ai=0,bo=0,rn=0,process.stdout.isTTY&&console.log(`${p.dim} \u21B3 Phase routing: plan(${Vt||"default"}) \u2192 implement \u2192 verify${p.reset}`),F(`${p.cyan} \u26A1 Phase routing enabled \u2014 plan phase with ${Vt||"default model"} (category: ${_s})${p.reset}`)));let v=0,O=new Map,R=new Set,k=new Set,H=Date.now(),Se=new __(lx),xe=Pc,ge=s.skillLoop?10:1,fi=3*ge,Dh=5*ge,Yc=Nc,qh=5*ge,Fh=8*ge,Bh=Mc,Wh=(we?6:4)*ge,Uh=(we?10:7)*ge,pi=xo,Hh=(we?5:3)*ge,To=(we?8:5)*ge,Yh=Lc,Gh=(we?4:3)*ge,Kh=(we?6:4)*ge,zh=3*ge,Xh=4*ge,Fn=on,Vh=(we?3:2)*ge,Jh=(we?5:3)*ge,Bn=(we?6:4)*ge,Zh=25,an=0,Qh=6*ge,em=10*ge,cn=0,Gc=5*ge,ln=0,tm=2*ge,nm=3,hi=0,vs=10,sm=16,Kc=s.skillLoop?999:n.investigationCap,We,Ot=s.maxIterations||(we?Mn(Pe):bc),mi=0,zc=3,gi=!1,Ro=0;e:for(;;){for(gi=!1,We=0;We<Ot&&!zr()?.aborted;We++){{let $=Qe(),y=Tt(T,$),ee=v===0?65:78;if(y.percentage>=ee){if(R.size>0||we&&Pe!=="plan"){let Q=T_(q,{filesModified:R,currentPhase:we?Pe:null});if(Q){let D=T.findIndex(N=>N._progressSnapshot);D!==-1&&T.splice(D,1);let le=T.findIndex(N=>N.role==="system");T.splice(le+1,0,Q)}}let{messages:S,tokensRemoved:A}=jt(T,$,v===0);if(A>0&&(T=S,A>50&&console.log(`${p.dim} [auto-compressed \u2014 ~${A} tokens freed, now ${Math.round(Tt(T,$).percentage)}%]${p.reset}`),xt&&R.size>=3)){let Q=[...R].map(le=>le.split("/").pop()).slice(0,10).join(", "),D={role:"user",content:`[FRAMEWORK \u2014 context compressed] Task is IN PROGRESS. Already created ${R.size} files: ${Q}. DO NOT restart or re-investigate what was already done. Continue from where you left off.`};T.push(D)}}}if(mt&&!ze&&$o<2){$o++;let $={role:"user",content:"[SYSTEM] SSH paused \u2014 you have made many consecutive SSH calls. Synthesize your findings so far: summarize what you learned and what the likely issue is. After your synthesis, SSH will be available again for targeted follow-up commands."};T.push($),q.push($),F(`${p.yellow} \u26A0 Pre-call SSH-blocked nudge #${$o} injected \u2014 model told to synthesize${p.reset}`)}mt||($o=0);let ke=!0;v>0&&X_();let Ae=null;if(l&&l.isActive())l._paused&&l.resume();else if(!l){let $,y=V_();if(y&&y.total>1){let ee=y.description.length>40?y.description.slice(0,37)+"\u2026":y.description;$=`Plan step ${y.current}/${y.total}: ${ee}`}else $=v>0?`${rc()} (step ${v+1})`:rc();Ae=new $s($),Ae.start()}let Wn=!0,lt="",Un=!1,Ve=new J_,Nt,yi=Date.now(),Co=!1,$i=new AbortController,Xc=setInterval(()=>{let $=Date.now()-yi;if($>=fc)Ve._clearCursorLine(),F(`${p.yellow} \u26A0 Stream stale for ${Math.round($/1e3)}s \u2014 aborting and retrying${p.reset}`),$i.abort();else if($>=dh&&!Co){Co=!0,Ve._clearCursorLine();let y=oi.fast?.[ws()],ee=X>0?` (retry ${X+1}/${Gr})`:"",S=Math.round((fc-$)/1e3);F(`${p.yellow} \u26A0 No tokens received for ${Math.round($/1e3)}s \u2014 waiting...${ee}${p.reset}`),y&&y!==At()?console.log(`${p.dim} \u{1F4A1} Will auto-switch to ${y} in ~${S}s if no tokens arrive${p.reset}`):console.log(`${p.dim} \u{1F4A1} Ctrl+C to abort \xB7 auto-abort in ~${S}s${p.reset}`)}},5e3),gt="",Bt=null;try{let $=$h(Qe()),y=new Set(["read_file","list_directory","search_files","glob","grep","git_status","git_diff","git_log","git_show","ssh_exec"]),ee=new Set(["read_file","list_directory","glob","grep","bash","git_status","git_diff","git_log","ssh_exec"]),S;_o()?S=$.filter(D=>gh.has(D.function.name)):we&&Pe==="plan"?S=$.filter(D=>y.has(D.function.name)):we&&Pe==="verify"?S=$.filter(D=>ee.has(D.function.name)):S=$;let A=zr(),Q=new AbortController;A&&A.addEventListener("abort",()=>Q.abort(),{once:!0}),$i.signal.addEventListener("abort",()=>Q.abort(),{once:!0}),Nt=await sh(T,S,{signal:Q.signal,...Vt?{model:Vt}:{},onThinkingToken:()=>{yi=Date.now(),Co=!1,Ft?.onThinkingToken&&Ft.onThinkingToken()},onToken:D=>{if(yi=Date.now(),Co=!1,Ft?.onToken){Ft.onToken(D),lt+=D;return}if(lt+=D,!Un&&lt.length>400&&lt.length%250<D.length+1){let le=wc(lt,3);le.truncated&&(Un=!0,Ve._clearCursorLine?.(),F(`${p.yellow} \u26A0 LLM stream loop detected (${le.repeatCount}\xD7 repeated) \u2014 suppressing display${p.reset}`))}Un||(gt+=D,process.stdout.isTTY?Bt||(Bt=setTimeout(()=>{gt&&Ve&&Ve.push(gt),gt="",Bt=null},50)):(Ve.push(gt),gt=""),Wn&&(l&&!l._paused?l.pause():Ae&&Ae.stop(),ke||(ke=!0),Ve.startCursor(),Wn=!1))}})}catch($){if(clearInterval(Xc),Bt&&(clearTimeout(Bt),Bt=null),gt&&Ve&&(Ve.push(gt),gt=""),l&&!l._paused&&l.pause(),Ae&&Ae.stop(),Ve.stopCursor(),$i.signal.aborted&&!zr()?.aborted){if(X++,X>Gr){if(me<1){me++,ys("Stale retries exhausted \u2014 last-resort force-compress...",p.yellow);let le=Qe(),{messages:N,tokensRemoved:B}=jt(T,le);T=N,B>50&&F(`${p.dim} [force-compressed \u2014 ~${B} tokens freed]${p.reset}`),X=0,We--;continue}l&&(l.stop(),l=null);let D=await Yx();if(D.action==="quit"){c(null),Fe(v,O,R,k,H),qe(q);break}D.action==="switch"&&(lh(`${D.provider}:${D.model}`),console.log(`${p.green} \u2713 Switched to ${D.provider}:${D.model}${p.reset}`)),X=0,We--;continue}let A=X===1?3e3:5e3;if(X>=1&&pe<1){pe++,ys(`Stale retry ${X}/${Gr} \u2014 force-compressing before retry...`,p.yellow);let D=Qe(),{messages:le,tokensRemoved:N}=jt(T,D,!0);if(T=le,N>0&&N>50&&F(`${p.dim} [force-compressed \u2014 ~${N} tokens freed]${p.reset}`),Ex){let B=oi.fast?.[ws()];B&&B!==At()&&(lh(`${ws()}:${B}`),console.log(`${p.cyan} \u26A1 Auto-switched to ${B} to avoid further stale timeouts${p.reset}`),console.log(`${p.dim} (disable with NEX_STALE_AUTO_SWITCH=0)${p.reset}`))}}else F(`${p.yellow} \u26A0 Stale retry ${X}/${Gr} \u2014 retrying in ${A/1e3}s...${p.reset}`);let Q=new $s(`Waiting ${A/1e3}s before retry...`);Q.start(),await new Promise(D=>setTimeout(D,A)),Q.stop(),We--;continue}if($.name==="AbortError"||$.name==="CanceledError"||$.message?.includes("canceled")||$.message?.includes("aborted")){l&&(l.stop(),l=null),c(null),Fe(v,O,R,k,H),qe(q);break}let y=$.message;if($.code==="ECONNREFUSED"||$.message.includes("ECONNREFUSED"))y="Connection refused \u2014 please check your internet connection or API endpoint";else if($.code==="ENOTFOUND"||$.message.includes("ENOTFOUND"))y="Network error \u2014 could not reach the API server. Please check your connection";else if($.code==="ETIMEDOUT"||$.message.includes("timeout"))y="Request timed out \u2014 the API server took too long to respond. Please try again";else if($.message.includes("401")||$.message.includes("Unauthorized"))y="Authentication failed \u2014 please check your API key in the .env file";else if($.message.includes("403")||$.message.includes("Forbidden"))y="Access denied \u2014 your API key may not have permission for this model";else if($.message.includes("404")){y=`Model not found (404): ${At?At():"unknown"} \u2014 check your .env MODEL setting or run /models to list available models`,console.log(`${p.red} \u2717 ${y}${p.reset}`),l&&(l.stop(),l=null),c(null),Fe(v,O,R,k,H),qe(q);break}else if($.message.includes("400")){if(me<3&&fe<$e){me++,fe++;let A=v===0&&me===1,Q=A||me===3||pe>0;if(A){me=3;let B=$.message.replace(/^API Error(\s*\[HTTP \d+\])?:\s*/i,"").slice(0,150);ys(`Bad request (400) \u2014 ${B||"system prompt too large"}, compressing...`,p.yellow)}else ys(Q?`Bad request (400) \u2014 nuclear compression (attempt ${me}/3, dropping history)...`:`Bad request (400) \u2014 force-compressing and retrying... (attempt ${me}/3)`,p.yellow);let D=Qe(),{messages:le,tokensRemoved:N}=jt(T,D,Q);T=le,N>50&&F(`${p.dim} [force-compressed \u2014 ~${N} tokens freed]${p.reset}`),We--;continue}{let A=T.find(U=>U.role==="system"),Q=T.find(U=>U.role==="user"&&!String(U.content).startsWith("[SYSTEM")&&!String(U.content).startsWith("BLOCKED:")),D=[A,Q].filter(Boolean),{getUsage:le}=It(),N=It().estimateMessagesTokens(D),B=It().estimateMessagesTokens(T);if(N<B){let U=[],V=q.filter(ne=>ne.role==="assistant"&&typeof ne.content=="string"&&ne.content.trim().length>30).slice(-5).map(ne=>ne.content.trim().slice(0,300).replace(/\n+/g," "));V.length>0&&U.push(`Key findings:
1201
+ `+V.map(ne=>`- ${ne}`).join(`
1202
+ `));let J=q.filter(ne=>ne.role==="tool"&&typeof ne.content=="string"&&!ne.content.startsWith("BLOCKED:")&&ne.content.trim().length>10).slice(-5).map(ne=>ne.content.trim().split(`
1169
1203
  `).slice(0,8).join(`
1170
- `).slice(0,500));if(X.length>0&&W.push(`Tool results summary:
1171
- `+X.map(ne=>`- ${ne}`).join(`
1172
- `)),T.size>0){let ne=[...T].map(Ne=>Ne.split("/").slice(-2).join("/")).join(", ");W.unshift(`Already modified: ${ne} \u2014 use edit_file to add missing pieces only, DO NOT use write_file on these files.`)}if(S.size>0){let ne=[...S].map(Ne=>Ne.split("/").slice(-2).join("/")).join(", ");W.push(`Files already investigated: ${ne}`)}let oe=require("os").tmpdir()+"/nex-session-checkpoint.json";try{require("fs").writeFileSync(oe,JSON.stringify({filesWritten:[...T].map(ne=>ne.split("/").slice(-2).join("/")),filesRead:[...S].map(ne=>ne.split("/").slice(-2).join("/")),isCreationTask:bt,wipeNumber:mo+1,timestamp:Date.now()},null,2)),W.push(`Session checkpoint: ${oe} \u2014 read it for exact file list`)}catch{}let ue=0;{let Ne=((typeof te?.content=="string"?te.content:Array.isArray(te?.content)?te.content.filter(Ve=>Ve.type==="text").map(Ve=>Ve.text).join(" "):"").match(/(?:^|\s)([\w./\-]+\.(?:js|ts|jsx|tsx|py|json|yml|yaml|sh|css|scss|html|md|go|rs|java|rb|php))/gm)||[]).map(Ve=>Ve.trim()).filter(Boolean),Xe=[...T],xt=Ne.filter(Ve=>!Xe.some(Fn=>Fn.endsWith(Ve)||Ve.endsWith(Fn.split("/").pop())));ue=xt.length;let lt=[...q].reverse().find(Ve=>Ve.role==="tool"&&typeof Ve.content=="string"&&!Ve.content.startsWith("BLOCKED:")&&Ve.content.length>5),Wt={completed:Xe.map(Ve=>Ve.split("/").slice(-2).join("/")),pending:xt.length>0?xt:Xe.length===0?["(task files not yet identified)"]:[],lastEdit:lt?lt.content.trim().slice(0,120):null};(Wt.completed.length>0||Wt.pending.length>0)&&W.unshift(`Work manifest:
1173
- ${JSON.stringify(Wt,null,2)}`)}if(W.length>0){let ne={role:"user",content:`[SYSTEM: Findings from investigation before context wipe]
1174
- ${W.join(`
1204
+ `).slice(0,500));if(J.length>0&&U.push(`Tool results summary:
1205
+ `+J.map(ne=>`- ${ne}`).join(`
1206
+ `)),R.size>0){let ne=[...R].map(Me=>Me.split("/").slice(-2).join("/")).join(", ");U.unshift(`Already modified: ${ne} \u2014 use edit_file to add missing pieces only, DO NOT use write_file on these files.`)}if(k.size>0){let ne=[...k].map(Me=>Me.split("/").slice(-2).join("/")).join(", ");U.push(`Files already investigated: ${ne}`)}let oe=require("os").tmpdir()+"/nex-session-checkpoint.json";try{require("fs").writeFileSync(oe,JSON.stringify({filesWritten:[...R].map(ne=>ne.split("/").slice(-2).join("/")),filesRead:[...k].map(ne=>ne.split("/").slice(-2).join("/")),isCreationTask:xt,wipeNumber:yo+1,timestamp:Date.now()},null,2)),U.push(`Session checkpoint: ${oe} \u2014 read it for exact file list`)}catch{}let he=0;{let Me=((typeof Q?.content=="string"?Q.content:Array.isArray(Q?.content)?Q.content.filter(Ye=>Ye.type==="text").map(Ye=>Ye.text).join(" "):"").match(/(?:^|\s)([\w./\-]+\.(?:js|ts|jsx|tsx|py|json|yml|yaml|sh|css|scss|html|md|go|rs|java|rb|php))/gm)||[]).map(Ye=>Ye.trim()).filter(Boolean),Ue=[...R],yt=Me.filter(Ye=>!Ue.some(_i=>_i.endsWith(Ye)||Ye.endsWith(_i.split("/").pop())));he=yt.length;let ut=[...q].reverse().find(Ye=>Ye.role==="tool"&&typeof Ye.content=="string"&&!Ye.content.startsWith("BLOCKED:")&&Ye.content.length>5),Ut={completed:Ue.map(Ye=>Ye.split("/").slice(-2).join("/")),pending:yt.length>0?yt:Ue.length===0?["(task files not yet identified)"]:[],lastEdit:ut?ut.content.trim().slice(0,120):null};(Ut.completed.length>0||Ut.pending.length>0)&&U.unshift(`Work manifest:
1207
+ ${JSON.stringify(Ut,null,2)}`)}if(U.length>0){let ne={role:"user",content:`[SYSTEM: Findings from investigation before context wipe]
1208
+ ${U.join(`
1175
1209
  `)}
1176
- Continue implementing the fixes based on these findings.`};F.push(ne)}if(mo>=3){let ne=T.size>0?`
1177
- Files modified so far: ${[...T].map(Ne=>Ne.split("/").slice(-1)[0]).join(", ")}`:"";D(`${p.red} \u2717 Super-nuclear limit reached (3\xD7) \u2014 aborting to prevent runaway context loop${p.reset}`),console.log(`${p.yellow} \u{1F4A1} Task may exceed model context. Try /clear and break it into smaller steps.${ne?p.dim+ne:""}${p.reset}`),l&&(l.stop(),l=null),c(null),We(k,N,T,S,J,{suppressHint:!0}),Be(q);break}_=F,mo++,Mn=12+Math.min(ue*3,15),uc=!0,Vr=T.size,Jr=!1,wt=0,P=0;for(let[ne,Ne]of In){let Xe=Ne?.count??Ne??0;eh(In,ne,Xe>=2?Xe:1)}for(let[ne]of tn)An(In,ne)<2&&tn.delete(ne);Nn.clear(),jn.clear(),bt&&Rt>0&&(Tt=!0,D(`${p.cyan} \u26A1 Post-wipe creation guard: cap pre-fired (${Rt} edits already made)${p.reset}`));for(let[ne]of bo)eh(bo,ne,Nc-1);if(ps(`Super-nuclear compression \u2014 dropped all history, keeping original task only (${B-j} tokens freed)`,p.yellow),mo>=1){let ne=[...In.entries()].filter(([,lt])=>lt>=bs).map(([lt])=>lt.split("/").slice(-1)[0]),Ne=ne.length>0?`
1210
+ Continue implementing the fixes based on these findings.`};D.push(ne)}if(yo>=3){let ne=R.size>0?`
1211
+ Files modified so far: ${[...R].map(Me=>Me.split("/").slice(-1)[0]).join(", ")}`:"";F(`${p.red} \u2717 Super-nuclear limit reached (3\xD7) \u2014 aborting to prevent runaway context loop${p.reset}`),console.log(`${p.yellow} \u{1F4A1} Task may exceed model context. Try /clear and break it into smaller steps.${ne?p.dim+ne:""}${p.reset}`),l&&(l.stop(),l=null),c(null),Fe(v,O,R,k,H,{suppressHint:!0}),qe(q);break}T=D,yo++,In=12+Math.min(he*3,15),vc=!0,Qr=R.size,ei=!1,_t=0,I=0;for(let[ne,Me]of on){let Ue=Me?.count??Me??0;mc(on,ne,Ue>=2?Ue:1)}for(let[ne]of zt)Dt(on,ne)<2&&zt.delete(ne);Pn.clear(),qn.clear(),xt&&Ct>0&&(Rt=!0,F(`${p.cyan} \u26A1 Post-wipe creation guard: cap pre-fired (${Ct} edits already made)${p.reset}`));for(let[ne]of xo)mc(xo,ne,To-1);if(ys(`Super-nuclear compression \u2014 dropped all history, keeping original task only (${B-N} tokens freed)`,p.yellow),yo>=1){let ne=[...on.entries()].filter(([,ut])=>ut>=Bn).map(([ut])=>ut.split("/").slice(-1)[0]),Me=ne.length>0?`
1178
1212
 
1179
- Files already at read cap \u2014 use grep_search instead: ${ne.join(", ")}`:"",xt={role:"user",content:ht&&!Ye?"[SYSTEM] Context was compressed. SSH is currently unavailable \u2014 do not read more local files. Summarize what you found and ask the user for the server output you need.":`[SYSTEM] Context was compressed. Use the findings above to implement your fix. If you need to re-read a file, use line_start/line_end for the specific section.${Ne}`};q.push(xt),_.push(xt)}ge=0,Fe--;continue}}y="Context too large to compress \u2014 use /clear to start fresh"}else $.message.includes("500")||$.message.includes("502")||$.message.includes("503")||$.message.includes("504")?y="API server error \u2014 the provider is experiencing issues. Please try again in a moment":($.message.includes("fetch failed")||$.message.includes("fetch"))&&(y="Network request failed \u2014 please check your internet connection");if(console.log(`${p.red} \u2717 ${y}${p.reset}`),$.message.includes("429")){if(he++,he>Za){console.log(`${p.red} Rate limit: max retries (${Za}) exceeded. Try again later or use /budget to check your limits.${p.reset}`),l&&(l.stop(),l=null),c(null),We(k,N,T,S,J),Be(q);break}let I=Math.min(1e4*Math.pow(2,he-1),12e4),te=new hs(`Rate limit \u2014 waiting ${Math.round(I/1e3)}s (retry ${he}/${Za})`);te.start(),await new Promise(F=>setTimeout(F,I)),te.stop();continue}let ee=process.env.NEX_PHASE_ROUTING!=="0"&&(()=>{try{return He().getActiveProviderName()==="ollama"}catch{return!1}})();if($.message.includes("socket disconnected")||$.message.includes("TLS")||$.message.includes("ECONNRESET")||$.message.includes("ECONNABORTED")||$.message.includes("ETIMEDOUT")||ee&&($.message.includes("500")||$.message.includes("502")||$.message.includes("503")||$.message.includes("504")||$.message.includes("401")||$.message.includes("Unauthorized"))||$.code==="ECONNRESET"||$.code==="ECONNABORTED"){if(de++,de>Qa){console.log(`${p.red} Network error: max retries (${Qa}) exceeded. Check your connection and try again.
1180
- Use /undo to revert changes made during this session.${p.reset}`),l&&(l.stop(),l=null),c(null),We(k,N,T,S,J),Be(q);break}let I=Math.min(2e3*Math.pow(2,de-1),3e4),te=new hs(`API temporarily unavailable \u2014 retrying in ${Math.round(I/1e3)}s (${de}/${Qa}). Your changes are safe.`);te.start(),await new Promise(F=>setTimeout(F,I)),te.stop(),Fe--;continue}l&&(l.stop(),l=null),c(null),We(k,N,T,S,J),Be(q);break}if(clearInterval(Ic),he=0,de=0,Dn&&(l&&!l._paused&&l.pause(),Te&&Te.stop()),Ft&&(clearTimeout(Ft),Ft=null),mt&&ze&&(ze.push(mt),mt=""),ct&&ze.flush(),de=0,me=0,At&&At.usage){let $=At.usage.prompt_tokens||0,y=At.usage.completion_tokens||0;Yp(ms(),Dt(),$,y),u+=$+y,l&&l.setStats({tokens:u})}else if(At&&!At.usage){let $=_.map(A=>typeof A.content=="string"?A.content:Array.isArray(A.content)?A.content.map(I=>typeof I=="string"?I:I.text||"").join(""):"").join(" "),y=zp($),ee=zp(At.content||ct||"");Yp(ms(),Dt(),y,ee),u+=y+ee,l&&l.setStats({tokens:u})}let{content:jc,tool_calls:Bt}=At,Ro=rc(jc||""),Dc=Ro.truncated?Ro.text:jc;Ro.truncated&&D(`${p.yellow} \u26A0 LLM output loop detected (${Ro.repeatCount}\xD7 repeated paragraph) \u2014 response truncated${p.reset}`);let Co=K_(Dc||""),Ot=Co.truncated?Co.text:Dc;Co.truncated&&D(`${p.yellow} \u26A0 LLM output loop detected (${Co.repeatCount}\xD7 repeated window) \u2014 response truncated${p.reset}`);let hi={role:"assistant",content:Ot||""};if(Bt&&Bt.length>0&&(hi.tool_calls=Bt),q.push(hi),_.push(hi),!Ye&&Ot&&Bt&&Bt.length>0){let $=nc(Ot);if($){Ye=!0,it=$.slice(0,120),jt=0,Tt=!1,Kt=0,D(`${p.yellow} \u26A1 Root cause in model analysis: ${it} \u2014 fix phase (read budget: 3)${p.reset}`);let y={role:"user",content:`[SYSTEM] Root cause identified: ${it}. Read only the file that needs fixing, then edit it. Do not read other files.`};q.push(y),_.push(y)}}if(!Bt||Bt.length===0){let $=(Ot||"").trim().length>0||ct.trim().length>0,y=!1;if(ht&&$&&(Hr>=2?D(`${p.yellow} \u26A0 SSH permanently blocked after ${Hr} storm warnings \u2014 no further SSH calls allowed${p.reset}`):(ht=!1,wt=_s-4,y=!0)),y&&$){let A=(Ot||"").trim();if(A.endsWith("?")||/\b(Wo |Bitte |Kannst du|Soll ich)\b/.test(A.slice(-200))){let te={role:"user",content:"[SYSTEM] Continue. Do not ask questions \u2014 implement the fix yourself using SSH. The server is at 94.130.37.43."};_.push(te),q.push(te);continue}}if(!$&&k>0&&Fe<ic-1){let A={role:"user",content:"[SYSTEM] You ran tools but produced no visible output. The user CANNOT see tool results \u2014 only your text. Please summarize your findings now."};_.push(A),q.push(A);continue}let ee=/keine.*Tool|can.?t use.*tool|Tool.?Budget|nicht.*zugreifen|cannot.*access|no.*tool.*access|keine.*Werkzeug|da ich keine.*kann/i;if($&&Fe<3&&ee.test((Ot||"").slice(0,600)))if(uc&&Mn<=0||ht){D(`${p.yellow} \u26A0 Tool avoidance (constrained context) \u2014 telling model to ask user${p.reset}`);let I={role:"user",content:"[SYSTEM] Correct \u2014 remote access is currently limited. Summarize what you have found so far and tell the user exactly what specific information (logs, process list, error output) you need from the server to continue."};_.push(I),q.push(I);continue}else{D(`${p.yellow} \u26A0 Tool avoidance detected \u2014 nudging model to use tools${p.reset}`);let I={role:"user",content:"[SYSTEM] You have full tool access. Use your tools to investigate and implement the fix directly \u2014 do not say you cannot use tools. If SSH is needed, use a single targeted command that captures the most relevant information rather than multiple sequential calls."};_.push(I),q.push(I);continue}if(s.skillLoop&&$&&k>3&&Eo<5){let A=(Ot||ct||"").toLowerCase();if(/\b(i.ll stop|stop the|stopped|done with|complet|summar|conclud|no more|finish|end of|that.s all|final|wrapped up|no further|mindful of|reached.*limit|tool call limit|at this point|recommend keep)/.test(A.slice(-600))){Eo=(Eo||0)+1,D(`${p.yellow} \u26A0 Skill loop: model tried to stop \u2014 continuation nudge #${Eo}${p.reset}`);let te={role:"user",content:"[SYSTEM] Do NOT stop. You are in an autonomous experiment loop. The user is away and expects you to keep running experiments indefinitely until they interrupt with Ctrl+C. Start the next experiment NOW: hypothesize a new change, checkpoint, edit, run, measure, keep or revert. Think harder \u2014 try a completely different optimization approach."};_.push(te),q.push(te);continue}}if($e&&De==="plan"&&nn>=2){D(`${p.cyan} \u21B3 Plan phase: ${nn} consecutive blocks \u2014 auto-advancing to implement${p.reset}`),nn=0;let A=fo("implement","[auto-advance: task only requires direct action]");if(A){q.push(A),_.push(A),Fe=0,Ct=Cn("implement");continue}}if($e&&$){let A=(Ot||ct||"").trim();if(De==="plan"){let I=fo("implement",A);if(I){q.push(I),_.push(I),Fe=0,Ct=Cn("implement");continue}}else if(De==="implement"&&T.size>0){let I=q.find(le=>le.role==="user"),te=typeof I?.content=="string"?I.content:"",F=fo("verify",A,T,te);if(F){q.push(F),_.push(F),Fe=0,Ct=Math.min(Cn("verify")+Math.max(0,(T.size-2)*2),20);continue}}else if(De==="verify"){let te=/\bFAIL\b|test.*fail|error|broken|missing|incorrect/i.test(A.slice(0,500));if(te&&$o<1){$o++;let F={role:"user",content:`[PHASE: RE-IMPLEMENTATION] Verification found issues:
1181
- ${A.slice(0,400)}
1213
+ Files already at read cap \u2014 use grep_search instead: ${ne.join(", ")}`:"",yt={role:"user",content:mt&&!ze?"[SYSTEM] Context was compressed. SSH is currently unavailable \u2014 do not read more local files. Summarize what you found and ask the user for the server output you need.":`[SYSTEM] Context was compressed. Use the findings above to implement your fix. If you need to re-read a file, use line_start/line_end for the specific section.${Me}`};q.push(yt),T.push(yt)}me=0,We--;continue}}y="Context too large to compress \u2014 use /clear to start fresh"}else $.message.includes("500")||$.message.includes("502")||$.message.includes("503")||$.message.includes("504")?y="API server error \u2014 the provider is experiencing issues. Please try again in a moment":($.message.includes("fetch failed")||$.message.includes("fetch"))&&(y="Network request failed \u2014 please check your internet connection");if(console.log(`${p.red} \u2717 ${y}${p.reset}`),$.message.includes("429")){if(Te++,Te>uc){console.log(`${p.red} Rate limit: max retries (${uc}) exceeded. Try again later or use /budget to check your limits.${p.reset}`),l&&(l.stop(),l=null),c(null),Fe(v,O,R,k,H),qe(q);break}let A=Math.min(1e4*Math.pow(2,Te-1),12e4),Q=new $s(`Rate limit \u2014 waiting ${Math.round(A/1e3)}s (retry ${Te}/${uc})`);Q.start(),await new Promise(D=>setTimeout(D,A)),Q.stop();continue}let ee=process.env.NEX_PHASE_ROUTING!=="0"&&(()=>{try{return Ge().getActiveProviderName()==="ollama"}catch{return!1}})();if($.message.includes("socket disconnected")||$.message.includes("TLS")||$.message.includes("ECONNRESET")||$.message.includes("ECONNABORTED")||$.message.includes("ETIMEDOUT")||ee&&($.message.includes("500")||$.message.includes("502")||$.message.includes("503")||$.message.includes("504")||$.message.includes("401")||$.message.includes("Unauthorized"))||$.code==="ECONNRESET"||$.code==="ECONNABORTED"){if(K++,K>dc){console.log(`${p.red} Network error: max retries (${dc}) exceeded. Check your connection and try again.
1214
+ Use /undo to revert changes made during this session.${p.reset}`),l&&(l.stop(),l=null),c(null),Fe(v,O,R,k,H),qe(q);break}let A=Math.min(2e3*Math.pow(2,K-1),3e4),Q=new $s(`API temporarily unavailable \u2014 retrying in ${Math.round(A/1e3)}s (${K}/${dc}). Your changes are safe.`);Q.start(),await new Promise(D=>setTimeout(D,A)),Q.stop(),We--;continue}l&&(l.stop(),l=null),c(null),Fe(v,O,R,k,H),qe(q);break}if(clearInterval(Xc),Te=0,K=0,Wn&&(l&&!l._paused&&l.pause(),Ae&&Ae.stop()),Bt&&(clearTimeout(Bt),Bt=null),gt&&Ve&&(Ve.push(gt),gt=""),lt&&Ve.flush(),K=0,X=0,Nt&&Nt.usage){let $=Nt.usage.prompt_tokens||0,y=Nt.usage.completion_tokens||0;rh(ws(),At(),$,y),u+=$+y,l&&l.setStats({tokens:u})}else if(Nt&&!Nt.usage){let $=T.map(S=>typeof S.content=="string"?S.content:Array.isArray(S.content)?S.content.map(A=>typeof A=="string"?A:A.text||"").join(""):"").join(" "),y=ah($),ee=ah(Nt.content||lt||"");rh(ws(),At(),y,ee),u+=y+ee,l&&l.setStats({tokens:u})}let{content:Vc,tool_calls:Wt}=Nt,Ao=wc(Vc||""),Jc=Ao.truncated?Ao.text:Vc;Ao.truncated&&F(`${p.yellow} \u26A0 LLM output loop detected (${Ao.repeatCount}\xD7 repeated paragraph) \u2014 response truncated${p.reset}`);let Oo=px(Jc||""),Mt=Oo.truncated?Oo.text:Jc;Oo.truncated&&F(`${p.yellow} \u26A0 LLM output loop detected (${Oo.repeatCount}\xD7 repeated window) \u2014 response truncated${p.reset}`);let wi={role:"assistant",content:Mt||""};if(Wt&&Wt.length>0&&(wi.tool_calls=Wt),q.push(wi),T.push(wi),!ze&&Mt&&Wt&&Wt.length>0){let $=hc(Mt);if($){ze=!0,at=$.slice(0,120),qt=0,Rt=!1,Xt=0,F(`${p.yellow} \u26A1 Root cause in model analysis: ${at} \u2014 fix phase (read budget: 3)${p.reset}`);let y={role:"user",content:`[SYSTEM] Root cause identified: ${at}. Read only the file that needs fixing, then edit it. Do not read other files.`};q.push(y),T.push(y)}}if(!Wt||Wt.length===0){let $=(Mt||"").trim().length>0||lt.trim().length>0,y=!1;if(mt&&$&&(Kr>=2?F(`${p.yellow} \u26A0 SSH permanently blocked after ${Kr} storm warnings \u2014 no further SSH calls allowed${p.reset}`):(mt=!1,_t=vs-4,y=!0)),y&&$){let S=(Mt||"").trim();if(S.endsWith("?")||/\b(Wo |Bitte |Kannst du|Soll ich)\b/.test(S.slice(-200))){let Q={role:"user",content:"[SYSTEM] Continue. Do not ask questions \u2014 implement the fix yourself using SSH. The server is at 94.130.37.43."};T.push(Q),q.push(Q);continue}}if(!$&&v>0&&We<bc-1){let S={role:"user",content:"[SYSTEM] You ran tools but produced no visible output. The user CANNOT see tool results \u2014 only your text. Please summarize your findings now."};T.push(S),q.push(S);continue}let ee=/keine.*Tool|can.?t use.*tool|Tool.?Budget|nicht.*zugreifen|cannot.*access|no.*tool.*access|keine.*Werkzeug|da ich keine.*kann/i;if($&&We<3&&ee.test((Mt||"").slice(0,600)))if(vc&&In<=0||mt){F(`${p.yellow} \u26A0 Tool avoidance (constrained context) \u2014 telling model to ask user${p.reset}`);let A={role:"user",content:"[SYSTEM] Correct \u2014 remote access is currently limited. Summarize what you have found so far and tell the user exactly what specific information (logs, process list, error output) you need from the server to continue."};T.push(A),q.push(A);continue}else{F(`${p.yellow} \u26A0 Tool avoidance detected \u2014 nudging model to use tools${p.reset}`);let A={role:"user",content:"[SYSTEM] You have full tool access. Use your tools to investigate and implement the fix directly \u2014 do not say you cannot use tools. If SSH is needed, use a single targeted command that captures the most relevant information rather than multiple sequential calls."};T.push(A),q.push(A);continue}if(s.skillLoop&&$&&v>3&&Ro<5){let S=(Mt||lt||"").toLowerCase();if(/\b(i.ll stop|stop the|stopped|done with|complet|summar|conclud|no more|finish|end of|that.s all|final|wrapped up|no further|mindful of|reached.*limit|tool call limit|at this point|recommend keep)/.test(S.slice(-600))){Ro=(Ro||0)+1,F(`${p.yellow} \u26A0 Skill loop: model tried to stop \u2014 continuation nudge #${Ro}${p.reset}`);let Q={role:"user",content:"[SYSTEM] Do NOT stop. You are in an autonomous experiment loop. The user is away and expects you to keep running experiments indefinitely until they interrupt with Ctrl+C. Start the next experiment NOW: hypothesize a new change, checkpoint, edit, run, measure, keep or revert. Think harder \u2014 try a completely different optimization approach."};T.push(Q),q.push(Q);continue}}if(we&&Pe==="plan"&&rn>=2){F(`${p.cyan} \u21B3 Plan phase: ${rn} consecutive blocks \u2014 auto-advancing to implement${p.reset}`),rn=0;let S=ho("implement","[auto-advance: task only requires direct action]");if(S){q.push(S),T.push(S),We=0,Ot=Mn("implement");continue}}if(we&&$){let S=(Mt||lt||"").trim();if(Pe==="plan"){let A=ho("implement",S);if(A){q.push(A),T.push(A),We=0,Ot=Mn("implement");continue}}else if(Pe==="implement"&&R.size>0){let A=q.find(le=>le.role==="user"),Q=typeof A?.content=="string"?A.content:"",D=ho("verify",S,R,Q);if(D){q.push(D),T.push(D),We=0,Ot=Math.min(Mn("verify")+Math.max(0,(R.size-2)*2),20);continue}}else if(Pe==="verify"){let Q=/\bFAIL\b|test.*fail|error|broken|missing|incorrect/i.test(S.slice(0,500));if(Q&&bo<1){bo++;let D={role:"user",content:`[PHASE: RE-IMPLEMENTATION] Verification found issues:
1215
+ ${S.slice(0,400)}
1182
1216
 
1183
- Fix the identified issues. This is the final attempt.`};De="implement",zt=oc("implement",ys),q.push(F),_.push(F),Fe=0,Ct=Cn("implement"),D(`${p.yellow} \u21B3 Verify \u2192 implement loop-back #${$o} (issues found)${p.reset}`);continue}D(`${p.green} \u2713 Verification phase complete${te?" (loop-back exhausted)":" (PASS)"}${p.reset}`)}}if(wo()&&$&&k===0)if(Kr++,Kr>2)D(`${p.yellow} \u26A0 Plan accepted despite no file reads (rejection loop cap reached)${p.reset}`);else{let A={role:"user",content:`[SYSTEM] You wrote a plan without reading any files. This plan may be based on incorrect assumptions (wrong database type, wrong file structure, etc.).
1217
+ Fix the identified issues. This is the final attempt.`};Pe="implement",Vt=$c("implement",_s),q.push(D),T.push(D),We=0,Ot=Mn("implement"),F(`${p.yellow} \u21B3 Verify \u2192 implement loop-back #${bo} (issues found)${p.reset}`);continue}if(F(`${p.green} \u2713 Verification phase complete${Q?" (loop-back exhausted)":" (PASS)"}${p.reset}`),!Q){Fe(v,O,R,k,H),qe(q),ic(q);break e}}}if(_o()&&$&&v===0)if(Vr++,Vr>2)F(`${p.yellow} \u26A0 Plan accepted despite no file reads (rejection loop cap reached)${p.reset}`);else{let S={role:"user",content:`[SYSTEM] You wrote a plan without reading any files. This plan may be based on incorrect assumptions (wrong database type, wrong file structure, etc.).
1184
1218
 
1185
- MANDATORY: Use read_file, glob, or grep to investigate the actual codebase first. Read at least the relevant module file and route file before writing the plan.`};q.push(A),_.push(A),D(`${p.yellow} \u26A0 Plan rejected (${Kr}/2): no files read \u2014 forcing investigation${p.reset}`);continue}if(wo()&&$){let A=(Ot||ct||"").trim();E_(A),ax(A);let I=T_(A);if(I.length>0){let te=q.find(B=>B.role==="user"),F=typeof te?.content=="string"?te.content.slice(0,120):"Task";R_(F,I);let le=I.length===1?"step":"steps",j=!1;if(process.stdout.isTTY&&process.stdin.isTTY){let{approvePlan:B,startExecution:W,setPlanMode:z}=qr();process.stdout.write(`
1186
- ${p.cyan}${p.bold}Plan ready${p.reset} ${p.dim}(${I.length} ${le})${p.reset} ${p.green}[A]${p.reset}${p.dim}pprove${p.reset} ${p.yellow}[E]${p.reset}${p.dim}dit${p.reset} ${p.red}[R]${p.reset}${p.dim}eject${p.reset} ${p.dim}[\u21B5 = approve]:${p.reset} `);let X=process.stdin.isRaw,oe=await new Promise(ue=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",ne=>{try{process.stdin.setRawMode(X||!1)}catch{}let Ne=ne.toString().toLowerCase()[0]||"\r";ue(Ne)})});if(process.stdout.write(`
1187
- `),oe==="r")console.log(`${p.red}Plan rejected.${p.reset} Ask follow-up questions to refine.`);else if(oe==="e")console.log(`${p.yellow}Type /plan edit to open in editor, or give feedback.${p.reset}`);else if(B()){W(),z(!1),cc(),console.log(`${p.green}${p.bold}Approved!${p.reset} Executing ${I.length} ${le}...`);let ue=`[PLAN APPROVED \u2014 EXECUTE NOW]
1219
+ MANDATORY: Use read_file, glob, or grep to investigate the actual codebase first. Read at least the relevant module file and route file before writing the plan.`};q.push(S),T.push(S),F(`${p.yellow} \u26A0 Plan rejected (${Vr}/2): no files read \u2014 forcing investigation${p.reset}`);continue}if(_o()&&$){let S=(Mt||lt||"").trim();G_(S),Tx(S);let A=K_(S);if(A.length>0){let Q=q.find(B=>B.role==="user"),D=typeof Q?.content=="string"?Q.content.slice(0,120):"Task";z_(D,A);let le=A.length===1?"step":"steps",N=!1;if(process.stdout.isTTY&&process.stdin.isTTY){let{approvePlan:B,startExecution:U,setPlanMode:V}=Wr();process.stdout.write(`
1220
+ ${p.cyan}${p.bold}Plan ready${p.reset} ${p.dim}(${A.length} ${le})${p.reset} ${p.green}[A]${p.reset}${p.dim}pprove${p.reset} ${p.yellow}[E]${p.reset}${p.dim}dit${p.reset} ${p.red}[R]${p.reset}${p.dim}eject${p.reset} ${p.dim}[\u21B5 = approve]:${p.reset} `);let J=process.stdin.isRaw,oe=await new Promise(he=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",ne=>{try{process.stdin.setRawMode(J||!1)}catch{}let Me=ne.toString().toLowerCase()[0]||"\r";he(Me)})});if(process.stdout.write(`
1221
+ `),oe==="r")console.log(`${p.red}Plan rejected.${p.reset} Ask follow-up questions to refine.`);else if(oe==="e")console.log(`${p.yellow}Type /plan edit to open in editor, or give feedback.${p.reset}`);else if(B()){U(),V(!1),xc(),console.log(`${p.green}${p.bold}Approved!${p.reset} Executing ${A.length} ${le}...`);let he=`[PLAN APPROVED \u2014 EXECUTE NOW]
1188
1222
 
1189
1223
  Implement the following plan step by step. All tools are now available.
1190
1224
 
1191
- ${A}`;q.push({role:"user",content:ue}),_.push({role:"user",content:ue}),j=!0}}else console.log(`
1192
- ${p.cyan}${p.bold}Plan ready${p.reset} ${p.dim}(${I.length} ${le} extracted).${p.reset} Type ${p.cyan}/plan approve${p.reset}${p.dim} to execute, or ${p.reset}${p.cyan}/plan edit${p.reset}${p.dim} to review.${p.reset}`);if(j){l&&(l.stop(),l=null),Fe--;continue}}else{let te=!1;if(process.stdout.isTTY&&process.stdin.isTTY){let{approvePlan:F,startExecution:le,setPlanMode:j}=qr();process.stdout.write(`
1193
- ${p.cyan}${p.bold}Plan ready.${p.reset} ${p.green}[A]${p.reset}${p.dim}pprove${p.reset} ${p.red}[R]${p.reset}${p.dim}eject${p.reset} ${p.dim}[\u21B5 = approve]:${p.reset} `);let B=process.stdin.isRaw,W=await new Promise(z=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",X=>{try{process.stdin.setRawMode(B||!1)}catch{}z(X.toString().toLowerCase()[0]||"\r")})});if(process.stdout.write(`
1194
- `),W==="r")console.log(`${p.red}Plan rejected.${p.reset} Ask follow-up questions to refine.`);else if(F()){le(),j(!1),cc(),console.log(`${p.green}${p.bold}Approved!${p.reset} Executing...`);let X=`[PLAN APPROVED \u2014 EXECUTE NOW]
1225
+ ${S}`;q.push({role:"user",content:he}),T.push({role:"user",content:he}),N=!0}}else console.log(`
1226
+ ${p.cyan}${p.bold}Plan ready${p.reset} ${p.dim}(${A.length} ${le} extracted).${p.reset} Type ${p.cyan}/plan approve${p.reset}${p.dim} to execute, or ${p.reset}${p.cyan}/plan edit${p.reset}${p.dim} to review.${p.reset}`);if(N){l&&(l.stop(),l=null),We--;continue}}else{let Q=!1;if(process.stdout.isTTY&&process.stdin.isTTY){let{approvePlan:D,startExecution:le,setPlanMode:N}=Wr();process.stdout.write(`
1227
+ ${p.cyan}${p.bold}Plan ready.${p.reset} ${p.green}[A]${p.reset}${p.dim}pprove${p.reset} ${p.red}[R]${p.reset}${p.dim}eject${p.reset} ${p.dim}[\u21B5 = approve]:${p.reset} `);let B=process.stdin.isRaw,U=await new Promise(V=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",J=>{try{process.stdin.setRawMode(B||!1)}catch{}V(J.toString().toLowerCase()[0]||"\r")})});if(process.stdout.write(`
1228
+ `),U==="r")console.log(`${p.red}Plan rejected.${p.reset} Ask follow-up questions to refine.`);else if(D()){le(),N(!1),xc(),console.log(`${p.green}${p.bold}Approved!${p.reset} Executing...`);let J=`[PLAN APPROVED \u2014 EXECUTE NOW]
1195
1229
 
1196
1230
  Implement the following plan step by step. All tools are now available.
1197
1231
 
1198
- ${getPlanContent()||At.content}`;q.push({role:"user",content:X}),_.push({role:"user",content:X}),te=!0}}else console.log(`
1199
- ${p.cyan}${p.bold}Plan ready.${p.reset} ${p.dim}Type ${p.reset}${p.cyan}/plan approve${p.reset}${p.dim} to execute, or ask follow-up questions to refine.${p.reset}`);if(te){l&&(l.stop(),l=null),Fe--;continue}}}if(l&&(l.stop(),l=null),c(null),We(k,N,T,S,J),bt&&T.size>=3){let A=[...T].map(j=>j.split("/").pop()).slice(0,8).join(", "),I=[...T].some(j=>j.endsWith("package.json")),te=[...T].some(j=>j.endsWith("requirements.txt")),F=[...T].some(j=>j.endsWith("package-lock.json")||j.endsWith("yarn.lock")||j.endsWith("pnpm-lock.yaml")),le=I&&!F?"npm install not yet run":te?"pip install not yet run":null;yo=`[Previous session created ${T.size} files: ${A}`+(le?` \u2014 ${le}`:"")+". Use this context to answer follow-up questions without re-reading files.]"}if(bt&&!dc&&k>0){let A=[...T].some(X=>X.endsWith("package.json")),I=[...T].some(X=>X.endsWith("requirements.txt")||X.endsWith("Pipfile")||X.endsWith("pyproject.toml")),te=[...T].some(X=>X.endsWith("package-lock.json")||X.endsWith("yarn.lock")||X.endsWith("pnpm-lock.yaml")),F=q.flatMap(X=>{let oe=Array.isArray(X.tool_calls)?X.tool_calls:[],ue=Array.isArray(X.content)?X.content.filter(ne=>ne?.type==="tool_use"):[];return[...oe,...ue]}).filter(X=>{let oe=X.function?.name||X.name||"";return oe==="bash"||oe==="Bash"}).map(X=>{try{let oe=X.function?.arguments??X.input??{};return(typeof oe=="string"?JSON.parse(oe):oe)?.command||""}catch{return""}}),le=F.some(X=>/pip\s+install|python\s+-m\s+venv/.test(X)),j=F.some(X=>/npm\s+install/.test(X)),W=[...T].some(X=>/\/App\.(js|ts|jsx|tsx)$/.test(X))&&!A&&!j;if(I&&!le||A&&!te&&!j||W){dc=!0;let X=[];I&&!le&&X.push("python -m venv venv && source venv/bin/activate && pip install -r requirements.txt"),W?X.push("create package.json for the React frontend (with react, react-dom, react-scripts dependencies), then run npm install"):A&&!te&&!j&&X.push("npm install");let oe=`[FRAMEWORK \u2014 post-creation check] You wrote dependency files but never ran the installer. Run now: ${X.join(" && ")}. Verify it succeeds, fix any errors, then write a closing summary.`;D(`${p.dim} [post-creation] bootstrapping environment (${X.join(", ")})${p.reset}`),q.push({role:"user",content:oe}),_.push({role:"user",content:oe});continue}}if(k>0&&!s._isSummaryTurn&&m_(Ot))try{D(`${p.dim} [post-turn] terse ending \u2014 requesting diagnosis/summary${p.reset}`);let A=T.size>0?"Write a closing summary (3+ sentences): what files changed and why, what the result is, anything the user should know or do next.":"Write a closing diagnosis (3+ sentences): what you investigated, what you found, and what the user should do next or what the root cause is.",I=[..._,{role:"user",content:A}],F=((await Up(I,[],{}))?.content||"").trim();F&&(console.log(`
1200
- ${F}`),q.push({role:"user",content:A},{role:"assistant",content:F}))}catch{}Be(q),Hp(q);return}k++,oi++,k>=1&&(xe=!1);for(let $ of Bt){let y=$.function.name;N.set(y,(N.get(y)||0)+1)}if(k>=30&&!nh){nh=!0,D(`${p.yellow} \u26A0 Tool budget warning: ${k} tool calls used \u2014 nudging model to wrap up${p.reset}`);let $={role:"user",content:"[SYSTEM] \u26A0 You have used "+k+" tool calls. This is approaching the quality threshold (40). Wrap up NOW: write your final summary and stop. Do NOT run additional verification commands (git status, git diff, git log) \u2014 your changes are already committed and verified. Further tool calls will hurt session quality."};q.push($),_.push($)}let pe=await Promise.all(Bt.map($=>cx($)));{let $=Et(_,Ze()),y=$.percentage,ee=pe.some(F=>F.canExecute&&F.fnName==="read_file"&&!F.args?.line_end),A=pe.filter(F=>F.canExecute&&F.fnName==="read_file"&&F.args?.path&&An(So,F.args.path)>=1&&!F.args?.line_start).map(F=>F.args.path.split("/").slice(-2).join("/")),I=A.length>0;if(y>=70&&ee&&li<70||y>=85&&li<85||I){li=y;let F=y>=85?"URGENT":"WARNING",le;I?(F="WARNING",le=`Full-file read of ${A.join(", ")} already done \u2014 use line_start/line_end for specific sections instead.`):ee?le=`Unbounded read at ${Math.round(y)}% context \u2014 use line_start/line_end to avoid overflow.`:le="Use targeted reads (line_start/line_end) to save space.";let j={role:"user",content:`[SYSTEM ${F}] Context ${Math.round(y)}% used (${$.used}/${$.limit} tokens). ${le}`};if(q.push(j),_.push(j),y>=85){let B=I?` (re-read of: ${A.join(", ")})`:"";D(`${p.yellow} \u26A0 Context ${Math.round(y)}% used \u2014 agent warned to use targeted reads${B}${p.reset}`)}}}let mi=new Map;for(let $ of pe){if(!$.canExecute||$.fnName!=="read_file")continue;let y=$.args?.path;if(!y)continue;let ee=An(So,y),A=mi.get(y)||0,I=ee+A,te=$.args?.line_start!=null,F=Nn.get(y)||0,le=F>0,j=2;if(I>=bs){let B=y.split("/").slice(-2).join("/"),W=(jn.get(y)||0)+1;if(jn.set(y,W),W===1)D(`${p.red} \u2716 Blocked: "${B}" read ${I}\xD7 \u2014 hard cap (${bs}) reached${p.reset}`);else if(W===2){D(`${p.red} \u2716 Escalated block: "${B}" \u2014 model ignored BLOCKED, injecting system warning${p.reset}`);let z={role:"user",content:`[SYSTEM WARNING] You already received a BLOCKED error for read_file("${y}") and tried again anyway. This file has reached its read cap (${bs}\xD7). Do NOT attempt to read it again. Use grep_search to find specific content, or proceed with what you already know.`};q.push(z),_.push(z)}$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 file already read ${I}\xD7 (hard cap: ${bs}). You have seen enough of this file. Use grep to find specific content or proceed with what you know.`,tool_call_id:$.callId}}else if(I>=1&&te)if(le&&F<=j){let B=y.split("/").slice(-2).join("/");console.log(`${p.cyan} \u21A9 Targeted re-read: "${B}" (line_start=${$.args.line_start}) \u2014 edit recovery #${F}${p.reset}`),Nn.set(y,F-1)}else if(le&&F>j){let B=y.split("/").slice(-2).join("/");D(`${p.red} \u2716 Edit recovery blocked: "${B}" \u2014 ${j} recovery reads already used. Use grep to find the exact line numbers, then retry.${p.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 edit recovery budget exhausted (${j} recovery reads used). You already have the file content. Use grep_search to find the exact line numbers of the text you want to change, then retry edit_file with the exact text shown.`,tool_call_id:$.callId}}else{let B=$.args.line_start||1,W=$.args.line_end||B+350,z=tn.get(y)||[],X=!1;for(let[oe,ue]of z){let ne=Math.max(B,oe),Ne=Math.min(W,ue);if(Ne>ne){let Xe=Ne-ne,xt=W-B||1,lt=ue-oe||1,Wt=Xe/lt>=.7&&Xe/xt<.7;if(!(W-B<=Wh)&&(Xe/xt>=.7||Xe/lt>=.7)){let Fn=y.split("/").slice(-2).join("/"),Uc=`${y}:${B}-${W}`,Bn=(ni.get(Uc)||0)+1;if(ni.set(Uc,Bn),D(Wt?`${p.red} \u2716 Blocked superread: "${Fn}" lines ${B}-${W} subsumes already-read ${oe}-${ue} \u2014 use line_start=${ue+1} to skip known content (block #${Bn})${p.reset}`:`${p.red} \u2716 Blocked duplicate read: "${Fn}" lines ${B}-${W} (\u226570% overlap with lines ${oe}-${ue} already in context, block #${Bn})${p.reset}`),Bn>=2){D(`${p.red} \u2716 Escalated range-block: "${Fn}" lines ${B}-${W} \u2014 model ignored BLOCKED, injecting system warning${p.reset}`);let Hc={role:"user",content:Wt?`[SYSTEM] Read blocked ${Bn}\xD7 for read_file("${y}", lines ${B}-${W}). Lines ${oe}-${ue} were already read. Use line_start=${ue+1} to read only new content, or use grep_search for specific lines.`:`[SYSTEM] Read blocked ${Bn}\xD7 for read_file("${y}", lines ${B}-${W}). Lines ${oe}-${ue} were already read and will NOT change. Use grep_search to find specific content instead.`};q.push(Hc),_.push(Hc)}$.canExecute=!1,$.errorResult={role:"tool",content:Wt?`BLOCKED: read_file("${y}", lines ${B}-${W}) re-reads lines ${oe}-${ue} already in context. Use line_start=${ue+1} to read only the new content beyond line ${ue}.`:`BLOCKED: read_file("${y}", lines ${B}-${W}) is a duplicate \u2014 lines ${oe}-${ue} are already in your context (\u226570% overlap). Use grep to find specific content instead of re-reading.`,tool_call_id:$.callId},X=!0;break}}}if(!X){let oe=z.length,ue=2;if(oe>=3){let Ne=y.split("/").slice(-2).join("/");D(`${p.red} \u2716 Blocked file-scroll: "${Ne}" \u2014 ${oe} sections already read. Use grep to find specific content.${p.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 you have already read ${oe} different sections of this file (file-scroll pattern). You have seen most of this file. Use grep_search to find the exact lines you need instead of continuing to scroll.`,tool_call_id:$.callId}}else oe>=ue&&($._scrollWarn={sectionCount:oe+1,path:y})}}else if(I>=1){let B=y.split("/").slice(-2).join("/"),W=(jn.get(y)||0)+1;if(jn.set(y,W),W===1)D(`${p.red} \u2716 Blocked unbounded re-read: "${B}" \u2014 already in context. Use line_start/line_end for specific sections.${p.reset}`);else if(W===2){D(`${p.red} \u2716 Escalated block: "${B}" \u2014 model ignored unbounded re-read block, injecting system warning${p.reset}`);let z={role:"user",content:`[SYSTEM] read_file("${y}") was blocked again \u2014 full-file reads are disabled after the first read. Use line_start/line_end for a specific section, or use grep_search to find what you need.`};q.push(z),_.push(z)}$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 file already in context (read ${I}\xD7). Use line_start/line_end to read a specific section instead of the full file.`,tool_call_id:$.callId}}$.canExecute&&mi.set(y,(mi.get(y)||0)+1)}if(en>=3)for(let $ of pe)$.canExecute&&($.fnName!=="read_file"&&$.fnName!=="edit_file"||(D(`${p.red} \u2716 Blocked ${$.fnName} \u2014 ${en} consecutive file-not-found errors, must search first${p.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: ${en} consecutive "File not found" errors. You must call search_files or glob_files to locate the correct path before reading or editing. Do not guess file paths.`,tool_call_id:$.callId}));for(let $ of pe){if(!$.canExecute||$.fnName!=="bash")continue;let y=($.args?.command||"").trim();if(/^\s*ls(\s+-[a-zA-Z]+)*(\s+\S+)?\s*$/.test(y)&&!/npm|yarn|pnpm|make|git/.test(y)){D(`${p.red} \u2716 Blocked bash ls \u2014 use list_directory tool instead${p.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:'BLOCKED: bash("ls ...") denied \u2014 use the list_directory tool instead. It returns structured output and does not penalize the session score.',tool_call_id:$.callId};continue}/\bfind\s+[\S.]/.test(y)&&!/git\s|npm\s|yarn\s|-exec\s+\S|-execdir/.test(y)&&(D(`${p.red} \u2716 Blocked bash find \u2014 use glob tool with a pattern instead${p.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:'BLOCKED: bash("find ...") denied \u2014 use the glob tool with a pattern like "**/*.py" or "src/**/*.js" instead. It is faster and does not penalize the session score.',tool_call_id:$.callId})}for(let $ of pe)$.canExecute&&($.fnName!=="ssh_exec"&&$.fnName!=="bash"||/\bsed\s+-n\b/.test($.args?.command||"")&&(D(`${p.red} \u2716 Blocked sed -n: use grep -n "pattern" <file> | head -30 instead${p.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:'BLOCKED: sed -n is forbidden \u2014 it floods context with line ranges. Use grep -n "pattern" <file> | head -30 to read a specific section, or cat <file> for the full file.',tool_call_id:$.callId}));for(let $ of pe){if(!$.canExecute||$.fnName!=="write_file")continue;let y=$.args?.path,ee=$.args?.content||"";if(y)try{let A=require("fs"),I=require("path").resolve(process.cwd(),y);if(A.existsSync(I)){let te=A.statSync(I).size,F=Buffer.byteLength(ee,"utf8"),le=te>0?F/te:1;if(le<.6&&te>200){let j=y.split("/").slice(-2).join("/");console.log(`${p.red} \u2716 write_file shrink guard: "${j}" would shrink to ${Math.round(le*100)}% of original \u2014 likely context loss${p.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: write_file("${y}") denied \u2014 new content is only ${Math.round(le*100)}% of current file size (${te} \u2192 ${F} bytes). This looks like a partial rewrite after context loss. Use edit_file/patch_file to add only the new code, or read the file first to see full content before replacing.`,tool_call_id:$.callId}}}}catch{}}let qc=new Map;for(let $ of pe){if(!$.canExecute||$.fnName!=="grep")continue;let y=$.args?.path;if(!y)continue;let ee=qc.get(y)||0,A=An(Oc,y)+ee;if(A>=Nc){let I=y.split("/").slice(-2).join("/");D(`${p.red} \u2716 Blocked grep: "${I}" grepped ${A}\xD7 with different patterns \u2014 flood threshold exceeded${p.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: grep("${y}") denied \u2014 ${A} patterns already tried. Use existing results or read the file instead.`,tool_call_id:$.callId}}$.canExecute&&qc.set(y,ee+1)}let zh=5,Fc=new Map;for(let $ of pe){if(!$.canExecute||$.fnName!=="ssh_exec")continue;let ee=($.args?.command||"").replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),A=Fc.get(ee)||0,I=An(Ac,ee)+A;I>=zh&&(D(`${p.yellow} \u26A0 Blocked ssh_exec: same command run ${I}\xD7 \u2014 result already in context${p.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: ssh_exec denied \u2014 this command has already run ${I} times and the output is in your context. Use existing results, try a different command, or run it as a local bash call: bash("ssh user@host 'your command'").`,tool_call_id:$.callId}),$.canExecute&&Fc.set(ee,A+1)}if(ht){let $=pe.filter(A=>A.canExecute&&A.fnName==="ssh_exec"),y=pe.some(A=>A.canExecute&&A.fnName!=="ssh_exec"),ee=w&&P<3;if($.length>0&&!y&&ee&&Xr<1)ht=!1,Xr++,wt=Math.max(0,_s-2),D(`${p.dim} [dual-block deadlock: SSH storm relaxed \u2014 allowing 1 SSH call (relax ${Xr}/1)]${p.reset}`);else for(let A of $)A.canExecute=!1,A.errorResult={role:"tool",content:Ye?`BLOCKED: ssh_exec denied \u2014 SSH paused (${_s}+ calls). Root cause is known (${it}). Edit the file now. You can still use bash("ssh user@host 'cmd'") for a single targeted lookup if essential.`:`BLOCKED: ssh_exec denied \u2014 SSH temporarily paused (${_s}+ calls). Provide a text summary of your findings first. Do NOT ask the user to run commands. SSH re-enables after your summary. For one-off lookups use bash("ssh user@host 'cmd'") instead.`,tool_call_id:A.callId}}if(w&&P<3&&!ht){for(let $ of pe)if($.canExecute&&["bash","read_file","find_files"].includes($.fnName)){P++;{let y=Ze(),{messages:ee}=It(_,y);_=ee}D(`${p.yellow} \u26A0 Jarvis-local guard: blocking local ${$.fnName} \u2014 use ssh_exec on 94.130.37.43${p.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: ${$.fnName} denied \u2014 this is a server issue. Use ssh_exec on 94.130.37.43 instead.`,tool_call_id:$.callId};break}}if(!$e&&Tt&&bt&&Rt>=1){let $=["read_file","grep","search_files","glob","list_directory","find_files"];for(let y of pe)y.canExecute&&$.includes(y.fnName)&&(D(`${p.red} \u2716 Creation hard-block: ${y.fnName} denied \u2014 cap fired, files already written${p.reset}`),y.canExecute=!1,y.errorResult={role:"tool",content:"BLOCKED: files already written \u2014 continue with write_file or edit_file to finish the remaining tasks. Do not read more files.",tool_call_id:y.callId})}if(Mn>=0){let $=pe.filter(y=>y.canExecute).length;if($>0&&(Mn-=$,Mn<0))if(!Jr&&T.size>Vr){Jr=!0,Mn=5,D(`${p.green} \u2713 Post-wipe progress detected (${T.size-Vr} files modified) \u2014 granting 5 bonus tool calls${p.reset}`);let y={role:"user",content:"[SYSTEM] Progress detected \u2014 5 bonus tool calls granted. Budget: 5 remaining."};q.push(y),_.push(y)}else{D(`${p.red} \u2716 Post-wipe tool budget exhausted \u2014 blocking all tool calls${p.reset}`);for(let ee of pe)ee.canExecute&&(ee.canExecute=!1,ee.errorResult={role:"tool",content:"BLOCKED: post-wipe tool budget exhausted. No further tool calls are allowed. Summarise what was accomplished and stop.",tool_call_id:ee.callId});let y={role:"user",content:"[SYSTEM] Post-wipe tool budget exhausted. All tool calls are now blocked. Respond with a final summary of what was done and stop \u2014 do not attempt any more tool calls."};q.push(y),_.push(y)}}let Xh=new Set(["edit_file","write_file","bash","ssh_exec","ask_user","spawn_agents","browser_click","browser_fill","browser_open","skill_ar_run_experiment","skill_ar_run_benchmark","skill_ar_checkpoint","skill_ar_revert","skill_ar_log_experiment","skill_ar_extract_metric"]);for(let $ of pe){if(!$.canExecute||Xh.has($.fnName))continue;let y=JSON.stringify($.args||{}),ee=`${$.fnName}|${y}`,A=An(si,ee);A>=2?(D(`${p.red} \u2716 Blocked duplicate: ${$.fnName}(${y.substring(0,80)}) \u2014 called ${A+1}\xD7 with identical args${p.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: ${$.fnName}() with these exact arguments has already been called ${A}\xD7 \u2014 the result is already in your context. Use the existing output instead of repeating the same call.`,tool_call_id:$.callId}):A===1&&D(`${p.yellow} \u26A0 Duplicate tool call: ${$.fnName}(${y.substring(0,80)}) \u2014 2nd call with identical args${p.reset}`),On(si,ee)}let xs=l?{skipSpinner:!0,skipSummaries:!0}:{},Vh=pe.some($=>$.fnName==="ask_user"),Bc=!xs.skipSummaries&&!xe,Ao=null;Bc&&!Vh?(xe=!0,xs.skipSpinner=!0,process.stdout.isTTY?(process.stdout.write(Wr(pe,k,!1,"blink")),Ao=!0):qt||process.stdout.write(Wr(pe,k,!1)+`
1201
- `)):Bc&&(xe=!0,xs.skipSpinner=!0),l&&l._paused&&l.resume();let Oo=null;if(Ao&&process.stdout.isTTY&&pe.some(y=>y.canExecute&&(y.fnName==="bash"||y.fnName==="ssh_exec"))){let y=Date.now();Oo=setInterval(()=>{let ee=Math.round((Date.now()-y)/1e3);ee>=3&&process.stdout.write(`\r\x1B[2K${Wr(pe,k,!1,"blink")} ${p.dim}[${ee}s]${p.reset}`)},1e3)}let{results:Nt,summaries:Jh}=await fx(pe,!0,{...xs,skipSummaries:!0});if(Oo&&(clearInterval(Oo),Oo=null),Ao&&(Ao=null,process.stdout.write(`\r\x1B[2K${Wr(pe,k,!1)}
1202
- `)),!xs.skipSummaries){let $=Jh.filter((A,I)=>!(pe[I]&&pe[I].fnName==="ask_user"));for(let A of $)console.log(A);console.log("");let y=pe.filter(A=>A&&A.fnName!=="ask_user").map(A=>A.fnName),ee=Re.record(0,y,S,T);ee&&H_(ee)}for(let $ of pe){if($.canExecute||!$.errorResult)continue;let y=typeof $.errorResult.content=="string"?$.errorResult.content:"";if((y.startsWith("BLOCKED:")||y.startsWith("PLAN MODE:"))&&(on++,on>=Mc)){D(`${p.red} \u2716 Loop abort: ${on} consecutive blocked calls (pre-execution) \u2014 model not heeding BLOCKED messages${p.reset}`),l&&(l.stop(),l=null),c(null),We(k,N,T,S,J,{suppressHint:!0}),Be(q);return}}for(let $=0;$<pe.length;$++){let y=pe[$];if(!y.canExecute)continue;let ee=Nt[$].content,A=ee.split(`
1203
- `)[0],I=!A.startsWith("ERROR")&&!A.startsWith("CANCELLED")&&!A.startsWith("Command failed")&&!A.startsWith("EXIT");if(!I&&(y.fnName==="edit_file"||y.fnName==="patch_file")&&y.args?.path&&A.includes("old_text not found")){let j=Nn.get(y.args.path)||0;Nn.set(y.args.path,j+1)}if(!I&&(y.fnName==="read_file"||y.fnName==="edit_file")&&/file not found|does not exist|ENOENT/i.test(A)){if(en++,en>=2){D(`${p.yellow} \u26A0 File-not-found streak: ${en} consecutive misses \u2014 forcing search${p.reset}`);let j={role:"user",content:`[SYSTEM] ${en} 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.`};q.push(j),_.push(j)}}else I&&(y.fnName==="read_file"||y.fnName==="edit_file"||y.fnName==="search_files"||y.fnName==="glob_files")&&(en=0);if(I&&y.fnName==="write_file"&&y.args?.path){let j=y.args.path.split("/").pop(),B=y.args.path.includes("/tests/")||y.args.path.includes("\\tests\\");if(/^(test_|demo_|temp_|tmp_|scratch_)/.test(j)&&!B){D(`${p.yellow} \u26A0 Temp file: "${j}" \u2014 delete with bash rm when done to keep the workspace clean${p.reset}`);let z={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.`};q.push(z),_.push(z)}}if(I&&["write_file","edit_file","patch_file"].includes(y.fnName)&&y.args&&y.args.path){Nn.delete(y.args.path),T.add(y.args.path);let j=On(Ce,y.args.path),B=y.args.path.split("/").slice(-2).join("/");if(j===Th){D(`${p.yellow} \u26A0 Loop warning: "${B}" edited ${j}\xD7 \u2014 possible edit loop${p.reset}`);let W={role:"user",content:`[SYSTEM WARNING] "${y.args.path}" edited ${j}\xD7. One more edit max, then move on.`};q.push(W),_.push(W)}else if(j>=Rh){D(`${p.red} \u2716 Loop abort: "${B}" edited ${j}\xD7 \u2014 aborting to prevent runaway loop${p.reset}`),l&&(l.stop(),l=null),c(null),We(k,N,T,S,J,{suppressHint:!0}),Be(q);return}}if(I&&y.canExecute&&$e&&(nn=0),I&&y.canExecute&&!($e&&De==="plan")){let j=["read_file","grep","search_files","glob","list_directory","ssh_exec","find_files"];["write_file","edit_file","patch_file"].includes(y.fnName)?(jt=0,Tt=!1,Kt=0,Rt++):j.includes(y.fnName)&&(jt++,Tt&&Kt++);let W=n.postEditCap,z=$e&&De==="implement"?Math.min(Lc,6):Lc,X=Ye?3:bt?Rt>0?2:4:Rt>0?W:z,oe=3;if(!$e&&Tt&&(Ye||bt&&Rt>=1||Kt>=oe)&&j.includes(y.fnName)){let ne=Ye?`root cause already identified (${it})`:Kt>=oe?`${jt} consecutive reads without an edit`:`${Rt} file edit(s) already made`;D(`${p.red} \u2716 Blocked read-only tool: cap fired, ${ne}${p.reset}`),y.canExecute=!1,y.errorResult={role:"tool",content:Ye?`BLOCKED: root cause already identified (${it}). Use edit_file to fix the issue \u2014 do not read more files.`:bt?"BLOCKED: files already written \u2014 continue with write_file or edit_file to finish the remaining tasks. Do not read more files.":Kt>=oe?`BLOCKED: You have read ${jt} files without making any edits. Stop investigating and either implement a fix with edit_file/write_file, or write your diagnosis as text output. Do not read more files.`:`BLOCKED: ${Rt} file edit(s) already made and post-edit investigation cap reached. The fix is in place. Do not read more files \u2014 proceed with the task.`,tool_call_id:y.callId}}else if(jt>=X&&!Tt){if(Tt=!0,D(`${p.yellow} \u26A0 Investigation cap: ${jt} read-only calls without an edit \u2014 forcing implementation${p.reset}`),$e&&De==="plan"){let Xe=[..._].reverse().find(Wt=>Wt.role==="assistant"),xt=typeof Xe?.content=="string"?Xe.content:"",lt=fo("implement",xt);lt&&(q.push(lt),_.push(lt),Fe=0,Ct=Cn("implement"))}let ne;Ye?ne=`[SYSTEM] Root cause was already identified (${it}). Edit the file now \u2014 do not read more files.`:ht?ne="[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.":ne="[SYSTEM] You have read enough files. Now implement your fix using edit_file.";let Ne={role:"user",content:ne};q.push(Ne),_.push(Ne)}}if((y.fnName==="bash"||y.fnName==="ssh_exec")&&y.args&&y.args.command){let j=y.args.command.replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),B=On(Ac,j);if(B===Ch){D(`${p.yellow} \u26A0 Loop warning: same bash command run ${B}\xD7 \u2014 possible debug loop${p.reset}`);let W={role:"user",content:`[SYSTEM WARNING] Same bash command ${B}\xD7. Debug loop detected \u2014 try a different approach.`};q.push(W),_.push(W)}else if(B>=Ah){D(`${p.red} \u2716 Loop abort: same bash command run ${B}\xD7 \u2014 aborting runaway debug loop${p.reset}`),l&&(l.stop(),l=null),c(null),We(k,N,T,S,J,{suppressHint:!0}),Be(q);return}}if(y.fnName==="ssh_exec"){wt++;{let W=(Nt[$]?.content??"").split(`
1204
- `).map(z=>z.trim()).find(z=>z.length>0&&!z.startsWith("**")&&(z.startsWith("EXIT")||/^[\w./-]+:\s/.test(z)||z.startsWith("bash:")||z.startsWith("sh:")))??"";if(W){if(W===Zr?Ln++:(Zr=W,Ln=1),Ln===3&&!ht){D(`${p.yellow} \u26A0 SSH repeated-error: "${W.slice(0,60)}" returned ${Ln}\xD7 \u2014 nudging to change approach${p.reset}`);let z={role:"user",content:`[SYSTEM WARNING] The last ${Ln} SSH commands all failed with the same error: "${W}". Retrying variants of the same command will not help. Switch to a different approach to accomplish the task (e.g. use a different tool, read a local file, or change the command syntax entirely).`};q.push(z),_.push(z)}}else Zr="",Ln=0}if(wt>=Kh){D(`${p.red} \u2716 SSH storm abort: ${wt} consecutive ssh_exec calls \u2014 aborting${p.reset}`),l&&(l.stop(),l=null),c(null),We(k,N,T,S,J,{suppressHint:!0}),Be(q);return}else if(wt===_s){{let W=Ze(),{messages:z}=It(_,W);_=z}ht=!0,Hr++,D(`${p.yellow} \u26A0 SSH storm warning (#${Hr}): ${wt} consecutive ssh_exec calls \u2014 blocking further SSH${p.reset}`);let B={role:"user",content:Ye?`[SYSTEM WARNING] ${wt} consecutive SSH calls. Root cause identified (${it}). Read the file that needs fixing, then edit it.`:`[SYSTEM WARNING] ${wt} 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.`};q.push(B),_.push(B)}}else y.canExecute&&(wt=0);if(y.fnName==="bash"&&y.canExecute){let W=(Nt[$]?.content??"").split(`
1205
- `).map(z=>z.trim()).find(z=>z.length>0&&(z.startsWith("EXIT")||/^[\w./-]+:\s/.test(z)||z.startsWith("bash:")||z.startsWith("sh:")))??"";if(W){if(W===Qr?Pn++:(Qr=W,Pn=1),Pn===3){D(`${p.yellow} \u26A0 Bash repeated-error: "${W.slice(0,60)}" returned ${Pn}\xD7 \u2014 nudging to change approach${p.reset}`);let z={role:"user",content:`[SYSTEM WARNING] The last ${Pn} bash commands all failed with the same error: "${W}". Retrying variants of the same command will not help. Switch to a completely different approach (e.g. use a different tool, change the command syntax, or use ssh_exec to run the command on the remote server instead).`};q.push(z),_.push(z)}}else Qr="",Pn=0}if(y.fnName==="bash"&&y.canExecute&&!sc&&y.args?.command){let j=Nt[$]?.content??"";if(/git\s+commit\b/.test(y.args.command)&&!j.startsWith("EXIT")&&!j.startsWith("ERROR")&&(/\[\S+\s+[a-f0-9]+\]/.test(j)||j.includes("files changed")||j.includes("file changed")||j.includes("insertions(+)")||j.includes("create mode"))){sc=!0,uo=0,D(`${p.green} \u2713 Git commit detected \u2014 post-commit verification cap active (max 2 git status/diff/log)${p.reset}`);let z={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."};q.push(z),_.push(z)}}if(sc&&y.fnName==="bash"&&y.args?.command&&/git\s+(status|diff|log|show)\b/.test(y.args.command)&&(uo++,uo>2)){D(`${p.yellow} \u26A0 Post-commit git verification blocked (call ${uo})${p.reset}`);let B={role:"user",content:"[SYSTEM] \u26A0 STOP: You already ran "+(uo-1)+" git verification commands after committing. The commit is confirmed. Write your final summary NOW and do not make any more tool calls."};q.push(B),_.push(B)}if(I&&y.fnName==="grep"&&y.args&&y.args.pattern){let j=`${y.args.pattern}|${y.args.path||""}`,B=On(Oh,j);if(B===Nh){D(`${p.yellow} \u26A0 Loop warning: grep pattern "${y.args.pattern.slice(0,40)}" run ${B}\xD7 \u2014 possible search loop${p.reset}`);let W={role:"user",content:`[SYSTEM WARNING] Same grep pattern ${B}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};q.push(W),_.push(W)}else if(B>=Mh){D(`${p.red} \u2716 Loop abort: grep pattern run ${B}\xD7 \u2014 aborting runaway search loop${p.reset}`),l&&(l.stop(),l=null),c(null),We(k,N,T,S,J,{suppressHint:!0}),Be(q);return}if(y.args.path){let W=On(Oc,y.args.path),z=An(So,y.args.path)>=1;if(W===(z?1:Lh)){let oe=y.args.path.split("/").slice(-2).join("/");D(`${p.yellow} \u26A0 Loop warning: "${oe}" grepped ${W}\xD7 with different patterns \u2014 context flood risk${p.reset}`);let ue={role:"user",content:z?`[SYSTEM NOTE] "${y.args.path}" was already fully read \u2014 its content is in context. Grepping it again is redundant; use the context you already have.`:`[SYSTEM NOTE] "${y.args.path}" grepped ${W}\xD7 \u2014 use the search results already in context instead of searching again.`};q.push(ue),_.push(ue)}}}if(I&&(y.fnName==="glob"||y.fnName==="glob_files"||y.fnName==="search_files")&&y.args){let j=y.args.pattern||y.args.query||y.args.path||"",B=On(Ph,j);if(B===Ih){D(`${p.yellow} \u26A0 Loop warning: glob pattern "${j.slice(0,40)}" run ${B}\xD7 \u2014 possible search loop${p.reset}`);let z={role:"user",content:`[SYSTEM WARNING] Same glob/search pattern ${B}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};q.push(z),_.push(z)}else if(B>=jh){D(`${p.red} \u2716 Loop abort: glob pattern run ${B}\xD7 \u2014 aborting runaway search loop${p.reset}`),l&&(l.stop(),l=null),c(null),We(k,N,T,S,J,{suppressHint:!0}),Be(q);return}let W=j.replace(/\*+/g," ").replace(/[{}()\[\],.\/\\]/g," ").split(/\s+/).filter(z=>z.length>=4&&!/^\.(js|ts|py|json|md|yaml|yml|txt|css|html|sh)$/.test(z));for(let z of W){let X=z.toLowerCase();_o.has(X)||_o.set(X,new Set);let oe=_o.get(X);if(oe.add(j),oe.size===qh){D(`${p.red} \u2716 Glob core-term block: ${oe.size} different patterns all searching for "${X}" \u2014 search loop${p.reset}`);let ue={role:"user",content:`[SYSTEM WARNING] You have searched for "${X}" using ${oe.size} different glob patterns. This is a search loop \u2014 the file you are looking for likely does not exist. Stop searching and work with the files you have already found, or ask the user for clarification.`};q.push(ue),_.push(ue)}else if(oe.size===Dh){D(`${p.yellow} \u26A0 Glob core-term warning: ${oe.size} different patterns searching for "${X}"${p.reset}`);let ue={role:"user",content:`[SYSTEM WARNING] ${oe.size} different glob patterns all target "${X}". If previous searches returned no results, the file probably does not exist \u2014 stop searching and proceed with available information.`};q.push(ue),_.push(ue)}}}let te=(y.args?.command||y.args?.cmd||y.args?.script||"").toLowerCase(),F=/\b(health|healthcheck|health-check|status|check|ping|validate|alive|ready)\b/.test(te)||/\/(health|status|ping|ready|alive)\b/.test(te);if(I&&(y.fnName==="bash"||y.fnName==="ssh_exec")&&F&&ee.includes('"valid":true')){{let B=Ze();if(Et(_,B).percentage>=60){let{messages:z,tokensRemoved:X}=It(_,B);X>0&&(_=z,console.log(`${p.dim} [pre-stop-compress \u2014 ~${X} tokens freed before STOP injection, now ${Math.round(Et(_,B).percentage)}%]${p.reset}`))}}let j={role:"user",content:'[SYSTEM STOP] Tool result contains {"valid":true}. The token/service is valid and reachable. STOP all further investigation immediately. Report to the user that the token is valid, the service is healthy, and no fix is needed. Do NOT read any more log files.'};q.push(j),_.push(j),console.log(`${p.cyan} \u2713 Health-check stop signal detected \u2014 injecting STOP instruction${p.reset}`)}if(ee.startsWith("BLOCKED:")){if(on++,on>=Mc){D(`${p.red} \u2716 Loop abort: ${on} consecutive blocked calls \u2014 model not heeding BLOCKED messages${p.reset}`),l&&(l.stop(),l=null),c(null),We(k,N,T,S,J,{suppressHint:!0}),Be(q);return}}else on=0;if(I)sn=0,di=!0;else if(sn++,sn===Uh){D(`${p.yellow} \u26A0 Loop warning: ${sn} consecutive tool errors \u2014 possible stuck loop${p.reset}`);let j={role:"user",content:`[SYSTEM WARNING] ${sn} consecutive errors. Stuck loop \u2014 try fundamentally different approach or declare done.`};q.push(j),_.push(j)}else if(sn>=Hh){D(`${p.red} \u2716 Loop abort: ${sn} consecutive errors \u2014 aborting stuck loop${p.reset}`),l&&(l.stop(),l=null),c(null),We(k,N,T,S,J,{suppressHint:!0}),Be(q);return}if(I&&y.fnName==="read_file"&&y.args&&y.args.path){S.add(y.args.path);let j=On(So,y.args.path);if(y.args.line_start!=null){let X=y.args.line_start||1,oe=y.args.line_end||X+350;tn.has(y.args.path)||tn.set(y.args.path,[]),tn.get(y.args.path).push([X,oe])}if(y._scrollWarn){let{sectionCount:X,path:oe}=y._scrollWarn,ue={role:"user",content:`[SYSTEM WARNING] "${oe}" \u2014 you have now read ${X} different sections of this file. This is a file-scroll pattern. Stop reading sections and use grep_search to find the specific lines you need instead.`};q.push(ue),_.push(ue),D(`${p.yellow} \u26A0 Scroll warning: "${oe.split("/").slice(-2).join("/")}" \u2014 ${X} sections read \u2014 use grep instead${p.reset}`)}let B=y.args.path.split("/").slice(-2).join("/"),W=!y.args?.line_start&&!y.args?.line_end,z=$e&&De==="plan";if(!z&&W&&j===Fh){{let oe=Ze();if(Et(_,oe).percentage>=60){let{messages:ne}=It(_,oe);_=ne}}D(`${p.yellow} \u26A0 Loop warning: "${B}" read unbounded ${j}\xD7 \u2014 use line_start/line_end${p.reset}`);let X={role:"user",content:`[SYSTEM WARNING] "${y.args.path}" read ${j}\xD7 without line ranges. Use line_start/line_end to read specific sections \u2014 do not re-read the full file.`};q.push(X),_.push(X)}else if(!z&&W&&j>=Bh){D(`${p.red} \u2716 Loop abort: "${B}" read unbounded ${j}\xD7 \u2014 aborting runaway read loop${p.reset}`),l&&(l.stop(),l=null),c(null),We(k,N,T,S,J,{suppressHint:!0}),Be(q);return}}if(y.fnName==="spawn_agents"){let j=(ee.match(/\bStatus: done\b/g)||[]).length;if((ee.match(/\bStatus: truncated\b/g)||[]).length>0&&j===0){if(rn++,rn===Gh){D(`${p.yellow} \u26A0 Swarm warning: all sub-agents hit iteration limit ${rn}\xD7 in a row${p.reset}`);let W={role:"user",content:`[SYSTEM WARNING] Sub-agents truncated ${rn}\xD7 in a row. Stop spawning \u2014 try different approach or report findings.`};q.push(W),_.push(W)}else if(rn>=Yh){console.log(`${p.red} \u2716 Swarm abort: all sub-agents hit iteration limit ${rn}\xD7 \u2014 aborting stuck swarm${p.reset}`),l&&(l.stop(),l=null),c(null),We(k,N,T,S,J,{suppressHint:!0}),Be(q);return}}else j>0&&(rn=0)}}for(let $ of Nt)q.push($),_.push($);if(!Ye)for(let $=0;$<Nt.length;$++){if(!pe[$]||pe[$].fnName!=="ssh_exec")continue;let y=Nt[$];if(!y||typeof y.content!="string")continue;let ee=nc(y.content);if(ee){Ye=!0,it=ee.slice(0,120),jt=0,Tt=!1,Kt=0,D(`${p.yellow} \u26A1 Root cause detected: ${it} \u2014 fix phase (read budget: 3)${p.reset}`);let A={role:"user",content:`[SYSTEM] Root cause identified: ${it}. Read only the file that needs fixing, then edit it. Do not read other files.`};q.push(A),_.push(A);break}}for(let $=0;$<Nt.length;$++){let y=pe[$];if(!y)continue;let ee=typeof Nt[$]?.content=="string"?Nt[$].content:"";if(y.fnName==="create_task"){let A=ee.match(/Task #(\d+) created/),I=typeof y.args?.subject=="string"?y.args.subject:"";A&&I&&xo.set(A[1],I)}else if((y.fnName==="write_file"||y.fnName==="edit_file")&&!ee.startsWith("BLOCKED:")&&ee.trim().length>0){let I=(typeof y.args?.path=="string"?y.args.path:typeof y.args?.file_path=="string"?y.args.file_path:"").split("/").pop().toLowerCase(),te=I.split(/[._\-/]/).filter(F=>F.length>2);for(let[F,le]of xo){if(ko.has(F))continue;let j=le.toLowerCase().split(/\W+/).filter(W=>W.length>3);te.filter(W=>j.some(z=>z.includes(W)||W.includes(z))).length>=1&&(ko.add(F),D(`${p.green} \u2714 Auto-matched task #${F} to ${I}: ${le.slice(0,60)}${p.reset}`))}}}{let $=Ze();if(Et(_,$).percentage>=78){let{messages:ee,tokensRemoved:A}=It(_,$);A>0&&(_=ee,console.log(`${p.dim} [auto-compressed \u2014 ~${A} tokens freed, now ${Math.round(Et(_,$).percentage)}%]${p.reset}`))}}let Wc=hx();if(Wc){let $={role:"user",content:`[User note mid-run]: ${Wc}`};q.push($),_.push($),console.log(`${p.cyan} \u270E Context added${p.reset}`)}}if(Fe>=Ct){if(l&&(l.stop(),l=null),c(null),We(k,N,T,S,J),Be(q),Hp(q),$e&&De==="plan"){let Dn=[...q].reverse().find(ze=>ze.role==="assistant"),ct=typeof Dn?.content=="string"?Dn.content:"",qn=fo("implement",ct);if(qn){q.push(qn),_=[{role:"system",content:await hc()},...q],Ct=Cn("implement"),D(`${p.yellow} \u26A0 Plan budget exhausted \u2014 auto-transitioning to implement${p.reset}`);continue e}}else if($e&&De==="verify"){D(`${p.yellow} \u26A0 Verify budget exhausted \u2014 completing session${p.reset}`);break e}let{getActiveProviderName:be}=He();if(be()==="ollama"&&ui<Pc){if(T.size===0&&!di){console.log(`${p.yellow} \u26A0 Max iterations reached with no progress. Stopping.${p.reset}`);break e}ui++,Ct=20,console.log(`${p.dim} \u2500\u2500 auto-extending (+20 turns, ext ${ui}/${Pc}) \u2500\u2500${p.reset}`);continue e}if(console.log(`
1206
- ${p.yellow}\u26A0 Max iterations reached.${p.reset}`),await oh(" Continue for 20 more turns?")){Ct=20;continue e}console.log(`${p.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${p.reset}`)}break e}}dh.exports={processInput:Sx,clearConversation:yx,getConversationLength:wx,getConversationMessages:bx,setConversationMessages:_x,setAbortSignalGetter:X_,setMaxIterations:z_,invalidateSystemPromptCache:cc,clearToolFilterCache:sx,getCachedFilteredTools:ah,buildSystemPrompt:hc,getProjectContextHash:ch,buildUserContent:ih,detectAndTruncateLoop:rc,injectMidRunNote:px,resetSessionTracking:uh}});var He=se((kv,yh)=>{var{OllamaProvider:Ex}=fl(),{OpenAIProvider:Tx}=gl(),{AnthropicProvider:Rx}=bl(),{GeminiProvider:Cx}=vl(),{LocalProvider:Ax}=Tl(),{checkBudget:Ox}=zo(),kc={top:{ollama:"kimi-k2:1t",openai:"gpt-4.1",anthropic:"claude-sonnet-4-5",gemini:"gemini-2.5-pro"},strong:{ollama:"qwen3-coder:480b",openai:"gpt-4o",anthropic:"claude-sonnet",gemini:"gemini-2.5-flash"},fast:{ollama:"devstral-small-2:24b",openai:"gpt-4.1-mini",anthropic:"claude-haiku",gemini:"gemini-2.0-flash"}},_c=(process.env.OLLAMA_FALLBACK_CHAIN||"").split(",").map(t=>t.trim()).filter(Boolean),hh={};for(let[t,e]of Object.entries(kc))for(let s of Object.values(e))hh[s]=t;function xc(t,e){let s=hh[t];return s&&kc[s][e]||t}var Ke={},at=null,qe=null,vo=[];function _t(){if(Object.keys(Ke).length>0)return;$s("ollama",new Ex),$s("openai",new Tx),$s("anthropic",new Rx),$s("gemini",new Cx),$s("local",new Ax);let t=process.env.DEFAULT_PROVIDER||"ollama",e=process.env.DEFAULT_MODEL||null;Ke[t]?(at=t,qe=e||Ke[t].defaultModel):(at="ollama",qe="kimi-k2.5");let s=process.env.FALLBACK_CHAIN;s&&(vo=s.split(",").map(n=>n.trim()).filter(Boolean))}function $s(t,e){Ke[t]=e}function Nx(t){return _t(),Ke[t]||null}function vc(){return _t(),Ke[at]||null}function Mx(){return _t(),at}function Lx(){return _t(),qe}function Px(){_t();let t=vc();if(!t)return{id:qe,name:qe,provider:at};let e=t.getModel(qe);return e?{...e,provider:at}:{id:qe,name:qe,provider:at}}function mh(t){if(!t)return{provider:null,model:null};let e=t.indexOf(":");if(e>0){let s=t.slice(0,e);if(Ke[s]||["ollama","openai","anthropic","gemini","local"].includes(s))return{provider:s,model:t.slice(e+1)}}return{provider:null,model:t}}function Ix(t){_t();let{provider:e,model:s}=mh(t);if(e){let o=Ke[e];return o&&(o.getModel(s)||e==="local"||e==="ollama")?(at=e,qe=s,ri(),!0):!1}let n=vc();if(n&&n.getModel(s))return qe=s,ri(),!0;for(let[o,r]of Object.entries(Ke))if(r.getModel(s))return at=o,qe=s,ri(),!0;return!1}function ri(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=fh();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=Pt();t()}catch{}}function jx(){_t();let t=new Set;for(let e of Object.values(Ke))for(let s of e.getModelNames())t.add(s);return Array.from(t)}function Dx(){return _t(),Object.entries(Ke).map(([t,e])=>({provider:t,configured:e.isConfigured(),models:Object.values(e.getModels()).map(s=>({...s,active:t===at&&s.id===qe}))}))}function qx(){_t();let t=[];for(let[e,s]of Object.entries(Ke)){let n=s.isConfigured();for(let o of Object.values(s.getModels()))t.push({spec:`${e}:${o.id}`,name:o.name,provider:e,configured:n})}return t}function Fx(t){vo=Array.isArray(t)?t:[]}function Bx(){return[...vo]}function ph(t){let e=t.message||"",s=t.code||"";return!!(e.includes("429")||e.includes("500")||e.includes("502")||e.includes("503")||e.includes("504")||s==="ECONNABORTED"||s==="ETIMEDOUT"||s==="ECONNREFUSED"||s==="ECONNRESET"||s==="EHOSTUNREACH"||s==="ENETUNREACH"||s==="EPIPE"||s==="ERR_SOCKET_CONNECTION_TIMEOUT"||e.includes("socket disconnected")||e.includes("TLS")||e.includes("ECONNRESET")||e.includes("ECONNABORTED")||e.includes("network")||e.includes("ETIMEDOUT"))}async function gh(t){let e=[at,...vo.filter(r=>r!==at)],s,n=0,o=0;for(let r=0;r<e.length;r++){let i=e[r],a=Ke[i];if(!a||!a.isConfigured())continue;o++;let c=Ox(i);if(!c.allowed){n++,s=new Error(`Budget limit reached for ${i}: $${c.spent.toFixed(2)} / $${c.limit.toFixed(2)}`);continue}try{let l=r>0,u=l?xc(qe,i):qe;return l&&u!==qe&&process.stderr.write(` [fallback: ${i}:${u}]
1207
- `),await t(a,i,u)}catch(l){if(s=l,!ph(l)||r>=e.length-1)throw l;if(i==="ollama"&&_c.length>0){let u=isFallback?xc(qe,i):qe;for(let d of _c)if(d!==u)try{return process.stderr.write(` [ollama fallback: ${d}]
1208
- `),await t(a,i,d)}catch(f){if(s=f,!ph(f))throw f}}continue}}throw n>0&&n===o?new Error("All providers are over budget. Use /budget to check limits or /budget <provider> off to remove a limit."):o===0?new Error("No configured provider available"):s||new Error("No configured provider available")}async function Wx(t,e,s={}){return _t(),gh((n,o,r)=>n.stream(t,e,{model:r,signal:s.signal,...s}))}async function Ux(t,e,s={}){if(_t(),s.provider){let n=Ke[s.provider];if(!n||!n.isConfigured())throw new Error(`Provider '${s.provider}' is not available`);let o={model:s.model||qe,...s};try{return await n.chat(t,e,o)}catch(r){if(typeof n.stream=="function")try{return await n.stream(t,e,{...o,onToken:()=>{}})}catch{}throw r}}return gh(async(n,o,r)=>{try{return await n.chat(t,e,{model:r,...s})}catch(i){if(typeof n.stream=="function")try{return await n.stream(t,e,{model:r,...s,onToken:()=>{}})}catch{}throw i}})}function Hx(){_t();let t=[];for(let[e,s]of Object.entries(Ke))s.isConfigured()&&t.push({name:e,models:Object.values(s.getModels())});return t}function Gx(){for(let t of Object.keys(Ke))delete Ke[t];at=null,qe=null,vo=[]}yh.exports={registerProvider:$s,getProvider:Nx,getActiveProvider:vc,getActiveProviderName:Mx,getActiveModelId:Lx,getActiveModel:Px,setActiveModel:Ix,getModelNames:jx,parseModelSpec:mh,listProviders:Dx,listAllModels:qx,callStream:Wx,callChat:Ux,getConfiguredProviders:Hx,setFallbackChain:Fx,getFallbackChain:Bx,resolveModelForProvider:xc,MODEL_EQUIVALENTS:kc,OLLAMA_FALLBACK_MODELS:_c,_reset:Gx}});var{C:G}=Ue(),Yx=He(),{TOOL_DEFINITIONS:$h}=Jn(),{saveRoutingConfig:Kx}=ls(),Tc=[{id:"read-package",category:"file-ops",prompt:"Read the file package.json and show me its contents.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("package.json")},{id:"write-file",category:"file-ops",prompt:'Create a file at /tmp/nex-bench-test.txt with the content "benchmark run".',expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&typeof t.content=="string"},{id:"edit-file",category:"file-ops",prompt:'In the file src/config.js, replace the string "debug: false" with "debug: true".',expectedTool:["edit_file","patch_file"],validateArgs:t=>!!(t.path&&t.old_string!==void 0&&t.new_string!==void 0||t.path&&Array.isArray(t.patches)&&t.patches.length>0)},{id:"list-directory",category:"file-ops",prompt:"Show me all files and folders in the cli/ directory.",expectedTool:["list_directory","glob"],validateArgs:t=>!!(typeof t.path=="string"&&t.path.includes("cli")||typeof t.pattern=="string"&&t.pattern.includes("cli"))},{id:"glob-js-files",category:"file-ops",prompt:"Find all JavaScript files (*.js) recursively in the cli/ directory.",expectedTool:"glob",validateArgs:t=>typeof t.pattern=="string"&&t.pattern.includes(".js")},{id:"search-constant",category:"search",prompt:'Search for the string "DEFAULT_MODEL" across all files in the project.',expectedTool:["search_files","grep"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("DEFAULT_MODEL")},{id:"grep-function-def",category:"search",prompt:'Find where the function "callStream" is defined in the codebase.',expectedTool:["grep","search_files"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("callStream")},{id:"search-todos",category:"search",prompt:"Find all TODO comments in the source code.",expectedTool:["grep","search_files","bash"],validateArgs:t=>JSON.stringify(t).toUpperCase().includes("TODO")},{id:"git-branch",category:"shell",prompt:"What git branch am I currently on?",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("git")},{id:"git-status",category:"shell",prompt:"Show me the current git status of the repository.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("git status")},{id:"npm-install",category:"shell",prompt:"Run npm install to install project dependencies.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("npm")},{id:"schema-strict",category:"schema",prompt:"Read the file README.md",expectedTool:"read_file",validateArgs:(t,e)=>{let s=e?.function?.parameters||{},n=s.required||[],o=Object.keys(s.properties||{});return n.every(r=>t[r]!==void 0)&&Object.keys(t).every(r=>o.includes(r))}},{id:"multi-step-version",category:"multi-step",prompt:"What is the current version of this project? Check the source files.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("package.json")},{id:"multi-step-count",category:"multi-step",prompt:"How many JavaScript files are in the cli/ directory? Count them.",expectedTool:["bash","glob","list_directory"],validateArgs:t=>!!(typeof t.command=="string"&&t.command.includes("cli")||typeof t.pattern=="string"&&t.pattern.includes("cli")||typeof t.path=="string"&&t.path.includes("cli"))},{id:"no-tool-reasoning",category:"reasoning",prompt:'What does the acronym "API" stand for?',expectedTool:null,validateArgs:()=>!0},{id:"frontend-find-hook",category:"frontend",prompt:"Find all files that import useState from React.",expectedTool:["grep","search_files"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("useState")},{id:"frontend-create-component",category:"frontend",prompt:"Create a React functional component called Button that accepts a label prop and renders a styled button element. Save it to src/components/Button.jsx.",expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&(t.path.includes(".jsx")||t.path.includes(".tsx")||t.path.includes(".js"))&&typeof t.content=="string"},{id:"frontend-edit-css",category:"frontend",prompt:'In the file src/styles.css, change the background-color value from "blue" to "red".',expectedTool:["edit_file","patch_file"],validateArgs:t=>t.path&&t.old_string!==void 0?t.path.includes(".css")||t.old_string.includes("blue")||t.old_string.includes("background"):!!(t.path&&Array.isArray(t.patches))},{id:"frontend-glob-components",category:"frontend",prompt:"Find all JSX and TSX component files in the components/ directory.",expectedTool:"glob",validateArgs:t=>typeof t.pattern=="string"&&(t.pattern.includes(".jsx")||t.pattern.includes(".tsx")||t.pattern.includes("{jsx,tsx}"))},{id:"frontend-list-assets",category:"frontend",prompt:"List all files in the src/assets/ directory.",expectedTool:["list_directory","glob"],validateArgs:t=>!!(typeof t.path=="string"&&t.path.includes("assets")||typeof t.pattern=="string"&&t.pattern.includes("assets"))},{id:"sysadmin-port-check",category:"sysadmin",prompt:"Which process is currently listening on port 3000?",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("lsof")||t.command.includes("ss")||t.command.includes("netstat")||t.command.includes("3000"))},{id:"sysadmin-nginx-config",category:"sysadmin",prompt:"Create an nginx server block that proxies requests to localhost:3000. Save it to /etc/nginx/sites-available/myapp.",expectedTool:["write_file","bash"],validateArgs:t=>!!(t.path&&(t.path.includes("nginx")||t.path.includes("sites-available"))||t.command&&t.command.includes("nginx"))},{id:"sysadmin-service-status",category:"sysadmin",prompt:"Check the status of the nginx service and show if it is running.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("systemctl")||t.command.includes("service")||t.command.includes("nginx"))},{id:"sysadmin-error-log",category:"sysadmin",prompt:"Show the last 100 lines of the nginx error log.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("tail")||t.command.includes("journalctl")||t.command.includes("nginx"))},{id:"sysadmin-docker-compose",category:"sysadmin",prompt:"Create a docker-compose.yml file for a Node.js application with a PostgreSQL database.",expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("docker-compose")&&typeof t.content=="string"},{id:"data-sql-query",category:"data",prompt:"Write a SQL query to find all users who have not logged in for more than 30 days. Save it to queries/inactive-users.sql.",expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&(t.path.includes(".sql")||t.path.includes("quer"))&&typeof t.content=="string"},{id:"data-find-json-key",category:"data",prompt:'Find all JSON files in the project that contain the key "userId".',expectedTool:["grep","search_files"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("userId")},{id:"data-python-csv",category:"data",prompt:'Write a Python script that reads data.csv and calculates the average of the "price" column. Save it to scripts/average_price.py.',expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes(".py")&&typeof t.content=="string"},{id:"data-find-migrations",category:"data",prompt:"Find all database migration files in this project.",expectedTool:["glob","search_files","grep"],validateArgs:t=>JSON.stringify(t).toLowerCase().includes("migrat")},{id:"data-find-schema",category:"data",prompt:"Find where the database schema or models are defined in this project.",expectedTool:["grep","glob"],validateArgs:t=>!!(t.pattern&&/schema|model|migration/i.test(t.pattern)||t.pattern&&/schema|model|migration/i.test(t.pattern))},{id:"data-write-query",category:"data",prompt:"Write a SQL query to find all users who registered in the last 30 days and save it to queries/recent-users.sql.",expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes(".sql")},{id:"data-read-env",category:"data",prompt:"Read the .env file to find the database connection string.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&/\.env|env\./i.test(t.path)},{id:"resilience-edit-failed",category:"resilience",prompt:"Your edit_file call on server.js failed: old_string 'const PORT = 3000' was not found in the file. What do you do next to recover?",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("server")},{id:"resilience-file-not-found",category:"resilience",prompt:"read_file returned 'file not found' for src/utils/helpers.js. You need to find where the helper functions are now. What tool do you use?",expectedTool:["glob_files","bash"],validateArgs:t=>{let e=JSON.stringify(t).toLowerCase();return e.includes("src")||e.includes("helper")||e.includes("util")||e.includes("*.js")}},{id:"resilience-large-file-nav",category:"resilience",prompt:"The file src/api.js is 2800 lines. You need to locate the authenticateUser function. What is the most efficient tool to use \u2014 read_file or bash with grep?",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("grep")||t.command.includes("rg")||t.command.includes("awk"))},{id:"resilience-broken-import",category:"resilience",prompt:"TypeScript reports: Cannot find module './config'. The file was recently renamed. What tool do you use to find the new location?",expectedTool:["glob_files","bash"],validateArgs:t=>{let e=JSON.stringify(t).toLowerCase();return e.includes("config")||e.includes("*.ts")||e.includes("*.js")||e.includes("find")}},{id:"resilience-bash-error-recover",category:"resilience",prompt:"The command 'npm test' failed with exit code 1. The output contains 'SyntaxError: Unexpected token' in src/parser.js:45. What is your next action?",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("parser")},{id:"resilience-grep-no-match",category:"resilience",prompt:"grep returned zero matches for 'getUserById' in src/. The function exists but may have been renamed. What bash command finds all exported function names in src/ to identify the current name?",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("grep")||t.command.includes("rg")||t.command.includes("src"))},{id:"ssh-exec-log",category:"ssh",prompt:'Show the last 50 lines of /var/log/nginx/error.log on server "prod-1".',expectedTool:"ssh_exec",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("tail")||t.command.includes("log"))&&(typeof t.host=="string"||typeof t.profile=="string")},{id:"ssh-exec-service",category:"ssh",prompt:'Restart the nginx service on server "prod-1".',expectedTool:"ssh_exec",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("nginx")||t.command.includes("systemctl")||t.command.includes("restart"))&&(typeof t.host=="string"||typeof t.profile=="string")},{id:"ssh-exec-port",category:"ssh",prompt:'Check if port 8080 is listening on server "prod-1".',expectedTool:"ssh_exec",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("8080")||t.command.includes("ss")||t.command.includes("netstat")||t.command.includes("lsof"))&&(typeof t.host=="string"||typeof t.profile=="string")},{id:"ssh-exec-processes",category:"ssh",prompt:'Show the top CPU-consuming processes on server "prod-1".',expectedTool:"ssh_exec",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("top")||t.command.includes("ps")||t.command.includes("htop"))&&(typeof t.host=="string"||typeof t.profile=="string")},{id:"git-diff-staged",category:"git",prompt:"Show all staged changes before committing.",expectedTool:["git_diff","bash"],validateArgs:t=>!!(t.staged===!0||t.staged==="true"||typeof t.command=="string"&&t.command.includes("diff"))},{id:"git-log-recent",category:"git",prompt:"Show the last 5 commit messages with their hashes.",expectedTool:["git_log","bash"],validateArgs:t=>!!(typeof t.limit=="number"||typeof t.n=="number"||typeof t.command=="string"&&t.command.includes("log"))},{id:"git-status-check",category:"git",prompt:"Check if there are any uncommitted changes in the repository.",expectedTool:["git_status","bash"],validateArgs:t=>t.path===void 0&&t.command===void 0?!1:(typeof t.command=="string"&&t.command.includes("status"),!0)},{id:"agentic-test-first",category:"agentic",prompt:"Run the full test suite. If any tests fail, identify the failing test file and read it to understand the issue.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("test")||t.command.includes("jest")||t.command.includes("npm"))},{id:"agentic-read-then-act",category:"agentic",prompt:"Read the project README.md, find the TODO section, and list which items are completed.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("README")},{id:"agentic-build-deploy",category:"agentic",prompt:"Build the project with npm run build, then verify the output exists in the dist/ directory.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("build")||t.command.includes("npm"))},{id:"agentic-spawn-parallel",category:"agentic",prompt:"Search for all TODO comments and all FIXME comments across the codebase in parallel using multiple agents.",expectedTool:"spawn_agents",validateArgs:t=>Array.isArray(t.agents)&&t.agents.length>=2},{id:"agentic-multi-investigate",category:"agentic",prompt:"The app is crashing on startup. Spawn parallel agents to check: (1) recent git changes, (2) npm dependency issues, (3) the main entry file for syntax errors.",expectedTool:"spawn_agents",validateArgs:t=>Array.isArray(t.agents)&&t.agents.length>=2}],wh=[{id:"phase-plan-diagnosis",category:"phase-plan",prompt:"The server returns 500 on /api/users. The error log shows: TypeError: Cannot read property 'map' of undefined at routes/users.js:42. Read the relevant file to diagnose the root cause.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&/users/i.test(t.path)},{id:"phase-plan-search",category:"phase-plan",prompt:"We're getting CORS errors in production. Search the codebase for where CORS middleware is configured.",expectedTool:"grep",validateArgs:t=>typeof t.pattern=="string"&&/cors/i.test(t.pattern)},{id:"phase-plan-context",category:"phase-plan",prompt:"The login page shows a blank screen after the last deploy. Check git log for recent changes that might have broken it.",expectedTool:"git_log",validateArgs:()=>!0},{id:"phase-verify-test",category:"phase-verify",prompt:"The file src/utils.js was modified to fix a null pointer bug. Run the test suite to verify the fix works correctly.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&/test|jest|npm\s+test|pytest|mocha/.test(t.command)},{id:"phase-verify-read",category:"phase-verify",prompt:"A patch was applied to config/database.js to fix the connection pool. Read the file to verify the changes look correct.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&/database/i.test(t.path)},{id:"phase-verify-lint",category:"phase-verify",prompt:"Code was modified in src/components/Header.tsx. Run the linter to check for any style violations.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&/lint|eslint|prettier|tsc/.test(t.command)},{id:"phase-plan-git-blame",category:"phase-plan",prompt:"A production bug was introduced 2 days ago. Use git log to find commits from the last 2 days to identify what changed.",expectedTool:"git_log",validateArgs:()=>!0},{id:"phase-plan-error-trace",category:"phase-plan",prompt:"The error stack trace mentions src/middleware/auth.js line 87. Read the file around that line to understand the bug.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&/auth/i.test(t.path)},{id:"phase-plan-grep-config",category:"phase-plan",prompt:"Users report the app is using wrong API keys in staging. Search for where API_KEY is loaded from environment.",expectedTool:"grep",validateArgs:t=>typeof t.pattern=="string"&&/api.?key|env/i.test(t.pattern)},{id:"phase-verify-build",category:"phase-verify",prompt:"The TypeScript source was modified. Run the build command to verify there are no compilation errors.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&/build|tsc|compile/.test(t.command)},{id:"phase-verify-git-diff",category:"phase-verify",prompt:"Changes were just committed. Show the git diff of the last commit to verify only the intended files were modified.",expectedTool:["git_diff","bash"],validateArgs:t=>(t.command&&/git.*diff|diff.*HEAD/.test(t.command),!0)},{id:"phase-verify-read-config",category:"phase-verify",prompt:"The deployment config was updated. Read config/production.json to verify the changes are correct before deploying.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&/config|production|deploy/i.test(t.path)}],ci=[...Tc,...wh],Sc=["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 zx(){try{let s=require("path").join(require("os").homedir(),".nex-code","benchmark-results.json");if(!require("fs").existsSync(s))return Sc;let n=JSON.parse(require("fs").readFileSync(s,"utf-8"));return!Array.isArray(n)||n.length===0?Sc:n.filter(o=>typeof o.score=="number"&&o.score>=60).sort((o,r)=>r.score-o.score).slice(0,12).map(o=>o.model)}catch{return Sc}}var Rc=zx(),Xx=["minimax-m2.7:cloud","qwen3-coder:480b","devstral-2:123b"],bh=(()=>{let t=Rc.slice(0,3);return t.length>=3?t:Xx})(),Vx=7,ii={producedToolCall:.2,correctTool:.35,validArgs:.3,schemaCompliant:.15},Jx="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 Ec(t,e){let s={taskId:t.id,category:t.category,model:e,producedToolCall:!1,correctTool:!1,validArgs:!1,schemaCompliant:!1,toolCalled:null,error:null,latencyMs:0},n=[{role:"system",content:Jx},{role:"user",content:t.prompt}],o=Date.now();try{let r=await Yx.callChat(n,$h,{provider:"ollama",model:e,temperature:0,timeout:9e4});s.latencyMs=Date.now()-o;let i=r.tool_calls||[];if(t.expectedTool===null){let a=i.length===0;s.producedToolCall=a,s.correctTool=a,s.validArgs=!0,s.schemaCompliant=!0}else if(i.length>0){let a=i[0],c=a.function?.name||"unknown",l=a.function?.arguments||{};s.producedToolCall=!0,s.toolCalled=c;let u=Array.isArray(t.expectedTool)?t.expectedTool:[t.expectedTool];if(s.correctTool=u.includes(c),s.correctTool){let d=$h.find(f=>f.function?.name===c);if(s.validArgs=!!t.validateArgs(l,d),d){let f=d.function?.parameters||{},h=f.required||[],m=Object.keys(f.properties||{});s.schemaCompliant=h.every(g=>l[g]!==void 0)&&Object.keys(l).every(g=>m.includes(g))}}}}catch(r){s.latencyMs=Date.now()-o,s.error=r.message.slice(0,120)}return s}function ws(t){return t.error?0:((t.producedToolCall?ii.producedToolCall:0)+(t.correctTool?ii.correctTool:0)+(t.validArgs?ii.validArgs:0)+(t.schemaCompliant?ii.schemaCompliant:0))*100}var _h={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 Cc(t){return Object.entries(t).map(([e,s])=>{let n=s.map(ws),o=n.reduce((a,c)=>a+c,0)/n.length,r=a=>Math.round(s.filter(a).length/s.length*100),i={};for(let a of["coding","frontend","sysadmin","data","agentic","plan","verify"]){let c=s.filter(u=>_h[u.category]===a);if(c.length===0)continue;let l=c.map(ws).reduce((u,d)=>u+d,0)/c.length;i[a]=Math.round(l*10)/10}return{model:e,score:Math.round(o*10)/10,toolCallRate:r(a=>!a.error&&(a.producedToolCall||a.category==="reasoning")),correctRate:r(a=>a.correctTool),validArgsRate:r(a=>a.validArgs),schemaRate:r(a=>a.schemaCompliant),avgLatency:Math.round(s.reduce((a,c)=>a+c.latencyMs,0)/s.length),errorCount:s.filter(a=>a.error).length,categoryScores:i,results:s}}).sort((e,s)=>s.score-e.score)}function xh(t){let e={};for(let a of["coding","frontend","sysadmin","data","agentic","plan","verify"]){let c=t.filter(g=>g.categoryScores[a]!==void 0&&g.score>=65).sort((g,b)=>b.categoryScores[a]-g.categoryScores[a]);if(c.length===0)continue;let u=(c[0]?.results||[]).filter(g=>_h[g.category]===a).length;if(u<4)continue;let d=c[0],f=c[1];if(d.categoryScores[a]>=95&&u<8&&f&&d.categoryScores[a]-f.categoryScores[a]<15){let b=t.filter(v=>v.categoryScores[a]!==void 0).find(v=>v.categoryScores[a]<95);b&&(e[a]={model:b.model,score:b.categoryScores[a],avgLatency:b.avgLatency,_flukePrevented:!0});continue}let m=c.filter(g=>d.categoryScores[a]-g.categoryScores[a]<=5).sort((g,b)=>g.avgLatency-b.avgLatency)[0];e[a]={model:m.model,score:m.categoryScores[a],avgLatency:m.avgLatency}}return e}function kh(t,e){let s=`nex-code Model Benchmark (${e} tasks \xB7 ollama cloud)`,n=[{label:"#",width:3},{label:"Model",width:26},{label:"Score",width:7},{label:"Tool\u2713",width:7},{label:"Name\u2713",width:7},{label:"Args\u2713",width:7},{label:"Schema\u2713",width:8},{label:"Latency",width:8},{label:"Err",width:4}],o=n.reduce((l,u)=>l+u.width+1,0)+1,r="\u2500".repeat(o);console.log(`
1209
- ${G.bold}${s}${G.reset}`),console.log(r);let i=n.map(l=>l.label.padEnd(l.width)).join(" ");if(console.log(`${G.dim}${i}${G.reset}`),console.log(r),t.forEach((l,u)=>{let d=String(u+1).padEnd(n[0].width),f=l.model.slice(0,n[1].width).padEnd(n[1].width),h=String(l.score).padEnd(n[2].width),m=`${l.toolCallRate}%`.padEnd(n[3].width),g=`${l.correctRate}%`.padEnd(n[4].width),b=`${l.validArgsRate}%`.padEnd(n[5].width),v=`${l.schemaRate}%`.padEnd(n[6].width),O=`${(l.avgLatency/1e3).toFixed(1)}s`.padEnd(n[7].width),U=l.errorCount>0?`${G.red}${l.errorCount}${G.reset}`:`${G.dim}0${G.reset}`,L=l.score>=80?G.green:l.score>=60?G.yellow:G.red,R=u===0?`${G.yellow}${d}${G.reset}`:`${G.dim}${d}${G.reset}`;console.log(`${R} ${L}${f}${G.reset} ${G.bold}${L}${h}${G.reset} ${m} ${g} ${b} ${v} ${G.dim}${O}${G.reset} ${U}`)}),console.log(r),t.length>0){let l=t[0];if(console.log(`
1210
- ${G.bold}${G.green}Winner: ${l.model}${G.reset} score ${l.score}/100`),t.length>1){let u=(l.score-t[1].score).toFixed(1);console.log(`${G.dim}+${u} pts over ${t[1].model}${G.reset}`)}}let a=["coding","frontend","sysadmin","data","agentic"];if(t.some(l=>Object.keys(l.categoryScores).length>1)){console.log(`
1211
- ${G.bold}Best model per task type:${G.reset}`);for(let l of a){let u=t.filter(m=>m.categoryScores[l]!==void 0).sort((m,g)=>g.categoryScores[l]-m.categoryScores[l]);if(u.length===0)continue;let d=u[0],f=d.categoryScores[l],h=f>=80?G.green:f>=60?G.yellow:G.red;console.log(` ${G.dim}${l.padEnd(10)}${G.reset} ${h}${d.model}${G.reset} ${G.dim}${f}/100${G.reset}`)}}console.log()}function vh(t){if(!(!t||t.length<2))try{let e=xh(t),{loadRoutingConfig:s}=ls(),n=s(),o={...n},r=[],i=new Set(["plan","verify"]);for(let[a,{model:c,score:l}]of Object.entries(e)){let u=i.has(a),d=u?n.phases&&n.phases[a]:n[a];d&&d!==c&&!t.find(h=>h.model===d)||(u?(o.phases||(o.phases={}),o.phases[a]!==c&&(o.phases[a]=c,r.push(`phase:${a}\u2192${c}`))):o[a]!==c&&(o[a]=c,r.push(`${a}\u2192${c}`)))}r.length>0&&(Kx(o),console.log(`
1212
- ${G.dim} Routing updated: ${r.join(", ")}${G.reset}`))}catch{}}async function Zx({models:t,quick:e=!1,onProgress:s,parallelModels:n=1}={}){let o=e?Tc.slice(0,Vx):ci,r=t?.length>0?t:e?bh:Rc,i={};for(let c of r)i[c]=[];if(n<=1)for(let c of r)for(let l of o){s?.({model:c,task:l.id,done:!1});let u=await Ec(l,c);i[c].push(u),s?.({model:c,task:l.id,done:!0,score:ws(u),error:u.error})}else{let c=Math.min(n,r.length),l=[...r],u=Array.from({length:c},async()=>{for(;l.length>0;){let d=l.shift();if(!d)break;for(let f of o){s?.({model:d,task:f.id,done:!1});let h=await Ec(f,d);i[d].push(h),s?.({model:d,task:f.id,done:!0,score:ws(h),error:h.error})}}});await Promise.all(u)}let a=Cc(i);return kh(a,o.length),vh(a),a}async function Qx({newModels:t,existingRanking:e=[],onProgress:s}={}){if(!t||t.length===0)return e;let n={};for(let i of t){n[i]=[];for(let a of ci){s?.({model:i,task:a.id,done:!1});let c=await Ec(a,i);n[i].push(c),s?.({model:i,task:a.id,done:!0,score:ws(c),error:c.error})}}let r=[...Cc(n)];for(let i of e)r.find(a=>a.model===i.model)||r.push(i);return r.sort((i,a)=>a.score-i.score),kh(r,ci.length),vh(r),r}var ai=[{id:"simple_question",name:"Simple Convergence",prompt:"What is 2+2?",maxTurns:3,successCriteria:["4"]}];function Sh(t){let e=require("fs"),n=require("path").join(t||process.cwd(),".nex","benchmark-config.json");if(!e.existsSync(n))return console.log(`${G.yellow}No scenarios configured.${G.reset} Create ${G.dim}.nex/benchmark-config.json${G.reset} to define your benchmark scenarios.
1232
+ ${getPlanContent()||Nt.content}`;q.push({role:"user",content:J}),T.push({role:"user",content:J}),Q=!0}}else console.log(`
1233
+ ${p.cyan}${p.bold}Plan ready.${p.reset} ${p.dim}Type ${p.reset}${p.cyan}/plan approve${p.reset}${p.dim} to execute, or ask follow-up questions to refine.${p.reset}`);if(Q){l&&(l.stop(),l=null),We--;continue}}}if(l&&(l.stop(),l=null),c(null),Fe(v,O,R,k,H),xt&&R.size>=3){let S=[...R].map(N=>N.split("/").pop()).slice(0,8).join(", "),A=[...R].some(N=>N.endsWith("package.json")),Q=[...R].some(N=>N.endsWith("requirements.txt")),D=[...R].some(N=>N.endsWith("package-lock.json")||N.endsWith("yarn.lock")||N.endsWith("pnpm-lock.yaml")),le=A&&!D?"npm install not yet run":Q?"pip install not yet run":null;wo=`[Previous session created ${R.size} files: ${S}`+(le?` \u2014 ${le}`:"")+". Use this context to answer follow-up questions without re-reading files.]"}if(xt&&!Sc&&v>0){let S=[...R].some(J=>J.endsWith("package.json")),A=[...R].some(J=>J.endsWith("requirements.txt")||J.endsWith("Pipfile")||J.endsWith("pyproject.toml")),Q=[...R].some(J=>J.endsWith("package-lock.json")||J.endsWith("yarn.lock")||J.endsWith("pnpm-lock.yaml")),D=q.flatMap(J=>{let oe=Array.isArray(J.tool_calls)?J.tool_calls:[],he=Array.isArray(J.content)?J.content.filter(ne=>ne?.type==="tool_use"):[];return[...oe,...he]}).filter(J=>{let oe=J.function?.name||J.name||"";return oe==="bash"||oe==="Bash"}).map(J=>{try{let oe=J.function?.arguments??J.input??{};return(typeof oe=="string"?JSON.parse(oe):oe)?.command||""}catch{return""}}),le=D.some(J=>/pip\s+install|python\s+-m\s+venv/.test(J)),N=D.some(J=>/npm\s+install/.test(J)),U=[...R].some(J=>/\/App\.(js|ts|jsx|tsx)$/.test(J))&&!S&&!N;if(A&&!le||S&&!Q&&!N||U){Sc=!0;let J=[];A&&!le&&J.push("python -m venv venv && source venv/bin/activate && pip install -r requirements.txt"),U?J.push("create package.json for the React frontend (with react, react-dom, react-scripts dependencies), then run npm install"):S&&!Q&&!N&&J.push("npm install");let oe=`[FRAMEWORK \u2014 post-creation check] You wrote dependency files but never ran the installer. Run now: ${J.join(" && ")}. Verify it succeeds, fix any errors, then write a closing summary.`;F(`${p.dim} [post-creation] bootstrapping environment (${J.join(", ")})${p.reset}`),q.push({role:"user",content:oe}),T.push({role:"user",content:oe});continue}}if(v>0&&!s._isSummaryTurn&&P_(Mt))try{F(`${p.dim} [post-turn] terse ending \u2014 requesting diagnosis/summary${p.reset}`);let S=R.size>0?"Write a closing summary (3+ sentences): what files changed and why, what the result is, anything the user should know or do next.":"Write a closing diagnosis (3+ sentences): what you investigated, what you found, and what the user should do next or what the root cause is.",A=[...T,{role:"user",content:S}],D=((await sh(A,[],{}))?.content||"").trim();D&&(console.log(`
1234
+ ${D}`),q.push({role:"user",content:S},{role:"assistant",content:D}))}catch{}qe(q),ic(q);return}v++,ai++,v>=1&&(ke=!1);for(let $ of Wt){let y=$.function.name;O.set(y,(O.get(y)||0)+1)}if(v>=30&&!hh){hh=!0,F(`${p.yellow} \u26A0 Tool budget warning: ${v} tool calls used \u2014 nudging model to wrap up${p.reset}`);let $={role:"user",content:"[SYSTEM] \u26A0 You have used "+v+" tool calls. This is approaching the quality threshold (40). Wrap up NOW: write your final summary and stop. Do NOT run additional verification commands (git status, git diff, git log) \u2014 your changes are already committed and verified. Further tool calls will hurt session quality."};q.push($),T.push($)}let ye=await Promise.all(Wt.map($=>Rx($)));{let $=Tt(T,Qe()),y=$.percentage,ee=ye.some(D=>D.canExecute&&D.fnName==="read_file"&&!D.args?.line_end),S=ye.filter(D=>D.canExecute&&D.fnName==="read_file"&&D.args?.path&&Dt(Fn,D.args.path)>=1&&!D.args?.line_start).map(D=>D.args.path.split("/").slice(-2).join("/")),A=S.length>0;if(y>=70&&ee&&hi<70||y>=85&&hi<85||A){hi=y;let D=y>=85?"URGENT":"WARNING",le;A?(D="WARNING",le=`Full-file read of ${S.join(", ")} already done \u2014 use line_start/line_end for specific sections instead.`):ee?le=`Unbounded read at ${Math.round(y)}% context \u2014 use line_start/line_end to avoid overflow.`:le="Use targeted reads (line_start/line_end) to save space.";let N={role:"user",content:`[SYSTEM ${D}] Context ${Math.round(y)}% used (${$.used}/${$.limit} tokens). ${le}`};if(q.push(N),T.push(N),y>=85){let B=A?` (re-read of: ${S.join(", ")})`:"";F(`${p.yellow} \u26A0 Context ${Math.round(y)}% used \u2014 agent warned to use targeted reads${B}${p.reset}`)}}}let bi=new Map;for(let $ of ye){if(!$.canExecute||$.fnName!=="read_file")continue;let y=$.args?.path;if(!y)continue;let ee=Dt(Fn,y),S=bi.get(y)||0,A=ee+S,Q=$.args?.line_start!=null,D=Pn.get(y)||0,le=D>0,N=2;if(A>=Bn){let B=y.split("/").slice(-2).join("/"),U=(qn.get(y)||0)+1;if(qn.set(y,U),U===1)F(`${p.red} \u2716 Blocked: "${B}" read ${A}\xD7 \u2014 hard cap (${Bn}) reached${p.reset}`);else if(U===2){F(`${p.red} \u2716 Escalated block: "${B}" \u2014 model ignored BLOCKED, injecting system warning${p.reset}`);let V={role:"user",content:`[SYSTEM WARNING] You already received a BLOCKED error for read_file("${y}") and tried again anyway. This file has reached its read cap (${Bn}\xD7). Do NOT attempt to read it again. Use grep_search to find specific content, or proceed with what you already know.`};q.push(V),T.push(V)}$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 file already read ${A}\xD7 (hard cap: ${Bn}). You have seen enough of this file. Use grep to find specific content or proceed with what you know.`,tool_call_id:$.callId}}else if(A>=1&&Q)if(le&&D<=N){let B=y.split("/").slice(-2).join("/");console.log(`${p.cyan} \u21A9 Targeted re-read: "${B}" (line_start=${$.args.line_start}) \u2014 edit recovery #${D}${p.reset}`),Pn.set(y,D-1)}else if(le&&D>N){let B=y.split("/").slice(-2).join("/");F(`${p.red} \u2716 Edit recovery blocked: "${B}" \u2014 ${N} recovery reads already used. Use grep to find the exact line numbers, then retry.${p.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 edit recovery budget exhausted (${N} recovery reads used). You already have the file content. Use grep_search to find the exact line numbers of the text you want to change, then retry edit_file with the exact text shown.`,tool_call_id:$.callId}}else{let B=$.args.line_start||1,U=$.args.line_end||B+350,V=zt.get(y)||[],J=!1;for(let[oe,he]of V){let ne=Math.max(B,oe),Me=Math.min(U,he);if(Me>ne){let Ue=Me-ne,yt=U-B||1,ut=he-oe||1,Ut=Ue/ut>=.7&&Ue/yt<.7,Ye=U-B<=Zh;if(Ue>=yt||!Ye&&(Ue/yt>=.7||Ue/ut>=.7)){let xi=y.split("/").slice(-2).join("/"),nl=`${y}:${B}-${U}`,Yn=(ri.get(nl)||0)+1;if(ri.set(nl,Yn),F(Ut?`${p.red} \u2716 Blocked superread: "${xi}" lines ${B}-${U} subsumes already-read ${oe}-${he} \u2014 use line_start=${he+1} to skip known content (block #${Yn})${p.reset}`:`${p.red} \u2716 Blocked duplicate read: "${xi}" lines ${B}-${U} (\u226570% overlap with lines ${oe}-${he} already in context, block #${Yn})${p.reset}`),Yn>=2){F(`${p.red} \u2716 Escalated range-block: "${xi}" lines ${B}-${U} \u2014 model ignored BLOCKED, injecting system warning${p.reset}`);let sl={role:"user",content:Ut?`[SYSTEM] Read blocked ${Yn}\xD7 for read_file("${y}", lines ${B}-${U}). Lines ${oe}-${he} were already read. Use line_start=${he+1} to read only new content, or use grep_search for specific lines.`:`[SYSTEM] Read blocked ${Yn}\xD7 for read_file("${y}", lines ${B}-${U}). Lines ${oe}-${he} were already read and will NOT change. Use grep_search to find specific content instead.`};q.push(sl),T.push(sl)}$.canExecute=!1,$.errorResult={role:"tool",content:Ut?`BLOCKED: read_file("${y}", lines ${B}-${U}) re-reads lines ${oe}-${he} already in context. Use line_start=${he+1} to read only the new content beyond line ${he}.`:`BLOCKED: read_file("${y}", lines ${B}-${U}) is a duplicate \u2014 lines ${oe}-${he} are already in your context (\u226570% overlap). Use grep to find specific content instead of re-reading.`,tool_call_id:$.callId},J=!0;break}}}if(!J){let oe=V.length,he=2;if(oe>=3){let Me=y.split("/").slice(-2).join("/");F(`${p.red} \u2716 Blocked file-scroll: "${Me}" \u2014 ${oe} sections already read. Use grep to find specific content.${p.reset}`);let Ue=Dt(pi,y)>=To;$.canExecute=!1,$.errorResult={role:"tool",content:Ue?`BLOCKED: read_file("${y}") denied \u2014 you have already read ${oe} different sections of this file (file-scroll pattern). Grep is also exhausted. The content you need is already in your context \u2014 work with what you have.`:`BLOCKED: read_file("${y}") denied \u2014 you have already read ${oe} different sections of this file (file-scroll pattern). You have seen most of this file. Use grep_search to find the exact lines you need instead of continuing to scroll.`,tool_call_id:$.callId}}else oe>=he&&($._scrollWarn={sectionCount:oe+1,path:y})}}else if(A>=1){let B=y.split("/").slice(-2).join("/"),U=(qn.get(y)||0)+1;if(qn.set(y,U),U===1)F(`${p.red} \u2716 Blocked unbounded re-read: "${B}" \u2014 already in context. Use line_start/line_end for specific sections.${p.reset}`);else if(U===2){F(`${p.red} \u2716 Escalated block: "${B}" \u2014 model ignored unbounded re-read block, injecting system warning${p.reset}`);let V={role:"user",content:`[SYSTEM] read_file("${y}") was blocked again \u2014 full-file reads are disabled after the first read. Use line_start/line_end for a specific section, or use grep_search to find what you need.`};q.push(V),T.push(V)}$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 file already in context (read ${A}\xD7). Use line_start/line_end to read a specific section instead of the full file.`,tool_call_id:$.callId}}$.canExecute&&bi.set(y,(bi.get(y)||0)+1)}if(sn>=3)for(let $ of ye)$.canExecute&&($.fnName!=="read_file"&&$.fnName!=="edit_file"||(F(`${p.red} \u2716 Blocked ${$.fnName} \u2014 ${sn} consecutive file-not-found errors, must search first${p.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: ${sn} consecutive "File not found" errors. You must call search_files or glob_files to locate the correct path before reading or editing. Do not guess file paths.`,tool_call_id:$.callId}));for(let $ of ye){if(!$.canExecute||$.fnName!=="bash")continue;let y=($.args?.command||"").trim();if(/^\s*ls(\s+-[a-zA-Z]+)*(\s+\S+)?\s*$/.test(y)&&!/npm|yarn|pnpm|make|git/.test(y)){F(`${p.red} \u2716 Blocked bash ls \u2014 use list_directory tool instead${p.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:'BLOCKED: bash("ls ...") denied \u2014 use the list_directory tool instead. It returns structured output and does not penalize the session score.',tool_call_id:$.callId};continue}/\bfind\s+[\S.]/.test(y)&&!/git\s|npm\s|yarn\s|-exec\s+\S|-execdir/.test(y)&&(F(`${p.red} \u2716 Blocked bash find \u2014 use glob tool with a pattern instead${p.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:'BLOCKED: bash("find ...") denied \u2014 use the glob tool with a pattern like "**/*.py" or "src/**/*.js" instead. It is faster and does not penalize the session score.',tool_call_id:$.callId})}for(let $ of ye)$.canExecute&&($.fnName!=="ssh_exec"&&$.fnName!=="bash"||/\bsed\s+-n\b/.test($.args?.command||"")&&(F(`${p.red} \u2716 Blocked sed -n: use grep -n "pattern" <file> | head -30 instead${p.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:'BLOCKED: sed -n is forbidden \u2014 it floods context with line ranges. Use grep -n "pattern" <file> | head -30 to read a specific section, or cat <file> for the full file.',tool_call_id:$.callId}));for(let $ of ye){if(!$.canExecute||$.fnName!=="write_file")continue;let y=$.args?.path,ee=$.args?.content||"";if(y)try{let S=require("fs"),A=require("path").resolve(process.cwd(),y);if(S.existsSync(A)){let Q=S.statSync(A).size,D=Buffer.byteLength(ee,"utf8"),le=Q>0?D/Q:1;if(le<.6&&Q>200){let N=y.split("/").slice(-2).join("/");console.log(`${p.red} \u2716 write_file shrink guard: "${N}" would shrink to ${Math.round(le*100)}% of original \u2014 likely context loss${p.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: write_file("${y}") denied \u2014 new content is only ${Math.round(le*100)}% of current file size (${Q} \u2192 ${D} bytes). This looks like a partial rewrite after context loss. Use edit_file/patch_file to add only the new code, or read the file first to see full content before replacing.`,tool_call_id:$.callId}}}}catch{}}let Zc=new Map;for(let $ of ye){if(!$.canExecute||$.fnName!=="grep")continue;let y=$.args?.path;if(!y)continue;let ee=Zc.get(y)||0,S=Dt(pi,y)+ee,A=Dt(Fn,y)>=1,Q=A?Math.min(3,To):To;if(S>=Q){let D=y.split("/").slice(-2).join("/");F(`${p.red} \u2716 Blocked grep: "${D}" grepped ${S}\xD7 with different patterns \u2014 flood threshold exceeded${p.reset}`);let le=Dt(Fn,y),N=le>=Bn;if(N){let B={role:"user",content:`[SYSTEM] Both read_file and grep are now blocked for "${y}". You have already read ${le} sections and tried ${S} grep patterns. Do NOT attempt to read or grep this file again. The content you need is already in your conversation context \u2014 scroll back to find it, or proceed with what you know.`};q.push(B),T.push(B),F(`${p.red} \u2716 Deadlock detected: "${D}" \u2014 both read and grep blocked, injecting deadlock-break${p.reset}`)}$.canExecute=!1,$.errorResult={role:"tool",content:N?`BLOCKED: grep("${y}") denied \u2014 ${S} patterns already tried AND reads are also exhausted. The content is already in your context. Do not attempt to read or grep this file again.`:A?`BLOCKED: grep("${y}") denied \u2014 file was already read and ${S} grep patterns tried. The content is already in your context; use it instead of searching again.`:`BLOCKED: grep("${y}") denied \u2014 ${S} patterns already tried. Work with the grep results already in your context.`,tool_call_id:$.callId}}$.canExecute&&Zc.set(y,ee+1)}let om=5,Qc=new Map;for(let $ of ye){if(!$.canExecute||$.fnName!=="ssh_exec")continue;let ee=($.args?.command||"").replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),S=Qc.get(ee)||0,A=Dt(Yc,ee)+S;A>=om&&(F(`${p.yellow} \u26A0 Blocked ssh_exec: same command run ${A}\xD7 \u2014 result already in context${p.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: ssh_exec denied \u2014 this command has already run ${A} times and the output is in your context. Use existing results, try a different command, or run it as a local bash call: bash("ssh user@host 'your command'").`,tool_call_id:$.callId}),$.canExecute&&Qc.set(ee,S+1)}if(mt){let $=ye.filter(S=>S.canExecute&&S.fnName==="ssh_exec"),y=ye.some(S=>S.canExecute&&S.fnName!=="ssh_exec"),ee=w&&I<3;if($.length>0&&!y&&ee&&Zr<1)mt=!1,Zr++,_t=Math.max(0,vs-2),F(`${p.dim} [dual-block deadlock: SSH storm relaxed \u2014 allowing 1 SSH call (relax ${Zr}/1)]${p.reset}`);else for(let S of $)S.canExecute=!1,S.errorResult={role:"tool",content:ze?`BLOCKED: ssh_exec denied \u2014 SSH paused (${vs}+ calls). Root cause is known (${at}). Edit the file now. You can still use bash("ssh user@host 'cmd'") for a single targeted lookup if essential.`:`BLOCKED: ssh_exec denied \u2014 SSH temporarily paused (${vs}+ calls). Provide a text summary of your findings first. Do NOT ask the user to run commands. SSH re-enables after your summary. For one-off lookups use bash("ssh user@host 'cmd'") instead.`,tool_call_id:S.callId}}if(w&&I<3&&!mt){for(let $ of ye)if($.canExecute&&["bash","read_file","find_files"].includes($.fnName)){I++;{let y=Qe(),{messages:ee}=jt(T,y);T=ee}F(`${p.yellow} \u26A0 Server-local guard: blocking local ${$.fnName} \u2014 use ssh_exec on 94.130.37.43${p.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: ${$.fnName} denied \u2014 this is a server issue. Use ssh_exec on 94.130.37.43 instead.`,tool_call_id:$.callId};break}}if(!we&&Rt&&xt&&Ct>=1){let $=["read_file","grep","search_files","glob","list_directory","find_files"];for(let y of ye)y.canExecute&&$.includes(y.fnName)&&(F(`${p.red} \u2716 Creation hard-block: ${y.fnName} denied \u2014 cap fired, files already written${p.reset}`),y.canExecute=!1,y.errorResult={role:"tool",content:"BLOCKED: files already written \u2014 continue with write_file or edit_file to finish the remaining tasks. Do not read more files.",tool_call_id:y.callId})}if(In>=0){let $=ye.filter(y=>y.canExecute).length;if($>0&&(In-=$,In<0))if(!ei&&R.size>Qr){ei=!0,In=5,F(`${p.green} \u2713 Post-wipe progress detected (${R.size-Qr} files modified) \u2014 granting 5 bonus tool calls${p.reset}`);let y={role:"user",content:"[SYSTEM] Progress detected \u2014 5 bonus tool calls granted. Budget: 5 remaining."};q.push(y),T.push(y)}else{F(`${p.red} \u2716 Post-wipe tool budget exhausted \u2014 blocking all tool calls${p.reset}`);for(let ee of ye)ee.canExecute&&(ee.canExecute=!1,ee.errorResult={role:"tool",content:"BLOCKED: post-wipe tool budget exhausted. No further tool calls are allowed. Summarise what was accomplished and stop.",tool_call_id:ee.callId});let y={role:"user",content:"[SYSTEM] Post-wipe tool budget exhausted. All tool calls are now blocked. Respond with a final summary of what was done and stop \u2014 do not attempt any more tool calls."};q.push(y),T.push(y)}}let rm=new Set(["edit_file","write_file","bash","ssh_exec","ask_user","spawn_agents","browser_click","browser_fill","browser_open","skill_ar_run_experiment","skill_ar_run_benchmark","skill_ar_checkpoint","skill_ar_revert","skill_ar_log_experiment","skill_ar_extract_metric"]);for(let $ of ye){if(!$.canExecute||rm.has($.fnName))continue;let y=JSON.stringify($.args||{}),ee=`${$.fnName}|${y}`,S=Dt(ii,ee);S>=2?(F(`${p.red} \u2716 Blocked duplicate: ${$.fnName}(${y.substring(0,80)}) \u2014 called ${S+1}\xD7 with identical args${p.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: ${$.fnName}() with these exact arguments has already been called ${S}\xD7 \u2014 the result is already in your context. Use the existing output instead of repeating the same call.`,tool_call_id:$.callId}):S===1&&F(`${p.yellow} \u26A0 Duplicate tool call: ${$.fnName}(${y.substring(0,80)}) \u2014 2nd call with identical args${p.reset}`),Ln(ii,ee)}let Ss=l?{skipSpinner:!0,skipSummaries:!0}:{},im=ye.some($=>$.fnName==="ask_user"),el=!Ss.skipSummaries&&!ke,No=null,Hn=null;el&&!im?(ke=!0,Ss.skipSpinner=!0,process.stdout.isTTY?(global._nexFooter&&(Hn=Math.min(global._nexFooter._lastOutputRow+1,global._nexFooter._scrollEnd)),process.stdout.write(Yr(ye,v,!1,"blink")),No=!0):Ft||process.stdout.write(Yr(ye,v,!1)+`
1235
+ `)):el&&(ke=!0,Ss.skipSpinner=!0),l&&l._paused&&l.resume();let Mo=null;if(No&&process.stdout.isTTY&&ye.some(y=>y.canExecute&&(y.fnName==="bash"||y.fnName==="ssh_exec"))){let y=Date.now();Mo=setInterval(()=>{let ee=Math.round((Date.now()-y)/1e3);if(ee>=3){let S=`${Yr(ye,v,!1,"blink")} ${p.dim}[${ee}s]${p.reset}`;Hn!==null?process.stdout.write(`\x1B[${Hn};1H\x1B[2K${S}`):process.stdout.write(`\r\x1B[2K${S}`)}},1e3)}let{results:Je,summaries:am}=await Nx(ye,!0,{...Ss,skipSummaries:!0});if(Mo&&(clearInterval(Mo),Mo=null),No){No=null;let $=Yr(ye,v,!1);Hn!==null?process.stdout.write(`\x1B[${Hn};1H\x1B[2K${$}
1236
+ `):process.stdout.write(`\r\x1B[2K${$}
1237
+ `),Hn=null}if(!Ss.skipSummaries){let $=am.filter((S,A)=>!(ye[A]&&ye[A].fnName==="ask_user"));for(let S of $)console.log(S);let y=ye.filter(S=>S&&S.fnName!=="ask_user").map(S=>S.fnName),ee=Se.record(0,y,k,R);ee&&ux(ee)}for(let $ of ye){if($.canExecute||!$.errorResult)continue;let y=typeof $.errorResult.content=="string"?$.errorResult.content:"";if((y.startsWith("BLOCKED:")||y.startsWith("PLAN MODE:")||y.startsWith("PLAN PHASE:"))&&(cn++,cn>=Gc)){F(`${p.red} \u2716 Loop abort: ${cn} consecutive blocked calls (pre-execution) \u2014 model not heeding BLOCKED messages${p.reset}`),l&&(l.stop(),l=null),c(null),Fe(v,O,R,k,H,{suppressHint:!0}),qe(q);return}}for(let $=0;$<ye.length;$++){let y=ye[$];if(!y.canExecute)continue;let ee=Je[$].content,S=ee.split(`
1238
+ `)[0],A=!S.startsWith("ERROR")&&!S.startsWith("CANCELLED")&&!S.startsWith("Command failed")&&!S.startsWith("EXIT");if(!A&&(y.fnName==="edit_file"||y.fnName==="patch_file")&&y.args?.path&&S.includes("old_text not found")){let N=Pn.get(y.args.path)||0;Pn.set(y.args.path,N+1)}if(!A&&(y.fnName==="read_file"||y.fnName==="edit_file")&&/file not found|does not exist|ENOENT/i.test(S)){if(sn++,sn>=2){F(`${p.yellow} \u26A0 File-not-found streak: ${sn} consecutive misses \u2014 forcing search${p.reset}`);let N={role:"user",content:`[SYSTEM] ${sn} 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.`};q.push(N),T.push(N)}}else A&&(y.fnName==="read_file"||y.fnName==="edit_file"||y.fnName==="search_files"||y.fnName==="glob_files")&&(sn=0);if(A&&y.fnName==="write_file"&&y.args?.path){let N=y.args.path.split("/").pop(),B=y.args.path.includes("/tests/")||y.args.path.includes("\\tests\\");if(/^(test_|demo_|temp_|tmp_|scratch_)/.test(N)&&!B){F(`${p.yellow} \u26A0 Temp file: "${N}" \u2014 delete with bash rm when done to keep the workspace clean${p.reset}`);let V={role:"user",content:`[HINT] "${y.args.path}" looks like a temporary test/demo file. Delete it with bash("rm ${y.args.path}") as soon as you're done \u2014 orphaned temp files count against session quality.`};q.push(V),T.push(V)}}if(A&&["write_file","edit_file","patch_file"].includes(y.fnName)&&y.args&&y.args.path){Pn.delete(y.args.path),R.add(y.args.path);let N=Ln(xe,y.args.path),B=y.args.path.split("/").slice(-2).join("/");if(N===fi){F(`${p.yellow} \u26A0 Loop warning: "${B}" edited ${N}\xD7 \u2014 possible edit loop${p.reset}`);let U={role:"user",content:`[SYSTEM WARNING] "${y.args.path}" edited ${N}\xD7. One more edit max, then move on.`};q.push(U),T.push(U)}else if(N>=Dh){F(`${p.red} \u2716 Loop abort: "${B}" edited ${N}\xD7 \u2014 aborting to prevent runaway loop${p.reset}`),l&&(l.stop(),l=null),c(null),Fe(v,O,R,k,H,{suppressHint:!0}),qe(q);return}}if(A&&y.canExecute&&we&&(rn=0),A&&y.canExecute&&!(we&&Pe==="plan")){let N=["read_file","grep","search_files","glob","list_directory","ssh_exec","find_files"];if(["write_file","edit_file","patch_file"].includes(y.fnName)){qt=0,Rt=!1,Xt=0,Ct++;let ne=y.args?.path||y.args?.file_path;ne&&(mc(on,ne,1),zt.delete(ne))}else N.includes(y.fnName)&&(qt++,Rt&&Xt++);let U=n.postEditCap,V=we&&Pe==="implement"?Math.min(Kc,6):Kc,J=ze?3:xt?Ct>0?2:4:Ct>0?U:V,oe=3;if(!we&&Rt&&(ze||xt&&Ct>=1||Xt>=oe)&&N.includes(y.fnName)){let ne=ze?`root cause already identified (${at})`:Xt>=oe?`${qt} consecutive reads without an edit`:`${Ct} file edit(s) already made`;F(`${p.red} \u2716 Blocked read-only tool: cap fired, ${ne}${p.reset}`),y.canExecute=!1,y.errorResult={role:"tool",content:ze?`BLOCKED: root cause already identified (${at}). Use edit_file to fix the issue \u2014 do not read more files.`:xt?"BLOCKED: files already written \u2014 continue with write_file or edit_file to finish the remaining tasks. Do not read more files.":Xt>=oe?`BLOCKED: You have read ${qt} 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: ${Ct} 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(qt>=J&&!Rt){if(Rt=!0,F(`${p.yellow} \u26A0 Investigation cap: ${qt} read-only calls without an edit \u2014 forcing implementation${p.reset}`),we&&Pe==="plan"){let Ue=[...T].reverse().find(Ut=>Ut.role==="assistant"),yt=typeof Ue?.content=="string"?Ue.content:"",ut=ho("implement",yt);ut&&(q.push(ut),T.push(ut),We=0,Ot=Mn("implement"))}let ne;ze?ne=`[SYSTEM] Root cause was already identified (${at}). Edit the file now \u2014 do not read more files.`:mt?ne="[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.":ne="[SYSTEM] You have read enough files. Now implement your fix using edit_file.";let Me={role:"user",content:ne};q.push(Me),T.push(Me)}}if((y.fnName==="bash"||y.fnName==="ssh_exec")&&y.args&&y.args.command){let N=y.args.command.replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),B=Ln(Yc,N);if(B===qh){F(`${p.yellow} \u26A0 Loop warning: same bash command run ${B}\xD7 \u2014 possible debug loop${p.reset}`);let U={role:"user",content:`[SYSTEM WARNING] Same bash command ${B}\xD7. Debug loop detected \u2014 try a different approach.`};q.push(U),T.push(U)}else if(B>=Fh){F(`${p.red} \u2716 Loop abort: same bash command run ${B}\xD7 \u2014 aborting runaway debug loop${p.reset}`),l&&(l.stop(),l=null),c(null),Fe(v,O,R,k,H,{suppressHint:!0}),qe(q);return}}if(y.fnName==="ssh_exec"){_t++;{let U=(Je[$]?.content??"").split(`
1239
+ `).map(V=>V.trim()).find(V=>V.length>0&&!V.startsWith("**")&&(V.startsWith("EXIT")||/^[\w./-]+:\s/.test(V)||V.startsWith("bash:")||V.startsWith("sh:")))??"";if(U){if(U===ti?jn++:(ti=U,jn=1),jn===3&&!mt){F(`${p.yellow} \u26A0 SSH repeated-error: "${U.slice(0,60)}" returned ${jn}\xD7 \u2014 nudging to change approach${p.reset}`);let V={role:"user",content:`[SYSTEM WARNING] The last ${jn} SSH commands all failed with the same error: "${U}". 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).`};q.push(V),T.push(V)}}else ti="",jn=0}if(_t>=sm){F(`${p.red} \u2716 SSH storm abort: ${_t} consecutive ssh_exec calls \u2014 aborting${p.reset}`),l&&(l.stop(),l=null),c(null),Fe(v,O,R,k,H,{suppressHint:!0}),qe(q);return}else if(_t===vs){{let U=Qe(),{messages:V}=jt(T,U);T=V}mt=!0,Kr++,F(`${p.yellow} \u26A0 SSH storm warning (#${Kr}): ${_t} consecutive ssh_exec calls \u2014 blocking further SSH${p.reset}`);let B={role:"user",content:ze?`[SYSTEM WARNING] ${_t} consecutive SSH calls. Root cause identified (${at}). Read the file that needs fixing, then edit it.`:`[SYSTEM WARNING] ${_t} 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.`};q.push(B),T.push(B)}}else y.canExecute&&(_t=0);if(y.fnName==="bash"&&y.canExecute){let U=(Je[$]?.content??"").split(`
1240
+ `).map(V=>V.trim()).find(V=>V.length>0&&(V.startsWith("EXIT")||/^[\w./-]+:\s/.test(V)||V.startsWith("bash:")||V.startsWith("sh:")))??"";if(U){if(U===ni?Dn++:(ni=U,Dn=1),Dn===3){F(`${p.yellow} \u26A0 Bash repeated-error: "${U.slice(0,60)}" returned ${Dn}\xD7 \u2014 nudging to change approach${p.reset}`);let V={role:"user",content:`[SYSTEM WARNING] The last ${Dn} bash commands all failed with the same error: "${U}". 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).`};q.push(V),T.push(V)}}else ni="",Dn=0}if(y.fnName==="bash"&&y.canExecute&&!gc&&y.args?.command){let N=Je[$]?.content??"";if(/git\s+commit\b/.test(y.args.command)&&!N.startsWith("EXIT")&&!N.startsWith("ERROR")&&(/\[\S+\s+[a-f0-9]+\]/.test(N)||N.includes("files changed")||N.includes("file changed")||N.includes("insertions(+)")||N.includes("create mode"))){gc=!0,po=0,F(`${p.green} \u2713 Git commit detected \u2014 post-commit verification cap active (max 2 git status/diff/log)${p.reset}`);let V={role:"user",content:"[SYSTEM] \u2713 Git commit succeeded. Your changes are committed. Do NOT run further git status / git diff / git log calls \u2014 the commit is done. Write your final summary and stop. Running extra verification commands wastes tool calls and hurts session quality."};q.push(V),T.push(V)}}if(gc&&y.fnName==="bash"&&y.args?.command&&/git\s+(status|diff|log|show)\b/.test(y.args.command)&&(po++,po>2)){F(`${p.yellow} \u26A0 Post-commit git verification blocked (call ${po})${p.reset}`);let B={role:"user",content:"[SYSTEM] \u26A0 STOP: You already ran "+(po-1)+" git verification commands after committing. The commit is confirmed. Write your final summary NOW and do not make any more tool calls."};q.push(B),T.push(B)}if(A&&y.fnName==="grep"&&y.args&&y.args.pattern){let N=`${y.args.pattern}|${y.args.path||""}`,B=Ln(Bh,N);if(B===Wh){F(`${p.yellow} \u26A0 Loop warning: grep pattern "${y.args.pattern.slice(0,40)}" run ${B}\xD7 \u2014 possible search loop${p.reset}`);let U={role:"user",content:`[SYSTEM WARNING] Same grep pattern ${B}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};q.push(U),T.push(U)}else if(B>=Uh){F(`${p.red} \u2716 Loop abort: grep pattern run ${B}\xD7 \u2014 aborting runaway search loop${p.reset}`),l&&(l.stop(),l=null),c(null),Fe(v,O,R,k,H,{suppressHint:!0}),qe(q);return}if(y.args.path){let U=Ln(pi,y.args.path),V=Dt(Fn,y.args.path)>=1;if(U===(V?1:Hh)){let oe=y.args.path.split("/").slice(-2).join("/");F(`${p.yellow} \u26A0 Loop warning: "${oe}" grepped ${U}\xD7 with different patterns \u2014 context flood risk${p.reset}`);let he={role:"user",content:V?`[SYSTEM NOTE] "${y.args.path}" was already fully read \u2014 its content is in context. Grepping it again is redundant; use the context you already have.`:`[SYSTEM NOTE] "${y.args.path}" grepped ${U}\xD7 \u2014 use the search results already in context instead of searching again.`};q.push(he),T.push(he)}}}if(A&&(y.fnName==="glob"||y.fnName==="glob_files"||y.fnName==="search_files")&&y.args){let N=y.args.pattern||y.args.query||y.args.path||"",B=Ln(Yh,N);if(B===Gh){F(`${p.yellow} \u26A0 Loop warning: glob pattern "${N.slice(0,40)}" run ${B}\xD7 \u2014 possible search loop${p.reset}`);let V={role:"user",content:`[SYSTEM WARNING] Same glob/search pattern ${B}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};q.push(V),T.push(V)}else if(B>=Kh){F(`${p.red} \u2716 Loop abort: glob pattern run ${B}\xD7 \u2014 aborting runaway search loop${p.reset}`),l&&(l.stop(),l=null),c(null),Fe(v,O,R,k,H,{suppressHint:!0}),qe(q);return}let U=N.replace(/\*+/g," ").replace(/[{}()\[\],.\/\\]/g," ").split(/\s+/).filter(V=>V.length>=4&&!/^\.(js|ts|py|json|md|yaml|yml|txt|css|html|sh)$/.test(V));for(let V of U){let J=V.toLowerCase();ko.has(J)||ko.set(J,new Set);let oe=ko.get(J);if(oe.add(N),oe.size===Xh){F(`${p.red} \u2716 Glob core-term block: ${oe.size} different patterns all searching for "${J}" \u2014 search loop${p.reset}`);let he={role:"user",content:`[SYSTEM WARNING] You have searched for "${J}" using ${oe.size} different glob patterns. This is a search loop \u2014 the file you are looking for likely does not exist. Stop searching and work with the files you have already found, or ask the user for clarification.`};q.push(he),T.push(he)}else if(oe.size===zh){F(`${p.yellow} \u26A0 Glob core-term warning: ${oe.size} different patterns searching for "${J}"${p.reset}`);let he={role:"user",content:`[SYSTEM WARNING] ${oe.size} different glob patterns all target "${J}". If previous searches returned no results, the file probably does not exist \u2014 stop searching and proceed with available information.`};q.push(he),T.push(he)}}}let Q=(y.args?.command||y.args?.cmd||y.args?.script||"").toLowerCase(),D=/\b(health|healthcheck|health-check|status|check|ping|validate|alive|ready)\b/.test(Q)||/\/(health|status|ping|ready|alive)\b/.test(Q);if(A&&(y.fnName==="bash"||y.fnName==="ssh_exec")&&D&&ee.includes('"valid":true')){{let B=Qe();if(Tt(T,B).percentage>=60){let{messages:V,tokensRemoved:J}=jt(T,B);J>0&&(T=V,console.log(`${p.dim} [pre-stop-compress \u2014 ~${J} tokens freed before STOP injection, now ${Math.round(Tt(T,B).percentage)}%]${p.reset}`))}}let N={role:"user",content:'[SYSTEM STOP] Tool result contains {"valid":true}. The token/service is valid and reachable. STOP all further investigation immediately. Report to the user that the token is valid, the service is healthy, and no fix is needed. Do NOT read any more log files.'};q.push(N),T.push(N),console.log(`${p.cyan} \u2713 Health-check stop signal detected \u2014 injecting STOP instruction${p.reset}`)}if(ee.startsWith("BLOCKED:")){if(cn++,cn>=Gc){F(`${p.red} \u2716 Loop abort: ${cn} consecutive blocked calls \u2014 model not heeding BLOCKED messages${p.reset}`),l&&(l.stop(),l=null),c(null),Fe(v,O,R,k,H,{suppressHint:!0}),qe(q);return}}else cn=0;if(A)an=0,gi=!0;else if(an++,an===Qh){F(`${p.yellow} \u26A0 Loop warning: ${an} consecutive tool errors \u2014 possible stuck loop${p.reset}`);let N={role:"user",content:`[SYSTEM WARNING] ${an} consecutive errors. Stuck loop \u2014 try fundamentally different approach or declare done.`};q.push(N),T.push(N)}else if(an>=em){F(`${p.red} \u2716 Loop abort: ${an} consecutive errors \u2014 aborting stuck loop${p.reset}`),l&&(l.stop(),l=null),c(null),Fe(v,O,R,k,H,{suppressHint:!0}),qe(q);return}if(A&&y.fnName==="read_file"&&y.args&&y.args.path){k.add(y.args.path);let N=Ln(Fn,y.args.path);{let J=y.args.line_start!=null&&y.args.line_start||1,oe=y.args.line_start!=null?y.args.line_end||J+350:350;zt.has(y.args.path)||zt.set(y.args.path,[]),zt.get(y.args.path).push([J,oe])}if(y._scrollWarn){let{sectionCount:J,path:oe}=y._scrollWarn,he={role:"user",content:`[SYSTEM WARNING] "${oe}" \u2014 you have now read ${J} different sections of this file. This is a file-scroll pattern. Stop reading sections and use grep_search to find the specific lines you need instead.`};q.push(he),T.push(he),F(`${p.yellow} \u26A0 Scroll warning: "${oe.split("/").slice(-2).join("/")}" \u2014 ${J} sections read \u2014 use grep instead${p.reset}`)}let B=y.args.path.split("/").slice(-2).join("/"),U=!y.args?.line_start&&!y.args?.line_end,V=we&&Pe==="plan";if(!V&&U&&N===Vh){{let oe=Qe();if(Tt(T,oe).percentage>=60){let{messages:ne}=jt(T,oe);T=ne}}F(`${p.yellow} \u26A0 Loop warning: "${B}" read unbounded ${N}\xD7 \u2014 use line_start/line_end${p.reset}`);let J={role:"user",content:`[SYSTEM WARNING] "${y.args.path}" read ${N}\xD7 without line ranges. Use line_start/line_end to read specific sections \u2014 do not re-read the full file.`};q.push(J),T.push(J)}else if(!V&&U&&N>=Jh){F(`${p.red} \u2716 Loop abort: "${B}" read unbounded ${N}\xD7 \u2014 aborting runaway read loop${p.reset}`),l&&(l.stop(),l=null),c(null),Fe(v,O,R,k,H,{suppressHint:!0}),qe(q);return}}if(y.fnName==="spawn_agents"){let N=(ee.match(/\bStatus: done\b/g)||[]).length;if((ee.match(/\bStatus: truncated\b/g)||[]).length>0&&N===0){if(ln++,ln===tm){F(`${p.yellow} \u26A0 Swarm warning: all sub-agents hit iteration limit ${ln}\xD7 in a row${p.reset}`);let U={role:"user",content:`[SYSTEM WARNING] Sub-agents truncated ${ln}\xD7 in a row. Stop spawning \u2014 try different approach or report findings.`};q.push(U),T.push(U)}else if(ln>=nm){console.log(`${p.red} \u2716 Swarm abort: all sub-agents hit iteration limit ${ln}\xD7 \u2014 aborting stuck swarm${p.reset}`),l&&(l.stop(),l=null),c(null),Fe(v,O,R,k,H,{suppressHint:!0}),qe(q);return}}else N>0&&(ln=0)}}{let y=Je.reduce((ee,S)=>ee+(typeof S.content=="string"?S.content.length:0),0);if(y>2e5){let ee=Je.map((S,A)=>({i:A,len:typeof S.content=="string"?S.content.length:0})).sort((S,A)=>A.len-S.len);for(let{i:S,len:A}of ee){if(y<=2e5)break;let Q=y-2e5,D=Math.max(A-Q,500);D<A&&typeof Je[S].content=="string"&&(Je[S]={...Je[S],content:Je[S].content.substring(0,D)+`
1241
+ ...(truncated ${A-D} chars \u2014 per-message budget)`},y-=A-D)}}}for(let $ of Je)q.push($),T.push($);if(!ze)for(let $=0;$<Je.length;$++){if(!ye[$]||ye[$].fnName!=="ssh_exec")continue;let y=Je[$];if(!y||typeof y.content!="string")continue;let ee=hc(y.content);if(ee){ze=!0,at=ee.slice(0,120),qt=0,Rt=!1,Xt=0,F(`${p.yellow} \u26A1 Root cause detected: ${at} \u2014 fix phase (read budget: 3)${p.reset}`);let S={role:"user",content:`[SYSTEM] Root cause identified: ${at}. Read only the file that needs fixing, then edit it. Do not read other files.`};q.push(S),T.push(S);break}}for(let $=0;$<Je.length;$++){let y=ye[$];if(!y)continue;let ee=typeof Je[$]?.content=="string"?Je[$].content:"";if(y.fnName==="create_task"){let S=ee.match(/Task #(\d+) created/),A=typeof y.args?.subject=="string"?y.args.subject:"";S&&A&&vo.set(S[1],A)}else if((y.fnName==="write_file"||y.fnName==="edit_file")&&!ee.startsWith("BLOCKED:")&&ee.trim().length>0){let A=(typeof y.args?.path=="string"?y.args.path:typeof y.args?.file_path=="string"?y.args.file_path:"").split("/").pop().toLowerCase(),Q=A.split(/[._\-/]/).filter(D=>D.length>2);for(let[D,le]of vo){if(So.has(D))continue;let N=le.toLowerCase().split(/\W+/).filter(U=>U.length>3);Q.filter(U=>N.some(V=>V.includes(U)||U.includes(V))).length>=1&&(So.add(D),F(`${p.green} \u2714 Auto-matched task #${D} to ${A}: ${le.slice(0,60)}${p.reset}`))}}}{let $=Qe();if(Tt(T,$).percentage>=78){let{messages:ee,tokensRemoved:S}=jt(T,$);S>0&&(T=ee,console.log(`${p.dim} [auto-compressed \u2014 ~${S} tokens freed, now ${Math.round(Tt(T,$).percentage)}%]${p.reset}`))}}let tl=Lx();if(tl){let $={role:"user",content:`[User note mid-run]: ${tl}`};q.push($),T.push($),console.log(`${p.cyan} \u270E Context added${p.reset}`)}}if(We>=Ot){if(l&&(l.stop(),l=null),c(null),Fe(v,O,R,k,H),qe(q),ic(q),we&&Pe==="plan"){let Wn=[...q].reverse().find(Ve=>Ve.role==="assistant"),lt=typeof Wn?.content=="string"?Wn.content:"",Un=ho("implement",lt);if(Un){q.push(Un),T=[{role:"system",content:await Cc()},...q],Ot=Mn("implement"),F(`${p.yellow} \u26A0 Plan budget exhausted \u2014 auto-transitioning to implement${p.reset}`);continue e}}else if(we&&Pe==="verify"){F(`${p.yellow} \u26A0 Verify budget exhausted \u2014 completing session${p.reset}`);break e}let{getActiveProviderName:be}=Ge();if(be()==="ollama"&&mi<zc){if(R.size===0&&!gi){console.log(`${p.yellow} \u26A0 Max iterations reached with no progress. Stopping.${p.reset}`);break e}mi++,Ot=20,console.log(`${p.dim} \u2500\u2500 auto-extending (+20 turns, ext ${mi}/${zc}) \u2500\u2500${p.reset}`);continue e}if(console.log(`
1242
+ ${p.yellow}\u26A0 Max iterations reached.${p.reset}`),await mh(" Continue for 20 more turns?")){Ot=20;continue e}console.log(`${p.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${p.reset}`)}break e}}xh.exports={processInput:Gx,clearConversation:Dx,getConversationLength:Fx,getConversationMessages:Bx,setConversationMessages:Wx,setAbortSignalGetter:mx,setMaxIterations:hx,invalidateSystemPromptCache:xc,clearToolFilterCache:kx,getCachedFilteredTools:$h,buildSystemPrompt:Cc,splitSystemPrompt:jx,SYSTEM_PROMPT_DYNAMIC_BOUNDARY:Rc,getProjectContextHash:wh,buildUserContent:yh,detectAndTruncateLoop:wc,injectMidRunNote:Mx,resetSessionTracking:_h}});var Ge=re((Hv,Rh)=>{var{OllamaProvider:Kx}=El(),{OpenAIProvider:zx}=Al(),{AnthropicProvider:Xx}=Ll(),{GeminiProvider:Vx}=Dl(),{LocalProvider:Jx}=Bl(),{checkBudget:Zx}=Jo(),Dc={top:{ollama:"kimi-k2:1t",openai:"gpt-4.1",anthropic:"claude-sonnet-4-5",gemini:"gemini-2.5-pro"},strong:{ollama:"qwen3-coder:480b",openai:"gpt-4o",anthropic:"claude-sonnet",gemini:"gemini-2.5-flash"},fast:{ollama:"devstral-small-2:24b",openai:"gpt-4.1-mini",anthropic:"claude-haiku",gemini:"gemini-2.0-flash"}},Ic=(process.env.OLLAMA_FALLBACK_CHAIN||"").split(",").map(t=>t.trim()).filter(Boolean),Sh={};for(let[t,e]of Object.entries(Dc))for(let s of Object.values(e))Sh[s]=t;function jc(t,e){let s=Sh[t];return s&&Dc[s][e]||t}var Xe={},ct=null,Be=null,Eo=[];function kt(){if(Object.keys(Xe).length>0)return;xs("ollama",new Kx),xs("openai",new zx),xs("anthropic",new Xx),xs("gemini",new Vx),xs("local",new Jx);let t=process.env.DEFAULT_PROVIDER||"ollama",e=process.env.DEFAULT_MODEL||null;Xe[t]?(ct=t,Be=e||Xe[t].defaultModel):(ct="ollama",Be="kimi-k2.5");let s=process.env.FALLBACK_CHAIN;s&&(Eo=s.split(",").map(n=>n.trim()).filter(Boolean))}function xs(t,e){Xe[t]=e}function Qx(t){return kt(),Xe[t]||null}function qc(){return kt(),Xe[ct]||null}function ek(){return kt(),ct}function tk(){return kt(),Be}function nk(){kt();let t=qc();if(!t)return{id:Be,name:Be,provider:ct};let e=t.getModel(Be);return e?{...e,provider:ct}:{id:Be,name:Be,provider:ct}}function Eh(t){if(!t)return{provider:null,model:null};let e=t.indexOf(":");if(e>0){let s=t.slice(0,e);if(Xe[s]||["ollama","openai","anthropic","gemini","local"].includes(s))return{provider:s,model:t.slice(e+1)}}return{provider:null,model:t}}function sk(t){kt();let{provider:e,model:s}=Eh(t);if(e){let o=Xe[e];return o&&(o.getModel(s)||e==="local"||e==="ollama")?(ct=e,Be=s,ci(),!0):!1}let n=qc();if(n&&n.getModel(s))return Be=s,ci(),!0;for(let[o,r]of Object.entries(Xe))if(r.getModel(s))return ct=o,Be=s,ci(),!0;return!1}function ci(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=kh();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=It();t()}catch{}}function ok(){kt();let t=new Set;for(let e of Object.values(Xe))for(let s of e.getModelNames())t.add(s);return Array.from(t)}function rk(){return kt(),Object.entries(Xe).map(([t,e])=>({provider:t,configured:e.isConfigured(),models:Object.values(e.getModels()).map(s=>({...s,active:t===ct&&s.id===Be}))}))}function ik(){kt();let t=[];for(let[e,s]of Object.entries(Xe)){let n=s.isConfigured();for(let o of Object.values(s.getModels()))t.push({spec:`${e}:${o.id}`,name:o.name,provider:e,configured:n})}return t}function ak(t){Eo=Array.isArray(t)?t:[]}function ck(){return[...Eo]}function vh(t){let e=t.message||"",s=t.code||"";return!!(e.includes("429")||e.includes("500")||e.includes("502")||e.includes("503")||e.includes("504")||s==="ECONNABORTED"||s==="ETIMEDOUT"||s==="ECONNREFUSED"||s==="ECONNRESET"||s==="EHOSTUNREACH"||s==="ENETUNREACH"||s==="EPIPE"||s==="ERR_SOCKET_CONNECTION_TIMEOUT"||e.includes("socket disconnected")||e.includes("TLS")||e.includes("ECONNRESET")||e.includes("ECONNABORTED")||e.includes("network")||e.includes("ETIMEDOUT"))}async function Th(t){let e=[ct,...Eo.filter(r=>r!==ct)],s,n=0,o=0;for(let r=0;r<e.length;r++){let i=e[r],a=Xe[i];if(!a||!a.isConfigured())continue;o++;let c=Zx(i);if(!c.allowed){n++,s=new Error(`Budget limit reached for ${i}: $${c.spent.toFixed(2)} / $${c.limit.toFixed(2)}`);continue}try{let l=r>0,u=l?jc(Be,i):Be;return l&&u!==Be&&process.stderr.write(` [fallback: ${i}:${u}]
1243
+ `),await t(a,i,u)}catch(l){if(s=l,!vh(l)||r>=e.length-1)throw l;if(i==="ollama"&&Ic.length>0){let u=isFallback?jc(Be,i):Be;for(let d of Ic)if(d!==u)try{return process.stderr.write(` [ollama fallback: ${d}]
1244
+ `),await t(a,i,d)}catch(f){if(s=f,!vh(f))throw f}}continue}}throw n>0&&n===o?new Error("All providers are over budget. Use /budget to check limits or /budget <provider> off to remove a limit."):o===0?new Error("No configured provider available"):s||new Error("No configured provider available")}async function lk(t,e,s={}){return kt(),Th((n,o,r)=>n.stream(t,e,{model:r,signal:s.signal,...s}))}async function uk(t,e,s={}){if(kt(),s.provider){let n=Xe[s.provider];if(!n||!n.isConfigured())throw new Error(`Provider '${s.provider}' is not available`);let o={model:s.model||Be,...s};try{return await n.chat(t,e,o)}catch(r){if(typeof n.stream=="function")try{return await n.stream(t,e,{...o,onToken:()=>{}})}catch{}throw r}}return Th(async(n,o,r)=>{try{return await n.chat(t,e,{model:r,...s})}catch(i){if(typeof n.stream=="function")try{return await n.stream(t,e,{model:r,...s,onToken:()=>{}})}catch{}throw i}})}function dk(){kt();let t=[];for(let[e,s]of Object.entries(Xe))s.isConfigured()&&t.push({name:e,models:Object.values(s.getModels())});return t}function fk(){for(let t of Object.keys(Xe))delete Xe[t];ct=null,Be=null,Eo=[]}Rh.exports={registerProvider:xs,getProvider:Qx,getActiveProvider:qc,getActiveProviderName:ek,getActiveModelId:tk,getActiveModel:nk,setActiveModel:sk,getModelNames:ok,parseModelSpec:Eh,listProviders:rk,listAllModels:ik,callStream:lk,callChat:uk,getConfiguredProviders:dk,setFallbackChain:ak,getFallbackChain:ck,resolveModelForProvider:jc,MODEL_EQUIVALENTS:Dc,OLLAMA_FALLBACK_MODELS:Ic,_reset:fk}});var{C:W}=He(),pk=Ge(),{TOOL_DEFINITIONS:Ch}=ts(),{saveRoutingConfig:hk}=ps(),Wc=[{id:"read-package",category:"file-ops",prompt:"Read the file package.json and show me its contents.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("package.json")},{id:"write-file",category:"file-ops",prompt:'Create a file at /tmp/nex-bench-test.txt with the content "benchmark run".',expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&typeof t.content=="string"},{id:"edit-file",category:"file-ops",prompt:'In the file src/config.js, replace the string "debug: false" with "debug: true".',expectedTool:["edit_file","patch_file"],validateArgs:t=>!!(t.path&&t.old_string!==void 0&&t.new_string!==void 0||t.path&&Array.isArray(t.patches)&&t.patches.length>0)},{id:"list-directory",category:"file-ops",prompt:"Show me all files and folders in the cli/ directory.",expectedTool:["list_directory","glob"],validateArgs:t=>!!(typeof t.path=="string"&&t.path.includes("cli")||typeof t.pattern=="string"&&t.pattern.includes("cli"))},{id:"glob-js-files",category:"file-ops",prompt:"Find all JavaScript files (*.js) recursively in the cli/ directory.",expectedTool:"glob",validateArgs:t=>typeof t.pattern=="string"&&t.pattern.includes(".js")},{id:"read-partial",category:"file-ops",prompt:"Read only lines 20 to 40 of src/index.js \u2014 I need to see that specific range.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("index")&&(typeof t.line_start=="number"||typeof t.start_line=="number")},{id:"glob-ts-defs",category:"file-ops",prompt:"Find all TypeScript type definition files (*.d.ts) anywhere in the project.",expectedTool:"glob",validateArgs:t=>typeof t.pattern=="string"&&t.pattern.includes(".d.ts")},{id:"write-gitignore",category:"file-ops",prompt:"Create a .gitignore file at the project root that ignores node_modules/ and dist/.",expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes(".gitignore")&&typeof t.content=="string"&&t.content.includes("node_modules")},{id:"edit-version-bump",category:"file-ops",prompt:'In package.json, change the version field from "1.0.0" to "1.1.0".',expectedTool:["edit_file","patch_file"],validateArgs:t=>!!(t.path&&t.path.includes("package"))},{id:"grep-with-filter",category:"search",prompt:"Search for all calls to require() but only inside .js files in the cli/ directory.",expectedTool:["grep","search_files"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("require")},{id:"no-tool-http-port",category:"reasoning",prompt:"What is the default port used by the HTTP protocol?",expectedTool:null,validateArgs:()=>!0},{id:"bash-node-version",category:"shell",prompt:"Check which version of Node.js is currently installed on this system.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("node")&&(t.command.includes("--version")||t.command.includes("-v"))},{id:"search-constant",category:"search",prompt:'Search for the string "DEFAULT_MODEL" across all files in the project.',expectedTool:["search_files","grep"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("DEFAULT_MODEL")},{id:"grep-function-def",category:"search",prompt:'Find where the function "callStream" is defined in the codebase.',expectedTool:["grep","search_files"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("callStream")},{id:"search-todos",category:"search",prompt:"Find all TODO comments in the source code.",expectedTool:["grep","search_files","bash"],validateArgs:t=>JSON.stringify(t).toUpperCase().includes("TODO")},{id:"git-branch",category:"shell",prompt:"What git branch am I currently on?",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("git")},{id:"git-status",category:"shell",prompt:"Show me the current git status of the repository.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("git status")},{id:"npm-install",category:"shell",prompt:"Run npm install to install project dependencies.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("npm")},{id:"schema-strict",category:"schema",prompt:"Read the file README.md",expectedTool:"read_file",validateArgs:(t,e)=>{let s=e?.function?.parameters||{},n=s.required||[],o=Object.keys(s.properties||{});return n.every(r=>t[r]!==void 0)&&Object.keys(t).every(r=>o.includes(r))}},{id:"multi-step-version",category:"multi-step",prompt:"What is the current version of this project? Check the source files.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("package.json")},{id:"multi-step-count",category:"multi-step",prompt:"How many JavaScript files are in the cli/ directory? Count them.",expectedTool:["bash","glob","list_directory"],validateArgs:t=>!!(typeof t.command=="string"&&t.command.includes("cli")||typeof t.pattern=="string"&&t.pattern.includes("cli")||typeof t.path=="string"&&t.path.includes("cli"))},{id:"no-tool-reasoning",category:"reasoning",prompt:'What does the acronym "API" stand for?',expectedTool:null,validateArgs:()=>!0},{id:"frontend-find-hook",category:"frontend",prompt:"Find all files that import useState from React.",expectedTool:["grep","search_files"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("useState")},{id:"frontend-create-component",category:"frontend",prompt:"Create a React functional component called Button that accepts a label prop and renders a styled button element. Save it to src/components/Button.jsx.",expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&(t.path.includes(".jsx")||t.path.includes(".tsx")||t.path.includes(".js"))&&typeof t.content=="string"},{id:"frontend-edit-css",category:"frontend",prompt:'In the file src/styles.css, change the background-color value from "blue" to "red".',expectedTool:["edit_file","patch_file"],validateArgs:t=>t.path&&t.old_string!==void 0?t.path.includes(".css")||t.old_string.includes("blue")||t.old_string.includes("background"):!!(t.path&&Array.isArray(t.patches))},{id:"frontend-glob-components",category:"frontend",prompt:"Find all JSX and TSX component files in the components/ directory.",expectedTool:"glob",validateArgs:t=>typeof t.pattern=="string"&&(t.pattern.includes(".jsx")||t.pattern.includes(".tsx")||t.pattern.includes("{jsx,tsx}"))},{id:"frontend-list-assets",category:"frontend",prompt:"List all files in the src/assets/ directory.",expectedTool:["list_directory","glob"],validateArgs:t=>!!(typeof t.path=="string"&&t.path.includes("assets")||typeof t.pattern=="string"&&t.pattern.includes("assets"))},{id:"sysadmin-port-check",category:"sysadmin",prompt:"Which process is currently listening on port 3000?",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("lsof")||t.command.includes("ss")||t.command.includes("netstat")||t.command.includes("3000"))},{id:"sysadmin-nginx-config",category:"sysadmin",prompt:"Create an nginx server block that proxies requests to localhost:3000. Save it to /etc/nginx/sites-available/myapp.",expectedTool:["write_file","bash"],validateArgs:t=>!!(t.path&&(t.path.includes("nginx")||t.path.includes("sites-available"))||t.command&&t.command.includes("nginx"))},{id:"sysadmin-service-status",category:"sysadmin",prompt:"Check the status of the nginx service and show if it is running.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("systemctl")||t.command.includes("service")||t.command.includes("nginx"))},{id:"sysadmin-error-log",category:"sysadmin",prompt:"Show the last 100 lines of the nginx error log.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("tail")||t.command.includes("journalctl")||t.command.includes("nginx"))},{id:"sysadmin-docker-compose",category:"sysadmin",prompt:"Create a docker-compose.yml file for a Node.js application with a PostgreSQL database.",expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("docker-compose")&&typeof t.content=="string"},{id:"data-sql-query",category:"data",prompt:"Write a SQL query to find all users who have not logged in for more than 30 days. Save it to queries/inactive-users.sql.",expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&(t.path.includes(".sql")||t.path.includes("quer"))&&typeof t.content=="string"},{id:"data-find-json-key",category:"data",prompt:'Find all JSON files in the project that contain the key "userId".',expectedTool:["grep","search_files"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("userId")},{id:"data-python-csv",category:"data",prompt:'Write a Python script that reads data.csv and calculates the average of the "price" column. Save it to scripts/average_price.py.',expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes(".py")&&typeof t.content=="string"},{id:"data-find-migrations",category:"data",prompt:"Find all database migration files in this project.",expectedTool:["glob","search_files","grep"],validateArgs:t=>JSON.stringify(t).toLowerCase().includes("migrat")},{id:"data-find-schema",category:"data",prompt:"Find where the database schema or models are defined in this project.",expectedTool:["grep","glob"],validateArgs:t=>!!(t.pattern&&/schema|model|migration/i.test(t.pattern)||t.pattern&&/schema|model|migration/i.test(t.pattern))},{id:"data-write-query",category:"data",prompt:"Write a SQL query to find all users who registered in the last 30 days and save it to queries/recent-users.sql.",expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes(".sql")},{id:"data-read-env",category:"data",prompt:"Read the .env file to find the database connection string.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&/\.env|env\./i.test(t.path)},{id:"resilience-edit-failed",category:"resilience",prompt:"Your edit_file call on server.js failed: old_string 'const PORT = 3000' was not found in the file. What do you do next to recover?",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("server")},{id:"resilience-file-not-found",category:"resilience",prompt:"read_file returned 'file not found' for src/utils/helpers.js. You need to find where the helper functions are now. What tool do you use?",expectedTool:["glob_files","bash"],validateArgs:t=>{let e=JSON.stringify(t).toLowerCase();return e.includes("src")||e.includes("helper")||e.includes("util")||e.includes("*.js")}},{id:"resilience-large-file-nav",category:"resilience",prompt:"The file src/api.js is 2800 lines. You need to locate the authenticateUser function. What is the most efficient tool to use \u2014 read_file or bash with grep?",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("grep")||t.command.includes("rg")||t.command.includes("awk"))},{id:"resilience-broken-import",category:"resilience",prompt:"TypeScript reports: Cannot find module './config'. The file was recently renamed. What tool do you use to find the new location?",expectedTool:["glob_files","bash"],validateArgs:t=>{let e=JSON.stringify(t).toLowerCase();return e.includes("config")||e.includes("*.ts")||e.includes("*.js")||e.includes("find")}},{id:"resilience-bash-error-recover",category:"resilience",prompt:"The command 'npm test' failed with exit code 1. The output contains 'SyntaxError: Unexpected token' in src/parser.js:45. What is your next action?",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("parser")},{id:"resilience-grep-no-match",category:"resilience",prompt:"grep returned zero matches for 'getUserById' in src/. The function exists but may have been renamed. What bash command finds all exported function names in src/ to identify the current name?",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("grep")||t.command.includes("rg")||t.command.includes("src"))},{id:"ssh-exec-log",category:"ssh",prompt:'Show the last 50 lines of /var/log/nginx/error.log on server "prod-1".',expectedTool:"ssh_exec",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("tail")||t.command.includes("log"))&&(typeof t.host=="string"||typeof t.profile=="string")},{id:"ssh-exec-service",category:"ssh",prompt:'Restart the nginx service on server "prod-1".',expectedTool:"ssh_exec",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("nginx")||t.command.includes("systemctl")||t.command.includes("restart"))&&(typeof t.host=="string"||typeof t.profile=="string")},{id:"ssh-exec-port",category:"ssh",prompt:'Check if port 8080 is listening on server "prod-1".',expectedTool:"ssh_exec",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("8080")||t.command.includes("ss")||t.command.includes("netstat")||t.command.includes("lsof"))&&(typeof t.host=="string"||typeof t.profile=="string")},{id:"ssh-exec-processes",category:"ssh",prompt:'Show the top CPU-consuming processes on server "prod-1".',expectedTool:"ssh_exec",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("top")||t.command.includes("ps")||t.command.includes("htop"))&&(typeof t.host=="string"||typeof t.profile=="string")},{id:"git-diff-staged",category:"git",prompt:"Show all staged changes before committing.",expectedTool:["git_diff","bash"],validateArgs:t=>!!(t.staged===!0||t.staged==="true"||typeof t.command=="string"&&t.command.includes("diff"))},{id:"git-log-recent",category:"git",prompt:"Show the last 5 commit messages with their hashes.",expectedTool:["git_log","bash"],validateArgs:t=>!!(typeof t.limit=="number"||typeof t.n=="number"||typeof t.command=="string"&&t.command.includes("log"))},{id:"git-status-check",category:"git",prompt:"Check if there are any uncommitted changes in the repository.",expectedTool:["git_status","bash"],validateArgs:t=>t.path===void 0&&t.command===void 0?!1:(typeof t.command=="string"&&t.command.includes("status"),!0)},{id:"agentic-test-first",category:"agentic",prompt:"Run the full test suite. If any tests fail, identify the failing test file and read it to understand the issue.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("test")||t.command.includes("jest")||t.command.includes("npm"))},{id:"agentic-read-then-act",category:"agentic",prompt:"Read the project README.md, find the TODO section, and list which items are completed.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("README")},{id:"agentic-build-deploy",category:"agentic",prompt:"Build the project with npm run build, then verify the output exists in the dist/ directory.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("build")||t.command.includes("npm"))},{id:"agentic-spawn-parallel",category:"agentic",prompt:"Search for all TODO comments and all FIXME comments across the codebase in parallel using multiple agents.",expectedTool:"spawn_agents",validateArgs:t=>Array.isArray(t.agents)&&t.agents.length>=2},{id:"agentic-multi-investigate",category:"agentic",prompt:"The app is crashing on startup. Spawn parallel agents to check: (1) recent git changes, (2) npm dependency issues, (3) the main entry file for syntax errors.",expectedTool:"spawn_agents",validateArgs:t=>Array.isArray(t.agents)&&t.agents.length>=2}],Ah=[{id:"phase-plan-diagnosis",category:"phase-plan",prompt:"The server returns 500 on /api/users. The error log shows: TypeError: Cannot read property 'map' of undefined at routes/users.js:42. Read the relevant file to diagnose the root cause.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&/users/i.test(t.path)},{id:"phase-plan-search",category:"phase-plan",prompt:"We're getting CORS errors in production. Search the codebase for where CORS middleware is configured.",expectedTool:"grep",validateArgs:t=>typeof t.pattern=="string"&&/cors/i.test(t.pattern)},{id:"phase-plan-context",category:"phase-plan",prompt:"The login page shows a blank screen after the last deploy. Check git log for recent changes that might have broken it.",expectedTool:"git_log",validateArgs:()=>!0},{id:"phase-verify-test",category:"phase-verify",prompt:"The file src/utils.js was modified to fix a null pointer bug. Run the test suite to verify the fix works correctly.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&/test|jest|npm\s+test|pytest|mocha/.test(t.command)},{id:"phase-verify-read",category:"phase-verify",prompt:"A patch was applied to config/database.js to fix the connection pool. Read the file to verify the changes look correct.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&/database/i.test(t.path)},{id:"phase-verify-lint",category:"phase-verify",prompt:"Code was modified in src/components/Header.tsx. Run the linter to check for any style violations.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&/lint|eslint|prettier|tsc/.test(t.command)},{id:"phase-plan-git-blame",category:"phase-plan",prompt:"A production bug was introduced 2 days ago. Use git log to find commits from the last 2 days to identify what changed.",expectedTool:"git_log",validateArgs:()=>!0},{id:"phase-plan-error-trace",category:"phase-plan",prompt:"The error stack trace mentions src/middleware/auth.js line 87. Read the file around that line to understand the bug.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&/auth/i.test(t.path)},{id:"phase-plan-grep-config",category:"phase-plan",prompt:"Users report the app is using wrong API keys in staging. Search for where API_KEY is loaded from environment.",expectedTool:"grep",validateArgs:t=>typeof t.pattern=="string"&&/api.?key|env/i.test(t.pattern)},{id:"phase-verify-build",category:"phase-verify",prompt:"The TypeScript source was modified. Run the build command to verify there are no compilation errors.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&/build|tsc|compile/.test(t.command)},{id:"phase-verify-git-diff",category:"phase-verify",prompt:"Changes were just committed. Show the git diff of the last commit to verify only the intended files were modified.",expectedTool:["git_diff","bash"],validateArgs:t=>(t.command&&/git.*diff|diff.*HEAD/.test(t.command),!0)},{id:"phase-verify-read-config",category:"phase-verify",prompt:"The deployment config was updated. Read config/production.json to verify the changes are correct before deploying.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&/config|production|deploy/i.test(t.path)}],di=[...Wc,...Ah],Fc=["devstral-2:123b","kimi-k2.5","glm-5:cloud","qwen3-coder:480b","qwen3-coder-next","ministral-3:14b","minimax-m2.7:cloud","kimi-k2:1t"];function mk(){try{let s=require("path").join(require("os").homedir(),".nex-code","benchmark-results.json");if(!require("fs").existsSync(s))return Fc;let n=JSON.parse(require("fs").readFileSync(s,"utf-8"));return!Array.isArray(n)||n.length===0?Fc:n.filter(o=>typeof o.score=="number"&&o.score>=60).sort((o,r)=>r.score-o.score).slice(0,12).map(o=>o.model)}catch{return Fc}}var Uc=mk(),gk=["minimax-m2.7:cloud","qwen3-coder:480b","devstral-2:123b"],Oh=(()=>{let t=Uc.slice(0,3);return t.length>=3?t:gk})(),yk=14,li={producedToolCall:.2,correctTool:.35,validArgs:.3,schemaCompliant:.15},$k="You are a coding assistant. Use the provided tools to help with file operations, search, and development tasks. Only call a tool when one is clearly needed to answer the request. Do not call a tool for questions you can answer from general knowledge.";async function Bc(t,e){let s={taskId:t.id,category:t.category,model:e,producedToolCall:!1,correctTool:!1,validArgs:!1,schemaCompliant:!1,toolCalled:null,error:null,latencyMs:0},n=[{role:"system",content:$k},{role:"user",content:t.prompt}],o=Date.now();try{let r=await pk.callChat(n,Ch,{provider:"ollama",model:e,temperature:0,timeout:9e4});s.latencyMs=Date.now()-o;let i=r.tool_calls||[];if(t.expectedTool===null){let a=i.length===0;s.producedToolCall=a,s.correctTool=a,s.validArgs=!0,s.schemaCompliant=!0}else if(i.length>0){let a=i[0],c=a.function?.name||"unknown",l=a.function?.arguments||{};s.producedToolCall=!0,s.toolCalled=c;let u=Array.isArray(t.expectedTool)?t.expectedTool:[t.expectedTool];if(s.correctTool=u.includes(c),s.correctTool){let d=Ch.find(f=>f.function?.name===c);if(s.validArgs=!!t.validateArgs(l,d),d){let f=d.function?.parameters||{},h=f.required||[],g=Object.keys(f.properties||{});s.schemaCompliant=h.every(m=>l[m]!==void 0)&&Object.keys(l).every(m=>g.includes(m))}}}}catch(r){s.latencyMs=Date.now()-o,s.error=r.message.slice(0,120)}return s}function ks(t){return t.error?0:((t.producedToolCall?li.producedToolCall:0)+(t.correctTool?li.correctTool:0)+(t.validArgs?li.validArgs:0)+(t.schemaCompliant?li.schemaCompliant:0))*100}var Nh={coding:"coding",search:"coding",shell:"coding",schema:"coding","multi-step":"coding",reasoning:"coding",frontend:"frontend",sysadmin:"sysadmin",data:"data",agentic:"agentic",resilience:"coding",ssh:"sysadmin",git:"coding","phase-plan":"plan","phase-verify":"verify"};function Hc(t){return Object.entries(t).map(([e,s])=>{let n=s.map(ks),o=n.reduce((a,c)=>a+c,0)/n.length,r=a=>Math.round(s.filter(a).length/s.length*100),i={};for(let a of["coding","frontend","sysadmin","data","agentic","plan","verify"]){let c=s.filter(u=>Nh[u.category]===a);if(c.length===0)continue;let l=c.map(ks).reduce((u,d)=>u+d,0)/c.length;i[a]=Math.round(l*10)/10}return{model:e,score:Math.round(o*10)/10,toolCallRate:r(a=>!a.error&&(a.producedToolCall||a.category==="reasoning")),correctRate:r(a=>a.correctTool),validArgsRate:r(a=>a.validArgs),schemaRate:r(a=>a.schemaCompliant),avgLatency:Math.round(s.reduce((a,c)=>a+c.latencyMs,0)/s.length),errorCount:s.filter(a=>a.error).length,categoryScores:i,results:s}}).sort((e,s)=>s.score-e.score)}function Mh(t){let e={};for(let a of["coding","frontend","sysadmin","data","agentic","plan","verify"]){let c=t.filter(m=>m.categoryScores[a]!==void 0&&m.score>=65).sort((m,b)=>b.categoryScores[a]-m.categoryScores[a]);if(c.length===0)continue;let u=(c[0]?.results||[]).filter(m=>Nh[m.category]===a).length;if(u<4)continue;let d=c[0],f=c[1];if(d.categoryScores[a]>=95&&u<8&&f&&d.categoryScores[a]-f.categoryScores[a]<15){let b=t.filter(x=>x.categoryScores[a]!==void 0).find(x=>x.categoryScores[a]<95);b&&(e[a]={model:b.model,score:b.categoryScores[a],avgLatency:b.avgLatency,_flukePrevented:!0});continue}let g=c.filter(m=>d.categoryScores[a]-m.categoryScores[a]<=5).sort((m,b)=>m.avgLatency-b.avgLatency)[0];e[a]={model:g.model,score:g.categoryScores[a],avgLatency:g.avgLatency}}return e}function Lh(t,e){let s=`nex-code Model Benchmark (${e} tasks \xB7 ollama cloud)`,n=[{label:"#",width:3},{label:"Model",width:26},{label:"Score",width:7},{label:"Tool\u2713",width:7},{label:"Name\u2713",width:7},{label:"Args\u2713",width:7},{label:"Schema\u2713",width:8},{label:"Latency",width:8},{label:"Err",width:4}],o=n.reduce((u,d)=>u+d.width+1,0)+1,r="\u2500".repeat(o);console.log(`
1245
+ ${W.bold}${s}${W.reset}`),console.log(r);let i=n.map(u=>u.label.padEnd(u.width)).join(" ");if(console.log(`${W.dim}${i}${W.reset}`),console.log(r),t.forEach((u,d)=>{let f=String(d+1).padEnd(n[0].width),h=u.model.slice(0,n[1].width).padEnd(n[1].width),g=String(u.score).padEnd(n[2].width),m=`${u.toolCallRate}%`.padEnd(n[3].width),b=`${u.correctRate}%`.padEnd(n[4].width),x=`${u.validArgsRate}%`.padEnd(n[5].width),j=`${u.schemaRate}%`.padEnd(n[6].width),G=`${(u.avgLatency/1e3).toFixed(1)}s`.padEnd(n[7].width),L=u.errorCount>0?`${W.red}${u.errorCount}${W.reset}`:`${W.dim}0${W.reset}`,P=u.score>=80?W.green:u.score>=60?W.yellow:W.red,C=d===0?`${W.yellow}${f}${W.reset}`:`${W.dim}${f}${W.reset}`;console.log(`${C} ${P}${h}${W.reset} ${W.bold}${P}${g}${W.reset} ${m} ${b} ${x} ${j} ${W.dim}${G}${W.reset} ${L}`)}),console.log(r),t.length>0){let u=t[0];if(console.log(`
1246
+ ${W.bold}${W.green}Winner: ${u.model}${W.reset} score ${u.score}/100`),t.length>1){let d=(u.score-t[1].score).toFixed(1);console.log(`${W.dim}+${d} pts over ${t[1].model}${W.reset}`)}}let a=t.filter(u=>u.results.some(d=>!d.error&&(!d.correctTool||!d.validArgs)));if(a.length>0){console.log(`${W.bold}Failing tasks:${W.reset}`);for(let u of a){let d=u.results.filter(g=>!g.error&&(!g.correctTool||!g.validArgs));if(d.length===0)continue;let f=u.model.slice(0,22),h=d.map(g=>{if(!g.correctTool){let m=g.toolCalled||"(none)";return`${W.dim}${g.taskId}${W.reset} ${W.red}\u2192${m}${W.reset}`}return`${W.dim}${g.taskId}${W.reset} ${W.yellow}bad-args${W.reset}`});console.log(` ${W.dim}${f.padEnd(22)}${W.reset} ${h.join(" ")}`)}console.log()}let c=["coding","frontend","sysadmin","data","agentic"];if(t.some(u=>Object.keys(u.categoryScores).length>1)){console.log(`
1247
+ ${W.bold}Best model per task type:${W.reset}`);for(let u of c){let d=t.filter(m=>m.categoryScores[u]!==void 0).sort((m,b)=>b.categoryScores[u]-m.categoryScores[u]);if(d.length===0)continue;let f=d[0],h=f.categoryScores[u],g=h>=80?W.green:h>=60?W.yellow:W.red;console.log(` ${W.dim}${u.padEnd(10)}${W.reset} ${g}${f.model}${W.reset} ${W.dim}${h}/100${W.reset}`)}}console.log()}function Ph(t){if(!(!t||t.length<2))try{let e=Mh(t),{loadRoutingConfig:s}=ps(),n=s(),o={...n},r=[],i=new Set(["plan","verify"]);for(let[a,{model:c,score:l}]of Object.entries(e)){let u=i.has(a),d=u?n.phases&&n.phases[a]:n[a];d&&d!==c&&!t.find(h=>h.model===d)||(u?(o.phases||(o.phases={}),o.phases[a]!==c&&(o.phases[a]=c,r.push(`phase:${a}\u2192${c}`))):o[a]!==c&&(o[a]=c,r.push(`${a}\u2192${c}`)))}r.length>0&&(hk(o),console.log(`
1248
+ ${W.dim} Routing updated: ${r.join(", ")}${W.reset}`),console.log(`
1249
+ ${W.green}\u{1F4A1} The best models have been saved to ~/.nex-code/.env and will be automatically used by nex-code from now on.${W.reset}`))}catch{}}async function wk({models:t,quick:e=!1,onProgress:s,parallelModels:n=1}={}){let o=e?Wc.slice(0,yk):di,r=t?.length>0?t:e?Oh:Uc,i={};for(let c of r)i[c]=[];if(n<=1)for(let c of r)for(let l of o){s?.({model:c,task:l.id,done:!1});let u=await Bc(l,c);i[c].push(u),s?.({model:c,task:l.id,done:!0,score:ks(u),error:u.error})}else{let c=Math.min(n,r.length),l=[...r],u=Array.from({length:c},async()=>{for(;l.length>0;){let d=l.shift();if(!d)break;for(let f of o){s?.({model:d,task:f.id,done:!1});let h=await Bc(f,d);i[d].push(h),s?.({model:d,task:f.id,done:!0,score:ks(h),error:h.error})}}});await Promise.all(u)}let a=Hc(i);return Lh(a,o.length),Ph(a),a}async function bk({newModels:t,existingRanking:e=[],onProgress:s}={}){if(!t||t.length===0)return e;let n={};for(let i of t){n[i]=[];for(let a of di){s?.({model:i,task:a.id,done:!1});let c=await Bc(a,i);n[i].push(c),s?.({model:i,task:a.id,done:!0,score:ks(c),error:c.error})}}let r=[...Hc(n)];for(let i of e)r.find(a=>a.model===i.model)||r.push(i);return r.sort((i,a)=>a.score-i.score),Lh(r,di.length),Ph(r),r}var ui=[{id:"simple_question",name:"Simple Convergence",prompt:"What is 2+2?",maxTurns:3,successCriteria:["4"]}];function Ih(t){let e=require("fs"),n=require("path").join(t||process.cwd(),".nex","benchmark-config.json");if(!e.existsSync(n))return console.log(`${W.yellow}No scenarios configured.${W.reset} Create ${W.dim}.nex/benchmark-config.json${W.reset} to define your benchmark scenarios.
1213
1250
  Example:
1214
1251
  {
1215
1252
  "scenarios": [
@@ -1222,14 +1259,14 @@ ${G.dim} Routing updated: ${r.join(", ")}${G.reset}`))}catch{}}async function Z
1222
1259
  }
1223
1260
  ]
1224
1261
  }
1225
- `),ai;try{let o=JSON.parse(e.readFileSync(n,"utf-8"));return!Array.isArray(o.scenarios)||o.scenarios.length===0?(console.log(`${G.yellow}benchmark-config.json has no scenarios \u2014 using defaults.${G.reset}
1226
- `),ai):o.scenarios}catch(o){return console.log(`${G.yellow}Failed to parse benchmark-config.json: ${o.message}${G.reset}
1227
- `),ai}}function Eh(t,e){let{scoreMessages:s,_extractToolCalls:n,_getLastAssistantText:o}=Lr(),r=s(t),i=r.score,a=[],c=o(t).toLowerCase();e.successCriteria.every(f=>c.includes(f.toLowerCase()))&&(i=Math.min(10,i+1),a.push("+1.0 all success criteria met"));let u=n(t);u.length<e.maxTurns/2&&(i=Math.min(10,i+.5),a.push(`+0.5 efficient (${u.length} tool calls < ${e.maxTurns/2})`)),i=Math.round(i*10)/10;let d=i>=9?"A":i>=8?"B":i>=7?"C":i>=6?"D":"F";return{score:i,grade:d,issues:r.issues,summary:r.summary,bonuses:a}}async function ek(t,e={}){let{spawn:s}=require("child_process"),n=require("fs"),o=require("path"),r=require("os"),i=o.join(r.tmpdir(),`nex-bench-${t.id}-${Date.now()}.txt`);n.writeFileSync(i,t.prompt,"utf-8");let a=o.resolve(__dirname,"..","bin","nex-code.js"),c=e.cwd||process.cwd(),l=[a,"--prompt-file",i,"--delete-prompt-file","--auto","--max-turns",String(t.maxTurns)];return e.model&&l.push("--model",e.model),new Promise(u=>{let d=s(process.execPath,l,{cwd:c,stdio:["ignore","pipe","pipe"],env:{...process.env}}),f=t.maxTurns*60*1e3,h=!1,m=setTimeout(()=>{h=!0;try{d.kill("SIGTERM")}catch{}},f);d.on("close",g=>{clearTimeout(m);try{n.unlinkSync(i)}catch{}let b=o.join(c,".nex","sessions","_autosave.json"),v=[];if(n.existsSync(b))try{v=JSON.parse(n.readFileSync(b,"utf-8")).messages||[]}catch{}u({messages:v,exitCode:g||0,timedOut:h})}),d.stdout.resume(),d.stderr.resume()})}function tk(t,e,s){let n=t.length>0?Math.round(t.reduce((c,l)=>c+l.score,0)/t.length*10)/10:0,o=n>=9?"A":n>=8?"B":n>=7?"C":n>=6?"D":"F",r=57,i="\u2500".repeat(r);console.log(`
1262
+ `),ui;try{let o=JSON.parse(e.readFileSync(n,"utf-8"));return!Array.isArray(o.scenarios)||o.scenarios.length===0?(console.log(`${W.yellow}benchmark-config.json has no scenarios \u2014 using defaults.${W.reset}
1263
+ `),ui):o.scenarios}catch(o){return console.log(`${W.yellow}Failed to parse benchmark-config.json: ${o.message}${W.reset}
1264
+ `),ui}}function jh(t,e){let{scoreMessages:s,_extractToolCalls:n,_getLastAssistantText:o}=jr(),r=s(t),i=r.score,a=[],c=o(t).toLowerCase();e.successCriteria.every(f=>c.includes(f.toLowerCase()))&&(i=Math.min(10,i+1),a.push("+1.0 all success criteria met"));let u=n(t);u.length<e.maxTurns/2&&(i=Math.min(10,i+.5),a.push(`+0.5 efficient (${u.length} tool calls < ${e.maxTurns/2})`)),i=Math.round(i*10)/10;let d=i>=9?"A":i>=8?"B":i>=7?"C":i>=6?"D":"F";return{score:i,grade:d,issues:r.issues,summary:r.summary,bonuses:a}}async function _k(t,e={}){let{spawn:s}=require("child_process"),n=require("fs"),o=require("path"),r=require("os"),i=o.join(r.tmpdir(),`nex-bench-${t.id}-${Date.now()}.txt`);n.writeFileSync(i,t.prompt,"utf-8");let a=o.resolve(__dirname,"..","bin","nex-code.js"),c=e.cwd||process.cwd(),l=[a,"--prompt-file",i,"--delete-prompt-file","--auto","--max-turns",String(t.maxTurns)];return e.model&&l.push("--model",e.model),new Promise(u=>{let d=s(process.execPath,l,{cwd:c,stdio:["ignore","pipe","pipe"],env:{...process.env}}),f=t.maxTurns*60*1e3,h=!1,g=setTimeout(()=>{h=!0;try{d.kill("SIGTERM")}catch{}},f);d.on("close",m=>{clearTimeout(g);try{n.unlinkSync(i)}catch{}let b=o.join(c,".nex","sessions","_autosave.json"),x=[];if(n.existsSync(b))try{x=JSON.parse(n.readFileSync(b,"utf-8")).messages||[]}catch{}u({messages:x,exitCode:m||0,timedOut:h})}),d.stdout.resume(),d.stderr.resume()})}function xk(t,e,s){let n=t.length>0?Math.round(t.reduce((c,l)=>c+l.score,0)/t.length*10)/10:0,o=n>=9?"A":n>=8?"B":n>=7?"C":n>=6?"D":"F",r=57,i="\u2500".repeat(r);console.log(`
1228
1265
  \u250C\u2500 Benchmark Results ${"\u2500".repeat(r-19)}\u2510`);for(let c of t){let l=c.id.padEnd(20),u=c.name.substring(0,26).padEnd(26),d=`${c.score}/10`.padStart(6),f=c.grade.padStart(2);console.log(`\u2502 ${l} ${u} ${d} ${f} \u2502`)}console.log(`\u2502 ${" ".repeat(r-2)} \u2502`);let a=`Overall: ${n}/10 (${o}) \xB7 v${e} \xB7 ${s}`;console.log(`\u2502 ${a.substring(0,r-4).padEnd(r-4)} \u2502`),console.log(`\u2514${"\u2500".repeat(r+1)}\u2518
1229
- `)}function nk(t=10){let e=require("fs"),n=require("path").join(process.cwd(),".nex","benchmark-history.json");if(!e.existsSync(n)){console.log(`${G.yellow}No score history yet. Run a session first.${G.reset}
1230
- `);return}let o=[];try{o=JSON.parse(e.readFileSync(n,"utf-8"))}catch{o=[]}if(!Array.isArray(o)||o.length===0){console.log(`${G.yellow}Score history is empty.${G.reset}
1266
+ `)}function kk(t=10){let e=require("fs"),n=require("path").join(process.cwd(),".nex","benchmark-history.json");if(!e.existsSync(n)){console.log(`${W.yellow}No score history yet. Run a session first.${W.reset}
1267
+ `);return}let o=[];try{o=JSON.parse(e.readFileSync(n,"utf-8"))}catch{o=[]}if(!Array.isArray(o)||o.length===0){console.log(`${W.yellow}Score history is empty.${W.reset}
1231
1268
  `);return}let r=o.slice(-t);console.log(`
1232
- ${G.bold}Score History (last ${r.length} session${r.length===1?"":"s"}):${G.reset}`);for(let i of r){let a=(i.date||"").replace("T"," ").substring(0,16),c=(i.version||"?").padEnd(8),l=(i.model||"?").substring(0,12).padEnd(12),u=`${i.score}/10`.padStart(6),d=i.grade||"?",f=i.issues&&i.issues.length>0?`${G.yellow}\u26A0 ${i.issues.slice(0,2).map(m=>m.substring(0,30)).join(", ")}${G.reset}`:`${G.green}\u2713${G.reset}`,h=i.score>=8?G.green:i.score>=6?G.yellow:G.red;console.log(` ${G.dim}${a}${G.reset} ${G.dim}v${c}${G.reset} ${G.dim}${l}${G.reset} ${h}${u} ${d}${G.reset} ${f}`)}console.log()}async function sk({dryRun:t=!1,model:e,cwd:s,onProgress:n}={}){let o=No(),r=Sh(s);if(t){console.log(`
1233
- ${G.bold}Jarvis Benchmark \u2014 Scenarios (dry-run):${G.reset}
1234
- `);for(let c of r)console.log(` ${G.cyan}${c.id.padEnd(20)}${G.reset} ${G.dim}${c.name}${G.reset} maxTurns=${c.maxTurns}`),console.log(` ${G.dim}${c.prompt.substring(0,80)}${G.reset}`);return console.log(),[]}let i=(()=>{if(e)return typeof e=="object"?e.id||"unknown":e;try{let{getActiveModel:c}=Ss(),l=c?c():null;return l?typeof l=="object"?l.id||"unknown":l:"unknown"}catch{return"unknown"}})(),a=[];for(let c of r){n?.({id:c.id,name:c.name,done:!1}),console.log(`
1235
- ${G.dim}Running scenario: ${c.name}...${G.reset}`);let{messages:l,timedOut:u}=await ek(c,{model:i,cwd:s}),d;u||l.length===0?d={score:0,grade:"F",issues:[u?"Scenario timed out":"No messages produced"],summary:"No output",bonuses:[]}:d=Eh(l,c);let f={id:c.id,name:c.name,score:d.score,grade:d.grade,issues:d.issues,bonuses:d.bonuses};a.push(f),n?.({id:c.id,name:c.name,done:!0,score:d.score,grade:d.grade});try{let{appendScoreHistory:h}=Lr();h(d.score,{version:o.version,model:i,sessionName:`bench:${c.id}`,issues:d.issues})}catch{}}return tk(a,o.version,i),a}module.exports={runBenchmark:Zx,runDiscoverBenchmark:Qx,buildSummary:Cc,buildCategoryWinners:xh,TASKS:Tc,PHASE_TASKS:wh,ALL_TASKS:ci,scoreResult:ws,DEFAULT_MODELS:Rc,QUICK_MODELS:bh,runJarvisBenchmark:sk,showScoreTrend:nk,loadScenarios:Sh,DEFAULT_SCENARIOS:ai,scoreJarvisScenario:Eh};
1269
+ ${W.bold}Score History (last ${r.length} session${r.length===1?"":"s"}):${W.reset}`);for(let i of r){let a=(i.date||"").replace("T"," ").substring(0,16),c=(i.version||"?").padEnd(8),l=(i.model||"?").substring(0,12).padEnd(12),u=`${i.score}/10`.padStart(6),d=i.grade||"?",f=i.issues&&i.issues.length>0?`${W.yellow}\u26A0 ${i.issues.slice(0,2).map(g=>g.substring(0,30)).join(", ")}${W.reset}`:`${W.green}\u2713${W.reset}`,h=i.score>=8?W.green:i.score>=6?W.yellow:W.red;console.log(` ${W.dim}${a}${W.reset} ${W.dim}v${c}${W.reset} ${W.dim}${l}${W.reset} ${h}${u} ${d}${W.reset} ${f}`)}console.log()}async function vk({dryRun:t=!1,model:e,cwd:s,onProgress:n}={}){let o=Lo(),r=Ih(s);if(t){console.log(`
1270
+ ${W.bold}Scenario Benchmark \u2014 Scenarios (dry-run):${W.reset}
1271
+ `);for(let c of r)console.log(` ${W.cyan}${c.id.padEnd(20)}${W.reset} ${W.dim}${c.name}${W.reset} maxTurns=${c.maxTurns}`),console.log(` ${W.dim}${c.prompt.substring(0,80)}${W.reset}`);return console.log(),[]}let i=(()=>{if(e)return typeof e=="object"?e.id||"unknown":e;try{let{getActiveModel:c}=Rs(),l=c?c():null;return l?typeof l=="object"?l.id||"unknown":l:"unknown"}catch{return"unknown"}})(),a=[];for(let c of r){n?.({id:c.id,name:c.name,done:!1}),console.log(`
1272
+ ${W.dim}Running scenario: ${c.name}...${W.reset}`);let{messages:l,timedOut:u}=await _k(c,{model:i,cwd:s}),d;u||l.length===0?d={score:0,grade:"F",issues:[u?"Scenario timed out":"No messages produced"],summary:"No output",bonuses:[]}:d=jh(l,c);let f={id:c.id,name:c.name,score:d.score,grade:d.grade,issues:d.issues,bonuses:d.bonuses};a.push(f),n?.({id:c.id,name:c.name,done:!0,score:d.score,grade:d.grade});try{let{appendScoreHistory:h}=jr();h(d.score,{version:o.version,model:i,sessionName:`bench:${c.id}`,issues:d.issues})}catch{}}return xk(a,o.version,i),a}module.exports={runBenchmark:wk,runDiscoverBenchmark:bk,buildSummary:Hc,buildCategoryWinners:Mh,TASKS:Wc,PHASE_TASKS:Ah,ALL_TASKS:di,scoreResult:ks,DEFAULT_MODELS:Uc,QUICK_MODELS:Oh,runScenarioBenchmark:vk,showScoreTrend:kk,loadScenarios:Ih,DEFAULT_SCENARIOS:ui,scoreScenario:jh};