nex-code 0.5.30 → 0.5.31

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/nex-code.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- var td=Object.defineProperty;var Iv=Object.getOwnPropertyDescriptor;var jv=Object.getOwnPropertyNames;var Dv=Object.prototype.hasOwnProperty;var qv=(e,t)=>()=>(e&&(t=e(e=0)),t);var Q=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Fv=(e,t)=>{for(var n in t)td(e,n,{get:t[n],enumerable:!0})},Bv=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of jv(t))!Dv.call(e,s)&&s!==n&&td(e,s,{get:()=>t[s],enumerable:!(o=Iv(t,s))||o.enumerable});return e};var Uv=e=>Bv(td({},"__esModule",{value:!0}),e);var Ar=Q((ED,Wv)=>{Wv.exports={name:"nex-code",version:"0.5.30",description:"Run 400B+ open coding models on your codebase without the hardware bill. Ollama Cloud first \u2014 OpenAI, Anthropic, and Gemini when you need them.",bin:{"nex-code":"./dist/nex-code.js"},files:["dist/","examples/","README.md","LICENSE"],engines:{node:">=18.0.0"},scripts:{start:"node dist/nex-code.js",build:"node scripts/build.js",dev:"node scripts/build.js --dev",test:"jest --runInBand","test:orchestrator":"jest tests/orchestrator.test.js --forceExit",coverage:"jest --coverage --forceExit","test:watch":"jest --watch",typecheck:"tsc --noEmit",format:"prettier --write .","scan:secrets":"node scripts/secret-scan.js --staged","install-hooks":"ln -sf ../../hooks/pre-commit .git/hooks/pre-commit && chmod +x .git/hooks/pre-commit && ln -sf ../../hooks/pre-push .git/hooks/pre-push && chmod +x .git/hooks/pre-push && ln -sf ../../hooks/post-merge .git/hooks/post-merge && chmod +x .git/hooks/post-merge && echo 'Hooks installed (pre-commit, pre-push, post-merge).'",prepublishOnly:"npm run build && npm test","merge-to-main":"bash scripts/merge-to-main.sh",improve:"node scripts/improve.js","extract-examples":"node scripts/extract-examples.js","benchmark:realworld":"node scripts/benchmark-realworld.js","benchmark:reallife":"node scripts/benchmark-reallife.js","benchmark:report":"node scripts/benchmark-reallife-report.js","improve:reallife":"node scripts/improve-reallife.js","benchmark:gate":"node scripts/benchmark-gate.js",release:"bash scripts/release.sh"},keywords:["ai","cli","coding","agent","ollama","ollama-cloud","openai","anthropic","gemini","llm","gpt","agentic","terminal","coding-assistant","open-source","free","qwen3","devstral","kimi-k2","deepseek","local-llm","mcp","model-context-protocol","multi-provider"],repository:{type:"git",url:"https://github.com/hybridpicker/nex-code.git"},bugs:{url:"https://github.com/hybridpicker/nex-code/issues"},homepage:"https://github.com/hybridpicker/nex-code#readme",license:"MIT",dependencies:{axios:"^1.15.0",dotenv:"^16.4.0",pixelmatch:"^7.1.0",pngjs:"^7.0.0"},devDependencies:{esbuild:"^0.27.3",jest:"^29.7.0",prettier:"^3.8.1",typescript:"^5.9.3"},overrides:{"brace-expansion":">=5.0.5",picomatch:">=4.0.4"},jest:{coverageThreshold:{global:{lines:45,functions:30,branches:35},"./cli/sub-agent.js":{lines:70,functions:60,branches:55}}}}});var ln=Q((TD,xm)=>{"use strict";var ym="\x1B[0m",$m="\x1B[1m",Or="\x1B[2m";function ie(e,t,n){return`\x1B[38;2;${e};${t};${n}m`}function Hv(){if(!process.stdout.isTTY)return null;try{let{execFileSync:e}=require("child_process"),t=["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
+ var td=Object.defineProperty;var Iv=Object.getOwnPropertyDescriptor;var jv=Object.getOwnPropertyNames;var Dv=Object.prototype.hasOwnProperty;var qv=(e,t)=>()=>(e&&(t=e(e=0)),t);var Q=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Fv=(e,t)=>{for(var n in t)td(e,n,{get:t[n],enumerable:!0})},Bv=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of jv(t))!Dv.call(e,s)&&s!==n&&td(e,s,{get:()=>t[s],enumerable:!(o=Iv(t,s))||o.enumerable});return e};var Uv=e=>Bv(td({},"__esModule",{value:!0}),e);var Ar=Q((ED,Wv)=>{Wv.exports={name:"nex-code",version:"0.5.31",description:"Run 400B+ open coding models on your codebase without the hardware bill. Ollama Cloud first \u2014 OpenAI, Anthropic, and Gemini when you need them.",bin:{"nex-code":"./dist/nex-code.js"},files:["dist/","examples/","README.md","LICENSE"],engines:{node:">=18.0.0"},scripts:{start:"node dist/nex-code.js",build:"node scripts/build.js",dev:"node scripts/build.js --dev",test:"jest --runInBand","test:orchestrator":"jest tests/orchestrator.test.js --forceExit",coverage:"jest --coverage --forceExit","test:watch":"jest --watch",typecheck:"tsc --noEmit",format:"prettier --write .","scan:secrets":"node scripts/secret-scan.js --staged","install-hooks":"ln -sf ../../hooks/pre-commit .git/hooks/pre-commit && chmod +x .git/hooks/pre-commit && ln -sf ../../hooks/pre-push .git/hooks/pre-push && chmod +x .git/hooks/pre-push && ln -sf ../../hooks/post-merge .git/hooks/post-merge && chmod +x .git/hooks/post-merge && echo 'Hooks installed (pre-commit, pre-push, post-merge).'",prepublishOnly:"npm run build && npm test","merge-to-main":"bash scripts/merge-to-main.sh",improve:"node scripts/improve.js","extract-examples":"node scripts/extract-examples.js","benchmark:realworld":"node scripts/benchmark-realworld.js","benchmark:reallife":"node scripts/benchmark-reallife.js","benchmark:report":"node scripts/benchmark-reallife-report.js","improve:reallife":"node scripts/improve-reallife.js","benchmark:gate":"node scripts/benchmark-gate.js",release:"bash scripts/release.sh"},keywords:["ai","cli","coding","agent","ollama","ollama-cloud","openai","anthropic","gemini","llm","gpt","agentic","terminal","coding-assistant","open-source","free","qwen3","devstral","kimi-k2","deepseek","local-llm","mcp","model-context-protocol","multi-provider"],repository:{type:"git",url:"https://github.com/hybridpicker/nex-code.git"},bugs:{url:"https://github.com/hybridpicker/nex-code/issues"},homepage:"https://github.com/hybridpicker/nex-code#readme",license:"MIT",dependencies:{axios:"^1.15.0",dotenv:"^16.4.0",pixelmatch:"^7.1.0",pngjs:"^7.0.0"},devDependencies:{esbuild:"^0.27.3",jest:"^29.7.0",prettier:"^3.8.1",typescript:"^5.9.3"},overrides:{"brace-expansion":">=5.0.5",picomatch:">=4.0.4"},jest:{coverageThreshold:{global:{lines:45,functions:30,branches:35},"./cli/sub-agent.js":{lines:70,functions:60,branches:55}}}}});var ln=Q((TD,xm)=>{"use strict";var ym="\x1B[0m",$m="\x1B[1m",Or="\x1B[2m";function ie(e,t,n){return`\x1B[38;2;${e};${t};${n}m`}function Hv(){if(!process.stdout.isTTY)return null;try{let{execFileSync:e}=require("child_process"),t=["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(`
3
3
  `),s=e("python3",["-c",t],{encoding:"buffer",timeout:400,stdio:["ignore","pipe","ignore"]}).toString("utf8").match(/rgb:([0-9a-fA-F]+)\/([0-9a-fA-F]+)\/([0-9a-fA-F]+)/);if(s){let r=parseInt(s[1].slice(0,2),16),i=parseInt(s[2].slice(0,2),16),a=parseInt(s[3].slice(0,2),16);return .299*r+.587*i+.114*a<128}}catch{}return null}function bm(){let e=require("os");return require("path").join(e.homedir(),".nex-code",".theme_cache.json")}function Gv(e){try{let n=require("fs").readFileSync(bm(),"utf8"),o=JSON.parse(n);if(o&&typeof o[e]=="boolean")return o[e]}catch(t){console.error("readThemeCache failed:",t.message)}return null}function Yv(e,t){try{let n=require("fs"),o=require("path"),s=bm(),r=o.dirname(s),i={};try{i=JSON.parse(n.readFileSync(s,"utf8"))}catch(c){console.error("theme cache failed:",c.message)}i[e]=t;let a=Object.keys(i);a.length>50&&a.slice(0,a.length-50).forEach(c=>delete i[c]),n.existsSync(r)||n.mkdirSync(r,{recursive:!0}),n.writeFileSync(s,JSON.stringify(i),"utf8")}catch{}}function zv(){let e=(process.env.NEX_THEME||"").toLowerCase();if(e==="light")return!1;if(e==="dark")return!0;let t=process.env.COLORFGBG;if(t){let i=t.split(";"),a=parseInt(i[i.length-1],10);if(!isNaN(a))return a<8}let n=process.env.TERM_SESSION_ID||"default",o=Gv(n);if(o!==null)return o;let s=Hv(),r=s!==null?s:!0;return Yv(n,r),r}var wm=zv(),_m={reset:ym,bold:$m,dim:Or,primary:ie(80,190,255),secondary:ie(60,170,190),success:ie(80,210,120),warning:ie(245,175,50),error:ie(230,80,80),muted:Or,subtle:ie(130,130,145),tool_read:ie(80,190,255),tool_write:ie(245,165,55),tool_exec:ie(185,100,235),tool_search:ie(70,185,190),tool_git:ie(90,210,100),tool_web:ie(100,215,250),tool_sysadmin:ie(225,150,75),tool_default:ie(100,205,115),syn_keyword:ie(185,100,235),syn_string:ie(90,210,120),syn_number:ie(245,175,50),syn_comment:Or,syn_key:ie(80,190,255),diff_add:ie(80,210,120),diff_rem:ie(230,80,80),banner_logo:ie(80,200,255),banner_name:ie(80,200,255),banner_version:Or,banner_model:Or,banner_yolo:ie(245,175,50),banner_gemini:ie(138,180,248),footer_sep:Or,footer_model:ie(80,175,235),footer_branch:ie(80,210,100),footer_project:ie(130,130,145),footer_divider:ie(80,80,95),footer_mode:ie(210,150,50),white:ie(210,210,220),red:ie(220,85,85),green:ie(80,200,110),yellow:ie(230,185,60),blue:ie(70,140,230),magenta:ie(200,120,190),cyan:ie(90,200,215),gray:ie(120,120,135),bgRed:"\x1B[48;2;140;40;40m",bgGreen:"\x1B[48;2;30;100;50m",diff_add_bg:"\x1B[48;2;10;46;20m",diff_rem_bg:"\x1B[48;2;58;16;16m",brightCyan:ie(110,215,230),brightMagenta:ie(220,140,210),brightBlue:ie(100,160,240)},km={reset:ym,bold:$m,dim:ie(110,110,120),primary:ie(0,110,190),secondary:ie(0,125,148),success:ie(0,148,62),warning:ie(168,92,0),error:ie(188,32,32),muted:ie(110,110,120),subtle:ie(155,155,165),tool_read:ie(0,110,190),tool_write:ie(168,92,0),tool_exec:ie(128,42,188),tool_search:ie(0,122,148),tool_git:ie(0,138,62),tool_web:ie(0,112,178),tool_sysadmin:ie(168,82,0),tool_default:ie(0,138,62),syn_keyword:ie(128,42,188),syn_string:ie(0,138,62),syn_number:ie(168,92,0),syn_comment:ie(135,135,148),syn_key:ie(0,110,190),diff_add:ie(0,148,62),diff_rem:ie(188,32,32),banner_logo:ie(0,122,205),banner_name:ie(0,122,205),banner_version:ie(100,100,118),banner_model:ie(100,100,118),banner_yolo:ie(168,62,0),banner_gemini:ie(26,115,232),footer_sep:ie(168,168,178),footer_model:ie(0,102,175),footer_branch:ie(0,138,62),footer_project:ie(135,135,148),footer_divider:ie(168,168,178),footer_mode:ie(148,88,0),white:ie(40,40,52),red:ie(188,32,32),green:ie(0,148,62),yellow:ie(168,92,0),blue:ie(0,110,190),magenta:ie(128,42,188),cyan:ie(0,125,148),gray:ie(132,132,142),bgRed:"\x1B[48;2;180;50;50m",bgGreen:"\x1B[48;2;30;130;60m",diff_add_bg:"\x1B[48;2;215;245;220m",diff_rem_bg:"\x1B[48;2;255;215;215m",brightCyan:ie(0,158,182),brightMagenta:ie(158,52,208),brightBlue:ie(0,112,208)},Kv=wm?_m:km;xm.exports={T:Kv,isDark:wm,DARK:_m,LIGHT:km}});var jo=Q((RD,Cm)=>{var{T:ae}=ln(),nd=5,Mr=(()=>{let e=[];for(let t=0;t<nd;t++)e.push(t);for(let t=nd-2;t>=1;t--)e.push(t);return e})(),vm=["\u273D","\u2726","\u2727","\u2726"],Sm=["\xB7 ","\xB7\xB7 ","\xB7\xB7\xB7"," \xB7\xB7"];function Em(e=""){let t=String(e).toLowerCase();return t.includes("search")||t.includes("read")||t.includes("list")||t.includes("inspect")?{glyph:"\u25CC",color:ae.cyan,accent:"scan"}:t.includes("write")||t.includes("edit")||t.includes("patch")||t.includes("build")?{glyph:"\u2726",color:ae.yellow,accent:"shape"}:t.includes("test")||t.includes("diff")||t.includes("check")||t.includes("verify")?{glyph:"\u25A3",color:ae.green,accent:"verify"}:t.includes("wait")||t.includes("github")||t.includes("fetch")||t.includes("browser")?{glyph:"\u25CD",color:ae.blue,accent:"wait"}:{glyph:"\u25CF",color:ae.cyan,accent:"think"}}function Tm(e,t,n){let o="";for(let s=0;s<nd;s++)s===e?o+=`${n}${t}${ae.reset}`:s===e-1||s===e+1?o+=`${ae.dim}\xB7${ae.reset}`:o+=`${ae.dim}\xB7${ae.reset}`;return o}function Rm(e){return`${ae.dim}${Sm[e%Sm.length]}${ae.reset}`}var sd=class{constructor(t="Thinking..."){this.text=t,this.frame=0,this.interval=null,this.startTime=null}_render(){if(this._stopped)return;let t=Mr[this.frame%Mr.length],n=Em(this.text),o=Tm(t,n.glyph,n.color),s=Rm(this.frame),r="";if(this.startTime){let i=Math.floor((Date.now()-this.startTime)/1e3);if(i>=60){let a=Math.floor(i/60),c=i%60;r=` ${ae.dim}${a}m ${String(c).padStart(2,"0")}s${ae.reset}`}else i>=1&&(r=` ${ae.dim}${i}s${ae.reset}`)}process.stderr.write(`\x1B[2K\r${n.color}${n.accent.toUpperCase()}${ae.reset}${s} ${o} ${ae.dim}${this.text}${ae.reset}${r}`),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),process.stderr.isTTY&&(process.stderr.write("\x1B[?25l"),this._render(),this.interval=setInterval(()=>this._render(),100))}update(t){this.text=t}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}},od=class{constructor(t){this.labels=t,this.statuses=t.map(()=>"running"),this.frame=0,this.interval=null,this.startTime=null,this.lineCount=t.length}_formatElapsed(){if(!this.startTime)return"";let t=Math.floor((Date.now()-this.startTime)/1e3);if(t<1)return"";let n=Math.floor(t/60),o=t%60;return n>0?`${n}m ${String(o).padStart(2,"0")}s`:`${o}s`}_render(){if(this._stopped)return;let t=Mr[this.frame%Mr.length],n=`${ae.cyan}\u25CC${ae.reset}`,o=this._formatElapsed(),s=o?` ${ae.dim}${o}${ae.reset}`:"",r=process.stderr.columns||80,i="";for(let a=0;a<this.labels.length;a++){let c,u;switch(this.statuses[a]){case"done":c=`${ae.green}\u2713${ae.reset}`,u=ae.dim;break;case"error":c=`${ae.red}\u2717${ae.reset}`,u=ae.dim;break;case"retry":c=`${ae.yellow}\u21BB${ae.reset}`,u=ae.yellow;break;default:c=a===t?n:`${ae.dim}\xB7${ae.reset}`,u=""}let d=a===this.labels.length-1?s:"",f=r-4-(d?o.length+1:0),p=this.labels[a].length>f?this.labels[a].substring(0,Math.max(10,f-3))+"...":this.labels[a];i+=`\x1B[2K ${c} ${u}${p}${ae.reset}${d}
4
4
  `}this.lineCount>0&&(i+=`\x1B[${this.lineCount}A`),process.stderr.write(i),this.frame++}start(){this._stopped=!1,this.startTime=Date.now();let t="\x1B[?25l";for(let n=0;n<this.lineCount;n++)t+=`
5
5
  `;this.lineCount>0&&(t+=`\x1B[${this.lineCount}A`),process.stderr.write(t),this._render(),this.interval=setInterval(()=>this._render(),100)}update(t,n){t>=0&&t<this.statuses.length&&(this.statuses[t]=n)}stop(t={}){if(this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),!t.silent)this._renderFinal();else{let n="";for(let o=0;o<this.lineCount;o++)n+=`\x1B[2K
@@ -38,7 +38,7 @@ ${C.dim} ${r}${C.reset}
38
38
  `);return}if(/^\s*[-*]\s/.test(t)){let s=t.match(/^(\s*)/)[1],r=t.replace(/^\s*[-*]\s/,""),i=`${s}${C.cyan}\u2022${C.reset} ${Bs(r)}`,a=Us(i,n,s+" ");this._safeWrite(`${a}
39
39
  `);return}if(/^\s*\d+\.\s/.test(t)){let s=t.match(/^(\s*)(\d+)\.\s(.*)/);if(s){let r=s[1],i=s[2],a=s[3],c=`${r}${C.cyan}${i}.${C.reset} ${Bs(a)}`,u=r+" ".repeat(i.length+2),d=Us(c,n,u);this._safeWrite(`${d}
40
40
  `);return}}let o=Us(Bs(t),n);this._safeWrite(`${o}
41
- `)}};function aS(e,t={}){let{maxDepth:n=4,maxFiles:o=60,highlight:s=new Set,dim:r=new Set,icons:i=!0}=t,a=require("fs"),c=require("path"),u=new Set([".git","node_modules",".next","__pycache__",".venv","venv",".cache","dist",".nex","coverage",".DS_Store","target"]);function d(S,O){if(!i)return"";if(O)return"\u{1F4C1} ";let L=c.extname(S).toLowerCase(),I={".js":"\u{1F4DC} ",".ts":"\u{1F537} ",".jsx":"\u269B ",".tsx":"\u{1F536} ",".py":"\u{1F40D} ",".rs":"\u{1F980} ",".go":"\u{1F535} ",".css":"\u{1F3A8} ",".scss":"\u{1F3A8} ",".html":"\u{1F310} ",".md":"\u{1F4DD} ",".json":"\u{1F4CB} ",".toml":"\u2699 ",".yml":"\u2699 ",".yaml":"\u2699 ",".sh":"\u26A1 ",".env":"\u{1F512} ",".svg":"\u{1F5BC} ",".test.js":"\u{1F9EA} ",".test.ts":"\u{1F9EA} ",".spec.js":"\u{1F9EA} "};return I[L]||I[S]||"\u{1F4C4} "}function f(S,O){if(O)return C.cyan;let L=c.extname(S).toLowerCase();return/\.(js|ts|jsx|tsx)$/.test(L)?C.yellow:/\.(py|rs|go|java|rb)$/.test(L)?C.green:/\.(css|scss|less)$/.test(L)?C.magenta:/\.(html|xml|svg)$/.test(L)?C.primary:/\.(md|txt|rst)$/.test(L)?C.white:/\.(json|toml|yml|yaml)$/.test(L)?C.subtle:/\.(sh|bash|zsh)$/.test(L)?C.success:C.reset}let p=[],h=0,m=Pt(),g=m?"\u251C\u2500\u2500 ":"|-- ",$=m?"\u2514\u2500\u2500 ":"`-- ",b=m?"\u2502 ":"| ",x=" ",_=c.relative(process.cwd(),e)||".";p.push(`${C.bold}${C.cyan}${_}${C.reset}`);function E(S,O,L){if(O>n||h>=o)return;let I;try{I=a.readdirSync(S,{withFileTypes:!0})}catch{p.push(`${L}${g}${C.dim}(unreadable)${C.reset}`);return}I.sort((K,X)=>K.isDirectory()!==X.isDirectory()?K.isDirectory()?-1:1:K.name.localeCompare(X.name)),I=I.filter(K=>!u.has(K.name)&&!K.name.startsWith("."));let D=20,Z=I.length-D;Z>0&&(I=I.slice(0,D));for(let K=0;K<I.length;K++){if(h>=o){p.push(`${L}${g}${C.dim}\u2026 +${Z} more${C.reset}`);return}let X=I[K],Fe=K===I.length-1&&Z<=0,Oe=Fe?$:g,V=L+(Fe?x:b),re=c.join(S,X.name),rt=c.relative(process.cwd(),re),qe=C.reset;s.has(rt)?qe=C.yellow:r.has(rt)?qe=C.dim:qe=f(X.name,X.isDirectory());let _e=d(X.name,X.isDirectory()),Me=X.isDirectory()?`${C.bold}${X.name}/${C.reset}`:X.name;p.push(`${L}${Oe}${qe}${_e}${Me}${C.reset}`),h++,X.isDirectory()&&E(re,O+1,V)}Z>0&&p.push(`${L}${g}${C.dim}\u2026 +${Z} more${C.reset}`)}return E(e,1,""),p.join(`
41
+ `)}};function aS(e,t={}){let{maxDepth:n=4,maxFiles:o=60,highlight:s=new Set,dim:r=new Set,icons:i=!0}=t,a=require("fs"),c=require("path"),u=new Set([".git","node_modules",".next","__pycache__",".venv","venv",".cache","dist",".nex","coverage",".DS_Store","target"]);function d(S,O){if(!i)return"";if(O)return"\u{1F4C1} ";let L=c.extname(S).toLowerCase(),I={".js":"\u{1F4DC} ",".ts":"\u{1F537} ",".jsx":"\u269B ",".tsx":"\u{1F536} ",".py":"\u{1F40D} ",".rs":"\u{1F980} ",".go":"\u{1F535} ",".css":"\u{1F3A8} ",".scss":"\u{1F3A8} ",".html":"\u{1F310} ",".md":"\u{1F4DD} ",".json":"\u{1F4CB} ",".toml":"\u2699 ",".yml":"\u2699 ",".yaml":"\u2699 ",".sh":"\u26A1 ",".env":"\u{1F512} ",".svg":"\u{1F5BC} ",".test.js":"\u{1F9EA} ",".test.ts":"\u{1F9EA} ",".spec.js":"\u{1F9EA} "};return I[L]||I[S]||"\u{1F4C4} "}function f(S,O){if(O)return C.cyan;let L=c.extname(S).toLowerCase();return/\.(js|ts|jsx|tsx)$/.test(L)?C.yellow:/\.(py|rs|go|java|rb)$/.test(L)?C.green:/\.(css|scss|less)$/.test(L)?C.magenta:/\.(html|xml|svg)$/.test(L)?C.primary:/\.(md|txt|rst)$/.test(L)?C.white:/\.(json|toml|yml|yaml)$/.test(L)?C.subtle:/\.(sh|bash|zsh)$/.test(L)?C.success:C.reset}let p=[],h=0,m=Pt(),g=m?"\u251C\u2500\u2500 ":"|-- ",y=m?"\u2514\u2500\u2500 ":"`-- ",b=m?"\u2502 ":"| ",x=" ",_=c.relative(process.cwd(),e)||".";p.push(`${C.bold}${C.cyan}${_}${C.reset}`);function E(S,O,L){if(O>n||h>=o)return;let I;try{I=a.readdirSync(S,{withFileTypes:!0})}catch{p.push(`${L}${g}${C.dim}(unreadable)${C.reset}`);return}I.sort((K,X)=>K.isDirectory()!==X.isDirectory()?K.isDirectory()?-1:1:K.name.localeCompare(X.name)),I=I.filter(K=>!u.has(K.name)&&!K.name.startsWith("."));let D=20,Z=I.length-D;Z>0&&(I=I.slice(0,D));for(let K=0;K<I.length;K++){if(h>=o){p.push(`${L}${g}${C.dim}\u2026 +${Z} more${C.reset}`);return}let X=I[K],Fe=K===I.length-1&&Z<=0,Oe=Fe?y:g,V=L+(Fe?x:b),re=c.join(S,X.name),rt=c.relative(process.cwd(),re),qe=C.reset;s.has(rt)?qe=C.yellow:r.has(rt)?qe=C.dim:qe=f(X.name,X.isDirectory());let ke=d(X.name,X.isDirectory()),Me=X.isDirectory()?`${C.bold}${X.name}/${C.reset}`:X.name;p.push(`${L}${Oe}${qe}${ke}${Me}${C.reset}`),h++,X.isDirectory()&&E(re,O+1,V)}Z>0&&p.push(`${L}${g}${C.dim}\u2026 +${Z} more${C.reset}`)}return E(e,1,""),p.join(`
42
42
  `)}Wm.exports={hasUnicode:Pt,G:bt,renderTree:aS,renderMarkdown:oS,renderInline:Bs,stripHeadingMarkers:An,highlightCode:ld,highlightJS:Lm,highlightBash:Im,highlightJSON:jm,highlightPython:Dm,highlightGo:qm,highlightRust:Fm,highlightCSS:Bm,highlightHTML:Um,renderTable:rS,renderProgress:iS,wrapAnsi:Us,StreamRenderer:cd}});var Sc=Q((OD,Qm)=>{var{T:A}=ln(),Pr=null;function _c(){if(Pr!==null)return Pr;let e=(process.env.LANG||process.env.LC_ALL||process.env.LC_CTYPE||"").toLowerCase();return e.includes("utf-8")||e.includes("utf8")||process.stdout.isTTY&&process.stdout.columns>0?Pr=!0:Pr=process.env.TERM?!/^(vt100|vt220|ansi|xterm)$/.test(process.env.TERM):!0,Pr}var st=A,Hm=require("path"),Gm=_c()?["\u25C6","\u25C7","\u25CE","\u25C7"]:["#","o","@","o"];function xc(e){if(!e)return"";let t=e.replace(/^\.\//,"").split("/");return t.length>1?t.slice(-2).join("/"):t[0]}var cS={read_file:A.tool_read,list_directory:A.tool_read,write_file:A.tool_write,edit_file:A.tool_write,patch_file:A.tool_write,bash:A.tool_exec,grep:A.tool_search,search_files:A.tool_search,glob:A.tool_search,git_commit:A.tool_git,git_push:A.tool_git,git_pull:A.tool_git,git_status:A.tool_git,git_diff:A.tool_git,git_log:A.tool_git,git_branch:A.tool_git,git_stash:A.tool_git,web_fetch:A.tool_web,web_search:A.tool_web,sysadmin:A.tool_sysadmin,ssh_exec:A.tool_sysadmin,ssh_upload:A.tool_sysadmin,ssh_download:A.tool_sysadmin,deploy:A.tool_sysadmin},Xm={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"},lS={read_file:{label:"Inspect",accent:A.tool_read,icon:"\u25CC"},list_directory:{label:"Inspect",accent:A.tool_read,icon:"\u25CC"},grep:{label:"Inspect",accent:A.tool_search,icon:"\u25CC"},search_files:{label:"Inspect",accent:A.tool_search,icon:"\u25CC"},glob:{label:"Inspect",accent:A.tool_search,icon:"\u25CC"},web_fetch:{label:"Explore",accent:A.tool_web,icon:"\u25CC"},web_search:{label:"Explore",accent:A.tool_web,icon:"\u25CC"},browser_open:{label:"Explore",accent:A.tool_web,icon:"\u25CC"},browser_screenshot:{label:"Capture",accent:A.tool_web,icon:"\u25CC"},browser_click:{label:"Interact",accent:A.tool_web,icon:"\u25CC"},browser_fill:{label:"Interact",accent:A.tool_web,icon:"\u25CC"},write_file:{label:"Shape",accent:A.tool_write,icon:"\u2726"},edit_file:{label:"Shape",accent:A.tool_write,icon:"\u2726"},patch_file:{label:"Shape",accent:A.tool_write,icon:"\u2726"},bash:{label:"Execute",accent:A.tool_exec,icon:"\u25A3"},sysadmin:{label:"Operate",accent:A.tool_sysadmin,icon:"\u25A3"},ssh_exec:{label:"Operate",accent:A.tool_sysadmin,icon:"\u25A3"},ssh_upload:{label:"Ship",accent:A.tool_sysadmin,icon:"\u25A3"},ssh_download:{label:"Collect",accent:A.tool_sysadmin,icon:"\u25A3"},deploy:{label:"Ship",accent:A.tool_sysadmin,icon:"\u25A3"},git_status:{label:"Verify",accent:A.tool_git,icon:"\u2713"},git_diff:{label:"Verify",accent:A.tool_git,icon:"\u2713"},git_log:{label:"Verify",accent:A.tool_git,icon:"\u2713"},git_commit:{label:"Commit",accent:A.tool_git,icon:"\u2713"},git_push:{label:"Ship",accent:A.tool_git,icon:"\u2713"},git_pull:{label:"Sync",accent:A.tool_git,icon:"\u2713"},git_branch:{label:"Sync",accent:A.tool_git,icon:"\u2713"},git_stash:{label:"Sync",accent:A.tool_git,icon:"\u2713"}};function Vm(e){return String(e||"").replace(/\x1B(?:\][^\x07]*(?:\x07|\x1B\\)|[PX^_][\s\S]*?\x1B\\)/g,"").replace(/[\x1B\x9B][[\]()#;?]*(?:\d{1,4}(?:;\d{0,4})*)?[0-9A-ORZcf-nq-uy=><]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,"")}function uS(e){let t=e.trim();if(!t)return!1;let n=t.replace(/^[│┃┆┊>↩✓✗⚠◆●◉◎⏺◌✦▣•\-\s]+/,"").trim();return!!(/^(INSPECT|SHAPE|EXECUTE|EXPLORE|VERIFY|OPERATE|SHIP|SYNC|COMMIT|RUN|CAPTURE|INTERACT)\b/i.test(n)||/^Step\s+\d+\b/i.test(n)||/^(Read|Write|Edit|Patch|Bash|Grep|Search|Glob|WebFetch|WebSearch|TaskList|Agent|AskUser)\b.*\s→\s/i.test(n)||/^(Reading|Writing|Editing|Patching|Running|Searching|Listing|Fetching|Delegating|Switching)\b/i.test(n)||/^\[(?:context|auto|pre-flight|pre-stop|debug|system)\b/i.test(n)||/\b(?:auto-abort|Ctrl\+C to abort|Headless early exit|Phase transition|tool budget|model metadata|orchestration log)\b/i.test(n)||/^(?:Thinking|Analyzing|Planning|Implementing|Verifying|Working)(?:[.\s]|$)/i.test(n)||/^(?:Model|Provider|Tokens|Cost|Usage):\s/i.test(n))}function dS(e){let t=Vm(e),n=[],o=!1;for(let s of t.split(/\r?\n/)){if(/^\s*```/.test(s)){o=!o,n.push(s.replace(/[ \t]+$/g,""));continue}!o&&uS(s)||n.push(s.replace(/[ \t]+$/g,""))}return n.join(`
43
43
  `).replace(/\n{3,}/g,`
44
44
 
@@ -46,7 +46,7 @@ ${C.dim} ${r}${C.reset}
46
46
  `).map(t=>{let n=t.match(/^(\d+):\s?(.*)$/s);return n?{lineNumber:n[1],content:n[2]||""}:null}).filter(Boolean)}function hS(e,t,n={}){let{maxLines:o=4,indent:s=" ",maxContent:r=110,includeOverflow:i=!0}=n;if(!Array.isArray(t)||t.length===0)return"";let{highlightLine:a,detectLang:c}=wc(),u=c(e||null),d=t.slice(0,o),f=d.map(({lineNumber:p,content:h})=>{let m=h.length>r?h.substring(0,r-1)+"\u2026":h;return`${s}${A.subtle}${p}:${A.reset} ${a(m,u)}${A.reset}`});return i&&t.length>d.length&&f.push(`${s}${A.subtle}\u2026 +${t.length-d.length} more line${t.length-d.length!==1?"s":""}${A.reset}`),f.join(`
47
47
  `)}function mS(e,t=96){let n=String(e||"").replace(/\t/g," ").trimEnd();return n.length>t?n.substring(0,Math.max(1,t-1))+"\u2026":n}function dd(e,t={}){let{maxLines:n=3,maxContent:o=96}=t,r=String(e||"").split(`
48
48
  `).filter((a,c,u)=>a.trim()||u.length===1||c===0),i=r.slice(0,n).map(a=>mS(a,o));return{shown:i,more:Math.max(0,r.length-i.length)}}function Jm(e,t={}){let{indent:n=" ",maxLines:o=2,maxContent:s=100}=t;if(!e)return"";let{shown:r,more:i}=dd(e,{maxLines:o,maxContent:s});if(r.length===0)return"";let a=r.map((c,u)=>`${n}${A.subtle}${u===0?"$":">"}${A.reset} ${A.muted}${c}${A.reset}`);return i>0&&a.push(`${n}${A.subtle}\u2026 +${i} more command line${i!==1?"s":""}${A.reset}`),a.join(`
49
- `)}function pd(e,t,n,o={}){let{indent:s=" ",maxLines:r=3,maxContent:i=96,includeLabels:a=!0}=o,{highlightLine:c,detectLang:u}=wc(),d=u(e||null),{shown:f,more:p}=dd(t,{maxLines:r,maxContent:i}),{shown:h,more:m}=dd(n,{maxLines:r,maxContent:i}),g=[];return f.length>0&&a&&g.push(`${s}${A.subtle}before${A.reset}`),f.forEach($=>{g.push(`${s}${A.diff_rem}- ${A.reset}${c($,d)}${A.reset}`)}),p>0&&g.push(`${s}${A.subtle}\u2026 ${p} more removed line${p!==1?"s":""}${A.reset}`),h.length>0&&a&&g.push(`${s}${A.subtle}after${A.reset}`),h.forEach($=>{g.push(`${s}${A.diff_add}+ ${A.reset}${c($,d)}${A.reset}`)}),m>0&&g.push(`${s}${A.subtle}\u2026 ${m} more added line${m!==1?"s":""}${A.reset}`),g.join(`
49
+ `)}function pd(e,t,n,o={}){let{indent:s=" ",maxLines:r=3,maxContent:i=96,includeLabels:a=!0}=o,{highlightLine:c,detectLang:u}=wc(),d=u(e||null),{shown:f,more:p}=dd(t,{maxLines:r,maxContent:i}),{shown:h,more:m}=dd(n,{maxLines:r,maxContent:i}),g=[];return f.length>0&&a&&g.push(`${s}${A.subtle}before${A.reset}`),f.forEach(y=>{g.push(`${s}${A.diff_rem}- ${A.reset}${c(y,d)}${A.reset}`)}),p>0&&g.push(`${s}${A.subtle}\u2026 ${p} more removed line${p!==1?"s":""}${A.reset}`),h.length>0&&a&&g.push(`${s}${A.subtle}after${A.reset}`),h.forEach(y=>{g.push(`${s}${A.diff_add}+ ${A.reset}${c(y,d)}${A.reset}`)}),m>0&&g.push(`${s}${A.subtle}\u2026 ${m} more added line${m!==1?"s":""}${A.reset}`),g.join(`
50
50
  `)}function Zm(e,t,n={}){let{indent:o=" ",maxPatches:s=2,maxLinesPerSide:r=2,maxContent:i=92}=n;if(!Array.isArray(t)||t.length===0)return"";let a=[];return t.slice(0,s).forEach((c,u)=>{a.push(`${o}${A.subtle}patch ${u+1}${A.reset}`);let d=pd(e,c.old_text,c.new_text,{indent:o+" ",maxLines:r,maxContent:i,includeLabels:!1});d&&a.push(d)}),t.length>s&&a.push(`${o}${A.subtle}\u2026 +${t.length-s} more patches${A.reset}`),a.join(`
51
51
  `)}function gS(e){let t=new Set,n=[];for(let o of e){let s=fd(o.fnName).label;t.has(s)||(t.add(s),n.push(s))}return n.length===0?"":n.length<=3?n.join(`${st.dim} \u2192 ${st.reset}`):`${n.slice(0,3).join(`${st.dim} \u2192 ${st.reset}`)}${st.dim} \u2192 +${n.length-3}${st.reset}`}function kc(e,t=!1,n=null){if(t)return`${A.error}${_c()?"\u2716":"x"}${A.reset}`;let o=cS[e]||A.tool_default;if(n==="blink")return`${o}\x1B[5m${_c()?"\u25CF":"*"}\x1B[25m${A.reset}`;let s=typeof n=="number"?Gm[n%Gm.length]:n!==null?n:_c()?"\u25CF":"*";return`${o}${s}${A.reset}`}function yS(e,t,n=!1,o=null){let s=(e||[]).filter(u=>u&&u.canExecute!==!1);if(s.length===0)return`${kc("",n,o)} Step ${t}`;if(s.length===1){let u=s[0],d=u.args||{},f=zm(u.fnName,{...d,path:d._originalPath||d.path});return`${kc(u.fnName,n,o)} ${Ym(u.fnName)} ${st.bold}${f}${st.reset}`}let r=s[0].fnName,i=gS(s)||`${s.length} tools`,a=s.slice(0,2).map(u=>zm(u.fnName,u.args||{})).filter(Boolean).join(`${st.dim} \xB7 ${st.reset}`),c=a?` ${A.subtle}\xB7${A.reset} ${st.dim}${a}${st.reset}`:"";return`${kc(r,n,o)} ${Ym(r)} ${st.bold}${i}${st.reset}${c}`}function $S(e,t){let n;switch(e){case"write_file":case"edit_file":case"patch_file":case"read_file":case"list_directory":n=t.path||"";break;case"bash":case"ssh_exec":n=(t.command||"").substring(0,52);break;case"grep":case"search_files":n=t.pattern?`"${t.pattern}"${t.path?` in ${t.path}`:""}`:"";break;case"glob":n=t.pattern||"";break;case"web_fetch":n=(t.url||"").substring(0,60);break;case"web_search":n=(t.query||"").substring(0,50);break;default:n=JSON.stringify(t).substring(0,80)}let o=Xm[e]||e.replace(/_/g," "),s=n?` ${st.dim}${n}${st.reset}`:"",r=`${kc(e)} ${st.bold}${o}${st.reset}${s}`;if(e==="bash"||e==="ssh_exec"){let i=Jm(t.command,{indent:" ",maxLines:2,maxContent:108});return i?`${r}
52
52
  ${i}`:r}if(e==="edit_file"){let i=pd(t.path,t.old_text,t.new_text,{indent:" ",maxLines:2,maxContent:92});return i?`${r}
@@ -56,52 +56,52 @@ ${i}`:r}return r}function bS(e,t=8){let n=e.split(`
56
56
  `);return s>0&&(r+=`
57
57
  ${A.subtle} \u2026 +${s} lines${A.reset}`),r}var vc=["Sampling","Decoding","Attending","Inferring","Generating","Routing","Embedding","Reasoning","Tokenizing","Predicting"],Km=Math.floor(Math.random()*vc.length),wS=null;function _S(e){wS=e}function kS(){let e=vc[Km%vc.length];return Km++,e}function xS(e,t){switch(e){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 ${t.path||"file"}`;case"list_directory":return`Listing ${t.path||"."}`;case"search_files":return`Searching ${t.pattern||"..."}`;case"glob":return`Searching ${t.pattern||"..."}`;case"grep":return`Searching ${t.pattern||"..."}`;case"web_fetch":return`Fetching ${(t.url||"").substring(0,60)}`;case"web_search":return`Searching web: ${(t.query||"").substring(0,50)}`;case"git_status":return"Analyzing repository status";case"git_diff":return`Diffing${t.file?` ${t.file}`:""}`;case"git_log":return`Reading git log${t.file?` (${t.file})`:""}`;case"gh_run_list":return`GitHub Actions: listing runs${t.workflow?` (${t.workflow})`:""}...`;case"gh_run_view":return`GitHub Actions: run ${t.run_id}...`;case"gh_workflow_trigger":return`GitHub Actions: trigger ${t.workflow}...`;case"browser_open":return`Browser: opening ${(t.url||"").substring(0,60)}...`;case"browser_screenshot":return`Browser: screenshot ${(t.url||"").substring(0,60)}...`;case"browser_click":return`Browser: clicking ${t.text||t.selector||"element"}...`;case"browser_fill":return`Browser: filling ${t.selector||"field"}...`;case"sysadmin":{let n=t.server&&t.server!=="local"?` [${t.server}]`:"";switch(t.action){case"audit":return`Sysadmin${n}: full audit...`;case"disk_usage":return`Sysadmin${n}: disk usage ${t.path||"/"}...`;case"process_list":return`Sysadmin${n}: top processes (${t.sort_by||"cpu"})...`;case"network_status":return`Sysadmin${n}: network status...`;case"ssl_check":return`Sysadmin${n}: SSL check ${t.domain||t.cert_path||""}...`;case"log_tail":return`Sysadmin${n}: tail ${t.path||"log"}...`;case"find_large":return`Sysadmin${n}: find large files in ${t.path||"/"}...`;case"service":return`Sysadmin${n}: service ${t.service_action||""} ${t.service_name||""}...`;case"kill_process":return`Sysadmin${n}: kill PID ${t.pid||t.process_name||"?"}...`;case"journalctl":return`Sysadmin${n}: journal ${t.unit?`[${t.unit}]`:""}${t.since?` since ${t.since}`:""}...`;case"package":return`Sysadmin${n}: package ${t.package_action||""} ${(t.packages||[]).join(" ")}...`;case"firewall":return`Sysadmin${n}: firewall ${t.firewall_action||""}...`;case"user_manage":return`Sysadmin${n}: user ${t.user_action||""} ${t.user||""}...`;case"cron":return`Sysadmin${n}: cron ${t.cron_action||""}...`;default:return`Sysadmin${n}: ${t.action}...`}}case"visual_diff":return"Comparing screenshots (pixel diff)...";case"responsive_sweep":return`Responsive sweep: ${(t.url||"").substring(0,50)}...`;case"visual_annotate":return`Annotating screenshot (${(t.annotations||[]).length} markers)...`;case"visual_watch":return`Visual watch: ${(t.url||"").substring(0,50)}...`;case"design_tokens":return"Extracting design tokens...";case"design_compare":return"Comparing against reference design...";default:return`Running: ${e}`}}function vS(e,t,n,o){let s=String(n||""),r=fd(e),i=` ${A.subtle}\u2502${A.reset} ${r.accent}${st.bold}${r.label}${A.reset} ${A.subtle}\xB7${A.reset} `;if(o){let u=s.split(`
58
58
  `)[0];if(u.startsWith("BLOCKED:")){let h=u.replace(/^BLOCKED:\s*/,"").replace(/\s*—.*$/,"").replace(/\s*\(hard cap:.*?\)/,"").trim().substring(0,70);return`${i}${A.muted}blocked: ${h}${A.reset}`}let d=u.replace(/^ERROR:\s*/i,"").substring(0,80),f=s.match(/\nHINT: (.+)/),p=f?`
59
- ${A.muted}${f[1].substring(0,100)}${A.reset}`:"";return`${i}${A.error}${d}${A.reset}${p}`}let a;switch(e){case"read_file":{let u=pS(s),d=u.length,f=u[u.length-1],p=f?parseInt(f.lineNumber||"0"):0,h=t.line_start||t.line_end,m=t.path?Hm.basename(t.path):null,g=m?` ${A.muted}from ${m}${A.reset}`:"";h&&p>d?a=`Read lines ${t.line_start||1}\u2013${p}${g}`:a=`Read ${d} line${d!==1?"s":""}${g}`;let $=hS(t.path,u,{maxLines:4,maxContent:120});$&&(a+=`
60
- ${$}`);break}case"write_file":{let d=(t.content||"").split(`
61
- `).length,f=t.path?Hm.basename(t.path):null,p=f?`Wrote ${f} \xB7 ${d} line${d!==1?"s":""}`:`Wrote ${d} line${d!==1?"s":""}`,{highlightLines:h}=wc(),m=h(t.content||"",t.path||null),g=40,$=8;if(d<=g){let b=m.map(x=>` ${x}`).join(`
59
+ ${A.muted}${f[1].substring(0,100)}${A.reset}`:"";return`${i}${A.error}${d}${A.reset}${p}`}let a;switch(e){case"read_file":{let u=pS(s),d=u.length,f=u[u.length-1],p=f?parseInt(f.lineNumber||"0"):0,h=t.line_start||t.line_end,m=t.path?Hm.basename(t.path):null,g=m?` ${A.muted}from ${m}${A.reset}`:"";h&&p>d?a=`Read lines ${t.line_start||1}\u2013${p}${g}`:a=`Read ${d} line${d!==1?"s":""}${g}`;let y=hS(t.path,u,{maxLines:4,maxContent:120});y&&(a+=`
60
+ ${y}`);break}case"write_file":{let d=(t.content||"").split(`
61
+ `).length,f=t.path?Hm.basename(t.path):null,p=f?`Wrote ${f} \xB7 ${d} line${d!==1?"s":""}`:`Wrote ${d} line${d!==1?"s":""}`,{highlightLines:h}=wc(),m=h(t.content||"",t.path||null),g=40,y=8;if(d<=g){let b=m.map(x=>` ${x}`).join(`
62
62
  `);a=`${p}
63
- ${b}`}else{let b=m.slice(0,$).map(x=>` ${x}`).join(`
63
+ ${b}`}else{let b=m.slice(0,y).map(x=>` ${x}`).join(`
64
64
  `);a=`${p}
65
65
  ${b}
66
- ${A.subtle}\u2026 +${d-$} lines${A.reset}`}break}case"edit_file":{let u=(t.old_text||"").split(`
66
+ ${A.subtle}\u2026 +${d-y} lines${A.reset}`}break}case"edit_file":{let u=(t.old_text||"").split(`
67
67
  `),d=(t.new_text||"").split(`
68
68
  `),f=u.length,p=d.length,h=t.path?xc(t.path):null,m=h?` ${A.muted}${h}${A.reset}`:"",g=pd(t.path,t.old_text,t.new_text,{indent:" ",maxLines:4,maxContent:96});a=`${A.diff_rem}\u2212${f}${A.reset} ${A.diff_add}+${p}${A.reset}${m}`+(g?`
69
- `+g:"");break}case"patch_file":{let u=t.patches||[],d=u.reduce((g,$)=>g+($.old_text||"").split(`
70
- `).length,0),f=u.reduce((g,$)=>g+($.new_text||"").split(`
69
+ `+g:"");break}case"patch_file":{let u=t.patches||[],d=u.reduce((g,y)=>g+(y.old_text||"").split(`
70
+ `).length,0),f=u.reduce((g,y)=>g+(y.new_text||"").split(`
71
71
  `).length,0),p=t.path?xc(t.path):null,h=p?` ${A.muted}${p}${A.reset}`:"";a=`${u.length} patch${u.length!==1?"es":""} ${A.diff_rem}\u2212${d}${A.reset} ${A.diff_add}+${f}${A.reset}${h}`;let m=Zm(t.path,u,{indent:" ",maxPatches:3,maxLinesPerSide:2,maxContent:92});m&&(a+=`
72
72
  ${m}`);break}case"bash":{let d=s.match(/^EXIT (\d+)/),f=s.split(`
73
- `).filter(g=>g&&!g.startsWith("EXIT ")&&!g.startsWith("HINT:")&&g.trim()),p=d?d[1]==="0"?`${A.success}\u2713${A.reset}`:`${A.error}\u2717 Exit ${d[1]}${A.reset}`:`${A.success}\u2713${A.reset}`,h=s.match(/\nHINT: (.+)/);if(h)a=`${p} ${A.muted}\u2014 ${h[1].substring(0,100)}${A.reset}`;else if(f.length===0)a=p;else{let g=d&&d[1]!=="0",$=g?f.slice(-3):f.slice(0,3),b=f.length-3,x=$.map((_,E)=>E===0?`${p} ${A.muted}${_.substring(0,120)}${A.reset}`:` ${A.muted}${_.substring(0,120)}${A.reset}`);if(b>0){let _=g?` ${A.subtle}${b} lines above\u2026${A.reset}`:` ${A.subtle}\u2026 +${b} lines${A.reset}`;g?x.unshift(_):x.push(_)}a=x.join(`
73
+ `).filter(g=>g&&!g.startsWith("EXIT ")&&!g.startsWith("HINT:")&&g.trim()),p=d?d[1]==="0"?`${A.success}\u2713${A.reset}`:`${A.error}\u2717 Exit ${d[1]}${A.reset}`:`${A.success}\u2713${A.reset}`,h=s.match(/\nHINT: (.+)/);if(h)a=`${p} ${A.muted}\u2014 ${h[1].substring(0,100)}${A.reset}`;else if(f.length===0)a=p;else{let g=d&&d[1]!=="0",y=g?f.slice(-3):f.slice(0,3),b=f.length-3,x=y.map((_,E)=>E===0?`${p} ${A.muted}${_.substring(0,120)}${A.reset}`:` ${A.muted}${_.substring(0,120)}${A.reset}`);if(b>0){let _=g?` ${A.subtle}${b} lines above\u2026${A.reset}`:` ${A.subtle}\u2026 +${b} lines${A.reset}`;g?x.unshift(_):x.push(_)}a=x.join(`
74
74
  `)}let m=Jm(t.command,{indent:" ",maxLines:2,maxContent:108});m&&(a=`${m}
75
- ${a}`);break}case"grep":case"search_files":{if(s.includes("(no matches)")||s==="no matches")a=`No matches${t.pattern?` ${A.muted}"${String(t.pattern).substring(0,40)}"${A.reset}`:""}`;else{let $=function(E){let S=E.indexOf(":");if(S===-1)return`${A.muted}${E.substring(0,90)}${A.reset}`;let O=E.substring(0,S),L=E.substring(S+1),I=L.match(/^(\d+)[:-](.*)/s),D=I?`:${I[1]}`:"",Z=(I?I[2]:L).trim(),K=`${A.subtle}${u.basename(O)}${D}${A.reset}`,X=`${A.muted}${Z.substring(0,80)}${Z.length>80?"\u2026":""}${A.reset}`;return`${K} ${X}`};var c=$;let u=require("path"),d=s.split(`
75
+ ${a}`);break}case"grep":case"search_files":{if(s.includes("(no matches)")||s==="no matches")a=`No matches${t.pattern?` ${A.muted}"${String(t.pattern).substring(0,40)}"${A.reset}`:""}`;else{let y=function(E){let S=E.indexOf(":");if(S===-1)return`${A.muted}${E.substring(0,90)}${A.reset}`;let O=E.substring(0,S),L=E.substring(S+1),I=L.match(/^(\d+)[:-](.*)/s),D=I?`:${I[1]}`:"",Z=(I?I[2]:L).trim(),K=`${A.subtle}${u.basename(O)}${D}${A.reset}`,X=`${A.muted}${Z.substring(0,80)}${Z.length>80?"\u2026":""}${A.reset}`;return`${K} ${X}`};var c=y;let u=require("path"),d=s.split(`
76
76
  `).filter(Boolean),f=d.length,h=new Set(d.map(E=>E.split(":")[0]).filter(Boolean)).size,m=t.pattern?` ${A.muted}"${String(t.pattern).substring(0,40)}"${A.reset}`:"",g=h>1?`${f} match${f!==1?"es":""} in ${h} files${m}`:`${f} match${f!==1?"es":""}${m}`,b=t.path?`
77
77
  ${A.subtle}path:${A.reset} ${A.muted}${String(t.path).substring(0,70)}${A.reset}`:"",x=d.slice(0,5).map((E,S)=>S===0?`${g}${b}
78
- ${$(E)}`:` ${$(E)}`),_=d.length-5;_>0&&x.push(` ${A.subtle}\u2026 +${_} more matches${A.reset}`),a=x.join(`
78
+ ${y(E)}`:` ${y(E)}`),_=d.length-5;_>0&&x.push(` ${A.subtle}\u2026 +${_} more matches${A.reset}`),a=x.join(`
79
79
  `)}break}case"glob":{let u=t.pattern?` ${A.muted}${String(t.pattern).substring(0,50)}${A.reset}`:"";if(s==="(no matches)")a=`No files found${u}`;else{let d=require("path"),f=s.split(`
80
- `).filter(Boolean),p=f.length,h=f.slice(0,8),m=p-h.length,g=h.map(b=>` ${A.muted}${b}${A.reset}`);m>0&&g.push(` ${A.subtle}\u2026 +${m} more files${A.reset}`);let $=t.path?`
81
- ${A.subtle}path:${A.reset} ${A.muted}${String(t.path).substring(0,70)}${A.reset}`:"";a=`${p} file${p!==1?"s":""}${u}${$}`+(g.length>0?`
80
+ `).filter(Boolean),p=f.length,h=f.slice(0,8),m=p-h.length,g=h.map(b=>` ${A.muted}${b}${A.reset}`);m>0&&g.push(` ${A.subtle}\u2026 +${m} more files${A.reset}`);let y=t.path?`
81
+ ${A.subtle}path:${A.reset} ${A.muted}${String(t.path).substring(0,70)}${A.reset}`:"";a=`${p} file${p!==1?"s":""}${u}${y}`+(g.length>0?`
82
82
  ${g.join(`
83
83
  `)}`:"")}break}case"list_directory":{if(s==="(empty)")a="0 entries";else{let u=s.split(`
84
84
  `).filter(Boolean),d=u.length,f=u.slice(0,6).join(", "),p=d-6;a=p>0?`${d} entries \u2014 ${A.muted}${f}, +${p} more${A.reset}`:`${d} entr${d!==1?"ies":"y"} \u2014 ${A.muted}${f}${A.reset}`}break}case"git_status":{let u=s.match(/Branch:\s*(\S+)/),d=s.split(`
85
85
  `).filter(f=>/^\s*[MADRCU?!]/.test(f)).length;a=u?`${u[1]} \xB7 ${d} change${d!==1?"s":""}`:"Done";break}case"git_diff":{let u=(s.match(/^\+[^+]/gm)||[]).length,d=(s.match(/^-[^-]/gm)||[]).length;a=u||d?`+${u} \u2212${d} lines`:"No diff";break}case"git_log":{let u=s.split(`
86
86
  `).filter(h=>/^commit\s+[0-9a-f]{7}/.test(h)),d=u.length,f=u[0]?u[0].replace(/^commit\s+/,"").substring(0,7):null,p=(()=>{let h=s.indexOf(u[0]||"\0");return h===-1?null:s.substring(h).split(`
87
- `).find((g,$)=>$>0&&g.trim()&&!g.startsWith("Author:")&&!g.startsWith("Date:")&&!g.startsWith("Merge:"))})();if(d===0)a="Log retrieved";else if(f&&p){let h=d>1?` ${A.muted}+${d-1} more${A.reset}`:"";a=`${f} ${A.muted}${p.trim().substring(0,60)}${A.reset}${h}`}else a=`${d} commit${d!==1?"s":""}`;break}case"git_commit":{let u=s.match(/\[[\w./\-]+ ([0-9a-f]{7,})\]/),d=s.match(/\[[\w./\-]+ [0-9a-f]+\]\s+(.+)/);a=u?`${u[1]}${d?` \u2014 ${d[1].substring(0,55)}`:""}`:"Committed";break}case"git_push":{let u=s.match(/(?:->|→)\s*(\S+)/);a=u?`\u2192 ${u[1]}`:"Pushed";break}case"git_pull":{if(/Already up.to.date/i.test(s))a="Already up to date";else{let u=(s.match(/^\+/gm)||[]).length;a=u>0?`Pulled \xB7 +${u} lines`:"Pulled"}break}case"web_fetch":{let u=s.match(/<title[^>]*>([^<]{1,80})<\/title>/i),d=s.match(/^#\s+(.{1,80})/m),f=t.url||"",p="";try{p=new URL(f).hostname}catch{p=f.substring(0,60)}let h=u?u[1].trim():d?d[1].trim():null;a=h?`${p} \u2014 ${A.muted}${h.substring(0,70)}${A.reset}`:`Fetched ${p}`;break}case"web_search":{let u=s.split(`
87
+ `).find((g,y)=>y>0&&g.trim()&&!g.startsWith("Author:")&&!g.startsWith("Date:")&&!g.startsWith("Merge:"))})();if(d===0)a="Log retrieved";else if(f&&p){let h=d>1?` ${A.muted}+${d-1} more${A.reset}`:"";a=`${f} ${A.muted}${p.trim().substring(0,60)}${A.reset}${h}`}else a=`${d} commit${d!==1?"s":""}`;break}case"git_commit":{let u=s.match(/\[[\w./\-]+ ([0-9a-f]{7,})\]/),d=s.match(/\[[\w./\-]+ [0-9a-f]+\]\s+(.+)/);a=u?`${u[1]}${d?` \u2014 ${d[1].substring(0,55)}`:""}`:"Committed";break}case"git_push":{let u=s.match(/(?:->|→)\s*(\S+)/);a=u?`\u2192 ${u[1]}`:"Pushed";break}case"git_pull":{if(/Already up.to.date/i.test(s))a="Already up to date";else{let u=(s.match(/^\+/gm)||[]).length;a=u>0?`Pulled \xB7 +${u} lines`:"Pulled"}break}case"web_fetch":{let u=s.match(/<title[^>]*>([^<]{1,80})<\/title>/i),d=s.match(/^#\s+(.{1,80})/m),f=t.url||"",p="";try{p=new URL(f).hostname}catch{p=f.substring(0,60)}let h=u?u[1].trim():d?d[1].trim():null;a=h?`${p} \u2014 ${A.muted}${h.substring(0,70)}${A.reset}`:`Fetched ${p}`;break}case"web_search":{let u=s.split(`
88
88
 
89
89
  `).filter(Boolean),d=u.length,f=u[0]?u[0].split(`
90
90
  `)[0].replace(/^\d+\.\s*/,"").trim():null,p=f?` ${A.muted}\u2014 ${f.substring(0,70)}${A.reset}`:"";a=`${d} result${d!==1?"s":""}${p}`;break}case"task_list":a="Done";break;case"spawn_agents":{if(s.includes("Background agents started")){let f=s.match(/\bbg-[\w-]+/g),p=f?f.length:0;a=`${p} bg agent${p!==1?"s":""} started`;break}let u=(s.match(/✓ Agent/g)||[]).length,d=(s.match(/✗ Agent/g)||[]).length;a=d>0?`${u} done, ${d} failed`:`${u} agent${u!==1?"s":""} done`;break}case"switch_model":{let u=s.match(/Switched to (.+)/);a=u?`\u2192 ${u[1]}`:"Done";break}case"ssh_exec":{let d=s.startsWith("EXIT ")||s.startsWith("Command failed"),f=s.split(`
91
- `).filter(h=>h.trim()&&!h.startsWith("EXIT ")),p=d?`${A.error}\u2717${A.reset}`:`${A.success}\u2713${A.reset}`;if(f.length===0)a=p;else{if(f.length>2&&f.every(b=>/^\[/.test(b.trim()))){a=`${p} ${f.length} log lines`;break}let m=d?f.slice(-3):f.slice(0,3),g=f.length-3,$=m.map((b,x)=>x===0?`${p} ${A.muted}${b.substring(0,120)}${A.reset}`:` ${A.muted}${b.substring(0,120)}${A.reset}`);if(g>0){let b=d?` ${A.subtle}${g} lines above\u2026${A.reset}`:` ${A.subtle}\u2026 +${g} lines${A.reset}`;d?$.unshift(b):$.push(b)}a=$.join(`
91
+ `).filter(h=>h.trim()&&!h.startsWith("EXIT ")),p=d?`${A.error}\u2717${A.reset}`:`${A.success}\u2713${A.reset}`;if(f.length===0)a=p;else{if(f.length>2&&f.every(b=>/^\[/.test(b.trim()))){a=`${p} ${f.length} log lines`;break}let m=d?f.slice(-3):f.slice(0,3),g=f.length-3,y=m.map((b,x)=>x===0?`${p} ${A.muted}${b.substring(0,120)}${A.reset}`:` ${A.muted}${b.substring(0,120)}${A.reset}`);if(g>0){let b=d?` ${A.subtle}${g} lines above\u2026${A.reset}`:` ${A.subtle}\u2026 +${g} lines${A.reset}`;d?y.unshift(b):y.push(b)}a=y.join(`
92
92
  `)}break}default:{let u=s.split(`
93
93
  `).filter(d=>d.trim()&&!d.startsWith("EXIT ")&&!d.startsWith("HINT:"));if(u.length>0){let d=u[0].trim().substring(0,90),f=u.length>1?` ${A.subtle}\u2026 +${u.length-1} lines${A.reset}`:"";a=`${A.muted}${d}${A.reset}${f}`}else a=`${r.label} complete`}}return`${i}${a}${A.reset}`}function SS(e,t,n,o,s,r){let i=Math.round(o/1e3),a=i>=60?`${Math.floor(i/60)}m ${i%60}s`:`${i}s`,c=`
94
- ${A.success}\u25C6${st.reset} ${st.bold}${e}${st.reset}`;c+=` ${A.subtle}\u2501\u2501${A.reset} ${st.dim}${a}`,r.size>0&&(c+=` \xB7 ${A.warning}${r.size} file${r.size!==1?"s":""} modified${st.reset}`),s.size>0&&(c+=` \xB7 ${A.subtle}${s.size} scanned${st.reset}`),c+=st.reset;let u=8,d=[...r].slice(0,u),f=[...s].filter(p=>!r.has(p)).slice(0,Math.max(0,u-d.length));if(d.length>0||f.length>0){let p=require("path"),h=(()=>{try{return ud().hasUnicode()}catch{return!0}})(),m=h?"\u251C\u2500 ":"|-- ",g=h?"\u2514\u2500 ":"`-- ",$=h?"\u2502 ":"| ",b=" ",x=[],_=0;for(let O of d){let L=p.relative(process.cwd(),O)||O,I=_===0&&f.length===0&&d.length===1?b:_===d.length-1&&f.length===0?g:m;x.push(`${A.subtle} ${I}${A.reset}${A.warning}${L}${A.reset}`),_++}for(let O=0;O<f.length;O++){let L=f[O],I=p.relative(process.cwd(),L)||L,D=O===f.length-1?g:m;x.push(`${A.subtle} ${D}${A.reset}${A.subtle}${I}${st.reset}`)}let E=r.size,S=s.size;if(E>u||d.length+f.length<E+S){let O=E-d.length+(S-f.length-(s.size-f.length));x.push(`${A.subtle} ${g}${A.reset}${st.dim}\u2026 +${Math.max(0,E+S-d.length-f.length)} more${st.reset}`)}x.length>0&&(c+=`
94
+ ${A.success}\u25C6${st.reset} ${st.bold}${e}${st.reset}`;c+=` ${A.subtle}\u2501\u2501${A.reset} ${st.dim}${a}`,r.size>0&&(c+=` \xB7 ${A.warning}${r.size} file${r.size!==1?"s":""} modified${st.reset}`),s.size>0&&(c+=` \xB7 ${A.subtle}${s.size} scanned${st.reset}`),c+=st.reset;let u=8,d=[...r].slice(0,u),f=[...s].filter(p=>!r.has(p)).slice(0,Math.max(0,u-d.length));if(d.length>0||f.length>0){let p=require("path"),h=(()=>{try{return ud().hasUnicode()}catch{return!0}})(),m=h?"\u251C\u2500 ":"|-- ",g=h?"\u2514\u2500 ":"`-- ",y=h?"\u2502 ":"| ",b=" ",x=[],_=0;for(let O of d){let L=p.relative(process.cwd(),O)||O,I=_===0&&f.length===0&&d.length===1?b:_===d.length-1&&f.length===0?g:m;x.push(`${A.subtle} ${I}${A.reset}${A.warning}${L}${A.reset}`),_++}for(let O=0;O<f.length;O++){let L=f[O],I=p.relative(process.cwd(),L)||L,D=O===f.length-1?g:m;x.push(`${A.subtle} ${D}${A.reset}${A.subtle}${I}${st.reset}`)}let E=r.size,S=s.size;if(E>u||d.length+f.length<E+S){let O=E-d.length+(S-f.length-(s.size-f.length));x.push(`${A.subtle} ${g}${A.reset}${st.dim}\u2026 +${Math.max(0,E+S-d.length-f.length)} more${st.reset}`)}x.length>0&&(c+=`
95
95
  `+x.join(`
96
- `))}return c}Qm.exports={C:st,formatToolCall:$S,formatResult:bS,getToolSpinnerText:xS,formatToolSummary:vS,formatSectionHeader:yS,formatMilestone:SS,stripAnsiControlSequences:Vm,sanitizeFinalAnswer:dS,getThinkingVerb:kS,setActiveModelForSpinner:_S,THINKING_VERBS:vc}});var dt=Q((MD,tg)=>{var{T:vs}=ln(),Ec=vs,ES=require("path"),eg=["01100110","01111110","01111110","01011010","01111110","00111100"];function TS(e,t){let n=[];for(let o=0;o<e.length;o+=2){let s="";for(let r=0;r<e[0].length;r++){let i=e[o][r]==="1",a=o+1<e.length&&e[o+1][r]==="1";i&&a?s+=`${t}\u2588\x1B[0m`:i&&!a?s+=`${t}\u2580\x1B[0m`:!i&&a?s+=`${t}\u2584\x1B[0m`:s+=" "}n.push(s)}return n}function RS(e,t,n={}){let o=Ec.bold,s=Ec.reset,r=TS(eg,vs.banner_logo),i=n.yolo?` ${o}${vs.banner_yolo}\u26A1 YOLO${s}`:"",a=n.gemini?` ${o}${vs.banner_gemini}\u2726 GEMINI${s}`:"",c=Ar().version,u=t?ES.basename(t):null,d=`${vs.muted}[${e||"model"}]${s}`,f=`${vs.muted}[${u||"workspace"}]${s}`,p=[` ${vs.banner_name}${o}nex-code${s} ${vs.banner_version}v${c}${s}`,` ${d} ${f}`,` ${vs.banner_logo}${o}terminal workbench${s} ${vs.muted}\xB7 /help${s}${a}${i}`,` ${Ec.dim}${"\u2014".repeat(50)}${s}`],h=Math.max(r.length,p.length),m=Math.floor((h-r.length)/2),g=Math.floor((h-p.length)/2),$=eg[0].length,b=[];for(let x=0;x<h;x++){let _=r[x-m]??" ".repeat($),E=p[x-g]??"";b.push(_+E)}console.log(`
96
+ `))}return c}Qm.exports={C:st,formatToolCall:$S,formatResult:bS,getToolSpinnerText:xS,formatToolSummary:vS,formatSectionHeader:yS,formatMilestone:SS,stripAnsiControlSequences:Vm,sanitizeFinalAnswer:dS,getThinkingVerb:kS,setActiveModelForSpinner:_S,THINKING_VERBS:vc}});var dt=Q((MD,tg)=>{var{T:vs}=ln(),Ec=vs,ES=require("path"),eg=["01100110","01111110","01111110","01011010","01111110","00111100"];function TS(e,t){let n=[];for(let o=0;o<e.length;o+=2){let s="";for(let r=0;r<e[0].length;r++){let i=e[o][r]==="1",a=o+1<e.length&&e[o+1][r]==="1";i&&a?s+=`${t}\u2588\x1B[0m`:i&&!a?s+=`${t}\u2580\x1B[0m`:!i&&a?s+=`${t}\u2584\x1B[0m`:s+=" "}n.push(s)}return n}function RS(e,t,n={}){let o=Ec.bold,s=Ec.reset,r=TS(eg,vs.banner_logo),i=n.yolo?` ${o}${vs.banner_yolo}\u26A1 YOLO${s}`:"",a=n.gemini?` ${o}${vs.banner_gemini}\u2726 GEMINI${s}`:"",c=Ar().version,u=t?ES.basename(t):null,d=`${vs.muted}[${e||"model"}]${s}`,f=`${vs.muted}[${u||"workspace"}]${s}`,p=[` ${vs.banner_name}${o}nex-code${s} ${vs.banner_version}v${c}${s}`,` ${d} ${f}`,` ${vs.banner_logo}${o}terminal workbench${s} ${vs.muted}\xB7 /help${s}${a}${i}`,` ${Ec.dim}${"\u2014".repeat(50)}${s}`],h=Math.max(r.length,p.length),m=Math.floor((h-r.length)/2),g=Math.floor((h-p.length)/2),y=eg[0].length,b=[];for(let x=0;x<h;x++){let _=r[x-m]??" ".repeat(y),E=p[x-g]??"";b.push(_+E)}console.log(`
97
97
  `+b.join(`
98
- `))}var{Spinner:CS,MultiProgress:AS,TaskProgress:OS,ToolProgress:MS,setActiveTaskProgress:PS,getActiveTaskProgress:NS,cleanupTerminal:LS}=jo(),{formatToolCall:IS,formatResult:jS,getToolSpinnerText:DS,formatToolSummary:qS,formatSectionHeader:FS,formatMilestone:BS,getThinkingVerb:US,setActiveModelForSpinner:WS}=Sc();tg.exports={C:Ec,banner:RS,Spinner:CS,MultiProgress:AS,TaskProgress:OS,ToolProgress:MS,setActiveTaskProgress:PS,getActiveTaskProgress:NS,cleanupTerminal:LS,formatToolCall:IS,formatResult:jS,getToolSpinnerText:DS,formatToolSummary:qS,formatSectionHeader:FS,formatMilestone:BS,getThinkingVerb:US,setActiveModelForSpinner:WS}});var un=Q((PD,ag)=>{var HS=require("readline"),{C:Ss}=dt(),GS=/[\u200B\u200C\u200D\uFEFF\u2060\u00AD]/g,YS=/^=([\w-]+)/;function Ri(e){return typeof e!="string"?e:e.replace(GS,"").replace(YS,"$1")}var gd=[/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/],ng=[...gd,/\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 zS(e){for(let t of ng)if(t.test(e))return t;return null}var sg=[/\.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)/],KS=/\b(?:rm|rmdir|unlink|truncate|shred|mv|cp)\b/,hd=[/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 og(e){let t=e.match(/ssh\s+[^"]*"([^"]+)"/)?.[1]||e.match(/ssh\s+[^']*'([^']+)'/)?.[1];if(!t)return!1;let o=t.replace(/\bfor\s[\s\S]*?\bdone\b/g,r=>r.replace(/;/g,"\0")).replace(/\bwhile\s[\s\S]*?\bdone\b/g,r=>r.replace(/;/g,"\0")).split(/\s*(?:&&|;)\s*/).map(r=>r.replace(/\x00/g,";").trim()).filter(Boolean);if(o.length===0)return!1;let s=r=>{let i=r.replace(/^sudo\s+(?:-[ugCD]\s+\S+\s+|-[A-Za-z]+\s+)*/,"");if(/^\s*(?:echo|printf)\s/.test(i))return!0;if(/^\s*for\s/.test(r)||/^\s*while\s/.test(r)){let a=r.match(/\bdo\s+([\s\S]*?)\s*(?:done|$)/)?.[1];return a?a.split(/\s*;\s*/).map(u=>u.trim()).filter(Boolean).every(u=>s(u)):hd.some(c=>c.test(r))}return/^\w+=\$?\(/.test(i)||/^\w+=["']/.test(i)||/^\w+=\S/.test(i)?!0:hd.some(a=>a.test(i))};return o.every(s)}var yd=[/rm\s+-rf\s/,/docker\s+system\s+prune/,/kubectl\s+delete/,/sudo\s/,/--no-verify\b/,/git\s+reset\s+--hard\b/,/git\s+clean\s+-[a-z]*f/,/git\s+checkout\s+--\s/,/git\s+push\s+(?:--force\b|-f\b)/,/\b(?:curl|wget|fetch)\b[^|;&`$()]*\|\s*(?:sh|bash|zsh|ksh|dash|python|python3|perl|ruby|node)\b/,/\b(?:curl|wget)\b[^;&`$()]*\$\([^)]*\)/,/\bbase64\s+(?:-d|--decode|-D)\b[^|;&`$()]*\|\s*(?:sh|bash|zsh|python|python3|perl|ruby|node)\b/,/\beval\s+["'`]?\$\(\s*(?:curl|wget|fetch)\b/,/\bbash\s+-i\s*>&?\s*\/dev\/tcp\//,/\bnc\s+(?:-[a-z]*e|-[a-z]*c)\b/,/\bmkfifo\b[^;&`]*;\s*(?:nc|ncat|telnet)\b/],rg=[/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/],ig=[...yd,...rg],$d=!1,Ws=null,md=null;function XS(e){$d=e}function VS(e){md=e}function JS(){return $d}function ZS(e){Ws=e}function QS(e){let t=Ri(e);for(let n of gd)if(n.test(t))return n;return null}function eE(e){let t=Ri(e);if(/ssh\s/.test(t)&&og(t))return!1;for(let n of ig)if(n.test(t))return!0;return!1}function tE(e){let t=Ri(e);for(let n of yd)if(n.test(t))return!0;return!1}function nE(e){if(process.env.NEX_UNPROTECT==="1")return null;let t=Ri(e);if(!KS.test(t))return null;for(let n of sg)if(n.test(t))return n;return null}function sE(e,t={}){if($d)return Promise.resolve(!0);if(md)return md(e,t);if(!process.stdout.isTTY||!process.stdin.isTTY||process.env.NODE_ENV==="test"||process.env.JEST_WORKER_ID||typeof process.stdin.setRawMode!="function")return oE(e,t);let n=t.toolName?["Yes","No","Always allow"]:["Yes","No"];return new Promise(o=>{let s=0;Ws&&typeof Ws.pause=="function"&&Ws.pause();let r=global._nexRawWrite||(f=>process.stdout.write(f)),i=()=>{let f=process.stdout.rows||24;return Math.max(1,f-n.length-2)},a=()=>{let f=i();global._nexRawWrite&&f>1&&global._nexRawWrite(`\x1B[1;${f-1}r`);let p=`\x1B[${f};1H\x1B[2K${Ss.yellow}${e}${Ss.reset}`;for(let h=0;h<n.length;h++){let m=h===s,g=m?`${Ss.yellow}\u276F${Ss.reset}`:" ",$=m?`${Ss.yellow}${n[h]}${Ss.reset}`:n[h];p+=`\x1B[${f+1+h};1H\x1B[2K ${g} ${$}`}r(p)},c=f=>{typeof process.stdin.setRawMode=="function"&&process.stdin.setRawMode(!1),process.stdin.pause(),process.stdin.removeListener("data",d);let p=global._nexRawWrite||(g=>process.stdout.write(g)),h=i(),m="";for(let g=0;g<n.length+1;g++)m+=`\x1B[${h+g};1H\x1B[2K`;p(m),global._nexRawWrite&&global._nexFooter&&global._nexRawWrite(`\x1B[1;${global._nexFooter._scrollEnd}r`),global._nexFooter&&global._nexFooter.drawFooter(),Ws&&typeof Ws.resume=="function"&&Ws.resume(),o(f)},u=f=>{if(f===1){c(!1);return}f===2&&t.toolName&&Tc(t.toolName),c(!0)},d=f=>{if(f[0]===3){c(!1);return}let p=f.toString();if(p==="\r"||p===`
98
+ `))}var{Spinner:CS,MultiProgress:AS,TaskProgress:OS,ToolProgress:MS,setActiveTaskProgress:PS,getActiveTaskProgress:NS,cleanupTerminal:LS}=jo(),{formatToolCall:IS,formatResult:jS,getToolSpinnerText:DS,formatToolSummary:qS,formatSectionHeader:FS,formatMilestone:BS,getThinkingVerb:US,setActiveModelForSpinner:WS}=Sc();tg.exports={C:Ec,banner:RS,Spinner:CS,MultiProgress:AS,TaskProgress:OS,ToolProgress:MS,setActiveTaskProgress:PS,getActiveTaskProgress:NS,cleanupTerminal:LS,formatToolCall:IS,formatResult:jS,getToolSpinnerText:DS,formatToolSummary:qS,formatSectionHeader:FS,formatMilestone:BS,getThinkingVerb:US,setActiveModelForSpinner:WS}});var un=Q((PD,ag)=>{var HS=require("readline"),{C:Ss}=dt(),GS=/[\u200B\u200C\u200D\uFEFF\u2060\u00AD]/g,YS=/^=([\w-]+)/;function Ri(e){return typeof e!="string"?e:e.replace(GS,"").replace(YS,"$1")}var gd=[/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/],ng=[...gd,/\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 zS(e){for(let t of ng)if(t.test(e))return t;return null}var sg=[/\.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)/],KS=/\b(?:rm|rmdir|unlink|truncate|shred|mv|cp)\b/,hd=[/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 og(e){let t=e.match(/ssh\s+[^"]*"([^"]+)"/)?.[1]||e.match(/ssh\s+[^']*'([^']+)'/)?.[1];if(!t)return!1;let o=t.replace(/\bfor\s[\s\S]*?\bdone\b/g,r=>r.replace(/;/g,"\0")).replace(/\bwhile\s[\s\S]*?\bdone\b/g,r=>r.replace(/;/g,"\0")).split(/\s*(?:&&|;)\s*/).map(r=>r.replace(/\x00/g,";").trim()).filter(Boolean);if(o.length===0)return!1;let s=r=>{let i=r.replace(/^sudo\s+(?:-[ugCD]\s+\S+\s+|-[A-Za-z]+\s+)*/,"");if(/^\s*(?:echo|printf)\s/.test(i))return!0;if(/^\s*for\s/.test(r)||/^\s*while\s/.test(r)){let a=r.match(/\bdo\s+([\s\S]*?)\s*(?:done|$)/)?.[1];return a?a.split(/\s*;\s*/).map(u=>u.trim()).filter(Boolean).every(u=>s(u)):hd.some(c=>c.test(r))}return/^\w+=\$?\(/.test(i)||/^\w+=["']/.test(i)||/^\w+=\S/.test(i)?!0:hd.some(a=>a.test(i))};return o.every(s)}var yd=[/rm\s+-rf\s/,/docker\s+system\s+prune/,/kubectl\s+delete/,/sudo\s/,/--no-verify\b/,/git\s+reset\s+--hard\b/,/git\s+clean\s+-[a-z]*f/,/git\s+checkout\s+--\s/,/git\s+push\s+(?:--force\b|-f\b)/,/\b(?:curl|wget|fetch)\b[^|;&`$()]*\|\s*(?:sh|bash|zsh|ksh|dash|python|python3|perl|ruby|node)\b/,/\b(?:curl|wget)\b[^;&`$()]*\$\([^)]*\)/,/\bbase64\s+(?:-d|--decode|-D)\b[^|;&`$()]*\|\s*(?:sh|bash|zsh|python|python3|perl|ruby|node)\b/,/\beval\s+["'`]?\$\(\s*(?:curl|wget|fetch)\b/,/\bbash\s+-i\s*>&?\s*\/dev\/tcp\//,/\bnc\s+(?:-[a-z]*e|-[a-z]*c)\b/,/\bmkfifo\b[^;&`]*;\s*(?:nc|ncat|telnet)\b/],rg=[/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/],ig=[...yd,...rg],$d=!1,Ws=null,md=null;function XS(e){$d=e}function VS(e){md=e}function JS(){return $d}function ZS(e){Ws=e}function QS(e){let t=Ri(e);for(let n of gd)if(n.test(t))return n;return null}function eE(e){let t=Ri(e);if(/ssh\s/.test(t)&&og(t))return!1;for(let n of ig)if(n.test(t))return!0;return!1}function tE(e){let t=Ri(e);for(let n of yd)if(n.test(t))return!0;return!1}function nE(e){if(process.env.NEX_UNPROTECT==="1")return null;let t=Ri(e);if(!KS.test(t))return null;for(let n of sg)if(n.test(t))return n;return null}function sE(e,t={}){if($d)return Promise.resolve(!0);if(md)return md(e,t);if(!process.stdout.isTTY||!process.stdin.isTTY||process.env.NODE_ENV==="test"||process.env.JEST_WORKER_ID||typeof process.stdin.setRawMode!="function")return oE(e,t);let n=t.toolName?["Yes","No","Always allow"]:["Yes","No"];return new Promise(o=>{let s=0;Ws&&typeof Ws.pause=="function"&&Ws.pause();let r=global._nexRawWrite||(f=>process.stdout.write(f)),i=()=>{let f=process.stdout.rows||24;return Math.max(1,f-n.length-2)},a=()=>{let f=i();global._nexRawWrite&&f>1&&global._nexRawWrite(`\x1B[1;${f-1}r`);let p=`\x1B[${f};1H\x1B[2K${Ss.yellow}${e}${Ss.reset}`;for(let h=0;h<n.length;h++){let m=h===s,g=m?`${Ss.yellow}\u276F${Ss.reset}`:" ",y=m?`${Ss.yellow}${n[h]}${Ss.reset}`:n[h];p+=`\x1B[${f+1+h};1H\x1B[2K ${g} ${y}`}r(p)},c=f=>{typeof process.stdin.setRawMode=="function"&&process.stdin.setRawMode(!1),process.stdin.pause(),process.stdin.removeListener("data",d);let p=global._nexRawWrite||(g=>process.stdout.write(g)),h=i(),m="";for(let g=0;g<n.length+1;g++)m+=`\x1B[${h+g};1H\x1B[2K`;p(m),global._nexRawWrite&&global._nexFooter&&global._nexRawWrite(`\x1B[1;${global._nexFooter._scrollEnd}r`),global._nexFooter&&global._nexFooter.drawFooter(),Ws&&typeof Ws.resume=="function"&&Ws.resume(),o(f)},u=f=>{if(f===1){c(!1);return}f===2&&t.toolName&&Tc(t.toolName),c(!0)},d=f=>{if(f[0]===3){c(!1);return}let p=f.toString();if(p==="\r"||p===`
99
99
  `){u(s);return}if(p==="\x1B[A"){s=(s-1+n.length)%n.length,a();return}if(p==="\x1B[B"){s=(s+1)%n.length,a();return}let h=p.toLowerCase().trim();if(h==="y"){c(!0);return}if(h==="n"){c(!1);return}if(h==="a"&&t.toolName){Tc(t.toolName),c(!0);return}};a(),process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",d)})}function oE(e,t){let n=t.toolName?"[Y/n/a] ":"[Y/n] ";return new Promise(o=>{let s=r=>{let i=r.trim().toLowerCase();i==="a"&&t.toolName?(Tc(t.toolName),o(!0)):o(i!=="n")};if(Ws)Ws.question(`${Ss.yellow}${e} ${n}${Ss.reset}`,s);else{let r=HS.createInterface({input:process.stdin,output:process.stdout});r.question(`${Ss.yellow}${e} ${n}${Ss.reset}`,i=>{r.close(),s(i)})}})}var Tc=()=>{};function rE(e){Tc=e}ag.exports={sanitizeBashCommand:Ri,FORBIDDEN_PATTERNS:gd,SSH_FORBIDDEN_PATTERNS:ng,BASH_PROTECTED_PATHS:sg,SSH_SAFE_PATTERNS:hd,isSSHReadOnly:og,DANGEROUS_BASH:ig,CRITICAL_BASH:yd,NOTABLE_BASH:rg,isForbidden:QS,isSSHForbidden:zS,isDangerous:eE,isCritical:tE,isBashPathForbidden:nE,confirm:sE,setAutoConfirm:XS,getAutoConfirm:JS,setConfirmHook:VS,setReadlineInterface:ZS,setAllowAlwaysHandler:rE}});var Fo=Q((ND,cg)=>{async function iE(e,t){if(!e.response?.data)return e.message;let n=e.response.data;if(typeof n=="object"&&n!==null&&typeof n.pipe!="function")return t(n)||e.message;try{let o=await new Promise((r,i)=>{let a=[];n.on("data",c=>a.push(c)),n.on("end",()=>r(Buffer.concat(a).toString("utf8"))),n.on("error",i)}),s=JSON.parse(o);return t(s)||o||e.message}catch{return e.message}}var bd=class e{constructor(t={}){if(new.target===e)throw new Error("BaseProvider is abstract \u2014 use a concrete provider");this.name=t.name||"unknown",this.baseUrl=t.baseUrl||"",this.models=t.models||{},this.defaultModel=t.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(t){return this.models[t]||null}async chat(t,n,o={}){throw new Error(`${this.name}: chat() not implemented`)}async stream(t,n,o={}){throw new Error(`${this.name}: stream() not implemented`)}formatMessages(t){return{messages:t}}formatTools(t){return t}normalizeResponse(t){throw new Error(`${this.name}: normalizeResponse() not implemented`)}};cg.exports={BaseProvider:bd,readStreamErrorBody:iE}});var Ir=Q((LD,ug)=>{var Nr=class{buildRequestBody(t){throw new Error("buildRequestBody() not implemented")}getEndpoint(){throw new Error("getEndpoint() not implemented")}formatTools(t){return t}normalizeResponse(t){throw new Error("normalizeResponse() not implemented")}createStreamParser(t,n={}){throw new Error("createStreamParser() not implemented")}},Lr=class{constructor(t,n={}){this.onToken=t,this.callbacks=n,this.content="",this.buffer=""}feed(t){this.buffer+=t;let n=this.buffer.split(`
100
100
  `);this.buffer=n.pop()||"";for(let o of n){let s=this.parseLine(o);if(s?.done)return s}return{done:!1}}flush(){return this.buffer.trim()&&(this.parseLine(this.buffer),this.buffer=""),this.getResult()}parseLine(t){throw new Error("parseLine() not implemented")}getResult(){throw new Error("getResult() not implemented")}},Rc=class extends Lr{constructor(t,n={}){super(t,n),this.toolCallsMap={}}parseLine(t){let n=t.trim();if(!n||!n.startsWith("data: "))return{done:!1};let o=n.slice(6);if(o==="[DONE]")return{done:!0,result:this.getResult()};let s;try{s=JSON.parse(o)}catch{return{done:!1}}let r=s.choices?.[0]?.delta;if(!r)return{done:!1};if(r.content&&(this.onToken(r.content),this.content+=r.content),r.tool_calls)for(let i of r.tool_calls){let a;i.index!==void 0&&i.index!==null?a=i.index:i.id?a=`id:${i.id}`:a=0,this.toolCallsMap[a]||(this.toolCallsMap[a]={id:i.id||"",name:"",arguments:""}),i.id&&(this.toolCallsMap[a].id=i.id),i.function?.name&&(this.toolCallsMap[a].name+=i.function.name),i.function?.arguments&&(this.toolCallsMap[a].arguments+=i.function.arguments)}return{done:!1}}getResult(){return{content:this.content,tool_calls:Object.values(this.toolCallsMap).filter(t=>t.name).map(t=>({id:t.id||`call-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,function:{name:t.name,arguments:t.arguments}}))}}},Cc=class extends Nr{getEndpoint(){return"/chat/completions"}buildRequestBody({model:t,messages:n,tools:o,maxTokens:s,temperature:r,stream:i}){let a={model:t,messages:n,max_tokens:s,temperature:r};return i&&(a.stream=!0),o&&o.length>0&&(a.tools=o),a}normalizeResponse(t){let n=t.choices?.[0]?.message||{},o=(n.tool_calls||[]).map(s=>({id:s.id,function:{name:s.function.name,arguments:s.function.arguments}}));return{content:n.content||"",tool_calls:o}}createStreamParser(t,n={}){return new Rc(t,n)}},Ac=class extends Lr{constructor(t,n={}){super(t,n),this.toolUses=[],this.currentToolIndex=-1}parseLine(t){let n=t.trim();if(!n.startsWith("data: "))return{done:!1};let o=n.slice(6),s;try{s=JSON.parse(o)}catch{return{done:!1}}switch(s.type){case"content_block_start":{let r=s.content_block;r?.type==="tool_use"&&(this.currentToolIndex=this.toolUses.length,this.toolUses.push({id:r.id,name:r.name,inputJson:""}));break}case"content_block_delta":{let r=s.delta;r?.type==="text_delta"&&r.text&&(this.onToken(r.text),this.content+=r.text),r?.type==="input_json_delta"&&r.partial_json!==void 0&&this.currentToolIndex>=0&&(this.toolUses[this.currentToolIndex].inputJson+=r.partial_json);break}case"content_block_stop":this.currentToolIndex=-1;break;case"message_stop":return{done:!0,result:this.getResult()}}return{done:!1}}getResult(){return{content:this.content,tool_calls:this.toolUses.filter(t=>t.name).map(t=>{let n={};if(t.inputJson)try{n=JSON.parse(t.inputJson)}catch{n=t.inputJson}return{id:t.id||`anthropic-${Date.now()}`,function:{name:t.name,arguments:n}}})}}},wd="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->",Oc=class extends Nr{getEndpoint(){return"/messages"}buildRequestBody({model:t,messages:n,tools:o,maxTokens:s,temperature:r,stream:i,extra:a}){let c={model:t,messages:n,max_tokens:s,temperature:r};if(i&&(c.stream=!0),a?.system){let u=a.system,d=u.indexOf(wd);if(d!==-1){let f=u.slice(0,d).trimEnd(),p=u.slice(d+wd.length).trimStart();c.system=[{type:"text",text:f},{type:"text",text:p,cache_control:{type:"ephemeral"}}]}else c.system=u}return o&&o.length>0&&(c.tools=o),c}formatTools(t){return!t||t.length===0?[]:t.map(n=>({name:n.function.name,description:n.function.description||"",input_schema:n.function.parameters||{type:"object",properties:{}}}))}normalizeResponse(t){let n="",o=[];for(let s of t.content||[])s.type==="text"?n+=s.text:s.type==="tool_use"&&o.push({id:s.id,function:{name:s.name,arguments:s.input}});return{content:n,tool_calls:o}}createStreamParser(t,n={}){return new Ac(t,n)}};function lg(e){if(e!==null&&typeof e=="object")return e;if(typeof e!="string")return e||{};try{return JSON.parse(e)}catch{}let t=e.replace(/,\s*([}\]])/g,"$1");t=t.replace(/([^\\])\n/g,"$1\\n");try{return JSON.parse(t)}catch{}return{}}var Mc=class extends Lr{constructor(t,n={}){super(t,n),this.toolCalls=[],this.onThinkingToken=n.onThinkingToken||(()=>{})}parseLine(t){if(!t.trim())return{done:!1};let n;try{n=JSON.parse(t)}catch{return{done:!1}}return n.message?.thinking&&this.onThinkingToken(n.message.thinking),n.message?.content&&(this.onToken(n.message.content),this.content+=n.message.content),n.message?.tool_calls&&(this.toolCalls=this.toolCalls.concat(n.message.tool_calls)),n.done?{done:!0,result:this.getResult()}:{done:!1}}getResult(){return{content:this.content,tool_calls:this.toolCalls.map((t,n)=>({id:t.id||`ollama-${Date.now()}-${n}`,function:{name:t.function?.name||t.name||"unknown",arguments:lg(t.function?.arguments??t.arguments)}}))}}},Pc=class extends Nr{getEndpoint(){return"/api/chat"}buildRequestBody({model:t,messages:n,tools:o,maxTokens:s,temperature:r,stream:i,extra:a}){let c={model:t,messages:n,stream:i,options:{temperature:r,num_predict:s,repeat_penalty:a?.repeat_penalty??1.05}};return o&&o.length>0&&(c.tools=o),c}normalizeResponse(t){let n=t.message||{};return{content:n.content||"",tool_calls:(n.tool_calls||[]).map((o,s)=>({id:o.id||`ollama-${Date.now()}-${s}`,function:{name:o.function?.name||o.name||"unknown",arguments:lg(o.function?.arguments??o.arguments)}}))}}createStreamParser(t,n={}){return new Mc(t,n)}},aE=new Cc,cE=new Oc,lE=new Pc;ug.exports={ANTHROPIC_CACHE_BOUNDARY:wd,WireProtocol:Nr,StreamParser:Lr,OpenAICompatibleProtocol:Cc,AnthropicProtocol:Oc,OllamaChatProtocol:Pc,OpenAIStreamParser:Rc,AnthropicStreamParser:Ac,OllamaStreamParser:Mc,openaiProtocol:aE,anthropicProtocol:cE,ollamaProtocol:lE}});var fg=Q((ID,dg)=>{var Nc=require("axios"),uE=require("http"),dE=require("https"),{BaseProvider:fE,readStreamErrorBody:pE}=Fo(),{ollamaProtocol:Bo}=Ir(),Lc=new uE.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Ic=new dE.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),jc={"qwen3-coder:480b":{id:"qwen3-coder:480b",name:"Qwen3 Coder 480B",maxTokens:16384,contextWindow:131072,capability:"agentic",speed:"balanced",quality:98,recommendedFor:["coding","agentic","refactor"]},"qwen3-coder-next":{id:"qwen3-coder-next",name:"Qwen3 Coder Next",maxTokens:16384,contextWindow:262144,capability:"agentic",speed:"balanced",quality:97,recommendedFor:["coding","agentic","large-context"]},"devstral-2:123b":{id:"devstral-2:123b",name:"Devstral 2 123B",maxTokens:16384,contextWindow:131072,capability:"agentic",speed:"balanced",quality:94,recommendedFor:["coding","sysadmin","agentic"]},"devstral-small-2:24b":{id:"devstral-small-2:24b",name:"Devstral Small 2 24B",maxTokens:16384,contextWindow:131072,capability:"fast-coding",speed:"fast",quality:82,recommendedFor:["quick-fix","sysadmin","fallback"]},"minimax-m2.7:cloud":{id:"minimax-m2.7:cloud",name:"MiniMax M2.7 Cloud",maxTokens:16384,contextWindow:131072,capability:"general",speed:"balanced",quality:90,recommendedFor:["coding","reasoning"]},"kimi-k2.5":{id:"kimi-k2.5",name:"Kimi K2.5",maxTokens:16384,contextWindow:256e3,capability:"reasoning",speed:"balanced",quality:96,recommendedFor:["reasoning","large-context","review"]},"kimi-k2:1t":{id:"kimi-k2:1t",name:"Kimi K2 1T",maxTokens:16384,contextWindow:256e3,capability:"reasoning",speed:"deliberate",quality:99,recommendedFor:["reasoning","architecture","review"]},"kimi-k2-thinking":{id:"kimi-k2-thinking",name:"Kimi K2 Thinking",maxTokens:16384,contextWindow:256e3,capability:"reasoning",speed:"deliberate",quality:98,recommendedFor:["reasoning","debugging","review"]},"deepseek-v4-pro:cloud":{id:"deepseek-v4-pro:cloud",name:"DeepSeek V4 Pro",maxTokens:16384,contextWindow:1048576,capability:"general",speed:"balanced",quality:96,recommendedFor:["coding","reasoning","review"]},"deepseek-v4-flash:cloud":{id:"deepseek-v4-flash:cloud",name:"DeepSeek V4 Flash",maxTokens:16384,contextWindow:1048576,capability:"general",speed:"fast",quality:90,recommendedFor:["coding","quick-fix","fallback"]},"deepseek-v3.2":{id:"deepseek-v3.2",name:"DeepSeek V3.2",maxTokens:16384,contextWindow:131072,capability:"general",speed:"balanced",quality:94,recommendedFor:["coding","reasoning","fallback"]},"deepseek-v3.1:671b":{id:"deepseek-v3.1:671b",name:"DeepSeek V3.1 671B",maxTokens:16384,contextWindow:131072},"cogito-2.1:671b":{id:"cogito-2.1:671b",name:"Cogito 2.1 671B",maxTokens:16384,contextWindow:131072},"qwen3.5:397b-cloud":{id:"qwen3.5:397b-cloud",name:"Qwen3.5 397B Cloud",maxTokens:16384,contextWindow:262144,capability:"vision-language",speed:"balanced",quality:95,recommendedFor:["frontend","vision","large-context"]},"qwen3.5:397b":{id:"qwen3.5:397b",name:"Qwen3.5 397B",maxTokens:16384,contextWindow:262144},"qwen3.5:122b-a10b":{id:"qwen3.5:122b-a10b",name:"Qwen3.5 122B-A10B",maxTokens:16384,contextWindow:262144},"qwen3.5:35b-a3b":{id:"qwen3.5:35b-a3b",name:"Qwen3.5 35B-A3B",maxTokens:16384,contextWindow:262144,capability:"fast-coding",speed:"fast",quality:84,recommendedFor:["quick-fix","coding","fallback"]},"qwen3.5:27b":{id:"qwen3.5:27b",name:"Qwen3.5 27B",maxTokens:16384,contextWindow:262144},"qwen3-next:80b":{id:"qwen3-next:80b",name:"Qwen3 Next 80B",maxTokens:16384,contextWindow:131072,capability:"fast-coding",speed:"fast",quality:86,recommendedFor:["quick-fix","coding"]},"mistral-large-3:675b":{id:"mistral-large-3:675b",name:"Mistral Large 3 675B",maxTokens:16384,contextWindow:131072},"gpt-oss:120b":{id:"gpt-oss:120b",name:"GPT-OSS 120B",maxTokens:16384,contextWindow:131072,capability:"open-reasoning",speed:"balanced",quality:88,recommendedFor:["open-source","reasoning","coding"]},"minimax-m2.5":{id:"minimax-m2.5",name:"MiniMax M2.5",maxTokens:16384,contextWindow:131072},"glm-5:cloud":{id:"glm-5:cloud",name:"GLM 5 Cloud",maxTokens:16384,contextWindow:2e5},"glm-5":{id:"glm-5",name:"GLM 5",maxTokens:16384,contextWindow:2e5},"glm-4.6":{id:"glm-4.6",name:"GLM 4.6",maxTokens:16384,contextWindow:2e5},"glm-4.7":{id:"glm-4.7",name:"GLM 4.7",maxTokens:16384,contextWindow:128e3},"nemotron-3-super:cloud":{id:"nemotron-3-super:cloud",name:"Nemotron 3 Super Cloud",maxTokens:16384,contextWindow:262144},"qwen3.5:9b":{id:"qwen3.5:9b",name:"Qwen3.5 9B",maxTokens:8192,contextWindow:262144},"qwen3.5:4b":{id:"qwen3.5:4b",name:"Qwen3.5 4B",maxTokens:8192,contextWindow:262144},"qwen3.5:2b":{id:"qwen3.5:2b",name:"Qwen3.5 2B",maxTokens:8192,contextWindow:262144},"qwen3.5:0.8b":{id:"qwen3.5:0.8b",name:"Qwen3.5 0.8B",maxTokens:8192,contextWindow:262144},"gemma3:27b":{id:"gemma3:27b",name:"Gemma 3 27B",maxTokens:8192,contextWindow:131072},"gemma3:12b":{id:"gemma3:12b",name:"Gemma 3 12B",maxTokens:8192,contextWindow:131072},"gemma3:4b":{id:"gemma3:4b",name:"Gemma 3 4B",maxTokens:8192,contextWindow:131072},"ministral-3:14b":{id:"ministral-3:14b",name:"Ministral 3 14B",maxTokens:8192,contextWindow:131072,capability:"fast-coding",speed:"fast",quality:78,recommendedFor:["quick-fix","fallback"]},"ministral-3:8b":{id:"ministral-3:8b",name:"Ministral 3 8B",maxTokens:8192,contextWindow:131072,capability:"fast",speed:"very-fast",quality:72,recommendedFor:["quick-fix","fallback"]},"gemma4:e2b":{id:"gemma4:e2b",name:"Gemma 4 E2B",maxTokens:8192,contextWindow:131072},"gemma4:e4b":{id:"gemma4:e4b",name:"Gemma 4 E4B",maxTokens:8192,contextWindow:131072},"gemma4:26b-a4b":{id:"gemma4:26b-a4b",name:"Gemma 4 26B A4B",maxTokens:16384,contextWindow:262144},"gemma4:31b":{id:"gemma4:31b",name:"Gemma 4 31B",maxTokens:16384,contextWindow:262144},"gemma4:31b-cloud":{id:"gemma4:31b-cloud",name:"Gemma 4 31B Cloud",maxTokens:16384,contextWindow:262144},"gemini-3-flash-preview":{id:"gemini-3-flash-preview",name:"Gemini 3 Flash Preview",maxTokens:16384,contextWindow:131072}},_d={coding:["qwen3-coder:480b","qwen3-coder-next","devstral-2:123b","deepseek-v4-pro:cloud"],agentic:["qwen3-coder:480b","qwen3-coder-next","devstral-2:123b","deepseek-v4-pro:cloud"],reasoning:["kimi-k2:1t","kimi-k2-thinking","kimi-k2.5"],"large-context":["qwen3-coder-next","qwen3.5:397b-cloud","kimi-k2.5"],frontend:["qwen3.5:397b-cloud","qwen3-coder-next","qwen3-coder:480b"],"quick-fix":["devstral-small-2:24b","qwen3-next:80b","ministral-3:14b","deepseek-v4-flash:cloud"],fallback:["devstral-small-2:24b","deepseek-v4-flash:cloud","deepseek-v3.2","qwen3.5:35b-a3b"],"open-source":["qwen3-coder:480b","devstral-2:123b","gpt-oss:120b"]};function hE(e="coding",t=5){let n=_d[e]||_d.coding;return n.map(s=>jc[s]).filter(Boolean).concat(Object.values(jc).filter(s=>!n.includes(s.id)).filter(s=>(s.recommendedFor||[]).includes(e))).sort((s,r)=>(r.quality||0)-(s.quality||0)).slice(0,t)}var kd=class extends fE{constructor(t={}){super({name:"ollama",baseUrl:t.baseUrl||"https://ollama.com",models:t.models||jc,defaultModel:t.defaultModel||"qwen3-coder:480b",...t}),this.timeout=t.timeout||18e4,this.temperature=t.temperature??.2,this._discovered=!1}async discoverModels(){if(!this._discovered){if(this._discovered=!0,!process.stdout.isTTY){Nc.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Lc,httpsAgent:Ic}).then(t=>{let n=t.data?.models||[];for(let o of n){let s=(o.name||o.model||"").replace(/:latest$/,"");!s||this.models[s]||(this.models[s]={id:s,name:o.name||s,maxTokens:16384,contextWindow:131072})}}).catch(()=>{});return}try{let n=(await Nc.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Lc,httpsAgent:Ic})).data?.models||[];for(let o of n){let s=(o.name||o.model||"").replace(/:latest$/,"");!s||this.models[s]||(this.models[s]={id:s,name:o.name||s,maxTokens:16384,contextWindow:131072})}}catch{}}}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OLLAMA_API_KEY||null}_getHeaders(){let t=this.getApiKey();if(!t)throw new Error("OLLAMA_API_KEY not set");return{Authorization:`Bearer ${t}`}}_formatMessages(t){return t.map(n=>{if(Array.isArray(n.content)){let o=[],s=[];for(let i of n.content)i.type==="text"?o.push(i.text??""):i.type==="image"&&i.data&&s.push(i.data);let r={role:n.role,content:o.join(`
101
- `)};return s.length>0&&(r.images=s),n.tool_call_id&&(r.tool_call_id=n.tool_call_id),r}return n})}async chat(t,n,o={}){await this.discoverModels();let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||16384,a=Bo.buildRequestBody({model:s,messages:this._formatMessages(t),tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!1,extra:{repeat_penalty:o.repeat_penalty}}),c;try{c=await Nc.post(`${this.baseUrl}${Bo.getEndpoint()}`,a,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),httpAgent:Lc,httpsAgent:Ic})}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||u.message;throw new Error(`API Error${d}: ${f}`)}return Bo.normalizeResponse(c.data)}async stream(t,n,o={}){await this.discoverModels();let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||16384,a=o.onToken||(()=>{}),c=o.onThinkingToken||(()=>{}),u=Bo.buildRequestBody({model:s,messages:this._formatMessages(t),tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!0,extra:{repeat_penalty:o.repeat_penalty}}),d;try{d=await Nc.post(`${this.baseUrl}${Bo.getEndpoint()}`,u,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal,httpAgent:Lc,httpsAgent:Ic})}catch(p){if(p.name==="CanceledError"||p.name==="AbortError"||p.code==="ERR_CANCELED")throw p;let h=p.response?.status?` [HTTP ${p.response.status}]`:"",m=await pE(p,$=>$?.error),g=new Error(`API Error${h}: ${m}`);throw g.code=p.code||(p.response?.status?`HTTP_${p.response.status}`:void 0),g}let f=Bo.createStreamParser(a,{onThinkingToken:c});return new Promise((p,h)=>{o.signal&&o.signal.addEventListener("abort",()=>{d.data.destroy(),h(new DOMException("The operation was aborted","AbortError"))},{once:!0}),d.data.on("data",m=>{let{done:g,result:$}=f.feed(m.toString());g&&p($)}),d.data.on("error",m=>{if(o.signal?.aborted)return;let g=new Error(`Stream error: ${m.message}`);g.code=m.code||m.name,h(g)}),d.data.on("end",()=>{p(f.flush())})})}normalizeResponse(t){return Bo.normalizeResponse(t)}};dg.exports={OllamaProvider:kd,OLLAMA_MODELS:jc,OLLAMA_USE_CASES:_d,getOllamaRecommendations:hE}});var vd=Q((jD,mg)=>{var pg=require("axios"),{BaseProvider:mE,readStreamErrorBody:gE}=Fo(),{openaiProtocol:Uo}=Ir(),hg={"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}},xd=class extends mE{constructor(t={}){super({name:"openai",baseUrl:t.baseUrl||"https://api.openai.com/v1",models:t.models||hg,defaultModel:t.defaultModel||"gpt-4o",...t}),this.timeout=t.timeout||18e4,this.temperature=t.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OPENAI_API_KEY||null}_getHeaders(){let t=this.getApiKey();if(!t)throw new Error("OPENAI_API_KEY not set");return{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(t){let n=[];for(let o of t){if(this._messageFormatCache.has(o)){n.push(this._messageFormatCache.get(o));continue}let s=this._getMessageCacheKey(o);if(this._messageStringCache.has(s)){let i=this._messageStringCache.get(s);this._messageFormatCache.set(o,i),n.push(i);continue}let r=this._formatSingleMessage(o);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(s,r),this._messageFormatCache.set(o,r),n.push(r)}return{messages:n}}_getMessageCacheKey(t){let n=t.role||"",o=typeof t.content=="string"?t.content.substring(0,100):"",s=t.tool_calls?t.tool_calls.length:0;return`${n}:${o.length}:${s}`}_formatSingleMessage(t){if(t.role==="assistant"&&t.tool_calls)return{role:"assistant",content:t.content||null,tool_calls:t.tool_calls.map(n=>({id:n.id||`call-${Date.now()}`,type:"function",function:{name:n.function.name,arguments:typeof n.function.arguments=="string"?n.function.arguments:JSON.stringify(n.function.arguments)}}))};if(t.role==="tool"){let n;return Array.isArray(t.content)?n=t.content.filter(s=>s.type==="text").map(s=>s.text).join(`
102
- `)||JSON.stringify(t.content):n=typeof t.content=="string"?t.content:JSON.stringify(t.content),{role:"tool",content:n,tool_call_id:t.tool_call_id}}if(t.role==="user"&&Array.isArray(t.content)){let n=[];for(let o of t.content)if(o.type==="text")n.push({type:"text",text:o.text??""});else if(o.type==="image"&&o.data){let s=o.data.startsWith("data:")?o.data:`data:${o.media_type||"image/png"};base64,${o.data}`;n.push({type:"image_url",image_url:{url:s,detail:"auto"}})}return{role:"user",content:n}}return{role:t.role,content:t.content}}prepareRequestBody(t,n={}){return t}async chat(t,n,o={}){let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||16384,{messages:a}=this.formatMessages(t),c=this.prepareRequestBody(Uo.buildRequestBody({model:s,messages:a,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!1}),o),u;try{u=await pg.post(`${this.baseUrl}${Uo.getEndpoint()}`,c,{timeout:o.timeout||this.timeout,headers:this._getHeaders()})}catch(d){if(d.name==="CanceledError"||d.name==="AbortError"||d.code==="ERR_CANCELED")throw d;let f=d.response?.status?` [HTTP ${d.response.status}]`:"",p=d.response?.data?.error?.message||d.response?.data?.error||d.message;throw new Error(`API Error${f}: ${p}`)}return Uo.normalizeResponse(u.data)}async stream(t,n,o={}){let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||16384,a=o.onToken||(()=>{}),{messages:c}=this.formatMessages(t),u=this.prepareRequestBody(Uo.buildRequestBody({model:s,messages:c,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!0}),o),d;try{d=await pg.post(`${this.baseUrl}${Uo.getEndpoint()}`,u,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal})}catch(p){if(p.name==="CanceledError"||p.name==="AbortError"||p.code==="ERR_CANCELED")throw p;let h=p.response?.status?` [HTTP ${p.response.status}]`:"",m=await gE(p,g=>g?.error?.message||g?.error);throw new Error(`API Error${h}: ${m}`)}let f=Uo.createStreamParser(a);return new Promise((p,h)=>{o.signal&&o.signal.addEventListener("abort",()=>{d.data.destroy(),h(new DOMException("The operation was aborted","AbortError"))},{once:!0}),d.data.on("data",m=>{let{done:g,result:$}=f.feed(m.toString());g&&p($)}),d.data.on("error",m=>{o.signal?.aborted||h(new Error(`Stream error: ${m.message}`))}),d.data.on("end",()=>{p(f.flush())})})}normalizeResponse(t){return Uo.normalizeResponse(t)}};mg.exports={OpenAIProvider:xd,OPENAI_MODELS:hg}});var $g=Q((DD,yg)=>{var{OpenAIProvider:yE}=vd(),gg={"deepseek-v4-flash":{id:"deepseek-v4-flash",name:"DeepSeek V4 Flash",maxTokens:16384,contextWindow:1048576,capability:"fast-coding",speed:"fast",quality:90,recommendedFor:["coding","quick-fix","fallback"]},"deepseek-v4-pro":{id:"deepseek-v4-pro",name:"DeepSeek V4 Pro",maxTokens:16384,contextWindow:1048576,capability:"agentic",speed:"balanced",quality:96,recommendedFor:["coding","agentic","reasoning","review"]}},Sd=class extends yE{constructor(t={}){super({name:"deepseek",baseUrl:t.baseUrl||process.env.DEEPSEEK_BASE_URL||"https://api.deepseek.com",models:t.models||gg,defaultModel:t.defaultModel||"deepseek-v4-flash",...t})}getApiKey(){return process.env.DEEPSEEK_API_KEY||null}_getHeaders(){let t=this.getApiKey();if(!t)throw new Error("DEEPSEEK_API_KEY not set");return{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}}prepareRequestBody(t,n={}){let o=n.thinking||process.env.DEEPSEEK_THINKING;return{...t,thinking:o!==void 0?{type:o}:{type:"disabled"}}}};yg.exports={DeepSeekProvider:Sd,DEEPSEEK_MODELS:gg}});var kg=Q((qD,_g)=>{var bg=require("axios"),{BaseProvider:$E,readStreamErrorBody:bE}=Fo(),{anthropicProtocol:lo}=Ir(),wg={"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}},wE="2023-06-01",Ed=class extends $E{constructor(t={}){super({name:"anthropic",baseUrl:t.baseUrl||"https://api.anthropic.com/v1",models:t.models||wg,defaultModel:t.defaultModel||"claude-sonnet",...t}),this.timeout=t.timeout||18e4,this.temperature=t.temperature??.2,this.apiVersion=t.apiVersion||wE}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.ANTHROPIC_API_KEY||null}_getHeaders(){let t=this.getApiKey();if(!t)throw new Error("ANTHROPIC_API_KEY not set");return{"x-api-key":t,"anthropic-version":this.apiVersion,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(t){let n="",o=[];for(let s of t){if(s.role==="system"){n+=(n?`
101
+ `)};return s.length>0&&(r.images=s),n.tool_call_id&&(r.tool_call_id=n.tool_call_id),r}return n})}async chat(t,n,o={}){await this.discoverModels();let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||16384,a=Bo.buildRequestBody({model:s,messages:this._formatMessages(t),tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!1,extra:{repeat_penalty:o.repeat_penalty}}),c;try{c=await Nc.post(`${this.baseUrl}${Bo.getEndpoint()}`,a,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),httpAgent:Lc,httpsAgent:Ic})}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||u.message;throw new Error(`API Error${d}: ${f}`)}return Bo.normalizeResponse(c.data)}async stream(t,n,o={}){await this.discoverModels();let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||16384,a=o.onToken||(()=>{}),c=o.onThinkingToken||(()=>{}),u=Bo.buildRequestBody({model:s,messages:this._formatMessages(t),tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!0,extra:{repeat_penalty:o.repeat_penalty}}),d;try{d=await Nc.post(`${this.baseUrl}${Bo.getEndpoint()}`,u,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal,httpAgent:Lc,httpsAgent:Ic})}catch(p){if(p.name==="CanceledError"||p.name==="AbortError"||p.code==="ERR_CANCELED")throw p;let h=p.response?.status?` [HTTP ${p.response.status}]`:"",m=await pE(p,y=>y?.error),g=new Error(`API Error${h}: ${m}`);throw g.code=p.code||(p.response?.status?`HTTP_${p.response.status}`:void 0),g}let f=Bo.createStreamParser(a,{onThinkingToken:c});return new Promise((p,h)=>{o.signal&&o.signal.addEventListener("abort",()=>{d.data.destroy(),h(new DOMException("The operation was aborted","AbortError"))},{once:!0}),d.data.on("data",m=>{let{done:g,result:y}=f.feed(m.toString());g&&p(y)}),d.data.on("error",m=>{if(o.signal?.aborted)return;let g=new Error(`Stream error: ${m.message}`);g.code=m.code||m.name,h(g)}),d.data.on("end",()=>{p(f.flush())})})}normalizeResponse(t){return Bo.normalizeResponse(t)}};dg.exports={OllamaProvider:kd,OLLAMA_MODELS:jc,OLLAMA_USE_CASES:_d,getOllamaRecommendations:hE}});var vd=Q((jD,mg)=>{var pg=require("axios"),{BaseProvider:mE,readStreamErrorBody:gE}=Fo(),{openaiProtocol:Uo}=Ir(),hg={"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}},xd=class extends mE{constructor(t={}){super({name:"openai",baseUrl:t.baseUrl||"https://api.openai.com/v1",models:t.models||hg,defaultModel:t.defaultModel||"gpt-4o",...t}),this.timeout=t.timeout||18e4,this.temperature=t.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OPENAI_API_KEY||null}_getHeaders(){let t=this.getApiKey();if(!t)throw new Error("OPENAI_API_KEY not set");return{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(t){let n=[];for(let o of t){if(this._messageFormatCache.has(o)){n.push(this._messageFormatCache.get(o));continue}let s=this._getMessageCacheKey(o);if(this._messageStringCache.has(s)){let i=this._messageStringCache.get(s);this._messageFormatCache.set(o,i),n.push(i);continue}let r=this._formatSingleMessage(o);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(s,r),this._messageFormatCache.set(o,r),n.push(r)}return{messages:n}}_getMessageCacheKey(t){let n=t.role||"",o=typeof t.content=="string"?t.content.substring(0,100):"",s=t.tool_calls?t.tool_calls.length:0;return`${n}:${o.length}:${s}`}_formatSingleMessage(t){if(t.role==="assistant"&&t.tool_calls)return{role:"assistant",content:t.content||null,tool_calls:t.tool_calls.map(n=>({id:n.id||`call-${Date.now()}`,type:"function",function:{name:n.function.name,arguments:typeof n.function.arguments=="string"?n.function.arguments:JSON.stringify(n.function.arguments)}}))};if(t.role==="tool"){let n;return Array.isArray(t.content)?n=t.content.filter(s=>s.type==="text").map(s=>s.text).join(`
102
+ `)||JSON.stringify(t.content):n=typeof t.content=="string"?t.content:JSON.stringify(t.content),{role:"tool",content:n,tool_call_id:t.tool_call_id}}if(t.role==="user"&&Array.isArray(t.content)){let n=[];for(let o of t.content)if(o.type==="text")n.push({type:"text",text:o.text??""});else if(o.type==="image"&&o.data){let s=o.data.startsWith("data:")?o.data:`data:${o.media_type||"image/png"};base64,${o.data}`;n.push({type:"image_url",image_url:{url:s,detail:"auto"}})}return{role:"user",content:n}}return{role:t.role,content:t.content}}prepareRequestBody(t,n={}){return t}async chat(t,n,o={}){let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||16384,{messages:a}=this.formatMessages(t),c=this.prepareRequestBody(Uo.buildRequestBody({model:s,messages:a,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!1}),o),u;try{u=await pg.post(`${this.baseUrl}${Uo.getEndpoint()}`,c,{timeout:o.timeout||this.timeout,headers:this._getHeaders()})}catch(d){if(d.name==="CanceledError"||d.name==="AbortError"||d.code==="ERR_CANCELED")throw d;let f=d.response?.status?` [HTTP ${d.response.status}]`:"",p=d.response?.data?.error?.message||d.response?.data?.error||d.message;throw new Error(`API Error${f}: ${p}`)}return Uo.normalizeResponse(u.data)}async stream(t,n,o={}){let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||16384,a=o.onToken||(()=>{}),{messages:c}=this.formatMessages(t),u=this.prepareRequestBody(Uo.buildRequestBody({model:s,messages:c,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!0}),o),d;try{d=await pg.post(`${this.baseUrl}${Uo.getEndpoint()}`,u,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal})}catch(p){if(p.name==="CanceledError"||p.name==="AbortError"||p.code==="ERR_CANCELED")throw p;let h=p.response?.status?` [HTTP ${p.response.status}]`:"",m=await gE(p,g=>g?.error?.message||g?.error);throw new Error(`API Error${h}: ${m}`)}let f=Uo.createStreamParser(a);return new Promise((p,h)=>{o.signal&&o.signal.addEventListener("abort",()=>{d.data.destroy(),h(new DOMException("The operation was aborted","AbortError"))},{once:!0}),d.data.on("data",m=>{let{done:g,result:y}=f.feed(m.toString());g&&p(y)}),d.data.on("error",m=>{o.signal?.aborted||h(new Error(`Stream error: ${m.message}`))}),d.data.on("end",()=>{p(f.flush())})})}normalizeResponse(t){return Uo.normalizeResponse(t)}};mg.exports={OpenAIProvider:xd,OPENAI_MODELS:hg}});var $g=Q((DD,yg)=>{var{OpenAIProvider:yE}=vd(),gg={"deepseek-v4-flash":{id:"deepseek-v4-flash",name:"DeepSeek V4 Flash",maxTokens:16384,contextWindow:1048576,capability:"fast-coding",speed:"fast",quality:90,recommendedFor:["coding","quick-fix","fallback"]},"deepseek-v4-pro":{id:"deepseek-v4-pro",name:"DeepSeek V4 Pro",maxTokens:16384,contextWindow:1048576,capability:"agentic",speed:"balanced",quality:96,recommendedFor:["coding","agentic","reasoning","review"]}},Sd=class extends yE{constructor(t={}){super({name:"deepseek",baseUrl:t.baseUrl||process.env.DEEPSEEK_BASE_URL||"https://api.deepseek.com",models:t.models||gg,defaultModel:t.defaultModel||"deepseek-v4-flash",...t})}getApiKey(){return process.env.DEEPSEEK_API_KEY||null}_getHeaders(){let t=this.getApiKey();if(!t)throw new Error("DEEPSEEK_API_KEY not set");return{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}}prepareRequestBody(t,n={}){let o=n.thinking||process.env.DEEPSEEK_THINKING;return{...t,thinking:o!==void 0?{type:o}:{type:"disabled"}}}};yg.exports={DeepSeekProvider:Sd,DEEPSEEK_MODELS:gg}});var kg=Q((qD,_g)=>{var bg=require("axios"),{BaseProvider:$E,readStreamErrorBody:bE}=Fo(),{anthropicProtocol:lo}=Ir(),wg={"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}},wE="2023-06-01",Ed=class extends $E{constructor(t={}){super({name:"anthropic",baseUrl:t.baseUrl||"https://api.anthropic.com/v1",models:t.models||wg,defaultModel:t.defaultModel||"claude-sonnet",...t}),this.timeout=t.timeout||18e4,this.temperature=t.temperature??.2,this.apiVersion=t.apiVersion||wE}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.ANTHROPIC_API_KEY||null}_getHeaders(){let t=this.getApiKey();if(!t)throw new Error("ANTHROPIC_API_KEY not set");return{"x-api-key":t,"anthropic-version":this.apiVersion,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(t){let n="",o=[];for(let s of t){if(s.role==="system"){n+=(n?`
103
103
 
104
- `:"")+s.content;continue}if(s.role!=="system"&&s.role!=="tool"&&this._messageFormatCache.has(s)){o.push(this._messageFormatCache.get(s));continue}let r=this._formatSingleMessage(s,o);if(r){if(s.role!=="system"&&s.role!=="tool"&&this._messageStringCache.size<this._maxCacheSize){let i=this._getMessageCacheKey(s);this._messageStringCache.set(i,r),this._messageFormatCache.set(s,r)}o.push(r)}}for(let s=o.length-1;s>0;s--)o[s].role==="user"&&o[s-1].role==="user"&&o.splice(s,0,{role:"assistant",content:[{type:"text",text:"[continuing]"}]});return{messages:o,system:n}}_getMessageCacheKey(t){let n=t.role||"",o=typeof t.content=="string"?t.content.substring(0,100):"",s=t.tool_calls?t.tool_calls.length:0;return`${n}:${o.length}:${s}`}_formatSingleMessage(t,n=[]){if(t.role==="assistant"){let o=[];if(t.content&&o.push({type:"text",text:t.content}),t.tool_calls)for(let s of t.tool_calls)o.push({type:"tool_use",id:s.id||`toolu-${Date.now()}`,name:s.function.name,input:typeof s.function.arguments=="string"?JSON.parse(s.function.arguments||"{}"):s.function.arguments||{}});return{role:"assistant",content:o.length>0?o:[{type:"text",text:""}]}}if(t.role==="tool"){let o=n[n.length-1],s;if(Array.isArray(t.content)){let i=[];for(let a of t.content)a.type==="text"?i.push({type:"text",text:a.text??""}):a.type==="image"&&a.data&&i.push({type:"image",source:{type:"base64",media_type:a.media_type||"image/png",data:a.data}});s=i}else s=typeof t.content=="string"?t.content:JSON.stringify(t.content);let r={type:"tool_result",tool_use_id:t.tool_call_id,content:s};return o&&o.role==="user"&&Array.isArray(o.content)&&o.content[0]?.type==="tool_result"?(o.content.push(r),null):{role:"user",content:[r]}}if(Array.isArray(t.content)){let o=[];for(let s of t.content)s.type==="text"?o.push({type:"text",text:s.text??""}):s.type==="image"&&s.data&&o.push({type:"image",source:{type:"base64",media_type:s.media_type||"image/png",data:s.data}});return{role:"user",content:o}}return{role:"user",content:t.content}}formatTools(t){return lo.formatTools(t)}_resolveModelId(t){return this.getModel(t)?.id||t}async chat(t,n,o={}){let s=o.model||this.defaultModel,r=this._resolveModelId(s),i=this.getModel(s),a=o.maxTokens||i?.maxTokens||8192,{messages:c,system:u}=this.formatMessages(t),d=this.formatTools(n),f=lo.buildRequestBody({model:r,messages:c,tools:d,maxTokens:a,temperature:o.temperature??this.temperature,stream:!1,extra:{system:u}}),p;try{p=await bg.post(`${this.baseUrl}${lo.getEndpoint()}`,f,{timeout:o.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 lo.normalizeResponse(p.data)}async stream(t,n,o={}){let s=o.model||this.defaultModel,r=this._resolveModelId(s),i=this.getModel(s),a=o.maxTokens||i?.maxTokens||8192,c=o.onToken||(()=>{}),{messages:u,system:d}=this.formatMessages(t),f=this.formatTools(n),p=lo.buildRequestBody({model:r,messages:u,tools:f,maxTokens:a,temperature:o.temperature??this.temperature,stream:!0,extra:{system:d}}),h;try{h=await bg.post(`${this.baseUrl}${lo.getEndpoint()}`,p,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal})}catch(g){if(g.name==="CanceledError"||g.name==="AbortError"||g.code==="ERR_CANCELED")throw g;let $=g.response?.status?` [HTTP ${g.response.status}]`:"",b=await bE(g,x=>x?.error?.message||x?.error);throw new Error(`API Error${$}: ${b}`)}let m=lo.createStreamParser(c);return new Promise((g,$)=>{o.signal&&o.signal.addEventListener("abort",()=>{h.data.destroy(),$(new DOMException("The operation was aborted","AbortError"))},{once:!0}),h.data.on("data",b=>{let{done:x,result:_}=m.feed(b.toString());x&&g(_)}),h.data.on("error",b=>{o.signal?.aborted||$(new Error(`Stream error: ${b.message}`))}),h.data.on("end",()=>{g(m.flush())})})}normalizeResponse(t){return lo.normalizeResponse(t)}};_g.exports={AnthropicProvider:Ed,ANTHROPIC_MODELS:wg}});var Eg=Q((FD,Sg)=>{var xg=require("axios"),{BaseProvider:_E,readStreamErrorBody:kE}=Fo(),{openaiProtocol:Wo}=Ir(),vg={"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}},Td=class extends _E{constructor(t={}){super({name:"gemini",baseUrl:t.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:t.models||vg,defaultModel:t.defaultModel||"gemini-2.5-flash",...t}),this.timeout=t.timeout||18e4,this.temperature=t.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||null}_getHeaders(){let t=this.getApiKey();if(!t)throw new Error("GEMINI_API_KEY not set");return{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(t){let n=[];for(let o of t){if(this._messageFormatCache.has(o)){n.push(this._messageFormatCache.get(o));continue}let s=this._getMessageCacheKey(o);if(this._messageStringCache.has(s)){let i=this._messageStringCache.get(s);this._messageFormatCache.set(o,i),n.push(i);continue}let r=this._formatSingleMessage(o);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(s,r),this._messageFormatCache.set(o,r),n.push(r)}return{messages:n}}_getMessageCacheKey(t){let n=t.role||"",o=typeof t.content=="string"?t.content.substring(0,100):"",s=t.tool_calls?t.tool_calls.length:0;return`${n}:${o.length}:${s}`}_formatSingleMessage(t){if(t.role==="assistant"&&t.tool_calls)return{role:"assistant",content:t.content||"",tool_calls:t.tool_calls.map(n=>({id:n.id||`call-${Date.now()}`,type:"function",function:{name:n.function.name,arguments:typeof n.function.arguments=="string"?n.function.arguments:JSON.stringify(n.function.arguments)}}))};if(t.role==="tool")return{role:"tool",content:typeof t.content=="string"?t.content:JSON.stringify(t.content),tool_call_id:t.tool_call_id};if(t.role==="user"&&Array.isArray(t.content)){let n=[];for(let o of t.content)if(o.type==="text")n.push({type:"text",text:o.text??""});else if(o.type==="image"&&o.data){let s=o.data.startsWith("data:")?o.data:`data:${o.media_type||"image/png"};base64,${o.data}`;n.push({type:"image_url",image_url:{url:s,detail:"auto"}})}return{role:"user",content:n}}return{role:t.role,content:t.content}}async chat(t,n,o={}){let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||8192,{messages:a}=this.formatMessages(t),c=Wo.buildRequestBody({model:s,messages:a,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!1}),u;try{u=await xg.post(`${this.baseUrl}${Wo.getEndpoint()}`,c,{timeout:o.timeout||this.timeout,headers:this._getHeaders()})}catch(d){if(d.name==="CanceledError"||d.name==="AbortError"||d.code==="ERR_CANCELED")throw d;let f=d.response?.status?` [HTTP ${d.response.status}]`:"",p=d.response?.data?.error?.message||d.response?.data?.error||d.message;throw new Error(`API Error${f}: ${p}`)}return Wo.normalizeResponse(u.data)}async stream(t,n,o={}){let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||8192,a=o.onToken||(()=>{}),{messages:c}=this.formatMessages(t),u=Wo.buildRequestBody({model:s,messages:c,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!0}),d;try{d=await xg.post(`${this.baseUrl}${Wo.getEndpoint()}`,u,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal})}catch(p){if(p.name==="CanceledError"||p.name==="AbortError"||p.code==="ERR_CANCELED")throw p;let h=p.response?.status?` [HTTP ${p.response.status}]`:"",m=await kE(p,g=>g?.error?.message||g?.error);throw new Error(`API Error${h}: ${m}`)}let f=Wo.createStreamParser(a);return new Promise((p,h)=>{o.signal&&o.signal.addEventListener("abort",()=>{d.data.destroy(),h(new DOMException("The operation was aborted","AbortError"))},{once:!0}),d.data.on("data",m=>{let{done:g,result:$}=f.feed(m.toString());g&&p($)}),d.data.on("error",m=>{o.signal?.aborted||h(new Error(`Stream error: ${m.message}`))}),d.data.on("end",()=>{p(f.flush())})})}normalizeResponse(t){return Wo.normalizeResponse(t)}};Sg.exports={GeminiProvider:Td,GEMINI_MODELS:vg}});var Cg=Q((BD,Rg)=>{var Dc=require("axios"),{BaseProvider:xE,readStreamErrorBody:vE}=Fo(),{ollamaProtocol:Ho}=Ir(),Tg="http://localhost:11434",Rd=class extends xE{constructor(t={}){super({name:"local",baseUrl:t.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||Tg,models:t.models||{},defaultModel:t.defaultModel||null,...t}),this.timeout=t.timeout||3e5,this.temperature=t.temperature??.2,this._modelsLoaded=!1}isConfigured(){return!0}async loadModels(){if(this._modelsLoaded)return this.models;try{let n=(await Dc.get(`${this.baseUrl}/api/tags`,{timeout:5e3})).data?.models||[];this.models={};for(let o of n){let s=o.name||o.model;if(!s)continue;let r=s.replace(/:latest$/,""),i=32768;try{let a=await Dc.post(`${this.baseUrl}/api/show`,{name:s},{timeout:5e3}),c=a.data?.model_info||a.data?.details||{};i=c["general.context_length"]||c["llama.context_length"]||this._parseContextFromModelfile(a.data?.modelfile)||32768}catch{}this.models[r]={id:r,name:o.name,maxTokens:Math.min(8192,Math.floor(i*.1)),contextWindow:i}}!this.defaultModel&&Object.keys(this.models).length>0&&(this.defaultModel=Object.keys(this.models)[0]),this._modelsLoaded=!0}catch{this.models={},this._modelsLoaded=!1}return this.models}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}_formatMessages(t){return t.map(n=>{if(n.role==="user"&&Array.isArray(n.content)){let o=[],s=[];for(let i of n.content)i.type==="text"?o.push(i.text??""):i.type==="image"&&i.data&&s.push(i.data);let r={role:"user",content:o.join(`
104
+ `:"")+s.content;continue}if(s.role!=="system"&&s.role!=="tool"&&this._messageFormatCache.has(s)){o.push(this._messageFormatCache.get(s));continue}let r=this._formatSingleMessage(s,o);if(r){if(s.role!=="system"&&s.role!=="tool"&&this._messageStringCache.size<this._maxCacheSize){let i=this._getMessageCacheKey(s);this._messageStringCache.set(i,r),this._messageFormatCache.set(s,r)}o.push(r)}}for(let s=o.length-1;s>0;s--)o[s].role==="user"&&o[s-1].role==="user"&&o.splice(s,0,{role:"assistant",content:[{type:"text",text:"[continuing]"}]});return{messages:o,system:n}}_getMessageCacheKey(t){let n=t.role||"",o=typeof t.content=="string"?t.content.substring(0,100):"",s=t.tool_calls?t.tool_calls.length:0;return`${n}:${o.length}:${s}`}_formatSingleMessage(t,n=[]){if(t.role==="assistant"){let o=[];if(t.content&&o.push({type:"text",text:t.content}),t.tool_calls)for(let s of t.tool_calls)o.push({type:"tool_use",id:s.id||`toolu-${Date.now()}`,name:s.function.name,input:typeof s.function.arguments=="string"?JSON.parse(s.function.arguments||"{}"):s.function.arguments||{}});return{role:"assistant",content:o.length>0?o:[{type:"text",text:""}]}}if(t.role==="tool"){let o=n[n.length-1],s;if(Array.isArray(t.content)){let i=[];for(let a of t.content)a.type==="text"?i.push({type:"text",text:a.text??""}):a.type==="image"&&a.data&&i.push({type:"image",source:{type:"base64",media_type:a.media_type||"image/png",data:a.data}});s=i}else s=typeof t.content=="string"?t.content:JSON.stringify(t.content);let r={type:"tool_result",tool_use_id:t.tool_call_id,content:s};return o&&o.role==="user"&&Array.isArray(o.content)&&o.content[0]?.type==="tool_result"?(o.content.push(r),null):{role:"user",content:[r]}}if(Array.isArray(t.content)){let o=[];for(let s of t.content)s.type==="text"?o.push({type:"text",text:s.text??""}):s.type==="image"&&s.data&&o.push({type:"image",source:{type:"base64",media_type:s.media_type||"image/png",data:s.data}});return{role:"user",content:o}}return{role:"user",content:t.content}}formatTools(t){return lo.formatTools(t)}_resolveModelId(t){return this.getModel(t)?.id||t}async chat(t,n,o={}){let s=o.model||this.defaultModel,r=this._resolveModelId(s),i=this.getModel(s),a=o.maxTokens||i?.maxTokens||8192,{messages:c,system:u}=this.formatMessages(t),d=this.formatTools(n),f=lo.buildRequestBody({model:r,messages:c,tools:d,maxTokens:a,temperature:o.temperature??this.temperature,stream:!1,extra:{system:u}}),p;try{p=await bg.post(`${this.baseUrl}${lo.getEndpoint()}`,f,{timeout:o.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 lo.normalizeResponse(p.data)}async stream(t,n,o={}){let s=o.model||this.defaultModel,r=this._resolveModelId(s),i=this.getModel(s),a=o.maxTokens||i?.maxTokens||8192,c=o.onToken||(()=>{}),{messages:u,system:d}=this.formatMessages(t),f=this.formatTools(n),p=lo.buildRequestBody({model:r,messages:u,tools:f,maxTokens:a,temperature:o.temperature??this.temperature,stream:!0,extra:{system:d}}),h;try{h=await bg.post(`${this.baseUrl}${lo.getEndpoint()}`,p,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal})}catch(g){if(g.name==="CanceledError"||g.name==="AbortError"||g.code==="ERR_CANCELED")throw g;let y=g.response?.status?` [HTTP ${g.response.status}]`:"",b=await bE(g,x=>x?.error?.message||x?.error);throw new Error(`API Error${y}: ${b}`)}let m=lo.createStreamParser(c);return new Promise((g,y)=>{o.signal&&o.signal.addEventListener("abort",()=>{h.data.destroy(),y(new DOMException("The operation was aborted","AbortError"))},{once:!0}),h.data.on("data",b=>{let{done:x,result:_}=m.feed(b.toString());x&&g(_)}),h.data.on("error",b=>{o.signal?.aborted||y(new Error(`Stream error: ${b.message}`))}),h.data.on("end",()=>{g(m.flush())})})}normalizeResponse(t){return lo.normalizeResponse(t)}};_g.exports={AnthropicProvider:Ed,ANTHROPIC_MODELS:wg}});var Eg=Q((FD,Sg)=>{var xg=require("axios"),{BaseProvider:_E,readStreamErrorBody:kE}=Fo(),{openaiProtocol:Wo}=Ir(),vg={"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}},Td=class extends _E{constructor(t={}){super({name:"gemini",baseUrl:t.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:t.models||vg,defaultModel:t.defaultModel||"gemini-2.5-flash",...t}),this.timeout=t.timeout||18e4,this.temperature=t.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||null}_getHeaders(){let t=this.getApiKey();if(!t)throw new Error("GEMINI_API_KEY not set");return{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(t){let n=[];for(let o of t){if(this._messageFormatCache.has(o)){n.push(this._messageFormatCache.get(o));continue}let s=this._getMessageCacheKey(o);if(this._messageStringCache.has(s)){let i=this._messageStringCache.get(s);this._messageFormatCache.set(o,i),n.push(i);continue}let r=this._formatSingleMessage(o);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(s,r),this._messageFormatCache.set(o,r),n.push(r)}return{messages:n}}_getMessageCacheKey(t){let n=t.role||"",o=typeof t.content=="string"?t.content.substring(0,100):"",s=t.tool_calls?t.tool_calls.length:0;return`${n}:${o.length}:${s}`}_formatSingleMessage(t){if(t.role==="assistant"&&t.tool_calls)return{role:"assistant",content:t.content||"",tool_calls:t.tool_calls.map(n=>({id:n.id||`call-${Date.now()}`,type:"function",function:{name:n.function.name,arguments:typeof n.function.arguments=="string"?n.function.arguments:JSON.stringify(n.function.arguments)}}))};if(t.role==="tool")return{role:"tool",content:typeof t.content=="string"?t.content:JSON.stringify(t.content),tool_call_id:t.tool_call_id};if(t.role==="user"&&Array.isArray(t.content)){let n=[];for(let o of t.content)if(o.type==="text")n.push({type:"text",text:o.text??""});else if(o.type==="image"&&o.data){let s=o.data.startsWith("data:")?o.data:`data:${o.media_type||"image/png"};base64,${o.data}`;n.push({type:"image_url",image_url:{url:s,detail:"auto"}})}return{role:"user",content:n}}return{role:t.role,content:t.content}}async chat(t,n,o={}){let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||8192,{messages:a}=this.formatMessages(t),c=Wo.buildRequestBody({model:s,messages:a,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!1}),u;try{u=await xg.post(`${this.baseUrl}${Wo.getEndpoint()}`,c,{timeout:o.timeout||this.timeout,headers:this._getHeaders()})}catch(d){if(d.name==="CanceledError"||d.name==="AbortError"||d.code==="ERR_CANCELED")throw d;let f=d.response?.status?` [HTTP ${d.response.status}]`:"",p=d.response?.data?.error?.message||d.response?.data?.error||d.message;throw new Error(`API Error${f}: ${p}`)}return Wo.normalizeResponse(u.data)}async stream(t,n,o={}){let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||8192,a=o.onToken||(()=>{}),{messages:c}=this.formatMessages(t),u=Wo.buildRequestBody({model:s,messages:c,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!0}),d;try{d=await xg.post(`${this.baseUrl}${Wo.getEndpoint()}`,u,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal})}catch(p){if(p.name==="CanceledError"||p.name==="AbortError"||p.code==="ERR_CANCELED")throw p;let h=p.response?.status?` [HTTP ${p.response.status}]`:"",m=await kE(p,g=>g?.error?.message||g?.error);throw new Error(`API Error${h}: ${m}`)}let f=Wo.createStreamParser(a);return new Promise((p,h)=>{o.signal&&o.signal.addEventListener("abort",()=>{d.data.destroy(),h(new DOMException("The operation was aborted","AbortError"))},{once:!0}),d.data.on("data",m=>{let{done:g,result:y}=f.feed(m.toString());g&&p(y)}),d.data.on("error",m=>{o.signal?.aborted||h(new Error(`Stream error: ${m.message}`))}),d.data.on("end",()=>{p(f.flush())})})}normalizeResponse(t){return Wo.normalizeResponse(t)}};Sg.exports={GeminiProvider:Td,GEMINI_MODELS:vg}});var Cg=Q((BD,Rg)=>{var Dc=require("axios"),{BaseProvider:xE,readStreamErrorBody:vE}=Fo(),{ollamaProtocol:Ho}=Ir(),Tg="http://localhost:11434",Rd=class extends xE{constructor(t={}){super({name:"local",baseUrl:t.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||Tg,models:t.models||{},defaultModel:t.defaultModel||null,...t}),this.timeout=t.timeout||3e5,this.temperature=t.temperature??.2,this._modelsLoaded=!1}isConfigured(){return!0}async loadModels(){if(this._modelsLoaded)return this.models;try{let n=(await Dc.get(`${this.baseUrl}/api/tags`,{timeout:5e3})).data?.models||[];this.models={};for(let o of n){let s=o.name||o.model;if(!s)continue;let r=s.replace(/:latest$/,""),i=32768;try{let a=await Dc.post(`${this.baseUrl}/api/show`,{name:s},{timeout:5e3}),c=a.data?.model_info||a.data?.details||{};i=c["general.context_length"]||c["llama.context_length"]||this._parseContextFromModelfile(a.data?.modelfile)||32768}catch{}this.models[r]={id:r,name:o.name,maxTokens:Math.min(8192,Math.floor(i*.1)),contextWindow:i}}!this.defaultModel&&Object.keys(this.models).length>0&&(this.defaultModel=Object.keys(this.models)[0]),this._modelsLoaded=!0}catch{this.models={},this._modelsLoaded=!1}return this.models}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}_formatMessages(t){return t.map(n=>{if(n.role==="user"&&Array.isArray(n.content)){let o=[],s=[];for(let i of n.content)i.type==="text"?o.push(i.text??""):i.type==="image"&&i.data&&s.push(i.data);let r={role:"user",content:o.join(`
105
105
  `)};return s.length>0&&(r.images=s),r}return n})}async chat(t,n,o={}){this._modelsLoaded||await this.loadModels();let s=o.model||this.defaultModel;if(!s)throw new Error("No local model available. Is Ollama running?");let r=Ho.buildRequestBody({model:s,messages:this._formatMessages(t),tools:n,maxTokens:o.maxTokens||8192,temperature:o.temperature??this.temperature,stream:!1}),i;try{i=await Dc.post(`${this.baseUrl}${Ho.getEndpoint()}`,r,{timeout:o.timeout||this.timeout})}catch(a){if(a.name==="CanceledError"||a.name==="AbortError"||a.code==="ERR_CANCELED")throw a;let c=a.response?.status?` [HTTP ${a.response.status}]`:"",u=a.response?.data?.error||a.message;throw new Error(`API Error${c}: ${u}`)}return Ho.normalizeResponse(i.data)}async stream(t,n,o={}){this._modelsLoaded||await this.loadModels();let s=o.model||this.defaultModel;if(!s)throw new Error("No local model available. Is Ollama running?");let r=o.onToken||(()=>{}),i=Ho.buildRequestBody({model:s,messages:this._formatMessages(t),tools:n,maxTokens:o.maxTokens||8192,temperature:o.temperature??this.temperature,stream:!0}),a;try{a=await Dc.post(`${this.baseUrl}${Ho.getEndpoint()}`,i,{timeout:o.timeout||this.timeout,responseType:"stream",signal:o.signal})}catch(u){if(u.name==="CanceledError"||u.name==="AbortError"||u.code==="ERR_CANCELED")throw u;let d=u.response?.status?` [HTTP ${u.response.status}]`:"",f=await vE(u,p=>p?.error);throw new Error(`API Error${d}: ${f}`)}let c=Ho.createStreamParser(r);return new Promise((u,d)=>{o.signal&&o.signal.addEventListener("abort",()=>{a.data.destroy(),d(new DOMException("The operation was aborted","AbortError"))},{once:!0}),a.data.on("data",f=>{let{done:p,result:h}=c.feed(f.toString());p&&u(h)}),a.data.on("error",f=>{o.signal?.aborted||d(new Error(`Stream error: ${f.message}`))}),a.data.on("end",()=>{u(c.flush())})})}normalizeResponse(t){return Ho.normalizeResponse(t)}_parseContextFromModelfile(t){if(!t)return null;let n=t.match(/PARAMETER\s+num_ctx\s+(\d+)/i);return n?parseInt(n[1],10):null}};Rg.exports={LocalProvider:Rd,DEFAULT_LOCAL_URL:Tg}});var Hs=Q((UD,Og)=>{"use strict";var On=require("fs"),Ag=require("path");function SE(e){if(!e||isNaN(e))return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function EE(e){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}catch{let t=Date.now()+e;for(;Date.now()<t;);}}function TE(e,t){let n=Ag.dirname(e),o=Ag.join(n,`.nex-tmp.${process.pid}.${Date.now()}`);try{On.existsSync(n)||On.mkdirSync(n,{recursive:!0,mode:448}),On.writeFileSync(o,t,{encoding:"utf-8",mode:384}),On.renameSync(o,e)}catch(s){try{On.unlinkSync(o)}catch{}throw s}}function RE(e,t,{timeout:n=5e3,retryMs:o=50}={}){let s=e+".lock",r=Date.now()+n;for(;;){let i=-1;try{i=On.openSync(s,"wx"),On.writeSync(i,Buffer.from(String(process.pid))),On.closeSync(i),i=-1;try{return t()}finally{try{On.unlinkSync(s)}catch{}}}catch(a){if(i!==-1)try{On.closeSync(i)}catch{}if(a.code!=="EEXIST")throw a;try{let c=On.readFileSync(s,"utf-8").trim(),u=parseInt(c,10);if(!SE(u)){try{On.unlinkSync(s)}catch{}continue}}catch(c){if(c.code&&c.code!=="ENOENT")throw c;continue}if(Date.now()>=r){try{On.unlinkSync(s)}catch{}return t()}EE(o)}}}Og.exports={atomicWrite:TE,withFileLockSync:RE}});var os=Q((WD,Dg)=>{var jr=require("fs"),Cd=require("path"),{T:qc}=ln(),{atomicWrite:CE,withFileLockSync:AE}=Hs(),Mg={openai:{"gpt-4o":{input:2.5,output:10},"gpt-4o-mini":{input:.15,output:.6},"gpt-4.1":{input:2,output:8},"gpt-4.1-mini":{input:.4,output:1.6},"gpt-4.1-nano":{input:.1,output:.4},o1:{input:15,output:60},o3:{input:10,output:40},"o3-mini":{input:1.1,output:4.4},"o4-mini":{input:1.1,output:4.4}},deepseek:{"deepseek-v4-flash":{input:.14,output:.28},"deepseek-v4-pro":{input:.435,output:.87}},anthropic:{"claude-sonnet":{input:3,output:15},"claude-opus":{input:5,output:25},"claude-haiku":{input:.8,output:4},"claude-sonnet-4-5":{input:3,output:15},"claude-sonnet-4":{input:3,output:15}},gemini:{"gemini-2.5-pro":{input:1.25,output:10},"gemini-2.5-flash":{input:.15,output:.6},"gemini-2.0-flash":{input:.1,output:.4},"gemini-2.0-flash-lite":{input:.075,output:.3}},ollama:{"qwen3-coder:480b":{input:0,output:0},"qwen3-coder-next":{input:0,output:0},"devstral-2:123b":{input:0,output:0},"devstral-small-2:24b":{input:0,output:0},"kimi-k2.5":{input:0,output:0},"kimi-k2:1t":{input:0,output:0},"deepseek-v4-pro:cloud":{input:0,output:0},"deepseek-v4-flash:cloud":{input:0,output:0},"deepseek-v3.2":{input:0,output:0},"minimax-m2.5":{input:0,output:0},"glm-5":{input:0,output:0},"glm-4.7":{input:0,output:0},"gpt-oss:120b":{input:0,output:0}},local:{}},OE=new Set(["ollama","local"]),ME=new Set(["openai","deepseek","anthropic","gemini"]),Bc=[],uo={},Fc=new Set;function Ci(e){let t=String(e||"").toLowerCase();return OE.has(t)?{provider:t,tier:"affordable",paid:!1,label:t==="local"?"local open model":"open-model path",detail:t==="local"?"runs through a local Ollama server with no per-token API charge":"recommended affordable path for open coding models"}:ME.has(t)?{provider:t,tier:"premium",paid:!0,label:"premium paid provider",detail:"may incur per-token API charges; use /budget to cap spend"}:{provider:t,tier:"unknown",paid:null,label:"cost unknown",detail:"pricing is not known to nex-code"}}function PE(e){return Ci(e).tier==="affordable"}function NE(e){return Ci(e).tier==="premium"}function LE(e){let t=Ci(e);return`${t.label} \u2014 ${t.detail}`}function IE(e,t,n,o,s=0){if(Bc.push({provider:e,model:t,input:n,output:o,cacheRead:s}),uo[e]!==void 0){let r=Ig(e);if(!r.allowed)process.stderr.write(`${qc.yellow}\u26A0 Budget limit reached for ${e}: $${r.spent.toFixed(2)} / $${r.limit.toFixed(2)}${qc.reset}
106
106
  `);else if(r.limit>0&&r.spent>=r.limit*.8){let i=`${e}:${r.limit}:80`;Fc.has(i)||(Fc.add(i),process.stderr.write(`${qc.yellow}Budget warning for ${e}: $${r.spent.toFixed(2)} / $${r.limit.toFixed(2)} used. Use /budget ${e} <amount> to raise the cap or /model ollama:<model> for the affordable path.${qc.reset}
107
107
  `))}}}function Ad(e,t){let n=Mg[e];return n?n[t]||{input:0,output:0}:{input:0,output:0}}function Pg(e){let t=Ad(e.provider,e.model);return(e.input*t.input+e.output*t.output)/1e6}function Ng(){let e={};for(let i of Bc){let a=`${i.provider}:${i.model}`;e[a]||(e[a]={provider:i.provider,model:i.model,requests:0,input:0,output:0,cacheRead:0}),e[a].requests++,e[a].input+=i.input,e[a].output+=i.output,e[a].cacheRead+=i.cacheRead||0}let t=Object.values(e).map(i=>({...i,cost:Pg(i)})),n=t.reduce((i,a)=>i+a.cost,0),o=t.reduce((i,a)=>i+a.input,0),s=t.reduce((i,a)=>i+a.output,0),r=t.reduce((i,a)=>i+(a.cacheRead||0),0);return{totalCost:n,totalInput:o,totalOutput:s,totalCacheRead:r,breakdown:t}}function jE(){let{totalCost:e,totalInput:t,totalOutput:n,breakdown:o}=Ng();if(o.length===0)return"No token usage recorded this session.";let s=[];s.push("Session Token Usage:"),s.push("");for(let r of o){let i=r.cost>0?`$${r.cost.toFixed(4)}`:"free",a=Ci(r.provider);s.push(` ${r.provider}:${r.model}`),s.push(` Path: ${a.label}`),s.push(` Input: ${r.input.toLocaleString()} tokens`),s.push(` Output: ${r.output.toLocaleString()} tokens`),s.push(` Cost: ${i}`)}return s.push(""),s.push(` Total: ${t.toLocaleString()} in + ${n.toLocaleString()} out = $${e.toFixed(4)}`),s.join(`
@@ -225,12 +225,12 @@ ${ee.bold}${ee.cyan} Diff: ${e}${ee.reset}`);let s=Oi(t,n),r=[];if(s.forEach((c
225
225
  ${ee.bold}${ee.cyan} File exists \u2014 showing changes: ${e}${ee.reset}`);let o=Oi(t,n),s=0;for(let i of o)i.type!=="same"&&s++;if(s===0){console.log(`${ee.gray} (identical content)${ee.reset}`);return}let r=0;for(let i of o){if(r>=30){console.log(`${ee.gray} ...(${s-r} more changes)${ee.reset}`);break}switch(i.type){case"remove":console.log(`${ee.red} - ${i.line}${ee.reset}`),r++;break;case"add":console.log(`${ee.green} + ${i.line}${ee.reset}`),r++;break;default:r>0&&console.log(`${ee.gray} ${i.line}${ee.reset}`)}}console.log()}function wT(e,t){console.log(`
226
226
  ${ee.bold}${ee.cyan} New file: ${e}${ee.reset}`);let n=t.split(`
227
227
  `),o=n.slice(0,20);for(let s of o)console.log(`${ee.green} + ${s}${ee.reset}`);n.length>20&&console.log(`${ee.gray} ...+${n.length-20} more lines${ee.reset}`),console.log()}async function _T(e){return yT()?!0:gT(` ${e}?`)}function kT(e,t,n,o){let s=o||process.stdout.columns||80,r=Math.floor((s-3)/2);console.log(`
228
- ${ee.bold}${ee.cyan} Side-by-side: ${e}${ee.reset}`),console.log(` ${ee.dim}${"\u2500".repeat(r)}\u252C${"\u2500".repeat(r)}${ee.reset}`);let i=Oi(t,n),a=[],c=0;for(;c<i.length;)if(i[c].type==="same")a.push({left:i[c].line,right:i[c].line,type:"same"}),c++;else if(i[c].type==="remove"){let 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 $=0;$<g;$++)a.push({left:$<h.length?h[$]:"",right:$<m.length?m[$]:"",type:"changed"})}else i[c].type==="add"&&(a.push({left:"",right:i[c].line,type:"changed"}),c++);let u=a.map((h,m)=>h.type!=="same"?m:-1).filter(h=>h>=0);if(u.length===0){console.log(` ${ee.gray}(no changes)${ee.reset}`);return}let d=Math.max(0,u[0]-2),f=Math.min(a.length,u[u.length-1]+3),p=(h,m)=>{let g=h.replace(/\x1b\[[0-9;]*m/g,"");return g.length>=m?h.substring(0,m):h+" ".repeat(m-g.length)};d>0&&console.log(` ${ee.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${ee.reset}`);for(let h=d;h<f;h++){let m=a[h];if(m.type==="same")console.log(` ${ee.gray}${p(m.left,r)}${ee.reset}\u2502${ee.gray}${p(m.right,r)}${ee.reset}`);else{let g=m.left?`${ee.red}${p(m.left,r)}${ee.reset}`:`${p("",r)}`,$=m.right?`${ee.green}${p(m.right,r)}${ee.reset}`:`${p("",r)}`;console.log(` ${g}\u2502${$}`)}}f<a.length&&console.log(` ${ee.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${ee.reset}`),console.log(` ${ee.dim}${"\u2500".repeat(r)}\u2534${"\u2500".repeat(r)}${ee.reset}
228
+ ${ee.bold}${ee.cyan} Side-by-side: ${e}${ee.reset}`),console.log(` ${ee.dim}${"\u2500".repeat(r)}\u252C${"\u2500".repeat(r)}${ee.reset}`);let i=Oi(t,n),a=[],c=0;for(;c<i.length;)if(i[c].type==="same")a.push({left:i[c].line,right:i[c].line,type:"same"}),c++;else if(i[c].type==="remove"){let 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 y=0;y<g;y++)a.push({left:y<h.length?h[y]:"",right:y<m.length?m[y]:"",type:"changed"})}else i[c].type==="add"&&(a.push({left:"",right:i[c].line,type:"changed"}),c++);let u=a.map((h,m)=>h.type!=="same"?m:-1).filter(h=>h>=0);if(u.length===0){console.log(` ${ee.gray}(no changes)${ee.reset}`);return}let d=Math.max(0,u[0]-2),f=Math.min(a.length,u[u.length-1]+3),p=(h,m)=>{let g=h.replace(/\x1b\[[0-9;]*m/g,"");return g.length>=m?h.substring(0,m):h+" ".repeat(m-g.length)};d>0&&console.log(` ${ee.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${ee.reset}`);for(let h=d;h<f;h++){let m=a[h];if(m.type==="same")console.log(` ${ee.gray}${p(m.left,r)}${ee.reset}\u2502${ee.gray}${p(m.right,r)}${ee.reset}`);else{let g=m.left?`${ee.red}${p(m.left,r)}${ee.reset}`:`${p("",r)}`,y=m.right?`${ee.green}${p(m.right,r)}${ee.reset}`:`${p("",r)}`;console.log(` ${g}\u2502${y}`)}}f<a.length&&console.log(` ${ee.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${ee.reset}`),console.log(` ${ee.dim}${"\u2500".repeat(r)}\u2534${"\u2500".repeat(r)}${ee.reset}
229
229
  `)}function xT(e,t,n,o={}){let s=o.label||"Update",r=o.context||3,i=o.annotations||[],a=Hc.isAbsolute(e)?Hc.relative(process.cwd(),e):e,c=Oi(t,n),u=1,d=1;for(let O of c)O.type==="same"?(O.oldLine=u++,O.newLine=d++):O.type==="remove"?(O.oldLine=u++,O.newLine=null):(O.oldLine=null,O.newLine=d++);let f=0,p=0;for(let O of c)O.type==="add"?f++:O.type==="remove"&&p++;if(console.log(`
230
230
  ${ee.green}\u23FA${ee.reset} ${ee.bold}${s}(${a})${ee.reset}`),f===0&&p===0){console.log(` ${ee.dim}\u23BF (no changes)${ee.reset}
231
- `);return}let h=[];if(f>0&&h.push(`Added ${f} line${f!==1?"s":""}`),p>0&&h.push(`removed ${p} line${p!==1?"s":""}`),i.length>0){let O=i.filter(Z=>Z.severity==="error").length,L=i.filter(Z=>Z.severity==="warn").length,I=i.filter(Z=>Z.severity==="info").length,D=[];O>0&&D.push(`${ee.red}${O} error${O!==1?"s":""}${ee.dim}`),L>0&&D.push(`${ee.yellow}${L} warning${L!==1?"s":""}${ee.dim}`),I>0&&D.push(`${ee.cyan}${I} info${I!==1?"s":""}${ee.dim}`),h.push(`found ${D.join(", ")}`)}console.log(` ${ee.dim}\u23BF ${h.join(", ")}${ee.reset}`);let g=[];c.forEach((O,L)=>{O.type!=="same"&&g.push(L)});let $=[],b=null,x=null;for(let O of g){let L=Math.max(0,O-r),I=Math.min(c.length-1,O+r);b===null?(b=L,x=I):(L<=x+1||($.push([b,x]),b=L),x=I)}b!==null&&$.push([b,x]);let _=" ",E=process.stdout.columns||120;function S(O,L,I){let D=I.replace(/\x1b\[[0-9;]*m/g,""),Z=I+" ".repeat(Math.max(0,E-D.length));return`${O}${L}${Z}${ee.reset}`}for(let O=0;O<$.length;O++){O>0&&console.log(`${_}${ee.dim}\xB7\xB7\xB7${ee.reset}`);let[L,I]=$[O];for(let D=L;D<=I;D++){let Z=c[D],K=Z.newLine!=null?Z.newLine:Z.oldLine,X=String(K).padStart(4),Fe=Z.type!=="remove"?i.filter(Oe=>Oe.line===Z.newLine):[];Z.type==="remove"?console.log(S(Ld.diff_rem_bg,ee.red,`${_}${X} - ${Z.line}`)):Z.type==="add"?console.log(S(Ld.diff_add_bg,ee.green,`${_}${X} + ${Z.line}`)):console.log(`${_}${ee.dim}${X} ${ee.reset}${Z.line}`);for(let Oe of Fe){let V=ee.cyan,re="\u2139";Oe.severity==="error"?(V=ee.red,re="\u2716"):Oe.severity==="warn"&&(V=ee.yellow,re="\u26A0"),console.log(`${_} ${V}${re} ${Oe.message}${ee.reset}`)}}}console.log()}function vT(e,t,n={}){let o=Hc.isAbsolute(e)?Hc.relative(process.cwd(),e):e,s=t.split(`
231
+ `);return}let h=[];if(f>0&&h.push(`Added ${f} line${f!==1?"s":""}`),p>0&&h.push(`removed ${p} line${p!==1?"s":""}`),i.length>0){let O=i.filter(Z=>Z.severity==="error").length,L=i.filter(Z=>Z.severity==="warn").length,I=i.filter(Z=>Z.severity==="info").length,D=[];O>0&&D.push(`${ee.red}${O} error${O!==1?"s":""}${ee.dim}`),L>0&&D.push(`${ee.yellow}${L} warning${L!==1?"s":""}${ee.dim}`),I>0&&D.push(`${ee.cyan}${I} info${I!==1?"s":""}${ee.dim}`),h.push(`found ${D.join(", ")}`)}console.log(` ${ee.dim}\u23BF ${h.join(", ")}${ee.reset}`);let g=[];c.forEach((O,L)=>{O.type!=="same"&&g.push(L)});let y=[],b=null,x=null;for(let O of g){let L=Math.max(0,O-r),I=Math.min(c.length-1,O+r);b===null?(b=L,x=I):(L<=x+1||(y.push([b,x]),b=L),x=I)}b!==null&&y.push([b,x]);let _=" ",E=process.stdout.columns||120;function S(O,L,I){let D=I.replace(/\x1b\[[0-9;]*m/g,""),Z=I+" ".repeat(Math.max(0,E-D.length));return`${O}${L}${Z}${ee.reset}`}for(let O=0;O<y.length;O++){O>0&&console.log(`${_}${ee.dim}\xB7\xB7\xB7${ee.reset}`);let[L,I]=y[O];for(let D=L;D<=I;D++){let Z=c[D],K=Z.newLine!=null?Z.newLine:Z.oldLine,X=String(K).padStart(4),Fe=Z.type!=="remove"?i.filter(Oe=>Oe.line===Z.newLine):[];Z.type==="remove"?console.log(S(Ld.diff_rem_bg,ee.red,`${_}${X} - ${Z.line}`)):Z.type==="add"?console.log(S(Ld.diff_add_bg,ee.green,`${_}${X} + ${Z.line}`)):console.log(`${_}${ee.dim}${X} ${ee.reset}${Z.line}`);for(let Oe of Fe){let V=ee.cyan,re="\u2139";Oe.severity==="error"?(V=ee.red,re="\u2716"):Oe.severity==="warn"&&(V=ee.yellow,re="\u26A0"),console.log(`${_} ${V}${re} ${Oe.message}${ee.reset}`)}}}console.log()}function vT(e,t,n={}){let o=Hc.isAbsolute(e)?Hc.relative(process.cwd(),e):e,s=t.split(`
232
232
  `),r=n.annotations||[];console.log(`
233
- ${ee.green}\u23FA${ee.reset} ${ee.bold}Create(${o})${ee.reset}`);let i=[`${s.length} line${s.length!==1?"s":""}`];if(r.length>0){let f=r.filter(g=>g.severity==="error").length,p=r.filter(g=>g.severity==="warn").length,h=r.filter(g=>g.severity==="info").length,m=[];f>0&&m.push(`${ee.red}${f} error${f!==1?"s":""}${ee.dim}`),p>0&&m.push(`${ee.yellow}${p} warning${p!==1?"s":""}${ee.dim}`),h>0&&m.push(`${ee.cyan}${h} info${h!==1?"s":""}${ee.dim}`),i.push(`found ${m.join(", ")}`)}console.log(` ${ee.dim}\u23BF ${i.join(", ")}${ee.reset}`);let c=" ",u=process.stdout.columns||120,d=Math.min(s.length,20);for(let f=0;f<d;f++){let p=String(f+1).padStart(4),h=f+1,m=r.filter(x=>x.line===h),g=`${c}${p} + ${s[f]}`,$=g.replace(/\x1b\[[0-9;]*m/g,""),b=g+" ".repeat(Math.max(0,u-$.length));console.log(`${Ld.diff_add_bg}${ee.green}${b}${ee.reset}`);for(let x of m){let _=ee.cyan,E="\u2139";x.severity==="error"?(_=ee.red,E="\u2716"):x.severity==="warn"&&(_=ee.yellow,E="\u26A0"),console.log(`${c} ${_}${E} ${x.message}${ee.reset}`)}}s.length>20&&console.log(`${c}${ee.dim} ...+${s.length-20} more lines${ee.reset}`),console.log()}Xg.exports={diffLines:Oi,showEditDiff:$T,showWriteDiff:bT,showNewFilePreview:wT,confirmFileChange:_T,showSideBySideDiff:kT,showDiff:xT,showNewFile:vT}});var fo=Q((VD,Qg)=>{var Jg=require("util").promisify(require("child_process").exec),ST=require("util").promisify(require("child_process").execFile),{C:Nt}=dt();async function Id(e){try{let{stdout:t}=await Jg(e,{cwd:process.cwd(),timeout:3e4});return t.trim()}catch{return null}}async function Gc(...e){try{let{stdout:t}=await ST("git",e,{cwd:process.cwd(),timeout:3e4});return t.trim()}catch{return null}}async function ET(){return await Id("git rev-parse --is-inside-work-tree")==="true"}async function TT(){return await Id("git branch --show-current")}async function jd(){try{let{stdout:e}=await Jg("git status --porcelain",{cwd:process.cwd(),timeout:3e4});return!e||!e.trim()?[]:e.split(`
233
+ ${ee.green}\u23FA${ee.reset} ${ee.bold}Create(${o})${ee.reset}`);let i=[`${s.length} line${s.length!==1?"s":""}`];if(r.length>0){let f=r.filter(g=>g.severity==="error").length,p=r.filter(g=>g.severity==="warn").length,h=r.filter(g=>g.severity==="info").length,m=[];f>0&&m.push(`${ee.red}${f} error${f!==1?"s":""}${ee.dim}`),p>0&&m.push(`${ee.yellow}${p} warning${p!==1?"s":""}${ee.dim}`),h>0&&m.push(`${ee.cyan}${h} info${h!==1?"s":""}${ee.dim}`),i.push(`found ${m.join(", ")}`)}console.log(` ${ee.dim}\u23BF ${i.join(", ")}${ee.reset}`);let c=" ",u=process.stdout.columns||120,d=Math.min(s.length,20);for(let f=0;f<d;f++){let p=String(f+1).padStart(4),h=f+1,m=r.filter(x=>x.line===h),g=`${c}${p} + ${s[f]}`,y=g.replace(/\x1b\[[0-9;]*m/g,""),b=g+" ".repeat(Math.max(0,u-y.length));console.log(`${Ld.diff_add_bg}${ee.green}${b}${ee.reset}`);for(let x of m){let _=ee.cyan,E="\u2139";x.severity==="error"?(_=ee.red,E="\u2716"):x.severity==="warn"&&(_=ee.yellow,E="\u26A0"),console.log(`${c} ${_}${E} ${x.message}${ee.reset}`)}}s.length>20&&console.log(`${c}${ee.dim} ...+${s.length-20} more lines${ee.reset}`),console.log()}Xg.exports={diffLines:Oi,showEditDiff:$T,showWriteDiff:bT,showNewFilePreview:wT,confirmFileChange:_T,showSideBySideDiff:kT,showDiff:xT,showNewFile:vT}});var fo=Q((VD,Qg)=>{var Jg=require("util").promisify(require("child_process").exec),ST=require("util").promisify(require("child_process").execFile),{C:Nt}=dt();async function Id(e){try{let{stdout:t}=await Jg(e,{cwd:process.cwd(),timeout:3e4});return t.trim()}catch{return null}}async function Gc(...e){try{let{stdout:t}=await ST("git",e,{cwd:process.cwd(),timeout:3e4});return t.trim()}catch{return null}}async function ET(){return await Id("git rev-parse --is-inside-work-tree")==="true"}async function TT(){return await Id("git branch --show-current")}async function jd(){try{let{stdout:e}=await Jg("git status --porcelain",{cwd:process.cwd(),timeout:3e4});return!e||!e.trim()?[]:e.split(`
234
234
  `).filter(Boolean).map(t=>{let n=t.substring(0,2).trim(),o=t.substring(3);return{status:n,file:o}})}catch{return[]}}async function Yc(e=!1){return await Id(`git diff ${e?"--cached":""}`)||""}async function Dd(){return(await jd()).map(t=>t.file)}async function Zg(){let e=await Dd();if(e.length===0)return null;let t=await Yc(),o=await Yc(!0)||t,s=0,r=0;if(o){let d=o.split(`
235
235
  `);for(let f of d)f.startsWith("+")&&!f.startsWith("+++")&&s++,f.startsWith("-")&&!f.startsWith("---")&&r++}else s=e.length;let i="chore",a=e.join(" ").toLowerCase();a.includes("test")?i="test":a.includes("readme")||a.includes("doc")?i="docs":s>r*2?i="feat":r>s?i="refactor":i="fix";let c=e.slice(0,3).map(d=>d.split("/").pop());return{summary:`${i}: update ${c.join(", ")}${e.length>3?` (+${e.length-3} more)`:""}`,type:i,files:e,stats:{additions:s,deletions:r}}}async function RT(e){let n=`feat/${e.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await Gc("checkout","-b",n)!==null?n:null}async function CT(e){return await Gc("add","-A"),await Gc("commit","-m",e)?await Gc("rev-parse","--short","HEAD"):null}async function AT(){let e=await Zg();if(!e)return`${Nt.dim}No changes${Nt.reset}`;let t=[];t.push(`
236
236
  ${Nt.bold}${Nt.cyan}Git Diff Summary:${Nt.reset}`),t.push(` ${Nt.green}+${e.stats.additions}${Nt.reset} ${Nt.red}-${e.stats.deletions}${Nt.reset} in ${e.files.length} file(s)`),t.push(`
@@ -277,7 +277,7 @@ ${t.location}`).join(`
277
277
  `),o=[],s=e?`.${e.split(".").pop()}`:"";for(let r=0;r<n.length;r++){let i=n[r],a=r+1;for(let c of XR)c.regex.test(i)&&o.push({line:a,message:`Potential secret detected: ${c.category}`,severity:"error"});for(let c of VR)c.ext&&!c.ext.includes(s)||c.regex.test(i)&&o.push({line:a,message:c.message||`Found ${c.name}`,severity:c.severity||"warn"})}return n.length>500&&o.push({line:0,message:`Large file detected (${n.length} lines). Consider refactoring.`,severity:"info"}),o}function ZR(){let e=process.memoryUsage();return{rss:Math.round(e.rss/1024/1024*100)/100,heapUsed:Math.round(e.heapUsed/1024/1024*100)/100}}Fy.exports={runDiagnostics:JR,getMemoryUsage:ZR}});var Es=Q((aq,Qy)=>{var zo=require("fs").promises,_n=require("path"),{exec:QR}=require("util").promisify(require("child_process").exec),po=[],Qd=null,sl=!1,Zd=0,e1=6e4;function ef(e){return!(po.length===0||Qd!==e||Date.now()-Zd>e1)}async function Yy(e){if(!sl&&!ef(e)){sl=!0,Qd=e;try{try{let{stdout:o}=await QR("rg --files",{cwd:e,timeout:5e3});po=o.split(`
278
278
  `).filter(Boolean),Zd=Date.now(),sl=!1;return}catch{}let t=[],n=async(o,s)=>{let r;try{r=await zo.readdir(o,{withFileTypes:!0})}catch{return}for(let i of r){if(i.name==="node_modules"||i.name===".git"||i.name.startsWith("."))continue;let a=s?`${s}/${i.name}`:i.name;i.isDirectory()?await n(_n.join(o,i.name),a):t.push(a)}};await n(e,""),po=t,Zd=Date.now()}catch(t){console.error(`Index error: ${t.message}`)}finally{sl=!1}}}function Li(){return po}function t1(){return Qd}function n1(e){return po.filter(t=>_n.basename(t)===e)}function s1(e){let t=e.toLowerCase();return po.filter(n=>n.toLowerCase().includes(t)).slice(0,20)}function zy(e,t){let n=e.length,o=t.length;if(n===0)return o;if(o===0)return n;let s=Array.from({length:o+1},(r,i)=>i);for(let r=1;r<=n;r++){let i=r-1;s[0]=r;for(let a=1;a<=o;a++){let c=e[r-1]===t[a-1]?i:1+Math.min(s[a],s[a-1],i);i=s[a],s[a]=c}}return s[o]}function Ky(e,t){let n=e.toLowerCase(),o=t.toLowerCase();if(n===o)return 1e3;let s=n.split("/").filter(Boolean),r=o.split("/").filter(Boolean),i=0;for(let d=1;d<=Math.min(s.length,r.length)&&s[s.length-d]===r[r.length-d];d++)i=d;if(i>0&&i===r.length)return 500+i*100;let a=_n.basename(e).toLowerCase(),c=_n.basename(t).toLowerCase(),u=0;if(a===c)u+=80;else{let d=Math.max(a.length,c.length);if(d>0&&d<100){let p=1-zy(a,c)/d;p>=.6&&(u+=Math.round(p*50))}}if((n.includes(o)||o.includes(n))&&(u+=20),r.length>1){let d=new Set(s),f=0;for(let p of r)d.has(p)&&f++;u+=f*10}return i>0&&(u+=i*30),u}function o1(e,{limit:t=10,minScore:n=15}={}){if(!e||po.length===0)return[];let o=[];for(let s of po){let r=Ky(s,e);r>=n&&o.push({file:s,score:r})}return o.sort((s,r)=>r.score-s.score),o.slice(0,t)}var Jd=null,Uy=0,Wy=null,Xy=12e4,ol=null,Hy=0,Gy=null,Vy=new Set([".js",".ts",".jsx",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".rb"]);function Jy(e,t){let n=[],o=e.split(`
279
279
  `);for(let s=0;s<o.length;s++){let r=o[s],i=s+1;if([".js",".ts",".jsx",".tsx",".mjs",".cjs"].includes(t)){let a=r.match(/(?:export\s+)?(?:async\s+)?function\s+(\w+)/);a&&n.push({type:"function",name:a[1],line:i});let c=r.match(/(?:export\s+)?class\s+(\w+)/);c&&n.push({type:"class",name:c[1],line:i});let u=r.match(/(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?(?:\([^)]*\)|[\w$]+)\s*=>/);u&&n.push({type:"function",name:u[1],line:i});let d=r.match(/module\.exports\s*=\s*\{([^}]+)\}/);if(d){let p=d[1].split(",").map(h=>h.trim().split(":")[0].trim()).filter(Boolean);for(let h of p)/^\w+$/.test(h)&&n.push({type:"export",name:h,line:i})}let f=r.match(/(?:require\(['"]([^'"]+)['"]\)|from\s+['"]([^'"]+)['"])/);if(f){let p=f[1]||f[2];n.push({type:"import",name:p,line:i})}}if(t===".py"){let a=r.match(/^(?:async\s+)?def\s+(\w+)/);a&&n.push({type:"function",name:a[1],line:i});let c=r.match(/^class\s+(\w+)/);c&&n.push({type:"class",name:c[1],line:i});let u=r.match(/^(?:from\s+(\S+)\s+)?import\s+(\S+)/);u&&n.push({type:"import",name:u[1]||u[2],line:i})}if(t===".go"){let a=r.match(/^func\s+(?:\([^)]+\)\s+)?(\w+)/);a&&n.push({type:"function",name:a[1],line:i});let c=r.match(/^type\s+(\w+)\s+struct/);c&&n.push({type:"class",name:c[1],line:i})}}return n}async function rl(e){e=e||process.cwd();let t=_n.join(e,".nex","index","content-index.json"),n={};if(Jd&&Wy===e&&Date.now()-Uy<Xy)return Jd;try{let i=await zo.readFile(t,"utf-8");n=JSON.parse(i)}catch{n={files:{}}}let o=Li();(!ef(e)||o.length===0)&&(await Yy(e),o=Li());let s={files:{}},r=!1;for(let i of Li()){let a=_n.extname(i);if(!Vy.has(a))continue;let c=_n.join(e,i);try{let d=(await zo.stat(c)).mtimeMs;if(n.files[i]&&n.files[i].mtime===d){s.files[i]=n.files[i];continue}let f=await zo.readFile(c,"utf-8"),p=Jy(f,a);s.files[i]={defs:p,mtime:d},r=!0}catch{}}if(r){let i=_n.join(e,".nex","index");await zo.mkdir(i,{recursive:!0}),await zo.writeFile(t,JSON.stringify(s),"utf-8")}return Jd=s,Uy=Date.now(),Wy=e,s}async function r1(e,t,n){let o=await rl(n),s=[],r=e.toLowerCase();for(let[i,a]of Object.entries(o.files))for(let c of a.defs)t&&c.type!==t||c.name.toLowerCase().includes(r)&&s.push({file:i,type:c.type,name:c.name,line:c.line});return s.sort((i,a)=>{let c=i.name.toLowerCase()===r?0:1,u=a.name.toLowerCase()===r?0:1;if(c!==u)return c-u;let d=i.name.toLowerCase().startsWith(r)?0:1,f=a.name.toLowerCase().startsWith(r)?0:1;return d-f}),s.slice(0,50)}function i1(e,t,n){if(!t||!t.startsWith("."))return null;let o=_n.posix.dirname(e.replace(/\\/g,"/")),s=_n.posix.normalize(_n.posix.join(o==="."?"":o,t)),r=[];if(_n.posix.extname(s))r.push(s);else for(let a of Vy)r.push(`${s}${a}`),r.push(_n.posix.join(s,`index${a}`));for(let a of r)if(n.has(a))return a;return null}async function tf(e){if(e=e||process.cwd(),ol&&Gy===e&&Date.now()-Hy<Xy)return ol;let t=await rl(e),n=Li(),o=new Set(n.map(i=>i.replace(/\\/g,"/"))),s={},r={};for(let i of Object.keys(t.files||{})){let a=i.replace(/\\/g,"/"),c=Array.isArray(t.files[i]?.defs)?t.files[i].defs:[],u=[],d=new Set;for(let f of c){if(f.type!=="import")continue;let p=i1(a,f.name,o);!p||p===a||d.has(p)||(d.add(p),u.push(p),r[p]||(r[p]=[]),r[p].push(a))}s[a]=u}for(let[i,a]of Object.entries(r))r[i]=[...new Set(a)].sort();return ol={importsByFile:s,importedByFile:r},Hy=Date.now(),Gy=e,ol}async function a1(e,t,n=6){if(!e)return[];let o=await tf(t),s=String(e).replace(/\\/g,"/"),r=[...o.importsByFile[s]||[],...o.importedByFile[s]||[]];return[...new Set(r)].filter(i=>i!==s).slice(0,n)}async function c1(e,t=4){let n=await tf(e),o=new Map;for(let[s,r]of Object.entries(n.importsByFile||{}))o.set(s,(o.get(s)||0)+r.length);for(let[s,r]of Object.entries(n.importedByFile||{}))o.set(s,(o.get(s)||0)+r.length);return[...o.entries()].filter(([,s])=>s>0).sort((s,r)=>r[1]-s[1]||s[0].localeCompare(r[0])).slice(0,t).map(([s,r])=>`${s} (${r} links)`)}function Zy(e){return String(e).replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function l1(e,t){let n=Zy(t);return[new RegExp(`\\bfunction\\s+${n}\\b`),new RegExp(`\\bclass\\s+${n}\\b`),new RegExp(`\\b(?:const|let|var)\\s+${n}\\b\\s*=`),new RegExp(`\\bdef\\s+${n}\\b`),new RegExp(`\\btype\\s+${n}\\b\\s+struct\\b`),new RegExp(`\\bmodule\\.exports\\b[^\\n]*\\b${n}\\b`),new RegExp(`\\bexport\\b[^\\n]*\\b${n}\\b`)].some(s=>s.test(e))}async function u1(e,t,n={}){t=t||process.cwd();let{excludeFile:o=null,excludeLine:s=null,limit:r=6}=n;if(!e||typeof e!="string")return[];let i=await rl(t),a=Zy(e),c=new RegExp(`\\b${a}\\s*\\(`),u=new RegExp(`\\b${a}\\b`),d=[];for(let f of Object.keys(i.files||{})){let p=f.replace(/\\/g,"/");try{let h=_n.join(t,p),g=(await zo.readFile(h,"utf-8")).split(`
280
- `);for(let $=0;$<g.length;$++){let b=g[$],x=$+1;if(!u.test(b)||o&&p===o&&s===x||l1(b,e))continue;let _=(p===o?0:4)+(c.test(b)?3:1);d.push({file:p,line:x,context:b.trim(),score:_})}}catch{}}return d.sort((f,p)=>p.score!==f.score?p.score-f.score:f.file.localeCompare(p.file)||f.line-p.line),d.slice(0,r)}Qy.exports={refreshIndex:Yy,getFileIndex:Li,getIndexedCwd:t1,findFileInIndex:n1,searchIndex:s1,isIndexValid:ef,buildContentIndex:rl,searchContentIndex:r1,extractDefinitions:Jy,buildImportGraph:tf,getRelatedFiles:a1,summarizeModuleHubs:c1,findSymbolReferences:u1,smartSearch:o1,scorePathMatch:Ky,pathLevenshtein:zy}});var Ks=Q((cq,r$)=>{var il=require("fs"),ul=require("path"),dl=require("os"),{execFile:d1}=require("child_process"),{promisify:f1}=require("util"),nf=f1(d1),p1=ul.join(dl.homedir(),".nex","servers.json"),al=ul.join(dl.tmpdir(),"nex-ssh-sockets");function h1(){return ul.join(process.cwd(),".nex","servers.json")}function e$(){let e=o=>{if(!il.existsSync(o))return{};try{return JSON.parse(il.readFileSync(o,"utf-8"))}catch{return{}}},t=e(p1),n=e(h1());return{...t,...n}}function m1(e){let t=e$();if(t[e])return{...t[e],_name:e};if(/^[\w.-]+@[\w.-]+$/.test(e)||/[\w-]+\.[\w.-]+/.test(e)||e==="localhost"){let[s,r]=e.includes("@")?e.split("@"):[void 0,e];return{host:r,user:s}}let n=Object.keys(t),o=n.length?`Available profiles: ${n.join(", ")}`:"No profiles configured. Create .nex/servers.json (project) or ~/.nex/servers.json (global)";throw new Error(`Unknown server: "${e}". ${o}`)}function g1(){il.existsSync(al)||il.mkdirSync(al,{recursive:!0})}function t$(e){let t=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=yes","-o","ServerAliveInterval=30"];e.key&&t.push("-i",e.key.replace(/^~/,dl.homedir())),e.port&&Number(e.port)!==22&&t.push("-p",String(e.port)),g1();let n=e.user?`${e.user}@${e.host}`:e.host,o=ul.join(al,n.replace(/[@.:]/g,"_"));return t.push("-o","ControlMaster=auto","-o",`ControlPath=${o}`,"-o","ControlPersist=120"),t.push(n),{args:t,target:n}}function n$(e){let t=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=yes","-r"];return e.key&&t.push("-i",e.key.replace(/^~/,dl.homedir())),e.port&&Number(e.port)!==22&&t.push("-P",String(e.port)),t}async function cl(e,t,{timeout:n=3e4,sudo:o=!1}={}){let{args:s}=t$(e),r=o&&e.sudo?`sudo sh -c ${JSON.stringify(t)}`:t;try{let{stdout:i,stderr:a}=await nf("ssh",[...s,r],{timeout:n,maxBuffer:4194304});return{stdout:i||"",stderr:a||"",exitCode:0}}catch(i){let a=typeof i.code=="number"?i.code:1,c=(i.stderr||i.message||"").toString();return{stdout:(i.stdout||"").toString(),stderr:c,exitCode:a,error:fl(c,e)}}}async function y1(e,t,n,{timeout:o=12e4}={}){let s=n$(e),r=e.user?`${e.user}@${e.host}`:e.host;s.push(t,`${r}:${n}`);try{let{stdout:i,stderr:a}=await nf("scp",s,{timeout:o,maxBuffer:1048576});return i||a||`Uploaded ${t} \u2192 ${r}:${n}`}catch(i){let a=(i.stderr||i.message||"").toString();throw new Error(fl(a,e)||a)}}async function $1(e,t,n,{timeout:o=12e4}={}){let s=n$(e),r=e.user?`${e.user}@${e.host}`:e.host;s.push(`${r}:${t}`,n);try{let{stdout:i,stderr:a}=await nf("scp",s,{timeout:o,maxBuffer:1048576});return i||a||`Downloaded ${r}:${t} \u2192 ${n}`}catch(i){let a=(i.stderr||i.message||"").toString();throw new Error(fl(a,e)||a)}}function fl(e,t){if(!e)return"";if(/connection refused/i.test(e)){let n=t.port||22;return`${e}
280
+ `);for(let y=0;y<g.length;y++){let b=g[y],x=y+1;if(!u.test(b)||o&&p===o&&s===x||l1(b,e))continue;let _=(p===o?0:4)+(c.test(b)?3:1);d.push({file:p,line:x,context:b.trim(),score:_})}}catch{}}return d.sort((f,p)=>p.score!==f.score?p.score-f.score:f.file.localeCompare(p.file)||f.line-p.line),d.slice(0,r)}Qy.exports={refreshIndex:Yy,getFileIndex:Li,getIndexedCwd:t1,findFileInIndex:n1,searchIndex:s1,isIndexValid:ef,buildContentIndex:rl,searchContentIndex:r1,extractDefinitions:Jy,buildImportGraph:tf,getRelatedFiles:a1,summarizeModuleHubs:c1,findSymbolReferences:u1,smartSearch:o1,scorePathMatch:Ky,pathLevenshtein:zy}});var Ks=Q((cq,r$)=>{var il=require("fs"),ul=require("path"),dl=require("os"),{execFile:d1}=require("child_process"),{promisify:f1}=require("util"),nf=f1(d1),p1=ul.join(dl.homedir(),".nex","servers.json"),al=ul.join(dl.tmpdir(),"nex-ssh-sockets");function h1(){return ul.join(process.cwd(),".nex","servers.json")}function e$(){let e=o=>{if(!il.existsSync(o))return{};try{return JSON.parse(il.readFileSync(o,"utf-8"))}catch{return{}}},t=e(p1),n=e(h1());return{...t,...n}}function m1(e){let t=e$();if(t[e])return{...t[e],_name:e};if(/^[\w.-]+@[\w.-]+$/.test(e)||/[\w-]+\.[\w.-]+/.test(e)||e==="localhost"){let[s,r]=e.includes("@")?e.split("@"):[void 0,e];return{host:r,user:s}}let n=Object.keys(t),o=n.length?`Available profiles: ${n.join(", ")}`:"No profiles configured. Create .nex/servers.json (project) or ~/.nex/servers.json (global)";throw new Error(`Unknown server: "${e}". ${o}`)}function g1(){il.existsSync(al)||il.mkdirSync(al,{recursive:!0})}function t$(e){let t=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=yes","-o","ServerAliveInterval=30"];e.key&&t.push("-i",e.key.replace(/^~/,dl.homedir())),e.port&&Number(e.port)!==22&&t.push("-p",String(e.port)),g1();let n=e.user?`${e.user}@${e.host}`:e.host,o=ul.join(al,n.replace(/[@.:]/g,"_"));return t.push("-o","ControlMaster=auto","-o",`ControlPath=${o}`,"-o","ControlPersist=120"),t.push(n),{args:t,target:n}}function n$(e){let t=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=yes","-r"];return e.key&&t.push("-i",e.key.replace(/^~/,dl.homedir())),e.port&&Number(e.port)!==22&&t.push("-P",String(e.port)),t}async function cl(e,t,{timeout:n=3e4,sudo:o=!1}={}){let{args:s}=t$(e),r=o&&e.sudo?`sudo sh -c ${JSON.stringify(t)}`:t;try{let{stdout:i,stderr:a}=await nf("ssh",[...s,r],{timeout:n,maxBuffer:4194304});return{stdout:i||"",stderr:a||"",exitCode:0}}catch(i){let a=typeof i.code=="number"?i.code:1,c=(i.stderr||i.message||"").toString();return{stdout:(i.stdout||"").toString(),stderr:c,exitCode:a,error:fl(c,e)}}}async function y1(e,t,n,{timeout:o=12e4}={}){let s=n$(e),r=e.user?`${e.user}@${e.host}`:e.host;s.push(t,`${r}:${n}`);try{let{stdout:i,stderr:a}=await nf("scp",s,{timeout:o,maxBuffer:1048576});return i||a||`Uploaded ${t} \u2192 ${r}:${n}`}catch(i){let a=(i.stderr||i.message||"").toString();throw new Error(fl(a,e)||a)}}async function $1(e,t,n,{timeout:o=12e4}={}){let s=n$(e),r=e.user?`${e.user}@${e.host}`:e.host;s.push(`${r}:${t}`,n);try{let{stdout:i,stderr:a}=await nf("scp",s,{timeout:o,maxBuffer:1048576});return i||a||`Downloaded ${r}:${t} \u2192 ${n}`}catch(i){let a=(i.stderr||i.message||"").toString();throw new Error(fl(a,e)||a)}}function fl(e,t){if(!e)return"";if(/connection refused/i.test(e)){let n=t.port||22;return`${e}
281
281
  HINT: Connection refused on ${t.host}:${n}. Check: server is running, SSH service is active (systemctl status sshd), firewall allows port ${n} (firewall-cmd --list-ports).`}if(/permission denied/i.test(e)){let n=t.key?`key: ${t.key}`:"SSH agent";return`${e}
282
282
  HINT: Auth failed using ${n} as user "${t.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(e)?`${e}
283
283
  HINT: Cannot reach ${t.host}. Check: network connection, correct hostname/IP, DNS resolution.`:/host key verification failed/i.test(e)?`${e}
@@ -290,7 +290,7 @@ ${s.map(a=>` - ${a.file}`).join(`
290
290
  `,"utf-8")}a$.exports={loadDeployConfigs:i$,resolveDeployConfig:v1,saveDeployConfigs:S1,getDeployConfigPath:of}});var Fi=Q((uq,u$)=>{var{getActiveModel:E1,getActiveProviderName:T1}=ft(),ji={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},Di={"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"},qi={ollama:"full",openai:"full",anthropic:"full",gemini:"full",local:"essential"},Ts={};function l$(){try{let e=require("fs"),n=require("path").join(process.cwd(),".nex","config.json");e.existsSync(n)&&(Ts=JSON.parse(e.readFileSync(n,"utf-8")).toolTiers||{})}catch{Ts={}}}l$();function af(){let t=E1()?.id,n=T1();return t&&Ts[t]?Ts[t]:n&&Ts[`${n}:*`]?Ts[`${n}:*`]:t&&Di[t]?Di[t]:n&&qi[n]?qi[n]:"full"}var R1=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"]),c$={anthropic:"strict",openai:"strict",gemini:"strict",ollama:"fuzzy",local:"fuzzy"};function C1(e,t){return e&&(R1.has(e)||e.startsWith("claude-"))?"strict":t&&c$[t]?c$[t]:"fuzzy"}function A1(e,t){return e&&Ts[e]?Ts[e]:t&&Ts[`${t}:*`]?Ts[`${t}:*`]:e&&Di[e]?Di[e]:t&&qi[t]?qi[t]:"full"}function O1(e,t){let n=t||af();if(n==="full"||!ji[n])return e;let o=new Set(ji[n]);return e.filter(s=>o.has(s.function.name))}function M1(){let e=af(),t=ji[e]?ji[e].length:"all";return{tier:e,toolCount:t}}u$.exports={filterToolsForModel:O1,getActiveTier:af,getModelTier:A1,getEditMode:C1,getTierInfo:M1,TIERS:ji,MODEL_TIERS:Di,PROVIDER_DEFAULT_TIER:qi,loadConfigOverrides:l$}});var Vs=Q((dq,h$)=>{var cf=null,Xs=null,Bi=null,lf=Symbol.for("nex-code.browserExitCleanup"),d$=`Playwright is not installed. Install with:
291
291
  npm install playwright && npx playwright install chromium
292
292
  Then restart nex-code.`;function f$(){if(Bi!==null)return Bi;try{require("playwright"),Bi=!0}catch{Bi=!1}return Bi}async function pl(){if(!f$())throw new Error(d$);return cf||(cf=require("playwright")),(!Xs||!Xs.isConnected())&&(Xs=await cf.chromium.launch({headless:!0})),Xs}async function P1(){if(Xs){try{await Xs.close()}catch(e){console.error("closeBrowser failed:",e.message)}Xs=null}}globalThis[lf]&&process.off("exit",globalThis[lf]);var p$=()=>{if(Xs)try{Xs.close()}catch(e){console.error("Error closing browser on exit:",e.message)}};globalThis[lf]=p$;process.on("exit",p$);async function N1(e,{timeout:t=3e4,waitFor:n="domcontentloaded"}={}){let s=await(await pl()).newPage();try{await s.goto(e,{waitUntil:n,timeout:t});let r=await s.title(),i=await s.evaluate(()=>(document.querySelectorAll("script,style,nav,footer,header,aside,[role=navigation]").forEach(u=>u.remove()),document.body?.innerText||"")),a=await s.evaluate(()=>Array.from(document.querySelectorAll("a[href]")).slice(0,30).map(c=>({text:(c.innerText||c.textContent||"").trim().substring(0,80),href:c.href})).filter(c=>c.text&&c.href&&!c.href.startsWith("javascript:")));return{title:r,url:s.url(),text:i.substring(0,8e3)+(i.length>8e3?`
293
- ...(truncated)`:""),links:a.slice(0,20)}}finally{await s.close()}}async function L1(e,{width:t=1280,height:n=800,fullPage:o=!1,timeout:s=3e4}={}){let i=await(await pl()).newPage();try{await i.setViewportSize({width:t,height:n}),await i.goto(e,{waitUntil:"networkidle",timeout:s});let a=await i.screenshot({type:"png",fullPage:o}),c=require("os"),u=require("path"),d=require("fs"),f=u.join(c.tmpdir(),`nex-screenshot-${Date.now()}.png`);return d.writeFileSync(f,a,{mode:384}),{path:f,base64:a.toString("base64"),media_type:"image/png",title:await i.title(),url:i.url()}}finally{await i.close()}}async function I1(e,{selector:t,text:n,timeout:o=3e4}={}){if(!t&&!n)throw new Error("selector or text is required");let r=await(await pl()).newPage();try{await r.goto(e,{waitUntil:"domcontentloaded",timeout:o}),n?await r.getByText(n,{exact:!1}).first().click({timeout:1e4}):await r.locator(t).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 j1(e,{selector:t,value:n,submit:o=!1,timeout:s=3e4}={}){if(!t||n===void 0)throw new Error("selector and value are required");let i=await(await pl()).newPage();try{return await i.goto(e,{waitUntil:"domcontentloaded",timeout:s}),await i.fill(t,String(n)),o&&(await i.keyboard.press("Enter"),await i.waitForLoadState("domcontentloaded")),`Filled "${t}" with value. ${o?`Submitted \u2192 ${i.url()}`:"Not submitted."}`}finally{await i.close()}}h$.exports={isPlaywrightAvailable:f$,browserNavigate:N1,browserScreenshot:L1,browserClick:I1,browserFill:j1,closeBrowser:P1,INSTALL_MSG:d$}});var uf=Q((fq,g$)=>{"use strict";var D1=require("util"),m$=require("stream"),is=g$.exports=function(){m$.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};D1.inherits(is,m$);is.prototype.read=function(e,t){this._reads.push({length:Math.abs(e),allowLess:e<0,func:t}),process.nextTick(function(){this._process(),this._paused&&this._reads&&this._reads.length>0&&(this._paused=!1,this.emit("drain"))}.bind(this))};is.prototype.write=function(e,t){if(!this.writable)return this.emit("error",new Error("Stream not writable")),!1;let n;return Buffer.isBuffer(e)?n=e:n=Buffer.from(e,t||this._encoding),this._buffers.push(n),this._buffered+=n.length,this._process(),this._reads&&this._reads.length===0&&(this._paused=!0),this.writable&&!this._paused};is.prototype.end=function(e,t){e&&this.write(e,t),this.writable=!1,this._buffers&&(this._buffers.length===0?this._end():(this._buffers.push(null),this._process()))};is.prototype.destroySoon=is.prototype.end;is.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};is.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};is.prototype._processReadAllowingLess=function(e){this._reads.shift();let t=this._buffers[0];t.length>e.length?(this._buffered-=e.length,this._buffers[0]=t.slice(e.length),e.func.call(this,t.slice(0,e.length))):(this._buffered-=t.length,this._buffers.shift(),e.func.call(this,t))};is.prototype._processRead=function(e){this._reads.shift();let t=0,n=0,o=Buffer.alloc(e.length);for(;t<e.length;){let s=this._buffers[n++],r=Math.min(s.length,e.length-t);s.copy(o,t,0,r),t+=r,r!==s.length&&(this._buffers[--n]=s.slice(r))}n>0&&this._buffers.splice(0,n),this._buffered-=e.length,e.func.call(this,o)};is.prototype._process=function(){try{for(;this._buffered>0&&this._reads&&this._reads.length>0;){let e=this._reads[0];if(e.allowLess)this._processReadAllowingLess(e);else if(this._buffered>=e.length)this._processRead(e);else break}this._buffers&&!this.writable&&this._end()}catch(e){this.emit("error",e)}}});var ff=Q(df=>{"use strict";var ho=[{x:[0],y:[0]},{x:[4],y:[0]},{x:[0,4],y:[4]},{x:[2,6],y:[0,4]},{x:[0,2,4,6],y:[2,6]},{x:[1,3,5,7],y:[0,2,4,6]},{x:[0,1,2,3,4,5,6,7],y:[1,3,5,7]}];df.getImagePasses=function(e,t){let n=[],o=e%8,s=t%8,r=(e-o)/8,i=(t-s)/8;for(let a=0;a<ho.length;a++){let c=ho[a],u=r*c.x.length,d=i*c.y.length;for(let f=0;f<c.x.length&&c.x[f]<o;f++)u++;for(let f=0;f<c.y.length&&c.y[f]<s;f++)d++;u>0&&d>0&&n.push({width:u,height:d,index:a})}return n};df.getInterlaceIterator=function(e){return function(t,n,o){let s=t%ho[o].x.length,r=(t-s)/ho[o].x.length*8+ho[o].x[s],i=n%ho[o].y.length,a=(n-i)/ho[o].y.length*8+ho[o].y[i];return r*4+a*e*4}}});var pf=Q((hq,y$)=>{"use strict";y$.exports=function(t,n,o){let s=t+n-o,r=Math.abs(s-t),i=Math.abs(s-n),a=Math.abs(s-o);return r<=i&&r<=a?t:i<=a?n:o}});var hf=Q((mq,b$)=>{"use strict";var q1=ff(),F1=pf();function $$(e,t,n){let o=e*t;return n!==8&&(o=Math.ceil(o/(8/n))),o}var qr=b$.exports=function(e,t){let n=e.width,o=e.height,s=e.interlace,r=e.bpp,i=e.depth;if(this.read=t.read,this.write=t.write,this.complete=t.complete,this._imageIndex=0,this._images=[],s){let a=q1.getImagePasses(n,o);for(let c=0;c<a.length;c++)this._images.push({byteWidth:$$(a[c].width,r,i),height:a[c].height,lineIndex:0})}else this._images.push({byteWidth:$$(n,r,i),height:o,lineIndex:0});i===8?this._xComparison=r:i===16?this._xComparison=r*2:this._xComparison=1};qr.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};qr.prototype._unFilterType1=function(e,t,n){let o=this._xComparison,s=o-1;for(let r=0;r<n;r++){let i=e[1+r],a=r>s?t[r-o]:0;t[r]=i+a}};qr.prototype._unFilterType2=function(e,t,n){let o=this._lastLine;for(let s=0;s<n;s++){let r=e[1+s],i=o?o[s]:0;t[s]=r+i}};qr.prototype._unFilterType3=function(e,t,n){let o=this._xComparison,s=o-1,r=this._lastLine;for(let i=0;i<n;i++){let a=e[1+i],c=r?r[i]:0,u=i>s?t[i-o]:0,d=Math.floor((u+c)/2);t[i]=a+d}};qr.prototype._unFilterType4=function(e,t,n){let o=this._xComparison,s=o-1,r=this._lastLine;for(let i=0;i<n;i++){let a=e[1+i],c=r?r[i]:0,u=i>s?t[i-o]:0,d=i>s&&r?r[i-o]:0,f=F1(u,c,d);t[i]=a+f}};qr.prototype._reverseFilterLine=function(e){let t=e[0],n,o=this._images[this._imageIndex],s=o.byteWidth;if(t===0)n=e.slice(1,s+1);else switch(n=Buffer.alloc(s),t){case 1:this._unFilterType1(e,n,s);break;case 2:this._unFilterType2(e,n,s);break;case 3:this._unFilterType3(e,n,s);break;case 4:this._unFilterType4(e,n,s);break;default:throw new Error("Unrecognised filter type - "+t)}this.write(n),o.lineIndex++,o.lineIndex>=o.height?(this._lastLine=null,this._imageIndex++,o=this._images[this._imageIndex]):this._lastLine=n,o?this.read(o.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}});var k$=Q((gq,_$)=>{"use strict";var B1=require("util"),w$=uf(),U1=hf(),W1=_$.exports=function(e){w$.call(this);let t=[],n=this;this._filter=new U1(e,{read:this.read.bind(this),write:function(o){t.push(o)},complete:function(){n.emit("complete",Buffer.concat(t))}}),this._filter.start()};B1.inherits(W1,w$)});var Fr=Q((yq,x$)=>{"use strict";x$.exports={PNG_SIGNATURE:[137,80,78,71,13,10,26,10],TYPE_IHDR:1229472850,TYPE_IEND:1229278788,TYPE_IDAT:1229209940,TYPE_PLTE:1347179589,TYPE_tRNS:1951551059,TYPE_gAMA:1732332865,COLORTYPE_GRAYSCALE:0,COLORTYPE_PALETTE:1,COLORTYPE_COLOR:2,COLORTYPE_ALPHA:4,COLORTYPE_PALETTE_COLOR:3,COLORTYPE_COLOR_ALPHA:6,COLORTYPE_TO_BPP_MAP:{0:1,2:3,3:1,4:2,6:4},GAMMA_DIVISION:1e5}});var yf=Q(($q,v$)=>{"use strict";var mf=[];(function(){for(let e=0;e<256;e++){let t=e;for(let n=0;n<8;n++)t&1?t=3988292384^t>>>1:t=t>>>1;mf[e]=t}})();var gf=v$.exports=function(){this._crc=-1};gf.prototype.write=function(e){for(let t=0;t<e.length;t++)this._crc=mf[(this._crc^e[t])&255]^this._crc>>>8;return!0};gf.prototype.crc32=function(){return this._crc^-1};gf.crc32=function(e){let t=-1;for(let n=0;n<e.length;n++)t=mf[(t^e[n])&255]^t>>>8;return t^-1}});var $f=Q((bq,S$)=>{"use strict";var Bt=Fr(),H1=yf(),Ht=S$.exports=function(e,t){this._options=e,e.checkCRC=e.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[Bt.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[Bt.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[Bt.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[Bt.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[Bt.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[Bt.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=t.read,this.error=t.error,this.metadata=t.metadata,this.gamma=t.gamma,this.transColor=t.transColor,this.palette=t.palette,this.parsed=t.parsed,this.inflateData=t.inflateData,this.finished=t.finished,this.simpleTransparency=t.simpleTransparency,this.headersFinished=t.headersFinished||function(){}};Ht.prototype.start=function(){this.read(Bt.PNG_SIGNATURE.length,this._parseSignature.bind(this))};Ht.prototype._parseSignature=function(e){let t=Bt.PNG_SIGNATURE;for(let n=0;n<t.length;n++)if(e[n]!==t[n]){this.error(new Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};Ht.prototype._parseChunkBegin=function(e){let t=e.readUInt32BE(0),n=e.readUInt32BE(4),o="";for(let r=4;r<8;r++)o+=String.fromCharCode(e[r]);let s=!!(e[4]&32);if(!this._hasIHDR&&n!==Bt.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new H1,this._crc.write(Buffer.from(o)),this._chunks[n])return this._chunks[n](t);if(!s){this.error(new Error("Unsupported critical chunk type "+o));return}this.read(t+4,this._skipChunk.bind(this))};Ht.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};Ht.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};Ht.prototype._parseChunkEnd=function(e){let t=e.readInt32BE(0),n=this._crc.crc32();if(this._options.checkCRC&&n!==t){this.error(new Error("Crc error - "+t+" - "+n));return}this._hasIEND||this.read(8,this._parseChunkBegin.bind(this))};Ht.prototype._handleIHDR=function(e){this.read(e,this._parseIHDR.bind(this))};Ht.prototype._parseIHDR=function(e){this._crc.write(e);let t=e.readUInt32BE(0),n=e.readUInt32BE(4),o=e[8],s=e[9],r=e[10],i=e[11],a=e[12];if(o!==8&&o!==4&&o!==2&&o!==1&&o!==16){this.error(new Error("Unsupported bit depth "+o));return}if(!(s in Bt.COLORTYPE_TO_BPP_MAP)){this.error(new Error("Unsupported color type"));return}if(r!==0){this.error(new Error("Unsupported compression method"));return}if(i!==0){this.error(new Error("Unsupported filter method"));return}if(a!==0&&a!==1){this.error(new Error("Unsupported interlace method"));return}this._colorType=s;let c=Bt.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:t,height:n,depth:o,interlace:!!a,palette:!!(s&Bt.COLORTYPE_PALETTE),color:!!(s&Bt.COLORTYPE_COLOR),alpha:!!(s&Bt.COLORTYPE_ALPHA),bpp:c,colorType:s}),this._handleChunkEnd()};Ht.prototype._handlePLTE=function(e){this.read(e,this._parsePLTE.bind(this))};Ht.prototype._parsePLTE=function(e){this._crc.write(e);let t=Math.floor(e.length/3);for(let n=0;n<t;n++)this._palette.push([e[n*3],e[n*3+1],e[n*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};Ht.prototype._handleTRNS=function(e){this.simpleTransparency(),this.read(e,this._parseTRNS.bind(this))};Ht.prototype._parseTRNS=function(e){if(this._crc.write(e),this._colorType===Bt.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(new Error("Transparency chunk must be after palette"));return}if(e.length>this._palette.length){this.error(new Error("More transparent colors than palette size"));return}for(let t=0;t<e.length;t++)this._palette[t][3]=e[t];this.palette(this._palette)}this._colorType===Bt.COLORTYPE_GRAYSCALE&&this.transColor([e.readUInt16BE(0)]),this._colorType===Bt.COLORTYPE_COLOR&&this.transColor([e.readUInt16BE(0),e.readUInt16BE(2),e.readUInt16BE(4)]),this._handleChunkEnd()};Ht.prototype._handleGAMA=function(e){this.read(e,this._parseGAMA.bind(this))};Ht.prototype._parseGAMA=function(e){this._crc.write(e),this.gamma(e.readUInt32BE(0)/Bt.GAMMA_DIVISION),this._handleChunkEnd()};Ht.prototype._handleIDAT=function(e){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-e,this._parseIDAT.bind(this,e))};Ht.prototype._parseIDAT=function(e,t){if(this._crc.write(t),this._colorType===Bt.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw new Error("Expected palette not found");this.inflateData(t);let n=e-t.length;n>0?this._handleIDAT(n):this._handleChunkEnd()};Ht.prototype._handleIEND=function(e){this.read(e,this._parseIEND.bind(this))};Ht.prototype._parseIEND=function(e){this._crc.write(e),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var bf=Q(T$=>{"use strict";var E$=ff(),G1=[function(){},function(e,t,n,o){if(o===t.length)throw new Error("Ran out of data");let s=t[o];e[n]=s,e[n+1]=s,e[n+2]=s,e[n+3]=255},function(e,t,n,o){if(o+1>=t.length)throw new Error("Ran out of data");let s=t[o];e[n]=s,e[n+1]=s,e[n+2]=s,e[n+3]=t[o+1]},function(e,t,n,o){if(o+2>=t.length)throw new Error("Ran out of data");e[n]=t[o],e[n+1]=t[o+1],e[n+2]=t[o+2],e[n+3]=255},function(e,t,n,o){if(o+3>=t.length)throw new Error("Ran out of data");e[n]=t[o],e[n+1]=t[o+1],e[n+2]=t[o+2],e[n+3]=t[o+3]}],Y1=[function(){},function(e,t,n,o){let s=t[0];e[n]=s,e[n+1]=s,e[n+2]=s,e[n+3]=o},function(e,t,n){let o=t[0];e[n]=o,e[n+1]=o,e[n+2]=o,e[n+3]=t[1]},function(e,t,n,o){e[n]=t[0],e[n+1]=t[1],e[n+2]=t[2],e[n+3]=o},function(e,t,n){e[n]=t[0],e[n+1]=t[1],e[n+2]=t[2],e[n+3]=t[3]}];function z1(e,t){let n=[],o=0;function s(){if(o===e.length)throw new Error("Ran out of data");let r=e[o];o++;let i,a,c,u,d,f,p,h;switch(t){default:throw new Error("unrecognised depth");case 16:p=e[o],o++,n.push((r<<8)+p);break;case 4:p=r&15,h=r>>4,n.push(h,p);break;case 2:d=r&3,f=r>>2&3,p=r>>4&3,h=r>>6&3,n.push(h,p,f,d);break;case 1:i=r&1,a=r>>1&1,c=r>>2&1,u=r>>3&1,d=r>>4&1,f=r>>5&1,p=r>>6&1,h=r>>7&1,n.push(h,p,f,d,u,c,a,i);break}}return{get:function(r){for(;n.length<r;)s();let i=n.slice(0,r);return n=n.slice(r),i},resetAfterLine:function(){n.length=0},end:function(){if(o!==e.length)throw new Error("extra data found")}}}function K1(e,t,n,o,s,r){let i=e.width,a=e.height,c=e.index;for(let u=0;u<a;u++)for(let d=0;d<i;d++){let f=n(d,u,c);G1[o](t,s,f,r),r+=o}return r}function X1(e,t,n,o,s,r){let i=e.width,a=e.height,c=e.index;for(let u=0;u<a;u++){for(let d=0;d<i;d++){let f=s.get(o),p=n(d,u,c);Y1[o](t,f,p,r)}s.resetAfterLine()}}T$.dataToBitMap=function(e,t){let n=t.width,o=t.height,s=t.depth,r=t.bpp,i=t.interlace,a;s!==8&&(a=z1(e,s));let c;s<=8?c=Buffer.alloc(n*o*4):c=new Uint16Array(n*o*4);let u=Math.pow(2,s)-1,d=0,f,p;if(i)f=E$.getImagePasses(n,o),p=E$.getInterlaceIterator(n,o);else{let h=0;p=function(){let m=h;return h+=4,m},f=[{width:n,height:o}]}for(let h=0;h<f.length;h++)s===8?d=K1(f[h],c,p,r,e,d):X1(f[h],c,p,r,a,u);if(s===8){if(d!==e.length)throw new Error("extra data found")}else a.end();return c}});var wf=Q((_q,R$)=>{"use strict";function V1(e,t,n,o,s){let r=0;for(let i=0;i<o;i++)for(let a=0;a<n;a++){let c=s[e[r]];if(!c)throw new Error("index "+e[r]+" not in palette");for(let u=0;u<4;u++)t[r+u]=c[u];r+=4}}function J1(e,t,n,o,s){let r=0;for(let i=0;i<o;i++)for(let a=0;a<n;a++){let c=!1;if(s.length===1?s[0]===e[r]&&(c=!0):s[0]===e[r]&&s[1]===e[r+1]&&s[2]===e[r+2]&&(c=!0),c)for(let u=0;u<4;u++)t[r+u]=0;r+=4}}function Z1(e,t,n,o,s){let r=255,i=Math.pow(2,s)-1,a=0;for(let c=0;c<o;c++)for(let u=0;u<n;u++){for(let d=0;d<4;d++)t[a+d]=Math.floor(e[a+d]*r/i+.5);a+=4}}R$.exports=function(e,t,n=!1){let o=t.depth,s=t.width,r=t.height,i=t.colorType,a=t.transColor,c=t.palette,u=e;return i===3?V1(e,u,s,r,c):(a&&J1(e,u,s,r,a),o!==8&&!n&&(o===16&&(u=Buffer.alloc(s*r*4)),Z1(e,u,s,r,o))),u}});var O$=Q((kq,A$)=>{"use strict";var Q1=require("util"),_f=require("zlib"),C$=uf(),eC=k$(),tC=$f(),nC=bf(),sC=wf(),Rs=A$.exports=function(e){C$.call(this),this._parser=new tC(e,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,"gamma"),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this),simpleTransparency:this._simpleTransparency.bind(this),headersFinished:this._headersFinished.bind(this)}),this._options=e,this.writable=!0,this._parser.start()};Q1.inherits(Rs,C$);Rs.prototype._handleError=function(e){this.emit("error",e),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy&&this._inflate.destroy(),this._filter&&(this._filter.destroy(),this._filter.on("error",function(){})),this.errord=!0};Rs.prototype._inflateData=function(e){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=_f.createInflate(),this._inflate.on("error",this.emit.bind(this,"error")),this._filter.on("complete",this._complete.bind(this)),this._inflate.pipe(this._filter);else{let n=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,o=Math.max(n,_f.Z_MIN_CHUNK);this._inflate=_f.createInflate({chunkSize:o});let s=n,r=this.emit.bind(this,"error");this._inflate.on("error",function(a){s&&r(a)}),this._filter.on("complete",this._complete.bind(this));let i=this._filter.write.bind(this._filter);this._inflate.on("data",function(a){s&&(a.length>s&&(a=a.slice(0,s)),s-=a.length,i(a))}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(e)};Rs.prototype._handleMetaData=function(e){this._metaData=e,this._bitmapInfo=Object.create(e),this._filter=new eC(this._bitmapInfo)};Rs.prototype._handleTransColor=function(e){this._bitmapInfo.transColor=e};Rs.prototype._handlePalette=function(e){this._bitmapInfo.palette=e};Rs.prototype._simpleTransparency=function(){this._metaData.alpha=!0};Rs.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};Rs.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};Rs.prototype._complete=function(e){if(this.errord)return;let t;try{let n=nC.dataToBitMap(e,this._bitmapInfo);t=sC(n,this._bitmapInfo,this._options.skipRescale),n=null}catch(n){this._handleError(n);return}this.emit("parsed",t)}});var P$=Q((xq,M$)=>{"use strict";var Kn=Fr();M$.exports=function(e,t,n,o){let s=[Kn.COLORTYPE_COLOR_ALPHA,Kn.COLORTYPE_ALPHA].indexOf(o.colorType)!==-1;if(o.colorType===o.inputColorType){let m=(function(){let g=new ArrayBuffer(2);return new DataView(g).setInt16(0,256,!0),new Int16Array(g)[0]!==256})();if(o.bitDepth===8||o.bitDepth===16&&m)return e}let r=o.bitDepth!==16?e:new Uint16Array(e.buffer),i=255,a=Kn.COLORTYPE_TO_BPP_MAP[o.inputColorType];a===4&&!o.inputHasAlpha&&(a=3);let c=Kn.COLORTYPE_TO_BPP_MAP[o.colorType];o.bitDepth===16&&(i=65535,c*=2);let u=Buffer.alloc(t*n*c),d=0,f=0,p=o.bgColor||{};p.red===void 0&&(p.red=i),p.green===void 0&&(p.green=i),p.blue===void 0&&(p.blue=i);function h(){let m,g,$,b=i;switch(o.inputColorType){case Kn.COLORTYPE_COLOR_ALPHA:b=r[d+3],m=r[d],g=r[d+1],$=r[d+2];break;case Kn.COLORTYPE_COLOR:m=r[d],g=r[d+1],$=r[d+2];break;case Kn.COLORTYPE_ALPHA:b=r[d+1],m=r[d],g=m,$=m;break;case Kn.COLORTYPE_GRAYSCALE:m=r[d],g=m,$=m;break;default:throw new Error("input color type:"+o.inputColorType+" is not supported at present")}return o.inputHasAlpha&&(s||(b/=i,m=Math.min(Math.max(Math.round((1-b)*p.red+b*m),0),i),g=Math.min(Math.max(Math.round((1-b)*p.green+b*g),0),i),$=Math.min(Math.max(Math.round((1-b)*p.blue+b*$),0),i))),{red:m,green:g,blue:$,alpha:b}}for(let m=0;m<n;m++)for(let g=0;g<t;g++){let $=h(r,d);switch(o.colorType){case Kn.COLORTYPE_COLOR_ALPHA:case Kn.COLORTYPE_COLOR:o.bitDepth===8?(u[f]=$.red,u[f+1]=$.green,u[f+2]=$.blue,s&&(u[f+3]=$.alpha)):(u.writeUInt16BE($.red,f),u.writeUInt16BE($.green,f+2),u.writeUInt16BE($.blue,f+4),s&&u.writeUInt16BE($.alpha,f+6));break;case Kn.COLORTYPE_ALPHA:case Kn.COLORTYPE_GRAYSCALE:{let b=($.red+$.green+$.blue)/3;o.bitDepth===8?(u[f]=b,s&&(u[f+1]=$.alpha)):(u.writeUInt16BE(b,f),s&&u.writeUInt16BE($.alpha,f+2));break}default:throw new Error("unrecognised color Type "+o.colorType)}d+=a,f+=c}return u}});var I$=Q((vq,L$)=>{"use strict";var N$=pf();function oC(e,t,n,o,s){for(let r=0;r<n;r++)o[s+r]=e[t+r]}function rC(e,t,n){let o=0,s=t+n;for(let r=t;r<s;r++)o+=Math.abs(e[r]);return o}function iC(e,t,n,o,s,r){for(let i=0;i<n;i++){let a=i>=r?e[t+i-r]:0,c=e[t+i]-a;o[s+i]=c}}function aC(e,t,n,o){let s=0;for(let r=0;r<n;r++){let i=r>=o?e[t+r-o]:0,a=e[t+r]-i;s+=Math.abs(a)}return s}function cC(e,t,n,o,s){for(let r=0;r<n;r++){let i=t>0?e[t+r-n]:0,a=e[t+r]-i;o[s+r]=a}}function lC(e,t,n){let o=0,s=t+n;for(let r=t;r<s;r++){let i=t>0?e[r-n]:0,a=e[r]-i;o+=Math.abs(a)}return o}function uC(e,t,n,o,s,r){for(let i=0;i<n;i++){let a=i>=r?e[t+i-r]:0,c=t>0?e[t+i-n]:0,u=e[t+i]-(a+c>>1);o[s+i]=u}}function dC(e,t,n,o){let s=0;for(let r=0;r<n;r++){let i=r>=o?e[t+r-o]:0,a=t>0?e[t+r-n]:0,c=e[t+r]-(i+a>>1);s+=Math.abs(c)}return s}function fC(e,t,n,o,s,r){for(let i=0;i<n;i++){let a=i>=r?e[t+i-r]:0,c=t>0?e[t+i-n]:0,u=t>0&&i>=r?e[t+i-(n+r)]:0,d=e[t+i]-N$(a,c,u);o[s+i]=d}}function pC(e,t,n,o){let s=0;for(let r=0;r<n;r++){let i=r>=o?e[t+r-o]:0,a=t>0?e[t+r-n]:0,c=t>0&&r>=o?e[t+r-(n+o)]:0,u=e[t+r]-N$(i,a,c);s+=Math.abs(u)}return s}var hC={0:oC,1:iC,2:cC,3:uC,4:fC},mC={0:rC,1:aC,2:lC,3:dC,4:pC};L$.exports=function(e,t,n,o,s){let r;if(!("filterType"in o)||o.filterType===-1)r=[0,1,2,3,4];else if(typeof o.filterType=="number")r=[o.filterType];else throw new Error("unrecognised filter types");o.bitDepth===16&&(s*=2);let i=t*s,a=0,c=0,u=Buffer.alloc((i+1)*n),d=r[0];for(let f=0;f<n;f++){if(r.length>1){let p=1/0;for(let h=0;h<r.length;h++){let m=mC[r[h]](e,c,i,s);m<p&&(d=r[h],p=m)}}u[a]=d,a++,hC[d](e,c,i,u,a,s),a+=i,c+=i}return u}});var kf=Q((Sq,j$)=>{"use strict";var tn=Fr(),gC=yf(),yC=P$(),$C=I$(),bC=require("zlib"),mo=j$.exports=function(e){if(this._options=e,e.deflateChunkSize=e.deflateChunkSize||32*1024,e.deflateLevel=e.deflateLevel!=null?e.deflateLevel:9,e.deflateStrategy=e.deflateStrategy!=null?e.deflateStrategy:3,e.inputHasAlpha=e.inputHasAlpha!=null?e.inputHasAlpha:!0,e.deflateFactory=e.deflateFactory||bC.createDeflate,e.bitDepth=e.bitDepth||8,e.colorType=typeof e.colorType=="number"?e.colorType:tn.COLORTYPE_COLOR_ALPHA,e.inputColorType=typeof e.inputColorType=="number"?e.inputColorType:tn.COLORTYPE_COLOR_ALPHA,[tn.COLORTYPE_GRAYSCALE,tn.COLORTYPE_COLOR,tn.COLORTYPE_COLOR_ALPHA,tn.COLORTYPE_ALPHA].indexOf(e.colorType)===-1)throw new Error("option color type:"+e.colorType+" is not supported at present");if([tn.COLORTYPE_GRAYSCALE,tn.COLORTYPE_COLOR,tn.COLORTYPE_COLOR_ALPHA,tn.COLORTYPE_ALPHA].indexOf(e.inputColorType)===-1)throw new Error("option input color type:"+e.inputColorType+" is not supported at present");if(e.bitDepth!==8&&e.bitDepth!==16)throw new Error("option bit depth:"+e.bitDepth+" is not supported at present")};mo.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};mo.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};mo.prototype.filterData=function(e,t,n){let o=yC(e,t,n,this._options),s=tn.COLORTYPE_TO_BPP_MAP[this._options.colorType];return $C(o,t,n,this._options,s)};mo.prototype._packChunk=function(e,t){let n=t?t.length:0,o=Buffer.alloc(n+12);return o.writeUInt32BE(n,0),o.writeUInt32BE(e,4),t&&t.copy(o,8),o.writeInt32BE(gC.crc32(o.slice(4,o.length-4)),o.length-4),o};mo.prototype.packGAMA=function(e){let t=Buffer.alloc(4);return t.writeUInt32BE(Math.floor(e*tn.GAMMA_DIVISION),0),this._packChunk(tn.TYPE_gAMA,t)};mo.prototype.packIHDR=function(e,t){let n=Buffer.alloc(13);return n.writeUInt32BE(e,0),n.writeUInt32BE(t,4),n[8]=this._options.bitDepth,n[9]=this._options.colorType,n[10]=0,n[11]=0,n[12]=0,this._packChunk(tn.TYPE_IHDR,n)};mo.prototype.packIDAT=function(e){return this._packChunk(tn.TYPE_IDAT,e)};mo.prototype.packIEND=function(){return this._packChunk(tn.TYPE_IEND,null)}});var B$=Q((Eq,F$)=>{"use strict";var wC=require("util"),D$=require("stream"),_C=Fr(),kC=kf(),q$=F$.exports=function(e){D$.call(this);let t=e||{};this._packer=new kC(t),this._deflate=this._packer.createDeflate(),this.readable=!0};wC.inherits(q$,D$);q$.prototype.pack=function(e,t,n,o){this.emit("data",Buffer.from(_C.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(t,n)),o&&this.emit("data",this._packer.packGAMA(o));let s=this._packer.filterData(e,t,n);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(r){this.emit("data",this._packer.packIDAT(r))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(s)}});var z$=Q((Ui,Y$)=>{"use strict";var U$=require("assert").ok,Br=require("zlib"),xC=require("util"),W$=require("buffer").kMaxLength;function Ko(e){if(!(this instanceof Ko))return new Ko(e);e&&e.chunkSize<Br.Z_MIN_CHUNK&&(e.chunkSize=Br.Z_MIN_CHUNK),Br.Inflate.call(this,e),this._offset=this._offset===void 0?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,e&&e.maxLength!=null&&(this._maxLength=e.maxLength)}function vC(e){return new Ko(e)}function H$(e,t){t&&process.nextTick(t),e._handle&&(e._handle.close(),e._handle=null)}Ko.prototype._processChunk=function(e,t,n){if(typeof n=="function")return Br.Inflate._processChunk.call(this,e,t,n);let o=this,s=e&&e.length,r=this._chunkSize-this._offset,i=this._maxLength,a=0,c=[],u=0,d;this.on("error",function(m){d=m});function f(m,g){if(o._hadError)return;let $=r-g;if(U$($>=0,"have should not go down"),$>0){let b=o._buffer.slice(o._offset,o._offset+$);if(o._offset+=$,b.length>i&&(b=b.slice(0,i)),c.push(b),u+=b.length,i-=b.length,i===0)return!1}return(g===0||o._offset>=o._chunkSize)&&(r=o._chunkSize,o._offset=0,o._buffer=Buffer.allocUnsafe(o._chunkSize)),g===0?(a+=s-m,s=m,!0):!1}U$(this._handle,"zlib binding closed");let p;do p=this._handle.writeSync(t,e,a,s,this._buffer,this._offset,r),p=p||this._writeState;while(!this._hadError&&f(p[0],p[1]));if(this._hadError)throw d;if(u>=W$)throw H$(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+W$.toString(16)+" bytes");let h=Buffer.concat(c,u);return H$(this),h};xC.inherits(Ko,Br.Inflate);function SC(e,t){if(typeof t=="string"&&(t=Buffer.from(t)),!(t instanceof Buffer))throw new TypeError("Not a string or buffer");let n=e._finishFlushFlag;return n==null&&(n=Br.Z_FINISH),e._processChunk(t,n)}function G$(e,t){return SC(new Ko(t),e)}Y$.exports=Ui=G$;Ui.Inflate=Ko;Ui.createInflate=vC;Ui.inflateSync=G$});var xf=Q((Tq,X$)=>{"use strict";var K$=X$.exports=function(e){this._buffer=e,this._reads=[]};K$.prototype.read=function(e,t){this._reads.push({length:Math.abs(e),allowLess:e<0,func:t})};K$.prototype.process=function(){for(;this._reads.length>0&&this._buffer.length;){let e=this._reads[0];if(this._buffer.length&&(this._buffer.length>=e.length||e.allowLess)){this._reads.shift();let t=this._buffer;this._buffer=t.slice(e.length),e.func.call(this,t.slice(0,e.length))}else break}if(this._reads.length>0)throw new Error("There are some read requests waitng on finished stream");if(this._buffer.length>0)throw new Error("unrecognised content at end of stream")}});var J$=Q(V$=>{"use strict";var EC=xf(),TC=hf();V$.process=function(e,t){let n=[],o=new EC(e);return new TC(t,{read:o.read.bind(o),write:function(r){n.push(r)},complete:function(){}}).start(),o.process(),Buffer.concat(n)}});var tb=Q((Cq,eb)=>{"use strict";var Z$=!0,Q$=require("zlib"),RC=z$();Q$.deflateSync||(Z$=!1);var CC=xf(),AC=J$(),OC=$f(),MC=bf(),PC=wf();eb.exports=function(e,t){if(!Z$)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n;function o(E){n=E}let s;function r(E){s=E}function i(E){s.transColor=E}function a(E){s.palette=E}function c(){s.alpha=!0}let u;function d(E){u=E}let f=[];function p(E){f.push(E)}let h=new CC(e);if(new OC(t,{read:h.read.bind(h),error:o,metadata:r,gamma:d,palette:a,transColor:i,inflateData:p,simpleTransparency:c}).start(),h.process(),n)throw n;let g=Buffer.concat(f);f.length=0;let $;if(s.interlace)$=Q$.inflateSync(g);else{let S=((s.width*s.bpp*s.depth+7>>3)+1)*s.height;$=RC(g,{chunkSize:S,maxLength:S})}if(g=null,!$||!$.length)throw new Error("bad png - invalid inflate data response");let b=AC.process($,s);g=null;let x=MC.dataToBitMap(b,s);b=null;let _=PC(x,s,t.skipRescale);return s.data=_,s.gamma=u||0,s}});var rb=Q((Aq,ob)=>{"use strict";var nb=!0,sb=require("zlib");sb.deflateSync||(nb=!1);var NC=Fr(),LC=kf();ob.exports=function(e,t){if(!nb)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n=t||{},o=new LC(n),s=[];s.push(Buffer.from(NC.PNG_SIGNATURE)),s.push(o.packIHDR(e.width,e.height)),e.gamma&&s.push(o.packGAMA(e.gamma));let r=o.filterData(e.data,e.width,e.height),i=sb.deflateSync(r,o.getDeflateOptions());if(r=null,!i||!i.length)throw new Error("bad png - invalid compressed data response");return s.push(o.packIDAT(i)),s.push(o.packIEND()),Buffer.concat(s)}});var ib=Q(vf=>{"use strict";var IC=tb(),jC=rb();vf.read=function(e,t){return IC(e,t||{})};vf.write=function(e,t){return jC(e,t)}});var lb=Q(cb=>{"use strict";var DC=require("util"),ab=require("stream"),qC=O$(),FC=B$(),BC=ib(),fn=cb.PNG=function(e){ab.call(this),e=e||{},this.width=e.width|0,this.height=e.height|0,this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null,e.fill&&this.data&&this.data.fill(0),this.gamma=0,this.readable=this.writable=!0,this._parser=new qC(e),this._parser.on("error",this.emit.bind(this,"error")),this._parser.on("close",this._handleClose.bind(this)),this._parser.on("metadata",this._metadata.bind(this)),this._parser.on("gamma",this._gamma.bind(this)),this._parser.on("parsed",function(t){this.data=t,this.emit("parsed",t)}.bind(this)),this._packer=new FC(e),this._packer.on("data",this.emit.bind(this,"data")),this._packer.on("end",this.emit.bind(this,"end")),this._parser.on("close",this._handleClose.bind(this)),this._packer.on("error",this.emit.bind(this,"error"))};DC.inherits(fn,ab);fn.sync=BC;fn.prototype.pack=function(){return!this.data||!this.data.length?(this.emit("error","No data provided"),this):(process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this)),this)};fn.prototype.parse=function(e,t){if(t){let n,o;n=function(s){this.removeListener("error",o),this.data=s,t(null,this)}.bind(this),o=function(s){this.removeListener("parsed",n),t(s,null)}.bind(this),this.once("parsed",n),this.once("error",o)}return this.end(e),this};fn.prototype.write=function(e){return this._parser.write(e),!0};fn.prototype.end=function(e){this._parser.end(e)};fn.prototype._metadata=function(e){this.width=e.width,this.height=e.height,this.emit("metadata",e)};fn.prototype._gamma=function(e){this.gamma=e};fn.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};fn.bitblt=function(e,t,n,o,s,r,i,a){if(n|=0,o|=0,s|=0,r|=0,i|=0,a|=0,n>e.width||o>e.height||n+s>e.width||o+r>e.height)throw new Error("bitblt reading outside image");if(i>t.width||a>t.height||i+s>t.width||a+r>t.height)throw new Error("bitblt writing outside image");for(let c=0;c<r;c++)e.data.copy(t.data,(a+c)*t.width+i<<2,(o+c)*e.width+n<<2,(o+c)*e.width+n+s<<2)};fn.prototype.bitblt=function(e,t,n,o,s,r,i){return fn.bitblt(this,e,t,n,o,s,r,i),this};fn.adjustGamma=function(e){if(e.gamma){for(let t=0;t<e.height;t++)for(let n=0;n<e.width;n++){let o=e.width*t+n<<2;for(let s=0;s<3;s++){let r=e.data[o+s]/255;r=Math.pow(r,1/2.2/e.gamma),e.data[o+s]=Math.round(r*255)}}e.gamma=0}};fn.prototype.adjustGamma=function(){fn.adjustGamma(this)}});var hb={};Fv(hb,{default:()=>fb});function fb(e,t,n,o,s,r={}){let{threshold:i=.1,alpha:a=.1,aaColor:c=[255,255,0],diffColor:u=[255,0,0],includeAA:d,diffColorAlt:f,diffMask:p}=r;if(!Sf(e)||!Sf(t)||n&&!Sf(n))throw new Error("Image data: Uint8Array, Uint8ClampedArray or Buffer expected.");if(e.length!==t.length||n&&n.length!==e.length)throw new Error("Image sizes do not match.");if(e.length!==o*s*4)throw new Error("Image data size does not match width/height.");let h=o*s,m=new Uint32Array(e.buffer,e.byteOffset,h),g=new Uint32Array(t.buffer,t.byteOffset,h),$=!0;for(let X=0;X<h;X++)if(m[X]!==g[X]){$=!1;break}if($){if(n&&!p)for(let X=0;X<h;X++)db(e,4*X,a,n);return 0}let b=35215*i*i,[x,_,E]=c,[S,O,L]=u,[I,D,Z]=f||u,K=0;for(let X=0;X<s;X++)for(let Fe=0;Fe<o;Fe++){let Oe=X*o+Fe,V=Oe*4,re=m[Oe]===g[Oe]?0:pb(e,t,V,V,!1);if(Math.abs(re)>b){let rt=ub(e,Fe,X,o,s,m,g)||ub(t,Fe,X,o,s,g,m);!d&&rt?n&&!p&&ml(n,V,x,_,E):(n&&(re<0?ml(n,V,I,D,Z):ml(n,V,S,O,L)),K++)}else n&&!p&&db(e,V,a,n)}return K}function Sf(e){return ArrayBuffer.isView(e)&&e.BYTES_PER_ELEMENT===1}function ub(e,t,n,o,s,r,i){let a=Math.max(t-1,0),c=Math.max(n-1,0),u=Math.min(t+1,o-1),d=Math.min(n+1,s-1),f=n*o+t,p=t===a||t===u||n===c||n===d?1:0,h=0,m=0,g=0,$=0,b=0,x=0;for(let _=a;_<=u;_++)for(let E=c;E<=d;E++){if(_===t&&E===n)continue;let S=pb(e,e,f*4,(E*o+_)*4,!0);if(S===0){if(p++,p>2)return!1}else S<h?(h=S,g=_,$=E):S>m&&(m=S,b=_,x=E)}return h===0||m===0?!1:hl(r,g,$,o,s)&&hl(i,g,$,o,s)||hl(r,b,x,o,s)&&hl(i,b,x,o,s)}function hl(e,t,n,o,s){let r=Math.max(t-1,0),i=Math.max(n-1,0),a=Math.min(t+1,o-1),c=Math.min(n+1,s-1),u=e[n*o+t],d=t===r||t===a||n===i||n===c?1:0;for(let f=r;f<=a;f++)for(let p=i;p<=c;p++)if(!(f===t&&p===n)&&(d+=+(u===e[p*o+f]),d>2))return!0;return!1}function pb(e,t,n,o,s){let r=e[n],i=e[n+1],a=e[n+2],c=e[n+3],u=t[o],d=t[o+1],f=t[o+2],p=t[o+3],h=r-u,m=i-d,g=a-f,$=c-p;if(!h&&!m&&!g&&!$)return 0;if(c<255||p<255){let S=48+159*(n%2),O=48+159*((n/1.618033988749895|0)%2),L=48+159*((n/2.618033988749895|0)%2);h=(r*c-u*p-S*$)/255,m=(i*c-d*p-O*$)/255,g=(a*c-f*p-L*$)/255}let b=h*.29889531+m*.58662247+g*.11448223;if(s)return b;let x=h*.59597799-m*.2741761-g*.32180189,_=h*.21147017-m*.52261711+g*.31114694,E=.5053*b*b+.299*x*x+.1957*_*_;return b>0?-E:E}function ml(e,t,n,o,s){e[t+0]=n,e[t+1]=o,e[t+2]=s,e[t+3]=255}function db(e,t,n,o){let s=255+(e[t]*.29889531+e[t+1]*.58662247+e[t+2]*.11448223-255)*n*e[t+3]/255;ml(o,t,s,s,s)}var mb=qv(()=>{});var Xo=Q((Pq,wb)=>{var Js=require("fs"),UC=require("path"),WC=require("os"),HC="nex-visual-";function yb(e){return UC.join(WC.tmpdir(),`${HC}${Date.now()}-${e}`)}var Ef=null;function gl(){return Ef||(Ef=lb().PNG),Ef}var Tf=null;function GC(){if(!Tf){let e=(mb(),Uv(hb));Tf=e.default||e}return Tf}function Af(e,t,{threshold:n=.1}={}){let o=gl(),s=GC(),r=o.sync.read(Js.readFileSync(e)),i=o.sync.read(Js.readFileSync(t)),a=Math.max(r.width,i.width),c=Math.max(r.height,i.height),u=gb(r,a,c),d=gb(i,a,c),f=new o({width:a,height:c}),p=s(u,d,f.data,a,c,{threshold:n,includeAA:!1}),h=a*c,m=(p/h*100).toFixed(1),g=YC(f.data,a,c,3,3),$=yb("diff.png");return Js.writeFileSync($,o.sync.write(f),{mode:384}),{diffPath:$,diffPercent:parseFloat(m),totalPixels:h,changedPixels:p,regionSummary:g,beforePath:e,afterPath:t,width:a,height:c}}function gb(e,t,n){if(e.width===t&&e.height===n)return e.data;let o=Buffer.alloc(t*n*4,0);for(let s=0;s<e.height;s++){let r=s*e.width*4,i=s*t*4;e.data.copy(o,i,r,r+e.width*4)}return o}function YC(e,t,n,o,s){let r=[["top-left","top-center","top-right"],["middle-left","center","middle-right"],["bottom-left","bottom-center","bottom-right"]],i=Math.ceil(t/o),a=Math.ceil(n/s),c=[];for(let u=0;u<s;u++)for(let d=0;d<o;d++){let f=0,p=0,h=d*i,m=u*a,g=Math.min(h+i,t),$=Math.min(m+a,n);for(let b=m;b<$;b++)for(let x=h;x<g;x++){p++;let _=(b*t+x)*4;(e[_]>0||e[_+1]>0)&&f++}if(f>0){let b=(f/p*100).toFixed(1),x=r[u]&&r[u][d]?r[u][d]:`row${u}-col${d}`;c.push({name:x,changedPercent:parseFloat(b),changed:f,total:p})}}return c.sort((u,d)=>d.changedPercent-u.changedPercent),c}var $b=[{width:320,label:"mobile-sm"},{width:768,label:"tablet"},{width:1024,label:"desktop-sm"},{width:1440,label:"desktop"},{width:1920,label:"desktop-lg"}];async function zC(e,{viewports:t=$b,height:n=800,fullPage:o=!1,timeout:s=3e4}={}){let{browserScreenshot:r}=Vs(),i=[];for(let a of t){let c=await r(e,{width:a.width,height:n,fullPage:o,timeout:s});i.push({label:a.label,width:a.width,path:c.path,base64:c.base64,media_type:c.media_type})}return i}function bb(e,t=[]){let n=gl(),o=n.sync.read(Js.readFileSync(e));for(let i of t){let a=KC(i.color||"#FF0000");i.type==="box"?(XC(o,i.x||0,i.y||0,i.width||50,i.height||50,a,i.thickness||3),i.label&&Cf(o,i.x||0,(i.y||0)-14,i.label,a)):i.type==="arrow"?(VC(o,i.x||0,i.y||0,i.toX||i.x+50,i.toY||i.y,a,i.thickness||3),i.label&&Cf(o,i.x||0,(i.y||0)-14,i.label,a)):i.type==="circle"&&(JC(o,i.x||0,i.y||0,i.radius||20,a,i.thickness||3),i.label&&Cf(o,(i.x||0)-(i.radius||20),(i.y||0)-(i.radius||20)-14,i.label,a))}let s=yb("annotated.png");Js.writeFileSync(s,n.sync.write(o),{mode:384});let r=Js.readFileSync(s).toString("base64");return{path:s,base64:r,media_type:"image/png"}}function KC(e){let t=e.replace("#","");return{r:parseInt(t.substring(0,2),16),g:parseInt(t.substring(2,4),16),b:parseInt(t.substring(4,6),16),a:255}}function Cs(e,t,n,o){if(t<0||n<0||t>=e.width||n>=e.height)return;let s=(n*e.width+t)*4;e.data[s]=o.r,e.data[s+1]=o.g,e.data[s+2]=o.b,e.data[s+3]=o.a}function XC(e,t,n,o,s,r,i=3){for(let a=0;a<i;a++){for(let c=0;c<o;c++)Cs(e,t+c,n+a,r),Cs(e,t+c,n+s-1-a,r);for(let c=0;c<s;c++)Cs(e,t+a,n+c,r),Cs(e,t+o-1-a,n+c,r)}}function Rf(e,t,n,o,s,r,i=3){let a=Math.abs(o-t),c=Math.abs(s-n),u=t<o?1:-1,d=n<s?1:-1,f=a-c,p=t,h=n;for(;;){let m=Math.floor(i/2);for(let $=-m;$<=m;$++)for(let b=-m;b<=m;b++)Cs(e,p+$,h+b,r);if(p===o&&h===s)break;let g=2*f;g>-c&&(f-=c,p+=u),g<a&&(f+=a,h+=d)}}function VC(e,t,n,o,s,r,i=3){Rf(e,t,n,o,s,r,i);let a=Math.atan2(s-n,o-t),c=15,u=a+Math.PI*.8,d=a-Math.PI*.8;Rf(e,o,s,Math.round(o+c*Math.cos(u)),Math.round(s+c*Math.sin(u)),r,i),Rf(e,o,s,Math.round(o+c*Math.cos(d)),Math.round(s+c*Math.sin(d)),r,i)}function JC(e,t,n,o,s,r=3){for(let i=0;i<r;i++){let a=o-i;for(let c=0;c<360;c+=.5){let u=c*Math.PI/180,d=Math.round(t+a*Math.cos(u)),f=Math.round(n+a*Math.sin(u));Cs(e,d,f,s)}}}function Cf(e,t,n,o,s){let i=o.length*6+4,a=12;for(let c=0;c<a;c++)for(let u=0;u<i;u++)Cs(e,t+u,n+c,{r:0,g:0,b:0,a:200});for(let c=0;c<i;c++)Cs(e,t+c,n+a-1,s),Cs(e,t+c,n+a-2,s);for(let c=0;c<o.length;c++){let u=t+2+c*6;for(let d=2;d<9;d++)for(let f=0;f<4;f++)Cs(e,u+f,n+d,s)}}async function*ZC(e,t,{maxIterations:n=20,hmrDelay:o=1500,width:s=1280,height:r=800,timeout:i=3e4}={}){let{browserScreenshot:a}=Vs(),c=QC("chokidar"),u=await a(e,{width:s,height:r,timeout:i});if(yield{iteration:0,type:"baseline",path:u.path,base64:u.base64,media_type:u.media_type},!c){yield{iteration:-1,type:"error",message:"chokidar not installed \u2014 watch mode requires it. Install with: npm install chokidar"};return}let d=0,f=!1,p=c.watch(t,{ignoreInitial:!0,ignored:/(node_modules|\.git|dist)/});p.on("change",()=>{f=!0});try{for(;d<n;){await tA(()=>f,3e5),f=!1,d++,await eA(o);let h=await a(e,{width:s,height:r,timeout:i}),m=null;try{m=Af(u.path,h.path)}catch{}u=h,yield{iteration:d,type:"change",path:h.path,base64:h.base64,media_type:h.media_type,diff:m?{diffPath:m.diffPath,diffPercent:m.diffPercent,changedPixels:m.changedPixels,regions:m.regionSummary}:null}}}finally{await p.close()}}function QC(e){try{return require(e)}catch{return null}}function eA(e){return new Promise(t=>setTimeout(t,e))}function tA(e,t=6e4){return new Promise((n,o)=>{let s=setInterval(()=>{e()&&(clearInterval(s),clearTimeout(r),n())},200),r=setTimeout(()=>{clearInterval(s),o(new Error("Watch timeout \u2014 no file changes detected"))},t)})}function nA(e,{sampleRate:t=4}={}){let o=gl().sync.read(Js.readFileSync(e)),s=new Map;for(let u=0;u<o.height;u+=t)for(let d=0;d<o.width;d+=t){let f=(u*o.width+d)*4,p=o.data[f],h=o.data[f+1],m=o.data[f+2];if(o.data[f+3]<128)continue;let $=Math.round(p/8)*8,b=Math.round(h/8)*8,x=Math.round(m/8)*8,_=`${$},${b},${x}`;s.set(_,(s.get(_)||0)+1)}let r=[...s.entries()].sort((u,d)=>d[1]-u[1]).slice(0,20),i=r.reduce((u,d)=>u+d[1],0),a=r.map(([u,d])=>{let[f,p,h]=u.split(",").map(Number);return{hex:sA(f,p,h),rgb:`rgb(${f}, ${p}, ${h})`,frequency:parseFloat((d/i*100).toFixed(1)),category:oA(f,p,h)}}),c=rA(o);return{colors:a,spacing:c,dimensions:{width:o.width,height:o.height},imagePath:e}}function sA(e,t,n){return"#"+[e,t,n].map(o=>Math.min(255,o).toString(16).padStart(2,"0")).join("")}function oA(e,t,n){let o=(e*299+t*587+n*114)/1e3;return o>240?"white/background":o<30?"black/text":o<80?"dark":e>200&&t<100&&n<100?"red/danger":e<100&&t>150&&n<100?"green/success":e<100&&t<100&&n>200?"blue/primary":e>200&&t>200&&n<100?"yellow/warning":e>200&&t>100&&n<50?"orange/accent":o>200?"light/subtle":"midtone"}function rA(e){let t=[],n=!1,o=0,s=iA(e);for(let i=0;i<e.height;i++){let a=!0;for(let c=0;c<e.width;c+=4){let u=(i*e.width+c)*4;if(Math.abs(e.data[u]-s.r)>20||Math.abs(e.data[u+1]-s.g)>20||Math.abs(e.data[u+2]-s.b)>20){a=!1;break}}if(a&&n)n=!1,o=i;else if(!a&&!n&&(n=!0,o>0)){let c=i-o;c>=4&&c<=200&&t.push(c)}}let r=new Map;for(let i of t){let a=Math.round(i/4)*4;r.set(a,(r.get(a)||0)+1)}return[...r.entries()].sort((i,a)=>a[1]-i[1]).slice(0,8).map(([i,a])=>({px:i,occurrences:a}))}function iA(e){let t=[[0,0],[e.width-1,0],[0,e.height-1],[e.width-1,e.height-1]],n=0,o=0,s=0;for(let[r,i]of t){let a=(i*e.width+r)*4;n+=e.data[a],o+=e.data[a+1],s+=e.data[a+2]}return{r:Math.round(n/4),g:Math.round(o/4),b:Math.round(s/4)}}async function aA(e,t,{width:n,height:o=800,fullPage:s=!1,threshold:r=.1,timeout:i=3e4}={}){let{browserScreenshot:a}=Vs(),u=gl().sync.read(Js.readFileSync(t)),d=n||u.width,f=o||u.height,p=await a(e,{width:d,height:f,fullPage:s,timeout:i}),h=Af(t,p.path,{threshold:r}),m=bb(p.path,h.regionSummary.filter(g=>g.changedPercent>1).map((g,$)=>{let _=Math.ceil(h.width/3),E=Math.ceil(h.height/3),S=[["top-left","top-center","top-right"],["middle-left","center","middle-right"],["bottom-left","bottom-center","bottom-right"]],O=0,L=0;for(let I=0;I<3;I++)for(let D=0;D<3;D++)S[I][D]===g.name&&(O=D,L=I);return{type:"box",x:O*_+2,y:L*E+2,width:_-4,height:E-4,label:`${g.name}: ${g.changedPercent}%`,color:g.changedPercent>10?"#FF0000":"#FFAA00"}}));return{livePath:p.path,referencePath:t,diffPath:h.diffPath,annotatedPath:m.path,diffPercent:h.diffPercent,changedPixels:h.changedPixels,totalPixels:h.totalPixels,regions:h.regionSummary,liveBase64:p.base64,diffBase64:Js.readFileSync(h.diffPath).toString("base64"),annotatedBase64:m.base64}}wb.exports={pixelDiff:Af,responsiveSweep:zC,annotateImage:bb,visualWatch:ZC,extractDesignTokens:nA,designCompare:aA,DEFAULT_VIEWPORTS:$b}});var yl=Q((Nq,_b)=>{var{C:Et}=dt(),Hi="",pn=[],Wi=0,Vo=null;function cA(e){Vo=e}function lA(e,t){Hi=e,pn=[],Wi=0;for(let o of t){Wi++;let s=`t${Wi}`;pn.push({id:s,description:o.description||o.title||o.name||o.task||`Task ${Wi}`,status:"pending",dependsOn:o.depends_on||[],result:null})}let n=pn.map(o=>({...o}));return Vo&&Vo("create",{name:e,tasks:n}),n}function uA(e,t,n){let o=pn.find(s=>s.id===e);return o?(o.status=t,n!==void 0&&(o.result=n),Vo&&Vo("update",{id:e,status:t,result:n}),{...o}):null}function dA(){return{name:Hi,tasks:pn.map(e=>({...e}))}}function fA(){Hi="",pn=[],Wi=0,Vo&&Vo("clear",{})}function pA(){return pn.filter(e=>e.status!=="pending"?!1:e.dependsOn.length===0?!0:e.dependsOn.every(t=>{let n=pn.find(o=>o.id===t);return n&&n.status==="done"}))}function hA(){if(pn.length===0)return`${Et.dim}No active tasks${Et.reset}`;let e=[];Hi&&(e.push(` ${Et.bold}${Et.cyan}Tasks: ${Hi}${Et.reset}`),e.push(` ${Et.dim}${"\u2500".repeat(40)}${Et.reset}`));for(let s of pn){let r,i;switch(s.status){case"done":r="\u2713",i=Et.green;break;case"in_progress":r="\u2192",i=Et.cyan;break;case"failed":r="\u2717",i=Et.red;break;default:r="\xB7",i=Et.dim}let a=s.dependsOn.length>0?` ${Et.dim}(after: ${s.dependsOn.join(", ")})${Et.reset}`:"",c=`[${s.status}]`,u=s.description.length>50?s.description.substring(0,47)+"...":s.description;if(e.push(` ${i}${r}${Et.reset} ${Et.bold}${s.id}${Et.reset} ${u.padEnd(40)} ${i}${c}${Et.reset}${a}`),s.result&&s.status==="done"){let d=s.result.length>60?s.result.substring(0,57)+"...":s.result;e.push(` ${Et.dim}\u2192 ${d}${Et.reset}`)}}let t=pn.filter(s=>s.status==="done").length,n=pn.filter(s=>s.status==="failed").length,o=pn.length;return e.push(` ${Et.dim}${"\u2500".repeat(40)}${Et.reset}`),e.push(` ${Et.dim}${t}/${o} done${n>0?`, ${n} failed`:""}${Et.reset}`),e.join(`
293
+ ...(truncated)`:""),links:a.slice(0,20)}}finally{await s.close()}}async function L1(e,{width:t=1280,height:n=800,fullPage:o=!1,timeout:s=3e4}={}){let i=await(await pl()).newPage();try{await i.setViewportSize({width:t,height:n}),await i.goto(e,{waitUntil:"networkidle",timeout:s});let a=await i.screenshot({type:"png",fullPage:o}),c=require("os"),u=require("path"),d=require("fs"),f=u.join(c.tmpdir(),`nex-screenshot-${Date.now()}.png`);return d.writeFileSync(f,a,{mode:384}),{path:f,base64:a.toString("base64"),media_type:"image/png",title:await i.title(),url:i.url()}}finally{await i.close()}}async function I1(e,{selector:t,text:n,timeout:o=3e4}={}){if(!t&&!n)throw new Error("selector or text is required");let r=await(await pl()).newPage();try{await r.goto(e,{waitUntil:"domcontentloaded",timeout:o}),n?await r.getByText(n,{exact:!1}).first().click({timeout:1e4}):await r.locator(t).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 j1(e,{selector:t,value:n,submit:o=!1,timeout:s=3e4}={}){if(!t||n===void 0)throw new Error("selector and value are required");let i=await(await pl()).newPage();try{return await i.goto(e,{waitUntil:"domcontentloaded",timeout:s}),await i.fill(t,String(n)),o&&(await i.keyboard.press("Enter"),await i.waitForLoadState("domcontentloaded")),`Filled "${t}" with value. ${o?`Submitted \u2192 ${i.url()}`:"Not submitted."}`}finally{await i.close()}}h$.exports={isPlaywrightAvailable:f$,browserNavigate:N1,browserScreenshot:L1,browserClick:I1,browserFill:j1,closeBrowser:P1,INSTALL_MSG:d$}});var uf=Q((fq,g$)=>{"use strict";var D1=require("util"),m$=require("stream"),is=g$.exports=function(){m$.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};D1.inherits(is,m$);is.prototype.read=function(e,t){this._reads.push({length:Math.abs(e),allowLess:e<0,func:t}),process.nextTick(function(){this._process(),this._paused&&this._reads&&this._reads.length>0&&(this._paused=!1,this.emit("drain"))}.bind(this))};is.prototype.write=function(e,t){if(!this.writable)return this.emit("error",new Error("Stream not writable")),!1;let n;return Buffer.isBuffer(e)?n=e:n=Buffer.from(e,t||this._encoding),this._buffers.push(n),this._buffered+=n.length,this._process(),this._reads&&this._reads.length===0&&(this._paused=!0),this.writable&&!this._paused};is.prototype.end=function(e,t){e&&this.write(e,t),this.writable=!1,this._buffers&&(this._buffers.length===0?this._end():(this._buffers.push(null),this._process()))};is.prototype.destroySoon=is.prototype.end;is.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};is.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};is.prototype._processReadAllowingLess=function(e){this._reads.shift();let t=this._buffers[0];t.length>e.length?(this._buffered-=e.length,this._buffers[0]=t.slice(e.length),e.func.call(this,t.slice(0,e.length))):(this._buffered-=t.length,this._buffers.shift(),e.func.call(this,t))};is.prototype._processRead=function(e){this._reads.shift();let t=0,n=0,o=Buffer.alloc(e.length);for(;t<e.length;){let s=this._buffers[n++],r=Math.min(s.length,e.length-t);s.copy(o,t,0,r),t+=r,r!==s.length&&(this._buffers[--n]=s.slice(r))}n>0&&this._buffers.splice(0,n),this._buffered-=e.length,e.func.call(this,o)};is.prototype._process=function(){try{for(;this._buffered>0&&this._reads&&this._reads.length>0;){let e=this._reads[0];if(e.allowLess)this._processReadAllowingLess(e);else if(this._buffered>=e.length)this._processRead(e);else break}this._buffers&&!this.writable&&this._end()}catch(e){this.emit("error",e)}}});var ff=Q(df=>{"use strict";var ho=[{x:[0],y:[0]},{x:[4],y:[0]},{x:[0,4],y:[4]},{x:[2,6],y:[0,4]},{x:[0,2,4,6],y:[2,6]},{x:[1,3,5,7],y:[0,2,4,6]},{x:[0,1,2,3,4,5,6,7],y:[1,3,5,7]}];df.getImagePasses=function(e,t){let n=[],o=e%8,s=t%8,r=(e-o)/8,i=(t-s)/8;for(let a=0;a<ho.length;a++){let c=ho[a],u=r*c.x.length,d=i*c.y.length;for(let f=0;f<c.x.length&&c.x[f]<o;f++)u++;for(let f=0;f<c.y.length&&c.y[f]<s;f++)d++;u>0&&d>0&&n.push({width:u,height:d,index:a})}return n};df.getInterlaceIterator=function(e){return function(t,n,o){let s=t%ho[o].x.length,r=(t-s)/ho[o].x.length*8+ho[o].x[s],i=n%ho[o].y.length,a=(n-i)/ho[o].y.length*8+ho[o].y[i];return r*4+a*e*4}}});var pf=Q((hq,y$)=>{"use strict";y$.exports=function(t,n,o){let s=t+n-o,r=Math.abs(s-t),i=Math.abs(s-n),a=Math.abs(s-o);return r<=i&&r<=a?t:i<=a?n:o}});var hf=Q((mq,b$)=>{"use strict";var q1=ff(),F1=pf();function $$(e,t,n){let o=e*t;return n!==8&&(o=Math.ceil(o/(8/n))),o}var qr=b$.exports=function(e,t){let n=e.width,o=e.height,s=e.interlace,r=e.bpp,i=e.depth;if(this.read=t.read,this.write=t.write,this.complete=t.complete,this._imageIndex=0,this._images=[],s){let a=q1.getImagePasses(n,o);for(let c=0;c<a.length;c++)this._images.push({byteWidth:$$(a[c].width,r,i),height:a[c].height,lineIndex:0})}else this._images.push({byteWidth:$$(n,r,i),height:o,lineIndex:0});i===8?this._xComparison=r:i===16?this._xComparison=r*2:this._xComparison=1};qr.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};qr.prototype._unFilterType1=function(e,t,n){let o=this._xComparison,s=o-1;for(let r=0;r<n;r++){let i=e[1+r],a=r>s?t[r-o]:0;t[r]=i+a}};qr.prototype._unFilterType2=function(e,t,n){let o=this._lastLine;for(let s=0;s<n;s++){let r=e[1+s],i=o?o[s]:0;t[s]=r+i}};qr.prototype._unFilterType3=function(e,t,n){let o=this._xComparison,s=o-1,r=this._lastLine;for(let i=0;i<n;i++){let a=e[1+i],c=r?r[i]:0,u=i>s?t[i-o]:0,d=Math.floor((u+c)/2);t[i]=a+d}};qr.prototype._unFilterType4=function(e,t,n){let o=this._xComparison,s=o-1,r=this._lastLine;for(let i=0;i<n;i++){let a=e[1+i],c=r?r[i]:0,u=i>s?t[i-o]:0,d=i>s&&r?r[i-o]:0,f=F1(u,c,d);t[i]=a+f}};qr.prototype._reverseFilterLine=function(e){let t=e[0],n,o=this._images[this._imageIndex],s=o.byteWidth;if(t===0)n=e.slice(1,s+1);else switch(n=Buffer.alloc(s),t){case 1:this._unFilterType1(e,n,s);break;case 2:this._unFilterType2(e,n,s);break;case 3:this._unFilterType3(e,n,s);break;case 4:this._unFilterType4(e,n,s);break;default:throw new Error("Unrecognised filter type - "+t)}this.write(n),o.lineIndex++,o.lineIndex>=o.height?(this._lastLine=null,this._imageIndex++,o=this._images[this._imageIndex]):this._lastLine=n,o?this.read(o.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}});var k$=Q((gq,_$)=>{"use strict";var B1=require("util"),w$=uf(),U1=hf(),W1=_$.exports=function(e){w$.call(this);let t=[],n=this;this._filter=new U1(e,{read:this.read.bind(this),write:function(o){t.push(o)},complete:function(){n.emit("complete",Buffer.concat(t))}}),this._filter.start()};B1.inherits(W1,w$)});var Fr=Q((yq,x$)=>{"use strict";x$.exports={PNG_SIGNATURE:[137,80,78,71,13,10,26,10],TYPE_IHDR:1229472850,TYPE_IEND:1229278788,TYPE_IDAT:1229209940,TYPE_PLTE:1347179589,TYPE_tRNS:1951551059,TYPE_gAMA:1732332865,COLORTYPE_GRAYSCALE:0,COLORTYPE_PALETTE:1,COLORTYPE_COLOR:2,COLORTYPE_ALPHA:4,COLORTYPE_PALETTE_COLOR:3,COLORTYPE_COLOR_ALPHA:6,COLORTYPE_TO_BPP_MAP:{0:1,2:3,3:1,4:2,6:4},GAMMA_DIVISION:1e5}});var yf=Q(($q,v$)=>{"use strict";var mf=[];(function(){for(let e=0;e<256;e++){let t=e;for(let n=0;n<8;n++)t&1?t=3988292384^t>>>1:t=t>>>1;mf[e]=t}})();var gf=v$.exports=function(){this._crc=-1};gf.prototype.write=function(e){for(let t=0;t<e.length;t++)this._crc=mf[(this._crc^e[t])&255]^this._crc>>>8;return!0};gf.prototype.crc32=function(){return this._crc^-1};gf.crc32=function(e){let t=-1;for(let n=0;n<e.length;n++)t=mf[(t^e[n])&255]^t>>>8;return t^-1}});var $f=Q((bq,S$)=>{"use strict";var Bt=Fr(),H1=yf(),Ht=S$.exports=function(e,t){this._options=e,e.checkCRC=e.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[Bt.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[Bt.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[Bt.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[Bt.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[Bt.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[Bt.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=t.read,this.error=t.error,this.metadata=t.metadata,this.gamma=t.gamma,this.transColor=t.transColor,this.palette=t.palette,this.parsed=t.parsed,this.inflateData=t.inflateData,this.finished=t.finished,this.simpleTransparency=t.simpleTransparency,this.headersFinished=t.headersFinished||function(){}};Ht.prototype.start=function(){this.read(Bt.PNG_SIGNATURE.length,this._parseSignature.bind(this))};Ht.prototype._parseSignature=function(e){let t=Bt.PNG_SIGNATURE;for(let n=0;n<t.length;n++)if(e[n]!==t[n]){this.error(new Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};Ht.prototype._parseChunkBegin=function(e){let t=e.readUInt32BE(0),n=e.readUInt32BE(4),o="";for(let r=4;r<8;r++)o+=String.fromCharCode(e[r]);let s=!!(e[4]&32);if(!this._hasIHDR&&n!==Bt.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new H1,this._crc.write(Buffer.from(o)),this._chunks[n])return this._chunks[n](t);if(!s){this.error(new Error("Unsupported critical chunk type "+o));return}this.read(t+4,this._skipChunk.bind(this))};Ht.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};Ht.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};Ht.prototype._parseChunkEnd=function(e){let t=e.readInt32BE(0),n=this._crc.crc32();if(this._options.checkCRC&&n!==t){this.error(new Error("Crc error - "+t+" - "+n));return}this._hasIEND||this.read(8,this._parseChunkBegin.bind(this))};Ht.prototype._handleIHDR=function(e){this.read(e,this._parseIHDR.bind(this))};Ht.prototype._parseIHDR=function(e){this._crc.write(e);let t=e.readUInt32BE(0),n=e.readUInt32BE(4),o=e[8],s=e[9],r=e[10],i=e[11],a=e[12];if(o!==8&&o!==4&&o!==2&&o!==1&&o!==16){this.error(new Error("Unsupported bit depth "+o));return}if(!(s in Bt.COLORTYPE_TO_BPP_MAP)){this.error(new Error("Unsupported color type"));return}if(r!==0){this.error(new Error("Unsupported compression method"));return}if(i!==0){this.error(new Error("Unsupported filter method"));return}if(a!==0&&a!==1){this.error(new Error("Unsupported interlace method"));return}this._colorType=s;let c=Bt.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:t,height:n,depth:o,interlace:!!a,palette:!!(s&Bt.COLORTYPE_PALETTE),color:!!(s&Bt.COLORTYPE_COLOR),alpha:!!(s&Bt.COLORTYPE_ALPHA),bpp:c,colorType:s}),this._handleChunkEnd()};Ht.prototype._handlePLTE=function(e){this.read(e,this._parsePLTE.bind(this))};Ht.prototype._parsePLTE=function(e){this._crc.write(e);let t=Math.floor(e.length/3);for(let n=0;n<t;n++)this._palette.push([e[n*3],e[n*3+1],e[n*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};Ht.prototype._handleTRNS=function(e){this.simpleTransparency(),this.read(e,this._parseTRNS.bind(this))};Ht.prototype._parseTRNS=function(e){if(this._crc.write(e),this._colorType===Bt.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(new Error("Transparency chunk must be after palette"));return}if(e.length>this._palette.length){this.error(new Error("More transparent colors than palette size"));return}for(let t=0;t<e.length;t++)this._palette[t][3]=e[t];this.palette(this._palette)}this._colorType===Bt.COLORTYPE_GRAYSCALE&&this.transColor([e.readUInt16BE(0)]),this._colorType===Bt.COLORTYPE_COLOR&&this.transColor([e.readUInt16BE(0),e.readUInt16BE(2),e.readUInt16BE(4)]),this._handleChunkEnd()};Ht.prototype._handleGAMA=function(e){this.read(e,this._parseGAMA.bind(this))};Ht.prototype._parseGAMA=function(e){this._crc.write(e),this.gamma(e.readUInt32BE(0)/Bt.GAMMA_DIVISION),this._handleChunkEnd()};Ht.prototype._handleIDAT=function(e){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-e,this._parseIDAT.bind(this,e))};Ht.prototype._parseIDAT=function(e,t){if(this._crc.write(t),this._colorType===Bt.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw new Error("Expected palette not found");this.inflateData(t);let n=e-t.length;n>0?this._handleIDAT(n):this._handleChunkEnd()};Ht.prototype._handleIEND=function(e){this.read(e,this._parseIEND.bind(this))};Ht.prototype._parseIEND=function(e){this._crc.write(e),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var bf=Q(T$=>{"use strict";var E$=ff(),G1=[function(){},function(e,t,n,o){if(o===t.length)throw new Error("Ran out of data");let s=t[o];e[n]=s,e[n+1]=s,e[n+2]=s,e[n+3]=255},function(e,t,n,o){if(o+1>=t.length)throw new Error("Ran out of data");let s=t[o];e[n]=s,e[n+1]=s,e[n+2]=s,e[n+3]=t[o+1]},function(e,t,n,o){if(o+2>=t.length)throw new Error("Ran out of data");e[n]=t[o],e[n+1]=t[o+1],e[n+2]=t[o+2],e[n+3]=255},function(e,t,n,o){if(o+3>=t.length)throw new Error("Ran out of data");e[n]=t[o],e[n+1]=t[o+1],e[n+2]=t[o+2],e[n+3]=t[o+3]}],Y1=[function(){},function(e,t,n,o){let s=t[0];e[n]=s,e[n+1]=s,e[n+2]=s,e[n+3]=o},function(e,t,n){let o=t[0];e[n]=o,e[n+1]=o,e[n+2]=o,e[n+3]=t[1]},function(e,t,n,o){e[n]=t[0],e[n+1]=t[1],e[n+2]=t[2],e[n+3]=o},function(e,t,n){e[n]=t[0],e[n+1]=t[1],e[n+2]=t[2],e[n+3]=t[3]}];function z1(e,t){let n=[],o=0;function s(){if(o===e.length)throw new Error("Ran out of data");let r=e[o];o++;let i,a,c,u,d,f,p,h;switch(t){default:throw new Error("unrecognised depth");case 16:p=e[o],o++,n.push((r<<8)+p);break;case 4:p=r&15,h=r>>4,n.push(h,p);break;case 2:d=r&3,f=r>>2&3,p=r>>4&3,h=r>>6&3,n.push(h,p,f,d);break;case 1:i=r&1,a=r>>1&1,c=r>>2&1,u=r>>3&1,d=r>>4&1,f=r>>5&1,p=r>>6&1,h=r>>7&1,n.push(h,p,f,d,u,c,a,i);break}}return{get:function(r){for(;n.length<r;)s();let i=n.slice(0,r);return n=n.slice(r),i},resetAfterLine:function(){n.length=0},end:function(){if(o!==e.length)throw new Error("extra data found")}}}function K1(e,t,n,o,s,r){let i=e.width,a=e.height,c=e.index;for(let u=0;u<a;u++)for(let d=0;d<i;d++){let f=n(d,u,c);G1[o](t,s,f,r),r+=o}return r}function X1(e,t,n,o,s,r){let i=e.width,a=e.height,c=e.index;for(let u=0;u<a;u++){for(let d=0;d<i;d++){let f=s.get(o),p=n(d,u,c);Y1[o](t,f,p,r)}s.resetAfterLine()}}T$.dataToBitMap=function(e,t){let n=t.width,o=t.height,s=t.depth,r=t.bpp,i=t.interlace,a;s!==8&&(a=z1(e,s));let c;s<=8?c=Buffer.alloc(n*o*4):c=new Uint16Array(n*o*4);let u=Math.pow(2,s)-1,d=0,f,p;if(i)f=E$.getImagePasses(n,o),p=E$.getInterlaceIterator(n,o);else{let h=0;p=function(){let m=h;return h+=4,m},f=[{width:n,height:o}]}for(let h=0;h<f.length;h++)s===8?d=K1(f[h],c,p,r,e,d):X1(f[h],c,p,r,a,u);if(s===8){if(d!==e.length)throw new Error("extra data found")}else a.end();return c}});var wf=Q((_q,R$)=>{"use strict";function V1(e,t,n,o,s){let r=0;for(let i=0;i<o;i++)for(let a=0;a<n;a++){let c=s[e[r]];if(!c)throw new Error("index "+e[r]+" not in palette");for(let u=0;u<4;u++)t[r+u]=c[u];r+=4}}function J1(e,t,n,o,s){let r=0;for(let i=0;i<o;i++)for(let a=0;a<n;a++){let c=!1;if(s.length===1?s[0]===e[r]&&(c=!0):s[0]===e[r]&&s[1]===e[r+1]&&s[2]===e[r+2]&&(c=!0),c)for(let u=0;u<4;u++)t[r+u]=0;r+=4}}function Z1(e,t,n,o,s){let r=255,i=Math.pow(2,s)-1,a=0;for(let c=0;c<o;c++)for(let u=0;u<n;u++){for(let d=0;d<4;d++)t[a+d]=Math.floor(e[a+d]*r/i+.5);a+=4}}R$.exports=function(e,t,n=!1){let o=t.depth,s=t.width,r=t.height,i=t.colorType,a=t.transColor,c=t.palette,u=e;return i===3?V1(e,u,s,r,c):(a&&J1(e,u,s,r,a),o!==8&&!n&&(o===16&&(u=Buffer.alloc(s*r*4)),Z1(e,u,s,r,o))),u}});var O$=Q((kq,A$)=>{"use strict";var Q1=require("util"),_f=require("zlib"),C$=uf(),eC=k$(),tC=$f(),nC=bf(),sC=wf(),Rs=A$.exports=function(e){C$.call(this),this._parser=new tC(e,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,"gamma"),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this),simpleTransparency:this._simpleTransparency.bind(this),headersFinished:this._headersFinished.bind(this)}),this._options=e,this.writable=!0,this._parser.start()};Q1.inherits(Rs,C$);Rs.prototype._handleError=function(e){this.emit("error",e),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy&&this._inflate.destroy(),this._filter&&(this._filter.destroy(),this._filter.on("error",function(){})),this.errord=!0};Rs.prototype._inflateData=function(e){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=_f.createInflate(),this._inflate.on("error",this.emit.bind(this,"error")),this._filter.on("complete",this._complete.bind(this)),this._inflate.pipe(this._filter);else{let n=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,o=Math.max(n,_f.Z_MIN_CHUNK);this._inflate=_f.createInflate({chunkSize:o});let s=n,r=this.emit.bind(this,"error");this._inflate.on("error",function(a){s&&r(a)}),this._filter.on("complete",this._complete.bind(this));let i=this._filter.write.bind(this._filter);this._inflate.on("data",function(a){s&&(a.length>s&&(a=a.slice(0,s)),s-=a.length,i(a))}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(e)};Rs.prototype._handleMetaData=function(e){this._metaData=e,this._bitmapInfo=Object.create(e),this._filter=new eC(this._bitmapInfo)};Rs.prototype._handleTransColor=function(e){this._bitmapInfo.transColor=e};Rs.prototype._handlePalette=function(e){this._bitmapInfo.palette=e};Rs.prototype._simpleTransparency=function(){this._metaData.alpha=!0};Rs.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};Rs.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};Rs.prototype._complete=function(e){if(this.errord)return;let t;try{let n=nC.dataToBitMap(e,this._bitmapInfo);t=sC(n,this._bitmapInfo,this._options.skipRescale),n=null}catch(n){this._handleError(n);return}this.emit("parsed",t)}});var P$=Q((xq,M$)=>{"use strict";var Kn=Fr();M$.exports=function(e,t,n,o){let s=[Kn.COLORTYPE_COLOR_ALPHA,Kn.COLORTYPE_ALPHA].indexOf(o.colorType)!==-1;if(o.colorType===o.inputColorType){let m=(function(){let g=new ArrayBuffer(2);return new DataView(g).setInt16(0,256,!0),new Int16Array(g)[0]!==256})();if(o.bitDepth===8||o.bitDepth===16&&m)return e}let r=o.bitDepth!==16?e:new Uint16Array(e.buffer),i=255,a=Kn.COLORTYPE_TO_BPP_MAP[o.inputColorType];a===4&&!o.inputHasAlpha&&(a=3);let c=Kn.COLORTYPE_TO_BPP_MAP[o.colorType];o.bitDepth===16&&(i=65535,c*=2);let u=Buffer.alloc(t*n*c),d=0,f=0,p=o.bgColor||{};p.red===void 0&&(p.red=i),p.green===void 0&&(p.green=i),p.blue===void 0&&(p.blue=i);function h(){let m,g,y,b=i;switch(o.inputColorType){case Kn.COLORTYPE_COLOR_ALPHA:b=r[d+3],m=r[d],g=r[d+1],y=r[d+2];break;case Kn.COLORTYPE_COLOR:m=r[d],g=r[d+1],y=r[d+2];break;case Kn.COLORTYPE_ALPHA:b=r[d+1],m=r[d],g=m,y=m;break;case Kn.COLORTYPE_GRAYSCALE:m=r[d],g=m,y=m;break;default:throw new Error("input color type:"+o.inputColorType+" is not supported at present")}return o.inputHasAlpha&&(s||(b/=i,m=Math.min(Math.max(Math.round((1-b)*p.red+b*m),0),i),g=Math.min(Math.max(Math.round((1-b)*p.green+b*g),0),i),y=Math.min(Math.max(Math.round((1-b)*p.blue+b*y),0),i))),{red:m,green:g,blue:y,alpha:b}}for(let m=0;m<n;m++)for(let g=0;g<t;g++){let y=h(r,d);switch(o.colorType){case Kn.COLORTYPE_COLOR_ALPHA:case Kn.COLORTYPE_COLOR:o.bitDepth===8?(u[f]=y.red,u[f+1]=y.green,u[f+2]=y.blue,s&&(u[f+3]=y.alpha)):(u.writeUInt16BE(y.red,f),u.writeUInt16BE(y.green,f+2),u.writeUInt16BE(y.blue,f+4),s&&u.writeUInt16BE(y.alpha,f+6));break;case Kn.COLORTYPE_ALPHA:case Kn.COLORTYPE_GRAYSCALE:{let b=(y.red+y.green+y.blue)/3;o.bitDepth===8?(u[f]=b,s&&(u[f+1]=y.alpha)):(u.writeUInt16BE(b,f),s&&u.writeUInt16BE(y.alpha,f+2));break}default:throw new Error("unrecognised color Type "+o.colorType)}d+=a,f+=c}return u}});var I$=Q((vq,L$)=>{"use strict";var N$=pf();function oC(e,t,n,o,s){for(let r=0;r<n;r++)o[s+r]=e[t+r]}function rC(e,t,n){let o=0,s=t+n;for(let r=t;r<s;r++)o+=Math.abs(e[r]);return o}function iC(e,t,n,o,s,r){for(let i=0;i<n;i++){let a=i>=r?e[t+i-r]:0,c=e[t+i]-a;o[s+i]=c}}function aC(e,t,n,o){let s=0;for(let r=0;r<n;r++){let i=r>=o?e[t+r-o]:0,a=e[t+r]-i;s+=Math.abs(a)}return s}function cC(e,t,n,o,s){for(let r=0;r<n;r++){let i=t>0?e[t+r-n]:0,a=e[t+r]-i;o[s+r]=a}}function lC(e,t,n){let o=0,s=t+n;for(let r=t;r<s;r++){let i=t>0?e[r-n]:0,a=e[r]-i;o+=Math.abs(a)}return o}function uC(e,t,n,o,s,r){for(let i=0;i<n;i++){let a=i>=r?e[t+i-r]:0,c=t>0?e[t+i-n]:0,u=e[t+i]-(a+c>>1);o[s+i]=u}}function dC(e,t,n,o){let s=0;for(let r=0;r<n;r++){let i=r>=o?e[t+r-o]:0,a=t>0?e[t+r-n]:0,c=e[t+r]-(i+a>>1);s+=Math.abs(c)}return s}function fC(e,t,n,o,s,r){for(let i=0;i<n;i++){let a=i>=r?e[t+i-r]:0,c=t>0?e[t+i-n]:0,u=t>0&&i>=r?e[t+i-(n+r)]:0,d=e[t+i]-N$(a,c,u);o[s+i]=d}}function pC(e,t,n,o){let s=0;for(let r=0;r<n;r++){let i=r>=o?e[t+r-o]:0,a=t>0?e[t+r-n]:0,c=t>0&&r>=o?e[t+r-(n+o)]:0,u=e[t+r]-N$(i,a,c);s+=Math.abs(u)}return s}var hC={0:oC,1:iC,2:cC,3:uC,4:fC},mC={0:rC,1:aC,2:lC,3:dC,4:pC};L$.exports=function(e,t,n,o,s){let r;if(!("filterType"in o)||o.filterType===-1)r=[0,1,2,3,4];else if(typeof o.filterType=="number")r=[o.filterType];else throw new Error("unrecognised filter types");o.bitDepth===16&&(s*=2);let i=t*s,a=0,c=0,u=Buffer.alloc((i+1)*n),d=r[0];for(let f=0;f<n;f++){if(r.length>1){let p=1/0;for(let h=0;h<r.length;h++){let m=mC[r[h]](e,c,i,s);m<p&&(d=r[h],p=m)}}u[a]=d,a++,hC[d](e,c,i,u,a,s),a+=i,c+=i}return u}});var kf=Q((Sq,j$)=>{"use strict";var tn=Fr(),gC=yf(),yC=P$(),$C=I$(),bC=require("zlib"),mo=j$.exports=function(e){if(this._options=e,e.deflateChunkSize=e.deflateChunkSize||32*1024,e.deflateLevel=e.deflateLevel!=null?e.deflateLevel:9,e.deflateStrategy=e.deflateStrategy!=null?e.deflateStrategy:3,e.inputHasAlpha=e.inputHasAlpha!=null?e.inputHasAlpha:!0,e.deflateFactory=e.deflateFactory||bC.createDeflate,e.bitDepth=e.bitDepth||8,e.colorType=typeof e.colorType=="number"?e.colorType:tn.COLORTYPE_COLOR_ALPHA,e.inputColorType=typeof e.inputColorType=="number"?e.inputColorType:tn.COLORTYPE_COLOR_ALPHA,[tn.COLORTYPE_GRAYSCALE,tn.COLORTYPE_COLOR,tn.COLORTYPE_COLOR_ALPHA,tn.COLORTYPE_ALPHA].indexOf(e.colorType)===-1)throw new Error("option color type:"+e.colorType+" is not supported at present");if([tn.COLORTYPE_GRAYSCALE,tn.COLORTYPE_COLOR,tn.COLORTYPE_COLOR_ALPHA,tn.COLORTYPE_ALPHA].indexOf(e.inputColorType)===-1)throw new Error("option input color type:"+e.inputColorType+" is not supported at present");if(e.bitDepth!==8&&e.bitDepth!==16)throw new Error("option bit depth:"+e.bitDepth+" is not supported at present")};mo.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};mo.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};mo.prototype.filterData=function(e,t,n){let o=yC(e,t,n,this._options),s=tn.COLORTYPE_TO_BPP_MAP[this._options.colorType];return $C(o,t,n,this._options,s)};mo.prototype._packChunk=function(e,t){let n=t?t.length:0,o=Buffer.alloc(n+12);return o.writeUInt32BE(n,0),o.writeUInt32BE(e,4),t&&t.copy(o,8),o.writeInt32BE(gC.crc32(o.slice(4,o.length-4)),o.length-4),o};mo.prototype.packGAMA=function(e){let t=Buffer.alloc(4);return t.writeUInt32BE(Math.floor(e*tn.GAMMA_DIVISION),0),this._packChunk(tn.TYPE_gAMA,t)};mo.prototype.packIHDR=function(e,t){let n=Buffer.alloc(13);return n.writeUInt32BE(e,0),n.writeUInt32BE(t,4),n[8]=this._options.bitDepth,n[9]=this._options.colorType,n[10]=0,n[11]=0,n[12]=0,this._packChunk(tn.TYPE_IHDR,n)};mo.prototype.packIDAT=function(e){return this._packChunk(tn.TYPE_IDAT,e)};mo.prototype.packIEND=function(){return this._packChunk(tn.TYPE_IEND,null)}});var B$=Q((Eq,F$)=>{"use strict";var wC=require("util"),D$=require("stream"),_C=Fr(),kC=kf(),q$=F$.exports=function(e){D$.call(this);let t=e||{};this._packer=new kC(t),this._deflate=this._packer.createDeflate(),this.readable=!0};wC.inherits(q$,D$);q$.prototype.pack=function(e,t,n,o){this.emit("data",Buffer.from(_C.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(t,n)),o&&this.emit("data",this._packer.packGAMA(o));let s=this._packer.filterData(e,t,n);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(r){this.emit("data",this._packer.packIDAT(r))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(s)}});var z$=Q((Ui,Y$)=>{"use strict";var U$=require("assert").ok,Br=require("zlib"),xC=require("util"),W$=require("buffer").kMaxLength;function Ko(e){if(!(this instanceof Ko))return new Ko(e);e&&e.chunkSize<Br.Z_MIN_CHUNK&&(e.chunkSize=Br.Z_MIN_CHUNK),Br.Inflate.call(this,e),this._offset=this._offset===void 0?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,e&&e.maxLength!=null&&(this._maxLength=e.maxLength)}function vC(e){return new Ko(e)}function H$(e,t){t&&process.nextTick(t),e._handle&&(e._handle.close(),e._handle=null)}Ko.prototype._processChunk=function(e,t,n){if(typeof n=="function")return Br.Inflate._processChunk.call(this,e,t,n);let o=this,s=e&&e.length,r=this._chunkSize-this._offset,i=this._maxLength,a=0,c=[],u=0,d;this.on("error",function(m){d=m});function f(m,g){if(o._hadError)return;let y=r-g;if(U$(y>=0,"have should not go down"),y>0){let b=o._buffer.slice(o._offset,o._offset+y);if(o._offset+=y,b.length>i&&(b=b.slice(0,i)),c.push(b),u+=b.length,i-=b.length,i===0)return!1}return(g===0||o._offset>=o._chunkSize)&&(r=o._chunkSize,o._offset=0,o._buffer=Buffer.allocUnsafe(o._chunkSize)),g===0?(a+=s-m,s=m,!0):!1}U$(this._handle,"zlib binding closed");let p;do p=this._handle.writeSync(t,e,a,s,this._buffer,this._offset,r),p=p||this._writeState;while(!this._hadError&&f(p[0],p[1]));if(this._hadError)throw d;if(u>=W$)throw H$(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+W$.toString(16)+" bytes");let h=Buffer.concat(c,u);return H$(this),h};xC.inherits(Ko,Br.Inflate);function SC(e,t){if(typeof t=="string"&&(t=Buffer.from(t)),!(t instanceof Buffer))throw new TypeError("Not a string or buffer");let n=e._finishFlushFlag;return n==null&&(n=Br.Z_FINISH),e._processChunk(t,n)}function G$(e,t){return SC(new Ko(t),e)}Y$.exports=Ui=G$;Ui.Inflate=Ko;Ui.createInflate=vC;Ui.inflateSync=G$});var xf=Q((Tq,X$)=>{"use strict";var K$=X$.exports=function(e){this._buffer=e,this._reads=[]};K$.prototype.read=function(e,t){this._reads.push({length:Math.abs(e),allowLess:e<0,func:t})};K$.prototype.process=function(){for(;this._reads.length>0&&this._buffer.length;){let e=this._reads[0];if(this._buffer.length&&(this._buffer.length>=e.length||e.allowLess)){this._reads.shift();let t=this._buffer;this._buffer=t.slice(e.length),e.func.call(this,t.slice(0,e.length))}else break}if(this._reads.length>0)throw new Error("There are some read requests waitng on finished stream");if(this._buffer.length>0)throw new Error("unrecognised content at end of stream")}});var J$=Q(V$=>{"use strict";var EC=xf(),TC=hf();V$.process=function(e,t){let n=[],o=new EC(e);return new TC(t,{read:o.read.bind(o),write:function(r){n.push(r)},complete:function(){}}).start(),o.process(),Buffer.concat(n)}});var tb=Q((Cq,eb)=>{"use strict";var Z$=!0,Q$=require("zlib"),RC=z$();Q$.deflateSync||(Z$=!1);var CC=xf(),AC=J$(),OC=$f(),MC=bf(),PC=wf();eb.exports=function(e,t){if(!Z$)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n;function o(E){n=E}let s;function r(E){s=E}function i(E){s.transColor=E}function a(E){s.palette=E}function c(){s.alpha=!0}let u;function d(E){u=E}let f=[];function p(E){f.push(E)}let h=new CC(e);if(new OC(t,{read:h.read.bind(h),error:o,metadata:r,gamma:d,palette:a,transColor:i,inflateData:p,simpleTransparency:c}).start(),h.process(),n)throw n;let g=Buffer.concat(f);f.length=0;let y;if(s.interlace)y=Q$.inflateSync(g);else{let S=((s.width*s.bpp*s.depth+7>>3)+1)*s.height;y=RC(g,{chunkSize:S,maxLength:S})}if(g=null,!y||!y.length)throw new Error("bad png - invalid inflate data response");let b=AC.process(y,s);g=null;let x=MC.dataToBitMap(b,s);b=null;let _=PC(x,s,t.skipRescale);return s.data=_,s.gamma=u||0,s}});var rb=Q((Aq,ob)=>{"use strict";var nb=!0,sb=require("zlib");sb.deflateSync||(nb=!1);var NC=Fr(),LC=kf();ob.exports=function(e,t){if(!nb)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n=t||{},o=new LC(n),s=[];s.push(Buffer.from(NC.PNG_SIGNATURE)),s.push(o.packIHDR(e.width,e.height)),e.gamma&&s.push(o.packGAMA(e.gamma));let r=o.filterData(e.data,e.width,e.height),i=sb.deflateSync(r,o.getDeflateOptions());if(r=null,!i||!i.length)throw new Error("bad png - invalid compressed data response");return s.push(o.packIDAT(i)),s.push(o.packIEND()),Buffer.concat(s)}});var ib=Q(vf=>{"use strict";var IC=tb(),jC=rb();vf.read=function(e,t){return IC(e,t||{})};vf.write=function(e,t){return jC(e,t)}});var lb=Q(cb=>{"use strict";var DC=require("util"),ab=require("stream"),qC=O$(),FC=B$(),BC=ib(),fn=cb.PNG=function(e){ab.call(this),e=e||{},this.width=e.width|0,this.height=e.height|0,this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null,e.fill&&this.data&&this.data.fill(0),this.gamma=0,this.readable=this.writable=!0,this._parser=new qC(e),this._parser.on("error",this.emit.bind(this,"error")),this._parser.on("close",this._handleClose.bind(this)),this._parser.on("metadata",this._metadata.bind(this)),this._parser.on("gamma",this._gamma.bind(this)),this._parser.on("parsed",function(t){this.data=t,this.emit("parsed",t)}.bind(this)),this._packer=new FC(e),this._packer.on("data",this.emit.bind(this,"data")),this._packer.on("end",this.emit.bind(this,"end")),this._parser.on("close",this._handleClose.bind(this)),this._packer.on("error",this.emit.bind(this,"error"))};DC.inherits(fn,ab);fn.sync=BC;fn.prototype.pack=function(){return!this.data||!this.data.length?(this.emit("error","No data provided"),this):(process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this)),this)};fn.prototype.parse=function(e,t){if(t){let n,o;n=function(s){this.removeListener("error",o),this.data=s,t(null,this)}.bind(this),o=function(s){this.removeListener("parsed",n),t(s,null)}.bind(this),this.once("parsed",n),this.once("error",o)}return this.end(e),this};fn.prototype.write=function(e){return this._parser.write(e),!0};fn.prototype.end=function(e){this._parser.end(e)};fn.prototype._metadata=function(e){this.width=e.width,this.height=e.height,this.emit("metadata",e)};fn.prototype._gamma=function(e){this.gamma=e};fn.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};fn.bitblt=function(e,t,n,o,s,r,i,a){if(n|=0,o|=0,s|=0,r|=0,i|=0,a|=0,n>e.width||o>e.height||n+s>e.width||o+r>e.height)throw new Error("bitblt reading outside image");if(i>t.width||a>t.height||i+s>t.width||a+r>t.height)throw new Error("bitblt writing outside image");for(let c=0;c<r;c++)e.data.copy(t.data,(a+c)*t.width+i<<2,(o+c)*e.width+n<<2,(o+c)*e.width+n+s<<2)};fn.prototype.bitblt=function(e,t,n,o,s,r,i){return fn.bitblt(this,e,t,n,o,s,r,i),this};fn.adjustGamma=function(e){if(e.gamma){for(let t=0;t<e.height;t++)for(let n=0;n<e.width;n++){let o=e.width*t+n<<2;for(let s=0;s<3;s++){let r=e.data[o+s]/255;r=Math.pow(r,1/2.2/e.gamma),e.data[o+s]=Math.round(r*255)}}e.gamma=0}};fn.prototype.adjustGamma=function(){fn.adjustGamma(this)}});var hb={};Fv(hb,{default:()=>fb});function fb(e,t,n,o,s,r={}){let{threshold:i=.1,alpha:a=.1,aaColor:c=[255,255,0],diffColor:u=[255,0,0],includeAA:d,diffColorAlt:f,diffMask:p}=r;if(!Sf(e)||!Sf(t)||n&&!Sf(n))throw new Error("Image data: Uint8Array, Uint8ClampedArray or Buffer expected.");if(e.length!==t.length||n&&n.length!==e.length)throw new Error("Image sizes do not match.");if(e.length!==o*s*4)throw new Error("Image data size does not match width/height.");let h=o*s,m=new Uint32Array(e.buffer,e.byteOffset,h),g=new Uint32Array(t.buffer,t.byteOffset,h),y=!0;for(let X=0;X<h;X++)if(m[X]!==g[X]){y=!1;break}if(y){if(n&&!p)for(let X=0;X<h;X++)db(e,4*X,a,n);return 0}let b=35215*i*i,[x,_,E]=c,[S,O,L]=u,[I,D,Z]=f||u,K=0;for(let X=0;X<s;X++)for(let Fe=0;Fe<o;Fe++){let Oe=X*o+Fe,V=Oe*4,re=m[Oe]===g[Oe]?0:pb(e,t,V,V,!1);if(Math.abs(re)>b){let rt=ub(e,Fe,X,o,s,m,g)||ub(t,Fe,X,o,s,g,m);!d&&rt?n&&!p&&ml(n,V,x,_,E):(n&&(re<0?ml(n,V,I,D,Z):ml(n,V,S,O,L)),K++)}else n&&!p&&db(e,V,a,n)}return K}function Sf(e){return ArrayBuffer.isView(e)&&e.BYTES_PER_ELEMENT===1}function ub(e,t,n,o,s,r,i){let a=Math.max(t-1,0),c=Math.max(n-1,0),u=Math.min(t+1,o-1),d=Math.min(n+1,s-1),f=n*o+t,p=t===a||t===u||n===c||n===d?1:0,h=0,m=0,g=0,y=0,b=0,x=0;for(let _=a;_<=u;_++)for(let E=c;E<=d;E++){if(_===t&&E===n)continue;let S=pb(e,e,f*4,(E*o+_)*4,!0);if(S===0){if(p++,p>2)return!1}else S<h?(h=S,g=_,y=E):S>m&&(m=S,b=_,x=E)}return h===0||m===0?!1:hl(r,g,y,o,s)&&hl(i,g,y,o,s)||hl(r,b,x,o,s)&&hl(i,b,x,o,s)}function hl(e,t,n,o,s){let r=Math.max(t-1,0),i=Math.max(n-1,0),a=Math.min(t+1,o-1),c=Math.min(n+1,s-1),u=e[n*o+t],d=t===r||t===a||n===i||n===c?1:0;for(let f=r;f<=a;f++)for(let p=i;p<=c;p++)if(!(f===t&&p===n)&&(d+=+(u===e[p*o+f]),d>2))return!0;return!1}function pb(e,t,n,o,s){let r=e[n],i=e[n+1],a=e[n+2],c=e[n+3],u=t[o],d=t[o+1],f=t[o+2],p=t[o+3],h=r-u,m=i-d,g=a-f,y=c-p;if(!h&&!m&&!g&&!y)return 0;if(c<255||p<255){let S=48+159*(n%2),O=48+159*((n/1.618033988749895|0)%2),L=48+159*((n/2.618033988749895|0)%2);h=(r*c-u*p-S*y)/255,m=(i*c-d*p-O*y)/255,g=(a*c-f*p-L*y)/255}let b=h*.29889531+m*.58662247+g*.11448223;if(s)return b;let x=h*.59597799-m*.2741761-g*.32180189,_=h*.21147017-m*.52261711+g*.31114694,E=.5053*b*b+.299*x*x+.1957*_*_;return b>0?-E:E}function ml(e,t,n,o,s){e[t+0]=n,e[t+1]=o,e[t+2]=s,e[t+3]=255}function db(e,t,n,o){let s=255+(e[t]*.29889531+e[t+1]*.58662247+e[t+2]*.11448223-255)*n*e[t+3]/255;ml(o,t,s,s,s)}var mb=qv(()=>{});var Xo=Q((Pq,wb)=>{var Js=require("fs"),UC=require("path"),WC=require("os"),HC="nex-visual-";function yb(e){return UC.join(WC.tmpdir(),`${HC}${Date.now()}-${e}`)}var Ef=null;function gl(){return Ef||(Ef=lb().PNG),Ef}var Tf=null;function GC(){if(!Tf){let e=(mb(),Uv(hb));Tf=e.default||e}return Tf}function Af(e,t,{threshold:n=.1}={}){let o=gl(),s=GC(),r=o.sync.read(Js.readFileSync(e)),i=o.sync.read(Js.readFileSync(t)),a=Math.max(r.width,i.width),c=Math.max(r.height,i.height),u=gb(r,a,c),d=gb(i,a,c),f=new o({width:a,height:c}),p=s(u,d,f.data,a,c,{threshold:n,includeAA:!1}),h=a*c,m=(p/h*100).toFixed(1),g=YC(f.data,a,c,3,3),y=yb("diff.png");return Js.writeFileSync(y,o.sync.write(f),{mode:384}),{diffPath:y,diffPercent:parseFloat(m),totalPixels:h,changedPixels:p,regionSummary:g,beforePath:e,afterPath:t,width:a,height:c}}function gb(e,t,n){if(e.width===t&&e.height===n)return e.data;let o=Buffer.alloc(t*n*4,0);for(let s=0;s<e.height;s++){let r=s*e.width*4,i=s*t*4;e.data.copy(o,i,r,r+e.width*4)}return o}function YC(e,t,n,o,s){let r=[["top-left","top-center","top-right"],["middle-left","center","middle-right"],["bottom-left","bottom-center","bottom-right"]],i=Math.ceil(t/o),a=Math.ceil(n/s),c=[];for(let u=0;u<s;u++)for(let d=0;d<o;d++){let f=0,p=0,h=d*i,m=u*a,g=Math.min(h+i,t),y=Math.min(m+a,n);for(let b=m;b<y;b++)for(let x=h;x<g;x++){p++;let _=(b*t+x)*4;(e[_]>0||e[_+1]>0)&&f++}if(f>0){let b=(f/p*100).toFixed(1),x=r[u]&&r[u][d]?r[u][d]:`row${u}-col${d}`;c.push({name:x,changedPercent:parseFloat(b),changed:f,total:p})}}return c.sort((u,d)=>d.changedPercent-u.changedPercent),c}var $b=[{width:320,label:"mobile-sm"},{width:768,label:"tablet"},{width:1024,label:"desktop-sm"},{width:1440,label:"desktop"},{width:1920,label:"desktop-lg"}];async function zC(e,{viewports:t=$b,height:n=800,fullPage:o=!1,timeout:s=3e4}={}){let{browserScreenshot:r}=Vs(),i=[];for(let a of t){let c=await r(e,{width:a.width,height:n,fullPage:o,timeout:s});i.push({label:a.label,width:a.width,path:c.path,base64:c.base64,media_type:c.media_type})}return i}function bb(e,t=[]){let n=gl(),o=n.sync.read(Js.readFileSync(e));for(let i of t){let a=KC(i.color||"#FF0000");i.type==="box"?(XC(o,i.x||0,i.y||0,i.width||50,i.height||50,a,i.thickness||3),i.label&&Cf(o,i.x||0,(i.y||0)-14,i.label,a)):i.type==="arrow"?(VC(o,i.x||0,i.y||0,i.toX||i.x+50,i.toY||i.y,a,i.thickness||3),i.label&&Cf(o,i.x||0,(i.y||0)-14,i.label,a)):i.type==="circle"&&(JC(o,i.x||0,i.y||0,i.radius||20,a,i.thickness||3),i.label&&Cf(o,(i.x||0)-(i.radius||20),(i.y||0)-(i.radius||20)-14,i.label,a))}let s=yb("annotated.png");Js.writeFileSync(s,n.sync.write(o),{mode:384});let r=Js.readFileSync(s).toString("base64");return{path:s,base64:r,media_type:"image/png"}}function KC(e){let t=e.replace("#","");return{r:parseInt(t.substring(0,2),16),g:parseInt(t.substring(2,4),16),b:parseInt(t.substring(4,6),16),a:255}}function Cs(e,t,n,o){if(t<0||n<0||t>=e.width||n>=e.height)return;let s=(n*e.width+t)*4;e.data[s]=o.r,e.data[s+1]=o.g,e.data[s+2]=o.b,e.data[s+3]=o.a}function XC(e,t,n,o,s,r,i=3){for(let a=0;a<i;a++){for(let c=0;c<o;c++)Cs(e,t+c,n+a,r),Cs(e,t+c,n+s-1-a,r);for(let c=0;c<s;c++)Cs(e,t+a,n+c,r),Cs(e,t+o-1-a,n+c,r)}}function Rf(e,t,n,o,s,r,i=3){let a=Math.abs(o-t),c=Math.abs(s-n),u=t<o?1:-1,d=n<s?1:-1,f=a-c,p=t,h=n;for(;;){let m=Math.floor(i/2);for(let y=-m;y<=m;y++)for(let b=-m;b<=m;b++)Cs(e,p+y,h+b,r);if(p===o&&h===s)break;let g=2*f;g>-c&&(f-=c,p+=u),g<a&&(f+=a,h+=d)}}function VC(e,t,n,o,s,r,i=3){Rf(e,t,n,o,s,r,i);let a=Math.atan2(s-n,o-t),c=15,u=a+Math.PI*.8,d=a-Math.PI*.8;Rf(e,o,s,Math.round(o+c*Math.cos(u)),Math.round(s+c*Math.sin(u)),r,i),Rf(e,o,s,Math.round(o+c*Math.cos(d)),Math.round(s+c*Math.sin(d)),r,i)}function JC(e,t,n,o,s,r=3){for(let i=0;i<r;i++){let a=o-i;for(let c=0;c<360;c+=.5){let u=c*Math.PI/180,d=Math.round(t+a*Math.cos(u)),f=Math.round(n+a*Math.sin(u));Cs(e,d,f,s)}}}function Cf(e,t,n,o,s){let i=o.length*6+4,a=12;for(let c=0;c<a;c++)for(let u=0;u<i;u++)Cs(e,t+u,n+c,{r:0,g:0,b:0,a:200});for(let c=0;c<i;c++)Cs(e,t+c,n+a-1,s),Cs(e,t+c,n+a-2,s);for(let c=0;c<o.length;c++){let u=t+2+c*6;for(let d=2;d<9;d++)for(let f=0;f<4;f++)Cs(e,u+f,n+d,s)}}async function*ZC(e,t,{maxIterations:n=20,hmrDelay:o=1500,width:s=1280,height:r=800,timeout:i=3e4}={}){let{browserScreenshot:a}=Vs(),c=QC("chokidar"),u=await a(e,{width:s,height:r,timeout:i});if(yield{iteration:0,type:"baseline",path:u.path,base64:u.base64,media_type:u.media_type},!c){yield{iteration:-1,type:"error",message:"chokidar not installed \u2014 watch mode requires it. Install with: npm install chokidar"};return}let d=0,f=!1,p=c.watch(t,{ignoreInitial:!0,ignored:/(node_modules|\.git|dist)/});p.on("change",()=>{f=!0});try{for(;d<n;){await tA(()=>f,3e5),f=!1,d++,await eA(o);let h=await a(e,{width:s,height:r,timeout:i}),m=null;try{m=Af(u.path,h.path)}catch{}u=h,yield{iteration:d,type:"change",path:h.path,base64:h.base64,media_type:h.media_type,diff:m?{diffPath:m.diffPath,diffPercent:m.diffPercent,changedPixels:m.changedPixels,regions:m.regionSummary}:null}}}finally{await p.close()}}function QC(e){try{return require(e)}catch{return null}}function eA(e){return new Promise(t=>setTimeout(t,e))}function tA(e,t=6e4){return new Promise((n,o)=>{let s=setInterval(()=>{e()&&(clearInterval(s),clearTimeout(r),n())},200),r=setTimeout(()=>{clearInterval(s),o(new Error("Watch timeout \u2014 no file changes detected"))},t)})}function nA(e,{sampleRate:t=4}={}){let o=gl().sync.read(Js.readFileSync(e)),s=new Map;for(let u=0;u<o.height;u+=t)for(let d=0;d<o.width;d+=t){let f=(u*o.width+d)*4,p=o.data[f],h=o.data[f+1],m=o.data[f+2];if(o.data[f+3]<128)continue;let y=Math.round(p/8)*8,b=Math.round(h/8)*8,x=Math.round(m/8)*8,_=`${y},${b},${x}`;s.set(_,(s.get(_)||0)+1)}let r=[...s.entries()].sort((u,d)=>d[1]-u[1]).slice(0,20),i=r.reduce((u,d)=>u+d[1],0),a=r.map(([u,d])=>{let[f,p,h]=u.split(",").map(Number);return{hex:sA(f,p,h),rgb:`rgb(${f}, ${p}, ${h})`,frequency:parseFloat((d/i*100).toFixed(1)),category:oA(f,p,h)}}),c=rA(o);return{colors:a,spacing:c,dimensions:{width:o.width,height:o.height},imagePath:e}}function sA(e,t,n){return"#"+[e,t,n].map(o=>Math.min(255,o).toString(16).padStart(2,"0")).join("")}function oA(e,t,n){let o=(e*299+t*587+n*114)/1e3;return o>240?"white/background":o<30?"black/text":o<80?"dark":e>200&&t<100&&n<100?"red/danger":e<100&&t>150&&n<100?"green/success":e<100&&t<100&&n>200?"blue/primary":e>200&&t>200&&n<100?"yellow/warning":e>200&&t>100&&n<50?"orange/accent":o>200?"light/subtle":"midtone"}function rA(e){let t=[],n=!1,o=0,s=iA(e);for(let i=0;i<e.height;i++){let a=!0;for(let c=0;c<e.width;c+=4){let u=(i*e.width+c)*4;if(Math.abs(e.data[u]-s.r)>20||Math.abs(e.data[u+1]-s.g)>20||Math.abs(e.data[u+2]-s.b)>20){a=!1;break}}if(a&&n)n=!1,o=i;else if(!a&&!n&&(n=!0,o>0)){let c=i-o;c>=4&&c<=200&&t.push(c)}}let r=new Map;for(let i of t){let a=Math.round(i/4)*4;r.set(a,(r.get(a)||0)+1)}return[...r.entries()].sort((i,a)=>a[1]-i[1]).slice(0,8).map(([i,a])=>({px:i,occurrences:a}))}function iA(e){let t=[[0,0],[e.width-1,0],[0,e.height-1],[e.width-1,e.height-1]],n=0,o=0,s=0;for(let[r,i]of t){let a=(i*e.width+r)*4;n+=e.data[a],o+=e.data[a+1],s+=e.data[a+2]}return{r:Math.round(n/4),g:Math.round(o/4),b:Math.round(s/4)}}async function aA(e,t,{width:n,height:o=800,fullPage:s=!1,threshold:r=.1,timeout:i=3e4}={}){let{browserScreenshot:a}=Vs(),u=gl().sync.read(Js.readFileSync(t)),d=n||u.width,f=o||u.height,p=await a(e,{width:d,height:f,fullPage:s,timeout:i}),h=Af(t,p.path,{threshold:r}),m=bb(p.path,h.regionSummary.filter(g=>g.changedPercent>1).map((g,y)=>{let _=Math.ceil(h.width/3),E=Math.ceil(h.height/3),S=[["top-left","top-center","top-right"],["middle-left","center","middle-right"],["bottom-left","bottom-center","bottom-right"]],O=0,L=0;for(let I=0;I<3;I++)for(let D=0;D<3;D++)S[I][D]===g.name&&(O=D,L=I);return{type:"box",x:O*_+2,y:L*E+2,width:_-4,height:E-4,label:`${g.name}: ${g.changedPercent}%`,color:g.changedPercent>10?"#FF0000":"#FFAA00"}}));return{livePath:p.path,referencePath:t,diffPath:h.diffPath,annotatedPath:m.path,diffPercent:h.diffPercent,changedPixels:h.changedPixels,totalPixels:h.totalPixels,regions:h.regionSummary,liveBase64:p.base64,diffBase64:Js.readFileSync(h.diffPath).toString("base64"),annotatedBase64:m.base64}}wb.exports={pixelDiff:Af,responsiveSweep:zC,annotateImage:bb,visualWatch:ZC,extractDesignTokens:nA,designCompare:aA,DEFAULT_VIEWPORTS:$b}});var yl=Q((Nq,_b)=>{var{C:Et}=dt(),Hi="",pn=[],Wi=0,Vo=null;function cA(e){Vo=e}function lA(e,t){Hi=e,pn=[],Wi=0;for(let o of t){Wi++;let s=`t${Wi}`;pn.push({id:s,description:o.description||o.title||o.name||o.task||`Task ${Wi}`,status:"pending",dependsOn:o.depends_on||[],result:null})}let n=pn.map(o=>({...o}));return Vo&&Vo("create",{name:e,tasks:n}),n}function uA(e,t,n){let o=pn.find(s=>s.id===e);return o?(o.status=t,n!==void 0&&(o.result=n),Vo&&Vo("update",{id:e,status:t,result:n}),{...o}):null}function dA(){return{name:Hi,tasks:pn.map(e=>({...e}))}}function fA(){Hi="",pn=[],Wi=0,Vo&&Vo("clear",{})}function pA(){return pn.filter(e=>e.status!=="pending"?!1:e.dependsOn.length===0?!0:e.dependsOn.every(t=>{let n=pn.find(o=>o.id===t);return n&&n.status==="done"}))}function hA(){if(pn.length===0)return`${Et.dim}No active tasks${Et.reset}`;let e=[];Hi&&(e.push(` ${Et.bold}${Et.cyan}Tasks: ${Hi}${Et.reset}`),e.push(` ${Et.dim}${"\u2500".repeat(40)}${Et.reset}`));for(let s of pn){let r,i;switch(s.status){case"done":r="\u2713",i=Et.green;break;case"in_progress":r="\u2192",i=Et.cyan;break;case"failed":r="\u2717",i=Et.red;break;default:r="\xB7",i=Et.dim}let a=s.dependsOn.length>0?` ${Et.dim}(after: ${s.dependsOn.join(", ")})${Et.reset}`:"",c=`[${s.status}]`,u=s.description.length>50?s.description.substring(0,47)+"...":s.description;if(e.push(` ${i}${r}${Et.reset} ${Et.bold}${s.id}${Et.reset} ${u.padEnd(40)} ${i}${c}${Et.reset}${a}`),s.result&&s.status==="done"){let d=s.result.length>60?s.result.substring(0,57)+"...":s.result;e.push(` ${Et.dim}\u2192 ${d}${Et.reset}`)}}let t=pn.filter(s=>s.status==="done").length,n=pn.filter(s=>s.status==="failed").length,o=pn.length;return e.push(` ${Et.dim}${"\u2500".repeat(40)}${Et.reset}`),e.push(` ${Et.dim}${t}/${o} done${n>0?`, ${n} failed`:""}${Et.reset}`),e.join(`
294
294
  `)}function mA(){return pn.length>0&&pn.some(e=>e.status==="pending"||e.status==="in_progress")}_b.exports={createTasks:lA,updateTask:uA,getTaskList:dA,clearTasks:fA,getReadyTasks:pA,renderTaskList:hA,setOnChange:cA,hasActiveTasks:mA}});var $l=Q((Lq,xb)=>{var Gi={"devstral-2":{staleWarn:6e4,staleAbort:18e4,investigationCap:18,postEditCap:10,briefing:`You are devstral-2, a strong coding model optimized for agentic tasks.
295
295
  Use tools confidently and without hesitation \u2014 tool use is the expected workflow.
296
296
  You excel at sysadmin, frontend, and multi-step coding tasks.
@@ -341,7 +341,7 @@ ${o}`,_compacted:!0,_originalCount:e.length},tokensRemoved:r-i})}catch{return Jo
341
341
  tools: ${s}`}return`[${n}] ${o}`}).join(`
342
342
 
343
343
  `)}Cb.exports={compactMessages:wA,formatMessagesForSummary:Rb,resetCompactionFailures:_A,COMPACTION_ENABLED:vb,COMPACTION_MIN_MESSAGES:Sb,COMPACTION_SUMMARY_BUDGET:Eb,MAX_CONSECUTIVE_FAILURES:Tb}});var Mn=Q((jq,qb)=>{var kA=require("path");function Ob(){return ft().getActiveModel()}var xA={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},vA={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},Zo=new Map,Ab=1e3,Pf=new WeakMap,Qo=null;function SA(){if(Qo!==null)return Qo;try{let e=Ob(),t=e?.provider||"ollama",n=(e?.id||"").toLowerCase();for(let[o,s]of Object.entries(vA))if(n.startsWith(o))return Qo=s,Qo;return Qo=xA[t]||4,Qo}catch{return 4}}function EA(){Qo=null}function er(e){if(!e)return 0;typeof e!="string"&&(e=JSON.stringify(e));let t=e.length<=120?e:`${e.length}:${e.substring(0,60)}:${e.substring(e.length>>1,(e.length>>1)+30)}:${e.substring(e.length-30)}`,n=Zo.get(t);if(n!==void 0)return Zo.delete(t),Zo.set(t,n),n;let o=Math.ceil(e.length/SA());if(Zo.size>=Ab){let s=Ab>>1,r=Zo.keys();for(let i=0;i<s;i++)Zo.delete(r.next().value)}return Zo.set(t,o),o}function TA(e){if(Pf.has(e))return Pf.get(e);let t=JSON.stringify(e);return Pf.set(e,t),t}function go(e){let n=4;if(e.content&&(n+=er(e.content)),e.tool_calls)for(let o of e.tool_calls){n+=4,n+=er(o.function?.name||"");let s=o.function?.arguments;typeof s=="string"?n+=er(s):s&&(n+=er(JSON.stringify(s)))}return n}function Xn(e){let t=0;for(let n of e)t+=go(n);return t}function RA(e,t){if(e&&e.length===t.length){let r=!1;for(let i=0;i<t.length;i++)if(e[i]!==t[i]){r=!0;break}if(!r)return 0}let n=e?e.length:0,o=t.length,s=0;for(let r=n;r<o;r++)s+=go(t[r]);return s}var Nf=new WeakMap;function bl(e){if(!e||e.length===0)return 0;if(Nf.has(e))return Nf.get(e);let t=er(JSON.stringify(e));return Nf.set(e,t),t}function wl(){return Ob()?.contextWindow||32768}var hn={msgCount:-1,lastMsgRef:null,toolCount:-1,result:null,messagesRef:null,messageTokens:0,systemTokens:0,conversationTokens:0,toolResultTokens:0};function CA(e,t){let n=e.length>0?e[e.length-1]:null,o=t?t.length:0;if(hn.result&&e.length===hn.msgCount&&n===hn.lastMsgRef&&o===hn.toolCount)return hn.result;let s,r,i,a;if(hn.messagesRef===e&&e.length>hn.msgCount&&hn.msgCount>=0){s=hn.messageTokens,r=hn.systemTokens,i=hn.conversationTokens,a=hn.toolResultTokens;for(let h=hn.msgCount;h<e.length;h++){let m=go(e[h]);s+=m,e[h].role==="system"?r+=m:e[h].role==="tool"?a+=m:i+=m}}else{s=0,r=0,i=0,a=0;for(let h of e){let m=go(h);s+=m,h.role==="system"?r+=m:h.role==="tool"?a+=m:i+=m}}let c=bl(t),u=s+c,d=wl(),f=d>0?u/d*100:0,p={used:u,limit:d,percentage:Math.round(f*10)/10,breakdown:{system:r,conversation:i,toolResults:a,toolDefinitions:c},messageCount:e.length};return hn={msgCount:e.length,lastMsgRef:n,toolCount:o,result:p,messagesRef:e,messageTokens:s,systemTokens:r,conversationTokens:i,toolResultTokens:a},p}var Yi=parseFloat(process.env.NEX_COMPRESSION_THRESHOLD)||.75,Mb=parseFloat(process.env.NEX_SAFETY_MARGIN)||.1,Pb=parseInt(process.env.NEX_KEEP_RECENT,10)||10,Nb={essential:.6,standard:.65,full:Math.min(Yi,.75)};function Lb(){if(process.env.NEX_COMPRESSION_THRESHOLD)return Yi;try{let{getActiveTier:e}=Fi(),t=e();return Nb[t]??Yi}catch{return Yi}}var AA=200,OA=1e3;function Ib(e,t){if(!e||e.length<=t)return e;let o=/^(ERROR|EXIT|BLOCKED|CANCELLED)/i.test(e)?t*3:t;if(e.length<=o)return e;let s=e.split(`
344
- `);if(s.length<=10){let m=Math.floor(o*.6),g=Math.floor(o*.4),$=e.substring(0,m),b=e.substring(e.length-g);return $+`
344
+ `);if(s.length<=10){let m=Math.floor(o*.6),g=Math.floor(o*.4),y=e.substring(0,m),b=e.substring(e.length-g);return y+`
345
345
  ...(${e.length} chars total)...
346
346
  `+b}let r=Math.floor(s.length*.4),i=Math.floor(s.length*.4),a=[],c=0,u=Math.floor(o*.4);for(let m=0;m<r&&c<u;m++)if(c+s[m].length+1>u&&s[m].trim().startsWith("```")){a.push(s[m]),c+=s[m].length+1;let g=m+1;for(;g<s.length&&c<u*1.5&&!s[g].trim().startsWith("```");)a.push(s[g]),c+=s[g].length+1,g++;g<s.length&&s[g].trim().startsWith("```")&&(a.push(s[g]),c+=s[g].length+1),m=g}else a.push(s[m]),c+=s[m].length+1;let d=[],f=0,p=Math.floor(o*.4);for(let m=s.length-1;m>=s.length-i&&f<p;m--)if(f+s[m].length+1>p&&s[m].trim().startsWith("```")){d.push(s[m]),f+=s[m].length+1;let g=m-1;for(;g>=0&&f<p*1.5&&!s[g].trim().startsWith("```");)d.push(s[g]),f+=s[g].length+1,g--;g>=0&&s[g].trim().startsWith("```")&&(d.push(s[g]),f+=s[g].length+1),m=g}else d.push(s[m]),f+=s[m].length+1;d.reverse();let h=s.length-a.length-d.length;return a.join(`
347
347
  `)+`
@@ -352,14 +352,14 @@ ${o}`,_compacted:!0,_originalCount:e.length},tokensRemoved:r-i})}catch{return Jo
352
352
  `+s.map(r=>`- ${r}`).join(`
353
353
  `)),o.length===0?null:{role:"system",content:`## Progress State (preserved through compression)
354
354
  ${o.join(`
355
- `)}`,_pinned:!0,_progressSnapshot:!0}}var Ur={msgCount:-1,lastMsgRef:null,result:null};function PA(){Ur={msgCount:-1,lastMsgRef:null,result:null},hn={msgCount:-1,lastMsgRef:null,toolCount:-1,result:null,messagesRef:null,messageTokens:0,systemTokens:0,conversationTokens:0,toolResultTokens:0}}async function NA(e,t,n={}){let o=e.length>0?e[e.length-1]:null;if(!n.force&&Ur.result&&e.length===Ur.msgCount&&o===Ur.lastMsgRef)return Ur.result;let s=n.threshold??Lb(),r=n.safetyMargin??Mb,i=n.keepRecent??Pb,a=wl(),c=bl(t),u=Math.floor(a*(s-r)),d=u-c,f=Xn(e);if(f+c<=u){let K={messages:e,compressed:!1,compacted:!1,tokensRemoved:0};return Ur={msgCount:e.length,lastMsgRef:o,result:K},K}let h=f,m=null,g=0;e.length>0&&e[0].role==="system"&&(m=e[0],g=1);let $=Math.max(g,e.length-i),b=e.slice(g,$),x=e.slice($),_=b.map(K=>Wr(K,"light")),E=Zs(m,_,x),S=Xn(E);if(S+c<=u)return{messages:E,compressed:!0,compacted:!1,tokensRemoved:h-S};if(_=b.map(K=>Wr(K,"medium")),E=Zs(m,_,x),S=Xn(E),S+c<=u)return{messages:E,compressed:!0,compacted:!1,tokensRemoved:h-S};if(_=b.map(K=>Wr(K,"aggressive")),E=Zs(m,_,x),S=Xn(E),S+c<=u)return{messages:E,compressed:!0,compacted:!1,tokensRemoved:h-S};let O=process.env.NEX_SKIP_COMPACTOR==="1",L=b.filter(K=>K._pinned),I=b.filter(K=>!K._compacted&&!K._pinned);if(!O&&I.length>=6)try{let{compactMessages:K}=Mf(),X=await K(I);if(X){let Fe=b.filter(rt=>rt._compacted&&!rt._pinned),Oe=[...L,...Fe,X.message],V=Zs(m,Oe,x),re=Xn(V);if(re+c<=u)return{messages:V,compressed:!0,compacted:!0,tokensRemoved:h-re};b=Oe}}catch(K){process.env.NEX_DEBUG&&console.error("[context-engine] LLM compacting failed:",K.message)}let D=Db([..._,...x]),Z=_.map((K,X)=>({msg:K,score:K._pinned?1/0:jb(K,X,_.length,D),tokens:go(K)}));for(;Z.length>0&&S>d;){let K=-1;for(let X=0;X<Z.length;X++)Z[X].score!==1/0&&(K===-1||Z[X].score<Z[K].score)&&(K=X);if(K===-1)break;S-=Z[K].tokens,Z.splice(K,1)}return _=Z.map(K=>K.msg),E=Zs(m,_,x),S=Xn(E),{messages:E,compressed:!0,compacted:!1,tokensRemoved:h-S}}function Zs(e,t,n){let o=[];return e&&o.push(e),o.push(...t,...n),o}function LA(e,t){if(!e)return"";if(er(e)<=t)return e;let o=t*4,s=e.split(`
355
+ `)}`,_pinned:!0,_progressSnapshot:!0}}var Ur={msgCount:-1,lastMsgRef:null,result:null};function PA(){Ur={msgCount:-1,lastMsgRef:null,result:null},hn={msgCount:-1,lastMsgRef:null,toolCount:-1,result:null,messagesRef:null,messageTokens:0,systemTokens:0,conversationTokens:0,toolResultTokens:0}}async function NA(e,t,n={}){let o=e.length>0?e[e.length-1]:null;if(!n.force&&Ur.result&&e.length===Ur.msgCount&&o===Ur.lastMsgRef)return Ur.result;let s=n.threshold??Lb(),r=n.safetyMargin??Mb,i=n.keepRecent??Pb,a=wl(),c=bl(t),u=Math.floor(a*(s-r)),d=u-c,f=Xn(e);if(f+c<=u){let K={messages:e,compressed:!1,compacted:!1,tokensRemoved:0};return Ur={msgCount:e.length,lastMsgRef:o,result:K},K}let h=f,m=null,g=0;e.length>0&&e[0].role==="system"&&(m=e[0],g=1);let y=Math.max(g,e.length-i),b=e.slice(g,y),x=e.slice(y),_=b.map(K=>Wr(K,"light")),E=Zs(m,_,x),S=Xn(E);if(S+c<=u)return{messages:E,compressed:!0,compacted:!1,tokensRemoved:h-S};if(_=b.map(K=>Wr(K,"medium")),E=Zs(m,_,x),S=Xn(E),S+c<=u)return{messages:E,compressed:!0,compacted:!1,tokensRemoved:h-S};if(_=b.map(K=>Wr(K,"aggressive")),E=Zs(m,_,x),S=Xn(E),S+c<=u)return{messages:E,compressed:!0,compacted:!1,tokensRemoved:h-S};let O=process.env.NEX_SKIP_COMPACTOR==="1",L=b.filter(K=>K._pinned),I=b.filter(K=>!K._compacted&&!K._pinned);if(!O&&I.length>=6)try{let{compactMessages:K}=Mf(),X=await K(I);if(X){let Fe=b.filter(rt=>rt._compacted&&!rt._pinned),Oe=[...L,...Fe,X.message],V=Zs(m,Oe,x),re=Xn(V);if(re+c<=u)return{messages:V,compressed:!0,compacted:!0,tokensRemoved:h-re};b=Oe}}catch(K){process.env.NEX_DEBUG&&console.error("[context-engine] LLM compacting failed:",K.message)}let D=Db([..._,...x]),Z=_.map((K,X)=>({msg:K,score:K._pinned?1/0:jb(K,X,_.length,D),tokens:go(K)}));for(;Z.length>0&&S>d;){let K=-1;for(let X=0;X<Z.length;X++)Z[X].score!==1/0&&(K===-1||Z[X].score<Z[K].score)&&(K=X);if(K===-1)break;S-=Z[K].tokens,Z.splice(K,1)}return _=Z.map(K=>K.msg),E=Zs(m,_,x),S=Xn(E),{messages:E,compressed:!0,compacted:!1,tokensRemoved:h-S}}function Zs(e,t,n){let o=[];return e&&o.push(e),o.push(...t,...n),o}function LA(e,t){if(!e)return"";if(er(e)<=t)return e;let o=t*4,s=e.split(`
356
356
  `),r=Math.floor(o*.6),i=Math.floor(o*.4),a="",c=0;for(let h of s){if(a.length+h.length+1>r)break;a+=(a?`
357
357
  `:"")+h,c++}let u="",d=0;for(let h=s.length-1;h>=c;h--){let m=s[h]+(u?`
358
358
  `:"")+u;if(m.length>i)break;u=m,d++}let p=`
359
359
 
360
360
  ... (${s.length-c-d} lines omitted, ${s.length} total) ...
361
361
 
362
- `;return a+p+u}var IA=6;function jA(e,t,n=!1){let o=wl(),s=bl(t),r=Math.floor(o*(n?.35:.5))-s,i=Xn(e),a=Math.floor(i*(n?.5:.8));r>a&&(r=a);let c=null,u=0;e.length>0&&e[0].role==="system"&&(c=e[0],u=1);let d=n?2:IA,f=Math.max(u,e.length-d),p=e.slice(u,f),h=e.slice(f),m=p;n&&(h=h.map(S=>Wr(S,"aggressive")));let g=Zs(c,m,h),$=Xn(g);for(;m.length>0&&$>r;){let S=m.shift();$-=go(S)}if(!n&&$>r&&m.length>0)for(m=m.map(S=>Wr(S,"aggressive")),g=Zs(c,m,h),$=Xn(g);m.length>0&&$>r;){let S=m.shift();$-=go(S)}n&&$>r&&(h=h.filter(O=>O.role==="user").slice(-1),g=Zs(c,[],h),$=Xn(g)),g=Zs(c,m,h);let b=e.filter(S=>S.role==="user"),x=S=>{let O=typeof S.content=="string"?S.content:"";return O.startsWith("[SYSTEM WARNING]")||O.startsWith("[SYSTEM:")||O.startsWith("BLOCKED:")},_=b.find(S=>!x(S)),E=[...b].reverse().find(S=>!x(S));if(_&&!g.find(S=>S===_)){let S=g.findIndex(L=>L.role==="system"),O=S>=0?S+1:0;g.splice(O,0,_)}return E&&E!==_&&!g.find(S=>S===E)&&g.push(E),{messages:g,tokensRemoved:i-Xn(g)}}qb.exports={estimateTokens:er,estimateMessageTokens:go,estimateMessagesTokens:Xn,estimateDeltaTokens:RA,estimateToolsTokens:bl,serializeMessage:TA,getContextWindow:wl,getUsage:CA,compressMessage:Wr,compressToolResult:Ib,scoreMessageRelevance:jb,extractActiveFiles:Db,buildProgressSnapshot:MA,fitToContext:NA,forceCompress:jA,truncateFileContent:LA,invalidateTokenRatioCache:EA,invalidateFitToContextCache:PA,getEffectiveCompressionThreshold:Lb,COMPRESSION_THRESHOLD:Yi,TIER_COMPRESSION_THRESHOLDS:Nb,SAFETY_MARGIN:Mb,KEEP_RECENT:Pb}});var Gr=Q((Dq,Fb)=>{var{fork:DA}=require("child_process"),qA=require("path"),FA=qA.join(__dirname,"background-worker.js"),tr=new Map,Hr=new Map;function BA(){return`bg-${Date.now()}-${Math.random().toString(36).slice(2,6)}`}function UA(e){let t=BA(),n=DA(FA,[],{silent:!0,env:process.env,cwd:process.cwd()});return n.send({jobId:t,agentDef:e}),n.on("message",o=>{o.type==="result"?Lf(t,e,o.payload):o.type==="error"&&Lf(t,e,{task:e.task,status:"failed",result:`Background agent error: ${o.error}`,toolsUsed:[],tokensUsed:{input:0,output:0}})}),n.on("exit",(o,s)=>{if(tr.has(t)){let r=s?`killed (${s})`:`exit code ${o}`;Lf(t,e,{task:e.task,status:"failed",result:`Background agent terminated unexpectedly: ${r}`,toolsUsed:[],tokensUsed:{input:0,output:0}})}}),tr.set(t,{process:n,agentDef:e,startedAt:Date.now()}),t}function Lf(e,t,n){tr.delete(e),Hr.set(e,{jobId:e,agentDef:t,result:n,finishedAt:Date.now()})}function WA(){if(Hr.size===0)return[];let e=[...Hr.values()];return Hr.clear(),e}function HA(){return tr.size>0||Hr.size>0}function GA(){let e=tr.size;return e===0?"":`${e} bg agent${e===1?"":"s"} running`}function YA(){for(let[e,t]of tr){try{t.process.kill("SIGTERM")}catch{}tr.delete(e)}Hr.clear()}Fb.exports={createJob:UA,getCompletedJobs:WA,getPendingJobSummary:GA,hasPendingOrCompletedJobs:HA,cancelAllJobs:YA}});var Sl=Q((Fq,aw)=>{var{callStream:zA,getActiveProviderName:kl,getActiveModelId:Bb,getConfiguredProviders:KA,getProvider:Ub,getActiveProvider:Wb,parseModelSpec:Hb}=ft(),{parseToolArgs:Gb}=Go(),{filterToolsForModel:XA,getModelTier:_l}=Fi(),{getModelBriefing:VA}=$l(),{trackUsage:Yb,estimateTokens:zb}=os(),{MultiProgress:JA,C:qq}=dt();function Kb(e){return!e||typeof e!="string"?0:typeof zb=="function"?zb(e):Math.ceil(e.length/4)}var Jb=15,ZA=parseInt(process.env.NEX_MAX_PARALLEL||"10",10),Xb=parseInt(process.env.NEX_MAX_CHAT_RETRIES||"3",10),Zb=8,QA=2,xl=new Map,Qb=600*1e3;function eO(e,t){let n=xl.get(e);return n&&n.agentId!==t&&Date.now()-n.timestamp<Qb?!1:(xl.set(e,{agentId:t,timestamp:Date.now()}),!0)}function zi(e){xl.delete(e)}function If(){xl.clear()}function jf(e){let t=(e.message||"").toLowerCase(),n=e.code||"";return t.includes("429")||t.includes("rate limit")?"rate_limit":t.includes("401")||t.includes("403")||t.includes("unauthorized")||t.includes("forbidden")?"auth":t.includes("context")&&(t.includes("too long")||t.includes("overflow")||t.includes("maximum"))||t.includes("400")&&(t.includes("content")||t.includes("length"))?"context_overflow":t.includes("500")||t.includes("502")||t.includes("503")||t.includes("504")?"server":t.includes("timed out")||t.includes("timeout")?"timeout":n==="ECONNRESET"||n==="ECONNABORTED"||n==="ETIMEDOUT"||n==="ECONNREFUSED"||n==="ENOTFOUND"||t.includes("socket disconnected")||t.includes("tls")||t.includes("econnreset")||t.includes("fetch failed")||t.includes("etimedout")||t.includes("enotfound")?"network":"unknown"}function ew(e){let t=jf(e);return t==="rate_limit"||t==="server"||t==="network"||t==="timeout"}async function tw(e,t,n){let o;for(let s=0;s<=Xb;s++)try{return await zA(e,t,n)}catch(r){o=r;let i=jf(r);if(i==="auth")throw r.message=`Authentication failed \u2014 check your API key or permissions. (${r.message})`,r;if(i==="context_overflow")throw r.message=`Context window exceeded \u2014 reduce message history or use a model with a larger context. (${r.message})`,r;if(s<Xb&&ew(r)){let c=i==="rate_limit"?Math.min(2e3*Math.pow(2,s),15e3):Math.min(500*Math.pow(2,s),4e3);await new Promise(u=>setTimeout(u,c).unref());continue}throw r}throw o}var Vb=new Set(["ask_user","task_list"]);function nw(e){return e>=2?new Set([...Vb,"spawn_agents"]):Vb}var tO=new Set(["write_file","edit_file","patch_file"]),sw={explore:{allowedTools:new Set(["bash","read_file","list_directory","glob","grep","search_files","web_fetch","web_search"]),systemSuffix:"You are an exploration agent. Read and search code only. Do NOT modify any files."},review:{allowedTools:new Set(["read_file","list_directory","glob","grep","search_files"]),systemSuffix:'You are a code review agent. Read code and report findings only. Do NOT make changes. Output findings first, ordered by severity, using this format: "Finding: <title> | Severity: <high|medium|low> | File: <path[:line]> | Why: <impact>". After findings, add one short "Residual risk:" line. If there are no findings, say "No material findings" and still mention the main residual risk/test gap.'},implement:{allowedTools:null,systemSuffix:""}},nO=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,sO=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function ow(e){return sO.test(e)?"full":nO.test(e)?"essential":e.length>300?"full":"standard"}function rw(e){let t=KA(),n=kl(),o=[...t].sort((s,r)=>(s.name===n?-1:1)-(r.name===n?-1:1));for(let s of o)for(let r of s.models)if(_l(r.id,s.name)===e)return{provider:s.name,model:r.id};return null}var oO={essential:process.env.NEX_FAST_MODEL||null,standard:process.env.NEX_STANDARD_MODEL||null,full:process.env.NEX_HEAVY_MODEL||null};function vl(e){if(e.model){let{provider:s,model:r}=Hb(e.model),i=s?Ub(s):Wb(),a=s||kl();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let c=_l(r,a);return{provider:a,model:r,tier:c}}}let t=ow(e.task),n=oO[t];if(n){let{provider:s,model:r}=Hb(n),i=s?Ub(s):Wb(),a=s||kl();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let c=_l(r,a);return{provider:a,model:r,tier:c}}}let o=rw(t);if(o){let s=_l(o.model,o.provider);return{provider:o.provider,model:o.model,tier:s}}return{provider:null,model:null,tier:null}}async function iw(e,t={},n=0){let o=n===0?Jb:Zb,s=Math.min(e.max_iterations||10,o),r=`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,i=[],a={input:0,output:0},c=new Set,u=new Map,d=e._systemPrompt||`You are a focused sub-agent. Complete this specific task efficiently.
362
+ `;return a+p+u}var IA=6;function jA(e,t,n=!1){let o=wl(),s=bl(t),r=Math.floor(o*(n?.35:.5))-s,i=Xn(e),a=Math.floor(i*(n?.5:.8));r>a&&(r=a);let c=null,u=0;e.length>0&&e[0].role==="system"&&(c=e[0],u=1);let d=n?2:IA,f=Math.max(u,e.length-d),p=e.slice(u,f),h=e.slice(f),m=p;n&&(h=h.map(S=>Wr(S,"aggressive")));let g=Zs(c,m,h),y=Xn(g);for(;m.length>0&&y>r;){let S=m.shift();y-=go(S)}if(!n&&y>r&&m.length>0)for(m=m.map(S=>Wr(S,"aggressive")),g=Zs(c,m,h),y=Xn(g);m.length>0&&y>r;){let S=m.shift();y-=go(S)}n&&y>r&&(h=h.filter(O=>O.role==="user").slice(-1),g=Zs(c,[],h),y=Xn(g)),g=Zs(c,m,h);let b=e.filter(S=>S.role==="user"),x=S=>{let O=typeof S.content=="string"?S.content:"";return O.startsWith("[SYSTEM WARNING]")||O.startsWith("[SYSTEM:")||O.startsWith("BLOCKED:")},_=b.find(S=>!x(S)),E=[...b].reverse().find(S=>!x(S));if(_&&!g.find(S=>S===_)){let S=g.findIndex(L=>L.role==="system"),O=S>=0?S+1:0;g.splice(O,0,_)}return E&&E!==_&&!g.find(S=>S===E)&&g.push(E),{messages:g,tokensRemoved:i-Xn(g)}}qb.exports={estimateTokens:er,estimateMessageTokens:go,estimateMessagesTokens:Xn,estimateDeltaTokens:RA,estimateToolsTokens:bl,serializeMessage:TA,getContextWindow:wl,getUsage:CA,compressMessage:Wr,compressToolResult:Ib,scoreMessageRelevance:jb,extractActiveFiles:Db,buildProgressSnapshot:MA,fitToContext:NA,forceCompress:jA,truncateFileContent:LA,invalidateTokenRatioCache:EA,invalidateFitToContextCache:PA,getEffectiveCompressionThreshold:Lb,COMPRESSION_THRESHOLD:Yi,TIER_COMPRESSION_THRESHOLDS:Nb,SAFETY_MARGIN:Mb,KEEP_RECENT:Pb}});var Gr=Q((Dq,Fb)=>{var{fork:DA}=require("child_process"),qA=require("path"),FA=qA.join(__dirname,"background-worker.js"),tr=new Map,Hr=new Map;function BA(){return`bg-${Date.now()}-${Math.random().toString(36).slice(2,6)}`}function UA(e){let t=BA(),n=DA(FA,[],{silent:!0,env:process.env,cwd:process.cwd()});return n.send({jobId:t,agentDef:e}),n.on("message",o=>{o.type==="result"?Lf(t,e,o.payload):o.type==="error"&&Lf(t,e,{task:e.task,status:"failed",result:`Background agent error: ${o.error}`,toolsUsed:[],tokensUsed:{input:0,output:0}})}),n.on("exit",(o,s)=>{if(tr.has(t)){let r=s?`killed (${s})`:`exit code ${o}`;Lf(t,e,{task:e.task,status:"failed",result:`Background agent terminated unexpectedly: ${r}`,toolsUsed:[],tokensUsed:{input:0,output:0}})}}),tr.set(t,{process:n,agentDef:e,startedAt:Date.now()}),t}function Lf(e,t,n){tr.delete(e),Hr.set(e,{jobId:e,agentDef:t,result:n,finishedAt:Date.now()})}function WA(){if(Hr.size===0)return[];let e=[...Hr.values()];return Hr.clear(),e}function HA(){return tr.size>0||Hr.size>0}function GA(){let e=tr.size;return e===0?"":`${e} bg agent${e===1?"":"s"} running`}function YA(){for(let[e,t]of tr){try{t.process.kill("SIGTERM")}catch{}tr.delete(e)}Hr.clear()}Fb.exports={createJob:UA,getCompletedJobs:WA,getPendingJobSummary:GA,hasPendingOrCompletedJobs:HA,cancelAllJobs:YA}});var Sl=Q((Fq,aw)=>{var{callStream:zA,getActiveProviderName:kl,getActiveModelId:Bb,getConfiguredProviders:KA,getProvider:Ub,getActiveProvider:Wb,parseModelSpec:Hb}=ft(),{parseToolArgs:Gb}=Go(),{filterToolsForModel:XA,getModelTier:_l}=Fi(),{getModelBriefing:VA}=$l(),{trackUsage:Yb,estimateTokens:zb}=os(),{MultiProgress:JA,C:qq}=dt();function Kb(e){return!e||typeof e!="string"?0:typeof zb=="function"?zb(e):Math.ceil(e.length/4)}var Jb=15,ZA=parseInt(process.env.NEX_MAX_PARALLEL||"10",10),Xb=parseInt(process.env.NEX_MAX_CHAT_RETRIES||"3",10),Zb=8,QA=2,xl=new Map,Qb=600*1e3;function eO(e,t){let n=xl.get(e);return n&&n.agentId!==t&&Date.now()-n.timestamp<Qb?!1:(xl.set(e,{agentId:t,timestamp:Date.now()}),!0)}function zi(e){xl.delete(e)}function If(){xl.clear()}function jf(e){let t=(e.message||"").toLowerCase(),n=e.code||"";return t.includes("429")||t.includes("rate limit")?"rate_limit":t.includes("401")||t.includes("403")||t.includes("unauthorized")||t.includes("forbidden")?"auth":t.includes("context")&&(t.includes("too long")||t.includes("overflow")||t.includes("maximum"))||t.includes("400")&&(t.includes("content")||t.includes("length"))?"context_overflow":t.includes("500")||t.includes("502")||t.includes("503")||t.includes("504")?"server":t.includes("timed out")||t.includes("timeout")?"timeout":n==="ECONNRESET"||n==="ECONNABORTED"||n==="ETIMEDOUT"||n==="ECONNREFUSED"||n==="ENOTFOUND"||t.includes("socket disconnected")||t.includes("tls")||t.includes("econnreset")||t.includes("fetch failed")||t.includes("etimedout")||t.includes("enotfound")?"network":"unknown"}function ew(e){let t=jf(e);return t==="rate_limit"||t==="server"||t==="network"||t==="timeout"}async function tw(e,t,n){let o;for(let s=0;s<=Xb;s++)try{return await zA(e,t,n)}catch(r){o=r;let i=jf(r);if(i==="auth")throw r.message=`Authentication failed \u2014 check your API key or permissions. (${r.message})`,r;if(i==="context_overflow")throw r.message=`Context window exceeded \u2014 reduce message history or use a model with a larger context. (${r.message})`,r;if(s<Xb&&ew(r)){let c=i==="rate_limit"?Math.min(2e3*Math.pow(2,s),15e3):Math.min(500*Math.pow(2,s),4e3);await new Promise(u=>setTimeout(u,c).unref());continue}throw r}throw o}var Vb=new Set(["ask_user","task_list"]);function nw(e){return e>=2?new Set([...Vb,"spawn_agents"]):Vb}var tO=new Set(["write_file","edit_file","patch_file"]),sw={explore:{allowedTools:new Set(["bash","read_file","list_directory","glob","grep","search_files","web_fetch","web_search"]),systemSuffix:"You are an exploration agent. Read and search code only. Do NOT modify any files."},review:{allowedTools:new Set(["read_file","list_directory","glob","grep","search_files"]),systemSuffix:'You are a code review agent. Read code and report findings only. Do NOT make changes. Output findings first, ordered by severity, using this format: "Finding: <title> | Severity: <high|medium|low> | File: <path[:line]> | Why: <impact>". After findings, add one short "Residual risk:" line. If there are no findings, say "No material findings" and still mention the main residual risk/test gap.'},implement:{allowedTools:null,systemSuffix:""}},nO=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,sO=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function ow(e){return sO.test(e)?"full":nO.test(e)?"essential":e.length>300?"full":"standard"}function rw(e){let t=KA(),n=kl(),o=[...t].sort((s,r)=>(s.name===n?-1:1)-(r.name===n?-1:1));for(let s of o)for(let r of s.models)if(_l(r.id,s.name)===e)return{provider:s.name,model:r.id};return null}var oO={essential:process.env.NEX_FAST_MODEL||null,standard:process.env.NEX_STANDARD_MODEL||null,full:process.env.NEX_HEAVY_MODEL||null};function vl(e){if(e.model){let{provider:s,model:r}=Hb(e.model),i=s?Ub(s):Wb(),a=s||kl();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let c=_l(r,a);return{provider:a,model:r,tier:c}}}let t=ow(e.task),n=oO[t];if(n){let{provider:s,model:r}=Hb(n),i=s?Ub(s):Wb(),a=s||kl();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let c=_l(r,a);return{provider:a,model:r,tier:c}}}let o=rw(t);if(o){let s=_l(o.model,o.provider);return{provider:o.provider,model:o.model,tier:s}}return{provider:null,model:null,tier:null}}async function iw(e,t={},n=0){let o=n===0?Jb:Zb,s=Math.min(e.max_iterations||10,o),r=`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,i=[],a={input:0,output:0},c=new Set,u=new Map,d=e._systemPrompt||`You are a focused sub-agent. Complete this specific task efficiently.
363
363
 
364
364
  TASK: ${e.task}
365
365
  ${e.context?`
@@ -387,14 +387,14 @@ ERROR RECOVERY:
387
387
  - If bash fails: read the error, fix the root cause, then retry.
388
388
  - After 2 failed attempts at the same operation, summarize the issue and stop.`,f=e.type&&sw[e.type],p=f&&f.systemSuffix?`
389
389
 
390
- ${f.systemSuffix}`:"",h=vl(e),m=h.provider,g=h.model,$=h.tier,b=VA(g||Bb()),_=[{role:"system",content:(b?`## Model Briefing
390
+ ${f.systemSuffix}`:"",h=vl(e),m=h.provider,g=h.model,y=h.tier,b=VA(g||Bb()),_=[{role:"system",content:(b?`## Model Briefing
391
391
  ${b}
392
392
 
393
393
  ---
394
394
 
395
- `:"")+d+p}];_.push({role:"user",content:e.task});let{TOOL_DEFINITIONS:E,executeTool:S}=rs(),O=nw(n),L=XA(E.filter(Z=>!O.has(Z.function.name)),$);if(f&&f.allowedTools&&(L=L.filter(Z=>f.allowedTools.has(Z.function.name))),g&&!e._skipLog){let Z=$?` (${$})`:"";process.stderr.write(` [sub-agent: ${m}:${g}${Z}]
396
- `)}let I={};m&&(I.provider=m),g&&(I.model=g);let D=new Set;try{for(let K=0;K<s;K++){let X=await tw(_,L,I);if(!X||typeof X!="object")throw new Error("Empty or invalid response from provider");{let _e=m||kl(),Me=g||Bb();if(X.usage){let R=X.usage.prompt_tokens||0,v=X.usage.completion_tokens||0;a.input+=R,a.output+=v,Yb(_e,Me,R,v)}else{let R=X.content||"",v=_.map(te=>typeof te.content=="string"?te.content:Array.isArray(te.content)?te.content.map(M=>typeof M=="string"?M:M.text||"").join(""):"").join(" "),z=Kb(v),ne=Kb(R);a.input+=z,a.output+=ne,a._estimated=!0,Yb(_e,Me,z,ne)}}let Fe=X.content||"",Oe=X.tool_calls,V={role:"assistant",content:Fe||""};if(Oe&&Oe.length>0&&(V.tool_calls=Oe),_.push(V),!Oe||Oe.length===0){for(let _e of c)zi(_e);return{task:e.task,status:"done",result:Fe||"(no response)",toolsUsed:i,tokensUsed:a,modelSpec:m&&g?`${m}:${g}`:null}}let re=new Set,rt=Oe.map(_e=>{let Me=_e.function.name,R=Gb(_e.function.arguments),v=_e.id||`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!R)return Promise.resolve({role:"tool",content:`ERROR: Malformed tool arguments for ${Me}`,tool_call_id:v});if(["edit_file","patch_file"].includes(Me)&&R.path){if(D.has(R.path)||re.has(R.path))return Promise.resolve({role:"tool",content:`BLOCKED: "${R.path}" was already edited \u2014 re-read the changed section first (read_file with line_start/line_end) before making another edit. The file content has changed and your previous read is stale.`,tool_call_id:v});re.add(R.path)}let z=null;if(tO.has(Me)&&R.path){let te=require("path"),M=te.isAbsolute(R.path)?R.path:te.resolve(process.cwd(),R.path);if(e._readOnlyFiles&&e._readOnlyFiles.length>0){let ye=te.relative(process.cwd(),M);if(e._readOnlyFiles.some(G=>ye===G||ye.startsWith(G+"/")||M===G||M.startsWith(G+"/")))return Promise.resolve({role:"tool",content:`ERROR: File '${R.path}' is owned by another agent and is READ ONLY. Write to your own scope files instead.`,tool_call_id:v})}if(c.has(M)||!eO(M,r))return Promise.resolve({role:"tool",content:`ERROR: File '${R.path}' is locked by another operation. Try a different approach or skip this file.`,tool_call_id:v});c.add(M),z=M}return i.push(Me),t.onUpdate&&t.onUpdate({type:"tool_call",tool:Me,agentId:r}),(Me==="spawn_agents"?Df(R,n+1):S(Me,R,{autoConfirm:!0,silent:!0})).then(te=>{z&&(zi(z),c.delete(z));let M=String(te??"");return R&&R.path&&(["edit_file","patch_file","write_file"].includes(Me)&&M.startsWith("Edited:")?D.add(R.path):Me==="read_file"&&!M.startsWith("ERROR")&&D.delete(R.path)),{role:"tool",content:M.length>2e4?M.substring(0,2e4)+`
397
- ...(truncated)`:M,tool_call_id:v}}).catch(te=>(z&&(zi(z),c.delete(z)),{role:"tool",content:`ERROR: ${te.message}`,tool_call_id:v}))}),qe=await Promise.all(rt);if(_.push(...qe),K>=7&&_.length>12)try{let{compressMessage:_e}=Mn(),Me=_.length-6;for(let R=1;R<Me;R++)_[R]._subAgentCompressed||(_[R]={..._e(_[R],"light"),_subAgentCompressed:!0})}catch{}for(let _e=0;_e<Oe.length;_e++){let Me=Oe[_e];if(Me.function.name==="bash_exec"){let R=Gb(Me.function.arguments);if((qe[_e]?.content||"").startsWith("ERROR")&&R&&R.command){let z=R.command.replace(/\s+/g," ").trim().slice(0,100);u.set(z,(u.get(z)||0)+1)}}}t.onUpdate&&t.onUpdate(`step ${K+1}/${s}`)}for(let K of c)zi(K);let Z=[...u.entries()].filter(([,K])=>K>=3).sort((K,X)=>X[1]-K[1]).slice(0,3).map(([K,X])=>`"${K}" (failed ${X}\xD7)`);return{task:e.task,status:"truncated",abortReason:"iteration_limit",repeatedFailures:Z,result:_[_.length-1]?.content||"(max iterations reached)",toolsUsed:i,tokensUsed:a,modelSpec:m&&g?`${m}:${g}`:null}}catch(Z){for(let K of c)zi(K);return{task:e.task,status:"failed",result:`Error: ${Z.message}`,toolsUsed:i,tokensUsed:a,modelSpec:m&&g?`${m}:${g}`:null}}}async function Df(e,t=0){if(t>=2)return"ERROR: max agent nesting depth (2) reached \u2014 reviewer agents cannot spawn further agents.";let n=t===0?ZA:QA,o=t===0?Jb:Zb,s=(e.agents||[]).slice(0,n);if(s.length===0)return"ERROR: No agents specified";let r=t>0?" \u21B3 ":"",i=t>0?38:44,a=s.map(d=>vl(d)),c=s.map((d,f)=>{let p=a[f],h=p.model?` [${p.model}]`:"",m=d.task.substring(0,i-h.length);return`${r}Agent ${f+1}${h}: ${m}${d.task.length>m.length?"...":""}`}),u=new JA(c);u.start();try{let d=s.map((g,$)=>{let b=a[$],x=Math.min(g.max_iterations||o,o),_=b.model?{...g,model:`${b.provider}:${b.model}`,_skipLog:!0,max_iterations:x}:{...g,_skipLog:!0,max_iterations:x};return iw(_,{onUpdate:()=>{}},t).then(E=>(u.update($,E.status==="failed"?"error":"done"),E)).catch(E=>(u.update($,"error"),{task:g.task,status:"failed",result:`Error: ${E.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}))}),f=await Promise.all(d);u.stop(),If();let p=["Sub-agent results:",""],h=0,m=0;for(let g=0;g<f.length;g++){let $=f[g],b=$.status==="done"?"\u2713":$.status==="truncated"?"\u26A0":"\u2717",x=$.modelSpec?` [${$.modelSpec}]`:"";p.push(`${b} Agent ${g+1}${x}: ${$.task}`),p.push(` Status: ${$.status}`),p.push(` Tools used: ${$.toolsUsed.length>0?$.toolsUsed.join(", "):"none"}`),p.push(` Result: ${$.result}`),$.repeatedFailures&&$.repeatedFailures.length>0&&p.push(` Repeated failures: ${$.repeatedFailures.join("; ")}`),p.push(""),h+=$.tokensUsed.input,m+=$.tokensUsed.output}return p.push(`Total sub-agent tokens: ${h} input + ${m} output`),p.join(`
395
+ `:"")+d+p}];_.push({role:"user",content:e.task});let{TOOL_DEFINITIONS:E,executeTool:S}=rs(),O=nw(n),L=XA(E.filter(Z=>!O.has(Z.function.name)),y);if(f&&f.allowedTools&&(L=L.filter(Z=>f.allowedTools.has(Z.function.name))),g&&!e._skipLog){let Z=y?` (${y})`:"";process.stderr.write(` [sub-agent: ${m}:${g}${Z}]
396
+ `)}let I={};m&&(I.provider=m),g&&(I.model=g);let D=new Set;try{for(let K=0;K<s;K++){let X=await tw(_,L,I);if(!X||typeof X!="object")throw new Error("Empty or invalid response from provider");{let ke=m||kl(),Me=g||Bb();if(X.usage){let R=X.usage.prompt_tokens||0,v=X.usage.completion_tokens||0;a.input+=R,a.output+=v,Yb(ke,Me,R,v)}else{let R=X.content||"",v=_.map(te=>typeof te.content=="string"?te.content:Array.isArray(te.content)?te.content.map(M=>typeof M=="string"?M:M.text||"").join(""):"").join(" "),z=Kb(v),ne=Kb(R);a.input+=z,a.output+=ne,a._estimated=!0,Yb(ke,Me,z,ne)}}let Fe=X.content||"",Oe=X.tool_calls,V={role:"assistant",content:Fe||""};if(Oe&&Oe.length>0&&(V.tool_calls=Oe),_.push(V),!Oe||Oe.length===0){for(let ke of c)zi(ke);return{task:e.task,status:"done",result:Fe||"(no response)",toolsUsed:i,tokensUsed:a,modelSpec:m&&g?`${m}:${g}`:null}}let re=new Set,rt=Oe.map(ke=>{let Me=ke.function.name,R=Gb(ke.function.arguments),v=ke.id||`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!R)return Promise.resolve({role:"tool",content:`ERROR: Malformed tool arguments for ${Me}`,tool_call_id:v});if(["edit_file","patch_file"].includes(Me)&&R.path){if(D.has(R.path)||re.has(R.path))return Promise.resolve({role:"tool",content:`BLOCKED: "${R.path}" was already edited \u2014 re-read the changed section first (read_file with line_start/line_end) before making another edit. The file content has changed and your previous read is stale.`,tool_call_id:v});re.add(R.path)}let z=null;if(tO.has(Me)&&R.path){let te=require("path"),M=te.isAbsolute(R.path)?R.path:te.resolve(process.cwd(),R.path);if(e._readOnlyFiles&&e._readOnlyFiles.length>0){let ye=te.relative(process.cwd(),M);if(e._readOnlyFiles.some(G=>ye===G||ye.startsWith(G+"/")||M===G||M.startsWith(G+"/")))return Promise.resolve({role:"tool",content:`ERROR: File '${R.path}' is owned by another agent and is READ ONLY. Write to your own scope files instead.`,tool_call_id:v})}if(c.has(M)||!eO(M,r))return Promise.resolve({role:"tool",content:`ERROR: File '${R.path}' is locked by another operation. Try a different approach or skip this file.`,tool_call_id:v});c.add(M),z=M}return i.push(Me),t.onUpdate&&t.onUpdate({type:"tool_call",tool:Me,agentId:r}),(Me==="spawn_agents"?Df(R,n+1):S(Me,R,{autoConfirm:!0,silent:!0})).then(te=>{z&&(zi(z),c.delete(z));let M=String(te??"");return R&&R.path&&(["edit_file","patch_file","write_file"].includes(Me)&&M.startsWith("Edited:")?D.add(R.path):Me==="read_file"&&!M.startsWith("ERROR")&&D.delete(R.path)),{role:"tool",content:M.length>2e4?M.substring(0,2e4)+`
397
+ ...(truncated)`:M,tool_call_id:v}}).catch(te=>(z&&(zi(z),c.delete(z)),{role:"tool",content:`ERROR: ${te.message}`,tool_call_id:v}))}),qe=await Promise.all(rt);if(_.push(...qe),K>=7&&_.length>12)try{let{compressMessage:ke}=Mn(),Me=_.length-6;for(let R=1;R<Me;R++)_[R]._subAgentCompressed||(_[R]={...ke(_[R],"light"),_subAgentCompressed:!0})}catch{}for(let ke=0;ke<Oe.length;ke++){let Me=Oe[ke];if(Me.function.name==="bash_exec"){let R=Gb(Me.function.arguments);if((qe[ke]?.content||"").startsWith("ERROR")&&R&&R.command){let z=R.command.replace(/\s+/g," ").trim().slice(0,100);u.set(z,(u.get(z)||0)+1)}}}t.onUpdate&&t.onUpdate(`step ${K+1}/${s}`)}for(let K of c)zi(K);let Z=[...u.entries()].filter(([,K])=>K>=3).sort((K,X)=>X[1]-K[1]).slice(0,3).map(([K,X])=>`"${K}" (failed ${X}\xD7)`);return{task:e.task,status:"truncated",abortReason:"iteration_limit",repeatedFailures:Z,result:_[_.length-1]?.content||"(max iterations reached)",toolsUsed:i,tokensUsed:a,modelSpec:m&&g?`${m}:${g}`:null}}catch(Z){for(let K of c)zi(K);return{task:e.task,status:"failed",result:`Error: ${Z.message}`,toolsUsed:i,tokensUsed:a,modelSpec:m&&g?`${m}:${g}`:null}}}async function Df(e,t=0){if(t>=2)return"ERROR: max agent nesting depth (2) reached \u2014 reviewer agents cannot spawn further agents.";let n=t===0?ZA:QA,o=t===0?Jb:Zb,s=(e.agents||[]).slice(0,n);if(s.length===0)return"ERROR: No agents specified";let r=t>0?" \u21B3 ":"",i=t>0?38:44,a=s.map(d=>vl(d)),c=s.map((d,f)=>{let p=a[f],h=p.model?` [${p.model}]`:"",m=d.task.substring(0,i-h.length);return`${r}Agent ${f+1}${h}: ${m}${d.task.length>m.length?"...":""}`}),u=new JA(c);u.start();try{let d=s.map((g,y)=>{let b=a[y],x=Math.min(g.max_iterations||o,o),_=b.model?{...g,model:`${b.provider}:${b.model}`,_skipLog:!0,max_iterations:x}:{...g,_skipLog:!0,max_iterations:x};return iw(_,{onUpdate:()=>{}},t).then(E=>(u.update(y,E.status==="failed"?"error":"done"),E)).catch(E=>(u.update(y,"error"),{task:g.task,status:"failed",result:`Error: ${E.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}))}),f=await Promise.all(d);u.stop(),If();let p=["Sub-agent results:",""],h=0,m=0;for(let g=0;g<f.length;g++){let y=f[g],b=y.status==="done"?"\u2713":y.status==="truncated"?"\u26A0":"\u2717",x=y.modelSpec?` [${y.modelSpec}]`:"";p.push(`${b} Agent ${g+1}${x}: ${y.task}`),p.push(` Status: ${y.status}`),p.push(` Tools used: ${y.toolsUsed.length>0?y.toolsUsed.join(", "):"none"}`),p.push(` Result: ${y.result}`),y.repeatedFailures&&y.repeatedFailures.length>0&&p.push(` Repeated failures: ${y.repeatedFailures.join("; ")}`),p.push(""),h+=y.tokensUsed.input,m+=y.tokensUsed.output}return p.push(`Total sub-agent tokens: ${h} input + ${m} output`),p.join(`
398
398
  `)}catch(d){return u.stop(),If(),`ERROR: Sub-agent execution failed: ${d.message}`}}async function rO(e){let{createJob:t}=Gr(),n=(e.agents||[]).filter(i=>i.background),o=(e.agents||[]).filter(i=>!i.background),s=n.map(i=>{let a=vl(i),c=a.model?{...i,model:`${a.provider}:${a.model}`,_skipLog:!0}:{...i,_skipLog:!0};return t(c)}),r=[];if(s.length>0&&r.push(`Background agents started: [${s.join(", ")}]
399
399
  `+n.map((i,a)=>` ${s[a]}: ${i.task}`).join(`
400
400
  `)+`
@@ -464,8 +464,8 @@ HINT: ${p}`:""}`}let i=IO(o);if(i)return`BLOCKED: Destructive operation on prote
464
464
  HINT: Protected files (.env, credentials, venv, .ssh, etc.) cannot be deleted or moved via bash. Override with NEX_UNPROTECT=1 if intentional.`;if(n.autoConfirm?Bw(o):LO(o)){let p=Bw(o)?"\u26D4":"\u26A0";if(!await cs(` ${p} bash: \`${o}\``,{toolName:"bash"}))return"CANCELLED: User declined to execute this command."}let c;try{c=process.cwd(),ls.accessSync(c)}catch{c=require("os").homedir(),n.silent||console.log(`${Te.yellow} \u26A0 Working directory no longer exists \u2014 running in ${c}${Te.reset}`)}let u=VO.test(o.trim())&&!JO.test(o.trim());if(XO.test(o.trim())||u){n.silent||console.log(`${Te.dim} \u25B6 interactive: ${o}${Te.reset}`);let p=MO("sh",["-c",o],{stdio:"inherit",cwd:c});return p.error?`ERROR: ${p.error.message}`:p.status===0?"(interactive command completed successfully)":`(interactive command exited with code ${p.status})`}let{ToolProgress:d}=jo(),f=n.silent?null:new d("bash",`$ ${o.substring(0,72)}`);f&&f.start();try{let{stdout:p,stderr:h}=await Lt(o,{cwd:c,timeout:9e4,maxBuffer:5242880});return f&&f.stop(),p||h||"(no output)"}catch(p){f&&f.stop();let h=(p.stderr||p.stdout||p.message||"").toString().substring(0,5e3),m=n0(h,o);return`EXIT ${p.code||1}
465
465
  ${m}`}}case"read_file":{let o=new Ol("read_file","Reading file...");o.start();try{let s=Vt(t.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${t.path}`;if(!await Pn(s)){let D=await Nl(t.path);if(D.fixedPath)s=D.fixedPath,console.log(`${Te.dim} \u2713 auto-fixed path: ${t.path} \u2192 ${pe.relative(process.cwd(),s)}${Te.reset}`),o.update({message:"Resolved path",detail:pe.relative(process.cwd(),s)});else return`ERROR: File not found: ${t.path}${D.message?`
466
466
  `+D.message:""}`}let i=pe.relative(process.cwd(),s);o.update({message:"Scanning",detail:i});let a=Buffer.alloc(8192),c=await ls.promises.open(s,"r"),{bytesRead:u}=await c.read(a,0,8192,0);await c.close();for(let D=0;D<u;D++)if(a[D]===0)return`ERROR: ${s} is a binary file (not readable as text)`;let d=await jt.readFile(s,"utf-8");if(!d&&(await jt.stat(s)).size>0)return`WARNING: ${s} is empty or unreadable`;let f=d.split(`
467
- `),p=await jt.stat(s),h=f.length,m=350,g=!t.line_start&&!t.line_end,$=g&&h>m,b=(t.line_start||1)-1,x=$?m:t.line_end||f.length,_=b+1,E=x;o.update({count:Math.max(0,x-b),total:h,detail:`${i} lines ${_}-${E}`,message:$?"Reading excerpt":"Reading"});let S=$?`showing lines 1-${m} of ${h}`:t.line_start||t.line_end?`lines ${b+1}-${x} of ${h}`:`${h} lines`,O=`File: ${i} (${S}, ${p.size} bytes)`,L=f.slice(b,x).map((D,Z)=>`${b+Z+1}: ${D}`).join(`
468
- `),I=$?`
467
+ `),p=await jt.stat(s),h=f.length,m=350,g=!t.line_start&&!t.line_end,y=g&&h>m,b=(t.line_start||1)-1,x=y?m:t.line_end||f.length,_=b+1,E=x;o.update({count:Math.max(0,x-b),total:h,detail:`${i} lines ${_}-${E}`,message:y?"Reading excerpt":"Reading"});let S=y?`showing lines 1-${m} of ${h}`:t.line_start||t.line_end?`lines ${b+1}-${x} of ${h}`:`${h} lines`,O=`File: ${i} (${S}, ${p.size} bytes)`,L=f.slice(b,x).map((D,Z)=>`${b+Z+1}: ${D}`).join(`
468
+ `),I=y?`
469
469
 
470
470
  [\u{1F6A8} FILE TRUNCATED: You are only seeing lines 1-${m} of ${h} total lines. The rest of the file is HIDDEN. You MUST use line_start and line_end to read further down (e.g. line_start=${m+1}), or use grep_search to find specific keywords.]`:!g&&h>x?`
471
471
 
@@ -475,11 +475,11 @@ ${L}${I}`}finally{o.stop()}}case"write_file":{let o=new Ol("write_file","Prepari
475
475
  `+f.message:""}`}o.update({message:"Loading",detail:pe.relative(process.cwd(),s)});let i=await jt.readFile(s,"utf-8"),a=t.old_text,c=!1,u=!1;if(!i.includes(t.old_text)){o.update({message:"Matching target",detail:`${pe.relative(process.cwd(),s)} ${String(t.old_text||"").trim().split(`
476
476
  `)[0].slice(0,40)}`});let{getActiveModelId:f,getActiveProviderName:p}=ft();if(zw(f(),p())==="strict"){let g=ia(i,t.old_text);return g?`ERROR: old_text not found in ${s} (strict mode \u2014 exact match required)
477
477
  Most similar text (line ${g.line}, distance ${g.distance}):
478
- ${g.text}`:`ERROR: old_text not found in ${s} (strict mode \u2014 exact match required)`}let m=Ww(i,t.old_text);if(m)a=m,c=!0,o.update({message:"Matched target",detail:`${pe.relative(process.cwd(),s)} whitespace-normalized`}),console.log(`${Te.dim} \u2713 fuzzy whitespace match applied${Te.reset}`);else{let g=s0(i,t.old_text,t.new_text);if(g){if(!n.autoConfirm){let E=await na(s,g.content);if(Al(s,i,g.content,{annotations:E}),!await ta(`Apply (auto-fix, line ${g.line}, distance ${g.distance})`))return"CANCELLED: User declined to apply edit."}await jt.writeFile(s,g.content,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(s)||s.endsWith(".sh")||g.content.startsWith("#!"))&&await jt.chmod(s,493),Ml("edit_file",s,i,g.content);let _=g.matchText.length>80?g.matchText.substring(0,77)+"...":g.matchText;return console.log(`${Te.dim} \u2713 auto-fixed edit: line ${g.line}, distance ${g.distance}${Te.reset}`),`Edited: ${s} (auto-fixed, line ${g.line}, distance ${g.distance}, matched: "${_}")`}let $=ia(i,t.old_text);if($){let _=i.split(`
479
- `),E=Math.max(0,$.line-6),S=Math.min(_.length,$.line+10),O=_.slice(E,S).map((I,D)=>`${E+D+1}: ${I}`).join(`
480
- `),L=`line_start=${Math.max(1,$.line-5)} line_end=${Math.min(_.length,$.line+15)}`;return`ERROR: old_text not found in ${s} (most similar at line ${$.line}, distance ${$.distance})
478
+ ${g.text}`:`ERROR: old_text not found in ${s} (strict mode \u2014 exact match required)`}let m=Ww(i,t.old_text);if(m)a=m,c=!0,o.update({message:"Matched target",detail:`${pe.relative(process.cwd(),s)} whitespace-normalized`}),console.log(`${Te.dim} \u2713 fuzzy whitespace match applied${Te.reset}`);else{let g=s0(i,t.old_text,t.new_text);if(g){if(!n.autoConfirm){let E=await na(s,g.content);if(Al(s,i,g.content,{annotations:E}),!await ta(`Apply (auto-fix, line ${g.line}, distance ${g.distance})`))return"CANCELLED: User declined to apply edit."}await jt.writeFile(s,g.content,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(s)||s.endsWith(".sh")||g.content.startsWith("#!"))&&await jt.chmod(s,493),Ml("edit_file",s,i,g.content);let _=g.matchText.length>80?g.matchText.substring(0,77)+"...":g.matchText;return console.log(`${Te.dim} \u2713 auto-fixed edit: line ${g.line}, distance ${g.distance}${Te.reset}`),`Edited: ${s} (auto-fixed, line ${g.line}, distance ${g.distance}, matched: "${_}")`}let y=ia(i,t.old_text);if(y){let _=i.split(`
479
+ `),E=Math.max(0,y.line-6),S=Math.min(_.length,y.line+10),O=_.slice(E,S).map((I,D)=>`${E+D+1}: ${I}`).join(`
480
+ `),L=`line_start=${Math.max(1,y.line-5)} line_end=${Math.min(_.length,y.line+15)}`;return`ERROR: old_text not found in ${s} (most similar at line ${y.line}, distance ${y.distance})
481
481
 
482
- Actual file content around line ${$.line} \u2014 use this to correct old_text:
482
+ Actual file content around line ${y.line} \u2014 use this to correct old_text:
483
483
  ${O}
484
484
 
485
485
  Fix: update old_text to match the exact lines above, then retry. If you need more context: read_file with ${L}`}let b=(t.old_text||"").trim().split(`
@@ -489,18 +489,18 @@ Recovery: use grep -n to locate the text, then re-read that section with line_st
489
489
  `)[0].slice(0,40)}`});let f=i.split(a).join(t.new_text),p=await na(s,f);if(Al(s,i,f,{annotations:p}),!await ta(c?"Apply (fuzzy match)":"Apply"))return"CANCELLED: User declined to apply edit."}let d=i.split(a).join(t.new_text);return o.update({message:"Applying edit",detail:`${pe.relative(process.cwd(),s)} ${String(t.new_text||"").trim().split(`
490
490
  `)[0].slice(0,40)}`}),await jt.writeFile(s,d,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(s)||s.endsWith(".sh")||d.startsWith("#!"))&&(o.update({message:"Chmod",detail:pe.relative(process.cwd(),s)}),await jt.chmod(s,493)),Ml("edit_file",s,i,d),c?`Edited: ${s} (fuzzy match)`:`Edited: ${s}`}finally{o.stop()}}case"list_directory":{let o=Vt(t.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${t.path}`;if(!await Pn(o)){let u=t.path.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),d=Vt(u),f=await Pn(d);if(d&&f)o=d;else return`ERROR: Directory not found: ${t.path}`}let r=t.max_depth||2,i=null;if(t.pattern)try{let u=t.pattern.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");i=new RegExp(`^${u}$`)}catch{return`ERROR: Invalid pattern: ${t.pattern}`}let a=[],c=async(u,d,f)=>{if(d>r)return;let p;try{p=await jt.readdir(u,{withFileTypes:!0})}catch{return}p=p.filter(h=>!h.name.startsWith(".")&&h.name!=="node_modules");for(let h of p){if(i&&!h.isDirectory()&&!i.test(h.name))continue;let m=h.isDirectory()?"/":"";a.push(`${f}${h.name}${m}`),h.isDirectory()&&await c(pe.join(u,h.name),d+1,f+" ")}};return await c(o,1,""),a.join(`
491
491
  `)||"(empty)"}case"search_files":{let o=Vt(t.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${t.path}`;let s=["-rn","-H"];t.file_pattern&&s.push(`--include=${t.file_pattern}`),s.push(t.pattern,o);try{let{stdout:r}=await rr("grep",s,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),i=sa(r).slice(0,50);return(await ep(i,{query:t.pattern,basePath:o})).join(`
492
- `)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let s=process.cwd(),r=t.path?Vt(t.path):s,i=t.pattern,a=S=>{let O=S.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"(.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");return new RegExp(`^${O}$`)},c=a(i),u=i.split("/").pop(),d=a(u),{ToolProgress:f}=jo(),p=new f("glob","Finding files...");p.start();let h=Hw();GO(r)||(await HO(r),h=Hw());let m=h.filter(S=>c.test(S)||d.test(pe.basename(S))).map(S=>pe.join(r,S));if(m.length===0)return p.stop(),"(no matches)"+Qf(t.path);let g=await Promise.all(m.slice(0,210).map(async S=>{try{let O=await jt.stat(S);return{path:S,mtime:O.mtimeMs}}catch{return{path:S,mtime:0}}})),$=new Map(g.map(S=>[S.path,S.mtime])),b=await e0(i,r),x=t0(g.map(S=>S.path),{query:i,basePath:r,definitionScores:b,mtimeByPath:$}),_=m.length>200,E=x.slice(0,200).join(`
492
+ `)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let s=process.cwd(),r=t.path?Vt(t.path):s,i=t.pattern,a=S=>{let O=S.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"(.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");return new RegExp(`^${O}$`)},c=a(i),u=i.split("/").pop(),d=a(u),{ToolProgress:f}=jo(),p=new f("glob","Finding files...");p.start();let h=Hw();GO(r)||(await HO(r),h=Hw());let m=h.filter(S=>c.test(S)||d.test(pe.basename(S))).map(S=>pe.join(r,S));if(m.length===0)return p.stop(),"(no matches)"+Qf(t.path);let g=await Promise.all(m.slice(0,210).map(async S=>{try{let O=await jt.stat(S);return{path:S,mtime:O.mtimeMs}}catch{return{path:S,mtime:0}}})),y=new Map(g.map(S=>[S.path,S.mtime])),b=await e0(i,r),x=t0(g.map(S=>S.path),{query:i,basePath:r,definitionScores:b,mtimeByPath:y}),_=m.length>200,E=x.slice(0,200).join(`
493
493
  `);return p.update({count:m.length,detail:t.pattern}),p.stop(),_?`${E}
494
494
 
495
495
  \u26A0 Results truncated at 200. Use a more specific pattern.`:E}case"grep":{let o=t.path?Vt(t.path):process.cwd();if(t.staged){let{getDiff:c}=fo(),u=await c(!0);if(!u.trim())return"(no staged changes)";let d=new Set,f=u.split(`
496
- `);for(let $ of f)if($.startsWith("diff --git")){let b=$.match(/diff --git a\/(.+) b\/(.+)/);b&&d.add(b[2])}let p=["-rn","-E","-H","--exclude=*.md","--exclude=*.txt","--exclude=*.json","--exclude=*.yaml","--exclude=*.yml"];t.ignore_case&&p.push("-i"),t.include&&p.push(`--include=${t.include}`),t.type&&p.push(`--include=*.${t.type}`),t.context?p.push("-C",String(t.context)):(t.before_context&&p.push("-B",String(t.before_context)),t.after_context&&p.push("-A",String(t.after_context))),t.output_mode==="files_with_matches"?p.push("-l"):t.output_mode==="count"&&p.push("-c"),p.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage");let{ToolProgress:h}=jo(),m=new h("grep","Searching staged content...");m.start();let g=[];for(let $ of d)try{let b=pe.join(process.cwd(),$);if(await Pn(b)){let x=[...p];x.push(t.pattern,b);let{stdout:_}=await rr("grep",x,{cwd:process.cwd(),timeout:3e4,maxBuffer:2*1024*1024});if(t.output_mode==="files_with_matches"||t.output_mode==="count"){let E=sa(_,t.output_mode);g=g.concat(E)}else g=g.concat(sa(_))}}catch{}return g=await ep(g,{query:t.pattern,basePath:process.cwd(),outputMode:t.output_mode}),m.update({count:g.length,detail:"in staged files"}),m.stop(),g.join(`
496
+ `);for(let y of f)if(y.startsWith("diff --git")){let b=y.match(/diff --git a\/(.+) b\/(.+)/);b&&d.add(b[2])}let p=["-rn","-E","-H","--exclude=*.md","--exclude=*.txt","--exclude=*.json","--exclude=*.yaml","--exclude=*.yml"];t.ignore_case&&p.push("-i"),t.include&&p.push(`--include=${t.include}`),t.type&&p.push(`--include=*.${t.type}`),t.context?p.push("-C",String(t.context)):(t.before_context&&p.push("-B",String(t.before_context)),t.after_context&&p.push("-A",String(t.after_context))),t.output_mode==="files_with_matches"?p.push("-l"):t.output_mode==="count"&&p.push("-c"),p.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage");let{ToolProgress:h}=jo(),m=new h("grep","Searching staged content...");m.start();let g=[];for(let y of d)try{let b=pe.join(process.cwd(),y);if(await Pn(b)){let x=[...p];x.push(t.pattern,b);let{stdout:_}=await rr("grep",x,{cwd:process.cwd(),timeout:3e4,maxBuffer:2*1024*1024});if(t.output_mode==="files_with_matches"||t.output_mode==="count"){let E=sa(_,t.output_mode);g=g.concat(E)}else g=g.concat(sa(_))}}catch{}return g=await ep(g,{query:t.pattern,basePath:process.cwd(),outputMode:t.output_mode}),m.update({count:g.length,detail:"in staged files"}),m.stop(),g.join(`
497
497
  `).trim()||"(no matches in staged files)"}let s=["-rn","-E","-H"];t.ignore_case&&s.push("-i"),t.include&&s.push(`--include=${t.include}`),t.type&&s.push(`--include=*.${t.type}`);let r=20;t.context?s.push("-C",String(Math.min(Number(t.context),r))):(t.before_context&&s.push("-B",String(Math.min(Number(t.before_context),r))),t.after_context&&s.push("-A",String(Math.min(Number(t.after_context),r)))),t.output_mode==="files_with_matches"?s.push("-l"):t.output_mode==="count"&&s.push("-c"),s.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage"),s.push(t.pattern,o);let{ToolProgress:i}=jo(),a=new i("grep","Searching...");a.start();try{let{stdout:c}=await rr("grep",s,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),u;t.output_mode==="files_with_matches"||t.output_mode==="count"?u=sa(c,t.output_mode):u=sa(c);let d=t.offset||0,f=t.head_limit||(t.output_mode==="files_with_matches"?200:100);return u=await ep(u,{query:t.pattern,basePath:o,outputMode:t.output_mode}),u=u.slice(d,d+f),a.update({count:u.length,detail:`in ${o}`}),a.stop(),u.join(`
498
498
  `).trim()||"(no matches)"+Qf(t.path)}catch(c){if(a.stop(),c.code===2){let u=(c.stderr||c.message||"").toString().trim();return u.includes("No such file or directory")?`ERROR: Directory not found: ${o}`:u.includes("Invalid")||u.includes("Unmatched")||u.includes("unterminated")||u.includes("unclosed")||u.includes("parse error")||u.includes("brackets")||u.includes("not balanced")?`ERROR: Invalid regex pattern: ${t.pattern}`:`ERROR: grep failed: ${u.slice(0,200)||"exit code 2"}`}return"(no matches)"+Qf(t.path)}}case"patch_file":{let o=new Ol("patch_file","Preparing patches...");o.start();try{await tp();let s=Vt(t.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${t.path}`;if(!await Pn(s)){let x=await Nl(t.path);if(x.fixedPath)s=x.fixedPath,console.log(`${Te.dim} \u2713 auto-fixed path: ${t.path} \u2192 ${pe.relative(process.cwd(),s)}${Te.reset}`);else return`ERROR: File not found: ${t.path}${x.message?`
499
499
  `+x.message:""}`}let i=t.patches;if(!Array.isArray(i)||i.length===0)return"ERROR: No patches provided";o.update({count:0,total:i.length,detail:`${pe.relative(process.cwd(),s)} ${i.length} patches`,message:"Validating patches"});let a=await jt.readFile(s,"utf-8"),{getActiveModelId:c,getActiveProviderName:u}=ft(),d=zw(c(),u()),f=[],p=!1,h=!1;for(let x=0;x<i.length;x++){o.update({count:x+1,total:i.length,detail:`${pe.relative(process.cwd(),s)} patch ${x+1}/${i.length}`,message:"Matching patches"});let{old_text:_,new_text:E}=i[x];if(a.includes(_))f.push({old_text:_,new_text:E});else if(d==="strict"){let S=ia(a,_);return S?`ERROR: Patch ${x+1} old_text not found in ${s} (strict mode \u2014 exact match required)
500
500
  Most similar text (line ${S.line}, distance ${S.distance}):
501
501
  ${S.text}`:`ERROR: Patch ${x+1} old_text not found in ${s} (strict mode \u2014 exact match required)`}else{let S=Ww(a,_);if(S)f.push({old_text:S,new_text:E}),p=!0;else{let O=ia(a,_);if(O){let L=Math.max(3,Math.ceil(_.length*.05));if(O.distance<=L)f.push({old_text:O.text,new_text:E}),h=!0;else return`ERROR: Patch ${x+1} old_text not found in ${s}
502
502
  Most similar text (line ${O.line}, distance ${O.distance}):
503
- ${O.text}`}else return`ERROR: Patch ${x+1} old_text not found in ${s}`}}}let m=a;for(let{old_text:x,new_text:_}of f)m=m.split(x).join(_);if(!n.autoConfirm){o.update({message:"Previewing patch set",count:f.length,total:i.length,detail:`${pe.relative(process.cwd(),s)} ${f.length} matched`});let x=await na(s,m);if(Al(s,a,m,{annotations:x}),!await ta(p?"Apply patches (fuzzy match)":"Apply patches"))return"CANCELLED: User declined to apply patches."}o.update({message:"Applying patches",count:f.length,total:i.length,detail:`${pe.relative(process.cwd(),s)} ${f.length} matched`}),await jt.writeFile(s,m,"utf-8");let g=/[/\\]\.git[/\\]hooks[/\\]/.test(s)||s.endsWith(".sh")||m.startsWith("#!");g&&(o.update({message:"Chmod",detail:pe.relative(process.cwd(),s)}),await jt.chmod(s,493)),Ml("patch_file",s,a,m);let $=h?" (auto-fixed)":p?" (fuzzy match)":"",b=g?" [chmod +x applied]":"";return`Patched: ${s} (${i.length} replacements)${$}${b}`}finally{o.stop()}}case"web_fetch":{let o=t.url,s=t.max_length||1e4;try{let i=new URL(o).hostname;if(/^(127\.|10\.|172\.(1[6-9]|2\d|3[01])\.|192\.168\.|169\.254\.|0\.|localhost$|\[::1?\]|\[fd|fc)/i.test(i))return"ERROR: Fetching private/internal addresses is not allowed.";let a=await Jf.get(o,{timeout:15e3,maxContentLength:1048576,responseType:"text",headers:{"User-Agent":"nex-code/0.2.0"}});return(typeof a.data=="string"?a.data:JSON.stringify(a.data)).replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim().substring(0,s)||"(empty response)"}catch(r){return`ERROR: Failed to fetch ${o}: ${r.message}`}}case"web_search":{let o=t.max_results||5;if(process.env.PERPLEXITY_API_KEY)try{let s=await Jf.post("https://api.perplexity.ai/chat/completions",{model:"sonar",messages:[{role:"user",content:t.query}],max_tokens:1024,search_recency_filter:"month",return_citations:!0},{timeout:2e4,headers:{Authorization:`Bearer ${process.env.PERPLEXITY_API_KEY}`,"Content-Type":"application/json"}}),r=s.data?.choices?.[0]?.message?.content||"",i=s.data?.citations||[],a=`[Perplexity grounded search]
503
+ ${O.text}`}else return`ERROR: Patch ${x+1} old_text not found in ${s}`}}}let m=a;for(let{old_text:x,new_text:_}of f)m=m.split(x).join(_);if(!n.autoConfirm){o.update({message:"Previewing patch set",count:f.length,total:i.length,detail:`${pe.relative(process.cwd(),s)} ${f.length} matched`});let x=await na(s,m);if(Al(s,a,m,{annotations:x}),!await ta(p?"Apply patches (fuzzy match)":"Apply patches"))return"CANCELLED: User declined to apply patches."}o.update({message:"Applying patches",count:f.length,total:i.length,detail:`${pe.relative(process.cwd(),s)} ${f.length} matched`}),await jt.writeFile(s,m,"utf-8");let g=/[/\\]\.git[/\\]hooks[/\\]/.test(s)||s.endsWith(".sh")||m.startsWith("#!");g&&(o.update({message:"Chmod",detail:pe.relative(process.cwd(),s)}),await jt.chmod(s,493)),Ml("patch_file",s,a,m);let y=h?" (auto-fixed)":p?" (fuzzy match)":"",b=g?" [chmod +x applied]":"";return`Patched: ${s} (${i.length} replacements)${y}${b}`}finally{o.stop()}}case"web_fetch":{let o=t.url,s=t.max_length||1e4;try{let i=new URL(o).hostname;if(/^(127\.|10\.|172\.(1[6-9]|2\d|3[01])\.|192\.168\.|169\.254\.|0\.|localhost$|\[::1?\]|\[fd|fc)/i.test(i))return"ERROR: Fetching private/internal addresses is not allowed.";let a=await Jf.get(o,{timeout:15e3,maxContentLength:1048576,responseType:"text",headers:{"User-Agent":"nex-code/0.2.0"}});return(typeof a.data=="string"?a.data:JSON.stringify(a.data)).replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim().substring(0,s)||"(empty response)"}catch(r){return`ERROR: Failed to fetch ${o}: ${r.message}`}}case"web_search":{let o=t.max_results||5;if(process.env.PERPLEXITY_API_KEY)try{let s=await Jf.post("https://api.perplexity.ai/chat/completions",{model:"sonar",messages:[{role:"user",content:t.query}],max_tokens:1024,search_recency_filter:"month",return_citations:!0},{timeout:2e4,headers:{Authorization:`Bearer ${process.env.PERPLEXITY_API_KEY}`,"Content-Type":"application/json"}}),r=s.data?.choices?.[0]?.message?.content||"",i=s.data?.citations||[],a=`[Perplexity grounded search]
504
504
 
505
505
  ${r}`;return i.length>0&&(a+=`
506
506
 
@@ -641,9 +641,9 @@ ${p||h}
641
641
  ${X.message}`}catch{}}return`EXIT ${f}
642
642
  ${p||h||"(no output)"}`}let m=/\bgrep\b/.test(s),g=h;m&&(g=g.split(`
643
643
  `).filter(O=>O!=="--").join(`
644
- `));let $=m?60:100,b=g.split(`
645
- `);b.length>$&&(g=`(${b.length-$} earlier lines omitted \u2014 showing last ${$})
646
- `+b.slice(-$).join(`
644
+ `));let y=m?60:100,b=g.split(`
645
+ `);b.length>y&&(g=`(${b.length-y} earlier lines omitted \u2014 showing last ${y})
646
+ `+b.slice(-y).join(`
647
647
  `));let x=4,_=g.split(`
648
648
  `),E=[],S=0;for(;S<_.length;){let O=S+1;for(;O<_.length&&_[O]===_[S];)O++;let L=O-S;if(E.push(_[S]),L>x)E.push(`... (${L-1} identical lines omitted)`);else for(let I=1;I<L;I++)E.push(_[S]);S=O}return E.join(`
649
649
  `)||"(command completed, no output)"}case"ssh_upload":{if(!t.server||!t.local_path||!t.remote_path)return"ERROR: server, local_path, and remote_path are required";let o;try{o=Vn(t.server)}catch(i){return`ERROR: ${i.message}`}let s=o.user?`${o.user}@${o.host}`:o.host;if(console.log(`
@@ -655,8 +655,8 @@ ${h.slice(-2e3)}`:h.slice(-5e3)||"Remote nex-code completed (no output)"}case"se
655
655
  ${Te.yellow} \u26A0 Service: systemctl ${t.action} ${t.service} on ${d}${Te.reset}`),!await cs(" Execute?"))return"CANCELLED: User declined service action."}let c=t.service.includes(".")?t.service:`${t.service}.service`,u=`systemctl ${t.action} ${ct(c)}`;if(r){let f=t.action!=="status"?`sudo ${u}`:u;try{let{stdout:p,stderr:h}=await Lt(f,{timeout:15e3});return(p||h||`systemctl ${t.action} ${t.service}: OK`).trim()}catch(p){let h=(p.stderr||p.message||"").toString().trim();return/not found|loaded.*not-found/i.test(h)?`ERROR: Service "${t.service}" not found. Check: systemctl list-units --type=service`:`EXIT ${p.code||1}
656
656
  ${h}`}}else{let{stdout:d,stderr:f,exitCode:p,error:h}=await mn(a,u,{timeout:15e3,sudo:!0}),m=[d,f].filter(Boolean).join(`
657
657
  `).trim();return p!==0?/not found|loaded.*not-found/i.test(m)?`ERROR: Service "${t.service}" not found on ${a.host}. Check: ssh_exec to run "systemctl list-units --type=service"`:`EXIT ${p}
658
- ${h||m||"(no output)"}`:m||`systemctl ${t.action} ${t.service}: OK`}}case"service_logs":{if(!t.service)return"ERROR: service is required";let o=sp(t.service);if(o)return o;let s=!t.server||t.server==="local"||t.server==="localhost",r=t.lines||50,i=t.service.includes(".")?t.service:`${t.service}.service`,a=t.since?`--since ${ct(t.since)}`:"",c=t.follow?"-f":"",u=`journalctl -u ${ct(i)} -n ${r} ${a} ${c} --no-pager`.trim().replace(/\s+/g," ");if(s)try{let{stdout:$,stderr:b}=await Lt(u,{timeout:15e3});return($||b||"(no log output)").trim()}catch($){return`EXIT ${$.code||1}
659
- ${($.stderr||$.message||"").toString().trim()}`}let d;try{d=Vn(t.server)}catch($){return`ERROR: ${$.message}`}let{stdout:f,stderr:p,exitCode:h,error:m}=await mn(d,u,{timeout:2e4}),g=[f,p].filter(Boolean).join(`
658
+ ${h||m||"(no output)"}`:m||`systemctl ${t.action} ${t.service}: OK`}}case"service_logs":{if(!t.service)return"ERROR: service is required";let o=sp(t.service);if(o)return o;let s=!t.server||t.server==="local"||t.server==="localhost",r=t.lines||50,i=t.service.includes(".")?t.service:`${t.service}.service`,a=t.since?`--since ${ct(t.since)}`:"",c=t.follow?"-f":"",u=`journalctl -u ${ct(i)} -n ${r} ${a} ${c} --no-pager`.trim().replace(/\s+/g," ");if(s)try{let{stdout:y,stderr:b}=await Lt(u,{timeout:15e3});return(y||b||"(no log output)").trim()}catch(y){return`EXIT ${y.code||1}
659
+ ${(y.stderr||y.message||"").toString().trim()}`}let d;try{d=Vn(t.server)}catch(y){return`ERROR: ${y.message}`}let{stdout:f,stderr:p,exitCode:h,error:m}=await mn(d,u,{timeout:2e4}),g=[f,p].filter(Boolean).join(`
660
660
  `).trim();return h!==0?`EXIT ${h}
661
661
  ${m||g||"(no output)"}`:g||"(no log output)"}case"container_list":{let o=!t.server||t.server==="local"||t.server==="localhost",r=`docker ps ${t.all?"-a":""} --format "table {{.ID}}\\t{{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}"`.trim().replace(/\s+/g," ");if(o)try{let{stdout:p,stderr:h}=await Lt(r,{timeout:1e4});return(p||h||"(no containers)").trim()}catch(p){return`EXIT ${p.code||1}
662
662
  ${(p.stderr||p.message||"").toString().trim()}`}let i;try{i=Vn(t.server)}catch(p){return`ERROR: ${p.message}`}let{stdout:a,stderr:c,exitCode:u,error:d}=await mn(i,r,{timeout:15e3}),f=[a,c].filter(Boolean).join(`
@@ -676,9 +676,9 @@ ${p||h}`:h||`docker ${t.action} ${t.container}: OK`}case"deploy":{if(t.config)tr
676
676
  ${Te.yellow} \u26A0 Deploy [git pull]: ${r}:${t.remote_path}${f}${Te.reset}`)}else{let f=t.local_path.endsWith("/")?t.local_path:`${t.local_path}/`;console.log(`
677
677
  ${Te.yellow} \u26A0 Deploy [rsync]: ${f} \u2192 ${r}:${t.remote_path}${Te.reset}`)}if(t.deploy_script&&console.log(`${Te.yellow} Then run: ${t.deploy_script}${Te.reset}`),t.health_check&&console.log(`${Te.yellow} Health check: ${t.health_check}${Te.reset}`),!await cs(" Proceed with deployment?"))return"CANCELLED: User declined."}let i="";if(o==="git"){let d=(t.branch||"").replace(/[^a-zA-Z0-9._\/-]/g,"");if(t.branch&&d!==t.branch)return`ERROR: Invalid branch name: ${t.branch}`;let f=(t.remote_path||"").replace(/'/g,"'\\''"),p=d?`cd '${f}' && git fetch origin && git checkout '${d}' && git pull origin '${d}'`:`cd '${f}' && git pull`;if(t.dry_run)return`DRY RUN [git]: would run on ${r}:
678
678
  ${p}${t.deploy_script?`
679
- ${t.deploy_script}`:""}`;let{stdout:h,stderr:m,exitCode:g,error:$}=await mn(s,p,{timeout:12e4});if(i=[h,m].filter(Boolean).join(`
679
+ ${t.deploy_script}`:""}`;let{stdout:h,stderr:m,exitCode:g,error:y}=await mn(s,p,{timeout:12e4});if(i=[h,m].filter(Boolean).join(`
680
680
  `).trim(),g!==0)return`ERROR (git pull, exit ${g}):
681
- ${$||i}`}else{let d=s.key?`-e "ssh -i ${s.key.replace(/^~/,require("os").homedir())}${s.port&&Number(s.port)!==22?` -p ${s.port}`:""}"`:s.port&&Number(s.port)!==22?`-e "ssh -p ${s.port}"`:"",f=(t.exclude||[]).map(g=>`--exclude="${g}"`).join(" "),p=t.dry_run?"--dry-run":"",h=t.local_path.endsWith("/")?t.local_path:`${t.local_path}/`,m=`rsync -avz --delete ${p} ${f} ${d} ${h} ${r}:${t.remote_path}`.trim().replace(/\s+/g," ");try{let{stdout:g,stderr:$}=await Lt(m,{timeout:12e4});i=(g||$||"").trim()}catch(g){return`ERROR (rsync): ${(g.stderr||g.message||"").toString().trim()}`}if(t.dry_run)return`DRY RUN [rsync]:
681
+ ${y||i}`}else{let d=s.key?`-e "ssh -i ${s.key.replace(/^~/,require("os").homedir())}${s.port&&Number(s.port)!==22?` -p ${s.port}`:""}"`:s.port&&Number(s.port)!==22?`-e "ssh -p ${s.port}"`:"",f=(t.exclude||[]).map(g=>`--exclude="${g}"`).join(" "),p=t.dry_run?"--dry-run":"",h=t.local_path.endsWith("/")?t.local_path:`${t.local_path}/`,m=`rsync -avz --delete ${p} ${f} ${d} ${h} ${r}:${t.remote_path}`.trim().replace(/\s+/g," ");try{let{stdout:g,stderr:y}=await Lt(m,{timeout:12e4});i=(g||y||"").trim()}catch(g){return`ERROR (rsync): ${(g.stderr||g.message||"").toString().trim()}`}if(t.dry_run)return`DRY RUN [rsync]:
682
682
  ${i||"(nothing to sync)"}`}let a="";if(t.deploy_script){let{stdout:d,stderr:f,exitCode:p,error:h}=await mn(s,t.deploy_script,{timeout:12e4}),m=[d,f].filter(Boolean).join(`
683
683
  `).trim();if(p!==0)return`${o==="git"?"git pull":"rsync"} OK
684
684
 
@@ -698,7 +698,7 @@ Health check FAILED: ${d} \u2192 ${p.message}`,(o==="git"?"git pull OK":"rsync O
698
698
  Health check FAILED (exit ${m}): ${g}`,(o==="git"?"git pull OK":"rsync OK")+i+a+c;c=`
699
699
 
700
700
  Health check: \u2713 ${g||"(exit 0)"}`}}let u=o==="git"?`${r}:${t.remote_path}`:`${t.local_path} \u2192 ${r}:${t.remote_path}`;return`Deployed [${o}] ${u}
701
- ${i}${a}${c}`.trim()}case"deployment_status":{let o=KO(),s=t.config?[t.config]:Object.keys(o);if(s.length===0)return"No deploy configs found. Create .nex/deploy.json to configure deployments.";let r=[];for(let i of s){let a=o[i];if(!a){r.push(`${i}: NOT FOUND`);continue}try{let c=Vn(a.server||i),d=(await mn(c,"echo OK",{timeout:1e4})).stdout.trim()==="OK",f="unknown";if(d&&a.deploy_script){let h=a.deploy_script.match(/systemctl\s+\w+\s+(\S+)/);if(h)try{f=(await mn(c,`systemctl is-active ${h[1]}`,{timeout:1e4})).stdout.trim()}catch{f="inactive"}}let p="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)=>setTimeout(()=>b(new Error("timeout")),1e4))]);p=g.ok?"healthy":`HTTP ${g.status}`}catch(m){p=`unhealthy: ${m.message.substring(0,50)}`}else try{p=(await mn(c,h,{timeout:1e4})).exitCode===0?"healthy":"unhealthy"}catch{p="unhealthy"}}r.push(`${i}: server=${d?"reachable":"unreachable"} service=${f} health=${p}`)}catch(c){r.push(`${i}: ERROR \u2014 ${c.message}`)}}return`Deployment Status:
701
+ ${i}${a}${c}`.trim()}case"deployment_status":{let o=KO(),s=t.config?[t.config]:Object.keys(o);if(s.length===0)return"No deploy configs found. Create .nex/deploy.json to configure deployments.";let r=[];for(let i of s){let a=o[i];if(!a){r.push(`${i}: NOT FOUND`);continue}try{let c=Vn(a.server||i),d=(await mn(c,"echo OK",{timeout:1e4})).stdout.trim()==="OK",f="unknown";if(d&&a.deploy_script){let h=a.deploy_script.match(/systemctl\s+\w+\s+(\S+)/);if(h)try{f=(await mn(c,`systemctl is-active ${h[1]}`,{timeout:1e4})).stdout.trim()}catch{f="inactive"}}let p="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((y,b)=>setTimeout(()=>b(new Error("timeout")),1e4))]);p=g.ok?"healthy":`HTTP ${g.status}`}catch(m){p=`unhealthy: ${m.message.substring(0,50)}`}else try{p=(await mn(c,h,{timeout:1e4})).exitCode===0?"healthy":"unhealthy"}catch{p="unhealthy"}}r.push(`${i}: server=${d?"reachable":"unreachable"} service=${f} health=${p}`)}catch(c){r.push(`${i}: ERROR \u2014 ${c.message}`)}}return`Deployment Status:
702
702
  ${r.join(`
703
703
  `)}`}case"frontend_recon":{let o=process.cwd(),s=(t.type||"").toLowerCase(),r=[],i=async(E,S=120)=>{try{let O=pe.isAbsolute(E)?E:pe.join(o,E),I=(await jt.readFile(O,"utf8")).split(`
704
704
  `),D=I.slice(0,S).join(`
@@ -722,8 +722,8 @@ ${S}
722
722
  ${O}
723
723
  \`\`\``),g=!0;break}}}g||r.push("(no main layout/index file found \u2014 try read_file on your root template manually)"),r.push(`
724
724
  ## STEP 3: Reference Component (same type)
725
- `);let $=[];if(s){for(let E of["*.html","*.vue","*.jsx","*.tsx"])if($=await d(s,E),$.length>0)break}if($.length===0)try{let{stdout:E}=await Lt(`find "${o}" -type f \\( -name "*.html" -o -name "*.vue" -o -name "*.jsx" -o -name "*.tsx" \\) -not -path "*/node_modules/*" -not -path "*/.git/*" -not -path "*/dist/*" -not -path "*/build/*" -not -name "base.html" -not -name "_base.html" -not -name "layout.html" -not -name "App.vue" -not -name "App.jsx" 2>/dev/null | head -20`,{timeout:8e3});$=E.trim().split(`
726
- `).filter(Boolean)}catch{$=[]}if($.length>0){let E=$[0],S=await i(E,150);S?r.push(`### Reference: ${pe.relative(o,E)}
725
+ `);let y=[];if(s){for(let E of["*.html","*.vue","*.jsx","*.tsx"])if(y=await d(s,E),y.length>0)break}if(y.length===0)try{let{stdout:E}=await Lt(`find "${o}" -type f \\( -name "*.html" -o -name "*.vue" -o -name "*.jsx" -o -name "*.tsx" \\) -not -path "*/node_modules/*" -not -path "*/.git/*" -not -path "*/dist/*" -not -path "*/build/*" -not -name "base.html" -not -name "_base.html" -not -name "layout.html" -not -name "App.vue" -not -name "App.jsx" 2>/dev/null | head -20`,{timeout:8e3});y=E.trim().split(`
726
+ `).filter(Boolean)}catch{y=[]}if(y.length>0){let E=y[0],S=await i(E,150);S?r.push(`### Reference: ${pe.relative(o,E)}
727
727
  \`\`\`html
728
728
  ${S}
729
729
  \`\`\``):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(`
@@ -739,7 +739,7 @@ ${S}
739
739
  (no output)`}case"disk_usage":{let c=t.path||"/",u=ct(c),d=`df -h ${u}; echo '--- Top subdirs ---'; du -d1 -x -h ${u} 2>/dev/null | sort -rh | head -20`,{out:f,exitCode:p}=await r(d,3e4);return p!==0?`EXIT ${p}
740
740
  ${f}`:f}case"process_list":{let c=t.sort_by==="mem"?"4":"3",u=(t.limit||20)+1,d=`ps aux --sort=-${t.sort_by==="mem"?"%mem":"%cpu"} 2>/dev/null | head -${u} || ps aux | awk 'NR==1{print; next} {print | "sort -k${c} -rn"}' | head -${u}`,{out:f,exitCode:p}=await r(d,15e3);return p!==0?`EXIT ${p}
741
741
  ${f}`:f}case"network_status":{let c="ss -tlnp 2>/dev/null || netstat -tlnp 2>/dev/null; echo '--- Active connections ---'; ss -tnp 2>/dev/null | head -30",{out:u,exitCode:d}=await r(c,15e3);return d!==0?`EXIT ${d}
742
- ${u}`:u}case"package":{if(!t.package_action)return"ERROR: package_action is required for action=package";let{out:c}=await r("which dnf 2>/dev/null && echo dnf || (which apt-get 2>/dev/null && echo apt) || echo unknown",1e4),u=c.includes("dnf")?"dnf":c.includes("apt")?"apt":null;if(!u)return"ERROR: No supported package manager found (dnf/apt)";let d=t.packages||[];if(!d.every(lM))return"ERROR: package names contain unsafe characters";let f=d.map(ct).join(" "),p;switch(t.package_action){case"list":p=u==="dnf"?"dnf list installed 2>/dev/null | head -60":"dpkg -l | head -60";break;case"check":{let g=u==="dnf"?'dnf check-update 2>/dev/null; EC=$?; [ $EC -eq 100 ] && echo "EXIT_STATUS: updates_available" || ([ $EC -eq 0 ] && echo "EXIT_STATUS: up_to_date" || echo "EXIT_STATUS: error $EC")':"apt-get -s upgrade 2>/dev/null | tail -5",{out:$}=await r(g,6e4);return $||"(no output from package check)"}case"install":if(!f)return"ERROR: packages required for install";p=u==="dnf"?`dnf install -y ${f}`:`apt-get install -y ${f}`;break;case"remove":if(!f)return"ERROR: packages required for remove";p=u==="dnf"?`dnf remove -y ${f}`:`apt-get remove -y ${f}`;break;case"update":if(!f)return"ERROR: packages required for update (use upgrade for full system upgrade)";p=u==="dnf"?`dnf update -y ${f}`:`apt-get install -y --only-upgrade ${f}`;break;case"upgrade":p=u==="dnf"?"dnf upgrade -y":"DEBIAN_FRONTEND=noninteractive apt-get upgrade -y";break;default:return`ERROR: Unknown package_action: ${t.package_action}`}let{out:h,exitCode:m}=await r(p,12e4);return m!==0?`EXIT ${m}
742
+ ${u}`:u}case"package":{if(!t.package_action)return"ERROR: package_action is required for action=package";let{out:c}=await r("which dnf 2>/dev/null && echo dnf || (which apt-get 2>/dev/null && echo apt) || echo unknown",1e4),u=c.includes("dnf")?"dnf":c.includes("apt")?"apt":null;if(!u)return"ERROR: No supported package manager found (dnf/apt)";let d=t.packages||[];if(!d.every(lM))return"ERROR: package names contain unsafe characters";let f=d.map(ct).join(" "),p;switch(t.package_action){case"list":p=u==="dnf"?"dnf list installed 2>/dev/null | head -60":"dpkg -l | head -60";break;case"check":{let g=u==="dnf"?'dnf check-update 2>/dev/null; EC=$?; [ $EC -eq 100 ] && echo "EXIT_STATUS: updates_available" || ([ $EC -eq 0 ] && echo "EXIT_STATUS: up_to_date" || echo "EXIT_STATUS: error $EC")':"apt-get -s upgrade 2>/dev/null | tail -5",{out:y}=await r(g,6e4);return y||"(no output from package check)"}case"install":if(!f)return"ERROR: packages required for install";p=u==="dnf"?`dnf install -y ${f}`:`apt-get install -y ${f}`;break;case"remove":if(!f)return"ERROR: packages required for remove";p=u==="dnf"?`dnf remove -y ${f}`:`apt-get remove -y ${f}`;break;case"update":if(!f)return"ERROR: packages required for update (use upgrade for full system upgrade)";p=u==="dnf"?`dnf update -y ${f}`:`apt-get install -y --only-upgrade ${f}`;break;case"upgrade":p=u==="dnf"?"dnf upgrade -y":"DEBIAN_FRONTEND=noninteractive apt-get upgrade -y";break;default:return`ERROR: Unknown package_action: ${t.package_action}`}let{out:h,exitCode:m}=await r(p,12e4);return m!==0?`EXIT ${m}
743
743
  ${h}`:h||`${t.package_action} OK`}case"user_manage":{if(!t.user_action)return"ERROR: user_action is required for action=user_manage";switch(t.user_action){case"list":{let c=`awk -F: '$3 >= 1000 && $1 != "nobody" {print $1, "uid="$3, "gid="$4, "shell="$7}' /etc/passwd`,{out:u,exitCode:d}=await r(c,1e4);return d!==0?`EXIT ${d}
744
744
  ${u}`:u||"(no regular users)"}case"info":{if(!t.user)return"ERROR: user is required for user_action=info";let c=oa(t.user);if(c)return c;let u=ct(t.user),d=`id ${u} && echo '--- Groups ---' && groups ${u} && echo '--- Last login ---' && lastlog -u ${u} 2>/dev/null`,{out:f,exitCode:p}=await r(d,1e4);return p!==0?`EXIT ${p}
745
745
  ${f}`:f}case"create":{if(!t.user)return"ERROR: user is required for user_action=create";let c=oa(t.user);if(c)return c;if(!(t.groups||[]).every(o0))return"ERROR: groups contain unsafe characters";let u=(t.groups||[]).map(m=>`-G ${ct(m)}`).join(" "),d=ct(t.user),f=`useradd -m ${u} ${d} && echo "User ${t.user} created"`,{out:p,exitCode:h}=await r(f,15e3);return h!==0?`EXIT ${h}
@@ -813,7 +813,7 @@ ${u}
813
813
  - 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 vM(e){let t=Xr(),n=c0(e,t);if(!n?.matchedProfile||!n?.matchedName)return null;let{matchedProfile:o,matchedName:s}=n,r=["ss -tlnp 2>/dev/null | awk 'NR>1{print $4}' | grep -oE ':[0-9]+$' | sort -u | head -8","echo '---services---'","ps aux 2>/dev/null | grep -E '(node |python3 |gunicorn|uvicorn|ruby |java )' | grep -v grep | awk '{print $11, $12, $13}' | head -6","echo '---data---'","find /home -maxdepth 5 -name 'data' -type d 2>/dev/null | head -6"].join("; ");try{let{stdout:i}=await pM(o,r,{timeout:4e3});if(!i||i.trim().length<5)return null;let a=o.user?`${o.user}@${o.host}`:o.host;return`[Server context for "${s}" (${a}) \u2014 probed at task start]
814
814
  `+i.trim()}catch{return null}}l0.exports={getServerContext:bM,getDeploymentContextBlock:kM,hasServerOS:wM,getProfileNames:_M,probeUrlServer:vM,detectRuntimeDebugTarget:c0,OS_HINTS:rp}});var jl=Q((Xq,f0)=>{var Jt=require("fs").promises,Ll=require("fs"),kt=require("path"),aa=require("util").promisify(require("child_process").exec),{C:Vr}=dt(),{getMergeConflicts:d0}=fo(),{getServerContext:SM}=ip(),{refreshIndex:EM,getFileIndex:TM,buildContentIndex:RM,summarizeModuleHubs:CM}=Es(),AM=new Set(["node_modules",".git",".svn","dist","build","coverage",".nyc_output","__pycache__",".DS_Store",".next",".nuxt",".turbo",".cache","vendor","tmp","temp"]),OM=[{file:"tsconfig.json",label:"TypeScript"},{file:"jest.config.js",label:"Jest"},{file:"jest.config.cjs",label:"Jest"},{file:"jest.config.mjs",label:"Jest"},{file:"vitest.config.js",label:"Vitest"},{file:"vitest.config.ts",label:"Vitest"},{file:"vite.config.js",label:"Vite"},{file:"vite.config.ts",label:"Vite"},{file:"next.config.js",label:"Next.js"},{file:"next.config.mjs",label:"Next.js"},{file:"tailwind.config.js",label:"Tailwind"},{file:"tailwind.config.ts",label:"Tailwind"},{file:"docker-compose.yml",label:"Docker Compose"},{file:"docker-compose.yaml",label:"Docker Compose"},{file:".github/workflows",label:"GitHub Actions"}];function MM(e,t=6){let n=new Map;for(let o of e){let s=o.includes("/")?o.split("/")[0]:"(root)";!s||s.startsWith(".")||n.set(s,(n.get(s)||0)+1)}return[...n.entries()].sort((o,s)=>s[1]-o[1]||o[0].localeCompare(s[0])).slice(0,t).map(([o,s])=>`${o} (${s})`)}function PM(e){let t=new Set(e),n=new Set;for(let o of OM)(t.has(o.file)||[...t].some(s=>s.startsWith(`${o.file}/`)))&&n.add(o.label);return t.has("package.json")&&n.add("Node.js"),[...t].some(o=>/^tests?\//.test(o)||/\.test\./.test(o)||/\.spec\./.test(o))&&n.add("Tests"),[...t].some(o=>o.startsWith("vscode/"))&&n.add("VS Code Extension"),[...n]}function NM(e){let t=["package.json","cli/index.js","src/index.ts","src/index.js","index.ts","index.js","bin/nex-code.js","dist/nex-code.js","README.md"],n=[];for(let o of t)if(e.includes(o)&&n.push(o),n.length>=5)break;return n}function LM(e,t=6){let n=e.filter(r=>/^tests?\//.test(r)||/\.test\./.test(r)||/\.spec\./.test(r));if(n.length===0)return[];let o=e.filter(r=>!/^tests?\//.test(r)&&!/\.test\./.test(r)&&!/\.spec\./.test(r)&&/\.(js|jsx|ts|tsx|py|go|rs|java)$/.test(r)),s=[];for(let r of o){let i=kt.basename(r).replace(/\.[^.]+$/,"");if(i.length<3)continue;let a=n.filter(c=>c.includes(i));if(a.length>0&&s.push(`${r} -> ${a.slice(0,2).join(", ")}`),s.length>=t)break}return s}function IM(e){return!e||!e.workspaces?[]:Array.isArray(e.workspaces)?e.workspaces:Array.isArray(e.workspaces.packages)?e.workspaces.packages:[]}async function jM(e){try{await EM(e);let t=TM();if(!t||t.length===0)return"";let n=PM(t),o=MM(t),s=NM(t),r=t.filter(f=>/^tests?\//.test(f)||/\.test\./.test(f)||/\.spec\./.test(f)).length,i=LM(t),a=[];try{let f=kt.join(e,"package.json");if(Ll.existsSync(f)){let p=JSON.parse(Ll.readFileSync(f,"utf-8"));a=IM(p)}}catch{}let c="",u="";try{let f=await RM(e),p=Object.entries(f.files||{}).map(([h,m])=>({file:h,defs:Array.isArray(m.defs)?m.defs.length:0})).filter(h=>h.defs>0).sort((h,m)=>m.defs-h.defs||h.file.localeCompare(m.file)).slice(0,4).map(h=>`${h.file} (${h.defs} defs)`);p.length>0&&(c=`CODE HOTSPOTS: ${p.join(", ")}`)}catch{}try{let f=await CM(e,4);f.length>0&&(u=`MODULE HUBS: ${f.join(", ")}`)}catch{}let d=[`REPO MAP: ${t.length} indexed files${n.length?` | stack: ${n.join(", ")}`:""}`];return o.length>0&&d.push(`WORK AREAS: ${o.join(", ")}`),s.length>0&&d.push(`LIKELY ENTRY POINTS: ${s.join(", ")}`),a.length>0&&d.push(`WORKSPACES: ${a.join(", ")}`),r>0&&d.push(`TEST FOOTPRINT: ${r} test files detected`),i.length>0&&d.push(`TEST MAP: ${i.join(" | ")}`),c&&d.push(c),u&&d.push(u),d.push("RETRIEVAL RULE: Prefer the smallest verified path set first \u2014 identify likely files, then read only the exact symbols/sections you need before editing."),d.join(`
815
815
  `)}catch{return""}}function DM(e){try{return Ll.readFileSync(e,"utf-8").split(`
816
- `).map(n=>n.trim()).filter(n=>n&&!n.startsWith("#")&&!n.startsWith("!")).map(n=>n.replace(/\/$/,""))}catch{return[]}}function qM(e,t){for(let n of t)if(n===e||n.includes("*")&&new RegExp("^"+n.replace(/\./g,"\\.").replace(/\*/g,".*")+"$").test(e))return!0;return!1}function FM(e,{maxDepth:t=3,maxFiles:n=200,giPatterns:o=[]}={}){let s=kt.join(e,".gitignore"),r=[...o,...DM(s)],i=0,a=[kt.basename(e)+"/"];function c(u,d,f){if(f>t||i>=n)return;let p;try{p=Ll.readdirSync(u,{withFileTypes:!0})}catch{return}p.sort((m,g)=>m.isDirectory()!==g.isDirectory()?m.isDirectory()?-1:1:m.name.localeCompare(g.name));let h=p.filter(m=>!(AM.has(m.name)||m.name.startsWith(".")&&m.name!==".env.example"||qM(m.name,r)));for(let m=0;m<h.length;m++){if(i>=n){a.push(`${d}\u2514\u2500\u2500 \u2026 (truncated)`);break}let g=h[m],$=m===h.length-1,b=$?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",x=d+($?" ":"\u2502 "),_=g.isDirectory()?g.name+"/":g.name;a.push(`${d}${b}${_}`),i++,g.isDirectory()&&c(kt.join(u,g.name),x,f+1)}}return c(e,"",1),a.join(`
816
+ `).map(n=>n.trim()).filter(n=>n&&!n.startsWith("#")&&!n.startsWith("!")).map(n=>n.replace(/\/$/,""))}catch{return[]}}function qM(e,t){for(let n of t)if(n===e||n.includes("*")&&new RegExp("^"+n.replace(/\./g,"\\.").replace(/\*/g,".*")+"$").test(e))return!0;return!1}function FM(e,{maxDepth:t=3,maxFiles:n=200,giPatterns:o=[]}={}){let s=kt.join(e,".gitignore"),r=[...o,...DM(s)],i=0,a=[kt.basename(e)+"/"];function c(u,d,f){if(f>t||i>=n)return;let p;try{p=Ll.readdirSync(u,{withFileTypes:!0})}catch{return}p.sort((m,g)=>m.isDirectory()!==g.isDirectory()?m.isDirectory()?-1:1:m.name.localeCompare(g.name));let h=p.filter(m=>!(AM.has(m.name)||m.name.startsWith(".")&&m.name!==".env.example"||qM(m.name,r)));for(let m=0;m<h.length;m++){if(i>=n){a.push(`${d}\u2514\u2500\u2500 \u2026 (truncated)`);break}let g=h[m],y=m===h.length-1,b=y?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",x=d+(y?" ":"\u2502 "),_=g.isDirectory()?g.name+"/":g.name;a.push(`${d}${b}${_}`),i++,g.isDirectory()&&c(kt.join(u,g.name),x,f+1)}}return c(e,"",1),a.join(`
817
817
  `)}var ap=new Map,Zr=new Map,Il=null,u0=3e4,Jr={result:null,expiry:0,cwd:null};async function Jn(e){try{return await e()}catch{return null}}async function BM(){if(!Il||Date.now()>Il)return!1;let e=[kt.join(process.cwd(),"package.json"),kt.join(process.cwd(),"README.md"),kt.join(process.cwd(),"AGENTS.md"),kt.join(process.cwd(),".gitignore")];for(let t of e)try{let n=await Jt.stat(t),o=Zr.get(t);if(!o||n.mtimeMs!==o)return!1}catch{if(Zr.has(t))return!1}try{let t=kt.join(process.cwd(),".git","HEAD"),n=await Jt.stat(t),o=Zr.get(t);if(!o||n.mtimeMs!==o)return!1}catch{}return!0}async function UM(){let e=[kt.join(process.cwd(),"package.json"),kt.join(process.cwd(),"README.md"),kt.join(process.cwd(),"AGENTS.md"),kt.join(process.cwd(),".gitignore"),kt.join(process.cwd(),".git","HEAD"),kt.join(process.cwd(),"CLAUDE.md"),kt.join(process.cwd(),".nex","CLAUDE.md")];for(let t of e)try{let n=await Jt.stat(t);Zr.set(t,n.mtimeMs)}catch{Zr.delete(t)}}async function WM(e){let t="fileContext",n=ap.get(t),o=!1;if(n&&await BM()&&(o=!0),!o){let d=[],f=kt.join(e,"package.json");if(await Jn(()=>Jt.access(f).then(()=>!0).catch(()=>!1)))try{let I=await Jt.readFile(f,"utf-8"),D=JSON.parse(I),Z={name:D.name,version:D.version};if(D.scripts&&(Z.scripts=Object.keys(D.scripts).slice(0,15)),D.dependencies&&(Z.deps=Object.keys(D.dependencies).length),D.devDependencies&&(Z.devDeps=Object.keys(D.devDependencies).length),d.push(`PACKAGE: ${JSON.stringify(Z)}`),D.scripts){let K=["test","build","lint","typecheck","check","benchmark:gate","benchmark"].filter(X=>D.scripts[X]).map(X=>`${X}=${D.scripts[X]}`).slice(0,8);K.length>0&&d.push(`AVAILABLE TOOL COMMANDS (use bash to run these):
818
818
  ${K.map(X=>` npm run ${X.split("=")[0]} # ${X}`).join(`
819
819
  `)}`)}}catch{}let h=kt.join(e,"README.md");if(await Jn(()=>Jt.access(h).then(()=>!0).catch(()=>!1))){let D=(await Jt.readFile(h,"utf-8")).split(`
@@ -835,7 +835,7 @@ ${d}`)}try{let d=SM();d&&s.push(d)}catch{}return s.join(`
835
835
  `)}async function HM(e){let t=kt.join(e,"package.json"),n="";if(await Jn(()=>Jt.access(t).then(()=>!0).catch(()=>!1)))try{let i=await Jt.readFile(t,"utf-8"),a=JSON.parse(i);n=`${a.name||"?"} v${a.version||"?"}`}catch{}let[s,r]=await Promise.all([Jn(async()=>{let{stdout:i}=await aa("git branch --show-current",{cwd:e,timeout:5e3});return i.trim()}),d0()]);if(r&&r.length>0){console.log(`${Vr.red} \u26A0 ${r.length} unresolved merge conflict(s):${Vr.reset}`);for(let i of r)console.log(`${Vr.red} ${i.file}${Vr.reset}`);console.log(`${Vr.yellow} \u2192 Resolve conflicts before starting tasks${Vr.reset}`)}console.log()}f0.exports={gatherProjectContext:WM,printContext:HM,generateFileTree:FM,_clearContextCache:()=>{ap.clear(),Zr.clear(),Il=null,Jr={result:null,expiry:0,cwd:null}}}});var ds=Q((Vq,m0)=>{var us=require("fs"),Dl=require("path"),{atomicWrite:GM}=Hs();function la(){return Dl.join(process.cwd(),".nex","sessions")}function cp(){let e=la();us.existsSync(e)||us.mkdirSync(e,{recursive:!0,mode:448})}function lp(e){let t=e.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return Dl.join(la(),`${t}.json`)}function up(e,t,n={}){cp();let o=lp(e),s={name:e,createdAt:n.createdAt||new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:t.length,model:n.model||null,provider:n.provider||null,messages:t};return GM(o,JSON.stringify(s,null,2)),{path:o,name:e}}function p0(e){let t=lp(e);if(!us.existsSync(t))return null;try{return JSON.parse(us.readFileSync(t,"utf-8"))}catch{return null}}function h0(){cp();let e=la(),t=us.readdirSync(e).filter(o=>o.endsWith(".json")),n=[];for(let o of t)try{let s=JSON.parse(us.readFileSync(Dl.join(e,o),"utf-8"));n.push({name:s.name||o.replace(".json",""),createdAt:s.createdAt,updatedAt:s.updatedAt,messageCount:s.messageCount||0,model:s.model,provider:s.provider,score:s.score!=null?s.score:null,scoreGrade:s.scoreGrade||null})}catch{}return n.sort((o,s)=>(s.updatedAt||"").localeCompare(o.updatedAt||""))}function YM(e){let t=lp(e);return us.existsSync(t)?(us.unlinkSync(t),!0):!1}function zM(){let e=h0();return e.length===0?null:p0(e[0].name)}var yo=null,eo=null,ca=null;function KM(e,t={}){e.length!==0&&(yo&&clearTimeout(yo),eo=e,ca=t||{},yo=setTimeout(()=>{eo&&eo.length>0&&up("_autosave",eo,ca),yo=null,eo=null,ca=null},5e3),yo.unref?.())}function XM(){yo&&(clearTimeout(yo),yo=null),eo&&eo.length>0&&(up("_autosave",eo,ca),eo=null,ca=null)}function VM(){cp();let e=la(),t=us.readdirSync(e).filter(r=>r.endsWith(".json")),n=new Date,o=new Date(n.getTime()-720*60*60*1e3),s=0;for(let r of t){let i=Dl.join(e,r);try{let a=us.statSync(i);new Date(a.mtime)<o&&(us.unlinkSync(i),s++)}catch{}}return s}m0.exports={saveSession:up,loadSession:p0,listSessions:h0,deleteSession:YM,getLastSession:zM,autoSave:KM,flushAutoSave:XM,clearOldSessions:VM,_getSessionsDir:la}});var ql=Q((Jq,x0)=>{"use strict";var ua=require("fs"),g0=require("path");function y0(e){let t=[];return e.forEach((n,o)=>{n.role==="assistant"&&(Array.isArray(n.content)&&n.content.forEach(s=>{s&&s.type==="tool_use"&&t.push({name:s.name||"",input:s.input||{},index:o,id:s.id||null})}),Array.isArray(n.tool_calls)&&n.tool_calls.forEach(s=>{let r=s.function?.name||s.name||"",i={};try{i=typeof s.function?.arguments=="string"?JSON.parse(s.function.arguments):s.function?.arguments||s.input||{}}catch{}t.push({name:r,input:i,index:o,id:s.id||null})}))}),t}function JM(e){let t=new Set;return e.forEach(n=>{n.role==="tool"&&typeof n.content=="string"&&n.content.startsWith("BLOCKED:")&&n.tool_call_id&&t.add(n.tool_call_id),n.role==="user"&&Array.isArray(n.content)&&n.content.forEach(o=>{o&&o.type==="tool_result"&&o.tool_use_id&&typeof o.content=="string"&&o.content.startsWith("BLOCKED:")&&t.add(o.tool_use_id)})}),t}function $0(e){let t=[];return e.forEach((n,o)=>{if(n.role==="user"&&Array.isArray(n.content)&&n.content.forEach(s=>{if(s&&s.type==="tool_result"){let r=typeof s.content=="string"?s.content:Array.isArray(s.content)?s.content.map(i=>typeof i=="string"?i:i.text||"").join(""):JSON.stringify(s.content||"");t.push({content:r,index:o})}}),n.role==="tool"){let s=typeof n.content=="string"?n.content:JSON.stringify(n.content||"");t.push({content:s,index:o})}}),t}function b0(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="assistant"){if(typeof n.content=="string")return n.content.trim();if(Array.isArray(n.content)){let o=n.content.filter(s=>s&&(s.type==="text"||typeof s=="string")).map(s=>typeof s=="string"?s:s.text||"").join("").trim();if(o)return o}}}return""}function w0(e,t){let n=[];for(let o=e.length-1;o>=0&&n.length<t;o--){let s=e[o];if(s.role!=="assistant")continue;let r="";typeof s.content=="string"?r=s.content.trim():Array.isArray(s.content)&&(r=s.content.filter(i=>i&&(i.type==="text"||typeof i=="string")).map(i=>typeof i=="string"?i:i.text||"").join("").trim()),r&&n.push(r)}return n}function _0(e){let t=new Map;for(let n of e){let o;try{o=JSON.stringify(n.input)}catch{o=String(n.input)}let s=`${n.name}|${o}`;t.set(s,(t.get(s)||0)+1)}return t}function k0(e){if(!Array.isArray(e)||e.length===0)return{score:0,issues:["Empty or invalid session \u2014 no messages to analyse"],summary:"No messages found"};let t=10,n=[],o=y0(e),s=$0(e),r=o.length,i=JM(e),a=o.filter(R=>!R.id||!i.has(R.id));e.some(R=>R.role==="user"&&typeof R.content=="string"&&R.content.startsWith("[SYSTEM WARNING]")&&(R.content.includes("edited")||R.content.includes("bash command")||R.content.includes("grep pattern")||R.content.includes("re-read")||R.content.includes("already in your context")))&&(t-=2,n.push("Loop-warning was fired during session (repeated file edits, bash commands, or re-reads)"));let u=o.find(R=>{let v=R.input?.command||R.input?.cmd||"";return/\bsed\s+-n\b/.test(v)});if(u){let R=(u.input?.command||u.input?.cmd||"").slice(0,80);s.some(z=>z.content.includes("BLOCKED: sed -n is forbidden")||z.content.includes("BLOCKED: sed -n"))?(t-=.25,n.push(`sed -n attempted but blocked by agent guard: ${R}`)):(t-=1.5,n.push(`sed -n anti-pattern used: ${R}`))}o.find(R=>{if(R.name!=="grep"&&R.name!=="bash"&&R.name!=="ssh_exec")return!1;let v=R.input?.command||R.input?.cmd||"",z=R.input?.pattern||"",ne=`${v} ${z}`;return/(?:-[CAB]|--context|--after|--before)\s*[=\s]?([2-9][1-9]|\d{3,})/.test(ne)||/grep.*-[CAB]\s*([2-9][1-9]|\d{3,})/.test(ne)})&&(t-=1,n.push("grep used with >20 context lines (context flood risk)"));let f=e.some(R=>R.role==="assistant"),p=b0(e),m=w0(e,3).some(R=>R.length>100&&!/^[^.!]{0,40}\?$/.test(R));if(f&&!m&&(p.length<80||/^[^.!]{0,40}\?$/.test(p))){t-=2;let R=p.length>0?`"${p.slice(0,60)}..."`:"(no assistant text found)";n.push(`Session ends without diagnosis \u2014 last response too short or is only a question: ${R}`)}r>40?(t-=1.5,n.push(`Excessive tool calls: ${r} (>40 threshold)`)):r>25&&(t-=.5,n.push(`High tool call count: ${r} (>25 threshold)`)),e.some(R=>{let v=typeof R.content=="string"?R.content:Array.isArray(R.content)?R.content.map(z=>typeof z=="string"?z:z.text||"").join(""):"";return/\[auto-compressed|context compacted|force-compressed/.test(v)})&&(t-=.5,n.push("Auto-compress triggered (context flood indicator)"));let b=_0(a),x=0,_="";for(let[R,v]of b)v>x&&(x=v,_=R);if(x>=3){let[R]=_.split("|");t-=1,n.push(`Same tool call repeated ${x}\xD7 (tool: ${R})`)}let E=!1,S=e.findIndex(R=>R.role==="user"&&typeof R.content=="string"&&R.content.includes("[SYSTEM STOP]")&&R.content.includes('"valid":true'));S>=0&&o.filter(v=>v.index>S).length>0&&(E=!0),E&&(t-=1.5,n.push('Stop-trigger ignored: tool result contained "valid":true but session continued with more tool calls'));let O=o.filter(R=>R.name==="ssh_exec");if(O.length>=8){let R=0,v=1;for(let z=1;z<O.length;z++)O[z].index<=O[z-1].index+2?v++:(R=Math.max(R,v),v=1);R=Math.max(R,v),R>=8&&(t-=.5,n.push(`SSH reconnect storm: ${R} consecutive SSH calls`))}f&&O.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(p)&&(t-=2,n.push("Surrender: model asked user to manually provide server output instead of gathering it"));let L=new Map;for(let R of a)if(R.name==="read_file"&&R.input?.path){let v=R.input.path;L.has(v)||L.set(v,{count:0,ranges:[]});let z=L.get(v);if(z.count++,R.input.line_start!=null){let ne=R.input.line_start||1,te=R.input.line_end||ne+350;z.ranges.push([ne,te])}}function I(R,v,z){for(let[ne,te]of z){let M=Math.max(R,ne),ye=Math.min(v,te);if(ye>M){let Qe=ye-M,G=v-R||1;if(Qe/G>=.7)return!0}}return!1}let D=0,Z="";for(let[R,v]of L){if(v.count<3)continue;if(v.ranges.length===v.count){let te=!1,M=[];for(let[ye,Qe]of v.ranges){if(M.length>0&&I(ye,Qe,M)){te=!0;break}M.push([ye,Qe])}if(!te)continue}if(v.count-v.ranges.length<=2&&v.ranges.length>=1){let te=!1,M=[];for(let[ye,Qe]of v.ranges){if(M.length>0&&I(ye,Qe,M)){te=!0;break}M.push([ye,Qe])}if(!te)continue}v.count>D&&(D=v.count,Z=R)}if(D>=3){t-=1;let R=Z.split("/").slice(-2).join("/");n.push(`read_file loop: "${R}" read ${D}\xD7 (file already in context)`)}let K=0,X="";for(let[R,v]of L){if(v.ranges.length<4)continue;let z=[],ne=!1;for(let[te,M]of v.ranges){if(z.length>0&&I(te,M,z)){ne=!0;break}z.push([te,M])}!ne&&v.ranges.length>K&&(K=v.ranges.length,X=R)}if(K>=4){t-=.5;let R=X.split("/").slice(-2).join("/");n.push(`File-scroll pattern: "${R}" read in ${K} sequential sections \u2014 use grep instead`)}let Fe=new Map;for(let R of a)if(R.name==="grep"&&R.input?.path&&R.input?.pattern){let v=R.input.path;Fe.has(v)||Fe.set(v,new Set),Fe.get(v).add(R.input.pattern)}let Oe=0,V="";for(let[R,v]of Fe)R.split("/").pop().includes(".")&&v.size>Oe&&(Oe=v.size,V=R);if(Oe>=3){t-=.75;let R=V.split("/").slice(-2).join("/");n.push(`grep flood on single file: "${R}" searched ${Oe}\xD7 with different patterns (file already in context)`)}{let R=new Set,v=new Set,z=/^(test_|demo_|temp_|tmp_|scratch_)/;for(let te of o){if(te.name==="write_file"&&te.input?.path){let M=te.input.path.split("/").pop(),ye=te.input.path.includes("/tests/");z.test(M)&&!ye&&R.add(te.input.path)}if((te.name==="bash"||te.name==="ssh_exec")&&te.input?.command){let M=te.input.command.match(/\brm\s+(?:-\w+\s+)?(\S+)/g);if(M)for(let ye of M){let Qe=ye.split(/\s+/),G=Qe[Qe.length-1];for(let ue of R)(ue.endsWith(G)||G.endsWith(ue.split("/").pop()))&&v.add(ue)}}}let ne=v.size;if(ne>=1){let te=Math.min(ne*.25,.5);t-=te;let M=[...v].map(ye=>ye.split("/").pop()).join(", ");n.push(`Temp file write-then-delete: ${M} \u2014 write inline logic or use tests/ instead`)}}let re=s.filter(R=>R.content.startsWith("EXIT")).length;re>=10?(t-=1,n.push(`Bash exit-error storm: ${re} tool results started with EXIT (repeated failing commands)`)):re>=5&&(t-=.5,n.push(`Repeated bash errors: ${re} tool results with non-zero exit code`));for(let R of e){if(R.role!=="assistant")continue;let v="";if(typeof R.content=="string"?v=R.content:Array.isArray(R.content)&&(v=R.content.filter(G=>G&&(G.type==="text"||typeof G=="string")).map(G=>typeof G=="string"?G:G.text||"").join("")),v.length<=5e3)continue;let z=v.split(/(?<=\. )/).filter(G=>G.trim().length>0);if(z.length<6)continue;let ne=new Map;for(let G=0;G<=z.length-3;G++){let ue=z.slice(G,G+3).join("").trim();ue.length>30&&ne.set(ue,(ne.get(ue)||0)+1)}let te=0,M="";for(let[G,ue]of ne)ue>te&&(te=ue,M=G);if(te<3)continue;let Qe=M.length*te/v.length;if(Qe>=.4||te>=10){t-=1.5,n.push(`llm output loop: assistant message repeated content detected (${te}\xD7 same paragraph, ${Math.round(Qe*100)}% repeated)`);break}}{let R=new Set(["read_file","list_directory","search_files","glob","grep"]),v=e.some(ne=>Array.isArray(ne.tool_calls)?ne.tool_calls.some(te=>R.has(te.function?.name)):Array.isArray(ne.content)?ne.content.some(te=>te.type==="tool_use"&&R.has(te.name)):!1);e.some(ne=>ne.role==="assistant"&&typeof ne.content=="string"&&(ne.content.includes("## Steps")||ne.content.includes("/plan approve")))&&!v&&(t-=2,n.push("plan written without reading any files \u2014 LLM invented data structures from training knowledge (hallucination risk)"))}let rt=s.filter(R=>R.content.startsWith("BLOCKED:")&&!R.content.includes("BLOCKED: sed -n")&&!R.content.includes("SSH paused")&&!R.content.includes("SSH temporarily paused"));if(rt.length>0){let R=Math.min(rt.length*.5,1.5);t-=R,n.push(`${rt.length} tool call${rt.length===1?"":"s"} blocked (agent attempted denied actions)`)}let qe=e.filter(R=>{let v=typeof R.content=="string"?R.content:"";return/\[SYSTEM WARNING\] Context wiped \d+×/.test(v)}).length;if(qe>0){let R=Math.min(qe*1,2);t-=R,n.push(`Super-nuclear context wipe fired ${qe}\xD7 (context collapse \u2014 task too large or read loops)`)}{let R=!1,v=!1,z=!1;for(let te of o){if(te.name!=="bash")continue;let M=(te.input?.command||te.input?.cmd||"").trim();!(/cat\s*>/.test(M)||/<</.test(M))&&/\bcat\s+\S/.test(M)&&(R=!0),/^\s*ls(\s|$)/.test(M)&&!/npm|yarn|pnpm|make|git\b/.test(M)&&(v=!0),/\bfind\s+\S/.test(M)&&!/git\b|npm\b|-exec\b/.test(M)&&(z=!0)}let ne=[R,v,z].filter(Boolean).length;if(ne>0){let te=Math.min(ne*.25,.75);t-=te;let M=[];R&&M.push("cat (use read_file)"),v&&M.push("ls (use list_directory)"),z&&M.push("find (use glob)"),n.push(`bash used instead of dedicated tool: ${M.join(", ")}`)}}{let R=o.some(M=>(M.name==="write_file"||M.name==="Write")&&M.input?.path&&(M.input.path.endsWith("requirements.txt")||M.input.path.endsWith("Pipfile")||M.input.path.endsWith("pyproject.toml"))),v=o.some(M=>(M.name==="write_file"||M.name==="Write")&&M.input?.path&&M.input.path.endsWith("package.json")),z=o.filter(M=>(M.name==="bash"||M.name==="Bash")&&M.input?.command).map(M=>M.input.command),ne=z.some(M=>/pip\s+install|python\s+-m\s+venv/.test(M)),te=z.some(M=>/npm\s+install/.test(M));R&&!ne?(t-=1,n.push("wrote requirements.txt but never ran pip install \u2014 environment not bootstrapped")):v&&!te&&o.some(ye=>(ye.name==="write_file"||ye.name==="Write")&&ye.input?.path&&/(\/src\/|index\.js|App\.js|main\.js)/.test(ye.input.path))&&(t-=.75,n.push("created new React/Node project but never ran npm install \u2014 project is not runnable"))}if(f){let R=e.find(M=>M.role==="assistant"),v="";R&&(typeof R.content=="string"?v=R.content:Array.isArray(R.content)&&(v=R.content.filter(M=>M&&(M.type==="text"||typeof M=="string")).map(M=>typeof M=="string"?M:M.text||"").join("")));let z=v.slice(0,400),ne=/^[\d\s\+\-\*\/×÷\(\)\.]+\s*=\s*[\d\s\+\-\*\/×÷\(\)\.]+[.\n]/m,te=z.split(`
836
836
  `).find(M=>{let ye=M.trim();return ye.length>0&&ye.length<=30&&/^\d/.test(ye)&&/=/.test(ye)&&!/[a-zA-Z]/.test(ye)});if(ne.test(z)||te){t-=1.5;let M=(te||z.split(`
837
837
  `)[0]).trim().slice(0,40);n.push(`Thinking-chain leak: non-sequitur artifact at response start: "${M}"`)}}if(f&&r>0){let R=e.findIndex(z=>z.role==="assistant"),v=e.findIndex(z=>!!(Array.isArray(z.tool_calls)&&z.tool_calls.length>0||Array.isArray(z.content)&&z.content.some(ne=>ne&&ne.type==="tool_use")));if(R!==-1&&v!==-1&&R<v){let z=e[R],ne="";typeof z.content=="string"?ne=z.content:Array.isArray(z.content)&&(ne=z.content.filter(ye=>ye&&(ye.type==="text"||typeof ye=="string")).map(ye=>typeof ye=="string"?ye:ye.text||"").join(""));let te=/ssh\s+\S+@\S+\s+"[^"]*\/[^"]*\./.test(ne),M=/\/(?:home|var|etc|usr|opt|root|srv|data)\/[a-zA-Z0-9_.\-\/]+\.[a-zA-Z]{2,5}/.test(ne);(te||M)&&(t-=1,n.push("Answer-before-verify: model gave concrete file paths/SSH commands before making any tool calls (paths guessed, not verified)"))}}if(f){let R=p;if(R.length>100){let z=(R.match(/^```/gm)||[]).length%2!==0,ne=/"\s*:\s*$/.test(R.trimEnd()),te=/[,\[{]\s*$/.test(R.trimEnd());(z||ne||te)&&(t-=.75,n.push("Truncated response: last assistant message ends mid-code-block or mid-JSON (model hit token limit)"))}}{let R=[];e.forEach((z,ne)=>{let te=[];Array.isArray(z.tool_calls)&&z.tool_calls.forEach(M=>{if((M.function?.name||M.name||"")==="read_file"){let Qe={};try{Qe=typeof M.function?.arguments=="string"?JSON.parse(M.function.arguments):M.function?.arguments||{}}catch{}(Qe.path||"").endsWith(".json")&&te.push({id:M.id,path:Qe.path})}}),Array.isArray(z.content)&&z.content.forEach(M=>{M&&M.type==="tool_use"&&M.name==="read_file"&&(M.input?.path||"").endsWith(".json")&&te.push({id:M.id,path:M.input.path})}),te.forEach(M=>R.push({...M,msgIdx:ne}))});let v=0;for(let z of R){let ne=null;for(let M of e){if(M.role==="tool"&&M.tool_call_id===z.id&&typeof M.content=="string"){ne=M.content;break}if(M.role==="user"&&Array.isArray(M.content)){let ye=M.content.find(Qe=>Qe&&Qe.type==="tool_result"&&Qe.tool_use_id===z.id);if(ye){ne=typeof ye.content=="string"?ye.content:"";break}}}if(!ne)continue;ne.split(`
838
- `).filter(M=>M.trim()).length<5&&/^\s*\[/.test(ne)&&!/\]\s*$/.test(ne.trimEnd())&&v++}v>=1&&(t-=.75,n.push(`Shallow JSON read: ${v} .json file${v>1?"s":""} read with < 5 lines \u2014 array was incomplete, model drew conclusions from truncated data`))}{let R=s.filter(v=>/argument errors?/i.test(v.content)||/missing required (argument|parameter)/i.test(v.content)||/invalid argument/i.test(v.content));R.length>=3?(t-=.75,n.push(`Repeated tool argument errors: ${R.length} tool calls returned argument errors \u2014 model couldn't correct its tool usage`)):R.length>=2&&(t-=.25,n.push(`Tool argument errors: ${R.length} tool calls returned argument errors`))}{let R=!1,v=0,z=0;for(let ne of a){if((ne.name==="bash"||ne.name==="Bash")&&ne.input?.command&&/git\s+commit\b/.test(ne.input.command)){R&&(z=Math.max(z,v)),R=!0,v=0;continue}R&&(ne.name==="bash"||ne.name==="Bash")&&ne.input?.command&&/git\s+(status|diff|log|show)\b/.test(ne.input.command)&&v++}z=Math.max(z,v),z>=3&&(t-=.75,n.push(`Post-commit verification waste: ${z} git status/diff/log calls after commit`))}t=Math.max(0,Math.min(10,t)),t=Math.round(t*10)/10;let _e=t>=9?"A":t>=8?"B":t>=7?"C":t>=6?"D":"F",Me=n.length===0?`Clean session \u2014 no quality issues detected (${r} tool calls)`:`${n.length} issue${n.length===1?"":"s"} found \u2014 ${r} tool calls`;return{score:t,grade:_e,issues:n,summary:Me}}function ZM(e){try{let{loadSession:t}=ds(),n=t(e);return n?k0(n.messages||[]):null}catch{return null}}function QM(e,t=null){let{score:n,issues:o}=e,s=t?.dim||"",r=t?.reset||"",i=t?.yellow||"";if(n>=8||o.length===0)return"";let a=o.map(d=>d.replace(/:\s+\d+.*$/,"").replace(/\s*\(.*?\)/,"").replace(/\s*—.*$/,""));if(n>=6){let d=a.slice(0,3),f=a.length-d.length,p=d.join(" \xB7 ");return f>0&&(p+=` (+${f})`),`
838
+ `).filter(M=>M.trim()).length<5&&/^\s*\[/.test(ne)&&!/\]\s*$/.test(ne.trimEnd())&&v++}v>=1&&(t-=.75,n.push(`Shallow JSON read: ${v} .json file${v>1?"s":""} read with < 5 lines \u2014 array was incomplete, model drew conclusions from truncated data`))}{let R=s.filter(v=>/argument errors?/i.test(v.content)||/missing required (argument|parameter)/i.test(v.content)||/invalid argument/i.test(v.content));R.length>=3?(t-=.75,n.push(`Repeated tool argument errors: ${R.length} tool calls returned argument errors \u2014 model couldn't correct its tool usage`)):R.length>=2&&(t-=.25,n.push(`Tool argument errors: ${R.length} tool calls returned argument errors`))}{let R=!1,v=0,z=0;for(let ne of a){if((ne.name==="bash"||ne.name==="Bash")&&ne.input?.command&&/git\s+commit\b/.test(ne.input.command)){R&&(z=Math.max(z,v)),R=!0,v=0;continue}R&&(ne.name==="bash"||ne.name==="Bash")&&ne.input?.command&&/git\s+(status|diff|log|show)\b/.test(ne.input.command)&&v++}z=Math.max(z,v),z>=3&&(t-=.75,n.push(`Post-commit verification waste: ${z} git status/diff/log calls after commit`))}t=Math.max(0,Math.min(10,t)),t=Math.round(t*10)/10;let ke=t>=9?"A":t>=8?"B":t>=7?"C":t>=6?"D":"F",Me=n.length===0?`Clean session \u2014 no quality issues detected (${r} tool calls)`:`${n.length} issue${n.length===1?"":"s"} found \u2014 ${r} tool calls`;return{score:t,grade:ke,issues:n,summary:Me}}function ZM(e){try{let{loadSession:t}=ds(),n=t(e);return n?k0(n.messages||[]):null}catch{return null}}function QM(e,t=null){let{score:n,issues:o}=e,s=t?.dim||"",r=t?.reset||"",i=t?.yellow||"";if(n>=8||o.length===0)return"";let a=o.map(d=>d.replace(/:\s+\d+.*$/,"").replace(/\s*\(.*?\)/,"").replace(/\s*—.*$/,""));if(n>=6){let d=a.slice(0,3),f=a.length-d.length,p=d.join(" \xB7 ");return f>0&&(p+=` (+${f})`),`
839
839
  ${s}${p}${r}`}let c="";for(let d of a.slice(0,4))c+=`
840
840
  ${i}\u26A0${r} ${s}${d}${r}`;let u=a.length-4;return u>0&&(c+=`
841
841
  ${s}(+${u} more)${r}`),c}function eP(e,t={}){try{let n=g0.join(process.cwd(),".nex");ua.existsSync(n)||ua.mkdirSync(n,{recursive:!0});let o=g0.join(n,"benchmark-history.json"),s=[];if(ua.existsSync(o))try{s=JSON.parse(ua.readFileSync(o,"utf-8"))}catch{s=[]}Array.isArray(s)||(s=[]);let r=e>=9?"A":e>=8?"B":e>=7?"C":e>=6?"D":"F",i={date:new Date().toISOString(),version:t.version||null,model:t.model||null,score:e,grade:r,sessionName:t.sessionName||null,issues:Array.isArray(t.issues)?t.issues:[]};s.push(i),s.length>100&&(s=s.slice(s.length-100)),ua.writeFileSync(o,JSON.stringify(s,null,2))}catch{}}x0.exports={scoreMessages:k0,scoreSession:ZM,formatScore:QM,appendScoreHistory:eP,_extractToolCalls:y0,_extractToolResults:$0,_getLastAssistantText:b0,_getLastNAssistantTexts:w0,_countDuplicateToolCalls:_0}});var fs=Q((Zq,R0)=>{"use strict";var tP=require("os"),dp=require("path"),$o=require("fs"),da=dp.join(tP.homedir(),".nex-code","model-routing.json"),Fl={"bug-fix":{id:"bug-fix",label:"Bug Fix",icon:"\u{1F41B}",envVar:"NEX_ROUTE_BUG_FIX",pattern:/\b(bug|crash|broken|fail|patch|stack\s*trace|typeerror|referenceerror|syntaxerror|unhandled|throw|throws|exception|root\s*cause|debug\s+(?:the\s+)?(?:stack|trace|issue|error)|resolve\s*(?:the|this)\s*(?:issue|bug|error|problem))\b/i},"feature-add":{id:"feature-add",label:"Feature",icon:"\u2728",envVar:"NEX_ROUTE_FEATURE",pattern:/\b(add|create|implement|build|scaffold|generate|new\s+feature|feature\s+request|enhancement|extend|introduce)\b/i},refactor:{id:"refactor",label:"Refactor",icon:"\u{1F527}",envVar:"NEX_ROUTE_REFACTOR",pattern:/\b(refactor|rewrite|restructure|reorgani[sz]e|clean\s*up|cleanup|simplify|extract\s+(?:function|method|class|component|module)|rename|move\s+(?:to|into)|split\s+(?:into|up)|consolidate|moderni[sz]e)\b/i},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}},v0=["agentic","frontend","sysadmin","data","bug-fix","feature-add","refactor","coding"];function nP(e){if(!e||e.length<8)return null;for(let t of v0){let n=Fl[t];if(!n.pattern||n.pattern.test(e))return n}return Fl.coding}function fa(){try{if($o.existsSync(da))return JSON.parse($o.readFileSync(da,"utf-8"))}catch{}return{}}function S0(e){if(process.env.NEX_FORCE_MODEL)return process.env.NEX_FORCE_MODEL;let t=Fl[e];return t?.envVar&&process.env[t.envVar]?process.env[t.envVar]:fa()[e]||null}var E0={explore:10,plan:10,implement:35,verify:8},fp={explore:"devstral-small-2:24b",plan:"qwen3-coder:480b",implement:null,verify:"devstral-small-2:24b"};function T0(){let e=fa();if(e.phases&&Object.keys(e.phases).length>0)return e.phases;try{let{getActiveProviderName:t}=ft();if(t()==="ollama")return fp}catch{}return process.env.NEX_PHASE_ROUTING==="1"?fp:null}function sP(e,t){if(process.env.NEX_FORCE_MODEL)return process.env.NEX_FORCE_MODEL;let n=T0();return n?.[e]?n[e]:t?S0(t):null}function oP(e){return fa().phaseBudgets?.[e]||E0[e]||20}function rP(){return process.env.NEX_PHASE_ROUTING==="0"||process.env.NEX_FORCE_MODEL?!1:T0()!==null}function iP(e){let t=dp.dirname(da);$o.existsSync(t)||$o.mkdirSync(t,{recursive:!0});let n=fa(),o={...n,...e};!e.phases&&n.phases&&(o.phases=n.phases),!e.phaseBudgets&&n.phaseBudgets&&(o.phaseBudgets=n.phaseBudgets),$o.writeFileSync(da,JSON.stringify(o,null,2));try{let s=dp.join(t,".env"),r="";$o.existsSync(s)&&(r=$o.readFileSync(s,"utf-8"));let i=r.split(/\r?\n/),a=(c,u)=>{let d=i.findIndex(f=>f.startsWith(c+"="));d>=0?i[d]=`${c}=${u}`:i.push(`${c}=${u}`)};o.coding&&a("NEX_ROUTE_CODING",o.coding),o.frontend&&a("NEX_ROUTE_FRONTEND",o.frontend),o.sysadmin&&a("NEX_ROUTE_SYSADMIN",o.sysadmin),o.data&&a("NEX_ROUTE_DATA",o.data),o.agentic&&a("NEX_ROUTE_AGENTIC",o.agentic),o.phases&&(o.phases.plan&&a("NEX_PHASE_PLAN_MODEL",o.phases.plan),o.phases.implement&&a("NEX_PHASE_IMPLEMENT_MODEL",o.phases.implement),o.phases.verify&&a("NEX_PHASE_VERIFY_MODEL",o.phases.verify)),$o.writeFileSync(s,i.filter(c=>c.trim()!=="").join(`
@@ -949,7 +949,7 @@ ${n.join(`
949
949
  `:""}async function r_(e,t,n={}){let o=n.maxSubTasks||Gl,s=ZP(),r=s?`${e}
950
950
 
951
951
  ${s}
952
- Use the project structure above to scope sub-tasks to real files and directories. Do not invent paths or files that do not exist.`:e,a=[{role:"system",content:e_.replace("{maxSubTasks}",String(o)).replace("{prompt}",r)},{role:"user",content:e}],c={};if(t){let b=V0(t);b.provider&&(c.provider=b.provider),b.model&&(c.model=b.model)}let d=(await X0(a,[],c)).content||"",f=wp(d);if(!Array.isArray(f))throw new Error(`Decompose returned non-array: ${typeof f}`);let p=10,m=f.slice(0,o).map((b,x)=>({id:b.id||`t${x+1}`,task:String(b.task||""),scope:Array.isArray(b.scope)?b.scope:[],estimatedCalls:typeof b.estimatedCalls=="number"?Math.min(b.estimatedCalls,p):8,priority:typeof b.priority=="number"?b.priority:x+1})).filter(b=>b.task.length>0),g=m.reduce((b,x)=>b+x.estimatedCalls,0),$=Gl*p;if(g>$){let{debugLog:b}=Wc();b(`${ln().T.yellow} \u26A0 Orchestrator: total estimated calls ${g} > ${$} \u2014 consider raising maxSubTasks${ln().T.reset}`)}return m}async function i_(e,t,n){if(!e||e.length===0)return{summary:"No sub-tasks were executed.",conflicts:[],commitMessage:"",resourcesChanged:[]};let o=e.map((p,h)=>{let m=p.status==="done"?"SUCCESS":p.status==="truncated"?"PARTIAL":"FAILED";return`--- Agent ${h+1} [${m}] ---
952
+ Use the project structure above to scope sub-tasks to real files and directories. Do not invent paths or files that do not exist.`:e,a=[{role:"system",content:e_.replace("{maxSubTasks}",String(o)).replace("{prompt}",r)},{role:"user",content:e}],c={};if(t){let b=V0(t);b.provider&&(c.provider=b.provider),b.model&&(c.model=b.model)}let d=(await X0(a,[],c)).content||"",f=wp(d);if(!Array.isArray(f))throw new Error(`Decompose returned non-array: ${typeof f}`);let p=10,m=f.slice(0,o).map((b,x)=>({id:b.id||`t${x+1}`,task:String(b.task||""),scope:Array.isArray(b.scope)?b.scope:[],estimatedCalls:typeof b.estimatedCalls=="number"?Math.min(b.estimatedCalls,p):8,priority:typeof b.priority=="number"?b.priority:x+1})).filter(b=>b.task.length>0),g=m.reduce((b,x)=>b+x.estimatedCalls,0),y=Gl*p;if(g>y){let{debugLog:b}=Wc();b(`${ln().T.yellow} \u26A0 Orchestrator: total estimated calls ${g} > ${y} \u2014 consider raising maxSubTasks${ln().T.reset}`)}return m}async function i_(e,t,n){if(!e||e.length===0)return{summary:"No sub-tasks were executed.",conflicts:[],commitMessage:"",resourcesChanged:[]};let o=e.map((p,h)=>{let m=p.status==="done"?"SUCCESS":p.status==="truncated"?"PARTIAL":"FAILED";return`--- Agent ${h+1} [${m}] ---
953
953
  Task: ${p.task}
954
954
  Result: ${p.result}
955
955
  Tools: ${(p.toolsUsed||[]).join(", ")||"none"}`}).join(`
@@ -957,7 +957,7 @@ Tools: ${(p.toolsUsed||[]).join(", ")||"none"}`}).join(`
957
957
  `),r=[{role:"system",content:t_.replace("{prompt}",t).replace("{results}",o)},{role:"user",content:"Synthesize the sub-agent results above."}],i={};if(n){let p=V0(n);p.provider&&(i.provider=p.provider),p.model&&(i.model=p.model)}let c=(await X0(r,[],i)).content||"",u=wp(c),d={summary:String(u.summary||""),conflicts:Array.isArray(u.conflicts)?u.conflicts:[],commitMessage:String(u.commitMessage||""),filesChanged:Array.isArray(u.filesChanged)?u.filesChanged:[]},f=a_(d,e);return f&&(d.commitMessage="",d.commitSuppressedReason=f),d}function a_(e,t){let n=/\b(fail(?:ed|ure|s)?|did not pass|tests? (?:are )?failing|red|broken)\b/i,o=/\b(reported|claimed|said)\b.*\b(pass|fail)/i;for(let s of e.conflicts)if(typeof s=="string"){if(n.test(s))return"conflict mentions failure";if(o.test(s)&&/pass/i.test(s)&&/fail/i.test(s))return"agents disagree on pass/fail"}for(let s of t){if(s.status==="error"||s.status==="failed"||s.status==="skipped")return`agent reported ${s.status}`;let r=String(s.result||"");if(/\b(test(?:s)? fail|verification fail|build (?:error|fail))/i.test(r))return"agent result describes test/build failure"}return null}async function QP(e,t={}){let n=t.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL||Q0,o=t.workerModel||Z0,s=t.maxParallel||J0,r=t.maxSubTasks||Gl,i=t.onProgress||(()=>{}),a={input:0,output:0};console.log(`
958
958
  ${Le.bold}Orchestrator${Le.reset} ${Le.dim}model: ${n} | workers: ${o} | max parallel: ${s}${Le.reset}
959
959
  `),i("decomposing"),console.log(`${Le.dim}Phase 1: Decomposing prompt into sub-tasks...${Le.reset}`);let c;try{c=await r_(e,n,{maxSubTasks:r})}catch(V){return console.log(`${Le.red}Decompose failed: ${V.message}${Le.reset}`),{results:[],synthesis:{summary:`Decompose failed: ${V.message}`,conflicts:[],commitMessage:"",resourcesChanged:[]},totalTokens:a}}if(c.length===0)return console.log(`${Le.yellow}No sub-tasks generated. Prompt may be too simple for orchestration.${Le.reset}`),{results:[],synthesis:{summary:"No sub-tasks generated.",conflicts:[],commitMessage:"",resourcesChanged:[]},totalTokens:a};console.log(`${Le.green}Decomposed into ${c.length} sub-tasks:${Le.reset}`);for(let V of c){console.log(` ${Le.dim}${V.id}:${Le.reset} ${V.task}`);let re=V.scope.filter(Boolean);re.length>0&&console.log(` ${Le.dim}scope: ${re.join(", ")}${Le.reset}`)}console.log("");let u=new Map;for(let V=0;V<c.length;V++)for(let re of c[V].scope)re&&!u.has(re)&&u.set(re,V);i("executing"),console.log(`${Le.dim}Phase 2: Running ${c.length} sub-agents (max ${s} parallel)...${Le.reset}
960
- `);let d=Date.now(),f=s_(s),p={findings:[],_lock:!1},h=c.map(V=>{let re=XP(V.task);return(re?K0(re.id):null)||o}),m=c.map((V,re)=>{let rt=`Agent ${re+1} [${h[re]}]: `,qe=Math.max(20,60-rt.length),_e=V.task.substring(0,qe)+(V.task.length>qe?"...":"");return rt+_e}),g=new VP(m);g.start();let $=`
960
+ `);let d=Date.now(),f=s_(s),p={findings:[],_lock:!1},h=c.map(V=>{let re=XP(V.task);return(re?K0(re.id):null)||o}),m=c.map((V,re)=>{let rt=`Agent ${re+1} [${h[re]}]: `,qe=Math.max(20,60-rt.length),ke=V.task.substring(0,qe)+(V.task.length>qe?"...":"");return rt+ke}),g=new VP(m);g.start();let y=`
961
961
  You are a focused coding agent executing ONE specific sub-task.
962
962
  Your scope is limited to the files listed in your task definition.
963
963
 
@@ -981,23 +981,23 @@ RULES:
981
981
  - Start with symbol-aware reads inside your scope: locate the target function/class/module, then read the exact section instead of scanning broadly.
982
982
  - Before finishing, run the smallest relevant verification for your scope and report any residual risk explicitly.
983
983
  - If your sub-task is review/audit/verify/preflight-oriented, do not edit files. Output findings or the blocker first with severity, file/resource, and impact. If nothing is wrong, say so explicitly and mention remaining risk.
984
- `,b=new Map;for(let V=0;V<c.length;V++){let re=c[V].priority||1;b.has(re)||b.set(re,[]),b.get(re).push({st:c[V],idx:V})}let x=[...b.keys()].sort((V,re)=>V-re),_=new Array(c.length),E=null;for(let V of x){let rt=b.get(V).map(async({st:Me,idx:R})=>{let v=await f();try{let z=await S(Me,R,{acquire:f,subTaskModels:h,labels:m,progress:g,sharedContext:p,_fileOwnership:u,workerModel:o,WORKER_SYSTEM_PROMPT:$});return _[R]=z,z}finally{v()}}),_e=(await Promise.all(rt)).find(Me=>u_(c[Me?._idx],Me,V,x));if(_e){E={task:c[_e._idx]?.task||_e.task||"unknown task",result:_e.result||""};break}}if(E)for(let V=0;V<_.length;V++)_[V]||(_[V]={task:c[V].task,status:"skipped",result:`Skipped because prerequisite failed: ${E.task}`,toolsUsed:[],tokensUsed:{input:0,output:0},_scope:c[V].scope,_idx:V});async function S(V,re,rt){try{let qe=p.findings.filter(G=>G.agentId!==V.id).map(G=>`Agent ${G.agentId} found: ${G.summary}`).join(`
985
- `),_e=[...u.entries()].filter(([,G])=>G===re).map(([G])=>G),Me=[...u.entries()].filter(([,G])=>G!==re).map(([G])=>G),R=f_(V.task),v=[`Worker mode: ${R}`,qe?`Prior agent findings:
984
+ `,b=new Map;for(let V=0;V<c.length;V++){let re=c[V].priority||1;b.has(re)||b.set(re,[]),b.get(re).push({st:c[V],idx:V})}let x=[...b.keys()].sort((V,re)=>V-re),_=new Array(c.length),E=null;for(let V of x){let rt=b.get(V).map(async({st:Me,idx:R})=>{let v=await f();try{let z=await S(Me,R,{acquire:f,subTaskModels:h,labels:m,progress:g,sharedContext:p,_fileOwnership:u,workerModel:o,WORKER_SYSTEM_PROMPT:y});return _[R]=z,z}finally{v()}}),ke=(await Promise.all(rt)).find(Me=>u_(c[Me?._idx],Me,V,x));if(ke){E={task:c[ke._idx]?.task||ke.task||"unknown task",result:ke.result||""};break}}if(E)for(let V=0;V<_.length;V++)_[V]||(_[V]={task:c[V].task,status:"skipped",result:`Skipped because prerequisite failed: ${E.task}`,toolsUsed:[],tokensUsed:{input:0,output:0},_scope:c[V].scope,_idx:V});async function S(V,re,rt){try{let qe=p.findings.filter(G=>G.agentId!==V.id).map(G=>`Agent ${G.agentId} found: ${G.summary}`).join(`
985
+ `),ke=[...u.entries()].filter(([,G])=>G===re).map(([G])=>G),Me=[...u.entries()].filter(([,G])=>G!==re).map(([G])=>G),R=f_(V.task),v=[`Worker mode: ${R}`,qe?`Prior agent findings:
986
986
  ${qe}
987
- `:"",V.scope.length>0?`Focus on files: ${V.scope.join(", ")}`:"",_e.length>0?`You OWN these files (may read+write): ${_e.join(", ")}`:"",Me.length>0?`READ ONLY (owned by other agents, do NOT write): ${Me.join(", ")}`:""].filter(Boolean),z=h[re],ne=process.env.NEX_FALLBACK_MODEL||K0("agentic")||o,te=0,M=await n_(async()=>{let G=te>0;G&&(g.update(re,"retry"),process.stderr.write(` ${Le.dim}[Agent ${re+1}] retrying after error...${Le.reset}
987
+ `:"",V.scope.length>0?`Focus on files: ${V.scope.join(", ")}`:"",ke.length>0?`You OWN these files (may read+write): ${ke.join(", ")}`:"",Me.length>0?`READ ONLY (owned by other agents, do NOT write): ${Me.join(", ")}`:""].filter(Boolean),z=h[re],ne=process.env.NEX_FALLBACK_MODEL||K0("agentic")||o,te=0,M=await n_(async()=>{let G=te>0;G&&(g.update(re,"retry"),process.stderr.write(` ${Le.dim}[Agent ${re+1}] retrying after error...${Le.reset}
988
988
  `)),te++;let ue=G&&z!==ne?ne:z;return z0({task:V.task,type:R,context:v.length>0?v.join(`
989
- `):void 0,max_iterations:Math.min(V.estimatedCalls||10,15),model:ue,_skipLog:!0,_systemPrompt:$,_readOnlyFiles:Me},{onUpdate:ve=>{if(ve&&ve.type==="tool_call"&&process.stderr.isTTY){let ke=`Agent ${re+1} [${ue}]`,ge=ve.tool||"...";g.labels[re]=`${ke}: ${ge}`}}})},1,2e3),ye="";if(l_(R,M,V,_e)){let G=[...new Set([..._e,...Array.isArray(M.filesModified)?M.filesModified:[],...Array.isArray(V.scope)?V.scope:[]])].filter(Boolean);try{g.labels[re]=`Agent ${re+1} [${z}] review`,g.update(re,"retry");let ue=await z0({task:`Review the completed changes for: ${V.task}`,type:"review",context:sN(V,M,G),max_iterations:4,model:z,_skipLog:!0,_systemPrompt:$},{onUpdate:()=>{}},1);c_(ue.result)?(ye=`
989
+ `):void 0,max_iterations:Math.min(V.estimatedCalls||10,15),model:ue,_skipLog:!0,_systemPrompt:y,_readOnlyFiles:Me},{onUpdate:ve=>{if(ve&&ve.type==="tool_call"&&process.stderr.isTTY){let xe=`Agent ${re+1} [${ue}]`,ge=ve.tool||"...";g.labels[re]=`${xe}: ${ge}`}}})},1,2e3),ye="";if(l_(R,M,V,ke)){let G=[...new Set([...ke,...Array.isArray(M.filesModified)?M.filesModified:[],...Array.isArray(V.scope)?V.scope:[]])].filter(Boolean);try{g.labels[re]=`Agent ${re+1} [${z}] review`,g.update(re,"retry");let ue=await z0({task:`Review the completed changes for: ${V.task}`,type:"review",context:sN(V,M,G),max_iterations:4,model:z,_skipLog:!0,_systemPrompt:y},{onUpdate:()=>{}},1);c_(ue.result)?(ye=`
990
990
 
991
991
  Reviewer findings:
992
992
  ${ue.result}`,p.findings.push({agentId:`${V.id}-review`,summary:String(ue.result||"").slice(0,200),files:G})):ue.result&&(ye=`
993
993
 
994
994
  Reviewer: ${ue.result}`)}catch(ue){ye=`
995
995
 
996
- Reviewer note: review pass failed (${ue.message})`}}let Qe=typeof M.result=="string"?`${M.result}${ye}`.slice(0,200):`${String(M.result||"")}${ye}`.slice(0,200);return p.findings.push({agentId:V.id,summary:Qe,files:Array.isArray(V.scope)?V.scope:[]}),g.labels[re]=m[re],g.update(re,M.status==="failed"?"error":"done"),a.input+=M.tokensUsed?.input||0,a.output+=M.tokensUsed?.output||0,M.tokensUsed?._estimated&&(a._estimated=!0),{...M,result:`${String(M.result||"")}${ye}`,_scope:V.scope,_idx:re}}catch(qe){return g.labels[re]=m[re],g.update(re,"error"),{task:V.task,status:"failed",result:`Error: ${qe.message}`,toolsUsed:[],tokensUsed:{input:0,output:0},_scope:V.scope,_idx:re}}}let O;try{O=_}finally{g.stop({silent:!0}),KP()}console.log("");let L=Math.round((Date.now()-d)/1e3),I=L>=60?`${Math.floor(L/60)}m ${L%60}s`:`${L}s`;for(let V=0;V<O.length;V++){let re=O[V],qe=re.status==="done"||re.status==="truncated"&&re.result&&!re.result.startsWith("Error")?`${Le.green}\u2713${Le.reset}`:`${Le.red}\u2717${Le.reset}`,_e=re._scope&&re._scope.length>0?re._scope.map(v=>v.replace(/^.*\//,"").replace(/\/$/,"")).filter(Boolean):[],Me=_e.length>0?_e.join(", "):re.task.substring(0,35)+(re.task.length>35?"...":""),R=V===O.length-1;console.log(` ${qe} Agent ${V+1} ${Le.dim}${Me}${Le.reset}${R?` ${Le.dim}${I}${Le.reset}`:""}`)}console.log(""),i("synthesizing"),console.log(`${Le.dim}Phase 3: Synthesizing results...${Le.reset}`);let D;if(E)D={summary:`Stopped before continuing because prerequisite sub-task failed: ${E.task}. ${E.result}`,conflicts:[],commitMessage:"",commitSuppressedReason:"prerequisite sub-task failed",filesChanged:[],resourcesChanged:[]};else try{D=await i_(O,e,n)}catch(V){console.log(`${Le.yellow}Synthesize failed: ${V.message} \u2014 using raw results.${Le.reset}`),D={summary:O.map(re=>re.result).join(`
996
+ Reviewer note: review pass failed (${ue.message})`}}let Qe=typeof M.result=="string"?`${M.result}${ye}`.slice(0,200):`${String(M.result||"")}${ye}`.slice(0,200);return p.findings.push({agentId:V.id,summary:Qe,files:Array.isArray(V.scope)?V.scope:[]}),g.labels[re]=m[re],g.update(re,M.status==="failed"?"error":"done"),a.input+=M.tokensUsed?.input||0,a.output+=M.tokensUsed?.output||0,M.tokensUsed?._estimated&&(a._estimated=!0),{...M,result:`${String(M.result||"")}${ye}`,_scope:V.scope,_idx:re}}catch(qe){return g.labels[re]=m[re],g.update(re,"error"),{task:V.task,status:"failed",result:`Error: ${qe.message}`,toolsUsed:[],tokensUsed:{input:0,output:0},_scope:V.scope,_idx:re}}}let O;try{O=_}finally{g.stop({silent:!0}),KP()}console.log("");let L=Math.round((Date.now()-d)/1e3),I=L>=60?`${Math.floor(L/60)}m ${L%60}s`:`${L}s`;for(let V=0;V<O.length;V++){let re=O[V],qe=re.status==="done"||re.status==="truncated"&&re.result&&!re.result.startsWith("Error")?`${Le.green}\u2713${Le.reset}`:`${Le.red}\u2717${Le.reset}`,ke=re._scope&&re._scope.length>0?re._scope.map(v=>v.replace(/^.*\//,"").replace(/\/$/,"")).filter(Boolean):[],Me=ke.length>0?ke.join(", "):re.task.substring(0,35)+(re.task.length>35?"...":""),R=V===O.length-1;console.log(` ${qe} Agent ${V+1} ${Le.dim}${Me}${Le.reset}${R?` ${Le.dim}${I}${Le.reset}`:""}`)}console.log(""),i("synthesizing"),console.log(`${Le.dim}Phase 3: Synthesizing results...${Le.reset}`);let D;if(E)D={summary:`Stopped before continuing because prerequisite sub-task failed: ${E.task}. ${E.result}`,conflicts:[],commitMessage:"",commitSuppressedReason:"prerequisite sub-task failed",filesChanged:[],resourcesChanged:[]};else try{D=await i_(O,e,n)}catch(V){console.log(`${Le.yellow}Synthesize failed: ${V.message} \u2014 using raw results.${Le.reset}`),D={summary:O.map(re=>re.result).join(`
997
997
  `),conflicts:[],commitMessage:"",resourcesChanged:[]}}let Z=p.findings.flatMap(V=>V.files),K=new Map;for(let V of Z)K.set(V,(K.get(V)||0)+1);let X=[...K.values()].some(V=>V>1),Fe=p.findings.length>1&&X?` ${Le.dim}(agents shared context)${Le.reset}`:"";if(console.log(`
998
998
  ${Le.bold}Summary:${Le.reset} ${D.summary}${Fe}`),D.conflicts.length>0){console.log(`${Le.yellow}Conflicts:${Le.reset}`);for(let V of D.conflicts)console.log(` - ${V}`)}D.commitMessage?console.log(`${Le.dim}Suggested commit: ${D.commitMessage}${Le.reset}`):D.commitSuppressedReason&&console.log(`${Le.yellow}No commit suggested:${Le.reset} ${D.commitSuppressedReason}`);let Oe=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(`${Le.dim}Tokens: ${Oe}${Le.reset}
999
999
  `),{results:O,synthesis:D,totalTokens:a}}var eN=/\b(research|analyze|investigate|check|verify|review|audit|read|find|search|discover|look|examine|inspect|scan|list)\b/i,tN=/\b(review|audit|verify|validate|inspect|critique)\b/i,nN=/\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 sN(e,t,n){let o=Array.isArray(n)&&n.length>0?`Files to review: ${n.join(", ")}`:"Files to review: inspect the files touched by the implementing agent";return["Review the finished implementation for correctness, regressions, and missing verification.",`Original task: ${e.task}`,o,`Implementation summary: ${String(t.result||"").slice(0,600)}`,'Report findings first. If no material issue exists, say "No material findings" and mention the main residual risk.'].join(`
1000
- `)}function c_(e){return!e||typeof e!="string"?!1:!/no material findings/i.test(e)}function l_(e,t,n,o){if(e!=="implement"||!t||t.status==="failed")return!1;let s=Array.isArray(n?.scope)?n.scope.length:0,r=Array.isArray(t.filesModified)?t.filesModified.length:0,i=Array.isArray(o)?o.length:0;return s+r+i>0}function u_(e,t,n,o){return oN(t)?d_(e)?!0:o.some(r=>r>n)&&n===o[0]:!1}function oN(e){return e&&(e.status==="failed"||e.status==="error"||e.status==="skipped")}function d_(e){let t=typeof e=="string"?e:`${e?.task||""} ${(e?.scope||[]).join(" ")}`;return/\b(preflight|git status|current branch|worktree|dirty|unrelated changes?|clean working tree|pull\/rebase|rebase|before changing|before editing|stop without|abort|blocker|verification gate|release gate)\b/i.test(t)}function f_(e){if(!e)return"implement";let t=eN.test(e),n=tN.test(e);return nN.test(e)?"implement":n?"review":t?"explore":"implement"}p_.exports={runOrchestrated:QP,decompose:r_,synthesize:i_,shouldSuppressCommit:a_,detectComplexPrompt:JP,detectCriticalPathPrompt:o_,extractJSON:wp,createSemaphore:s_,DECOMPOSE_PROMPT:e_,SYNTHESIZE_PROMPT:t_,DEFAULT_ORCHESTRATOR_MODEL:Q0,DEFAULT_WORKER_MODEL:Z0,DEFAULT_MAX_PARALLEL:J0,DEFAULT_MAX_SUBTASKS:Gl,withRetry:n_,_classifyWorkerType:f_,_hasMaterialReviewFindings:c_,_shouldRunFollowUpReview:l_,_shouldAbortAfterWave:u_,_isBlockingTask:d_}});var We=Q((hF,ok)=>{var{C:y,Spinner:ri,TaskProgress:rN,formatToolCall:iN,formatToolSummary:Ia,formatSectionHeader:$a,formatMilestone:aN,setActiveTaskProgress:lF,getThinkingVerb:_p,setActiveModelForSpinner:kp}=dt(),{debugLog:j,warnLog:uF}=Wc(),{MilestoneTracker:cN}=Yg(),{callStream:Yl}=ft(),{parseToolArgs:lN}=Go(),{executeTool:eh}=rs(),{gatherProjectContext:uN}=jl(),{fitToContext:dN,forceCompress:As,getUsage:hs,estimateTokens:fN,buildProgressSnapshot:pN}=Mn(),{autoSave:hN,flushAutoSave:mN}=ds(),{scoreMessages:gN,formatScore:yN,appendScoreHistory:$N}=ql(),{detectCategory:bN,getModelForPhase:Lp,getPhaseBudget:bo,isPhaseRoutingEnabled:wN}=fs();function Ce(e){hN(e),mN()}function zl(e){if(!e||typeof e!="string")return!0;let t=e.trim();return!!(t.length<80||/^(done|complete|finished|all done|analysis complete|finally done)[.!]*$/i.test(t)||/^[^.!]{0,40}\?$/.test(t))}function Ip(e){if(!e||typeof e!="string")return!1;let t=e.slice(-1200);return/\b(done|complete|completed|fixed|implemented|ready|verified|verification complete|tests? pass(?:ed)?|build pass(?:ed)?|all checks pass(?:ed)?|all good)\b/i.test(t)}function jp(e){return!e||typeof e!="string"?!1:/\b(not verified|verification (?:was )?not run|tests? (?:were )?not run|build (?:was )?not run|unchecked|unverified)\b/i.test(e)}function _N(e){return!e||typeof e!="string"?!1:/^\s*(?:final\s+)?(?:summary|report|answer|result)\s*:/i.test(e)}function kN(e){if(!e||typeof e!="string")return!1;let t=e.trim();if(!t)return!1;let n=t.slice(-300);return n.includes("?")?/(?:would you like|do you want|should i|shall i|can you clarify|could you clarify|what would you like me to|which (?:one|option|area|approach)|how would you like me to)\b/i.test(n):!1}function xN(e){return!e||typeof e!="string"?!1:/\.(?:md|mdx|txt|rst|adoc)$/i.test(e)}function wt(e){try{if(!e.some(o=>o.role!=="assistant"?!1:!!(Array.isArray(o.content)&&o.content.some(s=>s&&s.type==="tool_use")||Array.isArray(o.tool_calls)&&o.tool_calls.length>0)))return;let n=gN(e);if(!n)return;console.log(yN(n,y));try{let{_getSessionsDir:o}=ds(),s=require("fs"),r=require("path").join(o(),"_autosave.json");if(s.existsSync(r)){let i=JSON.parse(s.readFileSync(r,"utf-8"));i.score=n.score,i.scoreGrade=n.grade,i.scoreIssues=n.issues,s.writeFileSync(r,JSON.stringify(i,null,2))}}catch{}try{let{getActiveModel:o}=Go(),s=Ar();$N(n.score,{version:s.version,model:o?o():null,sessionName:"_autosave",issues:n.issues})}catch{}}catch{}}var{getMemoryContext:vN}=as(),{getDeploymentContextBlock:SN,probeUrlServer:EN,detectRuntimeDebugTarget:h_}=ip(),{getFewShotForInput:TN}=M0(),{checkPermission:RN,setPermission:CN,savePermissions:AN}=ma(),{confirm:L_,setAllowAlwaysHandler:ON,getAutoConfirm:vn}=un(),{isPlanMode:mr,getPlanModePrompt:MN,PLAN_MODE_ALLOWED_TOOLS:I_,setPlanContent:PN,extractStepsFromText:NN,createPlan:LN,getActivePlan:dF,startExecution:fF,advancePlanStep:IN,getPlanStepInfo:jN}=ps(),{StreamRenderer:DN}=ud(),{runHooks:m_}=bp(),{routeMCPCall:qN,getMCPToolDefinitions:FN}=Vc(),{getSkillInstructions:BN,getSkillToolDefinitions:UN,routeSkillCall:WN,matchSkillTriggers:HN}=Ys(),{trackUsage:g_,estimateTokens:y_,getSessionCosts:$_,getProviderCostMode:b_}=os();function w_(e){return!e||typeof e!="string"?0:typeof y_=="function"?y_(e):Math.ceil(e.length/4)}var{validateToolArgs:GN}=zd(),{filterToolsForModel:__,getModelTier:YN,PROVIDER_DEFAULT_TIER:pF}=Fi(),{getConfiguredProviders:zN,getActiveProviderName:Qn,getActiveModelId:Dn,setActiveModel:Kl,MODEL_EQUIVALENTS:Ca}=ft(),{getModelProfile:KN,getModelBriefing:XN}=$l(),ot=require("fs"),ut=require("path"),VN=(()=>{let e=parseInt(process.env.NEX_MILESTONE_STEPS??"5",10);return Number.isFinite(e)&&e>=0?e:5})();function JN(e){let t=aN(e.phaseName,e.stepCount,e.toolCounts,e.elapsed,e.filesRead,e.filesModified);process.stdout.write(`${t}
1000
+ `)}function c_(e){return!e||typeof e!="string"?!1:!/no material findings/i.test(e)}function l_(e,t,n,o){if(e!=="implement"||!t||t.status==="failed")return!1;let s=Array.isArray(n?.scope)?n.scope.length:0,r=Array.isArray(t.filesModified)?t.filesModified.length:0,i=Array.isArray(o)?o.length:0;return s+r+i>0}function u_(e,t,n,o){return oN(t)?d_(e)?!0:o.some(r=>r>n)&&n===o[0]:!1}function oN(e){return e&&(e.status==="failed"||e.status==="error"||e.status==="skipped")}function d_(e){let t=typeof e=="string"?e:`${e?.task||""} ${(e?.scope||[]).join(" ")}`;return/\b(preflight|git status|current branch|worktree|dirty|unrelated changes?|clean working tree|pull\/rebase|rebase|before changing|before editing|stop without|abort|blocker|verification gate|release gate)\b/i.test(t)}function f_(e){if(!e)return"implement";let t=eN.test(e),n=tN.test(e);return nN.test(e)?"implement":n?"review":t?"explore":"implement"}p_.exports={runOrchestrated:QP,decompose:r_,synthesize:i_,shouldSuppressCommit:a_,detectComplexPrompt:JP,detectCriticalPathPrompt:o_,extractJSON:wp,createSemaphore:s_,DECOMPOSE_PROMPT:e_,SYNTHESIZE_PROMPT:t_,DEFAULT_ORCHESTRATOR_MODEL:Q0,DEFAULT_WORKER_MODEL:Z0,DEFAULT_MAX_PARALLEL:J0,DEFAULT_MAX_SUBTASKS:Gl,withRetry:n_,_classifyWorkerType:f_,_hasMaterialReviewFindings:c_,_shouldRunFollowUpReview:l_,_shouldAbortAfterWave:u_,_isBlockingTask:d_}});var We=Q((hF,ok)=>{var{C:$,Spinner:ri,TaskProgress:rN,formatToolCall:iN,formatToolSummary:Ia,formatSectionHeader:$a,formatMilestone:aN,setActiveTaskProgress:lF,getThinkingVerb:_p,setActiveModelForSpinner:kp}=dt(),{debugLog:j,warnLog:uF}=Wc(),{MilestoneTracker:cN}=Yg(),{callStream:Yl}=ft(),{parseToolArgs:lN}=Go(),{executeTool:eh}=rs(),{gatherProjectContext:uN}=jl(),{fitToContext:dN,forceCompress:As,getUsage:hs,estimateTokens:fN,buildProgressSnapshot:pN}=Mn(),{autoSave:hN,flushAutoSave:mN}=ds(),{scoreMessages:gN,formatScore:yN,appendScoreHistory:$N}=ql(),{detectCategory:bN,getModelForPhase:Lp,getPhaseBudget:bo,isPhaseRoutingEnabled:wN}=fs();function Ce(e){hN(e),mN()}function zl(e){if(!e||typeof e!="string")return!0;let t=e.trim();return!!(t.length<80||/^(done|complete|finished|all done|analysis complete|finally done)[.!]*$/i.test(t)||/^[^.!]{0,40}\?$/.test(t))}function Ip(e){if(!e||typeof e!="string")return!1;let t=e.slice(-1200);return/\b(done|complete|completed|fixed|implemented|ready|verified|verification complete|tests? pass(?:ed)?|build pass(?:ed)?|all checks pass(?:ed)?|all good)\b/i.test(t)}function jp(e){return!e||typeof e!="string"?!1:/\b(not verified|verification (?:was )?not run|tests? (?:were )?not run|build (?:was )?not run|unchecked|unverified)\b/i.test(e)}function _N(e){return!e||typeof e!="string"?!1:/^\s*(?:final\s+)?(?:summary|report|answer|result)\s*:/i.test(e)}function kN(e){if(!e||typeof e!="string")return!1;let t=e.trim();if(!t)return!1;let n=t.slice(-300);return n.includes("?")?/(?:would you like|do you want|should i|shall i|can you clarify|could you clarify|what would you like me to|which (?:one|option|area|approach)|how would you like me to)\b/i.test(n):!1}function xN(e){return!e||typeof e!="string"?!1:/\.(?:md|mdx|txt|rst|adoc)$/i.test(e)}function wt(e){try{if(!e.some(o=>o.role!=="assistant"?!1:!!(Array.isArray(o.content)&&o.content.some(s=>s&&s.type==="tool_use")||Array.isArray(o.tool_calls)&&o.tool_calls.length>0)))return;let n=gN(e);if(!n)return;console.log(yN(n,$));try{let{_getSessionsDir:o}=ds(),s=require("fs"),r=require("path").join(o(),"_autosave.json");if(s.existsSync(r)){let i=JSON.parse(s.readFileSync(r,"utf-8"));i.score=n.score,i.scoreGrade=n.grade,i.scoreIssues=n.issues,s.writeFileSync(r,JSON.stringify(i,null,2))}}catch{}try{let{getActiveModel:o}=Go(),s=Ar();$N(n.score,{version:s.version,model:o?o():null,sessionName:"_autosave",issues:n.issues})}catch{}}catch{}}var{getMemoryContext:vN}=as(),{getDeploymentContextBlock:SN,probeUrlServer:EN,detectRuntimeDebugTarget:h_}=ip(),{getFewShotForInput:TN}=M0(),{checkPermission:RN,setPermission:CN,savePermissions:AN}=ma(),{confirm:L_,setAllowAlwaysHandler:ON,getAutoConfirm:vn}=un(),{isPlanMode:mr,getPlanModePrompt:MN,PLAN_MODE_ALLOWED_TOOLS:I_,setPlanContent:PN,extractStepsFromText:NN,createPlan:LN,getActivePlan:dF,startExecution:fF,advancePlanStep:IN,getPlanStepInfo:jN}=ps(),{StreamRenderer:DN}=ud(),{runHooks:m_}=bp(),{routeMCPCall:qN,getMCPToolDefinitions:FN}=Vc(),{getSkillInstructions:BN,getSkillToolDefinitions:UN,routeSkillCall:WN,matchSkillTriggers:HN}=Ys(),{trackUsage:g_,estimateTokens:y_,getSessionCosts:$_,getProviderCostMode:b_}=os();function w_(e){return!e||typeof e!="string"?0:typeof y_=="function"?y_(e):Math.ceil(e.length/4)}var{validateToolArgs:GN}=zd(),{filterToolsForModel:__,getModelTier:YN,PROVIDER_DEFAULT_TIER:pF}=Fi(),{getConfiguredProviders:zN,getActiveProviderName:Qn,getActiveModelId:Dn,setActiveModel:Kl,MODEL_EQUIVALENTS:Ca}=ft(),{getModelProfile:KN,getModelBriefing:XN}=$l(),ot=require("fs"),ut=require("path"),VN=(()=>{let e=parseInt(process.env.NEX_MILESTONE_STEPS??"5",10);return Number.isFinite(e)&&e>=0?e:5})();function JN(e){let t=aN(e.phaseName,e.stepCount,e.toolCounts,e.elapsed,e.filesRead,e.filesModified);process.stdout.write(`${t}
1001
1001
  `),global._nexFooter&&global._nexFooter.setFileInfo({modified:e.filesModified?.size||0,scanned:e.filesRead?.size||0})}var k_=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi,x_=/(?:^|\s)(https?:\/\/[^\s]+\.(?:png|jpe?g|gif|webp)(?:\?[^\s]*)?)(?:\s|$)/gi,ZN=/\b(?:clipboard|pasteboard|clipboard screenshot)\b/i;function QN(e){let t=[],n;for(k_.lastIndex=0;(n=k_.exec(e))!==null;){let o=n[1].trim(),s=o.startsWith("~")?o.replace("~",process.env.HOME||""):ut.resolve(o);ot.existsSync(s)&&t.push({raw:o,abs:s})}return t}function j_(e){let t=[],n;for(x_.lastIndex=0;(n=x_.exec(e))!==null;)t.push(n[1].trim());return t}async function D_(e){try{let n=await require("axios").get(e,{responseType:"arraybuffer",timeout:1e4,maxContentLength:10*1024*1024,headers:{"User-Agent":"nex-code/vision"}}),o=n.headers["content-type"]||"",s=o.startsWith("image/")?o.split(";")[0]:eL(e);return{data:Buffer.from(n.data).toString("base64"),media_type:s}}catch{return null}}function eL(e){let t=e.toLowerCase();return t.includes(".jpg")||t.includes(".jpeg")?"image/jpeg":t.includes(".gif")?"image/gif":t.includes(".webp")?"image/webp":"image/png"}function q_(){if(process.platform!=="darwin")return null;let{spawnSync:e}=require("child_process"),t=ut.join(require("os").tmpdir(),`nex-clipboard-${Date.now()}.png`);if(e("pngpaste",[t],{timeout:3e3}).status===0&&ot.existsSync(t)){let s=ot.readFileSync(t);if(s.length>100)return{data:s.toString("base64"),media_type:"image/png",path:t};try{ot.unlinkSync(t)}catch(r){console.error("Failed to unlink temp file:",r)}}let o=e("osascript",["-e",`try
1002
1002
  set imgData to the clipboard as \xABclass PNGf\xBB
1003
1003
  return "has_image"
@@ -1009,53 +1009,53 @@ end try`],{timeout:3e3});if(o.stdout&&o.stdout.toString().trim()==="has_image"){
1009
1009
  set fRef to open for access filePath with write permission
1010
1010
  write imgData to fRef
1011
1011
  close access fRef
1012
- `;if(e("osascript",["-e",s],{timeout:5e3}).status===0&&ot.existsSync(t)){let i=ot.readFileSync(t);if(i.length>100)return{data:i.toString("base64"),media_type:"image/png",path:t}}}return null}function v_(e){let t=ot.readFileSync(e),n=ut.extname(e).toLowerCase().replace(".",""),o=n==="jpg"||n==="jpeg"?"image/jpeg":n==="png"?"image/png":n==="gif"?"image/gif":n==="webp"?"image/webp":"image/png";return{data:t.toString("base64"),media_type:o}}function F_(e){let t=QN(e),n=j_(e),o=ZN.test(e),s=n.length>0||o;if(t.length===0&&!s)return e;if(!s){let r=[{type:"text",text:e}];for(let i of t)try{let{data:a,media_type:c}=v_(i.abs);r.push({type:"image",media_type:c,data:a})}catch{}return r.length>1?r:e}return(async()=>{let r=[{type:"text",text:e}];for(let i of t)try{let{data:a,media_type:c}=v_(i.abs);r.push({type:"image",media_type:c,data:a})}catch(a){j(`${y.yellow} \u26A0 Path resolution failed: ${a.message}${y.reset}`)}if(n.length>0){let i=await Promise.all(n.map(D_));for(let a of i)a&&r.push({type:"image",media_type:a.media_type,data:a.data})}if(o){let i=q_();i?(r.push({type:"image",media_type:i.media_type,data:i.data}),r[0].text+=`
1012
+ `;if(e("osascript",["-e",s],{timeout:5e3}).status===0&&ot.existsSync(t)){let i=ot.readFileSync(t);if(i.length>100)return{data:i.toString("base64"),media_type:"image/png",path:t}}}return null}function v_(e){let t=ot.readFileSync(e),n=ut.extname(e).toLowerCase().replace(".",""),o=n==="jpg"||n==="jpeg"?"image/jpeg":n==="png"?"image/png":n==="gif"?"image/gif":n==="webp"?"image/webp":"image/png";return{data:t.toString("base64"),media_type:o}}function F_(e){let t=QN(e),n=j_(e),o=ZN.test(e),s=n.length>0||o;if(t.length===0&&!s)return e;if(!s){let r=[{type:"text",text:e}];for(let i of t)try{let{data:a,media_type:c}=v_(i.abs);r.push({type:"image",media_type:c,data:a})}catch{}return r.length>1?r:e}return(async()=>{let r=[{type:"text",text:e}];for(let i of t)try{let{data:a,media_type:c}=v_(i.abs);r.push({type:"image",media_type:c,data:a})}catch(a){j(`${$.yellow} \u26A0 Path resolution failed: ${a.message}${$.reset}`)}if(n.length>0){let i=await Promise.all(n.map(D_));for(let a of i)a&&r.push({type:"image",media_type:a.media_type,data:a.data})}if(o){let i=q_();i?(r.push({type:"image",media_type:i.media_type,data:i.data}),r[0].text+=`
1013
1013
  [Clipboard image attached: ${i.path}]`):r[0].text+=`
1014
1014
  [No image found in clipboard]`}return r.length>1?r:e})()}var tL=[/\bwtf\b/i,/\buff\b/i,/\bugh\b/i,/\bffs\b/i,/\bargh\b/i,/why (?:isn'?t|doesn'?t|won'?t|can'?t|don'?t)/i,/(?:still|again) (?:broken|not working|failing|wrong)/i,/already told you/i,/come on[!.]/i,/seriously\?/i,/how (?:many|much) (?:times|more)/i,/nothing (?:works?|is working)/i];function B_(e){return typeof e!="string"||!e?!1:tL.some(t=>t.test(e))}function nL(e){if(!e||e.length<200)return{text:e,truncated:!1,repeatCount:0};let n=e.split(/(?<=\. )/).filter(c=>c.trim().length>0);if(n.length<6)return{text:e,truncated:!1,repeatCount:0};let o=new Map;for(let c=0;c<=n.length-3;c++){let u=n.slice(c,c+3).join("").trim();u.length>30&&o.set(u,(o.get(u)||0)+1)}let s=0,r="";for(let[c,u]of o)u>s&&(s=u,r=c);if(s<3)return{text:e,truncated:!1,repeatCount:s};let i=`
1015
1015
 
1016
1016
  [SYSTEM: Output repetition detected \u2014 response truncated (${s}\xD7 repeated paragraph)]`,a;if(e.length>8e3)a=e.slice(0,3e3)+i;else{let c=0,u=-1,d=0;for(;c<2;){let f=e.indexOf(r,d);if(f===-1)break;c++,u=f+r.length,d=f+1}a=u>0?e.slice(0,u)+i:e.slice(0,3e3)+i}return{text:a,truncated:!0,repeatCount:s}}function Dp(e,t=5){if(!e||e.length<40)return{text:e,truncated:!1,repeatCount:0};let n=e.split(`
1017
1017
  `),o=new Map;for(let h of n){let m=h.trim();m.length>=20&&o.set(m,(o.get(m)||0)+1)}let s=0,r="";for(let[h,m]of o)m>s&&(s=m,r=h);let a=r.toLowerCase().includes("read_file")||r.toLowerCase().includes("reading")?2:t;if(s<=a)return{text:e,truncated:!1,repeatCount:s};let c=`
1018
1018
 
1019
- \u26A0 [Response truncated: repeated paragraph detected (${s}\xD7)]`,u=0,d=-1,f=0;for(;u<t;){let h=e.indexOf(r,f);if(h===-1)break;u++,d=h+r.length,f=h+1}return{text:d>0?e.slice(0,d)+c:e.slice(0,2e3)+c,truncated:!0,repeatCount:s}}var xp=null,vp=null,Sp=null;function xn(){if(xp===null){let{TOOL_DEFINITIONS:e}=rs();xp=e}return vp===null&&(vp=UN()),Sp===null&&(Sp=FN()),[...xp,...vp,...Sp]}var Ql=50;function sL(e){Number.isFinite(e)&&e>0&&(Ql=e)}function Ep(e=Qn()){if(process.env.NEX_DISABLE_TOOL_BUDGET==="1")return 1/0;let t=process.env.NEX_MAX_TOOL_CALLS;if(t){let n=parseInt(t,10);if(Number.isFinite(n)&&n>0)return n}return e==="local"?5:30}function S_(e,t){return`[SYSTEM STOP] Tool-call budget reached (${e}/${t}). You MUST stop calling tools now. Provide your final answer based only on the information already in the conversation. If the task cannot be completed from the gathered evidence, state the blocker plainly and do not invent facts.`}var eu=()=>null;function oL(e){eu=e}var _a=null,qp=null,ii=null,ai="",ci=0,Fp="",Bp=0,tu=new Map,rL=1e4,iL=6e3,aL=/\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 cL(e){return!e||typeof e!="string"?e:e.replace(aL,(t,n)=>`${n}=***REDACTED***`)}var lL=7e3,uL=4e3;function dL(e,t=null){let n=cL(e),o=fN(n),s=t==="read_file"?lL:rL,r=t==="read_file"?uL:iL;if(o>s)try{let{compressToolResult:i}=Mn();return i(n,r)}catch{return n}return n}function U_(e){try{let{getActiveModel:t}=ft(),n=t(),o=n?`${n.provider}:${n.id}`:"default";if(tu.has(o))return tu.get(o);let s=__(e);return tu.set(o,s),s}catch{return __(e)}}function fL(){tu.clear()}function pL(e,t){let n=new Set(t);return(e||[]).some(o=>o.role!=="assistant"?!1:Array.isArray(o.tool_calls)?o.tool_calls.some(s=>n.has(s?.function?.name||s?.name)):Array.isArray(o.content)?o.content.some(s=>s?.type==="tool_use"&&n.has(s?.name)):!1)}var ka={hash:null,ts:0},hL=3e4;async function W_(){if(ka.hash&&Date.now()-ka.ts<hL)return ka.hash;try{let e=require("fs").promises,t=require("path"),n=[t.join(process.cwd(),"package.json"),t.join(process.cwd(),".git","HEAD"),t.join(process.cwd(),"README.md"),t.join(process.cwd(),"NEX.md")],s=(await Promise.allSettled(n.map(i=>e.stat(i).then(a=>`${i}:${a.mtimeMs}`)))).filter(i=>i.status==="fulfilled").map(i=>i.value);try{let{getMemoryContextHash:i}=as(),a=i();a&&s.push(`memory:${a}`)}catch{}try{let i=t.join(process.cwd(),".nex","brain");if(ot.existsSync(i)){let a=await e.stat(i);s.push(`brain:${a.mtimeMs}`)}}catch{}let r=s.join("|");return ka={hash:r,ts:Date.now()},r}catch{return`fallback:${Date.now()}`}}function nu(){_a=null,qp=null,ka={hash:null,ts:0},ii=null}var mL=new Set(["spawn_agents"]),Tp=10,Rp=10,Cp=5,E_=6e4,Ap=12e4,T_=process.env.NEX_STALE_AUTO_SWITCH!=="0";function gL(e){try{let t=require("fs"),n=require("path"),o=n.join(process.cwd(),".nex","plans");t.existsSync(o)||t.mkdirSync(o,{recursive:!0});let s=n.join(o,"current-plan.md");t.writeFileSync(s,e,"utf-8")}catch{}}ON(e=>{CN(e,"allow"),AN(),console.log(`${y.green} \u2713 ${e}: always allow${y.reset}`)});async function yL(e){let t=e.function.name,n=t;if(typeof t=="string"&&t.includes(".")){let p=t.split(".").pop(),h={exec:"bash",find:"search_files",search:"search_files",grep_search:"grep",list:"list_directory",print_tree:"list_directory",read:"read_file",tree:"list_directory"};xn().some(g=>g.function.name===p)?n=p:h[p]&&(n=h[p])}let o=lN(e.function.arguments),s=e.id||`cli-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!o){let h=xn().find(g=>g.function.name===n),m=h?JSON.stringify(h.function.parameters,null,2):"unknown";return j(`${y.yellow} \u26A0 ${n}: malformed arguments, sending schema hint${y.reset}`),{callId:s,fnName:n,args:null,canExecute:!1,errorResult:{role:"tool",content:`ERROR: Malformed tool arguments. Could not parse your arguments as JSON.
1019
+ \u26A0 [Response truncated: repeated paragraph detected (${s}\xD7)]`,u=0,d=-1,f=0;for(;u<t;){let h=e.indexOf(r,f);if(h===-1)break;u++,d=h+r.length,f=h+1}return{text:d>0?e.slice(0,d)+c:e.slice(0,2e3)+c,truncated:!0,repeatCount:s}}var xp=null,vp=null,Sp=null;function xn(){if(xp===null){let{TOOL_DEFINITIONS:e}=rs();xp=e}return vp===null&&(vp=UN()),Sp===null&&(Sp=FN()),[...xp,...vp,...Sp]}var Ql=50;function sL(e){Number.isFinite(e)&&e>0&&(Ql=e)}function Ep(e=Qn()){if(process.env.NEX_DISABLE_TOOL_BUDGET==="1")return 1/0;let t=process.env.NEX_MAX_TOOL_CALLS;if(t){let n=parseInt(t,10);if(Number.isFinite(n)&&n>0)return n}return e==="local"?5:30}function S_(e,t){return`[SYSTEM STOP] Tool-call budget reached (${e}/${t}). You MUST stop calling tools now. Provide your final answer based only on the information already in the conversation. If the task cannot be completed from the gathered evidence, state the blocker plainly and do not invent facts.`}var eu=()=>null;function oL(e){eu=e}var _a=null,qp=null,ii=null,ai="",ci=0,Fp="",Bp=0,tu=new Map,rL=1e4,iL=6e3,aL=/\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 cL(e){return!e||typeof e!="string"?e:e.replace(aL,(t,n)=>`${n}=***REDACTED***`)}var lL=7e3,uL=4e3;function dL(e,t=null){let n=cL(e),o=fN(n),s=t==="read_file"?lL:rL,r=t==="read_file"?uL:iL;if(o>s)try{let{compressToolResult:i}=Mn();return i(n,r)}catch{return n}return n}function U_(e){try{let{getActiveModel:t}=ft(),n=t(),o=n?`${n.provider}:${n.id}`:"default";if(tu.has(o))return tu.get(o);let s=__(e);return tu.set(o,s),s}catch{return __(e)}}function fL(){tu.clear()}function pL(e,t){let n=new Set(t);return(e||[]).some(o=>o.role!=="assistant"?!1:Array.isArray(o.tool_calls)?o.tool_calls.some(s=>n.has(s?.function?.name||s?.name)):Array.isArray(o.content)?o.content.some(s=>s?.type==="tool_use"&&n.has(s?.name)):!1)}var ka={hash:null,ts:0},hL=3e4;async function W_(){if(ka.hash&&Date.now()-ka.ts<hL)return ka.hash;try{let e=require("fs").promises,t=require("path"),n=[t.join(process.cwd(),"package.json"),t.join(process.cwd(),".git","HEAD"),t.join(process.cwd(),"README.md"),t.join(process.cwd(),"NEX.md")],s=(await Promise.allSettled(n.map(i=>e.stat(i).then(a=>`${i}:${a.mtimeMs}`)))).filter(i=>i.status==="fulfilled").map(i=>i.value);try{let{getMemoryContextHash:i}=as(),a=i();a&&s.push(`memory:${a}`)}catch{}try{let i=t.join(process.cwd(),".nex","brain");if(ot.existsSync(i)){let a=await e.stat(i);s.push(`brain:${a.mtimeMs}`)}}catch{}let r=s.join("|");return ka={hash:r,ts:Date.now()},r}catch{return`fallback:${Date.now()}`}}function nu(){_a=null,qp=null,ka={hash:null,ts:0},ii=null}var mL=new Set(["spawn_agents"]),Tp=10,Rp=10,Cp=5,E_=6e4,Ap=12e4,T_=process.env.NEX_STALE_AUTO_SWITCH!=="0";function gL(e){try{let t=require("fs"),n=require("path"),o=n.join(process.cwd(),".nex","plans");t.existsSync(o)||t.mkdirSync(o,{recursive:!0});let s=n.join(o,"current-plan.md");t.writeFileSync(s,e,"utf-8")}catch{}}ON(e=>{CN(e,"allow"),AN(),console.log(`${$.green} \u2713 ${e}: always allow${$.reset}`)});async function yL(e){let t=e.function.name,n=t;if(typeof t=="string"&&t.includes(".")){let p=t.split(".").pop(),h={exec:"bash",find:"search_files",search:"search_files",grep_search:"grep",list:"list_directory",print_tree:"list_directory",read:"read_file",tree:"list_directory"};xn().some(g=>g.function.name===p)?n=p:h[p]&&(n=h[p])}let o=lN(e.function.arguments),s=e.id||`cli-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!o){let h=xn().find(g=>g.function.name===n),m=h?JSON.stringify(h.function.parameters,null,2):"unknown";return j(`${$.yellow} \u26A0 ${n}: malformed arguments, sending schema hint${$.reset}`),{callId:s,fnName:n,args:null,canExecute:!1,errorResult:{role:"tool",content:`ERROR: Malformed tool arguments. Could not parse your arguments as JSON.
1020
1020
  Raw input: ${typeof e.function.arguments=="string"?e.function.arguments.substring(0,200):"N/A"}
1021
1021
 
1022
1022
  Expected JSON schema for "${n}":
1023
1023
  ${m}
1024
1024
 
1025
- Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:s}}}if(o&&typeof o.path=="string")try{let p=require("os"),h=ut.resolve(process.cwd(),o.path.replace(/^~/,p.homedir())),m=o.path;o.path=ut.relative(process.cwd(),h)||".",Object.defineProperty(o,"_originalPath",{value:m,enumerable:!1})}catch(p){console.error("path resolution failed:",p.message)}o&&(n==="search_files"||n==="grep")&&typeof o.pattern!="string"&&(typeof o.query=="string"?o.pattern=o.query:typeof o.search=="string"&&(o.pattern=o.search));let r=GN(n,o);if(!r.valid){j(`${y.yellow} \u26A0 ${n}: ${r.error.split(`
1026
- `)[0]}${y.reset}`);let p=(C_.get(n)||0)+1;C_.set(n,p);let h=p>=2?`${r.error}
1025
+ Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:s}}}if(o&&typeof o.path=="string")try{let p=require("os"),h=ut.resolve(process.cwd(),o.path.replace(/^~/,p.homedir())),m=o.path;o.path=ut.relative(process.cwd(),h)||".",Object.defineProperty(o,"_originalPath",{value:m,enumerable:!1})}catch(p){console.error("path resolution failed:",p.message)}o&&(n==="search_files"||n==="grep")&&typeof o.pattern!="string"&&(typeof o.query=="string"?o.pattern=o.query:typeof o.search=="string"&&(o.pattern=o.search));let r=GN(n,o);if(!r.valid){j(`${$.yellow} \u26A0 ${n}: ${r.error.split(`
1026
+ `)[0]}${$.reset}`);let p=(C_.get(n)||0)+1;C_.set(n,p);let h=p>=2?`${r.error}
1027
1027
 
1028
- [SYSTEM: This is argument error #${p} for "${n}". Study the "Expected parameters" schema above and correct your call \u2014 do not repeat the same mistake.]`:r.error;return{callId:s,fnName:n,args:o,canExecute:!1,errorResult:{role:"tool",content:h,tool_call_id:s}}}let i=r.corrected||o;if(r.corrected){let p=Object.keys(o),h=Object.keys(r.corrected),m=p.filter(g=>!h.includes(g));m.length&&console.log(`${y.dim} \u2713 ${n}: corrected args (${m.join(", ")})${y.reset}`)}if(mr()&&!I_.has(n))return console.log(`${y.yellow} \u2717 ${n}: blocked in plan mode${y.reset}`),{callId:s,fnName:n,args:i,canExecute:!1,errorResult:{role:"tool",content:`PLAN MODE: '${n}' is blocked. Only read-only tools are allowed. Present your plan as text output instead of making changes.`,tool_call_id:s}};let a=new Set(["read_file","list_directory","search_files","glob","grep","git_status","git_diff","git_log","git_show","ssh_exec"]),c=new Set(["read_file","list_directory","glob","grep","bash","git_status","git_diff","git_log","ssh_exec"]),u=n==="spawn_agents"&&Array.isArray(i?.agents)&&i.agents.length>0&&i.agents.every(p=>p.background===!0);if(be&&Pe==="plan"&&!a.has(n)&&!n.startsWith("skill_")&&!u)return So++,fi=n,j(`${y.yellow} \u2717 ${n}: blocked in plan phase (read-only, block #${So})${y.reset}`),{callId:s,fnName:n,args:i,canExecute:!1,errorResult:{role:"tool",content:`PLAN PHASE: '${n}' is blocked. Analyze the codebase using read-only tools, then present your findings as text. Edits happen in the next phase.`,tool_call_id:s}};if(be&&Pe==="verify"&&!c.has(n)&&!n.startsWith("skill_"))return j(`${y.yellow} \u2717 ${n}: blocked in verify phase (read + bash only)${y.reset}`),{callId:s,fnName:n,args:i,canExecute:!1,errorResult:{role:"tool",content:`VERIFY PHASE: '${n}' is blocked. Use read_file and bash (for tests/linters) to verify changes. Report PASS or FAIL.`,tool_call_id:s}};if(new Set(["write_file","edit_file","patch_file"]).has(n)&&process.env.NEX_SCOPE){let p=i.path||i.file_path||"";if(p){let h=process.env.NEX_SCOPE.split(",").map($=>$.trim()),m=p.replace(/\\/g,"/");if(!h.some($=>new RegExp("^"+$.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"___DOUBLESTAR___").replace(/\*/g,"[^/]*").replace(/___DOUBLESTAR___/g,".*")+"$").test(m)||m.endsWith($)||m===$))return j(`${y.yellow} \u2717 ${n}: ${p} outside scope (--scope ${process.env.NEX_SCOPE})${y.reset}`),{callId:s,fnName:n,args:i,canExecute:!1,errorResult:{role:"tool",content:`SCOPE BLOCKED: '${p}' is outside the allowed scope. Only these files may be edited: ${process.env.NEX_SCOPE}. Use read_file to inspect other files, but do not edit them.`,tool_call_id:s}}}}let f=RN(n);if(f==="deny")return console.log(`${y.red} \u2717 ${n}: denied by permissions${y.reset}`),{callId:s,fnName:n,args:i,canExecute:!1,errorResult:{role:"tool",content:`DENIED: Tool '${n}' is blocked by permissions`,tool_call_id:s}};if(f==="ask"){let p=` Allow ${n}?`;return n==="bash"&&i.command&&(p=` bash: \`${i.command.substring(0,80)}${i.command.length>80?"\u2026":""}\`?`),await L_(p,{toolName:n})?{callId:s,fnName:n,args:i,canExecute:!0,confirmedByUser:!0,errorResult:null}:{callId:s,fnName:n,args:i,canExecute:!1,confirmedByUser:!1,errorResult:{role:"tool",content:`CANCELLED: User declined ${n}`,tool_call_id:s}}}return{callId:s,fnName:n,args:i,canExecute:!0,confirmedByUser:!0,errorResult:null}}async function $L(e,t,n={}){let o=await WN(e,t);if(o!==null)return o;let s=await qN(e,t);return s!==null?s:eh(e,t,n)}function bL(e,t){switch(e){case"read_file":case"write_file":case"edit_file":case"patch_file":case"list_directory":return t._originalPath||t.path||"";case"bash":return(t.command||"").substring(0,60);case"grep":case"search_files":case"glob":return t.pattern||"";case"web_fetch":return(t.url||"").substring(0,50);case"web_search":return(t.query||"").substring(0,40);default:return""}}async function Op(e,t=!1){t||console.log(iN(e.fnName,e.args));let n=m_("pre-tool",{tool_name:e.fnName}),o=n.results;if(n.blocked){let $=`BLOCKED: pre-tool hook rejected ${e.fnName}: ${n.blockReason}`;t||console.log(`${y.yellow} [hook pre-tool] BLOCKED: ${n.blockReason}${y.reset}`);let b=Ia(e.fnName,e.args,$,!0);return t||console.log(b),{msg:{role:"tool",content:$,tool_call_id:e.callId},summary:b}}if(!t&&o.length>0)for(let $ of o)$.success?console.log(`${y.dim} [hook pre-tool] ${$.command} \u2192 ${$.output||"ok"}${y.reset}`):console.log(`${y.yellow} [hook pre-tool] ${$.command} \u2192 ERROR: ${$.error}${y.reset}`);Ot?.onToolStart&&Ot.onToolStart(e.fnName,e.args);let s=await $L(e.fnName,e.args,{silent:!0,autoConfirm:e.confirmedByUser===!0}),r=null,i;s&&typeof s=="object"&&s.text?(i=String(s.text),Array.isArray(s.images)&&s.images.length>0&&(r=s.images)):i=String(s??"");let a=i.length>5e4?i.substring(0,5e4)+`
1028
+ [SYSTEM: This is argument error #${p} for "${n}". Study the "Expected parameters" schema above and correct your call \u2014 do not repeat the same mistake.]`:r.error;return{callId:s,fnName:n,args:o,canExecute:!1,errorResult:{role:"tool",content:h,tool_call_id:s}}}let i=r.corrected||o;if(r.corrected){let p=Object.keys(o),h=Object.keys(r.corrected),m=p.filter(g=>!h.includes(g));m.length&&console.log(`${$.dim} \u2713 ${n}: corrected args (${m.join(", ")})${$.reset}`)}if(mr()&&!I_.has(n))return console.log(`${$.yellow} \u2717 ${n}: blocked in plan mode${$.reset}`),{callId:s,fnName:n,args:i,canExecute:!1,errorResult:{role:"tool",content:`PLAN MODE: '${n}' is blocked. Only read-only tools are allowed. Present your plan as text output instead of making changes.`,tool_call_id:s}};let a=new Set(["read_file","list_directory","search_files","glob","grep","git_status","git_diff","git_log","git_show","ssh_exec"]),c=new Set(["read_file","list_directory","glob","grep","bash","git_status","git_diff","git_log","ssh_exec"]),u=n==="spawn_agents"&&Array.isArray(i?.agents)&&i.agents.length>0&&i.agents.every(p=>p.background===!0);if(be&&Pe==="plan"&&!a.has(n)&&!n.startsWith("skill_")&&!u)return So++,fi=n,j(`${$.yellow} \u2717 ${n}: blocked in plan phase (read-only, block #${So})${$.reset}`),{callId:s,fnName:n,args:i,canExecute:!1,errorResult:{role:"tool",content:`PLAN PHASE: '${n}' is blocked. Analyze the codebase using read-only tools, then present your findings as text. Edits happen in the next phase.`,tool_call_id:s}};if(be&&Pe==="verify"&&!c.has(n)&&!n.startsWith("skill_"))return j(`${$.yellow} \u2717 ${n}: blocked in verify phase (read + bash only)${$.reset}`),{callId:s,fnName:n,args:i,canExecute:!1,errorResult:{role:"tool",content:`VERIFY PHASE: '${n}' is blocked. Use read_file and bash (for tests/linters) to verify changes. Report PASS or FAIL.`,tool_call_id:s}};if(new Set(["write_file","edit_file","patch_file"]).has(n)&&process.env.NEX_SCOPE){let p=i.path||i.file_path||"";if(p){let h=process.env.NEX_SCOPE.split(",").map(y=>y.trim()),m=p.replace(/\\/g,"/");if(!h.some(y=>new RegExp("^"+y.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"___DOUBLESTAR___").replace(/\*/g,"[^/]*").replace(/___DOUBLESTAR___/g,".*")+"$").test(m)||m.endsWith(y)||m===y))return j(`${$.yellow} \u2717 ${n}: ${p} outside scope (--scope ${process.env.NEX_SCOPE})${$.reset}`),{callId:s,fnName:n,args:i,canExecute:!1,errorResult:{role:"tool",content:`SCOPE BLOCKED: '${p}' is outside the allowed scope. Only these files may be edited: ${process.env.NEX_SCOPE}. Use read_file to inspect other files, but do not edit them.`,tool_call_id:s}}}}let f=RN(n);if(f==="deny")return console.log(`${$.red} \u2717 ${n}: denied by permissions${$.reset}`),{callId:s,fnName:n,args:i,canExecute:!1,errorResult:{role:"tool",content:`DENIED: Tool '${n}' is blocked by permissions`,tool_call_id:s}};if(f==="ask"){let p=` Allow ${n}?`;return n==="bash"&&i.command&&(p=` bash: \`${i.command.substring(0,80)}${i.command.length>80?"\u2026":""}\`?`),await L_(p,{toolName:n})?{callId:s,fnName:n,args:i,canExecute:!0,confirmedByUser:!0,errorResult:null}:{callId:s,fnName:n,args:i,canExecute:!1,confirmedByUser:!1,errorResult:{role:"tool",content:`CANCELLED: User declined ${n}`,tool_call_id:s}}}return{callId:s,fnName:n,args:i,canExecute:!0,confirmedByUser:!0,errorResult:null}}async function $L(e,t,n={}){let o=await WN(e,t);if(o!==null)return o;let s=await qN(e,t);return s!==null?s:eh(e,t,n)}function bL(e,t){switch(e){case"read_file":case"write_file":case"edit_file":case"patch_file":case"list_directory":return t._originalPath||t.path||"";case"bash":return(t.command||"").substring(0,60);case"grep":case"search_files":case"glob":return t.pattern||"";case"web_fetch":return(t.url||"").substring(0,50);case"web_search":return(t.query||"").substring(0,40);default:return""}}async function Op(e,t=!1){t||console.log(iN(e.fnName,e.args));let n=m_("pre-tool",{tool_name:e.fnName}),o=n.results;if(n.blocked){let y=`BLOCKED: pre-tool hook rejected ${e.fnName}: ${n.blockReason}`;t||console.log(`${$.yellow} [hook pre-tool] BLOCKED: ${n.blockReason}${$.reset}`);let b=Ia(e.fnName,e.args,y,!0);return t||console.log(b),{msg:{role:"tool",content:y,tool_call_id:e.callId},summary:b}}if(!t&&o.length>0)for(let y of o)y.success?console.log(`${$.dim} [hook pre-tool] ${y.command} \u2192 ${y.output||"ok"}${$.reset}`):console.log(`${$.yellow} [hook pre-tool] ${y.command} \u2192 ERROR: ${y.error}${$.reset}`);Ot?.onToolStart&&Ot.onToolStart(e.fnName,e.args);let s=await $L(e.fnName,e.args,{silent:!0,autoConfirm:e.confirmedByUser===!0}),r=null,i;s&&typeof s=="object"&&s.text?(i=String(s.text),Array.isArray(s.images)&&s.images.length>0&&(r=s.images)):i=String(s??"");let a=i.length>5e4?i.substring(0,5e4)+`
1029
1029
  ...(truncated ${i.length-5e4} chars)`:i,c=a.split(`
1030
- `)[0],u=c.startsWith("ERROR")||c.includes("CANCELLED")||c.includes("BLOCKED")||e.fnName==="spawn_agents"&&!/✓ Agent/.test(a)&&/✗ Agent/.test(a),d=Ia(e.fnName,e.args,a,u);t||console.log(d),Ot?.onToolEnd&&Ot.onToolEnd(e.fnName,d,!u);let p=m_("post-tool",{tool_name:e.fnName}).results;if(!t&&p.length>0)for(let $ of p)$.success?console.log(`${y.dim} [hook post-tool] ${$.command} \u2192 ${$.output||"ok"}${y.reset}`):console.log(`${y.yellow} [hook post-tool] ${$.command} \u2192 ERROR: ${$.error}${y.reset}`);let m=dL(a,e.fnName);if(e.fnName==="bash"&&e.args?.command){let $=e.args.command.trim();!/cat\s*>|<</.test($)&&/\bcat\s+\S/.test($)?m+=`
1031
- HINT: use read_file instead of bash cat \u2014 it is faster, context-efficient, and the preferred tool for reading files.`:/^\s*ls(\s|$)/.test($)&&!/npm|yarn|pnpm|make|git\b/.test($)?m+=`
1032
- HINT: use list_directory instead of bash ls \u2014 it is the preferred tool for listing directory contents.`:/\bfind\s+\S/.test($)&&!/git\b|npm\b|-exec\b|-delete\b|-print0\b/.test($)&&(m+=`
1033
- HINT: use glob instead of bash find for file discovery \u2014 it is faster and the preferred tool (e.g. glob('**/*.jsx')).`)}return{msg:{role:"tool",content:r?[{type:"text",text:m},...r.map($=>({type:"image",media_type:$.media_type,data:$.base64}))]:m,tool_call_id:e.callId},summary:d}}var wL=[{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 Mp(e){for(let{re:t,label:n}of wL){let o=e.match(t);if(o){let s=(o[1]||"").trim();return s?`${n}: ${s}`:n}}return null}async function _L(e,t=!1,n={}){let o=new Array(e.length),s=[],r=[],i=null;if(t&&!n.skipSpinner){let c=e.filter(u=>u.canExecute);if(c.length>0){let u;if(c.length===1){let d=c[0],f=bL(d.fnName,d.args);u=`\u23FA ${d.fnName}${f?`(${f})`:""}`}else{let d=c.map(f=>f.fnName).join(", ");u=`\u23FA ${c.length} tools: ${d.length>60?d.substring(0,57)+"\u2026":d}`}i=new ri(u),i.start()}}async function a(){if(r.length!==0){if(r.length===1){let c=r[0],{msg:u,summary:d}=await Op(e[c],t);o[c]=u,s.push(d)}else{let c=r.map(d=>Op(e[d],t)),u=await Promise.all(c);for(let d=0;d<r.length;d++)o[r[d]]=u[d].msg,s.push(u[d].summary)}r=[]}}for(let c=0;c<e.length;c++){let u=e[c];if(!u.canExecute){await a(),o[c]=u.errorResult,s.push(Ia(u.fnName,u.args||{},u.errorResult.content,!0));continue}if(mL.has(u.fnName)){await a(),u.fnName==="spawn_agents"&&i&&(i.stop(),i=null);let{msg:d,summary:f}=await Op(u,t);o[c]=d,s.push(f)}else r.push(c)}if(await a(),i&&i.stop(),t&&s.length>0&&!n.skipSummaries)for(let c of s)console.log(c);return{results:o,summaries:s}}var T=[],R_=300,H_=900*1e3;function Os(e,t){let n=e.get(t);return n?Date.now()-n.ts>H_?(e.delete(t),0):n.count:0}function ur(e,t){let n=e.get(t),o=n&&Date.now()-n.ts<=H_?n.count+1:1;return e.set(t,{count:o,ts:Date.now()}),o}function Pp(e,t,n){e.set(t,{count:n,ts:Date.now()})}var th=new Map,G_=new Map,su=new Map,Aa=new Set,Y_=new Map,ou=new Map,Oa=new Set,Ls=new Map,to=new Map,Ma=new Map,Gt=new Map,gr=new Map,C_=new Map,mu=new Map,Up=new Map,Zn=0,xa=0,ru=0,Wp="",iu=0,Ln=!1,Xl=0,au=0,ko=-1,Hp=!1,cu=0,lu=!1,es=0,jn=!1,ts=0,ns=0,Zt=!1,kn="",va=0,wo=0,uu="",fr=0,pr=0,du="",ba=0,ms=!1,Gp=!1,ja=new Map,Da=new Set,Sa=null,ni=!1,wa=0,A_=!1,Ve=null,In=!1,nh=null,Yp=!1,zp=!1,fu=!1,xo="",hr="",Ea="",Pe="plan",gu=0,be=!1,So=0,fi=null,gs=null,qa=null,Kp=null,li=0,pi=0,hi=0,vo=0,Ta=0,ui=0,Vl=0,Is=!1,js=0,yr=null,no=[],_o=new Set,et=!1,Sn=0,Fa=0,gn=new Set,$r=new Set,Yt=!1,_u="",pu=!1,Ps=0,qn=0,Pa=0,yu=0,$u=0,mi=new Set,Na=new Map,bu=8,di=10,O_=3,kL=3,xL=4,vL=new Set(["read_file","grep","search_files","glob","list_directory","find_files"]),M_=null;function SL(e){return e==="write_file"||e==="edit_file"||e==="patch_file"||e==="bash"}function Xp(e){let t=String(e||"");if(!t||Ua(t)||La(t).length!==1)return!1;let o=/\b(create|write|add|make|build|scaffold)\b[\s\S]{0,160}\b(refactor|rename|improve|update|change|edit)\b/i.test(t)||/\b(refactor|update|change|edit)\b[\s\S]{0,160}\b(create|write|add|make|build|scaffold)\b/i.test(t),s=/\b(create|write|add|make|build|refactor|update|change|edit)\b[\s\S]{0,160}\bfile\b/i.test(t);return o||s}function Ua(e){let t=String(e||"");return t?ku(t)?!0:/\bAutomation(?:\s+ID)?\b|\bLast run:\b/i.test(t)||/\b(work from main|at the start|current branch|git status|worktree|dirty|unrelated changes?|pull\/rebase|before changing|before editing)\b/i.test(t)||/\b(if|when)\b[\s\S]{0,120}\b(stop|abort|do not|don't|without editing|without committing|without pushing)\b/i.test(t)||/\b(backlog|primary backlog|pick (?:at most )?one|at most one|choose (?:one|a task)|priority order|verification is mandatory|stage only|commit and push|push main|push devel)\b/i.test(t):!1}function z_(e){let t=String(e||"");return!t||!Ua(t)?!1:/\b(primary backlog|backlog|pick at most one|at most one|priority order|choose (?:one|a task)|one tightly scoped improvement)\b/i.test(t)}function Ns({blocked:e=!1}={}){return[e?"[SYSTEM BLOCKED] Bounded backlog planning has enough evidence. Do not read or search more files.":"[SYSTEM] Bounded backlog automation plan template.","Before deciding, inspect the concrete backlog/reference paths named by the user prompt. Prefer read_file on those paths over generic searches for words like `backlog`, `TODO`, or `FIXME`.","Ground the selected improvement in those files and the current project. Do not invent generic React bugs, placeholder files, or example components that were not found in the evidence.","For UI work, choose only controls, labels, handlers, or component names that were actually visible in the evidence already read. Do not infer a button exists from the product domain; if the exact target is delegated to a child component, name that existing child component/file as the target instead.","Write the plan now using exactly these label lines. Do not use markdown headings for these labels.","Selected improvement: name one scoped task, or write `no safe task found`.","Selection rationale: why this task is the safest/highest-value choice from the backlog evidence.","Files: list the files you will change and any read-only reference files.","Implementation outline: concrete edit steps, kept to this one task.","Verification plan: exact focused commands or reads that will prove the change.","Browser/UI applicability: say required, not required, or blocked, with the reason.",`After ${bu}-${di} read/search tools, you must choose one scoped task or stop cleanly with \`no safe task found\`; do not keep exploring.`].join(`
1030
+ `)[0],u=c.startsWith("ERROR")||c.includes("CANCELLED")||c.includes("BLOCKED")||e.fnName==="spawn_agents"&&!/✓ Agent/.test(a)&&/✗ Agent/.test(a),d=Ia(e.fnName,e.args,a,u);t||console.log(d),Ot?.onToolEnd&&Ot.onToolEnd(e.fnName,d,!u);let p=m_("post-tool",{tool_name:e.fnName}).results;if(!t&&p.length>0)for(let y of p)y.success?console.log(`${$.dim} [hook post-tool] ${y.command} \u2192 ${y.output||"ok"}${$.reset}`):console.log(`${$.yellow} [hook post-tool] ${y.command} \u2192 ERROR: ${y.error}${$.reset}`);let m=dL(a,e.fnName);if(e.fnName==="bash"&&e.args?.command){let y=e.args.command.trim();!/cat\s*>|<</.test(y)&&/\bcat\s+\S/.test(y)?m+=`
1031
+ 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(y)&&!/npm|yarn|pnpm|make|git\b/.test(y)?m+=`
1032
+ HINT: use list_directory instead of bash ls \u2014 it is the preferred tool for listing directory contents.`:/\bfind\s+\S/.test(y)&&!/git\b|npm\b|-exec\b|-delete\b|-print0\b/.test(y)&&(m+=`
1033
+ HINT: use glob instead of bash find for file discovery \u2014 it is faster and the preferred tool (e.g. glob('**/*.jsx')).`)}return{msg:{role:"tool",content:r?[{type:"text",text:m},...r.map(y=>({type:"image",media_type:y.media_type,data:y.base64}))]:m,tool_call_id:e.callId},summary:d}}var wL=[{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 Mp(e){for(let{re:t,label:n}of wL){let o=e.match(t);if(o){let s=(o[1]||"").trim();return s?`${n}: ${s}`:n}}return null}async function _L(e,t=!1,n={}){let o=new Array(e.length),s=[],r=[],i=null;if(t&&!n.skipSpinner){let c=e.filter(u=>u.canExecute);if(c.length>0){let u;if(c.length===1){let d=c[0],f=bL(d.fnName,d.args);u=`\u23FA ${d.fnName}${f?`(${f})`:""}`}else{let d=c.map(f=>f.fnName).join(", ");u=`\u23FA ${c.length} tools: ${d.length>60?d.substring(0,57)+"\u2026":d}`}i=new ri(u),i.start()}}async function a(){if(r.length!==0){if(r.length===1){let c=r[0],{msg:u,summary:d}=await Op(e[c],t);o[c]=u,s.push(d)}else{let c=r.map(d=>Op(e[d],t)),u=await Promise.all(c);for(let d=0;d<r.length;d++)o[r[d]]=u[d].msg,s.push(u[d].summary)}r=[]}}for(let c=0;c<e.length;c++){let u=e[c];if(!u.canExecute){await a(),o[c]=u.errorResult,s.push(Ia(u.fnName,u.args||{},u.errorResult.content,!0));continue}if(mL.has(u.fnName)){await a(),u.fnName==="spawn_agents"&&i&&(i.stop(),i=null);let{msg:d,summary:f}=await Op(u,t);o[c]=d,s.push(f)}else r.push(c)}if(await a(),i&&i.stop(),t&&s.length>0&&!n.skipSummaries)for(let c of s)console.log(c);return{results:o,summaries:s}}var T=[],R_=300,H_=900*1e3;function Os(e,t){let n=e.get(t);return n?Date.now()-n.ts>H_?(e.delete(t),0):n.count:0}function ur(e,t){let n=e.get(t),o=n&&Date.now()-n.ts<=H_?n.count+1:1;return e.set(t,{count:o,ts:Date.now()}),o}function Pp(e,t,n){e.set(t,{count:n,ts:Date.now()})}var th=new Map,G_=new Map,su=new Map,Aa=new Set,Y_=new Map,ou=new Map,Oa=new Set,Ls=new Map,to=new Map,Ma=new Map,Gt=new Map,gr=new Map,C_=new Map,mu=new Map,Up=new Map,Zn=0,xa=0,ru=0,Wp="",iu=0,Ln=!1,Xl=0,au=0,ko=-1,Hp=!1,cu=0,lu=!1,es=0,jn=!1,ts=0,ns=0,Zt=!1,kn="",va=0,wo=0,uu="",fr=0,pr=0,du="",ba=0,ms=!1,Gp=!1,ja=new Map,Da=new Set,Sa=null,ni=!1,wa=0,A_=!1,Ve=null,In=!1,nh=null,Yp=!1,zp=!1,fu=!1,xo="",hr="",Ea="",Pe="plan",gu=0,be=!1,So=0,fi=null,gs=null,qa=null,Kp=null,li=0,pi=0,hi=0,vo=0,Ta=0,ui=0,Vl=0,Is=!1,js=0,yr=null,no=[],_o=new Set,et=!1,Sn=0,Fa=0,gn=new Set,$r=new Set,Yt=!1,_u="",pu=!1,Ps=0,qn=0,Pa=0,yu=0,$u=0,mi=new Set,Na=new Map,bu=8,di=10,O_=3,kL=3,xL=4,vL=new Set(["read_file","grep","search_files","glob","list_directory","find_files"]),M_=null;function SL(e){return e==="write_file"||e==="edit_file"||e==="patch_file"||e==="bash"}function Xp(e){let t=String(e||"");if(!t||Ua(t)||La(t).length!==1)return!1;let o=/\b(create|write|add|make|build|scaffold)\b[\s\S]{0,160}\b(refactor|rename|improve|update|change|edit)\b/i.test(t)||/\b(refactor|update|change|edit)\b[\s\S]{0,160}\b(create|write|add|make|build|scaffold)\b/i.test(t),s=/\b(create|write|add|make|build|refactor|update|change|edit)\b[\s\S]{0,160}\bfile\b/i.test(t);return o||s}function Ua(e){let t=String(e||"");return t?ku(t)?!0:/\bAutomation(?:\s+ID)?\b|\bLast run:\b/i.test(t)||/\b(work from main|at the start|current branch|git status|worktree|dirty|unrelated changes?|pull\/rebase|before changing|before editing)\b/i.test(t)||/\b(if|when)\b[\s\S]{0,120}\b(stop|abort|do not|don't|without editing|without committing|without pushing)\b/i.test(t)||/\b(backlog|primary backlog|pick (?:at most )?one|at most one|choose (?:one|a task)|priority order|verification is mandatory|stage only|commit and push|push main|push devel)\b/i.test(t):!1}function z_(e){let t=String(e||"");return!t||!Ua(t)?!1:/\b(primary backlog|backlog|pick at most one|at most one|priority order|choose (?:one|a task)|one tightly scoped improvement)\b/i.test(t)}function Ns({blocked:e=!1}={}){return[e?"[SYSTEM BLOCKED] Bounded backlog planning has enough evidence. Do not read or search more files.":"[SYSTEM] Bounded backlog automation plan template.","Before deciding, inspect the concrete backlog/reference paths named by the user prompt. Prefer read_file on those paths over generic searches for words like `backlog`, `TODO`, or `FIXME`.","Ground the selected improvement in those files and the current project. Do not invent generic React bugs, placeholder files, or example components that were not found in the evidence.","For UI work, choose only controls, labels, handlers, or component names that were actually visible in the evidence already read. Do not infer a button exists from the product domain; if the exact target is delegated to a child component, name that existing child component/file as the target instead.","Write the plan now using exactly these label lines. Do not use markdown headings for these labels.","Selected improvement: name one scoped task, or write `no safe task found`.","Selection rationale: why this task is the safest/highest-value choice from the backlog evidence.","Files: list the files you will change and any read-only reference files.","Implementation outline: concrete edit steps, kept to this one task.","Verification plan: exact focused commands or reads that will prove the change.","Browser/UI applicability: say required, not required, or blocked, with the reason.",`After ${bu}-${di} read/search tools, you must choose one scoped task or stop cleanly with \`no safe task found\`; do not keep exploring.`].join(`
1034
1034
  `)}function sn(e){return String(e||"").replace(/^\.\/+/,"").replace(/\/+$/,"")}function EL(e){let t=String(e||"");if(!t)return null;let n=[/\b(?:work|operate|run)\s+(?:only\s+)?(?:in|inside|within|from)\s+[`"']?(\/[^\s`"',;:)]+)/i,/\bworking\s+directory\s*:\s*[`"']?(\/[^\s`"',;:)]+)/i,/\bcwd\s*:\s*[`"']?(\/[^\s`"',;:)]+)/i];for(let o of n){let s=t.match(o);if(!s)continue;let r=String(s[1]||"").replace(/[.]+$/,"");if(r)try{let i=ut.resolve(r);if(ot.existsSync(i)&&ot.statSync(i).isDirectory())return ot.realpathSync(i)}catch{}}return null}function TL(e,t={}){if(!et||gn.size===0)return!0;let n=[];if(t.path&&n.push(t.path),t.pattern&&/[/.]/.test(String(t.pattern))&&n.push(t.pattern),t.include&&/[/.]/.test(String(t.include))&&n.push(t.include),t.file_pattern&&/[/.]/.test(String(t.file_pattern))&&n.push(t.file_pattern),n.length===0)return!1;let o=n.map(sn);for(let s of gn){let r=sn(s);if(r&&o.some(i=>i===r||i.endsWith(`/${r}`)||r.endsWith(`/${i}`)))return!0}return e==="grep"||e==="search_files"?o.some(s=>[...gn].some(r=>s.includes(sn(r)))):!1}function RL(e,t={}){if(e!=="grep"&&e!=="search_files"&&e!=="glob"&&e!=="list_directory"&&e!=="find_files")return!1;let n=sn(t.path||t.cwd||"");if(n&&gn.has(n))return!1;let o=String(t.pattern||t.glob||t.query||t.search||""),s=String(t.include||t.file_pattern||""),r=`${n} ${o} ${s}`;return![...gn].some(i=>{let a=sn(i);return a&&r.includes(a)})}function K_(e){if(!et)return!1;let t=String(e||"");if(!t.trim())return!1;let n=String(_u||"");if(/\b(stale data|list component|ListComponent)\b/i.test(t)&&!/\b(stale data|list component|ListComponent)\b/i.test(n))return!0;let s=new Set,r=/[`'"]?((?:[A-Za-z0-9_.@-]+\/)+[A-Za-z0-9_.@-]+\.(?:tsx|jsx|mjs|cjs|mdx|json|scss|html|yaml|yml|css|ts|js|md))[`'"]?/g,i;for(;i=r.exec(t);)s.add(sn(i[1]));let a=0,c=0;for(let u of s){if(gn.has(u))continue;a++;let d=ut.resolve(process.cwd(),u);ot.existsSync(d)&&c++}return!1}function X_(e){let t=new Set,n=/[`'"]?((?:[A-Za-z0-9_.@-]+\/)+[A-Za-z0-9_.@-]+\.(?:tsx|jsx|mjs|cjs|mdx|json|scss|html|yaml|yml|css|ts|js|md))[`'"]?/g,o;for(;o=n.exec(String(e||""));)t.add(sn(o[1]));return[...t]}function CL(e){if(!et||$r.size===0)return!1;let t=X_(e).filter(o=>o&&!/\.(md|mdx|txt|rst|adoc)$/i.test(o));return t.length===0?!1:t.filter(o=>ot.existsSync(ut.resolve(process.cwd(),o))).length===0}function Jl(e,t){let n=String(t||"").replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?:^|\\n)\\s*(?:[-*]\\s*)?(?:\\*\\*)?${n}\\s*:(?:\\*\\*)?`,"i").test(String(e||""))}function Ra(e){let t=String(e||"");return!t.trim()||K_(t)||V_(t)?!1:/\bno safe task found\b/i.test(t)?!0:Jl(t,"Selected improvement")&&Jl(t,"Selection rationale")&&Jl(t,"Files")&&Jl(t,"Verification plan")}function V_(e){let t=String(e||"");return t.trim()?/(?:^|\n)\s*#{1,6}\s*selected improvement\b/i.test(t)&&/(?:^|\n)\s*#{1,6}\s*selection rationale\b/i.test(t)&&/(?:^|\n)\s*#{1,6}\s*files\b/i.test(t)&&/(?:^|\n)\s*#{1,6}\s*verification plan\b/i.test(t):!1}function AL(e){let t=String(e||"");return t.trim()?/\b(need|must|will|should|let'?s|attempt|going)\b.{0,80}\b(call|issue|use|run|read)\b.{0,80}\b(read_file|tool call|tool_calls?|JSON calls?)\b/i.test(t)||/\b(need|must|will|should|let'?s|attempt|going)\b.{0,80}\b(run|check|use)\b.{0,80}\b(git status|bash|grep|glob|search)\b/i.test(t)||/\{\s*["']tool["']\s*:\s*["'](?:read_file|grep|search_files|glob)["']/i.test(t):!1}function dr(e,t){return et&&Yt&&(qn>0||Gt.size>0)&&e.size===0&&t===0}function J_(e){let t=String(e||"");if(!/\bno safe task found\b/i.test(t)||/\bexample only\b|\bnot applicable\b/i.test(t)||!(/\b(because|reason|blocked|blocker|cannot|can't|unable|failed|unavailable|permission denied|missing|not found|no readable|dirty worktree|wrong branch|merge conflict|precheck blocked|preflight failed|ambiguous|unrelated|manual user work|no safe worthwhile improvement)\b/i.test(t)&&t.trim().length>60))return!1;let o=gn.size===0||Fa>0;return Sn>=bu?o:/\b(blocked|blocker|cannot|can't|unable|failed|unavailable|permission denied|missing|not found|no readable|dirty worktree|wrong branch|merge conflict|precheck blocked|preflight failed)\b/i.test(t)&&/\b(because|reason|preflight|worktree|branch|git|permission|missing|unavailable|inspect|read|search)\b/i.test(t)}function Vp(e){let t=String(e||"");if(!t.trim()||/\bexample only\b/i.test(t))return!1;let n=/\bpreflight\s*:/i.test(t),o=/\bpreflight output\s*:/i.test(t),s=/\bbranch\s*:/i.test(t),r=/\b(chosen task|selected improvement)\s*:/i.test(t)||/\bno safe task found\b/i.test(t),i=/\bfiles changed\s*:/i.test(t),a=/\bverification\s*:/i.test(t),c=/\bcommit\s*:/i.test(t),u=/\bpush\s*:/i.test(t),d=/\bfinal git status\s*:/i.test(t);return!(n&&o&&s&&r&&i&&a&&c&&u&&d)||Ve?.ran&&(/\bpreflight\s*:\s*(?:not performed|not run|not applicable|unknown)\b/i.test(t)||/\bpreflight output\s*:\s*(?:not performed|not run|not applicable|unknown|\(missing preflight output\))\b/i.test(t)||/\bbranch\s*:\s*(?:not applicable|unknown)\b/i.test(t))?!1:/\bno safe task found\b/i.test(t)?J_(t):!0}function ku(e){let t=String(e||"");if(!t)return null;let n=[/\bwork\s+(?:from|on)\s+(?:the\s+)?(?:branch\s+)?[`'"]?([A-Za-z0-9._/-]+)[`'"]?\s+only\b/i,/\bwork\s+(?:from|on)\s+(?:the\s+)?[`'"]?([A-Za-z0-9._/-]+)[`'"]?\s+branch\s+only\b/i];for(let o of n){let s=t.match(o);if(!s)continue;let r=String(s[1]||"").trim();if(r)return r}return null}function OL(e){let t=String(e||"").trim();if(!t)return{branch:null,dirty:null,changedFiles:[]};if(/^fatal:/i.test(t))return{branch:null,dirty:null,changedFiles:[]};let n=t.split(`
1035
1035
  `).map(c=>c.replace(/\r$/,"")),o=n.find(c=>c.startsWith("## "))||n[0]||"",s=o.startsWith("## ")?o.slice(3).trim():o.trim(),r=s?s.split("...")[0].trim().split(/\s+/)[0]:null,i=n.filter(c=>!c.startsWith("## ")&&c.trim()!==""),a=[];for(let c of i){let u=c.match(/^[ MADRCU?!]{1,2}\s+(.*)$/);if(!u)continue;let d=(u[1]||"").trim();if(!d)continue;let f=d.includes(" -> ")?d.split(" -> ").pop():d;f&&a.push(f)}return{branch:r||null,dirty:a.length>0,changedFiles:a}}function ML(e){let t=String(e||"");return!t||!Ua(t)?!1:ku(t)?!0:/\b(git status|current branch|worktree|dirty|pull\/rebase|rebase|commit|push)\b/i.test(t)}function PL(e,t=2500){let n=String(e??"");return n.trim()?n.length<=t?n:n.slice(0,t)+`
1036
- ...(truncated ${n.length-t} chars)`:"(no output)"}async function NL(e,t,n){if(Ve?.ran)return Ve;let o=nh||ku(e),s="git status --short --branch",r="preflight-git-status";Ve={required:!0,ran:!0,ok:!1,command:s,requiredBranch:o,branch:null,dirty:null,changedFiles:[],raw:""};let i="",a=!1;try{let $={role:"assistant",content:"",tool_calls:[{id:r,type:"function",function:{name:"bash",arguments:JSON.stringify({command:s})}}]};n.push($),t.push($),Ot?.onToolStart&&(Ot.onToolStart("bash",{command:s}),a=!0),i=await eh("bash",{command:s},{silent:!0,autoConfirm:!0})}catch($){i=`ERROR: failed to run preflight: ${$?.message||String($)}`}let c=String(i??"");if(a&&Ot?.onToolEnd){let $=c.length>5e4?c.substring(0,5e4)+`
1037
- ...(truncated ${c.length-5e4} chars)`:c,b=$.split(`
1038
- `)[0]||"",x=b.startsWith("ERROR")||b.includes("CANCELLED")||b.includes("BLOCKED");try{Ot.onToolEnd("bash",Ia("bash",{command:s},$,x),!x)}catch{}}let u=c.trim(),d=/^\s*##\s+\S+/.test(u),f=OL(c);Ve.branch=f.branch,Ve.dirty=f.dirty,Ve.changedFiles=f.changedFiles,Ve.raw=c;let p={role:"tool",tool_call_id:r,content:c||"(no output)"};n.push(p),t.push(p);let h=PL(c),m=`[PRECHECK] Preflight ran: \`${s}\`.`+(o?` Required branch: ${o}.`:"")+`
1036
+ ...(truncated ${n.length-t} chars)`:"(no output)"}async function NL(e,t,n){if(Ve?.ran)return Ve;let o=nh||ku(e),s="git status --short --branch",r="preflight-git-status";Ve={required:!0,ran:!0,ok:!1,command:s,requiredBranch:o,branch:null,dirty:null,changedFiles:[],raw:""};let i="",a=!1;try{let y={role:"assistant",content:"",tool_calls:[{id:r,type:"function",function:{name:"bash",arguments:JSON.stringify({command:s})}}]};n.push(y),t.push(y),Ot?.onToolStart&&(Ot.onToolStart("bash",{command:s}),a=!0),i=await eh("bash",{command:s},{silent:!0,autoConfirm:!0})}catch(y){i=`ERROR: failed to run preflight: ${y?.message||String(y)}`}let c=String(i??"");if(a&&Ot?.onToolEnd){let y=c.length>5e4?c.substring(0,5e4)+`
1037
+ ...(truncated ${c.length-5e4} chars)`:c,b=y.split(`
1038
+ `)[0]||"",x=b.startsWith("ERROR")||b.includes("CANCELLED")||b.includes("BLOCKED");try{Ot.onToolEnd("bash",Ia("bash",{command:s},y,x),!x)}catch{}}let u=c.trim(),d=/^\s*##\s+\S+/.test(u),f=OL(c);Ve.branch=f.branch,Ve.dirty=f.dirty,Ve.changedFiles=f.changedFiles,Ve.raw=c;let p={role:"tool",tool_call_id:r,content:c||"(no output)"};n.push(p),t.push(p);let h=PL(c),m=`[PRECHECK] Preflight ran: \`${s}\`.`+(o?` Required branch: ${o}.`:"")+`
1039
1039
 
1040
1040
  ${h}`,g={role:"assistant",content:m};if(n.push(g),t.push(g),!rh)try{Ot?.onToken?Ot.onToken(m+`
1041
1041
  `):console.log(m)}catch{}return!c||/^ERROR:/i.test(c)||/^fatal:/i.test(c)||!d||f.dirty||o&&(!f.branch||f.branch!==o)?(Ve.ok=!1,Ve):(Ve.ok=!0,Ve)}async function LL(e,t){if(Yt||!et||gn.size===0)return;let n=[...gn].filter(d=>/\.(md|mdx|txt|rst|adoc|tsx?|jsx?)$/i.test(d)).slice(0,4);if(n.length===0)return;Yt=!0;let o="[BACKLOG PREFLIGHT] Reading prompt-named backlog/reference files before planning.",s={role:"assistant",content:o};if(t.push(s),e.push(s),!rh)try{Ot?.onToken?Ot.onToken(o+`
1042
- `):console.log(o)}catch{}let r=new Map;async function i(d,f,p,{named:h=!1}={}){let m={role:"assistant",content:"",tool_calls:[{id:p,type:"function",function:{name:d,arguments:JSON.stringify(f)}}]};t.push(m),e.push(m);let g="";try{Ot?.onToolStart&&Ot.onToolStart(d,f),g=await eh(d,f,{silent:!0,autoConfirm:!0})}catch(x){g=`ERROR: failed to read backlog evidence ${f.path||d}: ${x?.message||String(x)}`}let $=String(g||"");if(Ot?.onToolEnd){let x=$.split(`
1043
- `)[0]||"",_=/^ERROR:/i.test(x)||x.includes("CANCELLED")||x.includes("BLOCKED");try{Ot.onToolEnd(d,Ia(d,f,$.slice(0,5e4),_),!_)}catch{}}let b={role:"tool",tool_call_id:p,content:$||"(no output)"};return t.push(b),e.push(b),d==="read_file"&&f.path&&r.set(sn(f.path),$),Sn++,h&&Fa++,$}for(let d=0;d<n.length;d++){let f=n[d];await i("read_file",{path:f,line_start:1,line_end:140},`bounded-backlog-evidence-${d}`,{named:!0})}if(/\b(current UI|UI\/components|components?|toolbar|palette|inspector|command center|menus?)\b/i.test(_u)){let d=["components","src","app"].filter(h=>ot.existsSync(ut.resolve(process.cwd(),h)));for(let h=0;h<Math.min(d.length,2);h++)await i("list_directory",{path:d[h],max_depth:2},`bounded-backlog-ui-tree-${h}`);let f=["components/NotationToolbar.tsx","components/CommandCenter.tsx","components/EditPalette.tsx","components/Inspector.tsx"].filter(h=>ot.existsSync(ut.resolve(process.cwd(),h)));for(let h=0;h<Math.min(f.length,2);h++)$r.add(f[h]),await i("read_file",{path:f[h],line_start:1,line_end:180},`bounded-backlog-ui-evidence-${h}`);let p=[];for(let[h,m]of r.entries()){if(!h.startsWith("components/"))continue;let g=/from\s+['"](?:@\/components\/|\.\/)([A-Za-z][A-Za-z0-9_-]*)['"]/g,$;for(;$=g.exec(m);){let b=`components/${$[1]}.tsx`;ot.existsSync(ut.resolve(process.cwd(),b))&&!r.has(b)&&!p.includes(b)&&p.push(b)}}for(let h=0;h<Math.min(p.length,2);h++){let m=p[h];$r.add(m),await i("read_file",{path:m,line_start:1,line_end:180},`bounded-backlog-ui-child-evidence-${h}`)}}let u={role:"user",content:"[BACKLOG PREFLIGHT] The prompt-named backlog/reference files and any requested UI/component evidence above have already been read. Your next response must be the bounded plan labels exactly as requested (`Selected improvement:`, `Selection rationale:`, `Files:`, `Implementation outline:`, `Verification plan:`, `Browser/UI applicability:`). Choose only controls, handlers, labels, and files that are visible in that evidence; do not invent toolbar buttons or src/components paths. Do not request or describe more read_file calls."};t.push(u),e.push(u)}function IL(e){let t=String(e||"").trim();return t?/^(hi|hello|hey|yo)\b/i.test(t)||/\b(introduce yourself|who are you|what can you do|tell me about yourself)\b/i.test(t):!1}function Jp(e){return String(e||"").replace(/\\/g,"/").replace(/^\.\//,"").trim()}function La(e){let n=String(e||"").match(/(?:^|\s)((?:\.{1,2}\/)?[\w./-]+\.(?:js|ts|tsx|jsx|py|md|json|yml|yaml|sh|css|html))\b/gi);return n?[...new Set(n.map(o=>Jp(o)))]:[]}function si(e,t){e===Wp?(iu++,debug&&debug.DEBUG&&process.stdout.write(`\x1B[1A\x1B[2K${t} \u26A0 ${e} (\xD7${iu})${y.reset}
1044
- `)):(Wp=e,iu=1,j(`${t} \u26A0 ${e}${y.reset}`))}var hu=[];function jL(e){hu.push(e.trim())}function DL(){return hu.length===0?null:hu.splice(0,hu.length).join(`
1042
+ `):console.log(o)}catch{}let r=new Map;async function i(d,f,p,{named:h=!1}={}){let m={role:"assistant",content:"",tool_calls:[{id:p,type:"function",function:{name:d,arguments:JSON.stringify(f)}}]};t.push(m),e.push(m);let g="";try{Ot?.onToolStart&&Ot.onToolStart(d,f),g=await eh(d,f,{silent:!0,autoConfirm:!0})}catch(x){g=`ERROR: failed to read backlog evidence ${f.path||d}: ${x?.message||String(x)}`}let y=String(g||"");if(Ot?.onToolEnd){let x=y.split(`
1043
+ `)[0]||"",_=/^ERROR:/i.test(x)||x.includes("CANCELLED")||x.includes("BLOCKED");try{Ot.onToolEnd(d,Ia(d,f,y.slice(0,5e4),_),!_)}catch{}}let b={role:"tool",tool_call_id:p,content:y||"(no output)"};return t.push(b),e.push(b),d==="read_file"&&f.path&&r.set(sn(f.path),y),Sn++,h&&Fa++,y}for(let d=0;d<n.length;d++){let f=n[d];await i("read_file",{path:f,line_start:1,line_end:140},`bounded-backlog-evidence-${d}`,{named:!0})}if(/\b(current UI|UI\/components|components?|toolbar|palette|inspector|command center|menus?)\b/i.test(_u)){let d=["components","src","app"].filter(h=>ot.existsSync(ut.resolve(process.cwd(),h)));for(let h=0;h<Math.min(d.length,2);h++)await i("list_directory",{path:d[h],max_depth:2},`bounded-backlog-ui-tree-${h}`);let f=["components/NotationToolbar.tsx","components/CommandCenter.tsx","components/EditPalette.tsx","components/Inspector.tsx"].filter(h=>ot.existsSync(ut.resolve(process.cwd(),h)));for(let h=0;h<Math.min(f.length,2);h++)$r.add(f[h]),await i("read_file",{path:f[h],line_start:1,line_end:180},`bounded-backlog-ui-evidence-${h}`);let p=[];for(let[h,m]of r.entries()){if(!h.startsWith("components/"))continue;let g=/from\s+['"](?:@\/components\/|\.\/)([A-Za-z][A-Za-z0-9_-]*)['"]/g,y;for(;y=g.exec(m);){let b=`components/${y[1]}.tsx`;ot.existsSync(ut.resolve(process.cwd(),b))&&!r.has(b)&&!p.includes(b)&&p.push(b)}}for(let h=0;h<Math.min(p.length,2);h++){let m=p[h];$r.add(m),await i("read_file",{path:m,line_start:1,line_end:180},`bounded-backlog-ui-child-evidence-${h}`)}}let u={role:"user",content:"[BACKLOG PREFLIGHT] The prompt-named backlog/reference files and any requested UI/component evidence above have already been read. Your next response must be the bounded plan labels exactly as requested (`Selected improvement:`, `Selection rationale:`, `Files:`, `Implementation outline:`, `Verification plan:`, `Browser/UI applicability:`). Choose only controls, handlers, labels, and files that are visible in that evidence; do not invent toolbar buttons or src/components paths. Do not request or describe more read_file calls."};t.push(u),e.push(u)}function IL(e){let t=String(e||"").trim();return t?/^(hi|hello|hey|yo)\b/i.test(t)||/\b(introduce yourself|who are you|what can you do|tell me about yourself)\b/i.test(t):!1}function Jp(e){return String(e||"").replace(/\\/g,"/").replace(/^\.\//,"").trim()}function La(e){let n=String(e||"").match(/(?:^|\s)((?:\.{1,2}\/)?[\w./-]+\.(?:js|ts|tsx|jsx|py|md|json|yml|yaml|sh|css|html))\b/gi);return n?[...new Set(n.map(o=>Jp(o)))]:[]}function si(e,t){e===Wp?(iu++,debug&&debug.DEBUG&&process.stdout.write(`\x1B[1A\x1B[2K${t} \u26A0 ${e} (\xD7${iu})${$.reset}
1044
+ `)):(Wp=e,iu=1,j(`${t} \u26A0 ${e}${$.reset}`))}var hu=[];function jL(e){hu.push(e.trim())}function DL(){return hu.length===0?null:hu.splice(0,hu.length).join(`
1045
1045
  `)}function qL(e){let t=e._startedAt?Math.round((e.finishedAt-e._startedAt)/1e3):null,n=t!==null?`
1046
1046
  Duration: ${t}s`:"",o=typeof e.result.result=="string"?e.result.result.slice(0,4e3):JSON.stringify(e.result.result||"").slice(0,4e3),s=e.result.filesModified&&e.result.filesModified.length>0?`
1047
1047
  Files modified: ${e.result.filesModified.join(", ")}`:"";return`[BACKGROUND AGENT COMPLETED]
1048
1048
  Job: ${e.jobId}
1049
1049
  Task: "${e.agentDef.task}"`+n+`
1050
1050
  Status: ${e.result.status||"done"}`+s+`
1051
- Result: ${o}`}function Zl(e,t){let{getCompletedJobs:n}=Gr(),o=n();for(let s of o){let r={role:"user",content:qL(s)};e.push(r),t.push(r);let i=s.result?.status||"done",a=i==="failed"?y.red+" \u2717":y.cyan+" \u2713";process.stderr.write(`${a} Background agent ${i}: ${s.agentDef.task.slice(0,50)} \u2014 ${String(s.result?.result||"").slice(0,80)}${y.reset}
1051
+ Result: ${o}`}function Zl(e,t){let{getCompletedJobs:n}=Gr(),o=n();for(let s of o){let r={role:"user",content:qL(s)};e.push(r),t.push(r);let i=s.result?.status||"done",a=i==="failed"?$.red+" \u2717":$.cyan+" \u2713";process.stderr.write(`${a} Background agent ${i}: ${s.agentDef.task.slice(0,50)} \u2014 ${String(s.result?.result||"").slice(0,80)}${$.reset}
1052
1052
  `)}}function Z_(e,t){let n=[],o=new Set([...t.keys(),...Aa,...Oa]);if(!o.size||!e)return n;for(let s of o){let r=s.split("/").pop();if(r&&(e.includes(r)||e.includes(s))){let a=e.split(`
1053
1053
  `).find(c=>c.includes(r)||c.includes(s));n.push({file:s,action:(a||"edit this file").trim().slice(0,200),done:!1})}}return n}function FL(e){if(!e||typeof e!="string")return[];let t=e.match(/[A-Za-z_][A-Za-z0-9_]{2,}/g)||[],n=new Set(["the","and","for","with","from","into","that","this","when","then","have","your","just","read","write","edit","file","files","test","tests","verify","phase","implement","summary","report","pass","fail","changes","change","address","original","task","user","request","code","module","function","class"]),o=new Set,s=[];for(let r of t){let i=r.toLowerCase();n.has(i)||o.has(i)||(o.add(i),s.push(r))}return s.sort((r,i)=>i.length-r.length),s.slice(0,6)}function BL(){return ot.existsSync(ut.join(process.cwd(),"pnpm-lock.yaml"))?"pnpm":ot.existsSync(ut.join(process.cwd(),"yarn.lock"))?"yarn":"npm"}function Ms(e){let t=BL();return e==="test"?t==="yarn"?"yarn test":t==="pnpm"?"pnpm test":"npm test":t==="yarn"?`yarn ${e}`:t==="pnpm"?`pnpm run ${e}`:`npm run ${e}`}function P_(e,t,n){let o=[...e||[]].slice(0,6).join(", ")||"recently modified files",s=(t||[]).slice(0,3),r=(n||[]).slice(0,3),i=[`[SYSTEM] You already changed code in: ${o}.`,"Verification is mandatory before further exploration \u2014 do not read other files. STEP 1: read_file the modified file(s) to confirm the edit was applied correctly. Do not trust memory \u2014 verify the actual file content on disk. STEP 2: run the narrowest relevant verification command (lint, test, typecheck)."];return s.length>0&&i.push(`Suggested verification commands: ${s.join(" | ")}`),r.length>0&&i.push(`Likely related tests: ${r.join(", ")}`),i.push('If verification passes: report "Verification passed" and you may continue. If verification fails: fix the issue before any other work.'),i.push("MULTI-STEP CHECK: If you created a new file or extracted code into a module, verify that all files that should import/require it have been updated. If the task mentions multiple files, check that each one has been handled."),i.join(`
1054
1054
  `)}function N_(e){if(!e||!e.fnName||!["bash","ssh_exec"].includes(e.fnName))return!1;let t=String(e.args?.command||"").toLowerCase();return/\b(test|jest|vitest|pytest|mocha|rspec|phpunit|cargo test|go test|tsc|build|lint|eslint|check)\b/.test(t)||/\bnode\s+["']?[\w./ -]+\.(?:c?js|mjs)\b/.test(t)}async function Q_(e){let t=FL(e);if(t.length===0)return[];let{searchContentIndex:n}=Es(),o=[],s=new Set;for(let r of t)try{let i=await n(r,void 0,process.cwd());for(let a of i.slice(0,3)){let c=`${a.file}:${a.name}:${a.line}`;if(!s.has(c)&&(s.add(c),o.push(a),o.length>=5))return o}}catch{}return o}async function ek(e){let t=await Q_(e);if(t.length===0)return"";let{getRelatedFiles:n,findSymbolReferences:o}=Es(),s=["Likely symbol targets:"];for(let r=0;r<t.length;r++){let i=t[r],a=Math.max(1,i.line-20),c=i.line+40;s.push(`${r+1}. ${i.name} (${i.type}) in ${i.file}:${i.line} -> read_file(path='${i.file}', line_start=${a}, line_end=${c})`);try{let u=await n(i.file,process.cwd(),3);u.length>0&&s.push(` Follow-up files: ${u.join(", ")} (read only if the primary symbol points into one of these modules)`)}catch{}try{let u=await o(i.name,process.cwd(),{excludeFile:i.file,excludeLine:i.line,limit:2});u.length>0&&s.push(` Likely callers/usages: ${u.map(d=>`${d.file}:${d.line}`).join(", ")} (read these next if behavior depends on where ${i.name} is invoked)`)}catch{}}return`${s.join(`
1055
1055
  `)}
1056
1056
  Use these exact targeted reads before broader searching.
1057
1057
 
1058
- `}async function Ba(e){let{getFileIndex:t}=Es(),{buildContentIndex:n,findSymbolReferences:o,getRelatedFiles:s}=Es(),i=t().filter(u=>/^tests?\//.test(u)||/\.test\./.test(u)||/\.spec\./.test(u));if(i.length===0)return[];let a=new Set,c=await n(process.cwd());for(let u of e||[]){let d=String(u),f=ut.basename(d).replace(/\.[^.]+$/,"");if(f.length<3)continue;for(let m of i)if(m.includes(f)&&a.add(m),a.size>=4)return[...a];try{let m=await s(d,process.cwd(),4);for(let g of m){let $=ut.basename(g).replace(/\.[^.]+$/,"");if(!($.length<3)){for(let b of i)if(b.includes($)&&a.add(b),a.size>=4)return[...a]}}}catch{}let h=(Array.isArray(c.files?.[d]?.defs)?c.files[d].defs:[]).filter(m=>["function","class","export"].includes(m.type)).map(m=>m.name).filter((m,g,$)=>m&&$.indexOf(m)===g).slice(0,3);for(let m of h)try{let g=await o(m,process.cwd(),{excludeFile:d,limit:8});for(let $ of g)if(i.includes($.file)&&a.add($.file),a.size>=4)return[...a]}catch{}}return[...a]}function UL(e,t={}){if(!Array.isArray(e)||e.length===0)return[];let n=e.slice(0,4).join(" "),o=[],s=String(t.test||"");return/vitest/.test(s)||ot.existsSync(ut.join(process.cwd(),"vitest.config.ts"))||ot.existsSync(ut.join(process.cwd(),"vitest.config.js"))?o.push(`npx vitest run ${n}`):(/jest/.test(s)||ot.existsSync(ut.join(process.cwd(),"jest.config.js"))||ot.existsSync(ut.join(process.cwd(),"jest.config.cjs"))||ot.existsSync(ut.join(process.cwd(),"jest.config.mjs")))&&o.push(`npx jest --runInBand ${n}`),(ot.existsSync(ut.join(process.cwd(),"pytest.ini"))||ot.existsSync(ut.join(process.cwd(),"pyproject.toml")))&&e.some(r=>/\.py$/i.test(r))&&o.push(`pytest ${e.filter(r=>/\.py$/i.test(r)).slice(0,4).join(" ")}`),o}async function oi(e,t,n,o){if(!be)return null;let s=Pe;Pe=e,gu=0,gs=Lp(e,yr),e==="implement"&&(vo=0,et&&(qn=0,Pa=0,yu=0,$u=0,mi.clear(),Na.clear())),e==="verify"&&(pi=0,hi=0,Is=!1,js=0),es=0,jn=!1,ts=0,ns=0,gr.clear(),mu.clear(),th.clear(),Ma.clear(),e==="implement"&&(no=Z_(t||"",Ls));let r=no.length>0?`
1058
+ `}async function Ba(e){let{getFileIndex:t}=Es(),{buildContentIndex:n,findSymbolReferences:o,getRelatedFiles:s}=Es(),i=t().filter(u=>/^tests?\//.test(u)||/\.test\./.test(u)||/\.spec\./.test(u));if(i.length===0)return[];let a=new Set,c=await n(process.cwd());for(let u of e||[]){let d=String(u),f=ut.basename(d).replace(/\.[^.]+$/,"");if(f.length<3)continue;for(let m of i)if(m.includes(f)&&a.add(m),a.size>=4)return[...a];try{let m=await s(d,process.cwd(),4);for(let g of m){let y=ut.basename(g).replace(/\.[^.]+$/,"");if(!(y.length<3)){for(let b of i)if(b.includes(y)&&a.add(b),a.size>=4)return[...a]}}}catch{}let h=(Array.isArray(c.files?.[d]?.defs)?c.files[d].defs:[]).filter(m=>["function","class","export"].includes(m.type)).map(m=>m.name).filter((m,g,y)=>m&&y.indexOf(m)===g).slice(0,3);for(let m of h)try{let g=await o(m,process.cwd(),{excludeFile:d,limit:8});for(let y of g)if(i.includes(y.file)&&a.add(y.file),a.size>=4)return[...a]}catch{}}return[...a]}function UL(e,t={}){if(!Array.isArray(e)||e.length===0)return[];let n=e.slice(0,4).join(" "),o=[],s=String(t.test||"");return/vitest/.test(s)||ot.existsSync(ut.join(process.cwd(),"vitest.config.ts"))||ot.existsSync(ut.join(process.cwd(),"vitest.config.js"))?o.push(`npx vitest run ${n}`):(/jest/.test(s)||ot.existsSync(ut.join(process.cwd(),"jest.config.js"))||ot.existsSync(ut.join(process.cwd(),"jest.config.cjs"))||ot.existsSync(ut.join(process.cwd(),"jest.config.mjs")))&&o.push(`npx jest --runInBand ${n}`),(ot.existsSync(ut.join(process.cwd(),"pytest.ini"))||ot.existsSync(ut.join(process.cwd(),"pyproject.toml")))&&e.some(r=>/\.py$/i.test(r))&&o.push(`pytest ${e.filter(r=>/\.py$/i.test(r)).slice(0,4).join(" ")}`),o}async function oi(e,t,n,o){if(!be)return null;let s=Pe;Pe=e,gu=0,gs=Lp(e,yr),e==="implement"&&(vo=0,et&&(qn=0,Pa=0,yu=0,$u=0,mi.clear(),Na.clear())),e==="verify"&&(pi=0,hi=0,Is=!1,js=0),es=0,jn=!1,ts=0,ns=0,gr.clear(),mu.clear(),th.clear(),Ma.clear(),e==="implement"&&(no=Z_(t||"",Ls));let r=no.length>0?`
1059
1059
 
1060
1060
  ACTION ITEMS (execute these in order; use one targeted read if code context is needed):
1061
1061
  `+no.map((c,u)=>`${u+1}. ${c.file} \u2014 ${c.action}`).join(`
@@ -1081,7 +1081,7 @@ Prefer these before broader suites when a targeted run is possible.
1081
1081
  Report PASS (all good) or FAIL (list specific issues).
1082
1082
 
1083
1083
  Files modified: ${c}
1084
- ${i}${f}${p}Summary: ${Kp}`}return j(`${y.cyan} \u21B3 Phase transition: ${s} \u2192 ${e} (model: ${gs||"default"})${y.reset}`),a?{role:"user",content:a}:null}async function wu(e){let t=[],o=[...e||[]].map(c=>String(c).toLowerCase()),s={};try{let c=ut.join(process.cwd(),"package.json");if(ot.existsSync(c)){s=JSON.parse(ot.readFileSync(c,"utf-8")).scripts||{};let d=[["test",Ms("test")],["lint",Ms("lint")],["typecheck",Ms("typecheck")],["check",Ms("check")],["build",Ms("build")]];for(let[f,p]of d)s[f]&&t.push(p)}}catch{}t.length===0&&(ot.existsSync(ut.join(process.cwd(),"package.json"))&&t.push(Ms("test")),(ot.existsSync(ut.join(process.cwd(),"pytest.ini"))||ot.existsSync(ut.join(process.cwd(),"pyproject.toml")))&&t.push("pytest"));let r=await Ba(e);t.unshift(...UL(r,s));let i=o.some(c=>/\.(ts|tsx)$/.test(c)),a=o.some(c=>/\.(js|jsx|ts|tsx)$/.test(c));return i&&!t.includes(Ms("typecheck"))&&t.push(Ms("typecheck")),a&&!t.includes(Ms("lint"))&&t.push(Ms("lint")),[...new Set(t)].slice(0,4)}function sh(e){let t=process.env.NEX_LANGUAGE;if(t&&t!=="auto")return t;if(oh())return"English";let n=String(e||"").trim();if(!n)return"English";let s=n.replace(/```[\s\S]*?```/g," ").replace(/`[^`]*`/g," ").toLowerCase().match(/[a-zäöüß]+/gi)||[],r=new Set(["the","and","or","for","with","without","write","create","explain","refactor","query","function","makefile","dockerfile","healthcheck","preserve","return","input","output","using","should","must","please"]),i=new Set(["der","die","das","und","oder","ist","sind","nicht","bitte","erstelle","schreibe","erkl\xE4re","funktion","abfrage","datei","zur\xFCck","mit","ohne","danke"]),a=0,c=0;for(let u of s)r.has(u)&&a++,i.has(u)&&c++;return c>=3&&c>a*1.4?"German":"English"}function WL(e){let n=String(e||"").replace(/```[\s\S]*?```/g," ").replace(/`[^`]*`/g," ").toLowerCase().match(/[a-zäöüß]+/gi)||[];if(n.length===0)return"English";let o=new Set(["the","and","or","for","with","without","write","create","explain","refactor","query","function","makefile","dockerfile","healthcheck","preserve","return","input","output","using","should","must","please","this","that","it","is","are","as","in"]),s=new Set(["der","die","das","und","oder","ist","sind","nicht","bitte","ich","habe","wir","du","sie","es","diese","dieser","dass","wird","wurde","um","mit","ohne","danke"]),r=0,i=0;for(let a of n)o.has(a)&&r++,s.has(a)&&i++;return i>=3&&i>r*1.4?"German":"English"}function HL(e,t){if(typeof t!="string"||typeof e!="string")return!1;let n=e.toLowerCase(),o=t.toLowerCase(),s=/\b(bash|shell|sh)\b/.test(n)||/\b(one-?liner|pre-commit)\b/.test(n),r=/\b(dockerfile|makefile|cron|crontab|sql)\b/.test(n);if(!s&&!r&&(/```bash\b/.test(o)||/```sh\b/.test(o)))return!0;let i=t.replace(/```[\s\S]*?```/g," ").replace(/`[^`]*`/g," ").toLowerCase();return[/\b(let me|i(?:'|’)ll|i will)\s+(check|search|look)\b/,/\bfirst,\s*let me\b/,/\bsince i (?:do not|don’t|don't) see\b/,/\b(let me|i(?:'|’)ll|i will)\s+(?:run|execute)\b/,/\bsearch(?:ing)?\s+for\b/,/\bcheck if there(?: is| are)\b/].some(a=>a.test(i))}function tk(e){let t=String(e||"").trim();if(!t||t.length>2500)return!1;let n=t.toLowerCase();return/\b(?:repo|repository|project|codebase|existing|current workspace|this workspace)\b/.test(n)||/\b(?:create|write|save)\s+(?:a\s+)?file\b/.test(n)||/\b(?:read|search|inspect|look through|find in|run|install)\b/.test(n)?!1:[/\b(?:reply|respond|answer)\b.*\bexactly\b/i,/\b(?:sql\s+query|select\s+.+\s+from)\b/i,/\b(?:cron(?:\s+expression)?|crontab)\b/i,/\bregex\b.*\b(?:explain|refactor|rewrite|readable)\b/i,/\b(?:small|simple|minimal)?\s*makefile\b/i,/\b(?:small|simple|minimal)?\s*dockerfile\b/i,/\b(?:docker\s+healthcheck|healthcheck)\b/i,/\brefactor\b.*\bcallbacks?\b.*\basync\s*\/\s*await\b/i,/\bcallbacks?\b.*\basync\s*\/\s*await\b/i,/\btypescript\b.*\binterface\b/i,/\b(?:debug|fix)\b.*\bbash\b.*\bscript\b/i,/\bpre-commit\s+hook\b/i,/\bbash\s+one-?liner\b/i,/\bdataclass\b/i,/\bexpress\b.*\broute\b/i,/\beventemitter\b/i,/\b(?:javascript|js|python)\s+function\b/i,/\bfunction\s+\w+\s*\(/i].some(o=>o.test(t))}function GL(e){if(typeof e!="string")return null;let t=e.toLowerCase();return/\bsieve of eratosthenes\b/i.test(e)&&/\bprimes?\b/i.test(e)&&/\bup to n\b/i.test(e)?["```python","from __future__ import annotations","","from typing import List","","","def sieve_of_eratosthenes(n: int) -> List[int]:",' """Return all prime numbers <= n using the Sieve of Eratosthenes.',""," Args:"," n: Upper bound (inclusive).",""," Returns:"," A list of all primes p such that 2 <= p <= n, in ascending order.",' """'," if n < 2:"," return []",""," is_prime = [True] * (n + 1)"," is_prime[0] = False"," is_prime[1] = False",""," p = 2"," while p * p <= n:"," if is_prime[p]:"," for multiple in range(p * p, n + 1, p):"," is_prime[multiple] = False"," p += 1",""," return [i for i in range(2, n + 1) if is_prime[i]]","```"].join(`
1084
+ ${i}${f}${p}Summary: ${Kp}`}return j(`${$.cyan} \u21B3 Phase transition: ${s} \u2192 ${e} (model: ${gs||"default"})${$.reset}`),a?{role:"user",content:a}:null}async function wu(e){let t=[],o=[...e||[]].map(c=>String(c).toLowerCase()),s={};try{let c=ut.join(process.cwd(),"package.json");if(ot.existsSync(c)){s=JSON.parse(ot.readFileSync(c,"utf-8")).scripts||{};let d=[["test",Ms("test")],["lint",Ms("lint")],["typecheck",Ms("typecheck")],["check",Ms("check")],["build",Ms("build")]];for(let[f,p]of d)s[f]&&t.push(p)}}catch{}t.length===0&&(ot.existsSync(ut.join(process.cwd(),"package.json"))&&t.push(Ms("test")),(ot.existsSync(ut.join(process.cwd(),"pytest.ini"))||ot.existsSync(ut.join(process.cwd(),"pyproject.toml")))&&t.push("pytest"));let r=await Ba(e);t.unshift(...UL(r,s));let i=o.some(c=>/\.(ts|tsx)$/.test(c)),a=o.some(c=>/\.(js|jsx|ts|tsx)$/.test(c));return i&&!t.includes(Ms("typecheck"))&&t.push(Ms("typecheck")),a&&!t.includes(Ms("lint"))&&t.push(Ms("lint")),[...new Set(t)].slice(0,4)}function sh(e){let t=process.env.NEX_LANGUAGE;if(t&&t!=="auto")return t;if(oh())return"English";let n=String(e||"").trim();if(!n)return"English";let s=n.replace(/```[\s\S]*?```/g," ").replace(/`[^`]*`/g," ").toLowerCase().match(/[a-zäöüß]+/gi)||[],r=new Set(["the","and","or","for","with","without","write","create","explain","refactor","query","function","makefile","dockerfile","healthcheck","preserve","return","input","output","using","should","must","please"]),i=new Set(["der","die","das","und","oder","ist","sind","nicht","bitte","erstelle","schreibe","erkl\xE4re","funktion","abfrage","datei","zur\xFCck","mit","ohne","danke"]),a=0,c=0;for(let u of s)r.has(u)&&a++,i.has(u)&&c++;return c>=3&&c>a*1.4?"German":"English"}function WL(e){let n=String(e||"").replace(/```[\s\S]*?```/g," ").replace(/`[^`]*`/g," ").toLowerCase().match(/[a-zäöüß]+/gi)||[];if(n.length===0)return"English";let o=new Set(["the","and","or","for","with","without","write","create","explain","refactor","query","function","makefile","dockerfile","healthcheck","preserve","return","input","output","using","should","must","please","this","that","it","is","are","as","in"]),s=new Set(["der","die","das","und","oder","ist","sind","nicht","bitte","ich","habe","wir","du","sie","es","diese","dieser","dass","wird","wurde","um","mit","ohne","danke"]),r=0,i=0;for(let a of n)o.has(a)&&r++,s.has(a)&&i++;return i>=3&&i>r*1.4?"German":"English"}function HL(e,t){if(typeof t!="string"||typeof e!="string")return!1;let n=e.toLowerCase(),o=t.toLowerCase(),s=/\b(bash|shell|sh)\b/.test(n)||/\b(one-?liner|pre-commit)\b/.test(n),r=/\b(dockerfile|makefile|cron|crontab|sql)\b/.test(n);if(!s&&!r&&(/```bash\b/.test(o)||/```sh\b/.test(o)))return!0;let i=t.replace(/```[\s\S]*?```/g," ").replace(/`[^`]*`/g," ").toLowerCase();return[/\b(let me|i(?:'|’)ll|i will)\s+(check|search|look)\b/,/\bfirst,\s*let me\b/,/\bsince i (?:do not|don’t|don't) see\b/,/\b(let me|i(?:'|’)ll|i will)\s+(?:run|execute)\b/,/\bsearch(?:ing)?\s+for\b/,/\bcheck if there(?: is| are)\b/].some(a=>a.test(i))}function tk(e){let t=String(e||"").trim();if(!t||t.length>2500)return!1;let n=t.toLowerCase();return/\b(?:repo|repository|project|codebase|existing|current workspace|this workspace)\b/.test(n)||/\b(?:create|write|save)\s+(?:a\s+)?file\b/.test(n)||/\b(?:read|search|inspect|look through|find in|run|install)\b/.test(n)?!1:[/\b(?:reply|respond|answer)\b.*\bexactly\b/i,/\b(?:sql\s+query|select\s+.+\s+from)\b/i,/\b(?:cron(?:\s+expression)?|crontab)\b/i,/\bregex\b.*\b(?:explain|refactor|rewrite|readable)\b/i,/\b(?:small|simple|minimal)?\s*makefile\b/i,/\b(?:small|simple|minimal)?\s*dockerfile\b/i,/\b(?:docker\s+healthcheck|healthcheck)\b/i,/\brefactor\b.*\bcallbacks?\b.*\basync\s*\/\s*await\b/i,/\bcallbacks?\b.*\basync\s*\/\s*await\b/i,/\btypescript\b.*\binterface\b/i,/\b(?:debug|fix)\b.*\bbash\b.*\bscript\b/i,/\bpre-commit\s+hook\b/i,/\bbash\s+one-?liner\b/i,/\bdataclass\b/i,/\bexpress\b.*\broute\b/i,/\beventemitter\b/i,/\b(?:javascript|js|python)\s+function\b/i,/\bfunction\s+\w+\s*\(/i].some(o=>o.test(t))}function GL(e){if(typeof e!="string")return null;let t=e.toLowerCase();return/\bsieve of eratosthenes\b/i.test(e)&&/\bprimes?\b/i.test(e)&&/\bup to n\b/i.test(e)?["```python","from __future__ import annotations","","from typing import List","","","def sieve_of_eratosthenes(n: int) -> List[int]:",' """Return all prime numbers <= n using the Sieve of Eratosthenes.',""," Args:"," n: Upper bound (inclusive).",""," Returns:"," A list of all primes p such that 2 <= p <= n, in ascending order.",' """'," if n < 2:"," return []",""," is_prime = [True] * (n + 1)"," is_prime[0] = False"," is_prime[1] = False",""," p = 2"," while p * p <= n:"," if is_prime[p]:"," for multiple in range(p * p, n + 1, p):"," is_prime[multiple] = False"," p += 1",""," return [i for i in range(2, n + 1) if is_prime[i]]","```"].join(`
1085
1085
  `):/for\s+f\s+in\s+\$\(\s*ls\s+\*\.txt\s*\)\s*;\s*do/i.test(e)&&/\bfilenames?\s+with\s+spaces\b/i.test(e)?["The problem is word splitting: `$(ls *.txt)` produces whitespace-separated output, so filenames with spaces get split into multiple loop items.","","Use a glob directly (no `ls`, no command substitution) and quote the variable:","","```bash","for f in *.txt; do",' echo "$f"',"done","```","","Why this works:","- `*.txt` is expanded by the shell into one word per matching filename (spaces are preserved as part of the word).",'- Quoting `"$f"` prevents a filename like `My File.txt` from being split again when echoed/used.'].join(`
1086
1086
  `):/\bexplain\b.*\bregex\b/i.test(e)&&/25\[0-5\]/.test(e)&&/2\[0-4\]/.test(e)&&/\[01\]\?/.test(e)&&/\)\\\.\)\{3\}/.test(e)?["This regex validates an IPv4 address in dotted-decimal form (e.g. `192.168.0.1`).","","What it does:","- It matches **four** numeric octets separated by literal dots (`.`).","- Each octet must be in the range **0\u2013255**:"," - `25[0-5]` \u2192 250\u2013255"," - `2[0-4][0-9]` \u2192 200\u2013249"," - `[01]?[0-9][0-9]?` \u2192 0\u2013199 (allows 1\u20133 digits, including leading zeros like `001`)","- `^` and `$` anchor the match to the entire string (no extra characters).","","A more readable rewrite (same logic), using a reusable `octet` subpattern:","","```js","const octet = '(?:25[0-5]|2[0-4]\\\\d|[01]?\\\\d\\\\d?)';","const ipv4Regex = new RegExp(`^(?:${octet}\\\\.){3}${octet}$`);","```"].join(`
1087
1087
  `):/\brefactor\b.*\bcallbacks?\b.*\basync\s*\/\s*await\b/i.test(e)&&/fs\.readFile\(\s*["']a\.txt["']/.test(e)&&/fs\.writeFile\(\s*["']b\.txt["']/.test(e)?["```js","const { readFile, writeFile } = require('fs/promises');","","(async () => {"," const data = await readFile('a.txt');"," await writeFile('b.txt', data);"," console.log('done');",""," // If you need a specific encoding, use: await readFile('a.txt', 'utf8')","})().catch((err) => {"," // Closest to `if (err) throw err;` from the callback version."," console.error(err);"," process.exitCode = 1;","});","```","","This keeps the same control flow, but uses `fs/promises` so the operations can be awaited instead of nested callbacks."].join(`
@@ -1607,7 +1607,7 @@ class ErrorBoundary extends React.Component {
1607
1607
  `,qp=e,_a}function nk(){th.clear(),G_.clear(),su.clear(),Aa.clear(),Y_.clear(),ou.clear(),Oa.clear(),Ls.clear(),to.clear(),Ma.clear(),Gt.clear(),gr.clear(),mu.clear(),Up.clear(),Zn=0,xa=0,ru=0,Ln=!1,au=0,ko=-1,Hp=!1,cu=0,lu=!1,es=0,jn=!1,ts=0,ns=0,Zt=!1,kn="",va=0,uu="",fr=0,du="",pr=0,ms=!1,Gp=!1,Pe="plan",gu=0,be=!1,gs=null,qa=null,Kp=null,no=[],li=0,pi=0,hi=0,vo=0,Ta=0,ui=0,Is=!1,js=0,So=0,fi=null,yr=null,et=!1,Sn=0,Fa=0,gn.clear(),Yt=!1,_u="",pu=!1,Ps=0,qn=0,Pa=0,yu=0,$u=0,mi.clear(),Na.clear(),ja.clear(),Da.clear(),Ve=null,In=!1,nh=null,Yp=!1,zp=!1,fu=!1,xo="",hr="",Ea="",Wp="",iu=0}function VL(){T=[],Sa=null,ai="",ci=0,Fp="",Bp=0,nk();try{let{resetCompactionFailures:e}=Mf();e()}catch{}try{let{cancelAllJobs:e}=Gr();e()}catch{}}function JL(){T.length>R_&&T.splice(0,T.length-R_)}function oh(){try{let e=require("fs"),n=require("path").join(process.cwd(),"AGENTS.md");if(!e.existsSync(n))return!1;let o=e.readFileSync(n,"utf8");return/all.*english/i.test(o)&&/no german/i.test(o)}catch{return!1}}function Np(e,t,n,o=1500){return!e||!t?!1:e===t&&Date.now()-n<o}function ZL(){return T.length}function QL(){return T}function eI(e){T=e}async function tI(){let{execFile:e}=require("child_process"),t=require("fs"),n=process.cwd(),o=(f,p)=>new Promise(h=>{e(f,p,{cwd:n,timeout:3e3},(m,g)=>{h(m?"":(g||"").trim())})}),[s]=await Promise.all([o("find",[".","-type","f","-not","-path","*/node_modules/*","-not","-path","*/.git/*","-not","-path","*/dist/*","-not","-path","*/.next/*","-not","-path","*/build/*","-not","-path","*/__pycache__/*","-not","-path","*/vendor/*"])]),r=new Set(["js","ts","jsx","tsx","py","go","rs","rb","java","cpp","c","cs"]),i=(s?s.split(`
1608
1608
  `):[]).filter(f=>{let p=f.split(".").pop();return r.has(p)});if(i.length<3)return null;let a={};for(let f of i){let p=f.split(".").pop();a[p]=(a[p]||0)+1}let u=` \u{1F4C1} ${Object.entries(a).sort((f,p)=>p[1]-f[1]).slice(0,4).map(([f,p])=>`${p} .${f}`).join(" \xB7 ")}`,d=ut.join(n,"package.json");if(t.existsSync(d))try{let f=JSON.parse(t.readFileSync(d,"utf-8")),p=Object.keys({...f.dependencies||{},...f.devDependencies||{}});if(p.length>0){let h=p.slice(0,5).join(" \xB7 "),m=p.length>5?` +${p.length-5}`:"";u+=`
1609
1609
  \u{1F4E6} ${h}${m}`}}catch{}return u}function nI(e){if(process.platform==="darwin")try{let{execFileSync:t}=require("child_process");t("osascript",["-e",`display notification "${e.replace(/"/g,'\\"')}" with title "nex-code"`],{timeout:3e3,stdio:"ignore"})}catch{}}function Ze(e,t,n,o,s,{suppressHint:r=!1}={}){if(e<1)return;let i=[...t.values()].reduce((u,d)=>u+d,0),a=`\u2500\u2500 ${e} ${e===1?"step":"steps"} \xB7 ${i} ${i===1?"tool":"tools"}`,c=0;if(s){let u=Date.now()-s;c=Math.round(u/1e3),a+=c>=60?` \xB7 ${Math.floor(c/60)}m ${c%60}s`:` \xB7 ${c}s`}n.size>0&&(a+=` \xB7 ${n.size} ${n.size===1?"file":"files"} modified`),a+=" \u2500\u2500",console.log(`
1610
- ${y.dim} ${a}${y.reset}`);try{let{getActiveProviderName:u,getActiveModelId:d}=ft(),f=u(),p=d(),h=typeof b_=="function"?b_(f).label:"cost unknown",m=typeof $_=="function"?$_():null;if(f&&p&&m){let g=m.totalCost>0?`$${m.totalCost.toFixed(4)}`:"free";console.log(`${y.dim} model ${f}:${p} \xB7 ${h} \xB7 ${m.totalInput.toLocaleString()} in / ${m.totalOutput.toLocaleString()} out \xB7 ${g}${y.reset}`)}}catch{}if(c>=30&&process.stdout.isTTY){let u=n.size>0?`Done \u2014 ${n.size} ${n.size===1?"file":"files"} modified in ${c}s`:`Done \u2014 ${e} ${e===1?"step":"steps"} in ${c}s`;nI(u)}if(Da.size>0&&ja.size>0)for(let u of Da){let d=ja.get(u);d&&console.log(`${y.dim} \u2714 task #${u} auto-matched: ${d.slice(0,60)}${y.reset}`)}n.size>0?console.log(`${y.dim} \u{1F4A1} /diff \xB7 /commit \xB7 /undo${y.reset}`):!r&&o.size>=5&&n.size===0&&e>=3?console.log(`${y.dim} \u{1F4A1} Found issues? Say "fix 1" or "apply all fixes"${y.reset}`):o.size>0&&e>=2&&console.log(`${y.dim} \u{1F4A1} /save \xB7 /clear${y.reset}`)}async function sI(){if(!process.stdout.isTTY)return{action:"quit"};let e=Qn(),t=Dn(),n=Ca.fast?.[e],o=Ca.strong?.[e],s=n&&n!==t,r=o&&o!==t&&o!==n,i=[];i.push({key:"r",label:`Retry with current model ${y.dim}(${t})${y.reset}`}),s&&i.push({key:"f",label:`Switch to ${y.bold}${n}${y.reset} ${y.dim}\u2014 fast, low latency${y.reset}`,model:n}),r&&i.push({key:"s",label:`Switch to ${y.bold}${o}${y.reset} ${y.dim}\u2014 reliable tool-calling, medium speed${y.reset}`,model:o}),i.push({key:"q",label:`${y.dim}Quit${y.reset}`}),console.log(),console.log(`${y.yellow} Stream stale \u2014 all retries exhausted.${y.reset} What would you like to do?`);for(let a of i)console.log(` ${y.cyan}[${a.key}]${y.reset} ${a.label}`);return process.stdout.write(` ${y.yellow}> ${y.reset}`),new Promise(a=>{let c=process.stdin,u=c.isRaw;c.setRawMode(!0),c.resume(),c.setEncoding("utf8");let d=!1,f=p=>{if(d)return;d=!0,c.removeListener("data",f),c.setRawMode(u||!1),c.pause();let h=p.toLowerCase().trim();if(process.stdout.write(`${h}
1610
+ ${$.dim} ${a}${$.reset}`);try{let{getActiveProviderName:u,getActiveModelId:d}=ft(),f=u(),p=d(),h=typeof b_=="function"?b_(f).label:"cost unknown",m=typeof $_=="function"?$_():null;if(f&&p&&m){let g=m.totalCost>0?`$${m.totalCost.toFixed(4)}`:"free";console.log(`${$.dim} model ${f}:${p} \xB7 ${h} \xB7 ${m.totalInput.toLocaleString()} in / ${m.totalOutput.toLocaleString()} out \xB7 ${g}${$.reset}`)}}catch{}if(c>=30&&process.stdout.isTTY){let u=n.size>0?`Done \u2014 ${n.size} ${n.size===1?"file":"files"} modified in ${c}s`:`Done \u2014 ${e} ${e===1?"step":"steps"} in ${c}s`;nI(u)}if(Da.size>0&&ja.size>0)for(let u of Da){let d=ja.get(u);d&&console.log(`${$.dim} \u2714 task #${u} auto-matched: ${d.slice(0,60)}${$.reset}`)}n.size>0?console.log(`${$.dim} \u{1F4A1} /diff \xB7 /commit \xB7 /undo${$.reset}`):!r&&o.size>=5&&n.size===0&&e>=3?console.log(`${$.dim} \u{1F4A1} Found issues? Say "fix 1" or "apply all fixes"${$.reset}`):o.size>0&&e>=2&&console.log(`${$.dim} \u{1F4A1} /save \xB7 /clear${$.reset}`)}async function sI(){if(!process.stdout.isTTY)return{action:"quit"};let e=Qn(),t=Dn(),n=Ca.fast?.[e],o=Ca.strong?.[e],s=n&&n!==t,r=o&&o!==t&&o!==n,i=[];i.push({key:"r",label:`Retry with current model ${$.dim}(${t})${$.reset}`}),s&&i.push({key:"f",label:`Switch to ${$.bold}${n}${$.reset} ${$.dim}\u2014 fast, low latency${$.reset}`,model:n}),r&&i.push({key:"s",label:`Switch to ${$.bold}${o}${$.reset} ${$.dim}\u2014 reliable tool-calling, medium speed${$.reset}`,model:o}),i.push({key:"q",label:`${$.dim}Quit${$.reset}`}),console.log(),console.log(`${$.yellow} Stream stale \u2014 all retries exhausted.${$.reset} What would you like to do?`);for(let a of i)console.log(` ${$.cyan}[${a.key}]${$.reset} ${a.label}`);return process.stdout.write(` ${$.yellow}> ${$.reset}`),new Promise(a=>{let c=process.stdin,u=c.isRaw;c.setRawMode(!0),c.resume(),c.setEncoding("utf8");let d=!1,f=p=>{if(d)return;d=!0,c.removeListener("data",f),c.setRawMode(u||!1),c.pause();let h=p.toLowerCase().trim();if(process.stdout.write(`${h}
1611
1611
  `),p==="")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:e})};c.on("data",f)})}function oI(e){let t=/https?:\/\/[^\s/]+(\/[^\s?#]+)/g,n=new Set,o;for(;(o=t.exec(e))!==null;){let s=o[1].replace(/\/$/,"");s.length>1&&s.split("/").filter(i=>i.length>2).forEach(i=>n.add(i))}return Array.from(n)}function rI(e){let t=[];return(e.includes("@click")||e.includes("x-data")||e.includes("v-if")||e.includes("v-model"))&&t.push("Snippet contains Vue/Alpine.js directives (e.g., @click, v-model). Do not restrict your search to just .js/.ts/.vue files; also search .html and .py (templates) if appropriate."),(e.includes("className=")||e.includes("useEffect"))&&t.push("Snippet appears to be React. Look in .jsx, .tsx, .js, .ts files."),t}var Ot=null,rh=!1;async function iI(e,t=null,n={}){let o=KN(Dn());E_=o.staleWarn,Ap=o.staleAbort,Ot=t,rh=!!n.silent;let s=e;Sa&&typeof e=="string"&&(s=`${Sa}
1612
1612
 
1613
1613
  ${e}`,Sa=null);let r=typeof s=="string"?EL(s):null;if(r){let he=null;try{he=ot.realpathSync(process.cwd())}catch{he=ut.resolve(process.cwd())}he!==r&&(process.chdir(r),nu())}if(typeof s=="string"){let he=oI(s),Ae=rI(s);(he.length>0||Ae.length>0)&&(s+=`
@@ -1617,13 +1617,13 @@ ${e}`,Sa=null);let r=typeof s=="string"?EL(s):null;if(r){let he=null;try{he=ot.r
1617
1617
  `),Ae.length>0&&Ae.forEach(Xe=>{s+=`- ${Xe}
1618
1618
  `}),s+="Always prefer parallel search execution if unsure.]")}typeof s=="string"&&B_(s)&&(s+=`
1619
1619
 
1620
- [Note for assistant: the user appears frustrated \u2014 acknowledge their concern briefly and empathetically before proceeding]`);let i=typeof e=="string"?h_(e):null,a=typeof e=="string"&&tk(e),c=typeof e=="string"?sh(e):"English",u=F_(s);if(u&&typeof u.then=="function"&&(u=await u),T.push({role:"user",content:u}),JL(),a){let he=GL(e);if(he){let Ae={role:"assistant",content:he};return T.push(Ae),Ce(T),wt(T),console.log(he),{success:!0,deterministic:!0,content:he}}}let d=mr(),f=n.autoOrchestrate!==!1&&process.env.NEX_AUTO_ORCHESTRATE!=="false"&&!d,p=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10),h=typeof u=="string"?u:typeof e=="string"?e:"";if(Ua(h)&&(zp=!0),ML(h)){In=!0;let he=ku(h);he&&(nh=he)}let $=In,b=zp;try{let{detectComplexPrompt:he,runOrchestrated:Ae}=ya(),Xe=he(typeof e=="string"?e:"");if(!f&&d&&Xe.isComplex&&console.log(`${y.dim}Plan mode active: auto-orchestrate disabled until /plan approve${y.reset}`),!b&&sk(f,Xe,p,d)){console.log(`${y.yellow}\u26A1 Auto-orchestrate: ${Xe.estimatedGoals} goals \u2192 parallel agents${y.reset}`);let Ue=await Ae(e,{orchestratorModel:n.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL,workerModel:n.model});if(Ue&&Ue.synthesis){let Ne=Ue.synthesis.summary||"",Hn=Ue.synthesis.filesChanged?.length?`
1620
+ [Note for assistant: the user appears frustrated \u2014 acknowledge their concern briefly and empathetically before proceeding]`);let i=typeof e=="string"?h_(e):null,a=typeof e=="string"&&tk(e),c=typeof e=="string"?sh(e):"English",u=F_(s);if(u&&typeof u.then=="function"&&(u=await u),T.push({role:"user",content:u}),JL(),a){let he=GL(e);if(he){let Ae={role:"assistant",content:he};return T.push(Ae),Ce(T),wt(T),console.log(he),{success:!0,deterministic:!0,content:he}}}let d=mr(),f=n.autoOrchestrate!==!1&&process.env.NEX_AUTO_ORCHESTRATE!=="false"&&!d,p=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10),h=typeof u=="string"?u:typeof e=="string"?e:"";if(Ua(h)&&(zp=!0),ML(h)){In=!0;let he=ku(h);he&&(nh=he)}let y=In,b=zp;try{let{detectComplexPrompt:he,runOrchestrated:Ae}=ya(),Xe=he(typeof e=="string"?e:"");if(!f&&d&&Xe.isComplex&&console.log(`${$.dim}Plan mode active: auto-orchestrate disabled until /plan approve${$.reset}`),!b&&sk(f,Xe,p,d)){console.log(`${$.yellow}\u26A1 Auto-orchestrate: ${Xe.estimatedGoals} goals \u2192 parallel agents${$.reset}`);let Ue=await Ae(e,{orchestratorModel:n.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL,workerModel:n.model});if(Ue&&Ue.synthesis){let Ne=Ue.synthesis.summary||"",Hn=Ue.synthesis.filesChanged?.length?`
1621
1621
 
1622
1622
  Files changed: ${Ue.synthesis.filesChanged.join(", ")}`:"",$t=Ue.synthesis.conflicts?.length?`
1623
1623
 
1624
1624
  Conflicts:
1625
1625
  ${Ue.synthesis.conflicts.map(At=>`- ${At}`).join(`
1626
- `)}`:"";T.push({role:"assistant",content:Ne+Hn+$t}),Ce(T),wt(T)}return Ue}Xe.isComplex&&process.stdout.isTTY&&console.log(`${y.dim}Hint: ~${Xe.estimatedGoals} goals detected. Disable with NEX_AUTO_ORCHESTRATE=false${y.reset}`)}catch{}let{setOnChange:x}=yl(),_=null,E=0;x((he,Ae)=>{he==="create"?(_&&_.stop(),_=new rN(Ae.name,Ae.tasks),_.setStats({tokens:E}),_.start()):he==="update"&&_?_.updateTask(Ae.id,Ae.status):he==="clear"&&_&&(_.stop(),_=null)});let S=await Qp(),O=S;try{let{getBrainContext:he}=Vi(),Ae=await he(e);Ae&&(O=S+`
1626
+ `)}`:"";T.push({role:"assistant",content:Ne+Hn+$t}),Ce(T),wt(T)}return Ue}Xe.isComplex&&process.stdout.isTTY&&console.log(`${$.dim}Hint: ~${Xe.estimatedGoals} goals detected. Disable with NEX_AUTO_ORCHESTRATE=false${$.reset}`)}catch{}let{setOnChange:x}=yl(),_=null,E=0;x((he,Ae)=>{he==="create"?(_&&_.stop(),_=new rN(Ae.name,Ae.tasks),_.setStats({tokens:E}),_.start()):he==="update"&&_?_.updateTask(Ae.id,Ae.status):he==="clear"&&_&&(_.stop(),_=null)});let S=await Qp(),O=S;try{let{getBrainContext:he}=Vi(),Ae=await he(e);Ae&&(O=S+`
1627
1627
  `+Ae+`
1628
1628
  `)}catch(he){process.env.NEX_DEBUG&&console.error("[agent] brain context failed:",he.message)}let I=HN(typeof e=="string"?e:"");if(I.length>0){let he=I.map(Ae=>`[Triggered: ${Ae.name}]
1629
1629
  ${Ae.instructions}`).join(`
@@ -1633,16 +1633,16 @@ ${Ae.instructions}`).join(`
1633
1633
  `+zL(e),a&&(O+=`
1634
1634
  # Current Turn Direct Answer Mode
1635
1635
  This request is self-contained. Answer directly with the requested content. Do not inspect the workspace, create files, run commands, install packages, or mention internal process unless the user explicitly asked for that.
1636
- `);let D=[{role:"system",content:O},...T];kp(Dn());let Z=new ri(_p());Z.start();let K=T.length===1,X=K&&!a?tI().catch(()=>null):Promise.resolve(null),Fe=K?EN(typeof e=="string"?e:"").catch(()=>null):Promise.resolve(null),Oe=a?[]:xn(),[{messages:V,compressed:re,compacted:rt,tokensRemoved:qe},_e,Me]=await Promise.all([dN(D,Oe),X,Fe]),R=hs(D,Oe);if(Z.stop(),_e&&console.log(`${y.dim}${_e}${y.reset}`),rt)console.log(`${y.dim} [context compacted \u2014 summary (~${qe} tokens freed)]${y.reset}`);else if(re){let he=R.limit>0?Math.round(qe/R.limit*100):0;j(`${y.dim} [context compressed \u2014 ~${qe} tokens freed (${he}%)]${y.reset}`)}R.percentage>85&&j(`${y.yellow} \u26A0 Context ${Math.round(R.percentage)}% used (${Math.round(100-R.percentage)}% remaining) \u2014 consider /clear or /save + start fresh${y.reset}`);let v=V;if(Me&&K&&(v=[v[0],{role:"user",content:`[Server probe at task start]
1636
+ `);let D=[{role:"system",content:O},...T];kp(Dn());let Z=new ri(_p());Z.start();let K=T.length===1,X=K&&!a?tI().catch(()=>null):Promise.resolve(null),Fe=K?EN(typeof e=="string"?e:"").catch(()=>null):Promise.resolve(null),Oe=a?[]:xn(),[{messages:V,compressed:re,compacted:rt,tokensRemoved:qe},ke,Me]=await Promise.all([dN(D,Oe),X,Fe]),R=hs(D,Oe);if(Z.stop(),ke&&console.log(`${$.dim}${ke}${$.reset}`),rt)console.log(`${$.dim} [context compacted \u2014 summary (~${qe} tokens freed)]${$.reset}`);else if(re){let he=R.limit>0?Math.round(qe/R.limit*100):0;j(`${$.dim} [context compressed \u2014 ~${qe} tokens freed (${he}%)]${$.reset}`)}R.percentage>85&&j(`${$.yellow} \u26A0 Context ${Math.round(R.percentage)}% used (${Math.round(100-R.percentage)}% remaining) \u2014 consider /clear or /save + start fresh${$.reset}`);let v=V;if(Me&&K&&(v=[v[0],{role:"user",content:`[Server probe at task start]
1637
1637
  ${Me}`},{role:"assistant",content:"Understood \u2014 I have the server context. Proceeding with the task."},...v.slice(1)]),i&&K){let he=i.shouldPreferSsh?`[Runtime URL detected]
1638
1638
  The user linked a live app URL (${i.url}) and described broken behavior. Treat this as a runtime/deployed-instance issue first. Reproduce it with browser_open or browser_screenshot on the URL before reading local files. Because this URL matches server profile "${i.matchedName}", prefer ssh_exec/service_logs on that server for investigation before local repo inspection.`:`[Runtime URL detected]
1639
1639
  The user linked a live app URL (${i.url}) and described broken behavior. Treat this as a runtime issue first. Reproduce it with browser_open or browser_screenshot before reading local files. Only inspect the local repo after you have confirmed the live behavior.`;v=[v[0],{role:"user",content:he},{role:"assistant",content:"Understood \u2014 I will inspect the live app/runtime first."},...v.slice(1)]}if(K&&!b){let he=TN(typeof e=="string"?e:"");he&&(v=[v[0],{role:"user",content:`[EXAMPLE \u2014 illustrative only, not the real task]
1640
1640
  `+he.user},{role:"assistant",content:he.assistant+`
1641
- [END EXAMPLE \u2014 wait for the real user request below]`},...v.slice(1)])}if(hs(v,Oe).percentage>=65){let{messages:Ae,tokensRemoved:Xe}=As(v,Oe);Xe>0&&(v=Ae,console.log(`${y.dim} [pre-flight compress \u2014 ${Xe} tokens freed, now ${Math.round(hs(v,Oe).percentage)}% used]${y.reset}`))}let z=0,ne=0,te=0,M=0,ye=0,Qe=9,G=0,ue=new Set,ve=(()=>{let he=T.find(Ae=>Ae.role==="user");return typeof he?.content=="string"?he.content:""})(),ke=typeof ve=="string"?h_(ve):null,ge=La(ve),ze=/set_reminder|google.?auth|cron:|api\.log|swarm.{0,30}(agent|crash|fail)|agent.{0,30}(crashed|crash|fail)|server.{0,30}(error|crash|problem)|on.server/i.test(ve)||!!ke?.shouldPreferSsh,it=!!ke,Be=0;if(!Zt){let he=T.filter(Xe=>Xe.role==="user"||Xe.role==="tool").map(Xe=>typeof Xe.content=="string"?Xe.content:"").join(`
1642
- `),Ae=Mp(he);Ae&&(Zt=!0,kn=Ae.slice(0,120),j(`${y.yellow} \u26A1 Root cause in briefing: ${kn} \u2014 fix phase active from start (read budget: 3)${y.reset}`))}!Zt&&!ms&&/\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(ve)&&(ms=!0,j(`${y.cyan} \u26A1 Creation task detected \u2014 tight investigation cap (4 pre-edit, 2 post-edit)${y.reset}`));let tt=h||ve;if(!n.skipPhaseRouting&&!IL(tt)&&(T.length<=1||b&&!be)&&(be=b?!0:wN(),be)){yr=bN(tt)?.id||"coding";let Ae=Xp(tt);if(Pe=Ae?"implement":"plan",gs=Lp(Pe,yr),gu=0,li=0,So=0,fi=null,et=Pe==="plan"&&z_(tt),Sn=0,Fa=0,gn.clear(),$r.clear(),Yt=!1,_u=et?tt:"",et)for(let Ue of La(tt))gn.add(sn(Ue));pu=!1,Ps=0,_o.clear(),process.stdout.isTTY&&console.log(Ae?`${y.dim} \u21B3 Phase routing: implement(${gs||"default"}) \u2192 verify ${y.yellow}[plan skipped: direct file task]${y.reset}`:`${y.dim} \u21B3 Phase routing: plan(${gs||"default"}) \u2192 implement \u2192 verify${y.reset}`),j(Ae?`${y.cyan} \u26A1 Phase routing enabled \u2014 skipping plan phase for direct file task, starting in implement with ${gs||"default model"} (category: ${yr})${y.reset}`:`${y.cyan} \u26A1 Phase routing enabled \u2014 plan phase with ${gs||"default model"} (category: ${yr})${y.reset}`);let Xe=La(tt);if(Ae&&Xe.length>0){let Ne={role:"user",content:`[SYSTEM] This is a direct file task targeting: ${Xe.slice(0,3).join(", ")}. Modify only the explicitly requested file(s) unless the user asks for more. Do NOT create extra helper or test files for verification. Prefer inline verification with bash or by reading the edited file.`};T.push(Ne),v.push(Ne)}if(et){let Ue={role:"user",content:Ns()};T.push(Ue),v.push(Ue)}}if(In){Ve=null;let he=await NL(h,v,T);if(!he.ok){let Ae=he.requiredBranch,Xe=he.branch?`Current branch: ${he.branch}. `:"",Ue=Ae?`Required branch: ${Ae}. `:"",Ne=he.dirty===!0?`Worktree is dirty (${he.changedFiles.length} changed file${he.changedFiles.length===1?"":"s"}). `:"",$t="[PRECHECK BLOCKED] This prompt contains explicit git/worktree safety gates. I ran `git status --short --branch` as preflight and will not proceed until it's safe.\n\n"+`${!he.raw||/^ERROR:/i.test(he.raw)||/^fatal:/i.test(he.raw)?"Git preflight failed (no usable status output). ":""}${Xe}${Ue}${Ne}`.trim()+`
1641
+ [END EXAMPLE \u2014 wait for the real user request below]`},...v.slice(1)])}if(hs(v,Oe).percentage>=65){let{messages:Ae,tokensRemoved:Xe}=As(v,Oe);Xe>0&&(v=Ae,console.log(`${$.dim} [pre-flight compress \u2014 ${Xe} tokens freed, now ${Math.round(hs(v,Oe).percentage)}% used]${$.reset}`))}let z=0,ne=0,te=0,M=0,ye=0,Qe=9,G=0,ue=new Set,ve=(()=>{let he=T.find(Ae=>Ae.role==="user");return typeof he?.content=="string"?he.content:""})(),xe=typeof ve=="string"?h_(ve):null,ge=La(ve),ze=/set_reminder|google.?auth|cron:|api\.log|swarm.{0,30}(agent|crash|fail)|agent.{0,30}(crashed|crash|fail)|server.{0,30}(error|crash|problem)|on.server/i.test(ve)||!!xe?.shouldPreferSsh,it=!!xe,Be=0;if(!Zt){let he=T.filter(Xe=>Xe.role==="user"||Xe.role==="tool").map(Xe=>typeof Xe.content=="string"?Xe.content:"").join(`
1642
+ `),Ae=Mp(he);Ae&&(Zt=!0,kn=Ae.slice(0,120),j(`${$.yellow} \u26A1 Root cause in briefing: ${kn} \u2014 fix phase active from start (read budget: 3)${$.reset}`))}!Zt&&!ms&&/\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(ve)&&(ms=!0,j(`${$.cyan} \u26A1 Creation task detected \u2014 tight investigation cap (4 pre-edit, 2 post-edit)${$.reset}`));let tt=h||ve;if(!n.skipPhaseRouting&&!IL(tt)&&(T.length<=1||b&&!be)&&(be=b?!0:wN(),be)){yr=bN(tt)?.id||"coding";let Ae=Xp(tt);if(Pe=Ae?"implement":"plan",gs=Lp(Pe,yr),gu=0,li=0,So=0,fi=null,et=Pe==="plan"&&z_(tt),Sn=0,Fa=0,gn.clear(),$r.clear(),Yt=!1,_u=et?tt:"",et)for(let Ue of La(tt))gn.add(sn(Ue));pu=!1,Ps=0,_o.clear(),process.stdout.isTTY&&console.log(Ae?`${$.dim} \u21B3 Phase routing: implement(${gs||"default"}) \u2192 verify ${$.yellow}[plan skipped: direct file task]${$.reset}`:`${$.dim} \u21B3 Phase routing: plan(${gs||"default"}) \u2192 implement \u2192 verify${$.reset}`),j(Ae?`${$.cyan} \u26A1 Phase routing enabled \u2014 skipping plan phase for direct file task, starting in implement with ${gs||"default model"} (category: ${yr})${$.reset}`:`${$.cyan} \u26A1 Phase routing enabled \u2014 plan phase with ${gs||"default model"} (category: ${yr})${$.reset}`);let Xe=La(tt);if(Ae&&Xe.length>0){let Ne={role:"user",content:`[SYSTEM] This is a direct file task targeting: ${Xe.slice(0,3).join(", ")}. Modify only the explicitly requested file(s) unless the user asks for more. Do NOT create extra helper or test files for verification. Prefer inline verification with bash or by reading the edited file.`};T.push(Ne),v.push(Ne)}if(et){let Ue={role:"user",content:Ns()};T.push(Ue),v.push(Ue)}}if(In){Ve=null;let he=await NL(h,v,T);if(!he.ok){let Ae=he.requiredBranch,Xe=he.branch?`Current branch: ${he.branch}. `:"",Ue=Ae?`Required branch: ${Ae}. `:"",Ne=he.dirty===!0?`Worktree is dirty (${he.changedFiles.length} changed file${he.changedFiles.length===1?"":"s"}). `:"",$t="[PRECHECK BLOCKED] This prompt contains explicit git/worktree safety gates. I ran `git status --short --branch` as preflight and will not proceed until it's safe.\n\n"+`${!he.raw||/^ERROR:/i.test(he.raw)||/^fatal:/i.test(he.raw)?"Git preflight failed (no usable status output). ":""}${Xe}${Ue}${Ne}`.trim()+`
1643
1643
 
1644
- Next step: make the worktree clean and be on the required branch, then re-run the automation.`,At={role:"assistant",content:$t};T.push(At),Ce(T),wt(T),console.log($t);return}if(!Yp){let Ae={role:"user",content:"[SYSTEM] This is a gated automation workflow. In your final summary, use these exact labels (one per line): Preflight:, Preflight output:, Branch:, Chosen task: (or Selected improvement: / no safe task found), Files changed:, Verification:, Commit:, Push:, Final git status:, Remaining risk:. If any field is unknown or not run, write that explicitly. Do not claim safety, verification, commit, push, or git status checks without evidence from tool output."};T.push(Ae),v.push(Ae),Yp=!0}}await LL(v,T);let de=0,yt=0,Ie=new Map,Y=new Set,je=new Set,ss=[],qs=[],ws=new Set,_s=0,sm=0,Gu=0,nt=0,Ke=Date.now(),iv=new cN(VN),Yu=()=>ss.length>0||qs.length>0,av=Ma,qt=n.skillLoop?10:1,cv=3*qt,lv=5*qt,om=th,uv=5*qt,dv=8*qt,fv=G_,pv=(be?6:4)*qt,hv=(be?10:7)*qt,zu=su,mv=(be?5:3)*qt,ic=(be?8:5)*qt,gv=Y_,yv=(be?4:3)*qt,$v=(be?6:4)*qt,bv=3*qt,wv=4*qt,xr=Ls,_v=(be?6:4)*qt,kv=(be?10:8)*qt,vr=(be?12:10)*qt,xv=25,Mo=0,vv=10*qt,Sv=15*qt,Po=0,ac=5*qt,Sr=()=>et&&be&&Pe==="implement"&&Y.size===0&&nt===0&&Gt.size===0&&qn>0,No=0,Ev=2*qt,Tv=3,cc=!1,Ku=0,lc=!1,rm=0,Xu=0,Si=10,Rv=16,im=n.skillLoop?999:o.investigationCap,uc=async()=>{let{hasPendingOrCompletedJobs:he,getPendingJobSummary:Ae}=Gr();if(he()){if(Ae()){let Xe=Date.now()+45e3;for(process.stderr.write(`${y.cyan} \u23F3 Waiting for background agents to finish\u2026${y.reset}
1645
- `);Ae()&&Date.now()<Xe;)await new Promise(Ue=>setTimeout(Ue,500).unref()),Zl(T,v)}Zl(T,v),T.length>0&&Ce(T)}},ao=typeof e=="string"?e.trim():"",am=ao.length>0&&/^\s*(analyze|analyse|explain|describe|review|audit|summari[sz]e|list|understand|document|documentation|docs|what is|what does|how does|show me|show the|show all|tell me about)/i.test(ao)&&!/\b(fix|bug|crash|error|implement|add|create|change|update|refactor|rewrite|broken|fail|patch|migrate|port|build|edit|write|delete|remove|install|setup|deploy|run)\b/i.test(ao),dc=ao.length>0&&/\b(analyze|analyse|explain|describe|review|audit|summari[sz]e|understand|document|scan|count|inventory|map|list|identify)\b/i.test(ao)&&/\b(create|write|generate|produce|output)\b/i.test(ao)&&/\b([A-Z0-9_-]+\.md|markdown|report|summary|overview|architecture|audit|table|documentation|docs|inventory|catalog)\b/i.test(ao)&&!/\b(fix|bug|crash|error|implement|add(?!\s+(?:to|into)\b)|change|update|refactor|rewrite|broken|fail|patch|migrate|port|build|delete|remove|install|setup|deploy|run)\b/i.test(ao),Ct,cn=n.maxIterations||(be?bo(Pe):Ql);am&&(cn=Math.min(cn,4),j(`${y.dim} \u21B3 Analysis-only prompt detected \u2014 iter cap=${cn}${y.reset}`));let Vu=0,cm=3,fc=!1,pc=0,Ju=!1;e:for(;;){for(fc=!1,Ct=0;Ct<cn&&!eu()?.aborted;Ct++){Zl(T,v);{let k=xn(),w=hs(v,k),W=de===0?65:78;if(w.percentage>=W){if(Y.size>0||be&&Pe!=="plan"){let $e=pN(T,{filesModified:Y,currentPhase:be?Pe:null});if($e){let ce=v.findIndex(P=>P._progressSnapshot);ce!==-1&&v.splice(ce,1);let F=v.findIndex(P=>P.role==="system");v.splice(F+1,0,$e)}}let{messages:H,tokensRemoved:oe}=As(v,k,de===0);if(oe>0&&(v=H,oe>50&&console.log(`${y.dim} [auto-compressed \u2014 ~${oe} tokens freed, now ${Math.round(hs(v,k).percentage)}%]${y.reset}`),ms&&Y.size>=3)){let $e=[...Y].map(F=>F.split("/").pop()).slice(0,10).join(", "),ce={role:"user",content:`[FRAMEWORK \u2014 context compressed] Task is IN PROGRESS. Already created ${Y.size} files: ${$e}. DO NOT restart or re-investigate what was already done. Continue from where you left off.`};v.push(ce)}}}if(Ln&&!Zt&&va<2){va++;let k={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."};v.push(k),T.push(k),j(`${y.yellow} \u26A0 Pre-call SSH-blocked nudge #${va} injected \u2014 model told to synthesize${y.reset}`)}Ln||(va=0);let Ae=!0;de>0&&IN();let Xe=null;if(_&&_.isActive())_._paused&&_.resume();else if(!_){let k,w=jN();if(w&&w.total>1){let oe=w.description.length>40?w.description.slice(0,37)+"\u2026":w.description;k=`Plan step ${w.current}/${w.total}: ${oe}`}else k=de>0?`${_p()} (step ${de+1})`:_p();let{getPendingJobSummary:W}=Gr(),H=W();H&&(k+=` [${H}]`),Xe=new ri(k),Xe.start()}let Ue=!0,Ne="",Hn=!1,$t=new DN,At,Lo=Date.now(),hc=!1,lm=!1,Ei=new AbortController,Zu=setInterval(async()=>{let k=Date.now()-Lo;if(k>=Ap&&!lm){lm=!0,$t._clearCursorLine();let w=Ca.fast?.[Qn()];if(w&&w!==Dn()&&T_){j(`${y.green} \u{1F504} Stream stale for ${Math.round(k/1e3)}s \u2014 auto-switching to ${w}${y.reset}`);try{let{setActiveModel:W}=Go();W(w),kp(w),Ei.abort()}catch(W){j(`${y.red} \u26A0 Model switch failed: ${W.message}${y.reset}`),Ei.abort()}}else j(`${y.yellow} \u26A0 Stream stale for ${Math.round(k/1e3)}s \u2014 aborting and retrying${y.reset}`),Ei.abort()}else if(k>=E_&&!hc){hc=!0,$t._clearCursorLine();let w=Ca.fast?.[Qn()],W=Math.round((Ap-k)/1e3);j(`${y.yellow} \u26A0 No tokens received for ${Math.round(k/1e3)}s \u2014 waiting...${y.reset}`),w&&w!==Dn()?console.log(`${y.dim} \u{1F4A1} Will auto-switch to ${w} in ~${W}s if no tokens arrive${y.reset}`):console.log(`${y.dim} \u{1F4A1} Ctrl+C to abort \xB7 auto-abort in ~${W}s${y.reset}`)}},5e3);Zu.unref?.();let Gn="",ks=null;try{let k=a?[]:U_(xn()),w=new Set(["read_file","list_directory","search_files","glob","grep","git_status","git_diff","git_log","git_show","ssh_exec"]),W=new Set(["read_file","list_directory","glob","grep","bash","git_status","git_diff","git_log","ssh_exec"]),H;cc?H=[]:mr()?H=k.filter(ce=>I_.has(ce.function.name)):be&&Pe==="plan"?(H=k.filter(ce=>w.has(ce.function.name)),et&&(Yt||Sn>=di)&&(H=[])):be&&Pe==="verify"?H=k.filter(ce=>W.has(ce.function.name)):H=k;let oe=eu(),$e=new AbortController;if(oe&&oe.addEventListener("abort",()=>$e.abort(),{once:!0}),Ei.signal.addEventListener("abort",()=>$e.abort(),{once:!0}),At=await Yl(v,H,{signal:$e.signal,...gs?{model:gs}:{},onThinkingToken:()=>{Lo=Date.now(),hc=!1,Ot?.onThinkingToken&&Ot.onThinkingToken()},onToken:ce=>{if(Lo=Date.now(),hc=!1,Ot?.onToken){Ot.onToken(ce),Ne+=ce;return}if(Ne+=ce,!Hn&&Ne.length>400&&Ne.length%250<ce.length+1){let F=Dp(Ne,3);F.truncated&&(Hn=!0,$t._clearCursorLine?.(),j(`${y.yellow} \u26A0 LLM stream loop detected (${F.repeatCount}\xD7 repeated) \u2014 suppressing display${y.reset}`))}Hn||(Gn+=ce,process.stdout.isTTY?ks||(ks=setTimeout(()=>{Gn&&$t&&$t.push(Gn),Gn="",ks=null},50),ks.unref?.()):($t.push(Gn),Gn=""),Ue&&(_&&!_._paused?_.pause():Xe&&Xe.stop(),Ae||(Ae=!0),$t.startCursor(),Ue=!1))}}),!At||typeof At!="object")throw new Error("Provider returned an empty response (no content/tool_calls)")}catch(k){if(clearInterval(Zu),ks&&(clearTimeout(ks),ks=null),Gn&&$t&&($t.push(Gn),Gn=""),_&&!_._paused&&_.pause(),Xe&&Xe.stop(),$t.stopCursor(),Ei.signal.aborted&&!eu()?.aborted){if(te++,te>Cp){if(M<1){M++,si("Stale retries exhausted \u2014 last-resort force-compress...",y.yellow);let P=xn(),{messages:q,tokensRemoved:N}=As(v,P);v=q,N>50&&j(`${y.dim} [force-compressed \u2014 ~${N} tokens freed]${y.reset}`),te=0,Ct--;continue}_&&(_.stop(),_=null);let F=await sI();if(F.action==="quit"){x(null),Ze(de,Ie,Y,je,Ke),Ce(T);break}F.action==="switch"&&(Kl(`${F.provider}:${F.model}`),console.log(`${y.green} \u2713 Switched to ${F.provider}:${F.model}${y.reset}`)),te=0,Ct--;continue}let $e=te===1?3e3:5e3;if(te>=1&&G<1){G++,si(`Stale retry ${te}/${Cp} \u2014 force-compressing before retry...`,y.yellow);let F=xn(),{messages:P,tokensRemoved:q}=As(v,F,!0);if(v=P,q>0&&q>50&&j(`${y.dim} [force-compressed \u2014 ~${q} tokens freed]${y.reset}`),T_){let N=Ca.fast?.[Qn()];N&&N!==Dn()&&(Kl(`${Qn()}:${N}`),console.log(`${y.cyan} \u26A1 Auto-switched to ${N} to avoid further stale timeouts${y.reset}`),console.log(`${y.dim} (disable with NEX_STALE_AUTO_SWITCH=0)${y.reset}`))}}else j(`${y.yellow} \u26A0 Stale retry ${te}/${Cp} \u2014 retrying in ${$e/1e3}s...${y.reset}`);let ce=new ri(`Waiting ${$e/1e3}s before retry...`);ce.start(),await new Promise(F=>setTimeout(F,$e)),ce.stop(),Ct--;continue}if(k.name==="AbortError"||k.name==="CanceledError"||k.message?.includes("canceled")||k.message?.includes("aborted")){_&&(_.stop(),_=null),x(null),Ze(de,Ie,Y,je,Ke),Ce(T);break}let w=k.message.includes("Provider returned an empty response"),W=k.message;if(k.code==="ECONNREFUSED"||k.message.includes("ECONNREFUSED"))W="Connection refused \u2014 please check your internet connection or API endpoint";else if(k.code==="ENOTFOUND"||k.message.includes("ENOTFOUND"))W="Network error \u2014 could not reach the API server. Please check your connection";else if(k.code==="ETIMEDOUT"||k.message.includes("timeout"))W="Request timed out \u2014 the API server took too long to respond. Please try again";else if(k.message.includes("401")||k.message.includes("Unauthorized"))W="Authentication failed \u2014 please check your API key in the .env file";else if(k.message.includes("403")||k.message.includes("Forbidden"))W="Access denied \u2014 your API key may not have permission for this model";else if(k.message.includes("404")){let $e=Dn?Dn():"unknown",ce=q=>q.includes(":")&&q.split(":")[0].match(/^[a-z]+$/)&&!q.split(":")[1].includes(":")?q.split(":").slice(1).join(":"):q;ue.add(ce($e));let P=(()=>{let q=[];process.env.NEX_FALLBACK_MODEL&&q.push(process.env.NEX_FALLBACK_MODEL);try{let{getModelForCategory:N}=fs(),U=["agentic","coding","plan","verify","sysadmin","data","frontend"];for(let se of U){let Se=N(se);Se&&!q.includes(Se)&&q.push(Se)}}catch{}return q.filter(N=>!ue.has(ce(N)))})()[0];if(P){console.log(`${y.yellow} \u26A0 Model ${$e} unavailable (404) \u2014 switching to ${P}${y.reset}`),Kl(P),kp(P),Ct--;continue}W=`Model not found (404): ${$e} \u2014 no fallback available. Set NEX_FALLBACK_MODEL or run /models to list available models`,console.log(`${y.red} \u2717 ${W}${y.reset}`),_&&(_.stop(),_=null),x(null),Ze(de,Ie,Y,je,Ke),Ce(T);break}else if(k.message.includes("400")){if(M<3&&ye<Qe){M++,ye++;let $e=de===0&&M===1,ce=$e||M===3||G>0;if($e){M=3;let N=k.message.replace(/^API Error(\s*\[HTTP \d+\])?:\s*/i,"").slice(0,150);si(`Bad request (400) \u2014 ${N||"system prompt too large"}, compressing...`,y.yellow)}else si(ce?`Bad request (400) \u2014 nuclear compression (attempt ${M}/3, dropping history)...`:`Bad request (400) \u2014 force-compressing and retrying... (attempt ${M}/3)`,y.yellow);let F=xn(),{messages:P,tokensRemoved:q}=As(v,F,ce);v=P,q>50&&j(`${y.dim} [force-compressed \u2014 ~${q} tokens freed]${y.reset}`),Ct--;continue}{let $e=v.find(U=>U.role==="system"),ce=v.find(U=>U.role==="user"&&!String(U.content).startsWith("[SYSTEM")&&!String(U.content).startsWith("BLOCKED:")),F=[$e,ce].filter(Boolean),{getUsage:P}=Mn(),q=Mn().estimateMessagesTokens(F),N=Mn().estimateMessagesTokens(v);if(q<N){let U=[],se=T.filter(B=>B.role==="assistant"&&typeof B.content=="string"&&B.content.trim().length>30).slice(-5).map(B=>B.content.trim().slice(0,300).replace(/\n+/g," "));se.length>0&&U.push(`Key findings:
1644
+ Next step: make the worktree clean and be on the required branch, then re-run the automation.`,At={role:"assistant",content:$t};T.push(At),Ce(T),wt(T),console.log($t);return}if(!Yp){let Ae={role:"user",content:"[SYSTEM] This is a gated automation workflow. In your final summary, use these exact labels (one per line): Preflight:, Preflight output:, Branch:, Chosen task: (or Selected improvement: / no safe task found), Files changed:, Verification:, Commit:, Push:, Final git status:, Remaining risk:. If any field is unknown or not run, write that explicitly. Do not claim safety, verification, commit, push, or git status checks without evidence from tool output."};T.push(Ae),v.push(Ae),Yp=!0}}await LL(v,T);let de=0,yt=0,Ie=new Map,Y=new Set,je=new Set,ss=[],qs=[],ws=new Set,_s=0,sm=0,Gu=0,nt=0,Ke=Date.now(),iv=new cN(VN),Yu=()=>ss.length>0||qs.length>0,av=Ma,qt=n.skillLoop?10:1,cv=3*qt,lv=5*qt,om=th,uv=5*qt,dv=8*qt,fv=G_,pv=(be?6:4)*qt,hv=(be?10:7)*qt,zu=su,mv=(be?5:3)*qt,ic=(be?8:5)*qt,gv=Y_,yv=(be?4:3)*qt,$v=(be?6:4)*qt,bv=3*qt,wv=4*qt,xr=Ls,_v=(be?6:4)*qt,kv=(be?10:8)*qt,vr=(be?12:10)*qt,xv=25,Mo=0,vv=10*qt,Sv=15*qt,Po=0,ac=5*qt,Sr=()=>et&&be&&Pe==="implement"&&Y.size===0&&nt===0&&Gt.size===0&&qn>0,No=0,Ev=2*qt,Tv=3,cc=!1,Ku=0,lc=!1,rm=0,Xu=0,Si=10,Rv=16,im=n.skillLoop?999:o.investigationCap,uc=async()=>{let{hasPendingOrCompletedJobs:he,getPendingJobSummary:Ae}=Gr();if(he()){if(Ae()){let Xe=Date.now()+45e3;for(process.stderr.write(`${$.cyan} \u23F3 Waiting for background agents to finish\u2026${$.reset}
1645
+ `);Ae()&&Date.now()<Xe;)await new Promise(Ue=>setTimeout(Ue,500).unref()),Zl(T,v)}Zl(T,v),T.length>0&&Ce(T)}},ao=typeof e=="string"?e.trim():"",am=ao.length>0&&/^\s*(analyze|analyse|explain|describe|review|audit|summari[sz]e|list|understand|document|documentation|docs|what is|what does|how does|show me|show the|show all|tell me about)/i.test(ao)&&!/\b(fix|bug|crash|error|implement|add|create|change|update|refactor|rewrite|broken|fail|patch|migrate|port|build|edit|write|delete|remove|install|setup|deploy|run)\b/i.test(ao),dc=ao.length>0&&/\b(analyze|analyse|explain|describe|review|audit|summari[sz]e|understand|document|scan|count|inventory|map|list|identify)\b/i.test(ao)&&/\b(create|write|generate|produce|output)\b/i.test(ao)&&/\b([A-Z0-9_-]+\.md|markdown|report|summary|overview|architecture|audit|table|documentation|docs|inventory|catalog)\b/i.test(ao)&&!/\b(fix|bug|crash|error|implement|add(?!\s+(?:to|into)\b)|change|update|refactor|rewrite|broken|fail|patch|migrate|port|build|delete|remove|install|setup|deploy|run)\b/i.test(ao),Ct,cn=n.maxIterations||(be?bo(Pe):Ql);am&&(cn=Math.min(cn,4),j(`${$.dim} \u21B3 Analysis-only prompt detected \u2014 iter cap=${cn}${$.reset}`));let Vu=0,cm=3,fc=!1,pc=0,Ju=!1;e:for(;;){for(fc=!1,Ct=0;Ct<cn&&!eu()?.aborted;Ct++){Zl(T,v);{let k=xn(),w=hs(v,k),W=de===0?65:78;if(w.percentage>=W){if(Y.size>0||be&&Pe!=="plan"){let $e=pN(T,{filesModified:Y,currentPhase:be?Pe:null});if($e){let ce=v.findIndex(P=>P._progressSnapshot);ce!==-1&&v.splice(ce,1);let F=v.findIndex(P=>P.role==="system");v.splice(F+1,0,$e)}}let{messages:H,tokensRemoved:oe}=As(v,k,de===0);if(oe>0&&(v=H,oe>50&&console.log(`${$.dim} [auto-compressed \u2014 ~${oe} tokens freed, now ${Math.round(hs(v,k).percentage)}%]${$.reset}`),ms&&Y.size>=3)){let $e=[...Y].map(F=>F.split("/").pop()).slice(0,10).join(", "),ce={role:"user",content:`[FRAMEWORK \u2014 context compressed] Task is IN PROGRESS. Already created ${Y.size} files: ${$e}. DO NOT restart or re-investigate what was already done. Continue from where you left off.`};v.push(ce)}}}if(Ln&&!Zt&&va<2){va++;let k={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."};v.push(k),T.push(k),j(`${$.yellow} \u26A0 Pre-call SSH-blocked nudge #${va} injected \u2014 model told to synthesize${$.reset}`)}Ln||(va=0);let Ae=!0;de>0&&IN();let Xe=null;if(_&&_.isActive())_._paused&&_.resume();else if(!_){let k,w=jN();if(w&&w.total>1){let oe=w.description.length>40?w.description.slice(0,37)+"\u2026":w.description;k=`Plan step ${w.current}/${w.total}: ${oe}`}else k=de>0?`${_p()} (step ${de+1})`:_p();let{getPendingJobSummary:W}=Gr(),H=W();H&&(k+=` [${H}]`),Xe=new ri(k),Xe.start()}let Ue=!0,Ne="",Hn=!1,$t=new DN,At,Lo=Date.now(),hc=!1,lm=!1,Ei=new AbortController,Zu=setInterval(async()=>{let k=Date.now()-Lo;if(k>=Ap&&!lm){lm=!0,$t._clearCursorLine();let w=Ca.fast?.[Qn()];if(w&&w!==Dn()&&T_){j(`${$.green} \u{1F504} Stream stale for ${Math.round(k/1e3)}s \u2014 auto-switching to ${w}${$.reset}`);try{let{setActiveModel:W}=Go();W(w),kp(w),Ei.abort()}catch(W){j(`${$.red} \u26A0 Model switch failed: ${W.message}${$.reset}`),Ei.abort()}}else j(`${$.yellow} \u26A0 Stream stale for ${Math.round(k/1e3)}s \u2014 aborting and retrying${$.reset}`),Ei.abort()}else if(k>=E_&&!hc){hc=!0,$t._clearCursorLine();let w=Ca.fast?.[Qn()],W=Math.round((Ap-k)/1e3);j(`${$.yellow} \u26A0 No tokens received for ${Math.round(k/1e3)}s \u2014 waiting...${$.reset}`),w&&w!==Dn()?console.log(`${$.dim} \u{1F4A1} Will auto-switch to ${w} in ~${W}s if no tokens arrive${$.reset}`):console.log(`${$.dim} \u{1F4A1} Ctrl+C to abort \xB7 auto-abort in ~${W}s${$.reset}`)}},5e3);Zu.unref?.();let Gn="",ks=null;try{let k=a?[]:U_(xn()),w=new Set(["read_file","list_directory","search_files","glob","grep","git_status","git_diff","git_log","git_show","ssh_exec"]),W=new Set(["read_file","list_directory","glob","grep","bash","git_status","git_diff","git_log","ssh_exec"]),H;cc?H=[]:mr()?H=k.filter(ce=>I_.has(ce.function.name)):be&&Pe==="plan"?(H=k.filter(ce=>w.has(ce.function.name)),et&&(Yt||Sn>=di)&&(H=[])):be&&Pe==="verify"?H=k.filter(ce=>W.has(ce.function.name)):H=k;let oe=eu(),$e=new AbortController;if(oe&&oe.addEventListener("abort",()=>$e.abort(),{once:!0}),Ei.signal.addEventListener("abort",()=>$e.abort(),{once:!0}),At=await Yl(v,H,{signal:$e.signal,...gs?{model:gs}:{},onThinkingToken:()=>{Lo=Date.now(),hc=!1,Ot?.onThinkingToken&&Ot.onThinkingToken()},onToken:ce=>{if(Lo=Date.now(),hc=!1,Ot?.onToken){Ot.onToken(ce),Ne+=ce;return}if(Ne+=ce,!Hn&&Ne.length>400&&Ne.length%250<ce.length+1){let F=Dp(Ne,3);F.truncated&&(Hn=!0,$t._clearCursorLine?.(),j(`${$.yellow} \u26A0 LLM stream loop detected (${F.repeatCount}\xD7 repeated) \u2014 suppressing display${$.reset}`))}Hn||(Gn+=ce,process.stdout.isTTY?ks||(ks=setTimeout(()=>{Gn&&$t&&$t.push(Gn),Gn="",ks=null},50),ks.unref?.()):($t.push(Gn),Gn=""),Ue&&(_&&!_._paused?_.pause():Xe&&Xe.stop(),Ae||(Ae=!0),$t.startCursor(),Ue=!1))}}),!At||typeof At!="object")throw new Error("Provider returned an empty response (no content/tool_calls)")}catch(k){if(clearInterval(Zu),ks&&(clearTimeout(ks),ks=null),Gn&&$t&&($t.push(Gn),Gn=""),_&&!_._paused&&_.pause(),Xe&&Xe.stop(),$t.stopCursor(),Ei.signal.aborted&&!eu()?.aborted){if(te++,te>Cp){if(M<1){M++,si("Stale retries exhausted \u2014 last-resort force-compress...",$.yellow);let P=xn(),{messages:q,tokensRemoved:N}=As(v,P);v=q,N>50&&j(`${$.dim} [force-compressed \u2014 ~${N} tokens freed]${$.reset}`),te=0,Ct--;continue}_&&(_.stop(),_=null);let F=await sI();if(F.action==="quit"){x(null),Ze(de,Ie,Y,je,Ke),Ce(T);break}F.action==="switch"&&(Kl(`${F.provider}:${F.model}`),console.log(`${$.green} \u2713 Switched to ${F.provider}:${F.model}${$.reset}`)),te=0,Ct--;continue}let $e=te===1?3e3:5e3;if(te>=1&&G<1){G++,si(`Stale retry ${te}/${Cp} \u2014 force-compressing before retry...`,$.yellow);let F=xn(),{messages:P,tokensRemoved:q}=As(v,F,!0);if(v=P,q>0&&q>50&&j(`${$.dim} [force-compressed \u2014 ~${q} tokens freed]${$.reset}`),T_){let N=Ca.fast?.[Qn()];N&&N!==Dn()&&(Kl(`${Qn()}:${N}`),console.log(`${$.cyan} \u26A1 Auto-switched to ${N} to avoid further stale timeouts${$.reset}`),console.log(`${$.dim} (disable with NEX_STALE_AUTO_SWITCH=0)${$.reset}`))}}else j(`${$.yellow} \u26A0 Stale retry ${te}/${Cp} \u2014 retrying in ${$e/1e3}s...${$.reset}`);let ce=new ri(`Waiting ${$e/1e3}s before retry...`);ce.start(),await new Promise(F=>setTimeout(F,$e)),ce.stop(),Ct--;continue}if(k.name==="AbortError"||k.name==="CanceledError"||k.message?.includes("canceled")||k.message?.includes("aborted")){_&&(_.stop(),_=null),x(null),Ze(de,Ie,Y,je,Ke),Ce(T);break}let w=k.message.includes("Provider returned an empty response"),W=k.message;if(k.code==="ECONNREFUSED"||k.message.includes("ECONNREFUSED"))W="Connection refused \u2014 please check your internet connection or API endpoint";else if(k.code==="ENOTFOUND"||k.message.includes("ENOTFOUND"))W="Network error \u2014 could not reach the API server. Please check your connection";else if(k.code==="ETIMEDOUT"||k.message.includes("timeout"))W="Request timed out \u2014 the API server took too long to respond. Please try again";else if(k.message.includes("401")||k.message.includes("Unauthorized"))W="Authentication failed \u2014 please check your API key in the .env file";else if(k.message.includes("403")||k.message.includes("Forbidden"))W="Access denied \u2014 your API key may not have permission for this model";else if(k.message.includes("404")){let $e=Dn?Dn():"unknown",ce=q=>q.includes(":")&&q.split(":")[0].match(/^[a-z]+$/)&&!q.split(":")[1].includes(":")?q.split(":").slice(1).join(":"):q;ue.add(ce($e));let P=(()=>{let q=[];process.env.NEX_FALLBACK_MODEL&&q.push(process.env.NEX_FALLBACK_MODEL);try{let{getModelForCategory:N}=fs(),U=["agentic","coding","plan","verify","sysadmin","data","frontend"];for(let se of U){let Se=N(se);Se&&!q.includes(Se)&&q.push(Se)}}catch{}return q.filter(N=>!ue.has(ce(N)))})()[0];if(P){console.log(`${$.yellow} \u26A0 Model ${$e} unavailable (404) \u2014 switching to ${P}${$.reset}`),Kl(P),kp(P),Ct--;continue}W=`Model not found (404): ${$e} \u2014 no fallback available. Set NEX_FALLBACK_MODEL or run /models to list available models`,console.log(`${$.red} \u2717 ${W}${$.reset}`),_&&(_.stop(),_=null),x(null),Ze(de,Ie,Y,je,Ke),Ce(T);break}else if(k.message.includes("400")){if(M<3&&ye<Qe){M++,ye++;let $e=de===0&&M===1,ce=$e||M===3||G>0;if($e){M=3;let N=k.message.replace(/^API Error(\s*\[HTTP \d+\])?:\s*/i,"").slice(0,150);si(`Bad request (400) \u2014 ${N||"system prompt too large"}, compressing...`,$.yellow)}else si(ce?`Bad request (400) \u2014 nuclear compression (attempt ${M}/3, dropping history)...`:`Bad request (400) \u2014 force-compressing and retrying... (attempt ${M}/3)`,$.yellow);let F=xn(),{messages:P,tokensRemoved:q}=As(v,F,ce);v=P,q>50&&j(`${$.dim} [force-compressed \u2014 ~${q} tokens freed]${$.reset}`),Ct--;continue}{let $e=v.find(U=>U.role==="system"),ce=v.find(U=>U.role==="user"&&!String(U.content).startsWith("[SYSTEM")&&!String(U.content).startsWith("BLOCKED:")),F=[$e,ce].filter(Boolean),{getUsage:P}=Mn(),q=Mn().estimateMessagesTokens(F),N=Mn().estimateMessagesTokens(v);if(q<N){let U=[],se=T.filter(B=>B.role==="assistant"&&typeof B.content=="string"&&B.content.trim().length>30).slice(-5).map(B=>B.content.trim().slice(0,300).replace(/\n+/g," "));se.length>0&&U.push(`Key findings:
1646
1646
  `+se.map(B=>`- ${B}`).join(`
1647
1647
  `));let Se=T.filter(B=>B.role==="tool"&&typeof B.content=="string"&&!B.content.startsWith("BLOCKED:")&&B.content.trim().length>10).slice(-5).map(B=>B.content.trim().split(`
1648
1648
  `).slice(0,8).join(`
@@ -1653,17 +1653,17 @@ ${JSON.stringify(Cn,null,2)}`)}if(U.length>0){let B={role:"user",content:`[SYSTE
1653
1653
  ${U.join(`
1654
1654
  `)}
1655
1655
  Continue implementing the fixes based on these findings.`};F.push(B)}if(xa>=3){let B=Y.size>0?`
1656
- Files modified so far: ${[...Y].map(we=>we.split("/").slice(-1)[0]).join(", ")}`:"";j(`${y.red} \u2717 Super-nuclear limit reached (3\xD7) \u2014 aborting to prevent runaway context loop${y.reset}`),console.log(`${y.yellow} \u{1F4A1} Task may exceed model context. Try /clear and break it into smaller steps.${B?y.dim+B:""}${y.reset}`),_&&(_.stop(),_=null),x(null),Ze(de,Ie,Y,je,Ke,{suppressHint:!0}),Ce(T);break}v=F,xa++,ko=10+Math.min(fe*3,7),Hp=!0,cu=Y.size,lu=!1,Zn=0,Be=0;for(let[B,we]of Ls){let Je=we?.count??we??0;Pp(Ls,B,Je>=2?Je:1)}for(let[B]of to)Os(Ls,B)<2&&to.delete(B);Gt.clear(),gr.clear(),ms&&ns>0&&(jn=!0,j(`${y.cyan} \u26A1 Post-wipe creation guard: cap pre-fired (${ns} edits already made)${y.reset}`));for(let[B]of su)Pp(su,B,ic-1);if(si(`Super-nuclear compression \u2014 dropped all history, keeping original task only (${N-q} tokens freed)`,y.yellow),xa>=1){let B=[...Ls.entries()].filter(([,vt])=>vt>=vr).map(([vt])=>vt.split("/").slice(-1)[0]),we=B.length>0?`
1656
+ Files modified so far: ${[...Y].map(we=>we.split("/").slice(-1)[0]).join(", ")}`:"";j(`${$.red} \u2717 Super-nuclear limit reached (3\xD7) \u2014 aborting to prevent runaway context loop${$.reset}`),console.log(`${$.yellow} \u{1F4A1} Task may exceed model context. Try /clear and break it into smaller steps.${B?$.dim+B:""}${$.reset}`),_&&(_.stop(),_=null),x(null),Ze(de,Ie,Y,je,Ke,{suppressHint:!0}),Ce(T);break}v=F,xa++,ko=10+Math.min(fe*3,7),Hp=!0,cu=Y.size,lu=!1,Zn=0,Be=0;for(let[B,we]of Ls){let Je=we?.count??we??0;Pp(Ls,B,Je>=2?Je:1)}for(let[B]of to)Os(Ls,B)<2&&to.delete(B);Gt.clear(),gr.clear(),ms&&ns>0&&(jn=!0,j(`${$.cyan} \u26A1 Post-wipe creation guard: cap pre-fired (${ns} edits already made)${$.reset}`));for(let[B]of su)Pp(su,B,ic-1);if(si(`Super-nuclear compression \u2014 dropped all history, keeping original task only (${N-q} tokens freed)`,$.yellow),xa>=1){let B=[...Ls.entries()].filter(([,vt])=>vt>=vr).map(([vt])=>vt.split("/").slice(-1)[0]),we=B.length>0?`
1657
1657
 
1658
- Files already at read cap \u2014 use grep_search instead: ${B.join(", ")}`:"",at={role:"user",content:Ln&&!Zt?"[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.${we}`};T.push(at),v.push(at)}M=0,Ct--;continue}}W="Context too large to compress \u2014 use /clear to start fresh"}else k.message.includes("500")||k.message.includes("502")||k.message.includes("503")||k.message.includes("504")?W="API server error \u2014 the provider is experiencing issues. Please try again in a moment":(k.message.includes("fetch failed")||k.message.includes("fetch"))&&(W="Network request failed \u2014 please check your internet connection");if(console.log(`${y.red} \u2717 ${W}${y.reset}`),w){_&&(_.stop(),_=null),x(null),Ze(de,Ie,Y,je,Ke),Ce(T);break e}if(k.message.includes("429")){if(z++,z>Tp){console.log(`${y.red} Rate limit: max retries (${Tp}) exceeded. Try again later or use /budget to check your limits.${y.reset}`),_&&(_.stop(),_=null),x(null),Ze(de,Ie,Y,je,Ke),Ce(T);break e}let $e=Math.min(1e4*Math.pow(2,z-1),12e4),ce=new ri(`Rate limit \u2014 waiting ${Math.round($e/1e3)}s (retry ${z}/${Tp})`);ce.start(),await new Promise(F=>setTimeout(F,$e)),ce.stop();continue}let H=process.env.NEX_PHASE_ROUTING!=="0"&&(()=>{try{return ft().getActiveProviderName()==="ollama"}catch{return!1}})();if(k.message.includes("socket disconnected")||k.message.includes("TLS")||k.message.includes("ECONNRESET")||k.message.includes("ECONNABORTED")||k.message.includes("ETIMEDOUT")||H&&(k.message.includes("500")||k.message.includes("502")||k.message.includes("503")||k.message.includes("504")||k.message.includes("401")||k.message.includes("Unauthorized"))||k.code==="ECONNRESET"||k.code==="ECONNABORTED"){if(ne++,ne>Rp){console.log(`${y.red} Network error: max retries (${Rp}) exceeded. Check your connection and try again.
1659
- Use /undo to revert changes made during this session.${y.reset}`),_&&(_.stop(),_=null),x(null),Ze(de,Ie,Y,je,Ke),Ce(T);break e}let $e=Math.min(2e3*Math.pow(2,ne-1),3e4),ce=new ri(`API temporarily unavailable \u2014 retrying in ${Math.round($e/1e3)}s (${ne}/${Rp}). Your changes are safe.`);ce.start(),await new Promise(F=>setTimeout(F,$e)),ce.stop(),Ct--;continue}_&&(_.stop(),_=null),x(null),Ze(de,Ie,Y,je,Ke),Ce(T);break}if(clearInterval(Zu),z=0,ne=0,Ue&&(_&&!_._paused&&_.pause(),Xe&&Xe.stop()),ks&&(clearTimeout(ks),ks=null),Gn&&$t&&($t.push(Gn),Gn=""),Ne&&$t.flush(),ne=0,te=0,At&&At.usage){let k=At.usage.prompt_tokens||0,w=At.usage.completion_tokens||0;g_(Qn(),Dn(),k,w),E+=k+w,_&&_.setStats({tokens:E})}else if(At&&!At.usage){let k=v.map(H=>typeof H.content=="string"?H.content:Array.isArray(H.content)?H.content.map(oe=>typeof oe=="string"?oe:oe.text||"").join(""):"").join(" "),w=w_(k),W=w_(At.content||Ne||"");g_(Qn(),Dn(),w,W),E+=w+W,_&&_.setStats({tokens:E})}let{content:um,tool_calls:Er}=At,xt=Er,Qu=!1;if(Array.isArray(Er)&&Er.length>0){let k=Er.filter(w=>w?.function?.name==="ask_user");k.length>0&&(xt=[k[0]],Qu=Er.length!==1,Qu&&j(`${y.yellow} \u26A0 ask_user must run alone \u2014 deferring ${Er.length-1} other tool call(s) until the user replies${y.reset}`))}let mc=Dp(um||""),dm=mc.truncated?mc.text:um;mc.truncated&&j(`${y.yellow} \u26A0 LLM output loop detected (${mc.repeatCount}\xD7 repeated paragraph) \u2014 response truncated${y.reset}`);let gc=nL(dm||""),_t=gc.truncated?gc.text:dm;if(gc.truncated&&j(`${y.yellow} \u26A0 LLM output loop detected (${gc.repeatCount}\xD7 repeated window) \u2014 response truncated${y.reset}`),Array.isArray(xt)&&xt.length>0&&kN(_t||"")&&(j(`${y.yellow} \u26A0 Assistant asked the user a direct question in text \u2014 dropping tool calls and waiting for user input${y.reset}`),xt=[]),lc=!1,Array.isArray(xt)&&xt.length>0){let k=Ep(Qn());if(Number.isFinite(k)){let w=k-yt;if(w<=0){if(Ku++,j(`${y.yellow} \u26A0 Tool-call budget reached (${yt}/${k}) \u2014 forcing final answer${y.reset}`),be&&Pe==="implement"&&Y.size===0&&nt===0||dr(Y,nt)){let H=`Implementation stalled before edits.
1658
+ Files already at read cap \u2014 use grep_search instead: ${B.join(", ")}`:"",at={role:"user",content:Ln&&!Zt?"[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.${we}`};T.push(at),v.push(at)}M=0,Ct--;continue}}W="Context too large to compress \u2014 use /clear to start fresh"}else k.message.includes("500")||k.message.includes("502")||k.message.includes("503")||k.message.includes("504")?W="API server error \u2014 the provider is experiencing issues. Please try again in a moment":(k.message.includes("fetch failed")||k.message.includes("fetch"))&&(W="Network request failed \u2014 please check your internet connection");if(console.log(`${$.red} \u2717 ${W}${$.reset}`),w){_&&(_.stop(),_=null),x(null),Ze(de,Ie,Y,je,Ke),Ce(T);break e}if(k.message.includes("429")){if(z++,z>Tp){console.log(`${$.red} Rate limit: max retries (${Tp}) exceeded. Try again later or use /budget to check your limits.${$.reset}`),_&&(_.stop(),_=null),x(null),Ze(de,Ie,Y,je,Ke),Ce(T);break e}let $e=Math.min(1e4*Math.pow(2,z-1),12e4),ce=new ri(`Rate limit \u2014 waiting ${Math.round($e/1e3)}s (retry ${z}/${Tp})`);ce.start(),await new Promise(F=>setTimeout(F,$e)),ce.stop();continue}let H=process.env.NEX_PHASE_ROUTING!=="0"&&(()=>{try{return ft().getActiveProviderName()==="ollama"}catch{return!1}})();if(k.message.includes("socket disconnected")||k.message.includes("TLS")||k.message.includes("ECONNRESET")||k.message.includes("ECONNABORTED")||k.message.includes("ETIMEDOUT")||H&&(k.message.includes("500")||k.message.includes("502")||k.message.includes("503")||k.message.includes("504")||k.message.includes("401")||k.message.includes("Unauthorized"))||k.code==="ECONNRESET"||k.code==="ECONNABORTED"){if(ne++,ne>Rp){console.log(`${$.red} Network error: max retries (${Rp}) exceeded. Check your connection and try again.
1659
+ Use /undo to revert changes made during this session.${$.reset}`),_&&(_.stop(),_=null),x(null),Ze(de,Ie,Y,je,Ke),Ce(T);break e}let $e=Math.min(2e3*Math.pow(2,ne-1),3e4),ce=new ri(`API temporarily unavailable \u2014 retrying in ${Math.round($e/1e3)}s (${ne}/${Rp}). Your changes are safe.`);ce.start(),await new Promise(F=>setTimeout(F,$e)),ce.stop(),Ct--;continue}_&&(_.stop(),_=null),x(null),Ze(de,Ie,Y,je,Ke),Ce(T);break}if(clearInterval(Zu),z=0,ne=0,Ue&&(_&&!_._paused&&_.pause(),Xe&&Xe.stop()),ks&&(clearTimeout(ks),ks=null),Gn&&$t&&($t.push(Gn),Gn=""),Ne&&$t.flush(),ne=0,te=0,At&&At.usage){let k=At.usage.prompt_tokens||0,w=At.usage.completion_tokens||0;g_(Qn(),Dn(),k,w),E+=k+w,_&&_.setStats({tokens:E})}else if(At&&!At.usage){let k=v.map(H=>typeof H.content=="string"?H.content:Array.isArray(H.content)?H.content.map(oe=>typeof oe=="string"?oe:oe.text||"").join(""):"").join(" "),w=w_(k),W=w_(At.content||Ne||"");g_(Qn(),Dn(),w,W),E+=w+W,_&&_.setStats({tokens:E})}let{content:um,tool_calls:Er}=At,xt=Er,Qu=!1;if(Array.isArray(Er)&&Er.length>0){let k=Er.filter(w=>w?.function?.name==="ask_user");k.length>0&&(xt=[k[0]],Qu=Er.length!==1,Qu&&j(`${$.yellow} \u26A0 ask_user must run alone \u2014 deferring ${Er.length-1} other tool call(s) until the user replies${$.reset}`))}let mc=Dp(um||""),dm=mc.truncated?mc.text:um;mc.truncated&&j(`${$.yellow} \u26A0 LLM output loop detected (${mc.repeatCount}\xD7 repeated paragraph) \u2014 response truncated${$.reset}`);let gc=nL(dm||""),_t=gc.truncated?gc.text:dm;if(gc.truncated&&j(`${$.yellow} \u26A0 LLM output loop detected (${gc.repeatCount}\xD7 repeated window) \u2014 response truncated${$.reset}`),Array.isArray(xt)&&xt.length>0&&kN(_t||"")&&(j(`${$.yellow} \u26A0 Assistant asked the user a direct question in text \u2014 dropping tool calls and waiting for user input${$.reset}`),xt=[]),lc=!1,Array.isArray(xt)&&xt.length>0){let k=Ep(Qn());if(Number.isFinite(k)){let w=k-yt;if(w<=0){if(Ku++,j(`${$.yellow} \u26A0 Tool-call budget reached (${yt}/${k}) \u2014 forcing final answer${$.reset}`),be&&Pe==="implement"&&Y.size===0&&nt===0||dr(Y,nt)){let H=`Implementation stalled before edits.
1660
1660
 
1661
1661
  The implementation phase reached the tool-call budget without changing files. Stopping without commit or push so the workflow does not falsely report success.`,oe={role:"assistant",content:H};T.push(oe),v.push(oe),console.log(`
1662
1662
  ${H}`),Ce(T),wt(T);break e}let W={role:"user",content:S_(yt,k)};if(T.push(W),v.push(W),cc=!0,Ku>=2){if(et&&Yt&&Y.size===0&&nt===0){let oe=`Implementation stalled before edits.
1663
1663
 
1664
1664
  The implementation phase reached the tool-call budget without changing files. Stopping without commit or push so the workflow does not falsely report success.`,$e={role:"assistant",content:oe};T.push($e),v.push($e),console.log(`
1665
1665
  ${oe}`),Ce(T),wt(T);break e}let H={role:"assistant",content:"I reached the tool-call budget and cannot safely continue executing tools. Based on the information gathered so far, I cannot complete more investigation without risking a tool loop."};T.push(H),console.log(`
1666
- ${H.content}`),Ce(T),wt(T),await uc();return}continue}xt.length>w&&(j(`${y.yellow} \u26A0 Tool-call batch trimmed from ${xt.length} to ${w} (budget ${yt}/${k})${y.reset}`),xt=xt.slice(0,w),lc=!0)}}let Tr={role:"assistant",content:_t||""};if(xt&&xt.length>0&&(Tr.tool_calls=xt,ui=0),T.push(Tr),v.push(Tr),be&&Pe==="plan"&&et&&xt&&xt.length>0&&(Yt&&String(_t||Ne||"").trim()||Ra(_t||Ne||""))&&(delete Tr.tool_calls,xt=[]),am&&!zl(_t||Ne||"")&&Y.size===0&&nt===0){j(`${y.green} \u2713 Analysis-only early exit: ${(_t||"").length} chars produced, no file changes${y.reset}`),Tr.tool_calls&&delete Tr.tool_calls,Ze(de,Ie,Y,je,Ke),Ce(T);break e}if(!Zt&&_t&&xt&&xt.length>0){let k=Mp(_t);if(k){Zt=!0,kn=k.slice(0,120),es=0,jn=!1,ts=0,j(`${y.yellow} \u26A1 Root cause in model analysis: ${kn} \u2014 fix phase (read budget: 3)${y.reset}`);let w={role:"user",content:`[SYSTEM] Root cause identified: ${kn}. Read only the file that needs fixing, then edit it. Do not read other files.`};T.push(w),v.push(w)}}if(!xt||xt.length===0){if(vn()&&ui<3&&ui++,vn()&&ui>=3&&yt===0&&!et){let F=Dn(),P="devstral-2:123b";if(F&&!F.includes("123b")&&!F.includes("480b")&&!F.includes("1t")){Kl(`${Qn()}:${P}`),ui=0,j(`${y.yellow} \u26A1 Auto-escalate: 0 tool calls in 3 turns \u2192 switching to ${P}${y.reset}`);continue}}let k=(_t||"").trim().length>0||Ne.trim().length>0;if(!k&&et&&Yt&&dr(Y,nt)&&(cc||Ct>=cn-1)){let F=`Implementation stalled before edits.
1666
+ ${H.content}`),Ce(T),wt(T),await uc();return}continue}xt.length>w&&(j(`${$.yellow} \u26A0 Tool-call batch trimmed from ${xt.length} to ${w} (budget ${yt}/${k})${$.reset}`),xt=xt.slice(0,w),lc=!0)}}let Tr={role:"assistant",content:_t||""};if(xt&&xt.length>0&&(Tr.tool_calls=xt,ui=0),T.push(Tr),v.push(Tr),be&&Pe==="plan"&&et&&xt&&xt.length>0&&(Yt&&String(_t||Ne||"").trim()||Ra(_t||Ne||""))&&(delete Tr.tool_calls,xt=[]),am&&!zl(_t||Ne||"")&&Y.size===0&&nt===0){j(`${$.green} \u2713 Analysis-only early exit: ${(_t||"").length} chars produced, no file changes${$.reset}`),Tr.tool_calls&&delete Tr.tool_calls,Ze(de,Ie,Y,je,Ke),Ce(T);break e}if(!Zt&&_t&&xt&&xt.length>0){let k=Mp(_t);if(k){Zt=!0,kn=k.slice(0,120),es=0,jn=!1,ts=0,j(`${$.yellow} \u26A1 Root cause in model analysis: ${kn} \u2014 fix phase (read budget: 3)${$.reset}`);let w={role:"user",content:`[SYSTEM] Root cause identified: ${kn}. Read only the file that needs fixing, then edit it. Do not read other files.`};T.push(w),v.push(w)}}if(!xt||xt.length===0){if(vn()&&ui<3&&ui++,vn()&&ui>=3&&yt===0&&!et){let F=Dn(),P="devstral-2:123b";if(F&&!F.includes("123b")&&!F.includes("480b")&&!F.includes("1t")){Kl(`${Qn()}:${P}`),ui=0,j(`${$.yellow} \u26A1 Auto-escalate: 0 tool calls in 3 turns \u2192 switching to ${P}${$.reset}`);continue}}let k=(_t||"").trim().length>0||Ne.trim().length>0;if(!k&&et&&Yt&&dr(Y,nt)&&(cc||Ct>=cn-1)){let F=`Implementation stalled before edits.
1667
1667
 
1668
1668
  The bounded backlog workflow reached the response budget without changing files. Stopping without commit or push so the workflow does not falsely report success.`,P={role:"assistant",content:F};T.push(P),v.push(P),console.log(`
1669
1669
  ${F}`),Ce(T),wt(T);break e}if(a&&k&&(c==="English"&&WL(_t||Ne||"")!=="English"||HL(e,_t||Ne||"")))try{let P=[v[0],{role:"user",content:`Rewrite the text below to be a clean, direct answer.
@@ -1674,91 +1674,91 @@ ${F}`),Ce(T),wt(T);break e}if(a&&k&&(c==="English"&&WL(_t||Ne||"")!=="English"||
1674
1674
 
1675
1675
  ---
1676
1676
 
1677
- `+(_t||Ne||"")}],N=((await Yl(P,[],{}))?.content||"").trim();if(N){let U=T[T.length-1];U&&U.role==="assistant"&&(U.content=N);let se=v[v.length-1];se&&se.role==="assistant"&&(se.content=N),console.log(`\\n${N}`)}}catch{}let w=!1;if(Ln&&k&&(Xl>=2?j(`${y.yellow} \u26A0 SSH permanently blocked after ${Xl} storm warnings \u2014 no further SSH calls allowed${y.reset}`):(Ln=!1,Zn=Si-4,w=!0)),w&&k){let F=(_t||"").trim();if(F.endsWith("?")||/\b(Where |Please |Can you|Should I)\b/.test(F.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."};v.push(q),T.push(q);continue}}if(!k&&de>0&&Ct<Ql-1){let F={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."};v.push(F),T.push(F);continue}if(!k&&et&&Yt&&Ct<Ql-1){if(rm++,rm<=2){let N={role:"user",content:(be&&Pe==="implement"?"implementation":"planning")==="implementation"?"[SYSTEM] Empty implementation response is not progress. Continue now with a concrete tool call: read the implementation file from the accepted plan with a targeted range, or edit/patch/write the scoped change. Do not stop without edits.":"[SYSTEM] Empty planning response is not a valid result. The backlog and UI evidence has already been read. Respond now with the required labels: Selected improvement:, Selection rationale:, Files:, Implementation outline:, Verification plan:, Browser/UI applicability:."};v.push(N),T.push(N);continue}let F=(be&&Pe==="implement"?"Implementation stalled before edits.":"Planning stalled before selecting an improvement.")+`
1677
+ `+(_t||Ne||"")}],N=((await Yl(P,[],{}))?.content||"").trim();if(N){let U=T[T.length-1];U&&U.role==="assistant"&&(U.content=N);let se=v[v.length-1];se&&se.role==="assistant"&&(se.content=N),console.log(`\\n${N}`)}}catch{}let w=!1;if(Ln&&k&&(Xl>=2?j(`${$.yellow} \u26A0 SSH permanently blocked after ${Xl} storm warnings \u2014 no further SSH calls allowed${$.reset}`):(Ln=!1,Zn=Si-4,w=!0)),w&&k){let F=(_t||"").trim();if(F.endsWith("?")||/\b(Where |Please |Can you|Should I)\b/.test(F.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."};v.push(q),T.push(q);continue}}if(!k&&de>0&&Ct<Ql-1){let F={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."};v.push(F),T.push(F);continue}if(!k&&et&&Yt&&Ct<Ql-1){if(rm++,rm<=2){let N={role:"user",content:(be&&Pe==="implement"?"implementation":"planning")==="implementation"?"[SYSTEM] Empty implementation response is not progress. Continue now with a concrete tool call: read the implementation file from the accepted plan with a targeted range, or edit/patch/write the scoped change. Do not stop without edits.":"[SYSTEM] Empty planning response is not a valid result. The backlog and UI evidence has already been read. Respond now with the required labels: Selected improvement:, Selection rationale:, Files:, Implementation outline:, Verification plan:, Browser/UI applicability:."};v.push(N),T.push(N);continue}let F=(be&&Pe==="implement"?"Implementation stalled before edits.":"Planning stalled before selecting an improvement.")+`
1678
1678
 
1679
1679
  The model returned repeated empty responses after the gated backlog evidence was available. Stopping without commit or push so the workflow does not falsely report success.`,P={role:"assistant",content:F};T.push(P),v.push(P),console.log(`
1680
1680
  ${F}`),Ce(T),wt(T);break e}if(k&&et&&vn()&&Y.size===0&&nt===0){let F=_t||Ne||"";if(Ip(F)&&!jp(F)&&!Ra(F)){let P=`Implementation stalled before edits.
1681
1681
 
1682
1682
  The implementation phase claimed changes, verification, or a clean worktree without any successful file edit or verification evidence. Stopping without commit or push so the workflow does not falsely report success.`,q={role:"assistant",content:P};T.push(q),v.push(q),console.log(`
1683
- ${P}`),Ze(de,Ie,Y,je,Ke),Ce(T),wt(T);break e}}let W=/can.?t use.*tool|Tool.?Budget|cannot.*access|no.*tool.*access|unable to run (?:any )?(?:git )?commands?|system instructions?.{0,80}\bblock.{0,80}(?:git|tool|command)|(?:git|bash|tools?).{0,80}\b(blocked|forbidden|not allowed)\b/i;if(k&&Ct<3&&W.test((_t||"").slice(0,600)))if(Hp&&ko<=0||Ln){j(`${y.yellow} \u26A0 Tool avoidance (constrained context) \u2014 telling model to ask user${y.reset}`);let P={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."};v.push(P),T.push(P);continue}else{j(`${y.yellow} \u26A0 Tool avoidance detected \u2014 nudging model to use tools${y.reset}`);let P={role:"user",content:et&&be&&Pe==="implement"?"[SYSTEM] You are in implementation phase and the initial git preflight is already complete. Do not claim git/tools are unavailable, and do not re-run git status before editing. Locate the concrete implementation file with targeted read/search/list_directory if needed, then call edit_file/patch_file/write_file for the scoped change.":"[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."};v.push(P),T.push(P);continue}if(n.skillLoop&&k&&de>3&&pc<5){let F=(_t||Ne||"").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(F.slice(-600))){pc=(pc||0)+1,j(`${y.yellow} \u26A0 Skill loop: model tried to stop \u2014 continuation nudge #${pc}${y.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."};v.push(q),T.push(q);continue}}if((be&&Pe==="implement"||dr(Y,nt))&&vn()&&k&&Y.size===0&&nt===0){if(vo<3){vo++;let q={role:"user",content:"[SYSTEM] Implementation is not complete: you produced prose but made no file changes. Do not finish or restate the plan. In the next response, either call read_file with line_start/line_end on the concrete implementation file from the accepted plan, or call edit_file/patch_file/write_file to make the scoped change. Keep prose minimal and include at least one tool call."};T.push(q),v.push(q),j(`${y.yellow} \u26A0 Implement phase made no progress \u2014 nudging for concrete tool use (${vo}/3)${y.reset}`);continue}let F=`Implementation stalled before edits.
1683
+ ${P}`),Ze(de,Ie,Y,je,Ke),Ce(T),wt(T);break e}}let W=/can.?t use.*tool|Tool.?Budget|cannot.*access|no.*tool.*access|unable to run (?:any )?(?:git )?commands?|system instructions?.{0,80}\bblock.{0,80}(?:git|tool|command)|(?:git|bash|tools?).{0,80}\b(blocked|forbidden|not allowed)\b/i;if(k&&Ct<3&&W.test((_t||"").slice(0,600)))if(Hp&&ko<=0||Ln){j(`${$.yellow} \u26A0 Tool avoidance (constrained context) \u2014 telling model to ask user${$.reset}`);let P={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."};v.push(P),T.push(P);continue}else{j(`${$.yellow} \u26A0 Tool avoidance detected \u2014 nudging model to use tools${$.reset}`);let P={role:"user",content:et&&be&&Pe==="implement"?"[SYSTEM] You are in implementation phase and the initial git preflight is already complete. Do not claim git/tools are unavailable, and do not re-run git status before editing. Locate the concrete implementation file with targeted read/search/list_directory if needed, then call edit_file/patch_file/write_file for the scoped change.":"[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."};v.push(P),T.push(P);continue}if(n.skillLoop&&k&&de>3&&pc<5){let F=(_t||Ne||"").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(F.slice(-600))){pc=(pc||0)+1,j(`${$.yellow} \u26A0 Skill loop: model tried to stop \u2014 continuation nudge #${pc}${$.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."};v.push(q),T.push(q);continue}}if((be&&Pe==="implement"||dr(Y,nt))&&vn()&&k&&Y.size===0&&nt===0){if(vo<3){vo++;let q={role:"user",content:"[SYSTEM] Implementation is not complete: you produced prose but made no file changes. Do not finish or restate the plan. In the next response, either call read_file with line_start/line_end on the concrete implementation file from the accepted plan, or call edit_file/patch_file/write_file to make the scoped change. Keep prose minimal and include at least one tool call."};T.push(q),v.push(q),j(`${$.yellow} \u26A0 Implement phase made no progress \u2014 nudging for concrete tool use (${vo}/3)${$.reset}`);continue}let F=`Implementation stalled before edits.
1684
1684
 
1685
1685
  The plan phase completed, but the implementation phase produced text-only responses without changing files. Stopping without commit or push so the workflow does not falsely report success.`,P={role:"assistant",content:F};T.push(P),v.push(P),console.log(`
1686
- ${F}`),Ze(de,Ie,Y,je,Ke),Ce(T),wt(T);break e}if(k&&_N(_t||Ne||"")&&!n.skillLoop&&!mr()&&!be&&!In){j(`${y.green} \u2713 Explicit final summary exit: no follow-up provider call needed${y.reset}`),_&&(_.stop(),_=null),x(null),Ze(de,Ie,Y,je,Ke),Ce(T),wt(T),await uc();return}if(vn()&&!n.skillLoop&&Y.size===0&&nt===0&&je.size===0&&de===0&&k&&!be){j(`${y.green} \u2713 Headless direct response exit: text-only response received${y.reset}`),Ce(T);break e}if(vn()&&!n.skillLoop&&!be&&(Y.size>0||nt>0)&&Is&&!Yu()&&js<2){js++;let F=await wu(Y),P=await Ba(Y),q={role:"user",content:P_(Y,F,P)+`
1687
- Do not write a final completion summary until this verification evidence exists.`};T.push(q),v.push(q),j(`${y.yellow} \u26A0 Headless completion blocked \u2014 verification required (${js}/2)${y.reset}`);continue}if(vn()&&!n.skillLoop&&(Y.size>0||nt>0)&&k&&!zl(_t||Ne||"")&&de>=1&&(!Is||Yu())&&!be){j(`${y.green} \u2713 Headless early exit: ${Y.size} file(s) modified (+ ${nt} bash writes), substantive text response received${y.reset}`),Ze(de,Ie,Y,je,Ke),Ce(T);break e}let oe=SL(fi)?1:2;if(be&&Pe==="plan"&&So>=oe){j(`${y.cyan} \u21B3 Plan phase: ${So} consecutive blocks (last: ${fi||"unknown"}) \u2014 auto-advancing to implement${y.reset}`),So=0,fi=null;let F=await oi("implement","[auto-advance: task only requires direct action]");if(F){T.push(F),v.push(F),Ct=0,cn=bo("implement");continue}}if(be&&k){let F=(_t||Ne||"").trim();if(Pe==="plan"){if(et&&/\bno safe task found\b/i.test(F)){if(!J_(F)){Ps++;let Ee={role:"user",content:Ns()+"\n\nDo not answer `no safe task found` before reading/searching backlog evidence unless you name a concrete blocker such as dirty worktree, wrong branch, missing files, or unavailable permissions. If git preflight is clean, inspect the listed backlog/UI files and select one scoped improvement."};T.push(Ee),v.push(Ee),j(`${y.yellow} \u26A0 Bounded backlog plan: premature no-safe-task response \u2014 requiring backlog evidence${y.reset}`);continue}j(`${y.yellow} \u26A0 Bounded backlog plan: no safe task found \u2014 exiting gracefully${y.reset}`),Ze(de,Ie,Y,je,Ke),Ce(T);break e}if(et&&!Ra(F)){if(Yt&&AL(F)){Ps++;let B={role:"user",content:Ns({blocked:!0})+`
1686
+ ${F}`),Ze(de,Ie,Y,je,Ke),Ce(T),wt(T);break e}if(k&&_N(_t||Ne||"")&&!n.skillLoop&&!mr()&&!be&&!In){j(`${$.green} \u2713 Explicit final summary exit: no follow-up provider call needed${$.reset}`),_&&(_.stop(),_=null),x(null),Ze(de,Ie,Y,je,Ke),Ce(T),wt(T),await uc();return}if(vn()&&!n.skillLoop&&Y.size===0&&nt===0&&je.size===0&&de===0&&k&&!be){j(`${$.green} \u2713 Headless direct response exit: text-only response received${$.reset}`),Ce(T);break e}if(vn()&&!n.skillLoop&&!be&&(Y.size>0||nt>0)&&Is&&!Yu()&&js<2){js++;let F=await wu(Y),P=await Ba(Y),q={role:"user",content:P_(Y,F,P)+`
1687
+ Do not write a final completion summary until this verification evidence exists.`};T.push(q),v.push(q),j(`${$.yellow} \u26A0 Headless completion blocked \u2014 verification required (${js}/2)${$.reset}`);continue}if(vn()&&!n.skillLoop&&(Y.size>0||nt>0)&&k&&!zl(_t||Ne||"")&&de>=1&&(!Is||Yu())&&!be){j(`${$.green} \u2713 Headless early exit: ${Y.size} file(s) modified (+ ${nt} bash writes), substantive text response received${$.reset}`),Ze(de,Ie,Y,je,Ke),Ce(T);break e}let oe=SL(fi)?1:2;if(be&&Pe==="plan"&&So>=oe){j(`${$.cyan} \u21B3 Plan phase: ${So} consecutive blocks (last: ${fi||"unknown"}) \u2014 auto-advancing to implement${$.reset}`),So=0,fi=null;let F=await oi("implement","[auto-advance: task only requires direct action]");if(F){T.push(F),v.push(F),Ct=0,cn=bo("implement");continue}}if(be&&k){let F=(_t||Ne||"").trim();if(Pe==="plan"){if(et&&/\bno safe task found\b/i.test(F)){if(!J_(F)){Ps++;let Ee={role:"user",content:Ns()+"\n\nDo not answer `no safe task found` before reading/searching backlog evidence unless you name a concrete blocker such as dirty worktree, wrong branch, missing files, or unavailable permissions. If git preflight is clean, inspect the listed backlog/UI files and select one scoped improvement."};T.push(Ee),v.push(Ee),j(`${$.yellow} \u26A0 Bounded backlog plan: premature no-safe-task response \u2014 requiring backlog evidence${$.reset}`);continue}j(`${$.yellow} \u26A0 Bounded backlog plan: no safe task found \u2014 exiting gracefully${$.reset}`),Ze(de,Ie,Y,je,Ke),Ce(T);break e}if(et&&!Ra(F)){if(Yt&&AL(F)){Ps++;let B={role:"user",content:Ns({blocked:!0})+`
1688
1688
 
1689
- The backlog evidence has already been read into the conversation. Do not describe tool calls, JSON tool calls, or read_file calls in text. Write only the required bounded plan labels now.`};T.push(B),v.push(B),j(`${y.yellow} \u26A0 Bounded backlog plan: textual tool-call attempt after evidence prefetch${y.reset}`);continue}if(V_(F)){Ps++;let B={role:"user",content:Ns({blocked:Yt})+"\n\nYour previous plan used markdown headings. Rewrite the same plan using exact label lines, for example `Selected improvement:` instead of `### Selected improvement`."};T.push(B),v.push(B),j(`${y.yellow} \u26A0 Bounded backlog plan: heading labels rejected \u2014 requesting exact labels${y.reset}`);continue}if(K_(F)){Ps++;let B={role:"user",content:Ns({blocked:Sn>=di})+`
1689
+ The backlog evidence has already been read into the conversation. Do not describe tool calls, JSON tool calls, or read_file calls in text. Write only the required bounded plan labels now.`};T.push(B),v.push(B),j(`${$.yellow} \u26A0 Bounded backlog plan: textual tool-call attempt after evidence prefetch${$.reset}`);continue}if(V_(F)){Ps++;let B={role:"user",content:Ns({blocked:Yt})+"\n\nYour previous plan used markdown headings. Rewrite the same plan using exact label lines, for example `Selected improvement:` instead of `### Selected improvement`."};T.push(B),v.push(B),j(`${$.yellow} \u26A0 Bounded backlog plan: heading labels rejected \u2014 requesting exact labels${$.reset}`);continue}if(K_(F)){Ps++;let B={role:"user",content:Ns({blocked:Sn>=di})+`
1690
1690
 
1691
- Your previous plan was rejected because it invented an off-task React/list-component issue or referenced files that do not exist in this repository. Use only the prompt-named backlog evidence above and select one nex-note notation-editor workflow improvement.`};T.push(B),v.push(B),j(`${y.yellow} \u26A0 Bounded backlog plan: rejected off-topic selected improvement${y.reset}`);continue}if(Ps++,Ps>=(Yt?4:2)||Sn>=di){let B=`no safe task found
1691
+ Your previous plan was rejected because it invented an off-task React/list-component issue or referenced files that do not exist in this repository. Use only the prompt-named backlog evidence above and select one nex-note notation-editor workflow improvement.`};T.push(B),v.push(B),j(`${$.yellow} \u26A0 Bounded backlog plan: rejected off-topic selected improvement${$.reset}`);continue}if(Ps++,Ps>=(Yt?4:2)||Sn>=di){let B=`no safe task found
1692
1692
 
1693
1693
  Bounded backlog planning requires an explicit selected-improvement decision with files and verification evidence. Stopping before implementation because the plan response did not follow the required template.`,we={role:"assistant",content:B};T.push(we),console.log(`
1694
- ${B}`),Ce(T),wt(T);break e}let fe={role:"user",content:Ns({blocked:Sn>=di})};T.push(fe),v.push(fe),j(`${y.yellow} \u26A0 Bounded backlog plan: missing selected-improvement decision \u2014 re-prompting in plan phase${y.reset}`);continue}if(et&&Ps<1&&CL(F)){Ps++;let Ee=[...$r].slice(0,4).join(", "),fe={role:"user",content:Ns({blocked:Yt})+`
1694
+ ${B}`),Ce(T),wt(T);break e}let fe={role:"user",content:Ns({blocked:Sn>=di})};T.push(fe),v.push(fe),j(`${$.yellow} \u26A0 Bounded backlog plan: missing selected-improvement decision \u2014 re-prompting in plan phase${$.reset}`);continue}if(et&&Ps<1&&CL(F)){Ps++;let Ee=[...$r].slice(0,4).join(", "),fe={role:"user",content:Ns({blocked:Yt})+`
1695
1695
 
1696
- Your previous plan named implementation files that do not exist in this repository. Use an existing file from the UI evidence already read above, such as: ${Ee}. Do not invent src/components paths when the actual files are at the repository root.`};T.push(fe),v.push(fe),j(`${y.yellow} \u26A0 Bounded backlog plan: correcting nonexistent implementation paths${y.reset}`);continue}let P=/\b(no match(es)?|not found|couldn'?t find|does not exist|no results|nothing found|no files)\b/i,q=Z_(F,Ls).length===0,N=Aa.size>0,U=Oa.size>0,se=F.length>1500;if(vn()&&q&&!N&&!U&&!se&&P.test(F)){j(`${y.yellow} \u26A0 Plan phase: nothing actionable found \u2014 exiting gracefully${y.reset}`),process.stdout.isTTY&&process.stderr.write(`${y.yellow} \u26A0 Could not find the target in this project. The plan phase found no actionable items.${y.reset}
1697
- `),Ze(de,Ie,Y,je,Ke),Ce(T);break e}let Se=await oi("implement",F);if(Se){T.push(Se),v.push(Se),Ct=0,cn=bo("implement");continue}}else if(Pe==="implement"&&(Y.size>0||nt>0)){let P=T.find(U=>U.role==="user"),q=typeof P?.content=="string"?P.content:"",N=await oi("verify",F,Y,q);if(N){T.push(N),v.push(N),Ct=0,cn=Math.min(bo("verify")+Math.max(0,(Y.size-2)*2),20);continue}}else if(Pe==="verify"){let P=/\bPASS\b/i.test(F.slice(0,500)),N=/\bFAIL\b|test.*fail|error|broken|missing|incorrect/i.test(F.slice(0,500)),U=pi>0||v.some(se=>se.role==="assistant"&&typeof se.content=="string"&&/\bPASS\b/i.test(se.content.slice(0,500)));if(vn()&&!n.skillLoop&&U&&!N&&!zl(F)){if(j(`${y.green} \u2713 Verification phase complete (headless substantive summary)${y.reset}`),In&&!Vp(F))try{let se=ss.length>0?ss.join(" | "):qs.length>0?`post-edit read: ${qs.slice(0,8).join(", ")}`:"not run; state this explicitly and do not claim tests/build/checks passed",Se=Ve&&Ve.command||"git status --short --branch",Ee=Ve&&String(Ve.raw||"").trim()||"(missing preflight output)",fe=Ve&&Ve.branch||M_||"(unknown)",B=[...Y].slice(0,24).join(", ")||(nt>0?"files changed by shell commands":"(none)"),we=ni?"detected (git commit succeeded per bash output)":"not detected",Je=fu?"detected (git push succeeded per bash output)":xo?"attempted (see tool output)":"not detected",at=hr?`${Ea}
1696
+ Your previous plan named implementation files that do not exist in this repository. Use an existing file from the UI evidence already read above, such as: ${Ee}. Do not invent src/components paths when the actual files are at the repository root.`};T.push(fe),v.push(fe),j(`${$.yellow} \u26A0 Bounded backlog plan: correcting nonexistent implementation paths${$.reset}`);continue}let P=/\b(no match(es)?|not found|couldn'?t find|does not exist|no results|nothing found|no files)\b/i,q=Z_(F,Ls).length===0,N=Aa.size>0,U=Oa.size>0,se=F.length>1500;if(vn()&&q&&!N&&!U&&!se&&P.test(F)){j(`${$.yellow} \u26A0 Plan phase: nothing actionable found \u2014 exiting gracefully${$.reset}`),process.stdout.isTTY&&process.stderr.write(`${$.yellow} \u26A0 Could not find the target in this project. The plan phase found no actionable items.${$.reset}
1697
+ `),Ze(de,Ie,Y,je,Ke),Ce(T);break e}let Se=await oi("implement",F);if(Se){T.push(Se),v.push(Se),Ct=0,cn=bo("implement");continue}}else if(Pe==="implement"&&(Y.size>0||nt>0)){let P=T.find(U=>U.role==="user"),q=typeof P?.content=="string"?P.content:"",N=await oi("verify",F,Y,q);if(N){T.push(N),v.push(N),Ct=0,cn=Math.min(bo("verify")+Math.max(0,(Y.size-2)*2),20);continue}}else if(Pe==="verify"){let P=/\bPASS\b/i.test(F.slice(0,500)),N=/\bFAIL\b|test.*fail|error|broken|missing|incorrect/i.test(F.slice(0,500)),U=pi>0||v.some(se=>se.role==="assistant"&&typeof se.content=="string"&&/\bPASS\b/i.test(se.content.slice(0,500)));if(vn()&&!n.skillLoop&&U&&!N&&!zl(F)){if(j(`${$.green} \u2713 Verification phase complete (headless substantive summary)${$.reset}`),In&&!Vp(F))try{let se=ss.length>0?ss.join(" | "):qs.length>0?`post-edit read: ${qs.slice(0,8).join(", ")}`:"not run; state this explicitly and do not claim tests/build/checks passed",Se=Ve&&Ve.command||"git status --short --branch",Ee=Ve&&String(Ve.raw||"").trim()||"(missing preflight output)",fe=Ve&&Ve.branch||M_||"(unknown)",B=[...Y].slice(0,24).join(", ")||(nt>0?"files changed by shell commands":"(none)"),we=ni?"detected (git commit succeeded per bash output)":"not detected",Je=fu?"detected (git push succeeded per bash output)":xo?"attempted (see tool output)":"not detected",at=hr?`${Ea}
1698
1698
  ${hr}`:"(not checked in this run)",vt=["Write a final automation report using EXACT labels (one per line):",`Preflight: ${Se}`,"Preflight output: (paste exactly; do not paraphrase)",Ee,`Branch: ${fe}`,"Chosen task: (what you actually did; or `no safe task found`)",`Files changed: ${B}`,`Verification: ${se}`,`Commit: ${we}`,`Push: ${Je}`,`Final git status: ${at}`,"Remaining risk: (if any; otherwise `none`)","","Hard rules: do not claim verification/commit/push/git status checks without evidence from tool output. If unknown, write unknown."].join(`
1699
1699
  `),Cn=[...v,{role:"user",content:vt}],xs=((await Yl(Cn,[],{}))?.content||"").trim();xs&&(console.log(`
1700
1700
  ${xs}`),T.push({role:"user",content:vt},{role:"assistant",content:xs}),v.push({role:"user",content:vt},{role:"assistant",content:xs}))}catch{}Ze(de,Ie,Y,je,Ke),Ce(T),wt(T);break e}if(N&&li<3){li++;let se={role:"user",content:`[PHASE: RE-IMPLEMENTATION] Verification found issues:
1701
1701
  ${F.slice(0,400)}
1702
1702
 
1703
- Fix the identified issues. This is attempt ${li}/3.`};Pe="implement",gs=Lp("implement",yr),T.push(se),v.push(se),Ct=0,cn=bo("implement"),j(`${y.yellow} \u21B3 Verify \u2192 implement loop-back #${li} (issues found)${y.reset}`);continue}if(!N&&(!P||pi===0)){if(hi<2){hi++;let se=[];pi===0&&se.push("run at least one verification tool"),P||se.push("end your report with PASS or FAIL");let Se={role:"user",content:`[SYSTEM] Verification is incomplete: ${se.join(" and ")}. Do not stop yet. Re-read the modified files and/or run tests or linters, then respond with PASS or FAIL.`};T.push(Se),v.push(Se),j(`${y.yellow} \u26A0 Verify phase incomplete \u2014 nudging for evidence (${hi}/2)${y.reset}`);continue}j(`${y.yellow} \u26A0 Verify phase completion accepted without full markers after ${hi} nudges${y.reset}`)}if(j(`${y.green} \u2713 Verification phase complete${N?" (loop-back exhausted)":" (PASS)"}${y.reset}`),!N){Ze(de,Ie,Y,je,Ke),Ce(T),wt(T);break e}}}if(mr()&&k&&de===0)if(ru++,ru>2)j(`${y.yellow} \u26A0 Plan accepted despite no file reads (rejection loop cap reached)${y.reset}`);else{let F={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.).
1703
+ Fix the identified issues. This is attempt ${li}/3.`};Pe="implement",gs=Lp("implement",yr),T.push(se),v.push(se),Ct=0,cn=bo("implement"),j(`${$.yellow} \u21B3 Verify \u2192 implement loop-back #${li} (issues found)${$.reset}`);continue}if(!N&&(!P||pi===0)){if(hi<2){hi++;let se=[];pi===0&&se.push("run at least one verification tool"),P||se.push("end your report with PASS or FAIL");let Se={role:"user",content:`[SYSTEM] Verification is incomplete: ${se.join(" and ")}. Do not stop yet. Re-read the modified files and/or run tests or linters, then respond with PASS or FAIL.`};T.push(Se),v.push(Se),j(`${$.yellow} \u26A0 Verify phase incomplete \u2014 nudging for evidence (${hi}/2)${$.reset}`);continue}j(`${$.yellow} \u26A0 Verify phase completion accepted without full markers after ${hi} nudges${$.reset}`)}if(j(`${$.green} \u2713 Verification phase complete${N?" (loop-back exhausted)":" (PASS)"}${$.reset}`),!N){Ze(de,Ie,Y,je,Ke),Ce(T),wt(T);break e}}}if(mr()&&k&&de===0)if(ru++,ru>2)j(`${$.yellow} \u26A0 Plan accepted despite no file reads (rejection loop cap reached)${$.reset}`);else{let F={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.).
1704
1704
 
1705
- 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.`};T.push(F),v.push(F),j(`${y.yellow} \u26A0 Plan rejected (${ru}/2): no files read \u2014 forcing investigation${y.reset}`);continue}if(mr()&&k){let F=(_t||Ne||"").trim();PN(F),gL(F);let P=NN(F);if(P.length>0){let q=T.find(Ee=>Ee.role==="user"),N=typeof q?.content=="string"?q.content.slice(0,120):"Task";LN(N,P);let U=P.length===1?"step":"steps",se=!1;if(process.stdout.isTTY&&process.stdin.isTTY&&!process.env.JEST_WORKER_ID){let{approvePlan:Ee,startExecution:fe,setPlanMode:B}=ps();process.stdout.write(`
1706
- ${y.cyan}${y.bold}Plan ready${y.reset} ${y.dim}(${P.length} ${U})${y.reset} ${y.green}[A]${y.reset}${y.dim}pprove${y.reset} ${y.yellow}[E]${y.reset}${y.dim}dit${y.reset} ${y.red}[R]${y.reset}${y.dim}eject${y.reset} ${y.dim}[\u21B5 = approve]:${y.reset} `);let we=process.stdin.isRaw,Je=await new Promise(at=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",vt=>{try{process.stdin.setRawMode(we||!1)}catch{}let Cn=vt.toString().toLowerCase()[0]||"\r";at(Cn)})});if(process.stdout.write(`
1707
- `),Je==="r")console.log(`${y.red}Plan rejected.${y.reset} Ask follow-up questions to refine.`);else if(Je==="e")console.log(`${y.yellow}Type /plan edit to open in editor, or give feedback.${y.reset}`);else if(Ee()){fe(),B(!1),nu(),console.log(`${y.green}${y.bold}Approved!${y.reset} Executing ${P.length} ${U}...`);let at=`[PLAN APPROVED \u2014 EXECUTE NOW]
1705
+ 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.`};T.push(F),v.push(F),j(`${$.yellow} \u26A0 Plan rejected (${ru}/2): no files read \u2014 forcing investigation${$.reset}`);continue}if(mr()&&k){let F=(_t||Ne||"").trim();PN(F),gL(F);let P=NN(F);if(P.length>0){let q=T.find(Ee=>Ee.role==="user"),N=typeof q?.content=="string"?q.content.slice(0,120):"Task";LN(N,P);let U=P.length===1?"step":"steps",se=!1;if(process.stdout.isTTY&&process.stdin.isTTY&&!process.env.JEST_WORKER_ID){let{approvePlan:Ee,startExecution:fe,setPlanMode:B}=ps();process.stdout.write(`
1706
+ ${$.cyan}${$.bold}Plan ready${$.reset} ${$.dim}(${P.length} ${U})${$.reset} ${$.green}[A]${$.reset}${$.dim}pprove${$.reset} ${$.yellow}[E]${$.reset}${$.dim}dit${$.reset} ${$.red}[R]${$.reset}${$.dim}eject${$.reset} ${$.dim}[\u21B5 = approve]:${$.reset} `);let we=process.stdin.isRaw,Je=await new Promise(at=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",vt=>{try{process.stdin.setRawMode(we||!1)}catch{}let Cn=vt.toString().toLowerCase()[0]||"\r";at(Cn)})});if(process.stdout.write(`
1707
+ `),Je==="r")console.log(`${$.red}Plan rejected.${$.reset} Ask follow-up questions to refine.`);else if(Je==="e")console.log(`${$.yellow}Type /plan edit to open in editor, or give feedback.${$.reset}`);else if(Ee()){fe(),B(!1),nu(),console.log(`${$.green}${$.bold}Approved!${$.reset} Executing ${P.length} ${U}...`);let at=`[PLAN APPROVED \u2014 EXECUTE NOW]
1708
1708
 
1709
1709
  Implement the following plan step by step. All tools are now available.
1710
1710
 
1711
1711
  ${F}`;T.push({role:"user",content:at}),v.push({role:"user",content:at}),se=!0}}else console.log(`
1712
- ${y.cyan}${y.bold}Plan ready${y.reset} ${y.dim}(${P.length} ${U} extracted).${y.reset} Type ${y.cyan}/plan approve${y.reset}${y.dim} to execute, or ${y.reset}${y.cyan}/plan edit${y.reset}${y.dim} to review.${y.reset}`);if(se){_&&(_.stop(),_=null),Ct--;continue}}else{let q=!1;if(process.stdout.isTTY&&process.stdin.isTTY&&!process.env.JEST_WORKER_ID){let{approvePlan:U,startExecution:se,setPlanMode:Se}=ps();process.stdout.write(`
1713
- ${y.cyan}${y.bold}Plan ready.${y.reset} ${y.green}[A]${y.reset}${y.dim}pprove${y.reset} ${y.red}[R]${y.reset}${y.dim}eject${y.reset} ${y.dim}[\u21B5 = approve]:${y.reset} `);let Ee=process.stdin.isRaw,fe=await new Promise(B=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",we=>{try{process.stdin.setRawMode(Ee||!1)}catch{}B(we.toString().toLowerCase()[0]||"\r")})});if(process.stdout.write(`
1714
- `),fe==="r")console.log(`${y.red}Plan rejected.${y.reset} Ask follow-up questions to refine.`);else if(U()){se(),Se(!1),nu(),console.log(`${y.green}${y.bold}Approved!${y.reset} Executing...`);let we=`[PLAN APPROVED \u2014 EXECUTE NOW]
1712
+ ${$.cyan}${$.bold}Plan ready${$.reset} ${$.dim}(${P.length} ${U} extracted).${$.reset} Type ${$.cyan}/plan approve${$.reset}${$.dim} to execute, or ${$.reset}${$.cyan}/plan edit${$.reset}${$.dim} to review.${$.reset}`);if(se){_&&(_.stop(),_=null),Ct--;continue}}else{let q=!1;if(process.stdout.isTTY&&process.stdin.isTTY&&!process.env.JEST_WORKER_ID){let{approvePlan:U,startExecution:se,setPlanMode:Se}=ps();process.stdout.write(`
1713
+ ${$.cyan}${$.bold}Plan ready.${$.reset} ${$.green}[A]${$.reset}${$.dim}pprove${$.reset} ${$.red}[R]${$.reset}${$.dim}eject${$.reset} ${$.dim}[\u21B5 = approve]:${$.reset} `);let Ee=process.stdin.isRaw,fe=await new Promise(B=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",we=>{try{process.stdin.setRawMode(Ee||!1)}catch{}B(we.toString().toLowerCase()[0]||"\r")})});if(process.stdout.write(`
1714
+ `),fe==="r")console.log(`${$.red}Plan rejected.${$.reset} Ask follow-up questions to refine.`);else if(U()){se(),Se(!1),nu(),console.log(`${$.green}${$.bold}Approved!${$.reset} Executing...`);let we=`[PLAN APPROVED \u2014 EXECUTE NOW]
1715
1715
 
1716
1716
  Implement the following plan step by step. All tools are now available.
1717
1717
 
1718
1718
  ${getPlanContent()||At.content}`;T.push({role:"user",content:we}),v.push({role:"user",content:we}),q=!0}}else console.log(`
1719
- ${y.cyan}${y.bold}Plan ready.${y.reset} ${y.dim}Type ${y.reset}${y.cyan}/plan approve${y.reset}${y.dim} to execute, or ask follow-up questions to refine.${y.reset}`);if(q){_&&(_.stop(),_=null),Ct--;continue}}}if(_&&(_.stop(),_=null),x(null),Ze(de,Ie,Y,je,Ke),ms&&Y.size>=3){let F=[...Y].map(se=>se.split("/").pop()).slice(0,8).join(", "),P=[...Y].some(se=>se.endsWith("package.json")),q=[...Y].some(se=>se.endsWith("requirements.txt")),N=[...Y].some(se=>se.endsWith("package-lock.json")||se.endsWith("yarn.lock")||se.endsWith("pnpm-lock.yaml")),U=P&&!N?"npm install not yet run":q?"pip install not yet run":null;Sa=`[Previous session created ${Y.size} files: ${F}`+(U?` \u2014 ${U}`:"")+". Use this context to answer follow-up questions without re-reading files.]"}if(ms&&!Gp&&de>0){let F=[...Y].some(B=>B.endsWith("package.json")),P=[...Y].some(B=>B.endsWith("requirements.txt")||B.endsWith("Pipfile")||B.endsWith("pyproject.toml")),q=[...Y].some(B=>B.endsWith("package-lock.json")||B.endsWith("yarn.lock")||B.endsWith("pnpm-lock.yaml")),N=T.flatMap(B=>{let we=Array.isArray(B.tool_calls)?B.tool_calls:[],Je=Array.isArray(B.content)?B.content.filter(at=>at?.type==="tool_use"):[];return[...we,...Je]}).filter(B=>{let we=B.function?.name||B.name||"";return we==="bash"||we==="Bash"}).map(B=>{try{let we=B.function?.arguments??B.input??{};return(typeof we=="string"?JSON.parse(we):we)?.command||""}catch{return""}}),U=N.some(B=>/pip\s+install|python\s+-m\s+venv/.test(B)),se=N.some(B=>/npm\s+install/.test(B)),Ee=[...Y].some(B=>/\/App\.(js|ts|jsx|tsx)$/.test(B))&&!F&&!se;if(P&&!U||F&&!q&&!se||Ee){Gp=!0;let B=[];P&&!U&&B.push("python -m venv venv && source venv/bin/activate && pip install -r requirements.txt"),Ee?B.push("create package.json for the React frontend (with react, react-dom, react-scripts dependencies), then run npm install"):F&&!q&&!se&&B.push("npm install");let we=`[FRAMEWORK \u2014 post-creation check] You wrote dependency files but never ran the installer. Run now: ${B.join(" && ")}. Verify it succeeds, fix any errors, then write a closing summary.`;j(`${y.dim} [post-creation] bootstrapping environment (${B.join(", ")})${y.reset}`),T.push({role:"user",content:we}),v.push({role:"user",content:we});continue}}let $e=(Y.size>0||nt>0)&&!Yu()&&Ip(_t||Ne||"")&&!jp(_t||Ne||""),ce=In&&!Vp(_t||Ne||"");if(de>0&&!n._isSummaryTurn&&(zl(_t)||$e||ce))try{j(`${y.dim} [post-turn] terse ending \u2014 requesting diagnosis/summary${y.reset}`);let F=ss.length>0?ss.join(" | "):qs.length>0?`post-edit read: ${qs.slice(0,8).join(", ")}`:"not run; state this explicitly and do not claim tests/build/checks passed",P=Ve&&Ve.command||"git status --short --branch",q=Ve&&String(Ve.raw||"").trim()||"(missing preflight output)",N=Ve&&Ve.branch||M_||"(unknown)",U=[...Y].slice(0,24).join(", ")||(nt>0?"files changed by shell commands":"(none)"),se=ni?"detected (git commit succeeded per bash output)":"not detected",Se=fu?"detected (git push succeeded per bash output)":xo?"attempted (see tool output)":"not detected",Ee=hr?`${Ea}
1719
+ ${$.cyan}${$.bold}Plan ready.${$.reset} ${$.dim}Type ${$.reset}${$.cyan}/plan approve${$.reset}${$.dim} to execute, or ask follow-up questions to refine.${$.reset}`);if(q){_&&(_.stop(),_=null),Ct--;continue}}}if(_&&(_.stop(),_=null),x(null),Ze(de,Ie,Y,je,Ke),ms&&Y.size>=3){let F=[...Y].map(se=>se.split("/").pop()).slice(0,8).join(", "),P=[...Y].some(se=>se.endsWith("package.json")),q=[...Y].some(se=>se.endsWith("requirements.txt")),N=[...Y].some(se=>se.endsWith("package-lock.json")||se.endsWith("yarn.lock")||se.endsWith("pnpm-lock.yaml")),U=P&&!N?"npm install not yet run":q?"pip install not yet run":null;Sa=`[Previous session created ${Y.size} files: ${F}`+(U?` \u2014 ${U}`:"")+". Use this context to answer follow-up questions without re-reading files.]"}if(ms&&!Gp&&de>0){let F=[...Y].some(B=>B.endsWith("package.json")),P=[...Y].some(B=>B.endsWith("requirements.txt")||B.endsWith("Pipfile")||B.endsWith("pyproject.toml")),q=[...Y].some(B=>B.endsWith("package-lock.json")||B.endsWith("yarn.lock")||B.endsWith("pnpm-lock.yaml")),N=T.flatMap(B=>{let we=Array.isArray(B.tool_calls)?B.tool_calls:[],Je=Array.isArray(B.content)?B.content.filter(at=>at?.type==="tool_use"):[];return[...we,...Je]}).filter(B=>{let we=B.function?.name||B.name||"";return we==="bash"||we==="Bash"}).map(B=>{try{let we=B.function?.arguments??B.input??{};return(typeof we=="string"?JSON.parse(we):we)?.command||""}catch{return""}}),U=N.some(B=>/pip\s+install|python\s+-m\s+venv/.test(B)),se=N.some(B=>/npm\s+install/.test(B)),Ee=[...Y].some(B=>/\/App\.(js|ts|jsx|tsx)$/.test(B))&&!F&&!se;if(P&&!U||F&&!q&&!se||Ee){Gp=!0;let B=[];P&&!U&&B.push("python -m venv venv && source venv/bin/activate && pip install -r requirements.txt"),Ee?B.push("create package.json for the React frontend (with react, react-dom, react-scripts dependencies), then run npm install"):F&&!q&&!se&&B.push("npm install");let we=`[FRAMEWORK \u2014 post-creation check] You wrote dependency files but never ran the installer. Run now: ${B.join(" && ")}. Verify it succeeds, fix any errors, then write a closing summary.`;j(`${$.dim} [post-creation] bootstrapping environment (${B.join(", ")})${$.reset}`),T.push({role:"user",content:we}),v.push({role:"user",content:we});continue}}let $e=(Y.size>0||nt>0)&&!Yu()&&Ip(_t||Ne||"")&&!jp(_t||Ne||""),ce=In&&!Vp(_t||Ne||"");if(de>0&&!n._isSummaryTurn&&(zl(_t)||$e||ce))try{j(`${$.dim} [post-turn] terse ending \u2014 requesting diagnosis/summary${$.reset}`);let F=ss.length>0?ss.join(" | "):qs.length>0?`post-edit read: ${qs.slice(0,8).join(", ")}`:"not run; state this explicitly and do not claim tests/build/checks passed",P=Ve&&Ve.command||"git status --short --branch",q=Ve&&String(Ve.raw||"").trim()||"(missing preflight output)",N=Ve&&Ve.branch||M_||"(unknown)",U=[...Y].slice(0,24).join(", ")||(nt>0?"files changed by shell commands":"(none)"),se=ni?"detected (git commit succeeded per bash output)":"not detected",Se=fu?"detected (git push succeeded per bash output)":xo?"attempted (see tool output)":"not detected",Ee=hr?`${Ea}
1720
1720
  ${hr}`:"(not checked in this run)",fe=In?["Write a final automation report using EXACT labels (one per line):",`Preflight: ${P}`,"Preflight output: (paste exactly; do not paraphrase)",q,`Branch: ${N}`,"Chosen task: (what you actually did; or `no safe task found`)",`Files changed: ${U}`,`Verification: ${F}`,`Commit: ${se}`,`Push: ${Se}`,`Final git status: ${Ee}`,"Remaining risk: (if any; otherwise `none`)","","Hard rules: do not claim verification/commit/push/git status checks without evidence from tool output. If unknown, write unknown."].join(`
1721
1721
  `):Y.size>0||nt>0?["Write a closing summary (3+ sentences) with:",`- changed files: ${[...Y].slice(0,8).join(", ")||"files changed by shell commands"}`,`- verification: ${F}`,"- remaining risk or follow-up, if any."].join(`
1722
1722
  `):"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.",B=[...v,{role:"user",content:fe}],Je=((await Yl(B,[],{}))?.content||"").trim();Je&&(console.log(`
1723
- ${Je}`),T.push({role:"user",content:fe},{role:"assistant",content:Je}))}catch{}Ce(T),wt(T),await uc();return}de++,gu++,de>=1&&(Ae=!1),yt+=xt.length;{let k=Ep(Qn());Number.isFinite(k)&&yt>=k&&(lc=!0)}for(let k of xt){let w=k.function.name;Ie.set(w,(Ie.get(w)||0)+1)}if(yt>=30&&!A_){A_=!0,j(`${y.yellow} \u26A0 Tool budget warning: ${yt} tool calls used \u2014 nudging model to wrap up${y.reset}`);let k={role:"user",content:"[SYSTEM] \u26A0 You have used "+yt+" 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."};T.push(k),v.push(k)}let He=await Promise.all(xt.map(k=>yL(k)));if(Ju){let k=new Set(["read_file","grep","search_files","glob","list_directory","ssh_exec","find_files"]);for(let w of He)!w.canExecute||!k.has(w.fnName)||(w.canExecute=!1,w.errorResult={role:"tool",content:"BLOCKED: You already have enough evidence to produce the requested summary/document. Write the deliverable now and stop reading more files.",tool_call_id:w.callId})}if(et&&be&&Pe==="plan"&&(Yt||Sn>=di))for(let k of He)k.canExecute&&(k.canExecute=!1,k.errorResult={role:"tool",content:Ns({blocked:!0}),tool_call_id:k.callId});if(Is&&be&&Pe==="implement"){let k=new Set(["read_file","grep","search_files","glob","list_directory","find_files"]);for(let w of He)w.canExecute&&(N_(w)||k.has(w.fnName)&&(w.canExecute=!1,w.errorResult={role:"tool",content:"BLOCKED: code was already edited. Run a narrow verification command now, such as npm test, npm run build, npm run lint, or the focused test from the plan. Do not read or search more files before verification.",tool_call_id:w.callId}))}if(et&&be&&Pe==="implement"&&Yt&&Y.size===0)for(let k of He){if(!k.canExecute)continue;let w=sn(k.args?.path||""),W=k.fnName==="write_file"||k.fnName==="edit_file"||k.fnName==="patch_file",H=w&&(no.some(Kt=>sn(Kt.file)===w)||qa.includes(w)),oe=new Set(no.map(Kt=>sn(Kt.file)).filter(Boolean));for(let Kt of X_(qa)){let Io=sn(Kt);Io&&!gn.has(Io)&&!/\.(md|mdx|txt|rst|adoc)$/i.test(Io)&&oe.add(Io)}H&&oe.add(w);let $e=k.fnName==="read_file"&&w&&(H||!gn.has(w))&&(k.args?.line_start||k.args?.line_end),ce=$e?`${w}:${k.args?.line_start||""}:${k.args?.line_end||""}`:"",F=$e&&(Gt.get(k.args?.path)||0)>0,P=RL(k.fnName,k.args||{}),q=[...Gt.keys()].map(Kt=>sn(Kt)),N=String(k.args?.command||""),U=k.fnName==="bash"&&/^grep\s+-n\b/.test(N.trim())&&q.some(Kt=>Kt&&N.includes(Kt))&&!/[;&|`$]/.test(N)&&!/(^|\s)[<>]/.test(N),se=Gt.size>0&&(P||U),Se=sn(k.args?.path||k.args?.cwd||""),Ee=String(k.args?.pattern||k.args?.glob||k.args?.query||k.args?.search||k.args?.include||k.args?.file_pattern||""),fe=qn>0&&(k.fnName==="grep"||k.fnName==="search_files")&&Se&&oe.has(Se)&&Ee.trim().length>0,B=qn>0&&k.fnName==="bash"&&/^grep\s+-n\b/.test(N.trim())&&[...oe].some(Kt=>Kt&&N.includes(Kt))&&!/[;&|`$]/.test(N)&&!/(^|\s)[<>]/.test(N),we=$e&&qn>0&&oe.has(w)&&ce&&!mi.has(ce),Je=we&&(Na.get(w)||0)>0&&$u<xL,at=qn>0&&yu<kL&&(fe||B||we);if(W)continue;if($e&&qn<1||F){F||(qn++,ce&&mi.add(ce));continue}if(Je){$u++,k._boundedBacklogPostGrepRead=!0,ce&&mi.add(ce);continue}if(at){yu++,ce&&mi.add(ce);continue}if(se)continue;if(P&&qn===0&&Pa<O_){Pa++;continue}let vt=k.fnName==="read_file"&&w&&gn.has(w)&&!H,Cn=$e&&qn>=1,Mt=P&&Pa>=O_;k.canExecute=!1;let xs=qn>0;k.errorResult={role:"tool",content:xs?"BLOCKED: the planned implementation file has already been read. Make the scoped edit now with edit_file or patch_file; do not run git, search, or read more before editing.":vt?"BLOCKED: implementation phase has already completed backlog review. Do not re-read backlog files. Edit the concrete implementation file from the accepted plan now.":Cn?"BLOCKED: implementation phase has already read enough targeted code context. Make the scoped edit now with edit_file or patch_file; do not read more before editing.":Mt?"BLOCKED: implementation phase has already used enough path discovery. Read the concrete implementation file with line_start/line_end or make the scoped edit now.":"BLOCKED: implementation phase must not use bash/git or broad reading. Use a targeted glob/search/list_directory call only to locate the concrete implementation file, then read it with line_start/line_end or edit it.",tool_call_id:k.callId}}{let k=hs(v,xn()),w=k.percentage,W=He.some(ce=>ce.canExecute&&ce.fnName==="read_file"&&!ce.args?.line_end),H=He.filter(ce=>ce.canExecute&&ce.fnName==="read_file"&&ce.args?.path&&Os(xr,ce.args.path)>=1&&!ce.args?.line_start).map(ce=>ce.args.path.split("/").slice(-2).join("/")),oe=H.length>0;if(w>=70&&W&&Xu<70||w>=85&&Xu<85||oe){Xu=w;let ce=w>=85?"URGENT":"WARNING",F;oe?(ce="WARNING",F=`Full-file read of ${H.join(", ")} already done \u2014 use line_start/line_end for specific sections instead.`):W?F=`Unbounded read at ${Math.round(w)}% context \u2014 use line_start/line_end to avoid overflow.`:F="Use targeted reads (line_start/line_end) to save space.";let P={role:"user",content:`[SYSTEM ${ce}] Context ${Math.round(w)}% used (${k.used}/${k.limit} tokens). ${F}`};if(T.push(P),v.push(P),w>=85){let q=oe?` (re-read of: ${H.join(", ")})`:"";j(`${y.yellow} \u26A0 Context ${Math.round(w)}% used \u2014 agent warned to use targeted reads${q}${y.reset}`)}}}let ed=new Map;for(let k of He){if(!k.canExecute||k.fnName!=="read_file")continue;let w=k.args?.path;if(!w)continue;let W=Os(xr,w),H=ed.get(w)||0,oe=W+H,$e=_o.has(w),ce=k.args?.line_start!=null,F=Gt.get(w)||0,P=F>0,q=2;if(!$e&&oe>=vr){let N=w.split("/").slice(-2).join("/"),U=(gr.get(w)||0)+1;if(gr.set(w,U),U===1)j(`${y.red} \u2716 Blocked: "${N}" read ${oe}\xD7 \u2014 hard cap (${vr}) reached${y.reset}`);else if(U===2){j(`${y.red} \u2716 Escalated block: "${N}" \u2014 model ignored BLOCKED, injecting system warning${y.reset}`);let se={role:"user",content:`[SYSTEM WARNING] You already received a BLOCKED error for read_file("${w}") and tried again anyway. This file has reached its read cap (${vr}\xD7). Do NOT attempt to read it again. Use grep_search to find specific content, or proceed with what you already know.`};T.push(se),v.push(se)}k.canExecute=!1,k.errorResult={role:"tool",content:`BLOCKED: read_file("${w}") denied \u2014 file already read ${oe}\xD7 (hard cap: ${vr}). You have seen enough of this file. Use grep to find specific content or proceed with what you know.`,tool_call_id:k.callId}}else if(!$e&&oe>=1&&ce)if(P&&F<=q){let N=w.split("/").slice(-2).join("/");console.log(`${y.cyan} \u21A9 Targeted re-read: "${N}" (line_start=${k.args.line_start}) \u2014 edit recovery #${F}${y.reset}`),Gt.set(w,F-1)}else if(P&&F>q){let N=w.split("/").slice(-2).join("/");j(`${y.red} \u2716 Edit recovery blocked: "${N}" \u2014 ${q} recovery reads already used. Use grep to find the exact line numbers, then retry.${y.reset}`),k.canExecute=!1,k.errorResult={role:"tool",content:`BLOCKED: read_file("${w}") denied \u2014 edit recovery budget exhausted (${q} 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:k.callId}}else{let N=parseInt(k.args.line_start,10)||1,U=parseInt(k.args.line_end,10)||N+350,se=to.get(w)||[],Se=!1;for(let[Ee,fe]of se){let B=Math.max(N,Ee),we=Math.min(U,fe);if(we>B){let Je=we-B,at=U-N||1,vt=fe-Ee||1,Cn=Je/vt>=.7&&Je/at<.7,Mt=U-N<=xv;if(Je>=at||!Mt&&(Je/at>=.7||Je/vt>=.7)){let Kt=w.split("/").slice(-2).join("/"),Io=`${w}:${N}-${U}`,Cr=(mu.get(Io)||0)+1;if(mu.set(Io,Cr),j(Cn?`${y.red} \u2716 Blocked superread: "${Kt}" lines ${N}-${U} subsumes already-read ${Ee}-${fe} \u2014 use line_start=${fe+1} to skip known content (block #${Cr})${y.reset}`:`${y.red} \u2716 Blocked duplicate read: "${Kt}" lines ${N}-${U} (\u226570% overlap with lines ${Ee}-${fe} already in context, block #${Cr})${y.reset}`),Cr>=2){j(`${y.red} \u2716 Escalated range-block: "${Kt}" lines ${N}-${U} \u2014 model ignored BLOCKED, injecting system warning${y.reset}`);let gm={role:"user",content:Cn?`[SYSTEM] Read blocked ${Cr}\xD7 for read_file("${w}", lines ${N}-${U}). Lines ${Ee}-${fe} were already read. Use line_start=${fe+1} to read only new content, or use grep_search for specific lines.`:`[SYSTEM] Read blocked ${Cr}\xD7 for read_file("${w}", lines ${N}-${U}). Lines ${Ee}-${fe} were already read and will NOT change. Use grep_search to find specific content instead.`};T.push(gm),v.push(gm)}k.canExecute=!1,k.errorResult={role:"tool",content:Cn?`BLOCKED: read_file("${w}", lines ${N}-${U}) re-reads lines ${Ee}-${fe} already in context. Use line_start=${fe+1} to read only the new content beyond line ${fe}.`:`BLOCKED: read_file("${w}", lines ${N}-${U}) is a duplicate \u2014 lines ${Ee}-${fe} are already in your context (\u226570% overlap). Use grep to find specific content instead of re-reading.`,tool_call_id:k.callId},Se=!0;break}}}if(!Se){let Ee=se.length,fe=2;if(Ee>=3&&!k._boundedBacklogPostGrepRead){let we=w.split("/").slice(-2).join("/");j(`${y.red} \u2716 Blocked file-scroll: "${we}" \u2014 ${Ee} sections already read. Use grep to find specific content.${y.reset}`);let Je=Os(zu,w)>=ic;k.canExecute=!1,k.errorResult={role:"tool",content:Je?`BLOCKED: read_file("${w}") denied \u2014 you have already read ${Ee} 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("${w}") denied \u2014 you have already read ${Ee} 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:k.callId}}else Ee>=fe&&(k._scrollWarn={sectionCount:Ee+1,path:w})}}else if(!$e&&oe>=1){let N=Gt.get(w)||0;if(N>0){let U=w.split("/").slice(-2).join("/");console.log(`${y.cyan} \u21A9 Full re-read: "${U}" \u2014 test-failure recovery (${N} remaining)${y.reset}`);let se=N-1;se<=0?Gt.delete(w):Gt.set(w,se)}else{let U=w.split("/").slice(-2).join("/"),se=(gr.get(w)||0)+1;if(gr.set(w,se),se===1)j(`${y.red} \u2716 Blocked unbounded re-read: "${U}" \u2014 already in context. Use line_start/line_end for specific sections.${y.reset}`);else if(se===2){j(`${y.red} \u2716 Escalated block: "${U}" \u2014 model ignored unbounded re-read block, injecting system warning${y.reset}`);let Se={role:"user",content:`[SYSTEM] read_file("${w}") 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.`};T.push(Se),v.push(Se)}k.canExecute=!1,k.errorResult={role:"tool",content:`BLOCKED: read_file("${w}") denied \u2014 file already in context (read ${oe}\xD7). Use line_start/line_end to read a specific section instead of the full file.`,tool_call_id:k.callId}}}k.canExecute&&ed.set(w,(ed.get(w)||0)+1)}if(wo>=3)for(let k of He)k.canExecute&&(k.fnName!=="read_file"&&k.fnName!=="edit_file"||(j(`${y.red} \u2716 Blocked ${k.fnName} \u2014 ${wo} consecutive file-not-found errors, must search first${y.reset}`),k.canExecute=!1,k.errorResult={role:"tool",content:`BLOCKED: ${wo} 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:k.callId}));for(let k of He){if(!k.canExecute||k.fnName!=="bash")continue;let w=(k.args?.command||"").trim();if(/^\s*ls(\s+-[a-zA-Z]+)*(\s+\S+)?\s*$/.test(w)&&!/npm|yarn|pnpm|make|git/.test(w)){j(`${y.red} \u2716 Blocked bash ls \u2014 use list_directory tool instead${y.reset}`),k.canExecute=!1,k.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:k.callId};continue}/\bfind\s+[\S.]/.test(w)&&!/git\s|npm\s|yarn\s|-exec\s+\S|-execdir/.test(w)&&(j(`${y.red} \u2716 Blocked bash find \u2014 use glob tool with a pattern instead${y.reset}`),k.canExecute=!1,k.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:k.callId})}for(let k of He)k.canExecute&&(k.fnName!=="ssh_exec"&&k.fnName!=="bash"||/\bsed\s+-n\b/.test(k.args?.command||"")&&(j(`${y.red} \u2716 Blocked sed -n: use grep -n "pattern" <file> | head -30 instead${y.reset}`),k.canExecute=!1,k.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:k.callId}));for(let k of He){if(!k.canExecute||k.fnName!=="write_file")continue;let w=k.args?.path,W=k.args?.content||"";if(w)try{let H=require("fs"),oe=require("path").resolve(process.cwd(),w);if(H.existsSync(oe)){let $e=H.statSync(oe).size,ce=Buffer.byteLength(W,"utf8"),F=$e>0?ce/$e:1,P=Jp(ve),q=Jp(w);if(Xp(ve)&&(P.includes(q)||P.includes(`./${q}`)))continue;if(F<.6&&$e>200){let U=w.split("/").slice(-2).join("/");console.log(`${y.red} \u2716 write_file shrink guard: "${U}" would shrink to ${Math.round(F*100)}% of original \u2014 likely context loss${y.reset}`),k.canExecute=!1,k.errorResult={role:"tool",content:`BLOCKED: write_file("${w}") denied \u2014 new content is only ${Math.round(F*100)}% of current file size (${$e} \u2192 ${ce} 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:k.callId}}}}catch{}}let fm=new Map;for(let k of He){if(!k.canExecute||k.fnName!=="grep")continue;let w=k.args?.path;if(!w)continue;let W=fm.get(w)||0,H=Os(zu,w)+W,oe=Os(xr,w)>=1,$e=oe?Math.min(3,ic):ic;if(H>=$e){let ce=w.split("/").slice(-2).join("/");j(`${y.red} \u2716 Blocked grep: "${ce}" grepped ${H}\xD7 with different patterns \u2014 flood threshold exceeded${y.reset}`);let F=Os(xr,w),P=F>=vr;if(P){let q={role:"user",content:`[SYSTEM] Both read_file and grep are now blocked for "${w}". You have already read ${F} sections and tried ${H} 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.`};T.push(q),v.push(q),j(`${y.red} \u2716 Deadlock detected: "${ce}" \u2014 both read and grep blocked, injecting deadlock-break${y.reset}`)}k.canExecute=!1,k.errorResult={role:"tool",content:P?`BLOCKED: grep("${w}") denied \u2014 ${H} 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.`:oe?`BLOCKED: grep("${w}") denied \u2014 file was already read and ${H} grep patterns tried. The content is already in your context; use it instead of searching again.`:`BLOCKED: grep("${w}") denied \u2014 ${H} patterns already tried. Work with the grep results already in your context.`,tool_call_id:k.callId}}k.canExecute&&fm.set(w,W+1)}let Cv=5,pm=new Map;for(let k of He){if(!k.canExecute||k.fnName!=="ssh_exec")continue;let W=(k.args?.command||"").replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),H=pm.get(W)||0,oe=Os(om,W)+H;oe>=Cv&&(j(`${y.yellow} \u26A0 Blocked ssh_exec: same command run ${oe}\xD7 \u2014 result already in context${y.reset}`),k.canExecute=!1,k.errorResult={role:"tool",content:`BLOCKED: ssh_exec denied \u2014 this command has already run ${oe} 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:k.callId}),k.canExecute&&pm.set(W,H+1)}if(Ln){let k=He.filter(H=>H.canExecute&&H.fnName==="ssh_exec"),w=He.some(H=>H.canExecute&&H.fnName!=="ssh_exec"),W=ze&&Be<3;if(k.length>0&&!w&&W&&au<1)Ln=!1,au++,Zn=Math.max(0,Si-2),j(`${y.dim} [dual-block deadlock: SSH storm relaxed \u2014 allowing 1 SSH call (relax ${au}/1)]${y.reset}`);else for(let H of k)H.canExecute=!1,H.errorResult={role:"tool",content:Zt?`BLOCKED: ssh_exec denied \u2014 SSH paused (${Si}+ calls). Root cause is known (${kn}). 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 (${Si}+ 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:H.callId}}let Av=pL(T,["browser_open","browser_screenshot","ssh_exec","service_logs","remote_agent"]);if((ze||it)&&!Av&&Be<3&&!Ln)for(let k of He){if(!k.canExecute||!["bash","read_file","find_files","list_directory","search_files","glob","grep"].includes(k.fnName))continue;Be++;{let H=xn(),{messages:oe}=As(v,H);v=oe}let w=ke?.matchedName?`${ke.matchedName} (${ke.matchedProfile?.host||"server"})`:ke?.url,W=ke?.shouldPreferSsh?`BLOCKED: ${k.fnName} denied \u2014 this looks like a live app/server issue. Inspect ${ke?.url} with browser_open or use ssh_exec on ${w} first, then return to local code if needed.`:`BLOCKED: ${k.fnName} denied \u2014 this looks like a live app issue. Inspect ${ke?.url} with browser_open first, then return to local code if needed.`;j(`${y.yellow} \u26A0 Runtime guard: blocking local ${k.fnName} \u2014 inspect the live app first${y.reset}`),k.canExecute=!1,k.errorResult={role:"tool",content:W,tool_call_id:k.callId};break}if(!be&&jn&&ms&&ns>=1){let k=["read_file","grep","search_files","glob","list_directory","find_files"];for(let w of He)w.canExecute&&k.includes(w.fnName)&&(j(`${y.red} \u2716 Creation hard-block: ${w.fnName} denied \u2014 cap fired, files already written${y.reset}`),w.canExecute=!1,w.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:w.callId})}if(ko>=0){let k=He.filter(w=>w.canExecute).length;if(k>0&&(ko-=k,ko<0))if(!lu&&Y.size>cu){lu=!0,ko=5,j(`${y.green} \u2713 Post-wipe progress detected (${Y.size-cu} files modified) \u2014 granting 5 bonus tool calls${y.reset}`);let w={role:"user",content:"[SYSTEM] Progress detected \u2014 5 bonus tool calls granted. Budget: 5 remaining."};T.push(w),v.push(w)}else{j(`${y.yellow} \u26A0 Post-wipe tool budget exhausted (advisory) \u2014 nudging model to wrap up${y.reset}`);let w={role:"user",content:"[SYSTEM] You've used your post-wipe tool call budget. Consider wrapping up and summarizing what was accomplished, or continue if you need a few more steps to finish."};T.push(w),v.push(w),ko=-2}}let Ov=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 k of He){if(!k.canExecute||Ov.has(k.fnName))continue;let w=JSON.stringify(k.args||{}),W=`${k.fnName}|${w}`,H=Os(Up,W);H>=2?(j(`${y.red} \u2716 Blocked duplicate: ${k.fnName}(${w.substring(0,80)}) \u2014 called ${H+1}\xD7 with identical args${y.reset}`),k.canExecute=!1,k.errorResult={role:"tool",content:`BLOCKED: ${k.fnName}() with these exact arguments has already been called ${H}\xD7 \u2014 the result is already in your context. Use the existing output instead of repeating the same call.`,tool_call_id:k.callId}):H===1&&j(`${y.yellow} \u26A0 Duplicate tool call: ${k.fnName}(${w.substring(0,80)}) \u2014 2nd call with identical args${y.reset}`),ur(Up,W)}{let k=new Set;for(let w of He){if(!w.canExecute||!["edit_file","patch_file"].includes(w.fnName))continue;let W=w.args?.path;W&&(k.has(W)?(w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: "${W}" is already being edited in this batch. Finish one edit first, then re-read the changed section before the next one.`,tool_call_id:w.callId},j(`${y.yellow} \u26A0 Map-first gate: blocked duplicate same-batch edit of "${W.split("/").slice(-1)[0]}"${y.reset}`)):ws.has(W)&&!_o.has(W)?(w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: "${W}" was already edited \u2014 re-read the changed section first (read_file with line_start/line_end) before making another edit. The file content has changed and your previous read is stale.`,tool_call_id:w.callId},j(`${y.yellow} \u26A0 Map-first gate: blocked re-edit of "${W.split("/").slice(-1)[0]}" \u2014 re-read required${y.reset}`)):k.add(W))}}let Ti=_?{skipSpinner:!0,skipSummaries:!0}:{},Mv=He.some(k=>k.fnName==="ask_user"),hm=!Ti.skipSummaries&&!Ae,Yn=null,Rr=null;if(hm&&!Mv){if(Ae=!0,Ti.skipSpinner=!0,process.stdout.isTTY){global._nexFooter&&(Rr=Math.min(global._nexFooter._lastOutputRow+1,global._nexFooter._scrollEnd));let k=$a(He,de,!1,0),w=$a(He,de,!1);process.stdout.write(`${de>1?`
1723
+ ${Je}`),T.push({role:"user",content:fe},{role:"assistant",content:Je}))}catch{}Ce(T),wt(T),await uc();return}de++,gu++,de>=1&&(Ae=!1),yt+=xt.length;{let k=Ep(Qn());Number.isFinite(k)&&yt>=k&&(lc=!0)}for(let k of xt){let w=k.function.name;Ie.set(w,(Ie.get(w)||0)+1)}if(yt>=30&&!A_){A_=!0,j(`${$.yellow} \u26A0 Tool budget warning: ${yt} tool calls used \u2014 nudging model to wrap up${$.reset}`);let k={role:"user",content:"[SYSTEM] \u26A0 You have used "+yt+" 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."};T.push(k),v.push(k)}let He=await Promise.all(xt.map(k=>yL(k)));if(Ju){let k=new Set(["read_file","grep","search_files","glob","list_directory","ssh_exec","find_files"]);for(let w of He)!w.canExecute||!k.has(w.fnName)||(w.canExecute=!1,w.errorResult={role:"tool",content:"BLOCKED: You already have enough evidence to produce the requested summary/document. Write the deliverable now and stop reading more files.",tool_call_id:w.callId})}if(et&&be&&Pe==="plan"&&(Yt||Sn>=di))for(let k of He)k.canExecute&&(k.canExecute=!1,k.errorResult={role:"tool",content:Ns({blocked:!0}),tool_call_id:k.callId});if(Is&&be&&Pe==="implement"){let k=new Set(["read_file","grep","search_files","glob","list_directory","find_files"]);for(let w of He)w.canExecute&&(N_(w)||k.has(w.fnName)&&(w.canExecute=!1,w.errorResult={role:"tool",content:"BLOCKED: code was already edited. Run a narrow verification command now, such as npm test, npm run build, npm run lint, or the focused test from the plan. Do not read or search more files before verification.",tool_call_id:w.callId}))}if(et&&be&&Pe==="implement"&&Yt&&Y.size===0)for(let k of He){if(!k.canExecute)continue;let w=sn(k.args?.path||""),W=k.fnName==="write_file"||k.fnName==="edit_file"||k.fnName==="patch_file",H=w&&(no.some(Kt=>sn(Kt.file)===w)||qa.includes(w)),oe=new Set(no.map(Kt=>sn(Kt.file)).filter(Boolean));for(let Kt of X_(qa)){let Io=sn(Kt);Io&&!gn.has(Io)&&!/\.(md|mdx|txt|rst|adoc)$/i.test(Io)&&oe.add(Io)}H&&oe.add(w);let $e=k.fnName==="read_file"&&w&&(H||!gn.has(w))&&(k.args?.line_start||k.args?.line_end),ce=$e?`${w}:${k.args?.line_start||""}:${k.args?.line_end||""}`:"",F=$e&&(Gt.get(k.args?.path)||0)>0,P=RL(k.fnName,k.args||{}),q=[...Gt.keys()].map(Kt=>sn(Kt)),N=String(k.args?.command||""),U=k.fnName==="bash"&&/^grep\s+-n\b/.test(N.trim())&&q.some(Kt=>Kt&&N.includes(Kt))&&!/[;&|`$]/.test(N)&&!/(^|\s)[<>]/.test(N),se=Gt.size>0&&(P||U),Se=sn(k.args?.path||k.args?.cwd||""),Ee=String(k.args?.pattern||k.args?.glob||k.args?.query||k.args?.search||k.args?.include||k.args?.file_pattern||""),fe=qn>0&&(k.fnName==="grep"||k.fnName==="search_files")&&Se&&oe.has(Se)&&Ee.trim().length>0,B=qn>0&&k.fnName==="bash"&&/^grep\s+-n\b/.test(N.trim())&&[...oe].some(Kt=>Kt&&N.includes(Kt))&&!/[;&|`$]/.test(N)&&!/(^|\s)[<>]/.test(N),we=$e&&qn>0&&oe.has(w)&&ce&&!mi.has(ce),Je=we&&(Na.get(w)||0)>0&&$u<xL,at=qn>0&&yu<kL&&(fe||B||we);if(W)continue;if($e&&qn<1||F){F||(qn++,ce&&mi.add(ce));continue}if(Je){$u++,k._boundedBacklogPostGrepRead=!0,ce&&mi.add(ce);continue}if(at){yu++,ce&&mi.add(ce);continue}if(se)continue;if(P&&qn===0&&Pa<O_){Pa++;continue}let vt=k.fnName==="read_file"&&w&&gn.has(w)&&!H,Cn=$e&&qn>=1,Mt=P&&Pa>=O_;k.canExecute=!1;let xs=qn>0;k.errorResult={role:"tool",content:xs?"BLOCKED: the planned implementation file has already been read. Make the scoped edit now with edit_file or patch_file; do not run git, search, or read more before editing.":vt?"BLOCKED: implementation phase has already completed backlog review. Do not re-read backlog files. Edit the concrete implementation file from the accepted plan now.":Cn?"BLOCKED: implementation phase has already read enough targeted code context. Make the scoped edit now with edit_file or patch_file; do not read more before editing.":Mt?"BLOCKED: implementation phase has already used enough path discovery. Read the concrete implementation file with line_start/line_end or make the scoped edit now.":"BLOCKED: implementation phase must not use bash/git or broad reading. Use a targeted glob/search/list_directory call only to locate the concrete implementation file, then read it with line_start/line_end or edit it.",tool_call_id:k.callId}}{let k=hs(v,xn()),w=k.percentage,W=He.some(ce=>ce.canExecute&&ce.fnName==="read_file"&&!ce.args?.line_end),H=He.filter(ce=>ce.canExecute&&ce.fnName==="read_file"&&ce.args?.path&&Os(xr,ce.args.path)>=1&&!ce.args?.line_start).map(ce=>ce.args.path.split("/").slice(-2).join("/")),oe=H.length>0;if(w>=70&&W&&Xu<70||w>=85&&Xu<85||oe){Xu=w;let ce=w>=85?"URGENT":"WARNING",F;oe?(ce="WARNING",F=`Full-file read of ${H.join(", ")} already done \u2014 use line_start/line_end for specific sections instead.`):W?F=`Unbounded read at ${Math.round(w)}% context \u2014 use line_start/line_end to avoid overflow.`:F="Use targeted reads (line_start/line_end) to save space.";let P={role:"user",content:`[SYSTEM ${ce}] Context ${Math.round(w)}% used (${k.used}/${k.limit} tokens). ${F}`};if(T.push(P),v.push(P),w>=85){let q=oe?` (re-read of: ${H.join(", ")})`:"";j(`${$.yellow} \u26A0 Context ${Math.round(w)}% used \u2014 agent warned to use targeted reads${q}${$.reset}`)}}}let ed=new Map;for(let k of He){if(!k.canExecute||k.fnName!=="read_file")continue;let w=k.args?.path;if(!w)continue;let W=Os(xr,w),H=ed.get(w)||0,oe=W+H,$e=_o.has(w),ce=k.args?.line_start!=null,F=Gt.get(w)||0,P=F>0,q=2;if(!$e&&oe>=vr){let N=w.split("/").slice(-2).join("/"),U=(gr.get(w)||0)+1;if(gr.set(w,U),U===1)j(`${$.red} \u2716 Blocked: "${N}" read ${oe}\xD7 \u2014 hard cap (${vr}) reached${$.reset}`);else if(U===2){j(`${$.red} \u2716 Escalated block: "${N}" \u2014 model ignored BLOCKED, injecting system warning${$.reset}`);let se={role:"user",content:`[SYSTEM WARNING] You already received a BLOCKED error for read_file("${w}") and tried again anyway. This file has reached its read cap (${vr}\xD7). Do NOT attempt to read it again. Use grep_search to find specific content, or proceed with what you already know.`};T.push(se),v.push(se)}k.canExecute=!1,k.errorResult={role:"tool",content:`BLOCKED: read_file("${w}") denied \u2014 file already read ${oe}\xD7 (hard cap: ${vr}). You have seen enough of this file. Use grep to find specific content or proceed with what you know.`,tool_call_id:k.callId}}else if(!$e&&oe>=1&&ce)if(P&&F<=q){let N=w.split("/").slice(-2).join("/");console.log(`${$.cyan} \u21A9 Targeted re-read: "${N}" (line_start=${k.args.line_start}) \u2014 edit recovery #${F}${$.reset}`),Gt.set(w,F-1)}else if(P&&F>q){let N=w.split("/").slice(-2).join("/");j(`${$.red} \u2716 Edit recovery blocked: "${N}" \u2014 ${q} recovery reads already used. Use grep to find the exact line numbers, then retry.${$.reset}`),k.canExecute=!1,k.errorResult={role:"tool",content:`BLOCKED: read_file("${w}") denied \u2014 edit recovery budget exhausted (${q} 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:k.callId}}else{let N=parseInt(k.args.line_start,10)||1,U=parseInt(k.args.line_end,10)||N+350,se=to.get(w)||[],Se=!1;for(let[Ee,fe]of se){let B=Math.max(N,Ee),we=Math.min(U,fe);if(we>B){let Je=we-B,at=U-N||1,vt=fe-Ee||1,Cn=Je/vt>=.7&&Je/at<.7,Mt=U-N<=xv;if(Je>=at||!Mt&&(Je/at>=.7||Je/vt>=.7)){let Kt=w.split("/").slice(-2).join("/"),Io=`${w}:${N}-${U}`,Cr=(mu.get(Io)||0)+1;if(mu.set(Io,Cr),j(Cn?`${$.red} \u2716 Blocked superread: "${Kt}" lines ${N}-${U} subsumes already-read ${Ee}-${fe} \u2014 use line_start=${fe+1} to skip known content (block #${Cr})${$.reset}`:`${$.red} \u2716 Blocked duplicate read: "${Kt}" lines ${N}-${U} (\u226570% overlap with lines ${Ee}-${fe} already in context, block #${Cr})${$.reset}`),Cr>=2){j(`${$.red} \u2716 Escalated range-block: "${Kt}" lines ${N}-${U} \u2014 model ignored BLOCKED, injecting system warning${$.reset}`);let gm={role:"user",content:Cn?`[SYSTEM] Read blocked ${Cr}\xD7 for read_file("${w}", lines ${N}-${U}). Lines ${Ee}-${fe} were already read. Use line_start=${fe+1} to read only new content, or use grep_search for specific lines.`:`[SYSTEM] Read blocked ${Cr}\xD7 for read_file("${w}", lines ${N}-${U}). Lines ${Ee}-${fe} were already read and will NOT change. Use grep_search to find specific content instead.`};T.push(gm),v.push(gm)}k.canExecute=!1,k.errorResult={role:"tool",content:Cn?`BLOCKED: read_file("${w}", lines ${N}-${U}) re-reads lines ${Ee}-${fe} already in context. Use line_start=${fe+1} to read only the new content beyond line ${fe}.`:`BLOCKED: read_file("${w}", lines ${N}-${U}) is a duplicate \u2014 lines ${Ee}-${fe} are already in your context (\u226570% overlap). Use grep to find specific content instead of re-reading.`,tool_call_id:k.callId},Se=!0;break}}}if(!Se){let Ee=se.length,fe=2;if(Ee>=3&&!k._boundedBacklogPostGrepRead){let we=w.split("/").slice(-2).join("/");j(`${$.red} \u2716 Blocked file-scroll: "${we}" \u2014 ${Ee} sections already read. Use grep to find specific content.${$.reset}`);let Je=Os(zu,w)>=ic;k.canExecute=!1,k.errorResult={role:"tool",content:Je?`BLOCKED: read_file("${w}") denied \u2014 you have already read ${Ee} 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("${w}") denied \u2014 you have already read ${Ee} 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:k.callId}}else Ee>=fe&&(k._scrollWarn={sectionCount:Ee+1,path:w})}}else if(!$e&&oe>=1){let N=Gt.get(w)||0;if(N>0){let U=w.split("/").slice(-2).join("/");console.log(`${$.cyan} \u21A9 Full re-read: "${U}" \u2014 test-failure recovery (${N} remaining)${$.reset}`);let se=N-1;se<=0?Gt.delete(w):Gt.set(w,se)}else{let U=w.split("/").slice(-2).join("/"),se=(gr.get(w)||0)+1;if(gr.set(w,se),se===1)j(`${$.red} \u2716 Blocked unbounded re-read: "${U}" \u2014 already in context. Use line_start/line_end for specific sections.${$.reset}`);else if(se===2){j(`${$.red} \u2716 Escalated block: "${U}" \u2014 model ignored unbounded re-read block, injecting system warning${$.reset}`);let Se={role:"user",content:`[SYSTEM] read_file("${w}") 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.`};T.push(Se),v.push(Se)}k.canExecute=!1,k.errorResult={role:"tool",content:`BLOCKED: read_file("${w}") denied \u2014 file already in context (read ${oe}\xD7). Use line_start/line_end to read a specific section instead of the full file.`,tool_call_id:k.callId}}}k.canExecute&&ed.set(w,(ed.get(w)||0)+1)}if(wo>=3)for(let k of He)k.canExecute&&(k.fnName!=="read_file"&&k.fnName!=="edit_file"||(j(`${$.red} \u2716 Blocked ${k.fnName} \u2014 ${wo} consecutive file-not-found errors, must search first${$.reset}`),k.canExecute=!1,k.errorResult={role:"tool",content:`BLOCKED: ${wo} 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:k.callId}));for(let k of He){if(!k.canExecute||k.fnName!=="bash")continue;let w=(k.args?.command||"").trim();if(/^\s*ls(\s+-[a-zA-Z]+)*(\s+\S+)?\s*$/.test(w)&&!/npm|yarn|pnpm|make|git/.test(w)){j(`${$.red} \u2716 Blocked bash ls \u2014 use list_directory tool instead${$.reset}`),k.canExecute=!1,k.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:k.callId};continue}/\bfind\s+[\S.]/.test(w)&&!/git\s|npm\s|yarn\s|-exec\s+\S|-execdir/.test(w)&&(j(`${$.red} \u2716 Blocked bash find \u2014 use glob tool with a pattern instead${$.reset}`),k.canExecute=!1,k.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:k.callId})}for(let k of He)k.canExecute&&(k.fnName!=="ssh_exec"&&k.fnName!=="bash"||/\bsed\s+-n\b/.test(k.args?.command||"")&&(j(`${$.red} \u2716 Blocked sed -n: use grep -n "pattern" <file> | head -30 instead${$.reset}`),k.canExecute=!1,k.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:k.callId}));for(let k of He){if(!k.canExecute||k.fnName!=="write_file")continue;let w=k.args?.path,W=k.args?.content||"";if(w)try{let H=require("fs"),oe=require("path").resolve(process.cwd(),w);if(H.existsSync(oe)){let $e=H.statSync(oe).size,ce=Buffer.byteLength(W,"utf8"),F=$e>0?ce/$e:1,P=Jp(ve),q=Jp(w);if(Xp(ve)&&(P.includes(q)||P.includes(`./${q}`)))continue;if(F<.6&&$e>200){let U=w.split("/").slice(-2).join("/");console.log(`${$.red} \u2716 write_file shrink guard: "${U}" would shrink to ${Math.round(F*100)}% of original \u2014 likely context loss${$.reset}`),k.canExecute=!1,k.errorResult={role:"tool",content:`BLOCKED: write_file("${w}") denied \u2014 new content is only ${Math.round(F*100)}% of current file size (${$e} \u2192 ${ce} 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:k.callId}}}}catch{}}let fm=new Map;for(let k of He){if(!k.canExecute||k.fnName!=="grep")continue;let w=k.args?.path;if(!w)continue;let W=fm.get(w)||0,H=Os(zu,w)+W,oe=Os(xr,w)>=1,$e=oe?Math.min(3,ic):ic;if(H>=$e){let ce=w.split("/").slice(-2).join("/");j(`${$.red} \u2716 Blocked grep: "${ce}" grepped ${H}\xD7 with different patterns \u2014 flood threshold exceeded${$.reset}`);let F=Os(xr,w),P=F>=vr;if(P){let q={role:"user",content:`[SYSTEM] Both read_file and grep are now blocked for "${w}". You have already read ${F} sections and tried ${H} 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.`};T.push(q),v.push(q),j(`${$.red} \u2716 Deadlock detected: "${ce}" \u2014 both read and grep blocked, injecting deadlock-break${$.reset}`)}k.canExecute=!1,k.errorResult={role:"tool",content:P?`BLOCKED: grep("${w}") denied \u2014 ${H} 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.`:oe?`BLOCKED: grep("${w}") denied \u2014 file was already read and ${H} grep patterns tried. The content is already in your context; use it instead of searching again.`:`BLOCKED: grep("${w}") denied \u2014 ${H} patterns already tried. Work with the grep results already in your context.`,tool_call_id:k.callId}}k.canExecute&&fm.set(w,W+1)}let Cv=5,pm=new Map;for(let k of He){if(!k.canExecute||k.fnName!=="ssh_exec")continue;let W=(k.args?.command||"").replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),H=pm.get(W)||0,oe=Os(om,W)+H;oe>=Cv&&(j(`${$.yellow} \u26A0 Blocked ssh_exec: same command run ${oe}\xD7 \u2014 result already in context${$.reset}`),k.canExecute=!1,k.errorResult={role:"tool",content:`BLOCKED: ssh_exec denied \u2014 this command has already run ${oe} 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:k.callId}),k.canExecute&&pm.set(W,H+1)}if(Ln){let k=He.filter(H=>H.canExecute&&H.fnName==="ssh_exec"),w=He.some(H=>H.canExecute&&H.fnName!=="ssh_exec"),W=ze&&Be<3;if(k.length>0&&!w&&W&&au<1)Ln=!1,au++,Zn=Math.max(0,Si-2),j(`${$.dim} [dual-block deadlock: SSH storm relaxed \u2014 allowing 1 SSH call (relax ${au}/1)]${$.reset}`);else for(let H of k)H.canExecute=!1,H.errorResult={role:"tool",content:Zt?`BLOCKED: ssh_exec denied \u2014 SSH paused (${Si}+ calls). Root cause is known (${kn}). 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 (${Si}+ 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:H.callId}}let Av=pL(T,["browser_open","browser_screenshot","ssh_exec","service_logs","remote_agent"]);if((ze||it)&&!Av&&Be<3&&!Ln)for(let k of He){if(!k.canExecute||!["bash","read_file","find_files","list_directory","search_files","glob","grep"].includes(k.fnName))continue;Be++;{let H=xn(),{messages:oe}=As(v,H);v=oe}let w=xe?.matchedName?`${xe.matchedName} (${xe.matchedProfile?.host||"server"})`:xe?.url,W=xe?.shouldPreferSsh?`BLOCKED: ${k.fnName} denied \u2014 this looks like a live app/server issue. Inspect ${xe?.url} with browser_open or use ssh_exec on ${w} first, then return to local code if needed.`:`BLOCKED: ${k.fnName} denied \u2014 this looks like a live app issue. Inspect ${xe?.url} with browser_open first, then return to local code if needed.`;j(`${$.yellow} \u26A0 Runtime guard: blocking local ${k.fnName} \u2014 inspect the live app first${$.reset}`),k.canExecute=!1,k.errorResult={role:"tool",content:W,tool_call_id:k.callId};break}if(!be&&jn&&ms&&ns>=1){let k=["read_file","grep","search_files","glob","list_directory","find_files"];for(let w of He)w.canExecute&&k.includes(w.fnName)&&(j(`${$.red} \u2716 Creation hard-block: ${w.fnName} denied \u2014 cap fired, files already written${$.reset}`),w.canExecute=!1,w.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:w.callId})}if(ko>=0){let k=He.filter(w=>w.canExecute).length;if(k>0&&(ko-=k,ko<0))if(!lu&&Y.size>cu){lu=!0,ko=5,j(`${$.green} \u2713 Post-wipe progress detected (${Y.size-cu} files modified) \u2014 granting 5 bonus tool calls${$.reset}`);let w={role:"user",content:"[SYSTEM] Progress detected \u2014 5 bonus tool calls granted. Budget: 5 remaining."};T.push(w),v.push(w)}else{j(`${$.yellow} \u26A0 Post-wipe tool budget exhausted (advisory) \u2014 nudging model to wrap up${$.reset}`);let w={role:"user",content:"[SYSTEM] You've used your post-wipe tool call budget. Consider wrapping up and summarizing what was accomplished, or continue if you need a few more steps to finish."};T.push(w),v.push(w),ko=-2}}let Ov=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 k of He){if(!k.canExecute||Ov.has(k.fnName))continue;let w=JSON.stringify(k.args||{}),W=`${k.fnName}|${w}`,H=Os(Up,W);H>=2?(j(`${$.red} \u2716 Blocked duplicate: ${k.fnName}(${w.substring(0,80)}) \u2014 called ${H+1}\xD7 with identical args${$.reset}`),k.canExecute=!1,k.errorResult={role:"tool",content:`BLOCKED: ${k.fnName}() with these exact arguments has already been called ${H}\xD7 \u2014 the result is already in your context. Use the existing output instead of repeating the same call.`,tool_call_id:k.callId}):H===1&&j(`${$.yellow} \u26A0 Duplicate tool call: ${k.fnName}(${w.substring(0,80)}) \u2014 2nd call with identical args${$.reset}`),ur(Up,W)}{let k=new Set;for(let w of He){if(!w.canExecute||!["edit_file","patch_file"].includes(w.fnName))continue;let W=w.args?.path;W&&(k.has(W)?(w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: "${W}" is already being edited in this batch. Finish one edit first, then re-read the changed section before the next one.`,tool_call_id:w.callId},j(`${$.yellow} \u26A0 Map-first gate: blocked duplicate same-batch edit of "${W.split("/").slice(-1)[0]}"${$.reset}`)):ws.has(W)&&!_o.has(W)?(w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: "${W}" was already edited \u2014 re-read the changed section first (read_file with line_start/line_end) before making another edit. The file content has changed and your previous read is stale.`,tool_call_id:w.callId},j(`${$.yellow} \u26A0 Map-first gate: blocked re-edit of "${W.split("/").slice(-1)[0]}" \u2014 re-read required${$.reset}`)):k.add(W))}}let Ti=_?{skipSpinner:!0,skipSummaries:!0}:{},Mv=He.some(k=>k.fnName==="ask_user"),hm=!Ti.skipSummaries&&!Ae,Yn=null,Rr=null;if(hm&&!Mv){if(Ae=!0,Ti.skipSpinner=!0,process.stdout.isTTY){global._nexFooter&&(Rr=Math.min(global._nexFooter._lastOutputRow+1,global._nexFooter._scrollEnd));let k=$a(He,de,!1,0),w=$a(He,de,!1);process.stdout.write(`${de>1?`
1724
1724
  `:""}${k}`),ai=w,ci=Date.now(),Yn={start:Date.now(),frame:0,timer:null}}else if(!Ot){let k=$a(He,de,!1);Np(k,ai,ci)||(process.stdout.write(`${de>1?`
1725
1725
  `:""}${k}
1726
- `),ai=k,ci=Date.now())}}else hm&&(Ae=!0,Ti.skipSpinner=!0);_&&_._paused&&_.resume(),Yn&&process.stdout.isTTY&&(Yn.timer=setInterval(()=>{Yn.frame++;let k=Math.round((Date.now()-Yn.start)/1e3),w=k>=1?` ${y.dim}[${k}s]${y.reset}`:"",W=`${$a(He,de,!1,Yn.frame)}${w}`;Rr!==null?process.stdout.write(`\x1B[${Rr};1H\x1B[2K${W}`):process.stdout.write(`\r\x1B[2K${W}`)},120),Yn.timer.unref?.());let{results:Ft,summaries:Pv}=await _L(He,!0,{...Ti,skipSummaries:!0});if(Qu){let k={role:"user",content:"[SYSTEM] ask_user is exclusive. Wait for the user's answer before making any other tool calls."};T.push(k),v.push(k)}if(Yn){Yn.timer&&(clearInterval(Yn.timer),Yn.timer=null);let k=$a(He,de,!1);Np(k,ai,ci)||(Rr!==null?process.stdout.write(`\x1B[${Rr};1H\x1B[2K${k}
1726
+ `),ai=k,ci=Date.now())}}else hm&&(Ae=!0,Ti.skipSpinner=!0);_&&_._paused&&_.resume(),Yn&&process.stdout.isTTY&&(Yn.timer=setInterval(()=>{Yn.frame++;let k=Math.round((Date.now()-Yn.start)/1e3),w=k>=1?` ${$.dim}[${k}s]${$.reset}`:"",W=`${$a(He,de,!1,Yn.frame)}${w}`;Rr!==null?process.stdout.write(`\x1B[${Rr};1H\x1B[2K${W}`):process.stdout.write(`\r\x1B[2K${W}`)},120),Yn.timer.unref?.());let{results:Ft,summaries:Pv}=await _L(He,!0,{...Ti,skipSummaries:!0});if(Qu){let k={role:"user",content:"[SYSTEM] ask_user is exclusive. Wait for the user's answer before making any other tool calls."};T.push(k),v.push(k)}if(Yn){Yn.timer&&(clearInterval(Yn.timer),Yn.timer=null);let k=$a(He,de,!1);Np(k,ai,ci)||(Rr!==null?process.stdout.write(`\x1B[${Rr};1H\x1B[2K${k}
1727
1727
  `):process.stdout.write(`\r\x1B[2K${k}
1728
- `),ai=k,ci=Date.now()),Rr=null,Yn=null}if(!Ti.skipSummaries){let k=Pv.filter((H,oe)=>!(He[oe]&&He[oe].fnName==="ask_user"));for(let H of k)Np(H,Fp,Bp)||(console.log(H),Fp=H,Bp=Date.now());let w=He.filter(H=>H&&H.fnName!=="ask_user").map(H=>H.fnName),W=iv.record(0,w,je,Y);W&&JN(W)}for(let k of He){if(k.canExecute||!k.errorResult)continue;let w=typeof k.errorResult.content=="string"?k.errorResult.content:"";if(w.startsWith("BLOCKED:")||w.startsWith("PLAN MODE:")||w.startsWith("PLAN PHASE:")){if(Po++,Sr()&&w.includes("planned implementation file")){let H={role:"user",content:"[SYSTEM] The planned implementation file is already in context. Your next response must contain exactly one edit_file or patch_file tool call for the scoped change from the accepted plan. Do not run git, read_file, glob, search, or list_directory. Do not write prose before the tool call."};T.push(H),v.push(H)}let W=Sr()?Math.min(ac,3):ac;if(Po>=W){if(j(`${y.red} \u2716 Loop abort: ${Po} consecutive blocked calls (pre-execution) \u2014 model not heeding BLOCKED messages${y.reset}`),Sr()){let H=`Implementation stalled before edits.
1728
+ `),ai=k,ci=Date.now()),Rr=null,Yn=null}if(!Ti.skipSummaries){let k=Pv.filter((H,oe)=>!(He[oe]&&He[oe].fnName==="ask_user"));for(let H of k)Np(H,Fp,Bp)||(console.log(H),Fp=H,Bp=Date.now());let w=He.filter(H=>H&&H.fnName!=="ask_user").map(H=>H.fnName),W=iv.record(0,w,je,Y);W&&JN(W)}for(let k of He){if(k.canExecute||!k.errorResult)continue;let w=typeof k.errorResult.content=="string"?k.errorResult.content:"";if(w.startsWith("BLOCKED:")||w.startsWith("PLAN MODE:")||w.startsWith("PLAN PHASE:")){if(Po++,Sr()&&w.includes("planned implementation file")){let H={role:"user",content:"[SYSTEM] The planned implementation file is already in context. Your next response must contain exactly one edit_file or patch_file tool call for the scoped change from the accepted plan. Do not run git, read_file, glob, search, or list_directory. Do not write prose before the tool call."};T.push(H),v.push(H)}let W=Sr()?Math.min(ac,3):ac;if(Po>=W){if(j(`${$.red} \u2716 Loop abort: ${Po} consecutive blocked calls (pre-execution) \u2014 model not heeding BLOCKED messages${$.reset}`),Sr()){let H=`Implementation stalled before edits.
1729
1729
 
1730
1730
  The planned implementation file was already in context, but the model kept calling blocked read/search/git tools instead of editing. Stopping without commit or push so the workflow does not falsely report success.`,oe={role:"assistant",content:H};T.push(oe),v.push(oe),console.log(`
1731
1731
  ${H}`),Ce(T),wt(T)}_&&(_.stop(),_=null),x(null),Ze(de,Ie,Y,je,Ke,{suppressHint:!0}),Ce(T);return}}}let yc=!1;for(let k=0;k<He.length;k++){let w=He[k];if(!w.canExecute)continue;let W=Ft[k].content,H=W.split(`
1732
- `)[0],oe=!H.startsWith("ERROR")&&!H.startsWith("CANCELLED")&&!H.startsWith("Command failed")&&!H.startsWith("EXIT")&&!/old_text not found/i.test(H);if(w.fnName==="git_status"&&oe&&(Ea="git_status",hr=W),w.fnName==="bash"&&w.canExecute&&typeof w.args?.command=="string"){let P=w.args.command;/git\s+status\s+--short\s+--branch\b/.test(P)&&(Ea="bash:git status --short --branch",hr=W),/git\s+push\b/.test(P)&&(xo=W,oe&&!xo.startsWith("EXIT")&&(/\bEverything up[- ]to[- ]date\b/i.test(xo)||/\bTo\s+\S+/i.test(xo)||/\bWriting objects\b/i.test(xo))&&(fu=!0))}if(!oe&&(w.fnName==="edit_file"||w.fnName==="patch_file")&&w.args?.path&&H.includes("old_text not found")){let P=Gt.get(w.args.path)||0;Gt.set(w.args.path,P+1)}if(!oe&&w.fnName==="bash"&&Ma.size>0){let P=(w.args?.command||"").toLowerCase();if(/\b(test|jest|vitest|pytest|mocha|tsc|build|lint|eslint|check)\b/.test(P))for(let[N]of Ma)Gt.has(N)||(Gt.set(N,1),j(`${y.cyan} \u21A9 Test failure \u2014 queuing recovery re-read: "${N.split("/").pop()}"${y.reset}`))}if(!oe&&(w.fnName==="read_file"||w.fnName==="edit_file")&&/file not found|does not exist|ENOENT/i.test(H)){if(wo++,wo>=2){j(`${y.yellow} \u26A0 File-not-found streak: ${wo} consecutive misses \u2014 forcing search${y.reset}`);let P={role:"user",content:`[SYSTEM] ${wo} 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.`};T.push(P),v.push(P)}}else oe&&(w.fnName==="read_file"||w.fnName==="edit_file"||w.fnName==="search_files"||w.fnName==="glob_files")&&(wo=0);if(oe&&w.fnName==="write_file"&&w.args?.path){let P=w.args.path.split("/").pop(),q=w.args.path.includes("/tests/")||w.args.path.includes("\\tests\\");if(/^(test_|demo_|temp_|tmp_|scratch_)/.test(P)&&!q){j(`${y.yellow} \u26A0 Temp file: "${P}" \u2014 delete with bash rm when done to keep the workspace clean${y.reset}`);let U={role:"user",content:`[HINT] "${w.args.path}" looks like a temporary test/demo file. Delete it with bash("rm ${w.args.path}") as soon as you're done \u2014 orphaned temp files count against session quality.`};T.push(U),v.push(U)}}if(oe&&["write_file","edit_file","patch_file"].includes(w.fnName)&&w.args&&w.args.path){Gt.delete(w.args.path),Y.add(w.args.path);for(let N of no)!N.done&&w.args.path.endsWith(N.file.split("/").pop())&&(N.done=!0,j(`${y.green} \u2713 TODO done: ${N.file}${y.reset}`));let P=ur(av,w.args.path),q=w.args.path.split("/").slice(-2).join("/");if(P===cv){j(`${y.yellow} \u26A0 Loop warning: "${q}" edited ${P}\xD7 \u2014 possible edit loop${y.reset}`);let N={role:"user",content:`[SYSTEM WARNING] "${w.args.path}" edited ${P}\xD7. One more edit max, then move on.`};T.push(N),v.push(N)}else if(P>=lv){j(`${y.red} \u2716 Loop abort: "${q}" edited ${P}\xD7 \u2014 aborting to prevent runaway loop${y.reset}`),_&&(_.stop(),_=null),x(null),Ze(de,Ie,Y,je,Ke,{suppressHint:!0}),Ce(T);return}be&&Pe==="verify"||(Is=!0,js=0,yc=!0)}if(oe&&w.canExecute&&be&&(So=0),oe&&w.canExecute&&et&&be&&Pe==="plan"&&vL.has(w.fnName)&&(Sn++,TL(w.fnName,w.args)&&Fa++,Sn>=bu&&!pu)){pu=!0;let P={role:"user",content:Ns()};T.push(P),v.push(P),j(`${y.yellow} \u26A0 Bounded backlog plan: ${Sn} read/search tools used \u2014 requiring a decision${y.reset}`)}if(oe&&w.canExecute&&!(be&&Pe==="plan")){let P=["read_file","grep","search_files","glob","list_directory","ssh_exec","find_files"];if(["write_file","edit_file","patch_file"].includes(w.fnName)){es=0,jn=!1,ts=0,ns++;let fe=w.args?.path||w.args?.file_path;fe&&(w.fnName==="write_file"?(_o.add(fe),Ls.delete(fe),to.delete(fe),ws.delete(fe)):(_o.delete(fe),Pp(Ls,fe,1),to.delete(fe),ws.add(fe)))}else if(P.includes(w.fnName)){if(es++,jn&&ts++,be&&Pe==="implement"&&w.fnName==="read_file"){let fe=w.args?.path||w.args?.file_path||"";if(fe&&_o.has(fe)){let B={role:"user",content:`[SYSTEM] You just created and re-read "${fe}". Do NOT analyze further. Apply the requested refactor now with edit_file.`};T.push(B),v.push(B),j(`${y.yellow} \u26A0 Fresh-write nudge: ${fe} \u2014 refactor directly after re-read${y.reset}`)}}if(be&&Pe==="implement"&&w.fnName==="read_file"&&no.length>0){let fe=w.args?.path||w.args?.file_path||"",B=no.find(we=>!we.done&&fe.endsWith(we.file.split("/").pop()));if(B){let we={role:"user",content:`[TODO OBSERVER] You already analyzed "${B.file}" in the plan phase. Action: ${B.action}
1733
- Do NOT re-read \u2014 apply the edit directly with edit_file.`};T.push(we),v.push(we),j(`${y.yellow} \u26A0 TODO nudge: ${B.file} \u2014 already analyzed, edit directly${y.reset}`)}}be&&Pe==="implement"&&Is&&js<1&&(js++,yc=!0)}if(be&&Pe==="verify"&&pi++,oe&&N_(w)){let fe=String(w.args?.command||"").trim();if(fe&&ss.push(fe.slice(0,160)),Is=!1,js=0,In&&(Y.size>0||nt>0)&&!ni){let B={role:"user",content:"[SYSTEM] \u2713 Verification command succeeded after your edit. The dirty worktree now contains your own intended changes, not a preflight blocker. Do not restart planning or re-read the changed file. Stage only the files you changed, commit with a terse English message, push if the prompt requires it, then run one final `git status --short --branch`."};T.push(B),v.push(B)}}let N=o.postEditCap,U=be&&Pe==="implement"?Math.min(im,10):im,se=Zt?8:dc?ns>0?4:6:ms?ns>0?6:10:ns>0?N:U,Se=6,Ee=!be&&jn&&(Zt&&ts>=Se||ms&&ns>=3&&ts>=Se||ts>=Se);if(ba<2&&!jn&&es>=3&&Y.size===0){let fe=parseInt(process.env.NEX_TASK_TIMEOUT_MS,10)||0,B=Date.now()-Ke,we=ba===0?.4:.65;if(fe>0&&B>fe*we){ba++;let Je=Math.round(B/6e4),at=Math.round(B/fe*100);j(`${y.yellow} \u26A0 Time nudge #${ba}: ${Je}m elapsed (${at}%), ${es} reads, 0 edits${y.reset}`);let vt={role:"user",content:ba===1?`[SYSTEM] ${at}% of available time used and no files edited yet. Start implementing now using edit_file or write_file \u2014 you have enough context.`:`[SYSTEM] ${at}% of time used, still no edits. You MUST write code NOW. Use edit_file or write_file immediately \u2014 any further reading will be blocked.`};T.push(vt),v.push(vt)}}if(Ee&&P.includes(w.fnName)){let fe=Zt?`root cause already identified (${kn})`:ts>=Se?`${es} consecutive reads without an edit`:`${ns} file edit(s) already made`;j(`${y.yellow} \u26A0 Investigation cap soft-warn: ${fe} \u2014 allowing but nudging${y.reset}`);let B={role:"user",content:Zt?`[SYSTEM] Root cause was already identified (${kn}). Consider implementing the fix with edit_file rather than reading more files.`:ts>=Se?`[SYSTEM] You've read ${es} files without editing. Consider implementing your fix now \u2014 you likely have enough context.`:`[SYSTEM] ${ns} file edit(s) already made. Consider verifying or proceeding \u2014 further investigation may be unnecessary.`};T.push(B),v.push(B),ts=0,jn=!1}else if(es>=se&&!jn){if(jn=!0,dc&&(Ju=!0),j(`${y.yellow} \u26A0 Investigation cap: ${es} read-only calls without an edit \u2014 forcing implementation${y.reset}`),be&&Pe==="plan"){let we=[...v].reverse().find(vt=>vt.role==="assistant"),Je=typeof we?.content=="string"?we.content:"",at=await oi("implement",Je);at&&(T.push(at),v.push(at),Ct=0,cn=bo("implement"))}let fe;Zt?fe=`[SYSTEM] Root cause was already identified (${kn}). Edit the file now \u2014 do not read more files.`:dc?fe="[SYSTEM] You have enough evidence to write the requested summary/document now. Use write_file or edit_file to produce the deliverable, and stop reading more files unless a required section is still unsupported.":Ln?fe="[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.":fe="[SYSTEM] You have read enough files. Now implement your fix using edit_file.";let B={role:"user",content:fe};T.push(B),v.push(B)}}if((w.fnName==="bash"||w.fnName==="ssh_exec")&&w.args&&w.args.command){let P=w.args.command.replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),q=ur(om,P);if(q===uv){j(`${y.yellow} \u26A0 Loop warning: same bash command run ${q}\xD7 \u2014 possible debug loop${y.reset}`);let N={role:"user",content:`[SYSTEM WARNING] Same bash command ${q}\xD7. Debug loop detected \u2014 try a different approach.`};T.push(N),v.push(N)}else if(q>=dv){j(`${y.red} \u2716 Loop abort: same bash command run ${q}\xD7 \u2014 aborting runaway debug loop${y.reset}`),_&&(_.stop(),_=null),x(null),Ze(de,Ie,Y,je,Ke,{suppressHint:!0}),Ce(T);return}}if(w.fnName==="ssh_exec"){Zn++;{let N=(Ft[k]?.content??"").split(`
1734
- `).map(U=>U.trim()).find(U=>U.length>0&&!U.startsWith("**")&&(U.startsWith("EXIT")||/^[\w./-]+:\s/.test(U)||U.startsWith("bash:")||U.startsWith("sh:")))??"";if(N){if(N===uu?fr++:(uu=N,fr=1),fr===3&&!Ln){j(`${y.yellow} \u26A0 SSH repeated-error: "${N.slice(0,60)}" returned ${fr}\xD7 \u2014 nudging to change approach${y.reset}`);let U={role:"user",content:`[SYSTEM WARNING] The last ${fr} SSH commands all failed with the same error: "${N}". 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).`};T.push(U),v.push(U)}}else uu="",fr=0}if(Zn>=Rv){j(`${y.red} \u2716 SSH storm abort: ${Zn} consecutive ssh_exec calls \u2014 aborting${y.reset}`),_&&(_.stop(),_=null),x(null),Ze(de,Ie,Y,je,Ke,{suppressHint:!0}),Ce(T);return}else if(Zn===Si){{let N=xn(),{messages:U}=As(v,N);v=U}Ln=!0,Xl++,j(`${y.yellow} \u26A0 SSH storm warning (#${Xl}): ${Zn} consecutive ssh_exec calls \u2014 blocking further SSH${y.reset}`);let q={role:"user",content:Zt?`[SYSTEM WARNING] ${Zn} consecutive SSH calls. Root cause identified (${kn}). Read the file that needs fixing, then edit it.`:`[SYSTEM WARNING] ${Zn} 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.`};T.push(q),v.push(q)}}else w.canExecute&&(Zn=0);if(w.fnName==="bash"&&w.canExecute){let N=(Ft[k]?.content??"").split(`
1735
- `).map(U=>U.trim()).find(U=>U.length>0&&(U.startsWith("EXIT")||/^[\w./-]+:\s/.test(U)||U.startsWith("bash:")||U.startsWith("sh:")))??"";if(N){if(N===du?pr++:(du=N,pr=1),pr===3){j(`${y.yellow} \u26A0 Bash repeated-error: "${N.slice(0,60)}" returned ${pr}\xD7 \u2014 nudging to change approach${y.reset}`);let U={role:"user",content:`[SYSTEM WARNING] The last ${pr} bash commands all failed with the same error: "${N}". 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).`};T.push(U),v.push(U)}}else du="",pr=0}if(w.fnName==="bash"&&w.canExecute&&!ni&&w.args?.command){let P=Ft[k]?.content??"";if(/git\s+commit\b/.test(w.args.command)&&!P.startsWith("EXIT")&&!P.startsWith("ERROR")&&(/\[\S+\s+[a-f0-9]+\]/.test(P)||P.includes("files changed")||P.includes("file changed")||P.includes("insertions(+)")||P.includes("create mode"))){ni=!0,wa=0;let U=In?4:2;j(`${y.green} \u2713 Git commit detected \u2014 post-commit verification cap active (max ${U} git status/diff/log)${y.reset}`);let se=In?{role:"user",content:"[SYSTEM] \u2713 Git commit succeeded. This is a gated automation workflow: ensure you still capture final-state evidence. Next: push (if required by the prompt), then run `git status --short --branch` once and include its output in the final automation report. Avoid extra git diff/log unless needed to explain a blocker."}:{role:"user",content:"[SYSTEM] \u2713 Git commit succeeded. Your changes are committed. Do NOT run further git status / git diff / git log calls \u2014 the commit is done. Write your final summary and stop. Running extra verification commands wastes tool calls and hurts session quality."};T.push(se),v.push(se)}}if(ni&&w.fnName==="bash"&&w.args?.command&&/git\s+(status|diff|log|show)\b/.test(w.args.command)&&(wa++,wa>(In?4:2))){j(`${y.yellow} \u26A0 Post-commit git verification blocked (call ${wa})${y.reset}`);let N={role:"user",content:"[SYSTEM] \u26A0 STOP: You already ran "+(wa-1)+" git verification commands after committing. "+(In?"In gated automation workflows, keep tool use minimal: you already have enough evidence for the final report. Write the final automation report now and stop.":"The commit is confirmed. Write your final summary NOW and do not make any more tool calls.")};T.push(N),v.push(N)}if(oe&&w.fnName==="grep"&&W&&!W.startsWith("(no matches)")){let P=sn(w.args?.path||"");et&&be&&Pe==="implement"&&P&&Na.set(P,(Na.get(P)||0)+1);let q=W.split(`
1736
- `);for(let N of q){let U=N.indexOf(":");if(U>0){let se=N.substring(0,U);se.startsWith("/")&&!se.includes(" ")&&Aa.add(se)}else N.startsWith("/")&&!N.includes(" ")&&Aa.add(N.trim())}}{let P=["grep","search_files","glob","glob_files"].includes(w.fnName);if(P&&oe&&W&&(W.startsWith("(no matches)")||W.trim()===""||/^No matches found/.test(W.trim())||/^\(0 results\)/.test(W.trim()))){if(Gu++,Gu===3){j(`${y.yellow} \u26A0 3 consecutive empty local searches \u2014 injecting SSH pivot hint${y.reset}`);let N={role:"user",content:"[SYSTEM NOTE] 3 consecutive local searches returned no results. The target files may be on a remote server. If you have an SSH profile configured for this project's server, use ssh_exec to search there (e.g. ssh_exec with grep). Do not keep searching locally if the code does not exist on this machine."};T.push(N),v.push(N)}}else P&&oe&&W&&W.trim().length>0&&(Gu=0)}if(oe&&w.fnName==="grep"&&w.args&&w.args.pattern){let P=`${w.args.pattern}|${w.args.path||""}`,q=ur(fv,P);if(q===pv){j(`${y.yellow} \u26A0 Loop warning: grep pattern "${w.args.pattern.slice(0,40)}" run ${q}\xD7 \u2014 possible search loop${y.reset}`);let N={role:"user",content:`[SYSTEM WARNING] Same grep pattern ${q}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};T.push(N),v.push(N)}else if(q>=hv){j(`${y.red} \u2716 Loop abort: grep pattern run ${q}\xD7 \u2014 aborting runaway search loop${y.reset}`),_&&(_.stop(),_=null),x(null),Ze(de,Ie,Y,je,Ke,{suppressHint:!0}),Ce(T);return}if(w.args.path){let N=ur(zu,w.args.path),U=Os(xr,w.args.path)>=1;if(N===(U?1:mv)){let Se=w.args.path.split("/").slice(-2).join("/");j(`${y.yellow} \u26A0 Loop warning: "${Se}" grepped ${N}\xD7 with different patterns \u2014 context flood risk${y.reset}`);let Ee={role:"user",content:U?`[SYSTEM NOTE] "${w.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] "${w.args.path}" grepped ${N}\xD7 \u2014 use the search results already in context instead of searching again.`};T.push(Ee),v.push(Ee)}}}if(oe&&(w.fnName==="glob"||w.fnName==="glob_files"||w.fnName==="search_files")&&w.args){if(W&&!W.startsWith("(no matches)")){let U=W.split(`
1737
- `);for(let se of U)(se.startsWith("/")&&!se.includes(" ")||!se.includes(":")&&!se.startsWith("["))&&Oa.add(se.trim())}let P=w.args.pattern||w.args.query||w.args.path||"",q=ur(gv,P);if(q===yv){j(`${y.yellow} \u26A0 Loop warning: glob pattern "${P.slice(0,40)}" run ${q}\xD7 \u2014 possible search loop${y.reset}`);let U={role:"user",content:`[SYSTEM WARNING] Same glob/search pattern ${q}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};T.push(U),v.push(U)}else if(q>=$v){j(`${y.red} \u2716 Loop abort: glob pattern run ${q}\xD7 \u2014 aborting runaway search loop${y.reset}`),_&&(_.stop(),_=null),x(null),Ze(de,Ie,Y,je,Ke,{suppressHint:!0}),Ce(T);return}let N=P.replace(/\*+/g," ").replace(/[{}()\[\],.\/\\]/g," ").split(/\s+/).filter(U=>U.length>=4&&!/^\.(js|ts|py|json|md|yaml|yml|txt|css|html|sh)$/.test(U));for(let U of N){let se=U.toLowerCase();ou.has(se)||ou.set(se,new Set);let Se=ou.get(se);if(Se.add(P),Se.size===wv){j(`${y.red} \u2716 Glob core-term block: ${Se.size} different patterns all searching for "${se}" \u2014 search loop${y.reset}`);let Ee={role:"user",content:`[SYSTEM WARNING] You have searched for "${se}" using ${Se.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.`};T.push(Ee),v.push(Ee)}else if(Se.size===bv){j(`${y.yellow} \u26A0 Glob core-term warning: ${Se.size} different patterns searching for "${se}"${y.reset}`);let Ee={role:"user",content:`[SYSTEM WARNING] ${Se.size} different glob patterns all target "${se}". If previous searches returned no results, the file probably does not exist \u2014 stop searching and proceed with available information.`};T.push(Ee),v.push(Ee)}}}let $e=(w.args?.command||w.args?.cmd||w.args?.script||"").toLowerCase(),ce=/\b(health|healthcheck|health-check|status|check|ping|validate|alive|ready)\b/.test($e)||/\/(health|status|ping|ready|alive)\b/.test($e);if(oe&&(w.fnName==="bash"||w.fnName==="ssh_exec")&&ce&&W.includes('"valid":true')){{let q=xn();if(hs(v,q).percentage>=60){let{messages:U,tokensRemoved:se}=As(v,q);se>0&&(v=U,console.log(`${y.dim} [pre-stop-compress \u2014 ~${se} tokens freed before STOP injection, now ${Math.round(hs(v,q).percentage)}%]${y.reset}`))}}let P={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.'};T.push(P),v.push(P),console.log(`${y.cyan} \u2713 Health-check stop signal detected \u2014 injecting STOP instruction${y.reset}`)}if(oe&&(w.fnName==="bash"||w.fnName==="ssh_exec")&&$e&&/\bsed\s+-[ie]\b|\btee\b|\bcp\b|\bmv\b|\bpatch\b|\bdd\b|>\s*\S|\becho\b.*>|\bcat\b.*>|\bprintf\b.*>|\bpython[23]?\b.*open\b.*['"'w]|\bnpm\b.*run\b|\byarn\b.*run\b/.test($e)&&(nt++,j(`${y.dim} [bash write detected: _bashModifiedFiles=${nt}]${y.reset}`)),W.startsWith("BLOCKED:")){if(Po++,Sr()&&W.includes("planned implementation file")){let q={role:"user",content:"[SYSTEM] The planned implementation file is already in context. Your next response must contain exactly one edit_file or patch_file tool call for the scoped change from the accepted plan. Do not run git, read_file, glob, search, or list_directory. Do not write prose before the tool call."};T.push(q),v.push(q)}let P=Sr()?Math.min(ac,3):ac;if(Po>=P){if(j(`${y.red} \u2716 Loop abort: ${Po} consecutive blocked calls \u2014 model not heeding BLOCKED messages${y.reset}`),Sr()){let q=`Implementation stalled before edits.
1732
+ `)[0],oe=!H.startsWith("ERROR")&&!H.startsWith("CANCELLED")&&!H.startsWith("Command failed")&&!H.startsWith("EXIT")&&!/old_text not found/i.test(H);if(w.fnName==="git_status"&&oe&&(Ea="git_status",hr=W),w.fnName==="bash"&&w.canExecute&&typeof w.args?.command=="string"){let P=w.args.command;/git\s+status\s+--short\s+--branch\b/.test(P)&&(Ea="bash:git status --short --branch",hr=W),/git\s+push\b/.test(P)&&(xo=W,oe&&!xo.startsWith("EXIT")&&(/\bEverything up[- ]to[- ]date\b/i.test(xo)||/\bTo\s+\S+/i.test(xo)||/\bWriting objects\b/i.test(xo))&&(fu=!0))}if(!oe&&(w.fnName==="edit_file"||w.fnName==="patch_file")&&w.args?.path&&H.includes("old_text not found")){let P=Gt.get(w.args.path)||0;Gt.set(w.args.path,P+1)}if(!oe&&w.fnName==="bash"&&Ma.size>0){let P=(w.args?.command||"").toLowerCase();if(/\b(test|jest|vitest|pytest|mocha|tsc|build|lint|eslint|check)\b/.test(P))for(let[N]of Ma)Gt.has(N)||(Gt.set(N,1),j(`${$.cyan} \u21A9 Test failure \u2014 queuing recovery re-read: "${N.split("/").pop()}"${$.reset}`))}if(!oe&&(w.fnName==="read_file"||w.fnName==="edit_file")&&/file not found|does not exist|ENOENT/i.test(H)){if(wo++,wo>=2){j(`${$.yellow} \u26A0 File-not-found streak: ${wo} consecutive misses \u2014 forcing search${$.reset}`);let P={role:"user",content:`[SYSTEM] ${wo} 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.`};T.push(P),v.push(P)}}else oe&&(w.fnName==="read_file"||w.fnName==="edit_file"||w.fnName==="search_files"||w.fnName==="glob_files")&&(wo=0);if(oe&&w.fnName==="write_file"&&w.args?.path){let P=w.args.path.split("/").pop(),q=w.args.path.includes("/tests/")||w.args.path.includes("\\tests\\");if(/^(test_|demo_|temp_|tmp_|scratch_)/.test(P)&&!q){j(`${$.yellow} \u26A0 Temp file: "${P}" \u2014 delete with bash rm when done to keep the workspace clean${$.reset}`);let U={role:"user",content:`[HINT] "${w.args.path}" looks like a temporary test/demo file. Delete it with bash("rm ${w.args.path}") as soon as you're done \u2014 orphaned temp files count against session quality.`};T.push(U),v.push(U)}}if(oe&&["write_file","edit_file","patch_file"].includes(w.fnName)&&w.args&&w.args.path){Gt.delete(w.args.path),Y.add(w.args.path);for(let N of no)!N.done&&w.args.path.endsWith(N.file.split("/").pop())&&(N.done=!0,j(`${$.green} \u2713 TODO done: ${N.file}${$.reset}`));let P=ur(av,w.args.path),q=w.args.path.split("/").slice(-2).join("/");if(P===cv){j(`${$.yellow} \u26A0 Loop warning: "${q}" edited ${P}\xD7 \u2014 possible edit loop${$.reset}`);let N={role:"user",content:`[SYSTEM WARNING] "${w.args.path}" edited ${P}\xD7. One more edit max, then move on.`};T.push(N),v.push(N)}else if(P>=lv){j(`${$.red} \u2716 Loop abort: "${q}" edited ${P}\xD7 \u2014 aborting to prevent runaway loop${$.reset}`),_&&(_.stop(),_=null),x(null),Ze(de,Ie,Y,je,Ke,{suppressHint:!0}),Ce(T);return}be&&Pe==="verify"||(Is=!0,js=0,yc=!0)}if(oe&&w.canExecute&&be&&(So=0),oe&&w.canExecute&&et&&be&&Pe==="plan"&&vL.has(w.fnName)&&(Sn++,TL(w.fnName,w.args)&&Fa++,Sn>=bu&&!pu)){pu=!0;let P={role:"user",content:Ns()};T.push(P),v.push(P),j(`${$.yellow} \u26A0 Bounded backlog plan: ${Sn} read/search tools used \u2014 requiring a decision${$.reset}`)}if(oe&&w.canExecute&&!(be&&Pe==="plan")){let P=["read_file","grep","search_files","glob","list_directory","ssh_exec","find_files"];if(["write_file","edit_file","patch_file"].includes(w.fnName)){es=0,jn=!1,ts=0,ns++;let fe=w.args?.path||w.args?.file_path;fe&&(w.fnName==="write_file"?(_o.add(fe),Ls.delete(fe),to.delete(fe),ws.delete(fe)):(_o.delete(fe),Pp(Ls,fe,1),to.delete(fe),ws.add(fe)))}else if(P.includes(w.fnName)){if(es++,jn&&ts++,be&&Pe==="implement"&&w.fnName==="read_file"){let fe=w.args?.path||w.args?.file_path||"";if(fe&&_o.has(fe)){let B={role:"user",content:`[SYSTEM] You just created and re-read "${fe}". Do NOT analyze further. Apply the requested refactor now with edit_file.`};T.push(B),v.push(B),j(`${$.yellow} \u26A0 Fresh-write nudge: ${fe} \u2014 refactor directly after re-read${$.reset}`)}}if(be&&Pe==="implement"&&w.fnName==="read_file"&&no.length>0){let fe=w.args?.path||w.args?.file_path||"",B=no.find(we=>!we.done&&fe.endsWith(we.file.split("/").pop()));if(B){let we={role:"user",content:`[TODO OBSERVER] You already analyzed "${B.file}" in the plan phase. Action: ${B.action}
1733
+ Do NOT re-read \u2014 apply the edit directly with edit_file.`};T.push(we),v.push(we),j(`${$.yellow} \u26A0 TODO nudge: ${B.file} \u2014 already analyzed, edit directly${$.reset}`)}}be&&Pe==="implement"&&Is&&js<1&&(js++,yc=!0)}if(be&&Pe==="verify"&&pi++,oe&&N_(w)){let fe=String(w.args?.command||"").trim();if(fe&&ss.push(fe.slice(0,160)),Is=!1,js=0,In&&(Y.size>0||nt>0)&&!ni){let B={role:"user",content:"[SYSTEM] \u2713 Verification command succeeded after your edit. The dirty worktree now contains your own intended changes, not a preflight blocker. Do not restart planning or re-read the changed file. Stage only the files you changed, commit with a terse English message, push if the prompt requires it, then run one final `git status --short --branch`."};T.push(B),v.push(B)}}let N=o.postEditCap,U=be&&Pe==="implement"?Math.min(im,10):im,se=Zt?8:dc?ns>0?4:6:ms?ns>0?6:10:ns>0?N:U,Se=6,Ee=!be&&jn&&(Zt&&ts>=Se||ms&&ns>=3&&ts>=Se||ts>=Se);if(ba<2&&!jn&&es>=3&&Y.size===0){let fe=parseInt(process.env.NEX_TASK_TIMEOUT_MS,10)||0,B=Date.now()-Ke,we=ba===0?.4:.65;if(fe>0&&B>fe*we){ba++;let Je=Math.round(B/6e4),at=Math.round(B/fe*100);j(`${$.yellow} \u26A0 Time nudge #${ba}: ${Je}m elapsed (${at}%), ${es} reads, 0 edits${$.reset}`);let vt={role:"user",content:ba===1?`[SYSTEM] ${at}% of available time used and no files edited yet. Start implementing now using edit_file or write_file \u2014 you have enough context.`:`[SYSTEM] ${at}% of time used, still no edits. You MUST write code NOW. Use edit_file or write_file immediately \u2014 any further reading will be blocked.`};T.push(vt),v.push(vt)}}if(Ee&&P.includes(w.fnName)){let fe=Zt?`root cause already identified (${kn})`:ts>=Se?`${es} consecutive reads without an edit`:`${ns} file edit(s) already made`;j(`${$.yellow} \u26A0 Investigation cap soft-warn: ${fe} \u2014 allowing but nudging${$.reset}`);let B={role:"user",content:Zt?`[SYSTEM] Root cause was already identified (${kn}). Consider implementing the fix with edit_file rather than reading more files.`:ts>=Se?`[SYSTEM] You've read ${es} files without editing. Consider implementing your fix now \u2014 you likely have enough context.`:`[SYSTEM] ${ns} file edit(s) already made. Consider verifying or proceeding \u2014 further investigation may be unnecessary.`};T.push(B),v.push(B),ts=0,jn=!1}else if(es>=se&&!jn){if(jn=!0,dc&&(Ju=!0),j(`${$.yellow} \u26A0 Investigation cap: ${es} read-only calls without an edit \u2014 forcing implementation${$.reset}`),be&&Pe==="plan"){let we=[...v].reverse().find(vt=>vt.role==="assistant"),Je=typeof we?.content=="string"?we.content:"",at=await oi("implement",Je);at&&(T.push(at),v.push(at),Ct=0,cn=bo("implement"))}let fe;Zt?fe=`[SYSTEM] Root cause was already identified (${kn}). Edit the file now \u2014 do not read more files.`:dc?fe="[SYSTEM] You have enough evidence to write the requested summary/document now. Use write_file or edit_file to produce the deliverable, and stop reading more files unless a required section is still unsupported.":Ln?fe="[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.":fe="[SYSTEM] You have read enough files. Now implement your fix using edit_file.";let B={role:"user",content:fe};T.push(B),v.push(B)}}if((w.fnName==="bash"||w.fnName==="ssh_exec")&&w.args&&w.args.command){let P=w.args.command.replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),q=ur(om,P);if(q===uv){j(`${$.yellow} \u26A0 Loop warning: same bash command run ${q}\xD7 \u2014 possible debug loop${$.reset}`);let N={role:"user",content:`[SYSTEM WARNING] Same bash command ${q}\xD7. Debug loop detected \u2014 try a different approach.`};T.push(N),v.push(N)}else if(q>=dv){j(`${$.red} \u2716 Loop abort: same bash command run ${q}\xD7 \u2014 aborting runaway debug loop${$.reset}`),_&&(_.stop(),_=null),x(null),Ze(de,Ie,Y,je,Ke,{suppressHint:!0}),Ce(T);return}}if(w.fnName==="ssh_exec"){Zn++;{let N=(Ft[k]?.content??"").split(`
1734
+ `).map(U=>U.trim()).find(U=>U.length>0&&!U.startsWith("**")&&(U.startsWith("EXIT")||/^[\w./-]+:\s/.test(U)||U.startsWith("bash:")||U.startsWith("sh:")))??"";if(N){if(N===uu?fr++:(uu=N,fr=1),fr===3&&!Ln){j(`${$.yellow} \u26A0 SSH repeated-error: "${N.slice(0,60)}" returned ${fr}\xD7 \u2014 nudging to change approach${$.reset}`);let U={role:"user",content:`[SYSTEM WARNING] The last ${fr} SSH commands all failed with the same error: "${N}". 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).`};T.push(U),v.push(U)}}else uu="",fr=0}if(Zn>=Rv){j(`${$.red} \u2716 SSH storm abort: ${Zn} consecutive ssh_exec calls \u2014 aborting${$.reset}`),_&&(_.stop(),_=null),x(null),Ze(de,Ie,Y,je,Ke,{suppressHint:!0}),Ce(T);return}else if(Zn===Si){{let N=xn(),{messages:U}=As(v,N);v=U}Ln=!0,Xl++,j(`${$.yellow} \u26A0 SSH storm warning (#${Xl}): ${Zn} consecutive ssh_exec calls \u2014 blocking further SSH${$.reset}`);let q={role:"user",content:Zt?`[SYSTEM WARNING] ${Zn} consecutive SSH calls. Root cause identified (${kn}). Read the file that needs fixing, then edit it.`:`[SYSTEM WARNING] ${Zn} 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.`};T.push(q),v.push(q)}}else w.canExecute&&(Zn=0);if(w.fnName==="bash"&&w.canExecute){let N=(Ft[k]?.content??"").split(`
1735
+ `).map(U=>U.trim()).find(U=>U.length>0&&(U.startsWith("EXIT")||/^[\w./-]+:\s/.test(U)||U.startsWith("bash:")||U.startsWith("sh:")))??"";if(N){if(N===du?pr++:(du=N,pr=1),pr===3){j(`${$.yellow} \u26A0 Bash repeated-error: "${N.slice(0,60)}" returned ${pr}\xD7 \u2014 nudging to change approach${$.reset}`);let U={role:"user",content:`[SYSTEM WARNING] The last ${pr} bash commands all failed with the same error: "${N}". 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).`};T.push(U),v.push(U)}}else du="",pr=0}if(w.fnName==="bash"&&w.canExecute&&!ni&&w.args?.command){let P=Ft[k]?.content??"";if(/git\s+commit\b/.test(w.args.command)&&!P.startsWith("EXIT")&&!P.startsWith("ERROR")&&(/\[\S+\s+[a-f0-9]+\]/.test(P)||P.includes("files changed")||P.includes("file changed")||P.includes("insertions(+)")||P.includes("create mode"))){ni=!0,wa=0;let U=In?4:2;j(`${$.green} \u2713 Git commit detected \u2014 post-commit verification cap active (max ${U} git status/diff/log)${$.reset}`);let se=In?{role:"user",content:"[SYSTEM] \u2713 Git commit succeeded. This is a gated automation workflow: ensure you still capture final-state evidence. Next: push (if required by the prompt), then run `git status --short --branch` once and include its output in the final automation report. Avoid extra git diff/log unless needed to explain a blocker."}:{role:"user",content:"[SYSTEM] \u2713 Git commit succeeded. Your changes are committed. Do NOT run further git status / git diff / git log calls \u2014 the commit is done. Write your final summary and stop. Running extra verification commands wastes tool calls and hurts session quality."};T.push(se),v.push(se)}}if(ni&&w.fnName==="bash"&&w.args?.command&&/git\s+(status|diff|log|show)\b/.test(w.args.command)&&(wa++,wa>(In?4:2))){j(`${$.yellow} \u26A0 Post-commit git verification blocked (call ${wa})${$.reset}`);let N={role:"user",content:"[SYSTEM] \u26A0 STOP: You already ran "+(wa-1)+" git verification commands after committing. "+(In?"In gated automation workflows, keep tool use minimal: you already have enough evidence for the final report. Write the final automation report now and stop.":"The commit is confirmed. Write your final summary NOW and do not make any more tool calls.")};T.push(N),v.push(N)}if(oe&&w.fnName==="grep"&&W&&!W.startsWith("(no matches)")){let P=sn(w.args?.path||"");et&&be&&Pe==="implement"&&P&&Na.set(P,(Na.get(P)||0)+1);let q=W.split(`
1736
+ `);for(let N of q){let U=N.indexOf(":");if(U>0){let se=N.substring(0,U);se.startsWith("/")&&!se.includes(" ")&&Aa.add(se)}else N.startsWith("/")&&!N.includes(" ")&&Aa.add(N.trim())}}{let P=["grep","search_files","glob","glob_files"].includes(w.fnName);if(P&&oe&&W&&(W.startsWith("(no matches)")||W.trim()===""||/^No matches found/.test(W.trim())||/^\(0 results\)/.test(W.trim()))){if(Gu++,Gu===3){j(`${$.yellow} \u26A0 3 consecutive empty local searches \u2014 injecting SSH pivot hint${$.reset}`);let N={role:"user",content:"[SYSTEM NOTE] 3 consecutive local searches returned no results. The target files may be on a remote server. If you have an SSH profile configured for this project's server, use ssh_exec to search there (e.g. ssh_exec with grep). Do not keep searching locally if the code does not exist on this machine."};T.push(N),v.push(N)}}else P&&oe&&W&&W.trim().length>0&&(Gu=0)}if(oe&&w.fnName==="grep"&&w.args&&w.args.pattern){let P=`${w.args.pattern}|${w.args.path||""}`,q=ur(fv,P);if(q===pv){j(`${$.yellow} \u26A0 Loop warning: grep pattern "${w.args.pattern.slice(0,40)}" run ${q}\xD7 \u2014 possible search loop${$.reset}`);let N={role:"user",content:`[SYSTEM WARNING] Same grep pattern ${q}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};T.push(N),v.push(N)}else if(q>=hv){j(`${$.red} \u2716 Loop abort: grep pattern run ${q}\xD7 \u2014 aborting runaway search loop${$.reset}`),_&&(_.stop(),_=null),x(null),Ze(de,Ie,Y,je,Ke,{suppressHint:!0}),Ce(T);return}if(w.args.path){let N=ur(zu,w.args.path),U=Os(xr,w.args.path)>=1;if(N===(U?1:mv)){let Se=w.args.path.split("/").slice(-2).join("/");j(`${$.yellow} \u26A0 Loop warning: "${Se}" grepped ${N}\xD7 with different patterns \u2014 context flood risk${$.reset}`);let Ee={role:"user",content:U?`[SYSTEM NOTE] "${w.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] "${w.args.path}" grepped ${N}\xD7 \u2014 use the search results already in context instead of searching again.`};T.push(Ee),v.push(Ee)}}}if(oe&&(w.fnName==="glob"||w.fnName==="glob_files"||w.fnName==="search_files")&&w.args){if(W&&!W.startsWith("(no matches)")){let U=W.split(`
1737
+ `);for(let se of U)(se.startsWith("/")&&!se.includes(" ")||!se.includes(":")&&!se.startsWith("["))&&Oa.add(se.trim())}let P=w.args.pattern||w.args.query||w.args.path||"",q=ur(gv,P);if(q===yv){j(`${$.yellow} \u26A0 Loop warning: glob pattern "${P.slice(0,40)}" run ${q}\xD7 \u2014 possible search loop${$.reset}`);let U={role:"user",content:`[SYSTEM WARNING] Same glob/search pattern ${q}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};T.push(U),v.push(U)}else if(q>=$v){j(`${$.red} \u2716 Loop abort: glob pattern run ${q}\xD7 \u2014 aborting runaway search loop${$.reset}`),_&&(_.stop(),_=null),x(null),Ze(de,Ie,Y,je,Ke,{suppressHint:!0}),Ce(T);return}let N=P.replace(/\*+/g," ").replace(/[{}()\[\],.\/\\]/g," ").split(/\s+/).filter(U=>U.length>=4&&!/^\.(js|ts|py|json|md|yaml|yml|txt|css|html|sh)$/.test(U));for(let U of N){let se=U.toLowerCase();ou.has(se)||ou.set(se,new Set);let Se=ou.get(se);if(Se.add(P),Se.size===wv){j(`${$.red} \u2716 Glob core-term block: ${Se.size} different patterns all searching for "${se}" \u2014 search loop${$.reset}`);let Ee={role:"user",content:`[SYSTEM WARNING] You have searched for "${se}" using ${Se.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.`};T.push(Ee),v.push(Ee)}else if(Se.size===bv){j(`${$.yellow} \u26A0 Glob core-term warning: ${Se.size} different patterns searching for "${se}"${$.reset}`);let Ee={role:"user",content:`[SYSTEM WARNING] ${Se.size} different glob patterns all target "${se}". If previous searches returned no results, the file probably does not exist \u2014 stop searching and proceed with available information.`};T.push(Ee),v.push(Ee)}}}let $e=(w.args?.command||w.args?.cmd||w.args?.script||"").toLowerCase(),ce=/\b(health|healthcheck|health-check|status|check|ping|validate|alive|ready)\b/.test($e)||/\/(health|status|ping|ready|alive)\b/.test($e);if(oe&&(w.fnName==="bash"||w.fnName==="ssh_exec")&&ce&&W.includes('"valid":true')){{let q=xn();if(hs(v,q).percentage>=60){let{messages:U,tokensRemoved:se}=As(v,q);se>0&&(v=U,console.log(`${$.dim} [pre-stop-compress \u2014 ~${se} tokens freed before STOP injection, now ${Math.round(hs(v,q).percentage)}%]${$.reset}`))}}let P={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.'};T.push(P),v.push(P),console.log(`${$.cyan} \u2713 Health-check stop signal detected \u2014 injecting STOP instruction${$.reset}`)}if(oe&&(w.fnName==="bash"||w.fnName==="ssh_exec")&&$e&&/\bsed\s+-[ie]\b|\btee\b|\bcp\b|\bmv\b|\bpatch\b|\bdd\b|>\s*\S|\becho\b.*>|\bcat\b.*>|\bprintf\b.*>|\bpython[23]?\b.*open\b.*['"'w]|\bnpm\b.*run\b|\byarn\b.*run\b/.test($e)&&(nt++,j(`${$.dim} [bash write detected: _bashModifiedFiles=${nt}]${$.reset}`)),W.startsWith("BLOCKED:")){if(Po++,Sr()&&W.includes("planned implementation file")){let q={role:"user",content:"[SYSTEM] The planned implementation file is already in context. Your next response must contain exactly one edit_file or patch_file tool call for the scoped change from the accepted plan. Do not run git, read_file, glob, search, or list_directory. Do not write prose before the tool call."};T.push(q),v.push(q)}let P=Sr()?Math.min(ac,3):ac;if(Po>=P){if(j(`${$.red} \u2716 Loop abort: ${Po} consecutive blocked calls \u2014 model not heeding BLOCKED messages${$.reset}`),Sr()){let q=`Implementation stalled before edits.
1738
1738
 
1739
1739
  The planned implementation file was already in context, but the model kept calling blocked read/search/git tools instead of editing. Stopping without commit or push so the workflow does not falsely report success.`,N={role:"assistant",content:q};T.push(N),v.push(N),console.log(`
1740
- ${q}`),Ce(T),wt(T)}_&&(_.stop(),_=null),x(null),Ze(de,Ie,Y,je,Ke,{suppressHint:!0}),Ce(T);return}}else Po=0;if(oe)Mo=0,fc=!0;else if(Mo++,Mo===vv){j(`${y.yellow} \u26A0 Loop warning: ${Mo} consecutive tool errors \u2014 possible stuck loop${y.reset}`);let P={role:"user",content:`[SYSTEM WARNING] ${Mo} consecutive errors. Stuck loop \u2014 try fundamentally different approach or declare done.`};T.push(P),v.push(P)}else if(Mo>=Sv){j(`${y.red} \u2716 Loop abort: ${Mo} consecutive errors \u2014 aborting stuck loop${y.reset}`),_&&(_.stop(),_=null),x(null),Ze(de,Ie,Y,je,Ke,{suppressHint:!0}),Ce(T);return}if(oe&&w.fnName==="read_file"&&w.args&&w.args.path){je.add(w.args.path),(Y.has(w.args.path)||_o.has(w.args.path)||ws.has(w.args.path))&&(qs.push(w.args.path),Is=!1,js=0),_o.delete(w.args.path),ws.delete(w.args.path);let P=ur(xr,w.args.path);{let se=w.args.line_start!=null&&parseInt(w.args.line_start,10)||1,Se=w.args.line_start!=null?parseInt(w.args.line_end,10)||se+350:350;to.has(w.args.path)||to.set(w.args.path,[]),to.get(w.args.path).push([se,Se])}if(w._scrollWarn){let{sectionCount:se,path:Se}=w._scrollWarn,Ee={role:"user",content:`[SYSTEM WARNING] "${Se}" \u2014 you have now read ${se} 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.`};T.push(Ee),v.push(Ee),j(`${y.yellow} \u26A0 Scroll warning: "${Se.split("/").slice(-2).join("/")}" \u2014 ${se} sections read \u2014 use grep instead${y.reset}`)}let q=w.args.path.split("/").slice(-2).join("/"),N=!w.args?.line_start&&!w.args?.line_end,U=be&&Pe==="plan";if(!U&&N&&P===_v){{let Se=xn();if(hs(v,Se).percentage>=60){let{messages:fe}=As(v,Se);v=fe}}j(`${y.yellow} \u26A0 Loop warning: "${q}" read unbounded ${P}\xD7 \u2014 use line_start/line_end${y.reset}`);let se={role:"user",content:`[SYSTEM WARNING] "${w.args.path}" read ${P}\xD7 without line ranges. Use line_start/line_end to read specific sections \u2014 do not re-read the full file.`};T.push(se),v.push(se)}else if(!U&&N&&P>=kv){j(`${y.red} \u2716 Loop abort: "${q}" read unbounded ${P}\xD7 \u2014 aborting runaway read loop${y.reset}`),_&&(_.stop(),_=null),x(null),Ze(de,Ie,Y,je,Ke,{suppressHint:!0}),Ce(T);return}}if(w.fnName==="spawn_agents"){let P=(W.match(/\bStatus: done\b/g)||[]).length;if((W.match(/\bStatus: truncated\b/g)||[]).length>0&&P===0){if(No++,No===Ev){j(`${y.yellow} \u26A0 Swarm warning: all sub-agents hit iteration limit ${No}\xD7 in a row${y.reset}`);let N={role:"user",content:`[SYSTEM WARNING] Sub-agents truncated ${No}\xD7 in a row. Stop spawning \u2014 try different approach or report findings.`};T.push(N),v.push(N)}else if(No>=Tv){console.log(`${y.red} \u2716 Swarm abort: all sub-agents hit iteration limit ${No}\xD7 \u2014 aborting stuck swarm${y.reset}`),_&&(_.stop(),_=null),x(null),Ze(de,Ie,Y,je,Ke,{suppressHint:!0}),Ce(T);return}}else P>0&&(No=0)}}if(yc&&Is&&!(be&&Pe==="verify")){yc=!1;let k=await wu(Y),w=await Ba(Y),W={role:"user",content:P_(Y,k,w)};T.push(W),v.push(W),j(`${y.cyan} \u21B3 Post-edit verify prompt injected (${k.length} checks, ${w.length} tests)${y.reset}`)}let Nv=[...Gt.values()].reduce((k,w)=>k+w,0);if(dr(Y,nt)&&Nv>=2){let k=`Implementation stalled before edits.
1740
+ ${q}`),Ce(T),wt(T)}_&&(_.stop(),_=null),x(null),Ze(de,Ie,Y,je,Ke,{suppressHint:!0}),Ce(T);return}}else Po=0;if(oe)Mo=0,fc=!0;else if(Mo++,Mo===vv){j(`${$.yellow} \u26A0 Loop warning: ${Mo} consecutive tool errors \u2014 possible stuck loop${$.reset}`);let P={role:"user",content:`[SYSTEM WARNING] ${Mo} consecutive errors. Stuck loop \u2014 try fundamentally different approach or declare done.`};T.push(P),v.push(P)}else if(Mo>=Sv){j(`${$.red} \u2716 Loop abort: ${Mo} consecutive errors \u2014 aborting stuck loop${$.reset}`),_&&(_.stop(),_=null),x(null),Ze(de,Ie,Y,je,Ke,{suppressHint:!0}),Ce(T);return}if(oe&&w.fnName==="read_file"&&w.args&&w.args.path){je.add(w.args.path),(Y.has(w.args.path)||_o.has(w.args.path)||ws.has(w.args.path))&&(qs.push(w.args.path),Is=!1,js=0),_o.delete(w.args.path),ws.delete(w.args.path);let P=ur(xr,w.args.path);{let se=w.args.line_start!=null&&parseInt(w.args.line_start,10)||1,Se=w.args.line_start!=null?parseInt(w.args.line_end,10)||se+350:350;to.has(w.args.path)||to.set(w.args.path,[]),to.get(w.args.path).push([se,Se])}if(w._scrollWarn){let{sectionCount:se,path:Se}=w._scrollWarn,Ee={role:"user",content:`[SYSTEM WARNING] "${Se}" \u2014 you have now read ${se} 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.`};T.push(Ee),v.push(Ee),j(`${$.yellow} \u26A0 Scroll warning: "${Se.split("/").slice(-2).join("/")}" \u2014 ${se} sections read \u2014 use grep instead${$.reset}`)}let q=w.args.path.split("/").slice(-2).join("/"),N=!w.args?.line_start&&!w.args?.line_end,U=be&&Pe==="plan";if(!U&&N&&P===_v){{let Se=xn();if(hs(v,Se).percentage>=60){let{messages:fe}=As(v,Se);v=fe}}j(`${$.yellow} \u26A0 Loop warning: "${q}" read unbounded ${P}\xD7 \u2014 use line_start/line_end${$.reset}`);let se={role:"user",content:`[SYSTEM WARNING] "${w.args.path}" read ${P}\xD7 without line ranges. Use line_start/line_end to read specific sections \u2014 do not re-read the full file.`};T.push(se),v.push(se)}else if(!U&&N&&P>=kv){j(`${$.red} \u2716 Loop abort: "${q}" read unbounded ${P}\xD7 \u2014 aborting runaway read loop${$.reset}`),_&&(_.stop(),_=null),x(null),Ze(de,Ie,Y,je,Ke,{suppressHint:!0}),Ce(T);return}}if(w.fnName==="spawn_agents"){let P=(W.match(/\bStatus: done\b/g)||[]).length;if((W.match(/\bStatus: truncated\b/g)||[]).length>0&&P===0){if(No++,No===Ev){j(`${$.yellow} \u26A0 Swarm warning: all sub-agents hit iteration limit ${No}\xD7 in a row${$.reset}`);let N={role:"user",content:`[SYSTEM WARNING] Sub-agents truncated ${No}\xD7 in a row. Stop spawning \u2014 try different approach or report findings.`};T.push(N),v.push(N)}else if(No>=Tv){console.log(`${$.red} \u2716 Swarm abort: all sub-agents hit iteration limit ${No}\xD7 \u2014 aborting stuck swarm${$.reset}`),_&&(_.stop(),_=null),x(null),Ze(de,Ie,Y,je,Ke,{suppressHint:!0}),Ce(T);return}}else P>0&&(No=0)}}if(yc&&Is&&!(be&&Pe==="verify")){yc=!1;let k=await wu(Y),w=await Ba(Y),W={role:"user",content:P_(Y,k,w)};T.push(W),v.push(W),j(`${$.cyan} \u21B3 Post-edit verify prompt injected (${k.length} checks, ${w.length} tests)${$.reset}`)}let Nv=[...Gt.values()].reduce((k,w)=>k+w,0);if(dr(Y,nt)&&Nv>=2){let k=`Implementation stalled before edits.
1741
1741
 
1742
1742
  The implementation phase attempted file edits, but the edits did not match the current file content. Stopping without commit or push so the workflow does not falsely report success.`,w={role:"assistant",content:k};T.push(w),v.push(w),console.log(`
1743
1743
  ${k}`),Ce(T),wt(T);break e}{let w=Ft.reduce((W,H)=>W+(typeof H.content=="string"?H.content.length:0),0);if(w>2e5){let W=Ft.map((H,oe)=>({i:oe,len:typeof H.content=="string"?H.content.length:0})).sort((H,oe)=>oe.len-H.len);for(let{i:H,len:oe}of W){if(w<=2e5)break;let $e=w-2e5,ce=Math.max(oe-$e,500);ce<oe&&typeof Ft[H].content=="string"&&(Ft[H]={...Ft[H],content:Ft[H].content.substring(0,ce)+`
1744
1744
  ...(truncated ${oe-ce} chars \u2014 per-message budget)`},w-=oe-ce)}}}for(let k of Ft)T.push(k),v.push(k);if(lc){let k=Ep(Qn());if(be&&Pe==="implement"&&Y.size===0&&nt===0||dr(Y,nt)){let W=`Implementation stalled before edits.
1745
1745
 
1746
1746
  The implementation phase reached the tool-call budget without changing files. Stopping without commit or push so the workflow does not falsely report success.`,H={role:"assistant",content:W};T.push(H),v.push(H),console.log(`
1747
- ${W}`),Ce(T),wt(T);break e}let w={role:"user",content:S_(yt,k)};T.push(w),v.push(w),cc=!0,Ku++}let Lv=dc&&He.some((k,w)=>{if(!k||!["write_file","edit_file","patch_file"].includes(k.fnName))return!1;let W=k.args?.path||k.args?.file_path;return xN(W)&&typeof Ft[w]?.content=="string"&&!Ft[w].content.startsWith("ERROR")&&!Ft[w].content.startsWith("BLOCKED:")});if(vn()&&!n.skillLoop&&Ju&&Lv){j(`${y.green} \u2713 Synthesis deliverable exit: text deliverable written after evidence threshold reached${y.reset}`),Ze(de,Ie,Y,je,Ke),Ce(T);break e}if(Zl(T,v),!Zt)for(let k=0;k<Ft.length;k++){if(!He[k]||He[k].fnName!=="ssh_exec")continue;let w=Ft[k];if(!w||typeof w.content!="string")continue;let W=Mp(w.content);if(W){Zt=!0,kn=W.slice(0,120),es=0,jn=!1,ts=0,j(`${y.yellow} \u26A1 Root cause detected: ${kn} \u2014 fix phase (read budget: 3)${y.reset}`);let H={role:"user",content:`[SYSTEM] Root cause identified: ${kn}. Read only the file that needs fixing, then edit it. Do not read other files.`};T.push(H),v.push(H);break}}for(let k=0;k<Ft.length;k++){let w=He[k];if(!w)continue;let W=typeof Ft[k]?.content=="string"?Ft[k].content:"";if(w.fnName==="create_task"){let H=W.match(/Task #(\d+) created/),oe=typeof w.args?.subject=="string"?w.args.subject:"";H&&oe&&ja.set(H[1],oe)}else if((w.fnName==="write_file"||w.fnName==="edit_file")&&!W.startsWith("BLOCKED:")&&W.trim().length>0){let oe=(typeof w.args?.path=="string"?w.args.path:typeof w.args?.file_path=="string"?w.args.file_path:"").split("/").pop().toLowerCase(),$e=oe.split(/[._\-/]/).filter(ce=>ce.length>2);for(let[ce,F]of ja){if(Da.has(ce))continue;let P=F.toLowerCase().split(/\W+/).filter(N=>N.length>3);$e.filter(N=>P.some(U=>U.includes(N)||N.includes(U))).length>=1&&(Da.add(ce),j(`${y.green} \u2714 Auto-matched task #${ce} to ${oe}: ${F.slice(0,60)}${y.reset}`))}}}{let k=xn();if(hs(v,k).percentage>=78){let{messages:W,tokensRemoved:H}=As(v,k);H>0&&(v=W,console.log(`${y.dim} [auto-compressed \u2014 ~${H} tokens freed, now ${Math.round(hs(v,k).percentage)}%]${y.reset}`))}}if(vn()&&!n.skillLoop&&(He.some(w=>w&&["write_file","edit_file","patch_file"].includes(w.fnName))?(_s=0,Ta=0):(_s===0&&(sm=Y.size),_s++),_s>=9&&de>=4&&Y.size===sm)){if(be&&Pe==="implement"&&Y.size===0&&nt===0||dr(Y,nt)){if(vo<3){vo++,_s=0;let H={role:"user",content:"[SYSTEM] You have enough targeted implementation context. Your next response must contain exactly one edit_file or patch_file tool call for the scoped change from the accepted plan. Do not call read_file, grep, glob, list_directory, bash, or git. Do not write prose before the tool call."};T.push(H),v.push(H),j(`${y.yellow} \u26A0 Implement phase read-only streak \u2014 nudging for edit (${vo}/3)${y.reset}`);continue}let w=`Implementation stalled before edits.
1747
+ ${W}`),Ce(T),wt(T);break e}let w={role:"user",content:S_(yt,k)};T.push(w),v.push(w),cc=!0,Ku++}let Lv=dc&&He.some((k,w)=>{if(!k||!["write_file","edit_file","patch_file"].includes(k.fnName))return!1;let W=k.args?.path||k.args?.file_path;return xN(W)&&typeof Ft[w]?.content=="string"&&!Ft[w].content.startsWith("ERROR")&&!Ft[w].content.startsWith("BLOCKED:")});if(vn()&&!n.skillLoop&&Ju&&Lv){j(`${$.green} \u2713 Synthesis deliverable exit: text deliverable written after evidence threshold reached${$.reset}`),Ze(de,Ie,Y,je,Ke),Ce(T);break e}if(Zl(T,v),!Zt)for(let k=0;k<Ft.length;k++){if(!He[k]||He[k].fnName!=="ssh_exec")continue;let w=Ft[k];if(!w||typeof w.content!="string")continue;let W=Mp(w.content);if(W){Zt=!0,kn=W.slice(0,120),es=0,jn=!1,ts=0,j(`${$.yellow} \u26A1 Root cause detected: ${kn} \u2014 fix phase (read budget: 3)${$.reset}`);let H={role:"user",content:`[SYSTEM] Root cause identified: ${kn}. Read only the file that needs fixing, then edit it. Do not read other files.`};T.push(H),v.push(H);break}}for(let k=0;k<Ft.length;k++){let w=He[k];if(!w)continue;let W=typeof Ft[k]?.content=="string"?Ft[k].content:"";if(w.fnName==="create_task"){let H=W.match(/Task #(\d+) created/),oe=typeof w.args?.subject=="string"?w.args.subject:"";H&&oe&&ja.set(H[1],oe)}else if((w.fnName==="write_file"||w.fnName==="edit_file")&&!W.startsWith("BLOCKED:")&&W.trim().length>0){let oe=(typeof w.args?.path=="string"?w.args.path:typeof w.args?.file_path=="string"?w.args.file_path:"").split("/").pop().toLowerCase(),$e=oe.split(/[._\-/]/).filter(ce=>ce.length>2);for(let[ce,F]of ja){if(Da.has(ce))continue;let P=F.toLowerCase().split(/\W+/).filter(N=>N.length>3);$e.filter(N=>P.some(U=>U.includes(N)||N.includes(U))).length>=1&&(Da.add(ce),j(`${$.green} \u2714 Auto-matched task #${ce} to ${oe}: ${F.slice(0,60)}${$.reset}`))}}}{let k=xn();if(hs(v,k).percentage>=78){let{messages:W,tokensRemoved:H}=As(v,k);H>0&&(v=W,console.log(`${$.dim} [auto-compressed \u2014 ~${H} tokens freed, now ${Math.round(hs(v,k).percentage)}%]${$.reset}`))}}if(vn()&&!n.skillLoop&&(He.some(w=>w&&["write_file","edit_file","patch_file"].includes(w.fnName))?(_s=0,Ta=0):(_s===0&&(sm=Y.size),_s++),_s>=9&&de>=4&&Y.size===sm)){if(be&&Pe==="implement"&&Y.size===0&&nt===0||dr(Y,nt)){if(vo<3){vo++,_s=0;let H={role:"user",content:"[SYSTEM] You have enough targeted implementation context. Your next response must contain exactly one edit_file or patch_file tool call for the scoped change from the accepted plan. Do not call read_file, grep, glob, list_directory, bash, or git. Do not write prose before the tool call."};T.push(H),v.push(H),j(`${$.yellow} \u26A0 Implement phase read-only streak \u2014 nudging for edit (${vo}/3)${$.reset}`);continue}let w=`Implementation stalled before edits.
1748
1748
 
1749
1749
  The implementation phase kept reading/searching without changing files. Stopping without commit or push so the workflow does not falsely report success.`,W={role:"assistant",content:w};T.push(W),v.push(W),console.log(`
1750
- ${w}`),_&&(_.stop(),_=null),x(null),Ze(de,Ie,Y,je,Ke),Ce(T),wt(T);break e}if(Ta<2){Ta++,_s=0;let w={role:"user",content:"[SYSTEM] You have spent several iterations investigating without making changes. If you have enough information: summarize findings and ask the user what to do next. If the task requires file edits: make them now instead of continuing to read. Do not invent facts \u2014 if blocked, state the blocker plainly."};T.push(w),v.push(w),j(`${y.yellow} \u26A0 Stagnation nudge ${Ta}/2 \u2014 ${Vl||_s} read-only iterations, no new file changes${y.reset}`),Vl=_s;continue}j(`${y.yellow} \u26A0 Stagnation persistence: ${Vl||9}+ read-only iterations \u2014 exiting with summary${y.reset}`),process.stdout.isTTY&&process.stderr.write(`${y.yellow} \u26A0 Investigation stalled: ${Vl||9}+ iterations without edits. Exiting so you can adjust the task or provide feedback.${y.reset}
1751
- `),_&&(_.stop(),_=null),x(null),Ze(de,Ie,Y,je,Ke),Ce(T);break e}let mm=DL();if(mm){let k={role:"user",content:`[User note mid-run]: ${mm}`};T.push(k),v.push(k),console.log(`${y.cyan} \u270E Context added${y.reset}`)}}if(Ct>=cn){if(_&&(_.stop(),_=null),x(null),Ze(de,Ie,Y,je,Ke),Ce(T),wt(T),be&&Pe==="plan"){let Ue=[...T].reverse().find($t=>$t.role==="assistant"),Ne=typeof Ue?.content=="string"?Ue.content:"";if(et&&Sn>=bu&&!Ra(Ne)){let $t=`no safe task found
1750
+ ${w}`),_&&(_.stop(),_=null),x(null),Ze(de,Ie,Y,je,Ke),Ce(T),wt(T);break e}if(Ta<2){Ta++,_s=0;let w={role:"user",content:"[SYSTEM] You have spent several iterations investigating without making changes. If you have enough information: summarize findings and ask the user what to do next. If the task requires file edits: make them now instead of continuing to read. Do not invent facts \u2014 if blocked, state the blocker plainly."};T.push(w),v.push(w),j(`${$.yellow} \u26A0 Stagnation nudge ${Ta}/2 \u2014 ${Vl||_s} read-only iterations, no new file changes${$.reset}`),Vl=_s;continue}j(`${$.yellow} \u26A0 Stagnation persistence: ${Vl||9}+ read-only iterations \u2014 exiting with summary${$.reset}`),process.stdout.isTTY&&process.stderr.write(`${$.yellow} \u26A0 Investigation stalled: ${Vl||9}+ iterations without edits. Exiting so you can adjust the task or provide feedback.${$.reset}
1751
+ `),_&&(_.stop(),_=null),x(null),Ze(de,Ie,Y,je,Ke),Ce(T);break e}let mm=DL();if(mm){let k={role:"user",content:`[User note mid-run]: ${mm}`};T.push(k),v.push(k),console.log(`${$.cyan} \u270E Context added${$.reset}`)}}if(Ct>=cn){if(_&&(_.stop(),_=null),x(null),Ze(de,Ie,Y,je,Ke),Ce(T),wt(T),be&&Pe==="plan"){let Ue=[...T].reverse().find($t=>$t.role==="assistant"),Ne=typeof Ue?.content=="string"?Ue.content:"";if(et&&Sn>=bu&&!Ra(Ne)){let $t=`no safe task found
1752
1752
 
1753
1753
  The bounded backlog plan phase used ${Sn} read/search tools without producing the required selected-improvement decision. Stopping before implementation because the workflow requires choosing one scoped task with files and verification evidence.`,At={role:"assistant",content:$t};T.push(At),console.log(`
1754
- ${$t}`),Ce(T),wt(T);break e}let Hn=await oi("implement",Ne);if(Hn){T.push(Hn),v=[{role:"system",content:await Qp()},...T],cn=bo("implement"),j(`${y.yellow} \u26A0 Plan budget exhausted \u2014 auto-transitioning to implement${y.reset}`);continue e}}else if(be&&Pe==="verify"){j(`${y.yellow} \u26A0 Verify budget exhausted \u2014 completing session${y.reset}`);break e}else if(be&&Pe==="implement"&&(Y.size>0||nt>0)){let Ue=[...T].reverse().find(Lo=>Lo.role==="assistant"),Ne=typeof Ue?.content=="string"?Ue.content:"",Hn=T.find(Lo=>Lo.role==="user"),$t=typeof Hn?.content=="string"?Hn.content:"",At=await oi("verify",Ne,Y,$t);if(At){T.push(At),v.push(At),cn=Math.min(bo("verify")+Math.max(0,(Y.size-2)*2),20),j(`${y.yellow} \u26A0 Implement budget exhausted after edits \u2014 auto-transitioning to verify${y.reset}`);continue e}}else if(be&&Pe==="implement"&&Y.size===0&&nt===0||dr(Y,nt)){let Ue=`Implementation stalled before edits.
1754
+ ${$t}`),Ce(T),wt(T);break e}let Hn=await oi("implement",Ne);if(Hn){T.push(Hn),v=[{role:"system",content:await Qp()},...T],cn=bo("implement"),j(`${$.yellow} \u26A0 Plan budget exhausted \u2014 auto-transitioning to implement${$.reset}`);continue e}}else if(be&&Pe==="verify"){j(`${$.yellow} \u26A0 Verify budget exhausted \u2014 completing session${$.reset}`);break e}else if(be&&Pe==="implement"&&(Y.size>0||nt>0)){let Ue=[...T].reverse().find(Lo=>Lo.role==="assistant"),Ne=typeof Ue?.content=="string"?Ue.content:"",Hn=T.find(Lo=>Lo.role==="user"),$t=typeof Hn?.content=="string"?Hn.content:"",At=await oi("verify",Ne,Y,$t);if(At){T.push(At),v.push(At),cn=Math.min(bo("verify")+Math.max(0,(Y.size-2)*2),20),j(`${$.yellow} \u26A0 Implement budget exhausted after edits \u2014 auto-transitioning to verify${$.reset}`);continue e}}else if(be&&Pe==="implement"&&Y.size===0&&nt===0||dr(Y,nt)){let Ue=`Implementation stalled before edits.
1755
1755
 
1756
1756
  The plan phase completed, but the implementation phase exhausted its turn budget without changing files. Stopping without commit or push so the workflow does not falsely report success.`,Ne={role:"assistant",content:Ue};T.push(Ne),v.push(Ne),console.log(`
1757
1757
  ${Ue}`),Ce(T),wt(T);break e}let{getActiveProviderName:he}=ft(),Ae=he();if(et&&Yt&&Y.size===0&&nt===0&&!fc){let Ue=`Implementation stalled before edits.
1758
1758
 
1759
1759
  The bounded backlog workflow reached its turn budget after planning but before changing files. Stopping without commit or push so the workflow does not falsely report success.`,Ne={role:"assistant",content:Ue};T.push(Ne),v.push(Ne),console.log(`
1760
- ${Ue}`),Ce(T),wt(T);break e}if(Ae==="ollama"&&Vu<cm){if(Y.size===0&&!fc){console.log(`${y.yellow} \u26A0 Max iterations reached with no progress. Stopping.${y.reset}`);break e}Vu++,cn=20,console.log(`${y.dim} \u2500\u2500 auto-extending (+20 turns, ext ${Vu}/${cm}) \u2500\u2500${y.reset}`);continue e}if(console.log(`
1761
- ${y.yellow}\u26A0 Max iterations reached.${y.reset}`),await L_(" Continue for 20 more turns?")){cn=20;continue e}console.log(`${y.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${y.reset}`)}break e}if(et&&Yt&&Y.size===0&&nt===0){let he=[...T].reverse().find(Ue=>Ue.role==="assistant"),Ae=typeof he?.content=="string"?he.content:"";if(!/\b(no safe task found|implementation stalled before edits)\b/i.test(Ae)){let Ue=`Implementation stalled before edits.
1760
+ ${Ue}`),Ce(T),wt(T);break e}if(Ae==="ollama"&&Vu<cm){if(Y.size===0&&!fc){console.log(`${$.yellow} \u26A0 Max iterations reached with no progress. Stopping.${$.reset}`);break e}Vu++,cn=20,console.log(`${$.dim} \u2500\u2500 auto-extending (+20 turns, ext ${Vu}/${cm}) \u2500\u2500${$.reset}`);continue e}if(console.log(`
1761
+ ${$.yellow}\u26A0 Max iterations reached.${$.reset}`),await L_(" Continue for 20 more turns?")){cn=20;continue e}console.log(`${$.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${$.reset}`)}break e}if(et&&Yt&&Y.size===0&&nt===0){let he=[...T].reverse().find(Ue=>Ue.role==="assistant"),Ae=typeof he?.content=="string"?he.content:"";if(!/\b(no safe task found|implementation stalled before edits)\b/i.test(Ae)){let Ue=`Implementation stalled before edits.
1762
1762
 
1763
1763
  The bounded backlog workflow ended after reading/searching but before changing files. Stopping without commit or push so the workflow does not falsely report success.`,Ne={role:"assistant",content:Ue};T.push(Ne),v.push(Ne),console.log(`
1764
1764
  ${Ue}`),Ze(de,Ie,Y,je,Ke),Ce(T),wt(T)}}await uc()}function sk(e,t,n,o=!1){return!o&&e&&t&&t.isComplex&&t.estimatedGoals>=n}ok.exports={processInput:iI,clearConversation:VL,getConversationLength:ZL,getConversationMessages:QL,setConversationMessages:eI,setAbortSignalGetter:oL,setMaxIterations:sL,invalidateSystemPromptCache:nu,clearToolFilterCache:fL,getCachedFilteredTools:U_,buildSystemPrompt:Qp,splitSystemPrompt:XL,SYSTEM_PROMPT_DYNAMIC_BOUNDARY:Zp,getProjectContextHash:W_,_inferVerificationCommands:wu,_inferRelevantTests:Ba,_inferSymbolTargets:Q_,_buildSymbolHintBlock:ek,_detectResponseLanguage:sh,_isSimpleDirectAnswerPrompt:tk,_claimsVerificationOrCompletion:Ip,_statesVerificationGap:jp,_shouldAutoOrchestrate:sk,_shouldSkipPlanPhaseForDirectCreation:Xp,_hasAutomationOrPreflightGate:Ua,_extractDirectTaskPaths:La,_isBoundedBacklogPlanningPrompt:z_,_buildBoundedBacklogPlanInstruction:Ns,_looksLikeBoundedBacklogDecision:Ra,_looksLikeGatedAutomationFinalSummary:Vp,buildUserContent:F_,_detectImageURLs:j_,_downloadImageURL:D_,_grabClipboardImage:q_,detectFrustration:B_,detectAndTruncateLoop:Dp,injectMidRunNote:jL,resetSessionTracking:nk}});var ft=Q((mF,lk)=>{var{OllamaProvider:aI,getOllamaRecommendations:cI}=fg(),{OpenAIProvider:lI}=vd(),{DeepSeekProvider:uI}=$g(),{AnthropicProvider:dI}=kg(),{GeminiProvider:fI}=Eg(),{LocalProvider:pI}=Cg(),{checkBudget:hI,formatProviderCostMode:mI,getProviderCostMode:gI}=os(),ah={top:{ollama:"kimi-k2:1t",openai:"gpt-4.1",deepseek:"deepseek-v4-pro",anthropic:"claude-sonnet-4-5",gemini:"gemini-2.5-pro"},strong:{ollama:"qwen3-coder:480b",openai:"gpt-4o",deepseek:"deepseek-v4-pro",anthropic:"claude-sonnet",gemini:"gemini-2.5-flash"},fast:{ollama:"devstral-small-2:24b",openai:"gpt-4.1-mini",deepseek:"deepseek-v4-flash",anthropic:"claude-haiku",gemini:"gemini-2.0-flash"}},ih=(process.env.OLLAMA_FALLBACK_CHAIN||"").split(",").map(e=>e.trim()).filter(Boolean),ik={};for(let[e,t]of Object.entries(ah))for(let n of Object.values(t))ik[n]=e;function ak(e,t){let n=ik[e];return n&&ah[n][t]||e}function xu(){return["No configured provider available.","Lowest-cost path: run /setup and choose Ollama Cloud, or set OLLAMA_API_KEY plus DEFAULT_PROVIDER=ollama.","Local free path: start Ollama locally, pull a coding model, then use /model local:<model>.","Paid fallback: set DEEPSEEK_API_KEY, OPENAI_API_KEY, ANTHROPIC_API_KEY, or GEMINI_API_KEY and use /fallback only when you want paid backup."].join(`
@@ -1793,20 +1793,20 @@ ${Ha} No key entered \u2014 cancelled.${Ge}
1793
1793
  ${Ga} \u2713 Saved to ${u}${Ge}`),a.some(m=>m.includes("API_KEY"))&&console.log(`${Wt} (key stored locally \u2014 never committed)${Ge}`)}if(process.env.DEFAULT_PROVIDER)try{let{setActiveModel:p}=ft(),h=process.env.DEFAULT_MODEL?`${process.env.DEFAULT_PROVIDER}:${process.env.DEFAULT_MODEL}`:process.env.DEFAULT_PROVIDER;p(h),console.log(`${Ga} \u2713 Switched to ${h} for this session${Ge}`)}catch{}console.log(`
1794
1794
  ${Ga} \u2713 Setup complete!${Ge}`),console.log(`
1795
1795
  ${Ya}Tip: Run ${gi}/models coding${Ge} ${Ya}to see cost-aware open-model recommendations, or ${gi}/benchmark${Ge} to tune routing for your tasks.${Ge}
1796
- `)}uk.exports={runSetupWizard:NI}});var Su=Q((yF,yk)=>{"use strict";var ys=require("fs"),za=require("path"),{atomicWrite:pk}=Hs(),LI=20,II=3,hk=3,jI=14400*1e3;function Ka(){return za.join(process.cwd(),".nex","dream-logs")}function dh(){return za.join(Ka(),"_meta.json")}function DI(){let e=Ka();return ys.existsSync(e)||ys.mkdirSync(e,{recursive:!0}),e}function mk(e){if(!Array.isArray(e)||e.length===0)return null;let t={},n={},o={},s={},r=0,i=0,a=0,c=0;for(let u of e){if(u.role==="user"&&a++,u.role==="assistant"&&c++,u.role==="assistant"&&Array.isArray(u.content)){for(let d of u.content)if(d&&d.type==="tool_use"){let f=d.name||"unknown";t[f]=(t[f]||0)+1,r++;let p=d.input||{},h=p.path||p.file_path||p.filePath||"";h&&((f==="read_file"||f==="glob"||f==="grep"||f==="search_files")&&(o[h]=(o[h]||0)+1),(f==="write_file"||f==="edit_file"||f==="patch_file")&&(s[h]=(s[h]||0)+1))}}if(u.role==="assistant"&&Array.isArray(u.tool_calls))for(let d of u.tool_calls){let f=d.function?.name||d.name||"unknown";t[f]=(t[f]||0)+1,r++}if(u.role==="tool"){let d=typeof u.content=="string"?u.content:"";if(d.includes("Error")||d.includes("error")||d.includes("FAILED")||d.includes("failed")||d.includes("not found")||d.includes("permission denied")){let f=u.name||"unknown";n[f]=(n[f]||0)+1,i++}}}return r<II?null:{timestamp:new Date().toISOString(),userMessages:a,assistantMessages:c,totalToolCalls:r,totalErrors:i,toolCalls:t,toolErrors:n,filesAccessed:dk(o,10),filesModified:dk(s,10)}}function qI(e){let t=mk(e);if(!t)return null;let n=DI(),o=`dream-${Date.now()}.json`,s=za.join(n,o);try{return pk(s,JSON.stringify(t,null,2)),UI(n),s}catch{return null}}function FI(){let e=dh();if(!ys.existsSync(e))return!0;try{let s=JSON.parse(ys.readFileSync(e,"utf-8")),r=new Date(s.lastConsolidation||0).getTime();if(Date.now()-r<jI)return!1}catch{return!0}let t=fh(),n=ph();return t.filter(s=>!n.processed?.includes(s)).length>=hk}function BI(){let e=fh(),t=ph(),n=e.filter(m=>!t.processed?.includes(m));if(n.length<hk)return{insights:[],memoriesWritten:0};let o=[];for(let m of n)try{let g=JSON.parse(ys.readFileSync(za.join(Ka(),m),"utf-8"));o.push(g)}catch{}if(o.length===0)return{insights:[],memoriesWritten:0};let s=[],r=0,i={},a={},c={};for(let m of o){for(let[g,$]of Object.entries(m.toolCalls||{}))i[g]=(i[g]||0)+$;for(let[g,$]of Object.entries(m.toolErrors||{}))a[g]=(a[g]||0)+$;for(let[g,$]of Object.entries(m.filesAccessed||{}))c[g]=(c[g]||0)+$}let u=[];for(let[m,g]of Object.entries(a)){let $=i[m]||g,b=g/$;b>.3&&g>=3&&u.push({tool:m,errors:g,calls:$,rate:Math.round(b*100)})}if(u.length>0){let m=u.sort((b,x)=>x.rate-b.rate).map(b=>`- ${b.tool}: ${b.rate}% error rate (${b.errors}/${b.calls} calls)`).join(`
1796
+ `)}uk.exports={runSetupWizard:NI}});var Su=Q((yF,yk)=>{"use strict";var ys=require("fs"),za=require("path"),{atomicWrite:pk}=Hs(),LI=20,II=3,hk=3,jI=14400*1e3;function Ka(){return za.join(process.cwd(),".nex","dream-logs")}function dh(){return za.join(Ka(),"_meta.json")}function DI(){let e=Ka();return ys.existsSync(e)||ys.mkdirSync(e,{recursive:!0}),e}function mk(e){if(!Array.isArray(e)||e.length===0)return null;let t={},n={},o={},s={},r=0,i=0,a=0,c=0;for(let u of e){if(u.role==="user"&&a++,u.role==="assistant"&&c++,u.role==="assistant"&&Array.isArray(u.content)){for(let d of u.content)if(d&&d.type==="tool_use"){let f=d.name||"unknown";t[f]=(t[f]||0)+1,r++;let p=d.input||{},h=p.path||p.file_path||p.filePath||"";h&&((f==="read_file"||f==="glob"||f==="grep"||f==="search_files")&&(o[h]=(o[h]||0)+1),(f==="write_file"||f==="edit_file"||f==="patch_file")&&(s[h]=(s[h]||0)+1))}}if(u.role==="assistant"&&Array.isArray(u.tool_calls))for(let d of u.tool_calls){let f=d.function?.name||d.name||"unknown";t[f]=(t[f]||0)+1,r++}if(u.role==="tool"){let d=typeof u.content=="string"?u.content:"";if(d.includes("Error")||d.includes("error")||d.includes("FAILED")||d.includes("failed")||d.includes("not found")||d.includes("permission denied")){let f=u.name||"unknown";n[f]=(n[f]||0)+1,i++}}}return r<II?null:{timestamp:new Date().toISOString(),userMessages:a,assistantMessages:c,totalToolCalls:r,totalErrors:i,toolCalls:t,toolErrors:n,filesAccessed:dk(o,10),filesModified:dk(s,10)}}function qI(e){let t=mk(e);if(!t)return null;let n=DI(),o=`dream-${Date.now()}.json`,s=za.join(n,o);try{return pk(s,JSON.stringify(t,null,2)),UI(n),s}catch{return null}}function FI(){let e=dh();if(!ys.existsSync(e))return!0;try{let s=JSON.parse(ys.readFileSync(e,"utf-8")),r=new Date(s.lastConsolidation||0).getTime();if(Date.now()-r<jI)return!1}catch{return!0}let t=fh(),n=ph();return t.filter(s=>!n.processed?.includes(s)).length>=hk}function BI(){let e=fh(),t=ph(),n=e.filter(m=>!t.processed?.includes(m));if(n.length<hk)return{insights:[],memoriesWritten:0};let o=[];for(let m of n)try{let g=JSON.parse(ys.readFileSync(za.join(Ka(),m),"utf-8"));o.push(g)}catch{}if(o.length===0)return{insights:[],memoriesWritten:0};let s=[],r=0,i={},a={},c={};for(let m of o){for(let[g,y]of Object.entries(m.toolCalls||{}))i[g]=(i[g]||0)+y;for(let[g,y]of Object.entries(m.toolErrors||{}))a[g]=(a[g]||0)+y;for(let[g,y]of Object.entries(m.filesAccessed||{}))c[g]=(c[g]||0)+y}let u=[];for(let[m,g]of Object.entries(a)){let y=i[m]||g,b=g/y;b>.3&&g>=3&&u.push({tool:m,errors:g,calls:y,rate:Math.round(b*100)})}if(u.length>0){let m=u.sort((b,x)=>x.rate-b.rate).map(b=>`- ${b.tool}: ${b.rate}% error rate (${b.errors}/${b.calls} calls)`).join(`
1797
1797
  `),g=`High-error tools detected across ${o.length} sessions:
1798
- ${m}`;s.push(g),fk("dream-error-prone-tools","Tools with high error rates across recent sessions",g)&&r++}let d=o.length,f={};for(let m of o){let g=new Set;for(let $ of Object.keys(m.filesAccessed||{}))g.has($)||(f[$]=(f[$]||0)+1,g.add($))}let p=Object.entries(f).filter(([m,g])=>g>d*.5&&(c[m]||0)>5).map(([m,g])=>({file:m,sessions:g,reads:c[m]||0})).sort((m,g)=>g.sessions-m.sessions).slice(0,10);if(p.length>0){let m=p.map(b=>`- ${b.file}: accessed in ${b.sessions}/${d} sessions (${b.reads} total reads)`).join(`
1798
+ ${m}`;s.push(g),fk("dream-error-prone-tools","Tools with high error rates across recent sessions",g)&&r++}let d=o.length,f={};for(let m of o){let g=new Set;for(let y of Object.keys(m.filesAccessed||{}))g.has(y)||(f[y]=(f[y]||0)+1,g.add(y))}let p=Object.entries(f).filter(([m,g])=>g>d*.5&&(c[m]||0)>5).map(([m,g])=>({file:m,sessions:g,reads:c[m]||0})).sort((m,g)=>g.sessions-m.sessions).slice(0,10);if(p.length>0){let m=p.map(b=>`- ${b.file}: accessed in ${b.sessions}/${d} sessions (${b.reads} total reads)`).join(`
1799
1799
  `),g=`Frequently accessed files across ${d} sessions:
1800
- ${m}`;s.push(g),fk("dream-hot-files","Files accessed frequently across multiple sessions",g)&&r++}let h=o.map(m=>m.userMessages===0?null:m.totalToolCalls/m.userMessages).filter(Boolean);if(h.length>=3){let m=h.reduce(($,b)=>$+b,0)/h.length,g=o.reduce(($,b)=>$+(b.totalErrors||0),0)/o.length;if(m>15){let $=`High tool-call density: avg ${m.toFixed(1)} tool calls per user message across ${o.length} sessions. Consider more targeted investigation.`;s.push($)}if(g>5){let $=`High error rate: avg ${g.toFixed(1)} errors per session across ${o.length} sessions.`;s.push($)}}return gk({lastConsolidation:new Date().toISOString(),processed:[...t.processed||[],...n],totalConsolidations:(t.totalConsolidations||0)+1}),{insights:s,memoriesWritten:r}}function dk(e,t=10){return Object.fromEntries(Object.entries(e).sort(([,n],[,o])=>o-n).slice(0,t))}function fh(){let e=Ka();if(!ys.existsSync(e))return[];try{return ys.readdirSync(e).filter(t=>t.startsWith("dream-")&&t.endsWith(".json")).sort()}catch{return[]}}function UI(e){try{let t=ys.readdirSync(e).filter(n=>n.startsWith("dream-")&&n.endsWith(".json")).sort();for(;t.length>LI;){let n=t.shift();ys.unlinkSync(za.join(e,n))}}catch{}}function ph(){let e=dh();if(!ys.existsSync(e))return{};try{return JSON.parse(ys.readFileSync(e,"utf-8"))}catch{return{}}}function gk(e){try{pk(dh(),JSON.stringify(e,null,2))}catch{}}function fk(e,t,n){try{let{saveMemory:o}=as();return o("feedback",e,n,t).ok}catch{return!1}}yk.exports={extractSessionStats:mk,writeDreamLog:qI,shouldConsolidate:FI,consolidate:BI,_getDreamDir:Ka,_listDreamLogs:fh,_readMeta:ph,_writeMeta:gk}});var _k=Q((bF,wk)=>{"use strict";var Eu=require("fs"),{T:En,isDark:WI}=ln(),on="\x1B[0m",HI=!WI,GI=process.env.FOOTER_DEBUG==="1"||process.env.FOOTER_DEBUG==="2",YI=process.env.FOOTER_DEBUG==="2",$F=process.env.FOOTER_DEBUG==="3",bi=null;function Eo(...e){GI&&(bi||(bi=Eu.openSync("/tmp/footer-debug.log","w",384)),Eu.writeSync(bi,e.join(" ")+`
1800
+ ${m}`;s.push(g),fk("dream-hot-files","Files accessed frequently across multiple sessions",g)&&r++}let h=o.map(m=>m.userMessages===0?null:m.totalToolCalls/m.userMessages).filter(Boolean);if(h.length>=3){let m=h.reduce((y,b)=>y+b,0)/h.length,g=o.reduce((y,b)=>y+(b.totalErrors||0),0)/o.length;if(m>15){let y=`High tool-call density: avg ${m.toFixed(1)} tool calls per user message across ${o.length} sessions. Consider more targeted investigation.`;s.push(y)}if(g>5){let y=`High error rate: avg ${g.toFixed(1)} errors per session across ${o.length} sessions.`;s.push(y)}}return gk({lastConsolidation:new Date().toISOString(),processed:[...t.processed||[],...n],totalConsolidations:(t.totalConsolidations||0)+1}),{insights:s,memoriesWritten:r}}function dk(e,t=10){return Object.fromEntries(Object.entries(e).sort(([,n],[,o])=>o-n).slice(0,t))}function fh(){let e=Ka();if(!ys.existsSync(e))return[];try{return ys.readdirSync(e).filter(t=>t.startsWith("dream-")&&t.endsWith(".json")).sort()}catch{return[]}}function UI(e){try{let t=ys.readdirSync(e).filter(n=>n.startsWith("dream-")&&n.endsWith(".json")).sort();for(;t.length>LI;){let n=t.shift();ys.unlinkSync(za.join(e,n))}}catch{}}function ph(){let e=dh();if(!ys.existsSync(e))return{};try{return JSON.parse(ys.readFileSync(e,"utf-8"))}catch{return{}}}function gk(e){try{pk(dh(),JSON.stringify(e,null,2))}catch{}}function fk(e,t,n){try{let{saveMemory:o}=as();return o("feedback",e,n,t).ok}catch{return!1}}yk.exports={extractSessionStats:mk,writeDreamLog:qI,shouldConsolidate:FI,consolidate:BI,_getDreamDir:Ka,_listDreamLogs:fh,_readMeta:ph,_writeMeta:gk}});var _k=Q((bF,wk)=>{"use strict";var Eu=require("fs"),{T:En,isDark:WI}=ln(),on="\x1B[0m",HI=!WI,GI=process.env.FOOTER_DEBUG==="1"||process.env.FOOTER_DEBUG==="2",YI=process.env.FOOTER_DEBUG==="2",$F=process.env.FOOTER_DEBUG==="3",bi=null;function Eo(...e){GI&&(bi||(bi=Eu.openSync("/tmp/footer-debug.log","w",384)),Eu.writeSync(bi,e.join(" ")+`
1801
1801
  `))}function $k(e,t){if(!YI||typeof t!="string")return;bi||(bi=Eu.openSync("/tmp/footer-debug.log","w",384));let n=t.replace(/\x1b\[([^a-zA-Z]*)([a-zA-Z])/g,(o,s,r)=>`<ESC[${s}${r}>`).replace(/\x1b([^[])/g,(o,s)=>`<ESC${s}>`).replace(/\r/g,"<CR>").replace(/\n/g,`<LF>
1802
1802
  `).replace(/[\x00-\x08\x0b-\x1f\x7f]/g,o=>`<${o.charCodeAt(0).toString(16).padStart(2,"0")}>`);Eu.writeSync(bi,`${e}: ${n}
1803
- `)}function bk(e){return e.replace(/\x1b\[[^a-zA-Z]*[a-zA-Z]/g,"").length}var hh=class{constructor(){this._active=!1,this._rl=null,this._origWrite=null,this._origPrompt=null,this._origSetPr=null,this._origRefreshLine=null,this._origLog=null,this._origError=null,this._origStderrWrite=null,this._drawing=!1,this._offResize=null,this._cursorOnInputRow=!1,this._inRefreshLine=!1,this._lastOutputRow=1,this._prevTermRows=0,this._prevTermCols=0,this._consistencyTimer=null,this._dirty=!1,this._statusModel="",this._statusBranch="",this._statusProject="",this._statusMode="",this._statusFilesMod=0,this._statusFilesScan=0}setStatusInfo({model:t,branch:n,project:o,mode:s}={}){t!==void 0&&(this._statusModel=t),n!==void 0&&(this._statusBranch=n),o!==void 0&&(this._statusProject=o),s!==void 0&&(this._statusMode=s),this._active&&this.drawFooter()}setFileInfo({modified:t,scanned:n}={}){t!==void 0&&(this._statusFilesMod=t),n!==void 0&&(this._statusFilesScan=n),this._active&&this.drawFooter()}get _rows(){return process.stdout.rows||24}get _cols(){return process.stdout.columns||80}get _scrollEnd(){return this._rows-2}get _rowStatus(){return this._rows-1}get _rowInput(){return this._rows}_goto(t,n=1){return`\x1B[${t};${n}H`}_statusLine(){let t=this._cols,n=this._statusModel,o=this._statusBranch,s=this._statusProject,r=this._statusMode;if(!n)return`${En.footer_sep}\u2550${"\u2550".repeat(Math.max(0,t-2))}\u2550${on}`;let i=` ${En.footer_divider}\u2502${on} `,a=o?`${En.footer_branch}git:${o}${on}`:"",c=s?`${En.footer_project}${s}${on}`:"",u=[];n&&u.push(`${En.footer_model}${n}${on}`),a&&u.push(a),c&&u.push(c);let d=u.join(i),f="",p=0;if(this._statusFilesMod>0||this._statusFilesScan>0){let x=[];this._statusFilesMod>0&&x.push(`${En.warning}\u270E ${this._statusFilesMod}${on}`),this._statusFilesScan>0&&x.push(`${En.subtle}\u25CC ${this._statusFilesScan}${on}`),f=` ${En.footer_divider}\u2502${on} ${x.join(" \xB7 ")}`,p=x.reduce((_,E)=>_+E.replace(/\x1b\[[^a-zA-Z]*[a-zA-Z]/g,"").length,0)+5}let m=[n,o?`git:${o}`:"",s].filter(Boolean).join(" \xB7 ").length+p,g="\u257C ";if(r){let x=`[${r}]`,_=x.length,E=Math.max(0,t-g.length-m-1-1-_-3),S="\u2550".repeat(E);return`${En.footer_sep}${g}${on}${d}${f}${En.footer_sep} ${S} ${on}${En.footer_mode}${x}${on}${En.footer_sep} \u257E${on}`}let $=Math.max(0,t-g.length-m-2),b="\u2550".repeat($);return`${En.footer_sep}${g}${on}${d}${f}${En.footer_sep} ${b}${on}`}drawFooter(t){!this._origWrite||this._drawing||(this._drawing=!0,this._origWrite("\x1B7"+this._goto(this._rowStatus)+"\x1B[2K"+this._statusLine(t)+"\x1B8"),this._drawing=!1)}_setScrollRegion(){if(HI)return;let t=Math.max(1,this._scrollEnd);this._origWrite(`\x1B[1;${t}r`)}_clearScrollRegion(){this._origWrite&&this._origWrite("\x1B[r")}_eraseStatus(){this._origWrite&&this._origWrite("\x1B7"+this._goto(this._rowStatus)+"\x1B[2K\x1B8")}rawWrite(t){return $k("RAW",t),this._origWrite?this._origWrite(t):process.stdout.write(t)}_relayout(t){if(!this._origWrite)return;let n=this._origWrite,o=this._rows,s=this._cols,r=Math.max(1,o-2);Eo("RELAYOUT:",t,"rows="+o,"cols="+s,"scrollEnd="+r,"cursorOnInput="+this._cursorOnInputRow),this._prevTermRows=o,this._prevTermCols=s;let i=Math.min(this._lastOutputRow+1,r+1),a="";for(let c=i;c<=o;c++)a+=this._goto(c)+"\x1B[2K";n(a),this._setScrollRegion(),this._lastOutputRow=Math.min(this._lastOutputRow,r),this.drawFooter(),this._cursorOnInputRow&&this._rl&&this._rl.prompt(!0),this._dirty=!1}activate(t){if(!process.stdout.isTTY||!t||typeof t.setPrompt!="function"||typeof t.prompt!="function")return;this._rl=t,this._origWrite=process.stdout.write.bind(process.stdout),this._active=!0,this._prevTermRows=this._rows,this._prevTermCols=this._cols,this._origWrite("\x1B[r"),this._setScrollRegion(),this._lastOutputRow=1,this.drawFooter();let n=this,o=process.stdout.write.bind(process.stdout);this._origWrite=o,process.stdout.write=function(h,...m){if($k("PATCH",h),!n._active||typeof h!="string")return o(h,...m);if(n._inRefreshLine){let _=h.replace(/\n/g,"");return _?o(_,...m):!0}if(n._cursorOnInputRow){if(h.length<=4&&!h.includes(`
1804
- `)&&!h.includes("\r"))return Eo("STDOUT: input-row intercept:",JSON.stringify(h)),n._origRefreshLine&&n._doRefreshLine(),!0;Eo("STDOUT: non-echo on input row, anchoring to workspace, data="+JSON.stringify(h).slice(0,100)),n._cursorOnInputRow=!1,o(n._goto(Math.min(n._lastOutputRow+1,n._scrollEnd)))}let g=n._cols||80,$=0,b=h.split(`
1805
- `);for(let _=0;_<b.length;_++){let E=bk(b[_]);E>0&&($+=Math.floor((E-1)/g))}let x=b.length-1;return x+$>0&&(n._lastOutputRow=Math.min(n._lastOutputRow+x+$,n._scrollEnd)),o(h,...m)},this._cursorOnInputRow=!1,this._origStderrWrite=process.stderr.write.bind(process.stderr),process.stderr.write=function(h,...m){if(!n._active)return n._origStderrWrite(h,...m);if(typeof h=="string"&&h.includes("\r")){let $=Math.min(n._lastOutputRow+1,n._scrollEnd);if(n._cursorOnInputRow){n._origWrite("\x1B7"),n._origWrite(n._goto($));let b=n._origStderrWrite(h,...m);return n._origWrite("\x1B8"),b}n._origWrite(n._goto($))}let g=n._origStderrWrite(h,...m);return typeof h=="string"&&h.includes(`
1806
- `)&&!/\x1b\[\d+A/.test(h)&&n._cursorOnInputRow&&(n.drawFooter(),n._origWrite(n._goto(n._rowInput)+"\x1B[2K")),g},this._origLog=console.log,this._origError=console.error;function s(...h){if(!n._active){n._origLog(...h);return}n._origWrite(n._goto(Math.min(n._lastOutputRow+1,n._scrollEnd))),n._cursorOnInputRow=!1,n._origLog(...h),n.drawFooter(),o(n._goto(n._rowInput)+"\x1B[2K"),n._cursorOnInputRow=!0}function r(...h){if(!n._active){n._origError(...h);return}n._origWrite(n._goto(Math.min(n._lastOutputRow+1,n._scrollEnd))),n._cursorOnInputRow=!1,n._origError(...h),n.drawFooter(),o(n._goto(n._rowInput)+"\x1B[2K"),n._cursorOnInputRow=!0}if(console.log=s,console.error=r,this._origSetPr=t.setPrompt.bind(t),t.setPrompt=function(h){n._origSetPr(h),n._active&&n.drawFooter(h)},this._origPrompt=t.prompt.bind(t),t.prompt=function(h){if(!n._active)return n._origPrompt(h);Eo("PROMPT: goto rowInput="+n._rowInput),t.prevRows=0,o(n._goto(n._rowInput)+on+"\x1B[2K"),n._cursorOnInputRow=!0,n._origPrompt(h)},typeof t.question=="function"){let h=t.question.bind(t);t.question=function(m,g){if(!n._active)return h(m,g);o(n._goto(n._rowInput)+"\x1B[2K"),t.prevRows=0,n._cursorOnInputRow=!0,h(m,$=>{o(n._goto(n._rowInput)+"\x1B[2K"),n._cursorOnInputRow=!1,n.drawFooter(),g($)})}}let i=Object.getPrototypeOf(t),a=Object.getOwnPropertySymbols(i).find(h=>h.toString()==="Symbol(_refreshLine)"),c=a?i[a].bind(t):t._refreshLine?t._refreshLine.bind(t):null;if(this._origRefreshLine=c,this._doRefreshLine=function(){if(!n._active||!c)return;if(n._rows!==n._prevTermRows||n._cols!==n._prevTermCols){n._dirty=!0;return}t.prevRows=0,o(n._goto(n._rowInput)+on+"\x1B[2K");let h=n._cols,m=t._prompt||"",g=bk(m),$=h-g-1;n._inRefreshLine=!0;try{if(t.line.length<=$){Eo("REFRESH: short line, len="+t.line.length),c();return}Eo("REFRESH: long line, len="+t.line.length+", max="+$);let b=t.line,x=t.cursor,_=Math.max(1,$-1),E=Math.max(0,x-_),S=(E>0?"\xAB":"")+b.slice(E,E+_+(E>0?0:1));t.line=S,t.cursor=S.length,c(),t.line=b,t.cursor=x}finally{n._inRefreshLine=!1}},c){let h=this._doRefreshLine;a&&Object.defineProperty(t,a,{value:h,writable:!0,configurable:!0}),t._refreshLine=h}t.on("line",()=>{n._active&&(Eo("LINE: leaving input row"),n._cursorOnInputRow=!1,o(n._goto(n._rowInput)+"\x1B[2K"),o(n._goto(Math.min(n._lastOutputRow+1,n._scrollEnd))),n.drawFooter())});let u=null,d=null,f=()=>{u=null,n._relayout("resize"),d&&clearTimeout(d),d=setTimeout(()=>{d=null,n._relayout("resize-cleanup")},300),d.unref?.()},p=()=>{n._dirty=!0,u&&clearTimeout(u),u=setTimeout(f,80),u.unref?.()};process.stdout.on("resize",p),this._offResize=()=>{process.stdout.off("resize",p),u&&(clearTimeout(u),u=null),d&&(clearTimeout(d),d=null)},this._consistencyTimer=setInterval(()=>{if(!n._active)return;let h=n._rows,m=n._cols;(n._dirty||h!==n._prevTermRows||m!==n._prevTermCols)&&(Eo("CONSISTENCY: dirty="+n._dirty+" rows="+h+"/"+n._prevTermRows+" cols="+m+"/"+n._prevTermCols),n._relayout("consistency"))},800),this._consistencyTimer.unref?.()}deactivate(){if(this._active){if(this._active=!1,this._offResize&&(this._offResize(),this._offResize=null),this._consistencyTimer&&(clearInterval(this._consistencyTimer),this._consistencyTimer=null),this._origStderrWrite&&(process.stderr.write=this._origStderrWrite,this._origStderrWrite=null),this._origLog&&(console.log=this._origLog,this._origLog=null),this._origError&&(console.error=this._origError,this._origError=null),this._origWrite&&(process.stdout.write=this._origWrite),this._rl&&(this._origPrompt&&(this._rl.prompt=this._origPrompt,this._origPrompt=null),this._origSetPr&&(this._rl.setPrompt=this._origSetPr,this._origSetPr=null),this._origRefreshLine)){let t=Object.getOwnPropertySymbols(Object.getPrototypeOf(this._rl)).find(n=>n.toString()==="Symbol(_refreshLine)");t&&delete this._rl[t],delete this._rl._refreshLine,this._origRefreshLine=null}this._eraseStatus(),this._clearScrollRegion(),this._origWrite=null}}};wk.exports={StickyFooter:hh}});var vk=Q((wF,xk)=>{var{C:Rt}=dt(),{listProviders:zI,getActiveProviderName:KI,getActiveModelId:XI,setActiveModel:VI}=ft();function kk(e,t,n={}){let{title:o="Select",hint:s="\u2191\u2193 navigate \xB7 Enter select \xB7 Esc cancel"}=n;return new Promise(r=>{let i=t.map((b,x)=>b.isHeader?-1:x).filter(b=>b>=0);if(i.length===0){r(null);return}let a=t.findIndex(b=>b.isCurrent),c=a>=0?i.indexOf(a):0;c<0&&(c=0);let u=process.stdout.rows?Math.max(process.stdout.rows-6,5):20,d=0;function f(){let b=i[c];return b<d?d=b:b>=d+u&&(d=b-u+1),{start:d,end:Math.min(t.length,d+u)}}let p=0;function h(){if(p>0){process.stdout.write(`\x1B[${p}A`);for(let S=0;S<p;S++)process.stdout.write(`\x1B[2K
1803
+ `)}function bk(e){return e.replace(/\x1b\[[^a-zA-Z]*[a-zA-Z]/g,"").length}var hh=class{constructor(){this._active=!1,this._rl=null,this._origWrite=null,this._origPrompt=null,this._origSetPr=null,this._origRefreshLine=null,this._origLog=null,this._origError=null,this._origStderrWrite=null,this._drawing=!1,this._offResize=null,this._cursorOnInputRow=!1,this._inRefreshLine=!1,this._lastOutputRow=1,this._prevTermRows=0,this._prevTermCols=0,this._consistencyTimer=null,this._dirty=!1,this._statusModel="",this._statusBranch="",this._statusProject="",this._statusMode="",this._statusFilesMod=0,this._statusFilesScan=0}setStatusInfo({model:t,branch:n,project:o,mode:s}={}){t!==void 0&&(this._statusModel=t),n!==void 0&&(this._statusBranch=n),o!==void 0&&(this._statusProject=o),s!==void 0&&(this._statusMode=s),this._active&&this.drawFooter()}setFileInfo({modified:t,scanned:n}={}){t!==void 0&&(this._statusFilesMod=t),n!==void 0&&(this._statusFilesScan=n),this._active&&this.drawFooter()}get _rows(){return process.stdout.rows||24}get _cols(){return process.stdout.columns||80}get _scrollEnd(){return this._rows-2}get _rowStatus(){return this._rows-1}get _rowInput(){return this._rows}_goto(t,n=1){return`\x1B[${t};${n}H`}_statusLine(){let t=this._cols,n=this._statusModel,o=this._statusBranch,s=this._statusProject,r=this._statusMode;if(!n)return`${En.footer_sep}\u2550${"\u2550".repeat(Math.max(0,t-2))}\u2550${on}`;let i=` ${En.footer_divider}\u2502${on} `,a=o?`${En.footer_branch}git:${o}${on}`:"",c=s?`${En.footer_project}${s}${on}`:"",u=[];n&&u.push(`${En.footer_model}${n}${on}`),a&&u.push(a),c&&u.push(c);let d=u.join(i),f="",p=0;if(this._statusFilesMod>0||this._statusFilesScan>0){let x=[];this._statusFilesMod>0&&x.push(`${En.warning}\u270E ${this._statusFilesMod}${on}`),this._statusFilesScan>0&&x.push(`${En.subtle}\u25CC ${this._statusFilesScan}${on}`),f=` ${En.footer_divider}\u2502${on} ${x.join(" \xB7 ")}`,p=x.reduce((_,E)=>_+E.replace(/\x1b\[[^a-zA-Z]*[a-zA-Z]/g,"").length,0)+5}let m=[n,o?`git:${o}`:"",s].filter(Boolean).join(" \xB7 ").length+p,g="\u257C ";if(r){let x=`[${r}]`,_=x.length,E=Math.max(0,t-g.length-m-1-1-_-3),S="\u2550".repeat(E);return`${En.footer_sep}${g}${on}${d}${f}${En.footer_sep} ${S} ${on}${En.footer_mode}${x}${on}${En.footer_sep} \u257E${on}`}let y=Math.max(0,t-g.length-m-2),b="\u2550".repeat(y);return`${En.footer_sep}${g}${on}${d}${f}${En.footer_sep} ${b}${on}`}drawFooter(t){!this._origWrite||this._drawing||(this._drawing=!0,this._origWrite("\x1B7"+this._goto(this._rowStatus)+"\x1B[2K"+this._statusLine(t)+"\x1B8"),this._drawing=!1)}_setScrollRegion(){if(HI)return;let t=Math.max(1,this._scrollEnd);this._origWrite(`\x1B[1;${t}r`)}_clearScrollRegion(){this._origWrite&&this._origWrite("\x1B[r")}_eraseStatus(){this._origWrite&&this._origWrite("\x1B7"+this._goto(this._rowStatus)+"\x1B[2K\x1B8")}rawWrite(t){return $k("RAW",t),this._origWrite?this._origWrite(t):process.stdout.write(t)}_relayout(t){if(!this._origWrite)return;let n=this._origWrite,o=this._rows,s=this._cols,r=Math.max(1,o-2);Eo("RELAYOUT:",t,"rows="+o,"cols="+s,"scrollEnd="+r,"cursorOnInput="+this._cursorOnInputRow),this._prevTermRows=o,this._prevTermCols=s;let i=Math.min(this._lastOutputRow+1,r+1),a="";for(let c=i;c<=o;c++)a+=this._goto(c)+"\x1B[2K";n(a),this._setScrollRegion(),this._lastOutputRow=Math.min(this._lastOutputRow,r),this.drawFooter(),this._cursorOnInputRow&&this._rl&&this._rl.prompt(!0),this._dirty=!1}activate(t){if(!process.stdout.isTTY||!t||typeof t.setPrompt!="function"||typeof t.prompt!="function")return;this._rl=t,this._origWrite=process.stdout.write.bind(process.stdout),this._active=!0,this._prevTermRows=this._rows,this._prevTermCols=this._cols,this._origWrite("\x1B[r"),this._setScrollRegion(),this._lastOutputRow=1,this.drawFooter();let n=this,o=process.stdout.write.bind(process.stdout);this._origWrite=o,process.stdout.write=function(h,...m){if($k("PATCH",h),!n._active||typeof h!="string")return o(h,...m);if(n._inRefreshLine){let _=h.replace(/\n/g,"");return _?o(_,...m):!0}if(n._cursorOnInputRow){if(h.length<=4&&!h.includes(`
1804
+ `)&&!h.includes("\r"))return Eo("STDOUT: input-row intercept:",JSON.stringify(h)),n._origRefreshLine&&n._doRefreshLine(),!0;Eo("STDOUT: non-echo on input row, anchoring to workspace, data="+JSON.stringify(h).slice(0,100)),n._cursorOnInputRow=!1,o(n._goto(Math.min(n._lastOutputRow+1,n._scrollEnd)))}let g=n._cols||80,y=0,b=h.split(`
1805
+ `);for(let _=0;_<b.length;_++){let E=bk(b[_]);E>0&&(y+=Math.floor((E-1)/g))}let x=b.length-1;return x+y>0&&(n._lastOutputRow=Math.min(n._lastOutputRow+x+y,n._scrollEnd)),o(h,...m)},this._cursorOnInputRow=!1,this._origStderrWrite=process.stderr.write.bind(process.stderr),process.stderr.write=function(h,...m){if(!n._active)return n._origStderrWrite(h,...m);if(typeof h=="string"&&h.includes("\r")){let y=Math.min(n._lastOutputRow+1,n._scrollEnd);if(n._cursorOnInputRow){n._origWrite("\x1B7"),n._origWrite(n._goto(y));let b=n._origStderrWrite(h,...m);return n._origWrite("\x1B8"),b}n._origWrite(n._goto(y))}let g=n._origStderrWrite(h,...m);return typeof h=="string"&&h.includes(`
1806
+ `)&&!/\x1b\[\d+A/.test(h)&&n._cursorOnInputRow&&(n.drawFooter(),n._origWrite(n._goto(n._rowInput)+"\x1B[2K")),g},this._origLog=console.log,this._origError=console.error;function s(...h){if(!n._active){n._origLog(...h);return}n._origWrite(n._goto(Math.min(n._lastOutputRow+1,n._scrollEnd))),n._cursorOnInputRow=!1,n._origLog(...h),n.drawFooter(),o(n._goto(n._rowInput)+"\x1B[2K"),n._cursorOnInputRow=!0}function r(...h){if(!n._active){n._origError(...h);return}n._origWrite(n._goto(Math.min(n._lastOutputRow+1,n._scrollEnd))),n._cursorOnInputRow=!1,n._origError(...h),n.drawFooter(),o(n._goto(n._rowInput)+"\x1B[2K"),n._cursorOnInputRow=!0}if(console.log=s,console.error=r,this._origSetPr=t.setPrompt.bind(t),t.setPrompt=function(h){n._origSetPr(h),n._active&&n.drawFooter(h)},this._origPrompt=t.prompt.bind(t),t.prompt=function(h){if(!n._active)return n._origPrompt(h);Eo("PROMPT: goto rowInput="+n._rowInput),t.prevRows=0,o(n._goto(n._rowInput)+on+"\x1B[2K"),n._cursorOnInputRow=!0,n._origPrompt(h)},typeof t.question=="function"){let h=t.question.bind(t);t.question=function(m,g){if(!n._active)return h(m,g);o(n._goto(n._rowInput)+"\x1B[2K"),t.prevRows=0,n._cursorOnInputRow=!0,h(m,y=>{o(n._goto(n._rowInput)+"\x1B[2K"),n._cursorOnInputRow=!1,n.drawFooter(),g(y)})}}let i=Object.getPrototypeOf(t),a=Object.getOwnPropertySymbols(i).find(h=>h.toString()==="Symbol(_refreshLine)"),c=a?i[a].bind(t):t._refreshLine?t._refreshLine.bind(t):null;if(this._origRefreshLine=c,this._doRefreshLine=function(){if(!n._active||!c)return;if(n._rows!==n._prevTermRows||n._cols!==n._prevTermCols){n._dirty=!0;return}t.prevRows=0,o(n._goto(n._rowInput)+on+"\x1B[2K");let h=n._cols,m=t._prompt||"",g=bk(m),y=h-g-1;n._inRefreshLine=!0;try{if(t.line.length<=y){Eo("REFRESH: short line, len="+t.line.length),c();return}Eo("REFRESH: long line, len="+t.line.length+", max="+y);let b=t.line,x=t.cursor,_=Math.max(1,y-1),E=Math.max(0,x-_),S=(E>0?"\xAB":"")+b.slice(E,E+_+(E>0?0:1));t.line=S,t.cursor=S.length,c(),t.line=b,t.cursor=x}finally{n._inRefreshLine=!1}},c){let h=this._doRefreshLine;a&&Object.defineProperty(t,a,{value:h,writable:!0,configurable:!0}),t._refreshLine=h}t.on("line",()=>{n._active&&(Eo("LINE: leaving input row"),n._cursorOnInputRow=!1,o(n._goto(n._rowInput)+"\x1B[2K"),o(n._goto(Math.min(n._lastOutputRow+1,n._scrollEnd))),n.drawFooter())});let u=null,d=null,f=()=>{u=null,n._relayout("resize"),d&&clearTimeout(d),d=setTimeout(()=>{d=null,n._relayout("resize-cleanup")},300),d.unref?.()},p=()=>{n._dirty=!0,u&&clearTimeout(u),u=setTimeout(f,80),u.unref?.()};process.stdout.on("resize",p),this._offResize=()=>{process.stdout.off("resize",p),u&&(clearTimeout(u),u=null),d&&(clearTimeout(d),d=null)},this._consistencyTimer=setInterval(()=>{if(!n._active)return;let h=n._rows,m=n._cols;(n._dirty||h!==n._prevTermRows||m!==n._prevTermCols)&&(Eo("CONSISTENCY: dirty="+n._dirty+" rows="+h+"/"+n._prevTermRows+" cols="+m+"/"+n._prevTermCols),n._relayout("consistency"))},800),this._consistencyTimer.unref?.()}deactivate(){if(this._active){if(this._active=!1,this._offResize&&(this._offResize(),this._offResize=null),this._consistencyTimer&&(clearInterval(this._consistencyTimer),this._consistencyTimer=null),this._origStderrWrite&&(process.stderr.write=this._origStderrWrite,this._origStderrWrite=null),this._origLog&&(console.log=this._origLog,this._origLog=null),this._origError&&(console.error=this._origError,this._origError=null),this._origWrite&&(process.stdout.write=this._origWrite),this._rl&&(this._origPrompt&&(this._rl.prompt=this._origPrompt,this._origPrompt=null),this._origSetPr&&(this._rl.setPrompt=this._origSetPr,this._origSetPr=null),this._origRefreshLine)){let t=Object.getOwnPropertySymbols(Object.getPrototypeOf(this._rl)).find(n=>n.toString()==="Symbol(_refreshLine)");t&&delete this._rl[t],delete this._rl._refreshLine,this._origRefreshLine=null}this._eraseStatus(),this._clearScrollRegion(),this._origWrite=null}}};wk.exports={StickyFooter:hh}});var vk=Q((wF,xk)=>{var{C:Rt}=dt(),{listProviders:zI,getActiveProviderName:KI,getActiveModelId:XI,setActiveModel:VI}=ft();function kk(e,t,n={}){let{title:o="Select",hint:s="\u2191\u2193 navigate \xB7 Enter select \xB7 Esc cancel"}=n;return new Promise(r=>{let i=t.map((b,x)=>b.isHeader?-1:x).filter(b=>b>=0);if(i.length===0){r(null);return}let a=t.findIndex(b=>b.isCurrent),c=a>=0?i.indexOf(a):0;c<0&&(c=0);let u=process.stdout.rows?Math.max(process.stdout.rows-6,5):20,d=0;function f(){let b=i[c];return b<d?d=b:b>=d+u&&(d=b-u+1),{start:d,end:Math.min(t.length,d+u)}}let p=0;function h(){if(p>0){process.stdout.write(`\x1B[${p}A`);for(let S=0;S<p;S++)process.stdout.write(`\x1B[2K
1807
1807
  `);process.stdout.write(`\x1B[${p}A`)}let b=[];b.push(` ${Rt.bold}${Rt.cyan}${o}${Rt.reset}`),b.push(` ${Rt.dim}${s}${Rt.reset}`),b.push("");let{start:x,end:_}=f();x>0&&b.push(` ${Rt.dim}\u2191 more${Rt.reset}`);for(let S=x;S<_;S++){let O=t[S];if(O.isHeader){b.push(` ${Rt.bold}${Rt.dim}${O.label}${Rt.reset}`);continue}let L=i[c]===S,I=L?`${Rt.cyan}> `:" ",D=O.isCurrent?` ${Rt.yellow}<current>${Rt.reset}`:"";L?b.push(`${I}${Rt.bold}${O.label}${Rt.reset}${D}`):b.push(`${I}${Rt.dim}${O.label}${Rt.reset}${D}`)}_<t.length&&b.push(` ${Rt.dim}\u2193 more${Rt.reset}`);let E=b.join(`
1808
1808
  `);process.stdout.write(E+`
1809
- `),p=b.length}e.pause();let m=process.stdin.isRaw;process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume();function g(){process.stdin.removeListener("keypress",$),process.stdin.isTTY&&m!==void 0&&process.stdin.setRawMode(m),e.resume()}function $(b,x){if(x){if(x.name==="up"||x.ctrl&&x.name==="p"){c>0&&(c--,h());return}if(x.name==="down"||x.ctrl&&x.name==="n"){c<i.length-1&&(c++,h());return}if(x.name==="return"){let _=t[i[c]];g(),r(_?_.value:null);return}if(x.name==="escape"||x.ctrl&&x.name==="c"){g(),r(null);return}}}process.stdin.on("keypress",$),h()})}async function JI(e){let t=zI(),n=KI(),o=XI(),s=[];for(let i of t)if(i.models.length!==0){s.push({label:i.provider,value:null,isHeader:!0});for(let a of i.models){let c=i.provider===n&&a.id===o;s.push({label:` ${a.name} (${i.provider}:${a.id})`,value:`${i.provider}:${a.id}`,isCurrent:c})}}let r=await kk(e,s,{title:"Select Model"});return r?(VI(r),console.log(`${Rt.green}Switched to ${r}${Rt.reset}`),!0):(console.log(`${Rt.dim}Cancelled${Rt.reset}`),!1)}xk.exports={pickFromList:kk,showModelPicker:JI}});var gh=Q((kF,Mk)=>{var Sk=require("fs"),ZI=require("path"),{atomicWrite:QI,withFileLockSync:e2}=Hs(),{callChat:Ek}=ft(),{remember:t2,listMemories:_F,recall:n2}=as(),mh=4,s2=`You are a memory optimization agent for an AI coding assistant called nex-code.
1809
+ `),p=b.length}e.pause();let m=process.stdin.isRaw;process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume();function g(){process.stdin.removeListener("keypress",y),process.stdin.isTTY&&m!==void 0&&process.stdin.setRawMode(m),e.resume()}function y(b,x){if(x){if(x.name==="up"||x.ctrl&&x.name==="p"){c>0&&(c--,h());return}if(x.name==="down"||x.ctrl&&x.name==="n"){c<i.length-1&&(c++,h());return}if(x.name==="return"){let _=t[i[c]];g(),r(_?_.value:null);return}if(x.name==="escape"||x.ctrl&&x.name==="c"){g(),r(null);return}}}process.stdin.on("keypress",y),h()})}async function JI(e){let t=zI(),n=KI(),o=XI(),s=[];for(let i of t)if(i.models.length!==0){s.push({label:i.provider,value:null,isHeader:!0});for(let a of i.models){let c=i.provider===n&&a.id===o;s.push({label:` ${a.name} (${i.provider}:${a.id})`,value:`${i.provider}:${a.id}`,isCurrent:c})}}let r=await kk(e,s,{title:"Select Model"});return r?(VI(r),console.log(`${Rt.green}Switched to ${r}${Rt.reset}`),!0):(console.log(`${Rt.dim}Cancelled${Rt.reset}`),!1)}xk.exports={pickFromList:kk,showModelPicker:JI}});var gh=Q((kF,Mk)=>{var Sk=require("fs"),ZI=require("path"),{atomicWrite:QI,withFileLockSync:e2}=Hs(),{callChat:Ek}=ft(),{remember:t2,listMemories:_F,recall:n2}=as(),mh=4,s2=`You are a memory optimization agent for an AI coding assistant called nex-code.
1810
1810
  Analyze this conversation history and extract actionable learnings the assistant should remember.
1811
1811
 
1812
1812
  Return ONLY valid JSON in this exact format:
@@ -1891,7 +1891,7 @@ ${i.content}`;n(a,c.content+d),s.push({name:a,reason:i.reason||"",action:"update
1891
1891
  ${me.bold}${me.cyan}\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557${me.reset}`),console.log(`${me.bold}${me.cyan}\u2551 nex-code Server Setup Wizard \u2551${me.reset}`),console.log(`${me.bold}${me.cyan}\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D${me.reset}
1892
1892
  `);let o=Object.keys(n);if(o.length>0&&(console.log(`${me.dim}Existing profiles: ${o.join(", ")}${me.reset}`),!await wi("Add or update a server profile?",!0))){console.log(`${me.dim}No changes made.${me.reset}
1893
1893
  `);return}let s={...n},r=!0;for(;r;){console.log(`
1894
- ${me.bold}\u2500\u2500\u2500 New Server Profile \u2500\u2500\u2500${me.reset}`);let c=await $n("Profile name (e.g. prod, staging, macbook)");if(!c){console.log(`${me.red} Name is required.${me.reset}`);continue}let u=await $n("Host / IP address");if(!u){console.log(`${me.red} Host is required.${me.reset}`);continue}let d=await $n("SSH user","root"),f=await $n("SSH port","22"),p=parseInt(f,10)||22,h=await $n("SSH key path (leave empty for SSH agent)",""),m=await $h("Operating system",["almalinux9","macos","ubuntu","debian","other"],"almalinux9"),g=await wi("Allow sudo commands?",!0),$={host:u,user:d};p!==22&&($.port=p),h&&($.key=h),m!=="other"&&($.os=m),g&&($.sudo=!0),s[c]=$,console.log(`
1894
+ ${me.bold}\u2500\u2500\u2500 New Server Profile \u2500\u2500\u2500${me.reset}`);let c=await $n("Profile name (e.g. prod, staging, macbook)");if(!c){console.log(`${me.red} Name is required.${me.reset}`);continue}let u=await $n("Host / IP address");if(!u){console.log(`${me.red} Host is required.${me.reset}`);continue}let d=await $n("SSH user","root"),f=await $n("SSH port","22"),p=parseInt(f,10)||22,h=await $n("SSH key path (leave empty for SSH agent)",""),m=await $h("Operating system",["almalinux9","macos","ubuntu","debian","other"],"almalinux9"),g=await wi("Allow sudo commands?",!0),y={host:u,user:d};p!==22&&(y.port=p),h&&(y.key=h),m!=="other"&&(y.os=m),g&&(y.sudo=!0),s[c]=y,console.log(`
1895
1895
  ${me.green}\u2713${me.reset} Profile "${c}" added: ${d}@${u}${p!==22?`:${p}`:""}${m!=="other"?` [${m}]`:""}`),r=await wi(`
1896
1896
  Add another server?`,!1)}yn.existsSync(e)||yn.mkdirSync(e,{recursive:!0}),yn.writeFileSync(t,JSON.stringify(s,null,2)+`
1897
1897
  `,"utf-8"),console.log(`
@@ -1904,8 +1904,8 @@ ${me.dim}Use /servers to list profiles, /servers ping to check connectivity.${me
1904
1904
  `)}async function Bk(e,t){let n=t||_i.join(process.cwd(),Fk),o=_i.join(n,"deploy.json"),s={};if(yn.existsSync(o))try{s=JSON.parse(yn.readFileSync(o,"utf-8"))}catch{}if(!e){let u=_i.join(n,"servers.json");if(yn.existsSync(u))try{e=JSON.parse(yn.readFileSync(u,"utf-8"))}catch{e={}}else e={}}let r=Object.keys(e);console.log(`
1905
1905
  ${me.bold}${me.cyan}\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557${me.reset}`),console.log(`${me.bold}${me.cyan}\u2551 Deploy Config Wizard \u2551${me.reset}`),console.log(`${me.bold}${me.cyan}\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D${me.reset}
1906
1906
  `);let i=Object.keys(s);i.length>0&&console.log(`${me.dim}Existing deploy configs: ${i.join(", ")}${me.reset}`);let a={...s},c=!0;for(;c;){console.log(`
1907
- ${me.bold}\u2500\u2500\u2500 New Deploy Config \u2500\u2500\u2500${me.reset}`);let u=await $n("Config name (e.g. prod, staging)");if(!u){console.log(`${me.red} Name is required.${me.reset}`);continue}let d;r.length>0?d=await $h("Target server",r,r[0]):d=await $n("Target server (profile name or user@host)");let f=await $h("Deploy method",["rsync","git"],"rsync"),p="",h=[],m="";if(f==="rsync"){p=await $n("Local path to sync (e.g. dist/ or ./build)","dist/");let E=await $n("Exclude paths (comma-separated, e.g. node_modules,.env)","node_modules,.env");h=E?E.split(",").map(S=>S.trim()).filter(Boolean):[]}else m=await $n("Branch to pull (leave empty for current remote branch)","main");let g=await $n(f==="git"?"Remote repo path (e.g. /home/deploy/my-app)":"Remote destination path (e.g. /var/www/app)");if(!g){console.log(`${me.red} Remote path is required.${me.reset}`);continue}let $=await $n("Command to run on remote after deploy (leave empty to skip)",""),b=await $n("Health check URL or remote command (leave empty to skip)",""),x={server:d,method:f,remote_path:g};f==="rsync"?(x.local_path=p,h.length>0&&(x.exclude=h)):m&&(x.branch=m),$&&(x.deploy_script=$),b&&(x.health_check=b),a[u]=x;let _=f==="git"?`${d}:${g}${m?` (${m})`:""}`:`${p.endsWith("/")?p:p+"/"} \u2192 ${d}:${g}`;console.log(`
1908
- ${me.green}\u2713${me.reset} Deploy config "${u}": [${f}] ${_}`),$&&console.log(` ${me.dim} Then: ${$}${me.reset}`),b&&console.log(` ${me.dim} Health: ${b}${me.reset}`),c=await wi(`
1907
+ ${me.bold}\u2500\u2500\u2500 New Deploy Config \u2500\u2500\u2500${me.reset}`);let u=await $n("Config name (e.g. prod, staging)");if(!u){console.log(`${me.red} Name is required.${me.reset}`);continue}let d;r.length>0?d=await $h("Target server",r,r[0]):d=await $n("Target server (profile name or user@host)");let f=await $h("Deploy method",["rsync","git"],"rsync"),p="",h=[],m="";if(f==="rsync"){p=await $n("Local path to sync (e.g. dist/ or ./build)","dist/");let E=await $n("Exclude paths (comma-separated, e.g. node_modules,.env)","node_modules,.env");h=E?E.split(",").map(S=>S.trim()).filter(Boolean):[]}else m=await $n("Branch to pull (leave empty for current remote branch)","main");let g=await $n(f==="git"?"Remote repo path (e.g. /home/deploy/my-app)":"Remote destination path (e.g. /var/www/app)");if(!g){console.log(`${me.red} Remote path is required.${me.reset}`);continue}let y=await $n("Command to run on remote after deploy (leave empty to skip)",""),b=await $n("Health check URL or remote command (leave empty to skip)",""),x={server:d,method:f,remote_path:g};f==="rsync"?(x.local_path=p,h.length>0&&(x.exclude=h)):m&&(x.branch=m),y&&(x.deploy_script=y),b&&(x.health_check=b),a[u]=x;let _=f==="git"?`${d}:${g}${m?` (${m})`:""}`:`${p.endsWith("/")?p:p+"/"} \u2192 ${d}:${g}`;console.log(`
1908
+ ${me.green}\u2713${me.reset} Deploy config "${u}": [${f}] ${_}`),y&&console.log(` ${me.dim} Then: ${y}${me.reset}`),b&&console.log(` ${me.dim} Health: ${b}${me.reset}`),c=await wi(`
1909
1909
  Add another deploy config?`,!1)}yn.existsSync(n)||yn.mkdirSync(n,{recursive:!0}),yn.writeFileSync(o,JSON.stringify(a,null,2)+`
1910
1910
  `,"utf-8"),console.log(`
1911
1911
  ${me.green}\u2713 Saved .nex/deploy.json (${Object.keys(a).length} config${Object.keys(a).length!==1?"s":""})${me.reset}`),console.log(`${me.dim}Use: deploy prod (or with explicit params)${me.reset}
@@ -1937,11 +1937,11 @@ ${d}
1937
1937
  ${p}
1938
1938
  `;Dt.writeFileSync(n,c),i=!0}let a=ki.join(process.cwd(),"README.md");if(Dt.existsSync(a))try{let c=Dt.readFileSync(a,"utf-8"),u=c.indexOf(Gk),d=c.indexOf(bh);if(u!==-1&&d!==-1){let f=I2(e);c=c.slice(0,u)+f+c.slice(d+bh.length),Dt.writeFileSync(a,c)}}catch{}return{saved:!0,envUpdated:i,changes:o}}var F2=/thinking|reasoning|instruct|planner|orchestrat/i;function B2(e){return F2.test(e)}function U2(e){if(!e||e.length===0)return{updated:!1};let t=ki.join(Au.homedir(),".nex-code","models.env");if(!Dt.existsSync(t))return{updated:!1};let n=Dt.readFileSync(t,"utf-8"),o=n.match(/^NEX_ORCHESTRATOR_MODEL=(.+)$/m),s=o?o[1].trim():null,i=[...e].sort((d,f)=>f.overall-d.overall)[0],a=s?e.find(d=>d.model===s):null,c=a?a.overall:0;if(i.model===s)return{updated:!1};if(c>0&&i.overall<c*1.05)return{updated:!1};let u=`NEX_ORCHESTRATOR_MODEL=${i.model}`;return o?n=n.replace(/^NEX_ORCHESTRATOR_MODEL=.+$/m,u):n+=`
1939
1939
  ${u}
1940
- `,Dt.writeFileSync(t,n),{updated:!0,previousModel:s,newModel:i.model}}zk.exports={findNewModels:P2,fetchCloudModels:Hk,loadKnownModels:wh,markBenchmarked:M2,updateReadme:j2,updateModelsEnv:D2,updateRoutingConfig:q2,generateBenchmarkBlock:Yk,checkOrchestratorCandidate:B2,updateOrchestratorModel:U2,SENTINEL_START:_h,SENTINEL_END:Cu}});var Ao=Q((RF,ix)=>{"use strict";var{C:J}=dt(),W2=ft(),{TOOL_DEFINITIONS:Kk}=rs(),{saveRoutingConfig:H2}=fs();function Co(e){let t=Array.isArray(e?.tasks)?e.tasks.flatMap(n=>typeof n=="string"?[n]:n&&typeof n=="object"?[n.title,n.task,n.description]:[]):[];return[e?.pattern,e?.query,e?.regex,e?.file_pattern,e?.include,e?.path,e?.command,e?.name,...t].filter(n=>typeof n=="string").join(" ")}function oo(e){return typeof e=="string"?e.toLowerCase():""}function G2(e,t=[]){let n=oo(e);return t.some(o=>n.includes(oo(o)))}function Sh(e,t=[]){let n=oo(e);return t.every(o=>n.includes(oo(o)))}function Eh(e=""){return/\b(test|jest|vitest|mocha|ava|pytest|cargo\s+test|go\s+test|rspec|phpunit|mix\s+test|npm\s+(run\s+)?test|pnpm\s+(run\s+)?test|yarn\s+test)\b/i.test(e)}function Y2(e=""){return/\b(lint|eslint|prettier|ruff|flake8|rubocop|golangci-lint|tsc(?:\s|$)|npm\s+run\s+lint|pnpm\s+run\s+lint|yarn\s+lint)\b/i.test(e)}function z2(e=""){return/\b(build|compile|tsc(?:\s|$)|webpack|vite\s+build|next\s+build|npm\s+run\s+build|pnpm\s+run\s+build|yarn\s+build|cargo\s+build|go\s+build)\b/i.test(e)}function Xk(e=""){return/\b(rg|grep|find|fd|ls|dir|sed|awk)\b/i.test(e)}function Va(e,t=[]){return e?.action!=="create"||!Array.isArray(e.tasks)||e.tasks.length===0?!1:Sh(Co(e),t)}function Vk(e,{pathIncludes:t=[],table:n="users",action:o="select",conditionTerms:s=[]}={}){if(!Xa(e)||!Sh(e.path,t))return!1;let r=oo(e.content);return!r.includes(o)||!r.includes(n)?!1:s.every(i=>G2(r,i))}function K2(e,t=[]){let n=Co(e);return Sh(n,t)}function kh(e,{pathIncludes:t=[],oldTexts:n=[],newTexts:o=[]}={}){if(typeof e?.path!="string"||!(t.length===0||t.some(f=>e.path.toLowerCase().includes(f.toLowerCase()))))return!1;let r=Array.isArray(e.patches)?e.patches.flatMap(f=>[f.old_text,f.new_text]).filter(f=>typeof f=="string"):[],i=typeof e.old_text=="string"?e.old_text:"",a=typeof e.new_text=="string"?e.new_text:"",c=[i,a,...r],u=n.length===0||n.some(f=>c.some(p=>p.includes(f))),d=o.length===0||o.some(f=>c.some(p=>p.includes(f)));return!u||!d?!1:i&&a?!0:Array.isArray(e.patches)&&e.patches.length>0}function Xa(e,{pathIncludes:t=[],contentIncludes:n=[]}={}){return typeof e?.path!="string"||typeof e?.content!="string"||!(t.length===0||t.some(s=>oo(e.path).includes(oo(s))))?!1:n.length===0||n.every(s=>oo(e.content).includes(oo(s)))}var Th=[{id:"read-package",category:"file-ops",prompt:"Read the file package.json and show me its contents.",expectedTool:"read_file",validateArgs:e=>typeof e.path=="string"&&e.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:e=>Xa(e,{pathIncludes:["nex-bench-test.txt"],contentIncludes:["benchmark run"]})},{id:"edit-file",category:"file-ops",prompt:'You already read src/config.js and confirmed it contains the exact text "debug: false". Replace that exact text with "debug: true".',expectedTool:["edit_file","patch_file"],validateArgs:e=>kh(e,{pathIncludes:["config"],oldTexts:["debug: false"],newTexts:["debug: true"]})},{id:"list-directory",category:"file-ops",prompt:"Show me all files and folders in the cli/ directory.",expectedTool:["list_directory","glob"],validateArgs:e=>!!(typeof e.path=="string"&&e.path.includes("cli")||typeof e.pattern=="string"&&e.pattern.includes("cli"))},{id:"glob-js-files",category:"file-ops",prompt:"Find all JavaScript files (*.js) recursively in the cli/ directory.",expectedTool:"glob",validateArgs:e=>typeof e.pattern=="string"&&e.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:e=>typeof e.path=="string"&&e.path.includes("index")&&typeof e.line_start=="number"&&typeof e.line_end=="number"},{id:"glob-ts-defs",category:"file-ops",prompt:"Find all TypeScript type definition files (*.d.ts) anywhere in the project.",expectedTool:"glob",validateArgs:e=>typeof e.pattern=="string"&&e.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:e=>Xa(e,{pathIncludes:[".gitignore"],contentIncludes:["node_modules","dist"]})},{id:"edit-version-bump",category:"file-ops",prompt:'You already read package.json and confirmed it contains the exact snippet `"version": "1.0.0"`. Do not inspect the repo again. Update it directly to `"version": "1.1.0"`.',expectedTool:["edit_file","patch_file"],validateArgs:e=>kh(e,{pathIncludes:["package.json"],oldTexts:["1.0.0",'"version": "1.0.0"','"version":"1.0.0"'],newTexts:["1.1.0",'"version": "1.1.0"','"version":"1.1.0"']})},{id:"grep-with-filter",category:"search",prompt:"Search for all calls to require() but only inside .js files in the cli/ directory.",expectedTool:["grep","search_files"],validateArgs:e=>(e.pattern||e.query||e.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:e=>typeof e.command=="string"&&e.command.includes("node")&&(e.command.includes("--version")||e.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:e=>(e.pattern||e.query||e.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:e=>(e.pattern||e.query||e.regex||"").includes("callStream")},{id:"search-todos",category:"search",prompt:"Find all TODO comments in the source code.",expectedTool:["grep","search_files","bash"],validateArgs:e=>JSON.stringify(e).toUpperCase().includes("TODO")},{id:"git-branch",category:"shell",prompt:"What git branch am I currently on?",expectedTool:["bash","git_status"],validateArgs:e=>(typeof e.command=="string"&&e.command.includes("git"),!0)},{id:"git-status",category:"shell",prompt:"Show me the current git status of the repository.",expectedTool:["bash","git_status"],validateArgs:e=>(typeof e.command=="string"&&e.command.includes("git status"),!0)},{id:"npm-install",category:"shell",prompt:"Run npm install to install project dependencies.",expectedTool:"bash",validateArgs:e=>typeof e.command=="string"&&e.command.includes("npm")},{id:"schema-strict",category:"schema",prompt:"Read the file README.md",expectedTool:"read_file",validateArgs:(e,t)=>{let n=t?.function?.parameters||{},o=n.required||[],s=Object.keys(n.properties||{});return o.every(r=>e[r]!==void 0)&&Object.keys(e).every(r=>s.includes(r))}},{id:"multi-step-version",category:"multi-step",prompt:"You need to determine the current project version. What tool do you call first to inspect the most likely source file?",expectedTool:["read_file","glob","list_directory","search_files"],validateArgs:e=>!!(typeof e.path=="string"&&/package\.json|package|version/i.test(e.path)||typeof e.pattern=="string"&&/package\.json|package|version/i.test(e.pattern)||/package\.json|package|version/i.test(Co(e)))},{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:e=>!!(typeof e.command=="string"&&e.command.includes("cli")||typeof e.pattern=="string"&&e.pattern.includes("cli")||typeof e.path=="string"&&e.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:e=>(e.pattern||e.query||e.regex||"").includes("useState")},{id:"frontend-create-component",category:"frontend",prompt:"There is no existing Button component and no need to inspect other files first. What tool call do you use first to create src/components/Button.jsx with a React functional Button component that accepts a label prop and renders a styled button element?",expectedTool:"write_file",validateArgs:e=>Xa(e,{pathIncludes:["button.","src/components"],contentIncludes:["Button","label","button"]})},{id:"frontend-edit-css",category:"frontend",prompt:"You already read src/styles.css and confirmed it contains the exact text `background-color: blue`. Change that exact value to `background-color: red`.",expectedTool:["edit_file","patch_file"],validateArgs:e=>kh(e,{pathIncludes:[".css","styles"],oldTexts:["background-color: blue"],newTexts:["background-color: red"]})},{id:"frontend-glob-components",category:"frontend",prompt:"Find all JSX and TSX component files in the components/ directory.",expectedTool:"glob",validateArgs:e=>typeof e.pattern=="string"&&(e.pattern.includes(".jsx")||e.pattern.includes(".tsx")||e.pattern.includes("{jsx,tsx}"))},{id:"frontend-list-assets",category:"frontend",prompt:"List all files in the src/assets/ directory.",expectedTool:["list_directory","glob"],validateArgs:e=>!!(typeof e.path=="string"&&e.path.includes("assets")||typeof e.pattern=="string"&&e.pattern.includes("assets"))},{id:"sysadmin-port-check",category:"sysadmin",prompt:"Which process is currently listening on port 3000?",expectedTool:["bash","sysadmin"],validateArgs:e=>typeof e.command=="string"?e.command.includes("lsof")||e.command.includes("ss")||e.command.includes("netstat")||e.command.includes("3000"):e.action==="network_status"},{id:"sysadmin-nginx-config",category:"sysadmin",prompt:"Create an nginx server block that proxies requests to localhost:3000. Save it to /etc/nginx/sites-available/myapp.",expectedTool:["write_file","bash"],validateArgs:e=>!!(e.path&&(e.path.includes("nginx")||e.path.includes("sites-available"))||e.command&&e.command.includes("nginx"))},{id:"sysadmin-service-status",category:"sysadmin",prompt:"Check the status of the nginx service and show if it is running.",expectedTool:["bash","service_manage","sysadmin"],validateArgs:e=>typeof e.command=="string"?e.command.includes("systemctl")||e.command.includes("service")||e.command.includes("nginx"):e.action==="status"&&typeof e.service=="string"?e.service.includes("nginx"):e.action==="service"&&e.service_action==="status"&&typeof e.service_name=="string"&&e.service_name.includes("nginx")},{id:"sysadmin-error-log",category:"sysadmin",prompt:"Show the last 100 lines of the nginx error log.",expectedTool:["bash","service_logs","sysadmin"],validateArgs:e=>typeof e.command=="string"?e.command.includes("tail")||e.command.includes("journalctl")||e.command.includes("nginx"):typeof e.service=="string"?e.service.includes("nginx"):e.action==="journalctl"&&typeof e.unit=="string"&&e.unit.includes("nginx")||e.action==="log_tail"&&typeof e.path=="string"&&/nginx|error/i.test(e.path)},{id:"sysadmin-docker-compose",category:"sysadmin",prompt:"Create a docker-compose.yml file for a Node.js application with a PostgreSQL database.",expectedTool:"write_file",validateArgs:e=>typeof e.path=="string"&&e.path.includes("docker-compose")&&typeof e.content=="string"},{id:"data-sql-query",category:"data",prompt:"Do not inspect the repo first. Write a SQL query to find all users who have not logged in for more than 30 days and save it to queries/inactive-users.sql.",expectedTool:"write_file",validateArgs:e=>Vk(e,{pathIncludes:["queries","inactive-users.sql"],conditionTerms:[["last_login","last seen","last_seen","last_sign_in","last_signin","logged_in_at","login_at","last_active_at","lastactivity"],["30 day","30-day","interval '30 day'","interval '30 days'","date_sub","datetime('now', '-30 days')","current_date - 30","now() - interval","dateadd(day, -30","add_months","interval '1 month'"]]})},{id:"data-find-json-key",category:"data",prompt:'Find all JSON files in the project that contain the key "userId".',expectedTool:["grep","search_files"],validateArgs:e=>(e.pattern||e.query||e.regex||"").includes("userId")},{id:"data-python-csv",category:"data",prompt:'There is no need to inspect the repo first. What tool call do you use first to create scripts/average_price.py with a Python script that reads data.csv and calculates the average of the "price" column?',expectedTool:"write_file",validateArgs:e=>Xa(e,{pathIncludes:["average_price.py","scripts"],contentIncludes:["data.csv","price"]})},{id:"data-find-migrations",category:"data",prompt:"Find all database migration files in this project.",expectedTool:["glob","search_files","grep"],validateArgs:e=>JSON.stringify(e).toLowerCase().includes("migrat")},{id:"data-find-schema",category:"data",prompt:"Find where the database schema or models are defined in this project.",expectedTool:["grep","glob","search_files","list_directory","bash"],validateArgs:e=>/schema|model|migration|prisma|dbml|typeorm|sequelize|orm|db|database|entity/i.test(Co(e))},{id:"data-write-query",category:"data",prompt:"Do not inspect the repo first. Write a SQL query to find all users who registered in the last 30 days and save it to queries/recent-users.sql.",expectedTool:"write_file",validateArgs:e=>Vk(e,{pathIncludes:["queries","recent-users.sql"],conditionTerms:[["created_at","registered_at","registered_on","signup_date","signed_up_at","joined_at","createdon","created_on"],["30 day","30-day","interval '30 day'","interval '30 days'","date_sub","datetime('now', '-30 days')","current_date - 30","now() - interval","dateadd(day, -30","add_months","interval '1 month'"]]})},{id:"data-read-env",category:"data",prompt:"Read the .env file to find the database connection string.",expectedTool:"read_file",validateArgs:e=>typeof e.path=="string"&&/\.env|env\./i.test(e.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:e=>typeof e.path=="string"&&e.path.includes("server")},{id:"resilience-file-not-found",category:"resilience",prompt:"read_file returned 'file not found' for src/utils/helpers.js. You need to find where the helper functions are now. Use a discovery or search tool as your next step, not read_file again. What tool do you use first?",expectedTool:["glob","bash","search_files","list_directory"],validateArgs:e=>{let t=Co(e);return/src|helper|util|helpers|\.js|find/i.test(t)}},{id:"resilience-large-file-nav",category:"resilience",prompt:"The file src/api.js is 2800 lines. You need to locate the authenticateUser function. Use a search-oriented tool first instead of reading the whole file. What is the most efficient tool call?",expectedTool:["bash","grep","search_files","glob"],validateArgs:e=>typeof e.command=="string"&&Xk(e.command)&&/authenticateuser|src\/api\.js/i.test(e.command)?!0:K2(e,["authenticateuser"])},{id:"resilience-broken-import",category:"resilience",prompt:"TypeScript reports: Cannot find module './config'. The file was recently renamed. Use a search or discovery tool first to find the new location. What tool do you use?",expectedTool:["glob","bash","search_files","grep","list_directory"],validateArgs:e=>{let t=Co(e);return/config|rename|module|import|\.ts|\.js|find|src|path/i.test(t)}},{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:e=>typeof e.path=="string"&&e.path.includes("parser")},{id:"resilience-grep-no-match",category:"resilience",prompt:"grep returned zero matches for 'getUserById' in src/. The function exists but may have been renamed. Use a search tool to list exported function names in src/ and identify the current name. What tool call do you use first?",expectedTool:["bash","grep","search_files"],validateArgs:e=>typeof e.command=="string"?Xk(e.command)&&/src|export|function|module\.exports|exports\./i.test(e.command):/getUserById|export|function|module\.exports|exports\.|src|public|def /i.test(Co(e))},{id:"ssh-exec-log",category:"ssh",prompt:'Show the last 50 lines of /var/log/nginx/error.log on server "prod-1".',expectedTool:["ssh_exec","service_logs","sysadmin"],validateArgs:e=>typeof e.command=="string"?(e.command.includes("tail")||e.command.includes("log"))&&typeof e.server=="string":typeof e.service=="string"?e.service.includes("nginx"):typeof e.server=="string"&&(e.action==="journalctl"&&typeof e.unit=="string"&&e.unit.includes("nginx")||e.action==="log_tail"&&typeof e.path=="string"&&/nginx|error/i.test(e.path))},{id:"ssh-exec-service",category:"ssh",prompt:'Restart the nginx service on server "prod-1".',expectedTool:["ssh_exec","service_manage","sysadmin"],validateArgs:e=>typeof e.command=="string"?(e.command.includes("nginx")||e.command.includes("systemctl")||e.command.includes("restart"))&&typeof e.server=="string":e.action==="restart"&&typeof e.service=="string"&&e.service.includes("nginx")?!0:e.action==="service"&&e.service_action==="restart"&&typeof e.service_name=="string"&&e.service_name.includes("nginx")&&typeof e.server=="string"},{id:"ssh-exec-port",category:"ssh",prompt:'Check if port 8080 is listening on server "prod-1".',expectedTool:["ssh_exec","sysadmin"],validateArgs:e=>typeof e.command=="string"?(e.command.includes("8080")||e.command.includes("ss")||e.command.includes("netstat")||e.command.includes("lsof"))&&typeof e.server=="string":e.action==="network_status"&&typeof e.server=="string"},{id:"ssh-exec-processes",category:"ssh",prompt:'Show the top CPU-consuming processes on server "prod-1".',expectedTool:["ssh_exec","sysadmin"],validateArgs:e=>typeof e.command=="string"?(e.command.includes("top")||e.command.includes("ps")||e.command.includes("htop"))&&typeof e.server=="string":e.action==="process_list"&&typeof e.server=="string"},{id:"git-diff-staged",category:"git",prompt:"Show all staged changes before committing.",expectedTool:["git_diff","bash"],validateArgs:e=>!!(e.staged===!0||e.staged==="true"||typeof e.command=="string"&&e.command.includes("diff"))},{id:"git-log-recent",category:"git",prompt:"Show the last 5 commit messages with their hashes.",expectedTool:["git_log","bash"],validateArgs:e=>!!(typeof e.count=="number"||typeof e.limit=="number"||typeof e.n=="number"||typeof e.command=="string"&&e.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:e=>(Object.keys(e||{}).length===0||typeof e.command=="string"&&e.command.includes("status"),!0)},{id:"agentic-test-first",category:"agentic",prompt:"You need to run the full test suite first. Do not inspect files before that. If any tests fail after the run, identify the failing test file and read it to understand the issue. What is the first tool call?",expectedTool:["bash","task_list"],validateArgs:e=>typeof e.command=="string"?Eh(e.command):Va(e,["test"])},{id:"agentic-read-then-act",category:"agentic",prompt:"Read the project README.md, find the TODO section, and list which items are completed.",expectedTool:"read_file",validateArgs:e=>typeof e.path=="string"&&e.path.includes("README")},{id:"agentic-build-deploy",category:"agentic",prompt:"Build the project with npm run build, then verify the output exists in the dist/ directory.",expectedTool:["bash","task_list"],validateArgs:e=>{if(typeof e.command=="string")return e.command.includes("build")||e.command.includes("npm");let t=Co(e);return e.action==="create"&&/build|dist/i.test(t)}},{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:e=>Array.isArray(e.agents)&&e.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:e=>Array.isArray(e.agents)&&e.agents.length>=2}],Jk=[{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:e=>typeof e.path=="string"&&/users/i.test(e.path)},{id:"phase-plan-search",category:"phase-plan",prompt:"We're getting CORS errors in production. Search the codebase for where CORS middleware is configured.",expectedTool:["grep","search_files"],validateArgs:e=>{let t=e.pattern||e.query||e.regex||"";return/cors/i.test(t)}},{id:"phase-plan-context",category:"phase-plan",prompt:"The login page shows a blank screen after the last deploy. Check git log for recent changes that might have broken it.",expectedTool:["git_log","bash"],validateArgs:e=>(typeof e.command=="string"&&e.command.includes("log"),!0)},{id:"phase-verify-test",category:"phase-verify",prompt:"You are explicitly in the verify phase. Do not inspect files first. The first verification step is to run tests for a fix in src/utils.js. What tool call do you use first?",expectedTool:["bash","task_list"],validateArgs:e=>typeof e.command=="string"?Eh(e.command):Va(e,["test"])},{id:"phase-verify-read",category:"phase-verify",prompt:"A patch was applied to config/database.js to fix the connection pool. Read the file to verify the changes look correct.",expectedTool:"read_file",validateArgs:e=>typeof e.path=="string"&&/database/i.test(e.path)},{id:"phase-verify-lint",category:"phase-verify",prompt:"You are explicitly in the verify phase. Do not inspect files first. The first verification step is to run linting after changes in src/components/Header.tsx. What tool call do you use first?",expectedTool:["bash","task_list"],validateArgs:e=>typeof e.command=="string"?Y2(e.command):Va(e,["lint"])},{id:"phase-plan-git-blame",category:"phase-plan",prompt:"A production bug was introduced 2 days ago. Use git log to find commits from the last 2 days to identify what changed.",expectedTool:["git_log","bash"],validateArgs:e=>(typeof e.command=="string"&&e.command.includes("log"),!0)},{id:"phase-plan-error-trace",category:"phase-plan",prompt:"The error stack trace mentions src/middleware/auth.js line 87. Read the file around that line to understand the bug.",expectedTool:"read_file",validateArgs:e=>typeof e.path=="string"&&/auth/i.test(e.path)},{id:"phase-plan-grep-config",category:"phase-plan",prompt:"Users report the app is using wrong API keys in staging. Search for where API_KEY is loaded from environment.",expectedTool:["grep","search_files"],validateArgs:e=>{let t=e.pattern||e.query||e.regex||"";return/api.?key|env/i.test(t)}},{id:"phase-verify-build",category:"phase-verify",prompt:"You are in the verify phase. Do not inspect files first. The TypeScript source was modified, so run the build command to verify there are no compilation errors.",expectedTool:["bash","task_list"],validateArgs:e=>typeof e.command=="string"?z2(e.command):Va(e,["build"])},{id:"phase-verify-git-diff",category:"phase-verify",prompt:"Changes were just committed. Show the git diff of the last commit to verify only the intended files were modified.",expectedTool:["git_diff","bash"],validateArgs:e=>(e.command&&/git.*diff|diff.*HEAD/.test(e.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:e=>typeof e.path=="string"&&/config|production|deploy/i.test(e.path)}],Zk=[{id:"phase-implement-edit",category:"phase-implement",prompt:"You need to change the default port from 3000 to 8080 in config/server.js. Read the file first, then make the edit.",expectedTool:"read_file",validateArgs:e=>typeof e.path=="string"&&/server/i.test(e.path)},{id:"phase-implement-write",category:"phase-implement",prompt:"Create a new file src/utils/retry.js that exports an async retry helper function. Use write_file to create it.",expectedTool:"write_file",validateArgs:e=>typeof e.path=="string"&&/retry/i.test(e.path)},{id:"phase-implement-grep-edit",category:"phase-implement",prompt:'Find all places where "old_api_endpoint" is used in src/ and update them to "new_api_endpoint". Start by searching for the string.',expectedTool:["grep","search_files"],validateArgs:e=>{let t=(e.pattern||e.query||e.regex||"").toLowerCase();return t.includes("old_api_endpoint")||t.includes("old.api")}},{id:"phase-implement-patch",category:"phase-implement",prompt:"You need to add error handling to src/services/api.js. Read the file first, then use patch_file to add try/catch blocks.",expectedTool:"read_file",validateArgs:e=>typeof e.path=="string"&&/api/i.test(e.path)},{id:"phase-implement-test-after-edit",category:"phase-implement",prompt:"You just edited src/controllers/user.js to fix a validation bug. After making the edit, what should you do next to verify?",expectedTool:["bash","task_list"],validateArgs:e=>typeof e.command=="string"?Eh(e.command):Va(e,["test"])}],Ja=[...Th,...Jk,...Zk],xh=["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 X2(){try{let n=require("path").join(require("os").homedir(),".nex-code","benchmark-results.json");if(!require("fs").existsSync(n))return xh;let o=JSON.parse(require("fs").readFileSync(n,"utf-8"));return!Array.isArray(o)||o.length===0?xh:o.filter(s=>typeof s.score=="number"&&s.score>=60).sort((s,r)=>r.score-s.score).slice(0,12).map(s=>s.model)}catch{return xh}}var Rh=X2(),V2=["minimax-m2.7:cloud","qwen3-coder:480b","devstral-2:123b"],Ch=(()=>{let e=Rh.slice(0,3);return e.length>=3?e:V2})(),J2=14,Ou={producedToolCall:.2,correctTool:.35,validArgs:.3,schemaCompliant:.15},Z2="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 vh(e,t){let n={taskId:e.id,category:e.category,model:t,producedToolCall:!1,correctTool:!1,validArgs:!1,schemaCompliant:!1,toolCalled:null,error:null,latencyMs:0},o=[{role:"system",content:Z2},{role:"user",content:e.prompt}],s=Date.now();try{let r=await W2.callChat(o,Kk,{provider:"ollama",model:t,temperature:0,timeout:9e4});n.latencyMs=Date.now()-s;let i=r.tool_calls||[];if(e.expectedTool===null){let a=i.length===0;n.producedToolCall=a,n.correctTool=a,n.validArgs=!0,n.schemaCompliant=!0}else if(i.length>0){n.producedToolCall=!0;let a=Array.isArray(e.expectedTool)?e.expectedTool:[e.expectedTool],c=-1,u=i[0].function?.name||"unknown",d=!1,f=!1,p=!1;for(let h of i){let m=h.function?.name||"unknown",g=h.function?.arguments||{},$=a.includes(m),b=!1,x=!1,_=0;if($){let E=Kk.find(S=>S.function?.name===m);if(b=!!e.validateArgs(g,E),E){let S=E.function?.parameters||{},O=S.required||[],L=Object.keys(S.properties||{});x=O.every(I=>g[I]!==void 0)&&Object.keys(g).every(I=>L.includes(I))}_=($?2:0)+(b?1:0)+(x?.5:0)}_>c&&(c=_,u=m,d=$,f=b,p=x)}n.toolCalled=d?u:i[0].function?.name||"unknown",n.correctTool=d,n.validArgs=f,n.schemaCompliant=p}}catch(r){n.latencyMs=Date.now()-s,n.error=r.message.slice(0,120)}return n}function wr(e){return e.error?0:((e.producedToolCall?Ou.producedToolCall:0)+(e.correctTool?Ou.correctTool:0)+(e.validArgs?Ou.validArgs:0)+(e.schemaCompliant?Ou.schemaCompliant:0))*100}var Qk={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 Ah(e){return Object.entries(e).map(([t,n])=>{let o=n.map(wr),s=o.reduce((a,c)=>a+c,0)/o.length,r=a=>Math.round(n.filter(a).length/n.length*100),i={};for(let a of["coding","frontend","sysadmin","data","agentic","bug-fix","feature-add","refactor","plan","implement","verify"]){let c=n.filter(d=>Qk[d.category]===a);if(c.length===0)continue;let u=c.map(wr).reduce((d,f)=>d+f,0)/c.length;i[a]=Math.round(u*10)/10}return{model:t,score:Math.round(s*10)/10,toolCallRate:r(a=>!a.error&&(a.producedToolCall||a.category==="reasoning")),correctRate:r(a=>a.correctTool),validArgsRate:r(a=>a.validArgs),schemaRate:r(a=>a.schemaCompliant),avgLatency:Math.round(n.reduce((a,c)=>a+c.latencyMs,0)/n.length),errorCount:n.filter(a=>a.error).length,categoryScores:i,results:n}}).sort((t,n)=>n.score-t.score)}function ex(e){return tx(e)}function tx(e){let t={};for(let r of["coding","frontend","sysadmin","data","agentic","plan","verify"]){let i=e.filter(p=>p.categoryScores[r]!==void 0&&p.score>=65).sort((p,h)=>h.categoryScores[r]-p.categoryScores[r]);if(i.length===0||(i[0]?.results||[]).filter(p=>Qk[p.category]===r).length<4)continue;let u=i[0],f=i.filter(p=>u.categoryScores[r]-p.categoryScores[r]<=5).sort((p,h)=>p.avgLatency-h.avgLatency)[0];t[r]={model:f.model,score:f.categoryScores[r],avgLatency:f.avgLatency}}return t}function nx(e,t){let n=`nex-code Model Benchmark (${t} tasks \xB7 ollama cloud)`,o=[{label:"#",width:3},{label:"Model",width:26},{label:"Score",width:7},{label:"Tool\u2713",width:7},{label:"Name\u2713",width:7},{label:"Args\u2713",width:7},{label:"Schema\u2713",width:8},{label:"Latency",width:8},{label:"Err",width:4}],s=o.reduce((d,f)=>d+f.width+1,0)+1,r="\u2500".repeat(s);console.log(`
1941
- ${J.bold}${n}${J.reset}`),console.log(r);let i=o.map(d=>d.label.padEnd(d.width)).join(" ");if(console.log(`${J.dim}${i}${J.reset}`),console.log(r),e.forEach((d,f)=>{let p=String(f+1).padEnd(o[0].width),h=d.model.slice(0,o[1].width).padEnd(o[1].width),m=String(d.score).padEnd(o[2].width),g=`${d.toolCallRate}%`.padEnd(o[3].width),$=`${d.correctRate}%`.padEnd(o[4].width),b=`${d.validArgsRate}%`.padEnd(o[5].width),x=`${d.schemaRate}%`.padEnd(o[6].width),_=`${(d.avgLatency/1e3).toFixed(1)}s`.padEnd(o[7].width),E=d.errorCount>0?`${J.red}${d.errorCount}${J.reset}`:`${J.dim}0${J.reset}`,S=d.score>=80?J.green:d.score>=60?J.yellow:J.red,O=f===0?`${J.yellow}${p}${J.reset}`:`${J.dim}${p}${J.reset}`;console.log(`${O} ${S}${h}${J.reset} ${J.bold}${S}${m}${J.reset} ${g} ${$} ${b} ${x} ${J.dim}${_}${J.reset} ${E}`)}),console.log(r),e.length>0){let d=e[0];if(console.log(`
1940
+ `,Dt.writeFileSync(t,n),{updated:!0,previousModel:s,newModel:i.model}}zk.exports={findNewModels:P2,fetchCloudModels:Hk,loadKnownModels:wh,markBenchmarked:M2,updateReadme:j2,updateModelsEnv:D2,updateRoutingConfig:q2,generateBenchmarkBlock:Yk,checkOrchestratorCandidate:B2,updateOrchestratorModel:U2,SENTINEL_START:_h,SENTINEL_END:Cu}});var Ao=Q((RF,ix)=>{"use strict";var{C:J}=dt(),W2=ft(),{TOOL_DEFINITIONS:Kk}=rs(),{saveRoutingConfig:H2}=fs();function Co(e){let t=Array.isArray(e?.tasks)?e.tasks.flatMap(n=>typeof n=="string"?[n]:n&&typeof n=="object"?[n.title,n.task,n.description]:[]):[];return[e?.pattern,e?.query,e?.regex,e?.file_pattern,e?.include,e?.path,e?.command,e?.name,...t].filter(n=>typeof n=="string").join(" ")}function oo(e){return typeof e=="string"?e.toLowerCase():""}function G2(e,t=[]){let n=oo(e);return t.some(o=>n.includes(oo(o)))}function Sh(e,t=[]){let n=oo(e);return t.every(o=>n.includes(oo(o)))}function Eh(e=""){return/\b(test|jest|vitest|mocha|ava|pytest|cargo\s+test|go\s+test|rspec|phpunit|mix\s+test|npm\s+(run\s+)?test|pnpm\s+(run\s+)?test|yarn\s+test)\b/i.test(e)}function Y2(e=""){return/\b(lint|eslint|prettier|ruff|flake8|rubocop|golangci-lint|tsc(?:\s|$)|npm\s+run\s+lint|pnpm\s+run\s+lint|yarn\s+lint)\b/i.test(e)}function z2(e=""){return/\b(build|compile|tsc(?:\s|$)|webpack|vite\s+build|next\s+build|npm\s+run\s+build|pnpm\s+run\s+build|yarn\s+build|cargo\s+build|go\s+build)\b/i.test(e)}function Xk(e=""){return/\b(rg|grep|find|fd|ls|dir|sed|awk)\b/i.test(e)}function Va(e,t=[]){return e?.action!=="create"||!Array.isArray(e.tasks)||e.tasks.length===0?!1:Sh(Co(e),t)}function Vk(e,{pathIncludes:t=[],table:n="users",action:o="select",conditionTerms:s=[]}={}){if(!Xa(e)||!Sh(e.path,t))return!1;let r=oo(e.content);return!r.includes(o)||!r.includes(n)?!1:s.every(i=>G2(r,i))}function K2(e,t=[]){let n=Co(e);return Sh(n,t)}function kh(e,{pathIncludes:t=[],oldTexts:n=[],newTexts:o=[]}={}){if(typeof e?.path!="string"||!(t.length===0||t.some(f=>e.path.toLowerCase().includes(f.toLowerCase()))))return!1;let r=Array.isArray(e.patches)?e.patches.flatMap(f=>[f.old_text,f.new_text]).filter(f=>typeof f=="string"):[],i=typeof e.old_text=="string"?e.old_text:"",a=typeof e.new_text=="string"?e.new_text:"",c=[i,a,...r],u=n.length===0||n.some(f=>c.some(p=>p.includes(f))),d=o.length===0||o.some(f=>c.some(p=>p.includes(f)));return!u||!d?!1:i&&a?!0:Array.isArray(e.patches)&&e.patches.length>0}function Xa(e,{pathIncludes:t=[],contentIncludes:n=[]}={}){return typeof e?.path!="string"||typeof e?.content!="string"||!(t.length===0||t.some(s=>oo(e.path).includes(oo(s))))?!1:n.length===0||n.every(s=>oo(e.content).includes(oo(s)))}var Th=[{id:"read-package",category:"file-ops",prompt:"Read the file package.json and show me its contents.",expectedTool:"read_file",validateArgs:e=>typeof e.path=="string"&&e.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:e=>Xa(e,{pathIncludes:["nex-bench-test.txt"],contentIncludes:["benchmark run"]})},{id:"edit-file",category:"file-ops",prompt:'You already read src/config.js and confirmed it contains the exact text "debug: false". Replace that exact text with "debug: true".',expectedTool:["edit_file","patch_file"],validateArgs:e=>kh(e,{pathIncludes:["config"],oldTexts:["debug: false"],newTexts:["debug: true"]})},{id:"list-directory",category:"file-ops",prompt:"Show me all files and folders in the cli/ directory.",expectedTool:["list_directory","glob"],validateArgs:e=>!!(typeof e.path=="string"&&e.path.includes("cli")||typeof e.pattern=="string"&&e.pattern.includes("cli"))},{id:"glob-js-files",category:"file-ops",prompt:"Find all JavaScript files (*.js) recursively in the cli/ directory.",expectedTool:"glob",validateArgs:e=>typeof e.pattern=="string"&&e.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:e=>typeof e.path=="string"&&e.path.includes("index")&&typeof e.line_start=="number"&&typeof e.line_end=="number"},{id:"glob-ts-defs",category:"file-ops",prompt:"Find all TypeScript type definition files (*.d.ts) anywhere in the project.",expectedTool:"glob",validateArgs:e=>typeof e.pattern=="string"&&e.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:e=>Xa(e,{pathIncludes:[".gitignore"],contentIncludes:["node_modules","dist"]})},{id:"edit-version-bump",category:"file-ops",prompt:'You already read package.json and confirmed it contains the exact snippet `"version": "1.0.0"`. Do not inspect the repo again. Update it directly to `"version": "1.1.0"`.',expectedTool:["edit_file","patch_file"],validateArgs:e=>kh(e,{pathIncludes:["package.json"],oldTexts:["1.0.0",'"version": "1.0.0"','"version":"1.0.0"'],newTexts:["1.1.0",'"version": "1.1.0"','"version":"1.1.0"']})},{id:"grep-with-filter",category:"search",prompt:"Search for all calls to require() but only inside .js files in the cli/ directory.",expectedTool:["grep","search_files"],validateArgs:e=>(e.pattern||e.query||e.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:e=>typeof e.command=="string"&&e.command.includes("node")&&(e.command.includes("--version")||e.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:e=>(e.pattern||e.query||e.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:e=>(e.pattern||e.query||e.regex||"").includes("callStream")},{id:"search-todos",category:"search",prompt:"Find all TODO comments in the source code.",expectedTool:["grep","search_files","bash"],validateArgs:e=>JSON.stringify(e).toUpperCase().includes("TODO")},{id:"git-branch",category:"shell",prompt:"What git branch am I currently on?",expectedTool:["bash","git_status"],validateArgs:e=>(typeof e.command=="string"&&e.command.includes("git"),!0)},{id:"git-status",category:"shell",prompt:"Show me the current git status of the repository.",expectedTool:["bash","git_status"],validateArgs:e=>(typeof e.command=="string"&&e.command.includes("git status"),!0)},{id:"npm-install",category:"shell",prompt:"Run npm install to install project dependencies.",expectedTool:"bash",validateArgs:e=>typeof e.command=="string"&&e.command.includes("npm")},{id:"schema-strict",category:"schema",prompt:"Read the file README.md",expectedTool:"read_file",validateArgs:(e,t)=>{let n=t?.function?.parameters||{},o=n.required||[],s=Object.keys(n.properties||{});return o.every(r=>e[r]!==void 0)&&Object.keys(e).every(r=>s.includes(r))}},{id:"multi-step-version",category:"multi-step",prompt:"You need to determine the current project version. What tool do you call first to inspect the most likely source file?",expectedTool:["read_file","glob","list_directory","search_files"],validateArgs:e=>!!(typeof e.path=="string"&&/package\.json|package|version/i.test(e.path)||typeof e.pattern=="string"&&/package\.json|package|version/i.test(e.pattern)||/package\.json|package|version/i.test(Co(e)))},{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:e=>!!(typeof e.command=="string"&&e.command.includes("cli")||typeof e.pattern=="string"&&e.pattern.includes("cli")||typeof e.path=="string"&&e.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:e=>(e.pattern||e.query||e.regex||"").includes("useState")},{id:"frontend-create-component",category:"frontend",prompt:"There is no existing Button component and no need to inspect other files first. What tool call do you use first to create src/components/Button.jsx with a React functional Button component that accepts a label prop and renders a styled button element?",expectedTool:"write_file",validateArgs:e=>Xa(e,{pathIncludes:["button.","src/components"],contentIncludes:["Button","label","button"]})},{id:"frontend-edit-css",category:"frontend",prompt:"You already read src/styles.css and confirmed it contains the exact text `background-color: blue`. Change that exact value to `background-color: red`.",expectedTool:["edit_file","patch_file"],validateArgs:e=>kh(e,{pathIncludes:[".css","styles"],oldTexts:["background-color: blue"],newTexts:["background-color: red"]})},{id:"frontend-glob-components",category:"frontend",prompt:"Find all JSX and TSX component files in the components/ directory.",expectedTool:"glob",validateArgs:e=>typeof e.pattern=="string"&&(e.pattern.includes(".jsx")||e.pattern.includes(".tsx")||e.pattern.includes("{jsx,tsx}"))},{id:"frontend-list-assets",category:"frontend",prompt:"List all files in the src/assets/ directory.",expectedTool:["list_directory","glob"],validateArgs:e=>!!(typeof e.path=="string"&&e.path.includes("assets")||typeof e.pattern=="string"&&e.pattern.includes("assets"))},{id:"sysadmin-port-check",category:"sysadmin",prompt:"Which process is currently listening on port 3000?",expectedTool:["bash","sysadmin"],validateArgs:e=>typeof e.command=="string"?e.command.includes("lsof")||e.command.includes("ss")||e.command.includes("netstat")||e.command.includes("3000"):e.action==="network_status"},{id:"sysadmin-nginx-config",category:"sysadmin",prompt:"Create an nginx server block that proxies requests to localhost:3000. Save it to /etc/nginx/sites-available/myapp.",expectedTool:["write_file","bash"],validateArgs:e=>!!(e.path&&(e.path.includes("nginx")||e.path.includes("sites-available"))||e.command&&e.command.includes("nginx"))},{id:"sysadmin-service-status",category:"sysadmin",prompt:"Check the status of the nginx service and show if it is running.",expectedTool:["bash","service_manage","sysadmin"],validateArgs:e=>typeof e.command=="string"?e.command.includes("systemctl")||e.command.includes("service")||e.command.includes("nginx"):e.action==="status"&&typeof e.service=="string"?e.service.includes("nginx"):e.action==="service"&&e.service_action==="status"&&typeof e.service_name=="string"&&e.service_name.includes("nginx")},{id:"sysadmin-error-log",category:"sysadmin",prompt:"Show the last 100 lines of the nginx error log.",expectedTool:["bash","service_logs","sysadmin"],validateArgs:e=>typeof e.command=="string"?e.command.includes("tail")||e.command.includes("journalctl")||e.command.includes("nginx"):typeof e.service=="string"?e.service.includes("nginx"):e.action==="journalctl"&&typeof e.unit=="string"&&e.unit.includes("nginx")||e.action==="log_tail"&&typeof e.path=="string"&&/nginx|error/i.test(e.path)},{id:"sysadmin-docker-compose",category:"sysadmin",prompt:"Create a docker-compose.yml file for a Node.js application with a PostgreSQL database.",expectedTool:"write_file",validateArgs:e=>typeof e.path=="string"&&e.path.includes("docker-compose")&&typeof e.content=="string"},{id:"data-sql-query",category:"data",prompt:"Do not inspect the repo first. Write a SQL query to find all users who have not logged in for more than 30 days and save it to queries/inactive-users.sql.",expectedTool:"write_file",validateArgs:e=>Vk(e,{pathIncludes:["queries","inactive-users.sql"],conditionTerms:[["last_login","last seen","last_seen","last_sign_in","last_signin","logged_in_at","login_at","last_active_at","lastactivity"],["30 day","30-day","interval '30 day'","interval '30 days'","date_sub","datetime('now', '-30 days')","current_date - 30","now() - interval","dateadd(day, -30","add_months","interval '1 month'"]]})},{id:"data-find-json-key",category:"data",prompt:'Find all JSON files in the project that contain the key "userId".',expectedTool:["grep","search_files"],validateArgs:e=>(e.pattern||e.query||e.regex||"").includes("userId")},{id:"data-python-csv",category:"data",prompt:'There is no need to inspect the repo first. What tool call do you use first to create scripts/average_price.py with a Python script that reads data.csv and calculates the average of the "price" column?',expectedTool:"write_file",validateArgs:e=>Xa(e,{pathIncludes:["average_price.py","scripts"],contentIncludes:["data.csv","price"]})},{id:"data-find-migrations",category:"data",prompt:"Find all database migration files in this project.",expectedTool:["glob","search_files","grep"],validateArgs:e=>JSON.stringify(e).toLowerCase().includes("migrat")},{id:"data-find-schema",category:"data",prompt:"Find where the database schema or models are defined in this project.",expectedTool:["grep","glob","search_files","list_directory","bash"],validateArgs:e=>/schema|model|migration|prisma|dbml|typeorm|sequelize|orm|db|database|entity/i.test(Co(e))},{id:"data-write-query",category:"data",prompt:"Do not inspect the repo first. Write a SQL query to find all users who registered in the last 30 days and save it to queries/recent-users.sql.",expectedTool:"write_file",validateArgs:e=>Vk(e,{pathIncludes:["queries","recent-users.sql"],conditionTerms:[["created_at","registered_at","registered_on","signup_date","signed_up_at","joined_at","createdon","created_on"],["30 day","30-day","interval '30 day'","interval '30 days'","date_sub","datetime('now', '-30 days')","current_date - 30","now() - interval","dateadd(day, -30","add_months","interval '1 month'"]]})},{id:"data-read-env",category:"data",prompt:"Read the .env file to find the database connection string.",expectedTool:"read_file",validateArgs:e=>typeof e.path=="string"&&/\.env|env\./i.test(e.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:e=>typeof e.path=="string"&&e.path.includes("server")},{id:"resilience-file-not-found",category:"resilience",prompt:"read_file returned 'file not found' for src/utils/helpers.js. You need to find where the helper functions are now. Use a discovery or search tool as your next step, not read_file again. What tool do you use first?",expectedTool:["glob","bash","search_files","list_directory"],validateArgs:e=>{let t=Co(e);return/src|helper|util|helpers|\.js|find/i.test(t)}},{id:"resilience-large-file-nav",category:"resilience",prompt:"The file src/api.js is 2800 lines. You need to locate the authenticateUser function. Use a search-oriented tool first instead of reading the whole file. What is the most efficient tool call?",expectedTool:["bash","grep","search_files","glob"],validateArgs:e=>typeof e.command=="string"&&Xk(e.command)&&/authenticateuser|src\/api\.js/i.test(e.command)?!0:K2(e,["authenticateuser"])},{id:"resilience-broken-import",category:"resilience",prompt:"TypeScript reports: Cannot find module './config'. The file was recently renamed. Use a search or discovery tool first to find the new location. What tool do you use?",expectedTool:["glob","bash","search_files","grep","list_directory"],validateArgs:e=>{let t=Co(e);return/config|rename|module|import|\.ts|\.js|find|src|path/i.test(t)}},{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:e=>typeof e.path=="string"&&e.path.includes("parser")},{id:"resilience-grep-no-match",category:"resilience",prompt:"grep returned zero matches for 'getUserById' in src/. The function exists but may have been renamed. Use a search tool to list exported function names in src/ and identify the current name. What tool call do you use first?",expectedTool:["bash","grep","search_files"],validateArgs:e=>typeof e.command=="string"?Xk(e.command)&&/src|export|function|module\.exports|exports\./i.test(e.command):/getUserById|export|function|module\.exports|exports\.|src|public|def /i.test(Co(e))},{id:"ssh-exec-log",category:"ssh",prompt:'Show the last 50 lines of /var/log/nginx/error.log on server "prod-1".',expectedTool:["ssh_exec","service_logs","sysadmin"],validateArgs:e=>typeof e.command=="string"?(e.command.includes("tail")||e.command.includes("log"))&&typeof e.server=="string":typeof e.service=="string"?e.service.includes("nginx"):typeof e.server=="string"&&(e.action==="journalctl"&&typeof e.unit=="string"&&e.unit.includes("nginx")||e.action==="log_tail"&&typeof e.path=="string"&&/nginx|error/i.test(e.path))},{id:"ssh-exec-service",category:"ssh",prompt:'Restart the nginx service on server "prod-1".',expectedTool:["ssh_exec","service_manage","sysadmin"],validateArgs:e=>typeof e.command=="string"?(e.command.includes("nginx")||e.command.includes("systemctl")||e.command.includes("restart"))&&typeof e.server=="string":e.action==="restart"&&typeof e.service=="string"&&e.service.includes("nginx")?!0:e.action==="service"&&e.service_action==="restart"&&typeof e.service_name=="string"&&e.service_name.includes("nginx")&&typeof e.server=="string"},{id:"ssh-exec-port",category:"ssh",prompt:'Check if port 8080 is listening on server "prod-1".',expectedTool:["ssh_exec","sysadmin"],validateArgs:e=>typeof e.command=="string"?(e.command.includes("8080")||e.command.includes("ss")||e.command.includes("netstat")||e.command.includes("lsof"))&&typeof e.server=="string":e.action==="network_status"&&typeof e.server=="string"},{id:"ssh-exec-processes",category:"ssh",prompt:'Show the top CPU-consuming processes on server "prod-1".',expectedTool:["ssh_exec","sysadmin"],validateArgs:e=>typeof e.command=="string"?(e.command.includes("top")||e.command.includes("ps")||e.command.includes("htop"))&&typeof e.server=="string":e.action==="process_list"&&typeof e.server=="string"},{id:"git-diff-staged",category:"git",prompt:"Show all staged changes before committing.",expectedTool:["git_diff","bash"],validateArgs:e=>!!(e.staged===!0||e.staged==="true"||typeof e.command=="string"&&e.command.includes("diff"))},{id:"git-log-recent",category:"git",prompt:"Show the last 5 commit messages with their hashes.",expectedTool:["git_log","bash"],validateArgs:e=>!!(typeof e.count=="number"||typeof e.limit=="number"||typeof e.n=="number"||typeof e.command=="string"&&e.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:e=>(Object.keys(e||{}).length===0||typeof e.command=="string"&&e.command.includes("status"),!0)},{id:"agentic-test-first",category:"agentic",prompt:"You need to run the full test suite first. Do not inspect files before that. If any tests fail after the run, identify the failing test file and read it to understand the issue. What is the first tool call?",expectedTool:["bash","task_list"],validateArgs:e=>typeof e.command=="string"?Eh(e.command):Va(e,["test"])},{id:"agentic-read-then-act",category:"agentic",prompt:"Read the project README.md, find the TODO section, and list which items are completed.",expectedTool:"read_file",validateArgs:e=>typeof e.path=="string"&&e.path.includes("README")},{id:"agentic-build-deploy",category:"agentic",prompt:"Build the project with npm run build, then verify the output exists in the dist/ directory.",expectedTool:["bash","task_list"],validateArgs:e=>{if(typeof e.command=="string")return e.command.includes("build")||e.command.includes("npm");let t=Co(e);return e.action==="create"&&/build|dist/i.test(t)}},{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:e=>Array.isArray(e.agents)&&e.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:e=>Array.isArray(e.agents)&&e.agents.length>=2}],Jk=[{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:e=>typeof e.path=="string"&&/users/i.test(e.path)},{id:"phase-plan-search",category:"phase-plan",prompt:"We're getting CORS errors in production. Search the codebase for where CORS middleware is configured.",expectedTool:["grep","search_files"],validateArgs:e=>{let t=e.pattern||e.query||e.regex||"";return/cors/i.test(t)}},{id:"phase-plan-context",category:"phase-plan",prompt:"The login page shows a blank screen after the last deploy. Check git log for recent changes that might have broken it.",expectedTool:["git_log","bash"],validateArgs:e=>(typeof e.command=="string"&&e.command.includes("log"),!0)},{id:"phase-verify-test",category:"phase-verify",prompt:"You are explicitly in the verify phase. Do not inspect files first. The first verification step is to run tests for a fix in src/utils.js. What tool call do you use first?",expectedTool:["bash","task_list"],validateArgs:e=>typeof e.command=="string"?Eh(e.command):Va(e,["test"])},{id:"phase-verify-read",category:"phase-verify",prompt:"A patch was applied to config/database.js to fix the connection pool. Read the file to verify the changes look correct.",expectedTool:"read_file",validateArgs:e=>typeof e.path=="string"&&/database/i.test(e.path)},{id:"phase-verify-lint",category:"phase-verify",prompt:"You are explicitly in the verify phase. Do not inspect files first. The first verification step is to run linting after changes in src/components/Header.tsx. What tool call do you use first?",expectedTool:["bash","task_list"],validateArgs:e=>typeof e.command=="string"?Y2(e.command):Va(e,["lint"])},{id:"phase-plan-git-blame",category:"phase-plan",prompt:"A production bug was introduced 2 days ago. Use git log to find commits from the last 2 days to identify what changed.",expectedTool:["git_log","bash"],validateArgs:e=>(typeof e.command=="string"&&e.command.includes("log"),!0)},{id:"phase-plan-error-trace",category:"phase-plan",prompt:"The error stack trace mentions src/middleware/auth.js line 87. Read the file around that line to understand the bug.",expectedTool:"read_file",validateArgs:e=>typeof e.path=="string"&&/auth/i.test(e.path)},{id:"phase-plan-grep-config",category:"phase-plan",prompt:"Users report the app is using wrong API keys in staging. Search for where API_KEY is loaded from environment.",expectedTool:["grep","search_files"],validateArgs:e=>{let t=e.pattern||e.query||e.regex||"";return/api.?key|env/i.test(t)}},{id:"phase-verify-build",category:"phase-verify",prompt:"You are in the verify phase. Do not inspect files first. The TypeScript source was modified, so run the build command to verify there are no compilation errors.",expectedTool:["bash","task_list"],validateArgs:e=>typeof e.command=="string"?z2(e.command):Va(e,["build"])},{id:"phase-verify-git-diff",category:"phase-verify",prompt:"Changes were just committed. Show the git diff of the last commit to verify only the intended files were modified.",expectedTool:["git_diff","bash"],validateArgs:e=>(e.command&&/git.*diff|diff.*HEAD/.test(e.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:e=>typeof e.path=="string"&&/config|production|deploy/i.test(e.path)}],Zk=[{id:"phase-implement-edit",category:"phase-implement",prompt:"You need to change the default port from 3000 to 8080 in config/server.js. Read the file first, then make the edit.",expectedTool:"read_file",validateArgs:e=>typeof e.path=="string"&&/server/i.test(e.path)},{id:"phase-implement-write",category:"phase-implement",prompt:"Create a new file src/utils/retry.js that exports an async retry helper function. Use write_file to create it.",expectedTool:"write_file",validateArgs:e=>typeof e.path=="string"&&/retry/i.test(e.path)},{id:"phase-implement-grep-edit",category:"phase-implement",prompt:'Find all places where "old_api_endpoint" is used in src/ and update them to "new_api_endpoint". Start by searching for the string.',expectedTool:["grep","search_files"],validateArgs:e=>{let t=(e.pattern||e.query||e.regex||"").toLowerCase();return t.includes("old_api_endpoint")||t.includes("old.api")}},{id:"phase-implement-patch",category:"phase-implement",prompt:"You need to add error handling to src/services/api.js. Read the file first, then use patch_file to add try/catch blocks.",expectedTool:"read_file",validateArgs:e=>typeof e.path=="string"&&/api/i.test(e.path)},{id:"phase-implement-test-after-edit",category:"phase-implement",prompt:"You just edited src/controllers/user.js to fix a validation bug. After making the edit, what should you do next to verify?",expectedTool:["bash","task_list"],validateArgs:e=>typeof e.command=="string"?Eh(e.command):Va(e,["test"])}],Ja=[...Th,...Jk,...Zk],xh=["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 X2(){try{let n=require("path").join(require("os").homedir(),".nex-code","benchmark-results.json");if(!require("fs").existsSync(n))return xh;let o=JSON.parse(require("fs").readFileSync(n,"utf-8"));return!Array.isArray(o)||o.length===0?xh:o.filter(s=>typeof s.score=="number"&&s.score>=60).sort((s,r)=>r.score-s.score).slice(0,12).map(s=>s.model)}catch{return xh}}var Rh=X2(),V2=["minimax-m2.7:cloud","qwen3-coder:480b","devstral-2:123b"],Ch=(()=>{let e=Rh.slice(0,3);return e.length>=3?e:V2})(),J2=14,Ou={producedToolCall:.2,correctTool:.35,validArgs:.3,schemaCompliant:.15},Z2="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 vh(e,t){let n={taskId:e.id,category:e.category,model:t,producedToolCall:!1,correctTool:!1,validArgs:!1,schemaCompliant:!1,toolCalled:null,error:null,latencyMs:0},o=[{role:"system",content:Z2},{role:"user",content:e.prompt}],s=Date.now();try{let r=await W2.callChat(o,Kk,{provider:"ollama",model:t,temperature:0,timeout:9e4});n.latencyMs=Date.now()-s;let i=r.tool_calls||[];if(e.expectedTool===null){let a=i.length===0;n.producedToolCall=a,n.correctTool=a,n.validArgs=!0,n.schemaCompliant=!0}else if(i.length>0){n.producedToolCall=!0;let a=Array.isArray(e.expectedTool)?e.expectedTool:[e.expectedTool],c=-1,u=i[0].function?.name||"unknown",d=!1,f=!1,p=!1;for(let h of i){let m=h.function?.name||"unknown",g=h.function?.arguments||{},y=a.includes(m),b=!1,x=!1,_=0;if(y){let E=Kk.find(S=>S.function?.name===m);if(b=!!e.validateArgs(g,E),E){let S=E.function?.parameters||{},O=S.required||[],L=Object.keys(S.properties||{});x=O.every(I=>g[I]!==void 0)&&Object.keys(g).every(I=>L.includes(I))}_=(y?2:0)+(b?1:0)+(x?.5:0)}_>c&&(c=_,u=m,d=y,f=b,p=x)}n.toolCalled=d?u:i[0].function?.name||"unknown",n.correctTool=d,n.validArgs=f,n.schemaCompliant=p}}catch(r){n.latencyMs=Date.now()-s,n.error=r.message.slice(0,120)}return n}function wr(e){return e.error?0:((e.producedToolCall?Ou.producedToolCall:0)+(e.correctTool?Ou.correctTool:0)+(e.validArgs?Ou.validArgs:0)+(e.schemaCompliant?Ou.schemaCompliant:0))*100}var Qk={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 Ah(e){return Object.entries(e).map(([t,n])=>{let o=n.map(wr),s=o.reduce((a,c)=>a+c,0)/o.length,r=a=>Math.round(n.filter(a).length/n.length*100),i={};for(let a of["coding","frontend","sysadmin","data","agentic","bug-fix","feature-add","refactor","plan","implement","verify"]){let c=n.filter(d=>Qk[d.category]===a);if(c.length===0)continue;let u=c.map(wr).reduce((d,f)=>d+f,0)/c.length;i[a]=Math.round(u*10)/10}return{model:t,score:Math.round(s*10)/10,toolCallRate:r(a=>!a.error&&(a.producedToolCall||a.category==="reasoning")),correctRate:r(a=>a.correctTool),validArgsRate:r(a=>a.validArgs),schemaRate:r(a=>a.schemaCompliant),avgLatency:Math.round(n.reduce((a,c)=>a+c.latencyMs,0)/n.length),errorCount:n.filter(a=>a.error).length,categoryScores:i,results:n}}).sort((t,n)=>n.score-t.score)}function ex(e){return tx(e)}function tx(e){let t={};for(let r of["coding","frontend","sysadmin","data","agentic","plan","verify"]){let i=e.filter(p=>p.categoryScores[r]!==void 0&&p.score>=65).sort((p,h)=>h.categoryScores[r]-p.categoryScores[r]);if(i.length===0||(i[0]?.results||[]).filter(p=>Qk[p.category]===r).length<4)continue;let u=i[0],f=i.filter(p=>u.categoryScores[r]-p.categoryScores[r]<=5).sort((p,h)=>p.avgLatency-h.avgLatency)[0];t[r]={model:f.model,score:f.categoryScores[r],avgLatency:f.avgLatency}}return t}function nx(e,t){let n=`nex-code Model Benchmark (${t} tasks \xB7 ollama cloud)`,o=[{label:"#",width:3},{label:"Model",width:26},{label:"Score",width:7},{label:"Tool\u2713",width:7},{label:"Name\u2713",width:7},{label:"Args\u2713",width:7},{label:"Schema\u2713",width:8},{label:"Latency",width:8},{label:"Err",width:4}],s=o.reduce((d,f)=>d+f.width+1,0)+1,r="\u2500".repeat(s);console.log(`
1941
+ ${J.bold}${n}${J.reset}`),console.log(r);let i=o.map(d=>d.label.padEnd(d.width)).join(" ");if(console.log(`${J.dim}${i}${J.reset}`),console.log(r),e.forEach((d,f)=>{let p=String(f+1).padEnd(o[0].width),h=d.model.slice(0,o[1].width).padEnd(o[1].width),m=String(d.score).padEnd(o[2].width),g=`${d.toolCallRate}%`.padEnd(o[3].width),y=`${d.correctRate}%`.padEnd(o[4].width),b=`${d.validArgsRate}%`.padEnd(o[5].width),x=`${d.schemaRate}%`.padEnd(o[6].width),_=`${(d.avgLatency/1e3).toFixed(1)}s`.padEnd(o[7].width),E=d.errorCount>0?`${J.red}${d.errorCount}${J.reset}`:`${J.dim}0${J.reset}`,S=d.score>=80?J.green:d.score>=60?J.yellow:J.red,O=f===0?`${J.yellow}${p}${J.reset}`:`${J.dim}${p}${J.reset}`;console.log(`${O} ${S}${h}${J.reset} ${J.bold}${S}${m}${J.reset} ${g} ${y} ${b} ${x} ${J.dim}${_}${J.reset} ${E}`)}),console.log(r),e.length>0){let d=e[0];if(console.log(`
1942
1942
  ${J.bold}${J.green}Winner: ${d.model}${J.reset} score ${d.score}/100`),e.length>1){let f=(d.score-e[1].score).toFixed(1);console.log(`${J.dim}+${f} pts over ${e[1].model}${J.reset}`)}}let a=e.filter(d=>d.results.some(f=>!f.error&&(!f.correctTool||!f.validArgs)));if(a.length>0){console.log(`${J.bold}Failing tasks:${J.reset}`);for(let d of a){let f=d.results.filter(m=>!m.error&&(!m.correctTool||!m.validArgs));if(f.length===0)continue;let p=d.model.slice(0,22),h=f.map(m=>{if(!m.correctTool){let g=m.toolCalled||"(none)";return`${J.dim}${m.taskId}${J.reset} ${J.red}\u2192${g}${J.reset}`}return`${J.dim}${m.taskId}${J.reset} ${J.yellow}bad-args${J.reset}`});console.log(` ${J.dim}${p.padEnd(22)}${J.reset} ${h.join(" ")}`)}console.log()}if(e.length>=3){let d={},f={};for(let m of e)for(let g of m.results)g.error||(f[g.taskId]=(f[g.taskId]||0)+1,(!g.correctTool||!g.validArgs)&&(d[g.taskId]=(d[g.taskId]||0)+1));let p=Math.ceil(e.length*.5),h=Object.entries(d).filter(([m,g])=>g>=p&&f[m]>=3).sort((m,g)=>g[1]-m[1]);if(h.length>0){console.log(`
1943
- ${J.bold}Systemic failures${J.reset} ${J.dim}(>50% of models fail \u2014 may indicate benchmark design issues)${J.reset}`);for(let[m,g]of h){let $=f[m],b=Math.round(g/$*100),x=b>=80?J.red:J.yellow;console.log(` ${x}${b}%${J.reset} ${J.dim}fail${J.reset} ${m}`)}console.log()}}let c=["coding","frontend","sysadmin","data","agentic","plan","verify"];if(e.some(d=>Object.keys(d.categoryScores).length>1)){console.log(`
1944
- ${J.bold}Best model per task type:${J.reset}`);let d=tx(e);for(let f of c){let p=d[f];if(!p)continue;let h=p.score,m=h>=80?J.green:h>=60?J.yellow:J.red,g=e.filter(b=>b.categoryScores[f]!==void 0).sort((b,x)=>x.categoryScores[f]-b.categoryScores[f])[0],$=g&&g.model!==p.model?`${J.dim} raw leader: ${g.model} (${g.categoryScores[f]}/100)${J.reset}`:"";console.log(` ${J.dim}${f.padEnd(10)}${J.reset} ${m}${p.model}${J.reset} ${J.dim}${h}/100${J.reset}${$}`)}console.log(`${J.dim} Winners use the same conservative routing criteria as auto-update (overall-score floor plus latency tiebreak band).${J.reset}`)}console.log()}function sx(e){if(!(!e||e.length<2))try{let t=ex(e),{loadRoutingConfig:n}=fs(),o=n(),s={...o},r=[],i=new Set(["plan","verify"]);for(let[a,{model:c,score:u}]of Object.entries(t)){let d=i.has(a),f=d?o.phases&&o.phases[a]:o[a];f&&f!==c&&!e.find(h=>h.model===f)||(d?(s.phases||(s.phases={}),s.phases[a]!==c&&(s.phases[a]=c,r.push(`phase:${a}\u2192${c}`))):s[a]!==c&&(s[a]=c,r.push(`${a}\u2192${c}`)))}r.length>0&&(H2(s),console.log(`
1943
+ ${J.bold}Systemic failures${J.reset} ${J.dim}(>50% of models fail \u2014 may indicate benchmark design issues)${J.reset}`);for(let[m,g]of h){let y=f[m],b=Math.round(g/y*100),x=b>=80?J.red:J.yellow;console.log(` ${x}${b}%${J.reset} ${J.dim}fail${J.reset} ${m}`)}console.log()}}let c=["coding","frontend","sysadmin","data","agentic","plan","verify"];if(e.some(d=>Object.keys(d.categoryScores).length>1)){console.log(`
1944
+ ${J.bold}Best model per task type:${J.reset}`);let d=tx(e);for(let f of c){let p=d[f];if(!p)continue;let h=p.score,m=h>=80?J.green:h>=60?J.yellow:J.red,g=e.filter(b=>b.categoryScores[f]!==void 0).sort((b,x)=>x.categoryScores[f]-b.categoryScores[f])[0],y=g&&g.model!==p.model?`${J.dim} raw leader: ${g.model} (${g.categoryScores[f]}/100)${J.reset}`:"";console.log(` ${J.dim}${f.padEnd(10)}${J.reset} ${m}${p.model}${J.reset} ${J.dim}${h}/100${J.reset}${y}`)}console.log(`${J.dim} Winners use the same conservative routing criteria as auto-update (overall-score floor plus latency tiebreak band).${J.reset}`)}console.log()}function sx(e){if(!(!e||e.length<2))try{let t=ex(e),{loadRoutingConfig:n}=fs(),o=n(),s={...o},r=[],i=new Set(["plan","verify"]);for(let[a,{model:c,score:u}]of Object.entries(t)){let d=i.has(a),f=d?o.phases&&o.phases[a]:o[a];f&&f!==c&&!e.find(h=>h.model===f)||(d?(s.phases||(s.phases={}),s.phases[a]!==c&&(s.phases[a]=c,r.push(`phase:${a}\u2192${c}`))):s[a]!==c&&(s[a]=c,r.push(`${a}\u2192${c}`)))}r.length>0&&(H2(s),console.log(`
1945
1945
  ${J.dim} Routing updated: ${r.join(", ")}${J.reset}`),console.log(`
1946
1946
  ${J.green}\u{1F4A1} The best models have been saved to ~/.nex-code/.env and will be automatically used by nex-code from now on.${J.reset}`))}catch{}}async function Q2({models:e,quick:t=!1,onProgress:n,parallelModels:o=1}={}){let s=t?Th.slice(0,J2):Ja,r=e?.length>0?e:t?Ch:Rh,i={};for(let c of r)i[c]=[];if(o<=1)for(let c of r)for(let u of s){n?.({model:c,task:u.id,done:!1});let d=await vh(u,c);i[c].push(d),n?.({model:c,task:u.id,done:!0,score:wr(d),error:d.error})}else{let c=Math.min(o,r.length),u=[...r],d=Array.from({length:c},async()=>{for(;u.length>0;){let f=u.shift();if(!f)break;for(let p of s){n?.({model:f,task:p.id,done:!1});let h=await vh(p,f);i[f].push(h),n?.({model:f,task:p.id,done:!0,score:wr(h),error:h.error})}}});await Promise.all(d)}let a=Ah(i);return nx(a,s.length),sx(a),a}async function ej({newModels:e,existingRanking:t=[],onProgress:n}={}){if(!e||e.length===0)return t;let o={};for(let i of e){o[i]=[];for(let a of Ja){n?.({model:i,task:a.id,done:!1});let c=await vh(a,i);o[i].push(c),n?.({model:i,task:a.id,done:!0,score:wr(c),error:c.error})}}let r=[...Ah(o)];for(let i of t)r.find(a=>a.model===i.model)||r.push(i);return r.sort((i,a)=>a.score-i.score),nx(r,Ja.length),sx(r),r}var Mu=[{id:"simple_question",name:"Simple Convergence",prompt:"What is 2+2?",maxTurns:3,successCriteria:["4"]}];function ox(e){let t=require("fs"),o=require("path").join(e||process.cwd(),".nex","benchmark-config.json");if(!t.existsSync(o))return console.log(`${J.yellow}No scenarios configured.${J.reset} Create ${J.dim}.nex/benchmark-config.json${J.reset} to define your benchmark scenarios.
1947
1947
  Example:
@@ -1958,7 +1958,7 @@ ${J.green}\u{1F4A1} The best models have been saved to ~/.nex-code/.env and will
1958
1958
  }
1959
1959
  `),Mu;try{let s=JSON.parse(t.readFileSync(o,"utf-8"));return!Array.isArray(s.scenarios)||s.scenarios.length===0?(console.log(`${J.yellow}benchmark-config.json has no scenarios \u2014 using defaults.${J.reset}
1960
1960
  `),Mu):s.scenarios}catch(s){return console.log(`${J.yellow}Failed to parse benchmark-config.json: ${s.message}${J.reset}
1961
- `),Mu}}function rx(e,t){let{scoreMessages:n,_extractToolCalls:o,_getLastAssistantText:s}=ql(),r=n(e),i=r.score,a=[],c=s(e).toLowerCase();t.successCriteria.every(p=>c.includes(p.toLowerCase()))&&(i=Math.min(10,i+1),a.push("+1.0 all success criteria met"));let d=o(e);d.length<t.maxTurns/2&&(i=Math.min(10,i+.5),a.push(`+0.5 efficient (${d.length} tool calls < ${t.maxTurns/2})`)),i=Math.round(i*10)/10;let f=i>=9?"A":i>=8?"B":i>=7?"C":i>=6?"D":"F";return{score:i,grade:f,issues:r.issues,summary:r.summary,bonuses:a}}async function tj(e,t={}){let{spawn:n}=require("child_process"),o=require("fs"),s=require("path"),r=require("os"),i=s.join(r.tmpdir(),`nex-bench-${e.id}-${Date.now()}.txt`);o.writeFileSync(i,e.prompt,"utf-8");let a=s.resolve(__dirname,"..","bin","nex-code.js"),c=t.cwd||process.cwd(),u=[a,"--prompt-file",i,"--delete-prompt-file","--auto","--max-turns",String(e.maxTurns)];return t.model&&u.push("--model",t.model),new Promise(d=>{let f=n(process.execPath,u,{cwd:c,stdio:["ignore","pipe","pipe"],env:{...process.env}}),p=e.maxTurns*60*1e3,h=!1,m=setTimeout(()=>{h=!0;try{f.kill("SIGTERM")}catch{}},p);f.on("close",g=>{clearTimeout(m);try{o.unlinkSync(i)}catch{}let $=s.join(c,".nex","sessions","_autosave.json"),b=[];if(o.existsSync($))try{b=JSON.parse(o.readFileSync($,"utf-8")).messages||[]}catch{}d({messages:b,exitCode:g||0,timedOut:h})}),f.stdout.resume(),f.stderr.resume()})}function nj(e,t,n){let o=e.length>0?Math.round(e.reduce((c,u)=>c+u.score,0)/e.length*10)/10:0,s=o>=9?"A":o>=8?"B":o>=7?"C":o>=6?"D":"F",r=57,i="\u2500".repeat(r);console.log(`
1961
+ `),Mu}}function rx(e,t){let{scoreMessages:n,_extractToolCalls:o,_getLastAssistantText:s}=ql(),r=n(e),i=r.score,a=[],c=s(e).toLowerCase();t.successCriteria.every(p=>c.includes(p.toLowerCase()))&&(i=Math.min(10,i+1),a.push("+1.0 all success criteria met"));let d=o(e);d.length<t.maxTurns/2&&(i=Math.min(10,i+.5),a.push(`+0.5 efficient (${d.length} tool calls < ${t.maxTurns/2})`)),i=Math.round(i*10)/10;let f=i>=9?"A":i>=8?"B":i>=7?"C":i>=6?"D":"F";return{score:i,grade:f,issues:r.issues,summary:r.summary,bonuses:a}}async function tj(e,t={}){let{spawn:n}=require("child_process"),o=require("fs"),s=require("path"),r=require("os"),i=s.join(r.tmpdir(),`nex-bench-${e.id}-${Date.now()}.txt`);o.writeFileSync(i,e.prompt,"utf-8");let a=s.resolve(__dirname,"..","bin","nex-code.js"),c=t.cwd||process.cwd(),u=[a,"--prompt-file",i,"--delete-prompt-file","--auto","--max-turns",String(e.maxTurns)];return t.model&&u.push("--model",t.model),new Promise(d=>{let f=n(process.execPath,u,{cwd:c,stdio:["ignore","pipe","pipe"],env:{...process.env}}),p=e.maxTurns*60*1e3,h=!1,m=setTimeout(()=>{h=!0;try{f.kill("SIGTERM")}catch{}},p);f.on("close",g=>{clearTimeout(m);try{o.unlinkSync(i)}catch{}let y=s.join(c,".nex","sessions","_autosave.json"),b=[];if(o.existsSync(y))try{b=JSON.parse(o.readFileSync(y,"utf-8")).messages||[]}catch{}d({messages:b,exitCode:g||0,timedOut:h})}),f.stdout.resume(),f.stderr.resume()})}function nj(e,t,n){let o=e.length>0?Math.round(e.reduce((c,u)=>c+u.score,0)/e.length*10)/10:0,s=o>=9?"A":o>=8?"B":o>=7?"C":o>=6?"D":"F",r=57,i="\u2500".repeat(r);console.log(`
1962
1962
  \u250C\u2500 Benchmark Results ${"\u2500".repeat(r-19)}\u2510`);for(let c of e){let u=c.id.padEnd(20),d=c.name.substring(0,26).padEnd(26),f=`${c.score}/10`.padStart(6),p=c.grade.padStart(2);console.log(`\u2502 ${u} ${d} ${f} ${p} \u2502`)}console.log(`\u2502 ${" ".repeat(r-2)} \u2502`);let a=`Overall: ${o}/10 (${s}) \xB7 v${t} \xB7 ${n}`;console.log(`\u2502 ${a.substring(0,r-4).padEnd(r-4)} \u2502`),console.log(`\u2514${"\u2500".repeat(r+1)}\u2518
1963
1963
  `)}function sj(e=10){let t=require("fs"),o=require("path").join(process.cwd(),".nex","benchmark-history.json");if(!t.existsSync(o)){console.log(`${J.yellow}No score history yet. Run a session first.${J.reset}
1964
1964
  `);return}let s=[];try{s=JSON.parse(t.readFileSync(o,"utf-8"))}catch{s=[]}if(!Array.isArray(s)||s.length===0){console.log(`${J.yellow}Score history is empty.${J.reset}
@@ -1970,7 +1970,7 @@ ${J.dim}Running scenario: ${c.name}...${J.reset}`);let{messages:u,timedOut:d}=aw
1970
1970
  `).filter(Boolean).map(Lu).filter(Boolean):[]}function Za(e=process.cwd()){let t=Nu(e);return rn.existsSync(t)?rn.readdirSync(t).filter(n=>/^reallife-.*\.json$/.test(n)).map(n=>{let o=Bn.join(t,n);return{name:n,fullPath:o,mtimeMs:rn.statSync(o).mtimeMs}}).sort((n,o)=>o.mtimeMs-n.mtimeMs):[]}function cx(e=process.cwd()){let t=Za(e)[0];if(!t)return null;let n=Lu(rn.readFileSync(t.fullPath,"utf8"));return n?{...n,__file:t.fullPath}:null}function lx(e){if(!e)return!1;let t=e.metrics?.timeoutRate||0,n=e.finalScore||0,o=Array.isArray(e.results)?e.results:[];return t>0||n<90?!1:o.length===0?!0:o.every(s=>vi(s)==="healthy")}function lj(e=process.cwd()){let t=Za(e);for(let n of t){let o=Lu(rn.readFileSync(n.fullPath,"utf8"));if(!o)continue;let s={...o,__file:n.fullPath};if(!lx(s))return s}return cx(e)}function Oh(e){return`${Math.round(e||0)}%`}function Pu(e={}){let t=e.input||0,n=e.output||0;return`${t.toLocaleString()} in / ${n.toLocaleString()} out`}function vi(e){let t=e.completionReason==="timeout",n=e.toolCalls||0,o=e.tokens?.input||0,s=e.score??0,r=e.category==="docs"||e.category==="understanding";return t&&n>=20?"over-exploration":t&&r?"late finalization":t&&n===0?"tool underuse":t&&s>=60?"useful but unfinished":s<50&&o>=3e5?"high-cost weak result":n>=12&&s<70?"tool thrash":s>=80?"healthy":"quality gap"}function uj(e){switch(e){case"over-exploration":return"The agent keeps gathering evidence after enough context exists.";case"late finalization":return"The task likely has enough information, but the final deliverable starts too late.";case"tool underuse":return"The task finishes with little or no tool support, suggesting poor action selection.";case"useful but unfinished":return"The work is mostly correct, but the run exits before a clean final answer.";case"high-cost weak result":return"The task burns a large amount of tokens without converting that work into score.";case"tool thrash":return"The agent spends many tool calls for a middling result, suggesting loopiness.";case"quality gap":return"The task finishes, but output quality still needs improvement.";default:return"The task looks healthy compared with the rest of the run."}}function dj(e,t){if(!t?.runId||e.length<2)return null;let n=e.findIndex(s=>s.runId===t.runId);if(n<=0)return null;let o=e[n-1];return o?{previous:o,scoreDelta:(t.finalScore||0)-(o.finalScore||0),timeoutDelta:(t.metrics?.timeoutRate||0)-(o.metrics?.timeoutRate||0),toolDelta:(t.metrics?.avgToolCalls||0)-(o.metrics?.avgToolCalls||0)}:null}function fj(e=[],t){let n=new Map;for(let s of e){let r=vi(s);n.set(r,(n.get(r)||0)+1)}let o=[];return(n.get("over-exploration")||0)>0&&o.push("Reduce repeated read/search loops once enough evidence exists for a synthesis pass."),(n.get("late finalization")||0)>0&&o.push("Trigger earlier final deliverable generation for docs and understanding tasks."),(n.get("useful but unfinished")||0)>0&&o.push("Tighten headless completion criteria so strong partial work exits as a finished answer."),(n.get("tool thrash")||0)>0&&o.push("Cap redundant verification or repeated edits when score is not improving."),(t?.metrics?.timeoutRate||0)>=70&&o.push("Prioritize timeout reduction before raising quality bars or widening the benchmark slice."),o.slice(0,3)}function ux(e,t){let n=e?.metrics?.timeoutRate||0,o=e?.metrics?.avgToolCalls||0;return["The benchmark harness is healthy and measuring correctly.","","Current benchmark evidence:",`- Final weighted score: ${e?.finalScore||0}/100`,`- Timeout rate: ${n}%`,`- Avg tool calls: ${o}`,`- Tokens: ${Pu(e?.totalTokens)}`,"","Biggest bottleneck task:",`- ${t.id}: ${t.score}/100`,`- category: ${t.category}`,`- completionReason: ${t.completionReason||"unknown"}`,`- toolCalls: ${t.toolCalls||0}`,`- tokens: ${Pu(t.tokens)}`,`- likely issue: ${vi(t)}`,"","Your task:","Implement exactly one focused systemic fix in cli/ code that addresses this dominant bottleneck pattern.","","Constraints:","- Do not modify benchmark files or benchmark task definitions.","- Do not add task-specific hacks.","- Keep the patch focused and small.","- Preserve the working tool/token telemetry path.","","What I want:","1. Identify the main reason this pattern still happens.","2. Implement one fix only.","3. Run the most relevant focused tests.","4. Explain why this should improve completion rate broadly."].join(`
1971
1971
  `)}function dx(e=process.cwd()){return Bn.join(Nu(e),"prio")}function pj(e){return rn.mkdirSync(e,{recursive:!0}),e}function hj(e=new Date){return e.toISOString().replace(/[:.]/g,"-")}function fx(e,t=4){return(Array.isArray(e?.results)?e.results:[]).map(o=>({...o,pattern:vi(o)})).sort((o,s)=>{let r=o.completionReason==="timeout"?1:0,i=s.completionReason==="timeout"?1:0;return i!==r?i-r:(o.score||0)!==(s.score||0)?(o.score||0)-(s.score||0):(s.toolCalls||0)!==(o.toolCalls||0)?(s.toolCalls||0)-(o.toolCalls||0):(s.tokens?.input||0)-(o.tokens?.input||0)}).slice(0,t).map(o=>o.id)}function ax(e,t,n={}){return aj(e,t,{cwd:n.cwd||process.cwd(),env:n.env||process.env,encoding:"utf8",maxBuffer:n.maxBuffer||20*1024*1024})}function mj(e,t,n={}){return new Promise((o,s)=>{let r=ij(e,t,{cwd:n.cwd||process.cwd(),env:n.env||process.env,stdio:["ignore","pipe","pipe"]}),i="",a="",c="",u="";function d(f,p){let h=f.split(`
1972
1972
  `),m=h.pop();for(let g of h)p(g);return m}r.stdout.on("data",f=>{let p=f.toString("utf8");i+=p,c+=p,c=d(c,h=>{n.onStdoutLine&&n.onStdoutLine(h)})}),r.stderr.on("data",f=>{let p=f.toString("utf8");a+=p,u+=p,u=d(u,h=>{n.onStderrLine&&n.onStderrLine(h)})}),r.on("error",s),r.on("close",(f,p)=>{c&&n.onStdoutLine&&n.onStdoutLine(c),u&&n.onStderrLine&&n.onStderrLine(u),o({status:f,signal:p,stdout:i,stderr:a})})})}function gj(e){return!e||!rn.existsSync(e)?null:Lu(rn.readFileSync(e,"utf8"))}function yj(e,t=[]){let n=new Set(t),o=Za(e).find(s=>!n.has(s.fullPath));return o?o.fullPath:null}function px({sourceRun:e,verifiedRun:t,taskIds:n,tests:o,bundleDir:s}){let r=[],i=o.status===0?"passed":`failed (exit ${o.status})`,a=t?.finalScore??0,c=t?a-(e?.finalScore||0):null,u=t?(t.metrics?.timeoutRate||0)-(e?.metrics?.timeoutRate||0):null,d=t?(t.metrics?.avgToolCalls||0)-(e?.metrics?.avgToolCalls||0):null;return r.push(""),r.push("Harness Optimization Verification"),r.push(`- Source run: ${e?.runId||"unknown"}`),r.push(`- Focus tasks: ${n.join(", ")}`),r.push(`- Tests: ${i}`),t?(r.push(`- Verified run: ${t.runId||"unknown"}`),r.push(`- Score: ${a}/100${c===null?"":` (${c>=0?"+":""}${c})`}`),r.push(`- Timeout rate: ${Oh(t.metrics?.timeoutRate)}${u===null?"":` (${u>=0?"+":""}${u} pts)`}`),r.push(`- Avg tool calls: ${Math.round(t.metrics?.avgToolCalls||0)}${d===null?"":` (${d>=0?"+":""}${d})`}`),r.push(`- Tokens: ${Pu(t.totalTokens)}`)):r.push("- Verified run: not found"),r.push(`- Artifacts: ${s}`),r.push(""),r.push("Next Step"),o.status!==0?r.push("- Fix the failing tests before trusting the benchmark slice."):t?(t.metrics?.timeoutRate||0)>=70?r.push("- Timeout pressure is still high. Use the updated report and Codex prompt before running a full benchmark."):r.push("- This slice looks healthier. Re-run a broader slice or the full benchmark before updating the gate baseline."):r.push("- The benchmark slice did not produce a new result file. Inspect the captured logs."),r.join(`
1973
- `)}async function $j({rootDir:e=process.cwd(),latestRun:t,taskIds:n,testFiles:o,runner:s=ax,onProgress:r}={}){if(!t)throw new Error("No latest benchmark run available for verification.");let i=Array.isArray(n)&&n.length>0?n:fx(t),a=Array.isArray(o)&&o.length>0?o:["tests/agent.test.js","tests/headless.test.js","tests/benchmark-reallife.test.js"],c=pj(Bn.join(dx(e),hj())),u=Za(e).map(O=>O.fullPath);r&&r({phase:"tests",percent:5,message:`Running focused tests (${a.length} files)`});let d=Bn.join(e,"node_modules","jest","bin","jest.js"),f=await Promise.resolve(s(process.execPath,[d,...a,"--runInBand"],{cwd:e}));rn.writeFileSync(Bn.join(c,"tests.stdout.log"),f.stdout||""),rn.writeFileSync(Bn.join(c,"tests.stderr.log"),f.stderr||""),r&&r({phase:"tests",percent:20,message:f.status===0?"Focused tests passed":`Focused tests failed (exit ${f.status})`});let p=0,h=20,m=Math.max(1,i.length),g=s===ax?mj:s,$=[process.execPath,Bn.join(e,"scripts","benchmark-reallife.js"),"--tasks",i.join(",")];r&&r({phase:"benchmark",percent:25,message:`Running priority benchmark slice (${i.join(", ")})`});let b=await Promise.resolve(g(process.execPath,$.slice(1),{cwd:e,onStdoutLine(O){if(!r)return;let L=O.match(/Running ([\w-]+)\.\.\./);if(!L)return;p+=1;let Z=Math.min(95,20+Math.round(p/m*75));Z>h&&(h=Z,r({phase:"benchmark",percent:Z,message:`Running benchmark task ${p}/${m}: ${L[1]}`}))}}));rn.writeFileSync(Bn.join(c,"benchmark.stdout.log"),b.stdout||""),rn.writeFileSync(Bn.join(c,"benchmark.stderr.log"),b.stderr||""),r&&r({phase:"finalize",percent:97,message:"Writing verification artifacts"});let x=yj(e,u),_=gj(x),E=px({sourceRun:t,verifiedRun:_,taskIds:i,tests:f,bundleDir:c}),S={createdAt:new Date().toISOString(),sourceRunId:t.runId||null,taskIds:i,testFiles:a,tests:{status:f.status,signal:f.signal},benchmark:{status:b.status,signal:b.signal,resultPath:x},summary:E};return rn.writeFileSync(Bn.join(c,"verification.json"),JSON.stringify(S,null,2)),rn.writeFileSync(Bn.join(c,"SUMMARY.md"),`${E}
1973
+ `)}async function $j({rootDir:e=process.cwd(),latestRun:t,taskIds:n,testFiles:o,runner:s=ax,onProgress:r}={}){if(!t)throw new Error("No latest benchmark run available for verification.");let i=Array.isArray(n)&&n.length>0?n:fx(t),a=Array.isArray(o)&&o.length>0?o:["tests/agent.test.js","tests/headless.test.js","tests/benchmark-reallife.test.js"],c=pj(Bn.join(dx(e),hj())),u=Za(e).map(O=>O.fullPath);r&&r({phase:"tests",percent:5,message:`Running focused tests (${a.length} files)`});let d=Bn.join(e,"node_modules","jest","bin","jest.js"),f=await Promise.resolve(s(process.execPath,[d,...a,"--runInBand"],{cwd:e}));rn.writeFileSync(Bn.join(c,"tests.stdout.log"),f.stdout||""),rn.writeFileSync(Bn.join(c,"tests.stderr.log"),f.stderr||""),r&&r({phase:"tests",percent:20,message:f.status===0?"Focused tests passed":`Focused tests failed (exit ${f.status})`});let p=0,h=20,m=Math.max(1,i.length),g=s===ax?mj:s,y=[process.execPath,Bn.join(e,"scripts","benchmark-reallife.js"),"--tasks",i.join(",")];r&&r({phase:"benchmark",percent:25,message:`Running priority benchmark slice (${i.join(", ")})`});let b=await Promise.resolve(g(process.execPath,y.slice(1),{cwd:e,onStdoutLine(O){if(!r)return;let L=O.match(/Running ([\w-]+)\.\.\./);if(!L)return;p+=1;let Z=Math.min(95,20+Math.round(p/m*75));Z>h&&(h=Z,r({phase:"benchmark",percent:Z,message:`Running benchmark task ${p}/${m}: ${L[1]}`}))}}));rn.writeFileSync(Bn.join(c,"benchmark.stdout.log"),b.stdout||""),rn.writeFileSync(Bn.join(c,"benchmark.stderr.log"),b.stderr||""),r&&r({phase:"finalize",percent:97,message:"Writing verification artifacts"});let x=yj(e,u),_=gj(x),E=px({sourceRun:t,verifiedRun:_,taskIds:i,tests:f,bundleDir:c}),S={createdAt:new Date().toISOString(),sourceRunId:t.runId||null,taskIds:i,testFiles:a,tests:{status:f.status,signal:f.signal},benchmark:{status:b.status,signal:b.signal,resultPath:x},summary:E};return rn.writeFileSync(Bn.join(c,"verification.json"),JSON.stringify(S,null,2)),rn.writeFileSync(Bn.join(c,"SUMMARY.md"),`${E}
1974
1974
  `),r&&r({phase:"done",percent:100,message:`Saved verification bundle to ${c}`}),{bundleDir:c,summary:E,selectedTaskIds:i,selectedTests:a,tests:f,benchmark:b,verifiedRun:_}}function bj({latestRun:e,history:t,lastN:n=5,includePrompt:o=!1}={}){if(!e)return"No real-life benchmark results found. Run `npm run benchmark:reallife` first.";let s=Array.isArray(e.results)?e.results:[],r=t.slice(-Math.max(1,n)),i=dj(t,e),a=Object.entries(e.categoryMetrics||{}).sort((p,h)=>{let m=(p[1]?.avgScore||0)-(h[1]?.avgScore||0);return m!==0?m:(h[1]?.timeoutRate||0)-(p[1]?.timeoutRate||0)}).slice(0,3),c=s.map(p=>({...p,pattern:vi(p)})).sort((p,h)=>{let m=p.completionReason==="timeout"?1:0,g=h.completionReason==="timeout"?1:0;return g!==m?g-m:(p.score||0)!==(h.score||0)?(p.score||0)-(h.score||0):(h.toolCalls||0)!==(p.toolCalls||0)?(h.toolCalls||0)-(p.toolCalls||0):(h.tokens?.input||0)-(p.tokens?.input||0)}).slice(0,3),u=fj(s,e),d=c[0],f=[];if(f.push(""),f.push("Harness Optimization Report"),f.push(`- Run: ${e.runId||"unknown"}`),f.push(`- Score: ${e.finalScore||0}/100`),f.push(`- Timeout rate: ${Oh(e.metrics?.timeoutRate)}`),f.push(`- Avg tool calls: ${Math.round(e.metrics?.avgToolCalls||0)}`),f.push(`- Tokens: ${Pu(e.totalTokens)}`),f.push(`- Tasks: ${e.taskCount||s.length}`),i&&f.push(`- Trend vs previous: score ${i.scoreDelta>=0?"+":""}${i.scoreDelta}, timeout ${i.timeoutDelta>=0?"+":""}${i.timeoutDelta} pts, tools ${i.toolDelta>=0?"+":""}${i.toolDelta}`),r.length>1){let p=r.map(m=>m.finalScore||0),h=Math.round(p.reduce((m,g)=>m+g,0)/p.length);f.push(`- Recent average (${r.length} runs): ${h}/100`)}return f.push(""),f.push("Top Bottlenecks"),c.length===0?f.push("- No task-level details found in the latest run."):c.forEach((p,h)=>{f.push(`${h+1}. ${p.id} \u2014 ${p.score}/100, ${p.toolCalls||0} tools, ${p.completionReason||"unknown"}, ${p.pattern}`),f.push(` ${uj(p.pattern)}`)}),f.push(""),f.push("Weakest Categories"),a.length===0?f.push("- No category metrics found."):a.forEach(([p,h])=>{f.push(`- ${p}: ${h.avgScore}/100 avg, ${Oh(h.timeoutRate)} timeout, ${Math.round(h.avgToolCalls||0)} avg tools`)}),f.push(""),f.push("Recommendations"),u.length===0?f.push("- The latest run looks healthy. Re-run a larger slice before changing agent behavior."):u.forEach(p=>{f.push(`- ${p}`)}),o&&d&&(f.push(""),f.push("Suggested Codex Prompt"),f.push("```text"),f.push(ux(e,d)),f.push("```")),f.join(`
1975
1975
  `)}hx.exports={buildCodexPrompt:ux,buildOptimizationReport:bj,buildVerificationReport:px,classifyTask:vi,getPriorityDir:dx,getResultsDir:Nu,isHealthyRun:lx,listResultFiles:Za,readHistory:cj,readLatestResult:cx,readLatestProblematicResult:lj,selectPriorityTasks:fx,verifyHarnessOptimization:$j}});var vx=Q((AF,xx)=>{"use strict";var wj=require("os"),$x=require("path"),Mh=require("fs"),{callWithRetry:gx}=Sl(),{parseModelSpec:_j}=ft(),{extractJSON:yx,DECOMPOSE_PROMPT:kj,SYNTHESIZE_PROMPT:xj}=ya(),{C:Un}=dt(),Iu=$x.join(wj.homedir(),".nex-code","orchestrator-bench.json"),bx=[{id:"decompose_multi_bug",type:"decompose",prompt:"Fix 4 bugs: (1) 500 error on SmartThings API call, (2) invalid time format on Sunday schedule, (3) Google Auth callback fails with CORS, (4) contact search returns empty",expectedSubTasks:4,maxSubTasks:5},{id:"decompose_feature_mix",type:"decompose",prompt:"Add dark mode toggle to settings page, fix the broken login redirect, improve search performance by adding an index, update API docs for the new endpoints",expectedSubTasks:4,maxSubTasks:5},{id:"decompose_overlapping",type:"decompose",prompt:"Refactor auth.js to use JWT instead of sessions, update all tests that import auth.js, and add rate limiting to the login endpoint in auth.js",expectedSubTasks:3,maxSubTasks:4},{id:"decompose_single",type:"decompose",prompt:"Fix the broken CSS on the login page \u2014 the submit button is not aligned",expectedSubTasks:1,maxSubTasks:4},{id:"synthesize_clean",type:"synthesize",prompt:"Fix login and search bugs",subResults:[{task:"Fix login redirect",status:"done",result:"Changed auth.js line 42: fixed redirect URL to use req.originalUrl instead of hardcoded /",toolsUsed:["read_file","edit_file"]},{task:"Fix search index",status:"done",result:"Added index on users.email column in migration 20260323. Updated search.js to use indexed query.",toolsUsed:["write_file","edit_file"]}],expectedConflicts:0},{id:"synthesize_conflicts",type:"synthesize",prompt:"Fix config loading and add env validation",subResults:[{task:"Fix config loading",status:"done",result:"Modified config.js: changed loadConfig() to handle missing .env gracefully",toolsUsed:["edit_file"]},{task:"Add env validation",status:"done",result:"Modified config.js: added validateEnv() function that throws on missing required vars",toolsUsed:["edit_file"]}],expectedConflicts:1}];function wx(e,t){if(!Array.isArray(e))return 0;let n=0;n+=1.5;let o=Math.abs(e.length-t.expectedSubTasks);o===0?n+=3:o===1&&(n+=1.5),e.every(c=>c.task&&typeof c.task=="string"&&c.task.length>0)&&(n+=2);let r=e.flatMap(c=>Array.isArray(c.scope)?c.scope:[]),i=new Set(r);return r.length===i.size&&(n+=2),e.every(c=>typeof c.estimatedCalls=="number"||typeof c.estimatedSshCalls=="number")&&(n+=1.5),Math.min(10,Math.round(n*10)/10)}function _x(e,t){if(!e||typeof e!="object")return 0;let n=0;n+=1.5,e.summary&&e.summary.length>10&&(n+=2),e.commitMessage&&e.commitMessage.length>5&&(n+=2);let o=Array.isArray(e.conflicts)?e.conflicts:[];return t.expectedConflicts===0&&o.length===0||t.expectedConflicts>0&&o.length>0?n+=2.5:t.expectedConflicts>0&&o.length===0&&(n+=0),Array.isArray(e.filesChanged)&&e.filesChanged.length>0&&(n+=2),Math.min(10,Math.round(n*10)/10)}async function kx(e,t){let n={};if(t){let s=_j(t);s.provider&&(n.provider=s.provider),s.model&&(n.model=s.model)}let o=Date.now();try{if(e.type==="decompose"){let s=kj.replace("{maxSubTasks}",String(e.maxSubTasks)).replace("{prompt}",e.prompt),r=await gx([{role:"system",content:s},{role:"user",content:e.prompt}],[],n),i=yx(r.content||""),a=Date.now()-o;return{score:wx(i,e),latencyMs:a}}if(e.type==="synthesize"){let s=e.subResults.map((d,f)=>{let p=d.status==="done"?"SUCCESS":"FAILED";return`--- Agent ${f+1} [${p}] ---
1976
1976
  Task: ${d.task}
@@ -1981,8 +1981,8 @@ Tools: ${d.toolsUsed.join(", ")}`}).join(`
1981
1981
  ${Un.bold}${Un.cyan}Orchestrator Model Benchmark${Un.reset}
1982
1982
  `);let t=` ${"Model".padEnd(25)} ${"Decompose".padEnd(10)} ${"Synthesize".padEnd(11)} ${"Speed".padEnd(8)} ${"Score".padEnd(8)}`;console.log(`${Un.dim}${t}${Un.reset}`),console.log(` ${Un.dim}${"\u2500".repeat(65)}${Un.reset}`);for(let n of e){let o=e.indexOf(n)===0?"\u{1F947}":e.indexOf(n)===1?"\u{1F948}":e.indexOf(n)===2?"\u{1F949}":" ",s=`${(n.avgLatency/1e3).toFixed(1)}s`;console.log(`${o} ${n.model.padEnd(25)} ${(n.decompose+"/10").padEnd(10)} ${(n.synthesize+"/10").padEnd(11)} ${s.padEnd(8)} ${Un.bold}${n.overall}/10${Un.reset}`)}e.length>0&&(console.log(`
1983
1983
  ${Un.green}Best orchestrator: ${e[0].model} (${e[0].overall}/10)${Un.reset}`),console.log(` ${Un.dim}Saved to ${Iu}${Un.reset}
1984
- `))}xx.exports={runOrchestratorBenchmark:vj,ORCHESTRATOR_SCENARIOS:bx,scoreDecompose:wx,scoreSynthesize:_x,runScenario:kx,printResults:Sj,RESULTS_PATH:Iu}});var Tx=Q((OF,Ex)=>{var Ej=require("axios"),Qa=require("fs"),Sx=require("path"),Tj="nex-code",Ph=Sx.join(process.cwd(),".nex"),Nh=Sx.join(Ph,"last-version-check");Qa.existsSync(Ph)||Qa.mkdirSync(Ph,{recursive:!0});async function Rj(){try{let e=Aj(),t=Date.now();if(e&&t-e<1440*60*1e3)return{hasNewVersion:!1};Oj(t);let n=Cj(),s=(await Ej.get(`https://registry.npmjs.org/${Tj}/latest`,{timeout:5e3})).data.version,r=Mj(s,n);return{hasNewVersion:r,latestVersion:r?s:void 0,currentVersion:r?n:void 0}}catch{return{hasNewVersion:!1}}}function Cj(){return Ar().version}function Aj(){try{if(Qa.existsSync(Nh)){let e=Qa.readFileSync(Nh,"utf8");return parseInt(e,10)}}catch{}return null}function Oj(e){try{Qa.writeFileSync(Nh,e.toString())}catch{}}function Mj(e,t){try{let n=e.split(".").map(Number),o=t.split(".").map(Number);return n[0]>o[0]?!0:n[0]<o[0]?!1:n[1]>o[1]?!0:n[1]<o[1]?!1:n[2]>o[2]}catch{return!1}}Ex.exports={checkForNewVersion:Rj}});var Cx=Q((MF,Rx)=>{"use strict";var{C:le}=dt();function Lh(e){let t=Math.floor(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60),o=t%60;if(n<60)return`${n}m ${o<10?"0":""}${o}s`;let s=Math.floor(n/60),r=n%60;return`${s}h ${r<10?"0":""}${r}m ${o<10?"0":""}${o}s`}function ec(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e)}function tc(e,t){let n=String(e);return n.length>=t?n.slice(0,t):n+" ".repeat(t-n.length)}function Tn(e,t){let n=String(e);return n.length>=t?n.slice(0,t):" ".repeat(t-n.length)+n}function Pj(e,t,n=18){if(t===0)return"\u2591".repeat(n);let o=Math.round(e/t*n);return le.primary+"\u2588".repeat(o)+le.dim+"\u2591".repeat(n-o)+le.reset}function Nj({startTime:e,sessionId:t,messages:n}){if(!process.stdout.isTTY)return;let{extractSessionStats:o}=Su(),{getSessionCosts:s}=os(),r=o(n),i=s(),a=e?Date.now()-e:0,c=r!==null,u=i.breakdown.length>0;if(!c&&!u&&a<5e3)return;let f=Math.min(process.stdout.columns||72,80)-4,p=($="")=>process.stdout.write($+`
1985
- `),h=($=f)=>` ${le.dim}${"\u2500".repeat($)}${le.reset}`,m=$=>{p(""),p(` ${le.bold}${le.white}${$}${le.reset}`),p(h())};process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J"),p(""),p(h()),p(` ${le.bold}${le.primary} Agent powering down. Goodbye!${le.reset}`+(a>0?` ${le.dim}${Lh(a)}${le.reset}`:"")),p(h()),m("Interaction Summary");let g=($,b,x="")=>{p(` ${le.dim}${tc($+":",24)}${le.reset} ${le.white}${b}${le.reset}${x}`)};if(g("Session ID",t),c){let $=r.totalToolCalls-r.totalErrors,b=r.totalToolCalls>0?($/r.totalToolCalls*100).toFixed(1):"\u2014",x=`${r.totalToolCalls} ${le.dim}(${le.success}\u2713 ${$}${le.reset}`+(r.totalErrors>0?`${le.dim} ${le.error}\u2717 ${r.totalErrors}${le.reset}${le.dim}`:"")+`${le.dim})${le.reset}`;g("Tool Calls",x),g("Success Rate",`${b}%`),g("User Messages",String(r.userMessages));let _=Object.keys(r.filesModified||{}),E=Object.keys(r.filesAccessed||{});if(_.length>0){let S=_.slice(0,2).map(L=>{let I=L.split("/").pop();return`${le.dim}${I}${le.reset}`}).join(` ${le.dim}\xB7${le.reset} `),O=_.length>2?` ${le.dim}+${_.length-2} more${le.reset}`:"";g("Files Modified",String(_.length),` ${le.dim}\xB7${le.reset} ${S}${O}`)}E.length>0&&g("Files Read",String(E.length))}if(c&&a>0&&(m("Performance"),g("Wall Time",Lh(a)),g("Turns (user / assistant)",`${r.userMessages} ${le.dim}/${le.reset} ${r.assistantMessages}`),r.userMessages>0&&r.totalToolCalls>0)){let $=(r.totalToolCalls/r.userMessages).toFixed(1);g("Tools per User Message",$)}if(u){m("Token Usage");let $=34,b=6,x=10,_=9;p(` ${le.dim}`+tc("Model",$)+Tn("Reqs",b)+Tn("Input",x)+Tn("Output",x)+Tn("Cost",_)+le.reset),p(h());let E=0,S=0,O=0,L=0;for(let I of i.breakdown){let D=`${I.provider} \xB7 ${I.model}`,Z=D.length>$-1?D.slice(0,$-2)+"\u2026":D,K=I.cost>0?`$${I.cost.toFixed(4)}`:"free";E+=I.requests||0,S+=I.input,O+=I.output,L+=I.cost,p(` ${le.cyan}${tc(Z,$)}${le.reset}${le.dim}${Tn(I.requests||"\u2014",b)}${le.reset} ${le.dim}${Tn(ec(I.input),x-2)}${le.reset} ${le.dim}${Tn(ec(I.output),x-2)}${le.reset} ${I.cost>0?le.yellow:le.success}${Tn(K,_-2)}${le.reset}`)}if(i.breakdown.length>1){p(h());let I=L>0?`$${L.toFixed(4)}`:"free";p(` ${le.bold}${tc("Total",$)}${le.reset}${le.dim}${Tn(E||"\u2014",b)}${le.reset} ${le.dim}${Tn(ec(S),x-2)}${le.reset} ${le.dim}${Tn(ec(O),x-2)}${le.reset} ${L>0?le.yellow:le.success}${le.bold}${Tn(I,_-2)}${le.reset}`)}if(u&&S>0){let I=i.breakdown.reduce((D,Z)=>D+(Z.cacheRead||0),0);if(I>0){let D=(I/(S+I)*100).toFixed(1);p(""),p(` ${le.dim}Cache savings: ${le.success}${ec(I)}${le.reset}${le.dim} tokens (${D}%) served from cache${le.reset}`)}}}if(c&&r.totalToolCalls>0){let $=Object.entries(r.toolCalls).sort(([,b],[,x])=>x-b).slice(0,6);if($.length>0){m("Top Tools");let b=$[0][1],x=r.totalToolCalls;for(let[_,E]of $){let S=(E/x*100).toFixed(0),O=tc(_,22),L=Tn(String(E),4),I=Tn(`${S}%`,5);p(` ${le.cyan}${O}${le.reset} ${Pj(E,b,16)} ${le.white}${L}${le.reset} ${le.dim}${I}${le.reset}`)}}}if(c){let $=Object.entries(r.filesModified||{});if($.length>0){m("Modified Files");for(let[b,x]of $.slice(0,5)){let _=f-6,E=b.length>_?"\u2026"+b.slice(-(_-1)):b,S=x>1?` ${le.dim}(${x}\xD7)${le.reset}`:"";p(` ${le.success}\u270E${le.reset} ${le.white}${E}${le.reset}${S}`)}$.length>5&&p(` ${le.dim} \u2026 and ${$.length-5} more${le.reset}`)}}p(""),p(h()),p(` ${le.dim}Resume last session:${le.reset} ${le.cyan}nex-code --resume${le.reset}`),p(h()),p("")}Rx.exports={showGoodbyeScreen:Nj,formatDuration:Lh}});var Gh=Q((NF,Gx)=>{var Lj=require("readline"),en=require("fs"),zt=require("path"),{C:l,banner:Ij,cleanupTerminal:Ax}=dt(),{isDark:jj}=ln(),{listProviders:qh,getActiveProviderName:ro,listAllModels:PF,recommendModels:Dj,setFallbackChain:qj,getFallbackChain:Fj,getProvider:Bj}=ft(),{flushAutoSave:Ox}=ds(),{writeDreamLog:Uj,shouldConsolidate:Wj,consolidate:Hj}=Su(),{isDebug:Gj}=Wc(),{getActiveModel:bs,setActiveModel:Fh}=Go(),{printContext:Lx}=jl(),{loadAllSkills:Mx,getSkillCommands:Fu,handleSkillCommand:Yj}=Ys(),{setReadlineInterface:zj,setAutoConfirm:Kj,getAutoConfirm:jh,setAllowAlwaysHandler:Xj}=un(),{StickyFooter:Vj}=_k(),{getProviderCostMode:Px}=os(),an=process.cwd();function Ix(e){return typeof Px=="function"?Px(e):{tier:e==="ollama"||e==="local"?"affordable":"premium",label:e==="ollama"||e==="local"?"open-model path":"premium paid provider"}}function Oo(){return process.env.NODE_ENV==="test"||!!process.env.JEST_WORKER_ID}function Jj(e){return process.stdin.isTTY&&process.stdout.isTTY&&!Oo()&&e&&typeof e.setPrompt=="function"&&typeof e.prompt=="function"&&typeof e.question=="function"&&typeof e._ttyWrite=="function"&&typeof process.stdin.setRawMode=="function"}var gt=null,$s=null,Nx=null,Ih=null,ju=null,Du=Symbol.for("nex-code.replCleanup");function jx(){return $s?.signal??null}var rc=[{cmd:"/help",desc:"Show full help"},{cmd:"/model",desc:"Show/switch model"},{cmd:"/models",desc:"Recommend models by task type"},{cmd:"/routing",desc:"Show active model routing (per task category)"},{cmd:"/providers",desc:"List providers and models"},{cmd:"/fallback",desc:"Show/set fallback chain"},{cmd:"/tokens",desc:"Token usage and context budget"},{cmd:"/costs",desc:"Session token costs"},{cmd:"/budget",desc:"Show/set cost limits per provider"},{cmd:"/clear",desc:"Clear conversation"},{cmd:"/context",desc:"Show project context"},{cmd:"/tree [depth]",desc:"Show project file tree (default depth 3)"},{cmd:"/autoconfirm",desc:"Toggle auto-confirm"},{cmd:"/save",desc:"Save session"},{cmd:"/load",desc:"Load a saved session"},{cmd:"/sessions",desc:"List saved sessions"},{cmd:"/resume",desc:"Resume last session"},{cmd:"/branches",desc:"Show session tree (all branches)"},{cmd:"/timeline",desc:"Show message timeline of current branch"},{cmd:"/goto <index>",desc:"Jump to a message index (truncates after)"},{cmd:"/fork [index]",desc:"Create branch at index (default: current)"},{cmd:"/switch-branch <name>",desc:"Switch to a different conversation branch"},{cmd:"/delete-branch <name>",desc:"Delete a conversation branch"},{cmd:"/remember",desc:"Save a memory"},{cmd:"/forget",desc:"Delete a memory"},{cmd:"/memory",desc:"Show all memories"},{cmd:"/brain",desc:"Manage knowledge base"},{cmd:"/brain add",desc:"Add document: /brain add <name> [content]"},{cmd:"/brain list",desc:"List all brain documents"},{cmd:"/brain search",desc:"Search brain: /brain search <query>"},{cmd:"/brain show",desc:"Show document: /brain show <name>"},{cmd:"/brain remove",desc:"Remove document: /brain remove <name>"},{cmd:"/brain rebuild",desc:"Rebuild keyword index"},{cmd:"/brain embed",desc:"Build/rebuild embedding index"},{cmd:"/brain status",desc:"Show brain status (docs, index, embeddings)"},{cmd:"/brain review",desc:"Review pending brain changes (git diff)"},{cmd:"/brain undo",desc:"Undo last brain write"},{cmd:"/learn",desc:"Reflect on session and update memory"},{cmd:"/optimize",desc:"Show optimization opportunities"},{cmd:"/permissions",desc:"Show tool permissions"},{cmd:"/allow",desc:"Auto-allow a tool"},{cmd:"/deny",desc:"Block a tool"},{cmd:"/plan",desc:"Plan mode (analyze before executing)"},{cmd:"/plan edit",desc:"Open current plan in $EDITOR"},{cmd:"/plans",desc:"List saved plans"},{cmd:"/auto",desc:"Set autonomy level"},{cmd:"/commit",desc:"Smart commit (diff + message)"},{cmd:"/diff",desc:"Show current diff"},{cmd:"/review [--strict] [file]",desc:"Deep code review with score table and diff suggestions (--strict: force \u22653 critical findings)"},{cmd:"/branch",desc:"Create feature branch"},{cmd:"/mcp",desc:"MCP servers and tools"},{cmd:"/mcp list",desc:"List connected MCP servers and their tools"},{cmd:"/mcp status",desc:"Show which MCP servers are running"},{cmd:"/hooks",desc:"Show configured hooks"},{cmd:"/skills",desc:"List, enable, disable skills"},{cmd:"/install-skill <url>",desc:"Install a skill from git URL or user/repo"},{cmd:"/search-skill <query>",desc:"Search for skills on GitHub"},{cmd:"/remove-skill <name>",desc:"Remove an installed skill"},{cmd:"/tasks",desc:"Show task list"},{cmd:"/servers",desc:"List server profiles / ping"},{cmd:"/docker",desc:"List containers across all servers"},{cmd:"/deploy",desc:"List deploy configs / run named deploy"},{cmd:"/benchmark [--quick] [--models=a,b]",desc:"Rank Ollama Cloud models on nex-code tool-calling tasks (--history for nightly log)"},{cmd:"/bench [--dry-run] [--model=<spec>]",desc:"Run scenario benchmark (5 agentic tasks)"},{cmd:"/trend [n]",desc:"Show score history trend (default: last 10 sessions)"},{cmd:"/harness-optimization [--last N] [--prompt] [--verify]",desc:"Analyze recent real-life benchmark runs and optionally verify a priority slice"},{cmd:"/init",desc:"Interactive setup wizard (.nex/)"},{cmd:"/setup",desc:"Configure provider and API keys"},{cmd:"/retry [--model <id>]",desc:"Retry last user turn (optionally with a different model)"},{cmd:"/undo",desc:"Undo last file change"},{cmd:"/redo",desc:"Redo last undone change"},{cmd:"/history",desc:"Show file change history"},{cmd:"/snapshot [name]",desc:"Create a named git snapshot of current changes"},{cmd:"/restore [name|last]",desc:"Restore a previously created snapshot"},{cmd:"/orchestrate <prompt>",desc:"Decompose prompt into parallel sub-tasks, run, synthesize"},{cmd:"/bench-orchestrator",desc:"Benchmark models for orchestrator role"},{cmd:"/audit",desc:"Show tool execution audit log"},{cmd:"/k8s",desc:"Kubernetes overview: namespaces and pods"},{cmd:"/exit",desc:"Quit"}];function Dx(){let e=Fu(),t=[...rc,...e],n=Math.max(...t.map(o=>o.cmd.length));console.log("");for(let{cmd:o,desc:s}of rc)console.log(` ${l.cyan}${o.padEnd(n+2)}${l.reset}${l.dim}${s}${l.reset}`);for(let{cmd:o,desc:s}of e)console.log(` ${l.cyan}${o.padEnd(n+2)}${l.reset}${l.dim}${s} ${l.yellow}[skill]${l.reset}`);console.log(`
1984
+ `))}xx.exports={runOrchestratorBenchmark:vj,ORCHESTRATOR_SCENARIOS:bx,scoreDecompose:wx,scoreSynthesize:_x,runScenario:kx,printResults:Sj,RESULTS_PATH:Iu}});var Tx=Q((OF,Ex)=>{var Ej=require("axios"),Qa=require("fs"),Sx=require("path"),Tj="nex-code",Ph=Sx.join(process.cwd(),".nex"),Nh=Sx.join(Ph,"last-version-check");Qa.existsSync(Ph)||Qa.mkdirSync(Ph,{recursive:!0});async function Rj(){try{let e=Aj(),t=Date.now();if(e&&t-e<1440*60*1e3)return{hasNewVersion:!1};Oj(t);let n=Cj(),s=(await Ej.get(`https://registry.npmjs.org/${Tj}/latest`,{timeout:5e3})).data.version,r=Mj(s,n);return{hasNewVersion:r,latestVersion:r?s:void 0,currentVersion:r?n:void 0}}catch{return{hasNewVersion:!1}}}function Cj(){return Ar().version}function Aj(){try{if(Qa.existsSync(Nh)){let e=Qa.readFileSync(Nh,"utf8");return parseInt(e,10)}}catch{}return null}function Oj(e){try{Qa.writeFileSync(Nh,e.toString())}catch{}}function Mj(e,t){try{let n=e.split(".").map(Number),o=t.split(".").map(Number);return n[0]>o[0]?!0:n[0]<o[0]?!1:n[1]>o[1]?!0:n[1]<o[1]?!1:n[2]>o[2]}catch{return!1}}Ex.exports={checkForNewVersion:Rj}});var Cx=Q((MF,Rx)=>{"use strict";var{C:le}=dt();function Lh(e){let t=Math.floor(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60),o=t%60;if(n<60)return`${n}m ${o<10?"0":""}${o}s`;let s=Math.floor(n/60),r=n%60;return`${s}h ${r<10?"0":""}${r}m ${o<10?"0":""}${o}s`}function ec(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e)}function tc(e,t){let n=String(e);return n.length>=t?n.slice(0,t):n+" ".repeat(t-n.length)}function Tn(e,t){let n=String(e);return n.length>=t?n.slice(0,t):" ".repeat(t-n.length)+n}function Pj(e,t,n=18){if(t===0)return"\u2591".repeat(n);let o=Math.round(e/t*n);return le.primary+"\u2588".repeat(o)+le.dim+"\u2591".repeat(n-o)+le.reset}function Nj({startTime:e,sessionId:t,messages:n}){if(!process.stdout.isTTY)return;let{extractSessionStats:o}=Su(),{getSessionCosts:s}=os(),r=o(n),i=s(),a=e?Date.now()-e:0,c=r!==null,u=i.breakdown.length>0;if(!c&&!u&&a<5e3)return;let f=Math.min(process.stdout.columns||72,80)-4,p=(y="")=>process.stdout.write(y+`
1985
+ `),h=(y=f)=>` ${le.dim}${"\u2500".repeat(y)}${le.reset}`,m=y=>{p(""),p(` ${le.bold}${le.white}${y}${le.reset}`),p(h())};process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J"),p(""),p(h()),p(` ${le.bold}${le.primary} Agent powering down. Goodbye!${le.reset}`+(a>0?` ${le.dim}${Lh(a)}${le.reset}`:"")),p(h()),m("Interaction Summary");let g=(y,b,x="")=>{p(` ${le.dim}${tc(y+":",24)}${le.reset} ${le.white}${b}${le.reset}${x}`)};if(g("Session ID",t),c){let y=r.totalToolCalls-r.totalErrors,b=r.totalToolCalls>0?(y/r.totalToolCalls*100).toFixed(1):"\u2014",x=`${r.totalToolCalls} ${le.dim}(${le.success}\u2713 ${y}${le.reset}`+(r.totalErrors>0?`${le.dim} ${le.error}\u2717 ${r.totalErrors}${le.reset}${le.dim}`:"")+`${le.dim})${le.reset}`;g("Tool Calls",x),g("Success Rate",`${b}%`),g("User Messages",String(r.userMessages));let _=Object.keys(r.filesModified||{}),E=Object.keys(r.filesAccessed||{});if(_.length>0){let S=_.slice(0,2).map(L=>{let I=L.split("/").pop();return`${le.dim}${I}${le.reset}`}).join(` ${le.dim}\xB7${le.reset} `),O=_.length>2?` ${le.dim}+${_.length-2} more${le.reset}`:"";g("Files Modified",String(_.length),` ${le.dim}\xB7${le.reset} ${S}${O}`)}E.length>0&&g("Files Read",String(E.length))}if(c&&a>0&&(m("Performance"),g("Wall Time",Lh(a)),g("Turns (user / assistant)",`${r.userMessages} ${le.dim}/${le.reset} ${r.assistantMessages}`),r.userMessages>0&&r.totalToolCalls>0)){let y=(r.totalToolCalls/r.userMessages).toFixed(1);g("Tools per User Message",y)}if(u){m("Token Usage");let y=34,b=6,x=10,_=9;p(` ${le.dim}`+tc("Model",y)+Tn("Reqs",b)+Tn("Input",x)+Tn("Output",x)+Tn("Cost",_)+le.reset),p(h());let E=0,S=0,O=0,L=0;for(let I of i.breakdown){let D=`${I.provider} \xB7 ${I.model}`,Z=D.length>y-1?D.slice(0,y-2)+"\u2026":D,K=I.cost>0?`$${I.cost.toFixed(4)}`:"free";E+=I.requests||0,S+=I.input,O+=I.output,L+=I.cost,p(` ${le.cyan}${tc(Z,y)}${le.reset}${le.dim}${Tn(I.requests||"\u2014",b)}${le.reset} ${le.dim}${Tn(ec(I.input),x-2)}${le.reset} ${le.dim}${Tn(ec(I.output),x-2)}${le.reset} ${I.cost>0?le.yellow:le.success}${Tn(K,_-2)}${le.reset}`)}if(i.breakdown.length>1){p(h());let I=L>0?`$${L.toFixed(4)}`:"free";p(` ${le.bold}${tc("Total",y)}${le.reset}${le.dim}${Tn(E||"\u2014",b)}${le.reset} ${le.dim}${Tn(ec(S),x-2)}${le.reset} ${le.dim}${Tn(ec(O),x-2)}${le.reset} ${L>0?le.yellow:le.success}${le.bold}${Tn(I,_-2)}${le.reset}`)}if(u&&S>0){let I=i.breakdown.reduce((D,Z)=>D+(Z.cacheRead||0),0);if(I>0){let D=(I/(S+I)*100).toFixed(1);p(""),p(` ${le.dim}Cache savings: ${le.success}${ec(I)}${le.reset}${le.dim} tokens (${D}%) served from cache${le.reset}`)}}}if(c&&r.totalToolCalls>0){let y=Object.entries(r.toolCalls).sort(([,b],[,x])=>x-b).slice(0,6);if(y.length>0){m("Top Tools");let b=y[0][1],x=r.totalToolCalls;for(let[_,E]of y){let S=(E/x*100).toFixed(0),O=tc(_,22),L=Tn(String(E),4),I=Tn(`${S}%`,5);p(` ${le.cyan}${O}${le.reset} ${Pj(E,b,16)} ${le.white}${L}${le.reset} ${le.dim}${I}${le.reset}`)}}}if(c){let y=Object.entries(r.filesModified||{});if(y.length>0){m("Modified Files");for(let[b,x]of y.slice(0,5)){let _=f-6,E=b.length>_?"\u2026"+b.slice(-(_-1)):b,S=x>1?` ${le.dim}(${x}\xD7)${le.reset}`:"";p(` ${le.success}\u270E${le.reset} ${le.white}${E}${le.reset}${S}`)}y.length>5&&p(` ${le.dim} \u2026 and ${y.length-5} more${le.reset}`)}}p(""),p(h()),p(` ${le.dim}Resume last session:${le.reset} ${le.cyan}nex-code --resume${le.reset}`),p(h()),p("")}Rx.exports={showGoodbyeScreen:Nj,formatDuration:Lh}});var Gh=Q((NF,Gx)=>{var Lj=require("readline"),en=require("fs"),zt=require("path"),{C:l,banner:Ij,cleanupTerminal:Ax}=dt(),{isDark:jj}=ln(),{listProviders:qh,getActiveProviderName:ro,listAllModels:PF,recommendModels:Dj,setFallbackChain:qj,getFallbackChain:Fj,getProvider:Bj}=ft(),{flushAutoSave:Ox}=ds(),{writeDreamLog:Uj,shouldConsolidate:Wj,consolidate:Hj}=Su(),{isDebug:Gj}=Wc(),{getActiveModel:bs,setActiveModel:Fh}=Go(),{printContext:Lx}=jl(),{loadAllSkills:Mx,getSkillCommands:Fu,handleSkillCommand:Yj}=Ys(),{setReadlineInterface:zj,setAutoConfirm:Kj,getAutoConfirm:jh,setAllowAlwaysHandler:Xj}=un(),{StickyFooter:Vj}=_k(),{getProviderCostMode:Px}=os(),an=process.cwd();function Ix(e){return typeof Px=="function"?Px(e):{tier:e==="ollama"||e==="local"?"affordable":"premium",label:e==="ollama"||e==="local"?"open-model path":"premium paid provider"}}function Oo(){return process.env.NODE_ENV==="test"||!!process.env.JEST_WORKER_ID}function Jj(e){return process.stdin.isTTY&&process.stdout.isTTY&&!Oo()&&e&&typeof e.setPrompt=="function"&&typeof e.prompt=="function"&&typeof e.question=="function"&&typeof e._ttyWrite=="function"&&typeof process.stdin.setRawMode=="function"}var gt=null,$s=null,Nx=null,Ih=null,ju=null,Du=Symbol.for("nex-code.replCleanup");function jx(){return $s?.signal??null}var rc=[{cmd:"/help",desc:"Show full help"},{cmd:"/model",desc:"Show/switch model"},{cmd:"/models",desc:"Recommend models by task type"},{cmd:"/routing",desc:"Show active model routing (per task category)"},{cmd:"/providers",desc:"List providers and models"},{cmd:"/fallback",desc:"Show/set fallback chain"},{cmd:"/tokens",desc:"Token usage and context budget"},{cmd:"/costs",desc:"Session token costs"},{cmd:"/budget",desc:"Show/set cost limits per provider"},{cmd:"/clear",desc:"Clear conversation"},{cmd:"/context",desc:"Show project context"},{cmd:"/tree [depth]",desc:"Show project file tree (default depth 3)"},{cmd:"/autoconfirm",desc:"Toggle auto-confirm"},{cmd:"/save",desc:"Save session"},{cmd:"/load",desc:"Load a saved session"},{cmd:"/sessions",desc:"List saved sessions"},{cmd:"/resume",desc:"Resume last session"},{cmd:"/branches",desc:"Show session tree (all branches)"},{cmd:"/timeline",desc:"Show message timeline of current branch"},{cmd:"/goto <index>",desc:"Jump to a message index (truncates after)"},{cmd:"/fork [index]",desc:"Create branch at index (default: current)"},{cmd:"/switch-branch <name>",desc:"Switch to a different conversation branch"},{cmd:"/delete-branch <name>",desc:"Delete a conversation branch"},{cmd:"/remember",desc:"Save a memory"},{cmd:"/forget",desc:"Delete a memory"},{cmd:"/memory",desc:"Show all memories"},{cmd:"/brain",desc:"Manage knowledge base"},{cmd:"/brain add",desc:"Add document: /brain add <name> [content]"},{cmd:"/brain list",desc:"List all brain documents"},{cmd:"/brain search",desc:"Search brain: /brain search <query>"},{cmd:"/brain show",desc:"Show document: /brain show <name>"},{cmd:"/brain remove",desc:"Remove document: /brain remove <name>"},{cmd:"/brain rebuild",desc:"Rebuild keyword index"},{cmd:"/brain embed",desc:"Build/rebuild embedding index"},{cmd:"/brain status",desc:"Show brain status (docs, index, embeddings)"},{cmd:"/brain review",desc:"Review pending brain changes (git diff)"},{cmd:"/brain undo",desc:"Undo last brain write"},{cmd:"/learn",desc:"Reflect on session and update memory"},{cmd:"/optimize",desc:"Show optimization opportunities"},{cmd:"/permissions",desc:"Show tool permissions"},{cmd:"/allow",desc:"Auto-allow a tool"},{cmd:"/deny",desc:"Block a tool"},{cmd:"/plan",desc:"Plan mode (analyze before executing)"},{cmd:"/plan edit",desc:"Open current plan in $EDITOR"},{cmd:"/plans",desc:"List saved plans"},{cmd:"/auto",desc:"Set autonomy level"},{cmd:"/commit",desc:"Smart commit (diff + message)"},{cmd:"/diff",desc:"Show current diff"},{cmd:"/review [--strict] [file]",desc:"Deep code review with score table and diff suggestions (--strict: force \u22653 critical findings)"},{cmd:"/branch",desc:"Create feature branch"},{cmd:"/mcp",desc:"MCP servers and tools"},{cmd:"/mcp list",desc:"List connected MCP servers and their tools"},{cmd:"/mcp status",desc:"Show which MCP servers are running"},{cmd:"/hooks",desc:"Show configured hooks"},{cmd:"/skills",desc:"List, enable, disable skills"},{cmd:"/install-skill <url>",desc:"Install a skill from git URL or user/repo"},{cmd:"/search-skill <query>",desc:"Search for skills on GitHub"},{cmd:"/remove-skill <name>",desc:"Remove an installed skill"},{cmd:"/tasks",desc:"Show task list"},{cmd:"/servers",desc:"List server profiles / ping"},{cmd:"/docker",desc:"List containers across all servers"},{cmd:"/deploy",desc:"List deploy configs / run named deploy"},{cmd:"/benchmark [--quick] [--models=a,b]",desc:"Rank Ollama Cloud models on nex-code tool-calling tasks (--history for nightly log)"},{cmd:"/bench [--dry-run] [--model=<spec>]",desc:"Run scenario benchmark (5 agentic tasks)"},{cmd:"/trend [n]",desc:"Show score history trend (default: last 10 sessions)"},{cmd:"/harness-optimization [--last N] [--prompt] [--verify]",desc:"Analyze recent real-life benchmark runs and optionally verify a priority slice"},{cmd:"/init",desc:"Interactive setup wizard (.nex/)"},{cmd:"/setup",desc:"Configure provider and API keys"},{cmd:"/retry [--model <id>]",desc:"Retry last user turn (optionally with a different model)"},{cmd:"/undo",desc:"Undo last file change"},{cmd:"/redo",desc:"Redo last undone change"},{cmd:"/history",desc:"Show file change history"},{cmd:"/snapshot [name]",desc:"Create a named git snapshot of current changes"},{cmd:"/restore [name|last]",desc:"Restore a previously created snapshot"},{cmd:"/orchestrate <prompt>",desc:"Decompose prompt into parallel sub-tasks, run, synthesize"},{cmd:"/bench-orchestrator",desc:"Benchmark models for orchestrator role"},{cmd:"/audit",desc:"Show tool execution audit log"},{cmd:"/k8s",desc:"Kubernetes overview: namespaces and pods"},{cmd:"/exit",desc:"Quit"}];function Dx(){let e=Fu(),t=[...rc,...e],n=Math.max(...t.map(o=>o.cmd.length));console.log("");for(let{cmd:o,desc:s}of rc)console.log(` ${l.cyan}${o.padEnd(n+2)}${l.reset}${l.dim}${s}${l.reset}`);for(let{cmd:o,desc:s}of e)console.log(` ${l.cyan}${o.padEnd(n+2)}${l.reset}${l.dim}${s} ${l.yellow}[skill]${l.reset}`);console.log(`
1986
1986
  ${l.dim}Type /help for detailed usage${l.reset}
1987
1987
  `)}function qx(e){try{let t,n;e.endsWith("/")||e.endsWith(zt.sep)?(t=e,n=""):(t=zt.dirname(e),n=zt.basename(e)),t.startsWith("~")&&(t=zt.join(require("os").homedir(),t.slice(1)));let o=zt.isAbsolute(t)?t:zt.resolve(an,t);if(!en.existsSync(o)||!en.statSync(o).isDirectory())return[];let s=en.readdirSync(o,{withFileTypes:!0}),r=[];for(let i of s){if(i.name.startsWith(".")||i.name==="node_modules"||n&&!i.name.startsWith(n))continue;let a=e.endsWith("/")||e.endsWith(zt.sep)?e:zt.dirname(e)+"/",c=a==="./"&&!e.startsWith("./")?i.name:a+i.name;r.push(i.isDirectory()?c+"/":c)}return r}catch{return[]}}function Fx(e){if(e.startsWith("/")){let o=[...rc,...Fu()],s=o.map(r=>r.cmd).filter(r=>r.startsWith(e));return[s.length?s:o.map(r=>r.cmd),e]}let t=e.split(/\s+/),n=t[t.length-1]||"";return n&&(n.includes("/")||n.startsWith("./")||n.startsWith("../")||n.startsWith("~"))?[qx(n),n]:[[],e]}function Bx(){console.log(`
1988
1988
  ${l.bold}${l.cyan}Commands:${l.reset}
@@ -2072,7 +2072,7 @@ ${l.bold}${l.cyan}Token Usage:${l.reset}`),console.log(` ${l.dim}Model:${l.rese
2072
2072
  ${l.dim}Breakdown:${l.reset}`),console.log(` System prompt: ${c.breakdown.system.toLocaleString()} tokens`),console.log(` Conversation: ${c.breakdown.conversation.toLocaleString()} tokens`),console.log(` Tool results: ${c.breakdown.toolResults.toLocaleString()} tokens`),console.log(` Tool definitions: ${c.breakdown.toolDefinitions.toLocaleString()} tokens`),console.log(` Messages: ${c.messageCount}`),console.log(),!0}case"/costs":{let{formatCosts:s,resetCosts:r}=os();return o.join(" ").trim()==="reset"?(r(),console.log(`${l.green}Cost tracking reset${l.reset}`),!0):(console.log(`
2073
2073
  ${s()}
2074
2074
  `),!0)}case"/budget":{let{getCostLimits:s,getProviderSpend:r,checkBudget:i,removeCostLimit:a,saveCostLimits:c,setCostLimit:u}=os(),d=o[0];if(!d){let h=s(),m=qh();console.log(`
2075
- ${l.bold}${l.cyan}Cost Limits:${l.reset}`);let g=!1;for(let $ of m){let b=r($.provider),x=h[$.provider];if(x!==void 0){g=!0;let _=Math.min(100,Math.round(b/x*100)),E=10,S=Math.round(_/100*E),O=E-S,I=`${_>=100?l.red:_>=80?l.yellow:l.green}${"\u2588".repeat(S)}${l.dim}${"\u2591".repeat(O)}${l.reset}`;console.log(` ${l.bold}${$.provider}:${l.reset} $${b.toFixed(2)} / $${x.toFixed(2)} (${_}%) ${I}`)}else $.provider==="ollama"||$.provider==="local"?console.log(` ${l.bold}${$.provider}:${l.reset} ${l.dim}free (no limit)${l.reset}`):b>0&&console.log(` ${l.bold}${$.provider}:${l.reset} $${b.toFixed(2)} ${l.dim}(no limit)${l.reset}`)}return g||console.log(` ${l.dim}No limits set. Use /budget <provider> <amount> to set one.${l.reset}`),console.log(),!0}let f=o[1];if(!f){let h=i(d);return h.limit!==null?console.log(`${l.bold}${d}:${l.reset} $${h.spent.toFixed(2)} / $${h.limit.toFixed(2)} ($${h.remaining.toFixed(2)} remaining)`):console.log(`${l.bold}${d}:${l.reset} $${h.spent.toFixed(2)} ${l.dim}(no limit)${l.reset}`),!0}if(f==="off"||f==="remove"||f==="clear")return a(d),c(),console.log(`${l.green}Removed cost limit for ${d}${l.reset}`),!0;let p=parseFloat(f);return isNaN(p)||p<=0?(console.log(`${l.red}Invalid amount: ${f}. Use a positive number or 'off'.${l.reset}`),!0):(u(d,p),c(),console.log(`${l.green}Set ${d} budget limit: $${p.toFixed(2)}${l.reset}`),!0)}case"/clear":{let{clearConversation:s,getConversationMessages:r}=We(),{clearHistory:i}=Gs(),a=r();if(a.filter(d=>d.role==="user").length>=4){process.stdout.write(`${l.dim}Reflecting on session...${l.reset} `);let{learnFromSession:d}=gh();d(a).then(f=>{if(!f.skipped&&!f.error&&(f.applied.length>0||f.nexAdded.length>0)){let p=f.applied.length+f.nexAdded.length;process.stdout.write(`${l.green}${p} learning(s) saved${l.reset}
2075
+ ${l.bold}${l.cyan}Cost Limits:${l.reset}`);let g=!1;for(let y of m){let b=r(y.provider),x=h[y.provider];if(x!==void 0){g=!0;let _=Math.min(100,Math.round(b/x*100)),E=10,S=Math.round(_/100*E),O=E-S,I=`${_>=100?l.red:_>=80?l.yellow:l.green}${"\u2588".repeat(S)}${l.dim}${"\u2591".repeat(O)}${l.reset}`;console.log(` ${l.bold}${y.provider}:${l.reset} $${b.toFixed(2)} / $${x.toFixed(2)} (${_}%) ${I}`)}else y.provider==="ollama"||y.provider==="local"?console.log(` ${l.bold}${y.provider}:${l.reset} ${l.dim}free (no limit)${l.reset}`):b>0&&console.log(` ${l.bold}${y.provider}:${l.reset} $${b.toFixed(2)} ${l.dim}(no limit)${l.reset}`)}return g||console.log(` ${l.dim}No limits set. Use /budget <provider> <amount> to set one.${l.reset}`),console.log(),!0}let f=o[1];if(!f){let h=i(d);return h.limit!==null?console.log(`${l.bold}${d}:${l.reset} $${h.spent.toFixed(2)} / $${h.limit.toFixed(2)} ($${h.remaining.toFixed(2)} remaining)`):console.log(`${l.bold}${d}:${l.reset} $${h.spent.toFixed(2)} ${l.dim}(no limit)${l.reset}`),!0}if(f==="off"||f==="remove"||f==="clear")return a(d),c(),console.log(`${l.green}Removed cost limit for ${d}${l.reset}`),!0;let p=parseFloat(f);return isNaN(p)||p<=0?(console.log(`${l.red}Invalid amount: ${f}. Use a positive number or 'off'.${l.reset}`),!0):(u(d,p),c(),console.log(`${l.green}Set ${d} budget limit: $${p.toFixed(2)}${l.reset}`),!0)}case"/clear":{let{clearConversation:s,getConversationMessages:r}=We(),{clearHistory:i}=Gs(),a=r();if(a.filter(d=>d.role==="user").length>=4){process.stdout.write(`${l.dim}Reflecting on session...${l.reset} `);let{learnFromSession:d}=gh();d(a).then(f=>{if(!f.skipped&&!f.error&&(f.applied.length>0||f.nexAdded.length>0)){let p=f.applied.length+f.nexAdded.length;process.stdout.write(`${l.green}${p} learning(s) saved${l.reset}
2076
2076
  `)}else process.stdout.write(`${l.dim}nothing new${l.reset}
2077
2077
  `)}).catch(()=>process.stdout.write(`
2078
2078
  `))}s(),i(),gt=null;let{deleteSession:u}=ds();return u("_autosave"),console.log(`${l.green}Conversation cleared${l.reset}`),!0}case"/retry":{let{getConversationMessages:s,setConversationMessages:r,processInput:i}=We(),a=s(),c=a.map(g=>g.role).lastIndexOf("user");if(c===-1)return console.log(`${l.yellow}Nothing to retry \u2014 no user message found.${l.reset}`),!0;let u=o.indexOf("--model"),d=u!==-1&&o[u+1]?o[u+1]:null;if(d){let{setActiveModel:g}=ft();if(!g(d))return console.log(`${l.red}Unknown model: ${d}. Use /providers to see available models.${l.reset}`),!0;console.log(`${l.cyan}Switched to model: ${d}${l.reset}`)}let f=a[c],p;typeof f.content=="string"?p=f.content:Array.isArray(f.content)?p=f.content.filter(g=>g&&g.type==="text").map(g=>g.text).join(`
@@ -2083,27 +2083,27 @@ ${l.bold}${l.cyan}Project tree${l.reset}${l.dim} (depth ${i})${l.reset}
2083
2083
  ${l.bold}${l.cyan}Sessions:${l.reset}`);for(let i of r){let a=i.updatedAt?new Date(i.updatedAt).toLocaleString():"?",c=i.name==="_autosave"?` ${l.dim}(auto)${l.reset}`:"",u=i.score!=null?` \xB7 score ${i.score}/10${i.scoreGrade?` (${i.scoreGrade})`:""}`:"";console.log(` ${l.cyan}${i.name}${l.reset}${c} \u2014 ${i.messageCount} msgs, ${a}${l.dim}${u}${l.reset}`)}return console.log(),!0}case"/resume":{let{getLastSession:s}=ds(),{setConversationMessages:r}=We(),i=s();return i?(r(i.messages),console.log(`${l.green}Resumed: ${i.name} (${i.messageCount} messages)${l.reset}`),!0):(console.log(`${l.yellow}No session to resume${l.reset}`),!0)}case"/branches":{let{initTree:s,renderTree:r}=To(),{getConversationMessages:i}=We(),a=i();return a.length===0?(console.log(`${l.yellow}No conversation yet${l.reset}`),!0):(gt||(gt=s({messages:a})),console.log(r(gt)),console.log(),!0)}case"/timeline":{let{initTree:s,renderTimeline:r}=To(),{getConversationMessages:i}=We(),a=i();if(a.length===0)return console.log(`${l.yellow}No conversation yet${l.reset}`),!0;gt||(gt=s({messages:a})),To().setActiveMessages(gt,a);let u=parseInt(o[0],10)||20;return console.log(r(gt,u)),console.log(),!0}case"/goto":{let s=To(),{getConversationMessages:r,setConversationMessages:i}=We(),a=r();if(a.length===0)return console.log(`${l.yellow}No conversation yet${l.reset}`),!0;let c=parseInt(o[0],10);if(isNaN(c))return console.log(`${l.red}Usage: /goto <message-index>${l.reset}`),console.log(`${l.dim}Use /timeline to see message indices${l.reset}`),!0;gt||(gt=s.initTree({messages:a})),s.setActiveMessages(gt,a);try{let{truncated:u}=s.gotoMessage(gt,c),d=s.getActiveMessages(gt);i(d),console.log(`${l.green}Jumped to message ${c}. Removed ${u} later messages.${l.reset}`),console.log(`${l.dim}Conversation now has ${d.length} messages. Continue chatting from here.${l.reset}`)}catch(u){console.log(`${l.red}${u.message}${l.reset}`)}return!0}case"/fork":{let s=To(),{getConversationMessages:r,setConversationMessages:i}=We(),a=r();if(a.length===0)return console.log(`${l.yellow}No conversation yet${l.reset}`),!0;gt||(gt=s.initTree({messages:a})),s.setActiveMessages(gt,a);let c=o[0]?parseInt(o[0],10):a.length-1,u=o[1]||void 0;if(isNaN(c))return console.log(`${l.red}Usage: /fork [message-index] [branch-name]${l.reset}`),!0;try{let{branchName:d}=s.createBranch(gt,c,u),f=s.getActiveMessages(gt);i(f),console.log(`${l.green}Created branch "${d}" forking at message ${c}${l.reset}`),console.log(`${l.dim}Now on branch "${d}" with ${f.length} messages. Continue chatting.${l.reset}`)}catch(d){console.log(`${l.red}${d.message}${l.reset}`)}return!0}case"/switch-branch":{let s=To(),{getConversationMessages:r,setConversationMessages:i}=We();if(!gt){let c=r();gt=s.initTree({messages:c})}s.setActiveMessages(gt,r());let a=o.join(" ").trim();if(!a)return console.log(`${l.red}Usage: /switch-branch <name>${l.reset}`),console.log(`${l.dim}Available: ${Object.keys(gt.branches).join(", ")}${l.reset}`),!0;try{s.switchBranch(gt,a);let c=s.getActiveMessages(gt);i(c),console.log(`${l.green}Switched to branch "${a}" (${c.length} messages)${l.reset}`)}catch(c){console.log(`${l.red}${c.message}${l.reset}`)}return!0}case"/delete-branch":{let s=To();if(!gt){let{getConversationMessages:i}=We();gt=s.initTree({messages:i()})}let r=o.join(" ").trim();if(!r)return console.log(`${l.red}Usage: /delete-branch <name>${l.reset}`),!0;try{s.deleteBranch(gt,r),console.log(`${l.green}Deleted branch "${r}"${l.reset}`)}catch(i){console.log(`${l.red}${i.message}${l.reset}`)}return!0}case"/remember":{let{remember:s}=as(),r=o.join(" ").trim();if(!r)return console.log(`${l.red}Usage: /remember <key>=<value> or /remember <text>${l.reset}`),!0;let i=r.indexOf("="),a,c;return i>0?(a=r.substring(0,i).trim(),c=r.substring(i+1).trim()):(a=r.substring(0,40).replace(/\s+/g,"-"),c=r),s(a,c),console.log(`${l.green}Remembered: ${a}${l.reset}`),!0}case"/forget":{let{forget:s}=as(),r=o.join(" ").trim();return r?(s(r)?console.log(`${l.green}Forgotten: ${r}${l.reset}`):console.log(`${l.red}Memory not found: ${r}${l.reset}`),!0):(console.log(`${l.red}Usage: /forget <key>${l.reset}`),!0)}case"/memory":{let{listMemories:s}=as(),r=s();if(r.length===0)return console.log(`${l.dim}No memories saved${l.reset}`),!0;console.log(`
2084
2084
  ${l.bold}${l.cyan}Memory:${l.reset}`);for(let i of r)console.log(` ${l.cyan}${i.key}${l.reset} = ${i.value}`);return console.log(),!0}case"/brain":{let{listDocuments:s,readDocument:r,writeDocument:i,removeDocument:a,buildIndex:c,buildEmbeddingIndex:u,isEmbeddingAvailable:d,query:f}=Vi(),p=o[0],h=o.slice(1).join(" ").trim();switch(p){case"add":{if(!h)return console.log(`${l.red}Usage: /brain add <name> [content]${l.reset}`),console.log(`${l.dim} /brain add api-notes \u2014 creates empty file${l.reset}`),console.log(`${l.dim} /brain add api-notes This is content \u2014 writes directly${l.reset}`),!0;let m=h.indexOf(" ");if(m<0){i(h,`# ${h}
2085
2085
 
2086
- `);let g=require("path").join(process.cwd(),".nex","brain",`${h}.md`);console.log(`${l.green}Created .nex/brain/${h}.md${l.reset}`),console.log(`${l.dim}Edit it directly at: ${g}${l.reset}`)}else{let g=h.substring(0,m),$=h.substring(m+1);i(g,$),console.log(`${l.green}Added to brain: ${g}${l.reset}`)}return!0}case"list":{let m=s();if(m.length===0)return console.log(`${l.dim}No brain documents yet. Use /brain add <name> to create one.${l.reset}`),!0;console.log(`
2087
- ${l.bold}${l.cyan}Brain Documents:${l.reset}`);let g=Math.max(8,...m.map(b=>b.name.length)),$=20;console.log(` ${"Name".padEnd(g+2)}${"Tags".padEnd($)}${"Size".padStart(7)} Modified`),console.log(` ${"-".repeat(g+2)}${"-".repeat($)}${"-".repeat(7)} --------`);for(let b of m){let{frontmatter:x}=r(b.name),_=Array.isArray(x.tags)?x.tags.join(", "):"",E=b.size<1024?`${b.size}B`:`${(b.size/1024).toFixed(1)}K`,S=b.modified.toLocaleDateString();console.log(` ${l.cyan}${b.name.padEnd(g+2)}${l.reset}${l.dim}${_.substring(0,$-1).padEnd($)}${E.padStart(7)} ${S}${l.reset}`)}return console.log(),!0}case"search":{if(!h)return console.log(`${l.red}Usage: /brain search <query>${l.reset}`),!0;let m=await f(h,{topK:5});if(m.length===0)return console.log(`${l.dim}No matching brain documents for: ${h}${l.reset}`),!0;console.log(`
2088
- ${l.bold}${l.cyan}Brain Search: "${h}"${l.reset}`);for(let g of m){let $=typeof g.score=="number"?g.score.toFixed(2):g.score;console.log(`
2089
- ${l.cyan}${g.name}${l.reset} ${l.dim}(score: ${$})${l.reset}`),console.log(` ${l.dim}${g.excerpt||""}${l.reset}`)}return console.log(),!0}case"show":{if(!h)return console.log(`${l.red}Usage: /brain show <name>${l.reset}`),!0;let m=r(h);return m.content?(console.log(`
2086
+ `);let g=require("path").join(process.cwd(),".nex","brain",`${h}.md`);console.log(`${l.green}Created .nex/brain/${h}.md${l.reset}`),console.log(`${l.dim}Edit it directly at: ${g}${l.reset}`)}else{let g=h.substring(0,m),y=h.substring(m+1);i(g,y),console.log(`${l.green}Added to brain: ${g}${l.reset}`)}return!0}case"list":{let m=s();if(m.length===0)return console.log(`${l.dim}No brain documents yet. Use /brain add <name> to create one.${l.reset}`),!0;console.log(`
2087
+ ${l.bold}${l.cyan}Brain Documents:${l.reset}`);let g=Math.max(8,...m.map(b=>b.name.length)),y=20;console.log(` ${"Name".padEnd(g+2)}${"Tags".padEnd(y)}${"Size".padStart(7)} Modified`),console.log(` ${"-".repeat(g+2)}${"-".repeat(y)}${"-".repeat(7)} --------`);for(let b of m){let{frontmatter:x}=r(b.name),_=Array.isArray(x.tags)?x.tags.join(", "):"",E=b.size<1024?`${b.size}B`:`${(b.size/1024).toFixed(1)}K`,S=b.modified.toLocaleDateString();console.log(` ${l.cyan}${b.name.padEnd(g+2)}${l.reset}${l.dim}${_.substring(0,y-1).padEnd(y)}${E.padStart(7)} ${S}${l.reset}`)}return console.log(),!0}case"search":{if(!h)return console.log(`${l.red}Usage: /brain search <query>${l.reset}`),!0;let m=await f(h,{topK:5});if(m.length===0)return console.log(`${l.dim}No matching brain documents for: ${h}${l.reset}`),!0;console.log(`
2088
+ ${l.bold}${l.cyan}Brain Search: "${h}"${l.reset}`);for(let g of m){let y=typeof g.score=="number"?g.score.toFixed(2):g.score;console.log(`
2089
+ ${l.cyan}${g.name}${l.reset} ${l.dim}(score: ${y})${l.reset}`),console.log(` ${l.dim}${g.excerpt||""}${l.reset}`)}return console.log(),!0}case"show":{if(!h)return console.log(`${l.red}Usage: /brain show <name>${l.reset}`),!0;let m=r(h);return m.content?(console.log(`
2090
2090
  ${l.bold}${l.cyan}${h}.md${l.reset}
2091
- `),console.log(m.content),!0):(console.log(`${l.red}Document not found: ${h}${l.reset}`),!0)}case"remove":{if(!h)return console.log(`${l.red}Usage: /brain remove <name>${l.reset}`),!0;let{confirm:m}=un();if(!await m(`Remove brain document "${h}"?`))return console.log(`${l.dim}Cancelled${l.reset}`),!0;let $=a(h);return console.log($?`${l.green}Removed: ${h}.md${l.reset}`:`${l.red}Document not found: ${h}${l.reset}`),!0}case"rebuild":{let m=c(),g=Object.keys(m.documents).length;return console.log(`${l.green}Index rebuilt: ${g} document(s)${l.reset}`),!0}case"embed":{if(!await d())return console.log(`${l.yellow}Ollama embedding model not available.${l.reset}`),console.log(`${l.dim}Set NEX_EMBED_MODEL env var (default: nomic-embed-text) and ensure Ollama is running.${l.reset}`),!0;console.log(`${l.dim}Building embedding index...${l.reset}`);try{let g=await u(),$=Object.keys(g.documents||{}).length;console.log(`${l.green}Embedding index built: ${$} document(s)${l.reset}`)}catch(g){console.log(`${l.red}Embedding failed: ${g.message}${l.reset}`)}return!0}case"status":{let m=s(),g=require("fs"),$=require("path"),b=$.join(process.cwd(),".nex","brain",".brain-index.json"),x=$.join(process.cwd(),".nex","brain",".embeddings.json");if(console.log(`
2092
- ${l.bold}${l.cyan}Brain Status${l.reset}`),console.log(` Documents: ${m.length}`),console.log(` Index: ${g.existsSync(b)?l.green+"present"+l.reset:l.dim+"not built"+l.reset}`),console.log(` Embeddings: ${g.existsSync(x)?l.green+"present"+l.reset:l.dim+"not built (run /brain embed)"+l.reset}`),m.length>0){let _=m.reduce((E,S)=>E+S.size,0);console.log(` Total size: ${_<1024?_+"B":(_/1024).toFixed(1)+"K"}`)}return console.log(),!0}case"review":{let{exec:m}=require("child_process"),{promisify:g}=require("util"),$=g(m);try{let{stdout:b}=await $("git diff .nex/brain/",{cwd:process.cwd()});b.trim()?(console.log(`
2091
+ `),console.log(m.content),!0):(console.log(`${l.red}Document not found: ${h}${l.reset}`),!0)}case"remove":{if(!h)return console.log(`${l.red}Usage: /brain remove <name>${l.reset}`),!0;let{confirm:m}=un();if(!await m(`Remove brain document "${h}"?`))return console.log(`${l.dim}Cancelled${l.reset}`),!0;let y=a(h);return console.log(y?`${l.green}Removed: ${h}.md${l.reset}`:`${l.red}Document not found: ${h}${l.reset}`),!0}case"rebuild":{let m=c(),g=Object.keys(m.documents).length;return console.log(`${l.green}Index rebuilt: ${g} document(s)${l.reset}`),!0}case"embed":{if(!await d())return console.log(`${l.yellow}Ollama embedding model not available.${l.reset}`),console.log(`${l.dim}Set NEX_EMBED_MODEL env var (default: nomic-embed-text) and ensure Ollama is running.${l.reset}`),!0;console.log(`${l.dim}Building embedding index...${l.reset}`);try{let g=await u(),y=Object.keys(g.documents||{}).length;console.log(`${l.green}Embedding index built: ${y} document(s)${l.reset}`)}catch(g){console.log(`${l.red}Embedding failed: ${g.message}${l.reset}`)}return!0}case"status":{let m=s(),g=require("fs"),y=require("path"),b=y.join(process.cwd(),".nex","brain",".brain-index.json"),x=y.join(process.cwd(),".nex","brain",".embeddings.json");if(console.log(`
2092
+ ${l.bold}${l.cyan}Brain Status${l.reset}`),console.log(` Documents: ${m.length}`),console.log(` Index: ${g.existsSync(b)?l.green+"present"+l.reset:l.dim+"not built"+l.reset}`),console.log(` Embeddings: ${g.existsSync(x)?l.green+"present"+l.reset:l.dim+"not built (run /brain embed)"+l.reset}`),m.length>0){let _=m.reduce((E,S)=>E+S.size,0);console.log(` Total size: ${_<1024?_+"B":(_/1024).toFixed(1)+"K"}`)}return console.log(),!0}case"review":{let{exec:m}=require("child_process"),{promisify:g}=require("util"),y=g(m);try{let{stdout:b}=await y("git diff .nex/brain/",{cwd:process.cwd()});b.trim()?(console.log(`
2093
2093
  ${l.bold}${l.cyan}Brain Changes (git diff):${l.reset}
2094
- `),console.log(b)):console.log(`${l.dim}No pending brain changes (clean git state)${l.reset}`)}catch{console.log(`${l.dim}Not a git repo or no brain dir${l.reset}`)}return!0}case"undo":{let m=require("fs"),$=require("path").join(process.cwd(),".nex","brain");if(!m.existsSync($))return console.log(`${l.dim}No brain directory found${l.reset}`),!0;let b=s();if(b.length===0)return console.log(`${l.dim}No brain documents to undo${l.reset}`),!0;let x=b[0],{exec:_}=require("child_process"),{promisify:E}=require("util"),S=E(_);try{await S(`git checkout -- ".nex/brain/${x.name}.md"`,{cwd:process.cwd()}),c(),console.log(`${l.green}Undone: restored ${x.name}.md from git${l.reset}`)}catch{console.log(`${l.red}Could not undo \u2014 not tracked in git or no prior version${l.reset}`)}return!0}default:{let m=s();if(m.length===0)console.log(`
2094
+ `),console.log(b)):console.log(`${l.dim}No pending brain changes (clean git state)${l.reset}`)}catch{console.log(`${l.dim}Not a git repo or no brain dir${l.reset}`)}return!0}case"undo":{let m=require("fs"),y=require("path").join(process.cwd(),".nex","brain");if(!m.existsSync(y))return console.log(`${l.dim}No brain directory found${l.reset}`),!0;let b=s();if(b.length===0)return console.log(`${l.dim}No brain documents to undo${l.reset}`),!0;let x=b[0],{exec:_}=require("child_process"),{promisify:E}=require("util"),S=E(_);try{await S(`git checkout -- ".nex/brain/${x.name}.md"`,{cwd:process.cwd()}),c(),console.log(`${l.green}Undone: restored ${x.name}.md from git${l.reset}`)}catch{console.log(`${l.red}Could not undo \u2014 not tracked in git or no prior version${l.reset}`)}return!0}default:{let m=s();if(m.length===0)console.log(`
2095
2095
  ${l.bold}${l.cyan}Brain Knowledge Base${l.reset}`),console.log(`${l.dim}No documents yet. Create with /brain add <name>${l.reset}`),console.log(`
2096
2096
  ${l.dim}Commands: add \xB7 list \xB7 search \xB7 show \xB7 remove \xB7 rebuild \xB7 embed \xB7 status \xB7 review \xB7 undo${l.reset}
2097
2097
  `);else{console.log(`
2098
- ${l.bold}${l.cyan}Brain: ${m.length} document(s)${l.reset}`);for(let g of m){let{frontmatter:$}=r(g.name),b=Array.isArray($.tags)?` [${$.tags.join(", ")}]`:"";console.log(` ${l.cyan}${g.name}${l.reset}${l.dim}${b}${l.reset}`)}console.log(`
2098
+ ${l.bold}${l.cyan}Brain: ${m.length} document(s)${l.reset}`);for(let g of m){let{frontmatter:y}=r(g.name),b=Array.isArray(y.tags)?` [${y.tags.join(", ")}]`:"";console.log(` ${l.cyan}${g.name}${l.reset}${l.dim}${b}${l.reset}`)}console.log(`
2099
2099
  ${l.dim}Use /brain search <query> \xB7 /brain show <name> \xB7 /brain add <name>${l.reset}
2100
- `)}return!0}}}case"/learn":{let{learnFromSession:s,learnBrainFromSession:r}=gh(),{getConversationMessages:i}=We(),a=i(),c=a.filter(u=>u.role==="user").length;if(c<4)return console.log(`${l.yellow}Session too short to learn from (need 4+ user messages, have ${c})${l.reset}`),!0;console.log(`${l.dim}Analyzing session for learnings...${l.reset}`);try{let[u,d]=await Promise.all([s(a),r(a)]);if(u.skipped&&(!d.written||d.written.length===0))return console.log(`${l.dim}Session too short${l.reset}`),!0;u.error&&console.log(`${l.red}Reflection error: ${u.error}${l.reset}`),console.log(""),u.summary&&(console.log(`${l.bold}Session:${l.reset} ${l.dim}${u.summary}${l.reset}`),console.log(""));let f=u.applied&&u.applied.length>0,p=u.nexAdded&&u.nexAdded.length>0,h=d.written&&d.written.length>0;if(!f&&!p&&!h)console.log(`${l.dim}No new learnings extracted from this session${l.reset}`);else{if(f){console.log(`${l.bold}${l.cyan}Memory updates:${l.reset}`);for(let{key:m,value:g,action:$}of u.applied){let b=$==="updated"?`${l.yellow}~${l.reset}`:`${l.green}+${l.reset}`;console.log(` ${b} ${l.bold}${m}${l.reset} = ${g}`)}}if(p){console.log(`${l.bold}${l.cyan}Added to NEX.md:${l.reset}`);for(let m of u.nexAdded)console.log(` ${l.green}+${l.reset} ${m}`)}if(h){console.log(`${l.bold}${l.cyan}Brain documents:${l.reset}`);for(let{name:m,reason:g,action:$}of d.written){let b=$==="updated"?`${l.yellow}~${l.reset}`:`${l.green}+${l.reset}`;console.log(` ${b} ${l.bold}${m}.md${l.reset}${g?l.dim+" \u2014 "+g+l.reset:""}`)}}}console.log("")}catch(u){console.log(`${l.red}Learn failed: ${u.message}${l.reset}`)}return!0}case"/optimize":{let{getConversationMessages:s}=We(),{getUsage:r}=Mn(),{TOOL_DEFINITIONS:i}=rs(),{listMemories:a}=as(),c=s(),u=r(c,i),d=bs(),f=ro(),p=a();console.log(`
2100
+ `)}return!0}}}case"/learn":{let{learnFromSession:s,learnBrainFromSession:r}=gh(),{getConversationMessages:i}=We(),a=i(),c=a.filter(u=>u.role==="user").length;if(c<4)return console.log(`${l.yellow}Session too short to learn from (need 4+ user messages, have ${c})${l.reset}`),!0;console.log(`${l.dim}Analyzing session for learnings...${l.reset}`);try{let[u,d]=await Promise.all([s(a),r(a)]);if(u.skipped&&(!d.written||d.written.length===0))return console.log(`${l.dim}Session too short${l.reset}`),!0;u.error&&console.log(`${l.red}Reflection error: ${u.error}${l.reset}`),console.log(""),u.summary&&(console.log(`${l.bold}Session:${l.reset} ${l.dim}${u.summary}${l.reset}`),console.log(""));let f=u.applied&&u.applied.length>0,p=u.nexAdded&&u.nexAdded.length>0,h=d.written&&d.written.length>0;if(!f&&!p&&!h)console.log(`${l.dim}No new learnings extracted from this session${l.reset}`);else{if(f){console.log(`${l.bold}${l.cyan}Memory updates:${l.reset}`);for(let{key:m,value:g,action:y}of u.applied){let b=y==="updated"?`${l.yellow}~${l.reset}`:`${l.green}+${l.reset}`;console.log(` ${b} ${l.bold}${m}${l.reset} = ${g}`)}}if(p){console.log(`${l.bold}${l.cyan}Added to NEX.md:${l.reset}`);for(let m of u.nexAdded)console.log(` ${l.green}+${l.reset} ${m}`)}if(h){console.log(`${l.bold}${l.cyan}Brain documents:${l.reset}`);for(let{name:m,reason:g,action:y}of d.written){let b=y==="updated"?`${l.yellow}~${l.reset}`:`${l.green}+${l.reset}`;console.log(` ${b} ${l.bold}${m}.md${l.reset}${g?l.dim+" \u2014 "+g+l.reset:""}`)}}}console.log("")}catch(u){console.log(`${l.red}Learn failed: ${u.message}${l.reset}`)}return!0}case"/optimize":{let{getConversationMessages:s}=We(),{getUsage:r}=Mn(),{TOOL_DEFINITIONS:i}=rs(),{listMemories:a}=as(),c=s(),u=r(c,i),d=bs(),f=ro(),p=a();console.log(`
2101
2101
  ${l.bold}${l.cyan}Optimization Report${l.reset}
2102
2102
  `);let h=u.percentage>80?l.red:u.percentage>50?l.yellow:l.green;if(console.log(`${l.bold}Context Window:${l.reset} ${h}${u.percentage}%${l.reset} used (${u.used.toLocaleString()} / ${u.limit.toLocaleString()} tokens)`),u.percentage>75?console.log(` ${l.yellow}\u2192 Tip: Use /clear to free context (auto-learns first)${l.reset}`):u.percentage>50?console.log(` ${l.dim}\u2192 Context is filling up, consider /clear soon${l.reset}`):console.log(` ${l.green}\u2192 Context healthy${l.reset}`),console.log(`
2103
2103
  ${l.bold}Memory:${l.reset} ${p.length} entries`),p.length===0)console.log(` ${l.yellow}\u2192 No memories yet. Use /learn after sessions or /remember key=value${l.reset}`);else{let _=[...p].sort((O,L)=>new Date(L.updatedAt)-new Date(O.updatedAt))[0],E=_?Math.round((Date.now()-new Date(_.updatedAt))/6e4):null,S=E!==null?E<60?`${E}m ago`:`${Math.round(E/60)}h ago`:"?";console.log(` ${l.dim}Latest update: ${S}${l.reset}`),p.length>30&&console.log(` ${l.yellow}\u2192 Many memories (${p.length}) \u2014 consider pruning with /forget${l.reset}`)}console.log(`
2104
2104
  ${l.bold}Active Model:${l.reset} ${f}:${d.id}`);let m=d.contextWindow||d.maxTokens||0;m>0&&m<32e3&&c.length>10?console.log(` ${l.yellow}\u2192 Small context window (${(m/1e3).toFixed(0)}k). Consider /model for larger context${l.reset}`):m>=128e3&&console.log(` ${l.green}\u2192 Large context window (${(m/1e3).toFixed(0)}k) \u2014 good for long sessions${l.reset}`);let g=c.filter(x=>x.role==="user").length;console.log(`
2105
- ${l.bold}Session:${l.reset} ${g} turns, ${c.length} messages total`),g>=4&&g%10===0&&console.log(` ${l.cyan}\u2192 Good time to /learn and capture session insights${l.reset}`);let $=[],b=require("path").join(process.cwd(),"NEX.md");if(require("fs").existsSync(b)||$.push("Create NEX.md in project root to give nex-code project-specific instructions"),$.length>0){console.log(`
2106
- ${l.bold}Quick Wins:${l.reset}`);for(let x of $)console.log(` ${l.cyan}\u2192${l.reset} ${x}`)}return console.log(""),!0}case"/plan":{let{getActivePlan:s,approvePlan:r,startExecution:i,setPlanMode:a,getPlanContent:c,getPlanContent:u,formatPlan:d,extractStepsFromText:f,createPlan:p}=ps(),{invalidateSystemPromptCache:h}=We(),m=o.join(" ").trim();if(m==="status"){let g=s();return console.log(d(g)),!0}if(m==="edit"){let g=c();if(!g)return console.log(`${l.yellow}No plan to edit. Generate a plan first with /plan${l.reset}`),!0;let $=require("os"),b=require("path").join($.tmpdir(),`nex-plan-${Date.now()}.md`);require("fs").writeFileSync(b,g,"utf-8");let x=process.env.EDITOR||process.env.VISUAL||"nano",{spawnSync:_}=require("child_process");if(console.log(`${l.dim}Opening plan in ${x}... (save and close to update)${l.reset}`),_(x,[b],{stdio:"inherit"}).status===0){let{setPlanContent:S}=ps(),O=require("fs").readFileSync(b,"utf-8");S(O);let L=f(O);if(L.length>0){let D=s()?.task||"Task";p(D,L),console.log(`${l.green}Plan updated \u2014 ${L.length} steps extracted.${l.reset}`)}else console.log(`${l.green}Plan updated.${l.reset}`)}else console.log(`${l.yellow}Editor exited with error \u2014 plan unchanged.${l.reset}`);try{require("fs").unlinkSync(b)}catch{}return!0}if(m==="approve"){let g=c();if(r()){i(),a(!1),nc(),h();let b=s()?.steps?.length||0,x=b>0?` (${b} steps)`:"";if(console.log(`${l.green}${l.bold}Plan approved!${l.reset}${x} Executing...`),console.log(`${l.dim}Plan mode disabled \u2014 all tools now available.${l.reset}`),g){let{processInput:_}=We(),E=`[PLAN APPROVED \u2014 EXECUTE NOW]
2105
+ ${l.bold}Session:${l.reset} ${g} turns, ${c.length} messages total`),g>=4&&g%10===0&&console.log(` ${l.cyan}\u2192 Good time to /learn and capture session insights${l.reset}`);let y=[],b=require("path").join(process.cwd(),"NEX.md");if(require("fs").existsSync(b)||y.push("Create NEX.md in project root to give nex-code project-specific instructions"),y.length>0){console.log(`
2106
+ ${l.bold}Quick Wins:${l.reset}`);for(let x of y)console.log(` ${l.cyan}\u2192${l.reset} ${x}`)}return console.log(""),!0}case"/plan":{let{getActivePlan:s,approvePlan:r,startExecution:i,setPlanMode:a,getPlanContent:c,getPlanContent:u,formatPlan:d,extractStepsFromText:f,createPlan:p}=ps(),{invalidateSystemPromptCache:h}=We(),m=o.join(" ").trim();if(m==="status"){let g=s();return console.log(d(g)),!0}if(m==="edit"){let g=c();if(!g)return console.log(`${l.yellow}No plan to edit. Generate a plan first with /plan${l.reset}`),!0;let y=require("os"),b=require("path").join(y.tmpdir(),`nex-plan-${Date.now()}.md`);require("fs").writeFileSync(b,g,"utf-8");let x=process.env.EDITOR||process.env.VISUAL||"nano",{spawnSync:_}=require("child_process");if(console.log(`${l.dim}Opening plan in ${x}... (save and close to update)${l.reset}`),_(x,[b],{stdio:"inherit"}).status===0){let{setPlanContent:S}=ps(),O=require("fs").readFileSync(b,"utf-8");S(O);let L=f(O);if(L.length>0){let D=s()?.task||"Task";p(D,L),console.log(`${l.green}Plan updated \u2014 ${L.length} steps extracted.${l.reset}`)}else console.log(`${l.green}Plan updated.${l.reset}`)}else console.log(`${l.yellow}Editor exited with error \u2014 plan unchanged.${l.reset}`);try{require("fs").unlinkSync(b)}catch{}return!0}if(m==="approve"){let g=c();if(r()){i(),a(!1),nc(),h();let b=s()?.steps?.length||0,x=b>0?` (${b} steps)`:"";if(console.log(`${l.green}${l.bold}Plan approved!${l.reset}${x} Executing...`),console.log(`${l.dim}Plan mode disabled \u2014 all tools now available.${l.reset}`),g){let{processInput:_}=We(),E=`[PLAN APPROVED \u2014 EXECUTE NOW]
2107
2107
 
2108
2108
  Implement the following plan step by step. All tools are now available.
2109
2109
 
@@ -2190,7 +2190,7 @@ ${l.bold}${l.cyan}Kubernetes Overview${l.reset}${c?l.dim+" (remote: "+c+")"+l.re
2190
2190
  `).filter(Boolean);console.log(`${l.bold}Namespaces (${p.length}):${l.reset}`);for(let h of p)console.log(` ${l.cyan}${h}${l.reset}`);console.log()}catch{return console.log(`${l.dim}Could not reach cluster \u2014 is kubectl configured?${l.reset}
2191
2191
  `),!0}try{let{stdout:f}=await a(d("kubectl get pods -A --no-headers -o custom-columns=NS:.metadata.namespace,NAME:.metadata.name,READY:.status.containerStatuses[0].ready,STATUS:.status.phase,RESTARTS:.status.containerStatuses[0].restartCount"),{timeout:2e4}),p=f.trim().split(`
2192
2192
  `).filter(Boolean),h=p.filter(b=>b.includes("Running")).length,m=p.filter(b=>b.includes("Pending")).length,g=p.filter(b=>b.includes("Failed")||b.includes("Error")||b.includes("CrashLoop")).length;console.log(`${l.bold}Pods: ${p.length} total ${l.green}${h} running${l.reset} ${l.yellow}${m} pending${l.reset} ${l.red}${g} unhealthy${l.reset}
2193
- `);let $=p.filter(b=>!b.includes("Running")&&!b.includes("<none>"));if($.length>0){console.log(`${l.bold}${l.red}Unhealthy Pods:${l.reset}`);for(let b of $)console.log(` ${l.red}${b}${l.reset}`);console.log()}console.log(`${l.dim}Use k8s_pods / k8s_logs / k8s_exec tools for details${l.reset}`),console.log(`${l.dim}Or: /k8s user@host to query a remote cluster${l.reset}
2193
+ `);let y=p.filter(b=>!b.includes("Running")&&!b.includes("<none>"));if(y.length>0){console.log(`${l.bold}${l.red}Unhealthy Pods:${l.reset}`);for(let b of y)console.log(` ${l.red}${b}${l.reset}`);console.log()}console.log(`${l.dim}Use k8s_pods / k8s_logs / k8s_exec tools for details${l.reset}`),console.log(`${l.dim}Or: /k8s user@host to query a remote cluster${l.reset}
2194
2194
  `)}catch(f){console.log(`${l.dim}Could not list pods: ${f.message}${l.reset}
2195
2195
  `)}return!0}case"/servers":{let{loadServerProfiles:s,resolveProfile:r,sshExec:i}=Ks(),a=s(),c=Object.keys(a);if(c.length===0)return console.log(`
2196
2196
  ${l.dim}No servers configured. Create .nex/servers.json:${l.reset}`),console.log(`${l.dim} { "prod": { "host": "1.2.3.4", "user": "deploy", "os": "almalinux9" } }${l.reset}
@@ -2199,64 +2199,64 @@ ${l.bold}${l.cyan}Server connectivity:${l.reset}`),await Promise.all(f.map(async
2199
2199
  ${l.bold}${l.cyan}Configured servers (${c.length}):${l.reset}`);for(let f of c)console.log(` ${l.green}${f}${l.reset} ${l.dim}${d(f,a[f])}${l.reset}`);return console.log(`
2200
2200
  ${l.dim}/servers ping \u2014 check SSH connectivity for all servers${l.reset}`),console.log(`${l.dim}/servers ping <name> \u2014 check a specific server${l.reset}
2201
2201
  `),!0}case"/docker":{let{loadServerProfiles:s,sshExec:r}=Ks(),{exec:i}=require("child_process"),{promisify:a}=require("util"),c=a(i),u=o[0]==="-a"||o[0]==="--all"?'docker ps -a --format "table {{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}"':'docker ps --format "table {{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}"',d=s(),f=[["local",null],...Object.entries(d)];console.log(`
2202
- ${l.bold}${l.cyan}Docker Containers:${l.reset}`);for(let[p,h]of f){let m=p==="local"?`${l.dim}local${l.reset}`:`${l.cyan}${p}${l.reset}`;try{let g;if(p==="local"){let{stdout:$}=await c(u,{timeout:8e3});g=($||"").trim()}else{let $=await r(h,u,{timeout:1e4});if(g=[$.stdout,$.stderr].filter(Boolean).join("").trim(),$.exitCode!==0){console.log(` ${m}: ${l.red}SSH error (${$.exitCode})${l.reset}`);continue}}!g||g==="NAMES IMAGE STATUS PORTS"?console.log(` ${m}: ${l.dim}(no containers)${l.reset}`):(console.log(` ${m}:`),g.split(`
2203
- `).forEach($=>console.log(` ${l.dim}${$}${l.reset}`)))}catch(g){console.log(` ${m}: ${l.red}${g.message}${l.reset}`)}}return console.log(""),!0}case"/deploy":{let{loadDeployConfigs:s}=rf(),r=s(),i=Object.keys(r),a=o[0];if(a&&i.includes(a)){let c=o.includes("--dry-run")||o.includes("-n"),u=r[a],{executeTool:d}=rs();console.log(`
2202
+ ${l.bold}${l.cyan}Docker Containers:${l.reset}`);for(let[p,h]of f){let m=p==="local"?`${l.dim}local${l.reset}`:`${l.cyan}${p}${l.reset}`;try{let g;if(p==="local"){let{stdout:y}=await c(u,{timeout:8e3});g=(y||"").trim()}else{let y=await r(h,u,{timeout:1e4});if(g=[y.stdout,y.stderr].filter(Boolean).join("").trim(),y.exitCode!==0){console.log(` ${m}: ${l.red}SSH error (${y.exitCode})${l.reset}`);continue}}!g||g==="NAMES IMAGE STATUS PORTS"?console.log(` ${m}: ${l.dim}(no containers)${l.reset}`):(console.log(` ${m}:`),g.split(`
2203
+ `).forEach(y=>console.log(` ${l.dim}${y}${l.reset}`)))}catch(g){console.log(` ${m}: ${l.red}${g.message}${l.reset}`)}}return console.log(""),!0}case"/deploy":{let{loadDeployConfigs:s}=rf(),r=s(),i=Object.keys(r),a=o[0];if(a&&i.includes(a)){let c=o.includes("--dry-run")||o.includes("-n"),u=r[a],{executeTool:d}=rs();console.log(`
2204
2204
  ${l.bold}Running deploy: ${a}${c?" (dry run)":""}${l.reset}`);let f=await d("deploy",{...u,dry_run:c});return console.log(f),!0}if(i.length===0)return console.log(`
2205
2205
  ${l.dim}No deploy configs. Run /init to create .nex/deploy.json${l.reset}
2206
2206
  `),!0;console.log(`
2207
2207
  ${l.bold}${l.cyan}Deploy configs (${i.length}):${l.reset}`);for(let[c,u]of Object.entries(r)){let d=u.method||"rsync",f=`[${d}]`,p=d==="git"?`${u.server}:${u.remote_path}${u.branch?` (${u.branch})`:""}`:`${u.local_path||""} \u2192 ${u.server}:${u.remote_path}`,h=[u.deploy_script?`script: ${u.deploy_script}`:null,u.health_check?`health: ${u.health_check}`:null].filter(Boolean).map(m=>` ${l.dim}\u2192 ${m}${l.reset}`).join("");console.log(` ${l.green}${c}${l.reset} ${l.dim}${f} ${p}${l.reset}${h}`)}return console.log(`
2208
2208
  ${l.dim}/deploy <name> \u2014 run a named deploy${l.reset}`),console.log(`${l.dim}/deploy <name> --dry-run \u2014 preview without syncing${l.reset}
2209
- `),!0}case"/init":{let{runServerWizard:s,runDeployWizard:r,setWizardRL:i}=Wk();return i(t),o[0]==="deploy"?await r():await s(),!0}case"/setup":{let{runSetupWizard:s}=uh();return await s({rl:t,force:!0}),!0}case"/benchmark":{try{let $=require("path").join(require("os").homedir(),".nex-code","benchmark-results.json");if(en.existsSync($)){let b=(Date.now()-en.statSync($).mtimeMs)/864e5;b>30&&console.log(`${l.dim} \u2139 Benchmark results are ${Math.floor(b)} days old \u2014 run /benchmark --all to refresh${l.reset}
2210
- `)}}catch{}if(o.includes("--history")){let $=require("os"),b=process.env.NEX_BENCHMARK_HISTORY_DIR||zt.join($.homedir(),"Coding","nex-code-benchmarks","results");if(!en.existsSync(b)){console.log(`${l.yellow}No nightly results at ${b}${l.reset}`),console.log(`${l.dim}Use /benchmark (no flags) to run a live model comparison.${l.reset}`);break}let x=en.readdirSync(b).filter(E=>E.endsWith(".json")).sort().slice(-7);if(x.length===0){console.log(`${l.yellow}No result files found${l.reset}`);break}console.log(`
2209
+ `),!0}case"/init":{let{runServerWizard:s,runDeployWizard:r,setWizardRL:i}=Wk();return i(t),o[0]==="deploy"?await r():await s(),!0}case"/setup":{let{runSetupWizard:s}=uh();return await s({rl:t,force:!0}),!0}case"/benchmark":{try{let y=require("path").join(require("os").homedir(),".nex-code","benchmark-results.json");if(en.existsSync(y)){let b=(Date.now()-en.statSync(y).mtimeMs)/864e5;b>30&&console.log(`${l.dim} \u2139 Benchmark results are ${Math.floor(b)} days old \u2014 run /benchmark --all to refresh${l.reset}
2210
+ `)}}catch{}if(o.includes("--history")){let y=require("os"),b=process.env.NEX_BENCHMARK_HISTORY_DIR||zt.join(y.homedir(),"Coding","nex-code-benchmarks","results");if(!en.existsSync(b)){console.log(`${l.yellow}No nightly results at ${b}${l.reset}`),console.log(`${l.dim}Use /benchmark (no flags) to run a live model comparison.${l.reset}`);break}let x=en.readdirSync(b).filter(E=>E.endsWith(".json")).sort().slice(-7);if(x.length===0){console.log(`${l.yellow}No result files found${l.reset}`);break}console.log(`
2211
2211
  ${l.bold}${l.cyan}OpenClaw Nightly Results (${x.length}-day trend)${l.reset}
2212
2212
  `),console.log(` ${l.dim}${"Date".padEnd(12)} ${"Model".padEnd(25)} ${"Score".padEnd(8)} ${"Pass".padEnd(8)}${l.reset}`),console.log(` ${l.dim}${"\u2500".repeat(58)}${l.reset}`);let _=[];for(let E of x)try{let S=JSON.parse(en.readFileSync(zt.join(b,E),"utf-8")),O=E.replace(".json",""),L=S.tasks?.length||S.total||0,I=S.tasks?.filter(X=>X.passed||X.score>=.7)?.length||S.passed||0,D=S.score??S.overall_score??(L>0?Math.round(I/L*100):"N/A"),Z=S.model||S.config?.model||"unknown";_.push({date:O,model:Z,total:L,passed:I,score:D});let K=typeof D=="number"?D>=80?l.green:D>=60?l.yellow:l.red:l.dim;console.log(` ${O.padEnd(12)} ${Z.substring(0,24).padEnd(25)} ${K}${String(D).padEnd(8)}${l.reset} ${I}/${L}`)}catch{}if(_.length>=2){let E=_[0].score,S=_[_.length-1].score;if(typeof E=="number"&&typeof S=="number"){let O=S-E,L=O>0?`${l.green}\u25B2 +${O}`:O<0?`${l.red}\u25BC ${O}`:`${l.dim}\u2192 stable`;console.log(`
2213
- ${l.bold}Trend:${l.reset} ${L}${l.reset} over ${_.length} days`)}}console.log();break}if(o.includes("--all")){let{fetchCloudModels:$,markBenchmarked:b,updateReadme:x,updateModelsEnv:_,updateRoutingConfig:E}=xi(),{runBenchmark:S,buildCategoryWinners:O}=Ao(),L=new Set(["nemotron-3-super:cloud"]),I=o.find(ne=>ne.startsWith("--parallel=")),D=I?Math.max(1,parseInt(I.replace("--parallel=",""),10)||3):3;console.log(`
2214
- ${l.bold}Fetching all available Ollama Cloud models...${l.reset}`);let Z;try{Z=await $()}catch(ne){console.log(`${l.red}Failed to fetch model list: ${ne.message}${l.reset}`);break}let K=Z.filter(ne=>!L.has(ne)),X=Z.filter(ne=>L.has(ne)),Fe=56,Oe=Math.ceil(Fe*K.length*4/D/60);console.log(`${l.cyan}${K.length} models found${l.reset}`+(X.length>0?` ${l.dim}(${X.length} blacklisted: ${X.join(", ")})${l.reset}`:"")),console.log(`${l.dim}Models: ${K.join(", ")}${l.reset}`),console.log(`${l.dim}${Fe} tasks \xB7 ${D} parallel \xB7 ~${Oe}min estimated${l.reset}
2213
+ ${l.bold}Trend:${l.reset} ${L}${l.reset} over ${_.length} days`)}}console.log();break}if(o.includes("--all")){let{fetchCloudModels:y,markBenchmarked:b,updateReadme:x,updateModelsEnv:_,updateRoutingConfig:E}=xi(),{runBenchmark:S,buildCategoryWinners:O}=Ao(),L=new Set(["nemotron-3-super:cloud"]),I=o.find(ne=>ne.startsWith("--parallel=")),D=I?Math.max(1,parseInt(I.replace("--parallel=",""),10)||3):3;console.log(`
2214
+ ${l.bold}Fetching all available Ollama Cloud models...${l.reset}`);let Z;try{Z=await y()}catch(ne){console.log(`${l.red}Failed to fetch model list: ${ne.message}${l.reset}`);break}let K=Z.filter(ne=>!L.has(ne)),X=Z.filter(ne=>L.has(ne)),Fe=56,Oe=Math.ceil(Fe*K.length*4/D/60);console.log(`${l.cyan}${K.length} models found${l.reset}`+(X.length>0?` ${l.dim}(${X.length} blacklisted: ${X.join(", ")})${l.reset}`:"")),console.log(`${l.dim}Models: ${K.join(", ")}${l.reset}`),console.log(`${l.dim}${Fe} tasks \xB7 ${D} parallel \xB7 ~${Oe}min estimated${l.reset}
2215
2215
  `);let V=new Map,re=await S({models:K,quick:!1,parallelModels:D,onProgress:({model:ne,task:te,done:M,score:ye,error:Qe})=>{if(!M){V.has(ne)||(V.set(ne,""),process.stdout.write(`
2216
2216
  ${l.cyan}${ne.padEnd(30)}${l.reset} `));return}let G=Qe?`${l.red}\u2717${l.reset}`:ye>=80?`${l.green}\xB7${l.reset}`:ye>=40?`${l.yellow}\xB7${l.reset}`:`${l.red}\xB7${l.reset}`;process.stdout.write(G)}});process.stdout.write(`
2217
- `);let rt=require("os"),qe=require("path").join(rt.homedir(),".nex-code","benchmark-results.json");try{require("fs").writeFileSync(qe,JSON.stringify(re,null,2))}catch{}b(K);let _e=O(re),Me=E(_e),R=require("path").join(process.cwd(),"README.md"),v=x(re,R),z=_(re);if(v&&console.log(`
2218
- ${l.green}README.md benchmark table updated${l.reset}`),z.updated&&console.log(`${l.green}DEFAULT_MODEL: ${z.previousModel} \u2192 ${z.newModel}${l.reset}`),Me.changes.length>0){console.log(`${l.green}Routing updated:${l.reset}`);for(let ne of Me.changes)console.log(` ${l.dim}${ne}${l.reset}`)}return console.log(),!0}if(o.includes("--discover")){let{findNewModels:$,markBenchmarked:b,updateReadme:x,updateModelsEnv:_}=xi(),{runDiscoverBenchmark:E,buildSummary:S}=Ao();console.log(`
2219
- ${l.bold}Checking Ollama Cloud for new models...${l.reset}`);let O;try{O=await $()}catch(R){console.log(`${l.red}Discovery failed: ${R.message}${l.reset}`);break}let{newModels:L,allCloud:I}=O;if(console.log(`${l.dim}${I.length} models available on cloud${l.reset}`),L.length===0){console.log(`${l.green}No new models since last benchmark run.${l.reset}
2217
+ `);let rt=require("os"),qe=require("path").join(rt.homedir(),".nex-code","benchmark-results.json");try{require("fs").writeFileSync(qe,JSON.stringify(re,null,2))}catch{}b(K);let ke=O(re),Me=E(ke),R=require("path").join(process.cwd(),"README.md"),v=x(re,R),z=_(re);if(v&&console.log(`
2218
+ ${l.green}README.md benchmark table updated${l.reset}`),z.updated&&console.log(`${l.green}DEFAULT_MODEL: ${z.previousModel} \u2192 ${z.newModel}${l.reset}`),Me.changes.length>0){console.log(`${l.green}Routing updated:${l.reset}`);for(let ne of Me.changes)console.log(` ${l.dim}${ne}${l.reset}`)}return console.log(),!0}if(o.includes("--discover")){let{findNewModels:y,markBenchmarked:b,updateReadme:x,updateModelsEnv:_}=xi(),{runDiscoverBenchmark:E,buildSummary:S}=Ao();console.log(`
2219
+ ${l.bold}Checking Ollama Cloud for new models...${l.reset}`);let O;try{O=await y()}catch(R){console.log(`${l.red}Discovery failed: ${R.message}${l.reset}`);break}let{newModels:L,allCloud:I}=O;if(console.log(`${l.dim}${I.length} models available on cloud${l.reset}`),L.length===0){console.log(`${l.green}No new models since last benchmark run.${l.reset}
2220
2220
  `);break}console.log(`${l.cyan}New models to benchmark (${L.length}):${l.reset} ${L.join(", ")}
2221
2221
  `);let D=require("os"),Z=zt.join(D.homedir(),".nex-code","benchmark-results.json"),K=[];try{en.existsSync(Z)&&(K=JSON.parse(en.readFileSync(Z,"utf-8")))}catch{}let X="",Fe=await E({newModels:L,existingRanking:K,onProgress:({model:R,task:v,done:z,score:ne,error:te})=>{if(!z){R!==X&&(X&&process.stdout.write(`
2222
2222
  `),X=R,process.stdout.write(`${l.cyan}${R}${l.reset} `));return}let M=te?`${l.red}\u2717${l.reset}`:ne>=80?`${l.green}\xB7${l.reset}`:ne>=40?`${l.yellow}\xB7${l.reset}`:`${l.red}\xB7${l.reset}`;process.stdout.write(M)}});X&&process.stdout.write(`
2223
- `);try{en.writeFileSync(Z,JSON.stringify(Fe,null,2))}catch{}b(I);let Oe=zt.join(process.cwd(),"README.md"),V=x(Fe,Oe),re=_(Fe),{buildCategoryWinners:rt}=Ao(),{updateRoutingConfig:qe}=xi(),_e=rt(Fe),Me=qe(_e);if(V&&console.log(`${l.green}README.md benchmark table updated${l.reset}`),re.updated?console.log(`${l.green}DEFAULT_MODEL: ${re.previousModel} \u2192 ${re.newModel}${l.reset}`):re.reason&&console.log(`${l.dim}models.env unchanged: ${re.reason}${l.reset}`),Me.changes.length>0){console.log(`${l.green}Routing updated:${l.reset}`);for(let R of Me.changes)console.log(` ${l.dim}${R}${l.reset}`)}return console.log(),!0}let{runBenchmark:s,DEFAULT_MODELS:r,QUICK_MODELS:i}=Ao(),a=o.includes("--quick"),c=o.find($=>$.startsWith("--models=")),u=c?c.replace("--models=","").split(",").map($=>$.trim()).filter(Boolean):[],d=a?7:15,f=u.length>0?u:a?i:r;console.log(`
2223
+ `);try{en.writeFileSync(Z,JSON.stringify(Fe,null,2))}catch{}b(I);let Oe=zt.join(process.cwd(),"README.md"),V=x(Fe,Oe),re=_(Fe),{buildCategoryWinners:rt}=Ao(),{updateRoutingConfig:qe}=xi(),ke=rt(Fe),Me=qe(ke);if(V&&console.log(`${l.green}README.md benchmark table updated${l.reset}`),re.updated?console.log(`${l.green}DEFAULT_MODEL: ${re.previousModel} \u2192 ${re.newModel}${l.reset}`):re.reason&&console.log(`${l.dim}models.env unchanged: ${re.reason}${l.reset}`),Me.changes.length>0){console.log(`${l.green}Routing updated:${l.reset}`);for(let R of Me.changes)console.log(` ${l.dim}${R}${l.reset}`)}return console.log(),!0}let{runBenchmark:s,DEFAULT_MODELS:r,QUICK_MODELS:i}=Ao(),a=o.includes("--quick"),c=o.find(y=>y.startsWith("--models=")),u=c?c.replace("--models=","").split(",").map(y=>y.trim()).filter(Boolean):[],d=a?7:15,f=u.length>0?u:a?i:r;console.log(`
2224
2224
  ${l.bold}Starting benchmark${l.reset} ${l.dim}${d} tasks \xB7 ${f.length} models \xB7 ollama cloud${l.reset}`),console.log(`${l.dim}Models: ${f.join(", ")}${l.reset}
2225
- `);let p="",h=0,m=d*f.length,g=await s({models:f,quick:a,onProgress:({model:$,task:b,done:x,score:_,error:E})=>{if(!x){$!==p&&(p&&process.stdout.write(`
2226
- `),p=$,process.stdout.write(`${l.cyan}${$}${l.reset} `));return}h++;let S=E?`${l.red}\u2717${l.reset}`:_>=80?`${l.green}\xB7${l.reset}`:_>=40?`${l.yellow}\xB7${l.reset}`:`${l.red}\xB7${l.reset}`;process.stdout.write(S)}});if(p&&process.stdout.write(`
2227
- `),!a&&g&&g.length>0){let{buildCategoryWinners:$}=Ao(),{updateRoutingConfig:b,updateReadme:x,updateModelsEnv:_}=xi(),E=$(g),S=b(E);if(S.changes.length>0){console.log(`
2225
+ `);let p="",h=0,m=d*f.length,g=await s({models:f,quick:a,onProgress:({model:y,task:b,done:x,score:_,error:E})=>{if(!x){y!==p&&(p&&process.stdout.write(`
2226
+ `),p=y,process.stdout.write(`${l.cyan}${y}${l.reset} `));return}h++;let S=E?`${l.red}\u2717${l.reset}`:_>=80?`${l.green}\xB7${l.reset}`:_>=40?`${l.yellow}\xB7${l.reset}`:`${l.red}\xB7${l.reset}`;process.stdout.write(S)}});if(p&&process.stdout.write(`
2227
+ `),!a&&g&&g.length>0){let{buildCategoryWinners:y}=Ao(),{updateRoutingConfig:b,updateReadme:x,updateModelsEnv:_}=xi(),E=y(g),S=b(E);if(S.changes.length>0){console.log(`
2228
2228
  ${l.bold}Per-category routing saved:${l.reset}`);for(let D of S.changes)console.log(` ${l.dim}${D}${l.reset}`)}let O=zt.join(process.cwd(),"README.md");x(g,O)&&console.log(`${l.green}README.md updated${l.reset}`),_(g);let L=require("os"),I=zt.join(L.homedir(),".nex-code","benchmark-results.json");try{en.writeFileSync(I,JSON.stringify(g,null,2))}catch{}}return!0}case"/bench":{let{runScenarioBenchmark:s}=Ao(),r=o.includes("--dry-run"),i=o.find(c=>c.startsWith("--model=")),a=i?i.replace("--model=","").trim():void 0;return r||console.log(`
2229
2229
  ${l.bold}Scenario Benchmark${l.reset} ${l.dim}5 agentic scenarios \xB7 each run as child process${l.reset}
2230
2230
  `),await s({dryRun:r,model:a,cwd:an,onProgress:({id:c,name:u,done:d,score:f,grade:p})=>{if(!d)process.stdout.write(`${l.dim} \u2192 ${u}...${l.reset}`);else{let h=f>=8?l.green:f>=6?l.yellow:l.red;process.stdout.write(` ${h}${f}/10 (${p})${l.reset}
2231
2231
  `)}}}),!0}case"/trend":{let{showScoreTrend:s}=Ao(),r=parseInt(o[0],10)||10;return s(r),!0}case"/harness-optimization":{let{buildOptimizationReport:s,readHistory:r,readLatestResult:i,readLatestProblematicResult:a,verifyHarnessOptimization:c}=mx(),u=o.indexOf("--last"),d=u!==-1?Math.max(1,parseInt(o[u+1],10)||5):5,f=o.includes("--prompt"),p=r(an),h=i(an),m=s({latestRun:h,history:p,lastN:d,includePrompt:f});if(console.log(m),o.includes("--verify")){let g=a(an);console.log(`${l.dim}Running focused tests and a priority benchmark slice...${l.reset}
2232
- `),g?.runId&&g.runId!==h?.runId&&console.log(`${l.dim}Using latest problematic run for verification: ${g.runId}${l.reset}`);let $=-1,b=await c({rootDir:an,latestRun:g,onProgress(x){let _=Math.max(0,Math.min(100,Math.round(x.percent||0)));_===$&&x.phase!=="done"||($=_,console.log(`${l.dim}${String(_).padStart(3)}%${l.reset} ${x.message}`))}});console.log(b.summary)}return console.log(""),!0}case"/orchestrate":{let s=o.join(" ").trim();if(!s)return console.log(`${l.yellow}Usage: /orchestrate <prompt>${l.reset}`),console.log(`${l.dim}Example: /orchestrate fix login bug, update docs, add dark mode${l.reset}`),!0;let{runOrchestrated:r}=ya();return await r(s),!0}case"/bench-orchestrator":{let{runOrchestratorBenchmark:s,printResults:r}=vx(),i=o.find(u=>u.startsWith("--models=")),a=i?i.replace("--models=","").split(",").map(u=>u.trim()):void 0,c=await s({models:a,onProgress:({model:u,scenario:d,done:f,score:p,error:h})=>{f?h?process.stdout.write(` ${l.red}ERR${l.reset}
2232
+ `),g?.runId&&g.runId!==h?.runId&&console.log(`${l.dim}Using latest problematic run for verification: ${g.runId}${l.reset}`);let y=-1,b=await c({rootDir:an,latestRun:g,onProgress(x){let _=Math.max(0,Math.min(100,Math.round(x.percent||0)));_===y&&x.phase!=="done"||(y=_,console.log(`${l.dim}${String(_).padStart(3)}%${l.reset} ${x.message}`))}});console.log(b.summary)}return console.log(""),!0}case"/orchestrate":{let s=o.join(" ").trim();if(!s)return console.log(`${l.yellow}Usage: /orchestrate <prompt>${l.reset}`),console.log(`${l.dim}Example: /orchestrate fix login bug, update docs, add dark mode${l.reset}`),!0;let{runOrchestrated:r}=ya();return await r(s),!0}case"/bench-orchestrator":{let{runOrchestratorBenchmark:s,printResults:r}=vx(),i=o.find(u=>u.startsWith("--models=")),a=i?i.replace("--models=","").split(",").map(u=>u.trim()):void 0,c=await s({models:a,onProgress:({model:u,scenario:d,done:f,score:p,error:h})=>{f?h?process.stdout.write(` ${l.red}ERR${l.reset}
2233
2233
  `):process.stdout.write(` ${l.green}${p}/10${l.reset}
2234
- `):process.stdout.write(`${l.dim} \u2192 ${u}: ${d}...${l.reset}`)}});return r(c),!0}case"/exit":case"/quit":process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J"),process.exit(0);default:{let s=Yj(e);if(s)return s.agentPrompt&&(oc._pendingAgentPrompt=s.agentPrompt),!0;{let r=[...rc,...Fu()].map(u=>u.cmd.split(" ")[0]),i=(u,d)=>{let f=u.length,p=d.length,h=Array.from({length:f+1},(m,g)=>Array.from({length:p+1},($,b)=>g===0?b:b===0?g:0));for(let m=1;m<=f;m++)for(let g=1;g<=p;g++)h[m][g]=u[m-1]===d[g-1]?h[m-1][g-1]:1+Math.min(h[m-1][g],h[m][g-1],h[m-1][g-1]);return h[f][p]},a=null,c=3;for(let u of r){let d=i(n,u);d<c&&(c=d,a=u)}console.log(a?`${l.red}Unknown command: ${n}.${l.reset} ${l.dim}Did you mean ${l.reset}${l.cyan}${a}${l.reset}${l.dim}? Type /help for all commands.${l.reset}`:`${l.red}Unknown command: ${n}. Type /help${l.reset}`)}return!0}}}var Bh=1e3;function Uh(){return zt.join(process.cwd(),".nex","repl_history")}function Hx(){try{let e=Uh();if(en.existsSync(e))return en.readFileSync(e,"utf-8").split(`
2234
+ `):process.stdout.write(`${l.dim} \u2192 ${u}: ${d}...${l.reset}`)}});return r(c),!0}case"/exit":case"/quit":process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J"),process.exit(0);default:{let s=Yj(e);if(s)return s.agentPrompt&&(oc._pendingAgentPrompt=s.agentPrompt),!0;{let r=[...rc,...Fu()].map(u=>u.cmd.split(" ")[0]),i=(u,d)=>{let f=u.length,p=d.length,h=Array.from({length:f+1},(m,g)=>Array.from({length:p+1},(y,b)=>g===0?b:b===0?g:0));for(let m=1;m<=f;m++)for(let g=1;g<=p;g++)h[m][g]=u[m-1]===d[g-1]?h[m-1][g-1]:1+Math.min(h[m-1][g],h[m][g-1],h[m-1][g-1]);return h[f][p]},a=null,c=3;for(let u of r){let d=i(n,u);d<c&&(c=d,a=u)}console.log(a?`${l.red}Unknown command: ${n}.${l.reset} ${l.dim}Did you mean ${l.reset}${l.cyan}${a}${l.reset}${l.dim}? Type /help for all commands.${l.reset}`:`${l.red}Unknown command: ${n}. Type /help${l.reset}`)}return!0}}}var Bh=1e3;function Uh(){return zt.join(process.cwd(),".nex","repl_history")}function Hx(){try{let e=Uh();if(en.existsSync(e))return en.readFileSync(e,"utf-8").split(`
2235
2235
  `).filter(Boolean).slice(-Bh)}catch{}return[]}function qu(e){try{let t=Uh(),n=zt.dirname(t);en.existsSync(n)||en.mkdirSync(n,{recursive:!0}),en.appendFileSync(t,e+`
2236
- `)}catch{}}function Wn(){return`${l.bold}${l.cyan}\u203A${l.reset} `}function nc(){if(!global._nexFooter)return;let{isPlanMode:e,getAutonomyLevel:t}=ps(),{getAutoConfirm:n}=un(),o=[];e()&&o.push("plan");let s=t();s==="semi-auto"&&o.push("semi"),s==="autonomous"&&o.push("auto"),n()&&o.push("always"),global._nexFooter.setStatusInfo({mode:o.join(" \xB7 ")})}var Wh="\x1B[200~",Hh="\x1B[201~";function Zj(e){return typeof e=="string"&&e.includes(Wh)}function Qj(e){return typeof e=="string"&&e.includes(Hh)}function sc(e){return typeof e!="string"?e:e.split(Wh).join("").split(Hh).join("")}async function eD(){if(!Bj("local"))return!1;try{let{exec:t}=require("child_process"),{promisify:n}=require("util");return await n(t)("curl -s --max-time 1 http://localhost:11434/api/tags"),Fh("local:llama3"),!0}catch{return!1}}async function tD(){Nx=Date.now();try{let{randomBytes:G}=require("crypto");Ih=G(4).toString("hex")}catch{Ih=Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0")}let{setAbortSignalGetter:e,getConversationLength:t,processInput:n}=We();e(jx);let s=qh().some(G=>G.configured),r,i,a;if(Oo())Mx(),r={model:bs(),providerName:ro()},i=s,a={hasNewVersion:!1};else{let G=(async()=>{Mx();let ke=bs(),ge=ro();return{model:ke,providerName:ge}})(),ue=(async()=>s?!0:await eD()?(console.log(`${l.green}\u2713 Local Ollama detected \u2014 using local models${l.reset}`),console.log(`${l.dim}Tip: Set API keys for cloud providers for more model options (DEEPSEEK_API_KEY, OPENAI_API_KEY, ANTHROPIC_API_KEY, etc.)${l.reset}
2237
- `),!0):!1)(),ve=(async()=>{if(process.env.NEX_DISABLE_UPDATE_CHECK==="1")return{hasNewVersion:!1};try{let{checkForNewVersion:ke}=Tx();return await ke()}catch{return{hasNewVersion:!1}}})();[r,i,a]=await Promise.all([G,ue,ve])}if(!i&&!s){console.error(`
2236
+ `)}catch{}}function Wn(){return`${l.bold}${l.cyan}\u203A${l.reset} `}function nc(){if(!global._nexFooter)return;let{isPlanMode:e,getAutonomyLevel:t}=ps(),{getAutoConfirm:n}=un(),o=[];e()&&o.push("plan");let s=t();s==="semi-auto"&&o.push("semi"),s==="autonomous"&&o.push("auto"),n()&&o.push("always"),global._nexFooter.setStatusInfo({mode:o.join(" \xB7 ")})}var Wh="\x1B[200~",Hh="\x1B[201~";function Zj(e){return typeof e=="string"&&e.includes(Wh)}function Qj(e){return typeof e=="string"&&e.includes(Hh)}function sc(e){return typeof e!="string"?e:e.split(Wh).join("").split(Hh).join("")}async function eD(){if(!Bj("local"))return!1;try{let{exec:t}=require("child_process"),{promisify:n}=require("util");return await n(t)("curl -s --max-time 1 http://localhost:11434/api/tags"),Fh("local:llama3"),!0}catch{return!1}}async function tD(){Nx=Date.now();try{let{randomBytes:G}=require("crypto");Ih=G(4).toString("hex")}catch{Ih=Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0")}let{setAbortSignalGetter:e,getConversationLength:t,processInput:n}=We();e(jx);let s=qh().some(G=>G.configured),r,i,a;if(Oo())Mx(),r={model:bs(),providerName:ro()},i=s,a={hasNewVersion:!1};else{let G=(async()=>{Mx();let xe=bs(),ge=ro();return{model:xe,providerName:ge}})(),ue=(async()=>s?!0:await eD()?(console.log(`${l.green}\u2713 Local Ollama detected \u2014 using local models${l.reset}`),console.log(`${l.dim}Tip: Set API keys for cloud providers for more model options (DEEPSEEK_API_KEY, OPENAI_API_KEY, ANTHROPIC_API_KEY, etc.)${l.reset}
2237
+ `),!0):!1)(),ve=(async()=>{if(process.env.NEX_DISABLE_UPDATE_CHECK==="1")return{hasNewVersion:!1};try{let{checkForNewVersion:xe}=Tx();return await xe()}catch{return{hasNewVersion:!1}}})();[r,i,a]=await Promise.all([G,ue,ve])}if(!i&&!s){console.error(`
2238
2238
  ${l.red}\u2717 No provider configured and no local Ollama detected.${l.reset}
2239
- `),process.exit(1);return}let{loadPersistedHistory:c,pruneHistory:u}=Gs();Oo()||(c().then(G=>{}),u().catch(()=>{}));let d=Hx(),f=Lj.createInterface({input:process.stdin,output:process.stdout,prompt:Wn(),completer:Fx,history:d,historySize:Bh}),p=Jj(f);zj(f);let{setAskUserHandler:h}=rs();h(async(G,ue)=>{let{T:ve}=ln(),ke=ve.reset,ge=ve.bold,ze=ve.dim,it=ve.cyan,Be=ve.yellow;return process.stdout.write(`
2240
- ${ge}${Be}\u2753${ke} ${ge}${G}${ke}
2239
+ `),process.exit(1);return}let{loadPersistedHistory:c,pruneHistory:u}=Gs();Oo()||(c().then(G=>{}),u().catch(()=>{}));let d=Hx(),f=Lj.createInterface({input:process.stdin,output:process.stdout,prompt:Wn(),completer:Fx,history:d,historySize:Bh}),p=Jj(f);zj(f);let{setAskUserHandler:h}=rs();h(async(G,ue)=>{let{T:ve}=ln(),xe=ve.reset,ge=ve.bold,ze=ve.dim,it=ve.cyan,Be=ve.yellow;return process.stdout.write(`
2240
+ ${ge}${Be}\u2753${xe} ${ge}${G}${xe}
2241
2241
 
2242
- `),ue.forEach((tt,Rn)=>{process.stdout.write(` ${it}${Rn+1}${ke} ${tt}
2243
- `)}),process.stdout.write(` ${ze}${ue.length+1}${ke} ${ze}Custom answer...${ke}
2242
+ `),ue.forEach((tt,Rn)=>{process.stdout.write(` ${it}${Rn+1}${xe} ${tt}
2243
+ `)}),process.stdout.write(` ${ze}${ue.length+1}${xe} ${ze}Custom answer...${xe}
2244
2244
  `),process.stdout.write(`
2245
- ${it}[1-${ue.length+1}]${ke} \u203A `),new Promise(tt=>{f.resume(),f.once("line",Rn=>{let de=Rn.trim(),yt=parseInt(de);yt>=1&&yt<=ue.length?(process.stdout.write(`
2246
- `),tt(ue[yt-1])):yt===ue.length+1||de===""?(process.stdout.write(` ${it}\u203A${ke} `),f.once("line",Ie=>{process.stdout.write(`
2245
+ ${it}[1-${ue.length+1}]${xe} \u203A `),new Promise(tt=>{f.resume(),f.once("line",Rn=>{let de=Rn.trim(),yt=parseInt(de);yt>=1&&yt<=ue.length?(process.stdout.write(`
2246
+ `),tt(ue[yt-1])):yt===ue.length+1||de===""?(process.stdout.write(` ${it}\u203A${xe} `),f.once("line",Ie=>{process.stdout.write(`
2247
2247
  `),tt(Ie.trim()||"")})):(process.stdout.write(`
2248
2248
  `),tt(de))})})});let m=new Vj;p&&m.activate(f),global._nexFooter=m,p?global._nexRawWrite=G=>m.rawWrite(G):delete global._nexRawWrite,Xj(()=>nc()),p&&process.stdout.write("\x1B[H\x1B[2J\x1B[3J");let g=r.providerName==="ollama"?r.model.id:`${r.providerName}:${r.model.id}`;if(Ij(g,an,{yolo:jh(),gemini:!!process.env.NEX_FORCE_MODEL&&r.providerName==="gemini"}),m.setStatusInfo({model:g,branch:"",project:zt.basename(an)}),!Oo()){let{execFile:G}=require("child_process");G("git",["rev-parse","--abbrev-ref","HEAD"],{encoding:"utf8"},(ue,ve)=>{!ue&&ve&&m.setStatusInfo({model:g,branch:ve.trim(),project:zt.basename(an)})})}a.hasNewVersion&&console.log(`${l.yellow}\u{1F4A1} New version available!${l.reset} Run ${l.cyan}npm update -g nex-code${l.reset} to upgrade from ${l.dim}${a.currentVersion}${l.reset} to ${l.green}${a.latestVersion}${l.reset}
2249
- `),await Lx(an);let $=globalThis[Du]||ju;$&&($(),ju=null,globalThis[Du]=null);let b=Oo()?null:setTimeout(()=>{try{if(Wj()){let{insights:G}=Hj();G.length>0&&Gj()&&process.stdout.write(`${l.dim}\u{1F4AD} Dream consolidated ${G.length} insight(s) from recent sessions${l.reset}
2249
+ `),await Lx(an);let y=globalThis[Du]||ju;y&&(y(),ju=null,globalThis[Du]=null);let b=Oo()?null:setTimeout(()=>{try{if(Wj()){let{insights:G}=Hj();G.length>0&&Gj()&&process.stdout.write(`${l.dim}\u{1F4AD} Dream consolidated ${G.length} insight(s) from recent sessions${l.reset}
2250
2250
  `)}}catch{}},2e3);b?.unref?.();let x=!1,_=0,E=!1,S=null;function O(){Ox();let G=[];try{let{getConversationMessages:ue}=We();G=ue(),Uj(G)}catch{}m.deactivate(),Ax(),p&&process.stdout.write("\x1B[?2004l");try{let{showGoodbyeScreen:ue}=Cx();ue({startTime:Nx,sessionId:Ih||"--------",messages:G})}catch{process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J")}process.exit(0)}Oo()||process.on("SIGTERM",O);let L=()=>{Ox()};Oo()||process.on("exit",L),f.on("SIGINT",()=>{if(Ax(),_++,_>=2){O();return}if(x){$s&&$s.abort();let{cancelPendingAskUser:G}=rs();G(),console.log(`
2251
2251
  ${l.yellow} Task cancelled. Press Ctrl+C again to exit.${l.reset}`),x=!1,f.setPrompt(Wn()),f.prompt()}else console.log(`${l.dim} (Press Ctrl+C again to exit)${l.reset}`),f.setPrompt(Wn()),f.prompt(),S&&clearTimeout(S),S=setTimeout(()=>{_=0,S=null},2e3),S.unref?.()});let I=()=>{process.stdin.isTTY?(_++,_>=2&&O()):O()};Oo()||process.on("SIGINT",I);let D=!1,Z=[],K=0,X={},Fe=!1,Oe=null;function V(){let G=Z.join(`
2252
2252
  `).replace(/\r/g,"").trim();if(Z=[],D=!1,!G)return!0;K++,Fe=!0;let ue=K;X[ue]=G;let ve=G.split(`
2253
- `).length,ke=ve>1?`[Pasted content #${ue} \u2014 ${ve} lines]`:`[Pasted content #${ue}]`,ge=f.line||"",ze=ge&&!ge.endsWith(" ")?" ":"",it=ge+ze+ke;return f.setPrompt(Wn()),f.prompt(),f.line=it,f.cursor=it.length,f._refreshLine(),!0}function re(G){return G.replace(/\[Pasted content #(\d+)(?:[^\]]*)\]/g,(ue,ve)=>X[Number(ve)]||"")}function rt(){K=0,X={},Fe=!1}if(p){process.stdout.write("\x1B[?2004h");let G=process.stdin.emit.bind(process.stdin),ue=function(ve,...ke){if(ve!=="data")return G.call(process.stdin,ve,...ke);let ge=ke[0];if(Buffer.isBuffer(ge)&&(ge=ge.toString("utf8")),typeof ge!="string")return G.call(process.stdin,ve,...ke);let ze=ge.includes(Wh),it=ge.includes(Hh);if(ze&&it){let Be=sc(ge);return Be&&Z.push(...Be.split(`
2253
+ `).length,xe=ve>1?`[Pasted content #${ue} \u2014 ${ve} lines]`:`[Pasted content #${ue}]`,ge=f.line||"",ze=ge&&!ge.endsWith(" ")?" ":"",it=ge+ze+xe;return f.setPrompt(Wn()),f.prompt(),f.line=it,f.cursor=it.length,f._refreshLine(),!0}function re(G){return G.replace(/\[Pasted content #(\d+)(?:[^\]]*)\]/g,(ue,ve)=>X[Number(ve)]||"")}function rt(){K=0,X={},Fe=!1}if(p){process.stdout.write("\x1B[?2004h");let G=process.stdin.emit.bind(process.stdin),ue=function(ve,...xe){if(ve!=="data")return G.call(process.stdin,ve,...xe);let ge=xe[0];if(Buffer.isBuffer(ge)&&(ge=ge.toString("utf8")),typeof ge!="string")return G.call(process.stdin,ve,...xe);let ze=ge.includes(Wh),it=ge.includes(Hh);if(ze&&it){let Be=sc(ge);return Be&&Z.push(...Be.split(`
2254
2254
  `)),V()}if(ze){D=!0,Z=[];let Be=sc(ge);return Be&&Z.push(...Be.split(`
2255
2255
  `)),!0}if(it){let Be=sc(ge);return Be&&Z.push(...Be.split(`
2256
2256
  `)),V()}if(D){let Be=sc(ge);return Be&&Z.push(...Be.split(`
2257
2257
  `)),!0}return ge.includes(`
2258
2258
  `)&&ge.length>40&&!D?(Z.push(...ge.replace(/\r/g,"").split(`
2259
- `)),V()):G.call(process.stdin,ve,...ke)};process.stdin.emit=ue,Oe=()=>{process.stdin.emit===ue&&(process.stdin.emit=G)}}let qe=0,_e=-1,Me=[],R="";function v(){if(qe>0){let G=m._scrollEnd,ue="\x1B7";for(let ve=0;ve<qe;ve++)ue+=`\x1B[${G-qe+1+ve};1H\x1B[2K`;ue+="\x1B8",m.rawWrite(ue),qe=0}}function z(){v(),_e=-1,Me=[],R=""}function ne(G,ue=-1){let ve=[...rc,...Fu()].filter(de=>de.cmd.startsWith(G));if(!ve.length||ve.length===1&&ve[0].cmd===G&&ue<0)return;let ke=m._scrollEnd,ge=Math.min(10,ke-2);if(ge<1)return;let ze=ve.slice(0,ge),it=Math.max(...ze.map(de=>de.cmd.length));qe=ze.length,Me=ve,R=G,ve.length>ge&&qe++;let Be=ke-qe+1,tt="\x1B7",Rn=(m._cols||80)-1;for(let de=0;de<ze.length;de++){let{cmd:yt,desc:Ie}=ze[de],Y=Math.max(0,it-yt.length+2),je=2+yt.length+Y,ss=Ie;if(je+Ie.length>Rn){let ws=Math.max(0,Rn-je-3);ws>0?ss=Ie.substring(0,ws)+"...":(ss="",Y=1)}let qs=" ".repeat(Y);if(de===ue)tt+=`\x1B[${Be+de};1H\x1B[2K \x1B[7m ${l.bold}${yt}${l.reset}\x1B[7m${qs}${ss}\x1B[27m${l.reset}`;else{let ws=yt.substring(0,G.length),_s=yt.substring(G.length);tt+=`\x1B[${Be+de};1H\x1B[2K ${l.cyan}${ws}${l.reset}${l.dim}${_s}${qs}${ss}${l.reset}`}}ve.length>ge&&(tt+=`\x1B[${Be+ze.length};1H\x1B[2K ${l.dim}\u2026 +${ve.length-ge} more${l.reset}`),tt+="\x1B8",m.rawWrite(tt)}if(p){let G=f._ttyWrite.bind(f),ue=!1;f._ttyWrite=function(ve,ke){if(ue)return G(ve,ke);if(qe>0&&ke&&!ke.ctrl&&!ke.meta){let ge=Math.min(Me.length,10)-1;if(ke.name==="down"){_e=Math.min(_e+1,ge),ue=!0,f.write(null,{ctrl:!0,name:"u"}),f.write(_e>=0?Me[_e].cmd:R),ue=!1,v(),ne(R,_e);return}if(ke.name==="up"){if(_e===-1)_e=Math.min(Me.length,10)-1;else if(_e>0)_e--;else{_e=-1,ue=!0,f.write(null,{ctrl:!0,name:"u"}),f.write(R),ue=!1,v(),ne(R,-1);return}ue=!0,f.write(null,{ctrl:!0,name:"u"}),f.write(Me[_e].cmd),ue=!1,v(),ne(R,_e);return}}return G(ve,ke)},process.stdin.on("keypress",(ve,ke)=>{qe>0&&ke&&(ke.name==="down"||ke.name==="up")||(z(),!(ke&&(ke.name==="tab"||ke.name==="return"))&&setImmediate(()=>{f.line&&f.line.startsWith("/")&&ne(f.line,-1)}))})}let te=null,M=`${l.dim}...${l.reset} `;function ye(G){return(G.match(/[^\s\d](\d{1,2})\.\s+\S/g)||[]).length<2?G:G.replace(/([^\s\d])(\d{1,2})\.\s+/g,(ve,ke,ge)=>`${ke}
2259
+ `)),V()):G.call(process.stdin,ve,...xe)};process.stdin.emit=ue,Oe=()=>{process.stdin.emit===ue&&(process.stdin.emit=G)}}let qe=0,ke=-1,Me=[],R="";function v(){if(qe>0){let G=m._scrollEnd,ue="\x1B7";for(let ve=0;ve<qe;ve++)ue+=`\x1B[${G-qe+1+ve};1H\x1B[2K`;ue+="\x1B8",m.rawWrite(ue),qe=0}}function z(){v(),ke=-1,Me=[],R=""}function ne(G,ue=-1){let ve=[...rc,...Fu()].filter(de=>de.cmd.startsWith(G));if(!ve.length||ve.length===1&&ve[0].cmd===G&&ue<0)return;let xe=m._scrollEnd,ge=Math.min(10,xe-2);if(ge<1)return;let ze=ve.slice(0,ge),it=Math.max(...ze.map(de=>de.cmd.length));qe=ze.length,Me=ve,R=G,ve.length>ge&&qe++;let Be=xe-qe+1,tt="\x1B7",Rn=(m._cols||80)-1;for(let de=0;de<ze.length;de++){let{cmd:yt,desc:Ie}=ze[de],Y=Math.max(0,it-yt.length+2),je=2+yt.length+Y,ss=Ie;if(je+Ie.length>Rn){let ws=Math.max(0,Rn-je-3);ws>0?ss=Ie.substring(0,ws)+"...":(ss="",Y=1)}let qs=" ".repeat(Y);if(de===ue)tt+=`\x1B[${Be+de};1H\x1B[2K \x1B[7m ${l.bold}${yt}${l.reset}\x1B[7m${qs}${ss}\x1B[27m${l.reset}`;else{let ws=yt.substring(0,G.length),_s=yt.substring(G.length);tt+=`\x1B[${Be+de};1H\x1B[2K ${l.cyan}${ws}${l.reset}${l.dim}${_s}${qs}${ss}${l.reset}`}}ve.length>ge&&(tt+=`\x1B[${Be+ze.length};1H\x1B[2K ${l.dim}\u2026 +${ve.length-ge} more${l.reset}`),tt+="\x1B8",m.rawWrite(tt)}if(p){let G=f._ttyWrite.bind(f),ue=!1;f._ttyWrite=function(ve,xe){if(ue)return G(ve,xe);if(qe>0&&xe&&!xe.ctrl&&!xe.meta){let ge=Math.min(Me.length,10)-1;if(xe.name==="down"){ke=Math.min(ke+1,ge),ue=!0,f.write(null,{ctrl:!0,name:"u"}),f.write(ke>=0?Me[ke].cmd:R),ue=!1,v(),ne(R,ke);return}if(xe.name==="up"){if(ke===-1)ke=Math.min(Me.length,10)-1;else if(ke>0)ke--;else{ke=-1,ue=!0,f.write(null,{ctrl:!0,name:"u"}),f.write(R),ue=!1,v(),ne(R,-1);return}ue=!0,f.write(null,{ctrl:!0,name:"u"}),f.write(Me[ke].cmd),ue=!1,v(),ne(R,ke);return}}return G(ve,xe)},process.stdin.on("keypress",(ve,xe)=>{qe>0&&xe&&(xe.name==="down"||xe.name==="up")||(z(),!(xe&&(xe.name==="tab"||xe.name==="return"))&&setImmediate(()=>{f.line&&f.line.startsWith("/")&&ne(f.line,-1)}))})}let te=null,M=`${l.dim}...${l.reset} `;function ye(G){return(G.match(/[^\s\d](\d{1,2})\.\s+\S/g)||[]).length<2?G:G.replace(/([^\s\d])(\d{1,2})\.\s+/g,(ve,xe,ge)=>`${xe}
2260
2260
  ${ge}. `).trim()}f.setPrompt(Wn()),f.prompt(),f.on("line",async G=>{if(z(),Object.keys(X).length>0&&(G=re(G),rt(),f.setPrompt(Wn())),x){let ge=G.trim();if(ge){let{injectMidRunNote:ze}=We();ze(ge),process.stdout.write(`${l.cyan} \u270E Queued \u2014 will be applied in the next step${l.reset}
2261
2261
  `),f.prompt()}return}if(te!==null){if(te._mode==="triple"){if(G.trim()==='"""'){let ge=te.join(`
2262
2262
  `).trim();if(te=null,ge){qu(ge.replace(/\n/g,"\\n")),x=!0,f.prompt(),_=0,E=!1,S&&(clearTimeout(S),S=null),$s=new AbortController;try{await n(ge)}catch(it){if(!$s?.signal?.aborted){let Be=it.message?.split(`
@@ -2265,7 +2265,7 @@ ${ge}. `).trim()}f.setPrompt(Wn()),f.prompt(),f.on("line",async G=>{if(z(),Objec
2265
2265
  `)[0]||"An unexpected error occurred";console.log(`${l.red}Error: ${tt}${l.reset}`)}}let{getConversationLength:ze}=We();x=!1;let it=ze();it>0&&process.stdout.write(`${l.gray}[${it} messages] ${l.reset}`)}f.setPrompt(Wn()),f.prompt();return}f.setPrompt(M),f.prompt();return}if(G.trim()==='"""'||G.trim().startsWith('"""')){let ge=G.trim().substring(3);te=ge?[ge]:[],te._mode="triple",f.setPrompt(M),f.prompt();return}if(G.endsWith("\\")){te=[G.slice(0,-1)],te._mode="backslash",f.setPrompt(M),f.prompt();return}let ue=ye(G.trim());if(!ue){f.setPrompt(Wn()),f.prompt();return}if(qu(ue),ue==="/"){Dx(),f.setPrompt(Wn()),f.prompt();return}if(ue.startsWith("/")){await oc(ue,f);let ge=oc._pendingAgentPrompt;if(ge){oc._pendingAgentPrompt=null;try{let{isPlanMode:ze,setPlanMode:it}=ps(),{invalidateSystemPromptCache:Be}=We();ze()&&(it(!1),Be())}catch{}x=!0,f.prompt(),_=0,E=!1,S&&(clearTimeout(S),S=null),$s=new AbortController;try{await n(ge,null,{autoOrchestrate:!1,skipPhaseRouting:!0,skillLoop:!0,maxIterations:200})}catch(ze){if(!$s?.signal?.aborted){let it=ze.message?.split(`
2266
2266
  `)[0]||"An unexpected error occurred";console.log(`${l.red}Error: ${it}${l.reset}`)}}x=!1}f.setPrompt(Wn()),f.prompt();return}{let ge=jj?"\x1B[48;5;237m":"\x1B[48;2;220;225;235m",ze=process.stdout.columns||80,it=ue.split(`
2267
2267
  `);p&&process.stdout.write(`\x1B[${it.length}A`),it.forEach((Be,tt)=>{let Rn=tt===0?"\x1B[1;36m\u203A\x1B[22;39m":" ",de=2+Be.length,yt=" ".repeat(Math.max(0,ze-de));console.log(`\x1B[2K${ge}${Rn} ${Be}${yt}\x1B[0m`)}),console.log()}if(process.env.NEX_AUTO_PLAN!=="0"&&!jh()){let{isPlanMode:ge,setPlanMode:ze}=ps(),{invalidateSystemPromptCache:it}=We(),Be=/\b(implement|refactor|migrate|redesign)\b/i,tt=/\b(create|build|add|write|develop|set\s+up)\b/i,Rn=/^(how|what|why|when|where|which|explain|show|list|tell|describe|can\s+you|could\s+you|do\s+you)\b/i,de=/^(hi|hello|hey|yo)\b/i.test(ue)||/\b(introduce yourself|who are you|what can you do|tell me about yourself)\b/i.test(ue),yt=/\b(spawn[_\s]?agents?|swarm)\b/i;!de&&!Rn.test(ue)&&!yt.test(ue)&&(Be.test(ue)||tt.test(ue)&&ue.split(/\s+/).length>=5)&&!ge()&&(ze(!0),it(),console.log(`${l.cyan}${l.bold}\u2387 Auto Plan Mode${l.reset}${l.dim} \u2014 implementation task detected \xB7 read-only until /plan approve${l.reset}`))}{let{getConversationLength:ge}=We();if(ge()===0)try{let{detectCategory:ze,getModelForCategory:it}=fs(),Be=ze(ue);if(Be&&Be.id!=="coding"){let tt=it(Be.id),Rn=bs();if(tt&&tt!==Rn?.id&&Fh(tt)){let de=bs();console.log(`${l.dim}\u21B3 ${Be.icon} ${Be.label} task \u2014 routing to ${de?.name||tt}${l.reset}`),global._nexFooter&&global._nexFooter.setStatusInfo({model:de?.name||tt})}}}catch{}}x=!0,f.prompt(),_=0,E=!1,S&&(clearTimeout(S),S=null),$s=new AbortController;try{await n(ue)}catch(ge){if(!$s?.signal?.aborted){let ze=ge.message?.split(`
2268
- `)[0]||"An unexpected error occurred";console.log(`${l.red}Error: ${ze}${l.reset}`)}}x=!1;let{getConversationLength:ve}=We(),ke=ve();ke>0&&process.stdout.write(`${l.gray}[${ke} messages] ${l.reset}`),f.setPrompt(Wn()),f.prompt()});let Qe=()=>{b&&clearTimeout(b),S&&(clearTimeout(S),S=null),process.off("SIGTERM",O),process.off("exit",L),process.off("SIGINT",I),Oe&&(Oe(),Oe=null)};ju=Qe,globalThis[Du]=Qe,f.on("close",()=>{Qe(),ju=null,globalThis[Du]=null,p&&process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J"),process.exit(0)})}Gx.exports={startREPL:tD,getPrompt:Wn,loadHistory:Hx,appendHistory:qu,getHistoryPath:Uh,HISTORY_MAX:Bh,showCommandList:Dx,completer:Fx,completeFilePath:qx,handleSlashCommand:oc,showProviders:Dh,showModelRecommendations:Wx,showHelp:Bx,renderBar:Ux,hasPasteStart:Zj,hasPasteEnd:Qj,stripPasteSequences:sc,getAbortSignal:jx}});var zx=Q((LF,Yx)=>{"use strict";var nD=require("readline");function _r(e){process.stdout.write(JSON.stringify(e)+`
2268
+ `)[0]||"An unexpected error occurred";console.log(`${l.red}Error: ${ze}${l.reset}`)}}x=!1;let{getConversationLength:ve}=We(),xe=ve();xe>0&&process.stdout.write(`${l.gray}[${xe} messages] ${l.reset}`),f.setPrompt(Wn()),f.prompt()});let Qe=()=>{b&&clearTimeout(b),S&&(clearTimeout(S),S=null),process.off("SIGTERM",O),process.off("exit",L),process.off("SIGINT",I),Oe&&(Oe(),Oe=null)};ju=Qe,globalThis[Du]=Qe,f.on("close",()=>{Qe(),ju=null,globalThis[Du]=null,p&&process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J"),process.exit(0)})}Gx.exports={startREPL:tD,getPrompt:Wn,loadHistory:Hx,appendHistory:qu,getHistoryPath:Uh,HISTORY_MAX:Bh,showCommandList:Dx,completer:Fx,completeFilePath:qx,handleSlashCommand:oc,showProviders:Dh,showModelRecommendations:Wx,showHelp:Bx,renderBar:Ux,hasPasteStart:Zj,hasPasteEnd:Qj,stripPasteSequences:sc,getAbortSignal:jx}});var zx=Q((LF,Yx)=>{"use strict";var nD=require("readline");function _r(e){process.stdout.write(JSON.stringify(e)+`
2269
2269
  `)}function sD(){process.env.NEX_SERVER="1";let e=(...a)=>process.stderr.write(a.map(String).join(" ")+`
2270
2270
  `);console.log=e,console.warn=e,console.info=e;let{setConfirmHook:t}=un(),n=new Map,o=0;t((a,c)=>{let u="cfm-"+ ++o,d=c?.toolName||"",f=!1;try{let{isCritical:p}=un();f=p(a)}catch{}return _r({type:"confirm_request",id:u,question:a,tool:d,critical:f}),new Promise(p=>{n.set(u,p)})});let s=null,r={onToken(a){s&&_r({type:"token",id:s,text:a})},onThinkingToken(){},onToolStart(a,c){s&&_r({type:"tool_start",id:s,tool:a,args:c||{}})},onToolEnd(a,c,u){s&&_r({type:"tool_end",id:s,tool:a,summary:c||"",ok:!!u})}},i=nD.createInterface({input:process.stdin,output:null,terminal:!1});_r({type:"ready"}),i.on("line",async a=>{let c=a.trim();if(!c)return;let u;try{u=JSON.parse(c)}catch{return}switch(u.type){case"chat":{let d=u.id||"msg-"+Date.now();s=d;let{processInput:f}=We();try{await f(u.text,r),_r({type:"done",id:d})}catch(p){_r({type:"error",id:d,message:p?.message||String(p)})}finally{s=null}break}case"confirm":{let d=n.get(u.id);d&&(n.delete(u.id),d(!!u.answer));break}case"cancel":{for(let[d,f]of n)n.delete(d),f(!1);break}case"clear":{let{clearConversation:d}=We();d();for(let[f,p]of n)n.delete(f),p(!1);break}default:break}}),i.on("close",()=>{process.exit(0)})}Yx.exports={startServerMode:sD}});var Zx=Q((IF,Jx)=>{"use strict";var kr=require("fs"),Yh=require("path"),oD=require("https"),{execSync:zh}=require("child_process"),rD=5*1024*1024;function Kx(e){let t=e.match(/^\*\/(\d+) \* \* \* \*$/);if(t){let o=parseInt(t[1],10);if(o>0)return{intervalMs:o*60*1e3,initialDelayMs:0}}let n=e.match(/^0 (\d+) \* \* \*$/);if(n){let o=parseInt(n[1],10),s=new Date,r=new Date;return r.setHours(o,0,0,0),r<=s&&r.setDate(r.getDate()+1),{intervalMs:1440*60*1e3,initialDelayMs:r.getTime()-s.getTime()}}return null}function Kh(e,t){return e.replace(/\{(\w+)\}/g,(n,o)=>t[o]!==void 0?t[o]:n)}function Xx(e,t){if(e)try{let n=Yh.resolve(e),o=Yh.dirname(n);kr.existsSync(o)||kr.mkdirSync(o,{recursive:!0});try{kr.statSync(n).size>rD&&kr.truncateSync(n,0)}catch{}kr.appendFileSync(n,JSON.stringify(t)+`
2271
2271
  `,"utf-8")}catch(n){process.stderr.write(`[daemon] log write error: ${n.message}
@@ -2282,7 +2282,7 @@ press Ctrl+C to stop
2282
2282
  `);let a=[];for(let u of s.triggers){let d=null;switch(u.on){case"file-change":d=lD(u,s,n);break;case"git-commit":d=uD(u,s,n);break;case"schedule":d=dD(u,s);break;default:process.stderr.write(`[daemon] unknown trigger type: ${u.on}
2283
2283
  `)}d&&a.push(d)}let c=()=>{process.stdout.write(`
2284
2284
  [daemon] shutting down...
2285
- `);for(let u of a)try{u&&typeof u.close=="function"?u.close():u&&clearInterval(u)}catch{}process.exit(0)};return process.on("SIGINT",c),process.on("SIGTERM",c),new Promise(()=>{})}Jx.exports={startDaemon:fD,parseCronToMs:Kx,expandTemplate:Kh,appendLog:Xx,notifyMatrix:Vx}});var ev=Q((jF,Qx)=>{Qx.exports=Gh()});var Hu=require("path"),pD=require("os");process.env.NEX_NO_DOTENV!=="1"&&(require("dotenv").config({path:Hu.join(__dirname,"..",".env")}),require("dotenv").config({path:Hu.join(pD.homedir(),".nex-code",".env"),override:!0}),require("dotenv").config());var xe=process.argv.slice(2),tm=xe.includes("--json");(xe.includes("--help")||xe.includes("-h"))&&(console.log(`Usage: nex-code [options]
2285
+ `);for(let u of a)try{u&&typeof u.close=="function"?u.close():u&&clearInterval(u)}catch{}process.exit(0)};return process.on("SIGINT",c),process.on("SIGTERM",c),new Promise(()=>{})}Jx.exports={startDaemon:fD,parseCronToMs:Kx,expandTemplate:Kh,appendLog:Xx,notifyMatrix:Vx}});var ev=Q((jF,Qx)=>{Qx.exports=Gh()});var Hu=require("path"),pD=require("os");process.env.NEX_NO_DOTENV!=="1"&&(require("dotenv").config({path:Hu.join(__dirname,"..",".env")}),require("dotenv").config({path:Hu.join(pD.homedir(),".nex-code",".env"),override:!0}),require("dotenv").config());var _e=process.argv.slice(2),tm=_e.includes("--json");(_e.includes("--help")||_e.includes("-h"))&&(console.log(`Usage: nex-code [options]
2286
2286
 
2287
2287
  Options:
2288
2288
  --task <prompt> Run a single task and exit (headless mode)
@@ -2302,6 +2302,9 @@ Options:
2302
2302
  --max-turns <n> Max agentic loop iterations (default: 50)
2303
2303
  --scope <files> Restrict file edits to these files/dirs (comma-separated, globs ok)
2304
2304
  e.g. --scope 'src/index.js,src/components/*.tsx'
2305
+ --decompose Shell alias hint: multi-file tasks work best as
2306
+ sequential single-file runs. Use a shell loop:
2307
+ for f in a.js b.js; do nex-code --scope "$f" --task "..." --auto; done
2305
2308
  --orchestrate Use multi-agent orchestrator (with --task)
2306
2309
  --no-auto-orchestrate Disable auto-orchestration for multi-goal prompts (on by default)
2307
2310
  --orchestrator-model <m> Model for orchestrator (default: kimi-k2.5)
@@ -2311,13 +2314,13 @@ Options:
2311
2314
  --mcp-config <path> Path to MCP server config (default: .nex/mcp.json)
2312
2315
  -h, --help Show this help
2313
2316
  -v, --version Show version
2314
- `),process.exit(0));if(xe.includes("-v")||xe.includes("--version")){let e=Ar();console.log(e.version),process.exit(0)}var ov=xe.includes("--yolo")||xe.includes("-yolo");if(ov){let{setAutoConfirm:e}=un();e(!0)}if(!ov)try{let e=require("fs"),t=Hu.join(process.cwd(),".nex","config.json");if(e.existsSync(t)&&JSON.parse(e.readFileSync(t,"utf-8")).yolo===!0){let{setAutoConfirm:o}=un();o(!0)}}catch{}var hD=xe.indexOf("--gemini-model"),mD=xe.includes("--gemini")||xe.includes("-gemini")||hD!==-1,Vh=xe.indexOf("--model"),gD=Vh!==-1&&xe[Vh+1]?xe[Vh+1]:"",tv=(()=>{let e=gD.split(":")[0];return["ollama","openai","deepseek","anthropic","gemini","local","mock"].includes(e)?e:null})(),yD=process.env.DEFAULT_PROVIDER||"ollama",$D=tv!==null?tv==="ollama":yD==="ollama",nm=!mD&&(xe.includes("--flatrate")||!!process.env.OLLAMA_API_KEY&&!process.env.NEX_NO_FLATRATE&&$D);nm&&(process.env.NEX_MAX_PARALLEL||(process.env.NEX_MAX_PARALLEL="6"),process.env.NEX_MAX_SUBTASKS||(process.env.NEX_MAX_SUBTASKS="10"),process.env.NEX_MAX_CHAT_RETRIES||(process.env.NEX_MAX_CHAT_RETRIES="5"),process.env.OLLAMA_FALLBACK_CHAIN||(process.env.OLLAMA_FALLBACK_CHAIN="ministral-3:8b,qwen3-vl:235b-instruct,devstral-small-2:24b"),tm||process.stderr.write(`\x1B[38;2;80;210;120m\u25C6\x1B[0m \x1B[1mFlatrate mode\x1B[0m\x1B[2m \u2014 100 turns \xB7 6 parallel agents \xB7 5 retries \xB7 verify-on\x1B[0m
2315
- `));var Jh=xe.indexOf("--model");if(Jh!==-1&&xe[Jh+1]){let{setActiveModel:e}=ft(),t=xe[Jh+1];e(t)||(console.error(`\x1B[31mError:\x1B[0m Unknown model '${t}'.`),process.exit(1));let o=(()=>{let r=t.split(":")[0];return["ollama","openai","deepseek","anthropic","gemini","local","mock"].includes(r)?r:null})(),s=o?t.slice(o.length+1):t;process.env.NEX_FORCE_MODEL=s,process.env.NEX_PHASE_ROUTING="0",process.env.DEFAULT_MODEL=s,o&&(process.env.DEFAULT_PROVIDER=o)}var Uu=xe.indexOf("--gemini-model"),rv=xe.includes("--gemini")||xe.includes("-gemini")||Uu!==-1;if(rv){!process.env.GEMINI_API_KEY&&!process.env.GOOGLE_API_KEY&&(console.error("\x1B[31mError:\x1B[0m --gemini requires GEMINI_API_KEY (or GOOGLE_API_KEY) to be set."),process.exit(1));let e=Uu!==-1&&xe[Uu+1]?xe[Uu+1]:"gemini-3.1-pro-preview";process.env.NEX_FORCE_MODEL=e,process.env.NEX_PHASE_ROUTING="0",process.env.DEFAULT_PROVIDER="gemini",process.env.DEFAULT_MODEL=e,process.env.NEX_FALLBACK_MODEL=e;for(let o of["NEX_ROUTE_CODING","NEX_ROUTE_FRONTEND","NEX_ROUTE_SYSADMIN","NEX_ROUTE_DATA","NEX_ROUTE_AGENTIC","NEX_PHASE_PLAN_MODEL","NEX_PHASE_IMPLEMENT_MODEL","NEX_PHASE_VERIFY_MODEL","OLLAMA_FALLBACK_CHAIN"])delete process.env[o];let{setActiveModel:t}=ft();t(`gemini:${e}`)||(console.error(`\x1B[31mError:\x1B[0m Unknown Gemini model '${e}'.`),process.exit(1)),tm||process.stderr.write(`\x1B[38;2;138;180;248m\u25C6\x1B[0m \x1B[1mGemini mode\x1B[0m\x1B[2m \u2014 provider=gemini \xB7 model=${e} \xB7 routing locked\x1B[0m
2316
- `)}var Bu=xe.indexOf("--scope");Bu!==-1&&xe[Bu+1]&&!xe[Bu+1].startsWith("--")&&(process.env.NEX_SCOPE=xe[Bu+1]);var Wu=xe.indexOf("--max-turns");if(Wu!==-1&&xe[Wu+1]){let e=parseInt(xe[Wu+1],10);if(e>0){let{setMaxIterations:t}=We();t(e)}}else try{let e=require("fs"),t=Hu.join(process.cwd(),".nex","config.json");if(e.existsSync(t)){let n=JSON.parse(e.readFileSync(t,"utf-8")),o=parseInt(n.maxIterations,10);if(o>0){let{setMaxIterations:s}=We();s(o)}}}catch{}var Zh=xe.indexOf("--mcp-config");Zh!==-1&&xe[Zh+1]&&(process.env.NEX_MCP_CONFIG=xe[Zh+1]);function Qh(){if(process.platform==="darwin")try{let{spawn:e}=require("child_process"),t=e("caffeinate",["-i","-m"],{stdio:"ignore",detached:!1});t.unref();let n=()=>{try{t.kill()}catch{}};process.on("exit",n),process.on("SIGINT",n),process.on("SIGTERM",n)}catch{}}async function bD(){let{runSetupWizard:e}=uh();await e()}function io(e,t=process.stdout.write.bind(process.stdout)){t(JSON.stringify(e)+`
2317
+ `),process.exit(0));if(_e.includes("-v")||_e.includes("--version")){let e=Ar();console.log(e.version),process.exit(0)}var ov=_e.includes("--yolo")||_e.includes("-yolo");if(ov){let{setAutoConfirm:e}=un();e(!0)}if(!ov)try{let e=require("fs"),t=Hu.join(process.cwd(),".nex","config.json");if(e.existsSync(t)&&JSON.parse(e.readFileSync(t,"utf-8")).yolo===!0){let{setAutoConfirm:o}=un();o(!0)}}catch{}var hD=_e.indexOf("--gemini-model"),mD=_e.includes("--gemini")||_e.includes("-gemini")||hD!==-1,Vh=_e.indexOf("--model"),gD=Vh!==-1&&_e[Vh+1]?_e[Vh+1]:"",tv=(()=>{let e=gD.split(":")[0];return["ollama","openai","deepseek","anthropic","gemini","local","mock"].includes(e)?e:null})(),yD=process.env.DEFAULT_PROVIDER||"ollama",$D=tv!==null?tv==="ollama":yD==="ollama",nm=!mD&&(_e.includes("--flatrate")||!!process.env.OLLAMA_API_KEY&&!process.env.NEX_NO_FLATRATE&&$D);nm&&(process.env.NEX_MAX_PARALLEL||(process.env.NEX_MAX_PARALLEL="6"),process.env.NEX_MAX_SUBTASKS||(process.env.NEX_MAX_SUBTASKS="10"),process.env.NEX_MAX_CHAT_RETRIES||(process.env.NEX_MAX_CHAT_RETRIES="5"),process.env.OLLAMA_FALLBACK_CHAIN||(process.env.OLLAMA_FALLBACK_CHAIN="ministral-3:8b,qwen3-vl:235b-instruct,devstral-small-2:24b"),tm||process.stderr.write(`\x1B[38;2;80;210;120m\u25C6\x1B[0m \x1B[1mFlatrate mode\x1B[0m\x1B[2m \u2014 100 turns \xB7 6 parallel agents \xB7 5 retries \xB7 verify-on\x1B[0m
2318
+ `));var Jh=_e.indexOf("--model");if(Jh!==-1&&_e[Jh+1]){let{setActiveModel:e}=ft(),t=_e[Jh+1];e(t)||(console.error(`\x1B[31mError:\x1B[0m Unknown model '${t}'.`),process.exit(1));let o=(()=>{let r=t.split(":")[0];return["ollama","openai","deepseek","anthropic","gemini","local","mock"].includes(r)?r:null})(),s=o?t.slice(o.length+1):t;process.env.NEX_FORCE_MODEL=s,process.env.NEX_PHASE_ROUTING="0",process.env.DEFAULT_MODEL=s,o&&(process.env.DEFAULT_PROVIDER=o)}var Uu=_e.indexOf("--gemini-model"),rv=_e.includes("--gemini")||_e.includes("-gemini")||Uu!==-1;if(rv){!process.env.GEMINI_API_KEY&&!process.env.GOOGLE_API_KEY&&(console.error("\x1B[31mError:\x1B[0m --gemini requires GEMINI_API_KEY (or GOOGLE_API_KEY) to be set."),process.exit(1));let e=Uu!==-1&&_e[Uu+1]?_e[Uu+1]:"gemini-3.1-pro-preview";process.env.NEX_FORCE_MODEL=e,process.env.NEX_PHASE_ROUTING="0",process.env.DEFAULT_PROVIDER="gemini",process.env.DEFAULT_MODEL=e,process.env.NEX_FALLBACK_MODEL=e;for(let o of["NEX_ROUTE_CODING","NEX_ROUTE_FRONTEND","NEX_ROUTE_SYSADMIN","NEX_ROUTE_DATA","NEX_ROUTE_AGENTIC","NEX_PHASE_PLAN_MODEL","NEX_PHASE_IMPLEMENT_MODEL","NEX_PHASE_VERIFY_MODEL","OLLAMA_FALLBACK_CHAIN"])delete process.env[o];let{setActiveModel:t}=ft();t(`gemini:${e}`)||(console.error(`\x1B[31mError:\x1B[0m Unknown Gemini model '${e}'.`),process.exit(1)),tm||process.stderr.write(`\x1B[38;2;138;180;248m\u25C6\x1B[0m \x1B[1mGemini mode\x1B[0m\x1B[2m \u2014 provider=gemini \xB7 model=${e} \xB7 routing locked\x1B[0m
2319
+ `)}var Bu=_e.indexOf("--scope");Bu!==-1&&_e[Bu+1]&&!_e[Bu+1].startsWith("--")&&(process.env.NEX_SCOPE=_e[Bu+1]);var Wu=_e.indexOf("--max-turns");if(Wu!==-1&&_e[Wu+1]){let e=parseInt(_e[Wu+1],10);if(e>0){let{setMaxIterations:t}=We();t(e)}}else try{let e=require("fs"),t=Hu.join(process.cwd(),".nex","config.json");if(e.existsSync(t)){let n=JSON.parse(e.readFileSync(t,"utf-8")),o=parseInt(n.maxIterations,10);if(o>0){let{setMaxIterations:s}=We();s(o)}}}catch{}var Zh=_e.indexOf("--mcp-config");Zh!==-1&&_e[Zh+1]&&(process.env.NEX_MCP_CONFIG=_e[Zh+1]);function Qh(){if(process.platform==="darwin")try{let{spawn:e}=require("child_process"),t=e("caffeinate",["-i","-m"],{stdio:"ignore",detached:!1});t.unref();let n=()=>{try{t.kill()}catch{}};process.on("exit",n),process.on("SIGINT",n),process.on("SIGTERM",n)}catch{}}async function bD(){let{runSetupWizard:e}=uh();await e()}function io(e,t=process.stdout.write.bind(process.stdout)){t(JSON.stringify(e)+`
2317
2320
  `)}function wD(e){let{stripAnsiControlSequences:t}=Sc();return t(e)}function _D(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>t?typeof t=="string"?t:t.type==="text"&&t.text||"":"").filter(Boolean).join(`
2318
2321
  `):""}function kD(e){let t=wD(e||"").split(`
2319
- `).map(n=>n.trim()).filter(Boolean);return t.length===0?"":t[0].replace(/^[│↩]\s*/,"").replace(/\s+/g," ").trim()}function em(e){return Array.isArray(e)?e.reduce((t,n)=>!n||n.role!=="assistant"?t:Array.isArray(n.tool_calls)?t+n.tool_calls.length:Array.isArray(n.content)?t+n.content.filter(o=>o&&o.type==="tool_use").length:t,0):0}function xD(){process.env.NEX_SERVER="1";let e="",t=process.stdout.write.bind(process.stdout),n={log:console.log,warn:console.warn,info:console.info,error:console.error},o=process.stdout.write,s=process.stderr.write;function r(i,a,c){let u=c;return typeof a=="function"&&(u=a),typeof u=="function"&&u(),!0}return process.stdout.write=r,process.stderr.write=r,console.log=()=>{},console.warn=()=>{},console.info=()=>{},console.error=()=>{},{hooks:{onToken(i){e+=i||"",io({type:"token",text:i},t)},onThinkingToken(){io({type:"thinking"},t)},onToolStart(i,a){io({type:"tool_start",tool:i,args:a||{}},t)},onToolEnd(i,a,c){io({type:"tool_end",tool:i,summary:kD(a||""),ok:!!c},t)}},getStreamedText(){return e},restore(){process.stdout.write=o,process.stderr.write=s,console.log=n.log,console.warn=n.warn,console.info=n.info,console.error=n.error}}}function vD(){process.env.NEX_SERVER="1";let e="",t={log:console.log,warn:console.warn,info:console.info,error:console.error},n=process.stdout.write,o=process.stderr.write;function s(r,i,a){let c=a;return typeof i=="function"&&(c=i),typeof c=="function"&&c(),!0}return process.stdout.write=s,process.stderr.write=s,console.log=()=>{},console.warn=()=>{},console.info=()=>{},console.error=()=>{},{hooks:{onToken(r){e+=r||""},onThinkingToken(){},onToolStart(){},onToolEnd(){}},getStreamedText(){return e},restore(){process.stdout.write=n,process.stderr.write=o,console.log=t.log,console.warn=t.warn,console.info=t.info,console.error=t.error}}}function nv(e){if(xe.includes("--auto")){let{setAutoConfirm:p}=un();p(!0)}if(nm&&Wu===-1){let{setMaxIterations:p}=We();p(100)}if(!(xe.includes("--model")||rv)){let{setActiveModel:p}=ft(),h=process.env.HEADLESS_MODEL||"devstral-2:123b";p(h)}let n=!xe.includes("--no-auto-orchestrate")&&process.env.NEX_AUTO_ORCHESTRATE!=="false",o=xe.indexOf("--orchestrator-model"),s=o!==-1?xe[o+1]:void 0,r=tm?xD():null,i=null,a=r?r.hooks:null;function c(p){let{sanitizeFinalAnswer:h}=Sc(),m=p(),g="";for(let S=m.length-1;S>=0;S--){let O=m[S];if(O.role==="assistant"){let L=h(_D(O.content));if(L&&L.trim().length>0){g=L;break}}}let $=String(r?.getStreamedText?.()||i?.getStreamedText?.()||"").trim(),b=typeof g=="string"&&g.trim().length>0?g:$;if(!(typeof b=="string"&&b.trim().length>0)){let S=new Set(["write_file","edit_file","patch_file"]),O=!1;for(let Z of m){if(Z.role!=="assistant")continue;let K=Z.tool_calls||(Array.isArray(Z.content)?Z.content.filter(X=>X&&X.type==="tool_use"):[]);for(let X of K){let Fe=X.function?.name||X.name||"";if(S.has(Fe)){O=!0;break}}if(O)break}if(O){let Z="Headless run: files were modified but no final summary was produced. Exiting cleanly (writes detected).";if(!r){i&&i.restore(),console.error(Z),process.exit(0);return}let{getSessionCosts:K}=os(),X=K();r.restore(),io({type:"result",success:!0,warning:Z,response:"(files modified, no text summary)",usage:{input:X.totalInput||0,output:X.totalOutput||0,cacheRead:X.totalCacheRead||0},toolCalls:em(m)}),process.exit(0);return}let L="Headless run ended without a final assistant response. Stopping to avoid a false success.";if(!r){i&&i.restore(),console.error(L),process.exit(1);return}let{getSessionCosts:I}=os(),D=I();r.restore(),io({type:"error",success:!1,error:L,usage:{input:D.totalInput||0,output:D.totalOutput||0,cacheRead:D.totalCacheRead||0},toolCalls:em(m)}),process.exit(1);return}if(!r){i&&(i.restore(),b&&process.stdout.write(b+`
2320
- `)),process.exit(0);return}let{getSessionCosts:_}=os(),E=_();r.restore(),io({type:"done",success:!0,response:b,usage:{input:E.totalInput||0,output:E.totalOutput||0,cacheRead:E.totalCacheRead||0},toolCalls:em(m)}),process.exit(0)}function u(p){if(!r){i&&i.restore(),console.error(p.message),process.exit(1);return}r.restore(),io({type:"error",success:!1,error:p?.message||String(p)}),process.exit(1)}if(e.startsWith("/")){let{loadAllSkills:p,handleSkillCommand:h}=Ys();p();let m=h(e);if(m&&m.agentPrompt){let{processInput:$,getConversationMessages:b}=We();$(m.agentPrompt,a,{autoOrchestrate:n,orchestratorModel:s}).then(()=>c(b)).catch(x=>u(x));return}let{handleSlashCommand:g}=Gh();g(e,null).then(()=>{r&&(r.restore(),io({type:"done",success:!0,response:""})),process.exit(0)}).catch($=>u($));return}let{processInput:d,getConversationMessages:f}=We();r||(i=vD(),a=i.hooks),d(e,a,{autoOrchestrate:n,orchestratorModel:s}).then(()=>{try{let{writeDreamLog:p}=Su();p(f())}catch{}c(f)}).catch(p=>u(p))}if(xe.includes("--server")){let{setAutoConfirm:e}=un();e(!0),zx().startServerMode();return}if(xe.includes("--daemon")||xe.includes("--watch")){let e=xe.includes("--daemon")?xe.indexOf("--daemon"):xe.indexOf("--watch"),t=xe[e+1],n=t&&!t.startsWith("--")?t:".nex/daemon.json",{startDaemon:o}=Zx();o(n).catch(s=>{console.error("Daemon error:",s.message),process.exit(1)});return}var sv=xe.indexOf("--prompt-file");if(sv!==-1){let e=xe[sv+1];(!e||e.startsWith("--"))&&(console.error("--prompt-file requires a file path"),process.exit(1));let t=require("fs"),n;try{n=t.readFileSync(e,"utf-8").trim()}catch(o){console.error(`--prompt-file: cannot read file: ${o.message}`),process.exit(1)}if(n||(console.error("--prompt-file: file is empty"),process.exit(1)),xe.includes("--delete-prompt-file"))try{t.unlinkSync(e)}catch{}Qh(),nv(n)}else{let e=xe.indexOf("--task")!==-1?xe.indexOf("--task"):xe.indexOf("--prompt");if(e!==-1){let t=xe[e+1];if((!t||t.startsWith("--"))&&(console.error("--task/--prompt requires a prompt"),process.exit(1)),Qh(),xe.includes("--orchestrate")){let n=xe.indexOf("--orchestrator-model"),o=n!==-1?xe[n+1]:void 0,{runOrchestrated:s}=ya();s(t,{orchestratorModel:o}).then(()=>{process.exit(0)}).catch(r=>{console.error(`Orchestrator error: ${r.message}`),process.exit(1)})}else nv(t)}else bD().then(async()=>{if(Qh(),nm){let{setMaxIterations:n}=We();n(100)}if(xe.includes("--resume")){let{loadSession:n}=ds(),{setConversationMessages:o}=We(),s=n("_autosave");if(s&&s.messages&&s.messages.length>0){let i=s.messages,a=i.length>20?i.slice(-20):i;o(a);let{getUsage:c,forceCompress:u}=Mn();if(c(a,[]).percentage>=30){let{messages:p}=u(a,[]);o(p)}let{C:f}=dt();process.stdout.write(`${f.dim}Session restored (${a.length} messages)${f.reset}
2322
+ `).map(n=>n.trim()).filter(Boolean);return t.length===0?"":t[0].replace(/^[│↩]\s*/,"").replace(/\s+/g," ").trim()}function em(e){return Array.isArray(e)?e.reduce((t,n)=>!n||n.role!=="assistant"?t:Array.isArray(n.tool_calls)?t+n.tool_calls.length:Array.isArray(n.content)?t+n.content.filter(o=>o&&o.type==="tool_use").length:t,0):0}function xD(){process.env.NEX_SERVER="1";let e="",t=process.stdout.write.bind(process.stdout),n={log:console.log,warn:console.warn,info:console.info,error:console.error},o=process.stdout.write,s=process.stderr.write;function r(i,a,c){let u=c;return typeof a=="function"&&(u=a),typeof u=="function"&&u(),!0}return process.stdout.write=r,process.stderr.write=r,console.log=()=>{},console.warn=()=>{},console.info=()=>{},console.error=()=>{},{hooks:{onToken(i){e+=i||"",io({type:"token",text:i},t)},onThinkingToken(){io({type:"thinking"},t)},onToolStart(i,a){io({type:"tool_start",tool:i,args:a||{}},t)},onToolEnd(i,a,c){io({type:"tool_end",tool:i,summary:kD(a||""),ok:!!c},t)}},getStreamedText(){return e},restore(){process.stdout.write=o,process.stderr.write=s,console.log=n.log,console.warn=n.warn,console.info=n.info,console.error=n.error}}}function vD(){process.env.NEX_SERVER="1";let e="",t={log:console.log,warn:console.warn,info:console.info,error:console.error},n=process.stdout.write,o=process.stderr.write;function s(r,i,a){let c=a;return typeof i=="function"&&(c=i),typeof c=="function"&&c(),!0}return process.stdout.write=s,process.stderr.write=s,console.log=()=>{},console.warn=()=>{},console.info=()=>{},console.error=()=>{},{hooks:{onToken(r){e+=r||""},onThinkingToken(){},onToolStart(){},onToolEnd(){}},getStreamedText(){return e},restore(){process.stdout.write=n,process.stderr.write=o,console.log=t.log,console.warn=t.warn,console.info=t.info,console.error=t.error}}}async function nv(e){if(_e.includes("--decompose")&&process.env.NEX_SCOPE){let p=process.env.NEX_SCOPE.split(",").map(h=>h.trim()).filter(Boolean);if(p.length>1){let{execSync:h}=require("child_process"),m=process.argv[1],g=process.argv.slice(2).filter(y=>y!=="--decompose"&&y!==process.env.NEX_SCOPE).join(" ");console.error(`Decomposing into ${p.length} sequential tasks...`);for(let y=0;y<p.length;y++){let b=p[y];console.error(` [${y+1}/${p.length}] ${b}`);try{h(`${process.execPath} ${m} ${g} --scope '${b}' --task "${e.replace(/"/g,'\\"')}"`,{stdio:"inherit",timeout:6e5})}catch(x){console.error(` \u26A0 Subtask ${y+1} failed (exit ${x.status})`)}}console.error(`All ${p.length} subtasks complete.`),process.exit(0)}}if(_e.includes("--auto")){let{setAutoConfirm:p}=un();p(!0)}if(nm&&Wu===-1){let{setMaxIterations:p}=We();p(100)}if(!(_e.includes("--model")||rv)){let{setActiveModel:p}=ft(),h=process.env.HEADLESS_MODEL||"devstral-2:123b";p(h)}let n=!_e.includes("--no-auto-orchestrate")&&process.env.NEX_AUTO_ORCHESTRATE!=="false",o=_e.indexOf("--orchestrator-model"),s=o!==-1?_e[o+1]:void 0,r=tm?xD():null,i=null,a=r?r.hooks:null;function c(p){let{sanitizeFinalAnswer:h}=Sc(),m=p(),g="";for(let S=m.length-1;S>=0;S--){let O=m[S];if(O.role==="assistant"){let L=h(_D(O.content));if(L&&L.trim().length>0){g=L;break}}}let y=String(r?.getStreamedText?.()||i?.getStreamedText?.()||"").trim(),b=typeof g=="string"&&g.trim().length>0?g:y;if(!(typeof b=="string"&&b.trim().length>0)){let S=new Set(["write_file","edit_file","patch_file"]),O=!1;for(let Z of m){if(Z.role!=="assistant")continue;let K=Z.tool_calls||(Array.isArray(Z.content)?Z.content.filter(X=>X&&X.type==="tool_use"):[]);for(let X of K){let Fe=X.function?.name||X.name||"";if(S.has(Fe)){O=!0;break}}if(O)break}if(O){let Z="Headless run: files were modified but no final summary was produced. Exiting cleanly (writes detected).";if(!r){i&&i.restore(),console.error(Z),process.exit(0);return}let{getSessionCosts:K}=os(),X=K();r.restore(),io({type:"result",success:!0,warning:Z,response:"(files modified, no text summary)",usage:{input:X.totalInput||0,output:X.totalOutput||0,cacheRead:X.totalCacheRead||0},toolCalls:em(m)}),process.exit(0);return}let L="Headless run ended without a final assistant response. Stopping to avoid a false success.";if(!r){i&&i.restore(),console.error(L),process.exit(1);return}let{getSessionCosts:I}=os(),D=I();r.restore(),io({type:"error",success:!1,error:L,usage:{input:D.totalInput||0,output:D.totalOutput||0,cacheRead:D.totalCacheRead||0},toolCalls:em(m)}),process.exit(1);return}if(!r){i&&(i.restore(),b&&process.stdout.write(b+`
2323
+ `)),process.exit(0);return}let{getSessionCosts:_}=os(),E=_();r.restore(),io({type:"done",success:!0,response:b,usage:{input:E.totalInput||0,output:E.totalOutput||0,cacheRead:E.totalCacheRead||0},toolCalls:em(m)}),process.exit(0)}function u(p){if(!r){i&&i.restore(),console.error(p.message),process.exit(1);return}r.restore(),io({type:"error",success:!1,error:p?.message||String(p)}),process.exit(1)}if(e.startsWith("/")){let{loadAllSkills:p,handleSkillCommand:h}=Ys();p();let m=h(e);if(m&&m.agentPrompt){let{processInput:y,getConversationMessages:b}=We();return y(m.agentPrompt,a,{autoOrchestrate:n,orchestratorModel:s}).then(()=>c(b)).catch(x=>u(x))}let{handleSlashCommand:g}=Gh();g(e,null).then(()=>{r&&(r.restore(),io({type:"done",success:!0,response:""})),process.exit(0)}).catch(y=>u(y));return}let{processInput:d,getConversationMessages:f}=We();r||(i=vD(),a=i.hooks),d(e,a,{autoOrchestrate:n,orchestratorModel:s}).then(()=>{try{let{writeDreamLog:p}=Su();p(f())}catch{}c(f)}).catch(p=>u(p))}if(_e.includes("--server")){let{setAutoConfirm:e}=un();e(!0),zx().startServerMode();return}if(_e.includes("--daemon")||_e.includes("--watch")){let e=_e.includes("--daemon")?_e.indexOf("--daemon"):_e.indexOf("--watch"),t=_e[e+1],n=t&&!t.startsWith("--")?t:".nex/daemon.json",{startDaemon:o}=Zx();o(n).catch(s=>{console.error("Daemon error:",s.message),process.exit(1)});return}var sv=_e.indexOf("--prompt-file");if(sv!==-1){let e=_e[sv+1];(!e||e.startsWith("--"))&&(console.error("--prompt-file requires a file path"),process.exit(1));let t=require("fs"),n;try{n=t.readFileSync(e,"utf-8").trim()}catch(o){console.error(`--prompt-file: cannot read file: ${o.message}`),process.exit(1)}if(n||(console.error("--prompt-file: file is empty"),process.exit(1)),_e.includes("--delete-prompt-file"))try{t.unlinkSync(e)}catch{}Qh(),nv(n)}else{let e=_e.indexOf("--task")!==-1?_e.indexOf("--task"):_e.indexOf("--prompt");if(e!==-1){let t=_e[e+1];if((!t||t.startsWith("--"))&&(console.error("--task/--prompt requires a prompt"),process.exit(1)),Qh(),_e.includes("--orchestrate")){let n=_e.indexOf("--orchestrator-model"),o=n!==-1?_e[n+1]:void 0,{runOrchestrated:s}=ya();s(t,{orchestratorModel:o}).then(()=>{process.exit(0)}).catch(r=>{console.error(`Orchestrator error: ${r.message}`),process.exit(1)})}else nv(t)}else bD().then(async()=>{if(Qh(),nm){let{setMaxIterations:n}=We();n(100)}if(_e.includes("--resume")){let{loadSession:n}=ds(),{setConversationMessages:o}=We(),s=n("_autosave");if(s&&s.messages&&s.messages.length>0){let i=s.messages,a=i.length>20?i.slice(-20):i;o(a);let{getUsage:c,forceCompress:u}=Mn();if(c(a,[]).percentage>=30){let{messages:p}=u(a,[]);o(p)}let{C:f}=dt();process.stdout.write(`${f.dim}Session restored (${a.length} messages)${f.reset}
2321
2324
  `)}else{let{C:r}=dt();process.stdout.write(`${r.yellow}No previous session found.${r.reset}
2322
2325
  `)}}let{startREPL:t}=ev();t(),setTimeout(async()=>{try{let{loadKnownModels:n,findNewModels:o}=xi(),s=n(),r=s.lastChecked?new Date(s.lastChecked):null;if((r?(Date.now()-r.getTime())/864e5:999)<7||!process.env.OLLAMA_API_KEY)return;let{newModels:a}=await o();if(a.length>0){let{C:c}=dt();process.stdout.write(`
2323
2326
  ${c.dim}\u{1F4A1} ${a.length} new Ollama Cloud model(s) available \u2014 /benchmark --discover to test them${c.reset}