nex-code 0.5.9 → 0.5.11
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/background-worker.js +447 -406
- package/dist/benchmark.js +522 -481
- package/dist/nex-code.js +598 -557
- package/package.json +1 -1
package/dist/benchmark.js
CHANGED
|
@@ -1,136 +1,136 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`),o=t("python3",["-c",e],{encoding:"buffer",timeout:400,stdio:["ignore","pipe","ignore"]}).toString("utf8").match(/rgb:([0-9a-fA-F]+)\/([0-9a-fA-F]+)\/([0-9a-fA-F]+)/);if(o){let r=parseInt(o[1].slice(0,2),16),i=parseInt(o[2].slice(0,2),16),a=parseInt(o[3].slice(0,2),16);return .299*r+.587*i+.114*a<128}}catch{}return null}function
|
|
1
|
+
"use strict";var va=Object.defineProperty;var R0=Object.getOwnPropertyDescriptor;var C0=Object.getOwnPropertyNames;var A0=Object.prototype.hasOwnProperty;var O0=(t,e)=>()=>(t&&(e=t(t=0)),e);var J=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),N0=(t,e)=>{for(var s in e)va(t,s,{get:e[s],enumerable:!0})},M0=(t,e,s,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of C0(e))!A0.call(t,o)&&o!==s&&va(t,o,{get:()=>e[o],enumerable:!(n=R0(e,o))||n.enumerable});return t};var P0=t=>M0(va({},"__esModule",{value:!0}),t);var Yt=J((f1,Wu)=>{"use strict";var ju="\x1B[0m",Du="\x1B[1m",Es="\x1B[2m";function G(t,e,s){return`\x1B[38;2;${t};${e};${s}m`}function L0(){if(!process.stdout.isTTY)return null;try{let{execFileSync:t}=require("child_process"),e=["import sys,os,tty,termios,select","f=open('/dev/tty','r+b',buffering=0)","fd=f.fileno()","s=termios.tcgetattr(fd)","try:"," tty.setraw(fd)"," f.write(bytes([0x1b,0x5d,0x31,0x31,0x3b,0x3f,0x1b,0x5c]))"," r=select.select([fd],[],[],0.1)[0]"," d=b''"," if r:"," while True:"," r2=select.select([fd],[],[],0.05)[0]"," if not r2:break"," c=os.read(fd,1)"," d+=c"," if d[-1:]==bytes([0x07]) or d[-2:]==bytes([0x1b,0x5c]):break"," sys.stdout.buffer.write(d)","finally:"," termios.tcsetattr(fd,termios.TCSADRAIN,s)"," f.close()"].join(`
|
|
2
|
+
`),o=t("python3",["-c",e],{encoding:"buffer",timeout:400,stdio:["ignore","pipe","ignore"]}).toString("utf8").match(/rgb:([0-9a-fA-F]+)\/([0-9a-fA-F]+)\/([0-9a-fA-F]+)/);if(o){let r=parseInt(o[1].slice(0,2),16),i=parseInt(o[2].slice(0,2),16),a=parseInt(o[3].slice(0,2),16);return .299*r+.587*i+.114*a<128}}catch{}return null}function qu(){let t=require("os");return require("path").join(t.homedir(),".nex-code",".theme_cache.json")}function I0(t){try{let s=require("fs").readFileSync(qu(),"utf8"),n=JSON.parse(s);if(n&&typeof n[t]=="boolean")return n[t]}catch(e){console.error("readThemeCache failed:",e.message)}return null}function j0(t,e){try{let s=require("fs"),n=require("path"),o=qu(),r=n.dirname(o),i={};try{i=JSON.parse(s.readFileSync(o,"utf8"))}catch(c){console.error("theme cache failed:",c.message)}i[t]=e;let a=Object.keys(i);a.length>50&&a.slice(0,a.length-50).forEach(c=>delete i[c]),s.existsSync(r)||s.mkdirSync(r,{recursive:!0}),s.writeFileSync(o,JSON.stringify(i),"utf8")}catch{}}function D0(){let t=(process.env.NEX_THEME||"").toLowerCase();if(t==="light")return!1;if(t==="dark")return!0;let e=process.env.COLORFGBG;if(e){let i=e.split(";"),a=parseInt(i[i.length-1],10);if(!isNaN(a))return a<8}let s=process.env.TERM_SESSION_ID||"default",n=I0(s);if(n!==null)return n;let o=L0(),r=o!==null?o:!0;return j0(s,r),r}var Fu=D0(),Bu={reset:ju,bold:Du,dim:Es,primary:G(80,190,255),secondary:G(60,170,190),success:G(80,210,120),warning:G(245,175,50),error:G(230,80,80),muted:Es,subtle:G(130,130,145),tool_read:G(80,190,255),tool_write:G(245,165,55),tool_exec:G(185,100,235),tool_search:G(70,185,190),tool_git:G(90,210,100),tool_web:G(100,215,250),tool_sysadmin:G(225,150,75),tool_default:G(100,205,115),syn_keyword:G(185,100,235),syn_string:G(90,210,120),syn_number:G(245,175,50),syn_comment:Es,syn_key:G(80,190,255),diff_add:G(80,210,120),diff_rem:G(230,80,80),banner_logo:G(80,200,255),banner_name:G(80,200,255),banner_version:Es,banner_model:Es,banner_yolo:G(245,175,50),banner_gemini:G(138,180,248),footer_sep:Es,footer_model:G(80,175,235),footer_branch:G(80,210,100),footer_project:G(130,130,145),footer_divider:G(80,80,95),footer_mode:G(210,150,50),white:G(210,210,220),red:G(220,85,85),green:G(80,200,110),yellow:G(230,185,60),blue:G(70,140,230),magenta:G(200,120,190),cyan:G(90,200,215),gray:G(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:G(110,215,230),brightMagenta:G(220,140,210),brightBlue:G(100,160,240)},Uu={reset:ju,bold:Du,dim:G(110,110,120),primary:G(0,110,190),secondary:G(0,125,148),success:G(0,148,62),warning:G(168,92,0),error:G(188,32,32),muted:G(110,110,120),subtle:G(155,155,165),tool_read:G(0,110,190),tool_write:G(168,92,0),tool_exec:G(128,42,188),tool_search:G(0,122,148),tool_git:G(0,138,62),tool_web:G(0,112,178),tool_sysadmin:G(168,82,0),tool_default:G(0,138,62),syn_keyword:G(128,42,188),syn_string:G(0,138,62),syn_number:G(168,92,0),syn_comment:G(135,135,148),syn_key:G(0,110,190),diff_add:G(0,148,62),diff_rem:G(188,32,32),banner_logo:G(0,122,205),banner_name:G(0,122,205),banner_version:G(100,100,118),banner_model:G(100,100,118),banner_yolo:G(168,62,0),banner_gemini:G(26,115,232),footer_sep:G(168,168,178),footer_model:G(0,102,175),footer_branch:G(0,138,62),footer_project:G(135,135,148),footer_divider:G(168,168,178),footer_mode:G(148,88,0),white:G(40,40,52),red:G(188,32,32),green:G(0,148,62),yellow:G(168,92,0),blue:G(0,110,190),magenta:G(128,42,188),cyan:G(0,125,148),gray:G(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:G(0,158,182),brightMagenta:G(158,52,208),brightBlue:G(0,112,208)},q0=Fu?Bu:Uu;Wu.exports={T:q0,isDark:Fu,DARK:Bu,LIGHT:Uu}});var Er=J((p1,F0)=>{F0.exports={name:"nex-code",version:"0.5.11",description:"Run 400B+ open coding models on your codebase without the hardware bill. Ollama Cloud first \u2014 OpenAI, Anthropic, and Gemini when you need them.",bin:{"nex-code":"./dist/nex-code.js"},files:["dist/","examples/","README.md","LICENSE"],engines:{node:">=18.0.0"},scripts:{start:"node dist/nex-code.js",build:"node scripts/build.js",dev:"node scripts/build.js --dev",test:"jest --forceExit --maxWorkers=50%","test:orchestrator":"jest tests/orchestrator.test.js --forceExit",coverage:"jest --coverage --forceExit","test:watch":"jest --watch",typecheck:"tsc --noEmit",format:"prettier --write .","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 Rs=J((h1,Yu)=>{var{T:se}=Yt(),Cr=5,Ts=(()=>{let t=[];for(let e=0;e<Cr;e++)t.push(e);for(let e=Cr-2;e>=1;e--)t.push(e);return t})(),Hu=["\u273D","\u2726","\u2727","\u2726"],Ea=class{constructor(e="Thinking..."){this.text=e,this.frame=0,this.interval=null,this.startTime=null}_render(){if(this._stopped)return;let e=Ts[this.frame%Ts.length],s="";for(let o=0;o<Cr;o++)s+=o===e?`${se.cyan}\u25CF${se.reset}`:" ";let n="";if(this.startTime){let o=Math.floor((Date.now()-this.startTime)/1e3);if(o>=60){let r=Math.floor(o/60),i=o%60;n=` ${se.dim}${r}m ${String(i).padStart(2,"0")}s${se.reset}`}else o>=1&&(n=` ${se.dim}${o}s${se.reset}`)}process.stderr.write(`\x1B[2K\r${s} ${se.dim}${this.text}${se.reset}${n}`),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),process.stderr.isTTY&&(process.stderr.write("\x1B[?25l"),this._render(),this.interval=setInterval(()=>this._render(),100))}update(e){this.text=e}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),process.stderr.isTTY&&process.stderr.write("\x1B[2K\r\x1B[?25h"),this.startTime=null}},Ta=class{constructor(e){this.labels=e,this.statuses=e.map(()=>"running"),this.frame=0,this.interval=null,this.startTime=null,this.lineCount=e.length}_formatElapsed(){if(!this.startTime)return"";let e=Math.floor((Date.now()-this.startTime)/1e3);if(e<1)return"";let s=Math.floor(e/60),n=e%60;return s>0?`${s}m ${String(n).padStart(2,"0")}s`:`${n}s`}_render(){if(this._stopped)return;let e=Ts[this.frame%Ts.length],s=`${se.cyan}\u25CF${se.reset}`,n=this._formatElapsed(),o=n?` ${se.dim}${n}${se.reset}`:"",r=process.stderr.columns||80,i="";for(let a=0;a<this.labels.length;a++){let c,l;switch(this.statuses[a]){case"done":c=`${se.green}\u2713${se.reset}`,l=se.dim;break;case"error":c=`${se.red}\u2717${se.reset}`,l=se.dim;break;case"retry":c=`${se.yellow}\u21BB${se.reset}`,l=se.yellow;break;default:c=a===e?s:" ",l=""}let u=a===this.labels.length-1?o:"",d=r-4-(u?n.length+1:0),f=this.labels[a].length>d?this.labels[a].substring(0,Math.max(10,d-3))+"...":this.labels[a];i+=`\x1B[2K ${c} ${l}${f}${se.reset}${u}
|
|
3
3
|
`}this.lineCount>0&&(i+=`\x1B[${this.lineCount}A`),process.stderr.write(i),this.frame++}start(){this._stopped=!1,this.startTime=Date.now();let e="\x1B[?25l";for(let s=0;s<this.lineCount;s++)e+=`
|
|
4
4
|
`;this.lineCount>0&&(e+=`\x1B[${this.lineCount}A`),process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),100)}update(e,s){e>=0&&e<this.statuses.length&&(this.statuses[e]=s)}stop(e={}){if(this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),!e.silent)this._renderFinal();else{let s="";for(let n=0;n<this.lineCount;n++)s+=`\x1B[2K
|
|
5
|
-
`;this.lineCount>0&&(s+=`\x1B[${this.lineCount}A`),process.stderr.write(s)}process.stderr.write("\x1B[?25h")}_renderFinal(){let e=this._formatElapsed(),s=e?` ${
|
|
6
|
-
`}process.stderr.write(o)}}
|
|
7
|
-
`;for(let a=0;a<this.tasks.length;a++){let
|
|
5
|
+
`;this.lineCount>0&&(s+=`\x1B[${this.lineCount}A`),process.stderr.write(s)}process.stderr.write("\x1B[?25h")}_renderFinal(){let e=this._formatElapsed(),s=e?` ${se.dim}${e}${se.reset}`:"",n=process.stderr.columns||80,o="";for(let r=0;r<this.labels.length;r++){let i;switch(this.statuses[r]){case"done":i=`${se.green}\u2713${se.reset}`;break;case"error":i=`${se.red}\u2717${se.reset}`;break;case"retry":i=`${se.yellow}\u21BB${se.reset}`;break;default:i=`${se.yellow}\u25CB${se.reset}`}let a=r===this.labels.length-1?s:"",c=n-4-(a?e.length+1:0),l=this.labels[r].length>c?this.labels[r].substring(0,Math.max(10,c-3))+"...":this.labels[r];o+=`\x1B[2K ${i} ${se.dim}${l}${se.reset}${a}
|
|
6
|
+
`}process.stderr.write(o)}},Tr={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},Rr={done:se.green,in_progress:se.cyan,pending:se.dim,failed:se.red},En=null,Ra=class{constructor(e,s){this.name=e,this.tasks=s.map(n=>({id:n.id,description:n.description,status:n.status||"pending"})),this.frame=0,this.interval=null,this.startTime=null,this.tokens=0,this.lineCount=1+this.tasks.length,this._paused=!1}_formatElapsed(){if(!this.startTime)return"";let e=Math.floor((Date.now()-this.startTime)/1e3);if(e<1)return"";let s=Math.floor(e/60),n=e%60;return s>0?`${s}m ${String(n).padStart(2,"0")}s`:`${n}s`}_formatTokens(){return this.tokens<=0?"":this.tokens>=1e3?`${(this.tokens/1e3).toFixed(1)}k`:String(this.tokens)}_render(){if(this._stopped)return;let e=Hu[this.frame%Hu.length],s=this._formatElapsed(),n=this._formatTokens(),o=[s,n?`\u2193 ${n} tokens`:""].filter(Boolean).join(" \xB7 "),r=o?` ${se.dim}(${o})${se.reset}`:"",i=`\x1B[2K${se.cyan}${e}${se.reset} ${this.name}\u2026${r}
|
|
7
|
+
`;for(let a=0;a<this.tasks.length;a++){let c=this.tasks[a],l=a===0?"\u23BF":" ",u=Tr[c.status]||Tr.pending,d=Rr[c.status]||Rr.pending,f=c.description.length>55?c.description.substring(0,52)+"...":c.description;i+=`\x1B[2K ${se.dim}${l}${se.reset} ${d}${u}${se.reset} ${f}
|
|
8
8
|
`}i+=`\x1B[${this.lineCount}A`,process.stderr.write(i),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),this._paused=!1;let e="\x1B[?25l";for(let s=0;s<this.lineCount;s++)e+=`
|
|
9
|
-
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120),
|
|
9
|
+
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120),En=this}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),this._paused||this._renderFinal(),process.stderr.write("\x1B[?25h"),this._paused=!1,En===this&&(En=null)}pause(){if(this._paused)return;this.interval&&(clearInterval(this.interval),this.interval=null);let e="";for(let s=0;s<this.lineCount;s++)e+=`\x1B[2K
|
|
10
10
|
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._paused=!0}resume(){if(!this._paused)return;this._paused=!1;let e="\x1B[?25l";for(let s=0;s<this.lineCount;s++)e+=`
|
|
11
|
-
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120)}updateTask(e,s){let n=this.tasks.find(o=>o.id===e);n&&(n.status=s)}setStats({tokens:e}){e!==void 0&&(this.tokens=e)}isActive(){return this.interval!==null||this._paused}_renderFinal(){let e=this._formatElapsed(),s=this.tasks.filter(a=>a.status==="done").length,n=this.tasks.filter(a=>a.status==="failed").length,o=this.tasks.length,r=n>0?`${s}/${o} done, ${n} failed`:`${s}/${o} done`,i=`\x1B[2K${
|
|
12
|
-
`;for(let a=0;a<this.tasks.length;a++){let
|
|
13
|
-
`}process.stderr.write(i)}}
|
|
11
|
+
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120)}updateTask(e,s){let n=this.tasks.find(o=>o.id===e);n&&(n.status=s)}setStats({tokens:e}){e!==void 0&&(this.tokens=e)}isActive(){return this.interval!==null||this._paused}_renderFinal(){let e=this._formatElapsed(),s=this.tasks.filter(a=>a.status==="done").length,n=this.tasks.filter(a=>a.status==="failed").length,o=this.tasks.length,r=n>0?`${s}/${o} done, ${n} failed`:`${s}/${o} done`,i=`\x1B[2K${se.green}\u2714${se.reset} ${this.name} ${se.dim}(${e} \xB7 ${r})${se.reset}
|
|
12
|
+
`;for(let a=0;a<this.tasks.length;a++){let c=this.tasks[a],l=a===0?"\u23BF":" ",u=Tr[c.status]||Tr.pending,d=Rr[c.status]||Rr.pending,f=c.description.length>55?c.description.substring(0,52)+"...":c.description;i+=`\x1B[2K ${se.dim}${l}${se.reset} ${d}${u}${se.reset} ${se.dim}${f}${se.reset}
|
|
13
|
+
`}process.stderr.write(i)}},Ca=class{constructor(e,s){this.toolName=e,this.message=s||`Running ${e}...`,this.count=0,this.total=null,this.detail="",this.frame=0,this.interval=null,this.startTime=null,this._stopped=!1}_render(){if(this._stopped||!process.stderr.isTTY)return;let e=Ts[this.frame%Ts.length],s="";for(let r=0;r<Cr;r++)s+=r===e?`${se.cyan}\u25CF${se.reset}`:" ";let n=this.message;this.count>0&&(n+=` ${se.cyan}${this.count}${se.reset}`,this.total&&(n+=`/${this.total}`),this.detail&&(n+=` ${se.dim}${this.detail}${se.reset}`));let o="";if(this.startTime){let r=Math.floor((Date.now()-this.startTime)/1e3);r>=1&&(o=` ${se.dim}${r}s${se.reset}`)}process.stderr.write(`\x1B[2K\r${s} ${se.dim}${n}${se.reset}${o}`),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),process.stderr.isTTY&&(process.stderr.write("\x1B[?25l"),this._render(),this.interval=setInterval(()=>this._render(),100))}update(e){e.count!==void 0&&(this.count=e.count),e.total!==void 0&&(this.total=e.total),e.detail!==void 0&&(this.detail=e.detail),e.message!==void 0&&(this.message=e.message)}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),process.stderr.isTTY&&process.stderr.write("\x1B[2K\r\x1B[?25h")}};function B0(t){En=t}function U0(){return En}function W0(){En&&(En.stop(),En=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}Yu.exports={C:se,Spinner:Ea,MultiProgress:Ta,TaskProgress:Ra,ToolProgress:Ca,setActiveTaskProgress:B0,getActiveTaskProgress:U0,cleanupTerminal:W0}});var Aa=J((m1,Vu)=>{"use strict";var{T:Bn}=Yt(),le={kw:Bn.syn_keyword,str:Bn.syn_string,cmt:Bn.syn_comment,num:Bn.syn_number,type:Bn.cyan,punct:Bn.magenta,reset:Bn.reset},Gu={js:new Set(["const","let","var","function","return","if","else","for","while","do","class","new","this","import","export","from","default","async","await","try","catch","finally","throw","typeof","instanceof","in","of","switch","case","break","continue","null","undefined","true","false","extends","super","static","get","set","delete","void","yield","interface","type","enum","namespace","abstract","implements","declare","module","require","readonly","keyof","infer","never","unknown","any","as","satisfies"]),py:new Set(["def","class","return","if","elif","else","for","while","with","as","import","from","pass","break","continue","try","except","finally","raise","in","not","and","or","is","lambda","yield","global","nonlocal","del","assert","True","False","None","async","await","self","cls","print","range","len","type","list","dict","set","tuple","str","int","float","bool","open","super","property","staticmethod","classmethod"]),sh:new Set(["if","then","else","elif","fi","for","while","do","done","case","esac","in","function","return","local","export","source","echo","exit","break","continue","readonly","unset","shift","trap","read"]),go:new Set(["func","return","if","else","for","range","type","struct","interface","import","package","var","const","defer","go","chan","select","case","default","break","continue","fallthrough","nil","true","false","make","new","len","cap","append","copy","delete","panic","recover","map","error","string","int","int64","int32","uint","bool","byte","rune"]),rs:new Set(["fn","let","mut","return","if","else","for","while","loop","match","use","mod","pub","struct","enum","impl","trait","where","const","static","type","move","ref","in","as","unsafe","extern","crate","self","Self","super","true","false","None","Some","Ok","Err","i32","i64","u32","u64","usize","f32","f64","bool","str","String","Vec"]),java:new Set(["class","interface","extends","implements","import","package","return","if","else","for","while","do","switch","case","break","continue","new","this","super","null","true","false","public","private","protected","static","final","abstract","void","int","long","double","float","boolean","char","byte","short","try","catch","finally","throw","throws","synchronized","volatile","transient","instanceof","enum","record"])},H0={js:"js",jsx:"js",ts:"js",tsx:"js",mjs:"js",cjs:"js",py:"py",css:"css",scss:"css",less:"css",sh:"sh",bash:"sh",zsh:"sh",go:"go",rs:"rs",java:"java",json:"json",html:"html",htm:"html",xml:"xml",md:"md"};function Ku(t){if(!t)return null;let e=t.split(".").pop().toLowerCase();return H0[e]||null}var zu=/\x1b\[[0-9;]*m/g;function hn(t,e,s){let n=t.split(zu),o=t.match(zu)||[],r="";for(let i=0;i<n.length;i++)r+=n[i].replace(e,s),i<o.length&&(r+=o[i]);return r}function Y0(t){let e=t;return e=e.replace(/"([^"\\]|\\.)*"\s*:/g,s=>le.type+s+le.reset),e=hn(e,/"([^"\\]|\\.)*"/g,s=>le.str+s+le.reset),e=hn(e,/\b-?(\d+(\.\d+)?([eE][+-]?\d+)?)\b/g,s=>le.num+s+le.reset),e=hn(e,/\b(true|false|null)\b/g,s=>le.kw+s+le.reset),e}function G0(t){if(/<!--/.test(t))return t.replace(/<!--[\s\S]*?(?:-->|$)/g,s=>le.cmt+s+le.reset);let e=t;return e=e.replace(/(<\/?)([a-zA-Z][a-zA-Z0-9.-]*)/g,(s,n,o)=>n+le.type+o+le.reset),e=hn(e,/\s([a-zA-Z][a-zA-Z0-9-]*)=/g,(s,n)=>" "+le.kw+n+le.reset+"="),e=hn(e,/"([^"]*)"/g,s=>le.str+s+le.reset),e}function z0(t){let e=t;return e=e.replace(/\/\*[\s\S]*?(?:\*\/|$)/g,s=>le.cmt+s+le.reset),e=hn(e,/#[0-9a-fA-F]{3,8}\b/g,s=>le.num+s+le.reset),e=hn(e,/\b(-?\d+(?:\.\d+)?)(px|em|rem|vh|vw|vmin|vmax|%|s|ms|deg|fr)\b/g,(s,n,o)=>le.num+n+le.reset+o),e=hn(e,/([a-z][a-z-]*)(\s*:)/g,(s,n,o)=>le.type+n+le.reset+o),e=hn(e,/"[^"]*"|'[^']*'/g,s=>le.str+s+le.reset),e}function Xu(t,e,s){if(e==="json")return Y0(t);if(e==="html"||e==="xml")return G0(t);if(e==="css")return z0(t);if(e==="md")return t;let n=Gu[e]||Gu.js,o="",r=0;if(s.inBlockComment){let i=t.indexOf("*/");if(i===-1)return le.cmt+t+le.reset;if(o+=le.cmt+t.slice(0,i+2)+le.reset,s.inBlockComment=!1,r=i+2,r>=t.length)return o}if(s.inString==="`"){let i=t.indexOf("`");if(i===-1)return le.str+t+le.reset;if(o+=le.str+t.slice(0,i+1)+le.reset,s.inString=null,r=i+1,r>=t.length)return o}for(;r<t.length;){let i=t[r];if(!s.inString&&i==="/"&&t[r+1]==="*"){let a=t.indexOf("*/",r+2);if(a===-1)return o+=le.cmt+t.slice(r)+le.reset,s.inBlockComment=!0,o;o+=le.cmt+t.slice(r,a+2)+le.reset,r=a+2;continue}if(!s.inString&&((e==="js"||e==="go"||e==="rs"||e==="java")&&i==="/"&&t[r+1]==="/"||(e==="py"||e==="sh")&&i==="#"))return o+=le.cmt+t.slice(r)+le.reset,o;if(!s.inString&&(i==='"'||i==="'"||i==="`")){s.inString=i,o+=le.str+i,r++;continue}if(s.inString){if(i==="\\"&&r+1<t.length){o+=i+t[r+1],r+=2;continue}if(i===s.inString){o+=i+le.reset,s.inString=null,r++;continue}o+=i,r++;continue}if(/[0-9]/.test(i)&&(r===0||!/[a-zA-Z0-9_$]/.test(t[r-1]))){let a="";for(;r<t.length&&/[0-9a-fA-F_.xXoObBeE+-]/.test(t[r])&&!(a.length>0&&/[eE]/.test(t[r-1])&&/[^+-]/.test(i));)a+=t[r++];o+=le.num+a+le.reset;continue}if(i==="@"&&(e==="js"||e==="java"||e==="py")){let a="@";for(r++;r<t.length&&/[a-zA-Z0-9_$.]/.test(t[r]);)a+=t[r++];o+=le.punct+a+le.reset;continue}if(/[a-zA-Z_$]/.test(i)){let a="";for(;r<t.length&&/[a-zA-Z0-9_$]/.test(t[r]);)a+=t[r++];n.has(a)?o+=le.kw+a+le.reset:/^[A-Z][A-Za-z0-9]*$/.test(a)&&e!=="sh"?o+=le.type+a+le.reset:o+=a;continue}o+=i,r++}return s.inString&&s.inString!=="`"&&(o+=le.reset,s.inString=null),o}function K0(t,e){let s=Ku(e);if(!s)return t.split(`
|
|
14
14
|
`);let n=t.split(`
|
|
15
|
-
`),o={inString:null,inBlockComment:!1};return n.map(r=>
|
|
16
|
-
`),n=s.slice(0,e),o=s.length-e,r=`${
|
|
15
|
+
`),o={inString:null,inBlockComment:!1};return n.map(r=>Xu(r,s,o))}function X0(t,e){return e?Xu(t,e,{inString:null,inBlockComment:!1}):t}Vu.exports={detectLang:Ku,highlightLine:X0,highlightLines:K0}});var Qu=J((g1,Zu)=>{var{T:C}=Yt(),lt=C,V0={read_file:C.tool_read,list_directory:C.tool_read,write_file:C.tool_write,edit_file:C.tool_write,patch_file:C.tool_write,bash:C.tool_exec,grep:C.tool_search,search_files:C.tool_search,glob:C.tool_search,git_commit:C.tool_git,git_push:C.tool_git,git_pull:C.tool_git,git_status:C.tool_git,git_diff:C.tool_git,git_log:C.tool_git,git_branch:C.tool_git,git_stash:C.tool_git,web_fetch:C.tool_web,web_search:C.tool_web,sysadmin:C.tool_sysadmin,ssh_exec:C.tool_sysadmin,ssh_upload:C.tool_sysadmin,ssh_download:C.tool_sysadmin,deploy:C.tool_sysadmin},Oa={read_file:"Read",write_file:"Write",edit_file:"Edit",patch_file:"Edit",list_directory:"List",bash:"Bash",grep:"Grep",search_files:"Search",glob:"Glob",web_fetch:"WebFetch",web_search:"WebSearch",git_status:"Bash",git_diff:"Bash",git_log:"Bash",git_commit:"Bash",git_push:"Bash",git_pull:"Bash",git_branch:"Bash",git_stash:"Bash",task_list:"TaskList",spawn_agents:"Agent",ask_user:"AskUser",switch_model:"SwitchModel",gh_run_list:"Bash",gh_run_view:"Bash",gh_workflow_trigger:"Bash",browser_open:"Browser",browser_screenshot:"Browser",browser_click:"Browser",browser_fill:"Browser",ssh_exec:"Bash",ssh_upload:"Upload",ssh_download:"Download",service_manage:"Bash",service_logs:"Bash",container_list:"Bash",container_logs:"Bash",container_exec:"Bash",brain_write:"Write",deploy:"Bash",frontend_recon:"Search"};function Ar(t,e=!1,s=null){if(e)return`${C.error}\u23FA${C.reset}`;let n=V0[t]||C.tool_default;return s==="blink"?`${n}\x1B[5m\u23FA\x1B[25m${C.reset}`:`${n}${s!==null?s:"\u23FA"}${C.reset}`}function J0(t,e,s=!1,n=null){let o=(t||[]).filter(c=>c&&c.canExecute!==!1);if(o.length===0)return`${Ar("",s,n)} Step ${e}`;if(o.length===1){let c=o[0],l=c.args||{},u=Oa[c.fnName]||c.fnName.replace(/_/g," "),d="";l.path?d=l._originalPath||l.path:l.command?d=String(l.command).substring(0,80):l.query?d=String(l.query).substring(0,60):l.pattern?d=String(l.pattern).substring(0,60):l.url&&(d=String(l.url).substring(0,60));let f=d?`(${lt.dim}${d}${lt.reset})`:"";return`${Ar(c.fnName,s,n)} ${lt.bold}${u}${lt.reset}${f}`}let r=o[0].fnName,i=[...new Set(o.map(c=>Oa[c.fnName]||c.fnName.replace(/_/g," ")))],a=i.length<=3?i.join(", "):`${o.length} tools`;return`${Ar(r,s,n)} ${lt.bold}${a}${lt.reset}`}function Z0(t,e){let s;switch(t){case"write_file":case"edit_file":case"patch_file":case"read_file":case"list_directory":s=e.path||"";break;case"bash":case"ssh_exec":s=(e.command||"").substring(0,80);break;case"grep":case"search_files":s=e.pattern?`"${e.pattern}"${e.path?` in ${e.path}`:""}`:"";break;case"glob":s=e.pattern||"";break;case"web_fetch":s=(e.url||"").substring(0,60);break;case"web_search":s=(e.query||"").substring(0,50);break;default:s=JSON.stringify(e).substring(0,80)}let n=Oa[t]||t.replace(/_/g," "),o=s?`(${lt.dim}${s}${lt.reset})`:"";return`${Ar(t)} ${lt.bold}${n}${lt.reset}${o}`}function Q0(t,e=8){let s=t.split(`
|
|
16
|
+
`),n=s.slice(0,e),o=s.length-e,r=`${C.muted} \u23BF ${C.reset}`,i=" ",a=n.map((c,l)=>`${l===0?r:i}${C.success}${c}${C.reset}`).join(`
|
|
17
17
|
`);return o>0&&(a+=`
|
|
18
|
-
${
|
|
19
|
-
`)[0];if(a.startsWith("BLOCKED:")){let d=a.replace(/^BLOCKED:\s*/,"").replace(/\s*—.*$/,"").replace(/\s*\(hard cap:.*?\)/,"").trim().substring(0,70);return` ${
|
|
20
|
-
${
|
|
21
|
-
`).filter(Boolean).filter(g=>!/^File:\s/.test(g)&&!/^\[LARGE FILE:/.test(g)),c
|
|
22
|
-
`).length,
|
|
18
|
+
${C.subtle} \u2026 +${o} lines${C.reset}`),a}var Or=["Sampling","Decoding","Attending","Inferring","Generating","Routing","Embedding","Reasoning","Tokenizing","Predicting"],Ju=Math.floor(Math.random()*Or.length),Na=null;function ew(t){Na=t}function tw(){let t=Or[Ju%Or.length];Ju++;let e=Na?` \xB7 ${Na}`:"";return`${t}${e}`}function nw(t,e){switch(t){case"bash":case"ask_user":case"write_file":case"edit_file":case"patch_file":case"task_list":case"spawn_agents":return null;case"read_file":return`Reading ${e.path||"file"}`;case"list_directory":return`Listing ${e.path||"."}`;case"search_files":return`Searching ${e.pattern||"..."}`;case"glob":return`Searching ${e.pattern||"..."}`;case"grep":return`Searching ${e.pattern||"..."}`;case"web_fetch":return`Fetching ${(e.url||"").substring(0,60)}`;case"web_search":return`Searching web: ${(e.query||"").substring(0,50)}`;case"git_status":return"Checking git status";case"git_diff":return`Diffing${e.file?` ${e.file}`:""}`;case"git_log":return`Reading git log${e.file?` (${e.file})`:""}`;case"gh_run_list":return`GitHub Actions: listing runs${e.workflow?` (${e.workflow})`:""}...`;case"gh_run_view":return`GitHub Actions: run ${e.run_id}...`;case"gh_workflow_trigger":return`GitHub Actions: trigger ${e.workflow}...`;case"browser_open":return`Browser: opening ${(e.url||"").substring(0,60)}...`;case"browser_screenshot":return`Browser: screenshot ${(e.url||"").substring(0,60)}...`;case"browser_click":return`Browser: clicking ${e.text||e.selector||"element"}...`;case"browser_fill":return`Browser: filling ${e.selector||"field"}...`;case"sysadmin":{let s=e.server&&e.server!=="local"?` [${e.server}]`:"";switch(e.action){case"audit":return`Sysadmin${s}: full audit...`;case"disk_usage":return`Sysadmin${s}: disk usage ${e.path||"/"}...`;case"process_list":return`Sysadmin${s}: top processes (${e.sort_by||"cpu"})...`;case"network_status":return`Sysadmin${s}: network status...`;case"ssl_check":return`Sysadmin${s}: SSL check ${e.domain||e.cert_path||""}...`;case"log_tail":return`Sysadmin${s}: tail ${e.path||"log"}...`;case"find_large":return`Sysadmin${s}: find large files in ${e.path||"/"}...`;case"service":return`Sysadmin${s}: service ${e.service_action||""} ${e.service_name||""}...`;case"kill_process":return`Sysadmin${s}: kill PID ${e.pid||e.process_name||"?"}...`;case"journalctl":return`Sysadmin${s}: journal ${e.unit?`[${e.unit}]`:""}${e.since?` since ${e.since}`:""}...`;case"package":return`Sysadmin${s}: package ${e.package_action||""} ${(e.packages||[]).join(" ")}...`;case"firewall":return`Sysadmin${s}: firewall ${e.firewall_action||""}...`;case"user_manage":return`Sysadmin${s}: user ${e.user_action||""} ${e.user||""}...`;case"cron":return`Sysadmin${s}: cron ${e.cron_action||""}...`;default:return`Sysadmin${s}: ${e.action}...`}}case"visual_diff":return"Comparing screenshots (pixel diff)...";case"responsive_sweep":return`Responsive sweep: ${(e.url||"").substring(0,50)}...`;case"visual_annotate":return`Annotating screenshot (${(e.annotations||[]).length} markers)...`;case"visual_watch":return`Visual watch: ${(e.url||"").substring(0,50)}...`;case"design_tokens":return"Extracting design tokens...";case"design_compare":return"Comparing against reference design...";default:return`Running: ${t}`}}function sw(t,e,s,n){let o=String(s||"");if(n){let a=o.split(`
|
|
19
|
+
`)[0];if(a.startsWith("BLOCKED:")){let d=a.replace(/^BLOCKED:\s*/,"").replace(/\s*—.*$/,"").replace(/\s*\(hard cap:.*?\)/,"").trim().substring(0,70);return` ${C.muted}\u23BF blocked: ${d}${C.reset}`}let c=a.replace(/^ERROR:\s*/i,"").substring(0,80),l=o.match(/\nHINT: (.+)/),u=l?`
|
|
20
|
+
${C.muted}${l[1].substring(0,100)}${C.reset}`:"";return` ${C.error}\u23BF ${c}${C.reset}${u}`}let r;switch(t){case"read_file":{let c=o.split(`
|
|
21
|
+
`).filter(Boolean).filter(g=>!/^File:\s/.test(g)&&!/^\[LARGE FILE:/.test(g)),l=c.length,u=c[c.length-1],d=u?parseInt(u.match(/^(\d+):/)?.[1]||"0"):0,f=e.line_start||e.line_end,p=e.path?require("path").basename(e.path):null,h=p?` ${C.muted}from ${p}${C.reset}`:"";f&&d>l?r=`Read lines ${e.line_start||1}\u2013${d}${h}`:r=`Read ${l} line${l!==1?"s":""}${h}`;break}case"write_file":{let c=(e.content||"").split(`
|
|
22
|
+
`).length,l=e.path?require("path").basename(e.path):null,u=l?`Wrote ${l} \xB7 ${c} line${c!==1?"s":""}`:`Wrote ${c} line${c!==1?"s":""}`,{highlightLines:d}=Aa(),f=d(e.content||"",e.path||null),p=40,h=8;if(c<=p){let g=f.map(w=>` ${w}`).join(`
|
|
23
23
|
`);r=`${u}
|
|
24
|
-
${g}`}else{let g=f.slice(0,
|
|
24
|
+
${g}`}else{let g=f.slice(0,h).map(w=>` ${w}`).join(`
|
|
25
25
|
`);r=`${u}
|
|
26
26
|
${g}
|
|
27
|
-
${
|
|
28
|
-
`),
|
|
29
|
-
`),
|
|
30
|
-
`+
|
|
31
|
-
`):"");break}case"patch_file":{let a=e.patches||[],
|
|
32
|
-
`).length,0),
|
|
33
|
-
`).length,0);r=`${
|
|
34
|
-
`).filter(f=>f&&!f.startsWith("EXIT ")&&!f.startsWith("HINT:")&&f.trim()),u=
|
|
35
|
-
`)}break}case"grep":case"search_files":{if(o.includes("(no matches)")||o==="no matches")r=`No matches${e.pattern?` ${
|
|
36
|
-
`).filter(Boolean),c
|
|
37
|
-
${
|
|
38
|
-
`)}break}case"glob":{let a=e.pattern?` ${
|
|
39
|
-
`).filter(Boolean),u=
|
|
40
|
-
`).filter(Boolean),
|
|
41
|
-
`).filter(
|
|
42
|
-
`).filter(d=>/^commit\s+[0-9a-f]{7}/.test(d)),
|
|
43
|
-
`).find((p,
|
|
44
|
-
|
|
45
|
-
`).filter(Boolean),
|
|
46
|
-
`)[0].replace(/^\d+\.\s*/,"").trim():null,u=
|
|
47
|
-
`).filter(d=>d.trim()&&!d.startsWith("EXIT ")),u=
|
|
27
|
+
${C.subtle}\u2026 +${c-h} lines${C.reset}`}break}case"edit_file":{let a=(e.old_text||"").split(`
|
|
28
|
+
`),c=(e.new_text||"").split(`
|
|
29
|
+
`),l=a.length,u=c.length,d=e.path?require("path").basename(e.path):null,f=d?` ${C.muted}${d}${C.reset}`:"",p=a.find(I=>I.trim()),h=c.find(I=>I.trim()),{highlightLine:g,detectLang:w}=Aa(),x=w(e.path||null),O=[];p&&O.push(` ${C.diff_rem}- ${C.reset}${g(p.trimEnd().substring(0,72),x)}${C.reset}`),h&&O.push(` ${C.diff_add}+ ${C.reset}${g(h.trimEnd().substring(0,72),x)}${C.reset}`),r=`${C.diff_rem}\u2212${l}${C.reset} ${C.diff_add}+${u}${C.reset}${f}`+(O.length>0?`
|
|
30
|
+
`+O.join(`
|
|
31
|
+
`):"");break}case"patch_file":{let a=e.patches||[],c=a.reduce((u,d)=>u+(d.old_text||"").split(`
|
|
32
|
+
`).length,0),l=a.reduce((u,d)=>u+(d.new_text||"").split(`
|
|
33
|
+
`).length,0);r=`${C.reset}${a.length} patch${a.length!==1?"es":""} ${C.diff_rem}\u2212${c}${C.reset} ${C.diff_add}+${l}${C.reset}`;break}case"bash":{let c=o.match(/^EXIT (\d+)/),l=o.split(`
|
|
34
|
+
`).filter(f=>f&&!f.startsWith("EXIT ")&&!f.startsWith("HINT:")&&f.trim()),u=c?c[1]==="0"?`${C.success}\u2713${C.reset}`:`${C.error}\u2717 Exit ${c[1]}${C.reset}`:`${C.success}\u2713${C.reset}`,d=o.match(/\nHINT: (.+)/);if(d)r=`${u} ${C.muted}\u2014 ${d[1].substring(0,100)}${C.reset}`;else if(l.length===0)r=u;else{let f=c&&c[1]!=="0",p=f?l.slice(-3):l.slice(0,3),h=l.length-3,g=p.map((w,x)=>x===0?`${u} ${C.muted}${w.substring(0,120)}${C.reset}`:` ${C.muted}${w.substring(0,120)}${C.reset}`);if(h>0){let w=f?` ${C.subtle}${h} lines above\u2026${C.reset}`:` ${C.subtle}\u2026 +${h} lines${C.reset}`;f?g.unshift(w):g.push(w)}r=g.join(`
|
|
35
|
+
`)}break}case"grep":case"search_files":{if(o.includes("(no matches)")||o==="no matches")r=`No matches${e.pattern?` ${C.muted}"${String(e.pattern).substring(0,40)}"${C.reset}`:""}`;else{let h=function(x){let O=x.indexOf(":");if(O===-1)return`${C.muted}${x.substring(0,90)}${C.reset}`;let I=x.substring(0,O),E=x.substring(O+1),v=E.match(/^(\d+)[:-](.*)/s),A=v?`:${v[1]}`:"",te=(v?v[2]:E).trim(),oe=`${C.subtle}${a.basename(I)}${A}${C.reset}`,de=`${C.muted}${te.substring(0,80)}${te.length>80?"\u2026":""}${C.reset}`;return`${oe} ${de}`};var i=h;let a=require("path"),c=o.split(`
|
|
36
|
+
`).filter(Boolean),l=c.length,d=new Set(c.map(x=>x.split(":")[0]).filter(Boolean)).size,f=e.pattern?` ${C.muted}"${String(e.pattern).substring(0,40)}"${C.reset}`:"",p=d>1?`${l} match${l!==1?"es":""} in ${d} files${f}`:`${l} match${l!==1?"es":""}${f}`,g=c.slice(0,3).map((x,O)=>O===0?`${p}
|
|
37
|
+
${h(x)}`:` ${h(x)}`),w=c.length-3;w>0&&g.push(` ${C.subtle}\u2026 +${w} lines${C.reset}`),r=g.join(`
|
|
38
|
+
`)}break}case"glob":{let a=e.pattern?` ${C.muted}${String(e.pattern).substring(0,50)}${C.reset}`:"";if(o==="(no matches)")r=`No files found${a}`;else{let c=require("path"),l=o.split(`
|
|
39
|
+
`).filter(Boolean),u=l.length,d=l.slice(0,5).map(h=>c.basename(h)),f=u-d.length,p=d.join(", ")+(f>0?`, +${f} more`:"");r=`${u} file${u!==1?"s":""}${a} \u2014 ${C.muted}${p}${C.reset}`}break}case"list_directory":{if(o==="(empty)")r="0 entries";else{let a=o.split(`
|
|
40
|
+
`).filter(Boolean),c=a.length,l=a.slice(0,6).join(", "),u=c-6;r=u>0?`${c} entries \u2014 ${C.muted}${l}, +${u} more${C.reset}`:`${c} entr${c!==1?"ies":"y"} \u2014 ${C.muted}${l}${C.reset}`}break}case"git_status":{let a=o.match(/Branch:\s*(\S+)/),c=o.split(`
|
|
41
|
+
`).filter(l=>/^\s*[MADRCU?!]/.test(l)).length;r=a?`${a[1]} \xB7 ${c} change${c!==1?"s":""}`:"Done";break}case"git_diff":{let a=(o.match(/^\+[^+]/gm)||[]).length,c=(o.match(/^-[^-]/gm)||[]).length;r=a||c?`+${a} \u2212${c} lines`:"No diff";break}case"git_log":{let a=o.split(`
|
|
42
|
+
`).filter(d=>/^commit\s+[0-9a-f]{7}/.test(d)),c=a.length,l=a[0]?a[0].replace(/^commit\s+/,"").substring(0,7):null,u=(()=>{let d=o.indexOf(a[0]||"\0");return d===-1?null:o.substring(d).split(`
|
|
43
|
+
`).find((p,h)=>h>0&&p.trim()&&!p.startsWith("Author:")&&!p.startsWith("Date:")&&!p.startsWith("Merge:"))})();if(c===0)r="Log retrieved";else if(l&&u){let d=c>1?` ${C.muted}+${c-1} more${C.reset}`:"";r=`${l} ${C.muted}${u.trim().substring(0,60)}${C.reset}${d}`}else r=`${c} commit${c!==1?"s":""}`;break}case"git_commit":{let a=o.match(/\[[\w./\-]+ ([0-9a-f]{7,})\]/),c=o.match(/\[[\w./\-]+ [0-9a-f]+\]\s+(.+)/);r=a?`${a[1]}${c?` \u2014 ${c[1].substring(0,55)}`:""}`:"Committed";break}case"git_push":{let a=o.match(/(?:->|→)\s*(\S+)/);r=a?`\u2192 ${a[1]}`:"Pushed";break}case"git_pull":{if(/Already up.to.date/i.test(o))r="Already up to date";else{let a=(o.match(/^\+/gm)||[]).length;r=a>0?`Pulled \xB7 +${a} lines`:"Pulled"}break}case"web_fetch":{let a=o.match(/<title[^>]*>([^<]{1,80})<\/title>/i),c=o.match(/^#\s+(.{1,80})/m),l=e.url||"",u="";try{u=new URL(l).hostname}catch{u=l.substring(0,60)}let d=a?a[1].trim():c?c[1].trim():null;r=d?`${u} \u2014 ${C.muted}${d.substring(0,70)}${C.reset}`:`Fetched ${u}`;break}case"web_search":{let a=o.split(`
|
|
44
|
+
|
|
45
|
+
`).filter(Boolean),c=a.length,l=a[0]?a[0].split(`
|
|
46
|
+
`)[0].replace(/^\d+\.\s*/,"").trim():null,u=l?` ${C.muted}\u2014 ${l.substring(0,70)}${C.reset}`:"";r=`${c} result${c!==1?"s":""}${u}`;break}case"task_list":r="Done";break;case"spawn_agents":{if(o.includes("Background agents started")){let l=o.match(/\bbg-[\w-]+/g),u=l?l.length:0;r=`${u} bg agent${u!==1?"s":""} started`;break}let a=(o.match(/✓ Agent/g)||[]).length,c=(o.match(/✗ Agent/g)||[]).length;r=c>0?`${a} done, ${c} failed`:`${a} agent${a!==1?"s":""} done`;break}case"switch_model":{let a=o.match(/Switched to (.+)/);r=a?`\u2192 ${a[1]}`:"Done";break}case"ssh_exec":{let c=o.startsWith("EXIT ")||o.startsWith("Command failed"),l=o.split(`
|
|
47
|
+
`).filter(d=>d.trim()&&!d.startsWith("EXIT ")),u=c?`${C.error}\u2717${C.reset}`:`${C.success}\u2713${C.reset}`;if(l.length===0)r=u;else{if(l.length>2&&l.every(g=>/^\[/.test(g.trim()))){r=`${u} ${l.length} log lines`;break}let f=c?l.slice(-3):l.slice(0,3),p=l.length-3,h=f.map((g,w)=>w===0?`${u} ${C.muted}${g.substring(0,120)}${C.reset}`:` ${C.muted}${g.substring(0,120)}${C.reset}`);if(p>0){let g=c?` ${C.subtle}${p} lines above\u2026${C.reset}`:` ${C.subtle}\u2026 +${p} lines${C.reset}`;c?h.unshift(g):h.push(g)}r=h.join(`
|
|
48
48
|
`)}break}default:{let a=o.split(`
|
|
49
|
-
`).filter(
|
|
50
|
-
${
|
|
51
|
-
`+
|
|
49
|
+
`).filter(c=>c.trim()&&!c.startsWith("EXIT ")&&!c.startsWith("HINT:"));if(a.length>0){let c=a[0].trim().substring(0,90),l=a.length>1?` ${C.subtle}\u2026 +${a.length-1} lines${C.reset}`:"";r=`${C.muted}${c}${C.reset}${l}`}else r="Done"}}return` ${C.muted}\u23BF ${r}${C.reset}`}function ow(t,e,s,n,o,r){let i=Math.round(n/1e3),a=i>=60?`${Math.floor(i/60)}m ${i%60}s`:`${i}s`,c=`
|
|
50
|
+
${C.success}\u25C6${lt.reset} ${lt.bold}${t}${lt.reset}`;return c+=`${lt.dim} \xB7 ${a}`,r.size>0&&(c+=` \xB7 ${r.size} file${r.size!==1?"s":""} modified`),c+=lt.reset,c}Zu.exports={C:lt,formatToolCall:Z0,formatResult:Q0,getToolSpinnerText:nw,formatToolSummary:sw,formatSectionHeader:J0,formatMilestone:ow,getThinkingVerb:tw,setActiveModelForSpinner:ew,THINKING_VERBS:Or}});var Je=J((y1,td)=>{var{T:Tn}=Yt(),Ma=Tn,ed=["01100110","01111110","01111110","01011010","01111110","00111100"];function rw(t,e){let s=[];for(let n=0;n<t.length;n+=2){let o="";for(let r=0;r<t[0].length;r++){let i=t[n][r]==="1",a=n+1<t.length&&t[n+1][r]==="1";i&&a?o+=`${e}\u2588\x1B[0m`:i&&!a?o+=`${e}\u2580\x1B[0m`:!i&&a?o+=`${e}\u2584\x1B[0m`:o+=" "}s.push(o)}return s}function iw(t,e,s={}){let n=Ma.bold,o=Ma.reset,r=rw(ed,Tn.banner_logo),i=s.yolo?` ${n}${Tn.banner_yolo}\u26A1 YOLO${o}`:"",a=s.gemini?` ${n}${Tn.banner_gemini}\u2726 GEMINI${o}`:"",c=Er().version,l=[` ${Tn.banner_name}${n}nex-code${o} ${Tn.banner_version}v${c}${o}`,` ${Tn.banner_model}${t}${o} ${Tn.muted}\xB7 /help${o}${a}${i}`,""],u=Math.max(r.length,l.length),d=Math.floor((u-r.length)/2),f=Math.floor((u-l.length)/2),p=ed[0].length,h=[];for(let g=0;g<u;g++){let w=r[g-d]??" ".repeat(p),x=l[g-f]??"";h.push(w+x)}console.log(`
|
|
51
|
+
`+h.join(`
|
|
52
52
|
`)+`
|
|
53
|
-
`)}var{Spinner:
|
|
54
|
-
`);this.buffer=s.pop()||"";for(let n of s){let o=this.parseLine(n);if(o?.done)return o}return{done:!1}}flush(){return this.buffer.trim()&&(this.parseLine(this.buffer),this.buffer=""),this.getResult()}parseLine(e){throw new Error("parseLine() not implemented")}getResult(){throw new Error("getResult() not implemented")}},vr=class extends Es{constructor(e,s={}){super(e,s),this.toolCallsMap={}}parseLine(e){let s=e.trim();if(!s||!s.startsWith("data: "))return{done:!1};let n=s.slice(6);if(n==="[DONE]")return{done:!0,result:this.getResult()};let o;try{o=JSON.parse(n)}catch{return{done:!1}}let r=o.choices?.[0]?.delta;if(!r)return{done:!1};if(r.content&&(this.onToken(r.content),this.content+=r.content),r.tool_calls)for(let i of r.tool_calls){let a;i.index!==void 0&&i.index!==null?a=i.index:i.id?a=`id:${i.id}`:a=0,this.toolCallsMap[a]||(this.toolCallsMap[a]={id:i.id||"",name:"",arguments:""}),i.id&&(this.toolCallsMap[a].id=i.id),i.function?.name&&(this.toolCallsMap[a].name+=i.function.name),i.function?.arguments&&(this.toolCallsMap[a].arguments+=i.function.arguments)}return{done:!1}}getResult(){return{content:this.content,tool_calls:Object.values(this.toolCallsMap).filter(e=>e.name).map(e=>({id:e.id||`call-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,function:{name:e.name,arguments:e.arguments}}))}}},Er=class extends vs{getEndpoint(){return"/chat/completions"}buildRequestBody({model:e,messages:s,tools:n,maxTokens:o,temperature:r,stream:i}){let a={model:e,messages:s,max_tokens:o,temperature:r};return i&&(a.stream=!0),n&&n.length>0&&(a.tools=n),a}normalizeResponse(e){let s=e.choices?.[0]?.message||{},n=(s.tool_calls||[]).map(o=>({id:o.id,function:{name:o.function.name,arguments:o.function.arguments}}));return{content:s.content||"",tool_calls:n}}createStreamParser(e,s={}){return new vr(e,s)}},Tr=class extends Es{constructor(e,s={}){super(e,s),this.toolUses=[],this.currentToolIndex=-1}parseLine(e){let s=e.trim();if(!s.startsWith("data: "))return{done:!1};let n=s.slice(6),o;try{o=JSON.parse(n)}catch{return{done:!1}}switch(o.type){case"content_block_start":{let r=o.content_block;r?.type==="tool_use"&&(this.currentToolIndex=this.toolUses.length,this.toolUses.push({id:r.id,name:r.name,inputJson:""}));break}case"content_block_delta":{let r=o.delta;r?.type==="text_delta"&&r.text&&(this.onToken(r.text),this.content+=r.text),r?.type==="input_json_delta"&&r.partial_json!==void 0&&this.currentToolIndex>=0&&(this.toolUses[this.currentToolIndex].inputJson+=r.partial_json);break}case"content_block_stop":this.currentToolIndex=-1;break;case"message_stop":return{done:!0,result:this.getResult()}}return{done:!1}}getResult(){return{content:this.content,tool_calls:this.toolUses.filter(e=>e.name).map(e=>{let s={};if(e.inputJson)try{s=JSON.parse(e.inputJson)}catch{s=e.inputJson}return{id:e.id||`anthropic-${Date.now()}`,function:{name:e.name,arguments:s}}})}}},Ea="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->",Rr=class extends vs{getEndpoint(){return"/messages"}buildRequestBody({model:e,messages:s,tools:n,maxTokens:o,temperature:r,stream:i,extra:a}){let l={model:e,messages:s,max_tokens:o,temperature:r};if(i&&(l.stream=!0),a?.system){let c=a.system,u=c.indexOf(Ea);if(u!==-1){let d=c.slice(0,u).trimEnd(),f=c.slice(u+Ea.length).trimStart();l.system=[{type:"text",text:d},{type:"text",text:f,cache_control:{type:"ephemeral"}}]}else l.system=c}return n&&n.length>0&&(l.tools=n),l}formatTools(e){return!e||e.length===0?[]:e.map(s=>({name:s.function.name,description:s.function.description||"",input_schema:s.function.parameters||{type:"object",properties:{}}}))}normalizeResponse(e){let s="",n=[];for(let o of e.content||[])o.type==="text"?s+=o.text:o.type==="tool_use"&&n.push({id:o.id,function:{name:o.name,arguments:o.input}});return{content:s,tool_calls:n}}createStreamParser(e,s={}){return new Tr(e,s)}};function Uu(t){if(t!==null&&typeof t=="object")return t;if(typeof t!="string")return t||{};try{return JSON.parse(t)}catch{}let e=t.replace(/,\s*([}\]])/g,"$1");e=e.replace(/([^\\])\n/g,"$1\\n");try{return JSON.parse(e)}catch{}return{}}var Cr=class extends Es{constructor(e,s={}){super(e,s),this.toolCalls=[],this.onThinkingToken=s.onThinkingToken||(()=>{})}parseLine(e){if(!e.trim())return{done:!1};let s;try{s=JSON.parse(e)}catch{return{done:!1}}return s.message?.thinking&&this.onThinkingToken(s.message.thinking),s.message?.content&&(this.onToken(s.message.content),this.content+=s.message.content),s.message?.tool_calls&&(this.toolCalls=this.toolCalls.concat(s.message.tool_calls)),s.done?{done:!0,result:this.getResult()}:{done:!1}}getResult(){return{content:this.content,tool_calls:this.toolCalls.map((e,s)=>({id:e.id||`ollama-${Date.now()}-${s}`,function:{name:e.function?.name||e.name||"unknown",arguments:Uu(e.function?.arguments??e.arguments)}}))}}},Ar=class extends vs{getEndpoint(){return"/api/chat"}buildRequestBody({model:e,messages:s,tools:n,maxTokens:o,temperature:r,stream:i,extra:a}){let l={model:e,messages:s,stream:i,options:{temperature:r,num_predict:o,repeat_penalty:a?.repeat_penalty??1.05}};return n&&n.length>0&&(l.tools=n),l}normalizeResponse(e){let s=e.message||{};return{content:s.content||"",tool_calls:(s.tool_calls||[]).map((n,o)=>({id:n.id||`ollama-${Date.now()}-${o}`,function:{name:n.function?.name||n.name||"unknown",arguments:Uu(n.function?.arguments??n.arguments)}}))}}createStreamParser(e,s={}){return new Cr(e,s)}},z0=new Er,K0=new Rr,X0=new Ar;Wu.exports={ANTHROPIC_CACHE_BOUNDARY:Ea,WireProtocol:vs,StreamParser:Es,OpenAICompatibleProtocol:Er,AnthropicProtocol:Rr,OllamaChatProtocol:Ar,OpenAIStreamParser:vr,AnthropicStreamParser:Tr,OllamaStreamParser:Cr,openaiProtocol:z0,anthropicProtocol:K0,ollamaProtocol:X0}});var Gu=Q((_R,Yu)=>{var Or=require("axios"),V0=require("http"),J0=require("https"),{BaseProvider:Z0,readStreamErrorBody:Q0}=Ss(),{ollamaProtocol:In}=Ts(),Nr=new V0.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Mr=new J0.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Hu={"qwen3-coder:480b":{id:"qwen3-coder:480b",name:"Qwen3 Coder 480B",maxTokens:16384,contextWindow:131072},"qwen3-coder-next":{id:"qwen3-coder-next",name:"Qwen3 Coder Next",maxTokens:16384,contextWindow:262144},"devstral-2:123b":{id:"devstral-2:123b",name:"Devstral 2 123B",maxTokens:16384,contextWindow:131072},"devstral-small-2:24b":{id:"devstral-small-2:24b",name:"Devstral Small 2 24B",maxTokens:16384,contextWindow:131072},"minimax-m2.7:cloud":{id:"minimax-m2.7:cloud",name:"MiniMax M2.7 Cloud",maxTokens:16384,contextWindow:131072},"kimi-k2.5":{id:"kimi-k2.5",name:"Kimi K2.5",maxTokens:16384,contextWindow:256e3},"kimi-k2:1t":{id:"kimi-k2:1t",name:"Kimi K2 1T",maxTokens:16384,contextWindow:256e3},"kimi-k2-thinking":{id:"kimi-k2-thinking",name:"Kimi K2 Thinking",maxTokens:16384,contextWindow:256e3},"deepseek-v3.2":{id:"deepseek-v3.2",name:"DeepSeek V3.2",maxTokens:16384,contextWindow:131072},"deepseek-v3.1:671b":{id:"deepseek-v3.1:671b",name:"DeepSeek V3.1 671B",maxTokens:16384,contextWindow:131072},"cogito-2.1:671b":{id:"cogito-2.1:671b",name:"Cogito 2.1 671B",maxTokens:16384,contextWindow:131072},"qwen3.5:397b-cloud":{id:"qwen3.5:397b-cloud",name:"Qwen3.5 397B Cloud",maxTokens:16384,contextWindow:262144},"qwen3.5:397b":{id:"qwen3.5:397b",name:"Qwen3.5 397B",maxTokens:16384,contextWindow:262144},"qwen3.5:122b-a10b":{id:"qwen3.5:122b-a10b",name:"Qwen3.5 122B-A10B",maxTokens:16384,contextWindow:262144},"qwen3.5:35b-a3b":{id:"qwen3.5:35b-a3b",name:"Qwen3.5 35B-A3B",maxTokens:16384,contextWindow:262144},"qwen3.5:27b":{id:"qwen3.5:27b",name:"Qwen3.5 27B",maxTokens:16384,contextWindow:262144},"qwen3-next:80b":{id:"qwen3-next:80b",name:"Qwen3 Next 80B",maxTokens:16384,contextWindow:131072},"mistral-large-3:675b":{id:"mistral-large-3:675b",name:"Mistral Large 3 675B",maxTokens:16384,contextWindow:131072},"gpt-oss:120b":{id:"gpt-oss:120b",name:"GPT-OSS 120B",maxTokens:16384,contextWindow:131072},"minimax-m2.5":{id:"minimax-m2.5",name:"MiniMax M2.5",maxTokens:16384,contextWindow:131072},"glm-5:cloud":{id:"glm-5:cloud",name:"GLM 5 Cloud",maxTokens:16384,contextWindow:2e5},"glm-5":{id:"glm-5",name:"GLM 5",maxTokens:16384,contextWindow:2e5},"glm-4.6":{id:"glm-4.6",name:"GLM 4.6",maxTokens:16384,contextWindow:2e5},"glm-4.7":{id:"glm-4.7",name:"GLM 4.7",maxTokens:16384,contextWindow:128e3},"nemotron-3-super:cloud":{id:"nemotron-3-super:cloud",name:"Nemotron 3 Super Cloud",maxTokens:16384,contextWindow:262144},"qwen3.5:9b":{id:"qwen3.5:9b",name:"Qwen3.5 9B",maxTokens:8192,contextWindow:262144},"qwen3.5:4b":{id:"qwen3.5:4b",name:"Qwen3.5 4B",maxTokens:8192,contextWindow:262144},"qwen3.5:2b":{id:"qwen3.5:2b",name:"Qwen3.5 2B",maxTokens:8192,contextWindow:262144},"qwen3.5:0.8b":{id:"qwen3.5:0.8b",name:"Qwen3.5 0.8B",maxTokens:8192,contextWindow:262144},"gemma3:27b":{id:"gemma3:27b",name:"Gemma 3 27B",maxTokens:8192,contextWindow:131072},"gemma3:12b":{id:"gemma3:12b",name:"Gemma 3 12B",maxTokens:8192,contextWindow:131072},"gemma3:4b":{id:"gemma3:4b",name:"Gemma 3 4B",maxTokens:8192,contextWindow:131072},"ministral-3:14b":{id:"ministral-3:14b",name:"Ministral 3 14B",maxTokens:8192,contextWindow:131072},"ministral-3:8b":{id:"ministral-3:8b",name:"Ministral 3 8B",maxTokens:8192,contextWindow:131072},"gemma4:e2b":{id:"gemma4:e2b",name:"Gemma 4 E2B",maxTokens:8192,contextWindow:131072},"gemma4:e4b":{id:"gemma4:e4b",name:"Gemma 4 E4B",maxTokens:8192,contextWindow:131072},"gemma4:26b-a4b":{id:"gemma4:26b-a4b",name:"Gemma 4 26B A4B",maxTokens:16384,contextWindow:262144},"gemma4:31b":{id:"gemma4:31b",name:"Gemma 4 31B",maxTokens:16384,contextWindow:262144},"gemma4:31b-cloud":{id:"gemma4:31b-cloud",name:"Gemma 4 31B Cloud",maxTokens:16384,contextWindow:262144},"gemini-3-flash-preview":{id:"gemini-3-flash-preview",name:"Gemini 3 Flash Preview",maxTokens:16384,contextWindow:131072}},Ta=class extends Z0{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||Hu,defaultModel:e.defaultModel||"qwen3-coder:480b",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this._discovered=!1}async discoverModels(){if(!this._discovered){if(this._discovered=!0,!process.stdout.isTTY){Or.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Nr,httpsAgent:Mr}).then(e=>{let s=e.data?.models||[];for(let n of s){let o=(n.name||n.model||"").replace(/:latest$/,"");!o||this.models[o]||(this.models[o]={id:o,name:n.name||o,maxTokens:16384,contextWindow:131072})}}).catch(()=>{});return}try{let s=(await Or.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Nr,httpsAgent:Mr})).data?.models||[];for(let n of s){let o=(n.name||n.model||"").replace(/:latest$/,"");!o||this.models[o]||(this.models[o]={id:o,name:n.name||o,maxTokens:16384,contextWindow:131072})}}catch{}}}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OLLAMA_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OLLAMA_API_KEY not set");return{Authorization:`Bearer ${e}`}}_formatMessages(e){return e.map(s=>{if(Array.isArray(s.content)){let n=[],o=[];for(let i of s.content)i.type==="text"?n.push(i.text??""):i.type==="image"&&i.data&&o.push(i.data);let r={role:s.role,content:n.join(`
|
|
55
|
-
`)};return o.length>0&&(r.images=o),s.tool_call_id&&(r.tool_call_id=s.tool_call_id),r}return s})}async chat(e,s,n={}){await this.discoverModels();let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||16384,a=
|
|
56
|
-
`)||JSON.stringify(e.content):s=typeof e.content=="string"?e.content:JSON.stringify(e.content),{role:"tool",content:s,tool_call_id:e.tool_call_id}}if(e.role==="user"&&Array.isArray(e.content)){let s=[];for(let n of e.content)if(n.type==="text")s.push({type:"text",text:n.text??""});else if(n.type==="image"&&n.data){let o=n.data.startsWith("data:")?n.data:`data:${n.media_type||"image/png"};base64,${n.data}`;s.push({type:"image_url",image_url:{url:o,detail:"auto"}})}return{role:"user",content:s}}return{role:e.role,content:e.content}}async chat(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||16384,{messages:a}=this.formatMessages(e),
|
|
57
|
-
|
|
58
|
-
`:"")+o.content;continue}if(o.role!=="system"&&o.role!=="tool"&&this._messageFormatCache.has(o)){n.push(this._messageFormatCache.get(o));continue}let r=this._formatSingleMessage(o,n);if(r){if(o.role!=="system"&&o.role!=="tool"&&this._messageStringCache.size<this._maxCacheSize){let i=this._getMessageCacheKey(o);this._messageStringCache.set(i,r),this._messageFormatCache.set(o,r)}n.push(r)}}for(let o=n.length-1;o>0;o--)n[o].role==="user"&&n[o-1].role==="user"&&n.splice(o,0,{role:"assistant",content:[{type:"text",text:"[continuing]"}]});return{messages:n,system:s}}_getMessageCacheKey(e){let s=e.role||"",n=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${s}:${n.length}:${o}`}_formatSingleMessage(e,s=[]){if(e.role==="assistant"){let n=[];if(e.content&&n.push({type:"text",text:e.content}),e.tool_calls)for(let o of e.tool_calls)n.push({type:"tool_use",id:o.id||`toolu-${Date.now()}`,name:o.function.name,input:typeof o.function.arguments=="string"?JSON.parse(o.function.arguments||"{}"):o.function.arguments||{}});return{role:"assistant",content:n.length>0?n:[{type:"text",text:""}]}}if(e.role==="tool"){let n=s[s.length-1],o;if(Array.isArray(e.content)){let i=[];for(let a of e.content)a.type==="text"?i.push({type:"text",text:a.text??""}):a.type==="image"&&a.data&&i.push({type:"image",source:{type:"base64",media_type:a.media_type||"image/png",data:a.data}});o=i}else o=typeof e.content=="string"?e.content:JSON.stringify(e.content);let r={type:"tool_result",tool_use_id:e.tool_call_id,content:o};return n&&n.role==="user"&&Array.isArray(n.content)&&n.content[0]?.type==="tool_result"?(n.content.push(r),null):{role:"user",content:[r]}}if(Array.isArray(e.content)){let n=[];for(let o of e.content)o.type==="text"?n.push({type:"text",text:o.text??""}):o.type==="image"&&o.data&&n.push({type:"image",source:{type:"base64",media_type:o.media_type||"image/png",data:o.data}});return{role:"user",content:n}}return{role:"user",content:e.content}}formatTools(e){return $n.formatTools(e)}_resolveModelId(e){return this.getModel(e)?.id||e}async chat(e,s,n={}){let o=n.model||this.defaultModel,r=this._resolveModelId(o),i=this.getModel(o),a=n.maxTokens||i?.maxTokens||8192,{messages:l,system:c}=this.formatMessages(e),u=this.formatTools(s),d=$n.buildRequestBody({model:r,messages:l,tools:u,maxTokens:a,temperature:n.temperature??this.temperature,stream:!1,extra:{system:c}}),f;try{f=await Ju.post(`${this.baseUrl}${$n.getEndpoint()}`,d,{timeout:n.timeout||this.timeout,headers:this._getHeaders()})}catch(p){if(p.name==="CanceledError"||p.name==="AbortError"||p.code==="ERR_CANCELED")throw p;let m=p.response?.status?` [HTTP ${p.response.status}]`:"",g=p.response?.data?.error?.message||p.response?.data?.error||p.message;throw new Error(`API Error${m}: ${g}`)}return $n.normalizeResponse(f.data)}async stream(e,s,n={}){let o=n.model||this.defaultModel,r=this._resolveModelId(o),i=this.getModel(o),a=n.maxTokens||i?.maxTokens||8192,l=n.onToken||(()=>{}),{messages:c,system:u}=this.formatMessages(e),d=this.formatTools(s),f=$n.buildRequestBody({model:r,messages:c,tools:d,maxTokens:a,temperature:n.temperature??this.temperature,stream:!0,extra:{system:u}}),p;try{p=await Ju.post(`${this.baseUrl}${$n.getEndpoint()}`,f,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(g){if(g.name==="CanceledError"||g.name==="AbortError"||g.code==="ERR_CANCELED")throw g;let _=g.response?.status?` [HTTP ${g.response.status}]`:"",b=await sw(g,A=>A?.error?.message||A?.error);throw new Error(`API Error${_}: ${b}`)}let m=$n.createStreamParser(l);return new Promise((g,_)=>{n.signal&&n.signal.addEventListener("abort",()=>{p.data.destroy(),_(new DOMException("The operation was aborted","AbortError"))},{once:!0}),p.data.on("data",b=>{let{done:A,result:P}=m.feed(b.toString());A&&g(P)}),p.data.on("error",b=>{n.signal?.aborted||_(new Error(`Stream error: ${b.message}`))}),p.data.on("end",()=>{g(m.flush())})})}normalizeResponse(e){return $n.normalizeResponse(e)}};Qu.exports={AnthropicProvider:Ca,ANTHROPIC_MODELS:Zu}});var od=Q((xR,sd)=>{var td=require("axios"),{BaseProvider:rw,readStreamErrorBody:iw}=Ss(),{openaiProtocol:jn}=Ts(),nd={"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}},Aa=class extends rw{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||nd,defaultModel:e.defaultModel||"gemini-2.5-flash",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("GEMINI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let s=[];for(let n of e){if(this._messageFormatCache.has(n)){s.push(this._messageFormatCache.get(n));continue}let o=this._getMessageCacheKey(n);if(this._messageStringCache.has(o)){let i=this._messageStringCache.get(o);this._messageFormatCache.set(n,i),s.push(i);continue}let r=this._formatSingleMessage(n);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(o,r),this._messageFormatCache.set(n,r),s.push(r)}return{messages:s}}_getMessageCacheKey(e){let s=e.role||"",n=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${s}:${n.length}:${o}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||"",tool_calls:e.tool_calls.map(s=>({id:s.id||`call-${Date.now()}`,type:"function",function:{name:s.function.name,arguments:typeof s.function.arguments=="string"?s.function.arguments:JSON.stringify(s.function.arguments)}}))};if(e.role==="tool")return{role:"tool",content:typeof e.content=="string"?e.content:JSON.stringify(e.content),tool_call_id:e.tool_call_id};if(e.role==="user"&&Array.isArray(e.content)){let s=[];for(let n of e.content)if(n.type==="text")s.push({type:"text",text:n.text??""});else if(n.type==="image"&&n.data){let o=n.data.startsWith("data:")?n.data:`data:${n.media_type||"image/png"};base64,${n.data}`;s.push({type:"image_url",image_url:{url:o,detail:"auto"}})}return{role:"user",content:s}}return{role:e.role,content:e.content}}async chat(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||8192,{messages:a}=this.formatMessages(e),l=jn.buildRequestBody({model:o,messages:a,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!1}),c;try{c=await td.post(`${this.baseUrl}${jn.getEndpoint()}`,l,{timeout:n.timeout||this.timeout,headers:this._getHeaders()})}catch(u){if(u.name==="CanceledError"||u.name==="AbortError"||u.code==="ERR_CANCELED")throw u;let d=u.response?.status?` [HTTP ${u.response.status}]`:"",f=u.response?.data?.error?.message||u.response?.data?.error||u.message;throw new Error(`API Error${d}: ${f}`)}return jn.normalizeResponse(c.data)}async stream(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||8192,a=n.onToken||(()=>{}),{messages:l}=this.formatMessages(e),c=jn.buildRequestBody({model:o,messages:l,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!0}),u;try{u=await td.post(`${this.baseUrl}${jn.getEndpoint()}`,c,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let p=f.response?.status?` [HTTP ${f.response.status}]`:"",m=await iw(f,g=>g?.error?.message||g?.error);throw new Error(`API Error${p}: ${m}`)}let d=jn.createStreamParser(a);return new Promise((f,p)=>{n.signal&&n.signal.addEventListener("abort",()=>{u.data.destroy(),p(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",m=>{let{done:g,result:_}=d.feed(m.toString());g&&f(_)}),u.data.on("error",m=>{n.signal?.aborted||p(new Error(`Stream error: ${m.message}`))}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return jn.normalizeResponse(e)}};sd.exports={GeminiProvider:Aa,GEMINI_MODELS:nd}});var ad=Q((kR,id)=>{var Pr=require("axios"),{BaseProvider:aw,readStreamErrorBody:lw}=Ss(),{ollamaProtocol:qn}=Ts(),rd="http://localhost:11434",Oa=class extends aw{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||rd,models:e.models||{},defaultModel:e.defaultModel||null,...e}),this.timeout=e.timeout||3e5,this.temperature=e.temperature??.2,this._modelsLoaded=!1}isConfigured(){return!0}async loadModels(){if(this._modelsLoaded)return this.models;try{let s=(await Pr.get(`${this.baseUrl}/api/tags`,{timeout:5e3})).data?.models||[];this.models={};for(let n of s){let o=n.name||n.model;if(!o)continue;let r=o.replace(/:latest$/,""),i=32768;try{let a=await Pr.post(`${this.baseUrl}/api/show`,{name:o},{timeout:5e3}),l=a.data?.model_info||a.data?.details||{};i=l["general.context_length"]||l["llama.context_length"]||this._parseContextFromModelfile(a.data?.modelfile)||32768}catch{}this.models[r]={id:r,name:n.name,maxTokens:Math.min(8192,Math.floor(i*.1)),contextWindow:i}}!this.defaultModel&&Object.keys(this.models).length>0&&(this.defaultModel=Object.keys(this.models)[0]),this._modelsLoaded=!0}catch{this.models={},this._modelsLoaded=!1}return this.models}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}_formatMessages(e){return e.map(s=>{if(s.role==="user"&&Array.isArray(s.content)){let n=[],o=[];for(let i of s.content)i.type==="text"?n.push(i.text??""):i.type==="image"&&i.data&&o.push(i.data);let r={role:"user",content:n.join(`
|
|
59
|
-
`)};return o.length>0&&(r.images=o),r}return s})}async chat(e,s,n={}){this._modelsLoaded||await this.loadModels();let o=n.model||this.defaultModel;if(!o)throw new Error("No local model available. Is Ollama running?");let r=
|
|
60
|
-
`)}}function
|
|
61
|
-
`)}function
|
|
62
|
-
`),a}catch(a){throw o.stop(),a}}async function
|
|
63
|
-
`){
|
|
53
|
+
`)}var{Spinner:aw,MultiProgress:cw,TaskProgress:lw,ToolProgress:uw,setActiveTaskProgress:dw,getActiveTaskProgress:fw,cleanupTerminal:pw}=Rs(),{formatToolCall:hw,formatResult:mw,getToolSpinnerText:gw,formatToolSummary:yw,formatSectionHeader:ww,formatMilestone:$w,getThinkingVerb:bw,setActiveModelForSpinner:_w}=Qu();td.exports={C:Ma,banner:iw,Spinner:aw,MultiProgress:cw,TaskProgress:lw,ToolProgress:uw,setActiveTaskProgress:dw,getActiveTaskProgress:fw,cleanupTerminal:pw,formatToolCall:hw,formatResult:mw,getToolSpinnerText:gw,formatToolSummary:yw,formatSectionHeader:ww,formatMilestone:$w,getThinkingVerb:bw,setActiveModelForSpinner:_w}});var Cs=J((w1,nd)=>{async function xw(t,e){if(!t.response?.data)return t.message;let s=t.response.data;if(typeof s=="object"&&s!==null&&typeof s.pipe!="function")return e(s)||t.message;try{let n=await new Promise((r,i)=>{let a=[];s.on("data",c=>a.push(c)),s.on("end",()=>r(Buffer.concat(a).toString("utf8"))),s.on("error",i)}),o=JSON.parse(n);return e(o)||n||t.message}catch{return t.message}}var Pa=class t{constructor(e={}){if(new.target===t)throw new Error("BaseProvider is abstract \u2014 use a concrete provider");this.name=e.name||"unknown",this.baseUrl=e.baseUrl||"",this.models=e.models||{},this.defaultModel=e.defaultModel||null}isConfigured(){throw new Error(`${this.name}: isConfigured() not implemented`)}getApiKey(){return null}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}getModel(e){return this.models[e]||null}async chat(e,s,n={}){throw new Error(`${this.name}: chat() not implemented`)}async stream(e,s,n={}){throw new Error(`${this.name}: stream() not implemented`)}formatMessages(e){return{messages:e}}formatTools(e){return e}normalizeResponse(e){throw new Error(`${this.name}: normalizeResponse() not implemented`)}};nd.exports={BaseProvider:Pa,readStreamErrorBody:xw}});var Ns=J(($1,od)=>{var As=class{buildRequestBody(e){throw new Error("buildRequestBody() not implemented")}getEndpoint(){throw new Error("getEndpoint() not implemented")}formatTools(e){return e}normalizeResponse(e){throw new Error("normalizeResponse() not implemented")}createStreamParser(e,s={}){throw new Error("createStreamParser() not implemented")}},Os=class{constructor(e,s={}){this.onToken=e,this.callbacks=s,this.content="",this.buffer=""}feed(e){this.buffer+=e;let s=this.buffer.split(`
|
|
54
|
+
`);this.buffer=s.pop()||"";for(let n of s){let o=this.parseLine(n);if(o?.done)return o}return{done:!1}}flush(){return this.buffer.trim()&&(this.parseLine(this.buffer),this.buffer=""),this.getResult()}parseLine(e){throw new Error("parseLine() not implemented")}getResult(){throw new Error("getResult() not implemented")}},Nr=class extends Os{constructor(e,s={}){super(e,s),this.toolCallsMap={}}parseLine(e){let s=e.trim();if(!s||!s.startsWith("data: "))return{done:!1};let n=s.slice(6);if(n==="[DONE]")return{done:!0,result:this.getResult()};let o;try{o=JSON.parse(n)}catch{return{done:!1}}let r=o.choices?.[0]?.delta;if(!r)return{done:!1};if(r.content&&(this.onToken(r.content),this.content+=r.content),r.tool_calls)for(let i of r.tool_calls){let a;i.index!==void 0&&i.index!==null?a=i.index:i.id?a=`id:${i.id}`:a=0,this.toolCallsMap[a]||(this.toolCallsMap[a]={id:i.id||"",name:"",arguments:""}),i.id&&(this.toolCallsMap[a].id=i.id),i.function?.name&&(this.toolCallsMap[a].name+=i.function.name),i.function?.arguments&&(this.toolCallsMap[a].arguments+=i.function.arguments)}return{done:!1}}getResult(){return{content:this.content,tool_calls:Object.values(this.toolCallsMap).filter(e=>e.name).map(e=>({id:e.id||`call-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,function:{name:e.name,arguments:e.arguments}}))}}},Mr=class extends As{getEndpoint(){return"/chat/completions"}buildRequestBody({model:e,messages:s,tools:n,maxTokens:o,temperature:r,stream:i}){let a={model:e,messages:s,max_tokens:o,temperature:r};return i&&(a.stream=!0),n&&n.length>0&&(a.tools=n),a}normalizeResponse(e){let s=e.choices?.[0]?.message||{},n=(s.tool_calls||[]).map(o=>({id:o.id,function:{name:o.function.name,arguments:o.function.arguments}}));return{content:s.content||"",tool_calls:n}}createStreamParser(e,s={}){return new Nr(e,s)}},Pr=class extends Os{constructor(e,s={}){super(e,s),this.toolUses=[],this.currentToolIndex=-1}parseLine(e){let s=e.trim();if(!s.startsWith("data: "))return{done:!1};let n=s.slice(6),o;try{o=JSON.parse(n)}catch{return{done:!1}}switch(o.type){case"content_block_start":{let r=o.content_block;r?.type==="tool_use"&&(this.currentToolIndex=this.toolUses.length,this.toolUses.push({id:r.id,name:r.name,inputJson:""}));break}case"content_block_delta":{let r=o.delta;r?.type==="text_delta"&&r.text&&(this.onToken(r.text),this.content+=r.text),r?.type==="input_json_delta"&&r.partial_json!==void 0&&this.currentToolIndex>=0&&(this.toolUses[this.currentToolIndex].inputJson+=r.partial_json);break}case"content_block_stop":this.currentToolIndex=-1;break;case"message_stop":return{done:!0,result:this.getResult()}}return{done:!1}}getResult(){return{content:this.content,tool_calls:this.toolUses.filter(e=>e.name).map(e=>{let s={};if(e.inputJson)try{s=JSON.parse(e.inputJson)}catch{s=e.inputJson}return{id:e.id||`anthropic-${Date.now()}`,function:{name:e.name,arguments:s}}})}}},La="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->",Lr=class extends As{getEndpoint(){return"/messages"}buildRequestBody({model:e,messages:s,tools:n,maxTokens:o,temperature:r,stream:i,extra:a}){let c={model:e,messages:s,max_tokens:o,temperature:r};if(i&&(c.stream=!0),a?.system){let l=a.system,u=l.indexOf(La);if(u!==-1){let d=l.slice(0,u).trimEnd(),f=l.slice(u+La.length).trimStart();c.system=[{type:"text",text:d},{type:"text",text:f,cache_control:{type:"ephemeral"}}]}else c.system=l}return n&&n.length>0&&(c.tools=n),c}formatTools(e){return!e||e.length===0?[]:e.map(s=>({name:s.function.name,description:s.function.description||"",input_schema:s.function.parameters||{type:"object",properties:{}}}))}normalizeResponse(e){let s="",n=[];for(let o of e.content||[])o.type==="text"?s+=o.text:o.type==="tool_use"&&n.push({id:o.id,function:{name:o.name,arguments:o.input}});return{content:s,tool_calls:n}}createStreamParser(e,s={}){return new Pr(e,s)}};function sd(t){if(t!==null&&typeof t=="object")return t;if(typeof t!="string")return t||{};try{return JSON.parse(t)}catch{}let e=t.replace(/,\s*([}\]])/g,"$1");e=e.replace(/([^\\])\n/g,"$1\\n");try{return JSON.parse(e)}catch{}return{}}var Ir=class extends Os{constructor(e,s={}){super(e,s),this.toolCalls=[],this.onThinkingToken=s.onThinkingToken||(()=>{})}parseLine(e){if(!e.trim())return{done:!1};let s;try{s=JSON.parse(e)}catch{return{done:!1}}return s.message?.thinking&&this.onThinkingToken(s.message.thinking),s.message?.content&&(this.onToken(s.message.content),this.content+=s.message.content),s.message?.tool_calls&&(this.toolCalls=this.toolCalls.concat(s.message.tool_calls)),s.done?{done:!0,result:this.getResult()}:{done:!1}}getResult(){return{content:this.content,tool_calls:this.toolCalls.map((e,s)=>({id:e.id||`ollama-${Date.now()}-${s}`,function:{name:e.function?.name||e.name||"unknown",arguments:sd(e.function?.arguments??e.arguments)}}))}}},jr=class extends As{getEndpoint(){return"/api/chat"}buildRequestBody({model:e,messages:s,tools:n,maxTokens:o,temperature:r,stream:i,extra:a}){let c={model:e,messages:s,stream:i,options:{temperature:r,num_predict:o,repeat_penalty:a?.repeat_penalty??1.05}};return n&&n.length>0&&(c.tools=n),c}normalizeResponse(e){let s=e.message||{};return{content:s.content||"",tool_calls:(s.tool_calls||[]).map((n,o)=>({id:n.id||`ollama-${Date.now()}-${o}`,function:{name:n.function?.name||n.name||"unknown",arguments:sd(n.function?.arguments??n.arguments)}}))}}createStreamParser(e,s={}){return new Ir(e,s)}},kw=new Mr,Sw=new Lr,vw=new jr;od.exports={ANTHROPIC_CACHE_BOUNDARY:La,WireProtocol:As,StreamParser:Os,OpenAICompatibleProtocol:Mr,AnthropicProtocol:Lr,OllamaChatProtocol:jr,OpenAIStreamParser:Nr,AnthropicStreamParser:Pr,OllamaStreamParser:Ir,openaiProtocol:kw,anthropicProtocol:Sw,ollamaProtocol:vw}});var ad=J((b1,id)=>{var Dr=require("axios"),Ew=require("http"),Tw=require("https"),{BaseProvider:Rw,readStreamErrorBody:Cw}=Cs(),{ollamaProtocol:Un}=Ns(),qr=new Ew.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Fr=new Tw.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),rd={"qwen3-coder:480b":{id:"qwen3-coder:480b",name:"Qwen3 Coder 480B",maxTokens:16384,contextWindow:131072},"qwen3-coder-next":{id:"qwen3-coder-next",name:"Qwen3 Coder Next",maxTokens:16384,contextWindow:262144},"devstral-2:123b":{id:"devstral-2:123b",name:"Devstral 2 123B",maxTokens:16384,contextWindow:131072},"devstral-small-2:24b":{id:"devstral-small-2:24b",name:"Devstral Small 2 24B",maxTokens:16384,contextWindow:131072},"minimax-m2.7:cloud":{id:"minimax-m2.7:cloud",name:"MiniMax M2.7 Cloud",maxTokens:16384,contextWindow:131072},"kimi-k2.5":{id:"kimi-k2.5",name:"Kimi K2.5",maxTokens:16384,contextWindow:256e3},"kimi-k2:1t":{id:"kimi-k2:1t",name:"Kimi K2 1T",maxTokens:16384,contextWindow:256e3},"kimi-k2-thinking":{id:"kimi-k2-thinking",name:"Kimi K2 Thinking",maxTokens:16384,contextWindow:256e3},"deepseek-v3.2":{id:"deepseek-v3.2",name:"DeepSeek V3.2",maxTokens:16384,contextWindow:131072},"deepseek-v3.1:671b":{id:"deepseek-v3.1:671b",name:"DeepSeek V3.1 671B",maxTokens:16384,contextWindow:131072},"cogito-2.1:671b":{id:"cogito-2.1:671b",name:"Cogito 2.1 671B",maxTokens:16384,contextWindow:131072},"qwen3.5:397b-cloud":{id:"qwen3.5:397b-cloud",name:"Qwen3.5 397B Cloud",maxTokens:16384,contextWindow:262144},"qwen3.5:397b":{id:"qwen3.5:397b",name:"Qwen3.5 397B",maxTokens:16384,contextWindow:262144},"qwen3.5:122b-a10b":{id:"qwen3.5:122b-a10b",name:"Qwen3.5 122B-A10B",maxTokens:16384,contextWindow:262144},"qwen3.5:35b-a3b":{id:"qwen3.5:35b-a3b",name:"Qwen3.5 35B-A3B",maxTokens:16384,contextWindow:262144},"qwen3.5:27b":{id:"qwen3.5:27b",name:"Qwen3.5 27B",maxTokens:16384,contextWindow:262144},"qwen3-next:80b":{id:"qwen3-next:80b",name:"Qwen3 Next 80B",maxTokens:16384,contextWindow:131072},"mistral-large-3:675b":{id:"mistral-large-3:675b",name:"Mistral Large 3 675B",maxTokens:16384,contextWindow:131072},"gpt-oss:120b":{id:"gpt-oss:120b",name:"GPT-OSS 120B",maxTokens:16384,contextWindow:131072},"minimax-m2.5":{id:"minimax-m2.5",name:"MiniMax M2.5",maxTokens:16384,contextWindow:131072},"glm-5:cloud":{id:"glm-5:cloud",name:"GLM 5 Cloud",maxTokens:16384,contextWindow:2e5},"glm-5":{id:"glm-5",name:"GLM 5",maxTokens:16384,contextWindow:2e5},"glm-4.6":{id:"glm-4.6",name:"GLM 4.6",maxTokens:16384,contextWindow:2e5},"glm-4.7":{id:"glm-4.7",name:"GLM 4.7",maxTokens:16384,contextWindow:128e3},"nemotron-3-super:cloud":{id:"nemotron-3-super:cloud",name:"Nemotron 3 Super Cloud",maxTokens:16384,contextWindow:262144},"qwen3.5:9b":{id:"qwen3.5:9b",name:"Qwen3.5 9B",maxTokens:8192,contextWindow:262144},"qwen3.5:4b":{id:"qwen3.5:4b",name:"Qwen3.5 4B",maxTokens:8192,contextWindow:262144},"qwen3.5:2b":{id:"qwen3.5:2b",name:"Qwen3.5 2B",maxTokens:8192,contextWindow:262144},"qwen3.5:0.8b":{id:"qwen3.5:0.8b",name:"Qwen3.5 0.8B",maxTokens:8192,contextWindow:262144},"gemma3:27b":{id:"gemma3:27b",name:"Gemma 3 27B",maxTokens:8192,contextWindow:131072},"gemma3:12b":{id:"gemma3:12b",name:"Gemma 3 12B",maxTokens:8192,contextWindow:131072},"gemma3:4b":{id:"gemma3:4b",name:"Gemma 3 4B",maxTokens:8192,contextWindow:131072},"ministral-3:14b":{id:"ministral-3:14b",name:"Ministral 3 14B",maxTokens:8192,contextWindow:131072},"ministral-3:8b":{id:"ministral-3:8b",name:"Ministral 3 8B",maxTokens:8192,contextWindow:131072},"gemma4:e2b":{id:"gemma4:e2b",name:"Gemma 4 E2B",maxTokens:8192,contextWindow:131072},"gemma4:e4b":{id:"gemma4:e4b",name:"Gemma 4 E4B",maxTokens:8192,contextWindow:131072},"gemma4:26b-a4b":{id:"gemma4:26b-a4b",name:"Gemma 4 26B A4B",maxTokens:16384,contextWindow:262144},"gemma4:31b":{id:"gemma4:31b",name:"Gemma 4 31B",maxTokens:16384,contextWindow:262144},"gemma4:31b-cloud":{id:"gemma4:31b-cloud",name:"Gemma 4 31B Cloud",maxTokens:16384,contextWindow:262144},"gemini-3-flash-preview":{id:"gemini-3-flash-preview",name:"Gemini 3 Flash Preview",maxTokens:16384,contextWindow:131072}},Ia=class extends Rw{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||rd,defaultModel:e.defaultModel||"qwen3-coder:480b",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this._discovered=!1}async discoverModels(){if(!this._discovered){if(this._discovered=!0,!process.stdout.isTTY){Dr.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:qr,httpsAgent:Fr}).then(e=>{let s=e.data?.models||[];for(let n of s){let o=(n.name||n.model||"").replace(/:latest$/,"");!o||this.models[o]||(this.models[o]={id:o,name:n.name||o,maxTokens:16384,contextWindow:131072})}}).catch(()=>{});return}try{let s=(await Dr.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:qr,httpsAgent:Fr})).data?.models||[];for(let n of s){let o=(n.name||n.model||"").replace(/:latest$/,"");!o||this.models[o]||(this.models[o]={id:o,name:n.name||o,maxTokens:16384,contextWindow:131072})}}catch{}}}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OLLAMA_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OLLAMA_API_KEY not set");return{Authorization:`Bearer ${e}`}}_formatMessages(e){return e.map(s=>{if(Array.isArray(s.content)){let n=[],o=[];for(let i of s.content)i.type==="text"?n.push(i.text??""):i.type==="image"&&i.data&&o.push(i.data);let r={role:s.role,content:n.join(`
|
|
55
|
+
`)};return o.length>0&&(r.images=o),s.tool_call_id&&(r.tool_call_id=s.tool_call_id),r}return s})}async chat(e,s,n={}){await this.discoverModels();let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||16384,a=Un.buildRequestBody({model:o,messages:this._formatMessages(e),tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!1,extra:{repeat_penalty:n.repeat_penalty}}),c;try{c=await Dr.post(`${this.baseUrl}${Un.getEndpoint()}`,a,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),httpAgent:qr,httpsAgent:Fr})}catch(l){if(l.name==="CanceledError"||l.name==="AbortError"||l.code==="ERR_CANCELED")throw l;let u=l.response?.status?` [HTTP ${l.response.status}]`:"",d=l.response?.data?.error||l.message;throw new Error(`API Error${u}: ${d}`)}return Un.normalizeResponse(c.data)}async stream(e,s,n={}){await this.discoverModels();let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||16384,a=n.onToken||(()=>{}),c=n.onThinkingToken||(()=>{}),l=Un.buildRequestBody({model:o,messages:this._formatMessages(e),tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!0,extra:{repeat_penalty:n.repeat_penalty}}),u;try{u=await Dr.post(`${this.baseUrl}${Un.getEndpoint()}`,l,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal,httpAgent:qr,httpsAgent:Fr})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let p=f.response?.status?` [HTTP ${f.response.status}]`:"",h=await Cw(f,w=>w?.error),g=new Error(`API Error${p}: ${h}`);throw g.code=f.code||(f.response?.status?`HTTP_${f.response.status}`:void 0),g}let d=Un.createStreamParser(a,{onThinkingToken:c});return new Promise((f,p)=>{n.signal&&n.signal.addEventListener("abort",()=>{u.data.destroy(),p(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",h=>{let{done:g,result:w}=d.feed(h.toString());g&&f(w)}),u.data.on("error",h=>{if(n.signal?.aborted)return;let g=new Error(`Stream error: ${h.message}`);g.code=h.code||h.name,p(g)}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return Un.normalizeResponse(e)}};id.exports={OllamaProvider:Ia,OLLAMA_MODELS:rd}});var dd=J((_1,ud)=>{var cd=require("axios"),{BaseProvider:Aw,readStreamErrorBody:Ow}=Cs(),{openaiProtocol:Wn}=Ns(),ld={"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}},ja=class extends Aw{constructor(e={}){super({name:"openai",baseUrl:e.baseUrl||"https://api.openai.com/v1",models:e.models||ld,defaultModel:e.defaultModel||"gpt-4o",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OPENAI_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OPENAI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let s=[];for(let n of e){if(this._messageFormatCache.has(n)){s.push(this._messageFormatCache.get(n));continue}let o=this._getMessageCacheKey(n);if(this._messageStringCache.has(o)){let i=this._messageStringCache.get(o);this._messageFormatCache.set(n,i),s.push(i);continue}let r=this._formatSingleMessage(n);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(o,r),this._messageFormatCache.set(n,r),s.push(r)}return{messages:s}}_getMessageCacheKey(e){let s=e.role||"",n=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${s}:${n.length}:${o}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||null,tool_calls:e.tool_calls.map(s=>({id:s.id||`call-${Date.now()}`,type:"function",function:{name:s.function.name,arguments:typeof s.function.arguments=="string"?s.function.arguments:JSON.stringify(s.function.arguments)}}))};if(e.role==="tool"){let s;return Array.isArray(e.content)?s=e.content.filter(o=>o.type==="text").map(o=>o.text).join(`
|
|
56
|
+
`)||JSON.stringify(e.content):s=typeof e.content=="string"?e.content:JSON.stringify(e.content),{role:"tool",content:s,tool_call_id:e.tool_call_id}}if(e.role==="user"&&Array.isArray(e.content)){let s=[];for(let n of e.content)if(n.type==="text")s.push({type:"text",text:n.text??""});else if(n.type==="image"&&n.data){let o=n.data.startsWith("data:")?n.data:`data:${n.media_type||"image/png"};base64,${n.data}`;s.push({type:"image_url",image_url:{url:o,detail:"auto"}})}return{role:"user",content:s}}return{role:e.role,content:e.content}}async chat(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||16384,{messages:a}=this.formatMessages(e),c=Wn.buildRequestBody({model:o,messages:a,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!1}),l;try{l=await cd.post(`${this.baseUrl}${Wn.getEndpoint()}`,c,{timeout:n.timeout||this.timeout,headers:this._getHeaders()})}catch(u){if(u.name==="CanceledError"||u.name==="AbortError"||u.code==="ERR_CANCELED")throw u;let d=u.response?.status?` [HTTP ${u.response.status}]`:"",f=u.response?.data?.error?.message||u.response?.data?.error||u.message;throw new Error(`API Error${d}: ${f}`)}return Wn.normalizeResponse(l.data)}async stream(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||16384,a=n.onToken||(()=>{}),{messages:c}=this.formatMessages(e),l=Wn.buildRequestBody({model:o,messages:c,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!0}),u;try{u=await cd.post(`${this.baseUrl}${Wn.getEndpoint()}`,l,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let p=f.response?.status?` [HTTP ${f.response.status}]`:"",h=await Ow(f,g=>g?.error?.message||g?.error);throw new Error(`API Error${p}: ${h}`)}let d=Wn.createStreamParser(a);return new Promise((f,p)=>{n.signal&&n.signal.addEventListener("abort",()=>{u.data.destroy(),p(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",h=>{let{done:g,result:w}=d.feed(h.toString());g&&f(w)}),u.data.on("error",h=>{n.signal?.aborted||p(new Error(`Stream error: ${h.message}`))}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return Wn.normalizeResponse(e)}};ud.exports={OpenAIProvider:ja,OPENAI_MODELS:ld}});var md=J((x1,hd)=>{var fd=require("axios"),{BaseProvider:Nw,readStreamErrorBody:Mw}=Cs(),{anthropicProtocol:Rn}=Ns(),pd={"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}},Pw="2023-06-01",Da=class extends Nw{constructor(e={}){super({name:"anthropic",baseUrl:e.baseUrl||"https://api.anthropic.com/v1",models:e.models||pd,defaultModel:e.defaultModel||"claude-sonnet",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this.apiVersion=e.apiVersion||Pw}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.ANTHROPIC_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("ANTHROPIC_API_KEY not set");return{"x-api-key":e,"anthropic-version":this.apiVersion,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let s="",n=[];for(let o of e){if(o.role==="system"){s+=(s?`
|
|
57
|
+
|
|
58
|
+
`:"")+o.content;continue}if(o.role!=="system"&&o.role!=="tool"&&this._messageFormatCache.has(o)){n.push(this._messageFormatCache.get(o));continue}let r=this._formatSingleMessage(o,n);if(r){if(o.role!=="system"&&o.role!=="tool"&&this._messageStringCache.size<this._maxCacheSize){let i=this._getMessageCacheKey(o);this._messageStringCache.set(i,r),this._messageFormatCache.set(o,r)}n.push(r)}}for(let o=n.length-1;o>0;o--)n[o].role==="user"&&n[o-1].role==="user"&&n.splice(o,0,{role:"assistant",content:[{type:"text",text:"[continuing]"}]});return{messages:n,system:s}}_getMessageCacheKey(e){let s=e.role||"",n=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${s}:${n.length}:${o}`}_formatSingleMessage(e,s=[]){if(e.role==="assistant"){let n=[];if(e.content&&n.push({type:"text",text:e.content}),e.tool_calls)for(let o of e.tool_calls)n.push({type:"tool_use",id:o.id||`toolu-${Date.now()}`,name:o.function.name,input:typeof o.function.arguments=="string"?JSON.parse(o.function.arguments||"{}"):o.function.arguments||{}});return{role:"assistant",content:n.length>0?n:[{type:"text",text:""}]}}if(e.role==="tool"){let n=s[s.length-1],o;if(Array.isArray(e.content)){let i=[];for(let a of e.content)a.type==="text"?i.push({type:"text",text:a.text??""}):a.type==="image"&&a.data&&i.push({type:"image",source:{type:"base64",media_type:a.media_type||"image/png",data:a.data}});o=i}else o=typeof e.content=="string"?e.content:JSON.stringify(e.content);let r={type:"tool_result",tool_use_id:e.tool_call_id,content:o};return n&&n.role==="user"&&Array.isArray(n.content)&&n.content[0]?.type==="tool_result"?(n.content.push(r),null):{role:"user",content:[r]}}if(Array.isArray(e.content)){let n=[];for(let o of e.content)o.type==="text"?n.push({type:"text",text:o.text??""}):o.type==="image"&&o.data&&n.push({type:"image",source:{type:"base64",media_type:o.media_type||"image/png",data:o.data}});return{role:"user",content:n}}return{role:"user",content:e.content}}formatTools(e){return Rn.formatTools(e)}_resolveModelId(e){return this.getModel(e)?.id||e}async chat(e,s,n={}){let o=n.model||this.defaultModel,r=this._resolveModelId(o),i=this.getModel(o),a=n.maxTokens||i?.maxTokens||8192,{messages:c,system:l}=this.formatMessages(e),u=this.formatTools(s),d=Rn.buildRequestBody({model:r,messages:c,tools:u,maxTokens:a,temperature:n.temperature??this.temperature,stream:!1,extra:{system:l}}),f;try{f=await fd.post(`${this.baseUrl}${Rn.getEndpoint()}`,d,{timeout:n.timeout||this.timeout,headers:this._getHeaders()})}catch(p){if(p.name==="CanceledError"||p.name==="AbortError"||p.code==="ERR_CANCELED")throw p;let h=p.response?.status?` [HTTP ${p.response.status}]`:"",g=p.response?.data?.error?.message||p.response?.data?.error||p.message;throw new Error(`API Error${h}: ${g}`)}return Rn.normalizeResponse(f.data)}async stream(e,s,n={}){let o=n.model||this.defaultModel,r=this._resolveModelId(o),i=this.getModel(o),a=n.maxTokens||i?.maxTokens||8192,c=n.onToken||(()=>{}),{messages:l,system:u}=this.formatMessages(e),d=this.formatTools(s),f=Rn.buildRequestBody({model:r,messages:l,tools:d,maxTokens:a,temperature:n.temperature??this.temperature,stream:!0,extra:{system:u}}),p;try{p=await fd.post(`${this.baseUrl}${Rn.getEndpoint()}`,f,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(g){if(g.name==="CanceledError"||g.name==="AbortError"||g.code==="ERR_CANCELED")throw g;let w=g.response?.status?` [HTTP ${g.response.status}]`:"",x=await Mw(g,O=>O?.error?.message||O?.error);throw new Error(`API Error${w}: ${x}`)}let h=Rn.createStreamParser(c);return new Promise((g,w)=>{n.signal&&n.signal.addEventListener("abort",()=>{p.data.destroy(),w(new DOMException("The operation was aborted","AbortError"))},{once:!0}),p.data.on("data",x=>{let{done:O,result:I}=h.feed(x.toString());O&&g(I)}),p.data.on("error",x=>{n.signal?.aborted||w(new Error(`Stream error: ${x.message}`))}),p.data.on("end",()=>{g(h.flush())})})}normalizeResponse(e){return Rn.normalizeResponse(e)}};hd.exports={AnthropicProvider:Da,ANTHROPIC_MODELS:pd}});var $d=J((k1,wd)=>{var gd=require("axios"),{BaseProvider:Lw,readStreamErrorBody:Iw}=Cs(),{openaiProtocol:Hn}=Ns(),yd={"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}},qa=class extends Lw{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||yd,defaultModel:e.defaultModel||"gemini-2.5-flash",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("GEMINI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let s=[];for(let n of e){if(this._messageFormatCache.has(n)){s.push(this._messageFormatCache.get(n));continue}let o=this._getMessageCacheKey(n);if(this._messageStringCache.has(o)){let i=this._messageStringCache.get(o);this._messageFormatCache.set(n,i),s.push(i);continue}let r=this._formatSingleMessage(n);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(o,r),this._messageFormatCache.set(n,r),s.push(r)}return{messages:s}}_getMessageCacheKey(e){let s=e.role||"",n=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${s}:${n.length}:${o}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||"",tool_calls:e.tool_calls.map(s=>({id:s.id||`call-${Date.now()}`,type:"function",function:{name:s.function.name,arguments:typeof s.function.arguments=="string"?s.function.arguments:JSON.stringify(s.function.arguments)}}))};if(e.role==="tool")return{role:"tool",content:typeof e.content=="string"?e.content:JSON.stringify(e.content),tool_call_id:e.tool_call_id};if(e.role==="user"&&Array.isArray(e.content)){let s=[];for(let n of e.content)if(n.type==="text")s.push({type:"text",text:n.text??""});else if(n.type==="image"&&n.data){let o=n.data.startsWith("data:")?n.data:`data:${n.media_type||"image/png"};base64,${n.data}`;s.push({type:"image_url",image_url:{url:o,detail:"auto"}})}return{role:"user",content:s}}return{role:e.role,content:e.content}}async chat(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||8192,{messages:a}=this.formatMessages(e),c=Hn.buildRequestBody({model:o,messages:a,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!1}),l;try{l=await gd.post(`${this.baseUrl}${Hn.getEndpoint()}`,c,{timeout:n.timeout||this.timeout,headers:this._getHeaders()})}catch(u){if(u.name==="CanceledError"||u.name==="AbortError"||u.code==="ERR_CANCELED")throw u;let d=u.response?.status?` [HTTP ${u.response.status}]`:"",f=u.response?.data?.error?.message||u.response?.data?.error||u.message;throw new Error(`API Error${d}: ${f}`)}return Hn.normalizeResponse(l.data)}async stream(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||8192,a=n.onToken||(()=>{}),{messages:c}=this.formatMessages(e),l=Hn.buildRequestBody({model:o,messages:c,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!0}),u;try{u=await gd.post(`${this.baseUrl}${Hn.getEndpoint()}`,l,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let p=f.response?.status?` [HTTP ${f.response.status}]`:"",h=await Iw(f,g=>g?.error?.message||g?.error);throw new Error(`API Error${p}: ${h}`)}let d=Hn.createStreamParser(a);return new Promise((f,p)=>{n.signal&&n.signal.addEventListener("abort",()=>{u.data.destroy(),p(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",h=>{let{done:g,result:w}=d.feed(h.toString());g&&f(w)}),u.data.on("error",h=>{n.signal?.aborted||p(new Error(`Stream error: ${h.message}`))}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return Hn.normalizeResponse(e)}};wd.exports={GeminiProvider:qa,GEMINI_MODELS:yd}});var xd=J((S1,_d)=>{var Br=require("axios"),{BaseProvider:jw,readStreamErrorBody:Dw}=Cs(),{ollamaProtocol:Yn}=Ns(),bd="http://localhost:11434",Fa=class extends jw{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||bd,models:e.models||{},defaultModel:e.defaultModel||null,...e}),this.timeout=e.timeout||3e5,this.temperature=e.temperature??.2,this._modelsLoaded=!1}isConfigured(){return!0}async loadModels(){if(this._modelsLoaded)return this.models;try{let s=(await Br.get(`${this.baseUrl}/api/tags`,{timeout:5e3})).data?.models||[];this.models={};for(let n of s){let o=n.name||n.model;if(!o)continue;let r=o.replace(/:latest$/,""),i=32768;try{let a=await Br.post(`${this.baseUrl}/api/show`,{name:o},{timeout:5e3}),c=a.data?.model_info||a.data?.details||{};i=c["general.context_length"]||c["llama.context_length"]||this._parseContextFromModelfile(a.data?.modelfile)||32768}catch{}this.models[r]={id:r,name:n.name,maxTokens:Math.min(8192,Math.floor(i*.1)),contextWindow:i}}!this.defaultModel&&Object.keys(this.models).length>0&&(this.defaultModel=Object.keys(this.models)[0]),this._modelsLoaded=!0}catch{this.models={},this._modelsLoaded=!1}return this.models}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}_formatMessages(e){return e.map(s=>{if(s.role==="user"&&Array.isArray(s.content)){let n=[],o=[];for(let i of s.content)i.type==="text"?n.push(i.text??""):i.type==="image"&&i.data&&o.push(i.data);let r={role:"user",content:n.join(`
|
|
59
|
+
`)};return o.length>0&&(r.images=o),r}return s})}async chat(e,s,n={}){this._modelsLoaded||await this.loadModels();let o=n.model||this.defaultModel;if(!o)throw new Error("No local model available. Is Ollama running?");let r=Yn.buildRequestBody({model:o,messages:this._formatMessages(e),tools:s,maxTokens:n.maxTokens||8192,temperature:n.temperature??this.temperature,stream:!1}),i;try{i=await Br.post(`${this.baseUrl}${Yn.getEndpoint()}`,r,{timeout:n.timeout||this.timeout})}catch(a){if(a.name==="CanceledError"||a.name==="AbortError"||a.code==="ERR_CANCELED")throw a;let c=a.response?.status?` [HTTP ${a.response.status}]`:"",l=a.response?.data?.error||a.message;throw new Error(`API Error${c}: ${l}`)}return Yn.normalizeResponse(i.data)}async stream(e,s,n={}){this._modelsLoaded||await this.loadModels();let o=n.model||this.defaultModel;if(!o)throw new Error("No local model available. Is Ollama running?");let r=n.onToken||(()=>{}),i=Yn.buildRequestBody({model:o,messages:this._formatMessages(e),tools:s,maxTokens:n.maxTokens||8192,temperature:n.temperature??this.temperature,stream:!0}),a;try{a=await Br.post(`${this.baseUrl}${Yn.getEndpoint()}`,i,{timeout:n.timeout||this.timeout,responseType:"stream",signal:n.signal})}catch(l){if(l.name==="CanceledError"||l.name==="AbortError"||l.code==="ERR_CANCELED")throw l;let u=l.response?.status?` [HTTP ${l.response.status}]`:"",d=await Dw(l,f=>f?.error);throw new Error(`API Error${u}: ${d}`)}let c=Yn.createStreamParser(r);return new Promise((l,u)=>{n.signal&&n.signal.addEventListener("abort",()=>{a.data.destroy(),u(new DOMException("The operation was aborted","AbortError"))},{once:!0}),a.data.on("data",d=>{let{done:f,result:p}=c.feed(d.toString());f&&l(p)}),a.data.on("error",d=>{n.signal?.aborted||u(new Error(`Stream error: ${d.message}`))}),a.data.on("end",()=>{l(c.flush())})})}normalizeResponse(e){return Yn.normalizeResponse(e)}_parseContextFromModelfile(e){if(!e)return null;let s=e.match(/PARAMETER\s+num_ctx\s+(\d+)/i);return s?parseInt(s[1],10):null}};_d.exports={LocalProvider:Fa,DEFAULT_LOCAL_URL:bd}});var Gn=J((v1,Sd)=>{"use strict";var vt=require("fs"),kd=require("path");function qw(t){if(!t||isNaN(t))return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function Fw(t){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}catch{let e=Date.now()+t;for(;Date.now()<e;);}}function Bw(t,e){let s=kd.dirname(t),n=kd.join(s,`.nex-tmp.${process.pid}.${Date.now()}`);try{vt.existsSync(s)||vt.mkdirSync(s,{recursive:!0,mode:448}),vt.writeFileSync(n,e,{encoding:"utf-8",mode:384}),vt.renameSync(n,t)}catch(o){try{vt.unlinkSync(n)}catch{}throw o}}function Uw(t,e,{timeout:s=5e3,retryMs:n=50}={}){let o=t+".lock",r=Date.now()+s;for(;;){let i=-1;try{i=vt.openSync(o,"wx"),vt.writeSync(i,Buffer.from(String(process.pid))),vt.closeSync(i),i=-1;try{return e()}finally{try{vt.unlinkSync(o)}catch{}}}catch(a){if(i!==-1)try{vt.closeSync(i)}catch{}if(a.code!=="EEXIST")throw a;try{let c=vt.readFileSync(o,"utf-8").trim(),l=parseInt(c,10);if(!qw(l)){try{vt.unlinkSync(o)}catch{}continue}}catch(c){if(c.code&&c.code!=="ENOENT")throw c;continue}if(Date.now()>=r){try{vt.unlinkSync(o)}catch{}return e()}Fw(n)}}}Sd.exports={atomicWrite:Bw,withFileLockSync:Uw}});var Wr=J((E1,Nd)=>{var Ms=require("fs"),Ba=require("path"),{T:vd}=Yt(),{atomicWrite:Ww,withFileLockSync:Hw}=Gn(),Ed={openai:{"gpt-4o":{input:2.5,output:10},"gpt-4o-mini":{input:.15,output:.6},"gpt-4.1":{input:2,output:8},"gpt-4.1-mini":{input:.4,output:1.6},"gpt-4.1-nano":{input:.1,output:.4},o1:{input:15,output:60},o3:{input:10,output:40},"o3-mini":{input:1.1,output:4.4},"o4-mini":{input:1.1,output:4.4}},anthropic:{"claude-sonnet":{input:3,output:15},"claude-opus":{input:5,output:25},"claude-haiku":{input:.8,output:4},"claude-sonnet-4-5":{input:3,output:15},"claude-sonnet-4":{input:3,output:15}},gemini:{"gemini-2.5-pro":{input:1.25,output:10},"gemini-2.5-flash":{input:.15,output:.6},"gemini-2.0-flash":{input:.1,output:.4},"gemini-2.0-flash-lite":{input:.075,output:.3}},ollama:{"qwen3-coder:480b":{input:0,output:0},"qwen3-coder-next":{input:0,output:0},"devstral-2:123b":{input:0,output:0},"devstral-small-2:24b":{input:0,output:0},"kimi-k2.5":{input:0,output:0},"kimi-k2:1t":{input:0,output:0},"deepseek-v3.2":{input:0,output:0},"minimax-m2.5":{input:0,output:0},"glm-5":{input:0,output:0},"glm-4.7":{input:0,output:0},"gpt-oss:120b":{input:0,output:0}},local:{}},Ur=[],Cn={};function Yw(t,e,s,n,o=0){if(Ur.push({provider:t,model:e,input:s,output:n,cacheRead:o}),Cn[t]!==void 0){let r=Ad(t);r.allowed||process.stderr.write(`${vd.yellow}\u26A0 Budget limit reached for ${t}: $${r.spent.toFixed(2)} / $${r.limit.toFixed(2)}${vd.reset}
|
|
60
|
+
`)}}function Ua(t,e){let s=Ed[t];return s?s[e]||{input:0,output:0}:{input:0,output:0}}function Td(t){let e=Ua(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function Rd(){let t={};for(let i of Ur){let a=`${i.provider}:${i.model}`;t[a]||(t[a]={provider:i.provider,model:i.model,requests:0,input:0,output:0,cacheRead:0}),t[a].requests++,t[a].input+=i.input,t[a].output+=i.output,t[a].cacheRead+=i.cacheRead||0}let e=Object.values(t).map(i=>({...i,cost:Td(i)})),s=e.reduce((i,a)=>i+a.cost,0),n=e.reduce((i,a)=>i+a.input,0),o=e.reduce((i,a)=>i+a.output,0),r=e.reduce((i,a)=>i+(a.cacheRead||0),0);return{totalCost:s,totalInput:n,totalOutput:o,totalCacheRead:r,breakdown:e}}function Gw(){let{totalCost:t,totalInput:e,totalOutput:s,breakdown:n}=Rd();if(n.length===0)return"No token usage recorded this session.";let o=[];o.push("Session Token Usage:"),o.push("");for(let r of n){let i=r.cost>0?`$${r.cost.toFixed(4)}`:"free";o.push(` ${r.provider}:${r.model}`),o.push(` Input: ${r.input.toLocaleString()} tokens`),o.push(` Output: ${r.output.toLocaleString()} tokens`),o.push(` Cost: ${i}`)}return o.push(""),o.push(` Total: ${e.toLocaleString()} in + ${s.toLocaleString()} out = $${t.toFixed(4)}`),o.join(`
|
|
61
|
+
`)}function zw(t){return!t||typeof t!="string"?0:Math.ceil(t.length/4)}function Kw(t,e,s,n){let o=Ua(t,e),r=(s*o.input+n*o.output)/1e6;return r<=0?"":`[~$${r.toFixed(4)}]`}function Xw(){Ur=[]}function Vw(t,e){Cn[t]=e}function Jw(t){delete Cn[t]}function Zw(){return{...Cn}}function Cd(t){let e=0;for(let s of Ur)s.provider===t&&(e+=Td(s));return e}function Ad(t){let e=Cd(t),s=Cn[t];if(s===void 0)return{allowed:!0,spent:e,limit:null,remaining:null};let n=Math.max(0,s-e);return{allowed:e<s,spent:e,limit:s,remaining:n}}function Od(){let t=Ba.join(process.cwd(),".nex","config.json");if(Ms.existsSync(t))try{let e=JSON.parse(Ms.readFileSync(t,"utf-8"));e.costLimits&&typeof e.costLimits=="object"&&(Cn={...e.costLimits})}catch{}}function Qw(){let t=Ba.join(process.cwd(),".nex"),e=Ba.join(t,"config.json");Ms.existsSync(t)||Ms.mkdirSync(t,{recursive:!0}),Hw(e,()=>{let s={};if(Ms.existsSync(e))try{s=JSON.parse(Ms.readFileSync(e,"utf-8"))}catch{s={}}s.costLimits=Cn,Ww(e,JSON.stringify(s,null,2))})}function e$(){Cn={}}Od();Nd.exports={PRICING:Ed,trackUsage:Yw,getSessionCosts:Rd,formatCosts:Gw,formatCostHint:Kw,resetCosts:Xw,getPricing:Ua,setCostLimit:Vw,removeCostLimit:Jw,getCostLimits:Zw,getProviderSpend:Cd,checkBudget:Ad,loadCostLimits:Od,saveCostLimits:Qw,resetCostLimits:e$,estimateTokens:zw}});var Ha=J((T1,Md)=>{function Wa(){return process.env.NEX_DEBUG==="true"||process.argv.includes("--debug")}var t$=Wa();function n$(...t){Wa()&&console.log(...t)}function s$(...t){Wa()&&console.warn(...t)}Md.exports={DEBUG:t$,debugLog:n$,warnLog:s$}});var Id=J((R1,Ld)=>{"use strict";var o$=new Set(["read_file","grep","glob","search_files","list_directory"]),r$=new Set(["write_file","edit_file","patch_file"]),i$=new Set(["bash"]),a$=new Set(["web_search","web_fetch","perplexity_search"]);function Pd(t,e){let s=0,n=0,o=0,r=0,i=0;for(let[a,c]of t)i+=c,o$.has(a)&&(s+=c),r$.has(a)&&(n+=c),i$.has(a)&&(o+=c),a$.has(a)&&(r+=c);return i===0?`Phase ${e}`:r/i>.5?"Research":s/i>.5?"Exploration":n/i>.3?"Implementation":o/i>.3&&n/i<.15?"Verification":`Phase ${e}`}var Ya=class{constructor(e){this._N=e,this._disabled=e<=0,this._phaseNum=0,this._stepsThisPhase=0,this._phaseCounts=new Map,this._phaseStart=Date.now()}record(e,s,n,o){if(this._disabled)return null;this._stepsThisPhase++;for(let i of s)this._phaseCounts.set(i,(this._phaseCounts.get(i)||0)+1);if(this._stepsThisPhase<this._N)return null;this._phaseNum++;let r={phaseNum:this._phaseNum,phaseName:Pd(this._phaseCounts,this._phaseNum),stepCount:this._stepsThisPhase,toolCounts:new Map(this._phaseCounts),elapsed:Date.now()-this._phaseStart,filesRead:new Set(n),filesModified:new Set(o)};return this._stepsThisPhase=0,this._phaseCounts=new Map,this._phaseStart=Date.now(),r}};Ld.exports={MilestoneTracker:Ya,_phaseName:Pd}});var mo=J((C1,jd)=>{var ho=st(),c$={"kimi-k2.5":{id:"kimi-k2.5",name:"Kimi K2.5",max_tokens:16384},"qwen3-coder:480b":{id:"qwen3-coder:480b",name:"Qwen3 Coder 480B",max_tokens:16384}};function l$(){return ho.getActiveModel()}function u$(t){return ho.setActiveModel(t)}function d$(){return ho.getModelNames()}function f$(t){if(!t)return null;if(typeof t=="object")return t;try{return JSON.parse(t)}catch{}try{let n=t.replace(/,\s*([}\]])/g,"$1").replace(/'/g,'"');return JSON.parse(n)}catch{}let e=t.match(/\{[\s\S]*\}/);if(e)try{return JSON.parse(e[0])}catch{}try{let n=t.replace(/(\{|,)\s*([a-zA-Z_]\w*)\s*:/g,'$1"$2":');return JSON.parse(n)}catch{}let s=t.match(/```(?:json)?\s*([\s\S]*?)```/);if(s)try{return JSON.parse(s[1].trim())}catch{}return null}async function p$(t,e){let{C:s}=Je(),{Spinner:n}=Je(),o=new n("Thinking...");o.start();let r=!0,i="";try{let a=await ho.callStream(t,e,{onToken:c=>{r&&(o.stop(),process.stdout.write(`${s.blue}`),r=!1),process.stdout.write(c),i+=c}});return r?o.stop():process.stdout.write(`${s.reset}
|
|
62
|
+
`),a}catch(a){throw o.stop(),a}}async function h$(t,e){return ho.callChat(t,e)}jd.exports={MODELS:c$,getActiveModel:l$,setActiveModel:u$,getModelNames:d$,callOllamaStream:p$,callOllama:h$,parseToolArgs:f$}});var yo=J((A1,Wd)=>{var m$=require("readline"),{C:tn}=Je(),g$=/[\u200B\u200C\u200D\uFEFF\u2060\u00AD]/g,y$=/^=([\w-]+)/;function go(t){return typeof t!="string"?t:t.replace(g$,"").replace(y$,"$1")}var Ka=[/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/],Dd=[...Ka,/\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 w$(t){for(let e of Dd)if(e.test(t))return e;return null}var qd=[/\.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)/],$$=/\b(?:rm|rmdir|unlink|truncate|shred|mv|cp)\b/,Ga=[/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 Fd(t){let e=t.match(/ssh\s+[^"]*"([^"]+)"/)?.[1]||t.match(/ssh\s+[^']*'([^']+)'/)?.[1];if(!e)return!1;let n=e.replace(/\bfor\s[\s\S]*?\bdone\b/g,r=>r.replace(/;/g,"\0")).replace(/\bwhile\s[\s\S]*?\bdone\b/g,r=>r.replace(/;/g,"\0")).split(/\s*(?:&&|;)\s*/).map(r=>r.replace(/\x00/g,";").trim()).filter(Boolean);if(n.length===0)return!1;let o=r=>{let i=r.replace(/^sudo\s+(?:-[ugCD]\s+\S+\s+|-[A-Za-z]+\s+)*/,"");if(/^\s*(?:echo|printf)\s/.test(i))return!0;if(/^\s*for\s/.test(r)||/^\s*while\s/.test(r)){let a=r.match(/\bdo\s+([\s\S]*?)\s*(?:done|$)/)?.[1];return a?a.split(/\s*;\s*/).map(l=>l.trim()).filter(Boolean).every(l=>o(l)):Ga.some(c=>c.test(r))}return/^\w+=\$?\(/.test(i)||/^\w+=["']/.test(i)||/^\w+=\S/.test(i)?!0:Ga.some(a=>a.test(i))};return n.every(o)}var Xa=[/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/],Bd=[/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/],Ud=[...Xa,...Bd],Va=!1,zn=null,za=null;function b$(t){Va=t}function _$(t){za=t}function x$(){return Va}function k$(t){zn=t}function S$(t){let e=go(t);for(let s of Ka)if(s.test(e))return s;return null}function v$(t){let e=go(t);if(/ssh\s/.test(e)&&Fd(e))return!1;for(let s of Ud)if(s.test(e))return!0;return!1}function E$(t){let e=go(t);for(let s of Xa)if(s.test(e))return!0;return!1}function T$(t){if(process.env.NEX_UNPROTECT==="1")return null;let e=go(t);if(!$$.test(e))return null;for(let s of qd)if(s.test(e))return s;return null}function R$(t,e={}){if(Va)return Promise.resolve(!0);if(za)return za(t,e);if(!process.stdout.isTTY||!process.stdin.isTTY)return C$(t,e);let s=e.toolName?["Yes","No","Always allow"]:["Yes","No"];return new Promise(n=>{let o=0;zn&&zn.pause();let r=global._nexRawWrite||(d=>process.stdout.write(d)),i=()=>{let d=process.stdout.rows||24;return Math.max(1,d-s.length-2)},a=()=>{let d=i();global._nexRawWrite&&d>1&&global._nexRawWrite(`\x1B[1;${d-1}r`);let f=`\x1B[${d};1H\x1B[2K${tn.yellow}${t}${tn.reset}`;for(let p=0;p<s.length;p++){let h=p===o,g=h?`${tn.yellow}\u276F${tn.reset}`:" ",w=h?`${tn.yellow}${s[p]}${tn.reset}`:s[p];f+=`\x1B[${d+1+p};1H\x1B[2K ${g} ${w}`}r(f)},c=d=>{process.stdin.setRawMode(!1),process.stdin.pause(),process.stdin.removeListener("data",u);let f=global._nexRawWrite||(g=>process.stdout.write(g)),p=i(),h="";for(let g=0;g<s.length+1;g++)h+=`\x1B[${p+g};1H\x1B[2K`;f(h),global._nexRawWrite&&global._nexFooter&&global._nexRawWrite(`\x1B[1;${global._nexFooter._scrollEnd}r`),global._nexFooter&&global._nexFooter.drawFooter(),zn&&zn.resume(),n(d)},l=d=>{if(d===1){c(!1);return}d===2&&e.toolName&&Hr(e.toolName),c(!0)},u=d=>{if(d[0]===3){c(!1);return}let f=d.toString();if(f==="\r"||f===`
|
|
63
|
+
`){l(o);return}if(f==="\x1B[A"){o=(o-1+s.length)%s.length,a();return}if(f==="\x1B[B"){o=(o+1)%s.length,a();return}let p=f.toLowerCase().trim();if(p==="y"){c(!0);return}if(p==="n"){c(!1);return}if(p==="a"&&e.toolName){Hr(e.toolName),c(!0);return}};a(),process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",u)})}function C$(t,e){let s=e.toolName?"[Y/n/a] ":"[Y/n] ";return new Promise(n=>{let o=r=>{let i=r.trim().toLowerCase();i==="a"&&e.toolName?(Hr(e.toolName),n(!0)):n(i!=="n")};if(zn)zn.question(`${tn.yellow}${t} ${s}${tn.reset}`,o);else{let r=m$.createInterface({input:process.stdin,output:process.stdout});r.question(`${tn.yellow}${t} ${s}${tn.reset}`,i=>{r.close(),o(i)})}})}var Hr=()=>{};function A$(t){Hr=t}Wd.exports={sanitizeBashCommand:go,FORBIDDEN_PATTERNS:Ka,SSH_FORBIDDEN_PATTERNS:Dd,BASH_PROTECTED_PATHS:qd,SSH_SAFE_PATTERNS:Ga,isSSHReadOnly:Fd,DANGEROUS_BASH:Ud,CRITICAL_BASH:Xa,NOTABLE_BASH:Bd,isForbidden:S$,isSSHForbidden:w$,isDangerous:v$,isCritical:E$,isBashPathForbidden:T$,confirm:R$,setAutoConfirm:b$,getAutoConfirm:x$,setConfirmHook:_$,setReadlineInterface:k$,setAllowAlwaysHandler:A$}});var Gd=J((N1,Yd)=>{var Yr=require("path"),{C:U}=Je(),{T:Ja,isDark:O1}=Yt(),{confirm:O$,getAutoConfirm:N$}=yo(),Hd=2e3;function wo(t,e){let s=t.split(`
|
|
64
64
|
`),n=e.split(`
|
|
65
|
-
`),o=[],r=s.length,i=n.length;if(r>
|
|
66
|
-
${
|
|
67
|
-
${
|
|
68
|
-
${
|
|
69
|
-
`),n=s.slice(0,20);for(let o of n)console.log(`${
|
|
70
|
-
${
|
|
71
|
-
`)}function
|
|
72
|
-
${
|
|
73
|
-
`);return}let p=[];if(d>0&&p.push(`Added ${d} line${d!==1?"s":""}`),f>0&&p.push(`removed ${f} line${f!==1?"s":""}`),i.length>0){let
|
|
65
|
+
`),o=[],r=s.length,i=n.length;if(r>Hd||i>Hd){for(let d of s)o.push({type:"remove",line:d});for(let d of n)o.push({type:"add",line:d});return o}let a=Array.from({length:r+1},()=>new Array(i+1).fill(0));for(let d=1;d<=r;d++)for(let f=1;f<=i;f++)s[d-1]===n[f-1]?a[d][f]=a[d-1][f-1]+1:a[d][f]=Math.max(a[d-1][f],a[d][f-1]);let c=r,l=i,u=[];for(;c>0||l>0;)c>0&&l>0&&s[c-1]===n[l-1]?(u.unshift({type:"same",line:s[c-1]}),c--,l--):l>0&&(c===0||a[c][l-1]>=a[c-1][l])?(u.unshift({type:"add",line:n[l-1]}),l--):(u.unshift({type:"remove",line:s[c-1]}),c--);return u}function M$(t,e,s,n=3){console.log(`
|
|
66
|
+
${U.bold}${U.cyan} Diff: ${t}${U.reset}`);let o=wo(e,s),r=[];if(o.forEach((c,l)=>{c.type!=="same"&&r.push(l)}),r.length===0){console.log(`${U.gray} (no changes)${U.reset}`);return}let i=Math.max(0,r[0]-n),a=Math.min(o.length,r[r.length-1]+n+1);i>0&&console.log(`${U.gray} ...${U.reset}`);for(let c=i;c<a;c++){let l=o[c];switch(l.type){case"remove":console.log(`${U.red} - ${l.line}${U.reset}`);break;case"add":console.log(`${U.green} + ${l.line}${U.reset}`);break;default:console.log(`${U.gray} ${l.line}${U.reset}`)}}a<o.length&&console.log(`${U.gray} ...${U.reset}`),console.log()}function P$(t,e,s){console.log(`
|
|
67
|
+
${U.bold}${U.cyan} File exists \u2014 showing changes: ${t}${U.reset}`);let n=wo(e,s),o=0;for(let i of n)i.type!=="same"&&o++;if(o===0){console.log(`${U.gray} (identical content)${U.reset}`);return}let r=0;for(let i of n){if(r>=30){console.log(`${U.gray} ...(${o-r} more changes)${U.reset}`);break}switch(i.type){case"remove":console.log(`${U.red} - ${i.line}${U.reset}`),r++;break;case"add":console.log(`${U.green} + ${i.line}${U.reset}`),r++;break;default:r>0&&console.log(`${U.gray} ${i.line}${U.reset}`)}}console.log()}function L$(t,e){console.log(`
|
|
68
|
+
${U.bold}${U.cyan} New file: ${t}${U.reset}`);let s=e.split(`
|
|
69
|
+
`),n=s.slice(0,20);for(let o of n)console.log(`${U.green} + ${o}${U.reset}`);s.length>20&&console.log(`${U.gray} ...+${s.length-20} more lines${U.reset}`),console.log()}async function I$(t){return N$()?!0:O$(` ${t}?`)}function j$(t,e,s,n){let o=n||process.stdout.columns||80,r=Math.floor((o-3)/2);console.log(`
|
|
70
|
+
${U.bold}${U.cyan} Side-by-side: ${t}${U.reset}`),console.log(` ${U.dim}${"\u2500".repeat(r)}\u252C${"\u2500".repeat(r)}${U.reset}`);let i=wo(e,s),a=[],c=0;for(;c<i.length;)if(i[c].type==="same")a.push({left:i[c].line,right:i[c].line,type:"same"}),c++;else if(i[c].type==="remove"){let p=[];for(;c<i.length&&i[c].type==="remove";)p.push(i[c].line),c++;let h=[];for(;c<i.length&&i[c].type==="add";)h.push(i[c].line),c++;let g=Math.max(p.length,h.length);for(let w=0;w<g;w++)a.push({left:w<p.length?p[w]:"",right:w<h.length?h[w]:"",type:"changed"})}else i[c].type==="add"&&(a.push({left:"",right:i[c].line,type:"changed"}),c++);let l=a.map((p,h)=>p.type!=="same"?h:-1).filter(p=>p>=0);if(l.length===0){console.log(` ${U.gray}(no changes)${U.reset}`);return}let u=Math.max(0,l[0]-2),d=Math.min(a.length,l[l.length-1]+3),f=(p,h)=>{let g=p.replace(/\x1b\[[0-9;]*m/g,"");return g.length>=h?p.substring(0,h):p+" ".repeat(h-g.length)};u>0&&console.log(` ${U.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${U.reset}`);for(let p=u;p<d;p++){let h=a[p];if(h.type==="same")console.log(` ${U.gray}${f(h.left,r)}${U.reset}\u2502${U.gray}${f(h.right,r)}${U.reset}`);else{let g=h.left?`${U.red}${f(h.left,r)}${U.reset}`:`${f("",r)}`,w=h.right?`${U.green}${f(h.right,r)}${U.reset}`:`${f("",r)}`;console.log(` ${g}\u2502${w}`)}}d<a.length&&console.log(` ${U.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${U.reset}`),console.log(` ${U.dim}${"\u2500".repeat(r)}\u2534${"\u2500".repeat(r)}${U.reset}
|
|
71
|
+
`)}function D$(t,e,s,n={}){let o=n.label||"Update",r=n.context||3,i=n.annotations||[],a=Yr.isAbsolute(t)?Yr.relative(process.cwd(),t):t,c=wo(e,s),l=1,u=1;for(let A of c)A.type==="same"?(A.oldLine=l++,A.newLine=u++):A.type==="remove"?(A.oldLine=l++,A.newLine=null):(A.oldLine=null,A.newLine=u++);let d=0,f=0;for(let A of c)A.type==="add"?d++:A.type==="remove"&&f++;if(console.log(`
|
|
72
|
+
${U.green}\u23FA${U.reset} ${U.bold}${o}(${a})${U.reset}`),d===0&&f===0){console.log(` ${U.dim}\u23BF (no changes)${U.reset}
|
|
73
|
+
`);return}let p=[];if(d>0&&p.push(`Added ${d} line${d!==1?"s":""}`),f>0&&p.push(`removed ${f} line${f!==1?"s":""}`),i.length>0){let A=i.filter(ce=>ce.severity==="error").length,te=i.filter(ce=>ce.severity==="warn").length,oe=i.filter(ce=>ce.severity==="info").length,de=[];A>0&&de.push(`${U.red}${A} error${A!==1?"s":""}${U.dim}`),te>0&&de.push(`${U.yellow}${te} warning${te!==1?"s":""}${U.dim}`),oe>0&&de.push(`${U.cyan}${oe} info${oe!==1?"s":""}${U.dim}`),p.push(`found ${de.join(", ")}`)}console.log(` ${U.dim}\u23BF ${p.join(", ")}${U.reset}`);let g=[];c.forEach((A,te)=>{A.type!=="same"&&g.push(te)});let w=[],x=null,O=null;for(let A of g){let te=Math.max(0,A-r),oe=Math.min(c.length-1,A+r);x===null?(x=te,O=oe):(te<=O+1||(w.push([x,O]),x=te),O=oe)}x!==null&&w.push([x,O]);let I=" ",E=process.stdout.columns||120;function v(A,te,oe){let de=oe.replace(/\x1b\[[0-9;]*m/g,""),ce=oe+" ".repeat(Math.max(0,E-de.length));return`${A}${te}${ce}${U.reset}`}for(let A=0;A<w.length;A++){A>0&&console.log(`${I}${U.dim}\xB7\xB7\xB7${U.reset}`);let[te,oe]=w[A];for(let de=te;de<=oe;de++){let ce=c[de],ne=ce.newLine!=null?ce.newLine:ce.oldLine,S=String(ne).padStart(4),Te=ce.type!=="remove"?i.filter(W=>W.line===ce.newLine):[];ce.type==="remove"?console.log(v(Ja.diff_rem_bg,U.red,`${I}${S} - ${ce.line}`)):ce.type==="add"?console.log(v(Ja.diff_add_bg,U.green,`${I}${S} + ${ce.line}`)):console.log(`${I}${U.dim}${S} ${U.reset}${ce.line}`);for(let W of Te){let K=U.cyan,ge="\u2139";W.severity==="error"?(K=U.red,ge="\u2716"):W.severity==="warn"&&(K=U.yellow,ge="\u26A0"),console.log(`${I} ${K}${ge} ${W.message}${U.reset}`)}}}console.log()}function q$(t,e,s={}){let n=Yr.isAbsolute(t)?Yr.relative(process.cwd(),t):t,o=e.split(`
|
|
74
74
|
`),r=s.annotations||[];console.log(`
|
|
75
|
-
${
|
|
76
|
-
`).filter(Boolean).map(e=>{let s=e.substring(0,2).trim(),n=e.substring(3);return{status:s,file:n}})}catch{return[]}}async function
|
|
77
|
-
`);for(let d of u)d.startsWith("+")&&!d.startsWith("+++")&&o++,d.startsWith("-")&&!d.startsWith("---")&&r++}else o=t.length;let i="chore",a=t.join(" ").toLowerCase();a.includes("test")?i="test":a.includes("readme")||a.includes("doc")?i="docs":o>r*2?i="feat":r>o?i="refactor":i="fix";let
|
|
78
|
-
${
|
|
79
|
-
${
|
|
80
|
-
${
|
|
75
|
+
${U.green}\u23FA${U.reset} ${U.bold}Create(${n})${U.reset}`);let i=[`${o.length} line${o.length!==1?"s":""}`];if(r.length>0){let d=r.filter(g=>g.severity==="error").length,f=r.filter(g=>g.severity==="warn").length,p=r.filter(g=>g.severity==="info").length,h=[];d>0&&h.push(`${U.red}${d} error${d!==1?"s":""}${U.dim}`),f>0&&h.push(`${U.yellow}${f} warning${f!==1?"s":""}${U.dim}`),p>0&&h.push(`${U.cyan}${p} info${p!==1?"s":""}${U.dim}`),i.push(`found ${h.join(", ")}`)}console.log(` ${U.dim}\u23BF ${i.join(", ")}${U.reset}`);let c=" ",l=process.stdout.columns||120,u=Math.min(o.length,20);for(let d=0;d<u;d++){let f=String(d+1).padStart(4),p=d+1,h=r.filter(O=>O.line===p),g=`${c}${f} + ${o[d]}`,w=g.replace(/\x1b\[[0-9;]*m/g,""),x=g+" ".repeat(Math.max(0,l-w.length));console.log(`${Ja.diff_add_bg}${U.green}${x}${U.reset}`);for(let O of h){let I=U.cyan,E="\u2139";O.severity==="error"?(I=U.red,E="\u2716"):O.severity==="warn"&&(I=U.yellow,E="\u26A0"),console.log(`${c} ${I}${E} ${O.message}${U.reset}`)}}o.length>20&&console.log(`${c}${U.dim} ...+${o.length-20} more lines${U.reset}`),console.log()}Yd.exports={diffLines:wo,showEditDiff:M$,showWriteDiff:P$,showNewFilePreview:L$,confirmFileChange:I$,showSideBySideDiff:j$,showDiff:D$,showNewFile:q$}});var Kr=J((M1,Xd)=>{var zd=require("util").promisify(require("child_process").exec),F$=require("util").promisify(require("child_process").execFile),{C:Fe}=Je();async function Za(t){try{let{stdout:e}=await zd(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function Gr(...t){try{let{stdout:e}=await F$("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function B$(){return await Za("git rev-parse --is-inside-work-tree")==="true"}async function U$(){return await Za("git branch --show-current")}async function Qa(){try{let{stdout:t}=await zd("git status --porcelain",{cwd:process.cwd(),timeout:3e4});return!t||!t.trim()?[]:t.split(`
|
|
76
|
+
`).filter(Boolean).map(e=>{let s=e.substring(0,2).trim(),n=e.substring(3);return{status:s,file:n}})}catch{return[]}}async function zr(t=!1){return await Za(`git diff ${t?"--cached":""}`)||""}async function ec(){return(await Qa()).map(e=>e.file)}async function Kd(){let t=await ec();if(t.length===0)return null;let e=await zr(),n=await zr(!0)||e,o=0,r=0;if(n){let u=n.split(`
|
|
77
|
+
`);for(let d of u)d.startsWith("+")&&!d.startsWith("+++")&&o++,d.startsWith("-")&&!d.startsWith("---")&&r++}else o=t.length;let i="chore",a=t.join(" ").toLowerCase();a.includes("test")?i="test":a.includes("readme")||a.includes("doc")?i="docs":o>r*2?i="feat":r>o?i="refactor":i="fix";let c=t.slice(0,3).map(u=>u.split("/").pop());return{summary:`${i}: update ${c.join(", ")}${t.length>3?` (+${t.length-3} more)`:""}`,type:i,files:t,stats:{additions:o,deletions:r}}}async function W$(t){let s=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await Gr("checkout","-b",s)!==null?s:null}async function H$(t){return await Gr("add","-A"),await Gr("commit","-m",t)?await Gr("rev-parse","--short","HEAD"):null}async function Y$(){let t=await Kd();if(!t)return`${Fe.dim}No changes${Fe.reset}`;let e=[];e.push(`
|
|
78
|
+
${Fe.bold}${Fe.cyan}Git Diff Summary:${Fe.reset}`),e.push(` ${Fe.green}+${t.stats.additions}${Fe.reset} ${Fe.red}-${t.stats.deletions}${Fe.reset} in ${t.files.length} file(s)`),e.push(`
|
|
79
|
+
${Fe.bold}${Fe.cyan}Files:${Fe.reset}`);for(let s of t.files.slice(0,20))e.push(` ${Fe.dim}${s}${Fe.reset}`);return t.files.length>20&&e.push(` ${Fe.dim}...+${t.files.length-20} more${Fe.reset}`),e.push(`
|
|
80
|
+
${Fe.bold}${Fe.cyan}Suggested message:${Fe.reset}`),e.push(` ${Fe.cyan}${t.summary}${Fe.reset}
|
|
81
81
|
`),e.join(`
|
|
82
|
-
`)}async function
|
|
82
|
+
`)}async function G$(){return(await Qa()).filter(e=>e.status==="UU"||e.status==="AA"||e.status==="DD")}async function z$(){let t=await ec();if(t.length===0)return"";let e=[`CHANGED FILES (${t.length}):`];for(let n of t.slice(0,10))e.push(` ${n}`);let s=await zr();if(s){let n=s.length>5e3?s.substring(0,5e3)+`
|
|
83
83
|
...(truncated)`:s;e.push(`
|
|
84
84
|
DIFF:
|
|
85
85
|
${n}`)}return e.join(`
|
|
86
|
-
`)}
|
|
87
|
-
`).map(s=>{let n=s.match(/^stash@\{(\d+)\}:\s+(?:WIP on [^:]+:\s+\S+\s+|On \S+:\s+)(.*)/);if(!n)return null;let o=n[2].trim();return o.startsWith(
|
|
88
|
-
`)){let a=i.trim();if(/^trigger:\s*$/i.test(a)){r=!0;continue}r&&a.startsWith("- ")?o.push(a.slice(2).trim().replace(/^["']|["']$/g,"")):r&&a&&!a.startsWith("#")&&(r=!1)}return{triggers:o,body:n}}function
|
|
86
|
+
`)}Xd.exports={isGitRepo:B$,getCurrentBranch:U$,getStatus:Qa,getDiff:zr,getChangedFiles:ec,analyzeDiff:Kd,createBranch:W$,commit:H$,formatDiffSummary:Y$,getDiffContext:z$,getMergeConflicts:G$}});var sf=J((L1,nf)=>{var ot=require("fs").promises,P1=require("fs"),It=require("path"),K$=require("crypto"),{execSync:tc,execFileSync:Zd}=require("child_process"),X$=100*1024,Qd=50,bt=[],Ps=[];function V$(t,e,s,n){for(bt.push({tool:t,filePath:e,oldContent:s,newContent:n,timestamp:Date.now()});bt.length>Qd;)bt.shift();Ps.length=0,ef(bt[bt.length-1]).catch(()=>{})}async function J$(){if(bt.length===0)return null;let t=bt.pop();if(t.oldContent===null)try{await ot.unlink(t.filePath)}catch{}else await ot.writeFile(t.filePath,t.oldContent,"utf-8");return Ps.push(t),{tool:t.tool,filePath:t.filePath,wasCreated:t.oldContent===null}}async function Z$(){if(Ps.length===0)return null;let t=Ps.pop();return await ot.writeFile(t.filePath,t.newContent,"utf-8"),bt.push(t),{tool:t.tool,filePath:t.filePath}}function Q$(t=10){return bt.slice(-t).reverse().map(e=>({tool:e.tool,filePath:e.filePath,timestamp:e.timestamp}))}function eb(){return bt.length}function tb(){return Ps.length}function nb({diskToo:t=!0}={}){if(bt.length=0,Ps.length=0,t){let e=Vr();ot.readdir(e).then(s=>{for(let n of s)n.endsWith(".json")&&ot.unlink(It.join(e,n)).catch(()=>{})}).catch(()=>{})}}function Vr(){return It.join(process.cwd(),".nex","history")}async function Vd(t,e){if(t==null)return{inline:!0,content:t};if(Buffer.byteLength(t,"utf-8")<=X$)return{inline:!0,content:t};let s=K$.createHash("sha256").update(t,"utf-8").digest("hex"),n=It.join(e,"blobs");return await ot.mkdir(n,{recursive:!0}),await ot.writeFile(It.join(n,s),t,"utf-8"),{inline:!1,hash:s}}async function ef(t){let e=Vr();await ot.mkdir(e,{recursive:!0});let s=It.basename(t.filePath).replace(/[^a-zA-Z0-9]/g,"-"),n=`${t.timestamp}-${s}.json`,o=await Vd(t.oldContent,e),r=await Vd(t.newContent,e),i={tool:t.tool,filePath:t.filePath,timestamp:t.timestamp,oldContent:o.inline?{inline:!0,content:o.content}:{inline:!1,hash:o.hash},newContent:r.inline?{inline:!0,content:r.content}:{inline:!1,hash:r.hash}};await ot.writeFile(It.join(e,n),JSON.stringify(i),"utf-8")}async function Jd(t,e){if(!t)return null;if(t.inline)return t.content;let s=It.join(e,"blobs",t.hash);return ot.readFile(s,"utf-8")}async function sb(){let t=Vr(),e;try{e=await ot.readdir(t)}catch{return 0}let s=e.filter(o=>o.endsWith(".json")).sort(),n=0;for(let o of s)try{let r=await ot.readFile(It.join(t,o),"utf-8"),i=JSON.parse(r),a=await Jd(i.oldContent,t),c=await Jd(i.newContent,t);bt.push({tool:i.tool,filePath:i.filePath,timestamp:i.timestamp,oldContent:a,newContent:c}),n++}catch{}for(;bt.length>Qd;)bt.shift();return n}async function ob(t=7){let e=Vr(),s;try{s=await ot.readdir(e)}catch{return 0}let n=Date.now()-t*24*60*60*1e3,o=s.filter(l=>l.endsWith(".json")),r=0,i=new Set,a=[];for(let l of o)try{let u=await ot.readFile(It.join(e,l),"utf-8"),d=JSON.parse(u);d.timestamp<n?(a.push(l),r++):(d.oldContent&&!d.oldContent.inline&&d.oldContent.hash&&i.add(d.oldContent.hash),d.newContent&&!d.newContent.inline&&d.newContent.hash&&i.add(d.newContent.hash))}catch{}for(let l of a)try{await ot.unlink(It.join(e,l))}catch{}let c=It.join(e,"blobs");try{let l=await ot.readdir(c);for(let u of l)if(!i.has(u))try{await ot.unlink(It.join(c,u))}catch{}}catch{}return r}var Xr="nex-snapshot";function rb(t,e=process.cwd()){let s=t?`${Xr}-${t.replace(/[^a-zA-Z0-9_-]/g,"-")}`:`${Xr}-${Date.now()}`;try{return tc("git status --porcelain",{cwd:e,timeout:1e4}).toString().trim()?(Zd("git",["stash","push","-u","-m",s],{cwd:e,timeout:15e3}),tc("git stash pop",{cwd:e,timeout:1e4}),{name:s,label:s,ok:!0}):{name:s,label:s,ok:!1,error:"No changes to snapshot (working tree clean)"}}catch(n){return{name:s,label:s,ok:!1,error:n.message}}}function tf(t=process.cwd()){try{let e=tc("git stash list",{cwd:t,timeout:1e4}).toString().trim();return e?e.split(`
|
|
87
|
+
`).map(s=>{let n=s.match(/^stash@\{(\d+)\}:\s+(?:WIP on [^:]+:\s+\S+\s+|On \S+:\s+)(.*)/);if(!n)return null;let o=n[2].trim();return o.startsWith(Xr)?{index:parseInt(n[1],10),label:o,shortName:o.replace(`${Xr}-`,""),date:s}:null}).filter(Boolean):[]}catch{return[]}}function ib(t,e=process.cwd()){try{let s=tf(e);if(s.length===0)return{ok:!1,error:"No snapshots found"};let n;return t===void 0||t==="last"?n=s[0]:typeof t=="number"?n=s.find(o=>o.index===t):n=s.find(o=>o.label===t||o.shortName===t||o.shortName.includes(String(t))),n?(Zd("git",["stash","apply",`stash@{${n.index}}`],{cwd:e,timeout:15e3}),{ok:!0,label:n.label}):{ok:!1,error:`Snapshot not found: ${t}`}}catch(s){return{ok:!1,error:s.message}}}nf.exports={recordChange:V$,undo:J$,redo:Z$,getHistory:Q$,getUndoCount:eb,getRedoCount:tb,clearHistory:nb,persistEntry:ef,loadPersistedHistory:sb,pruneHistory:ob,createSnapshot:rb,listSnapshots:tf,restoreSnapshot:ib}});var ic=J((I1,uf)=>{var Le=require("fs"),_t=require("path"),{atomicWrite:ab,withFileLockSync:cb}=Gn(),pt=[];function $o(){return _t.join(process.cwd(),".nex","skills")}function of(){return _t.join(process.cwd(),".nex","config.json")}function rf(){let t=$o();return Le.existsSync(t)||Le.mkdirSync(t,{recursive:!0}),t}function oc(){let t=of();if(!Le.existsSync(t))return[];try{let e=JSON.parse(Le.readFileSync(t,"utf-8"));return e.skills&&Array.isArray(e.skills.disabled)?e.skills.disabled:[]}catch{return[]}}function af(t){let e=of(),s=_t.dirname(e);Le.existsSync(s)||Le.mkdirSync(s,{recursive:!0}),cb(e,()=>{let n={};if(Le.existsSync(e))try{n=JSON.parse(Le.readFileSync(e,"utf-8"))}catch{n={}}n.skills||(n.skills={}),n.skills.disabled=t,ab(e,JSON.stringify(n,null,2))})}function cf(t,e){let s=[];if(typeof t!="object"||t===null)return{valid:!1,errors:["Module must export an object"]};if(t.name!==void 0&&typeof t.name!="string"&&s.push("name must be a string"),t.description!==void 0&&typeof t.description!="string"&&s.push("description must be a string"),t.instructions!==void 0&&typeof t.instructions!="string"&&s.push("instructions must be a string"),t.commands!==void 0)if(!Array.isArray(t.commands))s.push("commands must be an array");else for(let n=0;n<t.commands.length;n++){let o=t.commands[n];(!o.cmd||typeof o.cmd!="string")&&s.push(`commands[${n}].cmd must be a non-empty string`),o.handler!==void 0&&typeof o.handler!="function"&&s.push(`commands[${n}].handler must be a function`)}if(t.tools!==void 0)if(!Array.isArray(t.tools))s.push("tools must be an array");else for(let n=0;n<t.tools.length;n++){let o=t.tools[n];(!o.function||!o.function.name||typeof o.function.name!="string")&&s.push(`tools[${n}].function.name must be a non-empty string`),o.execute!==void 0&&typeof o.execute!="function"&&s.push(`tools[${n}].execute must be a function`)}return{valid:s.length===0,errors:s}}function lf(t){let e=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(!e)return{triggers:[],body:t};let s=e[1],n=e[2].trim(),o=[],r=!1;for(let i of s.split(`
|
|
88
|
+
`)){let a=i.trim();if(/^trigger:\s*$/i.test(a)){r=!0;continue}r&&a.startsWith("- ")?o.push(a.slice(2).trim().replace(/^["']|["']$/g,"")):r&&a&&!a.startsWith("#")&&(r=!1)}return{triggers:o,body:n}}function nc(t){try{let e=Le.readFileSync(t,"utf-8").trim();if(!e)return null;let s=_t.basename(t,".md"),{triggers:n,body:o}=lf(e);return{name:s,type:"prompt",filePath:t,instructions:o||e,triggers:n,commands:[],tools:[]}}catch{return null}}function sc(t){try{let e=require(t),{valid:s,errors:n}=cf(e,t);return s?{name:e.name||_t.basename(t,".js"),type:"script",filePath:t,description:e.description||"",instructions:e.instructions||"",commands:(e.commands||[]).map(r=>({cmd:r.cmd.startsWith("/")?r.cmd:`/${r.cmd}`,desc:r.desc||r.description||"",handler:r.handler||null})),tools:(e.tools||[]).map(r=>({type:r.type||"function",function:{name:r.function.name,description:r.function.description||"",parameters:r.function.parameters||{type:"object",properties:{}}},execute:r.execute||null}))}:(console.error(`Skill validation failed: ${t}
|
|
89
89
|
${n.join(`
|
|
90
|
-
`)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function
|
|
90
|
+
`)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function rc(){pt=[];let t=oc(),e=$o(),s=[];if(Le.existsSync(e))try{s=Le.readdirSync(e)}catch{s=[]}for(let o of s){let r=_t.join(e,o),i;try{i=Le.statSync(r)}catch{continue}if(!i.isFile())continue;let a=null;o.endsWith(".md")?a=nc(r):o.endsWith(".js")&&(a=sc(r)),a&&(a.enabled=!t.includes(a.name),pt.push(a))}let n=_t.join(__dirname,"skills");if(!process.env.NEX_SKIP_BUILTIN_SKILLS&&Le.existsSync(n)){let o;try{o=Le.readdirSync(n).filter(r=>r.endsWith(".md")||r.endsWith(".js"))}catch{o=[]}for(let r of o){let i=_t.join(n,r),a=_t.basename(r,_t.extname(r));if(pt.some(u=>u.name===a))continue;let c;try{c=Le.statSync(i)}catch{continue}if(!c.isFile())continue;let l=r.endsWith(".md")?nc(i):sc(i);l&&(l._builtin=!0,l.enabled=!t.includes(l.name),pt.push(l))}}return pt}function lb(){let t=[];for(let e of pt)!e.enabled||!e.instructions||t.push(`[Skill: ${e.name}]
|
|
91
91
|
${e.instructions}`);return t.length===0?"":`SKILL INSTRUCTIONS:
|
|
92
92
|
${t.join(`
|
|
93
93
|
|
|
94
|
-
`)}`}function
|
|
94
|
+
`)}`}function ub(){let t=[];for(let e of pt)if(e.enabled)for(let s of e.commands)t.push({cmd:s.cmd,desc:s.desc||`[skill: ${e.name}]`});return t}function db(){let t=[];for(let e of pt)if(e.enabled)for(let s of e.tools)t.push({type:"function",function:{name:`skill_${s.function.name}`,description:`[Skill:${e.name}] ${s.function.description}`,parameters:s.function.parameters}});return t}async function fb(t,e){if(!t.startsWith("skill_"))return null;let s=t.substring(6);for(let n of pt)if(n.enabled){for(let o of n.tools)if(o.function.name===s&&o.execute)try{let r=await o.execute(e);return typeof r=="string"?r:JSON.stringify(r)}catch(r){return`ERROR: Skill tool '${s}' failed: ${r.message}`}}return`ERROR: Skill tool '${s}' not found`}function pb(t){let[e,...s]=t.split(/\s+/),n=s.join(" ").trim();for(let o of pt)if(o.enabled){for(let r of o.commands)if(r.cmd===e&&r.handler){try{let i=r.handler(n);if(typeof i=="string"&&i.length>0)return{handled:!0,agentPrompt:i}}catch(i){console.error(`Skill command error (${e}): ${i.message}`)}return{handled:!0}}}return!1}function hb(){return pt.map(t=>({name:t.name,type:t.type,enabled:t.enabled,description:t.description||"",commands:t.commands.length,tools:t.tools.length,filePath:t.filePath}))}function mb(t){let e=pt.find(n=>n.name===t);if(!e)return!1;e.enabled=!0;let s=oc().filter(n=>n!==t);return af(s),!0}function gb(t){let e=pt.find(n=>n.name===t);if(!e)return!1;e.enabled=!1;let s=oc();return s.includes(t)||(s.push(t),af(s)),!0}function yb(){return pt}async function wb(t,e={}){let{execFileSync:s}=require("child_process"),n=rf(),o=t;/^[\w-]+\/[\w.-]+$/.test(t)&&(o=`https://github.com/${t}.git`);let r=e.name||_t.basename(o,".git").replace(/^nex-skill-/,""),i=_t.join(n,r);if(Le.existsSync(i))return{ok:!1,name:r,error:`Skill "${r}" is already installed at ${i}. Remove it first to reinstall.`};try{if(!/^https?:\/\/[a-zA-Z0-9._\-/:.@]+$/.test(o))throw new Error(`Invalid git URL: ${o}`);s("git",["clone","--depth","1",o,i],{timeout:3e4,stdio:"pipe"})}catch(u){return{ok:!1,name:r,error:`Git clone failed: ${u.stderr?.toString().trim()||u.message}`}}let a=_t.join(i,"skill.json"),c=Le.existsSync(a),l=Le.readdirSync(i).some(u=>(u.endsWith(".md")||u.endsWith(".js"))&&!u.startsWith("."));if(!c&&!l){try{Le.rmSync(i,{recursive:!0,force:!0})}catch(u){console.error("skills.js line 562 failed:",u.message)}return{ok:!1,name:r,error:"No skill.json manifest or .md/.js skill file found in repository"}}if(c)try{let u=JSON.parse(Le.readFileSync(a,"utf-8"));u.name||(u.name=r)}catch{try{Le.rmSync(i,{recursive:!0,force:!0})}catch{}return{ok:!1,name:r,error:"Invalid skill.json \u2014 not valid JSON"}}return rc(),{ok:!0,name:r}}async function $b(t){let e=require("axios");try{let s=encodeURIComponent(`nex-skill ${t} OR nex-code-skill ${t}`);return((await e.get(`https://api.github.com/search/repositories?q=${s}&sort=stars&per_page=10`,{timeout:1e4,headers:{Accept:"application/vnd.github.v3+json"}})).data.items||[]).map(o=>({name:o.name.replace(/^nex-skill-/,""),description:o.description||"(no description)",url:o.clone_url,stars:o.stargazers_count,owner:o.owner.login}))}catch(s){return[{name:"error",description:`Search failed: ${s.message}`,url:"",stars:0,owner:""}]}}function bb(t){let e=_t.join($o(),t);if(!Le.existsSync(e))return{ok:!1,error:`Skill "${t}" not found in ${$o()}`};try{return Le.rmSync(e,{recursive:!0,force:!0}),rc(),{ok:!0}}catch(s){return{ok:!1,error:s.message}}}function _b(t){if(!t)return[];let e=t.toLowerCase(),s=[];for(let n of pt){if(!n.enabled||!n.triggers||n.triggers.length===0)continue;if(n.triggers.some(r=>e.includes(r.toLowerCase()))){let r=(n.instructions||"").split(`
|
|
95
95
|
`).slice(0,3).join(`
|
|
96
|
-
`);s.push({name:n.name,instructions:r})}}return s}
|
|
97
|
-
`,
|
|
98
|
-
`);for(let
|
|
99
|
-
`):JSON.stringify(o)}function
|
|
100
|
-
Available tools: ${d.join(", ")}`}}if(!s||!s.properties)return{valid:!0};let n=s.required||[],o=Object.keys(s.properties),r=Object.keys(e),i=[],a={...e},
|
|
96
|
+
`);s.push({name:n.name,instructions:r})}}return s}uf.exports={initSkillsDir:rf,loadAllSkills:rc,getSkillInstructions:lb,getSkillCommands:ub,getSkillToolDefinitions:db,routeSkillCall:fb,handleSkillCommand:pb,listSkills:hb,enableSkill:mb,disableSkill:gb,getLoadedSkills:yb,installSkill:wb,searchSkills:$b,removeSkill:bb,matchSkillTriggers:_b,_getSkillsDir:$o,_validateScriptSkill:cf,_loadMarkdownSkill:nc,_loadScriptSkill:sc,_parseFrontmatter:lf}});var cc=J((j1,gf)=>{var{spawn:xb}=require("child_process"),kb=require("path"),df=require("fs"),mn=new Map;function Sb(){return kb.join(process.cwd(),".nex","config.json")}function ac(){let t=Sb();if(!df.existsSync(t))return{};try{return JSON.parse(df.readFileSync(t,"utf-8")).mcpServers||{}}catch{return{}}}function Jr(t,e,s={},n=1e4){return new Promise((o,r)=>{let i=`${Date.now()}-${Math.random().toString(36).slice(2,6)}`,a=JSON.stringify({jsonrpc:"2.0",id:i,method:e,params:s})+`
|
|
97
|
+
`,c="",l=setTimeout(()=>{d(),r(new Error(`MCP request timeout: ${e}`))},n);function u(f){c+=f.toString();let p=c.split(`
|
|
98
|
+
`);for(let h of p)if(h.trim())try{let g=JSON.parse(h);if(g.id===i){d(),g.error?r(new Error(`MCP error: ${g.error.message||JSON.stringify(g.error)}`)):o(g.result);return}}catch{}c=p[p.length-1]||""}function d(){clearTimeout(l),t.stdout.removeListener("data",u)}t.stdout.on("data",u);try{t.stdin.write(a)}catch(f){d(),r(new Error(`MCP write failed: ${f.message}`))}})}async function ff(t,e){if(mn.has(t))return mn.get(t);let s=["PATH","HOME","USER","SHELL","LANG","TERM","NODE_ENV"],n={};for(let i of s)process.env[i]&&(n[i]=process.env[i]);let o=xb(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:{...n,...e.env||{}}}),r={name:t,proc:o,tools:[],config:e};try{await Jr(o,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.2.0"}});let i=await Jr(o,"tools/list",{});return r.tools=i&&i.tools||[],mn.set(t,r),r}catch(i){throw o.kill(),new Error(`Failed to connect MCP server '${t}': ${i.message}`)}}function pf(t){let e=mn.get(t);if(!e)return!1;try{e.proc.kill()}catch{}return mn.delete(t),!0}function vb(){for(let[t]of mn)pf(t)}async function hf(t,e,s={}){let n=mn.get(t);if(!n)throw new Error(`MCP server not connected: ${t}`);let o=await Jr(n.proc,"tools/call",{name:e,arguments:s});return o&&Array.isArray(o.content)?o.content.filter(r=>r.type==="text").map(r=>r.text).join(`
|
|
99
|
+
`):JSON.stringify(o)}function mf(){let t=[];for(let[e,s]of mn)for(let n of s.tools)t.push({server:e,name:n.name,description:n.description||"",inputSchema:n.inputSchema||{type:"object",properties:{}}});return t}function Eb(){return mf().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function Tb(t,e){if(!t.startsWith("mcp_"))return null;let s=t.substring(4).split("_");if(s.length<2)return null;let n=s[0],o=s.slice(1).join("_");return hf(n,o,e)}function Rb(){let t=ac();return Object.entries(t).map(([e,s])=>{let n=mn.get(e);return{name:e,command:s.command,connected:!!n,toolCount:n?n.tools.length:0}})}async function Cb(){let t=ac(),e=[];for(let[s,n]of Object.entries(t))try{let o=await ff(s,n);e.push({name:s,tools:o.tools.length})}catch(o){e.push({name:s,tools:0,error:o.message})}return e}gf.exports={loadMCPConfig:ac,sendRequest:Jr,connectServer:ff,disconnectServer:pf,disconnectAll:vb,callTool:hf,getAllTools:mf,getMCPToolDefinitions:Eb,routeMCPCall:Tb,listServers:Rb,connectAll:Cb}});var Qr=J((D1,bf)=>{var yf=require("fs"),lc=require("path"),Zr=[],bo=[],Kn={},_o=["onToolResult","onModelResponse","onSessionStart","onSessionEnd","onFileChange","beforeToolExec","afterToolExec"];function wf(t,e){if(!t||!t.function||!t.function.name)return{ok:!1,error:"Tool definition must have function.name"};if(typeof e!="function")return{ok:!1,error:"Handler must be a function"};let s=t.function.name;return bo.some(n=>n.definition.function.name===s)?{ok:!1,error:`Tool "${s}" is already registered`}:(bo.push({definition:{type:"function",...t},handler:e}),{ok:!0})}function $f(t,e){return _o.includes(t)?typeof e!="function"?{ok:!1,error:"Handler must be a function"}:(Kn[t]||(Kn[t]=[]),Kn[t].push(e),{ok:!0}):{ok:!1,error:`Unknown event "${t}". Available: ${_o.join(", ")}`}}async function uc(t,e){let s=Kn[t]||[],n=e;for(let o of s)try{let r=await o(n);r!==void 0&&(n=r)}catch(r){process.env.NEX_DEBUG&&console.error(`[plugin] Hook error on ${t}: ${r.message}`)}return n}function Ab(){let t=lc.join(process.cwd(),".nex","plugins"),e=[];if(!yf.existsSync(t))return{loaded:0,errors:[]};let s=yf.readdirSync(t).filter(o=>o.endsWith(".js")),n={registerTool:wf,registerHook:$f,EVENTS:_o};for(let o of s){let r=lc.join(t,o);try{let i=require(r);if(typeof i=="function")i(n);else if(typeof i.setup=="function")i.setup(n);else{e.push(`${o}: Plugin must export a function or { setup: function }`);continue}Zr.push({name:i.name||lc.basename(o,".js"),filePath:r})}catch(i){e.push(`${o}: ${i.message}`)}}return{loaded:Zr.length,errors:e}}function Ob(){return bo.map(t=>t.definition)}async function Nb(t,e,s={}){let n=bo.find(a=>a.definition.function.name===t);if(!n)return null;let o=await uc("beforeToolExec",{name:t,args:e,options:s}),r=await n.handler(o.args||e,s);return(await uc("afterToolExec",{name:t,args:e,result:r})).result||r}function Mb(){return[...Zr]}function Pb(){let t={};for(let e of _o)t[e]=(Kn[e]||[]).length;return t}function Lb(){Zr.length=0,bo.length=0;for(let t of Object.keys(Kn))delete Kn[t]}bf.exports={registerTool:wf,registerHook:$f,emit:uc,loadPlugins:Ab,getPluginToolDefinitions:Ob,executePluginTool:Nb,getLoadedPlugins:Mb,getHookCounts:Pb,clearPlugins:Lb,EVENTS:_o}});var dc=J((q1,Sf)=>{var{getSkillToolDefinitions:Ib}=ic(),{getMCPToolDefinitions:jb}=cc(),{getPluginToolDefinitions:Db}=Qr(),ei=new Map;function _f(){let{TOOL_DEFINITIONS:t}=Ls();return[...t,...Ib(),...jb(),...Db()]}function xf(t){if(ei.has(t))return ei.get(t);let s=_f().find(o=>o.function.name===t);if(!s)return null;let n=s.function.parameters;return ei.set(t,n),n}function qb(){ei.clear()}function ti(t,e){if(!t||e.length===0)return null;let s=null,n=1/0;for(let o of e){let r=kf(t.toLowerCase(),o.toLowerCase());r<n&&(n=r,s=o)}return n<=Math.ceil(t.length/2)?s:null}function kf(t,e){let s=t.length,n=e.length,o=Array.from({length:s+1},()=>Array(n+1).fill(0));for(let r=0;r<=s;r++)o[r][0]=r;for(let r=0;r<=n;r++)o[0][r]=r;for(let r=1;r<=s;r++)for(let i=1;i<=n;i++)o[r][i]=t[r-1]===e[i-1]?o[r-1][i-1]:1+Math.min(o[r-1][i],o[r][i-1],o[r-1][i-1]);return o[s][n]}function Fb(t,e){let s=xf(t);if(s===null){let d=_f().map(p=>p.function.name),f=ti(t,d);return{valid:!1,error:`Unknown tool "${t}".${f?` Did you mean "${f}"?`:""}
|
|
100
|
+
Available tools: ${d.join(", ")}`}}if(!s||!s.properties)return{valid:!0};let n=s.required||[],o=Object.keys(s.properties),r=Object.keys(e),i=[],a={...e},c=!1;for(let u of n)if(!(u in e)||e[u]===void 0||e[u]===null){let d=ti(u,r);d&&!o.includes(d)?(a[u]=e[d],delete a[d],c=!0):i.push(`Missing required parameter "${u}" (${s.properties[u]?.description||s.properties[u]?.type||"unknown"})`)}new Set(["grep","grep_search","search_files"]).has(t)&&(("-n"in a||"n"in a)&&!o.includes("-n")&&(delete a["-n"],delete a.n,c=!0),("-i"in a||"--ignore-case"in a)&&"ignore_case"in(s.properties||{})&&(a.ignore_case=!0,delete a["-i"],delete a["--ignore-case"],c=!0),("-r"in a||"--recursive"in a)&&(delete a["-r"],delete a["--recursive"],c=!0)),t==="read_file"&&("offset"in a&&!("line_start"in a)&&(a.line_start=a.offset,delete a.offset,c=!0),"start_line"in a&&!("line_start"in a)&&(a.line_start=a.start_line,delete a.start_line,c=!0),"end_line"in a&&!("line_end"in a)&&(a.line_end=a.end_line,delete a.end_line,c=!0));for(let u of Object.keys(a))if(!o.includes(u)){let d=ti(u,o);if(d&&!(d in a))a[d]=a[u],delete a[u],c=!0;else if(!c){let f=d?` Did you mean "${d}"?`:"";i.push(`Unknown parameter "${u}".${f}`)}}for(let u of Object.keys(a)){if(!s.properties[u])continue;let d=s.properties[u].type,f=typeof a[u];d==="string"&&f==="number"?(a[u]=String(a[u]),c=!0):d==="number"&&f==="string"&&!isNaN(a[u])?(a[u]=Number(a[u]),c=!0):d==="boolean"&&f==="string"&&(a[u]=a[u]==="true",c=!0)}return i.length>0&&!c?{valid:!1,error:`Tool "${t}" argument errors:
|
|
101
101
|
`+i.map(u=>` - ${u}`).join(`
|
|
102
102
|
`)+`
|
|
103
103
|
|
|
104
|
-
Expected parameters: ${JSON.stringify(s.properties,null,2)}`}:{valid:!0,corrected:
|
|
104
|
+
Expected parameters: ${JSON.stringify(s.properties,null,2)}`}:{valid:!0,corrected:c?a:null}}function Bb(t,e){let s=[],n={...t};if(!n.function&&!n.name)return s.push('Tool call missing both "function" and "name" fields'),{valid:!1,normalized:n,errors:s};if(!n.function&&n.name&&(n.function={name:n.name,arguments:n.arguments||n.args||{}},delete n.name,delete n.args),n.function&&n.function.args!==void 0&&n.function.arguments===void 0&&(n.function.arguments=n.function.args,delete n.function.args),n.function&&(n.function.arguments===void 0||n.function.arguments===null)&&(n.function.arguments={}),n.function&&typeof n.function.arguments=="string"){let o=n.function.arguments;if(o.trim()==="")n.function.arguments={};else try{n.function.arguments=JSON.parse(o)}catch(r){return s.push(`Invalid JSON in arguments${e?` (${e})`:""}: ${r.message}`),{valid:!1,normalized:n,errors:s}}}return n.function&&typeof n.function.arguments!="object"?(s.push(`Arguments must be an object, got ${typeof n.function.arguments}`),{valid:!1,normalized:n,errors:s}):!n.function.name||typeof n.function.name!="string"?(s.push("Tool call function name must be a non-empty string"),{valid:!1,normalized:n,errors:s}):{valid:s.length===0,normalized:n,errors:s}}Sf.exports={validateToolArgs:Fb,validateToolCallFormat:Bb,closestMatch:ti,levenshtein:kf,getCachedSchema:xf,clearSchemaCache:qb}});var Rf=J((F1,Tf)=>{var{levenshtein:ni}=dc(),Ub=200,Wb=.3,Hb=2;function fc(t){return t.replace(/\r\n/g,`
|
|
105
105
|
`).replace(/\r/g,`
|
|
106
|
-
`).replace(/\t/g," ".repeat(
|
|
106
|
+
`).replace(/\t/g," ".repeat(Hb)).split(`
|
|
107
107
|
`).map(e=>{let s=e.replace(/\s+$/,""),n=s.match(/^(\s*)(.*)/);if(!n)return s;let[,o,r]=n;return o+r.replace(/ {2,}/g," ")}).join(`
|
|
108
|
-
`)}function
|
|
108
|
+
`)}function Yb(t,e){if(t.includes(e))return e;if(e.length<10)return null;let s=fc(t),n=fc(e);if(!s.includes(n))return null;let o=t.split(`
|
|
109
109
|
`),r=s.split(`
|
|
110
110
|
`),i=n.split(`
|
|
111
|
-
`),a=i[0],
|
|
112
|
-
`)}if(i.length===1){for(let
|
|
111
|
+
`),a=i[0],c=i[i.length-1];for(let l=0;l<=r.length-i.length;l++){let u=!0;for(let d=0;d<i.length;d++)if(r[l+d]!==i[d]){u=!1;break}if(u)return o.slice(l,l+i.length).join(`
|
|
112
|
+
`)}if(i.length===1){for(let l=0;l<r.length;l++)if(r[l].indexOf(n)!==-1)return o[l]}return null}function Gb(t,e){if(!t||!e)return null;let s=t.split(`
|
|
113
113
|
`),o=e.split(`
|
|
114
|
-
`).length;return s.length===0||o===0?null:o===1?
|
|
115
|
-
`),
|
|
116
|
-
`),p=
|
|
117
|
-
`),n=[],o=t?`.${t.split(".").pop()}`:"";for(let r=0;r<s.length;r++){let i=s[r],a=r+1;for(let
|
|
118
|
-
`).filter(Boolean),
|
|
119
|
-
`);for(let o=0;o<n.length;o++){let r=n[o],i=o+1;if([".js",".ts",".jsx",".tsx",".mjs",".cjs"].includes(e)){let a=r.match(/(?:export\s+)?(?:async\s+)?function\s+(\w+)/);a&&s.push({type:"function",name:a[1],line:i});let
|
|
114
|
+
`).length;return s.length===0||o===0?null:o===1?zb(s,e):Xb(s,e,o)}function vf(t){return Math.max(1,Math.floor(t/Ub))}function Ef(t,e){return t<=Math.ceil(e*Wb)}function zb(t,e){let s=e.trim(),n=vf(t.length),o=null,r=1/0;for(let i=0;i<t.length;i+=n){let a=t[i];if(!a.trim())continue;let c=ni(a.trim(),s);c<r&&(r=c,o={text:a,distance:c,line:i+1})}return o&&n>1&&(o=Kb(t,s,o,n)||o,r=o.distance),Ef(r,e.length)?o:null}function Kb(t,e,s,n){let o=s.line-1,r=Math.max(0,o-n),i=Math.min(t.length-1,o+n),a=s.distance,c=null;for(let l=r;l<=i;l++){let u=t[l];if(!u.trim())continue;let d=ni(u.trim(),e);d<a&&(a=d,c={text:u,distance:d,line:l+1})}return c}function Xb(t,e,s){let n=t.length-s+1;if(n<=0)return null;let o=vf(n),r=null,i=1/0;for(let a=0;a<n;a+=o){let c=t.slice(a,a+s).join(`
|
|
115
|
+
`),l=ni(c,e);l<i&&(i=l,r={text:c,distance:l,line:a+1})}return r&&o>1&&(r=Vb(t,e,r,o,s,n)||r,i=r.distance),Ef(i,e.length)?r:null}function Vb(t,e,s,n,o,r){let i=s.line-1,a=Math.max(0,i-n),c=Math.min(r-1,i+n),l=s.distance,u=null;for(let d=a;d<=c;d++){let f=t.slice(d,d+o).join(`
|
|
116
|
+
`),p=ni(f,e);p<l&&(l=p,u={text:f,distance:p,line:d+1})}return u}Tf.exports={normalizeWhitespace:fc,fuzzyFindText:Yb,findMostSimilar:Gb}});var Af=J((U1,Cf)=>{var{C:B1}=Je(),Jb=[{name:"OpenAI API Key",regex:/sk-[a-zA-Z0-9]{20,}/i},{name:"Anthropic API Key",regex:/sk-ant-api03-[a-zA-Z0-9-]{90,}/i},{name:"Google Gemini API Key",regex:/AIzaSy[a-zA-Z0-9_-]{30,45}/i},{name:"Slack Token",regex:/xox[bpors]-[a-zA-Z0-9-]+/i},{name:"AWS Access Key",regex:/AKIA[A-Z0-9]{16}/i},{name:"GitHub Token",regex:/ghp_[a-zA-Z0-9]{36}/i},{name:"Private Key",regex:/BEGIN (RSA|EC|DSA|OPENSSH|PGP) PRIVATE KEY/i},{name:"Database URL",regex:/\b(postgres|mongodb|mysql|redis):\/\/[^"'\s]+/i},{name:"Hardcoded Secret",regex:/(password|secret|token|api_key|apikey|api_secret|access_token|auth_token|credentials)\s*[:=]\s*['"'][^'"']{8,}/i}],Zb=[{name:"TODO",regex:/\bTODO\b/i,severity:"warn"},{name:"FIXME",regex:/\bFIXME\b/i,severity:"warn"},{name:"Debugger",regex:/\bdebugger\b/,severity:"error",ext:[".js",".ts",".jsx",".tsx"]},{name:"eval()",regex:/\beval\s*\(/,severity:"warn",ext:[".js",".ts",".jsx",".tsx"]},{name:"Console Log",regex:/\bconsole\.log\(/,severity:"info",ext:[".js",".ts",".jsx",".tsx"]},{name:"ANSI Code",regex:/\\x1b\[[0-9;]*m/,severity:"warn",message:"Avoid hardcoded ANSI codes; use cli/ui.js instead."}];function Qb(t,e){let s=e.split(`
|
|
117
|
+
`),n=[],o=t?`.${t.split(".").pop()}`:"";for(let r=0;r<s.length;r++){let i=s[r],a=r+1;for(let c of Jb)c.regex.test(i)&&n.push({line:a,message:`Potential secret detected: ${c.name}`,severity:"error"});for(let c of Zb)c.ext&&!c.ext.includes(o)||c.regex.test(i)&&n.push({line:a,message:c.message||`Found ${c.name}`,severity:c.severity||"warn"})}return s.length>500&&n.push({line:0,message:`Large file detected (${s.length} lines). Consider refactoring.`,severity:"info"}),n}function e_(){let t=process.memoryUsage();return{rss:Math.round(t.rss/1024/1024*100)/100,heapUsed:Math.round(t.heapUsed/1024/1024*100)/100}}Cf.exports={runDiagnostics:Qb,getMemoryUsage:e_}});var gn=J((W1,Bf)=>{var Is=require("fs").promises,Et=require("path"),{exec:t_}=require("util").promisify(require("child_process").exec),An=[],mc=null,si=!1,hc=0,n_=6e4;function gc(t){return!(An.length===0||mc!==t||Date.now()-hc>n_)}async function Lf(t){if(!si&&!gc(t)){si=!0,mc=t;try{try{let{stdout:n}=await t_("rg --files",{cwd:t,timeout:5e3});An=n.split(`
|
|
118
|
+
`).filter(Boolean),hc=Date.now(),si=!1;return}catch{}let e=[],s=async(n,o)=>{let r;try{r=await Is.readdir(n,{withFileTypes:!0})}catch{return}for(let i of r){if(i.name==="node_modules"||i.name===".git"||i.name.startsWith("."))continue;let a=o?`${o}/${i.name}`:i.name;i.isDirectory()?await s(Et.join(n,i.name),a):e.push(a)}};await s(t,""),An=e,hc=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{si=!1}}}function xo(){return An}function s_(){return mc}function o_(t){return An.filter(e=>Et.basename(e)===t)}function r_(t){let e=t.toLowerCase();return An.filter(s=>s.toLowerCase().includes(e)).slice(0,20)}function If(t,e){let s=t.length,n=e.length;if(s===0)return n;if(n===0)return s;let o=Array.from({length:n+1},(r,i)=>i);for(let r=1;r<=s;r++){let i=r-1;o[0]=r;for(let a=1;a<=n;a++){let c=t[r-1]===e[a-1]?i:1+Math.min(o[a],o[a-1],i);i=o[a],o[a]=c}}return o[n]}function jf(t,e){let s=t.toLowerCase(),n=e.toLowerCase();if(s===n)return 1e3;let o=s.split("/").filter(Boolean),r=n.split("/").filter(Boolean),i=0;for(let u=1;u<=Math.min(o.length,r.length)&&o[o.length-u]===r[r.length-u];u++)i=u;if(i>0&&i===r.length)return 500+i*100;let a=Et.basename(t).toLowerCase(),c=Et.basename(e).toLowerCase(),l=0;if(a===c)l+=80;else{let u=Math.max(a.length,c.length);if(u>0&&u<100){let f=1-If(a,c)/u;f>=.6&&(l+=Math.round(f*50))}}if((s.includes(n)||n.includes(s))&&(l+=20),r.length>1){let u=new Set(o),d=0;for(let f of r)u.has(f)&&d++;l+=d*10}return i>0&&(l+=i*30),l}function i_(t,{limit:e=10,minScore:s=15}={}){if(!t||An.length===0)return[];let n=[];for(let o of An){let r=jf(o,t);r>=s&&n.push({file:o,score:r})}return n.sort((o,r)=>r.score-o.score),n.slice(0,e)}var pc=null,Of=0,Nf=null,Df=12e4,oi=null,Mf=0,Pf=null,qf=new Set([".js",".ts",".jsx",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".rb"]);function Ff(t,e){let s=[],n=t.split(`
|
|
119
|
+
`);for(let o=0;o<n.length;o++){let r=n[o],i=o+1;if([".js",".ts",".jsx",".tsx",".mjs",".cjs"].includes(e)){let a=r.match(/(?:export\s+)?(?:async\s+)?function\s+(\w+)/);a&&s.push({type:"function",name:a[1],line:i});let c=r.match(/(?:export\s+)?class\s+(\w+)/);c&&s.push({type:"class",name:c[1],line:i});let l=r.match(/(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?(?:\([^)]*\)|[\w$]+)\s*=>/);l&&s.push({type:"function",name:l[1],line:i});let u=r.match(/module\.exports\s*=\s*\{([^}]+)\}/);if(u){let f=u[1].split(",").map(p=>p.trim().split(":")[0].trim()).filter(Boolean);for(let p of f)/^\w+$/.test(p)&&s.push({type:"export",name:p,line:i})}let d=r.match(/(?:require\(['"]([^'"]+)['"]\)|from\s+['"]([^'"]+)['"])/);if(d){let f=d[1]||d[2];s.push({type:"import",name:f,line:i})}}if(e===".py"){let a=r.match(/^(?:async\s+)?def\s+(\w+)/);a&&s.push({type:"function",name:a[1],line:i});let c=r.match(/^class\s+(\w+)/);c&&s.push({type:"class",name:c[1],line:i});let l=r.match(/^(?:from\s+(\S+)\s+)?import\s+(\S+)/);l&&s.push({type:"import",name:l[1]||l[2],line:i})}if(e===".go"){let a=r.match(/^func\s+(?:\([^)]+\)\s+)?(\w+)/);a&&s.push({type:"function",name:a[1],line:i});let c=r.match(/^type\s+(\w+)\s+struct/);c&&s.push({type:"class",name:c[1],line:i})}}return s}async function yc(t){t=t||process.cwd();let e=Et.join(t,".nex","index","content-index.json"),s={};if(pc&&Nf===t&&Date.now()-Of<Df)return pc;try{let i=await Is.readFile(e,"utf-8");s=JSON.parse(i)}catch{s={files:{}}}let n=xo();(!gc(t)||n.length===0)&&(await Lf(t),n=xo());let o={files:{}},r=!1;for(let i of xo()){let a=Et.extname(i);if(!qf.has(a))continue;let c=Et.join(t,i);try{let u=(await Is.stat(c)).mtimeMs;if(s.files[i]&&s.files[i].mtime===u){o.files[i]=s.files[i];continue}let d=await Is.readFile(c,"utf-8"),f=Ff(d,a);o.files[i]={defs:f,mtime:u},r=!0}catch{}}if(r){let i=Et.join(t,".nex","index");await Is.mkdir(i,{recursive:!0}),await Is.writeFile(e,JSON.stringify(o),"utf-8")}return pc=o,Of=Date.now(),Nf=t,o}async function a_(t,e,s){let n=await yc(s),o=[],r=t.toLowerCase();for(let[i,a]of Object.entries(n.files))for(let c of a.defs)e&&c.type!==e||c.name.toLowerCase().includes(r)&&o.push({file:i,type:c.type,name:c.name,line:c.line});return o.sort((i,a)=>{let c=i.name.toLowerCase()===r?0:1,l=a.name.toLowerCase()===r?0:1;if(c!==l)return c-l;let u=i.name.toLowerCase().startsWith(r)?0:1,d=a.name.toLowerCase().startsWith(r)?0:1;return u-d}),o.slice(0,50)}function c_(t,e,s){if(!e||!e.startsWith("."))return null;let n=Et.posix.dirname(t.replace(/\\/g,"/")),o=Et.posix.normalize(Et.posix.join(n==="."?"":n,e)),r=[];if(Et.posix.extname(o))r.push(o);else for(let a of qf)r.push(`${o}${a}`),r.push(Et.posix.join(o,`index${a}`));for(let a of r)if(s.has(a))return a;return null}async function wc(t){if(t=t||process.cwd(),oi&&Pf===t&&Date.now()-Mf<Df)return oi;let e=await yc(t),s=xo(),n=new Set(s.map(i=>i.replace(/\\/g,"/"))),o={},r={};for(let i of Object.keys(e.files||{})){let a=i.replace(/\\/g,"/"),c=Array.isArray(e.files[i]?.defs)?e.files[i].defs:[],l=[],u=new Set;for(let d of c){if(d.type!=="import")continue;let f=c_(a,d.name,n);!f||f===a||u.has(f)||(u.add(f),l.push(f),r[f]||(r[f]=[]),r[f].push(a))}o[a]=l}for(let[i,a]of Object.entries(r))r[i]=[...new Set(a)].sort();return oi={importsByFile:o,importedByFile:r},Mf=Date.now(),Pf=t,oi}async function l_(t,e,s=6){if(!t)return[];let n=await wc(e),o=String(t).replace(/\\/g,"/"),r=[...n.importsByFile[o]||[],...n.importedByFile[o]||[]];return[...new Set(r)].filter(i=>i!==o).slice(0,s)}async function u_(t,e=4){let s=await wc(t),n=new Map;for(let[o,r]of Object.entries(s.importsByFile||{}))n.set(o,(n.get(o)||0)+r.length);for(let[o,r]of Object.entries(s.importedByFile||{}))n.set(o,(n.get(o)||0)+r.length);return[...n.entries()].filter(([,o])=>o>0).sort((o,r)=>r[1]-o[1]||o[0].localeCompare(r[0])).slice(0,e).map(([o,r])=>`${o} (${r} links)`)}Bf.exports={refreshIndex:Lf,getFileIndex:xo,getIndexedCwd:s_,findFileInIndex:o_,searchIndex:r_,isIndexValid:gc,buildContentIndex:yc,searchContentIndex:a_,extractDefinitions:Ff,buildImportGraph:wc,getRelatedFiles:l_,summarizeModuleHubs:u_,smartSearch:i_,scorePathMatch:jf,pathLevenshtein:If}});var js=J((H1,zf)=>{var ri=require("fs"),li=require("path"),ui=require("os"),{execFile:d_}=require("child_process"),{promisify:f_}=require("util"),$c=f_(d_),p_=li.join(ui.homedir(),".nex","servers.json"),ii=li.join(ui.tmpdir(),"nex-ssh-sockets");function h_(){return li.join(process.cwd(),".nex","servers.json")}function Uf(){let t=n=>{if(!ri.existsSync(n))return{};try{return JSON.parse(ri.readFileSync(n,"utf-8"))}catch{return{}}},e=t(p_),s=t(h_());return{...e,...s}}function m_(t){let e=Uf();if(e[t])return{...e[t],_name:t};if(/^[\w.-]+@[\w.-]+$/.test(t)||/[\w-]+\.[\w.-]+/.test(t)||t==="localhost"){let[o,r]=t.includes("@")?t.split("@"):[void 0,t];return{host:r,user:o}}let s=Object.keys(e),n=s.length?`Available profiles: ${s.join(", ")}`:"No profiles configured. Create .nex/servers.json (project) or ~/.nex/servers.json (global)";throw new Error(`Unknown server: "${t}". ${n}`)}function g_(){ri.existsSync(ii)||ri.mkdirSync(ii,{recursive:!0})}function Wf(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=yes","-o","ServerAliveInterval=30"];t.key&&e.push("-i",t.key.replace(/^~/,ui.homedir())),t.port&&Number(t.port)!==22&&e.push("-p",String(t.port)),g_();let s=t.user?`${t.user}@${t.host}`:t.host,n=li.join(ii,s.replace(/[@.:]/g,"_"));return e.push("-o","ControlMaster=auto","-o",`ControlPath=${n}`,"-o","ControlPersist=120"),e.push(s),{args:e,target:s}}function Hf(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=yes","-r"];return t.key&&e.push("-i",t.key.replace(/^~/,ui.homedir())),t.port&&Number(t.port)!==22&&e.push("-P",String(t.port)),e}async function ai(t,e,{timeout:s=3e4,sudo:n=!1}={}){let{args:o}=Wf(t),r=n&&t.sudo?`sudo sh -c ${JSON.stringify(e)}`:e;try{let{stdout:i,stderr:a}=await $c("ssh",[...o,r],{timeout:s,maxBuffer:4194304});return{stdout:i||"",stderr:a||"",exitCode:0}}catch(i){let a=typeof i.code=="number"?i.code:1,c=(i.stderr||i.message||"").toString();return{stdout:(i.stdout||"").toString(),stderr:c,exitCode:a,error:di(c,t)}}}async function y_(t,e,s,{timeout:n=12e4}={}){let o=Hf(t),r=t.user?`${t.user}@${t.host}`:t.host;o.push(e,`${r}:${s}`);try{let{stdout:i,stderr:a}=await $c("scp",o,{timeout:n,maxBuffer:1048576});return i||a||`Uploaded ${e} \u2192 ${r}:${s}`}catch(i){let a=(i.stderr||i.message||"").toString();throw new Error(di(a,t)||a)}}async function w_(t,e,s,{timeout:n=12e4}={}){let o=Hf(t),r=t.user?`${t.user}@${t.host}`:t.host;o.push(`${r}:${e}`,s);try{let{stdout:i,stderr:a}=await $c("scp",o,{timeout:n,maxBuffer:1048576});return i||a||`Downloaded ${r}:${e} \u2192 ${s}`}catch(i){let a=(i.stderr||i.message||"").toString();throw new Error(di(a,t)||a)}}function di(t,e){if(!t)return"";if(/connection refused/i.test(t)){let s=e.port||22;return`${t}
|
|
120
120
|
HINT: Connection refused on ${e.host}:${s}. Check: server is running, SSH service is active (systemctl status sshd), firewall allows port ${s} (firewall-cmd --list-ports).`}if(/permission denied/i.test(t)){let s=e.key?`key: ${e.key}`:"SSH agent";return`${t}
|
|
121
121
|
HINT: Auth failed using ${s} as user "${e.user||"root"}". Check: authorized_keys on server, correct username, key passphrase.`}return/no route to host|network unreachable|name or service not known/i.test(t)?`${t}
|
|
122
122
|
HINT: Cannot reach ${e.host}. Check: network connection, correct hostname/IP, DNS resolution.`:/host key verification failed/i.test(t)?`${t}
|
|
123
123
|
HINT: Host key changed for ${e.host}. To reset: ssh-keygen -R ${e.host}`:/timed out/i.test(t)?`${t}
|
|
124
124
|
HINT: Connection timed out to ${e.host}. Check firewall rules and network connectivity.`:/too many authentication failures/i.test(t)?`${t}
|
|
125
|
-
HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function
|
|
126
|
-
`).filter(Boolean).map(d=>d.startsWith(
|
|
125
|
+
HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function $_(t,e){let s=e.user?`${e.user}@${e.host}`:e.host,n=e.port&&Number(e.port)!==22?`:${e.port}`:"",o=e.os?` [${e.os}]`:"",r=e.key?` key:${e.key}`:"",i=e.sudo?" sudo:yes":"";return`${t}: ${s}${n}${o}${r}${i}`}var ci=new Map,b_=12e4;async function Yf(t,e,{force:s=!1}={}){let o=`${t.user?`${t.user}@${t.host}`:t.host}:${e}`,r=ci.get(o);if(!s&&r&&Date.now()-r.time<b_)return r.files;let i=`find ${e} -maxdepth 6 -type f -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/venv/*' -not -path '*/__pycache__/*' -not -path '*/dist/*' -not -name '*.pyc' 2>/dev/null | head -5000`,{stdout:a,exitCode:c}=await ai(t,i,{timeout:15e3});if(c!==0||!a.trim())return[];let l=e.endsWith("/")?e:e+"/",u=a.split(`
|
|
126
|
+
`).filter(Boolean).map(d=>d.startsWith(l)?d.slice(l.length):d);return ci.set(o,{files:u,time:Date.now()}),u}async function Gf(t,e,s,{limit:n=5,minScore:o=15}={}){let r=await Yf(t,e);if(r.length===0)return[];let{scorePathMatch:i}=gn(),a=[];for(let c of r){let l=i(c,s);l>=o&&a.push({file:c,score:l})}return a.sort((c,l)=>l.score-c.score),a.slice(0,n)}async function __(t,e,s){if(!s)return{fixedPath:null,message:""};let n=s.replace(/\/+/g,"/");if(n.startsWith("~/")){let{stdout:r}=await ai(t,"echo $HOME",{timeout:5e3}),i=r.trim();i&&(n=n.replace("~/",i+"/"))}if(n.startsWith("/")){let{exitCode:r}=await ai(t,`test -f ${JSON.stringify(n)}`,{timeout:5e3});if(r===0)return{fixedPath:n,message:"(auto-fixed: normalized path)"}}let o=await Gf(t,e,s,{limit:5,minScore:15});if(o.length>0){let i=(e.endsWith("/")?e:e+"/")+o[0].file;if(o[0].score>=200||o.length===1&&o[0].score>=50)return{fixedPath:i,message:`(auto-fixed: remote smart match \u2192 ${o[0].file})`};if(o.length>=2&&o[0].score>=80&&o[0].score>=o[1].score*1.5)return{fixedPath:i,message:`(auto-fixed: remote best match \u2192 ${o[0].file})`};if(o.length<=5)return{fixedPath:null,message:`File not found on remote. Did you mean:
|
|
127
127
|
${o.map(a=>` - ${a.file}`).join(`
|
|
128
|
-
`)}`}}return{fixedPath:null,message:""}}function
|
|
129
|
-
`,"utf-8")}
|
|
128
|
+
`)}`}}return{fixedPath:null,message:""}}function x_(t){t?ci.delete(t):ci.clear()}zf.exports={loadServerProfiles:Uf,resolveProfile:m_,buildSSHArgs:Wf,sshExec:ai,scpUpload:y_,scpDownload:w_,enrichSSHError:di,formatProfile:$_,SSH_SOCKET_DIR:ii,getRemoteIndex:Yf,remoteSmartSearch:Gf,remoteAutoFixPath:__,clearRemoteIndex:x_}});var Vf=J((Y1,Xf)=>{var ko=require("fs"),bc=require("path"),k_=bc.join(".nex","deploy.json");function _c(){return bc.join(process.cwd(),k_)}function Kf(){let t=_c();if(!ko.existsSync(t))return{};try{return JSON.parse(ko.readFileSync(t,"utf-8"))}catch{return{}}}function S_(t){let e=Kf();if(e[t])return{...e[t],_name:t};let s=Object.keys(e),n=s.length?`Available: ${s.join(", ")}`:"No deploy configs found. Create .nex/deploy.json or use explicit params.";throw new Error(`Unknown deploy config: "${t}". ${n}`)}function v_(t){let e=bc.join(process.cwd(),".nex");ko.existsSync(e)||ko.mkdirSync(e,{recursive:!0}),ko.writeFileSync(_c(),JSON.stringify(t,null,2)+`
|
|
129
|
+
`,"utf-8")}Xf.exports={loadDeployConfigs:Kf,resolveDeployConfig:S_,saveDeployConfigs:v_,getDeployConfigPath:_c}});var To=J((G1,Qf)=>{var{getActiveModel:E_,getActiveProviderName:T_}=st(),So={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},vo={"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"},Eo={ollama:"full",openai:"full",anthropic:"full",gemini:"full",local:"essential"},nn={};function Zf(){try{let t=require("fs"),s=require("path").join(process.cwd(),".nex","config.json");t.existsSync(s)&&(nn=JSON.parse(t.readFileSync(s,"utf-8")).toolTiers||{})}catch{nn={}}}Zf();function xc(){let e=E_()?.id,s=T_();return e&&nn[e]?nn[e]:s&&nn[`${s}:*`]?nn[`${s}:*`]:e&&vo[e]?vo[e]:s&&Eo[s]?Eo[s]:"full"}var R_=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"]),Jf={anthropic:"strict",openai:"strict",gemini:"strict",ollama:"fuzzy",local:"fuzzy"};function C_(t,e){return t&&(R_.has(t)||t.startsWith("claude-"))?"strict":e&&Jf[e]?Jf[e]:"fuzzy"}function A_(t,e){return t&&nn[t]?nn[t]:e&&nn[`${e}:*`]?nn[`${e}:*`]:t&&vo[t]?vo[t]:e&&Eo[e]?Eo[e]:"full"}function O_(t,e){let s=e||xc();if(s==="full"||!So[s])return t;let n=new Set(So[s]);return t.filter(o=>n.has(o.function.name))}function N_(){let t=xc(),e=So[t]?So[t].length:"all";return{tier:t,toolCount:e}}Qf.exports={filterToolsForModel:O_,getActiveTier:xc,getModelTier:A_,getEditMode:C_,getTierInfo:N_,TIERS:So,MODEL_TIERS:vo,PROVIDER_DEFAULT_TIER:Eo,loadConfigOverrides:Zf}});var wn=J((z1,np)=>{var kc=null,yn=null,Ro=null,ep=`Playwright is not installed. Install with:
|
|
130
130
|
npm install playwright && npx playwright install chromium
|
|
131
|
-
Then restart nex-code.`;function
|
|
132
|
-
...(truncated)`:""),links:a.slice(0,20)}}finally{await o.close()}}async function ob(t,{width:e=1280,height:s=800,fullPage:n=!1,timeout:o=3e4}={}){let i=await(await oi()).newPage();try{await i.setViewportSize({width:e,height:s}),await i.goto(t,{waitUntil:"networkidle",timeout:o});let a=await i.screenshot({type:"png",fullPage:n}),l=require("os"),c=require("path"),u=require("fs"),d=c.join(l.tmpdir(),`nex-screenshot-${Date.now()}.png`);return u.writeFileSync(d,a,{mode:384}),{path:d,base64:a.toString("base64"),media_type:"image/png",title:await i.title(),url:i.url()}}finally{await i.close()}}async function rb(t,{selector:e,text:s,timeout:n=3e4}={}){if(!e&&!s)throw new Error("selector or text is required");let r=await(await oi()).newPage();try{await r.goto(t,{waitUntil:"domcontentloaded",timeout:n}),s?await r.getByText(s,{exact:!1}).first().click({timeout:1e4}):await r.locator(e).first().click({timeout:1e4}),await r.waitForLoadState("domcontentloaded");let i=await r.title();return`Clicked \u2014 now at: ${r.url()} (${i})`}finally{await r.close()}}async function ib(t,{selector:e,value:s,submit:n=!1,timeout:o=3e4}={}){if(!e||s===void 0)throw new Error("selector and value are required");let i=await(await oi()).newPage();try{return await i.goto(t,{waitUntil:"domcontentloaded",timeout:o}),await i.fill(e,String(s)),n&&(await i.keyboard.press("Enter"),await i.waitForLoadState("domcontentloaded")),`Filled "${e}" with value. ${n?`Submitted \u2192 ${i.url()}`:"Not submitted."}`}finally{await i.close()}}jf.exports={isPlaywrightAvailable:Df,browserNavigate:sb,browserScreenshot:ob,browserClick:rb,browserFill:ib,closeBrowser:nb,INSTALL_MSG:If}});var pl=Q((zR,Ff)=>{"use strict";var ab=require("util"),qf=require("stream"),Ut=Ff.exports=function(){qf.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};ab.inherits(Ut,qf);Ut.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e}),process.nextTick(function(){this._process(),this._paused&&this._reads&&this._reads.length>0&&(this._paused=!1,this.emit("drain"))}.bind(this))};Ut.prototype.write=function(t,e){if(!this.writable)return this.emit("error",new Error("Stream not writable")),!1;let s;return Buffer.isBuffer(t)?s=t:s=Buffer.from(t,e||this._encoding),this._buffers.push(s),this._buffered+=s.length,this._process(),this._reads&&this._reads.length===0&&(this._paused=!0),this.writable&&!this._paused};Ut.prototype.end=function(t,e){t&&this.write(t,e),this.writable=!1,this._buffers&&(this._buffers.length===0?this._end():(this._buffers.push(null),this._process()))};Ut.prototype.destroySoon=Ut.prototype.end;Ut.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};Ut.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};Ut.prototype._processReadAllowingLess=function(t){this._reads.shift();let e=this._buffers[0];e.length>t.length?(this._buffered-=t.length,this._buffers[0]=e.slice(t.length),t.func.call(this,e.slice(0,t.length))):(this._buffered-=e.length,this._buffers.shift(),t.func.call(this,e))};Ut.prototype._processRead=function(t){this._reads.shift();let e=0,s=0,n=Buffer.alloc(t.length);for(;e<t.length;){let o=this._buffers[s++],r=Math.min(o.length,t.length-e);o.copy(n,e,0,r),e+=r,r!==o.length&&(this._buffers[--s]=o.slice(r))}s>0&&this._buffers.splice(0,s),this._buffered-=t.length,t.func.call(this,n)};Ut.prototype._process=function(){try{for(;this._buffered>0&&this._reads&&this._reads.length>0;){let t=this._reads[0];if(t.allowLess)this._processReadAllowingLess(t);else if(this._buffered>=t.length)this._processRead(t);else break}this._buffers&&!this.writable&&this._end()}catch(t){this.emit("error",t)}}});var ml=Q(hl=>{"use strict";var Sn=[{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]}];hl.getImagePasses=function(t,e){let s=[],n=t%8,o=e%8,r=(t-n)/8,i=(e-o)/8;for(let a=0;a<Sn.length;a++){let l=Sn[a],c=r*l.x.length,u=i*l.y.length;for(let d=0;d<l.x.length&&l.x[d]<n;d++)c++;for(let d=0;d<l.y.length&&l.y[d]<o;d++)u++;c>0&&u>0&&s.push({width:c,height:u,index:a})}return s};hl.getInterlaceIterator=function(t){return function(e,s,n){let o=e%Sn[n].x.length,r=(e-o)/Sn[n].x.length*8+Sn[n].x[o],i=s%Sn[n].y.length,a=(s-i)/Sn[n].y.length*8+Sn[n].y[i];return r*4+a*t*4}}});var gl=Q((XR,Bf)=>{"use strict";Bf.exports=function(e,s,n){let o=e+s-n,r=Math.abs(o-e),i=Math.abs(o-s),a=Math.abs(o-n);return r<=i&&r<=a?e:i<=a?s:n}});var yl=Q((VR,Wf)=>{"use strict";var lb=ml(),cb=gl();function Uf(t,e,s){let n=t*e;return s!==8&&(n=Math.ceil(n/(8/s))),n}var Ps=Wf.exports=function(t,e){let s=t.width,n=t.height,o=t.interlace,r=t.bpp,i=t.depth;if(this.read=e.read,this.write=e.write,this.complete=e.complete,this._imageIndex=0,this._images=[],o){let a=lb.getImagePasses(s,n);for(let l=0;l<a.length;l++)this._images.push({byteWidth:Uf(a[l].width,r,i),height:a[l].height,lineIndex:0})}else this._images.push({byteWidth:Uf(s,r,i),height:n,lineIndex:0});i===8?this._xComparison=r:i===16?this._xComparison=r*2:this._xComparison=1};Ps.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};Ps.prototype._unFilterType1=function(t,e,s){let n=this._xComparison,o=n-1;for(let r=0;r<s;r++){let i=t[1+r],a=r>o?e[r-n]:0;e[r]=i+a}};Ps.prototype._unFilterType2=function(t,e,s){let n=this._lastLine;for(let o=0;o<s;o++){let r=t[1+o],i=n?n[o]:0;e[o]=r+i}};Ps.prototype._unFilterType3=function(t,e,s){let n=this._xComparison,o=n-1,r=this._lastLine;for(let i=0;i<s;i++){let a=t[1+i],l=r?r[i]:0,c=i>o?e[i-n]:0,u=Math.floor((c+l)/2);e[i]=a+u}};Ps.prototype._unFilterType4=function(t,e,s){let n=this._xComparison,o=n-1,r=this._lastLine;for(let i=0;i<s;i++){let a=t[1+i],l=r?r[i]:0,c=i>o?e[i-n]:0,u=i>o&&r?r[i-n]:0,d=cb(c,l,u);e[i]=a+d}};Ps.prototype._reverseFilterLine=function(t){let e=t[0],s,n=this._images[this._imageIndex],o=n.byteWidth;if(e===0)s=t.slice(1,o+1);else switch(s=Buffer.alloc(o),e){case 1:this._unFilterType1(t,s,o);break;case 2:this._unFilterType2(t,s,o);break;case 3:this._unFilterType3(t,s,o);break;case 4:this._unFilterType4(t,s,o);break;default:throw new Error("Unrecognised filter type - "+e)}this.write(s),n.lineIndex++,n.lineIndex>=n.height?(this._lastLine=null,this._imageIndex++,n=this._images[this._imageIndex]):this._lastLine=s,n?this.read(n.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}});var Gf=Q((JR,Yf)=>{"use strict";var ub=require("util"),Hf=pl(),db=yl(),fb=Yf.exports=function(t){Hf.call(this);let e=[],s=this;this._filter=new db(t,{read:this.read.bind(this),write:function(n){e.push(n)},complete:function(){s.emit("complete",Buffer.concat(e))}}),this._filter.start()};ub.inherits(fb,Hf)});var Ls=Q((ZR,zf)=>{"use strict";zf.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 $l=Q((QR,Kf)=>{"use strict";var wl=[];(function(){for(let t=0;t<256;t++){let e=t;for(let s=0;s<8;s++)e&1?e=3988292384^e>>>1:e=e>>>1;wl[t]=e}})();var _l=Kf.exports=function(){this._crc=-1};_l.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=wl[(this._crc^t[e])&255]^this._crc>>>8;return!0};_l.prototype.crc32=function(){return this._crc^-1};_l.crc32=function(t){let e=-1;for(let s=0;s<t.length;s++)e=wl[(e^t[s])&255]^e>>>8;return e^-1}});var bl=Q((e1,Xf)=>{"use strict";var Ye=Ls(),pb=$l(),Xe=Xf.exports=function(t,e){this._options=t,t.checkCRC=t.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[Ye.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[Ye.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[Ye.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[Ye.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[Ye.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[Ye.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=e.read,this.error=e.error,this.metadata=e.metadata,this.gamma=e.gamma,this.transColor=e.transColor,this.palette=e.palette,this.parsed=e.parsed,this.inflateData=e.inflateData,this.finished=e.finished,this.simpleTransparency=e.simpleTransparency,this.headersFinished=e.headersFinished||function(){}};Xe.prototype.start=function(){this.read(Ye.PNG_SIGNATURE.length,this._parseSignature.bind(this))};Xe.prototype._parseSignature=function(t){let e=Ye.PNG_SIGNATURE;for(let s=0;s<e.length;s++)if(t[s]!==e[s]){this.error(new Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};Xe.prototype._parseChunkBegin=function(t){let e=t.readUInt32BE(0),s=t.readUInt32BE(4),n="";for(let r=4;r<8;r++)n+=String.fromCharCode(t[r]);let o=!!(t[4]&32);if(!this._hasIHDR&&s!==Ye.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new pb,this._crc.write(Buffer.from(n)),this._chunks[s])return this._chunks[s](e);if(!o){this.error(new Error("Unsupported critical chunk type "+n));return}this.read(e+4,this._skipChunk.bind(this))};Xe.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};Xe.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};Xe.prototype._parseChunkEnd=function(t){let e=t.readInt32BE(0),s=this._crc.crc32();if(this._options.checkCRC&&s!==e){this.error(new Error("Crc error - "+e+" - "+s));return}this._hasIEND||this.read(8,this._parseChunkBegin.bind(this))};Xe.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};Xe.prototype._parseIHDR=function(t){this._crc.write(t);let e=t.readUInt32BE(0),s=t.readUInt32BE(4),n=t[8],o=t[9],r=t[10],i=t[11],a=t[12];if(n!==8&&n!==4&&n!==2&&n!==1&&n!==16){this.error(new Error("Unsupported bit depth "+n));return}if(!(o in Ye.COLORTYPE_TO_BPP_MAP)){this.error(new Error("Unsupported color type"));return}if(r!==0){this.error(new Error("Unsupported compression method"));return}if(i!==0){this.error(new Error("Unsupported filter method"));return}if(a!==0&&a!==1){this.error(new Error("Unsupported interlace method"));return}this._colorType=o;let l=Ye.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:s,depth:n,interlace:!!a,palette:!!(o&Ye.COLORTYPE_PALETTE),color:!!(o&Ye.COLORTYPE_COLOR),alpha:!!(o&Ye.COLORTYPE_ALPHA),bpp:l,colorType:o}),this._handleChunkEnd()};Xe.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};Xe.prototype._parsePLTE=function(t){this._crc.write(t);let e=Math.floor(t.length/3);for(let s=0;s<e;s++)this._palette.push([t[s*3],t[s*3+1],t[s*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};Xe.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};Xe.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===Ye.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(new Error("Transparency chunk must be after palette"));return}if(t.length>this._palette.length){this.error(new Error("More transparent colors than palette size"));return}for(let e=0;e<t.length;e++)this._palette[e][3]=t[e];this.palette(this._palette)}this._colorType===Ye.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===Ye.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};Xe.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};Xe.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/Ye.GAMMA_DIVISION),this._handleChunkEnd()};Xe.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};Xe.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===Ye.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw new Error("Expected palette not found");this.inflateData(e);let s=t-e.length;s>0?this._handleIDAT(s):this._handleChunkEnd()};Xe.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};Xe.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var xl=Q(Jf=>{"use strict";var Vf=ml(),hb=[function(){},function(t,e,s,n){if(n===e.length)throw new Error("Ran out of data");let o=e[n];t[s]=o,t[s+1]=o,t[s+2]=o,t[s+3]=255},function(t,e,s,n){if(n+1>=e.length)throw new Error("Ran out of data");let o=e[n];t[s]=o,t[s+1]=o,t[s+2]=o,t[s+3]=e[n+1]},function(t,e,s,n){if(n+2>=e.length)throw new Error("Ran out of data");t[s]=e[n],t[s+1]=e[n+1],t[s+2]=e[n+2],t[s+3]=255},function(t,e,s,n){if(n+3>=e.length)throw new Error("Ran out of data");t[s]=e[n],t[s+1]=e[n+1],t[s+2]=e[n+2],t[s+3]=e[n+3]}],mb=[function(){},function(t,e,s,n){let o=e[0];t[s]=o,t[s+1]=o,t[s+2]=o,t[s+3]=n},function(t,e,s){let n=e[0];t[s]=n,t[s+1]=n,t[s+2]=n,t[s+3]=e[1]},function(t,e,s,n){t[s]=e[0],t[s+1]=e[1],t[s+2]=e[2],t[s+3]=n},function(t,e,s){t[s]=e[0],t[s+1]=e[1],t[s+2]=e[2],t[s+3]=e[3]}];function gb(t,e){let s=[],n=0;function o(){if(n===t.length)throw new Error("Ran out of data");let r=t[n];n++;let i,a,l,c,u,d,f,p;switch(e){default:throw new Error("unrecognised depth");case 16:f=t[n],n++,s.push((r<<8)+f);break;case 4:f=r&15,p=r>>4,s.push(p,f);break;case 2:u=r&3,d=r>>2&3,f=r>>4&3,p=r>>6&3,s.push(p,f,d,u);break;case 1:i=r&1,a=r>>1&1,l=r>>2&1,c=r>>3&1,u=r>>4&1,d=r>>5&1,f=r>>6&1,p=r>>7&1,s.push(p,f,d,u,c,l,a,i);break}}return{get:function(r){for(;s.length<r;)o();let i=s.slice(0,r);return s=s.slice(r),i},resetAfterLine:function(){s.length=0},end:function(){if(n!==t.length)throw new Error("extra data found")}}}function yb(t,e,s,n,o,r){let i=t.width,a=t.height,l=t.index;for(let c=0;c<a;c++)for(let u=0;u<i;u++){let d=s(u,c,l);hb[n](e,o,d,r),r+=n}return r}function wb(t,e,s,n,o,r){let i=t.width,a=t.height,l=t.index;for(let c=0;c<a;c++){for(let u=0;u<i;u++){let d=o.get(n),f=s(u,c,l);mb[n](e,d,f,r)}o.resetAfterLine()}}Jf.dataToBitMap=function(t,e){let s=e.width,n=e.height,o=e.depth,r=e.bpp,i=e.interlace,a;o!==8&&(a=gb(t,o));let l;o<=8?l=Buffer.alloc(s*n*4):l=new Uint16Array(s*n*4);let c=Math.pow(2,o)-1,u=0,d,f;if(i)d=Vf.getImagePasses(s,n),f=Vf.getInterlaceIterator(s,n);else{let p=0;f=function(){let m=p;return p+=4,m},d=[{width:s,height:n}]}for(let p=0;p<d.length;p++)o===8?u=yb(d[p],l,f,r,t,u):wb(d[p],l,f,r,a,c);if(o===8){if(u!==t.length)throw new Error("extra data found")}else a.end();return l}});var kl=Q((n1,Zf)=>{"use strict";function _b(t,e,s,n,o){let r=0;for(let i=0;i<n;i++)for(let a=0;a<s;a++){let l=o[t[r]];if(!l)throw new Error("index "+t[r]+" not in palette");for(let c=0;c<4;c++)e[r+c]=l[c];r+=4}}function $b(t,e,s,n,o){let r=0;for(let i=0;i<n;i++)for(let a=0;a<s;a++){let l=!1;if(o.length===1?o[0]===t[r]&&(l=!0):o[0]===t[r]&&o[1]===t[r+1]&&o[2]===t[r+2]&&(l=!0),l)for(let c=0;c<4;c++)e[r+c]=0;r+=4}}function bb(t,e,s,n,o){let r=255,i=Math.pow(2,o)-1,a=0;for(let l=0;l<n;l++)for(let c=0;c<s;c++){for(let u=0;u<4;u++)e[a+u]=Math.floor(t[a+u]*r/i+.5);a+=4}}Zf.exports=function(t,e,s=!1){let n=e.depth,o=e.width,r=e.height,i=e.colorType,a=e.transColor,l=e.palette,c=t;return i===3?_b(t,c,o,r,l):(a&&$b(t,c,o,r,a),n!==8&&!s&&(n===16&&(c=Buffer.alloc(o*r*4)),bb(t,c,o,r,n))),c}});var tp=Q((s1,ep)=>{"use strict";var xb=require("util"),Sl=require("zlib"),Qf=pl(),kb=Gf(),Sb=bl(),vb=xl(),Eb=kl(),Zt=ep.exports=function(t){Qf.call(this),this._parser=new Sb(t,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,"gamma"),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this),simpleTransparency:this._simpleTransparency.bind(this),headersFinished:this._headersFinished.bind(this)}),this._options=t,this.writable=!0,this._parser.start()};xb.inherits(Zt,Qf);Zt.prototype._handleError=function(t){this.emit("error",t),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy&&this._inflate.destroy(),this._filter&&(this._filter.destroy(),this._filter.on("error",function(){})),this.errord=!0};Zt.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=Sl.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 s=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,n=Math.max(s,Sl.Z_MIN_CHUNK);this._inflate=Sl.createInflate({chunkSize:n});let o=s,r=this.emit.bind(this,"error");this._inflate.on("error",function(a){o&&r(a)}),this._filter.on("complete",this._complete.bind(this));let i=this._filter.write.bind(this._filter);this._inflate.on("data",function(a){o&&(a.length>o&&(a=a.slice(0,o)),o-=a.length,i(a))}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};Zt.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new kb(this._bitmapInfo)};Zt.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};Zt.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};Zt.prototype._simpleTransparency=function(){this._metaData.alpha=!0};Zt.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};Zt.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};Zt.prototype._complete=function(t){if(this.errord)return;let e;try{let s=vb.dataToBitMap(t,this._bitmapInfo);e=Eb(s,this._bitmapInfo,this._options.skipRescale),s=null}catch(s){this._handleError(s);return}this.emit("parsed",e)}});var sp=Q((o1,np)=>{"use strict";var Mt=Ls();np.exports=function(t,e,s,n){let o=[Mt.COLORTYPE_COLOR_ALPHA,Mt.COLORTYPE_ALPHA].indexOf(n.colorType)!==-1;if(n.colorType===n.inputColorType){let m=(function(){let g=new ArrayBuffer(2);return new DataView(g).setInt16(0,256,!0),new Int16Array(g)[0]!==256})();if(n.bitDepth===8||n.bitDepth===16&&m)return t}let r=n.bitDepth!==16?t:new Uint16Array(t.buffer),i=255,a=Mt.COLORTYPE_TO_BPP_MAP[n.inputColorType];a===4&&!n.inputHasAlpha&&(a=3);let l=Mt.COLORTYPE_TO_BPP_MAP[n.colorType];n.bitDepth===16&&(i=65535,l*=2);let c=Buffer.alloc(e*s*l),u=0,d=0,f=n.bgColor||{};f.red===void 0&&(f.red=i),f.green===void 0&&(f.green=i),f.blue===void 0&&(f.blue=i);function p(){let m,g,_,b=i;switch(n.inputColorType){case Mt.COLORTYPE_COLOR_ALPHA:b=r[u+3],m=r[u],g=r[u+1],_=r[u+2];break;case Mt.COLORTYPE_COLOR:m=r[u],g=r[u+1],_=r[u+2];break;case Mt.COLORTYPE_ALPHA:b=r[u+1],m=r[u],g=m,_=m;break;case Mt.COLORTYPE_GRAYSCALE:m=r[u],g=m,_=m;break;default:throw new Error("input color type:"+n.inputColorType+" is not supported at present")}return n.inputHasAlpha&&(o||(b/=i,m=Math.min(Math.max(Math.round((1-b)*f.red+b*m),0),i),g=Math.min(Math.max(Math.round((1-b)*f.green+b*g),0),i),_=Math.min(Math.max(Math.round((1-b)*f.blue+b*_),0),i))),{red:m,green:g,blue:_,alpha:b}}for(let m=0;m<s;m++)for(let g=0;g<e;g++){let _=p(r,u);switch(n.colorType){case Mt.COLORTYPE_COLOR_ALPHA:case Mt.COLORTYPE_COLOR:n.bitDepth===8?(c[d]=_.red,c[d+1]=_.green,c[d+2]=_.blue,o&&(c[d+3]=_.alpha)):(c.writeUInt16BE(_.red,d),c.writeUInt16BE(_.green,d+2),c.writeUInt16BE(_.blue,d+4),o&&c.writeUInt16BE(_.alpha,d+6));break;case Mt.COLORTYPE_ALPHA:case Mt.COLORTYPE_GRAYSCALE:{let b=(_.red+_.green+_.blue)/3;n.bitDepth===8?(c[d]=b,o&&(c[d+1]=_.alpha)):(c.writeUInt16BE(b,d),o&&c.writeUInt16BE(_.alpha,d+2));break}default:throw new Error("unrecognised color Type "+n.colorType)}u+=a,d+=l}return c}});var ip=Q((r1,rp)=>{"use strict";var op=gl();function Tb(t,e,s,n,o){for(let r=0;r<s;r++)n[o+r]=t[e+r]}function Rb(t,e,s){let n=0,o=e+s;for(let r=e;r<o;r++)n+=Math.abs(t[r]);return n}function Cb(t,e,s,n,o,r){for(let i=0;i<s;i++){let a=i>=r?t[e+i-r]:0,l=t[e+i]-a;n[o+i]=l}}function Ab(t,e,s,n){let o=0;for(let r=0;r<s;r++){let i=r>=n?t[e+r-n]:0,a=t[e+r]-i;o+=Math.abs(a)}return o}function Ob(t,e,s,n,o){for(let r=0;r<s;r++){let i=e>0?t[e+r-s]:0,a=t[e+r]-i;n[o+r]=a}}function Nb(t,e,s){let n=0,o=e+s;for(let r=e;r<o;r++){let i=e>0?t[r-s]:0,a=t[r]-i;n+=Math.abs(a)}return n}function Mb(t,e,s,n,o,r){for(let i=0;i<s;i++){let a=i>=r?t[e+i-r]:0,l=e>0?t[e+i-s]:0,c=t[e+i]-(a+l>>1);n[o+i]=c}}function Pb(t,e,s,n){let o=0;for(let r=0;r<s;r++){let i=r>=n?t[e+r-n]:0,a=e>0?t[e+r-s]:0,l=t[e+r]-(i+a>>1);o+=Math.abs(l)}return o}function Lb(t,e,s,n,o,r){for(let i=0;i<s;i++){let a=i>=r?t[e+i-r]:0,l=e>0?t[e+i-s]:0,c=e>0&&i>=r?t[e+i-(s+r)]:0,u=t[e+i]-op(a,l,c);n[o+i]=u}}function Ib(t,e,s,n){let o=0;for(let r=0;r<s;r++){let i=r>=n?t[e+r-n]:0,a=e>0?t[e+r-s]:0,l=e>0&&r>=n?t[e+r-(s+n)]:0,c=t[e+r]-op(i,a,l);o+=Math.abs(c)}return o}var Db={0:Tb,1:Cb,2:Ob,3:Mb,4:Lb},jb={0:Rb,1:Ab,2:Nb,3:Pb,4:Ib};rp.exports=function(t,e,s,n,o){let r;if(!("filterType"in n)||n.filterType===-1)r=[0,1,2,3,4];else if(typeof n.filterType=="number")r=[n.filterType];else throw new Error("unrecognised filter types");n.bitDepth===16&&(o*=2);let i=e*o,a=0,l=0,c=Buffer.alloc((i+1)*s),u=r[0];for(let d=0;d<s;d++){if(r.length>1){let f=1/0;for(let p=0;p<r.length;p++){let m=jb[r[p]](t,l,i,o);m<f&&(u=r[p],f=m)}}c[a]=u,a++,Db[u](t,l,i,c,a,o),a+=i,l+=i}return c}});var vl=Q((i1,ap)=>{"use strict";var it=Ls(),qb=$l(),Fb=sp(),Bb=ip(),Ub=require("zlib"),vn=ap.exports=function(t){if(this._options=t,t.deflateChunkSize=t.deflateChunkSize||32*1024,t.deflateLevel=t.deflateLevel!=null?t.deflateLevel:9,t.deflateStrategy=t.deflateStrategy!=null?t.deflateStrategy:3,t.inputHasAlpha=t.inputHasAlpha!=null?t.inputHasAlpha:!0,t.deflateFactory=t.deflateFactory||Ub.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:it.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:it.COLORTYPE_COLOR_ALPHA,[it.COLORTYPE_GRAYSCALE,it.COLORTYPE_COLOR,it.COLORTYPE_COLOR_ALPHA,it.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([it.COLORTYPE_GRAYSCALE,it.COLORTYPE_COLOR,it.COLORTYPE_COLOR_ALPHA,it.COLORTYPE_ALPHA].indexOf(t.inputColorType)===-1)throw new Error("option input color type:"+t.inputColorType+" is not supported at present");if(t.bitDepth!==8&&t.bitDepth!==16)throw new Error("option bit depth:"+t.bitDepth+" is not supported at present")};vn.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};vn.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};vn.prototype.filterData=function(t,e,s){let n=Fb(t,e,s,this._options),o=it.COLORTYPE_TO_BPP_MAP[this._options.colorType];return Bb(n,e,s,this._options,o)};vn.prototype._packChunk=function(t,e){let s=e?e.length:0,n=Buffer.alloc(s+12);return n.writeUInt32BE(s,0),n.writeUInt32BE(t,4),e&&e.copy(n,8),n.writeInt32BE(qb.crc32(n.slice(4,n.length-4)),n.length-4),n};vn.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*it.GAMMA_DIVISION),0),this._packChunk(it.TYPE_gAMA,e)};vn.prototype.packIHDR=function(t,e){let s=Buffer.alloc(13);return s.writeUInt32BE(t,0),s.writeUInt32BE(e,4),s[8]=this._options.bitDepth,s[9]=this._options.colorType,s[10]=0,s[11]=0,s[12]=0,this._packChunk(it.TYPE_IHDR,s)};vn.prototype.packIDAT=function(t){return this._packChunk(it.TYPE_IDAT,t)};vn.prototype.packIEND=function(){return this._packChunk(it.TYPE_IEND,null)}});var dp=Q((a1,up)=>{"use strict";var Wb=require("util"),lp=require("stream"),Hb=Ls(),Yb=vl(),cp=up.exports=function(t){lp.call(this);let e=t||{};this._packer=new Yb(e),this._deflate=this._packer.createDeflate(),this.readable=!0};Wb.inherits(cp,lp);cp.prototype.pack=function(t,e,s,n){this.emit("data",Buffer.from(Hb.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,s)),n&&this.emit("data",this._packer.packGAMA(n));let o=this._packer.filterData(t,e,s);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(r){this.emit("data",this._packer.packIDAT(r))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(o)}});var yp=Q((vo,gp)=>{"use strict";var fp=require("assert").ok,Is=require("zlib"),Gb=require("util"),pp=require("buffer").kMaxLength;function Wn(t){if(!(this instanceof Wn))return new Wn(t);t&&t.chunkSize<Is.Z_MIN_CHUNK&&(t.chunkSize=Is.Z_MIN_CHUNK),Is.Inflate.call(this,t),this._offset=this._offset===void 0?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,t&&t.maxLength!=null&&(this._maxLength=t.maxLength)}function zb(t){return new Wn(t)}function hp(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}Wn.prototype._processChunk=function(t,e,s){if(typeof s=="function")return Is.Inflate._processChunk.call(this,t,e,s);let n=this,o=t&&t.length,r=this._chunkSize-this._offset,i=this._maxLength,a=0,l=[],c=0,u;this.on("error",function(m){u=m});function d(m,g){if(n._hadError)return;let _=r-g;if(fp(_>=0,"have should not go down"),_>0){let b=n._buffer.slice(n._offset,n._offset+_);if(n._offset+=_,b.length>i&&(b=b.slice(0,i)),l.push(b),c+=b.length,i-=b.length,i===0)return!1}return(g===0||n._offset>=n._chunkSize)&&(r=n._chunkSize,n._offset=0,n._buffer=Buffer.allocUnsafe(n._chunkSize)),g===0?(a+=o-m,o=m,!0):!1}fp(this._handle,"zlib binding closed");let f;do f=this._handle.writeSync(e,t,a,o,this._buffer,this._offset,r),f=f||this._writeState;while(!this._hadError&&d(f[0],f[1]));if(this._hadError)throw u;if(c>=pp)throw hp(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+pp.toString(16)+" bytes");let p=Buffer.concat(l,c);return hp(this),p};Gb.inherits(Wn,Is.Inflate);function Kb(t,e){if(typeof e=="string"&&(e=Buffer.from(e)),!(e instanceof Buffer))throw new TypeError("Not a string or buffer");let s=t._finishFlushFlag;return s==null&&(s=Is.Z_FINISH),t._processChunk(e,s)}function mp(t,e){return Kb(new Wn(e),t)}gp.exports=vo=mp;vo.Inflate=Wn;vo.createInflate=zb;vo.inflateSync=mp});var El=Q((l1,_p)=>{"use strict";var wp=_p.exports=function(t){this._buffer=t,this._reads=[]};wp.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};wp.prototype.process=function(){for(;this._reads.length>0&&this._buffer.length;){let t=this._reads[0];if(this._buffer.length&&(this._buffer.length>=t.length||t.allowLess)){this._reads.shift();let e=this._buffer;this._buffer=e.slice(t.length),t.func.call(this,e.slice(0,t.length))}else break}if(this._reads.length>0)throw new Error("There are some read requests waitng on finished stream");if(this._buffer.length>0)throw new Error("unrecognised content at end of stream")}});var bp=Q($p=>{"use strict";var Xb=El(),Vb=yl();$p.process=function(t,e){let s=[],n=new Xb(t);return new Vb(e,{read:n.read.bind(n),write:function(r){s.push(r)},complete:function(){}}).start(),n.process(),Buffer.concat(s)}});var vp=Q((u1,Sp)=>{"use strict";var xp=!0,kp=require("zlib"),Jb=yp();kp.deflateSync||(xp=!1);var Zb=El(),Qb=bp(),ex=bl(),tx=xl(),nx=kl();Sp.exports=function(t,e){if(!xp)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let s;function n(v){s=v}let o;function r(v){o=v}function i(v){o.transColor=v}function a(v){o.palette=v}function l(){o.alpha=!0}let c;function u(v){c=v}let d=[];function f(v){d.push(v)}let p=new Zb(t);if(new ex(e,{read:p.read.bind(p),error:n,metadata:r,gamma:u,palette:a,transColor:i,inflateData:f,simpleTransparency:l}).start(),p.process(),s)throw s;let g=Buffer.concat(d);d.length=0;let _;if(o.interlace)_=kp.inflateSync(g);else{let E=((o.width*o.bpp*o.depth+7>>3)+1)*o.height;_=Jb(g,{chunkSize:E,maxLength:E})}if(g=null,!_||!_.length)throw new Error("bad png - invalid inflate data response");let b=Qb.process(_,o);g=null;let A=tx.dataToBitMap(b,o);b=null;let P=nx(A,o,e.skipRescale);return o.data=P,o.gamma=c||0,o}});var Cp=Q((d1,Rp)=>{"use strict";var Ep=!0,Tp=require("zlib");Tp.deflateSync||(Ep=!1);var sx=Ls(),ox=vl();Rp.exports=function(t,e){if(!Ep)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let s=e||{},n=new ox(s),o=[];o.push(Buffer.from(sx.PNG_SIGNATURE)),o.push(n.packIHDR(t.width,t.height)),t.gamma&&o.push(n.packGAMA(t.gamma));let r=n.filterData(t.data,t.width,t.height),i=Tp.deflateSync(r,n.getDeflateOptions());if(r=null,!i||!i.length)throw new Error("bad png - invalid compressed data response");return o.push(n.packIDAT(i)),o.push(n.packIEND()),Buffer.concat(o)}});var Ap=Q(Tl=>{"use strict";var rx=vp(),ix=Cp();Tl.read=function(t,e){return rx(t,e||{})};Tl.write=function(t,e){return ix(t,e)}});var Mp=Q(Np=>{"use strict";var ax=require("util"),Op=require("stream"),lx=tp(),cx=dp(),ux=Ap(),dt=Np.PNG=function(t){Op.call(this),t=t||{},this.width=t.width|0,this.height=t.height|0,this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null,t.fill&&this.data&&this.data.fill(0),this.gamma=0,this.readable=this.writable=!0,this._parser=new lx(t),this._parser.on("error",this.emit.bind(this,"error")),this._parser.on("close",this._handleClose.bind(this)),this._parser.on("metadata",this._metadata.bind(this)),this._parser.on("gamma",this._gamma.bind(this)),this._parser.on("parsed",function(e){this.data=e,this.emit("parsed",e)}.bind(this)),this._packer=new cx(t),this._packer.on("data",this.emit.bind(this,"data")),this._packer.on("end",this.emit.bind(this,"end")),this._parser.on("close",this._handleClose.bind(this)),this._packer.on("error",this.emit.bind(this,"error"))};ax.inherits(dt,Op);dt.sync=ux;dt.prototype.pack=function(){return!this.data||!this.data.length?(this.emit("error","No data provided"),this):(process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this)),this)};dt.prototype.parse=function(t,e){if(e){let s,n;s=function(o){this.removeListener("error",n),this.data=o,e(null,this)}.bind(this),n=function(o){this.removeListener("parsed",s),e(o,null)}.bind(this),this.once("parsed",s),this.once("error",n)}return this.end(t),this};dt.prototype.write=function(t){return this._parser.write(t),!0};dt.prototype.end=function(t){this._parser.end(t)};dt.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};dt.prototype._gamma=function(t){this.gamma=t};dt.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};dt.bitblt=function(t,e,s,n,o,r,i,a){if(s|=0,n|=0,o|=0,r|=0,i|=0,a|=0,s>t.width||n>t.height||s+o>t.width||n+r>t.height)throw new Error("bitblt reading outside image");if(i>e.width||a>e.height||i+o>e.width||a+r>e.height)throw new Error("bitblt writing outside image");for(let l=0;l<r;l++)t.data.copy(e.data,(a+l)*e.width+i<<2,(n+l)*t.width+s<<2,(n+l)*t.width+s+o<<2)};dt.prototype.bitblt=function(t,e,s,n,o,r,i){return dt.bitblt(this,t,e,s,n,o,r,i),this};dt.adjustGamma=function(t){if(t.gamma){for(let e=0;e<t.height;e++)for(let s=0;s<t.width;s++){let n=t.width*e+s<<2;for(let o=0;o<3;o++){let r=t.data[n+o]/255;r=Math.pow(r,1/2.2/t.gamma),t.data[n+o]=Math.round(r*255)}}t.gamma=0}};dt.prototype.adjustGamma=function(){dt.adjustGamma(this)}});var jp={};n0(jp,{default:()=>Ip});function Ip(t,e,s,n,o,r={}){let{threshold:i=.1,alpha:a=.1,aaColor:l=[255,255,0],diffColor:c=[255,0,0],includeAA:u,diffColorAlt:d,diffMask:f}=r;if(!Rl(t)||!Rl(e)||s&&!Rl(s))throw new Error("Image data: Uint8Array, Uint8ClampedArray or Buffer expected.");if(t.length!==e.length||s&&s.length!==t.length)throw new Error("Image sizes do not match.");if(t.length!==n*o*4)throw new Error("Image data size does not match width/height.");let p=n*o,m=new Uint32Array(t.buffer,t.byteOffset,p),g=new Uint32Array(e.buffer,e.byteOffset,p),_=!0;for(let S=0;S<p;S++)if(m[S]!==g[S]){_=!1;break}if(_){if(s&&!f)for(let S=0;S<p;S++)Lp(t,4*S,a,s);return 0}let b=35215*i*i,[A,P,v]=l,[E,O,ne]=c,[J,ie,ce]=d||c,se=0;for(let S=0;S<o;S++)for(let Ee=0;Ee<n;Ee++){let W=S*n+Ee,Z=W*4,he=m[W]===g[W]?0:Dp(t,e,Z,Z,!1);if(Math.abs(he)>b){let Ce=Pp(t,Ee,S,n,o,m,g)||Pp(e,Ee,S,n,o,g,m);!u&&Ce?s&&!f&&ii(s,Z,A,P,v):(s&&(he<0?ii(s,Z,J,ie,ce):ii(s,Z,E,O,ne)),se++)}else s&&!f&&Lp(t,Z,a,s)}return se}function Rl(t){return ArrayBuffer.isView(t)&&t.BYTES_PER_ELEMENT===1}function Pp(t,e,s,n,o,r,i){let a=Math.max(e-1,0),l=Math.max(s-1,0),c=Math.min(e+1,n-1),u=Math.min(s+1,o-1),d=s*n+e,f=e===a||e===c||s===l||s===u?1:0,p=0,m=0,g=0,_=0,b=0,A=0;for(let P=a;P<=c;P++)for(let v=l;v<=u;v++){if(P===e&&v===s)continue;let E=Dp(t,t,d*4,(v*n+P)*4,!0);if(E===0){if(f++,f>2)return!1}else E<p?(p=E,g=P,_=v):E>m&&(m=E,b=P,A=v)}return p===0||m===0?!1:ri(r,g,_,n,o)&&ri(i,g,_,n,o)||ri(r,b,A,n,o)&&ri(i,b,A,n,o)}function ri(t,e,s,n,o){let r=Math.max(e-1,0),i=Math.max(s-1,0),a=Math.min(e+1,n-1),l=Math.min(s+1,o-1),c=t[s*n+e],u=e===r||e===a||s===i||s===l?1:0;for(let d=r;d<=a;d++)for(let f=i;f<=l;f++)if(!(d===e&&f===s)&&(u+=+(c===t[f*n+d]),u>2))return!0;return!1}function Dp(t,e,s,n,o){let r=t[s],i=t[s+1],a=t[s+2],l=t[s+3],c=e[n],u=e[n+1],d=e[n+2],f=e[n+3],p=r-c,m=i-u,g=a-d,_=l-f;if(!p&&!m&&!g&&!_)return 0;if(l<255||f<255){let E=48+159*(s%2),O=48+159*((s/1.618033988749895|0)%2),ne=48+159*((s/2.618033988749895|0)%2);p=(r*l-c*f-E*_)/255,m=(i*l-u*f-O*_)/255,g=(a*l-d*f-ne*_)/255}let b=p*.29889531+m*.58662247+g*.11448223;if(o)return b;let A=p*.59597799-m*.2741761-g*.32180189,P=p*.21147017-m*.52261711+g*.31114694,v=.5053*b*b+.299*A*A+.1957*P*P;return b>0?-v:v}function ii(t,e,s,n,o){t[e+0]=s,t[e+1]=n,t[e+2]=o,t[e+3]=255}function Lp(t,e,s,n){let o=255+(t[e]*.29889531+t[e+1]*.58662247+t[e+2]*.11448223-255)*s*t[e+3]/255;ii(n,e,o,o,o)}var qp=t0(()=>{});var Hn=Q((h1,Hp)=>{var fn=require("fs"),dx=require("path"),fx=require("os"),px="nex-visual-";function Bp(t){return dx.join(fx.tmpdir(),`${px}${Date.now()}-${t}`)}var Cl=null;function ai(){return Cl||(Cl=Mp().PNG),Cl}var Al=null;function hx(){if(!Al){let t=(qp(),o0(jp));Al=t.default||t}return Al}function Ml(t,e,{threshold:s=.1}={}){let n=ai(),o=hx(),r=n.sync.read(fn.readFileSync(t)),i=n.sync.read(fn.readFileSync(e)),a=Math.max(r.width,i.width),l=Math.max(r.height,i.height),c=Fp(r,a,l),u=Fp(i,a,l),d=new n({width:a,height:l}),f=o(c,u,d.data,a,l,{threshold:s,includeAA:!1}),p=a*l,m=(f/p*100).toFixed(1),g=mx(d.data,a,l,3,3),_=Bp("diff.png");return fn.writeFileSync(_,n.sync.write(d),{mode:384}),{diffPath:_,diffPercent:parseFloat(m),totalPixels:p,changedPixels:f,regionSummary:g,beforePath:t,afterPath:e,width:a,height:l}}function Fp(t,e,s){if(t.width===e&&t.height===s)return t.data;let n=Buffer.alloc(e*s*4,0);for(let o=0;o<t.height;o++){let r=o*t.width*4,i=o*e*4;t.data.copy(n,i,r,r+t.width*4)}return n}function mx(t,e,s,n,o){let r=[["top-left","top-center","top-right"],["middle-left","center","middle-right"],["bottom-left","bottom-center","bottom-right"]],i=Math.ceil(e/n),a=Math.ceil(s/o),l=[];for(let c=0;c<o;c++)for(let u=0;u<n;u++){let d=0,f=0,p=u*i,m=c*a,g=Math.min(p+i,e),_=Math.min(m+a,s);for(let b=m;b<_;b++)for(let A=p;A<g;A++){f++;let P=(b*e+A)*4;(t[P]>0||t[P+1]>0)&&d++}if(d>0){let b=(d/f*100).toFixed(1),A=r[c]&&r[c][u]?r[c][u]:`row${c}-col${u}`;l.push({name:A,changedPercent:parseFloat(b),changed:d,total:f})}}return l.sort((c,u)=>u.changedPercent-c.changedPercent),l}var Up=[{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 gx(t,{viewports:e=Up,height:s=800,fullPage:n=!1,timeout:o=3e4}={}){let{browserScreenshot:r}=dn(),i=[];for(let a of e){let l=await r(t,{width:a.width,height:s,fullPage:n,timeout:o});i.push({label:a.label,width:a.width,path:l.path,base64:l.base64,media_type:l.media_type})}return i}function Wp(t,e=[]){let s=ai(),n=s.sync.read(fn.readFileSync(t));for(let i of e){let a=yx(i.color||"#FF0000");i.type==="box"?(wx(n,i.x||0,i.y||0,i.width||50,i.height||50,a,i.thickness||3),i.label&&Nl(n,i.x||0,(i.y||0)-14,i.label,a)):i.type==="arrow"?(_x(n,i.x||0,i.y||0,i.toX||i.x+50,i.toY||i.y,a,i.thickness||3),i.label&&Nl(n,i.x||0,(i.y||0)-14,i.label,a)):i.type==="circle"&&($x(n,i.x||0,i.y||0,i.radius||20,a,i.thickness||3),i.label&&Nl(n,(i.x||0)-(i.radius||20),(i.y||0)-(i.radius||20)-14,i.label,a))}let o=Bp("annotated.png");fn.writeFileSync(o,s.sync.write(n),{mode:384});let r=fn.readFileSync(o).toString("base64");return{path:o,base64:r,media_type:"image/png"}}function yx(t){let e=t.replace("#","");return{r:parseInt(e.substring(0,2),16),g:parseInt(e.substring(2,4),16),b:parseInt(e.substring(4,6),16),a:255}}function Qt(t,e,s,n){if(e<0||s<0||e>=t.width||s>=t.height)return;let o=(s*t.width+e)*4;t.data[o]=n.r,t.data[o+1]=n.g,t.data[o+2]=n.b,t.data[o+3]=n.a}function wx(t,e,s,n,o,r,i=3){for(let a=0;a<i;a++){for(let l=0;l<n;l++)Qt(t,e+l,s+a,r),Qt(t,e+l,s+o-1-a,r);for(let l=0;l<o;l++)Qt(t,e+a,s+l,r),Qt(t,e+n-1-a,s+l,r)}}function Ol(t,e,s,n,o,r,i=3){let a=Math.abs(n-e),l=Math.abs(o-s),c=e<n?1:-1,u=s<o?1:-1,d=a-l,f=e,p=s;for(;;){let m=Math.floor(i/2);for(let _=-m;_<=m;_++)for(let b=-m;b<=m;b++)Qt(t,f+_,p+b,r);if(f===n&&p===o)break;let g=2*d;g>-l&&(d-=l,f+=c),g<a&&(d+=a,p+=u)}}function _x(t,e,s,n,o,r,i=3){Ol(t,e,s,n,o,r,i);let a=Math.atan2(o-s,n-e),l=15,c=a+Math.PI*.8,u=a-Math.PI*.8;Ol(t,n,o,Math.round(n+l*Math.cos(c)),Math.round(o+l*Math.sin(c)),r,i),Ol(t,n,o,Math.round(n+l*Math.cos(u)),Math.round(o+l*Math.sin(u)),r,i)}function $x(t,e,s,n,o,r=3){for(let i=0;i<r;i++){let a=n-i;for(let l=0;l<360;l+=.5){let c=l*Math.PI/180,u=Math.round(e+a*Math.cos(c)),d=Math.round(s+a*Math.sin(c));Qt(t,u,d,o)}}}function Nl(t,e,s,n,o){let i=n.length*6+4,a=12;for(let l=0;l<a;l++)for(let c=0;c<i;c++)Qt(t,e+c,s+l,{r:0,g:0,b:0,a:200});for(let l=0;l<i;l++)Qt(t,e+l,s+a-1,o),Qt(t,e+l,s+a-2,o);for(let l=0;l<n.length;l++){let c=e+2+l*6;for(let u=2;u<9;u++)for(let d=0;d<4;d++)Qt(t,c+d,s+u,o)}}async function*bx(t,e,{maxIterations:s=20,hmrDelay:n=1500,width:o=1280,height:r=800,timeout:i=3e4}={}){let{browserScreenshot:a}=dn(),l=xx("chokidar"),c=await a(t,{width:o,height:r,timeout:i});if(yield{iteration:0,type:"baseline",path:c.path,base64:c.base64,media_type:c.media_type},!l){yield{iteration:-1,type:"error",message:"chokidar not installed \u2014 watch mode requires it. Install with: npm install chokidar"};return}let u=0,d=!1,f=l.watch(e,{ignoreInitial:!0,ignored:/(node_modules|\.git|dist)/});f.on("change",()=>{d=!0});try{for(;u<s;){await Sx(()=>d,3e5),d=!1,u++,await kx(n);let p=await a(t,{width:o,height:r,timeout:i}),m=null;try{m=Ml(c.path,p.path)}catch{}c=p,yield{iteration:u,type:"change",path:p.path,base64:p.base64,media_type:p.media_type,diff:m?{diffPath:m.diffPath,diffPercent:m.diffPercent,changedPixels:m.changedPixels,regions:m.regionSummary}:null}}}finally{await f.close()}}function xx(t){try{return require(t)}catch{return null}}function kx(t){return new Promise(e=>setTimeout(e,t))}function Sx(t,e=6e4){return new Promise((s,n)=>{let o=setInterval(()=>{t()&&(clearInterval(o),clearTimeout(r),s())},200),r=setTimeout(()=>{clearInterval(o),n(new Error("Watch timeout \u2014 no file changes detected"))},e)})}function vx(t,{sampleRate:e=4}={}){let n=ai().sync.read(fn.readFileSync(t)),o=new Map;for(let c=0;c<n.height;c+=e)for(let u=0;u<n.width;u+=e){let d=(c*n.width+u)*4,f=n.data[d],p=n.data[d+1],m=n.data[d+2];if(n.data[d+3]<128)continue;let _=Math.round(f/8)*8,b=Math.round(p/8)*8,A=Math.round(m/8)*8,P=`${_},${b},${A}`;o.set(P,(o.get(P)||0)+1)}let r=[...o.entries()].sort((c,u)=>u[1]-c[1]).slice(0,20),i=r.reduce((c,u)=>c+u[1],0),a=r.map(([c,u])=>{let[d,f,p]=c.split(",").map(Number);return{hex:Ex(d,f,p),rgb:`rgb(${d}, ${f}, ${p})`,frequency:parseFloat((u/i*100).toFixed(1)),category:Tx(d,f,p)}}),l=Rx(n);return{colors:a,spacing:l,dimensions:{width:n.width,height:n.height},imagePath:t}}function Ex(t,e,s){return"#"+[t,e,s].map(n=>Math.min(255,n).toString(16).padStart(2,"0")).join("")}function Tx(t,e,s){let n=(t*299+e*587+s*114)/1e3;return n>240?"white/background":n<30?"black/text":n<80?"dark":t>200&&e<100&&s<100?"red/danger":t<100&&e>150&&s<100?"green/success":t<100&&e<100&&s>200?"blue/primary":t>200&&e>200&&s<100?"yellow/warning":t>200&&e>100&&s<50?"orange/accent":n>200?"light/subtle":"midtone"}function Rx(t){let e=[],s=!1,n=0,o=Cx(t);for(let i=0;i<t.height;i++){let a=!0;for(let l=0;l<t.width;l+=4){let c=(i*t.width+l)*4;if(Math.abs(t.data[c]-o.r)>20||Math.abs(t.data[c+1]-o.g)>20||Math.abs(t.data[c+2]-o.b)>20){a=!1;break}}if(a&&s)s=!1,n=i;else if(!a&&!s&&(s=!0,n>0)){let l=i-n;l>=4&&l<=200&&e.push(l)}}let r=new Map;for(let i of e){let a=Math.round(i/4)*4;r.set(a,(r.get(a)||0)+1)}return[...r.entries()].sort((i,a)=>a[1]-i[1]).slice(0,8).map(([i,a])=>({px:i,occurrences:a}))}function Cx(t){let e=[[0,0],[t.width-1,0],[0,t.height-1],[t.width-1,t.height-1]],s=0,n=0,o=0;for(let[r,i]of e){let a=(i*t.width+r)*4;s+=t.data[a],n+=t.data[a+1],o+=t.data[a+2]}return{r:Math.round(s/4),g:Math.round(n/4),b:Math.round(o/4)}}async function Ax(t,e,{width:s,height:n=800,fullPage:o=!1,threshold:r=.1,timeout:i=3e4}={}){let{browserScreenshot:a}=dn(),c=ai().sync.read(fn.readFileSync(e)),u=s||c.width,d=n||c.height,f=await a(t,{width:u,height:d,fullPage:o,timeout:i}),p=Ml(e,f.path,{threshold:r}),m=Wp(f.path,p.regionSummary.filter(g=>g.changedPercent>1).map((g,_)=>{let P=Math.ceil(p.width/3),v=Math.ceil(p.height/3),E=[["top-left","top-center","top-right"],["middle-left","center","middle-right"],["bottom-left","bottom-center","bottom-right"]],O=0,ne=0;for(let J=0;J<3;J++)for(let ie=0;ie<3;ie++)E[J][ie]===g.name&&(O=ie,ne=J);return{type:"box",x:O*P+2,y:ne*v+2,width:P-4,height:v-4,label:`${g.name}: ${g.changedPercent}%`,color:g.changedPercent>10?"#FF0000":"#FFAA00"}}));return{livePath:f.path,referencePath:e,diffPath:p.diffPath,annotatedPath:m.path,diffPercent:p.diffPercent,changedPixels:p.changedPixels,totalPixels:p.totalPixels,regions:p.regionSummary,liveBase64:f.base64,diffBase64:fn.readFileSync(p.diffPath).toString("base64"),annotatedBase64:m.base64}}Hp.exports={pixelDiff:Ml,responsiveSweep:gx,annotateImage:Wp,visualWatch:bx,extractDesignTokens:vx,designCompare:Ax,DEFAULT_VIEWPORTS:Up}});var Pl=Q((m1,Yp)=>{var{C:Pe}=Ke(),To="",ft=[],Eo=0,Yn=null;function Ox(t){Yn=t}function Nx(t,e){To=t,ft=[],Eo=0;for(let n of e){Eo++;let o=`t${Eo}`;ft.push({id:o,description:n.description||n.title||n.name||n.task||`Task ${Eo}`,status:"pending",dependsOn:n.depends_on||[],result:null})}let s=ft.map(n=>({...n}));return Yn&&Yn("create",{name:t,tasks:s}),s}function Mx(t,e,s){let n=ft.find(o=>o.id===t);return n?(n.status=e,s!==void 0&&(n.result=s),Yn&&Yn("update",{id:t,status:e,result:s}),{...n}):null}function Px(){return{name:To,tasks:ft.map(t=>({...t}))}}function Lx(){To="",ft=[],Eo=0,Yn&&Yn("clear",{})}function Ix(){return ft.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let s=ft.find(n=>n.id===e);return s&&s.status==="done"}))}function Dx(){if(ft.length===0)return`${Pe.dim}No active tasks${Pe.reset}`;let t=[];To&&(t.push(` ${Pe.bold}${Pe.cyan}Tasks: ${To}${Pe.reset}`),t.push(` ${Pe.dim}${"\u2500".repeat(40)}${Pe.reset}`));for(let o of ft){let r,i;switch(o.status){case"done":r="\u2713",i=Pe.green;break;case"in_progress":r="\u2192",i=Pe.cyan;break;case"failed":r="\u2717",i=Pe.red;break;default:r="\xB7",i=Pe.dim}let a=o.dependsOn.length>0?` ${Pe.dim}(after: ${o.dependsOn.join(", ")})${Pe.reset}`:"",l=`[${o.status}]`,c=o.description.length>50?o.description.substring(0,47)+"...":o.description;if(t.push(` ${i}${r}${Pe.reset} ${Pe.bold}${o.id}${Pe.reset} ${c.padEnd(40)} ${i}${l}${Pe.reset}${a}`),o.result&&o.status==="done"){let u=o.result.length>60?o.result.substring(0,57)+"...":o.result;t.push(` ${Pe.dim}\u2192 ${u}${Pe.reset}`)}}let e=ft.filter(o=>o.status==="done").length,s=ft.filter(o=>o.status==="failed").length,n=ft.length;return t.push(` ${Pe.dim}${"\u2500".repeat(40)}${Pe.reset}`),t.push(` ${Pe.dim}${e}/${n} done${s>0?`, ${s} failed`:""}${Pe.reset}`),t.join(`
|
|
133
|
-
`)}function
|
|
131
|
+
Then restart nex-code.`;function tp(){if(Ro!==null)return Ro;try{require("playwright"),Ro=!0}catch{Ro=!1}return Ro}async function fi(){if(!tp())throw new Error(ep);return kc||(kc=require("playwright")),(!yn||!yn.isConnected())&&(yn=await kc.chromium.launch({headless:!0})),yn}async function M_(){if(yn){try{await yn.close()}catch(t){console.error("closeBrowser failed:",t.message)}yn=null}}process.on("exit",()=>{if(yn)try{yn.close()}catch(t){console.error("Error closing browser on exit:",t.message)}});async function P_(t,{timeout:e=3e4,waitFor:s="domcontentloaded"}={}){let o=await(await fi()).newPage();try{await o.goto(t,{waitUntil:s,timeout:e});let r=await o.title(),i=await o.evaluate(()=>(document.querySelectorAll("script,style,nav,footer,header,aside,[role=navigation]").forEach(l=>l.remove()),document.body?.innerText||"")),a=await o.evaluate(()=>Array.from(document.querySelectorAll("a[href]")).slice(0,30).map(c=>({text:(c.innerText||c.textContent||"").trim().substring(0,80),href:c.href})).filter(c=>c.text&&c.href&&!c.href.startsWith("javascript:")));return{title:r,url:o.url(),text:i.substring(0,8e3)+(i.length>8e3?`
|
|
132
|
+
...(truncated)`:""),links:a.slice(0,20)}}finally{await o.close()}}async function L_(t,{width:e=1280,height:s=800,fullPage:n=!1,timeout:o=3e4}={}){let i=await(await fi()).newPage();try{await i.setViewportSize({width:e,height:s}),await i.goto(t,{waitUntil:"networkidle",timeout:o});let a=await i.screenshot({type:"png",fullPage:n}),c=require("os"),l=require("path"),u=require("fs"),d=l.join(c.tmpdir(),`nex-screenshot-${Date.now()}.png`);return u.writeFileSync(d,a,{mode:384}),{path:d,base64:a.toString("base64"),media_type:"image/png",title:await i.title(),url:i.url()}}finally{await i.close()}}async function I_(t,{selector:e,text:s,timeout:n=3e4}={}){if(!e&&!s)throw new Error("selector or text is required");let r=await(await fi()).newPage();try{await r.goto(t,{waitUntil:"domcontentloaded",timeout:n}),s?await r.getByText(s,{exact:!1}).first().click({timeout:1e4}):await r.locator(e).first().click({timeout:1e4}),await r.waitForLoadState("domcontentloaded");let i=await r.title();return`Clicked \u2014 now at: ${r.url()} (${i})`}finally{await r.close()}}async function j_(t,{selector:e,value:s,submit:n=!1,timeout:o=3e4}={}){if(!e||s===void 0)throw new Error("selector and value are required");let i=await(await fi()).newPage();try{return await i.goto(t,{waitUntil:"domcontentloaded",timeout:o}),await i.fill(e,String(s)),n&&(await i.keyboard.press("Enter"),await i.waitForLoadState("domcontentloaded")),`Filled "${e}" with value. ${n?`Submitted \u2192 ${i.url()}`:"Not submitted."}`}finally{await i.close()}}np.exports={isPlaywrightAvailable:tp,browserNavigate:P_,browserScreenshot:L_,browserClick:I_,browserFill:j_,closeBrowser:M_,INSTALL_MSG:ep}});var Sc=J((K1,op)=>{"use strict";var D_=require("util"),sp=require("stream"),Gt=op.exports=function(){sp.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};D_.inherits(Gt,sp);Gt.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e}),process.nextTick(function(){this._process(),this._paused&&this._reads&&this._reads.length>0&&(this._paused=!1,this.emit("drain"))}.bind(this))};Gt.prototype.write=function(t,e){if(!this.writable)return this.emit("error",new Error("Stream not writable")),!1;let s;return Buffer.isBuffer(t)?s=t:s=Buffer.from(t,e||this._encoding),this._buffers.push(s),this._buffered+=s.length,this._process(),this._reads&&this._reads.length===0&&(this._paused=!0),this.writable&&!this._paused};Gt.prototype.end=function(t,e){t&&this.write(t,e),this.writable=!1,this._buffers&&(this._buffers.length===0?this._end():(this._buffers.push(null),this._process()))};Gt.prototype.destroySoon=Gt.prototype.end;Gt.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};Gt.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};Gt.prototype._processReadAllowingLess=function(t){this._reads.shift();let e=this._buffers[0];e.length>t.length?(this._buffered-=t.length,this._buffers[0]=e.slice(t.length),t.func.call(this,e.slice(0,t.length))):(this._buffered-=e.length,this._buffers.shift(),t.func.call(this,e))};Gt.prototype._processRead=function(t){this._reads.shift();let e=0,s=0,n=Buffer.alloc(t.length);for(;e<t.length;){let o=this._buffers[s++],r=Math.min(o.length,t.length-e);o.copy(n,e,0,r),e+=r,r!==o.length&&(this._buffers[--s]=o.slice(r))}s>0&&this._buffers.splice(0,s),this._buffered-=t.length,t.func.call(this,n)};Gt.prototype._process=function(){try{for(;this._buffered>0&&this._reads&&this._reads.length>0;){let t=this._reads[0];if(t.allowLess)this._processReadAllowingLess(t);else if(this._buffered>=t.length)this._processRead(t);else break}this._buffers&&!this.writable&&this._end()}catch(t){this.emit("error",t)}}});var Ec=J(vc=>{"use strict";var On=[{x:[0],y:[0]},{x:[4],y:[0]},{x:[0,4],y:[4]},{x:[2,6],y:[0,4]},{x:[0,2,4,6],y:[2,6]},{x:[1,3,5,7],y:[0,2,4,6]},{x:[0,1,2,3,4,5,6,7],y:[1,3,5,7]}];vc.getImagePasses=function(t,e){let s=[],n=t%8,o=e%8,r=(t-n)/8,i=(e-o)/8;for(let a=0;a<On.length;a++){let c=On[a],l=r*c.x.length,u=i*c.y.length;for(let d=0;d<c.x.length&&c.x[d]<n;d++)l++;for(let d=0;d<c.y.length&&c.y[d]<o;d++)u++;l>0&&u>0&&s.push({width:l,height:u,index:a})}return s};vc.getInterlaceIterator=function(t){return function(e,s,n){let o=e%On[n].x.length,r=(e-o)/On[n].x.length*8+On[n].x[o],i=s%On[n].y.length,a=(s-i)/On[n].y.length*8+On[n].y[i];return r*4+a*t*4}}});var Tc=J((V1,rp)=>{"use strict";rp.exports=function(e,s,n){let o=e+s-n,r=Math.abs(o-e),i=Math.abs(o-s),a=Math.abs(o-n);return r<=i&&r<=a?e:i<=a?s:n}});var Rc=J((J1,ap)=>{"use strict";var q_=Ec(),F_=Tc();function ip(t,e,s){let n=t*e;return s!==8&&(n=Math.ceil(n/(8/s))),n}var Ds=ap.exports=function(t,e){let s=t.width,n=t.height,o=t.interlace,r=t.bpp,i=t.depth;if(this.read=e.read,this.write=e.write,this.complete=e.complete,this._imageIndex=0,this._images=[],o){let a=q_.getImagePasses(s,n);for(let c=0;c<a.length;c++)this._images.push({byteWidth:ip(a[c].width,r,i),height:a[c].height,lineIndex:0})}else this._images.push({byteWidth:ip(s,r,i),height:n,lineIndex:0});i===8?this._xComparison=r:i===16?this._xComparison=r*2:this._xComparison=1};Ds.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};Ds.prototype._unFilterType1=function(t,e,s){let n=this._xComparison,o=n-1;for(let r=0;r<s;r++){let i=t[1+r],a=r>o?e[r-n]:0;e[r]=i+a}};Ds.prototype._unFilterType2=function(t,e,s){let n=this._lastLine;for(let o=0;o<s;o++){let r=t[1+o],i=n?n[o]:0;e[o]=r+i}};Ds.prototype._unFilterType3=function(t,e,s){let n=this._xComparison,o=n-1,r=this._lastLine;for(let i=0;i<s;i++){let a=t[1+i],c=r?r[i]:0,l=i>o?e[i-n]:0,u=Math.floor((l+c)/2);e[i]=a+u}};Ds.prototype._unFilterType4=function(t,e,s){let n=this._xComparison,o=n-1,r=this._lastLine;for(let i=0;i<s;i++){let a=t[1+i],c=r?r[i]:0,l=i>o?e[i-n]:0,u=i>o&&r?r[i-n]:0,d=F_(l,c,u);e[i]=a+d}};Ds.prototype._reverseFilterLine=function(t){let e=t[0],s,n=this._images[this._imageIndex],o=n.byteWidth;if(e===0)s=t.slice(1,o+1);else switch(s=Buffer.alloc(o),e){case 1:this._unFilterType1(t,s,o);break;case 2:this._unFilterType2(t,s,o);break;case 3:this._unFilterType3(t,s,o);break;case 4:this._unFilterType4(t,s,o);break;default:throw new Error("Unrecognised filter type - "+e)}this.write(s),n.lineIndex++,n.lineIndex>=n.height?(this._lastLine=null,this._imageIndex++,n=this._images[this._imageIndex]):this._lastLine=s,n?this.read(n.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}});var up=J((Z1,lp)=>{"use strict";var B_=require("util"),cp=Sc(),U_=Rc(),W_=lp.exports=function(t){cp.call(this);let e=[],s=this;this._filter=new U_(t,{read:this.read.bind(this),write:function(n){e.push(n)},complete:function(){s.emit("complete",Buffer.concat(e))}}),this._filter.start()};B_.inherits(W_,cp)});var qs=J((Q1,dp)=>{"use strict";dp.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 Oc=J((eC,fp)=>{"use strict";var Cc=[];(function(){for(let t=0;t<256;t++){let e=t;for(let s=0;s<8;s++)e&1?e=3988292384^e>>>1:e=e>>>1;Cc[t]=e}})();var Ac=fp.exports=function(){this._crc=-1};Ac.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=Cc[(this._crc^t[e])&255]^this._crc>>>8;return!0};Ac.prototype.crc32=function(){return this._crc^-1};Ac.crc32=function(t){let e=-1;for(let s=0;s<t.length;s++)e=Cc[(e^t[s])&255]^e>>>8;return e^-1}});var Nc=J((tC,pp)=>{"use strict";var Xe=qs(),H_=Oc(),Ze=pp.exports=function(t,e){this._options=t,t.checkCRC=t.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[Xe.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[Xe.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[Xe.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[Xe.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[Xe.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[Xe.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=e.read,this.error=e.error,this.metadata=e.metadata,this.gamma=e.gamma,this.transColor=e.transColor,this.palette=e.palette,this.parsed=e.parsed,this.inflateData=e.inflateData,this.finished=e.finished,this.simpleTransparency=e.simpleTransparency,this.headersFinished=e.headersFinished||function(){}};Ze.prototype.start=function(){this.read(Xe.PNG_SIGNATURE.length,this._parseSignature.bind(this))};Ze.prototype._parseSignature=function(t){let e=Xe.PNG_SIGNATURE;for(let s=0;s<e.length;s++)if(t[s]!==e[s]){this.error(new Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};Ze.prototype._parseChunkBegin=function(t){let e=t.readUInt32BE(0),s=t.readUInt32BE(4),n="";for(let r=4;r<8;r++)n+=String.fromCharCode(t[r]);let o=!!(t[4]&32);if(!this._hasIHDR&&s!==Xe.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new H_,this._crc.write(Buffer.from(n)),this._chunks[s])return this._chunks[s](e);if(!o){this.error(new Error("Unsupported critical chunk type "+n));return}this.read(e+4,this._skipChunk.bind(this))};Ze.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};Ze.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};Ze.prototype._parseChunkEnd=function(t){let e=t.readInt32BE(0),s=this._crc.crc32();if(this._options.checkCRC&&s!==e){this.error(new Error("Crc error - "+e+" - "+s));return}this._hasIEND||this.read(8,this._parseChunkBegin.bind(this))};Ze.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};Ze.prototype._parseIHDR=function(t){this._crc.write(t);let e=t.readUInt32BE(0),s=t.readUInt32BE(4),n=t[8],o=t[9],r=t[10],i=t[11],a=t[12];if(n!==8&&n!==4&&n!==2&&n!==1&&n!==16){this.error(new Error("Unsupported bit depth "+n));return}if(!(o in Xe.COLORTYPE_TO_BPP_MAP)){this.error(new Error("Unsupported color type"));return}if(r!==0){this.error(new Error("Unsupported compression method"));return}if(i!==0){this.error(new Error("Unsupported filter method"));return}if(a!==0&&a!==1){this.error(new Error("Unsupported interlace method"));return}this._colorType=o;let c=Xe.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:s,depth:n,interlace:!!a,palette:!!(o&Xe.COLORTYPE_PALETTE),color:!!(o&Xe.COLORTYPE_COLOR),alpha:!!(o&Xe.COLORTYPE_ALPHA),bpp:c,colorType:o}),this._handleChunkEnd()};Ze.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};Ze.prototype._parsePLTE=function(t){this._crc.write(t);let e=Math.floor(t.length/3);for(let s=0;s<e;s++)this._palette.push([t[s*3],t[s*3+1],t[s*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};Ze.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};Ze.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===Xe.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(new Error("Transparency chunk must be after palette"));return}if(t.length>this._palette.length){this.error(new Error("More transparent colors than palette size"));return}for(let e=0;e<t.length;e++)this._palette[e][3]=t[e];this.palette(this._palette)}this._colorType===Xe.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===Xe.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};Ze.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};Ze.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/Xe.GAMMA_DIVISION),this._handleChunkEnd()};Ze.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};Ze.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===Xe.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw new Error("Expected palette not found");this.inflateData(e);let s=t-e.length;s>0?this._handleIDAT(s):this._handleChunkEnd()};Ze.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};Ze.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var Mc=J(mp=>{"use strict";var hp=Ec(),Y_=[function(){},function(t,e,s,n){if(n===e.length)throw new Error("Ran out of data");let o=e[n];t[s]=o,t[s+1]=o,t[s+2]=o,t[s+3]=255},function(t,e,s,n){if(n+1>=e.length)throw new Error("Ran out of data");let o=e[n];t[s]=o,t[s+1]=o,t[s+2]=o,t[s+3]=e[n+1]},function(t,e,s,n){if(n+2>=e.length)throw new Error("Ran out of data");t[s]=e[n],t[s+1]=e[n+1],t[s+2]=e[n+2],t[s+3]=255},function(t,e,s,n){if(n+3>=e.length)throw new Error("Ran out of data");t[s]=e[n],t[s+1]=e[n+1],t[s+2]=e[n+2],t[s+3]=e[n+3]}],G_=[function(){},function(t,e,s,n){let o=e[0];t[s]=o,t[s+1]=o,t[s+2]=o,t[s+3]=n},function(t,e,s){let n=e[0];t[s]=n,t[s+1]=n,t[s+2]=n,t[s+3]=e[1]},function(t,e,s,n){t[s]=e[0],t[s+1]=e[1],t[s+2]=e[2],t[s+3]=n},function(t,e,s){t[s]=e[0],t[s+1]=e[1],t[s+2]=e[2],t[s+3]=e[3]}];function z_(t,e){let s=[],n=0;function o(){if(n===t.length)throw new Error("Ran out of data");let r=t[n];n++;let i,a,c,l,u,d,f,p;switch(e){default:throw new Error("unrecognised depth");case 16:f=t[n],n++,s.push((r<<8)+f);break;case 4:f=r&15,p=r>>4,s.push(p,f);break;case 2:u=r&3,d=r>>2&3,f=r>>4&3,p=r>>6&3,s.push(p,f,d,u);break;case 1:i=r&1,a=r>>1&1,c=r>>2&1,l=r>>3&1,u=r>>4&1,d=r>>5&1,f=r>>6&1,p=r>>7&1,s.push(p,f,d,u,l,c,a,i);break}}return{get:function(r){for(;s.length<r;)o();let i=s.slice(0,r);return s=s.slice(r),i},resetAfterLine:function(){s.length=0},end:function(){if(n!==t.length)throw new Error("extra data found")}}}function K_(t,e,s,n,o,r){let i=t.width,a=t.height,c=t.index;for(let l=0;l<a;l++)for(let u=0;u<i;u++){let d=s(u,l,c);Y_[n](e,o,d,r),r+=n}return r}function X_(t,e,s,n,o,r){let i=t.width,a=t.height,c=t.index;for(let l=0;l<a;l++){for(let u=0;u<i;u++){let d=o.get(n),f=s(u,l,c);G_[n](e,d,f,r)}o.resetAfterLine()}}mp.dataToBitMap=function(t,e){let s=e.width,n=e.height,o=e.depth,r=e.bpp,i=e.interlace,a;o!==8&&(a=z_(t,o));let c;o<=8?c=Buffer.alloc(s*n*4):c=new Uint16Array(s*n*4);let l=Math.pow(2,o)-1,u=0,d,f;if(i)d=hp.getImagePasses(s,n),f=hp.getInterlaceIterator(s,n);else{let p=0;f=function(){let h=p;return p+=4,h},d=[{width:s,height:n}]}for(let p=0;p<d.length;p++)o===8?u=K_(d[p],c,f,r,t,u):X_(d[p],c,f,r,a,l);if(o===8){if(u!==t.length)throw new Error("extra data found")}else a.end();return c}});var Pc=J((sC,gp)=>{"use strict";function V_(t,e,s,n,o){let r=0;for(let i=0;i<n;i++)for(let a=0;a<s;a++){let c=o[t[r]];if(!c)throw new Error("index "+t[r]+" not in palette");for(let l=0;l<4;l++)e[r+l]=c[l];r+=4}}function J_(t,e,s,n,o){let r=0;for(let i=0;i<n;i++)for(let a=0;a<s;a++){let c=!1;if(o.length===1?o[0]===t[r]&&(c=!0):o[0]===t[r]&&o[1]===t[r+1]&&o[2]===t[r+2]&&(c=!0),c)for(let l=0;l<4;l++)e[r+l]=0;r+=4}}function Z_(t,e,s,n,o){let r=255,i=Math.pow(2,o)-1,a=0;for(let c=0;c<n;c++)for(let l=0;l<s;l++){for(let u=0;u<4;u++)e[a+u]=Math.floor(t[a+u]*r/i+.5);a+=4}}gp.exports=function(t,e,s=!1){let n=e.depth,o=e.width,r=e.height,i=e.colorType,a=e.transColor,c=e.palette,l=t;return i===3?V_(t,l,o,r,c):(a&&J_(t,l,o,r,a),n!==8&&!s&&(n===16&&(l=Buffer.alloc(o*r*4)),Z_(t,l,o,r,n))),l}});var $p=J((oC,wp)=>{"use strict";var Q_=require("util"),Lc=require("zlib"),yp=Sc(),ex=up(),tx=Nc(),nx=Mc(),sx=Pc(),sn=wp.exports=function(t){yp.call(this),this._parser=new tx(t,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,"gamma"),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this),simpleTransparency:this._simpleTransparency.bind(this),headersFinished:this._headersFinished.bind(this)}),this._options=t,this.writable=!0,this._parser.start()};Q_.inherits(sn,yp);sn.prototype._handleError=function(t){this.emit("error",t),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy&&this._inflate.destroy(),this._filter&&(this._filter.destroy(),this._filter.on("error",function(){})),this.errord=!0};sn.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=Lc.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 s=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,n=Math.max(s,Lc.Z_MIN_CHUNK);this._inflate=Lc.createInflate({chunkSize:n});let o=s,r=this.emit.bind(this,"error");this._inflate.on("error",function(a){o&&r(a)}),this._filter.on("complete",this._complete.bind(this));let i=this._filter.write.bind(this._filter);this._inflate.on("data",function(a){o&&(a.length>o&&(a=a.slice(0,o)),o-=a.length,i(a))}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};sn.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new ex(this._bitmapInfo)};sn.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};sn.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};sn.prototype._simpleTransparency=function(){this._metaData.alpha=!0};sn.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};sn.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};sn.prototype._complete=function(t){if(this.errord)return;let e;try{let s=nx.dataToBitMap(t,this._bitmapInfo);e=sx(s,this._bitmapInfo,this._options.skipRescale),s=null}catch(s){this._handleError(s);return}this.emit("parsed",e)}});var _p=J((rC,bp)=>{"use strict";var jt=qs();bp.exports=function(t,e,s,n){let o=[jt.COLORTYPE_COLOR_ALPHA,jt.COLORTYPE_ALPHA].indexOf(n.colorType)!==-1;if(n.colorType===n.inputColorType){let h=(function(){let g=new ArrayBuffer(2);return new DataView(g).setInt16(0,256,!0),new Int16Array(g)[0]!==256})();if(n.bitDepth===8||n.bitDepth===16&&h)return t}let r=n.bitDepth!==16?t:new Uint16Array(t.buffer),i=255,a=jt.COLORTYPE_TO_BPP_MAP[n.inputColorType];a===4&&!n.inputHasAlpha&&(a=3);let c=jt.COLORTYPE_TO_BPP_MAP[n.colorType];n.bitDepth===16&&(i=65535,c*=2);let l=Buffer.alloc(e*s*c),u=0,d=0,f=n.bgColor||{};f.red===void 0&&(f.red=i),f.green===void 0&&(f.green=i),f.blue===void 0&&(f.blue=i);function p(){let h,g,w,x=i;switch(n.inputColorType){case jt.COLORTYPE_COLOR_ALPHA:x=r[u+3],h=r[u],g=r[u+1],w=r[u+2];break;case jt.COLORTYPE_COLOR:h=r[u],g=r[u+1],w=r[u+2];break;case jt.COLORTYPE_ALPHA:x=r[u+1],h=r[u],g=h,w=h;break;case jt.COLORTYPE_GRAYSCALE:h=r[u],g=h,w=h;break;default:throw new Error("input color type:"+n.inputColorType+" is not supported at present")}return n.inputHasAlpha&&(o||(x/=i,h=Math.min(Math.max(Math.round((1-x)*f.red+x*h),0),i),g=Math.min(Math.max(Math.round((1-x)*f.green+x*g),0),i),w=Math.min(Math.max(Math.round((1-x)*f.blue+x*w),0),i))),{red:h,green:g,blue:w,alpha:x}}for(let h=0;h<s;h++)for(let g=0;g<e;g++){let w=p(r,u);switch(n.colorType){case jt.COLORTYPE_COLOR_ALPHA:case jt.COLORTYPE_COLOR:n.bitDepth===8?(l[d]=w.red,l[d+1]=w.green,l[d+2]=w.blue,o&&(l[d+3]=w.alpha)):(l.writeUInt16BE(w.red,d),l.writeUInt16BE(w.green,d+2),l.writeUInt16BE(w.blue,d+4),o&&l.writeUInt16BE(w.alpha,d+6));break;case jt.COLORTYPE_ALPHA:case jt.COLORTYPE_GRAYSCALE:{let x=(w.red+w.green+w.blue)/3;n.bitDepth===8?(l[d]=x,o&&(l[d+1]=w.alpha)):(l.writeUInt16BE(x,d),o&&l.writeUInt16BE(w.alpha,d+2));break}default:throw new Error("unrecognised color Type "+n.colorType)}u+=a,d+=c}return l}});var Sp=J((iC,kp)=>{"use strict";var xp=Tc();function ox(t,e,s,n,o){for(let r=0;r<s;r++)n[o+r]=t[e+r]}function rx(t,e,s){let n=0,o=e+s;for(let r=e;r<o;r++)n+=Math.abs(t[r]);return n}function ix(t,e,s,n,o,r){for(let i=0;i<s;i++){let a=i>=r?t[e+i-r]:0,c=t[e+i]-a;n[o+i]=c}}function ax(t,e,s,n){let o=0;for(let r=0;r<s;r++){let i=r>=n?t[e+r-n]:0,a=t[e+r]-i;o+=Math.abs(a)}return o}function cx(t,e,s,n,o){for(let r=0;r<s;r++){let i=e>0?t[e+r-s]:0,a=t[e+r]-i;n[o+r]=a}}function lx(t,e,s){let n=0,o=e+s;for(let r=e;r<o;r++){let i=e>0?t[r-s]:0,a=t[r]-i;n+=Math.abs(a)}return n}function ux(t,e,s,n,o,r){for(let i=0;i<s;i++){let a=i>=r?t[e+i-r]:0,c=e>0?t[e+i-s]:0,l=t[e+i]-(a+c>>1);n[o+i]=l}}function dx(t,e,s,n){let o=0;for(let r=0;r<s;r++){let i=r>=n?t[e+r-n]:0,a=e>0?t[e+r-s]:0,c=t[e+r]-(i+a>>1);o+=Math.abs(c)}return o}function fx(t,e,s,n,o,r){for(let i=0;i<s;i++){let a=i>=r?t[e+i-r]:0,c=e>0?t[e+i-s]:0,l=e>0&&i>=r?t[e+i-(s+r)]:0,u=t[e+i]-xp(a,c,l);n[o+i]=u}}function px(t,e,s,n){let o=0;for(let r=0;r<s;r++){let i=r>=n?t[e+r-n]:0,a=e>0?t[e+r-s]:0,c=e>0&&r>=n?t[e+r-(s+n)]:0,l=t[e+r]-xp(i,a,c);o+=Math.abs(l)}return o}var hx={0:ox,1:ix,2:cx,3:ux,4:fx},mx={0:rx,1:ax,2:lx,3:dx,4:px};kp.exports=function(t,e,s,n,o){let r;if(!("filterType"in n)||n.filterType===-1)r=[0,1,2,3,4];else if(typeof n.filterType=="number")r=[n.filterType];else throw new Error("unrecognised filter types");n.bitDepth===16&&(o*=2);let i=e*o,a=0,c=0,l=Buffer.alloc((i+1)*s),u=r[0];for(let d=0;d<s;d++){if(r.length>1){let f=1/0;for(let p=0;p<r.length;p++){let h=mx[r[p]](t,c,i,o);h<f&&(u=r[p],f=h)}}l[a]=u,a++,hx[u](t,c,i,l,a,o),a+=i,c+=i}return l}});var Ic=J((aC,vp)=>{"use strict";var ut=qs(),gx=Oc(),yx=_p(),wx=Sp(),$x=require("zlib"),Nn=vp.exports=function(t){if(this._options=t,t.deflateChunkSize=t.deflateChunkSize||32*1024,t.deflateLevel=t.deflateLevel!=null?t.deflateLevel:9,t.deflateStrategy=t.deflateStrategy!=null?t.deflateStrategy:3,t.inputHasAlpha=t.inputHasAlpha!=null?t.inputHasAlpha:!0,t.deflateFactory=t.deflateFactory||$x.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:ut.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:ut.COLORTYPE_COLOR_ALPHA,[ut.COLORTYPE_GRAYSCALE,ut.COLORTYPE_COLOR,ut.COLORTYPE_COLOR_ALPHA,ut.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([ut.COLORTYPE_GRAYSCALE,ut.COLORTYPE_COLOR,ut.COLORTYPE_COLOR_ALPHA,ut.COLORTYPE_ALPHA].indexOf(t.inputColorType)===-1)throw new Error("option input color type:"+t.inputColorType+" is not supported at present");if(t.bitDepth!==8&&t.bitDepth!==16)throw new Error("option bit depth:"+t.bitDepth+" is not supported at present")};Nn.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};Nn.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};Nn.prototype.filterData=function(t,e,s){let n=yx(t,e,s,this._options),o=ut.COLORTYPE_TO_BPP_MAP[this._options.colorType];return wx(n,e,s,this._options,o)};Nn.prototype._packChunk=function(t,e){let s=e?e.length:0,n=Buffer.alloc(s+12);return n.writeUInt32BE(s,0),n.writeUInt32BE(t,4),e&&e.copy(n,8),n.writeInt32BE(gx.crc32(n.slice(4,n.length-4)),n.length-4),n};Nn.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*ut.GAMMA_DIVISION),0),this._packChunk(ut.TYPE_gAMA,e)};Nn.prototype.packIHDR=function(t,e){let s=Buffer.alloc(13);return s.writeUInt32BE(t,0),s.writeUInt32BE(e,4),s[8]=this._options.bitDepth,s[9]=this._options.colorType,s[10]=0,s[11]=0,s[12]=0,this._packChunk(ut.TYPE_IHDR,s)};Nn.prototype.packIDAT=function(t){return this._packChunk(ut.TYPE_IDAT,t)};Nn.prototype.packIEND=function(){return this._packChunk(ut.TYPE_IEND,null)}});var Cp=J((cC,Rp)=>{"use strict";var bx=require("util"),Ep=require("stream"),_x=qs(),xx=Ic(),Tp=Rp.exports=function(t){Ep.call(this);let e=t||{};this._packer=new xx(e),this._deflate=this._packer.createDeflate(),this.readable=!0};bx.inherits(Tp,Ep);Tp.prototype.pack=function(t,e,s,n){this.emit("data",Buffer.from(_x.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,s)),n&&this.emit("data",this._packer.packGAMA(n));let o=this._packer.filterData(t,e,s);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(r){this.emit("data",this._packer.packIDAT(r))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(o)}});var Lp=J((Co,Pp)=>{"use strict";var Ap=require("assert").ok,Fs=require("zlib"),kx=require("util"),Op=require("buffer").kMaxLength;function Xn(t){if(!(this instanceof Xn))return new Xn(t);t&&t.chunkSize<Fs.Z_MIN_CHUNK&&(t.chunkSize=Fs.Z_MIN_CHUNK),Fs.Inflate.call(this,t),this._offset=this._offset===void 0?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,t&&t.maxLength!=null&&(this._maxLength=t.maxLength)}function Sx(t){return new Xn(t)}function Np(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}Xn.prototype._processChunk=function(t,e,s){if(typeof s=="function")return Fs.Inflate._processChunk.call(this,t,e,s);let n=this,o=t&&t.length,r=this._chunkSize-this._offset,i=this._maxLength,a=0,c=[],l=0,u;this.on("error",function(h){u=h});function d(h,g){if(n._hadError)return;let w=r-g;if(Ap(w>=0,"have should not go down"),w>0){let x=n._buffer.slice(n._offset,n._offset+w);if(n._offset+=w,x.length>i&&(x=x.slice(0,i)),c.push(x),l+=x.length,i-=x.length,i===0)return!1}return(g===0||n._offset>=n._chunkSize)&&(r=n._chunkSize,n._offset=0,n._buffer=Buffer.allocUnsafe(n._chunkSize)),g===0?(a+=o-h,o=h,!0):!1}Ap(this._handle,"zlib binding closed");let f;do f=this._handle.writeSync(e,t,a,o,this._buffer,this._offset,r),f=f||this._writeState;while(!this._hadError&&d(f[0],f[1]));if(this._hadError)throw u;if(l>=Op)throw Np(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+Op.toString(16)+" bytes");let p=Buffer.concat(c,l);return Np(this),p};kx.inherits(Xn,Fs.Inflate);function vx(t,e){if(typeof e=="string"&&(e=Buffer.from(e)),!(e instanceof Buffer))throw new TypeError("Not a string or buffer");let s=t._finishFlushFlag;return s==null&&(s=Fs.Z_FINISH),t._processChunk(e,s)}function Mp(t,e){return vx(new Xn(e),t)}Pp.exports=Co=Mp;Co.Inflate=Xn;Co.createInflate=Sx;Co.inflateSync=Mp});var jc=J((lC,jp)=>{"use strict";var Ip=jp.exports=function(t){this._buffer=t,this._reads=[]};Ip.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};Ip.prototype.process=function(){for(;this._reads.length>0&&this._buffer.length;){let t=this._reads[0];if(this._buffer.length&&(this._buffer.length>=t.length||t.allowLess)){this._reads.shift();let e=this._buffer;this._buffer=e.slice(t.length),t.func.call(this,e.slice(0,t.length))}else break}if(this._reads.length>0)throw new Error("There are some read requests waitng on finished stream");if(this._buffer.length>0)throw new Error("unrecognised content at end of stream")}});var qp=J(Dp=>{"use strict";var Ex=jc(),Tx=Rc();Dp.process=function(t,e){let s=[],n=new Ex(t);return new Tx(e,{read:n.read.bind(n),write:function(r){s.push(r)},complete:function(){}}).start(),n.process(),Buffer.concat(s)}});var Wp=J((dC,Up)=>{"use strict";var Fp=!0,Bp=require("zlib"),Rx=Lp();Bp.deflateSync||(Fp=!1);var Cx=jc(),Ax=qp(),Ox=Nc(),Nx=Mc(),Mx=Pc();Up.exports=function(t,e){if(!Fp)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let s;function n(E){s=E}let o;function r(E){o=E}function i(E){o.transColor=E}function a(E){o.palette=E}function c(){o.alpha=!0}let l;function u(E){l=E}let d=[];function f(E){d.push(E)}let p=new Cx(t);if(new Ox(e,{read:p.read.bind(p),error:n,metadata:r,gamma:u,palette:a,transColor:i,inflateData:f,simpleTransparency:c}).start(),p.process(),s)throw s;let g=Buffer.concat(d);d.length=0;let w;if(o.interlace)w=Bp.inflateSync(g);else{let v=((o.width*o.bpp*o.depth+7>>3)+1)*o.height;w=Rx(g,{chunkSize:v,maxLength:v})}if(g=null,!w||!w.length)throw new Error("bad png - invalid inflate data response");let x=Ax.process(w,o);g=null;let O=Nx.dataToBitMap(x,o);x=null;let I=Mx(O,o,e.skipRescale);return o.data=I,o.gamma=l||0,o}});var zp=J((fC,Gp)=>{"use strict";var Hp=!0,Yp=require("zlib");Yp.deflateSync||(Hp=!1);var Px=qs(),Lx=Ic();Gp.exports=function(t,e){if(!Hp)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let s=e||{},n=new Lx(s),o=[];o.push(Buffer.from(Px.PNG_SIGNATURE)),o.push(n.packIHDR(t.width,t.height)),t.gamma&&o.push(n.packGAMA(t.gamma));let r=n.filterData(t.data,t.width,t.height),i=Yp.deflateSync(r,n.getDeflateOptions());if(r=null,!i||!i.length)throw new Error("bad png - invalid compressed data response");return o.push(n.packIDAT(i)),o.push(n.packIEND()),Buffer.concat(o)}});var Kp=J(Dc=>{"use strict";var Ix=Wp(),jx=zp();Dc.read=function(t,e){return Ix(t,e||{})};Dc.write=function(t,e){return jx(t,e)}});var Jp=J(Vp=>{"use strict";var Dx=require("util"),Xp=require("stream"),qx=$p(),Fx=Cp(),Bx=Kp(),ht=Vp.PNG=function(t){Xp.call(this),t=t||{},this.width=t.width|0,this.height=t.height|0,this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null,t.fill&&this.data&&this.data.fill(0),this.gamma=0,this.readable=this.writable=!0,this._parser=new qx(t),this._parser.on("error",this.emit.bind(this,"error")),this._parser.on("close",this._handleClose.bind(this)),this._parser.on("metadata",this._metadata.bind(this)),this._parser.on("gamma",this._gamma.bind(this)),this._parser.on("parsed",function(e){this.data=e,this.emit("parsed",e)}.bind(this)),this._packer=new Fx(t),this._packer.on("data",this.emit.bind(this,"data")),this._packer.on("end",this.emit.bind(this,"end")),this._parser.on("close",this._handleClose.bind(this)),this._packer.on("error",this.emit.bind(this,"error"))};Dx.inherits(ht,Xp);ht.sync=Bx;ht.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)};ht.prototype.parse=function(t,e){if(e){let s,n;s=function(o){this.removeListener("error",n),this.data=o,e(null,this)}.bind(this),n=function(o){this.removeListener("parsed",s),e(o,null)}.bind(this),this.once("parsed",s),this.once("error",n)}return this.end(t),this};ht.prototype.write=function(t){return this._parser.write(t),!0};ht.prototype.end=function(t){this._parser.end(t)};ht.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};ht.prototype._gamma=function(t){this.gamma=t};ht.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};ht.bitblt=function(t,e,s,n,o,r,i,a){if(s|=0,n|=0,o|=0,r|=0,i|=0,a|=0,s>t.width||n>t.height||s+o>t.width||n+r>t.height)throw new Error("bitblt reading outside image");if(i>e.width||a>e.height||i+o>e.width||a+r>e.height)throw new Error("bitblt writing outside image");for(let c=0;c<r;c++)t.data.copy(e.data,(a+c)*e.width+i<<2,(n+c)*t.width+s<<2,(n+c)*t.width+s+o<<2)};ht.prototype.bitblt=function(t,e,s,n,o,r,i){return ht.bitblt(this,t,e,s,n,o,r,i),this};ht.adjustGamma=function(t){if(t.gamma){for(let e=0;e<t.height;e++)for(let s=0;s<t.width;s++){let n=t.width*e+s<<2;for(let o=0;o<3;o++){let r=t.data[n+o]/255;r=Math.pow(r,1/2.2/t.gamma),t.data[n+o]=Math.round(r*255)}}t.gamma=0}};ht.prototype.adjustGamma=function(){ht.adjustGamma(this)}});var nh={};N0(nh,{default:()=>eh});function eh(t,e,s,n,o,r={}){let{threshold:i=.1,alpha:a=.1,aaColor:c=[255,255,0],diffColor:l=[255,0,0],includeAA:u,diffColorAlt:d,diffMask:f}=r;if(!qc(t)||!qc(e)||s&&!qc(s))throw new Error("Image data: Uint8Array, Uint8ClampedArray or Buffer expected.");if(t.length!==e.length||s&&s.length!==t.length)throw new Error("Image sizes do not match.");if(t.length!==n*o*4)throw new Error("Image data size does not match width/height.");let p=n*o,h=new Uint32Array(t.buffer,t.byteOffset,p),g=new Uint32Array(e.buffer,e.byteOffset,p),w=!0;for(let S=0;S<p;S++)if(h[S]!==g[S]){w=!1;break}if(w){if(s&&!f)for(let S=0;S<p;S++)Qp(t,4*S,a,s);return 0}let x=35215*i*i,[O,I,E]=c,[v,A,te]=l,[oe,de,ce]=d||l,ne=0;for(let S=0;S<o;S++)for(let Te=0;Te<n;Te++){let W=S*n+Te,K=W*4,ge=h[W]===g[W]?0:th(t,e,K,K,!1);if(Math.abs(ge)>x){let Ae=Zp(t,Te,S,n,o,h,g)||Zp(e,Te,S,n,o,g,h);!u&&Ae?s&&!f&&hi(s,K,O,I,E):(s&&(ge<0?hi(s,K,oe,de,ce):hi(s,K,v,A,te)),ne++)}else s&&!f&&Qp(t,K,a,s)}return ne}function qc(t){return ArrayBuffer.isView(t)&&t.BYTES_PER_ELEMENT===1}function Zp(t,e,s,n,o,r,i){let a=Math.max(e-1,0),c=Math.max(s-1,0),l=Math.min(e+1,n-1),u=Math.min(s+1,o-1),d=s*n+e,f=e===a||e===l||s===c||s===u?1:0,p=0,h=0,g=0,w=0,x=0,O=0;for(let I=a;I<=l;I++)for(let E=c;E<=u;E++){if(I===e&&E===s)continue;let v=th(t,t,d*4,(E*n+I)*4,!0);if(v===0){if(f++,f>2)return!1}else v<p?(p=v,g=I,w=E):v>h&&(h=v,x=I,O=E)}return p===0||h===0?!1:pi(r,g,w,n,o)&&pi(i,g,w,n,o)||pi(r,x,O,n,o)&&pi(i,x,O,n,o)}function pi(t,e,s,n,o){let r=Math.max(e-1,0),i=Math.max(s-1,0),a=Math.min(e+1,n-1),c=Math.min(s+1,o-1),l=t[s*n+e],u=e===r||e===a||s===i||s===c?1:0;for(let d=r;d<=a;d++)for(let f=i;f<=c;f++)if(!(d===e&&f===s)&&(u+=+(l===t[f*n+d]),u>2))return!0;return!1}function th(t,e,s,n,o){let r=t[s],i=t[s+1],a=t[s+2],c=t[s+3],l=e[n],u=e[n+1],d=e[n+2],f=e[n+3],p=r-l,h=i-u,g=a-d,w=c-f;if(!p&&!h&&!g&&!w)return 0;if(c<255||f<255){let v=48+159*(s%2),A=48+159*((s/1.618033988749895|0)%2),te=48+159*((s/2.618033988749895|0)%2);p=(r*c-l*f-v*w)/255,h=(i*c-u*f-A*w)/255,g=(a*c-d*f-te*w)/255}let x=p*.29889531+h*.58662247+g*.11448223;if(o)return x;let O=p*.59597799-h*.2741761-g*.32180189,I=p*.21147017-h*.52261711+g*.31114694,E=.5053*x*x+.299*O*O+.1957*I*I;return x>0?-E:E}function hi(t,e,s,n,o){t[e+0]=s,t[e+1]=n,t[e+2]=o,t[e+3]=255}function Qp(t,e,s,n){let o=255+(t[e]*.29889531+t[e+1]*.58662247+t[e+2]*.11448223-255)*s*t[e+3]/255;hi(n,e,o,o,o)}var sh=O0(()=>{});var Vn=J((mC,ch)=>{var $n=require("fs"),Ux=require("path"),Wx=require("os"),Hx="nex-visual-";function rh(t){return Ux.join(Wx.tmpdir(),`${Hx}${Date.now()}-${t}`)}var Fc=null;function mi(){return Fc||(Fc=Jp().PNG),Fc}var Bc=null;function Yx(){if(!Bc){let t=(sh(),P0(nh));Bc=t.default||t}return Bc}function Hc(t,e,{threshold:s=.1}={}){let n=mi(),o=Yx(),r=n.sync.read($n.readFileSync(t)),i=n.sync.read($n.readFileSync(e)),a=Math.max(r.width,i.width),c=Math.max(r.height,i.height),l=oh(r,a,c),u=oh(i,a,c),d=new n({width:a,height:c}),f=o(l,u,d.data,a,c,{threshold:s,includeAA:!1}),p=a*c,h=(f/p*100).toFixed(1),g=Gx(d.data,a,c,3,3),w=rh("diff.png");return $n.writeFileSync(w,n.sync.write(d),{mode:384}),{diffPath:w,diffPercent:parseFloat(h),totalPixels:p,changedPixels:f,regionSummary:g,beforePath:t,afterPath:e,width:a,height:c}}function oh(t,e,s){if(t.width===e&&t.height===s)return t.data;let n=Buffer.alloc(e*s*4,0);for(let o=0;o<t.height;o++){let r=o*t.width*4,i=o*e*4;t.data.copy(n,i,r,r+t.width*4)}return n}function Gx(t,e,s,n,o){let r=[["top-left","top-center","top-right"],["middle-left","center","middle-right"],["bottom-left","bottom-center","bottom-right"]],i=Math.ceil(e/n),a=Math.ceil(s/o),c=[];for(let l=0;l<o;l++)for(let u=0;u<n;u++){let d=0,f=0,p=u*i,h=l*a,g=Math.min(p+i,e),w=Math.min(h+a,s);for(let x=h;x<w;x++)for(let O=p;O<g;O++){f++;let I=(x*e+O)*4;(t[I]>0||t[I+1]>0)&&d++}if(d>0){let x=(d/f*100).toFixed(1),O=r[l]&&r[l][u]?r[l][u]:`row${l}-col${u}`;c.push({name:O,changedPercent:parseFloat(x),changed:d,total:f})}}return c.sort((l,u)=>u.changedPercent-l.changedPercent),c}var ih=[{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 zx(t,{viewports:e=ih,height:s=800,fullPage:n=!1,timeout:o=3e4}={}){let{browserScreenshot:r}=wn(),i=[];for(let a of e){let c=await r(t,{width:a.width,height:s,fullPage:n,timeout:o});i.push({label:a.label,width:a.width,path:c.path,base64:c.base64,media_type:c.media_type})}return i}function ah(t,e=[]){let s=mi(),n=s.sync.read($n.readFileSync(t));for(let i of e){let a=Kx(i.color||"#FF0000");i.type==="box"?(Xx(n,i.x||0,i.y||0,i.width||50,i.height||50,a,i.thickness||3),i.label&&Wc(n,i.x||0,(i.y||0)-14,i.label,a)):i.type==="arrow"?(Vx(n,i.x||0,i.y||0,i.toX||i.x+50,i.toY||i.y,a,i.thickness||3),i.label&&Wc(n,i.x||0,(i.y||0)-14,i.label,a)):i.type==="circle"&&(Jx(n,i.x||0,i.y||0,i.radius||20,a,i.thickness||3),i.label&&Wc(n,(i.x||0)-(i.radius||20),(i.y||0)-(i.radius||20)-14,i.label,a))}let o=rh("annotated.png");$n.writeFileSync(o,s.sync.write(n),{mode:384});let r=$n.readFileSync(o).toString("base64");return{path:o,base64:r,media_type:"image/png"}}function Kx(t){let e=t.replace("#","");return{r:parseInt(e.substring(0,2),16),g:parseInt(e.substring(2,4),16),b:parseInt(e.substring(4,6),16),a:255}}function on(t,e,s,n){if(e<0||s<0||e>=t.width||s>=t.height)return;let o=(s*t.width+e)*4;t.data[o]=n.r,t.data[o+1]=n.g,t.data[o+2]=n.b,t.data[o+3]=n.a}function Xx(t,e,s,n,o,r,i=3){for(let a=0;a<i;a++){for(let c=0;c<n;c++)on(t,e+c,s+a,r),on(t,e+c,s+o-1-a,r);for(let c=0;c<o;c++)on(t,e+a,s+c,r),on(t,e+n-1-a,s+c,r)}}function Uc(t,e,s,n,o,r,i=3){let a=Math.abs(n-e),c=Math.abs(o-s),l=e<n?1:-1,u=s<o?1:-1,d=a-c,f=e,p=s;for(;;){let h=Math.floor(i/2);for(let w=-h;w<=h;w++)for(let x=-h;x<=h;x++)on(t,f+w,p+x,r);if(f===n&&p===o)break;let g=2*d;g>-c&&(d-=c,f+=l),g<a&&(d+=a,p+=u)}}function Vx(t,e,s,n,o,r,i=3){Uc(t,e,s,n,o,r,i);let a=Math.atan2(o-s,n-e),c=15,l=a+Math.PI*.8,u=a-Math.PI*.8;Uc(t,n,o,Math.round(n+c*Math.cos(l)),Math.round(o+c*Math.sin(l)),r,i),Uc(t,n,o,Math.round(n+c*Math.cos(u)),Math.round(o+c*Math.sin(u)),r,i)}function Jx(t,e,s,n,o,r=3){for(let i=0;i<r;i++){let a=n-i;for(let c=0;c<360;c+=.5){let l=c*Math.PI/180,u=Math.round(e+a*Math.cos(l)),d=Math.round(s+a*Math.sin(l));on(t,u,d,o)}}}function Wc(t,e,s,n,o){let i=n.length*6+4,a=12;for(let c=0;c<a;c++)for(let l=0;l<i;l++)on(t,e+l,s+c,{r:0,g:0,b:0,a:200});for(let c=0;c<i;c++)on(t,e+c,s+a-1,o),on(t,e+c,s+a-2,o);for(let c=0;c<n.length;c++){let l=e+2+c*6;for(let u=2;u<9;u++)for(let d=0;d<4;d++)on(t,l+d,s+u,o)}}async function*Zx(t,e,{maxIterations:s=20,hmrDelay:n=1500,width:o=1280,height:r=800,timeout:i=3e4}={}){let{browserScreenshot:a}=wn(),c=Qx("chokidar"),l=await a(t,{width:o,height:r,timeout:i});if(yield{iteration:0,type:"baseline",path:l.path,base64:l.base64,media_type:l.media_type},!c){yield{iteration:-1,type:"error",message:"chokidar not installed \u2014 watch mode requires it. Install with: npm install chokidar"};return}let u=0,d=!1,f=c.watch(e,{ignoreInitial:!0,ignored:/(node_modules|\.git|dist)/});f.on("change",()=>{d=!0});try{for(;u<s;){await tk(()=>d,3e5),d=!1,u++,await ek(n);let p=await a(t,{width:o,height:r,timeout:i}),h=null;try{h=Hc(l.path,p.path)}catch{}l=p,yield{iteration:u,type:"change",path:p.path,base64:p.base64,media_type:p.media_type,diff:h?{diffPath:h.diffPath,diffPercent:h.diffPercent,changedPixels:h.changedPixels,regions:h.regionSummary}:null}}}finally{await f.close()}}function Qx(t){try{return require(t)}catch{return null}}function ek(t){return new Promise(e=>setTimeout(e,t))}function tk(t,e=6e4){return new Promise((s,n)=>{let o=setInterval(()=>{t()&&(clearInterval(o),clearTimeout(r),s())},200),r=setTimeout(()=>{clearInterval(o),n(new Error("Watch timeout \u2014 no file changes detected"))},e)})}function nk(t,{sampleRate:e=4}={}){let n=mi().sync.read($n.readFileSync(t)),o=new Map;for(let l=0;l<n.height;l+=e)for(let u=0;u<n.width;u+=e){let d=(l*n.width+u)*4,f=n.data[d],p=n.data[d+1],h=n.data[d+2];if(n.data[d+3]<128)continue;let w=Math.round(f/8)*8,x=Math.round(p/8)*8,O=Math.round(h/8)*8,I=`${w},${x},${O}`;o.set(I,(o.get(I)||0)+1)}let r=[...o.entries()].sort((l,u)=>u[1]-l[1]).slice(0,20),i=r.reduce((l,u)=>l+u[1],0),a=r.map(([l,u])=>{let[d,f,p]=l.split(",").map(Number);return{hex:sk(d,f,p),rgb:`rgb(${d}, ${f}, ${p})`,frequency:parseFloat((u/i*100).toFixed(1)),category:ok(d,f,p)}}),c=rk(n);return{colors:a,spacing:c,dimensions:{width:n.width,height:n.height},imagePath:t}}function sk(t,e,s){return"#"+[t,e,s].map(n=>Math.min(255,n).toString(16).padStart(2,"0")).join("")}function ok(t,e,s){let n=(t*299+e*587+s*114)/1e3;return n>240?"white/background":n<30?"black/text":n<80?"dark":t>200&&e<100&&s<100?"red/danger":t<100&&e>150&&s<100?"green/success":t<100&&e<100&&s>200?"blue/primary":t>200&&e>200&&s<100?"yellow/warning":t>200&&e>100&&s<50?"orange/accent":n>200?"light/subtle":"midtone"}function rk(t){let e=[],s=!1,n=0,o=ik(t);for(let i=0;i<t.height;i++){let a=!0;for(let c=0;c<t.width;c+=4){let l=(i*t.width+c)*4;if(Math.abs(t.data[l]-o.r)>20||Math.abs(t.data[l+1]-o.g)>20||Math.abs(t.data[l+2]-o.b)>20){a=!1;break}}if(a&&s)s=!1,n=i;else if(!a&&!s&&(s=!0,n>0)){let c=i-n;c>=4&&c<=200&&e.push(c)}}let r=new Map;for(let i of e){let a=Math.round(i/4)*4;r.set(a,(r.get(a)||0)+1)}return[...r.entries()].sort((i,a)=>a[1]-i[1]).slice(0,8).map(([i,a])=>({px:i,occurrences:a}))}function ik(t){let e=[[0,0],[t.width-1,0],[0,t.height-1],[t.width-1,t.height-1]],s=0,n=0,o=0;for(let[r,i]of e){let a=(i*t.width+r)*4;s+=t.data[a],n+=t.data[a+1],o+=t.data[a+2]}return{r:Math.round(s/4),g:Math.round(n/4),b:Math.round(o/4)}}async function ak(t,e,{width:s,height:n=800,fullPage:o=!1,threshold:r=.1,timeout:i=3e4}={}){let{browserScreenshot:a}=wn(),l=mi().sync.read($n.readFileSync(e)),u=s||l.width,d=n||l.height,f=await a(t,{width:u,height:d,fullPage:o,timeout:i}),p=Hc(e,f.path,{threshold:r}),h=ah(f.path,p.regionSummary.filter(g=>g.changedPercent>1).map((g,w)=>{let I=Math.ceil(p.width/3),E=Math.ceil(p.height/3),v=[["top-left","top-center","top-right"],["middle-left","center","middle-right"],["bottom-left","bottom-center","bottom-right"]],A=0,te=0;for(let oe=0;oe<3;oe++)for(let de=0;de<3;de++)v[oe][de]===g.name&&(A=de,te=oe);return{type:"box",x:A*I+2,y:te*E+2,width:I-4,height:E-4,label:`${g.name}: ${g.changedPercent}%`,color:g.changedPercent>10?"#FF0000":"#FFAA00"}}));return{livePath:f.path,referencePath:e,diffPath:p.diffPath,annotatedPath:h.path,diffPercent:p.diffPercent,changedPixels:p.changedPixels,totalPixels:p.totalPixels,regions:p.regionSummary,liveBase64:f.base64,diffBase64:$n.readFileSync(p.diffPath).toString("base64"),annotatedBase64:h.base64}}ch.exports={pixelDiff:Hc,responsiveSweep:zx,annotateImage:ah,visualWatch:Zx,extractDesignTokens:nk,designCompare:ak,DEFAULT_VIEWPORTS:ih}});var Yc=J((gC,lh)=>{var{C:Ie}=Je(),Oo="",mt=[],Ao=0,Jn=null;function ck(t){Jn=t}function lk(t,e){Oo=t,mt=[],Ao=0;for(let n of e){Ao++;let o=`t${Ao}`;mt.push({id:o,description:n.description||n.title||n.name||n.task||`Task ${Ao}`,status:"pending",dependsOn:n.depends_on||[],result:null})}let s=mt.map(n=>({...n}));return Jn&&Jn("create",{name:t,tasks:s}),s}function uk(t,e,s){let n=mt.find(o=>o.id===t);return n?(n.status=e,s!==void 0&&(n.result=s),Jn&&Jn("update",{id:t,status:e,result:s}),{...n}):null}function dk(){return{name:Oo,tasks:mt.map(t=>({...t}))}}function fk(){Oo="",mt=[],Ao=0,Jn&&Jn("clear",{})}function pk(){return mt.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let s=mt.find(n=>n.id===e);return s&&s.status==="done"}))}function hk(){if(mt.length===0)return`${Ie.dim}No active tasks${Ie.reset}`;let t=[];Oo&&(t.push(` ${Ie.bold}${Ie.cyan}Tasks: ${Oo}${Ie.reset}`),t.push(` ${Ie.dim}${"\u2500".repeat(40)}${Ie.reset}`));for(let o of mt){let r,i;switch(o.status){case"done":r="\u2713",i=Ie.green;break;case"in_progress":r="\u2192",i=Ie.cyan;break;case"failed":r="\u2717",i=Ie.red;break;default:r="\xB7",i=Ie.dim}let a=o.dependsOn.length>0?` ${Ie.dim}(after: ${o.dependsOn.join(", ")})${Ie.reset}`:"",c=`[${o.status}]`,l=o.description.length>50?o.description.substring(0,47)+"...":o.description;if(t.push(` ${i}${r}${Ie.reset} ${Ie.bold}${o.id}${Ie.reset} ${l.padEnd(40)} ${i}${c}${Ie.reset}${a}`),o.result&&o.status==="done"){let u=o.result.length>60?o.result.substring(0,57)+"...":o.result;t.push(` ${Ie.dim}\u2192 ${u}${Ie.reset}`)}}let e=mt.filter(o=>o.status==="done").length,s=mt.filter(o=>o.status==="failed").length,n=mt.length;return t.push(` ${Ie.dim}${"\u2500".repeat(40)}${Ie.reset}`),t.push(` ${Ie.dim}${e}/${n} done${s>0?`, ${s} failed`:""}${Ie.reset}`),t.join(`
|
|
133
|
+
`)}function mk(){return mt.length>0&&mt.some(t=>t.status==="pending"||t.status==="in_progress")}lh.exports={createTasks:lk,updateTask:uk,getTaskList:dk,clearTasks:fk,getReadyTasks:pk,renderTaskList:hk,setOnChange:ck,hasActiveTasks:mk}});var gi=J((yC,dh)=>{var No={"devstral-2":{staleWarn:3e4,staleAbort:9e4,investigationCap:18,postEditCap:10,briefing:`You are devstral-2, a strong coding model optimized for agentic tasks.
|
|
134
134
|
Use tools confidently and without hesitation \u2014 tool use is the expected workflow.
|
|
135
135
|
You excel at sysadmin, frontend, and multi-step coding tasks.
|
|
136
136
|
Prefer action over narration \u2014 read, fix, verify, done.`},"devstral-small":{staleWarn:2e4,staleAbort:6e4,investigationCap:10,postEditCap:8,briefing:`You are devstral-small, a fast and lightweight coding model.
|
|
@@ -143,7 +143,7 @@ Focus on correctness over speed.`},"ministral-3":{staleWarn:2e4,staleAbort:6e4,i
|
|
|
143
143
|
Prioritize decisive, targeted edits. Read only what you need, then fix.
|
|
144
144
|
Stay on-scope \u2014 your strength is focused, efficient coding tasks.`},"qwen3-vl":{staleWarn:6e4,staleAbort:18e4,investigationCap:15,postEditCap:12,briefing:`You are qwen3-vl, the highest-ranked model for data, frontend, and agentic tasks.
|
|
145
145
|
Trust your reasoning. Use tools thoroughly when the task demands it.
|
|
146
|
-
You handle complex multi-step tasks well \u2014 don't cut corners prematurely.`}},
|
|
146
|
+
You handle complex multi-step tasks well \u2014 don't cut corners prematurely.`}},uh={staleWarn:6e4,staleAbort:12e4,investigationCap:18,postEditCap:10};function gk(t){let e=(t||"").toLowerCase(),s=null,n=0;for(let r of Object.keys(No))e.startsWith(r)&&r.length>n&&(s=r,n=r.length);let o=s?{...No[s]}:{...uh};for(let[r,i]of[["NEX_STALE_WARN_MS","staleWarn"],["NEX_STALE_ABORT_MS","staleAbort"]])if(process.env[r]){let a=parseInt(process.env[r],10);Number.isInteger(a)&&a>=1e3&&a<=3e5&&(o[i]=a)}return o}function yk(t){let e=(t||"").toLowerCase(),s=null,n=0;for(let o of Object.keys(No))e.startsWith(o)&&o.length>n&&(s=o,n=o.length);return s&&No[s].briefing||""}dh.exports={getModelProfile:gk,getModelBriefing:yk,PROFILES:No,DEFAULTS:uh}});var zc=J((wC,yh)=>{var{callChat:wk}=st(),{estimateTokens:Gc}=rn(),fh=process.env.NEX_COMPACTION!=="false",ph=6,hh=2e3,mh=3,$k=`Your task is to create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions.
|
|
147
147
|
This summary should be thorough in capturing technical details, code patterns, and architectural decisions that would be essential for continuing development work without losing context.
|
|
148
148
|
|
|
149
149
|
Before providing your final summary, wrap your analysis in <analysis> tags to organize your thoughts and ensure you've covered all necessary points. In your analysis process:
|
|
@@ -175,30 +175,30 @@ Format your output as:
|
|
|
175
175
|
|
|
176
176
|
<summary>
|
|
177
177
|
[Sections 1-9 above]
|
|
178
|
-
</summary>`,
|
|
179
|
-
${n}`,_compacted:!0,_originalCount:t.length},tokensRemoved:r-i})}catch{return
|
|
178
|
+
</summary>`,Zn=0;async function bk(t){if(!fh||t.length<ph||Zn>=mh)return null;let e=[{role:"system",content:$k},{role:"user",content:gh(t)}];try{let n=((await wk(e,[],{temperature:0,maxTokens:hh})).content||"").trim();if(!n)return Zn++,null;let o=n.match(/<summary>([\s\S]*?)<\/summary>/);if(o?n=o[1].trim():n=n.replace(/<analysis>[\s\S]*?<\/analysis>/g,"").trim(),!n)return Zn++,null;let r=t.reduce((a,c)=>a+Gc(c.content||"")+(c.tool_calls?Gc(JSON.stringify(c.tool_calls)):0),0),i=Gc(n);return i>=r*.8?(Zn++,null):(Zn=0,{message:{role:"system",content:`[Conversation Summary \u2014 ${t.length} messages compacted]
|
|
179
|
+
${n}`,_compacted:!0,_originalCount:t.length},tokensRemoved:r-i})}catch{return Zn++,null}}function _k(){Zn=0}function gh(t){return t.map(e=>{let s=e.role==="tool"?"tool_result":e.role,n=(e.content||"").substring(0,500);if(e.tool_calls){let o=e.tool_calls.map(r=>r.function?.name).join(", ");return`[${s}] ${n}
|
|
180
180
|
tools: ${o}`}return`[${s}] ${n}`}).join(`
|
|
181
181
|
|
|
182
|
-
`)}
|
|
183
|
-
`);if(o.length<=10){let
|
|
182
|
+
`)}yh.exports={compactMessages:bk,formatMessagesForSummary:gh,resetCompactionFailures:_k,COMPACTION_ENABLED:fh,COMPACTION_MIN_MESSAGES:ph,COMPACTION_SUMMARY_BUDGET:hh,MAX_CONSECUTIVE_FAILURES:mh}});var rn=J(($C,Th)=>{var xk=require("path");function $h(){return st().getActiveModel()}var kk={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},Sk={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},Qn=new Map,wh=1e3,Kc=new WeakMap,es=null;function vk(){if(es!==null)return es;try{let t=$h(),e=t?.provider||"ollama",s=(t?.id||"").toLowerCase();for(let[n,o]of Object.entries(Sk))if(s.startsWith(n))return es=o,es;return es=kk[e]||4,es}catch{return 4}}function Ek(){es=null}function ts(t){if(!t)return 0;typeof t!="string"&&(t=JSON.stringify(t));let e=t.length<=120?t:`${t.length}:${t.substring(0,60)}:${t.substring(t.length>>1,(t.length>>1)+30)}:${t.substring(t.length-30)}`,s=Qn.get(e);if(s!==void 0)return Qn.delete(e),Qn.set(e,s),s;let n=Math.ceil(t.length/vk());if(Qn.size>=wh){let o=wh>>1,r=Qn.keys();for(let i=0;i<o;i++)Qn.delete(r.next().value)}return Qn.set(e,n),n}function Tk(t){if(Kc.has(t))return Kc.get(t);let e=JSON.stringify(t);return Kc.set(t,e),e}function ns(t){let s=4;if(t.content&&(s+=ts(t.content)),t.tool_calls)for(let n of t.tool_calls){s+=4,s+=ts(n.function?.name||"");let o=n.function?.arguments;typeof o=="string"?s+=ts(o):o&&(s+=ts(JSON.stringify(o)))}return s}function zt(t){let e=0;for(let s of t)e+=ns(s);return e}function Rk(t,e){if(t&&t.length===e.length){let r=!1;for(let i=0;i<e.length;i++)if(t[i]!==e[i]){r=!0;break}if(!r)return 0}let s=t?t.length:0,n=e.length,o=0;for(let r=s;r<n;r++)o+=ns(e[r]);return o}var Xc=new WeakMap;function yi(t){if(!t||t.length===0)return 0;if(Xc.has(t))return Xc.get(t);let e=ts(JSON.stringify(t));return Xc.set(t,e),e}function wi(){return $h()?.contextWindow||32768}var gt={msgCount:-1,lastMsgRef:null,toolCount:-1,result:null,messagesRef:null,messageTokens:0,systemTokens:0,conversationTokens:0,toolResultTokens:0};function Ck(t,e){let s=t.length>0?t[t.length-1]:null,n=e?e.length:0;if(gt.result&&t.length===gt.msgCount&&s===gt.lastMsgRef&&n===gt.toolCount)return gt.result;let o,r,i,a;if(gt.messagesRef===t&&t.length>gt.msgCount&>.msgCount>=0){o=gt.messageTokens,r=gt.systemTokens,i=gt.conversationTokens,a=gt.toolResultTokens;for(let p=gt.msgCount;p<t.length;p++){let h=ns(t[p]);o+=h,t[p].role==="system"?r+=h:t[p].role==="tool"?a+=h:i+=h}}else{o=0,r=0,i=0,a=0;for(let p of t){let h=ns(p);o+=h,p.role==="system"?r+=h:p.role==="tool"?a+=h:i+=h}}let c=yi(e),l=o+c,u=wi(),d=u>0?l/u*100:0,f={used:l,limit:u,percentage:Math.round(d*10)/10,breakdown:{system:r,conversation:i,toolResults:a,toolDefinitions:c},messageCount:t.length};return gt={msgCount:t.length,lastMsgRef:s,toolCount:n,result:f,messagesRef:t,messageTokens:o,systemTokens:r,conversationTokens:i,toolResultTokens:a},f}var Mo=parseFloat(process.env.NEX_COMPRESSION_THRESHOLD)||.75,bh=parseFloat(process.env.NEX_SAFETY_MARGIN)||.1,_h=parseInt(process.env.NEX_KEEP_RECENT,10)||10,xh={essential:.6,standard:.65,full:Math.min(Mo,.75)};function kh(){if(process.env.NEX_COMPRESSION_THRESHOLD)return Mo;try{let{getActiveTier:t}=To(),e=t();return xh[e]??Mo}catch{return Mo}}var Ak=200,Ok=1e3;function Sh(t,e){if(!t||t.length<=e)return t;let n=/^(ERROR|EXIT|BLOCKED|CANCELLED)/i.test(t)?e*3:e;if(t.length<=n)return t;let o=t.split(`
|
|
183
|
+
`);if(o.length<=10){let h=Math.floor(n*.6),g=Math.floor(n*.4),w=t.substring(0,h),x=t.substring(t.length-g);return w+`
|
|
184
184
|
...(${t.length} chars total)...
|
|
185
|
-
`+
|
|
185
|
+
`+x}let r=Math.floor(o.length*.4),i=Math.floor(o.length*.4),a=[],c=0,l=Math.floor(n*.4);for(let h=0;h<r&&c<l;h++)if(c+o[h].length+1>l&&o[h].trim().startsWith("```")){a.push(o[h]),c+=o[h].length+1;let g=h+1;for(;g<o.length&&c<l*1.5&&!o[g].trim().startsWith("```");)a.push(o[g]),c+=o[g].length+1,g++;g<o.length&&o[g].trim().startsWith("```")&&(a.push(o[g]),c+=o[g].length+1),h=g}else a.push(o[h]),c+=o[h].length+1;let u=[],d=0,f=Math.floor(n*.4);for(let h=o.length-1;h>=o.length-i&&d<f;h--)if(d+o[h].length+1>f&&o[h].trim().startsWith("```")){u.push(o[h]),d+=o[h].length+1;let g=h-1;for(;g>=0&&d<f*1.5&&!o[g].trim().startsWith("```");)u.push(o[g]),d+=o[g].length+1,g--;g>=0&&o[g].trim().startsWith("```")&&(u.push(o[g]),d+=o[g].length+1),h=g}else u.push(o[h]),d+=o[h].length+1;u.reverse();let p=o.length-a.length-u.length;return a.join(`
|
|
186
186
|
`)+`
|
|
187
187
|
...(${p} lines omitted, ${o.length} total)...
|
|
188
188
|
`+u.join(`
|
|
189
|
-
`)}function
|
|
190
|
-
...(truncated)`),o.tool_calls&&e==="aggressive"&&(o.tool_calls=o.tool_calls.map(r=>({...r,function:{name:r.function.name,arguments:typeof r.function.arguments=="string"?r.function.arguments.substring(0,50):r.function.arguments}}))),o}return t}function
|
|
189
|
+
`)}function Us(t,e="light"){let s=e==="aggressive"?100:e==="medium"?200:Ok,n=e==="aggressive"?50:e==="medium"?100:Ak;if(t.role==="tool"){let o=typeof t.content=="string"?t.content:JSON.stringify(t.content);return o.length>n?{...t,content:Sh(o,n)}:t}if(t.role==="assistant"){let o={...t};return o.content&&o.content.length>s&&(o.content=o.content.substring(0,s)+`
|
|
190
|
+
...(truncated)`),o.tool_calls&&e==="aggressive"&&(o.tool_calls=o.tool_calls.map(r=>({...r,function:{name:r.function.name,arguments:typeof r.function.arguments=="string"?r.function.arguments.substring(0,50):r.function.arguments}}))),o}return t}function vh(t,e,s,n){let o=0;if(t.role==="system")return 100;if(t.role==="user")o+=35;else if(t.role==="tool"){let i=typeof t.content=="string"?t.content:JSON.stringify(t.content||"");/^(ERROR|BLOCKED|CANCELLED)/i.test(i)?o+=30:o+=15}else t.role==="assistant"&&(o+=t.tool_calls?20:10);let r=s>1?e/(s-1):1;if(o+=Math.round(r*30),n&&n.size>0){let i=typeof t.content=="string"?t.content:JSON.stringify(t.content||""),a=0;for(let c of n)(i.includes(c)||i.includes(xk.basename(c)))&&a++;o+=Math.min(30,a*10)}return Math.min(100,o)}function Eh(t,e=10){let s=new Set,n=t.slice(-e),o=/(?:\/[\w.-]+)+\.\w+/g;for(let r of n){let a=(typeof r.content=="string"?r.content:JSON.stringify(r.content||"")).match(o);a&&a.forEach(c=>s.add(c))}return s}function Nk(t,{filesModified:e=new Set,currentPhase:s=null}={}){let n=[];if(e.size>0){let r=[...e].map(i=>i.split("/").slice(-2).join("/")).join(", ");n.push(`Files already modified: ${r} \u2014 do NOT rewrite these, use edit_file for additions only.`)}s&&n.push(`Current phase: ${s}`);let o=t.filter(r=>r.role==="assistant"&&typeof r.content=="string"&&r.content.trim().length>30).slice(-3).map(r=>r.content.trim().slice(0,200).replace(/\n+/g," "));return o.length>0&&n.push(`Recent progress:
|
|
191
191
|
`+o.map(r=>`- ${r}`).join(`
|
|
192
192
|
`)),n.length===0?null:{role:"system",content:`## Progress State (preserved through compression)
|
|
193
193
|
${n.join(`
|
|
194
|
-
`)}`,_pinned:!0,_progressSnapshot:!0}}var
|
|
195
|
-
`),r=Math.floor(n*.6),i=Math.floor(n*.4),a="",
|
|
196
|
-
`:"")+p,
|
|
197
|
-
`:"")+
|
|
194
|
+
`)}`,_pinned:!0,_progressSnapshot:!0}}var Bs={msgCount:-1,lastMsgRef:null,result:null};function Mk(){Bs={msgCount:-1,lastMsgRef:null,result:null},gt={msgCount:-1,lastMsgRef:null,toolCount:-1,result:null,messagesRef:null,messageTokens:0,systemTokens:0,conversationTokens:0,toolResultTokens:0}}async function Pk(t,e,s={}){let n=t.length>0?t[t.length-1]:null;if(!s.force&&Bs.result&&t.length===Bs.msgCount&&n===Bs.lastMsgRef)return Bs.result;let o=s.threshold??kh(),r=s.safetyMargin??bh,i=s.keepRecent??_h,a=wi(),c=yi(e),l=Math.floor(a*(o-r)),u=l-c,d=zt(t);if(d+c<=l){let ne={messages:t,compressed:!1,compacted:!1,tokensRemoved:0};return Bs={msgCount:t.length,lastMsgRef:n,result:ne},ne}let p=d,h=null,g=0;t.length>0&&t[0].role==="system"&&(h=t[0],g=1);let w=Math.max(g,t.length-i),x=t.slice(g,w),O=t.slice(w),I=x.map(ne=>Us(ne,"light")),E=Mn(h,I,O),v=zt(E);if(v+c<=l)return{messages:E,compressed:!0,compacted:!1,tokensRemoved:p-v};if(I=x.map(ne=>Us(ne,"medium")),E=Mn(h,I,O),v=zt(E),v+c<=l)return{messages:E,compressed:!0,compacted:!1,tokensRemoved:p-v};if(I=x.map(ne=>Us(ne,"aggressive")),E=Mn(h,I,O),v=zt(E),v+c<=l)return{messages:E,compressed:!0,compacted:!1,tokensRemoved:p-v};let A=process.env.NEX_SKIP_COMPACTOR==="1",te=x.filter(ne=>ne._pinned),oe=x.filter(ne=>!ne._compacted&&!ne._pinned);if(!A&&oe.length>=6)try{let{compactMessages:ne}=zc(),S=await ne(oe);if(S){let Te=x.filter(Ae=>Ae._compacted&&!Ae._pinned),W=[...te,...Te,S.message],K=Mn(h,W,O),ge=zt(K);if(ge+c<=l)return{messages:K,compressed:!0,compacted:!0,tokensRemoved:p-ge};x=W}}catch(ne){process.env.NEX_DEBUG&&console.error("[context-engine] LLM compacting failed:",ne.message)}let de=Eh([...I,...O]),ce=I.map((ne,S)=>({msg:ne,score:ne._pinned?1/0:vh(ne,S,I.length,de),tokens:ns(ne)}));for(;ce.length>0&&v>u;){let ne=-1;for(let S=0;S<ce.length;S++)ce[S].score!==1/0&&(ne===-1||ce[S].score<ce[ne].score)&&(ne=S);if(ne===-1)break;v-=ce[ne].tokens,ce.splice(ne,1)}return I=ce.map(ne=>ne.msg),E=Mn(h,I,O),v=zt(E),{messages:E,compressed:!0,compacted:!1,tokensRemoved:p-v}}function Mn(t,e,s){let n=[];return t&&n.push(t),n.push(...e,...s),n}function Lk(t,e){if(!t)return"";if(ts(t)<=e)return t;let n=e*4,o=t.split(`
|
|
195
|
+
`),r=Math.floor(n*.6),i=Math.floor(n*.4),a="",c=0;for(let p of o){if(a.length+p.length+1>r)break;a+=(a?`
|
|
196
|
+
`:"")+p,c++}let l="",u=0;for(let p=o.length-1;p>=c;p--){let h=o[p]+(l?`
|
|
197
|
+
`:"")+l;if(h.length>i)break;l=h,u++}let f=`
|
|
198
198
|
|
|
199
|
-
... (${o.length-
|
|
199
|
+
... (${o.length-c-u} lines omitted, ${o.length} total) ...
|
|
200
200
|
|
|
201
|
-
`;return a+f+
|
|
201
|
+
`;return a+f+l}var Ik=6;function jk(t,e,s=!1){let n=wi(),o=yi(e),r=Math.floor(n*(s?.35:.5))-o,i=zt(t),a=Math.floor(i*(s?.5:.8));r>a&&(r=a);let c=null,l=0;t.length>0&&t[0].role==="system"&&(c=t[0],l=1);let u=s?2:Ik,d=Math.max(l,t.length-u),f=t.slice(l,d),p=t.slice(d),h=f.map(v=>Us(v,"aggressive"));s&&(p=p.map(v=>Us(v,"aggressive")));let g=Mn(c,h,p),w=zt(g);for(;h.length>0&&w>r;){let v=h.shift();w-=ns(v)}s&&w>r&&(p=p.filter(A=>A.role==="user").slice(-1),g=Mn(c,[],p),w=zt(g)),g=Mn(c,h,p);let x=t.filter(v=>v.role==="user"),O=v=>{let A=typeof v.content=="string"?v.content:"";return A.startsWith("[SYSTEM WARNING]")||A.startsWith("[SYSTEM:")||A.startsWith("BLOCKED:")},I=x.find(v=>!O(v)),E=[...x].reverse().find(v=>!O(v));if(I&&!g.find(v=>v===I)){let v=g.findIndex(te=>te.role==="system"),A=v>=0?v+1:0;g.splice(A,0,I)}return E&&E!==I&&!g.find(v=>v===E)&&g.push(E),{messages:g,tokensRemoved:i-zt(g)}}Th.exports={estimateTokens:ts,estimateMessageTokens:ns,estimateMessagesTokens:zt,estimateDeltaTokens:Rk,estimateToolsTokens:yi,serializeMessage:Tk,getContextWindow:wi,getUsage:Ck,compressMessage:Us,compressToolResult:Sh,scoreMessageRelevance:vh,extractActiveFiles:Eh,buildProgressSnapshot:Nk,fitToContext:Pk,forceCompress:jk,truncateFileContent:Lk,invalidateTokenRatioCache:Ek,invalidateFitToContextCache:Mk,getEffectiveCompressionThreshold:kh,COMPRESSION_THRESHOLD:Mo,TIER_COMPRESSION_THRESHOLDS:xh,SAFETY_MARGIN:bh,KEEP_RECENT:_h}});var Hs=J((bC,Rh)=>{var{fork:Dk}=require("child_process"),qk=require("path"),Fk=qk.join(__dirname,"background-worker.js"),ss=new Map,Ws=new Map;function Bk(){return`bg-${Date.now()}-${Math.random().toString(36).slice(2,6)}`}function Uk(t){let e=Bk(),s=Dk(Fk,[],{silent:!0,env:process.env,cwd:process.cwd()});return s.send({jobId:e,agentDef:t}),s.on("message",n=>{n.type==="result"?Vc(e,t,n.payload):n.type==="error"&&Vc(e,t,{task:t.task,status:"failed",result:`Background agent error: ${n.error}`,toolsUsed:[],tokensUsed:{input:0,output:0}})}),s.on("exit",(n,o)=>{if(ss.has(e)){let r=o?`killed (${o})`:`exit code ${n}`;Vc(e,t,{task:t.task,status:"failed",result:`Background agent terminated unexpectedly: ${r}`,toolsUsed:[],tokensUsed:{input:0,output:0}})}}),ss.set(e,{process:s,agentDef:t,startedAt:Date.now()}),e}function Vc(t,e,s){ss.delete(t),Ws.set(t,{jobId:t,agentDef:e,result:s,finishedAt:Date.now()})}function Wk(){if(Ws.size===0)return[];let t=[...Ws.values()];return Ws.clear(),t}function Hk(){return ss.size>0||Ws.size>0}function Yk(){let t=ss.size;return t===0?"":`${t} bg agent${t===1?"":"s"} running`}function Gk(){for(let[t,e]of ss){try{e.process.kill("SIGTERM")}catch{}ss.delete(t)}Ws.clear()}Rh.exports={createJob:Uk,getCompletedJobs:Wk,getPendingJobSummary:Yk,hasPendingOrCompletedJobs:Hk,cancelAllJobs:Gk}});var el=J((xC,Xh)=>{var{callStream:zk,getActiveProviderName:bi,getActiveModelId:Ch,getConfiguredProviders:Kk,getProvider:Ah,getActiveProvider:Oh,parseModelSpec:Nh}=st(),{parseToolArgs:Mh}=mo(),{filterToolsForModel:Xk,getModelTier:$i}=To(),{getModelBriefing:Vk}=gi(),{trackUsage:Ph,estimateTokens:Lh}=Wr(),{MultiProgress:Jk,C:_C}=Je();function Ih(t){return!t||typeof t!="string"?0:typeof Lh=="function"?Lh(t):Math.ceil(t.length/4)}var qh=15,Zk=parseInt(process.env.NEX_MAX_PARALLEL||"5",10),jh=parseInt(process.env.NEX_MAX_CHAT_RETRIES||"3",10),Fh=8,Qk=2,_i=new Map,Bh=600*1e3;function eS(t,e){let s=_i.get(t);return s&&s.agentId!==e&&Date.now()-s.timestamp<Bh?!1:(_i.set(t,{agentId:e,timestamp:Date.now()}),!0)}function Po(t){_i.delete(t)}function Jc(){_i.clear()}function Zc(t){let e=(t.message||"").toLowerCase(),s=t.code||"";return e.includes("429")||e.includes("rate limit")?"rate_limit":e.includes("401")||e.includes("403")||e.includes("unauthorized")||e.includes("forbidden")?"auth":e.includes("context")&&(e.includes("too long")||e.includes("overflow")||e.includes("maximum"))||e.includes("400")&&(e.includes("content")||e.includes("length"))?"context_overflow":e.includes("500")||e.includes("502")||e.includes("503")||e.includes("504")?"server":e.includes("timed out")||e.includes("timeout")?"timeout":s==="ECONNRESET"||s==="ECONNABORTED"||s==="ETIMEDOUT"||s==="ECONNREFUSED"||s==="ENOTFOUND"||e.includes("socket disconnected")||e.includes("tls")||e.includes("econnreset")||e.includes("fetch failed")||e.includes("etimedout")||e.includes("enotfound")?"network":"unknown"}function Uh(t){let e=Zc(t);return e==="rate_limit"||e==="server"||e==="network"||e==="timeout"}async function Wh(t,e,s){let n;for(let o=0;o<=jh;o++)try{return await zk(t,e,s)}catch(r){n=r;let i=Zc(r);if(i==="auth")throw r.message=`Authentication failed \u2014 check your API key or permissions. (${r.message})`,r;if(i==="context_overflow")throw r.message=`Context window exceeded \u2014 reduce message history or use a model with a larger context. (${r.message})`,r;if(o<jh&&Uh(r)){let c=i==="rate_limit"?Math.min(2e3*Math.pow(2,o),15e3):Math.min(500*Math.pow(2,o),4e3);await new Promise(l=>setTimeout(l,c).unref());continue}throw r}throw n}var Dh=new Set(["ask_user","task_list"]);function Hh(t){return t>=2?new Set([...Dh,"spawn_agents"]):Dh}var tS=new Set(["write_file","edit_file","patch_file"]),Yh={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:""}},nS=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,sS=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function Gh(t){return sS.test(t)?"full":nS.test(t)?"essential":t.length>300?"full":"standard"}function zh(t){let e=Kk(),s=bi(),n=[...e].sort((o,r)=>(o.name===s?-1:1)-(r.name===s?-1:1));for(let o of n)for(let r of o.models)if($i(r.id,o.name)===t)return{provider:o.name,model:r.id};return null}var oS={essential:process.env.NEX_FAST_MODEL||null,standard:process.env.NEX_STANDARD_MODEL||null,full:process.env.NEX_HEAVY_MODEL||null};function xi(t){if(t.model){let{provider:o,model:r}=Nh(t.model),i=o?Ah(o):Oh(),a=o||bi();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let c=$i(r,a);return{provider:a,model:r,tier:c}}}let e=Gh(t.task),s=oS[e];if(s){let{provider:o,model:r}=Nh(s),i=o?Ah(o):Oh(),a=o||bi();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let c=$i(r,a);return{provider:a,model:r,tier:c}}}let n=zh(e);if(n){let o=$i(n.model,n.provider);return{provider:n.provider,model:n.model,tier:o}}return{provider:null,model:null,tier:null}}async function Kh(t,e={},s=0){let n=s===0?qh:Fh,o=Math.min(t.max_iterations||10,n),r=`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,i=[],a={input:0,output:0},c=new Set,l=new Map,u=t._systemPrompt||`You are a focused sub-agent. Complete this specific task efficiently.
|
|
202
202
|
|
|
203
203
|
TASK: ${t.task}
|
|
204
204
|
${t.context?`
|
|
@@ -211,144 +211,145 @@ RULES:
|
|
|
211
211
|
- When done, respond with a clear summary of what you did and the result.
|
|
212
212
|
- Do not ask questions \u2014 make reasonable decisions.
|
|
213
213
|
- Use relative paths when possible.
|
|
214
|
+
- You are not alone in the codebase. Do NOT revert or overwrite work that may belong to another agent.
|
|
215
|
+
- Treat any files mentioned in your context/scope as your ownership boundary. Stay inside it unless you are only reading for context.
|
|
214
216
|
|
|
215
217
|
TOOL STRATEGY:
|
|
216
218
|
- Use read_file to read files (not bash cat). Use edit_file/patch_file to modify (not bash sed).
|
|
217
219
|
- Use glob to find files by name. Use grep to search contents. Only use bash for shell operations.
|
|
218
220
|
- ALWAYS read a file with read_file before editing it. edit_file old_text must match exactly.
|
|
221
|
+
- Prefer symbol-first retrieval: identify the owning file/function, then read the exact section you need.
|
|
222
|
+
- After making a change, verify with the smallest relevant check before doing more exploration.
|
|
219
223
|
|
|
220
224
|
ERROR RECOVERY:
|
|
221
225
|
- If edit_file fails with "old_text not found": read the file again, compare, and retry with exact text.
|
|
222
226
|
- If bash fails: read the error, fix the root cause, then retry.
|
|
223
|
-
- After 2 failed attempts at the same operation, summarize the issue and stop.`,d=t.type&&
|
|
227
|
+
- After 2 failed attempts at the same operation, summarize the issue and stop.`,d=t.type&&Yh[t.type],f=d&&d.systemSuffix?`
|
|
224
228
|
|
|
225
|
-
${d.systemSuffix}`:"",p=
|
|
226
|
-
${
|
|
229
|
+
${d.systemSuffix}`:"",p=xi(t),h=p.provider,g=p.model,w=p.tier,x=Vk(g||Ch()),I=[{role:"system",content:(x?`## Model Briefing
|
|
230
|
+
${x}
|
|
227
231
|
|
|
228
232
|
---
|
|
229
233
|
|
|
230
|
-
`:"")+u+f}];
|
|
231
|
-
`)}let
|
|
232
|
-
...(truncated)`:
|
|
233
|
-
`)}catch(u){return
|
|
234
|
+
`:"")+u+f}];I.push({role:"user",content:t.task});let{TOOL_DEFINITIONS:E,executeTool:v}=Ls(),A=Hh(s),te=Xk(E.filter(ce=>!A.has(ce.function.name)),w);if(d&&d.allowedTools&&(te=te.filter(ce=>d.allowedTools.has(ce.function.name))),g&&!t._skipLog){let ce=w?` (${w})`:"";process.stderr.write(` [sub-agent: ${h}:${g}${ce}]
|
|
235
|
+
`)}let oe={};h&&(oe.provider=h),g&&(oe.model=g);let de=new Set;try{for(let ne=0;ne<o;ne++){let S=await Wh(I,te,oe);if(!S||typeof S!="object")throw new Error("Empty or invalid response from provider");{let ke=h||bi(),xe=g||Ch();if(S.usage){let _=S.usage.prompt_tokens||0,j=S.usage.completion_tokens||0;a.input+=_,a.output+=j,Ph(ke,xe,_,j)}else{let _=S.content||"",j=I.map(L=>typeof L.content=="string"?L.content:Array.isArray(L.content)?L.content.map(b=>typeof b=="string"?b:b.text||"").join(""):"").join(" "),H=Ih(j),M=Ih(_);a.input+=H,a.output+=M,a._estimated=!0,Ph(ke,xe,H,M)}}let Te=S.content||"",W=S.tool_calls,K={role:"assistant",content:Te||""};if(W&&W.length>0&&(K.tool_calls=W),I.push(K),!W||W.length===0){for(let ke of c)Po(ke);return{task:t.task,status:"done",result:Te||"(no response)",toolsUsed:i,tokensUsed:a,modelSpec:h&&g?`${h}:${g}`:null}}let ge=new Set,Ae=W.map(ke=>{let xe=ke.function.name,_=Mh(ke.function.arguments),j=ke.id||`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!_)return Promise.resolve({role:"tool",content:`ERROR: Malformed tool arguments for ${xe}`,tool_call_id:j});if(["edit_file","patch_file"].includes(xe)&&_.path){if(de.has(_.path)||ge.has(_.path))return Promise.resolve({role:"tool",content:`BLOCKED: "${_.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:j});ge.add(_.path)}let H=null;if(tS.has(xe)&&_.path){let L=require("path"),b=L.isAbsolute(_.path)?_.path:L.resolve(process.cwd(),_.path);if(t._readOnlyFiles&&t._readOnlyFiles.length>0){let Z=L.relative(process.cwd(),b);if(t._readOnlyFiles.some(pe=>Z===pe||Z.startsWith(pe+"/")||b===pe||b.startsWith(pe+"/")))return Promise.resolve({role:"tool",content:`ERROR: File '${_.path}' is owned by another agent and is READ ONLY. Write to your own scope files instead.`,tool_call_id:j})}if(c.has(b)||!eS(b,r))return Promise.resolve({role:"tool",content:`ERROR: File '${_.path}' is locked by another operation. Try a different approach or skip this file.`,tool_call_id:j});c.add(b),H=b}return i.push(xe),e.onUpdate&&e.onUpdate({type:"tool_call",tool:xe,agentId:r}),(xe==="spawn_agents"?Qc(_,s+1):v(xe,_,{autoConfirm:!0,silent:!0})).then(L=>{H&&(Po(H),c.delete(H));let b=String(L??"");return _&&_.path&&(["edit_file","patch_file","write_file"].includes(xe)&&b.startsWith("Edited:")?de.add(_.path):xe==="read_file"&&!b.startsWith("ERROR")&&de.delete(_.path)),{role:"tool",content:b.length>2e4?b.substring(0,2e4)+`
|
|
236
|
+
...(truncated)`:b,tool_call_id:j}}).catch(L=>(H&&(Po(H),c.delete(H)),{role:"tool",content:`ERROR: ${L.message}`,tool_call_id:j}))}),qe=await Promise.all(Ae);if(I.push(...qe),ne>=7&&I.length>12)try{let{compressMessage:ke}=rn(),xe=I.length-6;for(let _=1;_<xe;_++)I[_]._subAgentCompressed||(I[_]={...ke(I[_],"light"),_subAgentCompressed:!0})}catch{}for(let ke=0;ke<W.length;ke++){let xe=W[ke];if(xe.function.name==="bash_exec"){let _=Mh(xe.function.arguments);if((qe[ke]?.content||"").startsWith("ERROR")&&_&&_.command){let H=_.command.replace(/\s+/g," ").trim().slice(0,100);l.set(H,(l.get(H)||0)+1)}}}e.onUpdate&&e.onUpdate(`step ${ne+1}/${o}`)}for(let ne of c)Po(ne);let ce=[...l.entries()].filter(([,ne])=>ne>=3).sort((ne,S)=>S[1]-ne[1]).slice(0,3).map(([ne,S])=>`"${ne}" (failed ${S}\xD7)`);return{task:t.task,status:"truncated",abortReason:"iteration_limit",repeatedFailures:ce,result:I[I.length-1]?.content||"(max iterations reached)",toolsUsed:i,tokensUsed:a,modelSpec:h&&g?`${h}:${g}`:null}}catch(ce){for(let ne of c)Po(ne);return{task:t.task,status:"failed",result:`Error: ${ce.message}`,toolsUsed:i,tokensUsed:a,modelSpec:h&&g?`${h}:${g}`:null}}}async function Qc(t,e=0){if(e>=2)return"ERROR: max agent nesting depth (2) reached \u2014 reviewer agents cannot spawn further agents.";let s=e===0?Zk:Qk,n=e===0?qh:Fh,o=(t.agents||[]).slice(0,s);if(o.length===0)return"ERROR: No agents specified";let r=e>0?" \u21B3 ":"",i=e>0?38:44,a=o.map(u=>xi(u)),c=o.map((u,d)=>{let f=a[d],p=f.model?` [${f.model}]`:"",h=u.task.substring(0,i-p.length);return`${r}Agent ${d+1}${p}: ${h}${u.task.length>h.length?"...":""}`}),l=new Jk(c);l.start();try{let u=o.map((g,w)=>{let x=a[w],O=Math.min(g.max_iterations||n,n),I=x.model?{...g,model:`${x.provider}:${x.model}`,_skipLog:!0,max_iterations:O}:{...g,_skipLog:!0,max_iterations:O};return Kh(I,{onUpdate:()=>{}},e).then(E=>(l.update(w,E.status==="failed"?"error":"done"),E)).catch(E=>(l.update(w,"error"),{task:g.task,status:"failed",result:`Error: ${E.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}))}),d=await Promise.all(u);l.stop(),Jc();let f=["Sub-agent results:",""],p=0,h=0;for(let g=0;g<d.length;g++){let w=d[g],x=w.status==="done"?"\u2713":w.status==="truncated"?"\u26A0":"\u2717",O=w.modelSpec?` [${w.modelSpec}]`:"";f.push(`${x} Agent ${g+1}${O}: ${w.task}`),f.push(` Status: ${w.status}`),f.push(` Tools used: ${w.toolsUsed.length>0?w.toolsUsed.join(", "):"none"}`),f.push(` Result: ${w.result}`),w.repeatedFailures&&w.repeatedFailures.length>0&&f.push(` Repeated failures: ${w.repeatedFailures.join("; ")}`),f.push(""),p+=w.tokensUsed.input,h+=w.tokensUsed.output}return f.push(`Total sub-agent tokens: ${p} input + ${h} output`),f.join(`
|
|
237
|
+
`)}catch(u){return l.stop(),Jc(),`ERROR: Sub-agent execution failed: ${u.message}`}}async function rS(t){let{createJob:e}=Hs(),s=(t.agents||[]).filter(i=>i.background),n=(t.agents||[]).filter(i=>!i.background),o=s.map(i=>{let a=xi(i),c=a.model?{...i,model:`${a.provider}:${a.model}`,_skipLog:!0}:{...i,_skipLog:!0};return e(c)}),r=[];if(o.length>0&&r.push(`Background agents started: [${o.join(", ")}]
|
|
234
238
|
`+s.map((i,a)=>` ${o[a]}: ${i.task}`).join(`
|
|
235
239
|
`)+`
|
|
236
|
-
Results will be injected into the conversation when each agent completes.`),n.length>0){let i=await
|
|
240
|
+
Results will be injected into the conversation when each agent completes.`),n.length>0){let i=await Qc({agents:n});r.push(i)}return r.join(`
|
|
237
241
|
|
|
238
|
-
`)||"No agents specified."}
|
|
239
|
-
`);for(let r of o){let i=r.match(/^(\w+):\s*(.+)$/);if(!i)continue;let a=i[1].trim(),
|
|
240
|
-
`);for(let i of r)if(i.startsWith("#")){let a=i.replace(/^#+\s*/,"");for(let
|
|
242
|
+
`)||"No agents specified."}Xh.exports={runSubAgent:Kh,executeSpawnAgents:Qc,executeSpawnAgentsBackground:rS,clearAllLocks:Jc,classifyTask:Gh,pickModelForTier:zh,resolveSubAgentModel:xi,classifyError:Zc,isRetryableError:Uh,callWithRetry:Wh,getExcludedTools:Hh,LOCK_TIMEOUT_MS:Bh,SUB_AGENT_TYPES:Yh}});var cl=J((kC,lm)=>{var He=require("fs"),bn=require("path"),{atomicWrite:Vh,withFileLockSync:Jh}=Gn(),iS=new Set(["the","a","an","is","are","and","or","but","in","on","at","to","for","of","with","this","that","it","as","be","by","from","was","were","has","have","had","not","do","does","did","so","if","its","my","me","we","you","he","she","they","our","your","their","can","will","would","could","should","may","might","then","than","also","which","when","where","how","what","who","all","any","each","more","most","use","used","using","get","set","new","add","make","der","die","das","den","dem","des","ein","eine","einen","einem","eines","und","oder","aber","von","zu","mit","auf","bei","nach","aus","vor","ist","sind","war","hat","haben","wird","kann","soll","muss","nicht","auch","als","durch"]);function Gs(){let t=bn.join(process.cwd(),".nex","brain");return He.existsSync(t)||He.mkdirSync(t,{recursive:!0}),t}function Si(){return bn.join(Gs(),".brain-index.json")}function sl(){return bn.join(Gs(),".embeddings.json")}function Lo(){let t=bn.join(process.cwd(),".nex","brain");if(!He.existsSync(t))return[];try{return He.readdirSync(t).filter(e=>e.endsWith(".md")&&!e.startsWith(".")).map(e=>{let s=bn.join(t,e),n=He.statSync(s);return{name:e.replace(/\.md$/,""),path:s,size:n.size,modified:new Date(n.mtimeMs)}}).sort((e,s)=>s.modified-e.modified)}catch{return[]}}function Io(t){let e={},s=t,n=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(n){let o=n[1].split(`
|
|
243
|
+
`);for(let r of o){let i=r.match(/^(\w+):\s*(.+)$/);if(!i)continue;let a=i[1].trim(),c=i[2].trim();c.startsWith("[")&&c.endsWith("]")?e[a]=c.slice(1,-1).split(",").map(l=>l.trim()).filter(Boolean):e[a]=c}s=n[2]}return{frontmatter:e,body:s}}function Zh(t){let e=bn.join(Gs(),`${t}.md`);if(!He.existsSync(e))return{name:t,content:"",body:"",frontmatter:{}};let s=He.readFileSync(e,"utf-8"),{frontmatter:n,body:o}=Io(s);return{name:t,content:s,body:o,frontmatter:n}}function aS(t,e){let s=bn.join(Gs(),`${t}.md`);Vh(s,e),uS(t,e),cS()}function cS(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return;let t=sl();He.existsSync(t)&&setImmediate(async()=>{try{await rm()}catch{}})}function lS(t){let e=bn.join(Gs(),`${t}.md`);return He.existsSync(e)?(He.unlinkSync(e),dS(t),!0):!1}function ki(t){return t.toLowerCase().replace(/[^a-z0-9äöüß\s-]/g," ").split(/[\s-]+/).filter(e=>e.length>2&&!iS.has(e))}function ol(t){let e={},{frontmatter:s,body:n}=Io(t),o=Array.isArray(s.tags)?s.tags:[];for(let i of o){let a=i.toLowerCase().replace(/[^a-z0-9-]/g,"");a.length>1&&(e[a]=(e[a]||0)+5)}let r=(n||t).split(`
|
|
244
|
+
`);for(let i of r)if(i.startsWith("#")){let a=i.replace(/^#+\s*/,"");for(let c of ki(a))e[c]=(e[c]||0)+3}for(let i of ki(n||t))e[i]=(e[i]||0)+1;return e}function rl(){let t=Si();if(!He.existsSync(t))return{documents:{}};try{return JSON.parse(He.readFileSync(t,"utf-8"))}catch{return{documents:{}}}}function il(t){Vh(Si(),JSON.stringify(t,null,2))}function uS(t,e){Jh(Si(),()=>{let s=rl(),{frontmatter:n}=Io(e),o=Array.isArray(n.tags)?n.tags:[];s.documents[t]={keywords:ol(e),tags:o,modified:new Date().toISOString()},il(s)})}function dS(t){Jh(Si(),()=>{let e=rl();delete e.documents[t],il(e)})}function nl(){let t=Lo(),e={documents:{}};for(let s of t){let n=He.readFileSync(s.path,"utf-8"),{frontmatter:o}=Io(n),r=Array.isArray(o.tags)?o.tags:[];e.documents[s.name]={keywords:ol(n),tags:r,modified:s.modified.toISOString()}}return il(e),e}function Qh(){let t=rl(),e=Lo();for(let s of e){let n=t.documents[s.name];if(!n||new Date(n.modified)<s.modified)return nl()}for(let s of Object.keys(t.documents))if(!e.some(n=>n.name===s))return nl();return t}function em(t,e={}){let{topK:s=3,minScore:n=.1}=e,o=ki(t);if(o.length===0)return[];let r=Qh(),i=[];for(let[a,c]of Object.entries(r.documents)){let l=0;for(let u of o){c.keywords[u]&&(l+=c.keywords[u]);for(let[d,f]of Object.entries(c.keywords))d!==u&&d.length>3&&u.length>3&&(d.includes(u)||u.includes(d))&&(l+=f*.3)}l>=n&&i.push({name:a,score:l})}return i.sort((a,c)=>c.score-a.score),i.slice(0,s)}var tm=process.env.NEX_EMBED_MODEL||"nomic-embed-text",tl=400,fS=50;async function nm(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return!1;try{let t=process.env.OLLAMA_HOST||"http://localhost:11434",e=require("http"),s=require("https"),n=new URL(`${t}/api/tags`),o=n.protocol==="https:"?s:e;return((await new Promise((a,c)=>{let l=o.get(n.toString(),{timeout:2e3},u=>{let d="";u.on("data",f=>d+=f),u.on("end",()=>{try{a(JSON.parse(d))}catch{c(new Error("bad json"))}})});l.on("error",c),l.on("timeout",()=>{l.destroy(),c(new Error("timeout"))})})).models||[]).map(a=>a.name).some(a=>a.startsWith(tm.split(":")[0]))}catch{return!1}}async function al(t){let e=process.env.OLLAMA_HOST||"http://localhost:11434",s=require("http"),n=require("https"),o=new URL(`${e}/api/embeddings`),r=o.protocol==="https:"?n:s,i=JSON.stringify({model:tm,prompt:t});return new Promise((a,c)=>{let l=r.request(o,{method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(i)},timeout:3e4},u=>{let d="";u.on("data",f=>d+=f),u.on("end",()=>{try{a(JSON.parse(d).embedding||[])}catch(f){c(f)}})});l.on("error",c),l.on("timeout",()=>{l.destroy(),c(new Error("embedding timeout"))}),l.write(i),l.end()})}function sm(t,e){if(!t||!e||t.length!==e.length)return 0;let s=0,n=0,o=0;for(let i=0;i<t.length;i++)s+=t[i]*e[i],n+=t[i]*t[i],o+=e[i]*e[i];let r=Math.sqrt(n)*Math.sqrt(o);return r===0?0:s/r}function om(t){let e=t.split(/\s+/),s=[],n=0;for(;n<e.length;){let o=e.slice(n,n+tl).join(" ");if(s.push({text:o,offset:n}),n+tl>=e.length)break;n+=tl-fS}return s}async function rm(){let t=Lo(),e={documents:{}},s=sl();if(He.existsSync(s))try{e=JSON.parse(He.readFileSync(s,"utf-8"))}catch{}for(let n of t){let o=e.documents[n.name];if(o&&new Date(o.modified)>=n.modified)continue;let r=He.readFileSync(n.path,"utf-8"),i=om(r),a=[];for(let c of i){let l=await al(c.text);a.push({text:c.text,embedding:l,offset:c.offset})}e.documents[n.name]={chunks:a,modified:n.modified.toISOString()}}for(let n of Object.keys(e.documents))t.some(o=>o.name===n)||delete e.documents[n];return He.writeFileSync(s,JSON.stringify(e),"utf-8"),e}async function im(t,e={}){let{topK:s=3,minSimilarity:n=.3}=e,o=sl();if(!He.existsSync(o))return[];let r;try{r=JSON.parse(He.readFileSync(o,"utf-8"))}catch{return[]}let i=await al(t),a=[];for(let[c,l]of Object.entries(r.documents||{})){let u=0,d="";for(let f of l.chunks||[]){let p=sm(i,f.embedding);p>u&&(u=p,d=f.text)}u>=n&&a.push({name:c,score:u,bestChunk:d})}return a.sort((c,l)=>l.score-c.score),a.slice(0,s)}function am(t,e,s={}){let{k:n=60,topK:o=3}=s,r={};return t.forEach((i,a)=>{r[i.name]=(r[i.name]||0)+1/(n+a+1)}),e.forEach((i,a)=>{r[i.name]=(r[i.name]||0)+1/(n+a+1)}),Object.entries(r).map(([i,a])=>({name:i,score:a})).sort((i,a)=>a.score-i.score).slice(0,o)}async function cm(t,e={}){let{topK:s=3,minScore:n=.1}=e,o=em(t,{topK:s,minScore:n}),r=o;if(process.env.NEX_BRAIN_EMBEDDINGS!=="false")try{if(await nm()){let a=await im(t,{topK:s});r=am(o,a,{topK:s})}}catch{}return r.map(i=>{let a=Zh(i.name),c=(a.body||a.content||"").slice(0,300).replace(/\n+/g," ")+"...";return{name:i.name,score:i.score,content:a.content,excerpt:c}})}var Ys={queryKey:null,result:null,ts:0},pS=3e5;async function hS(t){if(!t||!t.trim())return"";let e=bn.join(process.cwd(),".nex","brain");if(!He.existsSync(e)||Lo().length===0)return"";let n=t.trim().toLowerCase().slice(0,200);if(Ys.result!==null&&Ys.queryKey===n&&Date.now()-Ys.ts<pS)return Ys.result;let o;try{o=await cm(t,{topK:3})}catch{return""}if(!o||o.length===0)return"";let r;try{r=rn().estimateTokens}catch{r=u=>Math.ceil(u.length/4)}let i=25e3,a=[],c=0;for(let u of o){let d=u.content||"",f=r(d);if(c+f>i){let h=i-c;if(h<100)break;let g=h/f;d=d.slice(0,Math.floor(d.length*g))+`
|
|
241
245
|
...(truncated)`}let p=typeof u.score=="number"?u.score.toFixed(2):String(u.score);if(a.push(`--- ${u.name} (relevance: ${p}) ---
|
|
242
|
-
${d}`),
|
|
246
|
+
${d}`),c+=r(d),c>=i)break}if(a.length===0)return Ys={queryKey:n,result:"",ts:Date.now()},"";let l=`KNOWLEDGE BASE (auto-selected):
|
|
243
247
|
|
|
244
248
|
${a.join(`
|
|
245
249
|
|
|
246
|
-
`)}`;return
|
|
250
|
+
`)}`;return Ys={queryKey:n,result:l,ts:Date.now()},l}lm.exports={getBrainDir:Gs,listDocuments:Lo,readDocument:Zh,writeDocument:aS,removeDocument:lS,buildIndex:nl,getIndex:Qh,query:cm,getBrainContext:hS,isEmbeddingAvailable:nm,generateEmbedding:al,buildEmbeddingIndex:rm,semanticQuery:im,cosineSimilarity:sm,_keywordQuery:em,_extractKeywords:ol,_chunkText:om,parseFrontmatter:Io,tokenize:ki,_fuseResults:am}});var qo=J((SC,_m)=>{var je=require("fs"),Tt=require("path"),mS=require("os"),{atomicWrite:vi,withFileLockSync:um}=Gn(),jo=["user","feedback","project","reference"],gS=50;function os(){return Tt.join(process.cwd(),".nex","memory")}function zs(){return Tt.join(os(),"memory.json")}function dm(){return Tt.join(os(),"MEMORY.md")}function yS(){return Tt.join(process.cwd(),"NEX.md")}function fm(){return Tt.join(mS.homedir(),".nex","NEX.md")}function Ei(){let t=os();je.existsSync(t)||je.mkdirSync(t,{recursive:!0})}function pm(t){let e=Tt.join(os(),t);return je.existsSync(e)||je.mkdirSync(e,{recursive:!0}),e}function Do(){let t=zs();if(!je.existsSync(t))return{};try{return JSON.parse(je.readFileSync(t,"utf-8"))}catch{return{}}}function hm(t){Ei(),vi(zs(),JSON.stringify(t,null,2))}function mm(){let t=zs();if(!je.existsSync(t))return;let e=Do(),s=Object.keys(e);if(s.length===0){try{je.renameSync(t,t+".bak")}catch{}return}for(let n of s){let o=e[n],r=o.value||String(o),i=n.replace(/[^a-z0-9_-]/gi,"-").toLowerCase().replace(/-+/g,"-").replace(/^-|-$/g,"");if(!i)continue;let a=pm("project"),c=Tt.join(a,`${i}.md`),l=r.split(`
|
|
247
251
|
`)[0].slice(0,100),u=`---
|
|
248
252
|
name: ${n}
|
|
249
|
-
description: ${
|
|
253
|
+
description: ${l}
|
|
250
254
|
type: project
|
|
251
255
|
---
|
|
252
256
|
|
|
253
257
|
${r}
|
|
254
|
-
`;
|
|
255
|
-
`)[0].slice(0,100),
|
|
258
|
+
`;vi(c,u)}Ti();try{je.renameSync(t,t+".bak")}catch{}}function wS(t,e,s,n){if(!jo.includes(t))return{ok:!1,path:"",error:`Invalid type: ${t}. Must be one of: ${jo.join(", ")}`};if(!e||typeof e!="string")return{ok:!1,path:"",error:"name must be a non-empty string"};if(!s||typeof s!="string"||s.trim().length<5)return{ok:!1,path:"",error:"content must be at least 5 characters"};let o=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase().replace(/-+/g,"-").replace(/^-|-$/g,"");if(!o)return{ok:!1,path:"",error:"name produces empty slug after sanitization"};let r=pm(t),i=Tt.join(r,`${o}.md`);if(je.existsSync(i))try{if(ll(je.readFileSync(i,"utf-8")).body.slice(0,200)===s.slice(0,200))return{ok:!0,path:i,updated:!1}}catch{}let a=n||s.split(`
|
|
259
|
+
`)[0].slice(0,100),c=`---
|
|
256
260
|
name: ${e}
|
|
257
261
|
description: ${a}
|
|
258
262
|
type: ${t}
|
|
259
263
|
---
|
|
260
264
|
|
|
261
265
|
${s}
|
|
262
|
-
`;return
|
|
266
|
+
`;return vi(i,c),Ti(),{ok:!0,path:i,updated:!0}}function $S(t,e){if(!jo.includes(t))return!1;let s=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase(),n=Tt.join(os(),t,`${s}.md`);if(!je.existsSync(n))return!1;try{return je.unlinkSync(n),Ti(),!0}catch{return!1}}function ll(t){let e=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(!e)return{name:"",description:"",type:"",body:t.trim()};let s=e[1],n=(e[2]||"").trim(),o=r=>{let i=s.match(new RegExp(`^${r}:\\s*(.+)$`,"m"));return i?i[1].trim():""};return{name:o("name"),description:o("description"),type:o("type"),body:n}}function gm(){let t=[],e=os();for(let s of jo){let n=Tt.join(e,s);if(!je.existsSync(n))continue;let o;try{o=je.readdirSync(n).filter(r=>r.endsWith(".md"))}catch{continue}for(let r of o){let i=Tt.join(n,r);try{let a=je.readFileSync(i,"utf-8"),c=ll(a);t.push({type:s,name:c.name||Tt.basename(r,".md"),description:c.description,filePath:i})}catch{}}}return t}function Ti(){let t=gm(),e=["# Project Memory Index",""];for(let s of t){if(e.length>=gS+2)break;let n=`${s.type}/${Tt.basename(s.filePath)}`;e.push(`- [${s.name}](${n}) \u2014 ${s.description||"(no description)"}`)}Ei(),vi(dm(),e.join(`
|
|
263
267
|
`)+`
|
|
264
|
-
`)}function
|
|
265
|
-
${e}`);let s=
|
|
266
|
-
${s}`);let n="",o=
|
|
268
|
+
`)}function ym(){let t=dm();if(!je.existsSync(t))return"";try{return je.readFileSync(t,"utf-8").trim()}catch{return""}}function bS(t,e){Ei(),um(zs(),()=>{let s=Do();s[t]={value:e,updatedAt:new Date().toISOString()},hm(s)})}function _S(t){let e=Do();return e[t]?e[t].value:null}function xS(t){return Ei(),um(zs(),()=>{let e=Do();return t in e?(delete e[t],hm(e),!0):!1})}function wm(){let t=Do();return Object.entries(t).map(([e,s])=>({key:e,value:s.value,updatedAt:s.updatedAt}))}function $m(){let t=fm();if(!je.existsSync(t))return"";try{return je.readFileSync(t,"utf-8").trim()}catch{return""}}function bm(){let t=yS();if(!je.existsSync(t))return"";try{return je.readFileSync(t,"utf-8").trim()}catch{return""}}function kS(){mm();let t=[],e=$m();e&&t.push(`GLOBAL INSTRUCTIONS (~/.nex/NEX.md):
|
|
269
|
+
${e}`);let s=bm();s&&t.push(`PROJECT INSTRUCTIONS (NEX.md):
|
|
270
|
+
${s}`);let n="",o=ym();if(o)n=o;else{let d=wm();d.length>0&&(n=`PROJECT MEMORY:
|
|
267
271
|
${d.map(p=>` ${p.key}: ${p.value}`).join(`
|
|
268
272
|
`)}`)}let r=t.join(`
|
|
269
273
|
|
|
270
|
-
`),i="You can save insights with save_memory(type, name, content) and remove them with delete_memory(type, name).",
|
|
271
|
-
`),f="";for(let p of d){if(f.length+p.length+1>
|
|
274
|
+
`),i="You can save insights with save_memory(type, name, content) and remove them with delete_memory(type, name).",l=Math.max(1500,16e3-r.length-i.length-10);if(n.length>l&&l>200){let d=n.split(`
|
|
275
|
+
`),f="";for(let p of d){if(f.length+p.length+1>l-60)break;f+=p+`
|
|
272
276
|
`}n=f.trimEnd()+`
|
|
273
|
-
[Memory index truncated \u2014 use delete_memory to prune old entries]`}else n.length>
|
|
277
|
+
[Memory index truncated \u2014 use delete_memory to prune old entries]`}else n.length>l&&(n="");let u=[...t];return n&&u.push(n),u.length>0&&u.push(i),u.join(`
|
|
274
278
|
|
|
275
|
-
`)}
|
|
276
|
-
`;
|
|
277
|
-
`).filter(
|
|
279
|
+
`)}_m.exports={saveMemory:wS,deleteMemory:$S,scanMemories:gm,rebuildIndex:Ti,loadMemoryIndex:ym,remember:bS,recall:_S,forget:xS,listMemories:wm,loadGlobalInstructions:$m,loadProjectInstructions:bm,getMemoryContext:kS,_getMemoryDir:os,_getMemoryFile:zs,_getGlobalNexMdPath:fm,_parseMemoryFile:ll,_migrateIfNeeded:mm,VALID_TYPES:jo}});var Tm=J((vC,Em)=>{var Fo=require("fs"),ul=require("path"),dl=process.env.NEX_AUDIT!=="false",rs=null;function xm(){return rs||(rs=ul.join(process.cwd(),".nex","audit"),Fo.existsSync(rs)||Fo.mkdirSync(rs,{recursive:!0}),rs)}function km(){let t=new Date().toISOString().split("T")[0];return ul.join(xm(),`${t}.jsonl`)}function SS(t){if(dl)try{let e={timestamp:new Date().toISOString(),tool:t.tool,args:Sm(t.args),resultLength:typeof t.result=="string"?t.result.length:0,resultPreview:typeof t.result=="string"?t.result.substring(0,200):"",duration:t.duration||0,success:t.success!==!1,model:t.model||null,provider:t.provider||null},s=JSON.stringify(e)+`
|
|
280
|
+
`;Fo.appendFileSync(km(),s,"utf-8")}catch{}}function Sm(t){if(!t||typeof t!="object")return{};let e={};for(let[s,n]of Object.entries(t))/key|token|password|secret|credential/i.test(s)?e[s]="***":typeof n=="string"&&n.length>500?e[s]=n.substring(0,500)+`... (${n.length} chars)`:e[s]=n;return e}function vm(t={}){let e=xm(),s=t.days||1,n=[];for(let o=0;o<s;o++){let r=t.date||new Date(Date.now()-o*864e5).toISOString().split("T")[0],i=ul.join(e,`${r}.jsonl`);if(!Fo.existsSync(i))continue;let a=Fo.readFileSync(i,"utf-8").split(`
|
|
281
|
+
`).filter(c=>c.trim());for(let c of a)try{let l=JSON.parse(c);if(t.tool&&l.tool!==t.tool)continue;n.push(l)}catch{}if(t.date)break}return n}function vS(t=1){let e=vm({days:t});if(e.length===0)return{totalCalls:0,byTool:{},avgDuration:0,successRate:1};let s={},n=0,o=0;for(let r of e)s[r.tool]=(s[r.tool]||0)+1,n+=r.duration||0,r.success&&o++;return{totalCalls:e.length,byTool:s,avgDuration:Math.round(n/e.length),successRate:o/e.length}}function ES(t){dl=t}function TS(){return dl}function RS(){rs=null}Em.exports={logToolExecution:SS,sanitizeArgs:Sm,readAuditLog:vm,getAuditSummary:vS,setAuditEnabled:ES,isAuditEnabled:TS,getAuditLogPath:km,_reset:RS}});var Gm=J((TC,Ym)=>{var Ye=require("fs").promises,Xt=require("fs"),ue=require("path"),Be=require("util").promisify(require("child_process").exec),is=require("util").promisify(require("child_process").execFile),{spawnSync:CS}=require("child_process"),fl=require("axios"),{isForbidden:AS,isSSHForbidden:OS,isDangerous:NS,isCritical:Rm,isBashPathForbidden:MS,confirm:Kt}=yo(),{showDiff:Ri,showNewFile:PS,showEditDiff:EC,confirmFileChange:Bo}=Gd(),{C:ae,Spinner:LS,getToolSpinnerText:IS}=Je(),{isGitRepo:pl,getCurrentBranch:Cm,getStatus:jS,getDiff:DS}=Kr(),{recordChange:Ci}=sf(),{fuzzyFindText:Am,findMostSimilar:Go}=Rf(),{runDiagnostics:Uo}=Af(),{findFileInIndex:qS,getFileIndex:Om,searchContentIndex:FS,scorePathMatch:Nm,refreshIndex:BS,isIndexValid:US}=gn(),{resolveProfile:Dt,sshExec:yt,scpUpload:WS,scpDownload:Mm}=js(),{resolveDeployConfig:HS,loadDeployConfigs:YS}=Vf(),{getEditMode:Pm}=To(),GS=/^(vim?|nano|emacs|pico|less|more|top|htop|iftop|iotop|glances|telnet\s|screen|tmux|fzf|gum|dialog|whiptail|man\s|node\s*$|python3?\s*$|irb\s*$|rails\s*c|psql\s|mysql\s|redis-cli|mongosh?|sqlite3)\b/,zS=/^ssh\s/,KS=/^ssh(?:\s+-\S+)*\s+\S+@?\S+\s+["']?[^-]/;async function Rt(t){return Ye.access(t).then(()=>!0).catch(()=>!1)}var Ai=null,Lm=0,XS=12e4;function VS(){let t=Date.now();if(Ai&&t-Lm<XS)return Ai;let e=ue.dirname(process.cwd());try{let s=Xt.readdirSync(e,{withFileTypes:!0}),n=ue.basename(process.cwd()),o=s.filter(r=>r.isDirectory()&&r.name!==n&&!r.name.startsWith(".")).map(r=>r.name).sort();return Ai=o.length>0?o:null,Lm=t,Ai}catch{return null}}function hl(t){if(t&&ue.resolve(t)!==process.cwd())return"";let e=VS();if(!e)return"";let s=ue.dirname(process.cwd());return`
|
|
278
282
|
Hint: no matches in current project. Sibling directories in ${s}/:
|
|
279
283
|
${e.join(", ")}
|
|
280
|
-
You can search there with: grep pattern --path ${s}/<dir>`}async function
|
|
281
|
-
${i.map(
|
|
282
|
-
`)}`}}catch{}if(r&&r.length>2)try{let i=r.toLowerCase(),{getFileIndex:a}=
|
|
283
|
-
${
|
|
284
|
-
`)}`}}catch{}try{let{smartSearch:i}=
|
|
285
|
-
${a.map(u=>
|
|
286
|
-
`)}`}}}catch{}return{fixedPath:null,message:""}}function
|
|
284
|
+
You can search there with: grep pattern --path ${s}/<dir>`}async function Oi(t){if(!t)return{fixedPath:null,message:""};let e=t.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),s=rt(e);if(s&&await Rt(s))return{fixedPath:s,message:`(auto-fixed path: ${t} \u2192 ${e})`};let n=[".js",".ts",".jsx",".tsx",".mjs",".cjs",".json"],o=ue.extname(t);if(!o)for(let i of n){let a=rt(t+i);if(a&&await Rt(a))return{fixedPath:a,message:`(auto-fixed: added ${i} extension)`}}if(o){let i=t.replace(/\.[^.]+$/,"");for(let a of n){if(a===o)continue;let c=rt(i+a);if(c&&await Rt(c))return{fixedPath:c,message:`(auto-fixed: ${o} \u2192 ${a})`}}}let r=ue.basename(t);if(r&&r.length>2)try{let i=qS(r).map(a=>rt(a));if(i.length===1)return{fixedPath:i[0],message:`(auto-fixed: found ${r} at ${ue.relative(process.cwd(),i[0])})`};if(i.length>1&&i.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
|
|
285
|
+
${i.map(c=>ue.relative(process.cwd(),c)).map(c=>` - ${c}`).join(`
|
|
286
|
+
`)}`}}catch{}if(r&&r.length>2)try{let i=r.toLowerCase(),{getFileIndex:a}=gn(),c=a().filter(l=>ue.basename(l).toLowerCase()===i).map(l=>rt(l));if(c.length===1)return{fixedPath:c[0],message:`(auto-fixed: case-insensitive match \u2192 ${ue.relative(process.cwd(),c[0])})`};if(c.length>1&&c.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
|
|
287
|
+
${c.map(u=>ue.relative(process.cwd(),u)).map(u=>` - ${u}`).join(`
|
|
288
|
+
`)}`}}catch{}try{let{smartSearch:i}=gn(),a=i(t,{limit:5,minScore:15});if(a.length>0){let c=rt(a[0].file);if(a[0].score>=200||a.length===1&&a[0].score>=50)return{fixedPath:c,message:`(auto-fixed: smart matched ${t} \u2192 ${ue.relative(process.cwd(),c)})`};if(a.length>=2&&a[0].score>=80&&a[0].score>=a[1].score*1.5)return{fixedPath:c,message:`(auto-fixed: best match ${t} \u2192 ${ue.relative(process.cwd(),c)})`};if(a.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
|
|
289
|
+
${a.map(u=>ue.relative(process.cwd(),rt(u.file))).map(u=>` - ${u}`).join(`
|
|
290
|
+
`)}`}}}catch{}return{fixedPath:null,message:""}}function JS(t){return/\bprintenv\b/.test(t)?"printenv exposes all secrets. Use `echo $VAR_NAME` for a single variable, or `env | grep PATTERN` for filtered output.":/cat\s+.*\.env\b/.test(t)?'Reading .env directly is blocked. Use `grep -v "KEY=" .env` to inspect non-secret entries, or ask the user to share specific values.':/cat\s+.*credentials/i.test(t)?"Credentials files are blocked. Reference the variable name from the application config instead.":/python3?\s+-c\s/.test(t)?"Inline python -c is blocked. Write a temporary script file and run it with `python3 script.py` instead.":/node\s+-e\s/.test(t)?"Inline node -e is blocked. Write a temporary script file and run it with `node script.js` instead.":/curl.*-X\s*POST|curl.*--data/.test(t)?"curl POST is blocked to prevent data exfiltration. Use the application's own API client or ask the user to run the request.":/base64.*\|.*bash/.test(t)?"Piping base64-decoded content to bash is blocked. Decode the content first, inspect it, then run explicitly.":/\beval\s*\(/.test(t)?"eval is blocked. Execute the command directly without eval.":/(?:^|[;&|]\s*)history(?:\s|$)/.test(t)?"Shell history is blocked. Look at git log or project files for context instead.":/\bsed\s+-n\s+['"]?\d+,\d+p/.test(t)?'sed -n line-range scrolling floods context with irrelevant lines. Use targeted grep instead: grep -n "ERROR\\|pattern" <logfile> | tail -20':""}function qm(t){if(!t||typeof t!="string")return null;let e=t.trim();if(!e||/[()[\]{}|^$\\]/.test(e))return null;let s=e.replace(/\*\*/g," ").replace(/[*?]/g," ").replace(/[:=><!]+/g," ").replace(/\s+/g," ").trim();if(!s)return null;let n=s.split(/[\/\s,]+/).map(o=>o.trim()).filter(Boolean).filter(o=>o!=="."&&o!=="..").filter(o=>!/^\.[a-z0-9]+$/i.test(o)).filter(o=>o.length>=3);return n.length===0?null:(n.sort((o,r)=>r.length-o.length),n[0])}async function Fm(t,e){let s=qm(t);if(!s)return new Map;try{let n=await FS(s,void 0,e||process.cwd()),o=new Map;for(let r of n){let a=r.name.toLowerCase()===s.toLowerCase()?140:90;o.set(r.file,(o.get(r.file)||0)+a)}return o}catch{return new Map}}function Im(t,e){if(!t)return"";let s=e||process.cwd(),n=ue.isAbsolute(t)?t:ue.resolve(s,t),o=ue.relative(s,n);return o&&!o.startsWith("..")&&!ue.isAbsolute(o)?o:ue.relative(process.cwd(),n)}function Wo(t,e){let s=(t||"").trim();return s?e==="files_with_matches"||e==="count"?s.split(`
|
|
291
|
+
`).filter(n=>n.trim()):s.split(`
|
|
292
|
+
`).filter(n=>n.trim()):[]}function Bm(t,{query:e,basePath:s,definitionScores:n=new Map,mtimeByPath:o=new Map}={}){let r=qm(e);return[...t].sort((i,a)=>{let c=Im(i,s),l=Im(a,s),u=0,d=0;if(r&&(u+=Nm(c,r),d+=Nm(l,r)),u+=n.get(c)||0,d+=n.get(l)||0,u!==d)return d-u;let f=o.get(i)||0,p=o.get(a)||0;return f!==p?p-f:c.localeCompare(l)})}async function ml(t,{query:e,basePath:s,outputMode:n}={}){if(!Array.isArray(t)||t.length<=1)return t;let o=new Map,r=[];for(let l of t){if(!l)continue;let u=l;(n==="count"||n!=="files_with_matches")&&(u=l.split(":")[0]),o.has(u)||(o.set(u,[]),r.push(u)),o.get(u).push(l)}let i=await Fm(e,s),a=Bm(r,{query:e,basePath:s,definitionScores:i}),c=[];for(let l of a)c.push(...o.get(l)||[]);return c}function Um(t,e){let s=[];if(/command not found|: not found|not recognized/i.test(t)){let n=e.match(/^(\S+)/),o=n?n[1]:"";/^(npx|npm|node|yarn|pnpm|bun)$/.test(o)?s.push("HINT: Node.js/npm may not be in PATH. Check your Node.js installation."):/^(python|python3|pip|pip3)$/.test(o)?s.push("HINT: Python may not be installed. Try: brew install python3 (macOS) or apt install python3 (Linux)"):s.push(`HINT: "${o}" is not installed. Try installing it with your package manager.`)}if(/Cannot find module|MODULE_NOT_FOUND/i.test(t)){let n=t.match(/Cannot find module '([^']+)'/),o=n?n[1]:"";o&&!o.startsWith(".")&&!o.startsWith("/")?s.push(`HINT: Missing npm package "${o}". Run: npm install ${o}`):s.push("HINT: Module not found. Check the import path or run npm install.")}if(/permission denied|EACCES/i.test(t)&&s.push("HINT: Permission denied. Check file permissions or try a different approach."),/EADDRINUSE|address already in use/i.test(t)){let n=t.match(/port (\d+)|:(\d+)/),o=n?n[1]||n[2]:"";s.push(`HINT: Port ${o||""} is already in use. Kill the process or use a different port.`)}if(/SyntaxError|Unexpected token/i.test(t)&&s.push("HINT: Syntax error in the code. Check the file at the line number shown above."),/TS\d{4}:/i.test(t)&&s.push("HINT: TypeScript compilation error. Fix the type issue at the indicated line."),/Test Suites:.*failed|Tests:.*failed/i.test(t)&&s.push("HINT: Test failures detected. Read the error output above to identify failing tests."),/fatal: not a git repository/i.test(t)&&s.push("HINT: Not inside a git repository. Run git init or cd to a git project."),/^curl\b/.test(e)){let n=t.match(/curl:\s*\((\d+)\)/),o=n?parseInt(n[1],10):null;o===6||/Could not resolve host/i.test(t)?s.push("HINT: Hostname could not be resolved. Check DNS or use an IP address directly."):o===7||/Failed to connect|Connection refused/i.test(t)?s.push("HINT: Service not running or port wrong. Check if the service is up and the port is correct."):o===22||/HTTP error/i.test(t)?s.push("HINT: HTTP 4xx/5xx response. The endpoint exists but returned an error status."):o===28||/timed out/i.test(t)?s.push("HINT: Request timed out. The host may be unreachable or the service is slow."):(o===35||/SSL.*error/i.test(t))&&s.push("HINT: SSL/TLS handshake failed. Try with --insecure to bypass, or check the certificate.")}if(/remote port forwarding failed/i.test(t)){let n=t.match(/port (\d+)/),o=n?n[1]:"";s.push(`HINT: SSH remote port forwarding failed for port ${o}. The port may already be bound on the server. Check with: ssh server "ss -tuln | grep ${o}" and kill any lingering process with that port.`)}return/bind.*Cannot assign requested address|Address already in use/i.test(t)&&s.push("HINT: Port is already in use. Find the process with: ss -tuln | grep <port> and kill it, then retry."),/Connection.*timed out|ssh.*timeout/i.test(t)&&/^ssh\b/.test(e)&&s.push("HINT: SSH connection timed out. Check if the host is reachable: ping <host> and verify the port with: nc -zv <host> 22"),/spawn \/bin\/sh ENOENT|spawn sh ENOENT/i.test(t)&&s.push("HINT: The working directory was deleted during this session \u2014 bash cannot execute commands in a non-existent cwd. Previous rm/delete commands succeeded. Use list_directory or glob to verify the state instead of retrying bash."),/cp.*\$f.*\$f\.bak.*sed.*-i\.bak|sed.*-i\.bak.*cp.*\$f.*\$f\.bak/i.test(e)&&s.push('HINT: Using both cp with .bak and sed -i.bak creates double backups (.bak.bak). Choose one method: either cp "$f" "$f.bak" OR sed -i.bak, not both.'),s.length===0?t:t+`
|
|
287
293
|
|
|
288
294
|
`+s.join(`
|
|
289
|
-
`)}function _m(t,e,s){let n=Fo(t,e);if(!n)return null;let o=Math.max(2,Math.ceil(e.length*.03));return n.distance>o?null:{autoFixed:!0,matchText:n.text,content:t.split(n.text).join(s),distance:n.distance,line:n.line}}var gm=!1,ts=null;function wS(){ts&&(ts(),ts=null)}var rc=null;function _S(t){rc=t}async function oc(){if(!gm){gm=!0;try{let{stdout:t}=await je("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await je('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await je("git stash pop",{cwd:process.cwd(),timeout:1e4}),await je("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var $S=[/\.ssh\//i,/\.gnupg\//i,/\.aws\//i,/\.config\/gcloud/i,/\/etc\/shadow/,/\/etc\/passwd/,/\/etc\/sudoers/,/\.env(?:\.|$)/,/credentials/i,/\.npmrc$/,/\.docker\/config\.json/,/\.kube\/config/];function tt(t){let e=me.isAbsolute(t)?me.resolve(t):me.resolve(process.cwd(),t);for(let s of $S)if(s.test(e))return null;return e}var bS=[{type:"function",function:{name:"bash",description:`Execute a bash command in the project directory. Timeout: 90s (commands that exceed this are killed). Use for: running tests, installing packages, git commands, build tools, starting servers, compiling code. Example: use bash for "npm install" or "git status", but NOT for "cat config.json" (use read_file instead) or "grep -r 'error' src/" (use grep tool instead). AVOID using bash for: cat/head/tail (use read_file), sed/awk (use edit_file), find/ls (use glob or list_directory), grep/rg (use grep tool). Using dedicated tools is faster and produces better-formatted output. Always quote file paths containing spaces with double quotes. Check the exit code in output \u2014 non-zero means the command failed. For long-running commands (large builds, full test suites), warn the user if they may exceed 90s. Destructive or dangerous commands (rm -rf, git push, npm publish, sudo) require user confirmation.`,parameters:{type:"object",properties:{command:{type:"string",description:"The bash command to execute"}},required:["command"]}}},{type:"function",function:{name:"read_file",description:"Read a file's contents with line numbers. ALWAYS read a file before editing it to ensure exact content matching \u2014 edit_file requires the EXACT text including whitespace and newlines. Example: read_file path=src/app.js line_start=10 line_end=20. Auto-truncates at 350 lines for unbounded reads. For large files (>350 lines), use line_start/line_end to read specific sections. Concrete example: read_file(path='src/app.js', line_start=10, line_end=20) reads lines 10-20 of src/app.js. Prefer this over bash cat/head/tail \u2014 dedicated tools produce better-formatted output. Files are read with UTF-8 encoding. IMPORTANT: If you need more than 350 lines, specify line_start and line_end explicitly \u2014 omitting them will truncate the output.",parameters:{type:"object",properties:{path:{type:"string",description:"File path (relative or absolute)"},line_start:{type:"number",description:"Start line (1-based, optional)"},line_end:{type:"number",description:"End line (1-based, optional)"}},required:["path"]}}},{type:"function",function:{name:"write_file",description:"Create a new file or completely overwrite an existing file. Example: use write_file for creating a new config file like .env.example, but NOT for changing one line in an existing file (use edit_file instead). For targeted changes to existing files, prefer edit_file or patch_file instead \u2014 they only send the diff and are safer. Only use write_file when creating new files or when the entire content needs to be replaced.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},content:{type:"string",description:"Full file content"}},required:["path","content"]}}},{type:"function",function:{name:"edit_file",description:"Replace specific text in a file. ALWAYS call read_file first to get the exact content \u2014 edit_file requires the EXACT text including whitespace, indentation, and newlines. Example: edit_file(path='src/config.js', old_text='debug: false', new_text='debug: true'). IMPORTANT: old_text must match byte-for-byte \u2014 even a single space or newline difference will cause failure. If the edit fails with 'old_text not found', re-read that region with line_start/line_end then retry. For multiple replacements in one file, prefer patch_file (atomic). For new files, use write_file instead.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},old_text:{type:"string",description:"Exact text to find (must match file content precisely)"},new_text:{type:"string",description:"Replacement text"}},required:["path","old_text","new_text"]}}},{type:"function",function:{name:"list_directory",description:"List files and directories in a tree view. Use this to understand project structure. Example: use list_directory to see the overall layout of the src/ directory, but NOT for finding all .js files (use glob instead). For finding specific files by pattern, prefer glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory path"},max_depth:{type:"number",description:"Max depth (default: 2)"},pattern:{type:"string",description:"File filter glob (e.g. '*.js')"}},required:["path"]}}},{type:"function",function:{name:"search_files",description:"Search for a text pattern across files (regex). Returns matching lines with file paths. Example: use search_files for finding all occurrences of 'error' in .js files, but NOT for finding all .js files (use glob instead). For simple content search, grep is equivalent. For finding files by name, use glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory to search"},pattern:{type:"string",description:"Search pattern (regex)"},file_pattern:{type:"string",description:"File filter (e.g. '*.js')"}},required:["path","pattern"]}}},{type:"function",function:{name:"glob",description:"Find files matching a glob pattern by name or extension. Returns paths sorted by modification time. ALWAYS use this to locate files BEFORE reading them \u2014 never guess file paths. Example: glob(pattern='src/**/*.test.js') finds all test files in src directory. DO NOT use for content search (e.g. finding 'error' in files) \u2014 use grep tool instead. Examples: '**/*.test.js' (all test files), 'src/**/*.ts' (all TypeScript in src), 'package.json' (find config). Prefer this over bash find/ls. When you need file contents, glob first to get the exact path, then read_file to read it.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Glob pattern (e.g. '**/*.ts', 'src/**/*.test.js')"},path:{type:"string",description:"Base directory (default: project root)"}},required:["pattern"]}}},{type:"function",function:{name:"grep",description:"Search file CONTENTS with regex \u2014 use this when you need to find text inside files. Example: grep(pattern='callStream') finds files containing the text 'callStream'. Do NOT use glob for this \u2014 glob finds files by NAME pattern, grep searches file CONTENTS. Use output_mode='files_with_matches' for just file paths, output_mode='content' (default) for matching lines. Optionally use include to filter by file type (e.g. '*.js') but OMIT it when first searching \u2014 code may live in .html, .vue, .py or other unexpected file types. Supports context lines, offset pagination, and multiline patterns.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Regex pattern to search for"},path:{type:"string",description:"Directory or file to search (default: project root)"},include:{type:"string",description:"File filter glob (e.g. '*.js', '*.ts')"},ignore_case:{type:"boolean",description:"Case-insensitive search"},output_mode:{type:"string",enum:["content","files_with_matches","count"],description:"Output mode: content (matching lines), files_with_matches (file paths only), count (match counts). Default: content"},context:{type:"number",description:"Lines of context around each match (like grep -C)"},before_context:{type:"number",description:"Lines before each match (like grep -B)"},after_context:{type:"number",description:"Lines after each match (like grep -A)"},head_limit:{type:"number",description:"Limit output to first N results"},offset:{type:"number",description:"Skip first N results"},type:{type:"string",description:"File type filter (e.g. 'js', 'py', 'ts') \u2014 maps to --include='*.ext'"},multiline:{type:"boolean",description:"Enable multiline matching (grep -Pz)"},staged:{type:"boolean",description:"Search only staged content (git diff --cached). Default: false"}},required:["pattern"]}}},{type:"function",function:{name:"patch_file",description:"Apply multiple text replacements to a file atomically. All patches are validated before any are applied \u2014 if one fails, none are written. Example: when changing 3 different variables in the same function, use patch_file with an array of 3 { old_text, new_text } objects instead of 3 separate edit_file calls. This ensures either all changes are applied or none are, preventing partial edits. Like edit_file, all old_text values must match exactly.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},patches:{type:"array",description:"Array of { old_text, new_text } replacements to apply in order",items:{type:"object",properties:{old_text:{type:"string",description:"Text to find"},new_text:{type:"string",description:"Replacement text"}},required:["old_text","new_text"]}}},required:["path","patches"]}}},{type:"function",function:{name:"web_fetch",description:"Fetch content from a URL and return text. HTML tags are stripped. Use for reading documentation, API responses, or web pages. Will not work with authenticated/private URLs.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to fetch"},max_length:{type:"number",description:"Max response length in chars (default: 10000)"}},required:["url"]}}},{type:"function",function:{name:"web_search",description:"Search the web. Uses Perplexity (grounded, AI-summarized) if PERPLEXITY_API_KEY is set, otherwise DuckDuckGo. Returns titles, URLs, and summaries. Use to find documentation, solutions, or current information beyond your knowledge cutoff.",parameters:{type:"object",properties:{query:{type:"string",description:"Search query"},max_results:{type:"number",description:"Max results (default: 5)"}},required:["query"]}}},{type:"function",function:{name:"browser_open",description:"Open a URL in a headless browser and return the page title, text content, and links. More reliable than web_fetch for JavaScript-heavy pages. Requires playwright (npm install playwright && npx playwright install chromium).",parameters:{type:"object",properties:{url:{type:"string",description:"URL to open"},wait_for:{type:"string",enum:["domcontentloaded","networkidle","load"],description:"When to consider page loaded (default: domcontentloaded)"}},required:["url"]}}},{type:"function",function:{name:"browser_screenshot",description:"Take a screenshot of a URL in a headless browser. Returns the screenshot file path. The path can be pasted into the next message for visual analysis. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot"},full_page:{type:"boolean",description:"Capture full page (default: false \u2014 viewport only)"},width:{type:"number",description:"Viewport width in px (default: 1280)"},height:{type:"number",description:"Viewport height in px (default: 800)"}},required:["url"]}}},{type:"function",function:{name:"visual_review",description:"Screenshot a URL, analyze the visual result, and return structured feedback about layout, design, and usability issues. Use this to visually inspect web pages, check CSS changes, or verify UI fixes. Returns the screenshot path + analysis.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot and analyze"},focus:{type:"string",description:"What to focus on: layout, colors, typography, spacing, responsiveness, accessibility, or a custom description (e.g. 'check the navbar alignment')"},width:{type:"number",description:"Viewport width in px (default: 1280)"},height:{type:"number",description:"Viewport height in px (default: 800)"},full_page:{type:"boolean",description:"Capture full scrollable page (default: false)"},compare_with:{type:"string",description:"Path to a previous screenshot to compare against (optional). Enables before/after analysis."}},required:["url"]}}},{type:"function",function:{name:"clipboard_image",description:"Grab the current image from the system clipboard (macOS). Returns the screenshot path for visual analysis. Use when the user says 'clipboard', 'pasteboard', or wants to analyze a copied screenshot.",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"browser_click",description:"Click an element on a web page (by CSS selector or visible text). Returns the new URL after navigation. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of element to click (mutually exclusive with text)"},text:{type:"string",description:"Visible text of element to click (mutually exclusive with selector)"}},required:["url"]}}},{type:"function",function:{name:"browser_fill",description:"Fill a form field on a web page and optionally submit. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of the input field"},value:{type:"string",description:"Value to fill in"},submit:{type:"boolean",description:"Press Enter to submit after filling (default: false)"}},required:["url","selector","value"]}}},{type:"function",function:{name:"visual_diff",description:"Compare two screenshots pixel-by-pixel and compute a visual diff. Returns the percentage of changed pixels and which screen regions (top-left, center, bottom-right, etc.) were affected. Use after making CSS/HTML changes to quantify what changed. Example: take a before screenshot, make changes, take an after screenshot, then visual_diff both paths.",parameters:{type:"object",properties:{before:{type:"string",description:"Path to the 'before' screenshot (PNG)"},after:{type:"string",description:"Path to the 'after' screenshot (PNG)"},threshold:{type:"number",description:"Color distance threshold 0-1 (default: 0.1). Lower = more sensitive."}},required:["before","after"]}}},{type:"function",function:{name:"responsive_sweep",description:"Screenshot a URL at 5 viewport widths (320, 768, 1024, 1440, 1920) and return all screenshots for breakpoint analysis. Quickly identifies responsive layout issues across mobile, tablet, and desktop. Returns images for visual analysis.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot at each viewport"},viewports:{type:"array",items:{type:"object",properties:{width:{type:"number"},label:{type:"string"}}},description:"Custom viewport list (default: 320/768/1024/1440/1920)"},full_page:{type:"boolean",description:"Capture full scrollable page at each viewport (default: false)"}},required:["url"]}}},{type:"function",function:{name:"visual_annotate",description:"Draw annotations (red boxes, arrows, circles) directly on a screenshot to mark problem areas. Returns the annotated image. Use instead of describing locations verbally \u2014 visual markers are unambiguous.",parameters:{type:"object",properties:{image:{type:"string",description:"Path to the screenshot (PNG) to annotate"},annotations:{type:"array",items:{type:"object",properties:{type:{type:"string",description:"box, arrow, or circle"},x:{type:"number",description:"X position (px)"},y:{type:"number",description:"Y position (px)"},width:{type:"number",description:"Width for box (px)"},height:{type:"number",description:"Height for box (px)"},toX:{type:"number",description:"Arrow end X (px)"},toY:{type:"number",description:"Arrow end Y (px)"},radius:{type:"number",description:"Circle radius (px)"},label:{type:"string",description:"Text label for the annotation"},color:{type:"string",description:"Hex color (default: #FF0000)"}},required:["type","x","y"]},description:"List of annotations to draw"}},required:["image","annotations"]}}},{type:"function",function:{name:"visual_watch",description:"Hot-reload visual feedback loop: watches source files for changes, waits for HMR to settle, takes a new screenshot, diffs it against the previous one, and reports what changed. Runs up to N iterations (default: 10). Requires a running dev server (Vite, Next, etc.) and chokidar. Use for autonomous visual polish loops.",parameters:{type:"object",properties:{url:{type:"string",description:"Dev server URL to screenshot (e.g. http://localhost:5173)"},watch:{type:"array",items:{type:"string"},description:"File paths or directories to watch for changes (e.g. ['src/components', 'src/styles'])"},max_iterations:{type:"number",description:"Max number of change\u2192screenshot\u2192diff cycles (default: 10)"},hmr_delay:{type:"number",description:"Milliseconds to wait after file change for HMR to settle (default: 1500)"}},required:["url","watch"]}}},{type:"function",function:{name:"design_tokens",description:"Extract design tokens from a screenshot: dominant colors (with hex/rgb/frequency/category), detected vertical spacing values, and image dimensions. Use to audit visual consistency, compare against a design system, or reverse-engineer CSS variables from a rendered page.",parameters:{type:"object",properties:{image:{type:"string",description:"Path to screenshot (PNG) to analyze"},sample_rate:{type:"number",description:"Pixel sampling interval \u2014 lower = more accurate but slower (default: 4)"}},required:["image"]}}},{type:"function",function:{name:"design_compare",description:"Compare a live web page against a reference design (Figma export, mockup PNG). Screenshots the URL at the reference image's dimensions, computes pixel-level diff, and returns annotated images highlighting deviations. Use to verify implementation matches the design spec.",parameters:{type:"object",properties:{url:{type:"string",description:"Live URL to compare against the reference"},reference:{type:"string",description:"Path to reference design image (PNG)"},width:{type:"number",description:"Override viewport width (default: match reference image width)"},height:{type:"number",description:"Override viewport height (default: 800)"},threshold:{type:"number",description:"Color distance threshold 0-1 (default: 0.1)"}},required:["url","reference"]}}},{type:"function",function:{name:"ask_user",description:"Ask the user a clarifying question with 2-3 specific options. Use when the user's intent is ambiguous. Always provide concrete, actionable options. The user can select an option or type a custom answer.",parameters:{type:"object",properties:{question:{type:"string",description:"The clarifying question to ask"},options:{type:"array",items:{type:"string"},description:"2-3 specific, actionable answer options for the user to choose from",minItems:1,maxItems:3}},required:["question","options"]}}},{type:"function",function:{name:"git_status",description:"Get git status: current branch, changed files, staged/unstaged state. Use before git operations to understand the current state.",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"git_diff",description:"Get git diff for changed files. Shows additions and deletions.",parameters:{type:"object",properties:{staged:{type:"boolean",description:"Show only staged changes (default: false)"},file:{type:"string",description:"Diff specific file only (optional)"}},required:[]}}},{type:"function",function:{name:"git_log",description:"Show recent git commits (short format).",parameters:{type:"object",properties:{count:{type:"number",description:"Number of commits to show (default: 10)"},file:{type:"string",description:"Show commits for specific file (optional)"}},required:[]}}},{type:"function",function:{name:"task_list",description:"Create and manage a task list for complex multi-step tasks. Use for tasks with 3+ steps to track progress. Actions: create (new list with tasks), update (mark task in_progress/done/failed), get (view current list). Always update task status as you work.",parameters:{type:"object",properties:{action:{type:"string",enum:["create","update","get"],description:"Action to perform"},name:{type:"string",description:"Task list name (for create)"},tasks:{type:"array",description:"Array of tasks to create (for create)",items:{type:"object",properties:{description:{type:"string",description:"Task description"},depends_on:{type:"array",items:{type:"string"},description:"IDs of prerequisite tasks"}},required:["description"]}},task_id:{type:"string",description:"Task ID to update (for update)"},status:{type:"string",enum:["in_progress","done","failed"],description:"New status (for update)"},result:{type:"string",description:"Result summary (for update, optional)"}},required:["action"]}}},{type:"function",function:{name:"gh_run_list",description:"List recent GitHub Actions workflow runs for this repository. Shows run status, conclusion, branch, and timing. Use to check CI/CD status or find a run ID.",parameters:{type:"object",properties:{limit:{type:"number",description:"Number of runs to show (default: 10, max: 30)"},workflow:{type:"string",description:"Filter by workflow name or filename (optional)"},branch:{type:"string",description:"Filter by branch name (optional)"},status:{type:"string",enum:["completed","in_progress","queued","failure","success"],description:"Filter by status (optional)"}},required:[]}}},{type:"function",function:{name:"gh_run_view",description:"View details of a specific GitHub Actions workflow run: steps, logs, errors. Use gh_run_list first to get the run ID.",parameters:{type:"object",properties:{run_id:{type:"string",description:"The run ID (from gh_run_list)"},log:{type:"boolean",description:"Include full log output (default: false \u2014 shows step summary only)"}},required:["run_id"]}}},{type:"function",function:{name:"gh_workflow_trigger",description:"Trigger a GitHub Actions workflow dispatch event. Only works for workflows with workflow_dispatch trigger. Requires user confirmation.",parameters:{type:"object",properties:{workflow:{type:"string",description:"Workflow filename (e.g. ci.yml) or name"},branch:{type:"string",description:"Branch to run on (default: current branch)"},inputs:{type:"object",description:"Workflow input parameters as key-value pairs (optional)"}},required:["workflow"]}}},{type:"function",function:{name:"spawn_agents",description:"Run multiple independent sub-agents in parallel (max 5 at top level, max 2 when called from within a sub-agent). Each agent has its own conversation context. Use when 2+ tasks can run simultaneously \u2014 e.g. reading multiple files, analyzing separate modules, independent research. Do NOT use for tasks that depend on each other or modify the same file. Keep task descriptions specific and self-contained. SWARM PATTERN: Sub-agents can call spawn_agents once (max nesting depth 2) to enable Architect\u2192Coder\u2192Reviewer pipelines: a coder agent spawns 1-2 reviewer agents that validate and fix its own output before returning results to the parent.",parameters:{type:"object",properties:{agents:{type:"array",description:"Array of agent definitions to run in parallel (max 5)",items:{type:"object",properties:{task:{type:"string",description:"Task description for the agent"},context:{type:"string",description:"Additional context (optional)"},max_iterations:{type:"number",description:"Max iterations (default: 10, max: 15)"},model:{type:"string",description:'Override model for this agent (provider:model, e.g. "anthropic:claude-haiku"). Auto-selected if omitted.'},background:{type:"boolean",description:"Run this agent non-blocking in the background. The main session continues immediately; results are injected as [BACKGROUND AGENT COMPLETED] user messages when the agent finishes. Use for tasks that can run in parallel to your main work."}},required:["task"]}}},required:["agents"]}}},{type:"function",function:{name:"switch_model",description:"Switch the active AI model mid-conversation. Use when a different model is better for the next steps \u2014 e.g. switch to a fast model for simple lookups, or a more capable model for complex refactoring. The switch persists for all subsequent turns.",parameters:{type:"object",properties:{model:{type:"string",description:'Model spec: "provider:model" (e.g. "ollama:devstral-small-2:24b") or just model name'}},required:["model"]}}},{type:"function",function:{name:"k8s_pods",description:"List Kubernetes pods. Shows pod name, status, restarts, and age. Runs kubectl locally or via SSH on a remote server. Use namespace to filter, or omit for all namespaces.",parameters:{type:"object",properties:{namespace:{type:"string",description:"Namespace to list pods in (default: all namespaces)"},label:{type:"string",description:'Label selector filter (e.g. "app=nginx")'},context:{type:"string",description:"kubectl context to use (optional)"},server:{type:"string",description:"Remote server as user@host to run kubectl via SSH (optional, local kubectl if omitted)"}},required:[]}}},{type:"function",function:{name:"k8s_logs",description:'Fetch logs from a Kubernetes pod. Use tail to limit output, since for time-based filtering (e.g. "1h", "30m").',parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (required if pod has multiple containers)"},tail:{type:"number",description:"Number of recent lines to show (default: 100)"},since:{type:"string",description:'Show logs since duration (e.g. "1h", "30m", "5s")'},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod"]}}},{type:"function",function:{name:"k8s_exec",description:"Execute a command inside a running Kubernetes pod (kubectl exec). Requires user confirmation. Use for inspecting container state, reading configs, or debugging.",parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},command:{type:"string",description:'Command to run in the pod (e.g. "env", "ls /app", "cat /etc/config.yaml")'},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (optional)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod","command"]}}},{type:"function",function:{name:"k8s_apply",description:"Apply a Kubernetes manifest file (kubectl apply -f). Requires confirmation before applying to the cluster. Use dry_run=true to validate without applying.",parameters:{type:"object",properties:{file:{type:"string",description:"Path to manifest YAML file (relative or absolute)"},namespace:{type:"string",description:"Override namespace (optional)"},dry_run:{type:"boolean",description:"Validate only without applying (default: false)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["file"]}}},{type:"function",function:{name:"k8s_rollout",description:"Manage Kubernetes deployment rollouts: check status, restart (rolling update), view history, or undo (rollback). Restart and undo require confirmation.",parameters:{type:"object",properties:{action:{type:"string",enum:["status","restart","history","undo"],description:"Action: status (check rollout progress), restart (rolling restart), history (show revision history), undo (rollback to previous revision)"},deployment:{type:"string",description:"Deployment name"},namespace:{type:"string",description:"Namespace (default: default)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["action","deployment"]}}},{type:"function",function:{name:"brain_write",description:"Write or update a knowledge document in the project brain (.nex/brain/). Use this to persist important findings, architecture decisions, debugging insights, or conventions discovered during the session. The user can review changes via /brain review or git diff.",parameters:{type:"object",properties:{name:{type:"string",description:'Document name (without .md extension). Use kebab-case. Examples: "api-auth-flow", "db-schema-notes", "deployment-checklist"'},content:{type:"string",description:"Full Markdown content. Use headings (#), lists (-), and code blocks. Include optional YAML frontmatter with tags."},mode:{type:"string",enum:["create","update","append"],description:"create: new document (fails if exists). update: overwrite existing. append: add to end of existing document."}},required:["name","content","mode"]}}},{type:"function",function:{name:"ssh_exec",description:'Execute a command on a remote server via SSH. Server is a profile name from .nex/servers.json (e.g. "prod") or "user@host". Use for: checking status, reading logs, running deployments. Destructive commands (restart, delete, modify config) require confirmation. For service management prefer service_manage; for logs prefer service_logs.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name (from .nex/servers.json) or "user@host"'},command:{type:"string",description:"Shell command to run on the remote server"},sudo:{type:"boolean",description:"Run command with sudo (only if profile has sudo:true). Default: false"},timeout:{type:"number",description:"Timeout in seconds. Default: 30"}},required:["server","command"]}}},{type:"function",function:{name:"ssh_upload",description:"Upload a local file or directory to a remote server via SCP. Recursive for directories. Requires confirmation before upload.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},local_path:{type:"string",description:"Local path to upload (file or directory)"},remote_path:{type:"string",description:"Destination path on the remote server (absolute preferred)"}},required:["server","local_path","remote_path"]}}},{type:"function",function:{name:"ssh_download",description:"Download a file or directory from a remote server via SCP. Recursive for directories.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},remote_path:{type:"string",description:"Path on the remote server to download"},local_path:{type:"string",description:"Local destination path"}},required:["server","remote_path","local_path"]}}},{type:"function",function:{name:"remote_agent",description:'Delegate a coding task to nex-code running on a remote server. Use this when the task involves server-side projects (musikschule, stadtkapelle, cahill, schoensgibl) that live on almalinux9. Runs nex-code --auto on the server and streams output. Server is a profile name from .nex/servers.json or "user@host".',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name from .nex/servers.json (e.g. "almalinux9") or "user@host"'},task:{type:"string",description:"The full task description to run on the remote nex-code"},project_path:{type:"string",description:"Working directory on the remote server (e.g. /home/deploy/app). Defaults to home directory."},model:{type:"string",description:"Model to use on remote nex-code (e.g. qwen3-coder:480b). Defaults to server default."}},required:["server","task"]}}},{type:"function",function:{name:"service_manage",description:"Manage a systemd service on a remote (or local) server. Uses systemctl. Status is read-only; start/stop/restart/reload/enable/disable require confirmation. For AlmaLinux 9: runs via SSH with sudo if configured.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn", "postgresql")'},action:{type:"string",enum:["status","start","stop","restart","reload","enable","disable"],description:"systemctl action to perform"}},required:["service","action"]}}},{type:"function",function:{name:"service_logs",description:"Fetch systemd service logs via journalctl. Works on AlmaLinux 9 and any systemd Linux. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn")'},lines:{type:"number",description:"Number of recent log lines to fetch. Default: 50"},since:{type:"string",description:'Time filter, e.g. "1 hour ago", "today", "2024-01-01 12:00". Optional.'},follow:{type:"boolean",description:"Tail logs in real-time (follow mode). Default: false"}},required:["service"]}}},{type:"function",function:{name:"container_list",description:"List Docker containers on a server (or locally). Shows container ID, name, image, status, and ports. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},all:{type:"boolean",description:"Show all containers including stopped ones. Default: false (running only)."}},required:[]}}},{type:"function",function:{name:"container_logs",description:"Fetch logs from a Docker container on a server (or locally). Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},lines:{type:"number",description:"Number of recent log lines. Default: 50."},since:{type:"string",description:'Time filter, e.g. "1h", "30m", "2024-01-01T12:00:00". Optional.'}},required:["container"]}}},{type:"function",function:{name:"container_exec",description:"Execute a command inside a running Docker container. Destructive or state-changing commands require confirmation.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},command:{type:"string",description:'Command to run inside the container (e.g. "cat /etc/nginx/nginx.conf").'}},required:["container","command"]}}},{type:"function",function:{name:"container_manage",description:'Start, stop, restart, or remove a Docker container. All actions except "inspect" require confirmation.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},action:{type:"string",enum:["start","stop","restart","remove","inspect"],description:"Action to perform on the container."}},required:["container","action"]}}},{type:"function",function:{name:"frontend_recon",description:"MANDATORY first step before creating or significantly modifying any frontend file (HTML template, Vue/React component, CSS). Scans the project and returns: (1) design tokens \u2014 CSS variables, Tailwind theme colors/fonts, (2) main layout/index page structure, (3) a reference component of the same type, (4) detected JS/CSS framework stack. Call this BEFORE writing any markup or styles. Never skip it for frontend tasks.",parameters:{type:"object",properties:{type:{type:"string",description:'Type of frontend file you are about to create. Used to find a relevant reference component. Examples: "list", "form", "detail", "dashboard", "modal", "component". Optional but improves reference quality.'}},required:[]}}},{type:"function",function:{name:"deploy",description:'Deploy to a remote server. Supports two methods: "rsync" (sync local files) and "git" (git pull on remote). Can use a named config from .nex/deploy.json. Requires confirmation before executing.',parameters:{type:"object",properties:{config:{type:"string",description:'Named deploy config from .nex/deploy.json (e.g. "prod"). Overrides all other params if provided.'},method:{type:"string",enum:["rsync","git"],description:'Deploy method: "rsync" syncs local files (default), "git" runs git pull on the remote.'},server:{type:"string",description:'Profile name or "user@host". Required if no config.'},remote_path:{type:"string",description:"Remote project directory. Required for git method; destination path for rsync."},local_path:{type:"string",description:"Local directory or file to sync. Required for rsync method."},branch:{type:"string",description:"Branch to pull (git method only). Defaults to current remote branch."},deploy_script:{type:"string",description:'Shell command(s) to run on the remote after sync/pull (e.g. "npm ci && systemctl restart myapp"). Optional.'},health_check:{type:"string",description:"URL (HTTP GET) or shell command to verify the service is healthy after deploy. If it fails, the deploy is marked as failed. Optional."},exclude:{type:"array",items:{type:"string"},description:"Paths to exclude from rsync. Optional."},dry_run:{type:"boolean",description:"Show what would happen without executing. Default: false."}},required:[]}}},{type:"function",function:{name:"deployment_status",description:"Check deployment status across all configured servers. Reads .nex/deploy.json configs and checks service health on each server. Returns a status summary table.",parameters:{type:"object",properties:{config:{type:"string",description:"Specific deploy config name to check (optional \u2014 checks all if omitted)"}},required:[]}}},{type:"function",function:{name:"sysadmin",description:"Senior sysadmin operations on a remote (or local) Linux server. Covers: system audit, disk_usage, process_list, network_status, package management (dnf/apt), user management, firewall (firewalld/ufw/iptables), cron, SSL cert checks, log tailing, large file discovery, systemd service management, process kill, journalctl log querying. Read-only actions run without confirmation; state-changing actions require user approval.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},action:{type:"string",enum:["audit","disk_usage","process_list","network_status","package","user_manage","firewall","cron","ssl_check","log_tail","find_large","service","kill_process","journalctl"],description:"Sysadmin operation. audit=full health overview; disk_usage=df+du; process_list=top procs; network_status=open ports; package=dnf/apt (package_action: check|list|install|remove|update|upgrade); user_manage=users/keys; firewall=rules; cron=crontab; ssl_check=cert expiry+days; log_tail=tail any log; find_large=big files; service=systemd unit management; kill_process=kill by PID or name; journalctl=query system journal."},path:{type:"string",description:"File or directory path. For disk_usage (default /), log_tail (required), find_large (default /)."},lines:{type:"number",description:"Lines to tail for log_tail or journalctl. Default: 100."},limit:{type:"number",description:"Result count for process_list (default 20) or find_large (default 20)."},sort_by:{type:"string",enum:["cpu","mem"],description:"Sort order for process_list. Default: cpu."},min_size:{type:"string",description:'Minimum file size for find_large. Default: "100M". Examples: "50M", "1G".'},package_action:{type:"string",enum:["install","remove","update","list","upgrade"],description:"Package sub-action for action=package."},packages:{type:"array",items:{type:"string"},description:"Package name(s) for install/remove/update."},user_action:{type:"string",enum:["list","create","delete","add_ssh_key","info"],description:"User sub-action for action=user_manage."},user:{type:"string",description:"Linux username for user_manage or cron."},groups:{type:"array",items:{type:"string"},description:'Groups to assign on user create (e.g. ["sudo", "docker"]).'},ssh_key:{type:"string",description:"SSH public key string to add for user_action=add_ssh_key."},firewall_action:{type:"string",enum:["status","allow","deny","remove","reload"],description:"Firewall sub-action for action=firewall."},port:{type:"string",description:'Port/protocol for firewall rules, e.g. "80/tcp", "443", "8080/udp".'},cron_action:{type:"string",enum:["list","add","remove"],description:"Cron sub-action for action=cron."},schedule:{type:"string",description:'Cron schedule expression for cron add, e.g. "0 2 * * *".'},command:{type:"string",description:"Command for cron add, or substring to match for cron remove."},domain:{type:"string",description:`Domain for ssl_check (e.g. "example.com"). Auto-detects Let's Encrypt cert on server; falls back to live TLS probe.`},cert_path:{type:"string",description:'Explicit path to cert file on server for ssl_check (e.g. "/etc/letsencrypt/live/x/cert.pem").'},service_name:{type:"string",description:'Systemd unit name for action=service (e.g. "nginx", "my-api", "gunicorn"). .service suffix optional.'},service_action:{type:"string",enum:["status","start","stop","restart","reload","enable","disable","list_failed"],description:"Sub-action for action=service. list_failed shows all failed units."},pid:{type:"number",description:"Process ID to kill for action=kill_process."},process_name:{type:"string",description:"Process name to kill (uses pkill) for action=kill_process. Use with pid for safety."},signal:{type:"string",enum:["SIGTERM","SIGKILL","SIGHUP","SIGINT"],description:"Signal for kill_process. Default: SIGTERM."},unit:{type:"string",description:'Systemd unit to filter for journalctl (e.g. "nginx", "my-api"). Omit for system-wide.'},since:{type:"string",description:'Time filter for journalctl, e.g. "1 hour ago", "today", "2026-03-17 10:00". Default: last 200 lines.'},priority:{type:"string",enum:["emerg","alert","crit","err","warning","notice","info","debug"],description:"Minimum log priority for journalctl. Default: no filter."}},required:["action"]}}},{type:"function",function:{name:"save_memory",description:"Save a typed memory for cross-session persistence. Use this to remember user preferences, feedback, project context, or external references.",parameters:{type:"object",properties:{type:{type:"string",enum:["user","feedback","project","reference"],description:"Memory type: user (role/prefs), feedback (approach guidance), project (ongoing work), reference (external pointers)"},name:{type:"string",description:"Short slug identifier for this memory (e.g. 'testing-preference', 'deploy-workflow')"},content:{type:"string",description:"Markdown content of the memory"},description:{type:"string",description:"One-line description for the memory index (optional, defaults to first line of content)"}},required:["type","name","content"]}}},{type:"function",function:{name:"delete_memory",description:"Delete a typed memory entry. Use this to prune outdated or incorrect memories.",parameters:{type:"object",properties:{type:{type:"string",enum:["user","feedback","project","reference"],description:"Memory type to delete from"},name:{type:"string",description:"Slug identifier of the memory to delete"}},required:["type","name"]}}}];function qo(t,{server:e,context:s}={}){let n=e?e.replace(/[^a-zA-Z0-9@._-]/g,""):null,o=s?s.replace(/[^a-zA-Z0-9._/-]/g,""):null,r="kubectl";if(o&&(r+=` --context ${o}`),r+=` ${t}`,n){let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`ssh -o ConnectTimeout=10 -o BatchMode=yes ${n} "${i}"`}return r}async function ym(t,e,s={}){switch(t){case"bash":{let n=e.command,o=Qk(n);if(o){let d=yS(n);return`BLOCKED: Command matches forbidden pattern: ${o}${d?`
|
|
290
|
-
HINT: ${d}`:""}`}let r=
|
|
291
|
-
HINT: Protected files (.env, credentials, venv, .ssh, etc.) cannot be deleted or moved via bash. Override with NEX_UNPROTECT=1 if intentional.`;if(s.autoConfirm?
|
|
292
|
-
${p}`}}case"read_file":{let n=
|
|
293
|
-
`+
|
|
294
|
-
`),u=await
|
|
295
|
-
`),
|
|
296
|
-
|
|
297
|
-
[\u{1F6A8} FILE TRUNCATED: You are only seeing lines 1-${f} of ${d} 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=${f+1}), or use grep_search to find specific keywords.]`:!p&&d>
|
|
298
|
-
|
|
299
|
-
[\u{1F6A8} FILE CONTINUES: This is only lines ${g+1} to ${
|
|
300
|
-
${
|
|
301
|
-
`+u.message:""}`}let r=await
|
|
302
|
-
Most similar text (line ${
|
|
303
|
-
${
|
|
304
|
-
`),
|
|
305
|
-
`),
|
|
295
|
+
`)}function Wm(t,e,s){let n=Go(t,e);if(!n)return null;let o=Math.max(2,Math.ceil(e.length*.03));return n.distance>o?null:{autoFixed:!0,matchText:n.text,content:t.split(n.text).join(s),distance:n.distance,line:n.line}}var jm=!1,as=null;function ZS(){as&&(as(),as=null)}var $l=null;function QS(t){$l=t}async function gl(){if(!jm){jm=!0;try{let{stdout:t}=await Be("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await Be('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await Be("git stash pop",{cwd:process.cwd(),timeout:1e4}),await Be("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var ev=[/\.ssh\//i,/\.gnupg\//i,/\.aws\//i,/\.config\/gcloud/i,/\/etc\/shadow/,/\/etc\/passwd/,/\/etc\/sudoers/,/\.env(?:\.|$)/,/credentials/i,/\.npmrc$/,/\.docker\/config\.json/,/\.kube\/config/];function tv(){let t=process.cwd();try{return Xt.realpathSync(t)}catch{return ue.resolve(t)}}function nv(t,e){let s=ue.relative(e,t);return s===""||!s.startsWith("..")&&!ue.isAbsolute(s)}function sv(t){if(Xt.existsSync(t))return Xt.realpathSync(t);let e=ue.dirname(t);for(;e&&e!==ue.dirname(e);){if(Xt.existsSync(e)){let s=Xt.realpathSync(e),n=ue.relative(e,t);return ue.resolve(s,n)}e=ue.dirname(e)}return t}function rt(t){let e=ue.isAbsolute(t)?ue.resolve(t):ue.resolve(process.cwd(),t);for(let n of ev)if(n.test(e))return null;let s=sv(e);return nv(s,tv())?s:null}function Se(t){return`'${String(t).replace(/'/g,"'\\''")}'`}function Hm(t){return typeof t=="string"&&/^[a-z_][a-z0-9_-]{0,31}\$?$/i.test(t)}function ov(t){return typeof t=="string"&&/^[a-zA-Z0-9@_.:-]+(?:\.service)?$/.test(t)}function rv(t){return typeof t=="string"&&/^[a-zA-Z0-9+_.:@/-]+$/.test(t)}function yl(t){return typeof t=="string"&&/^\d{1,5}(?:\/(?:tcp|udp))?$/i.test(t)}function iv(t){return typeof t=="string"&&/^(?:SIG[A-Z0-9]+|[A-Z0-9]+|\d{1,2})$/.test(t)}function Ho(t,e="user"){return Hm(t)?null:`ERROR: ${e} contains unsafe characters`}function wl(t,e="service"){return ov(t)?null:`ERROR: ${e} contains unsafe characters`}var av=[{type:"function",function:{name:"bash",description:`Execute a bash command in the project directory. Timeout: 90s (commands that exceed this are killed). Use for: running tests, installing packages, git commands, build tools, starting servers, compiling code. Example: use bash for "npm install" or "git status", but NOT for "cat config.json" (use read_file instead) or "grep -r 'error' src/" (use grep tool instead). AVOID using bash for: cat/head/tail (use read_file), sed/awk (use edit_file), find/ls (use glob or list_directory), grep/rg (use grep tool). Using dedicated tools is faster and produces better-formatted output. Always quote file paths containing spaces with double quotes. Check the exit code in output \u2014 non-zero means the command failed. For long-running commands (large builds, full test suites), warn the user if they may exceed 90s. Destructive or dangerous commands (rm -rf, git push, npm publish, sudo) require user confirmation.`,parameters:{type:"object",properties:{command:{type:"string",description:"The bash command to execute"}},required:["command"]}}},{type:"function",function:{name:"read_file",description:"Read a file's contents with line numbers. ALWAYS read a file before editing it to ensure exact content matching \u2014 edit_file requires the EXACT text including whitespace and newlines. Example: read_file path=src/app.js line_start=10 line_end=20. Auto-truncates at 350 lines for unbounded reads. For large files (>350 lines), use line_start/line_end to read specific sections. Concrete example: read_file(path='src/app.js', line_start=10, line_end=20) reads lines 10-20 of src/app.js. Prefer this over bash cat/head/tail \u2014 dedicated tools produce better-formatted output. Files are read with UTF-8 encoding. IMPORTANT: If you need more than 350 lines, specify line_start and line_end explicitly \u2014 omitting them will truncate the output.",parameters:{type:"object",properties:{path:{type:"string",description:"File path (relative or absolute)"},line_start:{type:"number",description:"Start line (1-based, optional)"},line_end:{type:"number",description:"End line (1-based, optional)"}},required:["path"]}}},{type:"function",function:{name:"write_file",description:"Create a new file or completely overwrite an existing file. Example: use write_file for creating a new config file like .env.example, but NOT for changing one line in an existing file (use edit_file instead). For targeted changes to existing files, prefer edit_file or patch_file instead \u2014 they only send the diff and are safer. Only use write_file when creating new files or when the entire content needs to be replaced.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},content:{type:"string",description:"Full file content"}},required:["path","content"]}}},{type:"function",function:{name:"edit_file",description:"Replace specific text in a file. ALWAYS call read_file first to get the exact content \u2014 edit_file requires the EXACT text including whitespace, indentation, and newlines. Example: edit_file(path='src/config.js', old_text='debug: false', new_text='debug: true'). IMPORTANT: old_text must match byte-for-byte \u2014 even a single space or newline difference will cause failure. If the edit fails with 'old_text not found', re-read that region with line_start/line_end then retry. For multiple replacements in one file, prefer patch_file (atomic). For new files, use write_file instead.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},old_text:{type:"string",description:"Exact text to find (must match file content precisely)"},new_text:{type:"string",description:"Replacement text"}},required:["path","old_text","new_text"]}}},{type:"function",function:{name:"list_directory",description:"List files and directories in a tree view. Use this to understand project structure. Example: use list_directory to see the overall layout of the src/ directory, but NOT for finding all .js files (use glob instead). For finding specific files by pattern, prefer glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory path"},max_depth:{type:"number",description:"Max depth (default: 2)"},pattern:{type:"string",description:"File filter glob (e.g. '*.js')"}},required:["path"]}}},{type:"function",function:{name:"search_files",description:"Search for a text pattern across files (regex). Returns matching lines with file paths. Example: use search_files for finding all occurrences of 'error' in .js files, but NOT for finding all .js files (use glob instead). For simple content search, grep is equivalent. For finding files by name, use glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory to search"},pattern:{type:"string",description:"Search pattern (regex)"},file_pattern:{type:"string",description:"File filter (e.g. '*.js')"}},required:["path","pattern"]}}},{type:"function",function:{name:"glob",description:"Find files matching a glob pattern by name or extension. Returns paths sorted by modification time. ALWAYS use this to locate files BEFORE reading them \u2014 never guess file paths. Example: glob(pattern='src/**/*.test.js') finds all test files in src directory. DO NOT use for content search (e.g. finding 'error' in files) \u2014 use grep tool instead. Examples: '**/*.test.js' (all test files), 'src/**/*.ts' (all TypeScript in src), 'package.json' (find config). Prefer this over bash find/ls. When you need file contents, glob first to get the exact path, then read_file to read it.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Glob pattern (e.g. '**/*.ts', 'src/**/*.test.js')"},path:{type:"string",description:"Base directory (default: project root)"}},required:["pattern"]}}},{type:"function",function:{name:"grep",description:"Search file CONTENTS with regex \u2014 use this when you need to find text inside files. Example: grep(pattern='callStream') finds files containing the text 'callStream'. Do NOT use glob for this \u2014 glob finds files by NAME pattern, grep searches file CONTENTS. Use output_mode='files_with_matches' for just file paths, output_mode='content' (default) for matching lines. Optionally use include to filter by file type (e.g. '*.js') but OMIT it when first searching \u2014 code may live in .html, .vue, .py or other unexpected file types. Supports context lines, offset pagination, and multiline patterns.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Regex pattern to search for"},path:{type:"string",description:"Directory or file to search (default: project root)"},include:{type:"string",description:"File filter glob (e.g. '*.js', '*.ts')"},ignore_case:{type:"boolean",description:"Case-insensitive search"},output_mode:{type:"string",enum:["content","files_with_matches","count"],description:"Output mode: content (matching lines), files_with_matches (file paths only), count (match counts). Default: content"},context:{type:"number",description:"Lines of context around each match (like grep -C)"},before_context:{type:"number",description:"Lines before each match (like grep -B)"},after_context:{type:"number",description:"Lines after each match (like grep -A)"},head_limit:{type:"number",description:"Limit output to first N results"},offset:{type:"number",description:"Skip first N results"},type:{type:"string",description:"File type filter (e.g. 'js', 'py', 'ts') \u2014 maps to --include='*.ext'"},multiline:{type:"boolean",description:"Enable multiline matching (grep -Pz)"},staged:{type:"boolean",description:"Search only staged content (git diff --cached). Default: false"}},required:["pattern"]}}},{type:"function",function:{name:"patch_file",description:"Apply multiple text replacements to a file atomically. All patches are validated before any are applied \u2014 if one fails, none are written. Example: when changing 3 different variables in the same function, use patch_file with an array of 3 { old_text, new_text } objects instead of 3 separate edit_file calls. This ensures either all changes are applied or none are, preventing partial edits. Like edit_file, all old_text values must match exactly.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},patches:{type:"array",description:"Array of { old_text, new_text } replacements to apply in order",items:{type:"object",properties:{old_text:{type:"string",description:"Text to find"},new_text:{type:"string",description:"Replacement text"}},required:["old_text","new_text"]}}},required:["path","patches"]}}},{type:"function",function:{name:"web_fetch",description:"Fetch content from a URL and return text. HTML tags are stripped. Use for reading documentation, API responses, or web pages. Will not work with authenticated/private URLs.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to fetch"},max_length:{type:"number",description:"Max response length in chars (default: 10000)"}},required:["url"]}}},{type:"function",function:{name:"web_search",description:"Search the web. Uses Perplexity (grounded, AI-summarized) if PERPLEXITY_API_KEY is set, otherwise DuckDuckGo. Returns titles, URLs, and summaries. Use to find documentation, solutions, or current information beyond your knowledge cutoff.",parameters:{type:"object",properties:{query:{type:"string",description:"Search query"},max_results:{type:"number",description:"Max results (default: 5)"}},required:["query"]}}},{type:"function",function:{name:"browser_open",description:"Open a URL in a headless browser and return the page title, text content, and links. More reliable than web_fetch for JavaScript-heavy pages. Requires playwright (npm install playwright && npx playwright install chromium).",parameters:{type:"object",properties:{url:{type:"string",description:"URL to open"},wait_for:{type:"string",enum:["domcontentloaded","networkidle","load"],description:"When to consider page loaded (default: domcontentloaded)"}},required:["url"]}}},{type:"function",function:{name:"browser_screenshot",description:"Take a screenshot of a URL in a headless browser. Returns the screenshot file path. The path can be pasted into the next message for visual analysis. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot"},full_page:{type:"boolean",description:"Capture full page (default: false \u2014 viewport only)"},width:{type:"number",description:"Viewport width in px (default: 1280)"},height:{type:"number",description:"Viewport height in px (default: 800)"}},required:["url"]}}},{type:"function",function:{name:"visual_review",description:"Screenshot a URL, analyze the visual result, and return structured feedback about layout, design, and usability issues. Use this to visually inspect web pages, check CSS changes, or verify UI fixes. Returns the screenshot path + analysis.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot and analyze"},focus:{type:"string",description:"What to focus on: layout, colors, typography, spacing, responsiveness, accessibility, or a custom description (e.g. 'check the navbar alignment')"},width:{type:"number",description:"Viewport width in px (default: 1280)"},height:{type:"number",description:"Viewport height in px (default: 800)"},full_page:{type:"boolean",description:"Capture full scrollable page (default: false)"},compare_with:{type:"string",description:"Path to a previous screenshot to compare against (optional). Enables before/after analysis."}},required:["url"]}}},{type:"function",function:{name:"clipboard_image",description:"Grab the current image from the system clipboard (macOS). Returns the screenshot path for visual analysis. Use when the user says 'clipboard', 'pasteboard', or wants to analyze a copied screenshot.",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"browser_click",description:"Click an element on a web page (by CSS selector or visible text). Returns the new URL after navigation. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of element to click (mutually exclusive with text)"},text:{type:"string",description:"Visible text of element to click (mutually exclusive with selector)"}},required:["url"]}}},{type:"function",function:{name:"browser_fill",description:"Fill a form field on a web page and optionally submit. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of the input field"},value:{type:"string",description:"Value to fill in"},submit:{type:"boolean",description:"Press Enter to submit after filling (default: false)"}},required:["url","selector","value"]}}},{type:"function",function:{name:"visual_diff",description:"Compare two screenshots pixel-by-pixel and compute a visual diff. Returns the percentage of changed pixels and which screen regions (top-left, center, bottom-right, etc.) were affected. Use after making CSS/HTML changes to quantify what changed. Example: take a before screenshot, make changes, take an after screenshot, then visual_diff both paths.",parameters:{type:"object",properties:{before:{type:"string",description:"Path to the 'before' screenshot (PNG)"},after:{type:"string",description:"Path to the 'after' screenshot (PNG)"},threshold:{type:"number",description:"Color distance threshold 0-1 (default: 0.1). Lower = more sensitive."}},required:["before","after"]}}},{type:"function",function:{name:"responsive_sweep",description:"Screenshot a URL at 5 viewport widths (320, 768, 1024, 1440, 1920) and return all screenshots for breakpoint analysis. Quickly identifies responsive layout issues across mobile, tablet, and desktop. Returns images for visual analysis.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot at each viewport"},viewports:{type:"array",items:{type:"object",properties:{width:{type:"number"},label:{type:"string"}}},description:"Custom viewport list (default: 320/768/1024/1440/1920)"},full_page:{type:"boolean",description:"Capture full scrollable page at each viewport (default: false)"}},required:["url"]}}},{type:"function",function:{name:"visual_annotate",description:"Draw annotations (red boxes, arrows, circles) directly on a screenshot to mark problem areas. Returns the annotated image. Use instead of describing locations verbally \u2014 visual markers are unambiguous.",parameters:{type:"object",properties:{image:{type:"string",description:"Path to the screenshot (PNG) to annotate"},annotations:{type:"array",items:{type:"object",properties:{type:{type:"string",description:"box, arrow, or circle"},x:{type:"number",description:"X position (px)"},y:{type:"number",description:"Y position (px)"},width:{type:"number",description:"Width for box (px)"},height:{type:"number",description:"Height for box (px)"},toX:{type:"number",description:"Arrow end X (px)"},toY:{type:"number",description:"Arrow end Y (px)"},radius:{type:"number",description:"Circle radius (px)"},label:{type:"string",description:"Text label for the annotation"},color:{type:"string",description:"Hex color (default: #FF0000)"}},required:["type","x","y"]},description:"List of annotations to draw"}},required:["image","annotations"]}}},{type:"function",function:{name:"visual_watch",description:"Hot-reload visual feedback loop: watches source files for changes, waits for HMR to settle, takes a new screenshot, diffs it against the previous one, and reports what changed. Runs up to N iterations (default: 10). Requires a running dev server (Vite, Next, etc.) and chokidar. Use for autonomous visual polish loops.",parameters:{type:"object",properties:{url:{type:"string",description:"Dev server URL to screenshot (e.g. http://localhost:5173)"},watch:{type:"array",items:{type:"string"},description:"File paths or directories to watch for changes (e.g. ['src/components', 'src/styles'])"},max_iterations:{type:"number",description:"Max number of change\u2192screenshot\u2192diff cycles (default: 10)"},hmr_delay:{type:"number",description:"Milliseconds to wait after file change for HMR to settle (default: 1500)"}},required:["url","watch"]}}},{type:"function",function:{name:"design_tokens",description:"Extract design tokens from a screenshot: dominant colors (with hex/rgb/frequency/category), detected vertical spacing values, and image dimensions. Use to audit visual consistency, compare against a design system, or reverse-engineer CSS variables from a rendered page.",parameters:{type:"object",properties:{image:{type:"string",description:"Path to screenshot (PNG) to analyze"},sample_rate:{type:"number",description:"Pixel sampling interval \u2014 lower = more accurate but slower (default: 4)"}},required:["image"]}}},{type:"function",function:{name:"design_compare",description:"Compare a live web page against a reference design (Figma export, mockup PNG). Screenshots the URL at the reference image's dimensions, computes pixel-level diff, and returns annotated images highlighting deviations. Use to verify implementation matches the design spec.",parameters:{type:"object",properties:{url:{type:"string",description:"Live URL to compare against the reference"},reference:{type:"string",description:"Path to reference design image (PNG)"},width:{type:"number",description:"Override viewport width (default: match reference image width)"},height:{type:"number",description:"Override viewport height (default: 800)"},threshold:{type:"number",description:"Color distance threshold 0-1 (default: 0.1)"}},required:["url","reference"]}}},{type:"function",function:{name:"ask_user",description:"Ask the user a clarifying question with 2-3 specific options. Use when the user's intent is ambiguous. Always provide concrete, actionable options. The user can select an option or type a custom answer.",parameters:{type:"object",properties:{question:{type:"string",description:"The clarifying question to ask"},options:{type:"array",items:{type:"string"},description:"2-3 specific, actionable answer options for the user to choose from",minItems:1,maxItems:3}},required:["question","options"]}}},{type:"function",function:{name:"git_status",description:"Get git status: current branch, changed files, staged/unstaged state. Use before git operations to understand the current state.",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"git_diff",description:"Get git diff for changed files. Shows additions and deletions.",parameters:{type:"object",properties:{staged:{type:"boolean",description:"Show only staged changes (default: false)"},file:{type:"string",description:"Diff specific file only (optional)"}},required:[]}}},{type:"function",function:{name:"git_log",description:"Show recent git commits (short format).",parameters:{type:"object",properties:{count:{type:"number",description:"Number of commits to show (default: 10)"},file:{type:"string",description:"Show commits for specific file (optional)"}},required:[]}}},{type:"function",function:{name:"task_list",description:"Create and manage a task list for complex multi-step tasks. Use for tasks with 3+ steps to track progress. Actions: create (new list with tasks), update (mark task in_progress/done/failed), get (view current list). Always update task status as you work.",parameters:{type:"object",properties:{action:{type:"string",enum:["create","update","get"],description:"Action to perform"},name:{type:"string",description:"Task list name (for create)"},tasks:{type:"array",description:"Array of tasks to create (for create)",items:{type:"object",properties:{description:{type:"string",description:"Task description"},depends_on:{type:"array",items:{type:"string"},description:"IDs of prerequisite tasks"}},required:["description"]}},task_id:{type:"string",description:"Task ID to update (for update)"},status:{type:"string",enum:["in_progress","done","failed"],description:"New status (for update)"},result:{type:"string",description:"Result summary (for update, optional)"}},required:["action"]}}},{type:"function",function:{name:"gh_run_list",description:"List recent GitHub Actions workflow runs for this repository. Shows run status, conclusion, branch, and timing. Use to check CI/CD status or find a run ID.",parameters:{type:"object",properties:{limit:{type:"number",description:"Number of runs to show (default: 10, max: 30)"},workflow:{type:"string",description:"Filter by workflow name or filename (optional)"},branch:{type:"string",description:"Filter by branch name (optional)"},status:{type:"string",enum:["completed","in_progress","queued","failure","success"],description:"Filter by status (optional)"}},required:[]}}},{type:"function",function:{name:"gh_run_view",description:"View details of a specific GitHub Actions workflow run: steps, logs, errors. Use gh_run_list first to get the run ID.",parameters:{type:"object",properties:{run_id:{type:"string",description:"The run ID (from gh_run_list)"},log:{type:"boolean",description:"Include full log output (default: false \u2014 shows step summary only)"}},required:["run_id"]}}},{type:"function",function:{name:"gh_workflow_trigger",description:"Trigger a GitHub Actions workflow dispatch event. Only works for workflows with workflow_dispatch trigger. Requires user confirmation.",parameters:{type:"object",properties:{workflow:{type:"string",description:"Workflow filename (e.g. ci.yml) or name"},branch:{type:"string",description:"Branch to run on (default: current branch)"},inputs:{type:"object",description:"Workflow input parameters as key-value pairs (optional)"}},required:["workflow"]}}},{type:"function",function:{name:"spawn_agents",description:"Run multiple independent sub-agents in parallel (max 5 at top level, max 2 when called from within a sub-agent). Each agent has its own conversation context. Use when 2+ tasks can run simultaneously \u2014 e.g. reading multiple files, analyzing separate modules, independent research. Do NOT use for tasks that depend on each other or modify the same file. Keep task descriptions specific and self-contained. SWARM PATTERN: Sub-agents can call spawn_agents once (max nesting depth 2) to enable Architect\u2192Coder\u2192Reviewer pipelines: a coder agent spawns 1-2 reviewer agents that validate and fix its own output before returning results to the parent.",parameters:{type:"object",properties:{agents:{type:"array",description:"Array of agent definitions to run in parallel (max 5)",items:{type:"object",properties:{task:{type:"string",description:"Task description for the agent"},context:{type:"string",description:"Additional context (optional)"},max_iterations:{type:"number",description:"Max iterations (default: 10, max: 15)"},model:{type:"string",description:'Override model for this agent (provider:model, e.g. "anthropic:claude-haiku"). Auto-selected if omitted.'},background:{type:"boolean",description:"Run this agent non-blocking in the background. The main session continues immediately; results are injected as [BACKGROUND AGENT COMPLETED] user messages when the agent finishes. Use for tasks that can run in parallel to your main work."}},required:["task"]}}},required:["agents"]}}},{type:"function",function:{name:"switch_model",description:"Switch the active AI model mid-conversation. Use when a different model is better for the next steps \u2014 e.g. switch to a fast model for simple lookups, or a more capable model for complex refactoring. The switch persists for all subsequent turns.",parameters:{type:"object",properties:{model:{type:"string",description:'Model spec: "provider:model" (e.g. "ollama:devstral-small-2:24b") or just model name'}},required:["model"]}}},{type:"function",function:{name:"k8s_pods",description:"List Kubernetes pods. Shows pod name, status, restarts, and age. Runs kubectl locally or via SSH on a remote server. Use namespace to filter, or omit for all namespaces.",parameters:{type:"object",properties:{namespace:{type:"string",description:"Namespace to list pods in (default: all namespaces)"},label:{type:"string",description:'Label selector filter (e.g. "app=nginx")'},context:{type:"string",description:"kubectl context to use (optional)"},server:{type:"string",description:"Remote server as user@host to run kubectl via SSH (optional, local kubectl if omitted)"}},required:[]}}},{type:"function",function:{name:"k8s_logs",description:'Fetch logs from a Kubernetes pod. Use tail to limit output, since for time-based filtering (e.g. "1h", "30m").',parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (required if pod has multiple containers)"},tail:{type:"number",description:"Number of recent lines to show (default: 100)"},since:{type:"string",description:'Show logs since duration (e.g. "1h", "30m", "5s")'},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod"]}}},{type:"function",function:{name:"k8s_exec",description:"Execute a command inside a running Kubernetes pod (kubectl exec). Requires user confirmation. Use for inspecting container state, reading configs, or debugging.",parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},command:{type:"string",description:'Command to run in the pod (e.g. "env", "ls /app", "cat /etc/config.yaml")'},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (optional)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod","command"]}}},{type:"function",function:{name:"k8s_apply",description:"Apply a Kubernetes manifest file (kubectl apply -f). Requires confirmation before applying to the cluster. Use dry_run=true to validate without applying.",parameters:{type:"object",properties:{file:{type:"string",description:"Path to manifest YAML file (relative or absolute)"},namespace:{type:"string",description:"Override namespace (optional)"},dry_run:{type:"boolean",description:"Validate only without applying (default: false)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["file"]}}},{type:"function",function:{name:"k8s_rollout",description:"Manage Kubernetes deployment rollouts: check status, restart (rolling update), view history, or undo (rollback). Restart and undo require confirmation.",parameters:{type:"object",properties:{action:{type:"string",enum:["status","restart","history","undo"],description:"Action: status (check rollout progress), restart (rolling restart), history (show revision history), undo (rollback to previous revision)"},deployment:{type:"string",description:"Deployment name"},namespace:{type:"string",description:"Namespace (default: default)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["action","deployment"]}}},{type:"function",function:{name:"brain_write",description:"Write or update a knowledge document in the project brain (.nex/brain/). Use this to persist important findings, architecture decisions, debugging insights, or conventions discovered during the session. The user can review changes via /brain review or git diff.",parameters:{type:"object",properties:{name:{type:"string",description:'Document name (without .md extension). Use kebab-case. Examples: "api-auth-flow", "db-schema-notes", "deployment-checklist"'},content:{type:"string",description:"Full Markdown content. Use headings (#), lists (-), and code blocks. Include optional YAML frontmatter with tags."},mode:{type:"string",enum:["create","update","append"],description:"create: new document (fails if exists). update: overwrite existing. append: add to end of existing document."}},required:["name","content","mode"]}}},{type:"function",function:{name:"ssh_exec",description:'Execute a command on a remote server via SSH. Server is a profile name from .nex/servers.json (e.g. "prod") or "user@host". Use for: checking status, reading logs, running deployments. Destructive commands (restart, delete, modify config) require confirmation. For service management prefer service_manage; for logs prefer service_logs.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name (from .nex/servers.json) or "user@host"'},command:{type:"string",description:"Shell command to run on the remote server"},sudo:{type:"boolean",description:"Run command with sudo (only if profile has sudo:true). Default: false"},timeout:{type:"number",description:"Timeout in seconds. Default: 30"}},required:["server","command"]}}},{type:"function",function:{name:"ssh_upload",description:"Upload a local file or directory to a remote server via SCP. Recursive for directories. Requires confirmation before upload.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},local_path:{type:"string",description:"Local path to upload (file or directory)"},remote_path:{type:"string",description:"Destination path on the remote server (absolute preferred)"}},required:["server","local_path","remote_path"]}}},{type:"function",function:{name:"ssh_download",description:"Download a file or directory from a remote server via SCP. Recursive for directories.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},remote_path:{type:"string",description:"Path on the remote server to download"},local_path:{type:"string",description:"Local destination path"}},required:["server","remote_path","local_path"]}}},{type:"function",function:{name:"remote_agent",description:'Delegate a coding task to nex-code running on a remote server. Use this when the task involves server-side projects (musikschule, stadtkapelle, cahill, schoensgibl) that live on almalinux9. Runs nex-code --auto on the server and streams output. Server is a profile name from .nex/servers.json or "user@host".',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name from .nex/servers.json (e.g. "almalinux9") or "user@host"'},task:{type:"string",description:"The full task description to run on the remote nex-code"},project_path:{type:"string",description:"Working directory on the remote server (e.g. /home/deploy/app). Defaults to home directory."},model:{type:"string",description:"Model to use on remote nex-code (e.g. qwen3-coder:480b). Defaults to server default."}},required:["server","task"]}}},{type:"function",function:{name:"service_manage",description:"Manage a systemd service on a remote (or local) server. Uses systemctl. Status is read-only; start/stop/restart/reload/enable/disable require confirmation. For AlmaLinux 9: runs via SSH with sudo if configured.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn", "postgresql")'},action:{type:"string",enum:["status","start","stop","restart","reload","enable","disable"],description:"systemctl action to perform"}},required:["service","action"]}}},{type:"function",function:{name:"service_logs",description:"Fetch systemd service logs via journalctl. Works on AlmaLinux 9 and any systemd Linux. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn")'},lines:{type:"number",description:"Number of recent log lines to fetch. Default: 50"},since:{type:"string",description:'Time filter, e.g. "1 hour ago", "today", "2024-01-01 12:00". Optional.'},follow:{type:"boolean",description:"Tail logs in real-time (follow mode). Default: false"}},required:["service"]}}},{type:"function",function:{name:"container_list",description:"List Docker containers on a server (or locally). Shows container ID, name, image, status, and ports. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},all:{type:"boolean",description:"Show all containers including stopped ones. Default: false (running only)."}},required:[]}}},{type:"function",function:{name:"container_logs",description:"Fetch logs from a Docker container on a server (or locally). Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},lines:{type:"number",description:"Number of recent log lines. Default: 50."},since:{type:"string",description:'Time filter, e.g. "1h", "30m", "2024-01-01T12:00:00". Optional.'}},required:["container"]}}},{type:"function",function:{name:"container_exec",description:"Execute a command inside a running Docker container. Destructive or state-changing commands require confirmation.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},command:{type:"string",description:'Command to run inside the container (e.g. "cat /etc/nginx/nginx.conf").'}},required:["container","command"]}}},{type:"function",function:{name:"container_manage",description:'Start, stop, restart, or remove a Docker container. All actions except "inspect" require confirmation.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},action:{type:"string",enum:["start","stop","restart","remove","inspect"],description:"Action to perform on the container."}},required:["container","action"]}}},{type:"function",function:{name:"frontend_recon",description:"MANDATORY first step before creating or significantly modifying any frontend file (HTML template, Vue/React component, CSS). Scans the project and returns: (1) design tokens \u2014 CSS variables, Tailwind theme colors/fonts, (2) main layout/index page structure, (3) a reference component of the same type, (4) detected JS/CSS framework stack. Call this BEFORE writing any markup or styles. Never skip it for frontend tasks.",parameters:{type:"object",properties:{type:{type:"string",description:'Type of frontend file you are about to create. Used to find a relevant reference component. Examples: "list", "form", "detail", "dashboard", "modal", "component". Optional but improves reference quality.'}},required:[]}}},{type:"function",function:{name:"deploy",description:'Deploy to a remote server. Supports two methods: "rsync" (sync local files) and "git" (git pull on remote). Can use a named config from .nex/deploy.json. Requires confirmation before executing.',parameters:{type:"object",properties:{config:{type:"string",description:'Named deploy config from .nex/deploy.json (e.g. "prod"). Overrides all other params if provided.'},method:{type:"string",enum:["rsync","git"],description:'Deploy method: "rsync" syncs local files (default), "git" runs git pull on the remote.'},server:{type:"string",description:'Profile name or "user@host". Required if no config.'},remote_path:{type:"string",description:"Remote project directory. Required for git method; destination path for rsync."},local_path:{type:"string",description:"Local directory or file to sync. Required for rsync method."},branch:{type:"string",description:"Branch to pull (git method only). Defaults to current remote branch."},deploy_script:{type:"string",description:'Shell command(s) to run on the remote after sync/pull (e.g. "npm ci && systemctl restart myapp"). Optional.'},health_check:{type:"string",description:"URL (HTTP GET) or shell command to verify the service is healthy after deploy. If it fails, the deploy is marked as failed. Optional."},exclude:{type:"array",items:{type:"string"},description:"Paths to exclude from rsync. Optional."},dry_run:{type:"boolean",description:"Show what would happen without executing. Default: false."}},required:[]}}},{type:"function",function:{name:"deployment_status",description:"Check deployment status across all configured servers. Reads .nex/deploy.json configs and checks service health on each server. Returns a status summary table.",parameters:{type:"object",properties:{config:{type:"string",description:"Specific deploy config name to check (optional \u2014 checks all if omitted)"}},required:[]}}},{type:"function",function:{name:"sysadmin",description:"Senior sysadmin operations on a remote (or local) Linux server. Covers: system audit, disk_usage, process_list, network_status, package management (dnf/apt), user management, firewall (firewalld/ufw/iptables), cron, SSL cert checks, log tailing, large file discovery, systemd service management, process kill, journalctl log querying. Read-only actions run without confirmation; state-changing actions require user approval.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},action:{type:"string",enum:["audit","disk_usage","process_list","network_status","package","user_manage","firewall","cron","ssl_check","log_tail","find_large","service","kill_process","journalctl"],description:"Sysadmin operation. audit=full health overview; disk_usage=df+du; process_list=top procs; network_status=open ports; package=dnf/apt (package_action: check|list|install|remove|update|upgrade); user_manage=users/keys; firewall=rules; cron=crontab; ssl_check=cert expiry+days; log_tail=tail any log; find_large=big files; service=systemd unit management; kill_process=kill by PID or name; journalctl=query system journal."},path:{type:"string",description:"File or directory path. For disk_usage (default /), log_tail (required), find_large (default /)."},lines:{type:"number",description:"Lines to tail for log_tail or journalctl. Default: 100."},limit:{type:"number",description:"Result count for process_list (default 20) or find_large (default 20)."},sort_by:{type:"string",enum:["cpu","mem"],description:"Sort order for process_list. Default: cpu."},min_size:{type:"string",description:'Minimum file size for find_large. Default: "100M". Examples: "50M", "1G".'},package_action:{type:"string",enum:["install","remove","update","list","upgrade"],description:"Package sub-action for action=package."},packages:{type:"array",items:{type:"string"},description:"Package name(s) for install/remove/update."},user_action:{type:"string",enum:["list","create","delete","add_ssh_key","info"],description:"User sub-action for action=user_manage."},user:{type:"string",description:"Linux username for user_manage or cron."},groups:{type:"array",items:{type:"string"},description:'Groups to assign on user create (e.g. ["sudo", "docker"]).'},ssh_key:{type:"string",description:"SSH public key string to add for user_action=add_ssh_key."},firewall_action:{type:"string",enum:["status","allow","deny","remove","reload"],description:"Firewall sub-action for action=firewall."},port:{type:"string",description:'Port/protocol for firewall rules, e.g. "80/tcp", "443", "8080/udp".'},cron_action:{type:"string",enum:["list","add","remove"],description:"Cron sub-action for action=cron."},schedule:{type:"string",description:'Cron schedule expression for cron add, e.g. "0 2 * * *".'},command:{type:"string",description:"Command for cron add, or substring to match for cron remove."},domain:{type:"string",description:`Domain for ssl_check (e.g. "example.com"). Auto-detects Let's Encrypt cert on server; falls back to live TLS probe.`},cert_path:{type:"string",description:'Explicit path to cert file on server for ssl_check (e.g. "/etc/letsencrypt/live/x/cert.pem").'},service_name:{type:"string",description:'Systemd unit name for action=service (e.g. "nginx", "my-api", "gunicorn"). .service suffix optional.'},service_action:{type:"string",enum:["status","start","stop","restart","reload","enable","disable","list_failed"],description:"Sub-action for action=service. list_failed shows all failed units."},pid:{type:"number",description:"Process ID to kill for action=kill_process."},process_name:{type:"string",description:"Process name to kill (uses pkill) for action=kill_process. Use with pid for safety."},signal:{type:"string",enum:["SIGTERM","SIGKILL","SIGHUP","SIGINT"],description:"Signal for kill_process. Default: SIGTERM."},unit:{type:"string",description:'Systemd unit to filter for journalctl (e.g. "nginx", "my-api"). Omit for system-wide.'},since:{type:"string",description:'Time filter for journalctl, e.g. "1 hour ago", "today", "2026-03-17 10:00". Default: last 200 lines.'},priority:{type:"string",enum:["emerg","alert","crit","err","warning","notice","info","debug"],description:"Minimum log priority for journalctl. Default: no filter."}},required:["action"]}}},{type:"function",function:{name:"save_memory",description:"Save a typed memory for cross-session persistence. Use this to remember user preferences, feedback, project context, or external references.",parameters:{type:"object",properties:{type:{type:"string",enum:["user","feedback","project","reference"],description:"Memory type: user (role/prefs), feedback (approach guidance), project (ongoing work), reference (external pointers)"},name:{type:"string",description:"Short slug identifier for this memory (e.g. 'testing-preference', 'deploy-workflow')"},content:{type:"string",description:"Markdown content of the memory"},description:{type:"string",description:"One-line description for the memory index (optional, defaults to first line of content)"}},required:["type","name","content"]}}},{type:"function",function:{name:"delete_memory",description:"Delete a typed memory entry. Use this to prune outdated or incorrect memories.",parameters:{type:"object",properties:{type:{type:"string",enum:["user","feedback","project","reference"],description:"Memory type to delete from"},name:{type:"string",description:"Slug identifier of the memory to delete"}},required:["type","name"]}}}];function Yo(t,{server:e,context:s}={}){let n=e?e.replace(/[^a-zA-Z0-9@._-]/g,""):null,o=s?s.replace(/[^a-zA-Z0-9._/-]/g,""):null,r="kubectl";if(o&&(r+=` --context ${o}`),r+=` ${t}`,n){let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`ssh -o ConnectTimeout=10 -o BatchMode=yes ${n} "${i}"`}return r}async function Dm(t,e,s={}){switch(t){case"bash":{let n=e.command,o=AS(n);if(o){let d=JS(n);return`BLOCKED: Command matches forbidden pattern: ${o}${d?`
|
|
296
|
+
HINT: ${d}`:""}`}let r=MS(n);if(r)return`BLOCKED: Destructive operation on protected path: ${r}
|
|
297
|
+
HINT: Protected files (.env, credentials, venv, .ssh, etc.) cannot be deleted or moved via bash. Override with NEX_UNPROTECT=1 if intentional.`;if(s.autoConfirm?Rm(n):NS(n)){let d=Rm(n)?"\u26D4":"\u26A0";if(!await Kt(` ${d} bash: \`${n}\``,{toolName:"bash"}))return"CANCELLED: User declined to execute this command."}let a;try{a=process.cwd(),Xt.accessSync(a)}catch{a=require("os").homedir(),s.silent||console.log(`${ae.yellow} \u26A0 Working directory no longer exists \u2014 running in ${a}${ae.reset}`)}let c=zS.test(n.trim())&&!KS.test(n.trim());if(GS.test(n.trim())||c){s.silent||console.log(`${ae.dim} \u25B6 interactive: ${n}${ae.reset}`);let d=CS("sh",["-c",n],{stdio:"inherit",cwd:a});return d.error?`ERROR: ${d.error.message}`:d.status===0?"(interactive command completed successfully)":`(interactive command exited with code ${d.status})`}let{ToolProgress:l}=Rs(),u=s.silent?null:new l("bash",n.substring(0,40));u&&u.start();try{let{stdout:d,stderr:f}=await Be(n,{cwd:a,timeout:9e4,maxBuffer:5242880});return u&&u.stop(),d||f||"(no output)"}catch(d){u&&u.stop();let f=(d.stderr||d.stdout||d.message||"").toString().substring(0,5e3),p=Um(f,n);return`EXIT ${d.code||1}
|
|
298
|
+
${p}`}}case"read_file":{let n=rt(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await Rt(n)){let A=await Oi(e.path);if(A.fixedPath)n=A.fixedPath,console.log(`${ae.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ue.relative(process.cwd(),n)}${ae.reset}`);else return`ERROR: File not found: ${e.path}${A.message?`
|
|
299
|
+
`+A.message:""}`}let r=Buffer.alloc(8192),i=await Xt.promises.open(n,"r"),{bytesRead:a}=await i.read(r,0,8192,0);await i.close();for(let A=0;A<a;A++)if(r[A]===0)return`ERROR: ${n} is a binary file (not readable as text)`;let c=await Ye.readFile(n,"utf-8");if(!c&&(await Ye.stat(n)).size>0)return`WARNING: ${n} is empty or unreadable`;let l=c.split(`
|
|
300
|
+
`),u=await Ye.stat(n),d=l.length,f=350,p=!e.line_start&&!e.line_end,h=p&&d>f,g=(e.line_start||1)-1,w=h?f:e.line_end||l.length,x=ue.relative(process.cwd(),n),O=h?`showing lines 1-${f} of ${d}`:e.line_start||e.line_end?`lines ${g+1}-${w} of ${d}`:`${d} lines`,I=`File: ${x} (${O}, ${u.size} bytes)`,E=l.slice(g,w).map((A,te)=>`${g+te+1}: ${A}`).join(`
|
|
301
|
+
`),v=h?`
|
|
302
|
+
|
|
303
|
+
[\u{1F6A8} FILE TRUNCATED: You are only seeing lines 1-${f} of ${d} 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=${f+1}), or use grep_search to find specific keywords.]`:!p&&d>w?`
|
|
304
|
+
|
|
305
|
+
[\u{1F6A8} FILE CONTINUES: This is only lines ${g+1} to ${w} of ${d} total. The rest is HIDDEN. Use line_start=${w+1} to read the next section, or grep_search for keywords.]`:"";return`${I}
|
|
306
|
+
${E}${v}`}case"write_file":{await gl();let n=rt(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let o=await Rt(n),r=null;if(s.autoConfirm)o&&(r=await Ye.readFile(n,"utf-8"));else if(o){r=await Ye.readFile(n,"utf-8");let u=await Uo(n,e.content);if(Ri(n,r,e.content,{annotations:u}),!await Bo("Overwrite"))return"CANCELLED: User declined to overwrite file."}else{let u=await Uo(n,e.content);if(PS(n,e.content,{annotations:u}),!await Bo("Create"))return"CANCELLED: User declined to create file."}let i=ue.dirname(n);await Rt(i)||await Ye.mkdir(i,{recursive:!0}),await Ye.writeFile(n,e.content,"utf-8");let c=/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||e.content.startsWith("#!");c&&await Ye.chmod(n,493),Ci("write_file",n,r,e.content);let l=c?" [chmod +x applied]":"";return`Written: ${n} (${e.content.length} chars)${l}`}case"edit_file":{await gl();let n=rt(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await Rt(n)){let u=await Oi(e.path);if(u.fixedPath)n=u.fixedPath,console.log(`${ae.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ue.relative(process.cwd(),n)}${ae.reset}`);else return`ERROR: File not found: ${e.path}${u.message?`
|
|
307
|
+
`+u.message:""}`}let r=await Ye.readFile(n,"utf-8"),i=e.old_text,a=!1,c=!1;if(!r.includes(e.old_text)){let{getActiveModelId:u,getActiveProviderName:d}=st();if(Pm(u(),d())==="strict"){let h=Go(r,e.old_text);return h?`ERROR: old_text not found in ${n} (strict mode \u2014 exact match required)
|
|
308
|
+
Most similar text (line ${h.line}, distance ${h.distance}):
|
|
309
|
+
${h.text}`:`ERROR: old_text not found in ${n} (strict mode \u2014 exact match required)`}let p=Am(r,e.old_text);if(p)i=p,a=!0,console.log(`${ae.dim} \u2713 fuzzy whitespace match applied${ae.reset}`);else{let h=Wm(r,e.old_text,e.new_text);if(h){if(!s.autoConfirm){let I=await Uo(n,h.content);if(Ri(n,r,h.content,{annotations:I}),!await Bo(`Apply (auto-fix, line ${h.line}, distance ${h.distance})`))return"CANCELLED: User declined to apply edit."}await Ye.writeFile(n,h.content,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||h.content.startsWith("#!"))&&await Ye.chmod(n,493),Ci("edit_file",n,r,h.content);let O=h.matchText.length>80?h.matchText.substring(0,77)+"...":h.matchText;return console.log(`${ae.dim} \u2713 auto-fixed edit: line ${h.line}, distance ${h.distance}${ae.reset}`),`Edited: ${n} (auto-fixed, line ${h.line}, distance ${h.distance}, matched: "${O}")`}let g=Go(r,e.old_text);if(g){let O=r.split(`
|
|
310
|
+
`),I=Math.max(0,g.line-6),E=Math.min(O.length,g.line+10),v=O.slice(I,E).map((te,oe)=>`${I+oe+1}: ${te}`).join(`
|
|
311
|
+
`),A=`line_start=${Math.max(1,g.line-5)} line_end=${Math.min(O.length,g.line+15)}`;return`ERROR: old_text not found in ${n} (most similar at line ${g.line}, distance ${g.distance})
|
|
306
312
|
|
|
307
313
|
Actual file content around line ${g.line} \u2014 use this to correct old_text:
|
|
308
|
-
${
|
|
314
|
+
${v}
|
|
309
315
|
|
|
310
|
-
Fix: update old_text to match the exact lines above, then retry. If you need more context: read_file with ${
|
|
311
|
-
`)[0].slice(0,60),
|
|
312
|
-
Recovery: grep -n "${
|
|
313
|
-
Recovery: use grep -n to locate the text, then re-read that section with line_start/line_end.`;return`ERROR: old_text not found in ${n}${
|
|
314
|
-
`)||"(empty)"}case"search_files":{let n=
|
|
315
|
-
`).
|
|
316
|
-
`)
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
`)
|
|
321
|
-
`).
|
|
322
|
-
`
|
|
323
|
-
`).trim()||"(no matches in staged files)"}let o=["-rn","-E","--null","-H"];e.ignore_case&&o.push("-i"),e.include&&o.push(`--include=${e.include}`),e.type&&o.push(`--include=*.${e.type}`);let r=20;e.context?o.push("-C",String(Math.min(Number(e.context),r))):(e.before_context&&o.push("-B",String(Math.min(Number(e.before_context),r))),e.after_context&&o.push("-A",String(Math.min(Number(e.after_context),r)))),e.output_mode==="files_with_matches"?o.push("-l"):e.output_mode==="count"&&o.push("-c"),o.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage"),o.push(e.pattern,n);let{ToolProgress:i}=ks(),a=new i("grep","Searching...");a.start();try{let{stdout:l}=await es("grep",o,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),c;if(e.output_mode==="files_with_matches"||e.output_mode==="count")c=l.trim().split(`
|
|
324
|
-
`).filter(p=>p.trim());else{let p=l.split("\0");c=[];for(let m=0;m<p.length;m+=2){let g=p[m],_=p[m+1];if(g&&_){let b=_.split(`
|
|
325
|
-
`).filter(A=>A.trim());for(let A of b)c.push(`${g}:${A}`)}}}let u=e.offset||0,d=e.head_limit||(e.output_mode==="files_with_matches"?200:100);return c=c.slice(u,u+d),a.update({count:c.length,detail:`in ${n}`}),a.stop(),c.join(`
|
|
326
|
-
`).trim()||"(no matches)"+sc(e.path)}catch(l){if(a.stop(),l.code===2){let c=(l.stderr||l.message||"").toString().trim();return c.includes("No such file or directory")?`ERROR: Directory not found: ${n}`:c.includes("Invalid")||c.includes("Unmatched")||c.includes("unterminated")||c.includes("unclosed")||c.includes("parse error")||c.includes("brackets")||c.includes("not balanced")?`ERROR: Invalid regex pattern: ${e.pattern}`:`ERROR: grep failed: ${c.slice(0,200)||"exit code 2"}`}return"(no matches)"+sc(e.path)}}case"patch_file":{await oc();let n=tt(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await St(n)){let b=await ki(e.path);if(b.fixedPath)n=b.fixedPath,console.log(`${le.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${me.relative(process.cwd(),n)}${le.reset}`);else return`ERROR: File not found: ${e.path}${b.message?`
|
|
327
|
-
`+b.message:""}`}let r=e.patches;if(!Array.isArray(r)||r.length===0)return"ERROR: No patches provided";let i=await Be.readFile(n,"utf-8"),{getActiveModelId:a,getActiveProviderName:l}=Qe(),c=hm(a(),l()),u=[],d=!1,f=!1;for(let b=0;b<r.length;b++){let{old_text:A,new_text:P}=r[b];if(i.includes(A))u.push({old_text:A,new_text:P});else if(c==="strict"){let v=Fo(i,A);return v?`ERROR: Patch ${b+1} old_text not found in ${n} (strict mode \u2014 exact match required)
|
|
328
|
-
Most similar text (line ${v.line}, distance ${v.distance}):
|
|
329
|
-
${v.text}`:`ERROR: Patch ${b+1} old_text not found in ${n} (strict mode \u2014 exact match required)`}else{let v=fm(i,A);if(v)u.push({old_text:v,new_text:P}),d=!0;else{let E=Fo(i,A);if(E){let O=Math.max(3,Math.ceil(A.length*.05));if(E.distance<=O)u.push({old_text:E.text,new_text:P}),f=!0;else return`ERROR: Patch ${b+1} old_text not found in ${n}
|
|
316
|
+
Fix: update old_text to match the exact lines above, then retry. If you need more context: read_file with ${A}`}let w=(e.old_text||"").trim().split(`
|
|
317
|
+
`)[0].slice(0,60),x=w?`
|
|
318
|
+
Recovery: grep -n "${w.replace(/"/g,'\\"')}" <file> to find the line, then re-read that section with line_start/line_end.`:`
|
|
319
|
+
Recovery: use grep -n to locate the text, then re-read that section with line_start/line_end.`;return`ERROR: old_text not found in ${n}${x}`}}if(!s.autoConfirm){let u=r.split(i).join(e.new_text),d=await Uo(n,u);if(Ri(n,r,u,{annotations:d}),!await Bo(a?"Apply (fuzzy match)":"Apply"))return"CANCELLED: User declined to apply edit."}let l=r.split(i).join(e.new_text);return await Ye.writeFile(n,l,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||l.startsWith("#!"))&&await Ye.chmod(n,493),Ci("edit_file",n,r,l),a?`Edited: ${n} (fuzzy match)`:`Edited: ${n}`}case"list_directory":{let n=rt(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await Rt(n)){let l=e.path.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),u=rt(l),d=await Rt(u);if(u&&d)n=u;else return`ERROR: Directory not found: ${e.path}`}let r=e.max_depth||2,i=null;if(e.pattern)try{let l=e.pattern.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");i=new RegExp(`^${l}$`)}catch{return`ERROR: Invalid pattern: ${e.pattern}`}let a=[],c=async(l,u,d)=>{if(u>r)return;let f;try{f=await Ye.readdir(l,{withFileTypes:!0})}catch{return}f=f.filter(p=>!p.name.startsWith(".")&&p.name!=="node_modules");for(let p of f){if(i&&!p.isDirectory()&&!i.test(p.name))continue;let h=p.isDirectory()?"/":"";a.push(`${d}${p.name}${h}`),p.isDirectory()&&await c(ue.join(l,p.name),u+1,d+" ")}};return await c(n,1,""),a.join(`
|
|
320
|
+
`)||"(empty)"}case"search_files":{let n=rt(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let o=["-rn","-H"];e.file_pattern&&o.push(`--include=${e.file_pattern}`),o.push(e.pattern,n);try{let{stdout:r}=await is("grep",o,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),i=Wo(r).slice(0,50);return(await ml(i,{query:e.pattern,basePath:n})).join(`
|
|
321
|
+
`)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let o=process.cwd(),r=e.path?rt(e.path):o,i=e.pattern,a=v=>{let A=v.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"(.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");return new RegExp(`^${A}$`)},c=a(i),l=i.split("/").pop(),u=a(l),{ToolProgress:d}=Rs(),f=new d("glob","Finding files...");f.start();let p=Om();US(r)||(await BS(r),p=Om());let h=p.filter(v=>c.test(v)||u.test(ue.basename(v))).map(v=>ue.join(r,v));if(h.length===0)return f.stop(),"(no matches)"+hl(e.path);let g=await Promise.all(h.slice(0,210).map(async v=>{try{let A=await Ye.stat(v);return{path:v,mtime:A.mtimeMs}}catch{return{path:v,mtime:0}}})),w=new Map(g.map(v=>[v.path,v.mtime])),x=await Fm(i,r),O=Bm(g.map(v=>v.path),{query:i,basePath:r,definitionScores:x,mtimeByPath:w}),I=h.length>200,E=O.slice(0,200).join(`
|
|
322
|
+
`);return f.update({count:h.length,detail:e.pattern}),f.stop(),I?`${E}
|
|
323
|
+
|
|
324
|
+
\u26A0 Results truncated at 200. Use a more specific pattern.`:E}case"grep":{let n=e.path?rt(e.path):process.cwd();if(e.staged){let{getDiff:c}=Kr(),l=await c(!0);if(!l.trim())return"(no staged changes)";let u=new Set,d=l.split(`
|
|
325
|
+
`);for(let w of d)if(w.startsWith("diff --git")){let x=w.match(/diff --git a\/(.+) b\/(.+)/);x&&u.add(x[2])}let f=["-rn","-E","-H","--exclude=*.md","--exclude=*.txt","--exclude=*.json","--exclude=*.yaml","--exclude=*.yml"];e.ignore_case&&f.push("-i"),e.include&&f.push(`--include=${e.include}`),e.type&&f.push(`--include=*.${e.type}`),e.context?f.push("-C",String(e.context)):(e.before_context&&f.push("-B",String(e.before_context)),e.after_context&&f.push("-A",String(e.after_context))),e.output_mode==="files_with_matches"?f.push("-l"):e.output_mode==="count"&&f.push("-c"),f.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage");let{ToolProgress:p}=Rs(),h=new p("grep","Searching staged content...");h.start();let g=[];for(let w of u)try{let x=ue.join(process.cwd(),w);if(await Rt(x)){let O=[...f];O.push(e.pattern,x);let{stdout:I}=await is("grep",O,{cwd:process.cwd(),timeout:3e4,maxBuffer:2*1024*1024});if(e.output_mode==="files_with_matches"||e.output_mode==="count"){let E=Wo(I,e.output_mode);g=g.concat(E)}else g=g.concat(Wo(I))}}catch{}return g=await ml(g,{query:e.pattern,basePath:process.cwd(),outputMode:e.output_mode}),h.update({count:g.length,detail:"in staged files"}),h.stop(),g.join(`
|
|
326
|
+
`).trim()||"(no matches in staged files)"}let o=["-rn","-E","-H"];e.ignore_case&&o.push("-i"),e.include&&o.push(`--include=${e.include}`),e.type&&o.push(`--include=*.${e.type}`);let r=20;e.context?o.push("-C",String(Math.min(Number(e.context),r))):(e.before_context&&o.push("-B",String(Math.min(Number(e.before_context),r))),e.after_context&&o.push("-A",String(Math.min(Number(e.after_context),r)))),e.output_mode==="files_with_matches"?o.push("-l"):e.output_mode==="count"&&o.push("-c"),o.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage"),o.push(e.pattern,n);let{ToolProgress:i}=Rs(),a=new i("grep","Searching...");a.start();try{let{stdout:c}=await is("grep",o,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),l;e.output_mode==="files_with_matches"||e.output_mode==="count"?l=Wo(c,e.output_mode):l=Wo(c);let u=e.offset||0,d=e.head_limit||(e.output_mode==="files_with_matches"?200:100);return l=await ml(l,{query:e.pattern,basePath:n,outputMode:e.output_mode}),l=l.slice(u,u+d),a.update({count:l.length,detail:`in ${n}`}),a.stop(),l.join(`
|
|
327
|
+
`).trim()||"(no matches)"+hl(e.path)}catch(c){if(a.stop(),c.code===2){let l=(c.stderr||c.message||"").toString().trim();return l.includes("No such file or directory")?`ERROR: Directory not found: ${n}`:l.includes("Invalid")||l.includes("Unmatched")||l.includes("unterminated")||l.includes("unclosed")||l.includes("parse error")||l.includes("brackets")||l.includes("not balanced")?`ERROR: Invalid regex pattern: ${e.pattern}`:`ERROR: grep failed: ${l.slice(0,200)||"exit code 2"}`}return"(no matches)"+hl(e.path)}}case"patch_file":{await gl();let n=rt(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await Rt(n)){let x=await Oi(e.path);if(x.fixedPath)n=x.fixedPath,console.log(`${ae.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ue.relative(process.cwd(),n)}${ae.reset}`);else return`ERROR: File not found: ${e.path}${x.message?`
|
|
328
|
+
`+x.message:""}`}let r=e.patches;if(!Array.isArray(r)||r.length===0)return"ERROR: No patches provided";let i=await Ye.readFile(n,"utf-8"),{getActiveModelId:a,getActiveProviderName:c}=st(),l=Pm(a(),c()),u=[],d=!1,f=!1;for(let x=0;x<r.length;x++){let{old_text:O,new_text:I}=r[x];if(i.includes(O))u.push({old_text:O,new_text:I});else if(l==="strict"){let E=Go(i,O);return E?`ERROR: Patch ${x+1} old_text not found in ${n} (strict mode \u2014 exact match required)
|
|
330
329
|
Most similar text (line ${E.line}, distance ${E.distance}):
|
|
331
|
-
${E.text}
|
|
330
|
+
${E.text}`:`ERROR: Patch ${x+1} old_text not found in ${n} (strict mode \u2014 exact match required)`}else{let E=Am(i,O);if(E)u.push({old_text:E,new_text:I}),d=!0;else{let v=Go(i,O);if(v){let A=Math.max(3,Math.ceil(O.length*.05));if(v.distance<=A)u.push({old_text:v.text,new_text:I}),f=!0;else return`ERROR: Patch ${x+1} old_text not found in ${n}
|
|
331
|
+
Most similar text (line ${v.line}, distance ${v.distance}):
|
|
332
|
+
${v.text}`}else return`ERROR: Patch ${x+1} old_text not found in ${n}`}}}let p=i;for(let{old_text:x,new_text:O}of u)p=p.split(x).join(O);if(!s.autoConfirm){let x=await Uo(n,p);if(Ri(n,i,p,{annotations:x}),!await Bo(d?"Apply patches (fuzzy match)":"Apply patches"))return"CANCELLED: User declined to apply patches."}await Ye.writeFile(n,p,"utf-8");let h=/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||p.startsWith("#!");h&&await Ye.chmod(n,493),Ci("patch_file",n,i,p);let g=f?" (auto-fixed)":d?" (fuzzy match)":"",w=h?" [chmod +x applied]":"";return`Patched: ${n} (${r.length} replacements)${g}${w}`}case"web_fetch":{let n=e.url,o=e.max_length||1e4;try{let i=new URL(n).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 fl.get(n,{timeout:15e3,maxContentLength:1048576,responseType:"text",headers:{"User-Agent":"nex-code/0.2.0"}});return(typeof a.data=="string"?a.data:JSON.stringify(a.data)).replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim().substring(0,o)||"(empty response)"}catch(r){return`ERROR: Failed to fetch ${n}: ${r.message}`}}case"web_search":{let n=e.max_results||5;if(process.env.PERPLEXITY_API_KEY)try{let o=await fl.post("https://api.perplexity.ai/chat/completions",{model:"sonar",messages:[{role:"user",content:e.query}],max_tokens:1024,search_recency_filter:"month",return_citations:!0},{timeout:2e4,headers:{Authorization:`Bearer ${process.env.PERPLEXITY_API_KEY}`,"Content-Type":"application/json"}}),r=o.data?.choices?.[0]?.message?.content||"",i=o.data?.citations||[],a=`[Perplexity grounded search]
|
|
332
333
|
|
|
333
334
|
${r}`;return i.length>0&&(a+=`
|
|
334
335
|
|
|
335
336
|
Sources:
|
|
336
|
-
`+i.slice(0,n).map((l
|
|
337
|
-
`)),a}catch(o){console.error(`${
|
|
338
|
-
${
|
|
337
|
+
`+i.slice(0,n).map((c,l)=>`${l+1}. ${c}`).join(`
|
|
338
|
+
`)),a}catch(o){console.error(`${ae.dim} Perplexity search failed (${o.message}), falling back to DuckDuckGo${ae.reset}`)}try{let r=(await fl.get("https://html.duckduckgo.com/html/",{params:{q:e.query},timeout:1e4,responseType:"text",headers:{"User-Agent":"nex-code/0.2.0"}})).data,i=[],a=/<a[^>]*class="result__a"[^>]*href="([^"]*)"[^>]*>([\s\S]*?)<\/a>/gi,c;for(;(c=a.exec(r))!==null&&i.length<n;){let l=c[1].replace(/.*uddg=/,"").split("&")[0],u=c[2].replace(/<[^>]+>/g,"").trim();try{i.push({title:u,url:decodeURIComponent(l)})}catch{i.push({title:u,url:l})}}return i.length===0?"(no results)":i.map((l,u)=>`${u+1}. ${l.title}
|
|
339
|
+
${l.url}`).join(`
|
|
339
340
|
|
|
340
|
-
`)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:n}=
|
|
341
|
+
`)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:n}=wn();try{let o=await n(e.url,{waitFor:e.wait_for}),r=o.links.length>0?`
|
|
341
342
|
|
|
342
343
|
Links:
|
|
343
344
|
`+o.links.map(i=>` ${i.text} \u2192 ${i.href}`).join(`
|
|
344
345
|
`):"";return`Title: ${o.title}
|
|
345
346
|
URL: ${o.url}
|
|
346
347
|
|
|
347
|
-
${o.text}${r}`}catch(o){return`ERROR: ${o.message}`}}case"browser_screenshot":{let{browserScreenshot:n}=
|
|
348
|
+
${o.text}${r}`}catch(o){return`ERROR: ${o.message}`}}case"browser_screenshot":{let{browserScreenshot:n}=wn();try{let o=await n(e.url,{width:e.width,height:e.height,fullPage:e.full_page});return`Screenshot saved: ${o.path}
|
|
348
349
|
Title: ${o.title}
|
|
349
350
|
URL: ${o.url}
|
|
350
351
|
|
|
351
|
-
To analyze visually, paste the path into your next message: ${o.path}`}catch(o){return`ERROR: ${o.message}`}}case"visual_review":{let{browserScreenshot:n}=
|
|
352
|
+
To analyze visually, paste the path into your next message: ${o.path}`}catch(o){return`ERROR: ${o.message}`}}case"visual_review":{let{browserScreenshot:n}=wn();try{let o=await n(e.url,{width:e.width||1280,height:e.height||800,fullPage:e.full_page||!1}),r=e.focus||"general layout, spacing, typography, colors, and usability",i=`VISUAL REVIEW \u2014 Screenshot captured
|
|
352
353
|
URL: ${o.url}
|
|
353
354
|
Title: ${o.title}
|
|
354
355
|
Screenshot: ${o.path}
|
|
@@ -363,12 +364,12 @@ Analyze the screenshot above and provide structured feedback:
|
|
|
363
364
|
2. Visual hierarchy (typography, contrast, colors)
|
|
364
365
|
3. Consistency (margins, padding patterns)
|
|
365
366
|
4. Responsiveness concerns at this viewport
|
|
366
|
-
5. Specific issues related to: ${r}`;return e.compare_with&&
|
|
367
|
+
5. Specific issues related to: ${r}`;return e.compare_with&&Xt.existsSync(e.compare_with)&&(i+=`
|
|
367
368
|
|
|
368
|
-
COMPARISON: Previous screenshot at ${e.compare_with} \u2014 describe what changed.`),{text:i,images:[{path:o.path,base64:o.base64,media_type:"image/png"}],compare_with:e.compare_with||null}}catch(o){return`ERROR: ${o.message}`}}case"clipboard_image":try{let{_grabClipboardImage:n}=
|
|
369
|
+
COMPARISON: Previous screenshot at ${e.compare_with} \u2014 describe what changed.`),{text:i,images:[{path:o.path,base64:o.base64,media_type:"image/png"}],compare_with:e.compare_with||null}}catch(o){return`ERROR: ${o.message}`}}case"clipboard_image":try{let{_grabClipboardImage:n}=bl(),o=n();return o?{text:`Clipboard image captured: ${o.path}
|
|
369
370
|
Size: ${Math.round(Buffer.from(o.data,"base64").length/1024)} KB
|
|
370
371
|
|
|
371
|
-
[Clipboard image is attached for visual analysis]`,images:[{path:o.path,base64:o.data,media_type:o.media_type}]}:"No image found in clipboard. Copy a screenshot first (Cmd+Shift+4 on macOS), then try again."}catch(n){return`ERROR: ${n.message}`}case"browser_click":{let{browserClick:n}=
|
|
372
|
+
[Clipboard image is attached for visual analysis]`,images:[{path:o.path,base64:o.data,media_type:o.media_type}]}:"No image found in clipboard. Copy a screenshot first (Cmd+Shift+4 on macOS), then try again."}catch(n){return`ERROR: ${n.message}`}case"browser_click":{let{browserClick:n}=wn();try{return await n(e.url,{selector:e.selector,text:e.text})}catch(o){return`ERROR: ${o.message}`}}case"browser_fill":{let{browserFill:n}=wn();try{return await n(e.url,{selector:e.selector,value:e.value,submit:e.submit})}catch(o){return`ERROR: ${o.message}`}}case"visual_diff":try{let{pixelDiff:n}=Vn(),o=n(e.before,e.after,{threshold:e.threshold}),r=o.regionSummary.slice(0,5),i=r.length?r.map(a=>` ${a.name}: ${a.changedPercent}% changed`).join(`
|
|
372
373
|
`):" No significant regional changes";return{text:`VISUAL DIFF \u2014 ${o.diffPercent}% of pixels changed
|
|
373
374
|
Changed: ${o.changedPixels.toLocaleString()} / ${o.totalPixels.toLocaleString()} pixels
|
|
374
375
|
Canvas: ${o.width}\xD7${o.height}
|
|
@@ -377,7 +378,7 @@ Diff image: ${o.diffPath}
|
|
|
377
378
|
Regional breakdown:
|
|
378
379
|
${i}
|
|
379
380
|
|
|
380
|
-
[Diff image attached \u2014 red/magenta pixels indicate changes]`,images:[{path:o.diffPath,base64:
|
|
381
|
+
[Diff image attached \u2014 red/magenta pixels indicate changes]`,images:[{path:o.diffPath,base64:Xt.readFileSync(o.diffPath).toString("base64"),media_type:"image/png"}]}}catch(n){return`ERROR: ${n.message}`}case"responsive_sweep":try{let{responsiveSweep:n}=Vn(),o=await n(e.url,{viewports:e.viewports,fullPage:e.full_page}),r=o.map(i=>` ${i.label} (${i.width}px): ${i.path}`).join(`
|
|
381
382
|
`);return{text:`RESPONSIVE SWEEP \u2014 ${o.length} viewports captured
|
|
382
383
|
URL: ${e.url}
|
|
383
384
|
|
|
@@ -391,15 +392,15 @@ Analyze these screenshots for:
|
|
|
391
392
|
2. Typography scaling (text too small on mobile, too large on desktop)
|
|
392
393
|
3. Navigation pattern changes across viewports
|
|
393
394
|
4. Image/media sizing and aspect ratio issues
|
|
394
|
-
5. Touch target sizes on mobile viewports`,images:o.map(i=>({path:i.path,base64:i.base64,media_type:i.media_type}))}}catch(n){return`ERROR: ${n.message}`}case"visual_annotate":try{let{annotateImage:n}=
|
|
395
|
+
5. Touch target sizes on mobile viewports`,images:o.map(i=>({path:i.path,base64:i.base64,media_type:i.media_type}))}}catch(n){return`ERROR: ${n.message}`}case"visual_annotate":try{let{annotateImage:n}=Vn(),o=n(e.image,e.annotations),r=e.annotations.length,i=[...new Set(e.annotations.map(a=>a.type))].join(", ");return{text:`ANNOTATED IMAGE \u2014 ${r} annotation(s) added (${i})
|
|
395
396
|
Source: ${e.image}
|
|
396
397
|
Output: ${o.path}
|
|
397
398
|
|
|
398
|
-
[Annotated image attached with visual markers]`,images:[{path:o.path,base64:o.base64,media_type:o.media_type}]}}catch(n){return`ERROR: ${n.message}`}case"visual_watch":try{let{visualWatch:n}=
|
|
399
|
-
`),images:
|
|
399
|
+
[Annotated image attached with visual markers]`,images:[{path:o.path,base64:o.base64,media_type:o.media_type}]}}catch(n){return`ERROR: ${n.message}`}case"visual_watch":try{let{visualWatch:n}=Vn(),o=n(e.url,e.watch,{maxIterations:e.max_iterations||10,hmrDelay:e.hmr_delay||1500}),r=await o.next();if(r.value?.type==="error")return`ERROR: ${r.value.message}`;let i=[];i.push(`VISUAL WATCH \u2014 monitoring ${e.watch.length} path(s)`,`URL: ${e.url}`,`Baseline screenshot: ${r.value?.path}`,"","Watching for file changes... (will capture up to "+(e.max_iterations||10)+" iterations)");let a=await o.next();if(!a.done&&a.value){let c=a.value;i.push("",`--- Iteration ${c.iteration} ---`,`Screenshot: ${c.path}`),c.diff&&i.push(`Diff: ${c.diff.diffPercent}% changed (${c.diff.changedPixels} pixels)`,`Regions: ${c.diff.regions.map(u=>`${u.name}:${u.changedPercent}%`).join(", ")}`);let l=[{path:c.path,base64:c.base64,media_type:c.media_type}];return c.diff?.diffPath&&l.push({path:c.diff.diffPath,base64:Xt.readFileSync(c.diff.diffPath).toString("base64"),media_type:"image/png"}),{text:i.join(`
|
|
400
|
+
`),images:l}}return{text:i.join(`
|
|
400
401
|
`)+`
|
|
401
402
|
|
|
402
|
-
No changes detected within timeout.`,images:r.value?.base64?[{path:r.value.path,base64:r.value.base64,media_type:"image/png"}]:[]}}catch(n){return`ERROR: ${n.message}`}case"design_tokens":try{let{extractDesignTokens:n}=
|
|
403
|
+
No changes detected within timeout.`,images:r.value?.base64?[{path:r.value.path,base64:r.value.base64,media_type:"image/png"}]:[]}}catch(n){return`ERROR: ${n.message}`}case"design_tokens":try{let{extractDesignTokens:n}=Vn(),o=n(e.image,{sampleRate:e.sample_rate}),r=o.colors.slice(0,12).map(a=>` ${a.hex} ${a.rgb.padEnd(20)} ${a.frequency.toString().padStart(5)}% ${a.category}`).join(`
|
|
403
404
|
`),i=o.spacing.length?o.spacing.map(a=>` ${a.px}px (${a.occurrences} occurrences)`).join(`
|
|
404
405
|
`):" No clear spacing pattern detected";return`DESIGN TOKENS \u2014 extracted from ${o.dimensions.width}\xD7${o.dimensions.height} image
|
|
405
406
|
Source: ${o.imagePath}
|
|
@@ -413,7 +414,7 @@ ${i}
|
|
|
413
414
|
Use these values to:
|
|
414
415
|
- Compare against CSS variables / design system tokens
|
|
415
416
|
- Identify inconsistent colors or spacing
|
|
416
|
-
- Generate a color palette from the rendered output`}catch(n){return`ERROR: ${n.message}`}case"design_compare":try{let{designCompare:n}=
|
|
417
|
+
- Generate a color palette from the rendered output`}catch(n){return`ERROR: ${n.message}`}case"design_compare":try{let{designCompare:n}=Vn(),o=await n(e.url,e.reference,{width:e.width,height:e.height,threshold:e.threshold}),r=o.regions.filter(i=>i.changedPercent>.5).slice(0,6).map(i=>` ${i.name}: ${i.changedPercent}% deviation`).join(`
|
|
417
418
|
`)||" All regions match within tolerance";return{text:`DESIGN COMPARISON \u2014 ${o.diffPercent}% deviation from reference
|
|
418
419
|
Reference: ${o.referencePath}
|
|
419
420
|
Live: ${o.livePath}
|
|
@@ -425,162 +426,164 @@ Pixel deviation: ${o.changedPixels.toLocaleString()} / ${o.totalPixels.toLocaleS
|
|
|
425
426
|
Regional breakdown:
|
|
426
427
|
${r}
|
|
427
428
|
|
|
428
|
-
[Three images attached: live screenshot, pixel diff, annotated deviation map]`,images:[{path:o.livePath,base64:o.liveBase64,media_type:"image/png"},{path:o.diffPath,base64:o.diffBase64,media_type:"image/png"},{path:o.annotatedPath,base64:o.annotatedBase64,media_type:"image/png"}]}}catch(n){return`ERROR: ${n.message}`}case"ask_user":{let{question:n,options:o=[]}=e;return
|
|
429
|
-
${o.map((l
|
|
429
|
+
[Three images attached: live screenshot, pixel diff, annotated deviation map]`,images:[{path:o.livePath,base64:o.liveBase64,media_type:"image/png"},{path:o.diffPath,base64:o.diffBase64,media_type:"image/png"},{path:o.annotatedPath,base64:o.annotatedBase64,media_type:"image/png"}]}}catch(n){return`ERROR: ${n.message}`}case"ask_user":{let{question:n,options:o=[]}=e;return $l?new Promise(r=>{as=()=>r("CANCELLED"),$l(n,o).then(i=>{as=null,r(i||"User did not answer")})}):new Promise(r=>{let i=require("readline").createInterface({input:process.stdin,output:process.stdout});as=()=>{i.close(),r("CANCELLED")};let a=o.length>0?`
|
|
430
|
+
${o.map((c,l)=>` ${l+1}. ${c}`).join(`
|
|
430
431
|
`)}
|
|
431
432
|
`:"";console.log(`
|
|
432
|
-
${
|
|
433
|
+
${ae.cyan}${ae.bold} ? ${n}${ae.reset}${a}`),i.question(`${ae.cyan} > ${ae.reset}`,c=>{as=null,i.close(),r(c.trim()||"(no response)")})})}case"git_status":{if(!await pl())return"ERROR: Not a git repository";let n=await Cm()||"(detached)",o=await jS();if(o.length===0)return`Branch: ${n}
|
|
433
434
|
Clean working tree (no changes)`;let r=[`Branch: ${n}`,`Changed files (${o.length}):`];for(let i of o){let a=i.status==="M"?"modified":i.status==="A"?"added":i.status==="D"?"deleted":i.status==="??"?"untracked":i.status;r.push(` ${a}: ${i.file}`)}return r.join(`
|
|
434
|
-
`)}case"git_diff":{if(!await
|
|
435
|
+
`)}case"git_diff":{if(!await pl())return"ERROR: Not a git repository";let n;if(e.file){let o=["diff"];e.staged&&o.push("--cached"),o.push("--",e.file);try{n=execFileSync("git",o,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()}catch{n=""}}else n=await DS(!!e.staged);return n||"(no diff)"}case"git_log":{if(!await pl())return"ERROR: Not a git repository";let o=["log","--oneline",`-${Math.min(e.count||10,50)}`];e.file&&o.push("--",e.file);try{return execFileSync("git",o,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()||"(no commits)"}catch{return"(no commits)"}}case"task_list":{let{createTasks:n,updateTask:o,getTaskList:r,renderTaskList:i,hasActiveTasks:a}=Yc(),{getActiveTaskProgress:c}=Je(),l=c();switch(e.action){case"create":{if(!e.name||!e.tasks)return"ERROR: task_list create requires name and tasks";let u=n(e.name,e.tasks);return l||console.log(`
|
|
435
436
|
`+i()),`Created task list "${e.name}" with ${u.length} tasks:
|
|
436
437
|
`+u.map(d=>` ${d.id}: ${d.description}`).join(`
|
|
437
|
-
`)}case"update":return!e.task_id||!e.status?"ERROR: task_list update requires task_id and status":o(e.task_id,e.status,e.result)?(
|
|
438
|
-
`+i()),`Updated ${e.task_id}: ${e.status}${e.result?" \u2014 "+e.result:""}`):`ERROR: Task not found: ${e.task_id}`;case"get":{let u=r();return u.tasks.length===0?"No active tasks":(
|
|
439
|
-
`+i()),JSON.stringify(u,null,2))}default:return`ERROR: Unknown task_list action: ${e.action}. Use: create, update, get`}}case"spawn_agents":{let{executeSpawnAgents:n,executeSpawnAgentsBackground:o}=
|
|
438
|
+
`)}case"update":return!e.task_id||!e.status?"ERROR: task_list update requires task_id and status":o(e.task_id,e.status,e.result)?(l||console.log(`
|
|
439
|
+
`+i()),`Updated ${e.task_id}: ${e.status}${e.result?" \u2014 "+e.result:""}`):`ERROR: Task not found: ${e.task_id}`;case"get":{let u=r();return u.tasks.length===0?"No active tasks":(l||console.log(`
|
|
440
|
+
`+i()),JSON.stringify(u,null,2))}default:return`ERROR: Unknown task_list action: ${e.action}. Use: create, update, get`}}case"spawn_agents":{let{executeSpawnAgents:n,executeSpawnAgentsBackground:o}=el();return e.agents?.some(r=>r.background)?o(e):n(e)}case"switch_model":{let{setActiveModel:n,getActiveProviderName:o,getActiveModelId:r}=st();return n(e.model)?`Switched to ${o()}:${r()}`:`ERROR: Unknown model: ${e.model}. Use /providers to see available models.`}case"gh_run_list":{let n=Math.min(e.limit||10,30),o=["run","list","--limit",String(n),"--json","databaseId,status,conclusion,name,headBranch,createdAt,updatedAt,event"];e.workflow&&o.push("--workflow",e.workflow),e.branch&&o.push("--branch",e.branch),e.status&&o.push("--status",e.status);try{let{stdout:r}=await is("gh",o,{cwd:process.cwd(),timeout:3e4}),i=JSON.parse(r||"[]");return i.length===0?"No workflow runs found.":i.map(c=>{let l=c.conclusion||c.status||"unknown",u=l==="success"?"\u2713":l==="failure"?"\u2717":l==="in_progress"?"\u283F":"\u25CB",d=c.updatedAt?new Date(c.updatedAt).toISOString().slice(0,16).replace("T"," "):"";return`${u} [${c.databaseId}] ${c.name} \xB7 ${c.headBranch} \xB7 ${l} \xB7 ${d}`}).join(`
|
|
440
441
|
`)}catch(r){let i=(r.stderr||r.message||"").toString();return i.includes("not found")||i.includes("not logged")?"ERROR: gh CLI not found or not authenticated. Run: gh auth login":`ERROR: ${i.split(`
|
|
441
|
-
`)[0]}`}}case"gh_run_view":{if(!e.run_id)return"ERROR: run_id is required";if(!/^\d+$/.test(String(e.run_id)))return"ERROR: run_id must be numeric";try{if(e.log){let{stdout:i}=await
|
|
442
|
-
...(truncated)`:"")}let{stdout:n}=await
|
|
442
|
+
`)[0]}`}}case"gh_run_view":{if(!e.run_id)return"ERROR: run_id is required";if(!/^\d+$/.test(String(e.run_id)))return"ERROR: run_id must be numeric";try{if(e.log){let{stdout:i}=await is("gh",["run","view",String(e.run_id),"--log"],{cwd:process.cwd(),timeout:6e4,maxBuffer:5242880});return i.substring(0,8e3)+(i.length>8e3?`
|
|
443
|
+
...(truncated)`:"")}let{stdout:n}=await is("gh",["run","view",String(e.run_id),"--json","status,conclusion,name,headBranch,createdAt,updatedAt,jobs"],{cwd:process.cwd(),timeout:3e4}),o=JSON.parse(n),r=[`Run: ${o.name} [${e.run_id}]`,`Branch: ${o.headBranch} Status: ${o.conclusion||o.status}`,`Started: ${o.createdAt} Finished: ${o.updatedAt||"\u2014"}`,"","Jobs:"];for(let i of o.jobs||[]){let a=i.conclusion==="success"?"\u2713":i.conclusion==="failure"?"\u2717":"\u25CB";r.push(` ${a} ${i.name} (${i.conclusion||i.status})`);for(let c of i.steps||[]){if(c.conclusion==="failure"||c.conclusion==="skipped")continue;let l=c.conclusion==="success"?" \u2713":c.conclusion==="failure"?" \u2717":" \u25CB";r.push(` ${l} ${c.name}`)}}return r.join(`
|
|
443
444
|
`)}catch(n){return`ERROR: ${(n.stderr||n.message||"").toString().split(`
|
|
444
|
-
`)[0]}`}}case"gh_workflow_trigger":{if(!e.workflow)return"ERROR: workflow is required";if(!/^[\w./-]+$/.test(e.workflow))return"ERROR: invalid workflow name";let{confirm:n}=
|
|
445
|
-
${
|
|
446
|
-
`)[0]}`}}case"k8s_pods":{let n=e.namespace?`-n ${e.namespace}`:"-A",o=e.label?`-l ${e.label}`:"",r=
|
|
447
|
-
`)[0];return a.includes("command not found")?"ERROR: kubectl not found. Install kubectl or provide a server with kubectl.":`ERROR: ${a}`}}case"k8s_logs":{if(!e.pod)return"ERROR: pod is required";let n=e.namespace||"default",o=e.tail||100,r=`logs ${e.pod} -n ${n} --tail=${o}`;e.since&&(r+=` --since=${e.since}`),e.container&&(r+=` -c ${e.container}`);let i=
|
|
445
|
+
`)[0]}`}}case"gh_workflow_trigger":{if(!e.workflow)return"ERROR: workflow is required";if(!/^[\w./-]+$/.test(e.workflow))return"ERROR: invalid workflow name";let{confirm:n}=yo(),o=e.branch||await Cm()||"main";if(!/^[\w./-]+$/.test(o))return"ERROR: invalid branch name";let r=["workflow","run",e.workflow,"--ref",o];if(e.inputs)for(let[a,c]of Object.entries(e.inputs)){if(!/^[\w-]+$/.test(a))return`ERROR: invalid input key: ${a}`;r.push("-f",`${a}=${c}`)}if(console.log(`
|
|
446
|
+
${ae.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${o}${ae.reset}`),!await n(" Trigger?"))return"CANCELLED: User declined to trigger workflow.";try{return await is("gh",r,{cwd:process.cwd(),timeout:3e4}),`Workflow "${e.workflow}" triggered on branch "${o}". Check status with gh_run_list.`}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
|
|
447
|
+
`)[0]}`}}case"k8s_pods":{let n=e.namespace?`-n ${e.namespace}`:"-A",o=e.label?`-l ${e.label}`:"",r=Yo(`get pods ${n} ${o} -o wide`.trim(),e);try{let{stdout:i,stderr:a}=await Be(r,{timeout:3e4,maxBuffer:2097152});return(i||a||"(no pods)").trim()}catch(i){let a=(i.stderr||i.message||"").toString().split(`
|
|
448
|
+
`)[0];return a.includes("command not found")?"ERROR: kubectl not found. Install kubectl or provide a server with kubectl.":`ERROR: ${a}`}}case"k8s_logs":{if(!e.pod)return"ERROR: pod is required";let n=e.namespace||"default",o=e.tail||100,r=`logs ${e.pod} -n ${n} --tail=${o}`;e.since&&(r+=` --since=${e.since}`),e.container&&(r+=` -c ${e.container}`);let i=Yo(r,e);try{let{stdout:a,stderr:c}=await Be(i,{timeout:6e4,maxBuffer:5242880}),l=(a||c||"(no logs)").trim();return l.substring(0,2e4)+(l.length>2e4?`
|
|
448
449
|
...(truncated)`:"")}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
|
|
449
450
|
`)[0]}`}}case"k8s_exec":{if(!e.pod)return"ERROR: pod is required";if(!e.command)return"ERROR: command is required";let n=e.namespace||"default";if(console.log(`
|
|
450
|
-
${
|
|
451
|
+
${ae.yellow} \u26A0 kubectl exec into pod: ${e.pod} (ns: ${n})${ae.reset}`),console.log(`${ae.dim} Command: ${e.command}${ae.reset}`),!await Kt(" Execute in pod?"))return"CANCELLED: User declined.";let r=`exec ${e.pod} -n ${n}`;e.container&&(r+=` -c ${e.container}`),r+=` -- sh -c ${JSON.stringify(e.command)}`;let i=Yo(r,e);try{let{stdout:a,stderr:c}=await Be(i,{timeout:6e4,maxBuffer:2097152});return(a||c||"(no output)").trim()}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
|
|
451
452
|
`)[0]}`}}case"k8s_apply":{if(!e.file)return"ERROR: file is required";let n=!!e.dry_run;if(!n){let i=e.file;if(console.log(`
|
|
452
|
-
${
|
|
453
|
+
${ae.yellow} \u26A0 kubectl apply: ${i}${e.namespace?` (ns: ${e.namespace})`:""}${ae.reset}`),!await Kt(" Apply to cluster?"))return"CANCELLED: User declined."}let o=`apply -f ${e.file}`;e.namespace&&(o+=` -n ${e.namespace}`),n&&(o+=" --dry-run=client");let r=Yo(o,e);try{let{stdout:i,stderr:a}=await Be(r,{timeout:12e4,maxBuffer:2097152});return(i||a||"(no output)").trim()}catch(i){return`ERROR: ${(i.stderr||i.message||"").toString().split(`
|
|
453
454
|
`)[0]}`}}case"k8s_rollout":{if(!e.action)return"ERROR: action is required";if(!e.deployment)return"ERROR: deployment is required";let n=e.namespace||"default";if(e.action==="restart"||e.action==="undo"){let a=e.action==="restart"?"Rolling restart":"Rollback (undo)";if(console.log(`
|
|
454
|
-
${
|
|
455
|
-
`)[0]}`}}case"brain_write":{if(!e.name)return"ERROR: name is required";if(!e.content)return"ERROR: content is required";if(!e.mode)return"ERROR: mode is required (create, update, append)";let{writeDocument:n,readDocument:o}=
|
|
455
|
+
${ae.yellow} \u26A0 ${a}: deployment/${e.deployment} (ns: ${n})${ae.reset}`),!await Kt(` ${a}?`))return"CANCELLED: User declined."}let r=`rollout ${e.action} deployment/${e.deployment} -n ${n}`,i=Yo(r,e);try{let{stdout:a,stderr:c}=await Be(i,{timeout:12e4,maxBuffer:2097152});return(a||c||"(no output)").trim()}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
|
|
456
|
+
`)[0]}`}}case"brain_write":{if(!e.name)return"ERROR: name is required";if(!e.content)return"ERROR: content is required";if(!e.mode)return"ERROR: mode is required (create, update, append)";let{writeDocument:n,readDocument:o}=cl(),{name:r,content:i,mode:a}=e;if(a==="create"&&o(r).content)return`ERROR: Document "${r}" already exists. Use mode "update" to overwrite.`;if(a==="append"){let c=o(r),l=c.content?c.content+`
|
|
456
457
|
|
|
457
|
-
`+i:i;return n(r,
|
|
458
|
+
`+i:i;return n(r,l),`Appended to brain document: ${r}.md`}return n(r,i),`${a==="create"?"Created":"Updated"} brain document: ${r}.md`}case"ssh_exec":{if(!e.server)return"ERROR: server is required";if(!e.command)return"ERROR: command is required";let n;try{n=Dt(e.server)}catch(A){return`ERROR: ${A.message}`}let o=e.command,r=!!e.sudo,i=(e.timeout||30)*1e3,a=OS(o);if(a)return/\bsed\s+-n\s+['"]?\d+,\d+p/.test(o)?`BLOCKED: sed -n line-range is blocked (floods context). To read specific lines from a remote file use:
|
|
458
459
|
grep -n "pattern" /path/to/file -A 50
|
|
459
460
|
or to read the whole file:
|
|
460
461
|
cat /path/to/file
|
|
461
462
|
NEVER use sed -n again \u2014 it will always be blocked.`:`BLOCKED: Remote command matches SSH secret-exposure pattern: ${a}
|
|
462
|
-
HINT: Do not read .env, credentials, or private key files via ssh_exec \u2014 secrets would appear in tool output. Reference variable names or file paths instead.`;if(o=o.replace(/(-[BAC])\s*(\d+)/g,(
|
|
463
|
-
${
|
|
464
|
-
`).trim();if(d!==0){if(/no such file or directory/i.test(p)){let
|
|
463
|
+
HINT: Do not read .env, credentials, or private key files via ssh_exec \u2014 secrets would appear in tool output. Reference variable names or file paths instead.`;if(o=o.replace(/(-[BAC])\s*(\d+)/g,(A,te,oe)=>{let de=Math.min(Number(oe),20);return`${te} ${de}`}),o=o.replace(/(--(?:before|after|context)=)(\d+)/g,(A,te,oe)=>te+Math.min(Number(oe),20)),/\b(rm|rmdir|mv|cp|chmod|chown|dd|mkfs|systemctl\s+(start|stop|restart|reload|enable|disable)|dnf\s+(install|remove|update|upgrade)|yum\s+(install|remove)|apt(-get)?\s+(install|remove|purge)|pip\s+install|pip3\s+install|firewall-cmd\s+--permanent|semanage|setsebool|passwd|userdel|useradd|nginx\s+-s\s+(reload|stop)|service\s+\w+\s+(start|stop|restart))\b/.test(o)){let A=n.user?`${n.user}@${n.host}`:n.host;if(console.log(`
|
|
464
|
+
${ae.yellow} \u26A0 Remote command on ${A}: ${o}${ae.reset}`),!await Kt(" Execute on remote server?"))return"CANCELLED: User declined to execute remote command."}let{stdout:l,stderr:u,exitCode:d,error:f}=await yt(n,o,{timeout:i,sudo:r}),p=[l,u].filter(Boolean).join(`
|
|
465
|
+
`).trim();if(d!==0){if(/no such file or directory/i.test(p)){let te=p.match(/['"]?([/\w._-]+\.\w+)['"]?:\s*No such file/i),oe=o.match(/(?:cat|head|tail|less|grep\s+\S+\s+|ls\s+|stat\s+|wc\s+|file\s+)['"]?([/\w._-]+)['"]?/),de=te&&te[1]||oe&&oe[1];if(de)try{let{remoteAutoFixPath:ce}=js(),ne=de.startsWith("/")?de.split("/").slice(0,-1).join("/").replace(/\/[^/]+$/,"")||"/":"/home/"+(n.user||"root"),S=await ce(n,ne,de);if(S.fixedPath){let Te=o.replace(de,S.fixedPath);console.log(`${ae.dim} \u2713 remote auto-fix: ${de} \u2192 ${S.fixedPath}${ae.reset}`);let W=await yt(n,Te,{timeout:i,sudo:r}),K=[W.stdout,W.stderr].filter(Boolean).join(`
|
|
465
466
|
`).trim();if(W.exitCode===0)return`${S.message}
|
|
466
|
-
${
|
|
467
|
+
${K}`||"(command completed, no output)"}else if(S.message)return`EXIT ${d}
|
|
467
468
|
${f||p}
|
|
468
469
|
|
|
469
470
|
${S.message}`}catch{}}return`EXIT ${d}
|
|
470
|
-
${f||p||"(no output)"}`}let
|
|
471
|
-
`).filter(
|
|
472
|
-
`));let
|
|
473
|
-
`);
|
|
474
|
-
`+
|
|
475
|
-
`));let
|
|
476
|
-
`),
|
|
477
|
-
`)||"(command completed, no output)"}case"ssh_upload":{if(!e.server||!e.local_path||!e.remote_path)return"ERROR: server, local_path, and remote_path are required";let n;try{n=
|
|
478
|
-
${
|
|
479
|
-
${
|
|
480
|
-
|
|
481
|
-
${a.message}`}catch{}return`ERROR: ${o.message}`}}case"remote_agent":{let n=require("path").join(process.cwd(),".nex","servers.json"),o=null;try{o=JSON.parse(require("fs").readFileSync(n,"utf-8"))[e.server]||null}catch{}let r=o?`${o.user||"root"}@${o.host}`:e.server,i=o?.key?["-i",o.key]:[],a=(e.project_path||o?.home||"~").replace(/[^a-zA-Z0-9_/~.-]/g,""),
|
|
482
|
-
${p.slice(-2e3)}`:p.slice(-5e3)||"Remote nex-code completed (no output)"}case"service_manage":{if(!e.service)return"ERROR: service is required";if(!e.action)return"ERROR: action is required";let n=["status","start","stop","restart","reload","enable","disable"];if(!
|
|
483
|
-
${
|
|
484
|
-
${
|
|
485
|
-
`).trim();return
|
|
486
|
-
${
|
|
487
|
-
${(
|
|
488
|
-
`).trim();return
|
|
489
|
-
${
|
|
490
|
-
${(f.stderr||f.message||"").toString().trim()}`}let i;try{i=
|
|
491
|
-
`).trim();return
|
|
492
|
-
${u||d}`:d||"(no containers)"}case"container_logs":{if(!e.container)return"ERROR: container is required";let n=!e.server||e.server==="local"||e.server==="localhost",o=e.lines||50,r=e.since?`--since "${e.since}"`:"",i=`docker logs --tail ${o} ${r} ${e.container} 2>&1`.trim().replace(/\s+/g," ");if(n)try{let{stdout:p,stderr:
|
|
493
|
-
${(p.stderr||p.message||"").toString().trim()}`}let a;try{a=
|
|
471
|
+
${f||p||"(no output)"}`}let h=/\bgrep\b/.test(o),g=p;h&&(g=g.split(`
|
|
472
|
+
`).filter(A=>A!=="--").join(`
|
|
473
|
+
`));let w=h?60:100,x=g.split(`
|
|
474
|
+
`);x.length>w&&(g=`(${x.length-w} earlier lines omitted \u2014 showing last ${w})
|
|
475
|
+
`+x.slice(-w).join(`
|
|
476
|
+
`));let O=4,I=g.split(`
|
|
477
|
+
`),E=[],v=0;for(;v<I.length;){let A=v+1;for(;A<I.length&&I[A]===I[v];)A++;let te=A-v;if(E.push(I[v]),te>O)E.push(`... (${te-1} identical lines omitted)`);else for(let oe=1;oe<te;oe++)E.push(I[v]);v=A}return E.join(`
|
|
478
|
+
`)||"(command completed, no output)"}case"ssh_upload":{if(!e.server||!e.local_path||!e.remote_path)return"ERROR: server, local_path, and remote_path are required";let n;try{n=Dt(e.server)}catch(i){return`ERROR: ${i.message}`}let o=n.user?`${n.user}@${n.host}`:n.host;if(console.log(`
|
|
479
|
+
${ae.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${o}:${e.remote_path}${ae.reset}`),!await Kt(" Upload to remote server?"))return"CANCELLED: User declined upload.";try{let i=await WS(n,e.local_path,e.remote_path);try{js().clearRemoteIndex()}catch{}return i}catch(i){return`ERROR: ${i.message}`}}case"ssh_download":{if(!e.server||!e.remote_path||!e.local_path)return"ERROR: server, remote_path, and local_path are required";let n;try{n=Dt(e.server)}catch(o){return`ERROR: ${o.message}`}try{return await Mm(n,e.remote_path,e.local_path)}catch(o){if(/no such file|not found/i.test(o.message))try{let{remoteAutoFixPath:r}=js(),i=e.remote_path.split("/").slice(0,-1).join("/")||"/",a=await r(n,i,e.remote_path);if(a.fixedPath){console.log(`${ae.dim} \u2713 remote auto-fix: ${e.remote_path} \u2192 ${a.fixedPath}${ae.reset}`);let c=await Mm(n,a.fixedPath,e.local_path);return`${a.message}
|
|
480
|
+
${c}`}if(a.message)return`ERROR: ${o.message}
|
|
481
|
+
|
|
482
|
+
${a.message}`}catch{}return`ERROR: ${o.message}`}}case"remote_agent":{let n=require("path").join(process.cwd(),".nex","servers.json"),o=null;try{o=JSON.parse(require("fs").readFileSync(n,"utf-8"))[e.server]||null}catch{}let r=o?`${o.user||"root"}@${o.host}`:e.server,i=o?.key?["-i",o.key]:[],a=(e.project_path||o?.home||"~").replace(/[^a-zA-Z0-9_/~.-]/g,""),c=(e.model||"").replace(/[^a-zA-Z0-9_:.-]/g,""),u=['TMPFILE=$(mktemp /tmp/nexcode-XXXXXX.txt) && chmod 600 "$TMPFILE"',`echo "${Buffer.from(e.task).toString("base64")}" | base64 -d > "$TMPFILE"`,`cd "${a}" 2>/dev/null || true`,c?`nex-code --prompt-file "$TMPFILE" --auto --model "${c}" 2>&1`:'nex-code --prompt-file "$TMPFILE" --auto 2>&1',"EXIT_CODE=$?",'rm -f "$TMPFILE"',"exit $EXIT_CODE"].join(" && "),{spawnSync:d}=require("child_process"),f=d("ssh",[...i,"-o","StrictHostKeyChecking=yes","-o","ConnectTimeout=10",r,`bash -c '${u}'`],{encoding:"utf-8",maxBuffer:10*1024*1024,timeout:3e5});if(f.error)return`ERROR: SSH connection failed: ${f.error.message}`;let p=(f.stdout||"")+(f.stderr||"");return f.status!==0?`Remote nex-code exited with code ${f.status}.
|
|
483
|
+
${p.slice(-2e3)}`:p.slice(-5e3)||"Remote nex-code completed (no output)"}case"service_manage":{if(!e.service)return"ERROR: service is required";if(!e.action)return"ERROR: action is required";let n=wl(e.service);if(n)return n;let o=["status","start","stop","restart","reload","enable","disable"];if(!o.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${o.join(", ")}`;let r=!e.server||e.server==="local"||e.server==="localhost",i=e.action==="status",a=null;if(!r)try{a=Dt(e.server)}catch(u){return`ERROR: ${u.message}`}if(!i){let u=r?"local machine":a.user?`${a.user}@${a.host}`:a.host;if(console.log(`
|
|
484
|
+
${ae.yellow} \u26A0 Service: systemctl ${e.action} ${e.service} on ${u}${ae.reset}`),!await Kt(" Execute?"))return"CANCELLED: User declined service action."}let c=e.service.includes(".")?e.service:`${e.service}.service`,l=`systemctl ${e.action} ${Se(c)}`;if(r){let d=e.action!=="status"?`sudo ${l}`:l;try{let{stdout:f,stderr:p}=await Be(d,{timeout:15e3});return(f||p||`systemctl ${e.action} ${e.service}: OK`).trim()}catch(f){let p=(f.stderr||f.message||"").toString().trim();return/not found|loaded.*not-found/i.test(p)?`ERROR: Service "${e.service}" not found. Check: systemctl list-units --type=service`:`EXIT ${f.code||1}
|
|
485
|
+
${p}`}}else{let{stdout:u,stderr:d,exitCode:f,error:p}=await yt(a,l,{timeout:15e3,sudo:!0}),h=[u,d].filter(Boolean).join(`
|
|
486
|
+
`).trim();return f!==0?/not found|loaded.*not-found/i.test(h)?`ERROR: Service "${e.service}" not found on ${a.host}. Check: ssh_exec to run "systemctl list-units --type=service"`:`EXIT ${f}
|
|
487
|
+
${p||h||"(no output)"}`:h||`systemctl ${e.action} ${e.service}: OK`}}case"service_logs":{if(!e.service)return"ERROR: service is required";let n=wl(e.service);if(n)return n;let o=!e.server||e.server==="local"||e.server==="localhost",r=e.lines||50,i=e.service.includes(".")?e.service:`${e.service}.service`,a=e.since?`--since ${Se(e.since)}`:"",c=e.follow?"-f":"",l=`journalctl -u ${Se(i)} -n ${r} ${a} ${c} --no-pager`.trim().replace(/\s+/g," ");if(o)try{let{stdout:w,stderr:x}=await Be(l,{timeout:15e3});return(w||x||"(no log output)").trim()}catch(w){return`EXIT ${w.code||1}
|
|
488
|
+
${(w.stderr||w.message||"").toString().trim()}`}let u;try{u=Dt(e.server)}catch(w){return`ERROR: ${w.message}`}let{stdout:d,stderr:f,exitCode:p,error:h}=await yt(u,l,{timeout:2e4}),g=[d,f].filter(Boolean).join(`
|
|
489
|
+
`).trim();return p!==0?`EXIT ${p}
|
|
490
|
+
${h||g||"(no output)"}`:g||"(no log output)"}case"container_list":{let n=!e.server||e.server==="local"||e.server==="localhost",r=`docker ps ${e.all?"-a":""} --format "table {{.ID}}\\t{{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}"`.trim().replace(/\s+/g," ");if(n)try{let{stdout:f,stderr:p}=await Be(r,{timeout:1e4});return(f||p||"(no containers)").trim()}catch(f){return`EXIT ${f.code||1}
|
|
491
|
+
${(f.stderr||f.message||"").toString().trim()}`}let i;try{i=Dt(e.server)}catch(f){return`ERROR: ${f.message}`}let{stdout:a,stderr:c,exitCode:l,error:u}=await yt(i,r,{timeout:15e3}),d=[a,c].filter(Boolean).join(`
|
|
492
|
+
`).trim();return l!==0?`EXIT ${l}
|
|
493
|
+
${u||d}`:d||"(no containers)"}case"container_logs":{if(!e.container)return"ERROR: container is required";let n=!e.server||e.server==="local"||e.server==="localhost",o=e.lines||50,r=e.since?`--since "${e.since}"`:"",i=`docker logs --tail ${o} ${r} ${e.container} 2>&1`.trim().replace(/\s+/g," ");if(n)try{let{stdout:p,stderr:h}=await Be(i,{timeout:15e3});return(p||h||"(no log output)").trim()}catch(p){return`EXIT ${p.code||1}
|
|
494
|
+
${(p.stderr||p.message||"").toString().trim()}`}let a;try{a=Dt(e.server)}catch(p){return`ERROR: ${p.message}`}let{stdout:c,stderr:l,exitCode:u,error:d}=await yt(a,i,{timeout:2e4}),f=[c,l].filter(Boolean).join(`
|
|
494
495
|
`).trim();return u!==0?`EXIT ${u}
|
|
495
|
-
${d||f}`:f||"(no log output)"}case"container_exec":{if(!e.container)return"ERROR: container is required";if(!e.command)return"ERROR: command is required";let n=!e.server||e.server==="local"||e.server==="localhost",o=/^(cat|ls|echo|env|printenv|df|du|ps|id|whoami|uname|hostname|date|pwd|which|find\s|head\s|tail\s|grep\s|curl\s+-[A-Za-z]*G|curl\s+https?:\/\/[^\s]+$)/;if(!s.autoConfirm&&!o.test(e.command.trim())){let
|
|
496
|
-
${
|
|
497
|
-
${(
|
|
496
|
+
${d||f}`:f||"(no log output)"}case"container_exec":{if(!e.container)return"ERROR: container is required";if(!e.command)return"ERROR: command is required";let n=!e.server||e.server==="local"||e.server==="localhost",o=/^(cat|ls|echo|env|printenv|df|du|ps|id|whoami|uname|hostname|date|pwd|which|find\s|head\s|tail\s|grep\s|curl\s+-[A-Za-z]*G|curl\s+https?:\/\/[^\s]+$)/;if(!s.autoConfirm&&!o.test(e.command.trim())){let h=n?"local":e.server;if(console.log(`
|
|
497
|
+
${ae.yellow} \u26A0 docker exec in ${e.container} on ${h}: ${e.command}${ae.reset}`),!await Kt(" Execute?"))return"CANCELLED: User declined."}let i=(e.container||"").replace(/[^a-zA-Z0-9._\/-]/g,"");if(!i)return"ERROR: Invalid container name";let a=`docker exec ${i} sh -c ${JSON.stringify(e.command)}`;if(n)try{let{stdout:h,stderr:g}=await Be(a,{timeout:3e4});return(h||g||"(no output)").trim()}catch(h){return`EXIT ${h.code||1}
|
|
498
|
+
${(h.stderr||h.message||"").toString().trim()}`}let c;try{c=Dt(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:l,stderr:u,exitCode:d,error:f}=await yt(c,a,{timeout:35e3}),p=[l,u].filter(Boolean).join(`
|
|
498
499
|
`).trim();return d!==0?`EXIT ${d}
|
|
499
|
-
${f||p}`:p||"(no output)"}case"container_manage":{if(!e.container)return"ERROR: container is required";if(!e.action)return"ERROR: action is required";let n=["start","stop","restart","remove","inspect"];if(!n.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${n.join(", ")}`;let o=!e.server||e.server==="local"||e.server==="localhost";if(!(e.action==="inspect")&&!s.autoConfirm){let
|
|
500
|
-
${
|
|
501
|
-
${(
|
|
500
|
+
${f||p}`:p||"(no output)"}case"container_manage":{if(!e.container)return"ERROR: container is required";if(!e.action)return"ERROR: action is required";let n=["start","stop","restart","remove","inspect"];if(!n.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${n.join(", ")}`;let o=!e.server||e.server==="local"||e.server==="localhost";if(!(e.action==="inspect")&&!s.autoConfirm){let h=o?"local":e.server;if(console.log(`
|
|
501
|
+
${ae.yellow} \u26A0 docker ${e.action} ${e.container} on ${h}${ae.reset}`),!await Kt(" Execute?"))return"CANCELLED: User declined."}let i=e.action==="remove"?"rm":e.action,a=e.action==="inspect"?`docker inspect ${e.container}`:`docker ${i} ${e.container}`;if(o)try{let{stdout:h,stderr:g}=await Be(a,{timeout:3e4});return(h||g||`docker ${e.action} ${e.container}: OK`).trim()}catch(h){return`EXIT ${h.code||1}
|
|
502
|
+
${(h.stderr||h.message||"").toString().trim()}`}let c;try{c=Dt(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:l,stderr:u,exitCode:d,error:f}=await yt(c,a,{timeout:35e3}),p=[l,u].filter(Boolean).join(`
|
|
502
503
|
`).trim();return d!==0?`EXIT ${d}
|
|
503
|
-
${f||p}`:p||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...
|
|
504
|
-
${
|
|
505
|
-
${
|
|
504
|
+
${f||p}`:p||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...HS(e.config),...e},delete e.config,delete e._name}catch(u){return`ERROR: ${u.message}`}if(!e.server)return'ERROR: server is required (or use config: "<name>")';if(!e.remote_path)return"ERROR: remote_path is required";let n=e.method||"rsync";if(n==="rsync"&&!e.local_path)return"ERROR: local_path is required for rsync method";let o;try{o=Dt(e.server)}catch(u){return`ERROR: ${u.message}`}let r=o.user?`${o.user}@${o.host}`:o.host;if(!e.dry_run&&!s.autoConfirm){if(n==="git"){let d=e.branch?` (branch: ${e.branch})`:"";console.log(`
|
|
505
|
+
${ae.yellow} \u26A0 Deploy [git pull]: ${r}:${e.remote_path}${d}${ae.reset}`)}else{let d=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`;console.log(`
|
|
506
|
+
${ae.yellow} \u26A0 Deploy [rsync]: ${d} \u2192 ${r}:${e.remote_path}${ae.reset}`)}if(e.deploy_script&&console.log(`${ae.yellow} Then run: ${e.deploy_script}${ae.reset}`),e.health_check&&console.log(`${ae.yellow} Health check: ${e.health_check}${ae.reset}`),!await Kt(" Proceed with deployment?"))return"CANCELLED: User declined."}let i="";if(n==="git"){let u=(e.branch||"").replace(/[^a-zA-Z0-9._\/-]/g,"");if(e.branch&&u!==e.branch)return`ERROR: Invalid branch name: ${e.branch}`;let d=(e.remote_path||"").replace(/'/g,"'\\''"),f=u?`cd '${d}' && git fetch origin && git checkout '${u}' && git pull origin '${u}'`:`cd '${d}' && git pull`;if(e.dry_run)return`DRY RUN [git]: would run on ${r}:
|
|
506
507
|
${f}${e.deploy_script?`
|
|
507
|
-
${e.deploy_script}`:""}`;let{stdout:p,stderr:
|
|
508
|
+
${e.deploy_script}`:""}`;let{stdout:p,stderr:h,exitCode:g,error:w}=await yt(o,f,{timeout:12e4});if(i=[p,h].filter(Boolean).join(`
|
|
508
509
|
`).trim(),g!==0)return`ERROR (git pull, exit ${g}):
|
|
509
|
-
${
|
|
510
|
-
${i||"(nothing to sync)"}`}let a="";if(e.deploy_script){let{stdout:u,stderr:d,exitCode:f,error:p}=await
|
|
510
|
+
${w||i}`}else{let u=o.key?`-e "ssh -i ${o.key.replace(/^~/,require("os").homedir())}${o.port&&Number(o.port)!==22?` -p ${o.port}`:""}"`:o.port&&Number(o.port)!==22?`-e "ssh -p ${o.port}"`:"",d=(e.exclude||[]).map(g=>`--exclude="${g}"`).join(" "),f=e.dry_run?"--dry-run":"",p=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`,h=`rsync -avz --delete ${f} ${d} ${u} ${p} ${r}:${e.remote_path}`.trim().replace(/\s+/g," ");try{let{stdout:g,stderr:w}=await Be(h,{timeout:12e4});i=(g||w||"").trim()}catch(g){return`ERROR (rsync): ${(g.stderr||g.message||"").toString().trim()}`}if(e.dry_run)return`DRY RUN [rsync]:
|
|
511
|
+
${i||"(nothing to sync)"}`}let a="";if(e.deploy_script){let{stdout:u,stderr:d,exitCode:f,error:p}=await yt(o,e.deploy_script,{timeout:12e4}),h=[u,d].filter(Boolean).join(`
|
|
511
512
|
`).trim();if(f!==0)return`${n==="git"?"git pull":"rsync"} OK
|
|
512
513
|
|
|
513
514
|
ERROR (deploy_script, exit ${f}):
|
|
514
|
-
${p||
|
|
515
|
+
${p||h}`;a=`
|
|
515
516
|
|
|
516
517
|
Deploy script output:
|
|
517
|
-
${
|
|
518
|
+
${h||"(no output)"}`}let c="";if(e.health_check){let u=e.health_check.trim();if(/^https?:\/\//.test(u))try{let f=require("node-fetch"),p=await Promise.race([f(u),new Promise((h,g)=>setTimeout(()=>g(new Error("timeout")),15e3))]);if(p.ok)c=`
|
|
518
519
|
|
|
519
|
-
Health check: \u2713 ${u} \u2192 ${p.status}`;else return
|
|
520
|
+
Health check: \u2713 ${u} \u2192 ${p.status}`;else return c=`
|
|
520
521
|
|
|
521
|
-
Health check FAILED: ${u} \u2192 HTTP ${p.status}`,(n==="git"?"git pull OK":"rsync OK")+i+a+
|
|
522
|
+
Health check FAILED: ${u} \u2192 HTTP ${p.status}`,(n==="git"?"git pull OK":"rsync OK")+i+a+c}catch(f){return c=`
|
|
522
523
|
|
|
523
|
-
Health check FAILED: ${u} \u2192 ${f.message}`,(n==="git"?"git pull OK":"rsync OK")+i+a+
|
|
524
|
-
`).trim();if(
|
|
524
|
+
Health check FAILED: ${u} \u2192 ${f.message}`,(n==="git"?"git pull OK":"rsync OK")+i+a+c}else{let{stdout:f,stderr:p,exitCode:h}=await yt(o,u,{timeout:15e3}),g=[f,p].filter(Boolean).join(`
|
|
525
|
+
`).trim();if(h!==0)return c=`
|
|
525
526
|
|
|
526
|
-
Health check FAILED (exit ${
|
|
527
|
+
Health check FAILED (exit ${h}): ${g}`,(n==="git"?"git pull OK":"rsync OK")+i+a+c;c=`
|
|
527
528
|
|
|
528
|
-
Health check: \u2713 ${g||"(exit 0)"}`}}let
|
|
529
|
-
${i}${a}${
|
|
529
|
+
Health check: \u2713 ${g||"(exit 0)"}`}}let l=n==="git"?`${r}:${e.remote_path}`:`${e.local_path} \u2192 ${r}:${e.remote_path}`;return`Deployed [${n}] ${l}
|
|
530
|
+
${i}${a}${c}`.trim()}case"deployment_status":{let n=YS(),o=e.config?[e.config]:Object.keys(n);if(o.length===0)return"No deploy configs found. Create .nex/deploy.json to configure deployments.";let r=[];for(let i of o){let a=n[i];if(!a){r.push(`${i}: NOT FOUND`);continue}try{let c=Dt(a.server||i),u=(await yt(c,"echo OK",{timeout:1e4})).stdout.trim()==="OK",d="unknown";if(u&&a.deploy_script){let p=a.deploy_script.match(/systemctl\s+\w+\s+(\S+)/);if(p)try{d=(await yt(c,`systemctl is-active ${p[1]}`,{timeout:1e4})).stdout.trim()}catch{d="inactive"}}let f="N/A";if(a.health_check){let p=a.health_check.trim();if(/^https?:\/\//.test(p))try{let h=require("node-fetch"),g=await Promise.race([h(p),new Promise((w,x)=>setTimeout(()=>x(new Error("timeout")),1e4))]);f=g.ok?"healthy":`HTTP ${g.status}`}catch(h){f=`unhealthy: ${h.message.substring(0,50)}`}else try{f=(await yt(c,p,{timeout:1e4})).exitCode===0?"healthy":"unhealthy"}catch{f="unhealthy"}}r.push(`${i}: server=${u?"reachable":"unreachable"} service=${d} health=${f}`)}catch(c){r.push(`${i}: ERROR \u2014 ${c.message}`)}}return`Deployment Status:
|
|
530
531
|
${r.join(`
|
|
531
|
-
`)}`}case"frontend_recon":{let n=process.cwd(),o=(e.type||"").toLowerCase(),r=[],i=async(v
|
|
532
|
-
`),
|
|
533
|
-
`);return
|
|
534
|
-
... (${
|
|
535
|
-
`).filter(Boolean)}catch{return[]}},u=async(v
|
|
532
|
+
`)}`}case"frontend_recon":{let n=process.cwd(),o=(e.type||"").toLowerCase(),r=[],i=async(E,v=120)=>{try{let A=ue.isAbsolute(E)?E:ue.join(n,E),oe=(await Ye.readFile(A,"utf8")).split(`
|
|
533
|
+
`),de=oe.slice(0,v).join(`
|
|
534
|
+
`);return oe.length>v?de+`
|
|
535
|
+
... (${oe.length-v} more lines \u2014 use read_file for full content)`:de}catch{return null}},c=["node_modules",".git","dist","build","vendor",".next","__pycache__","venv",".venv"].map(E=>`-not -path "*/${E}/*"`).join(" "),l=async E=>{try{let{stdout:v}=await Be(`find "${n}" -type f -name "${E}" ${c} 2>/dev/null | head -10`,{timeout:8e3});return v.trim().split(`
|
|
536
|
+
`).filter(Boolean)}catch{return[]}},u=async(E,v)=>{try{let{stdout:A}=await Be(`grep -rl "${E}" "${n}" --include="${v}" --exclude-dir=node_modules --exclude-dir=.git --exclude-dir=dist --exclude-dir=build 2>/dev/null | head -5`,{timeout:8e3});return A.trim().split(`
|
|
536
537
|
`).filter(Boolean)}catch{return[]}};r.push(`## STEP 1: Design Tokens
|
|
537
|
-
`);let d=[...await
|
|
538
|
+
`);let d=[...await l("tailwind.config.js"),...await l("tailwind.config.ts"),...await l("tailwind.config.mjs")];if(d.length>0){let E=await i(d[0],80);E&&r.push(`### Tailwind config (${ue.relative(n,d[0])})
|
|
538
539
|
\`\`\`js
|
|
539
|
-
${
|
|
540
|
-
\`\`\``)}else r.push("(no tailwind.config found)");let f=["variables.css","_variables.scss","tokens.css","base.css","global.css","main.css","index.css","app.css","style.css","styles.css"],p=!1;for(let
|
|
540
|
+
${E}
|
|
541
|
+
\`\`\``)}else r.push("(no tailwind.config found)");let f=["variables.css","_variables.scss","tokens.css","base.css","global.css","main.css","index.css","app.css","style.css","styles.css"],p=!1;for(let E of f){let v=await l(E);for(let A of v){let te=await i(A,100);if(te&&te.includes(":root")){r.push(`### CSS Variables (${ue.relative(n,A)})
|
|
541
542
|
\`\`\`css
|
|
542
|
-
${
|
|
543
|
-
\`\`\``),p=!0;break}}if(p)break}if(!p){let
|
|
543
|
+
${te}
|
|
544
|
+
\`\`\``),p=!0;break}}if(p)break}if(!p){let E=await u(":root","*.css");if(E.length>0){let v=await i(E[0],100);v&&r.push(`### CSS Variables (${ue.relative(n,E[0])})
|
|
544
545
|
\`\`\`css
|
|
545
|
-
${
|
|
546
|
+
${v}
|
|
546
547
|
\`\`\``),p=!0}}p||r.push("(no CSS custom properties / :root found)"),r.push(`
|
|
547
548
|
## STEP 2: Main Layout / Index Page
|
|
548
|
-
`);let
|
|
549
|
+
`);let h=["base.html","_base.html","layout.html","base.jinja","App.vue","App.jsx","App.tsx","_app.jsx","_app.tsx","_app.js","layout.vue","index.html"],g=!1;for(let E of h){let v=await l(E);if(v.length>0){let A=await i(v[0],150);if(A){r.push(`### Main layout: ${ue.relative(n,v[0])}
|
|
549
550
|
\`\`\`html
|
|
550
|
-
${
|
|
551
|
+
${A}
|
|
551
552
|
\`\`\``),g=!0;break}}}g||r.push("(no main layout/index file found \u2014 try read_file on your root template manually)"),r.push(`
|
|
552
553
|
## STEP 3: Reference Component (same type)
|
|
553
|
-
`);let
|
|
554
|
-
`).filter(Boolean)}catch{
|
|
554
|
+
`);let w=[];if(o){for(let E of["*.html","*.vue","*.jsx","*.tsx"])if(w=await u(o,E),w.length>0)break}if(w.length===0)try{let{stdout:E}=await Be(`find "${n}" -type f \\( -name "*.html" -o -name "*.vue" -o -name "*.jsx" -o -name "*.tsx" \\) -not -path "*/node_modules/*" -not -path "*/.git/*" -not -path "*/dist/*" -not -path "*/build/*" -not -name "base.html" -not -name "_base.html" -not -name "layout.html" -not -name "App.vue" -not -name "App.jsx" 2>/dev/null | head -20`,{timeout:8e3});w=E.trim().split(`
|
|
555
|
+
`).filter(Boolean)}catch{w=[]}if(w.length>0){let E=w[0],v=await i(E,150);v?r.push(`### Reference: ${ue.relative(n,E)}
|
|
555
556
|
\`\`\`html
|
|
556
|
-
${
|
|
557
|
+
${v}
|
|
557
558
|
\`\`\``):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(`
|
|
558
559
|
## STEP 4: Framework Stack
|
|
559
|
-
`);let
|
|
560
|
+
`);let x=[],O=await i(ue.join(n,"package.json"),999);if(O){if((O.includes('"react"')||O.includes("'react'"))&&x.push("React"),O.includes('"vue"')||O.includes("'vue'")){let v=O.match(/"vue":\s*"[\^~]?(\d+)/);x.push(v?`Vue.js v${v[1]}`:"Vue.js")}let E=O.match(/"alpinejs":\s*"[\^~]?(\d+)/);E&&x.push(`Alpine.js v${E[1]} (\u26A0 v2 vs v3 API differs!)`),(O.includes('"htmx')||O.includes("'htmx"))&&x.push("HTMX"),O.includes('"tailwindcss"')&&x.push("Tailwind CSS"),O.includes('"bootstrap"')&&x.push("Bootstrap")}if((await Rt(ue.join(n,"manage.py"))||(await i(ue.join(n,"requirements.txt"),50)||"").includes("Django"))&&x.push("Django (server-rendered templates)"),!x.some(E=>E.includes("Alpine"))){let E=await u("alpinejs","*.html");if(E.length>0){let A=(await i(E[0],30)||"").match(/alpinejs[@/]v?(\d)/);x.push(A?`Alpine.js v${A[1]} (via CDN \u2014 \u26A0 v2 vs v3 API differs!)`:"Alpine.js (via CDN \u2014 check version!)")}}return x.some(E=>E.includes("HTMX"))||(await u("htmx","*.html")).length>0&&x.push("HTMX (via CDN)"),x.length>0?(r.push(x.map(E=>`- ${E}`).join(`
|
|
560
561
|
`)),r.push(`
|
|
561
562
|
\u26A0 Use ONLY the frameworks listed above. Do NOT mix (e.g. no fetch() when HTMX is used for the same action).`)):r.push("(framework not detected \u2014 check package.json or script tags manually)"),r.push(`
|
|
562
563
|
---
|
|
563
564
|
\u2705 Design recon complete. Now build consistently with the patterns above.`),r.join(`
|
|
564
|
-
`)}case"sysadmin":{if(!e.action)return"ERROR: action is required";let n=!e.server||e.server==="local"||e.server==="localhost",o;if(!n)try{o=
|
|
565
|
+
`)}case"sysadmin":{if(!e.action)return"ERROR: action is required";let n=!e.server||e.server==="local"||e.server==="localhost",o;if(!n)try{o=Dt(e.server)}catch(c){return`ERROR: ${c.message}`}let r=async(c,l=3e4)=>{if(n)try{let{stdout:u,stderr:d}=await Be(c,{timeout:l});return{out:(u||d||"").trim(),exitCode:0}}catch(u){return{out:(u.stderr||u.message||"").toString().trim(),exitCode:u.code||1}}else{let{stdout:u,stderr:d,exitCode:f,error:p}=await yt(o,c,{timeout:l}),h=[u,d].filter(Boolean).join(`
|
|
565
566
|
`).trim();return{out:p&&f!==0&&!u.trim()?(p+`
|
|
566
|
-
`+
|
|
567
|
-
(no output)`}case"disk_usage":{let
|
|
568
|
-
${
|
|
569
|
-
${d}`:d}case"network_status":{let
|
|
570
|
-
${
|
|
571
|
-
${
|
|
572
|
-
${
|
|
573
|
-
${
|
|
574
|
-
${
|
|
575
|
-
${
|
|
576
|
-
|
|
577
|
-
${
|
|
578
|
-
${d}`:d}case"
|
|
579
|
-
${
|
|
580
|
-
|
|
567
|
+
`+h).trim():h,exitCode:f}}};if(!(["audit","disk_usage","process_list","network_status","ssl_check","log_tail","find_large","journalctl"].includes(e.action)||e.action==="package"&&e.package_action==="list"||e.action==="user_manage"&&["list","info"].includes(e.user_action)||e.action==="firewall"&&e.firewall_action==="status"||e.action==="cron"&&e.cron_action==="list"||e.action==="service"&&["status","list_failed"].includes(e.service_action))&&!s.autoConfirm){let c=n?"local":e.server;if(!await Kt(`sysadmin [${e.action}] on ${c} \u2014 proceed?`))return"Cancelled."}switch(e.action){case"audit":{let c=["echo '=== OS / KERNEL ==='","cat /etc/os-release 2>/dev/null | grep -E '^(NAME|VERSION)=' || uname -a","echo '=== UPTIME / LOAD ==='","uptime","echo '=== MEMORY / SWAP ==='","free -h","echo '=== DISK ==='","df -h --output=target,size,used,avail,pcent 2>/dev/null || df -h","echo '=== TOP 10 PROCESSES (CPU) ==='","ps aux --sort=-%cpu | head -11","echo '=== FAILED SYSTEMD UNITS ==='","systemctl list-units --state=failed --no-legend 2>/dev/null || echo '(systemctl not available)'","echo '=== RECENT ERRORS (journalctl) ==='","journalctl -p err --no-pager -n 15 2>/dev/null || echo '(journalctl not available)'","echo '=== LISTENING PORTS ==='","ss -tlnp 2>/dev/null || netstat -tlnp 2>/dev/null || echo '(ss/netstat not available)'"].join(" && "),{out:l,exitCode:u}=await r(c,45e3);return l||`EXIT ${u}
|
|
568
|
+
(no output)`}case"disk_usage":{let c=e.path||"/",l=Se(c),u=`df -h ${l}; echo '--- Top subdirs ---'; du -d1 -x -h ${l} 2>/dev/null | sort -rh | head -20`,{out:d,exitCode:f}=await r(u,3e4);return f!==0?`EXIT ${f}
|
|
569
|
+
${d}`:d}case"process_list":{let c=e.sort_by==="mem"?"4":"3",l=(e.limit||20)+1,u=`ps aux --sort=-${e.sort_by==="mem"?"%mem":"%cpu"} 2>/dev/null | head -${l} || ps aux | awk 'NR==1{print; next} {print | "sort -k${c} -rn"}' | head -${l}`,{out:d,exitCode:f}=await r(u,15e3);return f!==0?`EXIT ${f}
|
|
570
|
+
${d}`:d}case"network_status":{let c="ss -tlnp 2>/dev/null || netstat -tlnp 2>/dev/null; echo '--- Active connections ---'; ss -tnp 2>/dev/null | head -30",{out:l,exitCode:u}=await r(c,15e3);return u!==0?`EXIT ${u}
|
|
571
|
+
${l}`:l}case"package":{if(!e.package_action)return"ERROR: package_action is required for action=package";let{out:c}=await r("which dnf 2>/dev/null && echo dnf || (which apt-get 2>/dev/null && echo apt) || echo unknown",1e4),l=c.includes("dnf")?"dnf":c.includes("apt")?"apt":null;if(!l)return"ERROR: No supported package manager found (dnf/apt)";let u=e.packages||[];if(!u.every(rv))return"ERROR: package names contain unsafe characters";let d=u.map(Se).join(" "),f;switch(e.package_action){case"list":f=l==="dnf"?"dnf list installed 2>/dev/null | head -60":"dpkg -l | head -60";break;case"check":{let g=l==="dnf"?'dnf check-update 2>/dev/null; EC=$?; [ $EC -eq 100 ] && echo "EXIT_STATUS: updates_available" || ([ $EC -eq 0 ] && echo "EXIT_STATUS: up_to_date" || echo "EXIT_STATUS: error $EC")':"apt-get -s upgrade 2>/dev/null | tail -5",{out:w}=await r(g,6e4);return w||"(no output from package check)"}case"install":if(!d)return"ERROR: packages required for install";f=l==="dnf"?`dnf install -y ${d}`:`apt-get install -y ${d}`;break;case"remove":if(!d)return"ERROR: packages required for remove";f=l==="dnf"?`dnf remove -y ${d}`:`apt-get remove -y ${d}`;break;case"update":if(!d)return"ERROR: packages required for update (use upgrade for full system upgrade)";f=l==="dnf"?`dnf update -y ${d}`:`apt-get install -y --only-upgrade ${d}`;break;case"upgrade":f=l==="dnf"?"dnf upgrade -y":"DEBIAN_FRONTEND=noninteractive apt-get upgrade -y";break;default:return`ERROR: Unknown package_action: ${e.package_action}`}let{out:p,exitCode:h}=await r(f,12e4);return h!==0?`EXIT ${h}
|
|
572
|
+
${p}`:p||`${e.package_action} OK`}case"user_manage":{if(!e.user_action)return"ERROR: user_action is required for action=user_manage";switch(e.user_action){case"list":{let c=`awk -F: '$3 >= 1000 && $1 != "nobody" {print $1, "uid="$3, "gid="$4, "shell="$7}' /etc/passwd`,{out:l,exitCode:u}=await r(c,1e4);return u!==0?`EXIT ${u}
|
|
573
|
+
${l}`:l||"(no regular users)"}case"info":{if(!e.user)return"ERROR: user is required for user_action=info";let c=Ho(e.user);if(c)return c;let l=Se(e.user),u=`id ${l} && echo '--- Groups ---' && groups ${l} && echo '--- Last login ---' && lastlog -u ${l} 2>/dev/null`,{out:d,exitCode:f}=await r(u,1e4);return f!==0?`EXIT ${f}
|
|
574
|
+
${d}`:d}case"create":{if(!e.user)return"ERROR: user is required for user_action=create";let c=Ho(e.user);if(c)return c;if(!(e.groups||[]).every(Hm))return"ERROR: groups contain unsafe characters";let l=(e.groups||[]).map(h=>`-G ${Se(h)}`).join(" "),u=Se(e.user),d=`useradd -m ${l} ${u} && echo "User ${e.user} created"`,{out:f,exitCode:p}=await r(d,15e3);return p!==0?`EXIT ${p}
|
|
575
|
+
${f}`:f}case"delete":{if(!e.user)return"ERROR: user is required for user_action=delete";let c=Ho(e.user);if(c)return c;let u=`userdel -r ${Se(e.user)} && echo "User ${e.user} deleted"`,{out:d,exitCode:f}=await r(u,15e3);return f!==0?`EXIT ${f}
|
|
576
|
+
${d}`:d}case"add_ssh_key":{if(!e.user)return"ERROR: user is required for user_action=add_ssh_key";if(!e.ssh_key)return"ERROR: ssh_key is required for user_action=add_ssh_key";let c=Ho(e.user);if(c)return c;let u=`${`/home/${e.user}`}/.ssh`,d=`${u}/authorized_keys`,f=Se(e.user),p=`mkdir -p ${Se(u)} && chmod 700 ${Se(u)} && printf '%s
|
|
577
|
+
' ${Se(e.ssh_key)} >> ${Se(d)} && chmod 600 ${Se(d)} && chown -R ${Se(`${e.user}:${e.user}`)} ${Se(u)} && echo "SSH key added for ${e.user}"`,{out:h,exitCode:g}=await r(p,15e3);return g!==0?`EXIT ${g}
|
|
578
|
+
${h}`:h}default:return`ERROR: Unknown user_action: ${e.user_action}`}}case"firewall":{if(!e.firewall_action)return"ERROR: firewall_action is required for action=firewall";let{out:c}=await r("which firewall-cmd 2>/dev/null && echo firewalld || (which ufw 2>/dev/null && echo ufw) || echo iptables",1e4),l=c.includes("firewalld")?"firewalld":c.includes("ufw")?"ufw":"iptables",u;switch(e.firewall_action){case"status":u=l==="firewalld"?"firewall-cmd --state && firewall-cmd --list-all":l==="ufw"?"ufw status verbose":"iptables -L -n --line-numbers | head -60";break;case"allow":if(!e.port)return'ERROR: port is required for firewall allow (e.g. "80/tcp")';if(!yl(e.port))return"ERROR: port contains unsafe characters";u=l==="firewalld"?`firewall-cmd --permanent --add-port=${e.port} && firewall-cmd --reload`:l==="ufw"?`ufw allow ${Se(e.port)}`:`iptables -A INPUT -p ${e.port.includes("/")?e.port.split("/")[1]:"tcp"} --dport ${e.port.split("/")[0]} -j ACCEPT`;break;case"deny":if(!e.port)return"ERROR: port is required for firewall deny";if(!yl(e.port))return"ERROR: port contains unsafe characters";u=l==="firewalld"?`firewall-cmd --permanent --remove-port=${e.port} && firewall-cmd --reload`:l==="ufw"?`ufw deny ${Se(e.port)}`:`iptables -A INPUT -p ${e.port.includes("/")?e.port.split("/")[1]:"tcp"} --dport ${e.port.split("/")[0]} -j DROP`;break;case"remove":if(!e.port)return"ERROR: port is required for firewall remove";if(!yl(e.port))return"ERROR: port contains unsafe characters";u=l==="firewalld"?`firewall-cmd --permanent --remove-port=${e.port} && firewall-cmd --reload`:l==="ufw"?`ufw delete allow ${Se(e.port)}`:`iptables -D INPUT -p ${e.port.includes("/")?e.port.split("/")[1]:"tcp"} --dport ${e.port.split("/")[0]} -j ACCEPT 2>/dev/null || true`;break;case"reload":u=l==="firewalld"?"firewall-cmd --reload":l==="ufw"?"ufw reload":'iptables-restore < /etc/iptables/rules.v4 2>/dev/null || echo "iptables: manual reload not available"';break;default:return`ERROR: Unknown firewall_action: ${e.firewall_action}`}let{out:d,exitCode:f}=await r(u,3e4);return f!==0?`EXIT ${f}
|
|
579
|
+
${d}`:d||`firewall ${e.firewall_action} OK`}case"cron":{if(!e.cron_action)return"ERROR: cron_action is required for action=cron";if(e.user){let l=Ho(e.user);if(l)return l}let c=e.user?`-u ${Se(e.user)}`:"";switch(e.cron_action){case"list":{let l=`crontab ${c} -l 2>/dev/null || echo '(no crontab for ${e.user||"current user"})'`,{out:u}=await r(l,1e4);return u||"(empty crontab)"}case"add":{if(!e.schedule)return"ERROR: schedule is required for cron add";if(!e.command)return"ERROR: command is required for cron add";let l=`${e.schedule} ${e.command}`,u=`(crontab ${c} -l 2>/dev/null; printf '%s
|
|
580
|
+
' ${Se(l)}) | crontab ${c} - && echo "Cron entry added: ${l}"`,{out:d,exitCode:f}=await r(u,15e3);return f!==0?`EXIT ${f}
|
|
581
|
+
${d}`:d}case"remove":{if(!e.command)return"ERROR: command (substring to match) is required for cron remove";let l=e.command.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),u=`crontab ${c} -l 2>/dev/null | grep -v "${l}" | crontab ${c} - && echo "Matching cron entries removed"`,{out:d,exitCode:f}=await r(u,15e3);return f!==0?`EXIT ${f}
|
|
582
|
+
${d}`:d}default:return`ERROR: Unknown cron_action: ${e.cron_action}`}}case"ssl_check":{if(!e.domain&&!e.cert_path)return"ERROR: domain or cert_path is required for ssl_check";let c;e.cert_path?c=`
|
|
583
|
+
CERT=${Se(e.cert_path)}
|
|
581
584
|
openssl x509 -in "$CERT" -noout -subject -issuer -startdate -enddate -ext subjectAltName 2>&1 && EXPIRY=$(openssl x509 -in "$CERT" -noout -enddate 2>/dev/null | cut -d= -f2) && DAYS=$(( ( $(date -d "$EXPIRY" +%s 2>/dev/null || date -j -f "%b %d %T %Y %Z" "$EXPIRY" +%s 2>/dev/null) - $(date +%s) ) / 86400 )) && echo "Days until expiry: $DAYS"
|
|
582
|
-
`.trim():
|
|
583
|
-
DOMAIN
|
|
585
|
+
`.trim():c=`
|
|
586
|
+
DOMAIN=${Se(e.domain)}
|
|
584
587
|
LECP="/etc/letsencrypt/live/$DOMAIN/cert.pem"
|
|
585
588
|
if [ -f "$LECP" ]; then
|
|
586
589
|
echo "Source: Let's Encrypt $LECP"
|
|
@@ -599,21 +602,21 @@ if [ -n "$EXPIRY" ]; then
|
|
|
599
602
|
[ "$DAYS" -lt 14 ] && echo "WARNING: Certificate expires in less than 14 days!"
|
|
600
603
|
[ "$DAYS" -lt 0 ] && echo "CRITICAL: Certificate has EXPIRED!"
|
|
601
604
|
fi
|
|
602
|
-
`.trim();let{out:
|
|
603
|
-
${
|
|
604
|
-
${u}`:u||"(empty log)"}case"find_large":{let
|
|
605
|
-
${f}`:f||`(no files larger than ${u} in ${
|
|
606
|
-
${u}`}case"kill_process":{if(!e.pid&&!e.process_name)return"ERROR: pid or process_name is required for kill_process";let
|
|
607
|
-
${u}`:u}case"journalctl":{let
|
|
608
|
-
${u}`:u||"(no log entries)"}default:return`ERROR: Unknown sysadmin action: ${e.action}`}}case"save_memory":{let{saveMemory:n}=
|
|
609
|
-
`)}function
|
|
605
|
+
`.trim();let{out:l,exitCode:u}=await r(c,25e3),d=/notAfter=|Days until expiry:/i.test(l);return u!==0&&!d?`EXIT ${u}
|
|
606
|
+
${l}`:l||"(no cert info returned)"}case"log_tail":{if(!e.path)return"ERROR: path is required for log_tail";let l=`tail -n ${e.lines||100} ${Se(e.path)} 2>&1`,{out:u,exitCode:d}=await r(l,15e3);return d!==0?`EXIT ${d}
|
|
607
|
+
${u}`:u||"(empty log)"}case"find_large":{let c=e.path||"/",l=e.limit||20,u=e.min_size||"100M",d=`find ${Se(c)} -xdev -type f -size +${Se(u)} 2>/dev/null | xargs du -sh 2>/dev/null | sort -rh | head -${l}`,{out:f,exitCode:p}=await r(d,6e4);return p!==0?`EXIT ${p}
|
|
608
|
+
${f}`:f||`(no files larger than ${u} in ${c})`}case"service":{if(!e.service_action)return"ERROR: service_action is required for action=service";if(e.service_action!=="list_failed"&&!e.service_name)return"ERROR: service_name is required (except for list_failed)";if(e.service_name){let p=wl(e.service_name,"service_name");if(p)return p}let c=e.service_name?e.service_name.includes(".")?e.service_name:`${e.service_name}.service`:"",l;switch(e.service_action){case"status":l=`systemctl status ${c} --no-pager -l 2>&1 | head -40`;break;case"list_failed":l="systemctl list-units --state=failed --no-legend 2>/dev/null";break;case"start":l=`systemctl start ${c} && systemctl status ${c} --no-pager -l 2>&1 | head -20`;break;case"stop":l=`systemctl stop ${c} && echo "${c} stopped"`;break;case"restart":l=`systemctl restart ${c} && systemctl status ${c} --no-pager -l 2>&1 | head -20`;break;case"reload":l=`systemctl reload ${c} 2>&1 || systemctl reload-or-restart ${c} 2>&1`;break;case"enable":l=`systemctl enable ${c} && echo "${c} enabled"`;break;case"disable":l=`systemctl disable ${c} && echo "${c} disabled"`;break;default:return`ERROR: Unknown service_action: ${e.service_action}`}let{out:u,exitCode:d}=await r(l,3e4);return d===0||e.service_action==="status"&&d===3?u||`service ${e.service_action} OK`:`EXIT ${d}
|
|
609
|
+
${u}`}case"kill_process":{if(!e.pid&&!e.process_name)return"ERROR: pid or process_name is required for kill_process";let c=e.signal||"SIGTERM";if(!iv(c))return"ERROR: signal contains unsafe characters";let l;if(e.pid){if(!/^\d+$/.test(String(e.pid)))return"ERROR: pid must be numeric";l=`ps -p ${e.pid} -o pid,user,%cpu,%mem,etime,cmd 2>/dev/null && kill -${c} ${e.pid} && echo "Sent ${c} to PID ${e.pid}"`}else l=`pgrep -a ${Se(e.process_name)} 2>/dev/null | head -5 && pkill -${c} ${Se(e.process_name)} && echo "Sent ${c} to all '${e.process_name}' processes"`;let{out:u,exitCode:d}=await r(l,15e3);return d!==0?`EXIT ${d}
|
|
610
|
+
${u}`:u}case"journalctl":{let c=e.lines||100,l=["journalctl","--no-pager","-n",String(c)];e.unit&&l.push("-u",e.unit.includes(".")?e.unit:`${e.unit}.service`),e.priority&&l.push("-p",e.priority),e.since&&l.push(`--since="${e.since}"`),l.push('2>/dev/null || echo "(journalctl not available)"');let{out:u,exitCode:d}=await r(l.join(" "),2e4);return d!==0?`EXIT ${d}
|
|
611
|
+
${u}`:u||"(no log entries)"}default:return`ERROR: Unknown sysadmin action: ${e.action}`}}case"save_memory":{let{saveMemory:n}=qo(),o=n(e.type,e.name,e.content,e.description);return o.ok?o.updated===!1?`Memory unchanged (duplicate): ${e.type}/${e.name}`:`Memory saved: ${e.type}/${e.name} \u2192 ${o.path}`:`ERROR: ${o.error}`}case"delete_memory":{let{deleteMemory:n}=qo();return n(e.type,e.name)?`Memory deleted: ${e.type}/${e.name}`:`Memory not found: ${e.type}/${e.name}`}default:{let{executePluginTool:n}=Qr(),o=await n(t,e,s);return o!==null?o:`ERROR: Unknown tool: ${t}`}}}async function cv(t,e,s={}){let{emit:n}=Qr(),{logToolExecution:o}=Tm(),r=Date.now(),i=s.silent?null:IS(t,e);if(!i){let c=await Dm(t,e,s);return o({tool:t,args:e,result:c,duration:Date.now()-r,success:!c.startsWith?.("ERROR")}),await n("onToolResult",{tool:t,args:e,result:c}),c}let a=new LS(i);a.start();try{let c=await Dm(t,e,s);return a.stop(),o({tool:t,args:e,result:c,duration:Date.now()-r,success:!c.startsWith?.("ERROR")}),await n("onToolResult",{tool:t,args:e,result:c}),c}catch(c){throw a.stop(),o({tool:t,args:e,result:c.message,duration:Date.now()-r,success:!1}),c}}Ym.exports={TOOL_DEFINITIONS:av,executeTool:cv,resolvePath:rt,autoFixPath:Oi,autoFixEdit:Wm,enrichBashError:Um,cancelPendingAskUser:ZS,setAskUserHandler:QS,fileExists:Rt}});var Ls=J((RC,zm)=>{zm.exports=Gm()});var xl=J((AC,Km)=>{var{loadServerProfiles:zo,resolveProfile:CC,sshExec:lv}=js(),_l={almalinux9:["Package manager: dnf (NOT apt). Install: dnf install <pkg>. Update: dnf update.","Service manager: systemctl. Logs: journalctl -u <service> -n 50.","Firewall: firewalld. Check: firewall-cmd --list-all. Open port: firewall-cmd --permanent --add-port=PORT/tcp && firewall-cmd --reload.","SELinux is active by default. Check: getenforce. Diagnose: ausearch -m avc -ts recent | audit2why. Fix context: restorecon -Rv /path.","Nginx config: /etc/nginx/. Test: nginx -t. Reload: systemctl reload nginx.","Process list: ps aux. Ports: ss -tuln.","Python: python3. Pip: pip3. Virtualenv: python3 -m venv."],almalinux8:["Package manager: dnf (NOT apt). Install: dnf install <pkg>. Update: dnf update.","Service manager: systemctl. Logs: journalctl -u <service> -n 50.","Firewall: firewalld. Check: firewall-cmd --list-all.","SELinux is active by default. Check: getenforce. Diagnose: ausearch -m avc -ts recent."],ubuntu:["Package manager: apt. Install: apt install <pkg>. Update: apt update && apt upgrade.","Service manager: systemctl. Logs: journalctl -u <service> -n 50.","Firewall: ufw. Status: ufw status. Allow port: ufw allow PORT/tcp.","SELinux NOT active by default (AppArmor instead). Check: aa-status."],debian:["Package manager: apt. Install: apt install <pkg>. Update: apt update && apt upgrade.","Service manager: systemctl. Logs: journalctl -u <service> -n 50.","Firewall: ufw or iptables."],macos:["Package manager: Homebrew (brew). Install: brew install <pkg>. Update: brew update && brew upgrade.","Service manager: launchctl (NOT systemctl). Start: brew services start <name>. List: brew services list.",`No systemd. No journalctl. Use: log show --predicate 'process == "nginx"' --last 1h instead.`,"Firewall: macOS built-in (pfctl or System Settings). Check: pfctl -s rules.","Process list: ps aux. Ports: lsof -i -n -P | grep LISTEN."]};function uv(){let t=zo();if(Object.keys(t).length===0)return null;let s=["## Remote Servers (.nex/servers.json)"];s.push(""),s.push("Available server profiles (use with ssh_exec, ssh_upload, ssh_download, service_manage, service_logs, container_list, container_logs, container_exec, container_manage, deploy):");for(let[o,r]of Object.entries(t)){let i=r.user?`${r.user}@${r.host}`:r.host,a=r.port&&Number(r.port)!==22?`:${r.port}`:"",c=r.os?` \u2014 OS: ${r.os}`:"",l=r.sudo?", sudo available":"";s.push(`- **${o}**: ${i}${a}${c}${l}`)}let n=new Set;for(let o of Object.values(t))o.os&&_l[o.os]&&n.add(o.os);if(n.size>0){s.push("");for(let o of n){let r={almalinux9:"AlmaLinux 9",almalinux8:"AlmaLinux 8",ubuntu:"Ubuntu",debian:"Debian",macos:"macOS"}[o]||o;s.push(`### ${r} Notes`);for(let i of _l[o])s.push(`- ${i}`)}}return s.join(`
|
|
612
|
+
`)}function dv(t){let e=zo();return Object.values(e).some(s=>s.os&&s.os.startsWith(t))}function fv(){return Object.keys(zo())}function pv(){let t=require("fs"),s=require("path").join(process.cwd(),"NEX.md"),n="";try{n=t.readFileSync(s,"utf-8")}catch{}let o=zo(),r=Object.keys(o);if(r.length===0)return null;let i=["server","deploy","remote","ssh","service","systemctl","production","linux","almalinux","ubuntu","debian"],a=n.toLowerCase();if(!i.some(f=>a.includes(f)))return null;let l=r.map(f=>{let p=o[f],h=p.user?`${p.user}@${p.host}`:p.host,g=p.port&&Number(p.port)!==22?`:${p.port}`:"";return` - **${f}**: ${h}${g}${p.os?` (${p.os})`:""}`}).join(`
|
|
610
613
|
`),u=r.map(f=>o[f].log_path).filter(Boolean),d=u.length>0?`
|
|
611
614
|
- Server log paths: ${u.join(", ")}`:"";return`# Deployment Context (Auto-detected)
|
|
612
615
|
|
|
613
616
|
This project is deployed on a **remote server**. The application runs as a service there \u2014 NOT locally.
|
|
614
617
|
|
|
615
618
|
## Configured Servers
|
|
616
|
-
${
|
|
619
|
+
${l}
|
|
617
620
|
|
|
618
621
|
## Critical Debugging Rules
|
|
619
622
|
|
|
@@ -624,7 +627,7 @@ ${c}
|
|
|
624
627
|
- \u274C Do NOT \`read_file\` on paths like \`logs/\` \u2014 these files do not exist locally
|
|
625
628
|
- \u274C Do NOT \`list_directory\` on server paths \u2014 the local project is the source, not the running instance
|
|
626
629
|
|
|
627
|
-
**When in doubt:** If a path contains \`logs/\`, \`/var/log/\`, or \`/home/<user>/\` \u2014 it is on the server. SSH there.${
|
|
630
|
+
**When in doubt:** If a path contains \`logs/\`, \`/var/log/\`, or \`/home/<user>/\` \u2014 it is on the server. SSH there.${hv(o)}`}function hv(t){return Object.values(t).some(s=>s.host==="94.130.37.43")?`
|
|
628
631
|
|
|
629
632
|
## Server Debugging Rules
|
|
630
633
|
|
|
@@ -635,35 +638,36 @@ ${c}
|
|
|
635
638
|
- CRITICAL: When the user pastes a server error message (error logs), this is NEVER a "simple question" to answer from training knowledge. You MUST ssh_exec to verify if the error is still occurring BEFORE writing any explanation. Do NOT explain from memory \u2014 investigate first, always.
|
|
636
639
|
- LOG FILES: Always check the CURRENT log first: /home/deploy/server-agent/logs/api-error.log (no date suffix). Log files WITH a date suffix (e.g. api-error.log-20260322) are ROTATED/OLD \u2014 errors there may already be fixed. Only look at dated logs if the current log is empty or the error is absent from the current log.
|
|
637
640
|
- FIX WORKFLOW (YOLO): Once you identify a fixable bug via SSH investigation: (1) edit the file on server using ssh_exec with tee or sed -i (NOT sed -n), (2) restart the affected service with systemctl restart, (3) verify with tail logs. Do NOT produce a report \u2014 execute the fix.
|
|
638
|
-
- 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
|
|
639
|
-
`+i.trim()}catch{return null}}
|
|
640
|
-
`)
|
|
641
|
-
`)
|
|
642
|
-
`).
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
${v.trim()}`)}let
|
|
647
|
-
${v.trim()}`)}
|
|
648
|
-
|
|
649
|
-
|
|
641
|
+
- 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 mv(t){if(typeof t!="string")return null;let e=[...t.matchAll(/https?:\/\/([a-zA-Z0-9._-]+)/g)];if(e.length===0)return null;let s=zo();if(Object.keys(s).length===0)return null;let n=null,o=null;for(let[,i]of e){let a=i.toLowerCase().split(".");for(let[c,l]of Object.entries(s))if(a.includes(c.toLowerCase())){n=l,o=c;break}if(n)break;for(let[c,l]of Object.entries(s))if(l.host===i){n=l,o=c;break}if(n)break}if(!n||!o)return null;let r=["ss -tlnp 2>/dev/null | awk 'NR>1{print $4}' | grep -oE ':[0-9]+$' | sort -u | head -8","echo '---services---'","ps aux 2>/dev/null | grep -E '(node |python3 |gunicorn|uvicorn|ruby |java )' | grep -v grep | awk '{print $11, $12, $13}' | head -6","echo '---data---'","find /home -maxdepth 5 -name 'data' -type d 2>/dev/null | head -6"].join("; ");try{let{stdout:i}=await lv(n,r,{timeout:4e3});if(!i||i.trim().length<5)return null;let a=n.user?`${n.user}@${n.host}`:n.host;return`[Server context for "${o}" (${a}) \u2014 probed at task start]
|
|
642
|
+
`+i.trim()}catch{return null}}Km.exports={getServerContext:uv,getDeploymentContextBlock:pv,hasServerOS:dv,getProfileNames:fv,probeUrlServer:mv,OS_HINTS:_l}});var Zm=J((OC,Jm)=>{var wt=require("fs").promises,Mi=require("fs"),Ue=require("path"),Ni=require("util").promisify(require("child_process").exec),{C:Ks}=Je(),{getMergeConflicts:Vm}=Kr(),{getServerContext:gv}=xl(),{refreshIndex:yv,getFileIndex:wv,buildContentIndex:$v,summarizeModuleHubs:bv}=gn(),_v=new Set(["node_modules",".git",".svn","dist","build","coverage",".nyc_output","__pycache__",".DS_Store",".next",".nuxt",".turbo",".cache","vendor","tmp","temp"]),xv=[{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 kv(t,e=6){let s=new Map;for(let n of t){let o=n.includes("/")?n.split("/")[0]:"(root)";!o||o.startsWith(".")||s.set(o,(s.get(o)||0)+1)}return[...s.entries()].sort((n,o)=>o[1]-n[1]||n[0].localeCompare(o[0])).slice(0,e).map(([n,o])=>`${n} (${o})`)}function Sv(t){let e=new Set(t),s=new Set;for(let n of xv)(e.has(n.file)||[...e].some(o=>o.startsWith(`${n.file}/`)))&&s.add(n.label);return e.has("package.json")&&s.add("Node.js"),[...e].some(n=>/^tests?\//.test(n)||/\.test\./.test(n)||/\.spec\./.test(n))&&s.add("Tests"),[...e].some(n=>n.startsWith("vscode/"))&&s.add("VS Code Extension"),[...s]}function vv(t){let e=["package.json","cli/index.js","src/index.ts","src/index.js","index.ts","index.js","bin/nex-code.js","dist/nex-code.js","README.md"],s=[];for(let n of e)if(t.includes(n)&&s.push(n),s.length>=5)break;return s}function Ev(t,e=6){let s=t.filter(r=>/^tests?\//.test(r)||/\.test\./.test(r)||/\.spec\./.test(r));if(s.length===0)return[];let n=t.filter(r=>!/^tests?\//.test(r)&&!/\.test\./.test(r)&&!/\.spec\./.test(r)&&/\.(js|jsx|ts|tsx|py|go|rs|java)$/.test(r)),o=[];for(let r of n){let i=Ue.basename(r).replace(/\.[^.]+$/,"");if(i.length<3)continue;let a=s.filter(c=>c.includes(i));if(a.length>0&&o.push(`${r} -> ${a.slice(0,2).join(", ")}`),o.length>=e)break}return o}function Tv(t){return!t||!t.workspaces?[]:Array.isArray(t.workspaces)?t.workspaces:Array.isArray(t.workspaces.packages)?t.workspaces.packages:[]}async function Rv(t){try{await yv(t);let e=wv();if(!e||e.length===0)return"";let s=Sv(e),n=kv(e),o=vv(e),r=e.filter(d=>/^tests?\//.test(d)||/\.test\./.test(d)||/\.spec\./.test(d)).length,i=Ev(e),a=[];try{let d=Ue.join(t,"package.json");if(Mi.existsSync(d)){let f=JSON.parse(Mi.readFileSync(d,"utf-8"));a=Tv(f)}}catch{}let c="",l="";try{let d=await $v(t),f=Object.entries(d.files||{}).map(([p,h])=>({file:p,defs:Array.isArray(h.defs)?h.defs.length:0})).filter(p=>p.defs>0).sort((p,h)=>h.defs-p.defs||p.file.localeCompare(h.file)).slice(0,4).map(p=>`${p.file} (${p.defs} defs)`);f.length>0&&(c=`CODE HOTSPOTS: ${f.join(", ")}`)}catch{}try{let d=await bv(t,4);d.length>0&&(l=`MODULE HUBS: ${d.join(", ")}`)}catch{}let u=[`REPO MAP: ${e.length} indexed files${s.length?` | stack: ${s.join(", ")}`:""}`];return n.length>0&&u.push(`WORK AREAS: ${n.join(", ")}`),o.length>0&&u.push(`LIKELY ENTRY POINTS: ${o.join(", ")}`),a.length>0&&u.push(`WORKSPACES: ${a.join(", ")}`),r>0&&u.push(`TEST FOOTPRINT: ${r} test files detected`),i.length>0&&u.push(`TEST MAP: ${i.join(" | ")}`),c&&u.push(c),l&&u.push(l),u.push("RETRIEVAL RULE: Prefer the smallest verified path set first \u2014 identify likely files, then read only the exact symbols/sections you need before editing."),u.join(`
|
|
643
|
+
`)}catch{return""}}function Cv(t){try{return Mi.readFileSync(t,"utf-8").split(`
|
|
644
|
+
`).map(s=>s.trim()).filter(s=>s&&!s.startsWith("#")&&!s.startsWith("!")).map(s=>s.replace(/\/$/,""))}catch{return[]}}function Av(t,e){for(let s of e)if(s===t||s.includes("*")&&new RegExp("^"+s.replace(/\./g,"\\.").replace(/\*/g,".*")+"$").test(t))return!0;return!1}function Ov(t,{maxDepth:e=3,maxFiles:s=200,giPatterns:n=[]}={}){let o=Ue.join(t,".gitignore"),r=[...n,...Cv(o)],i=0,a=[Ue.basename(t)+"/"];function c(l,u,d){if(d>e||i>=s)return;let f;try{f=Mi.readdirSync(l,{withFileTypes:!0})}catch{return}f.sort((h,g)=>h.isDirectory()!==g.isDirectory()?h.isDirectory()?-1:1:h.name.localeCompare(g.name));let p=f.filter(h=>!(_v.has(h.name)||h.name.startsWith(".")&&h.name!==".env.example"||Av(h.name,r)));for(let h=0;h<p.length;h++){if(i>=s){a.push(`${u}\u2514\u2500\u2500 \u2026 (truncated)`);break}let g=p[h],w=h===p.length-1,x=w?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",O=u+(w?" ":"\u2502 "),I=g.isDirectory()?g.name+"/":g.name;a.push(`${u}${x}${I}`),i++,g.isDirectory()&&c(Ue.join(l,g.name),O,d+1)}}return c(t,"",1),a.join(`
|
|
645
|
+
`)}var kl=new Map,Vs=new Map,Pi=null,Xm=3e4,Xs={result:null,expiry:0,cwd:null};async function an(t){try{return await t()}catch{return null}}async function Nv(){if(!Pi||Date.now()>Pi)return!1;let t=[Ue.join(process.cwd(),"package.json"),Ue.join(process.cwd(),"README.md"),Ue.join(process.cwd(),".gitignore")];for(let e of t)try{let s=await wt.stat(e),n=Vs.get(e);if(!n||s.mtimeMs!==n)return!1}catch{if(Vs.has(e))return!1}try{let e=Ue.join(process.cwd(),".git","HEAD"),s=await wt.stat(e),n=Vs.get(e);if(!n||s.mtimeMs!==n)return!1}catch{}return!0}async function Mv(){let t=[Ue.join(process.cwd(),"package.json"),Ue.join(process.cwd(),"README.md"),Ue.join(process.cwd(),".gitignore"),Ue.join(process.cwd(),".git","HEAD"),Ue.join(process.cwd(),"CLAUDE.md"),Ue.join(process.cwd(),".nex","CLAUDE.md")];for(let e of t)try{let s=await wt.stat(e);Vs.set(e,s.mtimeMs)}catch{Vs.delete(e)}}async function Pv(t){let e="fileContext",s=kl.get(e),n=!1;if(s&&await Nv()&&(n=!0),!n){let l=[],u=Ue.join(t,"package.json");if(await an(()=>wt.access(u).then(()=>!0).catch(()=>!1)))try{let v=await wt.readFile(u,"utf-8"),A=JSON.parse(v),te={name:A.name,version:A.version};A.scripts&&(te.scripts=Object.keys(A.scripts).slice(0,15)),A.dependencies&&(te.deps=Object.keys(A.dependencies).length),A.devDependencies&&(te.devDeps=Object.keys(A.devDependencies).length),l.push(`PACKAGE: ${JSON.stringify(te)}`)}catch{}let f=Ue.join(t,"README.md");if(await an(()=>wt.access(f).then(()=>!0).catch(()=>!1))){let A=(await wt.readFile(f,"utf-8")).split(`
|
|
646
|
+
`).slice(0,50);l.push(`README (first 50 lines):
|
|
647
|
+
${A.join(`
|
|
648
|
+
`)}`)}let h=Ue.join(t,".gitignore");if(await an(()=>wt.access(h).then(()=>!0).catch(()=>!1))){let v=await wt.readFile(h,"utf-8");l.push(`GITIGNORE:
|
|
649
|
+
${v.trim()}`)}let w=Ue.join(t,"CLAUDE.md");if(await an(()=>wt.access(w).then(()=>!0).catch(()=>!1))){let v=await wt.readFile(w,"utf-8");v.trim()&&l.push(`PROJECT INSTRUCTIONS (CLAUDE.md):
|
|
650
|
+
${v.trim()}`)}let O=Ue.join(t,".nex","CLAUDE.md");if(await an(()=>wt.access(O).then(()=>!0).catch(()=>!1))){let v=await wt.readFile(O,"utf-8");v.trim()&&l.push(`PRIVATE PROJECT INSTRUCTIONS (.nex/CLAUDE.md):
|
|
651
|
+
${v.trim()}`)}let E=await Rv(t);E&&l.push(E),s=l.join(`
|
|
652
|
+
|
|
653
|
+
`),kl.set(e,s),Pi=Date.now()+Xm,await Mv()}let o=[s],r,i,a,c;if(Xs.result&&Date.now()<Xs.expiry&&Xs.cwd===t?{branch:r,status:i,log:a,conflicts:c}=Xs.result:([r,i,a,c]=await Promise.all([an(async()=>{let{stdout:l}=await Ni("git branch --show-current",{cwd:t,timeout:5e3});return l.trim()}),an(async()=>{let{stdout:l}=await Ni("git status --short",{cwd:t,timeout:5e3});return l.trim()}),an(async()=>{let{stdout:l}=await Ni("git log --oneline -5",{cwd:t,timeout:5e3});return l.trim()}),Vm()]),Xs={result:{branch:r,status:i,log:a,conflicts:c},expiry:Date.now()+Xm,cwd:t}),r&&o.push(`GIT BRANCH: ${r}`),i&&o.push(`GIT STATUS:
|
|
650
654
|
${i}`),a&&o.push(`RECENT COMMITS:
|
|
651
|
-
${a}`),
|
|
655
|
+
${a}`),c&&c.length>0){let l=c.map(u=>` ${u.file}`).join(`
|
|
652
656
|
`);o.push(`MERGE CONFLICTS (resolve before editing these files):
|
|
653
|
-
${
|
|
654
|
-
|
|
655
|
-
`)}async function jS(t){let e=Ge.join(t,"package.json"),s="";if(await tn(()=>mt.access(e).then(()=>!0).catch(()=>!1)))try{let i=await mt.readFile(e,"utf-8"),a=JSON.parse(i);s=`${a.name||"?"} v${a.version||"?"}`}catch{}let[o,r]=await Promise.all([tn(async()=>{let{stdout:i}=await Si("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),Em()]);if(r&&r.length>0){console.log(`${Ys.red} \u26A0 ${r.length} unresolved merge conflict(s):${Ys.reset}`);for(let i of r)console.log(`${Ys.red} ${i.file}${Ys.reset}`);console.log(`${Ys.yellow} \u2192 Resolve conflicts before starting tasks${Ys.reset}`)}console.log()}Tm.exports={gatherProjectContext:DS,printContext:jS,generateFileTree:PS,_clearContextCache:()=>{cc.clear(),zs.clear(),vi=null,Gs={result:null,expiry:0,cwd:null}}}});var Ti=Q((N1,Om)=>{var Yt=require("fs"),Ei=require("path"),{atomicWrite:qS}=Fn();function Wo(){return Ei.join(process.cwd(),".nex","sessions")}function uc(){let t=Wo();Yt.existsSync(t)||Yt.mkdirSync(t,{recursive:!0,mode:448})}function dc(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return Ei.join(Wo(),`${e}.json`)}function fc(t,e,s={}){uc();let n=dc(t),o={name:t,createdAt:s.createdAt||new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:e.length,model:s.model||null,provider:s.provider||null,messages:e};return qS(n,JSON.stringify(o,null,2)),{path:n,name:t}}function Cm(t){let e=dc(t);if(!Yt.existsSync(e))return null;try{return JSON.parse(Yt.readFileSync(e,"utf-8"))}catch{return null}}function Am(){uc();let t=Wo(),e=Yt.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(Yt.readFileSync(Ei.join(t,n),"utf-8"));s.push({name:o.name||n.replace(".json",""),createdAt:o.createdAt,updatedAt:o.updatedAt,messageCount:o.messageCount||0,model:o.model,provider:o.provider,score:o.score!=null?o.score:null,scoreGrade:o.scoreGrade||null})}catch{}return s.sort((n,o)=>(o.updatedAt||"").localeCompare(n.updatedAt||""))}function FS(t){let e=dc(t);return Yt.existsSync(e)?(Yt.unlinkSync(e),!0):!1}function BS(){let t=Am();return t.length===0?null:Cm(t[0].name)}var ns=null,hn=null,Uo=null;function US(t,e={}){t.length!==0&&(ns&&clearTimeout(ns),hn=t,Uo=e||{},ns=setTimeout(()=>{hn&&hn.length>0&&fc("_autosave",hn,Uo),ns=null,hn=null,Uo=null},5e3))}function WS(){ns&&(clearTimeout(ns),ns=null),hn&&hn.length>0&&(fc("_autosave",hn,Uo),hn=null,Uo=null)}function HS(){uc();let t=Wo(),e=Yt.readdirSync(t).filter(r=>r.endsWith(".json")),s=new Date,n=new Date(s.getTime()-720*60*60*1e3),o=0;for(let r of e){let i=Ei.join(t,r);try{let a=Yt.statSync(i);new Date(a.mtime)<n&&(Yt.unlinkSync(i),o++)}catch{}}return o}Om.exports={saveSession:fc,loadSession:Cm,listSessions:Am,deleteSession:FS,getLastSession:BS,autoSave:US,flushAutoSave:WS,clearOldSessions:HS,_getSessionsDir:Wo}});var Ri=Q((M1,qm)=>{"use strict";var Ho=require("fs"),Nm=require("path");function Mm(t){let e=[];return t.forEach((s,n)=>{s.role==="assistant"&&(Array.isArray(s.content)&&s.content.forEach(o=>{o&&o.type==="tool_use"&&e.push({name:o.name||"",input:o.input||{},index:n,id:o.id||null})}),Array.isArray(s.tool_calls)&&s.tool_calls.forEach(o=>{let r=o.function?.name||o.name||"",i={};try{i=typeof o.function?.arguments=="string"?JSON.parse(o.function.arguments):o.function?.arguments||o.input||{}}catch{}e.push({name:r,input:i,index:n,id:o.id||null})}))}),e}function YS(t){let e=new Set;return t.forEach(s=>{s.role==="tool"&&typeof s.content=="string"&&s.content.startsWith("BLOCKED:")&&s.tool_call_id&&e.add(s.tool_call_id),s.role==="user"&&Array.isArray(s.content)&&s.content.forEach(n=>{n&&n.type==="tool_result"&&n.tool_use_id&&typeof n.content=="string"&&n.content.startsWith("BLOCKED:")&&e.add(n.tool_use_id)})}),e}function Pm(t){let e=[];return t.forEach((s,n)=>{if(s.role==="user"&&Array.isArray(s.content)&&s.content.forEach(o=>{if(o&&o.type==="tool_result"){let r=typeof o.content=="string"?o.content:Array.isArray(o.content)?o.content.map(i=>typeof i=="string"?i:i.text||"").join(""):JSON.stringify(o.content||"");e.push({content:r,index:n})}}),s.role==="tool"){let o=typeof s.content=="string"?s.content:JSON.stringify(s.content||"");e.push({content:o,index:n})}}),e}function Lm(t){for(let e=t.length-1;e>=0;e--){let s=t[e];if(s.role==="assistant"){if(typeof s.content=="string")return s.content.trim();if(Array.isArray(s.content)){let n=s.content.filter(o=>o&&(o.type==="text"||typeof o=="string")).map(o=>typeof o=="string"?o:o.text||"").join("").trim();if(n)return n}}}return""}function Im(t,e){let s=[];for(let n=t.length-1;n>=0&&s.length<e;n--){let o=t[n];if(o.role!=="assistant")continue;let r="";typeof o.content=="string"?r=o.content.trim():Array.isArray(o.content)&&(r=o.content.filter(i=>i&&(i.type==="text"||typeof i=="string")).map(i=>typeof i=="string"?i:i.text||"").join("").trim()),r&&s.push(r)}return s}function Dm(t){let e=new Map;for(let s of t){let n;try{n=JSON.stringify(s.input)}catch{n=String(s.input)}let o=`${s.name}|${n}`;e.set(o,(e.get(o)||0)+1)}return e}function jm(t){if(!Array.isArray(t)||t.length===0)return{score:0,issues:["Empty or invalid session \u2014 no messages to analyse"],summary:"No messages found"};let e=10,s=[],n=Mm(t),o=Pm(t),r=n.length,i=YS(t),a=n.filter($=>!$.id||!i.has($.id));t.some($=>$.role==="user"&&typeof $.content=="string"&&$.content.startsWith("[SYSTEM WARNING]")&&($.content.includes("edited")||$.content.includes("bash command")||$.content.includes("grep pattern")||$.content.includes("re-read")||$.content.includes("already in your context")))&&(e-=2,s.push("Loop-warning was fired during session (repeated file edits, bash commands, or re-reads)"));let c=n.find($=>{let I=$.input?.command||$.input?.cmd||"";return/\bsed\s+-n\b/.test(I)});if(c){let $=(c.input?.command||c.input?.cmd||"").slice(0,80);o.some(H=>H.content.includes("BLOCKED: sed -n is forbidden")||H.content.includes("BLOCKED: sed -n"))?(e-=.25,s.push(`sed -n attempted but blocked by agent guard: ${$}`)):(e-=1.5,s.push(`sed -n anti-pattern used: ${$}`))}n.find($=>{if($.name!=="grep"&&$.name!=="bash"&&$.name!=="ssh_exec")return!1;let I=$.input?.command||$.input?.cmd||"",H=$.input?.pattern||"",N=`${I} ${H}`;return/(?:-[CAB]|--context|--after|--before)\s*[=\s]?([2-9][1-9]|\d{3,})/.test(N)||/grep.*-[CAB]\s*([2-9][1-9]|\d{3,})/.test(N)})&&(e-=1,s.push("grep used with >20 context lines (context flood risk)"));let d=t.some($=>$.role==="assistant"),f=Lm(t),m=Im(t,3).some($=>$.length>100&&!/^[^.!]{0,40}\?$/.test($));if(d&&!m&&(f.length<80||/^[^.!]{0,40}\?$/.test(f))){e-=2;let $=f.length>0?`"${f.slice(0,60)}..."`:"(no assistant text found)";s.push(`Session ends without diagnosis \u2014 last response too short or is only a question: ${$}`)}r>40?(e-=1.5,s.push(`Excessive tool calls: ${r} (>40 threshold)`)):r>25&&(e-=.5,s.push(`High tool call count: ${r} (>25 threshold)`)),t.some($=>{let I=typeof $.content=="string"?$.content:Array.isArray($.content)?$.content.map(H=>typeof H=="string"?H:H.text||"").join(""):"";return/\[auto-compressed|context compacted|force-compressed/.test(I)})&&(e-=.5,s.push("Auto-compress triggered (context flood indicator)"));let b=Dm(a),A=0,P="";for(let[$,I]of b)I>A&&(A=I,P=$);if(A>=3){let[$]=P.split("|");e-=1,s.push(`Same tool call repeated ${A}\xD7 (tool: ${$})`)}let v=!1,E=t.findIndex($=>$.role==="user"&&typeof $.content=="string"&&$.content.includes("[SYSTEM STOP]")&&$.content.includes('"valid":true'));E>=0&&n.filter(I=>I.index>E).length>0&&(v=!0),v&&(e-=1.5,s.push('Stop-trigger ignored: tool result contained "valid":true but session continued with more tool calls'));let O=n.filter($=>$.name==="ssh_exec");if(O.length>=8){let $=0,I=1;for(let H=1;H<O.length;H++)O[H].index<=O[H-1].index+2?I++:($=Math.max($,I),I=1);$=Math.max($,I),$>=8&&(e-=.5,s.push(`SSH reconnect storm: ${$} consecutive SSH calls`))}d&&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(f)&&(e-=2,s.push("Surrender: model asked user to manually provide server output instead of gathering it"));let ne=new Map;for(let $ of a)if($.name==="read_file"&&$.input?.path){let I=$.input.path;ne.has(I)||ne.set(I,{count:0,ranges:[]});let H=ne.get(I);if(H.count++,$.input.line_start!=null){let N=$.input.line_start||1,q=$.input.line_end||N+350;H.ranges.push([N,q])}}function J($,I,H){for(let[N,q]of H){let x=Math.max($,N),Y=Math.min(I,q);if(Y>x){let ke=Y-x,pe=I-$||1;if(ke/pe>=.7)return!0}}return!1}let ie=0,ce="";for(let[$,I]of ne){if(I.count<3)continue;if(I.ranges.length===I.count){let q=!1,x=[];for(let[Y,ke]of I.ranges){if(x.length>0&&J(Y,ke,x)){q=!0;break}x.push([Y,ke])}if(!q)continue}if(I.count-I.ranges.length<=2&&I.ranges.length>=1){let q=!1,x=[];for(let[Y,ke]of I.ranges){if(x.length>0&&J(Y,ke,x)){q=!0;break}x.push([Y,ke])}if(!q)continue}I.count>ie&&(ie=I.count,ce=$)}if(ie>=3){e-=1;let $=ce.split("/").slice(-2).join("/");s.push(`read_file loop: "${$}" read ${ie}\xD7 (file already in context)`)}let se=0,S="";for(let[$,I]of ne){if(I.ranges.length<4)continue;let H=[],N=!1;for(let[q,x]of I.ranges){if(H.length>0&&J(q,x,H)){N=!0;break}H.push([q,x])}!N&&I.ranges.length>se&&(se=I.ranges.length,S=$)}if(se>=4){e-=.5;let $=S.split("/").slice(-2).join("/");s.push(`File-scroll pattern: "${$}" read in ${se} sequential sections \u2014 use grep instead`)}let Ee=new Map;for(let $ of a)if($.name==="grep"&&$.input?.path&&$.input?.pattern){let I=$.input.path;Ee.has(I)||Ee.set(I,new Set),Ee.get(I).add($.input.pattern)}let W=0,Z="";for(let[$,I]of Ee)$.split("/").pop().includes(".")&&I.size>W&&(W=I.size,Z=$);if(W>=3){e-=.75;let $=Z.split("/").slice(-2).join("/");s.push(`grep flood on single file: "${$}" searched ${W}\xD7 with different patterns (file already in context)`)}{let $=new Set,I=new Set,H=/^(test_|demo_|temp_|tmp_|scratch_)/;for(let q of n){if(q.name==="write_file"&&q.input?.path){let x=q.input.path.split("/").pop(),Y=q.input.path.includes("/tests/");H.test(x)&&!Y&&$.add(q.input.path)}if((q.name==="bash"||q.name==="ssh_exec")&&q.input?.command){let x=q.input.command.match(/\brm\s+(?:-\w+\s+)?(\S+)/g);if(x)for(let Y of x){let ke=Y.split(/\s+/),pe=ke[ke.length-1];for(let lt of $)(lt.endsWith(pe)||pe.endsWith(lt.split("/").pop()))&&I.add(lt)}}}let N=I.size;if(N>=1){let q=Math.min(N*.25,.5);e-=q;let x=[...I].map(Y=>Y.split("/").pop()).join(", ");s.push(`Temp file write-then-delete: ${x} \u2014 write inline logic or use tests/ instead`)}}let he=o.filter($=>$.content.startsWith("EXIT")).length;he>=10?(e-=1,s.push(`Bash exit-error storm: ${he} tool results started with EXIT (repeated failing commands)`)):he>=5&&(e-=.5,s.push(`Repeated bash errors: ${he} tool results with non-zero exit code`));for(let $ of t){if($.role!=="assistant")continue;let I="";if(typeof $.content=="string"?I=$.content:Array.isArray($.content)&&(I=$.content.filter(pe=>pe&&(pe.type==="text"||typeof pe=="string")).map(pe=>typeof pe=="string"?pe:pe.text||"").join("")),I.length<=5e3)continue;let H=I.split(/(?<=\. )/).filter(pe=>pe.trim().length>0);if(H.length<6)continue;let N=new Map;for(let pe=0;pe<=H.length-3;pe++){let lt=H.slice(pe,pe+3).join("").trim();lt.length>30&&N.set(lt,(N.get(lt)||0)+1)}let q=0,x="";for(let[pe,lt]of N)lt>q&&(q=lt,x=pe);if(q<3)continue;let ke=x.length*q/I.length;if(ke>=.4||q>=10){e-=1.5,s.push(`llm output loop: assistant message repeated content detected (${q}\xD7 same paragraph, ${Math.round(ke*100)}% repeated)`);break}}{let $=new Set(["read_file","list_directory","search_files","glob","grep"]),I=t.some(N=>Array.isArray(N.tool_calls)?N.tool_calls.some(q=>$.has(q.function?.name)):Array.isArray(N.content)?N.content.some(q=>q.type==="tool_use"&&$.has(q.name)):!1);t.some(N=>N.role==="assistant"&&typeof N.content=="string"&&(N.content.includes("## Steps")||N.content.includes("/plan approve")))&&!I&&(e-=2,s.push("plan written without reading any files \u2014 LLM invented data structures from training knowledge (hallucination risk)"))}let Ce=o.filter($=>$.content.startsWith("BLOCKED:")&&!$.content.includes("BLOCKED: sed -n")&&!$.content.includes("SSH paused")&&!$.content.includes("SSH temporarily paused"));if(Ce.length>0){let $=Math.min(Ce.length*.5,1.5);e-=$,s.push(`${Ce.length} tool call${Ce.length===1?"":"s"} blocked (agent attempted denied actions)`)}let We=t.filter($=>{let I=typeof $.content=="string"?$.content:"";return/\[SYSTEM WARNING\] Context wiped \d+×/.test(I)}).length;if(We>0){let $=Math.min(We*1,2);e-=$,s.push(`Super-nuclear context wipe fired ${We}\xD7 (context collapse \u2014 task too large or read loops)`)}{let $=!1,I=!1,H=!1;for(let q of n){if(q.name!=="bash")continue;let x=(q.input?.command||q.input?.cmd||"").trim();!(/cat\s*>/.test(x)||/<</.test(x))&&/\bcat\s+\S/.test(x)&&($=!0),/^\s*ls(\s|$)/.test(x)&&!/npm|yarn|pnpm|make|git\b/.test(x)&&(I=!0),/\bfind\s+\S/.test(x)&&!/git\b|npm\b|-exec\b/.test(x)&&(H=!0)}let N=[$,I,H].filter(Boolean).length;if(N>0){let q=Math.min(N*.25,.75);e-=q;let x=[];$&&x.push("cat (use read_file)"),I&&x.push("ls (use list_directory)"),H&&x.push("find (use glob)"),s.push(`bash used instead of dedicated tool: ${x.join(", ")}`)}}{let $=n.some(x=>(x.name==="write_file"||x.name==="Write")&&x.input?.path&&(x.input.path.endsWith("requirements.txt")||x.input.path.endsWith("Pipfile")||x.input.path.endsWith("pyproject.toml"))),I=n.some(x=>(x.name==="write_file"||x.name==="Write")&&x.input?.path&&x.input.path.endsWith("package.json")),H=n.filter(x=>(x.name==="bash"||x.name==="Bash")&&x.input?.command).map(x=>x.input.command),N=H.some(x=>/pip\s+install|python\s+-m\s+venv/.test(x)),q=H.some(x=>/npm\s+install/.test(x));$&&!N?(e-=1,s.push("wrote requirements.txt but never ran pip install \u2014 environment not bootstrapped")):I&&!q&&n.some(Y=>(Y.name==="write_file"||Y.name==="Write")&&Y.input?.path&&/(\/src\/|index\.js|App\.js|main\.js)/.test(Y.input.path))&&(e-=.75,s.push("created new React/Node project but never ran npm install \u2014 project is not runnable"))}if(d){let $=t.find(x=>x.role==="assistant"),I="";$&&(typeof $.content=="string"?I=$.content:Array.isArray($.content)&&(I=$.content.filter(x=>x&&(x.type==="text"||typeof x=="string")).map(x=>typeof x=="string"?x:x.text||"").join("")));let H=I.slice(0,400),N=/^[\d\s\+\-\*\/×÷\(\)\.]+\s*=\s*[\d\s\+\-\*\/×÷\(\)\.]+[.\n]/m,q=H.split(`
|
|
656
|
-
`).find(
|
|
657
|
-
`)[0]).trim().slice(0,40);s.push(`Thinking-chain leak: non-sequitur artifact at response start: "${
|
|
658
|
-
`).filter(
|
|
659
|
-
${o}${f}${r}`}let
|
|
660
|
-
${i}\u26A0${r} ${o}${u}${r}`;let
|
|
661
|
-
${o}(+${
|
|
657
|
+
${l}`)}try{let l=gv();l&&o.push(l)}catch{}return o.join(`
|
|
658
|
+
|
|
659
|
+
`)}async function Lv(t){let e=Ue.join(t,"package.json"),s="";if(await an(()=>wt.access(e).then(()=>!0).catch(()=>!1)))try{let i=await wt.readFile(e,"utf-8"),a=JSON.parse(i);s=`${a.name||"?"} v${a.version||"?"}`}catch{}let[o,r]=await Promise.all([an(async()=>{let{stdout:i}=await Ni("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),Vm()]);if(r&&r.length>0){console.log(`${Ks.red} \u26A0 ${r.length} unresolved merge conflict(s):${Ks.reset}`);for(let i of r)console.log(`${Ks.red} ${i.file}${Ks.reset}`);console.log(`${Ks.yellow} \u2192 Resolve conflicts before starting tasks${Ks.reset}`)}console.log()}Jm.exports={gatherProjectContext:Pv,printContext:Lv,generateFileTree:Ov,_clearContextCache:()=>{kl.clear(),Vs.clear(),Pi=null,Xs={result:null,expiry:0,cwd:null}}}});var Ii=J((NC,tg)=>{var Vt=require("fs"),Li=require("path"),{atomicWrite:Iv}=Gn();function Xo(){return Li.join(process.cwd(),".nex","sessions")}function Sl(){let t=Xo();Vt.existsSync(t)||Vt.mkdirSync(t,{recursive:!0,mode:448})}function vl(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return Li.join(Xo(),`${e}.json`)}function El(t,e,s={}){Sl();let n=vl(t),o={name:t,createdAt:s.createdAt||new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:e.length,model:s.model||null,provider:s.provider||null,messages:e};return Iv(n,JSON.stringify(o,null,2)),{path:n,name:t}}function Qm(t){let e=vl(t);if(!Vt.existsSync(e))return null;try{return JSON.parse(Vt.readFileSync(e,"utf-8"))}catch{return null}}function eg(){Sl();let t=Xo(),e=Vt.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(Vt.readFileSync(Li.join(t,n),"utf-8"));s.push({name:o.name||n.replace(".json",""),createdAt:o.createdAt,updatedAt:o.updatedAt,messageCount:o.messageCount||0,model:o.model,provider:o.provider,score:o.score!=null?o.score:null,scoreGrade:o.scoreGrade||null})}catch{}return s.sort((n,o)=>(o.updatedAt||"").localeCompare(n.updatedAt||""))}function jv(t){let e=vl(t);return Vt.existsSync(e)?(Vt.unlinkSync(e),!0):!1}function Dv(){let t=eg();return t.length===0?null:Qm(t[0].name)}var cs=null,_n=null,Ko=null;function qv(t,e={}){t.length!==0&&(cs&&clearTimeout(cs),_n=t,Ko=e||{},cs=setTimeout(()=>{_n&&_n.length>0&&El("_autosave",_n,Ko),cs=null,_n=null,Ko=null},5e3))}function Fv(){cs&&(clearTimeout(cs),cs=null),_n&&_n.length>0&&(El("_autosave",_n,Ko),_n=null,Ko=null)}function Bv(){Sl();let t=Xo(),e=Vt.readdirSync(t).filter(r=>r.endsWith(".json")),s=new Date,n=new Date(s.getTime()-720*60*60*1e3),o=0;for(let r of e){let i=Li.join(t,r);try{let a=Vt.statSync(i);new Date(a.mtime)<n&&(Vt.unlinkSync(i),o++)}catch{}}return o}tg.exports={saveSession:El,loadSession:Qm,listSessions:eg,deleteSession:jv,getLastSession:Dv,autoSave:qv,flushAutoSave:Fv,clearOldSessions:Bv,_getSessionsDir:Xo}});var ji=J((MC,lg)=>{"use strict";var Vo=require("fs"),ng=require("path");function sg(t){let e=[];return t.forEach((s,n)=>{s.role==="assistant"&&(Array.isArray(s.content)&&s.content.forEach(o=>{o&&o.type==="tool_use"&&e.push({name:o.name||"",input:o.input||{},index:n,id:o.id||null})}),Array.isArray(s.tool_calls)&&s.tool_calls.forEach(o=>{let r=o.function?.name||o.name||"",i={};try{i=typeof o.function?.arguments=="string"?JSON.parse(o.function.arguments):o.function?.arguments||o.input||{}}catch{}e.push({name:r,input:i,index:n,id:o.id||null})}))}),e}function Uv(t){let e=new Set;return t.forEach(s=>{s.role==="tool"&&typeof s.content=="string"&&s.content.startsWith("BLOCKED:")&&s.tool_call_id&&e.add(s.tool_call_id),s.role==="user"&&Array.isArray(s.content)&&s.content.forEach(n=>{n&&n.type==="tool_result"&&n.tool_use_id&&typeof n.content=="string"&&n.content.startsWith("BLOCKED:")&&e.add(n.tool_use_id)})}),e}function og(t){let e=[];return t.forEach((s,n)=>{if(s.role==="user"&&Array.isArray(s.content)&&s.content.forEach(o=>{if(o&&o.type==="tool_result"){let r=typeof o.content=="string"?o.content:Array.isArray(o.content)?o.content.map(i=>typeof i=="string"?i:i.text||"").join(""):JSON.stringify(o.content||"");e.push({content:r,index:n})}}),s.role==="tool"){let o=typeof s.content=="string"?s.content:JSON.stringify(s.content||"");e.push({content:o,index:n})}}),e}function rg(t){for(let e=t.length-1;e>=0;e--){let s=t[e];if(s.role==="assistant"){if(typeof s.content=="string")return s.content.trim();if(Array.isArray(s.content)){let n=s.content.filter(o=>o&&(o.type==="text"||typeof o=="string")).map(o=>typeof o=="string"?o:o.text||"").join("").trim();if(n)return n}}}return""}function ig(t,e){let s=[];for(let n=t.length-1;n>=0&&s.length<e;n--){let o=t[n];if(o.role!=="assistant")continue;let r="";typeof o.content=="string"?r=o.content.trim():Array.isArray(o.content)&&(r=o.content.filter(i=>i&&(i.type==="text"||typeof i=="string")).map(i=>typeof i=="string"?i:i.text||"").join("").trim()),r&&s.push(r)}return s}function ag(t){let e=new Map;for(let s of t){let n;try{n=JSON.stringify(s.input)}catch{n=String(s.input)}let o=`${s.name}|${n}`;e.set(o,(e.get(o)||0)+1)}return e}function cg(t){if(!Array.isArray(t)||t.length===0)return{score:0,issues:["Empty or invalid session \u2014 no messages to analyse"],summary:"No messages found"};let e=10,s=[],n=sg(t),o=og(t),r=n.length,i=Uv(t),a=n.filter(_=>!_.id||!i.has(_.id));t.some(_=>_.role==="user"&&typeof _.content=="string"&&_.content.startsWith("[SYSTEM WARNING]")&&(_.content.includes("edited")||_.content.includes("bash command")||_.content.includes("grep pattern")||_.content.includes("re-read")||_.content.includes("already in your context")))&&(e-=2,s.push("Loop-warning was fired during session (repeated file edits, bash commands, or re-reads)"));let l=n.find(_=>{let j=_.input?.command||_.input?.cmd||"";return/\bsed\s+-n\b/.test(j)});if(l){let _=(l.input?.command||l.input?.cmd||"").slice(0,80);o.some(H=>H.content.includes("BLOCKED: sed -n is forbidden")||H.content.includes("BLOCKED: sed -n"))?(e-=.25,s.push(`sed -n attempted but blocked by agent guard: ${_}`)):(e-=1.5,s.push(`sed -n anti-pattern used: ${_}`))}n.find(_=>{if(_.name!=="grep"&&_.name!=="bash"&&_.name!=="ssh_exec")return!1;let j=_.input?.command||_.input?.cmd||"",H=_.input?.pattern||"",M=`${j} ${H}`;return/(?:-[CAB]|--context|--after|--before)\s*[=\s]?([2-9][1-9]|\d{3,})/.test(M)||/grep.*-[CAB]\s*([2-9][1-9]|\d{3,})/.test(M)})&&(e-=1,s.push("grep used with >20 context lines (context flood risk)"));let d=t.some(_=>_.role==="assistant"),f=rg(t),h=ig(t,3).some(_=>_.length>100&&!/^[^.!]{0,40}\?$/.test(_));if(d&&!h&&(f.length<80||/^[^.!]{0,40}\?$/.test(f))){e-=2;let _=f.length>0?`"${f.slice(0,60)}..."`:"(no assistant text found)";s.push(`Session ends without diagnosis \u2014 last response too short or is only a question: ${_}`)}r>40?(e-=1.5,s.push(`Excessive tool calls: ${r} (>40 threshold)`)):r>25&&(e-=.5,s.push(`High tool call count: ${r} (>25 threshold)`)),t.some(_=>{let j=typeof _.content=="string"?_.content:Array.isArray(_.content)?_.content.map(H=>typeof H=="string"?H:H.text||"").join(""):"";return/\[auto-compressed|context compacted|force-compressed/.test(j)})&&(e-=.5,s.push("Auto-compress triggered (context flood indicator)"));let x=ag(a),O=0,I="";for(let[_,j]of x)j>O&&(O=j,I=_);if(O>=3){let[_]=I.split("|");e-=1,s.push(`Same tool call repeated ${O}\xD7 (tool: ${_})`)}let E=!1,v=t.findIndex(_=>_.role==="user"&&typeof _.content=="string"&&_.content.includes("[SYSTEM STOP]")&&_.content.includes('"valid":true'));v>=0&&n.filter(j=>j.index>v).length>0&&(E=!0),E&&(e-=1.5,s.push('Stop-trigger ignored: tool result contained "valid":true but session continued with more tool calls'));let A=n.filter(_=>_.name==="ssh_exec");if(A.length>=8){let _=0,j=1;for(let H=1;H<A.length;H++)A[H].index<=A[H-1].index+2?j++:(_=Math.max(_,j),j=1);_=Math.max(_,j),_>=8&&(e-=.5,s.push(`SSH reconnect storm: ${_} consecutive SSH calls`))}d&&A.length>0&&/\b(Könntest du|könntest du|Bitte (bereitstellen|kopier)|kannst du mir .* bereitstellen|could you (provide|share|paste)|please (provide|share|run .* and paste)|I (cannot|can't) access the server|nicht (auf den Server )?zugreifen|SSH .* (nicht verfügbar|unavailable|temporarily unavailable))\b/i.test(f)&&(e-=2,s.push("Surrender: model asked user to manually provide server output instead of gathering it"));let te=new Map;for(let _ of a)if(_.name==="read_file"&&_.input?.path){let j=_.input.path;te.has(j)||te.set(j,{count:0,ranges:[]});let H=te.get(j);if(H.count++,_.input.line_start!=null){let M=_.input.line_start||1,L=_.input.line_end||M+350;H.ranges.push([M,L])}}function oe(_,j,H){for(let[M,L]of H){let b=Math.max(_,M),Z=Math.min(j,L);if(Z>b){let fe=Z-b,pe=j-_||1;if(fe/pe>=.7)return!0}}return!1}let de=0,ce="";for(let[_,j]of te){if(j.count<3)continue;if(j.ranges.length===j.count){let L=!1,b=[];for(let[Z,fe]of j.ranges){if(b.length>0&&oe(Z,fe,b)){L=!0;break}b.push([Z,fe])}if(!L)continue}if(j.count-j.ranges.length<=2&&j.ranges.length>=1){let L=!1,b=[];for(let[Z,fe]of j.ranges){if(b.length>0&&oe(Z,fe,b)){L=!0;break}b.push([Z,fe])}if(!L)continue}j.count>de&&(de=j.count,ce=_)}if(de>=3){e-=1;let _=ce.split("/").slice(-2).join("/");s.push(`read_file loop: "${_}" read ${de}\xD7 (file already in context)`)}let ne=0,S="";for(let[_,j]of te){if(j.ranges.length<4)continue;let H=[],M=!1;for(let[L,b]of j.ranges){if(H.length>0&&oe(L,b,H)){M=!0;break}H.push([L,b])}!M&&j.ranges.length>ne&&(ne=j.ranges.length,S=_)}if(ne>=4){e-=.5;let _=S.split("/").slice(-2).join("/");s.push(`File-scroll pattern: "${_}" read in ${ne} sequential sections \u2014 use grep instead`)}let Te=new Map;for(let _ of a)if(_.name==="grep"&&_.input?.path&&_.input?.pattern){let j=_.input.path;Te.has(j)||Te.set(j,new Set),Te.get(j).add(_.input.pattern)}let W=0,K="";for(let[_,j]of Te)_.split("/").pop().includes(".")&&j.size>W&&(W=j.size,K=_);if(W>=3){e-=.75;let _=K.split("/").slice(-2).join("/");s.push(`grep flood on single file: "${_}" searched ${W}\xD7 with different patterns (file already in context)`)}{let _=new Set,j=new Set,H=/^(test_|demo_|temp_|tmp_|scratch_)/;for(let L of n){if(L.name==="write_file"&&L.input?.path){let b=L.input.path.split("/").pop(),Z=L.input.path.includes("/tests/");H.test(b)&&!Z&&_.add(L.input.path)}if((L.name==="bash"||L.name==="ssh_exec")&&L.input?.command){let b=L.input.command.match(/\brm\s+(?:-\w+\s+)?(\S+)/g);if(b)for(let Z of b){let fe=Z.split(/\s+/),pe=fe[fe.length-1];for(let Qe of _)(Qe.endsWith(pe)||pe.endsWith(Qe.split("/").pop()))&&j.add(Qe)}}}let M=j.size;if(M>=1){let L=Math.min(M*.25,.5);e-=L;let b=[...j].map(Z=>Z.split("/").pop()).join(", ");s.push(`Temp file write-then-delete: ${b} \u2014 write inline logic or use tests/ instead`)}}let ge=o.filter(_=>_.content.startsWith("EXIT")).length;ge>=10?(e-=1,s.push(`Bash exit-error storm: ${ge} tool results started with EXIT (repeated failing commands)`)):ge>=5&&(e-=.5,s.push(`Repeated bash errors: ${ge} tool results with non-zero exit code`));for(let _ of t){if(_.role!=="assistant")continue;let j="";if(typeof _.content=="string"?j=_.content:Array.isArray(_.content)&&(j=_.content.filter(pe=>pe&&(pe.type==="text"||typeof pe=="string")).map(pe=>typeof pe=="string"?pe:pe.text||"").join("")),j.length<=5e3)continue;let H=j.split(/(?<=\. )/).filter(pe=>pe.trim().length>0);if(H.length<6)continue;let M=new Map;for(let pe=0;pe<=H.length-3;pe++){let Qe=H.slice(pe,pe+3).join("").trim();Qe.length>30&&M.set(Qe,(M.get(Qe)||0)+1)}let L=0,b="";for(let[pe,Qe]of M)Qe>L&&(L=Qe,b=pe);if(L<3)continue;let fe=b.length*L/j.length;if(fe>=.4||L>=10){e-=1.5,s.push(`llm output loop: assistant message repeated content detected (${L}\xD7 same paragraph, ${Math.round(fe*100)}% repeated)`);break}}{let _=new Set(["read_file","list_directory","search_files","glob","grep"]),j=t.some(M=>Array.isArray(M.tool_calls)?M.tool_calls.some(L=>_.has(L.function?.name)):Array.isArray(M.content)?M.content.some(L=>L.type==="tool_use"&&_.has(L.name)):!1);t.some(M=>M.role==="assistant"&&typeof M.content=="string"&&(M.content.includes("## Steps")||M.content.includes("/plan approve")))&&!j&&(e-=2,s.push("plan written without reading any files \u2014 LLM invented data structures from training knowledge (hallucination risk)"))}let Ae=o.filter(_=>_.content.startsWith("BLOCKED:")&&!_.content.includes("BLOCKED: sed -n")&&!_.content.includes("SSH paused")&&!_.content.includes("SSH temporarily paused"));if(Ae.length>0){let _=Math.min(Ae.length*.5,1.5);e-=_,s.push(`${Ae.length} tool call${Ae.length===1?"":"s"} blocked (agent attempted denied actions)`)}let qe=t.filter(_=>{let j=typeof _.content=="string"?_.content:"";return/\[SYSTEM WARNING\] Context wiped \d+×/.test(j)}).length;if(qe>0){let _=Math.min(qe*1,2);e-=_,s.push(`Super-nuclear context wipe fired ${qe}\xD7 (context collapse \u2014 task too large or read loops)`)}{let _=!1,j=!1,H=!1;for(let L of n){if(L.name!=="bash")continue;let b=(L.input?.command||L.input?.cmd||"").trim();!(/cat\s*>/.test(b)||/<</.test(b))&&/\bcat\s+\S/.test(b)&&(_=!0),/^\s*ls(\s|$)/.test(b)&&!/npm|yarn|pnpm|make|git\b/.test(b)&&(j=!0),/\bfind\s+\S/.test(b)&&!/git\b|npm\b|-exec\b/.test(b)&&(H=!0)}let M=[_,j,H].filter(Boolean).length;if(M>0){let L=Math.min(M*.25,.75);e-=L;let b=[];_&&b.push("cat (use read_file)"),j&&b.push("ls (use list_directory)"),H&&b.push("find (use glob)"),s.push(`bash used instead of dedicated tool: ${b.join(", ")}`)}}{let _=n.some(b=>(b.name==="write_file"||b.name==="Write")&&b.input?.path&&(b.input.path.endsWith("requirements.txt")||b.input.path.endsWith("Pipfile")||b.input.path.endsWith("pyproject.toml"))),j=n.some(b=>(b.name==="write_file"||b.name==="Write")&&b.input?.path&&b.input.path.endsWith("package.json")),H=n.filter(b=>(b.name==="bash"||b.name==="Bash")&&b.input?.command).map(b=>b.input.command),M=H.some(b=>/pip\s+install|python\s+-m\s+venv/.test(b)),L=H.some(b=>/npm\s+install/.test(b));_&&!M?(e-=1,s.push("wrote requirements.txt but never ran pip install \u2014 environment not bootstrapped")):j&&!L&&n.some(Z=>(Z.name==="write_file"||Z.name==="Write")&&Z.input?.path&&/(\/src\/|index\.js|App\.js|main\.js)/.test(Z.input.path))&&(e-=.75,s.push("created new React/Node project but never ran npm install \u2014 project is not runnable"))}if(d){let _=t.find(b=>b.role==="assistant"),j="";_&&(typeof _.content=="string"?j=_.content:Array.isArray(_.content)&&(j=_.content.filter(b=>b&&(b.type==="text"||typeof b=="string")).map(b=>typeof b=="string"?b:b.text||"").join("")));let H=j.slice(0,400),M=/^[\d\s\+\-\*\/×÷\(\)\.]+\s*=\s*[\d\s\+\-\*\/×÷\(\)\.]+[.\n]/m,L=H.split(`
|
|
660
|
+
`).find(b=>{let Z=b.trim();return Z.length>0&&Z.length<=30&&/^\d/.test(Z)&&/=/.test(Z)&&!/[a-zA-Z]/.test(Z)});if(M.test(H)||L){e-=1.5;let b=(L||H.split(`
|
|
661
|
+
`)[0]).trim().slice(0,40);s.push(`Thinking-chain leak: non-sequitur artifact at response start: "${b}"`)}}if(d&&r>0){let _=t.findIndex(H=>H.role==="assistant"),j=t.findIndex(H=>!!(Array.isArray(H.tool_calls)&&H.tool_calls.length>0||Array.isArray(H.content)&&H.content.some(M=>M&&M.type==="tool_use")));if(_!==-1&&j!==-1&&_<j){let H=t[_],M="";typeof H.content=="string"?M=H.content:Array.isArray(H.content)&&(M=H.content.filter(Z=>Z&&(Z.type==="text"||typeof Z=="string")).map(Z=>typeof Z=="string"?Z:Z.text||"").join(""));let L=/ssh\s+\S+@\S+\s+"[^"]*\/[^"]*\./.test(M),b=/\/(?:home|var|etc|usr|opt|root|srv|data)\/[a-zA-Z0-9_.\-\/]+\.[a-zA-Z]{2,5}/.test(M);(L||b)&&(e-=1,s.push("Answer-before-verify: model gave concrete file paths/SSH commands before making any tool calls (paths guessed, not verified)"))}}if(d){let _=f;if(_.length>100){let H=(_.match(/^```/gm)||[]).length%2!==0,M=/"\s*:\s*$/.test(_.trimEnd()),L=/[,\[{]\s*$/.test(_.trimEnd());(H||M||L)&&(e-=.75,s.push("Truncated response: last assistant message ends mid-code-block or mid-JSON (model hit token limit)"))}}{let _=[];t.forEach((H,M)=>{let L=[];Array.isArray(H.tool_calls)&&H.tool_calls.forEach(b=>{if((b.function?.name||b.name||"")==="read_file"){let fe={};try{fe=typeof b.function?.arguments=="string"?JSON.parse(b.function.arguments):b.function?.arguments||{}}catch{}(fe.path||"").endsWith(".json")&&L.push({id:b.id,path:fe.path})}}),Array.isArray(H.content)&&H.content.forEach(b=>{b&&b.type==="tool_use"&&b.name==="read_file"&&(b.input?.path||"").endsWith(".json")&&L.push({id:b.id,path:b.input.path})}),L.forEach(b=>_.push({...b,msgIdx:M}))});let j=0;for(let H of _){let M=null;for(let b of t){if(b.role==="tool"&&b.tool_call_id===H.id&&typeof b.content=="string"){M=b.content;break}if(b.role==="user"&&Array.isArray(b.content)){let Z=b.content.find(fe=>fe&&fe.type==="tool_result"&&fe.tool_use_id===H.id);if(Z){M=typeof Z.content=="string"?Z.content:"";break}}}if(!M)continue;M.split(`
|
|
662
|
+
`).filter(b=>b.trim()).length<5&&/^\s*\[/.test(M)&&!/\]\s*$/.test(M.trimEnd())&&j++}j>=1&&(e-=.75,s.push(`Shallow JSON read: ${j} .json file${j>1?"s":""} read with < 5 lines \u2014 array was incomplete, model drew conclusions from truncated data`))}{let _=o.filter(j=>/argument errors?/i.test(j.content)||/missing required (argument|parameter)/i.test(j.content)||/invalid argument/i.test(j.content));_.length>=3?(e-=.75,s.push(`Repeated tool argument errors: ${_.length} tool calls returned argument errors \u2014 model couldn't correct its tool usage`)):_.length>=2&&(e-=.25,s.push(`Tool argument errors: ${_.length} tool calls returned argument errors`))}{let _=!1,j=0,H=0;for(let M of a){if((M.name==="bash"||M.name==="Bash")&&M.input?.command&&/git\s+commit\b/.test(M.input.command)){_&&(H=Math.max(H,j)),_=!0,j=0;continue}_&&(M.name==="bash"||M.name==="Bash")&&M.input?.command&&/git\s+(status|diff|log|show)\b/.test(M.input.command)&&j++}H=Math.max(H,j),H>=3&&(e-=.75,s.push(`Post-commit verification waste: ${H} git status/diff/log calls after commit`))}e=Math.max(0,Math.min(10,e)),e=Math.round(e*10)/10;let ke=e>=9?"A":e>=8?"B":e>=7?"C":e>=6?"D":"F",xe=s.length===0?`Clean session \u2014 no quality issues detected (${r} tool calls)`:`${s.length} issue${s.length===1?"":"s"} found \u2014 ${r} tool calls`;return{score:e,grade:ke,issues:s,summary:xe}}function Wv(t){try{let{loadSession:e}=Ii(),s=e(t);return s?cg(s.messages||[]):null}catch{return null}}function Hv(t,e=null){let{score:s,issues:n}=t,o=e?.dim||"",r=e?.reset||"",i=e?.yellow||"";if(s>=8||n.length===0)return"";let a=n.map(u=>u.replace(/:\s+\d+.*$/,"").replace(/\s*\(.*?\)/,"").replace(/\s*—.*$/,""));if(s>=6){let u=a.slice(0,3),d=a.length-u.length,f=u.join(" \xB7 ");return d>0&&(f+=` (+${d})`),`
|
|
663
|
+
${o}${f}${r}`}let c="";for(let u of a.slice(0,4))c+=`
|
|
664
|
+
${i}\u26A0${r} ${o}${u}${r}`;let l=a.length-4;return l>0&&(c+=`
|
|
665
|
+
${o}(+${l} more)${r}`),c}function Yv(t,e={}){try{let s=ng.join(process.cwd(),".nex");Vo.existsSync(s)||Vo.mkdirSync(s,{recursive:!0});let n=ng.join(s,"benchmark-history.json"),o=[];if(Vo.existsSync(n))try{o=JSON.parse(Vo.readFileSync(n,"utf-8"))}catch{o=[]}Array.isArray(o)||(o=[]);let r=t>=9?"A":t>=8?"B":t>=7?"C":t>=6?"D":"F",i={date:new Date().toISOString(),version:e.version||null,model:e.model||null,score:t,grade:r,sessionName:e.sessionName||null,issues:Array.isArray(e.issues)?e.issues:[]};o.push(i),o.length>100&&(o=o.slice(o.length-100)),Vo.writeFileSync(n,JSON.stringify(o,null,2))}catch{}}lg.exports={scoreMessages:cg,scoreSession:Wv,formatScore:Hv,appendScoreHistory:Yv,_extractToolCalls:sg,_extractToolResults:og,_getLastAssistantText:rg,_getLastNAssistantTexts:ig,_countDuplicateToolCalls:ag}});var ls=J((PC,hg)=>{"use strict";var Gv=require("os"),Tl=require("path"),Pn=require("fs"),Jo=Tl.join(Gv.homedir(),".nex-code","model-routing.json"),Di={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}},ug=["agentic","frontend","sysadmin","data","coding"];function zv(t){if(!t||t.length<8)return null;for(let e of ug){let s=Di[e];if(!s.pattern||s.pattern.test(t))return s}return Di.coding}function Zo(){try{if(Pn.existsSync(Jo))return JSON.parse(Pn.readFileSync(Jo,"utf-8"))}catch{}return{}}function dg(t){if(process.env.NEX_FORCE_MODEL)return process.env.NEX_FORCE_MODEL;let e=Di[t];return e?.envVar&&process.env[e.envVar]?process.env[e.envVar]:Zo()[t]||null}var fg={explore:10,plan:10,implement:35,verify:8},Rl={explore:"devstral-small-2:24b",plan:"qwen3-coder:480b",implement:null,verify:"devstral-small-2:24b"};function pg(){let t=Zo();if(t.phases&&Object.keys(t.phases).length>0)return t.phases;try{let{getActiveProviderName:e}=st();if(e()==="ollama")return Rl}catch{}return process.env.NEX_PHASE_ROUTING==="1"?Rl:null}function Kv(t,e){if(process.env.NEX_FORCE_MODEL)return process.env.NEX_FORCE_MODEL;let s=pg();return s?.[t]?s[t]:e?dg(e):null}function Xv(t){return Zo().phaseBudgets?.[t]||fg[t]||20}function Vv(){return process.env.NEX_PHASE_ROUTING==="0"||process.env.NEX_FORCE_MODEL?!1:pg()!==null}function Jv(t){let e=Tl.dirname(Jo);Pn.existsSync(e)||Pn.mkdirSync(e,{recursive:!0});let s=Zo(),n={...s,...t};!t.phases&&s.phases&&(n.phases=s.phases),!t.phaseBudgets&&s.phaseBudgets&&(n.phaseBudgets=s.phaseBudgets),Pn.writeFileSync(Jo,JSON.stringify(n,null,2));try{let o=Tl.join(e,".env"),r="";Pn.existsSync(o)&&(r=Pn.readFileSync(o,"utf-8"));let i=r.split(/\r?\n/),a=(c,l)=>{let u=i.findIndex(d=>d.startsWith(c+"="));u>=0?i[u]=`${c}=${l}`:i.push(`${c}=${l}`)};n.coding&&a("NEX_ROUTE_CODING",n.coding),n.frontend&&a("NEX_ROUTE_FRONTEND",n.frontend),n.sysadmin&&a("NEX_ROUTE_SYSADMIN",n.sysadmin),n.data&&a("NEX_ROUTE_DATA",n.data),n.agentic&&a("NEX_ROUTE_AGENTIC",n.agentic),n.phases&&(n.phases.plan&&a("NEX_PHASE_PLAN_MODEL",n.phases.plan),n.phases.implement&&a("NEX_PHASE_IMPLEMENT_MODEL",n.phases.implement),n.phases.verify&&a("NEX_PHASE_VERIFY_MODEL",n.phases.verify)),Pn.writeFileSync(o,i.filter(c=>c.trim()!=="").join(`
|
|
662
666
|
`)+`
|
|
663
|
-
`)}catch{}}
|
|
664
|
-
A: |`);if(r===-1)return null;let i=s.slice(r+5),a=[],
|
|
665
|
-
`))if(u.startsWith(" ")){for(;
|
|
666
|
-
`).trim();return{user:o,assistant:
|
|
667
|
+
`)}catch{}}hg.exports={CATEGORIES:Di,DETECTION_ORDER:ug,detectCategory:zv,getModelForCategory:dg,getModelForPhase:Kv,getPhaseBudget:Xv,isPhaseRoutingEnabled:Vv,DEFAULT_PHASE_BUDGETS:fg,BUILTIN_PHASE_DEFAULTS:Rl,saveRoutingConfig:Jv,loadRoutingConfig:Zo,ROUTING_CONFIG_PATH:Jo}});var wg=J((LC,yg)=>{"use strict";var us=require("fs"),Qo=require("path"),Zv=require("os"),{detectCategory:Qv}=ls(),Js=Qo.join(Zv.homedir(),".nex-code","examples"),Cl=Qo.join(__dirname,"..","examples");function mg(t){try{let s=us.readFileSync(t,"utf-8").replace(/<!--[\s\S]*?-->/g,"").trim(),n=s.match(/^user:\s*(.+)$/m);if(!n)return null;let o=n[1].trim(),r=s.indexOf(`
|
|
668
|
+
A: |`);if(r===-1)return null;let i=s.slice(r+5),a=[],c=0;for(let u of i.split(`
|
|
669
|
+
`))if(u.startsWith(" ")){for(;c>0;)a.push(""),c--;a.push(u.slice(2))}else if(u.trim()==="")a.length>0&&c++;else break;if(a.length===0)return null;let l=a.join(`
|
|
670
|
+
`).trim();return{user:o,assistant:l}}catch{return null}}function gg(t){let e=`${t}.md`,s=Qo.join(Js,e);if(us.existsSync(s)){let o=mg(s);if(o)return o}let n=Qo.join(Cl,e);return us.existsSync(n)?mg(n):null}function eE(t){if(process.env.NEX_FEW_SHOT==="0"||!t||t.length<8)return null;let e=Qv(t);return!e||e.id==="coding"&&!/\b(fix|bug|crash|error|implement|add|create|change|update|refactor|rewrite|broken|fail|patch|migrate|port)\b/i.test(t)?null:gg(e.id)}function tE(){let t=new Set;for(let e of[Js,Cl])try{for(let s of us.readdirSync(e))s.endsWith(".md")&&t.add(s.replace(".md",""))}catch{}return[...t].sort()}function nE(t,e){us.existsSync(Js)||us.mkdirSync(Js,{recursive:!0});let s=`<!-- Auto-extracted from high-scoring session \u2014 edit as needed -->
|
|
667
671
|
|
|
668
672
|
user: ${e.user}
|
|
669
673
|
|
|
@@ -671,14 +675,14 @@ A: |
|
|
|
671
675
|
${e.assistant.split(`
|
|
672
676
|
`).map(n=>` ${n}`).join(`
|
|
673
677
|
`)}
|
|
674
|
-
`;
|
|
675
|
-
${
|
|
676
|
-
`);for(let n=0;n<t.steps.length;n++){let o=t.steps[n],r;switch(o.status){case"done":r=`${
|
|
677
|
-
`)}function
|
|
678
|
+
`;us.writeFileSync(Qo.join(Js,`${t}.md`),s,"utf-8")}yg.exports={getFewShotForInput:eE,loadExampleForCategory:gg,listAvailableExamples:tE,savePrivateExample:nE,PRIVATE_EXAMPLES_DIR:Js,BUNDLED_EXAMPLES_DIR:Cl}});var Sg=J((jC,kg)=>{var Ct=require("fs"),Zs=require("path"),{C:IC}=Je(),{atomicWrite:sE,withFileLockSync:oE}=Gn(),qi={bash:"ask",read_file:"allow",write_file:"ask",edit_file:"ask",list_directory:"allow",search_files:"allow",glob:"allow",grep:"allow",patch_file:"ask",web_fetch:"allow",web_search:"allow",ask_user:"allow",task_list:"allow",spawn_agents:"ask",ssh_exec:"allow",ssh_upload:"ask",ssh_download:"ask"},Qs={...qi};function $g(){let t=Zs.join(process.cwd(),".nex","config.json");if(Ct.existsSync(t))try{let e=JSON.parse(Ct.readFileSync(t,"utf-8"));e.permissions&&(Qs={...qi,...e.permissions})}catch{}}function rE(){let t=Zs.join(process.cwd(),".nex"),e=Zs.join(t,"config.json");Ct.existsSync(t)||Ct.mkdirSync(t,{recursive:!0}),oE(e,()=>{let s={};if(Ct.existsSync(e))try{s=JSON.parse(Ct.readFileSync(e,"utf-8"))}catch{s={}}s.permissions=Qs,sE(e,JSON.stringify(s,null,2))})}function bg(t){return Qs[t]||"ask"}function iE(t,e){return["allow","ask","deny"].includes(e)?(Qs[t]=e,!0):!1}function aE(t){return bg(t)}function cE(){return Object.entries(Qs).map(([t,e])=>({tool:t,mode:e}))}function lE(){Qs={...qi}}var er={readonly:{description:"Read-only access \u2014 can search and read but not modify",allowedTools:["read_file","list_directory","search_files","glob","grep","git_status","git_diff","git_log","ask_user","web_fetch","web_search","browser_open","browser_screenshot","task_list"],blockedTools:["bash","write_file","edit_file","patch_file","deploy","ssh_exec","service_manage","container_manage","container_exec","remote_agent"],autoConfirm:!1,allowDangerous:!1},developer:{description:"Standard developer access \u2014 can read, write, and run commands",allowedTools:null,blockedTools:["deploy","service_manage","container_manage","remote_agent"],autoConfirm:!1,allowDangerous:!1},admin:{description:"Full access \u2014 all tools, including deployment and infrastructure",allowedTools:null,blockedTools:[],autoConfirm:!1,allowDangerous:!0}};function _g(){let t=Zs.join(process.cwd(),".nex","config.json");try{return Ct.existsSync(t)&&JSON.parse(Ct.readFileSync(t,"utf-8")).teamPermissions||null}catch{return null}}function uE(t){let e=Zs.join(process.cwd(),".nex"),s=Zs.join(e,"config.json");Ct.existsSync(e)||Ct.mkdirSync(e,{recursive:!0});let n={};try{Ct.existsSync(s)&&(n=JSON.parse(Ct.readFileSync(s,"utf-8")))}catch{n={}}n.teamPermissions=t,Ct.writeFileSync(s,JSON.stringify(n,null,2),"utf-8")}function xg(){let t=_g();if(!t)return er.admin;let e=t.role||"admin",s=er[e]||er.admin;return{...s,...t.overrides,blockedTools:[...s.blockedTools||[],...t.overrides?.blockedTools||[]]}}function dE(t){let e=xg();return e.blockedTools&&e.blockedTools.includes(t)?{allowed:!1,reason:`Tool "${t}" is blocked by permission preset "${e.description||"custom"}"`}:e.allowedTools&&!e.allowedTools.includes(t)?{allowed:!1,reason:`Tool "${t}" is not in the allowed list for this permission level`}:{allowed:!0}}function fE(){return Object.entries(er).map(([t,e])=>({name:t,description:e.description,toolCount:e.allowedTools?`${e.allowedTools.length} allowed`:"all allowed",blockedCount:e.blockedTools.length}))}$g();kg.exports={getPermission:bg,setPermission:iE,checkPermission:aE,listPermissions:cE,loadPermissions:$g,savePermissions:rE,resetPermissions:lE,DEFAULT_PERMISSIONS:qi,PERMISSION_PRESETS:er,loadPresetConfig:_g,savePresetConfig:uE,getEffectivePreset:xg,isToolAllowed:dE,listPresets:fE}});var Ui=J((qC,Cg)=>{var fs=require("fs"),Fi=require("path"),DC=require("readline"),{C:Ce}=Je(),Ee=null,Ol=!1,Nl=null,vg=new Set(["read_file","list_directory","search_files","glob","grep","web_search","web_fetch","git_status","git_diff","git_log","git_show"]);function Bi(){return Fi.join(process.cwd(),".nex","plans")}function Eg(){let t=Bi();fs.existsSync(t)||fs.mkdirSync(t,{recursive:!0})}function pE(t,e=[]){return Ee={name:`plan-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,task:t,steps:e.map(s=>({description:s.description||s,files:s.files||[],status:"pending"})),status:"draft",createdAt:new Date().toISOString()},Ee}function hE(){return Ee}function mE(t){Ol=t}function gE(){return Ol}function yE(){return!Ee||Ee.status!=="draft"?!1:(Ee.status="approved",Ee.updatedAt=new Date().toISOString(),!0)}function wE(){return!Ee||Ee.status!=="approved"?!1:(Ee.status="executing",!0)}function Al(t,e){return!Ee||t<0||t>=Ee.steps.length?!1:(Ee.steps[t].status=e,Ee.updatedAt=new Date().toISOString(),Ee.steps.every(s=>s.status==="done"||s.status==="skipped")&&(Ee.status="completed"),!0)}function $E(t){if(!t)return`${Ce.dim}No active plan${Ce.reset}`;let e={draft:`${Ce.yellow}DRAFT${Ce.reset}`,approved:`${Ce.green}APPROVED${Ce.reset}`,executing:`${Ce.blue}EXECUTING${Ce.reset}`,completed:`${Ce.green}COMPLETED${Ce.reset}`},s=[];s.push(`
|
|
679
|
+
${Ce.bold}${Ce.cyan}Plan: ${t.task}${Ce.reset}`),s.push(`${Ce.dim}Status: ${e[t.status]||t.status}${Ce.reset}
|
|
680
|
+
`);for(let n=0;n<t.steps.length;n++){let o=t.steps[n],r;switch(o.status){case"done":r=`${Ce.green}\u2713${Ce.reset}`;break;case"in_progress":r=`${Ce.blue}\u2192${Ce.reset}`;break;case"skipped":r=`${Ce.dim}\u25CB${Ce.reset}`;break;default:r=`${Ce.dim} ${Ce.reset}`}s.push(` ${r} ${Ce.bold}Step ${n+1}:${Ce.reset} ${o.description}`),o.files.length>0&&s.push(` ${Ce.dim}Files: ${o.files.join(", ")}${Ce.reset}`)}return s.push(""),s.join(`
|
|
681
|
+
`)}function bE(t){if(t||(t=Ee),!t)return null;Eg();let e=Fi.join(Bi(),`${t.name}.json`);return fs.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function _E(t){let e=Fi.join(Bi(),`${t}.json`);if(!fs.existsSync(e))return null;try{let s=JSON.parse(fs.readFileSync(e,"utf-8"));return Ee=s,s}catch{return null}}function xE(){Eg();let t=Bi(),e=fs.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(fs.readFileSync(Fi.join(t,n),"utf-8"));s.push({name:o.name,task:o.task,status:o.status,steps:o.steps?o.steps.length:0,createdAt:o.createdAt})}catch{}return s.sort((n,o)=>(o.createdAt||"").localeCompare(n.createdAt||""))}function kE(t){if(!t)return[];let e=[],s=t.match(/##\s+Steps?\s*\n([\s\S]*?)(?:\n##|\s*$)/i),n=s?s[1]:t,o=/^\s*(\d+)[.)]\s+(.+)/gm,r;for(;(r=o.exec(n))!==null;){let a=r[2].trim().replace(/^\*\*What\*\*:\s*/i,"").replace(/^\*\*\d+\.\*\*\s*/,"").replace(/\*\*/g,"").trim();a.length>3&&e.push({description:a,files:[],status:"pending"})}if(e.length===0){let i=/\*\*Step\s+\d+[:.]\*\*\s*(.+)/gi;for(;(r=i.exec(t))!==null;){let a=r[1].replace(/\*\*/g,"").trim();a.length>3&&e.push({description:a,files:[],status:"pending"})}}if(e.length>0){let i=/\*\*(?:Where|Files?)\*\*:\s*(.+)/gi,a=[...t.matchAll(i)];for(let c=0;c<Math.min(e.length,a.length);c++){let l=a[c][1];e[c].files=l.split(/[,\s]+/).filter(u=>/[./]/.test(u)).slice(0,5)}}return e}function SE(t){Nl=t}function vE(){return Nl}function EE(){Ee=null,Ol=!1,Nl=null,AE()}function TE(){return`
|
|
678
682
|
PLAN MODE ACTIVE: You are in analysis-only mode. You MUST NOT execute any changes.
|
|
679
683
|
|
|
680
684
|
# Allowed Tools (read-only)
|
|
681
|
-
You may ONLY use these tools: ${[...
|
|
685
|
+
You may ONLY use these tools: ${[...vg].join(", ")}
|
|
682
686
|
Any other tool call will be blocked and returned with an error.
|
|
683
687
|
|
|
684
688
|
# MANDATORY: Read Before You Plan
|
|
@@ -699,6 +703,13 @@ Thoroughly investigate before writing a plan:
|
|
|
699
703
|
- Architecture: How does the current code work? What patterns does it follow?
|
|
700
704
|
- Dependencies: What depends on the code being changed? What might break?
|
|
701
705
|
- Tests: What test coverage exists? What new tests are needed?
|
|
706
|
+
- Retrieval: Which 2-5 files are the highest-confidence targets? Start there instead of broad scans.
|
|
707
|
+
|
|
708
|
+
# Precision Rules
|
|
709
|
+
- Use the repo map, package scripts, and symbol/definition hints from context before searching blindly.
|
|
710
|
+
- Prefer one focused glob/grep/search followed by narrow reads over many overlapping reads.
|
|
711
|
+
- Each step must name a concrete verification action when applicable (test, lint, typecheck, benchmark, or a specific manual check).
|
|
712
|
+
- If the task is a bug fix, identify the current failing path first and include the smallest safe verification loop.
|
|
702
713
|
|
|
703
714
|
# Required Plan Format
|
|
704
715
|
After analysis, output a plan in this exact markdown format:
|
|
@@ -711,6 +722,7 @@ Numbered list. Each step:
|
|
|
711
722
|
- **What**: Clear description of the change
|
|
712
723
|
- **Where**: Specific file(s) and line ranges
|
|
713
724
|
- **How**: Implementation approach (edit, create, delete)
|
|
725
|
+
- **Verify**: Exact command or check that proves the step worked
|
|
714
726
|
|
|
715
727
|
## Files Affected
|
|
716
728
|
Bullet list of all files that will be modified or created.
|
|
@@ -722,26 +734,26 @@ Bullet list of potential issues and mitigations.
|
|
|
722
734
|
- Order steps by dependency (later steps may depend on earlier ones).
|
|
723
735
|
- After presenting the plan, tell the user to type \`/plan approve\` to proceed.
|
|
724
736
|
- Do NOT make any file changes \u2014 your role is analysis and planning only.
|
|
725
|
-
- Do NOT call ask_user. If anything is ambiguous, add an "## Assumptions" section to the plan and state your assumption. The user approves or rejects the whole plan \u2014 that is the only gate.`}var
|
|
726
|
-
`),s=[],n=!1,o="";for(let r of e){let i=
|
|
727
|
-
`)}function
|
|
737
|
+
- Do NOT call ask_user. If anything is ambiguous, add an "## Assumptions" section to the plan and state your assumption. The user approves or rejects the whole plan \u2014 that is the only gate.`}var ds=0;function RE(){!Ee||Ee.status!=="executing"||(ds>0&&Al(ds-1,"done"),ds<Ee.steps.length&&(Al(ds,"in_progress"),ds++))}function CE(){if(!Ee||Ee.status!=="executing"||Ee.steps.length===0)return null;let t=Math.min(ds,Ee.steps.length),e=Ee.steps.length,s=Math.max(0,t-1),n=Ee.steps[s]?.description||"";return{current:t,total:e,description:n}}function AE(){ds=0}var Tg=["interactive","semi-auto","autonomous"],Rg="interactive";function OE(t){return Tg.includes(t)?(Rg=t,!0):!1}function NE(){return Rg}Cg.exports={createPlan:pE,getActivePlan:hE,setPlanMode:mE,isPlanMode:gE,approvePlan:yE,startExecution:wE,updateStep:Al,formatPlan:$E,savePlan:bE,loadPlan:_E,listPlans:xE,clearPlan:EE,getPlanModePrompt:TE,setPlanContent:SE,getPlanContent:vE,extractStepsFromText:kE,advancePlanStep:RE,getPlanStepInfo:CE,PLAN_MODE_ALLOWED_TOOLS:vg,setAutonomyLevel:OE,getAutonomyLevel:NE,AUTONOMY_LEVELS:Tg}});var Fg=J((FC,qg)=>{var{C:k}=Je();function Ag(){return Math.max(10,(process.stdout.columns||80)-2)}function ME(t){if(!t)return"";let e=t.split(`
|
|
738
|
+
`),s=[],n=!1,o="";for(let r of e){let i=Ag();if(r.trim().startsWith("```")){if(n)s.push(`${k.dim}${"\u2500".repeat(40)}${k.reset}`),n=!1,o="";else{n=!0,o=r.trim().substring(3).trim();let a=o?` ${o} `:"";s.push(`${k.dim}${"\u2500".repeat(3)}${a}${"\u2500".repeat(Math.max(0,37-a.length))}${k.reset}`)}continue}if(n){s.push(` ${Pl(r,o)}`);continue}if(r.startsWith("###### ")){s.push(`${k.bold}${k.cyan} ${At(r.substring(7))}${k.reset}`);continue}if(r.startsWith("##### ")){s.push(`${k.bold}${k.cyan} ${At(r.substring(6))}${k.reset}`);continue}if(r.startsWith("#### ")){s.push(`${k.bold}${k.cyan} ${At(r.substring(5))}${k.reset}`);continue}if(r.startsWith("### ")){s.push(`${k.bold}${k.cyan} ${At(r.substring(4))}${k.reset}`);continue}if(r.startsWith("## ")){s.push(`${k.bold}${k.cyan} ${At(r.substring(3))}${k.reset}`);continue}if(r.startsWith("# ")){s.push(`${k.bold}${k.cyan}${At(r.substring(2))}${k.reset}`);continue}if(/^\s*[-*]\s/.test(r)){let a=r.match(/^(\s*)/)[1],c=r.replace(/^\s*[-*]\s/,""),l=`${a}${k.cyan}\u2022${k.reset} ${ps(c)}`;s.push(hs(l,i,a+" "));continue}if(/^\s*\d+\.\s/.test(r)){let a=r.match(/^(\s*)(\d+)\.\s(.*)/);if(a){let c=a[1],l=a[2],u=a[3],d=`${c}${k.cyan}${l}.${k.reset} ${ps(u)}`,f=c+" ".repeat(l.length+2);s.push(hs(d,i,f));continue}}s.push(hs(ps(r),i))}return s.join(`
|
|
739
|
+
`)}function At(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function ps(t){return t?t.replace(/`([^`]+)`/g,`${k.cyan}$1${k.reset}`).replace(/\*\*([^*]+)\*\*/g,`${k.bold}$1${k.reset}`).replace(/\*([^*]+)\*/g,`${k.dim}$1${k.reset}`).replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${k.cyan}$1${k.reset} ${k.dim}($2)${k.reset}`):""}function Pl(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?Og(t):e==="bash"||e==="sh"||e==="shell"||e==="zsh"?Ng(t):e==="json"||e==="jsonc"?Mg(t):e==="python"||e==="py"?Pg(t):e==="go"||e==="golang"?Lg(t):e==="rust"||e==="rs"?Ig(t):e==="css"||e==="scss"||e==="less"?jg(t):e==="html"||e==="xml"||e==="svg"||e==="htm"?Dg(t):t:""}function Og(t){let e=/\b(const|let|var|function|return|if|else|for|while|class|import|export|from|require|async|await|new|this|throw|try|catch|switch|case|break|default|typeof|instanceof)\b/g,s=/(["'`])(?:(?=(\\?))\2.)*?\1/g,n=/(\/\/.*$)/,o=/\b(\d+\.?\d*)\b/g,r=t;return r=r.replace(o,`${k.yellow}$1${k.reset}`),r=r.replace(e,`${k.magenta}$1${k.reset}`),r=r.replace(s,`${k.green}$&${k.reset}`),r=r.replace(n,`${k.dim}$1${k.reset}`),r}function Ng(t){let e=/^(\s*)([\w-]+)/,s=/(--?\w[\w-]*)/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(#.*$)/,r=t;return r=r.replace(s,`${k.cyan}$1${k.reset}`),r=r.replace(e,`$1${k.green}$2${k.reset}`),r=r.replace(n,`${k.yellow}$&${k.reset}`),r=r.replace(o,`${k.dim}$1${k.reset}`),r}function Mg(t){let e=/("[\w-]+")\s*:/g,s=/:\s*("(?:[^"\\]|\\.)*")/g,n=/:\s*(\d+\.?\d*)/g,o=/:\s*(true|false|null)/g,r=t;return r=r.replace(e,`${k.cyan}$1${k.reset}:`),r=r.replace(s,`: ${k.green}$1${k.reset}`),r=r.replace(n,`: ${k.yellow}$1${k.reset}`),r=r.replace(o,`: ${k.magenta}$1${k.reset}`),r}function Pg(t){let e=/\b(def|class|if|elif|else|for|while|return|import|from|as|try|except|finally|raise|with|yield|lambda|pass|break|continue|and|or|not|in|is|None|True|False|self|async|await|nonlocal|global)\b/g,s=/("""[\s\S]*?"""|'''[\s\S]*?'''|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')/g,n=/(#.*$)/,o=/\b(\d+\.?\d*)\b/g,r=/^(\s*@\w+)/,i=t;return i=i.replace(o,`${k.yellow}$1${k.reset}`),i=i.replace(e,`${k.magenta}$1${k.reset}`),i=i.replace(r,`${k.cyan}$1${k.reset}`),i=i.replace(s,`${k.green}$&${k.reset}`),i=i.replace(n,`${k.dim}$1${k.reset}`),i}function Lg(t){let e=/\b(func|package|import|var|const|type|struct|interface|map|chan|go|defer|return|if|else|for|range|switch|case|default|break|continue|select|fallthrough|nil|true|false|make|new|len|cap|append|copy|delete|panic|recover)\b/g,s=/\b(string|int|int8|int16|int32|int64|uint|uint8|uint16|uint32|uint64|float32|float64|bool|byte|rune|error|any)\b/g,n=/(["'`])(?:(?=(\\?))\2.)*?\1/g,o=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,i=t;return i=i.replace(r,`${k.yellow}$1${k.reset}`),i=i.replace(s,`${k.cyan}$1${k.reset}`),i=i.replace(e,`${k.magenta}$1${k.reset}`),i=i.replace(n,`${k.green}$&${k.reset}`),i=i.replace(o,`${k.dim}$1${k.reset}`),i}function Ig(t){let e=/\b(fn|let|mut|const|struct|enum|impl|trait|pub|use|mod|crate|self|super|match|if|else|for|while|loop|return|break|continue|where|as|in|ref|move|async|await|unsafe|extern|type|static|dyn|macro_rules)\b/g,s=/\b(i8|i16|i32|i64|i128|u8|u16|u32|u64|u128|f32|f64|bool|char|str|String|Vec|Option|Result|Box|Rc|Arc|Self|Some|None|Ok|Err|true|false)\b/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,i=/\b(\w+!)/g,a=t;return a=a.replace(r,`${k.yellow}$1${k.reset}`),a=a.replace(s,`${k.cyan}$1${k.reset}`),a=a.replace(e,`${k.magenta}$1${k.reset}`),a=a.replace(i,`${k.yellow}$1${k.reset}`),a=a.replace(n,`${k.green}$&${k.reset}`),a=a.replace(o,`${k.dim}$1${k.reset}`),a}function jg(t){let e=/^(\s*)([\w-]+)\s*:/,s=/:\s*([^;]+)/,n=/^(\s*[.#@][\w-]+)/,o=/\b(\d+\.?\d*(px|em|rem|%|vh|vw|s|ms|deg|fr)?)\b/g,r=/(\/\*.*?\*\/|\/\/.*$)/,i=/(#[0-9a-fA-F]{3,8})\b/g,a=t;return a=a.replace(i,`${k.yellow}$1${k.reset}`),a=a.replace(o,`${k.yellow}$1${k.reset}`),a=a.replace(e,`$1${k.cyan}$2${k.reset}:`),a=a.replace(n,`$1${k.magenta}$&${k.reset}`),a=a.replace(r,`${k.dim}$1${k.reset}`),a}function Dg(t){let e=/<\/?(\w[\w-]*)/g,s=/\s([\w-]+)=/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(<!--.*?-->)/g,r=/(&\w+;)/g,i=t;return i=i.replace(o,`${k.dim}$1${k.reset}`),i=i.replace(n,`${k.green}$&${k.reset}`),i=i.replace(e,`<${k.magenta}$1${k.reset}`),i=i.replace(s,` ${k.cyan}$1${k.reset}=`),i=i.replace(r,`${k.yellow}$1${k.reset}`),i}function hs(t,e,s=""){if(!e||e<10)return t;let n="",o=0,r=-1,i=0,a=0,c=t.length;for(;i<c;){if(t[i]==="\x1B"){let l=i+1;if(l<c&&t[l]==="["){for(l++;l<c&&!/[a-zA-Z]/.test(t[l]);)l++;l<c&&l++}i=l;continue}if(t[i]===" "&&(r=i),o++,o>e&&r!==-1){n+=t.slice(a,r)+`
|
|
728
740
|
`+s,a=r+1,i=a,o=s.length,r=-1;continue}o>e&&r===-1&&(n+=t.slice(a,i)+`
|
|
729
|
-
`+s,a=i,o=s.length+1),i++}return n+=t.slice(a),n}function
|
|
730
|
-
`)}function
|
|
741
|
+
`+s,a=i,o=s.length+1),i++}return n+=t.slice(a),n}function PE(t,e){if(!t||t.length===0)return"";let s=t.map((i,a)=>{let c=e.reduce((l,u)=>Math.max(l,(u[a]||"").length),0);return Math.max(i.length,c)}),n=s.map(i=>"\u2500".repeat(i+2)).join("\u253C"),o=t.map((i,a)=>` ${k.bold}${i.padEnd(s[a])}${k.reset} `).join("\u2502"),r=[];r.push(`${k.dim}\u250C${n.replace(/┼/g,"\u252C")}\u2510${k.reset}`),r.push(`${k.dim}\u2502${k.reset}${o}${k.dim}\u2502${k.reset}`),r.push(`${k.dim}\u251C${n}\u2524${k.reset}`);for(let i of e){let a=t.map((c,l)=>` ${(i[l]||"").padEnd(s[l])} `).join(`${k.dim}\u2502${k.reset}`);r.push(`${k.dim}\u2502${k.reset}${a}${k.dim}\u2502${k.reset}`)}return r.push(`${k.dim}\u2514${n.replace(/┼/g,"\u2534")}\u2518${k.reset}`),r.join(`
|
|
742
|
+
`)}function LE(t,e,s,n=30){let o=s>0?Math.round(e/s*100):0,r=Math.round(o/100*n),i=n-r,a=o>=100?k.green:o>50?k.yellow:k.cyan;return` ${t} ${a}${"\u2588".repeat(r)}${k.dim}${"\u2591".repeat(i)}${k.reset} ${o}% (${e}/${s})`}var Ml=class{constructor(){this.buffer="",this.inCodeBlock=!1,this.codeBlockLang="",this.lineCount=0,this._cursorTimer=null,this._cursorFrame=0,this._cursorActive=!1}_safeWrite(e){try{this.lineCount+=(e.match(/\n/g)||[]).length,process.stdout.write(e)}catch(s){if(s.code!=="EPIPE")throw s}}_cursorWrite(e){try{process.stderr.write(e)}catch(s){if(s.code!=="EPIPE")throw s}}startCursor(){process.stderr.isTTY&&(this._cursorActive=!0,this._cursorFrame=0,this._cursorWrite("\x1B[?25l"),this._renderCursor(),this._cursorTimer=setInterval(()=>this._renderCursor(),100))}_renderCursor(){let s=[0,1,2,3,4,3,2,1],n=s[this._cursorFrame%s.length],o="";for(let r=0;r<5;r++)o+=r===n?`${Yt().T.cyan}\u25CF${Yt().T.reset}`:" ";this._cursorWrite(`\x1B[2K\r${o}`),this._cursorFrame++}_clearCursorLine(){this._cursorActive&&this._cursorWrite("\x1B[2K\r")}stopCursor(){this._cursorTimer&&(clearInterval(this._cursorTimer),this._cursorTimer=null),this._cursorActive&&(this._cursorWrite("\x1B[2K\r\x1B[?25h"),this._cursorActive=!1)}push(e){if(!e)return;this._clearCursorLine(),this.buffer+=e;let s;for(;(s=this.buffer.indexOf(`
|
|
731
743
|
`))!==-1;){let n=this.buffer.substring(0,s);this.buffer=this.buffer.substring(s+1),this._renderLine(n)}this._cursorActive&&(this._renderCursor(),this._cursorTimer&&clearInterval(this._cursorTimer),this._cursorTimer=setInterval(()=>this._renderCursor(),100))}flush(){this.stopCursor(),this.buffer&&(this._renderLine(this.buffer),this.buffer=""),this.inCodeBlock&&(this._safeWrite(`${k.dim}${"\u2500".repeat(40)}${k.reset}
|
|
732
|
-
`),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){let s=
|
|
744
|
+
`),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){let s=Ag();if(e.trim().startsWith("```")){if(this.inCodeBlock)this._safeWrite(`${k.dim}${"\u2500".repeat(40)}${k.reset}
|
|
733
745
|
`),this.inCodeBlock=!1,this.codeBlockLang="";else{this.inCodeBlock=!0,this.codeBlockLang=e.trim().substring(3).trim();let o=this.codeBlockLang?` ${this.codeBlockLang} `:"";this._safeWrite(`${k.dim}${"\u2500".repeat(3)}${o}${"\u2500".repeat(Math.max(0,37-o.length))}${k.reset}
|
|
734
|
-
`)}return}if(this.inCodeBlock){this._safeWrite(` ${
|
|
735
|
-
`);return}if(e.startsWith("###### ")){this._safeWrite(`${k.bold}${k.cyan} ${
|
|
736
|
-
`);return}if(e.startsWith("##### ")){this._safeWrite(`${k.bold}${k.cyan} ${
|
|
737
|
-
`);return}if(e.startsWith("#### ")){this._safeWrite(`${k.bold}${k.cyan} ${
|
|
738
|
-
`);return}if(e.startsWith("### ")){this._safeWrite(`${k.bold}${k.cyan} ${
|
|
739
|
-
`);return}if(e.startsWith("## ")){this._safeWrite(`${k.bold}${k.cyan} ${
|
|
740
|
-
`);return}if(e.startsWith("# ")){this._safeWrite(`${k.bold}${k.cyan}${
|
|
741
|
-
`);return}if(/^\s*[-*]\s/.test(e)){let o=e.match(/^(\s*)/)[1],r=e.replace(/^\s*[-*]\s/,""),i=`${o}${k.cyan}\u2022${k.reset} ${
|
|
742
|
-
`);return}if(/^\s*\d+\.\s/.test(e)){let o=e.match(/^(\s*)(\d+)\.\s(.*)/);if(o){let r=o[1],i=o[2],a=o[3],
|
|
743
|
-
`);return}}let n=
|
|
744
|
-
`)}};
|
|
746
|
+
`)}return}if(this.inCodeBlock){this._safeWrite(` ${Pl(e,this.codeBlockLang)}
|
|
747
|
+
`);return}if(e.startsWith("###### ")){this._safeWrite(`${k.bold}${k.cyan} ${At(e.substring(7))}${k.reset}
|
|
748
|
+
`);return}if(e.startsWith("##### ")){this._safeWrite(`${k.bold}${k.cyan} ${At(e.substring(6))}${k.reset}
|
|
749
|
+
`);return}if(e.startsWith("#### ")){this._safeWrite(`${k.bold}${k.cyan} ${At(e.substring(5))}${k.reset}
|
|
750
|
+
`);return}if(e.startsWith("### ")){this._safeWrite(`${k.bold}${k.cyan} ${At(e.substring(4))}${k.reset}
|
|
751
|
+
`);return}if(e.startsWith("## ")){this._safeWrite(`${k.bold}${k.cyan} ${At(e.substring(3))}${k.reset}
|
|
752
|
+
`);return}if(e.startsWith("# ")){this._safeWrite(`${k.bold}${k.cyan}${At(e.substring(2))}${k.reset}
|
|
753
|
+
`);return}if(/^\s*[-*]\s/.test(e)){let o=e.match(/^(\s*)/)[1],r=e.replace(/^\s*[-*]\s/,""),i=`${o}${k.cyan}\u2022${k.reset} ${ps(r)}`,a=hs(i,s,o+" ");this._safeWrite(`${a}
|
|
754
|
+
`);return}if(/^\s*\d+\.\s/.test(e)){let o=e.match(/^(\s*)(\d+)\.\s(.*)/);if(o){let r=o[1],i=o[2],a=o[3],c=`${r}${k.cyan}${i}.${k.reset} ${ps(a)}`,l=r+" ".repeat(i.length+2),u=hs(c,s,l);this._safeWrite(`${u}
|
|
755
|
+
`);return}}let n=hs(ps(e),s);this._safeWrite(`${n}
|
|
756
|
+
`)}};qg.exports={renderMarkdown:ME,renderInline:ps,stripHeadingMarkers:At,highlightCode:Pl,highlightJS:Og,highlightBash:Ng,highlightJSON:Mg,highlightPython:Pg,highlightGo:Lg,highlightRust:Ig,highlightCSS:jg,highlightHTML:Dg,renderTable:PE,renderProgress:LE,wrapAnsi:hs,StreamRenderer:Ml}});var Yg=J((BC,Hg)=>{var{execSync:IE}=require("child_process"),Ll=require("path"),tr=require("fs"),Il=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function Bg(){return Ll.join(process.cwd(),".nex","hooks")}function jE(){return Ll.join(process.cwd(),".nex","config.json")}function Ug(){let t=jE();if(!tr.existsSync(t))return{};try{return JSON.parse(tr.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function Wi(t){if(!Il.includes(t))return[];let e=[],s=Bg(),n=Ll.join(s,t);tr.existsSync(n)&&e.push(n);let o=Ug();if(o[t]){let r=Array.isArray(o[t])?o[t]:[o[t]];e.push(...r)}return e}function Wg(t,e={},s=3e4){try{return{success:!0,exitCode:0,output:IE(t,{cwd:process.cwd(),encoding:"utf-8",timeout:s,env:{...process.env,...e},stdio:["pipe","pipe","pipe"]}).trim()}}catch(n){let o=typeof n.status=="number"?n.status:1;return{success:!1,exitCode:o,blocked:o===2,output:n.stdout?n.stdout.trim():"",error:n.stderr?n.stderr.trim():n.message}}}function DE(t,e={}){let s=Wi(t);if(s.length===0)return{results:[],blocked:!1};let n={};for(let[r,i]of Object.entries(e))n[`NEX_${r.toUpperCase()}`]=String(i);let o=[];for(let r of s){let i=Wg(r,n);if(o.push({command:r,...i}),i.blocked&&t.startsWith("pre-")){let a=i.output||i.error||"hook blocked tool call";return{results:o,blocked:!0,blockReason:a}}if(!i.success&&t.startsWith("pre-"))break}return{results:o,blocked:!1}}function qE(t){return Wi(t).length>0}function FE(){let t=[];for(let e of Il){let s=Wi(e);s.length>0&&t.push({event:e,commands:s})}return t}function BE(){let t=Bg();return tr.existsSync(t)||tr.mkdirSync(t,{recursive:!0}),t}Hg.exports={HOOK_EVENTS:Il,loadHookConfig:Ug,getHooksForEvent:Wi,executeHook:Wg,runHooks:DE,hasHooks:qE,listHooks:FE,initHooksDir:BE}});var ly=J((YC,cy)=>{"use strict";var{callWithRetry:Kg,runSubAgent:Gg,clearAllLocks:UE}=el(),{parseModelSpec:Xg,getActiveProviderName:UC,getActiveModelId:WC}=st(),{detectCategory:WE,getModelForCategory:zg}=ls(),{MultiProgress:HE,C:he}=Je(),{getModelBriefing:HC}=gi(),Vg=parseInt(process.env.NEX_MAX_PARALLEL||"4",10),Hi=parseInt(process.env.NEX_MAX_SUBTASKS||"8",10),Jg="devstral-2:123b",Zg="kimi-k2.5",Qg=`You are a task decomposition engine. Given a complex user request, split it into independent, atomic sub-tasks.
|
|
745
757
|
|
|
746
758
|
RULES:
|
|
747
759
|
- Output ONLY a JSON array, no markdown fences, no explanation.
|
|
@@ -756,7 +768,7 @@ RULES:
|
|
|
756
768
|
- If the request is simple (single goal), return an array with exactly 1 item.
|
|
757
769
|
|
|
758
770
|
USER REQUEST:
|
|
759
|
-
{prompt}`,
|
|
771
|
+
{prompt}`,ey=`You are a result synthesis engine. Given the results of multiple sub-agents that worked on parts of a larger task, produce a unified summary.
|
|
760
772
|
|
|
761
773
|
RULES:
|
|
762
774
|
- Output ONLY a JSON object with these fields:
|
|
@@ -770,16 +782,16 @@ ORIGINAL REQUEST:
|
|
|
770
782
|
{prompt}
|
|
771
783
|
|
|
772
784
|
SUB-AGENT RESULTS:
|
|
773
|
-
{results}`;async function
|
|
774
|
-
${e.slice(0,200)}`)}async function
|
|
785
|
+
{results}`;async function ty(t,e=1,s=2e3){for(let n=0;n<=e;n++)try{return await t()}catch(o){if(n===e)throw o;await new Promise(r=>setTimeout(r,s))}}function ny(t){let e=0,s=[];return function(){return new Promise(o=>{let r=()=>{e<t?(e++,o(()=>{e--,s.length>0&&s.shift()()})):s.push(r)};r()})}}function YE(t){if(!t||typeof t!="string")return{isComplex:!1,estimatedGoals:0,reason:"empty"};let e=0,s=[],n=t.match(/(?:(?:^|\n)\s*|\s)(?:\d+[.)]\s|[(]\d+[)][\s,]|[(][a-z][)][\s,])/g);n&&n.length>=2&&(e=Math.max(e,n.length),s.push(`${n.length} numbered items`));let o=t.match(/(?:^|\n)\s*[-*]\s+\S/g);o&&o.length>=3&&(e=Math.max(e,o.length),s.push(`${o.length} bullet points`));let r=t.split(/;\s*/).filter(l=>l.trim().length>10);r.length>=3&&(e=Math.max(e,r.length),s.push(`${r.length} semicolon-separated goals`));let i=t.match(/\b(also|additionally|and\s+(?:fix|add|update|create|implement|remove|refactor))\b/gi);i&&i.length>=2&&(e=Math.max(e,i.length+1),s.push(`${i.length} transition keywords`));let a=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10);return{isComplex:e>=a,estimatedGoals:e,reason:s.length>0?s.join(", "):"single goal"}}function jl(t){if(!t||typeof t!="string")throw new Error("Empty response from orchestrator model");let e=t.trim();try{return JSON.parse(e)}catch{}let s=e.match(/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/);if(s)try{return JSON.parse(s[1].trim())}catch{}let n=e.search(/[[\{]/);if(n>=0){let o=e.slice(n);try{return JSON.parse(o)}catch{}}throw new Error(`Could not extract valid JSON from response:
|
|
786
|
+
${e.slice(0,200)}`)}async function sy(t,e,s={}){let n=s.maxSubTasks||Hi,r=[{role:"system",content:Qg.replace("{maxSubTasks}",String(n)).replace("{prompt}",t)},{role:"user",content:t}],i={};if(e){let g=Xg(e);g.provider&&(i.provider=g.provider),g.model&&(i.model=g.model)}let c=(await Kg(r,[],i)).content||"",l=jl(c);if(!Array.isArray(l))throw new Error(`Decompose returned non-array: ${typeof l}`);let u=10,f=l.slice(0,n).map((g,w)=>({id:g.id||`t${w+1}`,task:String(g.task||""),scope:Array.isArray(g.scope)?g.scope:[],estimatedCalls:typeof g.estimatedCalls=="number"?Math.min(g.estimatedCalls,u):8,priority:typeof g.priority=="number"?g.priority:w+1})).filter(g=>g.task.length>0),p=f.reduce((g,w)=>g+w.estimatedCalls,0),h=Hi*u;if(p>h){let{debugLog:g}=Ha();g(`${Yt().T.yellow} \u26A0 Orchestrator: total estimated calls ${p} > ${h} \u2014 consider raising maxSubTasks${Yt().T.reset}`)}return f}async function oy(t,e,s){if(!t||t.length===0)return{summary:"No sub-tasks were executed.",conflicts:[],commitMessage:"",resourcesChanged:[]};let n=t.map((u,d)=>{let f=u.status==="done"?"SUCCESS":u.status==="truncated"?"PARTIAL":"FAILED";return`--- Agent ${d+1} [${f}] ---
|
|
775
787
|
Task: ${u.task}
|
|
776
788
|
Result: ${u.result}
|
|
777
789
|
Tools: ${(u.toolsUsed||[]).join(", ")||"none"}`}).join(`
|
|
778
790
|
|
|
779
|
-
`),r=[{role:"system",content:
|
|
780
|
-
${
|
|
781
|
-
`),i("decomposing"),console.log(`${
|
|
782
|
-
`);let u=Date.now(),d=
|
|
791
|
+
`),r=[{role:"system",content:ey.replace("{prompt}",e).replace("{results}",n)},{role:"user",content:"Synthesize the sub-agent results above."}],i={};if(s){let u=Xg(s);u.provider&&(i.provider=u.provider),u.model&&(i.model=u.model)}let c=(await Kg(r,[],i)).content||"",l=jl(c);return{summary:String(l.summary||""),conflicts:Array.isArray(l.conflicts)?l.conflicts:[],commitMessage:String(l.commitMessage||""),filesChanged:Array.isArray(l.filesChanged)?l.filesChanged:[]}}async function GE(t,e={}){let s=e.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL||Zg,n=e.workerModel||Jg,o=e.maxParallel||Vg,r=e.maxSubTasks||Hi,i=e.onProgress||(()=>{}),a={input:0,output:0};console.log(`
|
|
792
|
+
${he.bold}Orchestrator${he.reset} ${he.dim}model: ${s} | workers: ${n} | max parallel: ${o}${he.reset}
|
|
793
|
+
`),i("decomposing"),console.log(`${he.dim}Phase 1: Decomposing prompt into sub-tasks...${he.reset}`);let c;try{c=await sy(t,s,{maxSubTasks:r})}catch(W){return console.log(`${he.red}Decompose failed: ${W.message}${he.reset}`),{results:[],synthesis:{summary:`Decompose failed: ${W.message}`,conflicts:[],commitMessage:"",resourcesChanged:[]},totalTokens:a}}if(c.length===0)return console.log(`${he.yellow}No sub-tasks generated. Prompt may be too simple for orchestration.${he.reset}`),{results:[],synthesis:{summary:"No sub-tasks generated.",conflicts:[],commitMessage:"",resourcesChanged:[]},totalTokens:a};console.log(`${he.green}Decomposed into ${c.length} sub-tasks:${he.reset}`);for(let W of c){console.log(` ${he.dim}${W.id}:${he.reset} ${W.task}`);let K=W.scope.filter(Boolean);K.length>0&&console.log(` ${he.dim}scope: ${K.join(", ")}${he.reset}`)}console.log("");let l=new Map;for(let W=0;W<c.length;W++)for(let K of c[W].scope)K&&!l.has(K)&&l.set(K,W);i("executing"),console.log(`${he.dim}Phase 2: Running ${c.length} sub-agents (max ${o} parallel)...${he.reset}
|
|
794
|
+
`);let u=Date.now(),d=ny(o),f={findings:[],_lock:!1},p=c.map(W=>{let K=WE(W.task);return(K?zg(K.id):null)||n}),h=c.map((W,K)=>{let ge=`Agent ${K+1} [${p[K]}]: `,Ae=Math.max(20,60-ge.length),qe=W.task.substring(0,Ae)+(W.task.length>Ae?"...":"");return ge+qe}),g=new HE(h);g.start();let w=`
|
|
783
795
|
You are a focused coding agent executing ONE specific sub-task.
|
|
784
796
|
Your scope is limited to the files listed in your task definition.
|
|
785
797
|
|
|
@@ -800,16 +812,28 @@ RULES:
|
|
|
800
812
|
- If your task says "add X to README" \u2014 add it, don't check if it exists first.
|
|
801
813
|
- Max 10 tool calls. If you need more, you are doing too much \u2014 narrow your scope.
|
|
802
814
|
- When done: stop calling tools and write a one-line summary of what you changed.
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
`)
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
`)
|
|
812
|
-
`)
|
|
815
|
+
- You are part of a team of agents. Respect file ownership strictly: write only to files you own; other scoped files are read-only context.
|
|
816
|
+
- Start with symbol-aware reads inside your scope: locate the target function/class/module, then read the exact section instead of scanning broadly.
|
|
817
|
+
- Before finishing, run the smallest relevant verification for your scope and report any residual risk explicitly.
|
|
818
|
+
- If your sub-task is review/audit/verify-oriented, output findings first with severity, file, and impact. If nothing is wrong, say so explicitly and mention remaining risk.
|
|
819
|
+
`,x=new Map;for(let W=0;W<c.length;W++){let K=c[W].priority||1;x.has(K)||x.set(K,[]),x.get(K).push({st:c[W],idx:W})}let O=[...x.keys()].sort((W,K)=>W-K),I=new Array(c.length);for(let W of O){let ge=x.get(W).map(async({st:Ae,idx:qe})=>{let ke=await d();try{let xe=await E(Ae,qe,{acquire:d,subTaskModels:p,labels:h,progress:g,sharedContext:f,_fileOwnership:l,workerModel:n,WORKER_SYSTEM_PROMPT:w});return I[qe]=xe,xe}finally{ke()}});await Promise.all(ge)}async function E(W,K,ge){try{let Ae=f.findings.filter(fe=>fe.agentId!==W.id).map(fe=>`Agent ${fe.agentId} found: ${fe.summary}`).join(`
|
|
820
|
+
`),qe=[...l.entries()].filter(([,fe])=>fe===K).map(([fe])=>fe),ke=[...l.entries()].filter(([,fe])=>fe!==K).map(([fe])=>fe),xe=[Ae?`Prior agent findings:
|
|
821
|
+
${Ae}
|
|
822
|
+
`:"",W.scope.length>0?`Focus on files: ${W.scope.join(", ")}`:"",qe.length>0?`You OWN these files (may read+write): ${qe.join(", ")}`:"",ke.length>0?`READ ONLY (owned by other agents, do NOT write): ${ke.join(", ")}`:""].filter(Boolean),_=ay(W.task),j=p[K],H=process.env.NEX_FALLBACK_MODEL||zg("agentic")||n,M=0,L=await ty(async()=>{let fe=M>0;fe&&(g.update(K,"retry"),process.stderr.write(` ${he.dim}[Agent ${K+1}] retrying after error...${he.reset}
|
|
823
|
+
`)),M++;let pe=fe&&j!==H?H:j;return Gg({task:W.task,type:_,context:xe.length>0?xe.join(`
|
|
824
|
+
`):void 0,max_iterations:Math.min(W.estimatedCalls||10,15),model:pe,_skipLog:!0,_systemPrompt:w,_readOnlyFiles:ke},{onUpdate:Qe=>{if(Qe&&Qe.type==="tool_call"&&process.stderr.isTTY){let lo=`Agent ${K+1} [${pe}]`,Sn=Qe.tool||"...";g.labels[K]=`${lo}: ${Sn}`}}})},1,2e3),b="";if(iy(_,L,W,qe)){let fe=[...new Set([...qe,...Array.isArray(L.filesModified)?L.filesModified:[],...Array.isArray(W.scope)?W.scope:[]])].filter(Boolean);try{g.labels[K]=`Agent ${K+1} [${j}] review`,g.update(K,"retry");let pe=await Gg({task:`Review the completed changes for: ${W.task}`,type:"review",context:VE(W,L,fe),max_iterations:4,model:j,_skipLog:!0,_systemPrompt:w},{onUpdate:()=>{}},1);ry(pe.result)?(b=`
|
|
825
|
+
|
|
826
|
+
Reviewer findings:
|
|
827
|
+
${pe.result}`,f.findings.push({agentId:`${W.id}-review`,summary:String(pe.result||"").slice(0,200),files:fe})):pe.result&&(b=`
|
|
828
|
+
|
|
829
|
+
Reviewer: ${pe.result}`)}catch(pe){b=`
|
|
830
|
+
|
|
831
|
+
Reviewer note: review pass failed (${pe.message})`}}let Z=typeof L.result=="string"?`${L.result}${b}`.slice(0,200):`${String(L.result||"")}${b}`.slice(0,200);return f.findings.push({agentId:W.id,summary:Z,files:Array.isArray(W.scope)?W.scope:[]}),g.labels[K]=h[K],g.update(K,L.status==="failed"?"error":"done"),a.input+=L.tokensUsed?.input||0,a.output+=L.tokensUsed?.output||0,L.tokensUsed?._estimated&&(a._estimated=!0),{...L,result:`${String(L.result||"")}${b}`,_scope:W.scope,_idx:K}}catch(Ae){return g.labels[K]=h[K],g.update(K,"error"),{task:W.task,status:"failed",result:`Error: ${Ae.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}}}let v;try{v=I}finally{g.stop({silent:!0}),UE()}console.log("");let A=Math.round((Date.now()-u)/1e3),te=A>=60?`${Math.floor(A/60)}m ${A%60}s`:`${A}s`;for(let W=0;W<v.length;W++){let K=v[W],Ae=K.status==="done"||K.status==="truncated"&&K.result&&!K.result.startsWith("Error")?`${he.green}\u2713${he.reset}`:`${he.red}\u2717${he.reset}`,qe=K._scope&&K._scope.length>0?K._scope.map(_=>_.replace(/^.*\//,"").replace(/\/$/,"")).filter(Boolean):[],ke=qe.length>0?qe.join(", "):K.task.substring(0,35)+(K.task.length>35?"...":""),xe=W===v.length-1;console.log(` ${Ae} Agent ${W+1} ${he.dim}${ke}${he.reset}${xe?` ${he.dim}${te}${he.reset}`:""}`)}console.log(""),i("synthesizing"),console.log(`${he.dim}Phase 3: Synthesizing results...${he.reset}`);let oe;try{oe=await oy(v,t,s)}catch(W){console.log(`${he.yellow}Synthesize failed: ${W.message} \u2014 using raw results.${he.reset}`),oe={summary:v.map(K=>K.result).join(`
|
|
832
|
+
`),conflicts:[],commitMessage:"",resourcesChanged:[]}}let de=f.findings.flatMap(W=>W.files),ce=new Map;for(let W of de)ce.set(W,(ce.get(W)||0)+1);let ne=[...ce.values()].some(W=>W>1),S=f.findings.length>1&&ne?` ${he.dim}(agents shared context)${he.reset}`:"";if(console.log(`
|
|
833
|
+
${he.bold}Summary:${he.reset} ${oe.summary}${S}`),oe.conflicts.length>0){console.log(`${he.yellow}Conflicts:${he.reset}`);for(let W of oe.conflicts)console.log(` - ${W}`)}oe.commitMessage&&console.log(`${he.dim}Suggested commit: ${oe.commitMessage}${he.reset}`);let Te=a.input===0&&a.output===0?"n/a (provider does not report token counts)":a._estimated?`~${a.input} input / ~${a.output} output (est.)`:`${a.input} input + ${a.output} output`;return console.log(`${he.dim}Tokens: ${Te}${he.reset}
|
|
834
|
+
`),{results:v,synthesis:oe,totalTokens:a}}var zE=/\b(research|analyze|investigate|check|verify|review|audit|read|find|search|discover|look|examine|inspect|scan|list)\b/i,KE=/\b(review|audit|verify|validate|inspect|critique)\b/i,XE=/\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 VE(t,e,s){let n=Array.isArray(s)&&s.length>0?`Files to review: ${s.join(", ")}`:"Files to review: inspect the files touched by the implementing agent";return["Review the finished implementation for correctness, regressions, and missing verification.",`Original task: ${t.task}`,n,`Implementation summary: ${String(e.result||"").slice(0,600)}`,'Report findings first. If no material issue exists, say "No material findings" and mention the main residual risk.'].join(`
|
|
835
|
+
`)}function ry(t){return!t||typeof t!="string"?!1:!/no material findings/i.test(t)}function iy(t,e,s,n){if(t!=="implement"||!e||e.status==="failed")return!1;let o=Array.isArray(s?.scope)?s.scope.length:0,r=Array.isArray(e.filesModified)?e.filesModified.length:0,i=Array.isArray(n)?n.length:0;return o+r+i>0}function ay(t){if(!t)return"implement";let e=zE.test(t),s=KE.test(t);return XE.test(t)?"implement":s?"review":e?"explore":"implement"}cy.exports={runOrchestrated:GE,decompose:sy,synthesize:oy,detectComplexPrompt:YE,extractJSON:jl,createSemaphore:ny,DECOMPOSE_PROMPT:Qg,SYNTHESIZE_PROMPT:ey,DEFAULT_ORCHESTRATOR_MODEL:Zg,DEFAULT_WORKER_MODEL:Jg,DEFAULT_MAX_PARALLEL:Vg,DEFAULT_MAX_SUBTASKS:Hi,withRetry:ty,_classifyWorkerType:ay,_hasMaterialReviewFindings:ry,_shouldRunFollowUpReview:iy}});var bl=J((JC,By)=>{var{C:m,Spinner:to,TaskProgress:JE,formatToolCall:ZE,formatToolSummary:Vl,formatSectionHeader:Yi,formatMilestone:QE,setActiveTaskProgress:GC,getThinkingVerb:Dl,setActiveModelForSpinner:uy}=Je(),{debugLog:D,warnLog:zC}=Ha(),{MilestoneTracker:eT}=Id(),{callStream:dy}=st(),{parseToolArgs:tT}=mo(),{executeTool:nT}=Ls(),{gatherProjectContext:sT}=Zm(),{fitToContext:oT,forceCompress:cn,getUsage:Jt,estimateTokens:rT,buildProgressSnapshot:iT}=rn(),{autoSave:aT,flushAutoSave:cT}=Ii(),{scoreMessages:lT,formatScore:uT,appendScoreHistory:dT}=ji(),{detectCategory:fT,getModelForPhase:Jl,getPhaseBudget:ms,isPhaseRoutingEnabled:pT}=ls();function Oe(t){aT(t),cT()}function hT(t){if(!t||typeof t!="string")return!0;let e=t.trim();return!!(e.length<80||/^(done|complete|finished|all done|analysis complete|finally done)[.!]*$/i.test(e)||/^[^.!]{0,40}\?$/.test(e))}function Gi(t){try{if(!t.some(n=>n.role!=="assistant"?!1:!!(Array.isArray(n.content)&&n.content.some(o=>o&&o.type==="tool_use")||Array.isArray(n.tool_calls)&&n.tool_calls.length>0)))return;let s=lT(t);if(!s)return;console.log(uT(s,m));try{let{_getSessionsDir:n}=Ii(),o=require("fs"),r=require("path").join(n(),"_autosave.json");if(o.existsSync(r)){let i=JSON.parse(o.readFileSync(r,"utf-8"));i.score=s.score,i.scoreGrade=s.grade,i.scoreIssues=s.issues,o.writeFileSync(r,JSON.stringify(i,null,2))}}catch{}try{let{getActiveModel:n}=mo(),o=Er();dT(s.score,{version:o.version,model:n?n():null,sessionName:"_autosave",issues:s.issues})}catch{}}catch{}}var{getMemoryContext:mT}=qo(),{getDeploymentContextBlock:gT,probeUrlServer:yT}=xl(),{getFewShotForInput:wT}=wg(),{checkPermission:$T,setPermission:bT,savePermissions:_T}=Sg(),{confirm:Sy,setAllowAlwaysHandler:xT,getAutoConfirm:ur}=yo(),{isPlanMode:dr,getPlanModePrompt:kT,PLAN_MODE_ALLOWED_TOOLS:vy,setPlanContent:ST,extractStepsFromText:vT,createPlan:ET,getActivePlan:KC,startExecution:XC,advancePlanStep:TT,getPlanStepInfo:RT}=Ui(),{StreamRenderer:CT}=Fg(),{runHooks:fy}=Yg(),{routeMCPCall:AT,getMCPToolDefinitions:OT}=cc(),{getSkillInstructions:NT,getSkillToolDefinitions:MT,routeSkillCall:PT,matchSkillTriggers:LT}=ic(),{trackUsage:py,estimateTokens:hy}=Wr();function my(t){return!t||typeof t!="string"?0:typeof hy=="function"?hy(t):Math.ceil(t.length/4)}var{validateToolArgs:IT}=dc(),{filterToolsForModel:gy,getModelTier:jT,PROVIDER_DEFAULT_TIER:VC}=To(),{getConfiguredProviders:DT,getActiveProviderName:no,getActiveModelId:en,setActiveModel:ql,MODEL_EQUIVALENTS:ca}=st(),{getModelProfile:qT,getModelBriefing:FT}=gi(),De=require("fs"),Ge=require("path"),BT=(()=>{let t=parseInt(process.env.NEX_MILESTONE_STEPS??"5",10);return Number.isFinite(t)&&t>=0?t:5})();function UT(t){let e=QE(t.phaseName,t.stepCount,t.toolCounts,t.elapsed,t.filesRead,t.filesModified);process.stdout.write(`${e}
|
|
836
|
+
`)}var yy=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi,wy=/(?:^|\s)(https?:\/\/[^\s]+\.(?:png|jpe?g|gif|webp)(?:\?[^\s]*)?)(?:\s|$)/gi,WT=/\b(?:clipboard|pasteboard|zwischenablage|screenshot aus clipboard)\b/i;function HT(t){let e=[],s;for(yy.lastIndex=0;(s=yy.exec(t))!==null;){let n=s[1].trim(),o=n.startsWith("~")?n.replace("~",process.env.HOME||""):Ge.resolve(n);De.existsSync(o)&&e.push({raw:n,abs:o})}return e}function Ey(t){let e=[],s;for(wy.lastIndex=0;(s=wy.exec(t))!==null;)e.push(s[1].trim());return e}async function Ty(t){try{let s=await require("axios").get(t,{responseType:"arraybuffer",timeout:1e4,maxContentLength:10*1024*1024,headers:{"User-Agent":"nex-code/vision"}}),n=s.headers["content-type"]||"",o=n.startsWith("image/")?n.split(";")[0]:YT(t);return{data:Buffer.from(s.data).toString("base64"),media_type:o}}catch{return null}}function YT(t){let e=t.toLowerCase();return e.includes(".jpg")||e.includes(".jpeg")?"image/jpeg":e.includes(".gif")?"image/gif":e.includes(".webp")?"image/webp":"image/png"}function Ry(){if(process.platform!=="darwin")return null;let{spawnSync:t}=require("child_process"),e=Ge.join(require("os").tmpdir(),`nex-clipboard-${Date.now()}.png`);if(t("pngpaste",[e],{timeout:3e3}).status===0&&De.existsSync(e)){let o=De.readFileSync(e);if(o.length>100)return{data:o.toString("base64"),media_type:"image/png",path:e};try{De.unlinkSync(e)}catch(r){console.error("Failed to unlink temp file:",r)}}let n=t("osascript",["-e",`try
|
|
813
837
|
set imgData to the clipboard as \xABclass PNGf\xBB
|
|
814
838
|
return "has_image"
|
|
815
839
|
on error
|
|
@@ -820,64 +844,77 @@ end try`],{timeout:3e3});if(n.stdout&&n.stdout.toString().trim()==="has_image"){
|
|
|
820
844
|
set fRef to open for access filePath with write permission
|
|
821
845
|
write imgData to fRef
|
|
822
846
|
close access fRef
|
|
823
|
-
`;if(t("osascript",["-e",o],{timeout:5e3}).status===0&&
|
|
847
|
+
`;if(t("osascript",["-e",o],{timeout:5e3}).status===0&&De.existsSync(e)){let i=De.readFileSync(e);if(i.length>100)return{data:i.toString("base64"),media_type:"image/png",path:e}}}return null}function $y(t){let e=De.readFileSync(t),s=Ge.extname(t).toLowerCase().replace(".",""),n=s==="jpg"||s==="jpeg"?"image/jpeg":s==="png"?"image/png":s==="gif"?"image/gif":s==="webp"?"image/webp":"image/png";return{data:e.toString("base64"),media_type:n}}function Cy(t){let e=HT(t),s=Ey(t),n=WT.test(t),o=s.length>0||n;if(e.length===0&&!o)return t;if(!o){let r=[{type:"text",text:t}];for(let i of e)try{let{data:a,media_type:c}=$y(i.abs);r.push({type:"image",media_type:c,data:a})}catch{}return r.length>1?r:t}return(async()=>{let r=[{type:"text",text:t}];for(let i of e)try{let{data:a,media_type:c}=$y(i.abs);r.push({type:"image",media_type:c,data:a})}catch(a){D(`${m.yellow} \u26A0 Path resolution failed: ${a.message}${m.reset}`)}if(s.length>0){let i=await Promise.all(s.map(Ty));for(let a of i)a&&r.push({type:"image",media_type:a.media_type,data:a.data})}if(n){let i=Ry();i?(r.push({type:"image",media_type:i.media_type,data:i.data}),r[0].text+=`
|
|
824
848
|
[Clipboard image attached: ${i.path}]`):r[0].text+=`
|
|
825
|
-
[No image found in clipboard]`}return r.length>1?r:t})()}var
|
|
849
|
+
[No image found in clipboard]`}return r.length>1?r:t})()}var GT=[/\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 Ay(t){return typeof t!="string"||!t?!1:GT.some(e=>e.test(t))}function zT(t){if(!t||t.length<200)return{text:t,truncated:!1,repeatCount:0};let s=t.split(/(?<=\. )/).filter(c=>c.trim().length>0);if(s.length<6)return{text:t,truncated:!1,repeatCount:0};let n=new Map;for(let c=0;c<=s.length-3;c++){let l=s.slice(c,c+3).join("").trim();l.length>30&&n.set(l,(n.get(l)||0)+1)}let o=0,r="";for(let[c,l]of n)l>o&&(o=l,r=c);if(o<3)return{text:t,truncated:!1,repeatCount:o};let i=`
|
|
826
850
|
|
|
827
|
-
[SYSTEM: Output repetition detected \u2014 response truncated (${o}\xD7 repeated paragraph)]`,a;if(t.length>8e3)a=t.slice(0,3e3)+i;else{let
|
|
828
|
-
`),n=new Map;for(let p of s){let
|
|
851
|
+
[SYSTEM: Output repetition detected \u2014 response truncated (${o}\xD7 repeated paragraph)]`,a;if(t.length>8e3)a=t.slice(0,3e3)+i;else{let c=0,l=-1,u=0;for(;c<2;){let d=t.indexOf(r,u);if(d===-1)break;c++,l=d+r.length,u=d+1}a=l>0?t.slice(0,l)+i:t.slice(0,3e3)+i}return{text:a,truncated:!0,repeatCount:o}}function Zl(t,e=5){if(!t||t.length<40)return{text:t,truncated:!1,repeatCount:0};let s=t.split(`
|
|
852
|
+
`),n=new Map;for(let p of s){let h=p.trim();h.length>=20&&n.set(h,(n.get(h)||0)+1)}let o=0,r="";for(let[p,h]of n)h>o&&(o=h,r=p);let a=r.toLowerCase().includes("read_file")||r.toLowerCase().includes("reading")?2:e;if(o<=a)return{text:t,truncated:!1,repeatCount:o};let c=`
|
|
829
853
|
|
|
830
|
-
\u26A0 [Response truncated: repeated paragraph detected (${o}\xD7)]`,
|
|
854
|
+
\u26A0 [Response truncated: repeated paragraph detected (${o}\xD7)]`,l=0,u=-1,d=0;for(;l<e;){let p=t.indexOf(r,d);if(p===-1)break;l++,u=p+r.length,d=p+1}return{text:u>0?t.slice(0,u)+c:t.slice(0,2e3)+c,truncated:!0,repeatCount:o}}var Fl=null,Bl=null,Ul=null;function dt(){if(Fl===null){let{TOOL_DEFINITIONS:t}=Ls();Fl=t}return Bl===null&&(Bl=MT()),Ul===null&&(Ul=OT()),[...Fl,...Bl,...Ul]}var Ql=50;function KT(t){Number.isFinite(t)&&t>0&&(Ql=t)}var Vi=()=>null;function XT(t){Vi=t}var rr=null,eu=null,so=null,Ji=new Map,VT=1e4,JT=6e3,ZT=/\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 QT(t){return!t||typeof t!="string"?t:t.replace(ZT,(e,s)=>`${s}=***REDACTED***`)}var eR=7e3,tR=4e3;function nR(t,e=null){let s=QT(t),n=rT(s),o=e==="read_file"?eR:VT,r=e==="read_file"?tR:JT;if(n>o)try{let{compressToolResult:i}=rn();return i(s,r)}catch{return s}return s}function Oy(t){try{let{getActiveModel:e}=st(),s=e(),n=s?`${s.provider}:${s.id}`:"default";if(Ji.has(n))return Ji.get(n);let o=gy(t);return Ji.set(n,o),o}catch{return gy(t)}}function sR(){Ji.clear()}var ir={hash:null,ts:0},oR=3e4;async function Ny(){if(ir.hash&&Date.now()-ir.ts<oR)return ir.hash;try{let t=require("fs").promises,e=require("path"),s=[e.join(process.cwd(),"package.json"),e.join(process.cwd(),".git","HEAD"),e.join(process.cwd(),"README.md"),e.join(process.cwd(),"NEX.md")],o=(await Promise.allSettled(s.map(i=>t.stat(i).then(a=>`${i}:${a.mtimeMs}`)))).filter(i=>i.status==="fulfilled").map(i=>i.value);try{let{getMemoryContextHash:i}=qo(),a=i();a&&o.push(`memory:${a}`)}catch{}try{let i=e.join(process.cwd(),".nex","brain");if(De.existsSync(i)){let a=await t.stat(i);o.push(`brain:${a.mtimeMs}`)}}catch{}let r=o.join("|");return ir={hash:r,ts:Date.now()},r}catch{return`fallback:${Date.now()}`}}function tu(){rr=null,eu=null,ir={hash:null,ts:0},so=null}var rR=new Set(["spawn_agents"]),Wl=10,Hl=10,zi=5,by=6e4,Yl=12e4,iR=process.env.NEX_STALE_AUTO_SWITCH!=="0";function aR(t){try{let e=require("fs"),s=require("path"),n=s.join(process.cwd(),".nex","plans");e.existsSync(n)||e.mkdirSync(n,{recursive:!0});let o=s.join(n,"current-plan.md");e.writeFileSync(o,t,"utf-8")}catch{}}xT(t=>{bT(t,"allow"),_T(),console.log(`${m.green} \u2713 ${t}: always allow${m.reset}`)});async function cR(t){let e=t.function.name,s=tT(t.function.arguments),n=t.id||`cli-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!s){let d=dt().find(p=>p.function.name===e),f=d?JSON.stringify(d.function.parameters,null,2):"unknown";return D(`${m.yellow} \u26A0 ${e}: malformed arguments, sending schema hint${m.reset}`),{callId:n,fnName:e,args:null,canExecute:!1,errorResult:{role:"tool",content:`ERROR: Malformed tool arguments. Could not parse your arguments as JSON.
|
|
831
855
|
Raw input: ${typeof t.function.arguments=="string"?t.function.arguments.substring(0,200):"N/A"}
|
|
832
856
|
|
|
833
857
|
Expected JSON schema for "${e}":
|
|
834
858
|
${f}
|
|
835
859
|
|
|
836
|
-
Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:n}}}if(s&&typeof s.path=="string")try{let u=require("os"),d=
|
|
837
|
-
`)[0]}${
|
|
838
|
-
|
|
839
|
-
[SYSTEM: This is argument error #${u} for "${e}". Study the "Expected parameters" schema above and correct your call \u2014 do not repeat the same mistake.]`:o.error;return{callId:n,fnName:e,args:s,canExecute:!1,errorResult:{role:"tool",content:d,tool_call_id:n}}}let r=o.corrected||s;if(o.corrected){let u=Object.keys(s),d=Object.keys(o.corrected),f=u.filter(p=>!d.includes(p));f.length&&console.log(`${
|
|
840
|
-
...(truncated ${i.length-5e4} chars)`:i,
|
|
841
|
-
`)[0],c
|
|
842
|
-
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(
|
|
843
|
-
HINT: use list_directory instead of bash ls \u2014 it is the preferred tool for listing directory contents.`:/\bfind\s+\S/.test(
|
|
844
|
-
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:
|
|
845
|
-
`)):(
|
|
846
|
-
`)}function
|
|
860
|
+
Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:n}}}if(s&&typeof s.path=="string")try{let u=require("os"),d=Ge.resolve(process.cwd(),s.path.replace(/^~/,u.homedir())),f=s.path;s.path=Ge.relative(process.cwd(),d)||".",Object.defineProperty(s,"_originalPath",{value:f,enumerable:!1})}catch(u){console.error("path resolution failed:",u.message)}let o=IT(e,s);if(!o.valid){D(`${m.yellow} \u26A0 ${e}: ${o.error.split(`
|
|
861
|
+
`)[0]}${m.reset}`);let u=(xy.get(e)||0)+1;xy.set(e,u);let d=u>=2?`${o.error}
|
|
862
|
+
|
|
863
|
+
[SYSTEM: This is argument error #${u} for "${e}". Study the "Expected parameters" schema above and correct your call \u2014 do not repeat the same mistake.]`:o.error;return{callId:n,fnName:e,args:s,canExecute:!1,errorResult:{role:"tool",content:d,tool_call_id:n}}}let r=o.corrected||s;if(o.corrected){let u=Object.keys(s),d=Object.keys(o.corrected),f=u.filter(p=>!d.includes(p));f.length&&console.log(`${m.dim} \u2713 ${e}: corrected args (${f.join(", ")})${m.reset}`)}if(dr()&&!vy.has(e))return console.log(`${m.yellow} \u2717 ${e}: blocked in plan mode${m.reset}`),{callId:n,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`PLAN MODE: '${e}' is blocked. Only read-only tools are allowed. Present your plan as text output instead of making changes.`,tool_call_id:n}};let i=new Set(["read_file","list_directory","search_files","glob","grep","git_status","git_diff","git_log","git_show","ssh_exec"]),a=new Set(["read_file","list_directory","glob","grep","bash","git_status","git_diff","git_log","ssh_exec"]),c=e==="spawn_agents"&&Array.isArray(r?.agents)&&r.agents.length>0&&r.agents.every(u=>u.background===!0);if(be&&Pe==="plan"&&!i.has(e)&&!e.startsWith("skill_")&&!c)return jn++,D(`${m.yellow} \u2717 ${e}: blocked in plan phase (read-only, block #${jn})${m.reset}`),{callId:n,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`PLAN PHASE: '${e}' is blocked. Analyze the codebase using read-only tools, then present your findings as text. Edits happen in the next phase.`,tool_call_id:n}};if(be&&Pe==="verify"&&!a.has(e)&&!e.startsWith("skill_"))return D(`${m.yellow} \u2717 ${e}: blocked in verify phase (read + bash only)${m.reset}`),{callId:n,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`VERIFY PHASE: '${e}' is blocked. Use read_file and bash (for tests/linters) to verify changes. Report PASS or FAIL.`,tool_call_id:n}};let l=$T(e);if(l==="deny")return console.log(`${m.red} \u2717 ${e}: denied by permissions${m.reset}`),{callId:n,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`DENIED: Tool '${e}' is blocked by permissions`,tool_call_id:n}};if(l==="ask"){let u=` Allow ${e}?`;return e==="bash"&&r.command&&(u=` bash: \`${r.command.substring(0,80)}${r.command.length>80?"\u2026":""}\`?`),await Sy(u,{toolName:e})?{callId:n,fnName:e,args:r,canExecute:!0,confirmedByUser:!0,errorResult:null}:{callId:n,fnName:e,args:r,canExecute:!1,confirmedByUser:!1,errorResult:{role:"tool",content:`CANCELLED: User declined ${e}`,tool_call_id:n}}}return{callId:n,fnName:e,args:r,canExecute:!0,confirmedByUser:!0,errorResult:null}}async function lR(t,e,s={}){let n=await PT(t,e);if(n!==null)return n;let o=await AT(t,e);return o!==null?o:nT(t,e,s)}function uR(t,e){switch(t){case"read_file":case"write_file":case"edit_file":case"patch_file":case"list_directory":return e._originalPath||e.path||"";case"bash":return(e.command||"").substring(0,60);case"grep":case"search_files":case"glob":return e.pattern||"";case"web_fetch":return(e.url||"").substring(0,50);case"web_search":return(e.query||"").substring(0,40);default:return""}}async function Gl(t,e=!1){e||console.log(ZE(t.fnName,t.args));let s=fy("pre-tool",{tool_name:t.fnName}),n=s.results;if(s.blocked){let w=`BLOCKED: pre-tool hook rejected ${t.fnName}: ${s.blockReason}`;e||console.log(`${m.yellow} [hook pre-tool] BLOCKED: ${s.blockReason}${m.reset}`);let x=Vl(t.fnName,t.args,w,!0);return e||console.log(x),{msg:{role:"tool",content:w,tool_call_id:t.callId},summary:x}}if(!e&&n.length>0)for(let w of n)w.success?console.log(`${m.dim} [hook pre-tool] ${w.command} \u2192 ${w.output||"ok"}${m.reset}`):console.log(`${m.yellow} [hook pre-tool] ${w.command} \u2192 ERROR: ${w.error}${m.reset}`);dn?.onToolStart&&dn.onToolStart(t.fnName,t.args);let o=await lR(t.fnName,t.args,{silent:!0,autoConfirm:t.confirmedByUser===!0}),r=null,i;o&&typeof o=="object"&&o.text?(i=String(o.text),Array.isArray(o.images)&&o.images.length>0&&(r=o.images)):i=String(o??"");let a=i.length>5e4?i.substring(0,5e4)+`
|
|
864
|
+
...(truncated ${i.length-5e4} chars)`:i,c=a.split(`
|
|
865
|
+
`)[0],l=c.startsWith("ERROR")||c.includes("CANCELLED")||c.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(a)&&/✗ Agent/.test(a),u=Vl(t.fnName,t.args,a,l);e||console.log(u),dn?.onToolEnd&&dn.onToolEnd(t.fnName,u,!l);let f=fy("post-tool",{tool_name:t.fnName}).results;if(!e&&f.length>0)for(let w of f)w.success?console.log(`${m.dim} [hook post-tool] ${w.command} \u2192 ${w.output||"ok"}${m.reset}`):console.log(`${m.yellow} [hook post-tool] ${w.command} \u2192 ERROR: ${w.error}${m.reset}`);let h=nR(a,t.fnName);if(t.fnName==="bash"&&t.args?.command){let w=t.args.command.trim();!/cat\s*>|<</.test(w)&&/\bcat\s+\S/.test(w)?h+=`
|
|
866
|
+
HINT: use read_file instead of bash cat \u2014 it is faster, context-efficient, and the preferred tool for reading files.`:/^\s*ls(\s|$)/.test(w)&&!/npm|yarn|pnpm|make|git\b/.test(w)?h+=`
|
|
867
|
+
HINT: use list_directory instead of bash ls \u2014 it is the preferred tool for listing directory contents.`:/\bfind\s+\S/.test(w)&&!/git\b|npm\b|-exec\b|-delete\b|-print0\b/.test(w)&&(h+=`
|
|
868
|
+
HINT: use glob instead of bash find for file discovery \u2014 it is faster and the preferred tool (e.g. glob('**/*.jsx')).`)}return{msg:{role:"tool",content:r?[{type:"text",text:h},...r.map(w=>({type:"image",media_type:w.media_type,data:w.base64}))]:h,tool_call_id:t.callId},summary:u}}var dR=[{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 zl(t){for(let{re:e,label:s}of dR){let n=t.match(e);if(n){let o=(n[1]||"").trim();return o?`${s}: ${o}`:s}}return null}async function fR(t,e=!1,s={}){let n=new Array(t.length),o=[],r=[],i=null;if(e&&!s.skipSpinner){let c=t.filter(l=>l.canExecute);if(c.length>0){let l;if(c.length===1){let u=c[0],d=uR(u.fnName,u.args);l=`\u23FA ${u.fnName}${d?`(${d})`:""}`}else{let u=c.map(d=>d.fnName).join(", ");l=`\u23FA ${c.length} tools: ${u.length>60?u.substring(0,57)+"\u2026":u}`}i=new to(l),i.start()}}async function a(){if(r.length!==0){if(r.length===1){let c=r[0],{msg:l,summary:u}=await Gl(t[c],e);n[c]=l,o.push(u)}else{let c=r.map(u=>Gl(t[u],e)),l=await Promise.all(c);for(let u=0;u<r.length;u++)n[r[u]]=l[u].msg,o.push(l[u].summary)}r=[]}}for(let c=0;c<t.length;c++){let l=t[c];if(!l.canExecute){await a(),n[c]=l.errorResult,o.push(Vl(l.fnName,l.args||{},l.errorResult.content,!0));continue}if(rR.has(l.fnName)){await a(),l.fnName==="spawn_agents"&&i&&(i.stop(),i=null);let{msg:u,summary:d}=await Gl(l,e);n[c]=u,o.push(d)}else r.push(c)}if(await a(),i&&i.stop(),e&&o.length>0&&!s.skipSummaries)for(let c of o)console.log(c);return{results:n,summaries:o}}var P=[],_y=300,My=900*1e3;function ln(t,e){let s=t.get(e);return s?Date.now()-s.ts>My?(t.delete(e),0):s.count:0}function gs(t,e){let s=t.get(e),n=s&&Date.now()-s.ts<=My?s.count+1:1;return t.set(e,{count:n,ts:Date.now()}),n}function Kl(t,e,s){t.set(e,{count:s,ts:Date.now()})}var uu=new Map,Py=new Map,Zi=new Map,fr=new Set,Ly=new Map,Qi=new Map,pr=new Set,xn=new Map,In=new Map,hr=new Map,qt=new Map,bs=new Map,xy=new Map,la=new Map,nu=new Map,Ft=0,ar=0,ea=0,su="",ta=0,Ot=!1,Ki=0,na=0,ys=-1,ou=!1,sa=0,oa=!1,Ut=0,Wt=!1,Zt=0,Qt=0,it=!1,xt="",cr=0,Ln=0,ra="",ws=0,$s=0,ia="",nr=0,Bt=!1,ru=!1,gr=new Map,yr=new Set,lr=null,Xl=!1,sr=0,ky=!1,Pe="plan",ua=0,be=!1,jn=0,kn=null,iu=null,au=null,oo=0,mr=0,ro=0,io=null,_s=[];function eo(t,e){t===su?(ta++,debug.DEBUG&&process.stdout.write(`\x1B[1A\x1B[2K${e} \u26A0 ${t} (\xD7${ta})${m.reset}
|
|
869
|
+
`)):(su=t,ta=1,D(`${e} \u26A0 ${t}${m.reset}`))}var aa=[];function pR(t){aa.push(t.trim())}function hR(){return aa.length===0?null:aa.splice(0,aa.length).join(`
|
|
870
|
+
`)}function mR(t){let e=t._startedAt?Math.round((t.finishedAt-t._startedAt)/1e3):null,s=e!==null?`
|
|
847
871
|
Duration: ${e}s`:"",n=typeof t.result.result=="string"?t.result.result.slice(0,4e3):JSON.stringify(t.result.result||"").slice(0,4e3),o=t.result.filesModified&&t.result.filesModified.length>0?`
|
|
848
872
|
Files modified: ${t.result.filesModified.join(", ")}`:"";return`[BACKGROUND AGENT COMPLETED]
|
|
849
873
|
Job: ${t.jobId}
|
|
850
874
|
Task: "${t.agentDef.task}"`+s+`
|
|
851
875
|
Status: ${t.result.status||"done"}`+o+`
|
|
852
|
-
Result: ${n}`}function
|
|
853
|
-
`)}}function
|
|
854
|
-
`).find(
|
|
876
|
+
Result: ${n}`}function Xi(t,e){let{getCompletedJobs:s}=Hs(),n=s();for(let o of n){let r={role:"user",content:mR(o)};t.push(r),e.push(r);let i=o.result?.status||"done",a=i==="failed"?m.red+" \u2717":m.cyan+" \u2713";process.stderr.write(`${a} Background agent ${i}: ${o.agentDef.task.slice(0,50)} \u2014 ${String(o.result?.result||"").slice(0,80)}${m.reset}
|
|
877
|
+
`)}}function Iy(t,e){let s=[],n=new Set([...e.keys(),...fr,...pr]);if(!n.size||!t)return s;for(let o of n){let r=o.split("/").pop();if(r&&(t.includes(r)||t.includes(o))){let a=t.split(`
|
|
878
|
+
`).find(c=>c.includes(r)||c.includes(o));s.push({file:o,action:(a||"edit this file").trim().slice(0,200),done:!1})}}return s}function gR(t){if(!t||typeof t!="string")return[];let e=t.match(/[A-Za-z_][A-Za-z0-9_]{2,}/g)||[],s=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"]),n=new Set,o=[];for(let r of e){let i=r.toLowerCase();s.has(i)||n.has(i)||(n.add(i),o.push(r))}return o.sort((r,i)=>i.length-r.length),o.slice(0,6)}function yR(){return De.existsSync(Ge.join(process.cwd(),"pnpm-lock.yaml"))?"pnpm":De.existsSync(Ge.join(process.cwd(),"yarn.lock"))?"yarn":"npm"}function un(t){let e=yR();return t==="test"?e==="yarn"?"yarn test":e==="pnpm"?"pnpm test":"npm test":e==="yarn"?`yarn ${t}`:e==="pnpm"?`pnpm run ${t}`:`npm run ${t}`}async function jy(t){let e=gR(t);if(e.length===0)return[];let{searchContentIndex:s}=gn(),n=[],o=new Set;for(let r of e)try{let i=await s(r,void 0,process.cwd());for(let a of i.slice(0,3)){let c=`${a.file}:${a.name}:${a.line}`;if(!o.has(c)&&(o.add(c),n.push(a),n.length>=5))return n}}catch{}return n}async function Dy(t){let e=await jy(t);if(e.length===0)return"";let{getRelatedFiles:s}=gn(),n=["Likely symbol targets:"];for(let o=0;o<e.length;o++){let r=e[o],i=Math.max(1,r.line-20),a=r.line+40;n.push(`${o+1}. ${r.name} (${r.type}) in ${r.file}:${r.line} -> read_file(path='${r.file}', line_start=${i}, line_end=${a})`);try{let c=await s(r.file,process.cwd(),3);c.length>0&&n.push(` Follow-up files: ${c.join(", ")} (read only if the primary symbol points into one of these modules)`)}catch{}}return`${n.join(`
|
|
879
|
+
`)}
|
|
880
|
+
Use these exact targeted reads before broader searching.
|
|
881
|
+
|
|
882
|
+
`}function du(t){let{getFileIndex:e}=gn(),n=e().filter(r=>/^tests?\//.test(r)||/\.test\./.test(r)||/\.spec\./.test(r));if(n.length===0)return[];let o=new Set;for(let r of t||[]){let i=Ge.basename(String(r)).replace(/\.[^.]+$/,"");if(!(i.length<3)){for(let a of n)if(a.includes(i)&&o.add(a),o.size>=4)return[...o]}}return[...o]}function wR(t,e={}){if(!Array.isArray(t)||t.length===0)return[];let s=t.slice(0,4).join(" "),n=[],o=String(e.test||"");return/vitest/.test(o)||De.existsSync(Ge.join(process.cwd(),"vitest.config.ts"))||De.existsSync(Ge.join(process.cwd(),"vitest.config.js"))?n.push(`npx vitest run ${s}`):(/jest/.test(o)||De.existsSync(Ge.join(process.cwd(),"jest.config.js"))||De.existsSync(Ge.join(process.cwd(),"jest.config.cjs"))||De.existsSync(Ge.join(process.cwd(),"jest.config.mjs")))&&n.push(`npx jest --runInBand ${s}`),(De.existsSync(Ge.join(process.cwd(),"pytest.ini"))||De.existsSync(Ge.join(process.cwd(),"pyproject.toml")))&&t.some(r=>/\.py$/i.test(r))&&n.push(`pytest ${t.filter(r=>/\.py$/i.test(r)).slice(0,4).join(" ")}`),n}async function or(t,e,s,n){if(!be)return null;let o=Pe;Pe=t,ua=0,kn=Jl(t,io),t==="verify"&&(mr=0,ro=0),Ut=0,Wt=!1,Zt=0,Qt=0,bs.clear(),la.clear(),uu.clear(),hr.clear(),t==="implement"&&(_s=Iy(e||"",xn));let r=_s.length>0?`
|
|
855
883
|
|
|
856
884
|
ACTION ITEMS (execute these in order, do NOT re-read these files):
|
|
857
|
-
`+
|
|
858
|
-
`):"",i;if(t==="implement")
|
|
859
|
-
${
|
|
860
|
-
|
|
861
|
-
Now implement the fix/changes. Do not investigate further \u2014 edit files directly.`+r;else if(t==="verify"){
|
|
862
|
-
1.
|
|
863
|
-
|
|
864
|
-
|
|
885
|
+
`+_s.map((c,l)=>`${l+1}. ${c.file} \u2014 ${c.action}`).join(`
|
|
886
|
+
`):"",i=await Dy(t==="verify"?n:e||n||""),a;if(t==="implement")iu=e?.slice(0,2e3)||"",a=`[PHASE: IMPLEMENTATION] Analysis complete. Based on the analysis:
|
|
887
|
+
${iu}
|
|
888
|
+
|
|
889
|
+
${i}Now implement the fix/changes. Do not investigate further \u2014 edit files directly.`+r;else if(t==="verify"){au=e?.slice(0,500)||"";let c=s?[...s].join(", "):"none",l=qy(s),u=du(s),d=l.length>0?`Suggested checks (run the narrowest ones that fit the change):
|
|
890
|
+
${l.map((p,h)=>`${h+1}. ${p}`).join(`
|
|
891
|
+
`)}
|
|
892
|
+
|
|
893
|
+
`:"",f=u.length>0?`Likely related tests:
|
|
894
|
+
${u.map((p,h)=>`${h+1}. ${p}`).join(`
|
|
895
|
+
`)}
|
|
896
|
+
Prefer these before broader suites when a targeted run is possible.
|
|
897
|
+
|
|
898
|
+
`:"";a=`[PHASE: VERIFICATION] Implementation complete. Verify the changes:
|
|
899
|
+
1. Read only the modified sections/files and confirm the final code matches intent
|
|
900
|
+
2. Run the smallest relevant verification command(s)
|
|
901
|
+
3. If one check fails, explain the failure precisely and loop back with a focused fix
|
|
865
902
|
4. Does the implementation address: "${(n||"").slice(0,200)}"?
|
|
866
903
|
Report PASS (all good) or FAIL (list specific issues).
|
|
867
904
|
|
|
868
|
-
Files modified: ${
|
|
869
|
-
Summary: ${
|
|
870
|
-
`];n?o.push(`RESPONSE LANGUAGE: You MUST always respond in ${n}. This overrides any language defaults from your training. Never output Chinese, Japanese, or any other language in your responses \u2014 even when summarizing or thinking. ${n} only.`):o.push("RESPONSE LANGUAGE: Always respond in the same language as the user's message. If the user writes in German, respond in German; if in English, respond in English; etc."),o.push("CODE EXAMPLES: Always show actual, working code examples \u2014 never pseudocode or placeholder snippets."),o.push("COMPLETENESS RULES:"),o.push(" \u2022 ALWAYS show actual code when explaining implementations \u2014 never describe without showing"),
|
|
905
|
+
Files modified: ${c}
|
|
906
|
+
${i}${d}${f}Summary: ${au}`}return D(`${m.cyan} \u21B3 Phase transition: ${o} \u2192 ${t} (model: ${kn||"default"})${m.reset}`),a?{role:"user",content:a}:null}function qy(t){let e=[],n=[...t||[]].map(c=>String(c).toLowerCase()),o={};try{let c=Ge.join(process.cwd(),"package.json");if(De.existsSync(c)){o=JSON.parse(De.readFileSync(c,"utf-8")).scripts||{};let u=[["test",un("test")],["lint",un("lint")],["typecheck",un("typecheck")],["check",un("check")],["build",un("build")]];for(let[d,f]of u)o[d]&&e.push(f)}}catch{}e.length===0&&(De.existsSync(Ge.join(process.cwd(),"package.json"))&&e.push(un("test")),(De.existsSync(Ge.join(process.cwd(),"pytest.ini"))||De.existsSync(Ge.join(process.cwd(),"pyproject.toml")))&&e.push("pytest"));let r=du(t);e.unshift(...wR(r,o));let i=n.some(c=>/\.(ts|tsx)$/.test(c)),a=n.some(c=>/\.(js|jsx|ts|tsx)$/.test(c));return i&&!e.includes(un("typecheck"))&&e.push(un("typecheck")),a&&!e.includes(un("lint"))&&e.push(un("lint")),[...new Set(e)].slice(0,4)}function $R(){let t=process.env.NEX_LANGUAGE,e=process.env.NEX_CODE_LANGUAGE,s=process.env.NEX_COMMIT_LANGUAGE,n=!t||t==="auto"?null:t,o=[`# Language Rules (CRITICAL \u2014 enforce strictly)
|
|
907
|
+
`];n?o.push(`RESPONSE LANGUAGE: You MUST always respond in ${n}. This overrides any language defaults from your training. Never output Chinese, Japanese, or any other language in your responses \u2014 even when summarizing or thinking. ${n} only.`):o.push("RESPONSE LANGUAGE: Always respond in the same language as the user's message. If the user writes in German, respond in German; if in English, respond in English; etc."),o.push("CODE EXAMPLES: Always show actual, working code examples \u2014 never pseudocode or placeholder snippets."),o.push("COMPLETENESS RULES:"),o.push(" \u2022 ALWAYS show actual code when explaining implementations \u2014 never describe without showing"),ur()?o.push(" \u2022 FILE CREATION TASKS (Makefile, Dockerfile, config files, documentation): ALWAYS use write_file to create the file on disk. In auto mode the user cannot see your text output \u2014 only files on disk matter."):o.push(" \u2022 FILE CREATION TASKS (Makefile, Dockerfile, config files): paste the COMPLETE file content in a fenced code block in your TEXT RESPONSE \u2014 writing a file with a tool does NOT make it visible. The fenced code block MUST appear in your response, not just via write_file."),o.push(" \u2022 Include complete examples with full context (imports, function signatures, error handling)"),o.push(' \u2022 Show alternative approaches when relevant (e.g., "Alternative: use util.promisify instead")'),o.push(" \u2022 Include edge cases in explanations (empty input, null values, boundary conditions)"),o.push(" \u2022 Provide platform-specific guidance when commands differ by OS (Linux/macOS/Windows)"),o.push(' \u2022 For Makefiles, paste the COMPLETE Makefile code DIRECTLY in your text response \u2014 every target, recipe, dependency, and .PHONY line. Writing the Makefile with a tool does NOT count as showing it. The Makefile MUST appear verbatim in your chat text as a code block, even if you also wrote it to a file. Never describe structure without showing the actual code. CRITICAL: use EXACTLY the command specified \u2014 if the task says "runs jest", write "jest" in the recipe, NEVER "npm test". npm test is NOT jest. Recipes need real TAB indentation. ONE .PHONY line listing ALL phony targets.'),o.push(" \u2022 For dataclasses, paste the COMPLETE dataclass code DIRECTLY in your text response \u2014 @dataclass decorator, all fields with types and defaults, full __post_init__ validation. Writing the file with a tool does NOT count as showing the code. The code MUST appear verbatim in your chat text, even if you also wrote it to a file."),o.push(" \u2022 For cron expressions, re-read the exact time boundaries in the task before writing. If asked for 8-18h, the range is 8,9,...,18 \u2014 write exactly what was asked, not an approximation."),o.push(' \u2022 When a task explicitly specifies a tool (e.g., "use tsc"), NEVER mention alternatives (e.g., "swc build") \u2014 use exactly what was requested.'),o.push(' \u2022 In Makefile prerequisites, NEVER use shell glob patterns like src/**/*.ts \u2014 make does not expand these natively. Keep prerequisite lists explicit or omit them. When a Makefile target says "runs jest", call jest directly in the recipe (not npm test).'),o.push(" \u2022 For bash in-place text replacements with backups: use ONLY ONE backup method \u2014 either sed -i.bak (let sed create the backup) OR cp file file.bak followed by sed -i (no extension). Never use both cp and sed -i.bak together \u2014 that produces redundant double backups (file.bak and file.bak.bak)."),o.push(" \u2022 For iterative array-flattening (flattenDeep): use push() and reverse() at the end \u2014 NEVER unshift(). unshift is O(n) per call making the whole function O(n^2). The iterative version MUST use a loop (while/for) and an explicit stack array \u2014 zero recursive calls. If a function calls itself, it is recursive regardless of its name. Never label a recursive function as iterative."),o.push(" \u2022 FORBIDDEN: when refactoring callbacks to async/await, NEVER write try { ... } catch(e) { throw e } \u2014 this is an explicit anti-pattern. WRONG: async function f() { try { const d = await readFile(..); await writeFile(.., d); } catch(e) { throw e; } } \u2014 RIGHT: async function f() { const d = await readFile(..); await writeFile(.., d); } \u2014 omit the try-catch entirely, let rejections propagate."),o.push(" \u2022 Express/fetch error handling: When adding error handling to an Express route that fetches by ID: (1) validate the ID parameter first (check it exists and is a valid format), (2) wrap fetch in try-catch, (3) check response.ok and handle 404 specifically, (4) call next(error) to pass errors to Express error\u2011handling middleware \u2014 do not just send a raw 500 response."),o.push(' \u2022 Docker HEALTHCHECK: always include --start-period=30s (or appropriate startup time) so the container has time to initialise before failures are counted. Also note that curl may not be available in minimal Node.js images \u2014 offer wget or "node -e" as alternatives.'),o.push(' \u2022 When fixing a bash word-splitting bug like "for f in $(ls *.txt)": replace the entire $(ls *.txt) with a bare glob directly \u2014 "for f in *.txt". The fix is eliminating the ls command and $() subshell entirely. Emphasise this in the explanation: the glob in the for loop prevents word splitting because the shell expands the glob into separate words before the loop \u2014 there is no subshell output to split. CRITICAL: NEVER suggest "ls -N" or any ls variant as a fix \u2014 ls -N outputs filenames one per line, but word splitting still occurs on each line when used in a subshell expansion. The only correct fix is the bare glob pattern.');let r=e||"English";o.push(`CODE LANGUAGE: Write all code comments, docstrings, variable descriptions, and inline documentation in ${r}.`);let i=s||"English";return o.push(`COMMIT MESSAGES: Write all git commit messages in ${i}.`),n&&o.push(`
|
|
871
908
|
This is a hard requirement. Always respond in ${n}. Do NOT switch to any other language \u2014 even if the user writes to you in German, French, or any other language, your reply MUST be in ${n}.`),o.join(`
|
|
872
909
|
`)+`
|
|
873
910
|
|
|
874
|
-
`}function
|
|
911
|
+
`}function bR(){if(so!==null)return so;try{let e=DT().flatMap(o=>o.models.map(r=>({spec:`${o.name}:${r.id}`,tier:jT(r.id,o.name),name:r.name})));if(e.length<2)return so="","";let s={full:"complex tasks (refactor, implement, generate)",standard:"regular tasks (edit, fix, analyze)",essential:"simple tasks (read, search, list)"},n=`
|
|
875
912
|
# Sub-Agent Model Routing
|
|
876
913
|
|
|
877
914
|
`;n+='Sub-agents auto-select models by task complexity. Override with `model: "provider:model"` in agent definition.\n\n',n+=`| Model | Tier | Auto-assigned for |
|
|
878
915
|
|---|---|---|
|
|
879
916
|
`;for(let o of e)n+=`| ${o.spec} | ${o.tier} | ${s[o.tier]||o.tier} |
|
|
880
|
-
`;return
|
|
917
|
+
`;return so=n,n}catch(t){return process.env.NEX_DEBUG&&console.error("[agent] model routing guide failed:",t.message),so="",""}}var cu="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->";function _R(t){let e=t.indexOf(cu);return e===-1?{dynamic:t,static:""}:{dynamic:t.slice(0,e).trimEnd(),static:t.slice(e+cu.length).trimStart()}}async function lu(){let t=await Ny()+":"+en();if(rr!==null&&t===eu)return rr;let e=await sT(process.cwd()),s=mT(),n=NT(),o=dr()?kT():"",r=$R(),i=gT(),a=FT(en());return rr=`${a?`## Model Briefing
|
|
881
918
|
${a}
|
|
882
919
|
|
|
883
920
|
---
|
|
@@ -898,7 +935,7 @@ ${o}
|
|
|
898
935
|
${r?`${r}
|
|
899
936
|
`:""}${i?`${i}
|
|
900
937
|
|
|
901
|
-
`:""}${
|
|
938
|
+
`:""}${ur()?`# YOLO Mode \u2014 Auto-Execute
|
|
902
939
|
|
|
903
940
|
You are in YOLO mode (autoConfirm=true). All tool calls are pre-approved.
|
|
904
941
|
- NEVER ask for confirmation \u2014 just execute tasks directly
|
|
@@ -929,6 +966,9 @@ Plan mode is ONLY active when explicitly activated via the /plan command or show
|
|
|
929
966
|
- Be concise but complete. Keep responses focused while ensuring the user gets the information they asked for.
|
|
930
967
|
- When referencing code, include file:line (e.g. src/app.js:42) so the user can navigate.
|
|
931
968
|
- Do not make up file paths or URLs. Use tools to discover them.
|
|
969
|
+
- Treat the repo map in PROJECT CONTEXT as your first navigation aid. Start with the most likely 2-5 files or symbols, not a repo-wide wander.
|
|
970
|
+
- Prefer symbol-aware, high-signal retrieval: first locate the owning file/module, then read the exact function/class/section you need, then edit.
|
|
971
|
+
- For implementation tasks, keep the loop tight: diagnose -> edit the smallest viable surface -> run the narrowest meaningful verification -> continue only if still failing.
|
|
932
972
|
|
|
933
973
|
# Response Quality (Critical)
|
|
934
974
|
|
|
@@ -1135,7 +1175,7 @@ You have a soft budget of ~30 tool calls per task. Sessions with >40 tool calls
|
|
|
1135
1175
|
- Instead: use bash with inline node -e '...' for quick one-off checks.
|
|
1136
1176
|
- If the test is worth keeping, write it to tests/ with a proper name.
|
|
1137
1177
|
- Write-then-delete patterns waste 3 tool calls and leave orphans if the session is interrupted.
|
|
1138
|
-
${
|
|
1178
|
+
${bR()}
|
|
1139
1179
|
|
|
1140
1180
|
# Edit Protocol (Mandatory \u2014 Follow These Steps Exactly)
|
|
1141
1181
|
|
|
@@ -1185,6 +1225,7 @@ When a tool call returns ERROR \u2014 follow these exact recovery sequences:
|
|
|
1185
1225
|
**After 2 consecutive failures at the same operation** \u2192 stop and explain the issue to the user.
|
|
1186
1226
|
|
|
1187
1227
|
# Git Workflow
|
|
1228
|
+
- Always verify current branch before committing
|
|
1188
1229
|
|
|
1189
1230
|
- Before committing, review changes with git_diff. Write messages that explain WHY, not WHAT.
|
|
1190
1231
|
- Stage specific files rather than git add -A to avoid committing unrelated changes.
|
|
@@ -1326,91 +1367,91 @@ class ErrorBoundary extends React.Component {
|
|
|
1326
1367
|
- Use migrations for schema changes, never manual ALTER TABLE
|
|
1327
1368
|
- Add database-level constraints (unique, foreign key, check) not just app-level
|
|
1328
1369
|
|
|
1329
|
-
`,
|
|
1330
|
-
`):[]).filter(d=>{let f=d.split(".").pop();return r.has(f)});if(i.length<3)return null;let a={};for(let d of i){let f=d.split(".").pop();a[f]=(a[f]||0)+1}let
|
|
1331
|
-
\u{1F4E6} ${p}${
|
|
1332
|
-
${
|
|
1333
|
-
`),f==="")return a({action:"quit"});let
|
|
1370
|
+
`,eu=t,rr}function Fy(){uu.clear(),Py.clear(),Zi.clear(),fr.clear(),Ly.clear(),Qi.clear(),pr.clear(),xn.clear(),In.clear(),hr.clear(),qt.clear(),bs.clear(),la.clear(),nu.clear(),Ft=0,ar=0,ea=0,Ot=!1,na=0,ys=-1,ou=!1,sa=0,oa=!1,Ut=0,Wt=!1,Zt=0,Qt=0,it=!1,xt="",cr=0,ra="",ws=0,ia="",$s=0,Bt=!1,ru=!1,Pe="plan",ua=0,be=!1,kn=null,iu=null,au=null,_s=[],oo=0,mr=0,ro=0,jn=0,io=null,gr.clear(),yr.clear(),su="",ta=0}function xR(){P=[],lr=null,Fy();try{let{resetCompactionFailures:t}=zc();t()}catch{}try{let{cancelAllJobs:t}=Hs();t()}catch{}}function kR(){P.length>_y&&P.splice(0,P.length-_y)}function SR(){return P.length}function vR(){return P}function ER(t){P=t}async function TR(){let{execFile:t}=require("child_process"),e=require("fs"),s=process.cwd(),n=(d,f)=>new Promise(p=>{t(d,f,{cwd:s,timeout:3e3},(h,g)=>{p(h?"":(g||"").trim())})}),[o]=await Promise.all([n("find",[".","-type","f","-not","-path","*/node_modules/*","-not","-path","*/.git/*","-not","-path","*/dist/*","-not","-path","*/.next/*","-not","-path","*/build/*","-not","-path","*/__pycache__/*","-not","-path","*/vendor/*"])]),r=new Set(["js","ts","jsx","tsx","py","go","rs","rb","java","cpp","c","cs"]),i=(o?o.split(`
|
|
1371
|
+
`):[]).filter(d=>{let f=d.split(".").pop();return r.has(f)});if(i.length<3)return null;let a={};for(let d of i){let f=d.split(".").pop();a[f]=(a[f]||0)+1}let l=` \u{1F4C1} ${Object.entries(a).sort((d,f)=>f[1]-d[1]).slice(0,4).map(([d,f])=>`${f} .${d}`).join(" \xB7 ")}`,u=Ge.join(s,"package.json");if(e.existsSync(u))try{let d=JSON.parse(e.readFileSync(u,"utf-8")),f=Object.keys({...d.dependencies||{},...d.devDependencies||{}});if(f.length>0){let p=f.slice(0,5).join(" \xB7 "),h=f.length>5?` +${f.length-5}`:"";l+=`
|
|
1372
|
+
\u{1F4E6} ${p}${h}`}}catch{}return l}function RR(t){if(process.platform==="darwin")try{let{execFileSync:e}=require("child_process");e("osascript",["-e",`display notification "${t.replace(/"/g,'\\"')}" with title "nex-code"`],{timeout:3e3,stdio:"ignore"})}catch{}}function Me(t,e,s,n,o,{suppressHint:r=!1}={}){if(t<1)return;let i=[...e.values()].reduce((l,u)=>l+u,0),a=`\u2500\u2500 ${t} ${t===1?"step":"steps"} \xB7 ${i} ${i===1?"tool":"tools"}`,c=0;if(o){let l=Date.now()-o;c=Math.round(l/1e3),a+=c>=60?` \xB7 ${Math.floor(c/60)}m ${c%60}s`:` \xB7 ${c}s`}if(s.size>0&&(a+=` \xB7 ${s.size} ${s.size===1?"file":"files"} modified`),a+=" \u2500\u2500",console.log(`
|
|
1373
|
+
${m.dim} ${a}${m.reset}`),c>=30&&process.stdout.isTTY){let l=s.size>0?`Done \u2014 ${s.size} ${s.size===1?"file":"files"} modified in ${c}s`:`Done \u2014 ${t} ${t===1?"step":"steps"} in ${c}s`;RR(l)}if(yr.size>0&&gr.size>0)for(let l of yr){let u=gr.get(l);u&&console.log(`${m.dim} \u2714 task #${l} auto-matched: ${u.slice(0,60)}${m.reset}`)}s.size>0?console.log(`${m.dim} \u{1F4A1} /diff \xB7 /commit \xB7 /undo${m.reset}`):!r&&n.size>=5&&s.size===0&&t>=3?console.log(`${m.dim} \u{1F4A1} Found issues? Say "fix 1" or "apply all fixes"${m.reset}`):n.size>0&&t>=2&&console.log(`${m.dim} \u{1F4A1} /save \xB7 /clear${m.reset}`)}async function CR(){if(!process.stdout.isTTY)return{action:"quit"};let t=no(),e=en(),s=ca.fast?.[t],n=ca.strong?.[t],o=s&&s!==e,r=n&&n!==e&&n!==s,i=[];i.push({key:"r",label:`Retry with current model ${m.dim}(${e})${m.reset}`}),o&&i.push({key:"f",label:`Switch to ${m.bold}${s}${m.reset} ${m.dim}\u2014 fast, low latency${m.reset}`,model:s}),r&&i.push({key:"s",label:`Switch to ${m.bold}${n}${m.reset} ${m.dim}\u2014 reliable tool-calling, medium speed${m.reset}`,model:n}),i.push({key:"q",label:`${m.dim}Quit${m.reset}`}),console.log(),console.log(`${m.yellow} Stream stale \u2014 all retries exhausted.${m.reset} What would you like to do?`);for(let a of i)console.log(` ${m.cyan}[${a.key}]${m.reset} ${a.label}`);return process.stdout.write(` ${m.yellow}> ${m.reset}`),new Promise(a=>{let c=process.stdin,l=c.isRaw;c.setRawMode(!0),c.resume(),c.setEncoding("utf8");let u=!1,d=f=>{if(u)return;u=!0,c.removeListener("data",d),c.setRawMode(l||!1),c.pause();let p=f.toLowerCase().trim();if(process.stdout.write(`${p}
|
|
1374
|
+
`),f==="")return a({action:"quit"});let h=i.find(g=>g.key===p);!h||h.key==="q"||!h.model&&h.key!=="r"?a({action:"quit"}):h.key==="r"?a({action:"retry"}):a({action:"switch",model:h.model,provider:t})};c.on("data",d)})}function AR(t){let e=/https?:\/\/[^\s/]+(\/[^\s?#]+)/g,s=new Set,n;for(;(n=e.exec(t))!==null;){let o=n[1].replace(/\/$/,"");o.length>1&&o.split("/").filter(i=>i.length>2).forEach(i=>s.add(i))}return Array.from(s)}function OR(t){let e=[];return(t.includes("@click")||t.includes("x-data")||t.includes("v-if")||t.includes("v-model"))&&e.push("Snippet contains Vue/Alpine.js directives (e.g., @click, v-model). Do not restrict your search to just .js/.ts/.vue files; also search .html and .py (templates) if appropriate."),(t.includes("className=")||t.includes("useEffect"))&&e.push("Snippet appears to be React. Look in .jsx, .tsx, .js, .ts files."),e}var dn=null;async function NR(t,e=null,s={}){let n=qT(en());by=n.staleWarn,Yl=n.staleAbort,dn=e;let o=t;if(lr&&typeof t=="string"&&(o=`${lr}
|
|
1334
1375
|
|
|
1335
|
-
${t}`,
|
|
1376
|
+
${t}`,lr=null),typeof o=="string"){let ye=AR(o),we=OR(o);(ye.length>0||we.length>0)&&(o+=`
|
|
1336
1377
|
|
|
1337
1378
|
[System Note for Assistant: To resolve this task faster, consider these hints:
|
|
1338
|
-
`,
|
|
1339
|
-
`),
|
|
1340
|
-
`}),o+="Always prefer parallel search execution if unsure.]")}typeof o=="string"&&
|
|
1379
|
+
`,ye.length>0&&(o+=`- The user mentioned URLs containing the paths/folders: ${ye.join(", ")}. Prioritize searching these folder names using glob or grep first.
|
|
1380
|
+
`),we.length>0&&we.forEach(ve=>{o+=`- ${ve}
|
|
1381
|
+
`}),o+="Always prefer parallel search execution if unsure.]")}typeof o=="string"&&Ay(o)&&(o+=`
|
|
1341
1382
|
|
|
1342
|
-
[Note for assistant: the user appears frustrated \u2014 acknowledge their concern briefly and empathetically before proceeding]`);let r=
|
|
1383
|
+
[Note for assistant: the user appears frustrated \u2014 acknowledge their concern briefly and empathetically before proceeding]`);let r=Cy(o);r&&typeof r.then=="function"&&(r=await r),P.push({role:"user",content:r}),kR();let i=s.autoOrchestrate!==!1&&process.env.NEX_AUTO_ORCHESTRATE!=="false",a=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10);try{let{detectComplexPrompt:ye,runOrchestrated:we}=ly(),ve=ye(typeof t=="string"?t:"");if(i&&ve.isComplex&&ve.estimatedGoals>=a){console.log(`${m.yellow}\u26A1 Auto-orchestrate: ${ve.estimatedGoals} goals \u2192 parallel agents${m.reset}`);let et=await we(t,{orchestratorModel:s.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL,workerModel:s.model});if(et&&et.synthesis){let ft=et.synthesis.summary||"",vn=et.synthesis.filesChanged?.length?`
|
|
1343
1384
|
|
|
1344
|
-
Files changed: ${
|
|
1385
|
+
Files changed: ${et.synthesis.filesChanged.join(", ")}`:"",Ve=et.synthesis.conflicts?.length?`
|
|
1345
1386
|
|
|
1346
1387
|
Conflicts:
|
|
1347
|
-
${
|
|
1348
|
-
`)}`:"";
|
|
1349
|
-
`+
|
|
1350
|
-
`)}catch(
|
|
1351
|
-
${
|
|
1388
|
+
${et.synthesis.conflicts.map(Nt=>`- ${Nt}`).join(`
|
|
1389
|
+
`)}`:"";P.push({role:"assistant",content:ft+vn+Ve}),Oe(P),Gi(P)}return et}ve.isComplex&&process.stdout.isTTY&&console.log(`${m.dim}Hint: ~${ve.estimatedGoals} goals detected. Disable with NEX_AUTO_ORCHESTRATE=false${m.reset}`)}catch{}let{setOnChange:c}=Yc(),l=null,u=0;c((ye,we)=>{ye==="create"?(l&&l.stop(),l=new JE(we.name,we.tasks),l.setStats({tokens:u}),l.start()):ye==="update"&&l?l.updateTask(we.id,we.status):ye==="clear"&&l&&(l.stop(),l=null)});let d=await lu(),f=d;try{let{getBrainContext:ye}=cl(),we=await ye(t);we&&(f=d+`
|
|
1390
|
+
`+we+`
|
|
1391
|
+
`)}catch(ye){process.env.NEX_DEBUG&&console.error("[agent] brain context failed:",ye.message)}let h=LT(typeof t=="string"?t:"");if(h.length>0){let ye=h.map(we=>`[Triggered: ${we.name}]
|
|
1392
|
+
${we.instructions}`).join(`
|
|
1352
1393
|
`);f+=`
|
|
1353
|
-
`+
|
|
1354
|
-
`}let g=[{role:"system",content:f},...
|
|
1355
|
-
${ce}`},{role:"assistant",content:"Understood \u2014 I have the server context. Proceeding with the task."},...S.slice(1)]),
|
|
1356
|
-
`+
|
|
1357
|
-
[END EXAMPLE \u2014 wait for the real user request below]`},...S.slice(1)])}if(
|
|
1358
|
-
`),
|
|
1359
|
-
`);
|
|
1360
|
-
`+V.map(
|
|
1361
|
-
`));let X=
|
|
1394
|
+
`+ye+`
|
|
1395
|
+
`}let g=[{role:"system",content:f},...P];uy(en());let w=new to(Dl());w.start();let x=P.length===1,O=x?TR().catch(()=>null):Promise.resolve(null),I=x?yT(typeof t=="string"?t:"").catch(()=>null):Promise.resolve(null),E=dt(),[{messages:v,compressed:A,compacted:te,tokensRemoved:oe},de,ce]=await Promise.all([oT(g,E),O,I]),ne=Jt(g,E);if(w.stop(),de&&console.log(`${m.dim}${de}${m.reset}`),te)console.log(`${m.dim} [context compacted \u2014 summary (~${oe} tokens freed)]${m.reset}`);else if(A){let ye=ne.limit>0?Math.round(oe/ne.limit*100):0;D(`${m.dim} [context compressed \u2014 ~${oe} tokens freed (${ye}%)]${m.reset}`)}ne.percentage>85&&D(`${m.yellow} \u26A0 Context ${Math.round(ne.percentage)}% used (${Math.round(100-ne.percentage)}% remaining) \u2014 consider /clear or /save + start fresh${m.reset}`);let S=v;if(ce&&x&&(S=[S[0],{role:"user",content:`[Server probe at task start]
|
|
1396
|
+
${ce}`},{role:"assistant",content:"Understood \u2014 I have the server context. Proceeding with the task."},...S.slice(1)]),x){let ye=wT(typeof t=="string"?t:"");ye&&(S=[S[0],{role:"user",content:`[EXAMPLE \u2014 illustrative only, not the real task]
|
|
1397
|
+
`+ye.user},{role:"assistant",content:ye.assistant+`
|
|
1398
|
+
[END EXAMPLE \u2014 wait for the real user request below]`},...S.slice(1)])}if(Jt(S,dt()).percentage>=65){let{messages:we,tokensRemoved:ve}=cn(S,dt());ve>0&&(S=we,console.log(`${m.dim} [pre-flight compress \u2014 ${ve} tokens freed, now ${Math.round(Jt(S,dt()).percentage)}% used]${m.reset}`))}let Te=0,W=0,K=0,ge=0,Ae=0,qe=9,ke=0,xe=new Set,_=(()=>{let ye=P.find(we=>we.role==="user");return typeof ye?.content=="string"?ye.content:""})(),j=/set_reminder|google.?auth|cron:|api\.log|swarm.{0,30}(agent|crash|gecrasht|abgestürzt|fail)|agent.{0,30}(gecrasht|abgestürzt|crashed|fail)|server.{0,30}(passiert|fehler|crash|problem)|am.server/i.test(_),H=0;if(!it){let ye=P.filter(ve=>ve.role==="user"||ve.role==="tool").map(ve=>typeof ve.content=="string"?ve.content:"").join(`
|
|
1399
|
+
`),we=zl(ye);we&&(it=!0,xt=we.slice(0,120),D(`${m.yellow} \u26A1 Root cause in briefing: ${xt} \u2014 fix phase active from start (read budget: 3)${m.reset}`))}!it&&!Bt&&/\b(create|build|generate|implement|write|make|develop|set\s*up|scaffold|add)\b.{0,80}\b(app|component|page|game|api|backend|frontend|server|service|module|class|function|feature|project|system|bot|script|tool)\b/i.test(_)&&(Bt=!0,D(`${m.cyan} \u26A1 Creation task detected \u2014 tight investigation cap (4 pre-edit, 2 post-edit)${m.reset}`)),P.length<=1&&!s.skipPhaseRouting&&(be=pT(),be&&(io=fT(_)?.id||"coding",Pe="plan",kn=Jl("plan",io),ua=0,oo=0,jn=0,process.stdout.isTTY&&console.log(`${m.dim} \u21B3 Phase routing: plan(${kn||"default"}) \u2192 implement \u2192 verify${m.reset}`),D(`${m.cyan} \u26A1 Phase routing enabled \u2014 plan phase with ${kn||"default model"} (category: ${io})${m.reset}`)));let M=0,L=new Map,b=new Set,Z=new Set,fe=new Set,pe=0,Qe=0,lo=0,Sn=0,Ne=Date.now(),t0=new eT(BT),n0=hr,Ke=s.skillLoop?10:1,s0=3*Ke,o0=5*Ke,xu=uu,r0=5*Ke,i0=8*Ke,a0=Py,c0=(be?6:4)*Ke,l0=(be?10:7)*Ke,ma=Zi,u0=(be?5:3)*Ke,$r=(be?8:5)*Ke,d0=Ly,f0=(be?4:3)*Ke,p0=(be?6:4)*Ke,h0=3*Ke,m0=4*Ke,xs=xn,g0=(be?6:4)*Ke,y0=(be?10:8)*Ke,ks=(be?12:10)*Ke,w0=25,Dn=0,$0=10*Ke,b0=15*Ke,qn=0,ku=5*Ke,Fn=0,_0=2*Ke,x0=3,ga=0,uo=10,k0=16,Su=s.skillLoop?999:n.investigationCap,vu=async()=>{let{hasPendingOrCompletedJobs:ye,getPendingJobSummary:we}=Hs();if(ye()){if(we()){let ve=Date.now()+45e3;for(process.stderr.write(`${m.cyan} \u23F3 Waiting for background agents to finish\u2026${m.reset}
|
|
1400
|
+
`);we()&&Date.now()<ve;)await new Promise(et=>setTimeout(et,500).unref()),Xi(P,S)}Xi(P,S),P.length>0&&Oe(P)}},ya=typeof t=="string"?t.trim():"",Eu=ya.length>0&&/^\s*(analyze|analyse|analysiere|explain|erkläre|describe|beschreib|review|audit|summari[sz]e|zusammenfass|list|liste|what is|what does|wie funktioniert|wie geht|how does|show me|zeig|show the|show all|tell me about|erzähl)/i.test(ya)&&!/\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(ya),We,St=s.maxIterations||(be?ms(Pe):Ql);Eu&&(St=Math.min(St,4),D(`${m.dim} \u21B3 Analysis-only prompt detected \u2014 iter cap=${St}${m.reset}`));let wa=0,Tu=3,$a=!1,br=0;e:for(;;){for($a=!1,We=0;We<St&&!Vi()?.aborted;We++){Xi(P,S);{let $=dt(),y=Jt(S,$),z=M===0?65:78;if(y.percentage>=z){if(b.size>0||be&&Pe!=="plan"){let Q=iT(P,{filesModified:b,currentPhase:be?Pe:null});if(Q){let B=S.findIndex(R=>R._progressSnapshot);B!==-1&&S.splice(B,1);let re=S.findIndex(R=>R.role==="system");S.splice(re+1,0,Q)}}let{messages:T,tokensRemoved:N}=cn(S,$,M===0);if(N>0&&(S=T,N>50&&console.log(`${m.dim} [auto-compressed \u2014 ~${N} tokens freed, now ${Math.round(Jt(S,$).percentage)}%]${m.reset}`),Bt&&b.size>=3)){let Q=[...b].map(re=>re.split("/").pop()).slice(0,10).join(", "),B={role:"user",content:`[FRAMEWORK \u2014 context compressed] Task is IN PROGRESS. Already created ${b.size} files: ${Q}. DO NOT restart or re-investigate what was already done. Continue from where you left off.`};S.push(B)}}}if(Ot&&!it&&cr<2){cr++;let $={role:"user",content:"[SYSTEM] SSH paused \u2014 you have made many consecutive SSH calls. Synthesize your findings so far: summarize what you learned and what the likely issue is. After your synthesis, SSH will be available again for targeted follow-up commands."};S.push($),P.push($),D(`${m.yellow} \u26A0 Pre-call SSH-blocked nudge #${cr} injected \u2014 model told to synthesize${m.reset}`)}Ot||(cr=0);let we=!0;M>0&&TT();let ve=null;if(l&&l.isActive())l._paused&&l.resume();else if(!l){let $,y=RT();if(y&&y.total>1){let N=y.description.length>40?y.description.slice(0,37)+"\u2026":y.description;$=`Plan step ${y.current}/${y.total}: ${N}`}else $=M>0?`${Dl()} (step ${M+1})`:Dl();let{getPendingJobSummary:z}=Hs(),T=z();T&&($+=` [${T}]`),ve=new to($),ve.start()}let et=!0,ft="",vn=!1,Ve=new CT,Nt,ba=Date.now(),_r=!1,_a=new AbortController,Ru=setInterval(()=>{let $=Date.now()-ba;if($>=Yl)Ve._clearCursorLine(),D(`${m.yellow} \u26A0 Stream stale for ${Math.round($/1e3)}s \u2014 aborting and retrying${m.reset}`),_a.abort();else if($>=by&&!_r){_r=!0,Ve._clearCursorLine();let y=ca.fast?.[no()],z=K>0?` (retry ${K+1}/${zi})`:"",T=Math.round((Yl-$)/1e3);D(`${m.yellow} \u26A0 No tokens received for ${Math.round($/1e3)}s \u2014 waiting...${z}${m.reset}`),y&&y!==en()?console.log(`${m.dim} \u{1F4A1} Will auto-switch to ${y} in ~${T}s if no tokens arrive${m.reset}`):console.log(`${m.dim} \u{1F4A1} Ctrl+C to abort \xB7 auto-abort in ~${T}s${m.reset}`)}},5e3),Mt="",fn=null;try{let $=Oy(dt()),y=new Set(["read_file","list_directory","search_files","glob","grep","git_status","git_diff","git_log","git_show","ssh_exec"]),z=new Set(["read_file","list_directory","glob","grep","bash","git_status","git_diff","git_log","ssh_exec"]),T;dr()?T=$.filter(B=>vy.has(B.function.name)):be&&Pe==="plan"?T=$.filter(B=>y.has(B.function.name)):be&&Pe==="verify"?T=$.filter(B=>z.has(B.function.name)):T=$;let N=Vi(),Q=new AbortController;N&&N.addEventListener("abort",()=>Q.abort(),{once:!0}),_a.signal.addEventListener("abort",()=>Q.abort(),{once:!0}),Nt=await dy(S,T,{signal:Q.signal,...kn?{model:kn}:{},onThinkingToken:()=>{ba=Date.now(),_r=!1,dn?.onThinkingToken&&dn.onThinkingToken()},onToken:B=>{if(ba=Date.now(),_r=!1,dn?.onToken){dn.onToken(B),ft+=B;return}if(ft+=B,!vn&&ft.length>400&&ft.length%250<B.length+1){let re=Zl(ft,3);re.truncated&&(vn=!0,Ve._clearCursorLine?.(),D(`${m.yellow} \u26A0 LLM stream loop detected (${re.repeatCount}\xD7 repeated) \u2014 suppressing display${m.reset}`))}vn||(Mt+=B,process.stdout.isTTY?fn||(fn=setTimeout(()=>{Mt&&Ve&&Ve.push(Mt),Mt="",fn=null},50)):(Ve.push(Mt),Mt=""),et&&(l&&!l._paused?l.pause():ve&&ve.stop(),we||(we=!0),Ve.startCursor(),et=!1))}})}catch($){if(clearInterval(Ru),fn&&(clearTimeout(fn),fn=null),Mt&&Ve&&(Ve.push(Mt),Mt=""),l&&!l._paused&&l.pause(),ve&&ve.stop(),Ve.stopCursor(),_a.signal.aborted&&!Vi()?.aborted){if(K++,K>zi){if(ge<1){ge++,eo("Stale retries exhausted \u2014 last-resort force-compress...",m.yellow);let re=dt(),{messages:R,tokensRemoved:q}=cn(S,re);S=R,q>50&&D(`${m.dim} [force-compressed \u2014 ~${q} tokens freed]${m.reset}`),K=0,We--;continue}l&&(l.stop(),l=null);let B=await CR();if(B.action==="quit"){c(null),Me(M,L,b,Z,Ne),Oe(P);break}B.action==="switch"&&(ql(`${B.provider}:${B.model}`),console.log(`${m.green} \u2713 Switched to ${B.provider}:${B.model}${m.reset}`)),K=0,We--;continue}let N=K===1?3e3:5e3;if(K>=1&&ke<1){ke++,eo(`Stale retry ${K}/${zi} \u2014 force-compressing before retry...`,m.yellow);let B=dt(),{messages:re,tokensRemoved:R}=cn(S,B,!0);if(S=re,R>0&&R>50&&D(`${m.dim} [force-compressed \u2014 ~${R} tokens freed]${m.reset}`),iR){let q=ca.fast?.[no()];q&&q!==en()&&(ql(`${no()}:${q}`),console.log(`${m.cyan} \u26A1 Auto-switched to ${q} to avoid further stale timeouts${m.reset}`),console.log(`${m.dim} (disable with NEX_STALE_AUTO_SWITCH=0)${m.reset}`))}}else D(`${m.yellow} \u26A0 Stale retry ${K}/${zi} \u2014 retrying in ${N/1e3}s...${m.reset}`);let Q=new to(`Waiting ${N/1e3}s before retry...`);Q.start(),await new Promise(B=>setTimeout(B,N)),Q.stop(),We--;continue}if($.name==="AbortError"||$.name==="CanceledError"||$.message?.includes("canceled")||$.message?.includes("aborted")){l&&(l.stop(),l=null),c(null),Me(M,L,b,Z,Ne),Oe(P);break}let y=$.message;if($.code==="ECONNREFUSED"||$.message.includes("ECONNREFUSED"))y="Connection refused \u2014 please check your internet connection or API endpoint";else if($.code==="ENOTFOUND"||$.message.includes("ENOTFOUND"))y="Network error \u2014 could not reach the API server. Please check your connection";else if($.code==="ETIMEDOUT"||$.message.includes("timeout"))y="Request timed out \u2014 the API server took too long to respond. Please try again";else if($.message.includes("401")||$.message.includes("Unauthorized"))y="Authentication failed \u2014 please check your API key in the .env file";else if($.message.includes("403")||$.message.includes("Forbidden"))y="Access denied \u2014 your API key may not have permission for this model";else if($.message.includes("404")){let N=en?en():"unknown",Q=R=>R.includes(":")&&R.split(":")[0].match(/^[a-z]+$/)&&!R.split(":")[1].includes(":")?R.split(":").slice(1).join(":"):R;xe.add(Q(N));let re=(()=>{let R=[];process.env.NEX_FALLBACK_MODEL&&R.push(process.env.NEX_FALLBACK_MODEL);try{let{getModelForCategory:q}=ls(),F=["agentic","coding","plan","verify","sysadmin","data","frontend"];for(let V of F){let X=q(V);X&&!R.includes(X)&&R.push(X)}}catch{}return R.filter(q=>!xe.has(Q(q)))})()[0];if(re){console.log(`${m.yellow} \u26A0 Model ${N} unavailable (404) \u2014 switching to ${re}${m.reset}`),ql(re),uy(re),We--;continue}y=`Model not found (404): ${N} \u2014 no fallback available. Set NEX_FALLBACK_MODEL or run /models to list available models`,console.log(`${m.red} \u2717 ${y}${m.reset}`),l&&(l.stop(),l=null),c(null),Me(M,L,b,Z,Ne),Oe(P);break}else if($.message.includes("400")){if(ge<3&&Ae<qe){ge++,Ae++;let N=M===0&&ge===1,Q=N||ge===3||ke>0;if(N){ge=3;let q=$.message.replace(/^API Error(\s*\[HTTP \d+\])?:\s*/i,"").slice(0,150);eo(`Bad request (400) \u2014 ${q||"system prompt too large"}, compressing...`,m.yellow)}else eo(Q?`Bad request (400) \u2014 nuclear compression (attempt ${ge}/3, dropping history)...`:`Bad request (400) \u2014 force-compressing and retrying... (attempt ${ge}/3)`,m.yellow);let B=dt(),{messages:re,tokensRemoved:R}=cn(S,B,Q);S=re,R>50&&D(`${m.dim} [force-compressed \u2014 ~${R} tokens freed]${m.reset}`),We--;continue}{let N=S.find(F=>F.role==="system"),Q=S.find(F=>F.role==="user"&&!String(F.content).startsWith("[SYSTEM")&&!String(F.content).startsWith("BLOCKED:")),B=[N,Q].filter(Boolean),{getUsage:re}=rn(),R=rn().estimateMessagesTokens(B),q=rn().estimateMessagesTokens(S);if(R<q){let F=[],V=P.filter(ee=>ee.role==="assistant"&&typeof ee.content=="string"&&ee.content.trim().length>30).slice(-5).map(ee=>ee.content.trim().slice(0,300).replace(/\n+/g," "));V.length>0&&F.push(`Key findings:
|
|
1401
|
+
`+V.map(ee=>`- ${ee}`).join(`
|
|
1402
|
+
`));let X=P.filter(ee=>ee.role==="tool"&&typeof ee.content=="string"&&!ee.content.startsWith("BLOCKED:")&&ee.content.trim().length>10).slice(-5).map(ee=>ee.content.trim().split(`
|
|
1362
1403
|
`).slice(0,8).join(`
|
|
1363
1404
|
`).slice(0,500));if(X.length>0&&F.push(`Tool results summary:
|
|
1364
|
-
`+X.map(
|
|
1365
|
-
`)),
|
|
1366
|
-
${JSON.stringify(
|
|
1405
|
+
`+X.map(ee=>`- ${ee}`).join(`
|
|
1406
|
+
`)),b.size>0){let ee=[...b].map(_e=>_e.split("/").slice(-2).join("/")).join(", ");F.unshift(`Already modified: ${ee} \u2014 use edit_file to add missing pieces only, DO NOT use write_file on these files.`)}if(Z.size>0){let ee=[...Z].map(_e=>_e.split("/").slice(-2).join("/")).join(", ");F.push(`Files already investigated: ${ee}`)}let ie=require("os").tmpdir()+"/nex-session-checkpoint.json";try{require("fs").writeFileSync(ie,JSON.stringify({filesWritten:[...b].map(ee=>ee.split("/").slice(-2).join("/")),filesRead:[...Z].map(ee=>ee.split("/").slice(-2).join("/")),isCreationTask:Bt,wipeNumber:ar+1,timestamp:Date.now()},null,2)),F.push(`Session checkpoint: ${ie} \u2014 read it for exact file list`)}catch{}let me=0;{let _e=((typeof Q?.content=="string"?Q.content:Array.isArray(Q?.content)?Q.content.filter(nt=>nt.type==="text").map(nt=>nt.text).join(" "):"").match(/(?:^|\s)([\w./\-]+\.(?:js|ts|jsx|tsx|py|json|yml|yaml|sh|css|scss|html|md|go|rs|java|rb|php))/gm)||[]).map(nt=>nt.trim()).filter(Boolean),Re=[...b],$t=_e.filter(nt=>!Re.some(ka=>ka.endsWith(nt)||nt.endsWith(ka.split("/").pop())));me=$t.length;let tt=[...P].reverse().find(nt=>nt.role==="tool"&&typeof nt.content=="string"&&!nt.content.startsWith("BLOCKED:")&&nt.content.length>5),Lt={completed:Re.map(nt=>nt.split("/").slice(-2).join("/")),pending:$t.length>0?$t:Re.length===0?["(task files not yet identified)"]:[],lastEdit:tt?tt.content.trim().slice(0,120):null};(Lt.completed.length>0||Lt.pending.length>0)&&F.unshift(`Work manifest:
|
|
1407
|
+
${JSON.stringify(Lt,null,2)}`)}if(F.length>0){let ee={role:"user",content:`[SYSTEM: Findings from investigation before context wipe]
|
|
1367
1408
|
${F.join(`
|
|
1368
1409
|
`)}
|
|
1369
|
-
Continue implementing the fixes based on these findings.`};
|
|
1370
|
-
Files modified so far: ${[...
|
|
1410
|
+
Continue implementing the fixes based on these findings.`};B.push(ee)}if(ar>=3){let ee=b.size>0?`
|
|
1411
|
+
Files modified so far: ${[...b].map(_e=>_e.split("/").slice(-1)[0]).join(", ")}`:"";D(`${m.red} \u2717 Super-nuclear limit reached (3\xD7) \u2014 aborting to prevent runaway context loop${m.reset}`),console.log(`${m.yellow} \u{1F4A1} Task may exceed model context. Try /clear and break it into smaller steps.${ee?m.dim+ee:""}${m.reset}`),l&&(l.stop(),l=null),c(null),Me(M,L,b,Z,Ne,{suppressHint:!0}),Oe(P);break}S=B,ar++,ys=10+Math.min(me*3,7),ou=!0,sa=b.size,oa=!1,Ft=0,H=0;for(let[ee,_e]of xn){let Re=_e?.count??_e??0;Kl(xn,ee,Re>=2?Re:1)}for(let[ee]of In)ln(xn,ee)<2&&In.delete(ee);qt.clear(),bs.clear(),Bt&&Qt>0&&(Wt=!0,D(`${m.cyan} \u26A1 Post-wipe creation guard: cap pre-fired (${Qt} edits already made)${m.reset}`));for(let[ee]of Zi)Kl(Zi,ee,$r-1);if(eo(`Super-nuclear compression \u2014 dropped all history, keeping original task only (${q-R} tokens freed)`,m.yellow),ar>=1){let ee=[...xn.entries()].filter(([,tt])=>tt>=ks).map(([tt])=>tt.split("/").slice(-1)[0]),_e=ee.length>0?`
|
|
1371
1412
|
|
|
1372
|
-
Files already at read cap \u2014 use grep_search instead: ${
|
|
1373
|
-
Use /undo to revert changes made during this session.${
|
|
1374
|
-
`),
|
|
1413
|
+
Files already at read cap \u2014 use grep_search instead: ${ee.join(", ")}`:"",$t={role:"user",content:Ot&&!it?"[SYSTEM] Context was compressed. SSH is currently unavailable \u2014 do not read more local files. Summarize what you found and ask the user for the server output you need.":`[SYSTEM] Context was compressed. Use the findings above to implement your fix. If you need to re-read a file, use line_start/line_end for the specific section.${_e}`};P.push($t),S.push($t)}ge=0,We--;continue}}y="Context too large to compress \u2014 use /clear to start fresh"}else $.message.includes("500")||$.message.includes("502")||$.message.includes("503")||$.message.includes("504")?y="API server error \u2014 the provider is experiencing issues. Please try again in a moment":($.message.includes("fetch failed")||$.message.includes("fetch"))&&(y="Network request failed \u2014 please check your internet connection");if(console.log(`${m.red} \u2717 ${y}${m.reset}`),$.message.includes("429")){if(Te++,Te>Wl){console.log(`${m.red} Rate limit: max retries (${Wl}) exceeded. Try again later or use /budget to check your limits.${m.reset}`),l&&(l.stop(),l=null),c(null),Me(M,L,b,Z,Ne),Oe(P);break e}let N=Math.min(1e4*Math.pow(2,Te-1),12e4),Q=new to(`Rate limit \u2014 waiting ${Math.round(N/1e3)}s (retry ${Te}/${Wl})`);Q.start(),await new Promise(B=>setTimeout(B,N)),Q.stop();continue}let z=process.env.NEX_PHASE_ROUTING!=="0"&&(()=>{try{return st().getActiveProviderName()==="ollama"}catch{return!1}})();if($.message.includes("socket disconnected")||$.message.includes("TLS")||$.message.includes("ECONNRESET")||$.message.includes("ECONNABORTED")||$.message.includes("ETIMEDOUT")||z&&($.message.includes("500")||$.message.includes("502")||$.message.includes("503")||$.message.includes("504")||$.message.includes("401")||$.message.includes("Unauthorized"))||$.code==="ECONNRESET"||$.code==="ECONNABORTED"){if(W++,W>Hl){console.log(`${m.red} Network error: max retries (${Hl}) exceeded. Check your connection and try again.
|
|
1414
|
+
Use /undo to revert changes made during this session.${m.reset}`),l&&(l.stop(),l=null),c(null),Me(M,L,b,Z,Ne),Oe(P);break e}let N=Math.min(2e3*Math.pow(2,W-1),3e4),Q=new to(`API temporarily unavailable \u2014 retrying in ${Math.round(N/1e3)}s (${W}/${Hl}). Your changes are safe.`);Q.start(),await new Promise(B=>setTimeout(B,N)),Q.stop(),We--;continue}l&&(l.stop(),l=null),c(null),Me(M,L,b,Z,Ne),Oe(P);break}if(clearInterval(Ru),Te=0,W=0,et&&(l&&!l._paused&&l.pause(),ve&&ve.stop()),fn&&(clearTimeout(fn),fn=null),Mt&&Ve&&(Ve.push(Mt),Mt=""),ft&&Ve.flush(),W=0,K=0,Nt&&Nt.usage){let $=Nt.usage.prompt_tokens||0,y=Nt.usage.completion_tokens||0;py(no(),en(),$,y),u+=$+y,l&&l.setStats({tokens:u})}else if(Nt&&!Nt.usage){let $=S.map(T=>typeof T.content=="string"?T.content:Array.isArray(T.content)?T.content.map(N=>typeof N=="string"?N:N.text||"").join(""):"").join(" "),y=my($),z=my(Nt.content||ft||"");py(no(),en(),y,z),u+=y+z,l&&l.setStats({tokens:u})}let{content:Cu,tool_calls:pn}=Nt,xr=Zl(Cu||""),Au=xr.truncated?xr.text:Cu;xr.truncated&&D(`${m.yellow} \u26A0 LLM output loop detected (${xr.repeatCount}\xD7 repeated paragraph) \u2014 response truncated${m.reset}`);let kr=zT(Au||""),Pt=kr.truncated?kr.text:Au;kr.truncated&&D(`${m.yellow} \u26A0 LLM output loop detected (${kr.repeatCount}\xD7 repeated window) \u2014 response truncated${m.reset}`);let fo={role:"assistant",content:Pt||""};if(pn&&pn.length>0&&(fo.tool_calls=pn),P.push(fo),S.push(fo),Eu&&(Pt||"").trim().length>1500&&b.size===0&&Sn===0){D(`${m.green} \u2713 Analysis-only early exit: ${(Pt||"").length} chars produced, no file changes${m.reset}`),fo.tool_calls&&delete fo.tool_calls,Me(M,L,b,Z,Ne),Oe(P);break e}if(!it&&Pt&&pn&&pn.length>0){let $=zl(Pt);if($){it=!0,xt=$.slice(0,120),Ut=0,Wt=!1,Zt=0,D(`${m.yellow} \u26A1 Root cause in model analysis: ${xt} \u2014 fix phase (read budget: 3)${m.reset}`);let y={role:"user",content:`[SYSTEM] Root cause identified: ${xt}. Read only the file that needs fixing, then edit it. Do not read other files.`};P.push(y),S.push(y)}}if(!pn||pn.length===0){let $=(Pt||"").trim().length>0||ft.trim().length>0,y=!1;if(Ot&&$&&(Ki>=2?D(`${m.yellow} \u26A0 SSH permanently blocked after ${Ki} storm warnings \u2014 no further SSH calls allowed${m.reset}`):(Ot=!1,Ft=uo-4,y=!0)),y&&$){let T=(Pt||"").trim();if(T.endsWith("?")||/\b(Wo |Bitte |Kannst du|Soll ich)\b/.test(T.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."};S.push(Q),P.push(Q);continue}}if(!$&&M>0&&We<Ql-1){let T={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."};S.push(T),P.push(T);continue}let z=/keine.*Tool|can.?t use.*tool|Tool.?Budget|nicht.*zugreifen|cannot.*access|no.*tool.*access|keine.*Werkzeug|da ich keine.*kann/i;if($&&We<3&&z.test((Pt||"").slice(0,600)))if(ou&&ys<=0||Ot){D(`${m.yellow} \u26A0 Tool avoidance (constrained context) \u2014 telling model to ask user${m.reset}`);let N={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."};S.push(N),P.push(N);continue}else{D(`${m.yellow} \u26A0 Tool avoidance detected \u2014 nudging model to use tools${m.reset}`);let N={role:"user",content:"[SYSTEM] You have full tool access. Use your tools to investigate and implement the fix directly \u2014 do not say you cannot use tools. If SSH is needed, use a single targeted command that captures the most relevant information rather than multiple sequential calls."};S.push(N),P.push(N);continue}if(s.skillLoop&&$&&M>3&&br<5){let T=(Pt||ft||"").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(T.slice(-600))){br=(br||0)+1,D(`${m.yellow} \u26A0 Skill loop: model tried to stop \u2014 continuation nudge #${br}${m.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."};S.push(Q),P.push(Q);continue}}if(ur()&&!s.skillLoop&&!be&&(b.size>0||Sn>0)&&$&&M>=2){D(`${m.green} \u2713 Headless early exit: ${b.size} file(s) modified (+ ${Sn} bash writes), text response received${m.reset}`),Me(M,L,b,Z,Ne),Oe(P);break e}if(be&&Pe==="plan"&&jn>=2){D(`${m.cyan} \u21B3 Plan phase: ${jn} consecutive blocks \u2014 auto-advancing to implement${m.reset}`),jn=0;let T=await or("implement","[auto-advance: task only requires direct action]");if(T){P.push(T),S.push(T),We=0,St=ms("implement");continue}}if(be&&$){let T=(Pt||ft||"").trim();if(Pe==="plan"){let N=/\b(no match(es)?|not found|couldn'?t find|does not exist|no results|nothing found|no files|keine (Ergebnisse|Treffer|Übereinstimmung|Funde|passenden)|nicht gefunden|nichts gefunden)\b/i,Q=Iy(T,xn).length===0,B=fr.size>0,re=pr.size>0,R=T.length>1500;if(ur()&&Q&&!B&&!re&&!R&&N.test(T)){D(`${m.yellow} \u26A0 Plan phase: nothing actionable found \u2014 exiting gracefully${m.reset}`),process.stdout.isTTY&&process.stderr.write(`${m.yellow} \u26A0 Could not find the target in this project. The plan phase found no actionable items.${m.reset}
|
|
1415
|
+
`),Me(M,L,b,Z,Ne),Oe(P);break e}let q=await or("implement",T);if(q){P.push(q),S.push(q),We=0,St=ms("implement");continue}}else if(Pe==="implement"&&(b.size>0||Sn>0)){let N=P.find(re=>re.role==="user"),Q=typeof N?.content=="string"?N.content:"",B=await or("verify",T,b,Q);if(B){P.push(B),S.push(B),We=0,St=Math.min(ms("verify")+Math.max(0,(b.size-2)*2),20);continue}}else if(Pe==="verify"){let N=/\bPASS\b/i.test(T.slice(0,500)),B=/\bFAIL\b|test.*fail|error|broken|missing|incorrect/i.test(T.slice(0,500));if(B&&oo<3){oo++;let re={role:"user",content:`[PHASE: RE-IMPLEMENTATION] Verification found issues:
|
|
1375
1416
|
${T.slice(0,400)}
|
|
1376
1417
|
|
|
1377
|
-
Fix the identified issues. This is attempt ${
|
|
1418
|
+
Fix the identified issues. This is attempt ${oo}/3.`};Pe="implement",kn=Jl("implement",io),P.push(re),S.push(re),We=0,St=ms("implement"),D(`${m.yellow} \u21B3 Verify \u2192 implement loop-back #${oo} (issues found)${m.reset}`);continue}if(!B&&(!N||mr===0)){if(ro<2){ro++;let re=[];mr===0&&re.push("run at least one verification tool"),N||re.push("end your report with PASS or FAIL");let R={role:"user",content:`[SYSTEM] Verification is incomplete: ${re.join(" and ")}. Do not stop yet. Re-read the modified files and/or run tests or linters, then respond with PASS or FAIL.`};P.push(R),S.push(R),D(`${m.yellow} \u26A0 Verify phase incomplete \u2014 nudging for evidence (${ro}/2)${m.reset}`);continue}D(`${m.yellow} \u26A0 Verify phase completion accepted without full markers after ${ro} nudges${m.reset}`)}if(D(`${m.green} \u2713 Verification phase complete${B?" (loop-back exhausted)":" (PASS)"}${m.reset}`),!B){Me(M,L,b,Z,Ne),Oe(P),Gi(P);break e}}}if(dr()&&$&&M===0)if(ea++,ea>2)D(`${m.yellow} \u26A0 Plan accepted despite no file reads (rejection loop cap reached)${m.reset}`);else{let T={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.).
|
|
1378
1419
|
|
|
1379
|
-
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.`};
|
|
1380
|
-
${
|
|
1381
|
-
`),
|
|
1420
|
+
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.`};P.push(T),S.push(T),D(`${m.yellow} \u26A0 Plan rejected (${ea}/2): no files read \u2014 forcing investigation${m.reset}`);continue}if(dr()&&$){let T=(Pt||ft||"").trim();ST(T),aR(T);let N=vT(T);if(N.length>0){let Q=P.find(q=>q.role==="user"),B=typeof Q?.content=="string"?Q.content.slice(0,120):"Task";ET(B,N);let re=N.length===1?"step":"steps",R=!1;if(process.stdout.isTTY&&process.stdin.isTTY){let{approvePlan:q,startExecution:F,setPlanMode:V}=Ui();process.stdout.write(`
|
|
1421
|
+
${m.cyan}${m.bold}Plan ready${m.reset} ${m.dim}(${N.length} ${re})${m.reset} ${m.green}[A]${m.reset}${m.dim}pprove${m.reset} ${m.yellow}[E]${m.reset}${m.dim}dit${m.reset} ${m.red}[R]${m.reset}${m.dim}eject${m.reset} ${m.dim}[\u21B5 = approve]:${m.reset} `);let X=process.stdin.isRaw,ie=await new Promise(me=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",ee=>{try{process.stdin.setRawMode(X||!1)}catch{}let _e=ee.toString().toLowerCase()[0]||"\r";me(_e)})});if(process.stdout.write(`
|
|
1422
|
+
`),ie==="r")console.log(`${m.red}Plan rejected.${m.reset} Ask follow-up questions to refine.`);else if(ie==="e")console.log(`${m.yellow}Type /plan edit to open in editor, or give feedback.${m.reset}`);else if(q()){F(),V(!1),tu(),console.log(`${m.green}${m.bold}Approved!${m.reset} Executing ${N.length} ${re}...`);let me=`[PLAN APPROVED \u2014 EXECUTE NOW]
|
|
1382
1423
|
|
|
1383
1424
|
Implement the following plan step by step. All tools are now available.
|
|
1384
1425
|
|
|
1385
|
-
${T}`;
|
|
1386
|
-
${
|
|
1387
|
-
${
|
|
1388
|
-
`),F==="r")console.log(`${
|
|
1426
|
+
${T}`;P.push({role:"user",content:me}),S.push({role:"user",content:me}),R=!0}}else console.log(`
|
|
1427
|
+
${m.cyan}${m.bold}Plan ready${m.reset} ${m.dim}(${N.length} ${re} extracted).${m.reset} Type ${m.cyan}/plan approve${m.reset}${m.dim} to execute, or ${m.reset}${m.cyan}/plan edit${m.reset}${m.dim} to review.${m.reset}`);if(R){l&&(l.stop(),l=null),We--;continue}}else{let Q=!1;if(process.stdout.isTTY&&process.stdin.isTTY){let{approvePlan:B,startExecution:re,setPlanMode:R}=Ui();process.stdout.write(`
|
|
1428
|
+
${m.cyan}${m.bold}Plan ready.${m.reset} ${m.green}[A]${m.reset}${m.dim}pprove${m.reset} ${m.red}[R]${m.reset}${m.dim}eject${m.reset} ${m.dim}[\u21B5 = approve]:${m.reset} `);let q=process.stdin.isRaw,F=await new Promise(V=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",X=>{try{process.stdin.setRawMode(q||!1)}catch{}V(X.toString().toLowerCase()[0]||"\r")})});if(process.stdout.write(`
|
|
1429
|
+
`),F==="r")console.log(`${m.red}Plan rejected.${m.reset} Ask follow-up questions to refine.`);else if(B()){re(),R(!1),tu(),console.log(`${m.green}${m.bold}Approved!${m.reset} Executing...`);let X=`[PLAN APPROVED \u2014 EXECUTE NOW]
|
|
1389
1430
|
|
|
1390
1431
|
Implement the following plan step by step. All tools are now available.
|
|
1391
1432
|
|
|
1392
|
-
${getPlanContent()||
|
|
1393
|
-
${
|
|
1394
|
-
${U}`),L.push({role:"user",content:T},{role:"assistant",content:U}))}catch{}Ae(L),Di(L),await uu();return}N++,ta++,N>=1&&(ye=!1);for(let w of an){let y=w.function.name;q.set(y,(q.get(y)||0)+1)}if(N>=30&&!Vg){Vg=!0,j(`${h.yellow} \u26A0 Tool budget warning: ${N} tool calls used \u2014 nudging model to wrap up${h.reset}`);let w={role:"user",content:"[SYSTEM] \u26A0 You have used "+N+" 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."};L.push(w),S.push(w)}let we=await Promise.all(an.map(w=>uT(w)));{let w=Gt(S,at()),y=w.percentage,K=we.some(U=>U.canExecute&&U.fnName==="read_file"&&!U.args?.line_end),T=we.filter(U=>U.canExecute&&U.fnName==="read_file"&&U.args?.path&&sn(ys,U.args.path)>=1&&!U.args?.line_start).map(U=>U.args.path.split("/").slice(-2).join("/")),M=T.length>0;if(y>=70&&K&&aa<70||y>=85&&aa<85||M){aa=y;let U=y>=85?"URGENT":"WARNING",ae;M?(U="WARNING",ae=`Full-file read of ${T.join(", ")} already done \u2014 use line_start/line_end for specific sections instead.`):K?ae=`Unbounded read at ${Math.round(y)}% context \u2014 use line_start/line_end to avoid overflow.`:ae="Use targeted reads (line_start/line_end) to save space.";let C={role:"user",content:`[SYSTEM ${U}] Context ${Math.round(y)}% used (${w.used}/${w.limit} tokens). ${ae}`};if(L.push(C),S.push(C),y>=85){let D=M?` (re-read of: ${T.join(", ")})`:"";j(`${h.yellow} \u26A0 Context ${Math.round(y)}% used \u2014 agent warned to use targeted reads${D}${h.reset}`)}}}let pa=new Map;for(let w of we){if(!w.canExecute||w.fnName!=="read_file")continue;let y=w.args?.path;if(!y)continue;let K=sn(ys,y),T=pa.get(y)||0,M=K+T,ee=w.args?.line_start!=null,U=Lt.get(y)||0,ae=U>0,C=2;if(M>=ws){let D=y.split("/").slice(-2).join("/"),F=(hs.get(y)||0)+1;if(hs.set(y,F),F===1)j(`${h.red} \u2716 Blocked: "${D}" read ${M}\xD7 \u2014 hard cap (${ws}) reached${h.reset}`);else if(F===2){j(`${h.red} \u2716 Escalated block: "${D}" \u2014 model ignored BLOCKED, injecting system warning${h.reset}`);let V={role:"user",content:`[SYSTEM WARNING] You already received a BLOCKED error for read_file("${y}") and tried again anyway. This file has reached its read cap (${ws}\xD7). Do NOT attempt to read it again. Use grep_search to find specific content, or proceed with what you already know.`};L.push(V),S.push(V)}w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 file already read ${M}\xD7 (hard cap: ${ws}). You have seen enough of this file. Use grep to find specific content or proceed with what you know.`,tool_call_id:w.callId}}else if(M>=1&&ee)if(ae&&U<=C){let D=y.split("/").slice(-2).join("/");console.log(`${h.cyan} \u21A9 Targeted re-read: "${D}" (line_start=${w.args.line_start}) \u2014 edit recovery #${U}${h.reset}`),Lt.set(y,U-1)}else if(ae&&U>C){let D=y.split("/").slice(-2).join("/");j(`${h.red} \u2716 Edit recovery blocked: "${D}" \u2014 ${C} recovery reads already used. Use grep to find the exact line numbers, then retry.${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 edit recovery budget exhausted (${C} 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:w.callId}}else{let D=parseInt(w.args.line_start,10)||1,F=parseInt(w.args.line_end,10)||D+350,V=Cn.get(y)||[],X=!1;for(let[re,fe]of V){let te=Math.max(D,re),$e=Math.min(F,fe);if($e>te){let Te=$e-te,gt=F-D||1,Je=fe-re||1,Ot=Te/Je>=.7&&Te/gt<.7,Ze=F-D<=Uy;if(Te>=gt||!Ze&&(Te/gt>=.7||Te/Je>=.7)){let ma=y.split("/").slice(-2).join("/"),$u=`${y}:${D}-${F}`,$s=(ea.get($u)||0)+1;if(ea.set($u,$s),j(Ot?`${h.red} \u2716 Blocked superread: "${ma}" lines ${D}-${F} subsumes already-read ${re}-${fe} \u2014 use line_start=${fe+1} to skip known content (block #${$s})${h.reset}`:`${h.red} \u2716 Blocked duplicate read: "${ma}" lines ${D}-${F} (\u226570% overlap with lines ${re}-${fe} already in context, block #${$s})${h.reset}`),$s>=2){j(`${h.red} \u2716 Escalated range-block: "${ma}" lines ${D}-${F} \u2014 model ignored BLOCKED, injecting system warning${h.reset}`);let bu={role:"user",content:Ot?`[SYSTEM] Read blocked ${$s}\xD7 for read_file("${y}", lines ${D}-${F}). Lines ${re}-${fe} were already read. Use line_start=${fe+1} to read only new content, or use grep_search for specific lines.`:`[SYSTEM] Read blocked ${$s}\xD7 for read_file("${y}", lines ${D}-${F}). Lines ${re}-${fe} were already read and will NOT change. Use grep_search to find specific content instead.`};L.push(bu),S.push(bu)}w.canExecute=!1,w.errorResult={role:"tool",content:Ot?`BLOCKED: read_file("${y}", lines ${D}-${F}) re-reads lines ${re}-${fe} already in context. Use line_start=${fe+1} to read only the new content beyond line ${fe}.`:`BLOCKED: read_file("${y}", lines ${D}-${F}) is a duplicate \u2014 lines ${re}-${fe} are already in your context (\u226570% overlap). Use grep to find specific content instead of re-reading.`,tool_call_id:w.callId},X=!0;break}}}if(!X){let re=V.length,fe=2;if(re>=3){let $e=y.split("/").slice(-2).join("/");j(`${h.red} \u2716 Blocked file-scroll: "${$e}" \u2014 ${re} sections already read. Use grep to find specific content.${h.reset}`);let Te=sn(ia,y)>=fr;w.canExecute=!1,w.errorResult={role:"tool",content:Te?`BLOCKED: read_file("${y}") denied \u2014 you have already read ${re} different sections of this file (file-scroll pattern). Grep is also exhausted. The content you need is already in your context \u2014 work with what you have.`:`BLOCKED: read_file("${y}") denied \u2014 you have already read ${re} 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:w.callId}}else re>=fe&&(w._scrollWarn={sectionCount:re+1,path:y})}}else if(M>=1){let D=Lt.get(y)||0;if(D>0){let F=y.split("/").slice(-2).join("/");console.log(`${h.cyan} \u21A9 Full re-read: "${F}" \u2014 test-failure recovery (${D} remaining)${h.reset}`);let V=D-1;V<=0?Lt.delete(y):Lt.set(y,V)}else{let F=y.split("/").slice(-2).join("/"),V=(hs.get(y)||0)+1;if(hs.set(y,V),V===1)j(`${h.red} \u2716 Blocked unbounded re-read: "${F}" \u2014 already in context. Use line_start/line_end for specific sections.${h.reset}`);else if(V===2){j(`${h.red} \u2716 Escalated block: "${F}" \u2014 model ignored unbounded re-read block, injecting system warning${h.reset}`);let X={role:"user",content:`[SYSTEM] read_file("${y}") was blocked again \u2014 full-file reads are disabled after the first read. Use line_start/line_end for a specific section, or use grep_search to find what you need.`};L.push(X),S.push(X)}w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 file already in context (read ${M}\xD7). Use line_start/line_end to read a specific section instead of the full file.`,tool_call_id:w.callId}}}w.canExecute&&pa.set(y,(pa.get(y)||0)+1)}if(Rn>=3)for(let w of we)w.canExecute&&(w.fnName!=="read_file"&&w.fnName!=="edit_file"||(j(`${h.red} \u2716 Blocked ${w.fnName} \u2014 ${Rn} consecutive file-not-found errors, must search first${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: ${Rn} 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:w.callId}));for(let w of we){if(!w.canExecute||w.fnName!=="bash")continue;let y=(w.args?.command||"").trim();if(/^\s*ls(\s+-[a-zA-Z]+)*(\s+\S+)?\s*$/.test(y)&&!/npm|yarn|pnpm|make|git/.test(y)){j(`${h.red} \u2716 Blocked bash ls \u2014 use list_directory tool instead${h.reset}`),w.canExecute=!1,w.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:w.callId};continue}/\bfind\s+[\S.]/.test(y)&&!/git\s|npm\s|yarn\s|-exec\s+\S|-execdir/.test(y)&&(j(`${h.red} \u2716 Blocked bash find \u2014 use glob tool with a pattern instead${h.reset}`),w.canExecute=!1,w.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:w.callId})}for(let w of we)w.canExecute&&(w.fnName!=="ssh_exec"&&w.fnName!=="bash"||/\bsed\s+-n\b/.test(w.args?.command||"")&&(j(`${h.red} \u2716 Blocked sed -n: use grep -n "pattern" <file> | head -30 instead${h.reset}`),w.canExecute=!1,w.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:w.callId}));for(let w of we){if(!w.canExecute||w.fnName!=="write_file")continue;let y=w.args?.path,K=w.args?.content||"";if(y)try{let T=require("fs"),M=require("path").resolve(process.cwd(),y);if(T.existsSync(M)){let ee=T.statSync(M).size,U=Buffer.byteLength(K,"utf8"),ae=ee>0?U/ee:1;if(ae<.6&&ee>200){let C=y.split("/").slice(-2).join("/");console.log(`${h.red} \u2716 write_file shrink guard: "${C}" would shrink to ${Math.round(ae*100)}% of original \u2014 likely context loss${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: write_file("${y}") denied \u2014 new content is only ${Math.round(ae*100)}% of current file size (${ee} \u2192 ${U} 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:w.callId}}}}catch{}}let gu=new Map;for(let w of we){if(!w.canExecute||w.fnName!=="grep")continue;let y=w.args?.path;if(!y)continue;let K=gu.get(y)||0,T=sn(ia,y)+K,M=sn(ys,y)>=1,ee=M?Math.min(3,fr):fr;if(T>=ee){let U=y.split("/").slice(-2).join("/");j(`${h.red} \u2716 Blocked grep: "${U}" grepped ${T}\xD7 with different patterns \u2014 flood threshold exceeded${h.reset}`);let ae=sn(ys,y),C=ae>=ws;if(C){let D={role:"user",content:`[SYSTEM] Both read_file and grep are now blocked for "${y}". You have already read ${ae} sections and tried ${T} 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.`};L.push(D),S.push(D),j(`${h.red} \u2716 Deadlock detected: "${U}" \u2014 both read and grep blocked, injecting deadlock-break${h.reset}`)}w.canExecute=!1,w.errorResult={role:"tool",content:C?`BLOCKED: grep("${y}") denied \u2014 ${T} 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.`:M?`BLOCKED: grep("${y}") denied \u2014 file was already read and ${T} grep patterns tried. The content is already in your context; use it instead of searching again.`:`BLOCKED: grep("${y}") denied \u2014 ${T} patterns already tried. Work with the grep results already in your context.`,tool_call_id:w.callId}}w.canExecute&&gu.set(y,K+1)}let Ky=5,yu=new Map;for(let w of we){if(!w.canExecute||w.fnName!=="ssh_exec")continue;let K=(w.args?.command||"").replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),T=yu.get(K)||0,M=sn(au,K)+T;M>=Ky&&(j(`${h.yellow} \u26A0 Blocked ssh_exec: same command run ${M}\xD7 \u2014 result already in context${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: ssh_exec denied \u2014 this command has already run ${M} 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:w.callId}),w.canExecute&&yu.set(K,T+1)}if(Tt){let w=we.filter(T=>T.canExecute&&T.fnName==="ssh_exec"),y=we.some(T=>T.canExecute&&T.fnName!=="ssh_exec"),K=I&&H<3;if(w.length>0&&!y&&K&&zi<1)Tt=!1,zi++,It=Math.max(0,ao-2),j(`${h.dim} [dual-block deadlock: SSH storm relaxed \u2014 allowing 1 SSH call (relax ${zi}/1)]${h.reset}`);else for(let T of w)T.canExecute=!1,T.errorResult={role:"tool",content:nt?`BLOCKED: ssh_exec denied \u2014 SSH paused (${ao}+ calls). Root cause is known (${_t}). 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 (${ao}+ 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:T.callId}}if(I&&H<3&&!Tt){for(let w of we)if(w.canExecute&&["bash","read_file","find_files"].includes(w.fnName)){H++;{let y=at(),{messages:K}=nn(S,y);S=K}j(`${h.yellow} \u26A0 Server-local guard: blocking local ${w.fnName} \u2014 use ssh_exec on 94.130.37.43${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: ${w.fnName} denied \u2014 this is a server issue. Use ssh_exec on 94.130.37.43 instead.`,tool_call_id:w.callId};break}}if(!_e&&qt&&Dt&&Kt>=1){let w=["read_file","grep","search_files","glob","list_directory","find_files"];for(let y of we)y.canExecute&&w.includes(y.fnName)&&(j(`${h.red} \u2716 Creation hard-block: ${y.fnName} denied \u2014 cap fired, files already written${h.reset}`),y.canExecute=!1,y.errorResult={role:"tool",content:"BLOCKED: files already written \u2014 continue with write_file or edit_file to finish the remaining tasks. Do not read more files.",tool_call_id:y.callId})}if(ds>=0){let w=we.filter(y=>y.canExecute).length;if(w>0&&(ds-=w,ds<0))if(!Xi&&x.size>Ki){Xi=!0,ds=5,j(`${h.green} \u2713 Post-wipe progress detected (${x.size-Ki} files modified) \u2014 granting 5 bonus tool calls${h.reset}`);let y={role:"user",content:"[SYSTEM] Progress detected \u2014 5 bonus tool calls granted. Budget: 5 remaining."};L.push(y),S.push(y)}else{j(`${h.red} \u2716 Post-wipe tool budget exhausted \u2014 blocking all tool calls${h.reset}`);for(let K of we)K.canExecute&&(K.canExecute=!1,K.errorResult={role:"tool",content:"BLOCKED: post-wipe tool budget exhausted. No further tool calls are allowed. Summarise what was accomplished and stop.",tool_call_id:K.callId});let y={role:"user",content:"[SYSTEM] Post-wipe tool budget exhausted. All tool calls are now blocked. Respond with a final summary of what was done and stop \u2014 do not attempt any more tool calls."};L.push(y),S.push(y)}}let Xy=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 w of we){if(!w.canExecute||Xy.has(w.fnName))continue;let y=JSON.stringify(w.args||{}),K=`${w.fnName}|${y}`,T=sn(Uc,K);T>=2?(j(`${h.red} \u2716 Blocked duplicate: ${w.fnName}(${y.substring(0,80)}) \u2014 called ${T+1}\xD7 with identical args${h.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:`BLOCKED: ${w.fnName}() with these exact arguments has already been called ${T}\xD7 \u2014 the result is already in your context. Use the existing output instead of repeating the same call.`,tool_call_id:w.callId}):T===1&&j(`${h.yellow} \u26A0 Duplicate tool call: ${w.fnName}(${y.substring(0,80)}) \u2014 2nd call with identical args${h.reset}`),us(Uc,K)}{let w=new Set;for(let y of we){if(!y.canExecute||!["edit_file","patch_file"].includes(y.fnName))continue;let K=y.args?.path;K&&(ke.has(K)||w.has(K)?(y.canExecute=!1,y.errorResult={role:"tool",content:`BLOCKED: "${K}" was already edited \u2014 re-read the changed section first (read_file with line_start/line_end) before making another edit. The file content has changed and your previous read is stale.`,tool_call_id:y.callId},j(`${h.yellow} \u26A0 Map-first gate: blocked re-edit of "${K.split("/").slice(-1)[0]}" \u2014 re-read required${h.reset}`)):w.add(K))}}let co=c?{skipSpinner:!0,skipSummaries:!0}:{},Vy=we.some(w=>w.fnName==="ask_user"),wu=!co.skipSummaries&&!ye,yr=null,_s=null;wu&&!Vy?(ye=!0,co.skipSpinner=!0,process.stdout.isTTY?(global._nexFooter&&(_s=Math.min(global._nexFooter._lastOutputRow+1,global._nexFooter._scrollEnd)),process.stdout.write(Ii(we,N,!1,"blink")),yr=!0):on||process.stdout.write(Ii(we,N,!1)+`
|
|
1395
|
-
`)):
|
|
1396
|
-
`):process.stdout.write(`\r\x1B[2K${
|
|
1397
|
-
`),
|
|
1398
|
-
`)[0],
|
|
1399
|
-
Do NOT re-read \u2014 apply the edit directly with edit_file.`};
|
|
1400
|
-
`).map(V=>V.trim()).find(V=>V.length>0&&!V.startsWith("**")&&(V.startsWith("EXIT")||/^[\w./-]+:\s/.test(V)||V.startsWith("bash:")||V.startsWith("sh:")))??"";if(F){if(F===
|
|
1401
|
-
`).map(V=>V.trim()).find(V=>V.length>0&&(V.startsWith("EXIT")||/^[\w./-]+:\s/.test(V)||V.startsWith("bash:")||V.startsWith("sh:")))??"";if(F){if(F===
|
|
1402
|
-
`);for(let
|
|
1403
|
-
`);for(let X of V)(X.startsWith("/")&&!X.includes(" ")||!X.includes(":")&&!X.startsWith("["))&&
|
|
1404
|
-
...(truncated ${
|
|
1405
|
-
`),
|
|
1406
|
-
${
|
|
1407
|
-
`),await t(a,i,u)}catch(
|
|
1408
|
-
`),await t(a,i,d)}catch(f){if(s=f,!fy(f))throw f}}continue}}throw n>0&&n===o?new Error("All providers are over budget. Use /budget to check limits or /budget <provider> off to remove a limit."):o===0?new Error("No configured provider available"):s||new Error("No configured provider available")}async function KT(t,e,s={}){Ft();let n=s.model,o=n?(()=>{let{model:i}=tu(n);return i||n})():void 0,r=o!==n?{...s,model:o}:s;return hy((i,a,l)=>i.stream(t,e,{model:l,signal:r.signal,...r}))}async function XT(t,e,s={}){if(Ft(),s.provider){let n=st[s.provider];if(!n||!n.isConfigured())throw new Error(`Provider '${s.provider}' is not available`);let o={model:s.model||Ue,...s};try{return await n.chat(t,e,o)}catch(r){if(typeof n.stream=="function")try{return await n.stream(t,e,{...o,onToken:()=>{}})}catch{}throw r}}return hy(async(n,o,r)=>{try{return await n.chat(t,e,{model:r,...s})}catch(i){if(typeof n.stream=="function")try{return await n.stream(t,e,{model:r,...s,onToken:()=>{}})}catch{}throw i}})}function VT(){Ft();let t=[];for(let[e,s]of Object.entries(st))s.isConfigured()&&t.push({name:e,models:Object.values(s.getModels())});return t}function JT(){for(let t of Object.keys(st))delete st[t];$t=null,Ue=null,dr=[]}my.exports={registerProvider:oo,getProvider:jT,getActiveProvider:eu,getActiveProviderName:qT,getActiveModelId:FT,getActiveModel:BT,setActiveModel:UT,getModelNames:WT,parseModelSpec:tu,listProviders:HT,listAllModels:YT,callStream:KT,callChat:XT,getConfiguredProviders:VT,setFallbackChain:GT,getFallbackChain:zT,resolveModelForProvider:Zc,MODEL_EQUIVALENTS:Qc,OLLAMA_FALLBACK_MODELS:Jc,_reset:JT}});var{C:G}=Ke(),ZT=Qe(),{TOOL_DEFINITIONS:gy}=As(),{saveRoutingConfig:QT}=ss(),ou=[{id:"read-package",category:"file-ops",prompt:"Read the file package.json and show me its contents.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("package.json")},{id:"write-file",category:"file-ops",prompt:'Create a file at /tmp/nex-bench-test.txt with the content "benchmark run".',expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&typeof t.content=="string"},{id:"edit-file",category:"file-ops",prompt:'In the file src/config.js, replace the string "debug: false" with "debug: true".',expectedTool:["edit_file","patch_file"],validateArgs:t=>!!(t.path&&t.old_string!==void 0&&t.new_string!==void 0||t.path&&Array.isArray(t.patches)&&t.patches.length>0)},{id:"list-directory",category:"file-ops",prompt:"Show me all files and folders in the cli/ directory.",expectedTool:["list_directory","glob"],validateArgs:t=>!!(typeof t.path=="string"&&t.path.includes("cli")||typeof t.pattern=="string"&&t.pattern.includes("cli"))},{id:"glob-js-files",category:"file-ops",prompt:"Find all JavaScript files (*.js) recursively in the cli/ directory.",expectedTool:"glob",validateArgs:t=>typeof t.pattern=="string"&&t.pattern.includes(".js")},{id:"read-partial",category:"file-ops",prompt:"Read only lines 20 to 40 of src/index.js \u2014 I need to see that specific range.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("index")&&(typeof t.line_start=="number"||typeof t.start_line=="number")},{id:"glob-ts-defs",category:"file-ops",prompt:"Find all TypeScript type definition files (*.d.ts) anywhere in the project.",expectedTool:"glob",validateArgs:t=>typeof t.pattern=="string"&&t.pattern.includes(".d.ts")},{id:"write-gitignore",category:"file-ops",prompt:"Create a .gitignore file at the project root that ignores node_modules/ and dist/.",expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes(".gitignore")&&typeof t.content=="string"&&t.content.includes("node_modules")},{id:"edit-version-bump",category:"file-ops",prompt:'In package.json, change the version field from "1.0.0" to "1.1.0".',expectedTool:["edit_file","patch_file"],validateArgs:t=>!!(t.path&&t.path.includes("package"))},{id:"grep-with-filter",category:"search",prompt:"Search for all calls to require() but only inside .js files in the cli/ directory.",expectedTool:["grep","search_files"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("require")},{id:"no-tool-http-port",category:"reasoning",prompt:"What is the default port used by the HTTP protocol?",expectedTool:null,validateArgs:()=>!0},{id:"bash-node-version",category:"shell",prompt:"Check which version of Node.js is currently installed on this system.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("node")&&(t.command.includes("--version")||t.command.includes("-v"))},{id:"search-constant",category:"search",prompt:'Search for the string "DEFAULT_MODEL" across all files in the project.',expectedTool:["search_files","grep"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("DEFAULT_MODEL")},{id:"grep-function-def",category:"search",prompt:'Find where the function "callStream" is defined in the codebase.',expectedTool:["grep","search_files"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("callStream")},{id:"search-todos",category:"search",prompt:"Find all TODO comments in the source code.",expectedTool:["grep","search_files","bash"],validateArgs:t=>JSON.stringify(t).toUpperCase().includes("TODO")},{id:"git-branch",category:"shell",prompt:"What git branch am I currently on?",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("git")},{id:"git-status",category:"shell",prompt:"Show me the current git status of the repository.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("git status")},{id:"npm-install",category:"shell",prompt:"Run npm install to install project dependencies.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("npm")},{id:"schema-strict",category:"schema",prompt:"Read the file README.md",expectedTool:"read_file",validateArgs:(t,e)=>{let s=e?.function?.parameters||{},n=s.required||[],o=Object.keys(s.properties||{});return n.every(r=>t[r]!==void 0)&&Object.keys(t).every(r=>o.includes(r))}},{id:"multi-step-version",category:"multi-step",prompt:"What is the current version of this project? Check the source files.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("package.json")},{id:"multi-step-count",category:"multi-step",prompt:"How many JavaScript files are in the cli/ directory? Count them.",expectedTool:["bash","glob","list_directory"],validateArgs:t=>!!(typeof t.command=="string"&&t.command.includes("cli")||typeof t.pattern=="string"&&t.pattern.includes("cli")||typeof t.path=="string"&&t.path.includes("cli"))},{id:"no-tool-reasoning",category:"reasoning",prompt:'What does the acronym "API" stand for?',expectedTool:null,validateArgs:()=>!0},{id:"frontend-find-hook",category:"frontend",prompt:"Find all files that import useState from React.",expectedTool:["grep","search_files"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("useState")},{id:"frontend-create-component",category:"frontend",prompt:"Create a React functional component called Button that accepts a label prop and renders a styled button element. Save it to src/components/Button.jsx.",expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&(t.path.includes(".jsx")||t.path.includes(".tsx")||t.path.includes(".js"))&&typeof t.content=="string"},{id:"frontend-edit-css",category:"frontend",prompt:'In the file src/styles.css, change the background-color value from "blue" to "red".',expectedTool:["edit_file","patch_file"],validateArgs:t=>t.path&&t.old_string!==void 0?t.path.includes(".css")||t.old_string.includes("blue")||t.old_string.includes("background"):!!(t.path&&Array.isArray(t.patches))},{id:"frontend-glob-components",category:"frontend",prompt:"Find all JSX and TSX component files in the components/ directory.",expectedTool:"glob",validateArgs:t=>typeof t.pattern=="string"&&(t.pattern.includes(".jsx")||t.pattern.includes(".tsx")||t.pattern.includes("{jsx,tsx}"))},{id:"frontend-list-assets",category:"frontend",prompt:"List all files in the src/assets/ directory.",expectedTool:["list_directory","glob"],validateArgs:t=>!!(typeof t.path=="string"&&t.path.includes("assets")||typeof t.pattern=="string"&&t.pattern.includes("assets"))},{id:"sysadmin-port-check",category:"sysadmin",prompt:"Which process is currently listening on port 3000?",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("lsof")||t.command.includes("ss")||t.command.includes("netstat")||t.command.includes("3000"))},{id:"sysadmin-nginx-config",category:"sysadmin",prompt:"Create an nginx server block that proxies requests to localhost:3000. Save it to /etc/nginx/sites-available/myapp.",expectedTool:["write_file","bash"],validateArgs:t=>!!(t.path&&(t.path.includes("nginx")||t.path.includes("sites-available"))||t.command&&t.command.includes("nginx"))},{id:"sysadmin-service-status",category:"sysadmin",prompt:"Check the status of the nginx service and show if it is running.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("systemctl")||t.command.includes("service")||t.command.includes("nginx"))},{id:"sysadmin-error-log",category:"sysadmin",prompt:"Show the last 100 lines of the nginx error log.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("tail")||t.command.includes("journalctl")||t.command.includes("nginx"))},{id:"sysadmin-docker-compose",category:"sysadmin",prompt:"Create a docker-compose.yml file for a Node.js application with a PostgreSQL database.",expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("docker-compose")&&typeof t.content=="string"},{id:"data-sql-query",category:"data",prompt:"Write a SQL query to find all users who have not logged in for more than 30 days. Save it to queries/inactive-users.sql.",expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&(t.path.includes(".sql")||t.path.includes("quer"))&&typeof t.content=="string"},{id:"data-find-json-key",category:"data",prompt:'Find all JSON files in the project that contain the key "userId".',expectedTool:["grep","search_files"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("userId")},{id:"data-python-csv",category:"data",prompt:'Write a Python script that reads data.csv and calculates the average of the "price" column. Save it to scripts/average_price.py.',expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes(".py")&&typeof t.content=="string"},{id:"data-find-migrations",category:"data",prompt:"Find all database migration files in this project.",expectedTool:["glob","search_files","grep"],validateArgs:t=>JSON.stringify(t).toLowerCase().includes("migrat")},{id:"data-find-schema",category:"data",prompt:"Find where the database schema or models are defined in this project.",expectedTool:["grep","glob"],validateArgs:t=>!!(t.pattern&&/schema|model|migration/i.test(t.pattern)||t.pattern&&/schema|model|migration/i.test(t.pattern))},{id:"data-write-query",category:"data",prompt:"Write a SQL query to find all users who registered in the last 30 days and save it to queries/recent-users.sql.",expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes(".sql")},{id:"data-read-env",category:"data",prompt:"Read the .env file to find the database connection string.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&/\.env|env\./i.test(t.path)},{id:"resilience-edit-failed",category:"resilience",prompt:"Your edit_file call on server.js failed: old_string 'const PORT = 3000' was not found in the file. What do you do next to recover?",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("server")},{id:"resilience-file-not-found",category:"resilience",prompt:"read_file returned 'file not found' for src/utils/helpers.js. You need to find where the helper functions are now. What tool do you use?",expectedTool:["glob_files","bash"],validateArgs:t=>{let e=JSON.stringify(t).toLowerCase();return e.includes("src")||e.includes("helper")||e.includes("util")||e.includes("*.js")}},{id:"resilience-large-file-nav",category:"resilience",prompt:"The file src/api.js is 2800 lines. You need to locate the authenticateUser function. What is the most efficient tool to use \u2014 read_file or bash with grep?",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("grep")||t.command.includes("rg")||t.command.includes("awk"))},{id:"resilience-broken-import",category:"resilience",prompt:"TypeScript reports: Cannot find module './config'. The file was recently renamed. What tool do you use to find the new location?",expectedTool:["glob_files","bash"],validateArgs:t=>{let e=JSON.stringify(t).toLowerCase();return e.includes("config")||e.includes("*.ts")||e.includes("*.js")||e.includes("find")}},{id:"resilience-bash-error-recover",category:"resilience",prompt:"The command 'npm test' failed with exit code 1. The output contains 'SyntaxError: Unexpected token' in src/parser.js:45. What is your next action?",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("parser")},{id:"resilience-grep-no-match",category:"resilience",prompt:"grep returned zero matches for 'getUserById' in src/. The function exists but may have been renamed. What bash command finds all exported function names in src/ to identify the current name?",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("grep")||t.command.includes("rg")||t.command.includes("src"))},{id:"ssh-exec-log",category:"ssh",prompt:'Show the last 50 lines of /var/log/nginx/error.log on server "prod-1".',expectedTool:"ssh_exec",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("tail")||t.command.includes("log"))&&(typeof t.host=="string"||typeof t.profile=="string")},{id:"ssh-exec-service",category:"ssh",prompt:'Restart the nginx service on server "prod-1".',expectedTool:"ssh_exec",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("nginx")||t.command.includes("systemctl")||t.command.includes("restart"))&&(typeof t.host=="string"||typeof t.profile=="string")},{id:"ssh-exec-port",category:"ssh",prompt:'Check if port 8080 is listening on server "prod-1".',expectedTool:"ssh_exec",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("8080")||t.command.includes("ss")||t.command.includes("netstat")||t.command.includes("lsof"))&&(typeof t.host=="string"||typeof t.profile=="string")},{id:"ssh-exec-processes",category:"ssh",prompt:'Show the top CPU-consuming processes on server "prod-1".',expectedTool:"ssh_exec",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("top")||t.command.includes("ps")||t.command.includes("htop"))&&(typeof t.host=="string"||typeof t.profile=="string")},{id:"git-diff-staged",category:"git",prompt:"Show all staged changes before committing.",expectedTool:["git_diff","bash"],validateArgs:t=>!!(t.staged===!0||t.staged==="true"||typeof t.command=="string"&&t.command.includes("diff"))},{id:"git-log-recent",category:"git",prompt:"Show the last 5 commit messages with their hashes.",expectedTool:["git_log","bash"],validateArgs:t=>!!(typeof t.limit=="number"||typeof t.n=="number"||typeof t.command=="string"&&t.command.includes("log"))},{id:"git-status-check",category:"git",prompt:"Check if there are any uncommitted changes in the repository.",expectedTool:["git_status","bash"],validateArgs:t=>t.path===void 0&&t.command===void 0?!1:(typeof t.command=="string"&&t.command.includes("status"),!0)},{id:"agentic-test-first",category:"agentic",prompt:"Run the full test suite. If any tests fail, identify the failing test file and read it to understand the issue.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("test")||t.command.includes("jest")||t.command.includes("npm"))},{id:"agentic-read-then-act",category:"agentic",prompt:"Read the project README.md, find the TODO section, and list which items are completed.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("README")},{id:"agentic-build-deploy",category:"agentic",prompt:"Build the project with npm run build, then verify the output exists in the dist/ directory.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("build")||t.command.includes("npm"))},{id:"agentic-spawn-parallel",category:"agentic",prompt:"Search for all TODO comments and all FIXME comments across the codebase in parallel using multiple agents.",expectedTool:"spawn_agents",validateArgs:t=>Array.isArray(t.agents)&&t.agents.length>=2},{id:"agentic-multi-investigate",category:"agentic",prompt:"The app is crashing on startup. Spawn parallel agents to check: (1) recent git changes, (2) npm dependency issues, (3) the main entry file for syntax errors.",expectedTool:"spawn_agents",validateArgs:t=>Array.isArray(t.agents)&&t.agents.length>=2}],yy=[{id:"phase-plan-diagnosis",category:"phase-plan",prompt:"The server returns 500 on /api/users. The error log shows: TypeError: Cannot read property 'map' of undefined at routes/users.js:42. Read the relevant file to diagnose the root cause.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&/users/i.test(t.path)},{id:"phase-plan-search",category:"phase-plan",prompt:"We're getting CORS errors in production. Search the codebase for where CORS middleware is configured.",expectedTool:"grep",validateArgs:t=>typeof t.pattern=="string"&&/cors/i.test(t.pattern)},{id:"phase-plan-context",category:"phase-plan",prompt:"The login page shows a blank screen after the last deploy. Check git log for recent changes that might have broken it.",expectedTool:"git_log",validateArgs:()=>!0},{id:"phase-verify-test",category:"phase-verify",prompt:"The file src/utils.js was modified to fix a null pointer bug. Run the test suite to verify the fix works correctly.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&/test|jest|npm\s+test|pytest|mocha/.test(t.command)},{id:"phase-verify-read",category:"phase-verify",prompt:"A patch was applied to config/database.js to fix the connection pool. Read the file to verify the changes look correct.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&/database/i.test(t.path)},{id:"phase-verify-lint",category:"phase-verify",prompt:"Code was modified in src/components/Header.tsx. Run the linter to check for any style violations.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&/lint|eslint|prettier|tsc/.test(t.command)},{id:"phase-plan-git-blame",category:"phase-plan",prompt:"A production bug was introduced 2 days ago. Use git log to find commits from the last 2 days to identify what changed.",expectedTool:"git_log",validateArgs:()=>!0},{id:"phase-plan-error-trace",category:"phase-plan",prompt:"The error stack trace mentions src/middleware/auth.js line 87. Read the file around that line to understand the bug.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&/auth/i.test(t.path)},{id:"phase-plan-grep-config",category:"phase-plan",prompt:"Users report the app is using wrong API keys in staging. Search for where API_KEY is loaded from environment.",expectedTool:"grep",validateArgs:t=>typeof t.pattern=="string"&&/api.?key|env/i.test(t.pattern)},{id:"phase-verify-build",category:"phase-verify",prompt:"The TypeScript source was modified. Run the build command to verify there are no compilation errors.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&/build|tsc|compile/.test(t.command)},{id:"phase-verify-git-diff",category:"phase-verify",prompt:"Changes were just committed. Show the git diff of the last commit to verify only the intended files were modified.",expectedTool:["git_diff","bash"],validateArgs:t=>(t.command&&/git.*diff|diff.*HEAD/.test(t.command),!0)},{id:"phase-verify-read-config",category:"phase-verify",prompt:"The deployment config was updated. Read config/production.json to verify the changes are correct before deploying.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&/config|production|deploy/i.test(t.path)}],ra=[...ou,...yy],nu=["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 eR(){try{let s=require("path").join(require("os").homedir(),".nex-code","benchmark-results.json");if(!require("fs").existsSync(s))return nu;let n=JSON.parse(require("fs").readFileSync(s,"utf-8"));return!Array.isArray(n)||n.length===0?nu:n.filter(o=>typeof o.score=="number"&&o.score>=60).sort((o,r)=>r.score-o.score).slice(0,12).map(o=>o.model)}catch{return nu}}var ru=eR(),tR=["minimax-m2.7:cloud","qwen3-coder:480b","devstral-2:123b"],wy=(()=>{let t=ru.slice(0,3);return t.length>=3?t:tR})(),nR=14,sa={producedToolCall:.2,correctTool:.35,validArgs:.3,schemaCompliant:.15},sR="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 su(t,e){let s={taskId:t.id,category:t.category,model:e,producedToolCall:!1,correctTool:!1,validArgs:!1,schemaCompliant:!1,toolCalled:null,error:null,latencyMs:0},n=[{role:"system",content:sR},{role:"user",content:t.prompt}],o=Date.now();try{let r=await ZT.callChat(n,gy,{provider:"ollama",model:e,temperature:0,timeout:9e4});s.latencyMs=Date.now()-o;let i=r.tool_calls||[];if(t.expectedTool===null){let a=i.length===0;s.producedToolCall=a,s.correctTool=a,s.validArgs=!0,s.schemaCompliant=!0}else if(i.length>0){let a=i[0],l=a.function?.name||"unknown",c=a.function?.arguments||{};s.producedToolCall=!0,s.toolCalled=l;let u=Array.isArray(t.expectedTool)?t.expectedTool:[t.expectedTool];if(s.correctTool=u.includes(l),s.correctTool){let d=gy.find(f=>f.function?.name===l);if(s.validArgs=!!t.validateArgs(c,d),d){let f=d.function?.parameters||{},p=f.required||[],m=Object.keys(f.properties||{});s.schemaCompliant=p.every(g=>c[g]!==void 0)&&Object.keys(c).every(g=>m.includes(g))}}}}catch(r){s.latencyMs=Date.now()-o,s.error=r.message.slice(0,120)}return s}function ro(t){return t.error?0:((t.producedToolCall?sa.producedToolCall:0)+(t.correctTool?sa.correctTool:0)+(t.validArgs?sa.validArgs:0)+(t.schemaCompliant?sa.schemaCompliant:0))*100}var _y={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 iu(t){return Object.entries(t).map(([e,s])=>{let n=s.map(ro),o=n.reduce((a,l)=>a+l,0)/n.length,r=a=>Math.round(s.filter(a).length/s.length*100),i={};for(let a of["coding","frontend","sysadmin","data","agentic","plan","verify"]){let l=s.filter(u=>_y[u.category]===a);if(l.length===0)continue;let c=l.map(ro).reduce((u,d)=>u+d,0)/l.length;i[a]=Math.round(c*10)/10}return{model:e,score:Math.round(o*10)/10,toolCallRate:r(a=>!a.error&&(a.producedToolCall||a.category==="reasoning")),correctRate:r(a=>a.correctTool),validArgsRate:r(a=>a.validArgs),schemaRate:r(a=>a.schemaCompliant),avgLatency:Math.round(s.reduce((a,l)=>a+l.latencyMs,0)/s.length),errorCount:s.filter(a=>a.error).length,categoryScores:i,results:s}}).sort((e,s)=>s.score-e.score)}function $y(t){let e={};for(let a of["coding","frontend","sysadmin","data","agentic","plan","verify"]){let l=t.filter(g=>g.categoryScores[a]!==void 0&&g.score>=65).sort((g,_)=>_.categoryScores[a]-g.categoryScores[a]);if(l.length===0)continue;let u=(l[0]?.results||[]).filter(g=>_y[g.category]===a).length;if(u<4)continue;let d=l[0],f=l[1];if(d.categoryScores[a]>=95&&u<8&&f&&d.categoryScores[a]-f.categoryScores[a]<15){let _=t.filter(b=>b.categoryScores[a]!==void 0).find(b=>b.categoryScores[a]<95);_&&(e[a]={model:_.model,score:_.categoryScores[a],avgLatency:_.avgLatency,_flukePrevented:!0});continue}let m=l.filter(g=>d.categoryScores[a]-g.categoryScores[a]<=5).sort((g,_)=>g.avgLatency-_.avgLatency)[0];e[a]={model:m.model,score:m.categoryScores[a],avgLatency:m.avgLatency}}return e}function by(t,e){let s=`nex-code Model Benchmark (${e} tasks \xB7 ollama cloud)`,n=[{label:"#",width:3},{label:"Model",width:26},{label:"Score",width:7},{label:"Tool\u2713",width:7},{label:"Name\u2713",width:7},{label:"Args\u2713",width:7},{label:"Schema\u2713",width:8},{label:"Latency",width:8},{label:"Err",width:4}],o=n.reduce((u,d)=>u+d.width+1,0)+1,r="\u2500".repeat(o);console.log(`
|
|
1409
|
-
${
|
|
1410
|
-
${
|
|
1411
|
-
${
|
|
1412
|
-
${
|
|
1413
|
-
${
|
|
1433
|
+
${getPlanContent()||Nt.content}`;P.push({role:"user",content:X}),S.push({role:"user",content:X}),Q=!0}}else console.log(`
|
|
1434
|
+
${m.cyan}${m.bold}Plan ready.${m.reset} ${m.dim}Type ${m.reset}${m.cyan}/plan approve${m.reset}${m.dim} to execute, or ask follow-up questions to refine.${m.reset}`);if(Q){l&&(l.stop(),l=null),We--;continue}}}if(l&&(l.stop(),l=null),c(null),Me(M,L,b,Z,Ne),Bt&&b.size>=3){let T=[...b].map(R=>R.split("/").pop()).slice(0,8).join(", "),N=[...b].some(R=>R.endsWith("package.json")),Q=[...b].some(R=>R.endsWith("requirements.txt")),B=[...b].some(R=>R.endsWith("package-lock.json")||R.endsWith("yarn.lock")||R.endsWith("pnpm-lock.yaml")),re=N&&!B?"npm install not yet run":Q?"pip install not yet run":null;lr=`[Previous session created ${b.size} files: ${T}`+(re?` \u2014 ${re}`:"")+". Use this context to answer follow-up questions without re-reading files.]"}if(Bt&&!ru&&M>0){let T=[...b].some(X=>X.endsWith("package.json")),N=[...b].some(X=>X.endsWith("requirements.txt")||X.endsWith("Pipfile")||X.endsWith("pyproject.toml")),Q=[...b].some(X=>X.endsWith("package-lock.json")||X.endsWith("yarn.lock")||X.endsWith("pnpm-lock.yaml")),B=P.flatMap(X=>{let ie=Array.isArray(X.tool_calls)?X.tool_calls:[],me=Array.isArray(X.content)?X.content.filter(ee=>ee?.type==="tool_use"):[];return[...ie,...me]}).filter(X=>{let ie=X.function?.name||X.name||"";return ie==="bash"||ie==="Bash"}).map(X=>{try{let ie=X.function?.arguments??X.input??{};return(typeof ie=="string"?JSON.parse(ie):ie)?.command||""}catch{return""}}),re=B.some(X=>/pip\s+install|python\s+-m\s+venv/.test(X)),R=B.some(X=>/npm\s+install/.test(X)),F=[...b].some(X=>/\/App\.(js|ts|jsx|tsx)$/.test(X))&&!T&&!R;if(N&&!re||T&&!Q&&!R||F){ru=!0;let X=[];N&&!re&&X.push("python -m venv venv && source venv/bin/activate && pip install -r requirements.txt"),F?X.push("create package.json for the React frontend (with react, react-dom, react-scripts dependencies), then run npm install"):T&&!Q&&!R&&X.push("npm install");let ie=`[FRAMEWORK \u2014 post-creation check] You wrote dependency files but never ran the installer. Run now: ${X.join(" && ")}. Verify it succeeds, fix any errors, then write a closing summary.`;D(`${m.dim} [post-creation] bootstrapping environment (${X.join(", ")})${m.reset}`),P.push({role:"user",content:ie}),S.push({role:"user",content:ie});continue}}if(M>0&&!s._isSummaryTurn&&hT(Pt))try{D(`${m.dim} [post-turn] terse ending \u2014 requesting diagnosis/summary${m.reset}`);let T=b.size>0?"Write a closing summary (3+ sentences): what files changed and why, what the result is, anything the user should know or do next.":"Write a closing diagnosis (3+ sentences): what you investigated, what you found, and what the user should do next or what the root cause is.",N=[...S,{role:"user",content:T}],B=((await dy(N,[],{}))?.content||"").trim();B&&(console.log(`
|
|
1435
|
+
${B}`),P.push({role:"user",content:T},{role:"assistant",content:B}))}catch{}Oe(P),Gi(P),await vu();return}M++,ua++,M>=1&&(we=!1);for(let $ of pn){let y=$.function.name;L.set(y,(L.get(y)||0)+1)}if(M>=30&&!ky){ky=!0,D(`${m.yellow} \u26A0 Tool budget warning: ${M} tool calls used \u2014 nudging model to wrap up${m.reset}`);let $={role:"user",content:"[SYSTEM] \u26A0 You have used "+M+" 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."};P.push($),S.push($)}let $e=await Promise.all(pn.map($=>cR($)));{let $=Jt(S,dt()),y=$.percentage,z=$e.some(B=>B.canExecute&&B.fnName==="read_file"&&!B.args?.line_end),T=$e.filter(B=>B.canExecute&&B.fnName==="read_file"&&B.args?.path&&ln(xs,B.args.path)>=1&&!B.args?.line_start).map(B=>B.args.path.split("/").slice(-2).join("/")),N=T.length>0;if(y>=70&&z&&ga<70||y>=85&&ga<85||N){ga=y;let B=y>=85?"URGENT":"WARNING",re;N?(B="WARNING",re=`Full-file read of ${T.join(", ")} already done \u2014 use line_start/line_end for specific sections instead.`):z?re=`Unbounded read at ${Math.round(y)}% context \u2014 use line_start/line_end to avoid overflow.`:re="Use targeted reads (line_start/line_end) to save space.";let R={role:"user",content:`[SYSTEM ${B}] Context ${Math.round(y)}% used (${$.used}/${$.limit} tokens). ${re}`};if(P.push(R),S.push(R),y>=85){let q=N?` (re-read of: ${T.join(", ")})`:"";D(`${m.yellow} \u26A0 Context ${Math.round(y)}% used \u2014 agent warned to use targeted reads${q}${m.reset}`)}}}let xa=new Map;for(let $ of $e){if(!$.canExecute||$.fnName!=="read_file")continue;let y=$.args?.path;if(!y)continue;let z=ln(xs,y),T=xa.get(y)||0,N=z+T,Q=$.args?.line_start!=null,B=qt.get(y)||0,re=B>0,R=2;if(N>=ks){let q=y.split("/").slice(-2).join("/"),F=(bs.get(y)||0)+1;if(bs.set(y,F),F===1)D(`${m.red} \u2716 Blocked: "${q}" read ${N}\xD7 \u2014 hard cap (${ks}) reached${m.reset}`);else if(F===2){D(`${m.red} \u2716 Escalated block: "${q}" \u2014 model ignored BLOCKED, injecting system warning${m.reset}`);let V={role:"user",content:`[SYSTEM WARNING] You already received a BLOCKED error for read_file("${y}") and tried again anyway. This file has reached its read cap (${ks}\xD7). Do NOT attempt to read it again. Use grep_search to find specific content, or proceed with what you already know.`};P.push(V),S.push(V)}$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 file already read ${N}\xD7 (hard cap: ${ks}). You have seen enough of this file. Use grep to find specific content or proceed with what you know.`,tool_call_id:$.callId}}else if(N>=1&&Q)if(re&&B<=R){let q=y.split("/").slice(-2).join("/");console.log(`${m.cyan} \u21A9 Targeted re-read: "${q}" (line_start=${$.args.line_start}) \u2014 edit recovery #${B}${m.reset}`),qt.set(y,B-1)}else if(re&&B>R){let q=y.split("/").slice(-2).join("/");D(`${m.red} \u2716 Edit recovery blocked: "${q}" \u2014 ${R} recovery reads already used. Use grep to find the exact line numbers, then retry.${m.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 edit recovery budget exhausted (${R} recovery reads used). You already have the file content. Use grep_search to find the exact line numbers of the text you want to change, then retry edit_file with the exact text shown.`,tool_call_id:$.callId}}else{let q=parseInt($.args.line_start,10)||1,F=parseInt($.args.line_end,10)||q+350,V=In.get(y)||[],X=!1;for(let[ie,me]of V){let ee=Math.max(q,ie),_e=Math.min(F,me);if(_e>ee){let Re=_e-ee,$t=F-q||1,tt=me-ie||1,Lt=Re/tt>=.7&&Re/$t<.7,nt=F-q<=w0;if(Re>=$t||!nt&&(Re/$t>=.7||Re/tt>=.7)){let Sa=y.split("/").slice(-2).join("/"),Lu=`${y}:${q}-${F}`,vs=(la.get(Lu)||0)+1;if(la.set(Lu,vs),D(Lt?`${m.red} \u2716 Blocked superread: "${Sa}" lines ${q}-${F} subsumes already-read ${ie}-${me} \u2014 use line_start=${me+1} to skip known content (block #${vs})${m.reset}`:`${m.red} \u2716 Blocked duplicate read: "${Sa}" lines ${q}-${F} (\u226570% overlap with lines ${ie}-${me} already in context, block #${vs})${m.reset}`),vs>=2){D(`${m.red} \u2716 Escalated range-block: "${Sa}" lines ${q}-${F} \u2014 model ignored BLOCKED, injecting system warning${m.reset}`);let Iu={role:"user",content:Lt?`[SYSTEM] Read blocked ${vs}\xD7 for read_file("${y}", lines ${q}-${F}). Lines ${ie}-${me} were already read. Use line_start=${me+1} to read only new content, or use grep_search for specific lines.`:`[SYSTEM] Read blocked ${vs}\xD7 for read_file("${y}", lines ${q}-${F}). Lines ${ie}-${me} were already read and will NOT change. Use grep_search to find specific content instead.`};P.push(Iu),S.push(Iu)}$.canExecute=!1,$.errorResult={role:"tool",content:Lt?`BLOCKED: read_file("${y}", lines ${q}-${F}) re-reads lines ${ie}-${me} already in context. Use line_start=${me+1} to read only the new content beyond line ${me}.`:`BLOCKED: read_file("${y}", lines ${q}-${F}) is a duplicate \u2014 lines ${ie}-${me} are already in your context (\u226570% overlap). Use grep to find specific content instead of re-reading.`,tool_call_id:$.callId},X=!0;break}}}if(!X){let ie=V.length,me=2;if(ie>=3){let _e=y.split("/").slice(-2).join("/");D(`${m.red} \u2716 Blocked file-scroll: "${_e}" \u2014 ${ie} sections already read. Use grep to find specific content.${m.reset}`);let Re=ln(ma,y)>=$r;$.canExecute=!1,$.errorResult={role:"tool",content:Re?`BLOCKED: read_file("${y}") denied \u2014 you have already read ${ie} different sections of this file (file-scroll pattern). Grep is also exhausted. The content you need is already in your context \u2014 work with what you have.`:`BLOCKED: read_file("${y}") denied \u2014 you have already read ${ie} different sections of this file (file-scroll pattern). You have seen most of this file. Use grep_search to find the exact lines you need instead of continuing to scroll.`,tool_call_id:$.callId}}else ie>=me&&($._scrollWarn={sectionCount:ie+1,path:y})}}else if(N>=1){let q=qt.get(y)||0;if(q>0){let F=y.split("/").slice(-2).join("/");console.log(`${m.cyan} \u21A9 Full re-read: "${F}" \u2014 test-failure recovery (${q} remaining)${m.reset}`);let V=q-1;V<=0?qt.delete(y):qt.set(y,V)}else{let F=y.split("/").slice(-2).join("/"),V=(bs.get(y)||0)+1;if(bs.set(y,V),V===1)D(`${m.red} \u2716 Blocked unbounded re-read: "${F}" \u2014 already in context. Use line_start/line_end for specific sections.${m.reset}`);else if(V===2){D(`${m.red} \u2716 Escalated block: "${F}" \u2014 model ignored unbounded re-read block, injecting system warning${m.reset}`);let X={role:"user",content:`[SYSTEM] read_file("${y}") was blocked again \u2014 full-file reads are disabled after the first read. Use line_start/line_end for a specific section, or use grep_search to find what you need.`};P.push(X),S.push(X)}$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 file already in context (read ${N}\xD7). Use line_start/line_end to read a specific section instead of the full file.`,tool_call_id:$.callId}}}$.canExecute&&xa.set(y,(xa.get(y)||0)+1)}if(Ln>=3)for(let $ of $e)$.canExecute&&($.fnName!=="read_file"&&$.fnName!=="edit_file"||(D(`${m.red} \u2716 Blocked ${$.fnName} \u2014 ${Ln} consecutive file-not-found errors, must search first${m.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: ${Ln} consecutive "File not found" errors. You must call search_files or glob_files to locate the correct path before reading or editing. Do not guess file paths.`,tool_call_id:$.callId}));for(let $ of $e){if(!$.canExecute||$.fnName!=="bash")continue;let y=($.args?.command||"").trim();if(/^\s*ls(\s+-[a-zA-Z]+)*(\s+\S+)?\s*$/.test(y)&&!/npm|yarn|pnpm|make|git/.test(y)){D(`${m.red} \u2716 Blocked bash ls \u2014 use list_directory tool instead${m.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:'BLOCKED: bash("ls ...") denied \u2014 use the list_directory tool instead. It returns structured output and does not penalize the session score.',tool_call_id:$.callId};continue}/\bfind\s+[\S.]/.test(y)&&!/git\s|npm\s|yarn\s|-exec\s+\S|-execdir/.test(y)&&(D(`${m.red} \u2716 Blocked bash find \u2014 use glob tool with a pattern instead${m.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:'BLOCKED: bash("find ...") denied \u2014 use the glob tool with a pattern like "**/*.py" or "src/**/*.js" instead. It is faster and does not penalize the session score.',tool_call_id:$.callId})}for(let $ of $e)$.canExecute&&($.fnName!=="ssh_exec"&&$.fnName!=="bash"||/\bsed\s+-n\b/.test($.args?.command||"")&&(D(`${m.red} \u2716 Blocked sed -n: use grep -n "pattern" <file> | head -30 instead${m.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:'BLOCKED: sed -n is forbidden \u2014 it floods context with line ranges. Use grep -n "pattern" <file> | head -30 to read a specific section, or cat <file> for the full file.',tool_call_id:$.callId}));for(let $ of $e){if(!$.canExecute||$.fnName!=="write_file")continue;let y=$.args?.path,z=$.args?.content||"";if(y)try{let T=require("fs"),N=require("path").resolve(process.cwd(),y);if(T.existsSync(N)){let Q=T.statSync(N).size,B=Buffer.byteLength(z,"utf8"),re=Q>0?B/Q:1;if(re<.6&&Q>200){let R=y.split("/").slice(-2).join("/");console.log(`${m.red} \u2716 write_file shrink guard: "${R}" would shrink to ${Math.round(re*100)}% of original \u2014 likely context loss${m.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: write_file("${y}") denied \u2014 new content is only ${Math.round(re*100)}% of current file size (${Q} \u2192 ${B} bytes). This looks like a partial rewrite after context loss. Use edit_file/patch_file to add only the new code, or read the file first to see full content before replacing.`,tool_call_id:$.callId}}}}catch{}}let Ou=new Map;for(let $ of $e){if(!$.canExecute||$.fnName!=="grep")continue;let y=$.args?.path;if(!y)continue;let z=Ou.get(y)||0,T=ln(ma,y)+z,N=ln(xs,y)>=1,Q=N?Math.min(3,$r):$r;if(T>=Q){let B=y.split("/").slice(-2).join("/");D(`${m.red} \u2716 Blocked grep: "${B}" grepped ${T}\xD7 with different patterns \u2014 flood threshold exceeded${m.reset}`);let re=ln(xs,y),R=re>=ks;if(R){let q={role:"user",content:`[SYSTEM] Both read_file and grep are now blocked for "${y}". You have already read ${re} sections and tried ${T} 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.`};P.push(q),S.push(q),D(`${m.red} \u2716 Deadlock detected: "${B}" \u2014 both read and grep blocked, injecting deadlock-break${m.reset}`)}$.canExecute=!1,$.errorResult={role:"tool",content:R?`BLOCKED: grep("${y}") denied \u2014 ${T} 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.`:N?`BLOCKED: grep("${y}") denied \u2014 file was already read and ${T} grep patterns tried. The content is already in your context; use it instead of searching again.`:`BLOCKED: grep("${y}") denied \u2014 ${T} patterns already tried. Work with the grep results already in your context.`,tool_call_id:$.callId}}$.canExecute&&Ou.set(y,z+1)}let S0=5,Nu=new Map;for(let $ of $e){if(!$.canExecute||$.fnName!=="ssh_exec")continue;let z=($.args?.command||"").replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),T=Nu.get(z)||0,N=ln(xu,z)+T;N>=S0&&(D(`${m.yellow} \u26A0 Blocked ssh_exec: same command run ${N}\xD7 \u2014 result already in context${m.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: ssh_exec denied \u2014 this command has already run ${N} times and the output is in your context. Use existing results, try a different command, or run it as a local bash call: bash("ssh user@host 'your command'").`,tool_call_id:$.callId}),$.canExecute&&Nu.set(z,T+1)}if(Ot){let $=$e.filter(T=>T.canExecute&&T.fnName==="ssh_exec"),y=$e.some(T=>T.canExecute&&T.fnName!=="ssh_exec"),z=j&&H<3;if($.length>0&&!y&&z&&na<1)Ot=!1,na++,Ft=Math.max(0,uo-2),D(`${m.dim} [dual-block deadlock: SSH storm relaxed \u2014 allowing 1 SSH call (relax ${na}/1)]${m.reset}`);else for(let T of $)T.canExecute=!1,T.errorResult={role:"tool",content:it?`BLOCKED: ssh_exec denied \u2014 SSH paused (${uo}+ calls). Root cause is known (${xt}). 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 (${uo}+ 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:T.callId}}if(j&&H<3&&!Ot){for(let $ of $e)if($.canExecute&&["bash","read_file","find_files"].includes($.fnName)){H++;{let y=dt(),{messages:z}=cn(S,y);S=z}D(`${m.yellow} \u26A0 Server-local guard: blocking local ${$.fnName} \u2014 use ssh_exec on 94.130.37.43${m.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: ${$.fnName} denied \u2014 this is a server issue. Use ssh_exec on 94.130.37.43 instead.`,tool_call_id:$.callId};break}}if(!be&&Wt&&Bt&&Qt>=1){let $=["read_file","grep","search_files","glob","list_directory","find_files"];for(let y of $e)y.canExecute&&$.includes(y.fnName)&&(D(`${m.red} \u2716 Creation hard-block: ${y.fnName} denied \u2014 cap fired, files already written${m.reset}`),y.canExecute=!1,y.errorResult={role:"tool",content:"BLOCKED: files already written \u2014 continue with write_file or edit_file to finish the remaining tasks. Do not read more files.",tool_call_id:y.callId})}if(ys>=0){let $=$e.filter(y=>y.canExecute).length;if($>0&&(ys-=$,ys<0))if(!oa&&b.size>sa){oa=!0,ys=5,D(`${m.green} \u2713 Post-wipe progress detected (${b.size-sa} files modified) \u2014 granting 5 bonus tool calls${m.reset}`);let y={role:"user",content:"[SYSTEM] Progress detected \u2014 5 bonus tool calls granted. Budget: 5 remaining."};P.push(y),S.push(y)}else{D(`${m.red} \u2716 Post-wipe tool budget exhausted \u2014 blocking all tool calls${m.reset}`);for(let z of $e)z.canExecute&&(z.canExecute=!1,z.errorResult={role:"tool",content:"BLOCKED: post-wipe tool budget exhausted. No further tool calls are allowed. Summarise what was accomplished and stop.",tool_call_id:z.callId});let y={role:"user",content:"[SYSTEM] Post-wipe tool budget exhausted. All tool calls are now blocked. Respond with a final summary of what was done and stop \u2014 do not attempt any more tool calls."};P.push(y),S.push(y)}}let v0=new Set(["edit_file","write_file","bash","ssh_exec","ask_user","spawn_agents","browser_click","browser_fill","browser_open","skill_ar_run_experiment","skill_ar_run_benchmark","skill_ar_checkpoint","skill_ar_revert","skill_ar_log_experiment","skill_ar_extract_metric"]);for(let $ of $e){if(!$.canExecute||v0.has($.fnName))continue;let y=JSON.stringify($.args||{}),z=`${$.fnName}|${y}`,T=ln(nu,z);T>=2?(D(`${m.red} \u2716 Blocked duplicate: ${$.fnName}(${y.substring(0,80)}) \u2014 called ${T+1}\xD7 with identical args${m.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: ${$.fnName}() with these exact arguments has already been called ${T}\xD7 \u2014 the result is already in your context. Use the existing output instead of repeating the same call.`,tool_call_id:$.callId}):T===1&&D(`${m.yellow} \u26A0 Duplicate tool call: ${$.fnName}(${y.substring(0,80)}) \u2014 2nd call with identical args${m.reset}`),gs(nu,z)}{let $=new Set;for(let y of $e){if(!y.canExecute||!["edit_file","patch_file"].includes(y.fnName))continue;let z=y.args?.path;z&&(fe.has(z)||$.has(z)?(y.canExecute=!1,y.errorResult={role:"tool",content:`BLOCKED: "${z}" was already edited \u2014 re-read the changed section first (read_file with line_start/line_end) before making another edit. The file content has changed and your previous read is stale.`,tool_call_id:y.callId},D(`${m.yellow} \u26A0 Map-first gate: blocked re-edit of "${z.split("/").slice(-1)[0]}" \u2014 re-read required${m.reset}`)):$.add(z))}}let po=l?{skipSpinner:!0,skipSummaries:!0}:{},E0=$e.some($=>$.fnName==="ask_user"),Mu=!po.skipSummaries&&!we,Sr=null,Ss=null;Mu&&!E0?(we=!0,po.skipSpinner=!0,process.stdout.isTTY?(global._nexFooter&&(Ss=Math.min(global._nexFooter._lastOutputRow+1,global._nexFooter._scrollEnd)),process.stdout.write(Yi($e,M,!1,"blink")),Sr=!0):dn||process.stdout.write(Yi($e,M,!1)+`
|
|
1436
|
+
`)):Mu&&(we=!0,po.skipSpinner=!0),l&&l._paused&&l.resume();let vr=null;if(Sr&&process.stdout.isTTY&&$e.some(y=>y.canExecute&&(y.fnName==="bash"||y.fnName==="ssh_exec"))){let y=Date.now();vr=setInterval(()=>{let z=Math.round((Date.now()-y)/1e3);if(z>=3){let T=`${Yi($e,M,!1,"blink")} ${m.dim}[${z}s]${m.reset}`;Ss!==null?process.stdout.write(`\x1B[${Ss};1H\x1B[2K${T}`):process.stdout.write(`\r\x1B[2K${T}`)}},1e3)}let{results:ct,summaries:T0}=await fR($e,!0,{...po,skipSummaries:!0});if(vr&&(clearInterval(vr),vr=null),Sr){Sr=null;let $=Yi($e,M,!1);Ss!==null?process.stdout.write(`\x1B[${Ss};1H\x1B[2K${$}
|
|
1437
|
+
`):process.stdout.write(`\r\x1B[2K${$}
|
|
1438
|
+
`),Ss=null}if(!po.skipSummaries){let $=T0.filter((T,N)=>!($e[N]&&$e[N].fnName==="ask_user"));for(let T of $)console.log(T);let y=$e.filter(T=>T&&T.fnName!=="ask_user").map(T=>T.fnName),z=t0.record(0,y,Z,b);z&&UT(z)}for(let $ of $e){if($.canExecute||!$.errorResult)continue;let y=typeof $.errorResult.content=="string"?$.errorResult.content:"";if((y.startsWith("BLOCKED:")||y.startsWith("PLAN MODE:")||y.startsWith("PLAN PHASE:"))&&(qn++,qn>=ku)){D(`${m.red} \u2716 Loop abort: ${qn} consecutive blocked calls (pre-execution) \u2014 model not heeding BLOCKED messages${m.reset}`),l&&(l.stop(),l=null),c(null),Me(M,L,b,Z,Ne,{suppressHint:!0}),Oe(P);return}}for(let $=0;$<$e.length;$++){let y=$e[$];if(!y.canExecute)continue;let z=ct[$].content,T=z.split(`
|
|
1439
|
+
`)[0],N=!T.startsWith("ERROR")&&!T.startsWith("CANCELLED")&&!T.startsWith("Command failed")&&!T.startsWith("EXIT");if(!N&&(y.fnName==="edit_file"||y.fnName==="patch_file")&&y.args?.path&&T.includes("old_text not found")){let R=qt.get(y.args.path)||0;qt.set(y.args.path,R+1)}if(!N&&y.fnName==="bash"&&hr.size>0){let R=(y.args?.command||"").toLowerCase();if(/\b(test|jest|vitest|pytest|mocha|tsc|build|lint|eslint|check)\b/.test(R))for(let[F]of hr)qt.has(F)||(qt.set(F,1),D(`${m.cyan} \u21A9 Test failure \u2014 queuing recovery re-read: "${F.split("/").pop()}"${m.reset}`))}if(!N&&(y.fnName==="read_file"||y.fnName==="edit_file")&&/file not found|does not exist|ENOENT/i.test(T)){if(Ln++,Ln>=2){D(`${m.yellow} \u26A0 File-not-found streak: ${Ln} consecutive misses \u2014 forcing search${m.reset}`);let R={role:"user",content:`[SYSTEM] ${Ln} 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.`};P.push(R),S.push(R)}}else N&&(y.fnName==="read_file"||y.fnName==="edit_file"||y.fnName==="search_files"||y.fnName==="glob_files")&&(Ln=0);if(N&&y.fnName==="write_file"&&y.args?.path){let R=y.args.path.split("/").pop(),q=y.args.path.includes("/tests/")||y.args.path.includes("\\tests\\");if(/^(test_|demo_|temp_|tmp_|scratch_)/.test(R)&&!q){D(`${m.yellow} \u26A0 Temp file: "${R}" \u2014 delete with bash rm when done to keep the workspace clean${m.reset}`);let V={role:"user",content:`[HINT] "${y.args.path}" looks like a temporary test/demo file. Delete it with bash("rm ${y.args.path}") as soon as you're done \u2014 orphaned temp files count against session quality.`};P.push(V),S.push(V)}}if(N&&["write_file","edit_file","patch_file"].includes(y.fnName)&&y.args&&y.args.path){qt.delete(y.args.path),b.add(y.args.path);for(let F of _s)!F.done&&y.args.path.endsWith(F.file.split("/").pop())&&(F.done=!0,D(`${m.green} \u2713 TODO done: ${F.file}${m.reset}`));let R=gs(n0,y.args.path),q=y.args.path.split("/").slice(-2).join("/");if(R===s0){D(`${m.yellow} \u26A0 Loop warning: "${q}" edited ${R}\xD7 \u2014 possible edit loop${m.reset}`);let F={role:"user",content:`[SYSTEM WARNING] "${y.args.path}" edited ${R}\xD7. One more edit max, then move on.`};P.push(F),S.push(F)}else if(R>=o0){D(`${m.red} \u2716 Loop abort: "${q}" edited ${R}\xD7 \u2014 aborting to prevent runaway loop${m.reset}`),l&&(l.stop(),l=null),c(null),Me(M,L,b,Z,Ne,{suppressHint:!0}),Oe(P);return}}if(N&&y.canExecute&&be&&(jn=0),N&&y.canExecute&&!(be&&Pe==="plan")){let R=["read_file","grep","search_files","glob","list_directory","ssh_exec","find_files"];if(["write_file","edit_file","patch_file"].includes(y.fnName)){Ut=0,Wt=!1,Zt=0,Qt++;let ee=y.args?.path||y.args?.file_path;ee&&(Kl(xn,ee,1),In.delete(ee),fe.add(ee))}else if(R.includes(y.fnName)&&(Ut++,Wt&&Zt++,be&&Pe==="implement"&&y.fnName==="read_file"&&_s.length>0)){let ee=y.args?.path||y.args?.file_path||"",_e=_s.find(Re=>!Re.done&&ee.endsWith(Re.file.split("/").pop()));if(_e){let Re={role:"user",content:`[TODO OBSERVER] You already analyzed "${_e.file}" in the plan phase. Action: ${_e.action}
|
|
1440
|
+
Do NOT re-read \u2014 apply the edit directly with edit_file.`};P.push(Re),S.push(Re),D(`${m.yellow} \u26A0 TODO nudge: ${_e.file} \u2014 already analyzed, edit directly${m.reset}`)}}be&&Pe==="verify"&&mr++;let F=n.postEditCap,V=be&&Pe==="implement"?Math.min(Su,10):Su,X=it?8:Bt?Qt>0?6:10:Qt>0?F:V,ie=6,me=!be&&Wt&&(it&&Zt>=ie||Bt&&Qt>=3&&Zt>=ie||Zt>=ie);if(nr<2&&!Wt&&Ut>=3&&b.size===0){let ee=parseInt(process.env.NEX_TASK_TIMEOUT_MS,10)||0,_e=Date.now()-Ne,Re=nr===0?.4:.65;if(ee>0&&_e>ee*Re){nr++;let $t=Math.round(_e/6e4),tt=Math.round(_e/ee*100);D(`${m.yellow} \u26A0 Time nudge #${nr}: ${$t}m elapsed (${tt}%), ${Ut} reads, 0 edits${m.reset}`);let Lt={role:"user",content:nr===1?`[SYSTEM] ${tt}% of available time used and no files edited yet. Start implementing now using edit_file or write_file \u2014 you have enough context.`:`[SYSTEM] ${tt}% 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.`};P.push(Lt),S.push(Lt)}}if(me&&R.includes(y.fnName)){let ee=it?`root cause already identified (${xt})`:Zt>=ie?`${Ut} consecutive reads without an edit`:`${Qt} file edit(s) already made`;D(`${m.red} \u2716 Blocked read-only tool: cap fired, ${ee}${m.reset}`),y.canExecute=!1,y.errorResult={role:"tool",content:it?`BLOCKED: root cause already identified (${xt}). Use edit_file to fix the issue \u2014 do not read more files.`:Bt?"BLOCKED: files already written \u2014 continue with write_file or edit_file to finish the remaining tasks. Do not read more files.":Zt>=ie?`BLOCKED: You have read ${Ut} files without making any edits. Stop investigating and either implement a fix with edit_file/write_file, or write your diagnosis as text output. Do not read more files.`:`BLOCKED: ${Qt} file edit(s) already made and post-edit investigation cap reached. The fix is in place. Do not read more files \u2014 proceed with the task.`,tool_call_id:y.callId}}else if(Ut>=X&&!Wt){if(Wt=!0,D(`${m.yellow} \u26A0 Investigation cap: ${Ut} read-only calls without an edit \u2014 forcing implementation${m.reset}`),be&&Pe==="plan"){let Re=[...S].reverse().find(Lt=>Lt.role==="assistant"),$t=typeof Re?.content=="string"?Re.content:"",tt=await or("implement",$t);tt&&(P.push(tt),S.push(tt),We=0,St=ms("implement"))}let ee;it?ee=`[SYSTEM] Root cause was already identified (${xt}). Edit the file now \u2014 do not read more files.`:Ot?ee="[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.":ee="[SYSTEM] You have read enough files. Now implement your fix using edit_file.";let _e={role:"user",content:ee};P.push(_e),S.push(_e)}}if((y.fnName==="bash"||y.fnName==="ssh_exec")&&y.args&&y.args.command){let R=y.args.command.replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),q=gs(xu,R);if(q===r0){D(`${m.yellow} \u26A0 Loop warning: same bash command run ${q}\xD7 \u2014 possible debug loop${m.reset}`);let F={role:"user",content:`[SYSTEM WARNING] Same bash command ${q}\xD7. Debug loop detected \u2014 try a different approach.`};P.push(F),S.push(F)}else if(q>=i0){D(`${m.red} \u2716 Loop abort: same bash command run ${q}\xD7 \u2014 aborting runaway debug loop${m.reset}`),l&&(l.stop(),l=null),c(null),Me(M,L,b,Z,Ne,{suppressHint:!0}),Oe(P);return}}if(y.fnName==="ssh_exec"){Ft++;{let F=(ct[$]?.content??"").split(`
|
|
1441
|
+
`).map(V=>V.trim()).find(V=>V.length>0&&!V.startsWith("**")&&(V.startsWith("EXIT")||/^[\w./-]+:\s/.test(V)||V.startsWith("bash:")||V.startsWith("sh:")))??"";if(F){if(F===ra?ws++:(ra=F,ws=1),ws===3&&!Ot){D(`${m.yellow} \u26A0 SSH repeated-error: "${F.slice(0,60)}" returned ${ws}\xD7 \u2014 nudging to change approach${m.reset}`);let V={role:"user",content:`[SYSTEM WARNING] The last ${ws} SSH commands all failed with the same error: "${F}". 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).`};P.push(V),S.push(V)}}else ra="",ws=0}if(Ft>=k0){D(`${m.red} \u2716 SSH storm abort: ${Ft} consecutive ssh_exec calls \u2014 aborting${m.reset}`),l&&(l.stop(),l=null),c(null),Me(M,L,b,Z,Ne,{suppressHint:!0}),Oe(P);return}else if(Ft===uo){{let F=dt(),{messages:V}=cn(S,F);S=V}Ot=!0,Ki++,D(`${m.yellow} \u26A0 SSH storm warning (#${Ki}): ${Ft} consecutive ssh_exec calls \u2014 blocking further SSH${m.reset}`);let q={role:"user",content:it?`[SYSTEM WARNING] ${Ft} consecutive SSH calls. Root cause identified (${xt}). Read the file that needs fixing, then edit it.`:`[SYSTEM WARNING] ${Ft} 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.`};P.push(q),S.push(q)}}else y.canExecute&&(Ft=0);if(y.fnName==="bash"&&y.canExecute){let F=(ct[$]?.content??"").split(`
|
|
1442
|
+
`).map(V=>V.trim()).find(V=>V.length>0&&(V.startsWith("EXIT")||/^[\w./-]+:\s/.test(V)||V.startsWith("bash:")||V.startsWith("sh:")))??"";if(F){if(F===ia?$s++:(ia=F,$s=1),$s===3){D(`${m.yellow} \u26A0 Bash repeated-error: "${F.slice(0,60)}" returned ${$s}\xD7 \u2014 nudging to change approach${m.reset}`);let V={role:"user",content:`[SYSTEM WARNING] The last ${$s} bash commands all failed with the same error: "${F}". 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).`};P.push(V),S.push(V)}}else ia="",$s=0}if(y.fnName==="bash"&&y.canExecute&&!Xl&&y.args?.command){let R=ct[$]?.content??"";if(/git\s+commit\b/.test(y.args.command)&&!R.startsWith("EXIT")&&!R.startsWith("ERROR")&&(/\[\S+\s+[a-f0-9]+\]/.test(R)||R.includes("files changed")||R.includes("file changed")||R.includes("insertions(+)")||R.includes("create mode"))){Xl=!0,sr=0,D(`${m.green} \u2713 Git commit detected \u2014 post-commit verification cap active (max 2 git status/diff/log)${m.reset}`);let V={role:"user",content:"[SYSTEM] \u2713 Git commit succeeded. Your changes are committed. Do NOT run further git status / git diff / git log calls \u2014 the commit is done. Write your final summary and stop. Running extra verification commands wastes tool calls and hurts session quality."};P.push(V),S.push(V)}}if(Xl&&y.fnName==="bash"&&y.args?.command&&/git\s+(status|diff|log|show)\b/.test(y.args.command)&&(sr++,sr>2)){D(`${m.yellow} \u26A0 Post-commit git verification blocked (call ${sr})${m.reset}`);let q={role:"user",content:"[SYSTEM] \u26A0 STOP: You already ran "+(sr-1)+" git verification commands after committing. The commit is confirmed. Write your final summary NOW and do not make any more tool calls."};P.push(q),S.push(q)}if(N&&y.fnName==="grep"&&z&&!z.startsWith("(no matches)")){let R=z.split(`
|
|
1443
|
+
`);for(let q of R){let F=q.indexOf(":");if(F>0){let V=q.substring(0,F);V.startsWith("/")&&!V.includes(" ")&&fr.add(V)}else q.startsWith("/")&&!q.includes(" ")&&fr.add(q.trim())}}{let R=["grep","search_files","glob","glob_files"].includes(y.fnName);if(R&&N&&z&&(z.startsWith("(no matches)")||z.trim()===""||/^No matches found/.test(z.trim())||/^\(0 results\)/.test(z.trim()))){if(lo++,lo===3){D(`${m.yellow} \u26A0 3 consecutive empty local searches \u2014 injecting SSH pivot hint${m.reset}`);let F={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."};P.push(F),S.push(F)}}else R&&N&&z&&z.trim().length>0&&(lo=0)}if(N&&y.fnName==="grep"&&y.args&&y.args.pattern){let R=`${y.args.pattern}|${y.args.path||""}`,q=gs(a0,R);if(q===c0){D(`${m.yellow} \u26A0 Loop warning: grep pattern "${y.args.pattern.slice(0,40)}" run ${q}\xD7 \u2014 possible search loop${m.reset}`);let F={role:"user",content:`[SYSTEM WARNING] Same grep pattern ${q}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};P.push(F),S.push(F)}else if(q>=l0){D(`${m.red} \u2716 Loop abort: grep pattern run ${q}\xD7 \u2014 aborting runaway search loop${m.reset}`),l&&(l.stop(),l=null),c(null),Me(M,L,b,Z,Ne,{suppressHint:!0}),Oe(P);return}if(y.args.path){let F=gs(ma,y.args.path),V=ln(xs,y.args.path)>=1;if(F===(V?1:u0)){let ie=y.args.path.split("/").slice(-2).join("/");D(`${m.yellow} \u26A0 Loop warning: "${ie}" grepped ${F}\xD7 with different patterns \u2014 context flood risk${m.reset}`);let me={role:"user",content:V?`[SYSTEM NOTE] "${y.args.path}" was already fully read \u2014 its content is in context. Grepping it again is redundant; use the context you already have.`:`[SYSTEM NOTE] "${y.args.path}" grepped ${F}\xD7 \u2014 use the search results already in context instead of searching again.`};P.push(me),S.push(me)}}}if(N&&(y.fnName==="glob"||y.fnName==="glob_files"||y.fnName==="search_files")&&y.args){if(z&&!z.startsWith("(no matches)")){let V=z.split(`
|
|
1444
|
+
`);for(let X of V)(X.startsWith("/")&&!X.includes(" ")||!X.includes(":")&&!X.startsWith("["))&&pr.add(X.trim())}let R=y.args.pattern||y.args.query||y.args.path||"",q=gs(d0,R);if(q===f0){D(`${m.yellow} \u26A0 Loop warning: glob pattern "${R.slice(0,40)}" run ${q}\xD7 \u2014 possible search loop${m.reset}`);let V={role:"user",content:`[SYSTEM WARNING] Same glob/search pattern ${q}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};P.push(V),S.push(V)}else if(q>=p0){D(`${m.red} \u2716 Loop abort: glob pattern run ${q}\xD7 \u2014 aborting runaway search loop${m.reset}`),l&&(l.stop(),l=null),c(null),Me(M,L,b,Z,Ne,{suppressHint:!0}),Oe(P);return}let F=R.replace(/\*+/g," ").replace(/[{}()\[\],.\/\\]/g," ").split(/\s+/).filter(V=>V.length>=4&&!/^\.(js|ts|py|json|md|yaml|yml|txt|css|html|sh)$/.test(V));for(let V of F){let X=V.toLowerCase();Qi.has(X)||Qi.set(X,new Set);let ie=Qi.get(X);if(ie.add(R),ie.size===m0){D(`${m.red} \u2716 Glob core-term block: ${ie.size} different patterns all searching for "${X}" \u2014 search loop${m.reset}`);let me={role:"user",content:`[SYSTEM WARNING] You have searched for "${X}" using ${ie.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.`};P.push(me),S.push(me)}else if(ie.size===h0){D(`${m.yellow} \u26A0 Glob core-term warning: ${ie.size} different patterns searching for "${X}"${m.reset}`);let me={role:"user",content:`[SYSTEM WARNING] ${ie.size} different glob patterns all target "${X}". If previous searches returned no results, the file probably does not exist \u2014 stop searching and proceed with available information.`};P.push(me),S.push(me)}}}let Q=(y.args?.command||y.args?.cmd||y.args?.script||"").toLowerCase(),B=/\b(health|healthcheck|health-check|status|check|ping|validate|alive|ready)\b/.test(Q)||/\/(health|status|ping|ready|alive)\b/.test(Q);if(N&&(y.fnName==="bash"||y.fnName==="ssh_exec")&&B&&z.includes('"valid":true')){{let q=dt();if(Jt(S,q).percentage>=60){let{messages:V,tokensRemoved:X}=cn(S,q);X>0&&(S=V,console.log(`${m.dim} [pre-stop-compress \u2014 ~${X} tokens freed before STOP injection, now ${Math.round(Jt(S,q).percentage)}%]${m.reset}`))}}let R={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.'};P.push(R),S.push(R),console.log(`${m.cyan} \u2713 Health-check stop signal detected \u2014 injecting STOP instruction${m.reset}`)}if(N&&(y.fnName==="bash"||y.fnName==="ssh_exec")&&Q&&/\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(Q)&&(Sn++,D(`${m.dim} [bash write detected: _bashModifiedFiles=${Sn}]${m.reset}`)),z.startsWith("BLOCKED:")){if(qn++,qn>=ku){D(`${m.red} \u2716 Loop abort: ${qn} consecutive blocked calls \u2014 model not heeding BLOCKED messages${m.reset}`),l&&(l.stop(),l=null),c(null),Me(M,L,b,Z,Ne,{suppressHint:!0}),Oe(P);return}}else qn=0;if(N)Dn=0,$a=!0;else if(Dn++,Dn===$0){D(`${m.yellow} \u26A0 Loop warning: ${Dn} consecutive tool errors \u2014 possible stuck loop${m.reset}`);let R={role:"user",content:`[SYSTEM WARNING] ${Dn} consecutive errors. Stuck loop \u2014 try fundamentally different approach or declare done.`};P.push(R),S.push(R)}else if(Dn>=b0){D(`${m.red} \u2716 Loop abort: ${Dn} consecutive errors \u2014 aborting stuck loop${m.reset}`),l&&(l.stop(),l=null),c(null),Me(M,L,b,Z,Ne,{suppressHint:!0}),Oe(P);return}if(N&&y.fnName==="read_file"&&y.args&&y.args.path){Z.add(y.args.path),fe.delete(y.args.path);let R=gs(xs,y.args.path);{let X=y.args.line_start!=null&&parseInt(y.args.line_start,10)||1,ie=y.args.line_start!=null?parseInt(y.args.line_end,10)||X+350:350;In.has(y.args.path)||In.set(y.args.path,[]),In.get(y.args.path).push([X,ie])}if(y._scrollWarn){let{sectionCount:X,path:ie}=y._scrollWarn,me={role:"user",content:`[SYSTEM WARNING] "${ie}" \u2014 you have now read ${X} different sections of this file. This is a file-scroll pattern. Stop reading sections and use grep_search to find the specific lines you need instead.`};P.push(me),S.push(me),D(`${m.yellow} \u26A0 Scroll warning: "${ie.split("/").slice(-2).join("/")}" \u2014 ${X} sections read \u2014 use grep instead${m.reset}`)}let q=y.args.path.split("/").slice(-2).join("/"),F=!y.args?.line_start&&!y.args?.line_end,V=be&&Pe==="plan";if(!V&&F&&R===g0){{let ie=dt();if(Jt(S,ie).percentage>=60){let{messages:ee}=cn(S,ie);S=ee}}D(`${m.yellow} \u26A0 Loop warning: "${q}" read unbounded ${R}\xD7 \u2014 use line_start/line_end${m.reset}`);let X={role:"user",content:`[SYSTEM WARNING] "${y.args.path}" read ${R}\xD7 without line ranges. Use line_start/line_end to read specific sections \u2014 do not re-read the full file.`};P.push(X),S.push(X)}else if(!V&&F&&R>=y0){D(`${m.red} \u2716 Loop abort: "${q}" read unbounded ${R}\xD7 \u2014 aborting runaway read loop${m.reset}`),l&&(l.stop(),l=null),c(null),Me(M,L,b,Z,Ne,{suppressHint:!0}),Oe(P);return}}if(y.fnName==="spawn_agents"){let R=(z.match(/\bStatus: done\b/g)||[]).length;if((z.match(/\bStatus: truncated\b/g)||[]).length>0&&R===0){if(Fn++,Fn===_0){D(`${m.yellow} \u26A0 Swarm warning: all sub-agents hit iteration limit ${Fn}\xD7 in a row${m.reset}`);let F={role:"user",content:`[SYSTEM WARNING] Sub-agents truncated ${Fn}\xD7 in a row. Stop spawning \u2014 try different approach or report findings.`};P.push(F),S.push(F)}else if(Fn>=x0){console.log(`${m.red} \u2716 Swarm abort: all sub-agents hit iteration limit ${Fn}\xD7 \u2014 aborting stuck swarm${m.reset}`),l&&(l.stop(),l=null),c(null),Me(M,L,b,Z,Ne,{suppressHint:!0}),Oe(P);return}}else R>0&&(Fn=0)}}{let y=ct.reduce((z,T)=>z+(typeof T.content=="string"?T.content.length:0),0);if(y>2e5){let z=ct.map((T,N)=>({i:N,len:typeof T.content=="string"?T.content.length:0})).sort((T,N)=>N.len-T.len);for(let{i:T,len:N}of z){if(y<=2e5)break;let Q=y-2e5,B=Math.max(N-Q,500);B<N&&typeof ct[T].content=="string"&&(ct[T]={...ct[T],content:ct[T].content.substring(0,B)+`
|
|
1445
|
+
...(truncated ${N-B} chars \u2014 per-message budget)`},y-=N-B)}}}for(let $ of ct)P.push($),S.push($);if(Xi(P,S),!it)for(let $=0;$<ct.length;$++){if(!$e[$]||$e[$].fnName!=="ssh_exec")continue;let y=ct[$];if(!y||typeof y.content!="string")continue;let z=zl(y.content);if(z){it=!0,xt=z.slice(0,120),Ut=0,Wt=!1,Zt=0,D(`${m.yellow} \u26A1 Root cause detected: ${xt} \u2014 fix phase (read budget: 3)${m.reset}`);let T={role:"user",content:`[SYSTEM] Root cause identified: ${xt}. Read only the file that needs fixing, then edit it. Do not read other files.`};P.push(T),S.push(T);break}}for(let $=0;$<ct.length;$++){let y=$e[$];if(!y)continue;let z=typeof ct[$]?.content=="string"?ct[$].content:"";if(y.fnName==="create_task"){let T=z.match(/Task #(\d+) created/),N=typeof y.args?.subject=="string"?y.args.subject:"";T&&N&&gr.set(T[1],N)}else if((y.fnName==="write_file"||y.fnName==="edit_file")&&!z.startsWith("BLOCKED:")&&z.trim().length>0){let N=(typeof y.args?.path=="string"?y.args.path:typeof y.args?.file_path=="string"?y.args.file_path:"").split("/").pop().toLowerCase(),Q=N.split(/[._\-/]/).filter(B=>B.length>2);for(let[B,re]of gr){if(yr.has(B))continue;let R=re.toLowerCase().split(/\W+/).filter(F=>F.length>3);Q.filter(F=>R.some(V=>V.includes(F)||F.includes(V))).length>=1&&(yr.add(B),D(`${m.green} \u2714 Auto-matched task #${B} to ${N}: ${re.slice(0,60)}${m.reset}`))}}}{let $=dt();if(Jt(S,$).percentage>=78){let{messages:z,tokensRemoved:T}=cn(S,$);T>0&&(S=z,console.log(`${m.dim} [auto-compressed \u2014 ~${T} tokens freed, now ${Math.round(Jt(S,$).percentage)}%]${m.reset}`))}}if(ur()&&!s.skillLoop&&($e.some(y=>y&&["write_file","edit_file","patch_file"].includes(y.fnName))?pe=0:(pe===0&&(Qe=b.size),pe++),pe>=9&&M>=4&&b.size===Qe)){D(`${m.green} \u2713 Stagnation exit: ${pe} read-only iterations, no new file changes${m.reset}`),process.stdout.isTTY&&process.stderr.write(`${m.yellow} \u26A0 Stagnation detected: ${pe} iterations without edits \u2014 exiting. The model investigated but did not apply changes.${m.reset}
|
|
1446
|
+
`),l&&(l.stop(),l=null),c(null),Me(M,L,b,Z,Ne),Oe(P);break e}let Pu=hR();if(Pu){let $={role:"user",content:`[User note mid-run]: ${Pu}`};P.push($),S.push($),console.log(`${m.cyan} \u270E Context added${m.reset}`)}}if(We>=St){if(l&&(l.stop(),l=null),c(null),Me(M,L,b,Z,Ne),Oe(P),Gi(P),be&&Pe==="plan"){let et=[...P].reverse().find(Ve=>Ve.role==="assistant"),ft=typeof et?.content=="string"?et.content:"",vn=await or("implement",ft);if(vn){P.push(vn),S=[{role:"system",content:await lu()},...P],St=ms("implement"),D(`${m.yellow} \u26A0 Plan budget exhausted \u2014 auto-transitioning to implement${m.reset}`);continue e}}else if(be&&Pe==="verify"){D(`${m.yellow} \u26A0 Verify budget exhausted \u2014 completing session${m.reset}`);break e}let{getActiveProviderName:ye}=st();if(ye()==="ollama"&&wa<Tu){if(b.size===0&&!$a){console.log(`${m.yellow} \u26A0 Max iterations reached with no progress. Stopping.${m.reset}`);break e}wa++,St=20,console.log(`${m.dim} \u2500\u2500 auto-extending (+20 turns, ext ${wa}/${Tu}) \u2500\u2500${m.reset}`);continue e}if(console.log(`
|
|
1447
|
+
${m.yellow}\u26A0 Max iterations reached.${m.reset}`),await Sy(" Continue for 20 more turns?")){St=20;continue e}console.log(`${m.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${m.reset}`)}break e}await vu()}By.exports={processInput:NR,clearConversation:xR,getConversationLength:SR,getConversationMessages:vR,setConversationMessages:ER,setAbortSignalGetter:XT,setMaxIterations:KT,invalidateSystemPromptCache:tu,clearToolFilterCache:sR,getCachedFilteredTools:Oy,buildSystemPrompt:lu,splitSystemPrompt:_R,SYSTEM_PROMPT_DYNAMIC_BOUNDARY:cu,getProjectContextHash:Ny,_inferVerificationCommands:qy,_inferRelevantTests:du,_inferSymbolTargets:jy,_buildSymbolHintBlock:Dy,buildUserContent:Cy,_detectImageURLs:Ey,_downloadImageURL:Ty,_grabClipboardImage:Ry,detectFrustration:Ay,detectAndTruncateLoop:Zl,injectMidRunNote:pR,resetSessionTracking:Fy}});var st=J((ZC,Yy)=>{var{OllamaProvider:MR}=ad(),{OpenAIProvider:PR}=dd(),{AnthropicProvider:LR}=md(),{GeminiProvider:IR}=$d(),{LocalProvider:jR}=xd(),{checkBudget:DR}=Wr(),hu={top:{ollama:"kimi-k2:1t",openai:"gpt-4.1",anthropic:"claude-sonnet-4-5",gemini:"gemini-2.5-pro"},strong:{ollama:"qwen3-coder:480b",openai:"gpt-4o",anthropic:"claude-sonnet",gemini:"gemini-2.5-flash"},fast:{ollama:"devstral-small-2:24b",openai:"gpt-4.1-mini",anthropic:"claude-haiku",gemini:"gemini-2.0-flash"}},fu=(process.env.OLLAMA_FALLBACK_CHAIN||"").split(",").map(t=>t.trim()).filter(Boolean),Wy={};for(let[t,e]of Object.entries(hu))for(let s of Object.values(e))Wy[s]=t;function pu(t,e){let s=Wy[t];return s&&hu[s][e]||t}var at={},kt=null,ze=null,wr=[];function Ht(){if(Object.keys(at).length>0)return;ao("ollama",new MR),ao("openai",new PR),ao("anthropic",new LR),ao("gemini",new IR),ao("local",new jR);let t=process.env.DEFAULT_PROVIDER||"ollama",e=process.env.DEFAULT_MODEL||null;at[t]?(kt=t,ze=e||at[t].defaultModel):(kt="ollama",ze="kimi-k2.5");let s=process.env.FALLBACK_CHAIN;s&&(wr=s.split(",").map(n=>n.trim()).filter(Boolean))}function ao(t,e){at[t]=e}function qR(t){return Ht(),at[t]||null}function mu(){return Ht(),at[kt]||null}function FR(){return Ht(),kt}function BR(){return Ht(),ze}function UR(){Ht();let t=mu();if(!t)return{id:ze,name:ze,provider:kt};let e=t.getModel(ze);return e?{...e,provider:kt}:{id:ze,name:ze,provider:kt}}function gu(t){if(!t)return{provider:null,model:null};let e=t.indexOf(":");if(e>0){let s=t.slice(0,e);if(at[s]||["ollama","openai","anthropic","gemini","local"].includes(s))return{provider:s,model:t.slice(e+1)}}return{provider:null,model:t}}function WR(t){Ht();let{provider:e,model:s}=gu(t);if(e){let o=at[e];return o&&(o.getModel(s)||e==="local"||e==="ollama")?(kt=e,ze=s,da(),!0):!1}let n=mu();if(n&&n.getModel(s))return ze=s,da(),!0;for(let[o,r]of Object.entries(at))if(r.getModel(s))return kt=o,ze=s,da(),!0;return!1}function da(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=bl();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=rn();t()}catch{}}function HR(){Ht();let t=new Set;for(let e of Object.values(at))for(let s of e.getModelNames())t.add(s);return Array.from(t)}function YR(){return Ht(),Object.entries(at).map(([t,e])=>({provider:t,configured:e.isConfigured(),models:Object.values(e.getModels()).map(s=>({...s,active:t===kt&&s.id===ze}))}))}function GR(){Ht();let t=[];for(let[e,s]of Object.entries(at)){let n=s.isConfigured();for(let o of Object.values(s.getModels()))t.push({spec:`${e}:${o.id}`,name:o.name,provider:e,configured:n})}return t}function zR(t){wr=Array.isArray(t)?t:[]}function KR(){return[...wr]}function Uy(t){let e=t.message||"",s=t.code||"";return!!(e.includes("429")||e.includes("500")||e.includes("502")||e.includes("503")||e.includes("504")||s==="ECONNABORTED"||s==="ETIMEDOUT"||s==="ECONNREFUSED"||s==="ECONNRESET"||s==="EHOSTUNREACH"||s==="ENETUNREACH"||s==="EPIPE"||s==="ERR_SOCKET_CONNECTION_TIMEOUT"||e.includes("socket disconnected")||e.includes("TLS")||e.includes("ECONNRESET")||e.includes("ECONNABORTED")||e.includes("network")||e.includes("ETIMEDOUT"))}async function Hy(t){let e=[kt,...wr.filter(r=>r!==kt)],s,n=0,o=0;for(let r=0;r<e.length;r++){let i=e[r],a=at[i];if(!a||!a.isConfigured())continue;o++;let c=DR(i);if(!c.allowed){n++,s=new Error(`Budget limit reached for ${i}: $${c.spent.toFixed(2)} / $${c.limit.toFixed(2)}`);continue}try{let l=r>0,u=l?pu(ze,i):ze;return l&&u!==ze&&process.stderr.write(` [fallback: ${i}:${u}]
|
|
1448
|
+
`),await t(a,i,u)}catch(l){if(s=l,!Uy(l)||r>=e.length-1)throw l;if(i==="ollama"&&fu.length>0){let u=isFallback?pu(ze,i):ze;for(let d of fu)if(d!==u)try{return process.stderr.write(` [ollama fallback: ${d}]
|
|
1449
|
+
`),await t(a,i,d)}catch(f){if(s=f,!Uy(f))throw f}}continue}}throw n>0&&n===o?new Error("All providers are over budget. Use /budget to check limits or /budget <provider> off to remove a limit."):o===0?new Error("No configured provider available"):s||new Error("No configured provider available")}async function XR(t,e,s={}){Ht();let n=s.model,o=n?(()=>{let{model:i}=gu(n);return i||n})():void 0,r=o!==n?{...s,model:o}:s;return Hy((i,a,c)=>i.stream(t,e,{model:c,signal:r.signal,...r}))}async function VR(t,e,s={}){if(Ht(),s.provider){let n=at[s.provider];if(!n||!n.isConfigured())throw new Error(`Provider '${s.provider}' is not available`);let o={model:s.model||ze,...s};try{return await n.chat(t,e,o)}catch(r){if(typeof n.stream=="function")try{return await n.stream(t,e,{...o,onToken:()=>{}})}catch{}throw r}}return Hy(async(n,o,r)=>{try{return await n.chat(t,e,{model:r,...s})}catch(i){if(typeof n.stream=="function")try{return await n.stream(t,e,{model:r,...s,onToken:()=>{}})}catch{}throw i}})}function JR(){Ht();let t=[];for(let[e,s]of Object.entries(at))s.isConfigured()&&t.push({name:e,models:Object.values(s.getModels())});return t}function ZR(){for(let t of Object.keys(at))delete at[t];kt=null,ze=null,wr=[]}Yy.exports={registerProvider:ao,getProvider:qR,getActiveProvider:mu,getActiveProviderName:FR,getActiveModelId:BR,getActiveModel:UR,setActiveModel:WR,getModelNames:HR,parseModelSpec:gu,listProviders:YR,listAllModels:GR,callStream:XR,callChat:VR,getConfiguredProviders:JR,setFallbackChain:zR,getFallbackChain:KR,resolveModelForProvider:pu,MODEL_EQUIVALENTS:hu,OLLAMA_FALLBACK_MODELS:fu,_reset:ZR}});var{C:Y}=Je(),QR=st(),{TOOL_DEFINITIONS:Gy}=Ls(),{saveRoutingConfig:e1}=ls(),$u=[{id:"read-package",category:"file-ops",prompt:"Read the file package.json and show me its contents.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("package.json")},{id:"write-file",category:"file-ops",prompt:'Create a file at /tmp/nex-bench-test.txt with the content "benchmark run".',expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&typeof t.content=="string"},{id:"edit-file",category:"file-ops",prompt:'In the file src/config.js, replace the string "debug: false" with "debug: true".',expectedTool:["edit_file","patch_file"],validateArgs:t=>!!(t.path&&t.old_string!==void 0&&t.new_string!==void 0||t.path&&Array.isArray(t.patches)&&t.patches.length>0)},{id:"list-directory",category:"file-ops",prompt:"Show me all files and folders in the cli/ directory.",expectedTool:["list_directory","glob"],validateArgs:t=>!!(typeof t.path=="string"&&t.path.includes("cli")||typeof t.pattern=="string"&&t.pattern.includes("cli"))},{id:"glob-js-files",category:"file-ops",prompt:"Find all JavaScript files (*.js) recursively in the cli/ directory.",expectedTool:"glob",validateArgs:t=>typeof t.pattern=="string"&&t.pattern.includes(".js")},{id:"read-partial",category:"file-ops",prompt:"Read only lines 20 to 40 of src/index.js \u2014 I need to see that specific range.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("index")&&(typeof t.line_start=="number"||typeof t.start_line=="number")},{id:"glob-ts-defs",category:"file-ops",prompt:"Find all TypeScript type definition files (*.d.ts) anywhere in the project.",expectedTool:"glob",validateArgs:t=>typeof t.pattern=="string"&&t.pattern.includes(".d.ts")},{id:"write-gitignore",category:"file-ops",prompt:"Create a .gitignore file at the project root that ignores node_modules/ and dist/.",expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes(".gitignore")&&typeof t.content=="string"&&t.content.includes("node_modules")},{id:"edit-version-bump",category:"file-ops",prompt:'In package.json, change the version field from "1.0.0" to "1.1.0".',expectedTool:["edit_file","patch_file"],validateArgs:t=>!!(t.path&&t.path.includes("package"))},{id:"grep-with-filter",category:"search",prompt:"Search for all calls to require() but only inside .js files in the cli/ directory.",expectedTool:["grep","search_files"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("require")},{id:"no-tool-http-port",category:"reasoning",prompt:"What is the default port used by the HTTP protocol?",expectedTool:null,validateArgs:()=>!0},{id:"bash-node-version",category:"shell",prompt:"Check which version of Node.js is currently installed on this system.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("node")&&(t.command.includes("--version")||t.command.includes("-v"))},{id:"search-constant",category:"search",prompt:'Search for the string "DEFAULT_MODEL" across all files in the project.',expectedTool:["search_files","grep"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("DEFAULT_MODEL")},{id:"grep-function-def",category:"search",prompt:'Find where the function "callStream" is defined in the codebase.',expectedTool:["grep","search_files"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("callStream")},{id:"search-todos",category:"search",prompt:"Find all TODO comments in the source code.",expectedTool:["grep","search_files","bash"],validateArgs:t=>JSON.stringify(t).toUpperCase().includes("TODO")},{id:"git-branch",category:"shell",prompt:"What git branch am I currently on?",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("git")},{id:"git-status",category:"shell",prompt:"Show me the current git status of the repository.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("git status")},{id:"npm-install",category:"shell",prompt:"Run npm install to install project dependencies.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("npm")},{id:"schema-strict",category:"schema",prompt:"Read the file README.md",expectedTool:"read_file",validateArgs:(t,e)=>{let s=e?.function?.parameters||{},n=s.required||[],o=Object.keys(s.properties||{});return n.every(r=>t[r]!==void 0)&&Object.keys(t).every(r=>o.includes(r))}},{id:"multi-step-version",category:"multi-step",prompt:"What is the current version of this project? Check the source files.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("package.json")},{id:"multi-step-count",category:"multi-step",prompt:"How many JavaScript files are in the cli/ directory? Count them.",expectedTool:["bash","glob","list_directory"],validateArgs:t=>!!(typeof t.command=="string"&&t.command.includes("cli")||typeof t.pattern=="string"&&t.pattern.includes("cli")||typeof t.path=="string"&&t.path.includes("cli"))},{id:"no-tool-reasoning",category:"reasoning",prompt:'What does the acronym "API" stand for?',expectedTool:null,validateArgs:()=>!0},{id:"frontend-find-hook",category:"frontend",prompt:"Find all files that import useState from React.",expectedTool:["grep","search_files"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("useState")},{id:"frontend-create-component",category:"frontend",prompt:"Create a React functional component called Button that accepts a label prop and renders a styled button element. Save it to src/components/Button.jsx.",expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&(t.path.includes(".jsx")||t.path.includes(".tsx")||t.path.includes(".js"))&&typeof t.content=="string"},{id:"frontend-edit-css",category:"frontend",prompt:'In the file src/styles.css, change the background-color value from "blue" to "red".',expectedTool:["edit_file","patch_file"],validateArgs:t=>t.path&&t.old_string!==void 0?t.path.includes(".css")||t.old_string.includes("blue")||t.old_string.includes("background"):!!(t.path&&Array.isArray(t.patches))},{id:"frontend-glob-components",category:"frontend",prompt:"Find all JSX and TSX component files in the components/ directory.",expectedTool:"glob",validateArgs:t=>typeof t.pattern=="string"&&(t.pattern.includes(".jsx")||t.pattern.includes(".tsx")||t.pattern.includes("{jsx,tsx}"))},{id:"frontend-list-assets",category:"frontend",prompt:"List all files in the src/assets/ directory.",expectedTool:["list_directory","glob"],validateArgs:t=>!!(typeof t.path=="string"&&t.path.includes("assets")||typeof t.pattern=="string"&&t.pattern.includes("assets"))},{id:"sysadmin-port-check",category:"sysadmin",prompt:"Which process is currently listening on port 3000?",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("lsof")||t.command.includes("ss")||t.command.includes("netstat")||t.command.includes("3000"))},{id:"sysadmin-nginx-config",category:"sysadmin",prompt:"Create an nginx server block that proxies requests to localhost:3000. Save it to /etc/nginx/sites-available/myapp.",expectedTool:["write_file","bash"],validateArgs:t=>!!(t.path&&(t.path.includes("nginx")||t.path.includes("sites-available"))||t.command&&t.command.includes("nginx"))},{id:"sysadmin-service-status",category:"sysadmin",prompt:"Check the status of the nginx service and show if it is running.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("systemctl")||t.command.includes("service")||t.command.includes("nginx"))},{id:"sysadmin-error-log",category:"sysadmin",prompt:"Show the last 100 lines of the nginx error log.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("tail")||t.command.includes("journalctl")||t.command.includes("nginx"))},{id:"sysadmin-docker-compose",category:"sysadmin",prompt:"Create a docker-compose.yml file for a Node.js application with a PostgreSQL database.",expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("docker-compose")&&typeof t.content=="string"},{id:"data-sql-query",category:"data",prompt:"Write a SQL query to find all users who have not logged in for more than 30 days. Save it to queries/inactive-users.sql.",expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&(t.path.includes(".sql")||t.path.includes("quer"))&&typeof t.content=="string"},{id:"data-find-json-key",category:"data",prompt:'Find all JSON files in the project that contain the key "userId".',expectedTool:["grep","search_files"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("userId")},{id:"data-python-csv",category:"data",prompt:'Write a Python script that reads data.csv and calculates the average of the "price" column. Save it to scripts/average_price.py.',expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes(".py")&&typeof t.content=="string"},{id:"data-find-migrations",category:"data",prompt:"Find all database migration files in this project.",expectedTool:["glob","search_files","grep"],validateArgs:t=>JSON.stringify(t).toLowerCase().includes("migrat")},{id:"data-find-schema",category:"data",prompt:"Find where the database schema or models are defined in this project.",expectedTool:["grep","glob"],validateArgs:t=>!!(t.pattern&&/schema|model|migration/i.test(t.pattern)||t.pattern&&/schema|model|migration/i.test(t.pattern))},{id:"data-write-query",category:"data",prompt:"Write a SQL query to find all users who registered in the last 30 days and save it to queries/recent-users.sql.",expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes(".sql")},{id:"data-read-env",category:"data",prompt:"Read the .env file to find the database connection string.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&/\.env|env\./i.test(t.path)},{id:"resilience-edit-failed",category:"resilience",prompt:"Your edit_file call on server.js failed: old_string 'const PORT = 3000' was not found in the file. What do you do next to recover?",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("server")},{id:"resilience-file-not-found",category:"resilience",prompt:"read_file returned 'file not found' for src/utils/helpers.js. You need to find where the helper functions are now. What tool do you use?",expectedTool:["glob_files","bash"],validateArgs:t=>{let e=JSON.stringify(t).toLowerCase();return e.includes("src")||e.includes("helper")||e.includes("util")||e.includes("*.js")}},{id:"resilience-large-file-nav",category:"resilience",prompt:"The file src/api.js is 2800 lines. You need to locate the authenticateUser function. What is the most efficient tool to use \u2014 read_file or bash with grep?",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("grep")||t.command.includes("rg")||t.command.includes("awk"))},{id:"resilience-broken-import",category:"resilience",prompt:"TypeScript reports: Cannot find module './config'. The file was recently renamed. What tool do you use to find the new location?",expectedTool:["glob_files","bash"],validateArgs:t=>{let e=JSON.stringify(t).toLowerCase();return e.includes("config")||e.includes("*.ts")||e.includes("*.js")||e.includes("find")}},{id:"resilience-bash-error-recover",category:"resilience",prompt:"The command 'npm test' failed with exit code 1. The output contains 'SyntaxError: Unexpected token' in src/parser.js:45. What is your next action?",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("parser")},{id:"resilience-grep-no-match",category:"resilience",prompt:"grep returned zero matches for 'getUserById' in src/. The function exists but may have been renamed. What bash command finds all exported function names in src/ to identify the current name?",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("grep")||t.command.includes("rg")||t.command.includes("src"))},{id:"ssh-exec-log",category:"ssh",prompt:'Show the last 50 lines of /var/log/nginx/error.log on server "prod-1".',expectedTool:"ssh_exec",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("tail")||t.command.includes("log"))&&(typeof t.host=="string"||typeof t.profile=="string")},{id:"ssh-exec-service",category:"ssh",prompt:'Restart the nginx service on server "prod-1".',expectedTool:"ssh_exec",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("nginx")||t.command.includes("systemctl")||t.command.includes("restart"))&&(typeof t.host=="string"||typeof t.profile=="string")},{id:"ssh-exec-port",category:"ssh",prompt:'Check if port 8080 is listening on server "prod-1".',expectedTool:"ssh_exec",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("8080")||t.command.includes("ss")||t.command.includes("netstat")||t.command.includes("lsof"))&&(typeof t.host=="string"||typeof t.profile=="string")},{id:"ssh-exec-processes",category:"ssh",prompt:'Show the top CPU-consuming processes on server "prod-1".',expectedTool:"ssh_exec",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("top")||t.command.includes("ps")||t.command.includes("htop"))&&(typeof t.host=="string"||typeof t.profile=="string")},{id:"git-diff-staged",category:"git",prompt:"Show all staged changes before committing.",expectedTool:["git_diff","bash"],validateArgs:t=>!!(t.staged===!0||t.staged==="true"||typeof t.command=="string"&&t.command.includes("diff"))},{id:"git-log-recent",category:"git",prompt:"Show the last 5 commit messages with their hashes.",expectedTool:["git_log","bash"],validateArgs:t=>!!(typeof t.limit=="number"||typeof t.n=="number"||typeof t.command=="string"&&t.command.includes("log"))},{id:"git-status-check",category:"git",prompt:"Check if there are any uncommitted changes in the repository.",expectedTool:["git_status","bash"],validateArgs:t=>t.path===void 0&&t.command===void 0?!1:(typeof t.command=="string"&&t.command.includes("status"),!0)},{id:"agentic-test-first",category:"agentic",prompt:"Run the full test suite. If any tests fail, identify the failing test file and read it to understand the issue.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("test")||t.command.includes("jest")||t.command.includes("npm"))},{id:"agentic-read-then-act",category:"agentic",prompt:"Read the project README.md, find the TODO section, and list which items are completed.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("README")},{id:"agentic-build-deploy",category:"agentic",prompt:"Build the project with npm run build, then verify the output exists in the dist/ directory.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("build")||t.command.includes("npm"))},{id:"agentic-spawn-parallel",category:"agentic",prompt:"Search for all TODO comments and all FIXME comments across the codebase in parallel using multiple agents.",expectedTool:"spawn_agents",validateArgs:t=>Array.isArray(t.agents)&&t.agents.length>=2},{id:"agentic-multi-investigate",category:"agentic",prompt:"The app is crashing on startup. Spawn parallel agents to check: (1) recent git changes, (2) npm dependency issues, (3) the main entry file for syntax errors.",expectedTool:"spawn_agents",validateArgs:t=>Array.isArray(t.agents)&&t.agents.length>=2}],zy=[{id:"phase-plan-diagnosis",category:"phase-plan",prompt:"The server returns 500 on /api/users. The error log shows: TypeError: Cannot read property 'map' of undefined at routes/users.js:42. Read the relevant file to diagnose the root cause.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&/users/i.test(t.path)},{id:"phase-plan-search",category:"phase-plan",prompt:"We're getting CORS errors in production. Search the codebase for where CORS middleware is configured.",expectedTool:"grep",validateArgs:t=>typeof t.pattern=="string"&&/cors/i.test(t.pattern)},{id:"phase-plan-context",category:"phase-plan",prompt:"The login page shows a blank screen after the last deploy. Check git log for recent changes that might have broken it.",expectedTool:"git_log",validateArgs:()=>!0},{id:"phase-verify-test",category:"phase-verify",prompt:"The file src/utils.js was modified to fix a null pointer bug. Run the test suite to verify the fix works correctly.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&/test|jest|npm\s+test|pytest|mocha/.test(t.command)},{id:"phase-verify-read",category:"phase-verify",prompt:"A patch was applied to config/database.js to fix the connection pool. Read the file to verify the changes look correct.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&/database/i.test(t.path)},{id:"phase-verify-lint",category:"phase-verify",prompt:"Code was modified in src/components/Header.tsx. Run the linter to check for any style violations.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&/lint|eslint|prettier|tsc/.test(t.command)},{id:"phase-plan-git-blame",category:"phase-plan",prompt:"A production bug was introduced 2 days ago. Use git log to find commits from the last 2 days to identify what changed.",expectedTool:"git_log",validateArgs:()=>!0},{id:"phase-plan-error-trace",category:"phase-plan",prompt:"The error stack trace mentions src/middleware/auth.js line 87. Read the file around that line to understand the bug.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&/auth/i.test(t.path)},{id:"phase-plan-grep-config",category:"phase-plan",prompt:"Users report the app is using wrong API keys in staging. Search for where API_KEY is loaded from environment.",expectedTool:"grep",validateArgs:t=>typeof t.pattern=="string"&&/api.?key|env/i.test(t.pattern)},{id:"phase-verify-build",category:"phase-verify",prompt:"The TypeScript source was modified. Run the build command to verify there are no compilation errors.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&/build|tsc|compile/.test(t.command)},{id:"phase-verify-git-diff",category:"phase-verify",prompt:"Changes were just committed. Show the git diff of the last commit to verify only the intended files were modified.",expectedTool:["git_diff","bash"],validateArgs:t=>(t.command&&/git.*diff|diff.*HEAD/.test(t.command),!0)},{id:"phase-verify-read-config",category:"phase-verify",prompt:"The deployment config was updated. Read config/production.json to verify the changes are correct before deploying.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&/config|production|deploy/i.test(t.path)}],ha=[...$u,...zy],yu=["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 t1(){try{let s=require("path").join(require("os").homedir(),".nex-code","benchmark-results.json");if(!require("fs").existsSync(s))return yu;let n=JSON.parse(require("fs").readFileSync(s,"utf-8"));return!Array.isArray(n)||n.length===0?yu:n.filter(o=>typeof o.score=="number"&&o.score>=60).sort((o,r)=>r.score-o.score).slice(0,12).map(o=>o.model)}catch{return yu}}var bu=t1(),n1=["minimax-m2.7:cloud","qwen3-coder:480b","devstral-2:123b"],Ky=(()=>{let t=bu.slice(0,3);return t.length>=3?t:n1})(),s1=14,fa={producedToolCall:.2,correctTool:.35,validArgs:.3,schemaCompliant:.15},o1="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 wu(t,e){let s={taskId:t.id,category:t.category,model:e,producedToolCall:!1,correctTool:!1,validArgs:!1,schemaCompliant:!1,toolCalled:null,error:null,latencyMs:0},n=[{role:"system",content:o1},{role:"user",content:t.prompt}],o=Date.now();try{let r=await QR.callChat(n,Gy,{provider:"ollama",model:e,temperature:0,timeout:9e4});s.latencyMs=Date.now()-o;let i=r.tool_calls||[];if(t.expectedTool===null){let a=i.length===0;s.producedToolCall=a,s.correctTool=a,s.validArgs=!0,s.schemaCompliant=!0}else if(i.length>0){let a=i[0],c=a.function?.name||"unknown",l=a.function?.arguments||{};s.producedToolCall=!0,s.toolCalled=c;let u=Array.isArray(t.expectedTool)?t.expectedTool:[t.expectedTool];if(s.correctTool=u.includes(c),s.correctTool){let d=Gy.find(f=>f.function?.name===c);if(s.validArgs=!!t.validateArgs(l,d),d){let f=d.function?.parameters||{},p=f.required||[],h=Object.keys(f.properties||{});s.schemaCompliant=p.every(g=>l[g]!==void 0)&&Object.keys(l).every(g=>h.includes(g))}}}}catch(r){s.latencyMs=Date.now()-o,s.error=r.message.slice(0,120)}return s}function co(t){return t.error?0:((t.producedToolCall?fa.producedToolCall:0)+(t.correctTool?fa.correctTool:0)+(t.validArgs?fa.validArgs:0)+(t.schemaCompliant?fa.schemaCompliant:0))*100}var Xy={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 _u(t){return Object.entries(t).map(([e,s])=>{let n=s.map(co),o=n.reduce((a,c)=>a+c,0)/n.length,r=a=>Math.round(s.filter(a).length/s.length*100),i={};for(let a of["coding","frontend","sysadmin","data","agentic","plan","verify"]){let c=s.filter(u=>Xy[u.category]===a);if(c.length===0)continue;let l=c.map(co).reduce((u,d)=>u+d,0)/c.length;i[a]=Math.round(l*10)/10}return{model:e,score:Math.round(o*10)/10,toolCallRate:r(a=>!a.error&&(a.producedToolCall||a.category==="reasoning")),correctRate:r(a=>a.correctTool),validArgsRate:r(a=>a.validArgs),schemaRate:r(a=>a.schemaCompliant),avgLatency:Math.round(s.reduce((a,c)=>a+c.latencyMs,0)/s.length),errorCount:s.filter(a=>a.error).length,categoryScores:i,results:s}}).sort((e,s)=>s.score-e.score)}function Vy(t){let e={};for(let a of["coding","frontend","sysadmin","data","agentic","plan","verify"]){let c=t.filter(g=>g.categoryScores[a]!==void 0&&g.score>=65).sort((g,w)=>w.categoryScores[a]-g.categoryScores[a]);if(c.length===0)continue;let u=(c[0]?.results||[]).filter(g=>Xy[g.category]===a).length;if(u<4)continue;let d=c[0],f=c[1];if(d.categoryScores[a]>=95&&u<8&&f&&d.categoryScores[a]-f.categoryScores[a]<15){let w=t.filter(x=>x.categoryScores[a]!==void 0).find(x=>x.categoryScores[a]<95);w&&(e[a]={model:w.model,score:w.categoryScores[a],avgLatency:w.avgLatency,_flukePrevented:!0});continue}let h=c.filter(g=>d.categoryScores[a]-g.categoryScores[a]<=5).sort((g,w)=>g.avgLatency-w.avgLatency)[0];e[a]={model:h.model,score:h.categoryScores[a],avgLatency:h.avgLatency}}return e}function Jy(t,e){let s=`nex-code Model Benchmark (${e} tasks \xB7 ollama cloud)`,n=[{label:"#",width:3},{label:"Model",width:26},{label:"Score",width:7},{label:"Tool\u2713",width:7},{label:"Name\u2713",width:7},{label:"Args\u2713",width:7},{label:"Schema\u2713",width:8},{label:"Latency",width:8},{label:"Err",width:4}],o=n.reduce((u,d)=>u+d.width+1,0)+1,r="\u2500".repeat(o);console.log(`
|
|
1450
|
+
${Y.bold}${s}${Y.reset}`),console.log(r);let i=n.map(u=>u.label.padEnd(u.width)).join(" ");if(console.log(`${Y.dim}${i}${Y.reset}`),console.log(r),t.forEach((u,d)=>{let f=String(d+1).padEnd(n[0].width),p=u.model.slice(0,n[1].width).padEnd(n[1].width),h=String(u.score).padEnd(n[2].width),g=`${u.toolCallRate}%`.padEnd(n[3].width),w=`${u.correctRate}%`.padEnd(n[4].width),x=`${u.validArgsRate}%`.padEnd(n[5].width),O=`${u.schemaRate}%`.padEnd(n[6].width),I=`${(u.avgLatency/1e3).toFixed(1)}s`.padEnd(n[7].width),E=u.errorCount>0?`${Y.red}${u.errorCount}${Y.reset}`:`${Y.dim}0${Y.reset}`,v=u.score>=80?Y.green:u.score>=60?Y.yellow:Y.red,A=d===0?`${Y.yellow}${f}${Y.reset}`:`${Y.dim}${f}${Y.reset}`;console.log(`${A} ${v}${p}${Y.reset} ${Y.bold}${v}${h}${Y.reset} ${g} ${w} ${x} ${O} ${Y.dim}${I}${Y.reset} ${E}`)}),console.log(r),t.length>0){let u=t[0];if(console.log(`
|
|
1451
|
+
${Y.bold}${Y.green}Winner: ${u.model}${Y.reset} score ${u.score}/100`),t.length>1){let d=(u.score-t[1].score).toFixed(1);console.log(`${Y.dim}+${d} pts over ${t[1].model}${Y.reset}`)}}let a=t.filter(u=>u.results.some(d=>!d.error&&(!d.correctTool||!d.validArgs)));if(a.length>0){console.log(`${Y.bold}Failing tasks:${Y.reset}`);for(let u of a){let d=u.results.filter(h=>!h.error&&(!h.correctTool||!h.validArgs));if(d.length===0)continue;let f=u.model.slice(0,22),p=d.map(h=>{if(!h.correctTool){let g=h.toolCalled||"(none)";return`${Y.dim}${h.taskId}${Y.reset} ${Y.red}\u2192${g}${Y.reset}`}return`${Y.dim}${h.taskId}${Y.reset} ${Y.yellow}bad-args${Y.reset}`});console.log(` ${Y.dim}${f.padEnd(22)}${Y.reset} ${p.join(" ")}`)}console.log()}let c=["coding","frontend","sysadmin","data","agentic"];if(t.some(u=>Object.keys(u.categoryScores).length>1)){console.log(`
|
|
1452
|
+
${Y.bold}Best model per task type:${Y.reset}`);for(let u of c){let d=t.filter(g=>g.categoryScores[u]!==void 0).sort((g,w)=>w.categoryScores[u]-g.categoryScores[u]);if(d.length===0)continue;let f=d[0],p=f.categoryScores[u],h=p>=80?Y.green:p>=60?Y.yellow:Y.red;console.log(` ${Y.dim}${u.padEnd(10)}${Y.reset} ${h}${f.model}${Y.reset} ${Y.dim}${p}/100${Y.reset}`)}}console.log()}function Zy(t){if(!(!t||t.length<2))try{let e=Vy(t),{loadRoutingConfig:s}=ls(),n=s(),o={...n},r=[],i=new Set(["plan","verify"]);for(let[a,{model:c,score:l}]of Object.entries(e)){let u=i.has(a),d=u?n.phases&&n.phases[a]:n[a];d&&d!==c&&!t.find(p=>p.model===d)||(u?(o.phases||(o.phases={}),o.phases[a]!==c&&(o.phases[a]=c,r.push(`phase:${a}\u2192${c}`))):o[a]!==c&&(o[a]=c,r.push(`${a}\u2192${c}`)))}r.length>0&&(e1(o),console.log(`
|
|
1453
|
+
${Y.dim} Routing updated: ${r.join(", ")}${Y.reset}`),console.log(`
|
|
1454
|
+
${Y.green}\u{1F4A1} The best models have been saved to ~/.nex-code/.env and will be automatically used by nex-code from now on.${Y.reset}`))}catch{}}async function r1({models:t,quick:e=!1,onProgress:s,parallelModels:n=1}={}){let o=e?$u.slice(0,s1):ha,r=t?.length>0?t:e?Ky:bu,i={};for(let c of r)i[c]=[];if(n<=1)for(let c of r)for(let l of o){s?.({model:c,task:l.id,done:!1});let u=await wu(l,c);i[c].push(u),s?.({model:c,task:l.id,done:!0,score:co(u),error:u.error})}else{let c=Math.min(n,r.length),l=[...r],u=Array.from({length:c},async()=>{for(;l.length>0;){let d=l.shift();if(!d)break;for(let f of o){s?.({model:d,task:f.id,done:!1});let p=await wu(f,d);i[d].push(p),s?.({model:d,task:f.id,done:!0,score:co(p),error:p.error})}}});await Promise.all(u)}let a=_u(i);return Jy(a,o.length),Zy(a),a}async function i1({newModels:t,existingRanking:e=[],onProgress:s}={}){if(!t||t.length===0)return e;let n={};for(let i of t){n[i]=[];for(let a of ha){s?.({model:i,task:a.id,done:!1});let c=await wu(a,i);n[i].push(c),s?.({model:i,task:a.id,done:!0,score:co(c),error:c.error})}}let r=[..._u(n)];for(let i of e)r.find(a=>a.model===i.model)||r.push(i);return r.sort((i,a)=>a.score-i.score),Jy(r,ha.length),Zy(r),r}var pa=[{id:"simple_question",name:"Simple Convergence",prompt:"What is 2+2?",maxTurns:3,successCriteria:["4"]}];function Qy(t){let e=require("fs"),n=require("path").join(t||process.cwd(),".nex","benchmark-config.json");if(!e.existsSync(n))return console.log(`${Y.yellow}No scenarios configured.${Y.reset} Create ${Y.dim}.nex/benchmark-config.json${Y.reset} to define your benchmark scenarios.
|
|
1414
1455
|
Example:
|
|
1415
1456
|
{
|
|
1416
1457
|
"scenarios": [
|
|
@@ -1423,14 +1464,14 @@ ${G.green}\u{1F4A1} The best models have been saved to ~/.nex-code/.env and will
|
|
|
1423
1464
|
}
|
|
1424
1465
|
]
|
|
1425
1466
|
}
|
|
1426
|
-
`),
|
|
1427
|
-
`),
|
|
1428
|
-
`),
|
|
1429
|
-
\u250C\u2500 Benchmark Results ${"\u2500".repeat(r-19)}\u2510`);for(let
|
|
1430
|
-
`)}function
|
|
1431
|
-
`);return}let o=[];try{o=JSON.parse(e.readFileSync(n,"utf-8"))}catch{o=[]}if(!Array.isArray(o)||o.length===0){console.log(`${
|
|
1467
|
+
`),pa;try{let o=JSON.parse(e.readFileSync(n,"utf-8"));return!Array.isArray(o.scenarios)||o.scenarios.length===0?(console.log(`${Y.yellow}benchmark-config.json has no scenarios \u2014 using defaults.${Y.reset}
|
|
1468
|
+
`),pa):o.scenarios}catch(o){return console.log(`${Y.yellow}Failed to parse benchmark-config.json: ${o.message}${Y.reset}
|
|
1469
|
+
`),pa}}function e0(t,e){let{scoreMessages:s,_extractToolCalls:n,_getLastAssistantText:o}=ji(),r=s(t),i=r.score,a=[],c=o(t).toLowerCase();e.successCriteria.every(f=>c.includes(f.toLowerCase()))&&(i=Math.min(10,i+1),a.push("+1.0 all success criteria met"));let u=n(t);u.length<e.maxTurns/2&&(i=Math.min(10,i+.5),a.push(`+0.5 efficient (${u.length} tool calls < ${e.maxTurns/2})`)),i=Math.round(i*10)/10;let d=i>=9?"A":i>=8?"B":i>=7?"C":i>=6?"D":"F";return{score:i,grade:d,issues:r.issues,summary:r.summary,bonuses:a}}async function a1(t,e={}){let{spawn:s}=require("child_process"),n=require("fs"),o=require("path"),r=require("os"),i=o.join(r.tmpdir(),`nex-bench-${t.id}-${Date.now()}.txt`);n.writeFileSync(i,t.prompt,"utf-8");let a=o.resolve(__dirname,"..","bin","nex-code.js"),c=e.cwd||process.cwd(),l=[a,"--prompt-file",i,"--delete-prompt-file","--auto","--max-turns",String(t.maxTurns)];return e.model&&l.push("--model",e.model),new Promise(u=>{let d=s(process.execPath,l,{cwd:c,stdio:["ignore","pipe","pipe"],env:{...process.env}}),f=t.maxTurns*60*1e3,p=!1,h=setTimeout(()=>{p=!0;try{d.kill("SIGTERM")}catch{}},f);d.on("close",g=>{clearTimeout(h);try{n.unlinkSync(i)}catch{}let w=o.join(c,".nex","sessions","_autosave.json"),x=[];if(n.existsSync(w))try{x=JSON.parse(n.readFileSync(w,"utf-8")).messages||[]}catch{}u({messages:x,exitCode:g||0,timedOut:p})}),d.stdout.resume(),d.stderr.resume()})}function c1(t,e,s){let n=t.length>0?Math.round(t.reduce((c,l)=>c+l.score,0)/t.length*10)/10:0,o=n>=9?"A":n>=8?"B":n>=7?"C":n>=6?"D":"F",r=57,i="\u2500".repeat(r);console.log(`
|
|
1470
|
+
\u250C\u2500 Benchmark Results ${"\u2500".repeat(r-19)}\u2510`);for(let c of t){let l=c.id.padEnd(20),u=c.name.substring(0,26).padEnd(26),d=`${c.score}/10`.padStart(6),f=c.grade.padStart(2);console.log(`\u2502 ${l} ${u} ${d} ${f} \u2502`)}console.log(`\u2502 ${" ".repeat(r-2)} \u2502`);let a=`Overall: ${n}/10 (${o}) \xB7 v${e} \xB7 ${s}`;console.log(`\u2502 ${a.substring(0,r-4).padEnd(r-4)} \u2502`),console.log(`\u2514${"\u2500".repeat(r+1)}\u2518
|
|
1471
|
+
`)}function l1(t=10){let e=require("fs"),n=require("path").join(process.cwd(),".nex","benchmark-history.json");if(!e.existsSync(n)){console.log(`${Y.yellow}No score history yet. Run a session first.${Y.reset}
|
|
1472
|
+
`);return}let o=[];try{o=JSON.parse(e.readFileSync(n,"utf-8"))}catch{o=[]}if(!Array.isArray(o)||o.length===0){console.log(`${Y.yellow}Score history is empty.${Y.reset}
|
|
1432
1473
|
`);return}let r=o.slice(-t);console.log(`
|
|
1433
|
-
${
|
|
1434
|
-
${
|
|
1435
|
-
`);for(let
|
|
1436
|
-
${
|
|
1474
|
+
${Y.bold}Score History (last ${r.length} session${r.length===1?"":"s"}):${Y.reset}`);for(let i of r){let a=(i.date||"").replace("T"," ").substring(0,16),c=(i.version||"?").padEnd(8),l=(i.model||"?").substring(0,12).padEnd(12),u=`${i.score}/10`.padStart(6),d=i.grade||"?",f=i.issues&&i.issues.length>0?`${Y.yellow}\u26A0 ${i.issues.slice(0,2).map(h=>h.substring(0,30)).join(", ")}${Y.reset}`:`${Y.green}\u2713${Y.reset}`,p=i.score>=8?Y.green:i.score>=6?Y.yellow:Y.red;console.log(` ${Y.dim}${a}${Y.reset} ${Y.dim}v${c}${Y.reset} ${Y.dim}${l}${Y.reset} ${p}${u} ${d}${Y.reset} ${f}`)}console.log()}async function u1({dryRun:t=!1,model:e,cwd:s,onProgress:n}={}){let o=Er(),r=Qy(s);if(t){console.log(`
|
|
1475
|
+
${Y.bold}Scenario Benchmark \u2014 Scenarios (dry-run):${Y.reset}
|
|
1476
|
+
`);for(let c of r)console.log(` ${Y.cyan}${c.id.padEnd(20)}${Y.reset} ${Y.dim}${c.name}${Y.reset} maxTurns=${c.maxTurns}`),console.log(` ${Y.dim}${c.prompt.substring(0,80)}${Y.reset}`);return console.log(),[]}let i=(()=>{if(e)return typeof e=="object"?e.id||"unknown":e;try{let{getActiveModel:c}=mo(),l=c?c():null;return l?typeof l=="object"?l.id||"unknown":l:"unknown"}catch{return"unknown"}})(),a=[];for(let c of r){n?.({id:c.id,name:c.name,done:!1}),console.log(`
|
|
1477
|
+
${Y.dim}Running scenario: ${c.name}...${Y.reset}`);let{messages:l,timedOut:u}=await a1(c,{model:i,cwd:s}),d;u||l.length===0?d={score:0,grade:"F",issues:[u?"Scenario timed out":"No messages produced"],summary:"No output",bonuses:[]}:d=e0(l,c);let f={id:c.id,name:c.name,score:d.score,grade:d.grade,issues:d.issues,bonuses:d.bonuses};a.push(f),n?.({id:c.id,name:c.name,done:!0,score:d.score,grade:d.grade});try{let{appendScoreHistory:p}=ji();p(d.score,{version:o.version,model:i,sessionName:`bench:${c.id}`,issues:d.issues})}catch{}}return c1(a,o.version,i),a}module.exports={runBenchmark:r1,runDiscoverBenchmark:i1,buildSummary:_u,buildCategoryWinners:Vy,TASKS:$u,PHASE_TASKS:zy,ALL_TASKS:ha,scoreResult:co,DEFAULT_MODELS:bu,QUICK_MODELS:Ky,runScenarioBenchmark:u1,showScoreTrend:l1,loadScenarios:Qy,DEFAULT_SCENARIOS:pa,scoreScenario:e0};
|